diff --git "a/1426.jsonl" "b/1426.jsonl"
new file mode 100644--- /dev/null
+++ "b/1426.jsonl"
@@ -0,0 +1,655 @@
+{"seq_id":"636071317","text":"# Copyright (c) 2018, INRIA\n# Copyright (c) 2018, University of Lille\n# All rights reserved.\n\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n\n# * Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n\n# * Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\nimport pytest\nimport datetime\nfrom powerapi.report_model.hwpc_model import HWPCModel, BadInputData\n\n@pytest.fixture()\ndef hwpc_model():\n \"\"\"\n :return: HWPCModel\n \"\"\"\n return HWPCModel()\n\n##############################################################################\n# Tests #\n##############################################################################\n\n####################\n# MongoDB\n####################\n\n\n@pytest.mark.parametrize(\"json_input\", [\n ({\"_id\": \"fake-id\",\n \"timestamp\": datetime.datetime.now().timestamp(),\n \"sensor\": \"fake-sensor\",\n \"target\": \"fake-target\",\n \"groups\": {}})\n]\n)\ndef test_convert_hwpc_report_from_mongodb_work(hwpc_model, json_input):\n \"\"\"\n Test working input for HWPCReport from_mongodb\n :param json_input: Data in input\n \"\"\"\n hwpc_model.from_mongodb(json_input)\n assert True\n\n\n####################\n# CsvDB\n####################\n\n\n@pytest.mark.parametrize(\"json_input\", [\n ({\"timestamp\": datetime.datetime.now().timestamp(),\n \"sensor\": \"fake-sensor\",\n \"target\": \"fake-target\",\n \"socket\": 0,\n \"cpu\": 0,\n \"event1\": 1000,\n \"event2\": 2000}),\n ({\"timestamp\": datetime.datetime.now().timestamp(),\n \"sensor\": \"fake-sensor\",\n \"target\": \"fake-target\",\n \"socket\": 0,\n \"cpu\": 0}),\n]\n)\ndef test_convert_hwpc_report_from_csvdb_work(hwpc_model, json_input):\n \"\"\"\n :param json_input: Data in input\n \"\"\"\n hwpc_model.from_mongodb(json_input)\n assert True\n\n\n@pytest.mark.parametrize(\"json_input\", [\n ({\"sensor\": \"fake-sensor\",\n \"target\": \"fake-target\"}),\n ({\"timestamp\": datetime.datetime.now().timestamp(),\n \"target\": \"fake-target\"}),\n ({\"timestamp\": datetime.datetime.now().timestamp(),\n \"sensor\": \"fake-sensor\"}),\n ({\"timestamp\": datetime.datetime.now().timestamp(),\n \"sensor\": \"fake-sensor\",\n \"target\": \"fake-target\"}),\n ({\"timestamp\": datetime.datetime.now().timestamp(),\n \"sensor\": \"fake-sensor\",\n \"target\": \"fake-target\",\n \"socket\": 0}),\n ({\"timestamp\": datetime.datetime.now().timestamp(),\n \"sensor\": \"fake-sensor\",\n \"target\": \"fake-target\",\n \"cpu\": 0}),\n]\n)\ndef test_hwpc_report_from_csvdb_fail(hwpc_model, json_input):\n \"\"\"\n :param json_input: Data in input\n \"\"\"\n with pytest.raises(BadInputData):\n hwpc_model.from_csvdb(\"fake-name\", json_input)\n","sub_path":"tests/unit/report_model/test_hwpc_report_model.py","file_name":"test_hwpc_report_model.py","file_ext":"py","file_size_in_byte":4028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"212777789","text":"# Copyright 2021 UW-IT, University of Washington\n# SPDX-License-Identifier: Apache-2.0\n\nfrom django.conf import settings\n\n\ndef SameSiteMiddleware(get_response):\n def middleware(request):\n # See:\n # https://blog.chromium.org/2019/10/developers-get-ready-for-new.html\n # https://github.com/django/django/pull/11894\n # https://web.dev/samesite-cookie-recipes/#handling-incompatible-clients\n # https://www.chromium.org/updates/same-site/incompatible-clients\n\n # TLDR: Chrome (and soon Firefox and Safari) require that you set\n # SameSite=None\n # in order to have a cookie set cross-domain. The old behavior of\n # SameSite\n # being 'None' by default is no more. The new default is 'Lax'.\n # The issue is that we can't just set SameSite=None and be\n # done with it,\n # because some older browsers will break with this. Therefore we devise\n # a two-cookie approach: one that does the new behavior of setting\n # SameSite=None, and the second is the \"legacy\" cookie which relies on\n # the old-default's behavior. If we receive only the legacy cookie in\n # a request, we know we're dealing with one of those older browsers,\n # and we can repair the lost cookie before proceeding to process the\n # request.\n cookie = settings.SESSION_COOKIE_NAME\n legacy = \"{}_legacy\".format(cookie)\n\n if legacy in request.COOKIES:\n if cookie not in request.COOKIES:\n request.COOKIES[cookie] = request.COOKIES[legacy]\n del request.COOKIES[legacy]\n\n response = get_response(request)\n\n if cookie in response.cookies:\n response.cookies[legacy] = response.cookies[cookie].value\n # set Expiry, Path, etc.\n response.cookies[legacy].update(response.cookies[cookie])\n response.cookies[cookie]['samesite'] = 'None'\n if settings.SESSION_COOKIE_SECURE and not \\\n response.cookies[cookie].get('secure', False):\n # Fix Django's silly `delete_cookie()` behavior which doesn't\n # set `secure` correctly.\n response.cookies[cookie]['secure'] = True\n\n return response\n\n return middleware\n","sub_path":"cohort_manager/middleware/same_site_middleware.py","file_name":"same_site_middleware.py","file_ext":"py","file_size_in_byte":2283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"310274780","text":"\"\"\"\n\n**INPUT FILE FORMAT**\n\nThe file format consists of a one-row template header followed by a one-row data header and subsequent data\nrows.\n\nThe data represents refinery emission rate curves.\n\nFile Type\n comma-separated values (CSV)\n\nSample Header\n .. csv-table::\n\n input_template_name:,emission_rates_refinery,input_template_version:,0.1\n\nSample Data Columns\n .. csv-table::\n :widths: auto\n\n rate_name,independent_variable,last_year,slope_rate,intercept_rate,equation_rate_id\n pm25_grams_per_gallon,(calendar_year - 2016),2055,-2.58E-04,1.47E-01,((-0.000257743900872186 * (calendar_year - 2016)) + 0.147171057586721)\n nox_grams_per_gallon,(calendar_year - 2016),2055,-0.002233801,0.57763691,((-0.00223380056415021 * (calendar_year - 2016)) + 0.577636910469321)\n sox_grams_per_gallon,(calendar_year - 2016),2055,-0.00030085,0.221705126,((-0.000300850396789525 * (calendar_year - 2016)) + 0.221705126043959)\n voc_grams_per_gallon,(calendar_year - 2016),2055,-2.19E-03,5.00E-01,((-0.00219248448866068 * (calendar_year - 2016)) + 0.500358765360277)\n\nData Column Name and Description\n :rate_name:\n The emission rate providing the pollutant and units.\n\n :independent_variable:\n The independent variable used in calculating the emission rate.\n\n :last_year:\n The last calendar year from which the rate regression curves were generated.\n\n :slope_rate:\n The slope of the linear fit to the emission rate input data.\n\n :intercept_rate:\n The intercept of the linear fit to the emission rate input data.\n\n :equation_rate_id:\n The linear fit emission rate equation used to calculate an emission rate at the given independent variable.\n\n----\n\n**CODE**\n\n\"\"\"\nfrom omega_effects.general.general_functions import read_input_file\nfrom omega_effects.general.input_validation import validate_template_version_info, validate_template_column_names\n\n\nclass EmissionRatesRefinery:\n \"\"\"\n Loads and provides access to power sector emissions factors by calendar year.\n\n \"\"\"\n def __init__(self):\n self._data = dict() # private dict\n self._cache = dict()\n self.calendar_year_max = None\n self.deets = {} # this dictionary will not include the legacy fleet\n\n def init_from_file(self, filepath, effects_log):\n \"\"\"\n\n Initialize class data from input file.\n\n Args:\n filepath: the Path object to the file.\n effects_log: an instance of the EffectsLog class.\n\n Returns:\n Nothing, but reads the appropriate input file.\n\n \"\"\"\n # don't forget to update the module docstring with changes here\n input_template_name = 'emission_rates_refinery'\n input_template_version = 0.1\n input_template_columns = {\n 'rate_name',\n 'independent_variable',\n 'last_year',\n 'equation_rate_id',\n }\n\n df = read_input_file(filepath, effects_log)\n validate_template_version_info(df, input_template_name, input_template_version, effects_log)\n\n # read in the data portion of the input file\n df = read_input_file(filepath, effects_log, skiprows=1)\n validate_template_column_names(filepath, df, input_template_columns, effects_log)\n\n df.set_index(df['rate_name'], inplace=True)\n\n self.calendar_year_max = df['last_year'][0]\n\n self._data = df.to_dict('index')\n\n def get_emission_rate(self, session_settings, calendar_year, rate_names):\n \"\"\"\n\n Get emission rates by calendar year\n\n Args:\n session_settings: an instance of the SessionSettings class\n calendar_year (int): calendar year for which to get emission rates\n rate_names (str, [strs]): name of emission rate(s) to get\n\n Returns:\n A list of emission rates for the given kwh_demand in the given calendar_year.\n\n \"\"\"\n locals_dict = locals()\n return_rates = list()\n\n if calendar_year > self.calendar_year_max:\n calendar_year = self.calendar_year_max\n\n if calendar_year in self._cache:\n return_rates = self._cache[calendar_year]\n\n else:\n for idx, rate_name in enumerate(rate_names):\n rate = eval(self._data[rate_name]['equation_rate_id'], {}, locals_dict)\n\n return_rates.append(rate)\n\n self.deets.update(\n {(calendar_year, rate_name): {\n 'session_policy': session_settings.session_policy,\n 'session_name': session_settings.session_name,\n 'calendar_year': calendar_year,\n 'rate_name': rate_name,\n 'rate': rate,\n }}\n )\n self._cache[calendar_year] = return_rates\n\n return return_rates\n","sub_path":"omega_effects/effects/emission_rates_refinery.py","file_name":"emission_rates_refinery.py","file_ext":"py","file_size_in_byte":4910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"520520382","text":"# -*- coding: latin_1 -*-\r\n\r\nimport psycopg2\r\nimport os\r\nimport datetime\r\nimport platform\r\nimport sys\r\n\r\nsys.path.append(os.path.join(os.path.dirname(__file__), os.pardir))\r\nfrom shared.sendmail import send_mail\r\nfrom shared.printAndLog import printAndLog\r\n\r\nimport shared.databrugisconf as DBRUC\r\nimport shared.ordoconf as OCONF\r\n\r\n################################################################################\r\n\r\nif __name__ == \"__main__\":\r\n wfstepId = OCONF.getWorkflowID() \r\n mode = OCONF.getExecMode()\r\n dlevel = OCONF.getDebugLevel()\r\n OCONF.tokenFileWriteRunning(wfstepId)\r\n try:\r\n logFileName = \"{}-{}.log\".format(os.path.basename(__file__).replace('.py', ''),datetime.date.today().strftime('%d_%m_%Y'))\r\n with open(os.path.join(DBRUC._mailDir, logFileName), 'a') as logFile:\r\n dbName = DBRUC._db_dbname\r\n printAndLog( \"{} running\".format(wfstepId),logFile)\r\n printAndLog(\"Startup queryFDW\", logFile)\r\n \r\n conn_s = \"dbname='{}' user='{}' host='{}' password='{}'\".format(dbName,\r\n DBRUC._db_user,\r\n DBRUC._prod_db_host,\r\n DBRUC._db_password)\r\n \r\n if dlevel == 'V':\r\n printAndLog(\"Connection string {}\".format(conn_s), logFile)\r\n if mode == \"EMUL\":\r\n printAndLog(\"EMULATION MODE\", logFile)\r\n OCONF.tokenFileWriteDone(wfstepId) \r\n exit()\r\n conn = psycopg2.connect(conn_s)\r\n \r\n if dlevel == 'V':\r\n printAndLog(\"After connect\", logFile)\r\n \r\n cur = conn.cursor()\r\n cur.execute(\"SELECT commonbrugis.wf_intextintra_1synchro()\")\r\n conn.commit()\r\n\r\n printAndLog( \"{} done\".format(wfstepId),logFile)\r\n if DBRUC._sendMail:\r\n nodename = platform.node()\r\n send_mail('%s - %s - log - %s' % (nodename, os.path.basename(__file__), str(datetime.datetime.today())), logFile.read())\r\n OCONF.tokenFileWriteDone(wfstepId) \r\n except:\r\n OCONF.tokenFileWriteFail(wfstepId)\r\n \r\n \r\n","sub_path":"bdm_ordo/env_prod/queryFDW.py","file_name":"queryFDW.py","file_ext":"py","file_size_in_byte":2347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"651961062","text":"import argparse\nimport h5py\nimport merge\nimport numpy as np\nimport mpi_init\nimport subfind_data\nimport volume_read\nimport halo_properties as hp\n\n\ndef measure_profile_properties(mpi, path, snap, extent=5.0, R200scale=True, Nbins=25):\n \"\"\"\n Compute various profiles and quantities for halos above given mass\n\n Arguments:\n -mpi : MPI environment class instance\n -path : Path to simulation of interest\n -snap : Snapshot of interest\n -extent : Extent of the radial profiles\n -R200scale : BOOLEAN - if True: profiles extend EXTENT * R200, else [Mpc]\n -Nbins : NUmber of bins in the radial profile\n \"\"\"\n\n # First, rebuild the Subfind table for this snapshot\n subfind_table = subfind_data.build_table(mpi, sim=path, snap=snap)\n\n # Load the entire volume\n volume = volume_read.entire_snapshot_read(mpi, sim=path, snap=snap)\n\n # Read specified datasets, compute desired quantities, clean up\n required_datasets = [\n \"PartType1/Coordinates\",\n \"PartType1/Masses\",\n \"PartType1/Velocities\",\n ]\n volume.read_datasets(mpi, required_datasets)\n volume.tag_subhalo_particles(mpi, subfind_table)\n\n # Now select halos of interest\n subfind_table.select_halos(mpi, cut=1.0e12)\n if not mpi.Rank:\n print(\" > Found {0:d} halo(s)\".format(len(subfind_table.tags)), flush=True)\n\n # Initiate halo class, distribute required particles to tasks, store\n h = hp.halo(volume, Nbins=Nbins)\n\n h.halo_data_store(mpi, subfind_table, volume, Extent=extent, R200scale=R200scale)\n del subfind_table, volume\n\n # Now loop over haloes that were sent to my task\n hk = sorted(h.halo_data.keys())\n if not mpi.Rank:\n print(\" > Computing halo properties\", flush=True)\n for j in range(0, len(hk), 1):\n if not mpi.Rank:\n print(\" -{0}\".format(hk[j]), flush=True)\n\n h.set_up_halo(mpi, hk[j])\n\n # Compute mass profiles\n h.compute_mass_profiles(mpi)\n\n # Velocities and non-thermal pressure profiles\n h.compute_velocities_and_non_thermal_pressure(mpi)\n\n # Centre of mass offset\n h.compute_centre_of_mass_offset(mpi)\n\n # Compute NFW concentration - 1 parameter fit\n h.compute_concentration(mpi)\n\n # DM surface pressure\n h.compute_DM_surface_pressure(mpi)\n\n # Cumulative shape measurements\n h.compute_shape(mpi, aperture=\"500\", ptype=\"DM\")\n h.compute_shape(mpi, aperture=\"200\", ptype=\"DM\")\n h.compute_shape(mpi, aperture=\"Vir\", ptype=\"DM\")\n\n # Dark matter shape profile\n h.compute_shape_profile(mpi, ptype=\"DM\")\n\n # Store halo properties in HDF5 file\n h.save(mpi)\n\n # Now merge files\n mpi.comm.Barrier()\n if not mpi.Rank:\n ftag = \"{0}_Snap{1:03d}_z{2:d}p{3:02d}\".format(\n h.fname,\n h.snap,\n int(h.redshift),\n int(100.0 * (h.redshift - int(h.redshift))),\n )\n merge.merge_outputs(ftag)\n mpi.comm.Barrier()\n del h\n return\n\n\nif __name__ == \"__main__\":\n\n # Parse command-line options -- deals with missing arguments!\n parser = argparse.ArgumentParser(\n description=\"TNG analysis script to produce radial profiles\"\n )\n parser.add_argument(\n \"start\", action=\"store\", type=int, help=\"First snapshot to process\"\n )\n parser.add_argument(\n \"final\", action=\"store\", type=int, help=\"Final snapshot to process\"\n )\n inputs = parser.parse_args()\n\n # Simulation of interest\n paths = [\"/n/hernquistfs3/IllustrisTNG/Runs/L75n910TNG_DM/output\"]\n\n # Snapshots of interest\n snapshots = np.arange(inputs.final - inputs.start + 1) + inputs.start\n\n # Initialize MPI environment\n mpi = mpi_init.mpi()\n\n # Loop over sims and snapshots measuring profiles\n for x in paths:\n for y in snapshots:\n if not mpi.Rank:\n print(\"--- SNAPSHOT {0:03d} ---\".format(y), flush=True)\n measure_profile_properties(mpi, x, y)\n","sub_path":"Examples/DMO100.py","file_name":"DMO100.py","file_ext":"py","file_size_in_byte":4027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"96374240","text":"import os\r\n\r\nclass TaskProjectBuilder:\r\n\r\n\r\n def __init__(self, taskDirectory, env, lib, bin2hex, Glob):\r\n self.taskDirectory = taskDirectory\r\n self.bin2hex = bin2hex\r\n self.env = env.Clone()\r\n self.Glob = Glob\r\n self.env.Append(CPPPATH=[taskDirectory + '/shared/include'])\r\n self.fullTaskLibrary = [ lib, self.env.Library([ file for file in self.Glob(self.taskDirectory + '/shared/src/*.c', True, True, True) ]) ]\r\n\r\n def buildSubTaskProject(self, subTaskName, subTaskSourceFile, includeSubTaskSpecificLib = False, taskSpecificLib = []):\r\n subtaskEnv = self.env.Clone()\r\n mainFile = self.Glob('/'.join([ self.taskDirectory, subTaskName, subTaskSourceFile]), True, True, True)[0]\r\n sources = [ mainFile ]\r\n if includeSubTaskSpecificLib:\r\n subtaskEnv.Append(CPPPATH=[ '/'.join([ self.taskDirectory, subTaskName ]) ])\r\n sources.extend([ '/'.join([ self.taskDirectory, subTaskName, file]) for file in taskSpecificLib ])\r\n sources.extend(self.fullTaskLibrary);\r\n subtaskEnv.Program(sources)\r\n self.bin2hex(mainFile, subtaskEnv, 'esos')\r\n return self # return self so that we can chain these calls.\r\n","sub_path":"f16_imsai/Scons_TaskProjectBuilder.py","file_name":"Scons_TaskProjectBuilder.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"561167796","text":"from django.shortcuts import render,HttpResponse,HttpResponseRedirect\nfrom django.conf import settings\nfrom shop.models import Order\nfrom django.contrib.auth.decorators import login_required\n\n@login_required(login_url='/')\ndef my_orders(request):\n order=Order.objects.filter(contact=request.user)\n template_name = \"myorders.html\"\n return render(request, template_name, {'order':order})\n\n@login_required(login_url='/')\ndef cancel_orders(request,order_id):\n\n order=Order.objects.filter(contact=request.user,id=int(order_id))\n if order:\n os=OrderStatus()\n os.order=order[0]\n os.status=\"Cancelled\"\n os.save()\n return HttpResponseRedirect(\"/accounts/myorders/\")\n\n","sub_path":"accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"205124452","text":"def find_rsa(nums, X):\n \n len_n = len(nums)\n \n def _find(low, high):\n if low > high:\n return -1\n \n mid = low + (high-low)//2\n \n if nums[mid] == X:\n return mid\n \n if nums[low] <= nums[mid]: # left is sorted\n if nums[low] <= X and X < nums[mid]:\n return _find(low, mid-1)\n else:\n return _find(mid+1, high)\n else: # right is sorted\n if nums[mid] < X and X <= nums[high]:\n return _find(mid+1, high)\n else:\n return _find(low, mid-1)\n\n return _find(0, len_n-1)\n \n\n\nif __name__ == '__main__':\n nums1 = [5, 6, 7, 8, 9, 10, 1, 2, 3] # 3 → 8\n nums2 = [5, 6, 7, 8, 9, 10, 1, 2, 3] # 30 → -1\n nums3 = [30, 40, 50, 10, 20] # 10 → 3\n \n print(find_rsa(nums1, 3))\n print(find_rsa(nums2, 30))\n print(find_rsa(nums3, 10))\n ","sub_path":"4 Search/4-03_search_in_rsa.py","file_name":"4-03_search_in_rsa.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"623802658","text":"# -------------------------------------------------------------------------\n#\n# Part of the CodeChecker project, under the Apache License v2.0 with\n# LLVM Exceptions. See LICENSE for license information.\n# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n#\n# -------------------------------------------------------------------------\n\n\"\"\"\nThis module tests the correctness of the OutputParser and PListConverter, which\nused in sequence transform a Clang Tidy output file to a plist file.\n\"\"\"\nimport copy\nimport os\nimport unittest\n\nimport io\n\nimport codechecker_analyzer.analyzers.clangtidy.output_converter as \\\n tidy_out_conv\n\nOLD_PWD = None\n\n\ndef setup_module():\n \"\"\"Setup the test tidy reprs for the test classes in the module.\"\"\"\n global OLD_PWD\n OLD_PWD = os.getcwd()\n os.chdir(os.path.join(os.path.dirname(__file__), 'tidy_output_test_files'))\n\n # tidy1.out Message/Note representation\n tidy1_repr = [\n tidy_out_conv.Message(\n os.path.abspath('files/test.cpp'),\n 8, 12,\n 'Division by zero',\n 'clang-analyzer-core.DivideZero',\n None,\n [tidy_out_conv.Note(\n os.path.abspath('files/test.cpp'),\n 8, 12,\n 'Division by zero')]),\n tidy_out_conv.Message(\n os.path.abspath('files/test.cpp'),\n 8, 12,\n 'remainder by zero is undefined',\n 'clang-diagnostic-division-by-zero')\n ]\n\n # tidy2.out Message/Note representation\n tidy2_repr = [\n tidy_out_conv.Message(\n os.path.abspath('files/test2.cpp'),\n 5, 7,\n \"unused variable 'y'\",\n 'clang-diagnostic-unused-variable'),\n tidy_out_conv.Message(\n os.path.abspath('files/test2.cpp'),\n 13, 12,\n 'Division by zero',\n 'clang-analyzer-core.DivideZero',\n None,\n [\n tidy_out_conv.Note(\n os.path.abspath('files/test2.cpp'),\n 9, 7,\n \"Left side of '||' is false\"),\n tidy_out_conv.Note(\n os.path.abspath('files/test2.cpp'),\n 9, 3,\n 'Taking false branch'),\n tidy_out_conv.Note(\n os.path.abspath('files/test2.cpp'),\n 13, 12,\n 'Division by zero')\n ]),\n tidy_out_conv.Message(\n os.path.abspath('files/test2.cpp'),\n 13, 12,\n 'remainder by zero is undefined',\n 'clang-diagnostic-division-by-zero'),\n ]\n\n # tidy2_v6.out Message/Note representation\n tidy2_v6_repr = [\n tidy_out_conv.Message(\n os.path.abspath('files/test2.cpp'),\n 13, 12,\n 'Division by zero',\n 'clang-analyzer-core.DivideZero',\n None,\n [\n tidy_out_conv.Note(\n os.path.abspath('files/test2.cpp'),\n 9, 7,\n \"Left side of '||' is false\"),\n tidy_out_conv.Note(\n os.path.abspath('files/test2.cpp'),\n 9, 16,\n \"Assuming 'x' is 0\"),\n tidy_out_conv.Note(\n os.path.abspath('files/test2.cpp'),\n 9, 3,\n 'Taking false branch'),\n tidy_out_conv.Note(\n os.path.abspath('files/test2.cpp'),\n 13, 12,\n 'Division by zero')\n ]),\n tidy_out_conv.Message(\n os.path.abspath('files/test2.cpp'),\n 13, 12,\n 'remainder by zero is undefined',\n 'clang-diagnostic-division-by-zero'),\n ]\n\n # tidy3.out Message/Note representation\n tidy3_repr = [\n tidy_out_conv.Message(\n os.path.abspath('files/test3.cpp'),\n 4, 12,\n 'use nullptr',\n 'modernize-use-nullptr',\n [tidy_out_conv.Note(\n os.path.abspath('files/test3.cpp'),\n 4, 12,\n 'nullptr')]),\n tidy_out_conv.Message(\n os.path.abspath('files/test3.hh'),\n 6, 6,\n \"Dereference of null pointer (loaded from variable 'x')\",\n 'clang-analyzer-core.NullDereference',\n None,\n [\n tidy_out_conv.Note(\n os.path.abspath('files/test3.cpp'),\n 4, 3,\n \"'x' initialized to a null pointer value\"),\n tidy_out_conv.Note(\n os.path.abspath('files/test3.cpp'),\n 6, 11,\n \"Assuming 'argc' is > 3\"),\n tidy_out_conv.Note(\n os.path.abspath('files/test3.cpp'),\n 6, 3,\n 'Taking true branch'),\n tidy_out_conv.Note(\n os.path.abspath('files/test3.cpp'),\n 7, 9,\n \"Passing null pointer value via 1st parameter 'x'\"),\n tidy_out_conv.Note(\n os.path.abspath('files/test3.cpp'),\n 7, 5,\n \"Calling 'bar'\"),\n tidy_out_conv.Note(\n os.path.abspath('files/test3.hh'),\n 6, 6,\n \"Dereference of null pointer (loaded from variable 'x')\")\n ])\n ]\n\n # tidy5.out Message/Note representation\n tidy5_repr = [\n tidy_out_conv.Message(\n os.path.abspath('files/test4.cpp'),\n 3, 26,\n 'identifier after literal will be treated '\n 'as a reserved user-defined literal suffix in C++11',\n 'clang-diagnostic-c++11-compat-reserved-user-defined-literal',\n None, None),\n tidy_out_conv.Message(\n os.path.abspath('files/test4.cpp'),\n 10, 12,\n 'Division by zero',\n 'clang-analyzer-core.DivideZero',\n None,\n [tidy_out_conv.Note(\n os.path.abspath('files/test4.cpp'),\n 10, 12,\n 'Division by zero')]),\n tidy_out_conv.Message(\n os.path.abspath('files/test4.cpp'),\n 10, 12,\n 'remainder by zero is undefined',\n 'clang-diagnostic-division-by-zero')\n ]\n\n # tidy5_v6.out Message/Note representation\n tidy5_v6_repr = [\n tidy_out_conv.Message(\n os.path.abspath('files/test4.cpp'),\n 3, 26,\n 'invalid suffix on literal; C++11 requires a space '\n 'between literal and identifier',\n 'clang-diagnostic-reserved-user-defined-literal',\n None, None),\n tidy_out_conv.Message(\n os.path.abspath('files/test4.cpp'),\n 10, 12,\n 'remainder by zero is undefined',\n 'clang-diagnostic-division-by-zero')\n ]\n\n # tidy6.out Message/Note representation\n tidy6_repr = [\n tidy_out_conv.Message(\n os.path.abspath('files/test5.cpp'),\n 10, 9,\n 'no matching function for call to \\'get_type\\'',\n 'clang-diagnostic-error',\n None,\n [\n tidy_out_conv.Note(\n os.path.abspath('files/test5.cpp'),\n 2, 18,\n 'candidate template ignored: substitution failure '\n '[with T = int *]: type \\'int *\\' cannot be used prior to '\n '\\'::\\' because it has no members'),\n tidy_out_conv.Note(\n os.path.abspath('files/test5.cpp'),\n 5, 6,\n 'candidate template ignored: substitution failure '\n '[with T = int]: array size is negative'),\n ]\n )]\n\n TidyOutputParserTestCase.tidy1_repr = tidy1_repr\n TidyOutputParserTestCase.tidy2_repr = tidy2_repr\n TidyOutputParserTestCase.tidy2_v6_repr = tidy2_v6_repr\n TidyOutputParserTestCase.tidy3_repr = tidy3_repr\n TidyOutputParserTestCase.tidy5_repr = tidy5_repr\n TidyOutputParserTestCase.tidy6_repr = tidy6_repr\n TidyOutputParserTestCase.tidy5_v6_repr = tidy5_v6_repr\n TidyPListConverterTestCase.tidy1_repr = tidy1_repr\n TidyPListConverterTestCase.tidy2_repr = tidy2_repr\n TidyPListConverterTestCase.tidy3_repr = tidy3_repr\n\n\ndef teardown_module():\n \"\"\"Restore environment after tests have ran.\"\"\"\n global OLD_PWD\n os.chdir(OLD_PWD)\n\n\nclass TidyOutputParserTestCase(unittest.TestCase):\n \"\"\"\n Tests the output of the OutputParser, which converts a Clang Tidy output\n file to zero or more tidy_output_converter.Message.\n \"\"\"\n\n def setUp(self):\n \"\"\"Setup the OutputParser.\"\"\"\n self.parser = tidy_out_conv.OutputParser()\n\n def test_absolute_path(self):\n \"\"\"Test for absolute paths in Messages.\"\"\"\n for tfile in ['abs.out', 'tidy1.out']:\n messages = self.parser.parse_messages_from_file(tfile)\n self.assertNotEqual(len(messages), 0)\n for message in messages:\n self.assertTrue(os.path.isabs(message.path))\n\n def test_empty1(self):\n \"\"\"Test an empty ClangTidy output file.\"\"\"\n messages = self.parser.parse_messages_from_file('empty1.out')\n self.assertEqual(messages, [])\n\n def test_empty2(self):\n \"\"\"Test a ClangTidy output file that only contains empty lines.\"\"\"\n messages = self.parser.parse_messages_from_file('empty2.out')\n self.assertEqual(messages, [])\n\n def test_tidy1(self):\n \"\"\"Test the generated Messages of tidy1.out ClangTidy output file.\"\"\"\n messages = self.parser.parse_messages_from_file('tidy1.out')\n self.assertEqual(len(messages), len(self.tidy1_repr))\n for message in messages:\n self.assertIn(message, self.tidy1_repr)\n\n def test_tidy1_v6(self):\n \"\"\"Test the generated Messages of tidy1.out ClangTidy v6 output\n file.\"\"\"\n messages = self.parser.parse_messages_from_file('tidy1_v6.out')\n self.assertEqual(len(messages), len(self.tidy1_repr))\n for message in messages:\n self.assertIn(message, self.tidy1_repr)\n\n def test_tidy2(self):\n \"\"\"Test the generated Messages of tidy2.out ClangTidy output file.\"\"\"\n messages = self.parser.parse_messages_from_file('tidy2.out')\n self.assertEqual(len(messages), len(self.tidy2_repr))\n for message in messages:\n self.assertIn(message, self.tidy2_repr)\n\n def test_tidy2_v6(self):\n \"\"\"Test the generated Messages of tidy2.out ClangTidy v6 output\n file.\"\"\"\n messages = self.parser.parse_messages_from_file('tidy2_v6.out')\n self.assertEqual(len(messages), len(self.tidy2_v6_repr))\n for message in messages:\n self.assertIn(message, self.tidy2_v6_repr)\n\n def test_tidy3(self):\n \"\"\"Test the generated Messages of tidy3.out ClangTidy output file.\"\"\"\n messages = self.parser.parse_messages_from_file('tidy3.out')\n self.assertEqual(len(messages), len(self.tidy3_repr))\n for message in messages:\n self.assertIn(message, self.tidy3_repr)\n\n def test_tidy4(self):\n \"\"\"\n Test the generated Messages of tidy4.out ClangTidy output file.\n This is an uncomplete file which is equal with tidy1.out except it's\n missing the last two lines.\n \"\"\"\n messages = self.parser.parse_messages_from_file('tidy4.out')\n self.assertEqual(len(messages), len(self.tidy1_repr))\n for message in messages:\n self.assertIn(message, self.tidy1_repr)\n\n def test_tidy5(self):\n \"\"\"\n Test the grenerated Messages of tidy5.out ClangTidy output file.\n This is an uncomplete file which is equal with tidy1.out except it's\n missing the last two lines.\n \"\"\"\n messages = self.parser.parse_messages_from_file('tidy5.out')\n for message in messages:\n self.assertIn(message, self.tidy5_repr)\n\n def test_tidy5_v6(self):\n \"\"\"\n Test the grenerated Messages of tidy5_v6.out ClangTidy output file.\n This is an uncomplete file which is equal with tidy1.out except it's\n missing the last two lines.\n \"\"\"\n messages = self.parser.parse_messages_from_file('tidy5_v6.out')\n for message in messages:\n self.assertIn(message, self.tidy5_v6_repr)\n\n def test_tidy6(self):\n \"\"\"\n Test the generated Messages of tidy6.out ClangTidy output file.\n \"\"\"\n messages = self.parser.parse_messages_from_file('tidy6.out')\n for message in messages:\n self.assertIn(message, self.tidy6_repr)\n\n\nclass TidyPListConverterTestCase(unittest.TestCase):\n \"\"\"\n Test the output of the PListConverter, which converts Messages to plist\n format.\n \"\"\"\n\n def setUp(self):\n \"\"\"Setup the PListConverter.\"\"\"\n self.plist_conv = tidy_out_conv.PListConverter()\n\n def test_empty(self):\n \"\"\"Test for empty Messages.\"\"\"\n orig_plist = copy.deepcopy(self.plist_conv.plist)\n\n self.plist_conv.add_messages([])\n self.assertDictEqual(orig_plist, self.plist_conv.plist)\n\n output = io.BytesIO()\n self.plist_conv.write(output)\n\n with open('empty.plist', 'rb') as pfile:\n exp = pfile.read()\n print(exp.decode('utf-8'))\n print(output.getvalue().decode('utf-8'))\n self.assertEqual(exp, output.getvalue())\n\n output.close()\n\n def test_tidy1(self):\n \"\"\"Test for the tidy1.plist file.\"\"\"\n self.plist_conv.add_messages(self.tidy1_repr)\n\n # use relative path for this test\n self.plist_conv.plist['files'][0] = 'files/test.cpp'\n\n output = io.BytesIO()\n self.plist_conv.write(output)\n\n with open('tidy1.plist', 'rb') as pfile:\n exp = pfile.read()\n self.assertEqual(exp, output.getvalue())\n\n output.close()\n\n def test_tidy2(self):\n \"\"\"Test for the tidy2.plist file.\"\"\"\n self.plist_conv.add_messages(self.tidy2_repr)\n\n # use relative path for this test\n self.plist_conv.plist['files'][0] = 'files/test2.cpp'\n\n output = io.BytesIO()\n self.plist_conv.write(output)\n\n with open('tidy2.plist', 'rb') as pfile:\n exp = pfile.read()\n self.assertEqual(exp, output.getvalue())\n\n output.close()\n\n def test_tidy3(self):\n \"\"\"Test for the tidy3.plist file.\"\"\"\n self.plist_conv.add_messages(self.tidy3_repr)\n\n # use relative path for this test\n self.plist_conv.plist['files'][0] = 'files/test3.cpp'\n self.plist_conv.plist['files'][1] = 'files/test3.hh'\n\n output = io.BytesIO()\n self.plist_conv.write(output)\n\n with open('tidy3.plist', 'rb') as pfile:\n exp = pfile.read()\n self.assertEqual(exp, output.getvalue())\n\n output.close()\n","sub_path":"analyzer/tests/unit/test_tidy_output_converter.py","file_name":"test_tidy_output_converter.py","file_ext":"py","file_size_in_byte":15019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"439045847","text":"import wx\r\nimport wx.lib.stattext as statTex\r\nimport conf.config as config\r\nimport utils.charActivitiesUtils as nGUtils\r\nimport utils.bottomMenu as bottomMenu\r\nfrom os.path import join\r\n\r\nclass imageCharMatch(wx.Panel):\r\n def __init__(self, parent, id, mainWin, mainPanel, currentLesson):\r\n if wx.Platform != \"__WXGTK__\":\r\n statText = wx.StaticText\r\n else:\r\n statText = statTex.GenStaticText\r\n self.mainWin = mainWin\r\n self.mainPanel = mainPanel\r\n self.currentLesson = currentLesson\r\n self.buttonPressed = 20\r\n self.question = ''\r\n self.eventQueue = []\r\n\r\n self.question, self.answerList, self.answerImageList = nGUtils.nextImageMatchQuestion(self.currentLesson)\r\n self.checkNumberSet()\r\n\r\n self.fontSize = config.fontSize[4]\r\n if currentLesson == 'aaa': self.fontSize = config.fontSize[4]\r\n if currentLesson == 'kaKha': self.fontSize = config.fontSize[4]\r\n if currentLesson == 'oneTwo': self.fontSize = config.fontSize[5]\r\n if currentLesson == 'time': self.fontSize = config.fontSize[4]\r\n\r\n self.displayPanel = wx.Panel(parent, -1, (0, 0), (800, 600))\r\n self.displayPanel.SetBackgroundColour(config.backgroundColour)\r\n\r\n questionImg = wx.Bitmap(self.answerImageList[self.answerList.index(self.question)], wx.BITMAP_TYPE_PNG)\r\n self.questionImage = wx.StaticBitmap(self.displayPanel, 1, questionImg, (40,80), (questionImg.GetWidth(), questionImg.GetHeight()))\r\n\r\n displayImg = wx.Bitmap(join(config.coreImagesPath, 'divider.png'), wx.BITMAP_TYPE_PNG)\r\n self.displayImage = wx.StaticBitmap(self.displayPanel, -1, displayImg, (240,80), (displayImg.GetWidth(), displayImg.GetHeight()))\r\n\r\n self.displayText1 = statText(self.displayPanel, 1, self.answerList[0], (280, 70), style = wx.ALIGN_CENTRE)\r\n self.displayText1.SetFont(wx.Font(self.fontSize, wx.SWISS, wx.NORMAL, wx.NORMAL, False, config.fontName))\r\n self.displayText1.SetBackgroundColour(config.backgroundColour)\r\n self.displayText1.Bind(wx.EVT_LEFT_DOWN, self.OnAns1, id=1)\r\n\r\n self.displayText2 = statText(self.displayPanel, 2, self.answerList[1], (440, 70), style = wx.ALIGN_CENTRE)\r\n self.displayText2.SetFont(wx.Font(self.fontSize, wx.SWISS, wx.NORMAL, wx.NORMAL, False, config.fontName))\r\n self.displayText2.SetBackgroundColour(config.backgroundColour)\r\n self.displayText2.Bind(wx.EVT_LEFT_DOWN, self.OnAns2, id=2)\r\n\r\n self.displayText3 = statText(self.displayPanel, 3, self.answerList[2], (620, 70), style = wx.ALIGN_CENTRE)\r\n self.displayText3.SetFont(wx.Font(self.fontSize, wx.SWISS, wx.NORMAL, wx.NORMAL, False, config.fontName))\r\n self.displayText3.SetBackgroundColour(config.backgroundColour)\r\n self.displayText3.Bind(wx.EVT_LEFT_DOWN, self.OnAns3, id=3)\r\n\r\n answerImg = wx.Bitmap(join(config.coreImagesPath, 'ansBlank.png'), wx.BITMAP_TYPE_PNG)\r\n self.answerImage = wx.StaticBitmap(self.displayPanel, -1, answerImg, (160,300), (180,140))\r\n self.answerImage.SetBackgroundColour(config.backgroundColour)\r\n\r\n nextQuestionImg = wx.Bitmap(join(config.buttonsPath,'nextQuestion.png'), wx.BITMAP_TYPE_PNG)\r\n self.nextQuestionButton = wx.BitmapButton(self.displayPanel, 4, nextQuestionImg, (460,320), style = wx.NO_BORDER)\r\n self.nextQuestionButton.SetBackgroundColour(config.backgroundColour)\r\n self.nextQuestionButton.Bind(wx.EVT_BUTTON, self.OnNextQuestion, id=4)\r\n\r\n bottomMenu.bottomMenu([self.displayPanel], parent, self.mainWin, 'threeButton', self.mainPanel)\r\n \r\n def OnNextQuestion(self, event=None):\r\n if len(self.eventQueue) != 0:\r\n self.eventQueue[0].SetBackgroundColour(config.backgroundColour)\r\n self.eventQueue[0].SetLabel(self.eventQueue[0].GetLabel())\r\n self.eventQueue = []\r\n self.answerImage.SetBitmap(wx.Bitmap(join(config.coreImagesPath, 'ansBlank.png'), wx.BITMAP_TYPE_PNG))\r\n self.questionImage.SetBitmap(wx.Bitmap(join(config.coreImagesPath, 'blank.png'), wx.BITMAP_TYPE_PNG))\r\n self.question, self.answerList, self.answerImageList = nGUtils.nextImageMatchQuestion(self.currentLesson)\r\n self.questionImage.SetBitmap(wx.Bitmap(self.answerImageList[self.answerList.index(self.question)], wx.BITMAP_TYPE_PNG))\r\n self.checkNumberSet()\r\n self.displayText1.SetLabel(self.answerList[0])\r\n self.displayText2.SetLabel(self.answerList[1])\r\n self.displayText3.SetLabel(self.answerList[2])\r\n\r\n def OnAns1(self, event):\r\n self.eventQueue.append(event.GetEventObject())\r\n self.buttonPressed = 0\r\n self.changeBackgroundColour()\r\n answer = self.checkAnswer()\r\n self.displayResult(answer)\r\n\r\n def OnAns2(self, event):\r\n self.eventQueue.append(event.GetEventObject())\r\n self.buttonPressed = 1\r\n self.changeBackgroundColour()\r\n answer = self.checkAnswer()\r\n self.displayResult(answer)\r\n\r\n def OnAns3(self, event):\r\n self.eventQueue.append(event.GetEventObject())\r\n self.buttonPressed = 2\r\n self.changeBackgroundColour()\r\n answer = self.checkAnswer()\r\n self.displayResult(answer)\r\n\r\n def changeBackgroundColour(self):\r\n if len(self.eventQueue) == 1:\r\n self.eventQueue[0].SetBackgroundColour(config.fillColour)\r\n self.eventQueue[0].SetLabel(self.eventQueue[0].GetLabel())\r\n elif len(self.eventQueue) == 2:\r\n self.eventQueue[0].SetBackgroundColour(config.backgroundColour)\r\n self.eventQueue[0].SetLabel(self.eventQueue[0].GetLabel())\r\n self.eventQueue.pop(0)\r\n self.eventQueue[0].SetBackgroundColour(config.fillColour)\r\n self.eventQueue[0].SetLabel(self.eventQueue[0].GetLabel())\r\n\r\n def checkAnswer(self):\r\n answer = ''\r\n if self.question == self.answerList[self.buttonPressed]:\r\n answer = \"Right\"\r\n else:\r\n answer = \"Wrong\"\r\n return answer\r\n\r\n def displayResult(self, answer):\r\n if answer == \"Right\":\r\n self.answerImage.SetBitmap(wx.Bitmap(join(config.coreImagesPath, 'right.png'), wx.BITMAP_TYPE_PNG))\r\n else:\r\n self.answerImage.SetBitmap(wx.Bitmap(join(config.coreImagesPath, 'wrong.png'), wx.BITMAP_TYPE_PNG))\r\n \r\n## This function is to check for double printing of chars like && in Linux.\r\n## The function is kept here to solve problems occuring only in specific modules like this one.\r\n def checkNumberSet(self):\r\n if wx.Platform == \"__WXGTK__\":\r\n for i in range(len(self.answerList)):\r\n if self.answerList[i] == '&&':\r\n self.answerList[i] = self.answerList[i][0]\r\n else:\r\n pass\r\n","sub_path":"eBarnamala/activities/imageCharMatch.py","file_name":"imageCharMatch.py","file_ext":"py","file_size_in_byte":6848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"558634008","text":"# Jetfuel Game Engine- A SDL-based 2D game-engine\r\n# Copyright (C) 2017 InfernoStudios\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n# \r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n# \r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\n\nfrom ctypes import c_void_p\nfrom ctypes import c_wchar_p\nfrom ctypes import c_bool\n\nclass message_bus(object):\n _jetfuel = None;\n messagebusref = None;\n\n def __init__(self, jetfuelsoloader, messagebuspointer):\n self._jetfuel = jetfuelsoloader.jetfuelso;\n self.messagebusref = messagebuspointer;\n \n def post_message(self, message):\n if(self.messagebusref is None):\n return False;\n else:\n self._jetfuel.Message_bus_post_message_to_message_bus.argtypes = [\n c_void_p, c_wchar_p];\n \n self._jetfuel.Message_bus_post_message_to_message_bus(\n self.messagebusref, message);\n \n return True;\n \n def does_message_exist(self, message):\n if(self.messagebusref is None):\n return \"NULL message bus pointer\";\n else:\n self._jetfuel.Message_bus_does_message_exist.argtypes = [\n c_void_p, c_wchar_p];\n \n self._jetfuel.Message_bus_does_message_exist.restype = c_bool;\n \n return self._jetfuel.Message_bus_does_message_exist(\n self.messagebusref, message);","sub_path":"itchiodeployment/linux/PythonAPI/pythonwrappers/jetfuel/core/messagebus.py","file_name":"messagebus.py","file_ext":"py","file_size_in_byte":1905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"494528527","text":"from ya_glm.base.Glm import Glm\nfrom ya_glm.pen_max.lasso import get_pen_max\nfrom ya_glm.pen_max.ridge import get_ridge_pen_max\n\n\nclass GlmCvxPen(Glm):\n \"\"\"\n Base class for GLMs with convex penalties.\n \"\"\"\n\n def get_pen_val_max(self, X, y, sample_weight=None):\n \"\"\"\n Returns the largest reasonable penalty parameter for the processed data.\n\n Parameters\n ----------\n X: array-like, shape (n_samples, n_features)\n The training covariate data.\n\n y: array-like, shape (n_samples, )\n The training response data.\n\n sample_weight: None or array-like, shape (n_samples,)\n Individual weights for each sample.\n\n Output\n ------\n pen_val_max: float\n Largest reasonable tuning parameter value.\n \"\"\"\n X_pro, y_pro, _ = self.preprocess(X, y,\n sample_weight=sample_weight,\n copy=True)\n\n if self._primary_penalty_type == 'lasso':\n\n return get_pen_max(X=X_pro, y=y_pro,\n fit_intercept=self.fit_intercept,\n sample_weight=sample_weight,\n loss=self._get_loss_config(),\n penalty=self._get_penalty_config()\n )\n\n elif self._primary_penalty_type == 'ridge':\n return get_ridge_pen_max(X=X_pro, y=y_pro,\n fit_intercept=self.fit_intercept,\n sample_weight=sample_weight,\n loss=self._get_loss_config(),\n penalty=self._get_penalty_config()\n )\n\n else:\n raise ValueError(\"Bad self._primary_penalty_type: {}\"\n \"\".format(self._primary_penalty_type))\n\n ################################\n # subclasses need to implement #\n ################################\n\n @property\n def _primary_penalty_type(self):\n \"\"\"\n Is this primarily a ridge or a lasso penalty?\n \"\"\"\n # 'lasso' or 'ridge'\n raise NotImplementedError\n","sub_path":"ya_glm/base/GlmCvxPen.py","file_name":"GlmCvxPen.py","file_ext":"py","file_size_in_byte":2255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"252106639","text":"# Newlines\n# Create string with three sets of quotes to escape newlines in string\nprint('''Hello\n World''')\n\n# In-place Operators + - | ^ & / >> % // **\nx=2\nx += 3\nprint(x)\n\nx=7\nx %= 5\nprint(x)\n\n# Comparison => bez znaczenia (float or int)\n# <= or >= moża także używać do Str\nprint(7 > 7.0)\n\n# KALKULATOR ------------\nwhile True:\n print('''\n Opcje:\n Enter \"add\"\n Enter \"multiply\"\n Enter \"quit\"''')\n user_input = input('--> ')\n\n if user_input == 'quit':\n break\n elif user_input == 'add':\n num1 = float(input('1th number --> '))\n num2 = float(input('2th number --> '))\n print('Result: ' + str(num1 + num2) )\n elif user_input == 'multiply':\n print()\n else:\n print('Unknow input')\n","sub_path":"Sololearn.py","file_name":"Sololearn.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"493499805","text":"from flask import Flask, render_template, request, flash, url_for, redirect, make_response, session, jsonify\nimport json\nimport os\nfrom flask import request\n\nfrom webapp.utils import Levenshtein_distance\nfrom recognition.recognition import *\n\napp = Flask(__name__)\n\nwith open(os.path.join(\"static\", \"word_rus.txt\")) as fp:\n WORDS_RUS = [w.strip() for w in fp]\n\nclass Image:\n def __init__(self, img_name, img, found_img_name, found_img):\n self.img_name = img_name\n self.img = img\n self.found_img = found_img\n self.found_img_name = found_img_name\n\ndef find_nearest_word(word, words):\n if word in words:\n return word\n else:\n return min((Levenshtein_distance(w, word), w) for w in words)[1]\n\n\ndef create_response(text):\n resp = make_response(redirect(url_for(\"form\")))\n resp.set_cookie(\"value\", text)\n return resp\n\n\ndef get_words():\n return WORDS_RUS\n\n\ndef json_words():\n words = {\"words\": get_words()}\n return json.dumps(words, ensure_ascii=False)\n\n\ndef executor(*data):\n def wrapper(*functions):\n for func in functions:\n yield func(*data)\n\n return wrapper\n\n\ndef admin_only(func):\n def wrapper(*args, **kwargs):\n current_session = session.get(\"user\", 0)\n if current_session == 0:\n return func(*args, **kwargs)\n else:\n return func(*args, **kwargs)\n\n return wrapper\n\ndef search_core_image(word):\n available_words = [('рокета', 'rocket.jpg'),\n ('корабль', 'ship.png'),\n ('акула', 'shark.jpg'),\n ('кот', 'cat.jpg'),\n ('самолет', 'plane.jpg')]\n\n for k, v in available_words:\n if k == word:\n return v\n\n\ndef search_image(word):\n img_path = search_core_image(word)\n result = get_recognized_images(img_path)\n\n\n@app.route(\"/\")\ndef search_index():\n words = \", \".join(\"'%s'\" % w for w in get_words())\n return render_template(\"search/index.html\", openvariable=\"{{\", closevariable=\"}}\", words=words)\n\n\n@app.route(\"/search\")\ndef search_result():\n if request.method == 'GET':\n print(request)\n word = request.args.get('word')\n\n words = get_words()\n word = find_nearest_word(word, words)\n print(word)\n result_list = []\n result_list.append(Image('Horsehead Colombari', '/home/joby/Repo/nasa-default/recognition/img_test/space/space1.jpg',\n 'spit', '/home/joby/Repo/nasa-default/recognition/img_test/contours/contour_ship.png'))\n return render_template(\"search/result.html\", openvariable=\"{{\", closevariable=\"}}\", result_list=result_list)\n\n\n@app.route(\"/json/words\")\ndef words_autocomplete():\n return json_words()\n\n\nif __name__ == '__main__':\n app.config.from_pyfile(\"config.py\")\n app.run()","sub_path":"webapp/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"55331305","text":"import pandas as pd\n\n#기온 데이터\ndf1=pd.read_excel('./data/기온_전체_2010-2019.xlsx')\n#순서 역순으로 바꾸기\ndf1=df1.loc[::-1].reset_index(drop=True)\n#평균기온, 평균최고, 평균최저만 남기고 drop\ndf1.drop(['지역번호','지역명','최고기온관측지점','최저기온관측지점','최고기온(℃)','최저기온(℃)'],axis=1,inplace=True)\n#2019년 9월까지 자르기\ntemp=df1.iloc[96:108]\ntemp.set_index(['일시'],inplace=True)\n\n#강수일수\ndf2=pd.read_excel('./data/2018_강수일수.xlsx')\n\ndf2T=df2.transpose()\nrain_days=df2T[8].iloc[1:13]\nrain_days.astype('float')\n\n#강수량\nrainfall=pd.read_excel('./data/2018_강수량.xlsx',skiprows=[1,2,3,4,5,6,7])\nrainfall=rainfall['Unnamed: 2']\n\n#황사일수\ndust=pd.read_excel('./data/2018_황사일수.xlsx')\ndustT=dust.transpose()\ndust=dustT[8].iloc[1:13]\n\n#체감온도\nfeelingtemp = pd.read_excel('./data/2018_체감온도.xlsx', header=3)\n\nfor i in range(len(feelingtemp['일자'])):\n feelingtemp.loc[i, '월별'] = str(feelingtemp.loc[i, '일자'])[0:4]+ '.' + str(feelingtemp.loc[i, '일자'])[5:7] \n\nfeelingtemp = feelingtemp.groupby('월별').mean()\n\n#소비자 물가지수\ndf7 = pd.read_csv('C:/project1/data/2018소비자물가지수.csv', encoding='cp949', header=0).iloc[:, 2:]\nsobija = pd.DataFrame(df7.T[0])\n\n#폭염지수\nheat_wave = pd.read_excel('./data/2018_폭염지수.xlsx', header=5).iloc[[1], 1:13]\nheat_wave = heat_wave.T\n\nrain_days.index=rainfall.index=dust.index=feelingtemp.index=sobija.index=heat_wave.index=temp.index\n\ntotal_data=pd.concat([temp,rain_days,rainfall,dust,feelingtemp,heat_wave,sobija],axis=1)\ncols=['평균기온(℃)','평균최고기온(℃)','평균최저기온(℃)','강수일수','강수량','황사일수','기온(°C)','풍속(m/s)','체감기온(°C)','폭염지수','소비자물가지수']\ntotal_data.columns=cols\n\n","sub_path":"project1.py","file_name":"project1.py","file_ext":"py","file_size_in_byte":1870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"327564295","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /usr/lib/python2.7/site-packages/pyjznet/server.py\n# Compiled at: 2014-12-11 04:16:10\nfrom __future__ import print_function\nfrom geventwebsocket import WebSocketServer, WebSocketApplication, Resource\nimport sys, logging\nfrom . import pools\nfrom . import processors\nfrom . import listeners\nfrom . import messages\nroot = logging.getLogger()\nroot.setLevel(logging.DEBUG)\nch = logging.StreamHandler(sys.stdout)\nch.setLevel(logging.DEBUG)\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nch.setFormatter(formatter)\nroot.addHandler(ch)\n\nclass Server(object):\n\n def __init__(self):\n self.rpc_services = []\n self._send_msg_pool = pools.SendMessagePool()\n self._receive_msg_pool = pools.ReceiveMessagePool()\n self.message_builder = messages.MessageBuilder()\n\n def add_rpc_service(self, name, rpc_service):\n self.rpc_services.append((name, rpc_service))\n\n def start(self, host='127.0.0.1', port=8000):\n send_msg_pool = self._send_msg_pool\n receive_msg_pool = self._receive_msg_pool\n message_builder = self.message_builder\n send_msg_pool.add_listener(object, listeners.SendMessageHandler())\n\n class WSApplication(WebSocketApplication):\n\n def on_open(self):\n print('Connection opened')\n\n def on_close(self, reason):\n print('Connection closed')\n\n def on_message(self, message):\n print('got message', message)\n receive_msg_pool.offer_messages(message_builder.create_messages(self, message))\n\n msg_processor = processors.MessageProcessor(receive_msg_pool, send_msg_pool)\n msg_processor.add_rpc_services(self.rpc_services)\n msg_processor.start()\n ws_server = WebSocketServer((\n host, port), Resource({'/': WSApplication, '/websocket': WSApplication}))\n print('start to listen at http://%s:%d' % (host, port))\n ws_server.serve_forever()","sub_path":"pycfiles/jznet-0.0.1.linux-x86_64.tar/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"288447105","text":"# -*- coding: utf-8 -*-\n# Author : Manki Baek\n# e-mail : Manki.Baek@seculayer.co.kr\n# Powered by Seculayer © 2021 Service Model Team, R&D Center.\n\nfrom datetime import datetime\nimport json\nimport os\n\nfrom mlps.core.apeflow.interface.model.ModelAbstract import ModelAbstract\nfrom mlps.core.apeflow.api.algorithms.gs.GSAlgAbstract import GSAlgAbstract\nfrom mlps.core.RestManager import RestManager\n\n\nclass GSModel(ModelAbstract):\n def __init__(self, param_dict, ext_data=None):\n ModelAbstract.__init__(self, param_dict, ext_data)\n self.model: GSAlgAbstract = self._build()\n\n def learn(self, dataset):\n start_time = datetime.now()\n self.model.learn(dataset)\n learn_time_sec = (datetime.now() - start_time).total_seconds()\n\n if json.loads(os.environ[\"TF_CONFIG\"])[\"task\"][\"index\"] == \"0\":\n if self.model.learn_result_callback is None:\n eps = len(dataset[\"x\"]) / learn_time_sec\n learn_result = None\n else:\n eps = self.model.learn_result_callback.get_eps()\n learn_result = self.model.learn_result_callback.get_learn_result()\n\n RestManager.update_eps(self.param_dict['job_key'], eps)\n if learn_result is not None:\n RestManager.update_learn_result(self.param_dict['job_key'], learn_result)\n\n self.model.saved_model()\n","sub_path":"mlps/core/apeflow/interface/model/GSModel.py","file_name":"GSModel.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"237819039","text":"#Loops\n\n#FOR\n\n#Includes 2, excludes 6\nfor x in range(2, 6):\n print(x)\n\n#Step value\nfor x in range(2, 10, 2):\n print(x)\n\n#Looping through each letter of a string\nfor x in \"banana\":\n print(x)\n\n#Break\nfruits = [\"apple\", \"banana\", \"cherry\"]\nfor x in fruits:\n print(x)\n if x == \"banana\":\n break\n\n#Continue\nfruits = [\"apple\", \"banana\", \"cherry\"]\nfor x in fruits:\n if x == \"banana\":\n continue\n print(x)\n\n#WHILE\ni = 1\nwhile i < 6:\n print(i)\n i += 1\n\n#break and continue in while too\n","sub_path":"10_loops.py","file_name":"10_loops.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"206999191","text":"# -*-coding:Utf-8 -*\n\n#########################################################################\n#\n#Programme en python permettant d'exploiter les résultats d'analyse\n#d'un écoulement de liquide dans une conduite grâce au programme TracTrac\n#exploité sur Matlab. La matrice 'Pts' fut exportée en .csv\n#\n##########################################################################\n\n\n#-- importation des bibliothèques --\n\nimport numpy as np\nimport csv\nimport matplotlib.pyplot as plt\n\n#-- Variables --\n\n#largeur de la conduite en pixel et subdivision en intervalles de cette largeur\nlargeur=1000\nsubdi=20\nfichier_entree=\"resultats-matlab/tractrac120.csv\"\nfichier_sortie=\"resultats-python/res120-max.csv\"\n\n#-- Programme --\n\n\n#Creation d'une matrice \"results\" à partir du fichier .csv\n#Chaque ligne correspond à une particule à un certain moment\nresults = []\nwith open(fichier_entree) as csvfile:\n reader = csv.reader(csvfile, quoting=csv.QUOTE_NONNUMERIC)\n for row in reader:\n results.append(row)\n\n\ninter=largeur//subdi\n\n#Matrice 'réduction' de 2 colonnes et n lignes correspondants à la matrice résults\nreduction = np.zeros(shape=(len(results),2))\n\n#Matrice 'somme' de 2 lignes et n colonnes correspondants aux intervalles\nsomme = np.zeros(shape=(2,inter))\n\n#Matrice finale\nfinal = np.zeros(shape=(inter))\n\n#On réduit la matrice résults de 11 colonnes pour n'en faire plus que 2\n#Ces deux colonnes restantes correspondent à la position verticale et la vitesse\ni=0\nfor x in results:\n reduction[i][0]=x[3]\n reduction[i][1]=x[4]\n i+=1\n\n#On calcule la variable position qui correspond à la postion de la particule en pixel divisé\n#par la subdivision en intervalles.\n#Ainsi, la ligne 0 de la matrice correspond aux nombres de particules détectées pour toutes les images pour chaque intervalle\n#La ligne 1 correspond à la somme des vitesses pour les particules d'un intervalle donné.\ni=0\nfor x in reduction:\n position=reduction[i][0]//subdi\n position=int(position)\n somme[1][position-1]+=reduction[i][1]\n somme[0][position-1]+=1\n i+=1\n\n#La matrice finale correspond à la moyenne des vitesses. On fait la somme totale des vitesses divisé par le nombre de particules\n#pour chaque intervalle. On vérifie qu'il n'y a pas de division par 0 (s'il y a 0 particules détectées).\ni=0\nfor i in range(inter):\n if float(somme[0][i])==0.0:\n continue\n \n final[i]=abs(float(somme[1][i])/float(somme[0][i]))\n i+=1\n\n\nprint(final)\n\n#On sauvegarde la matrice finale dans un .csv\nnp.savetxt(fichier_sortie, final, delimiter=\",\", fmt='%1.4f')\n\n#On affiche le résultat\nplt.plot(final)\nplt.show()","sub_path":"ecoulement_fluide.py","file_name":"ecoulement_fluide.py","file_ext":"py","file_size_in_byte":2644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"589482666","text":"str = input('Enter a string: ')\nstr = str.strip()\n\nlength = len(str)\n\n#davis\n#01234\n#length = 5\n\n#leng = length - 1\n\nwhile True:\n if str == 'done':\n break;\n length = length - 1\n print(str[length])\n\n#sivad\n#43210\n","sub_path":"src/Excercise_1.py","file_name":"Excercise_1.py","file_ext":"py","file_size_in_byte":228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"634833900","text":"\"\"\"Update all the get-pip.py scripts.\"\"\"\n\nimport itertools\nimport operator\nimport re\nfrom base64 import b85encode\nfrom functools import lru_cache\nfrom io import BytesIO\nfrom pathlib import Path, PosixPath\nfrom typing import Dict, Iterable, List, Tuple\nfrom zipfile import ZipFile\n\nimport requests\nfrom cachecontrol import CacheControl\nfrom cachecontrol.caches.file_cache import FileCache\nfrom packaging.specifiers import SpecifierSet\nfrom packaging.version import Version\nfrom rich.console import Console\n\nSCRIPT_CONSTRAINTS = {\n \"default\": {\n \"pip\": \"\",\n \"setuptools\": \"\",\n \"wheel\": \"\",\n },\n \"2.6\": {\n \"pip\": \"<10\",\n \"setuptools\": \"<37\",\n \"wheel\": \"<0.30\",\n },\n \"2.7\": {\n \"pip\": \"<21.0\",\n \"setuptools\": \"<45\",\n \"wheel\": \"\",\n },\n \"3.2\": {\n \"pip\": \"<8\",\n \"setuptools\": \"<30\",\n \"wheel\": \"<0.30\",\n },\n \"3.3\": {\n \"pip\": \"<18\",\n \"setuptools\": \"\",\n \"wheel\": \"<0.30\",\n },\n \"3.4\": {\n \"pip\": \"<19.2\",\n \"setuptools\": \"\",\n \"wheel\": \"\",\n },\n \"3.5\": {\n \"pip\": \"<21.0\",\n \"setuptools\": \"\",\n \"wheel\": \"\",\n },\n}\n\nMOVED_SCRIPTS = {\n # legacy: current\n \"get-pip.py\": \"get-pip.py\", # redirect users of the file in the repository root.\n \"2.6/get-pip.py\": \"pip/2.6/get-pip.py\",\n \"2.7/get-pip.py\": \"pip/2.7/get-pip.py\",\n \"3.2/get-pip.py\": \"pip/3.2/get-pip.py\",\n \"3.3/get-pip.py\": \"pip/3.3/get-pip.py\",\n \"3.4/get-pip.py\": \"pip/3.4/get-pip.py\",\n \"3.5/get-pip.py\": \"pip/3.5/get-pip.py\",\n}\n\n\ndef get_all_pip_versions() -> Dict[Version, Tuple[str, str]]:\n data = requests.get(\"https://pypi.python.org/pypi/pip/json\").json()\n\n versions = sorted(Version(s) for s in data[\"releases\"].keys())\n\n retval = {}\n for version in versions:\n wheels = [\n (file[\"url\"], file[\"md5_digest\"])\n for file in data[\"releases\"][str(version)]\n if file[\"url\"].endswith(\".whl\")\n ]\n if not wheels:\n continue\n assert len(wheels) == 1, (version, wheels)\n retval[version] = wheels[0]\n return retval\n\n\ndef determine_latest(versions: Iterable[Version], *, constraint: str):\n assert sorted(versions) == list(versions)\n return list(SpecifierSet(constraint).filter(versions))[-1]\n\n\n@lru_cache\ndef get_ordered_templates() -> List[Tuple[Version, Path]]:\n \"\"\"Get an ordered list of templates, based on the max version they support.\n\n This looks at the templates directory, trims the \"pre-\" from the files,\n and returns a sorted list of (version, template_path) tuples.\n \"\"\"\n all_templates = list(Path(\"./templates\").iterdir())\n\n fallback = None\n ordered_templates = []\n for template in all_templates:\n # `moved.py` isn't one of the templates to be used here.\n if template.name == \"moved.py\":\n continue\n if template.name == \"default.py\":\n fallback = template\n continue\n assert template.name.startswith(\"pre-\")\n\n version_str = template.name[4:-3] # \"pre-{version}.py\"\n version = Version(version_str)\n ordered_templates.append((version, template))\n\n # Use the epoch mechanism, to force the fallback to the end.\n assert fallback is not None\n assert fallback.name == \"default.py\"\n ordered_templates.append((Version(\"1!0\"), fallback))\n\n # Order the (version, template) tuples, by increasing version numbers.\n return sorted(ordered_templates, key=operator.itemgetter(0))\n\n\ndef determine_template(version: Version):\n ordered_templates = get_ordered_templates()\n for template_version, template in ordered_templates:\n if version < template_version:\n return template\n else:\n assert template.name == \"default.py\"\n return template\n\n\ndef download_wheel(url: str, expected_md5: str) -> bytes:\n session = requests.session()\n cached_session = CacheControl(session, cache=FileCache(\".web_cache\"))\n\n response = cached_session.get(url)\n return response.content\n\n\ndef populated_script_constraints(original_constraints):\n \"\"\"Yields the original constraints, with `minimum_supported_version` added.\n\n For `M.N/get-pip.py`, it would be \"(M, N)\".\n\n For the \"default\" get-pip.py, it would be \"(M, N+1)\" where M.N is the\n highest version in the rest of the mapping.\n\n Also, the yield order is defined as \"default\" and then versions in\n increasing order.\n \"\"\"\n sorted_python_versions = sorted(set(original_constraints) - {\"default\"})\n for variant in itertools.chain([\"default\"], sorted_python_versions):\n if variant == \"default\":\n major, minor = map(int, sorted_python_versions[-1].split(\".\"))\n minor += 1\n else:\n major, minor = map(int, variant.split(\".\"))\n\n mapping = original_constraints[variant].copy()\n mapping[\"minimum_supported_version\"] = f\"({major}, {minor})\"\n\n yield variant, mapping\n\n\ndef repack_wheel(data: bytes):\n \"\"\"Remove the .dist-info, so that this is no longer a valid wheel.\"\"\"\n new_data = BytesIO()\n with ZipFile(BytesIO(data)) as existing_zip:\n with ZipFile(new_data, mode=\"w\") as new_zip:\n for zipinfo in existing_zip.infolist():\n if re.search(r\"pip-.+\\.dist-info/\", zipinfo.filename):\n continue\n new_zip.writestr(zipinfo, existing_zip.read(zipinfo))\n\n return new_data.getvalue()\n\n\ndef encode_wheel_contents(data: bytes) -> str:\n zipdata = b85encode(data).decode(\"utf8\")\n\n chunked = []\n for i in range(0, len(zipdata), 79):\n chunked.append(zipdata[i : i + 79])\n\n return \"\\n\".join(chunked)\n\n\ndef determine_destination(base: str, variant: str) -> Path:\n public = Path(base)\n if not public.exists():\n public.mkdir()\n\n if variant == \"default\":\n return public / \"get-pip.py\"\n\n retval = public / variant / \"get-pip.py\"\n if not retval.parent.exists():\n retval.parent.mkdir()\n\n return retval\n\n\ndef generate_one(variant, mapping, *, console, pip_versions):\n # Determing the correct wheel to download\n pip_version = determine_latest(pip_versions.keys(), constraint=mapping[\"pip\"])\n wheel_url, wheel_hash = pip_versions[pip_version]\n\n console.log(f\" Downloading [green]{PosixPath(wheel_url).name}\")\n original_wheel = download_wheel(wheel_url, wheel_hash)\n repacked_wheel = repack_wheel(original_wheel)\n encoded_wheel = encode_wheel_contents(repacked_wheel)\n\n # Generate the script, by rendering the template\n template = determine_template(pip_version)\n console.log(f\" Rendering [yellow]{template}\")\n rendered_template = template.read_text().format(\n zipfile=encoded_wheel,\n installed_version=pip_version,\n pip_version=mapping[\"pip\"],\n setuptools_version=mapping[\"setuptools\"],\n wheel_version=mapping[\"wheel\"],\n minimum_supported_version=mapping[\"minimum_supported_version\"],\n )\n # Write the script to the correct location\n destination = determine_destination(\"public\", variant)\n console.log(f\" Writing [blue]{destination}\")\n destination.write_text(rendered_template)\n\n\ndef generate_moved(destination: str, *, location: str, console: Console):\n template = Path(\"templates\") / \"moved.py\"\n assert template.exists()\n\n rendered_template = template.read_text().format(location=location)\n console.log(f\" Writing [blue]{destination}[reset]\")\n console.log(f\" Points users to [cyan]{location}[reset]\")\n Path(destination).write_text(rendered_template)\n\n\ndef main() -> None:\n console = Console()\n with console.status(\"Fetching pip versions...\"):\n pip_versions = get_all_pip_versions()\n console.log(f\"Found {len(pip_versions)} available pip versions.\")\n console.log(f\"Latest version: {max(pip_versions)}\")\n\n with console.status(\"Generating scripts...\") as status:\n for variant, mapping in populated_script_constraints(SCRIPT_CONSTRAINTS):\n status.update(f\"Working on [magenta]{variant}\")\n console.log(f\"[magenta]{variant}\")\n\n generate_one(variant, mapping, console=console, pip_versions=pip_versions)\n\n if MOVED_SCRIPTS:\n console.log(\"[magenta]Generating 'moved' scripts...\")\n with console.status(\"Generating 'moved' scripts...\") as status:\n for legacy, current in MOVED_SCRIPTS.items():\n status.update(f\"Working on [magenta]{legacy}\")\n generate_moved(legacy, console=console, location=current)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"scripts/generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":8608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"542800730","text":"import tornado.web\nimport json\nfrom decorators.handleException import handleException\nfrom decorators.checkAuthentication import checkAuthentication\nfrom utils.logger import Logger\nfrom handlers import base\nfrom exceptions import exceptions\nfrom services.pedirCuentaService import PedirCuentaService \n\nlogger = Logger('pedirCuentaHandler')\n\nclass PedirCuentaHandler(base.BaseHandler):\n\n @tornado.web.asynchronous\n @handleException\n def options(self, restaurante):\n self.finish()\n \n @tornado.web.asynchronous\n @handleException\n @checkAuthentication\n def post(self, restaurante):\n logger.debug('post')\n try:\n data = json.loads(self.request.body)\n logger.debug('body:{}'.format(data))\n # idsPedidos = data['cuenta']['ids_pedidos']\n idRestaurante = data['cuenta']['id_restaurante']\n idMesa = data['cuenta']['id_mesa']\n pedidos = data['cuenta']['pedidos']\n # if not isinstance(idsPedidos, list):\n # raise Exception('idsPedidos no es un array')\n \n except Exception as e:\n logger.error('Body incorrecto, exception: : {}'.format(e) + ' body: {}'.format(self.request.body))\n raise exceptions.BadRequest(3001)\n svc = PedirCuentaService()\n svc.pedirCuenta(idRestaurante, idMesa)\n # logger.debug('pedidos:{}'.format(pedidos))\n svc.actualizarPedidos(pedidos, 'finalizado')\n self.finish({})","sub_path":"byewait/src/handlers/pedirCuentaHandler.py","file_name":"pedirCuentaHandler.py","file_ext":"py","file_size_in_byte":1492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"252040691","text":"import sys\n\ninput=sys.stdin.readline\nn = int(input())\nqueue_list = [None for _ in range(n)]\nhead = 0\ntail = 0\n\nfor _ in range(n):\n cmd = list(input().split())\n\n if cmd[0] == 'push':\n x = int(cmd[1])\n queue_list[tail] =x\n tail += 1\n elif cmd[0] == 'pop':\n if tail-head > 0:\n head += 1\n pop_x = queue_list[head-1]\n print(pop_x)\n else:\n head = 0\n tail = 0\n print(-1)\n elif cmd[0] == 'size':\n print(tail - head)\n elif cmd[0] == 'empty':\n if tail-head > 0:\n print(0)\n else:\n print(1)\n elif cmd[0] == 'front':\n if tail-head > 0:\n print(queue_list[head])\n else:\n print(-1)\n elif cmd[0] == 'back':\n if tail-head > 0:\n print(queue_list[tail-1])\n else:\n print(-1)","sub_path":"algorithm_py/queue/baekjoon_18258_queue.py","file_name":"baekjoon_18258_queue.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"363555677","text":"import os\n\nfrom kgx import RdfOwlTransformer, PandasTransformer, JsonTransformer\nimport gzip\n\n\ndef test_load():\n \"\"\"\n load tests\n \"\"\"\n cwd = os.path.abspath(os.path.dirname(__file__))\n resdir = os.path.join(cwd, 'resources')\n tdir = os.path.join(cwd, 'target')\n os.makedirs(tdir, exist_ok=True)\n \n t = RdfOwlTransformer()\n fn = os.path.join(resdir, \"mody.ttl.gz\")\n f = gzip.open(fn, 'rb')\n t.parse(f, input_format='ttl')\n t.report()\n w1 = PandasTransformer(t.graph)\n w1.save(os.path.join(tdir, 'mondo-e.csv'), type='e')\n w1.save(os.path.join(tdir, 'mondo-n.csv'), type='n')\n w3 = JsonTransformer(t.graph)\n w3.save(os.path.join(tdir, \"mondo.json\"))\n","sub_path":"tests/test_rdf_owl.py","file_name":"test_rdf_owl.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"237808121","text":"from social.forms import *\nfrom django.contrib.auth.decorators import login_required, permission_required\nfrom users.models import Membership\nfrom project.models import Project\nfrom users.models import User\nfrom django.shortcuts import render_to_response, get_object_or_404\nfrom django.template import RequestContext\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.core.context_processors import request\nfrom django.core.exceptions import ValidationError\nfrom social.models import Request\nfrom project.views import manage_project\nfrom django.views.decorators.cache import cache_control\n\n# Create your views here.\n\n#@login_required\n#def request_invite_user(request):\n \n@login_required\n@cache_control(no_cache=True, must_revalidate=True, no_store=True)\ndef my_join_request(request):\n if request.method == 'POST': \n r = get_object_or_404(Request,to_user_id=request.user.id, project_id = request.POST['project'])\n message = \"\"\n if(request.POST['button'] == 'accept'):\n p = get_object_or_404(Project,pk=request.POST['project'])\n membership = Membership(user=request.user, project=p)\n membership.save()\n message = \"La solicitud ha sido aceptada\" \n else:\n message = \"La solicitud ha sido rechazada\" \n r.delete()\n return render_to_response('social/my_join_request.html',\n {'message':message},\n context_instance=RequestContext(request))\n else:\n join_request = Request.objects.filter(to_user_id=request.user.id)\n return render_to_response('social/my_join_request.html',\n {'join_request':join_request},\n context_instance=RequestContext(request))\n\n@login_required\n@cache_control(no_cache=True, must_revalidate=True, no_store=True)\ndef request_join_project(request,project_id):\n p = get_object_or_404(Project,pk=project_id)\n if request.method == 'POST':\n users = request.POST.getlist('to_user')\n for u in users:\n user = get_object_or_404(User,pk=u)\n if Request.objects.filter(from_user_id=request.user.id, to_user_id=user.id,project_id=project_id).count() == 0:\n r = Request(to_user = user, from_user=request.user,project=p)\n r.save()\n return manage_project(request) \n else:\n memberships = Membership.objects.filter(project_id=project_id)\n users = []\n for membership in memberships:\n users.append(membership.user)\n join_requests = Request.objects.filter(from_user_id=request.user.id, project_id=project_id) \n for r in join_requests:\n users.append(r.to_user) \n form = RequestForm(users=users)\n return render_to_response('social/request_join_project.html',\n {'form':form},\n context_instance=RequestContext(request))\n ","sub_path":"src/GPDS/social/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"510766312","text":"# time: O(n * K)\n# space: O(1)\n# where n is the size of the input array and k is the degree to which the array is messed\ndef sortKMessedArray(array, k):\n for i in range(len(array) - 1):\n for j in range(1, k + 1):\n print(i, j)\n if i + j < len(array) and array[i] > array[i + j]:\n swap(i, i + j, array)\n return array\n\ndef swap(i, j, array):\n temp = array[i]\n array[i] = array[j]\n array[j] = temp\n\n\nprint(sortKMessedArray([2, 4, 1, 3, 5], 2)) # [1, 2, 3, 4, 5]\n","sub_path":"misc/searching/sort-k-messed-array.py","file_name":"sort-k-messed-array.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"238235904","text":"import os\nimport datetime\nimport logging\nimport subprocess\nimport time\n\nlog_dir = '/var/log/iptables.log'\ncurrent_size = os.path.getsize(log_dir)\n\ndef run_command(command):\n try:\n process = subprocess.Popen(command, shell = True, stdout = subprocess.PIPE)\n process.wait()\n return process.stdout.readline().rstrip()\n except Exception as e:\n logger.error(e)\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\n# create a file handler\nhandler = logging.FileHandler('monitor_tcp_app.log')\nhandler.setLevel(logging.INFO)\n# create a logging format\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nhandler.setFormatter(formatter)\n# add the handlers to the logger\nlogger.addHandler(handler)\n# add the handlers to console\nconsole = logging.StreamHandler()\nconsole.setLevel(logging.DEBUG)\nconsole.setFormatter(formatter)\nlogger.addHandler(console)\n\nwhile True:\n if os.path.getsize(log_dir) != current_size:\n logger.info(\"Found new log, start monitor TCP\")\n current_datetime = datetime.datetime.now().strftime(\"%y-%m-%d-%H-%M\")\n # monitor tcp in 60 min\n tcpdump_command = \"timeout 60 tcpdump -i port1 -w /root/log_tcp_%s.pcap\" % (current_datetime)\n result_tcp = run_command(tcpdump_command)\n logger.info(\"Saved PCAP to /root/log/log_tcp_%s.pcap\" % (current_datetime))\n current_size = os.path.getsize(log_dir)","sub_path":"monitor_tcp.py","file_name":"monitor_tcp.py","file_ext":"py","file_size_in_byte":1436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"30378608","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/luoxi/Project/yunify/qingcloud-cli/qingcloud/cli/iaas_client/actions/s2/describe_s2_servers.py\n# Compiled at: 2017-07-19 01:59:02\nfrom qingcloud.cli.misc.utils import explode_array\nfrom qingcloud.cli.iaas_client.actions.base import BaseAction\n\nclass DescribeS2ServersAction(BaseAction):\n action = 'DescribeS2Servers'\n command = 'describe-s2-servers'\n usage = '%(prog)s [-s ...] [-f ]'\n\n @classmethod\n def add_ext_arguments(cls, parser):\n parser.add_argument('-s', '--s2-servers', dest='s2_servers', action='store', type=str, default=None, help='the IDs of s2 server you want to describe.')\n parser.add_argument('-T', '--service-types', dest='service_types', action='store', type=str, default=None, help=\"the type of service, valid value is 'vsan' or 'vnas'.\")\n parser.add_argument('-S', '--status', dest='status', action='store', type=str, default=None, help='valid values include pending, active, poweroffed, suspended, deleted, ceased.')\n parser.add_argument('-w', '--search-word', dest='search_word', action='store', type=str, default=None, help='you may use this field to search from id, name and description.')\n parser.add_argument('-t', '--tags', dest='tags', action='store', type=str, default=None, help='the array of IDs of tags.')\n parser.add_argument('-v', '--verbose', dest='verbose', action='store', type=int, default=None, help='the number to specify the verbose level, larger the number, the more detailed information will be returned.')\n return\n\n @classmethod\n def build_directive(cls, options):\n directive = {'s2_servers': explode_array(options.s2_servers), \n 'service_types': explode_array(options.service_types), \n 'status': explode_array(options.status), \n 'search_word': options.search_word, \n 'tags': explode_array(options.tags), \n 'verbose': options.verbose}\n return directive","sub_path":"pycfiles/qingcloud_cli-1.3.10-py2-none-any/describe_s2_servers.py","file_name":"describe_s2_servers.py","file_ext":"py","file_size_in_byte":2122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"347226560","text":"class cachetest:\r\n l = []\r\n def __iter__(self):\r\n return self.l.__iter__()\r\n\r\n def add(self,item):\r\n self.l.append(item)\r\n\r\nc = cachetest()\r\nc.add(1)\r\nc.add(2)\r\nc.add(3)\r\nc.add(4)\r\nprint(1 in c)","sub_path":"net1/nt2/cachetest.py","file_name":"cachetest.py","file_ext":"py","file_size_in_byte":217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"515070113","text":"from math import radians, cos, sin, asin, sqrt\r\nimport json\r\n\r\ncountry_list = ['Germany',\r\n 'France',\r\n 'Netherlands',\r\n 'Belgium',\r\n 'Switzerland',\r\n 'Austria',\r\n 'Italy',\r\n 'Spain',\r\n 'Portugal',\r\n 'United Kingdom',\r\n 'Ireland',\r\n 'Poland',\r\n 'Czech Republic',\r\n 'Croatia',\r\n 'Slovenia',\r\n 'Slovakia',\r\n 'Hungary',\r\n 'Romania',\r\n 'Serbia',\r\n 'Bosnia',\r\n 'Albania',\r\n 'Bulgaria',\r\n 'Mazedonia',\r\n 'Greece',\r\n 'Turkey',\r\n 'Sweden',\r\n 'Norway',\r\n 'Denmark']\r\n\r\nwith open('city_list2.json', 'r', encoding='utf-8') as data_file:\r\n data = json.load(data_file)\r\n\r\ndef haversine(lat1, lon1, lat2, lon2):\r\n \r\n # convert decimal degrees to radians\r\n lat1, lon1, lat2, lon2 = map(radians, [lat1, lon1, lat2, lon2])\r\n\r\n # haversine formula\r\n dlat = lat2 - lat1\r\n dlon = lon2 - lon1\r\n a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2\r\n c = 2 * asin(sqrt(a)) \r\n r = 6371000 # Radius of earth in meters. Use 3956 for miles\r\n return c * r\r\n\r\nfor Origin in data:\r\n if Origin['country'] in country_list:\r\n if Origin['geocoding']['latitude'] != 0.0 and Origin['geocoding']['longitude'] != 0:\r\n print(Origin['name'])\r\n for Destination in data:\r\n if Destination['country'] in country_list:\r\n if Destination['geocoding']['latitude'] != 0.0 and Destination['geocoding']['longitude'] != 0:\r\n latitude1 = Origin['geocoding']['latitude']\r\n longitude1 = Origin['geocoding']['longitude']\r\n latitude2 = Destination['geocoding']['latitude']\r\n longitude2 = Destination['geocoding']['longitude']\r\n haversine_distance = haversine(latitude1, longitude1, latitude2, longitude2)\r\n Origin['distances']['haversine'].update({'{}'.format(Destination['name']): int(haversine_distance)})\r\n \r\ndef writeToJSONFile(path, fileName, data):\r\n filePathNameWExt = './' + path + '/' + fileName + '.json'\r\n with open(filePathNameWExt, 'w') as fp:\r\n json.dump(data, fp)\r\n\r\nwriteToJSONFile('./','city_list2',data)\r\n","sub_path":"Haversine4DataBase.py","file_name":"Haversine4DataBase.py","file_ext":"py","file_size_in_byte":2552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"5025918","text":"from typing import Iterable\nfrom datetime import datetime\nfrom uuid import UUID\nfrom record import RelocationRecord, JobRecord\n\n\ndef _format_job_id(job_id: UUID) -> str:\n return str(job_id)\n\n\ndef _format_time(time: datetime) -> str:\n return time.isoformat()\n\n\ndef format_job_id(job_id: UUID) -> dict:\n return {'jobId': _format_job_id(job_id)}\n\n\ndef format_job_status(job: JobRecord) -> dict:\n \"\"\"\n >>> import datetime\n >>> job = JobRecord(1, datetime.datetime.utcnow(), ['a', 'b'])\n >>> format_job_status(job) # doctest: +ELLIPSIS\n {'id': '1', 'created': '2...', 'finished': None, 'status': 'pending', 'uploaded': {'pending': ['a', 'b'], 'complete': [], 'failed': []}}\n\n >>> job.commit(datetime.datetime.utcnow(), 'a')\n >>> format_job_status(job) # doctest: +ELLIPSIS\n {'id': '1', 'created': '2...', 'finished': None, 'status': 'in-progress', 'uploaded': {'pending': ['b'], 'complete': [], 'failed': ['a']}}\n\n >>> job.commit(datetime.datetime.utcnow(), 'a', 'A')\n >>> format_job_status(job) # doctest: +ELLIPSIS\n {'id': '1', 'created': '2...', 'finished': None, 'status': 'in-progress', 'uploaded': {'pending': ['b'], 'complete': ['A'], 'failed': []}}\n\n >>> job.commit(datetime.datetime.utcnow(), 'b')\n >>> format_job_status(job) # doctest: +ELLIPSIS\n {'id': '1', 'created': '2...', 'finished': '2...', 'status': 'complete', 'uploaded': {'pending': [], 'complete': ['A'], 'failed': ['b']}}\n\n >>> job.commit(datetime.datetime.utcnow(), 'a')\n >>> format_job_status(job) # doctest: +ELLIPSIS\n {'id': '1', 'created': '2...', 'finished': '2...', 'status': 'complete', 'uploaded': {'pending': [], 'complete': [], 'failed': ['a', 'b']}}\n\n >>> job.commit(datetime.datetime.utcnow(), 'a', 'A')\n >>> job.commit(datetime.datetime.utcnow(), 'b', 'B')\n >>> format_job_status(job) # doctest: +ELLIPSIS\n {'id': '1', 'created': '2...', 'finished': '2...', 'status': 'complete', 'uploaded': {'pending': [], 'complete': ['A', 'B'], 'failed': []}}\n \"\"\"\n pending = [reloc.url_old for reloc in filter(lambda r: r.is_pending, job.relocation)]\n failed = [reloc.url_old for reloc in filter(lambda r: r.is_failed, job.relocation)]\n complete = [reloc.url_new for reloc in filter(lambda r: r.is_stored, job.relocation)]\n\n if not pending:\n finished_time = _format_time(job.update_time)\n job_state = \"complete\"\n else:\n finished_time = None\n if complete or failed:\n job_state = 'in-progress'\n else:\n job_state = 'pending'\n\n status = {\n \"id\": _format_job_id(job.id),\n \"created\": _format_time(job.create_time),\n \"finished\": finished_time,\n \"status\": job_state,\n \"uploaded\": {\n \"pending\": pending,\n \"complete\": complete,\n \"failed\": failed\n }\n }\n\n return status\n\n\ndef format_uploaded_list(relocation: Iterable[RelocationRecord]) -> dict:\n \"\"\"\n >>> reolc = RelocationRecord('a')\n >>> reolc.commit(0)\n >>> format_uploaded_list([reolc])\n {'uploaded': []}\n\n >>> reolc.commit(1, 'A')\n >>> format_uploaded_list([reolc])\n {'uploaded': ['A']}\n \"\"\"\n uploaded = {\n \"uploaded\": []\n }\n\n for reloc in filter(lambda r: r.is_stored, relocation):\n uploaded['uploaded'].append(reloc.url_new)\n\n return uploaded\n\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n","sub_path":"response_format.py","file_name":"response_format.py","file_ext":"py","file_size_in_byte":3413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"420471645","text":"from Graph import State,Action,MarkovDecisionGraph\nimport pprint\n\nclass MDP(object):\n \n def __init__(self,data):\n\n self.data=data\n self.actions_per_states={}\n self.utilities={}\n for key in self.data.keys():\n self.actions_per_states[key]=key.getActions()\n self.utilities[key]=0.0\n\n def value_iteration(self,iterations,discount_factor):\n\n for i in range(iterations):\n \n for key in self.utilities.keys():\n \n transition_state_utilities=[]\n\n for i in self.actions_per_states[key]:\n \n transition_state_utilities.append(self.utilities[i[1]])\n \n if len(transition_state_utilities)>0:\n self.utilities[key]=key.getReward()+discount_factor*max(transition_state_utilities)\n else:\n self.utilities[key]=key.getReward()\n\ndef createAgent():\n \n start=State(0,True)\n\n empty1=State(0,False)\n empty2=State(0,False)\n empty3=State(0,False)\n\n bad1=State(-100,False)\n bad2=State(-100,False)\n bad3=State(-100,False)\n bad4=State(-100,False)\n bad5=State(-100,False)\n bad6=State(-100,False)\n\n\n goal10=State(100,False)\n goal1=State(10,False)\n goal10000=State(300,False)\n\n graph=MarkovDecisionGraph(start)\n\n graph.addAction(start,goal1,\"left\")\n graph.addAction(start,empty1,\"right\")\n\n graph.addAction(start,bad1,\"up\")\n graph.addAction(bad1,start,\"down\")\n\n graph.addAction(start,bad2,\"down\")\n graph.addAction(bad2,start,\"up\")\n\n \n graph.addAction(empty1,start,\"left\")\n graph.addAction(empty1,empty2,\"right\")\n graph.addAction(empty1,bad3,\"up\")\n graph.addAction(bad3,empty1,\"down\")\n\n graph.addAction(empty1,bad4,\"down\")\n\n graph.addAction(bad4,empty1,\"up\")\n\n\n graph.addAction(empty2,goal10,\"right\")\n\n graph.addAction(empty2,empty1,\"left\")\n graph.addAction(empty2,bad5,\"up\")\n graph.addAction(bad5,empty2,\"down\")\n\n graph.addAction(empty2,bad6,\"down\")\n graph.addAction(bad6,empty2,\"up\")\n\n graph.addAction(bad5,empty3,\"up\")\n graph.addAction(empty3,bad5,\"down\")\n\n\n graph.addAction(empty3,goal10000,\"right\")\n \"\"\"\n start=State(0,True)\n goal1=State(10,False)\n empty1=State(0,False)\n empty2=State(0,False)\n empty3=State(0,False)\n goal2=State(100,False)\n bad1=State(-100,False)\n\n graph=MarkovDecisionGraph(start)\n\n graph.addAction(start,goal1,\"left\")\n graph.addAction(start,empty1,\"right\")\n graph.addAction(start,bad1,\"down\")\n graph.addAction(bad1,start,\"up\")\n\n graph.addAction(empty1,start,\"left\")\n graph.addAction(empty1,empty2,\"right\")\n\n\n graph.addAction(empty2,empty1,\"left\")\n graph.addAction(empty2,empty3,\"right\")\n\n graph.addAction(empty3,empty2,\"left\")\n graph.addAction(empty3,goal2,\"right\")\n\n\n \"\"\"\n\n pprint.pprint(graph.coordinates)\n\n graph.Normalize()\n print(\"\")\n\n pprint.pprint(graph.coordinates)\n\n #graph.Gridify()\n\n print(\"\")\n\n pprint.pprint(graph.coordinates)\n\n mdp=MDP(graph.coordinates)\n\n mdp.value_iteration(1000,0.99)\n\n for key in mdp.actions_per_states.keys():\n print(key,key.getReward(),mdp.actions_per_states[key])\n print(\"\")\n \n \n pprint.pprint(mdp.utilities)\n \"\"\"\n game=Game(graph.coordinates)\n game.runGame()\n \"\"\"\n return graph.coordinates,mdp.utilities, mdp.actions_per_states\n\n\nif __name__ == '__main__':\n main()\n \n","sub_path":"Markov Decision Process Project/MarkovDecisionProcess.py","file_name":"MarkovDecisionProcess.py","file_ext":"py","file_size_in_byte":3489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"114697879","text":"# HG Quick Gator Paste Script\n# Uses http://hgfix.net/paste/\n# Revised 8-2015\n# \n# Takes the contents of a SOURCE below, creates a new pastebin page \n# containing this data, then outputs the URL to this page to the\n# DESTINATION below. Keyboard buffer output can be suppressed by\n# setting KEY_BUFF to False\n\n#*****************************INSTRUCTIONS******************************\n#\n#\t1. Paste the contents of this file into a new AutoKey script record\n#\n#\t2. Assign an autokey combination (i.e. WindowKey+C)\n#\n#\t3. Select the configuration for this particular event\n#\n#\t(Hint : You can set up multiple autokeys, each with a \n#\tunique keystroke combination and configuration)\n#\n#*******************************CONFIG**********************************\n#\n#\tRemove the \"#\" before the SOURCE/DESTINATION you wish to use.\n#\tIf multiple lines are uncommented, the last option\n#\twill be used\n#\n#\t\t!!! Note the options will raise an error if\n#\t\t!!! text selection fails (i.e. terminals, etc)\n#\t\t!!! or the SOURCE contains no data\n\nSOURCE = 'selection'\t\t# Grab highlighted text\n#SOURCE = 'mouse'\t\t\t# Grab selection from mouse clipboard\n#SOURCE = 'clipboard'\t\t# Grab selection from system clipboard\n\nDESTINATION = 'mouse'\t\t# Sends output to the mouse (middle click) buffer\n#DESTINATION = 'clipboard'\t# Sends output directly to the clipboard\n#DESTINATION = 'dialog'\t\t# Sends output to a dialog window\n\nKEY_BUFF = False\t\n# Sends output to the keyboard buffer if True, set to False to suppress\n# (Note : This is in addition to the DESTINATION set above)\n\nDEBUG = False # Change to turn off error handling\n\n#*****************************END CONFIG********************************\n\n#***********************************************************************\n#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \n#\t\t!!DO NOT TOUCH ANYTHING BELOW THIS BOX!!\t\t \n#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \n#***********************************************************************\n\nimport re\nimport urllib.parse\nimport urllib.request\nimport sys, os\nfrom subprocess import Popen, PIPE\n\ndef do_encode(post_arguments):\n\n\t# Encode It Properly\n\turi = urllib.parse.urlencode(post_arguments)\n\turi = uri.encode('utf-8') # data should be bytes\n\t\n\treturn urllib.request.Request('http://hgfix.net/paste/api/create', uri)\n\ndef do_post(request):\n\n\t# Make a POST Request\n\tresponse = urllib.request.urlopen(request)\n\t\n\t# Read the Response\n\tpaste_url = response.read().decode(\"utf-8\").rstrip() \n\tmatch = re.search(r\"http://hgfix.net/paste/view/(.+)\", paste_url)\n\tpaste_url = \"http://hgfix.net/paste/view/raw/\" + match.group(1)\n\t\n\treturn paste_url\n\ntry:\n\t\n\t# Grab the clipboard contents\n\tif SOURCE=='mouse':\n\t\tcontents = clipboard.get_selection()\n\t\t\n\telif SOURCE=='clipboard':\n\t\tcontents = clipboard.get_clipboard()\n\t\t\n\telif SOURCE=='selection':\n\t\tcontents = subprocess.check_output(\"xsel\", universal_newlines=True)\n\n\t# Pair Up the URI Query String\n\tpost_arguments = {'text' : contents, 'private': '', 'expires': '30', 'lang': 'text'}\n\t\n\t# Create paste and catch returned URL\n\tret_url = do_post(do_encode(post_arguments))\n\t\n\t# Send to keyboard buffer first, since dialogs kill it\n\tif KEY_BUFF:\n\t\tkeyboard.send_keys(ret_url)\n\t\n\t# Parse config variable\n\tif DESTINATION == 'dialog':\n\t\tretCode, inputText = dialog.input_dialog(\"HG Paste Link\", \n\t\t\t\t\t\t\t\t\t\t\t\"Returned URL:\", ret_url)\n\n\telif DESTINATION == 'clipboard':\n\t\tclipboard.fill_clipboard(ret_url)\n\t\t\n\telif DESTINATION == 'mouse':\n\t\tp = Popen(['xsel', '-pi'], stdin=PIPE)\n\t\tp.communicate(bytes(ret_url, 'UTF-8'))\n\t\nexcept Exception as x:\n\tif DEBUG:\n\t\traise\n\telse:\n\t\tdialog.info_dialog(\"Error\", str(x))\n\t\tsys.exit(0)\n","sub_path":"HGPaste/broken_script.py","file_name":"broken_script.py","file_ext":"py","file_size_in_byte":3579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"179027562","text":"import os\nimport time\nimport string\nimport pickle\nimport json\nimport re\nfrom operator import itemgetter\n\nfrom nltk.corpus import stopwords as sw\nfrom nltk.corpus import wordnet as wn\nfrom nltk import wordpunct_tokenize\nfrom nltk import WordNetLemmatizer\nfrom nltk import sent_tokenize\nfrom nltk import pos_tag\n\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.svm import SVC, LinearSVC\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.linear_model import LogisticRegression\n\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom sklearn.metrics import classification_report as clsr\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n#from sklearn.cross_validation import train_test_split as tts\nfrom sklearn.model_selection import train_test_split as tts\n\nimport sys\nreload(sys)\nsys.path \n\n# Notes1.- Other is positive(1) - Aurora is negative(0)\n\n# Notes2.- The underlying C implementation uses a random number generator to select features when fitting the model. It is thus not uncommon to have slightly different results for the same input data\n\nhttp_re = re.compile(r'\\s+http://[^\\s]*')\nremove_ellipsis_re = re.compile(r'\\.\\.\\.')\nat_sign_re = re.compile(r'\\@\\S+')\npunct_re = re.compile(r\"[\\\"'\\[\\],.:;()\\-&!]\")\nprice_re = re.compile(r\"\\d+\\.\\d\\d\")\nnumber_re = re.compile(r\"\\d+\")\n\n# converts to lower case and clean up the text\ndef normalize_tweet(tweet):\n t = tweet.lower()\n #t = re.sub(price_re, 'PRICE', t)\n t = re.sub(remove_ellipsis_re, '', t)\n t = re.sub(http_re, ' LINK', t)\n t = re.sub(punct_re, '', t)\n t = re.sub(at_sign_re, '@', t)\n t = re.sub(number_re, 'NUM', t)\n #t = re.sub(r\"\\n\", \" \", t) # remove newlines from text\n t = re.sub(r'[^\\w]', ' ', t)\n return t\n\n\ndef identity(arg):\n \"\"\"\n Simple identity function works as a passthrough.\n \"\"\"\n return arg\n\nclass NLTKPreprocessor(BaseEstimator, TransformerMixin):\n \"\"\"\n Transforms input data by using NLTK tokenization, lemmatization, and\n other normalization and filtering techniques.\n \"\"\"\n\n def __init__(self, stopwords=None, punct=None, lower=True, strip=True):\n \"\"\"\n Instantiates the preprocessor, which make load corpora, models, or do\n other time-intenstive NLTK data loading.\n \"\"\"\n self.lower = lower\n self.strip = strip\n self.stopwords = set(stopwords) if stopwords else set(sw.words('english'))\n self.punct = set(punct) if punct else set(string.punctuation)\n self.lemmatizer = WordNetLemmatizer()\n\n def fit(self, X, y=None):\n \"\"\"\n Fit simply returns self, no other information is needed.\n \"\"\"\n return self\n\n def inverse_transform(self, X):\n \"\"\"\n No inverse transformation\n \"\"\"\n return X\n\n def transform(self, X):\n \"\"\"\n Actually runs the preprocessing on each document.\n \"\"\"\n return [\n list(self.tokenize(doc)) for doc in X\n ]\n\n def tokenize(self, document):\n \"\"\"\n Returns a normalized, lemmatized list of tokens from a document by\n applying segmentation (breaking into sentences), then word/punctuation\n tokenization, and finally part of speech tagging. It uses the part of\n speech tags to look up the lemma in WordNet, and returns the lowercase\n version of all the words, removing stopwords and punctuation.\n \"\"\"\n # Break the document into sentences\n\t#print(\"Document is %s\" % document)\n\n try:\n sents = sent_tokenize(document)\n except ValueError:\n sents = \"ERROR\"\n if sents!= \"ERROR\":\n for sent in sents:\n try:\n sent = normalize_tweet(sent)\n for token, tag in pos_tag(wordpunct_tokenize(sent)):\n token = token.lower() if self.lower else token\n token = token.strip() if self.strip else token\n token = token.strip('_') if self.strip else token\n token = token.strip('*') if self.strip else token\n token = token.rstrip('?:!.,;\"!@')\n if token in self.stopwords or all(char in self.punct for char in token):\n continue\n lemma = self.lemmatize(token, tag)\n yield lemma\n except ValueError:\n pass\n\n def lemmatize(self, token, tag):\n \"\"\"\n Converts the Penn Treebank tag to a WordNet POS tag, then uses that\n tag to perform much more accurate WordNet lemmatization.\n \"\"\"\n tag = {\n 'N': wn.NOUN,\n 'V': wn.VERB,\n 'R': wn.ADV,\n 'J': wn.ADJ\n }.get(tag[0], wn.NOUN)\n\n return self.lemmatizer.lemmatize(token, tag)\n\n\n","sub_path":"Tweet_Classification_Auroras/Solution_Supervised_SVM/svm_model/classification_module.py","file_name":"classification_module.py","file_ext":"py","file_size_in_byte":5054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"490848591","text":"#a 4 tem a mesma pergunta que a 3\ndef aumentoSalario(VP, S):\n converPorcent = VP / 100\n valorAumento = S * converPorcent\n aumentoS = S + valorAumento\n return aumentoS\ndef main():\n S = float(input('Informe o salário: '))\n VP = int(input('Informe o valor de porcentagem de aumento que o salário vai ter: ')) \n print(S,'reais mais aumento de ',VP,'por cento =',aumentoSalario(VP, S),'reais') \n\nmain()\n","sub_path":"segundoModulo/PYTHON - DODO/0.4_list-f-c-retorno-c-parametro(TERMINADO)/4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"111061673","text":"import streamlit as st\nimport folium\nimport numpy as np\nimport pandas as pd\nfrom streamlit_folium import folium_static\n\ndef create_test_df():\n data = {\"id\": range(10000),\n \"year\": np.random.choice(range(2018, 2021), 10000),\n \"type\": np.random.choice([\"type_a\", \"type_b\", \"type_c\"], 10000),\n \"latitude\": np.random.uniform(low=10, high=20, size=10000),\n \"longitude\": np.random.uniform(low=10, high=20, size=10000)}\n\n # Respects order\n return pd.DataFrame(data, columns=[\"id\", \"year\", \"type\", \"latitude\", \"longitude\"])\n\n\ndef _plot_dot(point, map_element, color_col, radius=4, weight=1, color='black'):\n color_dict = {2018: \"blue\", 2019: \"orange\", 2020: \"red\"}\n\n folium.CircleMarker(location=[point[\"latitude\"], point[\"longitude\"]], radius=radius, weight=weight,\n color=color, fill=True,\n fill_color=color_dict[point[color_col]],\n fill_opacity=0.9,\n tooltip=f'id: {str(point[\"id\"])}'\n f' 'f'year: {str(point[\"year\"])}'\n f' 'f'type: {str(point[\"type\"])}',\n popup=f'id: {str(point[\"id\"])}'\n f' 'f'year: {str(point[\"year\"])}'\n f' 'f'type: {str(point[\"type\"])}'\n ).add_to(map_element)\n\n\ndef generate_map(df):\n map_element = folium.Map(location=[15, 15], zoom_start=6, tiles='cartodbpositron')\n\n df.apply(_plot_dot, axis=1, args=[map_element, \"year\"])\n\n return map_element\n\nif __name__ == \"__main__\":\n st.title(\"Complex Example\")\n\n df = create_test_df()\n\n option = st.selectbox('Select year?', df['year'].unique())\n st.write('You selected: ', option)\n\n dict_years = {}\n for year in df['year'].unique():\n dict_years[year] = generate_map(df[df[\"year\"] == year])\n\n folium_static(dict_years[option])\n\n","sub_path":"examples/streamlit_folium_complex_example.py","file_name":"streamlit_folium_complex_example.py","file_ext":"py","file_size_in_byte":2016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"200472322","text":"from datetime import datetime, timedelta\n\nfrom celery.utils.log import get_task_logger\nfrom pytz import utc\n\nfrom dataworkspace.apps.explorer.models import QueryLog, PlaygroundSQL\nfrom dataworkspace.cel import celery_app\n\n\nlogger = get_task_logger(__name__)\n\n\n@celery_app.task()\ndef truncate_querylogs(days):\n qs = QueryLog.objects.filter(run_at__lt=datetime.now() - timedelta(days=days))\n logger.info('Deleting %s QueryLog objects older than %s days.', qs.count, days)\n qs.delete()\n logger.info('Done deleting QueryLog objects.')\n\n\n@celery_app.task()\ndef cleanup_playground_sql_table():\n older_than = timedelta(days=14)\n oldest_date_to_retain = datetime.now(tz=utc) - older_than\n\n logger.info(\n \"Cleaning up Data Explorer PlaygroundSQL rows older than %s\",\n oldest_date_to_retain,\n )\n\n count = 0\n for play_sql in PlaygroundSQL.objects.filter(created_at__lte=oldest_date_to_retain):\n play_sql.delete()\n count += 1\n\n logger.info(\"Delete %s PlaygroundSQL rows\", count)\n","sub_path":"dataworkspace/dataworkspace/apps/explorer/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"210096284","text":"import pygame\nfrom block import Block, Vector, Colors, digits\nfrom random import randint\n\ndef check_click(mouse_pos, grid):\n for line in grid:\n for i in line:\n cond_min = mouse_pos[0] > i.x and mouse_pos[1] > i.y\n cond_max = mouse_pos[0] < i.x + i.size and mouse_pos[1] < i.y + i.size\n if cond_min and cond_max:\n if i.visible is False:\n i.color = Colors.active\n i.draw(W)\n print('Drawed №', i.__id__)\n i.visible = True\n return\n else:\n i.color = Colors.empty\n i.draw(W)\n print('Deleted №', i.__id__)\n i.visible = False\n return\ndef gen_grid(width, height):\n grid = []\n line = []\n coords = Vector(0,0)\n size = 1\n count = 0\n for h in range(height):\n coords.x = 0\n for w in range(width):\n block = Block(count, coords.x, coords.y)\n line.append(block)\n coords.x += size\n count += 1\n coords.y += size\n grid.append(line)\n return grid\ndef check_win(grid, win_num=0):\n for line in grid:\n for i in line:\n if bool(digits[win_num][i.__id__]) != i.visible:\n return False\n print('YOU WIN!')\n return True\n\n\nnum = int(input('Enter digit for drawing (0-3): '))\n\n\npygame.init()\nW = pygame.display.set_mode((300, 500))\npygame.display.set_caption(\"Plates\")\n\ngrid = gen_grid(3, 5)\nplay = True\n\nwhile play:\n pygame.time.delay(300)\n\n for e in pygame.event.get():\n if e.type == pygame.QUIT:\n play = False\n\n if e.type == pygame.MOUSEBUTTONDOWN:\n mouse_pos = e.pos\n # print(mouse_pos[0])\n check_click(mouse_pos, grid)\n check_win(grid, num)\n\n\n\n # for line in grid:\n # for i in line:\n # pass\n # i.draw(W)\n pygame.display.update()\n\n\npygame.quit()\n","sub_path":"__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":2028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"431834784","text":"from matplotlib import rc\nrc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})\nrc('text', usetex=True)\n\nfrom __future__ import print_function \nimport numpy as np \nimport matplotlib.pyplot as plt\nfrom scipy.spatial.distance import cdist\nfrom matplotlib.backends.backend_pdf import PdfPages\n\n\ndef softmax_stable(Z):\n \"\"\"\n Compute softmax values for each sets of scores in Z.\n each row of Z is a set of scores. \n \"\"\"\n e_Z = np.exp(Z - np.max(Z, axis = 1, keepdims = True))\n A = e_Z / e_Z.sum(axis = 1, keepdims = True)\n return A\n\ndef crossentropy_loss(Yhat, y):\n \"\"\"\n Yhat: a numpy array of shape (Npoints, nClasses) -- predicted output \n y: a numpy array of shape (Npoints) -- ground truth. We don't need to use \n the one-hot vector here since most of elements are zeros. When programming \n in numpy, we need to use the corresponding indexes only.\n \"\"\"\n id0 = range(Yhat.shape[0])\n return -np.mean(np.log(Yhat[id0, y]))\n\n\ndef mlp_init(d0, d1, d2):\n \"\"\" \n Initialize W1, b1, W2, b2 \n d0: dimension of input data \n d1: number of hidden unit \n d2: number of output unit = number of classes\n \"\"\"\n W1 = 0.01*np.random.randn(d0, d1)\n b1 = np.zeros(d1)\n W2 = 0.01*np.random.randn(d1, d2)\n b2 = np.zeros(d2)\n return (W1, b1, W2, b2)\n\ndef mlp_predict(X, W1, b1, W2, b2):\n \"\"\"\n Suppose that the network has been trained, predict class of new points. \n X: data matrix, each ROW is one data point.\n W1, b1, W2, b2: learned weight matrices and biases \n \"\"\"\n Z1 = X.dot(W1) + b1 # shape (N, d1)\n A1 = np.maximum(Z1, 0) # shape (N, d1)\n Z2 = A1.dot(W2) + b2 # shape (N, d2)\n return np.argmax(Z2, axis=1)\n\ndef mlp_fit(X, y, W1, b1, W2, b2, eta):\n loss_hist = []\n for i in xrange(10000):\n # feedforward \n Z1 = X.dot(W1) + b1 # shape (N, d1)\n A1 = np.maximum(Z1, 0) # shape (N, d1)\n Z2 = A1.dot(W2) + b2 # shape (N, d2)\n Yhat = softmax_stable(Z2) # shape (N, d2)\n \n if i %1000 == 0: # print loss after each 1000 iterations\n loss = crossentropy_loss(Yhat, y)\n print(\"iter %d, loss: %f\" %(i, loss))\n loss_hist.append(loss)\n\n # back propagation\n id0 = range(Yhat.shape[0])\n Yhat[id0, y] -=1 \n E2 = Yhat/N # shape (N, d2)\n dW2 = np.dot(A1.T, E2) # shape (d1, d2)\n db2 = np.sum(E2, axis = 0) # shape (d2,)\n E1 = np.dot(E2, W2.T) # shape (N, d1)\n E1[Z1 <= 0] = 0 # gradient of ReLU, shape (N, d1)\n dW1 = np.dot(X.T, E1) # shape (d0, d1)\n db1 = np.sum(E1, axis = 0) # shape (d1,)\n\n # Gradient Descent update\n W1 += -eta*dW1\n b1 += -eta*db1\n W2 += -eta*dW2\n b2 += -eta*db2\n return (W1, b1, W2, b2, loss_hist)\n\nd0 = 2\nd1 = h = 500 # size of hidden layer\nd2 = C = 3\neta = 1 # learning rate\n# initialize parameters randomly\n(W1, b1, W2, b2) = mlp_init(d0, d1, d2)\n(W1, b1, W2, b2, loss_hist) =mlp_fit(X, y, W1, b1, W2, b2, eta)\n\ny_pred = mlp_predict(X, W1, b1, W2, b2)\nacc = 100*np.mean(y_pred == y)\nprint('training accuracy: %.2f %%' % acc)","sub_path":"Basic-ML/multiplayer_neural_network/neural_network.py","file_name":"neural_network.py","file_ext":"py","file_size_in_byte":3184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"369996223","text":"import logging\n\nfrom .config import get_config_value, get_config_value_as_list\nfrom .validator import (JiraValidator, RegExpValidator, VersionsValidator)\n\nlog = logging.getLogger()\n\n\ndef validate_todos(todos, issue_pattern, version_pattern, version, versions):\n log.info('Validating %d todos.', len(todos))\n\n validators = []\n\n issue_validator = RegExpValidator(issue_pattern)\n validators.append(issue_validator)\n\n if get_config_value('jira_server', 'url'):\n jira_validator = JiraValidator(issue_pattern,\n get_config_value('jira_server', 'url'),\n get_config_value('jira_server', 'username'),\n get_config_value('jira_server', 'password'),\n get_config_value('jira_server', 'token'),\n get_config_value_as_list('statuses', 'all'),\n get_config_value('issue_filter', 'field'),\n get_config_value_as_list('issue_filter', 'values'))\n issue_validator.set_dependent_validator(jira_validator)\n\n if version_pattern is not None:\n version_validator = RegExpValidator(version_pattern)\n validators.append(version_validator)\n\n if versions is not None and version is not None:\n version_validator.set_dependent_validator(VersionsValidator(versions, version))\n\n invalid_todos = []\n amount_ignored = 0\n for todo in todos:\n validate_todo(validators, todo)\n if not todo.is_valid:\n invalid_todos.append(todo)\n amount_ignored += todo.is_ignored\n\n if not invalid_todos:\n log.info('All todos are fine.')\n return\n\n log.error('------------------------------------------------------------------------------')\n log.error('Found %d invalid todo(s) (%d of them ignored).', len(invalid_todos), amount_ignored)\n log.error('------------------------------------------------------------------------------')\n for invalid_todo in invalid_todos:\n invalid_todo.print()\n log.error('------------------------------------------------------------------------------')\n\n\ndef validate_todo(validators, todo):\n for validator in validators:\n if validator.validate(todo):\n return\n\n todo.mark_as_invalid('Todo is not conform to any validator.')\n","sub_path":"src/inspectortodo/todo_validation.py","file_name":"todo_validation.py","file_ext":"py","file_size_in_byte":2431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"148474368","text":"import sys\nimport numpy as np\nimport cv2\nfrom torch.utils import data\nimport torch\nimport glob\nimport random\nimport os\n\nclass MRLEyeDataset(data.Dataset):\n def __init__(self, data_dir, set_type='all', augmentation=True):\n self.EYE_IMAGE_SHAPE = (112, 112)\n self.data_dir = data_dir\n self.set_type = set_type\n assert self.set_type in ['train', 'val', 'all'], f'Set_type should belong to either \"train\"/\"val\"/\"all\" '\n # Train set belong to s0001 ---> s0025, val set belong to s0026->s0037, all set belong to s0001 --> s0037\n self.files = self.__load_files()\n\n def __load_files(self):\n files = []\n if self.set_type == \"train\":\n folder_indice = list(range(1, 26))\n elif self.set_type == \"val\":\n folder_indice = list(range(26, 38))\n else:\n folder_indice = list(range(1, 38))\n for i in folder_indice:\n files_part_i = glob.glob(f'{self.data_dir}/s{i:04}/*.png')\n files += files_part_i\n random.shuffle(files)\n print(f'Len files : {len(files)}')\n return files\n\n def __len__(self):\n return len(self.files)\n\n def __getitem__(self, index):\n f = self.files[index]\n # Eye image\n eye = cv2.imread(f)\n eye = cv2.resize(eye, self.EYE_IMAGE_SHAPE)\n # print(\"eye shape: \", eye.shape)\n # Label\n eyestate_label = int(os.path.basename(f).split(\"_\")[4])\n return eye, torch.FloatTensor([eyestate_label])\n\nif __name__ == \"__main__\":\n mrl = MLREyeDataset('data/mrleye')\n ","sub_path":"data/mrl.py","file_name":"mrl.py","file_ext":"py","file_size_in_byte":1579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"222539460","text":"class Solution(object):\n def minCostClimbingStairs(self, cost):\n \"\"\"\n :type cost: List[int]\n :rtype: int\n \"\"\"\n S = len(cost)\n cost += [0]\n for i in range(2, len(cost)):\n cost[i] = min(cost[i-1], cost[i-2]) + cost[i]\n return cost[-1]","sub_path":"leetcode/63A.py","file_name":"63A.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"343665871","text":"# coding=utf-8\nfrom steps_utils import *\n\n\ndef main():\n print(\"\")\n train, test = read_cifar10()\n print(\"\")\n normalize_set(train)\n normalize_set(test)\n print(\"\")\n centroids_size = 15\n num_centroids = 5\n centroids = generate_centroids_from_dataset(train, centroids_size, num_centroids)\n print(\"\")\n centroid_images = [centroid.reshape(15, 15, 3) for centroid in centroids]\n result = classify_with_ensemble_of_random_forest(train, test, centroid_images)\n print(\"\")\n print(result)\n\n\nif __name__ == \"__main__\":\n main()\n\n# RESULTS:\n# 36%\n","sub_path":"src/steps_n_k-s15-n5_erf.py","file_name":"steps_n_k-s15-n5_erf.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"223412381","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport os\nimport sys\nimport random\nimport json\nimport fcntl\nimport errno\nimport time\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras import backend as K\n\nclass ResultsCollector(tf.keras.callbacks.Callback):\n\n def __init__(self, results_dir, sess_name, data_type, model_id, params):\n super(ResultsCollector, self).__init__()\n\n assert( os.path.exists(results_dir) )\n results_dir = os.path.abspath(results_dir)\n\n self.results_dir = results_dir\n self.results_file = os.path.join(results_dir, \"results.json\")\n self.dtype_id = data_type\n self.model_id = model_id\n self.params_id = params\n self.sess_name = sess_name\n\n try:\n lock_fd = self.__get_lock()\n\n results = None\n curr_res_set = None\n\n if not os.path.exists(self.results_file):\n print(\"Creating results file at \" + self.results_file)\n\n # Results are organized as follows\n # SESS_NAME\n # '\n # '--> MODEL_ID\n # '\n # '--> PARAMS_SET\n # '\n # '--> DATA_TYPE\n\n results = {}\n results[self.sess_name] = {}\n\n curr_sess_set = results[self.sess_name]\n curr_sess_set[self.model_id] = {}\n curr_sess_set[self.model_id][self.params_id] = {}\n curr_sess_set[self.model_id][self.params_id][self.dtype_id] = {}\n\n curr_res_set = curr_sess_set[self.model_id] \\\n [self.params_id] \\\n [self.dtype_id]\n\n else:\n print(\"Making sure results file contains an entry for \"\n + \"[\" + self.sess_name + \"]\"\n + \"[\" + self.model_id + \"]\"\n + \"[\" + self.params_id + \"]\"\n + \"[\" + self.dtype_id + \"]\")\n\n with open(self.results_file, \"r\") as results_FD:\n results = json.load(results_FD)\n\n assert( results is not None )\n\n sess_set = results.get(self.sess_name, {})\n model_id_set = sess_set.get(self.model_id, {})\n params_set = model_id_set.get(self.params_id, {})\n data_type_set = params_set.get(self.dtype_id, {})\n\n params_set[self.dtype_id] = data_type_set\n model_id_set[self.params_id] = params_set\n sess_set[self.model_id] = model_id_set\n results[self.sess_name] = sess_set\n\n curr_res_set = data_type_set\n\n assert( results is not None )\n assert( curr_res_set is not None )\n curr_res_set['epoch'] = -1\n\n # print(json.dumps(results, indent=2), \"\\n\")\n\n # Now, write back the updated results\n with open(self.results_file, \"w\") as results_FD:\n json.dump(results, results_FD, indent=2)\n\n finally:\n self.__rel_lock(lock_fd)\n \n\n\n def __get_lock(self):\n lock_file = os.path.join(self.results_dir, \"results.lock\")\n lock_fd = open(lock_file, \"w\")\n\n count = 0\n\n while True:\n try:\n fcntl.flock(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)\n break\n except IOError as e:\n # raise on unrelated IOErrors\n if e.errno != errno.EAGAIN:\n raise\n else:\n # Raise an exception if waiting for > 30sec\n if count > 300:\n raise Exception(\"File not accessible for 30secs\")\n else:\n time.sleep(0.1)\n\n return lock_fd\n\n def __rel_lock(self, lock_fd):\n fcntl.flock(lock_fd, fcntl.LOCK_UN)\n lock_fd.close()\n\n\n def on_epoch_end(self, epoch, logs=None):\n try:\n lock_fd = self.__get_lock()\n \n results = None\n \n with open(self.results_file, \"r\") as results_FD:\n results = json.load(results_FD)\n \n assert( results is not None)\n \n sess_set = results[self.sess_name]\n curr_res_set = sess_set[self.model_id][self.params_id][self.dtype_id]\n\n new_val_loss = float(\"{:.5f}\".format(logs['val_loss']))\n\n # Update the model's attributes if we have a better val_loss\n if ( ('val_loss' not in curr_res_set.keys())\n or (new_val_loss <= curr_res_set['val_loss'])\n ):\n print(\"Updating results.\")\n for key in logs.keys():\n curr_res_set[key] = float(\"{:.5f}\".format(logs[key]))\n \n curr_res_set['epoch'] = epoch\n with open(self.results_file, \"w\") as results_FD:\n json.dump(results, results_FD, indent=2)\n \n finally:\n self.__rel_lock(lock_fd)\n\n#\n# Prior to tensorflow 1.14 there is discrepency between the\n# naming convention for learning rate in tensorflow and keras\n#\n# Because of this, LearningRateScheduler cannot be used with\n# tf.train.optimizers\n#\n# The following class is a workaround suggested on the Keras github\n#\n# https://github.com/tensorflow/tensorflow/issues/20999\n#\nclass MyLearningRateScheduler(tf.keras.callbacks.Callback):\n \"\"\"Learning rate scheduler.\n\n Arguments:\n schedule: a function that takes an epoch index as input\n (integer, indexed from 0) and current learning rate\n and returns a new learning rate as output (float).\n verbose: int. 0: quiet, 1: update messages.\n \"\"\"\n\n def __init__(self, schedule, verbose=0):\n super(MyLearningRateScheduler, self).__init__()\n self.schedule = schedule\n self.verbose = verbose\n\n def on_epoch_begin(self, epoch, logs=None):\n optimizer = self.model.optimizer\n\n if hasattr(optimizer, 'optimizer'):\n optimizer = optimizer.optimizer\n\n\n if not hasattr(optimizer, '_lr'):\n raise ValueError('Optimizer must have a \"_lr\" attribute.')\n\n # if not hasattr(optimizer, '_lr_t'):\n # raise ValueError('Optimizer must have a \"_lr_t\" attribute.')\n\n lr = float(K.get_value(optimizer._lr))\n print(\"Curr_lr = \", lr)\n\n try: # new API\n lr = self.schedule(epoch, lr)\n except TypeError: # old API for backward compatibility\n lr = self.schedule(epoch)\n\n if not isinstance(lr, (float, np.float32, np.float64)):\n raise ValueError('The output of the \"schedule\" function '\n 'should be float.')\n\n K.set_value(optimizer._lr, lr)\n # K.set_value(optimizer._lr_t, lr)\n # tf.assign(optimizer._lr_t, lr)\n\n if self.verbose > 0:\n print('\\nEpoch %05d: LearningRateScheduler setting learning '\n 'rate to %s.' % (epoch + 1, lr))\n\n def on_epoch_end(self, epoch, logs=None):\n logs = logs or {}\n\n optimizer = self.model.optimizer\n if hasattr(optimizer, 'optimizer'):\n optimizer = optimizer.optimizer\n\n logs['lr'] = K.get_value(optimizer._lr)\n\n\nif __name__ == \"__main__\":\n res_dir = os.path.abspath(\"./results\")\n if not os.path.exists(res_dir):\n os.makedirs(res_dir)\n\n data_types = [\"3D_DATA\", \"3D_DATA_low_q\", \"3D_DATA_mixed\"]\n model_ids = [\"unet3D_dice\", \"unet3D_ce\"]\n param_sets = [\"params_1e-5_2L\", \"params_1e-3_3L_L2\", \"params_9e-4_3L_L2\"]\n\n sess_names = [\"OOP\", \"regulaize\", \"dropout\"]\n \n for model_id in model_ids:\n sess_name = sess_names[random.randint(0,2)]\n\n for params in param_sets:\n for data_type in data_types:\n # print(model_id, params, data_type)\n results = ResultsCollector(res_dir, sess_name, data_type, model_id, params)\n \n logs = {}\n logs['loss'] = random.random()\n logs['dice_coef'] = random.random()\n logs['val_loss'] = random.random()\n logs['val_dice_coef'] = random.random()\n \n results.on_epoch_end(random.randint(0, 10), logs)\n","sub_path":"callbacks.py","file_name":"callbacks.py","file_ext":"py","file_size_in_byte":7543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"409306753","text":"from unittest import TestCase\n\nfrom models.field import Field\nfrom models.predator import Predator\nfrom models.prey import Prey\nfrom models.state import State\n\n\n__author__ = 'bas'\n\n\nclass TestState(TestCase):\n def setUp(self):\n self.field = Field(11, 11)\n predators = [Predator((0, 0)), Predator((0, 10)), Predator((10, 0))]\n prey = Prey((5, 5))\n for pred in predators:\n self.field.add_player(pred)\n self.field.add_player(prey)\n\n def test_state_from_field(self):\n state = State.state_from_field(self.field)\n self.assertEqual(state.relative_distances, [(5, 5), (5, -5), (-5, 5)])\n\n def test_terminal_functions(self):\n state = State.state_from_field(self.field)\n self.assertFalse(state.is_terminal())\n self.assertFalse(state.predators_have_collided())\n self.assertFalse(state.prey_is_caught())\n\n # Move prey to location of first predator\n self.field.get_prey().location = (0, 0)\n state = State.state_from_field(self.field)\n self.assertTrue(state.is_terminal())\n self.assertFalse(state.predators_have_collided())\n self.assertTrue(state.prey_is_caught())\n\n # Move predator 1 to location of last predator\n self.field.get_predators()[0].location = (10, 0)\n state = State.state_from_field(self.field)\n self.assertTrue(state.is_terminal())\n self.assertTrue(state.predators_have_collided())\n self.assertFalse(state.prey_is_caught())\n\n def test_all_states(self):\n all_states = State.all_states(self.field)\n self.assertEqual(len(all_states), 1771561)\n\n def test_all_states_without_terminal(self):\n states = State.all_states_without_terminal(self.field)\n self.assertEqual(len(states), 1685040)","sub_path":"models/test_state.py","file_name":"test_state.py","file_ext":"py","file_size_in_byte":1796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"226040533","text":"\"\"\"\nPlayer lister example client\n\nLogs in and prints the player list\n\"\"\"\n\nfrom __future__ import print_function\nfrom quarry.net.client import ClientFactory, ClientProtocol\nfrom quarry.mojang.profile import Profile\n\n\nclass PlayerListProtocol(ClientProtocol):\n def setup(self):\n self.players = {}\n\n def packet_player_list_item(self, buff):\n # 1.7.x\n if self.protocol_version <= 5:\n p_player_name = buff.unpack_string()\n p_online = buff.unpack('?')\n p_ping = buff.unpack('h')\n\n if p_online:\n self.players[p_player_name] = {\n 'name': p_player_name,\n 'ping': p_ping\n }\n elif p_player_name in self.players:\n del self.players[p_player_name]\n # 1.8.x\n else:\n p_action = buff.unpack_varint()\n p_count = buff.unpack_varint()\n for i in range(p_count):\n p_uuid = buff.unpack_uuid()\n if p_action == 0: # ADD_PLAYER\n p_player_name = buff.unpack_string()\n p_properties_count = buff.unpack_varint()\n p_properties = {}\n for j in range(p_properties_count):\n p_property_name = buff.unpack_string()\n p_property_value = buff.unpack_string()\n p_property_is_signed = buff.unpack('?')\n if p_property_is_signed:\n p_property_signature = buff.unpack_string()\n\n p_properties[p_property_name] = p_property_value\n p_gamemode = buff.unpack_varint()\n p_ping = buff.unpack_varint()\n p_has_display_name = buff.unpack('?')\n if p_has_display_name:\n p_display_name = buff.unpack_chat()\n else:\n p_display_name = None\n\n self.players[p_uuid] = {\n 'name': p_player_name,\n 'properties': p_properties,\n 'gamemode': p_gamemode,\n 'ping': p_ping,\n 'display_name': p_display_name\n }\n\n elif p_action == 1: # UPDATE_GAMEMODE\n p_gamemode = buff.unpack_varint()\n\n if p_uuid in self.players:\n self.players[p_uuid]['gamemode'] = p_gamemode\n elif p_action == 2: # UPDATE_LATENCY\n p_ping = buff.unpack_varint()\n\n if p_uuid in self.players:\n self.players[p_uuid]['ping'] = p_ping\n elif p_action == 3: # UPDATE_DISPLAY_NAME\n p_has_display_name = buff.unpack('?')\n if p_has_display_name:\n p_display_name = buff.unpack_chat()\n else:\n p_display_name = None\n\n if p_uuid in self.players:\n self.players[p_uuid]['display_name'] = p_display_name\n elif p_action == 4: # REMOVE_PLAYER\n if p_uuid in self.players:\n del self.players[p_uuid]\n\n def packet_player_position_and_look(self, buff):\n buff.discard()\n\n # convert self.players into a more readable format\n printable_players = []\n for data in self.players.values():\n printable_players.append((data['name'], data['ping']))\n\n for username, ping in sorted(printable_players):\n self.logger.info(\"%4sms %s\" % (ping, username))\n\n self.factory.stop()\n\n\nclass PlayerListFactory(ClientFactory):\n protocol = PlayerListProtocol\n\n\ndef main(args):\n # Parse options\n import optparse\n parser = optparse.OptionParser(\n usage=\"usage: %prog \"\n \" \")\n (options, args) = parser.parse_args(args)\n\n if len(args) != 4:\n return parser.print_usage()\n\n host, port, username, password = args\n\n # Create profile\n profile = Profile()\n\n # Create factory\n factory = PlayerListFactory()\n factory.profile = profile\n\n # Log in and connect\n deferred = profile.login(username, password)\n deferred.addCallbacks(\n lambda data: factory.connect(host, int(port)),\n lambda err: print(\"login failed:\", err.value))\n factory.run()\n\n\nif __name__ == \"__main__\":\n import sys\n main(sys.argv[1:])","sub_path":"examples/client_player_list.py","file_name":"client_player_list.py","file_ext":"py","file_size_in_byte":4571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"212719516","text":"import sklearn.metrics\nfrom sklearn.metrics import log_loss\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\nimport pandas as pd\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout\nfrom sklearn.feature_selection import RFE\nimport tensorflow as tf\n\n# Load data\ntrain = pd.read_csv('train.csv')\ntest = pd.read_csv('test.csv')\ndf = pd.concat([train, test])\n\ncheck = df.head(1)\n# Define our features and target\nfeatures = list(set(train.columns) - set(['Friends', 'ID']))\ntarget = 'Friends'\n\n# Encode our categorical data\ncategorical = ['Person A', 'Person B', 'Interaction Type', 'Moon Phase During Interaction']\nle = preprocessing.LabelEncoder()\n\nfor feature in categorical:\n df[feature] = le.fit_transform(df[feature])\n\n# Split data\nX = df[df[target].notnull()]\ny = df[df[target].isnull()]\nX[target] = X[target].astype(int)\n\nxtr, xte, ytr, yte = train_test_split(X[features], X[target], test_size=0.5, shuffle = False, random_state=False)\nxtr, validX, ytr, validY = train_test_split(xtr, ytr, test_size=0.5, shuffle = False, random_state= False)\n\nresults = []\nepochs = [10,20,30]\nbatches = [10,20,30]\n\n\ndef Hypereval(model):\n # evaluate the model\n bestAcc = 0\n bestEpoch = 0\n bestBatch = 0\n for batch in batches:\n for epoch in epochs:\n model.fit(xtr, ytr, epochs=epoch, batch_size=batch)\n scores = model.evaluate(validX, validY)\n for i in range(len(scores)):\n print(\"\\n%s: %f%%\" % (model.metrics_names[i], scores[i]))\n if scores[1] > bestAcc:\n bestAcc = scores[1]\n bestEpoch = epoch\n bestBatch = batch\n\n print(\"Best Acc \", bestAcc)\n print(\"Best Epoch \", bestEpoch)\n print(\"Best Batch \", bestBatch)\n return bestEpoch, bestBatch\n\n\n\ndef findRFE():\n labels = []\n acc = []\n filteredFeat = []\n\n for i in range(6):\n model = sklearn.linear_model.LogisticRegression()\n\n rfe = RFE(model, i+1)\n rfe = rfe.fit(xtr, ytr)\n\n print(\"\\n\", \"rfe\", i+1)\n print(rfe.support_)\n labels.append(rfe.support_)\n print(rfe.score(xte, yte))\n acc.append(rfe.score(xte, yte))\n\n # prob = rfe.predict_proba(xte)\n # loss1 = log_loss(yte, prob)\n #\n # print(\"Loss is \", loss1, \"\\n\")\n\n labels = np.asarray(labels)\n acc = np.asarray(acc)\n bestacc = np.argmax(acc)\n\n bestLabel = labels[bestacc]\n\n if bestLabel[0]:\n filteredFeat.append('Person A')\n if bestLabel[1]:\n filteredFeat.append('Person B')\n if bestLabel[2]:\n filteredFeat.append('Years of Knowing')\n if bestLabel[3]:\n filteredFeat.append('Interaction Duration')\n if bestLabel[4]:\n filteredFeat.append('Interaction Type')\n if bestLabel[5]:\n filteredFeat.append('Moon Phase During Interaction')\n return filteredFeat\n\nfiltFeat = findRFE()\n\n\n\nxtr, xte, ytr, yte = train_test_split(X[filtFeat], X[target], test_size=0.5, shuffle = False, random_state=False)\nxtr, validX, ytr, validY = train_test_split(xtr, ytr, test_size=0.5, shuffle = False, random_state= False)\n\nmodel1 = Sequential()\nmodel1.add(Dense(1, activation='sigmoid', input_dim=len(filtFeat)))\nmodel1.compile(optimizer='SGD',\n loss='binary_crossentropy',\n metrics=['accuracy'])\n\n\nbestEpoch, bestBatch = Hypereval(model1)\nmodel1.fit(xte, yte, epochs=bestEpoch, batch_size=bestBatch )\nyhatSubmit = np.around(model1.predict(y[filtFeat]))\n\nscores = model1.evaluate(xte, yte)\n\nfor i in range(len(scores)):\n print(\"\\nFinal %s: %f%%\" % (model1.metrics_names[i], scores[i]))\n\nprint(filtFeat)\nyhatSubmit = yhatSubmit.astype(int)\nprint(yhatSubmit)\n\n\nids = list(range(1, yhatSubmit.shape[0] + 1))\ndf = pd.DataFrame(data={'ID': ids, 'Friends': yhatSubmit.flatten()})\ndf.to_csv('deep_answerOrigRFE.csv', index=False)\n","sub_path":"deeplearningRFEOrig.py","file_name":"deeplearningRFEOrig.py","file_ext":"py","file_size_in_byte":3875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"131242265","text":"import requests\n\n\ndef download(url, params=None, retries=3):\n\n try:\n response = requests.get(url, params=params, headers=headers)\n except requests.exceptions.HTTPError as e:\n if 500 <= requests.status_codes < 600 and retries > 0:\n return download(url, params, retries - 1)\n else:\n print(requests.status_codes)\n print(requests.reason)\n print(requests.headers)\n return response\n\n\nurl = 'https://www.google.com/search'\n\nheaders = {\n \"user-agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36\"\n}\n\nresult = download(url, params={\"q\": \"파이썬\"})\n\nresult.url\nresult.content.decode('utf-8')\n","sub_path":"crawler/day02/code/web_crawler_2.py","file_name":"web_crawler_2.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"401071450","text":"#!/usr/bin/env python\n\n# --------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# --------------------------------------------------------------------------------------------\n\n\"\"\"\nExample to show managing rule entities under a ServiceBus Subscription, including\n - Create a rule\n - Create a rule with sql filter\n - Get rule properties and runtime information\n - Update a rule\n - Delete a rule\n - List rules under the given ServiceBus Subscription\n\"\"\"\n\nimport os\nimport uuid\nfrom azure.servicebus.management import (\n ServiceBusAdministrationClient,\n SqlRuleFilter\n)\n\nCONNECTION_STR = os.environ['SERVICEBUS_CONNECTION_STR']\nTOPIC_NAME = os.environ['SERVICEBUS_TOPIC_NAME']\nSUBSCRIPTION_NAME = os.environ['SERVICEBUS_SUBSCRIPTION_NAME']\nRULE_NAME = \"sb_mgmt_rule\" + str(uuid.uuid4())\nRULE_WITH_SQL_FILTER_NAME = \"sb_sql_rule\" + str(uuid.uuid4())\n\n\ndef create_rule(servicebus_mgmt_client):\n print(\"-- Create Rule\")\n servicebus_mgmt_client.create_rule(TOPIC_NAME, SUBSCRIPTION_NAME, RULE_NAME)\n print(\"Rule {} is created.\".format(RULE_NAME))\n print(\"\")\n\n print(\"-- Create Rule with SQL Filter\")\n sql_filter_parametrized = SqlRuleFilter(\n \"property1 = @param1 AND property2 = @param2\",\n parameters={\n \"@param1\": \"value\",\n \"@param2\": 1\n }\n )\n servicebus_mgmt_client.create_rule(TOPIC_NAME, SUBSCRIPTION_NAME, RULE_WITH_SQL_FILTER_NAME, filter=sql_filter_parametrized)\n print(\"Rule {} is created.\".format(RULE_WITH_SQL_FILTER_NAME))\n print(\"\")\n\n\ndef delete_rule(servicebus_mgmt_client):\n print(\"-- Delete Rule\")\n servicebus_mgmt_client.delete_rule(TOPIC_NAME, SUBSCRIPTION_NAME, RULE_NAME)\n print(\"Rule {} is deleted.\".format(RULE_NAME))\n servicebus_mgmt_client.delete_rule(TOPIC_NAME, SUBSCRIPTION_NAME, RULE_WITH_SQL_FILTER_NAME)\n print(\"Rule {} is deleted.\".format(RULE_WITH_SQL_FILTER_NAME))\n print(\"\")\n\n\ndef list_rules(servicebus_mgmt_client):\n print(\"-- List Rules\")\n for rule_properties in servicebus_mgmt_client.list_rules(TOPIC_NAME, SUBSCRIPTION_NAME):\n print(\"Rule Name:\", rule_properties.name)\n print(\"\")\n\n\ndef get_and_update_rule(servicebus_mgmt_client):\n print(\"-- Get and Update Rule\")\n rule_properties = servicebus_mgmt_client.get_rule(TOPIC_NAME, SUBSCRIPTION_NAME, RULE_NAME)\n print(\"Rule Name:\", rule_properties.name)\n print(\"Please refer to RuleProperties for complete available properties.\")\n print(\"\")\n\n # update by updating the properties in the model\n rule_properties.filter = SqlRuleFilter(\n \"property1 = @param1 AND property2 = @param2\",\n parameters={\n \"@param1\": \"value2\",\n \"@param2\": 2\n }\n )\n servicebus_mgmt_client.update_rule(TOPIC_NAME, SUBSCRIPTION_NAME, rule_properties)\n\n # update by passing keyword arguments\n rule_properties = servicebus_mgmt_client.get_rule(TOPIC_NAME, SUBSCRIPTION_NAME, RULE_NAME)\n servicebus_mgmt_client.update_rule(\n TOPIC_NAME,\n SUBSCRIPTION_NAME,\n rule_properties,\n filter=SqlRuleFilter(\n \"property1 = @param1 AND property2 = @param2\",\n parameters={\n \"@param1\": \"value3\",\n \"@param2\": 3\n }\n )\n )\n\n\nwith ServiceBusAdministrationClient.from_connection_string(CONNECTION_STR) as servicebus_mgmt_client:\n create_rule(servicebus_mgmt_client)\n list_rules(servicebus_mgmt_client)\n get_and_update_rule(servicebus_mgmt_client)\n delete_rule(servicebus_mgmt_client)\n","sub_path":"sdk/servicebus/azure-servicebus/samples/sync_samples/mgmt_rule.py","file_name":"mgmt_rule.py","file_ext":"py","file_size_in_byte":3724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"360096358","text":"# Задание-1:\n# Реализуйте описаную ниже задачу, используя парадигмы ООП:\n# В школе есть Классы(5А, 7Б и т.д.), в которых учатся Ученики.\n# У каждого ученика есть два Родителя(мама и папа).\n# Также в школе преподают Учителя. Один учитель может преподавать\n# в неограниченном кол-ве классов свой определенный предмет.\n# Т.е. Учитель Иванов может преподавать математику у 5А и 6Б,\n# но больше математику не может преподавать никто другой.\n\n# Выбранная и заполненная данными структура должна решать следующие задачи:\n# 1. Получить полный список всех классов школы\n# 2. Получить список всех учеников в указанном классе\n# (каждый ученик отображается в формате \"Фамилия И.О.\")\n# 3. Получить список всех предметов указанного ученика\n# (Ученик --> Класс --> Учителя --> Предметы)\n# 4. Узнать ФИО родителей указанного ученика\n# 5. Получить список всех Учителей, преподающих в указанном классе\nclass Person:\n def __init__(self, name, surname, f_name):\n self.name = name\n self.surname = surname\n self.f_name = f_name\n\n def get_full_name(self):\n return \"{} {} {}\".format(self.name, self.surname, self.f_name)\n\n def full_name_format(self):\n return \"{} {}. {}.\".format(self.name, self.surname[0].upper(), self.f_name[0].upper())\n\n\nclass Student(Person):\n def __init__(self, name, surname, f_name, class_group, father, mother):\n Person.__init__(self, name, surname, f_name)\n self.class_group = class_group\n self.father = father\n self.mother = mother\n\n\nclass Teacher(Person):\n def __init__(self, name, surname, f_name, subjects):\n Person.__init__(self, name, surname, f_name)\n self.subjects = subjects\n\n\nclass School:\n def __init__(self, classes, teachers):\n self.classes = classes\n self.teacher_dirs = {t.subjects: t for t in teachers}\n\n\nteachers = [Teacher('Торсунов', 'Никон', 'Егорович', 'История'),\n Teacher('Квакина', 'Марфа', 'Семеновна', 'Русский язык'),\n Teacher('Юганцева', 'Анастасия', 'Елизаровна', 'Математика'),\n Teacher('Шатова', 'Тамара', 'Ростиславовна', 'Иностранные языки'),\n Teacher('Нырцева', 'Альбина', 'Святославовна', 'Информатика'),\n Teacher('Ярополов', 'Аскольд', 'Наумович', 'Трудовое воспитание'),\n Teacher('Борхеса', 'Юлия', 'Якововна', 'Физика'),\n Teacher('Лазарева', 'Ирина', 'Мироновна', 'Химия'),\n Teacher('Лившиц', 'Богдан', 'Феликсович', 'Биология'),\n Teacher('Сарычев', 'Эдуард', 'Прохорович', 'Физкультура'),\n Teacher('Грекова', 'Римма', 'Степановна', 'Социология'),\n Teacher('Кручинин', 'Мир', 'Святославович', 'Экономика'),\n Teacher('Пищикова', 'Арина', 'Семеновна', 'Политология'),\n Teacher('Малец', 'Ав��ей', 'Михаилович', 'География')]\nclasses = [\n School('7 A', [teachers[0], teachers[1], teachers[2], teachers[3]]),\n School('7 Б', [teachers[2], teachers[3], teachers[4], teachers[5]]),\n School('8 A', [teachers[4], teachers[5], teachers[6], teachers[7]]),\n School('8 Б', [teachers[6], teachers[7], teachers[8], teachers[9]]),\n School('9 A', [teachers[8], teachers[9], teachers[10], teachers[11]]),\n School('9 Б', [teachers[10], teachers[11], teachers[12], teachers[13]]),\n School('10 A', [teachers[12], teachers[13], teachers[0], teachers[1]]),\n School('10 Б', [teachers[0], teachers[1], teachers[2], teachers[3]]),\n School('11 A', [teachers[2], teachers[3], teachers[4], teachers[5]]),\n School('11 Б', [teachers[4], teachers[5], teachers[6], teachers[7]]),\n ]\ndad = [Person('Голубов', 'Геннадий', 'Андреевич'),\n Person('Буданов', 'Степан', 'Адрианович'),\n Person('Мальчиков', 'Руслан', 'Геннадиевич'),\n Person('Попов', 'Модест', 'Прокофиевич'),\n Person('Рагозин', 'Филимон', 'Фролович'),\n Person('Шверник', 'Семен', 'Тимурович'),\n Person('Буров', 'Елисей', 'Сигизмундович'),\n Person('Дуванов', 'Денис', 'Тарасович'),\n Person('Ювелев', 'Емельян', 'Севастьянович'),\n Person('Кручинин', 'Роман', 'Архипович'),\n Person('Задорнов', 'Лавр', 'Фролович'),\n Person('Якунькин', 'Харитон', 'Аникитевич'),\n Person('Евремович', 'Артур', 'Валерьянович'),\n Person('Скоробогатов', 'Зиновий', 'Онисимович'),\n Person('Зарубин', 'Захар', 'Дмитриевич'),\n Person('Паршиков', 'Игорь', 'Федотович'),\n Person('Новосельцев', 'Фока', 'Андреевич'),\n Person('Квартин', 'Феликс', 'Эрнестович'),\n Person('Грибанов', 'Дмитрий', 'Александрович'),\n Person('Николаенко', 'Кузьма', 'Зиновиевич')]\nmom = [Person('Голубова', 'Арина', 'Василиевна'),\n Person('Буданова', 'Евгения', 'Игоревна'),\n Person('Мальчикова', 'Виктория', 'Юлиевна'),\n Person('Попова', 'Пелагея', 'Афанасиевна'),\n Person('Рагозина', 'Инга', 'Захаровна'),\n Person('Шверник', 'Любава', 'Филипповна'),\n Person('Бурова', 'Василиса', 'Никитевна'),\n Person('Дуванова', 'Фаина', 'Ипполитовна'),\n Person('Ювелева', 'Рада', 'Святославовна'),\n Person('Кручинина', 'Валерия', 'Георгиевна'),\n Person('Задорнова', 'Пелагея', 'Алексеевна'),\n Person('Якунькина', 'Лариса', 'Алексеевна'),\n Person('Евремович', 'Валентина', 'Серафимовна'),\n Person('Скоробогатова', 'Кристина', 'Тимуровна'),\n Person('Зарубина', 'Нина', 'Фомевна'),\n Person('Паршикова', 'Влада', 'Елизаровна'),\n Person('Новосельцев', 'Розалия', 'Яновна'),\n Person('Квартин', 'Доминика', 'Михеевна'),\n Person('Грибанов', 'Наталья', 'Романовна'),\n Person('Николаенко', 'Анисья', 'Трофимовна')]\nstudents = [Student('Голубова', 'Дина', 'Геннадиевна', classes[0], dad[0], mom[0]),\n Student('Буданова', 'Агафья', 'Степановна', classes[1], dad[1], mom[1]),\n Student('Мальчиков', 'Лука', 'Руслан', classes[2], dad[2], mom[2]),\n Student('Попов', 'Фома', 'Модестович', classes[3], dad[3], mom[3]),\n Student('Рагозин', 'Герман', 'Филимонович', classes[4], dad[4], mom[4]),\n Student('Шверник', 'Адам', 'Семенович', classes[5], dad[5], mom[5]),\n Student('Буров', 'Никифор', 'Елисеевич', classes[6], dad[6], mom[6]),\n Student('Дуванова', 'Инга', 'Денисовна', classes[7], dad[7], mom[7]),\n Student('Ювелев', 'Мир', 'Емельянович', classes[8], dad[8], mom[8]),\n Student('Кручинин', 'Иннокентий', 'Романович', classes[9], dad[9], mom[9]),\n Student('Задорнов', 'Моисей', 'Лаврович', classes[0], dad[10], mom[10]),\n Student('Якунькин', 'Наум', 'Харитонович', classes[1], dad[11], mom[11]),\n Student('Евремович', 'Фома', 'Артурович', classes[2], dad[12], mom[12]),\n Student('Скоробогатов', 'Петр', 'Зиновиевич', classes[3], dad[13], mom[13]),\n Student('Зарубина', 'Бронислава', 'Захарович', classes[4], dad[14], mom[14]),\n Student('Паршиков', 'Платон', 'Игорьевич', classes[5], dad[15], mom[15]),\n Student('Новосельцев', 'Пимен', 'Фокаевич', classes[6], dad[16], mom[16]),\n Student('Квартин', 'Осип', 'Феликсович', classes[7], dad[17], mom[17]),\n Student('Грибанов', 'Артемий', 'Дмитриевич', classes[8], dad[18], mom[18]),\n Student('Николаенко', 'Евдоким', 'Кузьмич', classes[9], dad[19], mom[19])]\n\n# 1. Получить полный список всех классов школы\n# print('CПИСОК ВСЕХ КЛАССОВ ШКОЛЫ: ')\n# for _ in classes:\n# print(_.classes)\n# 2. Получить список всех учеников в указанном классе\nfor _ in classes:\n print('УЧЕНИИКИ {} КЛАССА'.format(_.classes))\n for st in students:\n print(st.full_name_format())\n","sub_path":"Home/h7/h7_1n.py","file_name":"h7_1n.py","file_ext":"py","file_size_in_byte":10370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"148774228","text":"\n\nfrom xai.brain.wordbase.nouns._neckerchief import _NECKERCHIEF\n\n#calss header\nclass _NECKERCHIEVES(_NECKERCHIEF, ):\n\tdef __init__(self,): \n\t\t_NECKERCHIEF.__init__(self)\n\t\tself.name = \"NECKERCHIEVES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"neckerchief\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_neckerchieves.py","file_name":"_neckerchieves.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"519052092","text":"class Employee1:\n name = \"Vera\"\n\nvera = Employee1()\nprint(vera.name)\n\nclass Employee2:\n def __init__(self, name):\n self.name = name\n\nvera = Employee2(\"Vera\")\nchuck = Employee2(\"Chuck\")\nprint(vera.name)\nprint(chuck.name)\n","sub_path":"demo/organizingcode/classes/employee.py","file_name":"employee.py","file_ext":"py","file_size_in_byte":233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"323614876","text":"\"\"\"\nMain\n=====\n\"\"\"\n\nimport click\nfrom sumy.nlp.tokenizers import Tokenizer\nfrom sumy.parsers.plaintext import PlaintextParser\n\nfrom .textrank import alt_extract, get_summarizer\n\n\n@click.command()\n@click.argument('url')\n@click.option('--max-sent', default=10, help='The maximum number of sentences')\n@click.option('--language', default='english', help='Article language')\ndef main(url, max_sent, language='english'):\n tokenizer = Tokenizer(language)\n article = alt_extract(url)\n parser = PlaintextParser.from_string(article, tokenizer)\n return click.echo(get_summarizer(parser, max_sent, language))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"ExplainToMe/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"384370304","text":"\nfrom .. import File, Folder, IDFileobject\n\nfrom urllib.parse import unquote as urlunescape\nimport time\n\n\n__all__ = ['OnedriveFileobject', 'OnedriveFile', 'OnedriveFolder']\n\n\nclass OnedriveFileobject(IDFileobject):\n @classmethod\n def from_metadata(cls, odrive, meta):\n path = meta['parentReference']['path'] + '/' + meta['name']\n path = path[12:] # strip the \"/drive/root:\"\n path = urlunescape(path) # god knows why this thing is escaped\n\n obj = cls(odrive, path, escape=False)\n obj._update_metadata_local(meta)\n return obj\n\n def _load_metadata(self):\n resp = self.host._http_get('root:{}'.format(self.path))\n self._update_metadata_local(resp)\n\n def _update_metadata_local(self, meta):\n if 'id' in meta:\n self.id = meta['id']\n\n parentinfo = meta.get('parentReference')\n if parentinfo is not None:\n parent_path = parentinfo['path'][12:] # strip the \"/drive/root:\"\n parent = self.host.folder(parent_path)\n parent.id = parentinfo['id']\n\n @property\n def id(self):\n if self._id is None:\n self._load_metadata()\n return self._id\n\n @id.setter\n def id(self, id):\n self._id = id\n\n\nclass OnedriveFile(OnedriveFileobject, File):\n def _update_metadata_local(self, meta):\n super()._update_metadata_local(meta)\n\n def parse_time(t):\n if '.' in t:\n return time.strptime(t, '%Y-%m-%dT%H:%M:%S.%fZ')\n else:\n return time.strptime(t, '%Y-%m-%dT%H:%M:%SZ')\n\n mtime = meta.get('lastModifiedDateTime')\n if mtime is not None:\n self.server_modification_time = parse_time(mtime)\n\n if 'size' in meta:\n self.size = meta['size']\n\n if '@microsoft.graph.downloadUrl' in meta:\n self.download_url = meta['@microsoft.graph.downloadUrl']\n\n fsinfo = meta.get('fileSystemInfo')\n if fsinfo is not None:\n if self._client_modification_time is None:\n mtime = fsinfo.get('lastModifiedDateTime')\n if mtime is not None:\n self.client_modification_time = parse_time(mtime)\n\n def _get_server_modification_time(self):\n self._load_metadata()\n return self._server_modification_time\n\n def _get_client_modification_time(self):\n self._load_metadata()\n return self._client_modification_time\n\n def _get_size(self):\n self._load_metadata()\n return self._size\n\n _download_url = None\n\n @property\n def download_url(self):\n if self._download_url is None:\n self._load_metadata()\n assert self._download_url is not None, self\n return self._download_url\n\n @download_url.setter\n def download_url(self, url):\n self._download_url = url\n\n\nclass OnedriveFolder(OnedriveFileobject, Folder):\n def _update_metadata_local(self, meta):\n super()._update_metadata_local(meta)\n\n if 'size' in meta:\n self._size = meta['size']\n\n if 'folder' in meta:\n folder_meta = meta['folder']\n if 'childCount' in folder_meta:\n self.child_count = folder_meta['childCount']\n\n def _get_children(self):\n if self.path.is_root:\n url = 'root/children'\n else:\n url = 'root:{}:/children'.format(self.path)\n resp = self.host._http_get(url)\n files = resp['value']\n files = [file_or_folder_from_metadata(self.host, f) for f in files]\n return files\n\n\ndef file_or_folder_from_metadata(odrive, meta):\n if 'folder' in meta:\n return OnedriveFolder.from_metadata(odrive, meta)\n return OnedriveFile.from_metadata(odrive, meta)\n","sub_path":"webdrives/onedrive/files.py","file_name":"files.py","file_ext":"py","file_size_in_byte":3759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"283399287","text":"# -*- coding: utf8 -*-\n__author__ = 'leo'\n\nfrom alascrapy.spiders.samsung_uk import SamsungUkSpider\n\n\nclass SamsungInSpider(SamsungUkSpider):\n name = 'samsung_in'\n allowed_domains = ['samsung.com']\n start_urls = ['http://reviews.in.samsung.com/7463-en_in/allreviews.htm']\n","sub_path":"alascrapy/spiders/samsung_in.py","file_name":"samsung_in.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"192524008","text":"from . import utils\nfrom .base import Expression\nfrom .constants import BREAK, POS, RESULT\nfrom .fail import Fail\n\n\nclass Choice(Expression):\n is_commented = False\n num_blocks = 2\n\n def __init__(self, *exprs):\n self.exprs = exprs\n\n def __str__(self):\n return ' | '.join(str(x) for x in self.exprs)\n\n def operand_string(self):\n return f'({self})'\n\n def always_succeeds(self):\n return any(x.always_succeeds() for x in self.exprs)\n\n def can_partially_succeed(self):\n return not self.always_succeeds() and (\n any(x.can_partially_succeed() for x in self.exprs)\n )\n\n def _compile(self, out, flags):\n needs_err = not self.always_succeeds()\n needs_backtrack = any(x.can_partially_succeed() for x in self.exprs)\n\n backtrack = out.var('backtrack') if needs_backtrack else None\n farthest_pos = out.var('farthest_pos') if needs_err else None\n\n if needs_err:\n farthest_err = out.var('farthest_err', self.error_func())\n\n if needs_err and needs_backtrack:\n out += backtrack << farthest_pos << POS\n elif needs_backtrack:\n out += backtrack << POS\n elif needs_err:\n out += farthest_pos << POS\n\n with utils.breakable(out):\n for i, expr in enumerate(self.exprs):\n comment = f'Option {i + 1}:'\n if expr.always_succeeds():\n comment += ' (always_succeeds)'\n out.add_comment(comment)\n\n with utils.if_succeeds(out, flags, expr):\n if expr.always_succeeds():\n break\n else:\n out += BREAK\n\n if needs_err and expr.can_partially_succeed():\n if isinstance(expr, Fail):\n condition = farthest_pos <= POS\n else:\n condition = farthest_pos < POS\n\n with out.IF(condition):\n out += farthest_pos << POS\n out += farthest_err << RESULT\n\n if i + 1 < len(self.exprs) and expr.can_partially_succeed():\n out += POS << backtrack\n\n if needs_err:\n out += POS << farthest_pos\n out += RESULT << farthest_err\n\n def complain(self):\n return 'Unexpected input'\n","sub_path":"sourcer/expressions/choice.py","file_name":"choice.py","file_ext":"py","file_size_in_byte":2413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"211486944","text":"from eas import EA\nfrom copy import deepcopy\nimport numpy as np\nimport math\n\n\nclass PRO(EA):\n def __init__(self, *args, gnum: int = 3, nc: int = 8, **kwargs):\n \"\"\"\n :param gnum: Group Number 分组个数\n :param nc: 评分最后允许的次数\n \"\"\"\n super(PRO, self).__init__(*args, **kwargs)\n # group_num: Group Number 分组个数\n # 若分组个数为 3, 则评分从高到低依次为 1,2,3\n self.group_num = gnum\n # group_size: Group Size 组内个数\n self.group_size = self.np // self.group_num\n # max_limit_num: 连续考核垫底次数 >= max_limit_num 时\n # 该解向量需要重新生成\n self.max_limit_num = nc\n # assess_record: 用于保存考核信息\n # 垫底则对应分量加 1\n self.assess_record = np.zeros(self.np)\n # mean_solutions: 各解向量历史的平均值\n self.mean_solutions = deepcopy(self.sc)\n self._learn_rate_max = 2\n self._learn_rate_min = 0\n # learn_rate_seeds: 各解向量对应的生成学习率的随机种子\n # 重新生成解向量时,对应位置的随机种子需要重新生成\n self.learn_rate_seeds = self._learn_rate_max - \\\n (self._learn_rate_max - self._learn_rate_min) * \\\n np.random.random(self.np)\n\n # 2 -> 0\n self.a1g = lambda current_gen: 2 * (1 - current_gen / self.max_gen)\n # -1 -> -2\n self.a2g = lambda current_gen: -1 * (1 + current_gen / self.max_gen)\n\n def _reset_learn_rate_seed(self, i):\n self.learn_rate_seeds[i] = self._learn_rate_max - \\\n (self._learn_rate_max - self._learn_rate_min) * \\\n np.random.random()\n\n def _get_learn_rate(self, i, gen):\n \"\"\"传入解向量下标和当前迭代次数,返回对应解向量的学习率\n 在自我提升阶段使用\n \"\"\"\n seed = self.learn_rate_seeds[i]\n return np.random.random() * (seed - math.exp(gen / self.max_gen * math.log(seed)))\n # return np.random.random() * (seed - seed * gen / self.max_gen)\n\n def rate_stage(self, g):\n \"\"\"为每一个个体评分\"\"\"\n # self.sc 已排序\n start = self.group_size * (self.group_num - 1)\n for i in range(start, self.np):\n self.assess_record[i] += 1\n if self.assess_record[i] >= self.max_limit_num: # 表示该位置解向量需要重新生成\n # 针对每一个分量\n for j in range(self.n):\n r1, r2 = 2 * np.random.random(2) - 1\n si = np.random.randint(0, self.group_size)\n ai = np.random.randint(self.group_size, self.group_size * 2)\n self.sc[i, j] = (r1 * self.sc[si][j] + r2 * self.sc[ai][j]) / (r1 + r2)\n # 越界处理\n self.sc[i] = self.bs(self.sc[i], self.ub, self.lb)\n self.assess_record[i] = 0\n self._reset_learn_rate_seed(i)\n\n def learn_stage(self, g):\n \"\"\"组间学习\"\"\"\n for gi in range(self.group_num):\n \"\"\"第 gi 组\"\"\"\n for gj in range(self.group_size):\n \"\"\"第 gi 组的第 gj 个个体\"\"\"\n i = gi * self.group_size + gj # 种群中的第 i 个\n s_copy = deepcopy(self.sc[i])\n r = self._get_learn_rate(i, g)\n\n for j in range(self.n):\n # 随机选择一个组\n rand_g = np.random.choice([gx for gx in range(self.group_num) if gx != gi])\n # 随机选择该组中的两个解向量\n i1, i2 = np.random.choice(np.arange(rand_g * self.group_size, (rand_g + 1) * self.group_size), 2)\n rr = 2 * np.random.random() - 1\n s_copy[j] = self.sc[0,j] + r * rr * (self.sc[i1,j] - self.sc[i2,j])\n\n s_copy = self.bs(s_copy, self.ub, self.lb)\n if not self.better_than(i, s_copy):\n self.sc[i] = s_copy\n\n # 重新计算历史平均\n self.mean_solutions[i] = (self.mean_solutions[i] * g + self.sc[i]) / (g + 1)\n\n def promote_stage(self, g):\n \"\"\"提升阶段\"\"\"\n for i in range(self.np):\n r = self._get_learn_rate(i, g)\n s_new = deepcopy(self.sc[i])\n for j in range(self.n):\n rr = 2 * np.random.random() - 1\n s_new[j] += rr * r * (self.mean_solutions[i, j] - self.sc[i, j])\n\n s_new = self.bs(s_new, self.ub, self.lb)\n\n if not self.better_than(i, s_new):\n self.sc[i] = s_new\n\n # 重新计算历史平均\n self.mean_solutions[i] = (self.mean_solutions[i] * g + self.sc[i]) / (g + 1)\n\n A = 2 * self.a1g(g) * np.random.random() - self.a1g(g)\n if abs(A) > 1:\n self.hidden(g)\n\n def hidden(self, g):\n for i in range(self.np - 1, 0, -1):\n if np.random.random() > 0.8:\n s_copy = np.sum(self.sc, axis=0) / self.np * (2 * np.random.random() - 1)\n if not self.better_than(i, s_copy):\n self.sc[i] = s_copy\n self.mean_solutions[i] = (self.mean_solutions[i] * g + self.sc[i]) / (g + 1)\n\n def run(self, g):\n self.rate_stage(g)\n self.learn_stage(g)\n self.promote_stage(g)\n\n def sort(self):\n flag = 1 if self.optimal_minimal else -1\n self.fc = self.equip_procedure_all()\n sorted_indexes = np.argsort(flag * self.fc)\n self.sc = self.sc[sorted_indexes]\n self.mean_solutions = self.mean_solutions[sorted_indexes]\n self.assess_record = self.assess_record[sorted_indexes]\n self.fc = self.fc[sorted_indexes]\n","sub_path":"eas/PRO.py","file_name":"PRO.py","file_ext":"py","file_size_in_byte":5869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"640725375","text":"import multiprocessing\nimport time\n\nclass LoadingManager(object):\n \"\"\"\n This class is responsible for spinning up, spinning down, and coordinating loading processes on\n a single node.\n \"\"\"\n\n def __init__(self, loader, num_processes, node_number, total_nodes):\n self.loader = []\n self.processes = []\n\n begin_loader_id = num_processes * node_number\n total_loaders = num_processes * total_nodes\n\n for pnum in xrange(num_processes):\n proc = multiprocessing.Process(target=loader, args=(begin_loader_id+pnum, total_loaders))\n self.processes.append(proc)\n\n self.node_number = node_number\n\n\n def run(self):\n for index, proc in enumerate(self.processes):\n proc.start()\n for proc in self.processes:\n proc.join()\n","sub_path":"TBC/core/LoadingManager.py","file_name":"LoadingManager.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"55467276","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]\n# Embedded file name: T:\\InGame\\Gameplay\\Scripts\\Server\\gsi_handlers\\alarm_handlers.py\n# Compiled at: 2014-04-12 01:45:01\n# Size of source mod 2**32: 880 bytes\nfrom sims4.gsi.dispatcher import GsiHandler\nfrom sims4.gsi.schema import GsiGridSchema, GsiFieldVisualizers\nimport alarms\nalarm_schema = GsiGridSchema(label='Alarms')\nalarm_schema.add_field('time', label='Absolute Time', width=2)\nalarm_schema.add_field('time_left', label='Time Left', width=1)\nalarm_schema.add_field('ticks', label='Ticks Left', type=(GsiFieldVisualizers.INT))\nalarm_schema.add_field('handle', label='Handle', width=1, unique_field=True, hidden=True)\nalarm_schema.add_field('owner', label='Owner', width=3)\nalarm_schema.add_field('callback', label='Callback', width=3)\n\n@GsiHandler('alarms', alarm_schema)\ndef generate_alarm_data(*args, zone_id: int=None, **kwargs):\n return alarms.get_alarm_data_for_gsi()","sub_path":"Scripts/simulation/gsi_handlers/alarm_handlers.py","file_name":"alarm_handlers.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"288781796","text":"'''\n\nThis programme calculates the time difference between reported milestones\n\nOutput document:\n1) excel workbook with all project milestone information for each project\n\nSee instructions below.\n\nNote: all master data is taken from the data file. Make sure this is up to date and that all relevant data is in\nthe import statement.\n\n'''\n\n#TODO solve problem re filtering in excel when values have + sign in front of the them\n\nfrom openpyxl import Workbook\nfrom analysis.engine_functions import project_time_difference, all_milestones_dict\nfrom analysis.data import list_of_masters_all, bc_index, baseline_bc_stamp, root_path\n\n\ndef put_into_wb_all_single(function):\n '''\n\n Function that places all individual milestone data into excel wb.\n\n project_name_list: list of project to return data for\n t_data: dictionary containing milestone data for projects.\n dictionary structure is {'project name': {'milestone name': datetime.date: 'notes'}}\n td_data: dictionary containing time_delta milestone data for projects.\n dictionary structure is {'project name': {'milestone name': 'time delta info'}}\n td_data_two: dictionary containing second time_delta data for projects.\n same structure as for td_data.\n wb: blank excel wb\n\n '''\n\n '''get all milestone data'''\n p_current_milestones = function(list_of_masters_all[0].projects, list_of_masters_all[0])\n p_last_milestones = function(list_of_masters_all[1].projects, list_of_masters_all[1])\n\n '''calculate time current and last quarter'''\n first_diff_data = project_time_difference(p_current_milestones, p_last_milestones)\n\n wb = Workbook()\n\n for x, project_name in enumerate(list_of_masters_all[0].projects):\n '''worksheet is created for each project'''\n ws = wb.create_sheet(project_name[:29], x) # creating worksheets. name restricted to 30 characters\n ws.title = project_name[:29] # title of worksheet.\n\n row_num = 2\n for i, milestone in enumerate(first_diff_data[project_name].keys()):\n ws.cell(row=row_num + i, column=1).value = project_name\n ws.cell(row=row_num + i, column=2).value = milestone\n try:\n milestone_date = tuple(p_current_milestones[project_name][milestone])[0]\n ws.cell(row=row_num + i, column=3).value = milestone_date\n ws.cell(row=row_num + i, column=3).number_format = 'dd/mm/yy'\n except KeyError:\n ws.cell(row=row_num + i, column=3).value = 0\n\n try:\n value = first_diff_data[project_name][milestone]\n try:\n if int(value) > 0:\n ws.cell(row=row_num + i, column=4).value = '+' + str(value) + ' (days)'\n elif int(value) < 0:\n ws.cell(row=row_num + i, column=4).value = str(value) + ' (days)'\n elif int(value) == 0:\n ws.cell(row=row_num + i, column=4).value = value\n except ValueError:\n ws.cell(row=row_num + i, column=4).value = value\n except KeyError:\n ws.cell(row=row_num + i, column=4).value = 0\n\n p_oldest_milestones = function([project_name], list_of_masters_all[bc_index[project_name][2]])\n second_diff_data = project_time_difference(p_current_milestones, p_oldest_milestones)\n\n try:\n value = second_diff_data[project_name][milestone]\n try:\n if int(value) > 0:\n ws.cell(row=row_num + i, column=5).value = '+' + str(value) + ' (days)'\n elif int(value) < 0:\n ws.cell(row=row_num + i, column=5).value = str(value) + ' (days)'\n elif int(value) == 0:\n ws.cell(row=row_num + i, column=5).value = value\n except ValueError:\n ws.cell(row=row_num + i, column=5).value = value\n except KeyError:\n ws.cell(row=row_num + i, column=5).value = 0\n\n try:\n milestone_date = tuple(p_current_milestones[project_name][milestone])[0]\n ws.cell(row=row_num + i, column=6).value = p_current_milestones[project_name][milestone][milestone_date] # provided notes\n except IndexError:\n ws.cell(row=row_num + i, column=6).value = 0\n\n ws.cell(row=1, column=1).value = 'Project'\n ws.cell(row=1, column=2).value = 'Milestone'\n ws.cell(row=1, column=3).value = 'Date'\n ws.cell(row=1, column=4).value = '3/m change (days)'\n ws.cell(row=1, column=5).value = 'baseline change (days)'\n ws.cell(row=1, column=6).value = 'Notes'\n\n ws.cell(row=1, column=8).value = 'data baseline quarter'\n ws.cell(row=2, column=8).value = baseline_bc_stamp[project_name][0][1]\n\n return wb\n\n\n''' RUNNING THE PROGRAMME'''\n\n'''\nOnly one part of programme is to be amended each quarter. place which ever quarter information being produced at \nend of output file name e.g. q4_1920. Note make sure file ends with .xlsx format\n\n'''\n\noutput = put_into_wb_all_single(all_milestones_dict)\noutput.save(root_path/'output/ind_project_milestones_q4_1920_2.xlsx')","sub_path":"milestone_analysis/milestone_comparison_3_qrts_proj.py","file_name":"milestone_comparison_3_qrts_proj.py","file_ext":"py","file_size_in_byte":5254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"335603879","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is\n# regenerated.\n# --------------------------------------------------------------------------\n\nfrom msrest.serialization import Model\n\n\nclass ResourceOperation(Model):\n \"\"\"Individual resource operation information.\n\n Variables are only populated by the server, and will be ignored when\n sending a request.\n\n :param resource_name: Name of the resource as specified in the artifacts.\n For ARM resources, this is the name of the resource specified in the\n template.\n :type resource_name: str\n :ivar operation_id: Unique identifier of the operation. For ARM resources,\n this is the operationId obtained from ARM service.\n :vartype operation_id: str\n :param resource_type: Type of the resource as specified in the artifacts.\n For ARM resources, this is the type of the resource specified in the\n template.\n :type resource_type: str\n :ivar provisioning_state: State of the resource deployment. For ARM\n resources, this is the current provisioning state of the resource.\n :vartype provisioning_state: str\n :ivar status_message: Descriptive information of the resource operation.\n :vartype status_message: str\n :ivar status_code: Http status code of the operation.\n :vartype status_code: str\n \"\"\"\n\n _validation = {\n 'operation_id': {'readonly': True},\n 'provisioning_state': {'readonly': True},\n 'status_message': {'readonly': True},\n 'status_code': {'readonly': True},\n }\n\n _attribute_map = {\n 'resource_name': {'key': 'resourceName', 'type': 'str'},\n 'operation_id': {'key': 'operationId', 'type': 'str'},\n 'resource_type': {'key': 'resourceType', 'type': 'str'},\n 'provisioning_state': {'key': 'provisioningState', 'type': 'str'},\n 'status_message': {'key': 'statusMessage', 'type': 'str'},\n 'status_code': {'key': 'statusCode', 'type': 'str'},\n }\n\n def __init__(self, *, resource_name: str=None, resource_type: str=None, **kwargs) -> None:\n super(ResourceOperation, self).__init__(**kwargs)\n self.resource_name = resource_name\n self.operation_id = None\n self.resource_type = resource_type\n self.provisioning_state = None\n self.status_message = None\n self.status_code = None\n","sub_path":"azure-mgmt-deploymentmanager/azure/mgmt/deploymentmanager/models/resource_operation_py3.py","file_name":"resource_operation_py3.py","file_ext":"py","file_size_in_byte":2655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"539839270","text":"class Solution:\n def largestSumAfterKNegations(self, A: List[int], K: int) -> int:\n A = sorted(A)\n A.reverse()\n\n i = len(A) - 1\n while K > 0 and A[-1] <= 0: # flip negative numbers\n K -= 1\n tmp = A.pop() * -1\n A = self.insert(A, tmp)\n\n if K % 2 == 1:\n A[-1] *= -1\n\n return sum(A)\n\n def insert(self, A: List[int], n) -> List[int]:\n i = 0\n while i < len(A) and A[i] > n:\n i += 1\n A.insert(i, n)\n return A\n","sub_path":"leetcode/solved/001005. Maximize Sum Of Array After K Negations.py","file_name":"001005. Maximize Sum Of Array After K Negations.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"163677807","text":"import multiprocessing as mp\nimport binascii\n\n\ndef create_processes(filename, offset, interleave, L):\n processes = []\n parent_conns = []\n for c in range(3):\n parent_conn, child_conn = mp.Pipe()\n p = mp.Process(target=get_msg, args=(child_conn, filename, c, offset, interleave, L))\n p.start()\n processes.append(p)\n parent_conns.append(parent_conn)\n return processes, parent_conns\n\ndef get_msg(conn, filename, c, offset, interleave, L):\n pixel_counter = 0\n if c != 2:\n L = L // 3\n else:\n l = L // 3\n L = (L // 3) + L % 3\n counter = 0\n msg = \"\"\n interleave_counter = 1\n while len(msg) < L:\n read = conn.recv()\n for byte in read:\n if counter == c:\n pixel_counter += 1\n if pixel_counter > offset:\n interleave_counter -= 1\n if interleave_counter == 0:\n interleave_counter = interleave * 1\n byte = list(format(byte, '08b'))\n msg += byte[7]\n conn.send(byte[7])\n if len(msg) == L:\n break\n counter += 1\n if counter == 3:\n counter = 0\n conn.send('stop')\n","sub_path":"alumnos/57031-porollan-santiago/TP2/steganography/decode.py","file_name":"decode.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"54128277","text":"import time\nimport random\n\nfrom nose.plugins.attrib import attr\n\nfrom emmaa.db import Query, Result, EmmaaDatabaseManager\nfrom emmaa.queries import Query as QueryObject, PathProperty\n\n\ntest_query_jsons = [{'type': 'path_property', 'path': {'type': 'Activation',\n 'subj': {'type': 'Agent', 'name': 'BRAF'},\n 'obj': {'type': 'Agent', 'name': 'ERK'}}},\n {'type': 'path_property', 'path':\n {'type': 'Phosphorylation',\n 'enz': {'type': 'Agent', 'name': 'ERK'},\n 'sub': {'type': 'Agent', 'name': 'MEK'}}}]\n\ntest_queries = [QueryObject._from_json(qj) for qj in test_query_jsons]\n\n\ndef _get_test_db():\n db = EmmaaDatabaseManager('postgresql://postgres:@localhost/emmaadb_test')\n db.drop_tables(force=True)\n db.create_tables()\n return db\n\n\n@attr('nonpublic')\ndef test_instantiation():\n db = _get_test_db()\n assert db\n return\n\n\n@attr('nonpublic')\ndef test_put_queries():\n db = _get_test_db()\n db.put_queries('joshua', 1, test_queries[0], ['aml', 'luad'])\n with db.get_session() as sess:\n queries = sess.query(Query).all()\n assert len(queries) == 2, len(queries)\n\n\n@attr('nonpublic')\ndef test_get_queries():\n db = _get_test_db()\n for query in test_queries:\n db.put_queries('joshua', 1, query, ['aml', 'luad'])\n db.put_queries('test_user', 2, query, ['aml'])\n # We should only get distinct queries, independent of number of users\n queries = db.get_queries('aml')\n assert len(queries) == 2, len(queries)\n assert all(isinstance(query, PathProperty) for query in queries)\n queries = db.get_queries('luad')\n assert len(queries) == 2, len(queries)\n assert all(isinstance(query, PathProperty) for query in queries)\n\n\ndef _get_random_result():\n return random.choice(\n [{'12': [['This is fine.', '']]}, {'34': [['This is not ok.', '']]}])\n\n\n@attr('nonpublic')\ndef test_put_results():\n db = _get_test_db()\n db.put_queries('joshua', 1, test_queries[0], ['aml', 'luad'])\n queries = db.get_queries('aml')\n results = [(query, '', _get_random_result())\n for query in queries]\n db.put_results('aml', results)\n with db.get_session() as sess:\n db_results = sess.query(Result).all()\n assert len(db_results) == len(results)\n\n\n@attr('nonpublic')\ndef test_get_results():\n db = _get_test_db()\n models = ['aml', 'luad']\n\n # Fill up the database.\n for query in test_queries:\n db.put_queries('joshua', 1, query, models)\n for model in models:\n db.put_results(model, [(query, 'pysb', _get_random_result())\n for query in test_queries])\n\n # Try to get the results.\n results = db.get_results('joshua')\n assert len(results) == len(test_queries)*len(models), len(results)\n assert all(isinstance(result, tuple) for result in results)\n assert all(result[0] in models for result in results)\n assert any(results[0][1].matches(q) for q in test_queries)\n assert all(isinstance(result[2], str) for result in results)\n assert all(isinstance(result[3], dict) for result in results)\n\n\n@attr('nonpublic')\ndef test_get_latest_results():\n db = _get_test_db()\n models = ['aml', 'luad']\n\n # Fill up the database.\n for query in test_queries:\n db.put_queries('joshua', 1, query, models)\n for model in models:\n db.put_results(model, [(query, 'pysb', _get_random_result())\n for query in test_queries])\n\n # Add the same statements over again\n time.sleep(10)\n for model in models:\n db.put_results(model, [(query, 'pysb', _get_random_result())\n for query in test_queries])\n\n # Try to get the results. Make sure we only get the one set.\n results = db.get_results('joshua')\n assert len(results) == len(test_queries)*len(models), len(results)\n assert all(isinstance(result, tuple) for result in results)\n assert all(result[0] in models for result in results)\n assert any(results[0][1].matches(q) for q in test_queries)\n assert all(isinstance(result[2], str) for result in results)\n assert all(isinstance(result[3], dict) for result in results)\n","sub_path":"emmaa/tests/test_db.py","file_name":"test_db.py","file_ext":"py","file_size_in_byte":4238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"250958161","text":"from django.shortcuts import render, get_object_or_404\nfrom .models import Variation\n\ndef product_detail(request, id = None):\n\tinstance = get_object_or_404(Variation, id=id)\n\tcontext = {\n\t\t\"title\": \"Detalles\",\n\t\t\"instance\": instance,\n\t}\n\treturn render(request, \"test_detail.html\", context)\n","sub_path":"products/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"464931260","text":"\"\"\" PALMIA: \r\n# Yksittäinen ruokaitemi, HTML koodista\r\nclass=\"meal-name invidual-restaurant-meal-name\"\r\n\r\n# Päivämäärän merkintä\r\ndata-date=\"2021-11-9\"\r\n\r\n# Suomenkielinen, ruotsiksi id=\"3\"\r\ndata-language-id=\"2\"\r\n\r\n# Jokaisessa Kasvislounaassa sekä Lounas ja Lounaan Lisukkeet\r\nclass=\"invidual-restaurant-meal-paragraph\"\r\n #Pelkkä \"Lounas\" teksti\r\n class=\"meal-of-day invidual-restaurant-meal-of-day\"\r\n\r\ndata-meal=\"UyQ-KpQHSUKn_ccO_dpEIw\" \"\"\"\r\n\r\nimport requests\r\nimport bs4\r\nfrom datetime import datetime\r\n\r\ndef päivän_ruokalista():\r\n\r\n # Kerro nykyinen päivä numerona 0 maanantai - 6 sunnuntai\r\n päivä = datetime.today().weekday()\r\n #print(päivä)\r\n \r\n \"\"\" koulu = str(input(\"Kirjoita koulun nimi: \")).lower()\r\n koulu = koulu.replace(\" \", \"-\") \"\"\"\r\n \r\n\r\n res = requests.get(f\"https://ruoka.palmia.fi/fi/ravintola/koulu/alppilan-lukio/\")\r\n soup = bs4.BeautifulSoup(res.text, \"lxml\")\r\n\r\n # Päivän ruoka listaksi, josta korjataan ylimääräiset välit pois\r\n\r\n ruoka= []\r\n \r\n d = soup.select(\".menu-list-day.invidual-restaurant-menu-list-day\")\r\n s = (d[päivä].getText())\r\n ruoka.append(s)\r\n ruoka = [s.replace(\"\\n\\n\\n\\n\\n\", \"\\n\") for s in ruoka]\r\n print(ruoka[0])\r\n\r\npäivän_ruokalista()\r\n\r\n","sub_path":"RUOKALISTA PALMIA.py","file_name":"RUOKALISTA PALMIA.py","file_ext":"py","file_size_in_byte":1268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"441343747","text":"#!/bin/env python3\n# -*- coding: utf-8 -*-\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\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 General Public License for more details.\n# A copy of the GNU General Public License is available at\n# http://www.gnu.org/licenses/gpl-3.0.html\n\n\"\"\"Perform assembly based on debruijn graph.\"\"\"\n\nimport argparse\nimport os\nimport sys\nimport statistics\nimport random\nimport math\nfrom random import randint\n\nimport pickle\nimport networkx as nx\nimport matplotlib.pyplot as plt\n\nrandom.seed(9001)\n\n__author__ = \"ROBILLARD Nicolas\"\n__copyright__ = \"Universite Paris Diderot\"\n__credits__ = [\"ROBILLARD Nicolas\"]\n__license__ = \"GPL\"\n__version__ = \"1.0.0\"\n__maintainer__ = \"ROBILLARD Nicolas\"\n__email__ = \"nicolas.robillard@ymail.com\"\n__status__ = \"alpha test\"\n\ndef isfile(path):\n \"\"\"Check if path is an existing file.\n :Parameters:\n path: Path to the file\n \"\"\"\n if not os.path.isfile(path):\n if os.path.isdir(path):\n msg = \"{0} is a directory\".format(path)\n else:\n msg = \"{0} does not exist.\".format(path)\n raise argparse.ArgumentTypeError(msg)\n return path\n\ndef get_arguments():\n \"\"\"Retrieves the arguments of the program.\n Returns: An object that contains the arguments\n \"\"\"\n # Parsing arguments\n parser = argparse.ArgumentParser(description=__doc__, usage=\n \"{0} -h\"\n .format(sys.argv[0]))\n parser.add_argument('-i', dest='fastq_file', type=isfile,\n required=True, help=\"Fastq file\")\n parser.add_argument('-k', dest='kmer_size', type=int,\n default=22, help=\"K-mer size (default 22)\")\n parser.add_argument('-o', dest='output_file', type=str,\n default=os.curdir + os.sep + \"contigs.fasta\",\n help=\"Output contigs in fasta file\")\n parser.add_argument('-f', dest='graphimg_file', type=str,\n help=\"Save graph as image (png)\")\n return parser.parse_args()\n\ndef read_fastq(fastq_file):\n \"\"\"Read fasta file\n ---\n Read a fastq file to import sequences\\n\n Argument:\n - fastq_file (argparse) : fastq file make in arguments of program\\n\n Return:\n - Generator of sequnces in fastq\n \"\"\"\n with open(fastq_file, 'r', encoding ='utf-8') as fastq:\n lines = fastq.readlines()\n for i in range(len(lines)):\n if lines[i].startswith(\"@\"):\n yield lines[i+1][:-1]\n\ndef cut_kmer(read, kmer_size):\n \"\"\"Cut sequence in k-mers\n ---\n Take a sequences and cut it into k-mers a specified lenght\\n\n Arguments:\n - read (str): sequence of letters\n - kmer_size (int): size of k-mers wanted (give in argparse)\\n\n Return:\n - Generator of k-mers\n \"\"\"\n nb_kmers = len(read) - kmer_size + 1\n for i in range(nb_kmers):\n kmer = read[i:i + kmer_size]\n yield kmer\n\ndef build_kmer_dict(fastq_file, kmer_size):\n \"\"\"Build dictionnary of k-mers\n ---\n Arguments:\n - fastq_file (argparse): fastq file choosen\n - kmer_size (argparse): lenght of k-mers choosen\\n\n Return:\n - kmer_dict (dict): dictionnary of k-mers in the fastq file\n \"\"\"\n kmers_dict = {}\n for seq in read_fastq(fastq_file):\n for kmer in cut_kmer(seq, kmer_size):\n if kmer not in kmers_dict.keys():\n kmers_dict[kmer]=seq.find(kmer)\n else:\n break\n return kmers_dict\n\ndef build_graph(kmer_dict):\n \"\"\"Produce a directed graph\n ---\n Argument:\n - kmer_dict (dict): dictonnary of k-mers\\n\n Return:\n - graph (nx.DiGraph): directed graph for the k-mers\n \"\"\"\n graph = nx.DiGraph()\n for kmer in kmer_dict.keys():\n graph.add_edge(kmer[:-1],kmer[1:],weight=kmer_dict[kmer])\n return graph\n\ndef remove_paths(graph, path_list, delete_entry_node, delete_sink_node):\n \"\"\"Remove paths in a graph\n ---\n Arguments:\n - graph (nx.Graph): De Bruijn's Graph by Network X\n - path_list (list): list of path between two nodes in graph\n - delete_entry_node (bool): indicate if the entry node need to be deleted\n - delete_sink_node (bool): indicate if the last node need to be deleted\\n\n Return:\n - graph (nx.Graph): graph simplified of low informative nodes\n \"\"\"\n if delete_entry_node is True and delete_sink_node is True:\n graph.remove_nodes_from([node for path in path_list for node in path])\n elif delete_entry_node is True and delete_sink_node is False:\n graph.remove_nodes_from([node for path in path_list for node in path[:-1]])\n elif delete_entry_node is False and delete_sink_node is True:\n graph.remove_nodes_from([node for path in path_list for node in path[1:]])\n else:\n graph.remove_nodes_from([node for path in path_list for node in path[1:-1]])\n return graph\n\ndef std(data):\n \"\"\"Calcul of the standard deviation in a sample\n ---\n Argument:\n - data (list): list of nodes\\n\n Return:\n - Standard deviation (int): standard deviation of the data\n \"\"\"\n mean = sum(data)/len(data)\n ech_mean = sum((l-mean)**2 for l in data) / (len(data)-1)\n return math.sqrt(ech_mean)\n\n\ndef select_best_path(graph, path_list, path_length, weight_avg_list,\n delete_entry_node=False, delete_sink_node=False):\n \"\"\"Select the best path in list of path\n ---\n Arguments:\n - graph (nx.DiGraph): De Bruijn's Graph by Network X\n - path_list (list): list of path in the graph\n - path_lenght (list): list of the lenght of paths in path_list\n - weight_avg_list (list): average weight of paths in path_list\n - delete_entry_node (bool): indicate if the entry node need to be deleted\n - delete_sink_node (bool): indicate if the last node need to be deleted\\n\n Return:\n - graph (nx.DiGraph): simplified graph\n \"\"\"\n if std(weight_avg_list) > 0:\n index_keep = weight_avg_list.index(max(weight_avg_list))\n elif std(weight_avg_list) ==0 and std(path_length) > 0:\n index_keep = path_length.index(max(path_length))\n else:\n index_keep = randint(0,len(path_list))\n del path_list[index_keep]\n remove_paths(graph, path_list, delete_entry_node, delete_sink_node)\n return graph\n\ndef path_average_weight(graph, path):\n \"\"\"Calcul of the mean of weights in a path\n ---\n Arguments:\n - graph (nx.DiGraph): De Bruijn's Graph by Network X\n - path (list): list of nodes in a path\\n\n Return:\n - mean weight of the path (int)\n \"\"\"\n return statistics.mean([d[\"weight\"] for (u, v, d) in graph.subgraph(path).edges(data=True)])\n\ndef solve_bubble(graph, ancestor_node, descendant_node):\n \"\"\"Resolve the bubble in a graph\n ---\n Select the path with the higher weight or the higher lenght in a bubble\n and remove all others paths\\n\n Arguments:\n - graph (nx.DiGraph): De Bruijn's Graph by Network X\n - ancestor_node (node): upstream node in the graph\n - descendent_node (node): downstream node in the graph\\n\n Return:\n - graph (DiGraph): De Bruijn Graph without bubbles\n \"\"\"\n path_list = []\n path_lenght = []\n weight_avg_list = []\n for path in nx.all_simple_paths(graph, ancestor_node,descendant_node):\n path_list.append(path)\n path_lenght.append(len(path))\n weight_avg_list.append(path_average_weight(graph, path))\n select_best_path(graph, path_list, path_lenght, weight_avg_list)\n return graph\n\ndef simplify_bubbles(graph):\n \"\"\" Simplify bubbles\n ---\n Simplfy bubble in a graph to have the more informative path\\n\n Argument:\n - graph (nx.DiGraph): De Bruijn's Graph by Network X\\n\n Return:\n - graph (nx.DiGraph): simplified De Bruijn's graph without bubbles\n \"\"\"\n bubble = False\n for node in graph.nodes:\n if node in graph.nodes():\n list_nodes = list(graph.predecessors(node))\n if len(list_nodes) >1:\n for i, npre in enumerate(list_nodes):\n for j in range(i+1,len(list_nodes)):\n node_ancestor = nx.lowest_common_ancestor(graph, npre, list_nodes[j])\n if node_ancestor is not None:\n bubble = True\n break\n if bubble:\n graph = simplify_bubbles(solve_bubble(graph, node_ancestor, node))\n return graph\n\ndef solve_entry_tips(graph, starting_nodes):\n \"\"\"Resolve the entry in a graph\n ---\n Select the entry node of the graph with higher weight or the higher\n lenght of path and remove others.\\n\n Arguments:\n - graph (nx.DiGraph): De Bruijn Graph by Network X\n - starting_nodes (list): list of possible entry nodes\\n\n Return:\n - graph (nx.DiGraph): De Bruijn's graph with the one entry node\n \"\"\"\n path_list = []\n path_lenght = []\n weight_avg_path = []\n for nodes in graph.nodes:\n nodes_pred = list(graph.predecessors(nodes))\n if len(nodes_pred) > 1:\n for entries in starting_nodes:\n path_list += list(nx.all_simple_paths(graph, entries, nodes))\n if len(path_list) > 0:\n for path in path_list:\n path_lenght.append(len(path))\n weight_avg_path.append(path_average_weight(graph, path))\n graph = select_best_path(graph, path_list, path_lenght, weight_avg_path,\n delete_entry_node=True)\n return graph\n\ndef solve_out_tips(graph, ending_nodes):\n \"\"\"Resolve the output in a graph\n ---\n Select the output node of the graph with higher weight or\n the higher lenght of path and remove others.\\n\n Arguments:\n - graph (nx.DiGraph): De Bruijn Graph by Network X\n - ending_nodes (list): list of possible outputs nodes\\n\n Return:\n - graph (nx.DiGraph): De Bruijn's graph with the one output node\n \"\"\"\n path_list = []\n path_lenght = []\n weight_avg_path = []\n for nodes in graph.nodes:\n successors = list(graph.successors(nodes))\n if len(successors) > 1:\n for outputs in ending_nodes:\n path_list += list(nx.all_simple_paths(graph, nodes, outputs))\n if len(path_list) > 0:\n for path in path_list:\n path_lenght.append(len(path))\n weight_avg_path.append(path_average_weight(graph, path))\n graph = select_best_path(graph, path_list, path_lenght,\n weight_avg_path, delete_sink_node=True)\n return graph\n\ndef get_starting_nodes(graph):\n \"\"\"Get the starting node\n ---\n Select all starting nodes in a graph\\n\n Argument:\n - graph (nx.DiGraph): De Bruijn's graph\\n\n Return:\n - starting_nodes (list): list of starting nodes in the graph\n \"\"\"\n starting_nodes = []\n for nodes in graph:\n if len(list(graph.predecessors(nodes))) == 0:\n starting_nodes.append(nodes)\n return starting_nodes\n\ndef get_sink_nodes(graph):\n \"\"\"Get the ending node\n ---\n Select all ending nodes in a graph\\n\n Argument:\n - graph (nx.DiGraph): De Bruijn's graph\\n\n Return:\n - sink_nodes (list): list of ending nodes in the graph\n \"\"\"\n sink_nodes = []\n for nodes in graph:\n if len(list(graph.successors(nodes))) == 0:\n sink_nodes.append(nodes)\n return sink_nodes\n\ndef concat_path(path_list):\n \"\"\"Concantenate list of k-mers\n ---\n Argument:\n - path_list (list): list of k-mers\\n\n Return:\n - path_str (str): string of the path with k-mers\n \"\"\"\n path_str=path_list[0]\n for i in path_list[1:]:\n path_str += i[-1]\n return path_str\n\ndef get_contigs(graph, starting_nodes, ending_nodes):\n \"\"\"Build contigs between two nodes\n ---\n Arguments:\n - graph (nx.DiGraph): De Bruijn's graph\n - starting_nodes (list): list of starting nodes in a graph\n - ending_nodes (list): list of ending nodes in a graph\\n\n Return:\n - contigs (list): list of sequences (str) possible in the graph\n \"\"\"\n contigs = []\n for start_node in starting_nodes:\n for end_node in ending_nodes:\n if nx.has_path(graph, start_node,end_node):\n for simple_path in nx.all_simple_paths(graph,start_node,end_node):\n path = concat_path(simple_path)\n contigs.append((path,len(path)))\n return contigs\n\ndef save_contigs(contigs_list, output_file):\n \"\"\"Save contigs in a fasta file\n ---\n Arguments:\n - contigs_list (list): list of contigs in a graph\n - output_file (str): name of the fasta file return\\n\n Return:\n - fasta (fasta file): write fasta file for contigs\n \"\"\"\n with open(f\"{output_file}.fasta\", \"w\", encoding='utf-8') as fasta:\n # extract number of contig and contig\n for index,contig in enumerate(contigs_list):\n # write a fasta file\n fasta.write(\">contig_\" + str(index) + \" len=\" + str(contig[1]) +\n \"\\n\" + fill(contig[0]) + \"\\n\")\n return fasta\n\ndef fill(text, width=80):\n \"\"\"Split text with a line return to respect fasta format\"\"\"\n return os.linesep.join(text[i:i+width] for i in range(0, len(text), width))\n\ndef draw_graph(graph, graphimg_file):\n \"\"\"Draw the graph\n \"\"\"\n fig, ax = plt.subplots()\n elarge = [(u, v) for (u, v, d) in graph.edges(data=True) if d['weight'] > 3]\n\n esmall = [(u, v) for (u, v, d) in graph.edges(data=True) if d['weight'] <= 3]\n pos = nx.random_layout(graph)\n nx.draw_networkx_nodes(graph, pos, node_size=6)\n nx.draw_networkx_edges(graph, pos, edgelist=elarge, width=6)\n nx.draw_networkx_edges(graph, pos, edgelist=esmall, width=6, alpha=0.5,\n edge_color='b', style='dashed')\n plt.savefig(graphimg_file)\n\n\ndef save_graph(graph, graph_file):\n \"\"\"Save the graph with pickle\n \"\"\"\n with open(graph_file, \"wt\") as save:\n pickle.dump(graph, save)\n\n\n#==============================================================\n# Main program\n#==============================================================\ndef main():\n \"\"\"\n Main program function\n \"\"\"\n # Get arguments\n args = get_arguments()\n # Build k-mers dictionnary and the graph with it\n print(f\"Get sequences and dictionnary of k-mers in ... {args.fastq_file}\")\n kmer_dictionnary = build_kmer_dict(args.fastq_file, args.kmer_size)\n print(\"Build De Bruijn's graph ...\")\n graph = build_graph(kmer_dictionnary)\n # Simplify the graph with remove of bubles\n graph = simplify_bubbles(graph)\n # Determine the starting node\n starting_nodes = get_starting_nodes(graph)\n #Determine the ending node\n sink_nodes = get_sink_nodes(graph)\n # Clear the graph of non informative entries\n graph = solve_entry_tips(graph, starting_nodes)\n # Clear the graph of non informative outputs\n graph = solve_out_tips(graph, sink_nodes)\n #Get contigs from the graph and save it in fasta file\n print(\"Get contigs and build the fasta file ...\")\n contigs = get_contigs(graph, starting_nodes, sink_nodes)\n save_contigs(contigs, args.output_file)\n # Fonctions de dessin du graphe\n # A decommenter si vous souhaitez visualiser un petit\n # graphe\n # Plot the graph\n if args.graphimg_file:\n draw_graph(graph, args.graphimg_file)\n # Save the graph in file\n if args.graph_file:\n save_graph(graph, args.graph_file)\n\nif __name__ == '__main__':\n main()\n","sub_path":"debruijn/debruijn.py","file_name":"debruijn.py","file_ext":"py","file_size_in_byte":15712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"281598534","text":"# Copyright 2017-present Samsung Electronics Co., Ltd. and other contributors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport base\nimport json\n\nfrom API.common import console, paths, utils\n\n\nclass Application(base.ApplicationBase):\n '''\n IoT.js application.\n '''\n def __init__(self, options):\n super(self.__class__, self).__init__('iotjs', 'iotjs', options)\n\n def get_image(self):\n '''\n Return the path to the binary.\n '''\n return utils.join(paths.IOTJS_BUILD_PATH, 'iotjs') % self.buildtype\n\n def get_image_stack(self):\n '''\n Return the path to the stack binary.\n '''\n return utils.join(paths.IOTJS_BUILD_STACK_PATH, 'iotjs') % self.buildtype\n\n def get_target_profile_mapfile(self):\n '''\n Return the path to the target profile map file.\n '''\n return paths.IOTJS_TARGET_MAP_FILE_PATH\n\n def get_minimal_profile_mapfile(self):\n '''\n Return the path to the minimal profile map file.\n '''\n return paths.IOTJS_MINIMAL_MAP_FILE_PATH\n\n def get_home_dir(self):\n '''\n Return the path to the application files.\n '''\n return paths.IOTJS_APPS_PATH\n\n def get_install_dir(self):\n '''\n Return the path to where the application files should be copied.\n '''\n return utils.join(paths.NUTTX_APPS_SYSTEM_PATH, 'iotjs')\n\n def get_test_dir(self):\n '''\n Return the path to the application test files.\n '''\n return paths.IOTJS_TEST_PATH\n\n def get_config_file(self):\n '''\n Return the path to OS configuration file.\n '''\n return utils.join(paths.CONFIG_PATH, 'iotjs.config')\n\n def get_romfs_file(self):\n '''\n Return the path of the generated ROMFS image.\n '''\n utils.generate_romfs(paths.IOTJS_PATH, paths.IOTJS_TEST_PATH)\n\n return utils.join(paths.IOTJS_PATH, 'nsh_romfsimg.h')\n\n def __apply_heap_patches(self, device, revert=False):\n '''\n Apply memstat patches to measure the memory consumption of IoT.js\n '''\n if device.get_type() in ['stm32f4dis', 'artik053']:\n iotjs_memstat_patch = utils.join(paths.PATCHES_PATH, 'iotjs-memstat.diff')\n utils.patch(paths.IOTJS_PATH, iotjs_memstat_patch, revert)\n\n libtuv_memstat_patch = utils.join(paths.PATCHES_PATH, 'libtuv-memstat.diff')\n utils.patch(paths.IOTJS_LIBTUV_PATH, libtuv_memstat_patch, revert)\n utils.execute(paths.IOTJS_LIBTUV_PATH, 'git', ['add', '-u'])\n\n jerry_memstat_patch = utils.join(paths.PATCHES_PATH, 'jerry-memstat.diff')\n utils.patch(paths.IOTJS_JERRY_PATH, jerry_memstat_patch, revert)\n utils.execute(paths.IOTJS_JERRY_PATH, 'git', ['add', '-u'])\n\n def __apply_stack_patches(self, device, revert=False):\n '''\n Apply stack patch to measure the stack consumption of IoT.js\n '''\n if device.get_type() == 'rpi2':\n iotjs_stack_patch = utils.join(paths.PATCHES_PATH, 'iotjs-stack.diff')\n utils.patch(paths.IOTJS_PATH, iotjs_stack_patch, revert)\n\n if device.get_type() == 'stm32f4dis':\n iotjs_stack_nuttx_patch = utils.join(paths.PATCHES_PATH, 'iotjs-stack-nuttx.diff')\n utils.patch(paths.IOTJS_PATH, iotjs_stack_nuttx_patch, revert)\n\n def build(self, device):\n '''\n Build IoT.js for the target device/OS and for Raspberry Pi 2.\n '''\n\n # prebuild the OS\n os = device.get_os()\n os.prebuild(self)\n\n utils.rmtree(paths.IOTJS_MAP_DIR_PATH)\n utils.mkdir(paths.IOTJS_MAP_DIR_PATH)\n\n build_flags = [\n '--clean',\n '--buildtype=%s' % self.buildtype,\n '--target-arch=arm',\n '--target-os=%s' % os.get_name(),\n ]\n\n # Step 1: Set the appropriate build flags for the targets.\n if device.get_type() == 'stm32f4dis':\n build_flags.append('--target-board=%s' % device.get_type())\n build_flags.append('--jerry-heaplimit=56')\n build_flags.append('--no-parallel-build')\n build_flags.append('--nuttx-home=%s' % paths.NUTTX_PATH)\n\n profile = utils.join(paths.IOTJS_TEST_PROFILES_PATH, 'nuttx.profile')\n mapfile = utils.join(paths.NUTTX_PATH, \"arch/arm/src/nuttx.map\")\n\n elif device.get_type() == 'rpi2':\n build_flags.append('--target-board=%s' % device.get_type())\n\n profile = utils.join(paths.IOTJS_TEST_PROFILES_PATH, 'rpi2-linux.profile')\n mapfile = utils.join(paths.IOTJS_BUILD_PATH % self.buildtype, \"../iotjs.map\")\n\n elif device.get_type() == 'artik053':\n profile = utils.join(paths.IOTJS_TEST_PROFILES_PATH, 'tizenrt.profile')\n mapfile = utils.join(paths.TIZENRT_BUILD_PATH, \"output/bin/tinyara.map\")\n\n else:\n console.fail('Non-minimal IoT.js build failed, unsupported '\n 'device (%s)!' % device.get_type())\n\n # Step 2: Create minimal profile build for the binary size measurement.\n build_flags.append('--profile=%s' % paths.IOTJS_MINIMAL_PROFILE_PATH)\n\n # Note: IoT.js is built by TizenRT in case of artik053.\n if device.get_type() in ['stm32f4dis', 'rpi2']:\n utils.execute(paths.IOTJS_PATH, 'tools/build.py', build_flags)\n\n os.build(self, self.buildtype, build_flags, 'all')\n utils.copy_file(mapfile, paths.IOTJS_MINIMAL_MAP_FILE_PATH)\n\n # Step 3: Create target specific profile build for the binary size measurement.\n os.prebuild(self)\n\n build_flags = build_flags[:-1]\n build_flags.append('--profile=%s' % profile)\n\n if device.get_type() in ['stm32f4dis', 'rpi2']:\n utils.execute(paths.IOTJS_PATH, 'tools/build.py', build_flags)\n\n os.build(self, self.buildtype, build_flags, 'all')\n utils.copy_file(mapfile, paths.IOTJS_TARGET_MAP_FILE_PATH)\n\n # Step 4: Create target specific profile with patches for the tests.\n self.__apply_heap_patches(device)\n\n if device.get_type() in ['stm32f4dis', 'artik053']:\n self.__apply_stack_patches(device)\n\n os.prebuild(self)\n\n build_flags_heap = list(build_flags)\n build_flags_heap.append('--jerry-memstat')\n if device.get_type() == 'rpi2':\n build_flags_heap.append('--compile-flag=-g')\n build_flags_heap.append('--jerry-compile-flag=-g')\n\n if device.get_type() in ['stm32f4dis', 'rpi2']:\n utils.execute(paths.IOTJS_PATH, 'tools/build.py', build_flags_heap)\n\n os.build(self, self.buildtype, build_flags_heap, 'all')\n\n # Revert all the memstat patches from the project.\n self.__apply_heap_patches(device, revert=True)\n\n # Build the application to stack consumption check\n if device.get_type() == 'rpi2':\n self.__apply_stack_patches(device)\n build_flags.append('--builddir=%s' % paths.IOTJS_BUILD_STACK_DIR)\n utils.execute(paths.IOTJS_PATH, 'tools/build.py', build_flags)\n\n self.__apply_stack_patches(device, revert=True)\n\n\n def __in_dictlist(self, key, value, dictlist):\n for this in dictlist:\n if this[key] == value:\n return this\n return {}\n\n def __add_test_to_skip(self, os_name, test, reason):\n skip_os = test['skip'] if 'skip' in test else []\n\n if not ('all' and os_name) in skip_os:\n test['reason'] = reason\n skip_os.append(os_name)\n test['skip'] = skip_os\n\n def skip_test(self, test, os_name):\n '''\n Determine if a test should be skipped.\n '''\n skip_list = test.get('skip', [])\n\n for i in ['all', os_name, 'stable']:\n if i in skip_list:\n return True\n\n return False\n\n def read_testsets(self, device):\n '''\n Read all the tests\n '''\n\n # Read testsets\n testsets_file = utils.join(paths.IOTJS_TEST_PATH, 'testsets.json')\n testsets = {}\n\n with open(testsets_file, 'r') as testsets_p:\n testsets = json.load(testsets_p)\n\n # Read skip file\n skip_file = utils.join(paths.PROJECT_ROOT, 'API/testrunner/iotjs-skiplist.json')\n skip_list = self.get_skiplist(skip_file)\n skip_tests = skip_list[device.get_type()]['testfiles']\n skip_testsets = skip_list[device.get_type()]['testsets']\n\n os = device.get_os()\n os_name = os.get_name()\n\n # Update testset\n for testset in testsets:\n skip_testset = self.__in_dictlist('name', testset, skip_testsets)\n\n if skip_testset:\n for test in testsets[testset]:\n self.__add_test_to_skip(os_name, test, skip_testset['reason'])\n\n else:\n for skip_test in skip_tests:\n target_test = self.__in_dictlist('name', skip_test['name'], testsets[testset])\n\n if target_test:\n self.__add_test_to_skip(os_name, target_test, skip_test['reason'])\n\n return testsets\n","sub_path":"API/application/iotjs.py","file_name":"iotjs.py","file_ext":"py","file_size_in_byte":9660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"101120847","text":"# coding=utf-8\n# ------------------------------------\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n# ------------------------------------\n\nfrom azure.core.async_paging import AsyncItemPaged\n\n\nclass AnalyzeHealthcareEntitiesResultAsync(AsyncItemPaged):\n def __init__(self, *args, **kwargs):\n self.model_version = kwargs.pop('model_version')\n self.statistics = kwargs.pop('statistics')\n super(AnalyzeHealthcareEntitiesResultAsync, self).__init__(*args, **kwargs)\n\n\nclass AnalyzeResultAsync(AsyncItemPaged):\n def __init__(self, *args, **kwargs):\n self.statistics = kwargs.pop('statistics', None)\n super(AnalyzeResultAsync, self).__init__(*args, **kwargs)\n","sub_path":"sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_async_paging.py","file_name":"_async_paging.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"358213291","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.5 (62131)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.5-i386/egg/shabti/templates/moinmoin/data/moin/config/wikifarm/farmconfig.py\n# Compiled at: 2010-04-25 11:53:22\n\"\"\"\n MoinMoin - Configuration for a wiki farm\n\n If you run a single wiki only, you can keep the \"wikis\" list \"as is\"\n (it has a single rule mapping all requests to mywiki.py).\n\n Note that there are more config options than you'll find in\n the version of this file that is installed by default; see\n the module MoinMoin.config.multiconfig for a full list of names and their\n default values.\n\n Also, the URL http://moinmo.in/HelpOnConfiguration has\n a list of config options.\n\"\"\"\nwikis = [\n ('mywiki', '.*')]\nfrom MoinMoin.config import multiconfig, url_prefix_static\n\nclass FarmConfig(multiconfig.DefaultConfig):\n navi_bar = [\n 'RecentChanges',\n 'FindPage',\n 'HelpContents']\n theme_default = 'modern'\n language_default = 'en'\n page_category_regex = '(?PCategory(?P\\\\S+))'\n page_dict_regex = '(?P(?P\\\\S+)Dict)'\n page_group_regex = '(?P(?P\\\\S+)Group)'\n page_template_regex = '(?P(?P\\\\S+)Template)'\n show_hosts = 1\n show_interwiki = 1\n logo_string = ''","sub_path":"pycfiles/Shabti-0.4.4-py2.5/farmconfig.py","file_name":"farmconfig.py","file_ext":"py","file_size_in_byte":1350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"380577821","text":"import pandas as pd\r\nimport numpy as np\r\nimport sys\r\nimport time\r\nstart = time.time()\r\n#wait to do\r\n# correlation\r\n# ADAM\r\n#col_pay = ['pay_0', 'pay_2', 'pay_3', 'pay_4', 'pay_5', 'pay_6']\r\n#df[col_pay] = df[col_pay].apply(lambda x: x+2)\r\nclass Logistic_Regression():\r\n def __init__(self):\r\n pass\r\n def parameter_init(self, dim):\r\n self.b = 0\r\n self.W = np.zeros((dim, 1))\r\n\r\n def feature_scaling(self, X, train=False): \r\n if train:\r\n self.min = np.min(X, axis=0)\r\n self.max = np.max(X, axis=0)\r\n return (X - self.min) / (self.max - self.min+10**-20)\r\n \r\n def predict(self, X): \r\n return sigmoid(np.dot(X, self.W) + self.b)\r\n \r\n def RMSELoss(self, X, Y):\r\n return np.sqrt(np.mean((Y - self.predict(X))** 2) )\r\n \r\n def do_predict(self, X):\r\n threshold = 0.43\r\n X = self.feature_scaling(X, train=True)\r\n Y_pred = self.predict(X)\r\n Y_pred[Y_pred= threshold] = 1\r\n return Y_pred\r\n def train(self, X, Y, valid_X, valid_Y, epochs=10000, lr=0.01): \r\n \r\n batch_size = X.shape[0]\r\n self.parameter_init(X.shape[1])\r\n X = self.feature_scaling(X, train=True)\r\n X=X\r\n lr_b = 0\r\n lr_W = np.zeros((X.shape[1], 1))\r\n #accc=[]\r\n losss=[]\r\n for epoch in range(epochs):\r\n # mse loss\r\n grad_b = -np.sum(Y - self.predict(X))\r\n grad_W = -np.dot(X.T, (Y - self.predict(X)))\r\n\r\n # adagrad\r\n lr_b += grad_b ** 2\r\n lr_W += grad_W ** 2 \r\n\r\n #update\r\n self.b = self.b - lr / ( np.sqrt(lr_b) + 10**-20) * grad_b\r\n self.W = self.W - lr / ( np.sqrt(lr_W) + 10**-20) * grad_W\r\n #calculating loss = cross entropy\r\n loss = -np.mean(Y*np.log(self.predict(X))+(1-Y)*np.log(1-self.predict(X))) \r\n losss.append(loss)\r\n print('epoch:{}\\n Loss:{}\\n'.format(epoch+1, loss))\r\n return self.do_predict(X), self.W, self.b, losss\r\ndef OneHotEncoding(df):\r\n a = pd.get_dummies(df['SEX'],prefix='SEX')\r\n b = pd.get_dummies(df['EDUCATION'],prefix='EDUCATION')\r\n c = pd.get_dummies(df['MARRIAGE'],prefix='MARRIAGE')\r\n d = pd.get_dummies(df['PAY_0'],prefix='PAY_0')\r\n i = pd.get_dummies(df['PAY_6'],prefix='PAY_6')\r\n df.drop(labels=[\"SEX\",\"EDUCATION\", \"MARRIAGE\", 'PAY_0','PAY_6'],axis=\"columns\",inplace=True)\r\n df = pd.concat([df,a,b,c,d,i],axis=1)\r\n return df\r\ndef OneHotEncoding2(df):\r\n a = pd.get_dummies(df['SEX'],prefix='SEX')\r\n b = pd.get_dummies(df['EDUCATION'],prefix='EDUCATION')\r\n c = pd.get_dummies(df['MARRIAGE'],prefix='MARRIAGE')\r\n df.drop(labels=[\"SEX\",\"EDUCATION\", \"MARRIAGE\"],axis=\"columns\",inplace=True)\r\n df = pd.concat([df,a,b,c],axis=1)\r\n return df\r\ndef sigmoid(z):\r\n return 1/(1+np.exp(-1*z))\r\n#df = pd.read_csv('train_x.csv',encoding='big5')\r\ndf = pd.read_csv(sys.argv[1],encoding='big5')\r\ndf = OneHotEncoding(df)\r\nX_train = df.values\r\n#train_Y = pd.read_csv('train_y.csv',encoding='big5')\r\ntrain_Y = pd.read_csv(sys.argv[2],encoding='big5')\r\n\r\nY_train = train_Y.values\r\nmodel = Logistic_Regression()\r\nloss=[]\r\nY1,W,b, loss = model.train(X_train,Y_train,X_train,Y_train)\r\nprint(\"Accuracy\")\r\nright=0\r\nfor i in range(20000):\r\n if (Y_train[i,0] == Y1[i,0]):\r\n right+=1\r\nprint(right/20000)\r\n#Save model\r\nnp.save('model.npy',W)\r\nnp.save('modelb.npy',b)\r\n#W1 = np.load('model_0.81720.npy') \r\n#test data\r\n#test_X = pd.read_csv('test_x.csv', encoding='big5')\r\ntest_X = pd.read_csv(sys.argv[3], encoding='big5')\r\n\r\ntest_X = OneHotEncoding(test_X)\r\na=pd.DataFrame({\"PAY_6_8\":[0]*10000})\r\ntest_X = pd.concat([test_X, a],axis=1)\r\nX_test = test_X.values\r\nY_test = model.do_predict(X_test)\r\nY_test = Y_test.astype(int)\r\ncount=0\r\nfor i in range(10000):\r\n if(Y_test[i,0]==0):\r\n count+=1\r\n#Output\r\na=[]\r\nfor i in range(10000):\r\n a.append(\"id_\"+str(i))\r\nId = pd.DataFrame(a,columns=[\"id\"])\r\nvalue = pd.DataFrame({\"Value\":[0]*10000})\r\nresult = pd.concat([Id, value], axis=1)\r\nresult['Value'] = Y_test\r\n#result.to_csv('ans.csv', index=False, encoding='big5')\r\nresult.to_csv(sys.argv[4], index=False, encoding='big5')\r\nprint(time.time()-start)\r\n","sub_path":"hw2/Logistic_Regression.py","file_name":"Logistic_Regression.py","file_ext":"py","file_size_in_byte":4287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"625442268","text":"# CHALLENGE PROBLEM: \n#\n# Use your check_sudoku function as the basis for solve_sudoku(): a\n# function that takes a partially-completed Sudoku grid and replaces\n# each 0 cell with an integer in the range 1..9 in such a way that the\n# final grid is valid.\n#\n# There are many ways to cleverly solve a partially-completed Sudoku\n# puzzle, but a brute-force recursive solution with backtracking is a\n# perfectly good option. The solver should return None for broken\n# input, False for inputs that have no valid solutions, and a valid\n# 9x9 Sudoku grid containing no 0 elements otherwise. In general, a\n# partially-completed Sudoku grid does not have a unique solution. You\n# should just return some member of the set of solutions.\n#\n# A solve_sudoku() in this style can be implemented in about 16 lines\n# without making any particular effort to write concise code.\n\n# solve_sudoku should return None\n\nimport copy\n\nill_formed = [[5,3,4,6,7,8,9,1,2],\n [6,7,2,1,9,5,3,4,8],\n [1,9,8,3,4,2,5,6,7],\n [8,5,9,7,6,1,4,2,3],\n [4,2,6,8,5,3,7,9], # <---\n [7,1,3,9,2,4,8,5,6],\n [9,6,1,5,3,7,2,8,4],\n [2,8,7,4,1,9,6,3,5],\n [3,4,5,2,8,6,1,7,9]]\n\n# solve_sudoku should return valid unchanged\nvalid = [[5,3,4,6,7,8,9,1,2],\n [6,7,2,1,9,5,3,4,8],\n [1,9,8,3,4,2,5,6,7],\n [8,5,9,7,6,1,4,2,3],\n [4,2,6,8,5,3,7,9,1],\n [7,1,3,9,2,4,8,5,6],\n [9,6,1,5,3,7,2,8,4],\n [2,8,7,4,1,9,6,3,5],\n [3,4,5,2,8,6,1,7,9]]\n\n# solve_sudoku should return False\ninvalid = [[5,3,4,6,7,8,9,1,2],\n [6,7,2,1,9,5,3,4,8],\n [1,9,8,3,8,2,5,6,7],\n [8,5,9,7,6,1,4,2,3],\n [4,2,6,8,5,3,7,9,1],\n [7,1,3,9,2,4,8,5,6],\n [9,6,1,5,3,7,2,8,4],\n [2,8,7,4,1,9,6,3,5],\n [3,4,5,2,8,6,1,7,9]]\n\n# solve_sudoku should return a \n# sudoku grid which passes a \n# sudoku checker. There may be\n# multiple correct grids which \n# can be made from this starting \n# grid.\neasy = [[2,9,0,0,0,0,0,7,0],\n [3,0,6,0,0,8,4,0,0],\n [8,0,0,0,4,0,0,0,2],\n [0,2,0,0,3,1,0,0,7],\n [0,0,0,0,8,0,0,0,0],\n [1,0,0,9,5,0,0,6,0],\n [7,0,0,0,9,0,0,0,1],\n [0,0,1,2,0,0,3,0,6],\n [0,3,0,0,0,0,0,5,9]]\n\n# Note: this may timeout \n# in the Udacity IDE! Try running \n# it locally if you'd like to test \n# your solution with it.\n# \nhard = [[1,0,0,0,0,7,0,9,0],\n [0,3,0,0,2,0,0,0,8],\n [0,0,9,6,0,0,5,0,0],\n [0,0,5,3,0,0,9,0,0],\n [0,1,0,0,8,0,0,0,2],\n [6,0,0,0,0,4,0,0,0],\n [3,0,0,0,0,0,0,1,0],\n [0,4,0,0,0,0,0,0,7],\n [0,0,7,0,0,0,3,0,0]]\n\n\ndef check_sudoku (grid): \n \n if len(grid) != 9:\n return None\n \n for row in grid:\n \n if len(row) != 9:\n return None\n \n seen = []\n for num in row:\n \n if num == 0:\n continue\n \n if num < 1 or num > 9:\n return None\n # Should be no duplicate for non-zero\n # This also test whether all 1 - 9 will be inside the range\n if num in seen:\n return False;\n else:\n seen.append(num)\n \n # Each column should have all 1 - 9\n for i in range(0, 9):\n seen = []\n for j in range(0,9):\n \n num = grid[i][j]\n \n if num == 0:\n continue\n\n if num in seen:\n return False;\n else:\n seen.append(num)\n \n # Each square should have all 1 - 9\n \n for i in range(0, 3):\n rowMin = i * 3\n for j in range(0, 3):\n colMin = j * 3\n seen = []\n for row in range(rowMin, rowMin + 3):\n for col in range(colMin, colMin + 3):\n num = grid[row][col]\n \n if num == 0:\n continue\n \n if num in seen:\n return False;\n else:\n seen.append(num) \n\n return True\n\n\ndef get_sub_id(i, j):\n return int(i / 3) * 3 + int(j / 3)\n\ndef solve_sudoku (_grid):\n\n grid = copy.deepcopy(_grid)\n\n for i in range(0, 9):\n for j in range(0, 9):\n cell = grid[i][j]\n if isinstance(cell, list):\n if len(cell) == 1:\n grid[i][j] = cell[0]\n elif len(cell) == 0:\n return None\n else:\n grid[i][j] = 0\n\n check = check_sudoku(grid)\n if check != True:\n return check\n \n unsolveCount = 0\n \n possible = []\n \n rowSeen = []\n colSeen = []\n subSeen = []\n rowCandCount = []\n colCandCount = []\n subCandCount = []\n \n for i in range(0, 9):\n rowSeen.append([])\n colSeen.append([])\n subSeen.append([])\n rowCandCount.append([])\n colCandCount.append([])\n subCandCount.append([])\n for j in range(0, 10):\n rowCandCount[i].append(0)\n colCandCount[i].append(0)\n subCandCount[i].append(0)\n \n for i in range(0, 9):\n for j in range(0, 9):\n if grid[i][j] == 0:\n grid[i][j] = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n for k in range(1, 10):\n rowCandCount[i][k] += 1\n colCandCount[j][k] += 1\n subCandCount[get_sub_id(i, j)][k] += 1 \n unsolveCount += 1\n else:\n rowSeen[i].append(grid[i][j])\n colSeen[j].append(grid[i][j])\n subSeen[get_sub_id(i, j)].append(grid[i][j])\n rowCandCount[i][grid[i][j]] += 1\n colCandCount[j][grid[i][j]] += 1\n subCandCount[get_sub_id(i, j)][grid[i][j]] += 1 \n\n while unsolveCount > 0:\n\n gridChanged = False\n\n for i in range(0, 9):\n for j in range(0, 9):\n cell = grid[i][j]\n if isinstance(cell, list):\n oldCell = list(cell)\n cell = [x for x in cell if x not in rowSeen[i]]\n cell = [x for x in cell if x not in colSeen[j]]\n cell = [x for x in cell if x not in subSeen[get_sub_id(i, j)]]\n\n for val in oldCell:\n if val not in cell:\n rowCandCount[i][val] -= 1\n colCandCount[j][val] -= 1\n subCandCount[get_sub_id(i, j)][val] -= 1\n gridChanged = True\n \n if len(cell) == 1:\n grid[i][j] = cell[0]\n unsolveCount -= 1\n rowSeen[i].append(grid[i][j])\n colSeen[j].append(grid[i][j])\n subSeen[get_sub_id(i, j)].append(grid[i][j])\n else:\n select = -1\n for val in cell:\n if rowCandCount[i][val] == 1 or colCandCount[j][val] == 1 or subCandCount[get_sub_id(i, j)][val] == 1:\n select = val\n break\n\n if select == -1:\n grid[i][j] = cell\n else:\n gridChanged = True\n grid[i][j] = select\n rowSeen[i].append(select)\n colSeen[j].append(select)\n subSeen[get_sub_id(i, j)].append(select)\n unsolveCount -= 1\n \n #print(grid)\n if not gridChanged:\n # Now, we have to do a more heavy-weight prune.\n # We try to select a value from an undecided cell. And if it reaches a dead end,\n # we will prune this value. Otherwise we get the result.\n # After this prune, we go back to the above light-weight prune.\n #print(\"Selection start\")\n found = False\n for i in range(0, 9):\n for j in range(0, 9):\n cell = grid[i][j]\n if isinstance(cell, list):\n\n if len(cell) == 0:\n return None\n \n for val in cell:\n grid[i][j] = val\n result = solve_sudoku(grid)\n\n if result == None or result == False:\n # this selection fails, we need to prune it\n break\n else:\n return result\n cell.remove(val)\n grid[i][j] = cell\n\n\n rowCandCount[i][val] -= 1\n colCandCount[j][val] -= 1\n subCandCount[get_sub_id(i, j)][val] -= 1 \n \n found = True\n break\n if found:\n break\n \n #print(unsolveCount) \n \n #TODO: we currently just did a prune, which cannot lead us to the final solution.\n\n return grid\n\nassert check_sudoku(solve_sudoku(easy)) == True\nassert check_sudoku(solve_sudoku(hard)) == True\n\n# Extreme case\nempty= []\nfor i in range(0, 9):\n empty.append([])\n for j in range(0, 9):\n empty[i].append(0)\nassert check_sudoku(solve_sudoku(empty)) == True\n\nrandTestNum = 5\nfor round in range(0, randTestNum):\n i = randint(0, 8)\n j = randint(0, 8)\n # Actually, I think soduku solver is not a good target for random testing,\n # because it is so simple and we can simply write good test cases to test it.\n","sub_path":"Python/solve_sudoku.py","file_name":"solve_sudoku.py","file_ext":"py","file_size_in_byte":10056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"534728071","text":"import sys\r\n\r\ns=open('sudoko.txt', 'r')\r\npuzzle=[]\r\nreference=set('123456789')\r\nprint(\"Sudoko grid\")\r\nfor line in s:\r\n print( line.rstrip('\\n').split(' ') )\r\n puzzle.append(line.rstrip('\\n').split(' '))\r\n\r\nprint(\"\\nCheck Rows\")\r\nfor row in range(0, 9):\r\n check=set(puzzle[row][0:9])\r\n if (check-reference == set()) and (reference-check == set()): print('Row %d Good' % row) \r\n else: print('Row %d Bad' % row)\r\n \r\nprint(\"\\nCheck Columns\")\r\nfor col in range(0, 9):\r\n temp = [ row[col] for row in puzzle ]\r\n #check=set(temp)\r\n if (set(temp)-reference == set()) and (reference-set(temp) == set()): print('Col %d Good' % col) \r\n else: print('Col %d Bad' % col)\r\n\r\nprint(\"\\nCheck 3x3 boxes\")\r\nbox=0\r\nfor row in range(0,9,3):\r\n check=[]; temp=[]\r\n for col in range(0,9,3):\r\n check=[]; temp=[]\r\n for coffset in range(0,3):\r\n for roffset in range(0,3):\r\n temp.append(puzzle[row+roffset][col+coffset])\r\n if (set(temp)-reference == set()) and (reference-set(temp) == set()): print('Box %d Good' % box)\r\n else: print('Box %d Bad' % box)\r\n box=box+1","sub_path":"Suduko/suduko.py","file_name":"suduko.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"91716421","text":"from scipy import stats\nimport numpy as np\n\n\ndef get_boundaries_iqr(df_in, col_name, iqr_coeff=1.5):\n \"\"\" Getting a df_in[col_name] 'normal' values range based on the interquartile range.\n Points outside the range might be considered as outliers\"\"\"\n q1 = df_in[col_name].quantile(0.25)\n q3 = df_in[col_name].quantile(0.75)\n iqr = q3 - q1 #Interquartile range\n min_ = q1 - iqr_coeff * iqr\n max_ = q3 + iqr_coeff * iqr\n return min_, max_\n\n\ndef mad(x):\n \"\"\" Median absolute deviation \"\"\"\n med = np.median(x, axis=None)\n mad = np.median(np.abs(x - med))\n return mad\n\n\ndef modified_zscore(x):\n \"\"\"\n Modified z-score calculation.\n Adaptation of regular z-score to the small sample size (number of data points) case.\n Points with with modified_zscore > specific threshold (~3.0-3.5) might be considered as outliers\n\n Based on:\n \"NIST/SEMATECH e-Handbook of Statistical Methods\",\n https://www.itl.nist.gov/div898/handbook/eda/section3/eda35h.htm\n \"\"\"\n res = 0.6745 * (x - np.median(x)) / mad(x)\n return res\n\n","sub_path":"zscore.py","file_name":"zscore.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"429078553","text":"import os\nfrom options.test_options import TestOptions\nfrom data import CreateDataLoader\nfrom models import create_model\nfrom util.visualizer import save_images\nfrom util import html\n\n\"\"\"\nCopyright (C) 2018 NVIDIA Corporation. All rights reserved.\nLicensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).\n\"\"\"\n#from __future__ import print_function\n#from utils import get_config, get_data_loader_folder, pytorch03_to_pytorch04, load_inception\n#from trainer import MUNIT_Trainer, UNIT_Trainer\nfrom torch import nn\nfrom scipy.stats import entropy\nimport torch.nn.functional as F\n#import argparse\n#from torch.autograd import Variable\n#from data import ImageFolder\nimport numpy as np\n#import torchvision.utils as vutils\ntry:\n from itertools import izip as zip\nexcept ImportError: # will be 3.x series\n pass\nimport sys\nimport torch\nimport os\nfrom torchvision.models.inception import inception_v3\nfrom tqdm import tqdm\nfrom torch.autograd import Variable\nfrom scipy import linalg\n\ndef read_stats_file(filepath):\n \"\"\"read mu, sigma from .npz\"\"\"\n if filepath.endswith('.npz'):\n f = np.load(filepath)\n m, s = f['mu'][:], f['sigma'][:]\n f.close()\n else:\n raise Exception('ERROR! pls pass in correct npz file %s' % filepath)\n return m, s\n\ndef calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6):\n \"\"\"Numpy implementation of the Frechet Distance.\n The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1)\n and X_2 ~ N(mu_2, C_2) is\n d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)).\n Stable version by Dougal J. Sutherland.\n Params:\n -- mu1 : Numpy array containing the activations of a layer of the\n inception net (like returned by the function 'get_predictions')\n for generated samples.\n -- mu2 : The sample mean over activations, precalculated on an\n representative data set.\n -- sigma1: The covariance matrix over activations for generated samples.\n -- sigma2: The covariance matrix over activations, precalculated on an\n representative data set.\n Returns:\n -- : The Frechet Distance.\n \"\"\"\n\n mu1 = np.atleast_1d(mu1)\n mu2 = np.atleast_1d(mu2)\n\n sigma1 = np.atleast_2d(sigma1)\n sigma2 = np.atleast_2d(sigma2)\n\n assert mu1.shape == mu2.shape, \\\n 'Training and test mean vectors have different lengths %s, %s' % (mu1.shape, mu2.shape)\n assert sigma1.shape == sigma2.shape, \\\n 'Training and test covariances have different dimensions %s, %s' % (sigma1.shape, sigma2.shape)\n diff = mu1 - mu2\n # Product might be almost singular\n covmean, _ = linalg.sqrtm(sigma1.dot(sigma2), disp=False)\n if not np.isfinite(covmean).all():\n msg = ('fid calculation produces singular product; '\n 'adding %s to diagonal of cov estimates') % eps\n print(msg)\n offset = np.eye(sigma1.shape[0]) * eps\n covmean = linalg.sqrtm((sigma1 + offset).dot(sigma2 + offset))\n # Numerical error might give slight imaginary component\n if np.iscomplexobj(covmean):\n if not np.allclose(np.diagonal(covmean).imag, 0, atol=1e-3):\n m = np.max(np.abs(covmean.imag))\n raise ValueError('Imaginary component {}'.format(m))\n covmean = covmean.real\n tr_covmean = np.trace(covmean)\n return diff.dot(diff) + np.trace(sigma1) + np.trace(sigma2) - 2 * tr_covmean\n\nclass ScoreModel:\n def __init__(self, mode, cuda=True,\n stats_file='', mu1=0, sigma1=0):\n \"\"\"\n Computes the inception score of the generated images\n cuda -- whether or not to run on GPU\n mode -- image passed in inceptionV3 is normalized by mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]\n and in range of [-1, 1]\n 1: image passed in is normalized by mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]\n 2: image passed in is normalized by mean=[0.500, 0.500, 0.500], std=[0.500, 0.500, 0.500]\n \"\"\"\n # load mu, sigma for calc FID\n self.calc_fid = False\n if stats_file:\n self.calc_fid = True\n self.mu1, self.sigma1 = read_stats_file(stats_file)\n elif type(mu1) == type(sigma1) == np.ndarray:\n self.calc_fid = True\n self.mu1, self.sigma1 = mu1, sigma1\n\n # Set up dtype\n if cuda:\n self.dtype = torch.cuda.FloatTensor\n else:\n if torch.cuda.is_available():\n print(\"WARNING: You have a CUDA device, so you should probably set cuda=True\")\n self.dtype = torch.FloatTensor\n\n # setup image normalization mode\n self.mode = mode\n if self.mode == 1:\n transform_input = True\n elif self.mode == 2:\n transform_input = False\n else:\n raise Exception(\"ERR: unknown input img type, pls specify norm method!\")\n self.inception_model = inception_v3(pretrained=True, transform_input=transform_input).type(self.dtype)\n self.inception_model.eval()\n # self.up = nn.Upsample(size=(299, 299), mode='bilinear', align_corners=False).type(self.dtype)\n\n # remove inception_model.fc to get pool3 output 2048 dim vector\n self.fc = self.inception_model.fc\n self.inception_model.fc = nn.Sequential()\n\n # wrap with nn.DataParallel\n self.inception_model = nn.DataParallel(self.inception_model)\n self.fc = nn.DataParallel(self.fc)\n\n def __forward(self, x):\n \"\"\"\n x should be N x 3 x 299 x 299\n and should be in range [-1, 1]\n \"\"\"\n x = F.interpolate(x, size=(299, 299), mode='bilinear', align_corners=False)\n x = self.inception_model(x)\n pool3_ft = x.data.cpu().numpy()\n\n x = self.fc(x)\n preds = F.softmax(x, 1).data.cpu().numpy()\n return pool3_ft, preds\n\n @staticmethod\n def __calc_is(preds, n_split, return_each_score=False):\n \"\"\"\n regularly, return (is_mean, is_std)\n if n_split==1 and return_each_score==True:\n return (scores, 0)\n # scores is a list with len(scores) = n_img = preds.shape[0]\n \"\"\"\n\n n_img = preds.shape[0]\n # Now compute the mean kl-div\n split_scores = []\n for k in range(n_split):\n part = preds[k * (n_img // n_split): (k + 1) * (n_img // n_split), :]\n py = np.mean(part, axis=0)\n scores = []\n for i in range(part.shape[0]):\n pyx = part[i, :]\n scores.append(entropy(pyx, py))\n split_scores.append(np.exp(np.mean(scores)))\n if n_split == 1 and return_each_score:\n return scores, 0\n return np.mean(split_scores), np.std(split_scores)\n\n @staticmethod\n def __calc_stats(pool3_ft):\n mu = np.mean(pool3_ft, axis=0)\n sigma = np.cov(pool3_ft, rowvar=False)\n return mu, sigma\n\n def get_score_image_tensor(self, imgs_nchw, mu1=0, sigma1=0,\n n_split=10, batch_size=1, return_stats=False,\n return_each_score=False):\n \"\"\"\n param:\n imgs_nchw -- Pytorch Tensor, size=(N,C,H,W), in range of [-1, 1]\n batch_size -- batch size for feeding into Inception v3\n n_splits -- number of splits\n return:\n is_mean, is_std, fid\n mu, sigma of dataset\n\n regularly, return (is_mean, is_std)\n if n_split==1 and return_each_score==True:\n return (scores, 0)\n # scores is a list with len(scores) = n_img = preds.shape[0]\n \"\"\"\n\n n_img = imgs_nchw.shape[0]\n\n assert batch_size > 0\n assert n_img > batch_size\n\n pool3_ft = np.zeros((n_img, 2048))\n preds = np.zeros((n_img, 1000))\n for i in tqdm(range(np.int32(np.ceil(1.0 * n_img / batch_size)))):\n batch_size_i = min((i+1) * batch_size, n_img) - i * batch_size\n batchv = Variable(imgs_nchw[i * batch_size:i * batch_size + batch_size_i, ...].type(self.dtype))\n pool3_ft[i * batch_size:i * batch_size + batch_size_i], preds[i * batch_size:i * batch_size + batch_size_i] = self.__forward(batchv)\n\n # if want to return stats\n # or want to calc fid\n if return_stats or \\\n type(mu1) == type(sigma1) == np.ndarray or self.calc_fid:\n mu2, sigma2 = self.__calc_stats(pool3_ft)\n\n if self.calc_fid:\n mu1 = self.mu1\n sigma1 = self.sigma1\n\n is_mean, is_std = self.__calc_is(preds, n_split, return_each_score)\n\n fid = -1\n if type(mu1) == type(sigma1) == np.ndarray or self.calc_fid:\n fid = calculate_frechet_distance(mu1, sigma1, mu2, sigma2)\n\n if return_stats:\n return is_mean, is_std, fid, mu2, sigma2\n else:\n return is_mean, is_std, fid\n\n def get_score_dataset(self, dataset, mu1=0, sigma1=0,\n n_split=10, batch_size=32, return_stats=False,\n return_each_score=False):\n \"\"\"\n get score from a dataset\n param:\n dataset -- pytorch dataset, img in range of [-1, 1]\n batch_size -- batch size for feeding into Inception v3\n n_splits -- number of splits\n return:\n is_mean, is_std, fid\n mu, sigma of dataset\n\n regularly, return (is_mean, is_std)\n if n_split==1 and return_each_score==True:\n return (scores, 0)\n # scores is a list with len(scores) = n_img = preds.shape[0]\n \"\"\"\n\n n_img = len(dataset)\n dataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size)\n\n pool3_ft = np.zeros((n_img, 2048))\n preds = np.zeros((n_img, 1000))\n for i, batch in tqdm(enumerate(dataloader, 0)):\n batch = batch.type(self.dtype)\n batchv = Variable(batch)\n batch_size_i = batch.size()[0]\n pool3_ft[i * batch_size:i * batch_size + batch_size_i], preds[i * batch_size:i * batch_size + batch_size_i] = self.__forward(batchv)\n\n # if want to return stats\n # or want to calc fid\n if return_stats or \\\n type(mu1) == type(sigma1) == np.ndarray or self.calc_fid:\n mu2, sigma2 = self.__calc_stats(pool3_ft)\n\n if self.calc_fid:\n mu1 = self.mu1\n sigma1 = self.sigma1\n\n is_mean, is_std = self.__calc_is(preds, n_split, return_each_score)\n\n fid = -1\n if type(mu1) == type(sigma1) == np.ndarray or self.calc_fid:\n fid = calculate_frechet_distance(mu1, sigma1, mu2, sigma2)\n\n if return_stats:\n return is_mean, is_std, fid, mu2, sigma2\n else:\n return is_mean, is_std, fid\n\nif __name__ == '__main__':\n opt = TestOptions().parse()\n # hard-code some parameters for test\n opt.num_threads = 1 # test code only supports num_threads = 1\n opt.batch_size = 1 # test code only supports batch_size = 1\n opt.serial_batches = True # no shuffle\n opt.no_flip = True # no flip\n opt.display_id = -1 # no visdom display\n data_loader = CreateDataLoader(opt)\n dataset = data_loader.load_data()\n model = create_model(opt)\n model.setup(opt)\n # create a website\n web_dir = os.path.join(opt.results_dir, opt.name, '%s_%s' % (opt.phase, opt.epoch))\n webpage = html.HTML(web_dir, 'Experiment = %s, Phase = %s, Epoch = %s' % (opt.name, opt.phase, opt.epoch))\n # test with eval mode. This only affects layers like batchnorm and dropout.\n # pix2pix: we use batchnorm and dropout in the original pix2pix. You can experiment it with and without eval() mode.\n # CycleGAN: It should not affect CycleGAN as CycleGAN uses instancenorm without dropout.\n if opt.eval:\n model.eval()\n\n if opt.compute_fid:\n img_list_tensor1 = []\n img_list_tensor2 = []\n IS = []\n all_preds = []\n # if opt.compute_CIS:\n # CIS = []\n\n\n for i, data in enumerate(dataset):\n if i >= opt.num_test:\n break\n model.set_input(data)\n model.test()\n visuals = model.get_current_visuals()\n img_path = model.get_image_paths()\n # get AtoB\n is_AtoB = model.get_AtoB()\n if i % 5 == 0:\n print('processing (%04d)-th image... %s' % (i, img_path))\n save_images(webpage, visuals, img_path, aspect_ratio=opt.aspect_ratio, width=opt.display_winsize)\n\n # 计算IS和CIS\n # 评估指标Inception Score\n\n # if opt.compute_CIS:\n # cur_preds = [] # clear cur_preds in each loop\n\n\n\n if opt.compute_fid:\n if opt.model=='cycle_gan':\n is_fid_model = ScoreModel(mode=2, cuda=True)\n\n # img_list_tensor1.append(visuals['real_A'])\n # real_A_seg = visuals['real_A_seg']\n # real_A_seg_channel3 = torch.cat([real_A_seg, real_A_seg, real_A_seg], dim=1)\n # img_list_tensor1.append(real_A_seg_channel3)\n\n img_list_tensor1.append(visuals['real_A']) if is_AtoB else img_list_tensor1.append(\n visuals['real_B'])\n # real_B_seg = visuals['real_B_seg']\n # real_B_seg_channel3 = torch.cat([real_B_seg, real_B_seg, real_B_seg], dim=1)\n # img_list_tensor1.append(real_B_seg_channel3)\n\n # img_list_tensor2.append(visuals['fake_A'])\n # fake_A_seg = visuals['fake_A_seg']\n # fake_A_seg_channel3 = torch.cat([fake_A_seg, fake_A_seg, fake_A_seg], dim=1)\n # img_list_tensor2.append(fake_A_seg_channel3)\n\n img_list_tensor2.append(visuals['fake_A']) if is_AtoB else img_list_tensor2.append(\n visuals['fake_B'])\n # fake_B_seg = visuals['fake_B_seg']\n # fake_B_seg_channel3 = torch.cat([fake_B_seg, fake_B_seg, fake_B_seg], dim=1)\n # img_list_tensor2.append(fake_B_seg_channel3)\n elif opt.model=='insta_gan' or opt.model=='dense_gan':\n if opt.netG == 'star':\n is_fid_model = ScoreModel(mode=2, cuda=True)\n\n # img_list_tensor1.append(visuals['real_A_img'])\n # real_A_seg = visuals['real_A_seg']\n # real_A_seg_channel3 = torch.cat([real_A_seg, real_A_seg, real_A_seg], dim=1)\n # img_list_tensor1.append(real_A_seg_channel3)\n\n img_list_tensor1.append(visuals['real_A_img']) if is_AtoB else img_list_tensor1.append(\n visuals['real_B_img'])\n # real_B_seg = visuals['real_B_seg']\n # real_B_seg_channel3 = torch.cat([real_B_seg, real_B_seg, real_B_seg], dim=1)\n # img_list_tensor1.append(real_B_seg_channel3)\n\n # img_list_tensor2.append(visuals['fake_A_img'])\n # fake_A_seg = visuals['fake_A_seg']\n # fake_A_seg_channel3 = torch.cat([fake_A_seg, fake_A_seg, fake_A_seg], dim=1)\n # img_list_tensor2.append(fake_A_seg_channel3)\n\n img_list_tensor2.append(visuals['fake_A_img']) if is_AtoB else img_list_tensor2.append(\n visuals['fake_B_img'])\n # fake_B_seg = visuals['fake_B_seg']\n # fake_B_seg_channel3 = torch.cat([fake_B_seg, fake_B_seg, fake_B_seg], dim=1)\n # img_list_tensor2.append(fake_B_seg_channel3)\n else:\n is_fid_model = ScoreModel(mode=2, cuda=True)\n\n # img_list_tensor1.append(visuals['real_A_img'])\n # real_A_seg = visuals['real_A_seg']\n # real_A_seg_channel3 = torch.cat([real_A_seg, real_A_seg, real_A_seg], dim=1)\n # img_list_tensor1.append(real_A_seg_channel3)\n\n img_list_tensor1.append(visuals['real_A_img']) if is_AtoB else img_list_tensor1.append(\n visuals['real_B_img'])\n #img_list_tensor1.append(visuals['real_A_img'])\n #img_list_tensor1.append(visuals['real_B_img'])\n # real_B_seg = visuals['real_B_seg']\n # real_B_seg_channel3 = torch.cat([real_B_seg, real_B_seg, real_B_seg], dim=1)\n # img_list_tensor1.append(real_B_seg_channel3)\n\n # img_list_tensor2.append(visuals['fake_A_img'])\n # fake_A_seg = visuals['fake_A_seg']\n # fake_A_seg_channel3 = torch.cat([fake_A_seg, fake_A_seg, fake_A_seg], dim=1)\n # img_list_tensor2.append(fake_A_seg_channel3)\n\n\n img_list_tensor2.append(visuals['fake_A_img']) if is_AtoB else img_list_tensor2.append(visuals['fake_B_img'])\n #img_list_tensor2.append(visuals['fake_A_img'])\n #img_list_tensor2.append(visuals['fake_B_img'])\n # fake_B_seg = visuals['fake_B_seg']\n # fake_B_seg_channel3 = torch.cat([fake_B_seg, fake_B_seg, fake_B_seg], dim=1)\n # img_list_tensor2.append(fake_B_seg_channel3)\n\n\n else:\n pass\n\n\n\n\n\n\n\n img_list_tensor1 = torch.cat(img_list_tensor1, dim=0)\n img_list_tensor2 = torch.cat(img_list_tensor2, dim=0)\n\n if opt.compute_fid:\n print('Calculating 1st stat ...')\n is_mean1, is_std1, _, mu1, sigma1 = \\\n is_fid_model.get_score_image_tensor(img_list_tensor1, n_split=10, return_stats=True)\n\n print('Calculating 2nd stat ...')\n is_mean2, is_std2, fid = is_fid_model.get_score_image_tensor(img_list_tensor2,\n mu1=mu1, sigma1=sigma1,\n n_split=10)\n\n print('1st IS score =', is_mean1, ',', is_std1)\n print('2nd IS score =', is_mean2, ',', is_std2)\n print('FID =', fid)\n\n # save the website\n webpage.save()\n\n","sub_path":"test_fid.py","file_name":"test_fid.py","file_ext":"py","file_size_in_byte":18198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"141944570","text":"from django.conf.urls import url, include\nfrom rest_framework import routers\nfrom .views import EmployeeViewSet\n\n#User URL's\nempUrls = [\n url('list/', EmployeeViewSet.list),\n url('create/', EmployeeViewSet.post),\n url('matchFace/', EmployeeViewSet.match_face)\n]\n\nurlpatterns = [\n url('emp/', include(empUrls)),\n]","sub_path":"backend/backend/app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"349211015","text":"import itertools\nimport logging\n\nfrom django.db.models import Q\nfrom usaspending_api.awards.v2.filters.filter_helpers import combine_date_range_queryset, total_obligation_queryset\nfrom usaspending_api.awards.v2.filters.location_filter_geocode import geocode_filter_locations\nfrom usaspending_api.common.exceptions import InvalidParameterException\nfrom usaspending_api.references.models import PSC\nfrom usaspending_api.search.filters.postgres.psc import PSCCodes\nfrom usaspending_api.search.filters.postgres.tas import TasCodes, TreasuryAccounts\nfrom usaspending_api.search.helpers.matview_filter_helpers import build_award_ids_filter\nfrom usaspending_api.search.models import SubawardView\nfrom usaspending_api.search.v2 import elasticsearch_helper\nfrom usaspending_api.settings import API_MAX_DATE, API_MIN_DATE, API_SEARCH_MIN_DATE\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef subaward_download(filters):\n \"\"\" Used by the Custom download\"\"\"\n return subaward_filter(filters, for_downloads=True)\n\n\n# TODO: Performance when multiple false values are initially provided\ndef subaward_filter(filters, for_downloads=False):\n queryset = SubawardView.objects.all()\n\n recipient_scope_q = Q(recipient_location_country_code=\"USA\") | Q(recipient_location_country_name=\"UNITED STATES\")\n pop_scope_q = Q(pop_country_code=\"USA\") | Q(pop_country_name=\"UNITED STATES\")\n\n for key, value in filters.items():\n\n if value is None:\n raise InvalidParameterException(\"Invalid filter: \" + key + \" has null as its value.\")\n\n key_list = [\n \"keywords\",\n \"elasticsearch_keyword\",\n \"time_period\",\n \"award_type_codes\",\n \"prime_and_sub_award_types\",\n \"agencies\",\n \"legal_entities\",\n \"recipient_search_text\",\n \"recipient_scope\",\n \"recipient_locations\",\n \"recipient_type_names\",\n \"place_of_performance_scope\",\n \"place_of_performance_locations\",\n \"award_amounts\",\n \"award_ids\",\n \"program_numbers\",\n \"naics_codes\",\n PSCCodes.underscore_name,\n \"contract_pricing_type_codes\",\n \"set_aside_type_codes\",\n \"extent_competed_type_codes\",\n TasCodes.underscore_name,\n TreasuryAccounts.underscore_name,\n ]\n\n if key not in key_list:\n raise InvalidParameterException(\"Invalid filter: \" + key + \" does not exist.\")\n\n if key == \"keywords\":\n\n def keyword_parse(keyword):\n # keyword_ts_vector & award_ts_vector are Postgres TS_vectors.\n # keyword_ts_vector = recipient_name + psc_description + subaward_description\n # award_ts_vector = piid + fain + uri + subaward_number\n filter_obj = Q(keyword_ts_vector=keyword) | Q(award_ts_vector=keyword)\n # Commenting out until NAICS is associated with subawards in DAIMS 1.3.1\n # if keyword.isnumeric():\n # filter_obj |= Q(naics_code__contains=keyword)\n if len(keyword) == 4 and PSC.objects.filter(code__iexact=keyword).exists():\n filter_obj |= Q(product_or_service_code__iexact=keyword)\n\n return filter_obj\n\n filter_obj = Q()\n for keyword in value:\n filter_obj |= keyword_parse(keyword)\n potential_duns = list(filter((lambda x: len(x) > 7 and len(x) < 10), value))\n if len(potential_duns) > 0:\n filter_obj |= Q(recipient_unique_id__in=potential_duns) | Q(\n parent_recipient_unique_id__in=potential_duns\n )\n\n queryset = queryset.filter(filter_obj)\n\n elif key == \"elasticsearch_keyword\":\n keyword = value\n transaction_ids = elasticsearch_helper.get_download_ids(keyword=keyword, field=\"transaction_id\")\n # flatten IDs\n transaction_ids = list(itertools.chain.from_iterable(transaction_ids))\n logger.info(\"Found {} transactions based on keyword: {}\".format(len(transaction_ids), keyword))\n transaction_ids = [str(transaction_id) for transaction_id in transaction_ids]\n queryset = queryset.filter(latest_transaction_id__isnull=False)\n\n # Prepare a SQL snippet to include in the predicate for searching an array of transaction IDs\n sql_fragment = '\"subaward_view\".\"latest_transaction_id\" = ANY(\\'{{{}}}\\'::int[])' # int[] -> int array type\n queryset = queryset.extra(where=[sql_fragment.format(\",\".join(transaction_ids))])\n\n elif key == \"time_period\":\n min_date = API_SEARCH_MIN_DATE\n if for_downloads:\n min_date = API_MIN_DATE\n queryset &= combine_date_range_queryset(value, SubawardView, min_date, API_MAX_DATE)\n\n elif key == \"award_type_codes\":\n queryset = queryset.filter(prime_award_type__in=value)\n\n elif key == \"prime_and_sub_award_types\":\n award_types = value.get(\"sub_awards\")\n if award_types:\n queryset = queryset.filter(award_type__in=award_types)\n\n elif key == \"agencies\":\n # TODO: Make function to match agencies in award filter throwing dupe error\n funding_toptier = Q()\n funding_subtier = Q()\n awarding_toptier = Q()\n awarding_subtier = Q()\n for v in value:\n type = v[\"type\"]\n tier = v[\"tier\"]\n name = v[\"name\"]\n if type == \"funding\":\n if tier == \"toptier\":\n funding_toptier |= Q(funding_toptier_agency_name=name)\n elif tier == \"subtier\":\n if \"toptier_name\" in v:\n funding_subtier |= Q(funding_subtier_agency_name=name) & Q(\n funding_toptier_agency_name=v[\"toptier_name\"]\n )\n else:\n funding_subtier |= Q(funding_subtier_agency_name=name)\n\n elif type == \"awarding\":\n if tier == \"toptier\":\n awarding_toptier |= Q(awarding_toptier_agency_name=name)\n elif tier == \"subtier\":\n if \"toptier_name\" in v:\n awarding_subtier |= Q(awarding_subtier_agency_name=name) & Q(\n awarding_toptier_agency_name=v[\"toptier_name\"]\n )\n else:\n awarding_subtier |= Q(awarding_subtier_agency_name=name)\n\n awarding_queryfilter = Q()\n funding_queryfilter = Q()\n\n # Since these are Q filters, no DB hits for boolean checks\n if funding_toptier:\n funding_queryfilter |= funding_toptier\n if funding_subtier:\n funding_queryfilter |= funding_subtier\n if awarding_toptier:\n awarding_queryfilter |= awarding_toptier\n if awarding_subtier:\n awarding_queryfilter |= awarding_subtier\n\n queryset = queryset.filter(funding_queryfilter & awarding_queryfilter)\n\n elif key == \"legal_entities\":\n # This filter key has effectively become obsolete by recipient_search_text\n msg = 'API request included \"{}\" key. No filtering will occur with provided value \"{}\"'\n logger.info(msg.format(key, value))\n\n elif key == \"recipient_search_text\":\n\n def recip_string_parse(recipient_string):\n upper_recipient_string = recipient_string.upper()\n\n # recipient_name_ts_vector is a postgres TS_Vector\n filter_obj = Q(recipient_name_ts_vector=upper_recipient_string)\n if len(upper_recipient_string) == 9 and upper_recipient_string[:5].isnumeric():\n filter_obj |= Q(recipient_unique_id=upper_recipient_string)\n return filter_obj\n\n filter_obj = Q()\n for recipient in value:\n filter_obj |= recip_string_parse(recipient)\n queryset = queryset.filter(filter_obj)\n\n elif key == \"recipient_scope\":\n if value == \"domestic\":\n queryset = queryset.filter(recipient_scope_q)\n elif value == \"foreign\":\n queryset = queryset.exclude(recipient_scope_q)\n else:\n raise InvalidParameterException(\"Invalid filter: recipient_scope type is invalid.\")\n\n elif key == \"recipient_locations\":\n queryset = queryset.filter(geocode_filter_locations(\"recipient_location\", value))\n\n elif key == \"recipient_type_names\":\n if len(value) != 0:\n queryset = queryset.filter(business_categories__overlap=value)\n\n elif key == \"place_of_performance_scope\":\n if value == \"domestic\":\n queryset = queryset.filter(pop_scope_q)\n elif value == \"foreign\":\n queryset = queryset.exclude(pop_scope_q)\n else:\n raise InvalidParameterException(\"Invalid filter: place_of_performance_scope is invalid.\")\n\n elif key == \"place_of_performance_locations\":\n queryset = queryset.filter(geocode_filter_locations(\"pop\", value))\n\n elif key == \"award_amounts\":\n queryset &= total_obligation_queryset(value, SubawardView, filters)\n\n elif key == \"award_ids\":\n queryset = build_award_ids_filter(queryset, value, (\"piid\", \"fain\"))\n\n elif key == PSCCodes.underscore_name:\n q = PSCCodes.build_tas_codes_filter(value)\n queryset = queryset.filter(q) if q else queryset\n\n # add \"naics_codes\" (column naics) after NAICS are mapped to subawards\n elif key in (\"program_numbers\", \"contract_pricing_type_codes\"):\n filter_to_col = {\n \"program_numbers\": \"cfda_number\",\n \"contract_pricing_type_codes\": \"type_of_contract_pricing\",\n }\n in_query = [v for v in value]\n if len(in_query) != 0:\n queryset &= SubawardView.objects.filter(**{\"{}__in\".format(filter_to_col[key]): in_query})\n\n elif key in (\"set_aside_type_codes\", \"extent_competed_type_codes\"):\n or_queryset = Q()\n filter_to_col = {\"set_aside_type_codes\": \"type_set_aside\", \"extent_competed_type_codes\": \"extent_competed\"}\n in_query = [v for v in value]\n for v in value:\n or_queryset |= Q(**{\"{}__exact\".format(filter_to_col[key]): in_query})\n queryset = queryset.filter(or_queryset)\n\n # Because these two filters OR with each other, we need to know about the presense of both filters to know what to do\n # This filter was picked arbitrarily to be the one that checks for the other\n elif key == TasCodes.underscore_name:\n q = TasCodes.build_tas_codes_filter(queryset, value)\n if TreasuryAccounts.underscore_name in filters.keys():\n q |= TreasuryAccounts.build_tas_codes_filter(queryset, filters[TreasuryAccounts.underscore_name])\n queryset = queryset.filter(q)\n\n elif key == TreasuryAccounts.underscore_name and TasCodes.underscore_name not in filters.keys():\n queryset = queryset.filter(TreasuryAccounts.build_tas_codes_filter(queryset, value))\n\n return queryset\n","sub_path":"usaspending_api/awards/v2/filters/sub_award.py","file_name":"sub_award.py","file_ext":"py","file_size_in_byte":11525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"405451431","text":"#!/usr/bin/env python3\n# -*- encoding: utf-8 -*-\n# vim: tabstop=2 shiftwidth=2 softtabstop=2 expandtab\n\nfrom aws_cdk import (\n core,\n aws_dynamodb as dynamodb,\n aws_ec2,\n aws_events,\n aws_events_targets,\n aws_iam,\n aws_lambda as _lambda,\n aws_logs,\n aws_s3 as s3\n)\n\n\nclass DevtoRssFeedTransBotStack(core.Stack):\n\n def __init__(self, scope: core.Construct, construct_id: str, **kwargs) -> None:\n super().__init__(scope, construct_id, **kwargs)\n\n # The code that defines your stack goes here\n vpc_name = self.node.try_get_context(\"vpc_name\")\n vpc = aws_ec2.Vpc.from_lookup(self, \"ExistingVPC\",\n is_default=True,\n vpc_name=vpc_name)\n\n DYNAMODB_TABLE_NAME = self.node.try_get_context('dynamodb_table_name')\n if DYNAMODB_TABLE_NAME:\n ddb_table = dynamodb.Table.from_table_name(self, \"RssFeedDDBTable\", DYNAMODB_TABLE_NAME)\n else:\n ddb_table = dynamodb.Table(self, \"RssFeedDDBTable\",\n table_name=\"DevtoPost\",\n partition_key=dynamodb.Attribute(name=\"id\", type=dynamodb.AttributeType.STRING),\n billing_mode=dynamodb.BillingMode.PROVISIONED,\n read_capacity=25,\n write_capacity=15,\n time_to_live_attribute=\"expired_at\"\n )\n\n ddb_table.add_global_secondary_index(index_name='p_time-index',\n partition_key=dynamodb.Attribute(name=\"p_time\", type=dynamodb.AttributeType.NUMBER),\n projection_type=dynamodb.ProjectionType.KEYS_ONLY\n )\n DYNAMODB_TABLE_NAME = ddb_table.table_name\n assert DYNAMODB_TABLE_NAME\n\n sg_rss_feed_trans_bot = aws_ec2.SecurityGroup(self, 'RssFeedTransBotSG',\n vpc=vpc,\n allow_all_outbound=True,\n description='security group for rss feed trans bot',\n security_group_name='rss-feed-trans-bot'\n )\n core.Tags.of(sg_rss_feed_trans_bot).add('Name', 'rss-feed-trans-bot')\n\n s3_lib_bucket_name = self.node.try_get_context('lib_bucket_name')\n s3_lib_bucket = s3.Bucket.from_bucket_name(self, \"LambdaLayerS3Bucket\", s3_lib_bucket_name)\n\n lambda_lib_layer = _lambda.LayerVersion(self, \"RssFeedTransBotLib\",\n layer_version_name=\"devto_rss_feed_trans_bot-lib\",\n compatible_runtimes=[_lambda.Runtime.PYTHON_3_7],\n code=_lambda.Code.from_bucket(s3_lib_bucket, \"var/devto_rss_feed_trans_bot-lib.zip\")\n )\n\n lambda_fn_env = {\n 'REGION_NAME': core.Aws.REGION,\n 'TRANS_SRC_LANG': self.node.try_get_context('trans_src_lang'),\n 'TRANS_DEST_LANG': self.node.try_get_context('trans_dest_lang'),\n 'DRY_RUN': self.node.try_get_context('dry_run'),\n 'DYNAMODB_TABLE_NAME': DYNAMODB_TABLE_NAME\n }\n\n #XXX: Deploy lambda in VPC - https://github.com/aws/aws-cdk/issues/1342\n rss_feed_trans_bot_lambda_fn = _lambda.Function(self, 'RssFeedTransBot',\n runtime=_lambda.Runtime.PYTHON_3_7,\n function_name='DevtoRssFeedTransBot',\n handler='rss_feed_trans_bot.lambda_handler',\n description='Translate rss feed of Devto/AWS Builders',\n code=_lambda.Code.asset('./src/main/python/RssFeedTransBot'),\n environment=lambda_fn_env,\n timeout=core.Duration.minutes(15),\n layers=[lambda_lib_layer],\n security_groups=[sg_rss_feed_trans_bot],\n vpc=vpc\n )\n\n ddb_table_rw_policy_statement = aws_iam.PolicyStatement(\n effect=aws_iam.Effect.ALLOW,\n resources=[\"*\"], #XXX: You had better restrict to access only specific DynamoDB table\n actions=[\n \"dynamodb:BatchGetItem\",\n \"dynamodb:Describe*\",\n \"dynamodb:List*\",\n \"dynamodb:GetItem\",\n \"dynamodb:Query\",\n \"dynamodb:Scan\",\n \"dynamodb:BatchWriteItem\",\n \"dynamodb:DeleteItem\",\n \"dynamodb:PutItem\",\n \"dynamodb:UpdateItem\",\n \"dax:Describe*\",\n \"dax:List*\",\n \"dax:GetItem\",\n \"dax:BatchGetItem\",\n \"dax:Query\",\n \"dax:Scan\",\n \"dax:BatchWriteItem\",\n \"dax:DeleteItem\",\n \"dax:PutItem\",\n \"dax:UpdateItem\"\n ]\n )\n\n rss_feed_trans_bot_lambda_fn.add_to_role_policy(ddb_table_rw_policy_statement)\n\n translate_ro_policy = aws_iam.ManagedPolicy.from_managed_policy_arn(self,\n 'TranslateReadOnly',\n 'arn:aws:iam::aws:policy/TranslateReadOnly')\n rss_feed_trans_bot_lambda_fn.role.add_managed_policy(translate_ro_policy)\n\n comprehend_ro_policy = aws_iam.ManagedPolicy.from_managed_policy_arn(self,\n 'ComprehendReadOnly',\n 'arn:aws:iam::aws:policy/ComprehendReadOnly')\n rss_feed_trans_bot_lambda_fn.role.add_managed_policy(comprehend_ro_policy)\n\n # See https://docs.aws.amazon.com/lambda/latest/dg/tutorial-scheduled-events-schedule-expressions.html\n event_schedule = dict(zip(['minute', 'hour', 'month', 'week_day', 'year'],\n self.node.try_get_context('event_schedule').split(' ')))\n\n scheduled_event_rule = aws_events.Rule(self, 'RssFeedScheduledRule',\n schedule=aws_events.Schedule.cron(**event_schedule))\n\n scheduled_event_rule.add_target(aws_events_targets.LambdaFunction(rss_feed_trans_bot_lambda_fn))\n\n log_group = aws_logs.LogGroup(self, 'RssFeedTransBotLogGroup',\n log_group_name='/aws/lambda/DevtoRssFeedTransBot',\n retention=aws_logs.RetentionDays.THREE_DAYS)\n log_group.grant_write(rss_feed_trans_bot_lambda_fn)\n\n #core.CfnOutput(self, 'StackName', value=self.stack_name, export_name='StackName')\n #core.CfnOutput(self, 'VpcId', value=vpc.vpc_id, export_name='VpcId')\n core.CfnOutput(self, 'DynamoDBTableName', value=ddb_table.table_name, export_name='DynamoDBTableName')\n core.CfnOutput(self, 'LambdaFunctionName', value=rss_feed_trans_bot_lambda_fn.function_name,\n export_name='LambdaFunctionName')\n core.CfnOutput(self, 'LambdaFunctionRole', value=rss_feed_trans_bot_lambda_fn.role.role_name,\n export_name='LambdaFunctionRole')\n","sub_path":"devto_rss_feed_trans_bot/devto_rss_feed_trans_bot_stack.py","file_name":"devto_rss_feed_trans_bot_stack.py","file_ext":"py","file_size_in_byte":5759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"407298852","text":"##\n## Programación en Python\n## ===========================================================================\n##\n## Para el archivo `data.csv`, imprima el valor maximo y minimo de la columna\n## 2 por cada letra de la columa 1.\n##\n## Rta/\n## A,9,1\n## B,9,1\n## C,9,0\n## D,7,1\n## E,9,1\n##\n## >>> Escriba su codigo a partir de este punto <<<\n##\nimport itertools\nfrom operator import itemgetter\ndatos = open('data.csv','r').readlines()\ndatos = [d.split('\\t') for d in datos]\nl1 = [[key,max([int(d[1]) for d in list(group)])] for key,group in itertools.groupby(sorted(datos),key=itemgetter(0))]\nl2 = [[key,min([int(d[1]) for d in list(group)])] for key,group in itertools.groupby(sorted(datos),key=itemgetter(0))]\nfor l in l1:\n for L in l2:\n if l[0] == L[0]:\n print(l[0],l[1],L[1],sep=',')\n#[print(l[0],l[1],L[1],sep=',') for l in l1 for L in l2 if l[0] == L[0]]\n","sub_path":"03-python=1/q05=1/question.py","file_name":"question.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"429714368","text":"\"\"\"\n#Lesson##\n#XXXXX Exercise ##\n\"\"\"\n\n#!/usr/bin/env python3\n#import stuff here\nfrom pymongo import MongoClient\nimport logging\nimport csv\n\n\n#global variables here\nlogging.basicConfig(level=logging.DEBUG)\n#define function and classes\n\nclass MongoDBConnection():\n \"\"\"MongoDB Connection\"\"\"\n\n def __init__(self, host='127.0.0.1', port=27017):\n \"\"\" be sure to use the ip address not name for local windows\"\"\"\n self.host = host\n self.port = port\n self.connection = None\n\n def __enter__(self):\n self.connection = MongoClient(self.host, self.port)\n print(f\"Establishing a connection to {self.host} on port {self.port}\")\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n print(f\"Closing the connection to {self.host} - Have a nice day!\")\n self.connection.close()\n\n\n\ndef import_data(products_file, customers_file, rentals_file):\n# def import_data(directory_name, products_file, customers_file, rentals_file):\n \"\"\"\n This function takes a directory name three csv files as input, one with\n product data, one with customer data and the third one with rentals data and\n creates and populates a new MongoDB database with the these data.\n It returns 2 tuples: the first with a record count of the number of\n products, customers and rentals added (in that order), the second with a\n count of any errors that occurred, in the same order.\n\n Imports CSV data into a MongoDB.\n\n :param arg1: the name of the products csv file\n :param arg2: the name of the customers csv file\n :param arg3: the name of the rentals csv file\n \"\"\"\n mongo = MongoDBConnection()\n\n with mongo:\n #connect to Mongo\n db = mongo.connection.hp_norton\n\n #name the first collection we will work on\n products = db[\"products\"]\n customers = db[\"customers\"]\n rentals = db[\"rentals\"]\n\n error_count = 0\n record_count = 0\n #open the first csv to import into the db\n #could this be made its own function?? probably!\n try:\n with open(products_file) as products_csv, \\\n open(customers_file) as customers_csv, \\\n open(rentals_file) as rentals_csv:\n products_contents = csv.reader(products_csv, delimiter=',', quotechar='\"')\n customers_contents = csv.reader(customers_csv, delimiter=',', quotechar='\"')\n rentals_contents = csv.reader(rentals_csv, delimiter=',', quotechar='\"')\n\n #this probably won't work, we need to change the data to a dict\n # yup! you were right!\n # CONVERT ROW DATA TO DICT\n\n for row in products_contents:\n # this could be made into a func couldn't it?\n logging.info(f'IMPORTING PRODUCTS DATA')\n convert_to_dict = {'product_id': row[0],\n 'description': row[1],\n 'product_type': row[2],\n 'quantity_available': row[3]}\n try:\n result = products.insert_one(convert_to_dict)\n # who needs comments when your logging explains it all LOL\n logging.info(f'Adding {convert_to_dict} to the products collection')\n record_count += 1\n except Exception as e:\n logging.error(f'Error adding {convert_to_dict} to the products collection!')\n error_count += 1\n for row in customers_contents:\n logging.info(f'IMPORTING CUSTOMERS DATA')\n convert_to_dict = {'user_id': row[0],\n 'name': row[1],\n 'address': row[2],\n 'zip_code': row[3],\n 'phone_number': row[4],\n 'email': row[5]}\n try:\n result = customers.insert_one(convert_to_dict)\n logging.info(f'Adding {convert_to_dict} to the customers collection')\n record_count += 1\n except Exception as e:\n logging.error(f'Error adding {convert_to_dict} to the customers collection!')\n error_count += 1\n for row in rentals_contents:\n logging.info(f'IMPORTING RENTALS DATA')\n convert_to_dict = {'product_id': row[0],\n 'user_id': row[1]}\n try:\n result = rentals.insert_one(convert_to_dict)\n logging.info(f'Adding {convert_to_dict} to the rentals collection')\n record_count += 1\n except Exception as e:\n logging.error(f'Error adding {convert_to_dict} to the rentals collection!')\n error_count += 1\n except Exception as e:\n logging.error(f'Hm, we had an error here?')\n logging.error(e)\n\n print(f' the number of records in the products collection is: {db.products.count()}')\n print(f' the number of records in the customers collection is: {db.customers.count()}')\n print(f' the number of records in the rentals collection is: {db.rentals.count()}')\n return (record_count, error_count)\n\ndef show_available_products():\n \"\"\"\n Returns a Python dictionary of products listed as available with\n the following fields:\n\n product_id.\n description.\n product_type.\n quantity_available.\n \"\"\"\n mongo = MongoDBConnection()\n\n with mongo:\n #connect to Mongo\n db = mongo.connection.hp_norton\n\n #name the first collection we will work on\n products = db[\"products\"]\n customers = db[\"customers\"]\n rentals = db[\"rentals\"]\n\n for name in products.find():\n logging.debug(f\"{name.get('product_id')} : {name.get('quantity_available')}\")\n try:\n if int(name.get('quantity_available')) > 0:\n print(f\"{name.get('product_id')}: {name.get('description')} is available!\")\n except ValueError as e:\n logging.debug(f\"skipping {name.get('product_id')} due to error\")\n logging.error(e)\n\n\ndef show_rentals(product_id):\n \"\"\"\n Returns a Python dictionary with the following user information from\n users that have rented products matching product_id:\n\n user_id.\n name.\n address.\n phone_number.\n email.\n\n :param arg1: The product_id to search for\n \"\"\"\n # gosh, I'm repeating myself a lot here with these Mongo commands. could\n # be simplified into its own function, yes??\n mongo = MongoDBConnection()\n\n with mongo:\n #connect to Mongo\n db = mongo.connection.hp_norton\n\n #the collections we will be using\n customers = db[\"customers\"]\n rentals = db[\"rentals\"]\n customer_list = []\n customer_dict ={}\n for rented_item in rentals.find():\n logging.debug(f\"Does {product_id} match {rented_item.get('product_id')}?\")\n try:\n if rented_item.get('product_id') == product_id:\n logging.debug(f'found a match!')\n customer_list.append(rented_item.get('user_id'))\n logging.debug(f\"Adding {rented_item.get('user_id')} to list\")\n except ValueError as e:\n logging.debug(f\"skipping {rented_item.get('product_id')} due to error\")\n logging.error(e)\n\n for name in customers.find():\n logging.debug(f\"comparing found user id to the customer list\")\n logging.debug(f\"looking for {name.get('user_id')} in {customer_list}\")\n try:\n if name.get('user_id') in customer_list:\n logging.debug(f\"found {name.get('name')} in the list!\")\n customer_dict[name.get('user_id')] = [name.get('user_id'),\n name.get('name'),\n name.get('address'),\n name.get('phone_number'),\n name.get('email')]\n except ValueError as e:\n logging.debug(f\"skipping {name.get('name')} due to error\")\n logging.error(e)\n return customer_dict\n\n\n#for testing\nif __name__==\"__main__\":\n import_data('products.csv', 'customers.csv', 'rentals.csv')\n","sub_path":"students/ericstreit/lessons/lesson05/assignment/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":8757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"292790499","text":"\"\"\"\n博客资源\n\"\"\"\nimport re\nfrom datetime import datetime\nfrom flask import request, g\nfrom flask_restful import Resource\nfrom . import restful_api\nfrom .. import multi_auth, token_auth\nfrom app.exts import db\nfrom app.models.blog import Blog\n\n\nclass BlogResource(Resource):\n # decorators = [multi_auth.login_required]\n\n def get(self):\n blog_id = request.args.get('blog_id')\n blog = Blog.query.filter_by(id=blog_id).first()\n blog_json = {\n 'id': blog.id,\n 'title': blog.title,\n 'content': blog.content,\n 'summary': blog.summary,\n 'cover': blog.cover,\n 'reads_count': blog.reads_count,\n 'comments_count': blog.comments_count,\n 'updated': blog.updated.strftime('%Y-%m-%d %H:%M:%S')\n }\n return {\n \"blog\":blog_json\n }\n\n @token_auth.login_required\n def post(self):\n post_args = request.get_json()\n raw_content = post_args.get('content')\n\n title_index = raw_content.find('\\n')\n if title_index == -1:\n title = '无标题'\n else:\n raw_title = raw_content[:title_index]\n title = re.sub(r'\\#*', '', raw_title)\n\n cover_catch = re.findall(r'\\!\\[cover\\]\\(.*\\)', raw_content)\n if len(cover_catch) == 0:\n cover = \"\"\n else:\n cover = cover_catch[0][9:-1]\n\n new_blog = Blog(\n user_id=g.auth_user.id,\n title=title,\n content=raw_content,\n cover=cover,\n updated=datetime.utcnow()\n )\n db.session.add(new_blog)\n db.session.commit()\n\n return {\n\n }\n\n @token_auth.login_required\n def put(self):\n post_args = request.get_json()\n blog_id = post_args.get('blog_id')\n raw_content = post_args.get('content')\n\n title_index = raw_content.find('\\n')\n if title_index == -1:\n title = '无标题'\n else:\n raw_title = raw_content[:title_index]\n title = re.sub(r'\\#*', '', raw_title)\n\n cover_catch = re.findall(r'\\!\\[cover\\]\\(.*\\)', raw_content)\n if len(cover_catch) == 0:\n cover = \"\"\n else:\n cover = cover_catch[0][9:-1]\n\n update_blog = Blog.query.filter_by(id=blog_id).update(dict(\n title=title,\n content=raw_content,\n cover=cover,\n updated=datetime.utcnow()\n ))\n db.session.commit()\n\n return {\n\n }\n\n @token_auth.login_required\n def delete(self):\n blog_id = request.args.get('blog_id')\n blog = Blog.query.filter_by(id=blog_id).first()\n db.session.delete(blog)\n db.session.commit()\n return {}\n\n\nrestful_api.add_resource(BlogResource, '/blog')\n","sub_path":"app/api/v_1_0/blog.py","file_name":"blog.py","file_ext":"py","file_size_in_byte":2939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"393424806","text":"number = int(input(\"Please Enter any Number: \"))\nif(number==0):\n try:\n print(\"invalid number\")\n \n finally:\n print(\"final block stmt executed\")\nelse: \n reverse = 0\n temp = number\n\n while(temp > 0):\n Reminder = temp % 10\n reverse = (reverse * 10) + Reminder\n temp = temp //10\n \n print(\"Reverse of a Given number is = %d\" %reverse)\n\n if(number == reverse):\n print(\"%d is a Palindrome Number\" %number)\n else:\n print(\"%d is not a Palindrome Number\" %number)","sub_path":"2.2.4.py","file_name":"2.2.4.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"161157466","text":"import onnx\nimport torch\n\nfrom onnx_pytorch.op_code_generators import OpCodeGenerator\n\n\nclass IdentityOpCodeGenerator(OpCodeGenerator):\n\n def __init__(self,\n onnx_ver=onnx.defs.onnx_opset_version(),\n torch_ver=torch.__version__):\n super(IdentityOpCodeGenerator, self).__init__(onnx_ver, torch_ver)\n\n def gen(self, node, value_infos, initializers):\n inputs_str, outputs_str = self.gen_input_output_string(\n node, initializers, self.rename_helper, self.tensor_inplace)\n init_str, forward_str = [], []\n nn_name = self.onnx_op\n node_name = self.rename_helper.get_node_name(node.name, node.op_type)\n init_str.append(f\"self.{node_name} = nn.{nn_name}()\")\n forward_str.append(f\"{outputs_str[0]} = self.{node_name}({inputs_str[0]})\")\n return {\"init\": init_str, \"forward\": forward_str}\n","sub_path":"onnx_pytorch/op_code_generators/Identity.py","file_name":"Identity.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"404141609","text":"import json\n\nfrom math import isnan\nfrom itertools import compress\nfrom hashlib import md5\nfrom numbers import Number\nfrom typing import Optional, Tuple, Sequence, Any, List, Iterable, Dict\n\nfrom coba.pipes import Source, HttpSource\nfrom coba.config import CobaConfig, CobaException\n\nfrom coba.simulations.core import Context, Action, Interaction, Simulation, ClassificationSimulation, RegressionSimulation\n\nclass OpenmlSource(Source[Tuple[Sequence[Context], Sequence[Action]]]):\n\n def __init__(self, id:int, problem_type:str = \"classification\", nominal_as_str:bool=False, md5_checksum:str = None):\n \n assert problem_type in [\"classification\", \"regression\"]\n \n self._data_id = id\n self._md5_checksum = md5_checksum\n self._problem_type = problem_type \n self._nominal_as_str = nominal_as_str\n self._cached_urls = []\n\n #add flag to allow regression simulations\n #if a known exception happens still cache the query results\n\n def read(self) -> Tuple[Sequence[Sequence[Any]], Sequence[Any]]:\n \n #placing some of these at the top would cause circular references\n from coba.encodings import Encoder, NumericEncoder, OneHotEncoder, StringEncoder\n from coba.pipes import Encode, Transpose\n\n try:\n data_id = self._data_id\n md5_checksum = self._md5_checksum\n\n dataset_description = self._get_dataset_description(data_id)\n\n if dataset_description['status'] == 'deactivated':\n raise CobaException(f\"Openml {data_id} has been deactivated. This is often due to flags on the data.\")\n \n feature_descriptions = self._get_feature_descriptions(data_id)\n\n headers : List[str] = []\n encoders: List[Encoder] = []\n ignored : List[bool] = []\n target : str = \"\"\n\n for tipe in feature_descriptions:\n\n headers.append(tipe['name'].lower())\n ignored.append(tipe['is_ignore'] == 'true' or tipe['is_row_identifier'] == 'true')\n\n if tipe['is_target'] == 'true':\n target = tipe['name'].lower()\n \n if tipe['data_type'] == 'numeric':\n encoders.append(NumericEncoder()) \n elif tipe['data_type'] == 'nominal':\n if self._nominal_as_str:\n encoders.append(StringEncoder())\n else:\n encoders.append(OneHotEncoder(singular_if_binary=True))\n else:\n ignored[-1] = True\n encoders.append(StringEncoder())\n\n if target != \"\":\n target_encoder = encoders[headers.index(target)]\n problem_encoder = NumericEncoder if self._problem_type == \"regression\" else (OneHotEncoder,StringEncoder)\n\n if target == \"\" or not isinstance(target_encoder, problem_encoder):\n target = self._get_target_for_problem_type(data_id)\n ignored[headers.index(target)] = False\n\n if self._problem_type == \"classification\":\n target_encoder = StringEncoder() if self._nominal_as_str else OneHotEncoder(singular_if_binary=False)\n encoders[headers.index(target)] = target_encoder\n\n file_rows = self._get_dataset_rows(dataset_description[\"file_id\"], target, md5_checksum)\n is_sparse = isinstance(file_rows[0], tuple) and len(file_rows[0]) == 2\n\n if is_sparse:\n file_headers = [ header.lower() for header in file_rows.pop(0)[1]]\n else:\n file_headers = [ header.lower() for header in file_rows.pop(0)]\n\n file_cols = list(Transpose().filter(file_rows))\n\n for ignored_header in compress(headers, ignored):\n if ignored_header in file_headers:\n file_cols.pop(file_headers.index(ignored_header))\n file_headers.remove(ignored_header)\n\n file_encoders = [ encoders[headers.index(file_header)] for file_header in file_headers]\n\n if is_sparse:\n label_col = file_cols[file_headers.index(target)]\n \n dense_label_col = ['0']*len(file_rows)\n \n for index, value in zip(label_col[0], label_col[1]):\n dense_label_col[index] = value\n\n file_cols[file_headers.index(target)] = (tuple(range(len(file_rows))), tuple(dense_label_col))\n\n file_cols = list(Encode(file_encoders).filter(file_cols))\n label_col = file_cols.pop(file_headers.index(target))\n feature_rows = list(Transpose().filter(file_cols))\n\n if is_sparse:\n label_col = label_col[1]\n\n no_missing_values = [ not any(isinstance(val,Number) and isnan(val) for val in row) for row in feature_rows ]\n\n if not any(no_missing_values):\n raise CobaException(f\"Every example in openml {data_id} has a missing value. The simulation is being ignored.\")\n\n feature_rows = list(compress(feature_rows, no_missing_values))\n label_col = list(compress(label_col, no_missing_values)) \n \n return feature_rows, label_col\n\n except KeyboardInterrupt:\n #we don't want to clear the cache in the case of a KeyboardInterrupt\n raise\n \n except CobaException:\n raise\n\n except Exception:\n #if something unexpected went wrong clear the\n #cache just in case it was corrupted somehow\n \n for key in self._cached_urls:\n CobaConfig.Cacher.rmv(key)\n \n raise\n\n def _get_url(self, url:str, checksum:str=None) -> bytes:\n \n if url in CobaConfig.Cacher:\n bites = CobaConfig.Cacher.get(url)\n else:\n\n api_key = CobaConfig.Api_Keys['openml']\n response = HttpSource(url + (f'?api_key={api_key}' if api_key else '')).read()\n\n if response.status_code == 412:\n if 'please provide api key' in response.text:\n message = (\n \"An API Key is needed to access openml's rest API. A key can be obtained by creating an \"\n \"openml account at openml.org. Once a key has been obtained it should be placed within \"\n \"~/.coba as { \\\"api_keys\\\" : { \\\"openml\\\" : \\\"\\\", } }.\")\n raise CobaException(message) from None\n\n if 'authentication failed' in response.text:\n message = (\n \"The API Key you provided no longer seems to be valid. You may need to create a new one\"\n \"longing into your openml account and regenerating a key. After regenerating the new key \"\n \"should be placed in ~/.coba as { \\\"api_keys\\\" : { \\\"openml\\\" : \\\"\\\", } }.\")\n raise CobaException(message) from None\n\n if response.status_code == 404:\n message = (\n \"We're sorry but we were unable to find the requested dataset on openml. The most likely cause \"\n \"for this is openml not providing the requested dataset in a format that COBA can process.\")\n raise CobaException(message) from None\n\n if \"Usually due to high server load\" in response.text:\n message = (\n \"Openml has experienced an error that they believe is the result of high server loads.\"\n \"Openml recommends that you try again in a few seconds. Additionally, if not already \"\n \"done, consider setting up a DiskCache in coba config to reduce the number of openml \"\n \"calls in the future.\")\n raise CobaException(message) from None\n\n if '' == response.text:\n raise CobaException(\"Openml experienced an unexpected error. Please try requesting the data again.\") from None\n\n bites = response.content\n\n if url not in CobaConfig.Cacher:\n self._cached_urls.append(url)\n CobaConfig.Cacher.put(url,bites)\n\n if checksum is not None and md5(bites).hexdigest() != checksum:\n \n #if the cache has become corrupted we need to clear it\n CobaConfig.Cacher.rmv(url)\n\n message = (\n f\"The response from {url} did not match the given checksum {checksum}. This could be the result \"\n \"of network errors or the file becoming corrupted. Please consider downloading the file again. \"\n \"If the error persists you may want to manually download and reference the file.\")\n raise CobaException(message) from None\n\n return bites.decode('utf-8')\n\n def _get_dataset_description(self, data_id:int) -> Dict[str,Any]:\n\n description_txt = self._get_url(f'https://www.openml.org/api/v1/json/data/{data_id}')\n description_obj = json.loads(description_txt)[\"data_set_description\"]\n\n return description_obj\n\n def _get_feature_descriptions(self, data_id:int) -> Sequence[Dict[str,Any]]:\n \n types_txt = self._get_url(f'https://www.openml.org/api/v1/json/data/features/{data_id}')\n types_obj = json.loads(types_txt)[\"data_features\"][\"feature\"]\n\n return types_obj\n\n def _get_dataset_rows(self, file_id:str, target:str, md5_checksum:str) -> Any:\n from coba.pipes import ArffReader, CsvReader, Encode, Transpose\n \n csv_url = f\"http://www.openml.org/data/v1/get_csv/{file_id}\"\n arff_url = f\"http://www.openml.org/data/v1/download/{file_id}\"\n\n if arff_url in CobaConfig.Cacher:\n text = self._get_url(arff_url, md5_checksum)\n return list(ArffReader(skip_encoding=[target]).filter(text.splitlines()))\n\n try:\n text = self._get_url(csv_url, md5_checksum)\n return list(CsvReader().filter(text.splitlines()))\n \n except:\n text = self._get_url(arff_url, md5_checksum)\n return list(ArffReader(skip_encoding=[target]).filter(text.splitlines()))\n\n def _get_target_for_problem_type(self, data_id:int):\n\n text = self._get_url(f'https://www.openml.org/api/v1/json/task/list/data_id/{data_id}')\n tasks = json.loads(text).get(\"tasks\",{}).get(\"task\",[])\n\n task_type = 1 if self._problem_type == \"classification\" else 2\n\n for task in tasks:\n if task[\"task_type_id\"] == task_type: #aka, classification task\n for input in task['input']:\n if input['name'] == 'target_feature':\n return input['value'] #just take the first one\n\n raise CobaException(f\"Openml {data_id} does not appear to be a {self._problem_type} dataset\")\n\nclass OpenmlSimulation(Simulation):\n \"\"\"A simulation created from openml data with features and labels.\n\n OpenmlSimulation turns labeled observations from a classification data set,\n into interactions. For each interaction the feature set becomes the context and \n all possible labels become the actions. Rewards for each interaction are created by \n assigning a reward of 1 for taking the correct action (i.e., choosing the correct\n label) and a reward of 0 for taking any other action (i.e., choosing any of the\n incorrect lables).\n \"\"\"\n\n def __init__(self, id: int, simulation_type:str = \"classification\", nominal_as_str:bool = False, md5_checksum: str = None) -> None:\n self._source = OpenmlSource(id, simulation_type, nominal_as_str, md5_checksum)\n self._interactions: Optional[Sequence[Interaction]] = None\n\n def read(self) -> Iterable[Interaction]:\n \"\"\"Read the interactions in this simulation.\"\"\"\n\n features,labels = self._source.read()\n\n if isinstance(labels[0],Number):\n return RegressionSimulation(features,labels).read()\n else:\n return ClassificationSimulation(features,labels).read()\n \n\n def __repr__(self) -> str:\n return f'{{\"OpenmlSimulation\":{self._source._data_id}}}'\n","sub_path":"coba/simulations/openml.py","file_name":"openml.py","file_ext":"py","file_size_in_byte":12391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"220361555","text":"from datetime import datetime, timedelta\n\nimport yfinance as yf\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nNUMBER_OF_ENTRIES_A_DAY = 7\n\n\ndef is_stock_elevating(stock_token: str, start: str, time_delta_in_days: int) -> bool:\n \"\"\"\n returns a boolean whether the stock is elevating in time_delta_in_days from the start\n :param stock_token:\n :param start: start date of evaluation\n :param time_delta_in_days: how many days from start of evaluation should be included\n :return: True if Stock of stock_token is elevating else false\n \"\"\"\n ticker = yf.Ticker(stock_token)\n # calculate end\n date_parts = start.split('-')\n date_parts[2] = str(int(date_parts[2]) + time_delta_in_days).zfill(2)\n end = '-'.join(date_parts)\n\n dataframe = ticker.history(start=start, end=end, interval='1h')\n m, b = calculate_best_fitting_line(range(dataframe.shape[0]), dataframe['Close'].values)\n print(f'm={m} , b={b}')\n if m > 0:\n return True\n return False\n\n\ndef average_slopes_of_stock(stock_token: str, start_datetime: datetime, max_days: int = 10, plot_data: bool = False) -> \\\n np.ndarray or None:\n \"\"\"\n List of average slopes of the stock from the start in 1 to max_days-1 days intervals\n :param start_datetime: start datetime\n :param plot_data: True if the data and best fitting line should be ploted\n :param stock_token: the specific stock token\n :param max_days: how many days after start you want to have the average slopes\n :return: List of average slopes\n \"\"\"\n ticker = yf.Ticker(stock_token)\n # calculate start and end date\n timedelta_max_days = timedelta(days=max_days)\n end_datetime = start_datetime + timedelta_max_days\n start = start_datetime.strftime('%Y-%m-%d')\n end = end_datetime.strftime('%Y-%m-%d')\n # get tickers history\n dataframe = ticker.history(start=start, end=end, interval='1h')\n close = dataframe['Close'].values\n if len(close) > 0:\n # calculate best fitting line from start in interval_day steps\n elevations = np.zeros(17)\n i = 0\n for interval_day in range(1, max_days - 1):\n number_of_entries = int(interval_day * NUMBER_OF_ENTRIES_A_DAY)\n interval_close = close[0:number_of_entries]\n if i <= 16:\n m, b = calculate_best_fitting_line(range(len(interval_close)), interval_close, plot_data)\n if np.isnan(m):\n return None\n elevations[i] = m\n i += 1\n if elevations[0] != np.nan:\n return elevations\n return None\n\n\ndef calculate_best_fitting_line(x, y, plot_data: bool = False) -> (int, int):\n \"\"\"\n Calculates the best fitting line of points in dataframe\n :param y: Y-Coordinates\n :param x: X-Coordinates\n :param plot_data: whether the data and line should be plotted (default = False)\n :return: Gradient and y axis intercept\n \"\"\"\n # y = dataframe['Close']\n # x = range(dataframe.shape[0])\n try:\n m, b = np.polyfit(x, y, 1)\n except:\n return 0, 0\n if plot_data:\n plot_line_with_data_points(x, y, m, b)\n return m, b\n\n\ndef plot_line_with_data_points(x, y, m, b) -> None:\n \"\"\"\n Plots all datapoints x and y with a line crated from m and b\n :param x: x coordinates\n :param y: y coordinates\n :param m: Gradient of line\n :param b: y axis intercept of Line\n :return:None\n \"\"\"\n plt.plot(x, y, 'o')\n plt.plot(x, m * x + b)\n plt.show()\n\n\ndef plot_dataframe(dataframe) -> None:\n \"\"\"\n Plots the ['Close'] coordinates of the dataframe\n :param dataframe:\n :return: None\n \"\"\"\n dataframe['Close'].plot()\n plt.xlabel(\"Date\")\n plt.ylabel(\"Adjusted\")\n plt.show()\n\n\ndef plot_stock(stock_token: str, start: str, end: str) -> None:\n \"\"\"\n Plots a stock from a start date to the end date\n :param stock_token: token of stock which should be ploted\n :param start: start date in format \"YYYY-MM-DD\"\n :param end: end date in format \"YYYY-MM-DD\"\n :return: None\n \"\"\"\n ticker = yf.Ticker(stock_token)\n dataframe = ticker.history(start=start, end=end)\n plot_dataframe(dataframe)\n\n\nif __name__ == '__main__':\n print(is_stock_elevating('TSLA', \"2021-02-01\", 25))\n print(is_stock_elevating('CLOV', \"2021-02-01\", 25))\n start_datetime = datetime.fromisoformat(\"2021-02-01\")\n stocks_slope = average_slopes_of_stock('TSLA', start_datetime, 8, plot_data=True)\n print(stocks_slope)\n","sub_path":"retrieval/Financial.py","file_name":"Financial.py","file_ext":"py","file_size_in_byte":4489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"366460429","text":"#! /home/kazushi/anaconda3/bin/python\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable\nfrom mpl_toolkits.axes_grid1.colorbar import colorbar\n\nclass BNDL:\n def load(self,fname):\n fp=open(fname,\"r\")\n fp.readline()\n dat=fp.readline()\n Xa=list(map(float,dat.strip().split(\",\")))\n print(\"Xa=\",Xa)\n\n fp.readline()\n dat=fp.readline()\n dx=list(map(float,dat.strip().split(\",\")))\n print(\"dx=\",dx)\n\n fp.readline()\n dat=fp.readline()\n Nd=list(map(int,dat.strip().split(\",\")))\n print(\"Nd=\",Nd)\n\n fp.readline()\n dat=fp.readline()\n dat=list(map(float,dat.strip().split(\",\")))\n f1=dat[0]\n df=dat[1]\n Nf=int(dat[2])\n print(\"f1,df,Nf=\",f1,df,Nf)\n #Nf=int(Nf/2)\n\n fp.readline()\n amp=[]\n for row in fp:\n dat=row.strip().split(\",\")\n z=float(dat[0])+1j*float(dat[1])\n amp.append(z)\n amp=np.array(amp)\n Nx=Nd[0]\n Ny=Nd[1]\n #amp=amp.astype(np.float)\n print(np.size(amp))\n print(Nx*Ny*Nf)\n amp=np.reshape(amp,[Nx,Ny,Nf])\n print(np.shape(amp))\n self.amp=amp\n self.Nx=Nx\n self.Ny=Ny\n self.Nf=Nf\n self.dky=1/dx[1]/Ny;\n self.ky=np.arange(Ny)*self.dky\n self.freq=np.arange(Nf)*df+f1;\n self.df=df;\n self.Xa=Xa\n self.dx=dx\n self.xcod=np.arange(Nx)*dx[0]+Xa[0]\n self.ycod=np.arange(Ny)*dx[1]+Xa[1]\n fp.close()\n def get_index(self,val,axis):\n if axis==0:\n indx=np.argmin(np.abs(self.xcod-val))\n if axis==1:\n indx=np.argmin(np.abs(self.ycod-val))\n if axis==2:\n indx=np.argmin(np.abs(self.freq-val))\n return(indx)\n def get_cod(self,indx,axis):\n cod=0.0;\n if axis==0:\n indx=indx%self.Nx;\n cod=self.xcod[indx]\n if axis==1:\n indx=indx%self.Ny;\n cod=self.ycod[indx]\n if axis==2:\n indx=indx%self.Nf;\n cod=self.freq[indx]\n return(cod)\n def get_domain(self,axis):\n x=-self.xcod\n y=-self.ycod\n f= self.freq\n if axis==0:\n ext=[f[0],f[-1],y[0],y[-1]]\n if axis==1:\n ext=[f[0],f[-1],y[0],y[-1]]\n if axis==2:\n ext=[y[0],y[-1],x[0],x[-1]]\n return(ext)\n def stack(self,ax):\n S=np.mean(self.amp,axis=ax)\n return(S)\n\n\n\nif __name__==\"__main__\":\n\n dir_name=\"./Scopes\"\n\n fname=\"scopes_win.fft\"\n fname=dir_name+\"/\"+fname\n bndl=BNDL()\n bndl.load(fname)\n\n ext=bndl.get_domain(2);\n\n fsz=12\n fig1=plt.figure(figsize=(6,6.5))\n\n fs=[0.6, 0.7, 0.8, 1.0]\n mV=1.e03\n hd=[\"(a) \",\"(b) \",\"(c) \",\"(d) \"];\n ax=[];\n # Snapshots\n for k in range(4):\n ax.append(fig1.add_subplot(2,2,k+1))\n ax[k].tick_params(labelsize=fsz)\n axdiv=make_axes_locatable(ax[k])\n cax=axdiv.append_axes(\"right\",size=\"7%\",pad=\"2%\")\n indx=bndl.get_index(fs[k],2);\n ff=bndl.get_cod(indx,2);\n Phi=np.angle(bndl.amp[:,:,indx]);\n ima=ax[k].imshow(Phi,cmap=\"jet\",interpolation=\"none\",extent=ext,vmin=-np.pi,vmax=np.pi,aspect=\"equal\")\n cba=colorbar(ima,cax=cax)\n\n txtf=\"f=\"+str(fs[k])+\"[MHz]\"\n ax[k].set_title(hd[k]+txtf,loc=\"center\")\n\n ax[2].set_xlabel(\"x [mm]\",fontsize=12)\n ax[3].set_xlabel(\"x [mm]\",fontsize=12)\n ax[0].set_ylabel(\"y [mm]\",fontsize=12)\n ax[2].set_ylabel(\"y [mm]\",fontsize=12)\n\n\n fig2=plt.figure(figsize=(6,3.5))\n fig3=plt.figure(figsize=(6,3.5))\n bx=[]\n bx.append(fig2.add_subplot(111))\n bx.append(fig3.add_subplot(111))\n\n\n # Mean B-scan\n S=bndl.stack(0)\n ext2=bndl.get_domain(0)\n imb0=bx[0].imshow(np.abs(S*mV),extent=ext2,interpolation=\"bilinear\",aspect=\"auto\",cmap=\"jet\",origin=\"lower\")\n bxdiv=make_axes_locatable(bx[0])\n cbx=bxdiv.append_axes(\"right\",size=\"7%\",pad=\"2%\")\n cb0=colorbar(imb0,cax=cbx)\n\n # B-scan at xcod \n xcod=0\n indx=bndl.get_index(xcod,0);\n xcod=bndl.get_cod(indx,0)\n imb1=bx[1].imshow(np.abs(bndl.amp[indx,:,:]*mV),extent=ext2,interpolation=\"bilinear\",aspect=\"auto\",cmap=\"jet\",origin=\"lower\")\n bxdiv=make_axes_locatable(bx[1])\n cbx=bxdiv.append_axes(\"right\",size=\"7%\",pad=\"2%\")\n cb0=colorbar(imb1,cax=cbx)\n\n for k in range(2):\n bx[k].tick_params(labelsize=fsz)\n bx[k].set_xlim([0,2.5])\n bx[k].set_xlabel(\"freq [MHz]\",fontsize=fsz);\n bx[k].set_ylabel(\"x [mm]\",fontsize=fsz);\n plt.show()\n fig1.savefig(\"fsnap.png\",bbox_inches=\"tight\")\n fig2.savefig(\"spctrg_mean.png\",bbox_inches=\"tight\")\n fig2.savefig(\"spctrg.png\",bbox_inches=\"tight\")\n\n","sub_path":"Alminium2MHz/wavef.py","file_name":"wavef.py","file_ext":"py","file_size_in_byte":4800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"137191587","text":"import logging\n\nclass TGLogger(object):\n @staticmethod\n def set_logger(name, log_dir='/tmp/'):\n logger = logging.getLogger(name)\n hdlr = logging.FileHandler(\"/tmp/%s.log\" % name)\n formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s')\n hdlr.setFormatter(formatter)\n logger.addHandler(hdlr)\n logger.setLevel(logging.INFO)\n return(logger)\n","sub_path":"tactilegraphics/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"21332452","text":"'''\nCreated on Apr 11, 2016\n\n@author: Brandon\n'''\n\nimport pygame\nimport random\n\n\nclass TestCell:\n def __init__(self, dna = \"000\", brain = \"000\", pos = (0,0), color = (0,0,255)):\n self.dna = dna\n self.brain = brain\n \n self.pos_x = pos[0]\n self.pos_y = pos[1]\n self.color = color\n self.radius = 5\n \n def update(self, list):\n rand_x = random.randint(-9,9)\n rand_y = random.randint(-9,9)\n self.pos_x = self.pos_x + rand_x\n self.pos_y = self.pos_y + rand_y\n \n def paint(self, screen):\n pygame.draw.circle(screen, self.color, (self.pos_x, self.pos_y), self.radius)","sub_path":"TestCell.py","file_name":"TestCell.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"231709752","text":"import sys\nimport traceback\nfrom contextlib import contextmanager\n\nfrom cryptography.hazmat.backends import default_backend\nfrom cryptography.hazmat.primitives import serialization as crypt_serialization\nfrom cryptography.hazmat.primitives.asymmetric import rsa\n\nfrom six import reraise\n\n\ndef generate_key_pair():\n \"\"\"\n This method generates a keypair and returns it as a tuple\n of (public, private) keys.\n The public key format is OpenSSH and private key format is PEM.\n \"\"\"\n key_pair = rsa.generate_private_key(\n backend=default_backend(),\n public_exponent=65537,\n key_size=2048)\n private_key = key_pair.private_bytes(\n crypt_serialization.Encoding.PEM,\n crypt_serialization.PrivateFormat.PKCS8,\n crypt_serialization.NoEncryption()).decode('utf-8')\n public_key = key_pair.public_key().public_bytes(\n crypt_serialization.Encoding.OpenSSH,\n crypt_serialization.PublicFormat.OpenSSH).decode('utf-8')\n return public_key, private_key\n\n\ndef filter_by(prop_name, kwargs, objs):\n \"\"\"\n Utility method for filtering a list of objects by a property.\n If the given property has a non empty value in kwargs, then\n the list of objs is filtered by that value. Otherwise, the\n list of objs is returned as is.\n \"\"\"\n prop_val = kwargs.pop(prop_name, None)\n if prop_val:\n match = (o for o in objs if getattr(o, prop_name) == prop_val)\n return match\n return objs\n\n\ndef generic_find(filter_names, kwargs, objs):\n \"\"\"\n Utility method for filtering a list of objects by a list of filters.\n \"\"\"\n matches = objs\n for name in filter_names:\n matches = filter_by(name, kwargs, matches)\n\n # All kwargs should have been popped at this time.\n if len(kwargs) > 0:\n raise TypeError(\n \"Unrecognised parameters for search: %s. Supported attributes: %s\"\n % (kwargs, filter_names))\n\n return matches\n\n\n@contextmanager\ndef cleanup_action(cleanup_func):\n \"\"\"\n Context manager to carry out a given\n cleanup action after carrying out a set\n of tasks, or when an exception occurs.\n If any errors occur during the cleanup\n action, those are ignored, and the original\n traceback is preserved.\n\n :params func: This function is called if\n an exception occurs or at the end of the\n context block. If any exceptions raised\n by func are ignored.\n Usage:\n with cleanup_action(lambda e: print(\"Oops!\")):\n do_something()\n \"\"\"\n try:\n yield\n except Exception:\n ex_class, ex_val, ex_traceback = sys.exc_info()\n try:\n cleanup_func()\n except Exception as e:\n print(\"Error during exception cleanup: {0}\".format(e))\n traceback.print_exc()\n reraise(ex_class, ex_val, ex_traceback)\n try:\n cleanup_func()\n except Exception as e:\n print(\"Error during cleanup: {0}\".format(e))\n traceback.print_exc()\n","sub_path":"cloudbridge/cloud/base/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":2983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"477216133","text":"inputString = \"389547612\"\n\ninput = [int(x) for x in inputString] #cup values\n\ndef buildState(input):\n state = {} #key = cup, value = index in input of next cup\n last = input[-1]\n for i, v in enumerate(input):\n state[v] = i+1 if v != last else 0\n return state\n\ndef doMove(input, state, currentCup, minValue, maxValue):\n #Pick up all cups based on current cup\n pickupIndex1 = state[currentCup]\n pickupCup1 = input[pickupIndex1]\n pickupIndex2 = state[pickupCup1]\n pickupCup2 = input[pickupIndex2]\n pickupIndex3 = state[pickupCup2]\n pickupCup3 = input[pickupIndex3]\n\n #Select distination cup\n destinationCup = currentCup - 1 if currentcup != minValue else maxValue\n while destinationCup in [pickupCup1, pickupCup2, pickupCup3]:\n destinationCup = destinationCup - 1 if destinationCup > minValue else maxValue \n \n #Repoint state\n state[currentCup] = state[pickupCup3] #After currentcup comes the cup after the last picked up cup\n state[pickupCup3] = state[destinationCup] #After the last picked up cup comes the distinationCup\n state[destinationCup] = pickupIndex1 #After the distinationcup comes the first picked up cup\n #The rest stay the same.\n\n currentCup = input[state[currentCup]] #New currentcup (cup after the last picked up cup)\n return [state, currentCup]\n\n\nstate = buildState(input)\ncurrentcup = input[0]\nfor i in range(0,100):\n result = doMove(input, state, currentcup, 1, 9)\n state = result[0]\n currentcup = result[1]\n\ncup = 1\ncupstr = \"\"\nfor i in range(0,len(input)):\n cup = input[state[cup]]\n cupstr += str(cup)\nprint(cupstr[:-1])\n\n#Part 2\nfor i in range( max(input) + 1, 1000001 ):\n input.append(i)\n\nstate = buildState(input)\n\ncurrentcup = input[0]\nfor i in range(0,10000000): #Takes 13 seconds\n result = doMove(input, state, currentcup, 1, 1000000)\n state = result[0]\n currentcup = result[1]\n\ncup1 = input[state[1]]\ncup2 = input[state[cup1]]\nprint(cup1*cup2)","sub_path":"day23.py","file_name":"day23.py","file_ext":"py","file_size_in_byte":1984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"408207275","text":"from __future__ import annotations\nfrom typing import TYPE_CHECKING\nif TYPE_CHECKING:\n from typing import Dict, List, Iterable, Optional\n from chessmaker.typings import Piece\n\nfrom chessmaker import Color, Controller, Direction, Ply, Vector2\nfrom chessmaker.info_elements import InfoElement, InfoText\nfrom chessmaker.actions import DestroyAction\nfrom ....packs.standard import Chess\nfrom ....packs.standard.helpers import next_color, find_pieces, threatened, print_color, OFFSETS, players_without_pieces\nfrom ....packs.standard.pieces import Bishop, King, Knight, Pawn, Queen, Rook\n\nKING_COLOR = {\n Color.RED: Color.ORANGE,\n Color.BLUE: Color.PURPLE,\n Color.ORANGE: Color.ORANGE,\n Color.PURPLE: Color.PURPLE,\n}\n\nOPPONENTS = {\n Color.RED: [Color.BLUE, Color.PURPLE],\n Color.ORANGE: [Color.BLUE, Color.PURPLE],\n Color.BLUE: [Color.RED, Color.ORANGE],\n Color.PURPLE: [Color.RED, Color.ORANGE],\n}\n\n\nclass Duos(Chess, Controller):\n name = 'Duos'\n colors = [\n Color.ORANGE,\n Color.PURPLE,\n Color.RED,\n Color.BLUE,\n ]\n\n def init_board(self, board: Dict[Vector2, Piece]) -> None:\n for color, direction, row in zip([Color.RED, Color.BLUE], [Direction.NORTH, Direction.SOUTH], [7, 0]):\n board[Vector2(row, 0)] = Rook(color, direction)\n board[Vector2(row, 1)] = Knight(color, direction)\n board[Vector2(row, 2)] = Bishop(color, direction)\n board[Vector2(row, 3)] = Queen(color, direction)\n board[Vector2(row, 6)] = Knight(color, direction)\n\n for color, direction, row in zip([Color.ORANGE, Color.PURPLE], [Direction.NORTH, Direction.SOUTH], [7, 0]):\n board[Vector2(row, 4)] = King(color, direction)\n board[Vector2(row, 5)] = Bishop(color, direction)\n board[Vector2(row, 7)] = Rook(color, direction)\n\n for color, direction, row in zip([Color.ORANGE, Color.PURPLE], [Direction.NORTH, Direction.SOUTH], [6, 1]):\n for col in range(8):\n board[Vector2(row, col)] = Pawn(color, direction)\n\n def get_info(self, color: Optional[Color]) -> List[InfoElement]:\n result = []\n\n for king_color in [Color.ORANGE, Color.PURPLE]:\n # Check if their king is in check.\n king_position, king = next(find_pieces(self.game.board, King, king_color))\n if threatened(self.game, king_position, OPPONENTS[king_color]):\n result.append(InfoText(f'{print_color(king_color)} is in check!'))\n\n result.append(InfoText(f'Current Turn: {print_color(next_color(self.game, list(players_without_pieces(self.game))))}'))\n\n return result\n\n def get_plies(self, color: Color, from_pos: Vector2, to_pos: Vector2) -> Iterable[Ply]:\n board = self.game.board\n piece = board[from_pos]\n\n # Make sure it is their piece and their turn.\n if color != piece.color or color != next_color(self.game, list(players_without_pieces(self.game))):\n return\n\n # Check for pawn promotion.\n if isinstance(piece, Pawn) and (\n (to_pos.row == 0 and piece.color in [Color.RED, Color.ORANGE])\n or (to_pos.row == 7 and piece.color in [Color.BLUE, Color.PURPLE])\n ):\n plies = pawn_promotions(piece, from_pos, to_pos)\n else:\n plies = piece.get_plies(from_pos, to_pos, self.game.game_data)\n\n for ply in plies:\n # Make sure they are not capturing their teammate's piece.\n captures = filter(lambda action: isinstance(action, DestroyAction), ply.actions)\n if any(board[capture.pos].color not in OPPONENTS[color] for capture in captures):\n continue\n\n # The owner of their team's king needs to sure they are not in check after each ply is complete.\n if color == KING_COLOR[color]:\n state = self.game.next_state(color, ply)\n king_position, king = next(find_pieces(state.board, King, color))\n if threatened(self.game, king_position, OPPONENTS[color], state):\n continue\n\n yield ply\n\n def after_ply(self) -> None:\n color = next_color(self.game, list(players_without_pieces(self.game)))\n if color not in [Color.ORANGE, Color.PURPLE]:\n return\n\n king_position, king = next(find_pieces(self.game.board, King, color))\n\n if not self._has_legal_move(color):\n if threatened(self.game, king_position, OPPONENTS[color]):\n self.game.winner(OPPONENTS[color], 'Checkmate')\n else:\n self.game.winner([], 'Stalemate')\n\n def _is_legal(self, from_pos: Vector2, to_pos: Vector2) -> bool:\n if to_pos.row >= self.board_size.row or to_pos.row < 0 or to_pos.col >= self.board_size.col or to_pos.col < 0:\n return False\n\n piece = self.game.board[from_pos]\n plies = piece.get_plies(from_pos, to_pos, self.game.game_data)\n\n for ply in plies:\n # Capturing your teammate is not legal.\n captures = filter(lambda action: isinstance(action, DestroyAction), ply.actions) # TODO: Extract function.\n if any(self.game.board[capture.pos].color not in OPPONENTS[piece.color] for capture in captures):\n continue\n\n state = self.game.next_state(piece.color, ply)\n\n king_position, king = next(find_pieces(state.board, King, piece.color))\n\n if not threatened(self.game, king_position, OPPONENTS[piece.color], state):\n return True\n\n return False\n\n def _has_legal_move(self, color: Color) -> bool:\n for pos, piece in find_pieces(self.game.board, color=color):\n if isinstance(piece, Pawn):\n if piece.direction == Direction.NORTH and (\n self._is_legal(pos, pos + Vector2(0, -1))\n or self._is_legal(pos, pos + Vector2(0, -2))\n or self._is_legal(pos, pos + Vector2(1, -1))\n or self._is_legal(pos, pos + Vector2(-1, -1))\n ):\n return True\n\n if piece.direction == Direction.SOUTH and (\n self._is_legal(pos, pos + Vector2(0, 1))\n or self._is_legal(pos, pos + Vector2(0, 2))\n or self._is_legal(pos, pos + Vector2(1, 1))\n or self._is_legal(pos, pos + Vector2(-1, 1))\n ):\n return True\n\n if isinstance(piece, Rook) or isinstance(piece, Queen):\n for i in range(8):\n if self._is_legal(pos, Vector2(pos.row, i)) or self._is_legal(pos, Vector2(i, pos.col)):\n return True\n\n if isinstance(piece, Knight):\n if (\n self._is_legal(pos, pos + Vector2(1, 2))\n or self._is_legal(pos, pos + Vector2(2, 1))\n or self._is_legal(pos, pos + Vector2(1, -2))\n or self._is_legal(pos, pos + Vector2(2, -1))\n or self._is_legal(pos, pos + Vector2(-1, 2))\n or self._is_legal(pos, pos + Vector2(-2, 1))\n or self._is_legal(pos, pos + Vector2(-1, -2))\n or self._is_legal(pos, pos + Vector2(-2, -1))\n ):\n return True\n\n if isinstance(piece, Bishop) or isinstance(piece, Queen):\n for i in range(-7, 8):\n if self._is_legal(pos, pos + Vector2(i, i)) or self._is_legal(pos, pos + Vector2(i, i)):\n return True\n\n if isinstance(piece, King):\n for offset in OFFSETS.values():\n if self._is_legal(pos, pos + offset):\n return True\n\n return False\n","sub_path":"app/chessmaker/packs/party/controllers/duos.py","file_name":"duos.py","file_ext":"py","file_size_in_byte":7833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"101015758","text":"from datetime import datetime\r\nimport requests\r\nimport string\r\nimport urllib3\r\nimport json\r\nimport xlrd\r\nimport pandas as pd\r\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\r\n\r\nwith open('fortigateinventory.txt') as devices_file:\r\n firewalls = devices_file.readlines()\r\n\r\nwith open('api-call.txt') as api_file:\r\n apiaction = api_file.readlines()\r\n\r\ndf = pd.read_excel('addresses.xls', sheet_name='Sheet1')\r\n\r\nname = df['name'].values.tolist()\r\nstart = df['start-ip'].values.tolist()\r\nend = df['end-ip'].values.tolist()\r\n\r\ndate = datetime.now().strftime(\"%y-%m-%d-%M\")\r\ndate1 = datetime.now().strftime(\"%B %d, %Y\")\r\n\r\nfor line in firewalls:\r\n line = line.strip(\"\\n\")\r\n hostname = line.split(\",\")[0]\r\n ipaddr = line.split(\",\")[1]\r\n port = line.split(\",\")[2]\r\n token = line.split(\",\")[3]\r\n vdom = line.split(\",\")[4]\r\n\r\n for line in apiaction:\r\n line = line.strip(\"\\n\")\r\n context = line.split(\",\")[0]\r\n option = line.split(\",\")[1]\r\n i = 0\r\n for i, (a, b, c) in enumerate(zip(name, start, end)):\r\n namevar = a\r\n startvar = b\r\n endvar = c\r\n data1 = {\"name\": namevar, \"type\": \"ipmask\", \"start-ip\": startvar, \"end-ip\": endvar}\r\n i += 1\r\n api_url = r'https://'+ipaddr+':'+port+'/api/v2/cmdb/'+context+'/'+option+'/?access_token='+token\r\n print('Performing API Request to '+ hostname)\r\n r = requests.post(api_url, data=json.dumps(data1), verify=False)\r\n\r\nprint('*' * 20)\r\nprint('Job Completed!!')\r\nprint('*' * 20)","sub_path":"FortigateAPI_Module-POST-from-EXCEL_FortiOS-6.0.py","file_name":"FortigateAPI_Module-POST-from-EXCEL_FortiOS-6.0.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"554151876","text":"from flask import Blueprint, render_template\nfrom flask_login import login_required, current_user\n\nuser_profile = Blueprint('user_profile', __name__)\n\n@user_profile.route('/')\ndef index():\n return render_template('index.html')\n\n@user_profile.route('/profile')\n@login_required\ndef profile():\n firstname = current_user.firstname\n lastname = current_user.lastname\n credits = current_user.credits\n return render_template('login/profile.html', firstname=firstname, lastname=lastname, credits=credits)","sub_path":"eCommerce/login/profile.py","file_name":"profile.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"558633471","text":"import random\nprint(\"Hello, this is Alex. Lets have a discussion!!\")\nadmission = [\"Did you get admitted?\", \"Admission is over\", \"Admission is in progress\", \"Admission is by merit\"]\nscholarship = [\"We offer fully funded scholarships\", \"Scholarships are not available\", \"We only offer partial scholarships\"]\nwaiver = [\"waiver is available\", \"Sorry, no application fee waiver\", \"kindly send an email to the grad coordinator\"]\nBioinformatics = [\"yes, the program is available\", \"No, the program is not available\"]\nwhile True:\n question = input().split()\n if \"admission\" in question:\n print(random.choice(admission))\n elif \"scholarship\" in question:\n print(random.choice(scholarship))\n elif \"waiver\" in question or \"fee\" in question:\n print(random.choice(waiver))\n elif \"Bioinformatics\" in question:\n print(random.choice(Bioinformatics))\n elif \"Thanks\" in question:\n print(\"I'm glad i could be of help. Take care!!\")\n break\n else:\n print(\"Sorry, i dont have an answer for that. kindly ask another question.\")","sub_path":"Ahmad1/AutoReply.py","file_name":"AutoReply.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"570118536","text":"def minimo():\n r = 0\n x = [0,0]\n try: # try to read number\n x[0] = int(input(\"\"))\n x[1] = int(input(\"\"))\n if ((x[0] >= 1) and (x[0] <= 1000) and (x[1] >= 1) and (x[1] <= 1000)):\n m = abs(int((x[0] - x[1]) / 2))\n r = soma(r, m)\n # if dist is odd then add (m+1)\n if not ((x[0] - x[1]) % 2 == 0):\n r += m + 1\n print(r)\n else:\n print(\"Not between 1 and 1000. Try again!\")\n except:\n print(\"Not a number. Try again!\")\n\ndef soma(r, a):\n for i in range(a + 1):\n r += i\n return(r * 2)\n\nminimo()\n","sub_path":"ex1.py","file_name":"ex1.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"452108362","text":"from statistics import median\nfrom typing import Dict, List\n\nimport ccxt\nimport tqdm\n\nfrom modules.exchange import Price\nfrom modules.settings import settings\nfrom .coinone import coinone\nfrom .gopax import gopax\n\nEXCHANGE = settings.get('EXCHANGE', {\n \"BLACKLIST\": [],\n \"WHITELIST\": [],\n})\n\nEXCHANGE_BLACKLIST = EXCHANGE.get('BLACKLIST', [])\nEXCHANGE_WHITELIST = EXCHANGE.get('WHITELIST', None)\n\nDENOM = settings['UPDATER']['DENOM']\n\n# Inserting lite implementation of gopax API to ccxt\nsetattr(ccxt, \"gopax\", gopax)\nccxt.exchanges.append(\"gopax\")\n\n# replace coinone exchange with custom lite implementation to support LUNA/KRW pair\nsetattr(ccxt, \"coinone\", coinone)\n\n\n# noinspection PyBroadException\ndef filter_exchanges(currencies, from_exchanges) -> Dict[str, List[ccxt.Exchange]]:\n \"\"\"\n filtering exchanges, has fetch_ticker for luna/currency\n :return:\n filtered exchanges\n \"\"\"\n\n exchanges: Dict[str, List[ccxt.Exchange]] = {}\n\n for currency in currencies:\n symbol = f\"{DENOM}/{currency}\"\n exchanges[symbol] = []\n\n print(\"Checking available exchanges --\")\n\n exchange_tqdm = tqdm.tqdm(from_exchanges, \"Checking available exchanges\", disable=None)\n for exchange_id in exchange_tqdm:\n exchange_tqdm.set_description_str(f\"Checking '{exchange_id}' \")\n\n if exchange_id in EXCHANGE_BLACKLIST:\n continue\n\n try:\n exchange = getattr(ccxt, exchange_id)()\n markets = exchange.fetch_markets()\n if type(markets) == dict:\n markets = list(markets.values())\n\n if len(markets) == 0 or type(markets) != list or type(markets[0]) != dict:\n print(markets)\n print(\"Internal Error: Markets type mismatched on \", exchange_id)\n raise TypeError\n\n for market in markets:\n if 'symbol' not in market:\n print(market)\n print(\"Internal Error: Market type mismatched on \", exchange_id)\n raise TypeError\n\n symbol = market['symbol']\n if symbol in exchanges and hasattr(exchange, 'fetch_ticker'):\n exchanges[symbol].append(exchange)\n\n except Exception:\n pass\n\n return exchanges\n\n\ndef get_prices_data(exchanges: Dict[str, List[ccxt.Exchange]], sdr_rates, currencies) -> List[Price]:\n \"\"\"\n fetch add exchanges and calulcating additional values.\n :param exchanges: ccxt exchange object list to query\n :param sdr_rates: sdr rate information\n :param currencies: currencies ticker names to get\n :return: price list dictionary\n \"\"\"\n prices, sdr_prices, unfetched_currencies = fetch_all_exchanges(exchanges, sdr_rates, currencies)\n\n if not sdr_prices: # in case of no data fetched\n return []\n\n # calculate LUNA/SDR price\n sdr_price = median(sdr_prices)\n prices.append(Price(\"SDR\", sdr_price, dispersion=0))\n\n # fill unfetched prices in\n for currency in unfetched_currencies:\n sdr_rate = sdr_rates[currency]\n prices.append(Price(currency, (sdr_price / sdr_rate)))\n\n # calc. dispersion\n for price in prices:\n if price.currency == \"SDR\":\n continue\n\n sdr_rate = sdr_rates[price.currency]\n price.dispersion = 1 - ((sdr_price - (1 / price.raw_price / sdr_rate)) / sdr_price)\n\n return prices\n\n\ndef fetch_all_exchanges(exchanges: Dict[str, List[ccxt.Exchange]], sdr_rates: Dict[str, float],\n currencies: List[str]) -> (List[float]):\n prices: List[Price] = []\n sdr_prices: List[float] = []\n\n unfetched_currencies: List[str] = []\n\n success_count = 0\n failed_exchanges: List[str] = []\n\n currency_tqdm = tqdm.tqdm(currencies, \"Fetching\", disable=None)\n for currency in currency_tqdm:\n currency_tqdm.set_description_str(f\"Currency '{currency}'\")\n\n symbol = f\"{DENOM}/{currency}\"\n values: List[float] = []\n\n sdr_rate = sdr_rates.get(currency, 0)\n\n exchange_tqdm = tqdm.tqdm(exchanges[symbol], disable=None)\n for exchange in exchange_tqdm:\n exchange_tqdm.set_description_str(f\"Updating from '{exchange.id}'\")\n\n # noinspection PyBroadException\n try:\n last = float(exchange.fetch_ticker(symbol)['last'])\n values.append(last) # LUNA/CURRENCY <=> CURRENCY/LUNA\n\n if sdr_rate:\n sdr_prices.append(last * sdr_rate)\n\n success_count += 1\n\n except Exception:\n failed_exchanges.append(\"%s(%s)\" % (exchange.id, symbol))\n\n if values:\n prices.append(Price(currency, median(values)))\n else:\n unfetched_currencies.append(currency)\n\n # result logging\n print(\"\")\n print(f\"Success: {success_count}, Fail: {len(failed_exchanges)} [{failed_exchanges}]\")\n\n return prices, sdr_prices, unfetched_currencies\n","sub_path":"priceserver/modules/exchange/ccxt.py","file_name":"ccxt.py","file_ext":"py","file_size_in_byte":4945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"38948998","text":"import asyncio\nfrom ep_sock import payload\n\n\nasync def handler(_, writer: asyncio.StreamWriter):\n send_payload: payload.Payload = payload.Payload()\n print('[S] Request Handler function does not exist')\n await send_payload.err_write(writer)\n\n\nasync def run_server(host, port, handler_func=handler, debug=False):\n print('[S] RUN_SERVER') if debug else None\n server = await asyncio.start_server(handler_func, host=host, port=port)\n async with server:\n await server.serve_forever()\n\n\nclass Server:\n def __init__(self, host, port, handler_func=handler, debug=False):\n self.host = host\n self.port = port\n self.handler_func = handler_func\n self.debug = debug\n\n async def _run(self):\n await asyncio.wait([run_server(self.host, self.port, handler_func=self.handler_func, debug=self.debug)])\n\n def run(self):\n asyncio.run(self._run())\n","sub_path":"application/api/ep_sock/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"242986898","text":"import tkinter as tk\r\nfrom tkinter import ttk\r\nfrom db import dbop\r\nimport tkinter.messagebox\r\nfrom SQl.sql import *\r\n\r\n\r\ndef staffWindow():\r\n staffTop = tk.Toplevel(width=900, height=550)\r\n staffTop.title(string='staffTop')\r\n staffTop.resizable(False, False)\r\n addDataBtn = tk.Button(staffTop, text='新建', height=4, width=10)\r\n addDataBtn.place(x=40, y=40)\r\n attrCombo = ttk.Combobox(\r\n staffTop, width=14, state='readonly')\r\n attrCombo['values'] = ('员工身份证号', '支行名', '部门经理身份证号',\r\n '姓名', '电话', '家庭住址', '入职日期')\r\n attrCombo.place(x=220, y=20)\r\n attrCombo.current(0)\r\n conditionEntry = tk.Entry(staffTop, width=30)\r\n conditionEntry.place(x=380, y=20)\r\n cacheBtn = tk.Button(staffTop, text='添加', width=10)\r\n cacheBtn.place(x=650, y=20)\r\n searchBtn = tk.Button(staffTop, text='查找', width=10)\r\n searchBtn.place(x=750, y=20)\r\n conditionList = tk.Listbox(staffTop, width=52, height=5)\r\n conditionList.place(x=220, y=50)\r\n tree = ttk.Treeview(staffTop, height=13, columns=(\r\n 'ID', 'branch', 'managerID', 'name', 'phone', 'address', 'joinDate'))\r\n tree.column('ID', width=150, anchor='center')\r\n tree.column('branch', width=150, anchor='center')\r\n tree.column('managerID', width=150, anchor='center')\r\n tree.column('name', width=50, anchor='center')\r\n tree.column('phone', width=100, anchor='center')\r\n tree.column('address', width=150, anchor='center')\r\n tree.column('joinDate', width=80, anchor='center')\r\n tree.heading('ID', text='员工身份证号')\r\n tree.heading('branch', text='支行名')\r\n tree.heading('managerID', text='部门经理身份证号')\r\n tree.heading('name', text='姓名')\r\n tree.heading('phone', text='电话')\r\n tree.heading('address', text='家庭住址')\r\n tree.heading('joinDate', text='入职日期')\r\n tree[\"show\"] = \"headings\"\r\n tree.place(x=40, y=200)\r\n # staffTop.overrideredirect(1)\r\n\r\n def addData():\r\n newTop = tk.Toplevel(staffTop, width=900, height=300)\r\n newTop.resizable(False, False)\r\n newTop.overrideredirect(1)\r\n label1 = tk.Label(newTop, text='员工身份证号')\r\n label1.place(x=40, y=50)\r\n entry1 = tk.Entry(newTop, width=18)\r\n entry1.place(x=40, y=100)\r\n label2 = tk.Label(newTop, text='支行名')\r\n label2.place(x=190, y=50)\r\n entry2 = tk.Entry(newTop, width=18)\r\n entry2.place(x=190, y=100)\r\n label3 = tk.Label(newTop, text='部门经理身份证号')\r\n label3.place(x=340, y=50)\r\n entry3 = tk.Entry(newTop, width=18)\r\n entry3.place(x=340, y=100)\r\n label4 = tk.Label(newTop, text='姓名')\r\n label4.place(x=490, y=50)\r\n entry4 = tk.Entry(newTop, width=6)\r\n entry4.place(x=490, y=100)\r\n label5 = tk.Label(newTop, text='电话')\r\n label5.place(x=540, y=50)\r\n entry5 = tk.Entry(newTop, width=12)\r\n entry5.place(x=540, y=100)\r\n label6 = tk.Label(newTop, text='家庭住址')\r\n label6.place(x=640, y=50)\r\n entry6 = tk.Entry(newTop, width=18)\r\n entry6.place(x=640, y=100)\r\n label7 = tk.Label(newTop, text='入职日期')\r\n label7.place(x=790, y=50)\r\n entry7 = tk.Entry(newTop, width=12)\r\n entry7.place(x=790, y=100)\r\n confirmBtn = tk.Button(newTop, text='确认')\r\n confirmBtn.place(x=250, y=250)\r\n cancelBtn = tk.Button(newTop, text='取消')\r\n cancelBtn.place(x=350, y=250)\r\n ########################\r\n\r\n def confirmFunc():\r\n ID = entry1.get().strip()\r\n branch = entry2.get().strip()\r\n managerID = entry3.get().strip()\r\n name = entry4.get().strip()\r\n phone = entry5.get().strip()\r\n address = entry6.get().strip()\r\n joinDate = entry7.get().strip()\r\n sql = \"insert into bank.员工(`员工身份证号`,`支行名`,`部门经理身份证号`,`姓名`,`电话`,`家庭住址`,`入职日期`) values(%s,%s,%s,%s,%s,%s,%s);\"\r\n try:\r\n conn.execCommit(sql, (ID, branch, managerID,\r\n name, phone, address, joinDate))\r\n closeWindow()\r\n except Exception as e:\r\n tk.messagebox.showerror(\r\n \"警告\", \"无法添加 %s,%s,%s,%s,%s,%s,%s!\" % (ID, branch, managerID, name, phone, address, joinDate))\r\n print(\"Fail\", e)\r\n\r\n def closeWindow():\r\n newTop.destroy()\r\n confirmBtn.config(command=confirmFunc)\r\n cancelBtn.config(command=closeWindow)\r\n newTop.mainloop()\r\n\r\n def saveCondition():\r\n attr = attrCombo.get()\r\n condition = conditionEntry.get().strip()\r\n conditionList.insert('end', attr+':'+condition)\r\n\r\n def seachData():\r\n olditems = tree.get_children()\r\n [tree.delete(olditem) for olditem in olditems]\r\n rawCondition = conditionList.get(0, 'end')\r\n if len(rawCondition) == 0:\r\n sql = \"select * from bank.员工;\"\r\n else:\r\n sql = genSQL(\"员工\", rawCondition)\r\n alldata = conn.execSQL(sql, None)\r\n while True:\r\n item = alldata.fetchone()\r\n if not item:\r\n break\r\n print(item)\r\n tree.insert('', 'end', values=item)\r\n\r\n def removeCondition(*args):\r\n conditionList.delete(conditionList.curselection()[0])\r\n\r\n def removeData():\r\n item = tree.selection()[0]\r\n data = tree.item(item, \"values\")\r\n sql = \"delete from bank.员工 where `员工身份证号`=%s and `支行名`=%s and `部门经理身份证号`=%s and `姓名`=%s and `电话`=%s and `家庭住址`=%s and `入职日期`=%s;\"\r\n try:\r\n conn.execCommit(sql, data)\r\n tree.delete(tree.selection())\r\n except Exception as e:\r\n tk.messagebox.showerror(\"警告\", \"无法删除!\")\r\n print(\"Fail\", e)\r\n\r\n def editData():\r\n item = tree.selection()[0]\r\n data = tree.item(item, \"values\")\r\n editTop = tk.Toplevel(staffTop, width=900, height=300)\r\n editTop.resizable(False, False)\r\n editTop.overrideredirect(1)\r\n label1 = tk.Label(editTop, text='员工身份证号')\r\n label1.place(x=40, y=50)\r\n text1 = tk.StringVar()\r\n entry1 = tk.Entry(editTop, width=18, textvariable=text1)\r\n entry1.place(x=40, y=100)\r\n label2 = tk.Label(editTop, text='支行名')\r\n label2.place(x=190, y=50)\r\n text2 = tk.StringVar()\r\n entry2 = tk.Entry(editTop, width=18, textvariable=text2)\r\n entry2.place(x=190, y=100)\r\n label3 = tk.Label(editTop, text='部门经理身份证号')\r\n label3.place(x=340, y=50)\r\n text3 = tk.StringVar()\r\n entry3 = tk.Entry(editTop, width=18, textvariable=text3)\r\n entry3.place(x=340, y=100)\r\n label4 = tk.Label(editTop, text='姓名')\r\n label4.place(x=490, y=50)\r\n text4 = tk.StringVar()\r\n entry4 = tk.Entry(editTop, width=6, textvariable=text4)\r\n entry4.place(x=490, y=100)\r\n label5 = tk.Label(editTop, text='电话')\r\n label5.place(x=540, y=50)\r\n text5 = tk.StringVar()\r\n entry5 = tk.Entry(editTop, width=12, textvariable=text5)\r\n entry5.place(x=540, y=100)\r\n label6 = tk.Label(editTop, text='家庭住址')\r\n label6.place(x=640, y=50)\r\n text6 = tk.StringVar()\r\n entry6 = tk.Entry(editTop, width=18, textvariable=text6)\r\n entry6.place(x=640, y=100)\r\n label7 = tk.Label(editTop, text='入职日期')\r\n label7.place(x=790, y=50)\r\n text7 = tk.StringVar()\r\n entry7 = tk.Entry(editTop, width=12, textvariable=text7)\r\n entry7.place(x=790, y=100)\r\n confirmBtn = tk.Button(editTop, text='确认')\r\n confirmBtn.place(x=250, y=250)\r\n cancelBtn = tk.Button(editTop, text='取消')\r\n cancelBtn.place(x=350, y=250)\r\n ########################\r\n\r\n def confirmFunc():\r\n ID = entry1.get().strip()\r\n branch = entry2.get().strip()\r\n managerID = entry3.get().strip()\r\n name = entry4.get().strip()\r\n phone = entry5.get().strip()\r\n address = entry6.get().strip()\r\n joinDate = entry7.get().strip()\r\n sql = \"update bank.员工 set `员工身份证号`=%s,`支行名`=%s, `部门经理身份证号`=%s ,`姓名`=%s , `电话`=%s , `家庭住址`=%s , `入职日期`=%s where `员工身份证号`=%s and `支行名`=%s and `部门经理身份证号`=%s and `姓名`=%s and `电话`=%s and `家庭住址`=%s and `入职日期`=%s;\"\r\n try:\r\n conn.execCommit(sql, (ID, branch, managerID, name, phone, address, joinDate,\r\n data[0], data[1], data[2], data[3], data[4], data[5], data[6]))\r\n closeWindow()\r\n except Exception as e:\r\n tk.messagebox.showerror(\"警告\", \"修改失败!\")\r\n print(\"Fail\", e)\r\n\r\n def closeWindow():\r\n editTop.destroy()\r\n\r\n text1.set(data[0])\r\n text2.set(data[1])\r\n text3.set(data[2])\r\n text4.set(data[3])\r\n text5.set(data[4])\r\n text6.set(data[5])\r\n text7.set(data[6])\r\n confirmBtn.config(command=confirmFunc)\r\n cancelBtn.config(command=closeWindow)\r\n editTop.mainloop()\r\n rightMenu = tk.Menu(staffTop)\r\n rightMenu.add_command(label='编辑', command=editData)\r\n rightMenu.add_command(label='删除', command=removeData)\r\n\r\n def popupmenu(event):\r\n try:\r\n rightMenu.post(event.x_root, event.y_root)\r\n except:\r\n pass\r\n\r\n def closePop(*args):\r\n rightMenu.unpost()\r\n conn = dbop.mysqlConn()\r\n conditionList.bind('', removeCondition)\r\n tree.bind('', popupmenu)\r\n tree.bind('', closePop)\r\n conditionList.bind('', removeCondition)\r\n cacheBtn.config(command=saveCondition)\r\n addDataBtn.config(command=addData)\r\n searchBtn.config(command=seachData)\r\n staffTop.mainloop()\r\n","sub_path":"lab3/src/window/staff.py","file_name":"staff.py","file_ext":"py","file_size_in_byte":10285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"456087114","text":"import os\nimport re\nimport string\n\ndef load_transcription_file(path):\n regex = re.compile('[%s]' % re.escape(string.punctuation))\n\n text_file_path = path + \"sentence_text.txt\"\n print(\"\\nLoading %s\" % text_file_path)\n assert os.path.isfile(text_file_path)\n\n texts = []\n with open(text_file_path, \"r\") as f:\n i = 0\n for line in f:\n s = line.rstrip().split(\"\\t\")\n\t\t\t# remove numbers\n clean_s = filter(lambda x: not x.isdigit(),\n\t\t\t\t\t\t\t\tregex.sub('', s[1]).split())\n\t\t\t# remove non speech\n clean_s = filter(lambda x: x not in [\"laughs\", \"coughs\", \"giggles\"], clean_s)\n\n\t\t\t# replace 'xxx' or 'xx' (unknown) with 'aa'\n clean_s = [\"aa\" if s in [\"xxx\",\"xx\",\"yyy\",\"yy\"] else s for s in clean_s]\n clean_s = \" \".join(clean_s).lower()\n texts.append((i, s[0], clean_s.rstrip()))\n i += 1\n return texts\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"86515455","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\nclass Polynom(object):\n \"\"\" Polynomklasse Beschreibung .....\n \"\"\"\n def __init__(self,dp):\n if isinstance(dp,(int,float,complex)):\n dp = {0:dp}\n self.dp = dp\n self.degree = max(dp.keys())\n \n def __repr__(self):\n polystr = ''\n for k in sorted(self.dp):\n polystr = polystr + '{0:+g}*X^{1}'.format(self.dp[k],k)\n return 'Polynom: ' + polystr \n \n def __add__(self,other):\n spow = set(self.dp.keys())\n opow = set(other.dp.keys())\n pows = spow.union(opow)\n pps = dict()\n for k in pows:\n if k in spow:\n if k in opow:\n pps[k] = self.dp[k] + other.dp[k]\n else:\n pps[k] = self.dp[k]\n else:\n pps[k] = other.dp[k] \n return Polynom(pps)\n \n def __sub__(self,other):\n \"\"\" Substraktion zweier Polynomen \n \"\"\"\n spow = set(self.dp.keys())\n opow = set(other.dp.keys())\n pows = spow.union(opow)\n erg = dict()\n for k in pows:\n if k in spow:\n if k in opow:\n erg[k] = self.dp[k] - other.dp[k]\n else:\n erg[k] = self.dp[k]\n else:\n erg[k] = -other.dp[k] \n return Polynom(erg)\n \n def __call__(self,x):\n \"\"\" Auswertung des Polynoms \n \"\"\"\n return sum([self.dp[k]*x**k for k in self.dp])\n \n def __mul__(self, other):\n tempdict = {0:0}\n if isinstance(other,(int,float,complex)):\n for k in self.dp:\n tempdict[k] = self.dp[k] * other \n return Polynom(tempdict)\n elif isinstance(other, Polynom):\n for i in self.dp.keys():\n for j in other.dp.keys():\n if (i+j in tempdict.keys()):\n tempdict[i+j] += self.dp[i]*other.dp[j]\n else:\n print(j+i)\n tempdict[i+j] = self.dp[i]*other.dp[j]\n return Polynom(tempdict)\n else:\n return NotImplemented\n \n __rmul__ = __mul__\n\n def diff(self):\n tempdict = {}\n for i in self.dp.keys():\n if i > 0:\n tempdict[i-1] = i*self.dp[i]\n return Polynom(tempdict)\n\n def integral(self, a, b):\n tempdict = {}\n for i in self.dp.keys():\n tempdict[i+1] = self.dp[i]/(i+1)\n tempPoly = Polynom(tempdict)\n return tempPoly(b) - tempPoly(a)\n \n\npd = {0:3,1:1,2:8,4:5}\np = Polynom(pd)\n\nprint(\"Ableitung von \" + str(p) + \" ist \" + str(p.diff()))\n\nprint(\"und das Integral ist \" + str(p.integral(0, 1)))","sub_path":"hhu/blaetter/prog_la_3/Aufgabe12.py","file_name":"Aufgabe12.py","file_ext":"py","file_size_in_byte":2807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"374050754","text":"import argparse\nimport json\nimport csv\n\nimport yaml\nfrom backlog.base import BacklogAPI\n\ndef main():\n \"\"\"argparse tutorial 10\n\n Backlog APIを叩いてみるCLIツールを作る\n\n python-backlogの使用方法は以下のリンクを参照。\n http://blog.serverworks.co.jp/tech/2019/09/06/post-73944/\n\n API Keyの発行は以下のURLから\n https://.backlog.jp/EditApiSettings.action\n \"\"\"\n\n # https://docs.python.org/ja/3/library/argparse.html#argumentparser-objects\n parser = argparse.ArgumentParser(\n description=\"\"\"This is argparse tutorial - 10\n \n 簡易版Backlog CLIのようなもの\n \"\"\"\n )\n\n # 受け入れる引数の宣言\n parser.add_argument(\n '-c',\n '--conf',\n dest='conf',\n type=argparse.FileType('r'),\n default=open('conf.yml'),\n metavar='conf_file. (default: conf.yml)',\n # help='conf file'\n )\n\n parser.add_argument(\n '-p',\n '--project',\n dest='project',\n type=str,\n metavar='PROJECT_ID_OR_KEY',\n required=True,\n # help='Project id or key'\n )\n\n # パース+ロジック\n args = parser.parse_args()\n\n conf = yaml.load(args.conf, Loader=yaml.CLoader)\n check_conf(conf)\n\n backlog_client = backlog_get_client(\n space=conf['space'],\n api_key=conf['api_key']\n )\n\n # 戻り値はBacklog API V2の仕様に順序\n # https://developer.nulab.com/ja/docs/backlog/api/2/get-wiki-page-list/\n wikis = backlog_list_wikis(\n client=backlog_client,\n project=args.project\n )\n\n print(json.dumps(wikis))\n\n return 0\n\n\n\ndef backlog_get_client(space: str, api_key: str):\n \"\"\"Return Backlog API Client\n \n :param space: backlog space (backlog.jpのサブドメイン))\n :type space: str\n :param api_key: backlog api key\n :type api_key: str\n :return: Backlog API Client object\n :rtype: backlog.base.BacklogAPI\n \"\"\"\n return BacklogAPI(\n space=space,\n api_key=api_key\n )\n\n\ndef backlog_list_wikis(client: BacklogAPI, project: str):\n \"\"\"プロジェクト配下のwikiをリストする\n\n :param client: API Client\n :type client: BacklogAPI\n :param project: プロジェクトIDもくしはプロジェクトキー\n :type project: str\n \"\"\"\n return client.wiki.list(\n projectIdOrKey=project\n )\n\n\ndef check_conf(conf: dict):\n \"\"\"confの内容をチェック\n \n :param conf: 'space', 'api_key' の2つのキーが存在することを期待する\n :type conf: dict\n \"\"\"\n if not ('space' in conf.keys()):\n raise Exception('conf object does not have \"space\" key.')\n \n if not ('api_key' in conf.keys()):\n raise Exception('conf object does not have \"api_key\" key.')\n \n return True\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"10_example_cli_using_backlog_api/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":2877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"632701054","text":"def reverse_ll(head):\n if head is None:\n return None\n\n if head.next is None:\n return head\n\n prev= None\n curr = head\n next = None\n\n while(curr is not None):\n next = curr.next\n curr.next = prev\n prev = curr\n curr = next\n\n return prev\n\ndef add_number(head):\n f = reverse_ll(head)\n carry = 0\n head.data += 1\n prev = None\n\n while(head != None) and (head.data > 9 or carry > 0):\n prev = head\n head.data += carry\n carry = head.data // 10\n head.data = head.data % 10\n head = head.next\n\n if carry > 0:\n prev.next = Noed(carry)\n return reverse_ll(k)\n","sub_path":"Linked_List/add_1_linked_list.py","file_name":"add_1_linked_list.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"151742459","text":"import sys, getopt, urllib.parse, requests, time\n\nclass KiwiRequest:\n \n api_url = \"https://api.skypicker.com/flights\"\n bookingapi_url= \"http://128.199.48.38:8080/booking\"\n \n def __init__(self):\n #set Defaults parameters\n self.params = {'v':'3','partner':'picky','partner_market':'us','bags':'0','typeFlight':'oneway'}\n \n #make the api call and return the booking ID of the best flight du to the params\n def procces_request(self):\n \n request_url = self.api_url\n #required fields\n if set(['dateFrom','flyFrom','to']).issubset(set(self.params.keys())): \n response = requests.get(request_url,params = self.params)\n try: \n json = response.json()\n if response.status_code == requests.codes.ok:\n #parse json a make the booking api call\n if(json[\"data\"] is not None):\n flight = json[\"data\"][0]\n payload = {\n \"booking_token\":flight[\"booking_token\"], \n \"bags\":self.params[\"bags\"],\n \"currency\":\"EUR\",\n \"passengers\": [{\n \"firstName\":\"David\",\n \"lastName\":\"Ling\",\n \"email\":\"david.ling@post.cz\",\n \"documentID\":\"123456789\",\n \"birthday\":\"1997-08-25T15:33:00\",\n \"title\":\"Mr\"\n }]\n }\n response = requests.post(self.bookingapi_url,json=payload)\n if(response.status_code == requests.codes.ok):\n json = response.json()\n return json[\"pnr\"] \n except:\n return 0\n return 0\n\n \n \ndef main():\n\n #--cheapest --fastest colision\n type_arg = False \n \n #try to take parameters from command line\n try:\n opts, args = getopt.getopt(sys.argv[1:],\"\",[\"date=\",\"from=\",\"to=\",\"return=\",\"bags=\",\"one-way\",\"cheapest\",\"fastest\"])\n except:\n return 0\n \n #new KiwiRequest instance\n request = KiwiRequest() \n \n #loop through arguments and add them to request parameters\n for opt,arg in opts:\n if opt == \"--date\":\n #Convert yyyy-mm-dd format to dd%2Fmm%2Fyyyy format\n date = time.strptime(arg,\"%Y-%m-%d\")\n request.params['dateFrom'] = request.params['dateTo'] = urllib.parse.quote(time.strftime(\"%d/%m/%Y\",date))\n elif opt == \"--from\":\n request.params['flyFrom'] = arg\n elif opt == \"--to\":\n request.params['to'] = arg\n elif opt == \"--return\":\n request.params['daysInDestinationTo'] = request.params['daysInDestinationFrom'] = arg\n request.params['typeFlight'] = 'round'\n elif opt == \"--bags\":\n request.params['bags'] = arg\n elif opt == \"--fastest\":\n #--fastest and --cheapest together\n if type_arg:\n return 0\n else:\n request.params[\"sort\"] = \"duration\"\n type_arg = True\n elif opt == \"--cheapest\":\n #--fastest and --cheapest together\n if type_arg:\n return 0\n \n\n #make the api call\n return request.procces_request()\n \nprint(main())\n \n ","sub_path":"book_flight.py","file_name":"book_flight.py","file_ext":"py","file_size_in_byte":3526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"428129783","text":"from socket import *\r\nfrom threading import *\r\nfrom sys import *\r\n\r\nipnum = '127.0.0.1'\r\nportnum = 1234\r\ninfo = (ipnum,portnum)\r\nbuffer_size = 1000000\r\n\r\nsocket1 = socket(AF_INET, SOCK_STREAM)\r\n\r\ntry:\r\n socket1.connect(info)#Make a try : Connecting to the location(in info variable)\r\n socket1.send('Hello Server'.encode())\r\nexcept Exception as exc:\r\n print('%s:%s : Not Available to Connect'%info)\r\n sys.exit #Make Program end.\r\n\r\nprint('Connection Successful')\r\n\r\ndata = socket1.recv(buffer_size)\r\nprint(data)\r\n\r\nsocket1.close()","sub_path":"Basic Principle/Client.py","file_name":"Client.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"428975859","text":"\"\"\"\nDEPTH-FIRST SEARCH PROPERTIES\n\nDFS runs in O(E + V) time.\n\nPROPOSITION: DFS marks all vertices connected to s in time proportional to\nthe sum of their degrees.\n\nPROPOSITION: After DFS, can find vertices connected to s in constant time\nand can find a path to s (if one exists) in time proportional to its length.\n\nQUESTION: In a Graph G represented using the adjacency-lists representation,\ndepth-first search marks all vertices connected to s in time proportional to\nANSWER: The sum of the degrees of the vertices in the connected component\ncontaining s\n\nQUESTION: The critical data structures used in depth-first search and\nbreadth-first search are _____ and ____, respectively.\nANSWER: DFS->Stack BFS->Queue\nEXPLANATION: With DFS, it is either an explicit stack(w/ nonrecursive version)\nor the function-call stack (w/a recursive version)\n\"\"\"\nfrom itu.algs4.graphs.graph import Graph\n\n\nclass DepthFirstPaths(object):\n\n def __init__(self, Grph, src):\n self.src = src\n self.edge_to = [None] * Grph.v() # edge_to[v] = last edge on s-v path\n self.marked = [False] * Grph.v() # marked[v] = is there an s-v path?\n self.dfs(Grph, src)\n\n def dfs(self, Grph, v):\n \"\"\"\n Runs in O(V+E) time\n depth first search from vertex v\n :param Grph:\n :param v:\n :return:\n \"\"\"\n self.marked[v] = True\n for w in Grph.adj(v):\n if not self.marked[w]:\n # import ipdb; ipdb.set_trace()\n self.edge_to[w] = v\n self.dfs(Grph, w)\n\n def has_path_to(self, v):\n \"\"\"\n is there a path between source vertex s and vertex v?\n :param v:\n :return:\n \"\"\"\n return self.marked[v]\n\n def path_to(self, v):\n \"\"\"\n returns a path between source vertex s and vertex v, or None if it doesnt exist\n :param v:\n :return:\n \"\"\"\n if not self.has_path_to(v):\n return None\n\n path_stk = [] # stack for path\n # walk from v to src adding the edges into the stack\n x = v\n while x != self.src:\n path_stk.append(x) # push\n x = self.edge_to[x]\n path_stk.append(self.src)\n return path_stk\n\nif __name__ == '__main__':\n l = [13, 13, (0, 5), (4,3), (0,1), (9, 12), (6,4), (5,4), (0,2), (11, 12), (9, 10), (0,6),\n (7,8), (9,11), (5,3)]\n g = Graph(l)\n dfp = DepthFirstPaths(g, 6)\n print(dfp.edge_to) # [6, 0, 0, 5, 3, 0, None, None, None, None, None, None, None]\n print(dfp.marked) # [True, True, True, True, True, True, True, False, False, False, False,\n # False, False]\n print(dfp.path_to(4)) # [4, 3, 5, 0, 6] Note: not necessarily the shortest path\n","sub_path":"app/graphs/dfs.py","file_name":"dfs.py","file_ext":"py","file_size_in_byte":2739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"258879723","text":"\"\"\"\nconvert Pytorch IR, dtype into Tensorflow Op, dtype\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nfrom __future__ import division\n\nimport torch\n\nimport tensorflow as tf\n\nimport numpy as np\n\nfrom .convolution import convolution\nfrom .gemm import gemm\nfrom .normalization import batch_norm\nfrom .math import math_ops\nfrom .activations import activation\nfrom .pool import pool\nfrom .cast import cast\nfrom .dropout import dropout\nfrom .shape import shape_ops\nfrom .recurrent import recurrent\n\n_DTYPE_MAP = {\n # floating point\n torch.float16: tf.float16,\n torch.half: tf.float16,\n torch.float32: tf.float32,\n torch.float: tf.float32,\n torch.double: tf.float64,\n torch.float64: tf.float64,\n # integer\n torch.uint8: tf.uint8,\n torch.int8: tf.int8,\n torch.int16: tf.int16,\n torch.short: tf.int16,\n torch.int32: tf.int32,\n torch.int: tf.int32,\n torch.int64: tf.int64,\n torch.long: tf.int64,\n # boolean\n torch.bool: tf.bool,\n # ScalarType\n # from https://github.com/pytorch/pytorch/blob/master/c10/core/ScalarType.h\n 0: tf.uint8,\n 1: tf.int8,\n 2: tf.int16,\n 3: tf.int32,\n 4: tf.int64,\n 5: tf.float16,\n 6: tf.float32,\n 7: tf.float64,\n 11: tf.bool,\n}\n\ndef dtype_map(dtype):\n if isinstance(dtype, np.dtype):\n return tf.as_dtype(dtype)\n return _DTYPE_MAP[dtype]\n\n_OP_MAP = {\n # prim ops\n \"prim::Constant\": lambda x: x,\n \"prim::NumToTensor\": lambda x: x, # is it realy need to convert to tensor?\n \"prim::ListConstruct\": lambda *x: list(x),\n \"prim::ListUnpack\": lambda x: x,\n \"prim::TupleConstruct\": lambda *x: tuple(x),\n \"prim::TupleUnpack\": lambda x: x,\n # basic math operations\n \"aten::add\": math_ops(\"aten::add\"),\n \"aten::add_\": math_ops(\"aten::add\"),\n \"aten::mul\": math_ops(\"aten::mul\"),\n \"aten::mul_\": math_ops(\"aten::mul\"),\n \"aten::sub\": math_ops(\"aten::sub\"),\n \"aten::div\": math_ops(\"aten::div\"),\n \"aten::floor\": math_ops(\"aten::floor\"),\n \"aten::ceil\": math_ops(\"aten::ceil\"),\n \"aten::log_softmax\": math_ops(\"aten::log_softmax\"),\n \"aten::nll_loss\": math_ops(\"aten::nll_loss\"),\n \"aten::addmm\": gemm(\"aten::addmm\"),\n \"aten::matmul\": gemm(\"aten::matmul\"),\n # activations\n \"aten::relu\": activation(\"aten::relu\"),\n \"aten::relu_\": activation(\"aten::relu\"),\n \"aten::leaky_relu_\": activation(\"aten::leaky_relu_\"),\n \"aten::tanh\": activation(\"aten::tanh\"),\n \"aten::tanh_\": activation(\"aten::tanh\"),\n \"aten::hardtanh_\": activation(\"aten::hardtanh_\"),\n \"aten::sigmoid\": activation(\"aten::sigmoid\"),\n \"aten::sigmoid_\": activation(\"aten::sigmoid\"),\n \"aten::softmax\": activation(\"aten::softmax\"),\n # shape related\n \"aten::view\": shape_ops(\"aten::view\"),\n \"aten::flatten\": shape_ops(\"aten::flatten\"),\n \"aten::size\": shape_ops(\"aten::size\"),\n \"aten::t\": shape_ops(\"aten::t\"),\n \"aten::constant_pad_nd\": shape_ops(\"aten::constant_pad_nd\"),\n \"aten::slice\": shape_ops(\"aten::slice\"),\n \"aten::select\": shape_ops(\"aten::select\"),\n \"aten::chunk\": shape_ops(\"aten::chunk\"),\n # type, device placement casting\n \"aten::Int\": cast(\"aten::Int\"),\n \"aten::to\": cast(\"aten::to\"),\n # convolutions\n \"aten::_convolution\": convolution(\"aten::_convolution\"),\n # recurrents\n \"aten::lstm\": recurrent(\"aten::lstm\"),\n \"aten::rnn_tanh\": recurrent(\"aten::rnn_tanh\"),\n \"aten::rnn_relu\": recurrent(\"aten::rnn_relu\"),\n \"aten::gru\": recurrent(\"aten::gru\"),\n # pooling & unpooling (upsample included)\n \"aten::max_pool2d\": pool(\"aten::max_pool2d\"),\n \"aten::adaptive_avg_pool2d\": pool(\"aten::adaptive_avg_pool2d\"),\n \"aten::upsample_nearest2d\": pool(\"aten::upsample_nearest2d\"),\n # normalizations\n \"aten::batch_norm\": batch_norm(\"aten::batch_norm\"),\n # dropouts\n \"aten::dropout\": dropout(\"aten::dropout\"),\n \"aten::feature_dropout\": dropout(\"aten::dropout\"),\n # embeddings\n \"aten::embedding\": lambda *x: tf.nn.embedding_lookup(x[0], x[1]),\n # misc torch ops\n \"aten::detach\": tf.stop_gradient,\n \"aten::zeros\": lambda *x: tf.zeros(x[0], dtype_map(x[1])),\n \"aten::ones\": lambda *x: tf.ones(x[0], dtype_map(x[1])),\n}\n\ndef op_map(ir):\n assert isinstance(ir, torch.Node), \"Must be torch.Node\"\n kind = ir.kind()\n if kind in _OP_MAP:\n return _OP_MAP[kind]\n raise KeyError(\"%s is not in opmap\" % kind)\n","sub_path":"conversion/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"318323266","text":"############ \n# Coordinates the gsp and the bidder modules\n# For the WIN-EXP implementation\n############ \n\nimport numpy as np\nimport random\nimport math\nfrom copy import deepcopy\nfrom bidder import *\nfrom gsp import GSP\nfrom regret import *\nfrom regressions import *\n\n# returns the normalization of table A in [c,d]\ndef normalize(A, bid_space,c,d):\n minn = np.min(A)\n maxx = np.max(A)\n\n if (minn == maxx):\n B = [(1.0/bid_space) for _ in range(0,bid_space)]\n else:\n B = [1.0*(d-c)*(A[i] - minn)/(maxx - minn) + c for i in range(0,bid_space)]\n\n return B\n\n# if he gets allocated a slot, then reward = value - payment\n# else reward = 0\ndef compute_reward(payment_func, values, bid_space):\n reward_lst = [(values - payment_func[b]) for b in range(0, bid_space)] \n return reward_lst\n\n\ndef noise_mask(alloc_func, noise,ctr,num_slots):\n lst = []\n for b in alloc_func: \n if (b == 0):\n lst.append(np.max([0,np.min([noise[num_slots],1])]))\n else:\n lst.append(np.max([0,np.min([b+noise[ctr.index(b)],1])]))\n\n return lst\n \n\ndef main_winexp(bidder,curr_rep, T,num_bidders, num_slots, outcome_space, rank_scores, ctr, reserve, values,bids,threshold, noise,num_adaptive):\n algo_util = []\n temp_regr = []\n clean_alloc = [[] for _ in range(0,T)]\n clean_pay = [[] for _ in range(0,T)]\n clean_reward = [[] for _ in range(0,T)]\n for t in range(0,T):\n bid_chosen = [bidder[i].bidding() for i in range(0,num_adaptive)]\n for i in range(0,num_adaptive): \n bids[t][i] = bid_chosen[i]\n bid_vec = deepcopy(bids[t])\n gsp_instance =GSP(ctr[t], reserve[t], bid_vec, rank_scores[t], num_slots, num_bidders) \n\n arm_chosen = [int(math.ceil(bids[t][i]/bidder[i].eps)) for i in range(0,num_adaptive)] \n for i in range(0,num_adaptive):\n allocated = gsp_instance.alloc_func(bidder[i].id, bids[t][bidder[i].id])\n # temp is the clean allocation\n temp = [gsp_instance.alloc_func(bidder[i].id, bid*bidder[i].eps) for bid in range(0, bidder[i].bid_space)]\n if (i == 0):\n clean_alloc[t] = deepcopy(temp)\n clean_pay[t] = [gsp_instance.pay_func(bidder[i].id, bid*bidder[i].eps) for bid in range(0,bidder[i].bid_space)]\n temp_pay = gsp_instance.pay_func(bidder[i].id, bid_vec[i])\n bidder[i].payment[t] = temp_pay\n \n # bidder sees noisy data as his allocation\n noise_cp = deepcopy(noise)\n if i==0: \n bidder[i].currbid[t] = arm_chosen[i]*bidder[i].eps \n if allocated > threshold[t]:\n bidder[i].allocated[t] = 1\n bidder[i].alloc_func[t] = compute_allocation_function(bidder[i].currbid[:t+1], bidder[i].allocated[:t+1], bidder[i].bid_space, bidder[i].eps)\n\n bidder[i].alloc_func[t][arm_chosen[i]] = allocated\n bidder[i].pay_func[t] = compute_payment_function(bidder[i].currbid[:t+1], bidder[i].payment[:t+1], bidder[i].bid_space, bidder[i].eps) \n bidder[i].pay_func[t][arm_chosen[i]] = bidder[i].payment[t]\n temp_reward = [(values[t][0] - bidder[i].pay_func[t][b]) for b in range(0,bidder[i].bid_space)] \n clean_reward[t] = [(values[t][0] - clean_pay[t][b]) for b in range(0,bidder[i].bid_space)]\n bidder[i].reward_func[t] = normalize(temp_reward,bidder[i].bid_space,-1,1)\n bidder[i].utility[t] = (bidder[i].compute_utility(1, bidder[i].reward_func[t], bidder[i].alloc_func[t]))\n else:\n bidder[i].allocated[t] =0\n bidder[i].alloc_func[t] = compute_allocation_function(bidder[i].currbid[:t+1], bidder[i].allocated[:t+1], bidder[i].bid_space, bidder[i].eps)\n bidder[i].alloc_func[t][arm_chosen[i]] = allocated\n bidder[i].payment[t] = 0 \n bidder[i].pay_func[t] = [0]*bidder[i].bid_space\n bidder[i].reward_func[t] = [0 for _ in range(0,bidder[i].bid_space)]\n clean_reward[t] = bidder[i].reward_func[t]\n bidder[i].utility[t] = (bidder[i].compute_utility(0, bidder[i].reward_func[t], bidder[i].alloc_func[t]))\n \n (bidder[i].weights, bidder[i].pi) = bidder[i].weights_update_winexp(bidder[i].eta_winexp, bidder[i].utility[t]) \n else:\n bidder[i].alloc_func[t] = temp\n bidder[i].pay_func[t] = [gsp_instance.pay_func(bidder[i].id, bid*bidder[i].eps) for bid in range(0, bidder[i].bid_space)]\n if allocated > threshold[t]: \n bidder[i].reward_func[t] = [(values[t][i] - bidder[i].pay_func[t][b]) for b in range(0,bidder[i].bid_space)] \n else:\n bidder[i].reward_func[t] = [0 for _ in range(0,bidder[i].bid_space)]\n\n\n bidder[i].utility[t] = bidder[i].reward_func[t]\n\n ##weights update\n #arm_chosen[i] = int(math.ceil(bids[t][i]/bidder[i].eps))\n \n if bidder[i].pi[arm_chosen[i]] < 0.0000000001:\n bidder[i].pi[arm_chosen[i]] = 0.0000000001\n \n estimated_loss = -bidder[i].utility[t][arm_chosen[i]]/bidder[i].pi[arm_chosen[i]]\n bidder[i].loss[arm_chosen[i]] += estimated_loss\n arr = np.array([(-bidder[i].eta_exp3)*bidder[i].loss[b] for b in range(0,bidder[i].bid_space)], dtype=np.float128)\n bidder[i].weights = np.exp(arr)\n bidder[i].pi = [bidder[i].weights[b]/sum(bidder[i].weights) for b in range(0,bidder[i].bid_space)]\n \n algo_util.append((clean_reward[t][arm_chosen[0]]*clean_alloc[t][arm_chosen[0]]))\n temp_regr.append(regret(clean_reward,clean_alloc,bidder[0].bid_space, algo_util,t)) \n \n\n return temp_regr \n\n\n","sub_path":"regressions/exp3_adversaries/runner_winexp_all_bidders.py","file_name":"runner_winexp_all_bidders.py","file_ext":"py","file_size_in_byte":6231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"570350851","text":"import numpy as np\n\ndef linear_kernel(x, y, b=1):\n return x @ y.T + b\n\ndef gaussian_kernel(x, y, sigma=1):\n if np.ndim(x) == 1 and np.ndim(y) == 1:\n result = np.exp(- (np.linalg.norm(x - y, 2)) ** 2 / (2 * sigma ** 2))\n elif (np.ndim(x) > 1 and np.ndim(y) == 1) or (np.ndim(x) == 1 and np.ndim(y) > 1):\n result = np.exp(- (np.linalg.norm(x - y, 2, axis=1) ** 2) / (2 * sigma ** 2))\n elif np.ndim(x) > 1 and np.ndim(y) > 1:\n result = np.exp(- (np.linalg.norm(x[:, np.newaxis] - y[np.newaxis, :], 2, axis=2) ** 2) / (2 * sigma ** 2))\n return result\n\nclass SupportVectorMachines():\n def __init__(self, X= None, Y= None, max_iterations = 50, epsilon = 0.001, C= 1.0, kernel = None,\n min_optimisation_stop = 0.000001):\n self.X = X\n self.Y = Y\n self.alpha = np.mat(np.zeros((X.shape[0],1)))\n self.b = np.mat([[0]])\n self.max_iterations = max_iterations\n self.epsilon = epsilon\n self.C = C\n self.min_optimisation_stop = min_optimisation_stop\n \n if kernel == None:\n self.kernel = linear_kernel\n elif kernel == 'Gaussian':\n self.kernel = gaussian_kernel\n\n \n def prepare_data(self):\n return\n \n def perform_smo(self):\n alpha_pairs_optimised = 0\n for i in range(self.X.shape[0]):\n Ei = np.multiply(self.Y, self.alpha).T * self.kernel(self.X ,self.X[i]) + self.b - self.Y[i]\n if (self.check_kkt(self.alpha[i], Ei)):\n j = self.second_alpha_to_opt(i,self.X.shape[0])\n Ej = np.multiply(self.Y, self.alpha).T * self.kernel(self.X , self.X[j]) + self.b - self.Y[j]\n alphaoldi = self.alpha[i].copy()\n alphaoldj = self.alpha[j].copy()\n bounds = self.alpha_bounding(self.alpha[i], self.alpha[j], self.Y[i], self.Y[j])\n k11 = self.kernel(self.X[i], self.X[i])\n k12 = self.kernel(self.X[i], self.X[j])\n k22 = self.kernel(self.X[j], self.X[j])\n n_eta = 2 * k12 - k11 - k22\n if bounds[0] != bounds[1] and n_eta <0 :\n if self.optimize_alpha_pair( i, j, Ei, Ej, n_eta, bounds, alphaoldi, alphaoldj):\n alpha_pairs_optimised = alpha_pairs_optimised + 1\n return alpha_pairs_optimised\n \n def check_kkt(self, alpha, E):\n return (alpha > 0 and np.abs(E) < self.epsilon) or (alpha < self.C or np.abs(E) > self.epsilon)\n \n def second_alpha_to_opt(self, indexof1alpha, nrows):\n indexof2alpha = indexof1alpha\n while (indexof1alpha == indexof2alpha):\n indexof2alpha = int(np.random.uniform(0,nrows))\n return indexof2alpha\n \n def alpha_bounding(self, alpha_i, alpha_j, y_i, y_j):\n bounds = [2]\n if (y_i == y_j):\n bounds.insert(0, max(0,alpha_j + alpha_i -self.C))\n bounds.insert(1, min(self.C,alpha_j + alpha_i))\n else:\n bounds.insert(0, max(0,alpha_j - alpha_i ))\n bounds.insert(1, min(self.C,alpha_j - alpha_i + self.C))\n return bounds\n \n def optimize_alphai_alphaj(self, i , j, alpha_j_old):\n self.alpha[i] = self.alpha[j] * self.Y[i] *(alpha_j_old - self.alpha[j])\n\n def clip_alpha_j(self, j, bounds):\n if self.alpha[j] < bounds[0] :\n self.alpha[j] = bounds[0]\n if self.alpha[j] > bounds[1]:\n self.alpha[j] = bounds[1]\n\n def optimize_alpha_pair(self, i, j, Ei, Ej, n_eta, bounds, alphaoldi, alphaoldj):\n flag = False\n self.alpha[j] = self.alpha[j] - self.Y[j] * (Ei - Ej) / n_eta\n self.clip_alpha_j(j, bounds)\n if (abs(self.alpha[j] - alphaoldj) >= self.min_optimisation_stop):\n self.optimize_alphai_alphaj(i,j,alphaoldj)\n self.optimize_b(i, j, Ei, Ej, alphaoldi, alphaoldj)\n flag = True\n return flag\n \n def optimize_b(self,i, j, Ei, Ej, alphaoldi, alphaoldj):\n b1 = self.b - Ei - self.Y[i] * (self.alpha[i] - alphaoldi) * self.kernel(self.X[i],self.X[i]) \\\n - self.Y[j] * (self.alpha[j] - alphaoldj) * self.kernel(self.X[i],self.X[j])\n b2 = self.b - Ej - self.Y[i] * (self.alpha[i] - alphaoldi) * self.kernel(self.X[i],self.X[j]) \\\n - self.Y[j] * (self.alpha[j] - alphaoldj) * self.kernel(self.X[j] ,self.X[j])\n if (0 < self.alpha[i] and (self.C > self.alpha[i])):\n self.b = b1\n elif (0 < self.alpha[j] and (self.C > self.alpha[j])):\n self.b = b2\n else:\n self.b = (b1 + b2)/2.0\n \n def calculate_w(self, alpha, X, Y):\n w = np.zeros((X.shape[1],1))\n for i in range(X.shape[0]):\n w = w + np.multiply(Y[i] * alpha[i], X[i].T)\n return w\n \n def fit(self):\n i = 0\n while (i < self.max_iterations):\n if (self.perform_smo() == 0):\n i = i+1\n else:\n i = 0\n self.W = self.calculate_w(self.alpha, self.X, self.Y)\n\n def predict_row(self, x):\n classification = 0\n if (np.sign((x @ self.W + self.b).item(0,0)) == 1):\n classification = 1\n return classification\n\n \n\n\ndata = [\n [[9.12, 3.12], [+1]],\n [[9.12, 5.12], [+1]],\n [[5.12, 5.12], [-1]],\n [[8.12, 6.65], [+1]],\n [[4.65, 4.12], [-1]]\n ]\n\nX = []\nY = []\n\nfor i in range(len(data)):\n X.append(data[i][0])\n Y.append(data[i][1])\n\nsvm = SupportVectorMachines(X= np.mat(X), Y= np.mat(Y))\nsvm.fit()\n\nprint(svm.W)\nprint(svm.b)","sub_path":"Regression and SVM Code/svm_smo.py","file_name":"svm_smo.py","file_ext":"py","file_size_in_byte":5602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"253329478","text":"# -*- coding: utf-8 -*-\nfrom django import forms\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom common.forms import BaseForm\nfrom .models import Lab\n\n\nclass LabBaseForm(BaseForm):\n\n def clean(self):\n data = super(LabBaseForm, self).clean()\n if 'investigator' in data:\n if 'members' in data and set(data['investigator']) & set(data['members']):\n self._errors[\"members\"] = self.error_class(['field value \\'investigator\\' should not interfere with the field values \\'members\\''])\n del data['members']\n if 'guests' in data and set(data['investigator']) & set(data['guests']):\n self._errors[\"guests\"] = self.error_class(['field value \\'investigator\\' should not interfere with the field values \\'guests\\''])\n del data['guests']\n return data\n\n\nclass LabForm(LabBaseForm):\n \"\"\"\n Form for create/edit laboratory\n \"\"\"\n class Meta:\n model = Lab\n fields = ('name', 'investigator', 'members', 'guests')\n\n def __init__(self, *args, **kwargs):\n super(LabForm, self).__init__(*args, **kwargs)\n self.fields['investigator'].widget.attrs['data-dependent'] = 'members,guests'\n self.fields['members'].widget.attrs['data-dependent'] = 'investigator,guests'\n self.fields['guests'].widget.attrs['data-dependent'] = 'members,investigator'\n self.user = self.initial['user']\n del self.initial['user']\n\n def clean(self):\n data = super(LabForm, self).clean()\n\n if self.instance.id and self.instance.is_member(self.user):\n if 'investigator' in self.changed_data and self.instance.investigator != data['investigator']:\n self._errors['investigator'] = self.error_class([_('You have not permission change lab\\'s investigator')])\n del data['investigator']\n return data\n","sub_path":"apps/labs/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"245869075","text":"\n# model.py file\n\nimport csv\nimport cv2\nimport numpy as np\nimport matplotlib\nmatplotlib.use('agg')\nimport matplotlib.pyplot as plt\n\n# Read in recorded data from csv file\nlines = []\nwith open('track12/driving_log.csv') as csvfile:\n reader = csv.reader(csvfile)\n for line in reader:\n lines.append(line)\n\nlines = lines[1:]\nfrom sklearn.model_selection import train_test_split\nimport sklearn\nfrom sklearn.utils import shuffle\nshuffle(lines)\n# Split recorded into training and validation sets 80:20\ntrain_samples, valid_samples = train_test_split(lines, test_size=0.2)\n\n#Steering correction to apply for image frames from left or right camera perspective\ncorrection = 0.18\n\ndef augmentData(images, measurements):\n aug_images, aug_measurements = [], []\n for image, meas in zip(images, measurements):\n aug_images.append(image)\n aug_images.append(cv2.flip(image,1))\n aug_measurements.append(meas)\n aug_measurements.append(meas*-1.0)\n return (aug_images, aug_measurements)\n\n# Batch generator to generate data during training/validation\ndef generator(samples, batch_size=100):\n num_samples = len(samples)\n while 1: #loop forever so the generator never terminates\n shuffle(samples)\n for offset in range(0,num_samples,batch_size):\n end = offset+batch_size\n if (offset+batch_size)>num_samples:\n end = num_samples\n batch_samples = samples[offset:end]\n\n images = []\n angles = []\n for batch_sample in batch_samples:\n name = 'track12/IMG/' + batch_sample[0].split('/')[-1]\n center_image = cv2.imread(name)\n center_image = cv2.cvtColor(center_image, cv2.COLOR_BGR2RGB)\n center_angle = float(batch_sample[3])\n\n name = 'track12/IMG/' + batch_sample[1].split('/')[-1]\n left_image = cv2.imread(name)\n left_image = cv2.cvtColor(left_image, cv2.COLOR_BGR2RGB)\n left_angle = center_angle + correction\n\n name = 'track12/IMG/' + batch_sample[2].split('/')[-1]\n right_image = cv2.imread(name)\n right_image = cv2.cvtColor(right_image, cv2.COLOR_BGR2RGB)\n right_angle = center_angle - correction\n\n images.extend([center_image, left_image, right_image])\n angles.extend([center_angle, left_angle, right_angle])\n\n X_train = np.asarray(images)\n y_train = np.asarray(angles)\n yield sklearn.utils.shuffle(X_train, y_train)\n\ndef resize(image):\n from keras.backend import tf as ktf\n return ktf.image.resize_images(image, (66,200))\n \nfrom keras.models import Sequential\nfrom keras.layers import Flatten, Dense, Lambda, Cropping2D, Dropout\nfrom keras.layers.convolutional import Convolution2D\nfrom keras.layers.pooling import MaxPooling2D\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.backend import tf as ktf\n\n# Network architecture\nmodel = Sequential()\nmodel.add(Lambda(lambda x: (x/127.5) - 1.0, input_shape=(160,320,3), name='norm'))\n# Crop image to region of interest\nmodel.add(Cropping2D(cropping=((70,20),(0,0))))\nmodel.add(Lambda(resize, name = 'resize'))\nmodel.add(Convolution2D(24,5,5,subsample=(2,2),activation=\"relu\"))\nmodel.add(Convolution2D(36,5,5,subsample=(2,2),activation=\"relu\"))\nmodel.add(Convolution2D(48,5,5,subsample=(2,2),activation=\"relu\"))\nmodel.add(Convolution2D(64,3,3,activation=\"relu\"))\nmodel.add(Convolution2D(64,3,3,activation=\"relu\"))\nmodel.add(Flatten())\nmodel.add(Dense(100, activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(50, activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(10))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(1))\n\nmodel.compile(loss='mse', optimizer='adam')\n\ndef visualizeOutput(model, layer_name, image):\n layer_model = Model(input=model.input, output=model.get_layer(layer_name).output)\n image = np.expand_dims(image, axis=0)\n layer_output = layer_model.predict(image)\n print('Features shape: ', layer_output.shape)\n #plot\n plt.imshow(layer_output.squeeze())\n plt.show()\n\ntrain_generator = generator(train_samples)\nvalid_generator = generator(valid_samples)\nprint('Num train samples: ', len(train_samples))\n# Run training and validation model\nmodel.fit_generator(train_generator, samples_per_epoch = len(train_samples)*3, validation_data = valid_generator, nb_val_samples=len(valid_samples)*3, nb_epoch=10)\n\nmodel.save('model.h5')\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"423548000","text":"##### Writer : \"Atia\"\n\n\n###### Importign the Library\nimport os\nimport pandas as pd\nimport numpy as np\npd.set_option('display.max_columns', 500)\npd.set_option('display.width', 20)\nimport matplotlib.pyplot as plt\n\nos.chdir(\"/Users/macbook/Documents/pyhton/portfolio/Two_Line_Diagram\")\n\n#### reading the reference list\npath = \"renamed.xlsx\"\ndd = pd.read_excel(path)\nd = dd[[\"city\", \"source\", \"tag\", \"new_tag\"]]\n\n#### Find all the unique values in new_tag_dimension\ndimensions = d.new_tag.unique()\n\n\ndef lineplot (dim):\n d[\"binary\"] = np.where(d[\"new_tag\"] == dim, d[\"tag\"], \"other_tags\")\n df = d[[\"source\", \"binary\"]]\n tab = pd.pivot_table(df, index=\"source\", columns=\"binary\", aggfunc=len)\n tab = tab.fillna(0)\n\n tab[\"sum\"] = tab.sum(axis=1)\n\n #####make a copy for normalizaiton\n tab_Nor = tab.copy()\n tab = tab.drop(['other_tags', \"sum\"], axis=1)\n tab[\"sum\"] = round(tab.sum(axis=1), 2)\n tab = tab.fillna(0)\n\n list = tab_Nor.columns.to_list()\n for i in range(len(tab_Nor)):\n for j in range(len(list) - 1):\n tab_Nor.iloc[i, j] = round(((tab_Nor.iloc[i, j] / tab_Nor.iloc[i, -1]) * 100), 2)\n\n tab_Nor = tab_Nor.drop([\"sum\", 'other_tags'], axis=1)\n tab_Nor[\"sum\"] = round(tab_Nor.sum(axis=1), 2)\n tab_Nor = tab_Nor.fillna(0)\n tab_Nor = tab_Nor.drop([\"sum\"], axis=1)\n tab_Nor= tab_Nor.transpose()\n\n\n #############################################\n ###### with respect to internal percentages\n\n da = d[d[\"new_tag\"] == dim]\n da = da[[\"source\", \"tag\"]]\n tab2 = pd.pivot_table(da, index=\"source\", columns=\"tag\", aggfunc=len)\n tab2 = tab2.fillna(0)\n\n tab2[\"sum\"] = tab2.sum(axis=1)\n list2 = tab2.columns.to_list()\n\n for i in range(len(tab2)):\n for j in range(len(list2) - 1):\n tab2.iloc[i, j] = (round(((tab2.iloc[i, j] / tab2.iloc[i, -1]) * 100), 2))\n\n tab2 = tab2.drop([\"sum\"], axis=1)\n tab2_n= tab2.transpose()\n\n\n\n\n index_list = tab_Nor.index.values.tolist()\n\n # # Plotting the bars\n plt.rcParams['font.family'] = \"sans-serif\"\n\n fig, axs = plt.subplots(2, figsize=(12,16))\n\n\n\n # Create a bar with first data,\n\n\n\n axs[0].plot(tab_Nor ['Official Websites'],\n\n # with alpha 0.5\n alpha=0.8,\n # with color\n color='#3ca3bf',\n\n # with label the first value in first_name\n label= 'Official Websites',\n linewidth=2.0)\n\n\n axs[0].plot(tab_Nor['Personal Blogs'],\n\n # with alpha 0.5\n alpha=0.8,\n # with color\n color='#f68b37',\n\n # with label the first value in first_name\n label='Personal Blogs',\n linewidth=2.0\n )\n\n # Create a bar with second data,\n axs[0].plot(tab_Nor['Third Party Websites'],\n\n # with alpha 0.5\n alpha=0.8,\n # with color\n color='#735698',\n\n # with label the first value in first_name\n label='Third Party Websites',\n linewidth=2.0\n )\n\n\n axs[0].set_xticklabels(index_list, rotation=45, fontsize=10, ha='right')\n\n axs[0].set_ylabel('Image Frequency', fontsize=10, labelpad=10)\n axs[0].set_title('The Frequency of %s Attributes Compared to All Data ' %dim, fontsize=12, pad=20,\n fontname='Times New Roman')\n axs[0].set_xlabel('Image Attributes', fontsize=10, labelpad=10)\n axs[0].xaxis.grid()\n\n\n ##### Ajusting the legend\n axs[0].legend(['Official Websites', 'Personal Blogs', 'Third Party Websites'])\n axs[0].legend(prop={\"size\": 4}, borderpad=.5, labelspacing=1.5)\n\n axs[0].legend(loc='upper left', bbox_to_anchor=(0.01, .99), ncol=3,\n borderaxespad=.2, prop={\"size\": 4})\n\n\n ########################\n ########################\n # Create the second image\n axs[1].plot(tab2_n['Official Websites'],\n\n alpha=0.8,\n # with color\n color='#3ca3bf',\n\n # with label the first value in first_name\n label= 'Official Websites',\n linewidth=2.0\n )\n\n axs[1].plot(tab2_n['Personal Blogs'],\n\n # with alpha 0.5\n alpha=0.8,\n # with color\n color='#f68b37',\n\n # with label the first value in first_name\n label='Personal Blogs',\n linewidth=2.0\n )\n\n # Create a bar with second data,\n axs[1].plot(tab2_n['Third Party Websites'],\n\n # with alpha 0.5\n alpha=0.8,\n # with color\n color='#735698',\n\n # with label the first value in first_name\n label='Third Party Websites',\n linewidth=2.0\n )\n\n axs[1].set_xticklabels(index_list, rotation=45, fontsize=9, ha='right')\n\n axs[1].set_ylabel('Image Frequency', fontsize=12, labelpad=10)\n axs[1].set_title('The Frequency of %s Attributes Compared to Each other' %dim, fontsize=11, pad=20,\n fontname='Times New Roman')\n axs[1].set_xlabel('Image Attributes', fontsize=12, labelpad=10)\n axs[1].xaxis.grid()\n\n\n ##### Ajusting the legend\n axs[1].legend(['Official Websites', 'Personal Blogs', 'Third Party Websites'])\n axs[1].legend(prop={\"size\": 10}, borderpad=.5, labelspacing=1.5)\n\n axs[1].legend(loc='upper left', bbox_to_anchor=(0.01, .99), ncol=3,\n borderaxespad=.2, prop={\"size\": 10})\n ######## arrancing the xticks\n plt.subplots_adjust( wspace=0.3, hspace=.6,bottom=.15 )\n\n\n ##### saving the files\n file = ('%s Line plot.png' % dim)\n path = \"pictures\"\n figname = os.path.join(path, file)\n\n if os.path.exists(figname):\n os.remove(figname)\n\n plt.savefig(figname, dpi= 180)\n # plt.show()\n\n\n\nfor i in dimensions:\n lineplot(i)","sub_path":"Two_Line_Diagram/Two_line_graph.py","file_name":"Two_line_graph.py","file_ext":"py","file_size_in_byte":5868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"474201319","text":"import numpy as np\nimport pandas as pd\nclass Bookmy_Tickets:\n print('Welcome to StarkCinemas')\n\n def __init__(self):\n print('******************************************')\n print('PLEASE ENTER YOUR CHOICE : ')\n print('******************************************')\n print('1. Show the screens')\n print('2. Buy a Tickets')\n print('3. Statistics')\n print('4. Show booked Tickets User Info')\n print('5. Exit')\n choice = int(input('Enter your choice'))\n if choice == 0:\n exit()\n if choice == 1:\n print('Called')\n Bookmy_Tickets.show_screens()\n\n @classmethod\n def show_screens(self):\n\n print('Type of screen you want enjoy watching movie')\n print('1 . IMAX 4K Dual Digital Projecter')\n print('2 . Min_screen with Stellar Surround Sound')\n\n choice=int(input('Enter your screen Type you want'))\n\n if choice == 1:\n print(\"Total Seats in Imax_screen:\")\n self.row = 6\n self.col = 6\n self.details = {}\n self.matrix = []\n self.pricing = {}\n for i in range(self.row):\n a = []\n for j in range(self.col):\n a.append(\"S\")\n\n self.matrix.append(a)\n print(end=\" \")\n for j in range(self.col):\n print(j + 1, end=\" \")\n print()\n for i in range(self.row):\n print(i + 1, end=\" \")\n for j in range(6):\n print(self.matrix[i][j], end=\" \")\n print()\n\n buy = input('To Procced with Booking Tickets Press \"Yes\" or \"No\" ')\n if buy in ['Yes', 'yes', 'YES']:\n Bookmy_Tickets.Buy_tickets()\n elif buy in ['No', 'NO', 'no']:\n Bookmy_Tickets.display()\n # arr = np.array(self.matrix)\n # df = pd.DataFrame(arr)\n # df.iloc[2, 3] = 'b'\n # print(df)\n\n\n elif choice == 2:\n\n print(\"Total Seats in MinScreen :\")\n self.row = 8\n self.col = 8\n self.details = {}\n self.matrix = []\n\n self.pricing = {}\n for i in range(self.row):\n a = []\n for j in range(self.col):\n a.append(\"S\")\n\n self.matrix.append(a)\n print(end=\" \")\n for j in range(self.col):\n print(j + 1, end=\" \")\n print()\n for i in range(self.row):\n print(i + 1, end=\" \")\n for j in range(8):\n print(self.matrix[i][j], end=\" \")\n print()\n # arr = np.array(self.matrix)\n #\n # # print(arr)\n #\n # df = pd.DataFrame(arr)\n # df.iloc[2,3] = 'b'\n # print(df)\n\n # print('To Procced with Booking Tickets Press \"Yes\" or \"No\" ')\n buy=input('To Procced with Booking Tickets Press \"Yes\" or \"No\" ')\n if buy in ['Yes' , 'yes' , 'YES']:\n Bookmy_Tickets.Buy_tickets()\n if buy in ['No' , 'NO' , 'no']:\n Bookmy_Tickets.display()\n\n #@classmethod\n def Buy_tickets(self):\n print(\"Enter Row and Column Number for your desired Place\")\n arr = np.array(self.matrix)\n df = pd.DataFrame(arr)\n df.iloc[2,3] = 'b'\n print(df)\n\n\n\n\n\n\n\nmovie = Bookmy_Tickets()\nmovie.Buy_tickets()\n","sub_path":"bookmyshow.py","file_name":"bookmyshow.py","file_ext":"py","file_size_in_byte":3492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"160889681","text":"#!/usr/bin/env python\n\n\"\"\"\n\tThis Python program implements an on-line coverage path planning\n\tmethod for 2-dimensional surfaces embedded in R3. It is based on the\n\twork by Atkar et al. The strategy consists in covering successive\n\thorizontal slice plances intersecting the object. Sweeping direction\n\tis from top to bottom.\n\"\"\"\n\n# !!! THIS FILE IS MEANT TO BE EXECUTED USING CIRCLINGWORKS_uswim_cpp_scene.xml SCENE FILE IN UWSim\n\n# ROS stuff\nimport roslib; roslib.load_manifest('cirs_cpp')\nimport rospy\nimport actionlib\n\n# Python stuff\nfrom math import *\nfrom numpy import *\n\n# Sensor messages\nfrom auv_msgs.msg import *\nfrom sensor_msgs.msg import LaserScan\n\n# Linear regression\nfrom simple_linear_regression import SimpleLinearRegression\n\ndef normalizeAngle(angle) :\n return (angle + ( 2.0 * pi * floor( ( pi - angle ) / ( 2.0 * pi ) ) ) )\n\n# Just some constants definition\nclass PlannerParams :\n\tXCTVEL = 4.0 # Requested velocity in X when approaching object\n\tOMEGA = 4.0 # Offset distance to target object\n\tSTEP_LENGTH = 1.0 # COS edge following step length\n\nclass PlannerStates :\n\tAPPROACH = 1\n\tEDGE_FOLLOWING = 2\n\n# Main planner class\nclass SurfaceCoveragePlanner :\n\n\t###############\n\t# Constructor #\n\t###############\n\tdef __init__(self):\n\t\t# Planner FSM\n\t\tself.state = PlannerStates.APPROACH\n\n\t\t# Input data\n\t\tself.hDataAvailable = False\n\t\tself.vDataAvailable = False\n\t\tself.navDataAvailable = False\n\t\tself.hScan = LaserScan()\n\t\tself.vScan = LaserScan()\n\t\tself.navSts = NavSts()\n\t\t\n\t\t# Create subscribers for sensor data\n\t\trospy.Subscriber(\"/cirs_cpp/profile_h\", LaserScan, self.horizontalScanCallback)\n\t\trospy.Subscriber(\"/cirs_cpp/profile_v\", LaserScan, self.verticalScanCallback)\n\n\t\t# Create subscriber for navigation data\n\t\trospy.Subscriber(\"/navigation_g500/nav_sts\", NavSts, self.navCallback)\n\t\t\n\t\t# Create publisher for steering at low level\n\t\tself.bvrPub = rospy.Publisher(\"/control_g500/body_velocity_req\", BodyVelocityReq)\n\t\t\n\t\t# Create an action client for sending waypoint requests\n\t\trospy.loginfo(\"Creating action client...\")\n\t\tself.actionClient = actionlib.SimpleActionClient('absolute_x_y_z_yaw', WorldWaypointReqAction)\n\t\trospy.loginfo(\"Waiting for action server...\")\n\t\tself.actionClient.wait_for_server()\n\t\trospy.loginfo(\"Ready to use action client\")\n\t\t\n\t\t# Count action requests\n\t\tself.reqId = 0\n\n\t##########################\n\t# Subscription Callbacks #\n\t##########################\n\tdef horizontalScanCallback(self, data):\n\t\tself.hScan = data\n\t\tself.hDataAvailable = True\n\n\tdef verticalScanCallback(self, data):\n\t\tself.vScan = data\n\t\tself.vDataAvailable = True\n\n\tdef navCallback(self, data):\n\t\tself.navSts = data\n\t\tself.navDataAvailable = True\n\n\t############\n\t# Steering #\n\t############\n\tdef requestBodyVelocity(self, vx, vy, vz, vyaw):\n\t\t# Function for steering the robot at the low level\n\t\t\n\t\t# Build BodyVelocityReq message according to params\n\t\tmessage = BodyVelocityReq()\n\n\t\tmessage.header.stamp = rospy.get_rostime()\n\t\tmessage.goal.priority = 10 # BodyVelocityReq.PRIORITY_AVOID_OBSTACLE\n\t\tmessage.goal.requester = rospy.get_name()\n\t\tmessage.twist.linear.x = vx\n\t\tmessage.twist.linear.y = vy\n\t\tmessage.twist.linear.z = vz\n\t\tmessage.twist.angular.z = vyaw\n\n\t\tmessage.disable_axis.x = False;\n\t\tmessage.disable_axis.y = False;\n\t\tmessage.disable_axis.z = True;\n\t\tmessage.disable_axis.roll = True;\n\t\tmessage.disable_axis.pitch = True;\n\t\tmessage.disable_axis.yaw = True;\n\n\t\t# Publish built message\n\t\trospy.loginfo(rospy.get_name()+\", publishing BodyVelocityReq message\")\n\t\tself.bvrPub.publish(message)\t\t\n\n\tdef moveTo(self, x, y, z, yaw):\n\t\t# Create a goal to send to the action server\n\t\tgoal = WorldWaypointReqGoal()\n\t\tgoal.goal.requester = rospy.get_name()\n\t\tgoal.goal.id = self.reqId\n\t\t\n\t\tself.reqId = self.reqId + 1\n\t\t\n\t\tgoal.goal.priority = 30\n\t\tgoal.altitude_mode = False\n\t\t\n\t\tgoal.position.north = x\n\t\t\n\t\tgoal.position.east = y\n\n\t\tgoal.position.depth = self.navSts.position.depth\t\n\n\t\tgoal.orientation.yaw = yaw\n\t\t\n\t\t# Don't care about those\n\t\tgoal.altitude = 0\n\t\tgoal.orientation.roll = 0\n\t\tgoal.orientation.pitch = 0\n\n\t\t# Set movement type\n\t\tgoal.disable_axis.x = False\n\t\tgoal.disable_axis.y = False\n\t\t\n\t\tgoal.disable_axis.z = False\n\n\t\tgoal.disable_axis.roll = True\n\t\tgoal.disable_axis.pitch = True\n\t\tgoal.disable_axis.yaw = False\n\n\t\t# Set tolerances to 0 (default values)\n\t\tgoal.position_tolerance.x = 0.2\n\t\tgoal.position_tolerance.y = 0.2\n\t\tgoal.position_tolerance.z = 0.2\n\t\tgoal.orientation_tolerance.roll = 0.1\n\t\tgoal.orientation_tolerance.pitch = 0.1\n\t\tgoal.orientation_tolerance.yaw = 0.1\n\n\t\t# Send waypoint request to the action server\n\t\trospy.loginfo(\"Moving to point...\")\n\t\t#rospy.loginfo(\"%s, Requesting GOAL:\\n%s\", rospy.get_name(), goal)\n\t\tself.actionClient.send_goal(goal)\n\t\tself.actionClient.wait_for_result()\n\t\tresult = self.actionClient.get_result()\n\t\t#rospy.loginfo(\"%s, Goal RESULT:\\n%s\", rospy.get_name(), result)\t\n\t\trospy.loginfo(\"Point reached\")\n\n\tdef moveBy(self, dx, dy, dz, dyaw):\n\t\t\n\t\t# Coordinate frame transformation\n\t\ta = self.navSts.orientation.yaw\n\t\tcx = self.navSts.position.north\n\t\tcy = self.navSts.position.east\n\t\tT = matrix([[cos(a), -sin(a), cx], [sin(a), cos(a), cy], [0,0,1]]) # Transformation matrix\n\t\tp = matrix([[dx], [dy], [1]]) # Point w.r.t. vehicle frame\n\t\tpw = T*p # Point w.r.t. world frame\n\n\t\t# Now we move to a point in world coords\n\t\tx = pw[0]\n\t\ty = pw[1]\n\t\tz = self.navSts.position.depth + dz\n\t\tyaw = normalizeAngle(self.navSts.orientation.yaw + dyaw)\n\t\t\n\t\tself.moveTo(x, y, z, yaw)\n\n\tdef followTrajectory(self, xCoords, yCoords, zCoords, yawCoords):\n\t\t\n\t\t# Assuming all list arguments have the same length\n\t\t\n\t\tfor i in range(len(xCoords)):\n\t\t\trospy.loginfo(\"FT, moving to point i=%d, x=%f, y=%f, z=%f, yaw=%f rad, %f deg\", i, xCoords[i], yCoords[i], zCoords[i], yawCoords[i], degrees(yawCoords[i]))\n\t\t\tself.moveTo(xCoords[i], yCoords[i], zCoords[i], yawCoords[i])\n\n\tdef generateCircleWaypoints(self):\n\t\t\n\t\t# Generate circle points spaced by STEP_LENGTH arcs around the current\n\t\t# robot position, radius = OMEGA\n\t\t\t\t\n\t\t\"\"\"\n\t\t2D rotation about a point\n\t\t\n\t\txout\n\t\tyout\n\t\t1\t\t\n\t\t=\n\t\tr00 \tr01 \tx - r00*x - r01*y\n\t\tr10 \tr11 \ty - r10*x - r11*y\n\t\t0 \t0 \t1\n\t\t*\n\t\txin\n\t\tyin\n\t\t1\n\n\t\tr00 = cos(a), r01 = -sin(a), r10 = sin(a), r11 = cos(a)\n\t\ta = angle we are rotating around (in appropriate units for the trig functions we are using)\n\t\txin,yin = the coordinates of the input point\n\t\txout,yout = the coordinates of the output point (the result)\n\t\tx,y = the coordinates of the point that we are rotating around.\n\t\t\"\"\"\n\n\t\t# Initial configuration\n\t\tinitial_x = self.navSts.position.north\n\t\tinitial_y = self.navSts.position.east\n\t\tinitial_yaw = self.navSts.orientation.yaw\n\t\t\n\t\t# Circle center\n\t\tcx = initial_x + PlannerParams.OMEGA*cos(initial_yaw)\n\t\tcy = initial_y + PlannerParams.OMEGA*sin(initial_yaw)\n\n\t\t# Rotation angle corresponding to one STEP_LENGTH arc\n\t\ta = PlannerParams.STEP_LENGTH / PlannerParams.OMEGA\n\t\t\n\t\t# Transformation matrix for rotatin around the circle's center\n\t\tT = matrix([[cos(a), -sin(a), cx - cos(a)*cx + sin(a)*cy],\\\n\t\t [sin(a), cos(a), cy - sin(a)*cx - cos(a)*cy],\\\n\t\t [0,0,1]])\n\n\t\txCoords = []\n\t\tyCoords = []\n\t\tyawCoords = []\n\t\tcurrentPoint = matrix([[initial_x], [initial_y], [1]])\n\t\tcurrentYaw = initial_yaw\n\t\twhile a < 2*pi:\n\t\t\t# Apply tranformation\n\t\t\tnextPoint = T*currentPoint\n\t\t\tnextYaw = atan2( cy - nextPoint[1], cx - nextPoint[0] )\n\t\t\t\n\t\t\t# Tweak to \"look forward\" for the edge\n\t\t\tnewtYaw = normalizeAngle(nextYaw - radians(20))\n\t\t\t\n\t\t\txCoords.append(nextPoint[0])\n\t\t\tyCoords.append(nextPoint[1])\n\t\t\tyawCoords.append(nextYaw)\n\t\t\t\n\t\t\tcurrentPoint = nextPoint\n\t\t\tcurrentYaw = nextYaw\n\t\t\ta = a + PlannerParams.STEP_LENGTH / PlannerParams.OMEGA\n\t\t\n\t\t# Reverse lists to match edge following direction\n\t\txCoords.reverse()\n\t\tyCoords.reverse()\n\t\tyawCoords.reverse()\n\t\t\n\t\treturn {'xCoords': xCoords, 'yCoords': yCoords, 'yawCoords': yawCoords}\n\t\t\t\t\n\t##############\n\t# Perception #\n\t##############\n\tdef estimateProfile(self):\n\t\t\n\t\trospy.loginfo(\"R_3=%f, R_5=%f\", self.hScan.ranges[3], self.hScan.ranges[5])\n\t\t\n\t\tx1 = self.hScan.ranges[3]*cos(radians(90))\n\t\ty1 = self.hScan.ranges[3]*sin(radians(90))\n\n\t\tx2 = self.hScan.ranges[5]*cos(radians(90-20))\n\t\ty2 = self.hScan.ranges[5]*sin(radians(90-20))\n\n\t\trospy.loginfo(\"p1=(%f, %f), p2=(%f, %f)\", x1, y1, x2, y2)\n\n\t\tm = (y2-y1)/(x2-x1)\n\t\t\n\t\trospy.loginfo(\"Slope=%f, %f rad, %f deg\",m,atan(m),degrees(atan(m)))\n\n\t\tdx = m*PlannerParams.STEP_LENGTH\n\t\tdy = PlannerParams.STEP_LENGTH\n\t\tdz = 0\n\t\tdyaw = normalizeAngle(-atan(m))\n\t\trospy.loginfo(\"Motion would be dx=%f, dy=%f, dz=%f, dyaw=%f deg\", dx, dy, dz, degrees(dyaw))\n\t\t\n\t\treturn m\n\n\t########################\n\t# Planner's FSM states #\n\t########################\n\tdef approachObject(self):\n\t\t\t\n\t\t# Check front distance...\n\t\tif self.hScan.ranges[3] > PlannerParams.OMEGA:\n\t\t\t#self.requestBodyVelocity(PlannerParams.XCTVEL, 0.0, 0.0, 0.0)\n\t\t\tself.moveBy(0.3, 0, 0, 0)\n\t\telse:\n\t\t\tself.requestBodyVelocity(0.0, 0.0, 0.0, 0.0)\n\t\t\tself.state = PlannerStates.EDGE_FOLLOWING\n\n\tdef followEdge(self):\n\t\t# Follow COS edge in horizontal plane CCW from top,\n\t\t# uses waypoint navigation\n\n\t\tMAX_RANGE = 20.0 # TODO: move param to a more suitable place\n\n\t\tif self.hScan.ranges[3] < MAX_RANGE and self.hScan.ranges[5] < MAX_RANGE :\n\t\t\tm = self.estimateProfile()\n\n\t\t\tdx = m*PlannerParams.STEP_LENGTH\n\t\t\tdy = PlannerParams.STEP_LENGTH\n\t\t\tdz = 0\n\t\t\tdyaw = normalizeAngle(-atan(m))\n\t\t\trospy.loginfo(\"Following edge, moving robot by: dx=%f, dy=%f, dz=%f, dyaw=%f\", dx, dy, dz, dyaw)\n\t\t\tself.moveBy(dx, dy, dz, dyaw)\n\t\t\t\n\t\telse:\n\t\t\t# We've found a sharp edge here, apply circle strategy\n\t\t\tpoints = self.generateCircleWaypoints()\n\t\t\txCoords = points['xCoords']\n\t\t\tyCoords = points['yCoords']\n\t\t\tzCoords = [self.navSts.position.depth]*len(points['xCoords'])\n\t\t\tyawCoords = points['yawCoords']\n\t\t\t\n\t\t\tfor i in range(len(points['xCoords'])):\n\t\t\t\trospy.loginfo(\"Circle, moving to point i=%d, x=%f, y=%f, z=%f, yaw=%f rad, %f deg\", i, xCoords[i], yCoords[i], zCoords[i], yawCoords[i], degrees(yawCoords[i]))\n\t\t\t\tself.moveTo(xCoords[i], yCoords[i], zCoords[i], yawCoords[i])\n\t\t\t\t\n\t\t\t\trospy.loginfo(\"Checking ranges...\")\n\t\t\t\tif self.hScan.ranges[3] < MAX_RANGE and self.hScan.ranges[5] < MAX_RANGE :\n\t\t\t\t\trospy.loginfo(\"Edge found again! Awesome!\")\n\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\trospy.loginfo(\"Edge not found yet, circling continues\")\t \n\n\t\t\"\"\"\n\t\ta0 = radians(90+30)\n\t\ta1 = radians(90+20)\n\t\ta2 = radians(90+10)\n\t\ta3 = radians(90)\n\t\ta4 = radians(90-10)\n\t\ta5 = radians(90-20)\n\t\ta6 = radians(90-30)\n\t\t\n\t\tdata = [ \\\n\t\t(self.hScan.ranges[0]*cos(a0), self.hScan.ranges[0]*sin(a0)), \\\n\t\t(self.hScan.ranges[1]*cos(a1), self.hScan.ranges[1]*sin(a1)), \\\n\t\t(self.hScan.ranges[2]*cos(a2), self.hScan.ranges[2]*sin(a2)), \\\n\t\t(self.hScan.ranges[3]*cos(a3), self.hScan.ranges[3]*sin(a3)), \\\n\t\t(self.hScan.ranges[4]*cos(a4), self.hScan.ranges[4]*sin(a4)), \\\n\t\t(self.hScan.ranges[5]*cos(a5), self.hScan.ranges[5]*sin(a5)), \\\n\t\t(self.hScan.ranges[6]*cos(a6), self.hScan.ranges[6]*sin(a6)) ]\n\n\t\tprint(\"...data is %s\" % data)\n\n\t\tlinRegr = SimpleLinearRegression(data)\n\t\tif not linRegr.run():\n\t\t\tprint(\"...error: failed to calculate parameters\")\n\t\t\treturn\n\n\t\tprint(\"...the coefficient of correlation r = %f (r**2 is %f)\" % (linRegr.r, linRegr.r**2))\n\t\tprint(\"...parameter a of y = f(x) = a + b*x is %f\" % linRegr.a)\n\t\tprint(\"...parameter b of y = f(x) = a + b*x is %f\" % linRegr.b)\n\t\tprint(\"...linear function is then %s\" % linRegr)\n\t\tprint(\"...forecast of next value: f(5) = %f\" % linRegr.function(5))\n\n\t\tfirstY = linRegr.function(1)\n\t\tlastY = linRegr.function(4)\n\t\tchange = (lastY - firstY) / firstY * 100.0\n\n\t\t# keep in mind: reducing of error rate (inverse valuation)!\n\t\tif change < 0:\n\t\t\tprint(\"...the trend is about %.1f%% improvement\" % -change)\n\t\telse:\n\t\t\tprint(\"...the trend is about %.1f%% to the worse\" % change)\n\n\t\trospy.loginfo(\"Moving robot...\")\n\t\tself.moveBy(PlannerParams.STEP_LENGTH, linRegr.b*PlannerParams.STEP_LENGTH, 0, normalizeAngle( self.navSts.orientation.yaw - normalizeAngle(atan(linRegr.b) - radians(90)) ) )\n\t\t\"\"\"\n\t\t\n\tdef iterate(self):\n\t\t\n\t\trospy.loginfo(rospy.get_name()+\", STATE=%d\", self.state)\t\t\n\t\tif self.hDataAvailable and self.vDataAvailable and self.navDataAvailable:\n\n\t\t\tif self.state == PlannerStates.APPROACH:\n\t\t\t\tself.approachObject()\n\t\t\t\t\n\t\t\t\t# Profile estimation test\n\t\t\t\t#m = self.estimateProfile()\n\n\t\t\t\t#points = self.generateCircleWaypoints()\n\t\t\t\t#self.followTrajectory(points['xCoords'], points['yCoords'], [self.navSts.position.depth]*len(points['xCoords']), points['yawCoords'])\n\n\t\t\t\t#return\n\t\t\t\t\n\t\t\telif self.state == PlannerStates.EDGE_FOLLOWING:\n\t\t\t\tself.followEdge()\n\nif __name__ == '__main__':\n\ttry:\n\t\trospy.init_node('surface_coverage_planner')\n\t\tplanner = SurfaceCoveragePlanner()\n\t\tr = rospy.Rate(2)\n\t\twhile not rospy.is_shutdown():\n\t\t\tplanner.iterate()\n\t\t\tr.sleep()\n\texcept rospy.ROSInterruptException: pass\n","sub_path":"cirs_cpp/nodes/CIRCLINGWORKS_surface_coverage_planner.py","file_name":"CIRCLINGWORKS_surface_coverage_planner.py","file_ext":"py","file_size_in_byte":12828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"597626221","text":"import argparse\nimport basf2_mva\n\n# +\ndef get_variables():\n \n my_var=[ 'Btag_d1_R2', 'Btag_d1_thrustBm', 'Btag_d1_thrustOm',\n 'Btag_d1_cosTBTO' ,'Btag_d1_cosTBz', 'Btag_d1_KSFWVariables_hso00',\n 'Btag_d1_KSFWVariables_hso01' ,'Btag_d1_KSFWVariables_hso02',\n 'Btag_d1_KSFWVariables_hso03', 'Btag_d1_KSFWVariables_hso04',\n 'Btag_d1_KSFWVariables_hso10', 'Btag_d1_KSFWVariables_hso12',\n 'Btag_d1_KSFWVariables_hso14' ,'Btag_d1_KSFWVariables_hso20',\n 'Btag_d1_KSFWVariables_hso22', 'Btag_d1_KSFWVariables_hso24',\n 'Btag_d1_KSFWVariables_hoo0', 'Btag_d1_KSFWVariables_hoo1',\n 'Btag_d1_KSFWVariables_hoo2' ,'Btag_d1_KSFWVariables_hoo3',\n 'Btag_d1_KSFWVariables_hoo4',\n 'Btag_d1_px', 'Btag_d1_py', 'Btag_d1_pz', 'Btag_d1_pt'\n ]\n#'Btag_d1_px' 'Btag_d1_py' 'Btag_d1_pz' 'Btag_d1_pt'\n \n# 'Btag_d1_R2', 'Btag_d1_thrustOm',\n# 'Btag_d1_cosTBTO', 'Btag_d1_cosTBz' ,'Btag_d1_KSFWVariables_hso00',\n# 'Btag_d1_KSFWVariables_hso01', 'Btag_d1_KSFWVariables_hso02',\n# 'Btag_d1_KSFWVariables_hso03', 'Btag_d1_KSFWVariables_hso04',\n# 'Btag_d1_KSFWVariables_hso10', 'Btag_d1_KSFWVariables_hso12',\n# 'Btag_d1_KSFWVariables_hso14', 'Btag_d1_KSFWVariables_hso20',\n# 'Btag_d1_KSFWVariables_hso22', 'Btag_d1_KSFWVariables_hso24',\n# 'Btag_d1_KSFWVariables_hoo0', 'Btag_d1_KSFWVariables_hoo1',\n# 'Btag_d1_KSFWVariables_hoo2', 'Btag_d1_KSFWVariables_hoo3',\n# 'Btag_d1_KSFWVariables_hoo4' \n \n#'Bsig_d0_R2' , 'Bsig_d0_thrustOm', 'Bsig_d0_cosTBTO',\n# 'Bsig_d0_cosTBz', 'Bsig_d0_KSFWVariables_hso00',\n# 'Bsig_d0_KSFWVariables_hso01' ,'Bsig_d0_KSFWVariables_hso02',\n# 'Bsig_d0_KSFWVariables_hso03', 'Bsig_d0_KSFWVariables_hso04',\n# 'Bsig_d0_KSFWVariables_hso10', 'Bsig_d0_KSFWVariables_hso12',\n# 'Bsig_d0_KSFWVariables_hso14', 'Bsig_d0_KSFWVariables_hso20',\n# 'Bsig_d0_KSFWVariables_hso22', 'Bsig_d0_KSFWVariables_hso24',\n# 'Bsig_d0_KSFWVariables_hoo0', 'Bsig_d0_KSFWVariables_hoo1',\n# 'Bsig_d0_KSFWVariables_hoo2', 'Bsig_d0_KSFWVariables_hoo3',\n# 'Bsig_d0_KSFWVariables_hoo4'\n\n\n #ksfw_variables = [f'KSFWVariables{arg}' for arg in ksfw_args]\n #cleo_cones = [f'CleoConeCS{i}' for i in range(1,10)]\n # cs_variables = ['cosThetaCMS','foxWolframR1','foxWolframR2','foxWolframR3','foxWolframR4', \n # 'sphericity', 'aplanarity', 'thrust', 'thrustAxisCosTheta', 'cosTBTO', 'cosTBz' ]\n # cs_variables += cleo_cones\n # veto_variables = ['mu_0_isFromJpsiMu','mu_1_isFromJpsiMu', 'mu_0_isInD', 'mu_1_isInD', 'isFromJpsiMuRad']\n # kin_variables = ['pCMS', 'mu_0_pCMS', 'mu_1_pCMS','pCMSDaughterSum','pCMSDaughterDiff']\n # lt_variables = ['extraInfoMuPCMS', 'extraInfoEPCMS', 'extraInfoMuCosTheta', 'extraInfoECosTheta']\n #dt_variables = ['DeltaT', 'DeltaTErr']\n #train_variables = ['cosAngleBetweenMomentumAndVertexVectorInXYPlane',\n # 'cosAngleBetweenMomentumAndVertexVector', 'cosToThrustOfEvent',\n # 'missingMass2OfEvent', 'cosThetaBetweenParticleAndNominalB', 'chiProb']\n # train_variables += cs_variables\n #train_variables += m\n # train_variables += kin_variables\n #train_variables += veto_variables\n #train_variables += dt_variables\n \n return my_var\n\n\n# -\n\ndef get_specific_settings(model: str):\n sp = None\n if model == 'fisher':\n sp = basf2_mva.TMVAOptionsClassification()\n sp.m_method = \"Fisher\"\n sp.m_type = \"Fisher\"\n sp.m_config = (\"H:V:CreateMVAPdfs:VarTransform=N:PDFInterpolMVAPdf=Spline2:NbinsMVAPdf=50:NsmoothMVAPdf=10\")\n sp.transform2probability = False;\n elif model == 'svm':\n sp = basf2_mva.TMVAOptionsClassification()\n sp.m_method = \"SVM\"\n sp.m_type = \"SVM\"\n sp.m_config = (\"H:V:VarTransform=N\")\n sp.transform2probability = False;\n elif model == 'fbdt':\n sp = basf2_mva.FastBDTOptions() # here we use the FastBDT method\n sp.m_nTrees = 200 # number of trees in the FastBDT forest(200)\n sp.m_nLevels = 3 # depth of the trees(3)\n sp.m_shrinkage = 0.1 # shrinkage during boosting(0.1)\n sp.m_nCuts = 4 # number of cuts for each tree(4)\n sp.transform2probability = False;\n else:\n raise Exception(f'Model {model} is not supported!')\n return sp\n\ndef train(trainData: list, testData: list, model: str, \n tm_variable: str, output_weights_name: str, tree: str='my_ttree'):\n # Global/General options\n go = basf2_mva.GeneralOptions()\n go.m_datafiles = basf2_mva.vector(*trainData) # training sample\n go.m_treename = tree # ntuple tree name\n go.m_identifier = output_weights_name # name of the file with the trianing info\n train_variables = get_variables()\n go.m_variables = basf2_mva.vector(*train_variables) # input variables\n go.m_target_variable = tm_variable # target for training\n go.m_weight_variable = \"\"\n sp = get_specific_settings(model)\n basf2_mva.teacher(go,sp)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\"Script to split train test\")\n parser.add_argument('--train', nargs='+', help=\"Input MC file names for train\")\n parser.add_argument('--test', nargs='+', help=\"Input MC file names for test\")\n parser.add_argument('-tm', '--tm_variable', type=str, \n default = 'Btag_d1_isSignal', help=\"TM variable, 'Btag_d1_isSignal'\")\n parser.add_argument('-tag','--tag_name', type=str, default='mva', help=\"Tag name for output files\")\n parser.add_argument('-t','--tree', type=str, default='my_ttree', help=\"Tree to use\")\n parser.add_argument('-m', '--model', type=str, default='fbdt', \n choices=['fisher', 'fbdt', 'svm'], help=\"Model to use\")\n args = parser.parse_args()\n\n output_weights_name = f'./{args.model}_{args.tag_name}.xml'\n\n train(args.train, args.test, args.model, tm_variable=args.tm_variable, \n output_weights_name=output_weights_name)\n\n #Btag_d1_isSignal\n \n \n #outputPdf = f'evaluation-{xmlname}.tex'\n #os.system('$BELLE2_RELEASE_DIR/mva/tools/basf2_mva_evaluate.py -w notebooks/tmp/ '+\n # f'-id {go.m_identifier} MyTMVAfbdt.xml -tree {go.m_treename} -train {trainData[0]} -data {testData[0]} -out {outputPdf}')\n #os.system('~/code/4leptons/notebooks/tmp/; pdflatex latex.tex; cd ../../')\n","sub_path":"Machine Learning/trainMVA.py","file_name":"trainMVA.py","file_ext":"py","file_size_in_byte":6205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"28760351","text":"import numpy\nimport unittest\n\nfrom unittest.mock import MagicMock, Mock, patch, call\nfrom eye.video_stream import VideoStream, CameraDisconnectedException, CaptureMode\n\n\n@patch(\"eye.video_stream.sleep\", MagicMock())\n@patch(\"eye.video_stream.cv2\")\nclass TestVideoStream(unittest.TestCase):\n\n @patch(\"eye.video_stream.sleep\", MagicMock())\n @patch(\"eye.video_stream.cv2\")\n def setUp(self, cv2):\n self.frame = numpy.array([[1, 1]])\n self.stream = MagicMock()\n self.stream.read.return_value = True, self.frame\n cv2.VideoCapture.return_value = self.stream\n self.cv2 = cv2\n self.event = MagicMock()\n self.video_stream = VideoStream(None, self.event)\n\n def test_current_frame_is_returned_when_reading(self, cv2):\n cv2.undistort.return_value = self.frame\n self.video_stream._process()\n\n self.assertListEqual(self.video_stream.read().tolist(), self.frame.tolist())\n\n def test_table_calibration_scale_values_are_halved_when_reducing_resolution_by_half(self, cv2):\n self.video_stream.capture_mode = CaptureMode.HIGH_RES\n\n scale = self.video_stream.change_capture_mode(CaptureMode.LOW_RES)\n\n self.assertEqual(scale, 0.8)\n\n def test_table_calibration_scale_values_are_doubled_when_doubling_the_resolution(self, cv2):\n self.video_stream.capture_mode = CaptureMode.LOW_RES\n\n scale = self.video_stream.change_capture_mode(CaptureMode.HIGH_RES)\n\n self.assertEqual(scale, 1.25)\n\n def test_table_calibration_is_used_to_undistort_image(self, cv2):\n self.video_stream.table_calibration = {\n \"optimal\": numpy.array([\n [1., 0.0, 1.],\n [0.0, 1., 1.],\n [0.0, 0.0, 1.0],\n ]),\n \"roi\": numpy.array([0, 0, 2, 2]),\n \"camera_matrix\": numpy.array([\n [1., 0.0, 1.],\n [0.0, 1., 1.],\n [0.0, 0.0, 1.0],\n ]),\n \"distortion_coeff\": numpy.array([\n [0., 0., 0., 0., 0.],\n ])\n }\n undistorted_frame = numpy.array([[2, 2]])\n cv2.undistort.return_value = undistorted_frame\n\n self.video_stream._process()\n\n self.assertListEqual(self.video_stream.frame.tolist(), undistorted_frame.tolist())\n\n def test_event_is_cleared_when_capturing_frame_and_released_after(self, cv2):\n manager = Mock()\n manager.attach_mock(self.event, 'event')\n manager.attach_mock(self.stream, 'stream')\n\n self.video_stream._process()\n\n expected_calls = [call.event.clear(), call.stream.read(), call.event.set()]\n self.assertListEqual(manager.mock_calls, expected_calls)\n","sub_path":"anesthetic/test_eye/test_video_stream.py","file_name":"test_video_stream.py","file_ext":"py","file_size_in_byte":2696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"482524614","text":"'''\nThe purpose of this Helper file is to have all the utility functions necessary \nfor the recommendation engine so that the main ipynb file can be short and clutter free.\nThis also provides a chance to decouple the codes so that if anything needs to be modified,\nit can be done without having to rerun the main ipynb files.\n'''\n#importing all required libraries\nimport pandas as pd\nimport re\nimport nltk\nimport spacy\nimport en_core_web_sm\nnlp = en_core_web_sm.load()\nfrom spacy.matcher import PhraseMatcher\nimport os\nimport matplotlib.pyplot as plt\n\n\n'''\nThe import_dataset function imports the UpdatedResumeDataSet4.csv file\ncontaining the Resumes and the broad category it belings to.\nWe are randomly generating First Names and Last Names add adding it to the\ndataset for the purpose of our analyses.\n'''\ndef import_dataset():\n df_in = pd.read_csv('UpdatedResumeDataSet4.csv' ,encoding='utf-8')\n #generate random names\n from random import shuffle, seed\n from faker.providers.person.en import Provider\n\n first_names = list(set(Provider.first_names))\n last_names = list(set(Provider.last_names)) ##generates only 473 last names \n last_names = last_names*3 #so its is multipled 3 times to make more. There maybe some repetitions but its ok\n fn = first_names[0:962] #we need only 962 first names\n ln = last_names[0:962] #we need only 962 last names\n #Add the name columns to the df_in dataframe\n df_in['First_Name']=fn\n df_in['Last_Name']=ln\n return df_in\n'''\nclean_resume cleans the Resume column of the dataset\nThis is a text cleaning function that is capable of\nremoving commonly seen special characters\nextra whitespaces,typos,\n'''\ndef clean_resume(text):\n import re\n text = re.sub('http\\S+\\s*', ' ', text) # remove URLs\n text = re.sub('RT|cc', ' ', text) # remove RT and cc\n text = re.sub('#\\S+', '', text) # remove hashtags\n text = re.sub('@\\S+', ' ', text) # remove mentions\n text = re.sub('[%s]' % re.escape(\"\"\"!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~\"\"\"), ' ', text) # remove punctuations\n text = re.sub(r'[^\\x00-\\x7f]',r' ', text) \n text = re.sub('\\s+', ' ', text) # remove extra whitespace\n text = re.sub('machine learning', 'ML', text)\n text = re.sub('Machine Learning', 'ML', text)\n text = re.sub('Deep Learning', 'DL', text)\n text = re.sub('data', 'Data', text)\n text = re.sub('Hr', 'HR', text)\n text = re.sub('4HANA', 'HANA', text)\n text = re.sub('JAVA','Java',text)\n text = re.sub('Reduce', 'MapReduce', text)\n text = re.sub('TESTING', 'Selenium', text)\n text = re.sub('learnerEducation', 'Junior', text)\n text = re.sub('Exprience', 'experience', text)\n return text\n\n#We were unable to subset or iterate the df_in using the values in the 'Category' column\n#The following code will help fix that issue\ndef fix_subset(df_in):\n skills=[]\n name=[]\n category=[]\n for i in range(0,962):\n category.append(df_in.Category[i])\n skills.append(df_in.cleaned_resume[i])\n fname = df_in.First_Name[i]\n lname = df_in.Last_Name[i]\n name.append(fname+' '+lname)\n df_data = pd.DataFrame.from_records({'Name':name,'Category':category,'Resume':skills})\n return df_data\n\n'''\nCompared to using regular expressions on raw text, spaCy’s rule-based matcher engines \nand components not only let you find the words and phrases you’re looking for \n– they also give you access to the tokens within the document and their relationships.\n This means you can easily access and analyze the surrounding tokens, merge spans into single tokens\n or add entries to the named entities \n source: https://spacy.io/usage/rule-based-matching#matcher\n'''\n#matching phrases from the keywords using spacy\ndef match_keywords(skills,keywords):\n phrase_matcher = PhraseMatcher(nlp.vocab,attr=\"LOWER\")\n kw = [nlp.make_doc(skills) for text in keywords ]\n phrase_matcher.add(\"keywords\",None,*kw)\n doc = nlp(skills)\n matches = phrase_matcher(doc)\n found = []\n for match_id,start,end in matches:\n found += doc[start:end]\n return found\n'''\nSkill_profile function works in tandem with the match_keywords function\nOnce the PhraseMatcher finds occurances of the input keywords in the resumes,\nit returns a list containing the word occurances.\n\nWe use this to build a skill profile, by counting the number of times each keyword \nis found in a particular resume. The 'name' is the name of the candidate\nextracted from the df_data sataset.\n''' \n#build an skill set profile from the matched phrases text\ndef skill_profile(found,name,keywords):\n #print('building a profile for '+name) #for debugging purposes\n keyword_dict=dict.fromkeys(keywords,0)\n keyword_dict['Name']=name\n #print(keyword_dict)\n for i in found:\n j=str(i)\n if j in keywords:\n keyword_dict[j]+=1\n return keyword_dict\n\n'''\nThe helper_function() calls the match_keywords and the skill_profile\nfunctions in order to get each candidate's skill profile based on the \nrequirement given by the client\n'''\ndef helper_function(df_data,keywords):\n skill_count_list = []\n for i in range(0,len(df_data)):\n skills = df_data.Resume[i]\n name = df_data.Name[i]\n found = match_keywords(skills,keywords)\n skill_count=skill_profile(found,name,keywords)\n skill_count_list.append(skill_count)\n return skill_count_list\n'''plot_skillset_profile plots a horizontal stacked barchart \nusing the skill set count and names of the candidates to \nhelp us visually understand which candidate is releavnt to our\nrequirement\n'''\ndef plot_skillset_profile(df_plot):\n import matplotlib.pyplot as plt\n plt.rcParams.update({'font.size': 10})\n ax = df_plot[:200].plot.barh(title=\"Resume keywords by category\", legend=True, figsize=(20,150), stacked=True)\n labels = []\n for j in df_plot[:200].columns:\n for i in df_plot[:200].index:\n label = str(j)+\": \" + str(df_plot[:200].loc[i][j])\n labels.append(label)\n patches = ax.patches\n for label, rect in zip(labels, patches):\n width = rect.get_width()\n if width > 0:\n x = rect.get_x()\n y = rect.get_y()\n height = rect.get_height()\n ax.text(x + width/2., y + height/2., label, ha='center',va='center',color =\"white\",weight='bold')\n return plt.show()\n\n'''\nThe experience_chunk and the experience_idx functions\nattempt to get a gist of the experience profile of any\ncandidate the client is interested in\n'''\ndef experience_chunks(df_data,name):\n candidate_skills=[]\n for i in range(0,len(df_data)):\n if df_data.Name[i] == name:\n candidate_skills = str(df_data.Resume[i])\n sents = nltk.sent_tokenize(candidate_skills)\n chunk_style = \"chunk:{}\"\n parser = nltk.RegexpParser(chunk_style)\n for i in sents:\n words = nltk.word_tokenize(i)\n pos = nltk.pos_tag(words)\n chunks = parser.parse(pos)\n for i in chunks.subtrees():\n if i.label()==\"chunk\":\n print(i.leaves())\n\ndef experience_idx(df_data,name):\n candidate_skills=[]\n exp_profile=[]\n words=[]\n for i in range(0,len(df_data)):\n if df_data.Name[i] == name:\n candidate_skills = str(df_data.Resume[i])\n words = nltk.word_tokenize(candidate_skills)\n for idx,word in enumerate(words):\n if word == 'experience' and words[idx+1]=='Less':\n profile = [words[idx-2],words[idx-1],word,words[idx+1],words[idx+2],words[idx+3],words[idx+4]]\n exp_profile.append(profile)\n elif word == 'experience':\n profile = [words[idx-2],words[idx-1],word,words[idx+1],words[idx+2]]\n exp_profile.append(profile)\n print(exp_profile)\n\n'''\nThe recommendations functions gives the top 10\ncandidates of each skill set the client requires\n'''\ndef recommendations(df_skills,keywords):\n candidate_list =[]\n for i in keywords:\n temp_df = df_skills.nlargest(10,i)\n tmp_names = temp_df['Name']\n for name in tmp_names:\n skills_dict = {'Skill':i,'Candidates':name}\n candidate_list.append(skills_dict)\n #df_reco = pd.DataFrame(candidate_list,index=range(0,len(candidate_list)))\n return candidate_list \n\n'''\nthe find_common_words functions helps find the buzzwords present in the resumes\nThis can be very useful for training models,for searching skill sets,understanding\nthe skillsets in each industry in general\n'''\nfrom nltk.corpus import stopwords\nfrom nltk import WordNetLemmatizer\nimport string\ndef find_common_words(df_resume):\n oneSetOfStopWords = set(stopwords.words('english')+['``',\"''\"])\n totalWords =[]\n Sentences = df_resume['Resume'].values\n cleanedSentences = \"\"\n lem=WordNetLemmatizer()\n noise=['Details', 'Exprience', 'months', 'company', 'description', '1', 'year','36',\n 'Even','offered','frauds','hiding','compared','per','students','web','well',\n 'Chat','effective','leadership','Nov','member','along','January','Less', 'Skill','Maharashtra',\n '6','I','project','like', 'India','Pradesh','January','Jan','February','Feb','March','Mar','April','Apr',\n 'May','June','Jun','Jul','July','Aug','August','Sep','September','Oct','October','Nov','November',\n 'Dec','December','using','monthsCompany','B','C', 'Mumbai', 'Pune', 'Arts', 'A', 'application','24',\n 'various', 'Responsibilities','Nagpur','development','Management','Technologies','The',\n 'Company','University','British','Designed','Board','new','time','E','May','Ltd','Team',\n 'M','Development','etc','Used','2','Council','team','School','Working','work','Developed',\n 'Made','given','2016','Sri','required','Learning','Skills','related','involved','3','My',\n '4','Trust','2015','across','This','Lanka','Windows','Adichunchanagiri','Bahadarpur','Gorbanjara',\n 'Indira','Priyadarshini','Gandhi','shreekiaspack', '3staragroproducts','luckystationery','ALAMURI',\n 'HINDI','Madhya','36','providing','2014','university','board','State','Jalgaon','From','Nashik','Kisan',\n 'In','Sr','College','Parola','Dist','www','requirement','com','Higher','State','e','In','used','co','SYSTEM',\n 'gives','CURRICULUM','S','OF','LTD','turn','Bengaluru','Karnataka','LifeKonnect','Co','insurance','civil',\n 'Aurus','Participated','gathering','meetings','Reviewed','met','February','2006','different','indent',\n '0','S','understanding','writing','Nanded','R','K','KVA','10','28','30','agreed','providing','Timely',\n '2nd','level','Dubai','7','8','e','Helping','300','Su','QATAR','17','5','9','11','12','13','14','15',\n '26','INDIA','5','Thai','27','10','allow','2012','2008','Sr','Pvt','2900s','12D','Asha','2000','2003',\n 'ount','Delhi','process','OF','16','30','v10','v11','v12','Pvt','within','9','5','map','Map','Size',\n 'used','Unit','9','5','help','also','Inc','yes','June','good','Tech','Like','House','CBSE','Nov','Based',\n '05','07','Asst','To','2010','Pia','Hiralal','Your','2009','2017','Hard','2011','basically','even','P','done',\n 'Smt','2004','Apeksha','Naharkar','Thanks','Regards','Talreja','Hindi','Bajaj','Chandrapur','32','alleviate',\n 'continued','Savitribai','ANGEL','BOARD','INSTITUTE','Good','Kranti','ountabilities','Thakur','And','P','mumbai','com',\n 'Quick','SURYA','kranti','maharastra','PRAKASH','MUMBAI','RAJDEVI','whether', 'Of', 'By', 'ept', 'admin', 'At', 'provide', \n 'As', 'via', 'For', 'With', 'For', 'During', 'On','Of','24x7','201','20','31','7Education','1year','one','800','3000','2D',\n '3D', '3DEducation', '2007', '120','96', '48', '2013', 'Two', '625', '5000', '2000A', '450', '110V', '55', '33', '22','18', \n '101', '11gEducation', '01','2019', '3years','017', '2018', '20656', '2005']\n for i in range(0,len(df_resume)):\n cleanedText = clean_resume(Sentences[i])\n cleanedSentences += cleanedText\n cleanwords = nltk.word_tokenize(cleanedText)\n requiredWords=[lem.lemmatize(x) for x in cleanwords]\n for word in requiredWords:\n if word not in oneSetOfStopWords and word not in string.punctuation and word not in noise:\n totalWords.append(word)\n \n wordfreqdist = nltk.FreqDist(totalWords)\n mostcommon = wordfreqdist.most_common(200)\n return mostcommon\n\n'''\nThe plot_common_skills functions helps us visualize the \nbuzzwords in the resume using a wordcount - word barchart\n'''\ndef plot_common_skills(common_words,category):\n import plotly.express as px \n skill=[]\n count=[]\n for i in common_words:\n skill.append(i[0])\n count.append(i[1])\n fig = px.histogram(x=skill,y=count, template='simple_white',title= category+' buzzwords')\n fig.update_xaxes(categoryorder='total descending').update_xaxes(title='Buzzwords',tickangle = 45)\n fig.update_yaxes(title='Word count')\n return fig.show()\n'''\nThe experience_rake method extracts import phrases from the candidate's\nresume using the RAKE library.\nThese phrases are then evaluated to see if any words of interest are present.\nIn our case, we would like to know the experience,skills,trainings etc\n'''\nimport RAKE\nimport operator\ndef experience_rake(df_data,name,keywords):\n candidate_skills=[]\n phrases=[]\n for i in range(0,len(df_data)):\n if df_data.Name[i] == name:\n candidate_skills = str(df_data.Resume[i])\n r = RAKE.Rake('SmartStoplist.txt')\n keyphrases = r.run(candidate_skills)\n for phrase,score in keyphrases:\n if score > 3:\n phrases.append(phrase)\n for i in phrases:\n words = i.split(\" \")\n for j in keywords:\n if j.lower() in words:\n print(i)\n\n\n\n","sub_path":"RecommendationHelper_Final.py","file_name":"RecommendationHelper_Final.py","file_ext":"py","file_size_in_byte":13875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"38410477","text":"import cv2 as cv\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n'''\n形态学操作是根据图像形状进行的简单操作。一般情况下对二值化图像进行的操作。\n需要输入两个参数,一个是原始图像,第二个被称为结构化元素或核,它是用来决定操作的性质的。\n两个基本的形态学操作是腐蚀和膨胀。\n\n 腐蚀:用最小值替换中心像素。除白噪声很有用,也可以用来断开两个连在一块的物体等\n 膨胀:用最大值替换中心像素。增加图像中的白色区域(前景),也可以用来连接两个分开的物体。\n\n\n结构化元素\n 1.使用 Numpy 构建结构化元素,它是正方形的。\n 2. cv2.getStructuringElement(shape, ksize, anchor=None)。你只需要告诉他你需要的核的形状和大小。构建一个椭圆形/圆形的核\n - shape:\n cv2.MORPH_RECT 矩形\n cv2.MORPH_ELLIPSE 椭圆\n cv2.MORPH_CROSS 十字\n'''\n\n\n# 腐蚀\ndef erode_demo(image):\n print(image.shape)\n gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)\n ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)\n cv.imshow(\"binary\", binary)\n\n # 得到结构元素\n kernel = cv.getStructuringElement(cv.MORPH_RECT, (5, 5))\n dst = cv.erode(binary, kernel)\n cv.imshow(\"erode_image\", dst)\n\n\n# 膨胀\ndef dilate_demo(image):\n print(image.shape)\n gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)\n ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)\n cv.imshow(\"binary\", binary)\n\n # 得到结构元素\n kernel = cv.getStructuringElement(cv.MORPH_RECT, (5, 5))\n dst = cv.dilate(binary, kernel)\n cv.imshow(\"dilate_image\", dst)\n\n\ndef main():\n # 读取图片\n img = cv.imread(\"../code_images/bin2.jpg\")\n\n # 创建窗口,窗口尺寸自动调整\n # cv.namedWindow(\"lena\", cv.WINDOW_AUTOSIZE)\n\n # 显示图片\n cv.imshow(\"lena\", img)\n\n erode_demo(img)\n dilate_demo(img)\n\n # 等待键盘输入\n cv.waitKey(0)\n cv.destroyAllWindows()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"code/case_21_erode_dilate.py","file_name":"case_21_erode_dilate.py","file_ext":"py","file_size_in_byte":2149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"481960070","text":"#!/usr/bin/env python\nimport rospy\nimport time\nimport argparse\nimport csv\nfrom p3dx_navigation.msg import Wifidata\nfrom geometry_msgs.msg import PoseStamped, Point, Quaternion\n\nsub_ssid = []\nsub_rssi = []\nmax_rssi = -100\npermitRead = False\nPositionX = []\nPositionY = []\nSSID1 = []\nSSID2 = []\nSSID3 = []\nSSID4 = []\nSSID5 = []\nRSSI1 = []\nRSSI2 = []\nRSSI3 = []\nRSSI4 = []\nRSSI5 = []\nrow = []\npresubssid = ''\nprePositionX = 0\nprePositionY = 0\nnum = 0\n\n\n\n\"\"\"class RosNode(object):\n def wait_for_subscriber(self, pub, timeout):\n timeout_t = time.time() + timeout\n while pub.get_num_connections() == 0 and timeout_t > time.time():\n self.sleep(0.01)\n\n def sleep(self, duration):\n rospy.rostime.wallsleep(duration)\n\"\"\"\n\nclass WifiPosReaderNode:\n def __init__(self):\n # self.__pub = rospy.Publisher(\"/goal\", PoseStamped, queue_size=100)\n self.__pub = rospy.Publisher(\"/move_base_simple/goal\", PoseStamped, queue_size=100)\n rospy.init_node(\"wifiposreader_node\")\n rospy.Subscriber(\"wifi_state\", Wifidata, self.wifi_callback)\n\n def readCSV(self, csv_file):\n # super(WifiPosReaderNode, self).wait_for_subscriber(self.__pub, timeout=1.0) #timeout=5.0\n global row, PositionX, PositionY, SSID1, SSID2, SSID3, SSID4, SSID5, RSSI1, RSSI2, RSSI3, RSSI4, RSSI5\n\n with open(csv_file, 'r') as f:\n reader = csv.reader(f)\n header = next(reader)\n for row in reader:\n if rospy.is_shutdown():\n break;\n # rospy.loginfo(row)\n PositionX.append(float(row[0]))\n PositionY.append(float(row[1]))\n SSID1.append(row[2])\n RSSI1.append(int(row[3]))\n SSID2.append(row[4])\n RSSI2.append(int(row[5]))\n SSID3.append(row[6])\n RSSI3.append(int(row[7]))\n SSID4.append(row[8])\n RSSI4.append(int(row[9]))\n SSID5.append(row[10])\n RSSI5.append(int(row[11]))\n print(\"CSV file was read\")\n\n def wifi_callback(self, wifi_state):\n global sub_ssid, sub_rssi, max_rssi, presubssid, prePositionX, prePositionY, num\n maxPosX = 0\n maxPosY = 0\n permitPub = False\n rate = rospy.Rate(10) # 10hz\n wifi = wifi_state\n sub_ssid = wifi.ssid[:]\n sub_rssi = wifi.rssi[:]\n max_rssi = -100\n print(\"received wifistate\")\n print(sub_ssid)\n print(sub_rssi)\n\n i = 0\n for i in range(len(SSID1)):\n if SSID1[i] == sub_ssid[0] and RSSI1[i] > max_rssi:\n maxPosX = PositionX[i]\n maxPosY = PositionY[i]\n max_rssi = RSSI1[i]\n rospy.loginfo(maxPosX)\n rospy.loginfo(maxPosY)\n rospy.loginfo(max_rssi)\n print(\"updated max\")\n if sub_rssi[0] > -45 and sub_rssi[0] - sub_rssi[1] > 3:\n permitPub = True\n elif sub_rssi[0] > -50 and sub_rssi[0] - sub_rssi[1] > 2:\n permitPub = True\n elif sub_rssi[0] > -55 and sub_rssi[0] - sub_rssi[1] > 1:\n permitPub = True\n else:\n permitPub = False\n\n if permitPub == False:\n print(\"not found\")\n for i in range(len(SSID2)):\n if SSID2[i] == sub_ssid[0] and RSSI2[i] > max_rssi:\n maxPosX = PositionX[i]\n maxPosY = PositionY[i]\n max_rssi = RSSI2[i]\n rospy.loginfo(maxPosX)\n rospy.loginfo(maxPosY)\n rospy.loginfo(max_rssi)\n print(\"updated max\")\n permitPub = True\n\n \"\"\"\n if permitPub == False:\n print(\"Not matching\")\n for i in range(len(SSID1)):\n if SSID1[i] == sub_ssid[1] and RSSI1[i] > max_rssi:\n maxPosX = PositionX[i]\n maxPosY = PositionY[i]\n max_rssi = RSSI1[i]\n rospy.loginfo(maxPosX)\n rospy.loginfo(maxPosY)\n rospy.loginfo(max_rssi)\n print(\"updated max\")\n permitPub = True\n \"\"\"\n\n \"\"\"\n if permitPub == False:\n print(\"Not matching\")\n \"\"\"\n\n \"\"\"\n if permitPub:\n if sub_rssi[] #??????\n \"\"\"\n\n distance = ((maxPosX - prePositionX) * (maxPosX - prePositionX)) + ((maxPosY - prePositionY) * (maxPosY - prePositionY)) #distance of 2points(published point and publishing point)\n print(distance)\n\n if distance < 16: #distance to the second power\n permitPub = False\n print(\"Too near the point set\")\n\n\n \"\"\"\n if presubssid == sub_ssid[0] or distance < 9: #distance to the second power\n permitPub = False\n print(\"Too near the point set\")\n \"\"\"\n\n\n if permitPub:\n goal = self.__parse_row(row, maxPosX, maxPosY)\n self.__pub.publish(goal)\n print(\"published\")\n prePositionX = maxPosX\n prePositionY = maxPosY\n rate.sleep()\n num = num + 1\n rospy.loginfo(num)\n elif permitPub == False:\n print(\"Not publishing\")\n\n presubssid = sub_ssid[0]\n\n\n def __parse_row(self, row, x, y):\n frame = row[-1]\n\n goal = PoseStamped()\n goal.pose.position.x = x\n goal.pose.position.y = y\n goal.pose.position.z = 0\n goal.pose.orientation.x = 0\n goal.pose.orientation.y = 0\n goal.pose.orientation.z = 0.9993610636\n goal.pose.orientation.w = 0.0357416366999439\n goal.header.frame_id = frame\n goal.header.stamp = rospy.Time.now()\n\n return goal\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"wifipos_reader node publish goals from csv file.\")\n parser.add_argument(\"csv\", metavar=\"file\", type=str, help=\"name of csv file to read\")\n args = parser.parse_args()\n node = WifiPosReaderNode()\n\n try:\n node.readCSV(args.csv)\n except rospy.ROSInterruptException:\n pass\n\n rospy.spin()\n","sub_path":"p3dx_navigation/scripts/wifipos_reader2.py","file_name":"wifipos_reader2.py","file_ext":"py","file_size_in_byte":6308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"509683109","text":"import cv2\nimport numpy as np\n\n\ndef strokeEdges(src,dst,blurKsize=7,edgeKsize=5):\n\tif blurKsize>=3:\n\t\tblurredSrc=cv2.medianBlur(src,blurKsize)\n\t\tgraySrc=cv2.cvtColor(blurredSrc,cv2.COLOR_BGR2GRAY)\n\telse:\n\t\tgraySrc=cv2.cvtColor(src,cv2.COLOR_BGR2GRAY)\n\tcv2.Laplacian(graySrc,cv2.CV_8U,graySrc,ksize=edgeKsize)\n\tnormalizedInverseAlpha=(1.0/255)*(255-graySrc)\n\tchannels=cv2.split(src)\n\tfor channel in channels:\n\t\tchannel[:]=channel*normalizedInverseAlpha\n\tcv2.merge(channels,dst)\n\n\nclass VConvolutionFilter(object):\n\t\"\"\"A filter that applies a convolution to V (or all of BGR)\"\"\"\n\n\tdef __init__(self,kernel):\n\t\tself._kernel=kernel\n\n\tdef apply(self,src,dst):\n\t\t\"\"\"Apply the filter with a BGR or gray source/destination\"\"\"\n\t\tcv2.filter2D(src,-1,self._kernel,dst)\n\n#锐化过滤器:核权重和为1\nclass SharpenFilter(VConvolutionFilter):\n\t\"\"\"A sharpen filter with a 1-pixel radius.\"\"\"\n\n\tdef __init__(self):\n\t\tkernel=np.array([[-1,-1,-1],\n\t\t\t\t\t\t [-1,9,-1],\n\t\t\t\t\t\t [-1,-1,-1]])\n\t\tVConvolutionFilter.__init__(self,kernel)\n\n#边缘检测过滤器:核权重和为0\nclass FindEdgesFilter(VConvolutionFilter):\n\t\"\"\"An edge-finding filter with a 1-pixel radius\"\"\"\n\n\tdef __init__(self):\n\t\tkernel = np.array([[-1, -1, -1],\n\t\t\t\t\t\t [-1, 8, -1],\n\t\t\t\t\t\t [-1, -1, -1]])\n\t\tVConvolutionFilter.__init__(self, kernel)\n\n\n#模糊过滤器:核权重和为1,且周围权重全为正数\nclass BlurFilter(VConvolutionFilter):\n\t\"\"\"A blur filter with a 2-pixel radius\"\"\"\n\n\tdef __init__(self):\n\t\tkernel = np.array([[0.04,0.04,0.04,0.04,0.04],\n\t\t\t\t\t\t [0.04,0.04,0.04,0.04,0.04],\n\t\t\t\t\t\t [0.04,0.04,0.04,0.04,0.04],\n\t\t\t\t\t\t [0.04,0.04,0.04,0.04,0.04],\n\t\t\t\t\t\t [0.04,0.04,0.04,0.04,0.04]])\n\t\tVConvolutionFilter.__init__(self, kernel)\n\n\n#浮雕效果过滤器\nclass EmbossFilter(VConvolutionFilter):\n\t\"\"\"An emboss filter with a 1-pixel radius.\"\"\"\n\n\tdef __init__(self):\n\t\tkernel = np.array([[-2, -1, 0],\n\t\t\t\t\t\t [-1, 1, 1],\n\t\t\t\t\t\t [0, 1, 2]])\n\t\tVConvolutionFilter.__init__(self, kernel)","sub_path":"test/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":1964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"652937292","text":"import os\r\nimport openpyxl\r\n#=====================================================================\r\n# READ EXCELS FILE USING EXTERNAL PYTHON LIBRARY\r\n#=====================================================================\r\nprint(\"[database] loading\")\r\nfrom openpyxl import load_workbook\r\nwb = load_workbook(filename='13.xlsx', read_only=True)\r\nws = wb['Sheet1']\r\n\r\n#=====================================================================\r\n# CONVERT EXCEL TO ARRAYS\r\n#=====================================================================\r\nprint(\"[database] converting\")\r\ndef iter_rows(ws):\r\n for row in ws.iter_rows():\r\n yield [cell.value for cell in row]\r\ntabel = list(iter_rows(ws))\r\n\r\n#=====================================================================\r\n# REFORMATING ARRAYS - INFORMATION ROWS FINDER\r\n#=====================================================================\r\nc_utc_JST=0\r\nc_steps=0\r\nc_pulse=0\r\nc_calory=0\r\nc_transType=0\r\ndef find_row(tabel):\r\n count=0\r\n print(\"[database] finding necesseries data\")\r\n while(1):\r\n if (count==len(tabel[0])):\r\n global c_transType\r\n global c_steps\r\n global c_pulse\r\n global c_calory\r\n global c_utc_JST\r\n break\r\n if (tabel[0][count]==\"steps\"):\r\n c_steps=count\r\n if (tabel[0][count]==\"pulse\"):\r\n c_pulse=count\r\n if (tabel[0][count]==\"calory\"):\r\n c_calory=count\r\n if (tabel[0][count]==\"utc_JST\"):\r\n c_utc_JST=count\r\n if (tabel[0][count]==\"transType\"):\r\n c_transType=count\r\n count+=1\r\nfind_row(tabel)\r\n\r\n#=====================================================================\r\n# KIND OF INPUT DATA START PARAMETERS\r\n#=====================================================================\r\nname=\"Hans (Hanjara Cahya Adhyatma)\"\r\ngender=\"male\"\r\nage=22\r\nweigh=60\r\nheigh=170\r\npulse=0\r\navcnt=0\r\ni=0\r\nelevator=0\r\nwalking=0\r\nstay=0\r\nstair=0\r\nstp=0\r\nclr=0.0\r\nn=0\r\nperson=[]\r\ndatabase=[]\r\nall_pulse=[]\r\nall_stair=[]\r\nall_elevator=[]\r\nall_walking=[]\r\nall_stp=[]\r\nall_stay=[]\r\nall_clr=[]\r\n#=====================================================================\r\n# INFORMATION FILTERING\r\n#=====================================================================\r\nprint(\"[database] collecting necesseries data\")\r\nfor row in ws.rows:\r\n if(tabel[i][c_transType]==\"7(エレベータ降り中)\") or \\\r\n (tabel[i][c_transType]==\"6(エレベータ昇り中)\"):\r\n all_elevator.extend([[tabel[i][c_utc_JST], tabel[i][c_transType]]])\r\n elevator+=1\r\n if(tabel[i][c_transType]==\"2(歩行中)\"):\r\n all_walking.extend([[tabel[i][c_utc_JST], tabel[i][c_transType]]])\r\n walking+=1\r\n if(tabel[i][c_transType]==\"1(静止中)\"):\r\n all_stay.extend([[tabel[i][c_utc_JST], tabel[i][c_transType]]])\r\n stay+=1\r\n if(tabel[i][c_transType]==\"5(階段降り中)\"):\r\n all_stair.extend([[tabel[i][c_utc_JST], tabel[i][c_transType]]])\r\n stair+=1\r\n if(tabel[i][c_steps] != 0) and \\\r\n (tabel[i][c_steps] != None) and \\\r\n (tabel[i][c_steps] != \"steps\"):\r\n all_stp.extend([[tabel[i][c_utc_JST], tabel[i][c_steps]]])\r\n stp+=int(tabel[i][c_steps])\r\n if(tabel[i][c_calory] != 0) and \\\r\n (tabel[i][c_calory] != None) and \\\r\n (tabel[i][c_calory] != \"calory\") and \\\r\n (tabel[i][c_calory] != \"\"):\r\n all_clr.extend([[tabel[i][c_utc_JST], tabel[i][c_calory]]])\r\n clr+=float(tabel[i][c_calory])\r\n if(tabel[i][c_pulse] != 0) and \\\r\n (tabel[i][c_pulse] != None) and \\\r\n (tabel[i][c_pulse] != \"pulse\"):\r\n all_pulse.extend([[tabel[i][c_utc_JST], tabel[i][c_pulse]]])\r\n pulse+=int(tabel[i][c_pulse])\r\n avcnt+=1\r\n i+=1 \r\n \r\n#=====================================================================\r\n# INFORMATION PRINTING\r\n#=====================================================================\r\n\r\nprint()\r\nprint(\"Name \\t\",name)\r\nprint(\"Gender \\t\",gender)\r\nprint(age, \"\\t years old\")\r\nprint(weigh, \"\\t kg\")\r\nprint(heigh, \"\\t cm\")\r\nprint(round(pulse/avcnt, 2), \"\\t bpm\")\r\nprint(stair,\"\\t times detected using stairs\")\r\nprint(elevator,\"\\t times detected using elevator\")\r\nprint(walking, \"\\t times detected walking\")\r\nprint(stp,\"\\t total steps\")\r\nprint(stay, \"\\t times detected stay\")\r\nprint(round(clr, 2),\"\\t kcal burned total?\")\r\n\"\"\"\r\nglobal name\r\nglobal gender\r\nglobal age\r\nglobal weigh\r\nglobal heigh\r\nglobal pulse\r\nglobal avcnt\r\nglobal stair\r\nglobal elevator\r\nglobal walking\r\nglobal stp\r\nglobal stay\r\nglobal clr\r\n\"\"\"\r\n#=====================================================================\r\n# new NECESSERIES database\r\n#=====================================================================\r\nprint(\"[database] save collected data\")\r\nperson=[name,gender,age,weigh,heigh,round(pulse/avcnt, 2),stair,elevator,walking,stp,stay,round(clr, 2)]\r\ndatabase=[person,gender,age,weigh,heigh,all_pulse,all_stair,all_elevator,all_walking,all_stp,all_stay,all_clr]\r\n\"\"\"\r\nit=0\r\nwhile(1):\r\n if (it==len(database[9])):\r\n break\r\n print(database[9][it])\r\n it+=1\r\n\"\"\"\r\nprint(\"[database] finish\")","sub_path":"HealthCare/expertknowladge/read_xl.py","file_name":"read_xl.py","file_ext":"py","file_size_in_byte":4798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"310760448","text":"from django.core.exceptions import ImproperlyConfigured\n\nclass DebugCmd(object):\n def __init__(self, name, verbose_name, fn, params=None):\n self.name = name\n self.verbose_name = verbose_name\n if hasattr(fn, '__call__'): \n self.fn = fn \n self.doc = fn.__doc__\n else:\n raise ImproperlyConfigured('Debug cmd must have a callable intead of %s' % str(fn))\n self.params = params\n\n def __repr__(self):\n return '#'.join(['DebugCmd', self.name, str(self.params)])\n","sub_path":"debug_toolbar/utils/debug_cmd.py","file_name":"debug_cmd.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"264594162","text":"import sys\nfrom threading import Thread\nfrom PyQt5 import QtSvg\nfrom PyQt5.QtCore import pyqtSlot, QProcess, Qt, QRect\nfrom PyQt5.QtGui import QKeySequence, QTextCursor, QPainter, QColor, QTextFormat\nfrom PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QTextEdit, QFileDialog, QAction, QPlainTextEdit, QGridLayout, QDialog, QLabel, QMainWindow, QMdiArea, QMdiSubWindow, QShortcut, QTabWidget\nimport xml.etree.ElementTree as ET\nfrom io import StringIO, BytesIO\nimport syntax\n\nfrom ViewerWindow import ViewerWindow\nfrom ScriptWindow import ScriptWindow\nfrom OutputWindow import OutputWindow\n#from dataframe_viewer import DataFrameViewer\n#from pandasgui import show as DataFrameViewer\nfrom guipandas.widgets.dataframe_viewer import DataFrameViewer\n\nimport pandas as pd\n\ndef register_all_namespaces(filename):\n namespaces = dict([node for _, node in ET.iterparse(filename, events=['start-ns'])])\n for ns in namespaces:\n ET.register_namespace(ns, namespaces[ns])\n\nclass MainWindow(QMainWindow):\n count = 0\n linecount = 0\n maxLine = 100\n\n def __init__(self, parent = None):\n super(MainWindow, self).__init__(parent)\n self.item0 = BytesIO()\n\n self.mdi = QMdiArea()\n self.setCentralWidget(self.mdi)\n bar = self.menuBar()\n\n file = bar.addMenu(\"File\")\n file.addAction(\"New\")\n file.addAction(\"cascade\")\n file.addAction(\"Tiled\")\n file.triggered[QAction].connect(self.windowaction)\n self.setWindowTitle(\"Camphor\")\n\n MainWindow.count += 1\n self.output_window = OutputWindow()\n self.mdi.addSubWindow(self.output_window)\n\n MainWindow.count += 1\n self.script_window = ScriptWindow()\n self.mdi.addSubWindow(self.script_window)\n\n MainWindow.count += 1\n self.viewer_window = ViewerWindow()\n self.mdi.addSubWindow(self.viewer_window)\n\n #MainWindow.count += 1\n #self.spread_sheet = SpreadSheetWidget()\n #self.mdi.addSubWindow(self.spread_sheet)\n\n headers = [\"000\", \"001\", \"002\"]\n tableData0 = [\n ['abc',100,200],\n ['fff',130,260],\n ['jjj',190,300],\n ['ppp',700,500],\n ['yyy',800,900]\n ]\n\n #model = MyTableModel(tableData0, headers)\n table_df = pd.DataFrame(tableData0, columns=headers)\n\n MainWindow.count += 1\n self.dataframe_viewer = DataFrameViewer(table_df)\n self.mdi.addSubWindow(self.dataframe_viewer)\n\n # QProcess object for external app\n self.process = QProcess(self)\n self.process.readyReadStandardOutput.connect(lambda: self.dataReady(\"std\"))\n self.process.readyReadStandardError.connect(lambda: self.dataReady(\"error\"))\n self.process.finished.connect(lambda: self.update_svg())\n\n #Connect Slots\n self.script_window.button_exec.clicked.connect(lambda: self.run_script())\n self.script_window.button_read.clicked.connect(lambda: self.read_svg())\n #self.viewer_window.button_save.clicked.connect(lambda: self.save_svg())\n\n #Assign Shortcuts\n self.shortcut_update = QShortcut(QKeySequence(\"Ctrl+R\"), self)\n self.shortcut_update.activated.connect(lambda: self.run_script())\n self.shortcut_update = QShortcut(QKeySequence(\"Ctrl+O\"), self)\n self.shortcut_update.activated.connect(lambda: self.read_svg())\n self.shortcut_update = QShortcut(QKeySequence(\"Ctrl+S\"), self)\n self.shortcut_update.activated.connect(lambda: self.save_svg())\n\n def windowaction(self, q):\n if q.text() == \"cascade\":\n self.mdi.cascadeSubWindows()\n\n if q.text() == \"Tiled\":\n self.mdi.tileSubWindows()\n\n @pyqtSlot()\n def read_svg(self):\n print(\"READ\")\n self.script_window.fname = QFileDialog.getOpenFileName(self, 'Open file', '/home')\n if self.script_window.fname[0]:\n # import script metadata\n svg_tree = ET.parse(self.script_window.fname[0])\n root = svg_tree.getroot()\n for metadata in root.findall(\"{http://www.w3.org/2000/svg}metadata\"):\n for metadatum in metadata:\n if metadatum.tag == \"{https://korintje.com}script\":\n self.script_window.edit.setPlainText(metadatum.text)\n break\n self.run_script()\n\n # Parse original .svg\n print(self.script_window.fname[0])\n original_svg_tree = ET.parse(self.script_window.fname[0])\n original_root = original_svg_tree.getroot()\n for og in original_root.findall(\"{http://www.w3.org/2000/svg}g\"):\n if \"{http://www.inkscape.org/namespaces/inkscape}groupmode\" in og.attrib and og.attrib[\"{http://www.inkscape.org/namespaces/inkscape}groupmode\"] == \"layer\":\n if \"{http://www.inkscape.org/namespaces/inkscape}label\" in og.attrib and og.attrib[\"{http://www.inkscape.org/namespaces/inkscape}label\"] == \"Layer_mpl\":\n original_root.remove(og)\n register_all_namespaces(self.script_window.fname[0])\n original_svg_tree.write(\"bkg_temp.svg\", encoding=\"UTF-8\", xml_declaration=True)\n self.update_bkg(\"bkg_temp.svg\")\n\n @pyqtSlot()\n def run_script(self):\n self.output_window.stdout.clear()\n script = self.script_window.edit.toPlainText()\n self.process.start('python',['-c', script])\n self.viewer_window.button_save.clicked.connect(lambda: self.save_svg())\n\n @pyqtSlot()\n def update_svg(self):\n self.viewer_window.view.load(\"temp.svg\")\n\n @pyqtSlot()\n def dataReady(self,err_or_std):\n cursor = self.output_window.stdout.textCursor()\n cursor.movePosition(cursor.End)\n if err_or_std == \"std\":\n message = self.process.readAllStandardOutput().data().decode(\"utf8\")\n self.output_window.stdout.setTextColor(QColor(48, 255, 48))\n else: #if err_or_std == \"error\":\n message = self.process.readAllStandardError().data().decode(\"utf8\")\n self.output_window.stdout.setTextColor(QColor(255, 48, 48))\n self.output_window.stdout.insertPlainText(message)\n cursor.insertBlock()\n #self.output_window.setTopLevelWindow()\n\n @pyqtSlot()\n def update_bkg(self, filename):\n self.viewer_window.bkg.load(filename)\n\n @pyqtSlot()\n def save_svg(self):\n self.run_script()\n # Parse original .svg\n if self.script_window.fname[0]:\n print(self.script_window.fname[0])\n original_svg_tree = ET.parse(self.script_window.fname[0])\n original_root = original_svg_tree.getroot()\n for og in original_root.findall(\"{http://www.w3.org/2000/svg}g\"):\n if \"{http://www.inkscape.org/namespaces/inkscape}groupmode\" in og.attrib and og.attrib[\"{http://www.inkscape.org/namespaces/inkscape}groupmode\"] == \"layer\":\n if \"{http://www.inkscape.org/namespaces/inkscape}label\" in og.attrib and og.attrib[\"{http://www.inkscape.org/namespaces/inkscape}label\"] == \"Layer_mpl\":\n original_root.remove(og)\n\n # Insert modified .svg into the original .svg\n modified_svg_tree = ET.parse(\"temp.svg\")\n modified_root = modified_svg_tree.getroot()\n for mg in modified_root.findall(\"{http://www.w3.org/2000/svg}g\"):\n if \"id\" in mg.attrib and mg.attrib[\"id\"] == \"figure_1\":\n mg.set(\"inkscape:groupmode\", \"layer\")\n mg.set(\"inkscape:label\", \"Layer_mpl\")\n original_root.append(mg)\n print(\"done\")\n\n # Update the script in the metadata\n for metadata in original_root.findall(\"{http://www.w3.org/2000/svg}metadata\"):\n for metadatum in metadata:\n print(metadatum.tag)\n if metadatum.tag == \"{https://korintje.com}script\":\n metadatum.text = self.script_window.edit.toPlainText()\n print(metadatum.text)\n break\n\n register_all_namespaces(self.script_window.fname[0])\n original_svg_tree.write(\"mod_test2.svg\", encoding=\"UTF-8\", xml_declaration=True)\n\ndef main():\n app = QApplication(sys.argv)\n ex = MainWindow()\n ex.show()\n sys.exit(app.exec_())\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"153777797","text":"import sys\nfrom Logic import Game\nfrom Window import CanvasWindow\nfrom pygame.time import *\nfrom Rendering import PurgedRenderer as Renderer\n\nfor arg in sys.argv:\n if arg.startswith(\"#chdir#\"):\n s = arg.partition(\"#chdir#\")\n from os import chdir\n chdir(s[2])\n\nFPS = 30\nRESOLUTION = (10*32, 5*50)\n\nif __name__ == \"__main__\":\n canvas = CanvasWindow(RESOLUTION)\n game = Game()\n clock_timer = Clock()\n renderer = Renderer(game, RESOLUTION, clock_timer)\n canvas.render_call = renderer.render\n canvas.update()\n\n while True:\n user_input = canvas.get_input()\n if user_input:\n if not game.over and not renderer.super_busy():\n game.draw_card()\n canvas.update()\n canvas.handle_events()\n clock_timer.tick(FPS)\n","sub_path":"src/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"13013036","text":"from django import template\nfrom django.template.defaultfilters import stringfilter\n\nregister = template.Library()\n\n\n@register.filter(name='domain')\n@stringfilter\ndef cut_email_domain(value):\n if '@' not in value:\n return '[email not stated]'\n return value.partition('@')[2]\n","sub_path":"test_django/authors/templatetags/email_domain.py","file_name":"email_domain.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"430121766","text":"# -*- coding:utf-8 -*-\nimport tensorflow as tf\nimport tensorflow.contrib.slim as slim\nimport os,sys, time\nfrom text_read import next_batch\nfrom tensorflow.python.platform import flags\nfrom tensorflow import app\nfrom model import VGG16\nimport numpy as np\n\nFLAGS = flags.FLAGS\n\nflags.DEFINE_integer('batch_size', 5, 'Batch size.')\nflags.DEFINE_integer('roi_size', 16, 'roi size')\nflags.DEFINE_string('train_dir', 'train_dir/', 'Directory where to write event logs.')\nflags.DEFINE_string('dataset_path', 'data/train.tfrecord', 'Dataset root folder.')\nflags.DEFINE_string('checkpoint_path', None, 'The checkpoint path to restore')\nflags.DEFINE_float('learning_rate', 0.0004, 'learning rate')\nflags.DEFINE_float('weight_decay', 0.0001, 'weight decay')\nflags.DEFINE_float('momentum', 0.9, 'momentum')\nflags.DEFINE_float('scale_factor', 10.0, 'scale factor')\nflags.DEFINE_boolean('use_dropout', False, 'use_dropout')\nflags.DEFINE_integer('max_number_of_steps', int(10000), 'The maximum number of gradient steps.')\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = '0'\n\ndef main(_):\n if not tf.gfile.Exists(FLAGS.train_dir):\n tf.gfile.MakeDirs(FLAGS.train_dir)\n\n img_batch, groundtruth_label_batch, predict_label_batch,img_height_batch, img_width_batch = \\\n next_batch(dataset_path=FLAGS.dataset_path,\n batch_size=FLAGS.batch_size)\n model = VGG16(roi_size=FLAGS.roi_size,\n is_training=True,\n weight_decay=FLAGS.weight_decay,\n use_dropout=FLAGS.use_dropout)\n\n img_processed = model.preprocess(img_batch)\n img_features = model.extract_features(img_processed)\n predict_scores = model.predict(img_features)\n labels = model.encode(groundtruth_label_batch, predict_label_batch, img_height_batch, img_width_batch, scale_factor=FLAGS.scale_factor)\n loss = model.create_loss(predict_scores, labels)\n\n\n total_loss = slim.losses.get_total_loss()\n global_step = slim.get_or_create_global_step()\n lr = tf.train.piecewise_constant(global_step, \n boundaries=[np.int64(20000), np.int64(40000)],\n values=[FLAGS.learning_rate, FLAGS.learning_rate/10, FLAGS.learning_rate/100])\n optimizer = tf.train.MomentumOptimizer(lr, momentum=FLAGS.momentum)\n train_op = slim.learning.create_train_op(total_loss, optimizer, global_step)\n\n init_op = tf.group(\n tf.global_variables_initializer(),\n tf.local_variables_initializer()\n )\n\n saver = tf.train.Saver(max_to_keep=5)\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n with tf.Session(config=config) as sess:\n sess.run(init_op)\n\n if FLAGS.checkpoint_path:\n saver.restore(sess, FLAGS.checkpoint_path)\n\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(sess, coord)\n\n step_count = 0\n emv_loss = -1\n while (step_count < FLAGS.max_number_of_steps):\n step_count += 1\n _, loss_ = sess.run([train_op, total_loss])\n # print loss_\n if emv_loss < 0:\n emv_loss = loss_\n else:\n emv_loss = emv_loss*0.95 + loss_*0.05\n if step_count % 10 == 0:\n print ('step: %d, loss: %.5f, emv_loss: %.5f' % (step_count, loss_, emv_loss))\n sys.stdout.flush()\n if step_count % 500 == 0:\n saver.save(sess, os.path.join(FLAGS.train_dir, 'model.ckpt'),global_step=step_count)\n\n coord.request_stop()\n coord.join(threads)\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"533704191","text":"\"\"\"\nTrain the ESIM model on the preprocessed SNLI dataset.\n\"\"\"\n# Aurelien Coet, 2018.\n\nimport os\nimport argparse\nimport pickle\nimport torch\nimport json\nimport time\nimport matplotlib.pyplot as plt\nimport torch.nn as nn\nimport sys\nsys.path.insert(0, \"../../\")\nfrom torch.utils.data import DataLoader\nfrom esim.data import NLIDataset\nfrom esim.utils import correct_predictions\nfrom esim.model import ESIM\nfrom utils import train, validate\n\ndef test(model, num_classes, dataloader, print_Confusion=False):\n \"\"\"\n Test the accuracy of a model on some labelled test dataset.\n\n Args:\n model: The torch module on which testing must be performed.\n dataloader: A DataLoader object to iterate over some dataset.\n\n Returns:\n batch_time: The average time to predict the classes of a batch.\n total_time: The total time to process the whole dataset.\n accuracy: The accuracy of the model on the input data.\n \"\"\"\n # Switch the model to eval mode.\n model.eval()\n device = model.device\n\n time_start = time.time()\n batch_time = 0.0\n correct_preds = 0.0\n\n confusion = torch.zeros(num_classes, num_classes, dtype=torch.long)\n\n # Deactivate autograd for evaluation.\n with torch.no_grad():\n for batch in dataloader:\n batch_start = time.time()\n\n # Move input and output data to the GPU if one is used.\n premises = batch[\"premise\"].to(device)\n premises_lengths = batch[\"premise_length\"].to(device)\n hypotheses = batch[\"hypothesis\"].to(device)\n hypotheses_lengths = batch[\"hypothesis_length\"].to(device)\n labels = batch[\"label\"].to(device)\n\n _, probs = model(premises,\n premises_lengths,\n hypotheses,\n hypotheses_lengths)\n\n _, pred = probs.max(dim=1)\n for j in range(pred.size()[0]):\n confusion[pred[j], labels[j]] += 1\n\n correct_preds += correct_predictions(probs, labels)\n batch_time += time.time() - batch_start\n\n batch_time /= len(dataloader)\n total_time = time.time() - time_start\n accuracy = correct_preds / (len(dataloader.dataset))\n\n if print_Confusion == True:\n print(\"Confusion matrix:\")\n print(confusion)\n print(\"Report precision, recall, and f1:\")\n for i in range(confusion.size()[0]):\n p = confusion[i, i].item() / confusion[i, :].sum().item()\n r = confusion[i, i].item() / confusion[:, i].sum().item()\n f1 = 2 * p * r / (p + r)\n print(\"Label {}: {:.3f}, {:.3f}, {:.3f}\".format(i, p, r, f1))\n\n p = confusion[1, 1].item() / confusion[:, 1].sum().item()\n r = confusion[1, 1].item() / confusion[1, :].sum().item()\n f1 = 2 * p * r / (p + r)\n #print(\"Report precision, recall, and f1:\" , p, r, f1)\n return batch_time, total_time, f1, accuracy\n\n\ndef main(train_file,\n valid_file,\n test_file,\n embeddings_file,\n target_dir,\n hidden_size=300,\n dropout=0.5,\n num_classes=2,\n epochs=64,\n batch_size=32,\n lr=0.0004,\n patience=5,\n max_grad_norm=10.0,\n checkpoint=None,\n proportion=1,\n output=None):\n \"\"\"\n Train the ESIM model on the SNLI dataset.\n\n Args:\n train_file: A path to some preprocessed data that must be used\n to train the model.\n valid_file: A path to some preprocessed data that must be used\n to validate the model.\n embeddings_file: A path to some preprocessed word embeddings that\n must be used to initialise the model.\n target_dir: The path to a directory where the trained model must\n be saved.\n hidden_size: The size of the hidden layers in the model. Defaults\n to 300.\n dropout: The dropout rate to use in the model. Defaults to 0.5.\n num_classes: The number of classes in the output of the model.\n Defaults to 3.\n epochs: The maximum number of epochs for training. Defaults to 64.\n batch_size: The size of the batches for training. Defaults to 32.\n lr: The learning rate for the optimizer. Defaults to 0.0004.\n patience: The patience to use for early stopping. Defaults to 5.\n checkpoint: A checkpoint from which to continue training. If None,\n training starts from scratch. Defaults to None.\n \"\"\"\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n print(20 * \"=\", \" Preparing for training \", 20 * \"=\")\n\n if not os.path.exists(target_dir):\n os.makedirs(target_dir)\n\n # -------------------- Data loading ------------------- #\n print(\"\\t* Loading training data...\")\n with open(train_file, \"rb\") as pkl:\n train_data = NLIDataset(pickle.load(pkl), proportion, isRandom=True)#training data will be shuffled first, then we will get random data of different proportion\n\n train_loader = DataLoader(train_data, shuffle=False, batch_size=batch_size)\n\n\n print(\"\\t* Loading validation data...\")\n with open(valid_file, \"rb\") as pkl:\n valid_data = NLIDataset(pickle.load(pkl))\n\n valid_loader = DataLoader(valid_data, shuffle=False, batch_size=batch_size)\n\n print(\"\\t* Loading test data...\")\n with open(test_file, \"rb\") as pkl:\n test_data = NLIDataset(pickle.load(pkl))\n\n test_loader = DataLoader(test_data, shuffle=False, batch_size=batch_size)\n\n # -------------------- Model definition ------------------- #\n print(\"\\t* Building model...\")\n with open(embeddings_file, \"rb\") as pkl:\n embeddings = torch.tensor(pickle.load(pkl), dtype=torch.float)\\\n .to(device)\n\n model = ESIM(embeddings.shape[0],\n embeddings.shape[1],\n hidden_size,\n embeddings=embeddings,\n dropout=dropout,\n num_classes=num_classes,\n device=device).to(device)\n\n # -------------------- Preparation for training ------------------- #\n criterion = nn.CrossEntropyLoss()\n optimizer = torch.optim.Adam(model.parameters(), lr=lr)\n scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer,\n mode=\"max\",\n factor=0.5,\n patience=0)\n\n best_score = 0.0\n start_epoch = 1\n\n # Data for loss curves plot.\n epochs_count = []\n train_losses = []\n valid_losses = []\n\n # Continuing training from a checkpoint if one was given as argument.\n if checkpoint:\n checkpoint = torch.load(checkpoint)\n start_epoch = checkpoint[\"epoch\"] + 1\n best_score = checkpoint[\"best_score\"]\n\n print(\"\\t* Training will continue on existing model from epoch {}...\"\n .format(start_epoch))\n\n model.load_state_dict(checkpoint[\"model\"])\n optimizer.load_state_dict(checkpoint[\"optimizer\"])\n epochs_count = checkpoint[\"epochs_count\"]\n train_losses = checkpoint[\"train_losses\"]\n valid_losses = checkpoint[\"valid_losses\"]\n\n # Compute loss and accuracy before starting (or resuming) training.\n\n _, valid_loss, valid_accuracy = validate(model,\n valid_loader,\n criterion)\n print(\"\\t* Validation loss before training: {:.4f}, accuracy: {:.4f}%\"\n .format(valid_loss, (valid_accuracy*100)))\n\n # -------------------- Training epochs ------------------- #\n print(\"\\n\",\n 20 * \"=\",\n \"Training ESIM model on device: {}\".format(device),\n 20 * \"=\")\n\n patience_counter = 0\n for epoch in range(start_epoch, epochs+1):\n epochs_count.append(epoch)\n\n print(\"* Training epoch {}:\".format(epoch))\n epoch_time, epoch_loss, epoch_accuracy = train(model,\n train_loader,\n optimizer,\n criterion,\n epoch,\n max_grad_norm)\n\n train_losses.append(epoch_loss)\n print(\"-> Training time: {:.4f}s, loss = {:.4f}, accuracy: {:.4f}%\"\n .format(epoch_time, epoch_loss, (epoch_accuracy*100)))\n\n\n print(\"* Validation for epoch {}:\".format(epoch))\n epoch_time, epoch_loss, epoch_accuracy = validate(model,\n valid_loader,\n criterion)\n\n valid_losses.append(epoch_loss)\n print(\"-> Valid. time: {:.4f}s, loss: {:.4f}, accuracy: {:.4f}%\\n\"\n .format(epoch_time, epoch_loss, (epoch_accuracy*100)))\n\n # Update the optimizer's learning rate with the scheduler.\n scheduler.step(epoch_accuracy)\n\n print(\"* Testing for epoch {}:\".format(epoch))\n batch_time, total_time, f1, accuracy = test(model, num_classes, test_loader)\n print(\n \"-> Average batch processing time: {:.4f}s, total test time: {:.4f}s, f1: {:.4f}, accuracy: {:.4f}%\".format(\n batch_time, total_time, f1, (accuracy * 100)))\n print(20 * \"====\")\n\n\n # Early stopping on validation accuracy.\n if epoch > 2:\n if epoch_accuracy <= best_score:\n patience_counter += 1\n else:\n best_score = epoch_accuracy\n patience_counter = 0\n # Save the best model. The optimizer is not saved to avoid having\n # a checkpoint file that is too heavy to be shared. To resume\n # training from the best model, use the 'esim_*.pth.tar'\n # checkpoints instead.\n torch.save({\"epoch\": epoch,\n \"model\": model.state_dict(),\n \"best_score\": best_score,\n \"epochs_count\": epochs_count,\n \"train_losses\": train_losses,\n \"valid_losses\": valid_losses},\n os.path.join(target_dir, output + \"_\" + str(proportion) + \"_best.pth.tar\"))\n \n if patience_counter >= patience:\n print(\"-> Early stopping: patience limit reached, stopping...\")\n checkpoint = torch.load(os.path.join(target_dir, output + \"_\" + str(proportion) + \"_best.pth.tar\"))\n # Retrieving model parameters from checkpoint.\n vocab_size = checkpoint[\"model\"][\"_word_embedding.weight\"].size(0)\n embedding_dim = checkpoint[\"model\"]['_word_embedding.weight'].size(1)\n hidden_size = checkpoint[\"model\"][\"_projection.0.weight\"].size(0)\n num_classes = checkpoint[\"model\"][\"_classification.4.weight\"].size(0)\n print(\"\\t* Final test...\")\n model = ESIM(vocab_size,\n embedding_dim,\n hidden_size,\n num_classes=num_classes,\n device=device).to(device)\n model.load_state_dict(checkpoint[\"model\"])\n batch_time, total_time, f1, accuracy = test(model, num_classes, test_loader, print_Confusion=True)\n print(\"-> Final f1, accuracy: {:.4f}, {:.4f}%\".format(f1, accuracy * 100))\n os.remove(os.path.join(target_dir, output + \"_\" + str(proportion) + \"_best.pth.tar\"))\n break\n if epoch == 15:\n checkpoint = torch.load(os.path.join(target_dir, output + \"_\" + str(proportion) + \"_best.pth.tar\"))\n # Retrieving model parameters from checkpoint.\n vocab_size = checkpoint[\"model\"][\"_word_embedding.weight\"].size(0)\n embedding_dim = checkpoint[\"model\"]['_word_embedding.weight'].size(1)\n hidden_size = checkpoint[\"model\"][\"_projection.0.weight\"].size(0)\n num_classes = checkpoint[\"model\"][\"_classification.4.weight\"].size(0)\n print(\"\\t* Final test...\")\n model = ESIM(vocab_size,\n embedding_dim,\n hidden_size,\n num_classes=num_classes,\n device=device).to(device)\n model.load_state_dict(checkpoint[\"model\"])\n batch_time, total_time, f1, accuracy = test(model, num_classes, test_loader, print_Confusion=True)\n print(\"-> Final f1, accuracy: {:.4f}, {:.4f}%\".format(f1, accuracy * 100))\n os.remove(os.path.join(target_dir, output + \"_\" + str(proportion) + \"_best.pth.tar\"))\n\n\n\nif __name__ == \"__main__\":\n default_config = \"../../config/training/url_training.json\"\n\n parser = argparse.ArgumentParser(description=\"Train the ESIM model on PI\")\n parser.add_argument(\"--config\",\n default=default_config,\n help=\"Path to a json configuration file\")\n parser.add_argument(\"--checkpoint\",\n default=None,\n help=\"Path to a checkpoint file to resume training\")\n parser.add_argument(\"--proportion\", default=1, type=float,\n help=\"{Proportion of training data}\")\n parser.add_argument(\"--output\",\n default='100', type=str,\n help=\"where to Save model\")\n args = parser.parse_args()\n\n script_dir = os.path.dirname(os.path.realpath(__file__))\n\n if args.config == default_config:\n config_path = os.path.join(script_dir, args.config)\n else:\n config_path = args.config\n\n with open(os.path.normpath(config_path), 'r') as config_file:\n config = json.load(config_file)\n\n main(os.path.normpath(os.path.join(script_dir, config[\"train_data\"])),\n os.path.normpath(os.path.join(script_dir, config[\"valid_data\"])),\n os.path.normpath(os.path.join(script_dir, config[\"test_data\"])),\n os.path.normpath(os.path.join(script_dir, config[\"embeddings\"])),\n os.path.normpath(os.path.join(script_dir, config[\"target_dir\"])),\n config[\"hidden_size\"],\n config[\"dropout\"],\n config[\"num_classes\"],\n config[\"epochs\"],\n config[\"batch_size\"],\n config[\"lr\"],\n config[\"patience\"],\n config[\"max_gradient_norm\"],\n args.checkpoint,\n args.proportion,\n args.output)\n","sub_path":"ESIM/scripts/training/main_url.py","file_name":"main_url.py","file_ext":"py","file_size_in_byte":14640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"500481963","text":"num = int(input())\n# 输入的测试用例的数量\n\n\ndef find(array):\n array = sorted(array)\n pre = array[0]\n count = 1\n for index in range(1, len(array)):\n if array[index] == pre:\n count = count+1\n pre = array[index]\n else:\n count = 1\n pre = array[index]\n if count > len(array)/2:\n return array[index]\n return -1\n\n\nfor i in range(num):\n length = int(input())\n arrays = map(int, input().split(\" \"))\n print(find(arrays))\n\n","sub_path":"Code/CodeRecords/2307/60598/233589.py","file_name":"233589.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"623508163","text":"import re\nimport itertools\n\nfirst_word = ''\nsecond_word = ''\nrules = list()\nhand = open('000140.ant')\nfor line in hand:\n line = line.rstrip()\n if re.search('s[0-9]$', line):\n rules.append(line)\nprint(rules)\nfor a, b in itertools.combinations(rules, 2):\n if re.search('^amod', a) and re.search('^nmod', b):\n first_word = re.findall('\\((.*?)\\-', a)\n print(first_word)\n second_word = re.findall('\\, (.*?)\\-', b)\n print(second_word)\n","sub_path":"lexxe.py","file_name":"lexxe.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"534019667","text":"import sys\nfrom PCMtoXYZ import *\nfrom PyQt5.QtWidgets import QApplication, QDialog\nfrom tkinter import *\nfrom tkinter import filedialog\nfrom tkinter.filedialog import askopenfilename\nfrom MainUI import Ui_GUI\nfrom Popup1 import Ui_Complete\nfrom Popup2 import Ui_Err\nimport os\n\n###TestVariables###\npcmlocation = \"Z:\\MS\\TPY PCM\\MS2.pcm\"\nDirLocation = \"Z:\\MS\\TPY PCM\"\nPrefix = \"conf\"\n\ndef xyzgen(path, genname):\n if not os.path.exists(path):\n os.makedirs(path)\n open(path+'\\\\'+genname+'.xyz', 'w+')\n\nclass ProgramDesign(QDialog, Ui_GUI):\n def __init__(self):\n super().__init__()\n self.ui = Ui_GUI()\n self.ui.setupUi(self)\n self.show()\n self.ui.SaveButton.clicked.connect(self.mainftn)\n self.ui.ExitButton.clicked.connect(self.closeftn)\n self.ui.Choosefile.clicked.connect(self.chooseftn)\n self.ui.OutputB.clicked.connect(self.outputftn)\n\n\n def mainftn(self):\n global pcmlocation, DirLocation, Prefix\n# DirLocation = self.ui.OutputBox.toPlainText()\n Prefix = self.ui.PrefixBox.toPlainText()\n if pcmlocation == '' or DirLocation == '' or Prefix == '':\n global errpopup\n errpopup = Errorpopup()\n else:\n f = open(pcmlocation, \"r\")\n contents = f.readlines()\n numconf = 1\n for line in contents:\n string = line.split()\n if string[0] == '{PCM':\n Filename = Prefix+str(numconf)\n path = DirLocation + '\\\\' + str(Filename)\n xyzgen(path, Filename)\n flag = 1\n numconf = numconf + 1\n elif flag == 1:\n flag = 2\n numatom = string[1]\n xyzfile = open(path+'\\\\'+Filename+'.xyz', 'a')\n xyzfile.write(str(numatom))\n xyzfile.write('\\n\\n')\n elif string[0] == 'AT':\n xyzfile.write(PCM_XYZ(int(string[2]))+' ')\n xyzfile.write(string[3]+' '+string[4]+' '+string[5]+'\\n')\n f.close()\n global ui2\n ui2 = Completepopup()\n\n def chooseftn(self):\n Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing\n global pcmlocation\n pcmlocation = askopenfilename()\n self.ui.PCMBox.setPlainText(pcmlocation)\n\n def outputftn(self):\n Tk().withdraw()\n global DirLocation\n DirLocation = filedialog.askdirectory()\n self.ui.OutputBox.setPlainText(DirLocation)\n\n\n def closeftn(self):\n ui.close()\n\nclass Completepopup(QDialog, Ui_Complete):\n def __init__(self):\n super().__init__()\n self.ui = Ui_Complete()\n self.ui.setupUi(self)\n self.show()\n self.ui.OKButton.clicked.connect(self.closeftn)\n\n def closeftn(self):\n ui2.close()\n\n\nclass Errorpopup(QDialog, Ui_Err):\n def __init__(self):\n super().__init__()\n self.ui = Ui_Err()\n self.ui.setupUi(self)\n self.show()\n self.ui.OKButton_2.clicked.connect(self.closeftn)\n\n def closeftn(self):\n errpopup.close()\n\n\napp = QApplication(sys.argv)\n#GUI = QDialog()\nui = ProgramDesign()\n#ui.setupUi(GUI)\nui.show()\n#ui2 = Completepopup()\n#ui2.show()\nsys.exit(app.exec_())\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"18770691","text":"#!/usr/bin/env python\n\n\"\"\"Write JSON index for a directory.\"\"\"\n\nimport os\nimport sys\nimport json\nimport argparse\n\nEPILOG = \"\"\"\nThe index is a list of names of .json files in the directory, excluding the index file\nitself (if it is in the directory).\n\"\"\"\n\n\ndef main(args):\n # use os.path.isfile or os.path.isdir to avoid directories\n files = [filename for filename in os.listdir(args.directory)\n if filename.endswith('.json')]\n if args.output == '-':\n writer = sys.stdout\n else:\n out = args.output or args.directory + os.sep + 'index.json'\n writer = open(out, 'w')\n dirpath = os.path.abspath(args.directory)\n outdir, outfile = os.path.split(os.path.abspath(out))\n if dirpath == outdir and outfile in files:\n files.remove(outfile)\n json.dump(files, writer, indent=2, sort_keys=True)\n\n\ndef get_args():\n formatter = argparse.RawDescriptionHelpFormatter\n p = argparse.ArgumentParser(\n description=__doc__,\n epilog=EPILOG,\n formatter_class=formatter)\n p.add_argument('directory', nargs='?', type=str, default='.',\n help='directory to index, default is current directory')\n p.add_argument('--output', type=str,\n help=('output file, or \"-\" for stdout, default \"index.json\" ' +\n 'in indexed directory'))\n args = p.parse_args()\n return args\n\nif __name__ == \"__main__\":\n main(get_args())\n","sub_path":"scripts/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"617813215","text":"# coding: utf-8\n\n\"\"\"\nManagementInterface.py\n\n The Clear BSD License\n\n Copyright (c) – 2016, NetApp, Inc. All rights reserved.\n\n Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n\n * Neither the name of NetApp, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n\n NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\"\"\"\n\nfrom pprint import pformat\nfrom six import iteritems\n\n\nclass ManagementInterface(object):\n \"\"\"\n NOTE: This class is auto generated by the swagger code generator program.\n Do not edit the class manually.\n \"\"\"\n def __init__(self):\n \"\"\"\n ManagementInterface - a model defined in Swagger\n\n :param dict swaggerTypes: The key is attribute name\n and the value is attribute type.\n :param dict attributeMap: The key is attribute name\n and the value is json key in definition.\n \"\"\"\n self.swagger_types = {\n 'interface_name': 'str', # (required parameter)\n 'channel': 'int', # (required parameter)\n 'speed': 'int', # (required parameter)\n 'ip': 'int', # (required parameter)\n 'alias': 'str', # (required parameter)\n 'mac_addr': 'str', # (required parameter)\n 'gateway_ip': 'int', # (required parameter)\n 'subnet_mask': 'int', # (required parameter)\n 'bootp_used': 'bool', # (required parameter)\n 'rlogin_enabled': 'bool', # (required parameter)\n 'reserved1': 'str', \n 'setup_error': 'bool', # (required parameter)\n 'reserved2': 'str', \n 'interface_ref': 'str', # (required parameter)\n 'link_status': 'str', # (required parameter)\n 'ipv4_enabled': 'bool', # (required parameter)\n 'ipv4_address': 'str', # (required parameter)\n 'ipv4_subnet_mask': 'str', # (required parameter)\n 'ipv4_address_config_method': 'str', # (required parameter)\n 'ipv6_enabled': 'bool', # (required parameter)\n 'ipv6_local_address': 'IpV6AddressData', # (required parameter)\n 'ipv6_port_static_routable_address': 'IpV6AddressData', # (required parameter)\n 'ipv6_port_routable_addresses': 'list[IpV6AddressData]', # (required parameter)\n 'ipv6_address_config_method': 'str', # (required parameter)\n 'full_duplex': 'bool', # (required parameter)\n 'supported_speed_settings': 'list[str]', # (required parameter)\n 'configured_speed_setting': 'str', # (required parameter)\n 'current_speed': 'str', # (required parameter)\n 'physical_location': 'Location', # (required parameter)\n 'ipv4_gateway_address': 'str', \n 'controller_ref': 'str', \n 'controller_slot': 'int', \n 'dns_properties': 'ControllerDNSProperties', \n 'ntp_properties': 'ControllerNTPProperties', \n 'id': 'str'\n }\n\n self.attribute_map = {\n 'interface_name': 'interfaceName', # (required parameter)\n 'channel': 'channel', # (required parameter)\n 'speed': 'speed', # (required parameter)\n 'ip': 'ip', # (required parameter)\n 'alias': 'alias', # (required parameter)\n 'mac_addr': 'macAddr', # (required parameter)\n 'gateway_ip': 'gatewayIp', # (required parameter)\n 'subnet_mask': 'subnetMask', # (required parameter)\n 'bootp_used': 'bootpUsed', # (required parameter)\n 'rlogin_enabled': 'rloginEnabled', # (required parameter)\n 'reserved1': 'reserved1', \n 'setup_error': 'setupError', # (required parameter)\n 'reserved2': 'reserved2', \n 'interface_ref': 'interfaceRef', # (required parameter)\n 'link_status': 'linkStatus', # (required parameter)\n 'ipv4_enabled': 'ipv4Enabled', # (required parameter)\n 'ipv4_address': 'ipv4Address', # (required parameter)\n 'ipv4_subnet_mask': 'ipv4SubnetMask', # (required parameter)\n 'ipv4_address_config_method': 'ipv4AddressConfigMethod', # (required parameter)\n 'ipv6_enabled': 'ipv6Enabled', # (required parameter)\n 'ipv6_local_address': 'ipv6LocalAddress', # (required parameter)\n 'ipv6_port_static_routable_address': 'ipv6PortStaticRoutableAddress', # (required parameter)\n 'ipv6_port_routable_addresses': 'ipv6PortRoutableAddresses', # (required parameter)\n 'ipv6_address_config_method': 'ipv6AddressConfigMethod', # (required parameter)\n 'full_duplex': 'fullDuplex', # (required parameter)\n 'supported_speed_settings': 'supportedSpeedSettings', # (required parameter)\n 'configured_speed_setting': 'configuredSpeedSetting', # (required parameter)\n 'current_speed': 'currentSpeed', # (required parameter)\n 'physical_location': 'physicalLocation', # (required parameter)\n 'ipv4_gateway_address': 'ipv4GatewayAddress', \n 'controller_ref': 'controllerRef', \n 'controller_slot': 'controllerSlot', \n 'dns_properties': 'dnsProperties', \n 'ntp_properties': 'ntpProperties', \n 'id': 'id'\n }\n\n self._interface_name = None\n self._channel = None\n self._speed = None\n self._ip = None\n self._alias = None\n self._mac_addr = None\n self._gateway_ip = None\n self._subnet_mask = None\n self._bootp_used = None\n self._rlogin_enabled = None\n self._reserved1 = None\n self._setup_error = None\n self._reserved2 = None\n self._interface_ref = None\n self._link_status = None\n self._ipv4_enabled = None\n self._ipv4_address = None\n self._ipv4_subnet_mask = None\n self._ipv4_address_config_method = None\n self._ipv6_enabled = None\n self._ipv6_local_address = None\n self._ipv6_port_static_routable_address = None\n self._ipv6_port_routable_addresses = None\n self._ipv6_address_config_method = None\n self._full_duplex = None\n self._supported_speed_settings = None\n self._configured_speed_setting = None\n self._current_speed = None\n self._physical_location = None\n self._ipv4_gateway_address = None\n self._controller_ref = None\n self._controller_slot = None\n self._dns_properties = None\n self._ntp_properties = None\n self._id = None\n\n @property\n def interface_name(self):\n \"\"\"\n Gets the interface_name of this ManagementInterface.\n Name of the Ethernet port, as reported by the controller.\n\n :return: The interface_name of this ManagementInterface.\n :rtype: str\n :required/optional: required\n \"\"\"\n return self._interface_name\n\n @interface_name.setter\n def interface_name(self, interface_name):\n \"\"\"\n Sets the interface_name of this ManagementInterface.\n Name of the Ethernet port, as reported by the controller.\n\n :param interface_name: The interface_name of this ManagementInterface.\n :type: str\n \"\"\"\n self._interface_name = interface_name\n\n @property\n def channel(self):\n \"\"\"\n Gets the channel of this ManagementInterface.\n The channel number of this Ethernet interface.\n\n :return: The channel of this ManagementInterface.\n :rtype: int\n :required/optional: required\n \"\"\"\n return self._channel\n\n @channel.setter\n def channel(self, channel):\n \"\"\"\n Sets the channel of this ManagementInterface.\n The channel number of this Ethernet interface.\n\n :param channel: The channel of this ManagementInterface.\n :type: int\n \"\"\"\n self._channel = channel\n\n @property\n def speed(self):\n \"\"\"\n Gets the speed of this ManagementInterface.\n The speed of the interface, as currently configured, in Mbit/sec.\n\n :return: The speed of this ManagementInterface.\n :rtype: int\n :required/optional: required\n \"\"\"\n return self._speed\n\n @speed.setter\n def speed(self, speed):\n \"\"\"\n Sets the speed of this ManagementInterface.\n The speed of the interface, as currently configured, in Mbit/sec.\n\n :param speed: The speed of this ManagementInterface.\n :type: int\n \"\"\"\n self._speed = speed\n\n @property\n def ip(self):\n \"\"\"\n Gets the ip of this ManagementInterface.\n The 32-bit IP protocol address assigned to the interface.\n\n :return: The ip of this ManagementInterface.\n :rtype: int\n :required/optional: required\n \"\"\"\n return self._ip\n\n @ip.setter\n def ip(self, ip):\n \"\"\"\n Sets the ip of this ManagementInterface.\n The 32-bit IP protocol address assigned to the interface.\n\n :param ip: The ip of this ManagementInterface.\n :type: int\n \"\"\"\n self._ip = ip\n\n @property\n def alias(self):\n \"\"\"\n Gets the alias of this ManagementInterface.\n An ASCII string that identifies the alias name for the interface; this name is presumed to be associated with the IP protocol address.\n\n :return: The alias of this ManagementInterface.\n :rtype: str\n :required/optional: required\n \"\"\"\n return self._alias\n\n @alias.setter\n def alias(self, alias):\n \"\"\"\n Sets the alias of this ManagementInterface.\n An ASCII string that identifies the alias name for the interface; this name is presumed to be associated with the IP protocol address.\n\n :param alias: The alias of this ManagementInterface.\n :type: str\n \"\"\"\n self._alias = alias\n\n @property\n def mac_addr(self):\n \"\"\"\n Gets the mac_addr of this ManagementInterface.\n An ASCII string representation of the globally-unique 48-bit MAC address assigned to the Ethernet interface.\n\n :return: The mac_addr of this ManagementInterface.\n :rtype: str\n :required/optional: required\n \"\"\"\n return self._mac_addr\n\n @mac_addr.setter\n def mac_addr(self, mac_addr):\n \"\"\"\n Sets the mac_addr of this ManagementInterface.\n An ASCII string representation of the globally-unique 48-bit MAC address assigned to the Ethernet interface.\n\n :param mac_addr: The mac_addr of this ManagementInterface.\n :type: str\n \"\"\"\n self._mac_addr = mac_addr\n\n @property\n def gateway_ip(self):\n \"\"\"\n Gets the gateway_ip of this ManagementInterface.\n IP address of the gateway.\n\n :return: The gateway_ip of this ManagementInterface.\n :rtype: int\n :required/optional: required\n \"\"\"\n return self._gateway_ip\n\n @gateway_ip.setter\n def gateway_ip(self, gateway_ip):\n \"\"\"\n Sets the gateway_ip of this ManagementInterface.\n IP address of the gateway.\n\n :param gateway_ip: The gateway_ip of this ManagementInterface.\n :type: int\n \"\"\"\n self._gateway_ip = gateway_ip\n\n @property\n def subnet_mask(self):\n \"\"\"\n Gets the subnet_mask of this ManagementInterface.\n Network subnet mask.\n\n :return: The subnet_mask of this ManagementInterface.\n :rtype: int\n :required/optional: required\n \"\"\"\n return self._subnet_mask\n\n @subnet_mask.setter\n def subnet_mask(self, subnet_mask):\n \"\"\"\n Sets the subnet_mask of this ManagementInterface.\n Network subnet mask.\n\n :param subnet_mask: The subnet_mask of this ManagementInterface.\n :type: int\n \"\"\"\n self._subnet_mask = subnet_mask\n\n @property\n def bootp_used(self):\n \"\"\"\n Gets the bootp_used of this ManagementInterface.\n Bootpserver used to get network parameters.\n\n :return: The bootp_used of this ManagementInterface.\n :rtype: bool\n :required/optional: required\n \"\"\"\n return self._bootp_used\n\n @bootp_used.setter\n def bootp_used(self, bootp_used):\n \"\"\"\n Sets the bootp_used of this ManagementInterface.\n Bootpserver used to get network parameters.\n\n :param bootp_used: The bootp_used of this ManagementInterface.\n :type: bool\n \"\"\"\n self._bootp_used = bootp_used\n\n @property\n def rlogin_enabled(self):\n \"\"\"\n Gets the rlogin_enabled of this ManagementInterface.\n True if rlogin sessions are allowed.\n\n :return: The rlogin_enabled of this ManagementInterface.\n :rtype: bool\n :required/optional: required\n \"\"\"\n return self._rlogin_enabled\n\n @rlogin_enabled.setter\n def rlogin_enabled(self, rlogin_enabled):\n \"\"\"\n Sets the rlogin_enabled of this ManagementInterface.\n True if rlogin sessions are allowed.\n\n :param rlogin_enabled: The rlogin_enabled of this ManagementInterface.\n :type: bool\n \"\"\"\n self._rlogin_enabled = rlogin_enabled\n\n @property\n def reserved1(self):\n \"\"\"\n Gets the reserved1 of this ManagementInterface.\n\n\n :return: The reserved1 of this ManagementInterface.\n :rtype: str\n :required/optional: optional\n \"\"\"\n return self._reserved1\n\n @reserved1.setter\n def reserved1(self, reserved1):\n \"\"\"\n Sets the reserved1 of this ManagementInterface.\n\n\n :param reserved1: The reserved1 of this ManagementInterface.\n :type: str\n \"\"\"\n self._reserved1 = reserved1\n\n @property\n def setup_error(self):\n \"\"\"\n Gets the setup_error of this ManagementInterface.\n Set to true if there is a configuration error.\n\n :return: The setup_error of this ManagementInterface.\n :rtype: bool\n :required/optional: required\n \"\"\"\n return self._setup_error\n\n @setup_error.setter\n def setup_error(self, setup_error):\n \"\"\"\n Sets the setup_error of this ManagementInterface.\n Set to true if there is a configuration error.\n\n :param setup_error: The setup_error of this ManagementInterface.\n :type: bool\n \"\"\"\n self._setup_error = setup_error\n\n @property\n def reserved2(self):\n \"\"\"\n Gets the reserved2 of this ManagementInterface.\n\n\n :return: The reserved2 of this ManagementInterface.\n :rtype: str\n :required/optional: optional\n \"\"\"\n return self._reserved2\n\n @reserved2.setter\n def reserved2(self, reserved2):\n \"\"\"\n Sets the reserved2 of this ManagementInterface.\n\n\n :param reserved2: The reserved2 of this ManagementInterface.\n :type: str\n \"\"\"\n self._reserved2 = reserved2\n\n @property\n def interface_ref(self):\n \"\"\"\n Gets the interface_ref of this ManagementInterface.\n The unique identifier for a given instance of this structure.\n\n :return: The interface_ref of this ManagementInterface.\n :rtype: str\n :required/optional: required\n \"\"\"\n return self._interface_ref\n\n @interface_ref.setter\n def interface_ref(self, interface_ref):\n \"\"\"\n Sets the interface_ref of this ManagementInterface.\n The unique identifier for a given instance of this structure.\n\n :param interface_ref: The interface_ref of this ManagementInterface.\n :type: str\n \"\"\"\n self._interface_ref = interface_ref\n\n @property\n def link_status(self):\n \"\"\"\n Gets the link_status of this ManagementInterface.\n The status of the network link for this interface.\n\n :return: The link_status of this ManagementInterface.\n :rtype: str\n :required/optional: required\n \"\"\"\n return self._link_status\n\n @link_status.setter\n def link_status(self, link_status):\n \"\"\"\n Sets the link_status of this ManagementInterface.\n The status of the network link for this interface.\n\n :param link_status: The link_status of this ManagementInterface.\n :type: str\n \"\"\"\n allowed_values = [\"none\", \"up\", \"down\", \"failed\", \"__UNDEFINED\"]\n if link_status not in allowed_values:\n raise ValueError(\n \"Invalid value for `link_status`, must be one of {0}\"\n .format(allowed_values)\n )\n self._link_status = link_status\n\n @property\n def ipv4_enabled(self):\n \"\"\"\n Gets the ipv4_enabled of this ManagementInterface.\n True if IPV4 is enabled for this interface; otherwise false.\n\n :return: The ipv4_enabled of this ManagementInterface.\n :rtype: bool\n :required/optional: required\n \"\"\"\n return self._ipv4_enabled\n\n @ipv4_enabled.setter\n def ipv4_enabled(self, ipv4_enabled):\n \"\"\"\n Sets the ipv4_enabled of this ManagementInterface.\n True if IPV4 is enabled for this interface; otherwise false.\n\n :param ipv4_enabled: The ipv4_enabled of this ManagementInterface.\n :type: bool\n \"\"\"\n self._ipv4_enabled = ipv4_enabled\n\n @property\n def ipv4_address(self):\n \"\"\"\n Gets the ipv4_address of this ManagementInterface.\n The IPV4 address for the interface.\n\n :return: The ipv4_address of this ManagementInterface.\n :rtype: str\n :required/optional: required\n \"\"\"\n return self._ipv4_address\n\n @ipv4_address.setter\n def ipv4_address(self, ipv4_address):\n \"\"\"\n Sets the ipv4_address of this ManagementInterface.\n The IPV4 address for the interface.\n\n :param ipv4_address: The ipv4_address of this ManagementInterface.\n :type: str\n \"\"\"\n self._ipv4_address = ipv4_address\n\n @property\n def ipv4_subnet_mask(self):\n \"\"\"\n Gets the ipv4_subnet_mask of this ManagementInterface.\n The IPV4 subnet mask for the interface.\n\n :return: The ipv4_subnet_mask of this ManagementInterface.\n :rtype: str\n :required/optional: required\n \"\"\"\n return self._ipv4_subnet_mask\n\n @ipv4_subnet_mask.setter\n def ipv4_subnet_mask(self, ipv4_subnet_mask):\n \"\"\"\n Sets the ipv4_subnet_mask of this ManagementInterface.\n The IPV4 subnet mask for the interface.\n\n :param ipv4_subnet_mask: The ipv4_subnet_mask of this ManagementInterface.\n :type: str\n \"\"\"\n self._ipv4_subnet_mask = ipv4_subnet_mask\n\n @property\n def ipv4_address_config_method(self):\n \"\"\"\n Gets the ipv4_address_config_method of this ManagementInterface.\n The method by which the IPV4 address information is configured.\n\n :return: The ipv4_address_config_method of this ManagementInterface.\n :rtype: str\n :required/optional: required\n \"\"\"\n return self._ipv4_address_config_method\n\n @ipv4_address_config_method.setter\n def ipv4_address_config_method(self, ipv4_address_config_method):\n \"\"\"\n Sets the ipv4_address_config_method of this ManagementInterface.\n The method by which the IPV4 address information is configured.\n\n :param ipv4_address_config_method: The ipv4_address_config_method of this ManagementInterface.\n :type: str\n \"\"\"\n allowed_values = [\"configDhcp\", \"configStatic\", \"__UNDEFINED\"]\n if ipv4_address_config_method not in allowed_values:\n raise ValueError(\n \"Invalid value for `ipv4_address_config_method`, must be one of {0}\"\n .format(allowed_values)\n )\n self._ipv4_address_config_method = ipv4_address_config_method\n\n @property\n def ipv6_enabled(self):\n \"\"\"\n Gets the ipv6_enabled of this ManagementInterface.\n True if IPV6 is enabled for this interface; otherwise false.\n\n :return: The ipv6_enabled of this ManagementInterface.\n :rtype: bool\n :required/optional: required\n \"\"\"\n return self._ipv6_enabled\n\n @ipv6_enabled.setter\n def ipv6_enabled(self, ipv6_enabled):\n \"\"\"\n Sets the ipv6_enabled of this ManagementInterface.\n True if IPV6 is enabled for this interface; otherwise false.\n\n :param ipv6_enabled: The ipv6_enabled of this ManagementInterface.\n :type: bool\n \"\"\"\n self._ipv6_enabled = ipv6_enabled\n\n @property\n def ipv6_local_address(self):\n \"\"\"\n Gets the ipv6_local_address of this ManagementInterface.\n The IPV6 local address for the interface and associated data.\n\n :return: The ipv6_local_address of this ManagementInterface.\n :rtype: IpV6AddressData\n :required/optional: required\n \"\"\"\n return self._ipv6_local_address\n\n @ipv6_local_address.setter\n def ipv6_local_address(self, ipv6_local_address):\n \"\"\"\n Sets the ipv6_local_address of this ManagementInterface.\n The IPV6 local address for the interface and associated data.\n\n :param ipv6_local_address: The ipv6_local_address of this ManagementInterface.\n :type: IpV6AddressData\n \"\"\"\n self._ipv6_local_address = ipv6_local_address\n\n @property\n def ipv6_port_static_routable_address(self):\n \"\"\"\n Gets the ipv6_port_static_routable_address of this ManagementInterface.\n The IPV6 static routable address for the interface and associated data.\n\n :return: The ipv6_port_static_routable_address of this ManagementInterface.\n :rtype: IpV6AddressData\n :required/optional: required\n \"\"\"\n return self._ipv6_port_static_routable_address\n\n @ipv6_port_static_routable_address.setter\n def ipv6_port_static_routable_address(self, ipv6_port_static_routable_address):\n \"\"\"\n Sets the ipv6_port_static_routable_address of this ManagementInterface.\n The IPV6 static routable address for the interface and associated data.\n\n :param ipv6_port_static_routable_address: The ipv6_port_static_routable_address of this ManagementInterface.\n :type: IpV6AddressData\n \"\"\"\n self._ipv6_port_static_routable_address = ipv6_port_static_routable_address\n\n @property\n def ipv6_port_routable_addresses(self):\n \"\"\"\n Gets the ipv6_port_routable_addresses of this ManagementInterface.\n The set of IPV6 port routable addresses for the interface.\n\n :return: The ipv6_port_routable_addresses of this ManagementInterface.\n :rtype: list[IpV6AddressData]\n :required/optional: required\n \"\"\"\n return self._ipv6_port_routable_addresses\n\n @ipv6_port_routable_addresses.setter\n def ipv6_port_routable_addresses(self, ipv6_port_routable_addresses):\n \"\"\"\n Sets the ipv6_port_routable_addresses of this ManagementInterface.\n The set of IPV6 port routable addresses for the interface.\n\n :param ipv6_port_routable_addresses: The ipv6_port_routable_addresses of this ManagementInterface.\n :type: list[IpV6AddressData]\n \"\"\"\n self._ipv6_port_routable_addresses = ipv6_port_routable_addresses\n\n @property\n def ipv6_address_config_method(self):\n \"\"\"\n Gets the ipv6_address_config_method of this ManagementInterface.\n The method by which the IPV6 address information is configured for the interface.\n\n :return: The ipv6_address_config_method of this ManagementInterface.\n :rtype: str\n :required/optional: required\n \"\"\"\n return self._ipv6_address_config_method\n\n @ipv6_address_config_method.setter\n def ipv6_address_config_method(self, ipv6_address_config_method):\n \"\"\"\n Sets the ipv6_address_config_method of this ManagementInterface.\n The method by which the IPV6 address information is configured for the interface.\n\n :param ipv6_address_config_method: The ipv6_address_config_method of this ManagementInterface.\n :type: str\n \"\"\"\n allowed_values = [\"configStatic\", \"configStateless\", \"__UNDEFINED\"]\n if ipv6_address_config_method not in allowed_values:\n raise ValueError(\n \"Invalid value for `ipv6_address_config_method`, must be one of {0}\"\n .format(allowed_values)\n )\n self._ipv6_address_config_method = ipv6_address_config_method\n\n @property\n def full_duplex(self):\n \"\"\"\n Gets the full_duplex of this ManagementInterface.\n If set to true, the interface is operating in full duplex mode; otherwise, it is operating in half-duplex mode.\n\n :return: The full_duplex of this ManagementInterface.\n :rtype: bool\n :required/optional: required\n \"\"\"\n return self._full_duplex\n\n @full_duplex.setter\n def full_duplex(self, full_duplex):\n \"\"\"\n Sets the full_duplex of this ManagementInterface.\n If set to true, the interface is operating in full duplex mode; otherwise, it is operating in half-duplex mode.\n\n :param full_duplex: The full_duplex of this ManagementInterface.\n :type: bool\n \"\"\"\n self._full_duplex = full_duplex\n\n @property\n def supported_speed_settings(self):\n \"\"\"\n Gets the supported_speed_settings of this ManagementInterface.\n Support speed setting for interface\n\n :return: The supported_speed_settings of this ManagementInterface.\n :rtype: list[str]\n :required/optional: required\n \"\"\"\n return self._supported_speed_settings\n\n @supported_speed_settings.setter\n def supported_speed_settings(self, supported_speed_settings):\n \"\"\"\n Sets the supported_speed_settings of this ManagementInterface.\n Support speed setting for interface\n\n :param supported_speed_settings: The supported_speed_settings of this ManagementInterface.\n :type: list[str]\n \"\"\"\n self._supported_speed_settings = supported_speed_settings\n\n @property\n def configured_speed_setting(self):\n \"\"\"\n Gets the configured_speed_setting of this ManagementInterface.\n Configured setting for the interface.\n\n :return: The configured_speed_setting of this ManagementInterface.\n :rtype: str\n :required/optional: required\n \"\"\"\n return self._configured_speed_setting\n\n @configured_speed_setting.setter\n def configured_speed_setting(self, configured_speed_setting):\n \"\"\"\n Sets the configured_speed_setting of this ManagementInterface.\n Configured setting for the interface.\n\n :param configured_speed_setting: The configured_speed_setting of this ManagementInterface.\n :type: str\n \"\"\"\n allowed_values = [\"speedNone\", \"speedAutoNegotiated\", \"speed10MbitHalfDuplex\", \"speed10MbitFullDuplex\", \"speed100MbitHalfDuplex\", \"speed100MbitFullDuplex\", \"speed1000MbitHalfDuplex\", \"speed1000MbitFullDuplex\", \"__UNDEFINED\"]\n if configured_speed_setting not in allowed_values:\n raise ValueError(\n \"Invalid value for `configured_speed_setting`, must be one of {0}\"\n .format(allowed_values)\n )\n self._configured_speed_setting = configured_speed_setting\n\n @property\n def current_speed(self):\n \"\"\"\n Gets the current_speed of this ManagementInterface.\n Current speed of the interface.\n\n :return: The current_speed of this ManagementInterface.\n :rtype: str\n :required/optional: required\n \"\"\"\n return self._current_speed\n\n @current_speed.setter\n def current_speed(self, current_speed):\n \"\"\"\n Sets the current_speed of this ManagementInterface.\n Current speed of the interface.\n\n :param current_speed: The current_speed of this ManagementInterface.\n :type: str\n \"\"\"\n allowed_values = [\"speedUnknown\", \"speed1gig\", \"speed2gig\", \"speed4gig\", \"speed10gig\", \"speed15gig\", \"speed3gig\", \"speed10meg\", \"speed100meg\", \"speed2pt5Gig\", \"speed5gig\", \"speed20gig\", \"speed30gig\", \"speed60gig\", \"speed8gig\", \"speed6gig\", \"speed40gig\", \"speed16gig\", \"speed56gig\", \"speed12gig\", \"speed25gig\", \"speed32gig\", \"speed100gig\", \"__UNDEFINED\"]\n if current_speed not in allowed_values:\n raise ValueError(\n \"Invalid value for `current_speed`, must be one of {0}\"\n .format(allowed_values)\n )\n self._current_speed = current_speed\n\n @property\n def physical_location(self):\n \"\"\"\n Gets the physical_location of this ManagementInterface.\n The physical location of the Ethernet interface. The parent reference in Location identifies the physical component (e.g., controller or host card) where the interface circuitry is located, and the position field is a firmware-assigned 1-relative number signifying \\\"1st ethernet interface relative to the parent,\\\" \\\"2nd ethernet interface relative to the parent,\\\" etc. This \\\"interface number\\\" is independent of the interface's channel association.\n\n :return: The physical_location of this ManagementInterface.\n :rtype: Location\n :required/optional: required\n \"\"\"\n return self._physical_location\n\n @physical_location.setter\n def physical_location(self, physical_location):\n \"\"\"\n Sets the physical_location of this ManagementInterface.\n The physical location of the Ethernet interface. The parent reference in Location identifies the physical component (e.g., controller or host card) where the interface circuitry is located, and the position field is a firmware-assigned 1-relative number signifying \\\"1st ethernet interface relative to the parent,\\\" \\\"2nd ethernet interface relative to the parent,\\\" etc. This \\\"interface number\\\" is independent of the interface's channel association.\n\n :param physical_location: The physical_location of this ManagementInterface.\n :type: Location\n \"\"\"\n self._physical_location = physical_location\n\n @property\n def ipv4_gateway_address(self):\n \"\"\"\n Gets the ipv4_gateway_address of this ManagementInterface.\n\n\n :return: The ipv4_gateway_address of this ManagementInterface.\n :rtype: str\n :required/optional: optional\n \"\"\"\n return self._ipv4_gateway_address\n\n @ipv4_gateway_address.setter\n def ipv4_gateway_address(self, ipv4_gateway_address):\n \"\"\"\n Sets the ipv4_gateway_address of this ManagementInterface.\n\n\n :param ipv4_gateway_address: The ipv4_gateway_address of this ManagementInterface.\n :type: str\n \"\"\"\n self._ipv4_gateway_address = ipv4_gateway_address\n\n @property\n def controller_ref(self):\n \"\"\"\n Gets the controller_ref of this ManagementInterface.\n\n\n :return: The controller_ref of this ManagementInterface.\n :rtype: str\n :required/optional: optional\n \"\"\"\n return self._controller_ref\n\n @controller_ref.setter\n def controller_ref(self, controller_ref):\n \"\"\"\n Sets the controller_ref of this ManagementInterface.\n\n\n :param controller_ref: The controller_ref of this ManagementInterface.\n :type: str\n \"\"\"\n self._controller_ref = controller_ref\n\n @property\n def controller_slot(self):\n \"\"\"\n Gets the controller_slot of this ManagementInterface.\n\n\n :return: The controller_slot of this ManagementInterface.\n :rtype: int\n :required/optional: optional\n \"\"\"\n return self._controller_slot\n\n @controller_slot.setter\n def controller_slot(self, controller_slot):\n \"\"\"\n Sets the controller_slot of this ManagementInterface.\n\n\n :param controller_slot: The controller_slot of this ManagementInterface.\n :type: int\n \"\"\"\n self._controller_slot = controller_slot\n\n @property\n def dns_properties(self):\n \"\"\"\n Gets the dns_properties of this ManagementInterface.\n\n\n :return: The dns_properties of this ManagementInterface.\n :rtype: ControllerDNSProperties\n :required/optional: optional\n \"\"\"\n return self._dns_properties\n\n @dns_properties.setter\n def dns_properties(self, dns_properties):\n \"\"\"\n Sets the dns_properties of this ManagementInterface.\n\n\n :param dns_properties: The dns_properties of this ManagementInterface.\n :type: ControllerDNSProperties\n \"\"\"\n self._dns_properties = dns_properties\n\n @property\n def ntp_properties(self):\n \"\"\"\n Gets the ntp_properties of this ManagementInterface.\n\n\n :return: The ntp_properties of this ManagementInterface.\n :rtype: ControllerNTPProperties\n :required/optional: optional\n \"\"\"\n return self._ntp_properties\n\n @ntp_properties.setter\n def ntp_properties(self, ntp_properties):\n \"\"\"\n Sets the ntp_properties of this ManagementInterface.\n\n\n :param ntp_properties: The ntp_properties of this ManagementInterface.\n :type: ControllerNTPProperties\n \"\"\"\n self._ntp_properties = ntp_properties\n\n @property\n def id(self):\n \"\"\"\n Gets the id of this ManagementInterface.\n\n\n :return: The id of this ManagementInterface.\n :rtype: str\n :required/optional: optional\n \"\"\"\n return self._id\n\n @id.setter\n def id(self, id):\n \"\"\"\n Sets the id of this ManagementInterface.\n\n\n :param id: The id of this ManagementInterface.\n :type: str\n \"\"\"\n self._id = id\n\n def to_dict(self):\n \"\"\"\n Returns the model properties as a dict\n \"\"\"\n result = {}\n\n for attr, _ in iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"\n Returns the string representation of the model\n \"\"\"\n return pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"\n For `print` and `pprint`\n \"\"\"\n if self is None:\n return None\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"\n Returns true if both objects are equal\n \"\"\"\n if self is None or other is None:\n return None\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"\n Returns true if both objects are not equal\n \"\"\"\n return not self == other\n\n","sub_path":"netapp/santricity/models/v2/management_interface.py","file_name":"management_interface.py","file_ext":"py","file_size_in_byte":36722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"313405567","text":"from functools import wraps\n\nfrom py2store.base import Store\nfrom py2store.persisters.couchdb_w_couchdb import CouchDbPersister\nfrom py2store.util import lazyprop\n\n\nclass CouchDbStore(Store):\n def clear(self):\n super(CouchDbStore, self).clear()\n\n @wraps(CouchDbPersister.__init__)\n def __init__(self, *args, **kwargs):\n persister = CouchDbPersister(*args, **kwargs)\n super().__init__(persister)\n\n\nclass CouchDbTupleKeyStore(CouchDbStore):\n \"\"\"\n CouchDbStore using tuple keys.\n\n >>> s = CouchDbTupleKeyStore(key_fields=('_id', 'user'))\n >>> k = (1234, 'user')\n >>> v = {'name': 'bob', 'age': 42}\n >>> if k in s: # deleting all docs in tmp\n ... del s[k]\n >>> assert (k in s) == False # see that key is not in store (and testing __contains__)\n >>> orig_length = len(s)\n >>> s[k] = v\n >>> assert len(s) == orig_length + 1\n >>> assert k in list(s)\n >>> assert s[k] == v\n >>> assert s.get(k) == v\n >>> assert v in list(s.values())\n >>> assert (k in s) == True # testing __contains__ again\n >>> del s[k]\n >>> assert len(s) == orig_length\n \"\"\"\n\n @lazyprop\n def _key_fields(self):\n return self.store._key_fields\n\n def _id_of_key(self, k):\n return {field: field_val for field, field_val in zip(self._key_fields, k)}\n\n def _key_of_id(self, _id):\n return tuple(_id[x] for x in self._key_fields)\n\n\ndef test_couchdb_store(s=CouchDbStore(), k=None, v=None):\n if k is None:\n k = {'_id': 'foo'}\n if v is None:\n v = {'val': 'bar'}\n if k in s: # deleting all docs in tmp\n del s[k]\n assert (k in s) is False # see that key is not in store (and testing __contains__)\n orig_length = len(s)\n s[k] = v\n assert len(s) == orig_length + 1\n assert k in list(s)\n assert s[k] == v\n assert s.get(k) == v\n assert v in list(s.values())\n assert (k in s) is True # testing __contains__ again\n del s[k]\n assert len(s) == 0\n\n # tuple as key test\n s = CouchDbTupleKeyStore(key_fields=('_id', 'user'))\n k = (1234, 'user')\n v = {'name': 'bob', 'age': 42}\n if k in s: # deleting all docs in tmp\n del s[k]\n assert (k in s) is False # see that key is not in store (and testing __contains__)\n orig_length = len(s)\n s[k] = v\n assert len(s) == orig_length + 1\n assert k in list(s)\n assert s[k] == v\n assert s.get(k) == v\n assert v in list(s.values())\n assert (k in s) is True # testing __contains__ again\n del s[k]\n assert len(s) == orig_length\n\n\nif __name__ == '__main__':\n test_couchdb_store()\n","sub_path":"py2store/stores/couchdb_store.py","file_name":"couchdb_store.py","file_ext":"py","file_size_in_byte":2602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"635705168","text":"import numpy as np\nimport sys\nimport os\n\ndef load_n_col(file, numpy=False):\n data = []\n with open(file) as fp:\n for line in fp:\n data.append(line.strip().split(' '))\n columns = list(zip(*data))\n if numpy:\n columns = [np.array(list(i)) for i in columns]\n else:\n columns = [list(i) for i in columns]\n return columns\n\nif __name__ == \"__main__\":\n infile = sys.argv[1]\n outfile = sys.argv[2]\n\n utt0s, utt1s, labs = load_n_col(infile)\n\n targs = ['1' if l == 'target' else '0' for l in labs]\n\n with open(outfile, 'w+') as fp:\n for u0, u1, t in zip(utt0s, utt1s, targs):\n line = '{} {} {}\\n'.format(t, u0, u1)\n fp.write(line)","sub_path":"scripts/trials_to_veri_pairs.py","file_name":"trials_to_veri_pairs.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"309018034","text":"#!/usr/bin/env python3\nimport os\nimport sys\nimport random\nimport time\nfrom random import seed, randint\nimport argparse\nimport platform\nfrom datetime import datetime\nimport imp\nfrom myPersonalFunctions import *\nimport glob\nimport numpy as np\nimport pandas as pd\n\ndef process_data(folder, dis):\n location = folder + \"/simulation/dis_{}/0/\".format(dis)\n # print(location)\n all_lipid_list = []\n for i in range(4):\n file = \"lipid.{}.dat\".format(i)\n lipid = pd.read_csv(location+file).assign(Run = i)\n lipid.columns = lipid.columns.str.strip()\n lipid = lipid[[\"Steps\",\"Lipid\",\"Run\"]]\n all_lipid_list.append(lipid)\n lipid = pd.concat(all_lipid_list)\n\n all_dis_list = []\n for i in range(4):\n file = \"addforce.{}.dat\".format(i)\n dis = pd.read_csv(location+file).assign(Run = i)\n dis.columns = dis.columns.str.strip()\n remove_columns = ['AddedForce', 'Dis12', 'Dis34', 'Dis56']\n dis.drop(remove_columns, axis=1,inplace=True)\n all_dis_list.append(dis)\n dis = pd.concat(all_dis_list)\n\n all_wham_list = []\n for i in range(4):\n file = \"wham.{}.dat\".format(i)\n wham = pd.read_csv(location+file).assign(Run = i)\n wham.columns = wham.columns.str.strip()\n remove_columns = ['Rg', 'Tc']\n wham = wham.drop(remove_columns, axis=1)\n all_wham_list.append(wham)\n wham = pd.concat(all_wham_list)\n\n file = \"../log.lammps\"\n temper = pd.read_table(location+file, skiprows=2, sep=' ')\n temper = temper.melt(id_vars=['Step'], value_vars=['T0', 'T1', 'T2', 'T3'], value_name=\"Run\", var_name=\"Temp\")\n\n t2 = temper.merge(wham, how='inner', left_on=[\"Step\", \"Run\"], right_on=[\"Steps\", \"Run\"]\n ).sort_values('Step').drop('Steps', axis=1)\n t3 = t2.merge(dis, how='inner', left_on=[\"Step\", \"Run\"], right_on=[\"Steps\", \"Run\"]\n ).sort_values('Step').drop('Steps', axis=1)\n t4 = t3.merge(lipid, how='inner', left_on=[\"Step\", \"Run\"], right_on=[\"Steps\", \"Run\"]\n ).sort_values('Step').drop('Steps', axis=1)\n t4 = t4.assign(TotalE=t4.Energy + t4.Lipid)\n t350 = t4.query('Temp==\"T0\" & Step > 1e7')\n t350.to_csv(location+\"t350.dat\", sep=' ', index=False, header=False)\n t400 = t4.query('Temp==\"T1\" & Step > 1e7')\n t400.to_csv(location+\"t400.dat\", sep=' ', index=False, header=False)\n t450 = t4.query('Temp==\"T2\" & Step > 1e7')\n t450.to_csv(location+\"t450.dat\", sep=' ', index=False, header=False)\n t4.query('Temp==\"T3\" & Step > 1e7').to_csv(location+\"t500.dat\", sep=' ', index=False, header=False)\n\n# pre = \"/Users/weilu/Research/server/oct_2017/week_of_oct02/freeEnergy\"\n# folder_list = glob.glob(pre+\"/*\")\ndis_list = np.linspace(30, 130, 51)\nfolder = \"/scratch/wl45/oct_2017/week_of_oct09/no_go_freeEnergy\"\nfor dis in dis_list:\n process_data(folder, dis)\n","sub_path":"temper.py","file_name":"temper.py","file_ext":"py","file_size_in_byte":2882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"649731268","text":"import sqlite3\r\n\r\n#define connection and cursor\r\n\r\nconnection = sqlite3.connect (\"store transactions.db\")\r\n\r\ncursor = connection.cursor()\r\n\r\n# create stores table\r\n\r\ncommand1 = \"\"\"CREATE TABLE IF NOT EXISTS\r\nstores(store_id INTEGER PRIMARY KEY, location TEXT)\"\"\"\r\n\r\ncursor.execute(command1)\r\n\r\n# create purchase table\r\n\r\ncommand2 = \"\"\"CREATE TABLE IF NOT EXISTS\r\npurchases(purchase_id INTEGER PRIMARY KEY, store_id INTEGER, total_cost FLOAT,\r\nFOREIGN KEY(store_id) REFERENCES stores(store_id))\"\"\"\r\n\r\ncursor.execute(command2)\r\n\r\n# add to stores\r\n\r\ncursor.execute (\"INSERT INTO stores VALUES ( 21, 'Washington, DC')\")\r\ncursor.execute (\"INSERT INTO stores VALUES ( 22, 'Rockville, MD')\")\r\ncursor.execute (\"INSERT INTO stores VALUES ( 23, 'Bowie, MD')\")\r\n\r\n# add to purchases\r\n\r\ncursor.execute (\"INSERT INTO purchases VALUES (54, 21, 15.49)\")\r\ncursor.execute (\"INSERT INTO purchases VALUES (77, 43, 21.12)\")\r\n\r\n# get results\r\n\r\ncursor.execute(\"SELECT * FROM purchases\")\r\n\r\nresults = cursor.fetchall()\r\nprint (results)\r\n\r\n\r\n","sub_path":"store_transaction.py","file_name":"store_transaction.py","file_ext":"py","file_size_in_byte":1020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"399640313","text":"from sqlalchemy_utils import UUIDType\n\nfrom diilikone.extensions import db\n\n\nclass ProductType(db.Model):\n __tablename__ = 'product_type'\n\n id = db.Column(\n UUIDType(binary=False),\n server_default=db.func.uuid_generate_v4(),\n primary_key=True\n )\n\n name = db.Column(db.Unicode(255), nullable=False)\n\n price = db.Column(\n db.Numeric(scale=2, precision=5),\n nullable=False\n )\n\n stock = db.Column(db.Integer, nullable=False)\n\n @property\n def left_in_stock(self):\n return self.stock - len(self.deals)\n\n def __repr__(self):\n return '<{cls} name={name!r}, price={price!r}>'.format(\n cls=self.__class__.__name__,\n price=self.price,\n name=self.name\n )\n","sub_path":"diilikone/models/product_type.py","file_name":"product_type.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"604767334","text":"# Program to convert an xml\n# file to json file\n \nimport sys\n# import json module and xmltodict\n# module provided by python\nimport json\nimport xmltodict\n \n \n# open the input xml file and read\n# data in form of python dictionary \n# using xmltodict module\ninput_file = sys.argv[1]\noutput_file = sys.argv[2]\nprint(\"Input \",input_file,\" Output \",output_file)\nwith open(input_file) as xml_file:\n \n data_dict = xmltodict.parse(xml_file.read())\n xml_file.close()\n \n # generate the object using json.dumps() \n # corresponding to json data\n \n json_data = json.dumps(data_dict)\n \n out = open(output_file, \"w\")\n out.write('{\"corners\": [')\n #print(data_dict[\"PcGts\"][\"Page\"][\"TextRegion\"])\n beforesort = []\n for arr in data_dict[\"PcGts\"][\"Page\"][\"TextRegion\"]:\n points = arr[\"Coords\"][\"@points\"].split()\n for xy in points:\n beforesort.append(xy)\n beforesort.sort()\n first = 1\n for xy in beforesort:\n if first:\n out.write(\"[\"+xy+\"]\")\n first = 0\n else:\n out.write(\",[\"+xy+\"]\")\n out.write(']}')\n","sub_path":"data/convertToJson.py","file_name":"convertToJson.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"648928248","text":"# ----------------------------\r\n# Exercice 1\r\n# ----------------------------\r\n\r\nfrom random import *\r\n\r\ndef nbre_fois(nbre_tirage, nbre_return : int) -> int:\r\n \"\"\"\r\n Fonction renvoyent le nombre de fois qu'un nombre est tiré au sort d'un dictionaire.\r\n \"\"\"\r\n assert(type(nbre_return) == int and type(nbre_tirage) == int)\r\n assert(nbre_return > 0 and nbre_return <= 6)\r\n assert(nbre_tirage > 0)\r\n\r\n mon_diko = {1: 0, 2: 0, 3: 0, 4: 0, 5:0, 6:0}\r\n\r\n for i in range(nbre_tirage):\r\n x = randint(1, 6)\r\n mon_diko[x] += 1\r\n \r\n return mon_diko[nbre_return]\r\n\r\nassert(nbre_fois(100, 1) >= 0)\r\nprint(nbre_fois(100, 3))\r\n\r\n\r\n\r\n# ----------------------------\r\n# Exercice 2\r\n# ----------------------------\r\n\r\n\r\ndef compte_lettre(chaine_de_test : str) -> dict:\r\n \"\"\"\r\n Fonction qui prend en parametre une chaine de caractère et qui renvoit un dictionaire avec les lettres\r\n présente dans la chaine de caractère et le nombre de fois où elles apparaissent.\r\n \"\"\"\r\n assert(type(chaine_de_test) == str)\r\n assert(len(chaine_de_test) > 0)\r\n\r\n mon_diko = {}\r\n\r\n for i in chaine_de_test:\r\n if i not in mon_diko:\r\n mon_diko[i] = 1\r\n else:\r\n mon_diko[i] += 1\r\n \r\n return mon_diko\r\n\r\n\r\nassert(compte_lettre(\"hello\") == {\"h\": 1, \"e\": 1, \"l\": 2, \"o\": 1})\r\n\r\nprint(compte_lettre(\"comment ca va la street ??\"))\r\n\r\n\r\n# ----------------------------\r\n# Exercice 3\r\n# ----------------------------\r\n\r\n\r\ndico = {'I':'je','am':'suis','is':'est','a':'un(e)','girl':'fille',\r\n 'boy':'garçon', 'nice':'joli(e)','he' : 'il', 'she' : 'elle',\r\n 'eats' : 'mange', 'apple' : 'pomme', 'banana' : 'banane'}\r\n\r\ndef traduis(ch:str)->str :\r\n \"\"\"\r\n Traduit la chaine ch de l'anglais en français\r\n \"\"\"\r\n assert(type(ch) == str)\r\n assert(len(ch)>0)\r\n\r\n liste_francais = []\r\n liste_mot = ch.split(' ')\r\n \r\n for mot in liste_mot:\r\n mot = dico[mot]\r\n liste_francais.append(mot)\r\n \r\n trad = ' '.join(liste_francais)\r\n\r\n return trad\r\n\r\n\r\n\r\ndef translate(ch:str)->str :\r\n \"\"\"\r\n Traduit la chaine ch du français en anglais\r\n \"\"\"\r\n assert(type(ch) == str)\r\n assert(len(ch)>0)\r\n liste_anglais = []\r\n liste_mot = ch.split(' ')\r\n\r\n for mot in liste_mot:\r\n mot = [k for (k, val) in dico.items() if val == mot]\r\n liste_anglais.append(''.join(mot))\r\n \r\n trad = ' '.join(liste_anglais)\r\n return trad\r\n\r\n\r\nassert(traduis('she eats a banana') == 'elle mange un(e) banane')\r\nassert(translate('elle mange un(e) banane') == 'she eats a banana')\r\nprint(traduis('he is a nice boy'))\r\nprint(translate('un(e) fille mange un(e) joli(e) pomme'))\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"nsi_dictionnaire.py","file_name":"nsi_dictionnaire.py","file_ext":"py","file_size_in_byte":2738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"183717779","text":"# -*- coding: UTF-8 -*-\n\n# ------------------------------------------------------------------------------\n# Author: Atrament\n# Copyright: (c) Atrament 2014\n# Licence: CC-BY-SA https://creativecommons.org/licenses/by-sa/4.0/\n# ------------------------------------------------------------------------------\nfrom EulerFunctions import numerator_coincidence\nfrom timer import timed\n\n__author__ = 'Albéric'\n\n\n\"\"\"\nThe fraction 49/98 is a curious fraction,\n as an inexperienced mathematician in attempting to simplify\n it may incorrectly believe that 49/98 = 4/8, which is correct,\n is obtained by cancelling the 9s.\n We shall consider fractions like,\n 30/50 = 3/5, to be trivial examples.\n There are exactly four non-trivial examples of this type of fraction,\n less than one in value, and containing two digits in the numerator and denominator.\n If the product of these four fractions is given in its lowest common terms,\n find the value of the denominator.\n\"\"\"\n\n\n@timed\ndef pb033():\n \"\"\"\"\"\"\n prod_num = 1\n prod_den = 1\n\n for token in range(1, 10):\n for numerat_tok in range(1, 10):\n for denom_tok in range(1, 10):\n if numerat_tok >= denom_tok:\n continue # we look under 1.00\n elif numerator_coincidence(numerat_tok, token) \\\n / numerator_coincidence(token,denom_tok) == numerat_tok / denom_tok:\n prod_num *= numerat_tok\n prod_den *= denom_tok\n return prod_den // prod_num # assuming that would be clever...\n\nif __name__ == \"__main__\":\n print(pb033())\n pass\n","sub_path":"pbs/pb033.py","file_name":"pb033.py","file_ext":"py","file_size_in_byte":1642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"49922194","text":"#!/usr/bin/env python3\n'''\nSeth Hinson & Patrick McCabe\nCSCI 340 Project Two, Spring 2020\nRound Robbin Simulator\n'''\nimport sys, os, random\nfrom page import *\nfrom job import *\nfrom termcolor import colored\n\ndef printParams():\n \n print(colored('Memory Size: ' + str(sys.argv[1]), 'magenta'))\n \n print(colored('Page Size: ' + str(sys.argv[2]), 'magenta'))\n \n print(colored('Random Seed: ' + str(os.environ['RANDOM_SEED']), 'magenta'))\n \n print(colored('Number of jobs: ' + str(sys.argv[3]), 'magenta'))\n \n print(colored('Runtime (min-max) timesteps: ' + str(sys.argv[4]) + '-' + str(sys.argv[5]), 'magenta'))\n \n print(colored('Memory (min-max): ' + str(sys.argv[6]) + '-' + str(sys.argv[7]), 'magenta'))\n\ndef createJobs():\n\n numberOfJobs = int(sys.argv[3])\n \n runtimeMin = int(sys.argv[4])\n \n runtimeMax = int(sys.argv[5])\n \n memoryMin = int(sys.argv[6]) // int(sys.argv[2])\n \n memoryMax = int(sys.argv[7]) // int(sys.argv[2])\n \n jobs = []\n\n for i in range(numberOfJobs):\n\n runtime = random.randint(runtimeMin, runtimeMax) \n \n memory = random.randint(memoryMin, memoryMax) * int(sys.argv[2])\n \n jobs.append( job(i + 1, runtime, memory))\n \n print(colored('\\nJob Queue:', 'blue'))\n \n print(colored('Job #\\tRuntime\\tMemory', 'blue'))\n \n for jb in jobs:\n \n print(colored(str(jb),'blue')) \n \n return jobs\n\ndef jobsAreRunning(activeJobs):\n\n for job in activeJobs:\n \n if (job.getStatus() == 'Running' or job.getStatus() == 'Starting'):\n \n return True\n \n return False\n\ndef simulator(jobs):\n\n print(colored('\\nSimulator Starting:\\n', 'green'))\n \n numSteps = 0\n\n while (jobsAreRunning(jobs)):\n \n numSteps += 1\n \n if(numSteps == 1):\n \n for i in range(len(jobs)):\n \n print('Job ' + str(i + 1) + ' Starting')\n \n print('Job 1 Running')\n \n jobs[0].setStatus('Running')\n \n jobs[0].run()\n \n else:\n \n runningJob = numSteps % (len(jobs)) \n \n if(runningJob == 0):\n \n runningJob = len(jobs)\n\n noRun = True\n \n while(noRun):\n #print('Running Job: ' + str(runningJob)) debug for running job out of bounds\n if(jobs[runningJob - 1].isComplete()):\n \n runningJob = (runningJob + 1) % len(jobs)\n \n if(runningJob == 0):\n \n runningJob = len(jobs)\n \n else:\n\n jobs[runningJob - 1].setStatus('Running')\n\n jobs[runningJob - 1].run()\n \n print('Job ' + str(runningJob) + ' Running')\n \n if(jobs[runningJob - 1].isComplete()):\n \n print('Job ' + str(runningJob) + ' Completed')\n \n noRun = False\n'''\nTo do list:\n1. Page table output\n2. Job info @ end\n3. Make pretty \n4. Document\n5. Profit\n'''\ndef main():\n \n random.seed(os.environ['RANDOM_SEED'])\n \n if len(sys.argv) != 8:\n \n print(colored('Invalid number of arguments', 'red'))\n \n print(colored('Proper usage: ./projecttwo.py ', 'red'))\n \n else:\n \n print(colored('\\nProper number of arguments passed!\\n', 'green'))\n \n #print(colored(str(sys.argv[1]), 'green')) used for debugging sys.argv input\n \n printParams()\n \n jobQ = createJobs()\n \n simulator(jobQ)\n\n\nmain()","sub_path":"ProjectTwo/projecttwo.py","file_name":"projecttwo.py","file_ext":"py","file_size_in_byte":3937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"580995953","text":"import officeFurniture\r\nimport Desk\r\n\r\n\r\ndef main():\r\n # create a Furniture object\r\n chair = officeFurniture(\"chair\", \"leather\", \"5\", \"9\", \"12\", \"450\")\r\n # create a Desk object\r\n desk = Desk(\"cedar\", 10, 20, 15, 250, \"right\", 12)\r\n # display the chair and desk\r\n print(chair)\r\n print(desk)\r\n\r\n\r\nmain()\r\n","sub_path":"chapter 11/practice 11.1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"576625433","text":"#Dia Escolhido para Live\n\nmaior = 0\ntotal = 0\n\nsegunda = int(input(\"Informe a quantidade de votos recebidos para que a live seja transmitida às segundas-feiras? \"))\nterca = int(input(\"Informe a quantidade de votos recebidos para que a live seja transmitida às terças-feiras? \"))\nquarta = int(input(\"Informe a quantidade de votos recebidos para que a live seja transmitida às quartas-feiras? \"))\nquinta = int(input(\"Informe a quantidade de votos recebidos para que a live seja transmitida às quintas-feiras? \"))\nsexta = int(input(\"Informe a quantidade de votos recebidos para que a live seja transmitida às sextas-feiras? \"))\n\nif maior < segunda:\n maior = segunda\n dia = 'segunda'\n\nif maior < terca:\n maior = terca\n dia = 'terca'\n\nif maior < quarta:\n maior = quarta\n dia = 'quarta'\n\nif maior < quinta:\n maior = quinta\n dia = 'quinta'\n\nif maior < sexta:\n maior = sexta\n dia = 'sexta'\n\ntotal += segunda\ntotal += terca\ntotal += quarta\ntotal += quinta\ntotal += sexta\n\n\nprint(f\"O dia da semana mais votado foi {dia}-feira com {maior} votos.\")\nprint(f\"O total de votos computados foi de {total}.\")\n","sub_path":"FIAP/Fase2_cap2/RM86567_EX03.py","file_name":"RM86567_EX03.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"317143926","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Nov 13 09:16:05 2019\r\n\r\n@author: Satvik Chachra\r\n\"\"\"\r\n# =============================================================================\r\n# Programming Assignment-2: Small\r\n# Due on 2019-08-22, 23:59 IST\r\n# Given two numbers (integers) as input, print the smaller number.\r\n# \r\n# Input Format:\r\n# The first line of input contains two numbers separated by a space\r\n# \r\n# Output Format:\r\n# Print the smaller number\r\n# \r\n# Example:\r\n# \r\n# Input:\r\n# 2 3\r\n# \r\n# Output:\r\n# 2\r\n# =============================================================================\r\n\r\na,b = input().split(\" \")\r\na = int(a)\r\nb = int(b)\r\nif(a ai,bi間のへんしか存在しないことになる\n if not uf.issame(a,b):\n ans += 1\nprint(ans)","sub_path":"problems/practice/union_find/75c.py","file_name":"75c.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"592668875","text":"# 주어진 if 문을 dict를 사용하도록 수정하세요.\n\nmenu = input('메뉴: ')\n\nif menu == '오뎅':\n price = 300\nelif menu == '순대':\n price = 400\nelif menu == '만두':\n price = 500\nelse:\n price = 0\n\nprint('가격: {0}'.format(price))\n\n","sub_path":"prob09.py","file_name":"prob09.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"255151759","text":"from datetime import datetime, timezone\n\nimport hypothesis.strategies as strategies\nimport pytest\nfrom hypothesis import given\n\nfrom quart.wrappers.response import Response\n\n\n@pytest.mark.asyncio\nasync def test_response_body() -> None:\n response = Response(b'Body')\n assert b'Body' == (await response.get_data()) # type: ignore\n # Fetch again to ensure it isn't exhausted\n assert b'Body' == (await response.get_data()) # type: ignore\n\n\ndef test_response_cache_control() -> None:\n response = Response(b'Body')\n response.cache_control.max_age = 2\n assert response.headers['Cache-Control'] == 'max-age=2'\n response.cache_control.no_cache = True\n assert response.headers['Cache-Control'] == 'max-age=2,no-cache'\n\n\n@given(\n value=strategies.datetimes(\n timezones=strategies.just(timezone.utc), min_value=datetime(1900, 1, 1),\n ),\n)\n@pytest.mark.parametrize('header', ['date', 'expires', 'last_modified', 'retry_after'])\ndef test_datetime_headers(header: str, value: datetime) -> None:\n response = Response(b'Body')\n value = value.replace(microsecond=0)\n setattr(response, header, value)\n assert response.headers.get(header.title().replace('_', '-'))\n assert getattr(response, header) == value\n","sub_path":"tests/wrappers/test_response.py","file_name":"test_response.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"200531385","text":"'''Extract long-term probabilistic prediction result'''\nimport numpy as np\nnp.random.seed(1337)\nimport keras\nfrom keras.models import load_model\nimport h5py\nimport sklearn\nfrom sklearn.model_selection import train_test_split\nfrom keras.utils import np_utils\nimport pandas as pd\nimport os\nimport csv\nimport os.path\nimport math\nfrom time import *\n#from function_time_demo import *\nfrom pandas import read_csv\nfrom sklearn.preprocessing import MinMaxScaler\nimport time as tttt\nimport datetime\n#from interpolate_9_5_ccx_function import *\nimport sys\n#from micaps_function import *\nimport datetime as dt\ndef local2utc(local_st):\n\t'''convert local time to UTC'''\n\ttime_struct = tttt.mktime(local_st.timetuple())\n\tutc_st = dt.datetime.utcfromtimestamp(time_struct)\n\treturn utc_st\ndef utc2local(utc_st):\n\t'''convert UTC to local time'''\n\tnow_stamp = tttt.time()\n\tlocal_time = dt.datetime.fromtimestamp(now_stamp)\n\tutc_time = dt.datetime.utcfromtimestamp(now_stamp)\n\toffset = local_time - utc_time\n\tlocal_st = utc_st + offset\n\treturn local_st\n\n# create a log file\nname = os.path.dirname(__file__)\na = os.path.abspath(name)\nabsu = a+'/'\nfsock = open(absu+'4_10_p_error.log', 'a')\nsys.stderr = fsock\nsa = tttt.strftime(\"%Y%m%d%H%M\", tttt.localtime())\nef = open(absu+'4_10_p_error.log', 'a')\nef.write('*****************'+str(sa)+'*****************'+'\\n')\nef.close()\nstart = tttt.clock()\nsa = tttt.strftime(\"%Y%m%d%H\", tttt.localtime())\n#print('begin:',tttt.strftime(\"%Y%m%d%H\", tttt.localtime()))\nlocaltime = tttt.asctime(tttt.localtime(tttt.time()))\ntime_now = tttt.strftime(\"%Y%m%d%H%M\", tttt.localtime())\n\n# get time\ninital_time = tttt.strftime(\"%Y%m%d%H%M\", tttt.localtime())\ntoday = datetime.date.today()\nyesterday = today - datetime.timedelta(days = 1)\n#if int(inital_time[-4:]) < 420 and int(inital_time[-4:-2])%6 == 0:\n#\tqibao = str(yesterday)[:4]+str(yesterday)[5:7]+str(yesterday)[8:10]+'00'\n#elif int(inital_time[-4:]) < 1720 and int(inital_time[-4:-2])%6 == 0:\n#\tqibao = str(yesterday)[:4]+str(yesterday)[5:7]+str(yesterday)[8:10]+'12'\n#elif int(inital_time[-4:]) >= 1720 and int(inital_time[-4:-2])%6 == 0:\n#\tqibao = str(today)[:4]+str(today)[5:7]+str(today)[8:10]+'00'\n#else:\n#\tquit()\nif int(inital_time[-4:]) < 520 :\n\tqibao = str(yesterday)[:4]+str(yesterday)[5:7]+str(yesterday)[8:10]+'00'\nelif int(inital_time[-4:]) < 1720:\n\tqibao = str(yesterday)[:4]+str(yesterday)[5:7]+str(yesterday)[8:10]+'12'\nelse:\n\tqibao = str(today)[:4]+str(today)[5:7]+str(today)[8:10]+'00'\n#print('#',qibao)\n#qibao = '2018030512'\naaa = str(qibao)\nbbb = dt.datetime(int(aaa[:4]),int(aaa[4:6]), int(aaa[6:8]), int(aaa[8:10]))\ntimeaaa = utc2local(bbb)\nqibao_local = str(timeaaa)[:4]+str(timeaaa)[5:7]+str(timeaaa)[8:10]+str(timeaaa)[11:13]\n#qibao = '2017080412'#test\nte = str(inital_time)[:4]+'-'+str(inital_time)[4:6]+'-'+str(inital_time)[6:8]+\\\n'-'+str(inital_time)[8:10]\ninital_time_list = pd.date_range(te,periods = 40,freq = '6h').tolist()\n\n# create standard time series\ntime_list = []\nfor i in range(len(inital_time_list)):\n\ttime_list.append(str(inital_time_list[i])[:4]+str(inital_time_list[i])[5:7]+\\\n\tstr(inital_time_list[i])[8:10]+str(inital_time_list[i])[11:13])\n\n# read path from file\ndir_f = open(absu+'4_10_p.txt','r')\ndir_ff = dir_f.readlines()\npool_name = dir_ff[0].strip('\\n')\nover_name = dir_ff[1].strip('\\n')\nos.system('mkdir '+eval(over_name)+inital_time[:-2])\n\n# extract\ntry:\n\tfor i in range(len(time_list)):\n\t\tos.system('cp '+eval(pool_name)+qibao_local+'/'+time_list[i]+'finish.txt'+\\\n\t\t' '+eval(over_name)+inital_time[:-2]+'/')\nexcept:\n\t#print(time_list[i])\n\tpass\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\n","sub_path":"fjfog_v1.1_contain_EN_annotation/4_10_p/4_10_p.py","file_name":"4_10_p.py","file_ext":"py","file_size_in_byte":3591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"381338278","text":"import numpy as np\nimport hidden_prints\nfrom sklearn.neighbors import NearestNeighbors\nfrom tqdm import tqdm\n\n\nclass WeightedKNN:\n def __init__(self):\n pass\n\n @staticmethod\n def get_component_alphas(proj, cover, delta=0.1):\n \"\"\"Assigns image's latent space projection to cover's intervals.\n Projection is assigned to an interval if\n dist(proj, interval_midpoint) < interval_length*(1+delta)/2.\n\n :param proj: Projection of an image onto latent space's single\n component.\n :type proj: float\n :param cover: Cover of latent space's single component.\n :type cover: list\n :param delta: Parameter scaling intervals' lengths.\n :type delta: float\n\n :return: Indices of cover intervals onto which image was\n projected.\n :rtype: tuple\n \"\"\"\n\n alphas = []\n if proj < cover[0][1]:\n alphas.append(0)\n for i in range(1, len(cover)-1):\n midpoint = (cover[i][0] + cover[i][1])/2\n if abs(proj - midpoint) < abs(cover[i][1] - cover[i][0])*(1+delta)/2:\n alphas.append(i)\n if proj > cover[-1][0]:\n alphas.append(len(cover)-1)\n\n return tuple(alphas)\n \n def get_alphas(self, x, covers, latent_space):\n \"\"\"Assigns all images' latent space projections to covers'\n intervals.\n\n :param x: Images.\n :type x: numpy.ndarray\n :param covers: Covers of latent space's components.\n :type covers: list\n :param latent_space: Latent space projector.\n :type latent_space: latent_space.LatentSpace\n\n :return: Interval assignments of images' projections.\n :rtype: list\n \"\"\"\n \n with hidden_prints.HiddenPrints():\n x_latent = latent_space.transform(x)\n \n return [[self.get_component_alphas(img_latent[i], covers[i])\n for i in range(len(img_latent))] for img_latent in x_latent]\n\n @staticmethod\n def get_cover_preimages(x, covers, latent_space, n=0):\n \"\"\"Calculates cover preimages of latent space's nth component.\n\n :param x: Images.\n :type x: numpy.ndarray\n :param covers: Covers of latent space's components.\n :type covers: list\n :param latent_space: Latent space projector.\n :type latent_space: latent_space.LatentSpace\n :param n: Index of latent space's component.\n :type n: int\n\n :return preimage_ids: Ids of images split into preimages.\n :rtype preimage_ids: list\n \"\"\"\n\n n_intervals = len(covers[0])\n x_latent = latent_space.transform(x)\n preimage_ids = []\n\n for i in range(n_intervals):\n interval = covers[n][i]\n interval_ids = []\n\n for j, projection in enumerate(x_latent[:, n]):\n if projection > interval[0]:\n if projection < interval[1]:\n interval_ids.append(j)\n preimage_ids.append(interval_ids)\n\n return preimage_ids\n\n @staticmethod\n def fit_knns(x, preimages, k, n=0):\n \"\"\"Trains numerous KNN models on intervals' preimages.\n\n :param x: Images.\n :type x: numpy.ndarray\n :param preimages: Preimages of intervals covering\n latent space's nth component.\n :type preimages: list\n :param k: Number of nearest neighbours in KNN.\n :type k: int\n :param n: Index of latent space's component.\n :type n: int\n\n :return knns: KNNs trained on intervals' preimages.\n :rtype knns: dict\n \"\"\"\n\n knns = {}\n n_intervals = len(preimages)\n\n for i in range(n_intervals):\n knn = NearestNeighbors(n_neighbors=k, metric='euclidean')\n knn.fit(x[preimages[i]])\n knns.update({(n, tuple([i])): [knn, x[preimages[i]], np.array(preimages[i])]})\n if i > 0:\n knn = NearestNeighbors(n_neighbors=k, metric='euclidean')\n union = list(set(preimages[i]) | set(preimages[i-1]))\n knn.fit(x[union])\n knns.update({(n, tuple([i-1, i])): [knn, x[union], np.array(union)]})\n \n return knns\n\n @staticmethod\n def get_nearest_neighbours(x, alphas, knns, k, n=0):\n \"\"\"Calculates nearest neighbours of x's images.\n\n :param x: Images.\n :type x: numpy.ndarray\n :param alphas: Interval assignments of images' projections.\n :type alphas: list\n :param knns: Trained KNN models.\n :type knns: dict\n :param k: Number of nearest neighbours in KNN.\n :type k: int\n :param n: Index of latent space's component.\n :type n: int\n\n :return nn_ids: Ids of images' k nearest neighbours.\n :rtype nn_ids: list\n :return nn_dists: Distances of images to their k nearest\n neighbours.\n :rtype nn_dists: list\n \"\"\"\n\n nn_ids = []\n nn_dists = []\n n_images = x.shape[0]\n\n for i in tqdm(range(n_images), desc='[wknn]'):\n nn_comp_ids = []\n nn_comp_dists = []\n\n nn = knns.get((n, alphas[i][n]))\n\n if len(nn[2]) > k:\n knn = nn[0].kneighbors([x[i]])\n ids = nn[2][knn[1]]\n nn_comp_ids.append(ids.squeeze())\n nn_comp_dists.append(knn[0].squeeze())\n else:\n ids = nn[2]\n dists = np.linalg.norm(x[i] - nn[1], axis=1)\n nn_comp_ids.append(ids)\n nn_comp_dists.append(dists)\n\n nn_ids.append(nn_comp_ids)\n nn_dists.append(nn_comp_dists)\n \n return nn_ids, nn_dists\n\n @staticmethod\n def get_weighted_representation(x_binary, nn_ids, nn_dists, k, mu=1e-05):\n \"\"\"Calculates weighted KNN representations.\n\n :param x_binary: Binary representation of images on which KNNs\n were trained.\n :type x_binary: numpy.ndarray\n :param nn_ids: Ids of images' k nearest neighbours.\n :type nn_ids: list\n :param nn_dists: Distances of images to their k nearest\n neighbours.\n :type nn_dists: list\n :param k: Number of nearest neighbours in KNN.\n :type k: int\n :param mu: Parameter that ensures that there will be no\n division by 0.\n :type mu: float\n\n :return: Weighted KNN representation.\n :rtype: numpy.ndarray\n \"\"\"\n\n n_features = x_binary.shape[1]\n n_images = len(nn_ids)\n\n weighted_rep = np.zeros((n_images, n_features))\n\n for i in range(n_images):\n weights = nn_dists[i][0]\n weights = 1./(weights + mu)\n weights = np.asarray(weights / sum(weights)).reshape(1, k)\n features = weights.dot(x_binary[nn_ids[i][0], :].astype(float))\n weighted_rep[i] = features\n\n return np.asarray(weighted_rep)\n\n def fit_transform(self, k, x_test, x_train, x_train_binary, latent_space, covers):\n \"\"\"Generates a weighted KNN representation of x_test\n based on KNN models trained on x_train.\n\n :param k: Number of nearest neighbours in KNN.\n :type k: int\n :param x_test: Images without representation.\n :type x_test: numpy.ndarray\n :param x_train: Images with binary representation.\n :type x_train: numpy.ndarray\n :param x_train_binary: Binary representation of images.\n :type x_train_binary: numpy.ndarray\n :param latent_space: Latent space projector.\n :type latent_space: latent_space.LatentSpace\n :param covers: Covers of latent space's components.\n :type covers: list\n\n :return: Weighted KNN representation of x_test.\n :rtype: numpy.ndarray\n \"\"\"\n alphas = self.get_alphas(x_test, covers, latent_space)\n \n preimages = self.get_cover_preimages(x_train, covers, latent_space)\n knns = self.fit_knns(x_train, preimages, k)\n \n nn_ids, nn_dists = self.get_nearest_neighbours(x_test, alphas, knns, k)\n\n return self.get_weighted_representation(x_train_binary, nn_ids, nn_dists, k)\n","sub_path":"weighted_knn.py","file_name":"weighted_knn.py","file_ext":"py","file_size_in_byte":8176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"251331778","text":"import battlecode as bc\nimport random\nimport sys\nimport traceback\n\nimport Units.sense_util as sense_util\nimport Units.variables as variables\n\n\n#placeholder function for pathfinding algorithm\ndef try_move(gc,unit,coords,direction):\n\tif gc.is_move_ready(unit.id):\n\t\tcurrent_direction = direction\n\t\tcan_move = True\n\t\twhile not gc.can_move(unit.id, current_direction):\t\n\t\t\tcurrent_direction = current_direction.rotate_left()\n\t\t\tif current_direction == direction:\n\t\t\t\t# has tried every direction, cannot move\n\t\t\t\tcan_move = False\n\t\t\t\tbreak\n\t\tif can_move:\t\n\t\t\tgc.move_robot(unit.id, current_direction)\n\t\t\tadd_new_location(unit.id, coords, current_direction)\n\ndef add_new_location(unit_id, old_coords, direction):\n\tif variables.curr_planet == bc.Planet.Earth: \n\t\tquadrant_size = variables.earth_quadrant_size\n\telse:\n\t\tquadrant_size = variables.mars_quadrant_size\n\n\tunit_mov = variables.direction_to_coord[direction]\n\tnew_coords = (old_coords[0]+unit_mov[0], old_coords[1]+unit_mov[1])\n\tvariables.unit_locations[unit_id] = new_coords\n\n\told_quadrant = (int(old_coords[0] / quadrant_size), int(old_coords[1] / quadrant_size))\n\tnew_quadrant = (int(new_coords[0] / quadrant_size), int(new_coords[1] / quadrant_size))\n\n\tif old_quadrant != new_quadrant: \n\t\tvariables.quadrant_battle_locs[old_quadrant].remove_ally(unit_id)\n\t\tvariables.quadrant_battle_locs[new_quadrant].add_ally(unit_id, \"worker\")\n\ndef optimal_direction_towards(gc, unit, location, target, directions):\n\t# return the optimal direction towards a target that is achievable; not A*, but faster.\n\tshape = [target.x - location.x, target.y - location.y]\n\toptions = sense_util.get_best_option(shape)\n\tfor option in options:\n\t\tif gc.can_move(unit.id, option):\n\t\t\treturn option\n\treturn directions[8]\n\n","sub_path":"tricycle_bot_9_night_before/Units/movement.py","file_name":"movement.py","file_ext":"py","file_size_in_byte":1745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"476683910","text":"import itertools\nimport json\nfrom random import choice, randint, shuffle\nfrom threading import Thread\nfrom time import sleep, time\n\nimport requests\nimport urllib3\nfrom couchbase import experimental, subdocument\nfrom couchbase.bucket import Bucket\nfrom couchbase.exceptions import (\n ConnectError,\n CouchbaseError,\n HTTPError,\n KeyExistsError,\n NotFoundError,\n TemporaryFailError,\n TimeoutError,\n)\nfrom decorator import decorator\nfrom txcouchbase.connection import Connection as TxConnection\n\nfrom logger import logger\n\nexperimental.enable()\n\n\n@decorator\ndef quiet(method, *args, **kwargs):\n try:\n return method(*args, **kwargs)\n except (ConnectError, CouchbaseError, HTTPError, KeyExistsError,\n NotFoundError, TimeoutError) as e:\n logger.warn('{}, error: {}, args: {}'.format(method, e, args))\n\n\n@decorator\ndef backoff(method, *args, **kwargs):\n while True:\n try:\n return method(*args, **kwargs)\n except TemporaryFailError:\n sleep(1)\n\n\n@decorator\ndef timeit(method, *args, **kwargs) -> int:\n t0 = time()\n method(*args, **kwargs)\n return time() - t0\n\n\nclass CBAsyncGen:\n\n TIMEOUT = 60 # seconds\n\n def __init__(self, use_ssl=False, **kwargs):\n self.client = TxConnection(quiet=True, **kwargs)\n self.client.timeout = self.TIMEOUT\n\n def create(self, key: str, doc: dict):\n return self.client.set(key, doc)\n\n def read(self, key: str):\n return self.client.get(key)\n\n def update(self, key: str, doc: dict):\n return self.client.set(key, doc)\n\n def delete(self, key: str):\n return self.client.delete(key)\n\n\nclass CBGen(CBAsyncGen):\n\n NODES_UPDATE_INTERVAL = 15\n\n TIMEOUT = 10 # seconds\n\n def __init__(self, use_ssl=False, **kwargs):\n connection_string = 'couchbase://{}/{}?password={}'\n\n if use_ssl:\n connection_string = connection_string.replace('couchbase',\n 'couchbases')\n connection_string += '&certpath=root.pem'\n\n connection_string = connection_string.format(kwargs['host'],\n kwargs['bucket'],\n kwargs['password'])\n\n self.client = Bucket(connection_string=connection_string)\n self.client.timeout = self.TIMEOUT\n\n self.session = requests.Session()\n self.session.auth = (kwargs['username'], kwargs['password'])\n self.server_nodes = ['{}:{}'.format(kwargs['host'],\n kwargs.get('port', 8091))]\n self.nodes_url = 'http://{}:{}/pools/default/buckets/{}/nodes'.format(\n kwargs['host'],\n kwargs.get('port', 8091),\n kwargs['bucket'],\n )\n\n def start_updater(self):\n self.t = Thread(target=self._get_list_of_servers)\n self.t.daemon = True\n self.t.start()\n\n def _get_list_of_servers(self):\n while True:\n try:\n nodes = self.session.get(self.nodes_url).json()\n except Exception as e:\n logger.warn('Failed to get list of servers: {}'.format(e))\n continue\n self.server_nodes = [n['hostname'] for n in nodes['servers']]\n sleep(self.NODES_UPDATE_INTERVAL)\n\n @quiet\n @backoff\n def create(self, *args, **kwargs):\n super().create(*args, **kwargs)\n\n @quiet\n @timeit\n def read(self, *args, **kwargs):\n super().read(*args, **kwargs)\n\n @quiet\n @backoff\n @timeit\n def update(self, *args, **kwargs):\n super().update(*args, **kwargs)\n\n @quiet\n def delete(self, *args, **kwargs):\n super().delete(*args, **kwargs)\n\n @timeit\n def view_query(self, ddoc, view, query):\n node = choice(self.server_nodes).replace('8091', '8092')\n url = 'http://{}/{}/_design/{}/_view/{}?{}'.format(\n node, self.client.bucket, ddoc, view, query.encoded\n )\n self.session.get(url=url)\n\n @quiet\n @timeit\n def n1ql_query(self, query):\n tuple(self.client.n1ql_query(query))\n\n\nclass SubDocGen(CBGen):\n\n @quiet\n @timeit\n def read(self, key: str, field: str):\n self.client.lookup_in(key, subdocument.get(path=field))\n\n @quiet\n @timeit\n def update(self, key: str, field: str, doc: dict):\n new_field_value = doc[field]\n self.client.mutate_in(key, subdocument.upsert(path=field,\n value=new_field_value))\n\n @quiet\n @timeit\n def read_xattr(self, key: str, field: str):\n self.client.lookup_in(key, subdocument.get(path=field,\n xattr=True))\n\n @quiet\n @timeit\n def update_xattr(self, key: str, field: str, doc: dict):\n self.client.mutate_in(key, subdocument.upsert(path=field,\n value=doc,\n xattr=True,\n create_parents=True))\n\n\nclass FtsGen(CBGen):\n\n QUERY_TEMPLATE = {\"ctl\": {\"timeout\": 0}, \"query\": {}, \"size\": 10}\n\n def __init__(self, master_node, settings, auth=None):\n\n self.master_node = master_node\n self.query_port = settings.port\n self.auth = auth\n self.requests = requests.Session()\n self.http_pool = self.new_http_pool()\n\n self.settings = settings\n self.query_nodes = self.get_nodes()\n self.nodes_list_size = len(self.query_nodes)\n self.query_list = []\n self.header = {'Content-Type': 'application/json'}\n self.bool_map = {'conjuncts': 'must', 'disjuncts': 'should'}\n self.query_list_size = 0\n\n self.prepare_query_list()\n\n def new_http_pool(self):\n basic_auth = '{}:{}'.format(self.auth.username, self.auth.password)\n headers = urllib3.make_headers(keep_alive=True, basic_auth=basic_auth)\n headers.update({'Content-Type': 'application/json'})\n\n return urllib3.PoolManager(headers=headers)\n\n @property\n def query_template(self):\n return self.QUERY_TEMPLATE\n\n def get_nodes(self):\n nodes = []\n cluster_map = requests.get(url='http://{}:8091/pools/default'.format(self.master_node),\n auth=self.auth).json()\n for node in cluster_map['nodes']:\n if 'fts' in node['services']:\n url = node['hostname'].split(\":\")[0]\n nodes.append(url)\n return nodes\n\n def form_url(self, full_query):\n url = \"http://{}:{}/api/index/{}/query\".format(self.next_node(),\n self.query_port,\n self.settings.name)\n return {'url': url,\n 'auth': self.auth,\n 'headers': self.header,\n 'data': json.dumps(full_query)\n }\n\n @staticmethod\n def process_lines(line):\n if len(line) == 0:\n raise Exception('Empty line')\n value = line.strip().split()\n if len(value) == 2:\n return line.strip().split()\n else:\n return line.strip(), None\n\n @staticmethod\n def process_conj_disj(ttypes):\n index = 0\n keytypes = []\n while index < len(ttypes):\n count = int(ttypes[index])\n keytypes += count * [ttypes[index + 1]]\n index += 2\n return itertools.cycle(keytypes)\n\n def prepare_query_list(self):\n if self.settings.query_file:\n with open(self.settings.query_file, 'r') as tfile:\n for line in tfile:\n temp_query = {}\n tosearch, freq = FtsGen.process_lines(line.strip())\n query_type = self.settings.type\n if query_type in ['2_conjuncts', '2_disjuncts', '1_conjuncts_2_disjuncts']:\n from collections import defaultdict\n keytypes = FtsGen.process_conj_disj(query_type.split('_'))\n temp_query = defaultdict(list)\n tbool = {v: {k: None} for k, v in self.bool_map.items()}\n\n for terms in line.split():\n\n tmp_key = next(keytypes)\n temp_query[tmp_key].append({\"field\": self.settings.field,\n \"term\": terms})\n\n if query_type == '1_conjuncts_2_disjuncts':\n for k, v in self.bool_map.items():\n tbool[v][k] = temp_query[k]\n temp_query = tbool\n\n elif query_type == 'fuzzy':\n temp_query['fuzziness'] = int(freq)\n temp_query['term'] = tosearch\n temp_query['field'] = self.settings.field\n\n elif query_type == 'numeric':\n if freq.strip() == 'max_min':\n temp_query['max'], temp_query['min'] = \\\n [float(k) for k in tosearch.split(':')]\n elif freq.strip() == 'max':\n temp_query['max'] = float(tosearch)\n else:\n temp_query['min'] = float(tosearch)\n temp_query['inclusive_max'] = False\n temp_query['inclusive_min'] = False\n temp_query['field'] = self.settings.field\n\n elif query_type in ['match', 'match_phrase']:\n tosearch = line.strip()\n temp_query[query_type] = tosearch\n temp_query['field'] = self.settings.field\n\n elif query_type == 'ids':\n tosearch = [tosearch]\n temp_query[query_type] = tosearch\n temp_query['field'] = self.settings.field\n\n elif query_type == \"facet\":\n\n start_date, end_date = freq.split(':')\n temp_query[\"query\"] = \"text:{}\".format(tosearch)\n temp_query[\"boost\"] = 1\n self.query_template['fields'] = [\"*\"]\n self.query_template[\"facets\"] = {self.settings.field:\n {\"size\": self.settings.query_size,\n \"field\": self.settings.field,\n \"date_ranges\": [{\"name\": \"end\",\n \"end\": end_date},\n {\"name\": \"start\",\n \"start\": start_date}]}}\n else:\n temp_query[query_type] = tosearch\n temp_query['field'] = self.settings.field\n\n self.query_template['query'] = temp_query\n self.query_template['size'] = self.settings.query_size\n self.query_list.append(self.form_url(self.query_template))\n\n self.query_list_size = len(self.query_list)\n shuffle(self.query_list)\n\n def next(self):\n return self.requests.post, self.query_list[randint(0, self.query_list_size - 1)]\n\n def next_node(self):\n return self.query_nodes[randint(0, self.nodes_list_size - 1)]\n\n def execute_query(self, query):\n return self.http_pool.request('POST', query['url'], body=query['data'])\n\n\nclass ElasticGen(FtsGen):\n\n QUERY_TEMPLATE = {\"query\": {}, \"size\": 10}\n\n def form_url(self, full_query):\n url = \"http://{}:9200/{}/_search\".format(self.next_node(), self.settings.name)\n return {'url': url,\n 'auth': None,\n 'headers': self.header,\n 'data': json.dumps(full_query)\n }\n\n def get_nodes(self):\n nodes = []\n cluster_map = requests.get(url='http://{}:9200/_nodes'.format(self.master_node)).json()\n for node in cluster_map['nodes'].values():\n url = node[\"ip\"]\n nodes.append(url)\n return nodes\n\n def prepare_query_list(self):\n if self.settings.query_file:\n with open(self.settings.query_file, 'r') as tfile:\n for line in tfile:\n term, freq = ElasticGen.process_lines(line.strip())\n tmp_query = {}\n tmp_query_txt = {}\n query_type = self.settings.type\n if query_type == 'fuzzy':\n tmp_fuzzy = {\n 'fuzziness': int(freq),\n 'value': term,\n }\n tmp_query_txt[self.settings.field] = tmp_fuzzy\n tmp_query[query_type] = tmp_query_txt\n\n elif query_type == 'ids':\n tmp_query_txt['values'] = [term]\n tmp_query[query_type] = tmp_query_txt\n\n elif query_type in ['match', 'match_phrase']:\n tmp_query_txt[self.settings.field] = line.strip()\n tmp_query[query_type] = tmp_query_txt\n\n elif query_type == 'range':\n trange = {}\n if freq.strip() == 'max_min':\n trange['gte'], trange['lte'] = [float(k) for k in term.split(':')]\n elif freq.strip() == 'max':\n trange['gte'] = float(term)\n else:\n trange['lte'] = float(term)\n tmp_query_txt[self.settings.field] = trange\n tmp_query[query_type] = tmp_query_txt\n\n elif query_type in ['2_conjuncts', '2_disjuncts', '1_conjuncts_2_disjuncts']:\n tbool = {v: [] for k, v in self.bool_map.items()}\n keytypes = ElasticGen.process_conj_disj(query_type.split('_'))\n for term in line.strip().split():\n key = self.bool_map[next(keytypes)]\n tbool[key].append({'term': {self.settings.field: term}})\n tmp_query_txt = tbool\n tmp_query['bool'] = tmp_query_txt\n\n elif query_type == 'facet':\n start_date, end_date = freq.split(':')\n tmp_query = {\"term\": {\"text\": term}}\n self.query_template['size'] = self.settings.query_size\n self.query_template['aggs'] = {\n \"perf_elastic_index\": {\n \"date_range\": {\n \"field\": self.settings.field,\n \"format\": \"YYYY-MM-DD\",\n \"ranges\": [\n {\n \"from\": start_date,\n \"to\": end_date,\n },\n ]\n },\n \"aggs\": {\n \"terms_count\": {\"terms\": {\"field\": \"text\"}},\n },\n },\n }\n\n else:\n tmp_query_txt[self.settings.field] = term\n tmp_query[query_type] = tmp_query_txt\n\n self.query_template['query'] = tmp_query\n self.query_list.append(self.form_url(self.query_template))\n self.query_list_size = len(self.query_list)\n shuffle(self.query_list)\n","sub_path":"spring/cbgen.py","file_name":"cbgen.py","file_ext":"py","file_size_in_byte":16144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"408651451","text":"from tensorflow.keras.applications.resnet50 import ResNet50\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Dense, GlobalAveragePooling2D\nimport tensorflow as tf\nfrom tensorflow.python.keras import Sequential\nfrom tensorflow.python.keras.layers import BatchNormalization, Conv2D, MaxPooling2D, Flatten, Dropout\n\nfrom misc import get_optimiser\nfrom photo_models.model_args import ModelArgs\nfrom photo_models.model_misc import model_fit\n\n\ndef alexnet(model_args: ModelArgs, verbose=False):\n\n model = Sequential([\n # 1st Convolutional Layer\n Conv2D(filters=96, input_shape=model_args.input_shape, kernel_size=(11, 11), strides=(4, 4),\n padding='valid', activation='relu', name='conv_1'),\n # Max Pooling\n MaxPooling2D(pool_size=(2, 2), strides=(2, 2), padding='valid', name='pooling_1'),\n # 2nd Convolutional Layer\n Conv2D(filters=256, kernel_size=(11, 11), strides=(1, 1), padding='valid', activation='relu', name='conv_2'),\n # Max Pooling\n MaxPooling2D(pool_size=(2, 2), strides=(2, 2), padding='valid', name='pooling_2'),\n # 3rd Convolutional Layer\n Conv2D(filters=384, kernel_size=(3, 3), strides=(1, 1), padding='valid', activation='relu', name='conv_3'),\n # 4th Convolutional Layer\n Conv2D(filters=384, kernel_size=(3, 3), strides=(1, 1), padding='valid', activation='relu', name='conv_4'),\n # 5th Convolutional Layer\n Conv2D(filters=256, kernel_size=(3, 3), strides=(1, 1), padding='valid', activation='relu', name='conv_5'),\n # Max Pooling\n MaxPooling2D(pool_size=(2, 2), strides=(2, 2), padding='valid', name='pooling_3'),\n # Fully Connected layer\n Flatten(name='flatten_1'),\n # 1st Fully Connected Layer\n Dense(4096, input_shape=(model_args.input_shape[0]*model_args.input_shape[1]*model_args.input_shape[2],),\n activation='relu', name='fully_connected_1'),\n # Add Dropout to prevent overfitting\n Dropout(0.4, name='dropout_1'),\n # 2nd Fully Connected Layer\n Dense(4096, activation='relu', name='fully_connected_2'),\n # Add Dropout\n Dropout(0.4, name='dropout_2'),\n # 3rd Fully Connected Layer\n Dense(1000, activation='relu', name='fully_connected_3'),\n # Add Dropout\n Dropout(0.4, name='dropout_3'),\n # Output Layer\n Dense(model_args.class_count, activation='softmax', name='output')\n ])\n\n with tf.device(model_args.device_name):\n print(f\"Using '{model_args.device_name}'\")\n\n # training run 1\n # compile the model (should be done *after* setting layers to non-trainable)\n model.compile(optimizer=get_optimiser(model_args.misc_args['run1_optimizer']),\n loss='categorical_crossentropy',\n metrics=['accuracy'])\n\n return model_fit(model, model_args, verbose=verbose)\n","sub_path":"photo_models/alexnet.py","file_name":"alexnet.py","file_ext":"py","file_size_in_byte":2933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"589434767","text":"class BinarySearchTree:\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n\n # Insert the given value into the tree\n def insert(self, value):\n\n if value < self.value:\n if self.left == None:\n node = BinarySearchTree(value)\n self.left = node\n else:\n self.left.insert(value)\n elif value >= self.value:\n if self.right == None:\n node = BinarySearchTree(value)\n self.right = node\n else:\n self.right.insert(value)\n\n\n # Return True if the tree contains the value\n # False if it does not\n # def contains(self, target):\n # if self.value == target:\n # return True\n # # if right is there\n # elif self.left:\n # return self.left.contains(target)\n # # if left is there\n # elif self.right:\n # return self.right.contains(target)\n # else:\n # return False\n\n ## not sure why the above code doesnt work, but this was my first pass solution the other day and it works for some reason. Dont care I got mvp\n\n def contains(self, target):\n if target == self.value:\n return True\n if target < self.value:\n if not self.left:\n return False\n else:\n return self.left.contains(target)\n elif target > self.value: \n if not self.right:\n return False \n else:\n return self.right.contains(target)\n\n\n\n\n","sub_path":"names/binary.py","file_name":"binary.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"3846197","text":"#Kai Bernardini\n#kaidb@bu.edu\n\n\ndef dec_to_bin(n):\n \"\"\" converts a decimal to a binary number\n \"\"\"\n if n == 0:\n return '0'\n if n == 1:\n return '1'\n else:\n if n % 2 == 0:\n return dec_to_bin(n // 2) + '0'\n if n % 2 != 0:\n return dec_to_bin(n//2) + '1'\n\ndef bin_to_dec(s):\n \"\"\"converts a binary number to a decimal number\n \"\"\"\n if s == '0':\n return 0\n if s == '1':\n return 1\n else:\n if s[-1] == '1':\n return 2* bin_to_dec(s[0:-1]) + 1\n if s[-1] == '0':\n return 2* bin_to_dec(s[0:-1]) + 0\n\ndef increment(s):\n answer = dec_to_bin(bin_to_dec(s) + 1)\n if len(answer) == 8:\n return answer\n if len(answer) > 8:\n return answer[len(answer) - 8:]\n if len(answer) < 8:\n return ((8- len(answer)) * '0') + answer\n\ndef count(s, n):\n if n == 0:\n return\n else:\n print(s)\n return count(increment(s), n-1)\n","sub_path":"HW 4/ps4pr1.py","file_name":"ps4pr1.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"23582443","text":"import time\r\n\r\nimport numpy as np\r\nimport tensorflow as tf\r\n\r\nimport tflib as lib\r\nimport tflib.ops.linear\r\nimport tflib.ops.conv2d\r\nimport tflib.ops.batchnorm\r\nimport tflib.ops.deconv2d\r\nimport xplot\r\nimport datetime\r\nimport os\r\nimport random\r\nimport shutil\r\nimport copy\r\nimport collections\r\nfrom defaultlist import defaultlist\r\n\r\nimport utils\r\n\r\nfrom mpi4py import MPI\r\n\r\nimport matplotlib.pyplot as plt\r\nfrom scipy.misc import imsave\r\n\r\nimport _selector as box_selector\r\n\r\n\r\ndef Batchnorm(name, axes, inputs, is_train=tf.Variable(True, trainable=False),\r\n decay=0.9, epsilon=0.00001, act=tf.identity): # NCHW format\r\n\tif ((axes == [0, 2, 3]) or (axes == [0, 1, 2])):\r\n\t\tif axes == [0, 1, 2]: # NHW\r\n\t\t\tinputs = tf.expand_dims(inputs, 1)\r\n\t\t# axes = [0,2,3]\r\n\t\t# Old (working but pretty slow) implementation:\r\n\t\t##########\r\n\r\n\t\t# inputs = tf.transpose(inputs, [0,2,3,1])\r\n\r\n\t\t# mean, var = tf.nn.moments(inputs, [0,1,2], keep_dims=False)\r\n\t\t# offset = lib.param(name+'.offset', np.zeros(mean.get_shape()[-1], dtype='float32'))\r\n\t\t# scale = lib.param(name+'.scale', np.ones(var.get_shape()[-1], dtype='float32'))\r\n\t\t# result = tf.nn.batch_normalization(inputs, mean, var, offset, scale, 1e-4)\r\n\r\n\t\t# return tf.transpose(result, [0,3,1,2])\r\n\r\n\t\t# New (super fast but untested) implementation:\r\n\t\tinputs = tf.transpose(inputs, [0, 2, 3, 1]) # NCHW -> NHWC\r\n\r\n\tx_shape = inputs.get_shape()\r\n\tparams_shape = x_shape[-1:]\r\n\r\n\tfrom tensorflow.python.training import moving_averages\r\n\tfrom tensorflow.python.ops import control_flow_ops\r\n\r\n\twith tf.variable_scope(name) as vs:\r\n\t\taxis = list(range(len(x_shape) - 1))\r\n\r\n\t\t## 2.\r\n\t\t# if tf.__version__ > '0.12.1':\r\n\t\t#\t moving_mean_init = tf.zeros_initializer()\r\n\t\t# else:\r\n\t\t#\t moving_mean_init = tf.zeros_initializer\r\n\r\n\t\toffset = lib.param(name + '.offset', np.zeros(params_shape, dtype='float32'))\r\n\t\tscale = lib.param(name + '.scale', tf.random_normal(params_shape, mean=1.0, stddev=0.002))\r\n\r\n\t\tmoving_mean = lib.param(name + '.moving_mean', np.zeros(params_shape, dtype='float32'), trainable=False)\r\n\t\tmoving_variance = lib.param(name + '.moving_variance', np.ones(params_shape, dtype='float32'), trainable=False)\r\n\r\n\t\t## 3.\r\n\t\t# These ops will only be preformed when training.\r\n\t\tmean, variance = tf.nn.moments(inputs, axis)\r\n\r\n\t\tdef mean_var_with_update():\r\n\t\t\ttry: # TF12\r\n\t\t\t\tupdate_moving_mean = moving_averages.assign_moving_average(\r\n\t\t\t\t\tmoving_mean, mean, decay, zero_debias=False) # if zero_debias=True, has bias\r\n\t\t\t\tupdate_moving_variance = moving_averages.assign_moving_average(\r\n\t\t\t\t\tmoving_variance, variance, decay, zero_debias=False) # if zero_debias=True, has bias\r\n\t\t\t# print(\"TF12 moving\")\r\n\t\t\texcept Exception as e: # TF11\r\n\t\t\t\tupdate_moving_mean = moving_averages.assign_moving_average(\r\n\t\t\t\t\tmoving_mean, mean, decay)\r\n\t\t\t\tupdate_moving_variance = moving_averages.assign_moving_average(\r\n\t\t\t\t\tmoving_variance, variance, decay)\r\n\t\t\t# print(\"TF11 moving\")\r\n\t\t\twith tf.control_dependencies([update_moving_mean, update_moving_variance]):\r\n\t\t\t\treturn tf.identity(mean), tf.identity(variance)\r\n\r\n\t\tm, v = tf.cond(is_train, mean_var_with_update, lambda: (moving_mean, moving_variance))\r\n\t\tresult = act(tf.nn.batch_normalization(inputs, m, v, offset, scale, epsilon))\r\n\r\n\t\tif ((axes == [0, 2, 3]) or (axes == [0, 1, 2])):\r\n\t\t\tresult = tf.transpose(result, [0, 3, 1, 2]) # NHWC -> NCHW\r\n\r\n\t\treturn result\r\n\r\n\r\ndef Scaling(input, factor):\r\n\tinput = tf.keras.backend.resize_images(input, factor, factor, \"channels_first\")\r\n\treturn input\r\n\r\n\r\nclass Mask1:\r\n\r\n\tdef __init__(self, config):\r\n\r\n\t\tself.global_config = config\r\n\t\tself.config = config.get_section('mask1')\r\n\r\n\t\t# --------------\r\n\r\n\t\tself.step = 0\r\n\r\n\t\tself.load_path = self.config['load_path']\r\n\t\tself.log_time = self.config['log_every_n_steps']\r\n\t\tself.test_time = self.config['test_steps']\r\n\t\tself.summary_time = self.config['summary_every_n_steps']\r\n\t\tself.Isloadcheckpoint = self.config['isloadcheckpoint']\r\n\r\n\t\tself.path = self.global_config.get_value('cvmodel', 'path')\r\n\r\n\t\t# --------------\r\n\r\n\t\tself.lr = self.config['lr']\r\n\t\tself.beta1 = self.config['beta1']\r\n\t\tself.beta2 = self.config['beta2']\r\n\t\tself.lr_a = self.config['lr_a']\r\n\t\tself.beta1_a = self.config['beta1_a']\r\n\t\tself.beta2_a = self.config['beta2_a']\r\n\t\tself.lambda_STN_pixel = self.config['lambda_stn_pixel']\r\n\t\tself.lambda_STN_mask = self.config['lambda_stn_mask']\r\n\t\tself.lambda_Connect = self.config['lambda_connect']\r\n\t\tself.show_lambda_STN_pixel = self.config['show_lambda_stn_pixel']\r\n\t\tself.show_lambda_STN_mask = self.config['show_lambda_stn_mask']\r\n\t\tself.show_lambda_Connect = self.config['show_lambda_connect']\r\n\t\tself.num_box = self.config['num_box']\r\n\t\tself.mask_threshold = self.config['mask_threshold']\r\n\t\tself.CV_BATCH_SIZE = self.config['cv_batch_size']\r\n\t\tself.shuffle_times = self.config['shuffle_times']\r\n\t\tself.pad_b_width = self.config['pad_b_width']\r\n\r\n\t\t# --------------\r\n\r\n\t\tself.BATCH_SIZE = self.global_config.get_value('cvmodel', 'batch_size')\r\n\t\tself.HEIGHT = self.global_config.get_value('cvmodel', 'height')\r\n\t\tself.WIDTH = self.global_config.get_value('cvmodel', 'width')\r\n\t\tself.CHANNELS = self.global_config.get_value('cvmodel', 'channels')\r\n\t\tself.MASK_CHANNELS = self.global_config.get_value('cvmodel', 'mask_channels')\r\n\t\tself.B_HEIGHT = self.global_config.get_value('cvmodel', 'b_height')\r\n\t\tself.B_WIDTH = self.global_config.get_value('cvmodel', 'b_width')\r\n\t\tself.old_B_WIDTH = self.global_config.get_value('cvmodel', 'old_b_width')\r\n\t\tself.box_num_cover = self.global_config.get_value('cvmodel', 'box_num_cover')\r\n\t\tself.warning_path = self.global_config.get_value('cvmodel', 'warning_path')\r\n\r\n\t\t# --------------\r\n\r\n\t\tself.dynamic_object_instance_box_maxnum = \\\r\n\t\t\tself.global_config.get_value('cvmodel', 'dynamic_object_instance_box_maxnum')\r\n\t\tself.dynamic_object_class_maxnum = \\\r\n\t\t\tself.global_config.get_value('cvmodel', 'dynamic_object_class_maxnum')\r\n\t\tself.dynamic_object_instance_maxnum = \\\r\n\t\t\tself.global_config.get_value('cvmodel', 'dynamic_object_instance_maxnum')\r\n\r\n\t\t# --------------\r\n\r\n\t\tself.used_gpu = self.config['used_gpu']\r\n\t\tself.devices = ['gpu:%d' % i for i in range(self.used_gpu)]\r\n\t\tself.shared_device = self.devices[0]\r\n\t\tself.gpu_batch_size = self.CV_BATCH_SIZE // self.used_gpu\r\n\r\n\t\tassert (self.CV_BATCH_SIZE % self.used_gpu == 0)\r\n\r\n\t\t# --------------\r\n\r\n\t\tself.my_seed = self.global_config.get_value('main', 'mpi_seed')\r\n\t\tself.num_gpus = self.global_config.get_value('main', 'num_gpus')\r\n\r\n\t\tassert (self.used_gpu <= self.num_gpus)\r\n\r\n\t\t# --------------\r\n\r\n\t\tself.box_selector = box_selector.Selector(\r\n\t\t\tshape=(self.old_B_WIDTH, self.B_HEIGHT),\r\n\t\t\tI_channels=self.CHANNELS,\r\n\t\t\tM_classes=self.dynamic_object_class_maxnum,\r\n\t\t\tmask_threshold=self.mask_threshold\r\n\t\t)\r\n\r\n\t\t# --------------\r\n\r\n\t\t# MPI\r\n\t\tself.comm = MPI.COMM_WORLD\r\n\r\n\t\tself.mpi_rank = self.comm.Get_rank()\r\n\t\tself.mpi_size = self.comm.Get_size()\r\n\r\n\t\t# --------------\r\n\r\n\t\tself.selection_booster_num = self.config['selection_booster_num']\r\n\t\tself.s_mpi_size = min(self.mpi_size, self.selection_booster_num)\r\n\t\tself.cpu_batch_size = self.BATCH_SIZE // self.s_mpi_size\r\n\r\n\t\tassert (self.BATCH_SIZE % self.s_mpi_size == 0)\r\n\r\n\t\t# --------------\r\n\r\n\r\n\t\tif (self.mpi_rank == 0):\r\n\r\n\t\t\tself.graph = tf.Graph()\r\n\t\t\twith self.graph.as_default():\r\n\r\n\t\t\t\ttf.set_random_seed(self.my_seed)\r\n\t\t\t\tself.create_network()\r\n\r\n\t\t\t\tconfig = tf.ConfigProto(allow_soft_placement = True)\r\n\t\t\t\tconfig.gpu_options.allow_growth = True\r\n\r\n\t\t\t\tself.sess = tf.Session(config=config)\r\n\t\t\t\tself.sess.run(tf.global_variables_initializer())\r\n\r\n\t\t\t\tself.saver = tf.train.Saver()\r\n\r\n\t\t\t\tif self.Isloadcheckpoint:\r\n\t\t\t\t\tcheckpoint = tf.train.get_checkpoint_state(self.load_path)\r\n\t\t\t\t\tprint('------------------')\r\n\t\t\t\t\tprint('mpi_rank: ', self.mpi_rank)\r\n\t\t\t\t\tif checkpoint and checkpoint.model_checkpoint_path:\r\n\t\t\t\t\t\tprint('Mask1 load_path: ', checkpoint.model_checkpoint_path)\r\n\t\t\t\t\t\tself.saver.restore(self.sess, checkpoint.model_checkpoint_path)\r\n\t\t\t\t\t\tprint(\"Mask1 successfully loaded: \", checkpoint.model_checkpoint_path)\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tprint(\"Could not find old mask1 network weights\")\r\n\t\t\t\t\tprint('------------------')\r\n\r\n\t\t\t\tif tf.gfile.Exists(self.path + 'summary_mask1_train/'):\r\n\t\t\t\t\ttf.gfile.DeleteRecursively(self.path + 'summary_mask1_train/')\r\n\t\t\t\tif tf.gfile.Exists(self.path + 'summary_mask1_test/'):\r\n\t\t\t\t\ttf.gfile.DeleteRecursively(self.path + 'summary_mask1_test/')\r\n\t\t\t\tself.train_writer = tf.summary.FileWriter(self.path + 'summary_mask1_train/', graph=self.sess.graph)\r\n\t\t\t\tself.test_writer = tf.summary.FileWriter(self.path + 'summary_mask1_test/', graph=self.sess.graph)\r\n\r\n\tdef newsinglePerception(self, I, name, inchannel=3, is_train=None):\r\n\r\n\t\t# similar to the paper learn object from pixels\r\n\t\tX1 = lib.ops.conv2d.Conv2D('AttentionNet' + name + '.1', inchannel, 32, 5, I, stride=2)\r\n\t\tX1 = Batchnorm('AttentionNet' + name + '.BN1', [0, 2, 3], X1, is_train)\r\n\t\tX1 = tf.nn.relu(X1)\r\n\t\tX2 = lib.ops.conv2d.Conv2D('AttentionNet' + name + '.2', 32, 32, 3, X1, stride=2)\r\n\t\tX2 = Batchnorm('AttentionNet' + name + '.BN2', [0, 2, 3], X2, is_train)\r\n\t\tX2 = tf.nn.relu(X2)\r\n\t\tX3 = lib.ops.conv2d.Conv2D('AttentionNet' + name + '.3', 32, 32, 3, X2, stride=1)\r\n\t\tX3 = Batchnorm('AttentionNet' + name + '.BN3', [0, 2, 3], X3, is_train)\r\n\t\tX3 = tf.nn.relu(X3)\r\n\t\t# X4=multiF\r\n\t\tmultiF = tf.concat([I, Scaling(X1, 2), Scaling(X2, 4), Scaling(X3, 4)], 1)\r\n\r\n\t\tX4 = lib.ops.conv2d.Conv2D('AttentionNet' + name + '.4', inchannel + 32 + 32 + 32, 16, 1, multiF, stride=1)\r\n\t\tX4 = Batchnorm('AttentionNet' + name + '.BN4', [0, 2, 3], X4, is_train)\r\n\t\tX4 = tf.nn.relu(X4)\r\n\t\tX5 = lib.ops.conv2d.Conv2D('AttentionNet' + name + '.5', 16, 1, 3, X4, stride=1)\r\n\t\tX5 = Batchnorm('AttentionNet' + name + '.BN5', [0, 2, 3], X5, is_train)\r\n\t\toutput = X5\r\n\t\treturn output\r\n\r\n\tdef Mask_AttentionNet(self, I, Mask, inchannel=3, inheight=80, inwidth=80, object_maxnum=6, is_train=None,\r\n\t batch_size=16):\r\n\r\n\t\t# Mask: [batch_size * 2, height, width]\r\n\t\t# I: [batch_size * 2, channel, height, width]\r\n\t\t# M: [batch_size * 2, object_maxnum, height, width]\r\n\r\n\t\tMask = tf.expand_dims(Mask, 1)\r\n\r\n\t\t# trick, could use I instead of I * Mask\r\n\t\tM = self.newsinglePerception(I * Mask, 'mask_o0', inchannel, is_train)\r\n\r\n\t\tfor i in range(1, object_maxnum):\r\n\t\t\tM = tf.concat([M, self.newsinglePerception(I * Mask, 'mask_o' + str(i), inchannel, is_train)], 1)\r\n\r\n\t\tM = tf.nn.softmax(M, 1) * Mask\r\n\r\n\t\tEntropyLoss = -tf.reduce_mean(\r\n\t\t\ttf.reduce_sum(M[: batch_size, :, :, :] * tf.log(tf.clip_by_value(M[: batch_size, :, :, :], 1e-10, 1.0)),\r\n\t\t\t axis=1))\r\n\r\n\t\treturn I, Mask, M, EntropyLoss\r\n\r\n\tdef AgentCoordinates(self, agentmask, inheight, inwidth, batch_size):\r\n\t\t# co_agent: [bacthsize,2]\r\n\r\n\t\tPmap = tf.reduce_sum(agentmask, axis=[1, 2])\r\n\t\tPmap = tf.clip_by_value(Pmap, 1e-10, 1e10)\r\n\r\n\t\tXmap = tf.tile(tf.reshape(tf.range(inheight), [1, inheight, 1]), [batch_size, 1, inwidth])\r\n\t\tYmap = tf.tile(tf.reshape(tf.range(inwidth), [1, 1, inwidth]), [batch_size, inheight, 1])\r\n\r\n\t\tx_agent = tf.reduce_sum(agentmask * tf.cast(Xmap, tf.float32), axis=[1, 2]) / Pmap\r\n\t\ty_agent = tf.reduce_sum(agentmask * tf.cast(Ymap, tf.float32), axis=[1, 2]) / Pmap\r\n\r\n\t\treturn tf.stack([x_agent, y_agent], 1)\r\n\r\n\tdef Tailor_STN_loss(self, ndx, ndy, I, agentmask, batch_size, inheight, inwidth, pre_height, pre_width):\r\n\r\n\t\t# ndx:-dx,ndy:-dy [batch_size]\r\n\t\t# I:[batch_size, channel, height, width]\r\n\t\t# agentmask:[batch_size, height, width]\r\n\r\n\t\tpadI = tf.pad(I, [[0, 0], [0, 0], [pre_height, pre_height],\r\n\t\t [pre_width, pre_width]], \"CONSTANT\", constant_values=-1.0)\r\n\t\tpadMa = tf.pad(agentmask, [[0, 0], [pre_height, pre_height],\r\n\t\t [pre_width, pre_width]], \"CONSTANT\", constant_values=0.0)\r\n\r\n\t\tbatch_idx = tf.tile(tf.reshape(tf.range(0, batch_size), [batch_size, 1, 1]), [1, inheight, inwidth])\r\n\t\t# -dx+|dx|\r\n\t\tx_idx = tf.tile(tf.reshape(tf.range(0, inheight), [1, inheight, 1]), [batch_size, 1, inwidth]) + tf.reshape(\r\n\t\t\tndx + pre_height, [-1, 1, 1])\r\n\t\ty_idx = tf.tile(tf.reshape(tf.range(0, inwidth), [1, 1, inwidth]), [batch_size, inheight, 1]) + tf.reshape(\r\n\t\t\tndy + pre_width, [-1, 1, 1])\r\n\r\n\t\t# Pred_Ia:[batch_size, agent_horizon, agent_horizon, 3 ]\r\n\t\t# Pred_agentmask:[batch_size, agent_horizon, agent_horizon,1]\r\n\t\tindices = tf.stack([batch_idx, x_idx, y_idx], 3)\r\n\r\n\t\tpadI_tr = tf.transpose(padI, [0, 2, 3, 1])\r\n\t\tPred_Ia = tf.gather_nd(padI_tr, indices)\r\n\r\n\t\tindices = tf.stack([batch_idx, x_idx, y_idx], 3)\r\n\t\tPred_agentmask = tf.gather_nd(padMa, indices)\r\n\r\n\t\treturn Pred_Ia, tf.expand_dims(Pred_agentmask, 3)\r\n\r\n\tdef AgentImage_STN_loss(self, dco, I, agentmask, inheight, inwidth, batch_size, pre_height, pre_width):\r\n\t\t# interpolate\r\n\r\n\t\t# dco dx,dy [batch_size,2]\r\n\t\t# x:max_x-dx\r\n\t\t# y:max_y-dy\r\n\r\n\t\tx = pre_height - 1 - dco[:, 0]\r\n\t\ty = pre_width - 1 - dco[:, 1]\r\n\r\n\t\tx0 = tf.cast(tf.floor(x), 'int32')\r\n\t\tx1 = x0 + 1\r\n\t\ty0 = tf.cast(tf.floor(y), 'int32')\r\n\t\ty1 = y0 + 1\r\n\r\n\t\tzero = tf.zeros([], dtype='int32')\r\n\t\tmax_x = tf.cast(pre_height - 1, 'int32')\r\n\t\tmax_y = tf.cast(pre_width - 1, 'int32')\r\n\r\n\t\tx0_f = tf.cast(x0, 'float32')\r\n\t\tx1_f = tf.cast(x1, 'float32')\r\n\t\ty0_f = tf.cast(y0, 'float32')\r\n\t\ty1_f = tf.cast(y1, 'float32')\r\n\r\n\t\tx0 = tf.clip_by_value(x0, zero, 2 * max_x)\r\n\t\tx1 = tf.clip_by_value(x1, zero, 2 * max_x)\r\n\t\ty0 = tf.clip_by_value(y0, zero, 2 * max_y)\r\n\t\ty1 = tf.clip_by_value(y1, zero, 2 * max_y)\r\n\r\n\t\tw1 = tf.reshape(((x1_f - x) * (y1_f - y)), [-1, 1, 1, 1])\r\n\t\tw2 = tf.reshape(((x1_f - x) * (y - y0_f)), [-1, 1, 1, 1])\r\n\t\tw3 = tf.reshape(((x - x0_f) * (y1_f - y)), [-1, 1, 1, 1])\r\n\t\tw4 = tf.reshape(((x - x0_f) * (y - y0_f)), [-1, 1, 1, 1])\r\n\r\n\t\tPred_Ia1, Pred_agentmask1 = self.Tailor_STN_loss(x0 - max_x, y0 - max_y, I, agentmask, batch_size, inheight,\r\n\t\t inwidth, pre_height, pre_width)\r\n\t\tPred_Ia2, Pred_agentmask2 = self.Tailor_STN_loss(x0 - max_x, y1 - max_y, I, agentmask, batch_size, inheight,\r\n\t\t inwidth, pre_height, pre_width)\r\n\t\tPred_Ia3, Pred_agentmask3 = self.Tailor_STN_loss(x1 - max_x, y0 - max_y, I, agentmask, batch_size, inheight,\r\n\t\t inwidth, pre_height, pre_width)\r\n\t\tPred_Ia4, Pred_agentmask4 = self.Tailor_STN_loss(x1 - max_x, y1 - max_y, I, agentmask, batch_size, inheight,\r\n\t\t inwidth, pre_height, pre_width)\r\n\t\tPred_Ia = tf.add_n([w1 * Pred_Ia1, w2 * Pred_Ia2, w3 * Pred_Ia3, w4 * Pred_Ia4])\r\n\t\tPred_agentmask = tf.add_n(\r\n\t\t\t[w1 * Pred_agentmask1, w2 * Pred_agentmask2, w3 * Pred_agentmask3, w4 * Pred_agentmask4])\r\n\r\n\t\treturn Pred_Ia, Pred_agentmask\r\n\r\n\tdef STN_loss(self, Ibox, next_Ibox, M_d_objects, M_next_d_objects, object_maxnum=6,\r\n\t inchannel=3, inheight=80, inwidth=80, batch_size=16, show_lambda_pixel=1, show_lambda_mask=1):\r\n\r\n\t\tdef Pixel_diff_loss(Ibox_d_object_1, M_d_object_1, Ibox_d_object_2, M_d_object_2):\r\n\t\t\t# Ibox_d_object_1, Ibox_d_object_2: [New_batch_size, inheight * 3, inwidth * 3, inchannel]\r\n\t\t\t# M_d_object_1, M_d_object_2: [New_batch_size, inheight * 3, inwidth * 3, 1]\r\n\r\n\t\t\tIbox_d_object_2 = tf.stop_gradient(Ibox_d_object_2)\r\n\r\n\t\t\ttmp_Pmap = tf.maximum(M_d_object_1, M_d_object_2)\r\n\r\n\t\t\tM_d_object_1_sigmoid = tf.sigmoid((M_d_object_1 - 0.5) * 20)\r\n\t\t\tM_d_object_2_sigmoid = tf.sigmoid((M_d_object_2 - 0.5) * 20)\r\n\r\n\t\t\tPixel_loss = tf.reduce_mean(tf.reduce_sum(tf.square(Ibox_d_object_1 - Ibox_d_object_2) * tmp_Pmap,\r\n\t\t\t axis=[1, 2, 3]))\r\n\r\n\t\t\tMask_loss = tf.reduce_mean(tf.reduce_sum(tf.square(M_d_object_1_sigmoid - M_d_object_2_sigmoid),\r\n\t\t\t axis=[1, 2, 3]))\r\n\r\n\t\t\treturn Pixel_loss, Mask_loss\r\n\r\n\t\ttmp_Ibox = tf.tile(tf.expand_dims(Ibox, 1), [1, object_maxnum, 1, 1, 1])\r\n\t\ttmp_next_Ibox = tf.tile(tf.expand_dims(next_Ibox, 1), [1, object_maxnum, 1, 1, 1])\r\n\r\n\t\tNew_batch_size = batch_size * object_maxnum\r\n\t\t# ------------\r\n\t\ttmp_Ibox = tf.reshape(tmp_Ibox, [New_batch_size, inchannel, inheight, inwidth])\r\n\t\ttmp_next_Ibox = tf.reshape(tmp_next_Ibox, [New_batch_size, inchannel, inheight, inwidth])\r\n\t\t# ------------\r\n\t\ttmp_M_d_objects = tf.reshape(M_d_objects, [New_batch_size, inheight, inwidth])\r\n\t\ttmp_M_d_objects_next = tf.reshape(M_next_d_objects, [New_batch_size, inheight, inwidth])\r\n\t\t# ------------\r\n\r\n\t\tco_agent = self.AgentCoordinates(tmp_M_d_objects, inheight=inheight, inwidth=inwidth,\r\n\t\t batch_size=New_batch_size)\r\n\t\tco_agent_next = self.AgentCoordinates(tmp_M_d_objects_next, inheight=inheight, inwidth=inwidth,\r\n\t\t batch_size=New_batch_size)\r\n\t\tCalc_delt = co_agent_next - co_agent\r\n\r\n\t\t# tmp_Ibox, tmp_next_Ibox: [New_batch_size, inchannel, inheight, inwidth] ->\r\n\t\t# [New_batch_size, inchannel, inheight * 3, inwidth * 3]\r\n\t\t# tmp_M_d_objects, tmp_M_d_objects_next: [New_batch_size, inheight, inwidth] ->\r\n\t\t# [New_batch_size, inheight * 3, inwidth * 3]\r\n\r\n\t\t# ------------\r\n\r\n\t\ttmp_Ibox = tf.pad(tmp_Ibox, [[0, 0], [0, 0], [inheight, inheight],\r\n\t\t [inwidth, inwidth]], \"CONSTANT\", constant_values=-1.0)\r\n\t\ttmp_next_Ibox = tf.pad(tmp_next_Ibox, [[0, 0], [0, 0], [inheight, inheight],\r\n\t\t [inwidth, inwidth]], \"CONSTANT\", constant_values=-1.0)\r\n\t\ttmp_M_d_objects = tf.pad(tmp_M_d_objects, [[0, 0], [inheight, inheight],\r\n\t\t [inwidth, inwidth]], \"CONSTANT\", constant_values=0.0)\r\n\t\ttmp_M_d_objects_next = tf.pad(tmp_M_d_objects_next, [[0, 0], [inheight, inheight],\r\n\t\t [inwidth, inwidth]], \"CONSTANT\", constant_values=0.0)\r\n\r\n\t\t# ------------\r\n\r\n\t\tCalc_Ibox, Calc_M_d_objects = self.AgentImage_STN_loss(Calc_delt, tmp_Ibox, tmp_M_d_objects,\r\n\t\t inheight=inheight * 3, inwidth=inwidth * 3,\r\n\t\t batch_size=New_batch_size,\r\n\t\t pre_height=inheight, pre_width=inwidth)\r\n\r\n\t\t# Calc_Ibox: [New_batch_size, inheight * 3, inwidth * 3, inchannel]\r\n\t\t# Calc_M_d_objects: [New_batch_size, inheight * 3, inwidth * 3, 1]\r\n\r\n\t\tCalc_M_d_objects_next = tf.expand_dims(tmp_M_d_objects_next, 3)\r\n\t\tCalc_Ibox_next = tf.transpose(tmp_next_Ibox, [0, 2, 3, 1])\r\n\r\n\t\tPixel_loss, Mask_loss = Pixel_diff_loss(Calc_Ibox, Calc_M_d_objects, Calc_Ibox_next, Calc_M_d_objects_next)\r\n\r\n\t\tPixel_loss = Pixel_loss * object_maxnum / inheight / inwidth / inchannel * show_lambda_pixel\r\n\r\n\t\tMask_loss = Mask_loss * object_maxnum / inheight / inwidth * show_lambda_mask\r\n\r\n\t\toutput_M_d_objects = Calc_M_d_objects[:, inheight: inheight * 2, inwidth: inwidth * 2]\r\n\r\n\t\treturn Pixel_loss, Mask_loss, output_M_d_objects\r\n\r\n\tdef Gaussian_blur(self, M_d_objects, inheight=80, inwidth=80, object_maxnum=6, batch_size=16):\r\n\t\t'''\r\n\t\tstandard kernel 5 * 5:\r\n\t\t\t1 4 7 4 1\r\n\t\t\t4 16 26 16 4\r\n\t\t\t7 26 41 26 7 * 1. / 273\r\n\t\t\t4 16 26 16 4\r\n\t\t\t1 4 7 4 1\r\n\r\n\t\tstandard kernel 3 * 3:\r\n\t\t\t1 2 1\r\n\t\t\t2 4 2 * 1. / 16\r\n\t\t\t1 2 1\r\n\t\t'''\r\n\r\n\t\t# M_d_objects: [batch_size, object_maxnum, inheight, inwidth]\r\n\r\n\t\ttmp_M_d_objects = tf.reshape(M_d_objects, [batch_size * object_maxnum, 1, inheight, inwidth])\r\n\r\n\t\tsobel_x = tf.constant([[1, 4, 7, 4, 1], [4, 16, 26, 16, 4], [7, 26, 41, 26, 7],\r\n\t\t [4, 16, 26, 16, 4], [1, 4, 7, 4, 1]], 'float32') / 273\r\n\t\tsobel_x = tf.reshape(sobel_x, [5, 5, 1, 1])\r\n\r\n\t\t# sobel_x = tf.constant([[1, 2, 1], [2, 4, 2], [1, 2, 1]], 'float32') / 16\r\n\t\t# sobel_x = tf.reshape(sobel_x, [3, 3, 1, 1])\r\n\r\n\t\tresult = tf.nn.convolution(tmp_M_d_objects, filter=sobel_x, padding=\"SAME\", data_format=\"NCHW\")\r\n\r\n\t\tresult = tf.reshape(result, [batch_size, object_maxnum, inheight, inwidth])\r\n\r\n\t\treturn result\r\n\r\n\tdef Connection_loss(self, M_d_objects, object_maxnum=6,\r\n\t inchannel=3, inheight=80, inwidth=80, batch_size=16, show_lambda=1):\r\n\r\n\t\tdef Pixel_inter_loss(M_d_object_1, M_d_object_2):\r\n\t\t\t'''\r\n\t\t\tPmap_1 = tf.reduce_sum(M_d_object_1, axis=[1, 2])\r\n\t\t\tPmap_2 = tf.reduce_sum(M_d_object_2, axis=[1, 2])\r\n\r\n\t\t\tres = tf.reduce_sum(M_d_object_1 * M_d_object_2, axis=[1, 2]) * \\\r\n\t\t\t (tf.square(Pmap_1 + Pmap_2) - tf.square(Pmap_1 - Pmap_2))\r\n\r\n\t\t\tres = tf.reduce_mean(res / tf.clip_by_value(tf.square(Pmap_1 + Pmap_2), 1., 1e10))\r\n\r\n\t\t\treturn res\r\n\t\t\t'''\r\n\r\n\t\t\tres = tf.reduce_sum(tf.minimum(M_d_object_1, M_d_object_2), axis=[1, 2])\r\n\r\n\t\t\tres = tf.reduce_mean(res)\r\n\r\n\t\t\treturn res\r\n\r\n\t\t# tmp_M_d_objects: [batch_size, object_maxnum, inheight, inwidth]\r\n\r\n\t\ttmp_M_d_objects = self.Gaussian_blur(M_d_objects, inheight=inheight, inwidth=inwidth,\r\n\t\t object_maxnum=object_maxnum, batch_size=batch_size)\r\n\r\n\t\tConnect_loss = []\r\n\r\n\t\tfor i in range(object_maxnum):\r\n\t\t\tfor j in range(i + 1, object_maxnum):\r\n\t\t\t\tConnect_loss.append(Pixel_inter_loss(tmp_M_d_objects[:, i], tmp_M_d_objects[:, j]))\r\n\r\n\t\tConnect_loss = tf.reduce_sum(Connect_loss)\r\n\r\n\t\tConnect_loss = Connect_loss / inheight / inwidth * show_lambda\r\n\r\n\t\treturn Connect_loss, tmp_M_d_objects\r\n\r\n\tdef create_loss(self, input_Ibox, input_next_Ibox, input_dmask, input_next_dmask):\r\n\r\n\t\tIbox = 2 * (input_Ibox / 255. - .5)\r\n\t\tnext_Ibox = 2 * (input_next_Ibox / 255. - .5)\r\n\r\n\t\t# Ibox, next_Ibox: [gpu_batch_size, b_width, b_height, channel] -->\r\n\t\t# [gpu_batch_size, channel, b_height, b_width]\r\n\t\t# dmask, next_dmask: [gpu_batch_size, b_width, b_height] -->\r\n\t\t# [gpu_batch_size, b_height, b_width]\r\n\r\n\t\tIbox = tf.transpose(Ibox, [0, 3, 2, 1])\r\n\t\tnext_Ibox = tf.transpose(next_Ibox, [0, 3, 2, 1])\r\n\r\n\t\tdmask = tf.transpose(input_dmask, [0, 2, 1])\r\n\t\tnext_dmask = tf.transpose(input_next_dmask, [0, 2, 1])\r\n\r\n\t\t# ---------------------\r\n\t\t# M_d_objects: [gpu_batch_size, num_objects, b_height, b_width]\r\n\r\n\t\tmulti_Ibox, multi_dmask, M_d_objects_both, EL = \\\r\n\t\t\tself.Mask_AttentionNet(tf.concat([Ibox, next_Ibox], 0), tf.concat([dmask, next_dmask], 0),\r\n\t\t\t inchannel=self.CHANNELS, inheight=self.B_HEIGHT, inwidth=self.B_WIDTH,\r\n\t\t\t object_maxnum=self.dynamic_object_class_maxnum, is_train=self.is_train,\r\n\t\t\t batch_size=self.gpu_batch_size)\r\n\r\n\t\tM_d_objects = M_d_objects_both[: self.gpu_batch_size]\r\n\t\tM_next_d_objects = M_d_objects_both[self.gpu_batch_size:]\r\n\r\n\t\t# ---------------------\r\n\r\n\t\tSTN_pixel_loss, STN_mask_loss, output_M_d_objects = \\\r\n\t\t\tself.STN_loss(Ibox, next_Ibox, M_d_objects, M_next_d_objects,\r\n\t\t\t inchannel=self.CHANNELS,\r\n\t\t\t inheight=self.B_HEIGHT,\r\n\t\t\t inwidth=self.B_WIDTH,\r\n\t\t\t object_maxnum=self.dynamic_object_class_maxnum,\r\n\t\t\t batch_size=self.gpu_batch_size,\r\n\t\t\t show_lambda_pixel=self.show_lambda_STN_pixel,\r\n\t\t\t show_lambda_mask=self.show_lambda_STN_mask)\r\n\r\n\t\t# Calc_M_d_objects: [gpu_batch_size, object_maxnum, b_height, b_width]\r\n\t\tCalc_M_d_objects = tf.reshape(output_M_d_objects, [self.gpu_batch_size, self.dynamic_object_class_maxnum,\r\n\t\t self.B_HEIGHT, self.B_WIDTH])\r\n\r\n\t\t# ---------------------\r\n\r\n\t\tConnection_loss, Gaussian_M_d_objects_both = \\\r\n\t\t\tself.Connection_loss(M_d_objects_both,\r\n\t\t\t inchannel=self.CHANNELS,\r\n\t\t\t inheight=self.B_HEIGHT,\r\n\t\t\t inwidth=self.B_WIDTH,\r\n\t\t\t object_maxnum=self.dynamic_object_class_maxnum,\r\n\t\t\t batch_size=self.gpu_batch_size * 2,\r\n\t\t\t show_lambda=self.show_lambda_Connect)\r\n\r\n\t\t# ---------------------\r\n\r\n\t\tTotal_loss = self.lambda_STN_pixel * STN_pixel_loss\r\n\r\n\t\tloss_list = (Total_loss, STN_pixel_loss, STN_mask_loss, Connection_loss)\r\n\t\tsummary_list = (Ibox, next_Ibox, M_d_objects, M_next_d_objects, dmask, next_dmask,\r\n\t\t Gaussian_M_d_objects_both, Calc_M_d_objects)\r\n\t\ttest_list = (Ibox, next_Ibox, M_d_objects, M_next_d_objects)\r\n\r\n\t\treturn loss_list, summary_list, test_list\r\n\r\n\tdef create_network(self):\r\n\r\n\t\t# =======Construct graph=======\r\n\t\t# need all float32\r\n\t\t# input image : 0-255, [batch_size, width, height, 3]\r\n\r\n\t\tself.is_train = tf.placeholder(tf.bool)\r\n\t\tself.input_Ibox = tf.placeholder(tf.float32, shape=[self.CV_BATCH_SIZE, self.B_WIDTH,\r\n\t\t self.B_HEIGHT, self.CHANNELS])\r\n\t\tself.input_next_Ibox = tf.placeholder(tf.float32, shape=[self.CV_BATCH_SIZE, self.B_WIDTH,\r\n\t\t self.B_HEIGHT, self.CHANNELS])\r\n\t\tself.input_dmask = tf.placeholder(tf.float32, shape=[self.CV_BATCH_SIZE, self.B_WIDTH, self.B_HEIGHT])\r\n\t\tself.input_next_dmask = tf.placeholder(tf.float32, shape=[self.CV_BATCH_SIZE, self.B_WIDTH, self.B_HEIGHT])\r\n\r\n\t\t# ---------------------\r\n\r\n\t\twith tf.device(self.shared_device):\r\n\r\n\t\t\topt = tf.train.AdamOptimizer(learning_rate=self.lr)\r\n\r\n\t\t\tif (len(self.devices) == 1):\r\n\r\n\t\t\t\tloss_list, summary_list, test_list = \\\r\n\t\t\t\t\tself.create_loss(self.input_Ibox, self.input_next_Ibox, self.input_dmask, self.input_next_dmask)\r\n\t\t\t\tTotal_loss = loss_list[0]\r\n\r\n\t\t\t\tself.train_total_op = opt.minimize(Total_loss)\r\n\t\t\telse:\r\n\t\t\t\ttower_grads, tmp_loss_list, tmp_summary_list, tmp_test_list = [], [], [], []\r\n\t\t\t\twith tf.variable_scope(tf.get_variable_scope()):\r\n\t\t\t\t\tfor i, dev_id in enumerate(self.devices):\r\n\t\t\t\t\t\tl = i * self.gpu_batch_size\r\n\t\t\t\t\t\tr = (i + 1) * self.gpu_batch_size\r\n\r\n\t\t\t\t\t\twith tf.device(dev_id):\r\n\t\t\t\t\t\t\twith tf.name_scope('tower_{}'.format(i)):\r\n\t\t\t\t\t\t\t\tt_loss_list, t_summary_list, test_list = \\\r\n\t\t\t\t\t\t\t\t\tself.create_loss(self.input_Ibox[l: r], self.input_next_Ibox[l: r],\r\n\t\t\t\t\t\t\t\t\t self.input_dmask[l: r], self.input_next_dmask[l: r])\r\n\t\t\t\t\t\t\t\tTotal_loss = t_loss_list[0]\r\n\r\n\t\t\t\t\t\t\t\t# Reuse variables for the next tower.\r\n\t\t\t\t\t\t\t\ttf.get_variable_scope().reuse_variables()\r\n\r\n\t\t\t\t\t\t\t\tgrads = opt.compute_gradients(Total_loss)\r\n\t\t\t\t\t\t\t\ttower_grads.append(grads)\r\n\r\n\t\t\t\t\t\t\t\ttmp_loss_list.append(t_loss_list)\r\n\t\t\t\t\t\t\t\ttmp_summary_list.append(t_summary_list)\r\n\t\t\t\t\t\t\t\ttmp_test_list.append(test_list)\r\n\r\n\t\t\t\tgrads = utils.average_gradients(tower_grads)\r\n\t\t\t\tapply_gradient_op = opt.apply_gradients(grads)\r\n\t\t\t\tself.train_total_op = apply_gradient_op\r\n\r\n\t\t\t\tloss_list = utils.reduce_mean_tf_data_flow(tmp_loss_list)\r\n\t\t\t\tsummary_list = utils.concat_tf_data_flow(tmp_summary_list)\r\n\t\t\t\ttest_list = utils.concat_tf_data_flow(tmp_test_list)\r\n\r\n\t\t\tself.Total_loss, self.STN_pixel_loss, self.STN_mask_loss, self.Connection_loss = loss_list\r\n\t\t\tIbox, next_Ibox, M_d_objects, M_next_d_objects, dmask, next_dmask, \\\r\n\t\t\tGaussian_M_d_objects_both, Calc_M_d_objects = summary_list\r\n\t\t\tself.Ibox_1, self.Ibox_2, self.M_d_objects_1, self.M_d_objects_2 = test_list\r\n\r\n\t\t# ---------------------\r\n\r\n\t\ttf.summary.scalar('STN_pixel_loss', self.STN_pixel_loss)\r\n\t\ttf.summary.scalar('STN_mask_loss', self.STN_mask_loss)\r\n\t\ttf.summary.scalar('Connect_loss', self.Connection_loss)\r\n\t\ttf.summary.scalar('TotalLoss', self.Total_loss)\r\n\r\n\t\ttf.summary.image('Image_box', tf.transpose(Ibox, [0, 2, 3, 1]))\r\n\t\ttf.summary.image('Image_next_box', tf.transpose(next_Ibox, [0, 2, 3, 1]))\r\n\t\ttf.summary.image('dmask', tf.expand_dims(dmask, 3))\r\n\t\ttf.summary.image('next_dmask', tf.expand_dims(next_dmask, 3))\r\n\t\ttf.summary.image('Image_box_mask', tf.transpose(Ibox, [0, 2, 3, 1]) * tf.expand_dims(dmask, 3))\r\n\t\ttf.summary.image('Image_next_box_mask', tf.transpose(next_Ibox, [0, 2, 3, 1]) * tf.expand_dims(next_dmask, 3))\r\n\r\n\t\tfor i in range(self.dynamic_object_class_maxnum):\r\n\t\t\ttmp = tf.expand_dims(M_d_objects[:, i, :, :], 3)\r\n\t\t\ttf.summary.image('M_object_' + str(i), tmp)\r\n\t\t\ttf.summary.image('I_object_' + str(i), tf.cast(tmp >= 0.5, tf.float32) * tf.transpose(Ibox, [0, 2, 3, 1]))\r\n\r\n\t\t\ttmp = tf.expand_dims(M_next_d_objects[:, i, :, :], 3)\r\n\t\t\ttf.summary.image('M_object_next_' + str(i), tmp)\r\n\t\t\ttf.summary.image('I_object_next_' + str(i),\r\n\t\t\t tf.cast(tmp >= 0.5, tf.float32) * tf.transpose(next_Ibox, [0, 2, 3, 1]))\r\n\r\n\t\t\ttmp = tf.expand_dims(Gaussian_M_d_objects_both[: self.CV_BATCH_SIZE, i, :, :], 3)\r\n\t\t\ttf.summary.image('Gaussian_M_object_' + str(i), tmp)\r\n\r\n\t\t\ttmp = tf.expand_dims(Calc_M_d_objects[:, i, :, :], 3)\r\n\t\t\ttf.summary.image('Moved_M_object_' + str(i), tmp)\r\n\r\n\t\tself.summary_op = tf.summary.merge_all()\r\n\r\n\tdef data_batch_alignment(self, t_data, batch_size, pad_value):\r\n\r\n\t\tt_data_shape_num = len(t_data.shape)\r\n\t\tt_data_num = t_data.shape[0]\r\n\t\tt_data_num_fix = ((t_data_num - 1) // batch_size + 1) * batch_size\r\n\r\n\t\tpad_list = [[0, t_data_num_fix - t_data_num]] + [[0, 0]] * (t_data_shape_num - 1)\r\n\r\n\t\tt_data = np.pad(t_data, pad_list, 'constant', constant_values=pad_value)\r\n\r\n\t\treturn t_data\r\n\r\n\tdef evaluation(self, Ibox, next_Ibox, dynamics_mask, next_dynamics_mask, bbox_coor, is_train):\r\n\r\n\t\tdef recover_batch(data):\r\n\t\t\t# tmp_mask, tmp_mask_next: [each_batch_num, object_maxnum, b_height, b_width] ->\r\n\t\t\t# [each_batch_num, object_maxnum, b_height, old_b_width]\r\n\t\t\t# tmp_Ibox, tmp_Ibox_next: [each_batch_num, channel, b_height, b_width] ->\r\n\t\t\t# [each_batch_num, channel, b_height, old_b_width]\r\n\t\t\tdata = np.concatenate([data[:, :, :, : self.old_B_WIDTH],\r\n\t\t\t data[:, :, :, self.old_B_WIDTH + self.pad_b_width:]], axis=0)\r\n\t\t\treturn data\r\n\r\n\t\t# Ibox, next_Ibox: [list(batch), num_select_box, old_b_width, b_height, channel]\r\n\t\t# dynamics_mask, next_dynamics_mask: [list(batch), num_select_box, old_b_width, b_height]\r\n\t\t# bbox_coor: [list(batch), num_select_box, 4] (width_1, width_2, height_1, height_2)\r\n\r\n\t\tt_1 = time.time()\r\n\r\n\t\tt_data = []\r\n\t\tt_bbox = []\r\n\r\n\t\tfor i in range(self.BATCH_SIZE):\r\n\t\t\t# t_copy: [each_batch_num, old_b_width, b_height, channel * 2 + 2]\r\n\t\t\tt_copy = [Ibox[i].copy(), next_Ibox[i].copy(),\r\n\t\t\t np.expand_dims(dynamics_mask[i], 3), np.expand_dims(next_dynamics_mask[i], 3)]\r\n\t\t\tt_copy = np.concatenate(t_copy, axis=3)\r\n\t\t\tt_data.append(t_copy)\r\n\t\t\tt_bbox.append(bbox_coor[i])\r\n\r\n\t\tt_data = np.concatenate(t_data, axis=0)\r\n\t\tt_data = self.data_batch_alignment(t_data, 2 * self.CV_BATCH_SIZE, 0.)\r\n\r\n\t\tt_bbox = np.concatenate(t_bbox, axis=0)\r\n\r\n\t\t# t_data: [t_data_num_fix, old_b_width, b_height, channel * 2 + 2] ->\r\n\t\t# [t_data_num_fix // 2, b_width, b_height, channel * 2 + 2]\r\n\r\n\t\tt_data_num = t_data.shape[0]\r\n\r\n\t\tt_data_pad = np.pad(t_data[: t_data_num // 2], [[0, 0],\r\n\t\t [0, self.pad_b_width], [0, 0], [0, 0]], 'constant')\r\n\t\tt_data = np.concatenate([t_data_pad, t_data[t_data_num // 2:]], axis=1)\r\n\r\n\t\t# t_data_num: sum_batch_box\r\n\t\t# self.CV_BATCH_SIZE | t_data_num_fix\r\n\t\t# t_data: [t_data_num_fix, b_width, b_height, channel * 2 + 2]\r\n\t\t# t_bbox: [t_data_num, 4]\r\n\r\n\t\tres = defaultlist(list)\r\n\r\n\t\tfor i in range(t_data.shape[0] // self.CV_BATCH_SIZE):\r\n\r\n\t\t\tl = i * self.CV_BATCH_SIZE\r\n\t\t\tr = (i + 1) * self.CV_BATCH_SIZE\r\n\t\t\ttmp = self.CHANNELS * 2\r\n\r\n\t\t\twith self.graph.as_default():\r\n\t\t\t\t# tmp_Ibox_1, tmp_Ibox_2, tmp_mask_1, tmp_mask_2\r\n\t\t\t\tt_res = self.sess.run([self.Ibox_1, self.Ibox_2, self.M_d_objects_1, self.M_d_objects_2],\r\n\t\t\t\t feed_dict={\r\n\t\t\t\t\t\t self.input_Ibox: t_data[l: r, :, :, :self.CHANNELS],\r\n\t\t\t\t\t\t self.input_next_Ibox: t_data[l: r, :, :, self.CHANNELS: tmp],\r\n\t\t\t\t\t\t self.input_dmask: t_data[l: r, :, :, tmp],\r\n\t\t\t\t\t\t self.input_next_dmask: t_data[l: r, :, :, tmp + 1],\r\n\t\t\t\t\t\t self.is_train: is_train\r\n\t\t\t\t\t })\r\n\r\n\t\t\tfor x, item in enumerate(t_res):\r\n\t\t\t\tres[x].append(item)\r\n\r\n\t\tevaluation_data = []\r\n\r\n\t\tfor item in res:\r\n\t\t\titem_1 = np.concatenate(item, axis=0)\r\n\t\t\titem_2 = recover_batch(item_1)\r\n\t\t\tevaluation_data.append(item_2)\r\n\r\n\t\tt_res_Ibox_1, t_res_Ibox_2, t_res_mask_1, t_res_mask_2 = evaluation_data\r\n\r\n\t\tif (self.mpi_rank == 0 and is_train):\r\n\t\t\tprint('Testing mask1:', time.time() - t_1)\r\n\r\n\t\treturn t_res_Ibox_1, t_res_Ibox_2, t_res_mask_1, t_res_mask_2, t_bbox\r\n\r\n\tdef box_choose_K(self, t_dynamics_instances, K):\r\n\r\n\t\t# return_Ibox, return_Ibox_next: [selected_num, old_b_width, b_height, channel]\r\n\t\t# return_mask, return_mask_next: [selected_num, old_b_width, b_height]\r\n\t\t# return_bbox: [selected_num, 4]\r\n\t\t# return_label: [selected_num]\r\n\t\t# return_Md: [M_classes, width, height]\r\n\t\t# return_C, return_next_C: [selected_num, 2]\r\n\t\t# return_Ms: [selected_num, width, height]\r\n\r\n\t\treturn_Ibox, return_Ibox_next, return_mask, return_mask_next, return_bbox, return_label, return_Md, \\\r\n\t\treturn_C, return_next_C, return_Ms = t_dynamics_instances\r\n\r\n\t\t'''\r\n\t\tprint('return_Ibox', return_Ibox.shape)\r\n\t\tprint('return_Ibox_next', return_Ibox_next.shape)\r\n\t\tprint('return_mask', return_mask.shape)\r\n\t\tprint('return_mask_next', return_mask_next.shape)\r\n\t\tprint('return_bbox', return_bbox.shape)\r\n\t\tprint('return_label', return_label.shape)\r\n\t\tprint('return_Md', return_Md.shape)\r\n\t\t'''\r\n\r\n\t\tselected_num = return_Ibox.shape[0]\r\n\r\n\t\t'''\r\n\t\tif (selected_num > K):\r\n\t\t\tt_copy = (return_Ibox[: K], return_Ibox_next[: K], return_mask[: K], return_mask_next[: K],\r\n\t\t\t return_bbox[: K], return_label[: K], return_C[: K], return_next_C[: K], return_Ms[: K])\r\n\t\telse:\r\n\t\t\tt_copy = (return_Ibox, return_Ibox_next, return_mask, return_mask_next, return_bbox, return_label,\r\n\t\t\t return_C, return_next_C, return_Ms)\r\n\t\t'''\r\n\r\n\t\tif (selected_num > K):\r\n\t\t\tt_copy = (return_label[: K], return_C[: K], return_next_C[: K], return_Ms[: K])\r\n\t\telse:\r\n\t\t\tt_copy = (return_label, return_C, return_next_C, return_Ms)\r\n\r\n\t\tres = []\r\n\r\n\t\tfor item in t_copy:\r\n\t\t\tres.append(self.data_batch_alignment(item, K, 0))\r\n\r\n\t\tres.append(return_Md)\r\n\r\n\t\treturn res, selected_num\r\n\r\n\tdef folder_prepare(self, selection_path):\r\n\t\tfolder = os.path.exists(selection_path)\r\n\t\tif (folder):\r\n\t\t\tshutil.rmtree(selection_path)\r\n\t\tos.makedirs(selection_path)\r\n\r\n\tdef show_selection(self, I, nextI, wmask, next_wmask, batch_cache, batch_dynamics_instances):\r\n\r\n\t\t# batch_dynamics_instances: [batch_examples]\r\n\t\t# return_Ibox, return_Ibox_next: [selected_num, old_b_width, b_height, channel]\r\n\t\t# return_mask, return_mask_next: [selected_num, old_b_width, b_height]\r\n\t\t# return_bbox: [selected_num, 4]\r\n\t\t# return_label: [selected_num]\r\n\t\t# return_Md: [M_classes, width, height]\r\n\t\t# return_C, return_next_C: [selected_num, 2]\r\n\t\t# return_Ms: [selected_num, width, height]\r\n\t\t# wmask, next_wmask: [width, height]\r\n\r\n\t\tsave_start = self.mpi_rank * self.cpu_batch_size\r\n\r\n\t\tfor i in range(self.cpu_batch_size):\r\n\r\n\t\t\tt_Ibox, t_Ibox_next, t_mask, t_mask_next, t_bbox, t_label, t_Md, t_C, t_next_C, t_Ms = \\\r\n\t\t\t\tbatch_dynamics_instances[i]\r\n\r\n\t\t\tt_wmask, t_next_wmask = wmask[i], next_wmask[i]\r\n\r\n\t\t\tt_I, t_next_I = I[i], nextI[i]\r\n\r\n\t\t\tt_selected_num = t_Ibox.shape[0]\r\n\r\n\t\t\tselection_path = '../../tmp/' + self.path + 'selection_' + str(save_start + i) + '/'\r\n\r\n\t\t\tself.folder_prepare(selection_path)\r\n\r\n\t\t\tfor j in range(t_selected_num):\r\n\t\t\t\timsave(selection_path + 'Ibox_' + str(j) + '.jpg', np.transpose(t_Ibox[j], [1, 0, 2]))\r\n\t\t\t\timsave(selection_path + 'Ibox_next_' + str(j) + '.jpg', np.transpose(t_Ibox_next[j], [1, 0, 2]))\r\n\t\t\t\timsave(selection_path + 'mask_' + str(j) + '.jpg', np.transpose(t_mask[j], [1, 0]))\r\n\t\t\t\timsave(selection_path + 'mask_next_' + str(j) + '.jpg', np.transpose(t_mask_next[j], [1, 0]))\r\n\t\t\t\timsave(selection_path + 'Ms_' + str(j) + '.jpg', np.transpose(t_Ms[j], [1, 0]))\r\n\r\n\t\t\tnp.savetxt(selection_path + 'bbox.txt', t_bbox, fmt='%d ')\r\n\t\t\tnp.savetxt(selection_path + 'label.txt', t_label, fmt='%d ')\r\n\t\t\tnp.savetxt(selection_path + 'C.txt', t_C, fmt='%d ')\r\n\t\t\tnp.savetxt(selection_path + 'next_C.txt', t_next_C, fmt='%d ')\r\n\r\n\t\t\tfor j in range(self.dynamic_object_class_maxnum):\r\n\t\t\t\timsave(selection_path + 'Md_' + str(j) + '.jpg', np.transpose(t_Md[j], [1, 0]))\r\n\r\n\t\t\timsave(selection_path + 'wmask_' + '.jpg', np.transpose(t_wmask, [1, 0]))\r\n\t\t\timsave(selection_path + 'wmask_next_' + '.jpg', np.transpose(t_next_wmask, [1, 0]))\r\n\r\n\t\t\timsave(selection_path + 'I_true' + '.jpg', np.transpose(t_I, [1, 0, 2]))\r\n\t\t\timsave(selection_path + 'next_I_true' + '.jpg', np.transpose(t_next_I, [1, 0, 2]))\r\n\r\n\t\tfor i in range(self.cpu_batch_size):\r\n\t\t\tI_input, nextI_input = I[i], nextI[i]\r\n\t\t\tIb_input, nextIb_input, Mb_input, nextMb_input, XY_input, label_input = \\\r\n\t\t\t\tbatch_cache[i]\r\n\t\t\tselection_path = '../../tmp/' + self.path + 'selection_' + str(save_start + i) + '/'\r\n\t\t\timsave(selection_path + 'I.jpg', I_input)\r\n\t\t\timsave(selection_path + 'nextI.jpg', nextI_input)\r\n\t\t\tnp.save(selection_path + 'I_input.npy', I_input)\r\n\t\t\tnp.save(selection_path + 'nextI_input.npy', nextI_input)\r\n\t\t\tnp.save(selection_path + 'Ib_input.npy', Ib_input)\r\n\t\t\tnp.save(selection_path + 'nextIb_input.npy', nextIb_input)\r\n\t\t\tnp.save(selection_path + 'Mb_input.npy', Mb_input)\r\n\t\t\tnp.save(selection_path + 'nextMb_input.npy', nextMb_input)\r\n\t\t\tnp.save(selection_path + 'XY_input.npy', XY_input)\r\n\t\t\tnp.save(selection_path + 'label_input', label_input)\r\n\r\n\tdef selection(self, I, bgimage, nextI, Ibox, next_Ibox, wmask, next_wmask, evaluation_data,\r\n\t is_train, is_show=False):\r\n\r\n\t\tdef Transmit_numpy(item_list, mpi_id=0, tag=10):\r\n\t\t\t# list(x) for x in (tmp_Ibox, tmp_Ibox_next, tmp_mask, tmp_mask_next, tmp_bbox, tmp_label) and x is numpy\r\n\t\t\t#\r\n\t\t\t# tmp_Ibox, tmp_Ibox_next: [each_batch_num * object_maxnum, old_b_width, b_height, channel]\r\n\t\t\t# tmp_mask, tmp_mask_next: [each_batch_num * object_maxnum, old_b_width, b_height]\r\n\t\t\t# tmp_bbox: [each_batch_num * object_maxnum, 4]\r\n\t\t\t# tmp_label: [each_batch_num * object_maxnum]\r\n\t\t\tfor i in range(self.cpu_batch_size):\r\n\t\t\t\tutils.Transmit_numpy(list(item_list[i]), mpi_id=mpi_id, tag=tag)\r\n\r\n\t\t# I, nextI, bgimage: [batch, width, height, channel]\r\n\t\t# Ibox, next_Ibox: [list(batch), num_select_box, old_b_width, b_height, channel]\r\n\t\t# wmask, next_wmask: [batch, width, height]\r\n\r\n\t\tt_1 = time.time()\r\n\r\n\t\t# open selection booster\r\n\t\tutils.Transmit_normal(True, mpi_upper=self.s_mpi_size, tag=14)\r\n\r\n\t\t# transmit is_show\r\n\t\tutils.Transmit_normal(is_show, mpi_upper=self.s_mpi_size, tag=18)\r\n\r\n\t\tt_res_Ibox_1, t_res_Ibox_2, t_res_mask_1, t_res_mask_2, t_bbox = evaluation_data\r\n\r\n\t\tt_stamp = 0\r\n\t\tbatch_cache = []\r\n\r\n\t\tfor i in range(self.BATCH_SIZE):\r\n\t\t\tt_instance_num = Ibox[i].shape[0]\r\n\t\t\tt_num = t_stamp + t_instance_num\r\n\r\n\t\t\t# object_maxnum: self.dynamic_object_class_maxnum\r\n\t\t\t# tmp_mask, tmp_mask_next: [each_batch_num, object_maxnum, b_height, old_b_width]\r\n\t\t\t# tmp_Ibox, tmp_Ibox_next: [each_batch_num, channel, b_height, old_b_width]\r\n\t\t\t# tmp_bbox: [each_batch_num, 4]\r\n\r\n\t\t\ttmp_mask, tmp_mask_next = t_res_mask_1[t_stamp: t_num], t_res_mask_2[t_stamp: t_num]\r\n\t\t\ttmp_Ibox, tmp_Ibox_next = t_res_Ibox_1[t_stamp: t_num], t_res_Ibox_2[t_stamp: t_num]\r\n\t\t\ttmp_bbox = t_bbox[t_stamp: t_num]\r\n\r\n\t\t\tt_stamp = t_num\r\n\r\n\t\t\t# ---------------------\r\n\r\n\t\t\t# tmp_mask, tmp_mask_next -> [each_batch_num * object_maxnum, b_height, old_b_width]\r\n\t\t\t# tmp_Ibox, tmp_Ibox_next -> [each_batch_num * object_maxnum, channel, b_height, old_b_width]\r\n\t\t\t# tmp_bbox -> [each_batch_num * object_maxnum, 4]\r\n\t\t\t# tmp_label: [each_batch_num * object_maxnum]\r\n\r\n\t\t\ttmp_object_maxnum = self.dynamic_object_class_maxnum\r\n\r\n\t\t\ttmp_mask = np.reshape(tmp_mask, [t_instance_num * tmp_object_maxnum,\r\n\t\t\t self.B_HEIGHT, self.old_B_WIDTH])\r\n\t\t\ttmp_mask_next = np.reshape(tmp_mask_next, [t_instance_num * tmp_object_maxnum,\r\n\t\t\t self.B_HEIGHT, self.old_B_WIDTH])\r\n\t\t\ttmp_Ibox = np.reshape(np.tile(np.expand_dims(tmp_Ibox, 1), (1, tmp_object_maxnum, 1, 1, 1)),\r\n\t\t\t [t_instance_num * tmp_object_maxnum, self.CHANNELS,\r\n\t\t\t self.B_HEIGHT, self.old_B_WIDTH])\r\n\t\t\ttmp_Ibox_next = np.reshape(np.tile(np.expand_dims(tmp_Ibox_next, 1), (1, tmp_object_maxnum, 1, 1, 1)),\r\n\t\t\t [t_instance_num * tmp_object_maxnum, self.CHANNELS,\r\n\t\t\t self.B_HEIGHT, self.old_B_WIDTH])\r\n\t\t\ttmp_bbox = np.reshape(np.tile(np.expand_dims(tmp_bbox, 1), (1, tmp_object_maxnum, 1)),\r\n\t\t\t [t_instance_num * tmp_object_maxnum, 4])\r\n\t\t\ttmp_label = np.tile(np.arange(tmp_object_maxnum), t_instance_num)\r\n\r\n\t\t\t# tmp_mask, tmp_mask_next -> [each_batch_num * object_maxnum, old_b_width, b_height]\r\n\t\t\t# tmp_Ibox, tmp_Ibox_next -> [each_batch_num * object_maxnum, old_b_width, b_height, channel]\r\n\r\n\t\t\ttmp_mask = np.transpose(tmp_mask, [0, 2, 1])\r\n\t\t\ttmp_mask_next = np.transpose(tmp_mask_next, [0, 2, 1])\r\n\t\t\ttmp_Ibox = np.transpose(tmp_Ibox, [0, 3, 2, 1])\r\n\t\t\ttmp_Ibox_next = np.transpose(tmp_Ibox_next, [0, 3, 2, 1])\r\n\r\n\t\t\t# ---------------------\r\n\t\t\tbatch_cache.append((tmp_Ibox, tmp_Ibox_next, tmp_mask, tmp_mask_next, tmp_bbox, tmp_label))\r\n\r\n\t\t# Function = self.box_selector.get_selection\r\n\t\t#\r\n\t\t# Input:\r\n\t\t# I, nextI: [width, height, channel]\r\n\t\t# tmp_Ibox, tmp_Ibox_next: [each_batch_num * object_maxnum, old_b_width, b_height, channel]\r\n\t\t# tmp_mask, tmp_mask_next: [each_batch_num * object_maxnum, old_b_width, b_height]\r\n\t\t# tmp_bbox: [each_batch_num * object_maxnum, 4]\r\n\t\t# tmp_label: [each_batch_num * object_maxnum]\r\n\t\t# Output:\r\n\t\t# return_Ibox, return_Ibox_next: [selected_num, old_b_width, b_height, channel]\r\n\t\t# return_mask, return_mask_next: [selected_num, old_b_width, b_height]\r\n\t\t# return_bbox: [selected_num, 4]\r\n\t\t# return_label: [selected_num]\r\n\t\t# return_Md: [object_maxnum, width, height]\r\n\t\t# return_C, return_next_C: [selected_num, 2]\r\n\t\t# return_Ms: [selected_num, width, height]\r\n\t\t#\r\n\t\t# dynamic selected_num is not ok.\r\n\r\n\t\t#print('Selecting_1:', time.time() - t_1)\r\n\r\n\t\tfor mpi_id in range(1, self.s_mpi_size):\r\n\t\t\tl = mpi_id * self.cpu_batch_size\r\n\t\t\tr = (mpi_id + 1) * self.cpu_batch_size\r\n\t\t\tutils.Transmit_numpy([I[l: r], nextI[l: r],\r\n\t\t\t wmask[l: r], next_wmask[l: r]], mpi_id=mpi_id, tag=19)\r\n\t\t\tTransmit_numpy(batch_cache[l: r], mpi_id=mpi_id, tag=15)\r\n\r\n\t\t#print('Selecting_2:', time.time() - t_1)\r\n\r\n\t\tres_list = []\r\n\t\tshow_instances_cpu_size = []\r\n\t\tmerge_selection_num_list = []\r\n\r\n\t\tfor j in range(self.s_mpi_size):\r\n\r\n\t\t\tif (j == 0):\r\n\t\t\t\tbatch_dynamics_instances_K = defaultlist(list)\r\n\t\t\t\tselection_num_list = []\r\n\t\t\t\tfor i in range(self.cpu_batch_size):\r\n\t\t\t\t\ttmp_Ibox, tmp_Ibox_next, tmp_mask, tmp_mask_next, tmp_bbox, tmp_label = batch_cache[i]\r\n\t\t\t\t\tt_dynamics_instances = self.box_selector.get_selection(I[i], nextI[i], tmp_Ibox, tmp_Ibox_next,\r\n\t\t\t\t\t tmp_mask, tmp_mask_next, tmp_bbox, tmp_label,\r\n\t\t\t\t\t self.warning_path)\r\n\t\t\t\t\tt_dynamics_instances_K, box_selected_num = \\\r\n\t\t\t\t\t\tself.box_choose_K(t_dynamics_instances, self.dynamic_object_instance_box_maxnum)\r\n\t\t\t\t\t# (return_label, return_C, return_next_C, return_Ms, return_Md)\r\n\t\t\t\t\tfor t_stamp_K, item in enumerate(t_dynamics_instances_K):\r\n\t\t\t\t\t\tbatch_dynamics_instances_K[t_stamp_K].append(item)\r\n\t\t\t\t\tselection_num_list.append(box_selected_num)\r\n\t\t\t\t\tif (is_show):\r\n\t\t\t\t\t\tshow_instances_cpu_size.append(t_dynamics_instances)\r\n\r\n\t\t\t\tres = []\r\n\t\t\t\tfor item in batch_dynamics_instances_K:\r\n\t\t\t\t\tres.append(np.array(item))\r\n\r\n\t\t\t\t#print('Selecting_3:', time.time() - t_1)\r\n\t\t\telse:\r\n\t\t\t\tres = utils.Receive_numpy(source=j, tag=16)\r\n\t\t\t\tselection_num_list = self.comm.recv(source=j, tag=17)\r\n\r\n\t\t\tres_list.append(res)\r\n\t\t\tmerge_selection_num_list.append(selection_num_list)\r\n\r\n\t\tmerge_res = utils.concat_np_data_list_flow(res_list)\r\n\r\n\t\tif (self.mpi_rank == 0 and is_train):\r\n\t\t\tprint('Selecting:', time.time() - t_1)\r\n\t\t\tprint('Mean number of selection in a batch :', np.mean(merge_selection_num_list))\r\n\t\t\tprint('Max number of selection in a batch :', np.max(merge_selection_num_list))\r\n\t\t\txplot.plot('Mean_number_of_selection', np.mean(merge_selection_num_list))\r\n\t\t\txplot.plot('Max_number_of_selection', np.max(merge_selection_num_list))\r\n\r\n\t\tif (is_show):\r\n\t\t\tr = self.cpu_batch_size\r\n\t\t\tself.show_selection(I[:r], nextI[:r], wmask[:r], next_wmask[:r], batch_cache[:r], show_instances_cpu_size)\r\n\r\n\t\treturn merge_res\r\n\r\n\tdef evaluate_to_selection(self, I, bgimage, nextI, Ibox, next_Ibox, dynamics_mask, next_dynamics_mask,\r\n\t wmask, next_wmask, bbox_coor, is_train, is_show=False):\r\n\r\n\t\t# I, nextI, bgimage: [batch, width, height, channel]\r\n\t\t# Ibox, next_Ibox: [list(batch), num_select_box, old_b_width, b_height, channel]\r\n\t\t# dynamics_mask, next_dynamics_mask: [list(batch), num_select_box, old_b_width, b_height]\r\n\t\t# wmask, next_wmask: [batch, width, height]\r\n\t\t# bbox_coor: [list(batch), num_select_box, 4] (width_1, width_2, height_1, height_2)\r\n\r\n\t\t# ---------------------\r\n\r\n\t\t# Evaluation\r\n\r\n\t\tevaluation_data = \\\r\n\t\t\tself.evaluation(Ibox, next_Ibox, dynamics_mask, next_dynamics_mask, bbox_coor, is_train)\r\n\r\n\t\t# ---------------------\r\n\r\n\t\t# Selection\r\n\r\n\t\t# selected_num: self.dynamic_object_instance_box_maxnum\r\n\t\t# dynamics_mask_label: [batch, selected_num]\r\n\t\t# dynamics_mask_C, dynamics_mask_next_C: [batch, selected_num, 2]\r\n\t\t# dynamics_filter_box: [batch, selected_num, width, height]\r\n\t\t# dynamics_multi_mask: [batch, object_maxnum, width, height]\r\n\r\n\t\tres = self.selection(I, bgimage, nextI, Ibox, next_Ibox, wmask, next_wmask, evaluation_data,\r\n\t\t is_train, is_show=is_show)\r\n\r\n\t\treturn res\r\n\r\n\tdef save_to_file(self, file_name, contents):\r\n\t\tfh = open(file_name, 'w')\r\n\t\tfh.write(contents)\r\n\t\tfh.close()\r\n\r\n\tdef train_to_mask1(self, train_list, I, bgimage, nextI, Ibox, next_Ibox, dynamics_mask, next_dynamics_mask,\r\n\t wmask, next_wmask, bbox_coor, is_train):\r\n\r\n\t\t# I, nextI, bgimage: [batch, width, height, channel]\r\n\t\t# Ibox, next_Ibox: [list(batch), num_select_box, old_b_width, b_height, channel]\r\n\t\t# dynamics_mask, next_dynamics_mask: [list(batch), num_select_box, old_b_width, b_height]\r\n\t\t# wmask, next_wmask: [batch, width, height]\r\n\t\t# bbox_coor: [list(batch), num_select_box, 4] (width_1, width_2, height_1, height_2)\r\n\t\t#\r\n\t\t# CV_BATCH_SIZE | BATCH_SIZE * num_box\r\n\r\n\t\tt_shuffle = []\r\n\t\tbox_num_list = []\r\n\r\n\t\tfor i in range(self.BATCH_SIZE):\r\n\r\n\t\t\tt_copy = [Ibox[i].copy(), next_Ibox[i].copy(),\r\n\t\t\t np.expand_dims(dynamics_mask[i], 3), np.expand_dims(next_dynamics_mask[i], 3)]\r\n\t\t\tt_copy = np.concatenate(t_copy, axis=3)\r\n\r\n\t\t\t# t_copy: [each_batch_num, old_b_width, b_height, channel * 2 + 2]\r\n\r\n\t\t\tbox_num = Ibox[i].shape[0]\r\n\t\t\tbox_num_list.append(box_num)\r\n\r\n\t\t\t# ---------------------\r\n\r\n\t\t\tt_index = collections.defaultdict(list)\r\n\t\t\tpre_index = collections.defaultdict(int)\r\n\t\t\tchoose_index = collections.defaultdict(list)\r\n\r\n\t\t\tfor j in range(box_num):\r\n\t\t\t\trandom_flag = True\r\n\t\t\t\tkey_1 = bbox_coor[i][j, 1] - bbox_coor[i][j, 0]\r\n\t\t\t\tt_index[key_1].append(j)\r\n\t\t\t\tif (j + 1 < box_num):\r\n\t\t\t\t\tkey_2 = bbox_coor[i][j + 1, 1] - bbox_coor[i][j + 1, 0]\r\n\t\t\t\t\tif (key_1 == key_2):\r\n\t\t\t\t\t\trandom_flag = False\r\n\t\t\t\tif (random_flag):\r\n\t\t\t\t\tindex_start = pre_index[key_1]\r\n\t\t\t\t\tindex_end = len(t_index[key_1])\r\n\t\t\t\t\tfor k in range(self.shuffle_times):\r\n\t\t\t\t\t\tnp.random.shuffle(t_index[key_1][index_start: index_end])\r\n\t\t\t\t\tif (index_start + 1 < index_end):\r\n\t\t\t\t\t\tchoose_index[key_1].extend([x for x in range(index_start, index_end - 1)])\r\n\t\t\t\t\tpre_index[key_1] = index_end\r\n\r\n\t\t\tt_num_scale = len(choose_index)\r\n\t\t\tassert (t_num_scale > 0)\r\n\r\n\t\t\tt_box_type_list = []\r\n\t\t\tfor key in choose_index.keys():\r\n\t\t\t\tt_box_type_list.append(key)\r\n\t\t\t\tfor k in range(self.shuffle_times):\r\n\t\t\t\t\tnp.random.shuffle(choose_index[key])\r\n\r\n\t\t\tt_index_stamp = collections.defaultdict(int)\r\n\r\n\t\t\tfor j in range(self.num_box // 2):\r\n\r\n\t\t\t\t# expected to be t_num_scale (3 or 4) * 3 types and self.num_box to be 24 or 18\r\n\t\t\t\tseed_1 = j % (t_num_scale * 3)\r\n\t\t\t\tseed_2 = seed_1 % t_num_scale\r\n\t\t\t\tseed_3 = seed_1 / t_num_scale\r\n\r\n\t\t\t\tkey = t_box_type_list[seed_2]\r\n\r\n\t\t\t\tt_index_1 = t_index_stamp[key]\r\n\t\t\t\tt_index_2 = choose_index[key][t_index_1]\r\n\t\t\t\tt_index_3 = t_index[key][t_index_2]\r\n\t\t\t\tt_index_4 = t_index[key][t_index_2 + 1]\r\n\r\n\t\t\t\tif (t_index_1 + 1 >= len(choose_index[key])):\r\n\t\t\t\t\tt_index_stamp[key] = 0\r\n\t\t\t\t\tfor k in range(self.shuffle_times):\r\n\t\t\t\t\t\tnp.random.shuffle(choose_index[key])\r\n\t\t\t\t\t'''\r\n\t\t\t\t\tprint('warning!')\r\n\t\t\t\t\tprint('box_assert')\r\n\t\t\t\t\tprint(key)\r\n\t\t\t\t\tprint(choose_index[key])\r\n\t\t\t\t\tprint(box_num)\r\n\t\t\t\t\timsave(self.warning_path + 'I_' + '.jpg', np.transpose(I[i], [1, 0, 2]))\r\n\t\t\t\t\timsave(self.warning_path + 'I_next_' + '.jpg', np.transpose(nextI[i], [1, 0, 2]))\r\n\t\t\t\t\tself.save_to_file(self.warning_path + 'box_assert.txt', str(datetime.datetime.now()))\r\n\t\t\t\t\t'''\r\n\t\t\t\telse:\r\n\t\t\t\t\tt_index_stamp[key] += 1\r\n\r\n\t\t\t\tbox_same_flag = np.all(bbox_coor[i][t_index_3] == bbox_coor[i][t_index_4])\r\n\t\t\t\tinstance_1 = t_copy[t_index_3].copy()\r\n\t\t\t\tinstance_2 = t_copy[t_index_4].copy()\r\n\r\n\t\t\t\tinstance_1 = np.pad(instance_1, [[0, self.pad_b_width], [0, 0], [0, 0]], 'constant')\r\n\r\n\t\t\t\t# instance_1: [old_b_width + pad_b_width, b_height, channel * 2 + 2]\r\n\t\t\t\t# instance_2: [old_b_width, b_height, channel * 2 + 2]\r\n\r\n\t\t\t\t'''\r\n\t\t\t\tif (box_same_flag):\r\n\t\t\t\t\tprint('warning!')\r\n\t\t\t\t\tprint('box_assert')\r\n\t\t\t\t\tprint(key)\r\n\t\t\t\t\tprint(choose_index[key])\r\n\t\t\t\t\tprint(box_num)\r\n\t\t\t\t\timsave(self.warning_path + 'I_' + '.jpg', np.transpose(I[i], [1, 0, 2]))\r\n\t\t\t\t\timsave(self.warning_path + 'I_next_' + '.jpg', np.transpose(nextI[i], [1, 0, 2]))\r\n\t\t\t\t\tself.save_to_file(self.warning_path + 'box_assert.txt', str(datetime.datetime.now()))\r\n\t\t\t\t'''\r\n\r\n\t\t\t\tif (seed_3 == 0 or box_same_flag):\r\n\t\t\t\t\tt_shuffle.append(np.concatenate([instance_1, instance_2 * 0.], axis=0))\r\n\t\t\t\t\tt_shuffle.append(np.concatenate([instance_1 * 0., instance_2], axis=0))\r\n\t\t\t\telse:\r\n\t\t\t\t\ttmp = instance_2.copy()\r\n\t\t\t\t\ttmp[:, :, self.CHANNELS: self.CHANNELS * 2] = 0.\r\n\t\t\t\t\ttmp[:, :, self.CHANNELS * 2 + 1:] = 0.\r\n\t\t\t\t\tt_shuffle.append(np.concatenate([instance_1, tmp], axis=0))\r\n\r\n\t\t\t\t\ttmp = instance_1.copy()\r\n\t\t\t\t\ttmp[:, :, self.CHANNELS: self.CHANNELS * 2] = 0.\r\n\t\t\t\t\ttmp[:, :, self.CHANNELS * 2 + 1:] = 0.\r\n\t\t\t\t\tt_shuffle.append(np.concatenate([tmp, instance_2], axis=0))\r\n\r\n\t\tt_shuffle = np.array(t_shuffle)\r\n\t\tfor k in range(self.shuffle_times):\r\n\t\t\tnp.random.shuffle(t_shuffle)\r\n\r\n\t\tif (self.mpi_rank == 0 and is_train):\r\n\t\t\tprint('Mean number of box in a batch :', np.mean(box_num_list))\r\n\r\n\t\tres = []\r\n\r\n\t\tfor i in range(t_shuffle.shape[0] // self.CV_BATCH_SIZE):\r\n\t\t\tl = i * self.CV_BATCH_SIZE\r\n\t\t\tr = (i + 1) * self.CV_BATCH_SIZE\r\n\t\t\ttmp = self.CHANNELS * 2\r\n\r\n\t\t\twith self.graph.as_default():\r\n\t\t\t\tt_res = self.sess.run(train_list, feed_dict={\r\n\t\t\t\t\tself.input_Ibox: t_shuffle[l: r, :, :, :self.CHANNELS],\r\n\t\t\t\t\tself.input_next_Ibox: t_shuffle[l: r, :, :, self.CHANNELS: tmp],\r\n\t\t\t\t\tself.input_dmask: t_shuffle[l: r, :, :, tmp],\r\n\t\t\t\t\tself.input_next_dmask: t_shuffle[l: r, :, :, tmp + 1],\r\n\t\t\t\t\tself.is_train: is_train\r\n\t\t\t\t})\r\n\r\n\t\t\tres.append(t_res)\r\n\r\n\t\treturn res\r\n\r\n\tdef update(self, I, bgimage, nextI, Ibox, next_Ibox, dynamics_mask, next_dynamics_mask,\r\n\t wmask, next_wmask, bbox_coor,\r\n\t test_obset, test_bgimageset, test_nextobset, test_batch_num,\r\n\t box_get_proposal=None):\r\n\r\n\t\tt_1 = time.time()\r\n\t\tcost = self.train_to_mask1([self.train_total_op, self.Total_loss],\r\n\t\t I, bgimage, nextI, Ibox, next_Ibox,\r\n\t\t dynamics_mask, next_dynamics_mask, wmask, next_wmask, bbox_coor,\r\n\t\t is_train=True)\r\n\t\tif (self.mpi_rank == 0):\r\n\t\t\tprint('Training mask1:', time.time() - t_1)\r\n\r\n\t\tself.step += 1\r\n\r\n\t\txplot.plot('mask1_cost', np.mean(np.array(cost)[:, 1]))\r\n\r\n\t\tif self.step % self.log_time == 0:\r\n\t\t\twith self.graph.as_default():\r\n\t\t\t\tself.saver.save(self.sess, self.path + 'saved_mask1_networks/', global_step=self.step)\r\n\r\n\t\tif self.step % self.summary_time == 0:\r\n\t\t\tsummary_str = self.train_to_mask1(self.summary_op, I, bgimage, nextI, Ibox, next_Ibox,\r\n\t\t\t dynamics_mask, next_dynamics_mask, wmask, next_wmask, bbox_coor,\r\n\t\t\t is_train=True)\r\n\r\n\t\t\tself.train_writer.add_summary(summary_str[0], self.step)\r\n\t\t\tself.train_writer.flush()\r\n\r\n\t\tif self.step % self.test_time == 0:\r\n\r\n\t\t\ttest_Ibox, test_next_Ibox, test_dynamics_mask, test_next_dynamics_mask, test_wmask, test_next_wmask, \\\r\n\t\t\ttest_bbox_coor = [], [], [], [], [], [], []\r\n\r\n\t\t\tfor i in range(test_batch_num):\r\n\t\t\t\tt_Ibox, t_next_Ibox, t_dynamics_mask, t_next_dynamics_mask, t_wmask, t_next_wmask, t_bbox_coor = \\\r\n\t\t\t\t\tbox_get_proposal(test_obset[i], test_nextobset[i], test_bgimageset[i])\r\n\r\n\t\t\t\ttest_Ibox.append(t_Ibox)\r\n\t\t\t\ttest_next_Ibox.append(t_next_Ibox)\r\n\t\t\t\ttest_dynamics_mask.append(t_dynamics_mask)\r\n\t\t\t\ttest_next_dynamics_mask.append(t_next_dynamics_mask)\r\n\t\t\t\ttest_wmask.append(t_wmask)\r\n\t\t\t\ttest_next_wmask.append(t_next_wmask)\r\n\t\t\t\ttest_bbox_coor.append(t_bbox_coor)\r\n\r\n\t\t\ttest_closses = []\r\n\t\t\tfor i in range(test_batch_num):\r\n\t\t\t\ttest_closs = self.train_to_mask1([self.Total_loss],\r\n\t\t\t\t test_obset[i], test_bgimageset[i], test_nextobset[i],\r\n\t\t\t\t test_Ibox[i], test_next_Ibox[i],\r\n\t\t\t\t test_dynamics_mask[i], test_next_dynamics_mask[i],\r\n\t\t\t\t test_wmask[i], test_next_wmask[i], test_bbox_coor[i],\r\n\t\t\t\t is_train=False)\r\n\t\t\t\ttest_closses.append(np.mean(test_closs))\r\n\r\n\t\t\tsummary_str = self.train_to_mask1(self.summary_op,\r\n\t\t\t test_obset[i], test_bgimageset[i], test_nextobset[i],\r\n\t\t\t test_Ibox[i], test_next_Ibox[i],\r\n\t\t\t test_dynamics_mask[i], test_next_dynamics_mask[i],\r\n\t\t\t test_wmask[i], test_next_wmask[i], test_bbox_coor[i],\r\n\t\t\t is_train=False)\r\n\r\n\t\t\tself.test_writer.add_summary(summary_str[0], self.step)\r\n\t\t\tself.test_writer.flush()\r\n\r\n\t\t\ttrain_ccost = self.train_to_mask1([self.Total_loss], I, bgimage, nextI, Ibox, next_Ibox,\r\n\t\t\t dynamics_mask, next_dynamics_mask, wmask, next_wmask, bbox_coor,\r\n\t\t\t is_train=True)\r\n\r\n\t\t\txplot.plot('Train_mask1_C_loss', np.mean(train_ccost))\r\n\r\n\t\t\txplot.plot('Test_mask1_C_loss', np.mean(test_closses))\r\n\r\n\tdef worker_update(self):\r\n\r\n\t\tdef selection_booster():\r\n\r\n\t\t\tdef Receive_numpy(source=0, tag=15):\r\n\t\t\t\tt_data = []\r\n\t\t\t\tfor i in range(self.cpu_batch_size):\r\n\t\t\t\t\ttmp_data = utils.Receive_numpy(source=source, tag=tag)\r\n\t\t\t\t\tt_data.append(tmp_data)\r\n\t\t\t\treturn t_data\r\n\r\n\t\t\tis_show = self.comm.recv(source=0, tag=18)\r\n\r\n\t\t\tdata = utils.Receive_numpy(source=0, tag=19)\r\n\t\t\tI, nextI, wmask, next_wmask = data\r\n\r\n\t\t\tdata = Receive_numpy(source=0, tag=15)\r\n\t\t\tbatch_cache = data\r\n\r\n\t\t\tbatch_dynamics_instances_K = defaultlist(list)\r\n\t\t\tshow_instances_cpu_size = []\r\n\t\t\tselection_num_list = []\r\n\r\n\t\t\tfor i in range(self.cpu_batch_size):\r\n\t\t\t\ttmp_Ibox, tmp_Ibox_next, tmp_mask, tmp_mask_next, tmp_bbox, tmp_label = batch_cache[i]\r\n\t\t\t\tt_dynamics_instances = self.box_selector.get_selection(I[i], nextI[i], tmp_Ibox, tmp_Ibox_next,\r\n\t\t\t\t tmp_mask, tmp_mask_next, tmp_bbox, tmp_label)\r\n\t\t\t\tt_dynamics_instances_K, box_selected_num = \\\r\n\t\t\t\t\tself.box_choose_K(t_dynamics_instances, self.dynamic_object_instance_box_maxnum)\r\n\t\t\t\t# (return_label, return_C, return_next_C, return_Ms, return_Md)\r\n\t\t\t\tfor t_stamp_K, item in enumerate(t_dynamics_instances_K):\r\n\t\t\t\t\tbatch_dynamics_instances_K[t_stamp_K].append(item)\r\n\t\t\t\tselection_num_list.append(box_selected_num)\r\n\t\t\t\tif (is_show):\r\n\t\t\t\t\tshow_instances_cpu_size.append(t_dynamics_instances)\r\n\r\n\t\t\tres = []\r\n\t\t\tfor item in batch_dynamics_instances_K:\r\n\t\t\t\tres.append(np.array(item))\r\n\r\n\t\t\tutils.Transmit_numpy(res, mpi_id=0, tag=16)\r\n\t\t\tself.comm.send(selection_num_list, dest=0, tag=17)\r\n\r\n\t\t\tif (is_show):\r\n\t\t\t\tself.show_selection(I, nextI, wmask, next_wmask, batch_cache, show_instances_cpu_size)\r\n\r\n\t\t#self.step += 1\r\n\r\n\t\t# selection booster\r\n\t\tis_running_selection = self.comm.recv(source=0, tag=14)\r\n\r\n\t\tif (self.mpi_rank < self.s_mpi_size):\r\n\r\n\t\t\twhile (is_running_selection):\r\n\t\t\t\tselection_booster()\r\n\t\t\t\tis_running_selection = self.comm.recv(source=0, tag=14)\r\n\r\n","sub_path":"monsterkong/mask17.py","file_name":"mask17.py","file_ext":"py","file_size_in_byte":57510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"332020038","text":"import turtle\nwn = turtle.Screen()\nwn.bgcolor(\"black\")\nwn.tracer(False) # turns animation off\n#wn.title(\"L-System\")\ngreg = turtle.Turtle()\ngreg.color('green')\ngreg.hideturtle() # need to do this with tracer false\ngreg.speed('fastest')\ngreg.penup()\ngreg.goto(0,-600)\ngreg.pendown()\ngreg.left(90)\nstack =[]\n\ndef expand(currgen):\n\tglobal rule\n\tnextgen =\"\"\n\tfor char in currgen:\n\t\tif char == \"F\":\n\t\t\tnextgen+=rule\n\t\telse:\n\t\t\tnextgen+=char\n\treturn nextgen\n\t\ndef cntChr(lst, str):\n\t#list of characters\n\tcount = 0\n\tfor i in str:\n\t\tif i in lst:\n\t\t\tcount =count +1\n\t\t\t\n\treturn count\n\n\ndef plotturt(instructions, angle):\n global stack\n for chr in instructions:\n if chr == 'F':\n greg.forward(10)\n elif chr == '+':\n greg.right(angle)\n elif chr == '-':\n greg.left(angle)\n elif chr == '[':\n ang=greg.heading()\n pos=[greg.xcor(),greg.ycor()] #pos appended as a list index 0 = x indext 1 = y\n stack.append((ang,pos))\n \n \n elif chr == ']':\n ang,pos = stack.pop()\n greg.setheading(ang)\n greg.penup()\n greg.goto(pos[0],pos[1]) # at index of appended lists are x and y vals\n greg.pendown()\n \n\n\n#axiom=\"F\"\naxiom = \"F\"\nrule=\"F-F++F-F\"\ndna=axiom\nfor g in range(1,5):\n\tdna = expand(dna)\n\tprint('this is gen', g, 'dna len', len(dna), 'dna', dna)\n\tprint(\"number of Fs\",cntChr([\"F\"],dna))\n\tprint(\"number of terminal chr\",cntChr([\"+\",\"-\",\"[\",\"]\"],dna))\n\tprint(\"total number of chars:\",len(dna))\n\n\nplotturt(dna,60)\nwn.exitonclick()\n","sub_path":"PythonLSystemsExtraModule3Fractals/lsystem3bintree.py","file_name":"lsystem3bintree.py","file_ext":"py","file_size_in_byte":1598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"216851512","text":"# Prolog\n# Author: David Yurek\n# Section 012\n# Sept. 11, 2013\n# Lab 4 \n\n# Defines main()\ndef main():\n \n # Defines the height variables, gravity variable, and assigns values via input from the user.\n firstS_height = float(input(\"Enter the height for the first sphere: \"))\n secondS_height = float(input(\"Enter the height for the second sphere: \"))\n thirdS_height = float(input(\"Enter the height for the third sphere: \"))\n g = 9.81\n \n # Calculates the fall time using the equation given and the height variables.\n firstS_time = (2*firstS_height/g)**(1/2)\n secondS_time = (2*secondS_height/g)**(1/2)\n thirdS_time = (2*thirdS_height/g)**(1/2)\n \n # Calculates the total time by adding the three time variables.\n total_time = firstS_time + secondS_time + thirdS_time\n \n # Rounds the time variables to the appropriate decimal places.\n firstS_time = round(firstS_time, 3)\n secondS_time = round(secondS_time, 3)\n thirdS_time = round(thirdS_time, 3)\n total_time = round(total_time, 5)\n \n # Prints the final information from the rounded variables.\n print(\"Time for the first shpere to fall is\", firstS_time, \"seconds.\")\n print(\"Time for the second shpere to fall is\", secondS_time, \"seconds.\")\n print(\"Time for the third shpere to fall is\", thirdS_time, \"seconds.\")\n print(\"The total time is \", total_time, \"seconds.\")\n \n# Calls main() \nmain()\n ","sub_path":"lab4.py","file_name":"lab4.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"91958688","text":"#!/usr/bin/env python3\n#\n# Copyright (c) 2018-present, Facebook, Inc.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport argparse\nimport platform\nimport re\nfrom pathlib import Path\n\n\ndef is_linux() -> bool:\n return platform.system() == \"Linux\"\n\n\ndef valid_typeshed(typeshed_path: str) -> str:\n path = Path(typeshed_path).absolute() / \"stdlib\"\n if path.is_dir():\n return typeshed_path\n raise ValueError(\n \"The provided typeshed directory is not in the expected format: \\\n It does not contain a 'stdlib' directory.\"\n )\n\n\ndef valid_version(version: str) -> str:\n pattern = re.compile(r\"^[0-9]+\\.[0-9]+\\.[0-9]+$\")\n if pattern.match(version):\n return version\n raise ValueError(\"Invalid version format.\")\n\n\ndef main() -> None:\n parser = argparse.ArgumentParser(description=\"Build a PyPi Package.\")\n parser.add_argument(\"--typeshed-path\", type=valid_typeshed, required=True)\n parser.add_argument(\"--version\", type=valid_version, required=True)\n\n _ = parser.parse_args()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"scripts/build_pypi_package.py","file_name":"build_pypi_package.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"398685755","text":"import re\nimport time\nimport requests\nfrom lxml import etree\nfrom kuaishou.analyze_num import Analy\n\nanaly = Analy()\n\nfor i in range(157494640, 157494660):\n time.sleep(1)\n keyword = str(i)\n\n url = 'https://live.kuaishou.com/search/?keyword=%s' % (keyword)\n\n headers = {\n \"Host\": \"live.kuaishou.com\",\n \"Connection\": \"keep-alive\",\n \"Cache-Control\": \"max-age=0\",\n \"Upgrade-Insecure-Requests\": \"1\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36\",\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\n \"Referer\": \"https://live.kuaishou.com/search/?keyword=%E4%B8%B9%E4%B8%B9\",\n \"Accept-Encoding\": \"gzip, deflate, br\",\n \"Accept-Language\": \"zh-CN,zh;q=0.9\",\n \"Cookie\": \"did=web_89670e2b3c892184a0452f79ea15f9b4; didv=1557212874570; clientid=3; client_key=65890b29; needLoginToWatchHD=1; Hm_lvt_86a27b7db2c5c0ae37fee4a8a35033ee=1557212874,1557283015; __lfcc=1; kuaishou.live.bfb1s=ac5f27b3b62895859c4c1622f49856a4\"\n }\n\n res = requests.get(url=url, headers=headers)\n # print(res.text)\n\n con1 = re.findall(r'相关用户', res.text)\n\n if con1:\n con = etree.HTML(res.text)\n\n user_name = con.xpath('//div[@class=\"profile-card-user-info-detail\"]//h4//text()')[0].strip()\n print(user_name)\n\n fan = con.xpath('//p[@class=\"profile-card-user-info-counts\"]/text()')[0].split()[0].replace('粉丝', '')\n fans = analy.parsingChar(fan)\n print('fans', fans)\n\n follow = con.xpath('//p[@class=\"profile-card-user-info-counts\"]/text()')[0].split()[1].replace('关注', '')\n follows = analy.parsingChar(follow)\n print('follows', follows)\n\n photo = con.xpath('//p[@class=\"profile-card-user-info-counts\"]/text()')[0].split()[2].replace('作品', '')\n photos = analy.parsingChar(photo)\n print('photos', photos)\n\n profile = con.xpath('//div[@class=\"profile-card-user-info-detail\"]//h4/a/@href')[0].replace(r'/profile/', '')\n print('profile', profile)\n print('*' * 30)\n else:\n print(keyword)\n print('ID 为空号...')","sub_path":"ergodic_all_to_get_id.py","file_name":"ergodic_all_to_get_id.py","file_ext":"py","file_size_in_byte":2232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"155632907","text":"#!/usr/bin/env python3\n__author__ = 'dimv36'\nfrom argparse import ArgumentParser\nfrom os.path import abspath, curdir, exists\nfrom sys import argv\nfrom time import localtime, strftime\nfrom polib import pofile\n\nEMAIL = 'support@rusbitech.ru'\nTRANSLATOR = 'Dmitry Voronin'\n\n\ndef find_translated_message(msgid, old_po):\n for old_entry in old_po:\n if old_entry.msgid == msgid:\n return old_entry.msgstr\n return None\n\n\ndef update_metadata(new_po_file):\n metadata = new_po_file.metadata\n now = strftime('%Y-%m-%d %H:%M+0400', localtime())\n metadata['Report-Msgid-Bugs-To'] = EMAIL\n metadata['POT-Creation-Date'] = now\n metadata['PO-Revision-Date'] = now\n metadata['Last-Translator'] = '%s <%s>' % (TRANSLATOR, EMAIL)\n metadata['Language-Team'] = 'Russian <%s>' % EMAIL\n\n\ndef update_po(old_po_file_path, new_po_file_path, updated_po_file_path):\n was_update = False\n old_po = pofile(old_po_file_path)\n new_po = pofile(new_po_file_path)\n updated_po_file_path = abspath(updated_po_file_path)\n for new_entry in new_po.untranslated_entries():\n msgstr = find_translated_message(new_entry.msgid, old_po)\n if msgstr is not None:\n new_entry.msgstr = msgstr\n was_update = True\n for new_entry in new_po.fuzzy_entries():\n msgstr = find_translated_message(new_entry.msgid, old_po)\n if msgstr is not None:\n new_entry.msgstr = msgstr\n new_entry.flags.remove('fuzzy')\n was_update = True\n for new_entry in new_po.translated_entries():\n msgid = new_entry.msgid\n msgstr = new_entry.msgstr\n if 'column' in msgid:\n msgstr = find_translated_message(msgid, old_po)\n if msgstr is not None:\n new_entry.msgstr = msgstr\n was_update = True\n if msgstr is not None:\n if 'колон' in msgstr or 'Колон' in msgstr:\n msgstr = find_translated_message(msgid, old_po)\n if msgstr is not None:\n new_entry.msgstr = msgstr\n was_update = True\n if was_update:\n update_metadata(new_po)\n print('Done. New po was saved to %s' % updated_po_file_path)\n new_po.save(updated_po_file_path)\n\n\ndef get_statistic(po_file_path):\n try:\n po = pofile(po_file_path)\n print('***** Message statistic for \\'%s\\' *****' % po_file_path)\n print('translated: %d, fuzzy: %d, untranslated: %d' % (len(po.translated_entries()),\n len(po.fuzzy_entries()), len(po.untranslated_entries())))\n except OSError:\n print('Error when open file \\'%s\\': No such file' % po_file_path)\n\n\ndef check_is_path_exist(file_path):\n file_path = abspath(file_path)\n if not exists(file_path):\n print('Error: file \\'%s\\' does not exist' % abspath(file_path))\n exit(1)\n return file_path\n\n\nif __name__ == '__main__':\n arg_parser = ArgumentParser(prog=argv[0], add_help=False)\n\n subparsers = arg_parser.add_subparsers(dest='commands')\n\n update_po_parser = subparsers.add_parser('update-po')\n update_po_parser.add_argument('--old-po', action='store', required=True, help='Add path to old po file')\n update_po_parser.add_argument('--new-po', action='store', required=True, help='Add path to new po file')\n update_po_parser.add_argument('--save-as', action='store', help='Save updated po as',\n default=abspath(curdir + '/update.po'))\n\n statistic_po_parser = subparsers.add_parser('get-statistic')\n statistic_po_parser.add_argument('--po-file', action='store', required=True, help='Get statistic about po file')\n\n args = arg_parser.parse_args(argv[1:])\n if args.commands is not None:\n command = args.commands\n if command == 'update-po':\n old_po = args.old_po\n new_po = args.new_po\n save_po = args.save_as\n if old_po is not None and new_po is not None:\n old_po = check_is_path_exist(old_po)\n new_po = check_is_path_exist(new_po)\n update_po(old_po, new_po, save_po)\n else:\n update_po_parser.print_help()\n elif command == 'get-statistic':\n po_file = args.po_file\n if po_file is not None:\n po_file = check_is_path_exist(po_file)\n get_statistic(po_file)\n else:\n statistic_po_parser.print_help()\n else:\n arg_parser.print_help()\n","sub_path":"poedit.py","file_name":"poedit.py","file_ext":"py","file_size_in_byte":4549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"365012307","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n# Copyright 2013 Herve BREDIN (bredin@limsi.fr)\n\n# This file is part of PyAnnote.\n#\n# PyAnnote 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# PyAnnote 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 PyAnnote. If not, see .\n\n\nimport scipy.io.wavfile\nimport yaafelib\nfrom pyannote.core.feature import SlidingWindowFeature\nfrom pyannote.core.segment import SlidingWindow\nimport numpy as np\n\n\nclass YaafeFrame(SlidingWindow):\n \"\"\"Yaafe frames\n\n Parameters\n ----------\n blockSize : int, optional\n Window size (in number of samples). Default is 512.\n stepSize : int, optional\n Step size (in number of samples). Default is 256.\n sampleRate : int, optional\n Sample rate (number of samples per second). Default is 16000.\n\n References\n ----------\n http://yaafe.sourceforge.net/manual/quickstart.html\n\n \"\"\"\n def __init__(self, blockSize=512, stepSize=256, sampleRate=16000):\n\n duration = 1. * blockSize / sampleRate\n step = 1. * stepSize / sampleRate\n start = -0.5 * duration\n\n super(YaafeFrame, self).__init__(\n duration=duration, step=step, start=start\n )\n\n\nclass YaafeFeatureExtractor(object):\n \"\"\"\n\n Parameters\n ----------\n sample_rate : int, optional\n Defaults to 16000 (i.e. 16kHz)\n block_size : int, optional\n Defaults to 512.\n step_size : int, optional\n Defaults to 256.\n\n \"\"\"\n\n def __init__(\n self, sample_rate=16000, block_size=512, step_size=256\n ):\n\n super(YaafeFeatureExtractor, self).__init__()\n\n self.sample_rate = sample_rate\n self.block_size = block_size\n self.step_size = step_size\n\n def get_flow_and_stack(self, **kwargs):\n raise NotImplementedError(\n 'get_flow_and_stack method must be implemented'\n )\n\n def extract(self, wav):\n \"\"\"Extract features\n\n Parameters\n ----------\n wav : string\n Path to wav file.\n\n Returns\n -------\n features : SlidingWindowFeature\n\n \"\"\"\n\n # hack\n data_flow, stack = self.get_flow_and_stack()\n\n engine = yaafelib.Engine()\n engine.load(data_flow)\n\n sample_rate, raw_audio = scipy.io.wavfile.read(wav)\n assert sample_rate == self.sample_rate, \"sample rate mismatch\"\n\n audio = np.array(raw_audio, dtype=np.float64, order='C').reshape(1, -1)\n\n features = engine.processAudio(audio)\n data = np.hstack([features[name] for name in stack])\n\n sliding_window = YaafeFrame(\n blockSize=self.block_size, stepSize=self.step_size,\n sampleRate=self.sample_rate)\n\n return SlidingWindowFeature(data, sliding_window)\n\n\nclass YaafeMFCC(YaafeFeatureExtractor):\n\n \"\"\"\n | e | energy\n | c1 |\n | c2 | coefficients\n | c3 |\n | ... |\n | Δe | energy first derivative\n | Δc1 |\n x = | Δc2 | coefficients first derivatives\n | Δc3 |\n | ... |\n | ΔΔe | energy second derivative\n | ΔΔc1 |\n | ΔΔc2 | coefficients second derivatives\n | ΔΔc3 |\n | ... |\n\n\n Parameters\n ----------\n\n sample_rate : int, optional\n Defaults to 16000 (i.e. 16kHz)\n block_size : int, optional\n Defaults to 512.\n step_size : int, optional\n Defaults to 256.\n\n e : bool, optional\n Energy. Defaults to True.\n coefs : int, optional\n Number of coefficients. Defaults to 11.\n De : bool, optional\n Keep energy first derivative. Defaults to False.\n D : bool, optional\n Add first order derivatives. Defaults to False.\n DDe : bool, optional\n Keep energy second derivative. Defaults to False.\n DD : bool, optional\n Add second order derivatives. Defaults to False.\n\n Notes\n -----\n Default Yaafe values:\n * fftWindow = Hanning\n * melMaxFreq = 6854.0\n * melMinFreq = 130.0\n * melNbFilters = 40\n\n \"\"\"\n\n def __init__(\n self, sample_rate=16000, block_size=512, step_size=256,\n e=True, coefs=11, De=False, DDe=False, D=False, DD=False,\n ):\n\n super(YaafeMFCC, self).__init__(\n sample_rate=sample_rate,\n block_size=block_size,\n step_size=step_size\n )\n\n self.e = e\n self.coefs = coefs\n self.De = De\n self.DDe = DDe\n self.D = D\n self.DD = DD\n\n def get_flow_and_stack(self):\n\n feature_plan = yaafelib.FeaturePlan(sample_rate=self.sample_rate)\n stack = []\n\n # --- coefficients\n # 0 if energy is kept\n # 1 if energy is removed\n definition = (\n \"mfcc: \"\n \"MFCC CepsIgnoreFirstCoeff=%d CepsNbCoeffs=%d \"\n \"blockSize=%d stepSize=%d\" % (\n 0 if self.e else 1,\n self.coefs + self.e * 1,\n self.block_size, self.step_size\n )\n )\n assert feature_plan.addFeature(definition)\n stack.append('mfcc')\n\n # --- 1st order derivatives\n if self.D or self.De:\n definition = (\n \"mfcc_d: \"\n \"MFCC CepsIgnoreFirstCoeff=%d CepsNbCoeffs=%d \"\n \"blockSize=%d stepSize=%d > Derivate DOrder=1\" % (\n 0 if self.De else 1,\n self.D * self.coefs + self.De * 1,\n self.block_size, self.step_size\n )\n )\n assert feature_plan.addFeature(definition)\n stack.append('mfcc_d')\n\n # --- 2nd order derivatives\n if self.DD or self.DDe:\n definition = (\n \"mfcc_dd: \"\n \"MFCC CepsIgnoreFirstCoeff=%d CepsNbCoeffs=%d \"\n \"blockSize=%d stepSize=%d > Derivate DOrder=2\" % (\n 0 if self.DDe else 1,\n self.DD * self.coefs + self.DDe * 1,\n self.block_size, self.step_size\n )\n )\n assert feature_plan.addFeature(definition)\n stack.append('mfcc_dd')\n\n # --- prepare the Yaafe engine\n data_flow = feature_plan.getDataFlow()\n\n return data_flow, stack\n","sub_path":"pyannote/features/audio/yaafe.py","file_name":"yaafe.py","file_ext":"py","file_size_in_byte":6788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"563379694","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport cv2\nimport os\nfrom skimage.feature import local_binary_pattern\n\nMETHOD = 'uniform'\nscript_path = os.path.dirname(os.path.realpath(__file__))\n\n# settings for LBP\nradius = 2\nn_points = 2 * radius\ndataset = {}\n\n########################################\n#membaca dataset dan menyimpan ke dictionary\n\nmaps_path = r\"D:\\Teknik Informatika\\CV\\citra02\\citra02\\dataset\"\n# maps_path = os.path.join(script_path, \"dataset\")\nlistds = os.listdir(maps_path)\nnumber_files = len(listds)\n\nos.chdir(maps_path)\narr = os.listdir()\n\nj = 31\nfor i in range(number_files):\n\t\n\timage_name = arr[i]\n\timage = cv2.imread(image_name, 0)\n\tlbp = local_binary_pattern(image, n_points, radius, METHOD)\n\n\thist, _ = np.histogram(lbp, density=True, bins=6, range=(0,6))\n\n\n\tif(j==41):\n\t\tj+=1\n\telif(j==58):\n\t\tj+=2\n\n\tnrp = '21031810' + str(j)\n\n\tdataset.update({nrp : hist})\n\tj+=1\n\nj=31\n\n###############################################\n#membandingkan fitur\n\ndef match(counts):\n\tbest_score = 10\n\tbest_name = None\n\tfor key,value in dataset.items():\n\t\tscore = 0\n\t\tfor o in range(6):\n\t\t\tscore+=abs(value[o]-counts[o])\n\t\tif score < best_score:\n\t\t\tbest_score = score\n\t\t\tbest_name = key\n\treturn best_name\n\n\n# maps_path = os.path.join(script_path, \"testing01\")\nmaps_path = r\"D:\\Teknik Informatika\\CV\\citra02\\citra02\\testing02\"\nlistds = os.listdir(maps_path)\nnumber_files = len(listds)\nos.chdir(maps_path)\narr = os.listdir()\n\ncounterOfStatus = 0\nfor i in range(number_files):\n\timage_name = arr[i]\n\timage = cv2.imread(image_name, 0)\n\tlbp = local_binary_pattern(image, n_points, radius, METHOD)\n\n\thist, _ = np.histogram(lbp, density=True, bins=6, range=(0,6))\n\n\tif(j==41):\n\t\tj+=1\n\telif(j==58):\n\t\tj+=2\n\n\tnrp = '21031810' + str(j)\n\n\tstatus = \"Keluaran Tidak Cocok\"\n\tif(nrp == match(hist)):\n\t\tstatus = \"Keluaran Cocok\"\n\t\tcounterOfStatus+=1\n\n\tprint('Gambar : ' + image_name + '/NRP : ' + nrp)\n\tprint('Hasil : ' + match(hist) + '/Status : '+status)\n\tprint()\n\tj+=1\n\nprint('Hasil yang cocok = '+ str(counterOfStatus))\nprint('Hasil yang tidak cocok = '+ str(27 - counterOfStatus))","sub_path":"run_testing_project.py","file_name":"run_testing_project.py","file_ext":"py","file_size_in_byte":2075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"302701777","text":"#from selenium.webdriver.support.ui import Select\nfrom selenium import webdriver\nimport time\n#import math\nimport os\n\ntry: \n link = \"http://suninjuly.github.io/file_input.html\"\n browser = webdriver.Chrome()\n browser.get(link)\n\n first_name_input=browser.find_element_by_css_selector(\"input[name='firstname']\")\n first_name_input.send_keys(\"Ali\")\n last_name_input=browser.find_element_by_css_selector(\"input[name='lastname']\")\n last_name_input.send_keys(\"Baba\")\n email_input=browser.find_element_by_css_selector(\"input[name='email']\")\n email_input.send_keys(\"email\")\n file_input=browser.find_element_by_css_selector(\"input#file\")\n\n # получаем путь к директории текущего исполняемого файла\n current_dir = os.path.abspath(os.path.dirname(__file__))\n\n # добавляем к этому пути имя файла\n file_path = os.path.join(current_dir, 'lesson2_2_step8_file.txt')\n\n file_input.send_keys(file_path)\n\n submit_button=browser.find_element_by_css_selector(\".btn\")\n submit_button.click()\n\n \nfinally:\n # ожидание чтобы визуально оценить результаты прохождения скрипта\n time.sleep(10)\n # закрываем браузер после всех манипуляций\n browser.quit()\n","sub_path":"Scripts/Module2/lesson2_2_step8.py","file_name":"lesson2_2_step8.py","file_ext":"py","file_size_in_byte":1354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"278567547","text":"import json\nimport click\nfrom ..inspecting import InvalidProjectError, inspect_project\n\n\n@click.command()\ndef cli():\n \"\"\"Extract template variables from a project\"\"\"\n try:\n data = inspect_project()\n except InvalidProjectError as e:\n raise click.UsageError(str(e))\n click.echo(json.dumps(data, indent=4, sort_keys=True))\n","sub_path":"src/pyrepo/commands/inspect.py","file_name":"inspect.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"600760468","text":"# CSE1321L\n# Section 4\n# Term 1\n# Kevin Markley\n# Joseph Liou\n# Assignment 07\n\n\nclass IndexOfLargest:\n\n def __init__(self):\n self.nums = []\n for i in range(10):\n self.nums.append(int(input('Enter a number to add it to the list(up to 10): ')))\n\n def find_index(self):\n max_dig = 0\n for i in self.nums:\n if i > max_dig:\n max_dig = i\n print('Entered Integers:', self.nums)\n return self.nums.index(max_dig)\n\n\nindex_max = IndexOfLargest()\nprint('Index of largest value:', index_max.find_index())\n\n","sub_path":"Assignments/Liou_Joseph_Assignment_Seven/IndexOfLargest.py","file_name":"IndexOfLargest.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"280296008","text":"import logging\n\nch = logging.StreamHandler()\n# ch.setLevel(logging.DEBUG)\nch.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))\n\ndef get_logger(name):\n logger = logging.getLogger(name)\n logger.setLevel(logging.DEBUG)\n logger.addHandler(ch)\n # logger.info('avc')\n return logger\n","sub_path":"wvv/util/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"365044088","text":"import sys\nimport os\nimport json\nimport pickle\nimport pprint\nsys.path.append('../')\n\nimport torch\nimport torch.nn as nn\nimport numpy as np\nfrom bleu import bleu\nfrom cider import cider\n\nfrom base import framework\nimport encoder.pca\nimport decoder.att_rnn_rl\nimport d.full_sc\nimport model.util\n\nDEC = 'decoder'\nDIS = 'discriminator'\n\nclass ModelConfig(framework.GanModelConfig):\n def __init__(self):\n super(ModelConfig, self).__init__()\n\n self.subcfgs[DEC] = decoder.att_rnn_rl.Config()\n self.subcfgs[DIS] = d.full_sc.Config()\n\n self.strategy = 'beam'\n\n self.d_late_fusion = False\n self.d_quality_alpha = .8\n self.g_baseline = 'greedy'\n\n\ndef gen_cfg(**kwargs):\n cfg = ModelConfig()\n cfg.trn_batch_size = 64\n cfg.tst_batch_size = 64\n cfg.val_iter = -1\n cfg.monitor_iter = 100\n\n cfg.g_num_epoch = kwargs['g_num_epoch']\n cfg.g_base_lr = kwargs['g_lr']\n cfg.g_freeze = kwargs['g_freeze']\n cfg.g_freeze_epoch = kwargs['g_freeze_epoch']\n\n cfg.d_num_epoch = kwargs['d_num_epoch']\n cfg.d_base_lr = kwargs['d_lr']\n cfg.d_iter = kwargs['d_iter']\n cfg.d_val_acc = kwargs['d_val_acc']\n cfg.d_buffer_size = kwargs['d_buffer_size']\n cfg.d_late_fusion = kwargs['d_late_fusion']\n cfg.d_quality_alpha = kwargs['d_quality_alpha']\n cfg.g_baseline = kwargs['g_baseline']\n\n dec_cfg = cfg.subcfgs[DEC]\n dec_cfg.dim_embed = kwargs['dim_embed']\n dec_cfg.dim_att_ft = kwargs['dim_att_ft']\n dec_cfg.dropin = kwargs['g_dropin']\n dec_cfg.dropout = kwargs['g_dropout']\n dec_cfg.max_step = kwargs['max_step']\n dec_cfg.beam_width = kwargs['beam_width']\n dec_cfg.tied_key_val = kwargs['tied_key_val']\n dec_cfg.val_proj = kwargs['val_proj']\n dec_cfg.num_sample = kwargs['num_sample']\n\n cell_cfg = dec_cfg.subcfgs[decoder.att_rnn_rl.CELL]\n cell_cfg.dim_embed = kwargs['dim_embed']\n cell_cfg.dim_hidden = kwargs['dim_hidden']\n cell_cfg.dim_key = kwargs['dim_key']\n cell_cfg.dim_val = kwargs['dim_val']\n cell_cfg.num_att_ft = kwargs['num_att_ft']\n cell_cfg.dim_boom = kwargs['dim_boom']\n\n att_cfg = cell_cfg.subcfgs[decoder.att_rnn_rl.ATT]\n att_cfg.dim_hidden = kwargs['dim_hidden']\n att_cfg.dim_key = kwargs['dim_key']\n att_cfg.dim_val = kwargs['dim_val']\n att_cfg.num_att_ft = kwargs['num_att_ft']\n att_cfg.sim = kwargs['sim']\n\n dis_cfg = cfg.subcfgs[DIS]\n dis_cfg.dim_kernel = kwargs['dim_kernel']\n dis_cfg.num_kernel = kwargs['num_kernel']\n dis_cfg.noise = kwargs['d_noise']\n dis_cfg.dim_ft = kwargs['dim_ft']\n\n sent_enc_cfg = dis_cfg.subcfgs[d.simple.SE]\n sent_enc_cfg.cell = kwargs['cell']\n sent_enc_cfg.dim_embed = kwargs['dim_embed']\n sent_enc_cfg.dim_hidden = kwargs['dim_hidden']\n sent_enc_cfg.dropin = kwargs['d_noise']\n\n return cfg\n\n\nclass Model(nn.Module):\n def __init__(self, config):\n super(Model, self).__init__()\n\n self._config = config\n dec_cfg = self._config.subcfgs[DEC]\n dis_cfg = self._config.subcfgs[DIS]\n\n self.decoder = decoder.att_rnn_rl.Decoder(dec_cfg)\n self.discriminator = d.full_sc.Discriminator(dis_cfg)\n\n self.op2monitor = {}\n\n def forward(self, mode, **kwargs):\n if mode == 'g_trn':\n log_probs = kwargs['log_probs']\n log_masks = kwargs['log_masks']\n rewards = kwargs['rewards']\n\n b = rewards.size(0)\n loss = -rewards.view(b, 1) * log_probs\n loss = torch.sum(loss * log_masks) / torch.sum(log_masks)\n\n self.op2monitor['reward'] = rewards.mean()\n self.op2monitor['loss'] = loss\n\n return loss\n elif mode == 'd_trn':\n fts = kwargs['fts']\n sents = kwargs['sents']\n lens = kwargs['lens']\n y = kwargs['y']\n\n loss, loss_img, loss_sent, dist2img, dist2sent = self.discriminator('trn', fts, sents, lens, y=y)\n if self._config.d_late_fusion:\n alpha = self._config.d_quality_alpha\n return alpha * loss_img + (1. - alpha) * loss_sent\n else:\n return loss\n elif mode == 'g_sample':\n att_fts = kwargs['att_fts']\n att_masks = kwargs['att_masks']\n\n cell_config = self._config.subcfgs[DEC].subcfgs[decoder.att_rnn_rl.CELL]\n b = att_fts.size(0)\n init_state = torch.zeros(b, cell_config.dim_hidden).cuda()\n init_state = (init_state, init_state)\n\n return self.decoder('sample', init_state, att_fts, att_masks)\n elif mode == 'd_eval':\n fts = kwargs['fts']\n sents = kwargs['sents']\n lens = kwargs['lens']\n\n return self.discriminator('eval', fts, sents, lens, \n greedy_sents=kwargs['greedy_sents'], greedy_lens=kwargs['greedy_lens'])\n elif mode == 'd_val':\n fts = kwargs['fts']\n sents = kwargs['sents']\n lens = kwargs['lens']\n \n return self.discriminator('val', fts, sents, lens)\n elif mode == 'g_val':\n att_fts = kwargs['att_fts']\n att_masks = kwargs['att_masks']\n\n cell_config = self._config.subcfgs[DEC].subcfgs[decoder.att_rnn_rl.CELL]\n b = att_fts.size(0)\n init_state = torch.zeros(b, cell_config.dim_hidden).cuda()\n init_state = (init_state, init_state)\n\n return self.decoder('val', init_state, att_fts, att_masks)\n elif mode == 'g_tst':\n att_fts = kwargs['att_fts']\n att_masks = kwargs['att_masks']\n\n cell_config = self._config.subcfgs[DEC].subcfgs[decoder.att_rnn_rl.CELL]\n b = att_fts.size(0)\n init_state = torch.zeros(b, cell_config.dim_hidden).cuda()\n init_state = (init_state, init_state)\n\n return self.decoder('tst', init_state, att_fts, att_masks, strategy=kwargs['strategy'])\n\n def g_trainable_params(self):\n params = []\n for name, param in self.named_parameters():\n if name.startswith('encoder') or name.startswith('decoder'):\n print(name)\n params.append(param)\n return params\n\n def d_trainable_params(self):\n params = []\n for name, param in self.named_parameters():\n if name.startswith('discriminator'):\n print(name)\n params.append(param)\n return params\n\n\nPathCfg = model.util.AttPathCfg\n\n\nclass TrnTst(framework.GanTrnTst):\n def __init__(self, model_cfg, path_cfg, gpuids):\n super(TrnTst, self).__init__(model_cfg, path_cfg, gpuids)\n\n self.int2str = model.util.CaptionInt2str(path_cfg.word_file)\n\n def g_feed_data_forward_backward(self, data):\n # 1. sample from g\n att_fts = torch.Tensor(data['att_fts']).cuda()\n att_masks = torch.ones(att_fts.size()[:-1]).cuda()\n sample_out_wids, log_probs, greedy_out_wids = self.model('g_sample', att_fts=att_fts, att_masks=att_masks)\n\n # 2. eval d to get reward\n EOS = 1\n\n b, num_sample, _ = sample_out_wids.size()\n sample_out_wids = sample_out_wids.view(b*num_sample, -1)\n lens = []\n for sample in sample_out_wids:\n for k, wid in enumerate(sample):\n if wid == EOS:\n lens.append(k) # exclude EOS\n break\n else:\n lens.append(k+1)\n lens = torch.LongTensor(lens).cuda()\n data['samples'] = sample_out_wids.data.cpu().numpy()\n data['sample_lens'] = lens.data.cpu().tolist()\n\n greedy_lens = []\n for greedy in greedy_out_wids:\n for k, wid in enumerate(greedy):\n if wid == EOS:\n greedy_lens.append(k) # exclude EOS\n break\n else:\n greedy_lens.append(k+1)\n \n fts = torch.Tensor(data['fts']).cuda()\n log_p, log_p_img, log_p_sent, greedy_p, greedy_p_img, greedy_p_sent = \\\n self.model('d_eval', \n fts=fts, \n sents=sample_out_wids.transpose(0, 1), \n lens=lens, \n greedy_sents=greedy_out_wids.transpose(0, 1), \n greedy_lens=greedy_lens)\n if self.model_cfg.d_late_fusion:\n alpha = self.model_cfg.d_quality_alpha\n log_p = alpha * log_p_img + (1. - self.model_cfg.d_quality_alpha) * log_p_sent\n greedy_p = greedy_p_img + greedy_p_sent\n log_p = log_p.view(b, num_sample)\n if self.model_cfg.g_baseline == 'greedy':\n rewards = log_p - greedy_p.unsqueeze(1)\n elif self.model_cfg.g_baseline == 'mean':\n rewards = log_p - log_p.mean(dim=1, keepdim=True)\n rewards = rewards.view(b*num_sample)\n\n # 3. train by surrogate loss\n log_probs = log_probs.view(b*num_sample, -1)\n log_masks = torch.zeros_like(log_probs)\n for i, sample in enumerate(sample_out_wids):\n for j, wid in enumerate(sample):\n if wid == EOS:\n log_masks[i, :j+1] = 1.\n log_masks = log_masks.cuda()\n\n loss = self.model(\n 'g_trn', log_probs=log_probs, log_masks=log_masks, rewards=rewards)\n loss.backward()\n\n def g_feed_data_forward(self, data):\n att_fts = torch.Tensor(data['att_fts']).cuda()\n att_masks = torch.ones(att_fts.size()[:-1]).cuda()\n sample_out_wids, log_probs, greedy_out_wids = self.model('g_sample', att_fts=att_fts, att_masks=att_masks)\n\n EOS = 1\n b, num_sample, _ = sample_out_wids.size()\n sample_out_wids = sample_out_wids.view(b*num_sample, -1)\n lens = []\n for sample in sample_out_wids:\n for k, wid in enumerate(sample):\n if wid == EOS:\n lens.append(k) # exclude EOS\n break\n else:\n lens.append(k+1)\n lens = torch.LongTensor(lens).cuda()\n data['samples'] = sample_out_wids.data.cpu().numpy()\n data['sample_lens'] = lens.data.cpu().tolist()\n\n def d_feed_data_forward_backward(self, data):\n fts = torch.Tensor(data['fts']).cuda()\n captionids = torch.LongTensor(data['samples']).transpose(0, 1).cuda()\n lens = torch.LongTensor(data['sample_lens']).cuda()\n b = lens.size(0)\n y = torch.zeros(b, dtype=torch.long).cuda()\n loss = self.model('d_trn', fts=fts, sents=captionids, lens=lens, y=y)\n\n captionids = model.util.pad_sequence(data['pos_captionids'])\n captionids = torch.LongTensor(captionids).cuda()\n lens = torch.LongTensor(data['pos_lens']).cuda()\n y = torch.ones(b, dtype=torch.long).cuda()\n loss += self.model('d_trn', fts=fts, sents=captionids, lens=lens, y=y)\n\n captionids = model.util.pad_sequence(data['neg_captionids'])\n captionids = torch.LongTensor(captionids).cuda()\n lens = torch.LongTensor(data['neg_lens']).cuda()\n y = torch.zeros(b, dtype=torch.long).cuda()\n loss += self.model('d_trn', fts=fts, sents=captionids, lens=lens, y=y)\n\n loss.backward()\n\n # return acc\n def d_validation(self, buffer):\n hit = 0.\n hit_img = 0.\n hit_sent = 0.\n cnt = 0\n for data in buffer:\n fts = torch.Tensor(data['fts']).cuda()\n b, f = fts.size()\n num_sample = self.model_cfg.subcfgs[DEC].num_sample\n captionids = torch.LongTensor(data['samples']).transpose(0, 1).cuda()\n lens = torch.LongTensor(data['sample_lens']).cuda()\n predicts, predicts_img, predicts_sent = self.model('d_val', fts=fts, sents=captionids, lens=lens)\n hit += torch.sum(predicts[:, 0] > predicts[:, 1]).item()\n hit_img += torch.sum(predicts_img[:, 0] > predicts_img[:, 1]).item()\n hit_sent += torch.sum(predicts_sent[:, 0] > predicts_sent[:, 1]).item()\n cnt += lens.size(0)\n\n captionids = model.util.pad_sequence(data['pos_captionids'])\n captionids = torch.LongTensor(captionids).cuda()\n lens = torch.LongTensor(data['pos_lens']).cuda()\n predicts, predicts_img, predicts_sent = self.model('d_val', fts=fts, sents=captionids, lens=lens)\n hit += torch.sum(predicts[:, 1] > predicts[:, 0]).item()\n hit_img += torch.sum(predicts_img[:, 1] > predicts_img[:, 0]).item()\n hit_sent += torch.sum(predicts_sent[:, 1] > predicts_sent[:, 0]).item()\n cnt += lens.size(0)\n\n return hit / cnt\n\n # return metric dictionary\n def g_validation(self):\n vid2predicts = {}\n for data in self.tst_reader.yield_batch(self.model_cfg.tst_batch_size):\n att_fts = torch.Tensor(data['att_fts']).cuda()\n att_masks = torch.ones(att_fts.size()[:-1]).cuda()\n\n with torch.no_grad():\n out_wids = self.model('g_val', att_fts=att_fts, att_masks=att_masks)\n\n out_wids = out_wids.data.cpu().numpy()\n for i, sent in enumerate(out_wids):\n vid = data['vids'][i]\n vid2predicts[vid] = self.int2str(np.expand_dims(sent, 0))\n\n metrics = {}\n\n bleu_scorer = bleu.Bleu(4)\n bleu_score, _ = bleu_scorer.compute_score(self.tst_reader.vid2captions, vid2predicts)\n for i in range(4):\n metrics['bleu%d'%(i+1)] = bleu_score[i]\n\n cider_scorer = cider.Cider()\n cider_score, _ = cider_scorer.compute_score(self.tst_reader.vid2captions, vid2predicts)\n metrics['cider'] = cider_score\n\n return metrics\n\n def g_predict_in_tst(self):\n vid2predict = {}\n for data in self.tst_reader.yield_batch(self.model_cfg.tst_batch_size):\n att_fts = torch.Tensor(data['att_fts']).cuda()\n att_masks = torch.ones(att_fts.size()[:-1]).cuda()\n\n if self.model_cfg.strategy == 'beam':\n with torch.no_grad():\n beam_cum_log_probs, beam_pres, beam_ends, out_wids = self.model(\n 'g_tst', att_fts=att_fts, att_masks=att_masks, strategy='beam')\n beam_cum_log_probs = beam_cum_log_probs.data.cpu().numpy()\n beam_pres = beam_pres.data.cpu().numpy()\n beam_ends = beam_ends.data.cpu().numpy()\n out_wids = out_wids.data.cpu().numpy()\n\n if self.model_cfg.pool_size == 1:\n candidates = model.util.beamsearch_recover_captions(\n out_wids, beam_cum_log_probs, beam_pres, beam_ends)\n\n for i, candidate in enumerate(candidates):\n vid = data['vids'][i]\n sent = np.array(candidate, dtype=np.int)\n predict = self.int2str(np.expand_dims(sent, 0))[0]\n vid2predict[str(vid)] = predict\n else:\n candidate_scores = model.util.beamsearch_recover_multiple_captions(\n out_wids, beam_cum_log_probs, beam_pres, beam_ends, self.model_cfg.pool_size)\n\n for i, candidate_score in enumerate(candidate_scores):\n vid = data['vids'][i]\n out = []\n for d in candidate_score:\n sent = np.array(d['sent'])\n predict = self.int2str(np.expand_dims(sent, 0))[0]\n score = float(d['score'])\n out.append({\n 'sent': predict,\n 'score': score,\n }) \n vid2predict[str(vid)] = out\n\n with open(self.path_cfg.predict_file, 'w') as fout:\n json.dump(vid2predict, fout)\n","sub_path":"model/vead_gan_sc.py","file_name":"vead_gan_sc.py","file_ext":"py","file_size_in_byte":14186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"36373708","text":"def cycle_length(n):\n string = str(int('1' + '0' * 1100) // n)\n shift = 1\n while string[-100:] != string[:-shift][-100:]:\n shift += 1\n return shift\n\n\ndef ans():\n longest = (None, 0) \n for i in range(2, 1001):\n length = cycle_length(i)\n if longest[1] < length:\n longest = (i, length)\n return longest[0]\n\n\nif __name__ == '__main__':\n print(ans())\n","sub_path":"src/026.py","file_name":"026.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"641292255","text":"from numpy import arccos, arctan, array, cos, cross, dot, pi, sin, sqrt, tan\nfrom numpy.linalg import norm\nfrom datetime import datetime, timedelta\n\nμ = 3.986004418e5 #km^3/s^2\n\n# Solve Kepler's equation\ndef solveKepler(M,e):\n E = M\n dE = pi\n while dE > 1e-6:\n E0 = E\n E = M + e*sin(E)\n dE = abs(E-E0)\n return E\n\n# Rotation Matrices\ndef Rx(θ):\n mat = array([\n [1, 0, 0],\n [0, cos(θ), sin(θ)],\n [0, -sin(θ), cos(θ)]]\n )\n return mat\n\ndef Ry(θ):\n mat = array([\n [cos(θ), 0, -sin(θ)],\n [0, 1, 0],\n [sin(θ), 0, cos(θ)]]\n )\n return mat\n\ndef Rz(θ):\n mat = array([\n [cos(θ), sin(θ), 0],\n [-sin(θ), cos(θ), 0],\n [0, 0, 1]]\n )\n return mat\n\ndef pvt2kepler(pvt):\n # convert pvt to elements...\n assert isinstance(pvt[6], datetime), \"pvt[6] is not a valid datetime object\"\n t0 = pvt[6]\n \n r_ = array(pvt[0:3])\n v_ = array(pvt[3:6])\n\n r = norm(r_)\n \n h_ = cross(r_,v_)\n h = norm(h_)\n e_ = cross(v_,h_)/μ - r_/r\n e = norm(e_)\n\n p = h*h/μ\n\n a = p /(1-e*e)\n a = norm(a)\n\n i = arccos(h_[2]/h)\n\n Ω=0\n n_ = [-h_[1],h_[0],0]\n n = norm(n_)\n if n_[1] >= 0:\n Ω = arccos(n_[0]/n)\n if n_[1] < 0:\n Ω = 2*pi - arccos(n_[0]/n)\n\n ω = arccos(dot(n_,e_) / (n*e))\n if e_[2] < 0:\n ω = 2*pi - ω\n \n \n υ = arccos(dot(e_,r_)/(e*r))\n if dot(r_,v_) < 0:\n υ = 2*pi - υ\n\n # [a(km) e i(rad) Ω(rad) ω(rad) υ(rad)]\n elements = [a, e, i, Ω, ω, υ, t0]\n return elements\n\ndef kepler2pvt(elements):\n [a, e, i, Ω, ω, υ, t0] = elements\n assert isinstance(t0, datetime), \"elements[6] is not a valid datetime object\"\n\n E = 2*arctan(tan(υ/2)/sqrt((1+e)/(1-e)))\n\n r = a*(1-e*cos(E))\n\n o_ = r*array([cos(υ), sin(υ), 0])\n oDot_ = sqrt(μ*a)/r*array([-sin(E), sqrt(1-e*e)*cos(E), 0])\n\n # Convert to ICRF\n r_ = Rz(-Ω) @ Rx(-i) @ Rz(-ω) @ o_\n v_ = Rz(-Ω) @ Rx(-i) @ Rz(-ω) @ oDot_\n\n return [r_[0],r_[1],r_[2],v_[0],v_[1],v_[2],t0]\n\n\n# Propagate elements by dt seconds\ndef prop(dt, elements):\n [a, e, i, Ω, ω, υ, t0] = elements\n assert isinstance(t0, datetime), \"elements[6] is not a valid datetime object\"\n\n n = sqrt(μ/(a*a*a))\n E = arctan(sqrt(1-e*e)*sin(υ)/(e+cos(υ)))\n M = E - e*sin(E)\n M = M + n*(dt)\n\n # Kepler's equation\n E = solveKepler(M,e)\n\n υ = 2*arctan(sqrt((1+e)/(1-e))*tan(E/2))\n #print(υ)\n\n # New epoch\n dt = timedelta(0,dt)\n t1 = t0 + dt\n \n return [a, e, i, Ω, ω, υ, t1]","sub_path":"kepler2/challenge/kepler.py","file_name":"kepler.py","file_ext":"py","file_size_in_byte":2708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"341644246","text":"# -*- mode: python; coding: utf-8 -*-\n# Copyright (c) 2020 Radio Astronomy Software Group\n# Licensed under the 2-clause BSD License\n\n\"\"\"Class for reading and writing Mir files.\"\"\"\nimport numpy as np\n\nfrom .uvdata import UVData\nfrom . import mir_parser\nfrom .. import utils as uvutils\nfrom .. import get_telescope\n\n__all__ = [\"Mir\"]\n\n\nclass Mir(UVData):\n \"\"\"\n A class for Mir file objects.\n\n This class defines an Mir-specific subclass of UVData for reading and\n writing Mir files. This class should not be interacted with directly,\n instead use the read_mir and write_mir methods on the UVData class.\n \"\"\"\n\n def read_mir(self, filepath, isource=None, irec=None, isb=None, corrchunk=None):\n \"\"\"\n Read in data from an SMA MIR file, and map to the UVData model.\n\n Note that with the exception of filename, the rest of the parameters are\n used to sub-select a range of data that matches the limitations of the current\n instantiation of pyuvdata -- namely 1 spectral window, 1 source. These could\n be dropped in the future, as pyuvdata capabilities grow.\n\n Parameters\n ----------\n filepath : str\n The file path to the MIR folder to read from.\n isource : int\n Source code for MIR dataset\n irec : int\n Receiver code for MIR dataset\n isb : int\n Sideband code for MIR dataset\n corrchunk : int\n Correlator chunk code for MIR dataset\n \"\"\"\n # Use the mir_parser to read in metadata, which can be used to select data.\n mir_data = mir_parser.MirParser(filepath)\n\n # Select out data that we want to work with.\n if isource is None:\n isource = mir_data.in_read[\"isource\"][0]\n if irec is None:\n irec = mir_data.bl_read[\"irec\"][0]\n if isb is None:\n isb = mir_data.bl_read[\"isb\"][0]\n if corrchunk is None:\n corrchunk = mir_data.sp_read[\"corrchunk\"][0]\n\n mir_data.use_in = mir_data.in_read[\"isource\"] == isource\n mir_data.use_bl = np.logical_and(\n np.logical_and(\n mir_data.bl_read[\"isb\"] == isb, mir_data.bl_read[\"ipol\"] == 0\n ),\n mir_data.bl_read[\"irec\"] == irec,\n )\n mir_data.use_sp = mir_data.sp_read[\"corrchunk\"] == corrchunk\n\n # Load up the visibilities into the MirParser object. This will also update the\n # filters, and will make sure we're looking at the right metadata.\n mir_data._update_filter()\n if len(mir_data.in_data) == 0:\n raise IndexError(\"No valid records matching those selections!\")\n\n mir_data.load_data(load_vis=True, load_raw=True)\n\n # Create a simple array/list for broadcasting values stored on a\n # per-intergration basis in MIR into the (tasty) per-blt records in UVDATA.\n bl_in_maparr = [mir_data.inhid_dict[idx] for idx in mir_data.bl_data[\"inhid\"]]\n\n # Derive Nants_data from baselines.\n self.Nants_data = len(\n np.unique(\n np.concatenate((mir_data.bl_data[\"iant1\"], mir_data.bl_data[\"iant2\"]))\n )\n )\n\n self.Nants_telescope = 8\n self.Nbls = int(self.Nants_data * (self.Nants_data - 1) / 2)\n self.Nblts = len(mir_data.bl_data)\n self.Nfreqs = int(mir_data.sp_data[\"nch\"][0])\n self.Npols = 1 # todo: We will need to go back and expand this.\n self.Nspws = 1 # todo: We will need to go back and expand this.\n self.Ntimes = len(mir_data.in_data)\n self.ant_1_array = mir_data.bl_data[\"iant1\"] - 1\n self.ant_2_array = mir_data.bl_data[\"iant2\"] - 1\n self.antenna_names = [\n \"Ant 1\",\n \"Ant 2\",\n \"Ant 3\",\n \"Ant 4\",\n \"Ant 5\",\n \"Ant 6\",\n \"Ant 7\",\n \"Ant 8\",\n ]\n self.antenna_numbers = np.arange(8)\n\n # Prepare the XYZ coordinates of the antenna positions.\n antXYZ = np.zeros([self.Nants_telescope, 3])\n for idx in range(self.Nants_telescope):\n if (idx + 1) in mir_data.antpos_data[\"antenna\"]:\n antXYZ[idx] = mir_data.antpos_data[\"xyz_pos\"][\n mir_data.antpos_data[\"antenna\"] == (idx + 1)\n ]\n\n # Get the coordinates from the entry in telescope.py\n lat, lon, alt = get_telescope(\"SMA\")._telescope_location.lat_lon_alt()\n self.telescope_location_lat_lon_alt = (lat, lon, alt)\n # Calculate antenna postions in EFEF frame. Note that since both\n # coordinate systems are in relative units, no subtraction from\n # telescope geocentric position is required , i.e we are going from\n # relRotECEF -> relECEF\n self.antenna_positions = uvutils.ECEF_from_rotECEF(antXYZ, lon)\n self.baseline_array = self.antnums_to_baseline(\n self.ant_1_array, self.ant_2_array, attempt256=False\n )\n\n fsky = mir_data.sp_data[\"fsky\"][0] * 1e9 # GHz -> Hz\n fres = mir_data.sp_data[\"fres\"][0] * 1e6 # MHz -> Hz\n nch = mir_data.sp_data[\"nch\"][0]\n\n self.channel_width = fres\n # Need the half-channel offset below because of the weird way\n # in which MIR identifies the \"center\" of the band\n self.freq_array = fsky + fres * (np.arange(nch) - (nch / 2 - 0.5))\n\n # TODO: This will need to be fixed when spw > 1\n self.freq_array = np.reshape(self.freq_array, (1, -1))\n self.history = \"Raw Data\"\n self.instrument = \"SWARM\"\n\n # todo: This won't work when we have multiple spectral windows.\n self.integration_time = mir_data.sp_data[\"integ\"]\n\n # todo: Using MIR V3 convention, will need to be V2 compatible eventually.\n self.lst_array = (\n mir_data.in_data[\"lst\"][bl_in_maparr].astype(float) + (0.0 / 3600.0)\n ) * (np.pi / 12.0)\n\n # todo: We change between xx yy and rr ll, so we will need to update this.\n self.polarization_array = np.asarray([-5])\n\n self.spw_array = np.asarray([0])\n\n self.telescope_name = \"SMA\"\n time_array_mjd = mir_data.in_read[\"mjd\"][bl_in_maparr]\n self.time_array = time_array_mjd + 2400000.5\n\n # Need to flip the sign convention here on uvw, since we use a1-a2 versus the\n # standard a2-a1 that uvdata expects\n self.uvw_array = (-1.0) * np.transpose(\n np.vstack(\n (mir_data.bl_data[\"u\"], mir_data.bl_data[\"v\"], mir_data.bl_data[\"w\"])\n )\n )\n\n # todo: Raw data is in correlation coefficients, we may want to convert to Jy.\n self.vis_units = \"uncalib\"\n\n self._set_phased()\n\n sou_list = mir_data.codes_data[mir_data.codes_data[\"v_name\"] == b\"source\"]\n\n self.object_name = sou_list[sou_list[\"icode\"] == isource][\"code\"][0].decode(\n \"utf-8\"\n )\n\n self.phase_center_ra = mir_data.in_data[\"rar\"][0]\n self.phase_center_dec = mir_data.in_data[\"decr\"][0]\n self.phase_center_epoch = mir_data.in_data[\"epoch\"][0]\n\n self.phase_center_epoch = float(self.phase_center_epoch)\n self.antenna_diameters = np.zeros(self.Nants_telescope) + 6\n self.blt_order = (\"time\", \"baseline\")\n self.data_array = np.reshape(\n np.array(mir_data.vis_data),\n (self.Nblts, self.Nspws, self.Nfreqs, self.Npols),\n )\n # Don't need the data anymore, so drop it\n mir_data.unload_data()\n self.flag_array = np.zeros(self.data_array.shape, dtype=bool)\n self.nsample_array = np.ones(self.data_array.shape, dtype=np.float32)\n\n def write_mir(self, filename):\n \"\"\"\n Write out the SMA MIR files.\n\n Parameters\n ----------\n filename : str\n The path to the folder on disk to write data to.\n \"\"\"\n raise NotImplementedError\n","sub_path":"pyuvdata/uvdata/mir.py","file_name":"mir.py","file_ext":"py","file_size_in_byte":7903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"194570972","text":"\"\"\"Main collection of views.\"\"\"\nimport os\nfrom flask import Blueprint, jsonify, render_template, url_for\nfrom flask import current_app as app\n\n\n# Blue print for the main display\nhome_blueprint = Blueprint(\n 'home',\n __name__,\n template_folder='templates',\n static_folder='static'\n)\n\n\n@home_blueprint.route('/', methods=['GET'])\ndef home():\n \"\"\"Main home page.\"\"\"\n return render_template(\n 'main.html',\n )\n\n\n# Cache Buster for static files\n@home_blueprint.context_processor\ndef override_url_for():\n return dict(url_for=dated_url_for)\n\n\ndef dated_url_for(endpoint, **values):\n if endpoint == 'static':\n filename = values.get('filename', None)\n if filename:\n file_path = os.path.join(app.root_path,\n endpoint, filename)\n values['q'] = int(os.stat(file_path).st_mtime)\n return url_for(endpoint, **values)\n","sub_path":"app/flask_app/views/home/home.py","file_name":"home.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"285245959","text":"\"\"\"\nMount/unmount a ``kernel`` client.\n\"\"\"\nimport contextlib\nimport logging\n\nfrom teuthology import misc\nfrom cephfs.kernel_mount import KernelMount\n\nlog = logging.getLogger(__name__)\n\n@contextlib.contextmanager\ndef task(ctx, config):\n \"\"\"\n Mount/unmount a ``kernel`` client.\n\n The config is optional and defaults to mounting on all clients. If\n a config is given, it is expected to be a list of clients to do\n this operation on. This lets you e.g. set up one client with\n ``ceph-fuse`` and another with ``kclient``.\n\n Example that mounts all clients::\n\n tasks:\n - ceph:\n - kclient:\n - interactive:\n\n Example that uses both ``kclient` and ``ceph-fuse``::\n\n tasks:\n - ceph:\n - ceph-fuse: [client.0]\n - kclient: [client.1]\n - interactive:\n\n :param ctx: Context\n :param config: Configuration\n \"\"\"\n log.info('Mounting kernel clients...')\n assert config is None or isinstance(config, list), \\\n \"task kclient got invalid config\"\n\n if config is None:\n config = ['client.{id}'.format(id=id_)\n for id_ in misc.all_roles_of_type(ctx.cluster, 'client')]\n clients = list(misc.get_clients(ctx=ctx, roles=config))\n\n test_dir = misc.get_testdir(ctx)\n\n # Assemble mon addresses\n remotes_and_roles = ctx.cluster.remotes.items()\n roles = [roles for (remote_, roles) in remotes_and_roles]\n ips = [remote_.ssh.get_transport().getpeername()[0]\n for (remote_, _) in remotes_and_roles]\n mons = misc.get_mons(roles, ips).values()\n\n mounts = {}\n for id_, remote in clients:\n kernel_mount = KernelMount(mons, test_dir, id_, remote)\n mounts[id_] = kernel_mount\n\n kernel_mount.mount()\n\n ctx.mounts = mounts\n try:\n yield mounts\n finally:\n log.info('Unmounting kernel clients...')\n for mount in mounts.values():\n mount.umount()\n","sub_path":"tasks/kclient.py","file_name":"kclient.py","file_ext":"py","file_size_in_byte":1933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"618304829","text":"\"\"\"\nBasic Spark classification for titanic dataset using mllib library (RDD)\nExpected score: GBT = 0.755981, RF = 0.789474\n\"\"\"\n\nfrom pyspark import SparkContext, SparkConf\nfrom pyspark.sql import SQLContext\n\n# Setting SparkContext\nconf = SparkConf().setAppName(\"titanic_DF\").setMaster(\"local\")\nsc = SparkContext(conf=conf)\nsqlc = SQLContext(sc)\n\nfrom pyspark.sql.types import StructType, StructField, StringType, IntegerType, DoubleType\nfrom pyspark.ml.feature import StringIndexer, OneHotEncoder, VectorIndexer, VectorAssembler, StandardScaler, QuantileDiscretizer\nfrom pyspark.sql.functions import UserDefinedFunction\nfrom pyspark.ml.classification import RandomForestClassifier, RandomForestClassificationModel, GBTClassifier, GBTClassificationModel\nfrom pyspark.ml.evaluation import BinaryClassificationEvaluator\nfrom pyspark.ml import Pipeline\nimport pyspark.sql.functions as spark_fct\nimport pandas as pd\n\ncustomSchema_fields = [\n StructField(\"PassengerId\", IntegerType(), True),\n StructField(\"Survived\", DoubleType(), True),\n StructField(\"Pclass\", IntegerType(), True),\n StructField(\"Name\", StringType(), True),\n StructField(\"Sex\", StringType(), True),\n StructField(\"Age\", DoubleType(), True),\n StructField(\"SibSp\", IntegerType(), True),\n StructField(\"Parch\", IntegerType(), True),\n StructField(\"Ticket\", StringType(), True),\n StructField(\"Fare\", DoubleType(), True),\n StructField(\"Cabin\", StringType(), True),\n StructField(\"Embarked\", StringType(), True)\n ]\n\ntrain_df = sqlc.read.load(\n path=\"data/train.csv\",\n format=\"com.databricks.spark.csv\",\n header=True,\n schema=StructType(customSchema_fields)\n)\n\ntest_df = sqlc.read.load(\n path=\"data/test.csv\",\n format=\"com.databricks.spark.csv\",\n header=True,\n schema=StructType(customSchema_fields[:1] + customSchema_fields[2:])\n)\n\n################################################### Handling NAs\ndef blank_as_null(x):\n return spark_fct.when(x != \"\", x).otherwise(None)\n\ndef blank_as_value(x, value):\n return spark_fct.when(x != \"\", x).otherwise(value)\n\n######################### Embarked\ntrain_df = train_df.withColumn(\"Embarked\", blank_as_value(train_df.Embarked, \"S\"))\ntest_df = test_df.withColumn(\"Embarked\", blank_as_value(test_df.Embarked, \"S\"))\n\n######################### Age\ndef null_as_value(x, value):\n return spark_fct.when(~x.isNull(), x).otherwise(value)\n\n#### Fill age NAs with mean\nmean_age = train_df.select(\"Age\").unionAll(test_df.select(\"Age\")).select(spark_fct.mean(\"Age\")).head()[0]\ntrain_df = train_df.withColumn(\"Age\", null_as_value(train_df.Age, mean_age))\ntest_df = test_df.withColumn(\"Age\", null_as_value(test_df.Age, mean_age))\n\n######################### Fare\nmean_fare = train_df.select(\"Fare\").unionAll(test_df.select(\"Fare\")).select(spark_fct.mean(\"Fare\")).head()[0]\ntest_df = test_df.withColumn(\"Fare\", null_as_value(test_df.Fare, mean_fare))\n\n################################################### Encoding Strings\nsex_stringIndexer = StringIndexer(inputCol=\"Sex\", outputCol=\"sex_code\").fit(train_df.select(\"Sex\").unionAll(test_df.select(\"Sex\")))\nembarked_stringIndexer = StringIndexer(inputCol=\"Embarked\", outputCol=\"embarked_code\").fit(train_df.select(\"Embarked\").unionAll(test_df.select(\"Embarked\")))\nembarked_encoder = OneHotEncoder(inputCol=\"embarked_code\", outputCol=\"embarked_coded\")\nage_discretizer = QuantileDiscretizer(numBuckets=3, inputCol=\"Age\", outputCol=\"age_discretized\").fit(train_df.select(\"Age\").unionAll(test_df.select(\"Age\")))\nfare_discretizer = QuantileDiscretizer(numBuckets=3, inputCol=\"Fare\", outputCol=\"fare_discretized\").fit(train_df.select(\"Fare\").unionAll(test_df.select(\"Fare\")))\n\nfeatures_column = [\"sex_code\", \"embarked_coded\", \"Pclass\", \"SibSp\", \"Age\", \"age_discretized\", \"Parch\", \"fare_discretized\"]\nVectorAssembler = VectorAssembler(inputCols=features_column, outputCol=\"features\")\n\n############ Classifiers\nrfC = RandomForestClassifier(labelCol=\"Survived\", featuresCol=\"features\", numTrees=300, maxDepth=5)\ngbtC = GBTClassifier(labelCol=\"Survived\", featuresCol=\"features\", maxIter=50)\n\npipeline = Pipeline().setStages([\n sex_stringIndexer,\n age_discretizer,\n fare_discretizer,\n embarked_stringIndexer, embarked_encoder,\n VectorAssembler,\n rfC\n ]).fit(train_df)\n\n##### Applying pipeline\ntrain_piped = pipeline.transform(train_df)\ntest_piped = pipeline.transform(test_df)\n\n############################################### Feature importances\nprint(\"\\n----------- Feature importances\")\nrfCmodel = pipeline.stages[6]\nfor feature_name, feature_importance in sorted(zip(features_column, rfCmodel.featureImportances), key=lambda x: -x[1]):\n print(\"%20s: %s\" % (feature_name, feature_importance))\n\n############################################## Exporting\ndf_predictions = test_piped.select(\"prediction\").toPandas().reset_index()\ndf_predictions['index'] = df_predictions['index'] + 892\ndf_predictions.columns = ['PassengerId', 'Survived']\n\ndf_predictions.to_csv('submission.csv', index=False)\n","sub_path":"titanic_spark/classification_DF.py","file_name":"classification_DF.py","file_ext":"py","file_size_in_byte":5066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"511297265","text":"from inspect import signature\nfrom functools import wraps\n\n\ndef hoping(*iargs, **ikwargs):\n \"\"\"\n Implement the expected parameter type checking, note that it is a decorator usage\n \"\"\"\n\n def decorate(func):\n sig = signature(func)\n bound_types = sig.bind_partial(*iargs, **ikwargs).arguments\n\n @wraps(func)\n def wrapper(*args, **kwargs):\n bound_values = sig.bind(*args, **kwargs)\n for name, value in bound_values.arguments.items():\n if name in bound_types:\n if not isinstance(value, bound_types[name]):\n raise TypeError(\"Args's type who names [ {} ] should be {}\".format(name, bound_types[name]))\n return func(*args, **kwargs)\n\n return wrapper\n\n return decorate\n","sub_path":"src/decorator.py","file_name":"decorator.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"226736491","text":"class Solution:\n # @param grid, a list of lists of integers\n # @return an integer\n def minPathSum(self, grid):\n m = len(grid)\n if m == 0:\n return 0\n n = len(grid[0])\n if n == 0:\n return 0\n res = [[0 for c in range(n)] for r in range(m)] \n for r in range(m):\n for c in range(n):\n if r == 0 and c == 0:\n res[r][c] = grid[r][c]\n elif r == 0:\n res[r][c] = res[r][c - 1] + grid[r][c]\n elif c == 0:\n res[r][c] = res[r - 1][c] + grid[r][c]\n else:\n res[r][c] = min(res[r][c - 1], res[r - 1][c]) + grid[r][c]\n return res[m - 1][n - 1]\n","sub_path":"src/main/python/lc/minimum_path_sum.py","file_name":"minimum_path_sum.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"430456773","text":"import json\nfrom tqdm import tqdm\nfrom googleapiclient.discovery import build\nimport config\n\ndef google_search(search_term, api_key, cse_id, **kwargs):\n service = build(\"customsearch\", \"v1\", developerKey=api_key)\n res = service.cse().list(q=search_term, cx=cse_id, **kwargs).execute()\n return res['items']\n\nif __name__ == '__main__':\n my_api_key = config.api_key\n my_cse_id = config.cse_id\n my_search_topic = config.target_topic\n\n total_page_number = config.google_search_maximum_page_number\n results = []\n\n for page_number in tqdm(range(total_page_number)):\n current_result = google_search(my_search_topic, my_api_key, my_cse_id, num=10, start=page_number*10+1)\n results += current_result\n \n with open('google_search.json', 'w') as dump_file:\n json.dump(results, dump_file)\n","sub_path":"cse.py","file_name":"cse.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"120654011","text":"# -*- coding: utf-8 -*-\nfrom http import HTTPStatus\n\nimport flask\n\nfrom src.exceptions.response_exceptions import ConflictException, NotFoundException, BadRequestException\nfrom src.services.pokemons import PokemonService, PokemonRequest\n\n\npokemons_bp = flask.Blueprint('pokemons', __name__, url_prefix='/api/v1/pokemons')\n\n@pokemons_bp.route('/', methods=['GET'])\ndef get_pokemon(name):\n pokemon = PokemonService.get_pokemon(name)\n\n return flask.jsonify(pokemon), HTTPStatus.OK.value\n\n\n@pokemons_bp.route('', methods=['GET'])\ndef get_all_pokemons():\n request = PokemonRequest()\n\n if 'name' in flask.request.args:\n request.name = flask.request.args.get('name') \n if 'types' in flask.request.args:\n request.types = flask.request.args.get('types') \n if 'caught' in flask.request.args:\n request.caught = flask.request.args.get('caught') == 'true'\n if 'abilities' in flask.request.args:\n request.abilities = flask.request.args.get('abilities') \n if 'hidden_abilities' in flask.request.args:\n request.hidden_abilities = flask.request.args.get('hidden_abilities') == 'true'\n if 'order_by' in flask.request.args:\n request.order_by = flask.request.args.get('order_by')\n if 'descending' in flask.request.args:\n request.descending = flask.request.args.get('descending')\n\n pokemons = PokemonService.get_all_pokemons(request)\n\n return flask.jsonify(pokemons), HTTPStatus.OK.value\n\n\n@pokemons_bp.route('/', methods=['POST'])\ndef save_pokemon(name):\n pokemon = PokemonService.get_all_pokemons({ name })\n if pokemon:\n raise ConflictException('This pokemon has been already saved')\n\n payload = flask.request.get_json(cache=False)\n\n saved = PokemonService.insert_pokemon(payload)\n\n return flask.jsonify(saved), HTTPStatus.OK.value\n\n\n@pokemons_bp.route('/', methods=['PUT', 'PATCH'])\ndef update_pokemon(pokemon_id):\n\n pokemon = PokemonService.get_by_id(pokemon_id)\n if not pokemon:\n raise NotFoundException('This pokemon doesn\\'t belong to your team yeat')\n\n payload = flask.request.get_json()\n if not payload:\n raise BadRequestException()\n\n saved = PokemonService.update_pokemon(pokemon_id, payload)\n\n return flask.jsonify(saved.to_dict()), HTTPStatus.OK.value\n","sub_path":"back/src/blueprints/pokemons.py","file_name":"pokemons.py","file_ext":"py","file_size_in_byte":2320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"377392190","text":"# Copyright (C) 2020 University of Glasgow\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\nimport sys\nimport os\nimport time\n\nsys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))\n\nfrom ietfdata.datatracker import *\n\ndt = DataTracker(cache_dir=Path(\"cache\"))\nreplaces = dt.relationship_type(RelationshipTypeURI(\"/api/v1/name/docrelationshipname/replaces/\"))\n\ndocname = \"rfc8280\"\n\ndef print_revisions(document):\n revisions = list(dt.document_events(doc=document, event_type=\"new_revision\"))[::-1]\n for revision in revisions:\n print(\" {0: <50} | {1} | {2}\".format(document.name, revision.rev, revision.time.strftime(\"%Y-%m-%d\")))\n\ndef replacements(doc, docs_seen):\n replaced_docs = list(dt.related_documents(source=doc, relationship_type=replaces))\n replaced_docs = [dt.document_alias(replaced_doc.target) for replaced_doc in replaced_docs]\n for replaced_doc in replaced_docs:\n if replaced_doc not in docs_seen:\n replacements(dt.document(replaced_doc.document), docs_seen)\n docs_seen.append(replaced_doc)\n return replaced_docs\n\ndef get_replacement_chain(doc):\n docs_seen = []\n replacements(doc, docs_seen)\n return docs_seen\n\ndocs = list(dt.document_aliases(name=docname))\nif len(docs) == 1:\n doc = dt.document(docs[0].document)\n replacement_aliases = get_replacement_chain(doc)\n for replacement_alias in replacement_aliases:\n replacement_doc = dt.document(replacement_alias.document)\n print(replacement_doc.name)\n print_revisions(replacement_doc)\n print(doc.name)\n print_revisions(doc)\n if docname[:3] == \"rfc\":\n published_rfc_event = list(dt.document_events(doc=doc, event_type=\"published_rfc\"))[0]\n print(\"{0: <54} | -- | {1}\".format(docname, published_rfc_event.time.strftime(\"%Y-%m-%d\")))\n","sub_path":"examples/document-timeline.py","file_name":"document-timeline.py","file_ext":"py","file_size_in_byte":3079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"41393817","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\nX = []\nwith open(\"three.txt\") as fd:\n lines = fd.readlines()\n for line in lines:\n three = line.split()\n three = list(map(int, three))\n X.append(three)\n\nwith open(\"eight.txt\") as fd:\n lines = fd.readlines()\n for line in lines:\n three = line.split()\n three = list(map(int, three))\n X.append(three)\n\ny = []\nfor i in range(256):\n elem = 0\n for j in range(400):\n elem += X[j][i]\n y.append(elem/400)\n#y = np.array(y)\nX = np.array(X)\ny = np.mean(X.T, axis=1)\nX = X - y\n# S = np.dot(X.T,X)\n# S = np.divide(S,399)\nS = np.cov(X.T)\nw, v = np.linalg.eig(S)\nprint(w[:2])\nv1 = v[:,0]\nv2 = v[:,1]\n# v1 = np.divide(v1,(np.amax(v1)/255.0))\n# v2 = np.divide(v2,(np.amax(v2)/255.0))\nimg = v1.reshape(16,16,order='F')\nplt.imshow(img, cmap=\"gray\")\nplt.show()\nimg = v2.reshape(16,16,order='F')\nplt.imshow(img, cmap=\"gray\")\nplt.show()","sub_path":"HW8/Q4.py","file_name":"Q4.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"493113077","text":"# -*- coding: UTF-8 -*-\n\nfrom pyAudioAnalysis import audioBasicIO\nfrom pyAudioAnalysis import audioFeatureExtraction\nimport numpy as np\nfrom sklearn.svm import SVC\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.mixture import GaussianMixture\n\n# python speech feature\n\nmy_dir = ['common', 'throat']\nmy_file = ['1.wav', '2.wav', '3.wav', '4.wav', '5.wav', '6.wav', '7.wav', '8.wav', '9.wav', '10.wav',\n 'from-net-1.wav',\n 'from-net-2.wav', 'from-net-3.wav'\n ]\n# my_file = ['from-net-1.wav',\n# 'from-net-2.wav', 'from-net-3.wav']\n# my_file = ['train.wav']\n\nframe_length = 0.07\nstep_length = 0.035\n\ndata_matrix = []\nlabel_matrix = []\nn = 0\nn = int(n)\nfor f_dir in my_dir:\n n += 1\n for f_file in my_file:\n [Fs, x] = audioBasicIO.readAudioFile(\"D:/ML/mono_train/\" + f_dir + \"/\" + f_file)\n # F = audioFeatureExtraction.stFeatureExtraction(x, Fs, 256, 80)\n F = audioFeatureExtraction.stFeatureExtraction(x, Fs, frame_length * Fs, step_length * Fs)\n f = F[8:21, ]\n f = f.T\n data_matrix.append(f)\n label = np.empty(f.shape[0], dtype=int)\n label = np.full(label.shape, n)\n label_matrix.append(label)\ndata_matrix = np.concatenate(data_matrix, 0)\nlabel_matrix = np.concatenate(label_matrix, 0)\n\n# data_matrix = data_matrix\n# label_matrix = label_matrix\nprint(data_matrix.shape)\nprint(label_matrix.shape)\n\n# data_matrix_new = SelectKBest(f_regression, k=9).fit_transform(data_matrix, label_matrix)\n\nnp.savetxt(fname=\"data_matrix.csv\", X=data_matrix, delimiter=',')\nnp.savetxt(\"label_matrix.csv\", label_matrix, delimiter=',')\n\n# clf_svm = svm.SVC(gamma='scale', decision_function_shape='ovo')\n# clf_svm.fit(data_matrix, label_matrix)\n\nclf_svm = Pipeline([\n (\"scaler\", StandardScaler()),\n # (\"svm_clf\", SVC(kernel=\"poly\", C=1000))\n # (\"svm_clf\", SVC(kernel='rbf', gamma='scale', C=5, decision_function_shape='ovo'))\n (\"svm_clf\", SVC(kernel='poly', gamma='scale', C=100, decision_function_shape='ovo'))\n # (\"gmm_clf\", GaussianMixture(n_components=2, covariance_type='full'))\n])\n\n# clf_svm = RandomForestClassifier(n_estimators=100, max_depth=2, random_state=0)\nclf_svm.fit(data_matrix, label_matrix)\n\n\n# RandomForest\n\n# 预测\n\n\ndef max_list(lt):\n temp = 0\n for i in lt:\n if lt.count(i) > temp:\n max_str = i\n temp = lt.count(i)\n return str(max_str)\n\n\n# pre_dir = ['common', 'throat']\n# pre_file = ['1.wav', '2.wav', '3.wav', '4.wav', '5.wav', '6.wav', '7.wav', '8.wav', '9.wav',\n# '10.wav', '11.wav', '12.wav', '13.wav', '14.wav', '15.wav', 'xsb-common.wav.wav', ]\n# counter = current = 0\n#\n# result_matrix = []\n# for p_dir in pre_dir:\n# # current += 1\n# result_matrix.append(p_dir)\n# result_matrix.append(':')\n# for p_file in pre_file:\n# [Fs, x] = audioBasicIO.readAudioFile(\"D:/ML/mono_test/\" + p_dir + '/' + p_file)\n# F = audioFeatureExtraction.stFeatureExtraction(x, Fs, 0.050 * Fs, 0.025 * Fs)\n# # F = audioFeatureExtraction.stFeatureExtraction(x, Fs, 256, 80)\n# f = F[8:21, ].T\n# result = clf_svm.predict(f)\n# result_in = result.tolist()\n# result_matrix.append(max_list(result_in))\n# print(result_matrix)\n\npre_file = ['common1.wav', 'common2.wav', 'common3.wav', 'common4.wav', 'common5.wav',\n 'common6.wav', 'common7.wav', 'common8.wav', 'common9.wav', 'common10.wav',\n 't1.wav', 't2.wav', 't3.wav', 't4.wav', 't5.wav',\n 't6.wav', 't7.wav', 't8.wav', 't9.wav', 't10.wav',\n 't11.wav', 't12.wav', 't13.wav', 't14.wav', 't15.wav']\n\nresult_matrix = []\nfor p_file in pre_file:\n [Fs, x] = audioBasicIO.readAudioFile(\"D:/ML/data/SVM/\" + p_file)\n F = audioFeatureExtraction.stFeatureExtraction(x, Fs, frame_length * Fs, step_length * Fs)\n # F = audioFeatureExtraction.stFeatureExtraction(x, Fs, 256, 80)\n f = F[8:21, ].T\n result = clf_svm.predict(f)\n result_in = result.tolist()\n # result_matrix.append(p_file)\n result_matrix.append(max_list(result_in))\nprint(result_matrix)\n","sub_path":"Test Code/speak_reg/throat.py","file_name":"throat.py","file_ext":"py","file_size_in_byte":4125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"144185046","text":"casa = float(input('Qual o valor da casa R$?'))\nsal = float(input('Qual o seu salario R$?'))\nanos = int(input('Em quantos anos vai pagar?'))\n\nprest = casa / (anos * 12)\nsal30 = (sal * 30 / 100)\n\nif prest > sal30:\n print('Desculpe! Prestação excedeu o seu limite')\n \nelse:\n print('Parabéns!! Seu financiamento foi liberado')","sub_path":"36.py","file_name":"36.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"415585542","text":"# by amounra 0216 : http://www.aumhaa.com\n# written against Live 9.6 release on 021516\n\nfrom __future__ import absolute_import, print_function\n\nimport Live\n\nimport math\nimport sys\nfrom re import *\nfrom itertools import imap, chain, starmap\n\nfrom aumhaa.v2.base import initialize_debug\n\ndebug = initialize_debug()\n\n\ndef get_devices(track):\n\n\tdef dig(container_device):\n\t\tcontained_devices = []\n\t\tif container_device.can_have_chains:\n\t\t\tfor chain in container_device.chains:\n\t\t\t\tfor chain_device in chain.devices:\n\t\t\t\t\tfor item in dig(chain_device):\n\t\t\t\t\t\tcontained_devices.append(item)\n\t\telse:\n\t\t\tcontained_devices.append(container_device)\n\t\treturn contained_devices\n\t\n\n\tdevices = []\n\tfor device in track.devices:\n\t\tfor item in dig(device):\n\t\t\tdevices.append(item)\n\t\t\t#self.log_message('appending ' + str(item))\n\treturn devices\n\t\n\n","sub_path":"aumhaa/v2/base/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"87039992","text":"import pandas as pd\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns\n\n#Reading users file:\nu_users = ['id', 'user_id', 'joke_id']\nusers = pd.read_csv('c:\\\\Users\\\\hambekar\\\\Downloads\\\\joke_user.csv', sep=',', names=u_users, encoding='latin-1')\n\n#Reading ratings file:\nr_ratings = ['id', 'rating']\nratings = pd.read_csv('c:\\\\Users\\\\hambekar\\\\Downloads\\\\joke_rating.csv', sep=',', names=r_ratings, encoding='latin-1')\n\nusers['id']=users['id'].transform(float)\nratings['id']=ratings['id'].transform(float)\n\n\nratings = pd.merge(users, ratings, on='id')\n\n#ratings_df = pd.DataFrame(ratings.groupby('joke_id')['joke_id'].mean())\nratings['number_of_ratings'] = ratings.groupby('joke_id')['rating'].count()\nratings['number_of_ratings'].hist(bins=60)\n\nsns.jointplot(x='rating', y='number_of_ratings', data=ratings)\n\nprint(ratings)\n\nexit(0)\n\nn_users = users.user_id.unique().shape[0]\nn_items = users.joke_id.unique().shape[0]\n\ndata_matrix = np.zeros((n_users, n_items))\n\ndata_matrix = np.zeros((n_users, n_items))\nfor line in ratings.itertuples():\n data_matrix[line[1]-1, line[2]-1] = line[0]\n #print(line)\n\nfrom sklearn.metrics.pairwise import pairwise_distances\nuser_similarity = pairwise_distances(data_matrix, metric='cosine')\nitem_similarity = pairwise_distances(data_matrix.T, metric='cosine')\n\nuser_prediction = predict(data_matrix, user_similarity, type='user')\nitem_prediction = predict(data_matrix, item_similarity, type='item')\n\nprint(user_prediction)\nprint(item_prediction)\n","sub_path":"funny-jokes-ratings.py","file_name":"funny-jokes-ratings.py","file_ext":"py","file_size_in_byte":1523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"185713578","text":"from flask import Flask\napp = Flask(__name__)\n#from flask import Flask, request\nimport requests, json\n#app = Flask(__name__)\napiadd = 'https://api-ssl.bitly.com'\ngetr = '/v3/nsq/stats?topic=data_stream&access_token=29ec273e0984e4ca984c334fcb563b18ea250653'\nurl = apiadd + getr\nprint(url)\nurl2= 'https://api.coinmarketcap.com/v2/ticker/1/'\n\n@app.route(\"/\")\ndef display():\n\tres_data = requests.get(url2)\n\tres_data = res_data.json()\n\treturn json.dumps(res_data)\n\"\"\"\n\trel = res_data.json()\n\tret = rel['data']\n\tcur = ret['name']\n\tsym = ret['symbol']\n\tweb = ret['website_slug']\n\trn = ret['rank']\n\tcsup = ret['circulating_supply']\n\ttsup = ret['total_supply']\n\tmsup = ret['max_supply']\n\tquot = ret['quotes']\n\tusd = quot['USD']\n\tprc = usd['price']\n\tvol = usd['volume_24h']\n\tmar = usd['market_cap']\n\tper1h = usd['percent_change_1h']\n\tper24h = usd['percent_change_24h']\n\tper7d = usd['percent_change_7d']\n\tlu = ret['last_updated']\n\t#for i in ret:\n\t#\tprint(ret[i])\n\treturn '''\n \n\t\t\\nName of currency: {}\n\t\t\\nSymbol: {}\n\t\t\\nWebsite slug: {}\n\t\t\\nRank: {}\n\t\t\\nCirculating Supply: {}\n\t\t\\nTotal Supply: {}\n\t\t\\nMax Supply: {}\n\t\t\\nQuotes:\n\t\t\\n\t{} :\n\t\t\\n\t\tPrice: {}\n\t\t\\n\t\tVolume in 24h: {}\n\t\t\\n\t\tMarket Cap: {}\n\t\t\\n\t\tPercent Change in 1 hr: {}\n\t\t\\n\t\tPercentage Change in 24 hr: {}\n\t\t\\n\t\tPercentage Change in 7 days: {}\n\t\t\\nLast Updated: {}'''.format(cur,sym,web,rn,csup,tsup,msup,'USD',prc,vol,mar,per1h,per24h,per7d,lu)\n\"\"\"\n","sub_path":"python/new.py","file_name":"new.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"539729387","text":"import asyncio\nimport websockets\nfrom geolocation import Geolocation\nimport json\n\ngeolocation = Geolocation()\ngeolocation.connect_to_base()\n\n'''Класс Websocket'''\nclass Websocket():\n\n timeout = 1 \n client_imei = []\n USERS = set()\n host = \"127.0.0.1\"\n port = 3000\n\n async def addUser(self, websocket):\n self.USERS.add(websocket) \n\n async def removeUser(self,websocket):\n self.USERS.remove(websocket) \n\n def start(self): \n start_ws = websockets.serve(self.main, self.host, self.port) \n asyncio.get_event_loop().run_until_complete(start_ws)\n asyncio.get_event_loop().run_forever() \n\n '''Опрос базы данных и отправка клиенту локации тс с запрошенными imei с интервалом timeout'''\n async def worker(self, websocket, path): \n while True: \n await websocket.send(json.dumps(geolocation.get_geo(self.client_imei))) \n await asyncio.sleep(self.timeout) \n\n '''Прослушивание запросов от клиента'''\n async def recv(self, websocket, path): \n try:\n client_imei = await websocket.recv() \n self.client_imei = json.loads(client_imei)\n await self.recv(websocket, path)\n except: \n await self.removeUser(websocket)\n\n '''Запуск параллельной работы прослушивания ws и регулярной отправки сообщений'''\n async def main(self, websocket, path):\n await self.addUser(websocket) \n task1 = asyncio.get_event_loop().create_task(self.worker(websocket, path))\n task2 = asyncio.get_event_loop().create_task(self.recv(websocket, path)) \n await task1\n await task2 ","sub_path":"backend/websocket.py","file_name":"websocket.py","file_ext":"py","file_size_in_byte":1962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"542522870","text":"import unittest\n\nfrom entity.entity import Entity\nfrom field import Field\nfrom helpers.helpers import OccupationError\n\n\ndef setup_field():\n field = Field()\n entity = Entity((1, 2))\n\n # |-|-| |+|+|+|\n # |2|1|0|1|2|3|\n # --+-+-+-+-+-+-+\n # -1| | | | | | |\n # --+-+-+-+-+-+-+\n # 0| | |#|#| | |\n # --+-+-+-+-+-+-+\n # +1| | | | | | |\n # --+-+-+-+-+-+-+\n\n field.contents = [\n ((0, 0), entity)\n ]\n return field, entity\n\n\nclass FieldTests(unittest.TestCase):\n def test_query_for_empty_field(self):\n field = Field()\n results = field.query((0, 0))\n self.assertFalse(results)\n\n def test_query_for_entity(self):\n field, entity = setup_field()\n results = field.query((0, 0))\n self.assertTrue(results)\n self.assertEqual(results[0], entity)\n\n results = field.query((0, 1))\n self.assertTrue(results)\n self.assertEqual(results[0], entity)\n\n def test_query_for_too_right(self):\n field, entity = setup_field()\n results = field.query((0, 2))\n self.assertFalse(results)\n\n def test_query_for_too_left(self):\n field, entity = setup_field()\n results = field.query((0, -1))\n self.assertFalse(results)\n\n def test_query_for_too_down(self):\n field, entity = setup_field()\n results = field.query((1, 0))\n self.assertFalse(results)\n\n def test_query_for_too_down_2(self):\n field, entity = setup_field()\n results = field.query((2, 0))\n self.assertFalse(results)\n\n def test_query_for_too_up(self):\n field, entity = setup_field()\n results = field.query((-1, 0))\n self.assertFalse(results)\n\n def test_query_for_too_down_3(self):\n field, entity = setup_field()\n results = field.query((1, 1))\n self.assertFalse(results)\n\n def test_query_for_too_up_2(self):\n field, entity = setup_field()\n results = field.query((-1, 1))\n self.assertFalse(results)\n\n def test_insert_not_entity(self):\n field = Field()\n with self.assertRaises(TypeError):\n field.insert('hello', (0, 0))\n\n def test_insert_wrong_position(self):\n field = Field()\n with self.assertRaises(ValueError):\n field.insert(Entity((1, 2)), (0, 0, 0))\n\n\nclass EntityTests(unittest.TestCase):\n def test_occupation_profile(self):\n entity = Entity((1, 2))\n profile = entity.get_occupation_profile((1, 2))\n self.assertSetEqual(profile,\n {(1, 2), (1, 3)})\n\n\nclass InsertTests(unittest.TestCase):\n def test_insert_empty_field(self):\n field = Field()\n entity = Entity((1, 2))\n field.insert(entity, (1, 1))\n self.assertEqual(len(field.contents), 1)\n\n def test_occupation_check_fail(self):\n field = Field()\n en1 = Entity((1, 2))\n en2 = Entity((1, 2))\n field.insert(en1, (0, 0))\n with self.assertRaises(OccupationError):\n field.insert(en2, (0, 1))\n\n def test_occupation_check_success(self):\n field = Field()\n en1 = Entity((1, 2))\n en2 = Entity((1, 2))\n field.insert(en1, (0, 0))\n field.insert(en2, (0, 2))\n self.assertEqual(len(field.contents), 2)\n","sub_path":"tests/field_test.py","file_name":"field_test.py","file_ext":"py","file_size_in_byte":3281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"483211656","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport json\nimport os.path as osPath\nimport numpy as np\nfrom sklearn.cluster import KMeans\nfrom sklearn.decomposition import LatentDirichletAllocation\nfrom convert_data import ConvertData\nfrom extarct_tags import TagExtraction\n\ndef print_top_words(model, feature_names, n_top_words):\n for topic_idx, topic in enumerate(model.components_):\n print(\"Topic #%d:\" % topic_idx)\n print(\" \".join([feature_names[i]\n for i in topic.argsort()[:-n_top_words - 1:-1]]))\n print()\n\ntagExtraction = TagExtraction('product', 'tags.json')\nconverter = ConvertData('product')\n\ntags = tagExtraction.read_tags()\nrecords = tagExtraction.read_records()\nrecords = {record['id']: [record['productname'], record['description'], record['directoryname']] for record in records}\n\nvectors_id = converter.read_vectors()\nids = list(vectors_id.keys())\nvectors = list(vectors_id.values())\n\nlda = LatentDirichletAllocation(n_topics=100)\nlda_vectors = lda.fit_transform(vectors)\nprint_top_words(lda, tags, 20)\n\ncls = KMeans(n_clusters=500).fit(lda_vectors)\nlabels = cls.labels_\nlabel_map = dict(zip(ids, labels))\n\ntagExtraction = TagExtraction('product', 'tags.json')\ntags = tagExtraction.read_tags()\nrecords = tagExtraction.read_records()\nrecords = {record['id']: [record['productname'], record['description']] for record in records}\n\noutput = {}\nfor k, v in label_map.items():\n if v in output:\n output[v].append(k)\n else:\n output[v] = [k]\n\n\ndef dump_cluster(label, tags, records):\n with open(osPath.join(osPath.dirname(osPath.abspath(__file__)), 'product', 'clusters', str(label) + '_tags.json'),\n 'w',\n encoding='utf-8') as f:\n f.write(json.dumps(tags, ensure_ascii=False))\n\n with open(\n osPath.join(osPath.dirname(osPath.abspath(__file__)), 'product', 'clusters', str(label) + '_records.json'),\n 'w',\n encoding='utf-8') as f:\n f.write(json.dumps(records, ensure_ascii=False))\n\n\nfor k, v in output.items():\n print(k, len(v))\n\n sum = np.zeros(len(vectors[0]))\n for id in v:\n na = np.array(vectors_id[id], dtype=np.float64)\n na[na != 0] = 1\n sum += na\n sum = sum.tolist()\n\n _tags = [(tag, count) for tag, count in zip(tags, sum) if count != 0]\n _records = [[id] + records[id] for id in v]\n # _records = [[id] + records[id] + [[(index, value) for index,value in enumerate(vectors_id[id]) if value != 0]] for id in v]\n # _records = [vectors_id[id] for id in v]\n dump_cluster(k, sorted(_tags, key=lambda x: x[1], reverse=True), _records)\n # print([tags[index] for index, count in enumerate(sum) if count > len(v)*0.2])\n\n\n\n# while(True):\n# productId = input('productId\\n')\n# label = label_map[productId]\n# indexs = [index for index, item in enumerate(labels) if item == label]\n# for index in indexs:\n# print(records[ids[index]])\n","sub_path":"training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":2953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"109011552","text":"import urlparse\nfrom Acquisition import aq_base, aq_inner\n\nfrom Products.CMFCore.utils import getToolByName\nfrom Products.Five.browser import BrowserView\n\nfrom emas.theme import MessageFactory as _\n\n\nclass TableOfContents(BrowserView):\n \"\"\" Helper methods and a template that renders only the table of contents.\n \"\"\"\n\n def _items(self, container=None):\n portal_properties = getToolByName(self.context, 'portal_properties')\n navtree_properties = getattr(portal_properties, 'navtree_properties')\n portal_catalog = getToolByName(self.context, 'portal_catalog')\n\n blacklist = navtree_properties.getProperty('metaTypesNotToList', ())\n all_types = portal_catalog.uniqueValuesFor('portal_type')\n\n contentFilter = dict(\n portal_type=[t for t in all_types if t not in blacklist]\n )\n container = container or self.context\n\n idsNotToList = navtree_properties.getProperty('idsNotToList', ())\n result = []\n for brain in container.getFolderContents(contentFilter):\n if not (brain.getId in idsNotToList or brain.exclude_from_nav):\n result.append(brain.getObject())\n return result\n\n def getContentItems(self, container=None):\n result = self._items(container)\n if result and self.has_practise_content(self.context):\n # get the chapter context from the last link of the chapter\n lastitem_url = result[len(result)-1].absolute_url()\n lastitem_type = result[len(result)-1].portal_type\n # only add 'practice this chapter now' if the other items in the \n # result list are book links\n if lastitem_type == 'rhaptos.xmlfile.xmlfile':\n chapter = lastitem_url.split('/')[-2]\n chapter = '/' + chapter \n result.append(self._practice_url(chapter))\n\n return result\n\n def isFolder(self, item):\n return bool(getattr(aq_base(aq_inner(item)), 'isPrincipiaFolderish',\n False))\n \n def getTitle(self, item):\n \"\"\" If it does not have its own title, we fall back to id.\n \"\"\"\n return item.Title() or item.getId()\n\n def has_practise_content(self, context):\n retVal = True\n paths_without_practise_content = [\n '/emas/maths/grade-10-mathematical-literacy',\n '/emas/maths/grade-11-mathematical-literacy',\n '/emas/maths/grade-12-mathematical-literacy',\n '/emas/science/lifesciences',\n ]\n path = self.context.getPhysicalPath()\n if path:\n path = '/'.join(path[:4])\n if path in paths_without_practise_content:\n retVal = False\n\n return retVal\n\n def _practice_url(self, chapter):\n absolute_url = self.context.absolute_url()\n title = 'Practise this chapter now'\n parts = urlparse.urlparse(self.context.absolute_url())\n newparts = urlparse.ParseResult(parts.scheme,\n parts.netloc,\n '/@@practice' + parts.path + chapter,\n parts.params,\n parts.query,\n parts.fragment)\n url = urlparse.urlunparse(newparts)\n tmp_dict = {\n 'Title': title,\n 'absolute_url': url,\n 'css_class': 'practice-link',\n }\n return tmp_dict\n\n","sub_path":"emas/theme/browser/toc.py","file_name":"toc.py","file_ext":"py","file_size_in_byte":3504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"645381624","text":"buying_price= 550000\n\nfrac_down= 0.05\nclosing_cost=0.015\nselling_cost= 0.06\nprice_growth= 0.05\n\nrental_income = 1200 #rent you will charge for a bedroom in your house\nrent_inc= 0.03\nrental_sqfoot_percent = 0.3 #space that you are renting as a fraction of total house space (will be used to\n#determine fraction of mortgage insurance deduction from federal taxes)\n\nhoa_fees = 390\nyears_stay= 30\n\n","sub_path":"renting_vs_buying/house_config.py","file_name":"house_config.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"528953449","text":"import datetime\r\nimport json\r\nimport logging\r\nimport logging.handlers\r\nimport paho.mqtt.client as mqtt\r\nimport pyrebase\r\nimport time\r\nimport threading\r\nimport yaml\r\n\r\n# logging configuration\r\nLOG_FILENAME = '/opt/dmars/mqtt_subscriber_to_firebase.log'\r\n\r\nroot_logger=logging.getLogger()\r\nroot_logger.setLevel(logging.DEBUG)\r\nfile_handler = logging.FileHandler(LOG_FILENAME, 'w', 'utf-8')\r\nfile_handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s:%(message)s'))\r\n# Create the rotating file handler. Limit the size to 1000000Bytes ~ 1MB .\r\nrotating_file_handler = logging.handlers.RotatingFileHandler(\r\n LOG_FILENAME, maxBytes=1000000, backupCount=5)\r\n# Add the handlers to the logger\r\nroot_logger.addHandler(file_handler)\r\nroot_logger.addHandler(rotating_file_handler)\r\n\r\n# read configurations\r\nwith open(r'/opt/dmars/firebase_config.yml') as file:\r\n firebase_config = yaml.load(file, Loader=yaml.FullLoader)\r\n\r\nwith open(r'/opt/dmars/basestation_config.yml') as file:\r\n basestation_config = yaml.load(file, Loader=yaml.FullLoader)\r\n\r\nwith open(r'/opt/dmars/mqtt_config.yml') as file:\r\n mqtt_config = yaml.load(file, Loader=yaml.FullLoader)\r\n\r\npyrebase_config = {\r\n \"apiKey\": firebase_config['api_key'],\r\n \"authDomain\": firebase_config['auth_domain'],\r\n \"databaseURL\": firebase_config['database_url'],\r\n \"storageBucket\": firebase_config['storage_bucket'],\r\n \"serviceAccount\": firebase_config['service_account']\r\n}\r\n\r\nnode_ids_recognized = set()\r\n\r\n# Firebase: initialize app with config\r\nfirebase = pyrebase.initialize_app(pyrebase_config)\r\n\r\n# Firebase: authenticate a user\r\nauth = firebase.auth()\r\nuser = auth.sign_in_with_email_and_password(firebase_config['email'], firebase_config['password'])\r\n\r\ndb = firebase.database()\r\n\r\ndef handle_firebase_token_refresh():\r\n global user\r\n logging.debug('Refreshing Firebase token...')\r\n user = auth.refresh(user['refreshToken'])\r\n\r\n# need to refresh the firebase token every hour\r\ndef handle_firebase_token_refresh_thread():\r\n logging.debug('handling scheduled firebase token refresh')\r\n handle_firebase_token_refresh()\r\n # 1800 seconds = 30 minutes\r\n threading.Timer(1800, handle_firebase_token_refresh_thread).start()\r\n\r\ndef send_metadata_to_firebase(message):\r\n root_name = basestation_config['root_name']\r\n environment = basestation_config['environment']\r\n version = basestation_config['version']\r\n node_id = message['node_id']\r\n metadata = 'metadata'\r\n\r\n metadata_message = {\r\n \"base-station-id\": basestation_config['base_station_id'],\r\n \"source-id\": basestation_config['source_id'],\r\n \"element\": basestation_config['element'],\r\n \"location\": message['location']\r\n }\r\n\r\n\r\n db.child(root_name) \\\r\n .child(environment) \\\r\n .child(version) \\\r\n .child(metadata) \\\r\n .child(node_id) \\\r\n .set(metadata_message, user['idToken'])\r\n\r\n\r\ndef send_data_to_firebase(message):\r\n logging.debug('Sending event to Firebase...')\r\n\r\n if message['node_id'] not in node_ids_recognized:\r\n send_metadata_to_firebase(message)\r\n node_ids_recognized.add(message['node_id'])\r\n\r\n # Create using push\r\n # We are going to use this option as each send must have a unique ID.\r\n root_name = basestation_config['root_name']\r\n environment = basestation_config['environment']\r\n version = basestation_config['version']\r\n data = 'data'\r\n\r\n telemetry = {\r\n \"node-id\": message['node_id'],\r\n \"data-type\": message['data_type'],\r\n \"measurement-unit\": message['measurement_unit'],\r\n \"timestamp\": datetime.datetime.now().timestamp(),\r\n \"value\": message['value']\r\n }\r\n\r\n db.child(root_name) \\\r\n .child(environment) \\\r\n .child(version) \\\r\n .child(data) \\\r\n .push(telemetry, user['idToken'])\r\n\r\nclient = mqtt.Client()\r\nclient.connect(mqtt_config['address'],mqtt_config['port'])\r\n\r\nhandle_firebase_token_refresh_thread()\r\n\r\ndef on_connect(client, userdata, flags, rc):\r\n logging.debug('Connected to a broker!')\r\n logging.debug('Subscribing to topic: %s', mqtt_config['topic'])\r\n client.subscribe(mqtt_config['topic'])\r\n\r\ndef on_message(client, userdata, message):\r\n decoded_message = message.payload.decode()\r\n logging.debug('%s', decoded_message)\r\n\r\n send_data_to_firebase(json.loads(decoded_message))\r\n\r\nwhile True:\r\n client.on_connect = on_connect\r\n client.on_message = on_message\r\n client.loop_forever()","sub_path":"src/mqtt_subscriber_to_firebase.py","file_name":"mqtt_subscriber_to_firebase.py","file_ext":"py","file_size_in_byte":4361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"223244728","text":"# -*- coding: utf-8 -*-\n\"\"\"\nLibrary for demonstrating simple collaborative filtering\n@author: barry shepherd\n\"\"\"\n\nimport os\nimport math\nimport numpy as np\nimport pandas as pd\nimport time\nfrom statistics import mean\nfrom math import sqrt\n\n# convert the transaction data (long data) into a ratings matrix (wide data)\n# assume the first two columns are user and item names (which may be strings or integers and may not be contiguous)\n# also generate two lookup tables to map user and item names into indexes for accessing the ratings matrix\ndef makeratingsmatrix(trans):\n trans = trans.iloc[:,0:3] # keep only first 3 columns\n trans.columns = ['user','item','rating']\n # create the mappings between user and item names (as in raw data) and the matrix row and column indexes\n unames = np.sort(trans['user'].unique())\n inames = np.sort(trans['item'].unique())\n umap = dict(zip(unames,[i for i in range(len(unames))]))\n imap = dict(zip(inames,[i for i in range(len(inames))]))\n # create the ratings matrix, use average if multiple raings exist for same (user,item)\n #users = trans.pivot(index='user', columns='item', values='rating').values # fast, but no averaging, rows & cols are alphnum order\n users = pd.pivot_table(trans, index=['user'], columns=['item'], values=['rating'],aggfunc=[mean]).values # slower\n return [users, umap, imap]\n\ndef head(arr,r=10,c=10):\n nr, nc = arr.shape\n with np.printoptions(threshold=np.inf):\n if type(arr) == np.ndarray:\n print(arr[0:min(r,nr),0:min(c,nc)])\n else:\n print(arr.iloc[0:min(r,nr),0:min(c,nc)])\n\ndef sparsity(arr):\n return float(np.isnan(arr).sum()*100)/np.prod(arr.shape)\n #return (1.0 - ( count_nonzero(arr) / float(arr.size) ))\n\ndef wtavg(vals, weights):\n xy = vals * weights\n weights = weights[np.isnan(xy) == False] \n #if len(weights) == 0 : return np.nan\n if sum(weights) == 0 : return np.nan\n vals = vals[np.isnan(xy)==False]\n return sum(vals * weights)/sum(weights)\n \ndef pearsonsim(x,y):\n xy = x*y\n x = x[np.isnan(xy)==False]\n y = y[np.isnan(xy)==False]\n if(len(x)==0): return np.nan\n mx=mean(x)\n my=mean(y)\n rt = sqrt(sum((x-mx)**2)*sum((y-my)**2))\n if (rt == 0): return np.nan #math.isnan(rt)==True or \n return sum((x-mx)*(y-my))/rt\n \ndef cosinesim(x,y):\n xy = x*y\n x = x[np.isnan(xy)==False]\n y = y[np.isnan(xy)==False]\n if(len(x)==0): return np.nan\n rt = sqrt(sum(x**2)*sum(y**2))\n return sum(x*y)/rt\n\ndef euclidsim(x,y):\n xy = x*y\n x = x[np.isnan(xy)==False]\n y = y[np.isnan(xy)==False]\n z=(y-x)**2\n sz=sqrt(sum(z))\n return 1/(1+sz)\n\ndef euclidsimF(x,y):\n xy = x*y\n x = x[np.isnan(xy)==False]\n y = y[np.isnan(xy)==False]\n z=(y-x)**2\n return 1/(1+sum(z))\n\ndef getitemsimsmatrix(ratsmatrix,simfun):\n r,c = ratsmatrix.shape\n matrx = list([])\n for col1 in range(0,c):\n simrow = [0]*col1\n for col2 in range(col1,c):\n simrow.append(simfun(ratsmatrix[:,col1],ratsmatrix[:,col2]))\n matrx.append(simrow)\n matrx = np.array(matrx)\n matrx = matrx + matrx.T - np.diag(np.diag(matrx))\n return matrx\n \ndef predictrating_UU(targetrats, ratsmatrix, targetitemindx, simfun):\n return predictratings_UU(targetrats, ratsmatrix, doitems=[targetitemindx], simfun=simfun)[0]\n\ndef predictratings_UU(targetrats, ratsmatrix, doitems, simfun=pearsonsim):\n sims = list([])\n for row in ratsmatrix: sims.append(simfun(row,targetrats))\n sims = np.array(sims)\n with np.errstate(invalid='ignore'): sims[sims < 0] = np.nan\n rats = list([])\n for col in doitems: rats.append(wtavg(ratsmatrix[:,col],sims)) # assumes target rating is NA (if target in usersA)\n return np.array(rats)\n\ndef predictrating_II(targetrats, itemsims, targetitemid):\n return predictratings_II(targetrats, itemsims, doitems=[targetitemid])[0]\n\ndef predictratings_II(targetrats,itemsims,doitems):\n seenitems = np.isnan(targetrats)==False\n rats = list([])\n for row in doitems:\n rats.append(wtavg(targetrats[seenitems],itemsims[row,seenitems])) \n return np.array(rats)\n\ndef getRecommendations_UU(targetrats, ratsmatrix, imap, simfun=pearsonsim,topN=5):\n itemnames=list(imap.keys())\n unseenitemids = np.where(np.isnan(targetrats)==True)[0]\n ratsA = predictratings_UU(targetrats, ratsmatrix, doitems=unseenitemids, simfun=simfun)\n rats = pd.DataFrame(ratsA,index=[itemnames[i] for i in unseenitemids],columns=['predrating'])\n rats = rats.sort_values(ascending = False, by=['predrating'])\n return rats[0:min(topN,len(rats))]\n \ndef getRecommendations_II(targetrats, itemsims, imap, topN=5):\n itemnames=list(imap.keys()) \n unseenitemids = np.where(np.isnan(targetrats)==True)[0]\n ratsA = predictratings_II(targetrats,itemsims,doitems=unseenitemids)\n rats = pd.DataFrame(ratsA,index=[itemnames[i] for i in unseenitemids],columns=['predrating'])\n rats = rats.sort_values(ascending = False, by=['predrating'])\n return rats[0:min(topN,len(rats))]\n\n# compute prediction errors (predicted rating - actual rating) for the test events (events ~ 'user,item,rating')\ndef computeErrs_UU(testevents, ratsmatrix, uids, iids, simfun=cosinesim):\n res = list([])\n for testevent in testevents:\n print('.', end = '')\n testuserindx = uids[testevent[0]]\n testitemindx = iids[testevent[1]]\n pred = predictrating_UU(ratsmatrix[testuserindx,],ratsmatrix,testitemindx,simfun=simfun)\n res.append(pred-testevent[2])\n return np.array(res)\n\ndef computeErrs_II(testevents, ratsmatrix, uids, iids, itemsims):\n res = list([])\n for testevent in testevents:\n print('.', end = '')\n testuserindx = uids[testevent[0]]\n testitemindx = iids[testevent[1]]\n pred = predictrating_II(ratsmatrix[testuserindx,],itemsims,testitemindx)\n res.append(pred-testevent[2])\n return np.array(res)\n\n# returns the percentage ranking for each test event\n# if itemsims is supplied then do item-based CF, else do user-based CF\ndef computePR(testevents, ratsmatrix, uids, iids, itemsims=False, simfun=cosinesim):\n res = list([])\n for testevent in testevents:\n print('.', end = '')\n testuserindx = uids[testevent[0]]\n if (type(itemsims) == bool):\n recs = getRecommendations_UU(ratsmatrix[testuserindx,], ratsmatrix, iids, simfun=simfun, topN=100000)\n else:\n recs = getRecommendations_II(ratsmatrix[testuserindx,], itemsims, iids, topN=100000)\n rkpc = ((recs.index.get_loc(testevent[1]) + 1)*100)/len(recs)\n res.append(rkpc)\n return np.array(res)\n\n \n\n","sub_path":"Workshop1/demolib-arrays-v9.py","file_name":"demolib-arrays-v9.py","file_ext":"py","file_size_in_byte":6674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"213410359","text":"\nimport pandas as pd\nimport numpy as np\nfrom sklearn import datasets\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import Perceptron,LogisticRegression\nfrom sklearn.metrics import accuracy_score\nfrom matplotlib.colors import ListedColormap\nimport matplotlib.pyplot as plt\n\n\ndef plot_decision_regions(X, y, classifier,test_idx=None, resolution=0.02):\n # setup marker generator and color map\n markers = ('s', 'x', 'o', '^', 'v')\n colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')\n cmap = ListedColormap(colors[:len(np.unique(y))])\n # plot the decision surface\n x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1\n x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1\n xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),\n np.arange(x2_min, x2_max, resolution))\n Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)\n Z = Z.reshape(xx1.shape)\n plt.contourf(xx1, xx2, Z, alpha=0.3, cmap=cmap)\n plt.xlim(xx1.min(), xx1.max())\n plt.ylim(xx2.min(), xx2.max())\n # plot class examples\n for idx, cl in enumerate(np.unique(y)):\n plt.scatter(x=X[y == cl, 0],y=X[y == cl, 1],alpha=0.8, c=colors[idx],\n marker=markers[idx], label=cl, edgecolor='black')\n\n # highlight test samples\n if test_idx:\n # plot all samples\n X_test, y_test = X[test_idx, :], y[test_idx]\n plt.scatter(X_test[:, 0], X_test[:, 1], c='', edgecolor='black', alpha=1.0,\n linewidth=1, marker='o', s=100, label='test set')\n\ndef load_iris_data():\n iris = datasets.load_iris()\n X = iris.data[:, [2, 3]]\n y = iris.target\n print('Class labels:', np.unique(y))\n\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 1, stratify = y)\n\n print('Labels counts in y_train:', np.bincount(y_train))\n print('Labels counts in y_test:', np.bincount(y_test))\n\n sc = StandardScaler()\n sc.fit(X_train) #Using the fit method, StandardScaler estimated the parameters\n # μ (sample mean) and σ (standard deviation) for each feature dimension from the training data.\n X_train_std = sc.transform(X_train)\n X_test_std = sc.transform(X_test)\n\n return X_train_std,X_test_std,y_train, y_test\n\ndef test_ppn(X_train_std,X_test_std,y_train, y_test):\n ppn = Perceptron(max_iter=40, eta0=0.1, random_state=1)\n ppn.fit(X_train_std, y_train)\n\n y_pred = ppn.predict(X_test_std)\n print('Misclassified samples: %d' % (y_test != y_pred).sum())\n print('Accuracy: %.2f' % accuracy_score(y_test, y_pred))\n\n X_combined_std = np.vstack((X_train_std, X_test_std))\n y_combined = np.hstack((y_train, y_test))\n plot_decision_regions(X=X_combined_std,y = y_combined,classifier = ppn,test_idx = range(105, 150))\n plt.xlabel('petal length [standardized]')\n plt.ylabel('petal width [standardized]')\n plt.legend(loc='upper left')\n plt.show()\n\nclass Logistic_regression():\n def __init__(self,eta=0.0001,n_iter=1000):\n self.max_iter=n_iter\n self.eta=eta\n self.w_initialized = False\n self.shuffle = True\n self.cost_ = []\n\n def fit(self,x,y_gt):\n x_1 = np.hstack((x, np.ones((x.shape[0], 1))))\n self.w_=np.random.random(x_1.shape[-1])\n\n for iter in range(self.max_iter):\n hidden=self.net_input(x_1)\n y_pred=self.activation(hidden)\n dw_=self.eta*np.dot(x_1.T ,y_gt-y_pred)\n print(dw_)\n if np.sum(abs(dw_))<10e-9:\n break\n self.w_+=dw_\n self.cost_.append(-(y_gt*(np.log(y_pred)+(1-y_gt)*np.log(1-y_pred))))\n\n def partial_fit(self, X, y):\n if not self.w_initialized:\n self._initialize_weights(X.shape[1])\n if y.ravel().shape[0] > 1:\n for xi, target in zip(X, y):\n self._update_weights(xi, target)\n else:\n self._update_weights(X, y)\n return self\n\n def predict(self,x):\n x = np.hstack((x,np.ones((x.shape[0],1))))\n y_pred = self.activation(self.net_input(x))\n return np.array([1 if i > 0.5 else 0 for i in y_pred])\n\n def net_input(self,x):\n return np.dot(x,self.w_)#np.sum(x * self.w_, axis=1)\n\n def activation(self, X):\n return 1/(1+np.exp(-np.clip(X, -250, 250)))\n\n def _initialize_weights(self, m):\n self.w_ = np.random.random(1 + m)\n self.w_initialized = True\n\n def _shuffle(self, X, y):\n r = np.random.permutation(len(y))\n return X[r], y[r]\n\ndef plot_sigmoid():\n def sigmoid(z):\n return 1.0 / (1.0 + np.exp(-z))\n\n z = np.arange(-7, 7, 0.1)\n phi_z = sigmoid(z)\n plt.plot(z, phi_z)\n plt.axvline(0.0, color='k')\n plt.ylim(-0.1, 1.1)\n plt.xlabel('z')\n plt.ylabel('$\\phi (z)$') # y axis ticks and gridline\n plt.yticks([0.0, 0.5, 1.0])\n ax = plt.gca()\n ax.yaxis.grid(True)\n plt.show()\n\nX_train_std,X_test_std,y_train, y_test= load_iris_data()\n\n\n\nweights, params = [], []\nfor c in np.arange(-5, 5):\n lr = LogisticRegression(C=10.**c, random_state=1,\n solver='lbfgs',\n multi_class='ovr')\n lr.fit(X_train_std, y_train)\n weights.append(lr.coef_[1])\n params.append(10.**c)\n\nweights = np.array(weights)\nplt.plot(params, weights[:, 0],\n label='petal length')\nplt.plot(params, weights[:, 1], linestyle='--',\n label='petal width')\nplt.ylabel('weight coefficient')\nplt.xlabel('C')\nplt.legend(loc='upper left')\nplt.xscale('log')\n#plt.savefig('images/03_08.png', dpi=300)\nplt.show()","sub_path":"ch03/sklearn_utils.py","file_name":"sklearn_utils.py","file_ext":"py","file_size_in_byte":5631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"515298487","text":"import matplotlib.pyplot as plt\n\n# Measurements from block-size.data\nbsize = [\n ('Bamboo-SL',[\n (16.159, 10.15),\n (46.159, 10.76),\n (67.320, 12.25),\n (101.170, 16.63),\n (117.174, 21.69),\n (128.625, 26.85),\n (132.803, 30.55),\n (136.484, 36.5),\n (138.231, 45.44),\n (144.888, 51.7)\n ], '-o', 'coral'),\n ('Model-SL',[\n (16.519,5.53),\n (46.159,7.50),\n (67.32,9.86),\n (101.170,19.475),\n (128.625,26.33),\n (132.803,33.99),\n (136.484,44.74),\n ], '-s', 'steelblue')]\n\ndef do_plot():\n f = plt.figure(1, figsize=(7,5))\n plt.clf()\n ax = f.add_subplot(1, 1, 1)\n for name, entries, style, color in bsize:\n throughput = []\n latency = []\n for t, l in entries:\n throughput.append(t)\n latency.append(l)\n ax.plot(throughput, latency, style, color=color, label='%s' % name, markersize=8, alpha=0.8)\n plt.legend(loc='best', fancybox=True,frameon=False,framealpha=0.8)\n plt.grid(linestyle='--', alpha=0.3)\n plt.ylabel('Latency (ms)')\n plt.xlabel('Throughput (KTx/s)')\n plt.tight_layout()\n plt.ylim([0,60])\n plt.savefig('model-implementation.pdf', format='pdf')\n plt.show()\n\nif __name__ == '__main__':\n do_plot()\n","sub_path":"plot/model/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"552894734","text":"def binary_length(n):\n if n == 0: return 0\n else: return 1 + binary_length(n / 256)\n\ndef to_binary_array(n,L=None):\n if L is None: L = binary_length(n)\n if n == 0: return []\n else:\n x = to_binary_array(n / 256)\n x.append(n % 256)\n return x\n\ndef to_binary(n,L=None): return ''.join([chr(x) for x in to_binary_array(n,L)])\n\ndef from_binary(b):\n if len(b) == 0: return 0\n else: return from_binary(b[:-1]) * 256 + ord(b[-1])\n\ndef __decode(s,pos=0):\n if not s:\n return (None, 0)\n else:\n fchar = ord(s[pos])\n if fchar < 128:\n return (ord(s[pos]), pos+1)\n elif fchar < 184:\n b = ord(s[pos]) - 128\n return (s[pos+1:pos+1+b], pos+1+b)\n elif fchar < 192:\n b = ord(s[pos]) - 183\n b2 = from_binary(s[pos+1:pos+1+b])\n return (s[pos+1+b:pos+1+b+b2], pos+1+b+b2)\n elif fchar < 248:\n b = ord(s[pos]) - 192\n o, pos = [], pos+1\n for i in range(b):\n obj, pos = __decode(s,pos)\n o.append(obj)\n return (o,pos)\n else:\n b = ord(s[pos]) - 247\n b2 = from_binary(s[pos+1:pos+1+b])\n o, pos = [], pos+1+b\n for i in range(b):\n obj, pos = __decode(s,pos)\n o.append(obj)\n return (o,pos)\n\ndef decode(s): return __decode(s)[0]\n\ndef encode_length(L,offset):\n if L < 56:\n return chr(L + offset)\n elif L < 256**8:\n BL = to_binary(L)\n return chr(len(BL) + offset + 55) + BL\n else:\n raise Exception(\"input too long\")\n\ndef encode(s):\n if isinstance(s,(str,unicode)):\n s = str(s)\n if len(s) == 1 and ord(s) < 128: return s\n else: return encode_length(len(s),128) + s\n elif isinstance(s,list):\n output = ''\n for item in s: output += encode(item)\n return encode_length(len(output),192) + output\n","sub_path":"rlp.py","file_name":"rlp.py","file_ext":"py","file_size_in_byte":1868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"639403087","text":"import sys\n\ndef solve(ip):\n\tstall = ip[0]\n\tpeeps = int(ip[1])\n\tparts = []\n\tparts.append(int(stall))\n\ti=0\n\ty = 0\n\tz = 0\n\twhile i < peeps:\n\t\tlargest = max(parts)\n\t\tindex = parts.index(largest)\n\t\tparts.pop(index)\n\t\tif largest%2 == 0:\n\t\t\ty = (largest/2)-1\n\t\t\tz = y+1\n\t\telse:\n\t\t\ty = largest/2\n\t\t\tz = y\n\t\tparts.append(y)\n\t\tparts.append(z)\n\t\ti = i+1\n\treturn [max([y,z]),min([y,z])]\n\nif __name__ == \"__main__\":\n\tinputlist = [line.rstrip('\\n') for line in open(str(sys.argv[1]))]\n\tcases = inputlist[0]\n\tinputlist.pop(0)\n\tindex = 1\n\tfor line in inputlist:\n\t\tsoln = solve(line.split(' '))\n\t\ths = open(\"soln.txt\",\"a\")\n\t\ths.write('Case #'+str(index)+': '+str(soln[0])+' '+str(soln[1])+'\\n')\n\t\tindex = index+1\n","sub_path":"solutions_python/Problem_201/2716.py","file_name":"2716.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"510227166","text":"import numpy as np\r\nimport scipy.sparse as sp\r\nfrom tqdm import tqdm\r\nnp.random.seed(0)\r\n\r\ndef Scan_Context_process(PAR, args):\r\n NUM_WALKS = args.num_walks\r\n verbose=args.verbose\r\n seed = args.seed\r\n window, nb_negative = args.window_hsize, args.num_negative\r\n train_sen, word2id, id2word, subsamples = PAR['cata_sentences'], PAR['word2id'], PAR['id2word'], PAR['subsamples']\r\n num_node = PAR['nb_id']#len(word2id.keys())+1\r\n mulfn = []\r\n\r\n mulDmatrix = []\r\n mulComatrix_1hop =[]\r\n\r\n mulreformfnlist = []\r\n mulreformfn = []\r\n\r\n mulcount_list = []\r\n mulnegFre = []\r\n mulnegFrea = []\r\n Max_win_count = 0 \r\n\r\n \r\n if verbose == True:\r\n print('Scaning Contexts...')\r\n #sentences in walks\r\n\r\n #initial\r\n fn = []\r\n reformfn = {x:[] for x in range(num_node)}\r\n window_count = {x:0 for x in range(num_node)}\r\n Comatrix = (np.zeros((num_node, num_node)))\r\n Comatrix_1hop = (np.zeros((num_node, num_node)))\r\n Win_stack = {}\r\n if len(train_sen)>1:\r\n train_sen = [train_sen]\r\n for sens in (train_sen):\r\n # if NUM_WALKS subsamples[d[i]] and i>window:\r\n continue\r\n #End subsampling\r\n \r\n #save window in sequence form\r\n win = d[i-window:i+1+window] \r\n\r\n #save window in node-wise form\r\n reformfn[d[i]].append(win)\r\n window_count[d[i]]+=1\r\n\r\n #co-cuurence matrix\r\n c = win[window]\r\n for w in win[:window]:\r\n Comatrix[c, w] += 1\r\n Comatrix_1hop[c, w] += 1\r\n for w in win[(window+1)::]:\r\n Comatrix[c, w] += 1\r\n Comatrix_1hop[c, win[window+1]] += 1\r\n ###End window in sentence\r\n ##End sentence in sentences\r\n #End sentences in walks\r\n #...............................\r\n mulfn.append(sp.csr_matrix(fn))\r\n fn = None\r\n # Comatrix_1hop[:, 0] *=0 # SK\r\n mulComatrix_1hop.append(sp.csr_matrix(Comatrix_1hop))\r\n Comatrix_1hop =None\r\n #...............................\r\n\r\n #check\r\n #print(\"Check...\")\r\n #for k, v in reformfn.items():\r\n # if len(v)==0:\r\n # print(k)\r\n\r\n \r\n #update Max_win_count\r\n if verbose == True:\r\n print('Counting Contexts...')\r\n \r\n #update Max_win_count for NUM_WALK >1\r\n cur_max = max(window_count.values())\r\n Max_win_count = cur_max if Max_win_count< cur_max else Max_win_count\r\n\r\n\r\n #number of contexts per node\r\n count_list = [window_count[i] for i in range(num_node)]\r\n count_list_sort = sorted(count_list)[::-1]\r\n\r\n \r\n #Neg sampling\r\n TotalF = sum(np.array(count_list)) #total window_count\r\n negFre = [[0]* nb_negative] #neg samples padding for id 0\r\n negFrea = [] #controller\r\n \r\n #set context co-occurance prob.\r\n ALL_Win = [[j,(f)] for j,f in enumerate(count_list)]\r\n ALL_Win = np.array(ALL_Win)\r\n\r\n\r\n #Presampling Neg samples id\r\n np.random.seed(seed)\r\n Preindex = np.random.choice(ALL_Win[:, 0], nb_negative+10, replace=False, p=[(x/sum(ALL_Win[:, 1])) for x in ALL_Win[:, 1]])\r\n Preindex = [int(x) for x in Preindex]\r\n \r\n #Neg sampling controller\r\n indexa = np.array(count_list_sort[0])/TotalF\r\n #indexa = indexa.tolist()\r\n \r\n #choose neg samples out of contexts\r\n if verbose == True:\r\n print('Neg.Sampling...')\r\n \r\n for i in range(1, num_node):\r\n index = [j for j in Preindex if i!=j and Comatrix[i,j]==0][:nb_negative]\r\n ##if neg samples are not enough \r\n while len(index) < nb_negative:\r\n x=int(np.random.choice(ALL_Win[:, 0], 1, replace=False, p=[(x/sum(ALL_Win[:, 1])) for x in ALL_Win[:, 1]]))\r\n if i!=x and Comatrix[i,x]==0:\r\n index.append(x)\r\n ##save id \r\n negFre.append(sp.csr_matrix(index))\r\n index = None\r\n\r\n negFrea.append(indexa)\r\n\r\n #Normalized co-cuurence matrix\r\n # Comatrix[:, 0] *=0 # SK\r\n Dmatrix = Comatrix\r\n Comatrix = None\r\n Dmatrix[0] = (np.zeros(Dmatrix.shape[0]))\r\n Dmatrix[0,0]=1\r\n n_base = np.sqrt(np.sum(Dmatrix, 1))\r\n Dmatrix = ((Dmatrix.T/n_base).T)\r\n n_base = None\r\n \r\n #...............................\r\n mulDmatrix.append(sp.csr_matrix(Dmatrix))\r\n Dmatrix = None\r\n #............................... \r\n mulcount_list.append(count_list)\r\n count_list = None\r\n mulnegFre.append(sp.vstack(negFre))\r\n negFre = None\r\n mulnegFrea.append(negFrea)\r\n negFrea = None \r\n #...............................\r\n mulreformfnlist.append([reformfn[i] for i in range(len(reformfn))])\r\n reformfn = None\r\n #...............................\r\n\r\n if verbose == True:\r\n print('Summarizing...')\r\n\r\n mulreformfn = mulreformfnlist\r\n # for fnlist_id in range(len(mulreformfnlist)):\r\n # fnlist = mulreformfnlist[fnlist_id]\r\n # mulreformfnlist[fnlist_id] = None\r\n\r\n # reformfn = (np.zeros((num_node, Max_win_count*(window*2+1))))\r\n # ##each node\r\n # for i in range(len(fnlist)):\r\n # ##each window\r\n # for j in range(len(fnlist[i])):\r\n # reformfn[i, (window*2+1)*j:(window*2+1)*(j+1)] = fnlist[i][j]\r\n\r\n # mulreformfn.append(sp.csr_matrix(reformfn))\r\n # reformfn = None\r\n\r\n\r\n out_name = [\"mulDmatrix\", \"mulreformfn\", \"mulcount_list\", \"Max_win_count\", \"mulnegFre\", \"mulnegFrea\", \"mulComatrix_1hop\"]\r\n out_var = [mulDmatrix, mulreformfn, mulcount_list, Max_win_count, mulnegFre, mulnegFrea, mulComatrix_1hop]\r\n out ={}\r\n for n, v in zip(out_name, out_var):\r\n out[n] = v\r\n if verbose == True:\r\n print('Contexts Generating Done!')\r\n return out\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"CoANE topk with attributes preservation/CoANE/Contexts_Generator.py","file_name":"Contexts_Generator.py","file_ext":"py","file_size_in_byte":6217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"416851586","text":"import pandas as pd\nimport numpy as np\nimport json\nimport sys\nfrom GPfates import GPfates\n\nimport time\ncheckpoints = {}\n\n# ____________________________________________________________________________\n# Load data ####\np = json.load(open(\"/input/params.json\", \"r\"))\nend_n = json.load(open(\"/input/end_n.json\"))[0]\nexpression = pd.read_csv(\"/input/expression.csv\", index_col=0, header=0)\nexpression = expression[(expression > p[\"log_expression_cutoff\"]).sum(1) >= p[\"min_cells_expression_cutoff\"]]\n\nif expression.shape[0] == 0:\n raise ValueError(\"Expression preprocessing filtered out all cells\")\n\ncheckpoints[\"method_afterpreproc\"] = time.time()\n\n# ____________________________________________________________________________\n# Infer trajectory ####\ncellinfo = pd.DataFrame({\"cell_id\":expression.index.tolist()}, index = expression.index.tolist())\nm = GPfates.GPfates(cellinfo, expression.T)\n\n# dimensionality reduction\nm.dimensionality_reduction()\nm.store_dr(dims=range(p[\"ndim\"])) # store the dr in the sample table (m.s), so it can be used in the gplvm\n\n# infer pseudotime\nm.infer_pseudotime(s_columns=[\"bgplvm_\" + str(i) for i in range(p[\"ndim\"])]) # use the first two components to infer pseudotime\n\n# model different fates\nm.model_fates(C=end_n)\n\ncheckpoints[\"method_aftermethod\"] = time.time()\n\n# ____________________________________________________________________________\n# Process and save output ####\n# pseudotime\npseudotime = m.s.pseudotime.reset_index()\npseudotime.columns = [\"cell_id\", \"pseudotime\"]\npseudotime.to_csv(\"/output/pseudotime.csv\", index=False)\n\n# milestone network\nmilestone_network = pd.DataFrame({\n \"from\":\"M0\",\n \"to\":[\"M\" + str(i+1) for i in range(end_n)],\n \"length\":1,\n \"directed\":True\n})\nmilestone_network.to_csv(\"/output/milestone_network.csv\", index=False)\n\n# dimred\ndimred = pd.DataFrame(m.dr_models[\"bgplvm\"].X.mean[:,:].tolist())\ndimred[\"cell_id\"] = m.s.pseudotime.index.tolist()\ndimred.to_csv(\"/output/dimred.csv\", index=False)\n\n# progressions\nprogressions = pd.DataFrame(m.fate_model.phi)\nprogressions[\"cell_id\"] = m.s.pseudotime.index.tolist()\nprogressions = progressions.melt(id_vars = [\"cell_id\"], var_name = \"to\", value_name = \"percentage\")\nprogressions[\"to\"] = [\"M\" + str(i+1) for i in progressions[\"to\"]]\nprogressions[\"from\"] = \"M0\"\nprogressions.to_csv(\"/output/progressions.csv\", index=False)\n\n# divergence regions\ndivergence_regions = pd.DataFrame({\n \"milestone_id\": [\"M0\"] + [\"M\" + str(i+1) for i in range(end_n)],\n \"divergence_id\": \"A\",\n \"is_start\": [True] + [False for i in range(end_n)]\n})\ndivergence_regions.to_csv(\"/output/divergence_regions.csv\", index=False)\n\n# timings\njson.dump(checkpoints, open(\"/output/timings.json\", \"w\"))\n","sub_path":"containers/gpfates/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"329905576","text":"from schools3.ml.base.hyperparameters import *\nimport schools3.config.ml.hyperparameters.random_forest_hyperparameters_config as config\n\nclass RandomForestHyperparameters(Hyperparameters):\n def __init__(self, n_estimators=None, max_depth=None, min_samples_leaf=None, seed=None, max_features=None):\n super(RandomForestHyperparameters, self).__init__()\n self.n_estimators = config.get_n_estimators_hp(n_estimators)\n self.max_depth = config.get_max_depth_hp(max_depth)\n self.min_samples_leaf = config.get_min_samples_leaf_hp(min_samples_leaf)\n self.seed = config.get_seed_hp(seed)\n self.max_features = config.get_max_features_hp(max_features)\n","sub_path":"schools3/ml/hyperparameters/random_forest_hyperparameters.py","file_name":"random_forest_hyperparameters.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"576153263","text":"from youtube2notion.youtube2notion import Youtube2notion\nimport click\n\n\n@click.command()\n@click.argument('video_id')\n@click.option('--output-dir', '-o', 'output_dir', required=False, type=str)\n@click.option(\n '--notion-token-v2', '-t', 'notion_token_v2', required=False, type=str)\n@click.option(\n '--notion-page-url', '-p', 'notion_page_url', required=False, type=str)\n@click.option(\n '--text_language', '-l', 'text_language', required=False, type=str)\ndef youtube2notion(video_id: str, output_dir, notion_token_v2, notion_page_url, text_language):\n if not output_dir:\n output_dir = './tmp/%s/' % video_id\n\n click.echo('video_id: %s' % video_id)\n click.echo('output_dir: %s' % output_dir)\n click.echo('notion_token_v2: %s' % notion_token_v2)\n click.echo('notion_page_url: %s' % notion_page_url)\n click.echo('text_language: %s' % text_language)\n\n y2n = Youtube2notion(\n video_id=video_id,\n output_dir=output_dir,\n notion_token_v2=notion_token_v2,\n notion_page_url=notion_page_url,\n text_language=text_language)\n\n try:\n y2n.execute()\n except Exception as e:\n print(e)\n\n\nif __name__ == '__main__':\n youtube2notion()\n","sub_path":"youtube2notion.py","file_name":"youtube2notion.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"536199965","text":"import os\n\nfrom . import logger_helper as lh\n\nlogger = None\ninited = False\n\n\ndef init(conf=None, default_logger='common'):\n \"\"\"\n 初始化\n :param conf 这个参数\n :param default_logger 默认的日志对象的key\n :return:\n \"\"\"\n global logger, inited\n if inited:\n return\n if conf is None:\n conf = os.environ.get('ANDERSEN_CONFIG', None)\n lh.load_config(conf)\n lh.init_logger()\n logger = lh.get_logger(default_logger)\n inited = True\n\n\ndef get_logger(key='common'):\n return lh.get_logger(key)\n\n\ndef generate_sample_config(filename):\n \"\"\"\n 生成示例配置文件\n :param filename:\n :return:\n \"\"\"\n lh.generate_sample_config(filename)\n\n\ndef _get_param(kwargs):\n global logger\n list_sep = ', '\n dict_sep = '\\n'\n para_sep = '\\n'\n if 'sep' in kwargs:\n list_sep = kwargs['sep']\n dict_sep = kwargs['sep']\n para_sep = kwargs['sep']\n del kwargs['sep']\n if 'list_sep' in kwargs:\n list_sep = kwargs['list_sep']\n del kwargs['list_sep']\n if 'dict_sep' in kwargs:\n dict_sep = kwargs['dict_sep']\n del kwargs['dict_sep']\n if 'para_sep' in kwargs:\n para_sep = kwargs['para_sep']\n del kwargs['para_sep']\n local_log = logger\n if 'logger' in kwargs:\n local_log = lh.get_logger(kwargs['logger'])\n del kwargs['logger']\n return local_log, list_sep, dict_sep, para_sep\n\n\ndef _log_args(args, list_sep):\n if not args:\n return ''\n args = [str(arg) for arg in args]\n return list_sep.join(args)\n\n\ndef _log_kwargs(kwargs, dict_sep):\n if not kwargs:\n return ''\n out_str = []\n for k, v in kwargs.items():\n out_str.append(f'{str(k)}={str(v)}')\n return dict_sep.join(out_str)\n\n\ndef debug(*args, **kwargs):\n local_log, list_sep, dict_sep, para_sep = _get_param(kwargs)\n out_str1 = _log_args(args, list_sep)\n out_str2 = _log_kwargs(kwargs, dict_sep)\n if out_str1 and out_str2:\n out_str = para_sep.join([out_str1, out_str2])\n elif out_str1:\n out_str = out_str1\n elif out_str2:\n out_str = out_str2\n else:\n out_str = ''\n local_log.debug(out_str)\n\n\ndef info(*args, **kwargs):\n local_log, list_sep, dict_sep, para_sep = _get_param(kwargs)\n out_str1 = _log_args(args, list_sep)\n out_str2 = _log_kwargs(kwargs, dict_sep)\n if out_str1 and out_str2:\n out_str = para_sep.join([out_str1, out_str2])\n elif out_str1:\n out_str = out_str1\n elif out_str2:\n out_str = out_str2\n else:\n out_str = ''\n local_log.info(out_str)\n\n\ndef warn(*args, **kwargs):\n local_log, list_sep, dict_sep, para_sep = _get_param(kwargs)\n out_str1 = _log_args(args, list_sep)\n out_str2 = _log_kwargs(kwargs, dict_sep)\n if out_str1 and out_str2:\n out_str = para_sep.join([out_str1, out_str2])\n elif out_str1:\n out_str = out_str1\n elif out_str2:\n out_str = out_str2\n else:\n out_str = ''\n local_log.warn(out_str)\n\n\ndef error(*args, **kwargs):\n local_log, list_sep, dict_sep, para_sep = _get_param(kwargs)\n out_str1 = _log_args(args, list_sep)\n out_str2 = _log_kwargs(kwargs, dict_sep)\n if out_str1 and out_str2:\n out_str = para_sep.join([out_str1, out_str2])\n elif out_str1:\n out_str = out_str1\n elif out_str2:\n out_str = out_str2\n else:\n out_str = ''\n local_log.error(out_str)\n\n\ninit()\ninited = False\n","sub_path":"andersen/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":3465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"573440646","text":"import unittest\r\nfrom wine import data_knn3, data_knn5, data_kmeans\r\n\r\n\r\nclass Test_KNN3(unittest.TestCase):\r\n\r\n\tdef test_knn3(self):\r\n\t\texpected_n3 = 65 <= data_knn3(self) <= 70\r\n\t\tassert data_knn3(self), expected_n3\r\n\t\tprint(\"\\nK nearest Neighbor 3\\n..........Hit\")\r\n\r\n\tdef test_knn5(self):\r\n\t\texpected_n5 = 65 <= data_knn5(self) <= 70\r\n\t\tassert data_knn5(self), expected_n5\r\n\t\tprint(\"\\nK nearest Neighbor 5\\n..........Hit\")\r\n\r\n\tdef test_kmeans(self):\r\n\t\texpected_km = 30 <= data_kmeans(self) <= 70\r\n\t\tassert data_kmeans(self), expected_km\r\n\t\tprint(\"K-means Clustering\\n..........Hit\")\r\n\t\t\t\r\nif __name__ == '__main__':\r\n\tunittest.main()","sub_path":"unittest_wine.py","file_name":"unittest_wine.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"173114521","text":"## Script (Python) \"get_tabs\"\n##bind container=container\n##bind context=context\n##bind namespace=\n##bind script=script\n##bind subpath=traverse_subpath\n##parameters=\n##title=\n##\n# define:\n# name, id, up_id, toplink_accesskey, tab_accesskey, uplink_accesskey\ntabs = [('editor', 'tab_edit', 'tab_edit', '!', '1', '6'),\n ('preview', 'tab_preview', 'tab_preview', '@', '2', '7'),\n ('properties', 'tab_metadata', 'tab_metadata', '#', '3', '8'),\n ('access', 'tab_access', 'tab_access', '$', '4', '9'),\n ('status', 'tab_status', 'tab_status', '%', '5', '0'),\n ]\n\nreturn tabs\n","sub_path":"views/edit/VersionedContent/Anouncement/get_tabs.py","file_name":"get_tabs.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"123575663","text":"from unittest.mock import patch\n\nfrom lighthouse.constants.fields import FIELD_BARCODE, FIELD_DATE_TESTED, FIELD_LH_SOURCE_PLATE_UUID, FIELD_RESULT\nfrom lighthouse.helpers.mongo import get_positive_samples_in_source_plate, get_source_plate_uuid\n\n\ndef test_get_source_plate_uuid_returns_uuid(app, source_plates):\n with app.app_context():\n result = get_source_plate_uuid(source_plates[0][FIELD_BARCODE])\n\n assert result == source_plates[0][FIELD_LH_SOURCE_PLATE_UUID]\n\n\ndef test_get_source_plate_uuid_returns_none_no_plate_with_barcode(app, source_plates):\n with app.app_context():\n result = get_source_plate_uuid(\"barcode does not exist\")\n\n assert result is None\n\n\ndef test_get_source_plate_uuid_returns_none_failure_fetching_plates(app, source_plates):\n with app.app_context():\n with patch(\"flask.current_app.data.driver.db.source_plates\") as source_plates_collection:\n source_plates_collection.find_one.side_effect = Exception()\n result = get_source_plate_uuid(source_plates[0][FIELD_BARCODE])\n\n assert result is None\n\n\ndef test_get_positive_samples_in_source_plate_returns_matching_samples(app, samples):\n with app.app_context():\n samples, _ = samples\n source_plate_uuid = samples[0][FIELD_LH_SOURCE_PLATE_UUID]\n expected_samples = list(\n filter(\n lambda x: x[FIELD_RESULT] == \"Positive\"\n and x.get(FIELD_LH_SOURCE_PLATE_UUID, False) == source_plate_uuid,\n samples,\n )\n )\n result = get_positive_samples_in_source_plate(source_plate_uuid)\n\n # remove the microsecond before comparing\n if result is not None:\n for res in result:\n res.update({FIELD_DATE_TESTED: res[FIELD_DATE_TESTED].replace(microsecond=0)})\n for sample in expected_samples:\n sample.update({FIELD_DATE_TESTED: sample[FIELD_DATE_TESTED].replace(microsecond=0)})\n\n assert result == expected_samples\n\n\ndef test_get_positive_samples_in_source_plate_returns_empty_list_no_matching_samples(app, samples):\n with app.app_context():\n result = get_positive_samples_in_source_plate(\"source plate uuid does not exist\")\n\n assert result == []\n\n\ndef test_get_positive_samples_in_source_plate_returns_none_failure_fetching_samples(app, samples):\n with app.app_context():\n samples, _ = samples\n with patch(\"flask.current_app.data.driver.db.samples\") as samples_collection:\n samples_collection.find.side_effect = Exception()\n result = get_positive_samples_in_source_plate(samples[0][FIELD_LH_SOURCE_PLATE_UUID])\n\n assert result is None\n","sub_path":"tests/helpers/test_mongo.py","file_name":"test_mongo.py","file_ext":"py","file_size_in_byte":2706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"400299552","text":"# Copyright 2018 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport sys; sys.path.insert(0, '.')\nimport dual_net\nimport strategies\nimport sgf_wrapper\nimport numpy as np\nimport pdb\nimport random\nimport features\nimport symmetries\n\ndef initialize_game(sgf_file, load_file, move=1):\n with open(sgf_file) as f:\n sgf_contents = f.read()\n iterator = sgf_wrapper.replay_sgf(sgf_contents)\n for i in range(move):\n position_w_context = next(iterator)\n player = strategies.MCTSPlayerMixin(dual_net.DualNetwork(load_file))\n player.initialize_game(position_w_context.position)\n return player\n\ndef analyze_symmetries(sgf_file, load_file):\n with open(sgf_file) as f:\n sgf_contents = f.read()\n iterator = sgf_wrapper.replay_sgf(sgf_contents)\n net = dual_net.DualNetwork(load_file)\n for i, pwc in enumerate(iterator):\n if i < 200:\n continue\n feats = features.extract_features(pwc.position)\n variants = [symmetries.apply_symmetry_feat(s, feats) for s in symmetries.SYMMETRIES]\n values = net.sess.run(\n net.inference_output['value_output'],\n feed_dict={net.inference_input['pos_tensor']: variants})\n mean = np.mean(values)\n stdev = np.std(values)\n all_vals = sorted(zip(values, symmetries.SYMMETRIES))\n\n print(\"{:3d} {:.3f} +/- {:.3f} min {:.3f} {} max {:.3f} {}\".format(\n i, mean, stdev, *all_vals[0], *all_vals[-1]))\n\n\n","sub_path":"reinforcement/tensorflow/minigo/oneoffs/inspect_game.py","file_name":"inspect_game.py","file_ext":"py","file_size_in_byte":1967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"410562209","text":"#!/usr/bin/env python\n#coding:utf-8\n\"\"\"\n Author: --\n Purpose: Utils Classes\n Created: 2016/12/13\n\"\"\"\n\nimport unittest\n\n\n########################################################################\nclass Singleton(object):\n \"\"\"\"\"\"\n #_instance = None\n\n #----------------------------------------------------------------------\n def __new__(cls, *args, **kwargs):\n \"\"\"singleton class wrapper\"\"\"\n if not hasattr(cls, '_instance'):\n origin = super(Singleton, cls)\n cls._instance = origin.__new__(cls, *args, **kwargs)\n return cls._instance\n \n \n \nif __name__ == '__main__':\n unittest.main()","sub_path":"g3ar/taskbulter/utils_class.py","file_name":"utils_class.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"221057847","text":"from rest_framework import serializers\nfrom .models import *\n# from django.contrib.auth.models import User\n\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib.auth.models import Group, Permission\nfrom rest_framework.serializers import (\n CharField,\n EmailField,\n HyperlinkedIdentityField,\n ModelSerializer,\n SerializerMethodField,\n ValidationError\n)\nfrom django.contrib.auth import get_user_model\n# from accounts.models import User\nUser = get_user_model()\n\nclass UserCreateSerializer(ModelSerializer):\n email = EmailField(label='Email Address')\n # email2 = EmailField(label='Confirm Email')\n\n class Meta:\n model = User\n fields = [\n 'first_name',\n 'last_name',\n 'username',\n 'email',\n # 'email2',\n 'password',\n\n ]\n extra_kwargs = {\"password\":\n {\"write_only\": True}\n }\n\n def validate(self, data):\n # email = data['email']\n # user_qs = User.objects.filter(email=email)\n # if user_qs.exists():\n # raise ValidationError(\"This user has already registered.\")\n return data\n\n def validate_email(self, value):\n data = self.get_initial()\n email1 = data.get(\"email1\")\n # email2 = value\n # if email1 != email2:\n # raise ValidationError(\"Emails must match.\")\n\n user_qs = User.objects.filter(email=email1)\n if user_qs.exists():\n raise ValidationError(\"This user has already registered.\")\n\n return value\n\n def create(self, validated_data):\n first_name = validated_data['first_name']\n last_name = validated_data['last_name']\n username = validated_data['username']\n email = validated_data['email']\n password = validated_data['password']\n\n user_obj = User(\n first_name=first_name,\n last_name=last_name,\n username=username,\n email=email\n )\n user_obj.set_password(password)\n user_obj.save()\n return validated_data\n\nclass UserLoginSerializer(serializers.ModelSerializer):\n token = serializers.CharField(allow_blank=True, read_only=True)\n username = serializers.CharField()\n email = serializers.EmailField(label='Email Address')\n\n class Meta:\n model = User\n fields = [\n 'username',\n 'email',\n 'password',\n 'token',\n ]\n\n extra_kwargs = {\"password\":\n {\"write_only\": True}\n }\n\n def validate(self, data):\n return data\n\n\nclass TenantSerializer(serializers.ModelSerializer):\n\t# house = HouseNumberSerializer(read_only=True)\n\tclass Meta:\n\t\tmodel = Tenant\n\t\tfields = '__all__'\n\n\nclass BuildingSerializer(serializers.ModelSerializer):\n class Meta:\n model = Building\n fields = '__all__'\n\n \nclass HouseNumberSerializer(serializers.ModelSerializer):\n tenant = TenantSerializer(read_only=True)\n building = BuildingSerializer(read_only=True)\n class Meta:\n model = HouseNumber\n fields = '__all__'\n\nclass RentPaidSerializer(serializers.ModelSerializer):\n\tclass Meta:\n\t\tmodel = RentPaid\n\t\tfields = '__all__'\n\nclass RentPaidCreateSerializer(serializers.ModelSerializer):\n\tclass Meta:\n\t\tmodel = RentPaid\n\t\tfields = '__all__'\n\nclass RentPaidListSerializer(serializers.ModelSerializer):\n\ttenant = TenantSerializer(read_only=True)\n\tclass Meta:\n\t\tmodel = RentPaid\n\t\tfields = '__all__'\n\nclass DeactivateTenantSerializer(serializers.ModelSerializer):\n class Meta:\n model = Tenant\n fields = [\n 'not_active',\n # 'date_left',\n ]\n\n\nclass UserSerializer(serializers.ModelSerializer):\n # snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all())\n class Meta:\n model = User\n # fields = ('id', 'username')\n fields = '__all__'\n\nclass HouseOccupancySerializer(serializers.ModelSerializer):\n tenant = TenantSerializer(read_only=True)\n house = HouseNumberSerializer(read_only=True)\n building = BuildingSerializer(read_only=True)\n \n class Meta:\n model = HouseOccupancy\n fields = '__all__'\n\nclass VendorSerializer(serializers.ModelSerializer):\n class Meta:\n model = Vendor\n fields = '__all__'\n\nclass ExpenseSerializer(serializers.ModelSerializer):\n payee = VendorSerializer(read_only=True)\n building = BuildingSerializer(read_only=True)\n\n class Meta:\n model = Expense\n fields = '__all__'\n\n\nclass MerchantSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = Merchant\n fields = '__all__'","sub_path":"rntapp/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":4743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"173651295","text":"import os\nimport argparse\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport random\nfrom matplotlib.patches import Rectangle\nfrom matplotlib.ticker import MultipleLocator\n\n\nparser = argparse.ArgumentParser(description='Argument parser')\nparser.add_argument(\"--solution_path\", help=\"Path where the output files are stored\", required = True, type=str)\nparser.add_argument(\"--file_name\", help=\"Name of the file\", required = True, type=str)\nargs = parser.parse_args()\n\ndef main():\n\t\n\t\t\n\tfile = open(args.solution_path + '/' + args.file_name,\"r\") \n\t\t\n\t# Read the first line which contains the width and the height of the paper roll\n\tfirst_line = file.readline().strip().split(\" \")\n\t\n\twidth = int(first_line[0])\n\theight = int(first_line[1])\n\n\t# Read the second line which contains the number of necessary pieces of paper to cut off\n\tsecond_line = file.readline().strip().split(\" \")\n\t\n\tnumber_of_pieces = int(second_line[0])\n\t\n\t# Read all the remaining lines which contains the horizontal and vertical dimensionof the i-th piece of paper\n\tremaining_lines = file.readlines()\n\t# To remove empty lines\n\tremaining_lines = [line.strip() for line in remaining_lines if line.strip()]\n\t\n\tpieces = []\n\t\n\tfor i,line in enumerate(remaining_lines):\n\t\tline = line.split()\n\t\tpieces.append([int(line[0]),int(line[1]),int(line[2]),int(line[3])])\n\n\t\t\n\tfig = plt.figure(figsize=(5 + (width//8) ,5 + (height//8)))\n\tax = fig.gca(title = \"Plot of the solution\")\n\tfor i in range(number_of_pieces):\n\t\tcolor = [\"#\"+''.join([random.choice('0123456789ABCDEF') for j in range(6)])]\n\t\tsq = Rectangle((pieces[i][2],pieces[i][3]),pieces[i][0],pieces[i][1],fill = True,color=color[0], alpha=.3 )\n\t\tax.add_patch(sq)\n\tplt.plot()\n\tplt.show()\n\t\t\n\t\n\tfile.close() \n\t\t\nif __name__ == \"__main__\":\n\tmain()","sub_path":"SMT/src/solution_grid.py","file_name":"solution_grid.py","file_ext":"py","file_size_in_byte":1765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"218781597","text":"import requests\nimport bs4\n\nENTRY_URL = \"http://oa.intranet.htisec.net/names.nsf?Login\"\nMAIN_URL = \"http://oa.intranet.htisec.net/htisec/crdd.nsf/0/B061277A869828E0482580C000171342?opendocument\"\nID_FILE = \"id.txt\"\n\ndef files_lookup(tgt_dir, pattern, recur_list=False, sub_folder=False, most_recent=True):\n filepath_arr = []\n\n for fi in os.listdir(tgt_dir):\n full_path = os.path.join(tgt_dir, fi)\n if sub_folder and os.path.isdir(full_path):\n filepath_arr += files_lookup(full_path, pattern, recur_list, sub_folder, most_recent)\n if fnmatch.fnmatch(fi, pattern):\n filepath_arr.append(full_path)\n\n filepath_arr.sort(reverse=most_recent)\n if recur_list:\n return filepath_arr\n else:\n return filepath_arr[0]\n\ndef html_content():\n with open(ID_FILE, 'rU') as f: \n username = f.readline().strip()\n password = f.readline().strip()\n\n session = requests.Session()\n res = session.post(ENTRY_URL, { \"Username\":username, \"Password\":password})\n res = session.get(MAIN_URL)\n return res.text\n\ndef find_diff(html):\n \n return\n\ndef main():\n html = html_content()\n with open(\"list.html\", 'wb') as f:\n f.write(html.encode('utf8'))\n find_diff(html)\n\n\n return\n\nif __name__ == \"__main__\":\n print (\"Loading director list\")\n\n try:\n main()\n except KeyboardInterrupt:\n print (\"Ctrl+C pressed. Stopping...\")","sub_path":"director_list/director_list.py","file_name":"director_list.py","file_ext":"py","file_size_in_byte":1427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"368256848","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport collections\nfrom karbor.common import constants\nfrom karbor.context import RequestContext\nfrom karbor.resource import Resource\nfrom karbor.services.protection.bank_plugin import Bank\nfrom karbor.services.protection.bank_plugin import BankPlugin\nfrom karbor.services.protection.bank_plugin import BankSection\nfrom karbor.services.protection import client_factory\nfrom karbor.services.protection.protection_plugins. \\\n image.image_protection_plugin import GlanceProtectionPlugin\nfrom karbor.services.protection.protection_plugins.image \\\n import image_plugin_schemas\nfrom karbor.tests import base\nimport mock\nfrom oslo_config import cfg\nfrom oslo_config import fixture\n\n\nclass FakeBankPlugin(BankPlugin):\n def update_object(self, key, value):\n return\n\n def get_object(self, key):\n return\n\n def list_objects(self, prefix=None, limit=None, marker=None,\n sort_dir=None):\n return\n\n def delete_object(self, key):\n return\n\n def get_owner_id(self):\n return\n\n\nfake_bank = Bank(FakeBankPlugin())\nfake_bank_section = BankSection(bank=fake_bank, section=\"fake\")\n\nResourceNode = collections.namedtuple(\n \"ResourceNode\",\n [\"value\",\n \"child_nodes\"]\n)\n\n\nImage = collections.namedtuple(\n \"Image\",\n [\"disk_format\",\n \"container_format\",\n \"status\"]\n)\n\n\ndef call_hooks(operation, checkpoint, resource, context, parameters, **kwargs):\n def noop(*args, **kwargs):\n pass\n\n hooks = (\n 'on_prepare_begin',\n 'on_prepare_finish',\n 'on_main',\n 'on_complete',\n )\n for hook_name in hooks:\n hook = getattr(operation, hook_name, noop)\n hook(checkpoint, resource, context, parameters, **kwargs)\n\n\nclass CheckpointCollection(object):\n def __init__(self):\n super(CheckpointCollection, self).__init__()\n self.bank_section = fake_bank_section\n\n def get_resource_bank_section(self, resource_id):\n return self.bank_section\n\n\nclass GlanceProtectionPluginTest(base.TestCase):\n def setUp(self):\n super(GlanceProtectionPluginTest, self).setUp()\n\n plugin_config = cfg.ConfigOpts()\n plugin_config_fixture = self.useFixture(fixture.Config(plugin_config))\n plugin_config_fixture.load_raw_values(\n group='image_backup_plugin',\n poll_interval=0,\n )\n plugin_config_fixture.load_raw_values(\n group='image_backup_plugin',\n backup_image_object_size=65536,\n )\n self.plugin = GlanceProtectionPlugin(plugin_config)\n cfg.CONF.set_default('glance_endpoint',\n 'http://127.0.0.1:9292',\n 'glance_client')\n\n self.cntxt = RequestContext(user_id='demo',\n project_id='abcd',\n auth_token='efgh')\n self.glance_client = client_factory.ClientFactory.create_client(\n \"glance\", self.cntxt)\n self.checkpoint = CheckpointCollection()\n\n def test_get_options_schema(self):\n options_schema = self.plugin.get_options_schema(\n constants.IMAGE_RESOURCE_TYPE)\n self.assertEqual(options_schema, image_plugin_schemas.OPTIONS_SCHEMA)\n\n def test_get_restore_schema(self):\n options_schema = self.plugin.get_restore_schema(\n constants.IMAGE_RESOURCE_TYPE)\n self.assertEqual(options_schema, image_plugin_schemas.RESTORE_SCHEMA)\n\n def test_get_saved_info_schema(self):\n options_schema = self.plugin.get_saved_info_schema(\n constants.IMAGE_RESOURCE_TYPE)\n self.assertEqual(options_schema,\n image_plugin_schemas.SAVED_INFO_SCHEMA)\n\n @mock.patch('karbor.services.protection.protection_plugins.image.'\n 'image_protection_plugin.utils.status_poll')\n @mock.patch('karbor.services.protection.clients.glance.create')\n def test_create_backup(self, mock_glance_create, mock_status_poll):\n resource = Resource(id=\"123\",\n type=constants.IMAGE_RESOURCE_TYPE,\n name='fake')\n\n fake_bank_section.update_object = mock.MagicMock()\n\n protect_operation = self.plugin.get_protect_operation(resource)\n mock_glance_create.return_value = self.glance_client\n\n self.glance_client.images.get = mock.MagicMock()\n self.glance_client.images.return_value = Image(\n disk_format=\"\",\n container_format=\"\",\n status=\"active\"\n )\n\n fake_bank_section.update_object = mock.MagicMock()\n self.glance_client.images.data = mock.MagicMock()\n self.glance_client.images.data.return_value = []\n mock_status_poll.return_value = True\n call_hooks(protect_operation, self.checkpoint, resource, self.cntxt,\n {})\n\n def test_delete_backup(self):\n resource = Resource(id=\"123\",\n type=constants.IMAGE_RESOURCE_TYPE,\n name='fake')\n\n fake_bank_section.list_objects = mock.MagicMock()\n fake_bank_section.list_objects.return_value = [\"data_1\", \"data_2\"]\n fake_bank_section.delete_object = mock.MagicMock()\n delete_operation = self.plugin.get_delete_operation(resource)\n call_hooks(delete_operation, self.checkpoint, resource, self.cntxt,\n {})\n\n def test_get_supported_resources_types(self):\n types = self.plugin.get_supported_resources_types()\n self.assertEqual([constants.IMAGE_RESOURCE_TYPE], types)\n","sub_path":"karbor/tests/unit/protection/test_glance_protection_plugin.py","file_name":"test_glance_protection_plugin.py","file_ext":"py","file_size_in_byte":6139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"174206905","text":"# Programa para carga de datos en BBDD SQLite\n\nimport sqlite3\nfrom tkinter import *\nfrom tkinter import messagebox\nfrom tkinter import ttk\nfrom reportlab.lib.pagesizes import A4\nfrom reportlab.pdfgen import canvas\nfrom reportlab.lib import colors\n\nfrom Clases import Productos,Senasa\n\ncolor=\"#f2d05e\"\n\n\n# - - - - - - - funciones - - - - - - - - \n\ndef grabarProd(cod1,cod2,nom,peso,vol):\n # Si ya existe registro, actualizar\n # caso contratio, ingresar\n\n # - - - Control Datos -----\n f=True\n if cod1==\"\" or len(cod1)!=10:\n if len(cod1)!=10:\n messagebox.showerror(\"ERROR\", \"Cantidad del <<>>\\n deben ser 10 caracteres\")\n return\n f=False\n \n if len(cod2)>6:\n cod2=cod2[0:6]\n codigoBaseEntry.set(cod2)\n\n if cod2==\"\" or len(cod2)!=6:\n if len(cod2)!=6:\n messagebox.showerror(\"ERROR\", \"Cantidad del <<>>\\n deben ser 6 caracteres\")\n return\n f=False\n \n if nom==\"\":\n f=False\n \n if peso==\"\":\n f=False\n \n if vol==\"\":\n f=False\n\n if(f==False):\n messagebox.showwarning(\"ERROR\", \"Faltó completar campos...\")\n return\n \n dato_p=Productos.Productos()\n dato_p.setear_producto(cod1,cod2,nom,peso,vol)\n if dato_p.existe_producto():\n # Actualizar\n dato_p.actualizar_producto()\n else:\n # Ingresar\n dato_p.guardar_producto()\n\n \n limpiaDatos()\n\ndef limpiaDatos() :\n codigo1.set(\"\")\n codigoBaseEntry.set(\"\")\n #codigo2.set(\"\")\n nombre.set(\"\")\n peso.set(\"\")\n volumen.set(\"\")\n codigoProdEntry.focus()\n \ndef buscarProducto():\n global hija\n prod=Productos.Productos()\n lista_productos=prod.leer_lista()\n\n hija=Toplevel()\n hija.title(\"Busca Producto\")\n hija.iconbitmap(\"images/logo.ico\")\n hija.resizable(0,0)\n\n frame2=Frame(hija)\n frame2.config(bg=color, width=\"650\", height=\"350\")\n frame2.pack(fill=\"both\", expand=\"False\")\n \n listaProdEntry=ttk.Combobox(frame2,values=lista_productos,width=40,state=\"readonly\")\n listaProdEntry.grid(row=1,column=1,sticky=\"w\",padx=5, pady=5)\n listaProdEntry.config(font=\"Arial 10\")\n\n \n eligeItemBtn=Button(frame2,text=\"Elige Producto\", command=lambda:muestraProducto(listaProdEntry.get()))\n eligeItemBtn.grid(row=2,column=1,ipady=5)\n eligeItemBtn.config(width=\"20\")\n\ndef muestraProducto(prod):\n global hija\n # Busca Producto y formatea\n cod=prod[0:10]\n p=Productos.Productos()\n p.busca_producto(cod)\n codigo1.set(p.cod_producto)\n codigoBaseEntry.set(p.cod_producto_base)\n nombre.set(p.nombre_producto)\n peso.set(p.peso_producto)\n volumen.set(p.volumen_producto)\n hija.destroy()\n\n\n\n# - - - - - - - - - - Prog. Principal - - - - - - - \n\n\nraiz=Tk()\nraiz.title(\"Carga y Búsqueda de Productos\")\nraiz.iconbitmap(\"images/logo.ico\")\nraiz.resizable(0,0)\n\nframe=Frame(raiz)\nframe.config(bg=color, width=\"650\", height=\"350\")\nframe.pack(fill=\"both\", expand=\"False\")\n\ncodigo1 = StringVar()\n#codigo2 = StringVar()\nnombre = StringVar()\npeso = StringVar()\nvolumen = StringVar()\n\n \n# - - - - - Labels - - - - - -\ncodigoProdLbl=Label(frame,text=\"Código Producto: \")\ncodigoProdLbl.config(bg=color)\ncodigoProdLbl.grid(row=0,column=0,sticky=\"e\",padx=5, pady=5)\n\n\ncodigoBaseLbl=Label(frame,text=\"Código Base: \")\ncodigoBaseLbl.config(bg=color)\ncodigoBaseLbl.grid(row=1,column=0,sticky=\"e\",padx=5, pady=5)\n\nnombreComercialLbl=Label(frame,text=\"Nombre del Producto: \")\nnombreComercialLbl.config(bg=color)\nnombreComercialLbl.grid(row=2,column=0,sticky=\"e\",padx=5, pady=5)\n\npesoProdLbl=Label(frame,text=\"Peso del Producto: \")\npesoProdLbl.config(bg=color)\npesoProdLbl.grid(row=3,column=0,sticky=\"e\",padx=5, pady=5)\n\nvolumenProdLbl=Label(frame,text=\"Volumen del Producto: \")\nvolumenProdLbl.config(bg=color)\nvolumenProdLbl.grid(row=4,column=0,sticky=\"e\",padx=5, pady=5)\n\n# - - - - - Entrys - - - - - - \ncodigoProdEntry=Entry(frame,textvariable=codigo1,width=10)\ncodigoProdEntry.grid(row=0,column=1,sticky=\"w\",padx=5, pady=5,ipady=5)\ncodigoProdEntry.config(font=\"Arial 15\")\n\n\nlista=[]\nlista_senasa=Senasa.Senasa()\nlista=lista_senasa.leer_lista(lista)\ncodigoBaseEntry=ttk.Combobox(frame,values=lista,width=40)\ncodigoBaseEntry.grid(row=1,column=1,sticky=\"w\",padx=5, pady=5)\ncodigoBaseEntry.config(font=\"Arial 10\")\n\nnombreComercialEntry=Entry(frame,textvariable=nombre,width=30)\nnombreComercialEntry.grid(row=2,column=1,sticky=\"w\",padx=5, pady=5)\nnombreComercialEntry.config(font=\"Arial 15\")\n\npesoProdEntry=Entry(frame,textvariable=peso)\npesoProdEntry.grid(row=3,column=1,sticky=\"w\",padx=5, pady=5,)\npesoProdEntry.config(font=\"Arial 15\",width=\"10\")\n\nbuscarBtn=Button(frame,text=\"Buscar\", command=lambda:buscarProducto())\nbuscarBtn.grid(row=3,column=1,sticky=\"e\",ipady=5, pady=5, padx=15)\nbuscarBtn.config(width=\"10\")\n\nvolumenProdEntry=Entry(frame,textvariable=volumen)\nvolumenProdEntry.grid(row=4,column=1,sticky=\"w\",padx=5, pady=5)\nvolumenProdEntry.config(font=\"Arial 15\",width=\"10\")\n\n\nguardarBtn=Button(frame,text=\"Guardar\", command=lambda:grabarProd(codigo1.get(),codigoBaseEntry.get(),nombre.get(),peso.get(),volumen.get()))\nguardarBtn.grid(row=5,column=0,columnspan=2,ipady=5)\nguardarBtn.config(width=\"60\")\n\nlimpiarBtn=Button(frame,text=\"Limpiar\", command=lambda:limpiaDatos())\nlimpiarBtn.grid(row=6,column=0,columnspan=2,ipady=5)\nlimpiarBtn.config(width=\"60\")\n\n\nsalirBtn=Button(frame,text=\"Salir\",command=raiz.destroy)\nsalirBtn.grid(row=7,column=0,columnspan=2,ipady=5)\nsalirBtn.config(width=\"60\")\n\ncodigoProdEntry.focus()\n \nraiz.mainloop()\n","sub_path":"view_productos.py","file_name":"view_productos.py","file_ext":"py","file_size_in_byte":5588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"342581620","text":"import unicodedata\nimport random\nimport time\nimport math\n\nfrom text_generation.config import ALL_LETTERS, N_LETTERS, SAMPLE_LENGTH\nimport torch\nfrom torch.autograd import Variable\n\n\ndef unicode_to_ascii(s):\n return ''.join(\n c for c in unicodedata.normalize('NFD', s)\n if unicodedata.category(c) != 'Mn'\n and c in ALL_LETTERS\n )\n\n\ndef read_lines(filename):\n program = open(filename).read().split('--------')\n while '' in program:\n program.remove('')\n return [unicode_to_ascii(line) for line in program]\n\n\ndef read_prose_lines(filename):\n text = open(filename).read().split('.')\n only_long = filter(lambda line: len(line) > 10, text)\n stripped = [line.strip() for line in only_long]\n return [unicode_to_ascii(line) for line in stripped]\n\n\ndef random_choice(l):\n return l[random.randint(0, len(l) - 1)]\n\n\ndef create_input_tensor(line):\n length = SAMPLE_LENGTH if len(line) > SAMPLE_LENGTH else len(line)\n tensor = torch.zeros(length, 1, N_LETTERS)\n for li in range(length):\n letter = line[li]\n tensor[li][0][ALL_LETTERS.find(letter)] = 1\n return tensor\n\n\ndef create_target_tensor(line):\n length = SAMPLE_LENGTH if len(line) > SAMPLE_LENGTH else len(line)\n letter_indexes = [ALL_LETTERS.find(line[li]) for li in range(1,\n length)]\n letter_indexes.append(N_LETTERS - 1)\n return torch.LongTensor(letter_indexes)\n\n\ndef random_training_set(line, sample_length=500, volatile=False):\n length = sample_length if len(line) > sample_length else len(line)\n if length > sample_length:\n random_idx = torch.randint(0, length - sample_length - 1)\n line = line[random_idx : random_idx + sample_length + 1]\n input_line_tensor = Variable(create_input_tensor(line), volatile=volatile)\n target_line_tensor = Variable(create_target_tensor(line), volatile=volatile)\n\n return input_line_tensor, target_line_tensor","sub_path":"text_generation/utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"406137094","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth.decorators import login_required\nfrom buddysapp.forms import UserForm, DispensaryForm\nfrom django.contrib.auth import authenticate, login\nfrom django.contrib.auth.models import User\n\n# Create your views here.\ndef home(request):\n return redirect(dispensary_home)\n\n@login_required(login_url='/dispensary/sign-in/')\ndef dispensary_home(request):\n return render(request, 'dispensary/home.html', {})\n\ndef dispensary_sign_up(request):\n user_form = UserForm()\n dispensary_form = DispensaryForm()\n\n if request.method == \"POST\":\n user_form = UserForm(request.POST)\n dispensary_form = DispensaryForm(request.POST, request.FILES)\n\n if user_form.is_valid() and dispensary_form.is_valid():\n new_user = User.objects.create_user(**user_form.cleaned_data)\n new_dispensary = dispensary_form.save(commit=False)\n new_dispensary.user = new_user\n new_dispensary.save()\n\n login(request, authenticate(\n username = user_form.cleaned_data[\"username\"],\n password = user_form.cleaned_data[\"password\"]\n ))\n\n return redirect(dispensary_home)\n\n return render(request, 'dispensary/signup.html', {\n \"user_form\": user_form,\n \"dispensary_form\": dispensary_form\n })\n","sub_path":"buddysapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"606151011","text":"#USED TO PLOT EXCITATIONS \n#N AND DOUBLE OCCUPATIONS\n\nimport numpy as np \nimport matplotlib.pyplot as plt\nimport pickle \nimport pandas as pd \nimport seaborn as sns\nimport statsmodels.formula.api as sm\nfrom sklearn.metrics import r2_score\nsns.set(style=\"ticks\")\n\nwith open(\"gendata.pickle\", 'rb') as handle:\n data = pickle.load(handle)\n\n#Energies\ne=np.array(data['energy'])\ne-=e[0]\ne*=27.2114\n\n#Array of occupations \nncu=10\nno=4\nnsr=1\n\n#cu nn\ncunns=[\n[3,4,1,6],\n[0,5,7,2],\n[1,6,4,3],\n[0,7,5,2],\n[0,2,5,7],\n[1,6,3,4],\n[2,5,0,7],\n[1,6,3,4]\n]\n\n\n\nn=[]\ni=0\nfor rdms in data['1rdm']:\n tmp=[]\n for s in range(2):\n #Copper part \n cu=np.diag(rdms[s])[:8*ncu]\n cu=np.split(cu,8)\n cu=np.sum(cu,axis=0)\n \n #Oxygen part\n to=np.diag(rdms[s])[8*ncu:8*ncu+16*no]\n to=np.split(to,16)\n o=np.zeros(6)\n o[:4]=np.sum(to,axis=0)\n for i in range(16):\n if(i<8): \n o[4]+=to[i][1] #sigma\n o[5]+=to[i][2] #pi\n else:\n o[4]+=to[i][2] #sigma\n o[5]+=to[i][1] #pi\n #Sr part\n sr=np.diag(rdms[s])[8*ncu+16*no:8*ncu+16*no+8*nsr]\n sr=np.split(sr,8)\n sr=np.sum(sr,axis=0)\n \n tmp.append(np.concatenate((cu,o,sr),axis=None))\n\n #Cu nn\n cunn=0\n tcu=np.diag(rdms[0])[:8*ncu]+np.diag(rdms[1])[:8*ncu]\n tcu=np.split(tcu,8)\n for i in range(8):\n for j in cunns[i]:\n cunn+=np.abs(tcu[i][9]-tcu[j][9])\n cunn/=(8.*4.)\n\n ret=np.array(tmp[0])+np.array(tmp[1])\n ret=ret.tolist()\n ret.append(cunn)\n print(ret[-1])\n n.append(np.array(ret))\nn=np.array(n)\n\n#Array of double occupations \nncu=10\nno=4\nnsr=1\n\nu=[]\ni=0\nfor nund in data['2rdm']:\n #Copper part \n cu=nund[:8*ncu]\n cu=np.split(cu,8)\n cu=np.sum(cu,axis=0)\n\n #Oxygen part\n o=nund[8*ncu:8*ncu+16*no]\n o=np.split(o,16) #Split amongst the 16 atoms\n o=np.sum(o,axis=0)\n\n #Sr part\n sr=nund[8*ncu+16*no:8*ncu+16*no+8*nsr]\n sr=np.split(sr,8)\n sr=np.sum(sr,axis=0)\n \n u.append(np.concatenate((cu,o,sr),axis=None))\n\nu=np.array(u)\n\n#Hopping calculations \nch=[] #Hybridized hopping (Cu d and sigma, no curl)\ncc=[] #Curly hopping\ncxy=[] #x hopping\nnnh=[[0,6,8,11],\n[1,7,8,9],\n[2,4,9,10],\n[3,5,10,11],\n[0,4,12,15],\n[1,5,12,13],\n[2,6,13,14],\n[3,7,14,15]] #Nearest neighbors oxygens for a given copper\nsignh=[[-1,1,1,-1],\n[-1,1,-1,1],\n[-1,1,-1,1],\n[-1,1,-1,1],\n[1,-1,1,-1],\n[1,-1,-1,1],\n[1,-1,-1,1],\n[1,-1,-1,1]] #Hopping signs for neighbor oxygens\n\nnnhc=[[15,12,8,11],\n[12,13,9,8],\n[13,14,10,9],\n[14,15,11,10],\n[9,10,12,15],\n[10,11,13,12],\n[11,8,14,13],\n[8,9,15,14],\n[0,1,7,6],\n[1,2,4,7],\n[2,3,5,4],\n[3,0,6,5],\n[4,5,1,0],\n[5,6,2,1],\n[6,7,3,2],\n[7,4,0,3]]\nsgn=[1,-1,1,-1]\n\nncu=10\nno=4\nnsr=1\n\nz=0\nfor rdms in data['1rdm']:\n chtmp=0\n cctmp=0\n cxytmp=0\n \n\n #SIGMA\n for j in range(8):\n cui=ncu*j+9\n p=0\n for k in nnh[j]:\n oi=np.nan\n if(k<8): oi=ncu*8+no*k+1 #px\n else: oi=ncu*8+no*k+2 #py\n chtmp+=signh[j][p]*(rdms[0][oi,cui]+rdms[0][cui,oi]+rdms[1][oi,cui]+rdms[1][cui,oi])\n #if(z==4): print(\"4: \",signh[j][p]*(rdms[0][oi,cui]+rdms[0][cui,oi]+rdms[1][oi,cui]+rdms[1][cui,oi]))\n #if(z==16): print(\"16: \",signh[j][p]*(rdms[0][oi,cui]+rdms[0][cui,oi]+rdms[1][oi,cui]+rdms[1][cui,oi]))\n p+=1\n \n #PI\n for x in range(16):\n oi1=0\n oi2=0\n if(x<8): \n oi1=ncu*8+no*x+2 #py\n for y in range(4): #NN\n oi2=(ncu*8+no*nnhc[x][y]+1) #px\n cctmp+=sgn[y]*(rdms[0][oi1,oi2]+rdms[0][oi2,oi1]+rdms[1][oi1,oi2]+rdms[1][oi2,oi1])\n #if(z==4): print(\"4: \",sgn[y]*(rdms[0][oi1,oi2]+rdms[0][oi2,oi1]+rdms[1][oi1,oi2]+rdms[1][oi2,oi1]))\n #if(z==16): print(\"16: \",sgn[y]*(rdms[0][oi1,oi2]+rdms[0][oi2,oi1]+rdms[1][oi1,oi2]+rdms[1][oi2,oi1]))\n else:\n oi1=ncu*8+no*x+1 #px\n for y in range(4): #NN\n oi2=(ncu*8+no*nnhc[x][y]+2) #py\n cctmp+=sgn[y]*(rdms[0][oi1,oi2]+rdms[0][oi2,oi1]+rdms[1][oi1,oi2]+rdms[1][oi2,oi1])\n #if(z==4): print(\"4: \",sgn[y]*(rdms[0][oi1,oi2]+rdms[0][oi2,oi1]+rdms[1][oi1,oi2]+rdms[1][oi2,oi1]))\n #if(z==16): print(\"16: \",sgn[y]*(rdms[0][oi1,oi2]+rdms[0][oi2,oi1]+rdms[1][oi1,oi2]+rdms[1][oi2,oi1]))\n #X\n for x in range(16):\n oi1=0\n oi2=0\n oi1=ncu*8+no*x+1 #px\n for y in range(4): #NN\n oi2=(ncu*8+no*nnhc[x][y]+1) #px\n cxytmp-=(rdms[0][oi1,oi2]+rdms[0][oi2,oi1]+rdms[1][oi1,oi2]+rdms[1][oi2,oi1])\n #if(z==4): print(\"4: \",-(rdms[0][oi1,oi2]+rdms[0][oi2,oi1]+rdms[1][oi1,oi2]+rdms[1][oi2,oi1]))\n #if(z==16): print(\"16: \",-(rdms[0][oi1,oi2]+rdms[0][oi2,oi1]+rdms[1][oi1,oi2]+rdms[1][oi2,oi1]))\n \n #Y\n for x in range(16):\n oi1=0\n oi2=0\n oi1=ncu*8+no*x+2 #px\n for y in range(4): #NN\n oi2=(ncu*8+no*nnhc[x][y]+2) #px\n cxytmp-=(rdms[0][oi1,oi2]+rdms[0][oi2,oi1]+rdms[1][oi1,oi2]+rdms[1][oi2,oi1])\n #if(z==4): print(\"4: \",-(rdms[0][oi1,oi2]+rdms[0][oi2,oi1]+rdms[1][oi1,oi2]+rdms[1][oi2,oi1]))\n #if(z==16): print(\"16: \",-(rdms[0][oi1,oi2]+rdms[0][oi2,oi1]+rdms[1][oi1,oi2]+rdms[1][oi2,oi1]))\n \n cxy.append(cxytmp)\n ch.append(chtmp)\n cc.append(cctmp)\n z+=1\n\nch=np.array(ch)\ncc=np.array(cc)\ncxy=np.array(cxy)\n\n#Total data frame\nhue=np.zeros(len(e))+4\nfor i in range(len(hue)):\n if(data['symm'][i]=='xy'): hue[i]=1\n elif(data['symm'][i]=='pi'): hue[i]=2\n elif(data['symm'][i]=='sig'): hue[i]=3\n else: pass\n\nn1=n[:,9]-n[:,14]\nn2=n1\nXtot=np.concatenate(((e)[:,np.newaxis],n,n1[:,np.newaxis],n2[:,np.newaxis],u,ch[:,np.newaxis],cc[:,np.newaxis],cxy[:,np.newaxis],hue[:,np.newaxis]),axis=1)\ncols=[\n\"E\",\n\"3s\",\"4s\",\"3px\",\"3py\",\"3pz\",'3dxy','3dyz','3dz2','3dxz','3dx2y2','cunn',\n'2s','2px','2py','2pz','2psig','2ppi','5s','n1','n2',\n\"3sU\",\"4sU\",\"3pxU\",\"3pyU\",\"3pzU\",'3dxyU','3dyzU','3dz2U','3dxzU','3dx2y2U',\n'2sU','2pxU','2pyU','2pzU','5sU',\n'ts','tp','txy','symm'\n]\n\n#plt.hist(n[:,-1])\n#plt.show()\n\ndftot=pd.DataFrame(data=Xtot,columns=cols)\n#Energy, all hoppings, all occupations, all U\n#sns.pairplot(dftot,vars=[\"E\",\"2psig\",\"2ppi\",\"3dx2y2\",\"3dx2y2U\",\"ts\",\"tp\",\"txy\"],hue='symm')\nsns.pairplot(dftot,vars=[\"E\",\"ts\",\"2psig\",\"2ppi\"],hue='symm')\nplt.show()\nexit(0)\n\nweights=np.ones(len(e))\nweights[e<2.0]=(len(e)/7)\nregdf=pd.DataFrame({\"E\":e,\"A\":ch,\"B\":cc,\"O\":cxy,\"C\":n[:,9],\"D\":n[:,14],\"F\":n[:,9]-n[:,14]-n[:,15],\"G\":u[:,9]})\nresult=sm.wls(formula=\"E~A+F\",data=regdf[hue==3],weights=weights[hue==3]).fit()\nprint(result.summary())\npred=result.predict(regdf)\n#plt.plot(pred[hue==4],e[hue==4],'mo')\nplt.plot(pred[hue==3],e[hue==3],'ro')\n'''\nplt.plot(pred[hue==2],e[hue==2],'go')\nplt.plot(pred[hue==1],e[hue==1],'bo')\n'''\nplt.plot(e,e,'k-')\nplt.show()\nexit(0)\n\nXtot=np.concatenate((e[:,np.newaxis],n,u,ch[:,np.newaxis],cc[:,np.newaxis],cxy[:,np.newaxis],(e-pred)[:,np.newaxis],hue[:,np.newaxis]),axis=1)\ncols=[\n\"E\",\n\"3s\",\"4s\",\"3px\",\"3py\",\"3pz\",'3dxy','3dyz','3dz2','3dxz','3dx2y2',\n'2s','2px','2py','2pz','2psig','2ppi','5s',\n\"3sU\",\"4sU\",\"3pxU\",\"3pyU\",\"3pzU\",'3dxyU','3dyzU','3dz2U','3dxzU','3dx2y2U',\n'2sU','2pxU','2pyU','2pzU','5sU',\n'ts','tp','txy','res1','symm'\n]\ndftot=pd.DataFrame(data=Xtot,columns=cols)\nsns.pairplot(dftot,vars=[\"res1\",\"ts\",\"2ppi\"],hue='symm')\nplt.show()\n","sub_path":"undoped/PBE0_8/fit_data/analyzedata.py","file_name":"analyzedata.py","file_ext":"py","file_size_in_byte":6980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"184544925","text":"import sys\nfrom collections import Counter, OrderedDict\n\ndata = sys.stdin.read().replace(\" \", \"\")\n\nprint(\"### 10 most frequent letters ###\")\nprint(str(Counter(data).most_common(10)) + \"\\n\")\n\n\nprint(\"### 10 most frequent bi-patterns ###\")\nbi_pattern_list = []\nfor i in range(len(data) - 2):\n bi_pattern_list.append(data[i] + data[i+1])\n\nprint(str(Counter(bi_pattern_list).most_common(10)) + \"\\n\")\n\n\nprint(\"### 10 most frequent tri-patterns ###\")\ntri_pattern_list = []\nfor i in range(len(data) - 3):\n tri_pattern_list.append(data[i] + data[i+1] + data[i+2])\n\nprint(str(Counter(tri_pattern_list).most_common(10)) + \"\\n\")\n\nprint(\"### 10 most frequent quad-patterns ###\")\nquad_pattern_list = []\nfor i in range(len(data) - 4):\n quad_pattern_list.append(data[i] + data[i+1] + data[i+2] + data[i+3])\n\nprint(str(Counter(quad_pattern_list).most_common(10)) + \"\\n\")\n\nprint(\"### most frequent doubles ###\")\ndo_pattern_list = []\nfor i in range(len(data) - 2):\n if(data[i] == data[i+1]):\n do_pattern_list.append(data[i] + data[i+1])\n\nprint(str(Counter(do_pattern_list).most_common()) + \"\\n\")\n","sub_path":"overthewire/krypton/freq_analyser.py","file_name":"freq_analyser.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"457867260","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is\n# regenerated.\n# --------------------------------------------------------------------------\n\nfrom msrest.serialization import Model\n\n\nclass Usage(Model):\n \"\"\"The usage data for a usage request.\n\n Variables are only populated by the server, and will be ignored when\n sending a request.\n\n :param unit: The unit of the metric. Possible values include: 'Count',\n 'Bytes', 'Seconds', 'Percent', 'CountPerSecond', 'BytesPerSecond',\n 'Milliseconds'\n :type unit: str or ~azure.mgmt.cosmosdb.models.UnitType\n :ivar name: The name information for the metric.\n :vartype name: ~azure.mgmt.cosmosdb.models.MetricName\n :ivar quota_period: The quota period used to summarize the usage values.\n :vartype quota_period: str\n :ivar limit: Maximum value for this metric\n :vartype limit: long\n :ivar current_value: Current value for this metric\n :vartype current_value: long\n \"\"\"\n\n _validation = {\n 'name': {'readonly': True},\n 'quota_period': {'readonly': True},\n 'limit': {'readonly': True},\n 'current_value': {'readonly': True},\n }\n\n _attribute_map = {\n 'unit': {'key': 'unit', 'type': 'str'},\n 'name': {'key': 'name', 'type': 'MetricName'},\n 'quota_period': {'key': 'quotaPeriod', 'type': 'str'},\n 'limit': {'key': 'limit', 'type': 'long'},\n 'current_value': {'key': 'currentValue', 'type': 'long'},\n }\n\n def __init__(self, *, unit=None, **kwargs) -> None:\n super(Usage, self).__init__(**kwargs)\n self.unit = unit\n self.name = None\n self.quota_period = None\n self.limit = None\n self.current_value = None\n","sub_path":"src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/models/usage_py3.py","file_name":"usage_py3.py","file_ext":"py","file_size_in_byte":2038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"630325816","text":"# -*- coding: utf-8 -*-\n\"\"\"\n\n=================================\nAuthor: yangli\nCreated on: 2020/3/14\n\nE-mail:1179384105@qq.com\n\n=================================\n\n\n\"\"\"\n\nimport requests\nfrom requests.sessions import Session\nimport logging\nfrom common import logger\n\n\nclass HTTPRequest(object):\n\n def __init__(self):\n # 创建session对象\n self.session = Session()\n\n # 记录cookies信息,给下一次请求使用\n def request(self, method, url, params=None, data=None, headers=None, cookies=None, json=None):\n # 将方法名转化为小写\n method = method.lower()\n if method == \"post\":\n # 判断是否使用json来传参,适用于接口项目使用json传参\n if json:\n logging.info(\"正在发送请求,请求地址:{},请求参数:{}\".format(url, json))\n response = self.session.post(url=url, json=json, headers=headers, cookies=cookies)\n return response\n else:\n logging.info(\"正在发送请求,请求地址:{},请求参数:{}\".format(url, data))\n response = self.session.post(url=url, data=data, headers=headers, cookies=cookies)\n return response\n elif method == \"get\":\n logging.info(\"正在发送请求,请求地址:{},请求参数:{}\".format(url, params))\n response = self.session.get(url=url, params=params, headers=headers, cookies=cookies)\n return response\n elif method == \"put\":\n logging.info(\"正在发送请求,请求地址:{},请求参数:{}\".format(url, data))\n response = self.session.put(url=url, data=data, headers=headers, cookies=cookies)\n return response\n\n def close(self):\n self.session.close()\n\n\nclass HTTPRequest1(object):\n # 不记录cookies信息\n def request(self, method, url, params=None, data=None, headers=None, cookies=None, json=None):\n method = method.lower()\n if method == \"post\":\n if json:\n logging.info(\"正在发送请求,请求地址:{},请求参数:{}\".format(url, json))\n response = requests.post(url=url, json=json, headers=headers, cookies=cookies)\n return response\n else:\n logging.info(\"正在发送请求,请求地址:{},请求参数:{}\".format(url, data))\n response = requests.post(url=url, data=data, headers=headers, cookies=cookies)\n return response\n\n elif method == \"get\":\n logging.info(\"正在发送请求,请求地址:{},请求参数:{}\".format(url, params))\n response = requests.get(url=url, params=params, headers=headers, cookies=cookies)\n return response\n elif method == \"put\":\n if json:\n logging.info(\"正在发送请求,请求地址:{},请求参数:{}\".format(url, json))\n response = requests.put(url=url, json=json, headers=headers, cookies=cookies)\n return response\n logging.info(\"正在发送请求,请求地址:{},请求参数:{}\".format(url, data))\n response = requests.put(url=url, data=data, headers=headers, cookies=cookies)\n return response\n\n\nif __name__ == '__main__':\n r = HTTPRequest1()\n # url = \"http://118.24.221.133:8081/futureloan/mvc/api/member/login\"\n # method = \"post\"\n # data = {'mobilephone': '13342884220', 'pwd': '123456'}\n # response = r.request(method=method, url=url, data=data)\n # print(response.status_code)\n # print(response.json())\n # url = \"https://fsc-test.manshang.com/api/seller-setting/21\"\n # headers = {\n # \"Authorization\": \"Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvZnNjLXRlc3QubWFuc2hhbmcuY29tXC9hcGlcL2F1dGhcL3JlZnJlc2giLCJpYXQiOjE1ODU0NjAyMjIsImV4cCI6MTU4NTc1MjExOSwibmJmIjoxNTg1NzQ4NTE5LCJqdGkiOiJIM0twZ0NlVmF1YWxPNDNEIiwic3ViIjo3NywicHJ2IjoiODY4MDg3YjE4M2IzN2E2OTQ5NDgwMGNhMDE2MjI0Y2FiNWNhNGJjMyJ9.6M34u7KSFDkTplJ8Ky7oBy2z0ciF0mIjOvLaw7rPAAA\",\n # \"Content-Type\": \"application/json;charset=UTF-8\",\n # \"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36\",\n # \"Referer\": \"https://fsc-test.manshang.com/app/invoice/ApplyDetail/Apply\",\n # \"Origin\": \"https://fsc-test.manshang.com\",\n # \"Accept-Encoding\": \"gzip, deflate, br\"}\n # data = {'name': '客户022落落零零落落零零落落啦啦啦', \"id\": 21, \"customer_id\": 34, \"company_id\": 22, \"duty_paragraph\": \"222\", \"address\": \"地址222\",\n # \"phone\": \"15733100728\",\n # \"bank_name\": \"222\", \"card_no\": \"222\", \"payee\": \"222\", \"reviewer\": \"222\", \"drawer\": \"222\"}\n # response = requests.put(url=url, data=data, headers=headers)\n # print(response.json())\n\n # url = \"https://api.b.mydaydream.com/passport/passportv2/mobilePhoneLogin\"\n #\n # data = {\"code\":\"123456\",\"mobilePhone\":\"15733100728\",\"nationCode\":\"86\"}\n #\n # response = requests.post(url=url, json=data)\n # print(response.json())\n\n\n # url = \"https://api.b.mydaydream.com/dreamAppV3/user/getFollowList?page=1&size=10\"\n # headers = {\"x-access-token\": \"987dYZLtreDcOpQ8EpyZ+QyQe5YfBGwBkTrZwVLnLVcaMnZhvYz46bIuRZoqo5iMt5rQfoo4rdyPm8SOE3cSTNowV3T8la6sj5Ppgzs1iMNQOQugbJNIB8y9bOgBlBZEicl6yVrpoQ8E2LcKmLPrBlOsrzOjm/26tE1ecscvnuYJE+XRofvjMks7ak+q2C2Z5MwE2lecrU9a21b2Px8Vuts2ZwBClumepY3plyl4OUU4n1RdduGf3Ky3UI0\"}\n # response = requests.get(url=url, headers=headers)\n # print(response.json())\n\n url = \"https://api.b.mydaydream.com/dreamAppV3/user/follow\"\n headers = {\"x-access-token\": \"3395Gkk7x0YC/z9dBrc84qdn23jjASpfCLuW4bMSmaE+4frbx0OO6c61mzBw1BWs7+8F/s4ng13DBOal9FAe4s4V3Ox71nBLAg894539LCVEQU/uAYE4imosFi3DElWihGUWt0hyABQh39ypBKk8ah+i7s7gAvDTE61e6R3JZvOVr2+eukdJlnPNoL+m2Vl9xmoNSR7WbhcZRF7V30VzLq0toEqGtfB1HYWLMZRUzu+U+D7oN8JAwZUmPOc\"}\n data = {\"followUid\":\"18799\"}\n response = requests.post(url=url, json=data, headers=headers)\n print(response.json())\n\n","sub_path":"common/http_request.py","file_name":"http_request.py","file_ext":"py","file_size_in_byte":6102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"531040780","text":"#codeing=utf-8\n#python获取本机名称与IP地址\n\n#windows下获取函数\ndef gethostname_win():\n import socket\n #获取本机电脑名\n myname = socket.getfqdn(socket.gethostname( ))\n #获取本机ip\n myaddr = socket.gethostbyname(myname)\n print (myname)\n print (myaddr)\n#调用\ngethostname_win()\n'''\n#Linux下获取Ip函数\ndef gethostip_linux():\n import socket\n import fcntl\n import struct\n\n def get_ip_address(ifname):\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n return socket.inet_ntoa(fcntl.ioctl(\n s.fileno(),\n 0x8915, # SIOCGIFADDR\n struct.pack('256s', ifname[:15])\n )[20:24])\n'''\n\ndef f_ping():\n import os\n print(os.system(\"ping www.baidu.com\"))\n\nf_ping()","sub_path":"p_GetHostName.py","file_name":"p_GetHostName.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"511258695","text":"from nornir.plugins.tasks import networking\n\n\ndef test_netconf_capabilities(netconf):\n netconf = netconf.filter(name=\"netconf1.no_group\")\n assert netconf.inventory.hosts\n\n result = netconf.run(networking.netconf_capabilities)\n\n for _, v in result.items():\n assert \"urn:ietf:params:netconf:capability:writable-running:1.0\" in v.result\n","sub_path":"tests/plugins/tasks/networking/test_netconf_capabilities.py","file_name":"test_netconf_capabilities.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"398441494","text":"from django.shortcuts import render, get_object_or_404, get_list_or_404, redirect, render_to_response\nfrom django.http import HttpResponse, Http404, HttpResponseRedirect\nfrom django.utils import timezone\nfrom django.views.generic import ListView, DetailView\n\n\nfrom django.contrib.auth.models import User, Group\nfrom module_content.models import Module, Lecture\nfrom student.models import Student, AssignmentSubmit\nfrom todo.models import List, Item\nfrom usermodule.models import UserModule\n\nclass ModuleProgressView(ListView):\n template_name = 'module_progress/module_progress.html'\n context_object_name = 'student'\n\n\n def get_context_data(self, **kwargs):\n context = super(ModuleProgressView, self).get_context_data(**kwargs)\n self.module = get_object_or_404(Module, code=self.kwargs['code'])\n current_user = get_object_or_404(User, email=self.request.user.email)\n file_submit = AssignmentSubmit.objects.filter(student=current_user.student_profile).filter(module=self.module)\n list_lists = List.objects.filter(module=self.module).filter(user=self.request.user)\n item_completed = Item.objects.filter(list__in=list_lists, completed=1)\n objectives_remain = Item.objects.filter(list__in=list_lists, completed=0).count()\n current_user_module = UserModule.objects.filter(user=self.request.user, module=self.module)\n if not current_user_module:\n temp = UserModule(user=current_user, module=self.module)\n temp.save()\n temp.content_views +=1\n temp.objectives_remains = objectives_remain\n temp.save()\n else:\n current_user.user_module.content_views += 1\n current_user.user_module.objectives_remains = objectives_remain\n current_user.user_module.save()\n item_uncompleted = Item.objects.filter(list__in=list_lists, completed=0)\n context.update({\n 'module' : self.module,\n 'assignment_list' : file_submit,\n 'lists' : list_lists,\n 'items' : item_completed,\n 'remediation' : item_uncompleted,\n 'current_user' : current_user,\n })\n return context\n\n def get_queryset(self):\n current_user = get_object_or_404(User, email=self.request.user.email)\n self.module = get_object_or_404(Module, code=self.kwargs['code'])\n current_user_module = UserModule.objects.filter(user=self.request.user, module=self.module)\n if not current_user_module:\n temp = UserModule(user=current_user, module=self.module)\n temp.save()\n return current_user\n","sub_path":"module_progress/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"539180767","text":"# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport torch as th\nimport torch.nn as nn\n\n\nclass Gaussian(nn.Module):\n def __init__(self, kernel_size):\n super(Gaussian, self).__init__()\n sigma = 6\n x_cord = th.arange(kernel_size)\n if th.cuda.is_available():\n x_cord = x_cord.cuda()\n\n x_grid = x_cord.repeat(kernel_size).view(kernel_size, kernel_size)\n y_grid = x_grid.t()\n xy_grid = th.stack([x_grid, y_grid], dim=-1)\n mean = (kernel_size - 1) / 2.\n variance = sigma ** 2.\n gaussian_kernel = (1. / (2. * np.pi * variance)) * th.exp((-th.sum((xy_grid - mean)**2., dim=-1) / (2 * variance)).float())\n gaussian_kernel = gaussian_kernel / th.sum(gaussian_kernel)\n gaussian_kernel = gaussian_kernel.view(1, 1, kernel_size, kernel_size)\n self.gaussian_kernel = gaussian_kernel.repeat(1, 1, 1, 1)\n\n padding = (kernel_size - 1) // 2\n gaussian = nn.Conv2d(1, 1, kernel_size=kernel_size, padding=padding, bias=False)\n gaussian.weight.data = 3 * gaussian_kernel\n gaussian.weight.requires_grad_(False)\n gaussian.padding = (padding, padding)\n self.op = gaussian\n self.op.requires_grad_(True)\n self.op.weight.detach_()\n\n def forward(self, *input):\n return self.op(*input)\n","sub_path":"src/util/gauss.py","file_name":"gauss.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"245421062","text":"import airflow\nimport datetime\nfrom airflow import DAG\nfrom airflow.operators import python_operator, dummy_operator\n\ndefault_args = {\n 'owner': 'Nitin Ware',\n 'depends_on_past': False,\n 'retries': 1,\n 'retry_delay': datetime.timedelta(minutes=5),\n 'start_date': airflow.utils.dates.days_ago(1),\n}\n\ndag = DAG('cron_dag', default_args=default_args, schedule_interval='00 9 * * *',)\n\nstart_dag = dummy_operator.DummyOperator(\n task_id='start',\n default_args=default_args,\n dag=dag,\n)\n\ndef print_dag_info(**kwargs):\n context = kwargs\n print(\"Dag: \", context['dag_run'].dag_id)\n print(\"Task: \", context['task'].task_id)\n print(\"Current Date Time: \", datetime.datetime.now())\n\ncron_dag = python_operator.PythonOperator(\n task_id='cron_dag',\n python_callable=print_dag_info,\n provide_context=True,\n default_args=default_args,\n dag=dag,\n)\n\nstart_dag.set_downstream(cron_dag)\n","sub_path":"src/com/homedepot/airflow/examples/schedule/cron_dag_scheduler.py","file_name":"cron_dag_scheduler.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"332163088","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Apr 16 15:33:39 2019\n\n@author: JunbinZhang\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport csv\nimport math\nfrom brd_config import Brd_Config\nfrom frame import Frames\n#give the location of the file\n\nchns = [[],[],[],[],[],[],[],[]]\ncounts = [[],[],[],[],[],[],[],[]]\n\nwith open('D:\\python_workspace\\DUNE_COLDADC\\data\\ADC0_all.csv') as csvfile:\n readCSV = csv.reader(csvfile,delimiter=',')\n for row in readCSV: \n #print(row)\n \n chns[0].append(row[0])\n counts[0].append(row[1])\n \n chns[1].append(row[2])\n counts[1].append(row[3])\n \n chns[2].append(row[4])\n counts[2].append(row[5])\n \n chns[3].append(row[6])\n counts[3].append(row[7])\n \n chns[4].append(row[8])\n counts[4].append(row[9])\n \n chns[5].append(row[10])\n counts[5].append(row[11])\n \n chns[6].append(row[12])\n counts[6].append(row[13])\n \n chns[7].append(row[14])\n counts[7].append(row[15])\ncsvfile.close()\n\nfor i in range(8):\n chns[i] = chns[i][1:]\n counts[i] = counts[i][1:]\n\ne = counts[0][0] # convet str to int\n\n\n\n\nprint(type(e))\nprint(e)\nprint(type(counts[0]))\n\n\nd = counts[0]\nd = list(map(int,d))\n\nprint(type(d))\nprint(d[0])\nprint(type(d[0]))\nprint(sum(d))\n \n#x = counts[0]\n#y = sum(map(int,x.(',')))\n#print(y)\n#print(len(counts[0]))\n#for i in range(8):\n# print(sum(counts[i]))","sub_path":"dnl_test.py","file_name":"dnl_test.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"555048387","text":"import os, sys\n\ncurrentdir = os.path.dirname(os.path.realpath(__file__))\nparentdir = os.path.dirname(currentdir)\nsys.path.append(parentdir) # PYTHON > 3.3 does not allow relative referencing\n\nPYCHARM_EXEC = os.getenv('PYCHARM_EXEC') == 'True'\n\nimport tensorflow.keras.layers as kl\nimport tensorflow as tf\nfrom tensorflow.python.framework.errors import InvalidArgumentError\n\nfrom DeepDeformationMapRegistration.utils.operators import soft_threshold, gaussian_kernel, sample_unique\nimport DeepDeformationMapRegistration.utils.constants as C\nfrom DeepDeformationMapRegistration.utils.thin_plate_splines import ThinPlateSplines\nfrom voxelmorph.tf.layers import SpatialTransformer\n\n\nclass AugmentationLayer(kl.Layer):\n def __init__(self,\n max_deformation,\n max_displacement,\n max_rotation,\n num_control_points,\n in_img_shape,\n out_img_shape,\n num_augmentations=1,\n gamma_augmentation=True,\n brightness_augmentation=True,\n only_image=False,\n only_resize=True,\n return_displacement_map=False,\n **kwargs):\n super(AugmentationLayer, self).__init__(**kwargs)\n\n self.max_deformation = max_deformation\n self.max_displacement = max_displacement\n self.max_rotation = max_rotation\n self.num_control_points = num_control_points\n self.num_augmentations = num_augmentations\n self.in_img_shape = in_img_shape\n self.out_img_shape = out_img_shape\n self.only_image = only_image\n self.return_disp_map = return_displacement_map\n\n self.do_gamma_augm = gamma_augmentation\n self.do_brightness_augm = brightness_augmentation\n\n grid = C.CoordinatesGrid()\n grid.set_coords_grid(in_img_shape, [C.TPS_NUM_CTRL_PTS_PER_AXIS] * 3)\n self.control_grid = tf.identity(grid.grid_flat(), name='control_grid')\n self.target_grid = tf.identity(grid.grid_flat(), name='target_grid')\n\n grid.set_coords_grid(in_img_shape, in_img_shape)\n self.fine_grid = tf.identity(grid.grid_flat(), 'fine_grid')\n\n if out_img_shape is not None:\n self.downsample_factor = [i // o for o, i in zip(out_img_shape, in_img_shape)]\n self.img_gauss_filter = gaussian_kernel(3, 0.001, 1, 1, 3)\n # self.resize_transf = tf.diag([*self.downsample_factor, 1])[:-1, :]\n # self.resize_transf = tf.expand_dims(tf.reshape(self.resize_transf, [-1]), 0, name='resize_transformation') # ST expects a (12,) vector\n\n self.augment = not only_resize\n\n def compute_output_shape(self, input_shape):\n input_shape = tf.TensorShape(input_shape).as_list()\n img_shape = (input_shape[0], *self.out_img_shape, 1)\n seg_shape = (input_shape[0], *self.out_img_shape, input_shape[-1] - 1)\n disp_shape = (input_shape[0], *self.out_img_shape, 3)\n # Expect the input to have the image and segmentations in the same tensor\n if self.return_disp_map:\n return (img_shape, img_shape, seg_shape, seg_shape, disp_shape)\n else:\n return (img_shape, img_shape, seg_shape, seg_shape)\n\n #@tf.custom_gradient\n def call(self, in_data, training=None):\n # def custom_grad(in_grad):\n # return tf.ones_like(in_grad)\n if training is not None:\n self.augment = training\n return self.build_batch(in_data)# , custom_grad\n\n def build_batch(self, fix_data: tf.Tensor):\n if len(fix_data.get_shape().as_list()) < 5:\n fix_data = tf.expand_dims(fix_data, axis=0) # Add Batch dimension\n # fix_data = tf.tile(fix_data, (self.num_augmentations, *(1,)*4))\n fix_img_batch, mov_img_batch, fix_seg_batch, mov_seg_batch, disp_map = tf.map_fn(lambda x: self.augment_sample(x),\n fix_data,\n dtype=(tf.float32, tf.float32, tf.float32, tf.float32, tf.float32))\n # map_fn unstacks elems on axis 0\n if self.return_disp_map:\n return fix_img_batch, mov_img_batch, fix_seg_batch, mov_seg_batch, disp_map\n else:\n return fix_img_batch, mov_img_batch, fix_seg_batch, mov_seg_batch\n\n def augment_sample(self, fix_data: tf.Tensor):\n if self.only_image or not self.augment:\n fix_img = fix_data\n fix_segm = tf.zeros_like(fix_data, dtype=tf.float32)\n else:\n fix_img = fix_data[..., 0]\n fix_img = tf.expand_dims(fix_img, -1)\n fix_segm = fix_data[..., 1:] # We expect several segmentation masks\n\n if self.augment:\n # If we are training, do the full-fledged augmentation\n fix_img = self.min_max_normalization(fix_img)\n\n mov_img, mov_segm, disp_map = self.deform_image(tf.squeeze(fix_img), fix_segm)\n mov_img = tf.expand_dims(mov_img, -1) # Add the removed channel axis\n\n # Resample to output_shape\n if self.out_img_shape is not None:\n fix_img = self.downsize_image(fix_img)\n mov_img = self.downsize_image(mov_img)\n\n fix_segm = self.downsize_segmentation(fix_segm)\n mov_segm = self.downsize_segmentation(mov_segm)\n\n disp_map = self.downsize_displacement_map(disp_map)\n\n if self.do_gamma_augm:\n fix_img = self.gamma_augmentation(fix_img)\n mov_img = self.gamma_augmentation(mov_img)\n\n if self.do_brightness_augm:\n fix_img = self.brightness_augmentation(fix_img)\n mov_img = self.brightness_augmentation(mov_img)\n\n else:\n # During inference, just resize the input images\n mov_img = tf.zeros_like(fix_img)\n mov_segm = tf.zeros_like(fix_segm)\n\n disp_map = tf.tile(tf.zeros_like(fix_img), [1, 1, 1, 1, 3]) # TODO: change, don't use tile!!\n\n if self.out_img_shape is not None:\n fix_img = self.downsize_image(fix_img)\n mov_img = self.downsize_image(mov_img)\n\n fix_segm = self.downsize_segmentation(fix_segm)\n mov_segm = self.downsize_segmentation(mov_segm)\n\n disp_map = self.downsize_displacement_map(disp_map)\n\n fix_img = self.min_max_normalization(fix_img)\n mov_img = self.min_max_normalization(mov_img)\n return fix_img, mov_img, fix_segm, mov_segm, disp_map\n\n def downsize_image(self, img):\n img = tf.expand_dims(img, axis=0)\n # The filter is symmetrical along the three axes, hence there is no need for transposing the H and D dims\n img = tf.nn.conv3d(img, self.img_gauss_filter, strides=[1, ] * 5, padding='SAME', data_format='NDHWC')\n img = tf.layers.MaxPooling3D([1]*3, self.downsample_factor, padding='valid', data_format='channels_last')(img)\n\n return tf.squeeze(img, axis=0)\n\n def downsize_segmentation(self, segm):\n segm = tf.expand_dims(segm, axis=0)\n segm = tf.layers.MaxPooling3D([1]*3, self.downsample_factor, padding='valid', data_format='channels_last')(segm)\n\n segm = tf.cast(segm, tf.float32)\n return tf.squeeze(segm, axis=0)\n\n def downsize_displacement_map(self, disp_map):\n disp_map = tf.expand_dims(disp_map, axis=0)\n # The filter is symmetrical along the three axes, hence there is no need for transposing the H and D dims\n disp_map = tf.layers.AveragePooling3D([1]*3, self.downsample_factor, padding='valid', data_format='channels_last')(disp_map)\n\n # self.downsample_factor = in_shape / out_shape, but here we need out_shape / in_shape. Hence, 1 / factor\n if self.downsample_factor[0] != self.downsample_factor[1] != self.downsample_factor[2]:\n # Downsize the displacement magnitude along the different axes\n disp_map_x = disp_map[..., 0] * 1 / self.downsample_factor[0]\n disp_map_y = disp_map[..., 1] * 1 / self.downsample_factor[1]\n disp_map_z = disp_map[..., 2] * 1 / self.downsample_factor[2]\n\n disp_map = tf.stack([disp_map_x, disp_map_y, disp_map_z], axis=-1)\n else:\n disp_map = disp_map * 1 / self.downsample_factor[0]\n\n return tf.squeeze(disp_map, axis=0)\n\n def gamma_augmentation(self, in_img: tf.Tensor):\n in_img += 1e-5 # To prevent NaNs\n f = tf.random.uniform((), -1, 1, tf.float32) # gamma [0.5, 2]\n gamma = tf.pow(2.0, f)\n\n return tf.clip_by_value(tf.pow(in_img, gamma), 0, 1)\n\n def brightness_augmentation(self, in_img: tf.Tensor):\n c = tf.random.uniform((), -0.2, 0.2, tf.float32) # 20% shift\n return tf.clip_by_value(c + in_img, 0, 1)\n\n def min_max_normalization(self, in_img: tf.Tensor):\n return tf.div(tf.subtract(in_img, tf.reduce_min(in_img)),\n tf.subtract(tf.reduce_max(in_img), tf.reduce_min(in_img)))\n\n def deform_image(self, fix_img: tf.Tensor, fix_segm: tf.Tensor):\n # Get locations where the intensity > 0.0\n idx_points_in_label = tf.where(tf.greater(fix_img, 0.0))\n\n # Randomly select N points\n # random_idx = tf.random.uniform((self.num_control_points,),\n # minval=0, maxval=tf.shape(idx_points_in_label)[0],\n # dtype=tf.int32)\n #\n # disp_location = tf.gather(idx_points_in_label, random_idx) # And get the coordinates\n # disp_location = tf.cast(disp_location, tf.float32)\n disp_location = sample_unique(idx_points_in_label, self.num_control_points, tf.float32)\n\n # Get the coordinates of the control point displaces\n rand_disp = tf.random.uniform((self.num_control_points, 3), minval=-1, maxval=1, dtype=tf.float32) * self.max_deformation\n warped_location = disp_location + rand_disp\n\n # Add the selected locations to the control grid and the warped locations to the target grid\n control_grid = tf.concat([self.control_grid, disp_location], axis=0)\n trg_grid = tf.concat([self.control_grid, warped_location], axis=0)\n\n # Apply global transformation\n valid_trf = False\n while not valid_trf:\n trg_grid, aff = self.global_transformation(trg_grid)\n\n # Interpolate the displacement map\n try:\n tps = ThinPlateSplines(control_grid, trg_grid)\n def_grid = tps.interpolate(self.fine_grid)\n except InvalidArgumentError as err:\n # If the transformation raises a non-invertible error,\n # try again until we get a valid transformation\n tf.print('TPS non invertible matrix', output_stream=sys.stdout)\n continue\n else:\n valid_trf = True\n\n disp_map = self.fine_grid - def_grid\n disp_map = tf.reshape(disp_map, (*self.in_img_shape, -1))\n\n # Apply the displacement map\n fix_img = tf.expand_dims(tf.expand_dims(fix_img, -1), 0)\n fix_segm = tf.expand_dims(fix_segm, 0)\n disp_map = tf.cast(tf.expand_dims(disp_map, 0), tf.float32)\n\n mov_img = SpatialTransformer(interp_method='linear', indexing='ij', single_transform=False)([fix_img, disp_map])\n mov_segm = SpatialTransformer(interp_method='nearest', indexing='ij', single_transform=False)([fix_segm, disp_map])\n\n mov_img = tf.where(tf.is_nan(mov_img), tf.zeros_like(mov_img), mov_img)\n mov_img = tf.where(tf.is_inf(mov_img), tf.zeros_like(mov_img), mov_img)\n\n mov_segm = tf.where(tf.is_nan(mov_segm), tf.zeros_like(mov_segm), mov_segm)\n mov_segm = tf.where(tf.is_inf(mov_segm), tf.zeros_like(mov_segm), mov_segm)\n\n return tf.squeeze(mov_img), tf.squeeze(mov_segm, axis=0), tf.squeeze(disp_map, axis=0)\n\n def global_transformation(self, points: tf.Tensor):\n axis = tf.random.uniform((), 0, 3)\n\n alpha = C.DEG_TO_RAD * tf.cond(tf.logical_and(tf.greater(axis, 0.), tf.less_equal(axis, 1.)),\n lambda: tf.random.uniform((), -self.max_rotation, self.max_rotation),\n lambda: tf.zeros((), tf.float32))\n beta = C.DEG_TO_RAD * tf.cond(tf.logical_and(tf.greater(axis, 1.), tf.less_equal(axis, 2.)),\n lambda: tf.random.uniform((), -self.max_rotation, self.max_rotation),\n lambda: tf.zeros((), tf.float32))\n gamma = C.DEG_TO_RAD * tf.cond(tf.logical_and(tf.greater(axis, 2.), tf.less_equal(axis, 3.)),\n lambda: tf.random.uniform((), -self.max_rotation, self.max_rotation),\n lambda: tf.zeros((), tf.float32))\n\n ti = tf.random.uniform((), minval=-1, maxval=1, dtype=tf.float32) * self.max_displacement\n tj = tf.random.uniform((), minval=-1, maxval=1, dtype=tf.float32) * self.max_displacement\n tk = tf.random.uniform((), minval=-1, maxval=1, dtype=tf.float32) * self.max_displacement\n\n M = self.build_affine_transformation(tf.convert_to_tensor(self.in_img_shape, tf.float32),\n alpha, beta, gamma, ti, tj, tk)\n\n points = tf.transpose(points)\n new_pts = tf.matmul(M[:3, :3], points)\n new_pts = tf.expand_dims(M[:3, -1], -1) + new_pts\n return tf.transpose(new_pts), M\n\n @staticmethod\n def build_affine_transformation(img_shape, alpha, beta, gamma, ti, tj, tk):\n img_centre = tf.divide(img_shape, 2.)\n\n # Rotation matrix around the image centre\n # R* = T(p) R(ang) T(-p)\n # tf.cos and tf.sin expect radians\n\n T = tf.convert_to_tensor([[1, 0, 0, ti],\n [0, 1, 0, tj],\n [0, 0, 1, tk],\n [0, 0, 0, 1]], tf.float32)\n\n Ri = tf.convert_to_tensor([[1, 0, 0, 0],\n [0, tf.math.cos(alpha), -tf.math.sin(alpha), 0],\n [0, tf.math.sin(alpha), tf.math.cos(alpha), 0],\n [0, 0, 0, 1]], tf.float32)\n\n Rj = tf.convert_to_tensor([[ tf.math.cos(beta), 0, tf.math.sin(beta), 0],\n [0, 1, 0, 0],\n [-tf.math.sin(beta), 0, tf.math.cos(beta), 0],\n [0, 0, 0, 1]], tf.float32)\n\n Rk = tf.convert_to_tensor([[tf.math.cos(gamma), -tf.math.sin(gamma), 0, 0],\n [tf.math.sin(gamma), tf.math.cos(gamma), 0, 0],\n [0, 0, 1, 0],\n [0, 0, 0, 1]], tf.float32)\n\n R = tf.matmul(tf.matmul(Ri, Rj), Rk)\n\n Tc = tf.convert_to_tensor([[1, 0, 0, img_centre[0]],\n [0, 1, 0, img_centre[1]],\n [0, 0, 1, img_centre[2]],\n [0, 0, 0, 1]], tf.float32)\n\n Tc_ = tf.convert_to_tensor([[1, 0, 0, -img_centre[0]],\n [0, 1, 0, -img_centre[1]],\n [0, 0, 1, -img_centre[2]],\n [0, 0, 0, 1]], tf.float32)\n\n return tf.matmul(T, tf.matmul(Tc, tf.matmul(R, Tc_)))\n\n def get_config(self):\n config = super(AugmentationLayer, self).get_config()\n return config\n\n\n\n","sub_path":"DeepDeformationMapRegistration/layers/augmentation.py","file_name":"augmentation.py","file_ext":"py","file_size_in_byte":15549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"278384661","text":"import tkinter as tk\nfrom tkinter import Button\nfrom tkinter.filedialog import askopenfilename\n\n\nclass ImageProcessingApp(tk.Tk):\n def __init__(self, image_processor):\n self.__image_processor = image_processor\n tk.Tk.__init__(self)\n self.title(\"Hands photo processing application\")\n self.geometry(\"500x260\")\n self.resizable(False, False)\n\n self.__load_button = Button(self, text=\"Load image from file\", command=self.load_from_file,\n width=61, height=2)\n self.__load_button.pack()\n\n self.__process_button = Button(self, text=\"Process image\", command=self.process_image, state=\"disabled\",\n width=61, height=2)\n self.__process_button.pack()\n\n self.__show_button = Button(self, text=\"Show processed image\", command=self.show_processed_image,\n state=\"disabled\", width=61, height=2)\n self.__show_button.pack()\n\n self.__save_button = Button(self, text=\"Save processed image to file\", command=self.save_to_file,\n state=\"disabled\", width=61, height=2)\n\n self.__save_button.pack()\n\n self.__exit_button = Button(self, text=\"Exit\", command=self.exit, width=61, height=2)\n self.__exit_button.pack()\n\n def load_from_file(self):\n self.__image_processor.load_image_from_file(askopenfilename())\n self.__process_button[\"state\"] = \"normal\"\n\n def process_image(self):\n self.__image_processor.find_points()\n self.__show_button[\"state\"] = \"normal\"\n self.__save_button[\"state\"] = \"normal\"\n\n def show_processed_image(self):\n self.__image_processor.show_processed_image()\n\n def save_to_file(self):\n self.__image_processor.save_image_to_file()\n\n def exit(self):\n self.quit()","sub_path":"task_02/image_processing_app.py","file_name":"image_processing_app.py","file_ext":"py","file_size_in_byte":1870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"367873525","text":"from selenium import webdriver\nfrom time import sleep\ndr = webdriver.Firefox()\n#处理浏览器窗口\ndr.get('https://qzone.qq.com')\n#获取当前窗口字符串(句柄)\nprint(dr.current_window_handle)\nsleep(2)\n#处理框架 iframe(窗口)\n#dr.switch_to_frame() 框架的ID或者name或者先定位\ndr.switch_to.frame('login_frame')#切换到某一个框架\ndr.switch_to.default_content()#回到最开始的页面上\ndr.switch_to.parent_frame()#回到父框架\ndr.find_element_by_id('switcher_plogin').click()\nsleep(2)\n#获取所有窗口的句柄\nqq=dr.window_handles\n#切换句柄\ndr.switch_to.window(qq[-1])\ndr.find_element_by_id('u').send_keys(1872123622)\nsleep(2)\ndr.find_element_by_id('p').send_keys('13782826564yy')\nsleep(2)\ndr.find_element_by_id('login_button').click()","sub_path":"python_stu/测试/自动登录.py","file_name":"自动登录.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"597735924","text":"import sys\nfrom optparse import OptionParser\nimport os\nimport numpy as np\nfrom parse_gff3 import parseGFF3\nfrom tqdm import tqdm as tq\n\n\ndef main():\n usage = 'usage: %prog [options] '\n parser = OptionParser(usage)\n parser.add_option('-t', dest='loci_of_interest', default='CDS', type='str', help='Loci of interest e.g. TSS, SNP, CDS etc. [Default: %default]')\n parser.add_option('-e', dest='width', type='int', default=500, help='Extend all sequences to this length [Default: %default]')\n parser.add_option('-r', dest='stride', default=20, type='int', help='Stride size for moving window [Default: %default]')\n parser.add_option('-u', dest='upstream', default=500, type='int', help='Upstream distance to locus of interest to include [Default: %default]')\n parser.add_option('-d', dest='downstream', default=500, type='int', help='Upstream distance to locus of interest to include [Default: %default]')\n parser.add_option('-s', dest='split', default=2, type='int', help='Split into validation and test sets i.e. 0: only train, 1:train and test, 2: train test and validation [Default: %default]')\n (options, args) = parser.parse_args()\n\n # Make directory for the project, establish indexing bounds\n directory = \"../data/regions/\"\n if not os.path.exists(directory):\n os.makedirs(directory)\n with open(args[0], 'r') as f:\n chr_sizes = {line.split('\\t')[0]: (1, int(line.split('\\t')[-1].split('\\n')[0])) for line in f.readlines()}\n save_path = os.path.join(directory, args[2])\n xran_pos = np.arange(-options.upstream, options.downstream, options.stride)\n xran_neg = np.arange(-options.downstream, options.upstream, options.stride)\n\n # Read in gff3 annotation file\n with open(save_path, 'w') as fw:\n for record in tq(parseGFF3(args[1])):\n if (record['type'] != options.loci_of_interest) or \\\n (record['source'] != 'ensembl') or \\\n (record['seqid'] == 'Mito') or \\\n ((record['end'] - max(options.upstream, options.downstream)) > chr_sizes['chr' + record['seqid']]):\n continue\n starts = record['start'] + xran_pos if record['strand'] == '+' else record['end'] + xran_neg\n starts = starts[starts > 0]\n list_to_write = ['chr' + record['seqid'] + '\\t' + str(st) + '\\t' + str(st + options.width) + '\\t.\\t.\\t' + record['strand']\n for st in starts]\n fw.write('\\n'.join(list_to_write)+'\\n')\n\n # Construct train, test, and validation regions\n with open(save_path, 'r') as fr:\n _ = fr.readline() # discard first line, no information\n all_lines = fr.readlines()\n np.random.shuffle(all_lines)\n with open(os.path.join(directory, 'train_regions.bed'), 'w') as fw:\n fw.write(''.join(all_lines[4000:]))\n if options.split > 0:\n with open(os.path.join(directory, 'test_regions.bed'), 'w') as fw:\n fw.write(''.join(all_lines[2000:4000]))\n if options.split > 1:\n with open(os.path.join(directory, 'validation_regions.bed'), 'w') as fw:\n fw.write(''.join(all_lines[:2000]))\n\nif __name__ == '__main__':\n main()\n","sub_path":"fiddle/generate_regions.py","file_name":"generate_regions.py","file_ext":"py","file_size_in_byte":3240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"586236700","text":"import logging\n\nimport click\n\nfrom regparser.index import dependency, entry\nfrom regparser.notice.xml import NoticeXML\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef parse_notice(xml_file_path):\n \"\"\"Read the notice from the XML file; fill out any missing fields\"\"\"\n with open(xml_file_path, 'rb') as f:\n notice_xml = NoticeXML(f.read(), xml_file_path).preprocess()\n\n if has_requirements(notice_xml):\n notice_xml.derive_where_needed()\n return notice_xml\n\n\ndef has_requirements(notice_xml):\n \"\"\"A few pieces of meta data only come from the Federal Register API. As\n we don't have access to that, we verify that the XML has it embedded\"\"\"\n if not notice_xml.version_id:\n logger.error(\"Missing version_id (eregs-version-id attribute on root)\")\n elif not notice_xml.published:\n logger.error(\"Missing publish date (eregs-published-date attribute \"\n \"on the DATES tag)\")\n elif not notice_xml.fr_volume:\n logger.error(\"Missing volume (eregs-fr-volume attribute on the first \"\n \"PRTPAGE tag)\")\n else:\n return True\n\n\ndef write_if_stale(notice_xml):\n \"\"\"We only want to write out the processed xml if it is \"stale\", i.e. if\n its source has changed\"\"\"\n deps = dependency.Graph()\n notice_entry = entry.Notice(notice_xml.version_id)\n\n new_notice = notice_entry not in deps\n diff_source = notice_xml.source not in deps.dependencies(notice_xml)\n source_changed = deps.is_stale(notice_entry)\n\n if new_notice or diff_source or source_changed:\n deps.clear_for(notice_entry)\n deps.add(notice_entry, notice_xml.source)\n notice_entry.write(notice_xml)\n\n\n@click.command()\n@click.argument('xml_file', type=click.Path(exists=True))\ndef import_notice(xml_file):\n \"\"\"Convert XML file into a notice. May be used if manually creating a\n notice (e.g. from a Word doc). This command will also run a handful of\n validations on the XML\"\"\"\n notice_xml = parse_notice(xml_file)\n if notice_xml:\n write_if_stale(notice_xml)\n","sub_path":"regparser/commands/import_notice.py","file_name":"import_notice.py","file_ext":"py","file_size_in_byte":2068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"287911928","text":"import os\nimport subprocess\nimport json\nfrom psutil import virtual_memory\nimport datetime\nimport shutil\n\nROOT_PATH = 'data/database/aerospike/'\n\n\ndef create_conf(name='platform_aerospike3',\n network='eth0',\n port='300',\n mem_storage=10,\n hdd_storage=100,\n storage='G',\n ips=None,\n storage_conf='hdd'):\n global mem_storage_in_single_node, hdd_storage_in_single_node\n if ips is None:\n ips = ['10.5.36.43', '10.5.37.100', '10.5.37.97']\n template_path = ROOT_PATH + 'template_server/'\n server_path = ROOT_PATH + 'test_server/' + name + '/'\n if not os.path.isdir(server_path):\n\n # check mem usage\n monitor_path_file = ROOT_PATH + 'test_server/monitor.txt'\n if os.path.isfile(monitor_path_file):\n monitor_file = open(monitor_path_file, 'r')\n monitor_dict = json.load(monitor_file)\n monitor_file.close()\n else:\n monitor_dict = {'db_info': []}\n usage_mem = 0\n usage_hdd = 0\n for ae_cluster in monitor_dict['db_info']:\n if ae_cluster.get('storage') == 'G':\n usage_mem += ae_cluster.get('mem_storage') // len(ae_cluster.get('ips'))\n usage_hdd += ae_cluster.get('hdd_storage') // len(ae_cluster.get('ips'))\n elif ae_cluster.get('storage') == 'T':\n usage_mem += (ae_cluster.get('mem_storage') * (2 ** 10)) // len(ae_cluster.get('ips'))\n usage_hdd += (ae_cluster.get('hdd_storage') * (2 ** 10)) // len(ae_cluster.get('ips'))\n\n # check port\n if ae_cluster.get('port') == port:\n return {'status': 'port existed'}\n mem = virtual_memory()\n total_mem = mem.total // (2 ** 30)\n check_mem = total_mem - usage_mem\n total_hdd = shutil.disk_usage('/')[0] // (2 ** 30)\n check_hdd = total_hdd - usage_hdd\n if storage == 'G':\n mem_storage_in_single_node = mem_storage // len(ips)\n hdd_storage_in_single_node = hdd_storage // len(ips)\n elif storage == 'T':\n mem_storage_in_single_node = (mem_storage * (2 ** 10)) // len(ips)\n hdd_storage_in_single_node = (hdd_storage * (2 ** 10)) // len(ips)\n if check_mem > mem_storage_in_single_node and check_hdd > hdd_storage_in_single_node:\n\n # append and saving config\n monitor_dict['db_info'].append({'name': name,\n 'network': network,\n 'port': port,\n 'mem_storage': mem_storage,\n 'mem_storage_single_node': mem_storage // len(ips),\n 'hdd_storage_single_node': hdd_storage // len(ips),\n 'hdd_storage': hdd_storage,\n 'storage': storage,\n 'ips': ips,\n 'storage_conf': storage_conf,\n 'created_time': str(datetime.datetime.today())})\n monitor_dict['free_mem_in_single'] = str(check_mem - mem_storage_in_single_node) + 'G'\n monitor_dict['free_hdd_in_single'] = str(check_hdd - hdd_storage_in_single_node) + 'G'\n monitor_file = open(monitor_path_file, 'w')\n json.dump(monitor_dict, monitor_file)\n monitor_file.close()\n\n # create docker config\n os.mkdir(server_path)\n conf_output_file = open(server_path + 'aerospike.conf', 'w')\n with open(template_path + storage_conf + '.conf') as conf_file:\n for conf_line in conf_file:\n if '' in conf_line:\n conf_line = conf_line.replace('', network)\n if '' in conf_line:\n conf_line = conf_line.replace('', port)\n if '' in conf_line:\n conf_line = conf_line.replace('', name)\n if '' in conf_line:\n ip_conf_line = ''\n for ip in ips:\n ip_conf_line += conf_line.replace('', ip)\n conf_line = ip_conf_line\n if '' in conf_line:\n conf_line = conf_line.replace('', str(mem_storage // len(ips)) + storage)\n if '' in conf_line:\n conf_line = conf_line.replace('', str(hdd_storage // len(ips)) + storage)\n conf_output_file.write(conf_line)\n conf_output_file.close()\n\n subprocess.call('cp ' + template_path + 'stack.yml ' + server_path + 'stack.yml', shell=True)\n sh_file = open(server_path + 'run.sh', 'w')\n sh_file.write('docker stack deploy -c stack.yml ' + name + '\\n')\n sh_file.close()\n return {'status': 'create config done'}\n elif check_mem < mem_storage_in_single_node:\n return {'status': 'mem not enough storage'}\n elif check_hdd < hdd_storage_in_single_node:\n return {'status': 'hdd not enough storage'}\n return {'status': 'storage error'}\n return {'status': 'config existed'}\n\n\ndef get_info():\n # check mem usage\n monitor_path_file = ROOT_PATH + 'test_server/monitor.txt'\n if os.path.isfile(monitor_path_file):\n monitor_file = open(monitor_path_file, 'r')\n monitor_dict = json.load(monitor_file)\n monitor_file.close()\n return monitor_dict\n return {'status': 'info not exists'}\n\n\nif __name__ == '__main__':\n print(create_conf())","sub_path":"data/docker/database/aerospike/aerospike_creater.py","file_name":"aerospike_creater.py","file_ext":"py","file_size_in_byte":5874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"55343580","text":"# Return Fibonacci to n length\r\n\r\nfrom __future__ import print_function\r\nlimit = 1000\r\n\r\ndef fib(n):\r\n\r\n sequence = [1]\r\n\r\n while len(sequence) < n:\r\n if len(sequence) == 1:\r\n sequence.append(1)\r\n else:\r\n sequence.append(sequence[-1] + sequence[-2])\r\n\r\n for k in range(len(sequence)):\r\n sequence[k] = str(sequence[k])\r\n\r\n return (', '.join(sequence))\r\n\r\ndef shell():\r\n print (\"Enter length of Fibonacci:\")\r\n\r\n while True:\r\n k = input()\r\n if k == \"quit\":\r\n break\r\n if k > limit:\r\n print (\"Limit set to 1000, please go lower!\")\r\n else:\r\n print (str(fib(int(k))))\r\n\r\nif __name__==\"__main__\":\r\n shell()\r\n","sub_path":"fib/fib.py","file_name":"fib.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"603235158","text":"# initialize with random values\nimport math\nimport random\nimport datetime\nimport time\n\n'''\nAsteroid class for creating asteroid objects\n'''\nclass Asteroid:\n id = 1\n\n def __init__(self):\n self._ccmf = self.randCcmf()\n self._pos = (random.randint(0, 100), random.randint(0, 100), random.randint(0, 100))\n self._oldPos = ()\n self._vel = (random.randint(1, 5), random.randint(1, 5), random.randint(1, 5))\n self._id = self.addID()\n\n def move(self):\n curPos = self.getPos()\n curVel = self.getVel()\n newPos = (curPos[0] + curVel[0], curPos[1] + curVel[1], curPos[2] + curVel[2])\n self.setPos(newPos)\n self.__str__()\n\n def randCcmf(self):\n rad = random.randint(0, 4000)/1000\n ccmf = (2*math.pi*rad)\n return ccmf\n\n def addID(self):\n val = Asteroid.id\n Asteroid.id = Asteroid.id + 1\n return val\n\n def __str__(self):\n myString = 'Asteroid {0} has moved! Old Pos: {1}, {2}, {3} -> '\\\n 'New Pos: {4}, {5}, {6}\\nAsteroid {0} is currently at {4}, {5}, {6}' \\\n ' and is moving at {7}, {8}, {9} meters per second. ' \\\n 'It has a circumference of {10}'\\\n .format(self._id, self._oldPos[0], self._oldPos[1], self._oldPos[2],\n self._pos[0], self._pos[1], self._pos[2],\n self._vel[0], self._vel[1], self._vel[2],\n self._ccmf)\n print(myString)\n\n def getPos(self):\n return self._pos\n\n def getVel(self):\n return self._vel\n\n def setPos(self, new):\n self._oldPos = self._pos\n self._pos = new\n\nclass Controller:\n def __init__(self, i):\n self._asteroids = self.createAList(i)\n self._numAsteroids = i\n\n def createAList(self, i):\n aList = []\n for x in range(i - 1):\n aList.append(Asteroid())\n return aList\n\n def simulate(self, seconds):\n endTime = datetime.datetime.now() + datetime.timedelta(seconds=seconds)\n\n while datetime.datetime.now() < endTime:\n self.aggrMove()\n time.sleep(1)\n\n def aggrMove(self):\n for x in self._asteroids:\n x.move()\n\nc = Controller(10)\nc.simulate(4)","sub_path":"Labs/Lab 1/asteroid.py","file_name":"asteroid.py","file_ext":"py","file_size_in_byte":2295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"503288463","text":"\"\"\"In this example, we will import a mesh from a .obj file and render it with a material.\"\"\"\n\nimport blendersynth as bsyn\nbsyn.run_this_script(debug = False)\n\n# Load a OBJ file\nmesh = bsyn.Mesh.from_obj('../resources/monkeys/obj/monkey.obj')\nbsyn.world.set_color((0.8, 0.7, 0.8))\n\nbsyn.render.set_cycles_samples(10)\nbsyn.render.set_resolution(256, 256)\n\ncamera = bsyn.Camera()\ncamera.set_fov(20) # zoom in\n\n# render\ncomp = bsyn.Compositor()\ncomp.define_output('Image', 'obj', file_name='rgb', mode='image')\ncomp.render()","sub_path":"examples/mesh_importing.py","file_name":"mesh_importing.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"368283209","text":"def outlierCleaner(predictions, ages, net_worths):\n \"\"\"\n Clean away the 10% of points that have the largest\n residual errors (difference between the prediction\n and the actual net worth).\n\n Return a list of tuples named cleaned_data where\n each tuple is of the form (age, net_worth, error).\n \"\"\"\n\n cleaned_data = []\n\n ### your code goes here\n for i in range(len(ages)):\n residual = [int(ages[i]), float(net_worths[i]),\n float(net_worths[i] - predictions[i])**2]\n residual = tuple(residual)\n cleaned_data.append(residual)\n\n cleaned_data = sorted(cleaned_data, key = lambda residual: residual[2])\n\n reduced = int(len(ages) * 0.9)\n cleaned_data = cleaned_data[:reduced]\n\n return cleaned_data\n","sub_path":"outliers/outlier_cleaner.py","file_name":"outlier_cleaner.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"183771419","text":"import time\n\nimport pytest\n\nfrom pages.cart_page import CartPage\nfrom pages.login_page import LoginPage\nfrom pages.product_page import ProductPage\n\n\n@pytest.fixture\ndef setup(browser):\n link = \"http://selenium1py.pythonanywhere.com/ru/accounts/login/\"\n page = LoginPage(browser, link)\n page.open()\n email = str(time.time()) + \"@fakemail.org\"\n page.register_new_user(email, \"123password123\")\n page.should_be_authorized_user()\n\n@pytest.mark.parametrize('link', [\"http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/?promo=offer0\"])\nclass TestUserAddToCartFromProductPage(object):\n def test_user_cant_see_success_message(self, browser, link, setup):\n link = link\n page = ProductPage(browser, link)\n page.open()\n page.should_not_be_success_message()\n\n @pytest.mark.need_review\n def test_user_can_add_product_to_cart(self, browser, link, setup):\n link = link\n page = ProductPage(browser, link)\n page.open()\n page.add_product_to_cart()\n page.solve_quiz_and_get_code()\n page.should_be_added_to_cart()\n\n\n@pytest.mark.need_review\ndef test_guest_can_add_product_to_cart(browser):\n link = \"http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/?promo=offer0\"\n page = ProductPage(browser, link)\n page.open()\n page.add_product_to_cart()\n page.solve_quiz_and_get_code()\n page.should_be_added_to_cart()\n\n\n@pytest.mark.xfail\ndef test_guest_cant_see_success_message_after_adding_product_to_cart(browser):\n link = \"http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/\"\n page = ProductPage(browser, link)\n page.open()\n page.add_product_to_cart()\n page.should_not_be_success_message()\n\n\n@pytest.mark.xfail\ndef test_message_disappeared_after_adding_product_to_cart(browser):\n link = \"http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/\"\n page = ProductPage(browser, link)\n page.open()\n page.add_product_to_cart()\n page.should_not_be_appeared_success_message()\n\n\ndef test_guest_should_see_login_link_on_product_page(browser):\n link = \"http://selenium1py.pythonanywhere.com/en-gb/catalogue/the-city-and-the-stars_95/\"\n page = ProductPage(browser, link)\n page.open()\n page.should_be_login_link()\n\n\n@pytest.mark.need_review\ndef test_guest_can_go_to_login_page_from_product_page(browser):\n link = \"http://selenium1py.pythonanywhere.com/en-gb/catalogue/the-city-and-the-stars_95/\"\n page = ProductPage(browser, link)\n page.open()\n page.go_to_login_page()\n\n\n@pytest.mark.need_review\ndef test_guest_cant_see_product_in_cart_opened_from_product_page(browser):\n link = \"http://selenium1py.pythonanywhere.com/en-gb/catalogue/the-city-and-the-stars_95/\"\n page = ProductPage(browser, link)\n page.open()\n page.go_to_cart()\n cart_page = CartPage(browser, browser.current_url)\n cart_page.should_be_empty_cart()\n cart_page.should_be_empty_cart_message()","sub_path":"test_product_page.py","file_name":"test_product_page.py","file_ext":"py","file_size_in_byte":2963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"639238484","text":"# Author:XuQuan\nsalary = input(\"please enter your salary:\")\nshopping_list = [[\"apple\",4000],[\"mac\",8000],[\"book\",39],[\"bike\",3700]]\ncount = len(shopping_list)\nbuy_list = []\nfor index,product in enumerate(shopping_list):\n print(index,product)\nif salary.isdigit():\n salary = int(salary)\n while True:\n b = input(\"what do you want to buy,please enter your number:\")\n if b.isdigit():\n b = int(b)\n if b>=0 and b < count:\n if salary >= shopping_list[b][1]:\n print(\"your buy product is\",shopping_list[b][0])\n buy_list.append(shopping_list[b])\n salary -=shopping_list[b][1]\n print(\"your current salary is\",salary)\n else:\n print(\"your current salary is not ecough...\")\n else:\n print(\"your input is invaild...\")\n elif b == \"q\":\n print(buy_list)\n print(salary)\n exit()\n else:\n print(\"your input is invaild...\")\nelse:\n print(\"your input is invaild...\")\n","sub_path":"day2/购物车.py","file_name":"购物车.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"329511856","text":"'''\nCreated on Jul 24, 2013\n\n@package: ally core\n@copyright: 2011 Sourcefabric o.p.s.\n@license: http://www.gnu.org/licenses/gpl-3.0.txt\n@author: Gabriel Nistor\n\nProvides the queries ascending and descending order criteria decoding.\n'''\n\nfrom .create_parameter import Parameter\nfrom ally.api.type import List, Type\nfrom ally.container.ioc import injected\nfrom ally.core.impl.processor.decoder.base import addFailure\nfrom ally.design.processor.assembly import Assembly\nfrom ally.design.processor.attribute import requires, defines\nfrom ally.design.processor.branch import Branch\nfrom ally.design.processor.context import Context\nfrom ally.design.processor.execution import Processing\nfrom ally.design.processor.handler import HandlerBranching\nfrom ally.support.util_spec import IDo\n\n# --------------------------------------------------------------------\n\nNAME_ASC = 'asc'\n# The name used for the ascending list of names.\nNAME_DESC = 'desc'\n# The name used for the descending list of names.\n\n# --------------------------------------------------------------------\n\nclass Create(Context):\n '''\n The create context.\n '''\n # ---------------------------------------------------------------- Required\n orderSetters = requires(dict)\n orderPrioritySetters = requires(dict)\n orderPriorityGetters = requires(list)\n \nclass DecodingOrder(Context):\n '''\n The order decoding context.\n '''\n # ---------------------------------------------------------------- Defined\n doDecode = defines(IDo, doc='''\n @rtype: callable(target, value)\n Decodes the value into the provided target.\n @param target: Context\n Target context object used for decoding.\n @param value: object\n The value to be decoded.\n ''')\n type = defines(Type)\n \nclass DefinitionOrder(Context):\n '''\n The definition context.\n '''\n # ---------------------------------------------------------------- Defined\n enumeration = defines(list, doc='''\n @rtype: list[string]\n The enumeration values that are allowed for order.\n ''')\n \n# --------------------------------------------------------------------\n\n@injected\nclass CreateParameterOrderDecode(HandlerBranching):\n '''\n Implementation for a handler that provides the query order criterias decoding.\n '''\n \n decodeOrderAssembly = Assembly\n # The decode processors to be used for decoding.\n \n def __init__(self):\n assert isinstance(self.decodeOrderAssembly, Assembly), \\\n 'Invalid order decode assembly %s' % self.decodeOrderAssembly\n super().__init__(Branch(self.decodeOrderAssembly).using(parameter=Parameter).\n included(('decoding', 'Decoding')).included())\n \n def process(self, chain, processing, create:Create, Decoding:DecodingOrder, Definition:DefinitionOrder, **keyargs):\n '''\n @see: HandlerBranching.process\n \n Create the order decode.\n '''\n assert isinstance(processing, Processing), 'Invalid processing %s' % processing\n assert isinstance(create, Create), 'Invalid create %s' % create\n assert issubclass(Decoding, DecodingOrder), 'Invalid decoding class %s' % Decoding\n assert issubclass(Definition, DefinitionOrder), 'Invalid definition class %s' % Definition\n \n if not create.orderSetters: return \n # There is not order to process.\n \n adec, ddec = Decoding(), Decoding()\n assert isinstance(adec, DecodingOrder), 'Invalid decoding %s' % adec\n assert isinstance(ddec, DecodingOrder), 'Invalid decoding %s' % ddec\n \n adec.type = ddec.type = List(str)\n \n \n adec.doDecode = self.createDecode(True, create.orderSetters, create.orderPriorityGetters,\n create.orderPrioritySetters, adec)\n ddec.doDecode = self.createDecode(False, create.orderSetters, create.orderPriorityGetters,\n create.orderPrioritySetters, ddec)\n \n adef = Definition(enumeration=sorted(create.orderSetters.keys()))\n ddef = Definition(enumeration=sorted(create.orderSetters.keys()))\n \n processing.wingIn(chain, True, decoding=ddec, definition=ddef, parameter=processing.ctx.parameter(path=[NAME_DESC]))\n processing.wingIn(chain, True, decoding=adec, definition=adef, parameter=processing.ctx.parameter(path=[NAME_ASC]))\n\n # ----------------------------------------------------------------\n \n def createDecode(self, asc, settersAsc, gettersPriority, settersPriority, decoding):\n '''\n Create the order do decode.\n '''\n assert isinstance(asc, bool), 'Invalid ascending flag %s' % asc\n assert isinstance(settersAsc, dict), 'Invalid ascending mapping %s' % settersAsc\n assert isinstance(gettersPriority, list), 'Invalid priority getters %s' % gettersPriority\n assert isinstance(settersPriority, dict), 'Invalid priority setter %s' % settersPriority\n def doDecode(target, value):\n '''\n Do the order decode.\n '''\n if not isinstance(value, list): addFailure(target, decoding, value=value) \n else:\n for item in value:\n setAsc = settersAsc.get(item)\n if setAsc is None: addFailure(target, decoding, value=item)\n else:\n setAsc(target, asc)\n setPriority = settersPriority.get(item)\n if setPriority:\n priorities = [priority for priority in (getPriority(target) for getPriority in gettersPriority)\n if priority is not None]\n if priorities: current = max(priorities)\n else: current = 0\n \n setPriority(target, current + 1)\n return doDecode\n","sub_path":"components/ally-core-http/ally/core/http/impl/processor/decoder/create_parameter_order.py","file_name":"create_parameter_order.py","file_ext":"py","file_size_in_byte":5984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"411611126","text":"import pickle, gzip, os\nfrom urllib import request\nfrom pylab import imshow, show, cm\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom tensorflow import keras\n\ndef fixlabels(labels):\n new_labels = []\n for label in labels:\n tmp_arr = []\n for i in range(10):\n if i == label:\n tmp_arr.append(1)\n else:\n tmp_arr.append(0)\n new_labels.append(np.array(tmp_arr))\n\n return np.array(new_labels)\n\ndef get_image (number):\n (data, label) = [img[number] for img in train_set ]\n return (np.array(data), numberlabel_to_array(label))\n\ndef view_image (number):\n (X, y) = get_image (number)\n imshow (X.reshape(28 ,28), cmap=cm.gray)\n show()\n\nf = gzip.open('mnist.pkl.gz', 'rb')\ntrain_set, valid_set, test_set = pickle.load(f, encoding ='latin1')\nf.close()\n\ntrain = [img for img in train_set][0]\ntrain_labels = fixlabels(train_set[1])\n\nvalidation = [img for img in valid_set][0]\nvalidation_labels = fixlabels(valid_set[1])\n\n\n#more nodes means higher accuracy, 16 seems to be pretty good accuracy/speed tradeoff\nmodel = keras.Sequential([\n keras.layers.Dense(16, activation=tf.nn.sigmoid),\n keras.layers.Dense(10, activation=tf.nn.sigmoid)\n])\n\nmodel.compile(optimizer=keras.optimizers.Adam(0.01),\n loss=keras.losses.mean_squared_error,\n metrics=['accuracy'])\n\nepochs = 5\n\nhistory = model.fit(x=train, y=train_labels, validation_data=(validation,validation_labels),epochs=epochs)\n\nmodel.summary()\n\naccuracy=history.history['acc']\nval_accuracy = history.history['val_acc']\n\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs_range = range(epochs)\n\nplt.figure(figsize=(8, 8))\nplt.subplot(1, 2, 1)\nplt.plot(epochs_range, accuracy, label='Training Accuracy')\nplt.plot(epochs_range, val_accuracy, label='Validation Accuracy')\nplt.legend(loc='lower right')\nplt.title('Training and Validation Accuracy')\n\nplt.subplot(1, 2, 2)\nplt.plot(epochs_range, loss, label='Training Loss')\nplt.plot(epochs_range, val_loss, label='Validation Loss')\nplt.legend(loc='upper right')\nplt.title('Training and Validation Loss')\nplt.show()","sub_path":"vectors/nmist_classifier.py","file_name":"nmist_classifier.py","file_ext":"py","file_size_in_byte":2177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"370976707","text":"# -*- encoding: utf-8 -*-\n# Copyright (c) 2017 Servionica\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport mock\nfrom oslo_config import cfg\nfrom oslo_utils import timeutils\n\nfrom watcher.common import clients\nfrom watcher.common import exception\nfrom watcher.datasource import gnocchi as gnocchi_helper\nfrom watcher.tests import base\n\nCONF = cfg.CONF\n\n\n@mock.patch.object(clients.OpenStackClients, 'gnocchi')\nclass TestGnocchiHelper(base.BaseTestCase):\n\n def test_gnocchi_statistic_aggregation(self, mock_gnocchi):\n gnocchi = mock.MagicMock()\n expected_result = 5.5\n\n expected_measures = [[\"2017-02-02T09:00:00.000000\", 360, 5.5]]\n\n gnocchi.metric.get_measures.return_value = expected_measures\n mock_gnocchi.return_value = gnocchi\n\n helper = gnocchi_helper.GnocchiHelper()\n result = helper.statistic_aggregation(\n resource_id='16a86790-327a-45f9-bc82-45839f062fdc',\n metric='cpu_util',\n granularity=360,\n start_time=timeutils.parse_isotime(\"2017-02-02T09:00:00.000000\"),\n stop_time=timeutils.parse_isotime(\"2017-02-02T10:00:00.000000\"),\n aggregation='mean'\n )\n self.assertEqual(expected_result, result)\n\n def test_gnocchi_wrong_datetime(self, mock_gnocchi):\n gnocchi = mock.MagicMock()\n\n expected_measures = [[\"2017-02-02T09:00:00.000000\", 360, 5.5]]\n\n gnocchi.metric.get_measures.return_value = expected_measures\n mock_gnocchi.return_value = gnocchi\n\n helper = gnocchi_helper.GnocchiHelper()\n self.assertRaises(\n exception.InvalidParameter, helper.statistic_aggregation,\n resource_id='16a86790-327a-45f9-bc82-45839f062fdc',\n metric='cpu_util',\n granularity=360,\n start_time=\"2017-02-02T09:00:00.000000\",\n stop_time=timeutils.parse_isotime(\"2017-02-02T10:00:00.000000\"),\n aggregation='mean')\n","sub_path":"watcher/tests/datasource/test_gnocchi_helper.py","file_name":"test_gnocchi_helper.py","file_ext":"py","file_size_in_byte":2452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"479514327","text":"from django.urls import path\nfrom .views import *\n\nurlpatterns = [\n path('', index, name='post_index'),\n path('post//', detail, name='post_detail'),\n path('post/new', new, name='post_new'),\n path('post//edit/', edit, name='post_edit'),\n path('post//delete/', delete, name='post_delete'),\n path('post/search/', search, name='post_search'),\n path('manage/', manage, name='blog_manage'),\n path('tag//', TaggedObjectLV.as_view(), name='tagged_post_list'),\n]","sub_path":"djangoProject/blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"9606800","text":"\n\n#calss header\nclass _ELBOW():\n\tdef __init__(self,): \n\t\tself.name = \"ELBOW\"\n\t\tself.definitions = [u'to push someone rudely with your elbows so that you can move or have more space: ', u'to hit someone with your elbow, sometimes as a sign to make them notice or remember something: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'verbs'\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/verbs/_elbow.py","file_name":"_elbow.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"600881777","text":"import os\nimport numpy as np\nimport tensorflow as tf\nfrom PIL import Image\n\nimport util\n\nclass traffic_light_detector(object):\n def __init__(self, path, model=\"ssd_inception_v2_retrained_2806\"):\n #util.prepare_tensorflow_object_detection_api(path, model)\n self.predictor_fn = tf.contrib.predictor.from_saved_model(\n export_dir=os.path.join(path, model, \"saved_model\"),\n signature_def_key=\"serving_default\")\n\n def filter_boxes(self, min_score, boxes, scores, classes):\n \"\"\"Return boxes with a confidence >= `min_score`\"\"\"\n n = len(classes)\n idxs = []\n for i in range(n):\n # the class id of traffic lights is 1\n if scores[i] >= min_score and classes[i] == 1:\n idxs.append(i)\n\n filtered_boxes = boxes[idxs, ...]\n filtered_scores = scores[idxs, ...]\n filtered_classes = classes[idxs, ...]\n return filtered_boxes, filtered_scores, filtered_classes\n\n def to_image_coords(self, boxes, height, width):\n \"\"\"\n The original box coordinate output is normalized, i.e [0, 1].\n\n This converts it back to the original coordinate based on the image\n size.\n \"\"\"\n box_coords = np.zeros_like(boxes)\n box_coords[:, 0] = boxes[:, 0] * height\n box_coords[:, 1] = boxes[:, 1] * width\n box_coords[:, 2] = boxes[:, 2] * height\n box_coords[:, 3] = boxes[:, 3] * width\n return box_coords\n\n def predict(self, image, confidence_cutoff=0.4):\n image_np = np.expand_dims(np.asarray(image, dtype=np.uint8), 0)\n result = self.predictor_fn({'inputs': image_np})\n boxes = np.squeeze(result[\"detection_boxes\"])\n scores = np.squeeze(result[\"detection_scores\"])\n classes = np.squeeze(result[\"detection_classes\"])\n boxes, scores, classes = self.filter_boxes(confidence_cutoff,\n boxes, scores, classes)\n\n #width, height = image.size\n height = image.shape[0]\n width = image.shape[1]\n box_coords = self.to_image_coords(boxes, height, width)\n return box_coords, classes\n","sub_path":"ros/src/tl_detector/light_classification/tl_detection/detector.py","file_name":"detector.py","file_ext":"py","file_size_in_byte":2158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"273633664","text":"\n\n#calss header\nclass _MINT():\n\tdef __init__(self,): \n\t\tself.name = \"MINT\"\n\t\tself.definitions = [u'Mint stamps and coins, etc. have not been used: ', u'perfect, as if new: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'adjectives'\n\n\n\tdef run(self, obj1, obj2):\n\t\tself.jsondata[obj2] = {}\n\t\tself.jsondata[obj2]['properties'] = self.name.lower()\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/adjectives/_mint.py","file_name":"_mint.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"429712546","text":"with open(\"macacos-me-mordam.txt\",\"r\") as arquivo:\n conteudo = arquivo.read()\nlista= conteudo.split(\" \")\ni=0\nsoma= 0\nwhile i>>>>>>>>>>>>\", e)\n return str(e)\n return SUCCESS_CODE\n","sub_path":"code/deletions.py","file_name":"deletions.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"301659635","text":"# -*- coding: utf-8 -*-\n\nimport psycopg2\nimport time\nimport os\n\nclass DBdriver():\n # conn = psycopg2.connect(\"host='localhost' dbname='testdb' user='pythonspot' password='111111'\")\n conn = psycopg2.connect(os.environ['DATABASE_URL'], sslmode='require')\n conn.set_client_encoding('UTF8')\n cur = conn.cursor()\n table_name = None\n\n def read_all(self):\n sql = \"SELECT * FROM %s\" % self.table_name\n self.cur.execute(sql)\n print(self.table_name)\n for i in self.cur.fetchall():\n print(i)\n\n def _select(self, sql, data):\n self.cur.execute(sql, data)\n return [i for i in self.cur.fetchall()]\n\n def rollback(self):\n self.conn.rollback()\n\n def delete(self, id):\n sql = \"DELETE FROM \" + self.table_name + \" CASCADE WHERE id=\" + str(id)\n try:\n self.cur.execute(sql)\n self.conn.commit()\n except Exception as err:\n self.rollback()\n return str(err)\n return ''\n\n def _insert(self, sql, data):\n try:\n self.cur.execute(sql, data)\n self.conn.commit()\n except Exception as err:\n self.rollback()\n return str(err)\n return ''\n\n def _update(self, sql, data):\n try:\n self.cur.execute(sql, data)\n self.conn.commit()\n except Exception as err:\n self.rollback()\n return str(err)\n return ''\n\n\nclass Users(DBdriver):\n table_name = 'users'\n\n def __init__(self):\n sql = \"CREATE TABLE IF NOT EXISTS \"+self.table_name+\"(id SERIAL PRIMARY KEY, login VARCHAR(20) UNIQUE, passwd VARCHAR(20),\" \\\n \" token VARCHAR(20), status VARCHAR(20))\"\n self.cur.execute(sql)\n self.conn.commit()\n\n def insert(self, data):\n sql = \"INSERT INTO users (login, passwd, token, status) VALUES(%s, %s, %s, %s)\"\n data = (data.get('login'), data.get('passwd'), data.get('token'), data.get('status'))\n return super()._insert(sql, data)\n\n\nclass Modules(DBdriver):\n table_name = 'modules'\n\n def __init__(self):\n sql = \"CREATE TABLE IF NOT EXISTS \"+self.table_name+\"(id SERIAL PRIMARY KEY, user_id INTEGER, language_from VARCHAR(20),\" \\\n \" language_to VARCHAR(20), module VARCHAR(20) UNIQUE, show_module BOOLEAN, module_comment TEXT, \" \\\n \"FOREIGN KEY (user_id) REFERENCES users(id))\"\n self.cur.execute(sql)\n self.conn.commit()\n\n def insert(self, requestform, user_id):\n sql = \"INSERT INTO modules(user_id, language_from, language_to, module, show_module, module_comment)\" \\\n \"VALUES (%s, %s, %s, %s, %s, %s)\"\n data = (user_id, requestform.get('language_from'), requestform.get('language_to'), requestform.get('module'), \\\n requestform.get('show_module'), requestform.get('module_comment'))\n return super()._insert(sql, data)\n\n def update(self, status, module_id):\n sql = \"UPDATE modules SET show_module = %s WHERE id = %s\"\n data = (status, module_id)\n return super()._update(sql, data)\n\n\n def select_by_user(self, user_id):\n if user_id:\n sql = \"SELECT * FROM modules WHERE user_id = %s\"\n data = (user_id,)\n res = super()._select(sql, data)\n return res\n else:\n return 'Error user_id is empty'\n\n def select_by_language(self, language_from, language_to):\n sql = \"SELECT * FROM modules WHERE language_from = %s AND language_to = %s\"\n data = (language_from, language_to)\n res = super()._select(sql, data)\n return res\n\nclass Lessons(DBdriver):\n table_name = 'lessons'\n\n def __init__(self):\n sql = \"CREATE TABLE IF NOT EXISTS \"+self.table_name+\"(id SERIAL PRIMARY KEY, module_id INTEGER REFERENCES modules\" \\\n \" ON DELETE CASCADE, lesson VARCHAR(20) UNIQUE,\" \\\n \" show_lesson BOOLEAN, lesson_comment TEXT, FOREIGN KEY (module_id) REFERENCES modules (id))\"\n self.cur.execute(sql)\n self.conn.commit()\n\n def insert(self, formdata):\n sql = \"INSERT INTO lessons(module_id, lesson, show_lesson, lesson_comment) VALUES (%s, %s, %s, %s)\"\n data = (formdata.get('module_id'), formdata.get('lesson'), formdata.get('show_lesson'), formdata.get('lesson_comment'))\n return super()._insert(sql, data)\n\n def select_by_module(self, module_id):\n sql = \"SELECT * FROM lessons WHERE module_id = %s\"\n data = (module_id,)\n return super()._select(sql, data)\n\n def update(self, status, lesson_id):\n sql = \"UPDATE lessons SET show_lesson = %s WHERE id = %s\"\n data = (status, lesson_id)\n return super()._update(sql, data)\n\n\nclass Words(DBdriver):\n table_name = 'words'\n\n def __init__(self):\n sql = \"CREATE TABLE IF NOT EXISTS words(id SERIAL PRIMARY KEY, lesson_id INTEGER, word VARCHAR(20),\" \\\n \" translate VARCHAR(20), word_comment TEXT, FOREIGN KEY (lesson_id) REFERENCES lessons (id))\"\n self.cur.execute(sql)\n self.conn.commit()\n\n def insert(self, data):\n sql = \"INSERT INTO words(lesson_id, word, translate, word_comment) VALUES (%s, %s, %s, %s)\"\n sql_data = (data.get('lesson_id'), data.get('word'), data.get('translate'), data.get('word_comment'))\n print(sql)\n return super()._insert(sql, sql_data)\n\n def update(self, data):\n sql = \"UPDATE words SET word = %s, translate = %s, word_comment = %s, WHERE id = %s\"\n sql_data = (data['word'], data['translate'], data['id'], data['word_comment'])\n return super()._update(sql, sql_data)\n\n def select_by_lesson(self, lesson_id):\n sql = \"SELECT * FROM words WHERE lesson_id = %s\"\n data = (lesson_id,)\n return super()._select(sql, data)\n\n\nclass Answers(DBdriver):\n table_name = 'answers'\n\n def __init__(self):\n sql = \"CREATE TABLE IF NOT EXISTS answers(id SERIAL PRIMARY KEY, user_id INTEGER, lesson_id INTEGER, word_id INTEGER,\" \\\n \"answer VARCHAR(20), date VARCHAR(40), FOREIGN KEY (user_id) REFERENCES users (id))\"\n self.cur.execute(sql)\n self.conn.commit()\n\n def insert(self, data, user_id):\n sql = \"INSERT INTO answers(user_id, lesson_id, word_id, answer, date) VALUES (%s, %s, %s, %s, %s)\"\n data = (user_id, data.get('lesson_id'), data.get('word_id'), data.get('answer'), time.asctime())\n return super()._insert(sql, data)\n\n def read_by_lesson(self, lesson_id):\n sql = \"SELECT * FROM answers WHERE lesson_id = %s\"\n data = (lesson_id,)\n return super()._select(sql, data)\n","sub_path":"BackendJSON/DatabaseDriver.py","file_name":"DatabaseDriver.py","file_ext":"py","file_size_in_byte":6685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"325800756","text":"import fnmatch\nimport re\nimport itertools\n\nfrom .. import config\nfrom ..types import Origin\nfrom ..dao.containerutil import FileReference, create_containerreference_from_filereference, create_filereference_from_dictionary\nfrom ..web.errors import APIValidationException, InputValidationException\n\nfrom . import gears\nfrom .jobs import Job\nfrom .mappers import RulesMapper\nfrom .queue import Queue\n\nlog = config.log\n\n# {\n# '_id': 'SOME_ID',\n# 'project_id': 'SOME_PROJECT',\n\n# Algorithm to run if all sets of rules match\n# 'alg': 'my-gear-name',\n#\n# At least one match from this array must succeed, or array must be empty\n# 'any': [],\n#\n# There should be no matches in this array\n# 'not': [],\n#\n# All matches from array must succeed, or array must be empty\n# 'all': [\n# {\n# 'type': 'file.type', # Match the file's type\n# 'value': 'dicom'\n# },\n# {\n# 'type': 'file.name', # Match a shell glob for the file name\n# 'value': '*.dcm'\n# },\n# {\n# 'type': 'file.modality', # Match the file's modaliy\n# 'value': 'MR'\n# },\n# {\n# 'type': 'file.classification', # Match any of the file's classification\n# 'value': 'diffusion'\n# },\n# {\n# 'type': 'container.has-type', # Match the container having any file (including this one) with this type\n# 'value': 'bvec'\n# },\n# {\n# 'type': 'container.has-classification', # Match the container having any file (including this one) with this classification\n# 'value': 'functional'\n# }\n# ]\n# }\n\n\ndef get_base_rules():\n \"\"\"\n Fetch the install-global gear rules from the database\n \"\"\"\n\n # rule_doc = config.db.singletons.find_one({'_id': 'rules'}) or {}\n # return rule_doc.get('rule_list', [])\n return []\n\ndef _log_file_key_error(file_, container, error):\n log.warning('file ' + file_.get('name', '?') + ' in container ' + str(container.get('_id', '?')) + ' ' + error)\n\ndef eval_match(match_type, match_param, file_, container, regex=False):\n \"\"\"\n Given a match entry, return if the match succeeded.\n \"\"\"\n\n def match(value):\n if regex:\n return re.match(match_param, value, flags=re.IGNORECASE) is not None\n elif match_type == 'file.name':\n return fnmatch.fnmatch(value.lower(), match_param.lower())\n else:\n return match_param.lower() == value.lower()\n\n # Match the file's type\n if match_type == 'file.type':\n file_type = file_.get('type')\n if file_type:\n return match(file_type)\n else:\n _log_file_key_error(file_, container, 'has no type')\n return False\n\n # Match the file's modality\n if match_type == 'file.modality':\n file_modality = file_.get('modality')\n if file_modality:\n return match(file_modality)\n else:\n return False\n\n # Match a shell glob for the file name\n elif match_type == 'file.name':\n return match(file_['name'])\n\n # Match any of the file's classification\n elif match_type == 'file.classification':\n if match_param:\n classification_values = list(itertools.chain.from_iterable(file_.get('classification', {}).itervalues()))\n return any(match(value) for value in classification_values)\n else:\n return False\n\n # Match the container having any file (including this one) with this type\n elif match_type == 'container.has-type':\n for c_file in container['files']:\n c_file_type = c_file.get('type')\n if c_file_type and match(c_file_type):\n return True\n\n return False\n\n # Match the container having any file (including this one) with this classification\n elif match_type == 'container.has-classification':\n if match_param:\n for c_file in container['files']:\n classification_values = list(itertools.chain.from_iterable(c_file.get('classification', {}).itervalues()))\n if any(match(value) for value in classification_values):\n return True\n\n return False\n\n raise Exception('Unimplemented match type ' + match_type)\n\ndef eval_rule(rule, file_, container):\n \"\"\"\n Decide if a rule should spawn a job.\n \"\"\"\n\n # Are there matches in the 'not' set?\n for match in rule.not_:\n if eval_match(match['type'], match['value'], file_, container, regex=match.get('regex')):\n return False\n\n # Are there matches in the 'any' set?\n must_match = len(rule.any_) > 0\n has_match = False\n\n for match in rule.any_:\n if eval_match(match['type'], match['value'], file_, container, regex=match.get('regex')):\n has_match = True\n break\n\n # If there were matches in the 'any' array and none of them succeeded\n if must_match and not has_match:\n return False\n\n # Are there matches in the 'all' set?\n for match in rule.all_:\n if not eval_match(match['type'], match['value'], file_, container, regex=match.get('regex')):\n return False\n\n return True\n\ndef queue_job_legacy(gear_id, input_, fixed_inputs=None):\n \"\"\"\n Tie together logic used from the no-manifest, single-file era.\n Takes a single FileReference instead of a map.\n \"\"\"\n\n gear = gears.get_gear(gear_id)\n gear = gears.filter_optional_inputs(gear)\n fixed_input_keys = [fixed_input['input'] for fixed_input in fixed_inputs] if fixed_inputs else []\n\n if gears.count_file_inputs(gear) - len(fixed_input_keys) != 1:\n # This shouldn't happen if the handler is correctly validating the POST and PUT methods for rules\n log.error(\"Legacy gear enqueue attempt of \" + gear_id + \" failed: must have exactly 1 non-fixed input from the manifest, it has {} non-fixed inputs\".format(gears.count_file_inputs(gear) - len(fixed_input_keys)))\n return\n\n for x in gear['gear']['inputs'].keys():\n if gear['gear']['inputs'][x]['base'] == 'file' and x not in fixed_input_keys:\n input_name = x\n\n inputs = {\n input_name: input_\n }\n\n if fixed_inputs:\n for fixed_input in fixed_inputs:\n inputs[fixed_input['input']] = FileReference(type=fixed_input['type'], id=str(fixed_input['id']),\n name=fixed_input['name'])\n\n gear_name = gear['gear']['name']\n destination = create_containerreference_from_filereference(input_)\n job = Job(gear, inputs, destination=destination, tags=['auto', gear_name])\n return job\n\ndef find_type_in_container(container, type_):\n for c_file in container['files']:\n if type_ == c_file['type']:\n return c_file\n return None\n\ndef create_potential_jobs(db, container, container_type, file_, rule_failure_callback=None):\n \"\"\"\n Check all rules that apply to this file, and creates the jobs that should be run.\n Jobs are created but not enqueued.\n Returns list of potential job objects containing job ready to be inserted and rule.\n rule_failure_callback will be called for each rule evauation that fails for any reason\n \"\"\"\n\n potential_jobs = []\n\n # Skip if virus scan feature enabled and the file is quarantined\n if config.get_feature('virus_scan', False):\n virus_scan_state = file_.get('virus_scan', {}).get('state')\n if virus_scan_state and virus_scan_state != 'clean':\n log.info('Skipping rule evaluation for %s: %s %s - file is not clean',\n container_type, container['_id'], file_['name'])\n return []\n\n # Get configured rules for this project\n rules = get_rules_for_container(db, container)\n\n # Add hardcoded rules that cannot be removed or changed\n for hardcoded_rule in get_base_rules():\n rules.append(hardcoded_rule)\n\n for rule in rules:\n try:\n if eval_rule(rule, file_, container):\n gear_id = rule.gear_id\n\n input_ = FileReference(type=container_type, id=str(container['_id']), name=file_['name'])\n job = queue_job_legacy(gear_id, input_, fixed_inputs=rule.fixed_inputs)\n\n if 'config' in rule:\n job.config = rule.config\n\n if 'compute_provider_id' in rule:\n job.compute_provider_id = rule['compute_provider_id']\n\n if 'compute_provider_id' in rule:\n job.compute_provider_id = rule['compute_provider_id']\n\n potential_jobs.append({\n 'job': job,\n 'rule': rule.to_dict()\n })\n except Exception as exc_val: # pylint: disable=broad-except\n log.exception('Unable to evaluate rule %s(name=%s)', rule['_id'], rule.get('name'))\n if rule_failure_callback:\n rule_failure_callback(rule, exc_val)\n\n return potential_jobs\n\ndef create_jobs(db, container_before, container_after, container_type, replaced_files=None, rule_failure_callback=None):\n \"\"\"\n Given a before and after set of file attributes, enqueue a list of jobs that would only be possible\n after the changes.\n Returns the algorithm names that were queued.\n \"\"\"\n if container_type == 'collection':\n return []\n\n # A list of FileContainerReferences that have been completely replaced\n # Jobs with these as inputs should get enqueue even if they are in the jobs_before list\n if not replaced_files:\n replaced_files = []\n\n jobs_before, jobs_after, potential_jobs = [], [], []\n\n files_before = container_before.get('files', [])\n files_after = container_after.get('files', [])\n\n for f in files_before:\n jobs_before.extend(create_potential_jobs(db, container_before, container_type, f, rule_failure_callback=rule_failure_callback))\n\n for f in files_after:\n jobs_after.extend(create_potential_jobs(db, container_after, container_type, f, rule_failure_callback=rule_failure_callback))\n\n # Using a uniqueness constraint, create a list of the set difference of jobs_after \\ jobs_before\n # (members of jobs_after that are not in jobs_before)\n for ja in jobs_after:\n replaced_file_name = ''\n\n replaced_file_in_job_inputs = False\n list_of_inputs = [i for i in ja['job'].inputs.itervalues()]\n for replaced_file in replaced_files:\n if replaced_file in list_of_inputs:\n replaced_file_name = replaced_file.name\n replaced_file_in_job_inputs = True\n break\n\n if replaced_file_in_job_inputs:\n # one of the replaced files is an input\n log.info('Scheduling job for %s=%s via rule=<%s>, replaced_file=<%s>.',\n container_type, container_before['_id'], ja['rule'].get('name'), replaced_file_name)\n potential_jobs.append(ja)\n else:\n should_enqueue_job = True\n for jb in jobs_before:\n if ja['job'].intention_equals(jb['job']):\n log.info('Ignoring rule: <%s> for %s=%s - Job has already been queued!',\n ja['rule'].get('name'), container_type, container_before['_id'])\n should_enqueue_job = False\n break # this job matched in both before and after, ignore\n if should_enqueue_job:\n log.info('Scheduling job for %s=%s via rule=<%s>.',\n container_type, container_before['_id'], ja['rule'].get('name'))\n potential_jobs.append(ja)\n\n\n spawned_jobs = []\n origin ={\n 'type': str(Origin.system),\n 'id': None\n }\n\n for pj in potential_jobs:\n job_map = pj['job'].map()\n try:\n # This can raise if we somehow ended up with an invalid provider\n job = Queue.enqueue_job(job_map, origin)\n job.insert()\n spawned_jobs.append(pj['rule']['gear_id'])\n except Exception as exc_val: # pylint: disable=broad-except\n rule = pj.get('rule', {})\n log.exception('Unable to evaluate rule %s(name=%s)', rule.get('_id'), rule.get('name'))\n if rule_failure_callback:\n rule_failure_callback(rule, exc_val)\n\n return spawned_jobs\n\n\n# TODO: consider moving to a module that has a variety of hierarchy-management helper functions\ndef get_rules_for_container(db, container):\n \"\"\"\n Recursively walk the hierarchy until the project object is found.\n \"\"\"\n\n if 'session' in container:\n session = db.sessions.find_one({'_id': container['session']})\n return get_rules_for_container(db, session)\n elif 'project' in container:\n project = db.projects.find_one({'_id': container['project']})\n return get_rules_for_container(db, project)\n else:\n rules_mapper = RulesMapper()\n # Assume container is a project, or a collection (which currently cannot have a rules property)\n result = list(rules_mapper.find_all(project_id=str(container['_id']), disabled={'$ne': True}))\n\n if not result:\n return []\n else:\n return result\n\ndef copy_site_rules_for_project(project_id):\n \"\"\"\n Copy and insert all site-level rules for project.\n\n Note: Assumes project exists and caller has access.\n \"\"\"\n\n rules_mapper = RulesMapper()\n site_rules = rules_mapper.find_all(project_id='site')\n\n for rule in site_rules:\n rule_copy = rule.copy()\n rule_copy.project_id = str(project_id)\n rules_mapper.insert(rule_copy)\n\n\ndef validate_regexes(rule):\n invalid_patterns = set()\n for match in rule.get('all', []) + rule.get('any', []) + rule.get('not', []):\n if match.get('regex'):\n pattern = match['value']\n try:\n re.compile(pattern)\n except re.error:\n invalid_patterns.add(pattern)\n if invalid_patterns:\n raise APIValidationException(\n reason='Cannot compile regex patterns',\n patterns=sorted(invalid_patterns)\n )\n\n\ndef validate_auto_update(rule_config, gear_id, update_gear_is_latest, current_gear_is_latest, fixed_inputs):\n if rule_config:\n raise InputValidationException(\"Gear rule cannot be auto-updated with a config\")\n if fixed_inputs:\n raise InputValidationException(\"Gear rule cannot be auto-updated with fixed inputs\")\n # Can only change gear_id to latest id\n # (Really only happens if updating auto_update and gear_id at once)\n elif gear_id:\n if not update_gear_is_latest:\n raise InputValidationException(\"Cannot manually change gear version of gear rule that is auto-updated\")\n elif not current_gear_is_latest:\n raise InputValidationException(\"Gear rule cannot be auto-updated unless it is uses the latest version of the gear\")\n\n\ndef validate_fixed_inputs(geardoc, fixed_inputs):\n \"\"\"\n Validates the fixed inputs for a rule given a gear doc\n The fixed inputs must:\n - add up to one less than the number of required gear inputs\n - all be valid inputs for the gear\n - exist\n \"\"\"\n fixed_inputs = fixed_inputs if fixed_inputs else []\n if gears.count_file_inputs(gears.filter_optional_inputs(geardoc)) - len(fixed_inputs) != 1:\n raise InputValidationException(\"Rule must have exactly 1 non-fixed gear value\")\n for fixed_input in fixed_inputs:\n if not geardoc['gear']['inputs'].get(fixed_input['input']):\n raise InputValidationException(\"Unrecognized gear input cannot be fixed for the rule\")\n # Check to see that each fixed input actually exists\n create_filereference_from_dictionary(fixed_input).get_file()\n\n","sub_path":"api/jobs/rules.py","file_name":"rules.py","file_ext":"py","file_size_in_byte":15822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"298812714","text":"from bombanitio import eval_over\nfrom bombanitio import eval_kin\nfrom bombanitio import eval_nuc\nfrom bombanitio import eval_four\nfrom bombanitio import eval_dipole\nfrom bombanitio import read_xyz\nfrom bombanitio import create_basis\nfrom bombanitio import scf\nimport pytest\nimport numpy as np\n\n\ndef test_form_g_mat():\n #dens_xxx_01 fock_xxx_01 coord_xxx_01.xyz\n orca_dens = np.loadtxt(\"../data/dens_xxx_02\")\n orca_fock = np.loadtxt(\"../data/fock_xxx_02\")\n orca_fock2 = np.zeros(orca_fock.shape)\n orca_dens2 = np.zeros(orca_dens.shape)\n \n dict1 = {}\n dict1[0] = 0\n dict1[1] = 1\n dict1[2] = 4\n dict1[3] = 2\n dict1[4] = 3\n dict1[5] = 5\n dict1[6] = 6\n\n for i in range(orca_fock2.shape[0]):\n for j in range(orca_fock2.shape[1]):\n #k = i \n #l = j\n #if i =\n orca_fock2[dict1[i], dict1[j]] = orca_fock[i,j]\n orca_dens2[dict1[i], dict1[j]] = orca_dens[i,j]\n p = orca_dens2 \n #p =np.array([[2.10625, -0.44603, 0.00000, 0.10859, 0.00000, -0.02843, -0.02843],\n # [-0.44603, 1.96730, 0.00000,-0.61771, 0.00000, -0.03406, -0.03406],\n # [0.00000, 0.00000, 0.73554, 0.00000, 0.00000, 0.53974, -0.53974],\n # [0.10859, -0.61771, 0.00000, 1.24023, 0.00000, 0.47272, 0.47272],\n # [0.00000, 0.00000, 0.00000, 0.00000, 2.00000, 0.00000, 0.00000],\n # [-0.02843,-0.03406, 0.53974, 0.47272, 0.00000, 0.60093, -0.19120],\n # [-0.02843,-0.03406,-0.53974, 0.47272, 0.00000, -0.19120, 0.60093]])\n coord, atom = read_xyz.easy_read(\"../data/coord_xxx_02.xyz\", None, False, False)\n coord = coord[0,:,:]\n coord = read_xyz.xyz_to_bohr(coord)\n zoa = read_xyz.atom_to_zoa(atom)\n noa = atom.shape[0]\n #basisset(noa, zoa, coord) \n noo, orb_coord, orb_type, coef_mat, exp_mat = create_basis.basisset(noa, zoa, coord)\n #print(noo)\n #print(orb_coord)\n #print(orb_type)\n #print(coef_mat)\n #print(exp_mat)\n read_xyz.plot_initial_orbs(noo, orb_coord, orb_type, coef_mat, exp_mat)\n# print(coef_mat.dtype)\n\n over_mat = eval_over.get_overlap_mat(noo, orb_coord, orb_type, coef_mat, exp_mat)\n np.set_printoptions(precision=6, suppress=True)\n kin_mat = eval_kin.get_kin_mat(noo, orb_coord, orb_type, coef_mat, exp_mat)\n nuc_mat = eval_nuc.get_nuc_mat(noo, orb_coord, orb_type, coef_mat, exp_mat, coord, zoa)\n\n print(\"pre_noo:\", noo)\n four_mat = eval_four.get_four_mat(noo, orb_coord, orb_type, coef_mat, exp_mat)\n\n h = kin_mat + nuc_mat\n g = scf.formg(noo, four_mat, p)\n f = h + g\n #fock_ref = np.loadtxt(\"../data/fock.data\")\n #print()\n #print(f - fock_ref)\n #print()\n #print((f - fock_ref)/fock_ref)\n #print()\n #print(f )\n #print()\n #print(fock_ref)\n\n #../data/orca_dens_eq ../data/orca_fock_eq\n #assert f == pytest.approx(fock_ref, rel=1e-3, abs=1e-5)\n \n\n \n\n\n\n\n print(f - orca_fock2)\n print()\n #print((f - orca_fock2)/f)\n print()\n print(f)\n print()\n print(orca_fock2)\n assert f == pytest.approx(orca_fock2, rel=1e-3, abs=1e-4)\n assert p == pytest.approx(orca_dens2, rel=1e-3, abs=1e-4)\n","sub_path":"test/test_xxx_02.py","file_name":"test_xxx_02.py","file_ext":"py","file_size_in_byte":3120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"124694548","text":"import socketserver\n\n\nclass Nadador():\n def __init__(self, idade):\n self.idade = idade\n\n def classificacao(self):\n if self.idade < 5:\n return \"Não pode participar\"\n elif self.idade < 8:\n return \"infantil A\"\n elif self.idade < 11:\n return \"infantil B\"\n elif self.idade < 14:\n return \"juvenil A\"\n elif self.idade < 18:\n return \"juvenil B\"\n else:\n return \"adulto\"\n\n\nclass TCPHandler(socketserver.BaseRequestHandler):\n def handle(self):\n # Recebe uma string de um cliente e a divide nas variaveis apropriadas\n idade = self.request.recv(1024).decode('utf-8').split(',')\n\n # Cria um Funcionário e atualiza seu salário de acordo com o cargo\n data = Nadador(float(idade)).classificacao()\n\n self.request.sendall(data.encode(\"utf-8\"))\n\n\nif __name__ == '__main__':\n HOST, PORT = \"localhost\", 9992\n\n # Tenta criar um serivdor TCP\n with socketserver.TCPServer((HOST, PORT), TCPHandler) as server:\n # Roda eternamente\n server.serve_forever()\n","sub_path":"lista01/ex05.py","file_name":"ex05.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"392625262","text":"from django.conf import settings\nfrom django.contrib import messages\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.core.urlresolvers import reverse\nfrom django.shortcuts import render, redirect\nfrom django.views.generic import View\n\nfrom quizzes.models import Quiz\n\n\nclass AnswerSolveView(LoginRequiredMixin, View):\n\n def get(self, request, *args, **kwargs):\n\n hash_id = self.kwargs.get('slug')\n quiz = Quiz.objects.public().get(hash_id=hash_id)\n\n if request.user == quiz.user:\n return redirect(reverse(\"home\"))\n\n # if quiz is already submitted, redirect to result page\n if quiz in request.user.solve_quiz_set.public().filter(hash_id=hash_id):\n messages.add_message(\n request,\n messages.ERROR,\n settings.ANSWER_ALREADY_EXIST_ERROR_MESSAGE,\n )\n return redirect(\n reverse(\n \"quizzes:answer_result\",\n kwargs={\n 'slug': hash_id,\n }\n )\n )\n\n return render(\n request,\n \"answer/solve.html\",\n context={\n \"site_name\": \"typeYou\",\n \"quiz\": quiz,\n })\n","sub_path":"typeYou/quizzes/views/answer/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"499502194","text":"import numpy as np\nimport math\nfrom scipy.linalg import block_diag\nfrom mA import multipleA\nimport hat\nfrom for_gen import generator\n\n# QP constraints\ndef constraints(cur_state, xr, ddxr, x_tilt_current, x_tilt_m1, N, A, B, h2, D, L, T, switch_zmp, switch_input, thr_input, switch_state, thr_state,mu):\n n = A.shape[0]\n m = B.shape[1]\n\n #zmp matrix\n h = h2\n g = 9.81\n P = 1/(T*T)*np.array([ [1, 0, 0],\n [0, 1, 0],\n [0, 0, 0] ])\n\n ############################### backward finite difference for zmp ###############################\n if switch_zmp == 1:\n #G0{2*n*N, m*N} \n Bhat = np.zeros((N, n, m, N)) \n for b_hat_num in generator(1, N+1): \n #in writing Bi(k+j), in code Bj(k+i), \n #(1,2,3,4), 1:j, (2,3):B(:,:), 4:b_hat_num\n Bhat[b_hat_num-1, :, :, :b_hat_num] = hat.B_hat(A,B,cur_state, cur_state+b_hat_num) \n\n G01 = np.zeros((n*N, m*N))\n for i in generator(1, N+1): \n for j in generator(1, N+1): \n if i-j == 0: #diagonal \n G01[(i-1)*n : i*n, (j-1)*m : j*m] = np.matmul( P, Bhat[i-1,:,:,j-1] ) \n \n elif i-j == 1: #one lower than diagonal \n G01[(i-1)*n : i*n, (j-1)*m : j*m] = np.matmul( P, Bhat[i-1,:,:,j-1] ) + np.matmul( P, -2*Bhat[i-1-1,:,:,j-1] )\n\n elif i-j < 0: #upper diagonal is 0 \n G01[(i-1)*n : i*n, (j-1)*m : j*m] = 0\n\n else: #lower diagonal \n G01[(i-1)*n : i*n, (j-1)*m : j*m] = np.matmul(P, Bhat[i-1,:,:,j-1]) + np.matmul(P, -2*Bhat[i-1-1,:,:,j-1] + Bhat[i-1-2,:,:,j-1]) \n \n #G0 = np.append(G01,-G01, axis=0)\n G0 = G01.copy()\n\n #E0{2*n*N,n}\n E01 = np.zeros((n*N,n))\n for i in generator(1, N+1): \n if i == 1: \n E01[(i-1)*n : i*n,:] = np.matmul( P, hat.A_hat(A, cur_state, cur_state+i) ) + np.matmul( P, -2*np.eye(n) )\n \n elif i == 2:\n E01[(i-1)*n : i*n,:] = np.matmul( P, hat.A_hat(A, cur_state, cur_state+i) ) + np.matmul( P, -2*hat.A_hat(A,cur_state,cur_state+(i-1)) + np.eye(n) )\n\n else:\n E01[(i-1)*n : i*n,:] = np.matmul( P, hat.A_hat(A, cur_state, cur_state+i) ) + np.matmul( P, -2*hat.A_hat(A,cur_state,cur_state+(i-1)) + hat.A_hat(A,cur_state,cur_state+(i-2)) )\n\n #E0 = np.append(-E01, -(-E01), axis=0)\n E0 = -E01.copy()\n\n\n #W0{2*n*N,1}\n #w0 = np.zeros(2*n*N) \n w0u = np.zeros(n*N)\n w0l = np.zeros(n*N)\n for i in generator(1, N+1): \n w0u[(i-1)*n : i*n] = np.amin([ np.matmul(np.array([ [np.abs(np.cos(x_tilt_current[2]+xr[2,cur_state])), np.abs(np.sin(x_tilt_current[2]+xr[2,cur_state])), 0], \n [np.abs(np.sin(x_tilt_current[2]+xr[2,cur_state])), np.abs(np.cos(x_tilt_current[2]+xr[2,cur_state])), 0],\n [ 0, 0, 1] ]), np.array([D/2,L/2,0])*g/h), mu*g], axis=0) - np.array([ddxr[0,cur_state+i], ddxr[1,cur_state+i], 0])\n \n for i in generator(1, N+1): \n w0l[(i-1)*n : i*n] = - np.amin([ np.matmul(np.array([ [np.abs(np.cos(x_tilt_current[2]+xr[2,cur_state])), np.abs(np.sin(x_tilt_current[2]+xr[2,cur_state])), 0], \n [np.abs(np.sin(x_tilt_current[2]+xr[2,cur_state])), np.abs(np.cos(x_tilt_current[2]+xr[2,cur_state])), 0],\n [ 0, 0, 1] ]), np.array([D/2,L/2,0])*g/h), mu*g], axis=0) - np.array([ddxr[0,cur_state+i], ddxr[1,cur_state+i], 0])\n\n w0u = w0u - np.append(np.matmul(P, x_tilt_m1), np.zeros(n*(N-1)), axis=0)\n w0l = w0l - np.append(np.matmul(P, x_tilt_m1), np.zeros(n*(N-1)), axis=0) \n #w0 = np.append(w01, w02, axis=0) \n ############################################################## \n \n else:\n G0 = np.array([])\n E0 = np.array([])\n w0u = np.array([])\n w0l = np.array([])\n \n #############################################################################################\n\n ############################### state limit ###############################\n if switch_state == 1:\n #state limit\n E22 = np.zeros((n*N,n))\n for i in generator(1, N+1): \n E22[(i-1)*n : i*n,:] = multipleA(A, cur_state, cur_state + (i-1)) \n\n #E2 = np.append(-E22, -(-E22), axis=0)\n E2 = -E22.copy()\n\n G22 = np.zeros((n*N, m*N)) \n Bhat = np.zeros((N, n, m, N)) \n for i in generator(1, N+1): \n #in writing Bi(k+j), in code Bj(k+i), \n #(1,2,3,4), 1:j, (2,3):B(:,:), 4:b_hat_num\n Bhat[i-1, :, :, :i] = hat.B_hat(A,B,cur_state, cur_state+i) \n for j in generator(1, i+1): \n G22[(i-1)*n : i*n, (j-1)*m : j*m] = Bhat[i-1,:,:,j-1]\n \n #G2 = np.append(G22, -G22, axis=0)\n G2 = G22.copy()\n \n w2u = np.zeros(n*N)\n w2l = np.zeros(n*N)\n for i in generator(1, N+1):\n w2u[(i-1)*n : i*n] = thr_state[:3]\n \n for i in generator(1, N+1):\n w2l[(i-1)*n : i*n] = -thr_state[3:]\n \n #w2 = np.append(w21, w22, axis=0)\n else:\n G2 = np.array([])\n E2 = np.array([])\n w2u = np.array([])\n w2l = np.array([])\n \n #############################################################################################\n\n ############################### input limit ###############################\n if switch_input == 1:\n #input limit \n w1u = thr_input[:3]\n w1l = -thr_input[3:]\n for i in generator(2, N+1): \n w1u = np.append(w1u, thr_input[:3], axis=0)\n w1l = np.append(w1l, -thr_input[3:], axis=0)\n\n else: \n w1u = np.array([])\n w1l = np.array([])\n #############################################################################################\n\n #constraint completion\n G = np.append(G0, G2).reshape(-1,m*N)\n E = np.append(E0, E2).reshape(-1,n)\n wu = np.append(w0u, w2u).reshape(-1)\n wl = np.append(w0l, w2l).reshape(-1)\n wu_input = w1u\n wl_input = w1l \n\n return G, E, wu, wl, wu_input, wl_input\n\n","sub_path":"QP_constraints.py","file_name":"QP_constraints.py","file_ext":"py","file_size_in_byte":6868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"77535680","text":"#!/usr/bin/python3\n#/usr/local/bin/python3\n# Set the path to your python3 above\n\nfrom gtp_connection import GtpConnection\nfrom board_util import GoBoardUtil\nfrom simple_board import SimpleGoBoard\nimport numpy as np\nimport argparse\nimport sys\nimport operator\n\nclass Gomoku():\n def __init__(self,sim, sim_rule):\n \"\"\"\n Gomoku3 player that simulates move using flat monte carlo search\n and rules.\n \"\"\"\n self.name = \"GomokuAssignment3\"\n self.version = 1.0\n self.sim = sim\n self.random_simulation = True if sim_rule == 'random' else False\n\n\n def simulate(self,board):\n #Testing simulate with pseudocode with gtpconn.\n dictionaryWinCount = {}\n #DictionaryWinCount {Move:win}\n legal_moves = GoBoardUtil.generate_legal_moves_gomoku(board)\n numMoves = len(legal_moves)\n\n #Base case, if game is already won. We cannot simulate.\n gameCheck = board.check_game_end_gomoku()\n if gameCheck[0] == True:\n print(\"Game already won by\", gameCheck[1])\n return\n #Otherwise we iterate over the legal moves.\n for i in legal_moves:\n dictionaryWinCount[i] = 0\n #For each legal move.\n #Run this sim times.\n for j in range(sim):\n move = board._point_to_coord(i)\n \n #Need to implement simulateMove\n #print(i, move, board.current_player)\n win_count = self.simulateMove(i,board,board.current_player)\n #print(win_count)\n if(win_count > 0):\n dictionaryWinCount[i] += 1\n \n max_win = max(dictionaryWinCount.items(), key=operator.itemgetter(1))[0]\n print(dictionaryWinCount)\n #For i in dictionary;\n #Pick highest count. (Most winrate)\n \n #Return highest count move (\"Generate move.\")\n \n return max_win\n def simulateMove(self, move, board, color):\n boardToSimulate = board.copy()\n win_count = 0\n playerSimulationColor = board.current_player\n print(color)\n boardToSimulate.play_move_gomoku(move,color)\n gameCheck = boardToSimulate.check_game_end_gomoku()\n if gameCheck[0] == True:\n if gameCheck[1] == playerSimulationColor:\n #print(\"CurrentPlayerWon, adding in win\",gameCheck[1], color)\n win_count += 1\n\n while gameCheck[0] == False:\n legal_moves = GoBoardUtil.generate_legal_moves_gomoku(boardToSimulate)\n if len(legal_moves) == 0:\n break\n newMove = GoBoardUtil.generate_random_move_gomoku(boardToSimulate)\n boardToSimulate.play_move_gomoku(newMove, boardToSimulate.current_player)\n gameCheck = boardToSimulate.check_game_end_gomoku()\n print(gameCheck, GoBoardUtil.get_twoD_board(boardToSimulate),newMove)\n if gameCheck[0] == True:\n if gameCheck[1] == playerSimulationColor:\n #print(\"CurrentPlayerWon, adding in win\",gameCheck[1], color)\n win_count += 1\n break\n #Run simulation on board\n #if self.random_simulation == True:\n #first play the move*\n #then play random moves until no legal moves left.\n #check winner\n #if winner = current player, add to win_count\n \n return win_count\n def get_move(self, board, color):\n return GoBoardUtil.generate_random_move_gomoku(board)\n \ndef run(sim, sim_rule):\n \"\"\"\n start the gtp connection and wait for commands.\n \"\"\"\n board = SimpleGoBoard(7)\n con = GtpConnection(Gomoku(sim, sim_rule), board)\n con.start_connection()\n\n\ndef parse_args():\n \"\"\"\n Parse the arguments of the program.\n \"\"\"\n parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n #Default sim is 10. Otherwise can change it.\n parser.add_argument('--sim', type=int, default=10, help='number of simulations per move, so total playouts=sim*legal_moves')\n parser.add_argument('--simrule', type=str, default='random', help='type of simulation policy: random or rulebased')\n args = parser.parse_args()\n sim = args.sim\n sim_rule = args.simrule\n\n if sim_rule != \"random\" and sim_rule != \"rulebased\":\n print('simrule must be random or rulebased')\n sys.exit(0)\n\n return sim, sim_rule\n \nif __name__=='__main__':\n sim, sim_rule = parse_args()\n run(sim,sim_rule)\n","sub_path":"Gomoku3.py","file_name":"Gomoku3.py","file_ext":"py","file_size_in_byte":4582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"439775424","text":"############# preprocess ###################################\n# class Vertex: \n# class Edge:\n# class Face:\n#\n# output configuration:\n# can output per vertex, per edge, or per face attributes.\n#\n#\n############################################################\nimport math\nimport os, sys\nimport numpy as np\nfrom numpy import linalg as LA\nimport math\nimport time\n\nMAXINT = 1000\n\n\nclass Vertex(): \n pos = []\n vel = []\n\n edgeList = []\n faceList = []\n\n def __init__(self, p):\n self.pos = p\n\n def add_vel(self, velocity):\n self.vel = velocity\n\n def add_edge(self, e):\n self.edgeList.append(e)\n\n def add_face(self, f):\n self.faceList.append(f)\n\n\nclass Edge():\n # vertex index\n idx1 = 0\n idx2 = 0\n tri_list = [] \n\n #ratio of edge length\n rest_length = 0.0\n length = 0.0\n deform_ratio = 0.0\n\n def __init__(self, id1, id2, tid, l):\n self.idx1 = id1 if id1 < id2 else id2\n self.idx2 = id2 if id1 < id2 else id1\n self.tri_list.append(tid)\n self.length = l\n\n def is_same_edge(self, e1):\n if e1.idx1 == self.idx1 and e1.idx2 == self.idx2:\n return True\n else:\n return False\n\n\n\nclass Face():\n tri_id = -1\n tri_vert = [] # three id\n tri_angles = [] # three edge objects\n tri_cos = []\n tri_area = 0.0\n\n # deformation data\n deform_grad = []\n deform_angle_ratio = []\n deform_cos_ratio = []\n \n def __init__(self, id0, id1, id2, a0, a1, a2, ca0, ca1, ca2, face_idx, area):\n self.tri_id = face_idx\n self.tri_vert = [id0, id1, id2]\n self.tri_angles = [a0, a1, a2]\n self.tri_cos = [ca0, ca1, ca2]\n self.tri_area = area\n\n\n# vert --> list of objects\n# edges --> dictionary (v1, v2) vertex index pair as key.\n# faces --> dictionary face_index as key.\n# store all the properties within a object\ndef obj_loader(file_name, rest_pos=[]):\n if not os.path.isfile(file_name):\n print(\"file not exist\")\n return\n\n vert = []\n edges = {}\n faces = {}\n\n face_idx = 0\n vert_idx = -1\n\n with open(file_name, \"r\") as f1:\n for line in f1:\n s = line.strip().split(' ')\n if s[0] == 'v':\n vert_idx += 1\n v = list(map(float, s[1:]))\n if rest_pos:\n v = list(map(operator.sub, v, rest_pos[vert_idx]))\n vert.append(Vertex(v))\n elif s[0] == 'nv':\n nv = list(map(float, s[1:]))\n vert[vert_idx].add_vel(nv)\n elif s[0] == 'f':\n id0 = int(s[1].strip().split('/')[0]) - 1 # index start at 0\n id1 = int(s[2].strip().split('/')[0]) - 1\n id2 = int(s[3].strip().split('/')[0]) - 1\n # add to the edge dictionary\n v = sorted([id0, id1, id2])\n # compute some properties\n p0 = vert[v[0]].pos \n p1 = vert[v[1]].pos\n p2 = vert[v[2]].pos \n # edge vectors\n v0 = np.array(p2) - np.array(p1) \n v1 = np.array(p0) - np.array(p2)\n v2 = np.array(p1) - np.array(p0)\n # edge distance\n dist0 = LA.norm(v0)\n dist1 = LA.norm(v1)\n dist2 = LA.norm(v2)\n # cos\n ca0 = LA.norm(np.dot(-v1, v2)) \n ca1 = LA.norm(np.dot(v0, -v2)) \n ca2 = LA.norm(np.dot(-v0, v1))\n # angle\n a0 = math.acos(ca0)\n a1 = math.acos(ca1)\n a2 = math.acos(ca2)\n # triangle area\n area = 0.5 * LA.norm(np.cross(v1, v2))\n\n # add edges\n if not edges.get((v[0], v[1])):\n edges[(v[0], v[1])] = Edge(v[0], v[1], face_idx, dist2)\n else:\n edges[(v[0], v[1])].tri_list.append(face_idx)\n \n if not edges.get((v[1], v[2])):\n edges[(v[1], v[2])] = Edge(v[1], v[2], face_idx, dist0)\n else:\n edges[(v[1], v[2])].tri_list.append(face_idx)\n \n if not edges.get((v[0], v[2])):\n edges[(v[0], v[2])] = Edge(v[0], v[2], face_idx, dist1)\n else:\n edges[(v[0], v[2])].tri_list.append(face_idx)\n \n # add to face list\n faces[face_idx] = Face(id0, id1, id2, a0, a1, a2, ca0, ca1, ca2, face_idx, area)\n face_idx += 1\n\n print(\"how many vertices? \", len(vert))\n print(\"how many edges? \", len(edges))\n print(\"how many faces? \", len(faces))\n\n return vert, edges, faces\n\n\n# get position array from Vertex object array\ndef get_pos(vert):\n pos = []\n for x in vert:\n pos.append(x.pos)\n return pos\n\n\n# call this after get the base info from rest pos\ndef update_deformation(edges, rest_edges, faces, rest_faces):\n for x in edges:\n x.rest_length = rest_edges.get(x.idx1, x.idx2).length\n x.ratio = x.length / x.rest_length\n\n # TODO\n # for x in faces:\n # x.deform_grad = \n # x.deform_angle_ratio =\n # x.deform_cos_ratio =\n \n\n\n\n\n# find the vertex that an edge is facing in a triangle\n# return vertex index\ndef vert_for_edge(tri, edge):\n vertices = tri.tri_vert\n for v in vertices:\n if edge.idx1 != v and edge.idx2 != v:\n return v\n\n\n# find other two edges in current triangle besides given edge\ndef other_two_edges(tri, e):\n e_list = tri.tri_edges\n other_e = []\n for item in e_list:\n if not is_same_edge(item, e):\n other_e.append(item)\n return other_e\n\n\n# input: vert & faces\n# output tri_nb: local vertices per row * tri_num\n# n: per tri info data, 3 for one triangle position only, 6 for triangle with one layer neighbor, x... with velocity etc...\ndef comp_mtx(vert, edges, faces, n=3):\n vert_num = len(vert)\n tri_num = len(faces)\n dim = [tri_num, vert_num]\n # print dim\n\n # mtx = np.array([np.zeros(tri_num*3) for item in range(vert_num)])\n mtx = np.array([np.zeros(tri_num * n) for item in range(vert_num)])\n count = np.zeros((vert_num, 1))\n # print \">>> mtx shape: \", mtx.shape\n\n # new_edges = []\n for i in range(0, tri_num):\n [id1, id2, id3] = faces[i].tri_vert\n # original vertex in index matrix\n mtx[id1][i * n] = 1\n mtx[id2][i * n + 1] = 1\n mtx[id3][i * n + 2] = 1\n count[id1][0] += 1.0\n count[id2][0] += 1.0\n count[id3][0] += 1.0\n\n # # for the neighbors, get shared edge and corresponding vertex\n # for j in range(0, len(faces[i].tri_edges)):\n # ed = faces[i].tri_edges[j]\n # # retrieve the tri_list for the dictionary\n # shared_tri = edges[(ed.idx1, ed.idx2)]\n # if len(shared_tri) > 1:\n # other_tri = shared_tri[1] if shared_tri[0] == i else shared_tri[0]\n # new_vert_id = vert_for_edge(faces[other_tri], ed)\n # # add to index matrix\n # # mtx[new_vert_id][i * 6 + 3 + j] = 1\n # mtx[new_vert_id][i * n + 3 + j] = 1\n # count[new_vert_id][0] += 1.0\n\n mtx_1 = mtx\n mtx = mtx_1 / count\n\n return dim, mtx, mtx_1\n\n\ndef find_neighbors(vert, edges, faces, n=1):\n vert_num = len(vert)\n tri_num = len(faces)\n tri_nb = [0] * tri_num\n # print(vert_num, tri_num, tri_nb) 700 x 1292\n # new_edges = []\n for i in range(0, tri_num):\n # print \"i:{}\".format(i)\n [id1, id2, id3] = faces[i].tri_vert\n # original vertex position\n tri_nb.extend(vert[id1])\n tri_nb.extend(vert[id2])\n tri_nb.extend(vert[id3])\n # while n > 0:\n # n = n - 1\n # add neighbors\n for j in range(0, len(faces[i].tri_edges)):\n ed = faces[i].tri_edges[j]\n # retrieve the tri_list for the dictionary\n shared_tri = edges[(ed.idx1, ed.idx2)]\n if len(shared_tri) > 1:\n other_tri = shared_tri[1] if shared_tri[0] == i else shared_tri[0]\n new_vert_id = vert_for_edge(faces[other_tri], ed)\n tri_nb.extend(vert[new_vert_id])\n # new_edges.extend(other_two_edges(faces[other_tri], ed))\n else:\n tri_nb.extend([0.0, 0.0, 0.0]) # zero padding\n\n return tri_nb\n\n\ndef meshmtx_wnb(file_name):\n vert = []\n vel = []\n edges = {}\n faces = {}\n\n obj_loader(file_name, vert, vel, edges, faces)\n dim, mtx, mtx_1 = comp_mtx(vert, edges, faces)\n\n return dim, mtx, mtx_1\n\n\n# config (string): \n# vert: pos, vel, \n# face: \ndef load_sample(file_name, batch_data, config, rest_pos=[]):\n \n vert = []\n edges = {}\n faces = {}\n obj_loader(file_name, vert, edges, faces, rest_pos)\n\n # tri_nb = find_neighbors(vert, edges, faces)\n # TODO\n if config[:4] == 'vert':\n pass\n elif config[:4] == 'face':\n pass\n \n\n batch_data.append(output)\n\n\n# =========================================================\n# Dijkstra \n# =========================================================\n\n# A utility function to find the vertex with \n# minimum distance value, from the set of vertices \n# not yet included in shortest path tree\ndef minDistance(num_v, dist, sptSet, src):\n\n # Initilaize minimum distance for next node\n min_dist_next = MAXINT\n min_index = -1\n\n # Search not nearest vertex not in the \n # shortest path tree\n for v in range(0, num_v):\n if dist[v] < min_dist_next and sptSet[v] == False:\n min_dist_next = dist[v]\n min_index = v\n\n return min_index\n \n\n# Funtion that implements Dijkstra's single source \n# shortest path algorithm for a graph represented \n# using adjacency matrix representation\n# returns an array of distance start from the src\ndef dijkstra(num_v, graph, src):\n dist = [MAXINT] * num_v\n dist[src] = 0\n sptSet = [False] * num_v # track visted notes\n\n # cout = 0\n while (False in sptSet):\n # cout += 1\n\n # Pick the minimum distance vertex from \n # the set of vertices not yet processed. \n # u is always equal to src in first iteration\n u = minDistance(num_v, dist, sptSet, src) # return vertex index\n # if u < 0:\n # print(\"Error: u < 0, cant find minDistance ??\")\n # continue;\n\n # Put the minimum distance vertex in the \n # shotest path tree\n sptSet[u] = True\n\n # Update dist value of the adjacent vertices \n # of the picked vertex only if the current \n # distance is greater than new distance and\n # the vertex in not in the shotest path tree\n for v in range(num_v):\n if graph[u, v] > 0 and sptSet[v] == False and dist[v] > dist[u] + graph[u][v]:\n dist[v] = dist[u] + graph[u][v]\n \n # print(\"dijkstra iteration: \", cout). #700\n return dist\n\n\n# compute geodesic matrix\ndef compute_geodesic_distance(num_v, edges):\n graph = np.zeros((num_v, num_v), dtype=np.float32)\n geo_dist = np.zeros((num_v, num_v), dtype=np.float32)\n\n # build the graph\n for k, e in edges.items():\n graph[e.idx1, e.idx2] = e.length # e.idx1 always less than e.idx2\n graph[e.idx2, e.idx1] = e.length\n\n\n # build geo_dist matrix\n t = time.clock()\n for i in range(0, num_v):\n if i % 50 == 0:\n print(i/num_v, \" % \")\n geo_dist[i, :] = dijkstra(num_v, graph, i)\n print (time.clock() - t, \"seconds to compute geodesic distance matrix.\")\n \n # debug\n # print(\"================ geo_dist ================\")\n # print(geo_dist[0, :])\n\n return geo_dist\n \n\n# mask matrix from vertex distance\ndef compute_mask(num_v, dist):\n dmin = 0.1\n dmax = 1.0 \n masking = np.zeros((num_v, num_v), dtype=np.float32)\n \n for i in range(num_v):\n for j in range(i, num_v):\n if dist[i, j] < dmin:\n w = 1.0\n elif dist[i, j] > dmax:\n w = 0.0\n else:\n w = (dmax - dist[i, j]) / (dmax - dmin) \n masking[i, j] = w\n masking[j, i] = w\n\n # normalize each row to 1\n for x in range(num_v):\n rs = np.sum(masking[x, :]) # sum of the row\n # print(\"sum of row \", x, \" >>> \", rs)\n masking[x, :] /= rs\n\n return masking\n\n\n","sub_path":"sc1/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":12489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"292412772","text":"# Copyright 2015 Infoblox Inc.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport abc\nimport netaddr\nimport six\n\nfrom infoblox_client import objects\nfrom networking_infoblox.neutron.common import constants as const\n\n\n@six.add_metaclass(abc.ABCMeta)\nclass IPAllocator(object):\n \"\"\"Base class for ip allocation actions\"\"\"\n\n DEFAULT_OPTIONS = {\n 'use_host_record': True,\n 'configure_for_dhcp': True,\n 'configure_for_dns': True,\n 'dns_record_binding_types': [],\n 'dns_record_unbinding_types': [],\n 'dns_record_removable_types': []}\n\n def __new__(cls, ib_obj_manager, options):\n cls._validate_and_set_default_options(options)\n return super(IPAllocator, cls).__new__(\n cls._get_ip_allocator_class(options))\n\n def __init__(self, ib_obj_manager, options):\n self.manager = ib_obj_manager\n self.opts = options\n\n @classmethod\n def _validate_and_set_default_options(cls, options):\n if not isinstance(options, dict):\n raise ValueError('Options should be passed as dict')\n for key in cls.DEFAULT_OPTIONS:\n if key not in options:\n options[key] = cls.DEFAULT_OPTIONS[key]\n\n @staticmethod\n def _get_ip_allocator_class(options):\n if options['use_host_record']:\n return HostRecordIPAllocator\n else:\n return FixedAddressIPAllocator\n\n @abc.abstractmethod\n def allocate_ip_from_range(self, network_view, dns_view, zone_auth,\n hostname, mac, first_ip, last_ip,\n extattrs=None):\n pass\n\n @abc.abstractmethod\n def allocate_given_ip(self, network_view, dns_view, zone_auth,\n hostname, mac, ip, extattrs=None):\n pass\n\n @abc.abstractmethod\n def deallocate_ip(self, network_view, dns_view_name, ip):\n pass\n\n @abc.abstractmethod\n def bind_names(self, network_view, dns_view, ip, name, extattrs):\n pass\n\n @abc.abstractmethod\n def unbind_names(self, network_view, dns_view, ip, name, extattrs):\n pass\n\n\nclass HostRecordIPAllocator(IPAllocator):\n\n def bind_names(self, network_view, dns_view, ip, name, extattrs):\n # Don't use network view for DNS hosts\n net_view = None\n if not self.opts['configure_for_dns']:\n dns_view = None\n net_view = network_view\n\n # See OPENSTACK-181. In case hostname already exists on NIOS, update\n # host record which contains that hostname with the new IP address\n # rather than creating a separate host record object\n reserved_hostname_hr = self.manager.find_hostname(\n dns_view, name, ip, net_view)\n reserved_ip_hr = self.manager.get_host_record(\n dns_view, ip, net_view)\n\n if (reserved_hostname_hr and reserved_ip_hr and\n reserved_hostname_hr.ref == reserved_ip_hr.ref):\n reserved_hostname_hr.extattrs = extattrs\n reserved_hostname_hr.update()\n return\n\n if reserved_hostname_hr:\n for hr_ip in reserved_ip_hr.ips:\n ip_mac = hr_ip.mac if hr_ip.ip_version == 4 else hr_ip.duid\n if hr_ip == ip:\n reserved_ip_hr.delete()\n reserved_hostname_hr.extattrs = extattrs\n self.manager.add_ip_to_record(\n reserved_hostname_hr, ip, ip_mac)\n break\n else:\n self.manager.bind_name_with_host_record(\n dns_view, ip, name, extattrs, net_view)\n\n def unbind_names(self, network_view, dns_view, ip, name, extattrs):\n # Nothing to delete, all will be deleted together with host record.\n pass\n\n def allocate_ip_from_range(self, network_view, dns_view,\n zone_auth, hostname, mac, first_ip, last_ip,\n extattrs=None):\n use_dhcp = self.opts['configure_for_dhcp']\n use_dns = self.opts['configure_for_dns']\n fqdn = hostname + '.' + zone_auth\n host_record = self.manager.find_hostname(\n dns_view, fqdn, first_ip)\n\n if host_record:\n hr = self.manager.add_ip_to_host_record_from_range(\n host_record, network_view, mac, first_ip, last_ip, use_dhcp)\n else:\n # First search hosts with same MAC and if exists address within\n # given range - use it instead of creating new one\n # https://bugs.launchpad.net/networking-infoblox/+bug/1628517\n hosts = self.manager.find_host_records_by_mac(dns_view,\n mac.lower(),\n network_view)\n if hosts:\n ip_range = netaddr.IPRange(first_ip, last_ip)\n ip_version = netaddr.IPAddress(first_ip).version\n for host in hosts:\n if host.ip_version != ip_version:\n continue\n for ip in host.ips:\n ip_mac = ip.mac if ip_version == 4 else ip.duid\n if ip_mac != mac:\n continue\n ip_addr = netaddr.IPAddress(ip.ip)\n if ip_addr in ip_range:\n self.manager.update_host_record_eas(dns_view,\n ip.ip,\n extattrs)\n return ip.ip\n hr = self.manager.create_host_record_from_range(\n dns_view, network_view, zone_auth, hostname, mac,\n first_ip, last_ip, extattrs, use_dhcp, use_dns)\n return hr.ip[-1].ip\n\n def allocate_given_ip(self, network_view, dns_view, zone_auth,\n hostname, mac, ip, extattrs=None):\n use_dhcp = self.opts['configure_for_dhcp']\n use_dns = self.opts['configure_for_dns']\n # First search hosts with same MAC and if exists address with\n # same IP - use it instead of creating new one\n # https://bugs.launchpad.net/networking-infoblox/+bug/1628517\n ip_obj = objects.IP.create(ip=ip, mac=mac)\n ip_version = ip_obj.ip_version\n ip_mac = ip_obj.mac if ip_version == 4 else ip_obj.duid\n\n hosts = self.manager.find_host_records_by_mac(dns_view,\n ip_mac,\n network_view)\n if hosts:\n for host in hosts:\n if host.ip_version != ip_version:\n continue\n for host_ip in host.ips:\n host_ip_mac = (\n host_ip.mac if ip_version == 4 else host_ip.duid)\n if host_ip_mac != ip_mac:\n continue\n if host_ip.ip == ip:\n self.manager.update_host_record_eas(dns_view,\n host_ip.ip,\n extattrs)\n return host_ip.ip\n hr = self.manager.create_host_record_for_given_ip(\n dns_view, zone_auth, hostname, mac, ip, extattrs, use_dhcp,\n use_dns)\n return hr.ip[-1].ip\n\n def deallocate_ip(self, network_view, dns_view_name, ip):\n host_record = self.manager.get_host_record(dns_view_name, ip)\n if host_record:\n if len(host_record.ip) > 1:\n self.manager.delete_ip_from_host_record(host_record, ip)\n else:\n host_record.delete()\n\n\nclass FixedAddressIPAllocator(IPAllocator):\n\n def bind_names(self, network_view, dns_view, ip, name, extattrs):\n bind_cfg = self.opts['dns_record_binding_types']\n device_owner = extattrs.get(const.EA_PORT_DEVICE_OWNER)\n if device_owner in const.NEUTRON_FLOATING_IP_DEVICE_OWNERS:\n self.manager.update_fixed_address_eas(network_view, ip, extattrs)\n if self.opts['configure_for_dns']:\n self.manager.update_dns_record_eas(dns_view, ip, extattrs)\n if bind_cfg and self.opts['configure_for_dns']:\n self.manager.bind_name_with_record_a(\n dns_view, ip, name, bind_cfg, extattrs)\n\n def unbind_names(self, network_view, dns_view, ip, name, extattrs):\n unbind_cfg = self.opts['dns_record_unbinding_types']\n if unbind_cfg and self.opts['configure_for_dns']:\n self.manager.unbind_name_from_record_a(\n dns_view, ip, name, unbind_cfg)\n\n def allocate_ip_from_range(self, network_view, dns_view,\n zone_auth, hostname, mac, first_ip, last_ip,\n extattrs=None):\n # First search addresses with same MAC and if exists address within\n # given range - use it instead of creating new one\n # https://bugs.launchpad.net/networking-infoblox/+bug/1628517\n fixed_addrs = self.manager.get_fixed_addresses_by_mac(network_view,\n mac.lower())\n if fixed_addrs:\n ip_range = netaddr.IPRange(first_ip, last_ip)\n for fixed_addr in fixed_addrs:\n ip_addr = netaddr.IPAddress(fixed_addr.ip)\n if ip_addr in ip_range:\n self.manager.update_fixed_address_eas(network_view,\n fixed_addr.ip,\n extattrs)\n return fixed_addr.ip\n fa = self.manager.create_fixed_address_from_range(\n network_view, mac, first_ip, last_ip, extattrs)\n return fa.ip\n\n def allocate_given_ip(self, network_view, dns_view, zone_auth,\n hostname, mac, ip, extattrs=None):\n # First search addresses with same MAC and if exists address with\n # same IP - use it instead of creating new one\n # https://bugs.launchpad.net/networking-infoblox/+bug/1628517\n fixed_addrs = self.manager.get_fixed_addresses_by_mac(network_view,\n mac.lower())\n if fixed_addrs:\n for fixed_addr in fixed_addrs:\n if fixed_addr.ip == ip:\n self.manager.update_fixed_address_eas(network_view, ip,\n extattrs)\n return fixed_addr.ip\n fa = self.manager.create_fixed_address_for_given_ip(\n network_view, mac, ip, extattrs)\n return fa.ip\n\n def deallocate_ip(self, network_view, dns_view_name, ip):\n delete_cfg = self.opts['dns_record_removable_types']\n if delete_cfg and self.opts['configure_for_dns']:\n self.manager.unbind_name_from_record_a(dns_view_name, ip,\n None, delete_cfg)\n self.manager.delete_fixed_address(network_view, ip)\n","sub_path":"networking_infoblox/neutron/common/ip_allocator.py","file_name":"ip_allocator.py","file_ext":"py","file_size_in_byte":11711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"152862227","text":"import os\nfrom os import path\nfrom pyrogram import Client, filters\nfrom pyrogram.types import Message, Voice, InlineKeyboardButton, InlineKeyboardMarkup\nfrom pyrogram.errors import UserAlreadyParticipant\nfrom callsmusic import callsmusic, queues\nfrom callsmusic.callsmusic import client as USER\nfrom helpers.admins import get_administrators\nimport requests\nimport aiohttp\nimport youtube_dl\nfrom youtube_search import YoutubeSearch\nimport converter\nfrom downloaders import youtube\nfrom config import DURATION_LIMIT\nfrom helpers.filters import command\nfrom helpers.decorators import errors\nfrom helpers.errors import DurationLimitError\nfrom helpers.gets import get_url, get_file_name\nimport aiofiles\nimport ffmpeg\nfrom PIL import Image, ImageFont, ImageDraw\n\n\ndef transcode(filename):\n ffmpeg.input(filename).output(\"input.raw\", format='s16le', acodec='pcm_s16le', ac=2, ar='48k').overwrite_output().run() \n os.remove(filename)\n\n# Convert seconds to mm:ss\ndef convert_seconds(seconds):\n seconds = seconds % (24 * 3600)\n seconds %= 3600\n minutes = seconds // 60\n seconds %= 60\n return \"%02d:%02d\" % (minutes, seconds)\n\n\n# Convert hh:mm:ss to seconds\ndef time_to_seconds(time):\n stringt = str(time)\n return sum(int(x) * 60 ** i for i, x in enumerate(reversed(stringt.split(':'))))\n\n\n# Change image size\ndef changeImageSize(maxWidth, maxHeight, image):\n widthRatio = maxWidth / image.size[0]\n heightRatio = maxHeight / image.size[1]\n newWidth = int(widthRatio * image.size[0])\n newHeight = int(heightRatio * image.size[1])\n newImage = image.resize((newWidth, newHeight))\n return newImage\n\nasync def generate_cover(requested_by, title, views, duration, thumbnail):\n async with aiohttp.ClientSession() as session:\n async with session.get(thumbnail) as resp:\n if resp.status == 200:\n f = await aiofiles.open(\"background.png\", mode=\"wb\")\n await f.write(await resp.read())\n await f.close()\n\n image1 = Image.open(\"./background.png\")\n image2 = Image.open(\"etc/foreground.png\")\n image3 = changeImageSize(1280, 720, image1)\n image4 = changeImageSize(1280, 720, image2)\n image5 = image3.convert(\"RGBA\")\n image6 = image4.convert(\"RGBA\")\n Image.alpha_composite(image5, image6).save(\"temp.png\")\n img = Image.open(\"temp.png\")\n draw = ImageDraw.Draw(img)\n font = ImageFont.truetype(\"etc/font.otf\", 32)\n draw.text((190, 550), f\"Title: {title}\", (255, 255, 255), font=font)\n draw.text(\n (190, 590), f\"Duration: {duration}\", (255, 255, 255), font=font\n )\n draw.text((190, 630), f\"Views: {views}\", (255, 255, 255), font=font)\n draw.text((190, 670),\n f\"Added By: {requested_by}\",\n (255, 255, 255),\n font=font,\n )\n img.save(\"final.png\")\n os.remove(\"temp.png\")\n os.remove(\"background.png\")\n\n\n\n\n@Client.on_message(command(\"oynat\") \n & filters.group\n & ~filters.edited \n & ~filters.forwarded\n & ~filters.via_bot)\nasync def play(_, message: Message):\n\n lel = await message.reply(\"🔄 **İşleme...**\")\n \n administrators = await get_administrators(message.chat)\n chid = message.chat.id\n\n try:\n user = await USER.get_me()\n except:\n user.first_name = \"Mizuki\"\n usar = user\n wew = usar.id\n try:\n await _.get_chat_member(chid, wew)\n except:\n for administrator in administrators:\n if administrator == message.from_user.id:\n try:\n invitelink = await _.export_chat_invite_link(chid)\n except:\n await lel.edit(\n \"Önce beni grubun yöneticisi olarak ekle! \")\n return\n\n try:\n await USER.join_chat(invitelink)\n await USER.send_message(\n message.chat.id, \"**Mizuki Music asistanı müzik çalmak için bu gruba katıldı 🎵**\")\n\n except UserAlreadyParticipant:\n pass\n except Exception:\n await lel.edit(\n f\"🛑 Sel Bekleme Hatası 🛑 \\n\\Hey {user.first_name}, asistan userbot, yoğun katılım istekleri nedeniyle grubunuza katılamadı. Userbot'un grupta yasaklanmadığından emin olun ve daha sonra tekrar deneyin!\")\n try:\n await USER.get_chat(chid)\n except:\n await lel.edit(\n f\"Hey {user.first_name}, asistan userbot bu sohbette değil, yöneticiden göndermesini isteyin /oynat eklemek için ilk kez komut. \")\n dönüş\n \n audio = (message.reply_to_message.audio or message.reply_to_message.voice) if message.reply_to_message else None\n url = get_url(message)\n\n if audio:\n if round(audio.duration / 60) > DURATION_LIMIT:\n raise DurationLimitError(\n f\"❌ Daha uzun videolar {DURATION_LIMIT} dakika oynamak için izin verilmez!\"\n )\n\n file_name = get_file_name(audio)\n title = file_name\n thumb_name = \"https://telegra.ph/file/caeb50039026a746e7252.jpg\"\n thumbnail = thumb_name\n duration = round(audio.duration / 60)\n views = \"Locally added\"\n\n keyboard = InlineKeyboardMarkup(\n [\n [\n InlineKeyboardButton(\n text=\"Kanal 🔊\",\n url=\"https://t.me/Solofej\")\n \n ]\n ]\n )\n \n requested_by = message.from_user.first_name\n await generate_cover(requested_by, title, views, duration, thumbnail) \n file_path = await converter.convert(\n (await message.reply_to_message.download(file_name))\n if not path.isfile(path.join(\"downloads\", file_name)) else file_name\n )\n\n elif url:\n try:\n results = YoutubeSearch(url, max_results=1).to_dict()\n # print results\n title = results[0][\"title\"] \n thumbnail = results[0][\"thumbnails\"][0]\n thumb_name = f'thumb{title}.jpg'\n thumb = requests.get(thumbnail, allow_redirects=True)\n open(thumb_name, 'wb').write(thumb.content)\n duration = results[0][\"duration\"]\n url_suffix = results[0][\"url_suffix\"]\n views = results[0][\"views\"]\n durl = url\n durl = durl.replace(\"youtube\", \"youtubepp\")\n \n secmul, dur, dur_arr = 1, 0, duration.split(':')\n for i in range(len(dur_arr)-1, -1, -1):\n dur += (int(dur_arr[i]) * secmul)\n secmul *= 60\n \n keyboard = InlineKeyboardMarkup(\n [\n [\n InlineKeyboardButton(\n text=\"YouTube 🎬\",\n url=f\"{url}\"),\n InlineKeyboardButton(\n text=\"İndir 📥\",\n url=f\"{durl}\")\n\n ]\n ]\n )\n except Exception as e:\n title = \"NaN\"\n thumb_name = \"https://telegra.ph/file/638c20c44ca418c8b2178.jpg\"\n duration = \"NaN\"\n views = \"NaN\"\n keyboard = InlineKeyboardMarkup(\n [\n [\n InlineKeyboardButton(\n text=\"YouTube 🎬\",\n url=f\"https://youtube.com\")\n\n ]\n ]\n )\n if (dur / 60) > DURATION_LIMIT:\n await lel.edit(f\"❌ Daha uzun videolar {DURATION_LIMIT} dakika oynamak için izin verilmez!\")\n return\n requested_by = message.from_user.first_name\n await generate_cover(requested_by, title, views, duration, thumbnail) \n file_path = await converter.convert(youtube.download(url))\n else:\n if len(message.command) < 2:\n return await lel.edit(\"🧐 **Çalmak istediğiniz şarkı nedir?**\")\n await lel.edit(\"🔎 **Şarkıyı bulmak...**\")\n query = message.text.split(None, 1)[1]\n # print(query)\n await lel.edit(\"🎵 **Sesler işleniyor...**\")\n try:\n results = YoutubeSearch(query, max_results=1).to_dict()\n url = f\"https://youtube.com{results[0]['url_suffix']}\"\n # print results\n title = results[0][\"title\"] \n thumbnail = results[0][\"thumbnails\"][0]\n thumb_name = f'thumb{title}.jpg'\n thumb = requests.get(thumbnail, allow_redirects=True)\n open(thumb_name, 'wb').write(thumb.content)\n duration = results[0][\"duration\"]\n url_suffix = results[0][\"url_suffix\"]\n views = results[0][\"views\"]\n durl = url\n durl = durl.replace(\"youtube\", \"youtubepp\")\n\n secmul, dur, dur_arr = 1, 0, duration.split(':')\n for i in range(len(dur_arr)-1, -1, -1):\n dur += (int(dur_arr[i]) * secmul)\n secmul *= 60\n \n except Exception as e:\n await lel.edit(\n \"❌ Şarkı bulunamadı.\\n\\nTry başka bir şarkı ya da belki doğru şekilde heceleyin.\"\n )\n print(str(e))\n return\n\n keyboard = InlineKeyboardMarkup(\n [\n [\n InlineKeyboardButton(\n text=\"YouTube 🎬\",\n url=f\"{url}\"),\n InlineKeyboardButton(\n text=\"İndir 📥\",\n url=f\"{durl}\")\n\n ]\n ]\n )\n \n if (dur / 60) > DURATION_LIMIT:\n await lel.edit(f\"❌ Daha uzun videolar {DURATION_LIMIT} dakika oynamak için izin verilmez!\")\n return\n requested_by = message.from_user.first_name\n await generate_cover(requested_by, title, views, duration, thumbnail) \n file_path = await converter.convert(youtube.download(url))\n \n if message.chat.id in callsmusic.pytgcalls.active_calls:\n position = await queues.put(message.chat.id, file=file_path)\n await message.reply_photo(\n photo=\"final.png\", \n caption=\"**🎵 Şarkı:** {}\\n**🕒 Süre:**{} min\\n**👤 Ekleyen:** {}\\n\\n**#⃣ Sıradaki Pozisyon:** {}\".format(\n title, duration, message.from_user.mention(), position\n ),\n reply_markup=keyboard)\n os.remove(\"final.png\")\n return await lel.delete()\n else:\n callsmusic.pytgcalls.join_group_call(message.chat.id, file_path)\n await message.reply_photo(\n photo=\"final.png\",\n reply_markup=keyboard,\n caption=\"**🎵 Şarkı:** {}\\n**🕒 Süre:**{} min\\n**👤 Ekleyen:** {}\\n\\n**▶️ Şu anda Oynatılıyor`{}`...**\".format(\n title, duration, message.from_user.mention(), message.chat.title\n ), )\n os.remove(\"final.png\")\n return await lel.delete()\n","sub_path":"işleyiciler-/play.py","file_name":"play.py","file_ext":"py","file_size_in_byte":11160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"367192269","text":"import requests, bs4\nimport sys, os, subprocess\nimport tempfile\nfrom termcolor import *\nfrom urllib.parse import quote\nfrom time import sleep\n\nBASE_URL = \"http://www.allitebooks.com/\"\n\ndef send_request(url):\n\ttry:\n\t\tr = requests.get(url)\n\t\tr.raise_for_status()\n\t\treturn r\n\texcept requests.exceptions.ConnectionError:\n\t\tcprint(\"Connection Error Occurred\", 'red')\n\texcept requests.exceptions.HTTPError:\n\t\tcprint(str(r.status_code) + ' Error', 'red')\n\ndef download_and_save_pdf(title_h2):\n\ttitle_text = title_h2.find('a').text\n\tcprint('Downloading ' + title_text, 'green')\n\tanchor = title_h2.find('a')['href']\n\tr = send_request(anchor)\n\tsoup = bs4.BeautifulSoup(r.text, 'html.parser')\n\tdwnld_link = soup.find_all('span', {'class': 'download-links'})[0].find('a')['href']\n\tr = send_request(dwnld_link)\n\tf = open(title_text + '.pdf', 'wb')\n\tf.write(r.content)\n\tf.close()\n\tcprint('File %s has been saved in the current directory' % (title_text + '.pdf'), 'green')\n\ndef view_thumbnail(filepath):\n\tcprint('Opening thumbnail..', 'yellow')\n\tcprint('The thumbnail will be deleted automatically', 'blue')\n\tif sys.platform.startswith('darwin'):\n\t\tsubprocess.call(('open', filepath))\n\telif os.name == 'nt':\n\t\tos.startfile(filepath)\n\telif os.name == 'posix':\n\t\tsubprocess.call(('xdg-open', filepath))\n\tsleep(1) # So that the application gets time to launch and load the temp photo before the code exectus further and deletes it\n\ndef save_thumbnail(article):\n\tthumb = article.find('div', attrs={'class': 'entry-thumbnail'})\n\tsrc = thumb.find('img')['src']\n\tsuffix = '.' + src.split('.')[-1]\n\ttemp = tempfile.NamedTemporaryFile(delete=False, suffix=suffix)\n\ttry:\n\t\tr = send_request(src)\n\t\ttemp.write(r.content)\n\t\ttemp.close()\n\texcept:\n\t\tcprint('Sorry, error occurred while saving thumbnail', 'red')\n\t\tos.remove(temp.name)\n\treturn temp.name # filepath\n\ndef catalogue(soup):\n\tmain = soup.find('main', attrs={'id': 'main-content'})\n\tarticles = main.find_all('article')\n\tbooks = []\n\tfor article in articles:\n\t\ttitle = article.find('h2', attrs={'class': 'entry-title'})\n\t\tauthors = article.find('h5', attrs={'class': 'entry-author'})\n\t\tdescription = article.select('div.entry-summary > p')[0]\n\t\tprint('\\n')\n\t\tcprint(title.find('a').text, 'cyan')\n\t\tcprint('By: ' + ', '.join([a.text for a in authors.find_all('a')]), 'yellow')\n\t\tcprint(description.text, 'magenta')\n\t\t\n\t\tinp = input('Save this PDF? (To view its thumbnail photo, enter \\'p\\') (y/n/p): ').lower()\n\t\tif inp.startswith('y'):\n\t\t\tdownload_and_save_pdf(title)\n\t\t\texit(0)\n\t\telif inp.startswith('p'):\n\t\t\tfilepath = save_thumbnail(article)\n\t\t\ttry:\n\t\t\t\tview_thumbnail(filepath)\n\t\t\tfinally:\n\t\t\t\tos.remove(filepath)\n\t\t\tinp = input('Save this PDF? (y/n): ').lower()\n\t\t\tif inp.startswith('y'):\n\t\t\t\tdownload_and_save_pdf(title)\n\t\t\t\texit(0)\n\t\t\n\t\tinfo = {'title': title, 'authors': authors, 'description': description}\n\t\tbooks.append(info)\n\ndef paginate(page_soup, query):\n\tpaginator = page_soup.find('div', {'class': 'pagination'})\n\tlast_page_number = 1\n\tif paginator:\n\t\tpage_range = paginator.find('span', {'class': 'pages'}).get_text()\n\t\tlast_page_number = int(page_range.split('/')[-1].strip()[0])\n\tfor i in range(last_page_number):\n\t\tif i != 0: # Because the soup for the first page is passed in\n\t\t\tcprint('\\nRetrieving Page No. %s' % str(i+1), 'blue')\n\t\t\turl = BASE_URL + ('page/%s/?s=' % str(i+1)) + query\n\t\t\tprint(url)\n\t\t\tr = send_request(url)\n\t\t\tpage_soup = bs4.BeautifulSoup(r.text, 'html.parser')\n\t\tcatalogue(page_soup)\n\tcprint('Sorry, couldn\\'t find a relevant book', 'red')\n\nif __name__ == '__main__':\n\tquery = quote(input('Enter Search Query: '), safe='')\n\turl = BASE_URL + '?s=' + query\n\tr = send_request(url)\n\tsoup = bs4.BeautifulSoup(r.text, 'html.parser')\n\tpaginate(soup, query)\n","sub_path":"itebooks.py","file_name":"itebooks.py","file_ext":"py","file_size_in_byte":3723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"316745940","text":"from collections import defaultdict\n\n# Step #1. Input\nN, K = map(int, input().split())\ninput_line = list(map(int, input().split()))\nA = [0]\nA.extend(input_line)\n\n# Step #2. Shakutori\ncr = 1; cnt = 0; ans = 0\nnums = defaultdict(int)\nfor i in range(1, N+1):\n while cr <= N:\n if (nums[A[cr]] == 0)and(cnt == K):\n break\n if nums[A[cr]] == 0:\n cnt += 1\n nums[A[cr]] += 1\n cr += 1\n\n ans = max(ans, cr - i)\n if nums[A[i]] == 1:\n cnt -= 1\n nums[A[i]] -= 1\n\n# Step #3. Output The Answer\nprint(ans)","sub_path":"sol/034.py","file_name":"034.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"620260429","text":"import urllib.parse\nfrom datetime import date\nfrom io import BytesIO\nfrom logging import log\nfrom pathlib import Path\n\nimport aiohttp\nfrom discord.ext import timers\nfrom dotenv import load_dotenv\nfrom nepali_date import NepaliDate\n\nfrom models import ReputationPoints\nfrom modules.imports import *\n\nload_dotenv()\nenv_path = Path(\".\") / \".env\"\nload_dotenv(dotenv_path=env_path)\n\nWEATHER_TOKEN = os.getenv(\"WEATHER_API_TOKEN\")\n\n\ntime_regex = re.compile(\"(?:(\\d{1,5})(h|s|m|d))+?\")\ntime_dict = {\"h\": 3600, \"s\": 1, \"m\": 60, \"d\": 86400}\n\n\nclass TimeConverter(commands.Converter):\n async def convert(self, ctx, argument):\n args = argument.lower()\n matches = re.findall(time_regex, args)\n time = 0\n for v, k in matches:\n try:\n time += time_dict[k] * float(v)\n except KeyError:\n raise commands.BadArgument(\n \"{} is an invalid time-key! h/m/s/d are valid!\".format(k)\n )\n except ValueError:\n raise commands.BadArgument(\"{} is not a number!\".format(v))\n return time\n\n\nclass Misc(Cog):\n \"\"\"\n Miscellaneous Commands of the Bot\n \"\"\"\n\n def __init__(self, client):\n self.client = client\n self.client.load_extension(\"jishaku\")\n\n @command(name=\"avatar\", aliases=[\"av\"], brief=\"Returns the member's avatar.\")\n async def avatar_command(self, ctx, member: Optional[Member]):\n \"\"\"Returns the member's avatar.\"\"\"\n member = member or ctx.author\n avatarUrl = member.avatar_url\n embed = Embed(\n title=f\"Avatar - {member.name}\",\n timestamp=datetime.utcnow(),\n color=Color.blurple(),\n )\n embed.set_footer(text=f\"Requested by {ctx.author.name}\")\n embed.set_image(url=avatarUrl)\n await ctx.send(embed=embed)\n\n @command(name=\"serverinfo\", brief=\"Returns some info about the guild.\")\n async def serverinfo_command(self, ctx):\n \"\"\"Returns some info about the guild.\"\"\"\n owner = str(ctx.guild.owner.mention)\n id = str(ctx.guild.id)\n region = str(ctx.guild.region)\n memberCount = str(ctx.guild.member_count)\n textChannels = len(ctx.guild.text_channels)\n voiceChannels = len(ctx.guild.voice_channels)\n roles = len(ctx.guild.roles)\n guildCreatedate = ctx.guild.created_at.strftime(\"%a, %#d %B %Y, %I:%M %p\")\n\n embed = Embed(\n title=f\"Info of {ctx.guild.name} Server\",\n color=Color.blurple(),\n timestamp=datetime.utcnow(),\n )\n embed.set_footer(text=f\"Requested by {ctx.author.name}\")\n embed.set_thumbnail(url=ctx.guild.icon_url)\n fields = [\n (\"Server ID\", id, True),\n (\"Server Region\", region.capitalize(), True),\n (\"Owner\", owner, True),\n (\"Member Count\", memberCount, True),\n (\"Text Channels\", textChannels, True),\n (\"Voice Channels\", voiceChannels, True),\n (\"Role Count\", roles, True),\n (\"Created on\", guildCreatedate, True),\n ]\n for name, value, inline in fields:\n embed.add_field(name=name, value=value, inline=inline)\n await ctx.send(embed=embed)\n\n @command(name=\"userinfo\", brief=\"See the info of the user.\")\n async def userinfo_command(self, ctx, member: Optional[Member]):\n \"\"\"See the info of the user.\"\"\"\n member = member or ctx.author\n member_avatar = member.avatar_url\n id = member.id\n name = member.name\n accountAge = member.created_at.strftime(\"%a, %#d %B %Y, %I:%M %p UTC\")\n joinServerDate = member.joined_at.strftime(\"%a, %#d %B %Y, %I:%M %p UTC\")\n highestRole = member.top_role.mention\n\n info = \"Server Owner\" if ctx.guild.owner is ctx.author else \"Member\"\n\n embed = Embed(\n title=f\"User Info - {member.name}\",\n timestamp=datetime.utcnow(),\n color=Color.blurple(),\n )\n embed.set_footer(text=f\"Requested by {ctx.author.name}\")\n embed.set_thumbnail(url=member_avatar)\n fields = [\n (\"ID\", id, False),\n (\"Name\", f\"{name} #{ctx.author.discriminator}\", True),\n (\"Highest Role\", highestRole, True),\n (\"Account Created on\", accountAge, True),\n (\"Joined Server on\", joinServerDate, True),\n (\"Additional Info\", info, True),\n ]\n for name, value, inline in fields:\n embed.add_field(name=name, value=value, inline=inline)\n await ctx.send(embed=embed)\n\n @command(name=\"ping\", brief=\"Returns the bot latency.\")\n async def ping_command(self, ctx):\n \"\"\"Returns the bot latency.\"\"\"\n ping = int(self.client.latency * 1000)\n embed = Embed(\n title=\"Pong!\", description=f\"My ping is {ping}ms.\", color=Color.green()\n )\n await ctx.send(embed=embed)\n\n @command(name=\"botinvite\", brief=\"Returns the invite link of bot\")\n async def botinvite_command(self, ctx):\n \"\"\"Returns the invite link of bot\"\"\"\n invite = f\"https://discord.com/api/oauth2/authorize?client_id={self.client.user.id}&permissions=1374809815&scope=bot\"\n await ctx.send(invite)\n\n @command(name=\"countryinfo\", brief=\"Returns the info about the country provided.\")\n async def countryinfo_command(self, ctx, *, countryname: str):\n \"\"\"Returns the info about the country provided.\"\"\"\n async with aiohttp.ClientSession() as session:\n async with session.get(\n f\"https://restcountries.eu/rest/v2/name/{countryname}\"\n ) as resp:\n info = await resp.json()\n countryName = info[0][\"name\"]\n topLevelDomainn = info[0][\"topLevelDomain\"]\n topLevelDomain = \",\".join(topLevelDomainn)\n alpha2Code = info[0][\"alpha2Code\"]\n callingCodesList = info[0][\"callingCodes\"]\n callingCodes = \",\".join(callingCodesList)\n capital = info[0][\"capital\"]\n region = info[0][\"region\"]\n population = info[0][\"population\"]\n nativeName = info[0][\"nativeName\"]\n timeZonesList = info[0][\"timezones\"]\n timeZones = \",\".join(timeZonesList)\n currencies = info[0][\"currencies\"]\n currency_code = currencies[0][\"code\"]\n currency_symbol = currencies[0][\"symbol\"]\n alternativeSpellingsList = info[0][\"altSpellings\"]\n alternativeSpellings = \",\".join(alternativeSpellingsList)\n\n embed = Embed(\n color=Color.blurple(),\n timestamp=datetime.utcnow(),\n description=f\"**Name** - {countryName}\\n**Top Level Domain** - {topLevelDomain}\\n**Alpha2 Code** - {alpha2Code}\\n**Calling Codes** - {callingCodes}\\n**Capital** - {capital}\\n **Region** - {region}\\n**Population** - {population}\\n**Native Name** - {nativeName}\\n**Time Zones** - {timeZones}\\n**Currency Code** - {currency_code}\\n**Currency Symbol** - {currency_symbol}\\n**Alternative Spellings** - {alternativeSpellings}\",\n )\n embed.set_author(name=f\"Info of {countryName}\")\n embed.set_thumbnail(\n url=f\"https://flagcdn.com/w80/{str(alpha2Code).lower()}.png\"\n )\n embed.set_footer(text=f\"Requested by {ctx.author}\")\n await ctx.send(embed=embed)\n\n @command(name=\"githubinfo\", brief=\"Returns github info of the username provided.\")\n async def githubinfo_command(self, ctx, *, githubusername: str):\n \"\"\"Returns github info of the username provided.\"\"\"\n async with aiohttp.ClientSession() as session:\n async with session.get(\n f\"https://api.github.com/users/{githubusername}\"\n ) as resp:\n githubinfo = await resp.json()\n name = githubinfo[\"name\"]\n avatar_url = githubinfo[\"avatar_url\"]\n blog = githubinfo[\"blog\"]\n location = githubinfo[\"location\"]\n twitter_username = githubinfo[\"twitter_username\"]\n publicrepos = githubinfo[\"public_repos\"]\n followers = githubinfo[\"followers\"]\n following = githubinfo[\"following\"]\n embed = Embed(\n color=Color.blurple(),\n timestamp=datetime.utcnow(),\n description=(\n f\"**Name** - {name}\\n**Blog URL** - {None if not blog else blog}\\n**Location** - {location}\\n**Twitter Username** - {twitter_username}\\n **Public Repositories** - {publicrepos}\\n**Followers** - {followers}\\n**Following** - {following}\"\n ),\n )\n embed.set_author(name=f\"Github Profile info of username {githubusername}\")\n if avatar_url is not None:\n embed.set_thumbnail(url=avatar_url)\n await ctx.send(embed=embed)\n\n @command(name=\"weather\", brief=\"Returns the weather of the place provided.\")\n async def weather_command(self, ctx, *, cityName: str):\n \"\"\"Returns the weather of the place provided.\"\"\"\n base_url = \"http://api.openweathermap.org/data/2.5/weather?\"\n complete_url = base_url + \"appid=\" + WEATHER_TOKEN + \"&q=\" + cityName\n image = \"https://icons-for-free.com/iconfiles/png/512/fog+foggy+weather+icon-1320196634851598977.png\"\n async with aiohttp.ClientSession() as session:\n async with session.get(complete_url) as resp:\n data = await resp.json()\n main = data[\"main\"]\n wind = data[\"wind\"]\n weather = data[\"weather\"]\n city = data[\"name\"]\n temperature_in_celcius = int(main[\"temp\"] - 273)\n feelslike_in_celcius = int(main[\"feels_like\"] - 273)\n max_tempr = int(main[\"temp_max\"] - 273)\n min_tempr = int(main[\"temp_min\"] - 273)\n wind = data[\"wind\"]\n speed_wind = wind[\"speed\"]\n weather_description = str(weather[0][\"description\"]).title()\n embed = Embed(\n color=Color.blurple(),\n timestamp=datetime.utcnow(),\n description=f\"**Temperature** - {temperature_in_celcius} °C\\n**Feels like** - {feelslike_in_celcius} °C\\n**Maximum Temperature** - {max_tempr} °C\\n**Minimum Temperature** - {min_tempr} °C\\n**Description** - {weather_description}\\n**Wind Velocity** - {speed_wind} km/h\",\n )\n embed.set_author(name=f\"Weather of {cityName.title()}\")\n embed.set_thumbnail(url=image)\n await ctx.send(embed=embed)\n\n @command(name=\"carbon\", brief=\"Returns the code snippet of the code you provide.\")\n async def carbon_command(self, ctx, *, codeblock: str):\n \"\"\"Returns the code snippet of the code you provide.(Currently doesn't work for C++ and C)\"\"\"\n regex = re.compile(r\"(\\w*)\\s*(?:```)(\\w*)?([\\s\\S]*)(?:```$)\")\n matches = regex.findall(codeblock)\n if not matches:\n embed = Embed(color=Color.blurple())\n embed.set_author(\n name=f\"Could not find codeblock.\", icon_url=self.client.user.avatar_url\n )\n await ctx.send(embed=embed)\n code = matches[0][2]\n splitted_code = str(code).splitlines()\n codes = []\n codes = \"%250A\".join(splitted_code)\n # print(codes)\n\n async with aiohttp.ClientSession() as session:\n async with session.get(\n f\"https://carbonnowsh.herokuapp.com/?code={codes}&theme=monokai\"\n ) as resp:\n file = BytesIO(await resp.read())\n bytes = file.getvalue()\n file = open(\"carbon.png\", \"wb\")\n file.write(bytes)\n file.close()\n await ctx.send(file=discord.File(fp=\"carbon.png\", filename=\"carbon.png\"))\n os.remove(\"carbon.png\")\n\n @command(name=\"c19\", brief=\"Show the COVID-19 stats of the country provided.\")\n async def c19_command(self, ctx, *, country: Optional[str]):\n \"\"\"Show the COVID-19 stats of the country provided.\"\"\"\n with ctx.channel.typing():\n country = country or \"nepal\"\n logoUrl = \"http://covidcp.org/images/logo-icononly.png\"\n url = f\"https://coronavirus-19-api.herokuapp.com/countries/{country}\"\n async with aiohttp.ClientSession() as session:\n async with session.get(url) as resp:\n data = await resp.json()\n cntry = data[\"country\"]\n cases = data[\"cases\"]\n todayCases = data[\"todayCases\"]\n deaths = data[\"deaths\"]\n recovered = data[\"recovered\"]\n active = data[\"active\"]\n output = f\"Total Cases - **{cases}** \\n Cases Today - **{todayCases}** \\nTotal Deaths - **{deaths}** \\nActive Cases - **{active}** \\nTotal Recovered - **{recovered}**\"\n embed = Embed(\n color=Color.blurple(), timestamp=datetime.utcnow(), description=output\n )\n embed.set_author(name=f\"COVID-19 Stats for {cntry}\")\n embed.set_thumbnail(url=logoUrl)\n await ctx.send(embed=embed)\n\n def __init__(self, client):\n self.client = client\n\n async def _run_code(self, *, lang: str, code: str):\n async with aiohttp.ClientSession() as session:\n async with session.post(\n \"https://emkc.org/api/v1/piston/execute\",\n json={\"language\": lang, \"source\": code},\n ) as resp:\n return await resp.json()\n\n @command(name=\"compile\", brief=\"Returns output of the code provided.\")\n async def compile_command(self, ctx, *, codeblock: str):\n \"\"\"\n Returns output of the code provided.\n \"\"\"\n regex = re.compile(r\"(\\w*)\\s*(?:```)(\\w*)?([\\s\\S]*)(?:```$)\")\n matches = regex.findall(codeblock)\n if not matches:\n embed = Embed(color=Color.blurple())\n embed.set_author(\n name=f\"Could not find codeblock.\", icon_url=self.client.user.avatar_url\n )\n await ctx.send(embed=embed)\n lang = matches[0][0] or matches[0][1]\n if not lang:\n embed = Embed(color=Color.blurple())\n embed.set_author(\n name=f\"Could not find language hinted in the codeblock.\",\n icon_url=self.client.user.avatar_url,\n )\n code = matches[0][2]\n result = await self._run_code(lang=lang, code=code)\n await self._send_result(ctx, result)\n\n async def _send_result(self, ctx, result: dict):\n if \"message\" in result:\n return await ctx.send(\n embed=Embed(\n title=\"Error\", description=result[\"message\"], color=Color.red()\n )\n )\n output = result[\"output\"]\n embed = Embed(timestamp=datetime.utcnow(), color=Color.green())\n output = output[:500]\n shortened = len(output) > 500\n lines = output.splitlines()\n shortened = shortened or (len(lines) > 15)\n output = \"\\n\".join(lines[:15])\n output += shortened * \"\\n\\n**Output shortened**\"\n embed.set_author(\n name=f\"Your code was in {str(result['language']).capitalize()}.\",\n icon_url=ctx.author.avatar_url,\n )\n embed.add_field(name=\"Output\", value=f\"`{output}`\" or \"****\")\n embed.set_footer(text=f\"Requested by {ctx.author.name}\")\n await ctx.message.add_reaction(\"\")\n await asyncio.sleep(2)\n await ctx.message.clear_reaction(\"\")\n\n await ctx.send(embed=embed)\n\n @commands.cooldown(1, 86400, commands.BucketType.user)\n @command(name=\"rep\", brief=\"Give a reputation point to the user\")\n async def reputation_command(self, ctx, member: Member):\n \"\"\"Give a reputation point to the user\"\"\"\n await self.reputation_handler(ctx, member)\n\n async def reputation_handler(self, ctx, member):\n if member is ctx.author:\n await ctx.send(\"you cannot give reputation points to yourself.\")\n return\n model, _ = await ReputationPoints.get_or_create(\n member_name=member.name, guild_id=ctx.guild.id\n )\n model.points = model.points + 1\n await model.save()\n embed = Embed(color=Color.green()) # timestamp=datetime.utcnow())\n embed.set_author(\n name=f\"{ctx.author.name} gave a reputation point to {member.name}\",\n icon_url=ctx.author.avatar_url,\n )\n await ctx.send(embed=embed)\n\n @command(name=\"replist\", brief=\"View the leaderboard of reputation for the server.\")\n async def replist_command(self, ctx):\n \"\"\"View the leaderboard of reputation for the server.\"\"\"\n rep_model = (\n await ReputationPoints.filter(guild_id=ctx.guild.id)\n .order_by(\"-points\")\n .limit(10)\n )\n leaderboard = \"\\n\".join(\n [\n f\"**{i+1}.** {model.member_name} - {model.points}\"\n for (i, model) in enumerate(rep_model)\n ]\n )\n # print(leaderboard)\n embed = Embed(\n description=leaderboard if len(rep_model) else \"No data found\",\n color=Color.blurple(),\n timestamp=datetime.utcnow(),\n )\n embed.set_footer(text=f\"Requested by {ctx.author.name}\")\n embed.set_author(\n name=f\"{ctx.guild.name} Reputation Leaderboard\", icon_url=ctx.guild.icon_url\n )\n await ctx.send(embed=embed)\n\n @command(\n name=\"remainder\",\n aliases=[\"remind\", \"remindme\"],\n brief=\"Set a remainder for things.\",\n )\n async def remainder_command(self, ctx, time: TimeConverter, *, reason):\n \"\"\"Set a remainder for things.\"\"\"\n timers.Timer(\n self.client, \"remainder\", time, args=(ctx.channel.id, ctx.author.id, reason)\n ).start()\n embed = Embed(color=Color.blurple())\n embed.set_author(\n name=f\"Set a remainder for reason - {reason}\",\n icon_url=ctx.author.avatar_url,\n )\n await ctx.send(embed=embed)\n\n @Cog.listener()\n async def on_remainder(self, channel_id, author_id, reason):\n channel = self.client.get_channel(channel_id)\n await channel.send(f\" <@{author_id}>, Remainder: {reason}\")\n\n @command(name=\"nepalidate\")\n async def nepalidate_command(self, ctx):\n with ctx.channel.typing():\n nepdate = NepaliDate.today()\n\n nepdate_dev = NepaliDate.today(lang=\"nep\")\n await ctx.send(nepdate)\n await ctx.send(nepdate_dev)\n\n @command(name=\"serverinvite\")\n async def serverinvite_command(self, ctx):\n with ctx.channel.typing():\n link = await ctx.channel.create_invite(max_age=0)\n await ctx.send(f\"**The invite link for this server is**\\n{link}\")\n # yes\n # no\n\n @command(name=\"nepse\")\n async def nepse_command(self, ctx, company: str, today_date: Optional[str]):\n today_date = today_date or date.today()\n url = \"https://api.sheezh.com/nepse/v1/price\"\n async with aiohttp.ClientSession() as session:\n async with session.post(\n url, json={\"symbol\": company.upper(), \"date\": str(today_date)}\n ) as resp:\n data = await resp.json()\n maxprice = data[0][\"MaxPrice\"]\n minprice = data[0][\"MinPrice\"]\n closingprice = data[0][\"ClosingPrice\"]\n tradedshares = data[0][\"TradedShares\"]\n previousclosing = data[0][\"PreviousClosing\"]\n\n async with session.post(\n \"https://api.sheezh.com/nepse/v1/company\", json={\"symbol\": company}\n ) as res:\n name = await res.json()\n companyName = name[0][\"companyName\"]\n embed = Embed(\n color=Color.blurple(),\n timestamp=datetime.utcnow(),\n description=f\"**Maximum Price** - {maxprice}\\n**Minimum Price** - {minprice}\\n**Closing Price** - {closingprice}\\n**Traded Shares** - {tradedshares}\\n**Previous Closing Price** - {previousclosing}\",\n )\n embed.set_thumbnail(\n url=\"https://cdn6.aptoide.com/imgs/a/8/4/a8435b6d8d3424dbc79a4ad52f976ad7_icon.png\"\n )\n embed.set_author(name=f\"Details for - {companyName} \")\n await ctx.send(embed=embed)\n\n @commands.group(\n invoke_without_command=True,\n brief=\"Suggestion command. Use arguments `approve`, `deny` as arguments.\",\n )\n async def suggest(self, ctx, *, suggestion: str):\n \"\"\"Suggestion command. Use arguments `approve`, `deny` as arguments.\"\"\"\n emojis = [\"✅\", \"❌\"]\n author = ctx.author\n guild = ctx.guild\n embed = Embed(color=Color.blurple(), timestamp=datetime.utcnow())\n embed.add_field(name=\"Suggestion\", value=suggestion)\n embed.set_author(name=f\"Suggestion by - {author}\", icon_url=author.avatar_url)\n msg = await ctx.send(embed=embed)\n await ctx.message.delete()\n for i in range(len(emojis)):\n await msg.add_reaction(emojis[i])\n\n @suggest.group(name=\"approve\")\n @commands.has_permissions(administrator=True)\n async def approve_command(self, ctx, msgID: int):\n msg = await ctx.fetch_message(msgID)\n embed = msg.embeds[0]\n if embed is None:\n return\n embed.set_footer(text=f\"Approved by {ctx.author}\")\n embed.color = Color.green()\n await msg.edit(embed=embed)\n await msg.clear_reactions()\n\n @suggest.group(name=\"deny\")\n @commands.has_permissions(administrator=True)\n async def deny_command(self, ctx, msgID: int, *, reason: str):\n msg = await ctx.fetch_message(msgID)\n embed = msg.embeds[0]\n if embed is None:\n return\n embed.title = f\"Denial Reason - {reason}\"\n embed.set_footer(text=f\"Denied by {ctx.author}\")\n embed.color = Color.red()\n await msg.edit(embed=embed)\n await msg.clear_reactions()\n\n\ndef setup(client):\n client.add_cog(Misc(client))\n","sub_path":"cogs/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":22224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"328299376","text":"from pysnmp.hlapi import *\nfrom parse_config import config\nimport sys\n\n\n#Reference SNMAP-WALK from:https://www.google.com/search?q=snmp+walk+solarwinds&oq=snmp+walk&aqs=chrome.5.69i57j0l5.2209j0j4&sourceid=chrome&ie=UTF-8\n\n#.env file need to have VLAN number & Switch address\n\nswitches = config['switches']\nvlan = config['private_number']\n\n\ndef decToHexAddress(arg):\n arr = arg.split(\".\")\n output = ''\n\n for i in range(len(arr)):\n if i == len(arr) - 1:\n output = output + hex(int(arr[i])).replace('0x', '').upper()\n else:\n output = output + hex(int(arr[i])).replace('0x', '').upper() + \":\"\n return output\n\n\ndef mac_mapper(file):\n output = []\n mac_addresses = []\n for s in switches:\n host = s['switch_address']\n for (errorIndication, errorStatus, errorIndex, varBinds) in nextCmd(SnmpEngine(),\n CommunityData('private@'+str(vlan)), UdpTransportTarget((host, 161),timeout = 2, retries = 5), ContextData(),\n ObjectType(ObjectIdentity('1.3.6.1.2.1.17.4.3.1.2')), lexicographicMode=False):\n if errorIndication:\n print(errorIndication, file=sys.stderr)\n break\n elif errorStatus:\n print('%s at %s' % (errorStatus.prettyPrint(),\n errorIndex and varBinds[int(errorIndex) - 1][0] or '?'),\n file=sys.stderr)\n break\n else:\n data = []\n\n for varBind in varBinds:\n element = str(varBind)\n element = element.replace(\"SNMPv2-SMI::mib-2.17.4.3.1.2.\", \"\").replace(\" = \", \";\")\n splitArr = element.split(\";\")\n mac_address = element.replace(splitArr[0],decToHexAddress(splitArr[0]))\n mac_addresses.append(mac_address)\n data.append(host + ',' + mac_address)\n\n\n print(\"['SWITCH ADDRESS,MAC ADDRESS;PORT']\")\n print(data)\n\n output.extend(data)\n \n text = \"\"\n for j in output:\n text += j + '\\n'\n\n with open('mac_mapper.txt', \"w\") as f:\n f.write(text)\n\n if file != None:\n with open(file, \"w\") as f:\n for address in mac_addresses:\n f.write(address+\"\\n\")\n\n\nif __name__ == \"__main__\":\n mac_mapper()\n","sub_path":"utility/mac_mapper.py","file_name":"mac_mapper.py","file_ext":"py","file_size_in_byte":2362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"75680228","text":"from math import sqrt\r\ndef main():\r\n cord1 = input()\r\n cord2 = input()\r\n\r\n x1 = float(cord1.split()[0])\r\n y1 = float(cord1.split()[1])\r\n x2 = float(cord2.split()[0])\r\n y2 = float(cord2.split()[1])\r\n\r\n distancia = sqrt((x2 - x1)**2 + (y2 - y1)**2)\r\n\r\n print('%.4f' % distancia)\r\n\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"Python/URI/URI academic 1 parte 1/URI 1015.py","file_name":"URI 1015.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"631861116","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed May 16 13:42:19 2018\r\n\r\n@author: elies\r\n\"\"\"\r\n\r\nfrom flask import request\r\n\r\ndef multiplaescolha(pergunta):\r\n x = ''\r\n lista = []\r\n x = request.form[pergunta]\r\n if x == \"0\":\r\n x = 0\r\n elif x == \"1\":\r\n x = 1\r\n elif x == \"2\":\r\n x = 2\r\n elif x == \"3\":\r\n x = 3\r\n elif x == \"4\":\r\n x = 4\r\n elif x == \"5\":\r\n x = 5\r\n \r\n if pergunta == \"cidade\":\r\n if x == 0:\r\n lista = [\"Captain America\",\"Black Panther\"] \r\n elif x == 1:\r\n lista = [\"Hulk\",\"Iron Man\"] \r\n elif x == 2:\r\n lista = [\"Vision\",\"Scarlet Witch\"]\r\n elif x == 3:\r\n lista = [\"Thor\",\"Ant Man\"]\r\n elif x == 4:\r\n lista = [\"Doctor Strange\",\"Spider Man\"]\r\n elif x == 5:\r\n lista = [\"Peter Quill\",\"Rocket\"]\r\n \r\n elif pergunta == \"animal\":\r\n if x == 0:\r\n lista = [\"Black Panther\", \"Iron Man\"] \r\n elif x == 1:\r\n lista = [\"Rocket\", \"Vision\"] \r\n elif x == 2:\r\n lista = [\"Ant Man\", \"Peter Quill\"]\r\n elif x == 3:\r\n lista = [\"Captain America\", \"Hulk\"]\r\n elif x == 4:\r\n lista = [\"Thor\",\"Scarlet Witch\"]\r\n elif x == 5:\r\n lista = [\"Spider Man\",\"Doctor Strange\"]\r\n\r\n elif pergunta == \"planeta\":\r\n if x == 0:\r\n lista = [\"Doctor Strange\",\"Iron Man\"] \r\n elif x == 1:\r\n lista = [\"Thor\",\"Hulk\"] \r\n elif x == 2:\r\n lista = [\"Rocket\",\"Scarlet Witch\"]\r\n elif x == 3:\r\n lista = [\"Ant Man\",\"Spider Man\"]\r\n elif x == 4:\r\n lista = [\"Peter Quill\",\"Vision\"]\r\n elif x == 5:\r\n lista = [\"Black Panther\",\"Captain America\"]\r\n\r\n elif pergunta == \"esporte\":\r\n if x == 0:\r\n lista = [\"Rocket\",\"Scarlet Witch\"] \r\n elif x == 1:\r\n lista = [\"Doctor Strange\",\"Vision\"] \r\n elif x == 2:\r\n lista = [\"Thor\",\"Spider Man\"]\r\n elif x == 3:\r\n lista = [\"Iron Man\",\"Hulk\"]\r\n elif x == 4:\r\n lista = [\"Black Panther\",\"Captain America\"]\r\n elif x == 5:\r\n lista = [\"Ant Man\",\"Peter Quill\"]\r\n\r\n elif pergunta == \"olho\":\r\n if x == 0:\r\n lista = [\"Captain America\",\"Thor\"] \r\n elif x == 1:\r\n lista = [\"Scarlet Witch\",\"Peter Quill\"] \r\n elif x == 2:\r\n lista = [\"Doctor Strange\",\"Iron Man\"]\r\n elif x == 3:\r\n lista = [\"Black Panther\",\"Spider Man\"]\r\n elif x == 4:\r\n lista = [\"Ant Man\",\"Rocket\"]\r\n elif x == 5:\r\n lista = [\"Vision\",\"Hulk\"]\r\n\r\n elif pergunta == \"musica\":\r\n if x == 0:\r\n lista = [\"Vision\",\"Ant Man\"] \r\n elif x == 1:\r\n lista = [\"Hulk\",\"Black Panther\"] \r\n elif x == 2:\r\n lista = [\"Peter Quill\",\"Doctor Strange\"]\r\n elif x == 3:\r\n lista = [\"Iron Man\",\"Spider Man\"]\r\n elif x == 4:\r\n lista = [\"Captain America\",\"Rocket\"]\r\n elif x == 5:\r\n lista = [\"Thor\", \"Scarlet Witch\"]\r\n \r\n elif pergunta == \"camisa\":\r\n if x == 0:\r\n lista = [\"Rocket\",\"Scarlet Witch\"] \r\n elif x == 1:\r\n lista = [\"Peter Quill\", \"Black Panther\"] \r\n elif x == 2:\r\n lista = [\"Iron Man\",\"Spider Man\"]\r\n elif x == 3:\r\n lista = [\"Captain America\",\"Thor\"]\r\n elif x == 4:\r\n lista = [\"Hulk\",\"Doctor Strange\"]\r\n elif x == 5:\r\n lista = [\"Vision\",\"Ant Man\"]\r\n \r\n elif pergunta == \"filme\":\r\n if x == 0:\r\n lista = [\"Vision\",\"Thor\"] \r\n elif x == 1:\r\n lista = [\"Hulk\",\"Ant Man\"] \r\n elif x == 2:\r\n lista = [\"Peter Quill\",\"Doctor Strange\"]\r\n elif x == 3:\r\n lista = [\"Rocket\",\"Black Panther\"]\r\n elif x == 4:\r\n lista = [\"Spider Man\",\"Captain America\"]\r\n elif x == 5:\r\n lista = [\"Iron Man\",\"Scarlet Witch\"]\r\n \r\n elif pergunta == \"pedra\":\r\n if x == 0:\r\n lista = [\"Hulk\",\"Black Panther\"] \r\n elif x == 1:\r\n lista = [\"Doctor Strange\",\"Captain America\"] \r\n elif x == 2:\r\n lista = [\"Scarlet Witch\",\"Spider Man\"]\r\n elif x == 3:\r\n lista = [\"Vision\",\"Rocket\"]\r\n elif x == 4:\r\n lista = [\"Iron Man\",\"Peter Quill\"]\r\n elif x == 5:\r\n lista = [\"Thor\",\"Ant Man\"]\r\n \r\n elif pergunta == \"cor\":\r\n if x == 0:\r\n lista = [\"Spider Man\",\"Peter Quill\"] \r\n elif x == 1:\r\n lista = [\"Iron Man\", \"Captain America\"] \r\n elif x == 2:\r\n lista = [\"Thor\",\"Hulk\"]\r\n elif x == 3:\r\n lista = [\"Black Panther\",\"Doctor Strange\"]\r\n elif x == 4:\r\n lista = [\"Vision\",\"Ant Man\"]\r\n elif x == 5:\r\n lista = [\"Rocket\",\"Scarlet Witch\"]\r\n \r\n elif pergunta == \"comida\":\r\n if x == 0:\r\n lista = [\"Captain America\",\"Scarlet Witch\"] \r\n elif x == 1:\r\n lista = [\"Hulk\",\"Vision\"] \r\n elif x == 2:\r\n lista = [\"Thor\",\"Iron Man\"]\r\n elif x == 3:\r\n lista = [\"Vision\",\"Peter Quill\"]\r\n elif x == 4:\r\n lista = [\"Black Panther\",\"Doctor Strange\"]\r\n elif x == 5:\r\n lista = [\"Spider Man\",\"Rocket\"]\r\n \r\n elif pergunta == \"numero\":\r\n if x == 0:\r\n lista = [\"Doctor Strange\",\"Rocket\"] \r\n elif x == 1:\r\n lista = [\"Vision\",\"Black Panther\"] \r\n elif x == 2:\r\n lista = [\"Peter Quill\",\"Scarlet Witch\"]\r\n elif x == 3:\r\n lista = [\"Spider Man\",\"Ant Man\"]\r\n elif x == 4:\r\n lista = [\"Captain America\",\"Thor\"]\r\n elif x == 5:\r\n lista = [\"Iron Man\",\"Hulk\"]\r\n\r\n return lista","sub_path":"funcao.py","file_name":"funcao.py","file_ext":"py","file_size_in_byte":6026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"319784679","text":"import os\nimport json\nimport logging\nimport datetime as dt\nfrom flask import Flask, request, redirect, url_for\n\nfrom PIL import Image\nfrom packages.yolov3 import main as yolov3\n\nroot = os.getcwd()\napp = Flask(__name__)\n\n\n@app.route('/', methods=['POST'])\ndef upload_file():\n file = request.files['file']\n filename = file.filename.split(\".\")[0]\n\n img_raw = Image.open(file).convert(\"RGB\")\n os.chdir(\"./packages/yolov3/\")\n image, cropped = yolov3.detect(img_raw)\n os.chdir(root)\n\n result = {}\n logging.info(cropped)\n result = json.dumps(cropped, ensure_ascii=False).encode('utf-8')\n\n # tvmonitor images collection\n try:\n images_tvmonitor = []\n for i in cropped['tvmonitor']:\n images_tvmonitor.append(img_raw.crop((i[0], i[1], i[2], i[3])))\n images_tvmonitor[-1].save(\"./out/\" + str(len(images_tvmonitor)) +\n \".png\")\n except:\n pass\n\n # clock images collection\n try:\n images_clock = []\n for i in cropped['clock']:\n images_clock.append(\n img_raw.crop((i[0] - 15, i[1], i[2], i[3] + 15)))\n images_clock[-1].save(\"./out/\" + str(len(images_clock)) + \".png\")\n except:\n pass\n\n return result, 200, {\"ContentType\": \"application/json\"}\n\n\nif __name__ == '__main__':\n os.makedirs(\"./out/\", exist_ok=True)\n os.makedirs(\"./log/\", exist_ok=True)\n logging.basicConfig(filename=\"./log/app.log\",\n filemode=\"a\",\n format=\"%(asctime)s %(levelname)s:%(message)s\",\n datefmt=\"%Y-%m-%d %H:%M:%S\",\n level=logging.ERROR)\n\n app.run(host='localhost', port=8000, debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"536680506","text":"from flask import Flask, jsonify\nfrom flask.wrappers import Response\nfrom flask.globals import request\nfrom werkzeug.wrappers import ETagRequestMixin, ETagResponseMixin, BaseRequest, BaseResponse\n\nfrom Manager.manager import Manager\nfrom Reporter.Reporter import Reporter\n\napp = Flask(__name__)\n\n\nclass Response(BaseResponse, ETagResponseMixin):\n pass\n\n\nclass Request(BaseRequest, ETagRequestMixin):\n pass\n\n\ndef checkForm(json):\n keys = json.keys()\n return ('email' in keys and \"hashtags\" in keys and \"mentions\" in keys and \"startDate\" in keys and \"endDate\" in keys)\n\n\n# Goes from guinated string to list\ndef fixCampaing(c):\n c.hashtags = c.hashtags.split(\"-\")\n c.mentions = c.mentions.split(\"-\")\n return c\n\n\n# -------------------------- manager flask ------------------------------\n\n@app.route('/Campaing', methods=['POST', 'DELETE'])\ndef api_manager():\n if request.method == 'POST' and 'application/json' == request.headers['Content-Type']:\n if checkForm(request.json):\n idCampaign = Manager().insertCampaign(request.get_json())\n res = Response(status=201)\n res.set_etag(str(idCampaign), weak=False)\n return res\n else:\n return Response(status=412)\n\n elif request.method == 'DELETE':\n if 'idC' in request.json.keys():\n res = Manager().deleteCampaignByID(request.json['idC'])\n return Response(status=res)\n elif 'email' in request.json.keys():\n res = Manager().deleteCampaignsByEmail(request.json['email'])\n return Response(status=res)\n else:\n return Response(status=400)\n\n\n@app.route('/Campaing/', methods=['GET', 'PATCH'])\ndef api_manager_id(idC):\n if request.method == 'GET':\n campaign = Manager().returnCampaign(idC)\n return (Response(status=404) if campaign == [] else jsonify(fixCampaing(campaign).to_json()))\n\n elif request.method == 'PATCH':\n if ('columnaAModif' in request.json.keys()) and ('campoColumna' in request.json.keys()):\n res = Manager().modifyCampaign(idC, request.json['columnaAModif'], request.json['campoColumna'])\n return Response(status=res)\n else:\n return Response(status=400)\n else:\n return Response(status=404)\n\n\n# -------------------------- reporter flask ------------------------------\n\n@app.route('/Reporter/ReporterJSON/', methods=['GET'])\ndef api_report_json(idC):\n summary = Reporter().reportSummary(idC)\n if summary == 404:\n return Response(status=404)\n elif summary == 412:\n return Response(status=412)\n return jsonify(summary)\n\n\n@app.route('/Reporter/ReporterRAW/', methods=['GET'])\ndef api_report_raw(idC):\n data = Reporter().reportRawData(idC)\n if data == 404:\n return Response(status=404)\n elif data == 412:\n return Response(status=412)\n return jsonify(data)\n\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0')\n","sub_path":"campaign_api_flask.py","file_name":"campaign_api_flask.py","file_ext":"py","file_size_in_byte":2975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"247643017","text":"##\n# Copyright (c) 2015, Derek Ruths, David Jurgens\n#\n# All rights reserved. See LICENSE file for details\n##\nimport argparse\nimport json\nimport os, os.path\nimport gzip\nimport time\n\nfrom slp.build_dataset import posts2dataset\nfrom slp.sparse_dataset import SparseDataset\nfrom slp.spatial_label_propagation import SpatialLabelPropagation\n\ndef train(args):\n parser = argparse.ArgumentParser(prog='geoinf train',description='train a geoinference method on a specific dataset')\n parser.add_argument('-f','--force',help='overwrite the output model directory if it already exists')\n parser.add_argument('method_name',help='the method to use')\n parser.add_argument('method_settings',help='a json file containing method-specific configurations')\n parser.add_argument('dataset_dir',help='a directory containing a geoinference dataset')\n parser.add_argument('model_dir',help='a (non-existing) directory where the trained model will be stored')\n parser.add_argument('--location-source', nargs=1,\n help='specifies the source of ground-truth locations')\n\n args = parser.parse_args(args)\n\n if os.path.exists(args.model_dir):\n question = \"Would you like to remove the existing model directory %s?\" % args.model_dir\n if input(question+' (y/n): ').lower().strip() == \"y\":\n print(\"Removing existing model directory...\")\n os.system(\"rm -r %s\" % args.model_dir)\n else:\n raise Exception('dataset directory %s exists' % args.model_dir)\n\n print('creating directory %s' % args.model_dir)\n os.mkdir(args.model_dir)\n\n # # confirm that the output directory doesn't exist\n # if os.path.exists(args.model_dir) and not args.force:\n # raise Exception('output model_dir cannot exist')\n\n # load the method\n # method = get_method_by_name(args.method_name)\n\n # load the data\n with open(args.method_settings,'r') as fh:\n settings = json.load(fh)\n\n location_source = args.location_source\n if location_source:\n location_source = location_source[0]\n print('Using %s as the source of ground truth location'\n % location_source)\n settings['location_source'] = location_source\n\n\n\n # load the dataset\n ds = None #Dataset(args.dataset_dir)\n if not location_source is None:\n ds = SparseDataset(args.dataset_dir, default_location_source=location_source, settings=settings)\n else:\n ds = SparseDataset(args.dataset_dir, settings=settings)\n\n\n # load the method\n # method = get_method_by_name(args.method_name)\n # method_inst = method()\n method_inst = SpatialLabelPropagation(settings)\n\n print(\"Starting\")\n start_time = time.time()\n method_inst.train_model(settings,ds,args.model_dir)\n end_time = time.time()\n print('Trained model %s on dataset %s in %f seconds'\n % (args.method_name, args.dataset_dir, end_time - start_time))\n\n # drop some metadata into the run method\n # run the method\n # gi_inst = method()\n # gi_inst.train(settings,ds,args.model_dir)\n\n return\n\ndef build_dataset(args):\n parser = argparse.ArgumentParser(prog='geoinf build_dataset',description='build a new dataset')\n parser.add_argument('dataset_dir',help='the directory to put the dataset in')\n parser.add_argument('posts_file',help='the posts.json.gz file to use')\n parser.add_argument('user_id_field',help='the field name holding the user id of the post author')\n parser.add_argument('mention_field',help='the field name holding the list of user ids mentioned in a post (or the friends of a user, those they follow)')\n parser.add_argument('follow_field',help='the field name holding the list of user ids following the given user', nargs='?', type=str, default=None)\n\n args = parser.parse_args(args)\n\n uid_field_name = args.user_id_field.split('.')[::-1]\n mention_field_name = args.mention_field.split('.')[::-1]\n posts2dataset(args.dataset_dir,args.posts_file, args.user_id_field, args.mention_field, args.follow_field)\n\n # done\n\ndef main():\n parser = argparse.ArgumentParser(prog='geoinf',description='run a spatial label propagation method on a dataset')\n parser.add_argument('action',choices=['train','build_dataset'],\n help='indicate whether to train the model or create a dataset')\n parser.add_argument('action_args',nargs=argparse.REMAINDER,\n help='arguments specific to the chosen action')\n\n args = parser.parse_args()\n\n try:\n if args.action == 'train':\n train(args.action_args)\n elif args.action == 'build_dataset':\n build_dataset(args.action_args)\n else:\n raise Exception('unknown action: %s' % args.action)\n\n except Exception as e:\n print(e)\n\n # done!\n\nif __name__ == '__main__':\n main()\n\n\n","sub_path":"canadian_user_identification/spatial_label_propagation/slp/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"430410109","text":"# coding=utf8\n\n# Copyright 2018 JDCLOUD.COM\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# NOTE: This class is auto generated by the jdcloud code generator program.\n\n\nclass RedirectAction(object):\n\n def __init__(self, protocol=None, port=None, host=None, path=None, query=None, statusCode=None):\n \"\"\"\n :param protocol: (Optional) 重定向后协议,取值为Http、Https。不设置,表示重定向不修改请求协议,与客户端请求协议一致\n :param port: (Optional) 重定向后端口,取值范围为1-65535。不设置,表示重定向不修改请求端口,与客户端请求端口一致\n :param host: (Optional) 重定向后域名。不设置,表示重定向不修改请求域名,与客户端请求域名一致。支持输入IPv4地址和域名。域名输入限制为:仅支持输入大小写字母、数字、英文中划线“-”和点“.”,最少包括一个点\".\",不能以点\".\"和中划线\"-\"开头或结尾,中划线\"-\"前后不能为点\".\",不区分大小写,且不能超过110字符\n :param path: (Optional) 重定向后URL路径。不设置,表示重定向不修改请求URL路径,与客户端请求URL路径一致。必须以/开头,仅支持输入大小写字母、数字和特殊字符:$-_.+!'()%:@&=/,区分大小写,且不能超过128字符\n :param query: (Optional) 重定向后查询参数,不需手动输入,系统默认添加,不超过128字符,不设置,表示重定向不修改查询参数,与客户端请求查询参数一致\n :param statusCode: (Optional) 取值为http_301、http_302。301表示永久性转移,302表示暂时性转移\n \"\"\"\n\n self.protocol = protocol\n self.port = port\n self.host = host\n self.path = path\n self.query = query\n self.statusCode = statusCode\n","sub_path":"jdcloud_sdk/services/lb/models/RedirectAction.py","file_name":"RedirectAction.py","file_ext":"py","file_size_in_byte":2369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"134622089","text":"import os.path\r\n\r\n\r\n\r\nclass OntoFileUtils:\r\n #属性定义\r\n def __init__(self):\r\n self.filename = \"\"\r\n\r\n #创建OWL文件\r\n # 输入:filename:创建本体文件名\r\n # 无返回\r\n def createOntoFile(self):\r\n if os.path.exists(self.filename) :\r\n print(\"This File Has Exited\")\r\n f = open(self.filename, 'r', encoding='utf-8')\r\n content = f.readlines()\r\n if len(content) == False:\r\n print('This file is empty')\r\n #文件存在但文件为空\r\n flag = 0\r\n #文件存在,且文件不为空\r\n else: flag = 1\r\n #文件不存在\r\n else: flag = 0\r\n if flag == 0:\r\n RDFHead = \"\\n\"\r\n RDFContend = \"\\n\"\r\n OWLHead = \" \\n\"\r\n sectionLabel = \"\\n\"\r\n RDFEnd = \" \"\r\n Content = RDFHead + RDFContend + OWLHead + sectionLabel + RDFEnd\r\n # Content = RDFHead + RDFContend + OWLHead + RDFEnd\r\n print(Content)\r\n f = open(self.filename, 'w+', encoding='utf-8')\r\n f.write(Content)\r\n f.close()\r\n\r\n\r\n # 创建owl文件中的本体\r\n # 输入:Name:本体类名\r\n # ProClassName :该本体父类名\r\n # 返回:RDF文件内容,String\r\n # 例:\r\n # \r\n # \r\n # \r\n def addOntoClass(self,Name, ProClassName):\r\n head = \"\\n\"\r\n if ProClassName == 'Thing':\r\n content = \" \\n\"\r\n else:\r\n content = \" \\n\"\r\n end = \" \\n\"\r\n sectionLabel = \"\\n\"\r\n #final = \"\"\r\n resource = head + content + end +sectionLabel\r\n # resource = head + content + end\r\n print(resource)\r\n return resource\r\n\r\n #创建owl文件中的本体关系\r\n # 输入:RelationName:本体关系名\r\n # Domain :领域本体名\r\n # RangeList:子关系类列表\r\n # 返回:RDF文件内容,String\r\n # 例:\r\n # \r\n # \r\n # \r\n # \r\n def addOntoRelat(self,RelationName,Domain,RangeList):\r\n head = \"\\n\"\r\n domainContent = \" \\n\"\r\n rangeContent = \"\"\r\n for Range in RangeList:\r\n #print(RangeList[i])\r\n rangeContent += \" \\n\"\r\n #print(rangeContent)\r\n end = \" \\n\"\r\n sectionLabel = \"\\n\"\r\n #final = \"\"\r\n resource = head+domainContent+rangeContent+end+sectionLabel\r\n #resource = head+domainContent+rangeContent+end\r\n print(resource)\r\n return resource\r\n\r\n #删除OWL文件中的本体\r\n #本身的删除、子对象的删除、关系的删除\r\n def delOntoClass(self,className):\r\n contentLists = self.splitOntoFile()\r\n for i in range(len(contentLists)):\r\n if className in contentLists[i]:\r\n contentLists[i] = \"\\n\"\r\n print(\"已删除\")\r\n else:\r\n print(\"未删除\")\r\n string = \"\"\r\n for content in contentLists:\r\n string += content\r\n print(string)\r\n f = open(self.filename, 'w', encoding='utf-8')\r\n f.write(string)\r\n f.close()\r\n\r\n\r\n #onto文件写入操作\r\n #将编辑好的RDF内容写入文件\r\n def writeContent(self,resource):\r\n f = open(self.filename, 'r', encoding='utf-8')\r\n lines = f.readlines()\r\n resource += \"\"\r\n lines[-1] = resource\r\n f.close()\r\n f = open(self.filename, 'w', encoding='utf-8')\r\n print('Write Success!')\r\n f.truncate()\r\n for line in lines:\r\n f.write(line)\r\n f.close()\r\n\r\n #onto文本切割\r\n #按照空行进行切分\r\n def splitOntoFile(self):\r\n f = open(self.filename, 'r', encoding='utf-8')\r\n string = f.read()\r\n contentlists = string.split('\\n')\r\n return contentlists\r\n\r\n\r\n\r\n#测试代码\r\nif __name__ == '__main__':\r\n filepath = '../owl/4.owl'\r\n ontoFile = OntoFileUtils()\r\n ontoFile.filename = filepath\r\n ontoFile.createOntoFile()\r\n #本体类创建\r\n content = \"\"\r\n # content += ontoFile.addOntoClass('治疗', 'Thing')\r\n # content += ontoFile.addOntoClass('检查', 'Thing')\r\n # content += ontoFile.addOntoClass('OFPG', '检查')\r\n # content += ontoFile.addOntoClass('血糖检查', '检查')\r\n #content += ontoFile.addOntoClass('方案', '治疗')\r\n #关系创建\r\n # RelationName = \"isMemberof\"\r\n # Domain = \"检查\"\r\n # RangeList = [\"OFPG\", \"血糖检查\"]\r\n # content += ontoFile.addOntoRelat(RelationName,Domain,RangeList)\r\n\r\n #写操作\r\n #ontoFile.writeContent(content)\r\n #删除\r\n ontoFile.delOntoClass('治疗')","sub_path":"app/utils/OntoFileUtils.py","file_name":"OntoFileUtils.py","file_ext":"py","file_size_in_byte":5887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"634161500","text":"import json\nfrom google.cloud import storage\n\n\ndef _resolve_path(obj, path):\n ret = obj\n\n for p in path:\n if isinstance(p, int):\n if p < len(ret):\n ret = ret[p]\n else:\n return None\n elif p in ret:\n ret = ret[p]\n else:\n return None\n\n return ret\n\n\ndef _resolve_app_msgs(obj):\n lines = _resolve_path(obj, [\"protoPayload\", \"line\"])\n if lines is None:\n return None\n else:\n msgs = map(lambda l: l[\"logMessage\"], lines)\n return \"\\n\\n>===<\\n\\n\".join(msgs)\n\n\ndef preprocess_log(fp):\n fd = open(fp)\n text = fd.read()\n fd.close()\n return preprocess_log_str(text)\n\n\ndef preprocess_log_str(text):\n text = text.replace(\"}\\n\", \"},\\n\", text.count(\"}\\n\") - 1)\n return json.loads(f\"[{text}]\")\n\n\ndef parse_log_str(log, paths=[], regex_func=None, include_msg=True):\n\n paths_list = [p.split(\".\") for p in paths]\n out = []\n for line in log:\n msg = _resolve_app_msgs(line)\n\n if msg is None:\n continue\n\n row = [_resolve_path(line, p) for p in paths_list]\n if regex_func is not None:\n matches = regex_func(msg)\n if matches is None:\n continue\n row.extend(regex_func(msg))\n\n if include_msg:\n row.append(msg)\n\n out.append(row)\n\n return out\n\n\ndef parse_log_storage(bucket_name, bucket_prefix, log_paths=[],\n regex_func=None, include_msg=True):\n client = storage.Client()\n ret = []\n for blob in client.list_blobs(bucket_name, prefix=bucket_prefix):\n ret.extend(parse_log_str(\n preprocess_log_str(blob.download_as_string().decode(\"utf-8\")),\n log_paths, regex_func, include_msg))\n\n return ret\n","sub_path":"ix/google_ext/gae.py","file_name":"gae.py","file_ext":"py","file_size_in_byte":1621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"56171064","text":"from flask import Flask, jsonify, json\nimport plotly.graph_objs as go\nfrom plotly.utils import PlotlyJSONEncoder\nimport json\nimport requests\nimport requests_cache\n\n\napp = Flask(__name__)\n\nkey = '31d1aba5-0d2c-462f-90ff-fb20ce66918e'\n\ndef __init__(self, key):\n self.key = key\n@app.route('/Hol', methods=['GET'])\ndef holidays():\n url = 'https://holidayapi.com/v1/holidays?'\n\n if parameters.has_key('key') is False:\n parameters['key'] = self.key\n\n response = requests.get(url, params=parameters);\n data = json.loads(response.text)\n\n if response.status_code != 200:\n if data.has_key('error') is False:\n data['error'] = 'Unknown error.'\n\n return data\n\nif __name__ == '__main__':\n\tapp.run(debug=True)","sub_path":"Holidays.py","file_name":"Holidays.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"639865545","text":"normalizing_dictionary = {\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 # ('','','',''):'',\n # ('','','',''):'',\n # ('','','',''):'',\n ('رَ', 'رّ', 'رِ', 'رُ'): 'ر',\n\n ('یُ', 'یِ', 'یَ', 'یّ'): 'ی',\n}\n\ntokenizing_dictionary = { # for a single tuple use a comma to avoid unwanted casting. e.g. ('می سی سی پی', )\n ('می سی سی پی',): 'میسیسیپی', # fixes می سی سی پی\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 # 'مع ذلک':'معذلک',\n}\n\nverbs = {\n (' می ',): ' می', # no problem with آکادمی\n (' ام ', ' ام.', ' ام،', ' ام:'): 'ام ', # dot, comma, and ... will be eliminated as stop words.\n (' ای ', ' ای.', ' ای،', ' ای:'): 'ای ',\n (' ایم ', ' ایم.', ' ایم،', ' ایم:'): 'ایم ',\n (' اید ', ' اید.', ' اید،', ' اید:'): 'اید ',\n (' اند ', ' اند.', ' اند،', ' اند:'): 'اند ',\n\n}\n\ncasefolding = {\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 'چاووش': 'چاوش',\n 'داوود': 'داود',\n 'انظباط': 'انضباط',\n 'امپراطور': 'امپراتور',\n 'طاسکباب': 'تاسکباب',\n 'چلقوز': 'چلغوز',\n 'قورمه': 'قرمه',\n 'لاطاری': 'لاتاری',\n # '':'',\n}\n\nabbreviations = {\n 'ج.ا.': 'جمهوری اسلامی',\n 'آ.د.ک': 'آیین دادرسی کیفری',\n 'آبفا': 'آبوفاضلاب',\n 'آپ': 'آسان پرداخت',\n 'اتکا': 'اداره تدارکات کادر ارتش',\n # '':'',\n # http://www.mokhafaf.com/word/%DA%A9%D9%84%D9%85%D8%A7%D8%AA-%D9%81%D8%A7%D8%B1%D8%B3%D9%8A/\n # https://article.tebyan.net/281258/%D8%A7%D8%AE%D8%AA%D8%B5%D8%A7%D8%B1%D8%A7%D8%AA-%D9%88-%D8%A2%D8%BA%D8%A7%D8%B2%D9%87-%D9%87%D8%A7-%D8%AF%D8%B1-%D8%B2%D8%A8%D8%A7%D9%86-%D9%81%D8%A7%D8%B1%D8%B3%DB%8C\n}\n\n'''\nplurals = {\n 'آداب':'ادب',\n 'اطراف':'طرف',\n 'حقایق':'حقیقت',\n 'امواج':'موج',\n # 'ادبا\tادیب\n # 'اعماق\tعمق\n # 'خزائن\tخزینه\n # 'مراکز\tمرکز\n # 'آثار\tاثر\n # 'علما\tعالم\n # 'اخبار\tخبر\n # 'مواقع\tموقع\n # اسرا\tسر\n # علوم\tعلم\n # ادوار\tدور\n # مصارف\tمصرف\n # اسامی\tاسم\n # علائم\tعلامت\n # ادیان\tدین\n # معارف\tمعرفت\n # اساطیر\tاسطوره\n # علل\t\tعلت\n # دفاتر\tدفتر\n # مباحث\tمبحث\n # امرا\tامیر\n # عقائد\tعقیده\n # ذخایر\tذخیره\n # مواد\tماده\n # اوامر\tامور\n # اعمال\tعمل\n # رفقا\tرفیق\n # مذاهب\tمذهب\n # ائمه\tامام\n # اعیاد\tعید\n # آرا\t\tرای\n # مصائب\tمصیبت\n # اصول\tاصل\n # عناصر\tعنصر\n # رسوم\tرسم\n # معابد\tمعبد\n # آفاق\tافق\n # عواطف\tعاطفه\n # روابط\tرابطه\n # مساجد\tمسجد\n # ابیات\tبیت\n # اعضا\tعضو\n # رموز\tرمز\n # معابر\tمعبر\n # تجار\t\tتاجر\n # عبارات\tعبارت\n # رجال\tرجل\n # مظاهر\tمظهر\n # تصاویر\tتصویر\n # عجایب\tعجیبه\n # ارقام\tرقم\n # اجداد\tجد\n # فقها\tفقیه\n # زوایا\tزاویه\n # امراض\tمرض\n # جوانب\tجانب\n # فنون\tفن\n # زعما\tزعیم\n # موارد\tموزد\n # جزایر\tجزیره\n # افکار\tفکر\n # سوانح\tسانحه\n # مراحل\tمرحله\n # جبال\tجبل\n # فرایض\tفریضه\n # سلاطین\tسلطان\n # مفاهیم\tمفهوم\n # جرایم\tجریمه\n # افعال\tفعل\n # اشعار\tشعر\n # منابع\tمنبع\n # حوادث\tحادثه\n # فقرا\tفقیر\n # شعرا\tشاعر\n # اماکن\tمکان\n # احشام\tحشم\n # قواعد\tقاعده\n # آثار\tاثر\n # احوال \tحال\n # اخلاق \tخلق\n # ارکان \tرکن\n # اسرار \tسر\n # اشیا \tشی\n # اصول \tاصل\n # اعضا \tعضو\n # افراد \tفرد\n # افکار \tفکر\n # اقوام\tقوم\n # اوقات \tوقت\n # تصاویر \tتصویر\n # تعالیم \tتعلیم\n # تماثیل \tتمثیل\n # حقوق \tحق\n # حواس \tحس\n # خاطرات \tخاطره\n # خرافات\tخارفه\n # دلایل \tدلیل\n # شمایل \tشمیله\n # عناصر \tعنصر\n # عوامل\tعامل\n # فضایل \tفضیلت\n # کلمات \tکلمه\n # مجالس \tمجلس\n # مطالب \tمطلب\n # مظاهر \tمظهره\n # مفاهیم \tمفهوم\n # منابع \tمنبع\n # نشریات\tنشریه\n # نیّات \tنیت\n # وظایف \tوظیفه\n # فلاسفه\tفلاس\n # مذاکرات\tمذاکره\n # معاملات\tمعامله\n # ادارات\tاداره\n # ضربات\tضربه\n # حملات\tحمله\n # جزِئیات\tجزء\n # دخانیات\tدخان\n # شایعات\tشایعه\n # عنایات\tعنایت\n # اموال\tمال\n} \n'''\n","sub_path":"Phase1/search/code/dictionaries.py","file_name":"dictionaries.py","file_ext":"py","file_size_in_byte":7955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"396207005","text":"import sys\n\nfrom flask import current_app, flash, Flask, Markup, redirect, render_template\nfrom flask import request, url_for\nimport logging\n\n\nimport bucket\nimport datastore\n\napp = Flask(__name__)\nCERTS = None\nAUDIENCE = None\napp.config.update(\n ALLOWED_EXTENSIONS=set(['png', 'jpg']),\n BUCKET_NAME='lambda-functions-gcp-raw-images',\n DS_ENTITY_KEY='image-metadata'\n)\n\n# Following functions [certs, get_metadata, audience, validate_assertion]\n# are used here on Apache 2.0 license, source: \n# https://github.com/GoogleCloudPlatform/getting-started-python/tree/master/authenticating-users\n\n\ndef certs():\n \"\"\"Returns a dictionary of current Google public key certificates for\n validating Google-signed JWTs. Since these change rarely, the result\n is cached on first request for faster subsequent responses.\n \"\"\"\n import requests\n\n global CERTS\n if CERTS is None:\n response = requests.get(\n 'https://www.gstatic.com/iap/verify/public_key'\n )\n CERTS = response.json()\n return CERTS\n\n\ndef get_metadata(item_name):\n \"\"\"Returns a string with the project metadata value for the item_name.\n See https://cloud.google.com/compute/docs/storing-retrieving-metadata for\n possible item_name values.\n \"\"\"\n import requests\n\n endpoint = 'http://metadata.google.internal'\n path = '/computeMetadata/v1/project/'\n path += item_name\n response = requests.get(\n '{}{}'.format(endpoint, path),\n headers={'Metadata-Flavor': 'Google'}\n )\n metadata = response.text\n return metadata\n\n\ndef audience():\n \"\"\"Returns the audience value (the JWT 'aud' property) for the current\n running instance. Since this involves a metadata lookup, the result is\n cached when first requested for faster future responses.\n \"\"\"\n global AUDIENCE\n if AUDIENCE is None:\n project_number = get_metadata('numeric-project-id')\n project_id = get_metadata('project-id')\n AUDIENCE = '/projects/{}/apps/{}'.format(\n project_number, project_id\n )\n return AUDIENCE\n\n\ndef validate_assertion(assertion):\n \"\"\"Checks that the JWT assertion is valid (properly signed, for the\n correct audience) and if so, returns strings for the requesting user's\n email and a persistent user ID. If not valid, returns None for each field.\n \"\"\"\n from jose import jwt\n\n try:\n info = jwt.decode(\n assertion,\n certs(),\n algorithms=['ES256'],\n audience=audience()\n )\n return info['email'], info['sub']\n except Exception as e:\n print('Failed to validate assertion: {}'.format(e), file=sys.stderr)\n return None, None\n\n\n@app.route('/logout', methods=['GET'])\ndef logout():\n \"\"\"\n Logs the user out from the IAP.\n\n https://stackoverflow.com/questions/47329783/google-cloud-identity-aware-proxy-iap-force-logout\n \"\"\"\n return redirect(\"/_gcp_iap/clear_login_cookie\", code=302)\n\n\ndef upload_image(id, img):\n public_url = bucket.upload_file(\n id,\n img.read(),\n img.filename,\n img.content_type\n )\n logging.info(f\"Image uploaded {public_url}\")\n return public_url\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef front_page():\n \"\"\"\n Returns front page as a GET request after authenticating\n the user using GCP IAP.\n\n User can upload their image using POST request.\n \"\"\"\n assertion = request.headers.get('X-Goog-IAP-JWT-Assertion')\n email, id = validate_assertion(assertion)\n if email is None or id is None:\n return logout()\n\n if request.method == 'POST':\n image = request.files.get('image')\n image_key = upload_image(id, image)\n image.seek(0)\n datastore.write(id, email, image.filename, image_key, image.read())\n return render_template('success.html', email=email, filename=image.filename)\n\n return render_template('view.html', email=email)\n","sub_path":"frontend/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"270877582","text":"# -*- coding: utf-8 -*-\n\n# Copyright 2013 Mirantis, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\nfrom oslo_serialization import jsonutils\n\nfrom nailgun import objects\n\nfrom nailgun.db.sqlalchemy.models import Cluster\nfrom nailgun.db.sqlalchemy.models import ClusterChanges\nfrom nailgun.test.base import BaseIntegrationTest\nfrom nailgun.test.base import fake_tasks\nfrom nailgun.utils import reverse\n\n\nclass TestClusterChanges(BaseIntegrationTest):\n\n def tearDown(self):\n self._wait_for_threads()\n super(TestClusterChanges, self).tearDown()\n\n def test_cluster_creation_adds_pending_changes(self):\n self.env.create_cluster(api=True)\n attributes_changes = self.db.query(ClusterChanges).filter_by(\n name=\"attributes\"\n ).all()\n self.assertEqual(len(attributes_changes), 1)\n networks_changes = self.db.query(ClusterChanges).filter_by(\n name=\"networks\"\n ).all()\n self.assertEqual(len(networks_changes), 1)\n vmware_changes = self.db.query(ClusterChanges).filter_by(\n name=\"vmware_attributes\"\n ).all()\n self.assertEqual(len(vmware_changes), 1)\n all_changes = self.db.query(ClusterChanges).all()\n self.assertEqual(len(all_changes), 3)\n\n def test_node_volumes_modification_adds_pending_changes(self):\n cluster = self.env.create_cluster(api=True)\n self.env.create_node(\n api=True,\n cluster_id=cluster[\"id\"]\n )\n node_db = self.env.nodes[0]\n node_disks_changes = self.db.query(ClusterChanges).filter_by(\n name=\"disks\",\n node_id=node_db.id\n ).all()\n self.assertEqual(len(node_disks_changes), 1)\n resp = self.app.get(\n reverse(\n 'ClusterHandler',\n kwargs={'obj_id': cluster['id']}),\n headers=self.default_headers\n )\n self.assertIn(\n {\"name\": \"disks\", \"node_id\": node_db.id},\n resp.json_body[\"changes\"]\n )\n\n def test_node_volumes_clears_after_deletion_from_cluster(self):\n cluster = self.env.create_cluster(api=True)\n self.env.create_node(\n api=True,\n cluster_id=cluster[\"id\"]\n )\n node_db = self.env.nodes[0]\n node_disks_changes = self.db.query(ClusterChanges).filter_by(\n name=\"disks\",\n node_id=node_db.id\n ).all()\n self.assertEqual(len(node_disks_changes), 1)\n self.app.put(\n reverse('NodeCollectionHandler'),\n jsonutils.dumps([{\"id\": node_db.id, \"cluster_id\": None}]),\n headers=self.default_headers\n )\n self.env.refresh_clusters()\n node_disks_changes = self.db.query(ClusterChanges).filter_by(\n name=\"disks\",\n node_id=node_db.id\n ).all()\n self.assertEqual(len(node_disks_changes), 0)\n\n def test_attributes_changing_adds_pending_changes(self):\n cluster = self.env.create_cluster(api=True)\n cluster_db = self.env.clusters[0]\n objects.Cluster.clear_pending_changes(cluster_db)\n all_changes = self.db.query(ClusterChanges).all()\n self.assertEqual(len(all_changes), 0)\n self.app.put(\n reverse(\n 'ClusterAttributesHandler',\n kwargs={'cluster_id': cluster['id']}),\n jsonutils.dumps({\n 'editable': {\n \"foo\": \"bar\"\n }\n }),\n headers=self.default_headers\n )\n pending_changes = self.db.query(ClusterChanges).filter_by(\n name=\"attributes\"\n ).all()\n self.assertEqual(len(pending_changes), 1)\n\n def test_default_attributes_adds_pending_changes(self):\n cluster = self.env.create_cluster(api=True)\n cluster_db = self.env.clusters[0]\n objects.Cluster.clear_pending_changes(cluster_db)\n all_changes = self.db.query(ClusterChanges).all()\n self.assertEqual(len(all_changes), 0)\n self.app.put(\n reverse(\n 'ClusterAttributesDefaultsHandler',\n kwargs={'cluster_id': cluster['id']}),\n headers=self.default_headers\n )\n pending_changes = self.db.query(ClusterChanges).filter_by(\n name=\"attributes\"\n ).all()\n self.assertEqual(len(pending_changes), 1)\n\n @fake_tasks(override_state={\"progress\": 100, \"status\": \"ready\"})\n def test_successful_deployment_drops_all_changes(self):\n self.env.create(\n nodes_kwargs=[\n {\"api\": True, \"pending_addition\": True}\n ]\n )\n supertask = self.env.launch_deployment()\n self.env.wait_ready(supertask, 60)\n cluster_db = self.db.query(Cluster).get(\n self.env.clusters[0].id\n )\n self.assertEqual(list(cluster_db.changes), [])\n\n @fake_tasks()\n def test_failed_deployment_does_nothing_with_changes(self):\n cluster = self.env.create_cluster(api=True)\n self.env.create_node(\n cluster_id=cluster[\"id\"],\n status=\"error\",\n error_type=\"provision\"\n )\n supertask = self.env.launch_deployment()\n self.env.wait_error(supertask, 60)\n attributes_changes = self.db.query(ClusterChanges).filter_by(\n name=\"attributes\"\n ).all()\n self.assertEqual(len(attributes_changes), 1)\n networks_changes = self.db.query(ClusterChanges).filter_by(\n name=\"networks\"\n ).all()\n self.assertEqual(len(networks_changes), 1)\n vmware_changes = self.db.query(ClusterChanges).filter_by(\n name=\"vmware_attributes\"\n ).all()\n self.assertEqual(len(vmware_changes), 1)\n disks_changes = self.db.query(ClusterChanges).filter_by(\n name=\"disks\"\n ).all()\n self.assertEqual(len(disks_changes), 1)\n all_changes = self.db.query(ClusterChanges).all()\n self.assertEqual(len(all_changes), 5)\n\n @fake_tasks(override_state={\"progress\": 100, \"status\": \"ready\"})\n def test_role_unassignment_drops_changes(self):\n self.env.create(\n nodes_kwargs=[\n {\"pending_addition\": True, \"api\": True}\n ]\n )\n supertask = self.env.launch_deployment()\n self.env.wait_ready(supertask)\n new_node = self.env.create_node(\n cluster_id=self.env.clusters[0].id,\n pending_addition=True,\n api=True\n )\n self.app.put(\n reverse(\"NodeHandler\",\n kwargs={\"obj_id\": new_node[\"id\"]}),\n jsonutils.dumps({\n \"cluster\": None,\n \"pending_addition\": False,\n \"pending_roles\": []\n }),\n headers=self.default_headers\n )\n all_changes = self.db.query(ClusterChanges).filter_by(\n cluster_id=self.env.clusters[0].id,\n node_id=new_node[\"id\"]\n ).all()\n self.assertEqual(all_changes, [])\n","sub_path":"nailgun/nailgun/test/integration/test_changes_model.py","file_name":"test_changes_model.py","file_ext":"py","file_size_in_byte":7569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"366570235","text":"class ToDoList:\n def __init__(self, file_name):\n self.file_name = file_name\n self.tasks = self.load_file_into_list()\n\n def load_file_into_list(self):\n tasks = []\n with open(self.file_name, 'r') as file:\n for task in file:\n tasks.append(task.strip())\n return tasks\n\n def todo_list(self):\n for index, task in enumerate(self.tasks, start=1):\n print('{}) {}'.format(index, task))\n\n def write_into_file(self):\n with open(self.file_name, 'w') as file:\n for task in self.tasks:\n file.write('{}\\n'.format(task))\n\n def add_task(self, task):\n self.tasks.append(task)\n self.write_into_file()\n\n def done_task(self, task_index):\n task_exist = False\n for index, task in enumerate(self.tasks, start=1):\n if index == int(task_index):\n self.tasks.remove(task)\n print('{} completed.'.format(task))\n task_exist = True\n self.write_into_file()\n if not task_exist:\n print('There is no open task with index {}'.format(task_index))\n\ndef todo_help():\n print('\\nWelcome to To Do List App\\n')\n print('* Create new task: [todo Task]')\n print('* Mark a task as done: [done INDEX]')\n print('* See the to-do list: [list]\\n')\n\ndef run():\n todo_help()\n while True:\n todolist = ToDoList('todolist.txt')\n cmd_detail = input('Enter cmd: ')\n cmd = cmd_detail.split(' ',1)[0]\n if cmd == 'list':\n todolist.todo_list()\n elif cmd == 'todo':\n task = cmd_detail.split(' ',1)[1]\n todolist.add_task(task)\n elif cmd == 'done':\n task_index = cmd_detail.split(' ',1)[1]\n todolist.done_task(task_index)\n elif cmd == 'help':\n todo_help()\n elif cmd == 'exit':\n break\n","sub_path":"6.to do list.py","file_name":"6.to do list.py","file_ext":"py","file_size_in_byte":1918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"166971939","text":"# -*- coding: utf-8 -*-\n# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\nfrom __future__ import (absolute_import, division, print_function,\n unicode_literals)\n\nimport os\nimport shutil\n\nimport six\n\nfrom . import Command\nfrom ..benchmarks import Benchmarks\nfrom ..console import log\nfrom ..graph import Graph\nfrom ..machine import iter_machine_files\nfrom ..repo import get_repo\nfrom ..results import iter_results\nfrom .. import util\n\n\nclass Publish(Command):\n @classmethod\n def setup_arguments(cls, subparsers):\n parser = subparsers.add_parser(\n \"publish\", help=\"Collate results into a website\",\n description=\n \"\"\"\n Collate all results into a website. This website will be\n written to the ``html_dir`` given in the ``asv.conf.json``\n file, and may be served using any static web server.\"\"\")\n\n parser.set_defaults(func=cls.run_from_args)\n\n return parser\n\n @classmethod\n def run_from_conf_args(cls, conf, args):\n return cls.run(conf=conf)\n\n @classmethod\n def run(cls, conf):\n params = {}\n graphs = {}\n date_to_hash = {}\n machines = {}\n benchmark_names = set()\n\n log.set_nitems(5)\n\n if os.path.exists(conf.html_dir):\n shutil.rmtree(conf.html_dir)\n\n benchmarks = Benchmarks.load(conf)\n\n template_dir = os.path.join(\n os.path.dirname(os.path.abspath(__file__)), '..', 'www')\n shutil.copytree(template_dir, conf.html_dir)\n\n log.step()\n log.info(\"Loading machine info\")\n with log.indent():\n for path in iter_machine_files(conf.results_dir):\n d = util.load_json(path)\n machines[d['machine']] = d\n\n log.step()\n log.info(\"Loading results\")\n with log.indent():\n for results in iter_results(conf.results_dir):\n log.dot()\n date_to_hash[results.date] = results.commit_hash[\n :conf.hash_length]\n\n for key, val in six.iteritems(results.params):\n params.setdefault(key, set())\n params[key].add(val)\n\n for key, val in six.iteritems(results.results):\n benchmark_names.add(key)\n graph = Graph(key, results.params, params)\n if graph.path in graphs:\n graph = graphs[graph.path]\n else:\n graphs[graph.path] = graph\n graph.add_data_point(results.date, val)\n\n log.step()\n log.info(\"Generating graphs\")\n with log.indent():\n for graph in six.itervalues(graphs):\n log.dot()\n graph.save(conf.html_dir)\n\n log.step()\n log.info(\"Getting tags\")\n with log.indent():\n repo = get_repo(conf)\n tags = {}\n for tag in repo.get_tags():\n log.dot()\n tags[tag] = repo.get_date_from_tag(tag)\n\n log.step()\n log.info(\"Writing index\")\n benchmark_map = dict(benchmarks)\n for key, val in six.iteritems(params):\n val = list(val)\n val.sort(key=lambda x: x or '')\n params[key] = val\n util.write_json(os.path.join(conf.html_dir, \"index.json\"), {\n 'project': conf.project,\n 'project_url': conf.project_url,\n 'show_commit_url': conf.show_commit_url,\n 'date_to_hash': date_to_hash,\n 'params': params,\n 'benchmarks': benchmark_map,\n 'machines': machines,\n 'tags': tags\n })\n","sub_path":"asv/commands/publish.py","file_name":"publish.py","file_ext":"py","file_size_in_byte":3717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"99365368","text":"import argparse\r\nfrom Bio import SeqIO\r\n\r\n\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument('--threshold', type=int, default=25, help='threshold quality that would not be cut', required=True)\r\nparser.add_argument('--file', help='reads fastq format', required=True)\r\nparser.add_argument('--out', type=str, required=True)\r\nargs = parser.parse_args()\r\n\r\n\r\ndef trimming(f, thresh, outfile):\r\n \"\"\"\r\n trims the edges of the sequence with quality below the threshold\r\n \"\"\"\r\n reads = SeqIO.parse(f, 'fastq')\r\n for read in reads:\r\n start = []\r\n for i in enumerate(read.seq):\r\n i = i[0]\r\n if read.letter_annotations[\"phred_quality\"][i] >= thresh:\r\n start.append(i)\r\n try:\r\n sub_rec = read[min(start): max(start)+1]\r\n with open(outfile) as out:\r\n out.write(sub_rec.format(\"fastq\"))\r\n except ValueError:\r\n pass\r\n\r\n\r\nif __name__ == \"__main__\":\r\n print(\"***** trimming started *****\")\r\n trimming(args.file, args.threshold, args.out)\r\n print(\"***** trimming completed *****\")\r\n","sub_path":"ДЗ№20/trimmonatik.py","file_name":"trimmonatik.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"653685987","text":"##############################################################################\n#\n# Copyright (c) 2003, 2004 Zope Corporation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\n\"\"\"Functional tests for File.\n\n$Id: ftests.py 25177 2004-06-02 13:17:31Z jim $\n\"\"\"\nimport unittest\nfrom xml.sax.saxutils import escape\nfrom StringIO import StringIO\n\nfrom zope.app.tests.functional import BrowserTestCase\nfrom zope.app.file.file import File\n\nclass FileTest(BrowserTestCase):\n\n content = u'File ' \n\n def addFile(self):\n file = File(self.content)\n root = self.getRootFolder()\n root['file'] = file\n self.commit()\n\n def testAddForm(self):\n response = self.publish(\n '/+/zope.app.file.File=',\n basic='mgr:mgrpw')\n self.assertEqual(response.getStatus(), 200)\n body = response.getBody()\n self.assert_('Add a File' in body)\n self.assert_('Content Type' in body)\n self.assert_('Data' in body)\n self.assert_('Object Name' in body)\n self.assert_('\"Add\"' in body)\n self.checkForBrokenLinks(body, '/+/zope.app.file.File=',\n 'mgr:mgrpw')\n\n def testAdd(self):\n response = self.publish(\n '/+/zope.app.file.File=',\n form={'type_name': u'zope.app.file.File',\n 'field.contents.data': StringIO('A file'),\n 'field.contents.mimeType': u'',\n 'field.contents.encoding': u'',\n 'add_input_name': u'file',\n 'UPDATE_SUBMIT': u'Add'},\n basic='mgr:mgrpw')\n\n self.assertEqual(response.getStatus(), 302)\n self.assertEqual(response.getHeader('Location'),\n 'http://localhost/@@contents.html')\n root = self.getRootFolder()\n self.assert_('file' in root)\n file = root['file']\n self.assertEqual(file.data, 'A file')\n\n def testEditForm(self):\n self.addFile()\n response = self.publish(\n '/file/fileedit.html',\n basic='mgr:mgrpw')\n self.assertEqual(response.getStatus(), 200)\n body = response.getBody()\n self.assert_('Change a text file' in body)\n self.assert_('Content Type' in body)\n self.assert_('Data' in body)\n self.assert_(escape(self.content) in body)\n self.checkForBrokenLinks(body, '/file/@@fileedit.html', 'mgr:mgrpw')\n\n def testEdit(self):\n self.addFile()\n response = self.publish(\n '/file/fileedit.html',\n form={'field.contents.data': 'A File ',\n 'field.contents.mimeType': 'text/plain',\n 'field.contents.encoding': '',\n 'UPDATE_SUBMIT': u'Change'},\n basic='mgr:mgrpw')\n\n self.assertEqual(response.getStatus(), 200)\n body = response.getBody()\n self.assert_('Change a text file' in body)\n self.assert_('Content Type' in body)\n self.assert_('Data' in body)\n self.assert_(escape(u'A File ') in body)\n root = self.getRootFolder()\n file = root['file']\n self.assertEqual(file.open('r').read(), 'A File ')\n self.assertEqual(file.getMimeType(), 'text/plain')\n\n def testUploadForm(self):\n self.addFile()\n response = self.publish(\n '/file/@@fileupload.html',\n basic='mgr:mgrpw')\n self.assertEqual(response.getStatus(), 200)\n body = response.getBody()\n self.assert_('Encoding Type' in body)\n self.assert_('Content Type' in body)\n self.assert_('Data' in body)\n self.failIf(escape(self.content) in body)\n self.checkForBrokenLinks(body, '/file/@@fileupload.html', 'mgr:mgrpw')\n\n def testUpload(self):\n self.addFile()\n response = self.publish(\n '/file/@@fileupload.html',\n basic='mgr:mgrpw',\n form={'field.contents.data': StringIO('New file'),\n 'field.contents.mimeType': u'',\n 'field.contents.encoding': u'',\n 'add_input_name': u'file',\n 'UPDATE_SUBMIT': u'Add'})\n self.assertEqual(response.getStatus(), 200)\n body = response.getBody()\n self.assert_('Encoding Type' in body)\n self.assert_('Content Type' in body)\n self.assert_('Data' in body)\n self.failIf(escape(u'New File ') in body)\n root = self.getRootFolder()\n file = root['file']\n self.assertEqual(file.open('r').read(), 'New file ')\n self.assertEqual(file.getMimeType(), 'text/plain')\n \n def testIndex(self):\n self.addFile()\n response = self.publish(\n '/file/@@index.html',\n basic='mgr:mgrpw')\n self.assertEqual(response.getStatus(), 200)\n body = response.getBody()\n self.assertEqual(body, self.content)\n self.checkForBrokenLinks(body, '/file/@@index.html', 'mgr:mgrpw')\n\n def testPreview(self):\n self.addFile()\n response = self.publish(\n '/file/@@preview.html',\n basic='mgr:mgrpw')\n self.assertEqual(response.getStatus(), 200)\n body = response.getBody()\n self.assert_('
\n \n \n \n \n ''', \"html.parser\")\n\n cls.css_select_soup = BeautifulSoup(\n '''\n \n \n \n \n Here is my styled paragraph
\n \n \n \n ''', \"html.parser\")\n\n\n\n ##Directly defined tags, to compare with BS output.\n\n #a generic anchor tag for append testing\n cls.an_append_tag = cls.soup.new_tag(\"a\")\n cls.an_append_tag.string = \"Foo\"\n cls.an_appended_tag = cls.soup.new_tag(\"a\")\n cls.an_appended_tag.string = \"FooBar\"\n\n #a generic anchor tag\n cls.a_tag = cls.soup.new_tag(\"a\") \n cls.a_tag.string = \"An anchor tag\"\n\n #First, second, third anchor\n cls.a_tag_first = cls.soup.new_tag(\"a\") \n cls.a_tag_first.string = \"First anchor tag\"\n\n cls.a_tag_second = cls.soup.new_tag(\"a\") \n cls.a_tag_second.string = \"Second anchor tag\"\n\n cls.a_tag_third = cls.soup.new_tag(\"a\") \n cls.a_tag_third.string = \"Third anchor tag\"\n\n #a-tag with id\n cls.a_tag_id = cls.soup.new_tag(\"a\", id=\"my_link\") \n\n #p-tag with class attribute\n cls.p_tag_css = cls.soup.new_tag(\"p\", **{'class':'my_CSS_class'})\n cls.p_tag_css.string = \"Here is my styled paragraph\"\n\n #tag with no name\n cls.no_name_tag = cls.soup.new_tag(\"\")\n\n\n def test_soup_contents(self):\n ''' Test the contents attribute, which returns the contents of a tag. \n Note the line break elements\n A string should throw error on contents'''\n\n tags = [\"\\n\", self.a_tag_first, \"\\n\", self.a_tag_second, \"\\n\", self.a_tag_third, \"\\n\"]\n\n self.assertEqual(self.a_nested_soup.p.p.p.p.contents, tags)\n self.assertEqual(self.a_nested_soup.p.p.p.p.a.contents, [self.a_tag_first.string])\n\n with self.assertRaises(AttributeError):\n self.assertEqual(self.a_nested_soup.p.p.p.p.a.string.contents, 0) \n\n \n def test_soup_string(self):\n ''' Test the string attribute for finding the string in a tag '''\n \n markup = 'A tag string '\n string = 'A tag string'\n string_soup = BeautifulSoup(markup, \"html.parser\")\n self.assertEqual(string_soup.a.string, string)\n\n def test_soup_stringless(self):\n ''' Test soup constructor for nonexisting string '''\n \n markup = \" \"\n stringless_soup = BeautifulSoup(markup, \"html.parser\")\n self.assertEqual(stringless_soup.a.string, None)\n\n def test_soup_strings(self):\n ''' Test soup constructor for strings '''\n \n markup = 'String0String1String2'\n soup = BeautifulSoup(markup, \"html.parser\")\n\n strings = [\"String0\", \"String1\", \"String2\"]\n\n soup_strings = []\n for string in soup.strings:\n soup_strings.append(string)\n\n self.assertEqual(soup_strings, strings)\n\n with self.assertRaises(IndexError):\n soup_strings[3]\n\n def test_soup_no_strings(self):\n '''Test soup constructor for strings without strings'''\n\n markup = ''\n no_strings_soup = BeautifulSoup(markup, \"html.parser\")\n strings = []\n for string in no_strings_soup.strings:\n strings.append(string)\n self.assertEqual(strings, [])\n\n\n def test_soup_head(self):\n ''' Test attribute navigation for head tag '''\n \n markup = 'head testparagraph
'\n\n head_content_markup = ['head test']\n soup = BeautifulSoup(markup, \"html.parser\")\n \n head_tag = soup.new_tag(\"head\")\n head_tag.string = \"head test\"\n \n self.assertEqual(soup.head, head_tag)\n self.assertEqual(soup.head.contents, head_tag.contents)\n\n def test_soup_headless(self):\n ''' Test attribute navigation without head tag '''\n \n markup = 'paragraph
'\n headless_soup = BeautifulSoup(markup, \"html.parser\")\n \n self.assertEqual(headless_soup.head, None)\n\n def test_soup_title(self):\n ''' Test attribute navigation for title tag '''\n \n markup = 'A title '\n title_soup = BeautifulSoup(markup, \"html.parser\")\n\n title_tag = title_soup.new_tag(\"title\")\n title_tag.string = 'A title'\n \n self.assertEqual(title_soup.title, title_tag)\n self.assertEqual(title_soup.title.string, title_tag.string)\n\n def test_soup_titleless(self):\n ''' Test attribute navigation for nonexisting title tag '''\n \n markup = 'asddsa'\n title_soup = BeautifulSoup(markup, \"html.parser\")\n self.assertEqual(title_soup.title, None)\n \n \n def test_soup_children(self):\n ''' The children attribute returns a generator, for iterating over children\n Note that the children attribute returns linebreaks'''\n \n tags = [\"\\n\", self.a_tag_first, \"\\n\", self.a_tag_second, \"\\n\", self.a_tag_third, \"\\n\"]\n\n index = 0\n for c in self.a_nested_soup.p.p.p.p.children:\n self.assertEqual(c, tags[index])\n index += 1 \n\n\n def test_soup_descendants(self):\n ''' The descentants attribute returns the all descentants of a tag, including strings '''\n \n markup = 'bold tag 1 bold tag 2 '\n soup = BeautifulSoup(markup, \"html.parser\")\n\n a1 = soup.new_tag(\"a\")\n b1 = soup.new_tag(\"b\")\n b1.string = \"bold tag 1\"\n\n b2 = soup.new_tag(\"b\")\n b2.string = \"bold tag 2\"\n\n a1.append(b1)\n a1.append(b2)\n\n desc = [a1, b1, b1.string, b2, b2.string]\n\n index = 0\n for c in soup.descendants:\n self.assertEqual(c, desc[index])\n index += 1\n\n def test_soup_stripped_strings(self):\n ''' Test stripped_strings, which should remove whitespaces and linebreaks before and after strings '''\n \n markup = '''\n String0 \n String1 String2\n '''\n \n soup = BeautifulSoup(markup, \"html.parser\")\n\n strings = [\"String0\", \"String1\", \"String2\"]\n\n soup_strings = []\n for string in soup.stripped_strings:\n soup_strings.append(string)\n\n self.assertEqual(strings, soup_strings)\n\n with self.assertRaises(IndexError):\n strings[3]\n\n def test_soup_stripped_strings_empty(self):\n ''' Test stripping an soup with just whitespace'''\n\n markup = ''' \n '''\n soup = BeautifulSoup(markup, \"html.parser\")\n\n strings = []\n for string in soup.stripped_strings:\n strings.append(string)\n\n self.assertEqual(strings, [])\n\n def test_parent(self):\n '''Parent attribute finds the direct parent. This applies to strings as well.\n The parent of a soup is None'''\n\n markup = 'bold tag 1 bold tag 2 '\n soup = BeautifulSoup(markup, \"html.parser\")\n\n self.assertEqual(soup.a.b.parent, soup.a)\n self.assertEqual(soup.a.parent, soup)\n self.assertEqual(soup.parent, None)\n\n self.assertEqual(soup.a.b.string.parent, soup.a.b)\n\n def test_parents(self):\n '''The parents attribute finds all parents of a given tag'''\n\n markup = 'bold tag 1 bold tag 2 '\n soup = BeautifulSoup(markup, \"html.parser\")\n\n parents = [soup.a.b, soup.a, soup]\n\n ##Small irragularity here, parents does not go as high as None, although\n ##the documentation states that it should.\n\n index = 0\n for c in soup.a.b.string.parents:\n self.assertEqual(c, parents[index])\n index += 1\n \n def test_find(self):\n '''Tests finding tags with a given name '''\n\n self.assertEqual(self.a_simple_soup.find(\"a\"), self.a_tag)\n self.assertEqual(self.a_simple_soup.p.find(\"a\"), self.a_tag)\n self.assertEqual(self.a_nested_soup.find(\"a\"), self.a_tag_first)\n\n def test_find_empty(self):\n ''' Test finding a tag with empty string name '''\n\n self.assertEqual(self.a_nested_soup.find(\"\"), None) #finds html tag\n #self.assertEqual(self.a_nested_soup.find(\"\"), self.a_nested_soup) #this fails also\n\n def test_find_fail(self):\n '''Test not finding a tag '''\n\n self.assertEqual(self.a_nested_soup.find(\"b\"), None)\n\n def test_find_all(self):\n '''Find all tags, returns a list'''\n\n result = [self.a_tag_first,self.a_tag_second,self.a_tag_third]\n self.assertEqual(self.a_nested_soup.find_all(\"a\"), result)\n\n def test_find_all_not_found(self):\n '''Search for non-existing tags'''\n\n self.assertEqual(self.a_nested_soup.find_all(\"b\"), []) \n self.assertEqual(self.a_nested_soup.find_all(\"\"), []) #finds nothing\n\n def test_css_select(self):\n '''Find tags based on CSS selectors, returns a list'''\n\n self.assertEqual(self.css_select_soup.select(\".my_CSS_class\"), [self.p_tag_css])\n self.assertEqual(self.css_select_soup.select(\"a#my_link\"), [self.a_tag_id])\n self.assertEqual(self.css_select_soup.select('a[id=\"my_link\"]'), [self.a_tag_id])\n self.assertEqual(self.css_select_soup.select('#my_link'), [self.a_tag_id])\n self.assertEqual(self.css_select_soup.select('a[id~=\"my_link\"]'), [self.a_tag_id])\n\n def test_css_select_empty(self):\n ''' Test the select function with an empty string '''\n self.assertEqual(self.css_select_soup.select(\"\"), None) \n #Crashes with IndexError\n\n def test_find_next(self):\n '''Use find_next to find the next anchor tag, until there are no more'''\n\n self.assertEqual(self.a_nested_soup.a, self.a_tag_first)\n self.assertEqual(self.a_nested_soup.a.find_next(), self.a_tag_second)\n self.assertEqual(self.a_nested_soup.a.find_next().find_next(), self.a_tag_third)\n self.assertEqual(self.a_nested_soup.a.find_next().find_next().find_next(), None)\n\n def test_find_all_next(self):\n '''Find all following tags using two different usages of find_all_next'''\n\n self.next_tags = [self.a_tag_second, self.a_tag_third]\n self.first_link = self.a_nested_soup.a\n \n self.assertEqual(self.first_link.find_all_next(), self.next_tags)\n self.assertEqual(self.first_link.find_all_next(\"a\"), self.next_tags)\n self.assertEqual(self.first_link.find_all_next(\"b\"), [])\n \n def test_find_previous(self):\n '''Finds the previous tag of a given name '''\n\n self.assertEqual(self.a_simple_soup.a.find_previous(\"html\"), self.a_simple_soup.html)\n\n def test_find_all_previous(self):\n '''Finds all the previous tags of a given name '''\n\n result = [self.a_nested_soup.p.p.p.p, self.a_nested_soup.p.p.p ,self.a_nested_soup.p.p, self.a_nested_soup.p]\n self.assertEqual(self.a_nested_soup.a.find_all_previous(\"p\"), result)\n\n '''find previous which is not parent '''\n self.assertEqual(self.a_nested_soup.a.find_all_previous(\"head\"), [self.a_nested_soup.head])\n\n def test_find_parent(self):\n ''' Finds the parent of a given name'''\n\n self.assertEqual(self.a_nested_soup.a.find_parent(\"p\"), self.a_nested_soup.p.p.p.p)\n self.assertEqual(self.a_nested_soup.p.p.p.p.find_parent(\"p\"), self.a_nested_soup.p.p.p)\n\n\n \n def test_find_parents(self):\n '''Finds all the parents with a given name '''\n \n p_lvl1 = self.a_nested_soup.p\n p_lvl2 = self.a_nested_soup.p.p\n p_lvl3 = self.a_nested_soup.p.p.p\n p_lvl4 = self.a_nested_soup.p.p.p.p\n\n self.assertEqual(self.a_nested_soup.a.find_parents(\"p\"), [p_lvl4, p_lvl3, p_lvl2, p_lvl1])\n self.assertEqual(self.a_nested_soup.p.find_parents(\"body\"), [self.a_nested_soup.body])\n\n \n\n def test_append(self):\n ''' Test the append function by appending an Bar tag'''\n \n soup = BeautifulSoup(\"Foo \", \"html.parser\")\n tag = soup.new_tag(\"b\")\n tag.string = \"Bar\"\n\n soup.a.append(tag)\n\n self.assertEqual(soup.a.b, tag)\n self.assertEqual(\"FooBar \", str(soup.a)) \n \n ''' Test the append function by appending empty string '''\n \n soup_2 = BeautifulSoup(\"Foo \", \"html.parser\")\n soup_2_app = BeautifulSoup(\"Foo \", \"html.parser\")\n soup_2.append(\"\")\n self.assertEqual(soup_2.contents, soup_2_app.contents + [\"\"])\n\n\n def test_append_raise(self):\n ''' Assert that append without argument raises a TypeError due to too few arguments '''\n \n append_raise_soup = BeautifulSoup(\"Foo \", \"html.parser\")\n with self.assertRaises(TypeError):\n append_raise_soup.a.append()\n\n def test_insert_before(self):\n ''' Insert_before() test with a Don't tag inserted before string '''\n \n soup = BeautifulSoup(\"Don't stop \", \"html.parser\")\n b_soup = BeautifulSoup(\"stop \", \"html.parser\")\n \n tag = soup.new_tag(\"i\")\n tag.string = \"Don't\"\n \n b_soup.b.string.insert_before(tag)\n \n self.assertEqual(soup, b_soup)\n\n ''' Insert_before test with string argument before tag. '''\n soup_2 = BeautifulSoup(\"tester soup \", \"html.parser\")\n b_soup_2 = BeautifulSoup(\"Footester soup \", \"html.parser\")\n \n soup_2.b.insert_before(\"Foo\")\n self.assertEqual(soup_2, b_soup_2)\n\n def test_insert_before_raise(self):\n ''' Insert_before() without argument test.'''\n \n soup = BeautifulSoup(\"testing soup \", \"html.parser\")\n with self.assertRaises(TypeError):\n soup.insert_before()\n\n def test_insert_after(self):\n ''' Insert_after() test with an stop tag after string '''\n \n soup = BeautifulSoup(\"Don't \", \"html.parser\")\n soup_r = BeautifulSoup(\"Don't stop \", \"html.parser\")\n \n tag = soup.new_tag(\"i\")\n tag.string = \"stop\"\n \n soup.b.string.insert_after(tag)\n \n self.assertEqual(soup, soup_r)\n\n ''' Insert_after() test with an string argument after tag. '''\n soup_2 = BeautifulSoup(\"Don't \", \"html.parser\")\n soup_2_r = BeautifulSoup(\"Don't TestThis\", \"html.parser\")\n soup_2.b.insert_after(\"TestThis\")\n \n self.assertEqual(soup_2, soup_2_r)\n\n \n \n def test_insert_after_raise(self): \n ''' Insert_after () test with no argument, to raise exception. '''\n\n soup = BeautifulSoup(\"Don't \", \"html.parser\")\n with self.assertRaises(TypeError):\n soup.insert_after()\n\n def test_clear(self):\n ''' Clear the contents of a HTML tag. '''\n \n markup = ' I linked to example.com '\n soup = BeautifulSoup(markup, \"html.parser\")\n\n soup.a.clear()\n \n cleared_markup = ' '\n cleared_soup = BeautifulSoup(cleared_markup, \"html.parser\")\n\n self.assertEqual(soup, cleared_soup)\n\n def test_clear_empty(self):\n ''' Clear the contents of an empty HTML tag. '''\n \n markup = ' '\n soup = BeautifulSoup(markup, \"html.parser\")\n soup_2 = BeautifulSoup(markup, \"html.parser\")\n\n soup.a.clear()\n \n self.assertEqual(soup, soup_2)\n\n def test_clear_with_arg(self):\n ''' Call clear with argument, works just as clear(). '''\n \n markup = ' '\n soup = BeautifulSoup(markup, \"html.parser\")\n soup_2 = BeautifulSoup(markup, \"html.parser\")\n\n soup.a.clear(\"argument\")\n \n self.assertEqual(soup, soup_2)\n\n def test_extract(self):\n ''' Extract a tag and see if it is correctly returned, and that the original is changed accordingly '''\n \n markup = 'I linked to example.com '\n extracted_markup = 'I linked to '\n \n soup = BeautifulSoup(markup, \"html.parser\")\n extracted_soup = BeautifulSoup(extracted_markup, \"html.parser\")\n\n tag = soup.new_tag(\"i\")\n tag.string = \"example.com\"\n \n extracted_tag = soup.i.extract()\n \n self.assertEqual(extracted_tag.parent, None)\n self.assertEqual(extracted_tag, tag)\n self.assertEqual(soup, extracted_soup)\n\n def test_extract_raises(self):\n ''' Test extracting a non-existing tag, ensuring that the original isn't changed. '''\n \n markup = 'I linked to example.com '\n extr_soup = BeautifulSoup(markup, \"html.parser\")\n extr_null_soup = extr_soup.extract()\n \n self.assertEqual(extr_soup, extr_null_soup)\n\n def test_extract_with_arg(self):\n ''' Test extracting by calling extract() with a random argument. '''\n \n markup = 'I linked to example.com '\n extr_arg_soup = BeautifulSoup(markup, \"html.parser\")\n with self.assertRaises(TypeError):\n extr_arg_soup_extracted = extr_arg_soup.extract(\"arg\")\n\n def test_decompose(self):\n ''' Test the decompose function by removing and destroying a tag. '''\n \n markup = 'I linked to example.com '\n markup_decomposed = 'I linked to '\n \n soup = BeautifulSoup(markup, \"html.parser\")\n dec_soup = BeautifulSoup(markup_decomposed, \"html.parser\")\n\n soup.i.decompose()\n \n self.assertEqual(soup, dec_soup)\n\n def test_decompose_empty(self):\n ''' Test the decompose function by removing an empty tag. '''\n \n markup = 'I linked to '\n markup_decomposed = 'I linked to '\n \n soup = BeautifulSoup(markup, \"html.parser\")\n dec_soup = BeautifulSoup(markup_decomposed, \"html.parser\")\n\n soup.i.decompose()\n \n self.assertEqual(soup, dec_soup)\n\n def test_decmpose_arg(self):\n ''' Test the decompose function by calling decompose with arg. '''\n \n markup = 'I linked to test '\n markup_decomposed = 'I linked to '\n dec_soup = BeautifulSoup(markup, \"html.parser\")\n \n with self.assertRaises(TypeError):\n dec_soup.i.decompose(\"test_arg\")\n\n def test_replace_with(self):\n ''' Test the replace with function '''\n \n markup = 'I linked to example.com '\n rep_markup = 'I linked to new_example.com '\n \n soup = BeautifulSoup(markup, \"html.parser\")\n rep_soup = BeautifulSoup(rep_markup, \"html.parser\")\n \n new_tag = soup.new_tag(\"b\")\n new_tag.string = \"new_example.com\"\n\n soup.a.i.replace_with(new_tag)\n \n self.assertEqual(soup, rep_soup)\n\n def test_replace_tag_with_string(self):\n ''' Test replacing tag with string '''\n \n markup = 'I linked to example.com '\n rep_markup = 'I linked to testText '\n \n soup = BeautifulSoup(markup, \"html.parser\")\n rep_soup = BeautifulSoup(rep_markup, \"html.parser\")\n\n soup.i.replace_with(\"testText\")\n \n self.assertEqual(soup, rep_soup)\n self.assertEqual(str(soup), str(rep_soup))\n\n #soup.a.contents <--- this gives a list containing 2 elements, one for each string.\n\n def test_replace_with_no_tag(self):\n ''' Test replace_with() called without argument. '''\n \n markup = 'example.com '\n no_soup = BeautifulSoup(markup, \"html.parser\")\n a_tag = no_soup.a\n \n with self.assertRaises(AttributeError):\n a_tag.i.replace_with()\n\n def test_wrap(self):\n ''' Test wrap() by wrapping a b tag around an a tag '''\n\n markup = 'Text to be wrapped '\n soup = BeautifulSoup(markup, \"html.parser\")\n\n wr_markup = 'Text to be wrapped '\n wr_soup = BeautifulSoup(wr_markup, \"html.parser\")\n\n tag = soup.new_tag(\"b\")\n\n soup.a.wrap(tag)\n\n self.assertEqual(soup, wr_soup)\n\n def test_wrap_with_string(self):\n ''' Test wrap() by wrapping a b tag around an a tag, where b contains a string'''\n\n markup = 'Text to be wrapped '\n\n soup = BeautifulSoup(markup, \"html.parser\")\n\n wr_markup = 'stringText to be wrapped '\n wr_soup = BeautifulSoup(wr_markup, \"html.parser\")\n\n tag = soup.new_tag(\"b\")\n tag.string = \"string\"\n\n soup.a.wrap(tag)\n\n self.assertEqual(soup, wr_soup) \n\n def test_unwrap(self):\n ''' Test unwrapping and compare to soup after unwrapping.'''\n \n markup = 'I linked to example.com '\n soup = BeautifulSoup(markup, \"html.parser\")\n\n unwrapped_markup = 'I linked to example.com '\n unwrapped_soup = BeautifulSoup(unwrapped_markup, \"html.parser\")\n \n soup.a.i.unwrap()\n \n #The soups are not equal, but as strings they are equal\n self.assertEqual(str(soup), str(unwrapped_soup))\n self.assertEqual(soup, unwrapped_soup)\n\n #soup.a.string <-- This is None at this point\n #soup.a.contents <--- this gives a list containing 2 elements, one for each string.\n\n def test_unwrap_with_arg(self):\n ''' Test unwrap() with arg. '''\n \n markup = 'I linked to example.com '\n unwrap_soup = BeautifulSoup(markup, \"html.parser\")\n a_tag = unwrap_soup.a\n \n with self.assertRaises(TypeError):\n a_tag.i.unwrap(\"a\")\n\n \n def test_unwrap_no_tag(self):\n ''' Test unwrap() on non-exisiting tag. '''\n \n markup = 'htadsasdtp/example.codssdd'\n unwrap_soup = BeautifulSoup(markup, \"html.parser\")\n \n with self.assertRaises(ValueError):\n unwrap_soup.unwrap()\n \n\n def test_wrap_unwrap(self):\n ''' Test wrapping and then unwrapping '''\n\n markup = 'Text to be wrapped '\n soup = BeautifulSoup(markup, \"html.parser\")\n soup_2 = BeautifulSoup(markup, \"html.parser\")\n\n tag = soup.new_tag(\"b\")\n\n soup.a.wrap(tag)\n soup.b.unwrap()\n\n self.assertEqual(soup, soup_2)\n\n def test_no_name_tag(self):\n ''' test returning a name of a tag with no name'''\n\n self.assertEqual(self.no_name_tag.name, \"\")\n\n \n\nif __name__ == '__main__':\n unittest.main()\n\n","sub_path":"source/unittest_tests.py","file_name":"unittest_tests.py","file_ext":"py","file_size_in_byte":22882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"379797475","text":"#!/usr/bin/env python3\nimport argparse\nimport re\nimport glob\nimport sys\nimport tokenize\nimport csv\n\n\n########## Begin\nc_line=0\nff = range(1, 10+1)\n\n#var1=None\n\ntimeDiff_1 = []\ntimeDiff_2 = []\ntimeDiff_3 = []\n\nfilecnt=0\n\nfor curr in ff:\n print('try '+ str(curr))\n try: \n f = open(str(curr),'r')\n c_line = 0\n \t#with open(curr,'r') as f :\n for line in f:\n if c_line == 0:\n var1 = int(line) #t[0]\n c_line += 1\n elif c_line == 1:\n #var2 = int(line)\n c_line += 1\n elif c_line == 2:\n var3 = int(line)\n c_line += 1\n elif c_line == 3:\n var4 = int(line)\n c_line += 1\n elif c_line == 4:\n var5 = int(line)\n c_line += 1\n else:\n print('Too many lines ')\n #end if\n #Do Math\n filecnt += 1\n diff1 = var5 - var1\t# sleep latency\n diff2 = var4 - var3\t# int latency\n diff3 = var5 - var4\t# sche latency\n \n print('run '+ str(filecnt) +'\\t\\t1 '+str(diff1)+'\\t2 '+str(diff2)+'\\t3 '+str(diff3))\n \n timeDiff_1.append(diff1)\n timeDiff_2.append(diff2)\n timeDiff_3.append(diff3)\n except: \n pass\n\t#Add diff1 to end of array timeDiff_1\n\t\n#end for ff\n\n\n#Do Avgerage avg(timeDiff_1)\n\ncurAvg1=0\ncurAvg2=0\ncurAvg3=0\nfor c in timeDiff_1:\n\tcurAvg1 += c\n#end for timeDiff_1\nAa1 = curAvg1/filecnt\n\nfor c in timeDiff_2:\n\tcurAvg2 += c\n#end for timeDiff_2\nAa2 = curAvg2/filecnt\n\nfor c in timeDiff_3:\n\tcurAvg3 += c\n#end for timeDiff_3\nAa3 = curAvg3/filecnt\n\n#Time for printing to Person\nprint('Average \\t1 '+str(Aa1)+'\\t2 '+str(Aa2)+'\\t3 '+str(Aa3)+'\\tsample='+str(filecnt))\n\n\n#Now time to save to file!\nfilename ='jack_total.csv'\nwith open(filename,'a') as csvv:\n writer = csv.writer(csvv)\n writer.writerow(str(Aa1))\n writer.writerow(str(Aa2))\n writer.writerow(str(Aa3))\n\n","sub_path":"p5/group5_project5/p5_result_and_scripts/1s_results/resultRonR/parseTime.py","file_name":"parseTime.py","file_ext":"py","file_size_in_byte":2000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"463915379","text":"# placeholder for file that initializes project after it has been cloned\n\nimport os\nfrom setuptools import setup, find_packages\nPACKAGES = find_packages()\n\n# Get version and release info, which is all stored in shablona/version.py\n# ver_file = os.path.join('shablona', 'version.py')\n# with open(ver_file) as f:\n# exec(f.read())\n\npackages = ['csv', 'os', 'time', 'pandas', 'pickle', 'requests',\n 'urllib3', 'bs4.BeautifulSoup', 'numpy']\n\nopts = dict(name=\"NAME\",\n #maintainer=\"MAINTAINER\",\n #maintainer_email=\"MAINTAINER_EMAIL\",\n #description=\"DESCRIPTION\",\n #long_description=\"LONG_DESCRIPTION\",\n #url=\"URL\",\n #download_url=\"DOWNLOAD_URL\",\n #license=\"LICENSE\",\n #classifiers=\"CLASSIFIERS\",\n #author=\"AUTHOR\",\n #author_email=\"AUTHOR_EMAIL\",\n #platforms=\"PLATFORMS\",\n #version=\"VERSION\",\n packages=packages)#,\n #package_data=\"PACKAGE_DATA\",\n #install_requires=\"REQUIRES\",\n #requires=\"REQUIRES\")\n\nif __name__ == '__main__':\n setup(**opts)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"187782478","text":"# Copyright (c) 2015, 2014 Computational Molecular Biology Group, Free University\n# Berlin, 14195 Berlin, Germany.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without modification,\n# are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation and/or\n# other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\nfrom pyemma.coordinates.clustering.interface import AbstractClustering\nfrom pyemma.coordinates.transform.transformer import Transformer\nfrom pyemma.coordinates.data.feature_reader import FeatureReader\n\nfrom pyemma.util.log import getLogger\n\n__all__ = ['Discretizer',\n 'Pipeline',\n ]\n\n__author__ = 'noe, marscher'\n\n\nclass Pipeline(object):\n\n def __init__(self, chain, chunksize=100, param_stride=1):\n r\"\"\"Data processing pipeline.\n\n Parameters\n ----------\n chain : list of transformers like objects\n the order in the list defines the direction of data flow.\n chunksize : int, optional\n how many frames shall be processed at once.\n param_stride : int, optional\n omit every n'th data point\n\n \"\"\"\n self._chain = []\n self.chunksize = chunksize\n self.param_stride = param_stride\n self.chunksize = chunksize\n\n # add given elements in chain\n for e in chain:\n self.add_element(e)\n\n self._parametrized = False\n\n name = \"%s[%s]\" % (self.__class__.__name__, hex(id(self)))\n self._logger = getLogger(name)\n\n @property\n def chunksize(self):\n return self._chunksize\n\n @chunksize.setter\n def chunksize(self, cs):\n self._chunksize = cs\n # update transformers to use new chunksize\n for e in self._chain:\n e.chunksize = cs\n\n def add_element(self, e):\n r\"\"\" Appends a pipeline stage.\n\n Appends the given element to the end of the current chain.\n \"\"\"\n if not isinstance(e, Transformer):\n raise TypeError(\"given element is not a transformer.\")\n\n # set data producer\n if len(self._chain) == 0:\n data_producer = e\n else:\n data_producer = self._chain[-1]\n\n # avoid calling the setter of Transformer.data_producer, since this\n # triggers a re-parametrization even on readers (where it makes not sense)\n e._data_producer = data_producer\n e.chunksize = self.chunksize\n\n self._chain.append(e)\n\n def set_element(self, index, e):\n r\"\"\" Replaces a pipeline stage.\n\n Replace an element in chain and return replaced element.\n \"\"\"\n if index > len(self._chain):\n raise IndexError(\"tried to access element %i, but chain has only %i\"\n \" elements\" % (index, len(self._chain)))\n\n if type(index) is not int:\n raise ValueError(\n \"index is not a integer but '%s'\" % str(type(index)))\n # if e is already in chain, we're finished\n if self._chain[index] is e:\n return\n\n # remove current index and its data producer\n replaced = self._chain.pop(index)\n replaced.data_producer = None\n\n self._chain.insert(index, e)\n\n if index == 0:\n e.data_producer = e\n else:\n # rewire data_producers\n e.data_producer = self._chain[index - 1]\n\n # if e has a successive element, need to set data_producer\n try:\n successor = self._chain[index + 1]\n successor.data_producer = e\n except IndexError:\n pass\n\n # set data_producer for predecessor of e\n # self._chain[max(0, index - 1)].data_producer = self._chain[index]\n\n # since data producer of element after insertion changed, reset its status\n # TODO: make parameterized a property?\n self._chain[index]._parameterized = False\n\n return replaced\n\n def run(self):\n \"\"\"deprecated. Identical to parametrize()\n \"\"\"\n import warnings\n warnings.warn(\n \"run() is deprecated and will be disabled in the future. Use parametrize().\", DeprecationWarning)\n self.parametrize()\n\n # TODO: DISCUSS - renamed run() to parametrize (because run is a bit ambiguous).\n # TODO: We could also call it fit() (here and in the transformers).\n # TODO: This might be nicer because it's shorter and the spelling is unambiguous\n # TODO: (in contrast to parametrize and parameterize and parameterise that\n # are all correct in english.\n def parametrize(self):\n r\"\"\"\n Reads all data and discretizes it into discrete trajectories.\n \"\"\"\n for element in self._chain:\n element.parametrize(stride=self.param_stride)\n\n self._parametrized = True\n\n def _is_parametrized(self):\n r\"\"\"\n Iterates through the pipeline elements and checks if every element is parametrized.\n \"\"\"\n result = self._parametrized\n for el in self._chain:\n result &= el._parametrized\n return result\n\n\nclass Discretizer(Pipeline):\n\n r\"\"\"\n A Discretizer gets a FeatureReader, which extracts features (distances,\n angles etc.) of given trajectory data and passes this data in a memory\n efficient way through the given pipeline of a Transformer and Clustering.\n The clustering object is responsible for assigning the data to the cluster centers.\n\n Parameters\n ----------\n reader : a FeatureReader object\n reads trajectory data and selects features.\n transform : a Transformer object (optional)\n the Transformer will be used to e.g reduce dimensionality of inputs.\n cluster : a clustering object\n used to assign input data to discrete states/ discrete trajectories.\n chunksize : int, optional\n how many frames shall be processed at once.\n \"\"\"\n\n def __init__(self, reader, transform=None, cluster=None, chunksize=100, param_stride=1):\n # init with an empty chain and add given transformers afterwards\n Pipeline.__init__(\n self, [], chunksize=chunksize, param_stride=param_stride)\n\n # check input\n if not isinstance(reader, Transformer):\n raise ValueError('given reader is not of the correct type')\n else:\n if reader.data_producer is not reader:\n raise ValueError(\"given reader is not a first stance data source.\"\n \" Check if its a FeatureReader or DataInMemory\")\n if transform is not None:\n if not isinstance(transform, Transformer):\n raise ValueError('transform is not a transformer but \"%s\"' %\n str(type(transform)))\n if cluster is None:\n raise ValueError('Must specify a clustering algorithm!')\n else:\n assert isinstance(cluster, AbstractClustering), \\\n 'cluster is not of the correct type'\n\n if hasattr(reader, 'featurizer'): # reader is a FeatureReader\n if reader.featurizer.dimension == 0:\n self._logger.warning(\"no features selected!\")\n\n self.add_element(reader)\n\n if transform is not None:\n self.add_element(transform)\n\n self.add_element(cluster)\n\n self._parametrized = False\n\n @property\n def dtrajs(self):\n \"\"\" get discrete trajectories \"\"\"\n if not self._parametrized:\n self._logger.info(\"not yet parametrized, running now.\")\n self.parametrize()\n return self._chain[-1].dtrajs\n\n def save_dtrajs(self, prefix='', output_dir='.',\n output_format='ascii', extension='.dtraj'):\n r\"\"\"Saves calculated discrete trajectories. Filenames are taken from\n given reader. If data comes from memory dtrajs are written to a default\n filename.\n\n\n Parameters\n ----------\n prefix : str\n prepend prefix to filenames.\n output_dir : str (optional)\n save files to this directory. Defaults to current working directory.\n output_format : str\n if format is 'ascii' dtrajs will be written as csv files, otherwise\n they will be written as NumPy .npy files.\n extension : str\n file extension to append (eg. '.itraj')\n\n \"\"\"\n\n clustering = self._chain[-1]\n reader = self._chain[0]\n\n assert isinstance(clustering, AbstractClustering)\n\n trajfiles = None\n if isinstance(reader, FeatureReader):\n trajfiles = reader.trajfiles\n\n clustering.save_dtrajs(\n trajfiles, prefix, output_dir, output_format, extension)\n","sub_path":"pyemma/coordinates/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":9747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"528100031","text":"from flask import Flask, render_template, request, flash, redirect, url_for, jsonify\nfrom sqlalchemy import Column, String, Integer, Sequence, Date, ForeignKey, between, and_\nfrom wtforms import Form, TextField, validators, StringField, SubmitField, IntegerField\nimport time\nimport flask_sqlalchemy\nimport flask_restless\nimport flask_bootstrap\nfrom datetime import datetime, timedelta\nimport requests\nimport json\n\napp = Flask(__name__)\n\nflask_bootstrap.Bootstrap(app)\n\napp.config.from_pyfile('config.py')\n\ndb = flask_sqlalchemy.SQLAlchemy(app)\n\nmanager = flask_restless.APIManager(app, flask_sqlalchemy_db=db)\n\ndateRegex = \"^(([0-9])|([0-2][0-9])|([3][0-1]))\\-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\\-\\d{2}$\"\n\nclass AlchemyEncoder(json.JSONEncoder):\n\n def default(self, obj):\n if isinstance(obj.__class__, DeclarativeMeta):\n fields = {}\n for field in [x for x in dir(obj) if not x.startswith('_') and x != 'metadata']:\n data = obj.__getattribute__(field)\n try:\n json.dumps(data)\n fields[field] = data\n except TypeError:\n fields[field] = None\n return fields\n\n return json.JSONEncoder.default(self, obj)\n\n\n\nclass SurveyRequestForm(Form):\n development = TextField(\"Development Name: \", validators=[validators.required()])\n client = TextField(\"Client Name: \", validators=[validators.required()])\n location = TextField(\"Location Name: \", validators=[validators.required()])\n sRange = TextField(\"Range: \", validators=[validators.required(), validators.length(min=2, max=2, message=\"Min and max length 2\")])\n section = IntegerField(\"Section: \", validators=[validators.required(message=\"Must be integer value\"), validators.number_range(min=1, max=100000, message=\"Must be integer between 1 and 100000\")])\n township = TextField(\"Township: \", validators=[validators.required()])\n requestedBy = TextField(\"Requested By: \", validators=[validators.required()])\n\ndef _getDate():\n return datetime.now().date()\n\n#fields need to be all lowercase and same name as db\nclass SurveyRequest(db.Model):\n __tablename__ = 'surveyrequest'\n jobno = db.Column(Integer, Sequence('job_id_seq'), primary_key=True)\n development = db.Column(String)\n client = db.Column(String)\n contractdate = db.Column(Date, default=_getDate)\n location = db.Column(String)\n range = db.Column(String)\n section = db.Column(Integer)\n township = db.Column(String)\n daterequested = db.Column(Date, default=_getDate)\n requestedby = db.Column(String)\n completiondate = db.Column(Date, nullable=True)\n istwosetsdrawings = db.Column(String, nullable=True)\n restakecount = db.Column(Integer)\n\nclass Task(db.Model):\n __tablename__ = 'task'\n taskno = db.Column(Integer, Sequence('task_id_seq'), primary_key=True)\n description = db.Column(String)\n\nclass FieldBook(db.Model):\n __tablename__ = 'fieldbook'\n fieldbookno = db.Column(Integer, Sequence('fieldbook_id_seq'), primary_key=True)\n bookpath = db.Column(String)\n\nclass Crew(db.Model):\n __tablename__ = 'crew'\n crewno = db.Column(Integer, Sequence('crew_id_seq'), primary_key=True)\n\nclass Employee(db.Model):\n __tablename__ = 'employee'\n employeeno = db.Column(Integer, Sequence('employee_id_seq'), primary_key=True)\n firstname = db.Column(String)\n lastname = db.Column(String)\n crewno = db.Column(Integer, ForeignKey('crew.crewno'))\n\nclass Assigned(db.Model):\n __tablename__ = 'assigned'\n assignno = db.Column(Integer, Sequence('assigned_id_seq'), primary_key=True)\n crewno = db.Column(Integer, ForeignKey('crew.crewno'))\n taskno = db.Column(Integer, ForeignKey('task.taskno'))\n workdate = db.Column(Date)\n notes = db.Column(String)\n\nclass SurveyPlan(db.Model):\n __tablename__ = 'surveyplan'\n planno = db.Column(Integer, Sequence('plan_id_seq'), primary_key=True)\n jobno = db.Column(Integer, ForeignKey('surveyrequest.jobno'))\n taskno = db.Column(Integer, ForeignKey('task.taskno'))\n notes = db.Column(String)\n\nclass Schedule(db.Model):\n __tablename__ = 'schedule'\n scheduleno = db.Column(Integer, Sequence('schedule_id_seq'), primary_key=True)\n planno = db.Column(Integer, ForeignKey('surveyplan.planno'))\n jobno = db.Column(Integer, ForeignKey('surveyrequest.jobno'))\n assignno = db.Column(Integer, ForeignKey('assigned.assignno'))\n employeeno = db.Column(Integer, ForeignKey('employee.employeeno'))\n scheduledate = db.Column(Date)\n\nclass SurveyReport(db.Model):\n __tablename__ = 'surveyreport'\n reportno = db.Column(Integer, Sequence('report_id_seq'), primary_key=True)\n jobno = db.Column(Integer, ForeignKey('surveyrequest.jobno'))\n scheduleno = db.Column(Integer, ForeignKey('schedule.scheduleno'))\n iscompleted = db.Column(String)\n fieldbookno = db.Column(Integer, ForeignKey('fieldbook.fieldbookno'))\n beginningpageno = db.Column(Integer)\n employeeno = db.Column(Integer, ForeignKey('employee.employeeno'))\n\n@app.route('/home')\ndef home():\n return render_template('index.html')\n\n@app.route('/requestsurvey', methods=['GET', 'POST'])\ndef requestSurvey():\n form = SurveyRequestForm(request.form)\n\n if request.method == 'POST':\n\n if form.validate():\n\n data = {'development': request.form['development'],\n 'client': request.form['client'],\n 'location': request.form['location'],\n 'range': request.form['sRange'],\n 'section': request.form['section'],\n 'township': request.form['township'],\n 'requestedby': request.form['requestedBy'],\n 'restakecount': 0\n }\n response = requests.post('http://localhost:5000/api/surveyrequest', json=data)\n if response.status_code == requests.codes.created:\n time.sleep(3)\n\n return redirect(url_for('home'))\n return render_template('requestSurvey.html', form=form)\n\n@app.route('/plansurvey', methods=['GET', 'POST'])\ndef planSurvey():\n jobs = SurveyRequest.query.filter_by(completiondate=None)\n tasks = Task.query.all()\n if request.method == 'POST':\n data = request.get_json()\n jobno = data['jobno']\n for task in data['tasks']:\n plan = SurveyPlan(jobno=jobno, taskno=task['taskno'], notes=task['tasknotes'])\n db.session.add(plan)\n db.session.commit()\n\n return render_template('planSurvey.html', jobs=jobs, tasks=tasks)\n\n@app.route('/schedulesurvey', methods=['GET', 'POST'])\ndef scheduleSurvey():\n #surveyplans that have not been scheduled\n plans = db.session.query(SurveyPlan).join(Schedule, Schedule.planno == SurveyPlan.planno, isouter=True)\n #jobs in each plan\n jobs = []\n for plan in plans:\n jobs.append(SurveyRequest.query.get(plan.jobno))\n\n crews = Crew.query.all()\n\n if request.method == 'POST':\n assign = Assigned(crewno=request.form['crewno'],\n workdate=request.form['workdate'],\n notes=request.form['crewnotes']\n )\n db.session.add(assign)\n db.session.flush()\n assignno = assign.assignno\n db.session.commit()\n date = _getDate()\n schedule = Schedule(\n planno=request.form['planno'],\n jobno=request.form['jobno'],\n assignno=assignno,\n employeeno=request.form['employeeno'],\n scheduledate= date\n )\n db.session.add(schedule)\n db.session.commit()\n return render_template('scheduleSurvey.html', jobs=jobs, plans=plans, crews=crews)\n\n@app.route('/getjobsurveyplan', methods=['GET'])\ndef getjobSurveyPlan():\n jobno = request.args.get('jobno')\n unscheduled_plans = db.session.query(SurveyPlan).join(Schedule, Schedule.planno == SurveyPlan.planno, isouter=True)\n plans = None\n for plan in unscheduled_plans:\n plans = SurveyPlan.query.filter_by(jobno=jobno)\n\n json_plans = []\n for plan in plans:\n json_plans.append({\n 'planno': str(plan.planno),\n 'jobno': str(plan.jobno),\n 'taskno': str(plan.taskno),\n 'notes': str(plan.notes)\n })\n\n return jsonify(json_plans)\n\n@app.route('/fieldworkreport', methods=['GET', 'POST'])\ndef fieldworkReport():\n #getting all the jobs that have a schedule but have no fieldwork and those that are incomplete\n scheduleNoFieldWork = db.session.query(Schedule).join(SurveyReport, Schedule.scheduleno == SurveyReport.scheduleno, isouter=True)\n incompleteFieldWork = SurveyReport.query.filter_by(iscompleted='N')\n jobs = []\n for schedule in scheduleNoFieldWork:\n jobs.append(SurveyRequest.query.get(schedule.jobno))\n for work in incompleteFieldWork:\n jobs.append(SurveyRequest.query.get(work.jobno))\n\n if request.method == 'POST':\n pass\n\n\n return render_template('fieldreport.html', jobs=jobs)\n\n@app.route('/weeklyinfo', methods=['GET'])\ndef weeklyinfo():\n\n today = _getDate()\n today = datetime.strftime(today, '%d-%b-%y')\n week_after = datetime.now() + timedelta(days=7)\n week_after = datetime.strftime(week_after, '%d-%b-%y')\n scheduledetails = []\n allinfo = db.session.query(SurveyRequest, Task, SurveyPlan, Assigned, Schedule).filter(\n SurveyRequest.jobno == Schedule.jobno).filter(\n Assigned.assignno == Schedule.assignno).filter(\n Assigned.workdate >= today, Assigned.workdate <= week_after).filter(\n SurveyPlan.jobno == SurveyRequest.jobno).filter(\n Task.taskno == Assigned.taskno).all()\n\n biglistinfo = []\n for x in allinfo:\n for y in x:\n biglistinfo.append(y)\n\n\n schedule = {'jobno': None,\n 'tasks': [],\n 'development': None,\n 'restakecount': None}\n\n for b in biglistinfo:\n if isinstance(b, SurveyRequest):\n if b.jobno != schedule['jobno']:\n schedule['jobno'] = b.jobno\n schedule['development'] = b.development\n schedule['restakecount'] = b.restakecount\n scheduledetails.append(schedule)\n\n for b in biglistinfo:\n if isinstance(b, Task):\n for schedule in scheduledetails:\n if not any(t['taskno'] == b.taskno for t in schedule['tasks']):\n schedule['tasks'].append({'taskno': b.taskno, 'taskdesc': b.description})\n\n for b in biglistinfo:\n if isinstance(b, SurveyPlan):\n for schedule in scheduledetails:\n if any(t['taskno'] == b.taskno for t in schedule['tasks']):\n for t in schedule['tasks']:\n if t['taskno'] == b.taskno:\n if b.notes is None:\n t['notes'] = \"\"\n else:\n t['notes'] = b.notes\n\n for b in biglistinfo:\n if isinstance(b, Assigned):\n for schedule in scheduledetails:\n if any(t['taskno'] == b.taskno for t in schedule['tasks']):\n for t in schedule['tasks']:\n if t['taskno'] == b.taskno:\n t['crewno'] = b.crewno\n if b.notes is None:\n t['assignnotes'] = \"\"\n else:\n t['assignnotes'] = b.notes\n\n return jsonify(scheduledetails)\n\n@app.route('/weeklyschedule', methods=['GET'])\ndef weeklyschedule():\n today = _getDate()\n today = datetime.strftime(today, '%d-%b-%y')\n week_after = datetime.now() + timedelta(days=7)\n week_after = datetime.strftime(week_after, '%d-%b-%y')\n\n\n\n return render_template('weeklySchedule.html', start=today, end=week_after)\n\n\n\n\n\n\n\n\nmanager.create_api(SurveyRequest, methods=['GET', 'POST', 'PATCH', 'DELETE'])\nmanager.create_api(Task, methods=['GET', 'POST', 'PATCH', 'DELETE'])\nmanager.create_api(Assigned, methods=['GET', 'POST'])\nmanager.create_api(Schedule, methods=['GET', 'POST'])\nmanager.create_api(Crew, methods=['GET'])\nmanager.create_api(SurveyPlan, methods=['GET'])\nmanager.create_api(SurveyReport, methods=['GET', 'POST'])\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":12350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"261285723","text":"from flask_restful import Resource, reqparse\nfrom flask_jwt import jwt_required\nfrom models.coin import CoinModel\n \nclass Coin(Resource):\n parser = reqparse.RequestParser()\n\n parser.add_argument('name', type=str, required=True, help='This field cannot be left blank')\n parser.add_argument('slug', type=str)\n parser.add_argument('symbol', type=str)\n parser.add_argument('status', type=str)\n parser.add_argument('category', type=str)\n parser.add_argument('description', type=str)\n parser.add_argument('subreddit', type=str)\n parser.add_argument('notice', type=str)\n parser.add_argument('tags', type=str)\n parser.add_argument('tag_names', type=str)\n parser.add_argument('website', type=str)\n parser.add_argument('twitter', type=str)\n parser.add_argument('message_board', type=str)\n parser.add_argument('chat', type=str)\n parser.add_argument('explorer', type=str)\n parser.add_argument('reddit', type=str)\n parser.add_argument('technical_doc', type=str)\n parser.add_argument('source_code', type=str)\n parser.add_argument('announcement', type=str)\n parser.add_argument('platform_id', type=int)\n parser.add_argument('date_added', type=str)\n parser.add_argument('date_launched', type=str)\n\n @jwt_required()\n def get(self, name):\n coin = CoinModel.find_by_name(name)\n if coin:\n return coin.json()\n return {'message': 'Coin not fond'}, 404\n \n\n\n def post(self, name):\n if CoinModel.find_by_name(name):\n return {'message': \"A coin with the name '{}' already exists.\".format(name)}, 400\n\n data = Coin.parser.parse_args()\n coin = CoinModel(name,\n data['slug'],\n data['symbol'],\n data['status'],\n data['category'],\n data['description'],\n data['subreddit'],\n data['notice'],\n data['tags'],\n data['tag_names'],\n data['website'],\n data['twitter'],\n data['message_board'],\n data['chat'],\n data['explorer'],\n data['reddit'],\n data['technical_doc'],\n data['source_code'],\n data['announcement'],\n data['platform_id'],\n data['date_added'],\n data['date_launched']\n )\n try:\n coin.save_to_db()\n except:\n return {'message': 'An error occurred inserting coin.'}, 500\n\n return coin.json(), 201\n\n def delete(self, name):\n coin = CoinModel.find_by_name(name)\n if coin:\n coin.delete_from_db()\n\n return {'message': 'Coin deleted'}\n\n def put(self, name):\n data = Coin.parser.parse_args()\n \n coin = CoinModel.find_by_name(name)\n \n if coin is None:\n coin = CoinModel(name, **data)\n else:\n coin.slug = data['slug']\n coin.symbol = data['symbol']\n coin.status = data['status']\n coin.category = data['category']\n coin.description = data['description']\n coin.subreddit = data['subreddit']\n coin.notice = data['notice']\n coin.tags = data['tags']\n coin.tag_names = data['tag_names']\n coin.website = data['website']\n coin.twitter = data['twitter']\n coin.message_board = data['message_board']\n coin.chat = data['chat']\n coin.explorer = data['explorer']\n coin.reddit = data['reddit']\n coin.technical_doc = data['technical_doc']\n coin.source_code = data['source_code']\n coin.announcement = data['announcement']\n coin.platform_id = data['platform_id']\n coin.date_added = data['date_added']\n coin.date_launched = data['date_launched']\n\n coin.save_to_db()\n\n return coin.json() \n\nclass CoinList(Resource):\n def get(self):\n return {'coins': list(map(lambda x: x.json(), CoinModel.query.all()))}\n # return {'coins': [x.json() for x in ItemModel.query.all()]}\n\n\nclass CoinInfo(Resource):\n def get(self, id):\n coin = CoinModel.find_by_id(id)\n if coin:\n return coin.json()\n return {'message': 'Coin not fond'}, 404\n","sub_path":"resources/coin.py","file_name":"coin.py","file_ext":"py","file_size_in_byte":4540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"224642876","text":"import wave\nimport pygame\nfrom time import sleep\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy import signal, misc\nfrom scipy.io import wavfile\n\ndef Play_sound(filename):\n pygame.mixer.init()\n sound = pygame.mixer.Sound(filename)\n tmp = sound.play()\n while tmp.get_busy():\n pygame.time.delay(1)\n\n\n# Cosine wave x(t) = A * cos(2 *pi * f0 *t)\n\nA = 16000\nf0 = 200\nfs = 48000.0\nnum_sample = 48000\n\ncosine_wave = np.zeros(num_sample)\n# cosine_wave = [A*np.cos(2*np.pi * f0 * X /fs)]\nfor x in range(num_sample):\n cosine_wave[x] = A*np.cos(2*np.pi*f0 * x / fs)\n\n\nout = np.cast['int16'](cosine_wave)\n\nwavfile.write('cosine_wave.wav', int(fs), out)\nPlay_sound('cosine_wave.wav')\nplt.plot(out)\nplt.show()\n","sub_path":"Python_Class/sinsusodal_synthesis.py","file_name":"sinsusodal_synthesis.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"490006021","text":"# ==================================================================================================\n# Copyright 2011 Twitter, Inc.\n# --------------------------------------------------------------------------------------------------\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this work except in compliance with the License.\n# You may obtain a copy of the License in the LICENSE file, or at:\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==================================================================================================\n\n\"\"\"\n Twitter's wrapper around the optparse module.\n\n Typical usage (from module):\n from twitter.common import options\n options.add(\"-q\", \"--quiet\",\n action=\"store_false\", dest=\"verbose\", default=True,\n help=\"don't print status messages to stdout\")\n\n def my_function():\n opts = options.values()\n if opts.verbose:\n print 'LOOOOOOLLOLOLOL'\n\n From __main__ script:\n from twitter.common import options\n options.add(...)\n options.add(...)\n\n def main(argv):\n options.parse()\n\n All options are stored in a global options registry, and are grouped by\n the module from which they were added (and displayed as such in --help.)\n\n options.parse() must be called before modules can use options.values().\n options.values() will raise an exception if called before options.parse()\n by the __main__ module. this is to prevent parsing before all options\n have been registered.\n\n For more help on options formatting, see the optparse module.\n\"\"\"\n\n__author__ = 'Brian Wickman'\n\nimport sys\nimport inspect\nimport types\n\nfrom optparse import OptionParser, OptionValueError\n\nclass OptionsHaveNotBeenParsedException(Exception): pass\nclass OptionsAreFrozenException(Exception): pass\nclass OptionsInternalErrorException(Exception): pass\n\nclass _Global:\n OPTIONS = OptionParser(add_help_option=False)\n OPTIONS_LONG = OptionParser(add_help_option=False)\n VALUES = None\n OVERRIDES = {}\n ARGUMENTS = None\n GROUPS = {}\n PARSED = False\n\n @staticmethod\n def assert_not_parsed(msg=\"\"):\n if _Global.PARSED:\n raise OptionsAreFrozenException(msg)\n\n @staticmethod\n def warn_if_parsed(msg=\"\"):\n if _Global.PARSED:\n print >> sys.stderr, 'Warning: calling options.parse multiple times!'\n\ndef _short_help(option, opt, value, parser):\n _Global.OPTIONS.print_help()\n sys.exit(1)\n\ndef _long_help(option, opt, value, parser):\n _Global.OPTIONS_LONG.print_help()\n sys.exit(1)\n\ndef _add_both_options(*args, **kwargs):\n _Global.OPTIONS.add_option(*args, **kwargs)\n _Global.OPTIONS_LONG.add_option(*args, **kwargs)\n\n_add_both_options(\n \"-h\", \"--help\", \"--short-help\",\n action=\"callback\",\n callback=_short_help,\n help=\"show this help message and exit.\")\n\n_add_both_options(\n \"--long-help\",\n action=\"callback\",\n callback=_long_help,\n help=\"show options from all registered modules, not just the __main__ module.\")\n\ndef _find_calling_module():\n stack = inspect.stack()\n for fr_n in range(len(stack)):\n if '__name__' in stack[fr_n][0].f_locals:\n return stack[fr_n][0].f_locals['__name__']\n raise OptionsInternalErrorException(\"Unable to interpret stack frame from logging module.\")\n\ndef add(*args, **kwargs):\n _Global.assert_not_parsed(\"Cannot add new options after option.parse() has been called!\")\n adding_module = _find_calling_module()\n if adding_module == '__main__':\n _Global.OPTIONS.add_option(*args, **kwargs)\n _Global.OPTIONS_LONG.add_option(*args, **kwargs)\n else:\n adding_module = 'From module %s' % adding_module\n if adding_module not in _Global.GROUPS:\n _Global.GROUPS[adding_module] = _Global.OPTIONS_LONG.add_option_group(adding_module)\n _Global.GROUPS[adding_module].add_option(*args, **kwargs)\n\n# alias\nadd_option = add\n\ndef parse(args=None):\n _Global.warn_if_parsed()\n\n args_to_parse = []\n if args is None:\n args_to_parse.extend(sys.argv[1:])\n args_to_parse.extend('--%s=%s' % (k,v) for (k,v) in _Global.OVERRIDES.items())\n _Global.VALUES, _Global.ARGUMENTS = _Global.OPTIONS_LONG.parse_args(\n args=args_to_parse, values=_Global.VALUES)\n _Global.PARSED = True\n return _Global.VALUES, _Global.ARGUMENTS\n\n# alias\nparse_args = parse\n\ndef values():\n if not _Global.PARSED:\n raise OptionsHaveNotBeenParsedException(\"options.parse() has not been called!\")\n return _Global.VALUES\n\ndef arguments():\n if not _Global.PARSED:\n raise OptionsHaveNotBeenParsedException(\"options.parse() has not been called!\")\n return _Global.ARGUMENTS\n\ndef set_option(option_name, option_value):\n if isinstance(option_value, types.StringTypes) and isinstance(option_name, types.StringTypes):\n if option_name in _Global.OVERRIDES:\n print >> sys.stderr, \"WARNING: Calling set_option(%s) multiple times!\" % option_name\n _Global.OVERRIDES[option_name] = option_value\n else:\n raise OptionValueError(\"set_option values must be strings!\")\n\ndef set_usage(usage):\n _Global.OPTIONS.set_usage(usage)\n _Global.OPTIONS_LONG.set_usage(usage)\n\ndef help(*args, **kwargs):\n _Global.OPTIONS.print_help(*args, **kwargs)\n\ndef longhelp(*args, **kwargs):\n _Global.OPTIONS_LONG.print_help(*args, **kwargs)\n\n# alias\nprint_help = help\n\n__all__ = [\n 'add',\n 'add_option',\n 'parse',\n 'parse_args',\n 'values',\n 'arguments',\n 'set_option',\n 'set_usage',\n 'help',\n 'longhelp',\n 'print_help',\n 'OptionsHaveNotBeenParsedException',\n 'OptionsAreFrozenException',\n 'OptionsInternalErrorException',\n 'OptionValueError',\n]\n","sub_path":"src/python/twitter/common/options/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"503030489","text":"from Queue import PriorityQueue\n\n\ndef mergeKLists(lists):\n dummy = ListNode(0)\n curr = dummy\n q = PriorityQueue()\n\n for node in lists:\n if node:\n q.put((node.val, node))\n\n while q.size() > 0:\n curr.next = q.get()[1]\n curr = curr.next\n if curr.next:\n q.put((curr.next.val, curr.next))\n return dummy.next\n\n\n# A priority queue works like a standard queue except that the items are tuples of priority, item, so get() on such a queue will return that kind of tuple - if you want to get the actual item you should use either this which will give you both the item and its priority :\n#\n# prio, item = queue.get()\n# Or directly like this if you don't care about the priority at all :\n#\n# item = queue.get()[1]\n","sub_path":"CTCI_Python/mergeKLists.py","file_name":"mergeKLists.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"596658238","text":"from os import makedirs\nfrom os.path import join, isdir\nimport pytest\nfrom shutil import copyfile\n\nimport matplotlib.pyplot as plt\nfrom numpy import array, linspace, ones, pi, zeros\n\nfrom pyleecan.Classes.import_all import *\n\ntry:\n from pyleecan.Functions.GMSH.gen_3D_mesh import gen_3D_mesh\nexcept ImportError as error:\n gen_3D_mesh = error\nfrom Tests import save_plot_path\nfrom Tests.Plot.LamWind import wind_mat\nfrom pyleecan.Functions.load import load\nfrom pyleecan.Classes.InputCurrent import InputCurrent\nfrom pyleecan.Classes.MagFEMM import MagFEMM\nfrom pyleecan.Classes.Simu1 import Simu1\nfrom pyleecan.Classes.Output import Output\nfrom pyleecan.Classes.SlotUD2 import SlotUD2\nfrom pyleecan.Classes.OptiDesignVarInterval import OptiDesignVarInterval\nfrom pyleecan.Classes.OptiObjective import OptiObjective\nfrom pyleecan.Classes.OptiProblem import OptiProblem\nfrom pyleecan.Classes.ImportMatrixVal import ImportMatrixVal\nfrom pyleecan.Classes.ImportGenVectLin import ImportGenVectLin\nfrom pyleecan.Classes.OptiGenAlgNsga2Deap import OptiGenAlgNsga2Deap\n\nimport numpy as np\nimport random\nfrom pyleecan.Functions.load import load\nfrom pyleecan.definitions import DATA_DIR\n\n# Gather results in the same folder\nsave_path = join(save_plot_path, \"ICEM_2020\")\nif not isdir(save_path):\n makedirs(save_path)\n\n\n\"\"\"This test gather all the images/project for the ICEM 2020 publication:\n\"Design optimization of innovative electrical machines topologies based\non Pyleecan open-source object-oriented software\"\n\"\"\"\n\n\n@pytest.mark.long_5s\n@pytest.mark.long_1m\n@pytest.mark.MagFEMM\n@pytest.mark.SCIM\n@pytest.mark.periodicity\n@pytest.mark.SingleOP\ndef test_FEMM_sym():\n \"\"\"Figure 9: Check that the FEMM can handle symmetry\n From pyleecan/Tests/Validation/Simulation/test_EM_SCIM_NL_006.py\n \"\"\"\n SCIM_006 = load(join(DATA_DIR, \"Machine\", \"SCIM_006.json\"))\n simu = Simu1(name=\"test_ICEM_2020\", machine=SCIM_006)\n simu.machine.name = \"fig_09_FEMM_sym\"\n\n # Definition of the enforced output of the electrical module\n N0 = 1500\n Is = ImportMatrixVal(value=array([[20, -10, -10]]))\n Ir = ImportMatrixVal(value=zeros((1, 28)))\n Nt_tot = 1\n Na_tot = 4096\n simu.input = InputCurrent(\n Is=Is,\n Ir=Ir, # zero current for the rotor\n OP=OPdq(N0=N0),\n Nt_tot=Nt_tot,\n Na_tot=Na_tot,\n angle_rotor_initial=0.2244,\n )\n\n # Definition of the magnetic simulation\n # 2 sym + antiperiodicity = 1/4 Lamination\n simu.mag = MagFEMM(\n type_BH_stator=2, type_BH_rotor=2, is_periodicity_a=True, is_fast_draw=False\n )\n # Stop after magnetic computation\n simu.force = None\n simu.struct = None\n # Run simulation\n out = Output(simu=simu)\n simu.run()\n\n # FEMM files (mesh and results) are available in Results folder\n copyfile(\n join(out.path_result, \"Femm\", \"fig_09_FEMM_sym_model.ans\"),\n join(save_path, \"fig_09_FEMM_sym_model.ans\"),\n )\n copyfile(\n join(out.path_result, \"Femm\", \"fig_09_FEMM_sym_model.fem\"),\n join(save_path, \"fig_09_FEMM_sym_model.fem\"),\n )\n\n\n@pytest.mark.GMSH\ndef test_gmsh_mesh_dict():\n \"\"\"Figure 10: Generate a 3D mesh with Gmsh by setting the\n number of element on each lines\n \"\"\"\n if isinstance(gen_3D_mesh, ImportError):\n raise ImportError(\"Fail to import gen_3D_mesh (gmsh package missing)\")\n\n # Stator definition\n stator = LamSlotWind(\n Rint=0.1325,\n Rext=0.2,\n Nrvd=0,\n L1=0.35,\n Kf1=0.95,\n is_internal=False,\n is_stator=True,\n )\n stator.slot = SlotW10(\n Zs=36, H0=1e-3, H1=1.5e-3, H2=30e-3, W0=12e-3, W1=14e-3, W2=12e-3\n )\n\n # Plot, check and save\n stator.plot(is_lam_only=True, is_show_fig=False)\n fig = plt.gcf()\n fig.savefig(join(save_path, \"fig_10_ref_lamination.png\"))\n fig.savefig(join(save_path, \"fig_10_ref_lamination.svg\"), format=\"svg\")\n assert len(fig.axes[0].patches) == 4\n\n # Definition of the number of each element on each line\n mesh_dict = {\n \"0\": 5, # Yoke_Side_Right\n \"1\": 5, # Yoke_Side_Left\n \"2\": 5, # Yoke_Arc\n \"3\": 2,\n \"4\": 8,\n \"5\": 1,\n \"6\": 1,\n \"7\": 1,\n \"8\": 2, # bore_arc_bot\n \"9\": 2, # bore_arc_top\n \"10\": 1,\n \"11\": 1,\n \"12\": 1,\n \"13\": 8,\n \"14\": 2,\n }\n gen_3D_mesh(\n lamination=stator,\n save_path=join(save_path, \"fig_10_gmsh_mesh_dict.msh\"),\n mesh_size=7e-3,\n user_mesh_dict=mesh_dict,\n is_rect=True,\n Nlayer=18,\n display=False,\n )\n # To see the resulting mesh, gmsh_mesh_dict.msh need to be\n # opened in Gmsh\n\n\n@pytest.mark.skip\n@pytest.mark.GMSH\ndef test_SlotMulti_sym():\n \"\"\"Figure 11: Genera\n te a 3D mesh with GMSH for a lamination\n with several slot types and notches\n \"\"\"\n\n if isinstance(gen_3D_mesh, ImportError):\n raise ImportError(\"Fail to import gen_3D_mesh (gmsh package missing)\")\n\n plt.close(\"all\")\n # Rotor definition\n rotor = LamSlotMulti(\n Rint=0.2, Rext=0.7, is_internal=True, is_stator=False, L1=0.9, Nrvd=2, Wrvd=0.05\n )\n\n # Reference Slot\n Zs = 8\n Slot1 = SlotW10(\n Zs=Zs, W0=50e-3, H0=30e-3, W1=100e-3, H1=30e-3, H2=100e-3, W2=120e-3\n )\n Slot2 = SlotW22(Zs=Zs, W0=pi / 12, H0=50e-3, W2=pi / 6, H2=125e-3)\n\n # Reference slot are duplicated to get 4 of each in alternance\n slot_list = list()\n for ii in range(Zs // 2):\n slot_list.append(SlotW10(init_dict=Slot1.as_dict()))\n slot_list.append(SlotW22(init_dict=Slot2.as_dict()))\n rotor.slot_list = slot_list\n # Set slot position as linspace\n rotor.alpha = linspace(0, 2 * pi, 8, endpoint=False) + pi / Zs\n\n # Set evenly distributed notches\n slot3 = SlotW10(Zs=Zs // 2, W0=40e-3, W1=40e-3, W2=40e-3, H0=0, H1=0, H2=25e-3)\n notch = NotchEvenDist(notch_shape=slot3, alpha=2 * pi / Zs)\n rotor.notch = [notch]\n\n # Plot, check and save\n rotor.plot(sym=4, is_show_fig=False)\n fig = plt.gcf()\n fig.savefig(join(save_path, \"fig_11_SlotMulti_sym.png\"))\n fig.savefig(join(save_path, \"fig_11_SlotMulti_sym.svg\"), format=\"svg\")\n assert len(fig.axes[0].patches) == 1\n\n # Generate the gmsh equivalent\n gen_3D_mesh(\n lamination=rotor,\n save_path=join(save_path, \"fig_11_gmsh_SlotMulti.msh\"),\n sym=4,\n mesh_size=20e-3,\n Nlayer=20,\n display=False,\n )\n # To see the resulting mesh, gmsh_SlotMulti.msh need to be\n # opened in Gmsh\n\n\n@pytest.mark.MachineUD\ndef test_MachineUD():\n \"\"\"Figure 12: Check that you can plot a machine with 4 laminations\"\"\"\n machine = MachineUD()\n machine.name = \"Machine with 4 laminations\"\n\n # Main geometry parameter\n Rext = 170e-3 # Exterior radius of outter lamination\n W1 = 30e-3 # Width of first lamination\n A1 = 2.5e-3 # Width of the first airgap\n W2 = 20e-3\n A2 = 10e-3\n W3 = 20e-3\n A3 = 2.5e-3\n W4 = 60e-3\n\n # Outer stator\n lam1 = LamSlotWind(Rext=Rext, Rint=Rext - W1, is_internal=False, is_stator=True)\n lam1.slot = SlotW22(\n Zs=12, W0=2 * pi / 12 * 0.75, W2=2 * pi / 12 * 0.75, H0=0, H2=W1 * 0.65\n )\n lam1.winding = WindingUD(qs=3, p=3)\n lam1.winding.init_as_CW2LT()\n # External Rotor\n lam2 = LamSlot(\n Rext=lam1.Rint - A1, Rint=lam1.Rint - A1 - W2, is_internal=True, is_stator=False\n )\n lam2.slot = SlotW10(Zs=22, W0=25e-3, W1=25e-3, W2=15e-3, H0=0, H1=0, H2=W2 * 0.75)\n # Internal Rotor\n lam3 = LamSlot(\n Rext=lam2.Rint - A2,\n Rint=lam2.Rint - A2 - W3,\n is_internal=False,\n is_stator=False,\n )\n lam3.slot = SlotW10(\n Zs=22, W0=17.5e-3, W1=17.5e-3, W2=12.5e-3, H0=0, H1=0, H2=W3 * 0.75\n )\n # Inner stator\n lam4 = LamSlotWind(\n Rext=lam3.Rint - A3, Rint=lam3.Rint - A3 - W4, is_internal=True, is_stator=True\n )\n lam4.slot = SlotW10(Zs=12, W0=25e-3, W1=25e-3, W2=1e-3, H0=0, H1=0, H2=W4 * 0.75)\n lam4.winding = WindingUD(qs=3, p=3)\n lam4.winding.init_as_CW2LT()\n # Machine definition\n machine.lam_list = [lam1, lam2, lam3, lam4]\n machine.shaft = Shaft(Drsh=lam4.Rint * 2)\n\n # Plot, check and save\n machine.plot(is_show_fig=False, is_clean_plot=True)\n fig = plt.gcf()\n fig.savefig(join(save_path, \"fig_12_MachineUD.png\"))\n fig.savefig(join(save_path, \"fig_12_MachineUD.svg\"), format=\"svg\")\n assert len(fig.axes[0].patches) == 61\n\n machine.frame = None\n machine.name = None\n\n machine.plot(is_show_fig=False, is_clean_plot=True)\n fig = plt.gcf()\n fig.savefig(join(save_path, \"fig_12_MachineUD_no_frame_no_name.png\"))\n fig.savefig(join(save_path, \"fig_12_MachineUD_no_frame_no_name.svg\"), format=\"svg\")\n assert len(fig.axes[0].patches) == 61\n\n\ndef test_SlotMulti_rotor():\n \"\"\"Figure 13: Check that you can plot a LamSlotMulti rotor (two slots kind + notches)\"\"\"\n plt.close(\"all\")\n # Lamination main dimensions definition\n rotor = LamSlotMulti(Rint=0.2, Rext=0.7, is_internal=True, is_stator=False)\n\n # Reference slot definition\n Slot1 = SlotW10(\n Zs=10, W0=50e-3, H0=30e-3, W1=100e-3, H1=30e-3, H2=100e-3, W2=120e-3\n )\n Slot2 = SlotW22(Zs=12, W0=pi / 12, H0=50e-3, W2=pi / 6, H2=125e-3)\n\n # Reference slot are duplicated to get 5 of each in alternance\n slot_list = list()\n for ii in range(5):\n slot_list.append(SlotW10(init_dict=Slot1.as_dict()))\n slot_list.append(SlotW22(init_dict=Slot2.as_dict()))\n\n # Two slots in the list are modified (bigger than the others)\n rotor.slot_list = slot_list\n rotor.slot_list[0].H2 = 300e-3\n rotor.slot_list[7].H2 = 300e-3\n # Set slots position\n rotor.alpha = array([0, 29, 60, 120, 150, 180, 210, 240, 300, 330]) * pi / 180\n\n # Evenly distributed Notch definition\n slot3 = SlotW10(Zs=12, W0=40e-3, W1=40e-3, W2=40e-3, H0=0, H1=0, H2=25e-3)\n notch = NotchEvenDist(notch_shape=slot3, alpha=15 * pi / 180)\n rotor.notch = [notch]\n\n # Plot, check and save\n rotor.plot(is_show_fig=False, is_clean_plot=True, edgecolor=\"k\")\n fig = plt.gcf()\n fig.savefig(join(save_path, \"fig_13_LamSlotMulti_rotor.png\"))\n fig.savefig(join(save_path, \"fig_13_LamSlotMulti_rotor.svg\"), format=\"svg\")\n assert len(fig.axes[0].patches) == 2\n\n\ndef test_SlotMulti_stator():\n \"\"\"Figure 13: Check that you can plot a LamSlotMulti stator (two slots kind + notches)\"\"\"\n plt.close(\"all\")\n # Lamination main dimensions definition\n stator = LamSlotMulti(Rint=0.2, Rext=0.7, is_internal=False, is_stator=True)\n\n # Reference slot definition\n Slot1 = SlotW10(\n Zs=10, W0=50e-3, H0=30e-3, W1=100e-3, H1=30e-3, H2=100e-3, W2=120e-3\n )\n Slot2 = SlotW22(Zs=12, W0=pi / 12, H0=50e-3, W2=pi / 6, H2=125e-3)\n\n # Reference slot are duplicated to get 5 of each in alternance\n slot_list = list()\n for ii in range(5):\n slot_list.append(SlotW10(init_dict=Slot1.as_dict()))\n slot_list.append(SlotW22(init_dict=Slot2.as_dict()))\n\n # Two slots in the list are modified (bigger than the others)\n stator.slot_list = slot_list\n stator.slot_list[0].H2 = 300e-3\n stator.slot_list[7].H2 = 300e-3\n # Set slots position\n stator.alpha = array([0, 29, 60, 120, 150, 180, 210, 240, 300, 330]) * pi / 180\n\n # Evenly distributed Notch definition\n slot3 = SlotW10(Zs=12, W0=40e-3, W1=40e-3, W2=40e-3, H0=0, H1=0, H2=25e-3)\n notch = NotchEvenDist(notch_shape=slot3, alpha=15 * pi / 180)\n stator.notch = [notch]\n\n # Plot, check and save\n stator.plot(is_show_fig=False, is_clean_plot=True)\n fig = plt.gcf()\n fig.savefig(join(save_path, \"fig_13_LamSlotMulti_stator.png\"))\n fig.savefig(join(save_path, \"fig_13_LamSlotMulti_stator.svg\"), format=\"svg\")\n assert len(fig.axes[0].patches) == 2\n\n\n@pytest.mark.SlotUD\ndef test_SlotUD():\n \"\"\"Figure 14: User Defined slot \"snowflake\" \"\"\"\n\n plt.close(\"all\")\n # Enfore first point on rotor bore\n Rrotor = abs(0.205917893677990 - 0.107339745962156j)\n machine = MachineSRM()\n machine.name = \"User-Defined Slot\"\n # Stator definintion\n machine.stator = LamSlotWind(\n Rint=Rrotor + 5e-3, Rext=Rrotor + 120e-3, is_internal=False, is_stator=True\n )\n machine.stator.slot = SlotW21(\n Zs=36, W0=7e-3, H0=10e-3, H1=0, H2=70e-3, W1=30e-3, W2=0.1e-3\n )\n machine.stator.winding = WindingUD(qs=3, p=3, coil_pitch=5)\n machine.stator.winding.init_as_DWL(nlay=2)\n\n # Rotor definition\n machine.rotor = LamSlot(Rint=0.02, Rext=Rrotor, is_internal=True, is_stator=False)\n machine.rotor.axial_vent = [\n VentilationTrap(Zh=6, Alpha0=0, D0=0.025, H0=0.025, W1=0.015, W2=0.04)\n ]\n # Complex coordinates of half the snowflake slot\n point_list = [\n 0.205917893677990 - 0.107339745962156j,\n 0.187731360198517 - 0.0968397459621556j,\n 0.203257639640145 - 0.0919474411167423j,\n 0.199329436409870 - 0.0827512886940357j,\n 0.174740979141750 - 0.0893397459621556j,\n 0.143564064605510 - 0.0713397459621556j,\n 0.176848674296337 - 0.0616891108675446j,\n 0.172822394854708 - 0.0466628314259158j,\n 0.146001886779019 - 0.0531173140978201j,\n 0.155501886779019 - 0.0366628314259158j,\n 0.145109581933606 - 0.0306628314259158j,\n 0.127109581933606 - 0.0618397459621556j,\n 0.0916025403784439 - 0.0413397459621556j,\n 0.134949327895761 - 0.0282609076372691j,\n 0.129324972242779 - 0.0100025773880714j,\n 0.0690858798800485 - 0.0283397459621556j,\n 0.0569615242270663 - 0.0213397459621556j,\n ]\n machine.rotor.slot = SlotUD(Zs=6)\n machine.rotor.slot.set_from_point_list(is_sym=True, point_list=point_list)\n\n # Plot, check and save\n machine.plot(is_show_fig=False, is_clean_plot=True)\n fig = plt.gcf()\n assert len(fig.axes[0].patches) == 85\n fig.savefig(join(save_path, \"fig_14_SlotUD.png\"))\n fig.savefig(join(save_path, \"fig_14_SlotUD.svg\"), format=\"svg\")\n\n\ndef test_WindingUD():\n \"\"\"Figure 16: User-defined Winding\n From pyleecan/Tests/Plot/LamWind/test_Slot_12_plot.py\n \"\"\"\n plt.close(\"all\")\n machine = MachineDFIM()\n machine.name = \"User Defined Winding\"\n # Rotor definition\n machine.rotor = LamSlotWind(\n Rint=0.2, Rext=0.5, is_internal=True, is_stator=False, L1=0.9, Nrvd=2, Wrvd=0.05\n )\n machine.rotor.axial_vent = [\n VentilationPolar(Zh=6, Alpha0=0, W1=pi / 6, D0=100e-3, H0=0.3)\n ]\n machine.rotor.slot = SlotW12(Zs=6, R2=35e-3, H0=20e-3, R1=17e-3, H1=130e-3)\n machine.rotor.winding = WindingUD(wind_mat=wind_mat, qs=4, p=4, Lewout=60e-3)\n machine.rotor.mat_type.mag = MatMagnetics(Wlam=0.5e-3)\n # Stator definion\n machine.stator = LamSlotWind(\n Rint=0.51,\n Rext=0.8,\n is_internal=False,\n is_stator=True,\n L1=0.9,\n Nrvd=2,\n Wrvd=0.05,\n )\n machine.stator.slot = SlotW12(Zs=18, R2=25e-3, H0=30e-3, R1=0, H1=150e-3)\n machine.stator.winding.Lewout = 60e-3\n machine.stator.winding = WindingUD(qs=3, p=3, coil_pitch=1)\n machine.stator.winding.init_as_DWL(nlay=2)\n machine.stator.mat_type.mag = MatMagnetics(Wlam=0.5e-3)\n\n # Shaft & frame\n machine.shaft = Shaft(Drsh=machine.rotor.Rint * 2, Lshaft=1)\n machine.frame = Frame(Rint=0.8, Rext=0.9, Lfra=1)\n\n # Plot, check and save\n machine.plot(is_show_fig=False)\n fig = plt.gcf()\n fig.savefig(join(save_path, \"fig_16_WindingUD.png\"))\n fig.savefig(join(save_path, \"fig_16_WindingUD.svg\"), format=\"svg\")\n assert len(fig.axes[0].patches) == 77\n\n\ndef test_WindingUD_layer():\n \"\"\"Figure 17: User-defined Winding with uneven winding layer\"\"\"\n plt.close(\"all\")\n # Rotor definition\n rotor = LamSlotWind(\n Rint=0.2, Rext=0.5, is_internal=True, is_stator=False, L1=0.9, Nrvd=2, Wrvd=0.05\n )\n rotor.axial_vent = [VentilationCirc(Zh=6, Alpha0=0, D0=100e-3, H0=0.3)]\n rotor.slot = SlotW11(\n Zs=6, H0=15e-3, W0=60e-3, W1=100e-3, W2=100e-3, H1=20e-3, H2=200e-3\n )\n rotor.slot = rotor.slot.convert_to_SlotUD2()\n assert isinstance(rotor.slot, SlotUD2)\n key = \"Nrad=2, Ntan=2\"\n Top, Bottom = rotor.slot.active_surf.split_line(0, 100, is_join=True)\n Bottom_Left, Bottom_Right = Bottom.split_line(\n 0.320 - 100j, 0.320 + 100j, is_join=True\n )\n Top_Left, Top_Right = Top.split_line(0.410 - 100j, 0.410 + 100j, is_join=True)\n rotor.slot.split_active_surf_dict = {\n key: [Bottom_Right, Bottom_Left, Top_Right, Top_Left]\n }\n rotor.winding = WindingUD(wind_mat=wind_mat, qs=4, p=4, Lewout=60e-3)\n rotor.mat_type.mag = MatMagnetics(Wlam=0.5e-3)\n\n # For testing the _set_split_active_surf_dict method\n rotor.save(join(save_path, \"Fig17_rotor_wind_layer.json\"))\n rotor = load(join(save_path, \"Fig17_rotor_wind_layer.json\"))\n\n # Plot, check and save\n rotor.plot(is_show_fig=False, is_clean_plot=True, edgecolor=\"k\")\n fig = plt.gcf()\n fig.savefig(join(save_path, \"fig_17_WindingUD_layer.png\"))\n fig.savefig(join(save_path, \"fig_17_WindingUD_layer.svg\"), format=\"svg\")\n assert len(fig.axes[0].patches) == 34\n\n\ndef test_BoreFlower(is_show_fig=False):\n \"\"\"Figure 18: LamHole with uneven bore shape\n From pyleecan/Tests/Plot/LamHole/test_Hole_50_plot.py\n \"\"\"\n # Rotor definition\n rotor = LamHole(is_internal=True, Rint=0.021, Rext=0.075, is_stator=False, L1=0.7)\n rotor.hole = list()\n rotor.hole.append(\n HoleM50(\n Zh=8,\n W0=50e-3,\n W1=0,\n W2=1e-3,\n W3=1e-3,\n W4=20.6e-3,\n H0=17.3e-3,\n H1=3e-3,\n H2=0.5e-3,\n H3=6.8e-3,\n H4=0,\n )\n )\n # Rotor axial ventilation ducts\n rotor.axial_vent = list()\n rotor.axial_vent.append(VentilationCirc(Zh=8, Alpha0=0, D0=5e-3, H0=40e-3))\n rotor.axial_vent.append(VentilationCirc(Zh=8, Alpha0=pi / 8, D0=7e-3, H0=40e-3))\n # Remove a magnet\n rotor.hole[0].magnet_1 = None\n # Rotor bore shape\n rotor.bore = BoreFlower(N=8, Rarc=0.05, alpha=pi / 8)\n rotor.yoke = BoreFlower(N=8, Rarc=0.05 / 4, alpha=pi / 8)\n\n # Plot, check and save\n fig, _ = rotor.plot(is_show_fig=is_show_fig)\n fig.savefig(join(save_path, \"fig_18_BoreFlower.png\"))\n fig.savefig(join(save_path, \"fig_18_BoreFlower.svg\"), format=\"svg\")\n # 2 for lam + 3*8 for holes + 16 vents\n assert len(fig.axes[0].patches) == 42\n fig, _ = rotor.plot(is_show_fig=is_show_fig, sym=8)\n fig.savefig(join(save_path, \"fig_18_BoreFlower_sym.png\"))\n fig.savefig(join(save_path, \"fig_18_BoreFlower_sym.svg\"), format=\"svg\")\n # 1 for lam + 3*1 for holes + 3 vents\n assert len(fig.axes[0].patches) == 7\n\n\n@pytest.mark.SPMSM\n@pytest.mark.MagFEMM\n@pytest.mark.long_5s\n@pytest.mark.SingleOP\n@pytest.mark.periodicity\ndef test_ecc_FEMM():\n \"\"\"Figure 19: transfrom_list in FEMM for eccentricities\"\"\"\n SPMSM_015 = load(join(DATA_DIR, \"Machine\", \"SPMSM_015.json\"))\n simu = Simu1(name=\"test_ICEM_2020_ecc\", machine=SPMSM_015)\n simu.machine.name = \"fig_19_Transform_list\"\n\n # Modify stator Rext to get more convincing translation\n SPMSM_015.stator.Rext = SPMSM_015.stator.Rext * 0.9\n gap = SPMSM_015.comp_width_airgap_mec()\n\n # Definition of the enforced output of the electrical module\n N0 = 3000\n Is = ImportMatrixVal(value=array([[0, 0, 0]]))\n time = ImportGenVectLin(start=0, stop=0, num=1, endpoint=True)\n angle = ImportGenVectLin(start=0, stop=2 * 2 * pi / 9, num=2043, endpoint=False)\n simu.input = InputCurrent(\n Is=Is,\n Ir=None, # No winding on the rotor\n OP=OPdq(N0=N0),\n time=time,\n angle=angle,\n angle_rotor_initial=0,\n )\n\n # Definition of the magnetic simulation (is_mmfr=False => no flux from the magnets)\n simu.mag = MagFEMM(\n type_BH_stator=0,\n type_BH_rotor=0,\n is_sliding_band=False, # Ecc => No sliding band\n is_periodicity_a=False,\n is_mmfs=False,\n is_get_meshsolution=True,\n is_fast_draw=False,\n )\n simu.force = None\n simu.struct = None\n\n # Set two transformations\n # First rotate 3rd Magnet\n transform_list = [\n {\"type\": \"rotate\", \"value\": 0.08, \"label\": \"MagnetRotorRadial_S_R0_T0_S3\"}\n ]\n # Then Translate the rotor\n transform_list.append({\"type\": \"translate\", \"value\": gap * 0.75, \"label\": \"Rotor\"})\n simu.mag.transform_list = transform_list\n\n # Run the simulation\n out = Output(simu=simu)\n simu.run()\n\n # FEMM files (mesh and results) are available in Results folder\n copyfile(\n join(out.path_result, \"Femm\", \"fig_19_Transform_list_model.ans\"),\n join(save_path, \"fig_19_Transform_list_model.ans\"),\n )\n copyfile(\n join(out.path_result, \"Femm\", \"fig_19_Transform_list_model.fem\"),\n join(save_path, \"fig_19_Transform_list_model.fem\"),\n )\n # Plot, check, save\n out.mag.meshsolution.plot_mesh(\n save_path=join(save_path, \"fig_19_transform_list.png\"), is_show_fig=False\n )\n\n\n@pytest.mark.skip\n@pytest.mark.long_5s\n@pytest.mark.SPMSM\n@pytest.mark.periodicity\n@pytest.mark.SingleOP\ndef test_Optimization_problem():\n \"\"\"\n Figure19: Machine topology before optimization\n Figure20: Individuals in the fitness space\n Figure21: Pareto Front in the fitness space\n Figure22: Topology to maximize first torque harmonic\n Figure22: Topology to minimize second torque harmonic\n\n WARNING: The computation takes 6 hours on a single 3GHz CPU core.\n The algorithm uses randomization at different steps so\n the results won't be exactly the same as the one in the publication\n \"\"\"\n # ------------------ #\n # DEFAULT SIMULATION #\n # ------------------ #\n\n # First, we need to define a default simulation.\n # This simulation will the base of every simulation during the optimization process\n\n # Load the machine\n SPMSM_001 = load(join(DATA_DIR, \"Machine\", \"SPMSM_001.json\"))\n\n # Definition of the enforced output of the electrical module\n Na_tot = 1024 # Angular steps\n Nt_tot = 32 # Time step\n Is = ImportMatrixVal(\n value=np.array(\n [\n [1.73191211247099e-15, 24.4948974278318, -24.4948974278318],\n [-0.925435413499285, 24.9445002597334, -24.0190648462341],\n [-1.84987984757817, 25.3673918959653, -23.5175120483872],\n [-2.77234338398183, 25.7631194935712, -22.9907761095894],\n [-3.69183822565029, 26.1312592975275, -22.4394210718773],\n [-4.60737975447626, 26.4714170945114, -21.8640373400352],\n [-5.51798758565886, 26.7832286350338, -21.2652410493749],\n [-6.42268661752422, 27.0663600234871, -20.6436734059628],\n [-7.32050807568877, 27.3205080756888, -20.0000000000000],\n [-8.21049055044714, 27.5454006435389, -19.3349100930918],\n [-9.09168102627374, 27.7407969064430, -18.6491158801692],\n [-9.96313590233562, 27.9064876291883, -17.9433517268527],\n [-10.8239220029239, 28.0422953859991, -17.2183733830752],\n [-11.6731175767218, 28.1480747505277, -16.4749571738058],\n [-12.5098132838389, 28.2237124515809, -15.7138991677421],\n [-13.3331131695549, 28.2691274944141, -14.9360143248592],\n [-14.1421356237309, 28.2842712474619, -14.1421356237310],\n [-14.9360143248592, 28.2691274944141, -13.3331131695549],\n [-15.7138991677420, 28.2237124515809, -12.5098132838389],\n [-16.4749571738058, 28.1480747505277, -11.6731175767219],\n [-17.2183733830752, 28.0422953859991, -10.8239220029240],\n [-17.9433517268527, 27.9064876291883, -9.96313590233564],\n [-18.6491158801692, 27.7407969064430, -9.09168102627375],\n [-19.3349100930918, 27.5454006435389, -8.21049055044716],\n [-20, 27.3205080756888, -7.32050807568879],\n [-20.6436734059628, 27.0663600234871, -6.42268661752424],\n [-21.2652410493749, 26.7832286350338, -5.51798758565888],\n [-21.8640373400352, 26.4714170945114, -4.60737975447627],\n [-22.4394210718772, 26.1312592975275, -3.69183822565031],\n [-22.9907761095894, 25.7631194935712, -2.77234338398184],\n [-23.5175120483872, 25.3673918959653, -1.84987984757819],\n [-24.0190648462341, 24.9445002597334, -0.925435413499304],\n ]\n )\n )\n N0 = 400\n Ir = ImportMatrixVal(value=np.zeros((Nt_tot, 28)))\n\n SPMSM_001.name = (\n \"Default SPMSM machine\" # Rename the machine to have the good plot title\n )\n\n # Definition of the simulation\n simu = Simu1(name=\"test_Optimization_problem\", machine=SPMSM_001)\n\n simu.input = InputCurrent(\n Is=Is,\n Ir=Ir, # zero current for the rotor\n OP=OPdq(N0=N0),\n Nt_tot=Nt_tot,\n Na_tot=Na_tot,\n angle_rotor_initial=0.39,\n )\n\n # Definition of the magnetic simulation\n simu.mag = MagFEMM(\n type_BH_stator=2,\n type_BH_rotor=2,\n is_periodicity_a=True,\n )\n\n simu.struct = None\n\n # Default Output\n output = Output(simu=simu)\n\n # Modify magnet width and the slot opening height\n output.simu.machine.stator.slot.H0 = 0.001\n output.simu.machine.rotor.slot.magnet[0].Wmag *= 0.98\n\n # FIG21 Display default machine\n output.simu.machine.plot(is_show_fig=False)\n fig = plt.gcf()\n fig.savefig(join(save_path, \"fig_21_Machine_topology_before_optimization.png\"))\n fig.savefig(\n join(save_path, \"fig_21_Machine_topology_before_optimization.svg\"), format=\"svg\"\n )\n plt.close(\"all\")\n # -------------------- #\n # OPTIMIZATION PROBLEM #\n # -------------------- #\n\n # Objective functions\n \"\"\"Return the average torque opposite (opposite to be maximized)\"\"\"\n tem_av = \"lambda output: -abs(output.mag.Tem_av)\"\n\n \"\"\"Return the torque ripple \"\"\"\n Tem_rip_pp = \"lambda output: abs(output.mag.Tem_rip_pp)\"\n\n my_objs = [\n OptiObjective(\n name=\"Maximization of the average torque\",\n symbol=\"Tem_av\",\n unit=\"N.m\",\n keeper=tem_av,\n ),\n OptiObjective(\n name=\"Minimization of the torque ripple\",\n symbol=\"Tem_rip_pp\",\n unit=\"N.m\",\n keeper=Tem_rip_pp,\n ),\n ]\n\n # Design variables\n my_vars = [\n OptiDesignVarInterval(\n name=\"Stator slot opening\",\n symbol=\"W0\",\n unit=\"m\",\n space=[\n 0.2 * output.simu.machine.stator.slot.W2,\n output.simu.machine.stator.slot.W2,\n ],\n get_value=\"lambda space: random.uniform(*space)\",\n setter=\"simu.machine.stator.slot.W0\",\n ),\n OptiDesignVarInterval(\n name=\"Rotor magnet width\",\n symbol=\"Wmag\",\n unit=\"m\",\n space=[\n 0.5 * output.simu.machine.rotor.slot.W0,\n 0.99 * output.simu.machine.rotor.slot.W0,\n ], # May generate error in FEMM\n get_value=\"lambda space: random.uniform(*space)\",\n setter=\"simu.machine.rotor.slot.magnet[0].Wmag\",\n ),\n ]\n\n # Problem creation\n my_prob = OptiProblem(output=output, design_var=my_vars, obj_func=my_objs)\n\n # Solve problem with NSGA-II\n solver = OptiGenAlgNsga2Deap(problem=my_prob, size_pop=12, nb_gen=40, p_mutate=0.5)\n res = solver.solve()\n\n # ------------- #\n # PLOTS RESULTS #\n # ------------- #\n\n res.plot_generation(x_symbol=\"Tem_av\", y_symbol=\"Tem_rip_pp\")\n fig = plt.gcf()\n fig.savefig(join(save_path, \"fig_20_Individuals_in_fitness_space.png\"))\n fig.savefig(\n join(save_path, \"fig_20_Individuals_in_fitness_space.svg\"), format=\"svg\"\n )\n\n res.plot_pareto(x_symbol=\"Tem_av\", y_symbol=\"Tem_rip_pp\")\n fig = plt.gcf()\n fig.savefig(join(save_path, \"Pareto_front_in_fitness_space.png\"))\n fig.savefig(join(save_path, \"Pareto_front_in_fitness_space.svg\"), format=\"svg\")\n\n # Extraction of best topologies for every objective\n pareto_index = (\n res.get_pareto_index()\n ) # Extract individual index in the pareto front\n\n idx_1 = pareto_index[0] # First objective\n idx_2 = pareto_index[0] # Second objective\n\n Tem_av = res[\"Tem_av\"].result\n Tem_rip_pp = res[\"Tem_rip_pp\"].result\n\n for i in pareto_index:\n # First objective\n if Tem_av[i] < Tem_av[idx_1]:\n idx_1 = i\n # Second objective\n if Tem_rip_pp[i] < Tem_rip_pp[idx_2]:\n idx_2 = i\n\n # Get corresponding simulations\n simu1 = res.get_simu(idx_1)\n simu2 = res.get_simu(idx_2)\n\n # Rename machine to modify the title\n name1 = \"Machine that maximizes the average torque ({:.3f} Nm)\".format(\n abs(Tem_av[idx_1])\n )\n simu1.machine.name = name1\n name2 = \"Machine that minimizes the torque ripple ({:.4f}Nm)\".format(\n abs(Tem_rip_pp[idx_2])\n )\n simu2.machine.name = name2\n\n # plot the machine\n simu1.machine.plot(is_show_fig=False)\n fig = plt.gcf()\n fig.savefig(\n join(save_path, \"fig_21_Topology_to_maximize_average_torque.png\"), format=\"png\"\n )\n fig.savefig(\n join(save_path, \"fig_21_Topology_to_maximize_average_torque.svg\"), format=\"svg\"\n )\n\n simu2.machine.plot(is_show_fig=False)\n fig = plt.gcf()\n fig.savefig(\n join(save_path, \"fig_21_Topology_to_minimize_torque_ripple.png\"), format=\"png\"\n )\n fig.savefig(\n join(save_path, \"fig_21_Topology_to_minimize_torque_ripple.svg\"), format=\"svg\"\n )\n\n\nif __name__ == \"__main__\":\n # test_WindingUD_layer()\n # test_FEMM_sym()\n # test_gmsh_mesh_dict()\n # test_SlotMulti_sym()\n test_MachineUD()\n # test_WindingUD()\n # test_ecc_FEMM()\n # test_WindingUD_layer()\n print(\"Done\")\n","sub_path":"Tests/Plot/test_ICEM_2020.py","file_name":"test_ICEM_2020.py","file_ext":"py","file_size_in_byte":29935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"408162331","text":"# -*- coding: utf-8 -*-\nimport explainaboard.error_analysis as ea\nimport pickle\nimport numpy\nimport codecs\nimport os\n\n\ndef read_data(corpus_type, fn, column_no=-1, delimiter=' '):\n print('corpus_type', corpus_type)\n word_sequences = list()\n tag_sequences = list()\n total_word_sequences = list()\n total_tag_sequences = list()\n with codecs.open(fn, 'r', 'utf-8') as f:\n lines = f.readlines()\n curr_words = list()\n curr_tags = list()\n for k in range(len(lines)):\n line = lines[k].strip()\n if len(line) == 0 or line.startswith('-DOCSTART-'): # new sentence or new document\n if len(curr_words) > 0:\n word_sequences.append(curr_words)\n tag_sequences.append(curr_tags)\n curr_words = list()\n curr_tags = list()\n continue\n\n strings = line.split(delimiter)\n word = strings[0].strip()\n tag = strings[column_no].strip() # be default, we take the last tag\n\n tag = 'B-' + tag\n curr_words.append(word)\n curr_tags.append(tag)\n total_word_sequences.append(word)\n total_tag_sequences.append(tag)\n if k == len(lines) - 1:\n word_sequences.append(curr_words)\n tag_sequences.append(curr_tags)\n # if verbose:\n # \tprint('Loading from %s: %d samples, %d words.' % (fn, len(word_sequences), get_words_num(word_sequences)))\n # return word_sequences, tag_sequences\n return total_word_sequences, total_tag_sequences, word_sequences, tag_sequences\n\n\n# get_aspect_value(test_word_sequences, test_true_tag_sequences, test_word_sequences_sent, dict_precomputed_path)\n\ndef get_aspect_value(test_word_sequences, test_true_tag_sequences, test_word_sequences_sent,\n test_true_tag_sequences_sent, dict_precomputed_path, dict_aspect_func):\n def getSententialValue(test_true_tag_sequences_sent, test_word_sequences_sent, dict_oov=None):\n\n eDen = []\n sentLen = []\n oDen = []\n\n for i, test_sent in enumerate(test_true_tag_sequences_sent):\n pred_chunks = set(ea.get_chunks(test_sent))\n\n num_entityToken = 0\n for pred_chunk in pred_chunks:\n idx_start = pred_chunk[1]\n idx_end = pred_chunk[2]\n num_entityToken += idx_end - idx_start\n\n # introduce the entity token density in sentence ...\n eDen.append(float(num_entityToken) / len(test_sent))\n\n # introduce the sentence length in sentence ...\n sentLen.append(len(test_sent))\n\n # introduce the oov density in sentence ...\n if dict_oov != None:\n num_oov = 0\n for word in test_word_sequences_sent[i]:\n if word not in dict_oov:\n num_oov += 1\n oDen.append(float(num_oov) / len(test_sent))\n\n return eDen, sentLen, oDen\n\n dict_precomputed_model = {}\n for aspect, path in dict_precomputed_path.items():\n print(\"path:\\t\" + path)\n if ea.os.path.exists(path):\n print('load the hard dictionary of entity span in test set...')\n fread = open(path, 'rb')\n dict_precomputed_model[aspect] = pickle.load(fread)\n else:\n raise ValueError(\"can not load hard dictionary\" + aspect + \"\\t\" + path)\n\n dict_span2aspect_val = {}\n for aspect, fun in dict_aspect_func.items():\n dict_span2aspect_val[aspect] = {}\n\n eDen_list, sentLen_list = [], []\n dict_oov = None\n if \"oDen\" in dict_precomputed_model.keys():\n dict_oov = dict_precomputed_model['oDen']\n\n eDen_list, sentLen_list, oDen_list = getSententialValue(test_true_tag_sequences_sent,\n test_word_sequences_sent, dict_oov)\n\n # print(oDen_list)\n\n dict_pos2sid = ea.get_pos2sentid(test_word_sequences_sent)\n dict_ap2rp = ea.get_token_position(test_word_sequences_sent)\n all_chunks = ea.get_chunks(test_true_tag_sequences)\n\n dict_span2sid = {}\n dict_chunkid2span = {}\n for span_info in all_chunks:\n\n span_type = span_info[0].lower()\n\n idx_start = span_info[1]\n idx_end = span_info[2]\n span_sentid = dict_pos2sid[idx_start]\n span_cnt = ' '.join(test_word_sequences[idx_start:idx_end])\n\n span_pos = str(idx_start) + \"_\" + str(idx_end) + \"_\" + span_type\n\n # if str(idx_start) != \"\" or str(idx_end)!= \"\":\n\n span_length = idx_end - idx_start\n\n dict_span2sid[span_pos] = span_sentid\n\n dict_chunkid2span[span_pos] = ea.format4json(span_cnt) + \"|||\" + ea.format4json(\n ' '.join(test_word_sequences_sent[span_sentid]))\n # print(dict_chunkid2span[span_pos])\n # dict_chunkid2span[span_pos] = ' '.join(test_word_sequences[idx_start:idx_end])\n # for bootstrapping\n # if span_sentid not in dict_sid2span.keys():\n # \tdict_sid2span[span_sentid] = [span_pos]\n # else:\n # \tdict_sid2span[span_sentid].append(span_pos)\n\n span_token_list = test_word_sequences[idx_start:idx_end]\n span_token_pos_list = [str(pos) + \"_\" + span_type for pos in range(idx_start, idx_end)]\n\n sLen = float(sentLen_list[span_sentid])\n\n # Sentence Length: sLen\n aspect = \"sLen\"\n if aspect in dict_aspect_func.keys():\n dict_span2aspect_val[aspect][span_pos] = sLen\n #\n #\n # # Relative Position: relPos\n aspect = \"rPos\"\n if aspect in dict_aspect_func.keys():\n dict_span2aspect_val[aspect][span_pos] = (dict_ap2rp[idx_start]) * 1.0 / sLen\n #\n #\n # # Entity Length: eLen\n aspect = \"eLen\"\n if aspect in dict_aspect_func.keys():\n dict_span2aspect_val[aspect][span_pos] = float(span_length)\n #\n # # Entity Density: eDen\n aspect = \"eDen\"\n if aspect in dict_aspect_func.keys():\n dict_span2aspect_val[aspect][span_pos] = float(eDen_list[span_sentid])\n #\n #\n #\n # # Tag: tag\n aspect = \"tag\"\n if aspect in dict_aspect_func.keys():\n dict_span2aspect_val[aspect][span_pos] = span_type\n #\n #\n # # Tag: tag\n aspect = \"capital\"\n if aspect in dict_aspect_func.keys():\n dict_span2aspect_val[aspect][span_pos] = ea.cap_feature(span_cnt)\n\n # OOV Density: oDen\n aspect = \"oDen\"\n if aspect in dict_aspect_func.keys():\n dict_span2aspect_val[aspect][span_pos] = float(oDen_list[span_sentid])\n\n # Span-level Frequency: fre_span\n aspect = \"eFre\"\n span_cnt_lower = span_cnt.lower()\n if aspect in dict_aspect_func.keys():\n preCompute_freqSpan = dict_precomputed_model[aspect]\n span_fre_value = 0.0\n if span_cnt_lower in preCompute_freqSpan:\n span_fre_value = preCompute_freqSpan[span_cnt_lower]\n dict_span2aspect_val[aspect][span_pos] = float(span_fre_value)\n # dict_span2sid[aspect][span_pos] = span_sentid\n\n aspect = \"eCon\"\n if aspect in dict_aspect_func.keys():\n preCompute_ambSpan = dict_precomputed_model[aspect]\n span_amb_value = 0.0\n if span_cnt_lower in preCompute_ambSpan:\n if span_type.lower() in preCompute_ambSpan[span_cnt_lower]:\n span_amb_value = preCompute_ambSpan[span_cnt_lower][span_type]\n dict_span2aspect_val[aspect][span_pos] = span_amb_value\n\n # print(dict_chunkid2span)\n return dict_span2aspect_val, dict_span2sid, dict_chunkid2span\n\n\ndef tuple2str(triplet):\n res = \"\"\n for v in triplet:\n res += str(v) + \"_\"\n return res.rstrip(\"_\")\n\n\ndef evaluate(task_type=\"ner\", analysis_type=\"single\", systems=[], dataset_name='dataset_name', model_name='model_name',\n output_filename=\"./output.json\", is_print_ci=False,\n is_print_case=False, is_print_ece=False):\n path_text = systems[0] if analysis_type == \"single\" else \"\"\n path_comb_output = \"model_name\" + \"/\" + path_text.split(\"/\")[-1]\n dict_aspect_func, dict_precomputed_path, obj_json = ea.load_task_conf(task_dir=os.path.dirname(__file__))\n\n list_text_sent, list_text_token = ea.read_single_column(path_text, 0)\n list_true_tags_sent, list_true_tags_token = ea.read_single_column(path_text, 1)\n list_pred_tags_sent, list_pred_tags_token = ea.read_single_column(path_text, 2)\n\n dict_span2aspect_val, dict_span2sid, dict_chunkid2span = get_aspect_value(list_text_token, list_true_tags_token,\n list_text_sent, list_true_tags_sent,\n dict_precomputed_path, dict_aspect_func)\n dict_span2aspect_val_pred, dict_span2sid_pred, dict_chunkid2span_pred = get_aspect_value(list_text_token,\n list_pred_tags_token,\n list_text_sent,\n list_pred_tags_sent,\n dict_precomputed_path,\n dict_aspect_func)\n\n holistic_performance = ea.f1(list_true_tags_sent, list_pred_tags_sent)[\"f1\"]\n\n # Confidence Interval of Holistic Performance\n confidence_low_overall, confidence_up_overall = 0, 0\n if is_print_ci:\n confidence_low_overall, confidence_up_overall = ea.compute_confidence_interval_f1(dict_span2sid.keys(),\n dict_span2sid_pred.keys(),\n dict_span2sid,\n dict_span2sid_pred,\n n_times=100)\n\n print(\"confidence_low_overall:\\t\", confidence_low_overall)\n print(\"confidence_up_overall:\\t\", confidence_up_overall)\n\n print(\"------------------ Holistic Result\")\n print(holistic_performance)\n\n dict_bucket2span = {}\n dict_bucket2span_pred = {}\n dict_bucket2f1 = {}\n aspect_names = []\n error_case_list = []\n\n for aspect, func in dict_aspect_func.items():\n # print(aspect, dict_span2aspect_val[aspect])\n dict_bucket2span[aspect] = ea.select_bucketing_func(func[0], func[1], dict_span2aspect_val[aspect])\n # print(aspect, dict_bucket2span[aspect])\n # exit()\n dict_bucket2span_pred[aspect] = ea.bucket_attribute_specified_bucket_interval(dict_span2aspect_val_pred[aspect],\n dict_bucket2span[aspect].keys())\n dict_bucket2f1[aspect], error_case_list = get_bucket_f1(dict_bucket2span[aspect],\n dict_bucket2span_pred[aspect], dict_span2sid,\n dict_span2sid_pred, dict_chunkid2span,\n dict_chunkid2span_pred, is_print_ci, is_print_case)\n aspect_names.append(aspect)\n print(\"aspect_names: \", aspect_names)\n\n print(\"------------------ Breakdown Performance\")\n for aspect in dict_aspect_func.keys():\n ea.print_dict(dict_bucket2f1[aspect], aspect)\n print(\"\")\n\n # Calculate databias w.r.t numeric attributes\n dict_aspect2bias = {}\n for aspect, aspect2Val in dict_span2aspect_val.items():\n if type(list(aspect2Val.values())[0]) != type(\"string\"):\n dict_aspect2bias[aspect] = numpy.average(list(aspect2Val.values()))\n\n print(\"------------------ Dataset Bias\")\n for k, v in dict_aspect2bias.items():\n print(k + \":\\t\" + str(v))\n print(\"\")\n\n dict_fine_grained = {}\n for aspect, metadata in dict_bucket2f1.items():\n dict_fine_grained[aspect] = []\n for bucket_name, v in metadata.items():\n # print(\"---------debug--bucket name old---\")\n # print(bucket_name)\n bucket_name = ea.beautify_interval(bucket_name)\n # print(\"---------debug--bucket name new---\")\n # print(bucket_name)\n\n # bucket_value = format(v[0]*100,'.4g')\n bucket_value = format(float(v[0]) * 100, '.4g')\n n_sample = v[1]\n confidence_low = format(float(v[2]) * 100, '.4g')\n confidence_up = format(float(v[3]) * 100, '.4g')\n error_entity_list = v[4]\n\n # instantiation\n dict_fine_grained[aspect].append({\"bucket_name\": bucket_name, \"bucket_value\": bucket_value, \"num\": n_sample,\n \"confidence_low\": confidence_low, \"confidence_up\": confidence_up,\n \"bucket_error_case\": error_entity_list})\n\n # dict_fine_grained[aspect].append({\"bucket_name\":bucket_name, \"bucket_value\":bucket_value, \"num\":n_sample, \"confidence_low\":confidence_low, \"confidence_up\":confidence_up, \"bucket_error_case\":[]})\n\n obj_json[\"task\"] = task_type\n obj_json[\"data\"][\"name\"] = dataset_name\n obj_json[\"data\"][\"output\"] = path_comb_output\n obj_json[\"data\"][\"language\"] = \"English\"\n obj_json[\"data\"][\"bias\"] = dict_aspect2bias\n\n # obj_json[\"model\"][\"results\"][\"overall\"][\"error_case\"] = []\n obj_json[\"model\"][\"name\"] = model_name\n\n obj_json[\"model\"][\"results\"][\"overall\"][\"error_case\"] = error_case_list\n obj_json[\"model\"][\"results\"][\"overall\"][\"performance\"] = holistic_performance\n obj_json[\"model\"][\"results\"][\"overall\"][\"confidence_low\"] = confidence_low_overall\n obj_json[\"model\"][\"results\"][\"overall\"][\"confidence_up\"] = confidence_up_overall\n obj_json[\"model\"][\"results\"][\"fine_grained\"] = dict_fine_grained\n\n ea.save_json(obj_json, output_filename)\n\n\ndef get_bucket_f1(dict_bucket2span, dict_bucket2span_pred, dict_span2sid, dict_span2sid_pred, dict_chunkid2span,\n dict_chunkid2span_pred, is_print_ci, is_print_case):\n # print('------------------ attribute')\n dict_bucket2f1 = {}\n\n # predict: 2_3 -> NER\n dict_pos2tag_pred = {}\n for k_bucket_eval, spans_pred in dict_bucket2span_pred.items():\n for span_pred in spans_pred:\n pos_pred = \"_\".join(span_pred.split(\"_\")[0:2])\n tag_pred = span_pred.split(\"_\")[-1]\n dict_pos2tag_pred[pos_pred] = tag_pred\n # print(dict_pos2tag_pred)\n\n # true: 2_3 -> NER\n dict_pos2tag = {}\n for k_bucket_eval, spans in dict_bucket2span.items():\n for span in spans:\n pos = \"_\".join(span.split(\"_\")[0:2])\n tag = span.split(\"_\")[-1]\n dict_pos2tag[pos] = tag\n # print(dict_pos2tag_pred)\n\n error_case_list = ea.get_error_case(dict_pos2tag, dict_pos2tag_pred, dict_chunkid2span, dict_chunkid2span_pred)\n\n for bucket_interval, spans_true in dict_bucket2span.items():\n spans_pred = []\n\n # print('bucket_interval: ',bucket_interval)\n if bucket_interval not in dict_bucket2span_pred.keys():\n # print(bucket_interval)\n raise ValueError(\"Predict Label Bucketing Errors\")\n else:\n spans_pred = dict_bucket2span_pred[bucket_interval]\n\n confidence_low, confidence_up = 0, 0\n if is_print_ci:\n confidence_low, confidence_up = ea.compute_confidence_interval_f1(spans_true, spans_pred, dict_span2sid,\n dict_span2sid_pred)\n\n confidence_low = format(confidence_low, '.3g')\n confidence_up = format(confidence_up, '.3g')\n\n f1, p, r = ea.evaluate_chunk_level(spans_pred, spans_true)\n\n # print(\"-----------print spans_pred -------------\")\n\n error_entity_list = []\n if is_print_case:\n for span_true in spans_true:\n if span_true not in spans_pred:\n # print(span_true)\n pos_true = \"_\".join(span_true.split(\"_\")[0:2])\n tag_true = span_true.split(\"_\")[-1]\n\n if pos_true in dict_pos2tag_pred.keys():\n tag_pred = dict_pos2tag_pred[pos_true]\n if tag_pred != tag_true:\n error_entity_list.append(\n dict_chunkid2span[span_true] + \"|||\" + tag_true + \"|||\" + dict_pos2tag_pred[pos_true])\n else:\n error_entity_list.append(dict_chunkid2span[span_true] + \"|||\" + tag_true + \"|||\" + \"O\")\n\n # print(\"confidence_low:\\t\", confidence_low)\n # print(\"confidence_up:\\t\", confidence_up)\n # print(\"F1:\\t\", f1)\n # print(error_entity_list)\n\n # print(\"------------------------------------------\")\n\n dict_bucket2f1[bucket_interval] = [f1, len(spans_true), confidence_low, confidence_up, error_entity_list]\n\n # if bucket_interval[0] == 1.0:\n # \tprint(\"debug-f1:\",f1)\n # \tprint(spans_pred[0:20])\n # \tprint(spans_true[0:20])\n # print(\"dict_bucket2f1: \",dict_bucket2f1)\n return ea.sort_dict(dict_bucket2f1), error_case_list\n","sub_path":"explainaboard/tasks/ner/eval_spec.py","file_name":"eval_spec.py","file_ext":"py","file_size_in_byte":17575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"308818874","text":"\"\"\"Collection of tests around loading cookiecutter config.\"\"\"\nimport pytest\nimport os\n\nfrom yaml.scanner import ScannerError\n\nfrom tackle import utils\nfrom tackle.exceptions import ConfigDoesNotExistException\nfrom tackle.parser.settings import get_settings\n\n\ndef test_merge_configs():\n \"\"\"Verify default and user config merged in expected way.\"\"\"\n default = {\n 'cookiecutters_dir': '/home/example/some-path-to-templates',\n 'replay_dir': '/home/example/some-path-to-replay-files',\n 'default_context': {},\n 'abbreviations': {\n 'gh': 'https://github.com/{0}.git',\n 'gl': 'https://gitlab.com/{0}.git',\n 'bb': 'https://bitbucket.org/{0}',\n },\n }\n\n user_config = {\n 'default_context': {\n 'full_name': 'Raphael Pierzina',\n 'github_username': 'hackebrot',\n },\n 'abbreviations': {\n 'gl': 'https://gitlab.com/hackebrot/{0}.git',\n 'pytest-plugin': 'https://github.com/pytest-dev/pytest-plugin.git',\n },\n }\n\n expected_config = {\n 'cookiecutters_dir': '/home/example/some-path-to-templates',\n 'replay_dir': '/home/example/some-path-to-replay-files',\n 'default_context': {\n 'full_name': 'Raphael Pierzina',\n 'github_username': 'hackebrot',\n },\n 'abbreviations': {\n 'gh': 'https://github.com/{0}.git',\n 'gl': 'https://gitlab.com/hackebrot/{0}.git',\n 'bb': 'https://bitbucket.org/{0}',\n 'pytest-plugin': 'https://github.com/pytest-dev/pytest-plugin.git',\n },\n }\n\n assert utils.merge_configs(default, user_config) == expected_config\n\n\ndef test_get_config(change_dir):\n \"\"\"Verify valid config opened and rendered correctly.\"\"\"\n conf = get_settings(config_file='test-config/valid-config.yaml')\n expected_conf = {\n 'tackle_dir': '/home/example/some-path-to-templates',\n 'replay_dir': '/home/example/some-path-to-replay-files',\n 'default_context': {\n 'full_name': 'Firstname Lastname',\n 'email': 'firstname.lastname@gmail.com',\n 'github_username': 'example',\n },\n 'abbreviations': {\n 'gh': 'https://github.com/{0}.git',\n 'gl': 'https://gitlab.com/{0}.git',\n 'bb': 'https://bitbucket.org/{0}',\n 'helloworld': 'https://github.com/hackebrot/helloworld',\n },\n }\n assert conf.dict()['abbreviations'] == expected_conf['abbreviations']\n assert conf.dict()['default_context'] == expected_conf['default_context']\n assert conf.dict()['replay_dir'] == expected_conf['replay_dir']\n\n\ndef test_get_config_does_not_exist():\n \"\"\"Check that `exceptions.ConfigDoesNotExistException` is raised when \\\n attempting to get a non-existent config file.\"\"\"\n expected_error_msg = 'Config file tests/not-exist.yaml does not exist.'\n with pytest.raises(ConfigDoesNotExistException) as exc_info:\n get_settings('tests/not-exist.yaml')\n assert str(exc_info.value) == expected_error_msg\n\n\n#\ndef test_invalid_config(change_dir):\n \"\"\"An invalid config file should raise an `InvalidConfiguration` \\\n exception.\"\"\"\n with pytest.raises(ScannerError):\n get_settings('test-config/invalid-config.yaml')\n\n\ndef test_get_config_with_defaults(change_dir):\n \"\"\"A config file that overrides 1 of 3 defaults.\"\"\"\n conf = get_settings('test-config/valid-partial-config.yaml')\n default_cookiecutters_dir = os.path.expanduser('~/.tackle/')\n default_replay_dir = os.path.expanduser('~/.tackle/replay')\n expected_conf = {\n 'tackle_dir': default_cookiecutters_dir,\n 'replay_dir': default_replay_dir,\n 'default_context': {\n 'full_name': 'Firstname Lastname',\n 'email': 'firstname.lastname@gmail.com',\n 'github_username': 'example',\n },\n 'abbreviations': {\n 'gh': 'https://github.com/{0}.git',\n 'gl': 'https://gitlab.com/{0}.git',\n 'bb': 'https://bitbucket.org/{0}',\n },\n }\n assert conf.dict()['default_context'] == expected_conf['default_context']\n assert conf.dict()['abbreviations'] == expected_conf['abbreviations']\n assert conf.dict()['replay_dir'] == expected_conf['replay_dir']\n","sub_path":"tests/parser/settings/test_get_config.py","file_name":"test_get_config.py","file_ext":"py","file_size_in_byte":4293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"310263955","text":"#!/usr/bin/env python\n# _*_ encoding: utf-8 _*_\n\"\"\"\n@time: 2020/9/17 上午8:54\n@file: loss.py\n@author: caoyuhua\n@contact: caoyhseu@126.com\n\"\"\"\nimport torch\nimport torch.nn as nn\n\n\n# 二分类\nclass Focal_Loss(nn.Module):\n def __init__(self, gamma=2, alpha=0.25, size_average=True):\n super(Focal_Loss, self).__init__()\n self.gamma = gamma\n self.alpha = alpha\n self.size_average = size_average\n\n def forward(self, input, target):\n pt = torch.softmax(input, dim=1)\n p = pt[:, 1, :, :]\n target = target[:, 1, :, :]\n loss = -self.alpha * (1 - p) ** self.gamma * target * torch.log(p) - \\\n (1 - self.alpha) * p ** self.gamma * (1 - target)*torch.log(1 - p)\n if self.size_average:\n return loss.mean()\n else:\n return loss.sum()\n\n\n# 多分类\nclass FocalLoss(nn.Module):\n def __init__(self, class_num, alpha=None, gamma=2, use_alpha=False, size_average=True):\n super(FocalLoss, self).__init__()\n self.class_num = class_num\n self.alpha = alpha\n self.gamma = gamma\n if use_alpha:\n self.alpha = torch.tensor(alpha).cuda()\n\n self.softmax = nn.Softmax(dim=1)\n self.use_alpha = use_alpha\n self.size_average = size_average\n\n def forward(self, pred, target):\n prob = self.softmax(pred.view(-1,self.class_num))\n prob = prob.clamp(min=0.0001,max=1.0)\n\n target_ = torch.zeros(target.size(0),self.class_num).cuda()\n target_.scatter_(1, target.view(-1, 1).long(), 1.)\n\n if self.use_alpha:\n batch_loss = - self.alpha.double() * torch.pow(1-prob,self.gamma).double() * prob.log().double() * target_.double()\n else:\n batch_loss = - torch.pow(1-prob,self.gamma).double() * prob.log().double() * target_.double()\n\n batch_loss = batch_loss.sum(dim=1)\n\n if self.size_average:\n loss = batch_loss.mean()\n else:\n loss = batch_loss.sum()\n\n return loss\n","sub_path":"名企/week4/2/loss.py","file_name":"loss.py","file_ext":"py","file_size_in_byte":2017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"284673927","text":"import asyncio\nimport logging\n\nimport aiohttp\nimport asyncpg\nimport discord\n\nfrom .classes.bot import PINK\nfrom .classes.version import Version\nfrom .logging import setup_logging\nfrom .settings import settings\n\nlog = logging.getLogger(__name__)\n\ntry:\n import uvloop\nexcept ImportError:\n print(\"uvloop is not installed\")\nelse:\n uvloop.install()\n\n\nasync def main() -> None:\n setup_logging()\n\n version = Version()\n\n log.info(f\"running on version {version.full()}\")\n\n if settings.sentry.dsn is not None:\n import sentry_sdk\n\n sentry_sdk.init(\n settings.sentry.dsn,\n )\n else:\n log.warning(\"skipped sentry initialization\")\n\n session = aiohttp.ClientSession(headers={\"user-agent\": \"PINK bot\"})\n pg = asyncpg.create_pool(\n host=settings.database.host,\n port=settings.database.port,\n user=settings.database.user,\n password=settings.database.password,\n database=settings.database.database,\n )\n\n pink = PINK(\n session=session,\n pg=pg,\n version=version,\n command_prefix=settings.bot.prefix,\n case_insensitive=True,\n allowed_mentions=discord.AllowedMentions(roles=False, everyone=False, users=True),\n intents=discord.Intents(\n guilds=True,\n members=True,\n emojis=True,\n messages=True,\n message_content=True,\n reactions=True,\n ),\n )\n\n async with pink, session, pg:\n await pink.start(settings.bot.token)\n\n\nif __name__ == \"__main__\":\n try:\n asyncio.run(main())\n except KeyboardInterrupt:\n log.warning(\"KeyboardInterrupt\")\n","sub_path":"src/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"223645465","text":"class Paperboy: \n '''\n This class will represent a paperboy and his amount of papers delivered and amount \n of money made \n ''' \n\n def __init__(self, name='', experience='', earnings = 0): \n self.name = name\n self.experience = experience \n self.earnings = earnings\n \n \n def __str__(self): \n return f'My name is {self.name}, I made {self.earnings} delivering {int(self.quota())} papers.'\n \n def quota(self): \n papers = 50 \n new_quota = self.experience / 2\n if self.experience <= 0: \n return papers \n elif self.experience >= 0: \n papers += new_quota\n return papers \n \n def deliver(self, start_addr, end_addr): \n \n\n total_houses = end_addr - start_addr + 1 \n \n if self.quota() > total_houses: \n self.earnings += round((total_houses * .25 ) - 2, 2) \n elif self.quota() < total_houses: \n diff = total_houses - self.quota()\n diff *= .50\n qu = self.quota() * .25 \n total = qu + diff \n self.earnings += round(total, 2) \n \n \n \n def report(self): \n return f''' \n My name is {self.name}, \n I\\ve delivered {self.quota()} papers, \n and I have made ${self.earnings}. :) \n ''' \n\n\njack = Paperboy('Jack', 5)\njack.quota() # 80\njack.deliver(1, 75) # 16.75\njack.earnings # 34.25\njack.report() # \"I'm Tommy, I've been delivered 135 papers and I've earned $34.25 so far!\"\n\nprint(jack) \n\ntommy = Paperboy(\"Tommy\", 0)\n\ntommy.quota() # 50\ntommy.deliver(101, 160) # 17.5\ntommy.earnings # 17.5\ntommy.report() # \"I'm Tommy, I've delivered 60 papers and I've earned $17.5 so far!\"\n\n\nprint(tommy)\n\nrocky = Paperboy(\"Rocky\", 60)\n\nrocky.quota() # 80\nrocky.deliver(1, 75) # 16.75\nrocky.earnings # 34.25\nrocky.report() # \"I'm Tommy, I've been delivered 135 papers and I've earned $34.25 so far!\"\n\nprint(rocky) \n","sub_path":"paperboy/paper.py","file_name":"paper.py","file_ext":"py","file_size_in_byte":1992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"126879746","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Aug 9 21:53:32 2020\n\n@author: anarya\n\"\"\"\n\nimport numpy as np\nfrom numpy import pi\nfrom scipy import stats\nfrom scipy import special\nfrom scipy.interpolate import interp1d\nfrom source_mu import Fisher,SNR\nimport h5py\n#from source import SNR\nfrom astropy.cosmology import FlatLambdaCDM\nfrom astropy.cosmology import z_at_value\nfrom matplotlib import pyplot as ppl\ncosmo=FlatLambdaCDM(70.5,0.2736)\nfrom scipy.optimize import curve_fit\nfrom scipy.optimize import fsolve\nfrom scipy.optimize import root\nimport corner\n#from scipy import stats\nfrom scipy import interpolate\nimport scipy.integrate as integrate\nfrom scipy.special import erfc\n#from Selection import P_det_H0\nfrom joblib import Parallel, delayed\nimport multiprocessing\nimport math\n\"\"\" Geometricised Units; c=G=1, Mass[1500 meter/Solar Mass], Distance[meter], Time[3.0e8 meter/second]\"\"\"\n\n\"\"\"Parameters: (ln Mc_z, ln(Lambda),tc,Phi_c,ln d)\"\"\"\n\n# standard siren (EOS: SLY)\nm1_SLY = m2_SLY = 1.433684*1500. \t \t \nLambda_SLY=2.664334e+02\nPN_order=3.5\ndl_dM_SLY=(3.085067e+02-1.997018e+02)/((1.433684e+00 -1.493803)*1500.*2.)\nsm1=sm2=0.09*1500.\nZ_true=1.5\n\nN=100000\nz_peak=2.5\nz_Max=10.\n#load data\nm,L=np.loadtxt('Mass_Vs_TidalDeformability_SLY.txt',usecols=(0,1),unpack=True)\nm*=1500.\nm_l=min(m)\nm_u=max(m)\nmass=interp1d(L,m,kind='cubic')\nLamb=interp1d(m,L,kind='cubic')\nl_l=min(L)\nl_u=max(L)\nce_fs, ce_asd , et_asd, aligo_asd = np.loadtxt('Amplitude_of_Noise_Spectral_Density.txt', usecols=[0,3,2,1],unpack = True)\n\nRho_Th=8.0\n# correct units\nc=G=1\nc1=3.0e8\nMpc=3.086e22\n\nce_fs *= c1**-1.\nce_asd *= c1**0.5\net_asd *= c1**0.5\n\n#Draw True Values\ndef Draw_true(m10,m20,Lambda,dLambda,cosmo):\n beta=2.*z_Max/z_peak -2.\n z=np.random.beta(3,beta+1)*z_Max\n \n#COnly draw values within interpolation range \n \n m1_z=m10*(1.+z)\n m2_z=m20*(1.+z)\n \n Mz=m1_z+m2_z\n mu_z=m1_z*m2_z/Mz\n \n pc=np.random.uniform(0,2.*np.pi)\n tc=np.random.uniform(0,1)\n \n Mc_z=Mz**(2./5.)*mu_z**(3./5.)\n \n \n d_l=cosmo.luminosity_distance(z)\n \n d_l=d_l.value*Mpc\n Th=(np.random.beta(2,4))\n deff=d_l/Th\n \n eta=(mu_z/Mc_z)**(5./2.)\n Lambda=Lamb(m10)\n Lambdat=Lambda*(1.+7.*eta - 31.*eta**2)*16./13.\n return Th,Mc_z,mu_z,tc,pc,Lambdat,deff,m10,m20,z,d_l\n\n#Draw Measured Values from Fisher Matrix evaluated at True Values\ndef Draw_Measured(Mc_z,mu_z,Lambdat,deff,Th,z_true):\n Mean=np.array([np.log(Mc_z),np.log(mu_z),np.log(abs(Lambdat)),np.log(deff),1.,1.])\n V=Fisher(Mc_z,Lambdat,mu_z,deff,1.,1.,ce_fs,ce_asd)\n #print(V)\n Cov=np.absolute(np.linalg.inv(V))\n X1=[]\n X2=[]\n X3=[]\n X4=[]\n for i in range(4000):\n#Only draw values within Interpolation Range\n while True:\n Mc_z,mu_z,Lambdat,deff,tc,pc=np.random.multivariate_normal(Mean,Cov)\n M_z=2.5*Mc_z-1.5*mu_z\n if(M_znp.log((m_l+m_l)*(1.+z_true))): \n Mc_z=np.exp(Mc_z)\n Lambdat=np.exp(Lambdat)\n deff=np.exp(deff)\n mu_z=np.exp(mu_z)\n eta=(mu_z/Mc_z)**2.5\n \n Lambda=Lambdat/((1.+7.*eta - 31.*eta**2)*16./13.)\n h=0.1*Lambda\n \n if(Lambda<(max(L)-h) and Lambda>(min(L)+h)):\n break\n X1.append(Mc_z)\n X2.append(mu_z)\n X3.append(Lambdat)\n X4.append(deff)\n \n Mc_z=np.array(X1)\n Mu_z=np.array(X2)\n Lambdat=np.array(X3)\n deff=np.array(X4)\n Th=(np.random.beta(2,4))\n \n Th=np.random.beta(2,4)\n return Mc_z, Mu_z, Lambdat, deff, Th\nN_events=1000\nf=h5py.File('data_mu.h5','w')\nfor i in range(0,N_events):\n#Introduce SNR Bias \n while True:\n Th,Mc_z_true,mu_z_true,tc,pc,Lambdat_true,deff_true,m1,m2,z_true,dl_true=Draw_true(m1_SLY,m2_SLY,Lambda_SLY,dl_dM_SLY,cosmo)\n if( SNR(Mc_z_true,mu_z_true,deff_true,ce_fs,ce_asd)**0.5>Rho_Th):\n break\n\n Mc_z, Mu_z, Lambdat, deff, Th=Draw_Measured(Mc_z_true, mu_z_true, Lambdat_true, deff_true, Th, z_true)\n f.create_dataset('Measured_values_event_no.='+str(i),data=np.array([Mc_z,Mu_z,Lambdat,deff]))\n f.create_dataset('True_values_evebt_no.='+str(i),data=np.array([Mc_z_true,mu_z_true,Lambdat_true,deff_true]))\nf.close()\n","sub_path":"old_codes/24months/generate_events_mu.py","file_name":"generate_events_mu.py","file_ext":"py","file_size_in_byte":4372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"113644268","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 ('categories', '0001_initial'),\n ('manufacturers', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Attribute',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)),\n ('code', models.CharField(max_length=50, verbose_name='Значение')),\n ],\n options={\n 'verbose_name': 'Характеристика',\n 'verbose_name_plural': 'Характеристики',\n },\n ),\n migrations.CreateModel(\n name='AttributeName',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)),\n ('name', models.CharField(max_length=50)),\n ],\n options={\n 'verbose_name': 'Имя характеристики',\n 'verbose_name_plural': 'Имя характеристики',\n },\n ),\n migrations.CreateModel(\n name='AttributeSet',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)),\n ('name', models.CharField(max_length=50)),\n ],\n options={\n 'verbose_name': 'Название группы характеристики',\n 'verbose_name_plural': 'Названия групп характеристик',\n },\n ),\n migrations.CreateModel(\n name='Product',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)),\n ('name', models.CharField(max_length=100, verbose_name='Наименование')),\n ('short_description', models.CharField(max_length=100, verbose_name='Краткое описание')),\n ('full_description', models.TextField(verbose_name='Полное описание')),\n ('price', models.DecimalField(verbose_name='Цена', max_digits=10, decimal_places=2)),\n ('is_available', models.BooleanField(verbose_name='В наличии')),\n ('how_many', models.SmallIntegerField(verbose_name='Осталось на складе')),\n ('code', models.CharField(max_length=50, verbose_name='Артикул')),\n ('category', models.ManyToManyField(verbose_name='Категория', to='categories.Category')),\n ('manufacturer', models.ForeignKey(verbose_name='Производитель', to='manufacturers.Manufacturer')),\n ],\n options={\n 'verbose_name': 'Продукт',\n 'verbose_name_plural': 'Продукты',\n },\n ),\n migrations.CreateModel(\n name='ProductImages',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)),\n ('image', models.ImageField(default='no-image.png', upload_to='products')),\n ('product', models.ForeignKey(to='products.Product')),\n ],\n options={\n 'verbose_name': 'Изображения продукта',\n 'verbose_name_plural': 'Изображения продуктов',\n },\n ),\n migrations.AddField(\n model_name='attribute',\n name='attribute_set',\n field=models.ForeignKey(verbose_name='Группа характеристики', to='products.AttributeSet', related_name='set'),\n ),\n migrations.AddField(\n model_name='attribute',\n name='name',\n field=models.ForeignKey(verbose_name='Наименование', to='products.AttributeName'),\n ),\n migrations.AddField(\n model_name='attribute',\n name='product',\n field=models.ForeignKey(verbose_name='Продукт', to='products.Product', related_name='attributes'),\n ),\n ]\n","sub_path":"store/products/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":4357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"39425998","text":"#!/usr/bin/python\n\nimport numpy as np\nimport pylab as plt\nimport itertools\n\nimport seaborn as sns\n\nimport math\n\ndef root(num, r):\n base = num ** (1.0/r)\n roots = [base]\n for i in range(1, r):\n roots.append(complex(base * math.cos(2*math.pi * i / r), base * math.sin(2*math.pi * i / r)))\n return roots\n\nroots = root(2*math.sqrt(3)-2j, 2)\n\nn = 4\ncolors = sns.color_palette(\"hls\", n)\n\nplt.figure(figsize=(10,10))\n\nfor root,c in zip(roots,colors):\n plt.arrow(0,0,root.real,root.imag,ec=c,lw=3,label='2 cis {}'.format(roots))\n\nplt.xlim(-2,2)\nplt.ylim(-2,2)\nplt.legend()\nplt.show()\n\n","sub_path":"repos/school/Electromagnetism/complexroots.py","file_name":"complexroots.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"353987784","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License.\n# Author: Graham.Williams@microsoft.com\n#\n# A command line script to analyze text.\n#\n# ml language aztext \n# \n# https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/\n# quickstarts/python-sdk\n#\n\n# ----------------------------------------------------------------------\n# Setup\n# ----------------------------------------------------------------------\n\n# Import the required libraries.\n\nimport sys\nimport argparse\n\nfrom utils import request_priv_info\n\n# pip3 install --upgrade --user azure-cognitiveservices-language-textanalytics\n\nfrom azure.cognitiveservices.language.textanalytics import TextAnalyticsClient\nfrom msrest.authentication import CognitiveServicesCredentials\n\n# ----------------------------------------------------------------------\n# Parse command line arguments\n# ----------------------------------------------------------------------\n\noption_parser = argparse.ArgumentParser(add_help=False)\n\noption_parser.add_argument(\n 'sentence',\n nargs=\"*\",\n help='sentence to analyse')\n\nargs = option_parser.parse_args()\n\n# ----------------------------------------------------------------------\n# Request subscription key and endpoint from user.\n# ----------------------------------------------------------------------\n\nkey, endpoint = request_priv_info()\n\ncredentials = CognitiveServicesCredentials(key)\nclient = TextAnalyticsClient(endpoint=endpoint, credentials=credentials)\n\n# ------------------------------------------------------------------------\n# Helper function\n# ------------------------------------------------------------------------\n\ndef analyseText(txt):\n documents = [{ 'id': '1', 'text': txt }]\n response = client.detect_language(documents=documents)\n\n l = response.documents[0]\n dl = l.detected_languages[0]\n\n print(f\"{dl.score},{dl.iso6391_name},{dl.name}\", end=\"\")\n\n# ------------------------------------------------------------------------\n# Obtain text and analyze.\n# ------------------------------------------------------------------------\n\ntxt = \" \".join(args.sentence)\n\nif txt != \"\":\n analyseText(txt)\nelif not sys.stdin.isatty():\n for txt in sys.stdin.readlines():\n analyseText(txt)\n print()\nelse:\n print(\"Enter text to be analysed. Quit with Empty or Ctrl-d.\\n\")\n prompt = '> '\n try:\n txt = input(prompt)\n except EOFError:\n print()\n sys.exit(0)\n\n while txt != '':\n\n analyseText(txt)\n\n try:\n print()\n txt = input(prompt)\n except EOFError:\n print()\n sys.exit(0)\n","sub_path":"language.py","file_name":"language.py","file_ext":"py","file_size_in_byte":2701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"77857990","text":"from django.conf import settings\nfrom django.template.loader import render_to_string\n\nfrom core import tasks\n\n\nclass MultiUserOwnershipBaseNotification:\n from_email = settings.FAB_FROM_EMAIL\n\n def __init__(self, instance):\n self.instance = instance\n\n @property\n def subject(self):\n return self.instance.subject\n\n def get_context_data(self, **kwargs):\n return {\n 'invite_link': self.instance.invite_link,\n 'requestor': (\n self.instance.requestor.name or\n self.instance.requestor.company_email\n ),\n 'company_name': self.instance.company.name\n }\n\n def get_bodies(self):\n context = self.get_context_data()\n text_body = render_to_string(self.text_template, context)\n html_body = render_to_string(self.html_template, context)\n return text_body, html_body\n\n def send_async(self):\n text_body, html_body = self.get_bodies()\n tasks.send_email.delay(\n subject=self.instance.subject,\n text_body=text_body,\n html_body=html_body,\n recipient_email=self.instance.recipient_email,\n from_email=self.from_email,\n )\n\n\nclass OwnershipChangeNotification(MultiUserOwnershipBaseNotification):\n html_template = 'account_ownership_transfer_email.html'\n text_template = 'account_ownership_transfer_email.txt'\n\n\nclass CollaboratorNotification(MultiUserOwnershipBaseNotification):\n html_template = 'account_collaborator_email.html'\n text_template = 'account_collaborator_email.txt'\n","sub_path":"company/email.py","file_name":"email.py","file_ext":"py","file_size_in_byte":1592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"353413142","text":"import _pickle as pkl\n\n\nclass Sample:\n def __init__(self, filename):\n self.sample_list = []\n self.filename = filename\n\n def create_sample_from_txt(self, k):\n self.sample_list = []\n count = 0\n with open(self.filename, 'rb') as f:\n while count < k:\n new_line = str(f.readline())\n while 'product/productId:' not in new_line:\n new_line = str(f.readline())\n doc = dict()\n doc['_id'] = count\n doc['product/productId'] = new_line.split(\"product/productId: \", 1)[-1][:-3]\n doc['review/userId'] = str(f.readline()).split(\"review/userId: \", 1)[-1][:-3]\n doc['review/profileName'] = str(f.readline()).split(\"review/profileName: \", 1)[-1][:-3]\n doc['review/helpfulness'] = str(f.readline()).split(\"review/helpfulness: \", 1)[-1][:-3]\n doc['review/score'] = float(str(f.readline()).split(\"review/score: \", 1)[-1][:-3])\n doc['review/time'] = str(f.readline()).split(\"review/time: \", 1)[-1][:-3]\n doc['review/summary'] = str(f.readline()).split(\"review/summary: \", 1)[-1][:-3]\n doc['review/text'] = str(f.readline()).split(\"review/text: \", 1)[-1][:-3]\n doc['review/text1'] = set()\n review = doc['review/summary'] + \" \" + doc['review/text']\n\n review_length = len(review)\n review_index = 0\n word = ''\n while review_index < review_length:\n # search in list of special chars. we might get something like 'good.'\n if review[review_index] not in ['`', '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')',\n '_', '-', '+', '=', '{', '[', '}', '}', '|', '\\\\', ':', ';',\n '\"', \"'\", '<', ',', '>', '.', '?', '/', ' ']:\n word += review[review_index]\n else:\n word = word.lower()\n doc['review/text1'].add(word)\n word = ''\n review_index += 1\n\n self.sample_list.append(doc)\n count += 1\n\n filehandler = open('sample_review.p', 'wb')\n pkl.dump(self.sample_list, filehandler)\n filehandler.close()\n\n return len(self.sample_list)\n\n def get_sample(self):\n return self.sample_list\n\n def load_sample_pickle_file(self):\n file = open(\"sample_review.p\", 'rb')\n self.sample_list = pkl.load(file)\n return {\"message\": \"sample loaded\"}\n\n\nsample = Sample('finefoods.txt')","sub_path":"src/services/random_sample.py","file_name":"random_sample.py","file_ext":"py","file_size_in_byte":2728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"170380121","text":"#!/usr/bin/env python3\nfrom requests import Session\nfrom requests.auth import HTTPBasicAuth\nfrom zeep import Client\nfrom zeep.cache import SqliteCache\nfrom zeep.transports import Transport\nfrom zeep.plugins import HistoryPlugin\nfrom zeep import xsd\n\n\nclass MagfaSMS:\n \"\"\"\n\n \"\"\"\n session = Session()\n session.auth = HTTPBasicAuth('user', 'pass')\n\n transport = Transport()\n transport.session = session\n\n history = HistoryPlugin()\n\n client = Client(wsdl='http://sms.magfa.com/services/urn:SOAPSmsQueue?wsdl')\n client.transport = transport\n client.plugins = [history]\n\n factory = client.type_factory('ns1')\n\n def __init__(self):\n self.domain = 'magfa'\n self.sender_numbers = '300071000'\n self.encodings = 2\n self.udhs = ''\n self.message_classes = 1\n self.priorities = 1\n\n def _get_credit(self):\n result = self.client.service.getCredit(domain=self.domain)\n return result\n\n def _enqueue(self, message_bodies, recipient_numbers, checking_message_ids=''):\n result = self.client.service.enqueue(\n domain=self.domain,\n messageBodies=self.factory.ArrayOf_xsd_string([str(message_bodies)]),\n recipientNumbers=self.factory.ArrayOf_xsd_string([str(recipient_numbers)]),\n senderNumbers=self.factory.ArrayOf_xsd_string([str(self.sender_numbers)]),\n encodings=self.factory.ArrayOf_xsd_int([str(self.encodings)]),\n udhs=self.factory.ArrayOf_xsd_string(xsd.SkipValue),\n messageClasses=self.factory.ArrayOf_xsd_int([str(self.message_classes)]),\n priorities=self.factory.ArrayOf_xsd_int([str(self.priorities)]),\n checkingMessageIds=self.factory.ArrayOf_xsd_long([str(checking_message_ids)]),\n )\n return result[0].text\n\n def send(self, message, mobile, message_id=None):\n return self._enqueue(message_bodies=message, recipient_numbers=mobile, checking_message_ids=message_id)\n\n def test(self):\n pass\n","sub_path":"lib.py","file_name":"lib.py","file_ext":"py","file_size_in_byte":2016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"626753706","text":"import logging\nimport time\nimport math\nfrom typing import List\nfrom typing import Optional\nimport dataclasses\n\nimport click\n\ndef get_seat_from_string(seatString: str)-> (int, int):\n maxRow = 127\n minRow = 0\n maxCol = 7\n minCol = 0\n rowString = seatString[:7]\n colString = seatString[7:]\n for character in rowString:\n if character == 'F':\n maxRow -= math.floor(((maxRow - minRow) / 2) + 1)\n elif character == 'B':\n minRow += math.floor(((maxRow - minRow) / 2) + 1)\n else:\n raise Exception(f'Invalid row character: {character}')\n # print(minRow, maxRow)\n if maxRow != minRow:\n raise Exception(f'Failed to reach single answer for row: {minRow}-{maxRow}')\n for character in colString:\n if character == 'L':\n maxCol -= math.floor(((maxCol - minCol) / 2) + 1)\n elif character == 'R':\n minCol += math.floor(((maxCol - minCol) / 2) + 1)\n else:\n raise Exception(f'Invalid col character: {character}')\n # print(minCol, maxCol)\n if maxCol != minCol:\n raise Exception(f'Failed to reach single answer for col: {minCol}-{maxCol}')\n return (minRow, minCol)\n\ndef run_with_input_file(inputFilePath: str) -> str:\n allSeatIds = []\n with open(inputFilePath, 'r') as inputFile:\n for line in inputFile:\n inputLine = line.strip()\n if not inputLine:\n continue\n seat = get_seat_from_string(inputLine)\n (row, col) = seat\n seatId = row*8 + col\n print(inputLine, seat, seatId)\n allSeatIds.append(seatId)\n sortedSeatIds = sorted(allSeatIds)\n # print(sortedSeatIds)\n previousSeatId = None\n for seatId in sortedSeatIds:\n if previousSeatId is not None and previousSeatId != seatId - 1:\n return str(seatId - 1)\n previousSeatId = seatId\n return str(0)\n\n\n@click.command()\n@click.option('-i', '--input-file', 'inputFilePath', required=True, type=str)\n@click.option('-v', '--verbose', 'verbose', required=False, is_flag=True, default=False)\ndef run(inputFilePath: str, verbose: bool):\n logging.basicConfig(level=logging.DEBUG if verbose else logging.INFO)\n startTime = time.time()\n output = run_with_input_file(inputFilePath=inputFilePath)\n print(f'Time taken: {time.time() - startTime}')\n print(output)\n\nif __name__ == '__main__':\n run()\n","sub_path":"day5-2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"378400945","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html\nfrom pymongo import MongoClient\nfrom scrapy import log\n\nfrom dp_meta import settings\nfrom dp_meta.items import DpCategoryItem, DpLocationItem\n\n\nclass DpMetaPipeline(object):\n def __init__(self):\n host = settings.MONGODB_HOST\n port = settings.MONGODB_PORT\n db_name = settings.MONGODB_DBNAME\n client = MongoClient(host=host, port=port)\n tdb = client[db_name]\n self.categories = tdb['categories']\n self.locations = tdb['locations']\n\n def process_item(self, item, spider):\n if item.__class__ == DpCategoryItem:\n try:\n c = self.categories.find_one({'name': item['name']})\n\n if c:\n self.categories.find_one_and_update(\n {'name': item['name']}, {'$set': {'name': item['name'], 'cid': item['id']}})\n else:\n self.categories.insert_one(\n {'name': item['name'], 'cid': item['id']})\n\n except Exception as error:\n log(error)\n return item\n\n elif item.__class__ == DpLocationItem:\n try:\n c = self.locations.find_one({'name': item['name']})\n\n if c:\n self.locations.find_one_and_update(\n {'name': item['name']}, {'$set': {'name': item['name'], 'cid': item['id']}})\n else:\n self.locations.insert_one(\n {'name': item['name'], 'cid': item['id']})\n except Exception as error:\n log(error)\n return item\n\n else:\n pass\n","sub_path":"dp_meta/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"336085547","text":"import random as r\nai,player='O','X'\nboard=[['_','_','_'],['_','_','_'],['_','_','_']]\nweights=[[3,2,3],[2,4,2],[3,2,3]]\ndef init():\n global ai,player,board,weights\n ai,player='O','X'\n board=[['_','_','_'],['_','_','_'],['_','_','_']]\n weights=[[3,2,3],[2,4,2],[3,2,3]]\ndef move(row,col,ch):\n if board[row][col]=='_':\n board[row][col],weights[row][col]=ch,0\n return True\n else : return False\n\ndef display(move_type='board'):\n if move_type=='cpu' : print('*'*5+'CPU MOVE'+'*'*5)\n elif move_type=='board': print(\"*\"*5+' Board of Tic Tac Toe '+'*'*5)\n else :print('*'*5+'PLAYER MOVE'+'*'*5)\n for i in range(3):\n for j in range(3):\n print(board[i][j],end='\\t')\n print('\\n')\n print('\\n')\n\ndef compare_line(s1,ch):\n return '_' in s1 and s1.count(ch)==2\n\ndef get_position():\n max_value=max([max(x) for x in weights])\n positions=[(i,weights[i].index(max_value)) for i in range(3) if max_value in weights[i]]\n return positions\n\ndef has_tied():\n for row in board:\n if '_' in row: return False\n return True\n\ndef attacking_positiion(ch):\n default='_'\n for i in range(3):\n col=[board[0][i],board[1][i],board[2][i]]\n if compare_line(board[i],ch): return (i,board[i].index(default))\n elif compare_line(col,ch): return (col.index(default),i)\n diag1,diag2=[board[0][0],board[1][1],board[2][2]],[board[0][2],board[1][1],board[2][0]]\n if compare_line(diag1,ch):return (diag1.index(default),diag1.index(default))\n elif compare_line(diag2,ch): return (diag2.index(default),2-diag2.index(default))\n return False\n\ndef ai_move():\n global ai,player\n pos,f=attacking_positiion(ch=ai),False\n if pos!=False:(row,col),f=pos,True\n else :\n pos=attacking_positiion(ch=player)\n if pos!=False: row,col=pos\n else: row,col=r.choice(get_position())\n move(row,col,ai)\n return f\n\ndef run():\n global ai,player\n end,tied,move_type=False,False,None\n print('*'*10+ 'Tic Tac Toe'+'*'*10+'\\n')\n display()\n ch=input('Choose a Character X or O : ')\n if ch=='O': ai,player=player,ai\n while(True):\n if tied:\n print('*'*10+'The match is tied'+'*'*10)\n return\n elif end:\n print('*'*10+move_type+' has own '+'*'*10)\n return\n move_type='player'\n r=int(input(\"\\nEnter next move's row (1 to 3): \"))\n c=int(input(\"Enter next move's column (1 to 3): \"))\n if not move(r-1,c-1,player):\n print('\\nEnter proper positions!!')\n else:\n display(move_type=move_type)\n tied=has_tied()\n if tied: continue\n move_type='cpu'\n end=ai_move()\n display(move_type=move_type)\n tied=has_tied()\ndef main():\n run()\n f='Y'\n while(f=='Y'or f=='y'):\n f=input('Do you want to play again Y or N: ')\n init()\n if f=='Y' or f=='y':run()\n print('\\n\\n'+'*'*10+' Thank You '+'*'*10)\nmain() \n","sub_path":"Lab1/ticTacToe_lab1.py","file_name":"ticTacToe_lab1.py","file_ext":"py","file_size_in_byte":3036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"126492865","text":"\"\"\"\nMichael S. Emanuel\nMon Oct 24 00:55:33 2016\n\nTruncatable primes\nProblem 37\nThe number 3797 has an interesting property.\nBeing prime itself, it is possible to continuously remove digits from\nleft to right, and remain prime at each stage:\n3797, 797, 97, and 7.\nSimilarly we can work from right to left:\n3797, 379, 37, and 3.\n\nFind the sum of the only eleven primes that are both truncatable\nfrom left to right and right to left.\n\nNOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.\n\"\"\"\n\nfrom Euler.Primes import PrimeTable\nfrom typing import List\n\n\ndef isTruncPrimeRight(p: int, pt: PrimeTable) -> bool:\n \"\"\"Is p a truncatable prime from the right?\"\"\"\n # Assumes that p is already verified to be prme\n # Truncate from right to left by integer division\n n: int = p // 10\n while n > 0:\n if not pt.isPrime(n):\n return False\n n //= 10\n # If we reach the end of this loop, p is truncatable\n return True\n\n\ndef isTruncPrimeLeft(p: int, pt: PrimeTable) -> bool:\n \"\"\"Is p a truncatable prime from the left?\"\"\"\n s = str(p)\n n = len(s)\n for i in range(1, n):\n if not pt.isPrime(int(s[i:])):\n return False\n # If we reach the end of this loop, p is truncatable\n return True\n\n\ndef main() -> int:\n # Max prime to test\n N: int = 1000000\n # Instantiate PrimeTable\n pt: PrimeTable = PrimeTable(N)\n # List of discovered truncatable primes\n tp: List[int] = []\n # Test candidate primes\n for p in pt.genPrimes():\n # Loop up to two digit primes\n if p < 10:\n continue\n if isTruncPrimeRight(p, pt) and isTruncPrimeLeft(p, pt):\n tp.append(p)\n if len(tp) >= 11:\n break\n if p > N:\n break\n\n # Print answer\n ans = sum(tp)\n print(f'Answer: {ans}')\n print(f'{len(tp)} Truncatable primes:')\n print(tp)\n return ans\n\n\nif __name__ == \"__main__\":\n # execute only if run as a script\n main()\n","sub_path":"Prob037_TruncatablePrimes.py","file_name":"Prob037_TruncatablePrimes.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"130683548","text":"from abc import ABCMeta, abstractmethod\nfrom abc import abstractproperty # In P3 properties and abstract methods can\n# be nested\n\nfrom . import NOW\nfrom .__operations__ import TokenOperations, get_utc_now\n\n\nclass Token(object):\n __metaclass__ = ABCMeta\n\n def __init__(self, snap_to=None, snap_unit=None, **kwargs):\n self.snap_to = snap_to\n self.snap_unit = snap_unit\n\n @property\n def is_snapped(self):\n \"\"\"\n :rtype: bool\n :return: Whether the token has been snapped, either to the beginning\n or end.\n \"\"\"\n return self.snap_to is not None and self.snap_unit is not None\n\n @abstractproperty\n def is_calculated(self):\n \"\"\"\n :rtype: bool\n :return: Whether the token is modified, meaning it suffers from\n additions or subtractions.\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def to_date(self):\n \"\"\"\n :rtype: datetime.datetime\n :return: datetime representation\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def __str__(self):\n raise NotImplementedError\n\n\nclass SimpleToken(Token):\n \"\"\" A simple token that only takes in account zero or one modifiers, thus\n leveraging memory by ignoring all but the first modifiers. Handy for\n simple usage where the user only works with a limited preset of tokens\n \"\"\"\n def __init__(self, amount=None, unit=None, sign=None, **kwargs):\n self.sign = sign\n self.amount = amount\n self.unit = unit\n\n super(SimpleToken, self).__init__(**kwargs)\n\n @property\n def is_calculated(self):\n return self.amount is not None and self.unit is not None\n\n def to_date(self):\n result = get_utc_now()\n\n if self.is_calculated:\n amount_mod_func = TokenOperations.get_amount_modifier(self.sign,\n self.unit)\n result = amount_mod_func(result, self.amount)\n\n if self.is_snapped:\n amount_mod_func = TokenOperations.get_snap_modifier(self.snap_to,\n self.snap_unit)\n result = amount_mod_func(result)\n\n return result\n\n def __str__(self):\n res = NOW\n if self.is_calculated:\n res += '{}{}{}'.format(self.sign, self.amount, self.unit)\n if self.is_snapped:\n res += '{}{}'.format(self.snap_to, self.snap_unit)\n return res\n\n\nclass ComplexToken(Token):\n \"\"\" Parses all amount modifiers. It should be only used in advanced usage\n modes.\n \"\"\"\n def __init__(self, **kwargs):\n self.values = kwargs.pop('values', [])\n\n super(ComplexToken, self).__init__(**kwargs)\n\n @property\n def is_calculated(self):\n return len(self.values) > 0\n\n def to_date(self):\n result = get_utc_now()\n\n if self.is_calculated:\n for amount_mod in self.values:\n sign = amount_mod['sign']\n unit = amount_mod['unit']\n amount_mod_func = TokenOperations.get_amount_modifier(sign, unit)\n result = amount_mod_func(result, amount_mod['amount'])\n\n if self.is_snapped:\n amount_mod_func = TokenOperations.get_snap_modifier(self.snap_to,\n self.snap_unit)\n result = amount_mod_func(result)\n\n return result\n\n def __str__(self):\n res = NOW\n if self.is_calculated:\n res += ''.join(['{sign}{amount}{unit}'.format(**v)\n for v in self.values])\n if self.is_snapped:\n res += '{}{}'.format(self.snap_to, self.snap_unit)\n return res\n","sub_path":"datetoken/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"308605374","text":"import hypothesis as h\nimport numpy as np\nfrom hypothesis import strategies as st\nfrom hypothesis.extra import numpy as npst\n\nfrom .fft import FFTW\n\nst_myfloats = st.floats(1e-5, 1e5) | st.just(0) | st.floats(-1e5, -1e-5)\nst_arr_shape = st.tuples(st.integers(2, 5), st.integers(2, 5)) \\\n .flatmap(lambda shape: st.tuples(npst.arrays(float, shape, st_myfloats),\n st.tuples(st.integers(shape[0], 6), st.integers(shape[1], 6))))\n\n\n@h.given(st_arr_shape)\ndef test_fft(arr_shape):\n arr, shape = arr_shape\n\n fftw = FFTW(shape, arr.dtype)\n expected = np.fft.rfft2(arr, shape)\n result = fftw(arr)\n\n h.note(expected)\n h.note(result)\n assert np.allclose(expected, result, equal_nan=True)\n\n\nst_arr_arr_shape = st.tuples(st.integers(2, 5), st.integers(2, 5)) \\\n .flatmap(lambda shape: st.tuples(npst.arrays(float, shape, st_myfloats),\n npst.arrays(float, [s - 1 for s in shape], st_myfloats),\n st.tuples(st.integers(shape[0], 6), st.integers(shape[1], 6))))\n\n\n@h.given(st_arr_arr_shape)\ndef test_fft_multiple(arr_arr_shape):\n arr1, arr2, shape = arr_arr_shape\n\n fftw = FFTW(shape, arr1.dtype)\n expected = np.fft.rfft2(arr1, shape)\n result = fftw(arr1)\n\n h.note(expected)\n h.note(result)\n assert np.allclose(expected, result, equal_nan=True)\n\n expected = np.fft.rfft2(arr2, shape)\n result = fftw(arr2)\n\n h.note(expected)\n h.note(result)\n assert np.allclose(expected, result, equal_nan=True)\n\n\n@h.given(st_arr_shape)\ndef test_inverse_fft(arr_shape):\n arr, shape = arr_shape\n\n fft = np.fft.rfft2(arr, shape)\n\n fftw = FFTW(shape, arr.dtype)\n ifftw = fftw.get_inverse()\n expected = np.fft.irfft2(fft, shape)\n result = ifftw(fft)\n\n h.note(expected)\n h.note(result)\n assert np.allclose(expected, result, equal_nan=True)\n","sub_path":"wncc/test_fft.py","file_name":"test_fft.py","file_ext":"py","file_size_in_byte":1899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"552062759","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\r\n__author__ = 'Reiko Aruga and Akihiro Miyata'\r\n__copyright__ = 'Copyright (c) 2014 NTT Corp. All rights reserved.'\r\n__maintainer__ = 'Akihiro Miyata'\r\n__email__ = 'miyata.akihiro@lab.ntt.co.jp'\r\n\r\nimport sensor\r\n\r\nfrom datetime import datetime as dt\r\nimport logging\r\nimport serial\r\nimport time\r\n\r\nclass SensorReader():\r\n def __init__(self, env, snsPort, baudRate, snsTimeout, readSize, readInterval, snsWeight, accDigit):\r\n self.env = env\r\n self.sensors = sensor.SensorAggr()\r\n self.ser = serial.Serial(port = snsPort, baudrate = baudRate, timeout = snsTimeout)\r\n logging.info('Serial port initialized (snsPort = %s, baudRate = %d, snsTimeout = %f).' % (snsPort, baudRate, snsTimeout))\r\n self.readSize = readSize\r\n self.readInterval = readInterval\r\n self.W = snsWeight\r\n self.D = accDigit\r\n\r\n def start(self):\r\n logging.info('SensorReader start (readSize = %d, readInterval = %f, snsWeight = %f, accDigit = %d).' % (self.readSize, self.readInterval, self.W, self.D))\r\n while True:\r\n buf = []\r\n for bd in self.ser.read(self.readSize): buf.append(ord(bd))\r\n recvnum = len(buf)\r\n for i in xrange(recvnum):\r\n if (hex(buf[i]) == hex(ord('$'))) or (hex(buf[i]) == hex(ord('+'))):\r\n try:\r\n length = (buf[i + 2] & 0xff) | ((buf[i + 3] & 0xff) << 8)\r\n if (recvnum - i) < (length + 5): break\r\n else:\r\n z = i + 7\r\n k = buf[z + 6] * 2 + 11\r\n\r\n # Gets the last update time of the sensor.\r\n id = (buf[z + ((buf[z + 6] & 0xff) - 1) * 2 + 7] & 0xff) | ((buf[z + ((buf[z + 6] & 0xff) - 1) * 2 + 8] & 0xff) << 8)\r\n observedTime = self.sensors.lastUpdate(id)\r\n if not observedTime: break\r\n step = (dt.now() - observedTime) / recvnum\r\n\r\n # Reads temperature, luminance, battery and acceleration data.\r\n tmp = (buf[z + k] & 0xff) + ((buf[z + k + 1] & 0xff) << 8)\r\n lum = (buf[z + k + 2] & 0xff) + ((buf[z + k + 3] & 0xff) << 8)\r\n bat = (buf[z + k + 4] & 0xff) + ((buf[z + k + 5] & 0xff) << 8)\r\n k += 6\r\n for c in xrange(z + k, i + length, 6):\r\n xraw = (buf[c] & 0xff) + ((buf[c + 1] & 0xff) << 8)\r\n x = round(xraw * self.W, self.D) if xraw < 128 else round((xraw - 256) * self.W, self.D)\r\n yraw = (buf[c + 2] & 0xff) + ((buf[c + 3] & 0xff) << 8)\r\n y = round(yraw * self.W, self.D) if yraw < 128 else round((yraw - 256) * self.W, self.D)\r\n zraw = (buf[c + 4] & 0xff) + ((buf[c + 5] & 0xff) << 8)\r\n z = round(zraw * self.W, self.D) if zraw < 128 else round((zraw - 256) * self.W, self.D)\r\n self.env.snsData.append([observedTime.strftime('%H:%M:%S.%f'), id, tmp, lum, bat, x, y, z])\r\n observedTime += step\r\n self.sensors.update(id, observedTime)\r\n i += length + 4\r\n except IndexError: pass\r\n time.sleep(self.readInterval)\r\n","sub_path":"sensor/sensorreader.py","file_name":"sensorreader.py","file_ext":"py","file_size_in_byte":3565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"543860412","text":"# 自己做观��手机端慕课用\nimport os\nfrom time import sleep\nfrom random import randint\nrepeat_times = 60\n\n\ndef tap_screen(x, y):\n os.system(\"adb shell input tap {} {}\".format(x, y))\n\n\nif __name__ == \"__main__\":\n for i in range(repeat_times):\n tap_screen(2050, y=220)\n print(i)\n sleep(randint(25, 35))","sub_path":"Python测试/script/china_medicine_class_foot.py","file_name":"china_medicine_class_foot.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"161530086","text":"# https://www.hackerrank.com/challenges/beautiful-triplets/problem\n\ndef beautifulTriplets(d, arr):\n count = 0\n for index in range(len(arr)):\n if arr[index]+d in arr and arr[index]+2*d in arr:\n count += 1\n return count\n\n\nn,d = map(int, input().split())\n\narr = list(map(int, input().split()))\n\ncount= beautifulTriplets(d, arr)\n\nprint(count)","sub_path":"beautifulTriplets.py","file_name":"beautifulTriplets.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"404532859","text":"'''\r\nCreated on Mar 9, 2016\r\n\r\n@author: SashaTheSledDog\r\n'''\r\n\r\nclass PowerPlant(object):\r\n '''\r\n classdocs\r\n '''\r\n\r\n\r\n def __init__(\r\n self, power_plant, hull_percent, num_units, fuel_amount=0):\r\n '''\r\n Constructor\r\n '''\r\n \r\n self.power_plant = power_plant\r\n self.hull_percent = hull_percent\r\n self.num_units = num_units\r\n self.fuel_amount = fuel_amount","sub_path":"warship/component/powerplant.py","file_name":"powerplant.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"57162057","text":"import unittest\nfrom code.world import World\nfrom main import read_world_data, read_images\nimport pygame\nimport code\nfrom code.fighter import Fighter\nfrom code.terrain_objects import Item, TerrainObject\n\n# Get necessary things for the test\n\nhealth_box_img = pygame.image.load('static/img/icons/health_box.png').convert_alpha()\nitem_boxes = {\n 'Health': health_box_img\n}\nlevel = 1\nimg_list = read_images()\nworld_data = read_world_data(level)\nworld = code.world.World()\n\n\nclass TestWorld(unittest.TestCase):\n \"\"\"\n Tests whether in world.py certain objects (e.g., player) are an instance of a certain class (e.g., Fighter)\n \"\"\"\n\n def test_process_data(self):\n \"\"\"\n Test whether in world.py certain objects (e.g., player) are an instance of a certain class (e.g., Fighter)\n \"\"\"\n player, enemy_group, decoration_group, water_group, item_box_group, exit_group = \\\n world.process_data(world_data, img_list, item_boxes)\n # check whether player is an instance of the Fighter class\n self.assertIsInstance(player, Fighter)\n # test whether all enemies are an instance of Fighter class\n self.assertTrue(all([isinstance(enemy, Fighter) for enemy in enemy_group.sprites()]))\n # test whether all decoration is an instance of Decoration class\n self.assertTrue(all([isinstance(decoration, TerrainObject) for decoration in decoration_group.sprites()]))\n # test whether all water is an instance of Water class\n self.assertTrue(all([isinstance(water, TerrainObject) for water in water_group.sprites()]))\n # test whether all item boxes are an instance of Item class\n self.assertTrue(all([isinstance(item_box, Item) for item_box in item_box_group.sprites()]))\n # test whether all exits are an instance of Exit class\n self.assertTrue(all([isinstance(exit, TerrainObject) for exit in exit_group.sprites()]))\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test_package/test_world.py","file_name":"test_world.py","file_ext":"py","file_size_in_byte":1970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"491020603","text":"#! /usr/bin/env python3\n#\n# Disassembler for 6800 microprocessor.\n# Copyright (c) 2013-2015 by Jeff Tranter \n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport sys\nimport argparse\nimport signal\n\n# Avoids an error when output piped, e.g. to \"less\"\nsignal.signal(signal.SIGPIPE, signal.SIG_DFL)\n\n# Addressing modes. Used as indices into opcode table.\nimplied = 0 # e.g. inca\nimmediate = 1 # e.g. ldaa #$12\ndirect = 2 # e.g. ldaa $12\nindexed = 3 # e.g. ldaa $12,x\nextended = 4 # e.g. ldaa $1234\nrelative = 5 # e.g. bra $1234\n\n\n# Lookup table - given addressing mode, returns length of instruction in bytes.\nlengthTable = [\n 1, # 0 - implied\n 2, # 1 - immediate\n 2, # 2 - direct\n 2, # 3 - indexed\n 3, # 4 - extended\n 2, # 5 - relative\n]\n\n# Lookup table - given opcode byte as index, return mnemonic of instruction and addressing mode.\n# Invalid opcodes are listed as \"???\".\nopcodeTable = [\n [\"???\", implied], # 00\n [\"nop\", implied], # 01\n [\"???\", implied], # 02\n [\"???\", implied], # 03\n [\"???\", implied], # 04\n [\"???\", implied], # 05\n [\"tap\", implied], # 06\n [\"tpa\", implied], # 07\n [\"inx\", implied], # 08\n [\"dex\", implied], # 09\n [\"clv\", implied], # 0A\n [\"sev\", implied], # 0B\n [\"clc\", implied], # 0C\n [\"sec\", implied], # 0D\n [\"cli\", implied], # 0E\n [\"sei\", implied], # 0F\n\n [\"sba\", implied], # 10\n [\"cba\", implied], # 11\n [\"???\", implied], # 12\n [\"???\", implied], # 13\n [\"nba\", implied], # 14\n [\"???\", implied], # 15\n [\"tab\", implied], # 16\n [\"tba\", implied], # 17\n [\"???\", implied], # 18\n [\"daa\", implied], # 19\n [\"???\", implied], # 1A\n [\"aba\", implied], # 1B\n [\"???\", implied], # 1C\n [\"???\", implied], # 1D\n [\"???\", implied], # 1E\n [\"???\", implied], # 1F\n\n [\"bra\", relative], # 20\n [\"???\", implied], # 21\n [\"bhi\", relative], # 22\n [\"bls\", relative], # 23\n [\"bcc\", relative], # 24\n [\"bcs\", relative], # 25\n [\"bne\", relative], # 26\n [\"beq\", relative], # 27\n [\"bvc\", relative], # 28\n [\"bvs\", relative], # 29\n [\"bpl\", relative], # 2A\n [\"bmi\", relative], # 2B\n [\"bge\", relative], # 2C\n [\"blt\", relative], # 2D\n [\"bgt\", relative], # 2E\n [\"ble\", relative], # 2F\n\n [\"tsx\", implied], # 30\n [\"ins\", implied], # 31\n [\"pula\", implied], # 32\n [\"pulb\", implied], # 33\n [\"des\", implied], # 34\n [\"txs\", implied], # 35\n [\"psha\", implied], # 36\n [\"pshb\", implied], # 37\n [\"???\", implied], # 38\n [\"rts\", implied], # 39\n [\"???\", implied], # 3A\n [\"rti\", implied], # 3B\n [\"???\", implied], # 3C\n [\"???\", implied], # 3D\n [\"wai\", implied], # 3E\n [\"swi\", implied], # 3F\n\n [\"nega\", implied], # 40\n [\"???\", implied], # 41\n [\"???\", implied], # 42\n [\"com\", implied], # 43\n [\"lsra\", implied], # 44\n [\"???\", implied], # 45\n [\"rora\", implied], # 46\n [\"asra\", implied], # 47\n [\"asla\", implied], # 48\n [\"rola\", implied], # 49\n [\"deca\", implied], # 4A\n [\"???\", implied], # 4B\n [\"inca\", implied], # 4C\n [\"tsta\", implied], # 4D\n [\"???\", implied], # 4E\n [\"clra\", implied], # 4F\n\n [\"neg\", implied], # 50\n [\"???\", implied], # 51\n [\"???\", implied], # 52\n [\"comb\", implied], # 53\n [\"lsrb\", implied], # 54\n [\"???\", implied], # 55\n [\"rorb\", implied], # 56\n [\"asrb\", implied], # 57\n [\"aslb\", implied], # 58\n [\"rolb\", implied], # 59\n [\"decb\", implied], # 5A\n [\"???\", implied], # 5B\n [\"incb\", implied], # 5C\n [\"tstb\", implied], # 5D\n [\"???\", implied], # 5E\n [\"clrb\", implied], # 5F\n\n [\"neg\", indexed], # 60\n [\"???\", implied], # 61\n [\"???\", implied], # 62\n [\"com\", indexed], # 63\n [\"lsr\", indexed], # 64\n [\"???\", implied], # 65\n [\"ror\", indexed], # 66\n [\"asr\", indexed], # 67\n [\"asl\", indexed], # 68\n [\"rol\", indexed], # 69\n [\"dec\", indexed], # 6A\n [\"???\", implied], # 6B\n [\"inc\", indexed], # 6C\n [\"tst\", indexed], # 6D\n [\"jmp\", indexed], # 6E\n [\"clr\", indexed], # 6F\n\n [\"neg\", extended], # 70\n [\"???\", implied], # 71\n [\"???\", implied], # 72\n [\"com\", extended], # 73\n [\"lsr\", extended], # 74\n [\"???\", implied], # 75\n [\"ror\", extended], # 76\n [\"asr\", extended], # 77\n [\"asl\", extended], # 78\n [\"rol\", extended], # 79\n [\"dec\", extended], # 7A\n [\"???\", implied], # 7B\n [\"inc\", extended], # 7C\n [\"tst\", extended], # 7D\n [\"jmp\", extended], # 7E\n [\"clr\", extended], # 7F\n\n [\"sub\", immediate], # 80\n [\"cmp\", immediate], # 81\n [\"sbc\", immediate], # 82\n [\"???\", implied], # 83\n [\"and\", immediate], # 84\n [\"bit\", immediate], # 85\n [\"lda\", immediate], # 86\n [\"???\", implied], # 87 STA #\n [\"eor\", immediate], # 88\n [\"adc\", immediate], # 89\n [\"ora\", immediate], # 8A\n [\"add\", immediate], # 8B\n [\"cpx\", immediate], # 8C\n [\"bsr\", immediate], # 8D\n [\"lds\", immediate], # 8E\n [\"???\", implied], # 8F STS #\n\n [\"sub\", direct], # 90\n [\"cmp\", direct], # 91\n [\"sbc\", direct], # 92\n [\"???\", implied], # 93\n [\"and\", direct], # 94\n [\"bit\", direct], # 95\n [\"lda\", direct], # 96\n [\"sta\", direct], # 97\n [\"eor\", direct], # 98\n [\"adc\", direct], # 99\n [\"ora\", direct], # 9A\n [\"add\", direct], # 9B\n [\"cpx\", direct], # 9C\n [\"???\", implied], # 9D HCF\n [\"lds\", direct], # 9E\n [\"sts\", direct], # 9F\n\n [\"sub\", indexed], # A0\n [\"cmp\", indexed], # A1\n [\"sbc\", indexed], # A2\n [\"???\", implied], # A3\n [\"and\", indexed], # A4\n [\"bit\", indexed], # A5\n [\"ldaa\", indexed], # A6\n [\"staa\", indexed], # A7\n [\"eora\", indexed], # A8\n [\"adca\", indexed], # A9\n [\"oraa\", indexed], # AA\n [\"adda\", indexed], # AB\n [\"cpx\", indexed], # AC\n [\"jsr\", indexed], # AD\n [\"lds\", indexed], # AE\n [\"sts\", indexed], # AF\n\n [\"suba\", extended], # B0\n [\"cmpa\", extended], # B1\n [\"sbca\", extended], # B2\n [\"???\", implied], # B3\n [\"anda\", extended], # B4\n [\"bita\", extended], # B5\n [\"ldaa\", extended], # B6\n [\"staa\", extended], # B7\n [\"eora\", extended], # B8\n [\"adca\", extended], # B9\n [\"oraa\", extended], # BA\n [\"adda\", extended], # BB\n [\"cpx\", extended], # BC\n [\"jsr\", extended], # BD\n [\"lds\", extended], # BE\n [\"sts\", extended], # BF\n\n [\"subb\", immediate], # C0\n [\"cmpb\", immediate], # C1\n [\"sbcb\", immediate], # C2\n [\"???\", implied], # C3\n [\"andb\", immediate], # C4\n [\"bitb\", immediate], # C5\n [\"ldab\", immediate], # C6\n [\"???\", implied], # C7 STA #\n [\"eorb\", immediate], # C8\n [\"adcb\", immediate], # C9\n [\"orab\", immediate], # CA\n [\"addb\", immediate], # CB\n [\"???\", implied], # CC\n [\"???\", implied], # CD\n [\"ldx\", immediate], # CE\n [\"???\", implied], # CF STX #\n\n [\"subb\", direct], # D0\n [\"cmpb\", direct], # D1\n [\"sbcb\", direct], # D2\n [\"???\", implied], # D3\n [\"andb\", direct], # D4\n [\"bitb\", direct], # D5\n [\"ldab\", direct], # D6\n [\"stab\", direct], # D7\n [\"eorb\", direct], # D8\n [\"adcb\", direct], # D9\n [\"orab\", direct], # DA\n [\"addb\", direct], # DB\n [\"???\", implied], # DC\n [\"???\", implied], # DD HCF\n [\"ldx\", direct], # DE\n [\"stx\", direct], # DF\n\n [\"subb\", indexed], # E0\n [\"cmpb\", indexed], # E1\n [\"sbcb\", indexed], # E2\n [\"???\", implied], # E3\n [\"andb\", indexed], # E4\n [\"bitb\", indexed], # E5\n [\"ldab\", indexed], # E6\n [\"stab\", indexed], # E7\n [\"eorb\", indexed], # E8\n [\"adcb\", indexed], # E9\n [\"orab\", indexed], # EA\n [\"addb\", indexed], # EB\n [\"???\", implied], # EC\n [\"???\", implied], # ED\n [\"ldx\", indexed], # EE\n [\"stx\", indexed], # EF\n\n [\"subb\", extended], # F0\n [\"cmpb\", extended], # F1\n [\"sbcb\", extended], # F2\n [\"???\", implied], # F3\n [\"andb\", extended], # F4\n [\"bitb\", extended], # F5\n [\"ldab\", extended], # F6\n [\"stab\", extended], # F7\n [\"eorb\", extended], # F8\n [\"adcb\", extended], # F9\n [\"orab\", extended], # FA\n [\"addb\", extended], # FB\n [\"???\", implied], # FC\n [\"???\", implied], # FD\n [\"ldx\", extended], # FE\n [\"stx\", extended], # FF\n]\n\n# Indicates if uppercase option is in effect.\nupperOption = False\n\n# Functions\n\n\ndef isprint(c):\n \"Return if character is printable ASCII\"\n if c >= '@' and c <= '~':\n return True\n else:\n return False\n\n\ndef case(s):\n \"Return string or uppercase version of string if option is set.\"\n global upperOption\n if upperOption:\n return s.upper()\n else:\n return s\n\n\ndef formatByte(data):\n \"Format an 8-bit byte using the current display format (e.g. hex or octal)\"\n global args\n if args.format == 4: # Octal\n return \"%03o\" % data\n else: # Hex\n return \"%02X\" % data\n\n\ndef formatAddress(data):\n \"Format a 16-bit address using the current display format (e.g. hex or octal)\"\n global args\n if args.format == 4: # Octal\n return \"%06o\" % data\n else: # Hex\n return \"%04X\" % data\n\n# Parse command line options\nparser = argparse.ArgumentParser()\nparser.add_argument(\"filename\", help=\"Binary file to disassemble\")\nparser.add_argument(\"-n\", \"--nolist\", help=\"Don't list instruction bytes (make output suitable for assembler)\", action=\"store_true\")\nparser.add_argument(\"-u\", \"--uppercase\", help=\"Use uppercase for mnemonics\", action=\"store_true\")\nparser.add_argument(\"-a\", \"--address\", help=\"Specify decimal starting address (defaults to 0)\", default=0, type=int)\nparser.add_argument(\"-f\", \"--format\", help=\"Use number format: 1=$1234 2=1234h 3=1234 4=177777 (default 1)\", default=1, type=int, choices=range(1, 5))\nparser.add_argument(\"-i\", \"--invalid\", help=\"Show invalid opcodes as ??? rather than constants\", action=\"store_true\")\nargs = parser.parse_args()\n\n# Get filename from command line arguments.\nfilename = args.filename\n\n# Current instruction address. Silently force it to be in valid range.\naddress = args.address & 0xffff\n\n# Set uppercase output option.\nupperOption = args.uppercase\n\n# Contains a line of output\nline = \"\"\n\n# Open input file.\n# Display error and exit if filename does not exist.\ntry:\n f = open(filename, \"rb\")\nexcept FileNotFoundError:\n print(\"error: input file '%s' not found.\" % filename, file=sys.stderr)\n sys.exit(1)\n\n# Print initial origin address\nif args.nolist is False:\n if args.format == 1:\n print(\"%04X %s $%04X\" % (address, case(\".org\"), address))\n elif args.format == 2:\n print(\"%04X %s %04X%s\" % (address, case(\".org\"), address, case(\"h\")))\n elif args.format == 3:\n print(\"%04X %s %04X\" % (address, case(\".org\"), address))\n else:\n print(\"%06o %s %06o\" % (address, case(\".org\"), address))\nelse:\n if args.format == 1:\n print(\" %s $%04X\" % (case(\".org\"), address))\n elif args.format == 2:\n print(\" %s %04X%s\" % (case(\".org\"), address, case(\"h\")))\n elif args.format == 3:\n print(\" %s %04X\" % (case(\".org\"), address))\n else:\n print(\" %s %06o\" % (case(\".org\"), address))\n\nwhile True:\n try:\n b = f.read(1) # Get binary byte from file\n\n if len(b) == 0: # EOF\n if args.nolist is False:\n if args.format == 4:\n print(\"%06o %s\" % (address, case(\"end\"))) # Exit if end of file reached.\n else:\n print(\"%04X %s\" % (address, case(\"end\"))) # Exit if end of file reached.\n break\n\n if args.nolist is False:\n line = \"%s \" % formatAddress(address) # Print current address\n\n op = ord(b) # Get opcode byte\n\n mnem = case(opcodeTable[op][0]) # Get mnemonic\n\n mode = opcodeTable[op][1] # Get addressing mode\n\n n = lengthTable[mode] # Look up number of instruction bytes\n\n # Handle special case of immediate instructions that are three\n # bytes long.\n if mnem in set([\"cpx\", \"ldx\", \"lds\"]):\n n = 3\n\n # Print instruction bytes\n if n == 1:\n if args.nolist is False:\n if args.format == 4:\n line += \"%03o \" % op\n else:\n line += \"%02X \" % op\n elif n == 2:\n try: # Possible to get exception here if EOF reached.\n op1 = ord(f.read(1))\n except TypeError:\n op1 = 0 # Fake it to recover from EOF\n if args.nolist is False:\n if args.format == 4:\n line += \"%03o %03o \" % (op, op1)\n else:\n line += \"%02X %02X \" % (op, op1)\n elif n == 3:\n try: # Possible to get exception here if EOF reached.\n op1 = ord(f.read(1))\n op2 = ord(f.read(1))\n except TypeError:\n op1 = 0 # Fake it to recover from EOF\n op2 = 0\n if args.nolist is False:\n line += \"%s %s %s \" % (formatByte(op), formatByte(op1), formatByte(op2))\n if args.nolist is True:\n line += \" \"\n\n # Special check for invalid op code.\n if mnem == \"???\" and not args.invalid:\n if isprint(chr(op)):\n line += \"%s '%c'\" % (case(\".byte\"), op)\n else:\n if args.format == 1:\n line += \"%s $%s\" % (case(\".byte\"), formatByte(op))\n elif args.format == 2:\n line += \"%s %s%s\" % (case(\".byte\"), formatByte(op), case(\"h\"))\n else:\n line += \"%s %s\" % (case(\".byte\"), formatByte(op))\n else:\n line += mnem\n if len(mnem) == 3:\n line += \" \"\n\n if mode == implied:\n pass\n\n elif mode == immediate:\n if (n == 2):\n if isprint(chr(op1)):\n line += \" #'%c'\" % op1\n else:\n if args.format == 1:\n line += \" #$%s\" % formatByte(op1)\n elif args.format == 2:\n line += \" #%s%s\" % (formatByte(op1), case(\"h\"))\n else:\n line += \" #%s\" % formatByte(op1)\n elif (n == 3):\n if args.format == 1:\n line += \" #$%s%s\" % (formatByte(op1), formatByte(op2))\n elif args.format == 2:\n line += \" #%s%s%s\" % (formatByte(op1), formatByte(op2), case(\"h\"))\n else:\n line += \" #%s%s\" % (formatByte(op1), formatByte(op2))\n\n elif mode == direct:\n if args.format == 1:\n line += \" $%s\" % formatByte(op1)\n elif args.format == 2:\n line += \" %s%s\" % (formatByte(op1), case(\"h\"))\n else:\n line += \" %s\" % formatByte(op1)\n\n elif mode == indexed:\n if args.format == 1:\n line += \" $%s,%s\" % (formatByte(op1), case(\"x\"))\n elif args.format == 2:\n line += \" %s%s,%s\" % (formatByte(op1), case(\"h\"), case(\"x\"))\n else:\n line += \" %s,%s\" % (formatByte(op1), case(\"x\"))\n\n elif mode == extended:\n if args.format == 1:\n line += \" $%s%s\" % (formatByte(op1), formatByte(op2))\n elif args.format == 2:\n line += \" %s%s%s\" % (formatByte(op1), formatByte(op2), case(\"h\"))\n else:\n line += \" %s%s\" % (formatByte(op1), formatByte(op2))\n\n elif mode == relative:\n if op1 < 128:\n dest = address + op1 + 2\n else:\n dest = address - (256 - op1) + 2\n if dest < 0:\n dest = 65536 + dest\n if args.format == 1:\n line += \" $%s\" % formatAddress(dest)\n elif args.format == 2:\n line += \" %s%s\" % (formatAddress(dest), case(\"h\"))\n else:\n line += \" %s%s\" % (formatAddress(dest), formatByte(op1))\n\n else:\n print(\"Internal error: unknown addressing mode:\", mode, file=sys.stderr)\n sys.exit(1)\n\n # Update address\n address += n\n\n # Check for address exceeding 0xFFFF, if so wrap around.\n if address > 0xffff:\n address = address & 0xffff\n\n # Finished a line of disassembly\n print(line)\n line = \"\"\n\n except KeyboardInterrupt:\n print(\"Interrupted by Control-C\", file=sys.stderr)\n if args.format == 4:\n print(\"%s %s\" % (formatAddress(address), case(\"end\"))) # Exit if end of file reached.\n else:\n print(\"%s %s\" % (formatAddress(address), case(\"end\"))) # Exit if end of file reached.\n break\n","sub_path":"disasm/disasm6800.py","file_name":"disasm6800.py","file_ext":"py","file_size_in_byte":18433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"464412899","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.5 (3350)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/chisubmit/backend/api/migrations/0008_python3+django2_upgrade.py\n# Compiled at: 2018-10-02 19:35:34\n# Size of source mod 2**32: 1824 bytes\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\nclass Migration(migrations.Migration):\n dependencies = [\n ('api', '0007_registration_grading_started')]\n operations = [\n migrations.AlterField(model_name='course', name='extension_policy', field=models.CharField(choices=[('per-team', 'Extensions per team'), ('per-student', 'Extensions per student')], default='per-student', max_length=16)),\n migrations.AlterField(model_name='course', name='git_staging_usernames', field=models.CharField(choices=[('user-id', 'Same as user id'), ('custom', 'Custom git username')], default='user-id', max_length=16)),\n migrations.AlterField(model_name='course', name='git_usernames', field=models.CharField(choices=[('user-id', 'Same as user id'), ('custom', 'Custom git username')], default='user-id', max_length=16)),\n migrations.AlterField(model_name='registration', name='final_submission', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='final_submission_of', to='api.Submission')),\n migrations.AlterField(model_name='registration', name='grader', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='api.Grader')),\n migrations.AlterField(model_name='submission', name='submitted_by', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL))]","sub_path":"pycfiles/chisubmit-2.1.0-py3.5/0008_python3+django2_upgrade.cpython-35.py","file_name":"0008_python3+django2_upgrade.cpython-35.py","file_ext":"py","file_size_in_byte":1782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"619422734","text":"from flask import Flask, jsonify, send_from_directory, request, Blueprint\nimport datetime\nimport stormberry.util\nfrom stormberry.util import weather_list_to_dict_list\nfrom stormberry.server.util import get_repository\nimport json\n\nweather_blueprint = Blueprint('weather_blueprint', __name__)\n\n@weather_blueprint.route('/latest-reading')\ndef latest_reading():\n repo = get_repository()\n latest = repo.get_latest()\n return jsonify(latest.dict)\n\n@weather_blueprint.route('/since/')\ndef weather_since(start_date):\n repo = get_repository()\n\n readings = repo.get_between(start_date)\n return jsonify(weather_list_to_dict_list(readings))\n\n@weather_blueprint.route('/since//until/')\ndef weather_between(start_date, end_date):\n repo = get_repository()\n\n readings = repo.get_between(start_date, end_date)\n return jsonify(weather_list_to_dict_list(readings))\n\n@weather_blueprint.route('/past-hour')\ndef weather_past_hour():\n now = datetime.datetime.now()\n ago = now - datetime.timedelta(hours=1)\n\n repo = get_repository()\n datestr = ago.strftime(\"%Y-%m-%d %H:%M:%S\")\n readings = repo.get_between(datestr)\n return jsonify(weather_list_to_dict_list(readings))\n\n@weather_blueprint.route('/past-day')\ndef weather_past_day():\n now = datetime.datetime.now()\n ago = now - datetime.timedelta(days=1)\n\n repo = get_repository()\n datestr = ago.strftime(\"%Y-%m-%d %H:%M:%S\")\n readings = repo.get_between(datestr)\n return jsonify(weather_list_to_dict_list(readings))\n\n@weather_blueprint.route('/past-week')\ndef weather_past_week():\n now = datetime.datetime.now()\n ago = now - datetime.timedelta(days=7)\n repo = get_repository()\n datestr = ago.strftime(\"%Y-%m-%d %H:%M:%S\")\n\n readings = repo.get_between(datestr)\n return jsonify(weather_list_to_dict_list(readings))\n\n","sub_path":"src/stormberry/server/api/weather/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"482504594","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport logging\nimport threading\nfrom pymidi import server as pymidi_server\n\n# Maps pymidi note identifiers to their more conventional names.\nMIDI_NOTE_NAMES = {\n 'Cn1': 'C-1',\n 'Csn1': 'C#-1',\n 'Dn1': 'D-1',\n 'Dsn1': 'D#-1',\n 'En1': 'E-1',\n 'Fn1': 'F-1',\n 'Fsn1': 'F#-1',\n 'Gn1': 'G-1',\n 'Gsn1': 'G#-1',\n 'An1': 'A-1',\n 'Asn1': 'A#-1',\n 'Bn1': 'B-1',\n 'C0': 'C0',\n 'Cs0': 'C#0',\n 'D0': 'D0',\n 'Ds0': 'D#0',\n 'E0': 'E0',\n 'F0': 'F0',\n 'Fs0': 'F#0',\n 'G0': 'G0',\n 'Gs0': 'G#0',\n 'A0': 'A0',\n 'As0': 'A#0',\n 'B0': 'B0',\n 'C1': 'C1',\n 'Cs1': 'C#1',\n 'D1': 'D1',\n 'Ds1': 'D#1',\n 'E1': 'E1',\n 'F1': 'F1',\n 'Fs1': 'F#1',\n 'G1': 'G1',\n 'Gs1': 'G#1',\n 'A1': 'A1',\n 'As1': 'A#1',\n 'B1': 'B1',\n 'C2': 'C2',\n 'Cs2': 'C#2',\n 'D2': 'D2',\n 'Ds2': 'D#2',\n 'E2': 'E2',\n 'F2': 'F2',\n 'Fs2': 'F#2',\n 'G2': 'G2',\n 'Gs2': 'G#2',\n 'A2': 'A2',\n 'As2': 'A#2',\n 'B2': 'B2',\n 'C3': 'C3',\n 'Cs3': 'C#3',\n 'D3': 'D3',\n 'Ds3': 'D#3',\n 'E3': 'E3',\n 'F3': 'F3',\n 'Fs3': 'F#3',\n 'G3': 'G3',\n 'Gs3': 'G#3',\n 'A3': 'A3',\n 'As3': 'A#3',\n 'B3': 'B3',\n 'C4': 'C4',\n 'Cs4': 'C#4',\n 'D4': 'D4',\n 'Ds4': 'D#4',\n 'E4': 'E4',\n 'F4': 'F4',\n 'Fs4': 'F#4',\n 'G4': 'G4',\n 'Gs4': 'G#4',\n 'A4': 'A4',\n 'As4': 'A#4',\n 'B4': 'B4',\n 'C5': 'C5',\n 'Cs5': 'C#5',\n 'D5': 'D5',\n 'Ds5': 'D#5',\n 'E5': 'E5',\n 'F5': 'F5',\n 'Fs5': 'F#5',\n 'G5': 'G5',\n 'Gs5': 'G#5',\n 'A5': 'A5',\n 'As5': 'A#5',\n 'B5': 'B5',\n 'C6': 'C6',\n 'Cs6': 'C#6',\n 'D6': 'D6',\n 'Ds6': 'D#6',\n 'E6': 'E6',\n 'F6': 'F6',\n 'Fs6': 'F#6',\n 'G6': 'G6',\n 'Gs6': 'G#6',\n 'A6': 'A6',\n 'As6': 'A#6',\n 'B6': 'B6',\n 'C7': 'C7',\n 'Cs7': 'C#7',\n 'D7': 'D7',\n 'Ds7': 'D#7',\n 'E7': 'E7',\n 'F7': 'F7',\n 'Fs7': 'F#7',\n 'G7': 'G7',\n 'Gs7': 'G#7',\n 'A7': 'A7',\n 'As7': 'A#7',\n 'B7': 'B7',\n 'C8': 'C8',\n 'Cs8': 'C#8',\n 'D8': 'D8',\n 'Ds8': 'D#8',\n 'E8': 'E8',\n 'F8': 'F8',\n 'Fs8': 'F#8',\n 'G8': 'G8',\n 'Gs8': 'G#8',\n 'A8': 'A8',\n 'As8': 'A#8',\n 'B8': 'B8',\n 'C9': 'C9',\n 'Cs9': 'C#9',\n 'D9': 'D9',\n 'Ds9': 'D#9',\n 'E9': 'E9',\n 'F9': 'F9',\n 'Fs9': 'F#9',\n 'G9': 'G9',\n}\n\n# Convenience aliases for pymidi commands\nCOMMAND_NOTE_ON = 'note_on'\nCOMMAND_NOTE_OFF = 'note_off'\nCOMMAND_CONTROL_MODE_CHANGE = 'control_mode_change'\nSUPPORTED_COMMANDS = (COMMAND_NOTE_ON, COMMAND_NOTE_OFF, COMMAND_CONTROL_MODE_CHANGE)\n\n\nclass MidiFunctions(object):\n \"\"\"Defines things that can be controlled over midi.\n\n Instances of this class are simple containers which contain the\n constant `.name` value. The name of a MidiFunction is stable value\n that may be used in a MidiMapping (see later).\n\n The `ALL_FUNCTIONS` global contains all registered/available functions\n in the system. You can think of it like an enum.\n \"\"\"\n ALL_FUNCTIONS = {}\n\n def __init__(self, name, help_text=''):\n self.name = name\n self.help_text = help_text\n\n def __str__(self):\n return self.name\n\n @classmethod\n def add(cls, name, **kwargs):\n assert name not in cls.ALL_FUNCTIONS\n obj = cls(name, **kwargs)\n cls.ALL_FUNCTIONS[name] = obj\n setattr(cls, name, obj)\n\n\nMidiFunctions.add('playlist_next',\n help_text='Advance to the next item in the current playlist.')\nMidiFunctions.add('playlist_previous',\n help_text='Go to previous item in the current playlist.')\nMidiFunctions.add('playlist_pause',\n help_text='Pause the current playlist.')\nMidiFunctions.add('playlist_play',\n help_text='Pause the current playlist.')\nMidiFunctions.add('playlist_stay',\n help_text='Loop/repeat the current item in the playlist.')\nMidiFunctions.add('playlist_stop',\n help_text='Stop playback of the current playlist.')\nMidiFunctions.add('playlist_goto_1',\n help_text='Go to playlist position 1.')\nMidiFunctions.add('playlist_goto_2',\n help_text='Go to playlist position 2.')\nMidiFunctions.add('playlist_goto_3',\n help_text='Go to playlist position 3.')\nMidiFunctions.add('playlist_goto_4',\n help_text='Go to playlist position 4.')\nMidiFunctions.add('playlist_goto_5',\n help_text='Go to playlist position 5.')\nMidiFunctions.add('playlist_goto_6',\n help_text='Go to playlist position 6.')\nMidiFunctions.add('playlist_goto_7',\n help_text='Go to playlist position 7.')\nMidiFunctions.add('playlist_goto_8',\n help_text='Go to playlist position 8.')\nMidiFunctions.add('playlist_goto_9',\n help_text='Go to playlist position 9.')\nMidiFunctions.add('playlist_goto_10',\n help_text='Go to playlist position 10.')\nMidiFunctions.add('playlist_goto_11',\n help_text='Go to playlist position 11.')\nMidiFunctions.add('playlist_goto_12',\n help_text='Go to playlist position 12.')\nMidiFunctions.add('playlist_goto_13',\n help_text='Go to playlist position 13.')\nMidiFunctions.add('playlist_goto_14',\n help_text='Go to playlist position 14.')\nMidiFunctions.add('playlist_goto_15',\n help_text='Go to playlist position 15.')\nMidiFunctions.add('playlist_goto_16',\n help_text='Go to playlist position 16.')\nMidiFunctions.add('set_bpm',\n help_text='Set the global bpm based on note velocity or controller value.')\n\n\nclass MidiMapping(object):\n \"\"\"Maps MIDI commands to a special functions.\n\n Mappings will typically be one-to-one with MIDI devices, because the layout\n and configuration of physical keys and control surfaces varies widely.\n\n The internal representation is a map, from 2- or 3-tuple command, to desired\n MidiFunction instance. 2-tuple commands will match any velocity or value;\n 3-tuple commands only match the specified velocity or value.\n\n Example internal representation:\n {\n ('note_on', 'C3'): MidiFunctions('playlist_next'),\n ('note_on', 'C4'): MidiFunctions('playlist_previous'),\n ('control_mode_change', 22, 127): MidiFunctions('set_bpm'),\n }\n\n Equivalent JSON representation:\n {\n \"name\": \"KontrolPad\",\n \"mappings\": [\n {\n \"command\": [\"note_on\", \"C3\"],\n \"function\": \"playlist_next\"\n },\n {\n \"command\": [\"note_on\", \"C4\"],\n \"function\": \"playlist_previous\"\n },\n {\n \"command\": [\"control_mode_change\", 22, 127],\n \"function\": \"set_bpm\"\n }\n ]\n }\n \"\"\"\n def __init__(self, name, mappings=None):\n self.name = name\n self.mappings = mappings or {}\n\n def __eq__(self, other):\n if not isinstance(other, MidiMapping):\n return False\n return (self.name, self.mappings) == (other.name, other.mappings)\n\n def get_function(self, command):\n # Try an exact match (with velocity/value) first.\n exact_match = self.mappings.get(command)\n if exact_match or len(command) < 3:\n return exact_match\n\n # Try a partial match (ignore velocity/value).\n match = self.mappings.get(command[:2])\n return match\n\n def to_json(self):\n mappings_list = []\n for command, function in self.mappings.iteritems():\n mappings_list.append({\n 'command': command,\n 'function': function.name,\n })\n return {\n 'name': self.name,\n 'mappings': mappings_list,\n }\n\n @classmethod\n def from_json(cls, obj):\n \"\"\"Creates an instance from a parsed JSON object.\n\n Entries for unknown commands or unknown functions will be ignored.\n Structural errors will throw a KeyError.\n \"\"\"\n name = obj['name']\n mapping_list = obj['mappings']\n mapping_dict = {}\n for item in mapping_list:\n command = item['command']\n if command[0] not in SUPPORTED_COMMANDS:\n continue\n function = MidiFunctions.ALL_FUNCTIONS.get(item['function'])\n if not function:\n continue\n mapping_dict[tuple(command)] = function\n return cls(name, mapping_dict)\n\n\nclass MidiHandler(pymidi_server.Handler):\n def __init__(self, manager):\n self.manager = manager\n\n def on_peer_connected(self, peer):\n self.manager.on_midi_peer_connected(peer)\n\n def on_peer_disconnected(self, peer):\n self.manager.on_midi_peer_disconnected(peer)\n\n def on_midi_commands(self, peer, commands):\n self.manager.on_midi_commands(peer, commands)\n\n\nclass MidiManager(object):\n \"\"\"Binds a pymidi server to the dance floor controller.\"\"\"\n def __init__(self, port, controller, default_midi_mapping=None):\n self.controller = controller\n self.midi_server = pymidi_server.Server(port=port)\n self.midi_handler = MidiHandler(self)\n self.midi_server.add_handler(self.midi_handler)\n self.logger = logging.getLogger(self.__class__.__name__)\n self.midi_peers_to_mappings = {}\n self.logger.info('Midi enabled, port={}'.format(port))\n self.default_midi_mapping = default_midi_mapping or MidiMapping(name='default')\n\n def get_midi_mapping(self, peer):\n \"\"\"Returns the midi mapping for this peer.\"\"\"\n return self.midi_peers_to_mappings.get(peer.ssrc, self.default_midi_mapping)\n\n def command_to_tuple(self, cmd):\n \"\"\"Canonicalizes a pymidi command to its internal representation.\"\"\"\n if cmd.command in (COMMAND_NOTE_ON, COMMAND_NOTE_OFF):\n command = cmd.command\n note_name = MIDI_NOTE_NAMES.get(cmd.params.key, cmd.params.key)\n value = cmd.params.velocity\n if command == COMMAND_NOTE_ON and value == 0:\n # MIDI protocol specifies note on with velocity zero as a logical\n # note off; make the translation here.\n command = COMMAND_NOTE_OFF\n return (command, note_name, value)\n elif cmd.command == COMMAND_CONTROL_MODE_CHANGE:\n return (cmd.command, cmd.params.controller, cmd.params.value)\n return None\n\n def on_midi_peer_connected(self, peer):\n self.logger.info('Peer connected: {}'.format(peer))\n self.midi_peers_to_mappings[peer.ssrc] = self.default_midi_mapping\n\n def on_midi_peer_disconnected(self, peer):\n self.logger.info('Peer disconnected: {}'.format(peer))\n del self.midi_peers_to_mappings[peer.ssrc]\n\n def on_midi_commands(self, peer, commands):\n commands = map(self.command_to_tuple, commands)\n\n # Pass all midi messages through to the current processor.\n processor = self.controller.processor\n if processor and hasattr(processor, 'handle_midi_command'):\n for command in commands:\n processor.handle_midi_command(command)\n\n # Handle any special command bindings.\n mapping = self.get_midi_mapping(peer)\n for command in commands:\n function = mapping.get_function(command)\n if function:\n self.execute_midi_function(function, command)\n\n def execute_midi_function(self, midi_function, command):\n self.logger.info('MIDI function: {}'.format(midi_function))\n playlist = self.controller.playlist\n\n if midi_function == MidiFunctions.playlist_next:\n playlist.advance()\n elif midi_function == MidiFunctions.playlist_previous:\n playlist.previous()\n elif midi_function == MidiFunctions.playlist_stop:\n playlist.stop_playlist()\n elif midi_function == MidiFunctions.playlist_play:\n playlist.start_playlist()\n elif midi_function == MidiFunctions.playlist_stay:\n playlist.stay()\n elif midi_function == MidiFunctions.playlist_goto_1:\n playlist.go_to(1)\n elif midi_function == MidiFunctions.playlist_goto_2:\n playlist.go_to(2)\n elif midi_function == MidiFunctions.playlist_goto_3:\n playlist.go_to(3)\n elif midi_function == MidiFunctions.playlist_goto_4:\n playlist.go_to(4)\n elif midi_function == MidiFunctions.playlist_goto_5:\n playlist.go_to(5)\n elif midi_function == MidiFunctions.playlist_goto_6:\n playlist.go_to(6)\n elif midi_function == MidiFunctions.playlist_goto_7:\n playlist.go_to(7)\n elif midi_function == MidiFunctions.playlist_goto_8:\n playlist.go_to(8)\n elif midi_function == MidiFunctions.playlist_goto_9:\n playlist.go_to(9)\n elif midi_function == MidiFunctions.playlist_goto_10:\n playlist.go_to(10)\n elif midi_function == MidiFunctions.playlist_goto_11:\n playlist.go_to(11)\n elif midi_function == MidiFunctions.playlist_goto_12:\n playlist.go_to(12)\n elif midi_function == MidiFunctions.playlist_goto_13:\n playlist.go_to(13)\n elif midi_function == MidiFunctions.playlist_goto_14:\n playlist.go_to(14)\n elif midi_function == MidiFunctions.playlist_goto_15:\n playlist.go_to(15)\n elif midi_function == MidiFunctions.playlist_goto_16:\n playlist.go_to(16)\n elif midi_function == MidiFunctions.set_bpm:\n value = command.params.value\n bpm = 90\n bpm += float(value) / 127.0 * 80\n self.controller.set_bpm(bpm)\n\n def run_server(self):\n thr = threading.Thread(target=self.midi_server.serve_forever)\n thr.daemon = True\n self.logger.info('Starting midi server thread')\n thr.start()\n","sub_path":"floor/controller/midi.py","file_name":"midi.py","file_ext":"py","file_size_in_byte":13892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"442699013","text":"import argparse\nimport json\nimport requests\nfrom multiprocessing import Pool\n\nfrom flask import Flask, request, jsonify\nfrom flask_cors import CORS\nimport numpy as np\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--use_thin_client', type=int)\n parser.add_argument('--web_app_port', default='9210')\n parser.add_argument('--serving_uri', required=True)\n parser.add_argument('--model_name', required=True, nargs='+')\n args = parser.parse_args()\n\nstatic_folder = 'thin_static' if args.use_thin_client else 'rich_static'\nprint(static_folder)\napp = Flask(__name__, static_url_path='/static/', static_folder=static_folder)\nCORS(app)\n\n\ndef build_body(b64_img):\n return {\n 'instances': [\n {'image_bytes': {'b64': b64_img}}\n ]\n }\n\n\ndef decode_response(response, encoding_dict):\n prediction = json.loads(response.text)['predictions'][0]\n cls_idx = np.argmax(prediction)\n return encoding_dict[cls_idx]\n\n\ndef call_serving(args):\n b64_img, uri, encoding_dict = args\n body = build_body(b64_img)\n response = requests.post(uri, json=body)\n return decode_response(response, encoding_dict)\n\n\n@app.route('/init-client', methods=['GET'])\ndef init_client():\n global serving_uris, encoding_dicts\n return jsonify({'servingUris': serving_uris, 'encodingDicts': encoding_dicts})\n\n\n@app.route('/predict', methods=['POST'])\ndef get_prediction():\n global serving_uris, encoding_dicts\n b64_img = request.get_json()\n predictions = Pool(2).imap(call_serving, zip([b64_img] * len(serving_uris), serving_uris, encoding_dicts))\n return jsonify(' '.join(predictions))\n\n\n\n@app.route('/')\ndef main_page():\n return app.send_static_file('index.html')\n\n\nif __name__ == '__main__':\n serving_uris = []\n encoding_dicts = []\n\n for model_name in args.model_name:\n serving_uri = args.serving_uri.format(model_name=model_name)\n serving_uris.append(serving_uri)\n\n with open(f'/tmp/{model_name}.json', 'r') as f:\n encoding_dicts.append(json.load(f))\n\n args = parser.parse_args()\n app.run(host='0.0.0.0', port=args.web_app_port)\n","sub_path":"visual_attribution/web_app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"367410182","text":"#\n# Copyright (c) 2016 Juniper Networks, Inc. All rights reserved.\n#\n\nimport os\nfrom subprocess import Popen, PIPE\nimport psutil\n\nfrom sandesh.nodeinfo.cpuinfo.ttypes import SysMemInfo, SysCpuInfo, CpuLoadAvg\n\n\ndef _run_cmd(cmd):\n proc = Popen(cmd, shell=True, stdout=PIPE, close_fds=True)\n return int(proc.communicate()[0])\n\n\nclass LinuxSysMemCpuUsageData(object):\n def __init__(self, last_cpu, last_time):\n self.last_cpu = last_cpu\n self.last_time = last_time\n\n def get_num_socket(self):\n return _run_cmd('lscpu | grep \"Socket(s):\" '\n '| awk \\'{print $2}\\'')\n\n def get_num_cpu(self):\n return _run_cmd('lscpu | grep \"^CPU(s):\" '\n '| awk \\'{print $2}\\'')\n\n def get_num_core_per_socket(self):\n return _run_cmd('lscpu | grep \"Core(s) per socket:\" '\n '| awk \\'{print $4}\\'')\n\n def get_num_thread_per_core(self):\n return _run_cmd('lscpu | grep \"Thread(s) per core:\" '\n '| awk \\'{print $4}\\'')\n\n def get_sys_mem_info(self, node_type):\n virtmem_info = psutil.virtual_memory()\n sys_mem_info = SysMemInfo()\n sys_mem_info.total = virtmem_info.total / 1024\n sys_mem_info.used = virtmem_info.used / 1024\n sys_mem_info.free = virtmem_info.free / 1024\n sys_mem_info.buffers = virtmem_info.buffers / 1024\n sys_mem_info.cached = virtmem_info.cached / 1024\n sys_mem_info.node_type = node_type\n return sys_mem_info\n\n def get_sys_cpu_info(self, node_type):\n cpu_load_avg = self._get_sys_cpu_load_avg()\n sys_cpu_info = SysCpuInfo()\n sys_cpu_info.one_min_avg = cpu_load_avg.one_min_avg\n sys_cpu_info.five_min_avg = cpu_load_avg.five_min_avg\n sys_cpu_info.fifteen_min_avg = cpu_load_avg.fifteen_min_avg\n sys_cpu_info.cpu_share = self._get_sys_cpu_share()\n sys_cpu_info.node_type = node_type\n return sys_cpu_info\n\n def _get_sys_cpu_load_avg(self):\n load_avg = os.getloadavg()\n cpu_load_avg = CpuLoadAvg()\n cpu_load_avg.one_min_avg = load_avg[0]\n cpu_load_avg.five_min_avg = load_avg[1]\n cpu_load_avg.fifteen_min_avg = load_avg[2]\n return cpu_load_avg\n\n def _get_sys_cpu_share(self):\n last_cpu = self.last_cpu\n last_time = self.last_time\n\n current_cpu = psutil.cpu_times()\n current_time = 0.00\n for i in range(0, len(current_cpu) - 1):\n current_time += current_cpu[i]\n\n # tracking system/user time only\n interval_time = 0\n if last_cpu and (last_time != 0):\n sys_time = current_cpu.system - last_cpu.system\n usr_time = current_cpu.user - last_cpu.user\n interval_time = current_time - last_time\n\n self.last_cpu = current_cpu\n self.last_time = current_time\n\n if interval_time == 0:\n return 0\n\n sys_percent = 100 * sys_time / interval_time\n usr_percent = 100 * usr_time / interval_time\n cpu_share = round((sys_percent + usr_percent) / self.get_num_cpu(), 2)\n return cpu_share\n","sub_path":"src/nodemgr/common/linux_sys_mem_cpu.py","file_name":"linux_sys_mem_cpu.py","file_ext":"py","file_size_in_byte":3137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"612710184","text":"class Settings:\n \"\"\"\n Class to define game's settings\n \"\"\"\n\n def __init__(self):\n \"\"\"We initialize the game with some settings\"\"\"\n # Screen settings\n self.screen_width = 800\n self.screen_height = 600\n self.bg_color = (0,0,255)\n # Bar settings\n self.bar_width = 150\n self.bar_speed = 8\n # Ball settings\n self.ball_pos_x = int(self.screen_width/2)\n self.ball_pos_y = int(self.screen_height/2)\n self.ball_start_angle = 5 # between 1 and 88\n self.ball_end_angle = 175 # between 92 and 179\n self.ball_speed = 2\n self.ball_extra_move = 1\n self.ball_radius = 15\n self.ball_color = (255,255,255)\n self.ball_left = 3\n # TimeBar settings\n self.timebar_width = 150\n self.timebar_hight = 20\n self.timebar_color = (255, 255, 255)\n # Game factors\n self.session_duration = 30\n self.difficulty_factor = 1.2\n\n def initialize_settings(self):\n \"\"\"Initialize game difficulty parameters.\"\"\"\n self.ball_radius = 15\n self.bar_width = 150\n\n def increase_game_difficulty(self):\n \"\"\"Increase game difficulty.\"\"\"\n self.ball_radius /= self.difficulty_factor\n self.bar_width /= self.difficulty_factor","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"111504086","text":"def unique(spotted,plain):\n s = set(spotted)\n p = set(plain)\n \n if (s&p):\n return False\n return True\n#read in\nfin = open ('cownomics.in', 'r')\nfout = open ('cownomics.out', 'w')\nN,M = map(int, fin.readline().split())\nspotted,plain = [],[]\n\nfor i in range(N):\n spotted.append(fin.readline().strip())\nfor i in range(N):\n plain.append(fin.readline().strip())\n\ncount = 0\nhelp1,help2 = [],[]\nfor i in range(M):\n for j in spotted:\n help1.append(j[i])\n for j in plain:\n help2.append(j[i])\n \n if unique(help1,help2):\n count += 1 \n \n help1,help2 = [],[]\n\nprint(count)\nfout.write (str(count) + '\\n')\nfout.close()","sub_path":"src/bronze/cownomics.py","file_name":"cownomics.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"631513992","text":"t = int(input())\nfor _ in range(t):\n l = []\n s = input()\n for i in s:\n if len(l) > 0 and i == l[0]:\n l.pop(0)\n else:\n l.insert(0,i)\n l.reverse()\n if len(l) != 0:\n print(\"\".join(l))\n else:\n print(\"KHALI\")\n","sub_path":"Data Structures/Stacks/I hate Even Subarrays.py","file_name":"I hate Even Subarrays.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"409709433","text":"# Create your views here.\r\nfrom .Neural import *\r\nfrom .Robot import Track\r\nfrom .Robot import Truck\r\nfrom .Robot import Manipulator\r\nfrom api.models import Status\r\nfrom rest_framework.views import APIView\r\nfrom rest_framework.response import Response\r\n\r\n\r\n\r\nclass Robot(APIView):\r\n a = ''\r\n\r\n\r\n def get(self, request):\r\n # main loop\r\n while True:\r\n status = str(Status.objects.all()).split()[2][0]\r\n success, img = cap.read()\r\n\r\n blob = cv2.dnn.blobFromImage(img,1/255,(whT,whT),[0,0,0],1,crop=False) # ? to blob conv\r\n net.setInput(blob)\r\n\r\n layerNames = net.getLayerNames()\r\n outputNames = [layerNames[i[0]-1] for i in net.getUnconnectedOutLayers()]\r\n\r\n outputs = net.forward(outputNames)\r\n Neural.findObjects(outputs, img) # Используем нейронку\r\n if not Manipulator.busy: # Если манипулятор\r\n # свободен\r\n Track.findBottle(Neural.n_ame) # Ищем бутылку\r\n if Track.bottlefound and Truck.IsTurnedToTheTarget() and Neural.BottleRange > 35: # Если бутыла\r\n # найдена, тележка направлена на нёё и расстояние между тележкой и обьектом >35 см\r\n Truck.Move(Neural.BottleRange) # Двигаемся к обьекту\r\n if Neural.n_ame == 'BOTTLE' and Neural.BottleRange < 35: # Если расстояние\r\n # меньше 35 см, берем предмет\r\n Manipulator.Lock()\r\n Manipulator.busy = True\r\n if Manipulator.busy: # Если манипулятор занят\r\n Track.findHuman(Neural.n_ame) # Поиск человека\r\n if Manipulator.busy and Track.humanfound and Truck.IsTurnedToTheTarget():\r\n Truck.Move(Neural.HumanRange)\r\n if Neural.n_ame == 'PERSON' and Neural.BottleRange < 35 and Wannamore.dontwant:\r\n Manipulator.Unlock()\r\n Manipulator.busy = False\r\n while True:\r\n print('Робот доставил обьект. Хотите продолжить? (yes или no)')\r\n a = input('Введите ответ: ')\r\n if a == 'yes' or a == 'YES' or a == 'Yes' or a == 'y' or a == 'Y':\r\n status = '1'\r\n Wannamore.dontwant = False\r\n break\r\n elif a == 'no' or a == 'NO' or a == 'No' or a == 'n':\r\n status = '0'\r\n break\r\n else:\r\n print('Некорректный ввод')\r\n #print(str(Status.objects.all()).split()[2][0])\r\n if status == '0':\r\n break\r\n cv2.imshow('Image', img)\r\n if cv2.waitKey(25) & 0xFF == ord('q'):\r\n break\r\n return Response({\"good\"})","sub_path":"robot/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"577743484","text":"matr = [\n\n' Однажды в сffg f тудёнуюю зимнюю ', \n' пору ага. медленно Я иdd dd Aaaз лесу',\n' вышелada da . Был сильный нехороший и противный холодный',\n' мороз. медленно Г1-1+2ляжувв поddd ме 4+45654+4-5+55 дленно f22+3-4+3-4fg fggается fuf fff медленно в',\n' гору. Лошадка медленно в езуапапр 3+2+10ща fg я несущ ая много плохого хворосту ',\n' воз. И шевствую важн fg о, в спокойствии ',\n' чинном. мед2+2-1ленно fg Лошадк 6+4-6-5 у ве зета вф под уздцы мужичок'\n\n ]\nlen_max = 0\n\nfor i in matr:\n print(i)\nprint()\n\n'''# Выравнивание по левому краю.\nfor i in matr:\n u = len(i)\n j = 0\n k, k1 = 0, 0\n while i[j] == ' ':\n j += 1\n k1 += 1\n while i[u - 1] == ' ':\n k += 1\n u -= 1\n i = i[k1:len(i) - k]\n print(i)\n if len(i) > len_max:\n len_max = len(i)\n ' '.join(i.split())\nprint()\n\n# Выравнивание по правому краю.\nfor i in matr:\n u = len(i)\n j = 0\n k, k1 = 0, 0\n while i[j] == ' ':\n j += 1\n k1 += 1\n while i[u - 1] == ' ':\n k += 1\n u -= 1\n i = i[k1:len(i) - k]\n i = ' '*(len_max-len(i)) + i\n print(i)\nprint()\n\n# Выравнивание по ширине\nfor i in matr:\n count = 0\n k2 = 0\n u = len(i)\n j = 0\n k, k1 = 0, 0\n while i[j] == ' ':\n j += 1\n k1 += 1\n while i[u - 1] == ' ':\n k += 1\n u -= 1\n i = i[k1:len(i) - k]\n i = ' '.join(i.split())\n ln = len(i)\n ln_del = len_max - ln\n A = i.split()\n A2 = i.split()\n for y in i:\n if y == ' ':\n count += 1\n if ln_del == 0:\n print(i)\n elif (ln_del)//(count) == 0:\n ff = 0\n llenn = len(A)\n for tt in range(llenn-(ln_del+1)):\n A.pop()\n ff += 1\n i = ' '.join(A) + ' ' + ' '.join(A2[len(A2)-ff:])\n print(i)\n elif (ln_del)%(count)!= 0:\n zam = ' '*((ln_del)//(count)+1)\n i = zam.join(i.split())\n fm = 0\n A3 = i.split()\n A4 = i.split()\n llenn2 = len(A3)\n for tm in range(llenn2 - ((ln_del)%(count)+1)):\n A3.pop()\n fm += 1\n msm = ' '*((ln_del)//(count)+1)\n rdd = ' '*(((ln_del)//(count))+2)\n i = rdd.join(A3) + zam + zam.join(A4[len(A4)-fm:])\n print(i)\n else:\n mk = ' '*((ln_del)//(count)+1)\n i = mk.join(i.split())\n print(i)\nprint()'''\n\n'''# Замена слова. \nwordforreplace = 'медленно'\nnewword = 'хуй'\nword = \"\"\nfor item in range(len(matr)):\n wholeitem = \"\"\n for letter in matr[item]:\n if letter.isalpha():\n word += letter\n else:\n if word == wordforreplace:\n word = newword\n wholeitem += word + ' '\n word = \" \"\n else:\n wholeitem += word + ' '\n word = \"\"\n word= \"\"\n matr[item] = wholeitem\nprint()\nfor i in matr:\n print(i)\nprint()'''\n\n'''# Удаление слова. \nwordfordel = 'хуй'\nword = \"\"\nfor item in range(len(matr)):\n wholeitem = \"\"\n for letter in matr[item]:\n if letter.isalpha():\n word += letter\n else:\n if word == wordfordel:\n word = ''\n wholeitem += word + ' '\n word = \" \"\n else:\n wholeitem += word + ' '\n word = \"\"\n word= \"\"\n matr[item] = wholeitem\nprint()\nfor i in matr:\n print(i)\nprint()'''\n\n# Вычисление выражения строках.\nOld = []\nNew = []\nfor item in range(len(matr)):\n coin = []\n summ = None\n copp = \"\"\n buf = \"\"\n i = 1\n for letter in range(len(matr[item])):\n mar = matr[item]\n if mar[letter].isdigit() and not mar[letter-1].isdigit() and not mar[letter-1] == '+' and not mar[letter-1] == '-':\n buf += mar[letter]\n copp += mar[letter]\n while mar[letter+i].isdigit():\n buf += mar[letter+i]\n copp += mar[letter+i]\n i += 1\n else:\n while mar[letter+i] == \"-\" or mar[letter+i] == \"+\":\n \n while mar[letter+i] == \"+\":\n buf += ' '\n copp += '+'\n i += 1\n if mar[letter+i].isdigit():\n buf += mar[letter+i]\n copp += mar[letter+i]\n i += 1\n while mar[letter+i].isdigit():\n buf += mar[letter+i]\n copp += mar[letter+i]\n i += 1\n coin = buf.split()\n summ = int(coin[0])+int(coin[1])\n buf = str(summ)\n \n \n else:\n while mar[letter+i] == \"-\":\n buf += ' '\n copp += '-'\n i += 1\n if mar[letter+i].isdigit():\n buf += mar[letter+i]\n copp += mar[letter+i]\n i += 1\n while mar[letter+i].isdigit():\n buf += mar[letter+i]\n copp += mar[letter+i]\n i += 1\n coin = buf.split()\n summ = int(coin[0])-int(coin[1])\n buf = str(summ)\n print(copp)\n print(summ)\n Old.append(copp)\n New.append(summ)\n buf = \"\"\n copp = \"\"\n i = 1\n\nwordforreplace = str(Old[3])\nnewword = str(New[3])\nword = \"\"\nfor itemss in range(len(matr)):\n wholeitem = \"\"\n for letter1 in matr[itemss]:\n if not letter1 == ' ' and not letter1 == '.' and not letter1.isdigit():\n word += letter1\n else:\n if word == wordforreplace:\n word = newword\n wholeitem += word + ' '\n word = \" \"\n else:\n wholeitem += word + ' '\n word = \"\"\n word = \"\"\n matr[itemss] = wholeitem\nfor i in matr:\n print(i)\n \n'''\n# Количество слов длины 2, 3 и тд\nmi_len = 0\nch = 0\nmust = 0\nkolvo = 0\nv = 1\nfor i in matr:\n u = len(i)\n j = 0\n k, k1 = 0, 0\n while i[j] == ' ':\n j += 1\n k1 += 1\n while i[u - 1] == ' ':\n k += 1\n u -= 1\n i = i[k1:len(i) - k] + '@'\n for x in i:\n if x.isalnum():\n ch += 1\n if ch > mi_len:\n mi_len = ch\n else:\n ch = 0\n ch = 0\n for z in range(2,mi_len+1):\n for x in i:\n if x.isalnum():\n must += 1\n elif must == z:\n kolvo += 1\n \n if x.isalnum() == False:\n must = 0\n must = 0\n if kolvo !=0:\n print('Кол-во слов длиной',z,'в',v,'строке равно:', kolvo)\n kolvo = 0\n mi_len = 0\n v += 1\n print()'''\n \n \n \n\n\n \n\n","sub_path":"TrashPython/Лаб.раб.по прог/лаба строки/лаба норм пробелы — копия.py","file_name":"лаба норм пробелы — копия.py","file_ext":"py","file_size_in_byte":7632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"531993569","text":"\"\"\"\n\nCreated by: Nathan Starkweather\nCreated on: 02/11/2016\nCreated in: PyCharm Community Edition\n\n\n\"\"\"\nimport goffice.client\n\n__author__ = 'Nathan Starkweather'\n\nimport logging\nimport os\n\nimport lxml.etree\n\nlogger = logging.getLogger(__name__)\ninfo = logger.info\ndebug = logger.debug\nwarn = logger.warn\nfatal = logger.fatal\nlog = logger.log\n\n\n# Util #\n\n\ndef _local_curdir():\n return os.path.abspath(os.path.dirname(__file__))\n\n\ndef _join_local_curdir(*paths):\n return os.path.join(_local_curdir(), *paths)\n\n\ndef load_keypath(key_file):\n rv = _join_local_curdir(\"data\", \".auth\", key_file)\n debug(\"returning key path: %s\", rv)\n return rv\n\n\ndef _load_default_keypath():\n return load_keypath(\"_exp_auth_key_store.json\")\n\n\ndef open_client():\n from goffice.client import GClient, authorize_client, authorize_credentials\n from oauth2client.file import Storage\n\n keypath = _load_default_keypath()\n s = Storage(keypath)\n try:\n cr = s.locked_get()\n except Exception:\n cr = None\n if cr is None:\n cr = authorize_credentials(keypath.replace(\"_store\", ''))\n s.locked_put(cr)\n\n return GClient(cr)\n\n\n# noinspection PyUnresolvedReferences\ndef test():\n from goffice.client import GClient\n import goffice\n g = goffice.authorize_client(load_keypath(\"_exp_auth_key_encr.json\"), \"081089\")\n # import gspread\n #\n # c = gspread.Client(GClient(\"081089\").session.auth)\n # c.login()\n # print(c.get_spreadsheets_feed())\n content = g.get_workbooks()\n print(content)\n import tempfile\n import io\n tree = lxml.etree.parse(io.BytesIO(content))\n\n with tempfile.NamedTemporaryFile(\"wb\", delete=False) as f:\n tree.submit(f, pretty_print=True)\n import subprocess\n subprocess.Popen(\"notepad.exe %s\" % f.name)\n import time\n time.sleep(.5)\n os.remove(f.name)\n\nif __name__ == '__main__':\n test()\n","sub_path":"db_stuff/google_loader.py","file_name":"google_loader.py","file_ext":"py","file_size_in_byte":1892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"402079586","text":"# Python 2 / 3 compatibility\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport logging\nimport os.path\nimport re\n\n\n# Constants from rrdbotd and rrdbot-create.\nDEFAULT_CONFIG_DIR = \"/etc/rrdbot\"\n\nCONFIG_GENERAL = b\"general\"\nCONFIG_RAW = b\"raw\"\nCONFIG_POLL = b\"poll\"\nCONFIG_INTERVAL = b\"interval\"\nCONFIG_TIMEOUT = b\"timeout\"\nCONFIG_SOURCE = b\"source\"\nCONFIG_REFERENCE = b\"reference\"\nCONFIG_CREATE = b\"create\"\nCONFIG_CF = b\"cf\"\nCONFIG_ARCHIVE = b\"archive\"\nCONFIG_TYPE = b\"type\"\nCONFIG_MIN = b\"min\"\nCONFIG_MAX = b\"max\"\n\nVAL_UNKNOWN = b\"U\"\nVAL_ABSOLUTE = b\"ABSOLUTE\"\nVAL_GAUGE = b\"GAUGE\"\nVAL_COUNTER = b\"COUNTER\"\nVAL_DERIVE = b\"DERIVE\"\n\n\nclass ConfigurationError(Exception):\n pass\n\n\nclass RRDBotConfigItem(object):\n # pylint: disable=too-few-public-methods\n\n __slots__ = (\"name\", \"source\", \"reference\", \"type\", \"min\", \"max\")\n\n def __init__(self, name, source):\n self.name = name\n self.source = source\n self.reference = None\n self.type = VAL_ABSOLUTE\n self.min = VAL_UNKNOWN\n self.max = VAL_UNKNOWN\n\n @property\n def key(self):\n return (self.source, self.reference)\n\n\nclass RRDBotConfigFile(object):\n # pylint: disable=too-few-public-methods\n\n __slots__ = (\"filepath\", \"raw_file_templates\", \"items\")\n\n def __init__(self, filepath):\n self.filepath = filepath\n self.raw_file_templates = set()\n self.items = {}\n\n\n# See rrdbot/common/config-parser.c cfg_parse_dir, parse_dir_internal\ndef cfg_parse_dir(rrdbot_conf_dir):\n configs = []\n\n logger = logging.getLogger()\n logger.debug(\"Searching %s for configuration files\", rrdbot_conf_dir)\n for directory, dummy_subdirectories, files in os.walk(rrdbot_conf_dir):\n logger.debug(\"Searching directory %s\", directory)\n for filename in files:\n filepath = os.path.join(directory, filename)\n logger.debug(\"Reading %s\", filepath)\n config = RRDBotConfigFile(filepath)\n try:\n with open(filepath, \"rb\") as config_file:\n cfg_parse_file(config_file, config)\n configs.append(config)\n except EnvironmentError as ex:\n logger.warning(\n \"Failed to read config file %s : %s\", filepath, ex\n )\n except ConfigurationError as ex:\n logger.warning(\"%s\", ex)\n else:\n logger.debug(\" Raw file templates:\")\n for raw_file_template in sorted(config.raw_file_templates):\n logger.debug(\" %s\", raw_file_template)\n logger.debug(\" Items:\")\n for field in sorted(config.items.keys()):\n item = config.items[field]\n if item.reference is None:\n continue\n logger.debug(\n \" %s type=%s min=%s max=%s\",\n item.reference, item.type, item.min, item.max\n )\n\n return configs\n\n\n# See rrdbot/common/config-parser.c cfg_parse_file\ndef cfg_parse_file(config_file, config):\n header = name = value = None\n\n for index, line in enumerate(config_file):\n line = line.rstrip()\n\n # Continuation line (had spaces at start)\n if line and line[:1].isspace():\n if not value:\n raise ConfigurationError(\n \"Invalid continuation in config %s:%d : %s\" % \\\n (index+1, config_file.name, line)\n )\n\n # Continuations are separated by spaces\n # NB: config-parser.c does not handle this properly\n value += b\" \" + line.lstrip()\n continue\n\n # No continuation hand off value if necessary\n if name and value:\n config_value(header, name, value, config)\n\n name = value = None\n\n # Empty lines / comments at start / comments without continuation\n if not line or line.startswith(b\"#\"):\n continue\n\n # A header\n if line.startswith(b\"[\"):\n index = line.find(b\"]\", 1)\n if index == -1 or index == 1:\n raise ConfigurationError(\n \"Invalid config header %s:%d : %s\" % \\\n (index+1, config_file.name, line)\n )\n header = line[1:index].strip()\n continue\n\n # Look for the break between name = value on the same line\n match = re.search(b\"[:=]\", line)\n if match is None:\n raise ConfigurationError(\n \"Invalid config line %s:%d : %s\" % \\\n (index+1, config_file.name, line)\n )\n name = line[:match.start()].strip()\n value = line[match.end():].strip()\n\n if name and value:\n config_value(header, name, value, config)\n\n\n# See rrdbot/daemon/config.c cfg_value, config_value\n# tools/rrdbot-create.c cfg_value\ndef config_value(header, name, value, config):\n # pylint: disable=too-many-return-statements,too-many-branches\n\n logger = logging.getLogger()\n\n if header == CONFIG_GENERAL:\n if name == CONFIG_RAW:\n config.raw_file_templates.add(value.decode(\"latin-1\"))\n\n elif header == CONFIG_POLL:\n if name == CONFIG_INTERVAL:\n return\n\n if name == CONFIG_TIMEOUT:\n return\n\n # Parse out suffix\n if b\".\" not in name:\n return\n\n name, suffix = name.split(b\".\", 1)\n\n # If it starts with \"field.reference\"\n if suffix == CONFIG_SOURCE:\n # Parse out the field\n parse_item(name, value, config)\n\n # If it starts with \"field.reference\"\n if suffix == CONFIG_REFERENCE:\n # Parse out the field\n parse_item_reference(name, value, config)\n\n\n elif header == CONFIG_CREATE:\n if name == CONFIG_CF:\n return\n\n if name == CONFIG_ARCHIVE:\n return\n\n # Try and see if the field has a suffix\n if b\".\" not in name:\n return # Ignore unknown options\n\n name, suffix = name.split(b\".\", 1)\n\n if name not in config.items:\n logger.warning(\"%s: Field %s not found\", config.filepath, name)\n return\n\n if suffix == CONFIG_TYPE:\n value = value.upper()\n if value in [VAL_ABSOLUTE, VAL_COUNTER, VAL_GAUGE, VAL_DERIVE]:\n config.items[name].type = value\n else:\n logger.warning(\n \"%s: Invalid field type: %s\", config.filepath, value\n )\n return\n\n elif suffix == CONFIG_MIN:\n value = value.upper()\n if value != VAL_UNKNOWN:\n try:\n value = int(value)\n except ValueError:\n logger.warning(\n \"%s: Invalid field min: %s\", config.filepath, value\n )\n return\n config.items[name].min = value\n\n elif suffix == CONFIG_MAX:\n value = value.upper()\n if value != VAL_UNKNOWN:\n try:\n value = int(value)\n except ValueError:\n logger.warning(\n \"%s: Invalid field max: %s\", config.filepath, value\n )\n return\n config.items[name].max = value\n\n # Ignore unknown options\n\n\n# See rrdbot/daemon/config.c parse_item\ndef parse_item(field, uri, config):\n # Don't parse URI, we can't do it completely from here anyway\n if field not in config.items:\n config.items[field] = RRDBotConfigItem(field, uri)\n\n\n# See rrdbot/daemon/config.c parse_item_reference\ndef parse_item_reference(field, reference, config):\n if field not in config.items:\n logger = logging.getLogger()\n logger.warning(\"%s: Field %s not found\", config.filepath, field)\n else:\n config.items[field].reference = reference\n","sub_path":"rrdbot/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":8088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"250521410","text":"# coding: utf-8 -*-\n# app: encuestas\n# desc: RegEx para las URL de la app de encuestas\n# __author__: Javier Sanchez Toledano\n\nfrom django.urls import path\nfrom apps.encuestas import views\n\nurlpatterns = [\n path('', views.index, name='encuestas-index'),\n path('/', views.detalle, name='encuestas-detalle'),\n path('add/', views.add_encuesta, name='encuesta-anterior')\n]\n","sub_path":"src/apps/encuestas/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"429662345","text":"import numpy as np\nfrom scipy.spatial.distance import cosine, hamming\nfrom scipy.stats import pearsonr\nfrom sklearn.metrics.pairwise import cosine_similarity\n\n\ndef cosine_sim_closest(X, x_query, n=1):\n lim = n + 1\n sim = cosine_similarity(X, x_query.reshape(1, -1)).ravel()\n ind = np.argpartition(sim, -lim)[-lim:]\n ind = ind[np.argsort(sim[ind])]\n return ind[:-1], sim[ind[:-1]]\n\n\ndef cosine_sim_top(X, x_query, tol=0.95):\n sim = cosine_similarity(X, x_query.reshape(1, -1)).ravel()\n lim = sum(sim > tol)\n ind = np.argpartition(sim, -lim)[-lim:]\n ind = ind[np.argsort(sim[ind])]\n return ind[:-1], sim[ind[:-1]]\n\n\ndef inv_cosine(xi, xj):\n dij = cosine(xi, xj)\n val = 1.0 / dij\n return val\n\n\ndef inv_hamming(xi, xj):\n dij = hamming(xi, xj)\n val = 1.0 / dij\n return val\n\n\ndef pearson(xi, xj):\n return pearsonr(xi, xj)[0]\n\n\ndef inv_pearson(xi, xj):\n return 1.0 / pearson(xi, xj)\n\n\ndef diversity(plist, dist_f, norm_f):\n \"\"\" diversity of a playlist\n\n Common choices for dist_f are inverse cosine similarity, inverse\n Pearson correlation, or Hamming distance\n \"\"\"\n n = len(plist)\n sum_d = np.sum([dist_f(plist[i], plist[j])\n for i in range(n) for j in range(i + 1, n)])\n\n p_norm = norm_f(plist)\n val = sum_d / (p_norm * (p_norm - 1))\n\n return val\n\n\ndef dcg_from_ranking(y_true, ranking):\n \"\"\"Discounted cumulative gain (DCG) at rank k\n Parameters\n ----------\n y_true : array-like, shape = [n_samples]\n Ground truth (true relevance labels).\n ranking : array-like, shape = [k]\n Document indices, i.e.,\n ranking[0] is the index of top-ranked document,\n ranking[1] is the index of second-ranked document,\n ...\n k : int\n Rank.\n Returns\n -------\n DCG @k : float\n \"\"\"\n y_true = np.asarray(y_true)\n ranking = np.asarray(ranking)\n rel = y_true[ranking]\n gains = 2 ** rel - 1\n discounts = np.log2(np.arange(len(ranking)) + 2)\n return np.sum(gains / discounts)\n\ndef NDCG_1(y_true, ranking):\n \"\"\"Normalized discounted cumulative gain (NDCG) at rank k\n Parameters\n ----------\n y_true : array-like, shape = [n_samples]\n Ground truth (true relevance labels).\n ranking : array-like, shape = [k]\n Document indices, i.e.,\n ranking[0] is the index of top-ranked document,\n ranking[1] is the index of second-ranked document,\n ...\n k : int\n Rank.\n Returns\n -------\n NDCG @k : float\n \"\"\"\n y_true = np.array(y_true)\n ranking = np.array(ranking)\n k = len(ranking)\n best_ranking = np.argsort(y_true)[::-1]\n best = dcg_from_ranking(y_true, best_ranking)\n return dcg_from_ranking(y_true, ranking) / best\n\n\ndef IDCG(true, pred):\n n_common = len(set(true).intersection(set(pred)))\n return 1 + np.sum([1.0 / np.log2(i) for i in range(2, n_common + 1)])\n\ndef DCG(true, pred):\n\n relevant = set(true).intersection(set(pred))\n n_common = len(set(true).intersection(set(pred)))\n if n_common == 0:\n return 0.0\n else:\n ranks = [i for i,p in enumerate(pred) if p in relevant]\n score = 0.0\n for order, rank in enumerate(ranks):\n score += float(rank)/float(len(pred)) / np.log2((order + 2))\n return score\n\n\ndef NDCG(true, pred):\n return DCG(true, pred) / IDCG(true, pred)\n\n\ndef recall(true, pred):\n \"\"\"\n pred: a single prediction playlist\n true: ground truth\n\n \"\"\"\n return len(set(true).intersection(set(pred))) / float(len(set(true)))\n\n\ndef recommended_song_click(true, pred):\n \"\"\"\n pred: list of predictions\n true: ground truth\n \"\"\"\n cnt = 1\n for predictions in pred:\n if true in predictions:\n break\n else:\n cnt += 1\n\n return cnt / 10 * 1.0\n\ndef r_precision(true, pred):\n \"\"\"\n pred: a single, ranked prediction playlist\n true: ground truth\n \"\"\"\n gt_length = len(true)\n top_preds = pred[:gt_length]\n return len(set(true).intersection(set(top_preds))) / float(len(true))\n","sub_path":"src/data/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":4046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"460499442","text":"import gpandas as gpd\nimport datetime\nimport os\n\n\ntry:\n os.chdir(os.path.dirname(os.path.realpath(__file__)))\nexcept:\n pass\n\n\nfecha = datetime.datetime.now().strftime(\"%d/%m\")\n\n\ndef main():\n recipients = 'Emilio Bravo Maturana '\n titulo = f'Progreso al {fecha} (aviso automatizado)'\n html = populate_data_on_mail()\n \n send_mail(recipients, titulo, html)\n \n\ndef populate_data_on_mail():\n \n progress = gpd.read_gexcel('1My0exuCahxoaY78Aybw1NQQgA9C4DWFtEt34eQzVO5Q')[['Centro', 'Progress']].groupby(['Centro']).mean().round().astype(int)['Progress']\n progress_percent = (progress.astype(str) + '%').replace('0%','.')\n\n with open('mail_template.txt', 'r') as f:\n template = f.read()\n\n for centro in progress_percent.index:\n template = template.replace(f'#{centro}%#', str(progress_percent[centro]))\n for centro in progress.index:\n template = template.replace(f'#{centro}#', str(progress[centro]))\n \n return template\n\n\ndef send_mail(recipients, titulo, html):\n\n email = f'''From: Servidor SENDA \nTo: {recipients}\nSubject: {titulo}\nContent-Type: text/html\n\n {html}\n\n'''\n\n with open(\"progress_mail.txt\", \"w\") as text_file:\n text_file.write(email)\n\n os.system('sendmail -t < progress_mail.txt')\n\n \nif __name__ == \"__main__\":\n main()\n\n\n\n\n","sub_path":"py/mail_progress.py","file_name":"mail_progress.py","file_ext":"py","file_size_in_byte":1388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"362001239","text":"##modified from https://github.com/zhixuhao/unet\nfrom __future__ import print_function\nfrom keras.preprocessing.image import ImageDataGenerator\nimport numpy as np \nimport os\nimport glob\nimport skimage.io as io\nimport skimage.transform as trans\n\nSky = [128,128,128]\nBuilding = [128,0,0]\nPole = [192,192,128]\nRoad = [128,64,128]\nPavement = [60,40,222]\nTree = [128,128,0]\nSignSymbol = [192,128,128]\nFence = [64,64,128]\nCar = [64,0,128]\nPedestrian = [64,64,0]\nBicyclist = [0,128,192]\nUnlabelled = [0,0,0]\n\nCOLOR_DICT = np.array([Sky, Building, Pole, Road, Pavement,\n Tree, SignSymbol, Fence, Car, Pedestrian, Bicyclist, Unlabelled])\n\n\ndef adjustData(img,mask,flag_multi_class,num_class):\n if(flag_multi_class):\n img = img / 255\n mask = mask[:,:,:,0] if(len(mask.shape) == 4) else mask[:,:,0]\n new_mask = np.zeros(mask.shape + (num_class,))\n for i in range(num_class):\n #for one pixel in the image, find the class in mask and convert it into one-hot vector\n #index = np.where(mask == i)\n #index_mask = (index[0],index[1],index[2],np.zeros(len(index[0]),dtype = np.int64) + i) if (len(mask.shape) == 4) else (index[0],index[1],np.zeros(len(index[0]),dtype = np.int64) + i)\n #new_mask[index_mask] = 1\n new_mask[mask == i,i] = 1\n new_mask = np.reshape(new_mask,(new_mask.shape[0],new_mask.shape[1]*new_mask.shape[2],new_mask.shape[3])) if flag_multi_class else np.reshape(new_mask,(new_mask.shape[0]*new_mask.shape[1],new_mask.shape[2]))\n mask = new_mask\n elif(np.max(img) > 1):\n img = img / 255\n mask = mask /255\n mask[mask > 0.5] = 1\n mask[mask <= 0.5] = 0\n return (img,mask)\n\n\n\ndef trainGenerator(batch_size,train_path,image_folder,mask_folder,aug_dict,image_color_mode = \"grayscale\",\n mask_color_mode = \"grayscale\",image_save_prefix = \"image\",mask_save_prefix = \"mask\",\n flag_multi_class = False,num_class = 2,save_to_dir = None,target_size = (256,256),seed = 1):\n '''\n can generate image and mask at the same time\n use the same seed for image_datagen and mask_datagen to ensure the transformation for image and mask is the same\n if you want to visualize the results of generator, set save_to_dir = \"your path\"\n '''\n image_datagen = ImageDataGenerator(**aug_dict)\n mask_datagen = ImageDataGenerator(**aug_dict)\n image_generator = image_datagen.flow_from_directory(\n train_path,\n classes = [image_folder],\n class_mode = None,\n color_mode = image_color_mode,\n target_size = target_size,\n batch_size = batch_size,\n save_to_dir = save_to_dir,\n save_prefix = image_save_prefix,\n seed = seed)\n mask_generator = mask_datagen.flow_from_directory(\n train_path,\n classes = [mask_folder],\n class_mode = None,\n color_mode = mask_color_mode,\n target_size = target_size,\n batch_size = batch_size,\n save_to_dir = save_to_dir,\n save_prefix = mask_save_prefix,\n seed = seed)\n train_generator = zip(image_generator, mask_generator)\n for (img,mask) in train_generator:\n img,mask = adjustData(img,mask,flag_multi_class,num_class)\n yield (img,mask)\n\n\n\ndef testGenerator(test_path, strtstr, target_size = (256,256),flag_multi_class = False,as_gray = True):\n dir = os.path.expanduser(test_path)\n count = 0\n for target in sorted(os.listdir(dir)):\n d = os.path.join(dir, target)\n filename, ext = os.path.splitext(os.path.basename(d))\n #print(filename,ext)\n if filename.startswith(strtstr):\n #img = io.imread(d,as_gray = as_gray)\n #print('file read: ',filename)\n# for i in range(num_image):\n img = io.imread(d,as_gray = as_gray)\n img = img / 255\n img = trans.resize(img,target_size)\n img = np.reshape(img,img.shape+(1,)) if (not flag_multi_class) else img\n img = np.reshape(img,(1,)+img.shape)\n## if(count > 2):\n## break;\n## else:\n## count += 1\n yield img\n\n\ndef geneTrainNpy(image_path,mask_path,flag_multi_class = False,num_class = 2,image_prefix = \"image\",mask_prefix = \"mask\",image_as_gray = True,mask_as_gray = True):\n image_name_arr = glob.glob(os.path.join(image_path,\"%s*.png\"%image_prefix))\n image_arr = []\n mask_arr = []\n for index,item in enumerate(image_name_arr):\n img = io.imread(item,as_gray = image_as_gray)\n img = np.reshape(img,img.shape + (1,)) if image_as_gray else img\n mask = io.imread(item.replace(image_path,mask_path).replace(image_prefix,mask_prefix),as_gray = mask_as_gray)\n mask = np.reshape(mask,mask.shape + (1,)) if mask_as_gray else mask\n img,mask = adjustData(img,mask,flag_multi_class,num_class)\n image_arr.append(img)\n mask_arr.append(mask)\n image_arr = np.array(image_arr)\n mask_arr = np.array(mask_arr)\n return image_arr,mask_arr\n\n\ndef labelVisualize(num_class,color_dict,img):\n img = img[:,:,0] if len(img.shape) == 3 else img\n img_out = np.zeros(img.shape + (3,))\n for i in range(num_class):\n img_out[img == i,:] = color_dict[i]\n return img_out / 255\n\n\n#def saveResult(save_path,filename,npyfile,flag_multi_class = False,num_class = 2):\ndef saveResult(save_path,npyfile,pref,flag_multi_class = False,num_class = 2):\n full = np.zeros((1536, 2048))\n dim = 256\n col = 0\n row = 0\n## io.imsave(os.path.join(save_path,\".tif\"),img)\n for i,item in enumerate(npyfile):\n img = item[:,:,0]\n## #print(img)\n flname = pref+str(i)\n io.imsave(os.path.join(save_path,\"%s.tif\"%flname),img)\n #if you want to combine the image slices, uncomment below\n## full[col * dim: (col + 1) * dim, row * dim: (row + 1) * dim] = img\n## if row >= (2048/dim)-1 :\n## row = 0\n## col += 1\n## else:\n## row += 1\n## if col >= (1536/dim) :\n## print('all images saved')\n## break\n## io.imsave(os.path.join(save_path,\"%d_full.png\"%filename),full)\n## return full\n print(\"Results saved for: \",save_path)\n\n##\n##def saveResult(save_path,npyfile,flag_multi_class = False,num_class = 2):\n## for i,item in enumerate(npyfile):\n## img = item[:,:,0]\n## io.imsave(os.path.join(save_path,\"%d_predict.tif\"%i),img)\n\n","sub_path":"UNet/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":6455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"467778819","text":"\n# coding: utf-8\n\n# In[1]:\n\nfrom mongoengine.context_managers import switch_collection\nfrom mongoengine import connect\nfrom mongoengine.errors import ValidationError\n\n\n# In[2]:\n\npdb\n\n\n# In[3]:\n\nfrom flpd_helper.documents import resolution_mapping\n\n\n# In[4]:\n\nfrom flpd_helper import (\n DB_NAME,\n get_names,\n documents,\n main_collections,\n)\n\n\n# In[5]:\n\nfrom flpd_helper.documents import Accident, Citation\n\n\n# In[6]:\n\n(\n main_collection_names, \n validated_collection_names, \n mapped_collection_names,\n) = get_names()\n\n\n# In[7]:\n\nclient = connect(DB_NAME)\ndatabase = client.get_database(DB_NAME)\n\n\n# In[8]:\n\ndestination_collections = tuple(\n database.get_collection(name)\n for name in mapped_collection_names\n)\nsource_collections = tuple(\n database.get_collection(name)\n for name in validated_collection_names\n)\nassert all([len(collection) == 2 \n for collection \n in (destination_collections, source_collections)])\n\n\n# In[9]:\n\n# clear collections\nfor collection in destination_collections:\n collection.delete_many({})\n\n\n# In[10]:\n\nmixed_type_keys = (\n (\n 'district_code',\n 'report_area_description',\n 'zone_code',\n 'geoy',\n 'geox',\n 'time_reported',\n 'road_type_code',\n ),\n (\n 'geoy',\n 'geox',\n 'street_number',\n 'zone_code',\n 'reporting_area_desc',\n 'district_code',\n 'age',\n ),\n)\n# using a comprehension to create the mapping means only having to add values \n# to collections in mixed_type_keys\n# as validation errors are thrown during the call to save on mongoengine.Document subclass instances\nfalse_value_updates = tuple(dict(zip(keys, (None, ) * len(keys)))\n for keys in mixed_type_keys)\n\n\n# In[11]:\n\ndestination_documents = (Accident, Citation)\n\n\n# In[12]:\n\niter_items = zip(\n source_collections,\n destination_collections,\n destination_documents,\n documents.safe_keys,\n false_value_updates\n)\nfor item in iter_items:\n (\n validated_collection,\n destination_collection,\n destination_document,\n document_safe_keys,\n false_value_update\n ) = item\n for src_document in validated_collection.find({}):\n # update keys on src_document\n _src_document = dict([\n (new_key, src_document[old_key])\n for old_key, new_key \n in document_safe_keys\n ])\n # cast, for example, int to string if str is expected yet value is an int\n for old_key, new_key in document_safe_keys:\n type_recaster = resolution_mapping[validated_collection.name][old_key] if old_key in resolution_mapping[validated_collection.name] else lambda x: x\n try:\n _src_document[new_key] = type_recaster(_src_document[new_key])\n except TypeError:\n # because a custom type recaster returns a function\n # to match the api for instantiating mongoengine.Field classes\n _src_document[new_key] = type_recaster()(_src_document[new_key]) \n except ValueError as e:\n try:\n assert false_value_update.get(new_key, None) is None\n except AssertionError as e:\n print(AssertionError(e))\n print(new_key, old_key)\n print(\"Add a key to `mixed_type_keys`.\")\n for old_key, new_key in document_safe_keys:\n new_key_value = _src_document[new_key]\n if all((\n new_key in false_value_update,\n all((\n not new_key_value, \n new_key_value != 0, \n new_key_value != '0', \n )),\n )):\n _src_document[new_key] = false_value_update[new_key]\n with switch_collection(\n destination_document, \n destination_collection.name\n ) as Document:\n new_document = Document(**_src_document)\n try:\n new_document.save()\n except ValidationError as e:\n print(ValidationError(e))\n import pdb\n pdb.set_trace()\n\n\n# In[13]:\n\n# 4 to 6 of main_collections are valid_* collections\nfor item in destination_collections + tuple(main_collections[4:6]):\n print(': '.join((item.name, str(item.count()))))\nassert all([validated.count() == mapped.count() for validated, mapped \n in zip(source_collections, destination_collections)])\n\n","sub_path":"notebooks/unify_data_types_in_validated_collections.py","file_name":"unify_data_types_in_validated_collections.py","file_ext":"py","file_size_in_byte":4647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"235950387","text":"# coding:utf-8\n\nfrom flask.views import View\nfrom flask import request, make_response, current_app\nfrom werkzeug.wrappers import Response as ResponseBase\nfrom validater import validate\nfrom validater import ProxyDict\nfrom . import ResourceException, abort, exporters\n\n\nclass Resource(View):\n\n \"\"\"Resource代表一个资源\n\n - schema_inputs is a dict of scheams for validate inputs.\n it's key is method name\n - schema_outputs is a dict of scheams for validate outputs.\n it's key is method name\n - output_types is a list of custom type of outputs\n , the custom type object will be proxy by validater.ProxyDict\n - before_request_funcs is a list of functions\n - after_request_funcs is a list of functions\n - handle_error_func is a functions\n \"\"\"\n\n schema_inputs = {}\n schema_outputs = {}\n output_types = []\n before_request_funcs = []\n after_request_funcs = []\n handle_error_func = None\n\n @classmethod\n def _before_request(cls):\n \"\"\"before_request\"\"\"\n for fn in cls.before_request_funcs:\n rv = fn()\n if rv is not None:\n return rv\n return None\n\n @classmethod\n def _after_request(cls, rv, code, headers):\n for fn in cls.after_request_funcs:\n rv, code, headers = fn(rv, code, headers)\n return rv, code, headers\n\n @classmethod\n def _handle_error(cls, ex):\n if cls.handle_error_func:\n rv = cls.handle_error_func(ex)\n if rv is not None:\n return rv\n if isinstance(ex, ResourceException):\n if ex.code >= 500 and not current_app.debug:\n return {\"error\": \"interal server error\"}, ex.code\n else:\n return ex.error, ex.code\n else:\n raise ex\n\n @classmethod\n def after_request(cls, f):\n \"\"\"decorater\"\"\"\n cls.after_request_funcs.append(f)\n return f\n\n @classmethod\n def before_request(cls, f):\n \"\"\"decorater\"\"\"\n cls.before_request_funcs.append(f)\n return f\n\n @classmethod\n def error_handler(cls, f):\n \"\"\"decorater\"\"\"\n cls.handle_error_func = f\n return f\n\n def dispatch_request(self, *args, **kwargs):\n \"\"\"preproccess request and dispatch request\n \"\"\"\n act = request.endpoint.split('@')\n if len(act) > 1:\n meth_name = request.method.lower() + \"_\" + act[1]\n else:\n meth_name = request.method.lower()\n if not hasattr(self, meth_name) and request.method == 'HEAD':\n meth_name = \"get\"\n request.resource = self.__class__.__name__\n request.action = meth_name\n try:\n # before_request\n rv = self._before_request()\n if rv is None:\n rv = self.full_dispatch_request(*args, **kwargs)\n except Exception as ex:\n rv = self._handle_error(ex)\n rv, code, headers = unpack(rv)\n rv, code, headers = self._after_request(rv, code, headers)\n if rv is None:\n return make_response(\"\", code, headers)\n elif isinstance(rv, (ResponseBase, basestring)):\n return make_response(rv, code, headers)\n else:\n mediatype = request.accept_mimetypes.best_match(\n exporters.keys(), default='application/json')\n export = exporters[mediatype]\n return export(rv, code, headers)\n\n def full_dispatch_request(self, *args, **kwargs):\n \"\"\"actual dispatch request, validate inputs and outputs\n \"\"\"\n fn = getattr(self, request.action, None)\n if fn is None:\n abort(404, 'Unimplemented action %r' % fn.name)\n inputs = self.__class__.schema_inputs.get(request.action)\n outputs = self.__class__.schema_outputs.get(request.action)\n output_types = self.__class__.output_types\n method = request.method.lower()\n if inputs is not None:\n if method in [\"get\", \"delete\"]:\n data = request.args.copy()\n elif method in [\"post\", \"put\"]:\n if request.headers[\"Content-Type\"] == 'application/json':\n try:\n data = request.get_json()\n except:\n abort(400, \"Invalid json content\")\n else:\n data = request.form.copy()\n else:\n data = {}\n (errors, values) = validate(data, inputs)\n if errors:\n abort(400, dict(errors))\n else:\n rv = fn(**values)\n else:\n rv = fn()\n if outputs is not None:\n if output_types and isinstance(rv, tuple(output_types)):\n (errors, values) = validate(ProxyDict(rv, output_types), outputs)\n else:\n (errors, values) = validate(rv, outputs)\n if errors:\n abort(500, dict(errors))\n else:\n rv = values\n return rv\n\n\ndef unpack(rv):\n \"\"\"convert rv to tuple(data, code, headers)\n\n :param rv: data or tuple that contain code and headers\n \"\"\"\n status = headers = None\n if isinstance(rv, tuple):\n rv, status, headers = rv + (None,) * (3 - len(rv))\n if isinstance(status, (dict, list)):\n headers, status = status, None\n return (rv, status, headers)\n","sub_path":"flask_restaction/resource.py","file_name":"resource.py","file_ext":"py","file_size_in_byte":5404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"231524381","text":"#import matplotlib.pyplot as plt\n'''\n\t@ In this python code, the following are executed:\n\t@ Load the entire original images of evaluation dataset to a listdir\n\t@ Preprocess the original images to 224x224x3 RGB images\n\t@ Save new images to .hkl format files correspondingly\n\n'''\nimport numpy as np\nimport scipy.io\nimport cv2\nimport os\nimport hickle as hkl\n\n# Load the data\n\ndata_dir= '/nas/lhoang/data/evaluation/'# Path to original images\nsaved_dir='/nas/lhoang/data/hkl_file/' # Path to saved hkl files\nfn = os.listdir(data_dir) # load file names into a list\n\nfns = [data_dir+ name for name in fn]# concatenate the directory path with the file names\n\t\t\t\t\t\t\t\t\t # (i.e. /homes/lhoang/.../IMG0001.JPEG)\nnumpy = True\n\nfor i in range(len(fns)):\n\tif i%2000==0:\n\t\tprint('%d/%d' % (i,len(fns))) # Print out (2000/500000)\n\tname = fn[i].replace('.JPEG','')+'.hkl' # Remove the .JPEG extension and concatenate with .hkl extension\n\t\t\t\t\t\t\t\t\t\t\t# (i.e., IMG0001.JPEG -> IMG0001.hkl)\n\tname = saved_dir+name \t\t\t\t # Concatenate the saved directory with the hkl file\n\timg = cv2.imread(fns[i])\n\t#print img.shape\n\theight, width, channels = img.shape # Take the size of height, width and channles of an image\n\tnew_height = int((height*256)/min(img.shape[:2])) # Resize the image to 256x256\n\tnew_width = int((width*256)/min(img.shape[:2])) # Method is CUBIC\n\timg_new = cv2.resize(img, (new_width, new_height), interpolation=cv2.INTER_CUBIC).astype(np.float32)\n\t#cropping\n\theight, width, channels = img_new.shape\n\tstart_height = int((height-224)/2)\n\tstart_width = int((width-224)/2)\n\timg = img_new[start_height:start_height+224,start_width:start_width+224]\n\timg[:,:,0] -= 103.939\n\timg[:,:,1] -= 116.779\n\timg[:,:,2] -= 123.68\n\timg\t\t\t= img.transpose((2,0,1))\n\t# new image has the shape of (224,224,3)\n\timg = np.expand_dims(img, axis =0) # now the shape of the image is (1,224,224,3)\n\t#img = np.swapaxes(img, 1,2)\n\t#img = np.swapaxes(img, 1,3) # swap the axes to new shape (1,3,224,224)\n\t\t\t\t\t\t\t\t# This is neccesary to leverage the existing code in\n\t\t\t\t\t\t\t\t# Ares simulator. We will take other approaches if needed\n\thkl.dump(img, name, mode = 'w' ) # Save the new image to a .hkl name\n\n\n\n\t# array_image_data = np.expand_dims(array_image_data,axis=0)\n\t# print (\"shape after the expansion:\",array_image_data.shape)\n\t# array_image_data = preprocess_input(array_image_data)\n\t# print (\"Final shape:\",array_image_data.shape)\n","sub_path":"image_preprocess_2.py","file_name":"image_preprocess_2.py","file_ext":"py","file_size_in_byte":2406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"439909917","text":"from pathlib import Path\n\nfrom mlblocks import MLPipeline, add_pipelines_path, add_primitives_path\nfrom mlblocks import load_pipeline as _load_pipeline\n\nadd_primitives_path(Path(__file__).parents[2].joinpath('blocks', 'primitives'))\nadd_pipelines_path(Path(__file__).parents[2].joinpath('blocks', 'pipelines'))\n\n\nPIPELINES = [\n 'ballet_rf_regressor',\n 'ballet_elasticnet',\n 'train_mean',\n 'leaderboard_mean',\n]\nDEFAULT_PIPELINE = 'ballet_rf_regressor'\n\n\ndef load_pipeline(name: str = DEFAULT_PIPELINE) -> MLPipeline:\n if name not in PIPELINES:\n raise ValueError(f'Pipeline {name!r} is not supported')\n return MLPipeline(_load_pipeline(name))\n","sub_path":"src/fragile_families/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"494204490","text":"# -*- coding: utf-8 -*-\nfrom django.shortcuts import render_to_response, redirect\nfrom django.contrib import auth\nfrom django.core.context_processors import csrf\nfrom django.template import RequestContext\nfrom django.contrib.auth.models import AnonymousUser\nfrom django.db import connection\n\nfrom TestingApp.forms import ErrorForm, DateForm\n\nimport datetime\n\n\ndef remarks(request):\n if request.user == AnonymousUser():\n return redirect('/auth/login/')\n menu = check_user(request, 0)\n args = {\n 'items': menu.list,\n 'username': auth.get_user(request).username,\n 'group': menu.group,\n 'action': '/remarks/',\n 'button': 'Показати'\n }\n args.update(csrf(request))\n finish = datetime.datetime.now().date()\n start = finish - datetime.timedelta(days=30)\n if request.POST:\n date_form = DateForm(request.POST)\n if date_form.is_valid():\n start = date_form.cleaned_data['start']\n finish = date_form.cleaned_data['finish']\n else:\n date_form = DateForm()\n query = \"\"\"\n SELECT remark.idRemark, remark.Title, remark.CreationDate, remark.CorrectionDate,\n remark.Description, programmer.AllName, tester.AllName, version.Title, remark.IsError FROM testing.remark\n LEFT JOIN testing.programmer ON remark.ProgrammerId = programmer.id\n LEFT JOIN testing.tester ON remark.TesterId = tester.id\n LEFT JOIN testing.version ON remark.VersionId = version.idVersion\n WHERE remark.CustomerId = %s AND remark.CreationDate >= '%s' AND remark.CreationDate <= '%s'\n ORDER BY remark.idRemark\"\"\" % (\n menu.person_id,\n start,\n finish\n )\n cursor = connection.cursor()\n cursor.execute(query)\n records = cursor.fetchall()\n records = [[col for col in record] for record in records]\n for record in records:\n last_col = record[len(record) - 1]\n if last_col:\n record[len(record) - 1] = 'Помилка'\n else:\n record[len(record) - 1] = 'Доробка'\n args['records'] = records\n args['date_form'] = date_form\n return render_to_response(\n 'remarks.html',\n args,\n context_instance=RequestContext(request)\n )\n\n\ndef error(request):\n if request.user == AnonymousUser():\n return redirect('/auth/login/')\n menu = check_user(request, 1)\n customer = menu.person_id if request.user.groups.all()[0].name == 'customer' else 'NULL'\n args = {\n 'items': menu.list,\n 'username': auth.get_user(request).username,\n 'group': menu.group,\n 'action': '/error/',\n 'button': 'Створити'\n }\n args.update(csrf(request))\n if request.POST:\n error_form = ErrorForm(request.POST)\n if error_form.is_valid():\n cursor = connection.cursor()\n query = \"\"\"\n INSERT INTO `testing`.`remark` (`Title`, `CreationDate`, `Description`, `CustomerId`, `IsError`)\n VALUES (\"%s\", '%s', \"%s\", %s, %s)\"\"\" % (\n error_form.cleaned_data['title'],\n datetime.datetime.now().date(),\n error_form.cleaned_data['description'],\n customer,\n error_form.cleaned_data['choice']\n )\n cursor.execute(query)\n return redirect('/')\n else:\n error_form = ErrorForm()\n args['error_form'] = error_form\n return render_to_response(\n 'error.html',\n args,\n context_instance=RequestContext(request)\n )\n\n\ndef delete_remark(request, del_id):\n if request.user == AnonymousUser():\n return redirect('/auth/login/')\n cursor = connection.cursor()\n cursor.execute(\"\"\"SELECT TesterId FROM remark WHERE idRemark=%s\"\"\" % del_id)\n record = cursor.fetchall()\n if record[0][0]:\n menu = check_user(request, 1)\n args = {\n 'items': menu.list,\n 'username': auth.get_user(request).username,\n 'group': menu.group,\n 'message': 'Видалення заборонене, тому що зауваження опрацьовується тестувальником.'\n }\n return render_to_response(\n 'denied.html',\n args\n )\n query = \"\"\"DELETE FROM `testing`.`remark` WHERE `idRemark`=%s\"\"\" % del_id\n cursor.execute(query)\n return redirect('/')\n\n\ndef escape(s):\n return s.replace(\"'\", r\"\\'\")\n\n\ndef change_remark(request, change_id):\n if request.user == AnonymousUser():\n return redirect('/auth/login/')\n menu = check_user(request, 0)\n args = {\n 'items': menu.list,\n 'username': auth.get_user(request).username,\n 'group': menu.group,\n 'action': '/change-remark/%s/' % change_id,\n 'button': 'Змінити'\n }\n args.update(csrf(request))\n if request.POST:\n error_form = ErrorForm(request.POST)\n if error_form.is_valid():\n cursor = connection.cursor()\n query = \"\"\"\n UPDATE `testing`.`remark`\n SET `Title`=\"%s\", `Description`='%s', `CreationDate`='%s', `IsError`=%s\n WHERE `idRemark`=%s\"\"\" % (\n error_form.cleaned_data['title'],\n escape(error_form.cleaned_data['description']),\n datetime.datetime.now().date(),\n error_form.cleaned_data['choice'],\n change_id\n )\n cursor.execute(query)\n return redirect('/')\n else:\n cursor = connection.cursor()\n query = \"\"\"\n SELECT remark.Title, remark.Description, remark.IsError\n FROM `testing`.`remark` WHERE `idRemark`=%s\"\"\" % change_id\n cursor.execute(query)\n remark = cursor.fetchall()\n title, description, is_error = remark[0]\n initial = {\n 'title': title,\n 'description': description,\n 'choice': is_error\n }\n error_form = ErrorForm(initial=initial)\n args['error_form'] = error_form\n return render_to_response(\n 'error.html',\n args,\n context_instance=RequestContext(request)\n )\n\n\nclass Item:\n def __init__(self, name, link):\n self.name = name\n self.link = link\n self.current = False\n\n\nclass Menu:\n def __init__(self, lst, group, page, person_id):\n self.list = lst\n self.group = group\n self.page = page\n self.person_id = person_id\n\n\ndef check_user(request, current):\n user = request.user\n lst = []\n if user.customer:\n lst.append(Item('Мої зауваження', 'remarks'))\n lst.append(Item('Створити зауваження', 'error'))\n text = 'клієнта'\n page = 'remarks/'\n person_id = user.customer.id\n elif user.cto:\n lst.append(Item('Зауваження', 'cto-remarks'))\n lst.append(Item('Версії', 'versions'))\n lst.append(Item('Створити нову версію', 'add-version'))\n lst.append(Item('Навантаження на тестувальників', 'tester-load'))\n text = 'технічного директора'\n page = 'cto-remarks/'\n person_id = user.cto.id\n elif user.tester:\n lst.append(Item('Мої зауваження', 'tester'))\n lst.append(Item('Створити зауваження', 'error'))\n lst.append(Item('Навантаження на програмістів', 'programmer-load'))\n text = 'тестувальника'\n page = 'tester/'\n person_id = user.tester.id\n else:\n lst.append(Item('Мої зауваження', 'programmer'))\n text = 'програміста'\n page = 'programmer/'\n person_id = user.programmer.id\n lst.append(Item('Статистика версій', 'version-stat'))\n lst[current].current = True\n return Menu(lst, text, page, person_id)\n\n\ndef index(request):\n if request.user == AnonymousUser():\n return redirect('/auth/login/')\n menu = check_user(request, 0)\n return redirect(menu.page)\n\n\ndef version_stat(request):\n if request.user == AnonymousUser():\n return redirect('/')\n menu = check_user(request, 0)\n menu = check_user(request, len(menu.list) - 1)\n args = {\n 'items': menu.list,\n 'username': auth.get_user(request).username,\n 'group': menu.group\n }\n args.update(csrf(request))\n finish = datetime.datetime.now().date()\n start = finish - datetime.timedelta(days=30)\n if request.POST:\n date_form = DateForm(request.POST)\n if date_form.is_valid():\n start = date_form.cleaned_data['start']\n finish = date_form.cleaned_data['finish']\n else:\n date_form = DateForm()\n cursor = connection.cursor()\n query = \"\"\"SELECT version.idVersion, version.Title, t4.test_count, t2.prog_count\n FROM\n (SELECT t1.idVersion, COUNT(t1.ProgrammerId) AS prog_count\n FROM\n (SELECT idVersion, ProgrammerId\n FROM testing.version\n LEFT JOIN testing.remark ON version.idVersion = remark.VersionId\n GROUP BY version.idVersion, remark.ProgrammerId) AS t1\n GROUP BY t1.idVersion) AS t2\n JOIN\n (SELECT t3.idVersion, COUNT(t3.TesterId) AS test_count\n FROM\n (SELECT idVersion, TesterId\n FROM testing.version\n LEFT JOIN testing.remark ON version.idVersion = remark.VersionId\n GROUP BY version.idVersion, remark.TesterId) AS t3\n GROUP BY t3.idVersion) AS t4\n ON t2.idVersion = t4.idVersion\n JOIN testing.version ON t2.idVersion = version.idVersion\n WHERE version.ReleaseDate >= '%s' AND version.ReleaseDate <= '%s'\"\"\" % (\n start,\n finish\n )\n cursor.execute(query)\n records = cursor.fetchall()\n args['records'] = records\n args['button'] = 'Показати'\n args['date_form'] = date_form\n args['head'] = ['№', 'Назва версії', 'Тестувальники', 'Програмісти']\n args['title'] = 'Кількість працівників, які створювали версію'\n return render_to_response(\n 'loading.html',\n args,\n context_instance=RequestContext(request)\n )\n","sub_path":"TestingApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"150258406","text":"import datetime\n\ndef last_dow_noon(dow, d):\n hours_ahead = d.hour - 12\n if hours_ahead < 0:\n hours_ahead += 24\n last_noon = d - datetime.timedelta(hours=hours_ahead, minutes=d.minute, seconds=d.second, microseconds=d.microsecond)\n days_ahead = last_noon.weekday() - dow\n if days_ahead < 0:\n days_ahead += 7\n return last_noon - datetime.timedelta(days=days_ahead)\n","sub_path":"twitter_models/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"229251584","text":"import requests\nimport re\n\n#a = input()\n#b = input()\n\na = \"https://stepic.org/media/attachments/lesson/24472/sample0.html\"\nb = \"https://stepic.org/media/attachments/lesson/24472/sample2.html\"\n\naRequest = requests.get(a)\n\nlinks = re.findall(r'href=[\\'\"]?([^\\'\" >]+)',aRequest.text,flags=re.IGNORECASE)\n\ncLinks = []\nfor link in links:\n cLinks.extend(re.findall(r'href=[\\'\"]?([^\\'\" >]+)',requests.get(link).text,flags=re.IGNORECASE))\n\nif b in cLinks:\n print(\"Yes\")\nelse:\n print(\"No\")\n","sub_path":"week 3/3.4.6.py","file_name":"3.4.6.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"429004662","text":"# bisect Module : 정렬된 상태로 데이터를 추가할 수 있는 모듈을 의미\n# Heap Module : 리스트를 생성하고 정렬 ( 리스트가 긴 경우 힙 정렬은 시간이 오래 걸림 )\n\"\"\"\n데이터가 많은 경우 힙 정렬 방식보다 시간과 메모리 낭비를 줄일 수 있음.\n\n\"\"\"\n\nimport bisect\nimport random\n\nrandom.seed(1) # seeding : seed 값에 따라 똑같은 난수를 발생시킴\n\n# for i in range(5):\n# print(\"%5.4f\" %random.random(),end='')\n\nprint('New Index List')\nprint('=== ===== ====')\nli = []\n\nfor n in range(1,15):\n num = random.randint(1,100)\n #bisect(sequence, data)\n pos = bisect.bisect(li,num) # 아이템이 추가되었을 때 인덱스 값 리턴\n # 중복된 값이 나올 때 오른쪽에 배치가 됨 => insort()는 정렬시 오른쪽에 정렬 ( insort_right() )\n # 왼쪽에 정렬 ( insort_left() )\n bisect.insort(li,num) # 리스트를 정렬 상태로 유지\n\n# 왼쪽 정렬시\n \"\"\"\n bisect_left()\n insort_left() 사용\n \"\"\"\n print('%3d %3d' %(num, pos), li)\n\n\n","sub_path":"Library/ExampleGroup/Grammer/DataStructure/Bisect/bisect_Total.py","file_name":"bisect_Total.py","file_ext":"py","file_size_in_byte":1132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"62145308","text":"import streamlit as st\r\n\r\nfrom Pages.feature_analysis_page import FeatureAnalysisPage\r\nfrom Pages.introduction_page import IntroductionPage\r\nfrom Pages.models_analysis_page import ModelsAnalysisPage\r\nfrom Pages.predictor_page import PredictorPage\r\n\r\n# to run:\r\nfrom Pages.university_rating_analysis import UniversityRatingAnalysisPage\r\n\r\nif __name__ == '__main__':\r\n st.sidebar.title(\"Graduate Admission Prediction\")\r\n menu = st.sidebar.radio('Navigation', ('Introduction', \"Feature Analysis\", \"Models Analysis\",\r\n \"University Rating Analysis\",\"Predictor\"))\r\n st.sidebar.title(\"Details\")\r\n st.sidebar.info(\r\n \"Author: Zvi Berger and Liel Shuker\")\r\n st.sidebar.info(\r\n \"This Project is based on the paper - 'A Comparison of Regression Models for Predicting Graduate Admission'\")\r\n st.sidebar.info(\r\n \"[The paper](https://drive.google.com/file/d/17su4WNKIwrOA5WUXXS3qIPStu3eLfEfv/view?usp=sharing)\")\r\n st.sidebar.info(\r\n \"[Kaggle Dataset](https://www.kaggle.com/mohansacharya/datasets)\")\r\n st.sidebar.info(\"[Presentation](https://drive.google.com/file/d/1ZDnPhr3IassR4w9k2XWj2hxxtXuPciyS/view?usp=sharing)\")\r\n st.sidebar.info(\"[Github](https://github.com/BergerZvika/Data-Analysis-university-rating-prediction)\")\r\n\r\n introduction = IntroductionPage()\r\n feature_analysis = FeatureAnalysisPage()\r\n predictor = PredictorPage()\r\n models_analysis = ModelsAnalysisPage()\r\n university_rating = UniversityRatingAnalysisPage()\r\n\r\n if menu == 'Introduction':\r\n introduction.show_page()\r\n\r\n if menu == 'Feature Analysis':\r\n feature_analysis.show_page()\r\n\r\n if menu == 'Predictor':\r\n predictor.show_page()\r\n\r\n if menu == \"Models Analysis\":\r\n models_analysis.show_page()\r\n\r\n if menu == \"University Rating Analysis\":\r\n university_rating.show_page()\r\n\r\n\r\n\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"490885384","text":"# -------------------------------------------------------------------------------\n# Licence:\n# Copyright (c) 2012-2017 Luzzi Valerio \n#\n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n# OTHER DEALINGS IN THE SOFTWARE.\n#\n#\n# Name: datatypes.py\n# Purpose:\n#\n# Author: Luzzi Valerio\n#\n# Created: 27/07/2017\n# -------------------------------------------------------------------------------\nimport datetime\nimport numpy as np\nimport xlrd, xlwt\nimport json\n\nfrom .stime import strftime, ctod\nfrom .strings import *\n\n\ndef parseInt(text):\n \"\"\"\n parseInt\n \"\"\"\n if isstring(text):\n PATTERN1 = \"\"\"^[-+]?\\d+$\"\"\"\n PATTERN = \"\"\"(?P(%s))\"\"\" % (PATTERN1)\n text = text.strip()\n g = re.match(PATTERN, text, re.IGNORECASE | re.MULTILINE)\n if g:\n res = g.groupdict()[\"target\"]\n return int(res)\n return None\n\n\ndef parseFloat(text):\n \"\"\"\n parseFloat\n \"\"\"\n if isstring(text):\n PATTERN1 = \"\"\"^[-+]?(?:(\\d+|\\d+\\.\\d*|\\d*\\.\\d+)(e[-+]?\\d+)?)$\"\"\"\n PATTERN = \"\"\"(?P(%s))\"\"\" % (PATTERN1)\n text = text.strip()\n g = re.match(PATTERN, text, re.IGNORECASE | re.MULTILINE)\n if g:\n res = g.groupdict()[\"target\"]\n return float(res)\n return None\n\n\ndef parseDate(text):\n \"\"\"\n parseDate\n \"\"\"\n if isstring(text):\n PATTERN1 = \"\"\"^\\d{1,2}-\\d{1,2}-(\\d{4,4}|\\d{2,2})$\"\"\" # 1-1-2017\n PATTERN2 = \"\"\"^\\d{1,2}(\\/)\\d{1,2}(\\/)(\\d{4,4}|\\d{2,2})$\"\"\" # 1/1/2017\n PATTERN3 = \"\"\"^\\d{4,4}-\\d{1,2}-\\d{1,2}$\"\"\" # 2017-01-01\n PATTERN = \"\"\"(?P(%s)|(%s)|(%s))\"\"\" % (PATTERN1, PATTERN2, PATTERN3)\n text = text.strip()\n g = re.match(PATTERN, text, re.IGNORECASE | re.MULTILINE)\n if g:\n res = g.groupdict()[\"target\"]\n return strftime(\"%Y-%m-%d\", res)\n return None\n\n\ndef parseDatetime(text):\n \"\"\"\n parseDatetime\n \"\"\"\n if isstring(text):\n PATTERN1 = \"\"\"^\\d{1,2}-\\d{1,2}-(\\d{4,4}|\\d{2,2})(\\s\\d{1,2}(:|\\.)\\d{2,2}((:|\\.)\\d\\d)?)?$\"\"\"\n PATTERN2 = \"\"\"^\\d{1,2}(\\/)\\d{1,2}(\\/)(\\d{4,4}|\\d{2,2})(\\s\\d{1,2}(:|\\.)\\d{2,2}((:|\\.)\\d\\d)?)?$\"\"\"\n PATTERN3 = \"\"\"^\\d{4,4}-\\d{1,2}-\\d{1,2}(\\s\\d{1,2}(:|\\.)\\d{2,2}((:|\\.)\\d\\d)?)?$\"\"\"\n PATTERN = \"\"\"(?P(%s)|(%s)|(%s))\"\"\" % (PATTERN1, PATTERN2, PATTERN3)\n text = text.strip()\n g = re.match(PATTERN, text, re.IGNORECASE | re.MULTILINE)\n if g:\n res = g.groupdict()[\"target\"]\n return strftime(\"%Y-%m-%d %H:%M:%S\", res)\n return None\n\n\ndef parseBool(text):\n \"\"\"\n parseBool\n \"\"\"\n if isstring(text):\n text = text.lower()\n if text in (\"true\", \"1\", \"on\"):\n return True\n return False\n\n return True if text else False\n\n\ndef parseColor(text, out=\"hex\"):\n \"\"\"\n parseColor - TODO\n \"\"\"\n if isstring(text):\n\n if xlwt.Style.colour_map.has_key(text):\n return \"%06x\" % xlwt.Style.colour_map[text]\n\n elif len(listify(text.replace(r'[\\s;]', \",\"), \",\")) == 3:\n rgb = listify(text.replace(r'[\\s;]', \",\"), \",\")\n return \"#%02x%02x%02x\" % tuple(val(rgb))\n\n elif len(listify(text.replace(r'[\\s;]', \",\"), \",\")) == 4:\n rgba = listify(text.replace(r'[\\s;]', \",\"), \",\")\n (r, g, b, a) = val(rgba)\n a = int(a * 255) if a <= 1.0 else a\n return \"#%02x%02x%02x%02x\" % (r, g, b, a)\n\n\n return \"000000\"\n\n\ndef parseJSON(text):\n \"\"\"\n parseJSON - load json txt into obj\n \"\"\"\n if isinstance(text, (tuple, list, dict)):\n return text\n if isstring(text):\n return json.loads(text)\n return None\n\ndef isquery(text):\n pattern = r'^\\s*((SELECT|PRAGMA|INSERT|DELETE|REPLACE|UPDATE|CREATE).*)'\n res = re.match(pattern, text, re.IGNORECASE)\n return True if res else False\n\n\ndef isarray(value):\n return isinstance(value, (tuple, list, np.ndarray))\n\n\ndef isfloat(text):\n return not parseDate(text) is None\n\n\ndef isdate(text):\n if isinstance(text, (datetime.date,)):\n return True\n return not parseDate(text) is None\n\n\ndef isdatetime(text):\n if isinstance(text, (datetime.datetime,)):\n return True\n return not parseDatetime(text) is None\n\n\ndef parseValue(value, nodata=(\"\", \"Na\", \"NaN\", \"-\", \"--\", \"N/A\")):\n \"\"\"\n parseValue - parse values from string\n \"\"\"\n if value is None:\n return None\n if isstring(value) and value in nodata:\n return None\n elif isstring(value) and re.match(r'^(GEOMFROM|POINT).*', value, re.I | re.M):\n return value\n elif isdate(value):\n return strftime(\"%Y-%m-%d\", value)\n elif isdatetime(value):\n return strftime(\"%Y-%m-%d %H:%M:%S\", value)\n elif isfloat(value):\n return value\n elif isstring(value):\n return value\n elif isarray(value):\n return [parseValue(item) for item in value]\n return None\n\n\nSQLTYPES = {\n 9999: \"\",\n 9998: \"EMPTY\",\n 1: \"TEXT\",\n 2: \"DATETIME\",\n 3: \"DATE\",\n 4: \"TIME\",\n 5: \"FLOAT\",\n 6: \"INTEGER\",\n 7: \"GEOMETRY\",\n \"\": 9999,\n \"EMPTY\": 9998,\n \"TEXT\": 1,\n \"DATETIME\": 2,\n \"DATE\": 3,\n \"TIME\": 4,\n \"FLOAT\": 5,\n \"INTEGER\": 6,\n \"GEOMETRY\": 7\n}\n\nXLRDTYPES = {\n xlrd.XL_CELL_EMPTY: 9999,\n xlrd.XL_CELL_BLANK: 9999,\n xlrd.XL_CELL_TEXT: 1,\n xlrd.XL_CELL_DATE: 2,\n xlrd.XL_CELL_NUMBER: 5,\n xlrd.XL_CELL_BOOLEAN: 6\n}\n\n\ndef sqltype(cvalue, ctype=xlrd.XL_CELL_TEXT, nodata=(\"\", \"Na\", \"NaN\", \"-\", \"--\", \"N/A\")):\n \"\"\"\n Type symbol\tType number\tPython value\n XL_CELL_EMPTY\t0\tempty string u''\n XL_CELL_TEXT\t1\ta Unicode string\n XL_CELL_NUMBER\t2\tfloat\n XL_CELL_DATE\t3\tfloat\n XL_CELL_BOOLEAN\t4\tint; 1 means TRUE, 0 means FALSE\n XL_CELL_ERROR\t5\tint representing internal Excel codes; for a text representation, refer to the supplied dictionary error_text_from_code\n XL_CELL_BLANK\t6\tempty string u''. Note: this type will appear only when open_workbook(..., formatting_info=True) is used.\n \"\"\"\n if isarray(cvalue):\n if not isarray(ctype):\n ctype = [ctype] * len(cvalue)\n return [sqltype(cv, ct, nodata) for cv, ct in zip(cvalue, ctype)]\n if isinstance(cvalue, xlrd.sheet.Cell):\n return sqltype(cvalue.value, cvalue.ctype, nodata)\n if ctype == xlrd.XL_CELL_EMPTY:\n return 'EMPTY'\n elif ctype == xlrd.XL_CELL_TEXT and cvalue in nodata:\n return ''\n elif ctype == xlrd.XL_CELL_TEXT and isdate(cvalue):\n return 'DATE'\n elif ctype == xlrd.XL_CELL_TEXT and isdatetime(cvalue):\n return 'DATETIME'\n elif ctype == xlrd.XL_CELL_TEXT and parseInt(cvalue):\n return 'INTEGER'\n elif ctype == xlrd.XL_CELL_TEXT and parseFloat(cvalue) != None:\n return 'FLOAT'\n elif ctype == xlrd.XL_CELL_TEXT:\n return 'TEXT'\n elif ctype == xlrd.XL_CELL_NUMBER and int(cvalue) == cvalue:\n return 'INTEGER'\n elif ctype == xlrd.XL_CELL_NUMBER:\n return 'FLOAT'\n elif ctype == xlrd.XL_CELL_DATE:\n return 'DATETIME'\n elif ctype == xlrd.XL_CELL_BOOLEAN:\n return 'INTEGER'\n elif ctype == xlrd.XL_CELL_ERROR:\n return ''\n elif ctype == xlrd.XL_CELL_BLANK:\n return ''\n else:\n return 'TEXT'\n\n\ndef xlsvalue(cell, nodata=(\"\", \"Na\", \"NaN\", \"-\", \"--\", \"N/A\")):\n \"\"\"\n Type symbol\tType number\tPython value\n XL_CELL_EMPTY\t0\tempty string u''\n XL_CELL_TEXT\t1\ta Unicode string\n XL_CELL_NUMBER\t2\tfloat\n XL_CELL_DATE\t3\tfloat\n XL_CELL_BOOLEAN\t4\tint; 1 means TRUE, 0 means FALSE\n XL_CELL_ERROR\t5\tint representing internal Excel codes; for a text representation, refer to the supplied dictionary error_text_from_code\n XL_CELL_BLANK\t6\tempty string u''. Note: this type will appear only when open_workbook(..., formatting_info=True) is used.\n \"\"\"\n if isarray(cell):\n return [xlsvalue(item, nodata) for item in cell]\n\n cvalue, ctype = cell.value, cell.ctype\n if ctype == xlrd.XL_CELL_EMPTY:\n return None\n elif ctype == xlrd.XL_CELL_TEXT and cvalue in nodata:\n return None\n elif ctype == xlrd.XL_CELL_TEXT and isdate(cvalue.strip()):\n return parseDate(cvalue)\n elif ctype == xlrd.XL_CELL_TEXT and isdatetime(cvalue.strip()):\n return parseDatetime(cvalue)\n elif ctype == xlrd.XL_CELL_TEXT and parseInt(cvalue):\n return parseInt(cvalue)\n elif ctype == xlrd.XL_CELL_TEXT and parseFloat(cvalue.strip()) != None:\n return parseFloat(cvalue)\n elif ctype == xlrd.XL_CELL_TEXT:\n return cvalue\n elif ctype == xlrd.XL_CELL_NUMBER:\n return cvalue\n elif ctype == xlrd.XL_CELL_DATE:\n return ctod(cell)\n elif ctype == xlrd.XL_CELL_BOOLEAN:\n return cvalue\n elif ctype == xlrd.XL_CELL_ERROR:\n return None\n elif ctype == xlrd.XL_CELL_BLANK:\n return None\n else:\n return None\n\n\ndef main():\n pass\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Python27/Lib/site-packages/gecosistema_lite/datatypes.py","file_name":"datatypes.py","file_ext":"py","file_size_in_byte":9441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"116617375","text":"\"\"\"\nhttps://leetcode.com/problems/kth-largest-element-in-a-stream/\n\"\"\"\n\nfrom heapq import (\n heapify,\n heappush,\n heappop,\n heappushpop\n)\n\nclass KthLargest(object):\n def __init__(self, k, nums):\n self.nums = []\n heapify(self.nums)\n for i in range(0, max(len(nums), k)): #Have atleast k elements\n # we fill void to accomodate below input and avoid list index out of range\n # [\"KthLargest\",\"add\",\"add\",\"add\",\"add\",\"add\"]\n # [[1,[]],[-3],[-2],[-4],[0],[4]]\n heappush(self.nums, nums[i] if i= k: #Maintain only k elements\n heappop(self.nums) #removes smallest element\n \n def add(self, val):\n heappushpop(self.nums, val) #Will add k+1 element and remove (k+1)th element, removes small element\n return self.nums[0] # Will always be the kth largest\n \n\n\n# [\"KthLargest\",\"add\",\"add\",\"add\",\"add\",\"add\"]\n# [[3,[4,5,8,2]],[3],[5],[10],[9],[4]]\nk=3\nnums=[4,5,8,2]\nobj = KthLargest(k, nums)\nprint(obj.add(3))\nprint(obj.add(5))\nprint(obj.add(10))\nprint(obj.add(9))\nprint(obj.add(4))","sub_path":"MinHeap/KthLargestInStream.py","file_name":"KthLargestInStream.py","file_ext":"py","file_size_in_byte":1176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"227253942","text":"import pygame, sys\nfrom pygame.locals import *\nimport math\nimport Map\nfrom Map import Hexagon\nfrom Character import Character\nimport Tiles\nimport random\nfrom Menu import GameMenu, StatsScreen\n\nscreenWidth = 1250\nscreenHeight = 1250\n\nteal = (0,128,128)\nwhite = (255,255,255)\nblack = (0,0,0)\nred = (255,0,0)\ngreen = (0,255,0)\nblue = (0,0,255)\n\ncolors = [white, black, red, green, blue]\n\ndef create_stats_screen(location, character):\n pygame.draw.rect(gameDisplay, red, (*location, 300, 400))\n healthLabel = myFont.render(\"Hp: {}\".format(character.hp), 1, white)\n attackLabel = myFont.render(\"Attack: {}\".format(character.attack), 1, white)\n defenseLabel = myFont.render(\"Defense: {}\".format(character.defense), 1, white)\n movementSpeedLabel = myFont.render(\"Movement Speed: {}\".format(character.movementSpeed), 1, white)\n\n x,y = location\n labelCoordinates = [(x, y+ i*20) for i in range(4)]\n labels = [healthLabel, attackLabel, defenseLabel, movementSpeedLabel]\n for label, labelCoordinate in zip(labels, labelCoordinates):\n gameDisplay.blit(label, labelCoordinate)\n\ndef draw_map(map, display):\n display.fill(black)\n def render_tile(tile):\n pygame.draw.polygon(gameDisplay, tile.color, tile.vertices)\n #TODO Check convert alpha and colorkey to ignore the white\n #tileImage = pygame.image.load(tile.tilePic)\n #tileImage.set_colorkey((255,255,255))\n #gameDisplay.blit(tileImage.convert_alpha(),(tile.xPixel - tileImage.get_rect().size[0] / 2, tile.yPixel - tileImage.get_rect().size[1] / 2) )\n if tile.inhabited:\n gameDisplay.blit(tile.character.image.convert_alpha(), (tile.xPixel - tile.character.image.get_rect().size[0] / 2, tile.yPixel - tile.character.image.get_rect().size[1] / 2))\n\n for tile in map.tiles:\n render_tile(tile)\n map.hasChanged = False\n\n\n\npygame.init()\nclock = pygame.time.Clock()\ngameDisplay = pygame.display.set_mode((screenWidth, screenHeight), pygame.RESIZABLE)\n\nmyFont = pygame.font.SysFont(\"freesansbold.ttf\", 20)\n\ncar = Character('racecar.png')\nmario = Character('MarioPixel.png')\nraphael = Character(\"raphael.png\")\n\ngameDisplay.fill(black)\nhexagonMap = Map.map()\nhexagonMap.place_char(car, hexagonMap.tiles[0])\nhexagonMap.place_char(mario, hexagonMap.tiles[1])\nhexagonMap.place_char(raphael, hexagonMap.tiles[2])\n\ndraw_map(hexagonMap, gameDisplay)\n\n\ndef mouseOnWindowOption(mousePosition, openWindows):\n for window in openWindows:\n for optionsBox in window.optionBoxes:\n if optionsBox.x < mousePosition < optionsBox.width and optionsBox.y > mousePosition > optionsBox.height:\n return optionsBox.action()\n\n return None\n\n\n\nopenWindows = set()\n\ndef open_window(window, gameDisplay):\n openWindows.add(window)\n gameDisplay.blit(window, (window.x, window.y))\n\ndef close_window(window):\n openWindows.remove(window)\n draw_map(hexagonMap, gameDisplay)\n\nstatsScreen = StatsScreen(mario, 700, 0, 500, 500)\n\ndef text_objects(text, font):\n textSurface = font.render(text, True, black)\n return textSurface, textSurface.get_rect()\n\n\ndef game_intro():\n pass\n\ncharacterSelected = False\nmovingChar = False\n\n\n\n\nwhile True:\n\n if hexagonMap.hasChanged:\n draw_map(hexagonMap, gameDisplay)\n if openWindows:\n for window in openWindows:\n gameDisplay.blit(window, (window.x,window.y))\n\n for event in pygame.event.get():\n\n if event.type == pygame.MOUSEBUTTONDOWN:\n pos = pygame.mouse.get_pos()\n if mouseOnWindowOption(pos,openWindows):\n mouseOnWindowOption()\n\n\n tileSelected = [hexagon for hexagon in hexagonMap.tiles if (hexagon.xCoord, hexagon.yCoord) == Map.pixel_to_offset(pos)][0] if Map.pixel_to_offset(pos) in Map.map.fullMapCoords else hexagonMap.tiles[0]\n\n if event.button == 1:\n if movingChar:\n movingChar = False\n hexagonMap.move_char(movingFrom, tileSelected)\n\n elif tileSelected.inhabited:\n movingFrom = tileSelected\n movingChar = True\n\n if event.button == 3:\n if tileSelected.inhabited and statsScreen not in openWindows:\n statsScreen.character = tileSelected.character\n open_window(statsScreen, gameDisplay)\n elif statsScreen in openWindows:\n close_window(statsScreen)\n\n\n\n\n\n\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n\n\n pygame.display.update()\n","sub_path":"Game Code.py","file_name":"Game Code.py","file_ext":"py","file_size_in_byte":4580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"195388907","text":"# -*- coding: GBK -*-\n# @Time : 2018/4/18 18:29\n# @Author : 赵聪\n# @Site : \n# @File : UnZipFile.py\n# @Software : PyCharm\n# @Describe : 解压文件\nfrom ScriptLinux import ScriptLinux\n\nclass UnZipFile(object):\n # 通过路径,解压gz文件\n # 1、路径合法性校验:1)路径是文件夹,2)gz文件大于零;文件的更新日期大于上次更新日期;;\n # 2、查看路径下是否有压缩包;\n # 3、如果有解压所有的文件,进行解压,返回成功(Unzip Success),如果没有写日志返回失败;\n # 4、如果异常返回失败(fail);\n\n def handlerGzFile(self, path_name):\n if len(path_name) > 0 and path_name[0] == '/' and path_name[-1] == '/':\n sl = ScriptLinux()\n listGzFiles = sl.getGzListDir(path_name)\n if len(listGzFiles) > 0:\n if sl.gunZipFile(path_name) == 'success':\n return 'Unzip : Success'\n else:\n return 'Unzip : unknown error'\n else:\n return 'Unzip : No Files'\n else:\n return 'Unzip : Not A Folder'\n","sub_path":"src/UnZipFile.py","file_name":"UnZipFile.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"531646879","text":"# В текстовом файле посчитать количество строк, а также для каждой отдельной строки\n# определить количество в ней символов и слов.\n\n\ndef read_for_count(file_name):\n \"\"\"Функция для подсчета количества слов, символов в каждой строке текстового файла,\n функция возвращает кол-во строк и dict{№ : symbol_count, word_count}\"\"\"\n count = 1\n dict_for_return = {}\n with open(file_name, \"r\") as f:\n list_for_count = f.readlines()\n for j in list_for_count:\n dict_for_return[count] = [len(j), len(j.split())]\n count += 1\n string_count = len(dict_for_return)\n return string_count, dict_for_return\n\n\ndef test_read_for_count(file_name):\n \"\"\"сравнивает результыт выполнения read_for_count\n с заложенными внутри функции значениями\"\"\"\n test_string_count = 9\n test_dict = {1: [32, 7], 2: [24, 4], 3: [33, 6], 4: [31, 6], 5: [1, 0], 6: [35, 7], 7: [34, 6], 8: [36, 6], 9: [35, 7]}\n string_count, dict = read_for_count(file_name)\n if string_count == test_string_count and dict == test_dict:\n print(\"Test passed\")\n\n\nif __name__ == \"__main__\":\n my_file_name = \"my_file.txt\"\n string_count, for_count = read_for_count(my_file_name)\n print(\"String count - {}.\".format(string_count))\n for i in for_count:\n print(\"String № {0}: symbol count - {1}, \"\n \"word count {2}\".format(i, for_count.get(i)[0], for_count.get(i)[1]))\n # test_read_for_count(my_file_name)\n","sub_path":"homework/homework_8/task_1/task_1.py","file_name":"task_1.py","file_ext":"py","file_size_in_byte":1705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"501425266","text":"import os\nfrom tkinter import *\nfrom tkinter import ttk\nfrom tkinter import filedialog\n\n\nclass Configuration:\n def __init__(self, parent):\n self.__parent = parent\n self.managaPath = StringVar()\n self.downloadPath = StringVar()\n self.chapterPool = IntVar()\n self.pagePool = IntVar()\n self.__configPath = os.path.dirname(os.path.realpath(__file__))\n self.__confFile = \"%s\\\\%s\" % (self.__configPath, \"config.conf\")\n if os.path.isfile(self.__confFile):\n self.__readConf()\n else:\n handle = open(self.__confFile, \"w\")\n handle.write(\"managaPath=\\n\")\n handle.write(\"downloadPath=\\n\")\n handle.write(\"chapterPool=6\\n\")\n handle.write(\"pagePool=10\\n\")\n handle.close()\n handle = None\n self.__readConf()\n\n if self.managaPath.get() == \"\":\n self.configFrame()\n\n def __readConf(self):\n ctrl = [line.rstrip('\\n') for line in open(self.__confFile)]\n for k in ctrl:\n v = k.split(\"=\")\n if \"managaPath\" in v[0]:\n self.managaPath.set(v[1])\n if \"downloadPath\" in v[0]:\n self.downloadPath.set(v[1])\n if \"chapterPool\" in v[0]:\n self.chapterPool.set(v[1])\n if \"pagePool\" in v[0]:\n self.pagePool.set(v[1])\n\n if not os.path.isdir(self.managaPath.get()):\n self.managaPath.set(\"\")\n\n if not os.path.isdir(self.downloadPath.get()):\n self.downloadPath.set(\"\")\n\n def __saveConfiguration(self):\n handle = open(self.__confFile, \"w\")\n handle.write(\"managaPath=%s\\n\" % self.managaPath.get())\n handle.write(\"downloadPath=%s\\n\" % self.downloadPath.get())\n handle.write(\"chapterPool=%s\\n\" % self.chapterPool.get())\n handle.write(\"pagePool=%s\\n\" % self.pagePool.get())\n handle.close()\n handle = None\n\n def configFrame(self):\n for widget in self.__parent.winfo_children():\n widget.grid_remove()\n\n # Base Configuration\n ttk.Label(self.__parent, text=\"Configuration\", anchor=CENTER, relief=RAISED)\\\n .grid(row=0, column=0, columnspan=3, sticky=(N, W, E))\n\n # Manga Folder\n ttk.Label(self.__parent, text=\"Manga Folder:\", width=20).grid(row=1, column=0, sticky=(N, W))\n ttk.Label(self.__parent, textvariable=self.managaPath, width=40).grid(row=1, column=1, sticky=(N, W))\n ttk.Button(self.__parent, text='Select Folder', command=lambda: self.__askdirectory(self.managaPath))\\\n .grid(row=1, column=2, sticky=(N, E))\n # Download Folder\n ttk.Label(self.__parent, text=\"Download Folder:\", width=20).grid(row=2, column=0, sticky=(N, W))\n ttk.Label(self.__parent, textvariable=self.downloadPath, width=40).grid(row=2, column=1, sticky=(N, W))\n ttk.Button(self.__parent, text='Select Folder', command=lambda: self.__askdirectory(self.downloadPath))\\\n .grid(row=2, column=2, sticky=(N, E))\n\n # Adv Configuration\n # valCmd = (self.__parent.register(self.__validate), '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')\n # ttk.Label(self.__parent, text=\"Advanced\", anchor=CENTER, relief=RAISED)\\\n # .grid(row=3, column=0, columnspan=3, sticky=(N, W, E))\n # ttk.Label(self.__parent, text=\"Chapter Pool:\", width=20).grid(row=4, column=0, sticky=(N, W))\n # Entry(self.__parent, validate = 'key', validatecommand = valCmd, width=4, textvariable=self.chapterPool)\\\n # .grid(row=4, column=1, sticky=(N, W))\n # ttk.Label(self.__parent, text=\"Page Pool:\", width=20).grid(row=5, column=0, sticky=(N, W))\n # Entry(self.__parent, validate = 'key', validatecommand = valCmd, width=4, textvariable=self.pagePool)\\\n # .grid(row=5, column=1, sticky=(N, W))\n\n # Save Config\n ttk.Button(self.__parent, text='Save Configuration', command=self.__saveConfiguration)\\\n .grid(row=99, column=2, sticky=(N, E))\n return\n\n def __askdirectory(self, strvar):\n __dir_opt = options = {}\n if strvar.get() == \"\":\n options['initialdir'] = self.__configPath\n else:\n options['initialdir'] = strvar.get()\n options['mustexist'] = True\n options['parent'] = self.__parent\n options['title'] = 'Select Folder'\n strvar.set(filedialog.askdirectory(**__dir_opt))\n return\n\n def __validate(self, action, index, value_if_allowed, prior_value, text, validation_type, trigger_type, widget_name):\n if text in '0123456789':\n return True\n else:\n return False","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":4707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"241637442","text":"from panda3d.core import *\nfrom pandac.PandaModules import *\nfrom direct.actor.Actor import Actor\nfrom Models3D.BaseModel3D import BaseModel3D\n\nclass StaticModelVenus(BaseModel3D):\n def __init__(self,World, render,base,loader):\n BaseModel3D.__init__(self,World, render,base,loader)\n self.isVenusRotate = False\n\n #Load Venus\n self.orbit_root_venus = render.attachNewNode('orbit_root_venus')\n self.venus = loader.loadModel(\"models/planet_sphere\")\n self.venus_tex = loader.loadTexture(\"models/venus_1k_tex.jpg\")\n self.venus.setTexture(self.venus_tex, 1)\n self.venus.reparentTo(self.orbit_root_venus)\n self.venus.setPos( 10, -20, .8)\n self.venus.setScale(0.923 * 0.6)\n\n self.venusCNode = CollisionNode('venus')\n self.venusCNode.addSolid(CollisionSphere(0, 0, 0.01, 1.5))\n self.venusC = self.venus.attachNewNode(self.venusCNode)\n base.cTrav.addCollider(self.venusC, self.World.pusher)\n self.World.pusher.addCollider(self.venusC, self.venus, base.drive.node())\n\n self.day_period_venus = self.venus.hprInterval((60/365.0)*5, Vec3(360,0,0))\n\n def getVenus(self):\n return self.venus\n\n def rotateVenus(self, task):\n if self.getDistance()<10 and not self.isVenusRotate:\n self.isVenusRotate = True\n self.day_period_venus.loop()\n return task.cont\n\n def stopRotateVenus(self, task):\n if self.getDistance() > 10 and self.isVenusRotate:\n self.isVenusRotate = False\n self.day_period_venus.pause()\n return task.cont\n\n def getDistance(self):\n self.venus.setPos( 10, -20, .8)\n distanceVector = self.World.Character.actor.getPos()-self.venus.getPos()\n for model in self.World.CharacterManager.getCharacters():\n temp = model.actor.getPos()-self.venus.getPos()\n if temp.length() < distanceVector.length():\n distanceVector = temp\n return distanceVector.length()\n","sub_path":"client_side/Models3D/StaticModelVenus.py","file_name":"StaticModelVenus.py","file_ext":"py","file_size_in_byte":2076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"283414854","text":"import os\nimport torch\nimport albumentations as A\nimport albumentations.pytorch as AP\nimport cv2\nfrom tqdm import tqdm\nimport numpy as np\nfrom time import time\n\nfrom models import RetinaFace\nfrom layers.functions.prior_box import PriorBox\nfrom utils.nms.py_cpu_nms import py_cpu_nms\nfrom utils.box_utils import decode\nfrom data.config import cfg_mnet as cfg\n\ntransformerr = A.Compose(\n [\n A.Normalize(),\n AP.ToTensorV2()\n ],\n)\n\ndef transform(img):\n out = transformerr(image=img)\n return out['image']\n\ndef check_keys(model, pretrained_state_dict):\n ckpt_keys = set(pretrained_state_dict.keys())\n model_keys = set(model.state_dict().keys())\n used_pretrained_keys = model_keys & ckpt_keys\n unused_pretrained_keys = ckpt_keys - model_keys\n missing_keys = model_keys - ckpt_keys\n print('Missing keys:{}'.format(len(missing_keys)))\n print('Unused checkpoint keys:{}'.format(len(unused_pretrained_keys)))\n print('Used keys:{}'.format(len(used_pretrained_keys)))\n assert len(used_pretrained_keys) > 0, 'load NONE from pretrained checkpoint'\n return True\n\n\ndef remove_prefix(state_dict, prefix):\n ''' Old style model is stored with all names of parameters sharing common prefix 'module.' '''\n print('remove prefix \\'{}\\''.format(prefix))\n f = lambda x: x.split(prefix, 1)[-1] if x.startswith(prefix) else x\n return {f(key): value for key, value in state_dict.items()}\n\ndef load_model(model, pretrained_path, load_to_cpu):\n print('Loading pretrained model from {}'.format(pretrained_path))\n if load_to_cpu:\n print('Load to cpu')\n pretrained_dict = torch.load(pretrained_path, map_location=lambda storage, loc: storage)\n else:\n device = torch.cuda.current_device()\n pretrained_dict = torch.load(pretrained_path, map_location=lambda storage, loc: storage.cuda(device))\n state_dict = pretrained_dict['state_dict']\n # state_dict = model.filter_state_dict_with_prefix(state_dict, 'student_model.model', True)\n print(state_dict.keys())\n model.migrate(state_dict, force=True)\n return model\n\n# def load_model(model, pretrained_path, device='cuda'):\n# print('Loading pretrained model from {}'.format(pretrained_path))\n# if device == 'cpu':\n# print('load to cpu')\n# pretrained_dict = torch.load(pretrained_path, map_location=lambda storage, loc: storage)\n# else:\n# device = torch.cuda.current_device()\n# pretrained_dict = torch.load(pretrained_path, map_location=lambda storage, loc: storage.cuda(device))\n# if \"state_dict\" in pretrained_dict.keys():\n# pretrained_dict = remove_prefix(pretrained_dict['state_dict'], 'module.')\n# else:\n# pretrained_dict = remove_prefix(pretrained_dict, 'module.')\n# check_keys(model, pretrained_dict)\n# model.load_state_dict(pretrained_dict, strict=False)\n# return model\n\ndevice = 'cpu'\npriorbox = PriorBox(cfg, image_size=(96, 96))\npriors = priorbox.forward()\npriors = priors.to(device)\nprior_data = priors.data\n\ndef calculate_box(loc, conf):\n scores = conf[:, 1]\n ind = scores.argmax()\n boxes = decode(loc, prior_data, cfg['variance'])\n scores = scores[ind:ind+1]\n boxes = boxes[ind:ind+1]\n dets = np.hstack((boxes, scores[:, np.newaxis])).astype(np.float32, copy=False)\n return dets\n\ndef detect_iris(img, net):\n img = transform(img).unsqueeze(0)\n img = img.to(device)\n loc, conf = net(img) # forward pass\n loc = loc.squeeze(0).data.cpu()\n conf = conf.squeeze(0).data.cpu().numpy()\n split_index = loc.shape[0] // 2\n loc_left, loc_right = loc[:split_index], loc[split_index:]\n conf_left, conf_right = conf[:split_index], conf[split_index:]\n return calculate_box(loc_left, conf_left), calculate_box(loc_right, conf_right)\n\n# def detect_iris(img, net):\n# img = transform(img).unsqueeze(0)\n# img = img.to(device)\n\n# loc, conf = net(img) # forward pass\n\n# scores = conf.squeeze(0).data.cpu().numpy()[:, 1]\n# ind = scores.argmax()\n\n# boxes = decode(loc.data.squeeze(0), prior_data, cfg['variance'])\n# boxes = boxes.cpu().numpy()\n# scores = scores[ind:ind+1]\n# boxes = boxes[ind:ind+1]\n\n# dets = np.hstack((boxes, scores[:, np.newaxis])).astype(np.float32, copy=False)\n\n# return dets\n\n\ndef filter_iris_box(dets, threshold):\n widths = dets[:, 2] - dets[:, 0]\n heights = dets[:, 3] - dets[:, 1]\n mask = (heights / widths) > threshold\n dets = dets[mask]\n return dets\n\n\ndef filter_conf(dets, threshold):\n return dets[dets[:, 4] > threshold]\n\ndef paint_bbox(image, bboxes):\n for b in bboxes:\n text = \"{:.4f}\".format(b[4])\n b = list(map(int, b))\n cv2.rectangle(image, (b[0], b[1]), (b[2], b[3]), (0, 0, 255), 2)\n cx = b[0]\n cy = b[1] - 12\n cv2.putText(image, text, (cx, cy),\n cv2.FONT_HERSHEY_DUPLEX, 0.5, (255, 255, 255))\n\nif __name__ == '__main__':\n # net_path = os.path.join('weights_negpos', 'mobilenet0.25_Final.pth')\n # net_path = os.path.join('weights_negpos_cleaned', 'mobilenet0.25_Final.pth')\n # net_path = 'distill_logs/version_0/checkpoints/checkpoint-epoch=52-val_loss=7.4488.ckpt'\n # net_path = 'multi_ratio_prior_box_logs/version_0/checkpoints/checkpoint-epoch=99-val_loss=5.1367.ckpt'\n # net_path = 'test_logs/version_0/checkpoints/checkpoint-epoch=99-val_loss=4.4232.ckpt'\n net_path = 'logs/fpn_logs/version_0/checkpoints/checkpoint-epoch=99-val_loss=4.4232.ckpt'\n net = RetinaFace(cfg=cfg, phase = 'test')\n net = load_model(net, net_path, device)\n # net = net.cuda()\n net.eval()\n # if not os.path.isdir(out_open_image_dir):\n # os.makedirs(out_open_image_dir)\n # label_predict\n open_open = 0\n open_close = 0\n close_open = 0\n close_close = 0\n conf_threshold = 0.80625\n width_height_threshold = 0.4875 \n\n rgb_image_dir = os.path.join('../datasets', 'eyestate_label', 'outputrgb', 'Open')\n out_open_image_dir = os.path.join('../datasets', 'out', 'outputrgb', 'open_open')\n out_close_image_dir = os.path.join('../datasets', 'out', 'outputrgb', 'open_close')\n if not os.path.isdir(out_open_image_dir):\n os.makedirs(out_open_image_dir)\n if not os.path.isdir(out_close_image_dir):\n os.makedirs(out_close_image_dir)\n listdir = os.listdir(rgb_image_dir)\n listdir = listdir[:len(listdir) // 2 * 2]\n for image_file_one, image_file_two in tqdm(zip(listdir[::2], listdir[1::2])):\n image_one = cv2.imread(os.path.join(rgb_image_dir, image_file_one))\n image_two = cv2.imread(os.path.join(rgb_image_dir, image_file_two))\n image = np.concatenate([image_one, image_two], axis=0)\n one_dets, two_dets = detect_iris(image, net)\n one_dets = filter_iris_box(one_dets, width_height_threshold)\n one_dets = filter_conf(one_dets, conf_threshold)\n two_dets = filter_iris_box(one_dets, width_height_threshold)\n two_dets = filter_conf(two_dets, conf_threshold)\n\n if one_dets.shape[0] > 0:\n open_open += 1\n # paint_bbox(image, dets)\n else:\n open_close += 1\n # paint_bbox(image, dets)\n\n if two_dets.shape[0] > 0:\n open_open += 1\n # paint_bbox(image, dets)\n else:\n open_close += 1\n # paint_bbox(image, dets)\n\n rgb_image_dir = os.path.join('../datasets', 'eyestate_label', 'outputrgb', 'Close')\n out_open_image_dir = os.path.join('../datasets', 'out', 'outputrgb', 'close_open')\n out_close_image_dir = os.path.join('../datasets', 'out', 'outputrgb', 'close_close')\n if not os.path.isdir(out_open_image_dir):\n os.makedirs(out_open_image_dir)\n if not os.path.isdir(out_close_image_dir):\n os.makedirs(out_close_image_dir)\n listdir = os.listdir(rgb_image_dir)\n listdir = listdir[:len(listdir) // 2 * 2]\n for image_file_one, image_file_two in tqdm(zip(listdir[::2], listdir[1::2])):\n image_one = cv2.imread(os.path.join(rgb_image_dir, image_file_one))\n image_two = cv2.imread(os.path.join(rgb_image_dir, image_file_two))\n image = np.concatenate([image_one, image_two], axis=0)\n one_dets, two_dets = detect_iris(image, net)\n one_dets = filter_iris_box(one_dets, width_height_threshold)\n one_dets = filter_conf(one_dets, conf_threshold)\n two_dets = filter_iris_box(one_dets, width_height_threshold)\n two_dets = filter_conf(two_dets, conf_threshold)\n\n if one_dets.shape[0] > 0:\n close_open += 1\n # paint_bbox(image, dets)\n else:\n close_close += 1\n # paint_bbox(image, dets)\n\n if two_dets.shape[0] > 0:\n close_open += 1\n # paint_bbox(image, dets)\n else:\n close_close += 1\n # paint_bbox(image, dets)\n print(open_open, open_close, close_open, close_close)\n # print('Accuracy with open: {}'.format(match/total))\n\n\n # rgb_image_dir = os.path.join('../datasets', 'eyestate_label', 'outputir', 'Open')\n # out_open_image_dir = os.path.join('../datasets', 'out', 'outputir', 'open_open')\n # out_close_image_dir = os.path.join('../datasets', 'out', 'outputir', 'open_close')\n # if not os.path.isdir(out_open_image_dir):\n # os.makedirs(out_open_image_dir)\n # if not os.path.isdir(out_close_image_dir):\n # os.makedirs(out_close_image_dir)\n # listdir = os.listdir(rgb_image_dir)\n # for image_file in tqdm(listdir):\n # image = cv2.imread(os.path.join(rgb_image_dir, image_file))\n # dets = detect_iris(image, net)\n # dets = filter_iris_box(dets, width_height_threshold)\n # bboxes = dets[dets[:, 4] > conf_threshold]\n # if bboxes.shape[0] > 0:\n # # print('Predicted Open')\n # open_open += 1\n # paint_bbox(image, dets)\n # # cv2.imwrite(os.path.join(out_open_image_dir, image_file), image)\n # else:\n # # print('Predicted Close')\n # open_close += 1\n # paint_bbox(image, dets)\n # # cv2.imwrite(os.path.join(out_close_image_dir, image_file), image)\n # # paint_bbox(image, dets)\n\n # rgb_image_dir = os.path.join('../datasets', 'eyestate_label', 'outputir', 'Close')\n # out_open_image_dir = os.path.join('../datasets', 'out', 'outputir', 'close_open')\n # out_close_image_dir = os.path.join('../datasets', 'out', 'outputir', 'close_close')\n # if not os.path.isdir(out_open_image_dir):\n # os.makedirs(out_open_image_dir)\n # if not os.path.isdir(out_close_image_dir):\n # os.makedirs(out_close_image_dir)\n # listdir = os.listdir(rgb_image_dir)\n # listdir = os.listdir(rgb_image_dir)\n # for image_file in tqdm(listdir):\n # image = cv2.imread(os.path.join(rgb_image_dir, image_file))\n # dets = detect_iris(image, net)\n # dets = filter_iris_box(dets, width_height_threshold)\n # dets = dets[dets[:, 4] > conf_threshold]\n # if dets.shape[0] > 0:\n # # print('Predicted Open')\n # close_open += 1\n # paint_bbox(image, dets)\n # # cv2.imwrite(os.path.join(out_open_image_dir, image_file), image)\n # else:\n # # print('Predicted Close')\n # close_close += 1\n # # cv2.imwrite(os.path.join(out_close_image_dir, image_file), image)\n # # paint_bbox(image, dets)\n # # cv2.imwrite(os.path.join(out_open_image_dir, image_file), image)\n # print(open_open, open_close, close_open, close_close)\n # # print('Accuracy with open: {}'.format(match/total))\n","sub_path":"benchmark.py","file_name":"benchmark.py","file_ext":"py","file_size_in_byte":11591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"272083132","text":"####\n# Each team's file must define four tokens:\n# team_name: a string\n# strategy_name: a string\n# strategy_description: a string\n# move: A function that returns 'c' or 'b'\n####\n\nteam_name = 'FailSwch-b' # Only 10 chars displayed.\nstrategy_name = 'Switch strategies if last turn failed (b)'\nstrategy_description = 'Switch after being suckered or double betray'\n \ndef move(my_history, their_history, my_score, their_score):\n #collude in first turn\n if len(their_history) == 0:\n return 'b'\n #switch to betray if successfully suckered last turn\n elif my_history[-1]=='c' and their_history[-1]=='b':\n return 'b'\n #switch to collude if both players betrayed last turn\n elif my_history[-1]=='b' and their_history[-1]=='b':\n return 'c'\n #Stay with collude if both players colluded last turn\n elif my_history[-1]=='c' and their_history[-1]=='c':\n return 'c'\n #Stay with betray if betray was successful last turn\n elif my_history[-1]=='b' and their_history[-1]=='c':\n return 'b'","sub_path":"team12.py","file_name":"team12.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"25013704","text":"\"\"\" this module contains fake stations\n\tfor testing purpose\n\"\"\"\n\nfrom floodsystem.station import MonitoringStation\n\n\ndef list_of_fake():\n\t\"\"\"return a list of fake stations\n\n\t\"\"\"\n\n\tA = MonitoringStation(label = \"A\", typical_range = (1, 2), river = \"river1\", town = \"town1\",\n\t\t\t\t\t\t\t\tstation_id = None, measure_id = None, coord = None)\n\tA.latest_level = 2.5\t\n\n\tB = MonitoringStation(label = \"B\", typical_range = (None, 2), river = \"river2\", town = \"town2\",\n\t\t\t\t\t\t\t\tstation_id = None, measure_id = None, coord = None)\t\n\tB.latest_level = 0.9\n\n\tC = MonitoringStation(label = \"C\", typical_range = (4, 2), river = None, town = \"town3\",\n\t\t\t\t\t\t\t\tstation_id = None, measure_id = None, coord = None)\t\n\tC.latest_level = 0.9\n\n\tD = MonitoringStation(label = \"D\", typical_range = None, river = \"river1\", town = \"town4\",\n\t\t\t\t\t\t\t\tstation_id = None, measure_id = None, coord = None)\t\n\tD.latest_level = 0.9\n\n\tE = MonitoringStation(label = \"E\", typical_range = (1, 1), river = \"river1\", town = \"town5\",\n\t\t\t\t\t\t\t\tstation_id = None, measure_id = None, coord = None)\t\n\tE.latest_level = 1.35\n\n\treturn [A, B, C, D, E]\n\t\n","sub_path":"FakeStations.py","file_name":"FakeStations.py","file_ext":"py","file_size_in_byte":1093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"536084419","text":"# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport math\n\nimport torch\nimport torch.nn.functional as F\nfrom fairseq import metrics, utils\nfrom fairseq.criterions import FairseqCriterion, register_criterion\nimport random\n\ndef label_smoothed_nll_loss(lprobs, target, epsilon, ignore_index=None, reduce=True):\n if target.dim() == lprobs.dim() - 1:\n target = target.unsqueeze(-1)\n nll_loss = -lprobs.gather(dim=-1, index=target)\n smooth_loss = -lprobs.sum(dim=-1, keepdim=True)\n if ignore_index is not None:\n pad_mask = target.eq(ignore_index)\n nll_loss.masked_fill_(pad_mask, 0.)\n smooth_loss.masked_fill_(pad_mask, 0.)\n else:\n nll_loss = nll_loss.squeeze(-1)\n smooth_loss = smooth_loss.squeeze(-1)\n if reduce:\n nll_loss = nll_loss.sum()\n smooth_loss = smooth_loss.sum()\n eps_i = epsilon / lprobs.size(-1)\n loss = (1. - epsilon) * nll_loss + eps_i * smooth_loss\n return loss, nll_loss\n\n\n@register_criterion('cross_entropy_dirty_s')\nclass CrossEntropyDirtyS(FairseqCriterion):\n\n def __init__(self, task, sentence_avg, label_smoothing,threshold,sensword):\n super().__init__(task)\n self.sentence_avg = sentence_avg\n self.eps = label_smoothing\n self.threshold = threshold\n self.sensword = sensword\n\n @staticmethod\n def add_args(parser):\n \"\"\"Add criterion-specific arguments to the parser.\"\"\"\n # fmt: off\n parser.add_argument('--label-smoothing', default=0., type=float, metavar='D',\n help='epsilon for label smoothing, 0 means no label smoothing')\n parser.add_argument('--threshold', default=1.2, type=float, metavar='D',\n help='the threshold of dirty sentences')\n parser.add_argument('--sensword', default='sentence', type=str, metavar='D',\n help='the threshold of dirty sentences')\n # fmt: on\n\n def forward(self, model, sample, reduce=True):\n \"\"\"Compute the loss for the given sample.\n\n Returns a tuple with three elements:\n 1) the loss\n 2) the sample size, which is used as the denominator for the gradient\n 3) logging outputs to display while training\n \"\"\"\n\n if model.training:\n with torch.no_grad():\n ss = self.task.source_dictionary.encode_line(\n '你 真 漂亮', \n add_if_not_exist=False\n ).long().to(sample['net_input']['prev_output_tokens'])\n ss_len = torch.tensor([len(ss)]).long().to(sample['net_input']['prev_output_tokens'])\n xx = self.task.target_dictionary.encode_line(\n \"you are so beautiful .\", \n add_if_not_exist=False\n ).long().to(sample['net_input']['prev_output_tokens'])\n sample['target'] = torch.cat(tuple(xx[None,:] for i in range(10)),0).to(xx)\n xx[0],xx[1:] = 2, xx[:-1].clone()\n \n sample['net_input']['src_tokens'] = torch.cat(tuple(ss[None,:] for i in range(10)),0).to(ss)\n sample['net_input']['src_lengths'] = torch.cat(tuple(ss_len for i in range(10)),0).to(ss_len)\n sample['net_input']['prev_output_tokens'] = torch.cat(tuple(xx[None,:] for i in range(10)),0).to(xx)\n\n # print(xx)\n # print(sample['net_input'].keys())\n # print(sample['net_input']['prev_output_tokens'][0])\n # print(self.task.target_dictionary.string(sample['net_input']['prev_output_tokens'][0]))\n # print(sample['net_input']['prev_output_tokens'].shape)\n # print(sample['target'][0])\n # print(sample['target'].shape)\n # assert False\n noised_logits, noised_extra = model(**sample[\"net_input\"])\n input_logits, extra = model(**sample['net_input'])\n input_logits1, extra1 = model(**sample['net_input'])\n b,s = input_logits.shape[:2]\n mask_dirty = torch.ones(b,s).to(input_logits)\n\n for i in range(noised_logits.shape[0]):\n if self.sensword == 'sentence':\n print(1),\n\n elif self.sensword == 'word':\n klkl = self._get_symm_kl_except_first(noised_logits[i,:,:],input_logits[i,:,:],input_logits1[i,:,:])\n\n if klkl.data>self.threshold:\n mask_dirty[i,:] = 0\n\n klkl = self._get_symm_kl_list(noised_logits[i,:,:],input_logits[i,:,:])\n kl_res = klkl.sum(-1)\n print(kl_res,kl_res.sum() / noised_logits.size(1))\n\n mask_dirty[i] = (kl_res < 3).float()\n klkl = klkl.sum()\n\n\n src_token = sample['net_input']['src_tokens'][i]\n src_str = self.task.source_dictionary.string(src_token)\n\n tgt_token = sample['target'][i]\n tgt_str = self.task.target_dictionary.string(tgt_token)\n\n if mask_dirty[i].min() == 0:\n print(src_str)\n print(tgt_str)\n # print(mask_dirty[i])\n tgt_l = tgt_str.split(' ')\n ss = ''\n for i,j in zip(tgt_l,mask_dirty[i][:-1]):\n if j == 0:\n ss += ' --'+ i +'--'\n else:\n ss += ' '+i\n print(ss)\n\n # print(mask_dirty)\n # print(self.threshold)\n input_logits = mask_dirty[:,:,None] * input_logits\n\n assert False\n loss, nll_loss = self.compute_loss(model, (input_logits, extra), sample, reduce=reduce)\n sample_size = sample['target'].size(0) if self.sentence_avg else sample['ntokens']\n logging_output = {\n 'loss': loss.data,\n 'nll_loss': nll_loss.data,\n 'ntokens': sample['ntokens'],\n 'nsentences': sample['target'].size(0),\n 'sample_size': sample_size,\n }\n return loss, sample_size, logging_output\n\n def _get_symm_kl_except_first(self,noised_logits:torch.Tensor, input_logits:torch.Tensor,input_logits1:torch.Tensor):\n word_num = noised_logits.size(0) - 1\n klkl0 = self._get_symm_kl_list(noised_logits,input_logits)\n klkl0 = klkl0[1:,:].sum().data / word_num\n print('sentence1',klkl0)\n klkl1 = self._get_symm_kl_list(noised_logits,input_logits1)\n klkl1 = klkl1[1:,:].sum().data / word_num\n print('sentence1',klkl1)\n klkl2 = self._get_symm_kl_list(input_logits,input_logits1)\n klkl2 = klkl2[1:,:].sum().data / word_num\n print('sentence1',klkl2)\n print('sentence1',(klkl2+klkl0+klkl1)/3)\n return (klkl2+klkl0+klkl1)/3\n\n\n\n def _get_symm_kl_list(self, noised_logits:torch.Tensor, input_logits:torch.Tensor):\n # noised_logits, logits_index = noised_logits.topk(25,-1)\n # input_logits = input_logits.gather(1,logits_index)\n\n # input_logits = input_logits.topk(1000,-1)[0]\n\n return (\n F.kl_div(\n F.log_softmax(noised_logits, dim=-1, dtype=torch.float32),\n F.softmax(input_logits, dim=-1, dtype=torch.float32),\n None,\n False,\n None\n )\n + F.kl_div(\n F.log_softmax(input_logits, dim=-1, dtype=torch.float32),\n F.softmax(noised_logits, dim=-1, dtype=torch.float32),\n None,\n False,\n None\n )\n ) \n\n def _get_symm_kl(self, noised_logits, input_logits):\n # print(noised_logits.shape,input_logits.shape)\n return (\n F.kl_div(\n F.log_softmax(noised_logits, dim=-1, dtype=torch.float32),\n F.softmax(input_logits, dim=-1, dtype=torch.float32),\n None,\n None,\n \"sum\"\n )\n + F.kl_div(\n F.log_softmax(input_logits, dim=-1, dtype=torch.float32),\n F.softmax(noised_logits, dim=-1, dtype=torch.float32),\n None,\n None,\n \"sum\"\n )\n ) / noised_logits.size(0)\n\n def compute_loss(self, model, net_output, sample, reduce=True):\n lprobs = model.get_normalized_probs(net_output, log_probs=True)\n lprobs = lprobs.view(-1, lprobs.size(-1))\n target = model.get_targets(sample, net_output).view(-1, 1)\n loss, nll_loss = label_smoothed_nll_loss(\n lprobs, target, self.eps, ignore_index=self.padding_idx, reduce=reduce,\n )\n return loss, nll_loss\n\n @staticmethod\n def reduce_metrics(logging_outputs) -> None:\n \"\"\"Aggregate logging outputs from data parallel training.\"\"\"\n loss_sum = sum(log.get('loss', 0) for log in logging_outputs)\n nll_loss_sum = sum(log.get('nll_loss', 0) for log in logging_outputs)\n ntokens = sum(log.get('ntokens', 0) for log in logging_outputs)\n sample_size = sum(log.get('sample_size', 0) for log in logging_outputs)\n\n metrics.log_scalar('loss', loss_sum / sample_size / math.log(2), sample_size, round=3)\n metrics.log_scalar('nll_loss', nll_loss_sum / ntokens / math.log(2), ntokens, round=3)\n metrics.log_derived('ppl', lambda meters: utils.get_perplexity(meters['nll_loss'].avg))\n\n @staticmethod\n def logging_outputs_can_be_summed() -> bool:\n \"\"\"\n Whether the logging outputs returned by `forward` can be summed\n across workers prior to calling `reduce_metrics`. Setting this\n to True will improves distributed training speed.\n \"\"\"\n return True\n","sub_path":"fairseq/criterions/drc/dirty_s_personal_sen.py","file_name":"dirty_s_personal_sen.py","file_ext":"py","file_size_in_byte":10068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"443445141","text":"import tkinter, tkinter.constants, tkinter.filedialog\nfrom updated_parser import GetFbId\n\nclass FbParseApp(tkinter.Frame):\n \n def __init__(self, root):\n \n tkinter.Frame.__init__(self, root)\n button_opt = {'fill': tkinter.constants.BOTH, 'padx': 5, 'pady': 5}\n self.inputfile = \"\"\n \n #scroll = Scrollbar(root)\n \n instructions = tkinter.Text(root)\n instructions.insert(tkinter.INSERT, \" This program will take in a .txt file of Facebook URLs, \\n get the user IDs for those profiles, and then write them out \\n to a new .txt file. \\n \\n Before importing a .txt file, ensure that it adheres to these guidelines: \\n 1. There is one Facebook URL per line of the file. \\n 2. Each Facebook URL in the file is valid (preceded by https://www.). \\n 3. File name ends with the '.txt' extension. \\n \\n If your .txt file does not fit these criteria, the program will not run. \\n\\n To start the program, click \\'Get IDs\\' \\n\\n After you choose a .txt file, the program will run. Upon completion, \\n a confirmation box will pop up. \\n\\n Example of a valid Facebook URL: https://www.facebook.com/UserName \\n Make sure all URLs have \\'https://www.' preceding 'facebook.com/UserName' \\n\\n If your file is full of URLs that are missing https:// or www., click on \\n the Fix File button and we'll try to fix it for you.\")\n instructions.pack()\n tkinter.Button(self, text=\"Fix File\", command=self.askopenfilefix).pack(**button_opt)\n tkinter.Button(self, text='Get IDs', command=self.askopenfilename).pack(**button_opt)\n \n # define options for opening or saving a file\n self.file_opt = options = {}\n options['defaultextension'] = '.txt'\n options['filetypes'] = [('all files', '.*'), ('text files', '.txt')]\n options['initialdir'] = 'C:\\\\'\n options['initialfile'] = 'myfile.txt'\n options['parent'] = root\n options['title'] = 'Facebook URL Parser'\n\n # defining options for opening a directory\n self.dir_opt = options = {}\n options['initialdir'] = 'C:\\\\'\n options['mustexist'] = False\n options['parent'] = root\n options['title'] = 'Facebook URL Parser'\n\n def getfilename(self):\n\n \"\"\" Returns a file name from a dialog prompt.\n \"\"\"\n \n filename = tkinter.filedialog.askopenfilename(**self.file_opt)\n return filename\n \n def askopenfilename(self):\n\n \"\"\"Returns an opened file in read mode.\n This time the dialog just returns a filename and the file is opened by your own code.\n \"\"\"\n \n # get filename\n filename = tkinter.filedialog.askopenfilename(**self.file_opt)\n if filename:\n newwin = tkinter.Tk()\n parser = GetFbId(filename)\n validity = parser.verify_file()\n if (validity == None):\n success = tkinter.Text(newwin)\n success.insert(tkinter.INSERT, \"Success. Output will be written to a new .txt file located on the desktop.\")\n success.pack()\n parser.id_parse()\n else:\n invalid = tkinter.Text(newwin)\n invalid.insert(tkinter.INSERT, validity)\n invalid.pack()\n else:\n failwin = tkinter.Tk()\n failure = tkinter.Text(failwin)\n failure.insert(tkinter.INSERT, \"File failed to load. Please reload the program, read the instructions, \\n and try again.\")\n failure.pack()\n\n def askopenfilefix(self):\n \n \"\"\"Opens a file for fixing.\n \"\"\"\n\n filename = tkinter.filedialog.askopenfilename(**self.file_opt)\n if filename:\n newwin = tkinter.Tk()\n parser = GetFbId(filename)\n parser.fix_file()\n success = tkinter.Text(newwin)\n success.insert(tkinter.INSERT, \"Fix attemped. A text file with updated URLs is being saved to your desktop.\")\n success.pack()\n else:\n invalid = tkinter.Text(newwin)\n invalid.insert(tkinter.INSERT, \"Invalid file name\")\n invalid.pack()\n \n \nif __name__=='__main__':\n root = tkinter.Tk()\n root.wm_title(\"Facebook ID Parser\")\n FbParseApp(root).pack()\n root.mainloop()\n","sub_path":"FbParseApp1.1.py","file_name":"FbParseApp1.1.py","file_ext":"py","file_size_in_byte":4309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"543959860","text":"import socket\nimport sys\nimport threading\nimport subprocess\nimport sched\nimport time\nimport os\nimport signal\nfrom subprocess import check_output\nsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n#server_socket = ('192.168.1.138', 5000)\nserver_socket = ((sys.argv[1]), 5000)\n\nsock.bind(server_socket)\n\n\nprocess = None\ncurrentData = ',,'\nsleepT = 1;#measurement will affect the experiment, too much load on the cpu\n\ndef getPid():\n pids = subprocess.check_output(['pidof', 'nginx'])\n o=open(\"pid.txt\",\"a+\")\n o.write(pids)\n o.close() \ndef run_command(i,j):\n global process\n #find process id's of anything running nginx\n pids = subprocess.check_output(['pidof', 'nginx'])\n processes = pids.split()\n for p in range(len(processes)):\n process = (subprocess.Popen('(top -b -n 1 | grep '+str(processes[p])+' | head -1 | awk \\'{print $1 \" \" $7 \" \" $8 \" \" $9}\\') >> '+str(processes[p])+'htop-i'+str(i) +'PI'+str(j) +'.txt',shell=True))\n process = (subprocess.Popen('date +\\\"%T.%3N\\\" >> ' +str(processes[p])+'time'+str(i) +'PI'+str(j)+'.txt',shell=True))\n #time.sleep(sleepT)\n return process\ndef get_data():\n global currentData\n while True:\n data, address = sock.recvfrom(1024)\n currentData = data\ndef run():\n getPid()\n while True:\n AllData = currentData.split(\",\")\n iteration = AllData[2]\n iterationj = AllData[1]\n data = AllData[0]\n #print(data)\n if data == '1':\n run_command(iteration,iterationj)\n time.sleep(1)\n process.kill()\n if data == '2':\n process.kill()\n subprocess.Popen('pkill python', shell=True)\n if data == '3':\n subprocess.Popen('rc-service nginx stop',shell=True)\n print('nginx stopped final on pi1')\n print(\"Closing program\")\n subprocess.Popen('pkill python', shell=True)\n exit()\n\n#add_nginx()\nrunThread = threading.Thread(target = run)\nrunThread.start()\nget_DataThread = threading.Thread(target = get_data)\nget_DataThread.start()\nprint('starting listening thread')\n","sub_path":"DockerTests/data/pi3b+/docker2/0K/pi1/root/local_script.py","file_name":"local_script.py","file_ext":"py","file_size_in_byte":2176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"193306715","text":"import math\nimport numpy as np\n\nBASE = 3\nPRECISION = 5\nL = -3\nU = +3\n# We will represent a floating number as a tuple (mantissa, exponent, sign)\n# With: mantissa -- a list of integers of length PRECISION\n# exponent -- an integer between L and U (inclusive)\n# sign -- either 1 or -1\nexample_float = ([1, 0, 0, 1, 0], 1, 1)\nexample_float2 = ([2, 2, 2, 2, 2], 1, 1)\n\n\ntotal_num_floats = 2*(BASE-1)*math.pow(BASE, PRECISION-1)*(U-L+1)\ndef is_valid_mantissa(int_lst,float_value):\n\n if int_lst[0] == 0 and float_value == 0:\n for x in int_lst[1:]:\n if x >= base or x<1:\n return False\n else:\n for x in int_lst:\n if x >= base or x<1:\n return False\n return True\n\n\n\ndef is_valid_float(float_value):\n\n (mantissa, exponent, sign) = float_value\n return len(mantissa) == PRECISION and is_valid_mantissa(mantissa) and (exponent <= U and exponent >= L) and (sign == 1 or sign == -1)\n\n\nlargest_negative = ([2,2,2,2,2], 3,-1)\nsmallest_positive = ([1,0,0,0,1], -3, 1)\nfloat_32 = ([], None, None)\n\n\ndef to_num(float_value):\n \n (mantissa, exponent, sign) = float_value\n sum_mantissa = 0\n for i in range(len(mantissa)):\n sum_mantissa += mantissa[i] / math.pow(3,i)\n \n return sum_mantissa * math.pow(3,exponent)*sign\n\nprint(math.pow(BASE,L))\n\n\ndef add_float(float1, float2):\n \"\"\"Return a valid floating-point representation of the form (mantissa, exponent, sign)\n that is the sum of `float1` and `float2`. Raises a ValueError if the result of\n the addition is not a valid float.\n 2\n >>> add_float(example_float, example_float)\n ([2, 0, 0, 2, 0], 1, 1])\n \"\"\"\n \n (mantissa1, exponent1, sign1) = float1\n (mantissa2, exponent2, sign2) = float2\n\n\n # You may assume that sign1 and sign2 are positive\n assert (sign1 == 1) and (sign2 == 1)\n max_expo = exponent1\n shift = 0\n if exponent2 > exponent1:\n temp = []\n shift = exponent2 - exponent1\n temp = mantissa1\n mantissa1 = mantissa2\n mantissa2 = temp\n max_expo = exponent2\n else:\n shift = exponent1 - exponent2\n \n if shift >= PRECISION:\n return (mantissa1, max_expo, 1)\n\n #mantissa1 is the mantissa with the higher exponent\n #print(mantissa1)\n #print(mantissa2)\n carry = 0\n i = 0 \n lim = 5 - shift \n res = []\n #print(shift)\n while(i < PRECISION):\n store = 0\n #print('carry is ' + str(carry))\n if i < lim:\n # print(str(mantissa1[PRECISION - 1 - i]) + \"+\" + str(mantissa2[PRECISION-1-i - shift]))\n sums = mantissa1[PRECISION - 1 - i] + mantissa2[PRECISION-1-i - shift] + carry\n carry = sums // BASE\n store = sums%BASE\n else:\n # print('else ' + str(mantissa1[PRECISION - 1 - i])) \n sums = mantissa1[PRECISION - 1 - i] + carry\n carry = sums // BASE\n store = sums%BASE\n res = [store] + res\n #print(res)\n i+=1\n\n if carry > 0 and max_expo >= 3:\n raise ValueError() \n elif carry > 0:\n max_expo += 1\n res = [carry] + res\n res.pop()\n \n\n print(res)\n # Add your code here\n return (res[:5], max_expo, 1)\n\n\n\ndef h1(x, n):\n \"\"\"Returns a list of the first n terms of the Taylor Series expansion of 1/(1-x).\"\"\"\n return [pow(x,i) for i in range(n)]\n\ndef h2(x, n):\n \"\"\"Returns a list of the first n terms of the Taylor Series expansion of e^x.\"\"\"\n return [pow(x,i)/math.factorial(i) for i in range(n)]\n\nns = [20, 40, 60, 80, 100, 120, 140, 160]\nexp_est = [sum(h2(-30,n)) for n in ns]\nexp_est.sort()\nexp_estimates = exp_est\n\ndef z(n):\n a = pow(2.0, n) + 10.0\n b = (pow(2.0, n) + 5.0) + 5.0\n return a - b\n\ndef find_nonzero_z(n):\n result = []\n for i in range(n):\n if z(i) > 0:\n result.append(i)\n return result\n\nnonzero_zn = find_nonzero_z(1024)\n\na = ([0,0,0,0,1], 2, 1) \nb = ([2,2,2,2,2], 2, 1)\nc = ([0,1,0,0,0], 3, 1) \n\nx = add_float(a,b)\ny = add_float(b,c)\n\nprint(add_float(x,c) == add_float(a,y))","sub_path":"hw2.py","file_name":"hw2.py","file_ext":"py","file_size_in_byte":4068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"384128569","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\nimport pandas as pd\r\nimport json\r\n\r\n#Paramétrage des variables\r\nwebsite = \"https://gist.github.com/paulmillr/2657075\"\r\nhead = {'Authorization': 'token {}'.format('4ff5d101d25d4057916fcfeaa3d704041cd591e5')}\r\n\r\n\r\ndef _handle_request_result_and_build_soup(request_result):\r\n if request_result.status_code == 200:\r\n html_doc = request_result.content\r\n soup = BeautifulSoup(html_doc, \"html.parser\")\r\n return soup\r\n\r\n\r\ndef get_top_contributors(url_page):\r\n res = requests.get(url_page)\r\n soup = _handle_request_result_and_build_soup(res)\r\n listcontrib = []\r\n for i in range(1, 257):\r\n number = \"#\" + str(i)\r\n namecontrib = soup.find(text=number).parent.findNext('td').text\r\n listcontrib.append(namecontrib)\r\n return listcontrib\r\n\r\n\r\ndef real_user_name(longname):\r\n position = longname.find(\"(\")\r\n return(longname[:position - 1])\r\n\r\n\r\ndef get_mean_stars_users(listcontrib):\r\n #Initialisation des variables\r\n dico_mean_stars = {}\r\n list_stars_mean = []\r\n #Récupération de la liste formatée des users et insertion dans un dictionnaire\r\n listcontrib_user_name = list(map(real_user_name,listcontrib))\r\n dico_mean_stars[\"login\"] = listcontrib_user_name\r\n #Récupération de la moyenne de stars de tous les repos de chaque user\r\n for i in range(len(listcontrib_user_name)):\r\n sum_stars = 0\r\n mean_stars = 0\r\n get_nbrepo = requests.get(\"https://api.github.com/users/\" + str(listcontrib_user_name[i]), headers=head)\r\n nb_repo = json.loads(get_nbrepo.content).get(\"public_repos\")\r\n # Prise en compte du cas où l'utilisateur n'a pas de repo\r\n if nb_repo == 0:\r\n mean_stars = 0\r\n else:\r\n page = 1\r\n get_repo = requests.get(\"https://api.github.com/users/\" + listcontrib_user_name[i] +\r\n \"/repos?perpage=100&page=\" + str(page), headers=head)\r\n repo_page = json.loads(get_repo.content)\r\n #On cherche à calculaer la somme de tous les stars en prenant en comtpe la pagination\r\n while repo_page != []: #le contenu du get est une liste vide lorsque la page ne contient pas de repos\r\n for j in range(len(repo_page)):\r\n sum_stars += repo_page[j].get(\"stargazers_count\")\r\n page += 1\r\n get_repo = requests.get(\"https://api.github.com/users/\" + listcontrib_user_name[i] +\r\n \"/repos?perpage=100&page=\" + str(page), headers=head)\r\n repo_page = json.loads(get_repo.content)\r\n mean_stars = sum_stars/nb_repo\r\n list_stars_mean.append(mean_stars)\r\n #Mise en place dans le dictionnaire des moyennes de stars de chaque utilisateur\r\n dico_mean_stars[\"mean\"] = list_stars_mean\r\n df_users_stars_mean = pd.DataFrame.from_dict(dico_mean_stars)\r\n print(df_users_stars_mean.sort_values([\"mean\"], ascending=False))\r\n\r\n\r\nlistcontrib = get_top_contributors(website)\r\nget_mean_stars_users(listcontrib)\r\n","sub_path":"crawling_api_github.py","file_name":"crawling_api_github.py","file_ext":"py","file_size_in_byte":3097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"245704445","text":"import random\nimport string\nword = [\"Luke\", \"cat\", \"cool\", \"look!\", \"tools\",\n \"run\", \"code\", \"notes\", \"event\", \"girlfriends\"]\nletters_guess = []\nletters_guess_right = []\nguesses = 0\nguesses_made = []\nguesses_right = []\nrandom_word = random.choice(word)\nplaying = True\nhidden = list(random_word)\n\nfor i in range(len(hidden)):\n if hidden[i] in string.ascii_letters:\n hidden.pop(i)\n hidden.insert(i, \"* \")\n\nwhile guesses_made != 0 and playing:\n letter = input(\"What letter?\")\n if letter in guesses_made:\n print(\"You already guessed this letter\")\n elif letter not in random_word:\n print(\"wrong letter guess another one\")\n guesses -= 1\n guesses_made.append(letter)\n print(\"\" .join(hidden))\n else:\n print(\"Hey look you got it right good for you now guess another!\")\n guesses_right.append(letter)\n guesses_made.append(letter)\n for i in range(len(random_word)):\n if random_word[i].lower() in guesses_right:\n hidden.pop(i)\n hidden.insert(i, random_word[i])\n if list(random_word) == hidden:\n playing = False\nif not playing:\n print(\"Good job you get.................NOTHING\")\nelse:\n print(\"Hey look you won good for you.\")\nprint(\"de word was %s\" % random_word)\n","sub_path":"Brisa Serrano Hangman.py","file_name":"Brisa Serrano Hangman.py","file_ext":"py","file_size_in_byte":1438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"84992731","text":"__author__ = 'prakhardogra'\n\nfrom pymongo import MongoClient\nimport os.path\nimport json\nimport pprint\nfrom download_all import download_both\n\nalltweets = []\n\nfolder_path = \"/home/prakhardogra/PycharmProjects/project4/\"\n\nfilename = os.path.join(folder_path, 'all_tweets.json')\n\ndef get_tweets():\n\n client = MongoClient()\n\n db = client.test3\n\n c = db.tweets1\n\n tweets = c.find({},{\"text\":1,\"_id\":0})\n\n list = []\n hashlist = []\n\n for tweet in tweets:\n for word in tweet[\"text\"].split(\" \"):\n if \"@\" in word: #check for user mention\n if \".\" in word:\n word = word.replace('.','')\n if \":\" in word:\n word = word.replace(':','')\n if \",\" in word:\n word = word.replace(',','')\n if \"'s\" in word:\n word = word.replace(\"'s\",'')\n if \"?\" in word:\n word = word.replace('?','')\n if \")\" in word:\n word = word.replace(')','')\n if word.lower() not in list:\n if \"w/\" not in word:\n list.append(word.lower())\n if \"#\" in word: #check for hashtag\n if \".\" in word:\n word = word.replace('.','')\n if \":\" in word:\n word = word.replace(':','')\n if \",\" in word:\n word = word.replace(',','')\n if \"'s\" in word:\n word = word.replace(\"'s\",'')\n if \"?\" in word:\n word = word.replace('?','')\n if \")\" in word:\n word = word.replace(')','')\n if word.lower() not in list:\n if \"w/\" not in word:\n list.append(word.lower())\n hashlist.append(word.lower())\n\n print (list)\n\n with open(filename, 'w') as f:\n for word in list:\n if \"@\" in word:\n tweets = download_both(word)\n for tweet in tweets:\n if tweet['user']['listed_count'] == 0:\n tweet['user']['listed_count'] = 1\n alltweets.append({\"text\":tweet['text'],\"ratio\":tweet['user']['followers_count']/tweet['user']['listed_count'],\"fac\":tweet['favorite_count'],\"rc\":tweet['retweet_count'],\"hashtags\":tweet['entities']['hashtags']})\n if \"#\" in word:\n\n tweets = download_both(word)\n for tweet in tweets:\n if tweet.user.listed_count == 0:\n tweet.user.listed_count = 1\n alltweets.append({\"text\":tweet.text,\"fac\":tweet.favorite_count,\"ratio\":(tweet.user.followers_count)/(tweet.user.listed_count),\"rc\":tweet.retweet_count,\"hashtags\":hashlist})\n json.dump(alltweets, f)\n\n return list\n","sub_path":"processing_tweets.py","file_name":"processing_tweets.py","file_ext":"py","file_size_in_byte":2940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"31414936","text":"import tensorflow as tf\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nnum_input = 6\nnum_output = 3\nnum_hidden1 = 16\nnum_hidden2 = 16\nk_folds = 10\nN_EPOCHS = 500\n\nCROSS_VALIDATION_ACTIVE = True\n\ngpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.5)\n\nsession = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))\n\nX = tf.placeholder(tf.float32, shape=[None, num_input], name='X')\ny = tf.placeholder(tf.float32, shape=[None, num_output], name='y')\n\n#y_dumb = tf.placeholder(tf.float32, shape=[None, num_output], name='y_dumb')\ndata_csv = pd.read_csv('./out_re.csv')\ndataX = data_csv[['in1','in2','in3','in4','in5','in6']]\ndatay = data_csv[['out1','out2','out3']]\ndata = data_csv[['in1','in2','in3','in4','in5','in6','out1','out2','out3']]\nX_in = []\ny_in = []\n\ndef shuffle_data():\n global data,dataX,datay,X_in,y_in\n data = data.sample(frac=1).reset_index(drop=True)\n dataX = data[['in1','in2','in3','in4','in5','in6']]\n datay = data[['out1','out2','out3']]\n\n X_in_df = dataX.values\n y_in_df = datay.values\n X_in = X_in_df.tolist()\n y_in = y_in_df.tolist()\n\nshuffle_data()\n\nFOLDS_SIZE = len(X_in) // k_folds\n\nrmse_a = []\npred_list = []\n\ndef cost_func(layer, my_y_true):\n ret = tf.sqrt(tf.reduce_mean(tf.square(layer - my_y_true)))\n return ret\n\n\n# Neural Network Structure\ninputs = X\n\n# Input Layer\ninput_layer = inputs\n#input_layer = tf.Variable(inputs)\n\n# Hidden Layer #1\nh1 = tf.layers.dense(inputs=input_layer, \n units=num_hidden1,\n use_bias=True,\n activation=tf.nn.elu)\n \n# Hidden Layer #2\nh2 = tf.layers.dense(inputs=h1, \n units=num_hidden2,\n use_bias=True,\n activation=tf.nn.elu)\n \n# Output Layer\noutput_layer = tf.layers.dense(inputs=h2, \n units=num_output,\n use_bias=True,\n activation=None)\n\ncost = cost_func(output_layer,y)\n#session.run(output_layer)\n#feed_dict_train = {x: X_train,y_true:y_train}\n\noptimizer = tf.train.AdamOptimizer(learning_rate=1e-4).minimize(cost)\nsession.run(tf.global_variables_initializer())\n\ndef train():\n global rmse_a\n\n feed_dict_train = {X: X_train, y:y_train}\n\n \n _, cost_error = session.run([optimizer,cost], feed_dict=feed_dict_train)\n\n rmse_a += [cost_error]\n\ndef predict():\n global pred_list\n feed_dict_test = {X: X_test, y:y_test}\n pred_cost = session.run(cost,feed_dict=feed_dict_test)\n pred_list += [pred_cost]\n print (\"Test Error : \" , pred_cost )\n\n\n\nfor epoch in range(N_EPOCHS):\n print (\"EPOCH :\", epoch+1)\n \n cur_st = 0\n if CROSS_VALIDATION_ACTIVE :\n shuffle_data()\n while True:\n VALIDATION_L = cur_st\n VALIDATION_R = min(cur_st + FOLDS_SIZE,len(X_in))\n #print (VALIDATION_L, VALIDATION_R)\n #print (type(X_in))\n X_train_l = X_in[:VALIDATION_L] + X_in[VALIDATION_R:]\n y_train_l = y_in[:VALIDATION_L] + y_in[VALIDATION_R:]\n X_test_l = X_in[VALIDATION_L:VALIDATION_R]\n y_test_l = y_in[VALIDATION_L:VALIDATION_R]\n #print (\"-->\",len(X_train),len(X_test) )\n\n X_train = np.array(X_train_l)\n y_train = np.array(y_train_l)\n X_test = np.array(X_test_l)\n y_test = np.array(y_test_l)\n\n train()\n predict()\n\n cur_st += FOLDS_SIZE\n if cur_st >= len(X_in):\n break\n else :\n VALIDATION_NUM = (int) (0.2*len(X_in))\n print (VALIDATION_NUM)\n X_train = X_in[:VALIDATION_NUM]\n y_train = y_in[:VALIDATION_NUM]\n X_test = X_in[VALIDATION_NUM:]\n y_test = y_in[VALIDATION_NUM:]\n train()\n predict()\n\nprint (rmse_a[-1])\nprint (pred_list[-1])\nplt.plot(list(enumerate(range(len(rmse_a)))),rmse_a)\n#plt.plot(list(enumerate(range(len(pred_list)))),pred_list)\nplt.show()\n'''\ndef cross_val(k, _X, _y):\n print (_X)\n try:\n if _X.shape[0] != _y.shape[0]:\n raise ValueError('The size of input and output is not the same !',(_X.shape[0],_y.shape[0]))\n except(ValueError):\n exit('Please check the input and output') \n return _X, _y \n\ndef test_my_cross_val():\n print ('oraoraoraora')\n #cross_val(10, X, y)\n#print (dataX.values)\n#cross_val(10, X, y)\n\nfeed_dict = {X : dataX.values, y : datay.values}\n\nsession.run(tf.global_variables_initializer())\n\nsession.run(test_my_cross_val, feed_dict=feed_dict)\n'''\n'''\nfeed_dict = {X : X_in, y : y_in}\nsession.run(tf.global_variables_initializer(), feed_dict=feed_dict)\n'''","sub_path":"testing_ground/pred/cross_validation_gpu.py","file_name":"cross_validation_gpu.py","file_ext":"py","file_size_in_byte":4643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"492824292","text":"__author__ = 'Joe'\n\nfrom appJar import gui\nimport random\n\ndef recipeGUI(a_list, selected_items):\n ### Load data\n all_recipes ={}\n for item in a_list:\n all_recipes[item] = False\n\n suggest_recipes = all_recipes.copy()\n menu_recipes = {}\n rand_suggestion = random.choice(list(suggest_recipes))\n\n ### Configure\n app_title = \"Menu Builder\"\n\n section_1_title=\"All Recepies\"\n section_2_title=\"Random Suggestion\"\n section_3_title=\"Current Menu\"\n\n button_name_add_selected = \"Add Selected\"\n button_name_new_selection = \"New Suggestion\"\n button_name_add_selection = \"Add Suggestion\"\n button_name_no_save_quit = \"Quit\"\n button_name_remove_items = \"Remove Selected\"\n button_name_save_quit = \"Save and Quit\"\n button_7 = \"b7\"\n button_8 = \"b8\"\n\n ### debug constants\n # rand_suggestion = \"poo\"\n\n ### Function defs\n def press(button):\n if button == button_name_add_selected:\n add_selected_button_action()\n elif button == button_name_new_selection:\n new_suggest_button_action()\n elif button == button_name_add_selection:\n add_suggestion_button_action()\n elif button == button_name_no_save_quit:\n no_save_quit_button_action()\n elif button == button_name_remove_items:\n remove_items_button_action()\n elif button == button_name_save_quit:\n save_quit_button_action()\n elif button == button_7:\n print(button)\n elif button == button_8:\n print(button)\n else:\n print(button+\" is not a recognised button\")\n app.stop()\n\n\n ###\n def new_suggest_button_action():\n rand_sug = random.choice(list(suggest_recipes))\n app.setLabel(section_2_title, rand_sug)\n\n\n def add_suggestion_button_action():\n rand_suggestion = app.getLabel(section_2_title)\n app.setProperty(section_3_title, rand_suggestion)\n\n\n def remove_items_button_action():\n current_menu = app.getProperties(section_3_title)\n for item in current_menu:\n if current_menu[item]:\n app.deleteProperty(section_3_title, item)\n\n\n def add_selected_button_action():\n all_rec = app.getProperties(section_1_title)\n for item in all_rec:\n if all_rec[item]:\n app.setProperty(section_3_title, item)\n app.setProperty(section_1_title, item, False)\n\n def no_save_quit_button_action():\n app.stop()\n\n def save_quit_button_action():\n nonlocal selected_items\n for i in list(app.getProperties(section_3_title)):\n selected_items.append(i)\n app.stop()\n\n\n ### initialization look and feel\n app = gui()\n app.setBg(\"lightBlue\")\n app.setFont(12)\n\n ### add widgets\n # title\n app.addLabel(\"title\", app_title, 0, 0,)\n app.setLabelBg(\"title\", \"orange\")\n app.addButton(button_name_no_save_quit, press, 4,0)\n app.addButton(button_name_save_quit, press, 4,2)\n\n # select recipe panel\n app.startScrollPane(\"Pane1\", 1, 0)\n app.addProperties(section_1_title, all_recipes)\n app.stopScrollPane()\n app.addButton(button_name_add_selected, press, 2,0)\n\n # random suggestion panel\n app.addLabel(section_2_title, rand_suggestion, 1, 1,)\n app.setLabelBg(section_2_title, \"orange\")\n app.addButtons([button_name_new_selection, button_name_add_selection], press, 2,1)\n\n # current selection panel\n app.addProperties(section_3_title, menu_recipes, 1,2)\n app.addButton(button_name_remove_items, press, 2,2)\n\n ### go\n app.go()\n\nif __name__ == \"__main__\":\n all_recipes = [\"Cheese\", \"Tomato\", \"Bacon\", \"Corn\", \"Mushroom\"]\n selected = []\n recipeGUI(all_recipes, selected)\n print(selected)\n\n","sub_path":"src/grocery_gui.py","file_name":"grocery_gui.py","file_ext":"py","file_size_in_byte":3771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"484219903","text":"from __future__ import print_function, division \nimport sys\nimport math\nimport heapq\nimport random \nimport numpy as np \nimport matplotlib.pyplot as plt\nsys.dont_write_bytecode = True\n\n# import main_no_prune as main\nimport main\nimport node \n# import univ\nimport utils \nimport obstacles as obs\n\n\ndef getRandomNode(x_lim, y_lim, curr_node, goal_node, goal_probability=0.5):\n\tprob = np.random.sample()\n\t\n\t# exploration\n\tif prob > goal_probability:\n\t\tx_lim_low, x_lim_high = x_lim\n\t\ty_lim_low, y_lim_high = y_lim\n\t\n\t# heading towards to goal\n\telse:\n\t\tgn_x, gn_y = goal_node.getXYCoords()\n\t\tcn_x, cn_y = curr_node.getXYCoords()\n\n\t\tif (gn_y - cn_y) > 0:\n\t\t\ty_lim_low = cn_y\n\t\t\ty_lim_high = gn_y + ((y_lim[1] - gn_y) / 3)\n\t\telse:\n\t\t\ty_lim_low = gn_y - ((gn_y - y_lim[0]) / 3)\n\t\t\ty_lim_high = cn_y\n\n\t\tif (gn_x - cn_x) > 0:\n\t\t\tx_lim_low = cn_x\n\t\t\tx_lim_high = gn_x + ((x_lim[1] - gn_x) / 3)\n\t\telse:\n\t\t\tx_lim_low = gn_x - ((gn_x - x_lim[0]) / 3)\n\t\t\tx_lim_high = cn_x\n\n\trn_x = np.random.uniform(low=x_lim_low, high=x_lim_high)\n\trn_y = np.random.uniform(low=y_lim_low, high=y_lim_high)\n\n\treturn node.Node(current_coords=(rn_x, rn_y), parent_coords=None, distance=0)\n\n\ndef getStepNode(closest_node, rand_node, step_size):\n\t# dist = utils.euclideanDistance(point_1=closest_node.getXYCoords(), point_2=rand_node.getXYCoords())\n\n\tcn_x, cn_y = closest_node.getXYCoords()\n\trn_x, rn_y = rand_node.getXYCoords()\n\n\t# slope = (rn_y - cn_y) / (rn_x - cn_x)\n\ttheta = np.arctan2((rn_y - cn_y), (rn_x - cn_x))\n\n\t# intercept = cn_y - (slope * cn_x)\n\n\tsn_x = cn_x + (step_size * np.cos(theta))\n\tsn_y = cn_y + (step_size * np.sin(theta))\n\n\treturn node.Node(current_coords=(sn_x, sn_y), parent_coords=(cn_x, cn_y), distance=step_size)\n\n\ndef hitsObstacle(start_node, goal_node, step_size=0.1):\n\tsn_x, sn_y = start_node.getXYCoords()\n\tgn_x, gn_y = goal_node.getXYCoords()\n\n\ttheta = np.arctan2((gn_y - sn_y), (gn_x - sn_x))\n\n\tnn_x, nn_y = sn_x, sn_y\n\twhile (utils.euclideanDistance(point_1=(nn_x, nn_y), point_2=(gn_x, gn_y)) > 0.001):\n\t\t# next node\n\t\tnn_x = nn_x + (step_size * np.cos(theta))\n\t\tnn_y = nn_y + (step_size * np.sin(theta))\n\n\t\tif obs.withinObstacleSpace(point=(nn_x, nn_y), radius=main.DRONE_RADIUS, clearance=main.DRONE_RADIUS / 2):\n\t\t\treturn True\n\n\treturn False\n\n\ndef findClosestNode(rrt_nodes, rand_node):\n\tclosest_dist = 99999\n\tclosest_node = None\n\n\tfor rrt_node in rrt_nodes:\n\t\tnode_dist = utils.euclideanDistance(point_1=rrt_node.getXYCoords(), point_2=rand_node.getXYCoords())\n\n\t\tif node_dist < closest_dist:\n\t\t\tclosest_dist = node_dist\n\t\t\tclosest_node = rrt_node\n\n\treturn (closest_node, closest_dist)\n\n\ndef backtrack(rrt_nodes, goal_node):\n\tpath = []\n\n\ttemp_node = goal_node\n\twhile (temp_node.parent_coords is not None):\n\t\tpath.insert(0, temp_node)\n\t\ttemp_node = rrt_nodes[temp_node.parent_coords]\n\n\tpath.insert(0, temp_node)\n\n\treturn path\n\n\ndef prunePath(path_list):\n\tpass","sub_path":"Code/rrt.py","file_name":"rrt.py","file_ext":"py","file_size_in_byte":2861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"220949921","text":"from django.contrib.auth import get_user_model\nfrom django.urls import reverse\nfrom django.test import TestCase\n\nfrom rest_framework import status\nfrom rest_framework.test import APIClient\n\nfrom core.models import Aspect\n\nfrom dictionary.serializers import AspectSerializer\n\nASPECT_URL = reverse('dictionary:aspect-list')\n\n\ndef detail_url(aspect_id):\n \"\"\"Return aspect detail URL\"\"\"\n return reverse('dictionary:aspect-detail', args=[aspect_id])\n\n\ndef sample_aspect(name='vulg'):\n \"\"\"Create and return sample aspect\"\"\"\n return Aspect.objects.create(name=name)\n\n\nclass PublicAspectApiTest(TestCase):\n \"\"\"Test unauthenticated Aspect API access\"\"\"\n\n def setUp(self):\n self.client = APIClient()\n\n def test_auth_not_required(self):\n \"\"\"Test that authentication is not required for GET method\"\"\"\n res = self.client.get(ASPECT_URL)\n\n self.assertEqual(res.status_code, status.HTTP_200_OK)\n\n def test_retrieve_aspect(self):\n \"\"\"Test retrieving a list of aspects\"\"\"\n sample_aspect(name='dok')\n sample_aspect(name='not')\n\n res = self.client.get(ASPECT_URL)\n\n asp = Aspect.objects.all().order_by('-name')\n serializer = AspectSerializer(asp, many=True)\n self.assertEqual(res.status_code, status.HTTP_200_OK)\n self.assertEqual(res.data, serializer.data)\n\n def test_view_aspect_detail(self):\n \"\"\"Test viewing a aspect detail\"\"\"\n asp = sample_aspect(name='ksiaz')\n\n url = detail_url(asp.id)\n res = self.client.get(url)\n\n serializer = AspectSerializer(asp)\n self.assertEqual(res.data, serializer.data)\n\n\nclass PrivateAspectApiTest(TestCase):\n \"\"\"Test the authorized user Aspect API\"\"\"\n\n def setUp(self):\n self.user = get_user_model().objects.create_user(\n 'test@test.pl',\n 'pass1234'\n )\n self.client = APIClient()\n self.client.force_authenticate(self.user)\n\n def test_create_aspect_successful(self):\n \"\"\"Test create a new aspect\"\"\"\n payload = {'name': 'vulg'}\n self.client.post(ASPECT_URL, payload)\n\n exists = Aspect.objects.filter(\n name=payload['name']\n ).exists()\n self.assertTrue(exists)\n\n def test_partial_update_aspect(self):\n \"\"\"Test update a aspect with patch\"\"\"\n asp = sample_aspect(name='reg')\n\n payload = {\n 'name': 'vulg',\n }\n\n url = detail_url(asp.id)\n self.client.patch(url, payload)\n\n asp.refresh_from_db()\n self.assertEqual(asp.name, payload['name'])\n\n def test_full_update_aspect(self):\n \"\"\"Test updating a aspect with put\"\"\"\n asp = sample_aspect(name='not')\n\n payload = {\n 'name': 'yes',\n }\n\n url = detail_url(asp.id)\n self.client.put(url, payload)\n\n asp.refresh_from_db()\n self.assertEqual(asp.name, payload['name'])\n","sub_path":"app/dictionary/tests/test_aspect.py","file_name":"test_aspect.py","file_ext":"py","file_size_in_byte":2923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"583033534","text":"#! /usr/bin/env python\r\n#coding=utf-8\r\n\r\nfrom _widget import QTextDocument, QWidget, QHBoxLayout, QPlainTextEdit, QTextEdit\r\nfrom _widget import QFile, QTextStream, QApplication, Qt, QColor, QTextFormat\r\nfrom _widget import QPainter, QSize, QPoint, QRect\r\n\r\nfrom syntax_highlighter import SyntaxHighlighter\r\n\r\nclass TextDocument(QTextDocument):\r\n\t\r\n\tdef __init__(self, parent=None):\r\n\t\tsuper(TextDocument, self).__init__(parent)\r\n\r\n\t\tself.setHtml(\"text \")\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef get_mouse_position_block(self, mouse_y):\r\n\tblock = self.firstVisibleBlock()\r\n\r\n\twhile( block.blockNumber() != -1 and not block.isVisible() ):\r\n\t\tblock = block.next()\r\n\r\n\tif block.blockNumber() == -1 : return block\r\n\r\n\tblock_height = self.blockBoundRect(self).height()\r\n\tblock_num = mouse_y / block_height + 1\r\n\r\n\tif block_num <= self.blockCount():\r\n\t\ti = 1\r\n\t\twhile i < block_num:\r\n\t\t\tif block.blockNumber() == -1 : return block\r\n\t\t\tif not block.isVisible() : i = i - 1\r\n\t\t\tblock = block.next()\r\n\r\n\t\twhile block.blockNumber() != -1 and not block.isVisible():\r\n\t\t\tblock = block.next()\r\n\r\n\treturn block\r\n\r\ndef fold_area_paint_event(self, fold_area, event):\r\n\tpainter = QPainter(fold_area)\r\n\tpainter.fillRect(event.rect(), Qt.black)\r\n\r\n\tif fold_area.mouse_position.x() > 0 and fold_area.mouse_position.x() < 20 :\r\n\t\tblock = get_mouse_position_block(self, fold_area.mouse_position.y() )\r\n\t\tif block.blockNumber() != -1:\r\n\t\t\tif( is_judge_left_bracket(block) ):\r\n\t\t\t\tblock = block.next()\r\n\r\n\r\ndef is_judge_left_bracket(block):\r\n\tif block.next().blockNumber() == -1 : return False\r\n\r\n\tblock = block.next()\r\n\tfor i in xrange(block.text().length()):\r\n\t\tif block.text().at(i) != ' ' and block.text().at(i) != ':' : \r\n\t\t\treturn False\r\n\t\telif block.text().at(i) == '{':\r\n\t\t\treturn True\r\n\t\treturn False\r\n\r\nclass LineNumberAreaWidget(QWidget):\r\n\r\n\tdef __init__(self, parent=None):\r\n\t\tsuper(LineNumberAreaWidget, self).__init__(parent)\r\n\t\tself.editor = parent\r\n\r\n\tdef sizeHint(self):\r\n\t\treturn QSize(self.editor.line_number_area_width(), 0)\r\n\r\n\tdef paintEvent(self,event):\r\n\t\tself.editor.line_number_area_paint_event(self, event)\r\n\r\n\r\nclass FoldAreaWidget(QWidget):\r\n\r\n\tdef __init__(self, parent=None):\r\n\t\tsuper(FoldAreaWidget, self).__init__(parent)\r\n\t\tself.editor = parent\r\n\t\tself.setMouseTracking(True)\r\n\t\tself.mouse_position = QPoint()\r\n\r\n\tdef paintEvent(self, event):\r\n\t\tfold_area_paint_event(self.editor, self, event)\r\n\r\n\tdef leaveEvent(self, event):\r\n\t\tself.mouse_position.setX(-1)\r\n\r\n\tdef mouseMoveEvent(self, event):\r\n\t\tself.mouse_position.setX(event.x())\r\n\t\tself.mouse_position.setY(event.y())\r\n\r\n\r\n\r\nclass PlainTextEditor(QPlainTextEdit):\r\n\r\n\tdef __init__(self, parent=None):\r\n\t\tsuper(PlainTextEditor, self).__init__(parent)\r\n\r\n\t\tself.syntax_highlighter = SyntaxHighlighter(self.document())\r\n\t\tself.line_number_area = LineNumberAreaWidget(self)\r\n\t\t# self.folder_area = FoldAreaWidget(self)\r\n\r\n\t\tself.file_name = None\r\n\t\tself.is_modified = False\r\n\r\n\t\t#self.document = TextDocument(self)\r\n\r\n\t\tself.textChanged.connect(self.text_changed)\r\n\r\n\t\tself.cursorPositionChanged.connect(self.high_light_current_line)\r\n\t\tself.blockCountChanged.connect(self.update_line_number_area_width)\r\n\t\tself.updateRequest.connect(self.update_line_number_area)\r\n\r\n\r\n\r\n\t#########################################################################\r\n\t# for line number area widget\r\n\tdef update_line_number_area_width(self, new_block_count):\r\n\t\tself.setViewportMargins(self.line_number_area_width(), 0, 0, 0)\r\n\r\n\tdef update_line_number_area(self, rect, dy):\r\n\t\tif dy:\r\n\t\t\tself.line_number_area.scroll(0, dy)\r\n\t\telse:\r\n\t\t\tself.line_number_area.update(0, rect.y(), self.line_number_area.width(), rect.height() )\r\n\r\n\t\tif rect.contains(self.viewport().rect()):\r\n\t\t\tself.update_line_number_area_width(0)\r\n\r\n\tdef line_number_area_width(self):\r\n\t\tdigits = 1\r\n\t\tmax_value = max(1, self.blockCount())\r\n\r\n\t\twhile max_value >= 10:\r\n\t\t\tmax_value /= 10\r\n\t\t\tdigits = digits + 1\r\n\r\n\t\tspace = 5 + self.fontMetrics().width('9') * digits\r\n\t\treturn space\r\n\r\n\tdef line_number_area_paint_event(self, line_number_area, event):\r\n\t\tpainter = QPainter(line_number_area)\r\n\r\n\t\tpainter.fillRect(event.rect(), Qt.black)\r\n\r\n\t\tblock = self.firstVisibleBlock()\r\n\t\tblock_number = block.blockNumber()\r\n\t\ttop = self.blockBoundingGeometry(block).translated(self.contentOffset()).top()\r\n\t\tbottom = top + self.blockBoundingGeometry(block).height()\r\n\r\n\t\twhile block.isValid() and (top <= event.rect().bottom() ):\r\n\t\t\tif block.isVisible() and (bottom >= event.rect().top() ):\r\n\t\t\t\tpainter.setPen(Qt.gray)\r\n\t\t\t\tpainter.drawText(0, top, line_number_area.width(), self.fontMetrics().height(),\r\n\t\t\t\t\t\t\t\tQt.AlignRight, '%s' %(block_number+1) )\r\n\r\n\t\t\tblock = block.next()\r\n\t\t\ttop = bottom\r\n\t\t\tbottom = top + self.blockBoundingGeometry(block).height()\r\n\t\t\tblock_number = block_number + 1\r\n\r\n\r\n\t#########################################################################\r\n\tdef load_file(self, file_name):\r\n\t\t# 读取文件内容到系统中\r\n\t\tQApplication.setOverrideCursor(Qt.WaitCursor)\r\n\t\twith file(file_name) as fp:\r\n\t\t\tself.setPlainText(fp.read())\r\n\t\tQApplication.restoreOverrideCursor()\r\n\t\tself.is_modified = False\t\t\t# 注意文档内容修改的时候,会产生一个修改的状态\r\n\r\n\tdef save_file(self, file_name):\r\n\t\tQApplication.setOverrideCursor(Qt.WaitCursor)\r\n\t\twith file(file_name, 'w') as fp:\r\n\t\t\tfp.write(self.toPlainText())\r\n\t\tQApplication.restoreOverrideCursor()\r\n\r\n\r\n\tdef set_file_name(self, file_name):\r\n\t\tif self.file_name != file_name:\r\n\t\t\tself.file_name = file_name\r\n\t\t\tself.load_file(file_name)\r\n\r\n\r\n\tdef text_changed(self):\r\n\t\tself.is_modified = True\r\n\r\n\t\t# 其他高亮显示\r\n\r\n\r\n\tdef search_high_light(self):\r\n\t\tselections = self.extraSelections()\r\n\r\n\r\n\tdef high_light_current_line(self):\r\n\t\textra_selections = []\r\n\t\tif not self.isReadOnly():\r\n\t\t\tselection = QTextEdit.ExtraSelection()\r\n\t\t\tline_color = QColor(Qt.yellow).lighter(160)\r\n\r\n\t\t\tselection.format.setBackground(line_color)\r\n\t\t\tselection.format.setProperty(QTextFormat.FullWidthSelection, True)\r\n\t\t\tselection.cursor = self.textCursor()\r\n\t\t\tselection.cursor.clearSelection()\r\n\r\n\t\t\textra_selections.append(selection)\r\n\r\n\t\tself.setExtraSelections(extra_selections)\r\n\r\n\r\n\t#########################################################################\r\n\tdef resizeEvent(self, event):\r\n\t\tsuper(PlainTextEditor, self).resizeEvent(event)\r\n\r\n\t\trect = self.contentsRect()\r\n\t\tself.line_number_area.setGeometry(QRect(rect.left(), rect.top(), self.line_number_area_width(), rect.height() ))\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"widgets/editor_items/editor.py","file_name":"editor.py","file_ext":"py","file_size_in_byte":6471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"390881458","text":"\"\"\"\n[user, user_avg_item, item]\n\"\"\"\n\nimport torch\nfrom torch import log, unsqueeze\nimport torch.nn as nn\nfrom torch.nn.modules.transformer import TransformerEncoder, TransformerEncoderLayer\nimport torch.nn.utils.rnn as rnn_utils\nimport torch.nn.functional as F\nimport numpy as np\nimport time\n\nclass _ATTR_NETWORK(nn.Module):\n def __init__(self, vocab_obj, args, device):\n super(_ATTR_NETWORK, self).__init__()\n\n self.m_device = device\n \n self.m_vocab_size = vocab_obj.vocab_size\n self.m_user_num = vocab_obj.user_num\n self.m_item_num = vocab_obj.item_num\n\n self.m_attr_embed_size = args.attr_emb_size\n self.m_user_embed_size = args.user_emb_size\n self.m_item_embed_size = args.item_emb_size\n\n self.m_attn_head_num = args.attn_head_num\n self.m_attn_layer_num = args.attn_layer_num\n\n self.m_output_hidden_size = args.output_hidden_size\n\n self.m_attn_linear_size = args.attn_linear_size\n\n # self.m_attr_embedding = nn.Embedding(self.m_vocab_size, self.m_attr_embed_size)\n self.m_user_embedding = nn.Embedding(self.m_user_num, self.m_user_embed_size)\n self.m_item_embedding = nn.Embedding(self.m_item_num, self.m_item_embed_size)\n\n encoder_layers = TransformerEncoderLayer(self.m_attr_embed_size, self.m_attn_head_num, self.m_attn_linear_size)\n self.m_attn = TransformerEncoder(encoder_layers, self.m_attn_layer_num)\n\n self.m_attr_embedding_x = nn.Embedding(self.m_vocab_size, self.m_attr_embed_size)\n # self.m_attr_embedding_x = nn.Embedding(self.m_vocab_size, self.m_attr_embed_size)\n\n self.m_output_attr_embedding_user = nn.Embedding(self.m_vocab_size, self.m_attr_embed_size)\n self.m_output_attr_embedding_item = nn.Embedding(self.m_vocab_size, self.m_attr_embed_size)\n\n self.m_output_attr_embedding_user_x = nn.Embedding(self.m_vocab_size, self.m_attr_embed_size)\n self.m_output_attr_embedding_item_x = nn.Embedding(self.m_vocab_size, self.m_attr_embed_size)\n\n self.f_init_weight()\n\n self = self.to(self.m_device)\n\n def f_init_weight(self):\n initrange = 0.1\n\n torch.nn.init.uniform_(self.m_output_attr_embedding_user.weight, -initrange, initrange)\n\n torch.nn.init.uniform_(self.m_output_attr_embedding_item.weight, -initrange, initrange)\n\n torch.nn.init.uniform_(self.m_output_attr_embedding_user_x.weight, -initrange, initrange)\n\n torch.nn.init.uniform_(self.m_output_attr_embedding_item_x.weight, -initrange, initrange)\n\n torch.nn.init.uniform_(self.m_user_embedding.weight, -initrange, initrange)\n\n torch.nn.init.uniform_(self.m_item_embedding.weight, -initrange, initrange)\n\n def f_generate_mask(self, length):\n max_len = length.max().item()\n # print(\"max_len\", max_len)\n mask = torch.arange(0, max_len).expand(len(length), max_len).to(length.device)\n mask = mask < length.unsqueeze(1)\n\n mask = ~mask\n\n return mask\n\n def f_get_avg_attr(self, attr, attr_lens):\n ### attr_user_embed: batch_size*seq_len*embed_size\n attr_embed = self.m_attr_embedding_x(attr) \n\n attr_mask = self.f_generate_mask(attr_lens)\n attr_mask = ~attr_mask\n attr_mask = attr_mask.unsqueeze(-1)\n\n masked_attr_embed = attr_embed*attr_mask\n\n attr_x = masked_attr_embed.sum(1)/attr_mask.sum(1)\n\n return attr_x\n\n def f_get_avg_attr_user(self, attr_item, item_lens): \n ### attr_user: user_num*item_num*embed_size\n ### item_mask: user_num*item_num\n\n # print(\"attr_item\", attr_item.size())\n # print(\"item_mask\", item_mask.size())\n\n # t0 = time.time()\n\n item_mask = self.f_generate_mask(item_lens)\n item_mask = ~item_mask\n\n attr_user = torch.zeros((*item_mask.size(), attr_item.size(-1)), device=attr_item.device)\n\n # print('step 0 {} seconds'.format(time.time() - t0))\n\n ### item_mask: user_num*item_num\n item_mask = item_mask.bool()\n # item_mask = item_mask.unsqueeze(-1)\n attr_user[item_mask] = attr_item\n\n attr_user = torch.sum(attr_user, dim=1)\n # attr_user = attr_user_mean/torch.sum(item_mask, dim=1, keepdim=True)\n\n # print('avg user {} seconds'.format(time.time() - t0))\n \n return attr_user, item_mask\n\n def f_get_logits(self, embed, attr):\n logits = torch.matmul(embed, attr.unsqueeze(-1))\n logits = logits.squeeze(-1)\n\n return logits\n \n def forward(self, ref_attr_item_user, ref_attr_len_item_user, ref_item_len_user, ref_attr_user_item, ref_attr_len_user_item, ref_user_len_item, user_ids, item_ids, pos_targets, pos_lens, neg_targets, neg_lens):\n\n attr_x_item_user = self.f_get_avg_attr(ref_attr_item_user, ref_attr_len_item_user)\n user_x, user_mask = self.f_get_avg_attr_user(attr_x_item_user, ref_item_len_user)\n\n attr_x_user_item = self.f_get_avg_attr(ref_attr_user_item, ref_attr_len_user_item)\n item_x, item_mask = self.f_get_avg_attr_user(attr_x_user_item, ref_user_len_item)\n\n # x = (user_x+item_x)/torch.sum(user_mask+item_mask, dim=1, keepdim=True)\n\n user_embed = self.m_user_embedding(user_ids) \n item_embed = self.m_item_embedding(item_ids)\n \n neg_attr_embed_user = self.m_output_attr_embedding_user(neg_targets)\n neg_attr_embed_item = self.m_output_attr_embedding_item(neg_targets)\n neg_attr_embed_user_x = self.m_output_attr_embedding_user_x(neg_targets)\n neg_attr_embed_item_x = self.m_output_attr_embedding_item_x(neg_targets)\n\n neg_logits_user = torch.matmul(neg_attr_embed_user, user_embed.unsqueeze(-1))\n neg_logits_user = neg_logits_user.squeeze(-1)\n\n neg_logits_item = torch.matmul(neg_attr_embed_item, item_embed.unsqueeze(-1))\n neg_logits_item = neg_logits_item.squeeze(-1)\n\n neg_logits_user_x = torch.matmul(neg_attr_embed_user_x, user_x.unsqueeze(-1))\n neg_logits_user_x = neg_logits_user_x.squeeze(-1)\n\n neg_logits_item_x = torch.matmul(neg_attr_embed_item_x, item_x.unsqueeze(-1))\n neg_logits_item_x = neg_logits_item_x.squeeze(-1)\n\n neg_logits = neg_logits_user+neg_logits_item+neg_logits_user_x+neg_logits_item_x\n \n neg_mask = self.f_generate_mask(neg_lens)\n neg_mask = ~neg_mask\n\n ### targets: batch_size*pos_num\n ### pos_embed: batch_size*pos_num*embed_size\n\n pos_attr_embed_user = self.m_output_attr_embedding_user(pos_targets)\n pos_attr_embed_item = self.m_output_attr_embedding_item(pos_targets)\n pos_attr_embed_user_x = self.m_output_attr_embedding_user_x(pos_targets)\n pos_attr_embed_item_x = self.m_output_attr_embedding_item_x(pos_targets)\n\n ### user_item_output: batch_size*ouput_size\n ### neg_logits: batch_size*neg_num\n pos_logits_user = torch.matmul(pos_attr_embed_user, user_embed.unsqueeze(-1))\n pos_logits_user = pos_logits_user.squeeze(-1)\n\n pos_logits_item = torch.matmul(pos_attr_embed_item, item_embed.unsqueeze(-1))\n pos_logits_item = pos_logits_item.squeeze(-1)\n\n pos_logits_user_x = torch.matmul(pos_attr_embed_user_x, user_x.unsqueeze(-1))\n pos_logits_user_x = pos_logits_user_x.squeeze(-1)\n\n pos_logits_item_x = torch.matmul(pos_attr_embed_item_x, item_x.unsqueeze(-1))\n pos_logits_item_x = pos_logits_item_x.squeeze(-1)\n \n pos_logits = pos_logits_user+pos_logits_item+pos_logits_user_x+pos_logits_item_x\n\n pos_mask = self.f_generate_mask(pos_lens)\n pos_mask = ~pos_mask\n\n logits = torch.cat([pos_logits, neg_logits], dim=-1)\n\n mask = torch.cat([pos_mask, neg_mask], dim=-1)\n\n new_targets = torch.cat([torch.ones_like(pos_targets), torch.zeros_like(neg_targets)], dim=1)\n\n new_targets = new_targets*mask\n\n return logits, mask, new_targets\n\n def f_eval_forward(self, ref_attr_item_user, ref_attr_len_item_user, ref_item_len_user, ref_attr_user_item, ref_attr_len_user_item, ref_user_len_item, user_ids, item_ids):\n\n ### attr_x_item_user: batch_size*embedding\n attr_x_item_user = self.f_get_avg_attr(ref_attr_item_user, ref_attr_len_item_user)\n user_x, user_mask = self.f_get_avg_attr_user(attr_x_item_user, ref_item_len_user)\n\n attr_x_user_item = self.f_get_avg_attr(ref_attr_user_item, ref_attr_len_user_item)\n item_x, item_mask = self.f_get_avg_attr_user(attr_x_user_item, ref_user_len_item)\n\n # x = (user_x+item_x)/torch.sum(user_mask+item_mask, dim=1, keepdim=True)\n\n user_embed = self.m_user_embedding(user_ids)\n item_embed = self.m_item_embedding(item_ids)\n\n logits_user = torch.matmul(user_embed, self.m_output_attr_embedding_user.weight.t())\n\n logits_item = torch.matmul(item_embed, self.m_output_attr_embedding_item.weight.t())\n\n logits_user_x = torch.matmul(user_x, self.m_output_attr_embedding_user_x.weight.t())\n\n logits_item_x = torch.matmul(item_x, self.m_output_attr_embedding_item_x.weight.t())\n\n logits = logits_user+logits_item+logits_user_x+logits_item_x\n\n return logits","sub_path":"set2set/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":9194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"180326896","text":"## ---------------------------------------------------------------------------\n## Licensed to the Apache Software Foundation (ASF) under one or more\n## contributor license agreements. See the NOTICE file distributed with\n## this work for additional information regarding copyright ownership.\n## The ASF licenses this file to You under the Apache License, Version 2.0\n## (the \"License\"); you may not use this file except in compliance with\n## the License. You may obtain a copy of the License at\n##\n## http://www.apache.org/licenses/LICENSE-2.0\n##\n## Unless required by applicable law or agreed to in writing, software\n## distributed under the License is distributed on an \"AS IS\" BASIS,\n## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n## See the License for the specific language governing permissions and\n## limitations under the License.\n## ---------------------------------------------------------------------------\n\n# Put the 活动行名单.xlsx file in the project root directory,will be generated in the root directory name_split.csv file\n\nimport csv\nimport openpyxl\n\n # First, define a CSV file\nhead =[\"Email\",\"FirstName\",\"LastName\"]\nwith open(\"./name_split.csv\",\"a+\",encoding=\"utf-8\",newline=\"\") as f:\n csvf=csv.writer(f)\n csvf.writerow(head)\n\n\n# Open the EXECL file\ncollect=openpyxl.load_workbook(\"./活动行名单.xlsx\")\n\n# Gets the active table object\ncollect_active=collect.active\n\nfor cell in collect_active['C']:\n if cell.row!=1:\n email=cell.value\n cell_row=cell.row\n name=collect_active.cell(cell_row,2).value\n\n # Judge whether it is a Chinese name\n if '\\u4e00' <= name <='\\u9fff':\n name_list=list(name)\n firstName=name_list[0]\n lastName=\"\"\n for i in name_list[1:]:\n lastName=lastName+i\n else:\n firstName=name\n lastName=\"\"\n\n # Write data to a CSV file\n data=[\n (email,firstName,lastName)\n ]\n with open(\"./name_split.csv\",\"a+\",encoding=\"utf-8\",newline=\"\") as f:\n csvf=csv.writer(f)\n csvf.writerows(data)\n\n ","sub_path":"script/name_split.py","file_name":"name_split.py","file_ext":"py","file_size_in_byte":2098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"620010954","text":"__author__ = 'maury'\n\n\"\"\"\n Esempi di utlizzo delle strutture dati offerte dal Pacchetto Numpy per il calcolo scientifico\n (ndarrays,matrici...) che garantiscono maggiore efficienza nelle operazioni\n\"\"\"\n\nimport numpy as np\nfrom scipy.optimize import curve_fit\n\n\"\"\"\n NDARRAYS - A differenza delle liste gli array di NumPy permettono di memorizzare una sola tipologia di\n elementi per ogni colonna garantendo pero delle prestazioni maggiori quando si deve andare a compiere\n operazioni elemento per elemento (broadcasting)\n\"\"\"\n# Conversione da lista a ndarrays\nlista=[2, 5, 7]\narr=np.array(lista)\nprint(\"\\nLa lista di partenza risulta essere {0} di tipo {2} e l'array risultante convertito invece: {1} di tipo {3}\".format(lista, arr, type(lista), type(arr)))\n\n\"\"\"\n CREAZIONE ARRAYS\n\"\"\"\n# Creazione di un array di 5 elementi con 0.0 di tipo float con precisione di 64 bit\narr=np.zeros(5, dtype=np.float64)\n# Creazione di una matrice 3*3*3 di \"uni\" di tipo float con precisione di 32 bit\narr=np.ones((3, 3, 3)).astype(np.float32)\n# Creazione di una matrice 5*3 di tutti 0.0 di tipo float con precisione di 64 bit\narr=np.zeros((5, 3), dtype=np.float64)\nprint(\"\\nMatrice 5*3 di tutti 0.0: \\n\", arr)\n\n\"\"\"\n ARRAYS di RECORD (Array dove ogni valore invece di essere un elemento di tipo semplice\n risulta essere composto da vari campi)\n\"\"\"\n# Si definisce un array multidimensionale fatto da 2 righe e 3 colonne di tipi differenti di cui si definiscono i campi\nndarray = np.zeros((2,), dtype=[('x', np.int), ('y', np.float64), ('z', str)])\n# Si andranno a specificare ora le colonne con cui andare a riempire le righe di \"ndarray\"\ncol1 = np.arange(2) + 1\ncol2 = np.arange(2)\ncol3 = ['Hello', 'World']\n# Si andra a creare una lista di tuple con valori definiti precedentemente\ntoadd = zip(col1, col2, col3)\nprint(\"\\nLa lista di tuple risulta essere: \", toadd, \" di tipo: \", type(toadd))\n# Assegnazione della lista di tuple al \"ndarray\"\nndarray[:] = toadd\nprint(\"\\nL'array generato sara cosi: \", ndarray, \" di tipo: \", type(ndarray))\n# Creazione definitiva dell'array di record\nrecarr = ndarray.view(np.recarray)\nprint(\"\\nL'array di record generato sara: \", recarr, \" di tipo: \", type(recarr), \" dove il campo int e: \", recarr.x)\n\n\"\"\"\n INDEXING/SLICING\n\"\"\"\nalist = [[1, 2], [3, 4]]\narr = np.array(alist)\nprint(\"\\nL'array risulta essere: \\n\", arr, \"\\ndi tipo: \", type(arr))\nprint(\"\\n1 elemento dell'array e: \", arr[0, 0])\nprint(\"Ultima colonna: \", arr[:, 1])\nprint(\"Ultima riga: \", arr[1, :])\n\n# Individua i valori dall'array a 2 dim che presentano valori>2 recuperandone gli indici\nindex = arr > 2\nprint(\"\\nLista degli indici sotto forma di array dei valori>2: \\n\", index, \"\\ndi tipo: \", type(index))\nprint(\"\\nArray risultante: \", arr[index])\nprint(\"Array contrario: \", arr[~index])\n\n# Creazione di un nuovo array da quello di partenza eliminando i dati indici\n# arr2=np.delete(arr,index)\n# print \"Array derivato da quello di partenza: \",arr2\n\n","sub_path":"numPyProva.py","file_name":"numPyProva.py","file_ext":"py","file_size_in_byte":2957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"563061762","text":"def forecast(country,\n data,\n ftype='poly1',\n samples=10000,\n startdate=None,\n enddate=None,\n limit=0,\n targetdate=None,\n tune=2000,\n chains=20,\n cpu_cores=4,\n return_inis=False,\n **kwargs):\n \n \"\"\"\n do monte carlo fit of posterior (gives also the point max estimate)\n\n :param country: Country name, if there is \"countries\" column in the data - else use \"World or \"\" for all data\n :param data: dataframe with \"dates\" (datetime) and \"cases\" columns - coses is the number of daily new cases\n :param ftype: 'polyN' where N is a number between 0 and a few (don't try more than 10 or so - becomes quite slow)\n or 'exp' for exponential\n :param samples: number of samples to use\n :param startdate: start date of the data to use as datetime.date\n :param enddate: end date of the data to use as datetime.date\n :param limit: take start date to be where cumulative count exceeds limit\n :param targetdate: datetime.date for prediction\n import datetime\n targetdate = datetime.datetime.strptime('2020-06-30','%Y-%m-%d').date()\n :param return_inis: don't run but return initial parameters\n :param **kwargs: model params if wanted to use like intercept=[int_mean,int_std]\n :return: fitresults\n \"\"\"\n \n import pymc3 as pm\n import datetime\n import pandas as pd\n\n from .utils import calculateStats, modelfit_eval_dates\n from .models import poly_model, exp_model, logistic_model\n \n if isinstance(startdate, str):\n startdate = pd.to_datetime(startdate)\n\n if country==\"World\" or country==\"all\" or len(country)==0:\n temp = data.sort_values('dates')\n temp['cases'] = temp.groupby(['dates'])['cases'].transform('sum')\n temp['deaths'] = temp.groupby(['dates'])['deaths'].transform('sum')\n temp.drop_duplicates(subset=['dates'], inplace=True)\n \n else:\n temp = data[data.countries == country].sort_values('dates')\n\n temp['cumcases']=temp.cases.cumsum().values\n if startdate == None:\n startdate = temp[temp.cumcases > limit].dates.dt.date.min()\n\n if enddate == None:\n enddate = temp[temp.cases > 0].dates.dt.date.max()\n \n temp_new = temp[(temp.dates.dt.date>=startdate) & (temp.dates.dt.date<=enddate)]\n intercept = next((value for key, value in kwargs.items() if key == 'intercept'), None)\n if intercept is None:\n intercept = temp_new.cumcases.values.min()\n kwargs['intercept'] = [intercept, intercept / 10 + 20]\n\n try:\n x0 = temp_new.dates.dt.date - startdate\n except:\n x0 = temp_new.dates - startdate\n\n x = x0.dt.days\n y = temp_new.cumcases.values\n\n if targetdate == None:\n xTarget = None\n else:\n xTarget = (targetdate - startdate).days\n\n log = 'lin'\n \n if ftype=='exp':\n slope = next((value for key, value in kwargs.items() if key == 'slope'), None)\n if slope is None:\n a10 = (y.max() - y[0]) / x.max()\n kwargs['slope'] = [a10 / 2, a10 / 4 + 10]\n if return_inis:\n return kwargs\n model, varnames, modelfun = exp_model(x, y, **kwargs)\n log = 'log'\n \n elif 'poly' in ftype:\n order = int(ftype[4:])\n a1 = next((value for key, value in kwargs.items() if key == 'a1'), None)\n if not a1:\n a10 = (y.max() - y[0]) / x.max()\n kwargs['a1'] = [a10, a10 / 4 + 20]\n if return_inis:\n return kwargs\n model, varnames, modelfun = poly_model(x, y, order, **kwargs)\n\n elif 'logis' in ftype or 'scurve' in ftype or 'sigmoid' in ftype:\n peak = next((value for key, value in kwargs.items() if key == 'peak'), None)\n if peak is None:\n peak0 = y.max() * 1.5\n kwargs['peak'] = [peak0, peak0 / 4]\n shifted = next((value for key, value in kwargs.items() if key == 'shifted'), None)\n if shifted is None:\n kwargs['shifted'] = [x[temp_new.cases.idxmax()], x.max() / 5]\n if return_inis:\n return kwargs\n model, varnames, modelfun = logistic_model(x, y, **kwargs)\n else:\n return None\n\n with model:\n step = pm.Slice()\n trace = pm.sample(samples, step=step, tune=tune, chains=chains, cores=cpu_cores) # , step, tune=2500, cores=10)\n\n varstats = []\n for va in varnames + ['sigma']:\n stats = calculateStats(trace[va]) # mean 2, std 3, 20% 5, 80% 7\n varstats.append([stats[2], stats[3], stats[5], stats[7]])\n\n sigma = sum(calculateStats(trace['sigma'])[2:4]) # mean + std\n\n plotstrs = ['%s COVID-19 cases %s model'%(country, ftype),\n '%s to %s'%(datetime.datetime.strftime(startdate, '%d.%m.%Y'),\n datetime.datetime.strftime(enddate, '%d.%m.%Y')),\n 'cumulative cases']\n df = modelfit_eval_dates(y, x, temp_new.dates,\n modelfun,\n varstats[0:-1],\n sigma=sigma,\n target=xTarget,\n plotstrs=plotstrs,\n log=log,\n varnames=varnames)\n\n for va in varnames + ['sigma']:\n stats = calculateStats(trace[va])\n df.loc[va + '_mean'] = stats[2]\n df.loc[va + '_std'] = stats[3]\n #df.loc[va + '_20%'] = stats[5]\n #df.loc[va + '_80%'] = stats[7]\n\n return df","sub_path":"forecast.py","file_name":"forecast.py","file_ext":"py","file_size_in_byte":5514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"280510418","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.13-x86_64/egg/reviewboard/webapi/tests/test_hosting_service_account.py\n# Compiled at: 2020-02-11 04:03:57\nfrom __future__ import unicode_literals\nfrom django.utils import six\nfrom reviewboard.hostingsvcs.models import HostingServiceAccount\nfrom reviewboard.webapi.resources import resources\nfrom reviewboard.webapi.tests.base import BaseWebAPITestCase\nfrom reviewboard.webapi.tests.mimetypes import hosting_service_account_item_mimetype, hosting_service_account_list_mimetype\nfrom reviewboard.webapi.tests.mixins import BasicTestsMetaclass\nfrom reviewboard.webapi.tests.urls import get_hosting_service_account_item_url, get_hosting_service_account_list_url\n\ndef _compare_item(self, item_rsp, account):\n self.assertEqual(item_rsp[b'id'], account.id)\n self.assertEqual(item_rsp[b'username'], account.username)\n self.assertEqual(item_rsp[b'service'], account.service.hosting_service_id)\n\n\n@six.add_metaclass(BasicTestsMetaclass)\nclass ResourceListTests(BaseWebAPITestCase):\n \"\"\"Testing the HostingServiceAccountResource list APIs.\"\"\"\n sample_api_url = b'hosting-services-accounts/'\n resource = resources.hosting_service_account\n fixtures = [b'test_users']\n basic_post_use_admin = True\n compare_item = _compare_item\n\n def setup_http_not_allowed_list_test(self, user):\n return get_hosting_service_account_list_url()\n\n def setup_basic_get_test(self, user, with_local_site, local_site_name, populate_items):\n if populate_items:\n if with_local_site:\n local_site = self.get_local_site(name=local_site_name)\n else:\n local_site = None\n accounts = [\n HostingServiceAccount.objects.create(service_name=b'googlecode', username=b'bob', local_site=local_site)]\n else:\n accounts = []\n return (\n get_hosting_service_account_list_url(local_site_name),\n hosting_service_account_list_mimetype,\n accounts)\n\n def test_get_with_service(self):\n \"\"\"Testing the GET hosting-service-accounts/ API with service=\"\"\"\n HostingServiceAccount.objects.create(service_name=b'googlecode', username=b'bob')\n account = HostingServiceAccount.objects.create(service_name=b'github', username=b'bob')\n rsp = self.api_get(get_hosting_service_account_list_url(), query={b'service': b'github'}, expected_mimetype=hosting_service_account_list_mimetype)\n self.assertEqual(rsp[b'stat'], b'ok')\n self.assertEqual(len(rsp[b'hosting_service_accounts']), 1)\n self.compare_item(rsp[b'hosting_service_accounts'][0], account)\n\n def test_get_with_username(self):\n \"\"\"Testing the GET hosting-service-accounts/ API with username=\"\"\"\n account = HostingServiceAccount.objects.create(service_name=b'googlecode', username=b'bob')\n HostingServiceAccount.objects.create(service_name=b'googlecode', username=b'frank')\n rsp = self.api_get(get_hosting_service_account_list_url(), query={b'username': b'bob'}, expected_mimetype=hosting_service_account_list_mimetype)\n self.assertEqual(rsp[b'stat'], b'ok')\n self.assertEqual(len(rsp[b'hosting_service_accounts']), 1)\n self.compare_item(rsp[b'hosting_service_accounts'][0], account)\n\n def setup_basic_post_test(self, user, with_local_site, local_site_name, post_valid_data):\n if post_valid_data:\n post_data = {b'username': b'bob', b'service_id': b'googlecode'}\n else:\n post_data = {}\n return (\n get_hosting_service_account_list_url(local_site_name),\n hosting_service_account_item_mimetype,\n post_data, [])\n\n def check_post_result(self, user, rsp):\n HostingServiceAccount.objects.get(pk=rsp[b'hosting_service_account'][b'id'])\n\n\n@six.add_metaclass(BasicTestsMetaclass)\nclass ResourceItemTests(BaseWebAPITestCase):\n \"\"\"Testing the HostingServiceAccountResource item APIs.\"\"\"\n fixtures = [\n b'test_users']\n sample_api_url = b'hosting-service-accounts//'\n resource = resources.hosting_service_account\n compare_item = _compare_item\n\n def setup_http_not_allowed_item_test(self, user):\n account = HostingServiceAccount.objects.create(service_name=b'googlecode', username=b'bob')\n return get_hosting_service_account_item_url(account.pk)\n\n def setup_basic_get_test(self, user, with_local_site, local_site_name):\n if with_local_site:\n local_site = self.get_local_site(name=local_site_name)\n else:\n local_site = None\n account = HostingServiceAccount.objects.create(service_name=b'googlecode', username=b'bob', local_site=local_site)\n return (\n get_hosting_service_account_item_url(account, local_site_name),\n hosting_service_account_item_mimetype,\n account)","sub_path":"pycfiles/ReviewBoard-3.0.17-py2.7/test_hosting_service_account.py","file_name":"test_hosting_service_account.py","file_ext":"py","file_size_in_byte":4978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"261002223","text":"import cv2\nimport sys\n\nimage='../../images/'+sys.argv[1]\n\nimg=cv2.imread(image, cv2.IMREAD_UNCHANGED)\n\nsobx=cv2.Sobel(img, cv2.CV_64F,1,0,ksize=5)\n\ntmp=sys.argv[1]\next=sys.argv[2]\nname=tmp[:len(tmp)-len(ext)-1]\noutput=name+'_sobx'+'.'+ext\ntarget='../../images/'+output\n\nif cv2.imwrite(target, sobx): print(output, end='')\nelse: print('failed',end='')\n","sub_path":"filters/img_grad_py/sobx.py","file_name":"sobx.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"9295395","text":"import logging\nimport nltk\nimport numpy as np\nimport hydro_serving_grpc as hs\nimport os\n\n# update searching path for nltk\nnltk.data.path = [\"/model/files/nltk_data\"] + nltk.data.path\n\n\ndef tokenize(x):\n\tsentences = np.array(x.string_val)\n\tsentences = sentences.reshape([dim.size for dim in x.tensor_shape.dim])\n\n\ttokenized = np.copy(sentences)\n\tfor index, sentence in enumerate(sentences):\n\t\ttokenized[index] = \" \".join(nltk.word_tokenize(str(sentence[0], encoding=\"utf-8\").lower()))\n\t\n\ttokenized = hs.TensorProto(\n\t\tdtype=hs.DT_STRING,\n\t\tstring_val=tokenized.flatten(),\n\t\ttensor_shape=hs.TensorShapeProto(dim=[hs.TensorShapeProto.Dim(size=-1), hs.TensorShapeProto.Dim(size=1)]))\n\treturn hs.PredictResponse(outputs={\"input_data\": tokenized})\n","sub_path":"examples/seq2seq/tokenize/src/func_main.py","file_name":"func_main.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"304507680","text":"'''handler for loading reel objects created by the ndnp handler'''\n\nimport csv\nimport logging\nimport os\nfrom rdflib import Graph, Literal, URIRef\nfrom classes import pcdm\nfrom classes.exceptions import ConfigException\nfrom namespaces import carriers, dcterms, rdf\n\n#============================================================================\n# DATA LOADING FUNCTION\n#============================================================================\n\ndef load(repo, batch_config):\n return Batch(repo, batch_config)\n\n#============================================================================\n# CSV BATCH CLASS\n#============================================================================\n\nclass Batch():\n\n '''iterator class representing the set of resources to be loaded'''\n\n def __init__(self, repo, batch_config):\n self.logger = logging.getLogger(\n __name__ + '.' + self.__class__.__name__\n )\n self.collection = pcdm.Collection()\n self.collection.uri = URIRef(batch_config.get('COLLECTION'))\n\n # check that the supplied collection exists and get title\n response = repo.get(\n self.collection.uri, headers={'Accept': 'application/rdf+xml'}\n )\n if response.status_code == 200:\n coll_graph = Graph().parse(data=response.text)\n self.collection.title = str(self.collection.uri)\n for (subj, pred, obj) in coll_graph:\n if str(pred) == \"http://purl.org/dc/elements/1.1/title\":\n self.collection.title = obj\n else:\n raise ConfigException(\n \"Collection URI {0} could not be reached.\".format(\n self.collection.uri\n )\n )\n self.collections = [self.collection]\n self.path = batch_config.get('LOCAL_PATH')\n self.files = [os.path.join(self.path, f) for f in os.listdir(self.path)]\n self.length = len(self.files)\n self.num = 0\n\n def __iter__(self):\n return self\n\n def __next__(self):\n if self.num < self.length:\n reel = Reel(self.files[self.num])\n reel.collections = self.collections\n self.num += 1\n return reel\n else:\n self.logger.info('Processing complete!')\n raise StopIteration()\n\n#============================================================================\n# NDNP REEL OBJECT\n#============================================================================\n\nclass Reel(pcdm.Item):\n\n '''class representing an NDNP reel'''\n\n def __init__(self, csvfile):\n super(Reel, self).__init__()\n self.id = os.path.splitext(os.path.basename(csvfile))[0]\n self.title = 'Reel Number {0}'.format(self.id)\n self.sequence_attr = ('Frame', 'sequence')\n self.path = csvfile\n\n with open(self.path, 'r') as f:\n reader = csv.DictReader(f)\n self.components = [\n Frame(self, row['sequence'], row['uri']) for row in reader\n ]\n\n self.graph.add(\n (self.uri, dcterms.title, Literal(self.title)))\n self.graph.add(\n (self.uri, dcterms.identifier, Literal(self.id)))\n self.graph.add(\n (self.uri, rdf.type, carriers.hd))\n\n#============================================================================\n# NDNP FRAME OBJECT\n#============================================================================\n\nclass Frame(pcdm.Component):\n\n '''class referencing an existing page object for purpose of reel creation'''\n\n def __init__(self, reel, sequence, uri):\n super(Frame, self).__init__()\n\n self.sequence = sequence\n self.uri = URIRef(uri)\n\n self.title = \"{0}, frame {1}\".format(reel.title, self.sequence)\n self.ordered = True\n","sub_path":"handler/reel.py","file_name":"reel.py","file_ext":"py","file_size_in_byte":3839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"50580110","text":"# You are given two strings s1 and s2 of equal length. A string swap is an \n# operation where you choose two indices in a string (not necessarily different) and \n# swap the characters at these indices. \n# \n# Return true if it is possible to make both strings equal by performing at \n# most one string swap on exactly one of the strings. Otherwise, return false. \n# \n# \n# Example 1: \n# \n# \n# Input: s1 = \"bank\", s2 = \"kanb\"\n# Output: true\n# Explanation: For example, swap the first character with the last character of \n# s2 to make \"bank\".\n# \n# \n# Example 2: \n# \n# \n# Input: s1 = \"attack\", s2 = \"defend\"\n# Output: false\n# Explanation: It is impossible to make them equal with one string swap.\n# \n# \n# Example 3: \n# \n# \n# Input: s1 = \"kelb\", s2 = \"kelb\"\n# Output: true\n# Explanation: The two strings are already equal, so no string swap operation \n# is required.\n# \n# \n# \n# Constraints: \n# \n# \n# 1 <= s1.length, s2.length <= 100 \n# s1.length == s2.length \n# s1 and s2 consist of only lowercase English letters. \n# \n# Related Topics Hash Table String Counting 👍 487 👎 18\n\n\n# leetcode submit region begin(Prohibit modification and deletion)\nclass Solution:\n def areAlmostEqual(self, s1: str, s2: str) -> bool:\n notMatch = 0\n notMatchPos = []\n for i in range(len(s1)):\n if s1[i] != s2[i]:\n notMatch += 1\n notMatchPos.append(i)\n if notMatch == 0:\n return True\n if notMatch != 2:\n return False\n if s1[notMatchPos[0]] == s2[notMatchPos[1]] and s1[notMatchPos[1]] == s2[notMatchPos[0]]:\n return True\n return False\n# leetcode submit region end(Prohibit modification and deletion)\n","sub_path":"[1790]Check if One String Swap Can Make Strings Equal.py","file_name":"[1790]Check if One String Swap Can Make Strings Equal.py","file_ext":"py","file_size_in_byte":1722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"64758368","text":"import requests\nimport HTMLTestRunner\nimport BeautifulReport\n#反射\nclass MyRequest:\n def __init__(self,url,method='get',data=None,headers=None,is_json=False):\n method = method.lower()\n self.url = url\n self.data = data\n self.headers = headers\n self.is_json = is_json\n if hasattr(self,method):\n getattr(self,method)()\n\n def get(self):\n try:\n req = requests.get(self.url,self.data,headers=self.headers).json()\n except Exception as e:\n self.response = {\"error\":\"接口请求出错%s\"%e}\n else:\n self.response = req\n\n def post(self):\n try:\n if self.is_json:\n req = requests.post(self.url, json=self.data, headers=self.headers).json()\n else:\n req = requests.post(self.url, self.data, headers=self.headers).json()\n except Exception as e:\n self.response = {\"error\":\"接口请求出错%s\"%e}\n else:\n self.response = req\n\n\nif __name__ == '__main__':\n import jsonpath\n login = MyRequest('http://127.0.0.1:5000/login1',data={'username':'chenjie','password':'123456'})\n # sessionid = login.response.get('session_id')\n result = jsonpath.jsonpath(login.response,'$..session_id')\n if result:\n print('登录成功')\n else:\n print('登录失败')\n print(login.response)\n\n\n\n # data = {'sessionid':sessionid,'money':10000}\n # m = MyRequest('http://127.0.0.1:5000/pay',data=data)\n # print(m.response)\n","sub_path":"day7/my_request.py","file_name":"my_request.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"319218070","text":"import pymongo\nfrom pymongo import MongoClient\nfrom bson import ObjectId\nimport json\nimport os\n\ndbURL = os.environ.get('COVIDDB')\nif dbURL == None:\n print(\"Database URL Not Found!\");\n\nclient = MongoClient(dbURL)\n\ndb = client.get_database('hackcovid')\ntestimonials = db.testimonials\n\ndef create(data):\n data['user'] = ObjectId(data['uid'])\n newTestimonial = testimonials.insert_one(data)\n try:\n id = newTestimonial.inserted_id\n return {\n 'status': 200,\n 'id': id\n }\n except Exception as e:\n return {\n 'status': 500,\n 'error': \"Server Error\"\n }\n\ndef get(query):\n allTestimonials = testimonials.find(query).sort('rdate', pymongo.DESCENDING).limit(5)\n return {\n 'count': allTestimonials.count(),\n 'data': allTestimonials\n }","sub_path":"covidConnect/api/testimonialMongo.py","file_name":"testimonialMongo.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"246619690","text":"# -*- coding: utf-8 -*- #\n# Copyright 2015 Google LLC. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Resource definitions for cloud platform apis.\"\"\"\n\nimport enum\n\n\nBASE_URL = 'https://run.googleapis.com/v1/'\nDOCS_URL = 'https://cloud.google.com/run/'\n\n\nclass Collections(enum.Enum):\n \"\"\"Collections for all supported apis.\"\"\"\n\n NAMESPACES = (\n 'namespaces',\n 'namespaces/{namespacesId}',\n {},\n [u'namespacesId'],\n True\n )\n NAMESPACES_CONFIGURATIONS = (\n 'namespaces.configurations',\n '{+name}',\n {\n '':\n 'namespaces/{namespacesId}/configurations/{configurationsId}',\n },\n [u'name'],\n True\n )\n NAMESPACES_DOMAINMAPPINGS = (\n 'namespaces.domainmappings',\n '{+name}',\n {\n '':\n 'namespaces/{namespacesId}/domainmappings/{domainmappingsId}',\n },\n [u'name'],\n True\n )\n NAMESPACES_REVISIONS = (\n 'namespaces.revisions',\n '{+name}',\n {\n '':\n 'namespaces/{namespacesId}/revisions/{revisionsId}',\n },\n [u'name'],\n True\n )\n NAMESPACES_ROUTES = (\n 'namespaces.routes',\n '{+name}',\n {\n '':\n 'namespaces/{namespacesId}/routes/{routesId}',\n },\n [u'name'],\n True\n )\n NAMESPACES_SERVICES = (\n 'namespaces.services',\n '{+name}',\n {\n '':\n 'namespaces/{namespacesId}/services/{servicesId}',\n },\n [u'name'],\n True\n )\n PROJECTS = (\n 'projects',\n 'projects/{projectsId}',\n {},\n [u'projectsId'],\n True\n )\n PROJECTS_LOCATIONS = (\n 'projects.locations',\n '{+name}',\n {\n '':\n 'projects/{projectsId}/locations/{locationsId}',\n },\n [u'name'],\n True\n )\n PROJECTS_LOCATIONS_CONFIGURATIONS = (\n 'projects.locations.configurations',\n '{+name}',\n {\n '':\n 'projects/{projectsId}/locations/{locationsId}/configurations/'\n '{configurationsId}',\n },\n [u'name'],\n True\n )\n PROJECTS_LOCATIONS_DOMAINMAPPINGS = (\n 'projects.locations.domainmappings',\n '{+name}',\n {\n '':\n 'projects/{projectsId}/locations/{locationsId}/domainmappings/'\n '{domainmappingsId}',\n },\n [u'name'],\n True\n )\n PROJECTS_LOCATIONS_REVISIONS = (\n 'projects.locations.revisions',\n '{+name}',\n {\n '':\n 'projects/{projectsId}/locations/{locationsId}/revisions/'\n '{revisionsId}',\n },\n [u'name'],\n True\n )\n PROJECTS_LOCATIONS_ROUTES = (\n 'projects.locations.routes',\n '{+name}',\n {\n '':\n 'projects/{projectsId}/locations/{locationsId}/routes/'\n '{routesId}',\n },\n [u'name'],\n True\n )\n PROJECTS_LOCATIONS_SERVICES = (\n 'projects.locations.services',\n '{+name}',\n {\n '':\n 'projects/{projectsId}/locations/{locationsId}/services/'\n '{servicesId}',\n },\n [u'name'],\n True\n )\n\n def __init__(self, collection_name, path, flat_paths, params,\n enable_uri_parsing):\n self.collection_name = collection_name\n self.path = path\n self.flat_paths = flat_paths\n self.params = params\n self.enable_uri_parsing = enable_uri_parsing\n","sub_path":"google-cloud-sdk/lib/googlecloudsdk/third_party/apis/run/v1/resources.py","file_name":"resources.py","file_ext":"py","file_size_in_byte":3907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"634713978","text":"minlength = 98\nmaxlength = 100\ntargetlength = \"98\"\noutfile_R1 = open(\"F:\\\\Code\\\\python\\\\filterFastq_Piardend\\\\1_filter.fastq\", 'w')\n\noutfile_R2 = open(\"F:\\\\Code\\\\python\\\\filterFastq_Piardend\\\\2_filter.fastq\", 'w')\n\n\nwith open(\"F:\\\\Code\\\\python\\\\filterFastq_Piardend\\\\1.fastq\", 'r') as infile_R1, open(\"F:\\\\Code\\\\python\\\\filterFastq_Piardend\\\\2.fastq\", 'r') as infile_R2 :\n for line_R1, line_R2 in zip(infile_R1, infile_R2):\n try:\n headinfo_R1 = line_R1\n headinfo_R2 = line_R2\n \n sequence_R1 = infile_R1.__next__().strip()\n sequence_R2 = infile_R2.__next__().strip()\n\n comment_R1 = infile_R1.__next__()\n comment_R2 = infile_R2.__next__()\n\n quality_R1 = infile_R1.__next__()\n quality_R2 = infile_R2.__next__()\n except:\n break\n\n\n seqlength_R1 = len(sequence_R1)\n seqlength_R2 = len(sequence_R2)\n\n if ( int(minlength) <= seqlength_R1 <= int(maxlength) and int(minlength) <= seqlength_R2 <= int(maxlength) ):\n headinfo_R1split = headinfo_R1.split(\" \")\n headinfo_R1af = headinfo_R1split[0] + \" \" + headinfo_R1split[1] + \" \" + \"length=\" + targetlength + \"\\n\"\n sequence_R1af = sequence_R1[0:int(targetlength)] + \"\\n\"\n comment_R1split = comment_R1.split(\" \")\n comment_R1af = comment_R1split[0] + \" \" + comment_R1split[1] + \" \" + \"length=\" + targetlength + \"\\n\"\n quality_R1af = quality_R1[0:int(targetlength)] + \"\\n\"\n\n headinfo_R2split = headinfo_R2.split(\" \")\n headinfo_R2af = headinfo_R2split[0] + \" \" + headinfo_R2split[1] + \" \" + \"length=\" + targetlength+\"\\n\"\n sequence_R2af = sequence_R2[0:int(targetlength)] + \"\\n\"\n comment_R2split = comment_R2.split(\" \")\n comment_R2af = comment_R2split[0] + \" \" + comment_R2split[1] + \" \" + \"length=\" + targetlength+\"\\n\"\n quality_R2af = quality_R2[0:int(targetlength)] + \"\\n\"\n\n outfile_R1.write(headinfo_R1af)\n outfile_R1.write(sequence_R1af)\n outfile_R1.write(comment_R1af)\n outfile_R1.write(quality_R1af)\n\n outfile_R2.write(headinfo_R2af)\n outfile_R2.write(sequence_R2af)\n outfile_R2.write(comment_R2af)\n outfile_R2.write(quality_R2af)\n \n else:\n pass\n\n\n\n\n\n","sub_path":"filterFastqReadsLen/filterFastqpiardend-unix.py","file_name":"filterFastqpiardend-unix.py","file_ext":"py","file_size_in_byte":2467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"434567707","text":"############\r\n# Funcional e OO\r\n# Prof. Neylson\r\n# Gerson Vasconcelos Neto\r\n# aula 04 - python\r\n###########\r\n\r\nimport pandas as pd # Trabalhar com dataframes\r\nimport numpy as np # Cálculo e estatística\r\nimport matplotlib.pyplot as plt # Gráficos\r\nimport seaborn as sns # Gráficos também\r\n\r\npnad = pd.read_csv('https://raw.githubusercontent.com/neylsoncrepalde/introducao_ao_python/master/pes_2012.csv')\r\n\r\n\r\npnad.shape # tamanho do banco\r\n\r\npnad.columns # nomes das variáveis\r\n\r\npnad.head() # primeiros casos\r\n\r\npnad.dtypes # qual que é o type de cada variável\r\n\r\npnad['V0101'].head() # fazendo um head() de um subset\r\npnad.V0101.head() # fazendo um head() de um subset\r\n\r\npnad.UF.head()\r\npnad.UF.dtype # retorna como type objeto\r\npnad.UF = pnad.UF.astype('category') # mudando para uma variável categórica\r\n\r\n\r\n###########\r\n# Sexo\r\n\r\npnad.V0302.head()\r\npnad['sexo'] = pnad.V0302.astype('category') # atribuir como categórica para uma variável sexo\r\npnad.V0302.dtype\r\npnad.Sexo.dtype\r\n\r\n##########\r\n# Cor\r\n\r\npnad.V0404.head()\r\npnad.V0404.value_counts() # frequência\r\n\r\n# substituir nessa variável os sem declaração para NaN\r\n\r\n# só o subset\r\npnad.loc[9,'V8005'] # usar os labels\r\npnad.iloc[2,2] # usar o índice [pnad.columns]\r\n\r\n# substituindo\r\n\r\npnad.loc[pnad['V0404'] == 'Sem declaração', 'V0404'] = np.nan\r\n# selecionar na V0404 apenas os casos em que a V0404 serão 'Sem declaração' e transformá-los em NaN\r\n\r\npnad['V0404'] = pnad['V0404'].astype('category')\r\npnad.V0404.dtype\r\n\r\n\r\n#########\r\n# Renda de todos os trabalhos - V4720\r\n\r\npnad['V4720'].astype('float') # nao consegui porque tem uma sem declaração no meio\r\n\r\npnad.loc[pnad['V4720'] == 'Sem declaração', 'V4720'] = np.nan\r\npnad['renda'] = pnad['V4720'].astype('float') # atribui a uma nova variável em float\r\n\r\npnad.renda.describe() # estatísticas descritivas\r\n\r\n###################\r\n# analisando distribuição de sexo\r\n\r\npnad.sexo.value_counts()\r\n(pnad.sexo.value_counts() / pnad.sexo.value_counts().sum())*100 # em porcentagem\r\n# mas não estão fidedignas porque não está levando em conta o peso amostral dos indivíduos\r\n# análise viesada\r\n\r\n# Idade\r\n\r\npnad.V8005.describe() # estatísticas descritivas\r\npnad.V8005.mean() # média (está viesada)\r\npnad.V8005.var() # variância\r\npnad.V8005.std() # desvio padrão\r\n\r\nnp.average(pnad.V8005, weights = pnad.V4729) # levando em consideração o peso amostral (a V4729 são os pesos)\r\n\r\n##############\r\n# cor \r\n\r\n# distribuição de frequência\r\npd.crosstab(index = pnad.V0404, columns = 'Counts') # a diferença da value_counts é a ordenação\r\n\r\n# distribuição de porcentagens (parametro para percentual = normalize)\r\npd.crosstab(index = pnad.V0404, columns = '%',\r\n normalize = True) * 100\r\n\r\n# tabela cruzada entre sexo e cor\r\npd.crosstab(index = pnad.V0404, columns = pnad.sexo)\r\n\r\n# em porcentagem pelas linhas (margins = mostra os totais)\r\npd.crosstab(index = pnad.V0404, columns = pnad.sexo,\r\n margins = True, normalize = 'index') * 100\r\n\r\n# em porcentagem pelas colunas (margins = mostra os totais)\r\npd.crosstab(index = pnad.V0404, columns = pnad.sexo,\r\n margins = True, normalize = 'columns') * 100\r\n\r\n# percetuais da tabela inteira\r\npd.crosstab(index = pnad.V0404, columns = pnad.sexo,\r\n margins = True, normalize = 'all') * 100\r\n\r\n####################\r\n# sexo em gráficos\r\n\r\n# sns é do seaborn e plt é do matplotlib \r\nsns.countplot(x = pnad.sexo)\r\nplt.title('Distribuição de sexo no Brasil - 2012')\r\nplt.xlabel('Sexo')\r\nplt.ylabel('Frequência')\r\nplt.show()\r\n\r\n# grafico deitado\r\nsns.countplot(y = pnad.sexo)\r\nplt.title('Distribuição de sexo no Brasil - 2012')\r\nplt.ylabel('Sexo')\r\nplt.xlabel('Frequência')\r\nplt.show()\r\n \r\n# cor / raça\r\n\r\nsns.set(color_codes = True) # usando as paletas de cores do seaborn\r\nsns.countplot(y = pnad.V0404)\r\nplt.ylabel('Cor/Raça')\r\nplt.xlabel('Frequência')\r\nplt.show()\r\n\r\n# tudo em vermelho\r\n\r\nsns.set(color_codes = True) # usando as paletas de cores do seaborn\r\nsns.countplot(y = pnad.V0404, color = 'r')\r\nplt.ylabel('Cor/Raça')\r\nplt.xlabel('Frequência')\r\nplt.show()\r\n\r\n# visualizando variáveis numéricas\r\n\r\n# histograma\r\nsns.distplot(pnad.renda.dropna(), kde = False) # dropna para tirar as NaNs para poder plotar o gráfico\r\nplt.show()\r\n\r\n\r\n# densidade\r\nsns.distplot(pnad.renda.dropna(), hist = False)\r\nplt.show()\r\n\r\n\r\n# modificando algumas coisas\r\nfig, ax = plt.subplots() # axys\r\nfig.set_size_inches(8, 6)\r\nsns.distplot(pnad.renda.dropna(), hist = False)\r\nplt.show()\r\n\r\n# cruzar uma numérica e uma categórica\r\nsns.boxplot(x = 'V0404', y = 'V8005', data = pnad)\r\nplt.show()\r\n\r\n# cruzar duas variáveis numéricas\r\n# gráfico de dispersão\r\n\r\nplt.scatter(x = pnad.renda, y = pnad.V8005)\r\nplt.show()\r\n\r\n# scatter e a histograma de cada variável\r\nsns.jointplot(x = pnad.renda, y = pnad.V8005)\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"aula_pyOO_4.py","file_name":"aula_pyOO_4.py","file_ext":"py","file_size_in_byte":4961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"260245881","text":"\nimport tkinter\n\nclass Petrol:\n def __init__(self):\n self.pflag=False\n self.fflag=False\n\n self.window=tkinter.Tk()\n self.window.geometry('400x200')\n\n tkinter.Label(self.window,text='pertrol price : ').grid(row=0,column=0)\n self.pp=tkinter.Entry(self.window,highlightcolor='green')\n self.pp.bind('',self.checkFocusPrice)\n self.pp.grid(row=0,column=1)\n\n tkinter.Label(self.window,text='fill amount : ').grid(row=1,column=0)\n self.fp=tkinter.Entry(self.window,highlightcolor='green')\n self.fp.bind('',self.checkFocusFilling)\n self.fp.grid(row=1,column=1)\n\n self.gen=tkinter.Button(self.window,text='generate',relief='solid',bd=2,bg='green',\n activebackground='green',highlightcolor='yellow')\n self.gen.bind('',self.generatePrice)\n self.gen.bind('',self.generatePrice)\n self.gen.bind('',self.generatePrice)\n self.gen.bind('',self.generatePrice)\n self.gen.grid(row=2,column=1,columnspan=2,sticky=tkinter.E)\n\n tkinter.Button(self.window,text='exit',bg='red',activebackground='red',relief='solid',bd=2,command=lambda:self.window.destroy()).grid(row=2,column=0,columnspan=2)\n\n self.window.mainloop()\n\n def checkFocusPrice(self,Event):\n try:\n float(self.pp.get())\n self.pp.configure(highlightcolor='green',bg='green')\n self.pflag=True\n except ValueError:\n self.pp.configure(highlightcolor='red', bg='red')\n finally:\n if not(self.pflag and self.fflag):\n self.gen.configure(state=tkinter.DISABLED)\n\n def checkFocusFilling(self,entry):\n try:\n float(self.fp.get())\n self.fp.configure(highlightcolor='green')\n self.fflag=True\n except ValueError:\n self.fp.configure(highlightcolor='red', bg='red')\n finally:\n if not(self.pflag and self.fflag):\n self.gen.configure(state=tkinter.DISABLED)\n\n\n def generatePrice(self,event):\n print(\"we are in generate price\")\n try:\n petrol_price =float(self.pp.get())\n filling_price = float(self.fp.get())\n print(petrol_price,filling_price)\n price_in_gm = petrol_price / 1000\n petrol_in_gm = 0\n i=1\n while filling_price>=(price_in_gm*i):\n petrol_in_gm+=1\n i += 1\n else:\n try:\n self.ermsg['text']=''\n except AttributeError:\n pass\n tkinter.Label(self.window,text=\"money : {:.2f}\".format(price_in_gm*i-(price_in_gm)),fg='green',font=('',14)).grid(row=3,column=1)\n tkinter.Label(self.window,text=\"liter : {:.2f}\".format(petrol_in_gm/1000),fg='green',font=('',14)).grid(row=4,column=1)\n tkinter.Label(self.window,text=\"in gm : {:.2f}\".format(petrol_in_gm), fg='green',font=('', 14)).grid(row=5, column=1)\n except ValueError as ve:\n self.ermsg=tkinter.Label(self.window,text='character not allowed',fg='red',font=('',14))\n self.ermsg.grid(row=3,column=1)\n\nif __name__=='__main__':\n Petrol()","sub_path":"petrolpump.py","file_name":"petrolpump.py","file_ext":"py","file_size_in_byte":3288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"442024258","text":"# coding=utf-8\n\n'''\n:author pyx0622@gmail.com\n:date 2016.08.13\n:desc 山东临沂租赁点抓取脚本\n\n 由百度 place api 获得 POI 经纬度,再根据叮嗒出行的经纬度列表接口,由这些经纬度查询所有公共自行车租赁点\n\n'''\nimport random\nimport time\nimport traceback\n\nfrom tornado import gen\nfrom tornado.ioloop import IOLoop\nfrom tornado.util import ObjectDict\n\nfrom scripts.parser import Parser\n\n# 临沂\nCITY_ID = 37013\nSID = 3\n\n\nclass DingdaParser(Parser):\n \"\"\"\n 数据来自叮嗒出行客户端\n \"\"\"\n\n @gen.coroutine\n def get_regions(self):\n regions = yield self.region_ps.get_regions(conds={\n \"cid\": CITY_ID\n })\n raise gen.Return(regions)\n\n @gen.coroutine\n def get_stations(self):\n regions = yield self.get_regions()\n for region in regions:\n for q in self.const.BAIDU_POI_Q:\n for page_num in range(0, 40):\n baidu_poi_list = yield self.infra_ps.get_city_poi(q, region.pname, region.rname, page_num, coord_type = 3)\n\n for item in baidu_poi_list.results:\n if not item.get(\"location\"):\n continue\n dingda_list = yield self.infra_ps.get_dingda_nearby(item.get(\"location\",{}).get(\"lng\", \"\"),\n item.get(\"location\",{}).get(\"lat\", \"\"))\n if dingda_list.data and dingda_list.data.stationLists:\n for item in dingda_list.data.stationLists:\n station = ObjectDict()\n station['code'] = str(item.get('id'))\n station['status'] = self.const.STATUS_INUSE\n # station['type'] = \"\"\n # station['total'] = \"\"\n station['name'] = item['name']\n # station['address'] = \"\"\n # station['district'] = \"\"\n station['longitude'] = item[\"longitude\"]\n station['latitude'] = item[\"latitude\"]\n # station['service_time'] = \"\"\n # station['is_24'] = \"\"\n # station['is_duty'] = \"\"\n print(station)\n yield self.update_station(station)\n\n x = int(random.random() * 10)\n print(x)\n yield self.async_sleep(x)\n\n print (\"end\")\n\n raise gen.Return(True)\n\n @gen.coroutine\n def update_station(self, item):\n\n \"\"\"\n 增加或更新数据库中租赁点信息\n :param station:\n :return:\n \"\"\"\n station = yield self.station_ps.get_station(conds={\n \"code\": item.code,\n \"cid\": CITY_ID,\n \"sid\": SID,\n })\n\n if station:\n # 存在,则更新\n self.station_ps.update_station(\n conds={\n \"id\": station.id\n },\n fields={\n \"status\": item.status,\n # \"total\": item.total,\n \"name\": item.name,\n # \"address\": item.address,\n # \"district\": item.district,\n # \"district_id\": item.district_id,\n \"longitude\": item.longitude,\n \"latitude\": item.latitude\n }\n )\n else:\n # 不存在,则增加\n yield self.station_ps.add_station(fields={\n \"code\": item.code,\n \"cid\": CITY_ID,\n \"sid\": SID,\n \"status\": item.status,\n # \"total\": item.total,\n \"name\": item.name,\n # \"address\": item.address,\n # \"district\": item.district,\n # \"district_id\": item.district_id,\n \"longitude\": item.longitude,\n \"latitude\": item.latitude\n })\n\n @gen.coroutine\n def async_sleep(self, timeout):\n # Sleep without blocking the IOLoop\n yield gen.Task(IOLoop.instance().add_timeout, time.time() + timeout)\n\n @gen.coroutine\n def runner(self):\n try:\n yield self.get_stations()\n except Exception as e:\n self.logger.error(traceback.format_exc())\n # 增加抓取记录 log\n yield self.scraplog_ps.add_scrap_log(fields={\n \"cid\": CITY_ID,\n \"status\": self.const.STATUS_UNUSE,\n })\n\n # 增加抓取记录 log\n yield self.scraplog_ps.add_scrap_log(fields={\n \"cid\": CITY_ID,\n \"status\": self.const.STATUS_INUSE,\n })\n\n IOLoop.instance().stop()\n\n\nif __name__ == \"__main__\":\n jp = DingdaParser()\n jp.runner()\n IOLoop.instance().start()\n","sub_path":"scripts/bikestation/dingda_app/shandong_linyi.py","file_name":"shandong_linyi.py","file_ext":"py","file_size_in_byte":5047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"161374934","text":"import matplotlib.pyplot as plt\r\ndef twodrand():\r\n f = open ( 'input2' , 'r')\r\n l = []\r\n l = [ line.split() for line in f]\r\n x=[]\r\n y=[] \r\n n=len(l) \r\n for i in range(n-1):\r\n a=float(l[i][0])\r\n b=float(l[i][1])\r\n x.append(a)\r\n y.append(b)\r\n plt.plot(x,y,'ro')\r\n plt.xlabel(\"x values\")\r\n plt.ylabel(\"y values\")\r\n plt.title(\"scatter plot for ex2b\")\r\n\r\n\r\ntwodrand()\r\n ","sub_path":"Python/Lab 4/ex22.py","file_name":"ex22.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"293826487","text":"def acha_bigramas(s):\n i = 1\n l = []\n while i < len(s):\n b = s[i] + s[i-1]\n if b not in l:\n l.append(b)\n i += 1\n return l\nprint (l)","sub_path":"backup/user_101/ch64_2020_04_27_20_29_47_887175.py","file_name":"ch64_2020_04_27_20_29_47_887175.py","file_ext":"py","file_size_in_byte":175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"592813237","text":"from django.http.response import HttpResponseRedirect, HttpResponse\nfrom django.shortcuts import render\n\nfrom .models import Post\nfrom .forms import PostForm\nfrom django.utils import timezone\n\n\ndef index(request):\n latest_post_list = Post.objects.order_by('-pub_date')[:5]\n \n if request.method == \"POST\":\n form = PostForm(request.POST)\n if form.is_valid():\n post = form.save(commit=False)\n post.pub_date = timezone.now()\n form.save()\n return HttpResponseRedirect('/#testimonials')\n else:\n form = PostForm()\n return render(request, 'base.html', {'form': form, 'latest_post_list': latest_post_list,})\n \n","sub_path":"feirasjc/feirapage/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"639932128","text":"# @Time : 2019/6/15 7:56\n# @Author : Xu Huipeng\n# @Blog : https://brycexxx.github.io/\n\nfrom typing import List\n\n\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution:\n def generateTrees(self, n: int) -> List[TreeNode]:\n def dfs(first: int, last: int) -> List[TreeNode]:\n res = []\n for val in range(first, last):\n for l_tree in dfs(first, val):\n for r_tree in dfs(val + 1, last):\n root = TreeNode(val)\n root.left, root.right = l_tree, r_tree\n res += root\n return res or [None]\n\n return dfs(1, n + 1)\n\n def generateTrees1(self, n: int) -> List[TreeNode]:\n def generate(first, last):\n trees = []\n for root in range(first, last + 1):\n for left in generate(first, root - 1):\n for right in generate(root + 1, last):\n node = TreeNode(root)\n node.left = left\n node.right = right\n # 秀,逗号形成列表\n trees += node,\n return trees or [None]\n\n return generate(1, n)\n\n\nif __name__ == '__main__':\n s = Solution()\n print(s.generateTrees1(3))\n","sub_path":"generateTrees.py","file_name":"generateTrees.py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"354072035","text":"from flask import Flask, render_template, request, make_response\nimport json\nfrom datetime import datetime\n\nIPLIST_PATH = \"/opt/localnet/portal/known_ips.json\" # change this\n\napp = Flask(__name__)\n\n@app.route('/', defaults={'path': ''})\n@app.route('/')\ndef catch_all(path):\n if path == \"hotspot-detect.html\":\n # We can assume it's an Apple client\n with open(IPLIST_PATH, \"r\") as f:\n ip_list = json.load(f)\n if request.remote_addr in ip_list:\n return render_template(\"ios_success.html\")\n else:\n return render_template('information.html')\n elif path == \"registered.html\":\n with open(IPLIST_PATH, \"r\") as f:\n ip_list = json.load(f)\n ip_list[request.remote_addr] = datetime.now().isoformat()\n with open(IPLIST_PATH, \"w\") as f:\n json.dump(ip_list, f)\n return render_template(\"registered.html\")\n return \"blocked.\"\n\nif __name__ == '__main__':\n app.run(debug=True)","sub_path":"captive_portal/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"557362926","text":"from django.conf.urls import url\nfrom blog import views\n\n\nurlpatterns = [\n url('',views.PostListView.as_view(),name='post_list'),\n url('about/',views.AboutView.as_view(),name='about'),\n\n url('post/()',views.PostDetailView.as_view(),name='post_detail'),\n url('post/new/',views.CreatePostView.as_view(),name='post_new'),\n url('post/edit()',views.PostUpdateView.as_view(),name='post_edit'),\n url('post/remove/()',views.PostDeleteView.as_view(),name='post_remove'),\n url('drafts/',views.DraftListView.as_view(),name='post_draft_list'),\n url('post/comment/()',views.add_comment_to_post,name='add_comment_to_post'),\n url('comment/approve/()',views.comment_approve,name='comment_approve'),\n url('post/publish/()',views.post_publish,name='post_publish'),\n url('comment/remove/()',views.comment_remove,name='comment_remove'),\n]\n","sub_path":"mysite/blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"317292879","text":"import os\nimport csv\nimport json\nfrom datetime import datetime\n\nannot_base_dir = '/vision/u/bingbin/EPIC_KITCHENS_2018/annotations/'\nobj_base_dir = '/vision/u/bingbin/EPIC_KITCHENS_2018/object_detection_images/'\nepic_frame_format = '{:010d}.jpg'\n\ndef get_full_path(subset, pid, vid, frame):\n return os.path.join(obj_base_dir, subset, pid, vid, epic_frame_format.format(int(frame)))\n\ndef noun_categories():\n fcsv = '/sailhome/bingbin/VOG/dataset/EPIC/annotations/EPIC_noun_classes.csv'\n data = [line for line in csv.reader(open(fcsv, 'r'))]\n header = data[0]\n data = data[1:]\n cats = []\n for line in data:\n cats.append({\n 'id': int(line[0])+1,\n 'name': line[1],\n 'supercategory': line[1]\n })\n return cats\n\ndef parse_list(bboxes_str):\n bboxes = bboxes_str.split('),')\n ret = []\n for bbox in bboxes:\n bbox = bbox.replace('(', '').replace(')', '')\n bbox = bbox.replace('[', '').replace(']', '')\n bbox = bbox.replace(' ', '')\n bbox = [int(each) for each in bbox.split(',') if each]\n if bbox:\n ret += bbox,\n return ret\n\ndef to_COCO_format(fin, fout, subset):\n with open(fin, 'r') as handle:\n data = [line for line in csv.reader(handle)]\n header = data[0]\n data = data[1:]\n print('data: type:{} / len:{}'.format(type(data), len(data)))\n\n now = str(datetime.now())\n\n annotations = []\n images = []\n licenses = []\n uid = 0\n for [noun_cls, noun, pid, vid, frame, bboxes] in data:\n full_path = get_full_path(subset, pid, vid, frame)\n # print(full_path)\n if not os.path.exists(full_path):\n continue\n\n bboxes = parse_list(bboxes)\n if not bboxes:\n continue\n\n for bbox in bboxes:\n xmin, ymin = bbox[:2]\n xmax = xmin + bbox[2]\n ymax = ymin + bbox[3]\n seg = [xmin,ymin, xmax,ymin, xmax,ymax, xmin,ymax]\n\n area = bbox[2] * bbox[3]\n if area < 1:\n continue\n\n annotations.append({\n 'area': bbox[2] * bbox[3],\n 'bbox': bbox,\n 'category_id': int(noun_cls)+1,\n 'id': uid,\n 'image_id': int(frame),\n 'iscrowd': 0,\n 'segmentation': [seg],\n })\n images.append({\n 'id': int(frame),\n 'width': 1920, # TODO: are EPIC images uni size?\n 'height': 1080,\n 'file_name': full_path,\n 'license': 'license placeholder',\n 'flickr_url': 'flickr_url placeholder',\n 'coco_url': 'coco_url placeholder',\n 'date_captured': now\n })\n licenses.append({\n 'id': uid+1,\n 'name': 'name placeholder',\n 'url': 'url placeholder'\n })\n uid += 1\n print('#bbox:', uid)\n\n info = {\n 'year': 2018,\n 'version': 'v1',\n 'description': 'placeholder for COCO info',\n 'contributor': 'BB (not really)',\n 'url': '',\n 'data_created': now\n }\n\n categories = noun_categories()\n\n with open(fout, 'w') as handle:\n json.dump({\n 'info':info,\n 'images':images,\n 'licenses':licenses,\n 'annotations':annotations,\n 'categories':categories\n }, handle)\n\nif __name__ == '__main__':\n fin = os.path.join(annot_base_dir, 'EPIC_train_object_labels.csv')\n fout = os.path.join(annot_base_dir, 'coco_train_object_labels_exists.json')\n to_COCO_format(fin, fout, 'train')\n","sub_path":"utils_epic.py","file_name":"utils_epic.py","file_ext":"py","file_size_in_byte":3244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"384511806","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport os\nfrom GetDataLoaders import get_dataloaders, get_short_dataloaders\nfrom architectures.Resnets import resnet50_cifar as resnet50\nfrom architectures.ContrastiveLoss import ContrastiveLoss\nimport torch\nimport numpy as np\nfrom torch.utils.tensorboard import SummaryWriter\nfrom torch import nn\nimport time\nfrom torch import optim\nfrom tqdm import tqdm\nfrom torch.optim.lr_scheduler import ExponentialLR\n\n\n# In[2]:\n\n\n'''\n# we skip the probs for now\ngama = 2.0\nwith open(os.path.join(\"./PUprobs\", 'prob.dat'), 'r') as file_input:\n train_prob_str = file_input.readlines()\n train_prob = [float(i_prob_str.rstrip('\\n')) for i_prob_str in train_prob_str]\n print(len(train_prob)/4.0)\n train_weight = [1.0 if 0==i%4 else 1-train_prob[i]**gama for i in range(len(train_prob))]\n'''\n\n\n# In[3]:\n\n\nuse_cuda = torch.cuda.is_available()\ndevice = \"cuda\" if use_cuda else \"cpu\"\nbatch_size = 32\nlr = 1e-3\n\nnum_epochs = 200\n'''\nmomentum = 0.9\nnesterov = True\nLambdas = {'CE':1.0, 'MSE':1.0, 'NCE':1.0}\nLUT_lr = [(90,0.01), (130,0.001), (190,0.0001), (210,0.00001), (230,0.0001), (245,0.00001)]\n'''\nweight_decay = 1e-6\nloaders = get_dataloaders('imagenet', batch_size=batch_size, num_workers=2, unsupervised=True, simclr=True)\ntau = 0.1\ngamma = 2\ndecay_lr = 1e-6\naccumulation_steps = 4 \n\n\n# In[4]:\n\n\n'''\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torchvision\n\n# functions to show an image\n\n\ndef imshow(img):\n img = img / 2 + 0.5 # unnormalize\n npimg = img.numpy()\n plt.imshow(np.transpose(npimg, (1, 2, 0)))\n plt.show()\n\n\n# get some random training images\ndataiter = iter(loaders['train_loader'])\nimagesi, imagesj = dataiter.next()\n\n# show images\nimshow(torchvision.utils.make_grid(imagesi))\nimshow(torchvision.utils.make_grid(imagesj))\n'''\n\n\n# In[5]:\n\n\nfeature_net = resnet50(128).to(device)\noptimizer = optim.Adam(feature_net.parameters(), lr=lr, weight_decay=weight_decay)\nscheduler = ExponentialLR(optimizer, gamma=decay_lr)\n\n\nNetworks = {'feature':feature_net}\nOptimizers = {'feature':optimizer}\n\nContrastiveCriterion = ContrastiveLoss(tau=tau, normalize=True)\nCriterions = {'CE': nn.CrossEntropyLoss(reduction='none'), 'MSE':nn.MSELoss() }\n\n\n# In[6]:\n\n\nfeature_net\n\n\n# In[7]:\n\n\ndef train_validate(data_loader, epoch, train=True):\n \n mode = \"Train\" if train else \"Valid\"\n if train is True:\n for key in Networks:\n Networks[key].train()\n Networks[key].zero_grad()\n else:\n for key in Networks:\n Networks[key].eval()\n \n \n losses = {'mse':[], 'nce':[]}\n \n \n overallloss = None\n \n \n start_time = time.time()\n tqdm_bar = tqdm(data_loader)\n \n for batch_idx, batch in enumerate(tqdm_bar):\n datai, dataj = batch\n \n datai, dataj = datai.to(device), dataj.to(device)\n if train is False:\n with torch.no_grad():\n _, featuresi = Networks['feature'](datai)\n _, featuresj = Networks['feature'](dataj)\n loss_nce = ContrastiveCriterion(featuresi, featuresj)\n else:\n _, featuresi = Networks['feature'](datai)\n _, featuresj = Networks['feature'](dataj)\n loss_nce = ContrastiveCriterion(featuresi, featuresj)\n \n loss_nce = loss_nce / accumulation_steps\n\n if train is True:\n loss_nce.backward()\n if (batch_idx + 1) % accumulation_steps == 0:\n for key in Optimizers:\n Optimizers[key].step()\n Networks[key].zero_grad()\n\n #calculate rotation invariance by MSE\n with torch.no_grad():\n features_mean = featuresi + featuresj \n features_mean = torch.mul(features_mean, 0.5)\n loss_mse = Criterions['MSE'](featuresi, features_mean)\n loss_mse += Criterions['MSE'](featuresj, features_mean) \n \n losses['mse'].append(loss_mse.item())\n losses['nce'].append(loss_nce.item())\n tqdm_bar.set_description('{} Epoch: [{}] Loss: NCE {:.4f}, MSE {:.4f}'.format(mode, epoch, loss_nce.item(), loss_mse.item()))\n \n \n end_time = time.time()\n print(\"Time for epoch pass {}\".format(end_time-start_time))\n overallloss = {'mse': float(np.mean(losses['mse'])), 'nce':float(np.mean(losses['nce']))}\n print('{} set: Average loss: MSE {:.4f}, NT-Xent {:.4f}\\n'.format(mode, overallloss['mse'], overallloss['nce']))\n return overallloss\n\n\n\ndef run_main_loop(loaders, num_epochs, starting_epoch=1):\n writer = SummaryWriter('./logs/AlexNet_SimCLR')\n save_path = \"weights/AlexNet_Decoupling_Contrastive_SimCLR.pth\"\n best_loss = np.Inf\n for epoch in range(starting_epoch, starting_epoch+num_epochs):\n \n \n train_loss = train_validate(loaders['train_loader'], epoch, train=True)\n val_loss = train_validate(loaders['valid_loader'], epoch, train=False)\n scheduler.step()\n \n writer.add_scalar('MSELoss/train', train_loss['mse'], epoch)\n writer.add_scalar('NT-XENTLoss/train', train_loss['nce'], epoch)\n writer.add_scalar('MSELoss/Valid', val_loss['mse'], epoch)\n writer.add_scalar('NT-XENTLoss/Valid', val_loss['nce'], epoch)\n writer.add_scalar('LR', Optimizers['feature'].param_groups[0]['lr'], epoch+1)\n \n \n \n if (epoch)%10 == 0 :\n best_loss = val_loss['nce']\n #save model\n states = {\n 'epoch': epoch + 1,\n 'best_loss': best_loss,\n 'scheduler': scheduler.state_dict()\n }\n for key in Networks:\n states[key+\"net\"] = Networks[key].state_dict()\n for key in Optimizers:\n states[key+\"optimizer\"] = Optimizers[key].state_dict()\n torch.save(states, save_path)\n print('Model Saved')\n\n\n# In[8]:\n\n\nrun_main_loop(loaders, num_epochs)\n\n\n# In[ ]:\n\n\nsave_path = \"weights/AlexNet_Decoupling_Contrastive_SimCLR_Features.pth\"\nstates = {\n 'epoch':200,\n 'scheduler': scheduler.state_dict()\n }\nfor key in Networks:\n states[key+\"net\"] = Networks[key].state_dict()\nfor key in Optimizers:\n states[key+\"optimizer\"] = Optimizers[key].state_dict()\ntorch.save(states, save_path)\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"SimCLR-failure/pythonexports/pretraining-SimCLR.py","file_name":"pretraining-SimCLR.py","file_ext":"py","file_size_in_byte":6334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"221671365","text":"#!/usr/bin/env python\n\"\"\" \"\"\"\n\n# Script information for the file.\n__author__ = \"Philippe T. Pinard\"\n__email__ = \"philippe.pinard@gmail.com\"\n__version__ = \"0.1\"\n__copyright__ = \"Copyright (c) 2014 Philippe T. Pinard\"\n__license__ = \"GPL v3\"\n\n# Standard library modules.\nimport unittest\nimport logging\nfrom io import BytesIO\nimport xml.etree.ElementTree as etree\n\n# Third party modules.\n\n# Local modules.\nfrom pymontecarlo.fileformat.options.options import OptionsReader, OptionsWriter\n\nfrom pymontecarlo.options.options import Options\nfrom pymontecarlo.options.detector import BackscatteredElectronEnergyDetector\nfrom pymontecarlo.options.limit import ShowersLimit\nfrom pymontecarlo.options.model import ELASTIC_CROSS_SECTION\n\nfrom pymontecarlo.program.test_config import DummyProgram\n\n# Globals and constants variables.\n\nclass TestOptionsReader(unittest.TestCase):\n\n def setUp(self):\n unittest.TestCase.setUp(self)\n\n self.reader = OptionsReader()\n\n etree.register_namespace('mc', 'http://pymontecarlo.sf.net')\n source = BytesIO(b'dummy 1000 ')\n self.element = etree.parse(source).getroot()\n\n def tearDown(self):\n unittest.TestCase.tearDown(self)\n\n def testcan_parse(self):\n self.assertTrue(self.reader.can_parse(self.element))\n\n def testparse(self):\n self.reader.parse(self.element)\n obj = self.reader.get()\n\n self.assertEqual(\"Test\", obj.name)\n self.assertEqual('51d62e0261f2449eb41a74e4cb4501e0', obj.uuid)\n\n self.assertEqual(1, len(obj.programs))\n self.assertEqual('dummy', list(obj.programs.aliases())[0])\n\n self.assertAlmostEqual(1234, obj.beam.energy_eV, 4)\n\n self.assertEqual(1, len(obj.detectors))\n det = obj.detectors['bse']\n self.assertAlmostEqual(0, det.limits_eV[0], 4)\n self.assertAlmostEqual(1234, det.limits_eV[1], 4)\n self.assertEqual(1000, det.channels)\n\n self.assertEqual(1, len(obj.limits))\n limits = list(obj.limits.iterclass(ShowersLimit))\n self.assertEqual(1, len(limits))\n self.assertEqual(5678, limits[0].showers)\n\n self.assertEqual(1, len(obj.models))\n models = list(obj.models.iterclass(ELASTIC_CROSS_SECTION))\n self.assertEqual(1, len(models))\n self.assertEqual(ELASTIC_CROSS_SECTION.rutherford, models[0])\n\nclass TestOptionsWriter(unittest.TestCase):\n\n def setUp(self):\n unittest.TestCase.setUp(self)\n\n self.writer = OptionsWriter()\n\n self.obj = Options(name=\"Test\")\n\n self.obj.programs.add(DummyProgram())\n\n self.obj.beam.energy_eV = 1234\n\n self.obj.detectors['bse'] = BackscatteredElectronEnergyDetector(1000, (0, 1234))\n self.obj.limits.add(ShowersLimit(5678))\n self.obj.models.add(ELASTIC_CROSS_SECTION.rutherford)\n\n def tearDown(self):\n unittest.TestCase.tearDown(self)\n\n def testcan_convert(self):\n self.assertTrue(self.writer.can_convert(self.obj))\n\n def testconvert(self):\n self.writer.convert(self.obj)\n element = self.writer.get()\n\n self.assertEqual('Test', element.get('name'))\n\n self.assertEqual(self.obj.uuid, element.get('uuid'))\n\n children = list(element.find('programs'))\n self.assertEqual(1, len(children))\n\n children = list(element.find('beam'))\n self.assertEqual(1, len(children))\n\n children = list(element.find('geometry'))\n self.assertEqual(1, len(children))\n\n children = list(element.find('detectors'))\n self.assertEqual(1, len(children))\n\n children = list(element.find('limits'))\n self.assertEqual(1, len(children))\n\n children = list(element.find('models'))\n self.assertEqual(1, len(children))\n\n def testconvert2(self):\n uuid = self.obj.uuid\n self.writer.convert(self.obj)\n element = self.writer.get()\n self.assertEqual(uuid, element.get('uuid'))\n\nif __name__ == '__main__': # pragma: no cover\n logging.getLogger().setLevel(logging.DEBUG)\n unittest.main()\n","sub_path":"pymontecarlo/fileformat/options/test_options.py","file_name":"test_options.py","file_ext":"py","file_size_in_byte":4924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"367804835","text":"# -*- coding: utf-8 -*-\n\nimport json\nimport urllib\nimport asyncio\nimport argparse\nimport sys\nfrom aiohttp import ClientSession\n\nparser = argparse.ArgumentParser(description='Process arguments.')\nparser.add_argument('-i', '--id', type=str, required=True, help='id name')\nparser.add_argument('-k', '--key', type=str, required=True, help='keywords file')\n\n\nasync def get_app_list(bid, keyword, country, rank):\n\n itunes_url = 'http://itunes.apple.com/search?entity=macSoftware&term={}&country={}'.format(keyword, country)\n async with ClientSession() as session:\n async with session.get(itunes_url) as response:\n r = await response.text()\n j = json.loads(r)\n results = j[\"results\"]\n pos = 0\n for item in results:\n pos += 1\n t_id = item[\"trackId\"]\n if t_id == bid:\n break\n\n r_country = dict()\n r_country[country] = pos\n rank.setdefault(urllib.parse.unquote(keyword), []).append(r_country)\n\n\nif __name__ == '__main__':\n\n args = parser.parse_args()\n print(args)\n bid = args.id\n key_file = args.key\n if not bid or len(bid) == 0 or not key_file or len(key_file) == 0:\n sys.exit(0)\n\n loop = asyncio.get_event_loop()\n tasks = []\n result = dict()\n with open(key_file, encoding='utf-8') as fr:\n\n search_dict = json.loads(fr.read())\n for i in search_dict[\"items\"]:\n country_name = i['country']\n key_list = i[\"keys\"]\n for key in key_list:\n tasks.append(get_app_list(bid, urllib.parse.quote(key), country_name, result))\n loop.run_until_complete(asyncio.wait(tasks))\n loop.close()\n print(result)\n","sub_path":"MyTool/mac_search.py","file_name":"mac_search.py","file_ext":"py","file_size_in_byte":1760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"194464445","text":"from ._builtin import Page, WaitPage\nfrom .models import Constants, MovieSelection\nfrom .forms import MovieForm, MovieResultForm\nfrom django.forms import modelformset_factory\nimport time\n\nMovieFormset = modelformset_factory(MovieSelection, form=MovieForm, fields=('isChecked',), extra=0)\nRemainingMovie = modelformset_factory(MovieSelection, form=MovieResultForm, fields=('embeddedVideo',), extra=0)\n\nclass Consent(Page):\n pass\n\nclass Introduction(Page):\n def before_next_page(self):\n # user has 60 minutes to complete as many pages as possible\n if self.player.id_in_group == 1:\n self.player.isSelecting = True\n else:\n self.player.isSelecting = False\n\nclass ParticipantInfo(Page):\n template_name = 'volleying/ParticipantInfo.html'\n form_model = 'player'\n form_fields = ['first_name']\n\n def error_message(self, values):\n if len(values[\"first_name\"]) == 0:\n return 'Please enter your name'\n\nclass WelcomeInstructions(Page):\n def before_next_page(self):\n self.player.participant.vars['expiry'] = time.time() + 120\n\nclass ChatWaitPage(WaitPage):\n template_name = 'volleying/WaitForChat.html'\n \n def after_all_players_arrive(self):\n self.is_displayed = True\n\nclass Chat(Page):\n def get_timeout_seconds(self):\n return 90\n\nclass Instructions(Page):\n\n def get_timeout_seconds(self):\n return 45\n \nclass WaitForOtherPlayer(WaitPage):\n template_name = 'volleying/WaitPage.html'\n\ndef sort_movies(movie):\n return movie.key\n\nclass Volley(Page):\n form_model = 'group'\n template_name = 'volleying/Volley.html'\n\n def vars_for_template(self):\n remaining_movies = self.player.group.get_remaining_movies()\n\n question_formset = MovieFormset(queryset=MovieSelection.objects.filter(group__exact=self.player.group).filter(isRemaining__exact=True))\n for (form, model) in zip(question_formset, remaining_movies):\n form.setLabel(model.description)\n\n return {\n 'movie_formset': question_formset\n }\n \n def before_next_page(self):\n self.group.numberVolleys +=1\n self.player.isSelecting = False\n self.player.get_others_in_group()[0].isSelecting = True\n self.group.volley = self.group.volley + \"[\" + \" \".join(self.group.get_remaining_movie_names()) + \"] \"\n\n all_movies = MovieSelection.objects.filter(group__exact=self.player.group)\n remaining_movies = all_movies.filter(isRemaining__exact=True)\n\n submitted_data = self.form.data\n \n movies_by_id = {mov.pk: mov for mov in remaining_movies}\n \n for i in range(len(remaining_movies)):\n input_prefix = 'form-%d-' % i\n mov_id1 = int(submitted_data[input_prefix + 'id'])\n isChecked = submitted_data.get(input_prefix + 'isChecked')\n\n mov = movies_by_id[mov_id1]\n\n if isChecked:\n mov.isChecked = True\n\n if not self.group.eliminateNegative:\n if not mov.isChecked:\n mov.isRemaining = False\n else: \n mov.isRemaining = True\n mov.isChecked = False\n else:\n if mov.isChecked:\n mov.isRemaining = False\n mov.isChecked = True\n\n mov.save()\n\n if self.timeout_happened:\n self.player.get_partner().timed_out = True\n self.player.timed_out = True\n\n def get_timeout_seconds(self):\n return 120\n \n def error_message(self, values):\n remaining_movies = self.player.group.get_remaining_movies()\n submitted_data = self.form.data\n num_checked = 0\n\n for i in range(len(remaining_movies)):\n input_prefix = 'form-%d-' % i\n isChecked = submitted_data.get(input_prefix + 'isChecked')\n\n if isChecked:\n num_checked+=1 \n\n if (len(remaining_movies) == num_checked):\n return 'You cannot select every movie trailer'\n elif (num_checked == 0):\n return 'You must select at least one movie trailer'\n else:\n pass\n\nclass VolleyPlayer1(Volley):\n def is_displayed(self):\n return (not self.player.timed_out) and self.group.volleying() and (self.player.id_in_group == 1)\n\nclass VolleyPlayer2(Volley):\n def is_displayed(self):\n return (not self.player.timed_out) and self.group.volleying() and (self.player.id_in_group == 2)\n\nclass TrailerIntro(Page):\n timeout_seconds = 15\n\n def vars_for_template(self):\n self.player.madeFinalDecision = not self.player.isSelecting\n self.player.selectedMovie = self.player.group.last_movie_name()\n\n return {\n \"finalMovie\": self.player.selectedMovie\n }\n\n def is_displayed(self):\n return not self.player.timed_out\n\n def before_next_page(self):\n self.player.selectedMovie = self.player.group.last_movie_name()\n\n\nclass Results(Page):\n def get_timeout_seconds(self):\n return 200\n \n def is_displayed(self):\n return not self.player.timed_out\n\n def vars_for_template(self):\n remaining_movies = self.player.group.get_remaining_movies()\n question_formset = RemainingMovie(queryset=MovieSelection.objects.filter(group__exact=self.player.group).filter(isRemaining__exact=True))\n\n for (form, model) in zip(question_formset, remaining_movies):\n form.generateVideoHtml(model.embeddedVideo)\n\n return {\n 'movie_formset': question_formset\n }\n \nclass FollowUpQuestions(Page):\n form_model = 'player'\n form_fields = ['satisfied_trailer', 'satisfied_process', 'satisfied_treated', 'willing_to', 'comment']\n \n def is_displayed(self):\n return not self.player.timed_out\n\n def before_next_page(self):\n if self.timeout_happened:\n self.player.timed_out = True\n\nclass ManipulationChecks(Page):\n form_fields = ['manip_question']\n\nclass Demographics(Page):\n form_model = 'player'\n form_fields = ['sonaID', 'age', 'race', 'gender']\n \n def is_displayed(self):\n return not self.player.timed_out\n\n def before_next_page(self):\n if self.timeout_happened:\n self.player.timed_out = True\n\nclass Conclusion(Page):\n pass\n\n\npage_sequence = [\n Consent,\n Introduction,\n ParticipantInfo,\n WelcomeInstructions,\n ChatWaitPage,\n Chat,\n Instructions,\n VolleyPlayer1,\n WaitForOtherPlayer,\n VolleyPlayer2,\n WaitForOtherPlayer,\n VolleyPlayer1,\n WaitForOtherPlayer,\n VolleyPlayer2,\n WaitForOtherPlayer,\n VolleyPlayer1,\n WaitForOtherPlayer,\n VolleyPlayer2,\n WaitForOtherPlayer,\n VolleyPlayer1,\n WaitForOtherPlayer,\n VolleyPlayer2,\n WaitForOtherPlayer,\n VolleyPlayer1,\n WaitForOtherPlayer,\n VolleyPlayer2,\n WaitForOtherPlayer,\n VolleyPlayer1,\n WaitForOtherPlayer,\n VolleyPlayer2,\n WaitForOtherPlayer,\n VolleyPlayer1,\n WaitForOtherPlayer,\n VolleyPlayer2,\n WaitForOtherPlayer,\n TrailerIntro,\n Results,\n FollowUpQuestions,\n Demographics,\n Conclusion\n]\n","sub_path":"volleying/pages.py","file_name":"pages.py","file_ext":"py","file_size_in_byte":7165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"370435605","text":"import cv2\nimport numpy as np\nfrom matplotlib.pyplot import plot, show, draw, clf, hist, figure\nimport time\nimport sys\n\ndef avg_hist(hist, length):\n val = 0\n count = 0\n for i in range(length):\n count += hist[i]\n val += i * hist[i]\n return val/count\n\ndef std_dev_hist(hist, length):\n avg = avg_hist(hist, length)\n count = 0\n sqerr = 0\n for i in range(length):\n count += hist[i]\n sqerr += hist[i] * (avg-i)**2\n return (sqerr / count)**0.5\n\ndef lp_filter_array(new, old, alpha=0.05):\n res = []\n for x in range(len(new)):\n res.append(new[x]*alpha + old[x]*(1.0 - alpha))\n return res\n\ndef clamp(n, minn, maxn):\n return max(min(maxn, n), minn) \n \ncap = cv2.VideoCapture(\"./bitbuckets.mp4\")\n# cap = cv2.VideoCapture(\"./dropshot.mp4\")\noutput = cv2.VideoWriter(\"./output.mp4\", int(cap.get(cv2.CAP_PROP_FOURCC)),\n int(cap.get(cv2.CAP_PROP_FPS)), (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))))\n\nprint(\"FourCC: {0}\".format(int(cap.get(cv2.CAP_PROP_FOURCC))))\nprint(\"FPS: {0}\".format(int(cap.get(cv2.CAP_PROP_FPS))))\nprint(\"OpenCV Version: {0}\".format(cv2.__version__))\n\noldtime = time.time()\nfps = 0.0\n\n# avg_vals = [70,180,220] #for dropshot\n# avg_stds = [10, 20, 10]\navg_vals = [80,60,180] #for bitbuckets\navg_stds = [5, 15, 20]\nupper = np.array([int(avg_vals[x] + 2.5*avg_stds[x]) for x in range(3)])\nlower = np.array([int(avg_vals[x] - 2.5*avg_stds[x]) for x in range(3)])\n\n#plus_avg = avg_stds\n#med_avg = avg_vals\n#minus_avg = avg_stds\n\nhue_l=[80]\nsat_l=[60]\nvals_l=[180]\n\nwhile(True):\n ret, frame = cap.read()\n frame = cv2.pyrDown(frame)\n\n hsv = cv2.blur(cv2.cvtColor(frame, cv2.COLOR_BGR2HSV), (5,5))\n\n # cv2.imshow('hsv', hsv)\n\n hsvthresh = cv2.inRange(hsv, lower, upper)\n mask = cv2.bitwise_and(hsv, hsv, mask=hsvthresh)\n\n cv2.imshow('thresh', hsvthresh)\n cv2.imshow('mask', mask)\n\n im2, contours, hierarchy = cv2.findContours(hsvthresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)\n\n goalx = -1\n goaly = -1\n\n for contour in contours:\n moments = cv2.moments(contour)\n\n if moments['m00'] > 0:\n area = cv2.contourArea(contour)\n perim = cv2.arcLength(contour, True)\n\n if area < 100:\n continue\n\n hull = cv2.convexHull(contour)\n hullarea = cv2.contourArea(hull)\n rect = cv2.minAreaRect(contour)\n box = cv2.boxPoints(rect)\n box = np.int0(box)\n boxarea = cv2.contourArea(box)\n\n aspect = rect[1][1]/rect[1][0]\n\n adjusted_rect = rect\n adjusted_rect = ((rect[0][0], rect[0][1]-rect[1][0]*0.15), (adjusted_rect[1][0] * 0.40, adjusted_rect[1][1] * 0.40), rect[2])\n adjusted_box = cv2.boxPoints(adjusted_rect)\n adjusted_box = np.int0(adjusted_box)\n adjusted_mask = np.zeros(hsvthresh.shape,np.uint8)\n cv2.drawContours(adjusted_mask,[adjusted_box],0,255,-1)\n adjusted_mask = cv2.bitwise_not(adjusted_mask, adjusted_mask)\n\n mask = np.zeros(hsvthresh.shape,np.uint8)\n cv2.drawContours(mask,[contour],0,255,-1)\n # pixelpoints = np.transpose(np.nonzero(mask))\n # cv2.imshow('points', mask)\n adjusted_mask = cv2.bitwise_and(adjusted_mask, mask)\n # cv2.imshow('adjusted', cv2.bitwise_xor(adjusted_mask, mask))\n present = not(np.bitwise_xor(adjusted_mask,mask).any())\n\n if present and aspect > 0.4 and aspect < 2.5 and hullarea > 500:\n goalx = moments['m10']/moments['m00']\n goaly = moments['m01']/moments['m00']\n cv2.drawContours(frame,[adjusted_box],0,(0,0,255),2)\n cv2.putText(frame, 'AREA:{0:.2f}'.format(hullarea), (10,50), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 2, cv2.LINE_AA)\n hist_hue = cv2.calcHist([hsv],[0],mask,[180],[0,180])\n hist_sat = cv2.calcHist([hsv],[1],mask,[256],[0,256])\n hist_val = cv2.calcHist([hsv],[2],mask,[256],[0,256])\n\n # compute cumulative histogram\n hist_hue_cs = np.cumsum(hist_hue)\n hist_hue_cs = hist_hue_cs / hist_hue_cs[179]\n hist_sat_cs = np.cumsum(hist_sat)\n hist_sat_cs = hist_sat_cs / hist_sat_cs[255]\n hist_val_cs = np.cumsum(hist_val)\n hist_val_cs = hist_val_cs / hist_val_cs[255]\n \n # compute the quantiles\n #low=0.18\n #med=0.5\n #high=0.84\n #hue_low = np.amin(np.where(hist_hue_cs >=low))\n #sat_low = np.amin(np.where(hist_sat_cs >=low))\n #val_low = np.amin(np.where(hist_val_cs >=low))\n #hue_med = np.amin(np.where(hist_hue_cs >=med))\n #sat_med = np.amin(np.where(hist_sat_cs >=med))\n #val_med = np.amin(np.where(hist_val_cs >=med))\n #hue_high = np.amin(np.where(hist_hue_cs >=high))\n #sat_high = np.amin(np.where(hist_sat_cs >=high))\n #val_high = np.amin(np.where(hist_val_cs >=high))\n ## unfortunately this command does not work with mask\n ## p25, p50, p75 = np.percentile(img, (25,50,75))\n \n ## compute the boundaries and keep them wide\n #hue_plus = max(hue_high-hue_med, 5)\n #hue_minus = max(hue_med-hue_low, 5)\n #sat_plus = max(sat_high-sat_med, 10)\n #sat_minus = max(sat_med-sat_low, 10)\n #val_plus = max(val_high-val_med, 10)\n #val_minus = max(val_med-val_low, 10)\n\n #plus_avg = lp_filter_array([hue_plus, sat_plus, val_plus], plus_avg, 0.05)\n #med_avg = lp_filter_array([hue_med, sat_med, val_med], med_avg, 0.05)\n #minus_avg = lp_filter_array([hue_minus, sat_minus, val_minus], minus_avg, 0.05)\n\n #upper = np.array([int(med_avg[0] + 2.5*plus_avg[0]), int(med_avg[1] + 2.5*plus_avg[1]), int(med_avg[2] + 2.5*plus_avg[2] ) ])\n #lower = np.array([int(med_avg[0] - 2.5*minus_avg[1]), int(med_avg[1] - 2.5*minus_avg[1]), int(med_avg[2] - 2.5*minus_avg[2] ) ])\n #print(upper, lower)\n \n\n avg_vals = lp_filter_array(\n [clamp(avg_hist(hist_hue, 180)[0], 82, 98), \n clamp(avg_hist(hist_sat, 256)[0] , 60, 95),\n clamp(avg_hist(hist_val, 256)[0], 150, 230)],\n avg_vals)\n avg_stds = lp_filter_array(\n [max(std_dev_hist(hist_hue, 180)[0], 5),\n max(std_dev_hist(hist_sat, 256)[0], 10),\n max(std_dev_hist(hist_val, 256)[0], 15)],\n avg_stds)\n upper = np.array([int(avg_vals[x] + 2.5*avg_stds[x]) for x in range(3)])\n lower = np.array([int(avg_vals[x] - 2.5*avg_stds[x]) for x in range(3)])\n print (avg_vals, avg_stds)\n \n hue_l.append(avg_vals[0])\n sat_l.append(avg_vals[1])\n vals_l.append(avg_vals[2])\n \n #clf()\n #plot(hist_hue, color='r')\n #plot(hist_sat, color='g')\n #plot(hist_val, color='b')\n #show(block=False)\n \n for p in range(len(hull)):\n p1 = (hull[p-1][0][0],hull[p-1][0][1])\n p2 = (hull[p][0][0], hull[p][0][1])\n cv2.line(frame, p1, p2, (255,0,0), 2)\n\n cv2.putText(frame, 'X:{0:.2f}'.format(goalx), (10,20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 2, cv2.LINE_AA)\n cv2.putText(frame, 'Y:{0:.2f}'.format(goaly), (10,35), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 2, cv2.LINE_AA)\n cv2.imshow('frame', frame)\n output.write(frame)\n\n currtime = time.time()\n fps = 0.9 * fps + 0.1 * (1 / (currtime - oldtime))\n #print \"Framerate: {0}\".format(fps)\n oldtime = currtime\n\n if cv2.waitKey(5) & 0xFF == ord('q'):\n break\n\nfigure()\nhist(np.asarray(hue_l))\nfigure()\nhist(np.asarray(sat_l))\nfigure()\nhist(np.asarray(vals_l))\nshow();\n\n# reasonable values for average hue, sat and vals are\n# 77-101 max at 93 limit 82-98\n# 62-105 max at 72 limit 60-95\n# 150-230 max at 190 limit 150-230\n# Start was [80,60,180]\n\ncap.release()\noutput.release()\ncv2.destroyAllWindows()\n","sub_path":"2017 Pipeline/tower4uu.py","file_name":"tower4uu.py","file_ext":"py","file_size_in_byte":8528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"12091422","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as f\nimport numpy as np\n\n\nclass Uniform:\n\n def __init__(self, args):\n self.args = args\n self.device = torch.device('cpu')\n self.noise_distrib = torch.distributions.one_hot_categorical.OneHotCategorical(\n torch.tensor([1 / self.args.noise_dim for _ in range(self.args.noise_dim)]))\n\n def sample(self, state, test_mode):\n return self.noise_distrib.sample().to(self.device)\n\n def update_returns(self, state, noise, returns, test_mode, t):\n pass\n\n def to(self, device):\n self.device = device\n\n\nclass RNN(nn.Module):\n\n def __init__(self, input_shape, args):\n super(RNN, self).__init__()\n self.args = args\n\n self.fc1 = nn.Linear(input_shape, args.rnn_hidden_dim)\n # self.rnn = nn.GRUCell(args.rnn_hidden_dim, args.rnn_hidden_dim)\n self.rnn = nn.GRU(\n input_size=args.rnn_hidden_dim,\n num_layers=1,\n hidden_size=args.rnn_hidden_dim,\n batch_first=True,\n )\n\n self.fc2 = nn.Linear(args.rnn_hidden_dim, args.n_actions)\n\n def init_hidden(self):\n # make hidden states on same device as model\n return self.fc1.weight.new(1, self.args.rnn_hidden_dim).zero_()\n\n def forward(self, obs, hidden_state):\n if len(hidden_state.shape) == 2:\n hidden_state = hidden_state.unsqueeze(0)\n\n obs_c = obs.view(-1, obs.shape[-1])\n x = f.relu(self.fc1(obs_c))\n x = x.reshape(obs.shape[0], obs.shape[1], -1)\n\n h_in = hidden_state\n gru_out, _ = self.rnn(x, h_in)\n gru_out_c = gru_out.reshape(-1, gru_out.shape[-1])\n q = self.fc2(gru_out_c)\n q = q.reshape(obs.shape[0], obs.shape[1], -1)\n\n return q, gru_out\n\n\nclass MLP(nn.Module):\n\n def __init__(self, args):\n super(MLP, self).__init__()\n self.args = args\n self.fc = nn.Linear(args.rnn_hidden_dim, args.n_actions)\n\n def forward(self, hidden_state):\n q = self.fc(hidden_state)\n return q\n\n\nclass MLP_2(nn.Module):\n\n def __init__(self, args):\n super(MLP_2, self).__init__()\n self.args = args\n self.fc_1 = nn.Linear(args.rnn_hidden_dim, args.rnn_hidden_dim)\n self.fc_2 = nn.Linear(args.rnn_hidden_dim, args.n_actions)\n\n def forward(self, hidden_state):\n h1 = f.relu(self.fc_1(hidden_state))\n q = self.fc_2(h1)\n return q\n\n\nclass Critic(nn.Module):\n\n def __init__(self, input_shape, args):\n super(Critic, self).__init__()\n self.args = args\n self.fc1 = nn.Linear(input_shape, args.critic_dim)\n self.fc2 = nn.Linear(args.critic_dim, args.critic_dim)\n self.fc3 = nn.Linear(args.critic_dim, 1)\n\n def forward(self, inputs):\n x = f.relu(self.fc1(inputs))\n x = f.relu(self.fc2(x))\n q = self.fc3(x)\n return q\n","sub_path":"CDS_GRF/network/base_net.py","file_name":"base_net.py","file_ext":"py","file_size_in_byte":2899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"92179243","text":"import pigpio\nimport logging\n\n################################################################\n# CLASS DEFINITION: CD4094\n\nclass CD4094():\n def __init__(self, pins=[17,27,22,23], channels=8):\n logging.info('[CD4094] Initializing new CD4094 instance.')\n logging.debug('[CD4094] Spinning up pigpio instance.')\n self.pi = pigpio.pi()\n self.pins = pins\n\n if len(self.pins) == 4:\n self.strobePin, self.dataPin, self.clockPin, self.enablePin = self.pins\n else:\n raise Exception('pins argument expects a list of 4 GPIO pins: strobe, data, clock, and enable.')\n \n if self.strobePin < 1 or self.strobePin > 40 or self.dataPin < 1 or self.dataPin > 40 or self.clockPin < 1 or self.clockPin > 40 or self.enablePin < 1 or self.enablePin > 40:\n raise Exception('GPIO pins must be positive integers from 1-40.')\n\n if channels is None or type(channels) != int:\n raise Exception('channels must be an integer')\n elif channels <= 0:\n raise Exception('channels must be greater than 0')\n\n self.channels = channels\n\n #logging.debug('[CD4094] Initializing pins.')\n for pin in self.pins:\n self.pi.set_mode(pin, pigpio.OUTPUT)\n self.pi.write(pin, 0)\n self.reset()\n self.enable()\n\n def enable(self):\n #logging.debug('[CD4094] Enabling output.')\n self.pi.write(self.enablePin, 1)\n\n def disable(self):\n #logging.debug('[CD4094] Disabling output.')\n self.pi.write(self.enablePin, 0)\n\n def reset(self):\n #logging.debug('[CD4094] Resetting state.')\n self.pi.write(self.dataPin, 0)\n for i in range(self.channels):\n self.pi.write(self.clockPin, 1)\n self.pi.write(self.clockPin, 0)\n self.pi.write(self.strobePin, 1)\n self.pi.write(self.strobePin, 0)\n\n def update(self, data):\n #logging.debug('[CD4094] Updating state: %s' % repr(data))\n for i in range(self.channels):\n try:\n bit = data[self.channels - i - 1] & 0b1\n except:\n bit = 0\n self.pi.write(self.dataPin, bit)\n self.pi.write(self.clockPin, 1)\n self.pi.write(self.clockPin, 0)\n self.pi.write(self.strobePin, 1)\n self.pi.write(self.strobePin, 0)\n\n def stop(self):\n logging.info('[CD4094] Stopping.')\n self.disable()\n self.reset()","sub_path":"CD4094/CD4094.py","file_name":"CD4094.py","file_ext":"py","file_size_in_byte":2234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"140253189","text":"import scrapy\nfrom book.items import book_tag\nimport time\n\n\nclass tag_spider(scrapy.Spider):\n name = \"tag_spider\"\n\n def start_requests(self):\n urls = [\n 'https://book.douban.com/tag/?view=type&icn=index-sorttags-all'\n ]\n for url in urls:\n yield scrapy.Request(url=url, callback=self.parse)\n\n def parse(self, response):\n # body = response.body\n td = response.xpath(\"//table[@class='tagCol']//td\")\n for s2 in td.getall():\n date = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())\n tag = book_tag()\n str = scrapy.Selector(text=s2)\n tag['tag_name'] = str.xpath(\"//a/text()\").get()\n tag['spider_url'] = str.xpath(\"//a/@href\").get()\n tag['tag_count'] = str.xpath(\"//b/text()\").get()[1:-1]\n tag['create_time'] = date\n tag['last_update_time'] = date\n yield tag\n","sub_path":"book/book/spiders/tag_spider.py","file_name":"tag_spider.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"185079723","text":"from nokia import NokiaAuth\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output, State\nfrom dash_app import dash_app\nimport dash_core_components as dcc\nfrom lib.withingsAPI import withings_connected, connect_withings_link\nfrom oura import OuraOAuth2Client\nfrom lib.withingsAPI import save_withings_token\nimport configparser\nimport re\nimport time\n\nfrom nokia import NokiaAuth, NokiaApi\n\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\n\nclient_id = config.get('withings', 'client_id')\nclient_secret = config.get('withings', 'client_secret')\nredirect_uri = config.get('withings', 'redirect_uri')\n\nauth_client = NokiaAuth(client_id, client_secret, callback_uri=redirect_uri)\n\nlayout = html.Div(id='withings-auth-canvas', children=[\n html.Div(id='withings-token-refresh', style={'display': 'none'}),\n dcc.Loading(html.Div(id='withings-auth-layout'))\n])\n\n\ndef test_withings_connection():\n time.sleep(3)\n if not withings_connected():\n return html.Div(style={'textAlign': 'center'}, className='twelve columns', children=[\n html.A(html.Button('Connect'),\n href=connect_withings_link(auth_client))\n ])\n else:\n return html.I('Withings Connected!')\n\n\ndef generate_withings_auth():\n return [\n html.Div(id='authorize-withings-container', className='twelve columns maincontainer',\n children=[\n html.H4('Withings Connection'),\n html.Div(id='withings-auth', children=[test_withings_connection()]\n ), ])]\n\n\n# Callback for authorizing withings tokens\n@dash_app.callback(Output('withings-token-refresh', 'children'),\n [Input('url', 'search')],\n [State('url', 'pathname')])\ndef update_tokens(token, pathname):\n if 'withings' in pathname:\n dash_app.server.logger.debug(\n '*******************************************************************************************************************')\n if token:\n auth_code = re.findall('=(?<=\\=)(.*?)(?=\\&)', token)[0]\n dash_app.server.logger.debug(\n 'AUTH CODE = {}'.format(auth_code))\n\n creds = auth_client.get_credentials(auth_code)\n dash_app.server.logger.debug(\n 'CREDS = {}'.format(creds))\n\n save_withings_token(creds)\n\n\n# Main Dashboard Generation Callback\n@dash_app.callback(\n Output('withings-auth-layout', 'children'),\n [Input('withings-auth-canvas', 'children')]\n)\ndef settings_dashboard(dummy):\n return generate_withings_auth()\n","sub_path":"pages/authorize/withings.py","file_name":"withings.py","file_ext":"py","file_size_in_byte":2618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"630407329","text":"# -*- coding: utf-8 -*-\n\"\"\"\nAn implementation of the policyValueNet in PyTorch\nTested in PyTorch 0.2.0 and 0.3.0\n@author: Junxiao Song\n\"\"\"\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nimport numpy as np\n\n\ndef set_learning_rate(optimizer, lr):\n \"\"\"Sets the learning rate to the given value\"\"\"\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n\n\nclass Net(nn.Module):\n \"\"\"policy-value network module\"\"\"\n #nn.BatchNorm1d(n_hidden_1)\n def __init__(self, in_dim, n_hidden_1, n_hidden_2, out_dim):\n super(Net, self).__init__()\n self.layer1 = nn.Sequential(nn.Linear(in_dim, n_hidden_1),\n nn.ReLU())\n self.layer2 = nn.Sequential(nn.Linear(n_hidden_1, n_hidden_2),\n nn.ReLU())\n self.layer3 = nn.Sequential(nn.Linear(n_hidden_2, out_dim),\n # nn.Sigmoid())\n nn.ReLU())\n\n def forward(self, x):\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n return x\n\n\nclass PolicyValueNet():\n \"\"\"policy-value network \"\"\"\n def __init__(self, in_dim, n_hidden_1, n_hidden_2, out_dim,\n model_file=None, use_gpu=True):\n self.use_gpu = torch.cuda.is_available()\n self.in_dim = in_dim\n self.n_hidden_1 = n_hidden_1\n self.n_hidden_2 = n_hidden_2\n self.out_dim = out_dim\n\n self.l2_const = 1e-4 # coef of l2 penalty\n # the policy value net module\n if self.use_gpu:\n self.policy_value_net = Net(in_dim, n_hidden_1,n_hidden_2,out_dim).cuda()\n else:\n self.policy_value_net = Net(in_dim, n_hidden_1,n_hidden_2,out_dim)\n self.optimizer = optim.Adam(self.policy_value_net.parameters(),\n weight_decay=self.l2_const)\n\n if model_file:\n net_params = torch.load(model_file)\n self.policy_value_net.load_state_dict(net_params)\n\n def policy_value(self, state_batch):\n \"\"\"\n input: a batch of states\n output: a batch of action probabilities and state values\n \"\"\"\n if self.use_gpu:\n state_batch = Variable(torch.FloatTensor(state_batch).cuda())\n log_act_probs = self.policy_value_net(state_batch)\n act_probs = log_act_probs.data.cpu().numpy().flatten()\n\n return act_probs\n else:\n state_batch = Variable(torch.FloatTensor(state_batch))\n log_act_probs = self.policy_value_net(state_batch)\n act_probs = log_act_probs.data.numpy().flatten()\n\n return act_probs\n\n def train_step(self, state_batch, mcts_probs, lr):\n \"\"\"perform a training step\"\"\"\n # wrap in Variable\n if self.use_gpu:\n state_batch = Variable(torch.FloatTensor(state_batch).cuda())\n mcts_probs = Variable(torch.FloatTensor(mcts_probs).cuda())\n else:\n state_batch = Variable(torch.FloatTensor(state_batch))\n mcts_probs = Variable(torch.FloatTensor(mcts_probs))\n\n # zero the parameter gradients\n self.optimizer.zero_grad()\n # set learning rate\n set_learning_rate(self.optimizer, lr)\n\n # forward\n log_act_probs = self.policy_value_net(state_batch)\n # define the loss = (z - v)^2 - pi^T * log(p) + c||theta||^2\n # Note: the L2 penalty is incorporated in optimizer\n policy_loss = torch.sum(torch.abs(mcts_probs-log_act_probs.squeeze()))\n loss = policy_loss\n # backward and optimize\n loss.backward()\n self.optimizer.step()\n # calc policy entropy, for monitoring only\n\n # return loss.data[0], entropy.data[0]\n # for pytorch version >= 0.5 please use the following line instead.\n return loss.item(), 0\n\n def get_policy_param(self):\n net_params = self.policy_value_net.state_dict()\n return net_params\n\n def save_model(self, model_file):\n \"\"\" save model params to file \"\"\"\n net_params = self.get_policy_param() # get model params\n torch.save(net_params, model_file)\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"588679319","text":"_# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 24 11:18:24 2019\n\n@author: ciullo\n\"\"\"\n\nfrom ema_workbench import (MultiprocessingEvaluator,\n Scenario, SequentialEvaluator, Policy)\n\nfrom ema_workbench.em_framework.samplers import sample_uncertainties, sample_levers\nfrom ema_workbench.util import ema_logging\nimport pickle\nimport time\nimport pandas as pd\nfrom problem_formulation_4b import get_model_for_problem_formulation\n\n\ndef build_Pol(df, pf):\n policies = []\n for i, row in df.iterrows():\n name = '{}_{}'.format(pf, str(i))\n decision = {lever: row[lever] for lever in df.columns}\n policies.append(Policy(name=name, **decision))\n return policies\n\nif __name__ == '__main__':\n ema_logging.log_to_stderr(ema_logging.INFO)\n\n pf = 'disaggregated'\n\n dike_model = get_model_for_problem_formulation(pf)[0]\n \n average_values = {'Bmax': 150, 'Brate': 1.5, 'pfail': 0.5}\n scen1 = {}\n\n for key in dike_model.uncertainties:\n dikename, unc = key.name.split('_')\n scen1.update({key.name: average_values[unc]})\n\n ref_scenario = Scenario('reference', **scen1)\n policies = sample_levers(dike_model, 500)\n\n # No dike increase, none of the rfr project is selected, no damage\n # reduction:\n dike_increase = dict(zip((91, 101, 201, 301, 401, 501),\n (0, 0, 0, 0, 0, 0)))\n\n names = {'DikeIncrease': 0, 'rfr': 0,\n '201.0': 0, '401.0': 0}\n ## zero policy:\n pol0 = {}\n\n for key in dike_model.levers:\n s1, s2 = key.name.split('_')\n if s2 == 'DikeIncrease':\n branch = s1.split('.')[0]\n pol0.update({key.name: dike_increase[int(branch)]})\n\n else:\n pol0.update({key.name: names[s2]})\n\n policy0 = Policy('Policy 0', **pol0)\n policies = [policy0]\n# pf1\n# df = pd.read_excel('./results_pf2_100000nfe____.xlsx'\n# )[[l.name for l in dike_model.levers]]\n# policies.extend(build_Pol(df, 'pf1'))\n\n## pf2\n# df = pd.read_excel('./results_pf1_100000nfe_NSB1e6_0.xlsx'\n# )[[l.name for l in dike_model.levers]]\n# policies.extend(build_Pol(df, 'pf2'))\n#\n#### pf3\n# df = pd.read_excel('./results_pf3_100000nfe.xlsx'\n# )[[l.name for l in dike_model.levers]]\n# policies.extend(build_Pol(df, 'pf3'))\n\n\n\n## SIMULATION:\n## single run\n# start = time.time()\n# dike_model.run_model(ref_scenario, policies[1])\n# end = time.time() - start\n# print(end)\n# results = dike_model.outcomes_output\n\n## series run\n# with SequentialEvaluator(dike_model) as evaluator:\n# results = evaluator.perform_experiments(ref_scenario, policies[1])\n\n## multiprocessing\n# with MultiprocessingEvaluator(dike_model, n_processes = 3) as evaluator:\n# results = evaluator.perform_experiments(ref_scenario, policies)\n###\n#### save results\n# with open(\"./results//FirstDecentResults/simulation_noncooppolsx100.p\".format(pf), \"wb\") as f:\n# pickle.dump(results, f)\n \n \n \n \n \n \n \n\n","sub_path":"dike_model_simulation.py","file_name":"dike_model_simulation.py","file_ext":"py","file_size_in_byte":3076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"154718501","text":"import Sending\nimport csv\nimport math\nimport numpy as np\nfrom timeit import default_timer as timer\nfrom numba import vectorize\n@vectorize([\"float32(float32, float32)\"], target='cuda')\ndef readcsv(filename):\t\n file = open(filename, \"r\")\n reader = csv.reader(file, delimiter=\";\")\n rownum = 0\t\n a = []\n\n for row in reader:\n a.append (row)\n rownum += 1\n\n return a\n@vectorize([\"float32(float32, float32)\"], target='cuda')\ndef seperate(b):\n n=[]\n for i in b:\n for j in i:\n l=j.split(',')\n n.append(l)\n return n\nb=readcsv('C:\\\\Users\\\\akhil\\\\Downloads\\\\chikku\\\\Dataset\\\\MainDataSet.csv')\ntemp=len(b)\nprint(b[0])\ns=seperate(b)\ntotal_entered=0\ntotal_completed=0\nl=[]\n\"\"\"for i in [8,0,1,3,7,4]:\n li=[]\n for j in range(1,temp):\n if(s[j][i] not in li):\n li.append(s[j][i])\n li.sort()\n l.append(li)\ndist={'Andhra Pradesh':['ANANTAPUR', 'CHITTOOR', 'EAST GODAVARI', 'GUNTUR', 'KADAPA', 'KRISHNA',\n 'KURNOOL', 'PRAKASAM', 'SPSR NELLORE', 'SRIKAKULAM', 'VISAKHAPATANAM',\n 'VIZIANAGARAM', 'WEST GODAVARI'],\n 'Andaman and Nicobar Islands':['NICOBARS', 'NORTH AND MIDDLE ANDAMAN', 'SOUTH ANDAMANS'],\n 'Arunachal Pradesh':['ANJAW', 'CHANGLANG', 'DIBANG VALLEY', 'EAST KAMENG', 'EAST SIANG',\n 'KURUNG KUMEY', 'LOHIT', 'LONGDING', 'LOWER DIBANG VALLEY',\n 'LOWER SUBANSIRI', 'NAMSAI', 'PAPUM PARE', 'TAWANG', 'TIRAP',\n 'UPPER SIANG', 'UPPER SUBANSIRI', 'WEST KAMENG', 'WEST SIANG'],\n 'Assam':['BAKSA', 'BARPETA', 'BONGAIGAON', 'CACHAR', 'CHIRANG', 'DARRANG', 'DHEMAJI',\n 'DHUBRI', 'DIBRUGARH', 'DIMA HASAO', 'GOALPARA', 'GOLAGHAT', 'HAILAKANDI',\n 'JORHAT', 'KAMRUP', 'KAMRUP METRO', 'KARBI ANGLONG', 'KARIMGANJ', 'KOKRAJHAR',\n 'LAKHIMPUR', 'MARIGAON', 'NAGAON', 'NALBARI', 'SIVASAGAR', 'SONITPUR', 'TINSUKIA', 'UDALGURI'],\n 'Bihar':['ARARIA', 'ARWAL', 'AURANGABAD', 'BANKA', 'BEGUSARAI', 'BHAGALPUR', 'BHOJPUR'\n , 'BUXAR', 'DARBHANGA', 'GAYA', 'GOPALGANJ', 'JAMUI', 'JEHANABAD', 'KAIMUR (BHABUA)',\n 'KATIHAR', 'KHAGARIA', 'KISHANGANJ', 'LAKHISARAI', 'MADHEPURA', 'MADHUBANI', 'MUNGER',\n 'MUZAFFARPUR', 'NALANDA', 'NAWADA', 'PASHCHIM CHAMPARAN', 'PATNA', 'PURBI CHAMPARAN',\n 'PURNIA', 'ROHTAS', 'SAHARSA', 'SAMASTIPUR', 'SARAN', 'SHEIKHPURA', 'SHEOHAR', 'SITAMARHI',\n 'SIWAN', 'SUPAUL', 'VAISHALI'],\n 'Chhattisgarh':['BALOD', 'BALODA BAZAR', 'BALRAMPUR', 'BASTAR', 'BEMETARA', 'BIJAPUR', 'BILASPUR',\n 'DANTEWADA', 'DHAMTARI', 'DURG', 'GARIYABAND', 'JANJGIR-CHAMPA', 'JASHPUR', 'KABIRDHAM',\n 'KANKER', 'KONDAGAON', 'KORBA', 'KOREA', 'MAHASAMUND', 'MUNGELI', 'NARAYANPUR', 'RAIGARH',\n 'RAIPUR', 'RAJNANDGAON', 'SUKMA', 'SURAJPUR', 'SURGUJA'],\n 'Dadra and Nagar Haveli':['DADRA AND NAGAR HAVELI'],\n 'Goa':['NORTH GOA', 'SOUTH GOA'],\n 'Gujarat':['AHMADABAD', 'AMRELI', 'ANAND', 'BANAS KANTHA', 'BHARUCH', 'BHAVNAGAR', 'DANG', 'DOHAD',\n 'GANDHINAGAR', 'JAMNAGAR', 'JUNAGADH', 'KACHCHH', 'KHEDA', 'MAHESANA', 'NARMADA', 'NAVSARI',\n 'PANCH MAHALS', 'PATAN', 'PORBANDAR', 'RAJKOT', 'SABAR KANTHA', 'SURAT', 'SURENDRANAGAR', 'TAPI',\n 'VADODARA', 'VALSAD'],\n 'Chandigarh':['CHANDIGARH'],\n 'Haryana':['AMBALA', 'BHIWANI', 'FARIDABAD', 'FATEHABAD', 'GURGAON', 'HISAR', 'JHAJJAR', 'JIND', 'KAITHAL',\n 'KARNAL', 'KURUKSHETRA', 'MAHENDRAGARH', 'MEWAT', 'PALWAL', 'PANCHKULA', 'PANIPAT', 'REWARI',\n 'ROHTAK', 'SIRSA', 'SONIPAT', 'YAMUNANAGAR'],\n 'Himachal Pradesh':['BILASPUR', 'CHAMBA', 'HAMIRPUR', 'KANGRA', 'KINNAUR', 'KULLU', 'LAHUL AND SPITI',\n 'MANDI', 'SHIMLA', 'SIRMAUR', 'SOLAN', 'UNA'],\n 'Jammu and Kashmir':['ANANTNAG', 'BADGAM', 'BANDIPORA', 'BARAMULLA', 'DODA', 'GANDERBAL', 'JAMMU', 'KARGIL',\n 'KATHUA', 'KISHTWAR', 'KULGAM', 'KUPWARA', 'LEH LADAKH', 'POONCH', 'PULWAMA', 'RAJAURI',\n 'RAMBAN', 'REASI', 'SAMBA', 'SHOPIAN', 'SRINAGAR', 'UDHAMPUR'],\n 'Jharkhand':['BOKARO', 'CHATRA', 'DEOGHAR', 'DHANBAD', 'DUMKA', 'EAST SINGHBUM', 'GARHWA', 'GIRIDIH', 'GODDA',\n 'GUMLA', 'HAZARIBAGH', 'JAMTARA', 'KHUNTI', 'KODERMA', 'LATEHAR', 'LOHARDAGA', 'PAKUR', 'PALAMU',\n 'RAMGARH', 'RANCHI', 'SAHEBGANJ', 'SARAIKELA KHARSAWAN', 'SIMDEGA', 'WEST SINGHBHUM'],\n 'Karnataka':['BAGALKOT', 'BANGALORE RURAL', 'BELGAUM', 'BELLARY', 'BENGALURU URBAN', 'BIDAR', 'BIJAPUR',\n 'CHAMARAJANAGAR', 'CHIKBALLAPUR', 'CHIKMAGALUR', 'CHITRADURGA', 'DAKSHIN KANNAD', 'DAVANGERE',\n 'DHARWAD', 'GADAG', 'GULBARGA', 'HASSAN', 'HAVERI', 'KODAGU', 'KOLAR', 'KOPPAL', 'MANDYA',\n 'MYSORE', 'RAICHUR', 'RAMANAGARA', 'SHIMOGA', 'TUMKUR', 'UDUPI', 'UTTAR KANNAD', 'YADGIR'],\n 'Kerala':['ALAPPUZHA', 'ERNAKULAM', 'IDUKKI', 'KANNUR', 'KASARAGOD', 'KOLLAM', 'KOTTAYAM', 'KOZHIKODE',\n 'MALAPPURAM', 'PALAKKAD', 'PATHANAMTHITTA', 'THIRUVANANTHAPURAM', 'THRISSUR', 'WAYANAD'],\n 'Madhya Pradesh':['AGAR MALWA', 'ALIRAJPUR', 'ANUPPUR', 'ASHOKNAGAR', 'BALAGHAT', 'BARWANI', 'BETUL',\n 'BHIND', 'BHOPAL', 'BURHANPUR', 'CHHATARPUR', 'CHHINDWARA', 'DAMOH', 'DATIA', 'DEWAS',\n 'DHAR', 'DINDORI', 'GUNA', 'GWALIOR', 'HARDA', 'HOSHANGABAD', 'INDORE', 'JABALPUR',\n 'JHABUA', 'KATNI', 'KHANDWA', 'KHARGONE', 'MANDLA', 'MANDSAUR', 'MORENA', 'NARSINGHPUR',\n 'NEEMUCH', 'PANNA', 'RAISEN', 'RAJGARH', 'RATLAM', 'REWA', 'SAGAR', 'SATNA', 'SEHORE', 'SEONI',\n 'SHAHDOL', 'SHAJAPUR', 'SHEOPUR', 'SHIVPURI', 'SIDHI', 'SINGRAULI', 'TIKAMGARH', 'UJJAIN',\n 'UMARIA', 'VIDISHA'],\n 'Maharashtra':['AHMEDNAGAR', 'AKOLA', 'AMRAVATI', 'AURANGABAD', 'BEED', 'BHANDARA', 'BULDHANA', 'CHANDRAPUR',\n 'DHULE', 'GADCHIROLI', 'GONDIA', 'HINGOLI', 'JALGAON', 'JALNA', 'KOLHAPUR', 'LATUR', 'MUMBAI',\n 'NAGPUR', 'NANDED', 'NANDURBAR', 'NASHIK', 'OSMANABAD', 'PALGHAR', 'PARBHANI', 'PUNE', 'RAIGAD',\n 'RATNAGIRI', 'SANGLI', 'SATARA', 'SINDHUDURG', 'SOLAPUR', 'THANE', 'WARDHA', 'WASHIM', 'YAVATMAL'],\n 'Manipur':['BISHNUPUR', 'CHANDEL', 'CHURACHANDPUR', 'IMPHAL EAST', 'IMPHAL WEST', 'SENAPATI', 'TAMENGLONG', 'THOUBAL', 'UKHRUL'],\n 'Meghalaya':['EAST GARO HILLS', 'EAST JAINTIA HILLS', 'EAST KHASI HILLS', 'NORTH GARO HILLS', 'RI BHOI', 'SOUTH GARO HILLS',\n 'SOUTH WEST GARO HILLS', 'SOUTH WEST KHASI HILLS', 'WEST GARO HILLS', 'WEST JAINTIA HILLS', 'WEST KHASI HILLS'],\n 'Mizoram':['EAST GARO HILLS', 'EAST JAINTIA HILLS', 'EAST KHASI HILLS', 'NORTH GARO HILLS', 'RI BHOI', 'SOUTH GARO HILLS',\n 'SOUTH WEST GARO HILLS', 'SOUTH WEST KHASI HILLS', 'WEST GARO HILLS', 'WEST JAINTIA HILLS', 'WEST KHASI HILLS'],\n 'Nagaland':['DIMAPUR', 'KIPHIRE', 'KOHIMA', 'LONGLENG', 'MOKOKCHUNG', 'MON', 'PEREN', 'PHEK', 'TUENSANG', 'WOKHA', 'ZUNHEBOTO'],\n 'Odisha':['ANUGUL', 'BALANGIR', 'BALESHWAR', 'BARGARH', 'BHADRAK', 'BOUDH', 'CUTTACK', 'DEOGARH', 'DHENKANAL', 'GAJAPATI', 'GANJAM',\n 'JAGATSINGHAPUR', 'JAJAPUR', 'JHARSUGUDA', 'KALAHANDI', 'KANDHAMAL', 'KENDRAPARA', 'KENDUJHAR', 'KHORDHA', 'KORAPUT', 'MALKANGIRI',\n 'MAYURBHANJ', 'NABARANGPUR', 'NAYAGARH', 'NUAPADA', 'PURI', 'RAYAGADA', 'SAMBALPUR', 'SONEPUR', 'SUNDARGARH'], \n 'Puducherry':['KARAIKAL', 'MAHE', 'PONDICHERRY', 'YANAM'],\n 'Punjab':['AMRITSAR', 'BARNALA', 'BATHINDA', 'FARIDKOT', 'FATEHGARH SAHIB', 'FAZILKA', 'FIROZEPUR', 'GURDASPUR', 'HOSHIARPUR', 'JALANDHAR',\n 'KAPURTHALA', 'LUDHIANA', 'MANSA', 'MOGA', 'MUKTSAR', 'NAWANSHAHR', 'PATHANKOT', 'PATIALA', 'RUPNAGAR', 'S.A.S NAGAR', 'SANGRUR',\n 'TARN TARAN'],\n 'Rajasthan':['AJMER', 'ALWAR', 'BANSWARA', 'BARAN', 'BARMER', 'BHARATPUR', 'BHILWARA', 'BIKANER', 'BUNDI', 'CHITTORGARH', 'CHURU', 'DAUSA',\n 'DHOLPUR', 'DUNGARPUR', 'GANGANAGAR', 'HANUMANGARH', 'JAIPUR', 'JAISALMER', 'JALORE', 'JHALAWAR', 'JHUNJHUNU', 'JODHPUR', 'KARAULI',\n 'KOTA', 'NAGAUR', 'PALI', 'PRATAPGARH', 'RAJSAMAND', 'SAWAI MADHOPUR', 'SIKAR', 'SIROHI', 'TONK', 'UDAIPUR'],\n 'Sikkim':['EAST DISTRICT', 'NORTH DISTRICT', 'SOUTH DISTRICT', 'WEST DISTRICT'],\n 'Tamil Nadu':['ARIYALUR', 'COIMBATORE', 'CUDDALORE', 'DHARMAPURI', 'DINDIGUL', 'ERODE', 'KANCHIPURAM', 'KANNIYAKUMARI', 'KARUR',\n 'KRISHNAGIRI', 'MADURAI', 'NAGAPATTINAM', 'NAMAKKAL', 'PERAMBALUR', 'PUDUKKOTTAI', 'RAMANATHAPURAM', 'SALEM', 'SIVAGANGA',\n 'THANJAVUR', 'THE NILGIRIS', 'THENI', 'THIRUVALLUR', 'THIRUVARUR', 'TIRUCHIRAPPALLI', 'TIRUNELVELI', 'TIRUPPUR', 'TIRUVANNAMALAI',\n 'TUTICORIN', 'VELLORE', 'VILLUPURAM', 'VIRUDHUNAGAR'],\n 'Telangana':['ADILABAD', 'HYDERABAD', 'KARIMNAGAR', 'KHAMMAM', 'MAHBUBNAGAR', 'MEDAK', 'NALGONDA', 'NIZAMABAD', 'RANGAREDDI', 'WARANGAL'],\n 'Tripura':['DHALAI', 'GOMATI', 'KHOWAI', 'NORTH TRIPURA', 'SEPAHIJALA', 'SOUTH TRIPURA', 'UNAKOTI', 'WEST TRIPURA'],\n 'Uttar Pradesh':['AGRA', 'ALIGARH', 'ALLAHABAD', 'AMBEDKAR NAGAR', 'AMETHI', 'AMROHA', 'AURAIYA', 'AZAMGARH', 'BAGHPAT', 'BAHRAICH', 'BALLIA',\n 'BALRAMPUR', 'BANDA', 'BARABANKI', 'BAREILLY', 'BASTI', 'BIJNOR', 'BUDAUN', 'BULANDSHAHR', 'CHANDAULI', 'CHITRAKOOT', 'DEORIA',\n 'ETAH', 'ETAWAH', 'FAIZABAD', 'FARRUKHABAD', 'FATEHPUR', 'FIROZABAD', 'GAUTAM BUDDHA NAGAR', 'GHAZIABAD', 'GHAZIPUR', 'GONDA',\n 'GORAKHPUR', 'HAMIRPUR', 'HAPUR', 'HARDOI', 'HATHRAS', 'JALAUN', 'JAUNPUR', 'JHANSI', 'KANNAUJ', 'KANPUR DEHAT', 'KANPUR NAGAR',\n 'KASGANJ', 'KAUSHAMBI', 'KHERI', 'KUSHI NAGAR', 'LALITPUR', 'LUCKNOW', 'MAHARAJGANJ', 'MAHOBA', 'MAINPURI', 'MATHURA', 'MAU',\n 'MEERUT', 'MIRZAPUR', 'MORADABAD', 'MUZAFFARNAGAR', 'PILIBHIT', 'PRATAPGARH', 'RAE BARELI', 'RAMPUR', 'SAHARANPUR', 'SAMBHAL',\n 'SANT KABEER NAGAR', 'SANT RAVIDAS NAGAR', 'SHAHJAHANPUR', 'SHAMLI', 'SHRAVASTI', 'SIDDHARTH NAGAR', 'SITAPUR', 'SONBHADRA',\n 'SULTANPUR', 'UNNAO', 'VARANASI'],\n 'Uttarakhand':['ALMORA', 'BAGESHWAR', 'CHAMOLI', 'CHAMPAWAT', 'DEHRADUN', 'HARIDWAR', 'NAINITAL', 'PAURI GARHWAL', 'PITHORAGARH', 'RUDRA PRAYAG',\n 'TEHRI GARHWAL', 'UDAM SINGH NAGAR','UTTAR KASHI'],\n 'West Bengal':['24 PARAGANAS NORTH', '24 PARAGANAS SOUTH', 'BANKURA', 'BARDHAMAN', 'BIRBHUM', 'COOCHBEHAR', 'DARJEELING', 'DINAJPUR DAKSHIN',\n 'DINAJPUR UTTAR','HOOGHLY', 'HOWRAH', 'JALPAIGURI', 'MALDAH', 'MEDINIPUR EAST', 'MEDINIPUR WEST', 'MURSHIDABAD', 'NADIA', 'PURULIA']}\n#print(len(l[1]))\nrules=[]\nnorules=[]\nfile1=open('Rules1.csv','w+')\nfile2=open('NoRules1.csv','w+')\nco=0\ncond=[]\nfor s_soil in ['well drained loam soil']:\n com=len(l[0])-co\n print(com)\n #print(s_state+' Started \\n')\n for s_state in l[1]:\n for s_district in dist[s_state]:\n #print(s_soil)\n for s_season in l[3]:\n for s_water in l[4]:\n for i in range(1,temp):\n if((s_soil==s[i][8] and s_state==s[i][0] and s_district==s[i][1] and s_season==s[i][3] and s_water==s[i][7]) and [s_soil,s_state,s_district,s_season,s_water,s[i][4]] not in rules):\n rules.append([s_soil,s_state,s_district,s_season,s_water,s[i][4]])\n cond.append(([s_soil,s_state,s_district,s_season,s_water]))\n file1.write(s[i][8]+','+s[i][0]+','+s[i][1]+','+s[i][3]+','+s[i][7]+','+s[i][4]+'\\n')\n print(s_soil,s_state,s_district,s_season,s_water,s[i][4],1)\n \n co=co+1\n#print('\\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 \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n ')\nfor s_soil in ['well drained loam soil']:\n com=len(l[0])-co\n print(com)\n #print(s_state+' Started \\n')\n for s_state in l[1]:\n for s_district in dist[s_state]:\n #print(s_soil)\n for s_season in l[3]:\n for s_water in l[4]:\n for s_crop in l[5]:\n if([s_soil,s_state,s_district,s_season,s_water,s_crop] not in rules and [s_soil,s_state,s_district,s_season,s_water,s_crop] not in norules\n and [s_soil,s_state,s_district,s_season,s_water] not in cond):\n norules.append([s_soil,s_state,s_district,s_season,s_water,s_crop])\n cond.append(([s_soil,s_state,s_district,s_season,s_water]))\n file2.write(s_soil+','+s_state+','+s_district+','+s_season+','+s_water+','+s_crop+'\\n')\n print(s_soil,s_state,s_district,s_season,s_water,s_crop,2)\n \n co=co+1\n\nfile1.close()\nfile2.close()\n\"\"\"\n#Rules generation completed now claculating accuracy error rate\nnew=[]\ntp=0\nno=0\nfn=0\n#file1=open('C://Users//akhil//Downloads//chikku//testing//sum//Some_TruePositive.csv','w+')\n#file2=open('C://Users//akhil//Downloads//chikku//testing//sum//Some_Some_NoValuesTP.csv','w+')\n#file3=open('C://Users//akhil//Downloads//chikku//testing//sum//Some_NoCropvaluesFN.csv','w+')\n#file4=open('C://Users//akhil//Downloads//chikku//testing//sum//Some_AllValues.csv','w+')\nsize=int(input(\"Enter number of rows to be tested:\"))\nfor i in range(998,temp):\n Soil=s[i][8]\n State=s[i][0]\n District=s[i][1]\n Season=s[i][3]\n Water=s[i][7]\n crop=s[i][4]\n if(i==998+size+1):\n break\n if([Soil,State,District,Season,Water,crop] not in new):\n new.append([Soil,State,District,Season,Water,crop])\n l=Sending.Collect_crops(State,District,Season,Soil,Water)\n #Sending_information.show_crops(l,m,h)\n low_year=Sending.Collect_Data(l,State,District,Season,Soil,Water)\n low_year=Sending.Best_Crop(low_year)\n l=list(low_year.keys())\n l=l[0]\n if(l==crop and l!='no crops Found'):\n tp=tp+1\n print(i,Soil,State,District,Season,Water,crop,l,'yes',1111,tp)\n #file4.write(Soil+','+State+','+District+','+Season+','+Water+','+crop+','+l+','+'yes'+'\\n')\n #file1.write(Soil+','+State+','+District+','+Season+','+Water+','+crop+','+l+','+'yes'+'\\n')\n elif(l=='no crops Found'):\n fn=fn+1\n print(i,Soil,State,District,Season,Water,crop,l,'no crops Found',2222,fn)\n #file3.write(Soil+','+State+','+District+','+Season+','+Water+','+crop+','+l+','+'no crops Found'+'\\n')\n #file4.write(Soil+','+State+','+District+','+Season+','+Water+','+crop+','+l+','+'no crops Found'+'\\n')\n else:\n tp=tp+1\n print(i,Soil,State,District,Season,Water,crop,l,'no',3333,tp)\n #file2.write(Soil+','+State+','+District+','+Season+','+Water+','+crop+','+l+','+'no'+'\\n')\n #file4.write(Soil+','+State+','+District+','+Season+','+Water+','+crop+','+l+','+'no'+'\\n')\n#file1.close()\n#file2.close()\n#file3.close()\nb=readcsv('C:\\\\Users\\\\akhil\\\\Downloads\\\\chikku\\\\Dataset\\\\NoRules.csv')\ntemp=len(b)\nprint(b[0])\ns=seperate(b)\n#file1=open('C://Users//akhil//Downloads//chikku//testing//sum//Some_FalsePositive.csv','w+')\n#file2=open('C://Users//akhil//Downloads//chikku//testing//sum//Some_TrueNegative.csv','w+')\nfp=0\ntn=0\nfor i in range(998,temp):\n Soil=s[i][0]\n State=s[i][1]\n District=s[i][2]\n Season=s[i][3]\n Water=s[i][4]\n crop=s[i][5]\n if(i==998+size+1):\n break\n if([Soil,State,District,Season,Water,crop] not in new):\n new.append([Soil,State,District,Season,Water,crop])\n l=Sending.Collect_crops(State,District,Season,Soil,Water)\n #Sending_information.show_crops(l,m,h)\n low_year=Sending.Collect_Data(l,State,District,Season,Soil,Water)\n low_year=Sending.Best_Crop(low_year)\n l=list(low_year.keys())\n l=l[0]\n if(l!='no crops Found'):\n fp=fp+1\n print(i,Soil,State,District,Season,Water,crop,l,'yes',4444,fp)\n #file4.write(Soil+','+State+','+District+','+Season+','+Water+','+crop+','+l+','+'FalsePositive'+'Correct'+'\\n')\n #file1.write(Soil+','+State+','+District+','+Season+','+Water+','+crop+','+l+','+'FalsePositive'+'Correct'+'\\n')\n elif(l=='no crops Found'):\n tn=tn+1\n print(i,Soil,State,District,Season,Water,crop,l,'no crops Found',5555,tn)\n #file2.write(Soil+','+State+','+District+','+Season+','+Water+','+crop+','+l+','+'TrueNegative'+'\\n')\n #file4.write(Soil+','+State+','+District+','+Season+','+Water+','+crop+','+l+','+'TrueNegative'+'\\n')\n#file1.close()\n#file2.close()\n#file3.close()\n#file4.close()\nprint(tp,fn,'\\n',fp,tn)\nerr=(fp+fn)/(tp+fn+fp+tn)\nacc=(tp+tn)/(tp+fn+fp+tn)\nsn=tp/(tp+fn)\nsp=tn/tn+fp\nprec=tp/tp+fp\nfpr=fp/tn+fp\nmcc=(tp*tn)-(fp*fn)/math.sqrt((tp+fp)*(tp+fn)*(tn+fp)*(tn+fn))\nf_0=(1.25*prec*sn)/(1.25*prec+sn)\nf_1=(2*prec*sn)/(prec+sn)\nf_2=(5*prec*sn)/(4*prec+sn)\n#file1=open('C://Users//akhil//Downloads//chikku//testing//sum//Result.csv','w+')\n#file1.write('Error rate'+','+str(err)+'\\n')\nprint('Error rate',err)\n#file1.write('Accuracy'+','+str(acc)+'\\n')\nprint('Accuracy',acc)\n#file1.write('Sensitivity (or) True Positivity rate (or) Recall'+','+str(sn)+'\\n')\nprint('Sensitivity \\nTrue Positivity rate \\nRecall',sn)\n#file1.write('Specificity (or) True Negative rate'+','+str(sp)+'\\n')\nprint('Specificity \\nTrue Negative rate',sp)\n#file1.write('Precision (or) Positive Predicted Value'+','+str(prec)+'\\n')\nprint('Precision \\nPositive Predicted Value',prec)\n#file1.write('False positive rate'+','+str(fpr)+'\\n')\nprint('False positive rate',fpr)\n#file1.write('Matthews correlation coefficient'+','+str(mcc)+'\\n')\nprint('Matthews correlation coefficient',mcc)\n#file1.write('F_0.5'+','+str(f_0)+'\\n')\nprint('F_0.5',f_0)\n#file1.write('F_1'+','+str(f_1)+'\\n')\nprint('F_1',f_1)\n#file1.write('F_2'+','+str(f_2)+'\\n')\nprint('F_2',f_2)\n#file1.close()\n","sub_path":"testing/Testing - some.py","file_name":"Testing - some.py","file_ext":"py","file_size_in_byte":19315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"136741216","text":"#Creating a very simple 'guess the number' app\r\n\r\n#Imports\r\nimport random\r\nimport os\r\n\r\n\r\ndef GuessTheNumber():\r\n number = random.choice(range(0,100))\r\n\r\n os.system(\"cls\")\r\n print(\"The app has chosen a random number from 0 to 100, guess what the number is.\")\r\n guess = int(input(\"Guess:\"))\r\n\r\n while guess != number:\r\n os.system(\"cls\")\r\n print(\"\\nThats not the number\")\r\n print(\"You are {} away from the number.\".format(abs(number-guess)))\r\n guess = int(input(\"Guess:\"))\r\n\r\n if guess == number:\r\n print(\"\\nThats right. The number was {}!\".format(number))\r\n\r\nif __name__ == \"__main__\":\r\n GuessTheNumber()","sub_path":"GuessTheNumber.py","file_name":"GuessTheNumber.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"544447615","text":"from django.contrib.auth.models import User\nfrom django.db import migrations\n\nfrom ..models import Tag, Article\n\n\ndef create_data(*args):\n admin = User.objects.create_superuser(username='admin', email='admin@example.com', password='password')\n admin.save()\n\n tag1 = Tag(name='Journeys')\n tag2 = Tag(name='Food')\n tag3 = Tag(name='Sports')\n tag4 = Tag(name='Good day')\n tag5 = Tag(name='Awesome day')\n Tag.objects.bulk_create([tag1, tag2, tag3, tag4, tag5])\n\n article1 = Article(author=admin, title='My First Article')\n article2 = Article(author=admin, title='New Recipe')\n article3 = Article(author=admin, title='Snowboarding with my friends')\n article4 = Article(author=admin, title='My Collection of Rarest Vinyls')\n article5 = Article(author=admin, title='Going Camping!')\n article6 = Article(author=admin, title='My Promotion')\n Article.objects.bulk_create([article1, article2, article3, article4, article5, article6])\n\n tag1.articles.set([article3, article5])\n tag2.articles.set([article2])\n tag3.articles.set([article3])\n tag4.articles.set([article2, article4])\n tag5.articles.set([article1, article6])\n\n\nclass Migration(migrations.Migration):\n dependencies = [\n ('blog', '0001_initial'),\n ]\n\n operations = [\n migrations.RunPython(create_data),\n ]\n","sub_path":"blog/src/blog/migrations/0002_create_test_data.py","file_name":"0002_create_test_data.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"316555854","text":"import numpy as np\nimport tensorflow as tf\nfrom common_utilities.instance import tf2np\nfrom tensorflow_graphics.geometry.representation.mesh.normals import \\\n face_normals, vertex_normals\n\n\ndef compute_barycentric_coords(verts, triangles, n_samples):\n \"\"\"Computes barycentric coordinates and corresponding triangle indices for\n mesh sampling.\n\n Arguments\n ---------\n verts : np.ndarray of shape (n_verts, 3)\n Position of mesh vertices\n triangles : np.ndarray of shape (n_triangles, 3)\n Indices of vertices that make up the triangle.\n n_samples : int\n Number of samples on mesh surface.\n\n Returns\n -------\n coords : np.ndarray of shape (n_samples, 2)\n Barycentric coordinates for each sampled point.\n ids_triangle : np.ndarray of shape (n_samples, )\n Index of triangle for each sampled point.\n \"\"\"\n\n verts = tf2np(verts)\n triangles = tf2np(triangles)\n\n # compute area of each triangle and normalize\n cross = np.cross(\n verts[triangles[:, 0], :] - verts[triangles[:, 2], :],\n verts[triangles[:, 1], :] - verts[triangles[:, 2], :],\n )\n area_triangles = 1/2 * np.linalg.norm(cross, axis=1)\n area_normalized = area_triangles / np.sum(area_triangles)\n\n # sample points based on area\n n_samples_per_triangle = np.ceil(\n n_samples * area_normalized).astype(np.int32)\n n_extra = np.sum(n_samples_per_triangle) - n_samples\n if n_extra > 0:\n ids = np.nonzero(n_samples_per_triangle)[0]\n ids_extra = np.random.choice(ids, n_extra, replace=False)\n n_samples_per_triangle[ids_extra] -= 1\n n_samples = np.sum(n_samples_per_triangle)\n\n # map samples to triangle indices\n ids_triangle = np.zeros([n_samples, ], dtype=np.int32)\n count_samples = 0\n for idx_triangle, n_samples_this_triangle in \\\n enumerate(n_samples_per_triangle):\n ids_triangle[\n count_samples:\n count_samples + n_samples_this_triangle] = idx_triangle\n count_samples += n_samples_this_triangle\n\n # randomly generate barycentric coordinates\n coords = np.random.rand(n_samples, 2).astype(np.float32)\n\n return coords, ids_triangle\n\n\ndef dense_sample(verts, triangles, barycentric_coords, barycentric_triangles):\n corner1_vertices = tf.gather(\n verts, triangles[barycentric_triangles, 0]\n )\n corner2_vertices = tf.gather(\n verts, triangles[barycentric_triangles, 1]\n )\n corner3_vertices = tf.gather(\n verts, triangles[barycentric_triangles, 2]\n )\n\n samples = (1 - tf.sqrt(barycentric_coords[:, 0:1])) \\\n * corner1_vertices \\\n + tf.sqrt(barycentric_coords[:, 0:1]) *\\\n (1 - barycentric_coords[:, 1:]) * corner2_vertices \\\n + tf.sqrt(barycentric_coords[:, 0:1]) *\\\n barycentric_coords[:, 1:] * corner3_vertices\n\n return samples\n\n\ndef get_normals_at_samples(verts, triangles,\n barycentric_coords, barycentric_triangles):\n normals_at_verts = vertex_normals(verts, triangles)\n corner1_normals = tf.gather(\n normals_at_verts, triangles[barycentric_triangles, 0]\n )\n corner2_normals = tf.gather(\n normals_at_verts, triangles[barycentric_triangles, 1]\n )\n corner3_normals = tf.gather(\n normals_at_verts, triangles[barycentric_triangles, 2]\n )\n normals_at_samples = (1 - tf.sqrt(barycentric_coords[:, 0:1])) \\\n * corner1_normals \\\n + tf.sqrt(barycentric_coords[:, 0:1]) *\\\n (1 - barycentric_coords[:, 1:]) * corner2_normals \\\n + tf.sqrt(barycentric_coords[:, 0:1]) *\\\n barycentric_coords[:, 1:] * corner3_normals\n\n return normals_at_samples\n","sub_path":"barycentric_mesh_sampling.py","file_name":"barycentric_mesh_sampling.py","file_ext":"py","file_size_in_byte":3686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"285606746","text":"import json\nimport traceback\nfrom http import HTTPStatus\n\nfrom elasticsearch import TransportError\n\nfrom jassrealtime.webapi.handlers.base_handler import BaseHandler\n\nfrom jassrealtime.core.master_factory_list import get_master_document_corpus_list\nfrom jassrealtime.document.document_corpus import DocumentAlreadyExistsException, CorpusNotFoundException, \\\n DocumentNotFoundException\nfrom jassrealtime.security.security_selector import get_autorisation\nfrom jassrealtime.webapi.handlers.parameter_names import *\nfrom jassrealtime.core.settings_utils import get_env_id\n\nMAX_DOCUMENT_SIZE = 1000\n\n\nclass DocumentFolderHandler(BaseHandler):\n def post(self, corpusId):\n try:\n body = json.loads(self.request.body.decode(\"utf-8\"))\n\n language = body.get(\"language\")\n if not language:\n self.write_and_set_status({MESSAGE: \"Missing required parameters\"})\n self.set_status(HTTPStatus.UNPROCESSABLE_ENTITY)\n return\n\n envId = get_env_id()\n authorization = get_autorisation(envId, None, None)\n\n docId = body.get(\"id\") # Note: 'get' defaults to None when key does not exist\n text = body.get(\"text\", \"\")\n title = body.get(\"title\", \"\")\n source = body.get(\"source\", \"\")\n\n corpus = get_master_document_corpus_list(envId, authorization).get_corpus(corpusId)\n if not language in corpus.languages:\n self.write_and_set_status({MESSAGE: \"Document language do not correspond to corpus language\"},\n HTTPStatus.UNPROCESSABLE_ENTITY)\n return\n\n docId = corpus.add_text_document(text, title, language, docId, source)\n\n self.write_and_set_status({\"id\": docId},\n HTTPStatus.OK)\n except DocumentAlreadyExistsException:\n self.write_and_set_status({MESSAGE: \"Document with the same id already exists\"},\n HTTPStatus.CONFLICT)\n except Exception:\n trace = traceback.format_exc().splitlines()\n self.write_and_set_status({MESSAGE: \"Internal server error\", TRACE: trace},\n HTTPStatus.INTERNAL_SERVER_ERROR)\n\n def options(self, corpusId):\n self.write_and_set_status(None, HTTPStatus.OK)\n\n def get(self, corpusId):\n \"\"\"Get documents from corpus according to pagination\"\"\"\n try:\n fromIndexArgument = self.get_query_argument(\"from\")\n fromIndex = int(fromIndexArgument)\n if fromIndex < 0:\n self.write_and_set_status({MESSAGE: \"'from' must cannot be less than zero\"},\n HTTPStatus.UNPROCESSABLE_ENTITY)\n return\n\n sizeArgument = self.get_query_argument(\"size\")\n size = int(sizeArgument)\n\n if size < 1:\n self.write_and_set_status({MESSAGE: \"'size' cannot be less than 1\"},\n HTTPStatus.UNPROCESSABLE_ENTITY)\n return\n\n size = min(size, MAX_DOCUMENT_SIZE)\n\n envId = get_env_id()\n authorization = get_autorisation(envId, None, None)\n\n corpus = get_master_document_corpus_list(envId, authorization).get_corpus(corpusId)\n filterTitle = self.get_query_argument(\"filterTitle\", default=None)\n filterSource = self.get_query_argument(\"filterSource\", default=None)\n filterJoin = self.get_query_argument(\"filterJoin\", default=None)\n sortBy = self.get_query_argument(\"sortBy\", default=None)\n sortOrder = self.get_query_argument(\"sortOrder\", default=None)\n documents = corpus.get_text_documents(fromIndex, size, sortBy, sortOrder, filterTitle, filterSource,\n filterJoin)\n\n self.write_and_set_status({\"documents\": documents},\n HTTPStatus.OK)\n except CorpusNotFoundException:\n self.write_and_set_status({MESSAGE: \"Specified corpus not found\"},\n HTTPStatus.NOT_FOUND)\n except ValueError as ve:\n self.write_and_set_status({MESSAGE: \"Invalid 'from' or 'size' parameter\"},\n HTTPStatus.UNPROCESSABLE_ENTITY)\n except TransportError as te:\n trace = traceback.format_exc().splitlines()\n self.write_and_set_status({MESSAGE: \"ES TransportError\", TRACE: trace},\n te.status_code)\n except Exception as e:\n trace = traceback.format_exc().splitlines()\n self.write_and_set_status({MESSAGE: \"Internal server error\", TRACE: trace},\n HTTPStatus.INTERNAL_SERVER_ERROR)\n\n\nclass DocumentHandler(BaseHandler):\n def get(self, corpusId, documentId):\n \"\"\"Get a single document from corpus\"\"\"\n try:\n envId = get_env_id()\n authorization = get_autorisation(envId, None, None)\n corpus = get_master_document_corpus_list(envId, authorization).get_corpus(corpusId)\n document = corpus.get_text_document(documentId)\n\n if document is None:\n raise DocumentNotFoundException(documentId)\n\n self.write_and_set_status(document,\n HTTPStatus.OK)\n except CorpusNotFoundException:\n self.write_and_set_status({MESSAGE: \"Specified corpus not found\"},\n HTTPStatus.NOT_FOUND)\n except DocumentNotFoundException:\n self.write_and_set_status({MESSAGE: \"Specified document not found\"},\n HTTPStatus.NOT_FOUND)\n except Exception:\n trace = traceback.format_exc().splitlines()\n self.write_and_set_status({MESSAGE: \"Internal server error\", TRACE: trace},\n HTTPStatus.INTERNAL_SERVER_ERROR)\n\n def delete(self, corpusId, documentId):\n \"\"\"Delete a single document an optionally its annotations\"\"\"\n try:\n delete_annotations_argument = self.get_query_argument(\"deleteAnnotations\", None)\n if not delete_annotations_argument:\n self.missing_required_field(\"deleteAnnotations\")\n return\n\n delete_annotations = 'true' == delete_annotations_argument\n\n envId = get_env_id()\n authorization = get_autorisation(envId, None, None)\n corpus = get_master_document_corpus_list(envId, authorization).get_corpus(corpusId)\n document = corpus.delete_document(documentId, delete_annotations)\n self.write_and_set_status(document,\n HTTPStatus.OK)\n except CorpusNotFoundException:\n self.write_and_set_status({MESSAGE: \"Specified corpus not found\"},\n HTTPStatus.NOT_FOUND)\n except DocumentNotFoundException:\n self.write_and_set_status({MESSAGE: \"Specified document not found\"},\n HTTPStatus.NOT_FOUND)\n except Exception:\n trace = traceback.format_exc().splitlines()\n self.write_and_set_status({MESSAGE: \"Internal server error\", TRACE: trace},\n HTTPStatus.INTERNAL_SERVER_ERROR)\n\n def options(self, corpusId, documentId):\n self.write_and_set_status(None, HTTPStatus.OK)\n\n\nclass DocumentIdsHandler(BaseHandler):\n def options(self, corpusId):\n self.write_and_set_status(None, HTTPStatus.OK)\n\n def get(self, corpusId):\n try:\n envId = get_env_id()\n authorization = get_autorisation(envId, None, None)\n corpus = get_master_document_corpus_list(envId, authorization).get_corpus(corpusId)\n\n documentIds = corpus.get_document_ids()\n\n self.write_and_set_status({\"ids\": documentIds},\n HTTPStatus.OK)\n except CorpusNotFoundException:\n self.write_and_set_status({MESSAGE: \"Specified corpus not found\"},\n HTTPStatus.NOT_FOUND)\n except Exception:\n trace = traceback.format_exc().splitlines()\n self.write_and_set_status({MESSAGE: \"Internal server error\", TRACE: trace},\n HTTPStatus.INTERNAL_SERVER_ERROR)\n","sub_path":"jassrealtime/webapi/handlers/document.py","file_name":"document.py","file_ext":"py","file_size_in_byte":8551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"430303935","text":"'''\nCreated on Jul 9, 2012\n\n@author: iuri\n'''\nimport sys\n\nfrom twisted.internet.defer import inlineCallbacks, returnValue\nfrom twisted.internet import reactor\nfrom twisted.internet.endpoints import TCP4ClientEndpoint\n\nfrom txthoonk.client import ThoonkPubFactory, ThoonkSubFactory\nfrom twisted.python import log\n\nREDIS_HOST, REDIS_PORT = (\"localhost\", 6379)\n\n\n@inlineCallbacks\ndef getThoonkSubscriber():\n endpoint = TCP4ClientEndpoint(reactor, REDIS_HOST, REDIS_PORT)\n sub = yield endpoint.connect(ThoonkSubFactory())\n returnValue(sub)\n\n@inlineCallbacks\ndef getThoonkPublisher(db=15):\n endpoint = TCP4ClientEndpoint(reactor, REDIS_HOST, REDIS_PORT)\n pub = yield endpoint.connect(ThoonkPubFactory(db=db))\n returnValue(pub)\n\n\ndef newfeed(*args):\n log.msg(\"newfeed: %r\" % [args])\n\ndef delfeed(*args):\n log.msg(\"delfeed: %r\" % [args])\n\ndef publish(*args):\n log.msg(\"publish: %r\" % [args])\n\ndef retract(*args):\n log.msg(\"retract: %r\" % [args])\n\ndef edit(*args):\n log.msg(\"edit: %r\" % [args])\n\n@inlineCallbacks\ndef runTest01():\n pub = yield getThoonkPublisher()\n sub = yield getThoonkSubscriber()\n\n feed_name = \"test\"\n #flush redis\n yield pub.redis.flushdb()\n\n # setup handlers\n id_ = yield sub.register_handler(\"newfeed\", newfeed)\n log.msg(\"handler for newfeed id: %r\" % id_)\n\n id_ = yield sub.register_handler(\"delfeed\", delfeed)\n log.msg(\"handler for delfeed id: %r\" % id_)\n\n\n feed = yield pub.feed(feed_name)\n for chan, handler in zip([feed.channel_publish,\n feed.channel_edit,\n feed.channel_retract],\n [publish,\n edit,\n retract]):\n id_ = yield sub.register_handler(chan, handler)\n log.msg(\"handler for %r id: %r\" % (chan, id_))\n\n # publish without id \n new_item_id = yield feed.publish(\"new item\")\n\n # publish with id\n another_item_id = \"someid\"\n yield feed.publish(\"another item\", another_item_id)\n\n # publish with same id\n yield feed.publish(\"replace item\", another_item_id)\n\n # retract ids\n yield feed.retract(new_item_id)\n yield feed.retract(another_item_id)\n\n yield pub.delete_feed(feed_name)\n\n\n@inlineCallbacks\ndef runTest02():\n pub = yield getThoonkPublisher(12)\n #sub = yield getThoonkSubscriber()\n\n feed_name = \"test2\"\n yield pub.redis.flushdb()\n\n feed = yield pub.feed(feed_name)\n\n # set config\n yield feed.set_config({\"max_length\": 1})\n\n @inlineCallbacks\n def publish(array):\n for a in array:\n log.msg(\"publishing: %r\" % a)\n yield feed.publish(a)\n log.msg(\"published: %r\" % a)\n\n @inlineCallbacks\n def get_items():\n ids = yield feed.get_ids()\n for id_ in ids:\n item = yield feed.get_id(id_)\n log.msg(\"got item: %r\" % item)\n\n import string\n reactor.callLater(0, publish, string.ascii_lowercase)\n reactor.callLater(0, publish, string.ascii_uppercase)\n reactor.callLater(0.5, get_items)\n\ndef main(*args):\n log.startLogging(sys.stdout)\n reactor.callLater(0, runTest01) #@UndefinedVariable\n reactor.callLater(0.5, runTest02) #@UndefinedVariable\n reactor.callLater(1.5, reactor.stop) #@UndefinedVariable\n\n reactor.run() #@UndefinedVariable\n\nif __name__ == '__main__':\n main(sys.argv)\n","sub_path":"examples/feedpubsub.py","file_name":"feedpubsub.py","file_ext":"py","file_size_in_byte":3387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"64922827","text":"from flask import g, url_for, current_app\nfrom flask_restful import Resource, reqparse\nfrom .. import db\nfrom ..models import Post, Permission, Comment\nfrom . import restful\nfrom .decorators import permission_required\n\n\nclass CommentsView(Resource):\n def __init__(self):\n self.parser = reqparse.RequestParser()\n self.parser.add_argument('page', default=1, type=int, location='args')\n super().__init__()\n\n def get(self):\n page = self.parser.parse_args().get('page')\n pagination = Comment.query.order_by(Comment.timestamp.desc()).paginate(\n page, per_page=current_app.config['FLASKY_COMMENTS_PER_PAGE'],\n error_out=False)\n comments = pagination.items\n prev = None\n if pagination.has_prev:\n prev = url_for('api.comments_view', page=page - 1)\n next = None\n if pagination.has_next:\n next = url_for('api.comments_view', page=page + 1)\n return {\n 'comments': [comment.to_json() for comment in comments],\n 'prev': prev,\n 'next': next,\n 'count': pagination.total\n }\n\n\nclass CommentView(Resource):\n def get(self, id):\n comment = Comment.query.get_or_404(id)\n return comment.to_json()\n\n\nclass PostCommentsView(Resource):\n def __init__(self):\n self.parser = reqparse.RequestParser()\n self.parser.add_argument('page', default=1, type=int, location='args')\n self.parser.add_argument('body', type=str, location='json')\n super().__init__()\n\n def get(self, id):\n post = Post.query.get_or_404(id)\n page = self.parser.parse_args().get('page')\n pagination = post.comments.order_by(Comment.timestamp.asc()).paginate(\n page, per_page=current_app.config['FLASKY_COMMENTS_PER_PAGE'],\n error_out=False)\n comments = pagination.items\n prev = None\n if pagination.has_prev:\n prev = url_for('api.post_comments_view', id=id, page=page - 1)\n next = None\n if pagination.has_next:\n next = url_for('api.post_comments_view', id=id, page=page + 1)\n return {\n 'comments': [comment.to_json() for comment in comments],\n 'prev': prev,\n 'next': next,\n 'count': pagination.total\n }\n\n @permission_required(Permission.COMMENT)\n def post(self, id):\n args = self.parser.parse_args()\n post = Post.query.get_or_404(id)\n comment = Comment.from_json(args)\n comment.author = g.current_user\n comment.post = post\n db.session.add(comment)\n db.session.commit()\n return comment.to_json(), 201, \\\n {'Location': url_for('api.comment_view', id=comment.id)}\n\n\nrestful.add_resource(CommentsView, '/comments/', endpoint='comments_view')\nrestful.add_resource(CommentView, '/comments/', endpoint='comment_view')\nrestful.add_resource(PostCommentsView, '/posts//comments/', endpoint='post_comments_view')","sub_path":"app/api/comments.py","file_name":"comments.py","file_ext":"py","file_size_in_byte":3016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"37340776","text":"from azure.storage import CloudStorageAccount\r\nfrom azure.storage.blob import BlockBlobService, PageBlobService, AppendBlobService\r\nimport os\r\nimport config\r\n\r\n'''\r\nFurther reference:\r\n # 1. connect to the current blob\r\n https://docs.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-python-legacy\r\n 2. advanced properties\r\n https://github.com/Azure-Samples/storage-blob-python-getting-started/blob/master/blob_advanced_samples.py\r\n 3. create metadata and etc\r\n https://github.com/Azure/azure-storage-python/blob/master/samples/blob/block_blob_usage.py\r\n 4. Quickstart with blobs\r\n https://docs.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-python\r\n'''\r\n\r\n# 0. Setup account\r\nif config.IS_EMULATED:\r\n account = CloudStorageAccount(is_emulated=True)\r\nelse:\r\n account_name = config.STORAGE_ACCOUNT_NAME\r\n account_key = config.STORAGE_ACCOUNT_KEY\r\n account = CloudStorageAccount(account_name, account_key)\r\n\r\n\r\n# 1. Create the BlockBlockService that the system uses to call the Blob service for the storage account.\r\nblock_blob_service = account.create_block_blob_service()\r\n\r\n# 2. List the blobs in the container.\r\nprint(\"\\nList blobs in the container\")\r\ngenerator = block_blob_service.list_blobs('test01')\r\nfor blob in generator:\r\n print(\"\\t Blob name: \" + blob.name)\r\n\r\n# 3. Set metadata to blob\r\nmetadata = {'val1': 'foo', 'val2':'blah'}\r\nblock_blob_service.set_blob_metadata('test01', 'a dopo.txt', metadata)\r\n\r\n# 4. Explore the metadata of the blobs and properties\r\nprint('1. get blob properties')\r\nblob = block_blob_service.get_blob_properties('test01', 'a dopo.txt')\r\nprint(blob.name)\r\nprint(blob.properties.last_modified)\r\nprint(blob.metadata['val2'])\r\n\r\n'''\r\nfor key in blob.metadata:\r\n print(blob.metadata['val2'])\r\n'''","sub_path":"explore_blob.py","file_name":"explore_blob.py","file_ext":"py","file_size_in_byte":1803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"650983141","text":"import time\nfrom collections import OrderedDict\nfrom Options.TrainOptions import TrainOptions\nfrom torch.autograd import Variable\nimport torch.utils.data as data\nfrom utils import *\nimport torch\nimport CNN\nfrom Model_Configue import *\nimport FMCC_Dataset\nimport torch.nn as nn\nopt =TrainOptions().parse()\nif opt.Model == 'CNN_KWS_Model':\n configue = CNN_Model\n model = CNN.CNN_KWS_Model(configue)\nif len(opt.gpu_ids) > 0:\n model.cuda()\n GPU_Mode =1\nelse :\n GPU_Mode = 0\noptimizer = torch.optim.SGD(model.parameters(),lr=opt.lr,momentum=0.9)\n\ntrain_set = FMCC_Dataset.FMCC_Dataset(opt.train_label_path,opt.train_data_path,opt.word_path,opt.lexicon_path)\ntrain_loader = data.DataLoader(train_set,batch_size= opt.batchsize,shuffle=True)\n\ncriterion = nn.CrossEntropyLoss()\nmax_acc = 0\nfor epoch_idx in range(opt.epoch):\n print('Epoch {}/{}'.format(epoch_idx,opt.epoch-1))\n print('--'*10)\n since = time.time()\n model.train()\n if opt.Decay_Style == 'exp':\n optimizer = exp_lr_scheduler(optimizer=optimizer,epoch=epoch_idx,init_lr=opt.lr,lr_dacay_epoch=opt.epoch_decay,Decay_Weight=opt.Decay_Weight)\n elif opt.Decay_Style == 'linear':\n optimizer = linear_lr_scheduler(optimizer=optimizer,epoch=epoch_idx,init_lr=opt.lr,lr_dacay_epoch=opt.epoch_decay,max_epoch=opt.epoch)\n running_loss = 0.0\n running_corrects = 0\n counter = 0\n for data in train_loader:\n input = data['data']\n label = data['label']\n if GPU_Mode:\n input,label = Variable(input.float().cuda()),Variable(label.long().cuda())\n else:\n input,label = Variable(input),Variable(label.long())\n optimizer.zero_grad()\n out = model(input)\n loss = criterion(out,label)\n loss.backward()\n optimizer.step()\n running_loss +=loss.item()\n _,predicts = torch.max(out.data,1)\n\n running_corrects+= torch.sum(predicts==label.data)\n if counter %5000 ==0:\n print('Reached iteration',counter)\n counter +=1\n epoch_loss =running_loss/len(train_set)\n epoch_acc = (1.0*running_corrects.item())/len(train_set)\n print('{} Loss: {:.4f} Acc: {:.4f}'.format(opt.phase,epoch_loss,epoch_acc))\n\n time_elapsed = time.time()-since\n print('Training complete in {:.0f}m {:.0f}s'.format(time_elapsed//60,time_elapsed%60))\n\n if epoch_idx % opt.Save_Fre==0:\n save_name = opt.name+'__model'+str(epoch_idx)+'.pt'\n save_name = os.path.join(opt.checkpoints_dir, opt.name,save_name)\n torch.save(model.state_dict(),save_name)\n\n\n\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"149495279","text":"import graphene\nimport pdb\n\nfrom profiles.models.Profile import Profile\nfrom profiles.schema import ProfileNode\nfrom organization.models.Organization import Organization\nfrom user.schema import get_user\n\n\nclass CreateProfile(graphene.relay.ClientIDMutation):\n profile = graphene.Field(ProfileNode)\n\n class Input:\n organizations = graphene.List(graphene.Int)\n biography = graphene.String()\n\n def mutate_and_get_payload(self, info, **input):\n # get user here\n user = get_user(info) or None\n\n if not user:\n raise Exception(\"User does not exist.\")\n\n profile = Profile(\n user=user,\n biography=input.get(\"biography\")\n )\n\n profile.save()\n\n for id in input.get(\"organizations\"):\n print(\"orgid %s\" % id)\n organization = Organization.objects.filter(id=id).first()\n profile.organizations.add(organization)\n\n profile.save()\n\n return CreateProfile(profile=profile)\n","sub_path":"services/cms/profiles/schema/CreateProfile.py","file_name":"CreateProfile.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"396195735","text":"\"\"\"\r\nCRYPTO CSV PRE-PROCESSING:\r\n\t-> READ DATA TO ARRAYS\r\n\t-> CHECK DATA TYPES\r\n\t-> SET TO 2 DECIMAL PLACES\r\n\t-> PLOT SINGLE CHART\r\n\t-> PLOTTING VALUES\r\n\t-> WRITE LISTS BACK INTO CSV \r\n\"\"\"\r\n\r\nimport csv, time, sys\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.dates as mdates\r\nimport datetime as dt\r\n\r\n\r\nfile1 = \"crypto/BTC.csv\"\r\n\r\nDATE2 = []\r\n\r\n\r\n#########################\r\n## READ DATA TO ARRAYS ##\r\n#########################\r\n#column_names = [\"DATE\", \"BTC_OPEN\", \"ETH_OPEN\"]\r\ndf = pd.read_csv(file1)#, names=column_names)\r\n#print(df)\r\n\r\nDATE = df.DATE.to_list()\r\nBTC_OPEN = df.BTC_OPEN.to_list()\r\nETH_OPEN = df.ETH_OPEN.to_list()\r\n\r\n## Remove time from String ##\r\nfor i in DATE:\r\n\tDATE2.append(i.split(' ')[0])\r\nDATE = DATE2\r\n\r\n\r\n\"\"\"\r\n######################\r\n## CHECK DATA TYPES ##\r\n######################\r\nprint(type(DATE[12]))\t\t\t\t\t# check random value type\r\nprint(type(BTC_OPEN[12]))\t\t\t\t# check type is now float (2 decimal)\r\nprint(type(ETH_OPEN[12]))\t\t\t\t# check type is now float (2 decimal)\r\n\r\n## CONVERT ARRAY TO FLOAT - UNECESSARY ##\r\n#list(np.float_(BTC_OPEN))\r\n#list(np.float_(ETH_OPEN))\r\n\"\"\"\r\n\r\n#############################\r\n## SET TO 2 DECIMAL PLACES ##\r\n#############################\r\nBTC_OPEN = list(np.around(np.array(BTC_OPEN),2))\r\nETH_OPEN = list(np.around(np.array(ETH_OPEN),2))\r\n\r\n\r\n\"\"\"\r\n#######################\r\n## PLOT SINGLE CHART ##\r\n#######################\r\nx = [dt.datetime.strptime(d,'%Y-%m-%d').date() for d in DATE]\r\ny = range(len(x))\r\ny = BTC_OPEN\r\n\r\nplt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))\r\nplt.gca().xaxis.set_major_locator(mdates.DayLocator())\r\nplt.plot(x,y)\r\nplt.gcf().autofmt_xdate()\r\n\"\"\"\r\n\r\n#\"\"\"\r\n#####################\r\n## PLOTTING VALUES ##\r\n#####################\r\n#t = np.arange(0.01, 48.0, 0.01) \t\t# Set the range to number of rows?\r\nx = [dt.datetime.strptime(d,'%Y-%m-%d').date() for d in DATE]\t# X-Axis\r\ndata1 = BTC_OPEN\t\t\t\t\t\t\t\t\t\t\t\t# 1st Y-Axis \r\ndata2 = ETH_OPEN\t\t\t\t\t\t\t\t\t\t\t\t# 2nd Y-Axis \r\n\r\n\r\nfig, ax1 = plt.subplots()\r\n\r\ncolor = 'tab:red'\r\nax1.set_xlabel('time')\r\nax1.set_ylabel('BTC_OPEN', color=color)\r\nax1.plot(x, data1, color=color)\r\nax1.tick_params(axis='y', labelcolor=color)\r\n\r\nax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis\r\n\r\ncolor = 'tab:blue'\r\nax2.set_ylabel('ETH_OPEN', color=color)\r\nax2.plot(x, data2, color=color)\r\nax2.tick_params(axis='y', labelcolor=color)\r\n\r\nfig.tight_layout() \t\t# otherwise the right y-label is slightly clipped\r\n\r\nprint(\"Show Plot\")\r\nplt.show()\r\n#\"\"\"\r\n\r\n###############################\r\n## WRITE LISTS BACK INTO CSV ##\r\n###############################\r\ndf = pd.read_csv(file1) ## 1.csv is the csv file I want to import. \r\n\r\n#a = [0.001, 5, 38, 70, 101, 140, 190]\r\n#b = [35, 65, 100, 160, 170, 200]\r\n\r\ndf['DATE'] \t\t= DATE\r\ndf['BTC_OPEN'] \t= BTC_OPEN\r\ndf['ETH_OPEN'] \t= ETH_OPEN\r\n\r\ndf.to_csv(file1)\r\n\r\n\r\nprint(\"Executed Successfully...\")\r\nsys.exit(0)\t","sub_path":"files/csv/csv2.py","file_name":"csv2.py","file_ext":"py","file_size_in_byte":2938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"609268334","text":"import time\nfrom typing import Iterator\n\nimport openai\n\nfrom gptcache.adapter.adapter import adapt\nfrom gptcache.utils.response import get_message_from_openai_answer, get_stream_message_from_openai_answer\n\n\nclass ChatCompletion:\n \"\"\"Openai ChatCompletion Wrapper\"\"\"\n\n @classmethod\n def create(cls, *args, **kwargs):\n def llm_handler(*llm_args, **llm_kwargs):\n return openai.ChatCompletion.create(*llm_args, **llm_kwargs)\n\n def cache_data_convert(cache_data):\n if kwargs.get(\"stream\", False):\n return construct_stream_resp_from_cache(cache_data)\n return construct_resp_from_cache(cache_data)\n\n def update_cache_callback(llm_data, update_cache_func):\n if not isinstance(llm_data, Iterator):\n update_cache_func(get_message_from_openai_answer(llm_data))\n return llm_data\n else:\n\n def hook_openai_data(it):\n total_answer = \"\"\n for item in it:\n total_answer += get_stream_message_from_openai_answer(item)\n yield item\n update_cache_func(total_answer)\n\n return hook_openai_data(llm_data)\n\n return adapt(\n llm_handler, cache_data_convert, update_cache_callback, *args, **kwargs\n )\n\n\ndef construct_resp_from_cache(return_message):\n return {\n \"gptcache\": True,\n \"choices\": [\n {\n \"message\": {\"role\": \"assistant\", \"content\": return_message},\n \"finish_reason\": \"stop\",\n \"index\": 0,\n }\n ],\n \"created\": int(time.time()),\n \"usage\": {\"completion_tokens\": 0, \"prompt_tokens\": 0, \"total_tokens\": 0},\n \"object\": \"chat.completion\",\n }\n\n\ndef construct_stream_resp_from_cache(return_message):\n created = int(time.time())\n return [\n {\n \"choices\": [\n {\"delta\": {\"role\": \"assistant\"}, \"finish_reason\": None, \"index\": 0}\n ],\n \"created\": created,\n \"object\": \"chat.completion.chunk\",\n },\n {\n \"choices\": [\n {\n \"delta\": {\"content\": return_message},\n \"finish_reason\": None,\n \"index\": 0,\n }\n ],\n \"created\": created,\n \"object\": \"chat.completion.chunk\",\n },\n {\n \"gptcache\": True,\n \"choices\": [{\"delta\": {}, \"finish_reason\": \"stop\", \"index\": 0}],\n \"created\": created,\n \"object\": \"chat.completion.chunk\",\n },\n ]\n","sub_path":"openai/venv/lib/python3.10/site-packages/gptcache/adapter/openai.py","file_name":"openai.py","file_ext":"py","file_size_in_byte":2662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"72705959","text":"from django.contrib import admin\n\nfrom .models import (Car, Review,)\nfrom .forms import ReviewAdminForm\n\n\n@admin.register(Car)\nclass CarAdmin(admin.ModelAdmin):\n list_display = ['brand', 'model', 'review_count']\n list_filter = ['brand', 'model']\n search_fields = ['brand', 'model']\n ordering = ['-id']\n\n\n@admin.register(Review)\nclass ReviewAdmin(admin.ModelAdmin):\n form = ReviewAdminForm\n list_display = ['car', 'title']\n list_filter = ['car__brand']\n search_fields = ['car__brand', 'title']\n ordering = ['-id']\n\n","sub_path":"site-form-works/car_admin/app/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"47644618","text":"# -*- coding: utf-8 -*-\n\n# source:\n# https://github.com/madzak/python-json-logger/blob/master/src/pythonjsonlogger/jsonlogger.py\n# and Remy's contribution of RabbitMQHandler\n\n# Copyright (c) 2011, Zakaria Zajac\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n# following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following\n# disclaimer.\n# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following\n# disclaimer in the documentation and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nimport logging\nimport json\nimport re\nimport datetime\nimport traceback\nimport pika\nimport time\nimport os\nfrom inspect import istraceback\n\n# Support order in python 2.7 and 3\ntry:\n from collections import OrderedDict\nexcept ImportError:\n pass\n\nVERSION = '0.0.8'\nAPI_VERSION = '1.0.8'\n\n# defaults vars\nAMQP_URL = 'amqp://guest:guest@localhost'\nAMQP_EXCHANGE = 'amq.topic'\n\n# import AMQP variables from environment\ntry:\n AMQP_URL = str(os.environ['AMQP_URL'])\n AMQP_EXCHANGE = str(os.environ['AMQP_EXCHANGE'])\n print('Env vars for AMQP connection succesfully imported')\n print('URL: %s' % AMQP_URL)\n print('AMQP_EXCHANGE: %s' % AMQP_EXCHANGE)\n\nexcept KeyError as e:\n print(' Cannot retrieve environment variables for AMQP connection, using default url: %s, exchange: %s' % (\n AMQP_URL, AMQP_EXCHANGE))\n\n# skip natural LogRecord attributes\n# http://docs.python.org/library/logging.html#logrecord-attributes\nRESERVED_ATTRS = (\n 'args', 'asctime', 'created', 'exc_info', 'exc_text', 'filename',\n 'funcName', 'levelname', 'levelno', 'lineno', 'module',\n 'msecs', 'message', 'msg', 'name', 'pathname', 'process',\n 'processName', 'relativeCreated', 'stack_info', 'thread', 'threadName')\n\nRESERVED_ATTR_HASH = dict(zip(RESERVED_ATTRS, RESERVED_ATTRS))\n\n\ndef merge_record_extra(record, target, reserved=RESERVED_ATTR_HASH):\n \"\"\"\n Merges extra attributes from LogRecord object into target dictionary\n :param record: logging.LogRecord\n :param target: dict to update\n :param reserved: dict or list with reserved keys to skip\n \"\"\"\n for key, value in record.__dict__.items():\n # this allows to have numeric keys\n if (key not in reserved\n and not (hasattr(key, \"startswith\")\n and key.startswith('_'))):\n target[key] = value\n return target\n\n\nclass JsonFormatter(logging.Formatter):\n \"\"\"\n A custom formatter to format logging records as json strings.\n extra values will be formatted as str() if nor supported by\n json default encoder\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n :param json_default: a function for encoding non-standard objects\n as outlined in http://docs.python.org/2/library/json.html\n :param json_encoder: optional custom encoder\n :param prefix: an optional string prefix added at the beginning of\n the formatted string\n \"\"\"\n self.json_default = kwargs.pop(\"json_default\", None)\n self.json_encoder = kwargs.pop(\"json_encoder\", None)\n self.prefix = kwargs.pop(\"prefix\", \"\")\n # super(JsonFormatter, self).__init__(*args, **kwargs)\n logging.Formatter.__init__(self, *args, **kwargs)\n if not self.json_encoder and not self.json_default:\n def _default_json_handler(obj):\n '''Prints dates in ISO format'''\n if isinstance(obj, (datetime.date, datetime.time)):\n return obj.isoformat()\n elif istraceback(obj):\n tb = ''.join(traceback.format_tb(obj))\n return tb.strip()\n elif isinstance(obj, Exception):\n return \"Exception: %s\" % str(obj)\n return str(obj)\n\n self.json_default = _default_json_handler\n self._required_fields = self.parse()\n self._skip_fields = dict(zip(self._required_fields,\n self._required_fields))\n self._skip_fields.update(RESERVED_ATTR_HASH)\n\n def parse(self):\n \"\"\"Parses format string looking for substitutions\"\"\"\n standard_formatters = re.compile(r'\\((.+?)\\)', re.IGNORECASE)\n return standard_formatters.findall(self._fmt)\n\n def add_fields(self, log_record, record, message_dict):\n \"\"\"\n Override this method to implement custom logic for adding fields.\n \"\"\"\n for field in self._required_fields:\n log_record[field] = record.__dict__.get(field)\n log_record.update(message_dict)\n\n merge_record_extra(record, log_record, reserved=self._skip_fields)\n\n def process_log_record(self, log_record):\n \"\"\"\n Override this method to implement custom logic\n on the possibly ordered dictionary.\n \"\"\"\n return log_record\n\n def jsonify_log_record(self, log_record):\n \"\"\"Returns a json string of the log record.\"\"\"\n return json.dumps(log_record,\n default=self.json_default,\n cls=self.json_encoder)\n\n def format(self, record):\n \"\"\"Formats a log record and serializes to json\"\"\"\n message_dict = {}\n if isinstance(record.msg, dict):\n message_dict = record.msg\n record.message = None\n else:\n record.message = record.getMessage()\n # only format time if needed\n if \"asctime\" in self._required_fields:\n record.asctime = self.formatTime(record, self.datefmt)\n\n # Display formatted exception, but allow overriding it in the\n # user-supplied dict.\n if record.exc_info and not message_dict.get('exc_info'):\n message_dict['exc_info'] = self.formatException(record.exc_info)\n if not message_dict.get('exc_info') and record.exc_text:\n message_dict['exc_info'] = record.exc_text\n\n try:\n log_record = OrderedDict()\n log_record['component'] = record.name\n log_record['_api_version'] = API_VERSION\n except NameError:\n log_record = {}\n\n self.add_fields(log_record, record, message_dict)\n log_record = self.process_log_record(log_record)\n\n return \"%s%s\" % (self.prefix, self.jsonify_log_record(log_record))\n\n\nclass RabbitMQHandler(logging.Handler):\n \"\"\"\n A handler that acts as a RabbitMQ publisher\n Example setup::\n handler = RabbitMQHandler('amqp://guest:guest@localhost')\n \"\"\"\n\n def __init__(self, url, name, exchange=\"amq.topic\"):\n logging.Handler.__init__(self)\n self.url = url\n self.connection = pika.BlockingConnection(pika.URLParameters(self.url))\n self.channel = self.connection.channel()\n self.exchange = exchange\n self.name = name\n self.createLock()\n\n def emit(self, record):\n\n self.acquire()\n\n routing_key = \".\".join([\"log\", record.levelname.lower(), self.name])\n\n try:\n self.channel.basic_publish(\n exchange=self.exchange,\n routing_key=routing_key,\n body=self.format(record),\n properties=pika.BasicProperties(\n content_type='application/json'\n )\n )\n\n except (pika.exceptions.ConnectionClosed, BrokenPipeError):\n\n print(\"Log handler connection closed. Reconnecting..\")\n\n self.connection = pika.BlockingConnection(pika.URLParameters(self.url))\n self.channel = self.connection.channel()\n\n # send retry\n self.channel.basic_publish(\n exchange=self.exchange,\n routing_key=routing_key,\n body=self.format(record),\n properties=pika.BasicProperties(\n content_type='application/json'\n )\n )\n\n finally:\n self.release()\n\n def close(self):\n\n self.acquire()\n\n try:\n self.channel.close()\n except (AttributeError, pika.exceptions.ConnectionClosed):\n pass\n\n try:\n self.connection.close()\n except (AttributeError, pika.exceptions.ConnectionClosed):\n pass\n\n finally:\n self.release()\n\n self.connection, self.channel = None, None\n\n\nif __name__ == \"__main__\":\n\n rabbitmq_handler = RabbitMQHandler(AMQP_URL, \"MyComponent\")\n json_formatter = JsonFormatter()\n rabbitmq_handler.setFormatter(json_formatter)\n\n logger = logging.getLogger(__name__)\n logger.addHandler(rabbitmq_handler)\n logger.setLevel(logging.DEBUG)\n\n sh = logging.StreamHandler()\n logger.addHandler(sh)\n\n while True:\n logger.critical(\"This is a critical message\")\n time.sleep(1)\n logger.error(\"This is an error\")\n time.sleep(1)\n logger.warning(\"This is a warning\")\n time.sleep(1)\n logger.info(\"This is an info\")\n time.sleep(1)\n logger.debug(\"This is a debug\")\n","sub_path":"event_bus_utils/rmq_handler.py","file_name":"rmq_handler.py","file_ext":"py","file_size_in_byte":9954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"86596783","text":"#!BPY\n# coding: utf-8\n\"\"\" \nName: 'Flour Convex Compound Actor (.flower)...'\nBlender: 249\nGroup: 'Export'\nTooltip: 'Export scene as a compound actor(.flower).'\n\"\"\"\n\n__author__ = \"Robin Southern\"\n__url__ = \"flour.nxogre.org\"\n__version__ = \"0.1\"\n__bpydoc__ = \"\"\"\\\n\nFlour Compound Exporter\n\nThis script Exports a flower file that is readable by Flour\n\"\"\"\n#\n# Copyright (c) 2009 Robin Southern\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\n\nimport Blender\nimport flour\nimport bpy\n\n\nBlender.Window.FileSelector(flour.exportCompound, \"Export\", Blender.sys.makename(ext='.flower'))\n\n \n \n ","sub_path":"Flour/betajaen-flour-src-c45f06d/exporters/Blender/flour_compound_actor.py","file_name":"flour_compound_actor.py","file_ext":"py","file_size_in_byte":1601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"78474161","text":"\nimport time\nimport numpy as np\n\n\nfrom .update_d.update_d import update_d\nfrom .utils.dictionary import get_lambda_max\nfrom .utils.dictionary import get_max_error_dict\n\nfrom .update_z.distributed_sparse_encoder import DistributedSparseEncoder\n\n\nDEFAULT_DICOD_KWARGS = dict(max_iter=int(1e8), timeout=None)\n\n\ndef dicodile(X, D_hat, reg=.1, z_positive=True, n_iter=100, strategy='greedy',\n n_seg='auto', tol=1e-3, dicod_kwargs={}, stopping_pobj=None,\n w_world='auto', n_workers=4, hostfile=None, eps=1e-5,\n window=False, raise_on_increase=True, random_state=None,\n name=\"DICODILE\", verbose=0):\n\n lmbd_max = get_lambda_max(X, D_hat).max()\n if verbose > 5:\n print(\"[DEBUG:DICODILE] Lambda_max = {}\".format(lmbd_max))\n\n # Scale reg and tol\n reg_ = reg * lmbd_max\n tol = (1 - reg) * lmbd_max * tol\n\n params = DEFAULT_DICOD_KWARGS.copy()\n params.update(dicod_kwargs)\n params.update(dict(\n strategy=strategy, n_seg=n_seg, z_positive=z_positive, tol=tol,\n random_state=random_state, reg=reg_, timing=False, soft_lock='border',\n return_ztz=False, freeze_support=False, warm_start=True, debug=False\n ))\n\n encoder = DistributedSparseEncoder(n_workers, w_world=w_world,\n hostfile=hostfile, verbose=verbose-1)\n encoder.init_workers(X, D_hat, reg_, params)\n\n n_atoms, n_channels, *_ = D_hat.shape\n\n # Initialize constants for computations of the dictionary gradient.\n constants = {}\n constants['n_channels'] = n_channels\n constants['XtX'] = np.dot(X.ravel(), X.ravel())\n\n # monitor cost function\n times = [encoder.t_init]\n pobj = [encoder.get_cost()]\n t_start = time.time()\n\n # Initial step_size\n step_size = 1\n\n for ii in range(n_iter): # outer loop of coordinate descent\n if verbose == 1:\n msg = '.' if ((ii + 1) % 10 != 0) else '+\\n'\n print(msg, end='', flush=True)\n elif verbose > 1:\n print('[INFO:{}] - CD iterations {} / {} ({:.0f}s)'\n .format(name, ii, n_iter, time.time() - t_start))\n\n if verbose > 5:\n print('[DEBUG:{}] lambda = {:.3e}'.format(name, reg_))\n\n # Compute z update\n t_start_update_z = time.time()\n encoder.process_z_hat()\n times.append(time.time() - t_start_update_z)\n\n # monitor cost function\n pobj.append(encoder.get_cost())\n if verbose > 5:\n print('[DEBUG:{}] Objective (z) : {:.3e} ({:.0f}s)'\n .format(name, pobj[-1], times[-1]))\n\n z_nnz = encoder.get_z_nnz()\n if np.all(z_nnz == 0):\n import warnings\n warnings.warn(\"Regularization parameter `reg` is too large \"\n \"and all the activations are zero. No atoms has\"\n \" been learned.\", UserWarning)\n break\n\n # Compute D update\n t_start_update_d = time.time()\n constants['ztz'], constants['ztX'] = \\\n encoder.get_sufficient_statistics()\n step_size *= 100\n D_hat, step_size = update_d(X, None, D_hat,\n constants=constants, window=window,\n step_size=step_size, max_iter=100,\n eps=1e-5, verbose=verbose, momentum=False)\n times.append(time.time() - t_start_update_d)\n # Update the dictionary D_hat in the encoder\n encoder.set_worker_D(D_hat)\n\n # If an atom is un-used, replace it by the chunk of the residual with\n # the largest un-captured variance.\n null_atom_indices = np.where(z_nnz == 0)[0]\n if len(null_atom_indices) > 0:\n k0 = null_atom_indices[0]\n z_hat = encoder.get_z_hat()\n D_hat[k0] = get_max_error_dict(X, z_hat, D_hat, window=window)[0]\n if verbose > 1:\n print('[INFO:{}] Resampled atom {}'.format(name, k0))\n\n # Update the dictionary D_hat in the encoder\n encoder.set_worker_D(D_hat)\n\n # monitor cost function\n pobj.append(encoder.get_cost())\n if verbose > 5:\n print('[DEBUG:{}] Objective (d) : {:.3e} ({:.0f}s)'\n .format(name, pobj[-1], times[-1]))\n\n # Only check that the cost is always going down when the regularization\n # parameter is fixed.\n dz = (pobj[-3] - pobj[-2]) / min(pobj[-3], pobj[-2])\n du = (pobj[-2] - pobj[-1]) / min(pobj[-2], pobj[-1])\n if (dz < eps or du < eps):\n if dz < 0 and raise_on_increase:\n raise RuntimeError(\n \"The z update have increased the objective value by {}.\"\n .format(dz)\n )\n if du < -1e-10 and dz > 1e-12 and raise_on_increase:\n raise RuntimeError(\n \"The d update have increased the objective value by {}.\"\n \"(dz={})\".format(du, dz)\n )\n if dz < eps and du < eps:\n if verbose == 1:\n print(\"\")\n print(\"[INFO:{}] Converged after {} iteration, (dz, du) \"\n \"= {:.3e}, {:.3e}\".format(name, ii + 1, dz, du))\n break\n\n if stopping_pobj is not None and pobj[-1] < stopping_pobj:\n break\n\n encoder.process_z_hat()\n z_hat = encoder.get_z_hat()\n pobj.append(encoder.get_cost())\n\n runtime = np.sum(times)\n encoder.release_workers()\n print(\"[INFO:{}] Finished in {:.0f}s\".format(name, runtime))\n return pobj, times, D_hat, z_hat\n","sub_path":"dicodile/dicodile.py","file_name":"dicodile.py","file_ext":"py","file_size_in_byte":5609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"100435696","text":"#!/usr/bin/env python\nimport numpy as np\nfrom netCDF4 import Dataset\nfrom datetime import datetime, timedelta\nimport matplotlib.pyplot as plt\nfrom scipy.ndimage.filters import gaussian_filter\nfrom mpl_toolkits.basemap import Basemap\n\nimport sys\nfrom mpl_toolkits import basemap\nimport spharm\nimport os\nfrom hyperdiffusion import del4_filter, apply_des_filter\nimport namelist as NL # <---- IMPORTANT! Namelist containing constants and other model parameters\n\n\nclass Model:\n \"\"\"\n Class for storing/plotting flow fields for a homogeneous (constant density), \n non-divergent, and incompressible fluid on a sphere and integrating them forward \n with the barotropic vorticity equation.\n \"\"\"\n \n def __init__(self, ics, forcing=None):\n \"\"\"\n Initializes the model.\n \n Requires:\n ics -----> Dictionary of linearized fields and space/time dimensions\n keys: u_bar, v_bar, u_prime, v_prime, lats, lons, start_time\n forcing -> a 2D array (same shape as model fields) containing a\n vorticity tendency [s^-2] to be imposed at each integration time step\n \"\"\"\n # 1) STORE SPACE/TIME VARIABLES (DIMENSIONS)\n # Get the latitudes and longitudes (as lists)\n self.lats = ics['lats']\n self.lons = ics['lons']\n self.start_time = ics['start_time'] # datetime\n self.curtime = self.start_time\n \n \n # 2) GENERATE/STORE NONDIVERGENT INITIAL STATE\n # Set up the spherical harmonic transform object\n self.s = spharm.Spharmt(self.nlons(), self.nlats(), rsphere=NL.Re,\n gridtype='regular', legfunc='computed')\n # Truncation for the spherical transformation\n if NL.M is None:\n self.ntrunc = self.nlats()\n else:\n self.ntrunc = NL.M\n # Use the object to get the initial conditions\n # First convert to vorticity using spharm object\n vortb_spec, div_spec = self.s.getvrtdivspec(ics['u_bar'], ics['v_bar'])\n vortp_spec, div_spec = self.s.getvrtdivspec(ics['u_prime'], ics['v_prime'])\n div_spec = np.zeros(vortb_spec.shape) # Only want NON-DIVERGENT part of wind \n # Re-convert this to u-v winds to get the non-divergent component\n # of the wind field\n self.ub, self.vb = self.s.getuv(vortb_spec, div_spec) # MEAN WINDS\n self.up, self.vp = self.s.getuv(vortp_spec, div_spec) # PERTURBATION WINDS\n # Use these winds to get the streamfunction (psi) and \n # velocity potential (chi)\n self.psib,chi = self.s.getpsichi(self.ub, self.vb) # MEAN STREAMFUNCTION\n self.psip,chi = self.s.getpsichi(self.up, self.vp) # PERTURBATION STREAMFUNCTION\n # Convert the spectral vorticity to grid\n self.vort_bar = self.s.spectogrd(vortb_spec) # MEAN RELATIVE VORTICITY\n self.vortp = self.s.spectogrd(vortp_spec) # PERTURBATION RELATIVE VORTICITY\n self.tot_ke = []\n self.expected_ke = np.sum(np.power(self.ub + self.up, 2) + np.power(self.vb + self.vp, 2)) \n \n # 3) STORE A COUPLE MORE VARIABLES\n # Map projections for plotting\n self.bmaps = create_basemaps(self.lons, self.lats)\n # Get the vorticity tendency forcing (if any) for integration\n self.forcing = forcing\n self.topography(ics['lats'], ics['lons'], planet=NL.topo) \n \n #==== Some simple dimensional functions ========================================== \n def nlons(self):\n return len(self.lons)\n def nlats(self):\n return len(self.lats)\n \n def topography(self, lats, lons, planet='Earth'):\n if planet == 'Earth':\n # From: http://research.jisao.washington.edu/data/elevation/\n d = Dataset('elev.0.25-deg.nc')\n #print(d.variables.keys())\n topo_lat = np.flipud(d['lat'])\n topo_lon = d['lon'][:]\n topo_elev = np.flipud(d['data'][0])\n \n # Mask out oceans\n idx = np.where(topo_elev < 0)\n topo_elev[idx[0], idx[1]] = 0\n \n # Interpolate topography data to the known grid\n elif planet == 'Mars':\n d = np.load('mars.npz')\n topo_lat = d['lats'][:,0][::-1]\n topo_lon = d['lons'][0,1:]+180\n topo_elev = d['data'][:,1:][::-1,:] \n elif planet == 'flat':\n d = Dataset('elev.0.25-deg.nc')\n topo_lat = np.flipud(d['lat'])\n topo_lon = d['lon'][:]\n topo_elev = np.flipud(d['data'][0])\n topo_elev[:,:] = 0\n elif planet == 'isolated_mountain':\n # From: http://research.jisao.washington.edu/data/elevation/\n d = Dataset('elev.0.25-deg.nc')\n #print(d.variables.keys())\n topo_lat = np.flipud(d['lat'])\n topo_lon = d['lon'][:]\n topo_elev = np.flipud(d['data'][0])\n \n # Mask out oceans\n idx = np.where(topo_elev < 4000)\n topo_elev[idx[0], idx[1]] = 0\n elif planet == 'block':\n # From: http://research.jisao.washington.edu/data/elevation/\n d = Dataset('elev.0.25-deg.nc')\n #print(d.variables.keys())\n topo_lat = np.flipud(d['lat'])\n topo_lon = d['lon'][:]\n topo_elev = np.flipud(d['data'][0])\n #print(topo_lat.shape, topo_lon.shape, topo_elev.shape)\n # Mask out oceans\n #idx = np.where(topo_elev < 4000)\n topo_elev[:, :] = 0\n idx = np.where((topo_lon > 30) & (topo_lon < 60))\n topo_elev[:, idx[0]] = 1000\n \n new_lon, new_lat = np.meshgrid(self.lons, self.lats)\n self.topo = basemap.interp(topo_elev, topo_lon, topo_lat, new_lon, new_lat, order=1)\n ##plt.title(\"Terrain\")\n #plt.pcolormesh(new_lon, new_lat, self.topo)\n #cb = plt.colorbar()\n #cb.ax.set_ylabel(\"Elevation [m]\")\n #plt.ylabel(\"Latitude\")\n #plt.xlabel(\"Longitude\")\n #plt.show()\n self.topo = gaussian_filter(self.topo, NL.smooth_topo)\n #plt.title(\"Terrain\")\n #plt.pcolormesh(new_lon, new_lat, self.topo)\n #cb = plt.colorbar()\n #cb.ax.set_ylabel(\"Elevation [m]\")\n #plt.ylabel(\"Latitude\")\n #plt.xlabel(\"Longitude\")\n #plt.show()\n \n #stop \n #==== Primary function: model integrator ========================================= \n def integrate(self):\n \"\"\" \n Integrates the barotropic model using spherical harmonics.\n Simulation configuration is set in namelist.py\n \"\"\"\n # Create a radian grid\n lat_list_r = [x * np.pi/180. for x in self.lats]\n lon_list_r = [x * np.pi/180. for x in self.lons]\n\n # Meshgrid\n lons,lats = np.meshgrid(self.lons, self.lats)\n lamb, theta = np.meshgrid(lon_list_r, lat_list_r)\n\n # Need these for derivatives later\n dlamb = np.gradient(lamb)[1]\n dtheta = np.gradient(theta)[0]\n\n # Plot Initial Conditions\n if NL.plot_freq != 0:\n self.plot_figures(0)\n\n # Now loop through the timesteps\n for n in range(NL.ntimes):\n \n #if n > 1000:\n # self.topo[:,:] = 0\n # Leapfrog:\n if NL.integration_method == 'leapfrog':\n vort_tend = self.gettend(self.vortp, dlamb, dtheta, theta, n)\n print(np.max(vort_tend), np.min(vort_tend))\n if n == 0:\n # First step just do forward difference\n # Vorticity at next time is just vort + vort_tend * dt\n vortp_next = self.vortp + vort_tend * NL.dt\n else:\n # Otherwise do leapfrog\n vortp_next = vortp_prev + vort_tend * 2 * NL.dt\n\n elif NL.integration_method == 'rk4':\n h = NL.dt\n # runge kutta requires 4 estimates of the tendency equation \n vortp = self.vortp\n\n k1 = self.gettend(vortp, dlamb, dtheta, theta, n)\n# print(\"k1:\",np.max(k1), np.min(k1))\n k2 = self.gettend(vortp + 0.5 * h * k1, dlamb, dtheta, theta, n)\n# print(\"k2:\",np.max(k2), np.min(k2))\n k3 = self.gettend(vortp + 0.5 * h * k2, dlamb, dtheta, theta, n)\n# print(\"k3:\",np.max(k3), np.min(k3))\n k4 = self.gettend(vortp + h * k3, dlamb, dtheta, theta, n)\n# print(\"k4:\",np.max(k4), np.min(k4))\n vortp_next = vortp + h*(k1 + 2*k2 + 2*k3 + k4)/6.\n# print(\"VORTP NEXT:\",np.max(vortp_next), np.min(vortp_next))\n \n if np.isnan(vortp_next).any():\n print(\"BOOM.\")\n print(\"Looks like your model blew up. Change the dt or try a different model!\")\n print(\"The barotropic model will exit now.\")\n sys.exit()\n\n # First go back to spectral space\n vortp_spec = self.s.grdtospec(vortp_next)\n div_spec = np.zeros(np.shape(vortp_spec)) # Divergence is zero in barotropic vorticity\n\n # Now use the spharm methods to update the u and v grid\n self.up, self.vp = self.s.getuv(vortp_spec, div_spec)\n self.psip, chi = self.s.getpsichi(self.up, self.vp)\n\n # Update the vorticity\n self.vortp = self.s.spectogrd(vortp_spec)\n\n # Invert this new vort to get the new psi (or rather, uv winds)\n self.tot_ke.append(np.sum(np.power(self.up+self.ub,2) + np.power(self.vp+self.vb,2)))\n # Change vort_now to vort_prev\n # and if not first step, add Robert filter to dampen out crazy modes\n if NL.integration_method == 'leapfrog':\n if n == 0:\n vortp_prev = self.vortp\n else:\n vortp_prev = (1.-2.*NL.r)*self.vortp + NL.r*(vortp_next + vortp_prev)\n\n # Update the current time \n cur_fhour = (n+1) * NL.dt / 3600.\n self.curtime = self.start_time + timedelta(hours = cur_fhour)\n\n # Make figure(s) every hours\n if NL.plot_freq!=0 and cur_fhour % NL.plot_freq == 0:\n # Go from psi to geopotential\n print(\"Plotting hour\", cur_fhour)\n self.plot_figures(int(cur_fhour))\n \n def gettend(self,vortp, dlamb, dtheta, theta, n):\n # self.psip, self.psib, self.vortp, self.vort_bar\n # \n # Here we actually compute vorticity tendency\n # Compute tendency with beta as only forcing\n vort_tend = -2. * NL.omega/(NL.Re**2) * d_dlamb(self.psip + self.psib, dlamb) - \\\n Jacobian(self.psip+self.psib, vortp+self.vort_bar, theta, dtheta, dlamb)\n \n # Apply hyperdiffusion if requested for smoothing\n if NL.diff_opt=='del4':\n vort_tend -= del4_filter(vortp, self.lats, self.lons)\n elif NL.diff_opt=='des':\n vort_tend = apply_des_filter(self.s, vortp, vort_tend, self.ntrunc,\n t = (n+1) * NL.dt / 3600.).squeeze()\n \n # Now add any imposed vorticity tendency forcing\n print(n, NL.forcing_time)\n if NL.use_forcing is True and n < NL.forcing_time:\n vort_tend += self.forcing\n\n # Now add any geographical vorticity tendency forcing\n f = 2 * NL.omega * np.sin(theta)\n vort_tend += -((f) * \\\n Jacobian(self.psip+self.psib, self.topo, theta, dtheta, dlamb)) / \\\n NL.fluid_height \n return vort_tend\n\n\n #==== Plotting utilities =========================================================\n def plot_figures(self, n, winds='total', vorts='total', psis='pert', showforcing=True,\n vortlevs=np.array([-10,-8,-6,-4,-2,2,4,6,8,10])*1e-5,\n windlevs=np.arange(20,61,4), hgtlevs=np.linspace(-500,500,26),\n forcelevs=np.array([-15,-12,-9,-6,-3,3,6,9,12,15])*1e-10):\n \"\"\"\n Make global and regional plots of the flow.\n \n Requires:\n n ------------------> timestep number\n winds, vorts, psis -> are we plotting the 'mean', 'pert', or 'total' field?\n showforcing --------> if True, contour the vorticity tendency forcing\n *levs --------------> contour/fill levels for the respective variables\n \"\"\"\n # What wind component(s) are we plotting?\n if winds=='pert': u = self.up; v = self.vp\n elif winds=='mean': u = self.ub; v = self.vb\n else: u = self.up+self.ub; v = self.vp+self.vb\n # What vorticity component(s) are we plotting?\n if vorts=='pert': vort = self.vortp\n elif vorts=='mean': vort = self.vort_bar\n else: vort = self.vortp + self.vort_bar\n # What streamfunction component(s) are we plotting?\n if psis=='pert': psi = self.psip\n elif psis=='mean': psi = self.psib\n else: psi = self.psip + self.psib\n\n # MAKE GLOBAL ZETA & WIND BARB MAP\n fig, ax = plt.subplots(figsize=(10,8))\n fig.subplots_adjust(bottom=0.2, left=0.05, right=0.95)\n \n xx, yy = self.bmaps['global_x'], self.bmaps['global_y']\n plt.pcolormesh(xx, yy, self.topo, alpha=1, cmap='gist_earth', vmin=np.min(self.topo), vmax=np.max(self.topo))\n cs = ax.contourf(xx, yy, vort, vortlevs, cmap=plt.cm.RdBu_r, extend='both', alpha=0.5)\n plt.xlim(xx.min(), xx.max())\n plt.ylim(yy.min(), yy.max())\n if NL.topo == 'Earth':\n self.bmaps['global'].drawcoastlines()\n parallels = np.arange(-70.,81,10.)\n meridians = np.arange(10.,351.,20.)\n self.bmaps['global'].drawmeridians(meridians,labels=[True,False,False,True])\n self.bmaps['global'].drawparallels(parallels,labels=[True,False,False,True])\n ax.quiver(xx[::2,::2], yy[::2,::2], u[::2,::2], v[::2,::2])\n # Plot the forcing\n if showforcing and self.forcing is not None:\n ax.contour(xx, yy, self.forcing, forcelevs, linewidths=2, colors='darkorchid')\n ax.set_title('relative vorticity [s$^{-1}$] and winds [m s$^{-1}$] at %03d hours' % n)\n # Colorbar\n cax = fig.add_axes([0.05, 0.12, 0.9, 0.03])\n plt.colorbar(cs, cax=cax, orientation='horizontal')\n # Save figure\n if not os.path.isdir(NL.figdir+'/global'): os.makedirs(NL.figdir+'/global')\n plt.savefig('{}/global/zeta_wnd_{:03d}.png'.format(NL.figdir,n), bbox_inches='tight')\n plt.close()\n\n # MAKE REGIONAL HEIGHT & WIND SPEED MAP\n phi = np.divide(psi * NL.omega, NL.g)\n fig, ax = plt.subplots(figsize=(10,6))\n fig.subplots_adjust(bottom=0.2, left=0.05, right=0.95)\n xx, yy = self.bmaps['regional_x'], self.bmaps['regional_y']\n # Calculate wind speed\n wspd = np.sqrt(u**2 + v**2)\n cs = ax.contourf(xx, yy, wspd, windlevs, cmap=plt.cm.viridis, extend='max')\n self.bmaps['regional'].drawcoastlines()\n self.bmaps['regional'].drawcountries()\n self.bmaps['regional'].drawstates()\n hgtconts = ax.contour(xx, yy, phi, hgtlevs, colors='k')\n # Plot the forcing\n if showforcing and self.forcing is not None:\n ax.contour(xx, yy, self.forcing, forcelevs, linewidths=2, colors='darkorchid')\n ax.set_title('geopotential height [m] and wind speed [m s$^{-1}$] at %03d hours' % n)\n # Colorbar\n cax = fig.add_axes([0.05, 0.12, 0.9, 0.03])\n plt.colorbar(cs, cax=cax, orientation='horizontal')\n # Save figure\n if not os.path.isdir(NL.figdir+'/regional'): os.makedirs(NL.figdir+'/regional')\n plt.savefig('{}/regional/hgt_wspd_{:03d}.png'.format(NL.figdir,n), bbox_inches='tight')\n plt.close()\n \n \n###########################################################################################################\n##### Other Utilities #####################################################################################\n###########################################################################################################\n\n\ndef create_basemaps(lons,lats):\n \"\"\" Setup global and regional basemaps for eventual plotting \"\"\"\n print(\"Creating basemaps for plotting\")\n\n long, latg = np.meshgrid(lons,lats)\n\n # Set up a global map\n bmap_globe = Basemap(projection='merc',llcrnrlat=-70, urcrnrlat=70,\n llcrnrlon=0,urcrnrlon=360,lat_ts=20,resolution='c')\n xg,yg = bmap_globe(long,latg)\n \n # Set up a regional map (currently Pacific and N. America)\n bmap_reg = Basemap(projection='merc',llcrnrlat=0,urcrnrlat=65,llcrnrlon=80, \n urcrnrlon=290, lat_ts=20,resolution='l')\n xr,yr = bmap_reg(long,latg)\n\n return {'global' : bmap_globe, \n 'global_x' : xg, \n 'global_y' : yg,\n 'regional' : bmap_reg,\n 'regional_x' : xr, \n 'regional_y' : yr, \n }\n\ndef d_dlamb(field,dlamb):\n \"\"\" Finds a finite-difference approximation to gradient in\n the lambda (longitude) direction\"\"\"\n out = np.divide(np.gradient(field)[1],dlamb) \n return out\n\ndef d_dtheta(field,dtheta):\n \"\"\" Finds a finite-difference approximation to gradient in\n the theta (latitude) direction \"\"\"\n out = np.divide(np.gradient(field)[0],dtheta)\n return out\n\ndef Jacobian(A,B,theta,dtheta,dlamb):\n \"\"\" Returns the Jacobian of two fields in spherical coordinates \"\"\"\n term1 = d_dlamb(A,dlamb) * d_dtheta(B,dtheta)\n term2 = d_dlamb(B,dlamb) * d_dtheta(A,dtheta)\n return 1./(NL.Re**2 * np.cos(theta)) * (term1 - term2)\n\n###########################################################################################################\n\ndef test_case():\n \"\"\"\n Runs an example case: extratropical zonal jets with superimposed sinusoidal NH vorticity\n perturbations and a gaussian vorticity tendency forcing.\n \"\"\"\n from time import time\n start = time()\n \n # 1) LET'S CREATE SOME INITIAL CONDITIONS\n lons = np.arange(0, 360.1, 2.5)\n lats = np.arange(-87.5, 88, 2.5)[::-1]\n lamb, theta = np.meshgrid(lons * np.pi/180., lats * np.pi/180.)\n # Mean state: zonal extratropical jets\n ubar = NL.mag * np.cos(theta) - 30 * np.cos(theta)**3 + 300 * np.sin(theta)**2 * np.cos(theta)**6\n vbar = np.zeros(np.shape(ubar))\n # Initial perturbation: sinusoidal vorticity perturbations\n theta0 = np.deg2rad(NL.pert_center_lat) # center lat = 45 N\n thetaW = np.deg2rad(NL.pert_width) #15\n vort_pert = 0.5*NL.A*np.cos(theta)*np.exp(-((theta-theta0)/thetaW)**2)*np.cos(NL.m*lamb)\n \n # Get U' and V' from this vorticity perturbation\n s = spharm.Spharmt(len(lons), len(lats), gridtype='regular', legfunc='computed', rsphere=NL.Re)\n uprime, vprime = s.getuv(s.grdtospec(vort_pert), np.zeros(np.shape(s.grdtospec(vort_pert))))\n # Full initial conditions dictionary:\n ics = {'u_bar' : ubar,\n 'v_bar' : vbar,\n 'u_prime': uprime,\n 'v_prime': vprime,\n 'lons' : lons,\n 'lats' : lats,\n 'start_time' : datetime(2017,1,1,0)}\n\n # 2) LET'S ALSO FEED IN A GAUSSIAN NH RWS FORCING (CAN BE USED TO CREATE SYNTEHTIC HURRICANES)\n amplitude = NL.forcing_amp # s^-2\n forcing = np.zeros(np.shape(ubar))\n x, y = np.meshgrid(np.linspace(-1,1,10), np.linspace(-1,1,10))\n d = np.sqrt(x*x+y*y)\n sigma, mu = 0.5, 0.0\n g = np.exp(-( (d-mu)**2 / ( 2.0 * sigma**2 ) ) ) # GAUSSIAN CURVE\n source_lat = NL.forcing_lat; source_lon = NL.forcing_lon # The location of the forcing\n lat_i = np.where(lats==source_lat)[0][0]\n lon_i = np.where(lons==source_lon)[0][0]\n if NL.use_forcing == True:\n forcing[lat_i:lat_i+10, lon_i:lon_i+10] = g*amplitude\n else:\n forcing[:,:] = 0\n\n # 3) INTEGRATE!\n model = Model(ics, forcing=forcing)\n model.integrate()\n print('TOTAL INTEGRATION TIME: {:.02f} minutes'.format((time()-start)/60.))\n plt.plot((NL.dt * np.arange(len(model.tot_ke)))/3600., (1 - model.tot_ke/model.expected_ke) * 100)\n #plt.plot(np.arange(len(model.tot_ke)), model.tot_ke, 'o-')\n plt.title('Model Kinetic Energy Error vs. Time Step')\n plt.xlabel(\"Model Time [hr]\")\n plt.ylabel(u'Model Kinetic Energy Error [%]')\n print(\"Expected Kinetic Energy [m^2/s^2]:\", model.expected_ke)\n plt.savefig(NL.figdir + '/model_ke_ts.png', bbox_inches='tight')\n\nif __name__ == '__main__':\n test_case()\n","sub_path":"barotropic_spectral.py","file_name":"barotropic_spectral.py","file_ext":"py","file_size_in_byte":20695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"248219975","text":"#!/usr/bin/python3\n\n# Twitter Utilitarios\n# Author: Jose Fonseca (https://zefonseca.com/)\n\n# hashblocker.py\n# Bloqueia usuarios com base em termos de busca.\n# Use com cautela.\n# Blocks users whose tweets match search results.\n# Use with caution.\n\nimport conf\nimport time\nimport sys\nfrom TwitterAPI import TwitterAPI\nfrom TwitterAPI import TwitterPager\n\nespera_posban = 3\nespera_posloop = 1\nespera_timeout = 10\nespera_except = 20\ntotal_bloqueados = 0\nbloqueados = set()\n\nif len(sys.argv) < 2:\n print(\"Uso: python3 hashblocker.py \")\n sys.exit(1)\n\nq = sys.argv[1]\n\napi = TwitterAPI(conf.api_key, conf.api_secret, conf.token_key, conf.token_secret)\n\nprint(\"PROCURANDO TWEETS CONTENDO {}\".format(q))\n\nr = TwitterPager(api, 'search/tweets', {'q':q, 'count':100})\n\nfor item in r.get_iterator():\n if 'text' in item:\n\n id = item['user']['screen_name']\n\n if (id not in bloqueados):\n total_bloqueados += 1\n print(\"BLOQUEANDO {} - TOTAL DE BLOQUEADOS: {}\".format(id,total_bloqueados))\n flg = False\n\n while not flg:\n try:\n ret = api.request('blocks/create', {'screen_name':id})\n bloqueados.add(id)\n time.sleep(espera_posban)\n flg = True\n except:\n print(\"ERRO NO BLOQUEIO. AGUARDANDO {} SEGUNDOS PARA TENTAR NOVAMENTE\".format(espera_except))\n time.sleep(espera_except)\n\n elif 'message' in item and item['code'] == 88:\n print('AGUARDANDO {} SEGUNDOS (ATINGIDO LIMITE POR SEGUNDO): {}}\\n'.format(espera_timeout, item['message']))\n time.sleep(espera_timeout)\n\n time.sleep(espera_posloop)","sub_path":"hashblocker.py","file_name":"hashblocker.py","file_ext":"py","file_size_in_byte":1715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"473496196","text":"import spacy_universal_sentence_encoder\nfrom quickdraw import QuickDrawData\nnlp = spacy_universal_sentence_encoder.load_model('en_use_lg')\nqd = QuickDrawData()\nfrom quickdraw import QuickDrawDataGroup\nimport datetime\ndef doodle(text):\n doc_1 = nlp(text)\n score = {}\n for a in list(qd.drawing_names):\n doc_2 = nlp(a)\n score[a] = doc_1.similarity(doc_2)\n cat = sorted(score)\n doodle_cat = \"bird\"\n ants = QuickDrawDataGroup(doodle_cat)\n ant = ants.get_drawing()\n name = datetime.datetime.now().strftime(\"%Y_%m_%d-%I:%M:%S_%p\")\n ant.image.save(f\"frontend/src/assets/doodle/{name}.jpg\")\n\nimport os\nimport cv2\nfrom PIL import Image\n\nclass doodle_2_vid():\n def __init__(self) -> None:\n pass\n def find_mean_shape(self, path):\n mean_height = 0\n mean_width = 0\n\n num_of_images = len(os.listdir(path))\n\n for file in os.listdir(path):\n if file.endswith(\".jpg\") or file.endswith(\".jpeg\") or file.endswith(\"png\"):\n im = Image.open(os.path.join(path, file))\n width, height = im.size\n mean_width += width\n mean_height += height\n\n mean_width = int(mean_width / num_of_images)\n mean_height = int(mean_height / num_of_images)\n return mean_height, mean_width\n\n\n def resize(self, path):\n mean_height, mean_width = self.find_mean_shape(path)\n\n for file in os.listdir(path):\n if file.endswith(\".jpg\") or file.endswith(\".jpeg\") or file.endswith(\"png\"):\n\n im = Image.open(os.path.join(path, file))\n os.remove(os.path.join(path, file))\n\n width, height = im.size\n print(width, height)\n\n imResize = im.resize((mean_width, mean_height), Image.ANTIALIAS)\n imResize.save(os.path.join(path, file), \"JPEG\", quality=100)\n\n print(im.filename.split(\"\\\\\")[-1], \" is resized\")\n\n\n def generate_video(self, in_path, out_path):\n image_folder = in_path\n video_name = os.path.join(out_path, \"doodle.avi\")\n\n self.resize(image_folder)\n images = [\n img\n for img in os.listdir(image_folder)\n if img.endswith(\".jpg\") or img.endswith(\".jpeg\") or img.endswith(\"png\")\n ]\n\n print(images)\n\n frame = cv2.imread(os.path.join(image_folder, images[0]))\n\n height, width, layers = frame.shape\n # fourcc = cv2.VideoWriter_fourcc(*'FMP4')\n video = cv2.VideoWriter(video_name, 0, 1, (width, height))\n\n for image in images:\n video.write(cv2.imread(os.path.join(image_folder, image)))\n\n cv2.destroyAllWindows()\n video.release()\n output = \"generated\"\n os.popen(\"ffmpeg -y -i 'frontend/src/assets/video/doodle.avi' -ac 2 -b:v 2000k -c:a aac -c:v libx264 -b:a 160k -vprofile high -bf 0 -strict experimental -f mp4 'frontend/src/assets/video/doodle.mp4'\")\n\n# generate_video(\"images\", \"video\")\n\n\n# doodle(\"dog running ground\")","sub_path":"backend/doodle_generator.py","file_name":"doodle_generator.py","file_ext":"py","file_size_in_byte":3016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"203897536","text":"from history_tool import History, AddHistoryMixIn\nfrom typing import Union\n\n\nclass NegativeValue(Exception):\n pass\n\n\nclass BalanceTooLow(Exception):\n pass\n\n\nclass Account(AddHistoryMixIn):\n\n def __init__(self, id, balance :Union[int, float] = 0, client_name :str = '') -> None:\n super().__init__()\n self.client_name = client_name\n self.id = id\n if balance < 0:\n raise NegativeValue(\"You can't deposit a negative value or equal to zero.\")\n self.balance = balance\n self.add_history(\n message=f\"Account {id} opened with balance {balance}\"\n )\n self.active = True\n\n def deposit(self, value :Union[int, float]) -> None:\n self.add_history(\n message=f\"Deposit of {value}\"\n )\n if value <= 0:\n raise NegativeValue(\"You can't deposit a negative value or equal to zero.\")\n self.balance += value\n\n def withdrawal(self, value :Union[int, float]) -> None:\n if self.balance - value < 0:\n self.add_history(\n message=f\"Withdrawal {value} failed. BalanceTooLow\"\n )\n raise BalanceTooLow(\"You don't have enough money on your account.\")\n self.add_history(\n message=f\"Withdrawal {value}\"\n )\n self.balance -= value\n\n def close(self) -> Union[int, float]:\n self.active = False\n self.add_history(\n message=f\"Account {self.id} closed. Returned {self.balance} cash\",\n )\n return self.balance","sub_path":"account.py","file_name":"account.py","file_ext":"py","file_size_in_byte":1534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"583663173","text":"\"\"\" File: utils.py \"\"\"\n# Author: @parthraghav\n\nimport math\nimport random\nimport string\n\nALPHABET = string.ascii_uppercase + string.ascii_lowercase\n\ndef irange(a, b = None):\n\t\"\"\" Wrapper for Inclusive range [a, b] \"\"\"\n\tassert type(a) == int and ( b == None or type(b) == int )\n\n\tif b == None:\n\t\tif a <= 0:\n\t\t\treturn range(a)\n\t\telse:\n\t\t\treturn range(a+1)\n\telse:\n\t\treturn range(a, b+1)\n\ndef isPowerOfFour(n):\n\tif n ==1:\n\t\treturn True\n\telif n == 0:\n\t\treturn False\n\telif n%4 != 0:\n\t\treturn False\n\telif n == 1 or isPowerOfFour( n//4 ):\n\t\treturn True\n\treturn False\n\ndef int2bin(n, d = None):\n\t\"\"\" Converts integer number to binary,\n\twith d bits, and left-padded with zeros \"\"\"\n\n\tassert type(n) == int and ( d == None or type(d) == int )\n\n\tif (d == None):\n\t\tdigits = 8\n\t\td = math.ceil( math.log(n, 2) )\n\n\t\tif d > digits:\n\t\t\tdigits = int(d)\n\telse:\n\t\tdigits = d\n\treturn ('{0:0b}'.format(n)).rjust(digits, '0')\n\ndef bin2hex(n, w = 2):\n\t\"\"\" Convert a binary number to hex \"\"\"\n\n\tassert type(d) == str\n\n\treturn '{:0{w}x}'.format(int(n,2), w = w)\n\nclass Toggler():\n\tdef __init__(self, rng):\n\t\tassert type(rng)==range\n\t\tself.vals = list(rng)\n\t\tself.indx = 0\n\t\tself.curr = self.vals[self.indx]\n\tdef toggle(self):\n\t\tself.indx = (self.indx + 1)%len(self.vals)\n\t\tself.curr = self.vals[self.indx]\n\tdef __int__(self):\n\t\treturn int(self.curr)\n\tdef __repr__(self):\n\t\treturn 'Toggle(current={current},states={states})'.format(current = self.curr, states = int(self.vals))\n\ndef generate_random_str(length, typecase = 2):\n\t\"\"\"\n\t\t@length\t\t\t\t[length of the output]\t\t\t\t\t\t\t\t\n\t\t@typecase = 1,\t\t[output in UPPER case only]\n\t\t@typecase = 2,\t\t[output in BOTH upper and lower cases]\n\t\t@typecase = 3,\t\t[output in LOWER case only]\n\t\"\"\"\n\t\n\tif typecase == 1:\n\t\tstart = 0\n\t\tend = 25\n\telif typecase == 2:\n\t\tstart = 0\n\t\tend = 51\n\telif typecase == 3:\n\t\tstart = 26\n\t\tend = 51\n\telse:\n\t\traise ValueError(\"Wrong value of argument; @typecase should be lte 3.\")\n\t\n\tfin = ALPHABET[start:end]\n\tfout = \"\"\n\twhile length > 0:\n\t\tfout += ALPHABET[random.randint(start, end)]\n\t\tlength -= 1\n\treturn fout\t\n\ndef test_irange():\n\t\"\"\" Unit test for irange() function \"\"\"\n\n\tassert 0 in irange(-1, 0)\n\tassert 0 in irange(0, 10)\n\tassert -8 in irange(-12, -3)\n\tassert 8 in irange(3, 8)\n\n\tprint(\"all unit tests for irange() passed successfully!\")\n\ndef test_int2bin():\n\t\"\"\" Unit test for int2bin() function \"\"\"\n\n\tassert (int2bin(1) == '00000001')\n\tassert (int2bin(10) == '00001010')\n\tassert (int2bin(100) == '01100100')\n\tassert (int2bin(1000) == '1111101000')\n\tassert (int2bin(10000) == '10011100010000')\n\n\tprint(\"all unit tests for int2bin() passed successfully!\")\n\ndef test_bin2hex():\n\t\"\"\" Unit test for bin2hex() function \"\"\"\n\tassert (bin2hex('00000001') == '01')\n\tassert (bin2hex('00001010') == '0a')\n\tassert (bin2hex('01100100') == '64')\n\tassert (bin2hex('1111101000') == '3e8')\n\tassert (bin2hex('10011100010000') == '2710')\n\n\tprint(\"all unit tests for bin2hex() passed successfully!\")\n\n\ndef test_toggler():\n\t\"\"\" Unit test for Toggler class \"\"\"\n\tt = Toggler(range(0,2))\n\tassert int(t) == 0\n\tt.toggle()\n\tassert int(t) == 1\n\tt.toggle()\n\tassert int(t) == 0\n\tt.toggle()\n\tassert int(t) == 1\n\n\tprint(\"all unit tests for Toggler() passed successfully!\")\n\ndef test_generate_random_str():\n\t\"\"\"\n\t\tUnit test for the generate_random_str() function\n\t\"\"\"\n\n\tassert len(generate_random_str(0)) == 0\n\tassert len(generate_random_str(10)) == 10\n\tassert len(generate_random_str(99)) == 99\n\n\tupper = generate_random_str(100, 1)\n\ti = 0\n\twhile (i < len(upper)):\n\t\tassert (upper[i] in ALPHABET[:len(ALPHABET)//2]\n\t\t\tand not upper[i] in ALPHABET[len(ALPHABET)//2:])\n\t\ti += 1\n\n\tlower = generate_random_str(100, 3)\n\ti = 0\n\twhile (i < len(lower)):\n\t\tassert (lower[i] in ALPHABET[len(ALPHABET)//2:]\n\t\t\tand not lower[i] in ALPHABET[:len(ALPHABET)//2])\n\t\ti += 1\n\n\tprint(\"all unit tests passed successfully!\")\n\ndef test_isPowerOfFour():\n\n\tassert ( _isPowerOfFour(0) == False )\n\tassert ( _isPowerOfFour(1) == True )\n\tassert ( _isPowerOfFour(2) == False )\n\tassert ( _isPowerOfFour(4) == True )\n\tassert ( _isPowerOfFour(8) == False )\n\tassert ( _isPowerOfFour(16) == True )\n\n\tfor i in [pow(4,i) for i in range(20)]:\n\t\tassert ( _isPowerOfFour(i) == True )\n\n\nif __name__ == \"__main__\":\n\ttest_irange()\n\ttest_int2bin()\n\ttest_bin2hex()\n\ttest_toggler()\n\ttest_generate_random_str()\n\ttest_isPowerOfFour()","sub_path":"cuteqr/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"315569724","text":"\"\"\"Setup module.\"\"\"\nimport logging\nfrom pathlib import Path\n\nfrom setuptools import find_packages, setup # type: ignore\n\n\ndef main() -> None:\n \"\"\"Run setup.\"\"\"\n # run setup\n setup(\n name='pybotics',\n packages=find_packages(),\n url='https://github.com/nnadeau/pybotics',\n license='MIT',\n author='Nicholas Nadeau',\n author_email='nicholas.nadeau@gmail.com',\n description='Python Toolbox for Robotics',\n long_description=get_long_description(),\n long_description_content_type='text/markdown',\n use_scm_version=True,\n setup_requires=[\n 'setuptools',\n 'setuptools_scm'\n ],\n install_requires=get_requirements(), # type: ignore\n tests_require=['pytest'],\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Intended Audience :: Developers',\n 'Intended Audience :: Education',\n 'Intended Audience :: End Users/Desktop',\n 'Intended Audience :: Manufacturing',\n 'Intended Audience :: Science/Research',\n 'Topic :: Education',\n 'Topic :: Scientific/Engineering',\n 'Topic :: Scientific/Engineering :: Artificial Intelligence',\n 'Topic :: Scientific/Engineering :: Human Machine Interfaces',\n 'Topic :: Scientific/Engineering :: Mathematics',\n 'Topic :: Scientific/Engineering :: Physics',\n 'Topic :: Utilities',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python :: 3 :: Only',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n ],\n keywords=[\n 'python',\n 'robot',\n 'robotics',\n 'research',\n 'automation',\n 'kinematics',\n 'geometry',\n ]\n )\n\n\ndef get_long_description() -> str:\n \"\"\"Get description text.\"\"\"\n # description init\n description = ''\n\n # add README\n path = Path(__file__).parent / 'README.md'\n logging.info('README path: {}'.format(path.resolve()))\n with open(str(path)) as f:\n description += '\\n'\n description += f.read()\n\n # add changelog\n path = Path(__file__).parent / 'CHANGELOG.md'\n logging.info('CHANGELOG path: {}'.format(path.resolve()))\n with open(str(path)) as f:\n description += '\\n'\n description += f.read()\n\n return description\n\n\n# don't want to import typing... so ignore type\ndef get_requirements(): # type: ignore\n \"\"\"Get requirements list.\"\"\"\n # requirements\n requirements_path = Path(__file__).parent / 'requirements.txt'\n logging.info('Requirements path: {}'.format(requirements_path.resolve()))\n with open(str(requirements_path)) as f:\n requirements = f.read().splitlines()\n return requirements\n\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.INFO)\n main()\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"418297532","text":"import sys\n\n\nif len(sys.argv) <= 1:\n exit(0)\n\ntest_cases = open(sys.argv[1], 'r')\nl = []\nfor test in test_cases:\n test = test.strip(\"\\n\")\n if test == \"\":\n continue\n \n l.append(test)\n \ntest_cases.close()\n\n\n\nfor s in l:\n to_sort = []\n for d in s.split(\" \"):\n to_sort.append(float(d))\n u = [\"{:.3f}\".format(f) for f in sorted(to_sort)]\n print(\" \".join(u))","sub_path":"CodeEval/Challenge Solutions/easy/Python/091_simple_sorting.py","file_name":"091_simple_sorting.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"519104049","text":"import Grabber\nimport IO\nimport multiprocessing\nimport os\nfrom IO import SongList, Logger\nfrom multiprocessing import Value\n\n\ndef cleanup(args):\n print(\"At exit triggered\")\n args[1].clear()\n args[1].update(args[0])\n args[1].close()\n args[2].close()\n\n\nif __name__ == '__main__':\n import ctypes\n import atexit\n\n # This reads the settings file which the container executable for this should assert exists. In the case it\n # doesn't exist, this program will crash before it can even do anything. Make sure the settings file exists\n # in the same directory as this script and make sure it is formatted as such (python dictionary type):\n # {'songlist': %path of songlist.txt%, 'log': %path of log.txt%, 'root': %root music directory%, 'defaults':{'source': 'yt', '-o': True}}\n settings = IO.initialize()\n\n # The next two lines assert that songlist file and the log file exist. This is important and if they don't, ensure\n # that both the files exist in the directories as specified by the settings.txt file.\n assert(os.path.exists(settings['log']))\n assert(os.path.exists(settings['songlist']))\n\n # The next two lines initialize the logger and the songlist classes which may be used various times throughout this\n # script. The program crashes if the log or songlist files are unwritable/unreadable as the errors aren't handled.\n logger = Logger(open(settings['log'], 'r+'))\n songlist = SongList(open(settings['songlist'], 'r+'))\n\n # Initialize the webbrowser that will be passed to each song to retrive the offliberty URL. This could be done by\n # the song each time but that increases overhead slightly and risks the webdriver not being terminated as it should\n # when the process is terminated. So instead the webdriver/webbrowser will be initialized once and passed along each time.\n\n songs = songlist.get_songs()\n songs = list(filter(lambda x: x.strip() != \"\", songs))\n\n logger.clear()\n # songlist.clear()\n\n # register cleanup atexit now that all necessary variables have been initialized:4\n print(songs)\n atexit.register(cleanup, [songs, songlist, logger])\n print(\"Atexit registered.\")\n # exit()\n\n # cross_globals = [__name__, settings, logger, driver]\n\n if len(songs) != 0:\n logger.log(str(len(songs)) + \" items found in songlist.txt. Attempting to download\")\n count = 0\n total = len(songs)\n logger.close()\n for song in songs:\n # Initialize the shared state variable that will be shared with the following subprocess \"sub\"\n skipped = Value(ctypes.c_bool, True)\n\n # Start Grab as a subprocess\n sub = multiprocessing.Process(target=Grabber.grab, args=(settings, song, skipped))\n sub.start()\n sub.join(90)\n\n try:\n logger = Logger(open(settings['log'], 'a'))\n except:\n pass\n\n # Terminate thread if it is still alive after the 90 second timeout\n if sub.is_alive() and skipped.value:\n sub.terminate()\n sub.join()\n logger = \"\"\n try:\n logger = Logger(open(settings['log'], 'a'))\n except:\n logger.close()\n logger = Logger(open(settings['log'], 'a'))\n message = \"Stalled trying to download \" + song + \". Skipping the current song.\"\n logger.log(message)\n elif skipped.value:\n message = \"The song was skipped due to an error.\"\n logger.log(message)\n else:\n message = \"The song was successfully downloaded.\"\n logger.log(message)\n count += 1\n songs.remove(song)\n logger.log(\"\")\n logger.flush()\n logger.log(\"Successfully downloaded \" + str(count) + \"/\" + str(total) + \" songs.\")\n else:\n logger.log(\"No items found in songlist.txt. Terminating program\")\n","sub_path":"musicgrabber/Wrapper.py","file_name":"Wrapper.py","file_ext":"py","file_size_in_byte":4029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"37141996","text":"#!/usr/bin/env python3\n\nfrom time import sleep\nimport serial\nfrom sys import argv as args\n\n\ntry:\n port = args[1]\nexcept:\n port = \"/dev/ttyUSB0\"\n\ntry:\n baud = args[2]\nexcept:\n baud = 115200\n\nser = serial.Serial(port, baud) # Establish the connection on a specific port\n# ser.ReadIntervalTimeout=0\nwhile True:\n try:\n dicks = ser.readline().decode('utf-8')\n except:\n dicks = ser.readline()\n \n print(dicks,end='') # Read the newest output from the Arduino\n #sleep(.1) # Delay for one tenth of a second\n # ser.\n","sub_path":"LED2/ESP8266_Master/monitor.py","file_name":"monitor.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"541341690","text":"import requests\nimport string\nfrom bs4 import BeautifulSoup\nurl = \"https://www.ps.kz/domains/lists/free?letter=%s&period=all\"\nsigns = list(string.ascii_uppercase) + list(string.digits)\nfor sign in signs:\n\tresponse = requests.get(url % sign)\n\tsoup = BeautifulSoup(response.content,\"html.parser\")\n\tdomain_table = soup.find(\"table\", { \"class\" : \"table table-bordered\" })\n\tlinks = domain_table.find_all('a')\n\tfor link in links:\n\t\tif '.kz' in link.text:\n\t\t\toutput = open('sites/%s.txt' % (len(link.text) - 3),'a')\n\t\t\toutput.write(link.text + \"\\n\")\n\t\t\toutput.close()\n","sub_path":"sites.py","file_name":"sites.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"192983286","text":"from bs4 import BeautifulSoup\nfrom urllib.request import Request, urlopen\nfrom urllib.error import HTTPError,URLError\nimport requests\nimport subprocess\nimport pickle\nimport argparse\nimport json\nimport threading\nimport sys\n\n# class crawlingThread (threading.Thread):\n# def __init__(self, url, movies_data):\n# threading.Thread.__init__(self)\n# self.url = url\n# self.movies_data = movies_data\n# #self.counter = counter\n# def run(self):\n# print(\"Starting \", url)\n# # Acquire lock to synchronize thread\n# #threadLock.acquire()\n# update_movie_list(self.url, self.movies_data)\n# # Release lock for the next thread\n# #threadLock.release()\n# #print \"Exiting \" + self.name\n\n\n# # Returns all movies and it's page url\n# def update_movie_list(url, movies_data):\n# cont = requests.get(url)\n\n# if cont.status_code == 200:\n# soup = BeautifulSoup(cont.content, 'html.parser')\n# movielinks = soup.find_all(\"a\", class_=\"movielink\")\n\n# import pdb\n# pdb.set_trace()\n\n# for movie in movielinks:\n# movies_data.append((movie.string, movie['href']))\n\n# print('nice')\n\n\nclass myThread (threading.Thread):\n def __init__(self, movie, movies):\n threading.Thread.__init__(self)\n self.movie = movie\n self.movies = movies\n #self.counter = counter\n def run(self):\n #print(\"Starting \", self.movie)\n # Acquire lock to synchronize thread\n #threadLock.acquire()\n update_movies_torrent_url(self.movie, self.movies)\n # Release lock for the next thread\n #threadLock.release()\n #print \"Exiting \" + self.name\n\n\n# Returns all movies and it's torrent url\ndef update_movies_torrent_url(movie, movies):\n #print(url)\n cont = requests.get(movie[1])\n\n if cont.status_code == 200:\n soup = BeautifulSoup(cont.content, 'html.parser')\n torrent_urls = soup.find_all('a', id=\"dt\")\n movies[movie[0]] = torrent_urls[0]['href']\n\n\n# Returns all movies and it's page url\ndef get_movie_list(url):\n cont = requests.get(url)\n\n if cont.status_code == 200:\n soup = BeautifulSoup(cont.content, 'html.parser')\n movielinks = soup.find_all(\"a\", class_=\"movielink\")\n\n movies_data = []\n for movie in movielinks:\n movies_data.append((movie.string, movie['href']))\n\n return movies_data\n\n\n# Saves torrent file of from given url\ndef get_movie_torrent(url):\n torrent_file = url.rsplit('/', 1)[1]\n print(\"downloading \", url)\n try:\n #headers = { 'User-Agent': 'Mozilla/5.0' }\n r = requests.get(url, headers='', stream=True)\n with open(torrent_file, 'wb') as f:\n for chunk in r.iter_content(chunk_size=32*1024):\n if chunk:\n f.write(chunk)\n f.flush()\n except requests.exceptions.RequestException as e:\n print('\\n' + OutColors.LR + str(e))\n sys.exit(1);\n\n\ndef search_movie(movie_name, movies):\n # Look for exact movie name match\n if movie_name in movies:\n print('Movie Name:{0}'.format(movie_name))\n print('Movie Torrent:{0}'.format(movies[movie_name]))\n return\n\n # Look for movie name as a keyword in list of movies (keys)\n movie_list = list(movies.keys())\n movies_found = [movie for movie in movie_list if movie_name.lower() in movie.lower()]\n\n return movies_found\n #for movie in movies_found:\n #print('Found:{0} - {1}'.format(movie, movies[movie]))\n\n\nif __name__ == '__main__':\n\n movie_resolution = '1080p'\n pages = 200\n # movies read from movies.json\n movies = {}\n #threadLock = threading.Lock()\n\n movie_name = ''\n\n parser = argparse.ArgumentParser(description='Happy Movie Watching!')\n parser.add_argument('-m', help='provide movie name')\n parser.add_argument('-u', help='update movies')\n parser.add_argument('--resolution', help='provide movie resolution')\n\n args = parser.parse_args()\n\n if args.m:\n movie_name = args.m\n\n if args.resolution:\n movie_resolution = args.resolution\n\n try:\n with open('movies.json', 'r') as f:\n movies = json.load(f)\n except IOError as e:\n print(\"warning: 'movies.json' not found\")\n\n if movie_name:\n print('Searching for {0}...'.format(movie_name))\n found_movies = search_movie(movie_name, movies)\n for count, movie in enumerate(found_movies):\n print('{0} - {1} ### {2}'.format(count +1 , movie, movies[movie]))\n sys.exit()\n\n movies_data = []\n #crawling_threads = []\n for page in list(range(1, pages+1)):\n url = 'https://yifymovie.re/search/0/{0}/All/0/latest/60/page/{1}/'.format(movie_resolution, page)\n\n # Get the list of tuples (movie name, url which contains link to torrent file)\n\n #threads_id = crawlingThread(url, movies_data)\n #threads_id.start()\n #threads_id.join()\n #crawling_threads.append(threads_id)\n movies_per_page = get_movie_list(url)\n print('Crawling {0} - {1} movies'.format(url, len(movies_per_page)))\n if not movies_per_page:\n print(\"Crawling is done.\")\n break\n\n movies_data += movies_per_page;\n #print(movies_data)\n\n #for thread in crawling_threads:\n #thread.join()\n\n data_len = len(movies_data)\n threads = []\n for count, movie in enumerate(movies_data):\n if movie[0] not in movies:\n print(\"Retrieving torrent url {0}/{1} - {2}...\".format(count+1, data_len, movie[0]))\n threads_id = myThread(movie, movies)\n threads_id.start()\n threads.append(threads_id)\n\n for thread in threads:\n thread.join()\n\n # we found new movies from website\n if movies:\n try:\n print(\"Saving {0} movies in movies.json...\".format(len(movies)))\n with open('movies.json', 'w') as f:\n json.dump(movies, f)\n except IOError as e:\n print(\"warning:failed to dump 'movies.json'\")\n\n #import pdb\n #pdb.set_trace()","sub_path":"GetMovies.py","file_name":"GetMovies.py","file_ext":"py","file_size_in_byte":6135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"303341849","text":"#Guessing Game\nfrom random import *\nimport sys\n\nwords = {\n 1: \"peng\",\n 2: \"wagwan\",\n 3: \"pifting\",\n 4: \"benjamin\",\n 5: \"gamer\",\n 6: \"toll\",\n 7: \"tune\",\n 8: \"meal\",\n 9: \"christmas\",\n 10: \"rock\",\n 11: \"custard\",\n}\nsecret_word = words.get(randint(1,11))\nguess = \"\"\nguesses = 0\nguess_guesses = \"\"\nguess_guessses = \"\"\nguess_limit = int(input(\"How many guesses? \"))\nout_of_guesses = False\nif guess_limit == 0:\n print(\"invalid limit\")\n sys.exit()\nelif guess_limit == 1:\n guess_guessses = \"guess\"\nelif guess_limit >= 2:\n guess_guessses = \"guesses\"\nprint(\"\")\nprint(\"You have,\", guess_limit, guess_guessses,\"to guess the word!\")\n\nwhile guess != secret_word:\n guess = input(\"Enter Guess: \")\n guesses += 1\n if guess == \"debug\":\n print(secret_word)\n if guesses == guess_limit and guess != secret_word:\n out_of_guesses = True\n break\n\nif guesses == 1:\n guess_guesses = \"guess\"\nelif guesses >= 2:\n guess_guesses = \"guesses\"\nif out_of_guesses == False:\n print(\"You Guessed the correct word!\", \"It was,\", secret_word)\n print(\"You did it in,\", guesses, guess_guesses)\nelif out_of_guesses == True:\n print(\"You did not guess the word, it was\", \"'\",secret_word,\"'\")\n","sub_path":"Projects/Guessing Game.py","file_name":"Guessing Game.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"258517055","text":"from kzpy3.vis3 import *\nexec(identify_file_str)\n\n\n\n\n\n__started__ = False\ndef get_data_function(P):\n \n global __started__\n\n if not __started__:\n __started__ = True\n Values=loD('Values')\n Runs=loD('Runs')\n Os = {}\n Os_flip = {}\n for r in Runs.keys():\n p = opjD('Data',Runs[r],r,'original_timestamp_data.h5py')\n Os[r] = h5r(p)\n q = opjD('Data',Runs[r],r,'flip_images.h5py')\n Os_flip[r] = h5r(q)\n Keys = {}\n for n in Values.keys():\n Keys[n] = Values[n].keys()\n np.random.shuffle(Keys[n]) \n\n n = np.random.choice([2,3,4,5,6,7,8])\n ky = Keys[n][randint(len(Keys[n]))]\n f0 = ky[0][0]\n f1 = ky[1][0]\n i0 = ky[0][1]\n i1 = ky[1][1]\n if rndchoice([0,1]):\n B = Os\n ik = 'left_image'\n else:\n B = Os_flip\n ik = 'left_image_flip'\n img0 = B[f0][ik]['vals'][i0]\n img1 = B[f1][ik]['vals'][i1]\n d = Values[n][ky]\n input_data = np.concatenate((img0,img1),2).transpose(2,1,0)\n return input_data, None, na([d])\n\n\n\n\n\n\n#EOF\n","sub_path":"Learn/get_data/__older/Runs_Values.py","file_name":"Runs_Values.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"96308756","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport os, sys, cgi\n\nprint('Content-Type: text/json\\r\\n')\n\n# Log HTTP request\nREQUEST_METHOD = os.getenv('REQUEST_METHOD')\n#if REQUEST_METHOD:\ntry:\n sys.stderr.write(REQUEST_METHOD + ' ' + os.environ['SCRIPT_NAME'] + '?' + os.environ['QUERY_STRING'] + '\\n')\n #if REQUEST_METHOD == 'POST':\n # sys.stderr.write(sys.stdin.read() + '\\n')\n form = cgi.FieldStorage()\n for key in form.keys():\n sys.stderr.write(key + '=' + form[key].value + '\\n')\n access_token = form['client_id'].value + '?' + form['client_secret'].value # Trick: Use access_token to pass client_id and client_secret\nexcept:\n import traceback\n sys.stderr.write(traceback.format_exc())\n access_token = 'http://192.168.1.10:8123?password'\n\n# Print content\nprint('{\\\n\"access_token\": \"' + access_token + '\",\\\n\"expires_in\": 3600,\\\n\"token_type\": \"Bearer\",\\\n\"scope\": null,\\\n\"refresh_token\": \"a9f97c43a88c2f2c8270c53d4f1f2d5abc626e62\"\\\n}')\n","sub_path":"hagenie/access.py","file_name":"access.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"296505682","text":"from selenium import webdriver\r\nfrom selenium.webdriver.common.keys import Keys\r\nfrom selenium.webdriver.chrome.options import Options\r\n\r\nchrome_driver_path = \"C:/Users/ADMIN/Documents/KiemThu/chromedriver.exe\"\r\nchrome_options = Options()\r\n\r\nchrome_options.add_argument(\"--window-size=500,500\")\r\n\r\ndriver = webdriver.Chrome(chrome_driver_path, chrome_options=chrome_options)\r\n\r\ndriver.get(\"http://practice.automationtesting.in/\")\r\n# get current url\r\nprint(driver.page_source)\r\n\r\ndriver.quit()","sub_path":"Bai6.py","file_name":"Bai6.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"425201479","text":"#! /usr/bin/env python\n\n'''\nbuild supercells from unit cell for RMG\n'''\n\nimport os\nimport sys\n\ndim = [3, 3, 1]\n\nprefix = sys.argv[-1]\n\nwith open('%s'%(prefix), 'rb') as f:\n all_lines = f.readlines()\n\nrelative = False\nfactor = [1.0]*3\nspecies, x, y, z = [], [], [], []\nfor i in range(len(all_lines)):\n if \"Cell Relative\" in all_lines[i].split('#')[0]:\n relative = True\n\nfor i in range(len(all_lines)):\n if \"a_length\" in all_lines[i]:\n a_length = float(all_lines[i].split('\"')[1])\n if relative:\n factor[0] = a_length\n if \"b_length\" in all_lines[i]:\n b_length = float(all_lines[i].split('\"')[1])\n if relative:\n factor[1] = b_length\n if \"c_length\" in all_lines[i]:\n c_length = float(all_lines[i].split('\"')[1])\n if relative:\n factor[2] = c_length\n if \"atoms =\" in all_lines[i]:\n for j in range(i+2,len(all_lines)-1):\n species.append(str(all_lines[j].split()[0]))\n x.append(factor[0]*float(all_lines[j].split()[1]))\n y.append(factor[1]*float(all_lines[j].split()[2]))\n z.append(factor[2]*float(all_lines[j].split()[3]))\n\n\nlines_super = \"\"\nfor line in all_lines:\n if \"a_length\" in line:\n line = 'a_length=\"%.12f\"\\n'%(dim[0]*a_length)\n if \"b_length\" in line:\n line = 'b_length=\"%.12f\"\\n'%(dim[1]*b_length)\n if \"c_length\" in line:\n line = 'c_length=\"%.12f\"\\n'%(dim[2]*c_length)\n lines_super += line\n if 'atoms' in line.split('#')[0]:\n break\n\nif '\"' not in lines_super[-1]:\n lines_super += '\"\\n'\n\n\nfor i in range(dim[0]):\n for j in range(dim[1]):\n for k in range(dim[2]):\n for n in range(len(x)):\n atom_tmp = (species[n],\n i*a_length+x[n],\n j*b_length+y[n],\n k*c_length+z[n])\n lines_super += '%s%18.12f%18.12f%18.12f\\n'%(atom_tmp)\nlines_super += '\"'\n\nwith open(\"%s.super\"% prefix, 'wb') as f:\n f.write(lines_super)\n","sub_path":"personal/tools/unit2super.py","file_name":"unit2super.py","file_ext":"py","file_size_in_byte":2038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"275317402","text":"#!/usr/bin/env python3\n\nimport sys\nimport os\nimport difflib\nimport re\nimport shutil\nfrom jinja2 import Environment, PackageLoader\nimport subprocess\nfrom builtins import FileNotFoundError, NotADirectoryError\nimport concurrent.futures\nfrom bs4 import BeautifulSoup\n\nNUM_PROC = 7\n\n\nclass ERRaceClassifier(object):\n\n CLASSIFICATION = {\n 'rs': 'HIGH',\n 'ru': 'NORMAL',\n 'rk': 'LOW'\n }\n\n RACE_PARENT_RE = re.compile('(.*race[0-9]+)_race[0-9]+')\n\n def __init__(self, website_dir):\n\n self.website_dir = website_dir\n self._cache = {}\n\n def inject_classification(self, race_data, namespace):\n\n handle = race_data['handle']\n\n if 'race' not in handle:\n race_data['er_classification'] = 'PARSE_ERROR'\n race_data['er_classification_details'] = ''\n return\n \n id = handle[handle.rindex('race')+4:]\n\n parent = race_data['origin']\n\n if parent is None:\n\n match = self.RACE_PARENT_RE.match(handle)\n if match is None:\n parent = 'base'\n else:\n parent = match.group(1)\n\n if not parent in self._cache:\n\n varlist_path = os.path.join(self.website_dir, parent, 'varlist')\n\n if not os.path.exists(varlist_path):\n\n try:\n cmd = '$WEBERA_DIR/R4/er-classify.sh %s %s' % \\\n (os.path.join(self.website_dir, parent), namespace)\n stdout = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)\n except subprocess.CalledProcessError as e:\n print('Failed running %s' % cmd)\n\n try:\n with open(varlist_path, 'r') as fp:\n self._cache[parent] = BeautifulSoup(fp, 'html5lib')\n except FileNotFoundError:\n self._cache[parent] = None\n\n soup = self._cache.get(parent, None)\n\n if soup is not None:\n\n try:\n race_row = soup\\\n .find('a', href='race?id=%s' % id)\\\n .find_parent('tr')\\\n .previous_sibling.previous_sibling\n\n classification = self.CLASSIFICATION[race_row['class'][0][:2]]\n details = race_row.find_all('td')[-1].text\n details = details.strip()\n\n race_data['er_classification'] = classification\n race_data['er_classification_details'] = details\n except: #Exception as e:\n #raise e\n race_data['er_classification'] = 'PARSE_ERROR'\n race_data['er_classification_details'] = ''\n else:\n race_data['er_classification'] = 'UNKNOWN'\n race_data['er_classification_details'] = ''\n\n# Please look away, and allow me to be a bit quick-and-dirty for a moment\n\nmemlist_cache = {}\n\ndef get_memory_stats(race_dir, key):\n\n if race_dir not in memlist_cache:\n\n memlist_file = os.path.join(race_dir, 'memlist')\n if not os.path.exists(memlist_file) or os.stat(memlist_file).st_size == 0:\n print('Warning,', memlist_file, 'is missing')\n memlist_cache[race_dir] = {}\n\n else:\n\n RE_memory_location = re.compile('(Variable|Attribute)([a-zA-Z\\.0-9\\[\\]\\(\\)\\-_:/\\$]*) ')\n RE_value = re.compile('Uncovered races: \\([a-z ]+\\) ([0-9]+)(.*?)Covered races: ([0-9]+)(.*?) ')\n\n result = {}\n\n with open(memlist_file, 'rb') as fp:\n\n last_location = None\n\n for line in fp.readlines():\n line = line.decode('utf8', 'ignore')\n\n if last_location is None:\n match = RE_memory_location.search(line)\n if match is not None:\n last_location = match.group(2)\n\n else:\n match = RE_value.search(line)\n if match is not None:\n result[last_location] = {\n 'num_uncovered': int(match.group(1)),\n 'num_covered': int(match.group(3)),\n 'uncovered': match.group(2),\n 'covered': match.group(4)\n }\n else:\n print('Warning, could not find information for location', last_location)\n\n last_location = None\n\n memlist_cache[race_dir] = result\n\n return memlist_cache[race_dir].get(key, None)\n\nRE_value_with_memory = re.compile('\\[.*\\]|event action [0-9]+|IO_[0-9]+|:0x[abcdef\\-0-9]+|:[0-9]+|0x[abcdef0-9]+|x_x[0-9]+')\n\ndef anon(value, known_ids=[]):\n return RE_value_with_memory.sub('[??]', str(value)) if value not in known_ids else 'ID'\n\ndef abstract_memory_equal(handle, m1, m2):\n\n # start: Some fixes to the approximation\n\n # (b) id numbers (such as timer ids) can be stored as values, and naturally differ from execution to execution\n\n def get_known_ids(mem):\n ids = []\n for k,v in mem.items():\n if 'Timer:' in k:\n ids.append(k.split(':')[1])\n\n return ids\n\n known_ids = get_known_ids(m1)\n known_ids.extend(get_known_ids(m2))\n\n # Memory adresses are not equal in the two memory \"diffs\". We approximate their equality by stripping out\n # memory locations, and converting them into anon_memory_location=value strings.\n # We then check set equality\n\n memory1 = ['%s=%s' % (anon(location), anon(value, known_ids)) for location, value in m1.items()]\n\n # start: Some fixes to the approximation\n\n # (a) in some cases we observe registered event actions (which we execute) in the reordered sequence\n # but not in the original sequence. This is purely an anomaly in our instrumentation.\n\n ignore_memory2_keys = []\n for k,v in m2.items():\n if 'event action' in k and '-1' not in k and '%s=%s' % (anon(k), anon(v, known_ids)) not in memory1:\n ignore_memory2_keys.append(k)\n\n # end: fixes\n\n memory2 = ['%s=%s' % (anon(location), anon(value, known_ids)) for location, value in m2.items() if k not in ignore_memory2_keys]\n\n #if not set(memory1) == set(memory2):\n #print('\\n\\nMISS', \"\\n\", handle, \"\\n\", memory1, \"\\n\\n\", memory2, \"\\n\\n\", set(memory1) == set(memory2), \"\\n\\n\",\n # [v for v in memory1 if v not in memory2], \"\\n\\n\",\n # [k for k,v in m1.items() if '%s=%s' % (anon(k), anon(v, known_ids)) not in memory2], \"\\n\\n\",\n # [v for v in memory2 if v not in memory1], \"\\n\\n\",\n #[k for k,v in m2.items() if k not in ignore_memory2_keys and '%s=%s' % (anon(k), anon(v, known_ids)) not in memory1], \"\\n\\n\")\n\n\n print(memory1, \"\\n\\n\", memory2, \"\\n\\n\", set(memory1) == set(memory2), \"\\n\\n\", [v for v in memory1 if v not in memory2], \"\\n\\n\", [k for k,v in m1.items() if '%s=%s' % (anon(k), anon(v, known_ids)) not in memory2], \"\\n\\n\", [v for v in memory2 if v not in memory1], \"\\n\\n\", [k for k,v in m2.items() if k not in ignore_memory2_keys and '%s=%s' % (anon(k), anon(v, known_ids)) not in memory1])\n\n return (set(memory1) == set(memory2),\n [v for v in memory1 if v not in memory2],\n [v for v in memory2 if v not in memory1],\n [k for k,v in m1.items() if '%s=%s' % (anon(k), anon(v, known_ids)) not in memory2],\n [k for k,v in m2.items() if k not in ignore_memory2_keys and '%s=%s' % (anon(k), anon(v, known_ids)) not in memory1])\n\ndef create_if_missing_event_action_code(base_dir, namespace, *args):\n\n to_be_added = []\n\n for event_action_id in args:\n\n code_file = os.path.join(base_dir, 'varlist-%s.code' % event_action_id)\n if not os.path.exists(code_file) or os.stat(code_file).st_size == 0:\n to_be_added.append(event_action_id)\n\n if len(to_be_added) > 0:\n try:\n cmd = '$WEBERA_DIR/R4/er-code-file.sh %s %s %s' % (base_dir, namespace, ' '.join(to_be_added))\n stdout = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)\n except subprocess.CalledProcessError as e:\n print('Failed running %s' % cmd)\n\n\ndef get_or_create_event_action_memory(base_dir, memory, event_action_id):\n\n RE_operation = re.compile('(read|write|value|start) <.*>(.*)')\n\n code_file = os.path.join(base_dir, 'varlist-%s.code' % event_action_id)\n line_num = 0\n with open(code_file, 'rb') as fp:\n\n last_location = None\n known_ids = []\n\n for line in fp:\n line_num += 1\n line = line.decode('utf8', 'ignore')\n\n match = RE_operation.search(line)\n\n if match is None:\n continue\n\n operation = match.group(1)\n location_or_value = match.group(2)\n\n if operation == 'write':\n\n if 'CachedResource' in location_or_value:\n # Cached resources never have a value\n memory[location_or_value] = \"?\"\n\n elif 'Timer:' in location_or_value:\n known_ids.append(location_or_value.split(':')[1])\n memory['TIMER'] = memory.get('TIMER', 0) + 1\n\n else:\n last_location = location_or_value\n\n elif operation == 'value' and last_location is not None:\n if location_or_value in known_ids:\n location_or_value = '??'\n\n memory[last_location] = location_or_value\n last_location = None\n\n elif operation == 'start' and 'event action -1' not in location_or_value:\n # Approximation, is it always safe to filter out event action -1?\n # TODO: Figure out why these are added non-deterministically in some cases\n memory[location_or_value] = memory.get(location_or_value, 0) + 1\n last_location = None\n\n elif operation == 'read':\n last_location = None\n\n if line_num == 0:\n print('Warning,', code_file, 'is empty!')\n\n return memory\n\ndef get_abstract_memory(base_dir, namespace, event_handler1, event_handler2):\n\n if not event_handler1 or not event_handler2:\n return {}\n\n race_first_id, race_first_descriptor = event_handler1\n race_second_id, race_second_descriptor = event_handler2\n\n create_if_missing_event_action_code(base_dir, namespace, race_first_id, race_second_id)\n\n memory = get_or_create_event_action_memory(base_dir, {}, race_first_id)\n memory = get_or_create_event_action_memory(base_dir, memory, race_second_id)\n\n return memory\n\n\nclass RaceParseException(Exception):\n pass\n\n\nclass HashableDict(dict):\n\n def __init__(self, *args, **kwargs):\n self.ignore_properties = kwargs.pop('_ignore_properties', None)\n\n if self.ignore_properties is None:\n self.ignore_properties = []\n\n super(HashableDict, self).__init__(*args, **kwargs)\n\n def __cmp__(self, other):\n t = self.__hash__()\n o = other.__hash__()\n\n if t == o:\n return 0\n elif t < o:\n return -1\n else:\n return 1\n\n def __eq__(self, other):\n return self.__hash__() == other.__hash__()\n\n def __hash__(self):\n return hash(tuple(sorted([item for item in self.items() if item[0] not in self.ignore_properties])))\n\n\ndef parse_race(base_dir, handle):\n \"\"\"\n Outputs data\n \"\"\"\n\n handle_dir = os.path.join(base_dir, handle)\n\n # ERRORS\n\n errors_file = os.path.join(handle_dir, 'out.errors.log')\n if not os.path.exists(errors_file):\n errors_file = os.path.join(handle_dir, 'errors.log')\n\n errors = []\n exceptions = []\n new_events = []\n\n num_new_events = 0\n num_skipped_events = 0\n\n try:\n fp = open(errors_file, 'rb')\n except (FileNotFoundError, NotADirectoryError):\n raise RaceParseException()\n\n with fp:\n while True:\n header = fp.readline().decode('utf8', 'ignore')\n\n if header == '':\n break # EOF reached\n\n event_action_id, module, description, length = header.split(';')\n length = int(length)\n\n if length == 0:\n details = ''\n else:\n details = fp.read(length).decode('utf8', 'ignore')\n\n container = errors\n t = 'error'\n\n if 'JavaScript_Interpreter' in module:\n if 'An exception occured' in description and \\\n any([buildin_exception_indicator in details for buildin_exception_indicator in [\n 'EvalError', 'RangeError', 'ReferenceError', 'SyntaxError', 'TypeError', 'URIError'\n ]]):\n\n container = exceptions\n t = 'exception'\n\n elif 'console.log' in module:\n if 'ERROR' in description and \\\n any([buildin_exception_indicator in details for buildin_exception_indicator in [\n 'EvalError', 'RangeError', 'ReferenceError', 'SyntaxError', 'TypeError', 'URIError'\n ]]):\n\n container = exceptions\n t = 'exception'\n else:\n continue\n\n if 'Non-executed event action' in description:\n new_events.append(details)\n num_new_events += 1\n\n if 'JavaScript_Interpreter' in module and 'Event action skipped after timeout.' in description:\n num_skipped_events += 1\n\n if 'JavaScript_Interpreter' in module and 'Event action executed from pending schedule.' in description:\n num_skipped_events -= 1\n\n container.append(HashableDict(\n event_action_id=event_action_id,\n type=t,\n module=module,\n description=description,\n details=details,\n _ignore_properties=['event_action_id', 'type']\n ))\n\n # STDOUT\n\n stdout_file = os.path.join(handle_dir, 'stdout')\n if not os.path.exists(stdout_file):\n stdout_file = os.path.join(handle_dir, 'stdout.txt')\n\n with open(stdout_file, 'rb') as fp:\n stdout = fp.read().decode('utf8', 'ignore')\n\n result_match = re.compile('Result: ([A-Z]+)').search(stdout)\n state_match = re.compile('HTML-hash: ([0-9]+)').search(stdout)\n\n if result_match is None:\n print('Warning, result not found in file:', stdout_file)\n\n if state_match is None:\n print('Warning, state not found in file:', stdout_file)\n\n # Origin\n\n origin = None\n origin_file = os.path.join(handle_dir, 'origin')\n\n if os.path.exists(origin_file):\n with open(origin_file, 'rb') as fp:\n origin = str(fp.read().decode('utf8', 'ignore')).strip()\n\n # SCHEDULE\n\n schedule_file = os.path.join(handle_dir, 'new_schedule.data')\n if not os.path.isfile(schedule_file):\n schedule_file = os.path.join(handle_dir, 'new_wave_schedule.data')\n\n output_schedule_file = os.path.join(handle_dir, 'out.schedule.data')\n if not os.path.isfile(output_schedule_file):\n output_schedule_file = os.path.join(handle_dir, 'schedule.data')\n\n schedule = []\n raceFirst = \"\"\n raceFirstIndex = -1\n raceSecond = \"\"\n raceSecondIndex = -1\n\n with open(schedule_file, 'rb') as fp:\n\n index = 0\n for line in fp.readlines():\n line = line.decode('utf8', 'ignore')\n\n if line == '':\n continue\n\n if '' in line or '' in line:\n event_action_id = -1\n event_action_descriptor = line\n\n # This is a hack,\n # If se see , then the next line should be saved as the first racing event\n # and if we see , then the next line should be saved as the second racing event.\n\n if '' in line:\n raceFirst = None\n\n if '' in line:\n raceSecond = None\n\n else:\n event_action_id, event_action_descriptor = line.split(';', 1)\n\n # If any race is marked as None, then we should update it now\n\n if raceFirst is None:\n raceFirst = (event_action_id, event_action_descriptor)\n raceFirstIndex = index\n\n if raceSecond is None:\n raceSecond = (event_action_id, event_action_descriptor)\n raceSecondIndex = index\n\n index += 1\n\n output_race_first = None\n output_race_second = None\n\n with open(output_schedule_file, 'rb') as fp:\n\n lines = fp.readlines()\n\n try:\n # subtract 1 for the missing marker\n output_race_first = lines[raceFirstIndex-1].decode('utf8', 'ignore').split(';', 1)\n\n # subtract 2 for and markers\n output_race_second = lines[raceSecondIndex-2].decode('utf8', 'ignore').split(';', 1)\n\n except IndexError:\n output_race_first = None\n output_race_second = None\n\n index = 0\n for line in lines:\n line = line.decode('utf8', 'ignore')\n\n if line == '':\n continue\n\n if index == raceFirstIndex:\n\n schedule.append(HashableDict(\n event_action_id=-1,\n type='schedule',\n event_action_descriptor=\"\",\n _ignore_properties=['event_action_id', 'type']\n ))\n\n if index == raceSecondIndex:\n\n schedule.append(HashableDict(\n event_action_id=-1,\n type='schedule',\n event_action_descriptor=\"\",\n _ignore_properties=['event_action_id', 'type']\n ))\n\n event_action_id, event_action_descriptor = line.split(';', 1)\n\n schedule.append(HashableDict(\n event_action_id=event_action_id,\n type='schedule',\n event_action_descriptor=event_action_descriptor,\n _ignore_properties=['event_action_id', 'type']\n ))\n\n index += 1\n\n # ZIP ERRORS AND SCHEDULE\n\n zip_errors_schedule = []\n current_event_action_id = None\n\n buckets = {}\n\n for s in schedule:\n if s['event_action_id'] == -1:\n continue\n\n bucket = buckets.get(s['event_action_id'], [])\n bucket.append(s)\n buckets[s['event_action_id']] = bucket\n\n for s in errors:\n bucket = buckets.get(s['event_action_id'], [])\n bucket.append(s)\n buckets[s['event_action_id']] = bucket\n\n for s in exceptions:\n bucket = buckets.get(s['event_action_id'], [])\n bucket.append(s)\n buckets[s['event_action_id']] = bucket\n\n for s in schedule:\n if s['event_action_id'] == -1:\n zip_errors_schedule.append(s)\n continue\n\n try:\n zip_errors_schedule.extend(buckets[s['event_action_id']])\n del buckets[s['event_action_id']]\n except:\n print(\"Error applying event action\", s['event_action_id'], \"to zipped schedule\")\n\n for bucket in buckets:\n zip_errors_schedule.extend(buckets[bucket])\n\n return {\n 'handle': handle,\n 'errors': errors,\n 'exceptions': exceptions,\n 'schedule': schedule,\n 'zip_errors_schedule': zip_errors_schedule,\n 'result': result_match.group(1) if result_match is not None else 'ERROR',\n 'html_state': state_match.group(1) if state_match is not None else 'ERROR',\n 'race_dir': handle_dir,\n 'origin': origin,\n 'raceFirst': raceFirst,\n 'raceSecond': raceSecond,\n 'output_race_first': output_race_first,\n 'output_race_second': output_race_second,\n 'new_events': new_events,\n 'num_new_events': num_new_events,\n 'num_skipped_events': num_skipped_events\n }\n\n\ndef parse_er_log(base_dir):\n\n result = {\n 'races_total': -1,\n 'races_success': -1,\n 'races_failure': -1,\n 'execution_time': 0,\n 'stdout': ''\n }\n\n try:\n fp = open(os.path.join(base_dir, 'runner', 'stdout.txt'), 'rb')\n except (FileNotFoundError, NotADirectoryError):\n return result\n\n with fp:\n stdout = fp.read().decode('utf8', 'ignore')\n result['stdout'] = stdout\n\n if 'WARNING: Stopped iteration' in stdout:\n print('Warning, iteration max reached.')\n\n result_match = re.compile('Tried ([0-9]+) schedules. ([0-9]+) generated, ([0-9]+)').search(stdout)\n\n if result_match is not None:\n result['races_total'] = int(result_match.group(2))\n result['races_success'] = int(result_match.group(3))\n result['races_failure'] = int(result_match.group(2)) - int(result_match.group(3))\n else:\n print('FAIL')\n print(stdout)\n\n time_match = re.compile('real ([0-9]+)\\.[0-9]+').search(stdout)\n\n if time_match is not None:\n result['execution_time'] = int(time_match.group(1))\n\n return result\n\n\ndef generate_comparison_file(record_file, replay_file, comparison_file):\n try:\n cmd = 'compare -metric RMSE %s %s %s' % (record_file, replay_file, comparison_file)\n print(cmd)\n stdout = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)\n type = 'normal'\n except subprocess.CalledProcessError as e:\n if e.returncode == 2:\n return 'error', -1\n\n stdout = e.output\n type = 'normal'\n\n if b'image widths or heights differ' in stdout:\n # do a subimage search\n\n try:\n cmd = 'compare -metric RMSE -subimage-search %s %s %s' % (record_file, replay_file, comparison_file)\n print(cmd)\n stdout = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)\n type = 'subimage'\n except subprocess.CalledProcessError as e:\n if e.returncode == 2:\n return 'error', -1\n\n stdout = e.output\n type = 'subimage'\n\n match = re.compile(b'([0-9]+\\.?[0-9]*) \\([0-9]+\\.?[0-9]*\\)').search(stdout)\n\n if match is None:\n return 'error', -1\n\n return type, float(match.group(1))\n\n\ndef cimage_human(type, distance):\n if type == 'normal' and distance == 0:\n return 'EXACT'\n elif type == 'normal' and distance != 0:\n return 'DIFFER'\n elif type == 'subimage':\n return 'SUBSET'\n else:\n return 'ERROR'\n\n\ndef compare_race(base_data, race_data, namespace):\n \"\"\"\n Outputs comparison\n \"\"\"\n\n # Compare image\n\n cimage_meta = os.path.join(race_data['race_dir'], 'comparison.txt')\n\n if not os.path.isfile(cimage_meta):\n\n file1 = os.path.join(base_data['race_dir'], 'out.screenshot.png')\n if not os.path.exists(file1):\n file1 = os.path.join(base_data['race_dir'], 'screenshot.png')\n\n file2 = os.path.join(race_data['race_dir'], 'out.screenshot.png')\n if not os.path.exists(file2):\n file2 = os.path.join(race_data['race_dir'], 'screenshot.png')\n\n match_type, distance = generate_comparison_file(\n file1,\n file2,\n os.path.join(race_data['race_dir'], 'comparison.png'))\n\n cimage = {\n 'distance': float(distance),\n 'match_type': match_type,\n 'human': cimage_human(match_type, distance)\n }\n\n with open(cimage_meta, 'w') as fp:\n fp.writelines([\n str(cimage['distance']),\n cimage['match_type']\n ])\n\n else:\n\n with open(cimage_meta, 'r') as fp:\n line = fp.readline()\n match = re.compile('^(\\-?[0-9]+\\.?[0-9]*)([a-z]+)$').search(line)\n\n cimage = {\n 'distance': float(match.group(1)),\n 'match_type': match.group(2),\n 'human': cimage_human(match.group(2), float(match.group(1)))\n }\n\n def remove_new_event_action(base_list, race_list):\n # Remove \"new event action\" error at the end of error reports if they both have it\n # Often, this is not an error, just a side effect of the system, and this side effect\n # is different from execution to execution. Filter it away\n if len(base_list) > 0 and len(race_list) > 0:\n\n if base_list[-1]['type'] == 'error' and race_list[-1]['type'] == 'error' and \\\n 'event action observed' in base_list[-1]['description'] and \\\n 'event action observed' in race_list[-1]['description']:\n\n return base_list[:-1], race_list[:-1]\n\n return base_list, race_list\n\n # Errors diff\n\n base_errors = base_data['errors']\n race_errors = race_data['errors']\n\n base_errors, race_errors = remove_new_event_action(base_errors, race_errors)\n\n diff = difflib.SequenceMatcher(None, base_errors, race_errors)\n opcodes = diff.get_opcodes()\n opcodes_human = []\n\n for opcode in opcodes:\n tag, i1, i2, j1, j2 = opcode\n\n opcodes_human.append({\n 'base': base_errors[i1:i2],\n 'tag': tag,\n 'race': race_errors[j1:j2]\n })\n\n errors_distance = sum(1 for opcode in opcodes if opcode[0] != 'equal')\n\n # Exceptions diff\n\n base_exceptions = base_data['exceptions']\n race_exceptions = race_data['exceptions']\n\n exceptions_diff = difflib.SequenceMatcher(None, base_exceptions, race_exceptions)\n exceptions_opcodes = exceptions_diff.get_opcodes()\n exceptions_opcodes_human = []\n\n for opcode in exceptions_opcodes:\n tag, i1, i2, j1, j2 = opcode\n\n exceptions_opcodes_human.append({\n 'base': base_exceptions[i1:i2],\n 'tag': tag,\n 'race': race_exceptions[j1:j2]\n })\n\n exceptions_distance = sum(1 for opcode in exceptions_opcodes if opcode[0] != 'equal')\n\n exceptions_set_comparison = \\\n set(['%s%s' % (base_exception['description'], base_exception['details']) for base_exception in base_exceptions]) == \\\n set(['%s%s' % (base_exception['description'], base_exception['details']) for base_exception in race_exceptions])\n\n # Race and Errors Diff\n\n base_zip = base_data['zip_errors_schedule']\n race_zip = race_data['zip_errors_schedule']\n\n base_zip, race_zip = remove_new_event_action(base_zip, race_zip)\n\n zip_diff = difflib.SequenceMatcher(None, base_zip, race_zip)\n zip_opcodes = zip_diff.get_opcodes()\n zip_opcodes_human = []\n\n unequal_seen = False\n\n for zip_opcode in zip_opcodes:\n tag, i1, i2, j1, j2 = zip_opcode\n\n if not unequal_seen and tag != 'equal':\n unequal_seen = True\n first_unequal = True\n else:\n first_unequal = False\n\n zip_opcodes_human.append({\n 'base': base_zip[i1:i2],\n 'tag': tag,\n 'race': race_zip[j1:j2],\n 'first_unequal': first_unequal\n })\n\n # R4 race classification\n\n html_state_match = base_data['html_state'] == race_data['html_state']\n visual_state_match = cimage.get('human', 'FAIL') == 'EXACT'\n\n classification = 'NORMAL'\n classification_details = \"\"\n\n # Low triggers\n\n # High triggers (classifiers)\n\n if not exceptions_set_comparison:\n classification = 'HIGH'\n classification_details += 'R4_EXCEPTIONS '\n\n if not visual_state_match and not html_state_match:\n classification = 'HIGH'\n classification_details += 'R4_DOM_AND_RENDER_MISMATCH '\n\n if 'initialization race' in race_data['er_classification_details']:\n classification = 'HIGH'\n classification_details += 'ER_INITIALIZATION_RACE '\n\n if 'readyStateChange race' in race_data['er_classification_details']:\n classification = 'HIGH'\n classification_details += 'ER_READYSTATECHANGE_RACE '\n\n # Low Triggers (strong update)\n\n if 'LATE_EVENT_ATTACH' in race_data['er_classification_details']:\n classification = 'LOW'\n classification_details += 'ER_LATE_EVENT_ATTACH '\n\n if 'COOKIE_OR_CLASSNAME' in race_data['er_classification_details']:\n classification = 'LOW'\n classification_details += 'ER_COOKIE_OR_CLASSNAME '\n\n if 'MAYBE_LAZY_INIT' in race_data['er_classification_details']:\n classification = 'LOW'\n classification_details += 'ER_MAYBE_LAZY_INIT '\n\n if 'ONLY_LOCAL_WRITE' in race_data['er_classification_details']:\n classification = 'LOW'\n classification_details += 'ER_ONLY_LOCAL_WRITE '\n\n if 'NO_EVENT_ATTACHED' in race_data['er_classification_details']:\n classification = 'LOW'\n classification_details += 'ER_NO_EVENT_ATTACHED '\n\n if 'WRITE_SAME_VALUE' in race_data['er_classification_details']:\n classification = 'LOW'\n classification_details += 'ER_WRITE_SAME_VALUE '\n\n if classification != 'LOW' and race_data['er_classification'] == 'LOW':\n print('Error: Unknown classification', race_data['er_classification_details'])\n\n schedule_distance = race_data['num_new_events'] + race_data['num_skipped_events']\n\n return {\n 'schedule_distance': schedule_distance,\n 'exceptions_diff': exceptions_opcodes,\n 'exceptions_diff_human': exceptions_opcodes_human,\n 'exceptions_diff_distance': exceptions_distance,\n 'errors_diff': opcodes,\n 'errors_diff_human': opcodes_human,\n 'errors_diff_distance': errors_distance,\n 'zip_diff': zip_opcodes,\n 'zip_diff_human': zip_opcodes_human,\n 'zip_diff_has_unequal': unequal_seen,\n 'html_state_match': html_state_match,\n 'visual_state_match': cimage,\n 'is_equal': base_data['html_state'] == race_data['html_state'] and schedule_distance == 0 and exceptions_distance == 0,\n 'r4_classification': classification,\n 'r4_classification_details': classification_details\n }\n\n\ndef output_race_report(website, race, jinja, output_dir, input_dir):\n \"\"\"\n Outputs filename of written report\n \"\"\"\n\n record_file = os.path.join(output_dir, 'record.png')\n replay_file = os.path.join(output_dir, '%s-replay.png' % race['handle'])\n comparison_file = os.path.join(output_dir, '%s-comparison.png' % race['handle'])\n\n try:\n if not os.path.isfile(record_file):\n path = os.path.join(input_dir, website, 'base', 'out.screenshot.png')\n if not os.path.exists(path):\n path = os.path.join(input_dir, website, 'base', 'screenshot.png')\n\n shutil.copy(path, record_file)\n\n except FileNotFoundError:\n pass\n\n try:\n path = os.path.join(input_dir, website, race['handle'], 'out.screenshot.png')\n if not os.path.exists(path):\n path = os.path.join(input_dir, website, race['handle'], 'screenshot.png')\n shutil.copy(path, replay_file)\n except FileNotFoundError:\n pass\n\n try:\n shutil.copy(os.path.join(input_dir, website, race['handle'], 'comparison.png'), comparison_file)\n except FileNotFoundError:\n try:\n shutil.copy(os.path.join(input_dir, website, race['handle'], 'comparison-0.png'), comparison_file)\n except FileNotFoundError:\n pass\n\n with open(os.path.join(output_dir, '%s.html' % race['handle']), 'w') as fp:\n\n fp.write(jinja.get_template('race.html').render(\n website=website,\n race=race\n ))\n\n\ndef output_race_index(website, parsed_races, er_log, jinja, output_dir, input_dir):\n\n try:\n os.mkdir(output_dir)\n except OSError:\n pass # folder exists\n\n for race in parsed_races:\n output_race_report(website, race, jinja, output_dir, input_dir)\n\n with open(os.path.join(output_dir, 'index.html'), 'w') as fp:\n\n fp.write(jinja.get_template('race_index.html').render(\n website=website,\n parsed_races=parsed_races,\n er_log=er_log\n ))\n\ndef output_website_index(website_index, output_dir, input_dir):\n\n jinja = Environment(loader=PackageLoader('templates', ''))\n\n try:\n os.mkdir(output_dir)\n except OSError:\n pass # folder exists\n\n summary = {\n 'race_result': {\n 'equal': 0,\n 'diff': 0,\n 'timeout': 0,\n 'error': 0\n },\n 'execution_result': {\n 'total': 0,\n 'success': 0,\n 'failure': 0\n },\n 'er_classification_result': {\n 'high': 0,\n 'normal': 0,\n 'low': 0,\n 'unknown': 0\n },\n 'r4_classification_result': {\n 'high': 0,\n 'normal': 0,\n 'low': 0\n },\n 'execution_time': 0,\n }\n\n items = []\n\n for item in website_index:\n\n if item is None:\n continue\n\n summary['race_result']['equal'] += item['summary']['equal']\n summary['race_result']['diff'] += item['summary']['diff']\n summary['race_result']['timeout'] += item['summary']['timeout']\n summary['race_result']['error'] += item['summary']['error']\n\n summary['execution_result']['total'] += item['er_log']['races_total']\n summary['execution_result']['success'] += item['er_log']['races_success']\n summary['execution_result']['failure'] += item['er_log']['races_failure']\n\n summary['execution_time'] += item['er_log']['execution_time']\n\n summary['er_classification_result']['high'] += item['summary']['er_high']\n summary['er_classification_result']['normal'] += item['summary']['er_normal']\n summary['er_classification_result']['low'] += item['summary']['er_low']\n summary['er_classification_result']['unknown'] += item['summary']['er_unknown']\n summary['r4_classification_result']['high'] += item['summary']['r4_high']\n summary['r4_classification_result']['normal'] += item['summary']['r4_normal']\n summary['r4_classification_result']['low'] += item['summary']['r4_low']\n\n items.append(item)\n\n with open(os.path.join(output_dir, 'index.html'), 'w') as fp:\n\n fp.write(jinja.get_template('index.html').render(\n website_index=items,\n summary=summary\n ))\n\ndef process_race(website_dir, race_data, base_data, er_race_classifier, namespace):\n\n er_race_classifier.inject_classification(race_data, namespace)\n\n comparison = compare_race(base_data, race_data, namespace)\n\n return {\n 'handle': race_data['handle'],\n 'base_data': base_data,\n 'race_data': race_data,\n 'comparison': comparison\n }\n\n\ndef process(job):\n\n website, analysis_dir, output_dir, namespace = job\n\n print (\"PROCESSING\", website)\n\n website_dir = os.path.join(analysis_dir, website)\n parsed_races = []\n\n ## Get a list of races ##\n\n races = os.listdir(website_dir)\n\n try:\n races.remove('base')\n races.remove('record')\n except ValueError:\n print('Error, missing base or record directory in output dir for %s' % website)\n return None\n\n ignore_files = ['runner', 'record.png', 'arcs.log', 'out.schedule.data', 'new_schedule.data', 'stdout.txt', 'out.ER_actionlog', 'out.log.network.data', 'out.log.time.data', 'out.log.random.data', 'out.status.data']\n\n races = [race for race in races if not race.startswith('_') and not race in ignore_files]\n\n ## Parse each race ##\n\n er_race_classifier = ERRaceClassifier(website_dir)\n er_log = parse_er_log(website_dir)\n\n for race in races:\n\n try:\n race_data = parse_race(website_dir, race)\n except RaceParseException:\n print(\"Error parsing %s :: %s\" % (website, race))\n\n try:\n base_data = parse_race(website_dir, race_data['origin'])\n except RaceParseException:\n print(\"Error parsing %s :: %s (base)\" % website)\n break\n\n parsed_races.append(process_race(website_dir, race_data, base_data, er_race_classifier, namespace))\n\n classifiers = ['R4_EXCEPTIONS', 'R4_DOM_AND_RENDER_MISMATCH', 'ER_INITIALIZATION_RACE', 'ER_READYSTATECHANGE_RACE']\n\n er_tags = ['ER_LATE_EVENT_ATTACH', 'ER_COOKIE_OR_CLASSNAME', 'ER_MAYBE_LAZY_INIT', 'ER_ONLY_LOCAL_WRITE',\n 'ER_NO_EVENT_ATTACHED', 'ER_WRITE_SAME_VALUE']\n\n\n\n r4_tags = ['R4_AD_HOC_SYNC_PENDING_EVENTS',\n 'R4_DOM_TIMER_AD_HOC_SYNC[EARLY]', 'R4_DOM_TIMER_AD_HOC_SYNC[DELAY]', 'R4_EVENTS_COMMUTE',\n 'R4_SPAWN_TIMER_AD_HOC[DELAY]', 'R4_SPAWN_TIMER_AD_HOC[EARLY]', 'R4_CONTINUATION_AD_HOC']\n\n r4_classifiers = ['R4_EXCEPTIONS', 'R4_DOM_AND_RENDER_MISMATCH']\n er_classifiers = ['ER_INITIALIZATION_RACE', 'ER_READYSTATECHANGE_RACE']\n\n tags = ['ER_LATE_EVENT_ATTACH', 'ER_COOKIE_OR_CLASSNAME', 'ER_MAYBE_LAZY_INIT', 'ER_ONLY_LOCAL_WRITE',\n 'ER_NO_EVENT_ATTACHED', 'ER_WRITE_SAME_VALUE', 'R4_AD_HOC_SYNC_PENDING_EVENTS',\n 'R4_DOM_TIMER_AD_HOC_SYNC[EARLY]', 'R4_DOM_TIMER_AD_HOC_SYNC[DELAY]', 'R4_EVENTS_COMMUTE',\n 'R4_SPAWN_TIMER_AD_HOC[DELAY]', 'R4_SPAWN_TIMER_AD_HOC[EARLY]', 'R4_CONTINUATION_AD_HOC']\n\n data = [website,\n str(len(parsed_races)),\n str(len([1 for race in parsed_races if race['comparison']['r4_classification'] == 'LOW'])),\n str(len([1 for race in parsed_races if race['comparison']['r4_classification'] == 'NORMAL'])),\n str(len([1 for race in parsed_races if race['comparison']['r4_classification'] == 'HIGH']))]\n\n def filter_classifiers(details):\n return [c for c in details.split(' ') if c not in classifiers]\n\n def only_classifiers(details):\n return [c for c in details.split(' ') if c in classifiers]\n\n\n #for tag in tags:\n # if tag in classifiers:\n # data.append(str(len([1 for race in parsed_races if tag in only_classifiers(race['comparison']['r4_classification_details']) and len(only_classifiers(race['comparison']['r4_classification_details'])) == 1])))\n # else:\n # data.append(str(len([1 for race in parsed_races if tag in filter_classifiers(race['comparison']['r4_classification_details']) and len(filter_classifiers(race['comparison']['r4_classification_details'])) == 1])))\n\n # classified by R4\n for tag in r4_classifiers:\n data.append(str(len([1 for race in parsed_races if \\\n tag in race['comparison']['r4_classification_details'] and not \\\n any(t in race['comparison']['r4_classification_details'] for t in tags)])))\n\n # classified by ER\n for tag in er_classifiers:\n data.append(str(len([1 for race in parsed_races if \\\n tag in race['comparison']['r4_classification_details'] and not \\\n any(t in race['comparison']['r4_classification_details'] for t in tags)])))\n\n for tag in tags:\n data.append(str(len([1 for race in parsed_races if tag in race['comparison']['r4_classification_details']])))\n\n # filtered by ER\n data.append(str(len([1 for race in parsed_races if\n any([tag in er_tags for tag in race['comparison']['r4_classification_details'].split(' ')])])))\n\n # filtered by R4\n data.append(str(len([1 for race in parsed_races if\n any([tag in r4_tags for tag in race['comparison']['r4_classification_details'].split(' ')])])))\n\n # classified by R4 only\n for tag in r4_classifiers:\n data.append(str(len([1 for race in parsed_races if \\\n tag in race['comparison']['r4_classification_details'] and not \\\n any(t in race['comparison']['r4_classification_details'] for t in tags) and not \\\n any(t in race['comparison']['r4_classification_details'] for t in er_classifiers)])\\\n))\n\n # classified by ER only\n for tag in er_classifiers:\n data.append(str(len([1 for race in parsed_races if \\\n tag in race['comparison']['r4_classification_details'] and not \\\n any(t in race['comparison']['r4_classification_details'] for t in tags) and not \\\n any(t in race['comparison']['r4_classification_details'] for t in r4_classifiers)])\\\n))\n\n\n # ER classifies as high\n data.append(str(len([race for race in parsed_races if race['race_data']['er_classification'] == 'HIGH'])))\n\n ## Output statistics\n print(','.join(data))\n\n ## Generate HTML files ##\n\n jinja = Environment(loader=PackageLoader('templates', ''))\n\n website_output_dir = os.path.join(output_dir, website)\n output_race_index(website, parsed_races, er_log, jinja, website_output_dir, analysis_dir)\n\n ## End ##\n\n summary = {\n 'equal': len([race for race in parsed_races if race['race_data']['result'] == 'FINISHED' and race['comparison']['is_equal']]),\n 'diff': len([race for race in parsed_races if race['race_data']['result'] == 'FINISHED' and not race['comparison']['is_equal']]),\n 'timeout': len([race for race in parsed_races if race['race_data']['result'] == 'TIMEOUT']),\n 'error': len([race for race in parsed_races if race['race_data']['result'] == 'ERROR']),\n 'er_high': len([race for race in parsed_races if race['race_data']['er_classification'] == 'HIGH']),\n 'er_normal': len([race for race in parsed_races if race['race_data']['er_classification'] == 'NORMAL']),\n 'er_low': len([race for race in parsed_races if race['race_data']['er_classification'] == 'LOW']),\n 'er_unknown': len([race for race in parsed_races if race['race_data']['er_classification'] in ['UNKNOWN', 'PARSE_ERROR']]),\n 'r4_high': len([race for race in parsed_races if race['comparison']['r4_classification'] == 'HIGH']),\n 'r4_normal': len([race for race in parsed_races if race['comparison']['r4_classification'] == 'NORMAL']),\n 'r4_low': len([race for race in parsed_races if race['comparison']['r4_classification'] == 'LOW'])\n }\n\n return {\n 'website': website,\n 'er_log': er_log,\n 'summary': summary\n }\n\ndef main():\n\n try:\n analysis_dir = sys.argv[1]\n output_dir = sys.argv[2]\n except IndexError:\n print('Usage: %s ' % sys.argv[0])\n sys.exit(1)\n\n websites = os.listdir(analysis_dir)\n\n with concurrent.futures.ProcessPoolExecutor(NUM_PROC) as executor:\n website_index = executor.map(process, [(websites[index], analysis_dir, output_dir, str(8001+index)) for index in range(0, len(websites))])\n #website_index = [process([website, analysis_dir, output_dir, \"8001\"]) for website in websites]\n output_website_index(website_index, output_dir, analysis_dir)\n\nif __name__ == '__main__':\n main()\n","sub_path":"R4/utils/batch-report/report-wave.py","file_name":"report-wave.py","file_ext":"py","file_size_in_byte":42979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"104531696","text":"\"\"\"Steps for features of Onezone login page.\n\"\"\"\n__author__ = \"Jakub Liput\"\n__copyright__ = \"Copyright (C) 2016 ACK CYFRONET AGH\"\n__license__ = \"This software is released under the MIT license cited in \" \\\n \"LICENSE.txt\"\n\nimport re\nfrom selenium.webdriver.support.ui import WebDriverWait as wait\nfrom pytest_bdd import given, when, then, parsers\nfrom tests.utils.acceptance_utils import list_parser\nfrom pytest_selenium_multi.pytest_selenium_multi import select_browser\n\n\n@given(parsers.re(\"users? of (?P.*) opened Onezone URL\"))\ndef g_visit_onezone(base_url, selenium, browser_id_list):\n for browser_id in list_parser(browser_id_list):\n driver = select_browser(selenium, browser_id)\n oz_url = base_url\n driver.get(oz_url)\n\n\n@then(parsers.parse('user of {browser_id} should see login button '\n 'for {provider_name}'))\ndef login_provider_buttons(selenium, browser_id, provider_name):\n driver = select_browser(selenium, browser_id)\n assert driver.find_element_by_css_selector(\n '.login-box a.login-icon-box.{name}'.format(name=provider_name)\n )\n\n\ndef _click_login_provider_button(driver, provider_name):\n driver.find_element_by_css_selector(\n '.login-box a.login-icon-box.{:s}'.format(provider_name)\n ).click()\n\n\n@given(parsers.re('users? of (?P.*) clicked on the '\n '\"(?P.*)\" login button'))\ndef g_click_login_provider_button(selenium, browser_id_list, provider_name):\n for browser_id in list_parser(browser_id_list):\n driver = select_browser(selenium, browser_id)\n _click_login_provider_button(driver, provider_name)\n\n\n@when(parsers.re('users? of (?P.*) clicks on the '\n '\"(?P.*)\" login button'))\ndef w_click_login_provider_button(selenium, browser_id_list, provider_name):\n for browser_id in list_parser(browser_id_list):\n driver = select_browser(selenium, browser_id)\n _click_login_provider_button(driver, provider_name)\n\n\n@then(parsers.re('user of (?P.+) should be '\n 'redirected to (?P.+) page'))\ndef being_redirected_to_page(page, selenium, browser_id):\n driver = select_browser(selenium, browser_id)\n wait(driver, 5).until(lambda s: re.match(r'https?://.*?(/#)?(/.*)', s.current_url).group(2) == page)\n\n\n@given(parsers.re('users? of (?P.*) logged '\n 'as (?P.*)'))\ndef log_to_user_in_each_browser(selenium, browser_id_list,\n user_id_list):\n for browser_id, user_id in zip(list_parser(browser_id_list),\n list_parser(user_id_list)):\n driver = select_browser(selenium, browser_id)\n driver.find_element_by_link_text(user_id).click()\n","sub_path":"tests/gui/steps/onezone_before_login.py","file_name":"onezone_before_login.py","file_ext":"py","file_size_in_byte":2845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"220565718","text":"# -*- coding: utf-8 -*-\n\n# -----------------------------------------------\n# インポート\n# -----------------------------------------------\nimport pygame\nfrom obj.obj import ObjBase\n\n# -----------------------------------------------\n# 定義\n# -----------------------------------------------\n# 獲得スコア\nscore = 100\n\n# オブジェクトスピード\nobjSpeed = 10\n\n# -----------------------------------------------\n# 星表示\n# -----------------------------------------------\nclass Star(ObjBase):\n def __init__(self, parent, x, y, player):\n super().__init__(parent, player, score, 'img/obj/star.png', 'se/switch1.wav')\n \n # 初期位置\n self.rect.center = (x, y)\n\n # 初期回転角度\n self.angl = 0\n\n # アプデ時に表示するサーフェスとその位置\n def DrawnSur(self):\n r = self.rect\n self.angl += 10\n \n # 一旦一時サーフェスに書き出し\n temp = pygame.Surface((r.width, r.height), pygame.SRCALPHA)\n temp.blit(self.sur, (0, 0))\n\n # 回転\n temp = pygame.transform.rotate(temp, self.angl)\n\n # 回転でレクトが変わるので補正\n ofstX = (r.width - temp.get_width()) / 2\n ofstY = (r.height - temp.get_height()) / 2\n r.x -= objSpeed\n\n # 書き出すサーフェスと位置を返す\n return temp, ((r.x + ofstX, r.y + ofstY))\n\n# -----------------------------------------------\n# 単体テスト\n# -----------------------------------------------\nif __name__ == '__main__':\n # 初期化\n pygame.init()\n pygame.mixer.init()\n\n # 画面生成\n pygame.display.set_mode((800, 600), 0, 32)\n screen = pygame.display.get_surface()\n pygame.display.set_caption('Star')\n\n class Dummy():\n def __init__(self):\n self.rect = pygame.Rect(0,0,1,1)\n self.score = 0\n dum = Dummy()\n star = Star(screen, 400, 300, dum, dum.score)\n\n while True:\n star.Update()\n \n ","sub_path":"obj/star.py","file_name":"star.py","file_ext":"py","file_size_in_byte":2006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"603261004","text":"#!/usr/bin/python\r\n# -*- coding: utf-8 -*-\r\n\r\nimport codecs\r\nimport simplejson\r\nimport sys\r\n\r\n\r\nclass TagsFile:\r\n def __init__(self, filenameorlist):\r\n if isinstance(filenameorlist, list):\r\n self.tracks = filenameorlist\r\n else:\r\n with open(filenameorlist) as tags:\r\n tagsjson = simplejson.load(tags)\r\n self._process_saturated_tags(tagsjson)\r\n\r\n def _process_saturated_tags(self, tagsjson):\r\n self.tracks = []\r\n saturated_tags = {}\r\n\r\n for track in tagsjson:\r\n for tag_field, value in track.iteritems():\r\n if value == []:\r\n # This is, strangely, how the M-TAGS format erases values\r\n del saturated_tags[tag_field]\r\n else:\r\n saturated_tags[tag_field] = value\r\n\r\n self.tracks.append(saturated_tags.copy())\r\n\r\n def desaturate(self):\r\n desaturated = []\r\n if self.tracks:\r\n last_saturated_tags = {}\r\n for track in self.tracks:\r\n current_desaturated = {}\r\n for tag_field, value in track.iteritems():\r\n if tag_field in last_saturated_tags:\r\n if value != last_saturated_tags[tag_field]:\r\n current_desaturated[tag_field] = value\r\n else:\r\n current_desaturated[tag_field] = value\r\n for tag_field, value in last_saturated_tags.iteritems():\r\n if tag_field not in track:\r\n current_desaturated[tag_field] = []\r\n last_saturated_tags = track\r\n desaturated.append(current_desaturated)\r\n return desaturated\r\n\r\n def write(self, filename):\r\n with codecs.open(filename, 'w', encoding='utf-8-sig') as fp:\r\n simplejson.dump(self.desaturate(), fp,\r\n ensure_ascii=False, sort_keys=True, indent=3, separators=(',', ' : '))\r\n fp.write('\\n')\r\n","sub_path":"ExtractFeatures/Data/euphonogenizer/mtags.py","file_name":"mtags.py","file_ext":"py","file_size_in_byte":1756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"488603402","text":"from multiprocessing.connection import Listener\nfrom mss import mss\nimport pickle\nimport socket\n\n\nif __name__ == '__main__':\n localIP = socket.gethostbyname(socket.gethostname())\n print(\"local ip : \",localIP)\n s = Listener((localIP,58888))\n while True:\n\n conn = s.accept()\n print('Accept a new connection')\n\n conn.send(pickle.dumps(mss().shot()))\n conn.close()\n print('Closed the connection')\n","sub_path":"work/sceencapture/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"486741880","text":"import matplotlib.pyplot as plt\n\n\ndef linspace(start, stop, num):\n return [start + (stop - start) / (num - 1) * k for k in range(num)]\n\n\ndef zeros(rows, cols):\n return [[0 for j in range(cols)] for i in range(rows)]\n\n\nd = 100 # Pixel density \nn = 32 # Maximum number of iterations\nmaxN = -1\n\nx = linspace(-2.5, 1.5, 4 * d + 1)\ny = linspace(-1.5, 1.5, 3 * d + 1)\n\nT = zeros(len(y), len(x))\n\nfor i, b in enumerate(y):\n for j, a in enumerate(x):\n # Mandelbrot set: c(a, b), z(0, 0)\n c = complex(a, b)\n z = complex(0, 0)\n \n # Julia Set: Constant c, z(a,b)\n # c = complex('(0.285+0.01j)')\n # c = complex('(-0.8+0.156j)')\n # z = complex(a, b)\n for k in range(n):\n z = z * z + c\n if complex.__abs__(z) >= 2:\n T[i][j] = k + 1\n if k > maxN:\n maxN = k\n break\n\nplt.imshow(T, cmap=plt.cm.twilight_shifted)\nplt.show()\n#plt.savefig('mandelbrot.png', dpi=200)\nprint('maxN = {}'.format(maxN))","sub_path":"mandelbrot/mandelbrotComplex.py","file_name":"mandelbrotComplex.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"567383197","text":"\"\"\"\npyFLUT.data\n-----------\n\nThis module implements the parent data class for ULF and HDF5\nimplementing the\nplot capabilities and other common features.\n\nMichele Vascellari: Michele.Vascellari@vtc.tu.freiberg.de 2015 (c)\n\"\"\"\nfrom __future__ import division\nfrom builtins import zip\nfrom builtins import range\nfrom builtins import object\nfrom past.utils import old_div\nfrom six import string_types\n\nimport collections\nimport operator\nimport h5py\nimport numpy as np\nimport scipy.interpolate\nimport pyFLUT.definition as definition\nimport tabulate\n\n\ndef join(datas, axis=0):\n \"\"\"\n Join two or more Data classes using concatenate function in numpy.\n The classes must have the same input and output variables and the\n same size in all the dimensions, except the one concatenate,\n defined by the axis.\n\n Parameters\n ----------\n datas: list\n List of Data classes to join.\n axis: int, str, optional\n Axis for concatenate the data. It can be the number of axis or\n the name of the input variable.\n\n Returns\n -------\n New pyFLUT.data.Data instance\n \"\"\"\n return Data.join(datas, axis)\n\n\nclass Data(object):\n \"\"\"\n Data class.\n It us used for storing multi-dimensional arrays (based on numpy),\n manipulate, storing, plot and lookup.\n\n Attributes\n ----------\n data: np.ndarray (n0, n1, ..., nM, N)\n Data matrix\n input_dict: collections.OrderedDict\n Input dictionary, contains the ordered input variables and their\n grid values\n output_dict: collections.OrderedDict\n Output dictionary, contains the output variables and their\n indices corrsponding to the last dimensio of data\n\n Methods\n -------\n plotdata(x, y, parameters_to_plot, index, ax, legend, **kwargs)\n contourdata(x, y, z, levels, type, parameters_to_plot, index, ax,\n colorbar, return_cp, **kwargs)\n squeeze() lookup(input_values, variable)\n \"\"\"\n\n def __init__(self, **kwargs):\n \"\"\"\n Parameters\n ----------\n kwargs: optional argument for inizializing the class\n input_dict: dict\n Input dictionary defining the input variables.\n I.e ``{'v0':np.array([...]), 'v1':np.array([...])}, ...,\n 'vM': np.array([...])}``\n output_dict: collections.ordered\n Ordered dictionary reporting the index of the variables\n contained in data. The index corresponds to the index of\n output variables in `data'.\n data: numpy.ndarray(n0, n1, ..., nM, N)\n Data array containing the values of the dataset.\n `n0`, `n1`, ... `nM` are the length of the input variables\n defined in `input_dict`. `M` is the number of output\n variables\n\n Examples\n --------\n The `Data` object can be defined as follows::\n\n >>>> import pyFLUT.data\n >>> input_dict = collections.OrderedDict(zip(['Z', 'yc'],\n [np.linspace(0, 1, 51),\n np.linspace(0, 1, 21)]))\n >>> output_dict = collections.OrderedDict(\n zip(['T', 'CO', 'CO2'], range(3)))\n >>> data = np.random.rand(51, 21, 3)\n >>> d = pyFLUT.data.Data(input_dict=input_dict,\n output_dict=output_dict, data=data)\n\n The input and output dictionaries are defined using OrderedDict.\n It is mandatory for the `input_dict`, while is reccomanded for\n the output.\n Data are organized in the data array and they can be accessed::\n\n >>> T = d['T']\n >>> print(T.shape)\n (51, 21)\n >>> d.input_variables()\n ['Z', 'yc']\n >>> d.input_variable_values('Z')\n array([ 0. , 0.02, 0.04, 0.06, ..., 1])\n >>> d.input_variable_index('yc')\n 1\n >>> len(d.input_variable_values('Z'))\n 51\n >>> d.output_variable_index('T')\n 0\n >>> d.output_variables\n ['T', 'CO', 'CO2', 'Z', 'yc']\n\n The input variables ``Z`` and ``yc`` are also included among\n the output variables.\n This correspond to the cartesian mesh grid of the input\n variables.\n \"\"\"\n if 'output_dict' and 'input_dict' and 'data' in kwargs:\n self.output_dict = kwargs['output_dict']\n self.input_dict = kwargs['input_dict']\n self.data = kwargs['data']\n else:\n raise ValueError(\n \"Data input argument {} do not \"\n \"exist\".format(kwargs))\n self.add_variables_to_data(include_last=True)\n self.regular_grid = [True for _ in self._input_dict]\n\n @classmethod\n def read_h5(cls, file_h5):\n \"\"\"\n Read a binary file using hdf5 format. This is not the format\n used by ``flameletConfig``.\n\n Parameters\n ----------\n file_h5: str\n name of h5 file\n \"\"\"\n h5 = h5py.File(file_h5, 'r')\n # input_dict\n input_dict_0 = {}\n order = {}\n for var, val in h5['/input_dict'].items():\n input_dict_0[var] = h5['/input_dict'][var]['Values'].value\n order[var] = h5['/input_dict'][var]['Index'].value\n input_dict = collections.OrderedDict()\n for i in range(len(input_dict_0)):\n var = list(order.keys())[list(order.values()).index(i)]\n input_dict[var] = input_dict_0[var]\n # output_dict\n output_dict = {}\n for var, i in h5['/output_dict'].items():\n output_dict[var] = h5['/output_dict/' + var].value\n output_dict = collections.OrderedDict(\n sorted(list(output_dict.items()), key=operator.itemgetter(1)))\n data = h5['data'].value\n h5.close()\n return cls(input_dict=input_dict,\n output_dict=output_dict,\n data=data)\n\n # TODO input_dict and output_dict can be modified\n # find a method to avoid that!\n @property\n def input_dict(self):\n return self._input_dict\n\n @input_dict.setter\n def input_dict(self, input_dict):\n if isinstance(input_dict, collections.OrderedDict):\n if not all(\n isinstance(v, np.ndarray)\n for v in input_dict.values()):\n raise ValueError(\n 'Values of input_dict should be numpy arrays')\n if not all(\n (np.alltrue(np.diff(v) > 0)\n for v in input_dict.values()\n if len(v) > 0)):\n raise ValueError(\n 'Values of input_dict should be monotonic')\n self._input_dict = input_dict.copy()\n else:\n raise TypeError(\n 'input_dict should be defined as OrderedDict')\n\n @property\n def output_dict(self):\n return self._output_dict\n\n @output_dict.setter\n def output_dict(self, output_dict):\n if isinstance(output_dict, list):\n output_dict = collections.OrderedDict(\n [(v, i) for i, v in enumerate(output_dict)])\n elif not isinstance(output_dict, collections.OrderedDict):\n msg = (\n 'Output dict should be a list or OrderedDict'\n )\n raise TypeError(msg)\n self._output_dict = output_dict.copy()\n\n @property\n def data(self):\n return self._data\n\n @data.setter\n def data(self, data):\n if not isinstance(data, np.ndarray):\n raise TypeError('data has to be a np.ndarray')\n shape = data.shape\n shape_inp = tuple(len(val)\n for val in self.input_dict.values())\n if not shape[:-1] == shape_inp:\n msg = (\n 'Data shape {} not consistent with input_dict {}'\n ).format(shape, shape_inp)\n raise ValueError(msg)\n if not shape[-1] == len(self.output_dict):\n msg = (\n 'Data shape {} not consistent with output_dict {}'\n ).format(shape, len(self.output_dict))\n raise ValueError(msg)\n self._data = data\n\n def __getitem__(self, item):\n \"\"\"\n Extract the data array for the given item\n\n Parameters\n ----------\n item: str\n It should be defined in ``output_dict``\n\n Returns\n -------\n type:\n numpy.ndarray\n \"\"\"\n if item in self.output_dict:\n return self.data[..., self.output_dict[item]]\n else:\n raise ValueError('Item {} not in output_dict'.format(item))\n\n def __setitem__(self, key, value):\n \"\"\"\n Include a new variable to the data structure\n\n Parameters\n ----------\n key: str\n Name of the new properties. It will be added to\n ``output_dict``\n value: numpy.ndarray(N0, N1, N2, ..., Nm)\n New data added to the data structure and stored with the\n key `key`.\n The dimensions `N0`, `N1`,... `Nm` of the `value` should\n correspond to the length of the `m` input variables.\n\n Examples\n --------\n A new variable `New` is added to the dataset, using a random\n dataset generated with `numpy.random.rand`::\n\n >>> d['Random'] = np.random.rand(*[len(v)\n for v in d.input_dict.values()])\n\n It is possible to access to new data, simply by::\n\n >>> print(d['Random'])\n\n It is also possible to create new variables from the existing\n ones::\n\n >>> d['rhoT'] = d['rho'] * d['T']\n \"\"\"\n if isinstance(key, int):\n self._data[..., key] = value\n elif isinstance(key, string_types):\n if key in self._output_dict:\n self._data[..., self._output_dict[key]] = value\n else:\n l = len(self)\n self._output_dict[key] = l\n self.data = np.insert(self.data, l, value, axis=-1)\n else:\n message = \"Key {} should be a int or a string\".format(key)\n raise ValueError(message)\n # definition.error_message(ValueError, self.__setitem__,\n # message)\n\n def __delitem__(self, item):\n if item in self:\n n = self._output_dict.pop(item)\n self.data = np.delete(self.data, n, -1)\n\n def __len__(self):\n \"\"\"\n Return the number of output variables defined in the dataset\n\n Returns\n -------\n length: int\n\n \"\"\"\n return len(self._output_dict)\n\n def plotdata(self, x, y, **kwargs):\n \"\"\"\n Plot data using lines. Matplotlib is used for plotting\n\n Parameters\n ----------\n x: str\n Variable plotted in the x axis\n y: str\n Variable plotted in the y axis\n parameters_to_plot: {'var0':[v00, v01, ..., v0n],\n 'var1':[v10, v11, vn1], ...}\n Define which parameters are used for the plots.\n `var0`, `var1` are input variables defined in `input_dict`\n `[v00, v01, ..., v0n]` are the values plotted of the\n variabe `var0`. If `index` is `True` they are the inde of\n `var0` defined in `input_dict[var0]`, otherwise they\n represent the real values plotted.\n Alternatively the parameters can be directly passed as\n input. See example.\n index: bool, default False\n Use index values in `parameters_to_plot` if `True`,\n otherwise use real values.\n ax: matplotlib.axes, optional\n Use the given axes for plotting\n legend: bool, default True\n Show legend\n kwargs:\n Additional arguments passed to `matplotlib.pyplot.plot`\n\n Returns\n -------\n ax: matplotlib.pyplot.axes\n\n Examples\n --------\n ::\n\n >>> ax = d.plotdata('Z', 'CO', Tf=[1000,2000], t=0)\n >>> ax.figure.show()\n\n\n plots the variable `CO` as function of `Z` using constant\n values of `Tf` of `1000` and `2000`,\n and `t` equals to `0`.\n\n If the `index` option is used::\n\n >>> ax = d.plotdata('Z', 'CO', Tf=[1000,2000], t=0,\n index=True)\n >>> ax.figure.show()\n\n plots the variable `CO` as function of `Z` using indices `0`\n and `5` of parameter `Tf` and `1` of `t`.\n\n Legend can be show or not::\n\n >>> ax = d.plotdata('Z', 'CO', Tf=[1000,2000], t=0,\n legend=False)\n\n Additional parameters to ``matplotlib.pyplot.plot`` can be\n passed using kwargs::\n\n >>> ax = d.plotdata('Z', 'CO', Tf=[1000,2000], t=0,\n linewidth=3)\n\n The option `linewidth=3` is passed to the plot function.\n See matplotlib.plot for more argument to pass.\n\n The returned `axes` object can be used for externally\n manipulating the plot.\n For example it is possible to plot more than one variables\n passing the axes object::\n\n >>> ax = d.plotdata('Z', 'CO', Tf=[1000, 2000], t=0,\n label='CO')\n >>> d.plotdata('Z', 'CO2', Tf=[1000,2000], t=0, ax=ax,\n label='CO2')\n >>> ax.set_ylabel('Mass fraction')\n >>> ax.set_xlim([0, 0.2])\n >>> ax.figure.show()\n\n This example shows how to plot `CO` and `CO2` on the same axes.\n Default labels are modified\n by user defined ones (note that overwriting default labels can\n create problems when more than one line is plotted).\n Finally the ax object is used for changing the y label and the x\n axis::\n\n >>> ax = d.plotdata('Z', 'CO', Tf=[1000,2000], t=0, marker='*',\n linestyle='dashed')\n\n This example shows how to plot dashed lines with `*` symbols.\n\n It is possible to pass the parameters to plot directly as input\n parameters without using\n the dictionary. The following two commands are equivalent:\n\n >>> ax = d.plotdata('Z', 'CO',\n parameters_to_plot={'Tf':[2000], 't':[0]}, label='CO')\n >>> ax = d.plotdata('Z', 'CO', Tf= [2000], t=[0] label='CO')\n\n See Also\n --------\n contourdata\n \"\"\"\n from matplotlib.pyplot import subplots\n\n ax = kwargs.pop('ax', None)\n if not ax:\n fg, ax = subplots()\n legend = kwargs.pop('legend', True)\n index = kwargs.pop('index', False)\n parameters_to_plot = kwargs.pop('parameters_to_plot', {})\n n_parameters = len(self._input_dict) - 1\n if not parameters_to_plot:\n parameters_to_plot = {var: kwargs.pop(var)\n for var in self._input_dict.keys()\n if var in kwargs}\n\n # check dimensions\n if n_parameters != len(parameters_to_plot):\n definition.error_message(ValueError, self.plotdata,\n \"Define a number of \"\n \"parameters_to_plot = size flut\")\n\n # check what is the variable to plot\n # this variable does not exist in parameters_to_plot\n\n if parameters_to_plot:\n for ind, variable in enumerate(self._input_dict.keys()):\n if variable not in list(parameters_to_plot.keys()):\n main_var = variable\n main_index = ind\n main_len = len(self._input_dict[variable])\n break\n\n if not index:\n points = np.empty((main_len, len(self._input_dict)))\n points[:, main_index] = self.input_variable_values(\n main_var)\n\n for par, values in parameters_to_plot.items():\n if isinstance(values, (float, int)):\n parameters_to_plot[par] = [values]\n\n param_grid = np.meshgrid(\n *[values for values in parameters_to_plot.values()],\n **{'indexing': 'ij'})\n\n for ind, _ in enumerate(param_grid[0].ravel()):\n label = ''\n if index:\n xvalues = self.__getitem__(x)\n yvalues = self.__getitem__(y)\n for i_var, variable in enumerate(\n parameters_to_plot.keys()):\n if index:\n axis = self.input_variable_index(variable)\n ind_par = param_grid[i_var].ravel()[ind]\n parameter = self._input_dict[variable][ind_par]\n xvalues = np.expand_dims(\n np.take(xvalues, ind_par, axis=axis),\n axis=axis)\n yvalues = np.expand_dims(\n np.take(yvalues, ind_par, axis=axis),\n axis=axis)\n else:\n parameter = param_grid[i_var].ravel()[ind]\n points[:, self.input_variable_index(\n variable)] = parameter\n label = label + \"{}={} \".format(variable, parameter)\n\n if index:\n xvalues = xvalues.squeeze()\n yvalues = yvalues.squeeze()\n else:\n xvalues = self.getvalue(points, x)\n yvalues = self.getvalue(points, y)\n plotarg = kwargs.copy()\n if 'label' not in plotarg:\n plotarg['label'] = label\n ax.plot(xvalues, yvalues, **plotarg)\n else:\n plotarg = kwargs.copy()\n if 'label' not in plotarg:\n plotarg['label'] = '...'\n ax.plot(self.__getitem__(x), self.__getitem__(y), **plotarg)\n\n ax.set_xlabel(x)\n ax.set_ylabel(y)\n\n if legend:\n ax.legend(loc=0)\n return ax\n\n def parameters_grid(self):\n \"\"\"\n Create a grid using the inout variables.\n\n :return: grid parameters using numpy.meshgrid\n \"\"\"\n return np.meshgrid(*[v\n for v in self._input_dict.values()],\n **{'indexing': 'ij'})\n\n def add_variables_to_data(self, include_last=False):\n \"\"\"\n Add input_dict to data using meshgrid\n\n Parameters\n ----------\n include_last: bool, dafault False\n If it is `True` the last input variable is also added\n \"\"\"\n grid = self.parameters_grid()\n if include_last:\n iterator = zip(self._input_dict, grid)\n else:\n iterator = zip(list(self._input_dict)[:-1], grid[:-1])\n for variable, g in iterator:\n self[variable] = g\n\n def contourdata(self, x, y, z, **kwargs):\n \"\"\"\n Plot data using contours. Matplotlib is used for plotting.\n\n Parameters\n ----------\n x: str\n Variable plotted in the x axis\n y: str\n Variable plotted in the y axis\n z: str\n Variable which contour is plotted\n levels: int, array_like, default 20\n Levels used for representing the contour lines or surface.\n It is used only if `type` is `contour' or `contourf`.\n If is a int represents the number of levels automatically\n chosen by matplotlib. User-defined levels can be passed\n using an `array_like`\n type: str {'contourf', 'contour', 'pcolor', 'pcolormesh'},\n default 'contourf'\n Defines which kind of matplotlib methods is used for\n plotting the contour.\n * `contourf`: a filled contour is plotted\n * `contour`: a isolines are plotted\n * `pcolor': pseudocolor plot (slow)\n * `pcolormesh': pseudocolor plot (fast)\n parameters_to_plot: {'var0':v0, 'var1':v1, ...}\n Define which parameters are fixed for the plots.\n `var0`, `var1`, `varn` are input variables defined in\n `input_dict`\n `v0`, `v1`, `vn` are the values plotted of the variable\n `var0`. If `index` is `True`\n they are the index of `var0` defined in `input_dict[var0]`,\n otherwise they represent the real values plotted.\n If the number of input parameters is 2, `parameters_to_plot`\n is not required.\n Parameters can be directly used as input, without using the\n variable parameters_to_plot\n index bool, default False\n Use index values in `parameters_to_plot` if `True`,\n otherwise use real values.\n ax: matplotlib.axes, optional\n Use the given axes for plotting\n kwargs:\n Additional arguments passed to `matplotlib.pyplot`\n\n Returns\n -------\n ax: matplotlib.pyplot.axes\n\n Examples\n --------\n ::\n\n >>> ax = d.contourdata('Z', 'yc', 'CO', Tf=1000)\n >>> ax.figure.show()\n\n plots the contour of `CO` in `Z`-`yc` plane using a constant\n value of `Tf` of `1000`.\n By default `matplotlib.pyplot.contourf` is used.\n\n A different plot method can be specified using `type`::\n\n >>> ax = d.contourdata('Z', 'yc', 'CO', Tf=1000,\n type='pcolormesh')\n >>> ax = d.contourdata('Z', 'yc', 'CO', Tf=1000,\n type='contour')\n\n\n If the `index` option is used::\n\n >>> ax = d.contourdata('Z', 'yc', 'CO', Tf=1000,\n index=True)\n\n The contour is plotted for the 3rd index of `Tf`,\n corresponding to::\n\n >>> print(d.input_variable_values['Tf'][3])\n\n Colorbar can be show or not::\n\n >>> ax = d.contourdata('Z', 'yc', 'CO', Tf=1000,\n colorbar=False)\n\n The number of contour levels can be set::\n\n >>> ax = d.contourdata('Z', 'yc', 'CO', Tf=1000, levels=20)\n\n Otherwise it is possible to define the levels passing an array::\n\n >>> levels = np.linspace(0.1, 0.2, 12)\n >>> ax = d.contourdata('Z', 'yc', 'CO', Tf=1000,\n levels=levels)\n\n The returned `ax` object can be used for adding more plots to\n the figure::\n\n >>> ax = d.contourdata('Z', 'yc', 'CO', Tf=1000, alpha=0.5)\n >>> ax.plot([0, 1], [0,1])\n >>> ax.set_xlim([0, 1])\n\n In the example a line is added to the contour plot and the x\n axis range is set between 0 and 1.\n\n Parameters can be directly used as input. The two commands are\n equivalent::\n\n >>> ax = d.contourdata('Z', 'yc', 'CO',\n parameters_to_plot={'Tf':1000})\n >>> ax = d.contourdata('Z', 'yc', 'CO', Tf=1000)\n\n\n See Also\n --------\n plotdata\n \"\"\"\n from matplotlib.pyplot import subplots\n\n index = kwargs.pop('index', False)\n type = kwargs.pop('type', 'contourf')\n ax = kwargs.pop('ax', None)\n colorbar = kwargs.pop('colorbar', True)\n return_cp = kwargs.pop('return_cp', False)\n levels = kwargs.pop('levels', 20)\n parameters_to_plot = kwargs.pop('parameters_to_plot', None)\n if not parameters_to_plot:\n parameters_to_plot = {var: kwargs.pop(var)\n for var in self._input_dict.keys()\n if var in kwargs}\n\n if self._data.ndim == 2:\n definition.error_message(IOError, self.contourdata,\n \"No of dimension is 1 no contour \"\n \"plot is possible\")\n elif self._data.ndim == 3:\n # 2D data no parameters_to_plot are necessary\n xvalues, yvalues, zvalues = [\n self.__getitem__(i) for i in [x, y, z]]\n label = ''\n else:\n new_shape = [len(values)\n for variable, values\n in self._input_dict.items()\n if variable not in parameters_to_plot]\n\n if index:\n values_to_plot = [self.__getitem__(i)\n for i in [x, y, z]]\n for parameter, value in parameters_to_plot.items():\n axis = self.input_variable_index(parameter)\n values_to_plot = [np.expand_dims(np.take(values,\n value,\n axis=axis),\n axis=axis)\n for values in values_to_plot]\n xvalues, yvalues, zvalues = [\n values.squeeze() for values in values_to_plot]\n label = ''.join('{}={}\\t'.format(var,\n self._input_dict[var][\n val])\n for var, val in\n parameters_to_plot.items())[:-1]\n else:\n gridpoints = np.meshgrid(\n *[values if var not in parameters_to_plot\n else parameters_to_plot[var]\n for var, values in self._input_dict.items()],\n **{'indexing': 'ij'})\n points = np.empty(\n (len(gridpoints[0].ravel()), len(self._input_dict)))\n for i, _ in enumerate(self._input_dict.keys()):\n points[:, i] = gridpoints[i].ravel()\n xvalues, yvalues, zvalues = [\n self.getvalue(points, i).reshape(new_shape)\n for i in [x, y, z]]\n label = ''.join('{}={}\\t'.format(var, val)\n for var, val in\n parameters_to_plot.items())[:-1]\n\n if not ax:\n fg, ax = subplots()\n else:\n fg = ax.figure\n\n if hasattr(ax, type):\n contour = getattr(ax, type)\n args = [xvalues, yvalues, zvalues]\n if type not in ['pcolor', 'pcolormesh']:\n args.append(levels)\n cf = contour(*args, **kwargs)\n ax.set_xlabel(x)\n ax.set_ylabel(y)\n if colorbar:\n cb = fg.colorbar(cf, ax=ax)\n if colorbar:\n cb.set_label(z)\n else:\n cb.set_label(colorbar)\n else:\n cb = None\n ax.set_title(label)\n if return_cp:\n return ax, cf, cb\n else:\n return ax\n\n def interpolate_variable(self, variable):\n \"\"\"\n Define an interpolation class function for the given variable.\n\n Parameters\n ----------\n variable: str\n interpolated variable, it should be defined in `output_dict`\n\n Returns\n -------\n funct: scipy.interpolate.interp1d\n\n See Also\n --------\n Data.getvalue\n scipy.interpolate.interp1d\n\n Examples\n --------\n A interpolation function for the variable `T` is calculated::\n\n >>> T_ip = d.interpolate_variable('T')\n >>> print(T_ip([0.2, 0.15]))\n\n The function `T_ip` accept as input an array of the same length\n of the input_dict.\n \"\"\"\n def funct(x):\n if isinstance(x, list):\n x = np.array(x)\n if x.ndim == 1:\n x = np.expand_dims(x, axis=0)\n elif x.ndim > 2:\n definition.error_message(ValueError,\n self.interpolate_variable,\n \"Number of dimensions >2\")\n # check if one or more dimensions need to be removed\n columns = []\n for i, val in enumerate(self._input_dict.values()):\n x[:, i][x[:, i] < val.min()] = val.min()\n x[:, i][x[:, i] > val.max()] = val.max()\n if len(val) > 1:\n columns.append(i)\n x = np.take(x, columns, axis=1).squeeze()\n y = F(x)\n return np.array([y]) if y.shape == () else y\n\n method = 'linear'\n grid_input = [value for value in self._input_dict.values()\n if len(value) > 1]\n squeezed_var = np.squeeze(self.__getitem__(variable))\n if len(grid_input) > 1:\n F = scipy.interpolate.RegularGridInterpolator(\n grid_input,\n squeezed_var,\n method=method,\n bounds_error=False)\n else:\n F = scipy.interpolate.interp1d(grid_input[0],\n squeezed_var,\n kind=method,\n bounds_error=False)\n return funct\n\n def lookup(self, input_values, variable):\n \"\"\"\n Return the interpolated value of the of the given variable for\n the input_values\n\n Parameters\n ----------\n input_values: array_like(n_inp, n_points)\n Input values for the interpolation. The dimensions of the\n array are:\n * `n_inp`: number of input variables in the `input_dict`\n * `n_points`: number of input points for the interpolation\n variable: str:\n Name of the interpolated variables\n\n Returns\n -------\n interpolated_values: numpy.ndarray(n_points)\n Array of interpolated values of the `variable`\n\n Examples\n --------\n\n Considering the input variables::\n\n >>> d.input_variables()\n ['Z', 'yc']\n\n The first variable is `Z` and the second is `yc`::\n\n >>> points = [[0, 1], [0.5, 1], [1,1]]\n >>> T_ip = d.getvalue(points, 'T'\n >>> print(T_ip)\n array([ 1249. , 1343.7731, 678. ])\n\n \"\"\"\n F = self.interpolate_variable(variable)\n return F(input_values)\n\n def getvalue(self, input_values, variable):\n \"\"\"\n Return the interpolated value of the of the given variable for\n the input_values. The method is replace by lookup\n\n See Also\n --------\n lookup\n\n .. note:: Deprecated in pyFLUT 2.0\n `getvalue` will be replaced in pyFLUT 2.0 and replaced by\n `lookup`\n \"\"\"\n return self.lookup(input_values=input_values, variable=variable)\n\n def write_ascii(self, file_ascii):\n \"\"\"\n Export data in ASCII file\n\n Parameters\n ----------\n file_ascii: str\n name of the output ASCII file\n\n Examples\n --------\n Dataset can be exported as follows::\n\n >>> d.write_ascii('results.txt')\n\n The format of the file is the following::\n\n $ cat results.txt\n AR C C2H C2H2 C2H3 C2H4 C2H5 C2H6 C3H7 C3H8 CH CH2\n 0.0 0.0 0.0 0.24085096 0.0 0.079229316999999994\n 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0\n ...\n\n \"\"\"\n import csv\n # TODO allows to work for more than 2D tables\n with open(file_ascii, 'w') as f:\n wr = csv.writer(f, delimiter=' ')\n # write header\n # write input parameters\n for index, (var, values) in enumerate(\n self._input_dict.items()):\n # wr.writerow('# Input {}: {}'.format(index, var))\n # wr.writerow(values)\n f.write('# Input {}: {}\\n'.format(index, var))\n wr.writerow(values)\n wr.writerow(['#'] + list(self._output_dict.keys()))\n for data_row in self._data.reshape(-1, self._data.shape[-1]):\n wr.writerow(data_row)\n\n def write_vtk(self, file_vtk, output_variables=None):\n from pyevtk.hl import gridToVTK\n if len(self._input_dict) == 3:\n if not output_variables:\n output_variables = self.output_variables\n return gridToVTK(\"structured\", *list(self._input_dict.values()),\n pointData={var: self.__getitem__(var).T\n for var in output_variables})\n else:\n definition.error_message(ValueError, self.write_vtk,\n \"Export to VTK supported only \"\n \"for 3D dataset\")\n\n def write_bin(self, file_h5, compression=\"gzip\"):\n \"\"\"\n Write a binary file using hdf5 format. This is not the format\n used by ``flameletConfig``.\n\n Parameters\n ----------\n file_h5: str\n name of h5 file\n compression: str {'gzip', ...'}\n Type of compression used\n\n See Also\n --------\n h5py.create_dataset\n \"\"\"\n h5 = h5py.File(file_h5, 'w')\n # input_dict\n h5.create_group('input_dict')\n for i, (var, val) in enumerate(self._input_dict.items()):\n h5['/input_dict'].create_group(var)\n h5['/input_dict/' + var].create_dataset('Values', data=val)\n h5['/input_dict/' + var].create_dataset('Index', data=i)\n # output_dict\n h5.create_group('output_dict')\n for var, i in self._output_dict.items():\n h5['/output_dict'].create_dataset(var, data=i)\n\n h5.create_dataset('data', data=self._data,\n compression=compression)\n h5.close()\n\n @property\n def input_variables(self):\n \"\"\"\n Return a list of the input variables\n\n Returns\n -------\n inp_variables: list\n \"\"\"\n return list(self._input_dict.keys())\n\n def input_variable_index(self, variable):\n \"\"\"\n Return the index of the given input variable\n\n Parameters\n ----------\n variable: str\n name of the input variable\n\n Returns\n -------\n index: int\n index of the input variable\n \"\"\"\n return list(self._input_dict.keys()).index(variable)\n\n def input_variable_values(self, variable):\n \"\"\"\n Return the array of the given input variable\n\n Parameters\n ----------\n variable:str\n name of the input variable\n\n Returns\n -------\n input_array: numpy.ndarray\n Numpy array contaning the values of the input parameter\n \"\"\"\n return self._input_dict[variable]\n\n def __contains__(self, key):\n return key in self.output_dict\n\n @property\n def output_variables(self):\n \"\"\"\n Return the list of the output variables\n\n Returns\n -------\n out_variables: list\n list of the output variables\n\n \"\"\"\n return list(self._output_dict.keys())\n\n def output_variable_index(self, variable):\n \"\"\"\n Return the index of the given output variable\n\n Parameters\n ----------\n variable: str\n name of the output variable\n\n Returns\n -------\n index: int\n index of the output variable\n \"\"\"\n return self._output_dict[variable]\n\n def squeeze(self):\n \"\"\"\n Squeeze the dimensions of the data object\n \"\"\"\n input_dict = collections.OrderedDict()\n for var, vals in self._input_dict.items():\n if len(vals) > 1:\n # self._input_dict.pop(var)\n input_dict[var] = vals\n self.input_dict = input_dict\n self.data = np.squeeze(self._data)\n\n def __copy__(self):\n # cls = self.__class__\n # results = cls.__new__(cls)\n # results.__dict__.update(self.__dict__)\n # return results\n return Data(input_dict=self._input_dict, data=self._data,\n output_dict=self._output_dict)\n\n def __str__(self):\n return tabulate.tabulate(\n [[var, val.min(), val.max(), len(val)]\n for var, val in self._input_dict.items()],\n headers=['Variable', 'Min', 'Max', 'N'])\n\n def __repr__(self):\n return super(Data, self).__repr__() + '\\n\\n' + self.__str__()\n\n def gradient(self, variable, along=None, method='central',\n velocity=None):\n \"\"\"\n Calculate gradient\n\n Parameters\n ----------\n variable: str\n variable whose gradient is calculated\n along: str, None, default=None\n along which variable calculate gradient. If None use the\n last input_dict variable.\n method: str, default='central'\n method used for the gradient: 'central', 'upwind' are\n allowed.\n velocity: str, None, default=None\n velocity variable, use onlu with 'upwind'\n\n Returns\n -------\n np.array: gradient dY/dX with Y=variable and X=along\n\n \"\"\"\n if not along:\n along = self.input_variables()[-1]\n elif along not in self._input_dict:\n definition.error_message(IOError, self.gradient,\n \"Along has to be\"\n \" an input variable\")\n axis = list(self._input_dict.keys()).index(along)\n len_along = len(self._input_dict[along])\n x = self[along]\n y = self[variable]\n if method == 'central':\n mask_p_list = (\n [1], list(range(2, len_along)), [len_along - 1])\n mask_n_list = ([0], list(range(0, len_along - 2)),\n [len_along - 2])\n grad = [\n old_div((np.take(y, mask_p, axis=axis) -\n np.take(y, mask_n, axis=axis)),\n (np.take(x, mask_p, axis=axis) -\n np.take(x, mask_n, axis=axis)))\n for mask_p, mask_n in zip(mask_p_list, mask_n_list)]\n grad = np.concatenate(grad, axis=axis)\n elif method == 'upwind':\n if not velocity:\n definition.error_message(IOError, self.gradient,\n \"Define a velocity for\"\n \" upwind method\")\n elif velocity not in self._output_dict:\n definition.error_message(IOError, self.gradient,\n \"Defined velocity not in the \"\n \"output dictionary\")\n if len(self._input_dict) > 1:\n definition.error_message(NotImplemented, self.gradient,\n \"Upwind works NOW only for\"\n \" 1D data\")\n U = self[velocity]\n index_vel_pos = np.where(U >= 0)[0]\n if np.alltrue(np.diff(index_vel_pos == 1)):\n definition.error_message(NotImplemented, self.gradient,\n \"Upwind works only for 1D\"\n \" data with two distinct\"\n \" regions\")\n index_vel_neg = np.where(U < 0)[0]\n if np.alltrue(np.diff(index_vel_neg == 1)):\n definition.error_message(NotImplemented, self.gradient,\n \"Upwind works only for 1D data\"\n \" with two distinct regions\")\n if index_vel_pos.max() > index_vel_neg.min():\n definition.error_message(NotImplemented, self.gradient,\n \"Upwind works only for 1D data\"\n \" with two distinct regions \"\n \"It is assumed to have\"\n \" positive velocity on\"\n \" the left\")\n grad = []\n mask_p_list = np.concatenate([[1], index_vel_pos[1:],\n index_vel_neg[1:],\n index_vel_neg[-1:]])\n mask_n_list = np.concatenate([[0], index_vel_pos[:-1],\n index_vel_neg[:-1],\n index_vel_neg[-2:-1]])\n grad = old_div((y[mask_p_list] - y[mask_n_list]),\n (x[mask_p_list] - x[mask_n_list]))\n return grad\n\n def extract_values(self, variables=None, **kwargs):\n \"\"\"\n Extract values from the data object.\n\n Parameters\n ----------\n variables: list, str (default:None)\n List or single variable to export. If None export all\n the variables\n use_index: bool (default: False)\n Flag for using index or real values for extracting\n properties\n input_variables: float, int\n Input variables as defined in input_dict. Use float or int\n if use_index is False or True\n return_dict: bool (default: False)\n Output is returned as dictionary\n\n Returns\n -------\n float, np.array\n Extracted single value or array of values for multiple\n variables\n\n Examples\n --------\n Extract ``T`` for a given set of values (the input variables are\n ``X`` and ``Y``)::\n\n >>>> data.input_variables()\n ['X', 'Y']\n >>>> T = data.extract_value(X=0.5, Y=0.5, variables='T')\n >>>> print(T)\n 523.00\n\n Now the input variable ``Y`` is not defined. The first value of\n ``Y`` is assumed ::\n\n >>>> T = data.extract_value(X=0.5, variables='T')\n >>>> print(T)\n 350.00\n\n Now use ``use_index`` ::\n\n >>>> T = data.extract_value(X=2, Y=0, variables='T')\n >>>> print(T)\n 400.00\n >>>> T = data.extract_value(X=2, variables='T')\n >>>> print(T)\n 400.00\n\n Now extract more variables ::\n\n >>>> data.extract_value(X=2, Y=0, variables=['T', 'rho'])\n [400, 0.23]\n\n \"\"\"\n use_index = kwargs.get('use_index', False)\n return_dict = kwargs.get('return_dict', False)\n # print('use_index=', use_index)\n # variables = kwargs.get('variables', None)\n points = len(self._input_dict) * [0]\n for var, val in self._input_dict.items():\n if use_index:\n inp_val = kwargs.get(var, 0)\n # set index , default is 0\n else:\n # set value, default is first\n inp_val = kwargs.get(var, self._input_dict[var][0])\n points[list(self.input_dict).index(var)] = inp_val\n # print('points', points)\n if use_index:\n data = self._data[tuple(points)]\n # print('self.data shape', self.data.shape)\n # print('data shape', data.shape)\n if isinstance(variables, list):\n variable_indices = [self._output_dict[v]\n for v in variables\n if v in self._output_dict]\n elif isinstance(variables, str):\n variable_indices = self._output_dict[variables]\n else:\n variable_indices = list(self._output_dict.values())\n data = np.take(data, variable_indices)\n else:\n if not variables:\n variables = self.output_variables\n # print('variables', variables)\n if isinstance(variables, list):\n # return np.array([self.getvalue(points, v) for v in\n # variables]).squeeze()\n data = np.array([self.getvalue(points, v)\n for v in variables]).squeeze()\n elif isinstance(variables, string_types):\n # return self.getvalue(points, variables)[0]\n data = self.getvalue(points, variables)[0]\n\n if return_dict:\n if isinstance(variables, (list, np.ndarray)):\n return collections.OrderedDict(list(zip(variables, data)))\n else:\n return {variables: data}\n else:\n return data\n\n @property\n def shape(self):\n return self.data.shape\n\n @property\n def ndim(self):\n return self.data.ndim\n\n @classmethod\n def join(cls, datas, axis=0):\n \"\"\"\n Join two or more Data classes using concatenate function in\n numpy. The classes must have the same input and output\n variables and the same size in all the dimensions, except the\n one concatenate, defined by the axis.\n\n Parameters\n ----------\n datas: list\n List of Data classes to join.\n axis: int, str, optional\n Axis for concatenate the data. It can be the number of axis\n or the name of the input variable.\n\n Returns\n -------\n New pyFLUT.data.Data instance\n \"\"\"\n # TODO return same datatype as original\n if isinstance(axis, string_types):\n axis_name = axis\n axis = datas[0].input_variable_index(axis)\n else:\n axis_name = datas[0].input_variables()[axis]\n data = np.concatenate([d.data for d in datas], axis=axis)\n input_dict = collections.OrderedDict()\n for var in datas[0].input_dict.keys():\n if axis_name == var:\n input_dict[var] = np.concatenate(\n [d.input_dict[var] for d in datas])\n else:\n input_dict[var] = datas[0].input_dict[var]\n output_dict = datas[0].output_dict\n\n return cls(input_dict=input_dict, output_dict=output_dict,\n data=data)\n","sub_path":"pyFLUT/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":46293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"258406729","text":"from django.core.mail import send_mail\nimport requests\nfrom urllib import quote_plus\nfrom datetime import datetime\n\nfrom django.core.management.base import BaseCommand\nfrom django.conf import settings\n\nfrom artist.models import Artist, ArtistRating\nfrom event.models import Event\n\n\n\nclass Command(BaseCommand):\n def handle(self, *args, **options):\n for artist in Artist.objects.all():\n url = u'http://api.bandsintown.com/artists/{}/events.json?api_version=2.0&app_id=liveinconvert'\\\n .format(quote_plus(artist.name.encode('utf-8')))\n\n ret = requests.get(url)\n if ret.status_code != 200:\n continue\n\n data = ret.json()\n if type(data) == dict:\n continue\n\n for event in data:\n if event['venue']['country'] != 'Switzerland':\n continue\n\n event_obj, created = Event.objects.update_or_create(bandsintown_id=event['id'], defaults={\n 'name': event['title'],\n 'artist': artist,\n 'location': event['venue']['name'],\n 'date_time': datetime.strptime(event['datetime'], '%Y-%m-%dT%H:%M:%S'),\n 'bandsintown_id': event['id'],\n })\n\n if created:\n for rating in artist.artistrating_set.filter(rating=ArtistRating.LIKE):\n send_mail(u'New Concert for {}'.format(artist.name),\n u'{} {} {}'.format(event_obj.name, event_obj.artist, event_obj.date_time),\n settings.EMAIL_SENDER, [rating.user.email], fail_silently=False)\n","sub_path":"event/management/commands/bandsintown.py","file_name":"bandsintown.py","file_ext":"py","file_size_in_byte":1699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"371640980","text":"# Copyright 2016-19 Steven Cooper\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Network utilities.\"\"\"\n\nimport os\n\nfrom . import console\nfrom . import disk\nfrom . import command\n\n\ndef get_listener(port):\n \"\"\"Return port listener if any.\"\"\"\n with command.Command('lsof', '-i:%d' % port, '-sTCP:LISTEN', '-t') as cmd:\n for line in cmd:\n return int(line)\n\n\ndef ssh_tunnel_connect( #pylint: disable=unused-argument\n remote_host,\n remote_port,\n local_port,\n ssh_port=22,\n dry_run=False):\n \"\"\"Set up and connect an SSH tunnel.\"\"\"\n context = console.Context(**locals())\n lpid = get_listener(local_port)\n if lpid is None:\n context.info('Connecting tunnel from {remote_host}:{remote_port} '\n 'to localhost:{local_port}...')\n autossh_cmd = ('autossh -M 0 -f -N -o '\n '\"ServerAliveInterval 60\" -o \"ServerAliveCountMax 3\" '\n '-p {ssh_port} '\n '-L {local_port}:localhost:{remote_port} '\n '{remote_host}')\n if dry_run:\n context.info(autossh_cmd)\n else:\n if os.system(autossh_cmd) == 0:\n context.info('Tunnel from {remote_host}:{remote_port} '\n 'to localhost:{local_port} is active.')\n else:\n context.abort('Failed to connect tunnel from {remote_host}:{remote_port} '\n 'to localhost:{local_port}.')\n else:\n context.info('Port {local_port} is already handled by process {lpid}.')\n\n\ndef ssh_tunnel_disconnect(local_port, dry_run=False):\n \"\"\"Disconnect an ssh tunnel.\"\"\"\n context = console.Context(**locals())\n lpid = get_listener(local_port)\n if lpid:\n context.info('Killing port {local_port} listener process {lpid}...')\n kill_cmd = context.format_string('kill {lpid}')\n if dry_run:\n context.info(kill_cmd)\n else:\n if os.system(kill_cmd) == 0:\n context.info('Port listener process {lpid} was killed and '\n 'port {local_port} was disconnected.')\n else:\n context.abort('Failed to kill listener process {lpid}.')\n else:\n context.info('Port {port} does not have an active listener.')\n\n\ndef sshfs_mount(mountpoint, remote_host, ssh_port=22, dry_run=False): # pylint: disable=unused-argument\n \"\"\"Use sshfs to mount a remote drive.\"\"\"\n context = console.Context(**locals())\n if disk.mounts_check(mountpoint):\n context.info('{mountpoint} was already mounted.')\n else:\n if not os.path.exists(mountpoint):\n if dry_run:\n context.info('mkdir {mountpoint}')\n else:\n os.mkdir(mountpoint)\n sshfs_cmd = context.format_string(\n 'sshfs -p {ssh_port} -o idmap=user -o defer_permissions {remote_host}:/ {mountpoint}')\n if dry_run:\n context.info(sshfs_cmd)\n else:\n if os.system(sshfs_cmd) == 0:\n context.info('{mountpoint} is mounted.')\n else:\n context.abort('{mountpoint} failed to mount.')\n","sub_path":"scriptbase/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":3714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"415809949","text":"# https://leetcode.com/problems/reverse-integer/\n\nif x >= 0:\n temp = str(x)\n temp = int(temp[::-1])\n if (temp > (2**31 -1)) or (temp < -2**31):\n return 0\n else:\n return temp\nelif x == 0:\n return 0\nelse:\n temp = abs(x)\n temp = str(temp)\n temp = int(temp[::-1])\n temp *= -1\n if (temp > (2**31 -1)) or (temp < -2**31):\n return 0\n else:\n return temp","sub_path":"Reverse Integer.py","file_name":"Reverse Integer.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"223452271","text":"import pytest\nfrom flask import jsonify\n\nfrom apistrap import Swagger\nfrom apistrap.errors import SwaggerExtensionError\n\n\ndef test_swagger_extension_definition_conflict():\n with pytest.raises(ValueError):\n swagger = Swagger()\n swagger.add_definition(\"name\", {\"foo\": \"bar\"})\n swagger.add_definition(\"name\", {\"baz\": \"bar\"})\n\n\ndef test_getters():\n swagger = Swagger()\n swagger.title = \"Title\"\n swagger.description = \"Description\"\n assert swagger.title == \"Title\"\n assert swagger.description == \"Description\"\n\n\ndef test_spec_url(app, client):\n swagger = Swagger()\n\n swagger.spec_url = \"/myspecurl.json\"\n assert swagger.spec_url == \"/myspecurl.json\"\n\n swagger.init_app(app)\n\n @app.route(\"/\")\n @swagger.autodoc()\n def view():\n return jsonify()\n\n response = client.get(\"/myspecurl.json\")\n assert response.status_code == 200\n assert \"paths\" in response.json\n\n\ndef test_spec_url_reset(app, client):\n swagger = Swagger()\n\n swagger.spec_url = None\n assert swagger.spec_url is None\n\n swagger.spec_url = \"/myspecurl.json\"\n assert swagger.spec_url == \"/myspecurl.json\"\n\n swagger.init_app(app)\n\n @app.route(\"/\")\n @swagger.autodoc()\n def view():\n return jsonify()\n\n response = client.get(\"/myspecurl.json\")\n assert response.status_code == 200\n assert \"paths\" in response.json\n\n\ndef test_spec_url_cannot_be_set_after_init(app):\n swagger = Swagger(app)\n with pytest.raises(SwaggerExtensionError):\n swagger.spec_url = \"whatever\"\n\n\ndef test_disable_spec_url(app, client):\n swagger = Swagger()\n\n swagger.spec_url = None\n assert swagger.spec_url is None\n\n swagger.init_app(app)\n\n @app.route(\"/\")\n @swagger.autodoc()\n def view():\n return jsonify()\n\n response = client.get(\"/swagger.json\")\n assert response.status_code == 404\n\n\ndef test_disable_ui(app, client):\n swagger = Swagger()\n swagger.ui_url = None\n assert swagger.ui_url is None\n swagger.init_app(app)\n\n response = client.get(\"/apidocs/\")\n assert response.status_code == 404\n\n\ndef test_ui_url_cannot_be_set_after_init(app):\n swagger = Swagger(app)\n with pytest.raises(SwaggerExtensionError):\n swagger.ui_url = None\n\n\ndef test_set_ui_url(app, client):\n swagger = Swagger()\n\n swagger.ui_url = \"/docs/\"\n assert swagger.ui_url == \"/docs/\"\n\n swagger.init_app(app)\n\n response = client.get(\"/docs/\")\n assert response.status_code == 200\n","sub_path":"tests/test_swagger_extension.py","file_name":"test_swagger_extension.py","file_ext":"py","file_size_in_byte":2478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"169094284","text":"import pandas as pd\nfrom scipy import misc\nimport argparse\nfrom matplotlib.pyplot import imshow\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport scipy.io\nimport scipy.misc\nimport os, sys\nimport shutil\nimport fnmatch\nimport math\nimport random, shutil\nfrom PIL import Image\nimport numpy as np\nimport tensorflow as tf\nfrom keras import backend as K\nfrom keras.layers import Input, Lambda, Conv2D\nfrom keras.models import load_model, Model\nfrom keras import optimizers, initializers\nfrom keras.callbacks import TensorBoard, ModelCheckpoint, EarlyStopping\n\nfrom yolo_utils import read_classes, read_anchors, generate_colors, preprocess_image, draw_boxes, scale_boxes\nfrom retrain_yolo import process_data,process_data_pil,process_data_pil_wide,get_classes,get_anchors,get_detector_mask,train,draw\nfrom yad2k.models.keras_yolo import yolo_head, yolo_boxes_to_corners, preprocess_true_boxes,preprocess_true_boxes_true_box, yolo_loss, yolo_body, yolo_eval\n\n\ndef predict_any(sess , model, image_file, anchors, class_names, max_boxes, score_threshold, iou_threshold):\n \n # Get head of model\n yolo_outputs_ = yolo_head(model.output, anchors, len(class_names))\n input_image_shape = K.placeholder(shape=(2, ))\n \n # Preprocess your image\n model_image_size = model.inputs[0].get_shape().as_list()[-3:-1]\n image, image_data = preprocess_image(image_file, model_image_size = model_image_size )\n \n img=plt.imread(image_file)\n img_shape_ = img.shape[0:2]\n print( \"Reshaping input image \"+str( img_shape_) +\" to model input shape \"+str(model_image_size) )\n if img_shape_[0]>img_shape_[1]:\n print( \"Wrong input size \",str( img_shape_), \" Exiting\" )\n return (0,0,0)\n # Get the Tensors\n boxes, scores, classes = yolo_eval(yolo_outputs_, [float(i) for i in list(img_shape_)],\n max_boxes,\n score_threshold,\n iou_threshold) \n\n # Run the session with the correct tensors and choose the correct placeholders in the feed_dict.\n out_boxes, out_scores, out_classes = sess.run(\n [boxes, scores, classes],\n feed_dict={\n model.input: image_data,\n input_image_shape: [image_data.shape[2], image_data.shape[3]],\n K.learning_phase(): 0\n })\n\n # Print predictions info\n print('Found {} boxes for {}'.format(len(out_boxes), image_file))\n # Generate colors for drawing bounding boxes.\n colors = generate_colors(class_names)\n # Draw bounding boxes on the image file\n draw_boxes(image, out_scores, out_boxes, out_classes, class_names, colors)\n # Save the predicted bounding box on the image\n image.save(os.path.join(\"out\", image_file.split('/')[-1]), quality=90)\n # Display the results in the notebook\n plt.figure()\n\n output_image = scipy.misc.imread(os.path.join(\"out\", image_file.split('/')[-1]))\n plt.imshow(output_image)\n\n return out_scores, out_boxes, out_classes\n\n# Wrap the Yolo model with other model for training: You can select how to wrpait and if you wnat to do transfer learning\n# Create model around yolo model \n# Use freeze_body for doing transfer learning on 1st training stage \ndef create_model(anchors, class_names, load_pretrained=True, freeze_body=True, regularization_rate = 0.01):\n '''\n returns the body of the model and the model\n\n # Params:\n\n load_pretrained: whether or not to load the pretrained model or initialize all weights\n\n freeze_body: whether or not to freeze all weights except for the last layer's\n\n # Returns:\n\n model_body: YOLOv2 with new output layer\n\n model: YOLOv2 with custom loss Lambda layer\n\n '''\n\n detectors_mask_shape = (13, 13, 5, 1)\n matching_boxes_shape = (13, 13, 5, 5)\n\n # Create model input layers.\n image_input = Input(shape=(416, 416, 3))\n boxes_input = Input(shape=(None, 5))\n detectors_mask_input = Input(shape=detectors_mask_shape)\n matching_boxes_input = Input(shape=matching_boxes_shape)\n\n # Create model body.\n yolo_model = yolo_body(image_input, len(anchors), len(class_names))\n topless_yolo = Model(yolo_model.input, yolo_model.layers[-2].output)\n\n if load_pretrained:\n # Save topless yolo:\n topless_yolo_path = os.path.join('model_data', 'yolo_topless.h5')\n if not os.path.exists(topless_yolo_path):\n print(\"CREATING TOPLESS WEIGHTS FILE\")\n yolo_path = os.path.join('model_data', 'yolo.h5')\n model_body = load_model(yolo_path)\n model_body = Model(model_body.inputs, model_body.layers[-2].output)\n model_body.save_weights(topless_yolo_path)\n topless_yolo.load_weights(topless_yolo_path)\n\n if freeze_body:\n for layer in topless_yolo.layers:\n layer.trainable = False\n final_layer = Conv2D(len(anchors)*(5+len(class_names)), (1, 1), activation='linear')(topless_yolo.output)\n \n # Implement regularization\n if regularization_rate: # if we want regularization\n for layer in topless_yolo.layers:\n if hasattr(layer, 'kernel_regularizer'):\n layer.kernel_regularizer = regularization_rate\n \n model_body = Model(image_input, final_layer)\n\n # Place model loss on CPU to reduce GPU memory usage.\n with tf.device('/cpu:0'):\n # TODO: Replace Lambda with custom Keras layer for loss.\n model_loss = Lambda(\n yolo_loss,\n output_shape=(1, ),\n name='yolo_loss',\n arguments={'anchors': anchors,\n 'num_classes': len(class_names)})([\n model_body.output, boxes_input,\n detectors_mask_input, matching_boxes_input\n ])\n\n model = Model(\n [model_body.input, boxes_input, detectors_mask_input,\n matching_boxes_input], model_loss)\n\n return model_body, model\n\ndef create_model_wide(sess,anchors, class_names, load_pretrained=True, freeze_body=True, regularization_rate = 0.01,\n initialize_weights = False):\n '''\n returns the body of the model and the model\n\n # Params:\n\n load_pretrained: whether or not to load the pretrained model or initialize all weights\n\n freeze_body: whether or not to freeze all weights except for the last layer's\n\n # Returns:\n\n model_body: YOLOv2 with new output layer\n\n model: YOLOv2 with custom loss Lambda layer\n\n '''\n\n detectors_mask_shape = (13, 19, 5, 1)\n matching_boxes_shape = (13, 19, 5, 5)\n\n # Create model input layers.\n image_input = Input(shape=(416, 608, 3))\n boxes_input = Input(shape=(None, 5))\n detectors_mask_input = Input(shape=detectors_mask_shape)\n matching_boxes_input = Input(shape=matching_boxes_shape)\n\n # Create model body.\n yolo_model = yolo_body(image_input, len(anchors), len(class_names))\n topless_yolo = Model(yolo_model.input, yolo_model.layers[-2].output)\n \n if load_pretrained:\n # Save topless yolo:\n topless_yolo_path = os.path.join('model_data', 'yolo_topless.h5')\n if not os.path.exists(topless_yolo_path):\n print(\"CREATING TOPLESS WEIGHTS FILE\")\n yolo_path = os.path.join('model_data', 'yolo.h5')\n model_body = load_model(yolo_path)\n model_body = Model(model_body.inputs, model_body.layers[-2].output)\n model_body.save_weights(topless_yolo_path)\n topless_yolo.load_weights(topless_yolo_path)\n\n if freeze_body:\n for layer in topless_yolo.layers:\n layer.trainable = False\n final_layer = Conv2D(len(anchors)*(5+len(class_names)), (1, 1), activation='linear')(topless_yolo.output)\n \n model_body = Model(image_input, final_layer)\n \n # Implement regularization\n if regularization_rate: # if we want regularization\n for layer in model_body.layers:\n if hasattr(layer, 'kernel_regularizer'):\n layer.kernel_regularizer = regularization_rate\n \n # Implement initialize_weights\n if initialize_weights: # if we want initialize\n for layer in model_body.layers:\n if hasattr(layer, 'kernel_initializer'):\n layer.kernel_initializer = initializers.get(\"glorot_uniform\")\n layer.kernel.initializer.run(session=sess)\n \n# print(model_body.output)\n # Place model loss on CPU to reduce GPU memory usage.\n with tf.device('/cpu:0'):\n # TODO: Replace Lambda with custom Keras layer for loss.\n model_loss = Lambda(\n yolo_loss,\n output_shape=(1, ),\n name='yolo_loss',\n arguments={'anchors': anchors,\n 'num_classes': len(class_names)})([\n model_body.output, boxes_input,\n detectors_mask_input, matching_boxes_input\n ])\n\n model = Model(\n [model_body.input, boxes_input, detectors_mask_input,\n matching_boxes_input], model_loss)\n\n return model_body, model\n\ndef get_batch(list_filenames, batch_size,boxes_dir, class_idx,classes_path,anchors_path): \n # Get anchors and classes names\n class_names = get_classes(classes_path)\n anchors = get_anchors(anchors_path)\n Img_db = pd.read_csv(boxes_dir, header = 0)\n while True:\n for batches in range(len(list_filenames) // batch_size):\n images_list = []\n boxes_list = []\n image_data = None\n boxes = None\n for image_sample in list_filenames[batches*batch_size:min(len(list_filenames),(batches+1)*batch_size)]:\n \n# images_list.append( mpimg.imread(image_sample) )\n images_list.append( Image.open( image_sample ) )\n \n # Write the labels and boxes\n # Original boxes stored as 1D list of class, x_min, y_min, x_max, y_max.\n labels_boxes = []\n # print(Img_db[Img_db['image_filename']==image_sample.split(\"/\")[-1]].as_matrix())\n for box_matched in Img_db[Img_db['image_filename']==image_sample.split(\"/\")[-1]].as_matrix():\n labels_boxes.append( [class_idx[box_matched[-2]], *box_matched[2:6]] )\n boxes_list.append(np.asarray(labels_boxes))\n \n # Check if image is fliped and portrait it\n if images_list[-1].width= iou_eval_threshold and preds[0] == grounds[0] ):\n true_positives += 1\n labels_boxes_pred[i][0]=100\n labels_boxes_ground[j][0]=200\n\n # Precision and recall\n positive_detections += labels_boxes_pred.shape[0]\n positive_samples += labels_boxes_ground.shape[0]\n \n \n# print(true_positives,positive_samples,positive_detections)\n \n if(positive_detections!=0 and positive_samples!=0 ):\n precision = float(true_positives) / float(positive_detections)\n recall = float(true_positives) / float(positive_samples)\n\n print( \" mean precision = \",precision,\" , mean recall = \",recall )\n print( \" Final F1 score = \",2*precision*recall/(precision+recall) )\n\ndef nexar_eval_test(sess , model, image_files, boxes_dir, anchors,class_idx, class_names, max_boxes, score_threshold,\n iou_threshold=0.5, plot_result = False ):\n ## Evaluate all images in the the image_files list (Test images) and save the results to an Excel files with results\n # Resturns a Pandas Dataframe as a table with all the outputs boxes, confidences, etc\n \n # Define output dict\n results = { 'image_filename': [],'x0':[],'y0':[],'x1':[],'y1':[],'label':[],'confidence':[] }\n # Get head of model\n yolo_outputs_ = yolo_head(model.output, anchors, len(class_names))\n input_image_shape = K.placeholder(shape=(2, ))\n # Get the database\n# Test_img_db = pd.read_csv(boxes_dir, header = 0)\n \n # Get input image size\n img=plt.imread(image_files[0])\n img_shape_ = img.shape[0:2]\n \n # Get model input size\n model_image_size = model.inputs[0].get_shape().as_list()[-3:-1]\n \n # Get the Tensors\n boxes, scores, classes = yolo_eval(yolo_outputs_, [float(i) for i in list(img_shape_)],\n max_boxes,\n score_threshold,\n iou_threshold)\n\n for image_file in image_files: # Loop over all the files\n ## Get models output\n # Preprocess your image\n image, image_data = preprocess_image(image_file, model_image_size = model_image_size )\n # Run the session with the correct tensors and choose the correct placeholders in the feed_dict.\n out_boxes, out_scores, out_classes = sess.run(\n [boxes, scores, classes],\n feed_dict={\n model.input: image_data,\n input_image_shape: [image_data.shape[2], image_data.shape[3]],\n K.learning_phase(): 0\n })\n if plot_result:\n # Plot in comparison: Detection\n # Generate colors for drawing bounding boxes.\n colors = generate_colors(class_names)\n # Draw bounding boxes on the image file\n draw_boxes(image, out_scores, out_boxes, out_classes, class_names, colors)\n # Save the predicted bounding box on the image\n image.save(os.path.join(\"out\", image_file.split('/')[-1]), quality=90)\n # Display the results in the notebook\n output_image = scipy.misc.imread(os.path.join(\"out\", image_file.split('/')[-1]))\n plt.imshow(output_image)\n plt.show()\n # control\n input(\"Press a Enter to continue...\")\n \n # Save to results AND Swap x and y dimensions: they are ok for ploting but not for submiting\n # order is x0,y0,x1,y1\n for i in range(0,out_boxes.shape[0]):\n results['image_filename'].append( image_file.split('/')[-1] )\n results['x0'].append( out_boxes[i,1] )\n results['y0'].append( out_boxes[i,0] )\n results['x1'].append( out_boxes[i,3] )\n results['y1'].append( out_boxes[i,2] )\n results['label'].append( class_names[ out_classes[i] ] )\n results['confidence'].append( out_scores[i] )\n # To Pandas and Excel\n df = pd.DataFrame(data=results)\n df=df[[ 'image_filename','x0','y0','x1','y1','label','confidence' ]]\n \n return df\ndef preprocess_true_boxes_true_box(true_boxes, anchors, image_size):\n \"\"\"Find detector in YOLO where ground truth box should appear.\n\n Parameters\n ----------\n true_boxes : array\n List of ground truth boxes in form of relative x, y, w, h, class.\n Relative coordinates are in the range [0, 1] indicating a percentage\n of the original image dimensions.\n anchors : array\n List of anchors in form of w, h.\n Anchors are assumed to be in the range [0, conv_size] where conv_size\n is the spatial dimension of the final convolutional features.\n image_size : array-like\n List of image dimensions in form of h, w in pixels.\n\n Returns\n -------\n detectors_mask : array\n 0/1 mask for detectors in [conv_height, conv_width, num_anchors, 1]\n that should be compared with a matching ground truth box.\n matching_true_boxes: array\n Same shape as detectors_mask with the corresponding ground truth box\n adjusted for comparison with predicted parameters at training time.\n \"\"\"\n height, width = image_size\n num_anchors = len(anchors)\n # Downsampling factor of 5x 2-stride max_pools == 32.\n # TODO: Remove hardcoding of downscaling calculations.\n assert height % 32 == 0, 'Image sizes in YOLO_v2 must be multiples of 32.'\n assert width % 32 == 0, 'Image sizes in YOLO_v2 must be multiples of 32.'\n conv_height = height // 32\n conv_width = width // 32\n# print(conv_width,conv_height)\n num_box_params = true_boxes.shape[1]\n detectors_mask = np.zeros(\n (conv_height, conv_width, num_anchors, 1), dtype=np.float32)\n matching_true_boxes = np.zeros(\n (conv_height, conv_width, num_anchors, num_box_params),\n dtype=np.float32)\n# print(detectors_mask.shape)\n for box in true_boxes:\n # scale box to convolutional feature spatial dimensions\n box_class = box[4:5]\n box = box[0:4] * np.array(\n [conv_width, conv_height, conv_width, conv_height])\n i = np.floor(box[1]).astype('int')\n j = np.floor(box[0]).astype('int')\n best_iou = 0\n best_anchor = 0\n for k, anchor in enumerate(anchors):\n # Find IOU between box shifted to origin and anchor box.\n box_maxes = box[2:4] / 2.\n box_mins = -box_maxes\n anchor_maxes = (anchor / 2.)\n anchor_mins = -anchor_maxes\n \n intersect_mins = np.maximum(box_mins, anchor_mins)\n intersect_maxes = np.minimum(box_maxes, anchor_maxes)\n intersect_wh = np.maximum(intersect_maxes - intersect_mins, 0.)\n intersect_area = intersect_wh[0] * intersect_wh[1]\n box_area = box[2] * box[3]\n anchor_area = anchor[0] * anchor[1]\n iou = intersect_area / (box_area + anchor_area - intersect_area)\n if iou > best_iou:\n best_iou = iou\n best_anchor = k\n\n if best_iou > 0:\n detectors_mask[i, j, best_anchor] = 1\n adjusted_box = np.array(\n [\n box[0] - j, box[1] - i,\n# np.log(box[2] / anchors[best_anchor][0]),\n# np.log(box[3] / anchors[best_anchor][1]), box_class\n box[2],\n box[3], box_class\n ],\n dtype=np.float32)\n matching_true_boxes[i, j, best_anchor] = adjusted_box\n return detectors_mask, matching_true_boxes\n","sub_path":"src/nexar_yolo_utils2.py","file_name":"nexar_yolo_utils2.py","file_ext":"py","file_size_in_byte":27719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"492454126","text":"import requests\nfrom bs4 import BeautifulSoup\n\ndef trade_spider(max_pages):\n page = 1\n while page <= max_pages:\n url = 'http://online.stepashka.com/filmy/#/page/' + str(page)\n source_code = requests.get(url) #all website code\n plain_text = source_code.text #links,images,texts from website page\n soup = BeautifulSoup(plain_text)\n for link in soup.findAll('div', {'class': 'video-title'}):\n # href = link.get('href')\n a_tag = link.a\n print(a_tag['href'])\n page += 1\n\n\ndef get_single_item_data(item_url):\n source_code = requests.get(item_url)\n plain_text = source_code.text\n soup = BeautifulSoup(plain_text)\n for item_name in soup.findAll('div', {'class' : 'alternative-title'}):\n print(item_name.string)\n for link in soup.findAll('a'):\n href = link.get('href')\n print(href)\n\n\ntrade_spider(1)\n\n","sub_path":"web2.1.py","file_name":"web2.1.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"56184289","text":"import arcade\n\n# screen dimension variables\nWIDTH = 600\nHEIGHT = 600\n\n# pacman variables\npac_x = 300\npac_y = 200\npac_rad = 20\ninit_arc_angle = 0\nfinal_arc_angle = 360\n# is pacman in contact with perimeter walls, can pacman move U,D,L,R\npac_stop = [False]*4\npac_poss_motion = [True]*4\n# pacman as a circle (0) or arc(1)\npacman_character = 1\n\n# arrow key variables\nup_pressed = False\ndown_pressed = False\nleft_pressed = False\nright_pressed = False\npac_speed_x = 0\npac_speed_y = 0\ntime = 0\n\n# maze/wall variables\nperim_wall_pos1 = 300\nperim_wall_pos2 = 20\nperim_wall_width = 600\nperim_wall_height = 40\ncurrent_wall_distance = []\n\n\ndef on_update(delta_time):\n global pacman_character, time, pac_stop\n\n wall_outer_side = pac_stop_perim()\n\n # pac_move(wall_outerside)\n\n # change pacman's outfit (open mouth to closed mouth and vice versa)\n time += delta_time\n if time > 0.075:\n if pac_stop:\n pacman_character = 0\n elif pacman_character == 0:\n pacman_character = 1\n elif pacman_character == 1:\n pacman_character = 0\n time = 0\n\n\ndef pac_move():\n global final_arc_angle, time, pacman_character, up_pressed, down_pressed, left_pressed, right_pressed, pac_x, pac_y, pac_rad, pac_speed_x, init_arc_angle\n global pac_speed_y, perim_wall_pos1, perim_wall_pos2, perim_wall_width, perim_wall_height, current_wall_distance\n global WIDTH, HEIGHT, pac_stop, pac_poss_motion\n # set pac speeds depending on keys pressed\n if up_pressed:\n pac_speed_y = 2.5\n elif down_pressed:\n pac_speed_y = -2.5\n elif left_pressed:\n pac_speed_x = -2.5\n elif right_pressed:\n pac_speed_x = 2.5\n\n for i in range(len(pac_stop)):\n if pac_stop[i] == False:\n # check if any keys are pressed and stop all other motions accordingly\n if up_pressed:\n pac_speed_x = 0\n elif down_pressed:\n pac_speed_x = 0\n\n if left_pressed:\n pac_speed_y = 0\n elif right_pressed:\n pac_speed_y = 0\n\n # else:\n # check if pacman can still move in direction pressed\n\n if pac_stop[i]:\n # do not allow pacman to move past walls\n # do not pass top\n if pac_poss_motion[0] == False:\n if pac_speed_y > 0:\n pac_speed_y = 0\n # else:\n # pac_stop =\n # do not pass bottom\n elif pac_poss_motion[1] == False:\n if pac_speed_y < 0:\n pac_speed_y = 0\n\n # do not pass left\n if pac_poss_motion[2] == False:\n if pac_speed_x < 0:\n pac_speed_x = 0\n # do not pass right\n if pac_poss_motion[3] == False:\n if pac_speed_x > 0:\n pac_speed_x = 0\n\n if up_pressed:\n init_arc_angle = 135\n final_arc_angle = 405\n elif down_pressed:\n init_arc_angle = 315\n final_arc_angle = 585\n if left_pressed:\n init_arc_angle = 225\n final_arc_angle = 495\n elif right_pressed:\n init_arc_angle = 45\n final_arc_angle = 315\n # move pacman\n pac_x += pac_speed_x\n pac_y += pac_speed_y\n\n\n\ndef pac_stop_perim():\n global final_arc_angle, time, pacman_character, up_pressed, down_pressed, left_pressed, right_pressed, pac_x, pac_y, pac_rad, pac_speed_x, init_arc_angle\n global pac_speed_y, perim_wall_pos1, perim_wall_pos2, perim_wall_width, perim_wall_height, current_wall_distance\n global WIDTH, HEIGHT, pac_stop, pac_poss_motion\n # calculate distance from pacman to base wall, it touching make him stop moving\n d_to_base = pac_y - (perim_wall_pos2 + perim_wall_height // 2 - pac_rad)\n d_to_left = pac_x - (perim_wall_pos2 + perim_wall_height // 2 - pac_rad)\n d_to_right = (perim_wall_pos1 + perim_wall_width // 2 - pac_rad) - pac_x\n d_to_top = (perim_wall_pos1 + perim_wall_width // 2 - pac_rad) - pac_y\n\n # set the pacman distance\n current_wall_distance = [0] * 4\n current_wall_distance[0] = d_to_base\n current_wall_distance[1] = d_to_left\n current_wall_distance[2] = d_to_right\n current_wall_distance[3] = d_to_top\n\n # reset variables\n # pac_poss_motion = [True]*4\n pac_stop = [False]*4\n # set the index at 4; not touching\n current_wall_index = 4\n\n # check if pacman in contact with wall, and store the wall\n if d_to_base <= pac_rad + perim_wall_height // 2:\n pac_stop[0] = True\n elif d_to_top <= pac_rad + perim_wall_height // 2:\n pac_stop[1] = True\n if d_to_left <= pac_rad + perim_wall_height // 2:\n pac_stop[2] = True\n elif d_to_right <= pac_rad + perim_wall_height // 2:\n pac_stop[3] = True\n\n # for\n\n # if touching, return values\n return pac_stop[current_wall_index]\n\n\n\ndef on_draw():\n global pac_x, pac_y, pacman_character, perim_walls, wall_dimension, WIDTH, HEIGHT\n global perim_wall_pos1, perim_wall_pos2, perim_wall_width, perim_wall_height\n arcade.start_render()\n\n # base wall\n draw_perim_walls(perim_wall_pos1, perim_wall_pos2, perim_wall_width, perim_wall_height)\n # left_wall\n draw_perim_walls(perim_wall_pos2, perim_wall_pos1, perim_wall_height, perim_wall_width)\n #top wall\n draw_perim_walls(perim_wall_pos1, HEIGHT - perim_wall_pos2, perim_wall_width, perim_wall_height)\n # right wall\n draw_perim_walls(WIDTH - perim_wall_pos2, perim_wall_pos1, perim_wall_height, perim_wall_width)\n\n # Draw pacman, alternating\n if pacman_character == 1:\n draw_pacman_open(pac_x, pac_y)\n else:\n draw_pacman_closed(pac_x, pac_y)\n\n\ndef draw_perim_walls(perim_wall_basex, perim_wall_basey, width, height):\n # draw a peremiter wall\n arcade.draw_rectangle_filled(perim_wall_basex, perim_wall_basey, width, height, arcade.color.BLUE)\n\n\ndef draw_pacman_closed(x, y):\n global pac_rad\n arcade.draw_circle_filled(x, y, pac_rad, arcade.color.YELLOW)\n\n\ndef draw_pacman_open(x, y):\n global pac_rad, init_arc_angle, final_arc_angle\n arcade.draw_arc_filled(x, y, pac_rad, pac_rad, arcade.color.YELLOW, init_arc_angle, final_arc_angle)\n\n\ndef on_key_press(key, modifiers):\n global up_pressed, down_pressed, left_pressed, right_pressed\n # create a key list\n key_pressed_list = [0] * 4\n\n # check if any key is pressed, if it is set that direction to true (move in 1 direction)\n if key == arcade.key.UP:\n up_pressed = True\n key_pressed_list[0] = 1\n elif key == arcade.key.DOWN:\n down_pressed = True\n key_pressed_list[1] = 1\n elif key == arcade.key.LEFT:\n left_pressed = True\n key_pressed_list[2] = 1\n elif key == arcade.key.RIGHT:\n right_pressed = True\n key_pressed_list[3] = 1\n key_pressed_boolean = [up_pressed, down_pressed, left_pressed, right_pressed]\n\n # turn off all keys which are not pressed, account for no on key released\n for i in range(len(key_pressed_list)):\n if key_pressed_list[i] == 0:\n key_pressed_boolean[i] = False\n up_pressed = key_pressed_boolean[0]\n down_pressed = key_pressed_boolean[1]\n left_pressed = key_pressed_boolean[2]\n right_pressed = key_pressed_boolean[3]\n\n\ndef setup():\n global WIDTH, HEIGHT, wall_rows, wall_columns, perim_walls\n arcade.open_window(WIDTH, HEIGHT, \"My Arcade Game\")\n arcade.set_background_color(arcade.color.BLACK)\n arcade.schedule(on_update, 1 / 60)\n\n # Override arcade window methods\n window = arcade.get_window()\n window.on_draw = on_draw\n window.on_key_press = on_key_press\n\n arcade.run()\n\n\nif __name__ == '__main__':\n setup()","sub_path":"Working/pac_man_final/pac_mouth_test.py","file_name":"pac_mouth_test.py","file_ext":"py","file_size_in_byte":7697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"212258496","text":"# -*- coding: utf-8 -*-\n'''\nRandom Forest classifier\n'''\n\nfrom sklearn.cluster import DBSCAN\nfrom sklearn import metrics\nfrom sklearn.preprocessing import StandardScaler\n\nfrom ...core.routes import register\nfrom .base import BaseMl\nfrom sklearn.ensemble import RandomForestClassifier\n\n@register('ml.forest')\nclass ForestMl(BaseMl):\n '''Random forest\nParameters (not implemented yet) :\nclassifier : if not specified, create a new classifier.\ndata : if not specified, get most recent data from the chain.\naction : if not specified, a new classifier will be created \n and used on available data\n if 'fit' : classifier is created but not used\n if 'predict': previous classifier is used\nUsage : \n#create clusters\nbaf.process('cluster.ward')\n#load new data\nbaf.load('data.simple',(...))\n#train classifier and use \nbaf.process('ml.forest')\n\nTODO: Allow reuse of classifiers.\n '''\n init_kwargs = ('n_estimators', 'classifier', 'data', 'action')\n run_kwargs = ()\n #max_depth\n init_method = RandomForestClassifier.__init__\n run_method = RandomForestClassifier.fit_transform\n\n def __init__(self, *args, **kwargs):\n super(ForestMl, self).__init__(*args, **kwargs)\n self.action = kwargs.get('action',None)\n\n if self.action != \"predict\":\n n_estimators = kwargs.get('n_estimators', 10)\n self.classifier = RandomForestClassifier(n_estimators=n_estimators)\n self._data['classifier'] = self.classifier\n else:\n self.classifier = None\n\n def _get_classifier(self):\n if self.classifier:\n return self.classifier\n else:\n classifier = self.get('classifier')\n self.classifier = classifier\n return classifier\n\n def fit(self, caller, *args, **kwargs):\n '''Train a classifier from tagged data'''\n classifier = self._get_classifier()\n\n vectorizer_result = caller.get('vectorizer_result')\n clusters = caller.get(\"clusterizer_result\")\n classifier.fit(vectorizer_result.toarray(), clusters)\n\n return classifier\n\n def predict(self, caller, *args, **kwargs):\n '''Use classifier on new data'''\n classifier = self._get_classifier()\n vectorizer = caller.get_chain('vectorizer')\n\n #New data\n data_source = caller.get_chain(\"data_source\")\n new_vectorizer_result = vectorizer.transform(data_source.get_data())\n\n result = self.classifier.predict(new_vectorizer_result.toarray())\n return result\n\n def run(self, caller, *args, **kwargs):\n super(ForestMl, self).run(caller,*args, **kwargs)\n\n if self.action in (None, 'fit'):\n result = self.fit(caller, *args, **kwargs)\n self.update(\n result = result,\n classifier = result\n )\n\n if self.action in (None, 'predict'):\n result = self.predict(caller, *args, **kwargs)\n self.update(\n result=result,\n classifier_result=result\n )\n\n return self\n\n\n\n","sub_path":"bakfu/classify/ml/forest.py","file_name":"forest.py","file_ext":"py","file_size_in_byte":3078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"483113793","text":"import requests\r\nimport pygal\r\nfrom pygal.style import LightColorizedStyle as LCS, LightenStyle as LS\r\n# 执行API调用并存储响应\r\n# 将响应对象存储在r中\r\nURL = 'https://api.github.com/search/repositories?q=language:python&sort=star'\r\nr = requests.get(URL)\r\n\r\n\r\n# 状态码为200表示请求成功\r\ndef get_status_code(r):\r\n \"\"\"r是一个响应对象\"\"\"\r\n return r.status_code\r\n\r\n\r\nprint(\"Status code:\", get_status_code(r))\r\nresponse_dict = r.json()\r\nprint(\"Total repositories:\", response_dict['total_count'])\r\n\r\n# 研究有关仓库的信息,所有仓库在items对应的值里,也是一个一个字典\r\nrepo_dicts = response_dict['items']\r\nprint(\"Number of items:\", len(repo_dicts))\r\nnames = [repo_dict['name'] for repo_dict in repo_dicts]\r\nstars = [repo_dict['stargazers_count'] for repo_dict in repo_dicts]\r\n\r\n# 定制图标外观(改进)\r\nmy_config = pygal.Config()\r\nmy_config.x_label_rotation = 45\r\nmy_config.show_legend = False\r\nmy_config.title_font_size = 24\r\nmy_config.label_font_size = 14 # 副标签\r\nmy_config.major_label_font_size = 18 # 主标签\r\nmy_config.truncate_label = 15 # 将较长的项目名缩短为15个字符\r\nmy_config.show_y_guides = False\r\nmy_config.width = 1000\r\n# 可视化\r\nmy_style = LS('#333366', base_style=LCS)\r\n# chart = pygal.Bar(style=my_style, x_label_rotation=45, show_legend=False)\r\nchart = pygal.Bar(my_config, style=my_style)\r\nchart.title = 'Most-Starred Python Projects on GitHub'\r\nchart.x_labels = names\r\n\r\n# 自定义工具提示标签,根据value生成高度\r\nplot_dicts = []\r\nfor repo_dict in repo_dicts:\r\n if repo_dict['description'] != None:\r\n plot_dict = {'value': repo_dict['stargazers_count'],\r\n 'label': repo_dict['description'],\r\n 'xlink': repo_dict['html_url'],\r\n }\r\n else:\r\n plot_dict = {'value': repo_dict['stargazers_count'],\r\n 'label': \"No information\",\r\n 'xlink': repo_dict['html_url'],\r\n }\r\n plot_dicts.append(plot_dict)\r\n\r\n\r\nchart.add('', plot_dicts)\r\nchart.render_to_file('python_repos.svg')","sub_path":"python_work/DataVisualizaton/API/python_repos.py","file_name":"python_repos.py","file_ext":"py","file_size_in_byte":2132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"69891277","text":"# coding:iso-8859-9 Türkçe\r\n# p_31601.py: Sıfır yoğuşmalı -3/+3 dağılımlı tesadüfi gauss histogramı örneği.\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as mp\r\n#from p_315 import Renk\r\n\r\ngaussSayıları = np.random.normal (size=10000)\r\n\r\nmp.title (\"Gauss Histogram'ı\")\r\nmp.xlabel (\"Gauss Sayıları\")\r\nmp.ylabel (\"Sayıların Tekrarlanma Sıklığı\")\r\nmp.hist (gaussSayıları)\r\n\r\nmp.show()\r\n#-------------------------------------------------------------------------------------------------------\r\n\r\nmp.style.use (\"dark_background\")\r\n\r\nmp.title (\"Gauss Histogram'ı\")\r\nmp.xlabel (\"Gauss Sayıları\")\r\nmp.ylabel (\"Sayıların Tekrarlanma Sıklığı\")\r\nn, kutular, yamalar = mp.hist (gaussSayıları)\r\n\r\nmp.show()\r\n\r\nprint (\"Y=n (kutu boyu-tekrar sıklığı) ve toplam frekans:\\n\", n, \" +=\", sum(n), sep=\"\")\r\nprint (\"\\nX=kutular:\\n\", kutular, sep=\"\")\r\nprint (\"kutular arası fark (kutu genişliği):\", (kutular [1] - kutular [0]) )\r\nprint (\"\\nyamalar:\", yamalar)\r\nfor i in range (len (yamalar)): print (\"yama[\", i, \"]: \", yamalar [i], sep=\"\")\r\n\r\n\r\n\"\"\"Çıktı:\r\n>python p_31601.py\r\nY=n (kutu boyu-tekrar sıklığı) ve toplam frekans:\r\n[ 19. 159. 639. 1844. 2871. 2518. 1393. 459. 89. 9.] +=10000.0\r\n\r\nX=kutular:\r\n[-3.64670043 -2.89409171 -2.14148299 -1.38887427 -0.63626555 0.11634317\r\n 0.86895189 1.62156061 2.37416933 3.12677805 3.87938677]\r\nkutular arası fark (kutu genişliği): 0.7526087198614606\r\n\r\nyamalar: \r\nyama[0]: Rectangle(xy=(-3.6467, 0), width=0.752609, height=19, angle=0)\r\nyama[1]: Rectangle(xy=(-2.89409, 0), width=0.752609, height=159, angle=0)\r\nyama[2]: Rectangle(xy=(-2.14148, 0), width=0.752609, height=639, angle=0)\r\nyama[3]: Rectangle(xy=(-1.38887, 0), width=0.752609, height=1844, angle=0)\r\nyama[4]: Rectangle(xy=(-0.636266, 0), width=0.752609, height=2871, angle=0)\r\nyama[5]: Rectangle(xy=(0.116343, 0), width=0.752609, height=2518, angle=0)\r\nyama[6]: Rectangle(xy=(0.868952, 0), width=0.752609, height=1393, angle=0)\r\nyama[7]: Rectangle(xy=(1.62156, 0), width=0.752609, height=459, angle=0)\r\nyama[8]: Rectangle(xy=(2.37417, 0), width=0.752609, height=89, angle=0)\r\nyama[9]: Rectangle(xy=(3.12678, 0), width=0.752609, height=9, angle=0)\r\n\"\"\"","sub_path":"Bernd Klein (520) ile Python/p_31601.py","file_name":"p_31601.py","file_ext":"py","file_size_in_byte":2232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"163658034","text":"try:\n from django.conf.urls import patterns, url\nexcept ImportError:\n from django.conf.urls.defaults import patterns, url\n\n\nurlpatterns = patterns('',\n url(r'^$', 'cropduster.views.index', name='cropduster-index'),\n url(r'^crop/', 'cropduster.views.crop', name='cropduster-crop'),\n url(r'^upload/', 'cropduster.views.upload', name='cropduster-upload'),\n url(r'^standalone/', 'cropduster.standalone.views.index', name='cropduster-standalone'),\n)\n","sub_path":"cropduster/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"97757247","text":"import tornado.web\nimport tornado.httpserver\nimport tornado.ioloop\n\nimport tornado.options\n\nimport handler.realtime_plant_performance_handler as RealtimePlantHandler\nimport handler.realtime_plant_turbine_handler as RealtimeAllTurbineHandler\nimport handler.realtime_u2_turbine_handler as RealtimeU2TuebineHandler\nimport handler.RedisInfoMonitor_handler as RedisHandler\n\nclient = list() \n \nclass aboutHandler(tornado.web.RequestHandler):\n\n def get(self):\n self.render(\"about.html\") \n\nclass Application(tornado.web.Application):\n def __init__(self):\n handlers = [\n (r\"/\", RealtimePlantHandler.realtimeHandler), \n (r\"/realtime_plant_turbine/\", RealtimeAllTurbineHandler.realtimeHandler),\n (r\"/realtime_u2_turbine/\", RealtimeU2TuebineHandler.realtimeHandler),\n \n (r\"/RedisInfoMonitor/\", RedisHandler.RedisInfoHandler),\n (r\"/about/\", aboutHandler)\n ]\n \n settings = {\n 'template_path': 'templates',\n 'static_path': 'static'\n }\n tornado.web.Application.__init__(self, handlers, **settings)\n\nif __name__ == '__main__':\n tornado.options.parse_command_line()\n \n app = Application()\n server = tornado.httpserver.HTTPServer(app)\n server.listen(8000)\n tornado.ioloop.IOLoop.instance().start()\n \n\n","sub_path":"ReadExcelData/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"49114188","text":"'''\n*********************************************************************************************\n** PNOPrequest.py **\n** PREQUESTS ** \n** ** \n** Created by raech on 09/07/19. **\n*********************************************************************************************\n'''\n####################\n## User Variables ##\n####################\nuseKami = False\nuseFallLegit = True\nuseSI = False\nonlyKanna = False\n\n# God Mod Options\nuseGM = False\n#\"Full God Mode\"\n#\"30 Sec God Mode\"\n#\"Guard God Mode\"\ngmType = \"30 Sec God Mode\"\n\n# Virtual Key Codes\n# http://nehe.gamedev.net/article/msdn_virtualkey_codes/15009/\n# Q Key\npotionKey = 0x51\nautoAttackKey = 0x41\n# A key\n\n# Auto Pot (if you dont want to use godMode)\n# 2020013 = Reinder Milk\npotionID = 2020013\n\n# Auto ATK for the Heroes\nkannaID = 80011049\nayameID = 80011070\nhayatoID = 80011036\n\n# Mr Ali Option\nuseAli = False\n\n#############################################\n# if you feel some timers are a bit fast/slow, change these (seconds)\ntalkTime = 3\nteleportTime = 1\nwalkTime = 1\nquestTime = 2\nrushTime = 10\ndropTime = 2\nfckingCancerQuest = 30\n\ndebugMSG = False\n#############################################\nsendPacket = True\nsendHeader = 0x42D\nrecvHeader = 0x528\n\ndef SendingPacket():\n for reactor in Field.GetReactors():\n if reactor.valid:\n oPacket = Packet.COutPacket(sendHeader)\n oPacket.Encode4(int(reactor.oid)) \n Packet.SendPacket(oPacket)\n iPacket = Packet.WaitForRecv(recvHeader, 1000)\n\n############################################################################################################################\n######################################## Don't Touch Below #################################################################\n############################################################################################################################\n\nimport Character\nimport Field\nimport Inventory\nimport Quest\nimport Npc\nimport Terminal\nimport time\nimport GameState\nimport Key\nimport Packet\nimport Party\n\ndef EnterPortal(pos, enter=True):\n _map = Field.GetID()\n _portal = Field.FindPortal(pos)\n _char = Character.GetPos()\n\n if not (_portal.x - 10 < _char.x < _portal.x + 10) or not (_portal.y - 5 < _char.y < _portal.y +5):\n Character.Teleport(_portal.x, _portal.y)\n time.sleep(teleportTime)\n \n if enter:\n Character.EnterPortal()\n\n time.sleep(teleportTime)\n\ndef MoveToNpc(id, limit=False):\n _npc = Field.FindNpc(id)\n _char = Character.GetPos()\n\n if limit:\n npcDistance = 2\n else:\n npcDistance = 500\n\n if not (_npc.x - npcDistance < _char.x < _npc.x + npcDistance):\n # too far i assume? test this distance\n Character.Teleport(_npc.x, _npc.y)\n time.sleep(teleportTime)\n \n time.sleep(teleportTime)\n\ndef QuestCompleted(id):\n if Quest.GetQuestState(id) != 2:\n return False\n else:\n return True\n\ndef QuestStage(id):\n if Quest.GetQuestState(id) == 1:\n return 1\n elif Quest.GetQuestState(id) == 0:\n return -1\n else:\n print(\"something wrong with \", id)\n return 0\n\ndef QuestInProgress(quest, npc):\n if Quest.CheckCompleteDemand(quest, npc) != 0:\n return True\n else:\n return False\n\ndef StartingQuest(quest, npc):\n if QuestStage(quest) < 0:\n _npc = Field.FindNpc(npc)\n if _npc.valid:\n MoveToNpc(npc)\n \n if debugMSG:\n print(\"Started Quest: \", quest)\n Quest.StartQuest(quest, npc)\n time.sleep(questTime)\n\ndef CompletingQuest(quest, npc, map):\n if not QuestCompleted(quest):\n _map = Field.GetID()\n _npc = Field.FindNpc(npc)\n if _map != map:\n #Terminal.Rush(map)\n #time.sleep(rushTime)\n if debugMSG:\n print(\"wrongmap\")\n else:\n if _npc.valid:\n MoveToNpc(npc)\n if debugMSG:\n print(\"Completed Quest: \", quest)\n Quest.CompleteQuest(quest, npc)\n time.sleep(questTime)\n\n# Terminal Toggles\ndef TerminalATK(flag, quest=False):\n if not quest:\n if useSI:\n Terminal.SetCheckBox(\"Skill Injection\", flag)\n else:\n Terminal.SetCheckBox(\"Auto Attack\", flag)\n else:\n Terminal.SetCheckBox(\"Skill Injection\", False)\n Terminal.SetCheckBox(\"General FMA\", False)\n Terminal.SetCheckBox(\"Full Map Attack\", False)\n Terminal.SetCheckBox(\"Melee No Delay\", False)\n Terminal.SetCheckBox(\"Auto Attack\", flag)\n\n if useKami:\n Terminal.SetCheckBox(\"Kami Vac\", flag)\n elif useFallLegit:\n Terminal.SetCheckBox(\"Legit Vac\", flag)\n Terminal.SetCheckBox(\"Mob Falldown\", flag)\n if flag:\n _left = Field.GetRect().left\n _right = Field.GetRect().right\n _mid = (_left + _right) / 2\n if not (_mid -10 < Character.GetPos().x < _mid + 10):\n Character.AMoveX(int(_mid))\n time.sleep(walkTime)\n\n# Prequest\n# Hieizan Temple -> Regards, Takeda Shingen\ndef CheckQuestMap(mapid, forward=True):\n TerminalATK(False)\n _map = Field.GetID()\n momijigaoka = 807000000\n fieldmap1 = 811000001\n fieldmap2 = 811000004\n fieldmap3 = 811000006\n \n if _map != mapid and forward:\n if _map != momijigaoka and (_map < 811000000 or _map > 811000010):\n print(\"Moving to Momijigaoka\")\n Terminal.Rush(momijigaoka)\n elif _map == momijigaoka:\n Terminal.StopRush()\n EnterPortal(\"west00\")\n elif _map == fieldmap1:\n Terminal.StopRush()\n EnterPortal(\"out02\")\n elif _map == fieldmap2:\n Terminal.StopRush()\n EnterPortal(\"out01\")\n elif _map == fieldmap2+1:\n Terminal.StopRush()\n EnterPortal(\"out01\")\n \n elif _map != mapid and not forward:\n if _map != momijigaoka and (_map < 811000000 or _map > 811000010):\n print(\"Moving to Momijigaoka\")\n Terminal.Rush(momijigaoka)\n elif _map == fieldmap1:\n Terminal.StopRush()\n EnterPortal(\"out00\")\n elif _map == fieldmap2:\n Terminal.StopRush()\n EnterPortal(\"out00\")\n elif _map == fieldmap2+1:\n Terminal.StopRush()\n EnterPortal(\"out00\")\n elif _map == fieldmap3:\n Terminal.StopRush()\n EnterPortal(\"out00\")\n \ndef Hieizan(_map):\n takeda = 9130102\n mouri = 9130008\n ayame = 9130103\n sakuno = 9130104\n\n momijigaoka = 807000000\n\n q1 = 58901\n q2 = q1 + 1\n q3 = q2 + 1\n q4 = q3 + 4\n q5 = q4 + 1\n q6 = q5 + 1\n q7 = q6 + 1\n q8 = q7 + 1\n q9 = q8 + 2\n\n if not QuestCompleted(q1):\n TerminalATK(False)\n mapid = 811000001\n CheckQuestMap(mapid)\n StartingQuest(q1, takeda)\n CompletingQuest(q1, takeda, mapid)\n \n if not QuestCompleted(q2) and QuestCompleted(q1):\n mapid = 811000001\n CheckQuestMap(mapid)\n StartingQuest(q2, takeda)\n itemid = 4034126\n if QuestInProgress(q2, takeda): # and Inventory.GetItemCount(itemid) < 30:\n TerminalATK(True)\n else:\n TerminalATK(False)\n CompletingQuest(q2, takeda, mapid)\n\n if not QuestCompleted(q3) and QuestCompleted(q2):\n itemid = 4009286\n StartingQuest(q3, takeda)\n if QuestInProgress(q3, takeda):\n if Inventory.GetItemCount(itemid) < 20:\n mapid = 811000004\n CheckQuestMap(mapid)\n TerminalATK(True)\n else:\n mapid = 811000006\n TerminalATK(False)\n CheckQuestMap(mapid)\n if _map == mapid:\n if (Character.GetPos().x != -8) and Character.GetPos().y != -628:\n Character.Teleport(-8, -628)\n time.sleep(teleportTime)\n else:\n questItem = Inventory.FindItemByID(itemid)\n if questItem.valid:\n TerminalATK(False)\n for x in range(20):\n Inventory.SendChangeSlotPositionRequest(4, questItem.pos, 0, 1)\n time.sleep(dropTime)\n SendingPacket()\n if not QuestInProgress(q3, takeda):\n break;\n mapid = 811000001\n CheckQuestMap(mapid, False)\n else:\n mapid = 811000001\n herbid = 4034128\n if Inventory.GetItemCount(herbid) > 0:\n CheckQuestMap(mapid, False)\n else:\n CheckQuestMap(mapid)\n StartingQuest(q3, takeda)\n CompletingQuest(q3, takeda, mapid)\n\n if not QuestCompleted(q4) and QuestCompleted(q3):\n mapid = 811000001\n if _map > mapid:\n CheckQuestMap(mapid, False)\n StartingQuest(q4, takeda)\n time.sleep(questTime)\n CheckQuestMap(momijigaoka, False)\n CompletingQuest(q4, mouri, momijigaoka)\n elif QuestCompleted(q4):\n if _map == momijigaoka:\n EnterPortal(\"west00\")\n\n if not QuestCompleted(q5) and QuestCompleted(q4):\n StartingQuest(q5, ayame)\n\n if not QuestCompleted(q6) and QuestCompleted(q5):\n StartingQuest(q6, sakuno)\n\n if not QuestCompleted(q7) and QuestCompleted(q6):\n StartingQuest(q7, ayame)\n\n if not QuestCompleted(q8) and QuestCompleted(q7):\n StartingQuest(q8, ayame)\n CompletingQuest(q8, ayame, _map)\n\n if not QuestCompleted(q9) and QuestCompleted(q8):\n StartingQuest(q9, ayame)\n\ndef CheckInstanceMap(mapid, dir, forward=True):\n _map = Field.GetID()\n entrance = 811000014\n field1 = 811000098\n field2 = 811000097\n down1 = 811000015\n down2 = down1 + 1\n down3 = down2 + 1\n well1 = down3 + 1\n\n templeEntrance = 811000019\n boss1 = 811000020\n\n nBossEntry = 811000025\n nBoss1 = nBossEntry + 1\n nBoss2 = nBoss1 + 1\n nBoss3 = nBoss2 + 2\n\n lastBossEntry = nBossEntry + 3\n\n if _map != mapid:\n if dir != \"momi\":\n Terminal.StopRush()\n\n if forward:\n if _map == entrance and dir == \"up\":\n EnterPortal(\"out01\")\n if _map == field1 and dir == \"up\":\n EnterPortal(\"out01\")\n if _map == entrance and dir == \"down\":\n EnterPortal(\"out02\")\n if _map == down1 and dir == \"down\":\n EnterPortal(\"out01\")\n if _map == down2 and dir == \"down\":\n EnterPortal(\"out01\")\n if _map == down3 and dir == \"down\":\n EnterPortal(\"out01\")\n if _map == templeEntrance and dir == \"mid\":\n EnterPortal(\"in00\")\n if _map == entrance and dir == \"right\":\n EnterPortal(\"out02\")\n if _map == down1 and dir == \"right\":\n EnterPortal(\"out01\")\n if _map == down2 and dir == \"right\":\n EnterPortal(\"out01\")\n if _map == down3 and dir == \"right\":\n EnterPortal(\"out01\")\n if _map == templeEntrance-1 and dir == \"right\":\n EnterPortal(\"out01\")\n if _map == templeEntrance and dir == \"right\":\n EnterPortal(\"out01\")\n if _map == templeEntrance+1 and dir == \"right\":\n EnterPortal(\"out01\")\n if _map == boss1+1 and dir == \"right\":\n EnterPortal(\"out01\")\n if _map == nBossEntry and dir == \"right\":\n EnterPortal(\"out01\")\n if _map == lastBossEntry and dir == \"right\":\n EnterPortal(\"in00\")\n else:\n if _map == field1 and dir == \"up\":\n EnterPortal(\"out00\")\n if _map == field2 and dir == \"up\":\n EnterPortal(\"out00\")\n if _map == down1 and dir == \"down\":\n EnterPortal(\"out00\")\n if _map == down2 and dir == \"down\":\n EnterPortal(\"out00\")\n if _map == down3 and dir == \"down\":\n EnterPortal(\"out00\")\n if _map == boss1 and dir == \"mid\":\n EnterPortal(\"out00\")\n if _map == nBoss3 and dir == \"mid2\":\n EnterPortal(\"out00\")\n if _map == nBoss2 and dir == \"mid2\":\n EnterPortal(\"out00\")\n if _map == nBoss1 and dir == \"mid2\":\n EnterPortal(\"out00\")\n\n \n\n# Kanna Ring\ndef KannaRing(_map, hero):\n dcMap = 811000013\n momijigaoka = 807000000\n childMap = 811000014\n ayameMap = 811000008\n\n child = 9130107\n child2 = child + 1\n ayame = 9130103\n princess = 9130116\n gourdid = 2432732\n qAyame = 58916\n\n if hero == \"kanna\":\n q1 = 58941\n q2 = q1 + 1\n q3 = q2 + 1\n q4 = q3 + 1\n q5 = q4 + 1\n q6 = q5 + 1\n q7 = q6 + 1\n q8 = 58963\n q9 = q8 + 1\n q10 = 58965\n q11 = q10 + 1\n q12 = q11 + 1\n q13 = q12 + 1\n elif hero == \"hayato\":\n q1 = 58928\n q2 = q1 + 1\n q3 = q2 + 1\n q4 = q3 + 1\n q5 = q4 + 1\n q6 = q5 + 1\n q7 = q6 + 1\n q8 = q7 + 1\n q9 = q8 + 1\n q10 = 58937\n q11 = q10 + 1\n q12 = q11 + 1\n q13 = q12 + 1\n elif hero == \"ayameHero\":\n q1 = 58914\n q2 = 58915\n q3 = 58917\n q4 = 58918\n q5 = 58919\n q6 = 58920\n q7 = q6 + 1\n q8 = q7 + 1\n q9 = q8 + 1\n q10 = q9 + 1\n q11 = q10 + 1\n q12 = q11 + 1\n q13 = q12 + 1\n\n\n if _map == momijigaoka:\n TerminalATK(False, True)\n EnterPortal(\"west00\")\n elif _map == dcMap:\n TerminalATK(False, True)\n EnterPortal(\"out00\")\n elif _map == ayameMap:\n TerminalATK(False, True)\n gourd = Inventory.FindItemByID(gourdid)\n if not gourd.valid:\n MoveToNpc(ayame)\n Npc.ClearSelection()\n time.sleep(talkTime)\n #Character.TalkToNpc(ayame)\n time.sleep(talkTime)\n Npc.RegisterSelection('Talk to Ayame.')\n time.sleep(talkTime)\n Character.TalkToNpc(ayame)\n #Npc.RegisterSelection('Metamorph')\n Npc.RegisterSelection('Receive another Metamorph Potion')\n time.sleep(talkTime)\n else:\n Npc.ClearSelection()\n Inventory.UseItem(gourdid)\n if hero == \"kanna\":\n Npc.RegisterSelection('Kanna')\n if hero == \"hayato\":\n Npc.RegisterSelection('Hayato')\n if hero == \"ayameHero\":\n Npc.RegisterSelection('Ayame')\n elif _map == 811000099:\n #bug might be here\n bugQuest = 58913\n if QuestStage(bugQuest) < 0:\n print('hi')\n StartingQuest(bugQuest, ayame)\n else:\n TerminalATK(False, True)\n print(\"setting up skills\")\n if useGM:\n Terminal.SetCheckBox(gmType, True)\n if not useAli and not useGM:\n Key.Set(potionKey, 2, potionID)\n time.sleep(teleportTime)\n if hero == \"hayato\":\n Key.Set(autoAttackKey, 1, hayatoID)\n if hero == \"kanna\":\n Key.Set(autoAttackKey, 1, kannaID)\n if hero == \"ayameHero\":\n Key.Set(autoAttackKey, 1, ayameID)\n time.sleep(teleportTime)\n EnterPortal(\"out00\")\n else:\n if not QuestCompleted(q1):\n mapid = 811000098\n StartingQuest(q1, child)\n if QuestInProgress(q1, child):\n if Character.GetPos().x != 91:\n Character.Teleport(91, 62)\n time.sleep(teleportTime)\n else:\n if sendPacket:\n print(\"sending packet\")\n SendingPacket()\n\n else:\n CompletingQuest(q1, child, childMap)\n\n if not QuestCompleted(q2) and QuestCompleted(q1):\n if hero == \"ayameHero\" and QuestCompleted(q2):\n if debugMSG:\n print('we should be fcking done hre')\n else:\n if not QuestCompleted(q2) and not QuestCompleted(qAyame):\n StartingQuest(q2, child)\n if hero == \"ayameHero\" and not QuestCompleted(qAyame):\n #StartingQuest(q2, child)\n StartingQuest(qAyame, child)\n if QuestInProgress(qAyame, child):\n mapid = 811000098\n if _map != mapid:\n CheckInstanceMap(mapid, \"up\")\n else:\n TerminalATK(True, True)\n else:\n mapid = childMap\n TerminalATK(False, True)\n CheckInstanceMap(childMap, \"up\", False)\n if _map == childMap:\n CompletingQuest(qAyame, child, _map)\n else:\n if QuestInProgress(q2, child) and hero != \"ayameHero\":\n mapid = 811000098\n if _map != mapid:\n CheckInstanceMap(mapid, \"up\")\n else:\n TerminalATK(True, True)\n else:\n if hero != \"ayameHero\":\n TerminalATK(False, True)\n CheckInstanceMap(childMap, \"up\", False)\n if _map == childMap:\n CompletingQuest(q2, child, childMap)\n\n if hero == \"ayameHero\":\n q2 = qAyame\n if not QuestCompleted(q3) and QuestCompleted(q2):\n StartingQuest(q3, child)\n if QuestInProgress(q3, child):\n mapid = 811000098\n if _map != mapid:\n CheckInstanceMap(mapid, \"up\")\n else:\n TerminalATK(True, True)\n else:\n TerminalATK(False, True)\n CheckInstanceMap(childMap, \"up\", False)\n CompletingQuest(q3, child, childMap)\n\n if not QuestCompleted(q4) and QuestCompleted(q3):\n StartingQuest(q4, child)\n if QuestInProgress(q4, child):\n mapid = 811000015\n if _map != mapid:\n CheckInstanceMap(mapid, \"down\")\n else:\n TerminalATK(True, True)\n else:\n TerminalATK(False, True)\n CheckInstanceMap(childMap, \"down\", False)\n CompletingQuest(q4, child, childMap)\n\n if not QuestCompleted(q5) and QuestCompleted(q4) and QuestCompleted(q3):\n StartingQuest(q5, child)\n if QuestInProgress(q5, child):\n mapid = 811000016\n if _map != mapid:\n CheckInstanceMap(mapid, \"down\")\n else:\n TerminalATK(True, True)\n else:\n TerminalATK(False, True)\n CheckInstanceMap(childMap, \"down\", False)\n CompletingQuest(q5, child, childMap)\n\n if not QuestCompleted(q6) and QuestCompleted(q5):\n StartingQuest(q6, child)\n if QuestInProgress(q6, child):\n mapid = 811000017\n if _map != mapid:\n CheckInstanceMap(mapid, \"down\")\n else:\n TerminalATK(True, True)\n else:\n TerminalATK(False, True)\n CheckInstanceMap(childMap, \"down\", False)\n CompletingQuest(q6, child, childMap)\n\n if not QuestCompleted(q7) and QuestCompleted(q6):\n TerminalATK(False, True)\n StartingQuest(q7, child)\n if QuestInProgress(q7, child):\n mapid = 811000018\n CheckInstanceMap(mapid, \"down\")\n CompletingQuest(q7, child2, mapid)\n\n if not QuestCompleted(q8) and QuestCompleted(q7):\n StartingQuest(q8, child2)\n if QuestInProgress(q8, child2):\n mapid = 811000018\n CheckInstanceMap(mapid, \"down\")\n if _map == mapid:\n if Character.GetPos().x != 87:\n Character.Teleport(87, 62)\n else:\n if sendPacket:\n print(\"sending packet\")\n SendingPacket()\n\n if not QuestCompleted(q9) and QuestCompleted(q8):\n if Party.IsInParty():\n Party.LeaveParty()\n mapid = 811000020\n StartingQuest(q9, 0)\n if QuestInProgress(q9, 0):\n CheckInstanceMap(mapid, \"mid\")\n if _map == mapid:\n if len(Field.GetMobs()) > 0:\n TerminalATK(True, True)\n else:\n TerminalATK(False, True)\n else:\n CompletingQuest(q9, 0, mapid)\n CheckInstanceMap(mapid-1, \"mid\", False)\n\n if not QuestCompleted(q10) and QuestCompleted(q9):\n mapid = 811000021\n StartingQuest(q10, 0)\n StartingQuest(58950, 0) # extra quest somehow\n if QuestInProgress(q10, 0):\n CheckInstanceMap(mapid, \"right\")\n \n if not QuestCompleted(q11) and QuestCompleted(q10):\n mapid = 811000025\n StartingQuest(q11, 0)\n if QuestInProgress(q11, 0):\n CheckInstanceMap(mapid, \"right\")\n if len(Field.GetMobs()) > 0:\n TerminalATK(True, True)\n else:\n TerminalATK(False, True)\n else:\n CompletingQuest(q11, 0, mapid)\n\n if not QuestCompleted(q12) and QuestCompleted(q11):\n mapid = 811000025\n boss1 = mapid + 1\n boss2 = boss1 + 1\n boss3 = boss2 + 2\n if _map == mapid:\n EnterPortal(\"in00\")\n elif _map == boss1:\n if len(Field.GetMobs()) > 0:\n TerminalATK(True, True)\n else:\n TerminalATK(False, True)\n EnterPortal(\"next00\")\n elif _map == boss2:\n if len(Field.GetMobs()) > 0:\n TerminalATK(True, True)\n else:\n TerminalATK(False, False)\n EnterPortal(\"next00\")\n elif _map == boss3:\n StartingQuest(q12, princess)\n\n if not QuestCompleted(q13) and QuestCompleted(q12):\n mapid = 811000025\n lastTemp = 811000028\n lastDest = 811000033\n StartingQuest(q13, 0)\n if QuestInProgress(q13, 0):\n if _map != mapid and _map != lastTemp and _map != lastDest:\n CheckInstanceMap(mapid, \"mid2\", False)\n if (_map == mapid or _map == lastTemp) and _map != lastDest:\n CheckInstanceMap(lastDest, \"right\")\n if _map == lastDest:\n if len(Field.GetMobs()) > 0:\n TerminalATK(True, True)\n else:\n TerminalATK(False, True)\n else:\n TerminalATK(False, True)\n if _map == lastDest and Character.GetPos().x != -147:\n Character.Teleport(-147, -195)\n time.sleep(teleportTime)\n else:\n if _map != lastDest:\n CheckInstanceMap(lastDest, \"right\")\n else:\n if sendPacket:\n print(\"sending packet\")\n SendingPacket()\n\n CompletingQuest(q13, 0, lastDest)\n\n\n# Main Loop\ndef Main():\n if GameState.IsInGame() and not Terminal.IsRushing() and not Terminal.IsSolvingRune():\n hieizanLastQuest = 58913\n ayame = 9130103\n princess = ayame + 1\n \n kannaring = 1113155\n hayatoshoulder = 1152171\n ayametreasure = 1132275\n\n _map = Field.GetID()\n if not QuestCompleted(hieizanLastQuest-2) and QuestInProgress(hieizanLastQuest, ayame):\n Hieizan(_map)\n else:\n if onlyKanna:\n if Inventory.GetItemCount(kannaring) == 0:\n KannaRing(_map, \"kanna\")\n else:\n print('we are done')\n else:\n if Inventory.GetItemCount(kannaring) > 0 and Inventory.GetItemCount(hayatoshoulder) == 0:\n KannaRing(_map, \"hayato\")\n elif Inventory.GetItemCount(kannaring) > 0 and Inventory.GetItemCount(hayatoshoulder) > 0 and Inventory.GetItemCount(ayametreasure) == 0:\n KannaRing(_map, \"ayameHero\")\n elif Inventory.GetItemCount(kannaring) == 0:\n KannaRing(_map, \"kanna\")\n else:\n # pno quest line\n if Inventory.GetItemCount(4034142) > 0:\n if not QuestCompleted(hieizanLastQuest):\n CompletingQuest(hieizanLastQuest, ayame, _map)\n else:\n if not QuestCompleted(58950):\n CompletingQuest(58950, princess, _map)\n print(\"we're done here\")\n\n\nMain()","sub_path":"PrincessNoRing.py","file_name":"PrincessNoRing.py","file_ext":"py","file_size_in_byte":26006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"162162158","text":"from __future__ import print_function\nimport math\nfrom decimal import *\n\ngetcontext().prec = 300\n\n\ndef S(n):\n if n == Decimal(0):\n return Decimal(0)\n nn = ((Decimal(2).sqrt() - Decimal(1)) * Decimal(n)).quantize(\n Decimal(0), rounding=ROUND_FLOOR)\n return n * nn + (n * (n + Decimal(1))) // Decimal(2) - (\n nn * (nn + Decimal(1))) // Decimal(2) - S(nn)\n\n\nANS = [0] * 100000\n\n\ndef solution(s):\n return format(S(Decimal(s)), '.0f')\n\n\nif __name__ == \"__main__\":\n print(solution(\"77\"))\n print(solution(\"5\"))\n # for i in range(100):\n # print(solution(str(10**i)))\n","sub_path":"foo.bar-2019/dodge-the-lasers.py","file_name":"dodge-the-lasers.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"176313010","text":"keys = [1,2,3,4,5,6,7,8,9]\nprint(\"keys:\",keys)\ninputlist = []\nfor i in range(0, 11):\n n=i+1\n item = int(input(\"Enter element %d:\" % n))\n inputlist.append(item)\nprint(\"input list:\",inputlist)\n\ncount=[]\nfor i in keys:\n c = 0\n for j in inputlist:\n if j%i==0:\n c+=1\n count.append(c)\ndictionary = dict(zip(keys, count))\nprint(\"dictionary:\",dictionary)\n\n\n","sub_path":"pgm4.py","file_name":"pgm4.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"591579563","text":"from __future__ import unicode_literals\n# -*- coding: UTF-8 -*-\nfrom collections import Counter\nimport numpy as np\nimport copy\nimport cv2\nimport redis\nimport sys\n\n\n# 色抽出\ndef extract_color(src, hue_threshould_maximum, hue_threshould_minimum):\n hsv = cv2.cvtColor(src, cv2.COLOR_BGR2HSV)\n hue, saturation, lightness = cv2.split(hsv)\n\n if hue_threshould_minimum > hue_threshould_maximum:\n ret, hue_dest = cv2.threshold(hue, hue_threshould_minimum, 255, cv2.THRESH_BINARY)\n ret, hue_dest_inv = cv2.threshold(hue, hue_threshould_maximum, 255, cv2.THRESH_BINARY_INV)\n\n dest = cv2.bitwise_or(hue_dest, hue_dest_inv)\n\n else:\n ret, dest = cv2.threshold(hue, hue_threshould_minimum, 255, cv2.THRESH_TOZERO)\n ret, dest = cv2.threshold(dest, hue_threshould_maximum, 255, cv2.THRESH_TOZERO_INV)\n\n ret, dest = cv2.threshold(dest, 0, 255, cv2.THRESH_BINARY)\n\n return dest\n\n\n# 背景との差分取得\ndef difference(img, backimg, width):\n dst_img = copy.copy(img)\n # 背景画像との差分を算出\n img_diff = cv2.absdiff(img, backimg)\n img_diffm = cv2.threshold(img_diff, 0, 255, cv2.THRESH_BINARY)[1]\n # グレースケール変換&2値化\n gray = cv2.cvtColor(img_diffm, cv2.COLOR_BGR2GRAY)\n image = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]\n # ラベリング\n nLavels, lavelImage = cv2.connectedComponents(image)\n # ラベリング結果から0であるところは黒で塗りつぶす\n dst_img[np.where(lavelImage == 0)] = [0, 0, 0]\n return dst_img\n\n\nif __name__ == '__main__':\n database = redis.StrictRedis(host=\"localhost\", port=\"6379\", db=0)\n # cap = cv2.VideoCapture(0)\n # mirror = True\n # size = None\n hsv_color = np.array([[5, 170], [40, 20], [170, 150], [165, 145], [75, 55], [130, 110]])\n backimg = cv2.imread(\"./images/background.jpg\", 1)\n frame = cv2.imread(\"./images/image.jpg\", 1)\n height, width, channel = backimg.shape[:3]\n img_dst = difference(frame, backimg, width)\n for i in range(6):\n labels, labeled_image = cv2.connectedComponents(extract_color(img_dst, hsv_color[i][0], hsv_color[i][1]))\n label_list = list(labeled_image[labeled_image > 0].flatten())\n\n if len(label_list) == 0:\n continue\n # sys.exit('Failed to image encoding.')\n\n most_label = Counter(label_list).most_common()[0][0]\n\n vvec, hvec = (np.where(labeled_image == most_label))\n x = int(np.mean(hvec))\n y = int(np.mean(vvec))\n value = [x, y]\n database.set(\"car\" + str(i), value)\n print(\"x座標 : y座標 \" + str(database.get(\"car\" + str(i))))\n cv2.circle(frame, (int(x), int(y)), 10, (255, 255, 255))\n cv2.imshow('window', frame)\n cv2.imwrite(\"./images/result.jpg\", frame)\n cv2.imwrite(\"./images/debug.jpg\", img_dst)\n cv2.waitKey(0)\n # cap.release()\n cv2.destroyAllWindows()\n","sub_path":"sailab/capture.py","file_name":"capture.py","file_ext":"py","file_size_in_byte":2933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"584226998","text":"from commonvariables import *\r\nimport pygame\r\nimport gamegraphics\r\nimport sys\r\n\r\nclass BackgroundProperties:\r\n\tdef __init__(self, img):\r\n\t\tself.bg = img\r\n\t\tself.bg.set_alpha(50)\r\n\r\nclass TitleProperties:\r\n\tdef __init__(self):\r\n\t\tself.title = ['Better Luck Next Time!', 'You Nailed It!']\r\n\t\tself.loc = [(15,10),(30,10)]\r\n\t\tself.size = 60\r\n\t\tself.color = game_colors['red']\r\n\r\nclass ImageProperties:\r\n\tdef __init__(self, pokemon_img):\r\n\t\toriginal_size = pokemon_img.get_size()\r\n\t\tscale = 2\r\n\t\tself.exposed_img = pygame.transform.scale(pokemon_img,(original_size[0]*scale,original_size[1]*3))\r\n\t\tself.loc = (30,30)\r\n\r\nclass PokemonProperties:\r\n\tdef __init__(self, pokemonname, pokemon_type):\r\n\t\tself.name = pokemonname\r\n\t\tself.types = pokemon_type\r\n\t\tself.label = \"Type(s)\"\r\n\t\tself.name_loc = (50,45)\r\n\t\tself.label_loc = (50,55)\r\n\t\tself.label_color = game_colors['pink']\r\n\t\tself.name_color = game_colors['blue']\r\n\t\tself.type_color = game_colors['green']\r\n\t\tself.name_size = 60\r\n\t\tself.label_size = 30\r\n\r\nclass FooterProperties:\r\n\tdef __init__(self):\r\n\t\tself.msg = \"Press SPACE to continue\"\r\n\t\tself.color = game_colors['black']\r\n\t\tself.size = 30\r\n\t\tself.loc = (35,95)\r\n\r\nclass FinishScreen:\r\n\tdef __init__(self, properties):\r\n\t\tself.title_properties = TitleProperties()\r\n\t\tself.bg_properties = BackgroundProperties(properties.bg_img)\r\n\t\tself.image_properties = ImageProperties(properties.pokemon_img)\r\n\t\tself.pokemon_properties = PokemonProperties(properties.name, properties.types)\r\n\t\tself.footer_properties = FooterProperties()\r\n\t\tself.canvas = pygame.display.set_mode(SCREEN_SIZE,pygame.FULLSCREEN)\r\n\t\tself.graphics = gamegraphics.GraphicsManager()\r\n\r\n\tdef reveal(self, status):\r\n\t\tself.show_background()\r\n\t\tself.show_title(status)\r\n\t\tself.show_image()\r\n\t\tself.show_pokemon_details()\r\n\t\tself.show_footer()\r\n\t\tpygame.display.update()\r\n\t\tis_running = True\t\t\r\n\t\twhile is_running:\r\n\t\t\tfor event in pygame.event.get():\r\n\t\t\t\tif event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):\r\n\t\t\t\t\tis_running = False\r\n\t\t\t\t\tstatus = 0\r\n\t\t\t\telif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:\r\n\t\t\t\t\tis_running = False\r\n\t\treturn status\r\n\r\n\r\n\tdef show_background(self):\r\n\t\tself.canvas.fill((255,255,255))\r\n\t\tself.canvas.blit(self.bg_properties.bg,self.bg_properties.bg.get_rect())\r\n\r\n\tdef show_title(self, status):\t\r\n\t\tif status == 0:\r\n\t\t\tself.graphics.display_text(self.canvas,self.title_properties.title[0],self.title_properties.loc[0],\r\n\t\t\t\tself.title_properties.size,self.title_properties.color)\r\n\t\telse:\r\n\t\t\tself.graphics.display_text(self.canvas,self.title_properties.title[1],self.title_properties.loc[1],\r\n\t\t\t\tself.title_properties.size,self.title_properties.color)\r\n\r\n\tdef show_image(self):\r\n\t\tself.graphics.display_image(self.canvas, self.image_properties.exposed_img, self.image_properties.loc)\r\n\r\n\tdef show_pokemon_details(self):\r\n\t\tself.graphics.display_text(self.canvas, self.pokemon_properties.name, self.pokemon_properties.name_loc,\r\n\t\t\tself.pokemon_properties.name_size, self.pokemon_properties.name_color)\r\n\t\tself.graphics.display_text(self.canvas, self.pokemon_properties.label, self.pokemon_properties.label_loc,\r\n\t\t\tself.pokemon_properties.label_size, self.pokemon_properties.label_color)\r\n\t\tfor i in range(len(self.pokemon_properties.types)):\r\n\t\t\tloc = (self.pokemon_properties.label_loc[0], self.pokemon_properties.label_loc[1]+((i+1)*6))\r\n\t\t\tself.graphics.display_text(self.canvas, self.pokemon_properties.types[i], loc,\r\n\t\t\t\tself.pokemon_properties.label_size, self.pokemon_properties.type_color)\r\n\r\n\tdef show_footer(self):\r\n\t\tself.graphics.display_text(self.canvas, self.footer_properties.msg, self.footer_properties.loc,\r\n\t\t\tself.footer_properties.size, self.footer_properties.color)","sub_path":"PokemonHangman/NewCode/finish.py","file_name":"finish.py","file_ext":"py","file_size_in_byte":3744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"469868706","text":"import os\nimport inspect\nimport unittest\nimport diet\n\n# utility functions to assist with exploratory programming\ndef data_directory():\n rtn = os.path.join(os.path.dirname(os.path.abspath(inspect.getsourcefile(data_directory))), \"data\")\n assert os.path.isdir(rtn)\n return rtn\n\ndef get_file(file_name):\n rtn = os.path.join(data_directory(), file_name)\n assert os.path.exists(rtn) and os.path.isfile(rtn)\n return rtn\n\ndef per_error(x1, x2) :\n x1, x2 = map(float, (x1, x2))\n if x1 == x2: # handles both zero and both infinity\n return 0\n denominator = max(map(abs, (x1, x2)))\n if denominator == float(\"inf\"):\n return float(\"inf\")\n return (max(x1, x2) - min(x1, x2)) / denominator\n\nclass TestDiet(unittest.TestCase):\n def test_simple(self):\n dat = diet.input_schema.sql.create_tic_dat_from_sql(get_file(\"simple_data.sql\"))\n soln = diet.solve(dat)\n self.assertTrue(per_error(soln.parameters[\"Total Cost\"][\"Value\"], 11.8289) < 0.0001)\n self.assertTrue(per_error(soln.consume_nutrition[\"protein\"][\"Quantity\"], 91) < 0.0001)\n self.assertTrue(soln.buy_food[\"milk\"][\"Quantity\"] > 6)\n\n dat.foods[\"milk\"][\"Cost\"] *= 3\n soln2 = diet.solve(dat)\n self.assertTrue(soln2.parameters[\"Total Cost\"] > 1.05 * 11.8289)\n self.assertTrue(soln2.buy_food[\"milk\"][\"Quantity\"] < 0.95 * soln.buy_food[\"milk\"][\"Quantity\"])\n self.assertTrue(per_error(soln2.consume_nutrition[\"protein\"][\"Quantity\"], 91) < 0.0001)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"diet/testing/test_diet.py","file_name":"test_diet.py","file_ext":"py","file_size_in_byte":1551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"90524647","text":"import json\nimport os\nimport operator\nfrom django.http import HttpResponse\nfrom tweepy import OAuthHandler, API\nfrom slackclient import SlackClient\nfrom os import environ\nfrom django.views.decorators.csrf import csrf_exempt\n# from django.http import HttpResponse\n\noauth_token = environ.get('oauth_token', None)\nbot_oauth_token = environ.get('bot_oauth_token', None)\nslack_client = SlackClient(oauth_token)\nslack_bot = SlackClient(bot_oauth_token)\n\n\ndef get_trending():\n consumer_key = environ.get('consumer_key', None)\n consumer_secret = environ.get('consumer_secret', None)\n access_token = environ.get('access_token', None)\n access_token_secret = environ.get('access_token_secret', None)\n\n auth = OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(access_token, access_token_secret)\n api = API(auth)\n\n woe_id = 1\n trends = api.trends_place(woe_id)\n\n trends = json.loads(json.dumps(trends, indent=1))\n trend_temp = []\n for trend in trends[0][\"trends\"]:\n trend_temp.append((trend[\"name\"]))\n\n trending = ', \\n'.join(trend_temp[:10])\n return trending\n\n\ndef get_channel(request):\n ch_event = json.loads(request.body)\n channel = ch_event['event']['channel']\n event_text = ch_event['event']['text']\n if \"trend\" in event_text or \"twitter\" in event_text:\n slack_bot.api_call(\n \"chat.postMessage\",\n channel=channel,\n text=get_trending(),\n icon_emoji=':robot_face:'\n )\n else:\n slack_bot.api_call(\n \"chat.postMessage\",\n channel=channel,\n text=\"Sorry your request cannot be processed\",\n icon_emoji=':robot_face:'\n )\n\n return \"\"\n\n\n@csrf_exempt\ndef slack(request):\n req = json.loads(request.body)\n token = req['token']\n if os.environ.get(\"verification_token\") == token:\n get_channel(request)\n # challenge = req['challenge']\n else:\n word = \"\"\n # challenge = \"wala\"\n\n return HttpResponse(request)\n # return HttpResponse(challenge, content_type=\"text/plain\")\n","sub_path":"hello/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"493172646","text":"import requests\r\nimport json\r\n\r\nurl = 'https://reqres.in/api/users/2'\r\n\r\nfile = open('C:\\\\Users\\\\Arman\\\\PycharmProjects\\\\requests\\\\file\\\\createUser.json')\r\njson_input = file.read()\r\njson_request = json.loads(json_input)\r\nresponse = requests.put(url, json_request)\r\nprint(response, ' - ', response.content)\r\n\r\n\r\n","sub_path":"apiTesting/PutUser.py","file_name":"PutUser.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"645357425","text":"class Solution(object):\n def diffWaysToCompute(self, input):\n \"\"\"\n :type input: str\n :rtype: List[int]\n \"\"\"\n res = []\n \n for i in range(len(input)):\n if input[i] in \"0123456789\":\n continue \n \n sign = input[i]\n leftRes = self.diffWaysToCompute(input[:i])\n rightRes = self.diffWaysToCompute(input[i+1:])\n for j in range(len(leftRes)):\n for k in range(len(rightRes)):\n if sign == '-':\n res.append(leftRes[j]-rightRes[k])\n elif sign == '+':\n res.append(leftRes[j]+rightRes[k])\n else:\n res.append(leftRes[j]*rightRes[k])\n\n if not res: #input is digit\n return [int(input)]\n return res\n","sub_path":"Different-Ways-to-Add-Parentheses.py","file_name":"Different-Ways-to-Add-Parentheses.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"514530933","text":"X = int(input())\nline=1\nwhile line {i}\")\n\n ***Second way\n for i in range(len(user_str)):\n print(f\"{user_str[i]} ==> {i} \")\n\n'''\nuser_str = input(\"Enter Your String: \")\nindex = 0\nfor i in user_str:\n print(f\"{i} ==> {index}\")\n index = index + 1\n\n\n\n \n \n \n\n","sub_path":"Loop_Pass_Break_Continue/Real_time_use_case.py","file_name":"Real_time_use_case.py","file_ext":"py","file_size_in_byte":2647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"410091518","text":"#! /usr/bin/env python\n\nfrom __future__ import print_function\n\nfrom PyQt4 import QtGui, QtCore, uic\nfrom OpenGL.GLUT import *\nfrom optparse import OptionParser\n\nimport os, sys\nimport Shader\n\nclass ShaderTest(QtGui.QMainWindow):\n def __init__(self,vertexFile,fragmentFile,uniforms,textures):\n QtGui.QMainWindow.__init__(self)\n uic.loadUi('ShaderTest.ui', self) \n self.show()\n\n self.glWidget.vertexFile = vertexFile\n self.glWidget.fragmentFile = fragmentFile\n# if uniforms is not None:\n if uniforms:\n self.glWidget.uniformFile = uniforms\n if textures:\n self.glWidget.textureFile = textures\n self.glWidget.initializeGL()\n\n\n\nif __name__ == '__main__': \n parser = OptionParser()\n parser.add_option(\"-s\",\"--shader\",action=\"store\",type=\"string\",dest=\"shader\") \n parser.add_option(\"-f\",\"--fragment\", action=\"store\", type=\"string\", dest=\"fragment\")\n parser.add_option(\"-v\",\"--vertex\", action=\"store\", type=\"string\",dest=\"vertex\")\n parser.add_option(\"-c\",\"--compile\", action=\"store\", type=\"string\",dest=\"compile\")\n parser.add_option(\"-u\",\"--uniforms\", action=\"store\", \n type=\"string\",dest=\"uniforms\",default=\"\")\n parser.add_option(\"-t\",\"--textures\", action=\"store\", \n type=\"string\",dest=\"textures\",default=\"\")\n \n (options, args) = parser.parse_args()\n\n if options.compile is not None:\n print(Shader.getShader(options.compile,set(options.compile)))\n exit()\n\n\n app = QtGui.QApplication(['ShaderTest'])\n glutInit(sys.argv)\n \n vertex = options.vertex\n fragment = options.fragment \n \n if options.shader is not None: \n vertex = options.shader+\".vert\"\n fragment = options.shader+\".frag\"\n\n window = ShaderTest(vertex,fragment,options.uniforms,options.textures)\n window.setGeometry(0,0,512,512)\n window.show()\n sys.exit(app.exec_())\n\n","sub_path":"src/proto/ShaderTest.py","file_name":"ShaderTest.py","file_ext":"py","file_size_in_byte":1797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"150293365","text":"import redis\nfrom django.contrib.sessions.backends.base import SessionBase, CreateError\n\nfrom establishment.misc.settings_with_default import SettingsWithDefault\n\nsettings = SettingsWithDefault(\"REDIS_CONNECTION_SESSION\",\n HOST=\"localhost\",\n PORT=6379,\n SOCKET_TIMEOUT=0.2,\n RETRY_ON_TIMEOUT=True,\n DB=0,\n PASSWORD=None,\n PREFIX=\"session\",\n UNIX_DOMAIN_SOCKET_PATH=None,\n URL=None,\n POOL=None,\n SENTINEL_LIST=None,\n SENTINEL_MASTER_ALIAS=None\n )\n\n\nclass RedisConnectionType:\n SENTINEL = \"sentinel\"\n URL = \"url\"\n HOST = \"host\"\n UNIX_SOCKET = \"unix_socket\"\n\n\nclass RedisConnection:\n _redis_cache = {}\n\n def __init__(self, session_key):\n self.session_key = session_key\n self.connection_key = \"\"\n self.settings = settings\n\n if settings.SENTINEL_LIST is not None:\n self.connection_type = RedisConnectionType.SENTINEL\n else:\n if settings.POOL is not None:\n server_key, server = self.get_server(session_key, settings.POOL)\n self.connection_key = str(server_key)\n self.settings = SettingsWithDefault(fallback_settings=settings)\n\n if settings.URL is not None:\n self.connection_type = RedisConnectionType.URL\n elif settings.HOST is not None:\n self.connection_type = RedisConnectionType.HOST\n elif settings.UNIX_DOMAIN_SOCKET_PATH is not None:\n self.connection_type = RedisConnectionType.UNIX_SOCKET\n\n self.connection_key += self.connection_type\n\n @staticmethod\n def get_server(key, servers_pool):\n \"\"\"\n Assign a redis server pseudo-randomly, proportionally to server weights,\n consistently producing the same result for the same key.\n :param key:\n :param servers_pool:\n :return:\n \"\"\"\n total_weight = sum([server.get(\"weight\", 1) for server in servers_pool])\n\n import hashlib\n position = int(hashlib.sha256(key).hexdigest(), 16) % total_weight\n\n partial_weight_sum = 0\n for server_key, server in enumerate(servers_pool):\n current_weight = server.get(\"weight\", 1)\n if partial_weight_sum <= position < (partial_weight_sum + current_weight):\n return server_key, server\n partial_weight_sum += current_weight\n\n return server_key, server\n\n def create_connection(self):\n settings = self.settings\n\n if self.connection_type == RedisConnectionType.SENTINEL:\n from redis.sentinel import Sentinel\n return Sentinel(\n settings.SENTINEL_LIST,\n socket_timeout=settings.SOCKET_TIMEOUT,\n retry_on_timeout=settings.RETRY_ON_TIMEOUT,\n db=getattr(settings, \"db\", 0),\n password=getattr(settings, \"password\", None)\n ).master_for(settings.SENTINEL_MASTER_ALIAS)\n\n if self.connection_type == RedisConnectionType.URL:\n return redis.StrictRedis.from_url(settings.URL, socket_timeout=settings.SOCKET_TIMEOUT)\n\n if self.connection_type == RedisConnectionType.HOST:\n return redis.StrictRedis(\n host=settings.HOST,\n port=settings.PORT,\n socket_timeout=settings.SOCKET_TIMEOUT,\n retry_on_timeout=settings.RETRY_ON_TIMEOUT,\n db=settings.DB,\n password=settings.PASSWORD\n )\n\n if self.connection_type == RedisConnectionType.UNIX_SOCKET:\n return redis.StrictRedis(\n unix_socket_path=settings.UNIX_DOMAIN_SOCKET_PATH,\n socket_timeout=settings.SOCKET_TIMEOUT,\n retry_on_timeout=settings.RETRY_ON_TIMEOUT,\n db=settings.DB,\n password=settings.PASSWORD,\n )\n\n def get(self):\n if self.connection_key not in self._redis_cache:\n self._redis_cache[self.connection_key] = self.create_connection()\n\n return self._redis_cache[self.connection_key]\n\n\nclass UselessByteWrapper(str):\n def __init__(self, bytes):\n self.bytes = bytes\n\n def encode(self, encoding, errors=None):\n return self.bytes\n\n\nclass SessionStore(SessionBase):\n def __init__(self, session_key=None):\n super().__init__(session_key)\n self.server = RedisConnection(session_key).get()\n\n @classmethod\n def clear_expired(cls):\n # Redis already has expiration built-in\n pass\n\n def load(self):\n try:\n self._get_or_create_session_key()\n session_data = self.server.get(self.get_redis_key_name())\n return self.decode(session_data.decode(\"utf-8\"))\n except Exception as e:\n self._session_key = None\n return {}\n\n def exists(self, session_key=None):\n return self.server.exists(self.get_redis_key_name(session_key))\n\n def create(self):\n for _ in range(5):\n self._session_key = self._get_new_session_key()\n\n try:\n self.save(must_create=True)\n except CreateError:\n # Key wasn't unique. Try again.\n continue\n self.modified = True\n return\n\n raise RuntimeError(\"Failed to create key\")\n\n def save(self, must_create=False):\n # Make sure the session key exists\n self._get_or_create_session_key()\n\n if must_create and self.exists(self._get_or_create_session_key()):\n raise CreateError\n\n data = self.encode(self._get_session(no_load=must_create))\n\n self.server.setex(self.get_redis_key_name(), self.get_expiry_age(), data)\n\n def delete(self, session_key=None):\n try:\n self.server.delete(self.get_redis_key_name(session_key))\n except:\n pass\n\n def get_redis_key_name(self, session_key=None):\n \"\"\"\n Return the key name in redis, adding the prefix if it exists\n @return string\n \"\"\"\n session_key = session_key or self._session_key\n prefix = settings.PREFIX and (settings.PREFIX + \":\")\n return (prefix or \"\") + session_key\n","sub_path":"session/redis_session.py","file_name":"redis_session.py","file_ext":"py","file_size_in_byte":6524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"338324310","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n# @Author: vasezhong\r\n# @Date: 2017-01-10 15:37:10\r\n# @Last Modified by: vasezhong\r\n# @Last Modified time: 2017-01-12 13:14:10\r\n\r\nts = 0.1\r\nepoch = 166\r\nchannel_num = 3 # 1 # set 3 when using vgg-face\r\nface_size = 224 # 128 # set 224 when using vgg-face\r\ngpu_id = 0 # set -1 to use cpu mode\r\nbatch_size = 1\r\nfeature_size = 4096 # 256 # set 4096 when using vgg-face\r\nexts = [\".jpg\", \".png\"]\r\n\r\nextractor = 'vgg_face' # 'lightened_cnn' # set vgg_face when using vgg-face\r\n\r\n# innerEyesAndBottomLip # outerEyes # innerEyesAndNoseAndLipCorner # outerEyesAndNose\r\nlandmarks = 'innerEyesAndBottomLip'\r\nmodel_prefix = r'../model/lightened_cnn/lightened_cnn_gpu'\r\ndlib_model_file = r'../model/dlib/shape_predictor_68_face_landmarks.dat'\r\n\r\nmean_val = [129.1863, 104.7624, 93.5940] # mean value (b, g, r)\r\nvgg_model_def = r'../model/vgg_face_caffe/VGG_FACE_deploy.prototxt'\r\nvgg_model_weights = r'../model/vgg_face_caffe/VGG_FACE.caffemodel'\r\n","sub_path":"identification/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"328996511","text":"import numpy\n\n\ndef sigmoid(x):\n # Функция активации sigmoid:: f(x) = 1 / (1 + e^(-x))\n return 1 / (1 + numpy.exp(-x))\n\n\ndef deriv_sigmoid(x):\n # Производная от sigmoid: f'(x) = f(x) * (1 - f(x))\n fx = sigmoid(x)\n return fx * (1 - fx)\n\n\ndef mse_loss(y_true, y_pred):\n # y_true и y_pred являются массивами numpy с одинаковой длиной\n return ((y_true - y_pred) ** 2).mean()\n\n\nclass OurNeuralNetwork:\n\n def __init__(self):\n # Вес\n self.w1 = numpy.random.normal()\n self.w2 = numpy.random.normal()\n self.w3 = numpy.random.normal()\n self.w4 = numpy.random.normal()\n self.w5 = numpy.random.normal()\n self.w6 = numpy.random.normal()\n\n # Смещения\n self.b1 = numpy.random.normal()\n self.b2 = numpy.random.normal()\n self.b3 = numpy.random.normal()\n\n def feedforward(self, x):\n h1 = sigmoid(self.w1 * x[0] + self.w2 * x[1] + self.b1)\n h2 = sigmoid(self.w3 * x[0] + self.w4 * x[1] + self.b2)\n o1 = sigmoid(self.w5 * h1 + self.w6 * h2 + self.b3)\n return o1\n\n def train(self, data, all_y_trues):\n\n learn_rate = 0.9\n itteration = 2000\n\n for epoch in range(itteration):\n for x, y_true in zip(data, all_y_trues):\n\n sum_h1 = self.w1 * x[0] + self.w2 * x[1] + self.b1\n h1 = sigmoid(sum_h1)\n\n sum_h2 = self.w3 * x[0] + self.w4 * x[1] + self.b2\n h2 = sigmoid(sum_h2)\n\n sum_o1 = self.w5 * h1 + self.w6 * h2 + self.b3\n o1 = sigmoid(sum_o1)\n y_pred = o1\n\n # --- Подсчет частных производных\n\n d_L_d_ypred = -2 * (y_true - y_pred)\n\n # Нейрон o1\n d_ypred_d_w5 = h1 * deriv_sigmoid(sum_o1)\n d_ypred_d_w6 = h2 * deriv_sigmoid(sum_o1)\n d_ypred_d_b3 = deriv_sigmoid(sum_o1)\n\n d_ypred_d_h1 = self.w5 * deriv_sigmoid(sum_o1)\n d_ypred_d_h2 = self.w6 * deriv_sigmoid(sum_o1)\n\n # Нейрон h1\n d_h1_d_w1 = x[0] * deriv_sigmoid(sum_h1)\n d_h1_d_w2 = x[1] * deriv_sigmoid(sum_h1)\n d_h1_d_b1 = deriv_sigmoid(sum_h1)\n\n # Нейрон h2\n d_h2_d_w3 = x[0] * deriv_sigmoid(sum_h2)\n d_h2_d_w4 = x[1] * deriv_sigmoid(sum_h2)\n d_h2_d_b2 = deriv_sigmoid(sum_h2)\n\n # --- Обновлние веса и смещения\n # Нейрон h1\n self.w1 -= learn_rate * d_L_d_ypred * d_ypred_d_h1 * d_h1_d_w1\n self.w2 -= learn_rate * d_L_d_ypred * d_ypred_d_h1 * d_h1_d_w2\n self.b1 -= learn_rate * d_L_d_ypred * d_ypred_d_h1 * d_h1_d_b1\n\n # Нейрон h2\n self.w3 -= learn_rate * d_L_d_ypred * d_ypred_d_h2 * d_h2_d_w3\n self.w4 -= learn_rate * d_L_d_ypred * d_ypred_d_h2 * d_h2_d_w4\n self.b2 -= learn_rate * d_L_d_ypred * d_ypred_d_h2 * d_h2_d_b2\n\n # Нейрон o1\n self.w5 -= learn_rate * d_L_d_ypred * d_ypred_d_w5\n self.w6 -= learn_rate * d_L_d_ypred * d_ypred_d_w6\n self.b3 -= learn_rate * d_L_d_ypred * d_ypred_d_b3\n\n # общая потеря в конце каждой фазы\n if epoch % 10 == 0:\n y_preds = numpy.apply_along_axis(self.feedforward, 1, data)\n loss = mse_loss(all_y_trues, y_preds)\n # print(\"Epoch %d loss: %.3f\" % (epoch, loss))\n\n\ndata = [\n [-5, -5], # 60 кг 165 см\n [7, 12], # 72 кг 180 см\n [3, 7], # 68 кг 177 см\n [-11, -18] # 54 кг 152 см\n]\n\nall_y_trues = [\n 1, # ж\n 0, # м\n 0, # м\n 1, # ж\n]\n\nnetwork = OurNeuralNetwork()\ndef retrain(data,all_y_trues):\n network.train(data, all_y_trues)\n print(data)","sub_path":"neural_network.py","file_name":"neural_network.py","file_ext":"py","file_size_in_byte":4016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"454001180","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nimport torch.optim as optim\n\n\ndef squared_l2_norm(x):\n flattened = x.view(x.unsqueeze(0).shape[0], -1)\n return (flattened ** 2).sum(1)\n\n\ndef l2_norm(x):\n return squared_l2_norm(x).sqrt()\n\n\ndef car_trades_loss(model,\n x_natural,\n y,\n idx,\n contrast_idx,\n criterion_car,\n optimizer,\n car_beta,\n step_size=0.003,\n epsilon=0.031,\n perturb_steps=10,\n trades_beta=1.0,\n distance='l_inf',\n tol=10e-8):\n\n # define KL-loss\n criterion_kl = nn.KLDivLoss(reduction='sum')\n model.eval()\n batch_size = len(x_natural)\n norm = distance.split('_')[1]\n\n # random start\n delta = torch.rand_like(x_natural) * 2 * epsilon - epsilon\n if distance != 'l_inf': # projected into feasible set if needed\n normVal = torch.norm(delta.view(batch_size, -1), int(norm), 1)\n normVal = torch.max(normVal, torch.ones_like(norm) * 1e-6)\n mask = normVal <= epsilon\n scaling = epsilon / normVal\n scaling[mask] = 1\n delta = delta * scaling.view(batch_size, 1, 1, 1)\n\n x_adv = x_natural.detach() + delta.detach()\n\n # PGD with KL loss\n for _ in range(perturb_steps):\n x_adv.requires_grad_(True)\n with torch.enable_grad():\n _, logit_adv = model(x_adv)\n _, logit_natural = model(x_natural)\n loss_kl = criterion_kl(F.log_softmax(logit_adv, dim=1),\n F.softmax(logit_natural, dim=1))\n updates = torch.autograd.grad(loss_kl, [x_adv])[0]\n if distance == 'l_inf':\n updates = torch.sign(updates)\n else:\n normVal = torch.norm(updates.view(batch_size, -1), int(norm), 1)\n normVal = torch.max(normVal, torch.ones_like(norm) * 1e-6)\n updates = updates / normVal.view(batch_size, 1, 1, 1)\n\n updates = updates * step_size\n x_adv = x_adv.detach() + updates.detach()\n\n # projection\n delta = x_adv - x_natural\n if distance == 'l_inf':\n delta = torch.clamp(delta, -epsilon, epsilon)\n else:\n normVal = torch.norm(delta.view(batch_size, -1), int(norm), 1)\n normVal = torch.max(normVal, torch.ones_like(norm) * 1e-6)\n mask = normVal <= epsilon\n scaling = epsilon / normVal\n scaling[mask] = 1\n delta = delta * scaling.view(batch_size, 1, 1, 1)\n\n x_adv = torch.clamp(x_natural+delta, 0.0, 1.0)\n\n model.train()\n x_adv = Variable(torch.clamp(x_adv, 0.0, 1.0), requires_grad=False)\n\n # zero gradient\n optimizer.zero_grad()\n # calculate robust loss\n feats_adv, logit_adv = model(x_adv)\n feats_natural, logit_natural = model(x_natural)\n loss_natural = F.cross_entropy(logit_natural, y)\n\n loss_robust = (1.0 / batch_size) * criterion_kl(F.log_softmax(logit_adv, dim=1),\n F.softmax(logit_natural, dim=1))\n loss_car = criterion_car(feats_natural, feats_adv, idx, contrast_idx)\n loss = loss_natural + trades_beta * loss_robust + car_beta * loss_car\n return loss, loss_natural, loss_robust, loss_car\n","sub_path":"car_trades.py","file_name":"car_trades.py","file_ext":"py","file_size_in_byte":3366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"258973993","text":"list1=[]\nn = int(input(\"enter number of elements: \"))\nfor i in range(n):\n list1.append(input(\"Enter number: \"))\nprint(list1)\nitem = input(\"Enter the element to be removed :\")\nwhile(True):\n if item in list1:\n list1.remove(item)\n print(list1)\n break\n else:\n print(\"Item does not exist\")\n item = input(\"Enter the element to be removed :\")\n","sub_path":"TM-2/List/8.py","file_name":"8.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"394691061","text":"class Solution:\n \"\"\"\n @param matrix: matrix, a list of lists of integers\n @param target: An integer\n @return: a boolean, indicate whether matrix contains target\n \"\"\"\n def searchMatrix(self, matrix, target):\n # write your code here\n if matrix == [] or matrix == [[]]:\n return False\n start, end = 0, len(matrix)-1\n\n while start + 1 < end:\n mid = (start + end) // 2\n if target < matrix[mid][0]:\n end = mid\n elif target > matrix[mid][-1]:\n start = mid \n elif matrix[mid][0] <= target <= matrix[mid][-1]:\n end = mid \n \n if target in matrix[start] or target in matrix[end]:\n return True\n return False\n","sub_path":"3Binary_Search/28. Search a 2D Matrix.py","file_name":"28. Search a 2D Matrix.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"51449139","text":"# Copyright (c) 2021.\n# Chunyan Zhang\n\nimport numpy as np\nfrom nltk.tokenize import TweetTokenizer\nfrom wordsegment import segment, load\nimport pandas as pd\nimport re, pickle, os\nimport random\nimport logging\n# K-fold splits\nfrom sklearn.model_selection import train_test_split\n\nlogging.basicConfig(level=logging.INFO, filename=\"log.txt\",\n format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(funcName)s - %(levelname)s: %(message)s')\nprint(\"log is saving into log.txt ...\")\n\ndata_path = \"C:/cyzhang/project/twitter_projects/Twitter-Occupation-Prediction/Twi_data/\"\nuser_label_data_csv_file = data_path + 'known_user_label_2.jsonl'\nraw_data_pkl_file = './data/crawled_data.pkl'\nsplit_data_file = './data/crawled_data_splits.pkl'\n\nnum_splits = 10\n\nfrom config import dir_name, vaccine_file_list\n\n################################################################################\n############################ Create training data ##############################\n################################################################################\nimport ast\n\ndef generate_label_tweets():\n if os.path.isfile(raw_data_pkl_file):\n return\n\n tweet_dict = {}\n for line in open(user_label_data_csv_file, 'r', encoding='utf-8'):\n record = ast.literal_eval(line)\n tweet_dict[record['id']] = [record['label_3class'], record['description'], record['name']]\n\n with open(raw_data_pkl_file, 'wb') as fp:\n pickle.dump(tweet_dict, fp)\n\n\n################################################################################\n############################## Text Preprocessing ##############################\n################################################################################\ndef text_preprocess(text, tknzr):\n FLAGS = re.MULTILINE | re.DOTALL\n # Different regex parts for smiley faces\n eyes = r\"[8:=;]\"\n nose = r\"['`\\-]?\"\n\n # function so code less repetitive\n def re_sub(pattern, repl):\n return re.sub(pattern, repl, text, flags=FLAGS)\n\n text = re_sub(r\"https?:\\/\\/\\S+\\b|www\\.(\\w+\\.)+\\S*\", \"\")\n text = re_sub(r\"/\", \" / \")\n text = re_sub(r\"@\\w+\", \"\")\n text = re_sub(r\"{}{}[)dD]+|[)dD]+{}{}\".format(eyes, nose, nose, eyes), \"\")\n text = re_sub(r\"{}{}p+\".format(eyes, nose), \"\")\n text = re_sub(r\"{}{}\\(+|\\)+{}{}\".format(eyes, nose, nose, eyes), \"\")\n text = re_sub(r\"{}{}[\\/|l*]\".format(eyes, nose), \"\")\n text = re_sub(r\"<3\", \"\")\n text = re_sub(r\"[-+]?[.\\d]*[\\d]+[:,.\\d]*\", \"\")\n text = re_sub(r\"([!?.]){2,}\", r\"\\1 \")\n text = re_sub(r\"\\b(\\S*?)(.)\\2{2,}\\b\", r\"\\1\\2 \")\n text = re_sub(r\"#\\S+\", lambda hashtag: \" \".join(segment(hashtag.group()[1:]))) # segment hastags\n\n tokens = tknzr.tokenize(text.lower())\n return \" \".join(tokens)\n\n\ndef concat_data():\n path = os.path.dirname(os.path.abspath(__file__)) + \"/data/\"\n with open(raw_data_pkl_file, \"rb\") as f:\n id2entities = pickle.load(f)\n\n ########## Lookup Tables ##########\n labels = sorted(list(set([entity[0] for entity in id2entities.values()])))\n num_classes = len(labels)\n\n label_lookup = np.zeros((num_classes, num_classes), int)\n np.fill_diagonal(label_lookup, 1)\n ###################################\n\n text_data, context_data, label_data = [], [], []\n label_dict = {}\n for i, label in enumerate(labels):\n label_dict[label] = i\n\n load()\n tknzr = TweetTokenizer(reduce_len=True, preserve_case=False, strip_handles=False)\n print(\"Preprocessing tweets.....\")\n for _id in id2entities:\n if id2entities[_id][0] in label_dict.keys():\n text_data.append(text_preprocess(id2entities[_id][1], tknzr))\n context_data.append(text_preprocess(id2entities[_id][2], tknzr))\n\n label_data.append(label_lookup[label_dict[id2entities[_id][0]]])\n\n assert len(text_data) == len(context_data) == len(label_data)\n\n return text_data, context_data, label_data\n\n\n################################################################################\n############################## K-fold Data Split ###############################\n################################################################################\ndef kfold_splits(text_data, context_data, label_data, k):\n kfold_text, kfold_context, kfold_label = [], [], []\n for i in range(k):\n _text_data = {\"train\": {}, \"valid\": {}, \"test\": {}}\n _context_data = {\"train\": {}, \"valid\": {}, \"test\": {}}\n _label_data = {\"train\": {}, \"valid\": {}, \"test\": {}}\n kfold_text.append(_text_data)\n kfold_context.append(_context_data)\n kfold_label.append(_label_data)\n\n random_state = np.random.randint(0, 10000)\n from sklearn.model_selection import StratifiedKFold\n kf = StratifiedKFold(n_splits=k, shuffle=True, random_state=random_state)\n # kf = KFold(n_splits=k, shuffle=True, random_state=0)\n\n kfold_index = 0\n for rest_index, test_index in kf.split(text_data, np.array(label_data)[:, 0]):\n train_index, valid_index, _, _ = train_test_split(rest_index, np.zeros_like(rest_index), test_size=0.05)\n\n kfold_text[kfold_index][\"train\"] = [text_data[index] for index in train_index]\n kfold_text[kfold_index][\"test\"] = [text_data[index] for index in test_index]\n kfold_text[kfold_index][\"valid\"] = [text_data[index] for index in valid_index]\n\n kfold_context[kfold_index][\"train\"] = [context_data[index] for index in train_index]\n kfold_context[kfold_index][\"test\"] = [context_data[index] for index in test_index]\n kfold_context[kfold_index][\"valid\"] = [context_data[index] for index in valid_index]\n\n kfold_label[kfold_index][\"train\"] = [label_data[index] for index in train_index]\n kfold_label[kfold_index][\"test\"] = [label_data[index] for index in test_index]\n kfold_label[kfold_index][\"valid\"] = [label_data[index] for index in valid_index]\n\n assert len(kfold_text[kfold_index][\"train\"]) == len(kfold_context[kfold_index][\"train\"]) == len(\n kfold_label[kfold_index][\"train\"])\n assert len(kfold_text[kfold_index][\"valid\"]) == len(kfold_context[kfold_index][\"valid\"]) == len(\n kfold_label[kfold_index][\"valid\"])\n assert len(kfold_text[kfold_index][\"test\"]) == len(kfold_context[kfold_index][\"test\"]) == len(\n kfold_label[kfold_index][\"test\"])\n\n train_length = len(kfold_text[kfold_index][\"train\"])\n valid_length = len(kfold_text[kfold_index][\"valid\"])\n test_length = len(kfold_text[kfold_index][\"test\"])\n\n kfold_index += 1\n\n print(\"Input Data Splitted: %s (train) / %s (valid) / %s (test)\" % (train_length, valid_length, test_length))\n\n return kfold_text, kfold_context, kfold_label\n\n\ndef generate_label_tweets_ourdata():\n global raw_data_pkl_file, split_data_file\n raw_data_pkl_file = './data/our_data/crawled_data.pkl'\n split_data_file = './data/our_data/crawled_data_splits.pkl'\n if os.path.isfile(raw_data_pkl_file):\n return\n\n tweets_count = 0\n tweet_dict = {}\n for file in vaccine_file_list:\n print(\"{}\".format(file))\n logging.warning(\"{}\".format(file))\n empty_bio_count = 0\n total_count = 0\n covid_file_dir = os.path.join(dir_name, file)\n if not os.path.exists(covid_file_dir):\n print('{} not exsits.'.format(covid_file_dir))\n logging.warning('{} not exsits.'.format(covid_file_dir))\n continue\n\n tweet_file = os.path.join(dir_name, file, 'vaccine_tweets.csv')\n\n if not os.path.exists(tweet_file):\n print('{} not exsits.'.format(tweet_file))\n logging.warning('{} not exsits.'.format(tweet_file))\n continue\n\n for line in open(tweet_file, 'r', encoding='utf-8'):\n tweets_count += 1\n record = ast.literal_eval(line)\n user_id = record['includes']['users'][0]['id']\n bio = record['includes']['users'][0]['description']\n count = 0\n if user_id in tweet_dict:\n count = tweet_dict[user_id][3]+1\n tweet_dict[user_id][3] += 1\n user_id = '{}_{}'.format(user_id, count)\n\n if len(bio) == 0:\n bio = record['data']['text']\n empty_bio_count += 1\n tweet_dict[user_id] = ['label', bio, record['includes']['users'][0]['name'], count]\n total_count += 1\n print('empty bio:{}, total:{}, percent:{:.2%}'.format(empty_bio_count, total_count, empty_bio_count / total_count))\n with open(raw_data_pkl_file, 'wb') as fp:\n pickle.dump(tweet_dict, fp)\n\ndef generate_label_tweets_ourdata_origin():\n global raw_data_pkl_file, split_data_file\n raw_data_pkl_file = './data/our_data/crawled_data.pkl'\n split_data_file = './data/our_data/crawled_data_splits.pkl'\n if os.path.isfile(raw_data_pkl_file):\n return\n\n tweets_count = 0\n empty_bio_count = 0\n total_count = 0\n tweet_dict = {}\n tweet_dir = \"D:/twitter_data/origin_tweets/\"\n tweet_file_list = [\"Sampled_Stream_detail_20200715_0720_origin/twitter_sample_origin-20200715141905.csv\",\n \"Sampled_Stream_detail_20200811_0815_origin/twitter_sample_origin-20200811233217.csv\",\n \"Sampled_Stream_detail_20200914_0917_origin/twitter_sample_origin-20200916100506.csv\",\n \"Sampled_Stream_detail_20201105_1110_origin/twitter_sample_origin-20201109062630.csv\",\n \"Sampled_Stream_detail_20201210_1214_origin/twitter_sample_origin-20201214190040.csv\",\n \"Sampled_Stream_detail_20210410_0416_origin/twitter_sample_origin-20210410123126.csv\"\n ]\n tweet_file = tweet_dir + tweet_file_list[5]\n\n for line in open(tweet_file, 'r', encoding='utf-8'):\n tweets_count += 1\n record = ast.literal_eval(line)\n user_id = record['includes']['users'][0]['id']\n bio = record['includes']['users'][0]['description']\n count = 0\n if user_id in tweet_dict:\n count = tweet_dict[user_id][3]+1\n tweet_dict[user_id][3] += 1\n user_id = '{}_{}'.format(user_id, count)\n\n if len(bio) == 0:\n bio = record['data']['text']\n empty_bio_count += 1\n tweet_dict[user_id] = ['label', bio, record['includes']['users'][0]['name'], count]\n total_count += 1\n\n print('empty bio:{}, total:{}, percent:{:.2%}'.format(empty_bio_count, total_count, empty_bio_count / total_count))\n with open(raw_data_pkl_file, 'wb') as fp:\n pickle.dump(tweet_dict, fp)\n\ndef process_training_data():\n generate_label_tweets()\n _text, _ctxt, _label = concat_data()\n print(\"Splitting data into 10 folds.....\")\n _text_split, _ctxt_split, _label_split = kfold_splits(_text, _ctxt, _label, num_splits)\n\n path = os.path.dirname(os.path.abspath(__file__)) + \"/data/\"\n if not os.path.exists(path):\n os.makedirs(path)\n with open(split_data_file, \"wb\") as f:\n print(\"Creating pickle files for each split to \" + split_data_file)\n pickle.dump({\"text_data\": _text_split, \"context_data\": _ctxt_split, \"label_data\": _label_split}, f)\n\ndef process_our_data():\n text_fold0, context_fold0, label_fold0 = [], [], []\n text_fold0.append({\"train\": {}, \"valid\": {}, \"test\": {}})\n context_fold0.append({\"train\": {}, \"valid\": {}, \"test\": {}})\n label_fold0.append({\"train\": {}, \"valid\": {}, \"test\": {}})\n # 将标注数据集分为训练集和验证集\n generate_label_tweets()\n _text, _ctxt, _label = concat_data()\n from sklearn.model_selection import ShuffleSplit # or StratifiedShuffleSplit\n sss = ShuffleSplit(n_splits=1, test_size=0.1)\n train_index, val_index = next(sss.split(_text, _label))\n text_fold0[0][\"train\"] = [_text[index] for index in train_index]\n context_fold0[0][\"train\"] = [_ctxt[index] for index in train_index]\n label_fold0[0][\"train\"] = [_label[index] for index in train_index]\n text_fold0[0][\"valid\"] = [_text[index] for index in val_index]\n context_fold0[0][\"valid\"] = [_ctxt[index] for index in val_index]\n label_fold0[0][\"valid\"] = [_label[index] for index in val_index]\n\n #处理vaccine tweet用generate_label_tweets_ourdata,处理origin tweet用generate_label_tweets_ourdata_origin\n #generate_label_tweets_ourdata()\n generate_label_tweets_ourdata_origin()\n _text, _ctxt, _label = concat_data()\n text_fold0[0][\"test\"] = _text\n context_fold0[0][\"test\"] = _ctxt\n label_fold0[0][\"test\"] = _label\n\n with open(split_data_file, \"wb\") as f:\n print(\"Creating pickle files for each split to \" + split_data_file)\n pickle.dump({\"text_data\": text_fold0, \"context_data\": context_fold0, \"label_data\": label_fold0}, f)\n\nif __name__ == \"__main__\":\n #f = open('./data/our_data/crawled_data_splits.pkl', \"rb\")\n #id2entities = pickle.load(f)\n #process_training_data()\n process_our_data()","sub_path":"1. data_mining/occupation_predictor/data_preprocess.py","file_name":"data_preprocess.py","file_ext":"py","file_size_in_byte":12975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"369573124","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport subprocess\nimport socket\nfrom redis import Redis\nimport pymysql\nfrom check import config\n\n\ndef check_redis():\n \"\"\"\n 检查redis连接情况\n :return: \n \"\"\"\n ip = config.REDIS['ip']\n port = int(config.REDIS['port'])\n database = int(config.REDIS['database'])\n try:\n redis = Redis(ip, port, db=database)\n ping = redis.ping()\n if ping:\n print('check_redis : ok')\n else:\n print('check_redis : fail')\n except Exception as ex:\n print('check_redis : fail')\n print(\"error_message:\", ex)\n\n\ndef check_thrift():\n \"\"\"\n 检查thrift是否启动\n :return: \n \"\"\"\n ip = config.CORE_THRIFT['ip']\n port = int(config.CORE_THRIFT['port'])\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.settimeout(3)\n try:\n s.connect((ip, port))\n s.close()\n print('check_thrift : ok')\n except Exception as ex:\n print(\"error_message:\", ex)\n print(\"check_thrift:fail\")\n\n\ndef check_port():\n \"\"\"\n 检查端口是否正常监听\n :return: \n \"\"\"\n port = int(config.CORE_THRIFT['port'])\n command = \"netstat -anp | grep \" + str(port) + \" |awk '{print $6}' |head -1\"\n try:\n result = subprocess.getoutput(command)\n if 'LISTEN' in result:\n print('check_port : ok')\n else:\n print('check_port : fail')\n except Exception as ex:\n print(\"error_message:\", ex)\n print(\"check_thrift:\", ex)\n\n\ndef check_log_file():\n \"\"\"\n 检查日志文件是否有错误\n :return: \n \"\"\"\n log_file = config.LOG_FILE_PATH\n no_error = True\n with open(log_file, encoding='utf-8') as f:\n for line_no, line in enumerate(f):\n if '[ERROR]' in line:\n print('lineNo:{} message:{}'.format(line_no, line),end='')\n no_error = False\n break\n\n if no_error:\n print(\"check_log_file: ok\")\n else:\n print('check_log_file: fail')\n\n\ndef check_database():\n \"\"\"\n 检查数据库连接配置\n :return: \n \"\"\"\n ip = config.MYSQL['ip']\n port = int(config.MYSQL['port'])\n database = config.MYSQL['database']\n user = config.MYSQL['user']\n password = config.MYSQL['password']\n\n db = pymysql.connect(host=ip, port=port, user=user, password=password, database=database)\n try:\n cursor = db.cursor()\n cursor.execute(\"select version()\")\n print(\"check_database: ok\")\n except Exception as ex:\n print(\"error_message:\", ex)\n print(\"check_database: fail\")\n db.close()\n\n\nif __name__ == '__main__':\n check_thrift()\n check_redis()\n check_port()\n check_log_file()\n check_database()\n","sub_path":"check/prodct_check.py","file_name":"prodct_check.py","file_ext":"py","file_size_in_byte":2759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"254584280","text":"#!/usr/bin/env python\n# encoding: utf-8\n\ndef trailingZeros(n):\n res = 0\n a = 5\n while a < n:\n res += (n // a)\n a *= 5\n return res\n\n\nif __name__ == \"__main__\":\n print(trailingZeros(29))\n","sub_path":"Yao/factorial.py","file_name":"factorial.py","file_ext":"py","file_size_in_byte":214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"66019458","text":"import logging\nimport requests\n\nfrom django.conf import settings\nlog = logging.getLogger(__name__)\n\n\ndef _get_json(response):\n try:\n return response.json()\n except:\n return {}\n\n\nclass PlpApiClient(object):\n \"\"\"\n API client for communication with PLP.\n Checks that settings are setup, otherwise logs errors\n Returns data for supported actions\n \"\"\"\n def __init__(self):\n self.base_url = getattr(settings, \"PLP_URL\", None)\n self.api_key = getattr(settings, \"PLP_API_KEY\", None)\n if self.base_url is None or self.api_key is None:\n self._request = self._dummy\n\n def normalize_url(self, url, lms_url):\n if url.startswith(\"http://\") or url.startswith(\"https://\"):\n return url\n return lms_url.strip(\"/\") + url\n\n def push_grade_api_result(self, path, local_csv_url, local_csv_err_url):\n \"\"\"\n Returns url with requests CSV grade sheet\n \"\"\"\n lms_url = getattr(settings, \"LMS_ROOT_URL\", None)\n if not lms_url:\n log.error(\"Undefined LMS_ROOT_URL. Can't return to PLP CSV file absolute url\")\n return\n\n data = {\"url\": self.normalize_url(local_csv_url, lms_url)}\n if local_csv_err_url:\n data[\"url_err\"] = self.normalize_url(local_csv_err_url, lms_url)\n\n return self._request(path, data)\n\n\n def push_course_user_group_changed(self, course_id, username, group_name):\n data = {}\n data['course_id'] = str(course_id)\n data['username'] = username\n data['group_name'] = group_name\n self._request('api/user-add-group', data)\n\n def _request(self, path, data):\n headers = {'x-plp-api-key': self.api_key}#, 'Content-Type': 'application/json'}\n request_url = \"{}/{}/\".format(\n self.base_url.strip(\"/\"),\n path.strip(\"/\")\n )\n plp_response = requests.post(request_url, data=data, headers=headers)\n if plp_response.ok:\n return _get_json(plp_response)\n else:\n message = \"PlpApiClient error: request ({}, {});\".format(request_url, str(data))\n message += \"response ({}, {})\".format(plp_response.status_code, _get_json(plp_response))\n log.error(message)\n return {}\n\n def _dummy(self, *args, **kwargs):\n \"\"\"\n If settings are not setup we log every attempt to call PLP\n but do nothing\n \"\"\"\n message = \"Tried to use PlpApiClient, but settings are incorrect. \" \\\n \"You have to configure PLP_URL and PLP_API_KEY to use PlpApiClient.\"\n log.error(message)\n return {}\n","sub_path":"open_edx_api_extension/api_client.py","file_name":"api_client.py","file_ext":"py","file_size_in_byte":2643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"247578035","text":"#absence.py\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@author Falko Benthin\n@Date 17.01.2014\n@brief reads and writes absence file, absent is a timestamp (int), when seheiah recognise the byebye command. Absent==0 means, the monitored person is at home \n\"\"\"\n\nimport os,time\nimport logging\nimport logdb\nimport readConfig as rc\n\nclass Absence():\n\t\n\tdef __init__(self):\n\t\tself.absenceFileName = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), rc.config.get('absencefile','absenceFile'))\n\t\t#intervals to considering in seconds\n\t\"\"\"\n\tsets absence\n\t\"\"\"\n\tdef set(self,absent):\n\t\ttry:\n\t\t\tabsenceFile = open(self.absenceFileName, \"r+\")\n\t\t\tif (absent == 0): #when home\n\t\t\t\ttry:\n\t\t\t\t\tstarttime = int(absenceFile.read())\n\t\t\t\texcept IOError:\n\t\t\t\t\tlogging.error(\"couldn't read from file\" + self.absenceFileName)\n\t\t\t\t#logging to database\n\t\t\t\tdb = logdb.logDB()\n\t\t\t\tdb.addAbsence(starttime,int(time.time()))\n\t\t\t\tdb.closeDB()\n\t\t\ttry:\n\t\t\t\tabsenceFile.seek(0)\n\t\t\t\tabsenceFile.write(str(absent))\n\t\t\t\tabsenceFile.truncate()\n\t\t\texcept IOError:\n\t\t\t\tlogging.error(\"couldn't write to file \" + self.absenceFileName)\n\t\t\tfinally:\n\t\t\t\tabsenceFile.close()\n\t\texcept IOError:\n\t\t\tlogging.error(\"couldn't open file \" + self.absenceFileName)\n\t\n\t#checks via file, if subject at home\n\tdef get(self):\n\t\ttry:\n\t\t\tabsenceFile = open(self.absenceFileName, \"r\")\n\t\t\ttry:\n\t\t\t\tabsenceValue = int(absenceFile.read())\n\t\t\texcept IOError:\n\t\t\t\tlogging.error(\"couldn't read from file\" + self.absenceFileName)\n\t\t\tfinally:\n\t\t\t\tabsenceFile.close()\n\t\texcept IOError:\n\t\t\tlogging.error(\"file \" + self.absenceFileName + \" doesn't exists\")\n\t\treturn bool(absenceValue)\n\n","sub_path":"program/absence.py","file_name":"absence.py","file_ext":"py","file_size_in_byte":1621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"186653311","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jul 30 14:22:35 2018\n\n@author: taneljoon\n\"\"\"\n\n\n# importing libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# importing data\npath = ('/Users/taneljoon/Documents/Python/Machine_Learning_udemy/'\n'Part 8 - Deep Learning/Section 39 - Artificial Neural Networks (ANN)/'\n'Churn_Modelling.csv')\ndataset = pd.read_csv(path)\n\nX = dataset.iloc[:,3:13].values # first : is that we take lines, next ho many\nY = dataset.iloc[:,13].values\n \n# categorise the data - we use the sklearn library\n# for country & sex\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\nlabelencoder_X_1 = LabelEncoder()\nX[:,1] = labelencoder_X_1.fit_transform(X[:,1])\nlabelencoder_X_2 = LabelEncoder()\nX[:,2] = labelencoder_X_2.fit_transform(X[:,2])\n# we will use dummy encoding - if is France 0/1, if is Spain 0/1\nonehotencoder = OneHotEncoder(categorical_features = [1]) # 1 is the index\nX = onehotencoder.fit_transform(X).toarray()\nX = X[:,1:]\n \n# splitting the dataset to the training set and test set\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state = 0)\n\n# Fitting the XGBoost to the training set\nfrom xgboost import XGBClassifier\nclassifier = XGBClassifier()\nclassifier.fit(X_train, Y_train)\n\n\ny_pred = classifier.predict(X_test)\n# this works better\n#for ii in range(0,len(y_pred)):\n# y_pred[ii] = round(y_pred[ii],0)\n\n# Making a confusion matrix\nfrom sklearn.metrics import confusion_matrix\ncm = confusion_matrix(Y_test, y_pred)\n\n# Applying k_fold_cross_validation\nfrom sklearn.model_selection import cross_val_score\naccuracies = cross_val_score(estimator = classifier, X = X_train, y = Y_train, cv = 10)\n# we take average of accuracies vector\naccuracies.mean()\naccuracies.std()","sub_path":"ML/xgboost.py","file_name":"xgboost.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"231804810","text":"import numpy as np\nimport cv2 as cv\nimport PIL\nfrom cv2 import aruco\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport pandas as pd\nimport os\n\ndef callback(x):\n pass\n\n\npath = os.path.join(os.getcwd(), 'camera_calibration/data/test/edited/')\n\naruco_dict = aruco.Dictionary_get(aruco.DICT_6X6_250)\ncv.namedWindow('thresh')\ncv.createTrackbar('L', 'thresh', 0, 255, callback)\ncv.createTrackbar('U', 'thresh', 0, 255, callback)\ndef generate():\n fig = plt.figure()\n nx = 4\n ny = 3\n for i in range(1, nx * ny + 1):\n ax = fig.add_subplot(ny, nx, i)\n img = aruco.drawMarker(aruco_dict, i, 700)\n plt.imshow(img, cmap=mpl.cm.gray, interpolation=\"nearest\")\n ax.axis(\"off\")\n\n plt.savefig(\"data/markers.png\")\n plt.show()\n\nsource = 0\ncapture = cv.VideoCapture(source)\nwith np.load(path + 'output/data.npz') as file:\n mtx, dist, r_m, t_m = [file[i] for i in ('mtx', 'dist', 'rotation', 'translation')]\n\nwhile capture.isOpened():\n L = cv.getTrackbarPos('L', 'thresh')\n U = cv.getTrackbarPos('U', 'thresh')\n\n retain, frame = capture.read()\n if retain:\n gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)\n ret, thresh = cv.threshold(gray, L, U, cv.THRESH_BINARY)\n\n parameters = aruco.DetectorParameters_create()\n corners, ids, rejected = aruco.detectMarkers(thresh, aruco_dict, parameters=parameters)\n\n if len(corners) > 0:\n cv.aruco.drawDetectedMarkers(frame, corners, ids)\n if ids is not None:\n rvecs, tvecs, _ = cv.aruco.estimatePoseSingleMarkers(corners, 0.1, mtx, dist, r_m, t_m)\n for i in range(len(ids)):\n cv.aruco.drawAxis(frame, mtx, dist, rvecs[i], tvecs[i], 0.1)\n\n cv.imshow('frame', frame)\n cv.imshow('thresh', thresh)\n key = cv.waitKey(1)\n if key == 27 or 0xFF == ord('q'):\n break\n\n\ncapture.release()\ncv.destroyAllWindows()","sub_path":"CV/code/opencv/aruco.py","file_name":"aruco.py","file_ext":"py","file_size_in_byte":1934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"40172255","text":"import life as m\nimport time\nimport numpy as np\n\n\nN1, N2 = 300, 300\nN = N1 * N2 // 4\n\n# initialization\n\n# using random generator in c++\n# test = m.life(N1, N2, N, 1343145)\n\n# input outside configuration\ntest = m.life(N1, N2, np.random.randint(2, size=N1 * N2))\n\n# calculate average fps\nframes = 0\n\nones = np.ones([N1 * N2])\n\nstart = time.time()\ninterval = 0\n\nwhile interval<30:\n # using 2 process, 1 by default\n test.update(2)\n img = (ones * test.getData()).reshape([N1, N2])\n frames += 1\n end = time.time()\n interval=end-start\nprint(\"average fps: \", frames / (end - start))\n","sub_path":"tests/test_noGUI.py","file_name":"test_noGUI.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"282557358","text":"import os\nimport store_db\nimport numpy as np\nimport pandas as pd\nimport data_cleansing as dc\n\n\nclass DataSet:\n def __init__(self, applications, people, jobs, views, people_skills, job_skills):\n self.cleanPath = \"./data/clean/\"\n self.name = 'final_ds'\n self.cleanCSV = self.cleanPath + self.name + \".csv\"\n self.appl = applications\n self.ppl = people\n self.jbs = jobs\n self.vws = views\n self.ppl_skls = people_skills\n self.jbs_skls = job_skills\n self.df = self.load_final_ds(self.appl, self.ppl, self.jbs, self.vws, self.ppl_skls, self.jbs_skls)\n\n def load_final_ds(self, appl, ppl, jbs, vws, ppl_skls, jbs_skls):\n if not os.path.exists(self.cleanCSV):\n self.prepare_ds(appl, ppl, jbs, vws, ppl_skls, jbs_skls)\n\n # Load the clean final_ds\n return pd.read_csv(self.cleanCSV, delimiter=',', parse_dates=True)\n\n def prepare_ds(self, appl, ppl, jbs, vws, ppl_skls, jbs_skls):\n # Merge the necessary columns and create a unique, master dataset\n # Assumption. User only applies for a job offer it has already seen. The user then chooses to apply or not.\n # In this sense, we are filtering for all the offers that have views\n\n # The Clean deduplicated jobs_views is already a pivot table of every user that saw a job offer\n final_df = vws.jobs_views_df\n final_df = final_df.drop(['page_vws', 'time_vws'], axis=1)\n final_df = final_df.drop_duplicates(['user_id_vws', 'job_id_vws'])\n\n # Line Control\n self.print_line_control(\"Base Users vs Job View\", len(final_df), 175165)\n\n # The inner join will help filter the rows in the job_views that do not have a job id, but a string or where there is no longer information on the job (149488). On some instances a company 7697 was not on the table also)\n # Using the job_views <-> ppl_views\n final_df = pd.merge(final_df, jbs.df, left_on='job_id_vws', right_on='id_jbs', how='inner')\n\n # Line Control\n self.print_line_control(\"Merged Job Info\", len(final_df), 175165)\n\n # The inner join will help filter the persons for which we have information\n # If there is no information on the person (user) then the analysis cannot be completed. Some of the users have a match if the join if by person.id. However, for user 90130 (person.id) it was created on a date after the view the user with the same id (user_id).\n # Searching the people.id with 90130 and the jobs_views.user_id with the same id. It will be possible to see inconsistent dates between the view date and the created_at date.\n # Get the ppl information, from the user_id\n # a Drop in rows is expected.\n\n # Feature engineer. Convert some of the countries to \"Other\"\n # To reduce the number of dummy variables\n\n ppl.df = ppl.country_binning()\n\n final_df = pd.merge(final_df, ppl.df, left_on='user_id_vws', right_on='user_id_ppl', how='inner')\n\n # Line Control\n # Some users do not have their user_id on the people table, nor on the people skills table.\n # As such, they will not be considered as no information can be gathered\n self.print_line_control(\"Merged User Info\", len(final_df), 171833)\n\n # Join Applications (left join) to keep the information we have in the table and avoid filtering\n # the join between the Applications and the People is by applications.person_id and people.id\n # !!Do not use the user_id here!!\n final_df = pd.merge(final_df, appl.df, left_on=['id_ppl', 'job_id_vws'], right_on=['person_id_appl', 'job_ad_id_appl'], how='left')\n\n # Line Control\n # As a user can apply for more than one job, the lines increased\n # The increment is expected\n self.print_line_control(\"Merged Applications Info\", len(final_df), 172132)\n\n # Cleanup after the Join\n final_df = final_df.drop(['id_jbs',\n 'user_id_ppl',\n 'person_id_appl',\n 'job_ad_id_appl',\n 'person_created_at_ppl',\n 'person_created_at_wkd_ppl',\n 'id_appl'],\n axis=1)\n\n # Get a table with the count of the views each user had for each job offer\n jobs_views_per_user = vws.get_job_offer_views_per_user()\n\n # Get the number of views, per user, per job id\n final_df = pd.merge(final_df, jobs_views_per_user, left_on=['job_id_vws', 'user_id_vws'], right_on=['job_id_vws', 'user_id_vws'], how='inner')\n\n # Line Control\n self.print_line_control(\"Merged User views per Job\", len(final_df), 172132)\n\n # Obtain the of users vs jobs\n match_skills = final_df.loc[:, ['job_id_vws', 'user_id_vws', 'id_ppl']]\n match_skills = match_skills.drop_duplicates()\n match_skills = pd.merge(match_skills, jbs_skls.df, left_on='job_id_vws', right_on='job_id_jb_skl', how='inner') # this will guarantee that there is always a job skill for a given job\n match_skills = pd.merge(match_skills, ppl_skls.df, left_on=['id_ppl', 'canonical_tag_id_jb_skl'], right_on=['person_id_ppl_skl', 'canonical_tag_id_ppl_skl'], how='inner')\n match_skills['count_matching_skills'] = match_skills['job_id_vws']\n match_skills = match_skills.groupby(['id_ppl', 'job_id_vws'])['count_matching_skills'].count().reset_index()\n total_job_req = jbs_skls.get_total_skills_by_job()\n\n skills_coverage = pd.merge(match_skills, total_job_req, left_on='job_id_vws', right_on='job_id_jb_skl', how='left')\n skills_coverage['total_skills_job'] = skills_coverage['canonical_tag_id_jb_skl']\n skills_coverage['skills_coverage_percent'] = (skills_coverage['count_matching_skills'] / skills_coverage['canonical_tag_id_jb_skl']) * 100\n\n final_df = pd.merge(final_df, skills_coverage, left_on=['id_ppl', 'job_id_vws'], right_on=['id_ppl', 'job_id_vws'], how='left')\n final_df = final_df.drop(['canonical_tag_id_jb_skl', 'job_id_jb_skl'], axis=1)\n\n # Line Control\n self.print_line_control(\"Merged job and ppl skills \", len(final_df), 172132)\n\n # Line Control\n self.print_line_control(\"Dropped lines without total_skills_job \", len(final_df), 172132)\n\n # Add the last seen date per user, per job\n final_df = pd.merge(final_df, vws.job_views_last_date, left_on=['job_id_vws', 'user_id_vws'], right_on=['job_id_date_vws', 'user_id_date_vws'], how='left')\n\n # Drop unnecessary columns from Jobs Last view date\n final_df = final_df.drop(['job_id_date_vws', 'user_id_date_vws', 'max_view_date_vws'], axis=1)\n\n # Replacing nan values on the categorical features with \"unknown\"\n final_df['country_code_ppl'] = final_df['country_code_ppl'].fillna('unknown')\n final_df['availability_ppl'] = final_df['availability_ppl'].fillna('unknown')\n final_df['remote_ppl'] = final_df['remote_ppl'].fillna('unknown')\n\n\n # ---------------------------------------------------------------------------------\n # THE SCORE COLUMN MUST BE THE LAST COLUMN\n # Create the score column on the dataset\n # 1 - if the user applied to a job\n # 0 - if the user did not apply for a job\n final_df['score'] = np.where(final_df['submitted_at_appl'].isnull(), 0, 1)\n\n # Line Control\n self.print_line_control(\"Table ready. \", len(final_df), 172132)\n\n # Just checking...\n final_df = dc.DataPrep.remove_dup_rows(final_df, 'final_ds')\n\n # Line Control\n self.print_line_control(\"After duplicate lines\", len(final_df), 172132)\n\n # Reset everything before going out\n final_df.reset_index(drop=True)\n sqlite = store_db.SQLite()\n final_df.to_sql('final_ds', con=sqlite.create_connection(), if_exists='replace', index=False)\n # export to CSV for easier use in the future\n final_df.to_csv(self.cleanCSV, index=False)\n\n def print_line_control(self, title, lines, expected):\n print(\"-\" * 8 + \" \" + title + \" \" + \"-\" * 8)\n if lines == expected:\n print(\"Exported \" + str(lines) + \" as expected.\")\n else:\n print(\"Lines exported: \" + str(lines) + \". Expected lines: \" + str(expected))\n if lines < expected:\n print(\"ATTENTION! Loss of lines\")\n else:\n print(\"Lines incremented\")\n","sub_path":"dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":8553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"244921922","text":"import os\nimport numpy as np\nimport tensorflow as tf\nimport time\nimport collections\nimport itertools as it\nimport random\nimport pdb\n\nclass DeepQNetwork(object):\n\n def __init__(self, lr, n_actions, name, fc1_dims=512, LSTM_DIM=256,\n input_dims=(210, 160, 4), chkpt_dir=\"tmp/dqn\"):\n self.lr = lr\n self.name = name\n config = tf.ConfigProto()\n config.gpu_options.visible_device_list = \"2,3\"\n #config.gpu_options.allow_growth = True\n #config.gpu_options.per_process_gpu_memory_fraction = 0.5\n self.LSTM_DIM = LSTM_DIM\n self.n_actions = n_actions\n self.fc1_dims = fc1_dims\n self.chkpt_dir = chkpt_dir\n self.input_dims = input_dims\n self.sess = tf.Session(config=config)\n self.build_network()\n self.sess.run(tf.global_variables_initializer())\n self.checkpoint_file = os.path.join(chkpt_dir, \"deepqnet.ckpt\")\n self.saver = tf.train.Saver(max_to_keep=100)\n self.params = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES,\n scope=self.name)\n self.write_op = tf.summary.merge_all()\n #dirname = os.path.dirname(__file__)\n #self.log = os.path.join(*[dirname, 'tmp', 'log_dir', self.name])\n #if os.path.isdir(self.log):\n # print(\"output_results: \", str(self.log))\n #else:\n #os.mkdir(self.log)\n self.make_log_dir()\n self.writer = tf.summary.FileWriter(self.log, self.sess.graph)\n\n def make_log_dir(self):\n path = '/home/azlaans/aienvs'\n self.log = os.path.join(*[path, 'test', 'tmp', 'log_dir', 'single', self.name])\n if os.path.isdir(self.log):\n print('Log_Dir exists for tensorboard summary')\n else:\n os.mkdir(self.log)\n print('Lod_Dir created for tensorboard summary', self.log)\n \n\n def build_network(self):\n\n with tf.variable_scope(self.name):\n self.states = tf.placeholder(tf.float32, shape=[None, *self.input_dims],\n name='states') \n self.actions = tf.placeholder(tf.float32, shape=[None, self.n_actions],\n name='action_taken')\n self.q_target = tf.placeholder(tf.float32, shape=[None],\n name='q_value')\n self.seq_len = tf.placeholder(tf.int32, name='sequence_length')\n self.batch_size = tf.placeholder(tf.int32, name='batch_size')\n\n # Create placeholders to input the hidden state values\n c_in = tf.placeholder(tf.float32, [None, self.LSTM_DIM], name='cell_state')\n h_in = tf.placeholder(tf.float32, [None, self.LSTM_DIM], name='h_state')\n self.state_in = tf.nn.rnn_cell.LSTMStateTuple(c_in, h_in)\n\n #self._reward = tf.placeholder(tf.float32, shape=[], name='Reward/Time_step')\n #self.reward_sum = tf.summary.scalar('Reward/Time_step', self._reward)\n\n #self._waitingtime = tf.placeholder(tf.float32, shape=[], name='TotalWaitingTime/Time_step')\n #self.waitingtime_sum = tf.summary.scalar('TotalWaitingTime/Time_step', self._waitingtime)\n\n #self._delay = tf.placeholder(tf.float32, shape=[], name='TotalDelay/Time_step')\n #self.delay_sum = tf.summary.scalar('TotalDelay/Time_step', self._delay)\n\n conv1 = tf.layers.conv2d(inputs=self.states, filters=16,\n kernel_size=(8, 8), strides=(4,4), name='conv1', padding='VALID',\n kernel_initializer=tf.contrib.layers.variance_scaling_initializer(factor=2),use_bias=True, bias_initializer=tf.constant_initializer(0.1))\n # TensorShape([Dimension(None), Dimension(44), Dimension(39), Dimension(32)])\n\n conv1_activated = tf.nn.relu(conv1)\n\n conv2 = tf.layers.conv2d(inputs=conv1_activated, filters=32,\n kernel_size=(4, 4), strides=(2,2), name='conv2', padding='VALID',\n kernel_initializer=tf.contrib.layers.variance_scaling_initializer(factor=2), use_bias=True, bias_initializer=tf.constant_initializer(0.1))\n # TensorShape([Dimension(None), Dimension(21), Dimension(18), Dimension(64)])\n\n conv2_activated = tf.nn.relu(conv2)\n\n #conv3 = tf.layers.conv2d(inputs=conv2_activated, filters=64,\n # kernel_size=(3, 3), strides=1, name='conv3',\n #kernel_initializer=tf.contrib.layers.variance_scaling_initializer(factor=2))\n #conv3_activated = tf.nn.relu(conv3)\n\n n_input = conv2_activated.get_shape().as_list()[1]*conv2_activated.get_shape().as_list()[2]*conv2_activated.get_shape().as_list()[3]\n \n conv2_activated = tf.reshape(conv2_activated, [-1, n_input])\n \n conv2_activated = tf.reshape(conv2_activated, [self.batch_size, self.seq_len, n_input])\n \n lstm_cell = tf.nn.rnn_cell.LSTMCell(self.LSTM_DIM, initializer=tf.contrib.layers.xavier_initializer())\n outputs, self.cell_state = tf.nn.dynamic_rnn(lstm_cell, conv2_activated, initial_state=self.state_in, dtype=tf.float32, sequence_length=self.seq_len)\n\n var1 = tf.get_variable('weights', (self.LSTM_DIM, self.n_actions), initializer=tf.contrib.layers.xavier_initializer(), trainable=True, \n regularizer=tf.contrib.layers.l2_regularizer(0.01))\n var2 = tf.get_variable('biases', (self.n_actions,), trainable=True, initializer=tf.constant_initializer(0.1))\n\n h = outputs[:,-1,:] \n\n self.Q_values = tf.matmul(h, var1) + var2\n tf.summary.histogram('Q_value', self.Q_values)\n\n self.q = tf.reduce_sum(tf.multiply(self.Q_values, self.actions), axis=1)\n\n self.loss = tf.reduce_mean(tf.square(self.q_target - self.q))\n \n self.loss_sum = tf.summary.scalar(\"Loss\", self.loss)\n\n self.train_op = tf.train.AdamOptimizer(self.lr).minimize(self.loss)\n\n if self.name == 'q_eval':\n for var in tf.trainable_variables():\n c = var.name[:-2]\n with tf.name_scope(c):\n self.variable_summaries(var)\n\n def variable_summaries(self, var):\n \"\"\"Attach a lot of summaries to a Tensor (for TensorBoard visualization).\"\"\"\n with tf.name_scope('summaries'):\n mean = tf.reduce_mean(var)\n tf.summary.histogram('histogram', var)\n\n def load_checkpoint(self, filename):\n print('... loading checkpoint ...')\n self.saver.restore(self.sess, filename)\n\n def save_checkpoint(self, epi_num):\n print('... Saving Checkpoint ...')\n #self.epi_num = epi_num\n #dir_name = os.path.join(self.chkpt_dir, str(self.epi_num))\n #if os.path.isdir(dir_name):\n # print(\"directory exists \", str(dirname))\n #else:\n # os.mkdir(dir_name)\n #filename = \"deepQnet_\" + str(epi_num)\n self.saver.save(self.sess, self.checkpoint_file, global_step=epi_num)\n\nclass Agent(object):\n def __init__(self, alpha, gamma, mem_size, epsilon, batch_size, num_agents, act_per_agent,\n replace_target=3000, input_dims=(210, 160, 4), q_next_dir=\"tmp/q_next\", q_eval_dir=\"tmp/q_eval\", test= False):\n self.num_agents = num_agents\n self.act_per_agent = act_per_agent\n self.input_dims = input_dims\n self.n_actions = self.act_per_agent**(self.num_agents)\n self.action_space = [i for i in range(self.act_per_agent)]\n self.gamma = gamma\n self.seq_length = 10\n self.LSTM_DIM = 256\n self.mem_size = mem_size\n self.mem_cntr = 0\n self.epsilon = epsilon\n self.batch_size = batch_size\n self.replace_target = replace_target \n \n self.q_eval = DeepQNetwork(alpha, self.n_actions, input_dims=input_dims,\n name='q_eval', chkpt_dir=q_eval_dir)\n\n #self.q_next = DeepQNetwork(alpha, self.n_actions, input_dims=input_dims,\n #name='q_next', chkpt_dir=q_next_dir)\n\n if test==False:\n self.create_memory()\n else:\n self.test_initialiser()\n \n self.all_list = []\n for j in it.product(tuple(self.action_space), repeat = self.num_agents):\n self.all_list.append(j) \n\n def create_memory(self):\n self.state_memory = np.zeros((self.mem_size, *self.input_dims)) \n self.new_state_memory = np.zeros((self.mem_size, *self.input_dims))\n self.action_memory = np.zeros((self.mem_size, self.n_actions),\n dtype=np.int8)\n self.reward_memory = np.zeros(self.mem_size)\n self.terminal_memory = np.zeros(self.mem_size, dtype=np.int8)\n c_init = np.zeros((1, self.LSTM_DIM), np.float32)\n h_init = np.zeros((1, self.LSTM_DIM), np.float32)\n self.state_out = (c_init, h_init)\n\n def action_hot_encoder(self, actions, all_list):\n action = np.zeros((self.n_actions))\n value_list = tuple(actions.values())\n for key, val in enumerate(all_list):\n if val == value_list:\n action[key] = 1.\n break\n return action\n\n def action_decoder(self, encoded_action, all_list):\n index = (list(np.where(encoded_action==1.))[0])[0]\n decoded_action = collections.OrderedDict()\n for i in range(len(encoded_action)):\n try:\n decoded_action[str(i)] = all_list[index][i]\n except:\n break\n return decoded_action\n\n def store_transition(self, state, action, reward, state_, terminal):\n index = self.mem_cntr % self.mem_size\n self.state_memory[index] = state\n self.reward = reward\n self.action_memory[index] = self.action_hot_encoder(action, self.all_list)\n self.reward_memory[index] = reward['result']\n self.new_state_memory[index] = state_\n self.terminal_memory[index] = terminal\n if self.mem_cntr >= self.mem_size:\n self.epsilon = 0.01\n \n def upgrade(self):\n self.mem_cntr +=1\n \n def choose_action(self, state):\n rand = np.random.random()\n if rand < self.epsilon:\n value_list = []\n for i in range(self.num_agents):\n value_list.append(np.random.choice(self.action_space))\n value_list = tuple(value_list)\n action = np.zeros((self.n_actions))\n for key, val in enumerate(self.all_list):\n if val == value_list:\n action[key] = 1.\n break\n action = self.action_decoder(action, self.all_list)\n else:\n actions, lstm_state = self.q_eval.sess.run([self.q_eval.Q_values, self.q_eval.cell_state],\n feed_dict={self.q_eval.states: state,\n self.q_eval.state_in: self.state_out,\n self.q_eval.seq_len: 1,\n self.q_eval.batch_size: 1})\n lstm_c, lstm_h = lstm_state\n self.state_out = (lstm_c[:1, :], lstm_h[:1, :])\n action = np.argmax(actions)\n action_ht = np.zeros((self.n_actions))\n action_ht[action] = 1. \n action = self.action_decoder(action_ht, self.all_list)\n return action\n\n def RandomSequenceSampling(self):\n batch_length = self.batch_size*self.seq_length\n state_batch = np.zeros((batch_length, *self.input_dims))\n next_state_batch = np.zeros((batch_length, *self.input_dims))\n reward_batch = []\n action_batch = []\n terminal_batch = []\n indices = np.arange(self.seq_length-1, self.mem_size)\n for b in np.arange(0, batch_length, self.seq_length):\n i = random.choice(indices)\n while (sum(self.terminal_memory[i+1-self.seq_length:i+1]) > 0 and self.terminal_memory[i] != 1):\n i = random.choice(indices)\n state_batch[b:b+self.seq_length] = self.get_sequence(i, self.state_memory)\n action_batch.append(self.action_memory[i])\n reward_batch.append(self.reward_memory[i])\n next_state_batch[b:b+self.seq_length] = self.get_sequence(i, self.new_state_memory)\n terminal_batch.append(self.terminal_memory[i])\n return state_batch, np.asarray(action_batch), np.asarray(reward_batch), next_state_batch, np.asarray(terminal_batch)\n\n def get_sequence(self, index, collection):\n stop = index + 1 \n start = stop - self.seq_length \n if start < 0 and stop >= 0:\n try:\n seq = np.vstack((collection[start:], collection[:stop]))\n except ValueError:\n seq = np.append(collection[start:], collection[:stop])\n else:\n seq = collection[start:stop]\n\n if len(seq.shape) != len(collection.shape):\n seq = np.reshape(seq, (-1,))\n return seq\n\n def learn(self):\n if self.mem_cntr % self.replace_target == 0:\n self.update_graph()\n\n state_batch, action_batch, reward_batch, next_state_batch, terminal_batch = self.RandomSequenceSampling() \n\n state = (np.zeros((self.batch_size, self.LSTM_DIM)),np.zeros((self.batch_size, self.LSTM_DIM)))\n\n q_eval = self.q_eval.sess.run(self.q_eval.Q_values,\n feed_dict={self.q_eval.states: state_batch,\n self.q_eval.state_in: state,\n self.q_eval.seq_len: self.seq_length,\n self.q_eval.batch_size: self.batch_size})\n\n q_eval_next = self.q_eval.sess.run(self.q_eval.Q_values,\n feed_dict={self.q_eval.states: next_state_batch,\n self.q_eval.state_in: state,\n self.q_eval.seq_len: self.seq_length,\n self.q_eval.batch_size: self.batch_size})\n\n index_best_action = np.argmax(q_eval_next, axis=1)\n\n q_next = self.q_next.sess.run(self.q_next.Q_values,\n feed_dict={self.q_next.states: next_state_batch,\n self.q_next.state_in: state,\n self.q_next.seq_len: self.seq_length,\n self.q_next.batch_size: self.batch_size})\n\n idx = np.arange(self.batch_size)\n q_target = reward_batch + \\\n self.gamma*(q_next[idx, index_best_action])*(1 - terminal_batch)\n \n _ = self.q_eval.sess.run(self.q_eval.train_op,\n feed_dict={self.q_eval.states: state_batch,\n self.q_eval.actions: action_batch,\n self.q_eval.q_target: q_target,\n self.q_eval.seq_len: self.seq_length,\n self.q_eval.batch_size: self.batch_size,\n self.q_eval.state_in: state,\n self.q_eval._reward: self.reward['result'],\n self.q_eval._waitingtime: self.reward['total_waiting'],\n self.q_eval._delay: self.reward['total_delay']})\n\n if self.mem_cntr % 400==0:\n summary1, _ = self.q_eval.sess.run([self.q_eval.write_op, self.q_eval.train_op],\n feed_dict={self.q_eval.states: state_batch,\n self.q_eval.actions: action_batch,\n self.q_eval.q_target: q_target,\n self.q_eval.seq_len: self.seq_length,\n self.q_eval.batch_size: self.batch_size,\n self.q_eval.state_in: state,\n self.q_eval._reward: self.reward['result'],\n self.q_eval._waitingtime: self.reward['total_waiting'],\n self.q_eval._delay: self.reward['total_delay']})\n self.q_eval.writer.add_summary(summary1)\n self.q_eval.writer.flush()\n\n def test(self, state):\n actions, lstm_state = self.q_eval.sess.run([self.q_eval.Q_values, self.q_eval.cell_state],\n feed_dict={self.q_eval.states: state,\n self.q_eval.state_in: self.state_out,\n self.q_eval.seq_len: 1,\n self.q_eval.batch_size: 1})\n lstm_c, lstm_h = lstm_state\n self.state_out = (lstm_c[:1, :], lstm_h[:1, :])\n action = np.argmax(actions)\n action_ht = np.zeros((self.n_actions))\n action_ht[action] = 1.\t\n return self.action_decoder(action_ht, self.all_list) \n\n def get_qval(self, state):\n q_values, lstm_state = self.q_eval.sess.run([self.q_eval.Q_values, self.q_eval.cell_state],\n feed_dict={self.q_eval.states: state,\n self.q_eval.state_in: self.state_out,\n self.q_eval.seq_len: 1,\n self.q_eval.batch_size: 1})\n lstm_c, lstm_h = lstm_state\n self.state_out = (lstm_c[:1, :], lstm_h[:1, :])\n return q_values\n \n def test_initialiser(self):\n c_init = np.zeros((1, self.LSTM_DIM), np.float32)\n h_init = np.zeros((1, self.LSTM_DIM), np.float32)\n self.state_out = (c_init, h_init)\n\n def reset(self):\n self.state_out = (np.zeros(self.state_out[0].shape),np.zeros(self.state_out[1].shape))\n \n def save_models(self, episode_number):\n self.episode_number = episode_number\n self.q_eval.save_checkpoint(epi_num = self.episode_number)\n self.q_next.save_checkpoint(epi_num = self.episode_number)\n\n def load_models(self, filename):\n self.q_eval.load_checkpoint(filename)\n #self.q_next.load_checkpoint()\n\n def update_graph(self):\n t_params = self.q_next.params\n e_params = self.q_eval.params\n\n for t, e in zip(t_params, e_params):\n self.q_eval.sess.run(tf.assign(t, e))\n","sub_path":"implementation/imp_DQRN.py","file_name":"imp_DQRN.py","file_ext":"py","file_size_in_byte":18997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"129849642","text":"\nimport random\nimport enum\nimport math\nimport Lab1_Agents_Task1_World as World\n\ndef Turn(Leftdis,Rightdis):\n global Rightspeed,Lspeed\n global motorSpeed;\n Rspeed = Leftspeed = 0\n motorSpeed = dict(speedLeft=Leftspeed, speedRight=Rightspeed)\n World.setMotorSpeeds(motorSpeed)\n if(Rightdis >= Leftdis):\n Leftspeed = 0\n Rightspeed = -1\n else:\n Leftspeed = -1\n Rightspeed = 0\n\n motorSpeed = dict(speedLeft=Leftspeed, speedRight=Rightspeed)\n World.execute(motorSpeed, 2000, -1)\n return;\n\ndef run(Ldis,Rdis,TP):\n global PLdis, PRdis\n global FindWall, FindingEnrgyCn\n global motorSpeed\n global Leftspeed, Rightspeed\n\n if (TP < 0.2 and TP > -0.2):\n Rightspeed = Leftspeed = 2\n if(TP>=0.2):\n Rightspeed = 0\n Leftspeed = 1\n if(TP<=-0.2):\n Leftspeed = 0\n Rightspeed = 1\n motorSpeed = dict(speedLeft=Leftspeed, speedRight=Rightspeed)\n\n return\n\n\n\n\ndef RandomStrategy():\n ESensor = World.getSensorReading(\"energySensor\")\n LSensor = World.getSensorReading(\"ultraSonicSensorLeft\")\n RSensor = World.getSensorReading(\"ultraSonicSensorRight\")\n global motorSpeed,Leftspeed,Rightspeed\n if(LSensor > 0.3 and RSensor > 0.3):\n Leftspeed = random.uniform(2, 10)\n Rightspeed = Leftspeed # random.uniform(0, 10)\n\n elif(RSensor<0.3):\n Leftspeed = 0\n Rightspeed = -random.uniform(2, 10)\n\n elif(LSensor <0.3):\n Leftspeed = -random.uniform(2, 10)\n Rightspeed = 0\n\n motorSpeed = dict(speedLeft=Leftspeed, speedRight=Rightspeed)\n World.setMotorSpeeds(motorSpeed)\n return\n\nrobot = World.init()\n# print important parts of the robot\nprint(sorted(robot.keys()))\n\nCounter = 0\nLeftspeed = 1\nRightspeed = 1\nPreTime = World.getSimulationTime()\nCurrentState = 0\nTCn = 0\nFindingEnrgyCn = 0\nFindWall = 0\nwhile robot:\n simulationTime = World.getSimulationTime()\n ElapsedTime = simulationTime - PreTime;\n\n if ElapsedTime > 1000:\n PreTime = simulationTime\n FindingEnrgyCn = FindingEnrgyCn +1\n TCn = TCn + 1\n Counter = Counter + 1\n\n if (FindingEnrgyCn > 10):\n FindingEnrgyCn = 0\n if(CurrentState == 0):\n #CurrentState = 1\n print(\"Random agent\")\n else:\n #CurrentState = 0\n print(\"Memory agent\")\n\n if(CurrentState == 0):\n ESensor = World.getSensorReading(\"energySensor\")\n LSensor = World.getSensorReading(\"ultraSonicSensorLeft\")\n RSensor = World.getSensorReading(\"ultraSonicSensorRight\")\n if(LSensor>0.3 and RSensor >0.3):\n run(LSensor, RSensor, ESensor.direction)\n else:\n CurrentState = 1\n World.STOP()\n Timer = 0\n elif(CurrentState == 1):\n Turn(LSensor, RSensor)\n\n if(LSensor > 0.4 and RSensor > 0.4):\n Timer = 0\n CurrentState = 2\n elif(CurrentState == 2):\n if (LSensor > 0.3 and RSensor > 0.3):\n run(LSensor, RSensor, 0)\n\n if(Timer >= 5):\n Timer = 0\n CurrentState = 0\n else:\n CurrentState = 1\n World.STOP()\n Timer = 0\n elif (CurrentState == 3):\n RandomStrategy()\n\n if(Counter >= 20):\n Counter = 0\n if(CurrentState == 3):\n CurrentState = 0\n else:\n CurrentState = 3\n\n\n print(LSensor,RSensor)\n World.setMotorSpeeds(motorSpeed)\n if (ESensor.distance < 0.3):\n World.collectNearestBlock()\n Counter = 0\n CurrentState = 0","sub_path":"ProteusLaptop/Lab/OutPut/Lab 1_M_Mirian/Lab1_Agents_code/Lab1_Memory_ Agents_Task1_Pioneer.py","file_name":"Lab1_Memory_ Agents_Task1_Pioneer.py","file_ext":"py","file_size_in_byte":3552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"223058857","text":"import theano\nimport numpy as np\nfrom utils import pdf\nimport theano.tensor as T\nfrom lasagne.random import get_rng\nfrom lasagne.layers.base import Layer\nfrom lasagne import layers, updates\nfrom lasagne.init import Constant, GlorotUniform, Normal\nfrom theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams\nfrom lasagne.nonlinearities import rectify, identity, softmax, sigmoid\n\nclass DenseLayer(Layer):\n def __init__(self, incoming, num_units, W=Normal(), b=Constant(0.), nonlinearity=rectify, p=0.5, **kwargs):\n super(DenseLayer, self).__init__(incoming, **kwargs)\n\n self.name = 'Dense'\n self.mode = 'none'\n self.p, self.num_units, num_inputs = p, num_units, int(np.prod(self.input_shape[1:]))\n self.nonlinearity = (identity if nonlinearity is None else nonlinearity)\n self.W = self.add_param(W, (num_inputs, num_units), name=\"W\")\n self.W = updates.norm_constraint(self.W, 3)\n self._srng = RandomStreams(get_rng().randint(1, 2147462579))\n self.num_inputs = int(np.prod(self.input_shape[1:]))\n\n if b is None:\n self.b = None\n else:\n self.b = self.add_param(b, (num_units,), name=\"b\", regularizable=False)\n\n def get_output_shape_for(self, input_shape):\n return (input_shape[0], self.num_units)\n\n def get_output_for(self, input, deterministic=False, **kwargs):\n if input.ndim > 2:\n input = input.flatten(2)\n\n return self.get_output_for_(input, deterministic)\n\n def get_output_for_(self, input, deterministic):\n return self.nonlinearity(T.dot(input, self.W) + self.b.dimshuffle('x', 0))\n\n def eval_reg(self):\n return 0\n\n def get_p(self):\n return -1\n\nclass DenseBinaryDropOut(DenseLayer):\n def __init__(self, incoming, num_units, W=Normal(), b=Constant(0.), nonlinearity=rectify, p=0.5, **kwargs):\n super(DenseBinaryDropOut, self).__init__(incoming, num_units, W, b, nonlinearity, p, **kwargs)\n self.name = 'Dense + DropOut'\n self.num_updates = 0\n\n def get_output_for_(self, input, deterministic):\n input_shape = input.shape if any(s is None for s in self.input_shape) else self.input_shape\n\n if not (deterministic or self.p == 0):\n input /= (1 - self.p)\n input *= self._srng.binomial(input_shape, p=1 - self.p, dtype=input.dtype)\n\n return self.nonlinearity(T.dot(input, self.W) + self.b.dimshuffle('x', 0))\n\n def get_p(self):\n return self.p\n\nclass DensePreGaussianDropOut(DenseLayer):\n def __init__(self, incoming, num_units, W=GlorotUniform(), b=Constant(0.), nonlinearity=rectify, p=0.5, **kwargs):\n super(DensePreGaussianDropOut, self).__init__(incoming, num_units, W, b, nonlinearity, p, **kwargs)\n self._srng = RandomStreams(get_rng().randint(1, 2147462579))\n self.alpha = T.sqrt(p / (1 - p))\n self.name = 'DenseGaussianDropOut'\n\n def get_output_for_(self, input, deterministic):\n if not (deterministic or self.p == 0):\n input *= self._srng.normal(input.shape, avg=1.0, std=self.alpha)\n\n return self.nonlinearity(T.dot(input, self.W) + self.b.dimshuffle('x', 0))\n\n def get_p(self):\n return self.alpha.eval()\n\nclass DensePosGaussianDropOut(DenseLayer):\n def __init__(self, incoming, num_units, W=GlorotUniform(), b=Constant(0.), nonlinearity=rectify, p=0.5, **kwargs):\n super(DensePosGaussianDropOut, self).__init__(incoming, num_units, W, b, nonlinearity, p, **kwargs)\n self._srng = RandomStreams(get_rng().randint(1, 2147462579))\n self.alpha = T.sqrt(p / (1 - p))\n self.name = 'DensePosGaussianDropOut'\n\n def get_output_for_(self, input, deterministic):\n if not (deterministic or self.p == 0):\n mu, sigma = T.dot(input, self.W), T.sqrt(self.alpha * T.dot(input * input, self.W * self.W))\n activation = self._srng.normal(mu.shape, avg=mu, std=sigma)\n else:\n activation = T.dot(input, self.W)\n\n return self.nonlinearity(activation + self.b.dimshuffle('x', 0))\n\n def get_p(self):\n return self.alpha.eval()\n\nclass DenseVarDropOut(DenseLayer):\n def __init__(self, incoming, num_units, W=GlorotUniform(), b=Constant(0.), nonlinearity=rectify,\n p=0.5, mode='layer', restr='sigmoid'):\n super(DenseVarDropOut, self).__init__(incoming, num_units, W, b, nonlinearity, p)\n\n self.name, self.mode = 'Var', mode\n\n if restr not in ['sigmoid', 'rectify', 'exp']:\n raise Exception('alpha_restriction should be: sigmoid, rectify, exp instead of %s' % mode)\n if restr == 'sigmoid':\n self.bound_function, self.reverse_bf = lambda x: 1.0 * T.nnet.sigmoid(x), lambda x: np.log(x / (1 - x)) * (1.0/1.0)\n if restr == 'rectify':\n self.bound_function, self.reverse_bf = T.nnet.relu, lambda x: x\n if restr == 'exp':\n self.bound_function, self.reverse_bf = np.exp, np.log\n\n if mode not in ['fixing', 'model', 'layer', 'features', 'neurons', 'weights']:\n raise Exception('mode should be: fixing, layer, features, neuron, weights instead of %s' % mode)\n alpha = Constant(self.reverse_bf(p / (1 - p)))\n if mode == 'fixing':\n self.alpha = self.add_param(alpha, (), name=\"alpha_fixing\", trainable=False)\n if mode == 'model':\n if self.input_layer.name == 'Input' or self.input_layer.mode == 'fixing':\n self.alpha = self.add_param(alpha, (), name=\"alpha_model\")\n else:\n self.alpha = self.input_layer.alpha\n if mode == 'layer':\n self.alpha = self.add_param(alpha, (), name=\"alpha_layer\")\n alpha = Normal(0.1, self.reverse_bf(p / (1 - p)))\n if mode == 'features':\n self.alpha = self.add_param(alpha, (self.num_inputs, ), name=\"alpha_features\")\n if mode == 'neurons':\n self.alpha = self.add_param(alpha, (self.num_units, ), name=\"alpha_neurons\")\n if mode == 'weights':\n self.alpha = self.add_param(alpha, (self.num_inputs, self.num_units), name=\"alpha_weights\")\n\n def get_output_for_(self, input, deterministic):\n self.input = input\n if deterministic:\n activation = T.dot(input, self.W)\n else:\n alpha = self.bound_function(self.alpha)\n if self.mode == 'features':\n mu, sigma = T.dot(input, self.W), T.sqrt(T.dot(input * input, (alpha * (self.W * self.W).T).T))\n else:\n mu, sigma = T.dot(input, self.W), T.sqrt(T.dot(input * input, alpha * self.W * self.W))\n\n activation = mu + sigma * self._srng.normal(mu.shape, avg=0, std=1)\n\n activation = activation + self.b.dimshuffle('x', 0)\n return self.nonlinearity(activation)\n\n def eval_reg(self):\n alpha = self.bound_function(self.alpha)\n regf = lambda a: -(0.5 * T.log1p(np.exp(-T.log(a))) - (0.03 + 1.0 / (1.0 + T.exp(-(1.5 * (np.log(a) + 1.3)))) * 0.64))\n\n if self.mode in ['fixing', 'model', 'layer']:\n reg = regf(alpha) * self.num_units * self.num_inputs\n if self.mode == 'features':\n reg = regf(alpha).sum() * self.num_units\n if self.mode == 'neurons':\n reg = regf(alpha).sum() * self.num_inputs\n if self.mode == 'weights':\n reg = regf(alpha).sum()\n\n return - reg\n\n def get_p(self):\n alpha = self.alpha.get_value()\n alpha = self.bound_function(alpha)\n p = alpha\n\n return p if isinstance(p, np.float64) or isinstance(p, np.ndarray) else p.eval()\n\nclass Conv2DLayer(layers.Conv2DLayer):\n def __init__(self, incoming, num_filters, filter_size, max_norm=3, **kwargs):\n super(Conv2DLayer, self).__init__(incoming, num_filters, filter_size, **kwargs)\n self.W = updates.norm_constraint(self.W, max_norm=max_norm)\n\nclass MaxPool2DLayer(layers.MaxPool2DLayer):\n pass\n\nclass InputLayer(layers.InputLayer):\n pass\n\n","sub_path":"nets/layers.py","file_name":"layers.py","file_ext":"py","file_size_in_byte":8003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"32073272","text":"\"\"\"\nThis file contains a set of functions to calculate outliers on a given 1-D numerical array.\n\n@author Antonio Samaniego\n@file OutlierDetection.py\n@scope public\n\"\"\"\n\n# third party dependencies\nimport os\nimport csv\nimport math\nimport numpy as np\n\n# Set location of log folder relative to this script\nOUT_DIR = os.path.normpath(os.path.join(os.path.dirname(__file__), '../logs/outliers'))\n\n\ndef moving_average(t, n=10):\n \"\"\"\n Function to calculate moving/rolling average of a 1-dimensional numerical array.\n\n Parameters\n ----------\n t: 1-dimensional array of numbers (e.g. int, float).\n n: Window length for moving average step calculation (e.g. n=5 means\n every average step is calculated with 5 elements). Default: n=3\n Returns\n -------\n Moving average of t\n \"\"\"\n ret = np.cumsum(t)\n ret[n:] = ret[n:] - ret[:-n]\n return ret[n - 1:] / n\n\n# Detects outliers based on std and moving average, and saves them on a .csv file\n\n\ndef detect_outliers(t, n=10, s=2, filename='outliers.csv'):\n \"\"\"\n Function to detect outliers based on whether an element is s standard deviations (std)\n away from the corresponding rolling mean. Results are both returned in a dict and\n saved into an output .csv file.\n\n Parameters\n ----------\n t: 1-dimensional array of numbers (e.g. int, float).\n n: Window length for moving average step calculation (e.g. n=5 means\n every moving average step is calculated with 5 elements). Default: n=10\n s: Number of std away from the rolling mean from which a value is\n considered to be an outlier. Default s=2\n filename: Output .csv filename. Default filename='outliers.csv'\n\n Returns\n -------\n outliers: dict containing {'timestamp': outlier_value}\n \"\"\"\n if len(t) == 1:\n print('Time series length is 1 (no possible outliers). No output file created.')\n return None\n\n mov_avg_t = moving_average(t) # Moving/rolling average\n std_dev = np.std(t[0:len(mov_avg_t-1)]) # Std\n\n outliers = {}\n for idx, v in enumerate(t):\n # More than s stds from the corresponding set/window's rolling mean\n current_mov_avg = mov_avg_t[math.floor(idx % n)]\n if v > current_mov_avg and (v - (s*std_dev)) > current_mov_avg: \n outliers[idx] = v\n elif v < current_mov_avg and (v + (s*std_dev)) < current_mov_avg:\n outliers[idx] = v\n\n # Save on output .csv file\n with open(os.path.join(OUT_DIR, filename), mode='w') as outlier_file:\n outlier_writer = csv.writer(outlier_file, delimiter=';',\n quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n outlier_writer.writerow(['idx', 'value'])\n for k, v in outliers.items():\n outlier_writer.writerow([k, v])\n\n return outliers\n","sub_path":"app/lib/OutlierDetection.py","file_name":"OutlierDetection.py","file_ext":"py","file_size_in_byte":2861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"144157679","text":"import sys\nimport os\n\nfrom zope.interface import implements\nfrom twisted.web import error as web_error\nfrom twisted.internet import error\nfrom twisted.web._newclient import ResponseDone\nfrom twisted.python import failure\n\nfrom feat.agencies.database import Connection, ChangeListener\nfrom feat.common import log, defer, time\nfrom feat.agencies import common\n\nfrom feat.agencies.interface import *\nfrom feat.interface.view import *\n\n\nfrom feat import extern\n# Add feat/extern/paisley to the load path\nsys.path.insert(0, os.path.join(extern.__path__[0], 'paisley'))\nfrom paisley.changes import ChangeNotifier\nfrom paisley.client import CouchDB\n\n\nDEFAULT_DB_HOST = \"localhost\"\nDEFAULT_DB_PORT = 5984\nDEFAULT_DB_NAME = \"feat\"\n\n\nclass Database(common.ConnectionManager, log.LogProxy, ChangeListener):\n\n implements(IDbConnectionFactory, IDatabaseDriver)\n\n log_category = \"database\"\n\n def __init__(self, host, port, db_name):\n common.ConnectionManager.__init__(self)\n log.LogProxy.__init__(self, log.FluLogKeeper())\n ChangeListener.__init__(self, self)\n\n self.semaphore = defer.DeferredSemaphore(1)\n self.paisley = None\n self.db_name = None\n self.host = None\n self.port = None\n self.notifier = None\n\n self.retry = 0\n self.reconnector = None\n\n self._configure(host, port, db_name)\n\n def reconfigure(self, host, port, name):\n if self.notifier.isRunning():\n self.notifier.stop()\n self._configure(host, port, name)\n self._setup_notifier()\n\n def show_status(self):\n eta = self.reconnector and self.reconnector.active() and \\\n time.left(self.reconnector.getTime())\n return \"Database\", self.is_connected(), self.host, self.port, eta\n\n ### IDbConnectionFactory\n\n def get_connection(self):\n return Connection(self)\n\n ### IDatabaseDriver\n\n def open_doc(self, doc_id):\n return self._paisley_call(self.paisley.openDoc, self.db_name, doc_id)\n\n def save_doc(self, doc, doc_id=None):\n return self._paisley_call(self.paisley.saveDoc,\n self.db_name, doc, doc_id)\n\n def delete_doc(self, doc_id, revision):\n return self._paisley_call(self.paisley.deleteDoc,\n self.db_name, doc_id, revision)\n\n def create_db(self):\n return self._paisley_call(self.paisley.createDB,\n self.db_name)\n\n def listen_changes(self, doc_ids, callback):\n d = ChangeListener.listen_changes(self, doc_ids, callback)\n d.addCallback(defer.bridge_param, self._setup_notifier)\n return d\n\n def cancel_listener(self, listener_id):\n ChangeListener.cancel_listener(self, listener_id)\n return self._setup_notifier()\n\n def query_view(self, factory, **options):\n factory = IViewFactory(factory)\n d = self._paisley_call(self.paisley.openView,\n self.db_name, DESIGN_DOC_ID, factory.name,\n **options)\n d.addCallback(self._parse_view_result)\n return d\n\n ### paisleys ChangeListener interface\n\n def changed(self, change):\n # The change parameter is just an ugly effect of json unserialization\n # of the couchdb output. It can be many different things, hence the\n # strange logic above.\n if \"changes\" in change:\n doc_id = change['id']\n for line in change['changes']:\n # The changes are analized when there is not http request\n # pending. Otherwise it can result in race condition problem.\n self.semaphore.run(self._trigger_change, doc_id, line['rev'])\n else:\n self.info('Bizare notification received from CouchDB: %r', change)\n\n def connectionLost(self, reason):\n if reason.check(error.ConnectionDone):\n # expected just pass\n return\n elif reason.check(ResponseDone):\n self.debug(\"CouchDB closed the notification listener. This might \"\n \"indicate missconfiguration. Take look at it\")\n return\n elif reason.check(error.ConnectionRefusedError):\n self.retry += 1\n wait = min(2**(self.retry - 1), 300)\n self.debug('CouchDB refused connection for %d time. '\n 'This indicates missconfiguration or temporary '\n 'network problem. Will try to reconnect in %d seconds.',\n self.retry, wait)\n self.reconnector = time.callLater(wait, self._setup_notifier)\n self._on_disconnected()\n return\n else:\n # FIXME handle disconnection when network is down\n self._on_disconnected()\n self.warning('Connection to db lost with reason: %r', reason)\n return self._setup_notifier()\n\n ### private\n\n def _configure(self, host, port, name):\n self._cancel_reconnector()\n self.host, self.port = host, port\n self.paisley = CouchDB(host, port)\n self.db_name = name\n self.notifier = ChangeNotifier(self.paisley, self.db_name)\n self.notifier.addListener(self)\n\n # ping database to figure trigger changing state to connected\n d = self._paisley_call(self.paisley.listDB)\n d.addErrback(failure.Failure.trap, NotConnectedError)\n\n def _parse_view_result(self, resp):\n assert \"rows\" in resp\n\n for row in resp[\"rows\"]:\n yield row[\"key\"], row[\"value\"]\n\n def _setup_notifier(self):\n doc_ids = self._extract_doc_ids()\n self.log('Setting up the notifier passing. Doc_ids: %r.',\n doc_ids)\n if self.notifier.isRunning():\n self.notifier.stop()\n if len(doc_ids) == 0:\n # Don't run listner if it is not needed,\n # cancel reconnector if one is running.\n if self.reconnector and self.reconnector.active():\n self.reconnector.cancel()\n self.reconnector = None\n return\n\n d = self.notifier.start(\n heartbeat=1000)\n d.addCallback(self._connected)\n d.addErrback(self.connectionLost)\n d.addErrback(failure.Failure.trap, NotConnectedError)\n return d\n\n def _connected(self, _):\n self.debug('Established persistent connection for receiving '\n 'notifications.')\n self._on_connected()\n self._cancel_reconnector()\n\n def _cancel_reconnector(self):\n if self.reconnector:\n if self.reconnector.active():\n self.reconnector.cancel()\n self.reconnector = None\n self.retry = 0\n\n def _paisley_call(self, method, *args, **kwargs):\n # It is necessarry to acquire the lock to perform the http request\n # because we need to be sure that we are not in the middle of sth\n # while analizing the change notification\n d = self.semaphore.run(method, *args, **kwargs)\n d.addCallback(defer.bridge_param, self._on_connected)\n d.addErrback(self._error_handler)\n return d\n\n def _error_handler(self, failure):\n exception = failure.value\n msg = failure.getErrorMessage()\n if isinstance(exception, web_error.Error):\n status = int(exception.status)\n if status == 409:\n raise ConflictError(msg)\n elif status == 404:\n raise NotFoundError(msg)\n else:\n self.info(exception.response)\n raise NotImplementedError(\n 'Behaviour for response code %d not define yet, FIXME!' %\n status)\n elif failure.check(error.ConnectionRefusedError):\n self._on_disconnected()\n raise NotConnectedError(\"Database connection refused.\")\n else:\n failure.raiseException()\n","sub_path":"src/feat/agencies/net/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":7945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"644708696","text":"import sys\n\ntry:\n path = sys.argv[1] # Получение пути до директории в которой лежит файл\n\nexcept IndexError:\n path = '' # По умолчанию файл ищется в текущей директории\n\ntry:\n f = open(path+'numbers.csv', 'r') # Открытие файла на чтение\n \n for numbers in f:\n \n string_numbers = numbers # Получение строки из файла\n\n string_numbers = string_numbers.split(',') # Разбиение строки на список строк\n\n numbers = list() \n\n for number in string_numbers:\n \n numbers.append(int(number)) # Конвертация строк в целые числа\n\n numbers.sort() # Сортировка\n\n print(numbers)\n\nexcept FileNotFoundError:\n \n print(\"Файл отсутствует в данной директории\")\n\nexcept ValueError:\n\n print(\"Файл должен содержать только числа\")\n\nfinally:\n f.close() # Закрытие файла","sub_path":"test_task_2.py","file_name":"test_task_2.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"7081809","text":"import hikvisionbroker_extension\nimport time\ncnt = [0, 0]\ndef callback(x):\n cnt[0] = cnt[0] + 1; t=time.time(); print(1/(t-cnt[1])); cnt[1]=t\n\n\ncamera = hikvisionbroker_extension.Camera(0)\ncamera.register_callback(callback)\ncamera.set_io_configuration()\ncamera.set_frame_rate(2.)\ncamera.start_acquisition()\ntime.sleep(3)\ncamera.stop_acquisition()\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"321999050","text":"import time\nimport json\nimport requests\nimport Blinker\nimport Beeper\n\nclass Scheduler(object):\n\n def __init__(self):\n global light\n global beep\n light = Blinker.Blinker()\n beep = Beeper.Beeper()\n\n def getTime(self):\n busStop = json.load(open('bus.json'))\n url = 'https://svc.metrotransit.org/NexTrip/' + busStop['Stop'] + '?format=json'\n rTJson = requests.get(url).json()\n rTStr = str(rTJson[0]['DepartureText'])\n if \"Min\" in rTStr:\n return int(filter(str.isdigit, rTStr))\n else:\n return 20\n\n def put20Minutes(self):\n light.turnOff()\n time.sleep(30)\n\n def put10Minutes(self):\n t_end = time.time() + 30\n while time.time() < t_end:\n light.turnOn()\n\n def put6Minutes(self):\n light.turnOff()\n t_end = time.time() + 30\n while time.time() < t_end:\n light.blinkSlow()\n\n def put4Minutes(self):\n light.turnOff()\n beep.quickBeep()\n t_end = time.time() + 30\n while time.time() < t_end:\n light.blinkFast()\n\n def put3Minutes(self):\n light.turnOff()\n t_end = time.time() + 30\n while time.time() < t_end:\n light.blinkFast()\n","sub_path":"Scheduler.py","file_name":"Scheduler.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"576715065","text":"import random\n\nimport numpy as np\nfrom tensorflow import keras\nfrom tensorflow.python.keras.layers import Input, LSTM, Embedding, Dense, Bidirectional\n\nfrom peom_read import get_poem_name2content\n\npoem_pick = r\"poem/\"\ntext_name, text_content, num2word, length = get_poem_name2content(poem_pick + \"poems.plk\")\none_hot = np.eye(length + 1, dtype='int')\nbatch_size = 10\n\n\n# def get_label(batch):\n# train = np.array(one_hot[batch[0]])\n# train = train.reshape([1, train.shape[0], train.shape[1]])\n# print(train.shape)\n# for i in range(batch.shape[0] - 1):\n# i += 1\n# tmp = one_hot[batch[i]]\n# # tmp = tmp.reshape([1, tmp.shape[0], tmp.shape[1]])\n# # # print(tmp.shape)\n# # train = np.r_[train, tmp]\n# train = []\n# for i in range(batch.shape[0]):\n# tmp = one_hot[batch[i]]\n# train.append(tmp)\n# return np.array(train)\ndef get_label(batch):\n train = one_hot[batch]\n return train\n\n\n# def get_input(batch):\n# # start = np.zeros(batch.shape[0], dtype='int')\n# # start[start == 0] = length + 1\n# start = []\n# for ii in range(batch.shape[0]):\n# start.append(np.insert(batch[ii], 0, [length + 1])[:-1])\n# start = np.array(start)\n# return start\ndef get_input(batch):\n batch = batch[:, :-1]\n start = np.zeros(batch.shape[0], dtype='int')\n start[start == 0] = length + 1\n return np.c_[start, batch]\n\n\nclass PoemSequence(keras.utils.Sequence):\n def __init__(self, encoder_data, decoder_data, batch_size_=32):\n self.encoder_data = encoder_data\n self.decoder_data = decoder_data\n self.batch_size = batch_size_\n\n def __len__(self):\n return len(self.encoder_data) // self.batch_size\n\n def __getitem__(self, idx):\n encoder_inp = self.encoder_data[idx * self.batch_size:(idx + 1) * self.batch_size]\n decoder_inp = self.decoder_data[idx * self.batch_size:(idx + 1) * self.batch_size]\n decoder_out = get_label(decoder_inp)\n decoder_inp = get_input(decoder_inp)\n return [encoder_inp, decoder_inp], decoder_out\n\n\nencoder_inputs = Input(shape=[None])\nembedding_1 = Embedding(length + 1, 200)\nx_ = embedding_1(encoder_inputs)\nencoder = Bidirectional(LSTM(150, return_state=True))\n\nencoder_outputs, state_h_1, state_c_1, state_h_2, state_c_2 = encoder(x_)\nstate_h = keras.layers.Concatenate()([state_h_1, state_h_2])\nstate_c = keras.layers.Concatenate()([state_c_1, state_c_2])\n\nencoder_states = [state_h, state_c]\n\ndecoder_inputs = Input(shape=[None])\nembedding_2 = Embedding(length + 2, 200)\nx = embedding_2(decoder_inputs)\ndecoder = LSTM(300, return_state=True, return_sequences=True)\ndecoder_outputs, _, __ = decoder(x, initial_state=encoder_states)\ndecoder_dense = Dense(length + 1, activation='softmax')\ndecoder_outputs = decoder_dense(decoder_outputs)\nmodel = keras.Model(inputs=[encoder_inputs, decoder_inputs], outputs=[decoder_outputs])\nmodel.summary()\nmodel.load_weights(\"./logs/poem_model_bidirectional/\")\n# #\n# embedding_weights = train_word2vec(text_name, num2word, name=\"embedding\")\n# weights = np.array([v for v in embedding_weights.values()])\n# embedding_1.set_weights([weights])\n# embedding_1.trainable = False\n# embedding_weights = train_word2vec(text_content, num2word, name=\"content_embedding\")\n# weights = np.array([v for v in embedding_weights.values()])\n# embedding_2.set_weights([weights])\n# embedding_2.trainable = False\n# #\n# model.compile(optimizer=keras.optimizers.RMSprop(lr=0.005, decay=0.0005), loss='categorical_crossentropy')\n# model.fit_generator(PoemSequence(text_name, text_content, batch_size), epochs=1,\n# callbacks=[\n# ModelCheckpoint(\"./logs/poem_model_bidirectional/\", save_best_only=True, period=1,\n# save_weights_only=True, monitor='loss'),\n# TensorBoard(\"./logs/poem/\", batch_size=batch_size, write_graph=True, write_grads=True),\n# EarlyStopping(patience=4, baseline=0.1, monitor='loss')\n# ])\n#\n# embedding_1.trainable = True\n# embedding_2.trainable = True\n# model.compile(optimizer=keras.optimizers.RMSprop(), loss='categorical_crossentropy')\n# model.fit_generator(PoemSequence(text_name, text_content, batch_size), epochs=1,\n# callbacks=[\n# ModelCheckpoint(\"./logs/poem_model_bidirectional/\", save_best_only=True, period=1,\n# save_weights_only=True, monitor='loss'),\n# TensorBoard(\"./logs/poem/\", batch_size=batch_size, write_graph=True, write_grads=True),\n# EarlyStopping(patience=4, baseline=0.1, monitor='loss')\n# ])\n\nencoder_model = keras.Model(inputs=[encoder_inputs], outputs=encoder_states)\n\ndecoder_states_h = Input([300])\ndecoder_states_c = Input([300])\ndecoder_states_input = [decoder_states_h, decoder_states_c]\ndecoder_outputs_, state_h_d, state_c_d = decoder(x, initial_state=decoder_states_input)\ndecoder_outputs_ = decoder_dense(decoder_outputs_)\ndecoder_model = keras.Model(\n [decoder_inputs, decoder_states_input[0], decoder_states_input[1]],\n [decoder_outputs_, state_h_d, state_c_d])\n\n\n# decoder_model.summary()\n\n\ndef decode_sequence(input_seq):\n # Encode the input as state vectors.\n states_value = encoder_model.predict(input_seq)\n # Generate empty target sequence of length 1.\n a = random.randint(0, length)\n target_seq = np.array([[a + 1]])\n # Populate the first character of target sequence with the start character.\n\n # Sampling loop for a batch of sequences\n # (to simplify, here we assume a batch of size 1).\n decoded_sentence = ''\n while True:\n output_tokens, h, c = decoder_model.predict(\n [target_seq, states_value[0], states_value[1]])\n # Sample a token\n sampled_token_index = np.argmax(output_tokens[0, -1, :])\n if sampled_token_index == 0 or len(decoded_sentence) > 100:\n break\n sampled_char = num2word[sampled_token_index]\n decoded_sentence += sampled_char\n # Exit condition: either hit max length\n # or find stop character.\n\n # Update the target sequence (of length 1).\n target_seq = np.array([[sampled_token_index]])\n # Update states\n states_value = [h, c]\n return decoded_sentence\n\n\ndef name(text_na):\n sentence = ''\n for i in text_na:\n if i == 0:\n break\n sentence += num2word[i]\n return sentence\n\n\nword2num = dict(zip(num2word.values(), num2word.keys()))\nfor seq_index in range(5):\n # Take one sequence (part of the training set)\n # for trying out decoding.\n a = random.randint(0, 5000)\n input_seq = text_name[a: a + 1]\n zbdx = np.zeros_like(input_seq)\n name_ = ['北','山','孤','雁']\n for index,nn in enumerate(name_):\n zbdx[0][index] = word2num[nn]\n print('-')\n print('Input sentence:', name(zbdx[0]))\n decoded_sentence = decode_sequence(zbdx)\n print('Decoded sentence:', decoded_sentence)\n","sub_path":"poem_bi.py","file_name":"poem_bi.py","file_ext":"py","file_size_in_byte":7023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"302090387","text":"import requests\nimport json\n\nMERAKI_ORG = '681155'\nMERAKI_URL = f'https://api.meraki.com/api/v1/organizations/{MERAKI_ORG}/networks'\nMERAKI_X_AUTH = '6bec40cf957de430a6f1f2baa056b99a4fac9ea0'\n\n# payload is an empty dictionary\npayload = {}\n\n# define the necessary headers for Meraki\nheaders = {'X-Cisco-Meraki-API-Key': MERAKI_X_AUTH,\n 'Accept': 'application/json',\n 'Content-type': 'application/json'\n }\n\n# create a variable to store the response of upcoming request\nresponse = requests.request('GET', url=MERAKI_URL, headers=headers, data=payload)\n\n# print the status code and the response itself\nprint(response.status_code)\n\n# print out the resulting networks\nprint(json.dumps(response.json(), indent=2))\n\n","sub_path":"devasc/8_enterprise netmgmt_platforms_apis/meraki_get_networks.py","file_name":"meraki_get_networks.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"182724003","text":"a = []\nfor i in open('input.txt','r'):\n a.append(i.strip())\n\nn = int(a[0]);dict = {}\nfor i in range(n):\n s = a[i+1].split(' ')\n dict[s[0]] = s[1]\n\nfor j in a[n+1:]:\n if dict.get(j,None):\n print(j +'='+dict[j])\n else:\n print('Not found')","sub_path":"122---HackerRank/30days/Day8/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"438305222","text":"import numpy as np\nimport os\nimport pytest\nimport subprocess\n\nfrom karabo_data.utils import QuickView\n\n\ndef test_summary_on_data_file():\n testdatapath = \"data/example_data/R0126-AGG01-S00002.h5\"\n if os.path.exists(testdatapath):\n # next line assumes that the have installed the package\n output = str(subprocess.check_output(\"euxfel_h5tool.py {}\".format(\n testdatapath), shell=True))\n print(output)\n assert \"Size: 665.596177 MB\" in output\n assert \"Entries: 10\" in output\n assert \"First Train: 1362168960\" in output\n else:\n pytest.skip(\"test data file not available ()\".format(testdatapath))\n\n\ndef test_cbf_conversion():\n testdatapath = \"data/example_data/R0126-AGG01-S00002.h5\"\n if os.path.exists(testdatapath):\n # Test that the help message pops up when the command is malformed\n command = \"euxfel_h5tool.py convert-cbf\".format(testdatapath)\n output = str(subprocess.check_output(command), shell=True)\n print(output)\n assert \"Usage:\" in output\n\n # Test that the cbf file is correctly created for index 0\n command = (\"euxfel_h5tool.py convert-cbf {}\"\n \"0 out.cbf\".format(testdatapath))\n expected_output = \"Convert {} index 0 to out.cbf\".format(testdatapath)\n output = str(subprocess.check_output(command), shell=True)\n print(output)\n assert expected_output == output\n\n # Test that the cbf file is correctly created for an arbitrary index\n command = (\"euxfel_h5tool.py convert-cbf {}\"\n \"42 out.cbf\".format(testdatapath))\n expected_output = \"Convert {} index 42 to out.cbf\".format(testdatapath)\n output = str(subprocess.check_output(command), shell=True)\n print(output)\n assert expected_output == output\n\n # Test graceful fail for inexisting file\n command = \"euxfel_h5tool.py convert-cbf non_existing_data.h5 0 out.cbf\"\n expected_output = \"non_exisiting_data.h5: Could not be opened.\"\n output = str(subprocess.check_output(command), shell=True)\n print(output)\n assert expected_output == output\n\n # Test graceful fail for index out of range\n maxint_64 = 9223372036854775808\n command = (\"euxfel_h5tool.py convert-cbf non_existing_data.h5\"\n \"{} out.cbf\".format(maxint_64))\n expected_output = \"Index ({}) out of range\".format(maxint_64)\n output = str(subprocess.check_output(command), shell=True)\n print(output)\n assert expected_output in output\n\n # Clean up\n os.remove(\"out.cbf\")\n\n else:\n pytest.skip(\"test data file not available ()\".format(testdatapath))\n\n\ndef test_init_quick_view():\n qv = QuickView()\n\n assert qv.data is None\n qv.data = np.empty((1,1,1), dtype=np.int8)\n assert len(qv) == 1\n assert qv.pos == 0\n\n with pytest.raises(TypeError) as info:\n qv.data = 4\n\n with pytest.raises(TypeError) as info:\n qv.data = np.empty((1,1,1,1), dtype=np.int8)\n\n\nif __name__ == \"__main__\":\n pytest.main([\"-v\"])\n print(\"Run 'py.test -v -s' to see more output\")\n","sub_path":"karabo_data/tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":3153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"343821913","text":"'''\nCALCULADORA:\n- 2 campos de texto\n- 4 botones\n- Mostrar resultado en una alerta\n'''\nfrom tkinter import *\nfrom tkinter import messagebox\n\nclass Calculadora:\n\n def __init__(self, alertas):\n self.numero1=StringVar()\n self.numero2=StringVar()\n self.resultado=StringVar()\n self.alertas=alertas\n\n def convertirFloat(self, numero):\n try:\n result = float(numero)\n return result\n except:\n self.alertas.showerror(\"Error\", \"introduce bien los datos\")\n\n def sumar(self):\n self.resultado.set(self.convertirFloat(self.numero1.get()) + self.convertirFloat(self.numero2.get()))\n self.mostrarResultado()\n\n def restar(self):\n self.resultado.set(self.convertirFloat(self.numero1.get()) - self.convertirFloat(self.numero2.get()))\n self.mostrarResultado()\n\n def multiplicar(self):\n self.resultado.set(self.convertirFloat(self.numero1.get()) * self.convertirFloat(self.numero2.get()))\n self.mostrarResultado()\n\n def dividir(self):\n self.resultado.set(self.convertirFloat(self.numero1.get()) / self.convertirFloat(self.numero2.get()))\n self.mostrarResultado()\n\n def mostrarResultado(self):\n self.alertas.showinfo('Resultado', f'El resultado de la operación es {self.resultado.get()}')\n self.numero1.set('')\n self.numero2.set('')\n\n\nventana = Tk()\nventana.title('Ejercicio calculadora con Tkinter')\nventana.geometry('400x400')\nventana.config(bd=25)\n\ncalculadora = Calculadora(messagebox)\n\nmarco = Frame(ventana, width=350, height=200)\nmarco.config(\n bd=5,\n relief=SOLID,\n padx=15,\n pady=15\n)\nmarco.pack(anchor=CENTER)\nmarco.pack_propagate(FALSE) # Para que no se deforme al meter el formulario dentro\n\nLabel(marco, text='Primer número: ').pack()\nEntry(marco, textvariable=calculadora.numero1, justify='center').pack()\n\nLabel(marco, text='Segundo número: ').pack()\nEntry(marco, textvariable=calculadora.numero2, justify='center').pack()\n\nLabel(marco, text='') # Separador\n\nButton(marco, text='Sumar', command=calculadora.sumar).pack(side=LEFT, fill=X, expand=YES)\nButton(marco, text='Restar', command=calculadora.restar).pack(side=LEFT, fill=X, expand=YES)\nButton(marco, text='Multiplicar', command=calculadora.multiplicar).pack(side=LEFT, fill=X, expand=YES)\nButton(marco, text='Dividir', command=calculadora.dividir).pack(side=LEFT, fill=X, expand=YES)\n\n\n\nventana.mainloop()","sub_path":"10-ejercicioPlus.py","file_name":"10-ejercicioPlus.py","file_ext":"py","file_size_in_byte":2442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"161434575","text":"from game_env import Game\r\nfrom game_net import DeepQNetwork\r\nimport numpy as np\r\n\r\ntrain_steps = 50000\r\n\r\n\r\ndef train_game():\r\n step = 0\r\n scores = []\r\n for episode in range(train_steps):\r\n if step%1000 == 0:\r\n print(\"step:\", step)\r\n score = 0\r\n observation = game.init_map()\r\n print(\"初始地图:\", observation)\r\n moves = []\r\n while(True):\r\n is_done = False\r\n action = RL.choose_action(observation, train=True)\r\n moves.append(action)\r\n print(\"action:\",action)\r\n print(\"observation:\",observation)\r\n # RL take action and get next observation and reward\r\n observation_, reward, is_done = game.move(action)\r\n if reward >= 0:\r\n score += reward\r\n\r\n print(\"observation_:\",observation_, \"reward:\",reward, \"is_done:\",is_done)\r\n RL.store_transition(observation, action, reward, observation_)\r\n if (step > 200) and (step % 5 == 0):\r\n RL.learn()\r\n\r\n # swap observation\r\n observation = observation_\r\n\r\n # break while loop when end of this episode\r\n if is_done:\r\n print(\"moves:\", moves, \"score:\", score)\r\n scores.append(score)\r\n break\r\n step += 1\r\n import matplotlib.pyplot as plt\r\n plt.plot(np.arange(len(scores)), scores)\r\n plt.ylabel('Scores')\r\n plt.xlabel('training steps')\r\n plt.show()\r\n\r\nif __name__ == \"__main__\":\r\n game = Game()\r\n # print(game.init_map())\r\n # print(game.init_map())\r\n RL = DeepQNetwork(n_actions=9,\r\n map_w=4,\r\n map_h=4,\r\n learning_rate=0.01,\r\n reward_decay=0.9,\r\n e_greedy=0.9,\r\n replace_target_iter=300,\r\n memory_size=2000,\r\n e_greedy_increment=0.2,\r\n output_graph=False\r\n )\r\n train_game()\r\n RL.plot_cost()\r\n # print(game.init_map())","sub_path":"game_ai_4_4/run_this.py","file_name":"run_this.py","file_ext":"py","file_size_in_byte":2110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"608859645","text":"class Node:\n # DO NOT MODIFY THIS CLASS #\n __slots__ = 'value', 'parent', 'left', 'right'\n\n def __init__(self, value, parent=None, left=None, right=None):\n \"\"\"\n Initialization of a node\n :param value: value stored at the node\n :param parent: the parent node\n :param left: the left child node\n :param right: the right child node\n \"\"\"\n self.value = value\n self.parent = parent\n self.left = left\n self.right = right\n\n def __eq__(self, other):\n \"\"\"\n Determine if the two nodes are equal\n :param other: the node being compared to\n :return: true if the nodes are equal, false otherwise\n \"\"\"\n if type(self) is not type(other):\n return False\n return self.value == other.value\n\n def __str__(self):\n \"\"\"String representation of a node by its value\"\"\"\n return str(self.value)\n\n def __repr__(self):\n \"\"\"String representation of a node by its value\"\"\"\n return str(self.value)\n\n\nclass BinarySearchTree:\n\n def __init__(self):\n # DO NOT MODIFY THIS FUNCTION #\n \"\"\"\n Initializes an empty Binary Search Tree\n \"\"\"\n self.root = None\n self.size = 0\n\n def __eq__(self, other):\n \"\"\"\n Describe equality comparison for BSTs ('==')\n :param other: BST being compared to\n :return: True if equal, False if not equal\n \"\"\"\n if self.size != other.size:\n return False\n if self.root != other.root:\n return False\n if self.root is None or other.root is None:\n return True # Both must be None\n\n if self.root.left is not None and other.root.left is not None:\n r1 = self._compare(self.root.left, other.root.left)\n else:\n r1 = (self.root.left == other.root.left)\n if self.root.right is not None and other.root.right is not None:\n r2 = self._compare(self.root.right, other.root.right)\n else:\n r2 = (self.root.right == other.root.right)\n\n result = r1 and r2\n return result\n\n def _compare(self, t1, t2):\n \"\"\"\n Recursively compares two trees, used in __eq__.\n :param t1: root node of first tree\n :param t2: root node of second tree\n :return: True if equal, False if nott\n \"\"\"\n if t1 is None or t2 is None:\n return t1 == t2\n if t1 != t2:\n return False\n result = self._compare(t1.left, t2.left) and self._compare(t1.right, t2.right)\n return result\n\n ### Implement/Modify the functions below ###\n\n def insert(self, value):\n \"\"\"\n Take a value and insert it into the proper position of the tree\n :param value: the value of the node to be inserted\n :return: No return value\n \"\"\"\n\n if self.root is None: # If tree is empty, set the root to the value provided\n self.root = Node(value)\n self.size += 1\n else:\n parent = self.search(value, self.root) # Get parent node of value\n # Now 'parent' is the parent node of where value is to be inserted\n if value < parent.value: # If value < parent node value, insert into left subtree\n # print value, \"goes to the left subtree of\", parent\n parent.left = Node(value)\n parent.left.parent = parent\n self.size += 1\n if value > parent.value: # If value > parent node value, insert into left subtree\n # print value, \"goes to the right subtree of\", parent\n parent.right = Node(value)\n parent.right.parent = parent\n self.size += 1\n\n def remove(self, value):\n \"\"\"\n Removes a node with the provided value. If node is not in the tree, do nothing.\n :param value: Value of node to be removed\n :return: No return\n \"\"\"\n temp = self.root\n node = self.search(value, temp)\n\n if node is None or node.value != value or self.size == 0 or temp is None:\n return\n\n if self.size == 1 and value == self.root.value: # If removing the only node in the tree\n self.root = None\n self.size -= 1\n return\n\n if temp.value != value: # If not removing the root node\n while temp is not None: # Move down the tree until a leaf node is reached\n parent = temp\n if temp.left is not None and temp.left.value == value:\n break\n if temp.right is not None and temp.right.value == value:\n break\n if value < temp.value:\n temp = temp.left\n continue\n if value > temp.value:\n temp = temp.right\n continue\n else: # If removing root node, parent is none\n parent = None\n\n if node.left is not None and node.right is not None: # Two children\n # When removing a node with two children, replace with the minimum of the right subtree\n min_parent = node\n min_node = node.right\n\n while min_node.left is not None: # Get min and parent of min\n min_parent = min_node\n min_node = min_node.left\n\n node.value = min_node.value\n node.parent = parent\n\n if min_parent.left == min_node:\n min_parent.left = min_node.right\n else:\n min_parent.right = min_node.right\n\n elif node.left is None and node.right is None: # If no children\n if parent.left == node:\n parent.left = None\n else:\n parent.right = None\n else: # If one child\n if node.left is None:\n holder = node.right\n else:\n holder = node.left\n if parent is None: # Removing root node\n if self.root.left is None:\n self.root = self.root.right\n self.root.parent = None\n elif self.root.right is None:\n self.root = self.root.left\n self.root.parent = None\n else:\n if parent.left is node:\n holder.parent = parent\n parent.left = holder\n else:\n holder.parent = parent\n parent.right = holder\n self.size -= 1\n\n def search(self, value, node):\n \"\"\"\n Searches the tree for a given value starting at a provided node. If value is found,\n return the node it is found it. Otherwise, return the parent node of where that value\n would be inserted. Must be recursive.\n :param value: Value to search for\n :param node: The root node of the given tree/subtree\n :return: Returns the node with the matching key (if found)\n If not found, return the parent node of where it would go.\n \"\"\"\n if node is None: # Accounts for an empty list being searched\n return None\n if value == node.value: # if value is found (base case)\n return node\n if value > node.value:\n if node.right is None:\n return node # if next node is none (base case)\n return self.search(value, node.right)\n if value < node.value:\n if node.left is None:\n return node # if next node is none (base case)\n return self.search(value, node.left)\n\n # Iterative version. Made and used to help turn function recursive.\n # while node is not None: # Move down the tree until a leaf node is reached\n # parent = node # Keep parent at the previous node\n # if value == node.value: # if value is already in the list, do nothing\n # break\n # if value > node.value:\n # node = node.right\n # elif value < node.value:\n # node = node.left\n # return parent\n\n def inorder(self, node):\n \"\"\"\n Returns a generator object of the tree traversed using the inorder method.\n Must be recursive.\n :param node: Node to begin at (root)\n :return: returns a generator object\n \"\"\"\n if node is not None:\n\n for item in self.inorder(node.left):\n yield item\n\n yield node.value\n\n for item in self.inorder(node.right):\n yield item\n\n def preorder(self, node):\n \"\"\"\n Returns a generator object of the tree traversed using the preorder method.\n Must be recursive.\n :param node: Node to begin at (root)\n :return: returns a generator object\n \"\"\"\n if node is not None:\n\n yield node.value\n\n for item in self.preorder(node.left):\n yield item\n for item in self.preorder(node.right):\n yield item\n\n def postorder(self, node):\n \"\"\"\n Returns a generator object of the tree traversed using the postorder method.\n Must be recursive.\n :param node: Node to begin at (root)\n :return: returns a generator object\n \"\"\"\n if node is not None:\n\n for item in self.postorder(node.left):\n yield item\n for item in self.postorder(node.right):\n yield item\n\n yield node.value\n\n def depth(self, value):\n \"\"\"\n Gets and returns the depth of the node with the given value\n :param value: Value of node to get depth of\n :return: The depth of the tree at the given value\n \"\"\"\n if self.size == 1:\n return 0\n if self.size == 0:\n return -1\n node = self.root\n total = 0\n while node is not None:\n if node.value == value:\n return total\n if value < node.value:\n if node.right is None: # Value not in tree\n return -1\n node = node.left\n total += 1\n if value > node.value:\n if node.right is None: # Value not in tree\n return -1\n node = node.right\n total += 1\n\n def height(self, node):\n \"\"\"\n Returns the height of the tree rooted at the given node. Must be recursive.\n :param node: Node to begin counting at (root)\n :return: The height of tree starting at the given node\n \"\"\"\n if node is None: # Base case\n return -1\n\n left = self.height(node.left) # Get height of left and right subtree\n right = self.height(node.right)\n\n if left > right: # Use the bigger of the two heights\n return left + 1\n else:\n return right + 1\n\n def min(self, node):\n \"\"\"\n Returns the minimum node of the tree rooted at the given node. Must be recursive.\n :param node: Node to begin searching for minimum at (root)\n :return: The minimum node of the tree\n \"\"\"\n if self.root is None:\n return None\n if node.left is not None:\n return self.min(node.left)\n return node\n\n def max(self, node):\n \"\"\"\n Returns the maximum node of the tree rooted at the given node. Must be recursive.\n :param node: Node to begin searching for maximum at (root)\n :return: The maximum node of the tree\n \"\"\"\n if self.root is None:\n return None\n if node.right is not None:\n return self.max(node.right)\n return node\n\n def get_size(self):\n \"\"\"\n Returns the number of nodes in the tree\n :return: Size of tree (number of nodes)\n \"\"\"\n return self.size\n\n def is_perfect(self, node):\n \"\"\"\n Determines whether or not the tree is perfect (using the provided node as the root node)\n :param node: Node to begin at (root)\n :return: A bool of whether the tree is perfect or not\n \"\"\"\n\n if self.root is None:\n return True\n elif self.root is not None and node is None:\n return\n\n height = self.height(node)\n total = (2**(height+1))-1\n\n new_size = self.curr_size(node)\n\n return total == new_size\n\n def is_degenerate(self):\n \"\"\"\n Determines whether or not the tree is degenerate\n :return: A bool of whether the tree is degenerate or not\n \"\"\"\n if self.root is None:\n return False\n\n node = self.root\n\n while node is not None:\n if node.left is not None and node.right is not None: # If node has 2 children\n return False\n if node.left is None and node.right is not None: # If node has 1 child, continue loop\n node = node.right\n continue\n if node.left is not None and node.right is None: # If node has 1 child, continue loop\n node = node.left\n continue\n if node.left is None and node.right is None: # If leaf node is reached, return True\n return True\n\n def curr_size(self, node):\n \"\"\"\n Gets the size of a tree using \"node\" as the provided root\n :param node: Node to use as root\n :return: Size of tree using provided node as the root\n \"\"\"\n if node is None:\n return 0\n else:\n return self.curr_size(node.right) + self.curr_size(node.left) + 1\n","sub_path":"Projects/Project6/BinarySearchTree.py","file_name":"BinarySearchTree.py","file_ext":"py","file_size_in_byte":13685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"270134370","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport random\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\n\n\n#images are 28x28, (784px total)\n#pixel values are int from 0~255 indicating lightness or darkness\n\n#train dataset has 785 col. first col is label, digit drawn by the user\n#Rest of the col contain pixel-values of associated image\n#each pixel col has name like pexelx where x is from 0~783 inclusive.\n#\n\nmnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n\n#params\ntraining_epochs = 1000\nbatch_size = 100\nlearning_rate = 0.001\nnode_n = 256\n\nnb_classes = 10\n\n#28 * 28 = 784\nX = tf.placeholder(tf.float32, [None, 784])\n# 0~9 digits, 10 classes\nY = tf.placeholder(tf.float32, [None, nb_classes])\n\n#layer1\nW1 = tf.Variable(tf.random_normal([784, node_n]))\nb1 = tf.Variable(tf.random_normal([node_n]))\nlayer1 = tf.nn.relu(tf.matmul(X, W1) + b1)\n\n#layer2\nW2 = tf.Variable(tf.random_normal([node_n, node_n]))\nb2 = tf.Variable(tf.random_normal([node_n]))\nlayer2 = tf.nn.relu(tf.matmul(layer1, W2) + b2)\n\n#layer3\nW3 = tf.Variable(tf.random_normal([node_n,10]))\nb3 = tf.Variable(tf.random_normal([nb_classes]))\n#Hypothesis using softmax\nhypothesis = (tf.matmul(layer2, W3) + b3)\n\n#cross-entropy of onehot Y\ncost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=hypothesis, labels=Y))\noptimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)\n\n# testing\nis_correct = tf.equal(tf.argmax(hypothesis, 1), tf.argmax(Y,1))\naccuracy = tf.reduce_mean(tf.cast(is_correct, tf.float32))\n\n\nwith tf.Session() as sess:\n #init TF variable\n sess.run(tf.global_variables_initializer())\n #training cycle\n for epoch in range(training_epochs):\n avg_cost = 0\n total_batch = int(mnist.train.num_examples / batch_size )\n\n for i in range(total_batch):\n batch_xs, batch_ys = mnist.train.next_batch(batch_size)\n c, _ = sess.run([cost, optimizer], feed_dict={X: batch_xs, Y:batch_ys})\n avg_cost += c / total_batch\n print('Epoch:', '%04d' % (epoch + 1), 'cost = ', '{:.9f}'.format(avg_cost))\n\n #Creates batches of 100 because there is no need for all data to be on memory\n batch_xs, batch_ys = mnist.train.next_batch(100)\n\n print(\"acc: \", accuracy.eval(session=sess, feed_dict={X: mnist.test.images, Y: mnist.test.labels}))\n #predict 1 sample\n r = random.randint(0, mnist.test.num_examples-1)\n print(\"Label: \", sess.run(tf.argmax(mnist.test.labels[r:r + 1], 1)))\n print(\"prediction: \", sess.run(tf.argmax(hypothesis, 1), feed_dict={X: mnist.test.images[r:r + 1]}))\n\n plt.imshow( \n mnist.test.images[r:r + 1].reshape(28, 28),\n cmap='Greys',\n interpolation='nearest')\n plt.show()\n","sub_path":"relu_mnist.py","file_name":"relu_mnist.py","file_ext":"py","file_size_in_byte":2777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"227234809","text":"import numpy as np\r\n\r\n\r\n#Tree Structure\r\n#class definition\r\n\r\nclass TreeNode:\r\n \r\n def __init__(self,boxsize=0,mass=1,coord=np.zeros([2]),level=0):\r\n #boxsize is a diameter of the box in 2norm\r\n #mass and coord -- obvious\r\n #level is tree depth, level=0 corresponds to root\r\n\r\n self.mass=mass\r\n self.coord=coord\r\n self.children=[]\r\n self.level=level\r\n self.boxsize=boxsize\r\n \r\n \r\n def addChild(self,child):\r\n self.children.append(child)\r\n \r\n def recomputeValues(self):\r\n if(len(self.children)>0):\r\n [self.children[k].recomputeValues for k in np.arange(len(self.children))]#faster\r\n self.mass = 0\r\n self.coord = -1\r\n for child in self.children:\r\n try:\r\n if self.coord.shape:#if it is not -1\r\n self.mass = self.mass + child.mass #really????\r\n self.coord = self.coord+ child.coord*child.mass\r\n except:\r\n self.mass = child.mass\r\n self.coord = child.coord * child.mass\r\n \r\n \r\n self.coord = self.coord / self.mass\r\n else:\r\n return self.coord, self.mass\r\n \r\n\r\n def getNumberOfNodes(self):\r\n if(len(self.children)==0):\r\n return 1\r\n else:\r\n res=1 #count this particular node\r\n for child in self.children:\r\n res=res+ child.getNumberOfNodes()\r\n \r\n return res \r\n \r\n\r\n\r\n\r\n#CONSTRUCTION\r\n\r\n# Tree Construction\r\n\r\ndef AssignParticlesToClusters(locs,seps):\r\n #locs: d X N locations\r\n #seps: N separators\r\n clIds = np.zeros([locs.shape[1]])\r\n for locId in np.arange(locs.shape[1]):\r\n ind=(locs[:,locId]-seps >=0).astype('int32')\r\n ind=str(ind.tolist())[1:-1].replace(' ','')\r\n ind=ind.replace(',','')\r\n clIds[locId]=int( ind, base=2)\r\n \r\n return clIds\r\n \r\ndef ConstructTree(xs,ms,root,level):\r\n #xs is array d X N, N is number of particles, d is dimension\r\n \r\n \r\n if(len(xs.shape)==1 or xs.shape[1]==1):\r\n #1 particle, leave it\r\n root.mass = ms\r\n #print('construct root.coord=',xs)\r\n root.coord = xs\r\n root.level = level\r\n \r\n return root\r\n \r\n #Otherwise go recursively\r\n \r\n xMin = np.amin(xs,axis=1)\r\n xMax = np.amax(xs,axis=1)\r\n separators = (xMin + xMax)/2 # QuadTree\r\n clusters = AssignParticlesToClusters(xs,separators)\r\n \r\n clIds = np.unique(clusters)\r\n \r\n for clId in clIds:\r\n clKeys = (clusters==clId)\r\n child = TreeNode(boxsize=np.linalg.norm(xMax-separators,2),level=level+1)\r\n child=ConstructTree(np.squeeze(xs[:,clKeys]),ms[clKeys],child,level+1)\r\n child.recomputeValues()\r\n root.addChild(child)\r\n \r\n return root\r\n\r\ndef DeepTraverse(root): #depth traversal\r\n \r\n if(len(root.children)==0):\r\n return\r\n \r\n for c in root.children:\r\n print(c.level,c.mass,c.coord)\r\n DeepTraverse(c)\r\n\r\n## working EXAMPLE!!\r\n\r\n#xs = np.array([[0,1,0,1,1.2,1.25],[0,0.75,1,1,1,0.9]])\r\n#ms= np.array([1,2,3,4,5,6])\r\n\r\n#treeRoot = TreeNode()\r\n#treeRoot=ConstructTree(xs,ms,treeRoot,level=0) \r\n","sub_path":"ps1/quadtrees.py","file_name":"quadtrees.py","file_ext":"py","file_size_in_byte":3345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"442952514","text":"import os\n\nimport numpy as np\nimport tables as tb\n\nfrom pytest import mark\n\nfrom . rwf_io import rwf_writer\n\n\n@mark.parametrize(\"group_name\", (None, 'RD', 'BLR'))\ndef test_rwf_writer(config_tmpdir, group_name):\n\n nevt = 3\n nsensor = 3\n nsample = 10\n table_name = 'testwf'\n\n ofile = os.path.join(config_tmpdir, 'testRWF.h5')\n\n test_data = np.random.randint(10, size = (nevt, nsensor, nsample))\n\n with tb.open_file(ofile, \"w\") as h5out:\n rwf_writer_ = rwf_writer(h5out,\n group_name = group_name,\n table_name = table_name,\n n_sensors = nsensor,\n waveform_length = nsample)\n\n for evt in test_data:\n rwf_writer_(evt)\n\n with tb.open_file(ofile) as h5test:\n if group_name is None:\n group = h5test.root\n else:\n group = getattr(h5test.root, group_name)\n\n\n assert table_name in group\n\n table = getattr(group, table_name)\n assert table.shape == (nevt, nsensor, nsample)\n assert np.all(test_data == table.read())\n","sub_path":"invisible_cities/io/rwf_io_test.py","file_name":"rwf_io_test.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"131641787","text":"import pytest\nimport pandas as pd\nfrom collections import OrderedDict\nimport os.path\n\nfrom .luck import luck_factor\n\n\nSCRIPT_DIR = os.path.abspath(os.path.dirname(__file__))\n\n\nclass Case(object):\n def __init__(self, coins, symbol, start_date, end_date, expected):\n self.coins = coins\n self.symbol = symbol\n self.start_date = start_date\n self.end_date = end_date\n self.expected = expected\n\n\nCOINS = pd.read_csv(os.path.join(SCRIPT_DIR, 'coins.csv'))\nCOINS['datetime'] = pd.to_datetime(COINS['date'])\nCOINS.set_index('datetime', inplace=True)\n\n\nTEST_CASES = OrderedDict([\n (\n \"test_case_0\",\n Case(\n coins=pd.DataFrame(\n data=[\n ['BTC', 15404.8, 17513.9, '2017-12-11'],\n ['BTC', 16571.6, 17781.8, '2017-12-12'],\n ['BTC', 16039.7, 17653.1, '2017-12-13']],\n columns=['symbol', 'low', 'high', 'date'],\n index=pd.to_datetime(['2017-12-11', '2017-12-12', '2017-12-13'])\n ),\n symbol='BTC',\n start_date='2017-12-11',\n end_date='2017-12-13',\n expected=1.342650014778795\n )\n ),\n (\n \"test_case_1\",\n Case(\n coins=COINS,\n symbol='BTC',\n start_date='2017-12-11',\n end_date='2017-12-13',\n expected=1.342650014778795\n )\n ),\n (\n \"test_case_2\",\n Case(\n coins=COINS,\n symbol='PPT',\n start_date='2017-09-01',\n end_date='2018-01-10',\n expected=363502397080.77655\n )\n ),\n (\n \"test_case_3\",\n Case(\n coins=COINS,\n symbol='LTC',\n start_date='2017-09-11',\n end_date='2017-12-30',\n expected=110822.93933259304\n )\n ),\n (\n \"test_case_4\",\n Case(\n coins=COINS,\n symbol='ADA',\n start_date='2017-08-11',\n end_date='2017-12-30',\n expected=32104531.358640753\n )\n ),\n (\n \"test_case_5\",\n Case(\n coins=COINS,\n symbol='FUN',\n start_date='2018-04-01',\n end_date='2018-05-01',\n expected=18.464747305540669\n )\n )\n])\n\n\n@pytest.mark.parametrize(\n 'test_case',\n TEST_CASES.values(),\n ids=list(TEST_CASES.keys())\n)\ndef test_luck_factor(test_case):\n factor = luck_factor(\n test_case.coins,\n test_case.symbol,\n test_case.start_date,\n test_case.end_date)\n assert pytest.approx(factor, rel=1e-3) == test_case.expected\n","sub_path":"hw3_luck/test_public.py","file_name":"test_public.py","file_ext":"py","file_size_in_byte":2652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"529545941","text":"#!/usr/bin/python3\n\n# @Project = step_LeetCode\n# @File : 5041_Uncrossed_Lines\n# @Author : TCY\n# @Time : 2019/4/28 14:42\n# @Email : tangcaiyuan@hust.edu.cn\n# @Software: PyCharm\n\n\"\"\"直接动态规划\"\"\"\nclass Solution:\n def maxUncrossedLines(self, A, B):\n vis = []\n for i in range(len(A) + 1):\n tmp = []\n for j in range(len(B) + 1):\n tmp.append(0)\n vis.append(tmp)\n for i in range(1, len(A) + 1):\n for j in range(1, len(B) + 1):\n if A[i - 1] == B[j - 1]:\n vis[i][j] = vis[i - 1][j - 1] + 1\n else:\n vis[i][j] = max(vis[i - 1][j], vis[i][j - 1])\n return vis[-1][-1]\n","sub_path":"Weekly_Contest/Weekly_Contest_134/5041_Uncrossed_Lines.py","file_name":"5041_Uncrossed_Lines.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"47976013","text":"import numpy as np\nfrom ROI_Arrival import ROI_Arrival,ROI_Location\n#prefined imports\nimport sys,time,winsound\nimport numpy as np\nfrom PyQt5.QtWidgets import (QApplication, QPushButton,QWidget,QGridLayout,\n QSizePolicy,QLineEdit,\n QMainWindow,QAction,QVBoxLayout\n ,QDockWidget,QListView,\n QAbstractItemView,QLabel,QFileDialog,QTextEdit,\n QInputDialog,QSlider,QMdiArea,QMdiSubWindow,\n QMessageBox)\nfrom PyQt5.QtGui import QFont\nfrom PyQt5.QtCore import Qt\n#import numpy as np\nfrom matplotlib.figure import Figure\nfrom matplotlib.backends.backend_qt5agg import (\n FigureCanvas, NavigationToolbar2QT as NavigationToolbar)\n\nclass ROI_Viewer(QMainWindow):\n done=False\n def __init__(self,list_time,list_channel,sync_time,calibration):\n super().__init__()\n self.num_sync=sync_time.size\n self.num_pulses=list_time.size\n self.list_time,self.list_channel=list_time,list_channel\n self.sync_time,self.calibration=sync_time,calibration\n self.sync_delta=sync_time[2]-sync_time[1]\n self.lower,self.upper=9.5,10.9\n self.font1=QFont()\n self.font1.setPointSize(12)\n self.size_policy=QSizePolicy.Expanding\n self.menu()\n self.showMaximized()\n self.setWindowTitle('ROI Timing Arrival')\n self.geometry()\n# self.process()\n self.show()\n \n def menu(self):\n self.menuFile=self.menuBar().addMenu('&File')\n self.save_file=QAction('&Save Spectrum')\n self.save_file.triggered.connect(self.save_spectrum)\n self.save_file.setShortcut('CTRL+S')\n self.save_file.setEnabled(False)\n \n # self.save_roi=QAction('&Save ROI')\n # self.save_roi.triggered.connect(self.save_roi_csv)\n # self.save_roi.setEnabled(True)\n self.menuFile.addActions([self.save_file])\n \n def geometry(self):\n r1_label=QLabel(r'Region 1-2 divider: [us]')\n r1_label.setFont(self.font1)\n r2_label=QLabel(r'Region 2-3 divider: [us]')\n r2_label.setFont(self.font1)\n \n self.r_1_slider=QSlider(Qt.Horizontal)\n self.r_1_slider.setSizePolicy(self.size_policy,self.size_policy)\n self.r_1_slider.setMinimum(0)\n self.r_1_slider.setMaximum(self.sync_delta-1)\n self.r_1_slider.setSingleStep(1)\n self.r_1_slider.setTickInterval(50)\n self.r_1_slider.setValue(100)\n self.r_1_slider.setTickPosition(QSlider.TicksBelow)\n self.r_1_slider.valueChanged.connect(self.update_r_1)\n self.r_1_slider.setFont(self.font1)\n \n self.r_2_slider=QSlider(Qt.Horizontal)\n self.r_2_slider.setSizePolicy(self.size_policy,self.size_policy)\n self.r_2_slider.setMinimum(101)\n self.r_2_slider.setMaximum(self.sync_delta)\n self.r_2_slider.setSingleStep(1)\n self.r_2_slider.setTickInterval(50)\n self.r_2_slider.setValue(101)\n self.r_2_slider.setTickPosition(QSlider.TicksBelow)\n self.r_2_slider.valueChanged.connect(self.update_r_2)\n self.r_2_slider.setFont(self.font1)\n \n self.r_1_label=QLabel(self)\n self.r_1_label.setSizePolicy(self.size_policy,self.size_policy)\n self.r_1_label.setText(str(self.r_1_slider.value()))\n self.r_1_label.setFont(self.font1)\n self.r_2_label=QLabel(self)\n self.r_2_label.setSizePolicy(self.size_policy,self.size_policy)\n self.r_2_label.setText(str(self.r_2_slider.value())) \n self.r_2_label.setFont(self.font1)\n \n self.processer=QPushButton('Process',self)\n self.processer.clicked.connect(self.process)\n self.processer.setFont(self.font1)\n \n lower_label=QLabel('Lower ROI: [MeV]',self)\n lower_label.setFont(self.font1)\n upper_label=QLabel('Upper ROI: [MeV]',self)\n upper_label.setFont(self.font1)\n \n self.lower_text=QLineEdit(self)\n self.lower_text.setFont(self.font1)\n self.lower_text.setText(str(self.lower))\n self.upper_text=QLineEdit(self)\n self.upper_text.setFont(self.font1)\n self.upper_text.setText(str(self.upper))\n \n self.time_plot=QWidget()\n self.time_figure=Figure()\n self.time_canvas=FigureCanvas(self.time_figure)\n self.time_toolbar=NavigationToolbar(self.time_canvas,self)\n layout=QVBoxLayout()\n layout.addWidget(self.time_toolbar)\n layout.addWidget(self.time_canvas)\n self.time_plot.setLayout(layout)\n self.time_ax=self.time_canvas.figure.subplots()\n self.time_ax.set_title('Time')\n \n main_=QWidget()\n layout=QGridLayout(self)\n layout.addWidget(r1_label,0,0)\n layout.addWidget(self.r_1_slider,0,1)\n layout.addWidget(self.r_1_label,0,2)\n layout.addWidget(lower_label,0,3)\n layout.addWidget(self.lower_text,0,4)\n layout.addWidget(upper_label,1,3)\n layout.addWidget(self.upper_text,1,4)\n layout.addWidget(r2_label,1,0)\n layout.addWidget(self.r_2_slider,1,1)\n layout.addWidget(self.r_2_label,1,2)\n layout.addWidget(self.processer,2,0)\n layout.addWidget(self.time_plot,3,0,1,5)\n main_.setLayout(layout)\n self.setCentralWidget(main_)\n \n def update_r_1(self):\n self.r_2_slider.setMinimum(self.r_1_slider.value()+1)\n self.r_1_label.setText(str(self.r_1_slider.value()))\n \n def update_r_2(self):\n self.r_2_label.setText(str(self.r_2_slider.value()))\n\n def process(self):\n self.save_file.setEnabled(True)\n # self.save_roi.setEnabled(True)\n s1=time.time()\n delt=(self.sync_time[2]-self.sync_time[1])\n self.lower=float(self.lower_text.text())\n self.upper=float(self.upper_text.text())\n self.arrival,self.height,self.raw=ROI_Arrival(self.sync_time,self.list_time,\n self.num_sync,self.list_channel,\n self.num_pulses,self.lower,\n self.upper,self.calibration)\n num_bins=int(delt/4)\n bins=np.linspace(0,delt,num_bins)\n self.bins=bins\n s=len(self.arrival)\n self.output=ROI_Location(self.arrival,bins,num_bins,s)\n r1,r2,r3=0,0,0\n print('Process ROI Arrivals in {:.3f}s'.format(time.time()-s1))\n for i in range(num_bins):\n if bins[i]<=self.r_1_slider.value():\n r1+=self.output[i]\n elif bins[i]>self.r_1_slider.value() and bins[i]<=self.r_2_slider.value():\n r2+=self.output[i]\n else:\n r3+=self.output[i]\n \n self.time_ax.clear()\n self.time_ax.plot(bins,self.output,'r*')\n self.time_ax.axvline(self.r_1_slider.value(),label='Region 1-2 divider at {:.2f}'.format(self.r_1_slider.value()))\n self.time_ax.axvline(self.r_2_slider.value(),label='Region 2-3 divider at {:.2f}'.format(self.r_2_slider.value()))\n# self.time_ax.set_yscale('log')\n self.time_ax.set_ylabel('Counts',fontsize=18)\n self.time_ax.set_xlabel(r'Arrival Time [$\\mu s$]',fontsize=18)\n self.time_canvas.draw()\n self.done=True\n self.percentages=[r1/(r1+r2+r3)*100,\n r2/(r1+r2+r3)*100,\n r3/(r1+r2+r3)*100]\n QMessageBox.information(self,\n 'ROI Perecentages','''Region 1:{:.2f}%\\nRegion 2:{:.2f}%\\nRegion 3:{:.2f}%'''.format(\n r1/(r1+r2+r3)*100,\n r2/(r1+r2+r3)*100,r3/(r1+r2+r3)*100),\n QMessageBox.Ok)\n# print('Region 1 total ROI percentage: {:.2f}%'.format(r1/(r1+r2+r3)*100))\n# print('Region 2 total ROI percentage: {:.2f}%'.format(r2/(r1+r2+r3)*100))\n# print('Region 3 total ROI percentage: {:.2f}%'.format(r3/(r1+r2+r3)*100))\n \n def save_spectrum(self):\n name=QFileDialog.getSaveFileName(self,'File Name','',\n 'Text File (*.txt);;Comma Seperated File (*.csv)')\n if name[0]!=' ':\n f=open(name[0],'w')\n f.write('%{:.2f},{:.2f},{:.2f}\\n'.format(*self.percentages))\n for i in range(len(self.bins)):\n f.write('{:.6f},{}\\n'.format(self.bins[i],self.output[i]))\n f.close()\n \n # def save_roi_csv(self):\n # name,ok=QFileDialog.getSaveFileName(self,'Safe File Name','',\n # 'Comma Seperated File (*.csv)')\n # if ok:\n # f=open(name,'w')\n # f.write('Pulse_Height(MeV),Time(s)\\n')\n # print(len(self.height))\n # for i in range(len(self.height)):\n # f.write('{:.3f},{:.3f}\\n'.format(self.height[i],self.raw[i]*1e-6))\n # f.close()\n # print('All finished')","sub_path":"ROI_Arrival_Viewer.py","file_name":"ROI_Arrival_Viewer.py","file_ext":"py","file_size_in_byte":9050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"524079112","text":"import random\r\n\r\ndef esPar(num):\r\n return num % 2 == 0\r\n\r\n\r\nlista = [random.randint(1,100) for i in range(50)]\r\nprint(lista)\r\n\r\npares = filter(esPar,lista)\r\nmultiplos3 = filter(lambda x : x % 3 == 0,lista)\r\nlistaPares = list(pares)\r\nprint(listaPares)\r\n\r\nfor x in multiplos3:\r\n print(x, end=\" \")","sub_path":"Practica 2/Practica Clase 4/EjFilter.py","file_name":"EjFilter.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"614683292","text":"from __future__ import absolute_import\nfrom __future__ import print_function\n\n\n# -----------------------------------------------------------------------------\n# Imports\n# -----------------------------------------------------------------------------\nimport threading\nimport logging\n\nimport readline\n\nfrom builtins import input\n\nlogger = logging.getLogger(__name__)\n\nclass CLI(object):\n input_func = input\n\n def __init__(self, options=None, namespace=None, quit_func=None):\n cls = self.__class__\n self._cli_thread = None\n self._options = options\n if namespace is None:\n namespace = dict(__lock=threading.Lock())\n self.namespace = namespace\n if not hasattr(namespace, '__lock'):\n namespace.update(dict(__lock=threading.Lock()))\n self._lock = namespace['__lock']\n self._quit_function = quit_func\n\n def set_quit_function(self, func):\n self._quit_function = func\n\n\n def run(self):\n \"\"\" allows to run an ipython shell with the CLI's context vars \"\"\"\n namespace = self.namespace\n try:\n from IPython.terminal.embed import InteractiveShellEmbed\n use_ipython = True\n logger.debug(\"CLI using ipython\")\n except ImportError:\n use_ipython = False\n logger.debug(\"CLI using basic fallback\")\n\n if use_ipython:\n shell = InteractiveShellEmbed(user_ns=namespace)\n shell()\n\n else:\n self.mini_shell(namespace=namespace)\n\n if self._quit_function:\n try:\n self._quit_function(self)\n except TypeError:\n logger.warning(\"using obsolete quit function without argument\")\n self._quit_function()\n\n def mini_shell(self, namespace):\n \"\"\" Rather lousy Python shell for debugging.\n Just in case ipython is not installed or has the wrong version\n \"\"\"\n while True:\n cmd_line = self.input_func('-->')\n upper_stripped = cmd_line.strip().upper()\n shall_quit = (upper_stripped == 'Q' or upper_stripped == 'QUIT')\n if shall_quit:\n break\n try:\n eval(compile(cmd_line, '', 'single'), namespace) # pylint: disable=W0122,C0301\n except Exception as exc: # pylint: disable=W0703\n logger.error('ERROR: %r' % exc)\n\n print(\"END OF CLI\")\n self.write_history()\n\n def write_history(self, fname=None):\n pass\n\n def run_as_thread(self, name='cli', daemon=True):\n \"\"\" start cli as a thread\n This is needed for Qt Apps, where the GUI must be called in the main thread\n \"\"\"\n self._cli_thread = cli_thread = threading.Thread(target=self.run,\n name=name)\n cli_thread.daemon = daemon\n cli_thread.start()\n\ndef main():\n pass\n\nif __name__ == '__main__':\n main()\n# -----------------------------------------------------------------------------\n# End of file\n# -----------------------------------------------------------------------------\n","sub_path":"mytb/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":3117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"543139371","text":"# coding=utf-8\n# 这是为twitter(PC站)镜像配置的示例配置文件\n#\n# 使用方法:\n# 1. 复制本文件到 zmirror 根目录(wsgi.py所在目录), 并重命名为 config.py\n# 2. 修改 my_host_name 为你自己的域名\n#\n# 各项设置选项的详细介绍请看 config_default.py 中对应的部分\n# 本配置文件假定你的服务器本身在墙外\n# 如果服务器本身在墙内(或者在本地环境下测试, 请修改`Proxy Settings`中的设置\n#\n# 由于twitterPC和twitterMobile实际上是相互独立的, 而且由于逻辑非常复杂, 即使使用镜像隔离功能, 也会导致手机站不正常\n# 所以把twitterPC和twitterMobile分成两个配置文件\n# 使用本配置文件运行的twitter镜像, 支持所有的twitter功能(暂时还没发现不能用的功能)\n#\n# ########################################\n# 警告: twitter镜像在非https环境下可能会无法注册, 其他功能也可能会出现问题, 请在https环境下部署twitter镜像\n# ########################################\n#\n#\n# ############## Local Domain Settings ##############\nmy_host_name = '127.0.0.1'\nmy_host_scheme = 'http://'\n\n# ############## Target Domain Settings ##############\ntarget_domain = 'twitter.com'\ntarget_scheme = 'https://'\n\n# 这里面大部分域名都是通过 `enable_automatic_domains_whitelist` 自动采集的, 我只是把它们复制黏贴到了这里\n# 实际镜像一个新的站时, 手动只需要添加很少的几个域名就可以了.\n# 自动采集会不断告诉你新域名\nexternal_domains = [\n 'mobile.twitter.com',\n\n 't.co',\n 'dev.twitter.com',\n 'ads.twitter.com',\n 'analytics.twitter.com',\n 'pic.twitter.com',\n 'api.twitter.com',\n 'platform.twitter.com',\n 'upload.twitter.com',\n 'ton.twitter.com',\n 'support.twitter.com',\n 'about.twitter.com',\n 'tweetdeck-devel.atla.twitter.com',\n 'tweetdeck-devel.smf1.twitter.com',\n 'tdapi-staging.smf1.twitter.com',\n 'tweetdeck.localhost.twitter.com',\n 'tweetdeck.twitter.com',\n 'tdapi-staging.atla.twitter.com',\n 'localhost.twitter.com',\n 'donate.twitter.com',\n 'syndication.twitter.com',\n 'status.twitter.com',\n 'engineering.twitter.com',\n 'help.twitter.com',\n 'blog.twitter.com',\n 'business.twitter.com',\n 'cards-dev.twitter.com',\n\n 'caps.twitter.com',\n 'quickread.twitter.com',\n 'tailfeather.twimg.com',\n 'publish.twitter.com',\n 'brand.twitter.com',\n 't.lv.twimg.com',\n 'media.twitter.com',\n\n 'g2.twimg.com',\n 'hca.twimg.com',\n 'g.twimg.com',\n 'video.twimg.com',\n 'ma.twimg.com',\n 'abs.twimg.com',\n 'pbs.twimg.com',\n 'ton.twimg.com',\n 'ma-0.twimg.com',\n 'ma-1.twimg.com',\n 'ma-2.twimg.com',\n 'o.twimg.com',\n 'abs-0.twimg.com',\n 'abs-1.twimg.com',\n 'abs-2.twimg.com',\n 'amp.twimg.com',\n\n 'www.google.com',\n 'ssl.gstatic.com',\n 'www.gstatic.com',\n 'apis.google.com',\n 'encrypted-tbn0.gstatic.com',\n 'encrypted-tbn1.gstatic.com',\n 'encrypted-tbn2.gstatic.com',\n 'encrypted-tbn3.gstatic.com',\n 'accounts.google.com',\n 'accounts.youtube.com',\n 'fonts.googleapis.com',\n]\n\nforce_https_domains = 'ALL'\n\nenable_automatic_domains_whitelist = True\ndomains_whitelist_auto_add_glob_list = ('*.twitter.com', '*.twimg.com',)\n\n# ############## Proxy Settings ##############\n# 如果你在墙内使用本配置文件, 请指定一个墙外的http代理\nis_use_proxy = False\n# 代理的格式及SOCKS代理, 请看 http://docs.python-requests.org/en/latest/user/advanced/#proxies\nrequests_proxies = dict(\n http='http://127.0.0.1:8123',\n https='https://127.0.0.1:8123',\n)\n\ntext_like_mime_keywords = ('text', 'json', 'javascript', 'xml', 'x-mpegurl')\n\n# ############## Misc ##############\n# 不加这个似乎也没影响的样子..... 不过以防万一还是加上吧\ncustom_allowed_remote_headers = {\n 'access-control-allow-credentials', 'access-control-allow-headers', 'access-control-allow-methods',\n 'access-control-max-age', 'access-control-allow-origin', 'x-connection-hash'}\n","sub_path":"more_configs/config_twitter_pc.py","file_name":"config_twitter_pc.py","file_ext":"py","file_size_in_byte":4063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"247089853","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom layers import Conv3x3, Conv1x1, ConvT_UNet\n\n\nclass UNet(nn.Module):\n \"\"\"\n 设down4的输出边长为u,我算出image的边长为16u+124, 输出边长为16u-60\n 故输入边长应为16u+124,其中u为>=4的整数\n 推荐输入边长为510,则对应的输出边长为418\n \"\"\"\n\n class UNetDoubleConv(nn.Module):\n\n def __init__(self, in_ch: int, out_ch: int, bn: bool = True, acv: str = 'relu'):\n super().__init__()\n self.conv1 = Conv3x3(in_ch=in_ch, out_ch=out_ch, bn=bn, acv=acv)\n self.conv2 = Conv3x3(in_ch=out_ch, out_ch=out_ch, bn=bn, acv=acv)\n\n def forward(self, x):\n # x = self.pad(x)\n x = self.conv1(x)\n x = self.conv2(x)\n return x\n\n class UNetEncoderBlock(nn.Module):\n\n def __init__(self, in_ch, out_ch, pool: bool = True):\n super().__init__()\n self.down = nn.MaxPool2d(kernel_size=2) if pool else nn.Identity()\n self.conv = UNet.UNetDoubleConv(in_ch, out_ch)\n\n def forward(self, x):\n x = self.down(x)\n x = self.conv(x)\n return x\n\n class UNetDecoderBlock(nn.Module):\n\n def __init__(self, in_ch, out_ch, mode='bilinear'):\n super().__init__()\n mode = mode.lower()\n if mode in ['bilinear', 'interpolation']:\n self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)\n else:\n self.up = ConvT_UNet(in_ch=in_ch // 2, out_ch=in_ch // 2, mag=2)\n self.conv = UNet.UNetDoubleConv(in_ch, out_ch)\n\n def forward(self, x0, shortcut):\n # x0和shortcut的通道数相等,加起来等于in_ch\n x0 = self.up(x0)\n dh = shortcut.size()[2] - x0.size()[2]\n dw = shortcut.size()[3] - x0.size()[3]\n\n pad = [dw // 2, dw - dw // 2, dh // 2, dh - dh // 2] # 顺序:左右上下\n x0 = F.pad(x0, pad=pad) # 把x0补充或裁剪到和shortcut一样尺寸\n\n x = torch.cat([shortcut, x0], dim=1)\n x = self.conv(x)\n\n return x\n\n def __init__(self, image_ch=3, out_classes=1):\n super().__init__()\n\n self.en0 = UNet.UNetEncoderBlock(in_ch=image_ch, out_ch=64, pool=False)\n self.en1 = UNet.UNetEncoderBlock(in_ch=64, out_ch=128)\n self.en2 = UNet.UNetEncoderBlock(in_ch=128, out_ch=256)\n self.en3 = UNet.UNetEncoderBlock(in_ch=256, out_ch=512)\n self.en4 = UNet.UNetEncoderBlock(in_ch=512, out_ch=512)\n\n self.de1 = UNet.UNetDecoderBlock(in_ch=1024, out_ch=256)\n self.de2 = UNet.UNetDecoderBlock(in_ch=512, out_ch=128)\n self.de3 = UNet.UNetDecoderBlock(in_ch=256, out_ch=64)\n self.de4 = UNet.UNetDecoderBlock(in_ch=128, out_ch=64)\n self.conv1x1 = Conv1x1(in_ch=64, out_ch=out_classes, acv='sigmoid') # 合并特征通道,同时纠正relu带来的偏置\n\n def forward(self, image):\n x0 = self.en0(image)\n x1 = self.en1(x0)\n x2 = self.en2(x1)\n x3 = self.en3(x2)\n x4 = self.en4(x3)\n x = self.de1(x4, x3)\n x = self.de2(x, x2)\n x = self.de3(x, x1)\n x = self.de4(x, x0)\n x = self.conv1x1(x)\n return x\n","sub_path":"model_diy.py","file_name":"model_diy.py","file_ext":"py","file_size_in_byte":3318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"377290999","text":"import os\nimport gensim.downloader as api\nfrom gensim.models.doc2vec import Doc2Vec\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\nimport pandas as pd\n\nfrom modAL.uncertainty import uncertainty_sampling, margin_sampling, entropy_sampling\n\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\n\nROOT = os.path.abspath( os.path.dirname( __file__ ) )\nDATA_PATH = os.path.join( ROOT, '..', 'data' )\n\nfrom sio_server import Server\n\nt_path = os.path.abspath(os.path.join(DATA_PATH, \"processed\", \"t-davidson_processed.pkl\"))\np_path = os.path.abspath(os.path.join(DATA_PATH, \"processed\", \"personal_processed.pkl\"))\n\ndef main():\n t_davidson = pd.read_pickle(t_path)\n personal = pd.read_pickle(p_path)\n #%% ----------------------------------------------------------------word embeddings\n print(\"downloading pre-trained GloVe model...\")\n glove = api.load('glove-twitter-25')\n print(\"done.\")\n #%% ----------------------------------------------------------------doc2vec\n doc2vec = Doc2Vec(vector_size=50, min_count=2, epochs=10)\n #%% ----------------------------------------------------------------tfidf\n tfidf = TfidfVectorizer(\n ngram_range=(1, 3),\n max_features=8000,\n min_df=1,\n max_df=0.75\n )\n #%% ----------------------------------------------------------------\n options = {\n 'classifiers': [\n {'name': 'Logistic Regression', 'classifier': LogisticRegression(class_weight='balanced', solver='liblinear', random_state=42)},\n {'name': 'Linear SVM', 'classifier': SVC(class_weight='balanced', kernel='linear', probability=True, random_state=42)},\n {'name': 'Random Forest', 'classifier': RandomForestClassifier(class_weight='balanced', random_state=42, n_jobs= -1)},\n {'name': 'K Nearest Neighbors', 'classifier': KNeighborsClassifier(n_neighbors=2, n_jobs= -1)}],\n 'datasets': [\n {'name': 'T Davidson Hate Speech/Offensive Language',\n 'df': t_davidson,\n 'targets': [\n {'val': 0,'name': 'hate speech'},\n {'val': 1,'name': 'offensive language'},\n {'val': 2,'name': 'neither'}]\n },\n {'name': 'Project Dataset',\n 'df': personal,\n 'targets': [\n {'val': 0,'name': 'non-malicious'},\n {'val': 1,'name': 'malicious'}]\n }],\n 'vectorizers': [\n {'name': 'TF IDF Vectorizer', 'vectorizer': tfidf},\n {'name': 'GloVe Word Embeddings', 'vectorizer': glove},\n {'name': 'Doc2Vec Paragraph Embeddings', 'vectorizer': doc2vec}],\n 'features': [\n {'name': 'text', 'cols': [('tweet', 'tweet')]},\n {'name': 'user', 'cols': [('user_is_verified', 'bool'),\n ('user_posts', 'numeric'),\n ('user_likes','numeric'),\n ('user_followers', 'numeric'),\n ('user_friends', 'numeric')]},\n {'name': 'stats', 'cols': [('emoji_count', 'numeric'),\n ('polarity', 'numeric'),\n ('subjectivity', 'numeric'),\n ('hashtag_count', 'numeric'),\n ('mentions_count', 'numeric'),\n ('words_count', 'numeric'),\n ('char_count', 'numeric'),\n ('url_count', 'numeric'),\n ('is_retweet', 'bool'),\n ('tweet_likes', 'numeric'),\n ('tweet_retweets', 'numeric'),\n ('tweet_is_quote', 'bool')]}],\n 'query_strategies': [\n {'name': 'Uncertainty Sampling', 'strategy': uncertainty_sampling},\n {'name': 'Entropy Sampling', 'strategy': entropy_sampling},\n {'name': 'Margin Sampling', 'strategy': margin_sampling}],\n }\n Server(options=options).run()\n\nif __name__ == '__main__': main()","sub_path":"backend/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"195193404","text":"from collections.abc import MutableSequence\nfrom typing import Any\n\nimport proto\n\nfrom google.ads.googleads.v14.enums.types.customer_match_upload_key_type import (\n CustomerMatchUploadKeyTypeEnum,\n)\nfrom google.ads.googleads.v14.enums.types.user_list_crm_data_source_type import (\n UserListCrmDataSourceTypeEnum,\n)\nfrom google.ads.googleads.v14.enums.types.user_list_date_rule_item_operator import (\n UserListDateRuleItemOperatorEnum,\n)\nfrom google.ads.googleads.v14.enums.types.user_list_flexible_rule_operator import (\n UserListFlexibleRuleOperatorEnum,\n)\nfrom google.ads.googleads.v14.enums.types.user_list_logical_rule_operator import (\n UserListLogicalRuleOperatorEnum,\n)\nfrom google.ads.googleads.v14.enums.types.user_list_number_rule_item_operator import (\n UserListNumberRuleItemOperatorEnum,\n)\nfrom google.ads.googleads.v14.enums.types.user_list_prepopulation_status import (\n UserListPrepopulationStatusEnum,\n)\nfrom google.ads.googleads.v14.enums.types.user_list_rule_type import (\n UserListRuleTypeEnum,\n)\nfrom google.ads.googleads.v14.enums.types.user_list_string_rule_item_operator import (\n UserListStringRuleItemOperatorEnum,\n)\n\nclass BasicUserListInfo(proto.Message):\n actions: MutableSequence[UserListActionInfo]\n def __init__(\n self,\n mapping: Any | None = ...,\n *,\n ignore_unknown_fields: bool = ...,\n actions: MutableSequence[UserListActionInfo] = ...\n ) -> None: ...\n\nclass CrmBasedUserListInfo(proto.Message):\n app_id: str\n upload_key_type: CustomerMatchUploadKeyTypeEnum.CustomerMatchUploadKeyType\n data_source_type: UserListCrmDataSourceTypeEnum.UserListCrmDataSourceType\n def __init__(\n self,\n mapping: Any | None = ...,\n *,\n ignore_unknown_fields: bool = ...,\n app_id: str = ...,\n upload_key_type: CustomerMatchUploadKeyTypeEnum.CustomerMatchUploadKeyType = ...,\n data_source_type: UserListCrmDataSourceTypeEnum.UserListCrmDataSourceType = ...\n ) -> None: ...\n\nclass FlexibleRuleOperandInfo(proto.Message):\n rule: UserListRuleInfo\n lookback_window_days: int\n def __init__(\n self,\n mapping: Any | None = ...,\n *,\n ignore_unknown_fields: bool = ...,\n rule: UserListRuleInfo = ...,\n lookback_window_days: int = ...\n ) -> None: ...\n\nclass FlexibleRuleUserListInfo(proto.Message):\n inclusive_rule_operator: UserListFlexibleRuleOperatorEnum.UserListFlexibleRuleOperator\n inclusive_operands: MutableSequence[FlexibleRuleOperandInfo]\n exclusive_operands: MutableSequence[FlexibleRuleOperandInfo]\n def __init__(\n self,\n mapping: Any | None = ...,\n *,\n ignore_unknown_fields: bool = ...,\n inclusive_rule_operator: UserListFlexibleRuleOperatorEnum.UserListFlexibleRuleOperator = ...,\n inclusive_operands: MutableSequence[FlexibleRuleOperandInfo] = ...,\n exclusive_operands: MutableSequence[FlexibleRuleOperandInfo] = ...\n ) -> None: ...\n\nclass LogicalUserListInfo(proto.Message):\n rules: MutableSequence[UserListLogicalRuleInfo]\n def __init__(\n self,\n mapping: Any | None = ...,\n *,\n ignore_unknown_fields: bool = ...,\n rules: MutableSequence[UserListLogicalRuleInfo] = ...\n ) -> None: ...\n\nclass LogicalUserListOperandInfo(proto.Message):\n user_list: str\n def __init__(\n self,\n mapping: Any | None = ...,\n *,\n ignore_unknown_fields: bool = ...,\n user_list: str = ...\n ) -> None: ...\n\nclass RuleBasedUserListInfo(proto.Message):\n prepopulation_status: UserListPrepopulationStatusEnum.UserListPrepopulationStatus\n flexible_rule_user_list: FlexibleRuleUserListInfo\n def __init__(\n self,\n mapping: Any | None = ...,\n *,\n ignore_unknown_fields: bool = ...,\n prepopulation_status: UserListPrepopulationStatusEnum.UserListPrepopulationStatus = ...,\n flexible_rule_user_list: FlexibleRuleUserListInfo = ...\n ) -> None: ...\n\nclass SimilarUserListInfo(proto.Message):\n seed_user_list: str\n def __init__(\n self,\n mapping: Any | None = ...,\n *,\n ignore_unknown_fields: bool = ...,\n seed_user_list: str = ...\n ) -> None: ...\n\nclass UserListActionInfo(proto.Message):\n conversion_action: str\n remarketing_action: str\n def __init__(\n self,\n mapping: Any | None = ...,\n *,\n ignore_unknown_fields: bool = ...,\n conversion_action: str = ...,\n remarketing_action: str = ...\n ) -> None: ...\n\nclass UserListDateRuleItemInfo(proto.Message):\n operator: UserListDateRuleItemOperatorEnum.UserListDateRuleItemOperator\n value: str\n offset_in_days: int\n def __init__(\n self,\n mapping: Any | None = ...,\n *,\n ignore_unknown_fields: bool = ...,\n operator: UserListDateRuleItemOperatorEnum.UserListDateRuleItemOperator = ...,\n value: str = ...,\n offset_in_days: int = ...\n ) -> None: ...\n\nclass UserListLogicalRuleInfo(proto.Message):\n operator: UserListLogicalRuleOperatorEnum.UserListLogicalRuleOperator\n rule_operands: MutableSequence[LogicalUserListOperandInfo]\n def __init__(\n self,\n mapping: Any | None = ...,\n *,\n ignore_unknown_fields: bool = ...,\n operator: UserListLogicalRuleOperatorEnum.UserListLogicalRuleOperator = ...,\n rule_operands: MutableSequence[LogicalUserListOperandInfo] = ...\n ) -> None: ...\n\nclass UserListNumberRuleItemInfo(proto.Message):\n operator: UserListNumberRuleItemOperatorEnum.UserListNumberRuleItemOperator\n value: float\n def __init__(\n self,\n mapping: Any | None = ...,\n *,\n ignore_unknown_fields: bool = ...,\n operator: UserListNumberRuleItemOperatorEnum.UserListNumberRuleItemOperator = ...,\n value: float = ...\n ) -> None: ...\n\nclass UserListRuleInfo(proto.Message):\n rule_type: UserListRuleTypeEnum.UserListRuleType\n rule_item_groups: MutableSequence[UserListRuleItemGroupInfo]\n def __init__(\n self,\n mapping: Any | None = ...,\n *,\n ignore_unknown_fields: bool = ...,\n rule_type: UserListRuleTypeEnum.UserListRuleType = ...,\n rule_item_groups: MutableSequence[UserListRuleItemGroupInfo] = ...\n ) -> None: ...\n\nclass UserListRuleItemGroupInfo(proto.Message):\n rule_items: MutableSequence[UserListRuleItemInfo]\n def __init__(\n self,\n mapping: Any | None = ...,\n *,\n ignore_unknown_fields: bool = ...,\n rule_items: MutableSequence[UserListRuleItemInfo] = ...\n ) -> None: ...\n\nclass UserListRuleItemInfo(proto.Message):\n name: str\n number_rule_item: UserListNumberRuleItemInfo\n string_rule_item: UserListStringRuleItemInfo\n date_rule_item: UserListDateRuleItemInfo\n def __init__(\n self,\n mapping: Any | None = ...,\n *,\n ignore_unknown_fields: bool = ...,\n name: str = ...,\n number_rule_item: UserListNumberRuleItemInfo = ...,\n string_rule_item: UserListStringRuleItemInfo = ...,\n date_rule_item: UserListDateRuleItemInfo = ...\n ) -> None: ...\n\nclass UserListStringRuleItemInfo(proto.Message):\n operator: UserListStringRuleItemOperatorEnum.UserListStringRuleItemOperator\n value: str\n def __init__(\n self,\n mapping: Any | None = ...,\n *,\n ignore_unknown_fields: bool = ...,\n operator: UserListStringRuleItemOperatorEnum.UserListStringRuleItemOperator = ...,\n value: str = ...\n ) -> None: ...\n","sub_path":"google-stubs/ads/googleads/v14/common/types/user_lists.pyi","file_name":"user_lists.pyi","file_ext":"pyi","file_size_in_byte":7603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"269512061","text":"# Copyright 2020 DeepMind Technologies Limited.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Configuration for Prisoner's Dilemma in the Matrix.\n\nExample video: https://youtu.be/bQkEKc1zNuE\n\nSee _Running with Scissors in the Matrix_ for a general description of the\ngame dynamics. Here the payoff matrix represents the Prisoner's Dilemma game.\n`K = 2` resources represent \"cooperate\" and \"defect\" pure strategies.\n\nPlayers have the default `11 x 11` (off center) observation window.\n\"\"\"\n\nimport copy\nfrom typing import Any, Dict, Iterable, Sequence, Tuple\n\nfrom ml_collections import config_dict\nfrom meltingpot.python.utils.substrates import colors\nfrom meltingpot.python.utils.substrates import game_object_utils\nfrom meltingpot.python.utils.substrates import shapes\n\nPrefabConfig = game_object_utils.PrefabConfig\n\n# The number of resources must match the (square) size of the matrix.\nNUM_RESOURCES = 2\n\n# This color is green.\nRESOURCE1_COLOR = (30, 225, 185, 255)\nRESOURCE1_HIGHLIGHT_COLOR = (98, 234, 206, 255)\nRESOURCE1_COLOR_DATA = (RESOURCE1_COLOR, RESOURCE1_HIGHLIGHT_COLOR)\n# This color is red.\nRESOURCE2_COLOR = (225, 30, 70, 255)\nRESOURCE2_HIGHLIGHT_COLOR = (234, 98, 126, 255)\nRESOURCE2_COLOR_DATA = (RESOURCE2_COLOR, RESOURCE2_HIGHLIGHT_COLOR)\n\n# The procedural generator replaces all 'a' chars in the default map with chars\n# representing specific resources, i.e. with either '1' or '2'.\nDEFAULT_ASCII_MAP = \"\"\"\nWWWWWWWWWWWWWWWWWWWWWWWWW\nWPPPP W W PPPPW\nWPPPP PPPPW\nWPPPP PPPPW\nWPPPP PPPPW\nW W\nW 11 W\nW 11 W\nW aa W\nW WW W 222 W\nWW 1a W 222 W\nWWW 1a WWWWWWWWW W\nW 1a 111 WWW\nW 111 W\nW aa W W\nW 22 W WW W\nW 22 Waaa W\nW 222 W\nW W\nWPPPP PPPPW\nWPPPP PPPPW\nWPPPP PPPPW\nWPPPP W PPPPW\nWWWWWWWWWWWWWWWWWWWWWWWWW\n\"\"\"\n\n_resource_names = [\n \"resource_class1\",\n \"resource_class2\",\n]\n\n# `prefab` determines which prefab game object to use for each `char` in the\n# ascii map.\nCHAR_PREFAB_MAP = {\n \"a\": {\"type\": \"choice\", \"list\": _resource_names},\n \"1\": _resource_names[0],\n \"2\": _resource_names[1],\n \"P\": \"spawn_point\",\n \"W\": \"wall\",\n}\n\n_COMPASS = [\"N\", \"E\", \"S\", \"W\"]\n\nWALL = {\n \"name\": \"wall\",\n \"components\": [\n {\n \"component\": \"StateManager\",\n \"kwargs\": {\n \"initialState\": \"wall\",\n \"stateConfigs\": [{\n \"state\": \"wall\",\n \"layer\": \"upperPhysical\",\n \"sprite\": \"Wall\",\n }],\n }\n },\n {\n \"component\": \"Transform\",\n \"kwargs\": {\n \"position\": (0, 0),\n \"orientation\": \"N\"\n }\n },\n {\n \"component\": \"Appearance\",\n \"kwargs\": {\n \"renderMode\": \"ascii_shape\",\n \"spriteNames\": [\"Wall\"],\n \"spriteShapes\": [shapes.WALL],\n \"palettes\": [{\"*\": (95, 95, 95, 255),\n \"&\": (100, 100, 100, 255),\n \"@\": (109, 109, 109, 255),\n \"#\": (152, 152, 152, 255)}],\n \"noRotates\": [False]\n }\n },\n {\n \"component\": \"BeamBlocker\",\n \"kwargs\": {\n \"beamType\": \"gameInteraction\"\n }\n },\n ]\n}\n\nSPAWN_POINT = {\n \"name\": \"spawnPoint\",\n \"components\": [\n {\n \"component\": \"StateManager\",\n \"kwargs\": {\n \"initialState\": \"spawnPoint\",\n \"stateConfigs\": [{\n \"state\": \"spawnPoint\",\n \"layer\": \"alternateLogic\",\n \"groups\": [\"spawnPoints\"]\n }],\n }\n },\n {\n \"component\": \"Transform\",\n \"kwargs\": {\n \"position\": (0, 0),\n \"orientation\": \"N\"\n }\n },\n ]\n}\n\n# PLAYER_COLOR_PALETTES is a list with each entry specifying the color to use\n# for the player at the corresponding index.\nNUM_PLAYERS_UPPER_BOUND = 32\nPLAYER_COLOR_PALETTES = []\nfor idx in range(NUM_PLAYERS_UPPER_BOUND):\n PLAYER_COLOR_PALETTES.append(shapes.get_palette(colors.palette[idx]))\n\n# Primitive action components.\n# pylint: disable=bad-whitespace\n# pyformat: disable\nNOOP = {\"move\": 0, \"turn\": 0, \"interact\": 0}\nFORWARD = {\"move\": 1, \"turn\": 0, \"interact\": 0}\nSTEP_RIGHT = {\"move\": 2, \"turn\": 0, \"interact\": 0}\nBACKWARD = {\"move\": 3, \"turn\": 0, \"interact\": 0}\nSTEP_LEFT = {\"move\": 4, \"turn\": 0, \"interact\": 0}\nTURN_LEFT = {\"move\": 0, \"turn\": -1, \"interact\": 0}\nTURN_RIGHT = {\"move\": 0, \"turn\": 1, \"interact\": 0}\nINTERACT = {\"move\": 0, \"turn\": 0, \"interact\": 1}\n# pyformat: enable\n# pylint: enable=bad-whitespace\n\nACTION_SET = (\n NOOP,\n FORWARD,\n BACKWARD,\n STEP_LEFT,\n STEP_RIGHT,\n TURN_LEFT,\n TURN_RIGHT,\n INTERACT,\n)\n\nTARGET_SPRITE_SELF = {\n \"name\": \"Self\",\n \"shape\": shapes.CUTE_AVATAR,\n \"palette\": shapes.get_palette((50, 100, 200)),\n \"noRotate\": True,\n}\n\n\ndef create_scene():\n \"\"\"Creates the global scene.\"\"\"\n scene = {\n \"name\": \"scene\",\n \"components\": [\n {\n \"component\": \"StateManager\",\n \"kwargs\": {\n \"initialState\": \"scene\",\n \"stateConfigs\": [{\n \"state\": \"scene\",\n }],\n }\n },\n {\n \"component\": \"Transform\",\n \"kwargs\": {\n \"position\": (0, 0),\n \"orientation\": \"N\"\n },\n },\n {\n \"component\": \"TheMatrix\",\n \"kwargs\": {\n \"zero_initial_inventory\": True,\n \"matrix\": [\n # row player chooses a row of this matrix.\n # C D\n [3, 0], # C\n [4, 1], # D\n ],\n \"columnPlayerMatrix\": [\n # column player chooses a column of this matrix.\n # C D\n [3, 4], # C\n [0, 1], # D\n ],\n }\n },\n ]\n }\n return scene\n\n\ndef create_resource_prefab(resource_id, color_data):\n \"\"\"Creates resource prefab with provided `resource_id` (num) and color.\"\"\"\n resource_name = \"resource_class{}\".format(resource_id)\n resource_prefab = {\n \"name\": resource_name,\n \"components\": [\n {\n \"component\": \"StateManager\",\n \"kwargs\": {\n \"initialState\": resource_name,\n \"stateConfigs\": [\n {\"state\": resource_name + \"_wait\",\n \"groups\": [\"resourceWaits\"]},\n {\"state\": resource_name,\n \"layer\": \"lowerPhysical\",\n \"sprite\": resource_name + \"_sprite\"},\n ]\n },\n },\n {\n \"component\": \"Transform\",\n \"kwargs\": {\n \"position\": (0, 0),\n \"orientation\": \"N\"\n },\n },\n {\n \"component\": \"Appearance\",\n \"kwargs\": {\n \"renderMode\": \"ascii_shape\",\n \"spriteNames\": [resource_name + \"_sprite\"],\n \"spriteShapes\": [shapes.BUTTON],\n \"palettes\": [{\"*\": color_data[0],\n \"#\": color_data[1],\n \"x\": (0, 0, 0, 0)}],\n \"noRotates\": [False]\n },\n },\n {\n \"component\": \"Resource\",\n \"kwargs\": {\n \"resourceClass\": resource_id,\n \"visibleType\": resource_name,\n \"waitState\": resource_name + \"_wait\",\n \"groupToRespawn\": \"resourceWaits\",\n \"regenerationRate\": 0.005,\n \"regenerationDelay\": 50\n },\n },\n {\n \"component\": \"Destroyable\",\n \"kwargs\": {\n \"visibleType\": resource_name,\n \"waitState\": resource_name + \"_wait\",\n \"initialHealth\": 1,\n },\n },\n ]\n }\n return resource_prefab\n\n\ndef create_prefabs() -> PrefabConfig:\n \"\"\"Returns the prefabs.\n\n Prefabs are a dictionary mapping names to template game objects that can\n be cloned and placed in multiple locations accoring to an ascii map.\n \"\"\"\n prefabs = {\n \"wall\": WALL,\n \"spawn_point\": SPAWN_POINT,\n }\n prefabs[\"resource_class1\"] = create_resource_prefab(1, RESOURCE1_COLOR_DATA)\n prefabs[\"resource_class2\"] = create_resource_prefab(2, RESOURCE2_COLOR_DATA)\n return prefabs\n\n\ndef create_avatar_object(player_idx: int,\n target_sprite_self: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"Create an avatar object that always sees itself as blue.\"\"\"\n # Lua is 1-indexed.\n lua_index = player_idx + 1\n\n # Setup the self vs other sprite mapping.\n source_sprite_self = \"Avatar\" + str(lua_index)\n custom_sprite_map = {source_sprite_self: target_sprite_self[\"name\"]}\n\n live_state_name = \"player{}\".format(lua_index)\n avatar_object = {\n \"name\": \"avatar\",\n \"components\": [\n {\n \"component\": \"StateManager\",\n \"kwargs\": {\n \"initialState\": live_state_name,\n \"stateConfigs\": [\n {\"state\": live_state_name,\n \"layer\": \"upperPhysical\",\n \"sprite\": source_sprite_self,\n \"contact\": \"avatar\",\n \"groups\": [\"players\"]},\n\n {\"state\": \"playerWait\",\n \"groups\": [\"playerWaits\"]},\n ]\n }\n },\n {\n \"component\": \"Transform\",\n \"kwargs\": {\n \"position\": (0, 0),\n \"orientation\": \"N\"\n }\n },\n {\n \"component\": \"Appearance\",\n \"kwargs\": {\n \"renderMode\": \"ascii_shape\",\n \"spriteNames\": [source_sprite_self],\n \"spriteShapes\": [shapes.CUTE_AVATAR],\n \"palettes\": [shapes.get_palette(colors.palette[player_idx])],\n \"noRotates\": [True]\n }\n },\n {\n \"component\": \"AdditionalSprites\",\n \"kwargs\": {\n \"renderMode\": \"ascii_shape\",\n \"customSpriteNames\": [target_sprite_self[\"name\"]],\n \"customSpriteShapes\": [target_sprite_self[\"shape\"]],\n \"customPalettes\": [target_sprite_self[\"palette\"]],\n \"customNoRotates\": [target_sprite_self[\"noRotate\"]],\n }\n },\n {\n \"component\": \"Avatar\",\n \"kwargs\": {\n \"index\": lua_index,\n \"aliveState\": live_state_name,\n \"waitState\": \"playerWait\",\n \"speed\": 1.0,\n \"spawnGroup\": \"spawnPoints\",\n \"actionOrder\": [\"move\", \"turn\", \"interact\"],\n \"actionSpec\": {\n \"move\": {\"default\": 0, \"min\": 0, \"max\": len(_COMPASS)},\n \"turn\": {\"default\": 0, \"min\": -1, \"max\": 1},\n \"interact\": {\"default\": 0, \"min\": 0, \"max\": 1},\n },\n \"view\": {\n \"left\": 5,\n \"right\": 5,\n \"forward\": 9,\n \"backward\": 1,\n \"centered\": False\n },\n \"spriteMap\": custom_sprite_map,\n # The following kwarg makes it possible to get rewarded even\n # on frames when an avatar is \"dead\". It is needed for in the\n # matrix games in order to correctly handle the case of two\n # players getting hit simultaneously by the same beam.\n \"skipWaitStateRewards\": False,\n }\n },\n {\n \"component\": \"GameInteractionZapper\",\n \"kwargs\": {\n \"cooldownTime\": 32,\n \"beamLength\": 3,\n \"beamRadius\": 1,\n \"framesTillRespawn\": 200,\n \"numResources\": NUM_RESOURCES,\n \"reset_winner_inventory\": False,\n \"reset_loser_inventory\": True,\n \"losingPlayerDies\": True,\n }\n },\n {\n \"component\": \"ReadyToShootObservation\",\n \"kwargs\": {\n \"zapperComponent\": \"GameInteractionZapper\",\n }\n },\n {\n \"component\": \"InventoryObserver\",\n \"kwargs\": {\n }\n },\n {\n \"component\": \"Taste\",\n \"kwargs\": {\n \"mostTastyResourceClass\": -1, # -1 indicates no preference.\n }\n },\n {\n \"component\": \"InteractionTaste\",\n \"kwargs\": {\n \"mostTastyResourceClass\": -1, # -1 indicates no preference.\n \"zeroDefaultInteractionReward\": True,\n \"extraReward\": 1.0,\n }\n },\n {\n \"component\": \"LocationObserver\",\n \"kwargs\": {\n \"objectIsAvatar\": True,\n \"alsoReportOrientation\": True\n }\n },\n {\n \"component\": \"AvatarMetricReporter\",\n \"kwargs\": {\n \"metrics\": [\n {\n # Report the inventories of both players involved in\n # an interaction on this frame formatted as\n # (self inventory, partner inventory).\n \"name\": \"INTERACTION_INVENTORIES\",\n \"type\": \"tensor.DoubleTensor\",\n \"shape\": (2, NUM_RESOURCES),\n \"component\": \"GameInteractionZapper\",\n \"variable\": \"latest_interaction_inventories\",\n },\n ]\n }\n },\n ]\n }\n\n return avatar_object\n\n\ndef create_avatar_objects(num_players: int) -> Sequence[PrefabConfig]:\n \"\"\"Returns all game objects for the map.\n\n Args:\n num_players: number of players to create avatars for.\n \"\"\"\n avatar_objects = []\n for player_idx in range(num_players):\n avatar = create_avatar_object(player_idx, TARGET_SPRITE_SELF)\n avatar_objects.append(avatar)\n return avatar_objects\n\n\ndef create_lab2d_settings(\n num_players: int,\n ascii_map_string: str,\n settings_overrides: Iterable[Tuple[str, Any]] = ()) -> Dict[str, Any]:\n \"\"\"Returns the lab2d settings.\n\n Args:\n num_players: (int) the number of players.\n ascii_map_string: ascii map.\n settings_overrides: (key, value) overrides for default settings.\n \"\"\"\n settings = {\n \"levelName\": \"the_matrix\",\n \"levelDirectory\": \"meltingpot/lua/levels\",\n \"numPlayers\": num_players,\n \"episodeLengthFrames\": 1000,\n \"spriteSize\": 8,\n \"simulation\": {\n \"map\": ascii_map_string,\n \"gameObjects\": create_avatar_objects(num_players=num_players),\n \"scene\": copy.deepcopy(create_scene()),\n \"prefabs\": create_prefabs(),\n \"charPrefabMap\": CHAR_PREFAB_MAP,\n }\n }\n settings.update(settings_overrides)\n return settings\n\n\ndef get_config(factory=create_lab2d_settings):\n \"\"\"Default config for prisoners dilemma in the matrix.\"\"\"\n config = config_dict.ConfigDict()\n\n # Basic configuration.\n config.num_players = 8\n config.lab2d_settings = factory(config.num_players, DEFAULT_ASCII_MAP)\n\n # Action set configuration.\n config.action_set = ACTION_SET\n # Observation format configuration.\n config.individual_observation_names = [\n \"RGB\",\n \"INVENTORY\",\n \"READY_TO_SHOOT\",\n \"POSITION\",\n \"ORIENTATION\",\n \"INTERACTION_INVENTORIES\",\n ]\n config.global_observation_names = [\n \"WORLD.RGB\",\n ]\n\n return config\n","sub_path":"meltingpot/python/configs/substrates/prisoners_dilemma_in_the_matrix.py","file_name":"prisoners_dilemma_in_the_matrix.py","file_ext":"py","file_size_in_byte":16992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"246882309","text":"\"\"\"\n*Реализовать структуру данных «Товары». Она должна представлять собой список кортежей. Каждый кортеж хранит информацию\nоб отдельном товаре. В кортеже должно быть два элемента — номер товара и словарь с параметрами (характеристиками товара:\nназвание, цена, количество, единица измерения). Структуру нужно сформировать программно, т.е. запрашивать все данные у\nпользователя.\nНеобходимо собрать аналитику о товарах. Реализовать словарь, в котором каждый ключ — характеристика товара, например\nназвание, а значение — список значений-характеристик, например список названий товаров.\n\"\"\"\n\nitems_from_task = [(1, {'название': 'компьютер', 'цена': 20000, 'количество': 5, 'ед': 'шт.'}),\n (2, {'название': 'принтер', 'цена': 6000, 'количество': 2, 'ед': 'шт.'}),\n (3, {'название': 'сканер', 'цена': 2000, 'количество': 7, 'ед': 'шт.'})]\n\n# answer_dict for self check\nanswer_dict = {'название': ['компьютер', 'принтер', 'сканер'],\n 'цена': [20000, 6000, 2000],\n 'количество': [5, 2, 7],\n 'ед': ['шт.']}\n\n# Input user dictionary\n# items_dict = dict.fromkeys(['название', 'цена', 'количество', 'ед']) # init keys\n\n# user_input = [(i, {key: input(f\"Введите {key}: \") for key in items_dict})\n# for i in range(int(input(\"Количество товаров: \")))] # dict generator inside of the list generator\n\n# print(\"\\nВведённый словарь:\")\n# for item in user_input:\n# print(item)\n\nprint(\"\\nСловарь из задания:\")\nfor item in items_from_task:\n print(item)\n\n# form my_result_dict with analytics for the task\nmy_result_dict = {} # init my_result_dict\nfor item in items_from_task:\n _, dict_item = list(item)\n for key, value in dict_item.items():\n if my_result_dict.get(key) and key != 'ед':\n my_result_dict[key] += [value] # add to existing value\n else:\n my_result_dict[key] = [value] # create key:value\nprint(\"\\nРезультирующий словарь:\\n\", my_result_dict, sep=\"\")\nprint(\"Сравнение с ответом из задания: \", answer_dict == my_result_dict)\n\n# Var - 2. form my_result_dict with analytics for the task\nmy_result_dict = {} # init my_result_dict\nfor item in items_from_task:\n for key, value in item[1].items():\n my_result_dict.setdefault(key, []).append(value)\nprint(\"\\nРезультирующий словарь вар - 2:\\n\", my_result_dict, sep=\"\")\n","sub_path":"lesson_2/task_6.py","file_name":"task_6.py","file_ext":"py","file_size_in_byte":3139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"486098361","text":"import json\n\nfrom db import models, ForeignKey, createsession, engine, attach_session\nfrom auth import User\nfrom core import defaults, error\nfrom accounts import Currency, Account, Movement\n\nfrom datetime import datetime\n\nfrom sqlalchemy.orm.exc import MultipleResultsFound, NoResultFound\nfrom sqlalchemy import Column, String, Numeric, DateTime, Text, Boolean, Integer\n\nimport urllib2\nimport blockchain.formatstrings as blc\n\nclass CurrencyWallet(models.Model):\n\tcurrency = ForeignKey(Currency)\n\tidentifier = Column(String(100))\n\tpassword = Column(String(100))\n\tdefaultrate = Column(Numeric(20, 10))\n\n\t@attach_session\n\tdef get_rate(self, session):\n\t\tstock = self.currency.stock\n\n\t\turl = blc['getbalance'].format(identifier=identifier, password=password)\n\n\t\tresponse = urllib2.urlopen(url)\n\t\tdata = json.loads(response.read())\n\n\t\tif 'error' in data:\n\t\t\traise Exception(data['error'])\n\n\t\tif 'balance' in data:\n\t\t\tbalance = Decimal(data['balance'])\n\t\telse:\n\t\t\traise Exception('No balance.')\n\n\t\trate = (balance / Decimal('1e8')) / stock\n\n\t\tif rate == Decimal(0):\n\t\t\trate = self.defaultrate\n\n\t\treturn rate\n\n\t@staticmethod\n\t@attach_session\n\tdef getinfo(currency, session):\n\t\tif isinstance(currency, str):\n\t\t\ttry:\n\t\t\t\tcurrency = session.query(Currency).filter_by(name=currency).one()\n\t\t\texcept NoResultFound:\n\t\t\t\traise Exception('Invalid currency.')\n\n\t\ttry:\n\t\t\twalletinfo = session.query(CurrencyWallet).filter_by(currency=currency).one()\n\t\texcept NoResultFound:\n\t\t\traise Exception('No wallet info found.')\n\t\texcept MultipleResultsFound:\n\t\t\traise Exception('Wallet info error.')\n\n\t\tresponse = {\n\t\t\t\"currency\": currency.name,\n\t\t\t\"identifier\": walletinfo.identifier,\n\t\t\t\"password\": walletinfo.password,\n\t\t\t\"defaultrate\": walletinfo.defaultrate\n\t\t}\n\n\t\treturn response\n\n\nclass AccountWallet(models.Model):\n\taccount = Column(String(255))\n\taddress = Column(String(50))\n\nclass IncomingTransactions(models.Model):\n\ttxhash = Column(String(255))\n\taccount = Column(String(255))\n\nclass MovementQueue(models.Model):\n\ttimestamp = Column(DateTime)\n\tmovement = ForeignKey(Movement)\n\torig = Column(String(255))\n\tdest = Column(String(255))\n\tuser = ForeignKey(User)\n\tstatus = Column(String(50))\n\n\t@staticmethod\n\t@attach_session\n\tdef next(status, session):\n\t\ttry:\n\t\t\titem = session.query(MovementQueue).filter_by(status=status).order_by('-timestamp').first()\n\t\texcept NoResultFound:\n\t\t\treturn None\n\n\t\treturn item\n\n\t@staticmethod\n\t@attach_session\n\tdef put(status, movement, orig, dest, user, session):\n\n\t\tif isinstance(orig, Account):\n\t\t\torig = orig.name\n\n\t\tif isinstance(dest, Account):\n\t\t\tdest = dest.name\n\n\t\titem = MovementQueue(timestamp=movement.timestamp, movement=movement, orig=orig, dest=dest, user=user, status=status)\n\t\tsession.add(item)\n\t\tpass","sub_path":"modules/blockchain/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"51703447","text":"# Import libraries\nimport requests\nimport urllib.request\nimport time\nimport datetime\nfrom bs4 import BeautifulSoup\n\n# Set the URL you want to webscrape from\n#url = 'http://web.mta.info/developers/turnstile.html'\nurl = 'https://www.rki.de/DE/Content/InfAZ/N/Neuartiges_Coronavirus/Fallzahlen.html'\n\n# Connect to the URL\nresponse = requests.get(url)\n#print (response)\n\n# Parse HTML and save to BeautifulSoup object¶\nsoup = BeautifulSoup(response.text, \"html.parser\")\n#print(soup)\n\n#print (soup.findAll('td'))\n\ndata = []\ntable = soup.find('table')\n#rows = table.findAll('tr')\n#for row in rows:\n# print(row)\n#\n# cols = row.findAll('td')[6]\n# print(cols)\n#\n# country = cols[0].string\n# number = cols[1].string\n# diff = cols[2].string\n# np100t = cols[3].string\n# dead = cols[4].string\n# #remarks = cols[5].string\n#\n# #entry = (country, number, diff, np100t, dead, remarks)\n# entry = (country, number, diff, np100t, dead)\n# print (entry)\n\ndt_date = datetime.datetime.now()\ndate = datetime.date.today()\n#print (\"The Current date is:\" ,dt_date)\n#print(\"In specified format:\", dt_date.isoformat())\nfilename='RKI_Corona_'+dt_date.isoformat()\n#this file contais all data from the RKI table\nfilename3='RKI_Corona_'+dt_date.isoformat()+'ALL'\nf1=open(filename, 'w')\nf3=open(filename3, 'w')\n\nrows = table.find_all('tr')\n#print(rows)\nfor row in rows:\n cols = row.findAll('td')\n if len(cols) > 0:\n country = cols[0].text.strip()\n number = cols[1].text.strip()\n diff = cols[2].text.strip()\n np100t = cols[3].text.strip()\n inc7 = cols[4].text.strip()\n dead = cols[5].text.strip()\n f1.write(\"%s, %s, %s, %s, %s, %s\\n\" % (date, country, number, diff, np100t, dead))\n f3.write(\"%s, %s, %s, %s, %s, %s, %s\\n\" % (date, country, number, diff, np100t, inc7, dead))\n #cols = [ele.text.strip() for ele in cols]\n #data.append([ele for ele in cols if ele])\n\nf1.close()\nf3.close()\n\nprint(filename)\nf2=open(\"file_of_the_day\", 'w')\nf2.write(\"%s\\n\" % filename)\nf2.close\n","sub_path":"rki_get_data.py","file_name":"rki_get_data.py","file_ext":"py","file_size_in_byte":2046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"244139502","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build\\bdist.win-amd64\\egg\\bca4abm\\tables\\trips.py\n# Compiled at: 2020-02-14 01:16:04\n# Size of source mod 2**32: 3310 bytes\nimport logging, pandas as pd\nfrom activitysim.core import inject\nfrom activitysim.core import config\nfrom bca4abm import bca4abm as bca\nlogger = logging.getLogger(__name__)\n\ndef read_merged_trips(table_name, alt_table_name, data_dir, table_settings, persons):\n trips = bca.read_csv_table(table_name=table_name, data_dir=data_dir, settings=table_settings)\n trips_alt = bca.read_csv_table(table_name=alt_table_name, data_dir=data_dir, settings=table_settings)\n trips_merged = pd.merge(trips, trips_alt, on=['household_id',\n 'person_idx',\n 'tour_idx',\n 'half_tour_idx',\n 'half_tour_seg_idx'])\n persons = persons.to_frame()[['household_id', 'person_idx']]\n persons['person_id'] = persons.index\n trips_merged = pd.merge(trips_merged, persons, on=['household_id', 'person_idx'])\n return trips_merged\n\n\n@inject.table()\ndef base_trips(data_dir, persons):\n logger.debug('reading base_trips table')\n table_settings = config.read_model_settings('tables.yaml')\n trips_merged = read_merged_trips(table_name='basetrips', alt_table_name='basetrips_buildlos',\n data_dir=data_dir,\n table_settings=table_settings,\n persons=persons)\n trips_merged['build'] = 0\n trips_merged['base'] = 1\n return trips_merged\n\n\n@inject.table()\ndef build_trips(data_dir, persons):\n logger.debug('reading build_trips table')\n table_settings = config.read_model_settings('tables.yaml')\n trips_merged = read_merged_trips(table_name='buildtrips', alt_table_name='buildtrips_baselos',\n data_dir=data_dir,\n table_settings=table_settings,\n persons=persons)\n trips_merged['build'] = 1\n trips_merged['base'] = 0\n return trips_merged\n\n\n@inject.table()\ndef disaggregate_trips(base_trips, build_trips):\n build = build_trips.to_frame()\n base = base_trips.to_frame()\n df = base.append(build, ignore_index=True, sort=False)\n df['index1'] = df.index\n return df\n\n\ninject.broadcast(cast='persons_merged', onto='disaggregate_trips',\n cast_index=True,\n onto_on='person_id')\n\n@inject.table()\ndef trips_with_demographics(disaggregate_trips, persons_merged):\n return inject.merge_tables(target=(disaggregate_trips.name), tables=[\n disaggregate_trips, persons_merged])","sub_path":"pycfiles/bca4abm-0.5-py3.7/trips.cpython-37.py","file_name":"trips.cpython-37.py","file_ext":"py","file_size_in_byte":2514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"210891007","text":"#\n# build the source distribution for tor_async_couchdb-*.*.*.tar.gz\n#\n# >git clone https://github.com/simonsdave/tor-async-couchdb.git\n# >cd tor-async-couchdb\n# >source cfg4dev\n# >python setup.py sdist --formats=gztar\n#\n# update pypitest with both meta data and source distribution (FYI ...\n# use of pandoc is as per https://github.com/pypa/pypi-legacy/issues/148#issuecomment-226939424\n# since PyPI requires long description in RST but the repo's readme is in\n# markdown)\n#\n# >pandoc README.md -o README.rst\n# >twine upload dist/* -r testpypi\n#\n# you will be able to find the package at\n#\n# https://test.pypi.org/project/tor-async-couchdb\n#\n# use the uploaded package\n#\n# >pip install -i https://testpypi.python.org/pypi tor_async_couchdb\n#\nimport re\nfrom setuptools import setup\n\n#\n# this approach used below to determine ```version``` was inspired by\n# https://github.com/kennethreitz/requests/blob/master/setup.py#L31\n#\n# why this complexity? wanted version number to be available in the\n# a runtime.\n#\n# the code below assumes the distribution is being built with the\n# current directory being the directory in which setup.py is stored\n# which should be totally fine 99.9% of the time. not going to add\n# the coode complexity to deal with other scenarios\n#\nreg_ex_pattern = r\"__version__\\s*=\\s*['\\\"](?P[^'\\\"]*)['\\\"]\"\nreg_ex = re.compile(reg_ex_pattern)\nversion = \"\"\nwith open(\"tor_async_couchdb/__init__.py\", \"r\") as fd:\n for line in fd:\n match = reg_ex.match(line)\n if match:\n version = match.group(\"version\")\n break\nif not version:\n raise Exception(\"Can't locate tor_async_couchdb's version number\")\n\n\ndef _long_description():\n try:\n with open('README.rst', 'r') as f:\n return f.read()\n except IOError:\n # simple fix to avoid failure on 'source cfg4dev'\n return \"a long description\"\n\n\n# list of valid classifiers @ https://pypi.python.org/pypi?%3Aaction=list_classifiers\n_classifiers = [\n \"Development Status :: 5 - Production/Stable\",\n \"Intended Audience :: Developers\",\n \"Natural Language :: English\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 2.7\",\n \"Programming Language :: Python :: Implementation :: CPython\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n]\n\n_author = \"Dave Simons\"\n_author_email = \"simonsdave@gmail.com\"\n\n_keywords = [\n 'tornado',\n 'couchdb',\n]\n\nsetup(\n name=\"tor_async_couchdb\",\n packages=[\n \"tor_async_couchdb\",\n ],\n install_requires=[\n \"python-keyczar==0.716\",\n \"requests>=2.7.0\",\n ],\n version=version,\n description=\"Tornado Async Client for CouchDB\",\n long_description=_long_description(),\n author=_author,\n author_email=_author_email,\n maintainer=_author,\n maintainer_email=_author_email,\n license=\"MIT\",\n url=\"https://github.com/simonsdave/tor-async-couchdb\",\n download_url=\"https://github.com/simonsdave/tor-async-couchdb/tarball/v%s\" % version,\n keywords=_keywords,\n classifiers=_classifiers,\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"339459604","text":"from pwn import *\ncontext.clear(arch='amd64')\ncontext.binary = 'babyrop_level2_teaching1'\np = process('./babyrop_level2_teaching1')\nrop = ROP(context.binary)\np.recvuntil(b'().')\np.recvline()\nx = p.recvline().decode('utf-8')\naddr1 = int(x[x.find('0'):-2], 16)\nx = p.recvline().decode('utf-8')\naddr2 = int(x[x.find('0'):-2], 16)\nlog.info('win_stage_1() at '+hex(addr1))\nlog.info('win_stage_2() at '+hex(addr2))\nr = ROP(context.binary)\nr.call(addr1)\nr.call(addr2)\n# send the ROP chain\np.sendline(fit({56:r.chain()}))\np.interactive()","sub_path":"courses/pwncollege/rop/level2/exploit.py","file_name":"exploit.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"181603569","text":"import json\nimport time\nPOPULATION_SIZE = 40\nMUTATION_RATE = 0.1\nCROSSOVER_RATE = 0.9\nTOURNAMENT_SELECTION_SIZE = 3\nNUMB_OF_ELITE_SCHEDULES = 4\nSPLIT_VAR = 4\nNUMB_OF_GENERATION = 35\n\ndef run():\n\n from data import Data\n from genetic_algorithm import GeneticAlgorithm\n from population import Population\n from utils import get_random_number\n\n generation_number = 0\n data = Data()\n param = []\n param.append([POPULATION_SIZE,MUTATION_RATE,CROSSOVER_RATE,TOURNAMENT_SELECTION_SIZE,0,NUMB_OF_ELITE_SCHEDULES])\n \n start = time.time()\n\n # Creation de la population initiale\n _genetic_algorithm = GeneticAlgorithm(data=data, param=param[0])\n _population = Population(size=POPULATION_SIZE, data=data)\n\n while _population.schedules[0]._fitness != 1.0:\n generation_number += 1\n \n # Calcul la fitness de chaque emploi du temps dans la population\n for schedule in _population.schedules:\n schedule._fitness = schedule.calculate_fitness()\n \n # Tri la population et evolution de cette population\n _population.sort_by_fitness()\n _population = _genetic_algorithm.evolve(population=_population)\n \n for schedule in _population.schedules:\n schedule._fitness = schedule.calculate_fitness()\n \n _population.sort_by_fitness()\n print(\"fitness : {}\".format(_population.schedules[0]._fitness))\n\n end = time.time()\n print(\"Nombre de générations : {} Temps d'exécution : {} s\".format(generation_number, end-start))\n print(_population.schedules[0])\n return (generation_number,end-start)\n\n# Methode pour obtenir un csv avec les resultats utiles a l'analyse de l'algorithme\ndef data_analysis(nb_of_exec,name_of_the_csv):\n with open(\"analyse/\"+name_of_the_csv,\"w+\") as f:\n f.write(\"nbRun;nbGeneration;timeExec\\n\")\n for i in range(nb_of_exec):\n print(i)\n res_tuple = run()\n string = str(i)+\";\"+str(res_tuple[0])+\";\"+str(res_tuple[1])+\"\\n\"\n f.write(string) \n\nif __name__ == '__main__' and __package__ is None:\n run()","sub_path":"Scheduling/main_sequentiel_local.py","file_name":"main_sequentiel_local.py","file_ext":"py","file_size_in_byte":2063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"469311998","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('logistics_api', '0007_auto_20160331_1334'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Logistics_user',\n fields=[\n ('contact_num', models.IntegerField(default=0, serialize=False, primary_key=True)),\n ('email_id', models.CharField(max_length=80)),\n ('name', models.CharField(max_length=50)),\n ('password', models.CharField(max_length=30)),\n ],\n ),\n migrations.RemoveField(\n model_name='orders',\n name='date',\n ),\n migrations.RemoveField(\n model_name='orders',\n name='trip_id',\n ),\n migrations.RemoveField(\n model_name='orders',\n name='user_id',\n ),\n migrations.RemoveField(\n model_name='trip',\n name='user_id',\n ),\n migrations.AddField(\n model_name='driver',\n name='trip_id',\n field=models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, to='logistics_api.Trip', null=True),\n ),\n migrations.AlterField(\n model_name='driver',\n name='name',\n field=models.CharField(max_length=30),\n ),\n migrations.AlterField(\n model_name='orders',\n name='contact_num',\n field=models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, to='logistics_api.Logistics_user', null=True),\n ),\n migrations.AlterField(\n model_name='trip',\n name='order_id',\n field=models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, to='logistics_api.Orders', null=True),\n ),\n migrations.DeleteModel(\n name='User',\n ),\n ]\n","sub_path":"logistics_api/migrations/0008_auto_20160403_1233.py","file_name":"0008_auto_20160403_1233.py","file_ext":"py","file_size_in_byte":1996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"33616388","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jul 22 14:46:47 2015\n\n@author: stoimenoff\n\"\"\"\nimport random\nclass Node:\n def __init__(self, value, next_node=None):\n self.value = value\n self.next_node = next_node\n def value(self):\n return self.value\n def get_next(self):\n return self.next_node\n def set_next(self, next_node):\n self.next_node = next_node\n def __gt__(self, node):\n return self.value > node.value\n def __lt__(self, node):\n return self.value < node.value\n def __str__(self):\n return (self.value)\n \nclass LinkedList:\n def __init__(self):\n self.head = None\n self.tail = None\n self.size = 0\n def contains(self, value):\n current = self.head\n while current != None:\n if current.value == value:\n return True\n current = current.next_node\n return False\n def remove(self, value):\n if self.head.value == value:\n self.head = self.head.next_node\n else:\n current = self.head\n while current != None:\n if current.next_node.value == value:\n if current.next_node == self.tail:\n self.tail = current\n current.next_node = current.next_node.next_node\n break\n def add_tail(self, value):\n new_node = Node(value)\n if self.head == None:\n self.head = new_node\n self.tail = self.head\n else:\n self.tail.set_next(new_node)\n self.tail = new_node\n def add_head(self, value):\n new_node = Node(value)\n if self.head == None:\n self.head = new_node\n self.tail = self.head\n else:\n new_node.set_next(self.head)\n self.head = new_node\n def pop(self):\n if self.head != None:\n value = self.head.value\n self.head = self.head.get_next()\n if self.head == None:\n self.tail = None\n return value\n\nclass RandSet:\n def __init__(self, size = 11):\n self.items = [LinkedList() for i in range(size)]\n self.values = []\n self.last = None\n self.size = size\n self.items_count = 0\n def hash(self, number):\n return number % self.size\n def contains(self, number):\n item = self.items[self.hash(number)].head\n while item != None:\n if self.values[item.value] == number:\n return True\n item = item.next_node\n return False\n def insert(self, number):\n if not self.contains(number):\n self.items[self.hash(number)].add_tail(len(self.values))\n self.last = self.items[self.hash(number)].tail\n self.values.append(number)\n self.items_count += 1\n if self.items_count / self.size > 0.7:\n #TODO\n #Resize set\n pass\n def remove(self, number):\n item = self.items[self.hash(number)].head\n while item != None:\n if self.values[item.value] == number:\n self.last.value = item.value\n item.value = len(self.values) - 1\n swap = self.values[item.value]\n self.values[item.value] = self.values[self.last.value]\n self.values[self.last.value] = swap\n del self.values[-1]\n self.items_count -= 1\n self.items[self.hash(number)].remove(item.value)\n break\n item = item.next_node\n item = self.items[self.hash(self.values[-1])].head\n while item != None:\n if self.values[item.value] == number:\n self.last = item\n break\n item = item.next_node\n def get_random(self):\n r = random.randint(0, self.items_count - 1)\n return self.values[r]\n \ndef main():\n r_set = RandSet()\n n = int(input())\n result = []\n for i in range(n):\n cmd = [item for item in input().split()]\n if cmd[0] == \"insert\":\n r_set.insert(int(cmd[1]))\n elif cmd[0] == \"remove\":\n r_set.remove(int(cmd[1]))\n elif cmd[0] == \"contains\":\n result.append(str(r_set.contains(int(cmd[1]))))\n elif cmd[0] == \"random\":\n result.append(r_set.get_random())\n for item in result:\n print(item)\nmain()","sub_path":"week6/5-Rand-Set/rand_set.py","file_name":"rand_set.py","file_ext":"py","file_size_in_byte":4434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"563339305","text":"import smbl\r\nimport snakemake\r\nimport os\r\n\r\nfrom ._program import *\r\n\r\nPBSIM = get_bin_file_path(\"pbsim\")\r\n\r\n\r\n##########################################\r\n##########################################\r\n\r\n\r\nclass PbSim(Program):\r\n\t@classmethod\r\n\tdef get_installation_files(cls):\r\n\t\treturn [\r\n\t\t\t\tPBSIM,\r\n\t\t\t]\r\n\r\n\t@classmethod\r\n\tdef install(cls):\r\n\t\tfn=cls.download_file(\"https://pbsim.googlecode.com/files/pbsim-1.0.3.tar.gz\",\"pbsim.tar.gz\")\r\n\t\tdir=cls.extract_tar(fn,strip=1)\r\n\t\tcls.run_configure(dir)\r\n\t\tcls.run_make(dir)\r\n\t\tcls.install_file(\"src/pbsim\",PBSIM)\r\n\r\n\t@classmethod\r\n\tdef supported_platforms(cls):\r\n\t\treturn [\"cygwin\",\"osx\",\"linux\"]\r\n","sub_path":"smbl/prog/plugins/pbsim.py","file_name":"pbsim.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"262761297","text":"# \n# fubuild -- functional build system -- Public Domain or Apache 2.0\n# Patrick Crawley\n# \n# \n# This sofware is dual licensed, you may choose either\n# of the two licenses below when using this software.\n# \n# License 1 -- Public Domain\n# \n# This software is in the public domain. Where that dedication is not\n# recognized, you are granted a perpetual, irrevokable license to copy\n# and modify this file as you see fit.\n# \n# License 2 -- Apache 2.0\n# \n# Copyright [2012-2014] [Patrick Crawley]\n# \n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# \n\n################################################################################\n################################################################################\n\nfrom .common import *\nimport shutil\n\n################################################################################\n################################################################################\n\ndef copytree2(src, dst, symlinks=False, ignore=None, copy_function=shutil.copy2, ignore_dangling_symlinks=False):\n \"\"\"Recursively copy a directory tree.\n\n The destination directory must not already exist.\n If exception(s) occur, an Error is raised with a list of reasons.\n\n If the optional symlinks flag is true, symbolic links in the\n source tree result in symbolic links in the destination tree; if\n it is false, the contents of the files pointed to by symbolic\n links are copied. If the file pointed by the symlink doesn't\n exist, an exception will be added in the list of errors raised in\n an Error exception at the end of the copy process.\n\n You can set the optional ignore_dangling_symlinks flag to true if you\n want to silence this exception. Notice that this has no effect on\n platforms that don't support os.symlink.\n\n The optional ignore argument is a callable. If given, it\n is called with the `src` parameter, which is the directory\n being visited by copytree(), and `names` which is the list of\n `src` contents, as returned by os.listdir():\n\n callable(src, names) -> ignored_names\n\n Since copytree() is called recursively, the callable will be\n called once for each directory that is copied. It returns a\n list of names relative to the `src` directory that should\n not be copied.\n\n The optional copy_function argument is a callable that will be used\n to copy each file. It will be called with the source path and the\n destination path as arguments. By default, copy2() is used, but any\n function that supports the same signature (like copy()) can be used.\n\n \"\"\"\n names = os.listdir(src)\n if ignore is not None:\n ignored_names = ignore(src, names)\n else:\n ignored_names = set()\n\n if dst.endswith(os.sep):\n MakeDirectoryForFile(dst)\n else:\n MakeDirectoryForFile(sjoin(dst, ''))\n errors = []\n for name in names:\n if name in ignored_names:\n continue\n srcname = os.path.join(src, name)\n dstname = os.path.join(dst, name)\n try:\n if os.path.islink(srcname):\n linkto = os.readlink(srcname)\n if symlinks:\n os.symlink(linkto, dstname)\n else:\n # ignore dangling symlink if the flag is on\n if not os.path.exists(linkto) and ignore_dangling_symlinks:\n continue\n # otherwise let the copy occurs. copy2 will raise an error\n copy_function(srcname, dstname)\n elif os.path.isdir(srcname):\n copytree2(srcname, dstname, symlinks, ignore, copy_function)\n else:\n # Will raise a SpecialFileError for unsupported file types\n copy_function(srcname, dstname)\n # catch the Error from the recursive copytree so that we can\n # continue with other files\n except shutil.Error as err:\n errors.extend(err.args[0])\n except EnvironmentError as why:\n errors.append((srcname, dstname, str(why)))\n try:\n shutil.copystat(src, dst)\n except OSError as why:\n if shutil.WindowsError is not None and isinstance(why, WindowsError):\n # Copying file access times may fail on Windows\n pass\n else:\n errors.extend((src, dst, str(why)))\n if errors:\n raise shutil.Error(errors)\n\n################################################################################\n################################################################################\n\ndef CreateOsxAppBundle(exe, plistFile, resourcesDirectory, output):\n\tassert output.endswith('.app')\n\n\timport os\n\timport stat\n\n\tMakeDirectoryForFile(sjoin(output, ''))\n\tMakeDirectoryForFile(sjoin(output, 'Contents', ''))\n\tMakeDirectoryForFile(sjoin(output, 'Contents', 'MacOS', ''))\n\tMakeDirectoryForFile(sjoin(output, 'Contents', 'Resources', ''))\n\tMakeDirectoryForFile(sjoin(output, 'Contents', 'Resources', 'English.lproj', ''))\n\n\tif resourcesDirectory:\n\t\ttry:\n\t\t\tcopytree2(resourcesDirectory, sjoin(output, 'Contents', 'Resources', 'English.lproj', ''))\n\t\texcept OSError:\n\t\t\tpass #mkdir error\n\n\tshutil.copyfile(plistFile, sjoin(output, 'Contents', os.path.basename(plistFile)))\n\n\toutExe = sjoin(output, 'Contents', 'MacOS', os.path.basename(output).replace('.app', ''))\n\tshutil.copyfile(exe, outExe)\n\tos.chmod(outExe, stat.S_IRUSR|stat.S_IWUSR|stat.S_IXUSR|stat.S_IRGRP|stat.S_IXGRP|stat.S_IROTH|stat.S_IXOTH)\n\n################################################################################\n################################################################################\n\n","sub_path":"bin/fubuild/createosxappbundle.py","file_name":"createosxappbundle.py","file_ext":"py","file_size_in_byte":6159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"567383722","text":"# -*- coding: utf-8 -*-\n\nimport sqlite3 as db\nimport codecs\nimport random\nimport re\nimport os\n\ncon = db.connect('chat_bot_t.db')\ncur = con.cursor()\nanswer = \"hello\"\ndef GetAnswer( msg ):\n\tglobal answer\n\tmsg = msg.lower()\n\twordList = list()\n\tfor word in msg.split():\n\t\twordList.append(word)\n\n\tcur.execute(\"SELECT * FROM answers\")\n\tresults = cur.fetchall()\n\tresults = list(results)\n\tnum = -1\n\tnumq = -1\n\tfor z in results:\n\t\tnum += 1\n\t\tz = list(z)\n\t\tindex = 0\n\t\tfor k in wordList:\n\t\t\tif(z[0].find(k) != -1):\n\t\t\t\tindex +=1\n\t\tresults[num] = list(results[num])\n\t\tresults[num].append(index)\n\n\tmaxval = max(map(lambda x: x[2], results))\n\tfor z in results:\n\t\tif(z[2] == maxval):\n\t\t\tif(maxval == 0):\n\t\t\t\tAns = results[random.randint(0, num + 1)][1]\n\t\t\telse:\n\t\t\t\tAns = z[1]\n\t\t\tcur.execute(\"INSERT INTO answers VALUES('\"+answer+\"','\"+msg+\"')\")\n\t\t\tcon.commit()\n\t\t\tanswer = Ans\n\t\t\treturn Ans\n","sub_path":"hellbox_bot.py","file_name":"hellbox_bot.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"92464240","text":"import requests\nfrom lxml import html\nfrom urllib.parse import urljoin\n\nclass ImageSender:\n @staticmethod\n def send_image(bot, chat, url, xpath, name, name_xpath=None):\n response = requests.get(url)\n parsed_body = html.fromstring(response.text)\n image = parsed_body.xpath(xpath)\n if name_xpath:\n name = parsed_body.xpath(name_xpath)\n image = urljoin(response.url, image[0])\n bot.sendPhotoUrl(chat, image, name)\n","sub_path":"tools/imageSender.py","file_name":"imageSender.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"212374452","text":"#CPE 202 - Project 3\n#Name: Ajay Patel and Jack Langston\n#Section: 11\n#Instructor: S. Einakian \n\n\nimport sys\nargs = sys.argv\n\nclass HuffmanNode:\n\n #initializes the Node\n #character, frequency --> None\n def __init__(self, char, freq):\n #char is a character with a ascii value\n #freq is the freq of the character in the txt file\n #left is the left child of the node\n #right is the right child of the node\n self.char = char \n self.freq = freq\n self.left = None\n self.right = None\n\n def set_code(self, code):\n self.code = code\n\n def set_left(self, node):\n self.left = node\n\n def set_right(self, node):\n self.right = node\n\n def isLeaf(self):\n return not (self.left or self.right)\n\n def hasLeft(self):\n return self.left\n\n def hasRight(self):\n return self.right\n\n\n\n\nclass HuffmanTree:\n\n #Creates huffman tree\n #None --> None\n def __init__(self):\n #root is a node\n self.root = None\n\n\n#To check whether node a comes before node b \n#node node --> True or False\ndef comes_before(a, b) :\n if a.freq < b.freq:\n return True\n elif a.freq == b.freq and ord(a.char) < ord(b.char):\n return True\n else:\n return False \n \n\n#To count the frequency of strings in file and append frequency to list with ASCII values\n#file --> list\ndef cnt_freq(filename): \n try:\n file = open(filename, 'r')\n except:\n print(\"Input file not found\")\n empty = []\n file = open(filename, 'r')\n for line in file:\n for elements in line:\n empty.append(elements)\n\n freq = {}\n for character in empty:\n if not character in freq: \n freq[character] = 0\n freq[character] += 1\n\n final_list = [0] * 256 \n for x,y in freq.items(): \n x = ord(x)\n final_list[x] = y\n\n return final_list\n\n\n#To take in a list of 256 ASCII values, convert values > 0 to nodes, and make a Huffman tree from the nodes\n#list --> huffman tree\ndef create_huff_tree(char_freq):\n huff_list = []\n for i in range(len(char_freq)):\n if char_freq[i] > 0:\n node = HuffmanNode(chr(i), char_freq[i])\n huff_list.append(node)\n\n if len(huff_list) == 0:\n return None\n\n for node in huff_list:\n node.char = ord(node.char)\n \n while len(huff_list) > 1:\n min1 = find_min(huff_list)\n min2 = findNextMin(huff_list, min1)\n\n newtree = combine(min1, min2)\n\n for node in huff_list:\n if node.freq == min1.freq and node.char == min1.char:\n huff_list.remove(node)\n if node.freq == min2.freq and node.char == min2.char:\n huff_list.remove(node)\n\n huff_list.append(newtree)\n\n return huff_list[0]\n\n\n#To find the nodes in the list with the 2 lowest frequencies\n#list --> int of min frequency referring to node\ndef find_min(nodelist):\n minfreq = nodelist[0]\n for node in nodelist:\n if node.freq < minfreq.freq:\n minfreq = node\n elif node.freq == minfreq.freq:\n if (node.char) < (minfreq.char):\n minfreq = node\n \n return minfreq\n\n\n#To recursivley call find_min without the true min frequency so that the next lowest min is returned\n#list(nodes) int(min frequency) --> int of min frequency referring to node\ndef findNextMin(nodelist, minfreq):\n for node in nodelist:\n if node.freq == minfreq.freq and node.char == minfreq.char:\n nodelist.remove(node)\n return find_min(nodelist)\n\n\n#To create a new node; frequency = sum of 2 min node frequencies, data = lower ASCII value of 2 min nodes\n#node(min 1) node(min 2) --> node \ndef combine(a, b):\n if (a.char) > (b.char):\n newchar = b.char\n else:\n newchar = a.char\n \n newfreq = a.freq + b.freq\n \n if a.freq > b.freq:\n newleft = b\n newright = a\n elif a.freq == b.freq:\n if (a.char) > (b.char):\n newleft = b\n newright = a\n else:\n newleft = a\n newright = b\n else: \n newright = b\n newleft = a\n \n newnode = HuffmanNode(newchar,newfreq) #makes new node\n newnode.left = newleft\n newnode.right = newright\n return newnode\n\n\n#To create a list of the 256 ASCII values so we can append the Huffman leaves \n#string path to corresponding ASCII value; uses a helper function \n#node --> string\ndef create_code(node):\n coded = [None]*256\n str = ''\n rootfreq = node.freq\n return traverse_tree(node, coded, str, rootfreq)\n\n\n#To return the string representing path to leaves in Huffman Tree\n#node, list of 256 ASCII values, empty string, node frequency\ndef traverse_tree(node, coded, str, rootfreq):\n if node.isLeaf():\n coded[node.char] = str\n return\n else:\n if node.hasLeft():\n str = str + '0'\n traverse_tree(node.left, coded, str, rootfreq)\n str = str[:-1]\n if node.hasRight():\n str = str + '1'\n traverse_tree(node.right, coded, str, rootfreq)\n str = str[:-1]\n if node.freq != rootfreq:\n return\n return coded\n\n\n#To write the preorder traversal of our tree\n#Node(tree) --> str\ndef tree_preord(tree):\n prelist = [] \n return preorder_helper(tree, prelist)\n\n#To actually write the preorder traversal\n#node list --> list\ndef preorder_helper(temp, prelist):\n if not temp:\n return\n \n if temp.isLeaf():\n prelist.append('1')\n prelist.append(chr(temp.char))\n else:\n prelist.append('0')\n\n preorder_helper(temp.left, prelist)\n preorder_helper(temp.right, prelist)\n\n if len(prelist) == 2:\n return \"\".join(prelist)\n \n return prelist\n\n\n#To convert the ASCII values to 0's and 1's\n#in_file and empty out file --> out file\ndef huffman_encode(in_file, out_file):\n input_list = cnt_freq(in_file)\n count_original = 0\n listed_file = open(in_file,'r')\n\n file_list = []\n for i in range(len(input_list)):\n if input_list[i] > 0:\n j = i\n count_original += 1\n\n if count_original == 0:\n out_file = open(out_file, \"w\")\n out_file.write(\"\")\n\n elif count_original <= 2:\n out_file = open(out_file, 'w')\n list1 = [chr(j), \" \" ,input_list[j]] \n for i in list1:\n out_file.write(str(i))\n return \n else:\n root = create_huff_tree(input_list)\n final_string = create_code(root)\n out_file = open(out_file, 'w')\n\n for line in listed_file:\n for character in line:\n file_list.append(character)\n\n for i in file_list: \n code = final_string[ord(i)]\n out_file.write(code)\n\n\n#To interpret 0s and 1s into strings and or sentences\n#list, file, empty file --> file of strings\ndef huffman_decode(freqs, encoded_file, decode_file):\n try:\n in_file = open(encoded_file, 'r')\n except FileNotFoundError:\n print(\"Input file not found\")\n \n out_file = open(decode_file, \"w\")\n elements = []\n count = 0\n for line in in_file:\n for element in line:\n count += 1 \n elements.append(element)\n\n if count == 0:\n out_file.write(\"\")\n elif not elements[0].isdigit():\n for i in range(int(elements[2])):\n out_file.write(elements[0])\n else: \n hufftree = create_huff_tree(freqs)\n huffnode = hufftree\n\n for item in elements: \n if item == '0':\n huffnode = huffnode.left\n if item == '1':\n huffnode = huffnode.right\n if huffnode.isLeaf():\n out_file.write(chr(huffnode.char))\n huffnode = hufftree\n","sub_path":"Project5/Project3/huffman.py","file_name":"huffman.py","file_ext":"py","file_size_in_byte":7636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"513010036","text":"# -*- coding: utf-8 -*-\r\n\r\n# Copyright 2015 www.suishouguan.com\r\n#\r\n# Licensed under the Private License (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# https://github.com/samuelbaizg/ssguan/blob/master/LICENSE\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n\r\nimport platform\r\n\r\nfrom tornado.ioloop import IOLoop, PeriodicCallback\r\n\r\nfrom ssguan.ignitor.base import context\r\nfrom ssguan.ignitor.orm.model import Model\r\nfrom ssguan.ignitor.sched import logger\r\nfrom ssguan.ignitor.sched.cronjob import CronJob\r\nfrom ssguan.ignitor.sched.error import SchedRunningError\r\nfrom ssguan.ignitor.utility import kind, parallel, reflect\r\n\r\n\r\nclass Scheduler(object):\r\n \r\n _lock = parallel.create_rlock(process=False)\r\n \r\n def __new__(cls, node): \r\n with cls._lock:\r\n if not hasattr(cls, '_instances'):\r\n cls._instances = {}\r\n if not node in cls._instances:\r\n orig = super(Scheduler, cls) \r\n instance = orig.__new__(cls)\r\n instance._node = node\r\n instance._periodic_callback = None\r\n cls._instances[node] = instance \r\n return cls._instances[node]\r\n \r\n def start(self, interval, io_loop=None):\r\n if self.is_running():\r\n raise SchedRunningError()\r\n func = reflect.wrap_func(self.run_once, Model.NULL_USER_ID)\r\n self._periodic_callback = PeriodicCallback(func, interval * 1000) \r\n self._periodic_callback.start()\r\n if io_loop is None:\r\n io_loop = IOLoop.current()\r\n logger.info(\"Scheduler %s is running per %d seconds.\" % (self._node, interval))\r\n io_loop.start()\r\n \r\n def stop(self):\r\n if self.is_running():\r\n self._periodic_callback.stop()\r\n self._periodic_callback = None\r\n else:\r\n self._periodic_callback = None\r\n \r\n def is_running(self):\r\n state = False\r\n if self._periodic_callback is None:\r\n state = False\r\n else:\r\n state = self._periodic_callback.is_running()\r\n return state\r\n \r\n def run_all(self, caller, broken=None):\r\n query = CronJob.all() \r\n query.filter(\"job_node =\", self._node) \r\n query.filter(\"next_run_time <=\", kind.utcnow())\r\n if broken is not None:\r\n query.filter(\"broken =\", broken)\r\n cronjobs = query.fetch()\r\n for cronjob in cronjobs:\r\n cronjob.run_once(caller)\r\n \r\n def run_once(self, job_id, caller):\r\n cronjob = CronJob.get_by_key(job_id)\r\n cronjob.run_once(caller)\r\n\r\ndef create_cronjob(job_name, job_desc, job_runner, job_node, job_group=None, run_params=None, broken=False, logged=True, singleton=True, fire_year='*', fire_month=1, fire_day=1, fire_week='*', fire_dayofweek='*', fire_hour=0, fire_minute=0, fire_second=0, start_time=None, end_time=None, timezone=kind.tz_utc()):\r\n cronjob = CronJob(job_name=job_name, job_runner=job_runner)\r\n cronjob.job_desc = job_desc\r\n cronjob.job_node = job_node\r\n cronjob.job_group = job_group\r\n cronjob.run_params = run_params\r\n cronjob.broken = broken\r\n cronjob.logged = logged\r\n cronjob.singleton = singleton\r\n cronjob.fire_year = fire_year\r\n cronjob.fire_month = fire_month\r\n cronjob.fire_day = fire_day\r\n cronjob.fire_week = fire_week\r\n cronjob.fire_dayofweek = fire_dayofweek\r\n cronjob.fire_hour = fire_hour\r\n cronjob.fire_minute = fire_minute\r\n cronjob.fire_second = fire_second\r\n cronjob.start_time = start_time\r\n cronjob.end_time = end_time\r\n cronjob.timezone = timezone\r\n cronjob.previous_run_time = None\r\n if not broken:\r\n cronjob.next_run_time = cronjob.get_next_fire_time(None, kind.utcnow())\r\n else:\r\n cronjob.next_run_time = None\r\n cronjob.create(context.get_user_id())\r\n return cronjob\r\n\r\ndef get_cronjob(job_id=None, job_name=None):\r\n cronjob = None\r\n if job_id is not None:\r\n cronjob = CronJob.get_by_key(job_id) \r\n if cronjob is None and job_name is not None:\r\n cronjob = CronJob.get_by_name(job_name)\r\n return cronjob\r\n \r\ndef break_cronjob(job_id, broken):\r\n cronjob = CronJob.get_by_key(job_id)\r\n cronjob.broken = broken\r\n cronjob = cronjob.update(context.get_user_id())\r\n return cronjob\r\n \r\ndef delete_cronjob(job_id):\r\n cronjob = CronJob.get_by_key(job_id)\r\n return cronjob.delete(context.get_user_id())\r\n\r\ndef fetch_cronjobs(job_name=None, job_node=None, job_group=None, broken=None):\r\n query = CronJob.all()\r\n if job_name is not None:\r\n query.filter(\"job_name like\", '%%%s%%' % job_name)\r\n if job_node is not None:\r\n query.filter(\"job_node =\", job_node)\r\n if job_group is not None:\r\n query.filter(\"job_group =\", job_group)\r\n if broken is not None:\r\n query.filter(\"broken =\", broken)\r\n return query.fetch()\r\n\r\ndef start(node, interval=1, io_loop=None):\r\n node = platform.node() if node is None else node\r\n scheduler = Scheduler(node)\r\n scheduler.start(interval, io_loop=io_loop)\r\n\r\n\r\n\r\n","sub_path":"ssguan/ignitor/sched/scheduler.py","file_name":"scheduler.py","file_ext":"py","file_size_in_byte":5494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"426783620","text":"# https://leetcode.com/problems/linked-list-cycle-ii/description/\n\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def detectCycle(self, head):\n i = head\n j = head\n p = None\n while i and j and j.next:\n i = i.next\n j = j.next.next\n if i == j:\n p = i\n break\n \n if p == None:\n return None\n q = head\n while p != q:\n p = p.next\n q = q.next\n return p\n","sub_path":"leetcode/linked_list_cycle_II.py","file_name":"linked_list_cycle_II.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"380338001","text":"#C:\\Users\\saurabhj\\OneDrive\\Documents\\Python Scripts\\RL\n#https://github.com/saurabhjadhav1911/RL.git\nfrom colorama import Fore, Back, Style\nimport colorama\ncolorama.init()\nfrom misc import *\nimport serial\nimport multiprocessing\nimport time\nimport traceback\n\nvalue = 0\nlav = 0\nnf = 0\ncolor = Fore.GREEN\n\n\nclass Env():\n \"\"\"docstring for Env\"\"\"\n\n def __init__(self, config):\n print(color + 'Env created')\n self.config = config\n self.ser = self.get_Serial()\n self.default_action = config['Env_config']['default_action']\n self.data = \"\"\n\n def get_Serial(self):\n return serial.Serial(\n self.config['Serial_config']['port'],\n baudrate=self.config['Serial_config']['baud'],\n timeout=self.config['Serial_config']['timeout'])\n\n def reset(self):\n self.action(self.default_action)\n return self.read_state()\n\n def action(self, act):\n line = \"G \" + \" \".join(map(str, act))\n print(color, line)\n #self.serial.write(line)\n\n def run(self, q, r, agent_obs_que, agent_reward_que, agent_action_que):\n #ser=serial.Serial(config['Serial_config']['port'],baudrate=config['Serial_config']['baud'],timeout=config['Serial_config']['timeout'])\n print(color, \"Serial communicatoion started\")\n while True:\n self.read_write_state(q, r)\n\n def read_write_state(self, q, r):\n global value, lav\n flag = False\n while r.empty() is False:\n flag = True\n arr = \" \".join(map(str, r.get()))\n arr += \"|\"\n #unicode(s, \"utf-8\")\n if (self.config['Env_config']['show_obs']):\n\n print(color, self.config['Env_config']['show_obs'], arr)\n self.ser.write(arr.encode())\n\n if (self.ser.inWaiting() > 0):\n c, timestamp = self.ser.read(), time.time()\n #print(color,c)\n try:\n c = str(c, 'utf-8')\n if c is '|':\n\n #dta=data\n #nf+=1\n lav = value\n\n if self.config['Env_config']['Env_vector_size'] > 1:\n value = list(map(int, self.data.split()))\n else:\n value = int(self.data)\n #if lav is not value:\n value.append(timestamp)\n if (self.config['Env_config']['show_obs']):\n print(color, self.config['Env_config']['show_obs'],\n self.data)\n q.put(value)\n #v=q.get()\n self.data = \"\"\n else:\n self.data += c\n except Exception as e:\n exc_traceback = traceback.format_exc()\n print(color, exc_traceback)\n #pass\n def test_run(self, q, r):\n #ser=serial.Serial(config['Serial_config']['port'],baudrate=config['Serial_config']['baud'],timeout=config['Serial_config']['timeout'])\n while True:\n self.read_write_state(q, r)\n\n\n############################ testing Env ############################\n\n\ndef Env_process_target(recieve_que, send_que, config):\n print(color, 'Env process start')\n env = Env(config)\n env.run(recieve_que, send_que)\n\n\ndef Test_process_target(recieve_que, send_que, config):\n\n print(color, 'Test process start')\n generate_step(recieve_que, send_que, config)\n\n\ndef main():\n multiprocessing.freeze_support()\n\n config = read_config('config_crawler.json')\n config = arg_parser(config)\n save_config(config, 'config_crawler.json')\n #initialise communicatoions between processes\n send_que = multiprocessing.Queue()\n recieve_que = multiprocessing.Queue()\n\n #process initialisation\n\n env_process = multiprocessing.Process(\n target=Env_process_target, args=(recieve_que, send_que, config))\n test_process = multiprocessing.Process(\n target=Test_process_target, args=(recieve_que, send_que, config))\n\n env_process.start()\n test_process.start()\n #con.start()\n test_process.join()\n env_process.join()\n #prod.join()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"RL_SPIDER/Env.py","file_name":"Env.py","file_ext":"py","file_size_in_byte":4223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"549742054","text":"# -*- coding: utf-8 -*-\n# Part of BrowseInfo. See LICENSE file for full copyright and licensing details.\n\nfrom odoo import api, fields, models, _\n\n\nclass AccountCommonReport(models.TransientModel):\n _inherit = \"account.common.report\"\n\n branch_ids = fields.Many2one('res.branch', string='Branch')\n \n def _build_contexts(self, data):\n result = {}\n data['form']['branch_ids'] = self.read(['branch_ids'])[0]\n result['branch_ids'] = \\\n 'branch_ids' in data['form'] \\\n and data['form']['branch_ids'] or False\n branch_name_long = ''\n if result['branch_ids'].get('branch_ids'):\n branch_name = self.env['res.branch'].browse(result['branch_ids'].get('branch_ids')[0]).name\n branch_name_long += branch_name \n result['branch_ids'] = branch_name_long\n result['journal_ids'] = 'journal_ids' in data['form'] and data['form']['journal_ids'] or False\n result['state'] = 'target_move' in data['form'] and data['form']['target_move'] or ''\n result['date_from'] = data['form']['date_from'] or False\n result['date_to'] = data['form']['date_to'] or False\n result['strict_range'] = True if result['date_from'] else False\n return result\n\n\n\n\n\n\n\n\n\n","sub_path":"branch/wizard/account_common_report.py","file_name":"account_common_report.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"132716567","text":"from django.contrib import admin\nfrom django.urls import path\nfrom . import views\nurlpatterns = [\n\n path('watchmoon', views.watchmoon, name=\"watchmoon\"),\n path('watchsunset', views.watchsunset, name=\"watchsunset\"),\n path('watchgallery', views.watchgallery, name=\"watchgallery\"),\n path('playbedroom', views.playbedroom, name=\"playbedroom\"),\n path('readletters', views.readletters, name=\"readletters\"),\n path('playmusic', views.playmusic, name=\"playmusic\"),\n path('timeline', views.timeline, name=\"timeline\"),\n\n]\n","sub_path":"activity/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"102751821","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport doc2vec\nfrom gensim import models\n\nmodel = models.Doc2Vec.load('doc2vec.model')\n\n# 似た文章を探す\n# id : メールアドレス\ndef search_similar_texts(id, num): \n most_similar_texts = model.docvecs.most_similar(id)\n similar_list = []\n i = 0\n for similar_text in most_similar_texts:\n similar_list.append(most_similar_texts[i])\n i += 1\n if((i+1)>num):\n break\n return similar_list\n \nif __name__ == '__main__':\n print('文字列入力:')\n search_str = input()\n search_similar_texts(search_str)\n","sub_path":"takenaka/bot/doc2vec_search.py","file_name":"doc2vec_search.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"308310635","text":"# -*- coding: utf-8 -*-\n# Author : Seungyeon Jo\n# e-mail : syjo@seculayer.co.kr\n# Powered by Seculayer © 2018 AI-Core Team\n\nfrom mlps.core.data.cnvrtr.ConvertAbstract import ConvertAbstract\nimport re\n\n\nclass RegexGet(ConvertAbstract):\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.reg = re.compile(self.arg_list[0])\n \n def apply(self, data):\n result = ''\n \n # check blank\n if self._isBlank(data):\n return [result]\n \n try:\n result = self.reg.match(data).groups()\n if len(result) > 0:\n result = result[0]\n except Exception as e:\n self.LOGGER.error(str(e))\n result = ''\n \n return [result]\n\n\nif __name__ == \"__main__\":\n _str = \"prefix_123_suffix\"\n print(RegexGet(arg_list=[\"[a-z]+_(\\\\d+)_[a-z]+\"]).apply(_str))\n","sub_path":"mlps/core/data/cnvrtr/functions/RegexGet.py","file_name":"RegexGet.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"446685151","text":"#LC 931 - Minimum Falling Path Sum\r\n#Time Complexity - O(n^2)\r\n#Space Complexity - O(1)\r\nclass Solution(object):\r\n def minFallingPathSum(self, A):\r\n \"\"\"\r\n :type A: List[List[int]]\r\n :rtype: int\r\n \"\"\"\r\n \r\n for i in range(1,len(A)):\r\n for j in range(len(A[0])):\r\n if j == 0:\r\n A[i][j] = A[i][j] + min(A[i-1][j],A[i-1][j+1])\r\n elif j == len(A[0])-1:\r\n A[i][j] = A[i][j] + min(A[i-1][j],A[i-1][j-1])\r\n else:\r\n A[i][j] = A[i][j] + min(A[i-1][j],A[i-1][j-1],A[i-1][j+1])\r\n \r\n \r\n return min(A[-1])","sub_path":"PA_23.py","file_name":"PA_23.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"41786631","text":"import math\r\nfor t in range(int(input())):\r\n n=int(input())\r\n a=list(map(int,input().split()))\r\n b=list(map(int,input().split()))\r\n\r\n ind=[]\r\n mini=math.inf\r\n for i in range(n):\r\n if (a[0]+b[i])%n5 or self.grade < 1:\n print(\"Ooops, sg's wrong! Try again!\")\n else:\n self.grades_list.append(self.grade)\n\n def salute(self):\n self.average = sum(self.grades_list) / len(self.grades_list)\n print(\"Your average is: %s.\" % (self.average))\n\nstudent1 = Student(\"Emma\", \"Parker\")\nstudent1.greet()\nstudent1.add_grades(5)\nstudent1.add_grades(2)\nstudent1.add_grades(3)\nstudent1.add_grades(5)\nstudent1.salute()\nstudent1.add_grades(6)\n","sub_path":"week-03/day-3/08.py","file_name":"08.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"98647768","text":"import pygame, sys\nfrom pygame.locals import *\nimport time\nimport tkinter\nfrom tkinter import *\n\n'''anything go with rect use the form (left, top, width, height)'''\n\npygame.init()\n#from this is the define for game statistics\nFPS = 60\nfpsClock = pygame.time.Clock()\n\nWINDOWSIZE = (1280,720) #window size\n\npygame.display.set_caption('Racing bet 888') #set Caption for title bar\n\nMAINMENUSCREEN = pygame.image.load('image\\mainmenu.png')\nMAINMENUSCREEN = pygame.transform.scale(MAINMENUSCREEN, WINDOWSIZE) #create background image\n\nmenuSound = pygame.mixer.Sound('soundFX\\menu.wav') #open sound\n\nDISPLAYSURFACE = pygame.display.set_mode(WINDOWSIZE) #create surface for mainmenu\ngMoney = 0\ncharacterSet = None\n\n#define font using \nfont = pygame.font.SysFont(None, 20, bold=True, italic=False) #set font for drawing\nmediumfont = pygame.font.SysFont(None, 30, bold = True, italic = False)\nbigfont = pygame.font.SysFont(None, 40, bold = True, italic = False)\n\n#end define the game statistics\n#------------------------------------------------------------------------------------------------#\n\n#drawing text on screen\ndef draw_text(text, font, color, surface, x, y): \n textobj = font.render(text, 1, color)\n textrect = textobj.get_rect()\n textrect.topleft = (x,y)\n surface.blit(textobj, textrect)\n return 1\n\n#running main menu\ndef mainMenu(money, characterSet):\n Running = True\n clicked = False\n toggleMenuSub = False\n\n while Running:\n #menuSound.play(-1) #repeat sound\n DISPLAYSURFACE.blit(MAINMENUSCREEN, (0,0)) #draw background\n draw_text(str(money), mediumfont, (255,0,0), DISPLAYSURFACE, 700, 630)\n draw_text('YOUR CURRENT SET IS: ' + str(characterSet), font, (0,0,0), DISPLAYSURFACE, 550, 200)\n #define the Buttons\n exitButton = pygame.Rect(40, 20, 100, 65)\n helpButton = pygame.Rect(55, 580, 110, 100)\n miniGameButton = pygame.Rect(200, 580, 110, 100)\n changeSetButton = pygame.Rect(350, 580, 110, 100)\n shopButton = pygame.Rect(885, 580, 90, 95)\n gameButton = pygame.Rect(1050, 580, 210, 100)\n playButton = pygame.Rect(1075, 470, 120, 40)\n changeNameButton = pygame.Rect(1075, 515, 120, 40)\n\n #GET MOUSE CLICK\n dx, dy = pygame.mouse.get_pos() #get clicked\n\n #if mouse click execute\n if exitButton.collidepoint(dx, dy):\n if clicked:\n exitConfirmScreen()\n if helpButton.collidepoint(dx, dy):\n if clicked:\n helpScreen()\n if miniGameButton.collidepoint(dx, dy):\n if clicked:\n money = miniGameScreen(money)\n if changeSetButton.collidepoint(dx, dy):\n if clicked:\n characterSet = changeSetScreen(characterSet)\n if shopButton.collidepoint(dx, dy):\n if clicked:\n money = shopScreen(money)\n if gameButton.collidepoint(dx, dy):\n if clicked:\n toggleMenuSub = not toggleMenuSub\n if playButton.collidepoint(dx, dy):\n if clicked and toggleMenuSub:\n draw_text('PRESSED', mediumfont, (0,0,0), DISPLAYSURFACE, 500, 500)\n if changeNameButton.collidepoint(dx, dy):\n if clicked and toggleMenuSub:\n draw_text('PRESSED', mediumfont, (0,0,0), DISPLAYSURFACE, 500, 500)\n clicked = False\n\n #checking exit game or input mouse click\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n if event.type == MOUSEBUTTONDOWN:\n if event.button == 1:\n clicked = True\n #if menusub is on then draw it \n if toggleMenuSub:\n drawGameMenuSub()\n\n #update screen every frame of loop\n fpsClock.tick(FPS)\n pygame.display.update() #update screen every execution\n return Running #return the running status to main\n\ndef exitConfirmScreen():\n running = True\n clicked = False\n while running:\n DISPLAYSURFACE.fill((0,0,0))\n draw_text('Confirm Exit?', bigfont, (255,255,255), DISPLAYSURFACE, 500, 200)\n dx, dy = pygame.mouse.get_pos()\n\n #define and draw yes/no buttons\n yesButton = pygame.Rect(480, 300, 50, 50)\n noButton = pygame.Rect(680, 300, 50, 50)\n pygame.draw.rect(DISPLAYSURFACE, (255,255,255), yesButton)\n draw_text('Yes', font, (0,0,0), DISPLAYSURFACE, 490, 320)\n pygame.draw.rect(DISPLAYSURFACE, (255,255,255), noButton)\n draw_text('No', font, (0,0,0), DISPLAYSURFACE, 695, 320)\n\n if yesButton.collidepoint(dx,dy):\n if clicked:\n pygame.exit()\n sys.exit()\n elif noButton.collidepoint(dx,dy):\n if clicked:\n running = False\n\n clicked = False\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n if event.type == MOUSEBUTTONDOWN:\n if event.button == 1:\n clicked = True\n if event.type == KEYDOWN:\n if event.key == K_ESCAPE:\n running = False\n fpsClock.tick(FPS)\n pygame.display.update()\n return running\n\ndef drawHelp():\n draw_text('HELP', bigfont, (255,255,255), DISPLAYSURFACE, 620, 20)\n draw_text('Welcome to Racing Bet Game', mediumfont, (255,255,255), DISPLAYSURFACE, 500, 50)\n draw_text('Nothing to see here at this time', font, (255,255,255), DISPLAYSURFACE, 550, 100)\n draw_text('Press ESC Key to return Main Menu', font, (255,255,255), DISPLAYSURFACE, 530, 120)\n\ndef helpScreen():\n running = True\n while running:\n DISPLAYSURFACE.fill((0,0,0))\n drawHelp()\n #check event\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n if event.type == KEYDOWN:\n if event.key == K_ESCAPE:\n running = False\n fpsClock.tick(FPS)\n pygame.display.update()\n\ndef miniGameScreen(money):\n running = True\n while running:\n DISPLAYSURFACE.fill((0,0,0))\n draw_text('Nothing to see at this time', bigfont, (255,255,255), DISPLAYSURFACE, 450, 300)\n money = miniGameEvent(money)\n draw_text('Money at this time is: ' + str(money), mediumfont, (255,255,255), DISPLAYSURFACE, 500, 400)\n draw_text('Press ESC Key to return Main Menu', font, (255,255,255), DISPLAYSURFACE, 530, 120)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n if event.type == KEYDOWN:\n if event.key == K_ESCAPE:\n running = False\n fpsClock.tick(FPS)\n pygame.display.update()\n return money\n\ndef miniGameEvent(money):\n money += 10\n return money\n\ndef changeSetScreen(selectedSet):\n running = True\n while running:\n DISPLAYSURFACE.fill((0,0,0))\n draw_text('CHOSE YOUR FAVORITE SET: ', bigfont, (255,255,255), DISPLAYSURFACE, 400, 50)\n draw_text('YOUR CURRENT SET IS: ' + str(selectedSet), mediumfont, (255,255,255), DISPLAYSURFACE, 450, 100) \n draw_text('Press 1 to 5 to choose set', mediumfont, (255,255,255), DISPLAYSURFACE, 480, 150)\n draw_text('Press ESC Key to return Main Menu', mediumfont, (255,255,255), DISPLAYSURFACE, 415, 200)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n if event.type == KEYDOWN:\n if event.key == ord('1'):\n selectedSet = 1\n if event.key == ord('2'):\n selectedSet = 2\n if event.key == ord('3'):\n selectedSet = 3\n if event.key == ord('4'):\n selectedSet = 4\n if event.key == ord('5'):\n selectedSet = 5\n if event.key == K_ESCAPE:\n running = False\n\n fpsClock.tick(FPS)\n pygame.display.update()\n return selectedSet\n\ndef shopScreen(money):\n running = True\n while running:\n DISPLAYSURFACE.fill((0,0,0))\n draw_text('Nothing at this time', bigfont, (255,255,255), DISPLAYSURFACE, 470, 300)\n draw_text('Money at this time is: ' + str(money), mediumfont, (255,255,255), DISPLAYSURFACE, 490, 350)\n draw_text('Press ESC Key to return Main Menu', font, (255,255,255), DISPLAYSURFACE, 490, 200)\n draw_text('Press 1 to 5 to buy', font, (255,255,255), DISPLAYSURFACE, 550, 400)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n if event.type == KEYDOWN:\n if event.key == ord('1'):\n if money < 100:\n draw_text('YOU DON\\'T HAVE ENOUGHT MONEY', bigfont, (255,255,255), DISPLAYSURFACE, 400, 500)\n else:\n money -= 100\n if event.key == ord('2'):\n if money < 200:\n draw_text('YOU DON\\'T HAVE ENOUGHT MONEY', bigfont, (255,255,255), DISPLAYSURFACE, 400, 500)\n else: \n money -= 200\n if event.key == ord('3'):\n if money < 300:\n draw_text('YOU DON\\'T HAVE ENOUGHT MONEY', bigfont, (255,255,255), DISPLAYSURFACE, 400, 500)\n else:\n money -= 300\n if event.key == ord('4'):\n if money < 400:\n draw_text('YOU DON\\'T HAVE ENOUGHT MONEY', bigfont, (255,255,255), DISPLAYSURFACE, 400, 500)\n else: \n money -= 400\n if event.key == ord('5'):\n if money < 500:\n draw_text('YOU DON\\'T HAVE ENOUGHT MONEY', bigfont, (255,255,255), DISPLAYSURFACE, 400, 500)\n else: \n money -= 500 \n if event.key == K_ESCAPE:\n running = False\n fpsClock.tick(FPS)\n pygame.display.update()\n return money\n\ndef drawGameMenuSub():\n subMenuArea = pygame.Rect(1060, 460, 150, 100)\n pygame.draw.rect(DISPLAYSURFACE, (255,255,255), subMenuArea)\n playButton = pygame.Rect(1075, 470, 120, 40)\n changeNameButton = pygame.Rect(1075, 515, 120, 40)\n pygame.draw.rect(DISPLAYSURFACE, (0,0,0), playButton, 3)\n pygame.draw.rect(DISPLAYSURFACE, (0,0,0), changeNameButton, 3)\n draw_text('PLAY', font, (0,0,0), DISPLAYSURFACE, 1115, 485)\n draw_text('CHANGE NAME', font, (0,0,0), DISPLAYSURFACE, 1080, 530)\n\ndef playScreen():\n pass\n\ndef changeNameScreen():\n pass\n\ndef main():\n Running = True\n while Running:\n Running = mainMenu(gMoney, characterSet)\n\nif __name__ == \"__main__\":\n main()\n\n#end of file","sub_path":"SourceCode/mainMenu.py","file_name":"mainMenu.py","file_ext":"py","file_size_in_byte":11110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"397977695","text":"\"\"\"\r\n@author: nianhui guo\r\n@license: (C) Copyright 2020-2020, NWPU\r\n@contact: guonianhui199512@gmail.com\r\n@software: BNN\r\n@file: resent.py\r\n@time: 2020/10/17 14:22\r\n@desc:Binary Neural Network Optimization\r\n\"\"\"\r\n\r\nimport sys\r\nimport math\r\nimport random\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nfrom torchvision.transforms import transforms\r\nfrom .modules import BConv, MultiBConv, GhostSign, GhostBNSign\r\n\r\n\r\n__all__ = ['boolnet18', 'boolnet34']\r\n\r\n \r\ndef init_model(model):\r\n for m in model.modules():\r\n \r\n if isinstance(m, (nn.Conv2d)):\r\n nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\r\n \r\n if isinstance(m, BConv):\r\n m.weight.data.clamp_(-0.99, 0.99)\r\n \r\n if m.bias is not None:\r\n nn.init.constant_(m.bias, 0)\r\n \r\n elif isinstance(m, (BConv, MultiBConv)):\r\n nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\r\n \r\n m.weight.data.mul_(1e-2)\r\n #m.weight.data.clamp_(-0.5, 0.5)\r\n \r\n if m.temperature is not None:\r\n nn.init.constant_(m.temperature, 1)\r\n \r\n elif isinstance(m, GhostSign):\r\n \r\n if m.temperature is not None:\r\n nn.init.constant_(m.temperature, 1)\r\n \r\n #if m.length_1 is not None:\r\n # nn.init.constant_(m.length_1, 1)\r\n \r\n #if m.length_2 is not None:\r\n # nn.init.constant_(m.length_2, 1)\r\n \r\n elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm, nn.InstanceNorm2d)):\r\n if m.weight is not None:\r\n nn.init.constant_(m.weight, 1)\r\n \r\n if m.bias is not None:\r\n nn.init.constant_(m.bias, 0)\r\n \r\n if m.running_mean is not None:\r\n nn.init.constant_(m.running_mean, 0)\r\n \r\n if m.running_var is not None:\r\n nn.init.constant_(m.running_var, 1) \r\n\r\n\r\ndef OR(x, y): # -1,1\r\n y_l = y.add(1).div(2) # 0,1\r\n x_l = x.add(1).div(2) # 0,1\r\n\r\n return ((x_l.add(y_l).clamp(0,1).mul(2).add(-1)))\r\n\r\ndef XOR(x, y): #-1,1/1,-1\r\n y = XNOR(x, -y)\r\n\r\n return y\r\n\r\ndef XNOR(x, y): #-1,1\r\n\r\n return x.mul(y)\r\n\r\n\r\nclass Conv1x1(nn.Module):\r\n def __init__(self,\r\n in_channels = 3,\r\n out_channels = 64,\r\n stride = 1,\r\n dilation = 1,\r\n groups = 1,\r\n bias = False):\r\n super(Conv1x1, self).__init__()\r\n \r\n self.Conv1x1 = nn.Conv2d(in_channels, out_channels, 1, stride = stride, padding = 0, groups = groups, bias = bias) \r\n \r\n def forward(self, x):\r\n return self.Conv1x1(x)\r\n \r\nclass BasicBlock(nn.Module):\r\n expansion = 1\r\n \r\n def __init__(self, in_channels = 16, out_channels = 16, stride = 1, dilation = 1, groups = 1, bias = False, downsample=None, base_width = 64, last_block = False, max_slices = 4):\r\n super(BasicBlock, self).__init__()\r\n self.max_slices = max_slices\r\n \r\n stochastic = False\r\n\r\n self.conv_slices_1 = 2**(random.randint(0,int(math.log(max_slices)/math.log(2)))) if stochastic else self.max_slices #specify an int even number to tell the slices to be used(less than max_slices)\r\n self.conv_slices_2 = 2**(random.randint(0,int(math.log(max_slices)/math.log(2)))) if stochastic else self.max_slices #specify an int even number to tell the slices to be used(less than max_slices)\r\n \r\n self.stride = stride\r\n \r\n self.in_channels = in_channels\r\n \r\n self.conv1 = MultiBConv(self.in_channels, out_channels, 3, stride, 1, dilation, groups = self.conv_slices_1, bias = bias, wb = True) \r\n self.conv2 = MultiBConv(out_channels, out_channels, 3, 1, 1, dilation, groups = self.conv_slices_2, bias = bias, wb = True)\r\n \r\n self.bn1 = nn.BatchNorm2d(out_channels)\r\n self.bn2 = nn.BatchNorm2d(out_channels)\r\n self.bn3 = nn.BatchNorm2d(out_channels)\r\n\r\n self.ghostsign1 = GhostSign(out_channels, slices = max_slices)\r\n self.ghostsign2 = GhostSign(out_channels, slices = max_slices)\r\n\r\n \r\n self.downsample = downsample\r\n \r\n self.last_block = last_block\r\n \r\n \r\n self.stride = stride\r\n \r\n def forward(self, x):\r\n N, S, C, H, W = x.size()\r\n \r\n residual = x\r\n\r\n if self.downsample is not None:\r\n residual = self.downsample(residual.view(N, -1, H, W))\r\n \r\n x = self.conv1(x)\r\n x = self.bn1(x)\r\n x = self.ghostsign1(x)\r\n x = XNOR(x, residual) \r\n \r\n \r\n z = self.conv2(x)\r\n z = self.bn2(z)\r\n \r\n if not self.last_block:\r\n z = self.ghostsign2(z)\r\n z = OR(z, residual)\r\n\r\n else:\r\n z = z + self.bn3(x.mean(1)) \r\n \r\n return z\r\n\r\nclass BoolNet(nn.Module):\r\n def __init__(self, block, layers, num_classes=10, zero_init_residual=False,\r\n\r\n groups=1, width_per_group=64, replace_stride_with_dilation=None,\r\n\r\n max_slices = 4, binary_downsample=False):\r\n\r\n super(BoolNet, self).__init__() \r\n expansion = 1\r\n \r\n if replace_stride_with_dilation is None:\r\n # each element in the tuple indicates if we should replace\r\n # the 2x2 stride with a dilated convolution instead\r\n replace_stride_with_dilation = [False, False, False]\r\n \r\n if len(replace_stride_with_dilation) != 3:\r\n raise ValueError(\"replace_stride_with_dilation should be None \"\r\n \"or a 3-element tuple, got {}\".format(replace_stride_with_dilation))\r\n \r\n scale = 1 \r\n self.groups = groups\r\n self.base_width = width_per_group\r\n self.binary_downsample = binary_downsample\r\n \r\n self.inplanes = 64*scale\r\n self.dilation = 1\r\n \r\n self.max_slices = max_slices\r\n \r\n self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3, bias = False)\r\n\r\n self.maxpool = nn.Sequential(\r\n nn.BatchNorm2d(self.inplanes),\r\n nn.MaxPool2d(kernel_size = 3, stride = 2, padding = 1)\r\n )\r\n \r\n self.ghostbnsign = nn.Sequential(\r\n nn.BatchNorm2d(self.inplanes),\r\n GhostSign(self.inplanes, slices = max_slices)\r\n )\r\n\r\n self.layer1 = self._make_layer(block, 64*scale, layers[0], max_slices = self.max_slices)\r\n\r\n self.layer2 = self._make_layer(block, 128*scale, layers[1], stride=2,\r\n\r\n dilate=replace_stride_with_dilation[0], max_slices = self.max_slices)\r\n\r\n self.layer3 = self._make_layer(block, 256*scale, layers[2], stride=2,\r\n\r\n dilate=replace_stride_with_dilation[1], max_slices = self.max_slices)\r\n\r\n self.layer4 = self._make_layer(block, 512*scale, layers[3], stride=2,\r\n\r\n dilate=replace_stride_with_dilation[2], max_slices = self.max_slices)\r\n \r\n self.layer4[-1].last_block = True\r\n \r\n self.prelu2 = nn.PReLU(512* scale * block.expansion)\r\n self.avgpool = nn.AdaptiveAvgPool2d((1, 1))\r\n \r\n self.fc = nn.Linear(512* scale * block.expansion, num_classes)\r\n \r\n # Zero-initialize the last BN in each residual branch,\r\n\r\n # so that the residual branch starts with zeros, and each residual block behaves like an identity.\r\n\r\n # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677\r\n\r\n if zero_init_residual:\r\n\r\n for m in self.modules():\r\n\r\n if isinstance(m, BasicBlock):\r\n \tnn.init.constant_(m.bn2.weight, 1e-8)\r\n \r\n init_model(self)\r\n \r\n self.distillation_loss = 0\r\n \r\n self.name = 'boolnet'\r\n \r\n def _make_layer(self, block, planes, blocks, stride=1, dilate=False, max_slices = 4):\r\n\r\n downsample = None\r\n\r\n previous_dilation = self.dilation\r\n\r\n if dilate:\r\n\r\n self.dilation *= stride\r\n\r\n stride = 1\r\n\r\n if stride != 1 or self.inplanes != planes * block.expansion:\r\n if self.binary_downsample:\r\n downsample = nn.Sequential(\r\n BConv(self.inplanes*max_slices, planes * block.expansion, kernel_size = 1, stride = 1, padding = 0, groups = 1),\r\n nn.MaxPool2d(kernel_size = 2, stride = 2),\r\n nn.BatchNorm2d(planes * block.expansion),\r\n GhostSign(planes * block.expansion, slices = max_slices)\r\n )\r\n else:\r\n downsample = nn.Sequential(\r\n nn.Conv2d(self.inplanes*max_slices, planes * block.expansion, kernel_size = 1, stride = 1, padding = 0, groups = max_slices),\r\n nn.AvgPool2d(kernel_size=2, stride=2),\r\n nn.BatchNorm2d(planes * block.expansion),\r\n GhostSign(planes * block.expansion, slices=max_slices)\r\n )\r\n\r\n layers = []\r\n\r\n layers.append(block(self.inplanes, planes, stride, previous_dilation, self.groups, False, downsample, max_slices = max_slices))\r\n \r\n self.inplanes = planes * block.expansion\r\n\r\n for _ in range(1, blocks):\r\n\r\n layers.append(block(self.inplanes, planes, 1, self.dilation, self.groups, False,\r\n None, base_width = self.base_width, max_slices = max_slices\r\n ))\r\n\r\n return nn.Sequential(*layers)\r\n \r\n def forward(self, x):\r\n out = []\r\n \r\n x = self.conv1(x)\r\n x = self.maxpool(x)\r\n x = self.ghostbnsign(x)\r\n \r\n x = self.layer1(x)\r\n x = self.layer2(x)\r\n x = self.layer3(x)\r\n x = self.layer4(x)\r\n \r\n x = self.prelu2(x)\r\n \r\n out = self.fc(self.avgpool(x).contiguous().view(x.size(0), -1))\r\n \r\n return out\r\n \r\nclass boolnet18(BoolNet):\r\n \"\"\"Constructs a resnet18 model with Binarized weight and activation. \r\n \r\n Args:\r\n num_classes(int): an int number used to identify the num of classes, default 10\r\n inflate(int): an int number used to control the width of a singel convolution layer, default 4(4*16)\r\n \"\"\"\r\n def __init__(self, block = BasicBlock, layers = [2, 2, 2, 2], num_classes = 10, max_slices = 4, binary_downsample = False):\r\n super(boolnet18, self).__init__(block = block, layers = layers, num_classes = num_classes, max_slices = max_slices, binary_downsample = binary_downsample)\r\n \r\n self.name = 'boolnet18'\r\n \r\nclass boolnet34(BoolNet):\r\n \"\"\"Constructs a resnet34 model with Binarized weight and activation. \r\n \r\n Args:\r\n num_classes(int): an int number used to identify the num of classes, default 10\r\n inflate(int): an int number used to control the width of a singel convolution layer, default 4(4*16)\r\n \r\n \"\"\"\r\n def __init__(self, block = BasicBlock, layers = [3, 4, 6, 3], num_classes = 10, max_slices = 4, binary_downsample = False):\r\n super(boolnet34, self).__init__(block = block, layers = layers, num_classes = num_classes, max_slices = max_slices, binary_downsample = binary_downsample)\r\n \r\n self.name = 'boolnet34'\r\n","sub_path":"BaseNet_k_1/src/models/boolnet.py","file_name":"boolnet.py","file_ext":"py","file_size_in_byte":11914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"91828107","text":"from room import Room\nfrom player import Player\nfrom item import Item\n\n# Declare all the rooms\n\nroom = {\n 'outside': Room(\"Outside Cave Entrance\",\n\"North of you, the cave mount beckons.\\n\"),\n\n 'foyer': Room(\"Foyer\", \"\"\"Dim light filters in from the south. Dusty\npassages run north and east.\\n\"\"\"),\n\n 'overlook': Room(\"Grand Overlook\", \"\"\"A steep cliff appears before you, falling\ninto the darkness. Ahead to the north, a light flickers in\nthe distance, but there is no way across the chasm.\\n\"\"\"),\n\n 'narrow': Room(\"Narrow Passage\", \"\"\"The narrow passage bends here from west\nto north. The smell of gold permeates the air.\\n\"\"\"),\n\n 'treasure': Room(\"Treasure Chamber\", \"\"\"You've found the long-lost treasure\nchamber! Sadly, it has already been completely emptied by\nearlier adventurers. The only exit is to the south.\\n\"\"\"),\n}\n\nplayer = {'default_character': Player('Terrance', room['outside']),}\n\n\n# Link rooms together\n\n# room['outside'].n_to = room['foyer']\n# room['foyer'].s_to = room['outside']\n\n# room['foyer'].n_to = room['overlook']\n# room['foyer'].e_to = room['narrow']\n\n# room['overlook'].s_to = room['foyer']\n\n# room['narrow'].w_to = room['foyer']\n# room['narrow'].n_to = room['treasure']\n# room['treasure'].s_to = room['narrow']\n\nroom['outside'].connectRooms(room['foyer'], 'n')\nroom['foyer'].connectRooms(room['overlook'], 'n')\nroom['foyer'].connectRooms(room['narrow'], 'e')\nroom['narrow'].connectRooms(room['treasure'], 'n')\n\nrock = Item('rock', 'large, grey boulder near the entrance to the cave.')\n\nroom['outside'].addItem(rock)\n\n\ndef printErrorString(errorString):\n print(\"\\n{}\\n\".format(errorString))\n global noPrint\n noPrint = True\n\n\n\nvalidDirection = ['n', 's', 'e', 'w']\nnoPrint = False\ncurrent_room = room['outside']\nuser_character = player['default_character']\nprint(\"Welcome to the game!\")\ninp = input(\"Type 'Terrance' to play as default character, or Type 'C' to create a character:\")\nif inp == 'Terrance':\n user_character == player['default_character']\n print(user_character)\nelif inp == 'C' or inp == 'c':\n user_character = Player(input(\"Please enter your characters name: \"), start_room = room['outside'])\n print('Welcome, {}!'.format(user_character.name))\n\n\ndef lookCommand(player, *args):\n if len(args) == 1:\n return False\n elif args[1] in validDirection:\n lookRoom = user_character.location.getRoomInDirection(args[1])\n if lookRoom == None:\n printErrorString('\\nThere is nothing to see that way\\n')\n return True\n else:\n print(f'\\nTo the {args[1]} you see {lookRoom.name}.\\n')\n return True\n else:\n print('\\nI dont even know where you are trying to go..\\n')\n return True\n\ndef moveCommand(player, *args):\n global current_room\n current_room = user_character.location.getRoomInDirection(args[0])\n global newRoom\n newRoom = user_character.location.getRoomInDirection(args[0])\n if newRoom == None:\n printErrorString('Cant go that direction')\n else:\n user_character.changeLocation(newRoom)\n return False\n \ndef itemCommand(user_character, *args):\n if (args[0] == 'get' or args[0] == 'take'):\n item = user_character.location.findItem(args[1])\n print(item)\n if item == None:\n printErrorString('\\nThat item is not avalible\\n')\n else:\n user_character.addItem(args[1])\n print(f'{args[1]} added to your inventory\\n')\n return True\n elif args[0] == 'drop':\n if len(args) > 1:\n user_character.removeItem(args[1])\n print(f'\\n{args[1]} was deleted from your inventory\\n')\n return True\n else:\n print(f'{args[1]} doesnt exist.') \n\ncommands = {}\ncommands['n'] = moveCommand\ncommands['s'] = moveCommand\ncommands['e'] = moveCommand\ncommands['w'] = moveCommand\ncommands['look'] = lookCommand\ncommands['get'] = itemCommand\ncommands['take'] = itemCommand\ncommands['drop'] = itemCommand\n\ncommandsHelp = {}\ncommandsHelp['n'] = 'move north'\ncommandsHelp['s'] = 'move south'\ncommandsHelp['e'] = 'move east'\ncommandsHelp['w'] = 'move west'\ncommandsHelp['look'] = 'look somewhere'\n\n\n\nwhile True:\n if noPrint:\n noPrint = False\n else:\n print(current_room)\n inp = input(\"What is your input: \")\n inplist = inp.split(' ')\n print(f'Your input has {len(inplist)} arguments')\n for arg in inplist:\n print(arg)\n\n if inplist[0] == 'q':\n print(\"Bye!\")\n break\n \n \n\n elif (inplist[0] == 'inventory' or inplist[0] == 'items'):\n print('\\n--Your Inventory--\\n')\n if len(user_character.inventory) > 0:\n for item in user_character.inventory:\n print(f'item --{item}\\n')\n noPrint = True\n else:\n printErrorString('\\nThere is nothing in your inventory\\n') \n\n elif inplist[0] == 'help':\n for command in commandsHelp:\n print(f'{command} -- {commandsHelp[command]}')\n elif inplist[0] in commands:\n noPrint = commands[inplist[0]](user_character, *inplist)\n else:\n printErrorString(\"\\nI don't understand that\\n\")\n","sub_path":"src/days-2-4-adv/adv.py","file_name":"adv.py","file_ext":"py","file_size_in_byte":4933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"171027416","text":"# -*- coding: utf8 -*-fr\n# pylint: disable=too-many-instance-attributes, invalid-name\n\"\"\"\nItopapiTeam is an abstraction of Team representation on iTop\nIt inherits from ItopapiContact\n\"\"\"\n\nfrom itopapi.model.prototype import ItopapiPrototype\nfrom itopapi.model.contact import ItopapiContact\nfrom itopapi.model.features.hasOrganization import HasOrganization\n\n__version__ = '1.0'\n__authors__ = ['Julien Nauroy ']\n\n\nclass ItopapiTeam(ItopapiContact, HasOrganization):\n \"\"\"\n ItopapiTeam is an object that represents a Team from iTop\n \"\"\"\n\n \"\"\" Configuration specific to itop \"\"\"\n itop = {\n # Name of the class in Itop\n 'name': 'Team',\n # Define which fields to save when creating or updating from the python API\n 'save': ['status', 'phone', 'notify', 'name', 'function', 'email'],\n 'foreign_keys': [\n HasOrganization.foreign_key,\n ],\n 'list_types': {\n 'persons_list': 'Person',\n 'cis_list': 'functionalci_id_finalclass_recall'\n },\n }\n\n @staticmethod\n def find(key):\n \"\"\" Retrieve one or more instance of Team with the given key or criteria \"\"\"\n return ItopapiPrototype.find(ItopapiTeam, key)\n\n @staticmethod\n def find_by_name(name):\n return ItopapiPrototype.find_by_name(ItopapiTeam, name)\n\n @staticmethod\n def find_all():\n \"\"\" Retrieve all instance of Rack \"\"\"\n return ItopapiPrototype.find_all(ItopapiTeam)\n\n def __init__(self, data=None):\n super(ItopapiTeam, self).__init__(data)\n\n ##################################\n # Properties #\n ##################################\n self.status = None\n self.phone = None\n self.notify = None\n self.function = None\n self.email = None\n ##################################\n # Lists #\n ##################################\n self.cis_list = None\n self.tickets_list = None\n self.persons_list = None\n\n# Register as a subclass of Contact\nItopapiContact.register(ItopapiTeam)","sub_path":"itopapi/model/team.py","file_name":"team.py","file_ext":"py","file_size_in_byte":2136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"321607746","text":"#!/usr/bin/python3\n\"\"\"\nmatrix_divided - divids list of lists\n\"\"\"\n\n\ndef matrix_divided(matrix, div):\n \"\"\"\n Args:\n\n matrix (list of lists): first parameter\n div (int, float): second parameter\n\n Raises:\n\n TypeError: matrix must be a matrix (list of lists) of integers/floats\n TypeError: div must be a number\n TypeError: Each row of the matrix must have the same size\n ZeroDivisionError: division by zero\n \"\"\"\n if not isinstance(matrix, list) or not any(isinstance(y, list)\n for y in matrix):\n raise TypeError(\"matrix must be a matrix \"\n \"(list of lists) of integers/floats\")\n if not all(isinstance(x, (float, int))for y in matrix for x in y):\n raise TypeError(\"matrix must be a matrix \"\n \"(list of lists) of integers/floats\")\n if not isinstance(div, (float, int)):\n raise TypeError(\"div must be a number\")\n if not all(len(x) == len(next(iter(matrix))) for x in iter(matrix)):\n raise TypeError(\"Each row of the matrix must have the same size\")\n if div == 0:\n raise ZeroDivisionError(\"division by zero\")\n\n return [[round(x / div, 2) for x in y] for y in matrix]\n","sub_path":"0x07-python-test_driven_development/2-matrix_divided.py","file_name":"2-matrix_divided.py","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"121197133","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import print_function\n\nfrom dronekit import connect, VehicleMode, LocationGlobal, LocationGlobalRelative\nfrom pymavlink import mavutil # Needed for command message definitions\nimport time\nimport math\n\nimport argparse\n\nparser = argparse.ArgumentParser(description = 'Control Copter and send commands in guided mode')\nparser.add_argument('--connect',\n help = 'Vehicle connection target string. If not specified, SITL will automatically start and be used') \nargs = parser.parse_args()\n\nconnection_string = args.connect\nsitl = None\n\n#Start SITL if no connection string specified\nif not connection_string:\n import dronekit_sitl\n sitl = dronekit_sitl.start_default()\n connection_string = sitl.connection_string()\n\n# Connect to the vehicle\nprint('Connecting to vehicle on: %s' % connection_string)\nvehicle = connect(connection_string, wait_ready = True)\n\n\"\"\"\nArms vehicle and takes off to specified altitude\n\"\"\"\ndef arm_and_takeoff(aTargetAltitude):\n print(\"Basic pre-arm checks\")\n # Ensures user does not try to arm until autopilot is ready\n while not vehicle.is_armable:\n print(\"Waiting for vehicle to initialize...\")\n time.sleep(1)\n \n print(\"Arming motors\")\n # Copter should arm in guided mode\n vehicle.mode = VehicleMode(\"GUIDED\")\n vehicle.armed = True\n\n while not vehicle.armed:\n print(\"Waiting for vehicle to arm...\")\n time.sleep(1)\n\n print(\"Vehicle is taking off!\")\n # Take off to specified altitude\n vehicle.simple_takeoff(aTargetAltitude)\n\n \"\"\"\n Wait until vehicle has reached specified altitude before processing next command\n Any command directly after Vehicle.simple_takeoff will execute immediately \n \"\"\"\n while True:\n print(\"Altitude: \", vehicle.location.global_relative_frame.alt)\n if vehicle.location.global_relative_frame.alt >= aTargetAltitude * 0.95:\n print(\"Reached target altitude\")\n break\n time.sleep(1)\n \n# Arm and take off to altitude of 5 meters\narm_and_takeoff(5)\n\n\"\"\"\nReturns a LocationGlobal object containing the latitude/longitude `dNorth` and `dEast` metres from the \nspecified `original_location`. The returned LocationGlobal has the same `alt` value\nas `original_location`.\n\nThe function is useful when you want to move the vehicle around specifying locations relative to \nthe current vehicle position.\n\nThe algorithm is relatively accurate over small distances (10m within 1km) except close to the poles.\n\"\"\"\n\ndef get_location_metres(original_location, dNorth, dEast):\n # 'Spherical' radius of earth\n earth_radius = 6378137.0\n # Coordinate offsets in radians\n dLat = dNorth/earth_radius\n dLon = dEast/(earth_radius * math.cos(math.pi * original_location.lat/180))\n\n # New position in decimal degrees\n newLat = original_location.lat + (dLat * 180/math.pi)\n newLon = original_location.lon + (dLon * 180/math.pi)\n if type(original_location) is LocationGlobal:\n targetlocation = LocationGlobal(newLat, newLon, original_location.alt)\n elif type(original_location) is LocationGlobalRelative:\n targetlocation = LocationGlobalRelative(newLat, newLon, original_location.alt)\n else:\n raise Exception(\"Invalid Location object passed\")\n\n return targetlocation\n\n\"\"\"\nReturns the ground distance in metres between two LocationGlobal objects.\n\nThis method is an approximation, and will not be accurate over large distances and close to the \nearth's poles.\n\"\"\"\ndef get_distance_metres(aLocation1, aLocation2):\n dLat = aLocation2.lat - aLocation1.lat\n dLon = aLocation2.lon - aLocation1.lon\n return math.sqrt((dLat * dLat) + (dLon * dLon)) * 1.113195e5\n\n\"\"\"\nReturns the bearing between the two LocationGlobal objects passed as parameters.\nThis method is an approximation, and may not be accurate over long distances and\nclose earths poles.\n\"\"\"\ndef get_bearing(aLocation1, aLocation2):\n off_x = aLocation2.lon - aLocation1.lon\n off_y = aLocation2.lat - aLocation1.lat\n bearing = 90.00 + math.atan2(-off_y, off_x) * 57.2957795\n if bearing < 0:\n bearing += 360.00\n return bearing\n\n\"\"\"\nSend SET_POSITION_TARGET_GLOBAL_INT command to request the vehicle fly to a specified LocationGlobal.\n\"\"\"\ndef goto_position_target_global_int(aLocation):\n\n msg = vehicle.message_factory.set_position_target_global_int_encode(\n 0, # time_boot_ms (not used)\n 0, 0, # target system, target component\n mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT_INT, # frame\n 0b0000111111111000, # type_mask (only speeds enabled)\n int(aLocation.lat*1e7), # lat_int - X Position in WGS84 frame in 1e7 * meters\n int(aLocation.lon*1e7), # lon_int - Y Position in WGS84 frame in 1e7 * meters\n int(aLocation.alt), # alt - Altitude in meters in AMSL altitude, not WGS84 if absolute or relative, above terrain if GLOBAL_TERRAIN_ALT_INT\n 0, 0, 0, # X,Y,Z velocity in NED frame in m/s\n 0, 0, 0, # afx, afy, afz acceleration (not supported yet, ignored in GCS_Mavlink)\n 0, 0) # yaw, yaw_rate (not supported yet, ignored in GCS_Mavlink) \n # send command to vehicle\n print(msg)\n vehicle.send_mavlink(msg)\n\n\"\"\"\nMoves the vehicle to a postiion dNorth meters North and dEast meters East\nof the current position.\nThe method takes a function pointer argument with a single `dronekit.lib.LocationGlobal` parameter for \nthe target position. This allows it to be called with different position-setting commands.\nThis method reports the distance to target every two seconds\n\"\"\"\ndef goto(dNorth, dEast, gotoFunction = vehicle.simple_goto):\n currentLocation = vehicle.location.global_relative_frame\n targetLocation = get_location_metres(currentLocation, dNorth, dEast)\n targetDistance = get_distance_metres(currentLocation, targetLocation)\n gotoFunction(targetLocation)\n\n #Stop action if we are no longer in guided mode\n while vehicle.mode.name == \"GUIDED\":\n remainingDistance = get_distance_metres(vehicle.location.global_relative_frame, targetLocation)\n print(\"Distance to target: \", remainingDistance)\n if remainingDistance <= targetDistance*0.01:\n print(\"Target reached\")\n break\n time.sleep(2)\n\nprint(\"Fly straight line path to 30 yard line\")\nprint(\"Setting groundspeed to 5 m/s\")\nvehicle.groundspeed = 5\ngoto(27.41,0,goto_position_target_global_int)\n\nprint(\"Setting LAND mode...\")\nvehicle.mode = VehicleMode(\"LAND\")\n\nprint(\"Close vehicle object\")\nvehicle.close()\n\nif sitl is not None:\n sitl.stop()\n\nprint(\"Mission Complete\")\n\n","sub_path":"Showcase1/DistanceTravel.py","file_name":"DistanceTravel.py","file_ext":"py","file_size_in_byte":6650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"623008789","text":"# Author: Christian Brodbeck \nfrom itertools import izip\nimport re\n\nimport numpy as np\n\nfrom . import stats\n\n\n# array functions: work on array, take axis argument\nnp_afuncs = {'min': np.min,\n 'max': np.max,\n 'sum': np.sum}\n# binary functions: work on two arrays\nnp_bfuncs = {'subtract': np.subtract,\n 'add': np.add}\n# unary functions: work on a single array\nnp_ufuncs = {'abs': np.abs,\n 'negative': np.negative}\n\n\nclass TContrastRel(object):\n \"Parse a contrast expression and expose methods to apply it\"\n\n def __init__(self, contrast, cells, indexes):\n \"\"\"Parse a contrast expression and expose methods to apply it\n\n Parameters\n ----------\n contrast : str\n Contrast specification.\n cells : tuple of cells\n Cells that occur in the contrast (each cell is represented by a str\n or a tuple of str).\n indexes : dict {cell: index}\n Indexes for the data of every cell.\n \"\"\"\n parse = _parse_t_contrast(contrast)\n n_buffers, cells_in_contrast = _t_contrast_rel_properties(parse)\n pcells, mcells = _t_contrast_rel_expand_cells(cells_in_contrast, cells)\n\n self.contrast = contrast\n self.indexes = indexes\n self._parsed_contrast = parse\n self._pcells = pcells\n self._mcells = mcells\n self._n_buffers = n_buffers\n\n # data buffers\n self._buffer_shape = None\n self._buffer = None\n self._y_perm = None\n\n def map(self, y):\n \"Apply contrast without retainig data buffers\"\n buff = np.empty((self._n_buffers,) + y.shape[1:])\n data = _t_contrast_rel_data(y, self.indexes, self._pcells, self._mcells)\n tmap = _t_contrast_rel(self._parsed_contrast, data, buff)\n return tmap\n\n def __call__(self, y, out, perm):\n \"Apply contrast to permutation of the data, storing and recycling data buffers\"\n buffer_shape = (self._n_buffers,) + y.shape[1:]\n if self._buffer_shape != buffer_shape:\n self._buffer = np.empty(buffer_shape)\n self._y_perm = np.empty_like(y)\n self._buffer_shape = buffer_shape\n self._y_perm[perm] = y\n data = _t_contrast_rel_data(self._y_perm, self.indexes, self._pcells, self._mcells)\n tmap = _t_contrast_rel(self._parsed_contrast, data, self._buffer, out)\n return tmap\n\n\ndef _parse_cell(cell_name):\n \"Parse a cell name for t_contrast\"\n cell = tuple(s.strip() for s in cell_name.split('|'))\n if len(cell) == 1:\n return cell[0]\n else:\n return cell\n\n\ndef _parse_t_contrast(contrast):\n \"\"\"Parse a string specifying a t-contrast into nested instruction tuples\n\n Parameters\n ----------\n contrast : str\n Contrast specification string.\n\n Returns\n -------\n compiled_contrast : tuple\n Nested tuple composed of:\n Comparisons: ``('comp', c1, c0)`` and\n Unary functions: ``('ufunc', func, arg)``\n Binary functions: ``('bfunc', func, [arg1, arg2])``\n Array functions: ``('afunc', func, [arg1, arg2, ...])``\n where ``arg1`` etc. are in turn comparisons and functions.\n \"\"\"\n depth = 0\n start = 0\n if not '(' in contrast:\n m = re.match(\"\\s*([\\w\\|*]+)\\s*([<>])\\s*([\\w\\|*]+)\", contrast)\n if m:\n c1, direction, c0 = m.groups()\n if direction == '<':\n c1, c0 = c0, c1\n c1 = _parse_cell(c1)\n c0 = _parse_cell(c0)\n return ('comp', c1, c0)\n\n for i, c in enumerate(contrast):\n if c == '(':\n if depth == 0:\n prefix = contrast[start:i]\n i_open = i + 1\n items = []\n depth += 1\n elif c == ',':\n if depth == 0:\n raise\n elif depth == 1:\n item = _parse_t_contrast(contrast[i_open:i])\n items.append(item)\n i_open = i + 1\n elif c == ')':\n depth -= 1\n if depth == 0:\n item = _parse_t_contrast(contrast[i_open:i])\n items.append(item)\n\n if contrast[i+1:].strip():\n raise ValueError(\"Expression continues after last \"\n \"parentheses closed: %s\" % contrast)\n elif prefix == '':\n if len(items) == 1:\n return items[0]\n else:\n raise ValueError(\"Multiple comparisons without \"\n \"combination expression: %s\" % contrast)\n\n m = re.match(\"\\s*(\\w+)\\s*\", prefix)\n if m is None:\n raise ValueError(\"uninterpretable prefix: %r\" % prefix)\n func = m.group(1)\n if func in np_ufuncs:\n if len(items) != 1:\n raise ValueError(\"Wrong number of input values for \"\n \"unary function: %s\" % contrast)\n return 'ufunc', np_ufuncs[func], items[0]\n elif func in np_bfuncs:\n if len(items) != 2:\n raise ValueError(\"Wrong number of input values for \"\n \"binary function: %s\" % contrast)\n return 'bfunc', np_bfuncs[func], items\n elif func in np_afuncs:\n if len(items) < 2:\n raise ValueError(\"Wrong number of input values for \"\n \"array comparison function: %s\"\n % contrast)\n return 'afunc', np_afuncs[func], items\n else:\n raise ValueError(\"Unknown function: %s\" % contrast)\n elif depth == -1:\n err = \"Invalid ')' at position %i of %r\" % (i, contrast)\n raise ValueError(err)\n\n\ndef _t_contrast_rel_properties(item):\n \"\"\"Find properties of a compiled t-contrast\n\n Parameters\n ----------\n item : tuple\n Contrast specification.\n\n Returns\n -------\n n_buffers : int\n Number of buffer maps needed.\n cells : set\n names of all cells that occur in the contrast.\n \"\"\"\n if item[0] == 'ufunc':\n needed_buffers, cells = _t_contrast_rel_properties(item[2])\n return needed_buffers + 1, cells\n elif item[0] in ('bfunc', 'afunc'):\n _, _, items_ = item\n local_buffers = len(items_)\n cells = set()\n for i, item_ in enumerate(items_):\n available_buffers = local_buffers - i - 1\n needed_buffers, cells_ = _t_contrast_rel_properties(item_)\n additional_buffers = needed_buffers - available_buffers\n if additional_buffers > 0:\n local_buffers += additional_buffers\n cells.update(cells_)\n return local_buffers, cells\n else:\n return 0, set(item[1:])\n\n\ndef _t_contrast_rel_expand_cells(cells, all_cells):\n \"\"\"Find cells that are an average of other cells\n\n Parameters\n ----------\n cells : set\n Cells occurring in the contrast.\n all_cells : tuple\n All cells in the data.\n\n Returns\n -------\n primary_cells : set\n All cells that occur directly in the data.\n mean_cells : dict\n ``{name: components}`` dictionary (components being a tuple with all\n cells to be averaged).\n \"\"\"\n # check all cells have same number of components\n ns = set(1 if isinstance(cell, str) else len(cell) for cell in all_cells)\n ns.update(1 if isinstance(cell, str) else len(cell) for cell in cells)\n if len(ns) > 1:\n msg = (\"Not all cells have the same number of components: %s\" %\n str(tuple(cells) + tuple(all_cells)))\n raise ValueError(msg)\n\n primary_cells = set()\n mean_cells = {}\n for cell in cells:\n if cell in all_cells:\n primary_cells.add(cell)\n elif isinstance(cell, str):\n if cell != '*':\n raise ValueError(\"%s not in all_cells\" % repr(cell))\n mean_cells[cell] = all_cells\n primary_cells.update(all_cells)\n elif not '*' in cell:\n msg = \"Contrast contains cell not in data: %s\" % repr(cell)\n raise ValueError(msg)\n else:\n # find cells that should be averaged (\"base\")\n base = tuple(cell_ for cell_ in all_cells if\n all(i in (i_, '*') for i, i_ in izip(cell, cell_)))\n if len(base) == 0:\n raise ValueError(\"No cells in data match %s\" % repr(cell))\n mean_cells[cell] = base\n primary_cells.update(base)\n\n return primary_cells, mean_cells\n\n\ndef _t_contrast_rel_data(y, indexes, cells, mean_cells):\n \"Create {cell: data} dictionary\"\n data = {}\n for cell in cells:\n index = indexes[cell]\n data[cell] = y[index]\n\n for name, cells_ in mean_cells.iteritems():\n cell = cells_[0]\n x = data[cell].copy()\n for cell in cells_[1:]:\n x += data[cell]\n x /= len(cells_)\n data[name] = x\n\n return data\n\n\ndef _t_contrast_rel(item, data, buff, out=None):\n \"Execute a t_contrast (recursive)\"\n if item[0] == 'ufunc':\n _, func, item_ = item\n tmap = _t_contrast_rel(item_, data, buff[1:], buff[0])\n tmap = func(tmap, tmap)\n elif item[0] == 'bfunc':\n _, func, items = item\n tmap1 = _t_contrast_rel(items[0], data, buff[2:], buff[1])\n tmap2 = _t_contrast_rel(items[1], data, buff[2:], buff[0])\n tmap = func(tmap1, tmap2, tmap2)\n elif item[0] == 'afunc':\n _, func, items_ = item\n tmaps = buff[:len(items_)]\n for i, item_ in enumerate(items_):\n _t_contrast_rel(item_, data, buff[i + 1:], tmaps[i])\n tmap = func(tmaps, axis=0, out=out)\n else:\n _, c1, c0 = item\n tmap = stats.t_1samp(data[c1] - data[c0], out)\n\n return tmap\n","sub_path":"eelbrain/_stats/t_contrast.py","file_name":"t_contrast.py","file_ext":"py","file_size_in_byte":10099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"243181223","text":"from random import randint\nimport math\nimport os\nimport matplotlib.pyplot as plt\n\ndef clear(i):\n print(' \\n' * i)\n\nprint(\"Press Enter to play\")\n\nbalance = 100 ##give player 100 coins\nbet = 0\ncombo = 0\ncnt = 0\n\nst_balance = []\nst_bet = []\nst_reward = []\nst_combo = []\n\nwhile True:\n while True:\n cnt = cnt+1 \n bet = int(input('Place your bet. Remaining coins: ' + str(balance)) or 0)\n \n \n if balance - int(bet) < 0:\n bet=int(input('Insufficient coins. Your balance: ' + str(balance)) or 0) \n else: \n balance = balance - bet\n break\n \n if bet == 0:\n continue\n \n a = randint(1,3)\n b = randint(1,3)\n c = randint(1,3)\n\n## a = 1 \n## b = 1\n## c = 1\n##for debugging\n clear(100)\n print(a, b, c, sep=\",\")\n\n if a == b and a==c:\n combo = combo + 1\n reward = int(bet *10 + (pow((combo - 1),2) * bet))\n balance = balance + reward\n print(\"Congrats... JackPot!!!\")\n if combo > 1:\n print('Combo count: '+str(combo))\n print(\"Now you have \"+str(balance)+\" coins\") \n else:\n print(\"Now you have \"+str(balance)+\" coins\")\n combo = 0\n reward = 0\n \n ##stats[cnt] = [balance, bet, reward, combo]\n\n st_balance.append(balance)\n st_bet.append(bet)\n st_reward.append(reward)\n st_combo.append(combo)\n \n if balance == 0:\n print('Sorry, but you have just lost this game :(')\n x_axis = list(range(0, len(st_balance), 1))\n plt.xlabel('Time')\n plt.ylabel('Your Balance')\n plt.grid(True)\n plt.plot(x_axis, st_balance, 'r')\n plt.axis([0, len(x_axis), 0, max(st_balance)*1.5 ])\n \n plt.show()\n break\n ##print('combo: '+ str(combo)) # for debugging\n","sub_path":"jackpot.py","file_name":"jackpot.py","file_ext":"py","file_size_in_byte":1863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"70698122","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom openpyxl import load_workbook\n\n# 타겟 URL을 읽어서 HTML를 받아오고,\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}\ndata = requests.get('https://movie.naver.com/movie/sdb/rank/rmovie.nhn?sel=pnt&date=20190909', headers=headers)\n\nsoup = BeautifulSoup\n# HTML을 BeautifulSoup이라는 라이브러리를 활용해 검색하기 용이한 상태로 만듦\n# soup이라는 변수에 \"파싱 용이해진 html\"이 담긴 상태가 됨\n# 이제 코딩을 통해 필요한 부분을 추출하면 된다.\n\n# HTML을 BeautifulSoup이라는 라이브러리를 활용해 검색하기 용이한 상태로 만듦\nsoup = BeautifulSoup(data.text, 'html.parser')\n\n# select를 이용해서, tr들을 불러오기\nmovies = soup.select('#old_content > table > tbody > tr')\n\nmovie_table = load_workbook('prac01.xlsx')\nmovie_sheet = movie_table['prac']\n\n# movies (tr들) 의 반복문을 돌리기\nrow = 2\nnum = 1\nfor movie in movies:\n # movie 안에 a 가 있으면,\n a_tag = movie.select_one('td.title > div > a')\n if a_tag is not None:\n # a의 text를 찍어본다.\n movie_title = a_tag.text\n point = movie.select('td.point')[0].text\n\n movie_sheet.cell(row=row, column=1, value=num)\n movie_sheet.cell(row=row, column=2, value=movie_title)\n movie_sheet.cell(row=row, column=3, value=point)\n row += 1\n num += 1\n\n movie_table.save('movie.xlsx')\n","sub_path":"movieScrapToExel.py","file_name":"movieScrapToExel.py","file_ext":"py","file_size_in_byte":1552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"321532467","text":"import os\nimport sys\nimport re\nimport json\nimport urllib.request\n\n\ndef getTrend():\n client_id = \"st9xvPkKYLgT7c3bdZVa\"\n client_secret = \"4NTYUN_MVb\"\n encText = urllib.parse.quote(\"자취생 간단 요리 레시피\")\n url = \"https://openapi.naver.com/v1/search/blog?query=\" + encText # json 결과\n request = urllib.request.Request(url)\n request.add_header(\"X-Naver-Client-Id\", client_id)\n request.add_header(\"X-Naver-Client-Secret\", client_secret)\n response = urllib.request.urlopen(request)\n rescode = response.getcode()\n if(rescode == 200):\n response_body = response.read().decode('utf-8')\n dict = json.loads(response_body)\n dict = dict['items']\n \n trend=[]\n for i in dict:\n tmp={}\n title_tmp = re.sub('(<([^>]+)>)', '', i['title'])\n title_tmp = re.sub('["lg;]', '', title_tmp)\n tmp['title']=title_tmp\n tmp['link']=i['link']\n trend.append(tmp)\n return trend\n else:\n return rescode\n","sub_path":"exec/analysis/service/TrendingService.py","file_name":"TrendingService.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"472559879","text":"#!/usr/bin/env python3\n\nimport pygame\nimport sys\nfrom pygame.sprite import Sprite\nfrom pygame.sprite import Group\n\nclass Ship(Sprite) : \n def __init__(self, screen) : \n super().__init__()\n self.image = pygame.image.load('img/ship.bmp')\n self.rect = self.image.get_rect()\n self.screen = screen\n self.screen_rect = self.screen.get_rect()\n self.reset()\n self.moving_up = False\n self.moving_down = False\n def reset(self) : \n ''' reposition the ship to the center left of the screen '''\n self.rect.centery = self.screen_rect.centery\n def blitme(self) : \n ''' draw the ship on the screen object '''\n self.screen.blit(self.image, self.rect)\n def move(self, speed_factor = 1) : \n if self.moving_up and self.rect.y > 0: \n self.rect.y -= 10 * speed_factor\n if self.moving_down and self.rect.bottom < self.screen_rect.height: \n self.rect.y += 10 * speed_factor\n\nclass Target(Sprite) : \n def __init__(self, screen) : \n super().__init__()\n self.rect = pygame.Rect(0,0,100,100)\n self.screen = screen\n self.screen_rect = self.screen.get_rect()\n self.moving_direction = 1\n self.reset()\n def move(self, speed_factor) : \n self.check_edge()\n self.rect.y += self.moving_direction * speed_factor\n print(speed_factor)\n def draw(self) : \n self.screen.fill((0,0,0), self.rect)\n def reset(self) : \n self.rect.centery = self.screen_rect.centery\n self.rect.right = self.screen_rect.right\n def check_edge(self) : \n if self.rect.bottom > self.screen_rect.bottom or self.rect.top < 0 : \n self.moving_direction *= -1\n\nclass Bullet(Sprite) : \n def __init__(self, ship, target, screen) : \n super().__init__()\n self.rect = pygame.Rect(0,0,10,10)\n self.ship = ship\n self.target = target\n self.screen = screen\n self.screen_rect = self.screen.get_rect()\n self.reset_tries()\n\n # define an flag to check whether the bullet is out of screen\n self.out_of_screen = False\n # define an internal flag to see whether user has fired the bullet\n self.is_fire = False\n\n def fire(self) : \n self.reset()\n self.is_fire = True\n\n def reset(self) : \n self.rect.centery = self.ship.rect.centery\n self.rect.right = self.ship.rect.right\n\n def hit(self) : \n self.is_fire = False\n # a bug fix, after a hit, remove the collison status by resetting the bullets under the ship\n self.reset()\n \n def reset_tries(self) : \n self.tries_left = 3\n\n def move(self, speed_factor) : \n if self.is_fire : \n self.rect.x += 1 * speed_factor\n self.check_edge()\n\n def check_edge(self) : \n if self.rect.left >= self.screen_rect.right : \n self.out_of_screen = True\n self.tries_left -= 1\n self.is_fire = False\n\n def draw(self) : \n if self.is_fire : \n self.screen.fill((0,0,0), self.rect)\nclass Button() : \n def __init__(self, width, height, font_size, screen) : \n self.rect = pygame.Rect(0,0,width, height)\n self.font = pygame.font.SysFont(None, font_size)\n self.screen = screen\n\n def draw(self, msg, font_color, bg_color) : \n self.img = self.font.render(msg, True, font_color, bg_color)\n self.screen.blit(self.img, self.rect)\n\n# initialize pygame\npygame.init()\n\n# get the screen\nsc = pygame.display.set_mode((500,300))\n\n# initalize the object\nship = Ship(sc)\ntarget = Target(sc)\nbullet = Bullet(ship, target, sc)\n\n# flag to see whether game is active\ngame_active = False\n\n# construct buttons\n# number of tries button\ntries_button = Button(50, 50, 40, sc )\n# position the button\ntries_button.rect.y = 0\ntries_button.rect.centerx = sc.get_rect().centerx\n# start button\nstart_button = Button(100, 50, 40, sc )\nstart_button.rect.centerx = sc.get_rect().centerx\nstart_button.rect.centery = sc.get_rect().centery\n\n# initalize speed factor\nspeed_factor = 1\nspeed_up_factor = 1.1\n\nwhile True : \n events = pygame.event.get()\n for event in events : \n if event.type == pygame.QUIT : \n sys.exit()\n elif event.type == pygame.KEYDOWN : \n if event.key == pygame.K_q : \n sys.exit()\n elif event.key == pygame.K_UP : \n ship.moving_up = True\n elif event.key == pygame.K_DOWN : \n ship.moving_down = True\n elif event.key == pygame.K_SPACE : \n # introduce the bullet to the screen\n if not bullet.is_fire and bullet.tries_left > 0 : \n bullet.fire()\n elif event.type == pygame.KEYUP : \n if event.key == pygame.K_UP : \n ship.moving_up = False\n elif event.key == pygame.K_DOWN : \n ship.moving_down = False\n elif event.type == pygame.MOUSEBUTTONDOWN: \n # pygame has a 'mouse' class containing the clicked mouse positions\n mouse_x, mouse_y = pygame.mouse.get_pos()\n if start_button.rect.collidepoint(mouse_x, mouse_y) : \n bullet.reset_tries()\n game_active = True\n\n # check if player lost\n if bullet.tries_left <= 0 : \n game_active = False\n speed_factor = 1\n # repaint the screen\n sc.fill((230,230,230))\n # draw the button\n tries_button.draw(str(bullet.tries_left), (0,0,0), (230,230,230))\n # draw the start button\n if not game_active : \n start_button.draw('START', (255,255,255), (0,255,0))\n \n if game_active : \n # draw the ship based on internal flags\n ship.move(speed_factor)\n ship.blitme()\n # draw the target\n target.move(speed_factor)\n target.draw()\n # draw the bullet\n bullet.move(speed_factor)\n bullet.draw()\n # check collision \n if pygame.sprite.collide_rect(bullet, target) : \n bullet.hit()\n # increase the speed\n speed_factor *= speed_up_factor\n # refresh the screen\n pygame.display.flip()\n","sub_path":"practice/14.03_three_bullets_various_speed/three_bullets.py","file_name":"three_bullets.py","file_ext":"py","file_size_in_byte":6189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"589638511","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# Date: 2018/6/21\n\nimport socket\nfrom threading import Thread\n\n\nclass Ftp:\n ip = '127.0.0.1'\n port = 8111\n\n def __init__(self):\n self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n self.socket.bind((self.ip, self.port))\n self.socket.listen(5)\n self.add = None\n\n def run(self):\n while True:\n try:\n conn, self.add = self.socket.accept()\n print(conn, self.add)\n t = Thread(target=self.task, args=(conn,), name='ftp')\n t.start()\n except ConnectionResetError:\n break\n self.socket.colse()\n\n def task(self, conn):\n while True:\n try:\n data = conn.recv(8019)\n if not data:\n break\n print(data.decode('utf-8'))\n conn.send(data.upper())\n except ConnectionResetError:\n print(\"连接断开\")\n break\n conn.close()\n\n\nif __name__ == '__main__':\n f = Ftp()\n f.run()\n","sub_path":"20180621/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"153239998","text":"#!/usr/bin/env python3\n\nimport sys\nimport os\nimport argparse\nimport subprocess\nimport readline\nimport pandas as pd\nimport numpy as np\nfrom plio.io.io_bae import read_gpf, save_gpf\n\n\n## Create an argument parser\ndef parse_args():\n parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,\n description = \"\"\"Transform points in a Socet Set Ground Point File (GPF).\nThe transformed latitude, longitude, and height values from the Tie Points are then written to a new GPF with their sigmas set equal to 1 and the \"known\" flag \nchanged from \"1\" (Tie Point) to \"3\" (XYZ Control). Non-Tie Points from the original GPF are written to the new GPF with their \"known\" flags changed to \"1.\" \nTie Points from the original GPF that were not active (\"stat\" = 0) are copied \"as-is\" into the new GPF. The output GPF preserves the order of the ground points from the original GPF.\n\nIf it is desired to update all active points in the input GPF, use the '--all-points' flag. The modified points will still have their \"known\" flag set to \"3\" (XYZ Control) in the output GPF.\n\nThe script requires the \"plio\" Python library (https://github.com/USGS-Astrogeology/plio) in order to read/write GPFs. \nThe Ames Stereo Pipeline program pc_align must be available in the user's path or somewhere else where Python can find it. \nMore information about the Ames Stereo Pipeline is available on the project's Git repository: https://github.com/NeoGeographyToolkit/StereoPipeline\"\"\")\n parser.add_argument(\"socet_gpf\",\n help = \"The name of the Socet Ground Point File to transform.\")\n parser.add_argument(\"transform_matrix\",\n help = \"\"\"Name of a pc_align-compatible transformation matrix to apply to the input GPF.\"\"\")\n parser.add_argument(\"tfm_socet_gpf\",\n help = \"\"\"Name to use for the output (transformed) ground point file. Must include \".gpf\" extension.\"\"\")\n parser.add_argument(\"--all-points\",\n action='store_true',\n help = \"This flag will force updating of all active (stat = 1) points in the input GPF, not just tie points.\")\n refshape = parser.add_mutually_exclusive_group(required=True)\n refshape.add_argument(\"--datum\",\n nargs=1,\n choices=['D_MARS', 'D_MOON', 'MOLA', 'NAD27', 'NAD83', 'WGS72', 'WGS_1984'],\n help = \"\"\"Use this datum for heights in the input GPF.\"\"\")\n refshape.add_argument(\"--radii\",\n nargs=2,\n metavar=('semi-major-axis','semi-minor-axis'),\n type=float,\n help=\"\"\"Semi-major and semi-minor axes, expressed in meters, that define the ellipsoid that heights in the input GPF are referenced to.\"\"\")\n args = parser.parse_args()\n return args\n\n\ndef run_pc_align(args):\n \"\"\"\n Use subprocess to call the external program, pc_align. Relies on\n pc_align to decide if arguments are valid or not.\n Pipe STDERR to STDOUT.\n\n\n Parameters\n ----------\n args : list\n list of arguments to be passed to pc_align\n\n \"\"\"\n \n align_args = [\"pc_align\"]\n align_args.extend(args)\n run_align = subprocess.run(align_args,check=True,stderr=subprocess.STDOUT,encoding='utf-8')\n\n return run_align\n\ndef update_gpf(gpf_df,tp_df,all_points,outname):\n \"\"\"\n Update a GPF DataFrame with new lat/long/height values from another DataFrame,\n Change point types based on user input, and set sigmas of updated points == 1 meter.\n\n\n Parameters\n ----------\n gpf_df : pd.DataFrame\n Pandas DataFrame of a Socet GPF file. Format obtained from read_gpf(),\n and subsequently indexed on point_id field.\n\n tp_df : pd.DataFrame\n Pandas DataFrame of a Socet GPF file. Format obtained from read_gpf(),\n and subsequently indexed on point_id field. Should be (at least) a \n subset of gpf_df\n\n all_points : boolean\n If True, update all active points in gpf_df, regardless of point type.\n If False, update only active tiepoints in gpf_df, and then change \n active non-tiepoints to tiepoints.\n\n outname: str\n Path to the output GPF\n\n Returns\n -------\n int : success value\n 0 = success, 1 = errors\n \n\n \"\"\"\n\n print(\"Updating GPF data frame with Transformed lat/long/z values from pc_align\")\n gpf_df.update(tp_df)\n\n print(\"Updating ground point types in output GPF\")\n\n ## Build boolean masks of gpf_df to enable selective updating of point types\n ## transformed tie point mask\n if all_points is True:\n tfm_tp_mask = (gpf_df['stat'] == 1)\n else:\n ## non-tie point mask\n non_tp_mask = ((gpf_df['stat'] == 1) & (gpf_df['known'] > 0))\n tfm_tp_mask = ((gpf_df['stat'] == 1) & (gpf_df['known'] == 0))\n ## Change non-Tie Points to Tie Point\n print(\"Changing active non-Tiepoints to Tiepoints\")\n gpf_df.loc[non_tp_mask, 'known'] = 0\n\n ## Change transformed Tie Points to XYZ Control, sigmas = 1.0, residuals = 0.0\n print(\"Changing transformed points to XYZ Control with sigmas = 1 and residuals = 0\")\n gpf_df.loc[tfm_tp_mask, 'known'] = 3\n gpf_df.loc[tfm_tp_mask, 'sig0':'sig2'] = 1.0\n gpf_df.loc[tfm_tp_mask, 'res0':'res2'] = 0.0\n\n ## Convert the 'stat' and 'known' columns to unsigned integers\n gpf_df.known = pd.to_numeric(gpf_df['known'], downcast = 'unsigned')\n gpf_df.stat = pd.to_numeric(gpf_df['stat'], downcast = 'unsigned')\n\n print(\"Writing transformed GPF to file: \" + outname)\n save_gpf(gpf_df, outname)\n\n return\n\n\ndef main(socet_gpf,tfm_socet_gpf,all_points,transform_matrix,datum,radii):\n \n if tfm_socet_gpf[-4:] != \".gpf\":\n print(\"\"\"USER ERROR: Output file name must include \".gpf\" extension\"\"\")\n sys.exit(1)\n\n ## Read in the Socet ground point file using plio's read_gpf()\n gpf_df = read_gpf(socet_gpf)\n # Set the index of the GPF dataframe to be the point_id column\n gpf_df.set_index('point_id', drop=False, inplace=True)\n\n ## If user passed \"--all-points\" option, copy *all active* points to new data frame\n ## Otherwise, copy active tie points (known == 0) only\n ## Note that DataFrame is named \"tp_df\" regardless of whether it includes only tiepoints or not\n if all_points:\n tp_df = gpf_df[(gpf_df.stat == 1)].copy()\n else:\n tp_df = gpf_df[(gpf_df.known == 0) & (gpf_df.stat == 1)].copy()\n\n tp_df.lat_Y_North = np.degrees(tp_df.lat_Y_North)\n tp_df.long_X_East = ((360 + np.degrees(tp_df.long_X_East)) % 360)\n \n ## Write out CSV (compatible with pc_align) containing lat/long/height of points to be updated\n socet_gpf_csv = ((os.path.splitext(socet_gpf)[0]) + '.csv')\n tp_df.to_csv(path_or_buf=socet_gpf_csv,\n header=False,\n index=False,\n columns=['lat_Y_North','long_X_East','ht'])\n\n gpf_align_prefix = os.path.splitext(tfm_socet_gpf)[0]\n\n ## Build arguments list and apply transformation to selected points from GPF using pc_align\n \n ## Set num-iterations = 0 and turn off max-displacement (-1) because only going to apply existing transform\n apply_tfm_args = [\"--initial-transform\",transform_matrix,\n \"--num-iterations\",\"0\",\n \"--max-displacement\",\"-1\",\n \"--save-transformed-source-points\",\n \"-o\", gpf_align_prefix ]\n ## Extend the list of arguments for pc_align to include the datum or radii as necessary\n if datum is not None:\n apply_tfm_args.extend([\"--datum\", str(datum[0])])\n elif radii is not None:\n apply_tfm_args.extend([\"--semi-major-axis\", str(radii[0]), \"--semi-minor-axis\", str(radii[1])])\n\n ## Extend the list to place point clouds at the end of the list of arguments for pc_align\n ## Note that we're specifying the same file as the reference and source clouds because pc_align requires 2 files as input,\n ## even if we're only applying a transform and not iterating\n apply_tfm_args.extend([socet_gpf_csv,socet_gpf_csv])\n\n print(apply_tfm_args)\n\n\n ## Apply transform from previous pc_align run to tie points CSV\n try:\n print(\"Calling pc_align with 0 iterations to apply transform from previous run to Tie Points from GPF\")\n run_align = run_pc_align(apply_tfm_args)\n # print(run_align.stdout)\n except subprocess.CalledProcessError as e:\n print(e)\n sys.exit(1)\n\n\n ## mergeTransformedGPFTies\n ### Ingest the transformed tie points to a pandas data frame\n t = np.genfromtxt((gpf_align_prefix + '-trans_source.csv'),delimiter=',',\n skip_header=3,dtype='unicode')\n id_list = tp_df['point_id'].tolist()\n tfm_index = pd.Index(id_list)\n tfm_tp_df = pd.DataFrame(t, index=tfm_index, columns=['lat_Y_North','long_X_East','ht'])\n tfm_tp_df = tfm_tp_df.apply(pd.to_numeric)\n\n\n ## Update the original tiepoint DataFrame with the transformed lat/long/height values from pc_align\n tp_df.update(tfm_tp_df)\n\n # ### Convert long from 0-360 to +/-180 and convert lat/long back to radians\n tp_df.lat_Y_North = np.radians(tp_df['lat_Y_North'])\n tp_df.long_X_East = np.radians(((tp_df['long_X_East'] + 180) % 360) - 180)\n\n # Apply updates to the original GPF DataFrame, and save transformed GPF file\n update_gpf(gpf_df,tp_df,all_points,tfm_socet_gpf)\n\n ## Write list of pointIDs of the transformed tiepoints to a file\n ## Included for legacy compatibility, not actually used for anything\n tp_df.to_csv(path_or_buf=((os.path.splitext(socet_gpf)[0]) + '.tiePointIds.txt'),\n sep=' ', header=False,\n index=False,\n columns=['point_id'])\n\n\nif __name__ == \"__main__\":\n args = parse_args()\n sys.exit(main(**vars(args)))\n","sub_path":"SurfaceFit/gpf_transform.py","file_name":"gpf_transform.py","file_ext":"py","file_size_in_byte":10005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"297658772","text":"#!/usr/bin/env python\n\n#----------------------------------#\n# ,--. ,--. ,--. #\n# | .' / ,---. ,-' '-. ,--,--. #\n# | . ' | .-. |'-. .-'' ,-. | #\n# | |\\ \\' '-' ' | | \\ '-' | #\n# `--' '--' `---' `--' `--`--' #\n# kotajacob.tk #\n# Copyright (C) 2017 Dakota Walsh #\n#----------------------------------#\n\n\"\"\"\nWal Steam\n\nUsage:\n wal_steam.py (-w | -g)\n wal_steam.py (-h | --help)\n wal_steam.py (-v | --version)\n\nOptions:\n -w use wal for colors\n -g use wpg for colors\n -h --help show this help message and exit\n -v --version show version and exit\n\"\"\"\nfrom lib.docopt import docopt # argument parsing\nfrom shutil import move # moveing files\nfrom shutil import copy # copying files\nimport os # getting paths\nimport urllib.request # downloading the zip files\nimport zipfile # extracting the zip files\nfrom distutils.dir_util import copy_tree # copytree from shutil is FUCKING GARBAGE for no reason so we use this instead\n\n# set some variables for the file locations\nROOT_DIR = os.path.expanduser(\"~/.cache/wal_steam/\")\n\nmetroUrl = \"http://metroforsteam.com/downloads/4.2.4.zip\"\nmetroPatchUrl = \"http://github.com/redsigma/UPMetroSkin/archive/master.zip\"\n\nmetroZip = os.path.join(ROOT_DIR, \"metroZip.zip\")\nmetroPatchZip = os.path.join(ROOT_DIR, \"metroPatchZip.zip\")\nmetroResource = os.path.join(ROOT_DIR, \"metroZip/\")\nmetroPatchResource = os.path.join(ROOT_DIR, \"metroPatchZip/\")\nmetroPatchCopy = os.path.join(ROOT_DIR, \"metroPatchZip/UPMetroSkin-master/Unofficial 4.2.4 Patch/Main Files [Install First]/\")\nmetroCopy = os.path.join(ROOT_DIR, \"metroZip/Metro 4.2.4/\")\n\nmetroInstallOther = os.path.expanduser(\"~/.steam/steam/skins/Metro 4.2.4 Wal_Mod/\")\nmetroInstallUbuntu = os.path.expanduser(\"~/.steam/skins/Metro 4.2.4 Wal_Mod/\")\nsteamSkins = os.path.expanduser(\"~/.steam/steam/skins/\")\nsteamSkinsUbuntu = os.path.expanduser(\"~/.steam/skins/\")\n\nnewColors = os.path.join(ROOT_DIR, \"colors.styles\")\nwpgConfig = os.path.expanduser(\"~/.wallpapers/current.css\")\nwalConfig = os.path.expanduser(\"~/.cache/wal/colors.css\")\n\n# Set metro install\nif os.path.isdir(steamSkins):\n # use \"other\" path\n metroInstall = metroInstallOther\nelif os.path.isdir(steamSkinsUbuntu):\n # use \"ubuntu\" path\n metroInstall = metroInstallUbuntu\nelse:\n # no steam found\n sys.exit(\"Error: Steam not found!\")\n\n\ndef tupToPrint(tup):\n tmp = ' '.join(map(str, tup)) # convert the tupple (rgb color) to a string ready to print\n return tmp\n\ndef checkDir(dirName):\n # check if wal_steam has been run before\n if os.path.isdir(dirName):\n return True\n else:\n return False\n\ndef makeStyle(colors):\n # create and write the colors.styles file\n print(\"Patching new colors\")\n\n try:\n os.remove(newColors) # just in case it was already there for some reason\n except FileNotFoundError:\n print(\"No file to remove\")\n f_name = open(newColors, 'w')\n\n # First write the variables we aren't changing\n f_name.write('\\\"settings.styles\\\"\\n')\n f_name.write('{\\n')\n f_name.write('\\tcolors\\n')\n f_name.write('\\t{\\n')\n f_name.write('\\t\\tnone=\\\"0 0 0 0\\\"\\n')\n f_name.write('\\t\\tFocus_T=\\\"0 114 198 30.6\\\"\\n')\n f_name.write('\\t\\twhite03=\\\"255 255 255 7.65\\\"\\n')\n f_name.write('\\t\\twhite08=\\\"255 255 255 20.4\\\"\\n')\n f_name.write('\\t\\twhite05=\\\"255 255 255 12.75\\\"\\n')\n f_name.write('\\t\\twhite10=\\\"255 255 255 25.5\\\"\\n')\n f_name.write('\\t\\twhite12=\\\"255 255 255 30.6\\\"\\n')\n # f.write('\\t\\twhite15=\\\"255 255 255 \\\"\\n') this was commented in the file...\n f_name.write('\\t\\twhite20=\\\"255 255 255 51\\\"\\n')\n f_name.write('\\t\\twhite24=\\\"255 255 255 61.2\\\"\\n')\n f_name.write('\\t\\twhite25=\\\"255 255 255 63.75\\\"\\n')\n f_name.write('\\t\\twhite35=\\\"255 255 255 89.25\\\"\\n')\n f_name.write('\\t\\twhite45=\\\"255 255 255 114.75\\\"\\n')\n f_name.write('\\t\\twhite50=\\\"255 255 255 127.5\\\"\\n')\n f_name.write('\\t\\twhite75=\\\"255 255 255 191.25\\\"\\n')\n f_name.write('\\t\\twhite=\\\"255 255 255 255\\\"\\n')\n f_name.write('\\t\\tblack03=\\\"0 0 0 7.65\\\"\\n')\n f_name.write('\\t\\tblack08=\\\"0 0 0 20.4\\\"\\n')\n f_name.write('\\t\\tblack05=\\\"0 0 0 12.75\\\"\\n')\n f_name.write('\\t\\tblack10=\\\"0 0 0 25.5\\\"\\n')\n f_name.write('\\t\\tblack12=\\\"0 0 0 30.6\\\"\\n')\n # f.write('\\t\\tblack15=\\\"0 0 0 38.25\\\"\\n') this was commented in the file too...\n f_name.write('\\t\\tblack20=\\\"0 0 0 51\\\"\\n')\n f_name.write('\\t\\tblack24=\\\"0 0 0 61.2\\\"\\n')\n f_name.write('\\t\\tblack35=\\\"0 0 0 106\\\"\\n')\n f_name.write('\\t\\tblack25=\\\"0 0 0 63.75\\\"\\n')\n f_name.write('\\t\\tblack75=\\\"0 0 0 191.25\\\"\\n')\n f_name.write('\\t\\tBlack=\\\"0 0 0 255\\\"\\n')\n f_name.write('\\t\\tScroll_blu=\\\"88 168 242 165\\\"\\n')\n f_name.write('\\t\\tScroll_blu_s=\\\"103 193 245 175\\\"\\n')\n f_name.write('\\t\\tDetailsBackground=\\\"Black45\\\"\\n')\n f_name.write('\\t\\tDetailPanels=\\\"black45\\\"\\n')\n f_name.write('\\t\\tOverlaySidePanels=\\\"255 255 255 144.75\\\"\\n')\n f_name.write('\\t\\tOverlayHover05=\\\"255 255 255 12.75\\\"\\n')\n f_name.write('\\t\\ttransparent_notification=\\\"5 5 5 229.5\\\"\\n')\n f_name.write('\\t\\tchatframe=\\\"White50\\\"\\n')\n f_name.write('\\t\\tScrollBar=\\\"86 86 86 255\\\"\\n')\n f_name.write('\\t\\tScrollBarH=\\\"110 110 110 255\\\"\\n')\n f_name.write('\\t\\tGrey1=\\\"40 40 40 255\\\"\\n')\n f_name.write('\\t\\tGrey2=\\\"48 48 48 255\\\"\\n')\n f_name.write('\\t\\tGrey3=\\\"75 75 75 255\\\"\\n')\n f_name.write('\\t\\tClientBGTransparent=\\\"43 43 43 191.25\\\"\\n')\n f_name.write('\\t\\tRed=\\\"255 0 0 255\\\"\\n')\n f_name.write('\\t\\tW10close_Red_h=\\\"232 18 35 255\\\"\\n')\n f_name.write('\\t\\tW10close_Red_p=\\\"241 112 121 255\\\"\\n')\n\n # Now for some variables we are changing\n f_name.write('\\t\\tblack45=\\\"' + tupToPrint(colors[0]) + ' 120' + '\\\"\\n')\n f_name.write('\\t\\tFocus=\\\"' + tupToPrint(colors[4]) + ' 255' + '\\\"\\n')\n f_name.write('\\t\\tFriends_InGame=\\\"' + tupToPrint(colors[1]) + ' 255' + '\\\"\\n')\n f_name.write('\\t\\tFriends_Online=\\\"' + tupToPrint(colors[2]) + ' 255' + '\\\"\\n')\n f_name.write('\\t\\tFrameBorder=\\\"' + tupToPrint(colors[0]) + ' 255' + '\\\"\\n')\n f_name.write('\\t\\tGameList=\\\"' + tupToPrint(colors[0]) + ' 255' + '\\\"\\n')\n f_name.write('\\t\\tDividers=\\\"' + tupToPrint(colors[15]) + ' 255' + '\\\"\\n')\n f_name.write('\\t\\tSeperator=\\\"' + tupToPrint(colors[15]) + ' 255' + '\\\"\\n')\n f_name.write('\\t\\tOverlayBackground=\\\"' + tupToPrint(colors[0]) + ' 80' + '\\\"\\n')\n f_name.write('\\t\\tOverlayPanels=\\\"' + tupToPrint(colors[0]) + ' 120' + '\\\"\\n')\n f_name.write('\\t\\tOverlayClock=\\\"' + tupToPrint(colors[15]) + ' 120' + '\\\"\\n')\n f_name.write('\\t\\tOverlaySideButtons=\\\"' + tupToPrint(colors[1]) + ' 120' + '\\\"\\n')\n f_name.write('\\t\\tOverlaySideButtons_h=\\\"' + tupToPrint(colors[4]) + ' 120' + '\\\"\\n')\n f_name.write('\\t\\tTextEntry=\\\"' + tupToPrint(colors[0]) + ' 255' + '\\\"\\n')\n f_name.write('\\t\\tHeader_Dark=\\\"' + tupToPrint(colors[0]) + ' 255' + '\\\"\\n')\n f_name.write('\\t\\tClientBG=\\\"' + tupToPrint(colors[0]) + ' 255' + '\\\"\\n')\n\n # Final formatting stuff\n f_name.write('\\t}\\n')\n f_name.write('}\\n')\n\n f_name.close()\n copy(newColors, metroInstall)\n # cleanup by removing generated color file\n os.remove(newColors)\n print(\"Wal colors are now patched and ready to go\")\n print(\"If this is your first run you may have to \")\n print(\"enable Metro Wal Mod skin in steam then \")\n print(\"simply restart steam!\")\n\ndef hexToRgb(hexColors):\n # convert hex colors to rgb colors (takes a list)\n tmpColors = []\n rgbColors = []\n for color in hexColors: # loop through the hex colors\n # remove the optothorpe\n # use tuple and a loop to convert them to rgb\n # append new colors to our rgb list\n tmp = color.lstrip('#')\n tmpColors.append(tuple(int(tmp[i:i+2], 16) for i in (0, 2 ,4)))\n return tmpColors\n\ndef parseCss(config):\n # parse colors file and return colors in list\n print(\"Reading colors\")\n f_name = open(config, 'r')\n raw_file = f_name.readlines() # save lines into raw_file\n del raw_file[0:11] # delete elements up to the colors\n del raw_file[16] # also that last line is just a } (16 now because we removed some already)\n\n colors = []\n for line in raw_file: # loop through raw_file\n tmp = line[line.find(\"#\"):] # remove everything before the octothorpe\n tmp = tmp[:7] # remove everything after the color\n\n colors.append(tmp) # add tmp to the new list\n\n f_name.close()\n return colors\n\n##################\n# For installing #\n# Wal Steam #\n##################\n\ndef makeCache():\n os.mkdir(ROOT_DIR)\n\ndef downloadMetro():\n # download metro for steam\n # download metro for steam patch\n print(\"Downloading Metro for steam\")\n urllib.request.urlretrieve(metroUrl, metroZip)\n z = zipfile.ZipFile(metroZip, 'r')\n z.extractall(metroResource)\n z.close()\n print(\"Downloading Metro patch\")\n urllib.request.urlretrieve(metroPatchUrl, metroPatchZip)\n z = zipfile.ZipFile(metroPatchZip, 'r')\n z.extractall(metroPatchResource)\n z.close()\n\ndef installMetro():\n print(\"Installing Metro Wal\")\n copy_tree(metroPatchCopy, metroCopy) # use copy_tree not copytree, shutil copytree is broken\n copy_tree(metroCopy, metroInstall)\n print(\"Metro Wal is now installed\")\n\ndef checkInstall():\n if not checkDir(ROOT_DIR):\n # wal_steam cache missing\n # redownload and patch\n makeCache()\n downloadMetro()\n installMetro()\n else:\n # cache was found\n # check for skin\n if not checkDir(metroInstall):\n # metro install missing\n downloadMetro()\n installMetro()\n else:\n # metro install found\n print(\"Metro install found\")\n\ndef main(arguments):\n checkInstall()\n\n if (arguments['--help'] == False and arguments['--version'] == False): # determine the mode\n if (arguments['-g'] == True):\n colors = parseCss(wpgConfig) # they picked g so parse wpg\n colors = hexToRgb(colors)\n makeStyle(colors)\n else:\n colors = parseCss(walConfig) # they picked w so parse wal\n colors = hexToRgb(colors)\n makeStyle(colors)\n\nif __name__ == '__main__':\n arguments = docopt(__doc__, version='Wal Steam 1.1.0') # create the flags from the comment\n main(arguments)\n","sub_path":"wal_steam.py","file_name":"wal_steam.py","file_ext":"py","file_size_in_byte":10557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"396615537","text":"import luigi\nimport os\nimport time\nimport json\n\nimport pandas as pd\n\nfrom jobmon import qmaster, central_job_monitor, job, sge\nfrom jobmon.executors import sge_exec\n\nfrom task_master import builder\nfrom task_master.process_artifact.process import PyProcess, Hook, ShellProcess\nfrom task_master.process_artifact.artifact import ModelableEntity, ComoVersion\n\nfrom db_tools.ezfuncs import query\n\nfrom super_squeeze import launch_squeeze\n\n\n# module level globals\ncode_dir = os.path.dirname(os.path.realpath(__file__))\ndata_dir = \"FILEPATH\"\nlog_dir = \"FILEPATH\"\n\nconda_bin_dir = \"FILEPATH\"\nconda_env = \"epic\"\n\ndescription = \"Exclusivity adjustment auto-mark\"\n\n\nclass DagMonitorMixins(builder.TaskBuilder):\n\n task_builder = luigi.Parameter(\n significant=False,\n dUSERt=(\n \"task_master.process_artifact.builders.JSONProcessArtifactMap?\"\n \"FILEPATH.json\".format(code_dir=code_dir)))\n\n @luigi.Task.event_handler(luigi.Event.FAILURE)\n def mourn_failure(task, exception):\n df = pd.DataFrame({\"process\": task.identity,\n \"error\": str(exception)},\n index=[0])\n df.to_csv(os.path.join(log_dir, \"failures\", task.identity + \".csv\"),\n index=False)\n\n def get_qmaster(self):\n execute = sge_exec.SGEExecutor(\n log_dir, 3, 30000, conda_bin_dir, conda_env)\n return qmaster.MonitoredQ(execute)\n\n\nclass Hook(Hook, DagMonitorMixins):\n identity = luigi.Parameter(dUSERt=\"como\")\n\n\nclass ModelableEntity(ModelableEntity, DagMonitorMixins):\n pass\n\n\nclass ComoVersion(ComoVersion, DagMonitorMixins):\n pass\n\n\nclass SevSplits(PyProcess, DagMonitorMixins):\n\n def _get_latest_mvid(self, meid):\n q = \"\"\"\n SELECT model_version_id\n FROM epi.model_version\n WHERE modelable_entity_id = {meid}\n ORDER BY date_inserted DESC LIMIT 1\n \"\"\".format(meid=meid)\n mvid = query(q, conn_def='epi').model_version_id.item()\n return mvid\n\n def execute(self):\n\n # get args\n kwargs = self.build_args[1]\n parent_meid = kwargs[\"parent_meid\"]\n env = \"prod\"\n\n # get qmaster\n q = self.get_qmaster()\n\n # submit split job\n remote_job = job.Job(\n mon_dir=log_dir,\n name=\"split_\" + (str(parent_meid)),\n runfile=os.path.join(code_dir, \"scripts\", \"FILEPATH.py\"),\n job_args=[str(parent_meid), env])\n q.queue_job(\n remote_job,\n slots=49,\n memory=98,\n project=\"proj_epic\")\n q.block_till_done(poll_interval=60)\n\n # submit aggregation/save jobs\n outputs_tuples = self.builder.get_process_outputs(self.identity)\n children_meids = [task_tuple[0] for task_tuple in outputs_tuples]\n for meid in children_meids:\n mvid = self._get_latest_mvid(meid)\n remote_job = job.Job(\n mon_dir=log_dir,\n name=\"save_\" + str(mvid),\n runfile=sge.true_path(executable=\"aggregate_mvid\"),\n job_args=[str(mvid), '--env', env, '--mark_best'])\n q.queue_job(\n remote_job,\n slots=40,\n memory=80,\n project=\"proj_epic\")\n q.block_till_done(poll_interval=60)\n\n\nclass Exclusivity(PyProcess, DagMonitorMixins):\n\n def execute(self):\n\n # compile submission arguments\n kwargs = self.build_args[1]\n me_map = kwargs.pop(\"me_map\")\n\n # get qmaster\n q = self.get_qmaster()\n\n # command line args for adjuster.py\n # parallelize by year\n for i in [1990, 1995, 2000, 2005, 2010, 2016]:\n ex_params = [\"--me_map\", json.dumps(me_map),\n \"--out_dir\", data_dir, \"--year_id\", str(i)]\n remote_job = job.Job(\n mon_dir=log_dir,\n runfile=os.path.join(code_dir, \"scripts\", \"run_ex_adjust.py\"),\n name=\"{proc}_{year}\".format(proc=self.identity, year=i),\n job_args=ex_params\n )\n q.queue_job(\n remote_job,\n slots=20,\n memory=40,\n project=\"proj_epic\")\n q.block_till_done(poll_interval=60)\n\n outputs_tuples = self.builder.get_process_outputs(self.identity)\n result_meids = [task_tuple[0] for task_tuple in outputs_tuples]\n for meid in result_meids:\n save_params = [\n meid,\n description,\n os.path.join(data_dir, str(meid)),\n \"--best\",\n \"--file_pattern\", \"{year_id}.h5\",\n \"--h5_tablename\", \"draws\"]\n\n remote_job = job.Job(\n mon_dir=log_dir,\n name=\"save_\" + str(meid),\n runfile=sge.true_path(executable=\"save_custom_results\"),\n job_args=save_params)\n q.queue_job(\n remote_job,\n slots=40,\n memory=80,\n project=\"proj_epic\")\n q.block_till_done(poll_interval=60)\n\n\nclass SuperSqueeze(ShellProcess, DagMonitorMixins):\n\n def execute(self):\n launch_squeeze(log_dir=log_dir)\n\n\nif __name__ == \"__main__\":\n try:\n cjm = central_job_monitor.CentralJobMonitor(log_dir, persistent=False)\n time.sleep(3)\n except:\n pass\n else:\n luigi.run()\n finally:\n cjm.generate_report()\n cjm.stop_responder()\n","sub_path":"shared_code/central_comp/non_fatal/como/severity_splits/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":5514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"437121836","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Implements vlans, bridges, and iptables rules using linux utilities.\"\"\"\n\nimport os\n\nfrom oslo_log import log as logging\nfrom oslo_utils import excutils\n\nfrom vif_plug_midonet.i18n import _LE\nfrom vif_plug_midonet import processutils\n\nLOG = logging.getLogger(__name__)\n\n\ndef device_exists(device):\n \"\"\"Check if ethernet device exists.\"\"\"\n return os.path.exists('/sys/class/net/%s' % device)\n\n\ndef create_tap_dev(dev, mac_address=None):\n if not device_exists(dev):\n try:\n # First, try with 'ip'\n processutils.execute('ip', 'tuntap', 'add', dev, 'mode',\n 'tap', check_exit_code=[0, 2, 254],\n run_as_root=True)\n except processutils.ProcessExecutionError:\n # Second option: tunctl\n processutils.execute('tunctl', '-b', '-t', dev,\n run_as_root=True)\n if mac_address:\n processutils.execute('ip', 'link', 'set', dev, 'address', mac_address,\n check_exit_code=[0, 2, 254],\n run_as_root=True)\n processutils.execute('ip', 'link', 'set', dev, 'up',\n check_exit_code=[0, 2, 254],\n run_as_root=True)\n\n\ndef delete_net_dev(dev):\n \"\"\"Delete a network device only if it exists.\"\"\"\n if device_exists(dev):\n try:\n processutils.execute('ip', 'link', 'delete', dev,\n check_exit_code=[0, 2, 254],\n run_as_root=True)\n LOG.debug(\"Net device removed: '%s'\", dev)\n except processutils.ProcessExecutionError:\n with excutils.save_and_reraise_exception():\n LOG.error(_LE(\"Failed removing net device: '%s'\"), dev)\n","sub_path":"vif_plug_midonet/linux_net.py","file_name":"linux_net.py","file_ext":"py","file_size_in_byte":2398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"178133246","text":"import requests\n\nfrom .globals import bitcoin, ESPLORA_URL\n\n\ndef get_fee(tx):\n # multiply stuff by 100000000 because bitcoind returns values in btc\n inputsum = sum(\n [\n int(\n bitcoin.getrawtransaction(inp[\"txid\"], True)[\"vout\"][inp[\"vout\"]][\n \"value\"\n ]\n * 100000000\n )\n for inp in tx[\"vin\"]\n ]\n )\n outputsum = sum([int(out[\"value\"] * 100000000) for out in tx[\"vout\"]])\n\n return inputsum - outputsum\n\n\ndef get_outspends(txid):\n return call_esplora(f\"/tx/{txid}/outspends\")\n\n\ndef call_esplora(path):\n try:\n r = requests.get(ESPLORA_URL + path)\n if r.ok:\n return r.json()\n except requests.exceptions.ConnectionError:\n pass\n\n r = requests.get(\"https://mempool.space/electrs\" + path)\n r.raise_for_status()\n return r.json()\n","sub_path":"getdata/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"18361361","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# @File Name: problem_134.py\n# @Author: Copyright (c) 2017-06-14 20:12:32 Gillett Hernandez\n# @Date: 2017-06-14 20:12:32\n# @Last Modified by: Gillett Hernandez\n# @Last Modified time: 2017-08-10 12:40:46\n\nfrom euler_funcs import *\nfrom math import log\n\ndef length(n):\n \"\"\"returns n's length by calculating ceil(log10(n))\"\"\"\n return 1+int(log(1+n,10))\n\n@timed\ndef main():\n primes = get_primes(limit=1000003)\n # for any p1, p2\n # n = 0 mod(p2) # is divisible by p2\n # n = p1 mod(10^len(p1)) # ends in p1\n S = 0\n for p, q in lag(primes[2:]):\n # if p >= 100:\n # break\n m0 = length(p)\n sm = 10**m0\n (s,t), C, (A,B) = egcd(q, sm)\n # print(p, q, sm, s, t, x)\n # print(p, q, A, B, s, t)\n x = p*s*q\n N = sm*q\n # lowest k such that x + kN > 0 is\n # x > -kN\n # x/-N < k\n # k > x/(-N)\n start = int(x/(-N))\n x += start*N\n while x <= 0:\n x += N\n # solutions are in the form x = x0 + N*k where N = n1*n2*...*nn\n # print(x)\n S += x\n print(S)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Python/problem_134.py","file_name":"problem_134.py","file_ext":"py","file_size_in_byte":1248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"509706757","text":"import App\nimport GlobalPropertyTemplates\n# Setting up local templates.\n#################################################\nFwdTube = App.TorpedoTubeProperty_Create(\"Fwd Tube\")\n\nFwdTube.SetMaxCondition(2500.000000)\nFwdTube.SetCritical(0)\nFwdTube.SetTargetable(1)\nFwdTube.SetPrimary(1)\nFwdTube.SetPosition(0.000000, 5.700000, -0.450000)\nFwdTube.SetPosition2D(55.000000, 18.000000)\nFwdTube.SetRepairComplexity(2.000000)\nFwdTube.SetDisabledPercentage(0.450000)\nFwdTube.SetRadius(0.100000)\nFwdTube.SetDumbfire(1)\nFwdTube.SetWeaponID(1)\nFwdTube.SetGroups(17)\nFwdTube.SetDamageRadiusFactor(0.060000)\nFwdTube.SetIconNum(370)\nFwdTube.SetIconPositionX(73.000000)\nFwdTube.SetIconPositionY(40.000000)\nFwdTube.SetIconAboveShip(1)\nFwdTube.SetImmediateDelay(0.000000)\nFwdTube.SetReloadDelay(40.000000)\nFwdTube.SetMaxReady(1)\nFwdTubeDirection = App.TGPoint3()\nFwdTubeDirection.SetXYZ(0.000000, 1.000000, 0.000000)\nFwdTube.SetDirection(FwdTubeDirection)\nFwdTubeRight = App.TGPoint3()\nFwdTubeRight.SetXYZ(0.000000, 0.000000, 1.000000)\nFwdTube.SetRight(FwdTubeRight)\nApp.g_kModelPropertyManager.RegisterLocalTemplate(FwdTube)\n#################################################\nShieldGenerator = App.ShieldProperty_Create(\"Shield Generator\")\n\nShieldGenerator.SetMaxCondition(10000.000000)\nShieldGenerator.SetCritical(0)\nShieldGenerator.SetTargetable(1)\nShieldGenerator.SetPrimary(1)\nShieldGenerator.SetPosition(0.000000, -2.500000, 1.000000)\nShieldGenerator.SetPosition2D(65.000000, 59.000000)\nShieldGenerator.SetRepairComplexity(1.000000)\nShieldGenerator.SetDisabledPercentage(0.500000)\nShieldGenerator.SetRadius(0.500000)\nShieldGenerator.SetNormalPowerPerSecond(2000.000000)\nShieldGeneratorShieldGlowColor = App.TGColorA()\nShieldGeneratorShieldGlowColor.SetRGBA(0.392157, 0.886275, 0.529412, 0.466667)\nShieldGenerator.SetShieldGlowColor(ShieldGeneratorShieldGlowColor)\nShieldGenerator.SetShieldGlowDecay(1.000000)\nShieldGenerator.SetMaxShields(ShieldGenerator.FRONT_SHIELDS, 12000.000000)\nShieldGenerator.SetMaxShields(ShieldGenerator.REAR_SHIELDS, 12000.000000)\nShieldGenerator.SetMaxShields(ShieldGenerator.TOP_SHIELDS, 12000.000000)\nShieldGenerator.SetMaxShields(ShieldGenerator.BOTTOM_SHIELDS, 12000.000000)\nShieldGenerator.SetMaxShields(ShieldGenerator.LEFT_SHIELDS, 12000.000000)\nShieldGenerator.SetMaxShields(ShieldGenerator.RIGHT_SHIELDS, 12000.000000)\nShieldGenerator.SetShieldChargePerSecond(ShieldGenerator.FRONT_SHIELDS, 10.000000)\nShieldGenerator.SetShieldChargePerSecond(ShieldGenerator.REAR_SHIELDS, 10.000000)\nShieldGenerator.SetShieldChargePerSecond(ShieldGenerator.TOP_SHIELDS, 10.000000)\nShieldGenerator.SetShieldChargePerSecond(ShieldGenerator.BOTTOM_SHIELDS, 10.000000)\nShieldGenerator.SetShieldChargePerSecond(ShieldGenerator.LEFT_SHIELDS, 10.000000)\nShieldGenerator.SetShieldChargePerSecond(ShieldGenerator.RIGHT_SHIELDS, 10.000000)\nApp.g_kModelPropertyManager.RegisterLocalTemplate(ShieldGenerator)\n#################################################\nHull = App.HullProperty_Create(\"Hull\")\n\nHull.SetMaxCondition(15000.000000)\nHull.SetCritical(1)\nHull.SetTargetable(1)\nHull.SetPrimary(1)\nHull.SetPosition(0.000000, 0.000000, 0.000000)\nHull.SetPosition2D(15.000000, 16.000000)\nHull.SetRepairComplexity(1.000000)\nHull.SetDisabledPercentage(0.000000)\nHull.SetRadius(5.000000)\nApp.g_kModelPropertyManager.RegisterLocalTemplate(Hull)\n#################################################\nSensorArray = App.SensorProperty_Create(\"Sensor Array\")\n\nSensorArray.SetMaxCondition(7500.000000)\nSensorArray.SetCritical(0)\nSensorArray.SetTargetable(1)\nSensorArray.SetPrimary(1)\nSensorArray.SetPosition(0.000000, 1.280000, -0.400000)\nSensorArray.SetPosition2D(66.000000, 16.000000)\nSensorArray.SetRepairComplexity(1.000000)\nSensorArray.SetDisabledPercentage(0.300000)\nSensorArray.SetRadius(0.300000)\nSensorArray.SetNormalPowerPerSecond(500.000000)\nSensorArray.SetBaseSensorRange(2500.000000)\nSensorArray.SetMaxProbes(10)\nApp.g_kModelPropertyManager.RegisterLocalTemplate(SensorArray)\n#################################################\nQuantumSingularity = App.PowerProperty_Create(\"Quantum Singularity\")\n\nQuantumSingularity.SetMaxCondition(11000.000000)\nQuantumSingularity.SetCritical(1)\nQuantumSingularity.SetTargetable(1)\nQuantumSingularity.SetPrimary(1)\nQuantumSingularity.SetPosition(0.000000, 3.400000, -0.100000)\nQuantumSingularity.SetPosition2D(65.000000, 75.000000)\nQuantumSingularity.SetRepairComplexity(1.000000)\nQuantumSingularity.SetDisabledPercentage(0.500000)\nQuantumSingularity.SetRadius(0.340000)\nQuantumSingularity.SetMainBatteryLimit(700000.000000)\nQuantumSingularity.SetBackupBatteryLimit(400000.000000)\nQuantumSingularity.SetMainConduitCapacity(7000.000000)\nQuantumSingularity.SetBackupConduitCapacity(950.000000)\nQuantumSingularity.SetPowerOutput(6500.000000)\nApp.g_kModelPropertyManager.RegisterLocalTemplate(QuantumSingularity)\n#################################################\nImpulseEngines = App.ImpulseEngineProperty_Create(\"Impulse Engines\")\n\nImpulseEngines.SetMaxCondition(500.000000)\nImpulseEngines.SetCritical(0)\nImpulseEngines.SetTargetable(0)\nImpulseEngines.SetPrimary(1)\nImpulseEngines.SetPosition(0.000000, 0.000000, 1.200000)\nImpulseEngines.SetPosition2D(64.000000, 104.000000)\nImpulseEngines.SetRepairComplexity(1.000000)\nImpulseEngines.SetDisabledPercentage(0.250000)\nImpulseEngines.SetRadius(0.500000)\nImpulseEngines.SetNormalPowerPerSecond(1000.000000)\nImpulseEngines.SetMaxAccel(1.900000)\nImpulseEngines.SetMaxAngularAccel(0.150000)\nImpulseEngines.SetMaxAngularVelocity(0.150000)\nImpulseEngines.SetMaxSpeed(7.000000)\nImpulseEngines.SetEngineSound(\"Romulan Engines\")\nApp.g_kModelPropertyManager.RegisterLocalTemplate(ImpulseEngines)\n#################################################\nFwdPort = App.PulseWeaponProperty_Create(\"Fwd Port\")\n\nFwdPort.SetMaxCondition(7000.000000)\nFwdPort.SetCritical(0)\nFwdPort.SetTargetable(1)\nFwdPort.SetPrimary(1)\nFwdPort.SetPosition(-0.500000, 4.150000, 0.500000)\nFwdPort.SetPosition2D(59.000000, 4.000000)\nFwdPort.SetRepairComplexity(2.000000)\nFwdPort.SetDisabledPercentage(0.250000)\nFwdPort.SetRadius(0.100000)\nFwdPort.SetDumbfire(1)\nFwdPort.SetWeaponID(1)\nFwdPort.SetGroups(0)\nFwdPort.SetDamageRadiusFactor(0.060000)\nFwdPort.SetIconNum(365)\nFwdPort.SetIconPositionX(65.000000)\nFwdPort.SetIconPositionY(40.000000)\nFwdPort.SetIconAboveShip(1)\nFwdPort.SetFireSound(\"\")\nFwdPort.SetMaxCharge(6.000000)\nFwdPort.SetMaxDamage(1.000000)\nFwdPort.SetMaxDamageDistance(150.000000)\nFwdPort.SetMinFiringCharge(1.000000)\nFwdPort.SetNormalDischargeRate(1.000000)\nFwdPort.SetRechargeRate(0.300000)\nFwdPort.SetIndicatorIconNum(0)\nFwdPort.SetIndicatorIconPositionX(26.000000)\nFwdPort.SetIndicatorIconPositionY(68.000000)\nFwdPortForward = App.TGPoint3()\nFwdPortForward.SetXYZ(0.000000, 1.000000, 0.000000)\nFwdPortUp = App.TGPoint3()\nFwdPortUp.SetXYZ(0.000000, 0.000000, 1.000000)\nFwdPort.SetOrientation(FwdPortForward, FwdPortUp)\nFwdPort.SetArcWidthAngles(0.087266, -1.570796)\nFwdPort.SetArcHeightAngles(-0.872665, 0.872665)\nFwdPort.SetCooldownTime(0.100000)\nFwdPort.SetModuleName(\"Custom.BCSTNG.CWP.Scripts.blackelmwarbirdpulsedisruptor\")\nApp.g_kModelPropertyManager.RegisterLocalTemplate(FwdPort)\n#################################################\nDisruptorCannons = App.WeaponSystemProperty_Create(\"Disruptor Cannons\")\n\nDisruptorCannons.SetMaxCondition(6000.000000)\nDisruptorCannons.SetCritical(0)\nDisruptorCannons.SetTargetable(0)\nDisruptorCannons.SetPrimary(1)\nDisruptorCannons.SetPosition(0.000000, 0.000000, 1.200000)\nDisruptorCannons.SetPosition2D(64.000000, 44.000000)\nDisruptorCannons.SetRepairComplexity(9.000000)\nDisruptorCannons.SetDisabledPercentage(0.250000)\nDisruptorCannons.SetRadius(0.500000)\nDisruptorCannons.SetNormalPowerPerSecond(600.000000)\nDisruptorCannons.SetWeaponSystemType(DisruptorCannons.WST_PULSE)\nDisruptorCannons.SetSingleFire(1)\nDisruptorCannons.SetAimedWeapon(0)\nkFiringChainString = App.TGString()\nkFiringChainString.SetString(\"\")\nDisruptorCannons.SetFiringChainString(kFiringChainString)\nApp.g_kModelPropertyManager.RegisterLocalTemplate(DisruptorCannons)\n#################################################\nWarpEngines = App.WarpEngineProperty_Create(\"Warp Engines\")\n\nWarpEngines.SetMaxCondition(8000.000000)\nWarpEngines.SetCritical(0)\nWarpEngines.SetTargetable(0)\nWarpEngines.SetPrimary(1)\nWarpEngines.SetPosition(0.000000, 0.000000, 1.300000)\nWarpEngines.SetPosition2D(64.000000, 104.000000)\nWarpEngines.SetRepairComplexity(3.000000)\nWarpEngines.SetDisabledPercentage(0.500000)\nWarpEngines.SetRadius(0.500000)\nWarpEngines.SetNormalPowerPerSecond(0.000000)\nApp.g_kModelPropertyManager.RegisterLocalTemplate(WarpEngines)\n#################################################\nTorpedoes = App.TorpedoSystemProperty_Create(\"Torpedoes\")\n\nTorpedoes.SetMaxCondition(2200.000000)\nTorpedoes.SetCritical(0)\nTorpedoes.SetTargetable(0)\nTorpedoes.SetPrimary(1)\nTorpedoes.SetPosition(0.000000, 0.650000, 0.040000)\nTorpedoes.SetPosition2D(64.000000, 10.000000)\nTorpedoes.SetRepairComplexity(3.000000)\nTorpedoes.SetDisabledPercentage(0.500000)\nTorpedoes.SetRadius(0.090000)\nTorpedoes.SetNormalPowerPerSecond(650.000000)\nTorpedoes.SetWeaponSystemType(Torpedoes.WST_TORPEDO)\nTorpedoes.SetSingleFire(0)\nTorpedoes.SetAimedWeapon(1)\nkFiringChainString = App.TGString()\nkFiringChainString.SetString(\"0;Single;12;Dual;5;All\")\nTorpedoes.SetFiringChainString(kFiringChainString)\nTorpedoes.SetMaxTorpedoes(0, 24)\nTorpedoes.SetTorpedoScript(0, \"Custom.BCSTNG.CWP.Scripts.blackelmwarbirdtorpedo2\")\nTorpedoes.SetMaxTorpedoes(1, 500)\nTorpedoes.SetTorpedoScript(1, \"Custom.BCSTNG.CWP.Scripts.blackelmwarbirdtorpedo1\")\nTorpedoes.SetNumAmmoTypes(2)\nApp.g_kModelPropertyManager.RegisterLocalTemplate(Torpedoes)\n#################################################\nCloakingDevice = App.CloakingSubsystemProperty_Create(\"Cloaking Device\")\n\nCloakingDevice.SetMaxCondition(4500.000000)\nCloakingDevice.SetCritical(0)\nCloakingDevice.SetTargetable(1)\nCloakingDevice.SetPrimary(1)\nCloakingDevice.SetPosition(0.000000, 2.000000, 1.220000)\nCloakingDevice.SetPosition2D(74.000000, 51.000000)\nCloakingDevice.SetRepairComplexity(3.000000)\nCloakingDevice.SetDisabledPercentage(0.500000)\nCloakingDevice.SetRadius(0.200000)\nCloakingDevice.SetNormalPowerPerSecond(1000.000000)\nCloakingDevice.SetCloakStrength(1000.000000)\nApp.g_kModelPropertyManager.RegisterLocalTemplate(CloakingDevice)\n#################################################\nStarImpulse = App.EngineProperty_Create(\"Star Impulse\")\n\nStarImpulse.SetMaxCondition(5000.000000)\nStarImpulse.SetCritical(0)\nStarImpulse.SetTargetable(1)\nStarImpulse.SetPrimary(1)\nStarImpulse.SetPosition(4.400000, -1.700000, 0.000000)\nStarImpulse.SetPosition2D(107.000000, 78.000000)\nStarImpulse.SetRepairComplexity(3.000000)\nStarImpulse.SetDisabledPercentage(0.500000)\nStarImpulse.SetRadius(0.400000)\nStarImpulse.SetEngineType(StarImpulse.EP_IMPULSE)\nApp.g_kModelPropertyManager.RegisterLocalTemplate(StarImpulse)\n#################################################\nDamageControl = App.RepairSubsystemProperty_Create(\"Damage Control\")\n\nDamageControl.SetMaxCondition(3000.000000)\nDamageControl.SetCritical(0)\nDamageControl.SetTargetable(0)\nDamageControl.SetPrimary(1)\nDamageControl.SetPosition(0.000000, 0.000000, 1.200000)\nDamageControl.SetPosition2D(64.000000, 80.000000)\nDamageControl.SetRepairComplexity(2.000000)\nDamageControl.SetDisabledPercentage(0.100000)\nDamageControl.SetRadius(0.500000)\nDamageControl.SetNormalPowerPerSecond(1.000000)\nDamageControl.SetMaxRepairPoints(75.000000)\nDamageControl.SetNumRepairTeams(5)\nApp.g_kModelPropertyManager.RegisterLocalTemplate(DamageControl)\n#################################################\nTalshiarWarbird = App.ShipProperty_Create(\"TalshiarWarbird\")\n\nTalshiarWarbird.SetGenus(1)\nTalshiarWarbird.SetSpecies(401)\nTalshiarWarbird.SetMass(1000.000000)\nTalshiarWarbird.SetRotationalInertia(2000.000000)\nTalshiarWarbird.SetShipName(\"TalshiarWarbird\")\nTalshiarWarbird.SetModelFilename(\"\")\nTalshiarWarbird.SetDamageResolution(10.000000)\nTalshiarWarbird.SetAffiliation(0)\nTalshiarWarbird.SetStationary(0)\nTalshiarWarbird.SetAIString(\"NonFedAttack\")\nTalshiarWarbird.SetDeathExplosionSound(\"g_lsDeathExplosions\")\nApp.g_kModelPropertyManager.RegisterLocalTemplate(TalshiarWarbird)\n#################################################\nViewscreenForward = App.PositionOrientationProperty_Create(\"ViewscreenForward\")\n\nViewscreenForwardForward = App.TGPoint3()\nViewscreenForwardForward.SetXYZ(0.000000, 1.000000, 0.000000)\nViewscreenForwardUp = App.TGPoint3()\nViewscreenForwardUp.SetXYZ(0.000000, 0.000000, 1.000000)\nViewscreenForwardRight = App.TGPoint3()\nViewscreenForwardRight.SetXYZ(1.000000, 0.000000, 0.000000)\nViewscreenForward.SetOrientation(ViewscreenForwardForward, ViewscreenForwardUp, ViewscreenForwardRight)\nViewscreenForwardPosition = App.TGPoint3()\nViewscreenForwardPosition.SetXYZ(0.000000, 6.500000, 0.000000)\nViewscreenForward.SetPosition(ViewscreenForwardPosition)\nApp.g_kModelPropertyManager.RegisterLocalTemplate(ViewscreenForward)\n#################################################\nViewscreenBack = App.PositionOrientationProperty_Create(\"ViewscreenBack\")\n\nViewscreenBackForward = App.TGPoint3()\nViewscreenBackForward.SetXYZ(0.000000, -1.000000, 0.000000)\nViewscreenBackUp = App.TGPoint3()\nViewscreenBackUp.SetXYZ(0.000000, 0.000000, 1.000000)\nViewscreenBackRight = App.TGPoint3()\nViewscreenBackRight.SetXYZ(-1.000000, 0.000000, 0.000000)\nViewscreenBack.SetOrientation(ViewscreenBackForward, ViewscreenBackUp, ViewscreenBackRight)\nViewscreenBackPosition = App.TGPoint3()\nViewscreenBackPosition.SetXYZ(0.000000, -6.500000, 0.000000)\nViewscreenBack.SetPosition(ViewscreenBackPosition)\nApp.g_kModelPropertyManager.RegisterLocalTemplate(ViewscreenBack)\n#################################################\nViewscreenLeft = App.PositionOrientationProperty_Create(\"ViewscreenLeft\")\n\nViewscreenLeftForward = App.TGPoint3()\nViewscreenLeftForward.SetXYZ(-1.000000, 0.000000, 0.000000)\nViewscreenLeftUp = App.TGPoint3()\nViewscreenLeftUp.SetXYZ(0.000000, 0.000000, 1.000000)\nViewscreenLeftRight = App.TGPoint3()\nViewscreenLeftRight.SetXYZ(0.000000, 1.000000, 0.000000)\nViewscreenLeft.SetOrientation(ViewscreenLeftForward, ViewscreenLeftUp, ViewscreenLeftRight)\nViewscreenLeftPosition = App.TGPoint3()\nViewscreenLeftPosition.SetXYZ(-5.500000, 0.000000, 0.000000)\nViewscreenLeft.SetPosition(ViewscreenLeftPosition)\nApp.g_kModelPropertyManager.RegisterLocalTemplate(ViewscreenLeft)\n#################################################\nViewscreenRight = App.PositionOrientationProperty_Create(\"ViewscreenRight\")\n\nViewscreenRightForward = App.TGPoint3()\nViewscreenRightForward.SetXYZ(1.000000, 0.000000, 0.000000)\nViewscreenRightUp = App.TGPoint3()\nViewscreenRightUp.SetXYZ(0.000000, 0.000000, 1.000000)\nViewscreenRightRight = App.TGPoint3()\nViewscreenRightRight.SetXYZ(0.000000, -1.000000, 0.000000)\nViewscreenRight.SetOrientation(ViewscreenRightForward, ViewscreenRightUp, ViewscreenRightRight)\nViewscreenRightPosition = App.TGPoint3()\nViewscreenRightPosition.SetXYZ(5.500000, 0.000000, 0.000000)\nViewscreenRight.SetPosition(ViewscreenRightPosition)\nApp.g_kModelPropertyManager.RegisterLocalTemplate(ViewscreenRight)\n#################################################\nViewscreenUp = App.PositionOrientationProperty_Create(\"ViewscreenUp\")\n\nViewscreenUpForward = App.TGPoint3()\nViewscreenUpForward.SetXYZ(0.000000, 0.000000, 1.000000)\nViewscreenUpUp = App.TGPoint3()\nViewscreenUpUp.SetXYZ(0.000000, -1.000000, 0.000000)\nViewscreenUpRight = App.TGPoint3()\nViewscreenUpRight.SetXYZ(1.000000, 0.000000, 0.000000)\nViewscreenUp.SetOrientation(ViewscreenUpForward, ViewscreenUpUp, ViewscreenUpRight)\nViewscreenUpPosition = App.TGPoint3()\nViewscreenUpPosition.SetXYZ(0.000000, 0.000000, 2.000000)\nViewscreenUp.SetPosition(ViewscreenUpPosition)\nApp.g_kModelPropertyManager.RegisterLocalTemplate(ViewscreenUp)\n#################################################\nViewscreenDown = App.PositionOrientationProperty_Create(\"ViewscreenDown\")\n\nViewscreenDownForward = App.TGPoint3()\nViewscreenDownForward.SetXYZ(0.000000, 0.000000, -1.000000)\nViewscreenDownUp = App.TGPoint3()\nViewscreenDownUp.SetXYZ(0.000000, 1.000000, 0.000000)\nViewscreenDownRight = App.TGPoint3()\nViewscreenDownRight.SetXYZ(1.000000, 0.000000, 0.000000)\nViewscreenDown.SetOrientation(ViewscreenDownForward, ViewscreenDownUp, ViewscreenDownRight)\nViewscreenDownPosition = App.TGPoint3()\nViewscreenDownPosition.SetXYZ(0.000000, 0.000000, -2.000000)\nViewscreenDown.SetPosition(ViewscreenDownPosition)\nApp.g_kModelPropertyManager.RegisterLocalTemplate(ViewscreenDown)\n#################################################\nFirstPersonCamera = App.PositionOrientationProperty_Create(\"FirstPersonCamera\")\n\nFirstPersonCameraForward = App.TGPoint3()\nFirstPersonCameraForward.SetXYZ(0.000000, 1.000000, 0.000000)\nFirstPersonCameraUp = App.TGPoint3()\nFirstPersonCameraUp.SetXYZ(0.000000, 0.000000, 1.000000)\nFirstPersonCameraRight = App.TGPoint3()\nFirstPersonCameraRight.SetXYZ(1.000000, 0.000000, 0.000000)\nFirstPersonCamera.SetOrientation(FirstPersonCameraForward, FirstPersonCameraUp, FirstPersonCameraRight)\nFirstPersonCameraPosition = App.TGPoint3()\nFirstPersonCameraPosition.SetXYZ(0.000000, 6.500000, 0.100000)\nFirstPersonCamera.SetPosition(FirstPersonCameraPosition)\nApp.g_kModelPropertyManager.RegisterLocalTemplate(FirstPersonCamera)\n#################################################\nFwdStar = App.PulseWeaponProperty_Create(\"Fwd Star\")\n\nFwdStar.SetMaxCondition(7000.000000)\nFwdStar.SetCritical(0)\nFwdStar.SetTargetable(1)\nFwdStar.SetPrimary(1)\nFwdStar.SetPosition(0.500000, 4.150000, 0.500000)\nFwdStar.SetPosition2D(71.000000, 4.000000)\nFwdStar.SetRepairComplexity(2.000000)\nFwdStar.SetDisabledPercentage(0.250000)\nFwdStar.SetRadius(0.040000)\nFwdStar.SetDumbfire(1)\nFwdStar.SetWeaponID(1)\nFwdStar.SetGroups(0)\nFwdStar.SetDamageRadiusFactor(0.060000)\nFwdStar.SetIconNum(365)\nFwdStar.SetIconPositionX(90.000000)\nFwdStar.SetIconPositionY(40.000000)\nFwdStar.SetIconAboveShip(1)\nFwdStar.SetFireSound(\"\")\nFwdStar.SetMaxCharge(6.000000)\nFwdStar.SetMaxDamage(1.000000)\nFwdStar.SetMaxDamageDistance(150.000000)\nFwdStar.SetMinFiringCharge(1.000000)\nFwdStar.SetNormalDischargeRate(1.000000)\nFwdStar.SetRechargeRate(0.300000)\nFwdStar.SetIndicatorIconNum(0)\nFwdStar.SetIndicatorIconPositionX(26.000000)\nFwdStar.SetIndicatorIconPositionY(68.000000)\nFwdStarForward = App.TGPoint3()\nFwdStarForward.SetXYZ(0.000000, 1.000000, 0.000000)\nFwdStarUp = App.TGPoint3()\nFwdStarUp.SetXYZ(0.000000, 0.000000, 1.000000)\nFwdStar.SetOrientation(FwdStarForward, FwdStarUp)\nFwdStar.SetArcWidthAngles(-0.087266, 1.570796)\nFwdStar.SetArcHeightAngles(-0.872665, 0.872665)\nFwdStar.SetCooldownTime(0.100000)\nFwdStar.SetModuleName(\"Custom.BCSTNG.CWP.Scripts.blackelmwarbirdpulsedisruptor\")\nApp.g_kModelPropertyManager.RegisterLocalTemplate(FwdStar)\n#################################################\nAftDorsal1 = App.PulseWeaponProperty_Create(\"Aft Dorsal 1\")\n\nAftDorsal1.SetMaxCondition(7000.000000)\nAftDorsal1.SetCritical(0)\nAftDorsal1.SetTargetable(1)\nAftDorsal1.SetPrimary(1)\nAftDorsal1.SetPosition(1.350000, -3.600000, 0.670000)\nAftDorsal1.SetPosition2D(43.000000, 67.000000)\nAftDorsal1.SetRepairComplexity(2.000000)\nAftDorsal1.SetDisabledPercentage(0.250000)\nAftDorsal1.SetRadius(0.100000)\nAftDorsal1.SetDumbfire(1)\nAftDorsal1.SetWeaponID(1)\nAftDorsal1.SetGroups(0)\nAftDorsal1.SetDamageRadiusFactor(0.060000)\nAftDorsal1.SetIconNum(366)\nAftDorsal1.SetIconPositionX(59.000000)\nAftDorsal1.SetIconPositionY(96.000000)\nAftDorsal1.SetIconAboveShip(1)\nAftDorsal1.SetFireSound(\"\")\nAftDorsal1.SetMaxCharge(3.000000)\nAftDorsal1.SetMaxDamage(1.000000)\nAftDorsal1.SetMaxDamageDistance(150.000000)\nAftDorsal1.SetMinFiringCharge(1.000000)\nAftDorsal1.SetNormalDischargeRate(1.000000)\nAftDorsal1.SetRechargeRate(0.300000)\nAftDorsal1.SetIndicatorIconNum(0)\nAftDorsal1.SetIndicatorIconPositionX(26.000000)\nAftDorsal1.SetIndicatorIconPositionY(68.000000)\nAftDorsal1Forward = App.TGPoint3()\nAftDorsal1Forward.SetXYZ(0.431934, -0.863868, 0.259161)\nAftDorsal1Up = App.TGPoint3()\nAftDorsal1Up.SetXYZ(0.000000, 0.000000, 1.000000)\nAftDorsal1.SetOrientation(AftDorsal1Forward, AftDorsal1Up)\nAftDorsal1.SetArcWidthAngles(-0.610865, 0.610865)\nAftDorsal1.SetArcHeightAngles(-0.523599, 1.047198)\nAftDorsal1.SetCooldownTime(0.100000)\nAftDorsal1.SetModuleName(\"Custom.BCSTNG.CWP.Scripts.blackelmwarbirdpulsedisruptor\")\nApp.g_kModelPropertyManager.RegisterLocalTemplate(AftDorsal1)\n#################################################\nFwdTube2 = App.TorpedoTubeProperty_Create(\"Fwd Tube 2\")\n\nFwdTube2.SetMaxCondition(4000.000000)\nFwdTube2.SetCritical(0)\nFwdTube2.SetTargetable(1)\nFwdTube2.SetPrimary(1)\nFwdTube2.SetPosition(0.000000, 5.700000, -0.450000)\nFwdTube2.SetPosition2D(79.000000, 18.000000)\nFwdTube2.SetRepairComplexity(2.000000)\nFwdTube2.SetDisabledPercentage(0.450000)\nFwdTube2.SetRadius(0.100000)\nFwdTube2.SetDumbfire(1)\nFwdTube2.SetWeaponID(1)\nFwdTube2.SetGroups(17)\nFwdTube2.SetDamageRadiusFactor(0.060000)\nFwdTube2.SetIconNum(370)\nFwdTube2.SetIconPositionX(83.000000)\nFwdTube2.SetIconPositionY(40.000000)\nFwdTube2.SetIconAboveShip(1)\nFwdTube2.SetImmediateDelay(0.000000)\nFwdTube2.SetReloadDelay(40.000000)\nFwdTube2.SetMaxReady(1)\nFwdTube2Direction = App.TGPoint3()\nFwdTube2Direction.SetXYZ(0.000000, 1.000000, 0.000000)\nFwdTube2.SetDirection(FwdTube2Direction)\nFwdTube2Right = App.TGPoint3()\nFwdTube2Right.SetXYZ(0.707107, 0.000000, 0.707107)\nFwdTube2.SetRight(FwdTube2Right)\nApp.g_kModelPropertyManager.RegisterLocalTemplate(FwdTube2)\n#################################################\nPortImpulse = App.EngineProperty_Create(\"Port Impulse\")\n\nPortImpulse.SetMaxCondition(5000.000000)\nPortImpulse.SetCritical(0)\nPortImpulse.SetTargetable(1)\nPortImpulse.SetPrimary(1)\nPortImpulse.SetPosition(-4.400000, -1.700000, 0.000000)\nPortImpulse.SetPosition2D(22.000000, 78.000000)\nPortImpulse.SetRepairComplexity(3.000000)\nPortImpulse.SetDisabledPercentage(0.500000)\nPortImpulse.SetRadius(0.400000)\nPortImpulse.SetEngineType(PortImpulse.EP_IMPULSE)\nApp.g_kModelPropertyManager.RegisterLocalTemplate(PortImpulse)\n#################################################\nBridge = App.HullProperty_Create(\"Bridge\")\n\nBridge.SetMaxCondition(10000.000000)\nBridge.SetCritical(1)\nBridge.SetTargetable(1)\nBridge.SetPrimary(0)\nBridge.SetPosition(0.020000, 5.480000, 0.160000)\nBridge.SetPosition2D(65.000000, 31.000000)\nBridge.SetRepairComplexity(1.000000)\nBridge.SetDisabledPercentage(0.000000)\nBridge.SetRadius(0.050000)\nApp.g_kModelPropertyManager.RegisterLocalTemplate(Bridge)\n#################################################\nAftDorsal2 = App.PulseWeaponProperty_Create(\"Aft Dorsal 2\")\n\nAftDorsal2.SetMaxCondition(7000.000000)\nAftDorsal2.SetCritical(0)\nAftDorsal2.SetTargetable(1)\nAftDorsal2.SetPrimary(1)\nAftDorsal2.SetPosition(-1.350000, -3.600000, 0.670000)\nAftDorsal2.SetPosition2D(81.000000, 67.000000)\nAftDorsal2.SetRepairComplexity(2.000000)\nAftDorsal2.SetDisabledPercentage(0.250000)\nAftDorsal2.SetRadius(0.100000)\nAftDorsal2.SetDumbfire(1)\nAftDorsal2.SetWeaponID(1)\nAftDorsal2.SetGroups(0)\nAftDorsal2.SetDamageRadiusFactor(0.060000)\nAftDorsal2.SetIconNum(366)\nAftDorsal2.SetIconPositionX(98.000000)\nAftDorsal2.SetIconPositionY(97.000000)\nAftDorsal2.SetIconAboveShip(1)\nAftDorsal2.SetFireSound(\"\")\nAftDorsal2.SetMaxCharge(3.000000)\nAftDorsal2.SetMaxDamage(1.000000)\nAftDorsal2.SetMaxDamageDistance(150.000000)\nAftDorsal2.SetMinFiringCharge(1.000000)\nAftDorsal2.SetNormalDischargeRate(1.000000)\nAftDorsal2.SetRechargeRate(0.300000)\nAftDorsal2.SetIndicatorIconNum(0)\nAftDorsal2.SetIndicatorIconPositionX(26.000000)\nAftDorsal2.SetIndicatorIconPositionY(68.000000)\nAftDorsal2Forward = App.TGPoint3()\nAftDorsal2Forward.SetXYZ(-0.377190, -0.887077, 0.266123)\nAftDorsal2Up = App.TGPoint3()\nAftDorsal2Up.SetXYZ(0.000000, 0.000000, 1.000000)\nAftDorsal2.SetOrientation(AftDorsal2Forward, AftDorsal2Up)\nAftDorsal2.SetArcWidthAngles(-0.610865, 0.610865)\nAftDorsal2.SetArcHeightAngles(-0.523599, 1.047198)\nAftDorsal2.SetCooldownTime(0.100000)\nAftDorsal2.SetModuleName(\"Custom.BCSTNG.CWP.Scripts.blackelmwarbirdpulsedisruptor\")\nApp.g_kModelPropertyManager.RegisterLocalTemplate(AftDorsal2)\n#################################################\nFwdVentral1 = App.PulseWeaponProperty_Create(\"Fwd Ventral 1\")\n\nFwdVentral1.SetMaxCondition(7000.000000)\nFwdVentral1.SetCritical(0)\nFwdVentral1.SetTargetable(1)\nFwdVentral1.SetPrimary(1)\nFwdVentral1.SetPosition(0.200000, 1.360000, -0.750000)\nFwdVentral1.SetPosition2D(50.000000, 32.000000)\nFwdVentral1.SetRepairComplexity(2.000000)\nFwdVentral1.SetDisabledPercentage(0.250000)\nFwdVentral1.SetRadius(0.100000)\nFwdVentral1.SetDumbfire(1)\nFwdVentral1.SetWeaponID(1)\nFwdVentral1.SetGroups(0)\nFwdVentral1.SetDamageRadiusFactor(0.060000)\nFwdVentral1.SetIconNum(365)\nFwdVentral1.SetIconPositionX(65.000000)\nFwdVentral1.SetIconPositionY(54.000000)\nFwdVentral1.SetIconAboveShip(1)\nFwdVentral1.SetFireSound(\"\")\nFwdVentral1.SetMaxCharge(3.000000)\nFwdVentral1.SetMaxDamage(1.000000)\nFwdVentral1.SetMaxDamageDistance(150.000000)\nFwdVentral1.SetMinFiringCharge(1.000000)\nFwdVentral1.SetNormalDischargeRate(1.000000)\nFwdVentral1.SetRechargeRate(0.300000)\nFwdVentral1.SetIndicatorIconNum(0)\nFwdVentral1.SetIndicatorIconPositionX(0.000000)\nFwdVentral1.SetIndicatorIconPositionY(0.000000)\nFwdVentral1Forward = App.TGPoint3()\nFwdVentral1Forward.SetXYZ(0.000000, 0.894427, -0.447214)\nFwdVentral1Up = App.TGPoint3()\nFwdVentral1Up.SetXYZ(0.000000, 0.000000, -1.000000)\nFwdVentral1.SetOrientation(FwdVentral1Forward, FwdVentral1Up)\nFwdVentral1.SetArcWidthAngles(-0.872665, 0.872665)\nFwdVentral1.SetArcHeightAngles(0.174533, 1.047198)\nFwdVentral1.SetCooldownTime(0.100000)\nFwdVentral1.SetModuleName(\"Custom.BCSTNG.CWP.Scripts.blackelmwarbirdpulsedisruptor\")\nApp.g_kModelPropertyManager.RegisterLocalTemplate(FwdVentral1)\n#################################################\nFwdVentral2 = App.PulseWeaponProperty_Create(\"Fwd Ventral 2\")\n\nFwdVentral2.SetMaxCondition(7000.000000)\nFwdVentral2.SetCritical(0)\nFwdVentral2.SetTargetable(1)\nFwdVentral2.SetPrimary(1)\nFwdVentral2.SetPosition(-0.200000, 1.360000, -0.750000)\nFwdVentral2.SetPosition2D(80.000000, 32.000000)\nFwdVentral2.SetRepairComplexity(2.000000)\nFwdVentral2.SetDisabledPercentage(0.250000)\nFwdVentral2.SetRadius(0.100000)\nFwdVentral2.SetDumbfire(1)\nFwdVentral2.SetWeaponID(1)\nFwdVentral2.SetGroups(0)\nFwdVentral2.SetDamageRadiusFactor(0.060000)\nFwdVentral2.SetIconNum(365)\nFwdVentral2.SetIconPositionX(90.000000)\nFwdVentral2.SetIconPositionY(54.000000)\nFwdVentral2.SetIconAboveShip(1)\nFwdVentral2.SetFireSound(\"\")\nFwdVentral2.SetMaxCharge(3.000000)\nFwdVentral2.SetMaxDamage(1.000000)\nFwdVentral2.SetMaxDamageDistance(150.000000)\nFwdVentral2.SetMinFiringCharge(1.000000)\nFwdVentral2.SetNormalDischargeRate(1.000000)\nFwdVentral2.SetRechargeRate(0.300000)\nFwdVentral2.SetIndicatorIconNum(0)\nFwdVentral2.SetIndicatorIconPositionX(26.000000)\nFwdVentral2.SetIndicatorIconPositionY(68.000000)\nFwdVentral2Forward = App.TGPoint3()\nFwdVentral2Forward.SetXYZ(0.000000, 0.894427, -0.447214)\nFwdVentral2Up = App.TGPoint3()\nFwdVentral2Up.SetXYZ(0.000000, 0.000000, -1.000000)\nFwdVentral2.SetOrientation(FwdVentral2Forward, FwdVentral2Up)\nFwdVentral2.SetArcWidthAngles(-0.872665, 0.872665)\nFwdVentral2.SetArcHeightAngles(0.174533, 1.047198)\nFwdVentral2.SetCooldownTime(0.100000)\nFwdVentral2.SetModuleName(\"Custom.BCSTNG.CWP.Scripts.blackelmwarbirdpulsedisruptor\")\nApp.g_kModelPropertyManager.RegisterLocalTemplate(FwdVentral2)\n#################################################\nFwdTube1a = App.TorpedoTubeProperty_Create(\"Fwd Tube 1a\")\n\nFwdTube1a.SetMaxCondition(4000.000000)\nFwdTube1a.SetCritical(0)\nFwdTube1a.SetTargetable(1)\nFwdTube1a.SetPrimary(1)\nFwdTube1a.SetPosition(0.000000, 5.700000, -0.450000)\nFwdTube1a.SetPosition2D(55.000000, 18.000000)\nFwdTube1a.SetRepairComplexity(2.000000)\nFwdTube1a.SetDisabledPercentage(0.450000)\nFwdTube1a.SetRadius(0.100000)\nFwdTube1a.SetDumbfire(1)\nFwdTube1a.SetWeaponID(1)\nFwdTube1a.SetGroups(18)\nFwdTube1a.SetDamageRadiusFactor(0.060000)\nFwdTube1a.SetIconNum(370)\nFwdTube1a.SetIconPositionX(73.000000)\nFwdTube1a.SetIconPositionY(40.000000)\nFwdTube1a.SetIconAboveShip(1)\nFwdTube1a.SetImmediateDelay(0.000000)\nFwdTube1a.SetReloadDelay(40.000000)\nFwdTube1a.SetMaxReady(1)\nFwdTube1aDirection = App.TGPoint3()\nFwdTube1aDirection.SetXYZ(0.000000, 1.000000, 0.000000)\nFwdTube1a.SetDirection(FwdTube1aDirection)\nFwdTube1aRight = App.TGPoint3()\nFwdTube1aRight.SetXYZ(1.000000, 0.000000, 0.000000)\nFwdTube1a.SetRight(FwdTube1aRight)\nApp.g_kModelPropertyManager.RegisterLocalTemplate(FwdTube1a)\n#################################################\nFwdTube1b = App.TorpedoTubeProperty_Create(\"Fwd Tube 1b\")\n\nFwdTube1b.SetMaxCondition(4000.000000)\nFwdTube1b.SetCritical(0)\nFwdTube1b.SetTargetable(1)\nFwdTube1b.SetPrimary(1)\nFwdTube1b.SetPosition(0.000000, 5.700000, -0.450000)\nFwdTube1b.SetPosition2D(55.000000, 18.000000)\nFwdTube1b.SetRepairComplexity(2.000000)\nFwdTube1b.SetDisabledPercentage(0.450000)\nFwdTube1b.SetRadius(0.100000)\nFwdTube1b.SetDumbfire(1)\nFwdTube1b.SetWeaponID(1)\nFwdTube1b.SetGroups(18)\nFwdTube1b.SetDamageRadiusFactor(0.060000)\nFwdTube1b.SetIconNum(370)\nFwdTube1b.SetIconPositionX(73.000000)\nFwdTube1b.SetIconPositionY(40.000000)\nFwdTube1b.SetIconAboveShip(1)\nFwdTube1b.SetImmediateDelay(0.000000)\nFwdTube1b.SetReloadDelay(40.000000)\nFwdTube1b.SetMaxReady(1)\nFwdTube1bDirection = App.TGPoint3()\nFwdTube1bDirection.SetXYZ(0.000000, 1.000000, 0.000000)\nFwdTube1b.SetDirection(FwdTube1bDirection)\nFwdTube1bRight = App.TGPoint3()\nFwdTube1bRight.SetXYZ(-1.000000, 0.000000, 0.000000)\nFwdTube1b.SetRight(FwdTube1bRight)\nApp.g_kModelPropertyManager.RegisterLocalTemplate(FwdTube1b)\n#################################################\nFwdTube1c = App.TorpedoTubeProperty_Create(\"Fwd Tube 1c\")\n\nFwdTube1c.SetMaxCondition(4000.000000)\nFwdTube1c.SetCritical(0)\nFwdTube1c.SetTargetable(1)\nFwdTube1c.SetPrimary(1)\nFwdTube1c.SetPosition(0.000000, 5.700000, -0.450000)\nFwdTube1c.SetPosition2D(55.000000, 18.000000)\nFwdTube1c.SetRepairComplexity(2.000000)\nFwdTube1c.SetDisabledPercentage(0.450000)\nFwdTube1c.SetRadius(0.100000)\nFwdTube1c.SetDumbfire(1)\nFwdTube1c.SetWeaponID(1)\nFwdTube1c.SetGroups(17)\nFwdTube1c.SetDamageRadiusFactor(0.060000)\nFwdTube1c.SetIconNum(370)\nFwdTube1c.SetIconPositionX(73.000000)\nFwdTube1c.SetIconPositionY(40.000000)\nFwdTube1c.SetIconAboveShip(1)\nFwdTube1c.SetImmediateDelay(0.000000)\nFwdTube1c.SetReloadDelay(50.000000)\nFwdTube1c.SetMaxReady(1)\nFwdTube1cDirection = App.TGPoint3()\nFwdTube1cDirection.SetXYZ(0.000000, 1.000000, 0.000000)\nFwdTube1c.SetDirection(FwdTube1cDirection)\nFwdTube1cRight = App.TGPoint3()\nFwdTube1cRight.SetXYZ(0.000000, 0.000000, -1.000000)\nFwdTube1c.SetRight(FwdTube1cRight)\nApp.g_kModelPropertyManager.RegisterLocalTemplate(FwdTube1c)\n#################################################\nFwdTube2a = App.TorpedoTubeProperty_Create(\"Fwd Tube 2a\")\n\nFwdTube2a.SetMaxCondition(4000.000000)\nFwdTube2a.SetCritical(0)\nFwdTube2a.SetTargetable(1)\nFwdTube2a.SetPrimary(1)\nFwdTube2a.SetPosition(0.000000, 5.700000, -0.450000)\nFwdTube2a.SetPosition2D(79.000000, 18.000000)\nFwdTube2a.SetRepairComplexity(2.000000)\nFwdTube2a.SetDisabledPercentage(0.450000)\nFwdTube2a.SetRadius(0.100000)\nFwdTube2a.SetDumbfire(1)\nFwdTube2a.SetWeaponID(1)\nFwdTube2a.SetGroups(18)\nFwdTube2a.SetDamageRadiusFactor(0.060000)\nFwdTube2a.SetIconNum(370)\nFwdTube2a.SetIconPositionX(83.000000)\nFwdTube2a.SetIconPositionY(40.000000)\nFwdTube2a.SetIconAboveShip(1)\nFwdTube2a.SetImmediateDelay(0.000000)\nFwdTube2a.SetReloadDelay(40.000000)\nFwdTube2a.SetMaxReady(1)\nFwdTube2aDirection = App.TGPoint3()\nFwdTube2aDirection.SetXYZ(0.000000, 1.000000, 0.000000)\nFwdTube2a.SetDirection(FwdTube2aDirection)\nFwdTube2aRight = App.TGPoint3()\nFwdTube2aRight.SetXYZ(0.707107, 0.000000, -0.707107)\nFwdTube2a.SetRight(FwdTube2aRight)\nApp.g_kModelPropertyManager.RegisterLocalTemplate(FwdTube2a)\n#################################################\nFwdTube2b = App.TorpedoTubeProperty_Create(\"Fwd Tube 2b\")\n\nFwdTube2b.SetMaxCondition(4000.000000)\nFwdTube2b.SetCritical(0)\nFwdTube2b.SetTargetable(1)\nFwdTube2b.SetPrimary(1)\nFwdTube2b.SetPosition(0.000000, 5.700000, -0.450000)\nFwdTube2b.SetPosition2D(55.000000, 18.000000)\nFwdTube2b.SetRepairComplexity(2.000000)\nFwdTube2b.SetDisabledPercentage(0.450000)\nFwdTube2b.SetRadius(0.100000)\nFwdTube2b.SetDumbfire(1)\nFwdTube2b.SetWeaponID(1)\nFwdTube2b.SetGroups(18)\nFwdTube2b.SetDamageRadiusFactor(0.060000)\nFwdTube2b.SetIconNum(370)\nFwdTube2b.SetIconPositionX(83.000000)\nFwdTube2b.SetIconPositionY(40.000000)\nFwdTube2b.SetIconAboveShip(1)\nFwdTube2b.SetImmediateDelay(0.000000)\nFwdTube2b.SetReloadDelay(40.000000)\nFwdTube2b.SetMaxReady(1)\nFwdTube2bDirection = App.TGPoint3()\nFwdTube2bDirection.SetXYZ(0.000000, 1.000000, 0.000000)\nFwdTube2b.SetDirection(FwdTube2bDirection)\nFwdTube2bRight = App.TGPoint3()\nFwdTube2bRight.SetXYZ(-0.707107, 0.000000, 0.707107)\nFwdTube2b.SetRight(FwdTube2bRight)\nApp.g_kModelPropertyManager.RegisterLocalTemplate(FwdTube2b)\n#################################################\nFwdTube2c = App.TorpedoTubeProperty_Create(\"Fwd Tube 2c\")\n\nFwdTube2c.SetMaxCondition(4000.000000)\nFwdTube2c.SetCritical(0)\nFwdTube2c.SetTargetable(1)\nFwdTube2c.SetPrimary(1)\nFwdTube2c.SetPosition(0.000000, 5.700000, -0.450000)\nFwdTube2c.SetPosition2D(55.000000, 18.000000)\nFwdTube2c.SetRepairComplexity(2.000000)\nFwdTube2c.SetDisabledPercentage(0.450000)\nFwdTube2c.SetRadius(0.100000)\nFwdTube2c.SetDumbfire(1)\nFwdTube2c.SetWeaponID(1)\nFwdTube2c.SetGroups(17)\nFwdTube2c.SetDamageRadiusFactor(0.060000)\nFwdTube2c.SetIconNum(370)\nFwdTube2c.SetIconPositionX(83.000000)\nFwdTube2c.SetIconPositionY(40.000000)\nFwdTube2c.SetIconAboveShip(1)\nFwdTube2c.SetImmediateDelay(0.000000)\nFwdTube2c.SetReloadDelay(50.000000)\nFwdTube2c.SetMaxReady(1)\nFwdTube2cDirection = App.TGPoint3()\nFwdTube2cDirection.SetXYZ(0.000000, 1.000000, 0.000000)\nFwdTube2c.SetDirection(FwdTube2cDirection)\nFwdTube2cRight = App.TGPoint3()\nFwdTube2cRight.SetXYZ(-0.707107, 0.000000, -0.707107)\nFwdTube2c.SetRight(FwdTube2cRight)\nApp.g_kModelPropertyManager.RegisterLocalTemplate(FwdTube2c)\n#################################################\nPortWarp = App.EngineProperty_Create(\"Port Warp\")\n\nPortWarp.SetMaxCondition(8000.000000)\nPortWarp.SetCritical(0)\nPortWarp.SetTargetable(1)\nPortWarp.SetPrimary(1)\nPortWarp.SetPosition(-4.400000, 0.400000, 0.000000)\nPortWarp.SetPosition2D(22.000000, 59.000000)\nPortWarp.SetRepairComplexity(1.000000)\nPortWarp.SetDisabledPercentage(0.250000)\nPortWarp.SetRadius(1.000000)\nPortWarp.SetEngineType(PortWarp.EP_WARP)\nApp.g_kModelPropertyManager.RegisterLocalTemplate(PortWarp)\n#################################################\nStarWarp = App.EngineProperty_Create(\"Star Warp\")\n\nStarWarp.SetMaxCondition(8000.000000)\nStarWarp.SetCritical(0)\nStarWarp.SetTargetable(1)\nStarWarp.SetPrimary(1)\nStarWarp.SetPosition(4.400000, 0.400000, 0.000000)\nStarWarp.SetPosition2D(107.000000, 59.000000)\nStarWarp.SetRepairComplexity(1.000000)\nStarWarp.SetDisabledPercentage(0.250000)\nStarWarp.SetRadius(1.000000)\nStarWarp.SetEngineType(StarWarp.EP_WARP)\nApp.g_kModelPropertyManager.RegisterLocalTemplate(StarWarp)\n#################################################\nAftVentral1 = App.PulseWeaponProperty_Create(\"Aft Ventral 1\")\n\nAftVentral1.SetMaxCondition(7000.000000)\nAftVentral1.SetCritical(0)\nAftVentral1.SetTargetable(1)\nAftVentral1.SetPrimary(1)\nAftVentral1.SetPosition(0.680000, -4.000000, -0.760000)\nAftVentral1.SetPosition2D(52.000000, 95.000000)\nAftVentral1.SetRepairComplexity(2.000000)\nAftVentral1.SetDisabledPercentage(0.250000)\nAftVentral1.SetRadius(0.100000)\nAftVentral1.SetDumbfire(1)\nAftVentral1.SetWeaponID(1)\nAftVentral1.SetGroups(0)\nAftVentral1.SetDamageRadiusFactor(0.060000)\nAftVentral1.SetIconNum(366)\nAftVentral1.SetIconPositionX(65.000000)\nAftVentral1.SetIconPositionY(113.000000)\nAftVentral1.SetIconAboveShip(1)\nAftVentral1.SetFireSound(\"\")\nAftVentral1.SetMaxCharge(3.000000)\nAftVentral1.SetMaxDamage(1.000000)\nAftVentral1.SetMaxDamageDistance(150.000000)\nAftVentral1.SetMinFiringCharge(1.000000)\nAftVentral1.SetNormalDischargeRate(1.000000)\nAftVentral1.SetRechargeRate(0.300000)\nAftVentral1.SetIndicatorIconNum(0)\nAftVentral1.SetIndicatorIconPositionX(26.000000)\nAftVentral1.SetIndicatorIconPositionY(68.000000)\nAftVentral1Forward = App.TGPoint3()\nAftVentral1Forward.SetXYZ(0.270674, -0.902248, -0.335686)\nAftVentral1Up = App.TGPoint3()\nAftVentral1Up.SetXYZ(0.000000, 0.000000, -1.000000)\nAftVentral1.SetOrientation(AftVentral1Forward, AftVentral1Up)\nAftVentral1.SetArcWidthAngles(-0.610865, 0.610865)\nAftVentral1.SetArcHeightAngles(-0.523599, 1.221731)\nAftVentral1.SetCooldownTime(0.100000)\nAftVentral1.SetModuleName(\"Custom.BCSTNG.CWP.Scripts.blackelmwarbirdpulsedisruptor\")\nApp.g_kModelPropertyManager.RegisterLocalTemplate(AftVentral1)\n#################################################\nAftVentral2 = App.PulseWeaponProperty_Create(\"Aft Ventral 2\")\n\nAftVentral2.SetMaxCondition(7000.000000)\nAftVentral2.SetCritical(0)\nAftVentral2.SetTargetable(1)\nAftVentral2.SetPrimary(1)\nAftVentral2.SetPosition(-0.680000, -4.000000, -0.760000)\nAftVentral2.SetPosition2D(76.000000, 95.000000)\nAftVentral2.SetRepairComplexity(2.000000)\nAftVentral2.SetDisabledPercentage(0.250000)\nAftVentral2.SetRadius(0.100000)\nAftVentral2.SetDumbfire(1)\nAftVentral2.SetWeaponID(1)\nAftVentral2.SetGroups(0)\nAftVentral2.SetDamageRadiusFactor(0.060000)\nAftVentral2.SetIconNum(366)\nAftVentral2.SetIconPositionX(91.000000)\nAftVentral2.SetIconPositionY(113.000000)\nAftVentral2.SetIconAboveShip(1)\nAftVentral2.SetFireSound(\"\")\nAftVentral2.SetMaxCharge(3.000000)\nAftVentral2.SetMaxDamage(1.000000)\nAftVentral2.SetMaxDamageDistance(150.000000)\nAftVentral2.SetMinFiringCharge(1.000000)\nAftVentral2.SetNormalDischargeRate(1.000000)\nAftVentral2.SetRechargeRate(0.300000)\nAftVentral2.SetIndicatorIconNum(0)\nAftVentral2.SetIndicatorIconPositionX(26.000000)\nAftVentral2.SetIndicatorIconPositionY(68.000000)\nAftVentral2Forward = App.TGPoint3()\nAftVentral2Forward.SetXYZ(-0.270674, -0.902248, -0.335686)\nAftVentral2Up = App.TGPoint3()\nAftVentral2Up.SetXYZ(0.000000, 0.000000, -1.000000)\nAftVentral2.SetOrientation(AftVentral2Forward, AftVentral2Up)\nAftVentral2.SetArcWidthAngles(-0.610865, 0.610865)\nAftVentral2.SetArcHeightAngles(-0.523599, 1.221731)\nAftVentral2.SetCooldownTime(0.100000)\nAftVentral2.SetModuleName(\"Custom.BCSTNG.CWP.Scripts.blackelmwarbirdpulsedisruptor\")\nApp.g_kModelPropertyManager.RegisterLocalTemplate(AftVentral2)\n#################################################\nAftPort = App.PulseWeaponProperty_Create(\"Aft Port\")\n\nAftPort.SetMaxCondition(7000.000000)\nAftPort.SetCritical(0)\nAftPort.SetTargetable(1)\nAftPort.SetPrimary(1)\nAftPort.SetPosition(-0.220000, -5.740000, 0.140000)\nAftPort.SetPosition2D(59.000000, 100.000000)\nAftPort.SetRepairComplexity(2.000000)\nAftPort.SetDisabledPercentage(0.250000)\nAftPort.SetRadius(0.100000)\nAftPort.SetDumbfire(1)\nAftPort.SetWeaponID(1)\nAftPort.SetGroups(0)\nAftPort.SetDamageRadiusFactor(0.060000)\nAftPort.SetIconNum(366)\nAftPort.SetIconPositionX(74.000000)\nAftPort.SetIconPositionY(118.000000)\nAftPort.SetIconAboveShip(1)\nAftPort.SetFireSound(\"\")\nAftPort.SetMaxCharge(3.000000)\nAftPort.SetMaxDamage(1.000000)\nAftPort.SetMaxDamageDistance(150.000000)\nAftPort.SetMinFiringCharge(1.000000)\nAftPort.SetNormalDischargeRate(1.000000)\nAftPort.SetRechargeRate(0.300000)\nAftPort.SetIndicatorIconNum(0)\nAftPort.SetIndicatorIconPositionX(26.000000)\nAftPort.SetIndicatorIconPositionY(68.000000)\nAftPortForward = App.TGPoint3()\nAftPortForward.SetXYZ(0.000000, -1.000000, 0.000000)\nAftPortUp = App.TGPoint3()\nAftPortUp.SetXYZ(0.000000, 0.000000, 1.000000)\nAftPort.SetOrientation(AftPortForward, AftPortUp)\nAftPort.SetArcWidthAngles(-0.087266, 1.570796)\nAftPort.SetArcHeightAngles(-0.523599, 0.523599)\nAftPort.SetCooldownTime(0.100000)\nAftPort.SetModuleName(\"Custom.BCSTNG.CWP.Scripts.blackelmwarbirdpulsedisruptor\")\nApp.g_kModelPropertyManager.RegisterLocalTemplate(AftPort)\n#################################################\nAftStar = App.PulseWeaponProperty_Create(\"Aft Star\")\n\nAftStar.SetMaxCondition(7000.000000)\nAftStar.SetCritical(0)\nAftStar.SetTargetable(1)\nAftStar.SetPrimary(1)\nAftStar.SetPosition(0.220000, -5.740000, 0.140000)\nAftStar.SetPosition2D(70.000000, 101.000000)\nAftStar.SetRepairComplexity(2.000000)\nAftStar.SetDisabledPercentage(0.250000)\nAftStar.SetRadius(0.100000)\nAftStar.SetDumbfire(1)\nAftStar.SetWeaponID(1)\nAftStar.SetGroups(0)\nAftStar.SetDamageRadiusFactor(0.060000)\nAftStar.SetIconNum(366)\nAftStar.SetIconPositionX(82.000000)\nAftStar.SetIconPositionY(118.000000)\nAftStar.SetIconAboveShip(1)\nAftStar.SetFireSound(\"\")\nAftStar.SetMaxCharge(3.000000)\nAftStar.SetMaxDamage(1.000000)\nAftStar.SetMaxDamageDistance(150.000000)\nAftStar.SetMinFiringCharge(1.000000)\nAftStar.SetNormalDischargeRate(1.000000)\nAftStar.SetRechargeRate(0.300000)\nAftStar.SetIndicatorIconNum(0)\nAftStar.SetIndicatorIconPositionX(26.000000)\nAftStar.SetIndicatorIconPositionY(68.000000)\nAftStarForward = App.TGPoint3()\nAftStarForward.SetXYZ(0.000000, -1.000000, 0.000000)\nAftStarUp = App.TGPoint3()\nAftStarUp.SetXYZ(0.000000, 0.000000, 1.000000)\nAftStar.SetOrientation(AftStarForward, AftStarUp)\nAftStar.SetArcWidthAngles(0.087266, -1.570796)\nAftStar.SetArcHeightAngles(-0.523599, 0.523599)\nAftStar.SetCooldownTime(0.100000)\nAftStar.SetModuleName(\"Custom.BCSTNG.CWP.Scripts.blackelmwarbirdpulsedisruptor\")\nApp.g_kModelPropertyManager.RegisterLocalTemplate(AftStar)\n#################################################\nDisruptorBeam = App.WeaponSystemProperty_Create(\"Disruptor Beam\")\n\nDisruptorBeam.SetMaxCondition(2000.000000)\nDisruptorBeam.SetCritical(0)\nDisruptorBeam.SetTargetable(0)\nDisruptorBeam.SetPrimary(1)\nDisruptorBeam.SetPosition(0.000000, 5.700000, -0.450000)\nDisruptorBeam.SetPosition2D(0.000000, 0.000000)\nDisruptorBeam.SetRepairComplexity(3.000000)\nDisruptorBeam.SetDisabledPercentage(0.500000)\nDisruptorBeam.SetRadius(0.100000)\nDisruptorBeam.SetNormalPowerPerSecond(650.000000)\nDisruptorBeam.SetWeaponSystemType(DisruptorBeam.WST_PHASER)\nDisruptorBeam.SetSingleFire(1)\nDisruptorBeam.SetAimedWeapon(0)\nkFiringChainString = App.TGString()\nkFiringChainString.SetString(\"\")\nDisruptorBeam.SetFiringChainString(kFiringChainString)\nApp.g_kModelPropertyManager.RegisterLocalTemplate(DisruptorBeam)\n#################################################\nFwdBeam1 = App.PhaserProperty_Create(\"Fwd Beam 1\")\n\nFwdBeam1.SetMaxCondition(4000.000000)\nFwdBeam1.SetCritical(0)\nFwdBeam1.SetTargetable(1)\nFwdBeam1.SetPrimary(1)\nFwdBeam1.SetPosition(0.000000, 5.680000, -0.450000)\nFwdBeam1.SetPosition2D(66.000000, 2.000000)\nFwdBeam1.SetRepairComplexity(3.000000)\nFwdBeam1.SetDisabledPercentage(0.500000)\nFwdBeam1.SetRadius(0.100000)\nFwdBeam1.SetDumbfire(0)\nFwdBeam1.SetWeaponID(0)\nFwdBeam1.SetGroups(0)\nFwdBeam1.SetDamageRadiusFactor(0.060000)\nFwdBeam1.SetIconNum(364)\nFwdBeam1.SetIconPositionX(65.000000)\nFwdBeam1.SetIconPositionY(21.000000)\nFwdBeam1.SetIconAboveShip(1)\nFwdBeam1.SetFireSound(\"ZZ_KlingonPhaser\")\nFwdBeam1.SetMaxCharge(0.800000)\nFwdBeam1.SetMaxDamage(1500.000000)\nFwdBeam1.SetMaxDamageDistance(100.000000)\nFwdBeam1.SetMinFiringCharge(0.800000)\nFwdBeam1.SetNormalDischargeRate(1.000000)\nFwdBeam1.SetRechargeRate(0.100000)\nFwdBeam1.SetIndicatorIconNum(510)\nFwdBeam1.SetIndicatorIconPositionX(59.000000)\nFwdBeam1.SetIndicatorIconPositionY(16.000000)\nFwdBeam1Forward = App.TGPoint3()\nFwdBeam1Forward.SetXYZ(0.000000, 1.000000, 0.000000)\nFwdBeam1Up = App.TGPoint3()\nFwdBeam1Up.SetXYZ(0.000000, 0.000000, 1.000000)\nFwdBeam1.SetOrientation(FwdBeam1Forward, FwdBeam1Up)\nFwdBeam1.SetWidth(0.050000)\nFwdBeam1.SetLength(0.100000)\nFwdBeam1.SetArcWidthAngles(-0.523599, 0.523599)\nFwdBeam1.SetArcHeightAngles(-0.523599, 0.523599)\nFwdBeam1.SetPhaserTextureStart(0)\nFwdBeam1.SetPhaserTextureEnd(0)\nFwdBeam1.SetPhaserWidth(0.300000)\nkColor = App.TGColorA()\nkColor.SetRGBA(0.000000, 0.501961, 0.000000, 1.000000)\nFwdBeam1.SetOuterShellColor(kColor)\nkColor.SetRGBA(0.000000, 0.501961, 0.247059, 1.000000)\nFwdBeam1.SetInnerShellColor(kColor)\nkColor.SetRGBA(0.501961, 1.000000, 0.000000, 1.000000)\nFwdBeam1.SetOuterCoreColor(kColor)\nkColor.SetRGBA(0.501961, 1.000000, 0.501961, 1.000000)\nFwdBeam1.SetInnerCoreColor(kColor)\nFwdBeam1.SetNumSides(6)\nFwdBeam1.SetMainRadius(0.350000)\nFwdBeam1.SetTaperRadius(0.025000)\nFwdBeam1.SetCoreScale(0.500000)\nFwdBeam1.SetTaperRatio(0.250000)\nFwdBeam1.SetTaperMinLength(100.000000)\nFwdBeam1.SetTaperMaxLength(100.000000)\nFwdBeam1.SetLengthTextureTilePerUnit(0.500000)\nFwdBeam1.SetPerimeterTile(1.000000)\nFwdBeam1.SetTextureSpeed(2.500000)\nFwdBeam1.SetTextureName(\"data/textures/tactical/CARomulan.tga\")\nApp.g_kModelPropertyManager.RegisterLocalTemplate(FwdBeam1)\n#################################################\nFwdBeam2 = App.PhaserProperty_Create(\"Fwd Beam 2\")\n\nFwdBeam2.SetMaxCondition(4000.000000)\nFwdBeam2.SetCritical(0)\nFwdBeam2.SetTargetable(1)\nFwdBeam2.SetPrimary(1)\nFwdBeam2.SetPosition(0.000000, 5.680000, -0.450000)\nFwdBeam2.SetPosition2D(66.000000, 2.000000)\nFwdBeam2.SetRepairComplexity(3.000000)\nFwdBeam2.SetDisabledPercentage(0.500000)\nFwdBeam2.SetRadius(0.100000)\nFwdBeam2.SetDumbfire(0)\nFwdBeam2.SetWeaponID(0)\nFwdBeam2.SetGroups(0)\nFwdBeam2.SetDamageRadiusFactor(0.060000)\nFwdBeam2.SetIconNum(364)\nFwdBeam2.SetIconPositionX(65.000000)\nFwdBeam2.SetIconPositionY(21.000000)\nFwdBeam2.SetIconAboveShip(1)\nFwdBeam2.SetFireSound(\"ZZ_KlingonPhaser\")\nFwdBeam2.SetMaxCharge(0.800000)\nFwdBeam2.SetMaxDamage(1500.000000)\nFwdBeam2.SetMaxDamageDistance(100.000000)\nFwdBeam2.SetMinFiringCharge(0.800000)\nFwdBeam2.SetNormalDischargeRate(1.000000)\nFwdBeam2.SetRechargeRate(0.100000)\nFwdBeam2.SetIndicatorIconNum(510)\nFwdBeam2.SetIndicatorIconPositionX(59.000000)\nFwdBeam2.SetIndicatorIconPositionY(16.000000)\nFwdBeam2Forward = App.TGPoint3()\nFwdBeam2Forward.SetXYZ(0.000000, 1.000000, 0.000000)\nFwdBeam2Up = App.TGPoint3()\nFwdBeam2Up.SetXYZ(0.000000, 0.000000, 1.000000)\nFwdBeam2.SetOrientation(FwdBeam2Forward, FwdBeam2Up)\nFwdBeam2.SetWidth(0.050000)\nFwdBeam2.SetLength(0.100000)\nFwdBeam2.SetArcWidthAngles(-0.523599, 0.523599)\nFwdBeam2.SetArcHeightAngles(-0.523599, 0.523599)\nFwdBeam2.SetPhaserTextureStart(0)\nFwdBeam2.SetPhaserTextureEnd(0)\nFwdBeam2.SetPhaserWidth(0.300000)\nkColor = App.TGColorA()\nkColor.SetRGBA(0.000000, 0.501961, 0.000000, 1.000000)\nFwdBeam2.SetOuterShellColor(kColor)\nkColor.SetRGBA(0.000000, 0.501961, 0.247059, 1.000000)\nFwdBeam2.SetInnerShellColor(kColor)\nkColor.SetRGBA(0.501961, 1.000000, 0.000000, 1.000000)\nFwdBeam2.SetOuterCoreColor(kColor)\nkColor.SetRGBA(0.501961, 1.000000, 0.501961, 1.000000)\nFwdBeam2.SetInnerCoreColor(kColor)\nFwdBeam2.SetNumSides(6)\nFwdBeam2.SetMainRadius(0.350000)\nFwdBeam2.SetTaperRadius(0.025000)\nFwdBeam2.SetCoreScale(0.500000)\nFwdBeam2.SetTaperRatio(0.250000)\nFwdBeam2.SetTaperMinLength(100.000000)\nFwdBeam2.SetTaperMaxLength(100.000000)\nFwdBeam2.SetLengthTextureTilePerUnit(0.500000)\nFwdBeam2.SetPerimeterTile(1.000000)\nFwdBeam2.SetTextureSpeed(2.500000)\nFwdBeam2.SetTextureName(\"data/textures/tactical/CARomulan.tga\")\nApp.g_kModelPropertyManager.RegisterLocalTemplate(FwdBeam2)\n#################################################\nFwdBeam3 = App.PhaserProperty_Create(\"Fwd Beam 3\")\n\nFwdBeam3.SetMaxCondition(4000.000000)\nFwdBeam3.SetCritical(0)\nFwdBeam3.SetTargetable(1)\nFwdBeam3.SetPrimary(1)\nFwdBeam3.SetPosition(0.000000, 5.680000, -0.450000)\nFwdBeam3.SetPosition2D(66.000000, 2.000000)\nFwdBeam3.SetRepairComplexity(3.000000)\nFwdBeam3.SetDisabledPercentage(0.500000)\nFwdBeam3.SetRadius(0.100000)\nFwdBeam3.SetDumbfire(0)\nFwdBeam3.SetWeaponID(0)\nFwdBeam3.SetGroups(0)\nFwdBeam3.SetDamageRadiusFactor(0.060000)\nFwdBeam3.SetIconNum(364)\nFwdBeam3.SetIconPositionX(65.000000)\nFwdBeam3.SetIconPositionY(21.000000)\nFwdBeam3.SetIconAboveShip(1)\nFwdBeam3.SetFireSound(\"ZZ_KlingonPhaser\")\nFwdBeam3.SetMaxCharge(0.800000)\nFwdBeam3.SetMaxDamage(1500.000000)\nFwdBeam3.SetMaxDamageDistance(100.000000)\nFwdBeam3.SetMinFiringCharge(0.800000)\nFwdBeam3.SetNormalDischargeRate(1.000000)\nFwdBeam3.SetRechargeRate(0.100000)\nFwdBeam3.SetIndicatorIconNum(510)\nFwdBeam3.SetIndicatorIconPositionX(59.000000)\nFwdBeam3.SetIndicatorIconPositionY(16.000000)\nFwdBeam3Forward = App.TGPoint3()\nFwdBeam3Forward.SetXYZ(0.000000, 1.000000, 0.000000)\nFwdBeam3Up = App.TGPoint3()\nFwdBeam3Up.SetXYZ(0.000000, 0.000000, 1.000000)\nFwdBeam3.SetOrientation(FwdBeam3Forward, FwdBeam3Up)\nFwdBeam3.SetWidth(0.050000)\nFwdBeam3.SetLength(0.100000)\nFwdBeam3.SetArcWidthAngles(-0.523599, 0.523599)\nFwdBeam3.SetArcHeightAngles(-0.523599, 0.523599)\nFwdBeam3.SetPhaserTextureStart(0)\nFwdBeam3.SetPhaserTextureEnd(0)\nFwdBeam3.SetPhaserWidth(0.300000)\nkColor = App.TGColorA()\nkColor.SetRGBA(0.000000, 0.501961, 0.000000, 1.000000)\nFwdBeam3.SetOuterShellColor(kColor)\nkColor.SetRGBA(0.000000, 0.501961, 0.247059, 1.000000)\nFwdBeam3.SetInnerShellColor(kColor)\nkColor.SetRGBA(0.501961, 1.000000, 0.000000, 1.000000)\nFwdBeam3.SetOuterCoreColor(kColor)\nkColor.SetRGBA(0.501961, 1.000000, 0.501961, 1.000000)\nFwdBeam3.SetInnerCoreColor(kColor)\nFwdBeam3.SetNumSides(6)\nFwdBeam3.SetMainRadius(0.350000)\nFwdBeam3.SetTaperRadius(0.025000)\nFwdBeam3.SetCoreScale(0.500000)\nFwdBeam3.SetTaperRatio(0.250000)\nFwdBeam3.SetTaperMinLength(100.000000)\nFwdBeam3.SetTaperMaxLength(100.000000)\nFwdBeam3.SetLengthTextureTilePerUnit(0.500000)\nFwdBeam3.SetPerimeterTile(1.000000)\nFwdBeam3.SetTextureSpeed(2.500000)\nFwdBeam3.SetTextureName(\"data/textures/tactical/CARomulan.tga\")\nApp.g_kModelPropertyManager.RegisterLocalTemplate(FwdBeam3)\n#################################################\nFwdTractor = App.TractorBeamProperty_Create(\"Fwd Tractor\")\n\nFwdTractor.SetMaxCondition(2000.000000)\nFwdTractor.SetCritical(0)\nFwdTractor.SetTargetable(1)\nFwdTractor.SetPrimary(1)\nFwdTractor.SetPosition(0.000000, 5.600000, -0.100000)\nFwdTractor.SetPosition2D(0.000000, 0.000000)\nFwdTractor.SetRepairComplexity(3.000000)\nFwdTractor.SetDisabledPercentage(0.500000)\nFwdTractor.SetRadius(0.200000)\nFwdTractor.SetDumbfire(0)\nFwdTractor.SetWeaponID(0)\nFwdTractor.SetGroups(0)\nFwdTractor.SetDamageRadiusFactor(0.100000)\nFwdTractor.SetIconNum(0)\nFwdTractor.SetIconPositionX(0.000000)\nFwdTractor.SetIconPositionY(0.000000)\nFwdTractor.SetIconAboveShip(1)\nFwdTractor.SetFireSound(\"Tractor Beam\")\nFwdTractor.SetMaxCharge(6.000000)\nFwdTractor.SetMaxDamage(500.000000)\nFwdTractor.SetMaxDamageDistance(100.000000)\nFwdTractor.SetMinFiringCharge(3.000000)\nFwdTractor.SetNormalDischargeRate(1.000000)\nFwdTractor.SetRechargeRate(0.300000)\nFwdTractor.SetIndicatorIconNum(0)\nFwdTractor.SetIndicatorIconPositionX(0.000000)\nFwdTractor.SetIndicatorIconPositionY(0.000000)\nFwdTractorForward = App.TGPoint3()\nFwdTractorForward.SetXYZ(0.000000, 1.000000, 0.000000)\nFwdTractorUp = App.TGPoint3()\nFwdTractorUp.SetXYZ(0.000000, 0.000000, 1.000000)\nFwdTractor.SetOrientation(FwdTractorForward, FwdTractorUp)\nFwdTractor.SetArcWidthAngles(-0.349066, 0.349066)\nFwdTractor.SetArcHeightAngles(-0.349066, 0.349066)\nFwdTractor.SetTractorBeamWidth(0.200000)\nFwdTractor.SetTextureStart(0)\nFwdTractor.SetTextureEnd(0)\nFwdTractor.SetTextureName(\"data/Textures/Tactical/TractorBeam.tga\")\nkColor = App.TGColorA()\nkColor.SetRGBA(0.400000, 0.400000, 1.000000, 1.000000)\nFwdTractor.SetOuterShellColor(kColor)\nkColor.SetRGBA(0.400000, 0.400000, 1.000000, 1.000000)\nFwdTractor.SetInnerShellColor(kColor)\nkColor.SetRGBA(0.400000, 0.400000, 1.000000, 1.000000)\nFwdTractor.SetOuterCoreColor(kColor)\nkColor.SetRGBA(0.400000, 0.400000, 1.000000, 1.000000)\nFwdTractor.SetInnerCoreColor(kColor)\nFwdTractor.SetNumSides(12)\nFwdTractor.SetMainRadius(0.075000)\nFwdTractor.SetTaperRadius(0.000000)\nFwdTractor.SetCoreScale(0.450000)\nFwdTractor.SetTaperRatio(0.200000)\nFwdTractor.SetTaperMinLength(1.000000)\nFwdTractor.SetTaperMaxLength(5.000000)\nFwdTractor.SetLengthTextureTilePerUnit(0.250000)\nFwdTractor.SetPerimeterTile(1.000000)\nFwdTractor.SetTextureSpeed(0.200000)\nFwdTractor.SetTextureName(\"data/Textures/Tactical/TractorBeam.tga\")\nApp.g_kModelPropertyManager.RegisterLocalTemplate(FwdTractor)\n#################################################\nAftTractor = App.TractorBeamProperty_Create(\"Aft Tractor\")\n\nAftTractor.SetMaxCondition(2000.000000)\nAftTractor.SetCritical(0)\nAftTractor.SetTargetable(1)\nAftTractor.SetPrimary(1)\nAftTractor.SetPosition(0.000000, -5.950000, 0.000000)\nAftTractor.SetPosition2D(0.000000, 0.000000)\nAftTractor.SetRepairComplexity(3.000000)\nAftTractor.SetDisabledPercentage(0.500000)\nAftTractor.SetRadius(0.200000)\nAftTractor.SetDumbfire(0)\nAftTractor.SetWeaponID(0)\nAftTractor.SetGroups(0)\nAftTractor.SetDamageRadiusFactor(0.100000)\nAftTractor.SetIconNum(0)\nAftTractor.SetIconPositionX(0.000000)\nAftTractor.SetIconPositionY(0.000000)\nAftTractor.SetIconAboveShip(1)\nAftTractor.SetFireSound(\"Tractor Beam\")\nAftTractor.SetMaxCharge(6.000000)\nAftTractor.SetMaxDamage(500.000000)\nAftTractor.SetMaxDamageDistance(100.000000)\nAftTractor.SetMinFiringCharge(3.000000)\nAftTractor.SetNormalDischargeRate(1.000000)\nAftTractor.SetRechargeRate(0.300000)\nAftTractor.SetIndicatorIconNum(0)\nAftTractor.SetIndicatorIconPositionX(0.000000)\nAftTractor.SetIndicatorIconPositionY(0.000000)\nAftTractorForward = App.TGPoint3()\nAftTractorForward.SetXYZ(0.000000, -1.000000, 0.000000)\nAftTractorUp = App.TGPoint3()\nAftTractorUp.SetXYZ(0.000000, 0.000000, 1.000000)\nAftTractor.SetOrientation(AftTractorForward, AftTractorUp)\nAftTractor.SetArcWidthAngles(-0.349066, 0.349066)\nAftTractor.SetArcHeightAngles(-0.349066, 0.349066)\nAftTractor.SetTractorBeamWidth(0.200000)\nAftTractor.SetTextureStart(0)\nAftTractor.SetTextureEnd(0)\nAftTractor.SetTextureName(\"data/Textures/Tactical/TractorBeam.tga\")\nkColor = App.TGColorA()\nkColor.SetRGBA(0.400000, 0.400000, 1.000000, 1.000000)\nAftTractor.SetOuterShellColor(kColor)\nkColor.SetRGBA(0.400000, 0.400000, 1.000000, 1.000000)\nAftTractor.SetInnerShellColor(kColor)\nkColor.SetRGBA(0.400000, 0.400000, 1.000000, 1.000000)\nAftTractor.SetOuterCoreColor(kColor)\nkColor.SetRGBA(0.400000, 0.400000, 1.000000, 1.000000)\nAftTractor.SetInnerCoreColor(kColor)\nAftTractor.SetNumSides(12)\nAftTractor.SetMainRadius(0.075000)\nAftTractor.SetTaperRadius(0.000000)\nAftTractor.SetCoreScale(0.450000)\nAftTractor.SetTaperRatio(0.200000)\nAftTractor.SetTaperMinLength(1.000000)\nAftTractor.SetTaperMaxLength(5.000000)\nAftTractor.SetLengthTextureTilePerUnit(0.250000)\nAftTractor.SetPerimeterTile(1.000000)\nAftTractor.SetTextureSpeed(0.200000)\nAftTractor.SetTextureName(\"data/Textures/Tactical/TractorBeam.tga\")\nApp.g_kModelPropertyManager.RegisterLocalTemplate(AftTractor)\n#################################################\nVentralTractor = App.TractorBeamProperty_Create(\"Ventral Tractor\")\n\nVentralTractor.SetMaxCondition(2000.000000)\nVentralTractor.SetCritical(0)\nVentralTractor.SetTargetable(1)\nVentralTractor.SetPrimary(1)\nVentralTractor.SetPosition(0.000000, 2.600000, -0.450000)\nVentralTractor.SetPosition2D(0.000000, 0.000000)\nVentralTractor.SetRepairComplexity(3.000000)\nVentralTractor.SetDisabledPercentage(0.500000)\nVentralTractor.SetRadius(0.200000)\nVentralTractor.SetDumbfire(0)\nVentralTractor.SetWeaponID(0)\nVentralTractor.SetGroups(0)\nVentralTractor.SetDamageRadiusFactor(0.100000)\nVentralTractor.SetIconNum(0)\nVentralTractor.SetIconPositionX(0.000000)\nVentralTractor.SetIconPositionY(0.000000)\nVentralTractor.SetIconAboveShip(1)\nVentralTractor.SetFireSound(\"Tractor Beam\")\nVentralTractor.SetMaxCharge(6.000000)\nVentralTractor.SetMaxDamage(500.000000)\nVentralTractor.SetMaxDamageDistance(100.000000)\nVentralTractor.SetMinFiringCharge(3.000000)\nVentralTractor.SetNormalDischargeRate(1.000000)\nVentralTractor.SetRechargeRate(0.300000)\nVentralTractor.SetIndicatorIconNum(0)\nVentralTractor.SetIndicatorIconPositionX(0.000000)\nVentralTractor.SetIndicatorIconPositionY(0.000000)\nVentralTractorForward = App.TGPoint3()\nVentralTractorForward.SetXYZ(0.000000, 0.447214, -0.894427)\nVentralTractorUp = App.TGPoint3()\nVentralTractorUp.SetXYZ(0.000000, 1.000000, 0.000000)\nVentralTractor.SetOrientation(VentralTractorForward, VentralTractorUp)\nVentralTractor.SetArcWidthAngles(-0.349066, 0.349066)\nVentralTractor.SetArcHeightAngles(-0.349066, 0.349066)\nVentralTractor.SetTractorBeamWidth(0.200000)\nVentralTractor.SetTextureStart(0)\nVentralTractor.SetTextureEnd(0)\nVentralTractor.SetTextureName(\"data/Textures/Tactical/TractorBeam.tga\")\nkColor = App.TGColorA()\nkColor.SetRGBA(0.400000, 0.400000, 1.000000, 1.000000)\nVentralTractor.SetOuterShellColor(kColor)\nkColor.SetRGBA(0.400000, 0.400000, 1.000000, 1.000000)\nVentralTractor.SetInnerShellColor(kColor)\nkColor.SetRGBA(0.400000, 0.400000, 1.000000, 1.000000)\nVentralTractor.SetOuterCoreColor(kColor)\nkColor.SetRGBA(0.400000, 0.400000, 1.000000, 1.000000)\nVentralTractor.SetInnerCoreColor(kColor)\nVentralTractor.SetNumSides(12)\nVentralTractor.SetMainRadius(0.075000)\nVentralTractor.SetTaperRadius(0.000000)\nVentralTractor.SetCoreScale(0.450000)\nVentralTractor.SetTaperRatio(0.200000)\nVentralTractor.SetTaperMinLength(1.000000)\nVentralTractor.SetTaperMaxLength(5.000000)\nVentralTractor.SetLengthTextureTilePerUnit(0.250000)\nVentralTractor.SetPerimeterTile(1.000000)\nVentralTractor.SetTextureSpeed(0.200000)\nVentralTractor.SetTextureName(\"data/Textures/Tactical/TractorBeam.tga\")\nApp.g_kModelPropertyManager.RegisterLocalTemplate(VentralTractor)\n#################################################\nTractorBeam = App.WeaponSystemProperty_Create(\"Tractor Beam\")\n\nTractorBeam.SetMaxCondition(2000.000000)\nTractorBeam.SetCritical(0)\nTractorBeam.SetTargetable(0)\nTractorBeam.SetPrimary(1)\nTractorBeam.SetPosition(0.000000, 0.000000, 1.000000)\nTractorBeam.SetPosition2D(0.000000, 0.000000)\nTractorBeam.SetRepairComplexity(3.000000)\nTractorBeam.SetDisabledPercentage(0.500000)\nTractorBeam.SetRadius(0.500000)\nTractorBeam.SetNormalPowerPerSecond(500.000000)\nTractorBeam.SetWeaponSystemType(TractorBeam.WST_TRACTOR)\nTractorBeam.SetSingleFire(1)\nTractorBeam.SetAimedWeapon(0)\nkFiringChainString = App.TGString()\nkFiringChainString.SetString(\"\")\nTractorBeam.SetFiringChainString(kFiringChainString)\nApp.g_kModelPropertyManager.RegisterLocalTemplate(TractorBeam)\n#################################################\nLifeSupport = App.HullProperty_Create(\"Life Support\")\n\nLifeSupport.SetMaxCondition(15000.000000)\nLifeSupport.SetCritical(0)\nLifeSupport.SetTargetable(1)\nLifeSupport.SetPrimary(0)\nLifeSupport.SetPosition(0.000000, 0.500000, 0.000000)\nLifeSupport.SetPosition2D(0.000000, 0.000000)\nLifeSupport.SetRepairComplexity(1.000000)\nLifeSupport.SetDisabledPercentage(0.100000)\nLifeSupport.SetRadius(0.250000)\nApp.g_kModelPropertyManager.RegisterLocalTemplate(LifeSupport)\n\n# Property load function.\ndef LoadPropertySet(pObj):\n\t\"Sets up the object's properties.\"\n\tprop = App.g_kModelPropertyManager.FindByName(\"TalshiarWarbird\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"Hull\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"Bridge\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"Quantum Singularity\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"Shield Generator\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"Sensor Array\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"Warp Engines\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"Impulse Engines\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"Port Impulse\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"Star Impulse\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"Cloaking Device\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"Damage Control\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"ViewscreenForward\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"ViewscreenBack\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"ViewscreenLeft\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"ViewscreenRight\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"ViewscreenUp\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"ViewscreenDown\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"FirstPersonCamera\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"Disruptor Cannons\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"Fwd Port\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"Fwd Star\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"Aft Dorsal 1\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"Aft Dorsal 2\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"Fwd Ventral 1\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"Fwd Ventral 2\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"Torpedoes\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"Fwd Tube\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"Fwd Tube 1a\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"Fwd Tube 1b\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"Fwd Tube 2\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"Fwd Tube 2a\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"Fwd Tube 2b\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"Port Warp\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"Star Warp\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"Aft Ventral 1\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"Aft Ventral 2\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"Aft Port\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"Aft Star\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"Disruptor Beam\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"Fwd Beam 1\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"Fwd Beam 2\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"Fwd Beam 3\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"Fwd Tractor\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"Aft Tractor\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"Ventral Tractor\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"Tractor Beam\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\n\tprop = App.g_kModelPropertyManager.FindByName(\"Life Support\", App.TGModelPropertyManager.LOCAL_TEMPLATES)\n\tif (prop != None):\n\t\tpObj.AddToSet(\"Scene Root\", prop)\t\t\n","sub_path":"scripts/ships/Hardpoints/DS9FXWarbird.py","file_name":"DS9FXWarbird.py","file_ext":"py","file_size_in_byte":66128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"36170269","text":"\"\"\"\nExports the Simulation class.\n\"\"\"\n\nfrom os import mkdir, chdir, path\nfrom subprocess import run\nfrom datetime import datetime\n\n\nclass Simulation:\n\t\"\"\"\n\tRun a vapour hydrated brush simulation in a standard manner. Wraps LAMMPS.\n\t\"\"\"\n\n\tdef __init__(self, command: str, dry_run: bool = False, verbose: bool = False, prefix: str = \"\"):\n\t\t\"\"\"\n\t\t:param str command: Command to run to call LAMMPS.\n\t\t:param bool dry_run: Doesn't do anything productive if true.\n\t\t:param str prefix: String to prepend to all print() output.\n\t\t\"\"\"\n\t\tself.command = command\n\t\tself.dry_run = dry_run\n\t\tself.verbose = verbose\n\t\tself.prefix = prefix\n\n\tdef _run_with_vars(self, input_filename: str, log_filename: str, vars: dict = {}) -> None:\n\t\t\"\"\"\n\t\tRun a LAMMPS simulation in a subprocess with variables.\n\t\t:param str input_filename: Filename of the LAMMPS input file\n\t\t:param str log_filename: Filename of the log file to write to\n\t\t:param dict vars: Dictionary describing LAMMPS equal-style variables to set\n\t\t\"\"\"\n\t\twith open(log_filename, 'w') as f:\n\t\t\tcmd = self.command + ' -in {} '.format(input_filename) + ''.join(['-var {} {} '.format(k, v) for k, v in vars.items()])\n\t\t\tif self.verbose:\n\t\t\t\tprint(cmd)\n\t\t\trun(cmd, universal_newlines=True, stdout=f, shell=True)\n\n\tdef _run_in_subdir(self, subdir: str, vars: dict = {}) -> None:\n\t\t\"\"\"\n\t\tRun a simulation in a subdirectory.\n\t\t:param str subdir: Subdirectory to run the simulation in\n\t\t:param dict vars: Dictionary describing LAMMPS equal-style variables to set\n\t\t\"\"\"\n\t\t# Create a subdirectory for every simulation. Skip simulation entirely if dir already exists\n\t\tif not path.isdir(subdir):\n\t\t\tprint(\"{} {}: Simulating {}...\".format(self.prefix, datetime.now(), subdir))\n\t\t\tif not self.dry_run:\n\t\t\t\tmkdir(subdir)\n\t\t\t\tchdir(subdir)\n\t\t\t\tself._run_with_vars('../gcmc.in', 'gcmc.log', vars)\n\t\t\t\tchdir('../')\n\t\t\t\tprint(\"{} {}: Finished {}.\".format(self.prefix, datetime.now(), subdir))\n\t\telse:\n\t\t\tprint(\"{} {}: Found existing subdir {}. Skipping.\".format(self.prefix, datetime.now(), subdir))\n\n\tdef run_gcmc(self, static_vars: dict = {}, dyn_vars: dict = {}) -> None:\n\t\t\"\"\"\n\t\tSimulate a system with the given parameters.\n\t\t:param dict vars: Dictionary describing LAMMPS equal-style variables to set\n\t\t\"\"\"\n\t\tsubdir = 'grid' + ''.join(['_{}{:.4f}'.format(k, float(v)) for k, v in dyn_vars.items()])\n\n\t\t# Combine vars dicts\n\t\tstatic_vars.update(dyn_vars)\n\n\t\tself._run_in_subdir(subdir, static_vars)\n\n\tdef run_equi(self, vars: dict = {}) -> None:\n\t\t\"\"\"\n\t\tRun equilibration.\n\t\t:param dict vars: Dictionary describing LAMMPS equal-style variables to set\n\t\t\"\"\"\n\t\tprint(\"{}: Equilibrating...\".format(datetime.now()))\n\t\tif not self.dry_run:\n\t\t\tself._run_with_vars('equi.in', 'equi.log', vars)\n\t\t\tprint(\"{}: Finished equilibration.\".format(datetime.now()))\n","sub_path":"Simulation.py","file_name":"Simulation.py","file_ext":"py","file_size_in_byte":2789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"25035759","text":"# https://atcoder.jp/contests/abc065/tasks/abc065_b\nn = int(input())\ns = [int(input()) for _ in range(n)]\nt = set()\ni = 1\ncount = 0\n\nwhile(i not in t):\n count += 1\n t.add(i)\n i = s[i-1]\n if i==2:\n print(count)\n break\nelse:\n print(-1)\n","sub_path":"ABC065/b_trained?.py","file_name":"b_trained?.py","file_ext":"py","file_size_in_byte":263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"478474745","text":"from django.core.management.base import BaseCommand, CommandError\nfrom api.models import ActivityPeriods, Members\nfrom services.command.demogenerators import RandomIdGenerator, RandomNameGenerator, RandomTimeZone, RandomDate\nimport random\n\nclass Command(BaseCommand):\n help = \"Updates Database With Dummy Data\"\n\n def __init__(self):\n self.count = 0\n\n\n def handle(self, *args, **options):\n while True:\n\n '''\n Count is used to keep track of how many rows have been inserted in the models\n '''\n if self.count == 10:\n break\n '''\n Generates random datetime stamps and saves it to ActivityPeriods Model.\n '''\n try:\n start, end = RandomDate.gen_datetime()\n activity = ActivityPeriods.objects.create(start_time=start, end_time=end)\n activity.save()\n except Exception as e:\n print(e, 'Error occurred when creating data for activity ')\n\n '''\n Generates random Id, name and timezone stamps and saves it to Members Model.\n '''\n\n try:\n ids = RandomIdGenerator.get_id()\n name = RandomNameGenerator.get_male_name()\n timezone = RandomTimeZone.get_time_zone()\n\n count = ActivityPeriods.objects.count()\n activity_obj1 = ActivityPeriods.objects.get(id=random.randint(1, count))\n activity_obj2 = ActivityPeriods.objects.get(id=random.randint(1, count))\n\n member = Members.objects.create(id=ids, real_name=name, tz=timezone)\n member.activity_periods.add(activity_obj2)\n member.activity_periods.add(activity_obj1)\n member.save()\n except Exception as e:\n print(e, \"Error happened when creating data for Members. Please try again!!!\")\n\n self.count += 1\n","sub_path":"api/management/commands/insertdummydata.py","file_name":"insertdummydata.py","file_ext":"py","file_size_in_byte":1957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"397422799","text":"\"\"\" Permet de jouer et d'entrainer une strategie\n * changer les strategies ajoutees\n * utilisation : python entrainer prefix_fichier_exemple\n par defaut ajoute au fichier d'exemples sil existe deja\n (extension : .exp pour le fichier exemple)\n\"\"\"\n\nfrom soccersimulator import SoccerMatch, show, SoccerTeam,Player,KeyboardStrategy\nfrom strat import *\nimport sys\n\nif __name__==\"__main__\":\n\tprefix = \"tree\"\n\tif len(sys.argv)>1:\n\t\tprefix = sys.argv[1]\n\tstrat_key = KeyboardStrategy()\n\tstrat_key.add(\"a\",StrategyF())\n\tstrat_key.add(\"g\",StrategyG())\n\t\n\tteam_noob = SoccerTeam(\"lobIA\",[Player(\"lobIA\", strat_key)])\n\tteam_bad = SoccerTeam(\"teamTest\",[Player(\"Fonceur\",StrategyP())])\n\t#match = SoccerMatch(team_noob,team_bad,1000)\n\tmatch = SoccerMatch(team_bad,team_noob,1000)\n\t#show(match)\n\tstrat_key.write(prefix+\".exp\",True)","sub_path":"entrainer.py","file_name":"entrainer.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"95611641","text":"# Copyright (c) 2019-2020 Paul Irofti \n# \n# Permission to use, copy, modify, and/or distribute this software for any\n# purpose with or without fee is hereby granted, provided that the above\n# copyright notice and this permission notice appear in all copies.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\nfrom gensr_sspg import gensr_sspg, stepsize_lin\nfrom gensr_proxgd import gensr_proxgd\nfrom gensr_cvx import gensr_cvx\n\nfrom sklearn.datasets import make_sparse_coded_signal\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nfrom timeit import default_timer as timer\n\nimport pickle\n\nfrom reslimit import limit_memory\n\n# SETUP\nn_nonzero_coefs = 3 # sparsity (s)\nn_samples = 1 # number of signals (N)\n\nalpha = 0.5 # l2 weight\nlam = 5 # l1 weight\nmu = 0.05 # learning rate\neps = 1e-6 # precision\n\ndatasize = 2.5 * 1024 * 1024 * 1024 # limit memory usage\n\nprefix = 'sr-atoms'\n\n\n# TEST\nlimit_memory(datasize)\n\ncvx_time, prox_time, sspg_time = [], [], []\natoms = range(5, 130, 5)\n# atoms = range(20, 500, 20)\nfname = '{0}-{1}-{2}-{3}'.format(prefix, atoms.start, atoms.stop, atoms.step)\nfor n_components in atoms:\n print(\"----------\")\n print(\"atoms\", n_components)\n n_features = n_components * 4\n # Generate sparse signals using a dictionary\n sample, dictionary, codes = make_sparse_coded_signal(\n n_samples=n_samples,\n n_components=n_components,\n n_features=n_features,\n n_nonzero_coefs=n_nonzero_coefs,\n random_state=0)\n Delta = np.random.standard_normal((n_features, n_components))\n\n start = timer()\n cvx_x = gensr_cvx(sample, dictionary, Delta, alpha, lam)\n end = timer()\n cvx_time.append(end-start)\n print(\"CVX time: \", end - start)\n\n x0 = np.ones(dictionary.shape[1])\n start = timer()\n prox_x, _, prox_errs = gensr_proxgd(sample, dictionary, Delta, alpha, lam,\n x0, eps, cvx_x)\n end = timer()\n prox_time.append(end-start)\n print(\"Prox time: \", end - start)\n # print(\"Prox: Sparsity\", np.count_nonzero(Delta@prox_x),\n # \"solution\", Delta@prox_x)\n\n start = timer()\n sspg_x, _, _, sspg_errs = gensr_sspg(sample, dictionary, Delta, alpha, lam,\n None, stepsize_lin, eps, cvx_x)\n end = timer()\n sspg_time.append(end-start)\n print(\"SSPG time: \", end - start)\n # print(\"SSPG: Sparsity\", np.count_nonzero(Delta@sspg_x),\n # \"solution\", Delta@sspg_x)\n\n\nwith open('{0}.dat'.format(fname), 'wb') as fp:\n pickle.dump(cvx_time, fp)\n pickle.dump(prox_time, fp)\n pickle.dump(sspg_time, fp)\n\nplt.plot(atoms, cvx_time, 'b', label='cvx')\nplt.plot(atoms, prox_time, 'r', label='prox')\nplt.plot(atoms, sspg_time, 'g', label='sspg')\nplt.xlabel('atoms')\nplt.ylabel('time (s)')\nplt.legend()\nplt.savefig('{0}.pdf'.format(fname))\nplt.show()\n\n","sub_path":"test_gensr.py","file_name":"test_gensr.py","file_ext":"py","file_size_in_byte":3336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"195888424","text":"import numpy as np\r\nfrom Funkcja import Funkcja\r\n\r\nclass funkcjaLiniowa(Funkcja):\r\n def __init__(self, a, b):\r\n self.a = a\r\n self.b = b\r\n self.x = []\r\n self.y = []\r\n self.step = 0.0001\r\n self.x_min = -10\r\n self.x_max = 10\r\n self.type = \"liniowa\"\r\n self.info = f\"f(x) = {self.a}*x + {self.b}\"\r\n\r\n def set_x_range(self, x_min, x_max):\r\n self.x_min = x_min\r\n self.x_max = x_max\r\n\r\n def set_step(self, step):\r\n self.step = step\r\n\r\n def calculate(self):\r\n self.x.clear() \r\n self.y.clear()\r\n self.x = list(np.arange(self.x_min, self.x_max, self.step))\r\n self.y = [self.a*x+self.b for x in self.x] \r\n\r\n def show(self):\r\n print(\"a: \", self.a)\r\n print(\"b: \", self.b)\r\n\r\n @classmethod\r\n def create_function(cls, **kwargs):\r\n if kwargs['a']:\r\n a = int(kwargs['a'])\r\n b = int(kwargs['b'])\r\n return funkcjaLiniowa(a, b)\r\n else:\r\n raise Exception\r\n (\"Nalezy podac parametry a i b funkcji liniowej\")\r\n","sub_path":"piate zajecia/funkcjaLiniowa.py","file_name":"funkcjaLiniowa.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"395453439","text":"import string\nlista = string.ascii_uppercase\n\ndef szyfruj(tekst, kod):\n szyfr = \"\"\n kod = kod%26\n\n for i in tekst:\n if str(i).upper() not in lista:\n szyfr = szyfr + i\n else:\n if str(i).isupper():\n n = kod + ord(i)\n if n > 90: n -= 26\n szyfr = szyfr + chr(n)\n else:\n n = kod + ord(str(i).upper())\n if n > 90: n -= 26\n szyfr = szyfr + str(chr(n)).lower()\n\n return szyfr\n\ndef deszyfr(tekst, kod):\n deszyfr = \"\"\n kod = kod % 26\n\n for i in tekst:\n if str(i).upper() not in lista:\n deszyfr = deszyfr + i\n else:\n if str(i).isupper():\n n = ord(i) - kod\n if n < 65: n += 26\n deszyfr = deszyfr + chr(n)\n else:\n n = ord(str(i).upper()) - kod\n if n < 65: n += 26\n deszyfr = deszyfr + str(chr(n)).lower()\n\n return deszyfr","sub_path":"LISTA6/szyfr_cezara.py","file_name":"szyfr_cezara.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"306440336","text":"N = int(input())\nrows = [i for i in range(N)]\ncolumns = [i for i in range(N)]\ntransposed = False\n\nQ = int(input())\nfor _ in range(Q):\n q = list(map(int,input().split()))\n\n if q[0] == 3:\n transposed = not transposed\n else:\n A, B = q[1]-1, q[2]-1\n if q[0] == 1:\n if transposed:\n columns[A], columns[B] = columns[B], columns[A]\n else:\n rows[A], rows[B] = rows[B], rows[A]\n elif q[0] == 2:\n if transposed:\n rows[A], rows[B] = rows[B], rows[A]\n else:\n columns[A], columns[B] = columns[B], columns[A]\n elif q[0] == 4:\n if transposed:\n A, B = B, A\n r,c = rows[A], columns[B]\n\n print(N*r+c)","sub_path":"atcoder/2020/Other/0523_PAST/I.py","file_name":"I.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"316100618","text":"import numpy as np\nimport tvm\nfrom tvm.contrib import graph_runtime\nimport topi.testing\nimport nnvm.symbol as sym\nimport nnvm.compiler\nfrom nnvm.testing.config import ctx_list\nfrom test_top_level1 import helper\n\ndef check_map(symfunc, np_func, np_backward=None):\n x = sym.Variable(\"x\")\n y = symfunc(x)\n dtype = \"float32\"\n dshape = (1, 3, 32, 32)\n inputs = [('x', dshape, x)]\n helper(y, inputs, dtype, lambda x: np_func(x), np_backward)\n\n\ndef test_floor():\n check_map(sym.floor, np.floor)\n\ndef test_ceil():\n check_map(sym.ceil, np.ceil)\n\ndef test_trunc():\n check_map(sym.trunc, np.trunc)\n\ndef test_round():\n check_map(sym.round, np.round)\n\n\nif __name__ == \"__main__\":\n test_floor()\n test_ceil()\n test_round()\n test_trunc()\n","sub_path":"3rdparty/tvm/nnvm/tests/python/compiler/test_top_level3.py","file_name":"test_top_level3.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"2435864","text":"import zstackwoodpecker.test_state as ts_header\nimport os\nTestAction = ts_header.TestAction\ndef path():\n\n return dict(initial_formation=\"template5\", path_list=[\n\t\t[TestAction.create_vm, 'vm1', 'flag=sblk'],\n\t\t[TestAction.create_volume, 'volume1', 'flag=ceph,scsi'],\n\t\t[TestAction.attach_volume, 'vm1', 'volume1'],\n\t\t[TestAction.create_volume, 'volume2', 'flag=sblk,scsi'],\n\t\t[TestAction.attach_volume, 'vm1', 'volume2'],\n\t\t[TestAction.create_volume, 'volume3', 'flag=ceph,scsi'],\n\t\t[TestAction.attach_volume, 'vm1', 'volume3'],\n\t\t[TestAction.clone_vm, 'vm1', 'vm2', 'full'],\n\t\t[TestAction.create_vm_snapshot, 'vm2', 'vm2-snapshot1'],\n\t\t[TestAction.reboot_vm, 'vm2'],\n\t\t[TestAction.clone_vm, 'vm1', 'vm3', 'full'],\n\t\t[TestAction.create_vm_snapshot, 'vm1', 'vm1-snapshot5'],\n\t\t[TestAction.stop_vm, 'vm2'],\n\t\t[TestAction.use_vm_snapshot, 'vm2-snapshot1'],\n\t\t[TestAction.start_vm, 'vm2'],\n])\n\n\n\n'''\nThe final status:\nRunning:['vm1', 'vm3', 'vm2']\nStopped:[]\nEnadbled:['vm2-snapshot1', 'volume4-snapshot1', 'volume5-snapshot1', 'volume6-snapshot1', 'vm1-snapshot5', 'volume1-snapshot5', 'volume2-snapshot5', 'volume3-snapshot5']\nattached:['volume1', 'volume2', 'volume3', 'volume4', 'volume5', 'volume6', 'volume7', 'volume8', 'volume9']\nDetached:[]\nDeleted:[]\nExpunged:[]\nHa:[]\nGroup:\n\tvm_snap2:['vm1-snapshot5', 'volume1-snapshot5', 'volume2-snapshot5', 'volume3-snapshot5']---vm1volume1_volume2_volume3\n\tvm_snap1:['vm2-snapshot1', 'volume4-snapshot1', 'volume5-snapshot1', 'volume6-snapshot1']---vm2volume4_volume5_volume6\n'''","sub_path":"integrationtest/vm/multihosts/vm_snapshots/paths/sc_path42.py","file_name":"sc_path42.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"371307837","text":"#The prime factors of 13195 are 5, 7, 13 and 29.\n\n#What is the largest prime factor of the number 600851475143 ?\n\na = []\n\ndef getPrimeFactors(num):\n d = 2\n while num > 1:\n while num % d == 0:\n a.append(d)\n num /= d\n d += 1\n if d*d > num:\n if num > 1: a.append(num)\n break\n \n\ngetPrimeFactors(13195)\ngetPrimeFactors(600851475143)\n\n\nprint (max(a))","sub_path":"Problems/problem-3.py","file_name":"problem-3.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"364335057","text":"# Задача 7. Вариант 28.\n# 1-50. Разработайте систему начисления очков для задачи 6, в соответствии с которой игрок получал бы большее количество баллов за меньшее количество попыток.\n\n# Cherniy F. Y.\n# 28.03.2016\n\nimport random\n\nprint(\"Компьютер загадал название одного из шести континентов Земли, а Вы должны его угадать.\\n\")\n\ncontinents = ('Евразия','Африка','Северная Америка','Южная Америка','Австралия','Антарктида')\ncontinent = random.randint(0,5)\nx = 0\ni = 0\nscore = 0\n\n#print (continents[0]\\n,continents[1]\\n,continents[2]\\n,continents[3]\\n,continents[4]\\n,continents[5])\n\nwhile(x != 6):\n\tprint(continents[x])\n\tx += 1\n\nanswer = input(\"\\nВведите название континента: \")\n\nwhile(answer != continents[continent]):\n print(\"Неверно, попробуйте ещё раз.\")\n answer = input(\"\\nВведите название континента: \")\n i += 1\n\nif i == 0:\n\tscore = 10\n\t\nelif 0[0-9A-Za-z_\\-]+)/(?P[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',\r\n views.activate, name='activate'),\r\n\r\n url(r'(?P.*)/$', views.category),\r\n \r\n\r\n \r\n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\r\n","sub_path":"findr/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"571653336","text":"import nltk\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer\n\nnltk.download('vader_lexicon')\nvader = SentimentIntensityAnalyzer()\nvader.lexicon.update({\n 'moon': 5,\n 'rocket': 5,\n 'skyrocket': 5,\n 'bullish': 5,\n 'bearish': -5,\n 'purchased': 2,\n 'bought': 2,\n 'buy': 2,\n 'sell': -2,\n 'sold': -2,\n 'buying': 2,\n 'selling': -2,\n 'purchasing': 2,\n 'HODL': 1,\n 'HODLing': 1,\n 'HODLING': 1,\n 'bull': 5,\n 'bear': 5,\n 'crushes': 5,\n 'beats': 3,\n 'misses': -3,\n 'trouble': -5,\n 'falls': -4,\n 'crashes': -5,\n 'inflationary': -5,\n 'inflation': -5,\n 'launch': 4,\n 'launched': 4,\n 'scarcity': -3,\n 'scarce': -3,\n 'fall': -4,\n 'rise': 4,\n 'rising': 4,\n 'falling': -5,\n 'bubble': -5,\n 'plunge': -5,\n 'plunging': -5,\n 'surge': 4,\n \"ABLE\": 5,\n \"ABUNDANCE\": 5,\n \"ABUNDANT\": 5,\n \"ACCLAIMED\": 5,\n \"ACCOMPLISH\": 5,\n \"ACCOMPLISHED\": 5,\n \"ACCOMPLISHES\": 5,\n \"ACCOMPLISHING\": 5,\n \"ACCOMPLISHMENT\": 5,\n \"ACCOMPLISHMENTS\": 5,\n \"ACHIEVE\": 5,\n \"ACHIEVED\": 5,\n \"ACHIEVEMENT\": 5,\n \"ACHIEVEMENTS\": 5,\n \"ACHIEVES\": 5,\n \"ACHIEVING\": 5,\n \"ADEQUATELY\": 5,\n \"ADVANCEMENT\": 5,\n \"ADVANCEMENTS\": 5,\n \"ADVANCES\": 5,\n \"ADVANCING\": 5,\n \"ADVANTAGE\": 5,\n \"ADVANTAGED\": 5,\n \"ADVANTAGEOUS\": 5,\n \"ADVANTAGEOUSLY\": 5,\n \"ADVANTAGES\": 5,\n \"ALLIANCE\": 5,\n \"ALLIANCES\": 5,\n \"ASSURE\": 5,\n \"ASSURED\": 5,\n \"ASSURES\": 5,\n \"ASSURING\": 5,\n \"ATTAIN\": 5,\n \"ATTAINED\": 5,\n \"ATTAINING\": 5,\n \"ATTAINMENT\": 5,\n \"ATTAINMENTS\": 5,\n \"ATTAINS\": 5,\n \"ATTRACTIVE\": 5,\n \"ATTRACTIVENESS\": 5,\n \"BEAUTIFUL\": 5,\n \"BEAUTIFULLY\": 5,\n \"BENEFICIAL\": 5,\n \"BENEFICIALLY\": 5,\n \"BENEFIT\": 5,\n \"BENEFITED\": 5,\n \"BENEFITING\": 5,\n \"BENEFITTED\": 5,\n \"BENEFITTING\": 5,\n \"BEST\": 5,\n \"BETTER\": 5,\n \"BOLSTERED\": 5,\n \"BOLSTERING\": 5,\n \"BOLSTERS\": 5,\n \"BOOM\": 5,\n \"BOOMING\": 5,\n \"BOOST\": 5,\n \"BOOSTED\": 5,\n \"BREAKTHROUGH\": 5,\n \"BREAKTHROUGHS\": 5,\n \"BRILLIANT\": 5,\n \"CHARITABLE\": 5,\n \"COLLABORATE\": 5,\n \"COLLABORATED\": 5,\n \"COLLABORATES\": 5,\n \"COLLABORATING\": 5,\n \"COLLABORATION\": 5,\n \"COLLABORATIONS\": 5,\n \"COLLABORATIVE\": 5,\n \"COLLABORATOR\": 5,\n \"COLLABORATORS\": 5,\n \"COMPLIMENT\": 5,\n \"COMPLIMENTARY\": 5,\n \"COMPLIMENTED\": 5,\n \"COMPLIMENTING\": 5,\n \"COMPLIMENTS\": 5,\n \"CONCLUSIVE\": 5,\n \"CONCLUSIVELY\": 5,\n \"CONDUCIVE\": 5,\n \"CONFIDENT\": 5,\n \"CONSTRUCTIVE\": 5,\n \"CONSTRUCTIVELY\": 5,\n \"COURTEOUS\": 5,\n \"CREATIVE\": 5,\n \"CREATIVELY\": 5,\n \"CREATIVENESS\": 5,\n \"CREATIVITY\": 5,\n \"DELIGHT\": 5,\n \"DELIGHTED\": 5,\n \"DELIGHTFUL\": 5,\n \"DELIGHTFULLY\": 5,\n \"DELIGHTING\": 5,\n \"DELIGHTS\": 5,\n \"DEPENDABILITY\": 5,\n \"DEPENDABLE\": 5,\n \"DESIRABLE\": 5,\n \"DESIRED\": 5,\n \"DESPITE\": 5,\n \"DESTINED\": 5,\n \"DILIGENT\": 5,\n \"DILIGENTLY\": 5,\n \"DISTINCTION\": 5,\n \"DISTINCTIONS\": 5,\n \"DISTINCTIVE\": 5,\n \"DISTINCTIVELY\": 5,\n \"DISTINCTIVENESS\": 5,\n \"DREAM\": 5,\n \"EASIER\": 5,\n \"EASILY\": 5,\n \"EASY\": 5,\n \"EFFECTIVE\": 5,\n \"EFFICIENCIES\": 5,\n \"EFFICIENCY\": 5,\n \"EFFICIENT\": 5,\n \"EFFICIENTLY\": 5,\n \"EMPOWER\": 5,\n \"EMPOWERED\": 5,\n \"EMPOWERING\": 5,\n \"EMPOWERS\": 5,\n \"ENABLE\": 5,\n \"ENABLED\": 5,\n \"ENABLES\": 5,\n \"ENABLING\": 5,\n \"ENCOURAGED\": 5,\n \"ENCOURAGEMENT\": 5,\n \"ENCOURAGES\": 5,\n \"ENCOURAGING\": 5,\n \"ENHANCE\": 5,\n \"ENHANCED\": 5,\n \"ENHANCEMENT\": 5,\n \"ENHANCEMENTS\": 5,\n \"ENHANCES\": 5,\n \"ENHANCING\": 5,\n \"ENJOY\": 5,\n \"ENJOYABLE\": 5,\n \"ENJOYABLY\": 5,\n \"ENJOYED\": 5,\n \"ENJOYING\": 5,\n \"ENJOYMENT\": 5,\n \"ENJOYS\": 5,\n \"ENTHUSIASM\": 5,\n \"ENTHUSIASTIC\": 5,\n \"ENTHUSIASTICALLY\": 5,\n \"EXCELLENCE\": 5,\n \"EXCELLENT\": 5,\n \"EXCELLING\": 5,\n \"EXCELS\": 5,\n \"EXCEPTIONAL\": 5,\n \"EXCEPTIONALLY\": 5,\n \"EXCITED\": 5,\n \"EXCITEMENT\": 5,\n \"EXCITING\": 5,\n \"EXCLUSIVE\": 5,\n \"EXCLUSIVELY\": 5,\n \"EXCLUSIVENESS\": 5,\n \"EXCLUSIVES\": 5,\n \"EXCLUSIVITY\": 5,\n \"EXEMPLARY\": 5,\n \"FANTASTIC\": 5,\n \"FAVORABLE\": 5,\n \"FAVORABLY\": 5,\n \"FAVORED\": 5,\n \"FAVORING\": 5,\n \"FAVORITE\": 5,\n \"FAVORITES\": 5,\n \"FRIENDLY\": 5,\n \"GAIN\": 5,\n \"GAINED\": 5,\n \"GAINING\": 5,\n \"GAINS\": 5,\n \"GOOD\": 5,\n \"GREAT\": 5,\n \"GREATER\": 5,\n \"GREATEST\": 5,\n \"GREATLY\": 5,\n \"GREATNESS\": 5,\n \"HAPPIEST\": 5,\n \"HAPPILY\": 5,\n \"HAPPINESS\": 5,\n \"HAPPY\": 5,\n \"HIGHEST\": 5,\n \"HONOR\": 5,\n \"HONORABLE\": 5,\n \"HONORED\": 5,\n \"HONORING\": 5,\n \"HONORS\": 5,\n \"IDEAL\": 5,\n \"IMPRESS\": 5,\n \"IMPRESSED\": 5,\n \"IMPRESSES\": 5,\n \"IMPRESSING\": 5,\n \"IMPRESSIVE\": 5,\n \"IMPRESSIVELY\": 5,\n \"IMPROVE\": 5,\n \"IMPROVED\": 5,\n \"IMPROVEMENT\": 5,\n \"IMPROVEMENTS\": 5,\n \"IMPROVES\": 5,\n \"IMPROVING\": 5,\n \"INCREDIBLE\": 5,\n \"INCREDIBLY\": 5,\n \"INFLUENTIAL\": 5,\n \"INFORMATIVE\": 5,\n \"INGENUITY\": 5,\n \"INNOVATE\": 5,\n \"INNOVATED\": 5,\n \"INNOVATES\": 5,\n \"INNOVATING\": 5,\n \"INNOVATION\": 5,\n \"INNOVATIONS\": 5,\n \"INNOVATIVE\": 5,\n \"INNOVATIVENESS\": 5,\n \"INNOVATOR\": 5,\n \"INNOVATORS\": 5,\n \"INSIGHTFUL\": 5,\n \"INSPIRATION\": 5,\n \"INSPIRATIONAL\": 5,\n \"INTEGRITY\": 5,\n \"INVENT\": 5,\n \"INVENTED\": 5,\n \"INVENTING\": 5,\n \"INVENTION\": 5,\n \"INVENTIONS\": 5,\n \"INVENTIVE\": 5,\n \"INVENTIVENESS\": 5,\n \"INVENTOR\": 5,\n \"INVENTORS\": 5,\n \"LEADERSHIP\": 5,\n \"LEADING\": 5,\n \"LOYAL\": 5,\n \"LUCRATIVE\": 5,\n \"MERITORIOUS\": 5,\n \"OPPORTUNITIES\": 5,\n \"OPPORTUNITY\": 5,\n \"OPTIMISTIC\": 5,\n \"OUTPERFORM\": 5,\n \"OUTPERFORMED\": 5,\n \"OUTPERFORMING\": 5,\n \"OUTPERFORMS\": 5,\n \"PERFECT\": 5,\n \"PERFECTED\": 5,\n \"PERFECTLY\": 5,\n \"PERFECTS\": 5,\n \"PLEASANT\": 5,\n \"PLEASANTLY\": 5,\n \"PLEASED\": 5,\n \"PLEASURE\": 5,\n \"PLENTIFUL\": 5,\n \"POPULAR\": 5,\n \"POPULARITY\": 5,\n \"POSITIVELY\": 5,\n \"PREEMINENCE\": 5,\n \"PREEMINENT\": 5,\n \"PREMIER\": 5,\n \"PREMIERE\": 5,\n \"PRESTIGE\": 5,\n \"PRESTIGIOUS\": 5,\n \"PROACTIVE\": 5,\n \"PROACTIVELY\": 5,\n \"PROFICIENCY\": 5,\n \"PROFICIENT\": 5,\n \"PROFICIENTLY\": 5,\n \"PROFITABILITY\": 5,\n \"PROFITABLE\": 5,\n \"PROFITABLY\": 5,\n \"PROGRESS\": 5,\n \"PROGRESSED\": 5,\n \"PROGRESSES\": 5,\n \"PROGRESSING\": 5,\n \"PROSPERED\": 5,\n \"PROSPERING\": 5,\n \"PROSPERITY\": 5,\n \"PROSPEROUS\": 5,\n \"PROSPERS\": 5,\n \"REBOUND\": 5,\n \"REBOUNDED\": 5,\n \"REBOUNDING\": 5,\n \"RECEPTIVE\": 5,\n \"REGAIN\": 5,\n \"REGAINED\": 5,\n \"REGAINING\": 5,\n \"RESOLVE\": 5,\n \"REVOLUTIONIZE\": 5,\n \"REVOLUTIONIZED\": 5,\n \"REVOLUTIONIZES\": 5,\n \"REVOLUTIONIZING\": 5,\n \"REWARD\": 5,\n \"REWARDED\": 5,\n \"REWARDING\": 5,\n \"REWARDS\": 5,\n \"SATISFACTION\": 5,\n \"SATISFACTORILY\": 5,\n \"SATISFACTORY\": 5,\n \"SATISFIED\": 5,\n \"SATISFIES\": 5,\n \"SATISFY\": 5,\n \"SATISFYING\": 5,\n \"SMOOTH\": 5,\n \"SMOOTHING\": 5,\n \"SMOOTHLY\": 5,\n \"SMOOTHS\": 5,\n \"SOLVES\": 5,\n \"SOLVING\": 5,\n \"SPECTACULAR\": 5,\n \"SPECTACULARLY\": 5,\n \"STABILITY\": 5,\n \"STABILIZATION\": 5,\n \"STABILIZATIONS\": 5,\n \"STABILIZE\": 5,\n \"STABILIZED\": 5,\n \"STABILIZES\": 5,\n \"STABILIZING\": 5,\n \"STABLE\": 5,\n \"STRENGTH\": 5,\n \"STRENGTHEN\": 5,\n \"STRENGTHENED\": 5,\n \"STRENGTHENING\": 5,\n \"STRENGTHENS\": 5,\n \"STRENGTHS\": 5,\n \"STRONG\": 5,\n \"STRONGER\": 5,\n \"STRONGEST\": 5,\n \"SUCCEED\": 5,\n \"SUCCEEDED\": 5,\n \"SUCCEEDING\": 5,\n \"SUCCEEDS\": 5,\n \"SUCCESS\": 5,\n \"SUCCESSES\": 5,\n \"SUCCESSFUL\": 5,\n \"SUCCESSFULLY\": 5,\n \"SUPERIOR\": 5,\n \"SURPASS\": 5,\n \"SURPASSED\": 5,\n \"SURPASSES\": 5,\n \"SURPASSING\": 5,\n \"TRANSPARENCY\": 5,\n \"TREMENDOUS\": 5,\n \"TREMENDOUSLY\": 5,\n \"UNMATCHED\": 5,\n \"UNPARALLELED\": 5,\n \"UNSURPASSED\": 5,\n \"UPTURN\": 5,\n \"UPTURNS\": 5,\n \"VALUABLE\": 5,\n \"VERSATILE\": 5,\n \"VERSATILITY\": 5,\n \"VIBRANCY\": 5,\n \"VIBRANT\": 5,\n \"WIN\": 5,\n \"WINNER\": 5,\n \"WINNERS\": 5,\n \"WINNING\": 5,\n \"WORTHY\": 5,\n \"PROFIT\": 5,\n \"buy\": 5,\n \"buying\": 5,\n \"buys\": 5,\n \"bought\": 5,\n \"create\": 5,\n \"creates\": 5,\n \"created\": 5,\n \"creating\": 5,\n \"value\": 5,\n \"ABANDON\": -5,\n \"ABANDONED\": -5,\n \"ABANDONING\": -5,\n \"ABANDONMENT\": -5,\n \"ABANDONMENTS\": -5,\n \"ABANDONS\": -5,\n \"ABDICATED\": -5,\n \"ABDICATES\": -5,\n \"ABDICATING\": -5,\n \"ABDICATION\": -5,\n \"ABDICATIONS\": -5,\n \"ABERRANT\": -5,\n \"ABERRATION\": -5,\n \"ABERRATIONAL\": -5,\n \"ABERRATIONS\": -5,\n \"ABETTING\": -5,\n \"ABNORMAL\": -5,\n \"ABNORMALITIES\": -5,\n \"ABNORMALITY\": -5,\n \"ABNORMALLY\": -5,\n \"ABOLISH\": -5,\n \"ABOLISHED\": -5,\n \"ABOLISHES\": -5,\n \"ABOLISHING\": -5,\n \"ABROGATE\": -5,\n \"ABROGATED\": -5,\n \"ABROGATES\": -5,\n \"ABROGATING\": -5,\n \"ABROGATION\": -5,\n \"ABROGATIONS\": -5,\n \"ABRUPT\": -5,\n \"ABRUPTLY\": -5,\n \"ABRUPTNESS\": -5,\n \"ABSENCE\": -5,\n \"ABSENCES\": -5,\n \"ABSENTEEISM\": -5,\n \"ABUSE\": -5,\n \"ABUSED\": -5,\n \"ABUSES\": -5,\n \"ABUSING\": -5,\n \"ABUSIVE\": -5,\n \"ABUSIVELY\": -5,\n \"ABUSIVENESS\": -5,\n \"ACCIDENT\": -5,\n \"ACCIDENTAL\": -5,\n \"ACCIDENTALLY\": -5,\n \"ACCIDENTS\": -5,\n \"ACCUSATION\": -5,\n \"ACCUSATIONS\": -5,\n \"ACCUSE\": -5,\n \"ACCUSED\": -5,\n \"ACCUSES\": -5,\n \"ACCUSING\": -5,\n \"ACQUIESCE\": -5,\n \"ACQUIESCED\": -5,\n \"ACQUIESCES\": -5,\n \"ACQUIESCING\": -5,\n \"ACQUIT\": -5,\n \"ACQUITS\": -5,\n \"ACQUITTAL\": -5,\n \"ACQUITTALS\": -5,\n \"ACQUITTED\": -5,\n \"ACQUITTING\": -5,\n \"ADULTERATE\": -5,\n \"ADULTERATED\": -5,\n \"ADULTERATING\": -5,\n \"ADULTERATION\": -5,\n \"ADULTERATIONS\": -5,\n \"ADVERSARIAL\": -5,\n \"ADVERSARIES\": -5,\n \"ADVERSARY\": -5,\n \"ADVERSE\": -5,\n \"ADVERSELY\": -5,\n \"ADVERSITIES\": -5,\n \"ADVERSITY\": -5,\n \"AFTERMATH\": -5,\n \"AFTERMATHS\": -5,\n \"AGAINST\": -5,\n \"AGGRAVATE\": -5,\n \"AGGRAVATED\": -5,\n \"AGGRAVATES\": -5,\n \"AGGRAVATING\": -5,\n \"AGGRAVATION\": -5,\n \"AGGRAVATIONS\": -5,\n \"ALERTED\": -5,\n \"ALERTING\": -5,\n \"ALIENATE\": -5,\n \"ALIENATED\": -5,\n \"ALIENATES\": -5,\n \"ALIENATING\": -5,\n \"ALIENATION\": -5,\n \"ALIENATIONS\": -5,\n \"ANNOY\": -5,\n \"ANNOYANCE\": -5,\n \"ANNOYANCES\": -5,\n \"ANNOYED\": -5,\n \"ANNOYING\": -5,\n \"ANNOYS\": -5,\n \"ANNUL\": -5,\n \"ANNULLED\": -5,\n \"ANNULLING\": -5,\n \"ANNULMENT\": -5,\n \"ANNULMENTS\": -5,\n \"ANNULS\": -5,\n \"ANOMALIES\": -5,\n \"ANOMALOUS\": -5,\n \"ANOMALOUSLY\": -5,\n \"ANOMALY\": -5,\n \"ANTICOMPETITIVE\": -5,\n \"ANTITRUST\": -5,\n \"ARGUE\": -5,\n \"ARGUED\": -5,\n \"ARGUING\": -5,\n \"ARGUMENT\": -5,\n \"ARGUMENTATIVE\": -5,\n \"ARGUMENTS\": -5,\n \"ARREARAGE\": -5,\n \"ARREARAGES\": -5,\n \"ARREARS\": -5,\n \"ARREST\": -5,\n \"ARRESTED\": -5,\n \"ARRESTS\": -5,\n \"ARTIFICIALLY\": -5,\n \"ASSAULT\": -5,\n \"ASSAULTED\": -5,\n \"ASSAULTING\": -5,\n \"ASSAULTS\": -5,\n \"ASSERTIONS\": -5,\n \"ATTRITION\": -5,\n \"AVERSELY\": -5,\n \"BACKDATING\": -5,\n \"BAD\": -5,\n \"BAIL\": -5,\n \"BAILOUT\": -5,\n \"BALK\": -5,\n \"BALKED\": -5,\n \"BANKRUPT\": -5,\n \"BANKRUPTCIES\": -5,\n \"BANKRUPTCY\": -5,\n \"BANKRUPTED\": -5,\n \"BANKRUPTING\": -5,\n \"BANKRUPTS\": -5,\n \"BANS\": -5,\n \"BARRED\": -5,\n \"BARRIER\": -5,\n \"BARRIERS\": -5,\n \"BOTTLENECK\": -5,\n \"BOTTLENECKS\": -5,\n \"BOYCOTT\": -5,\n \"BOYCOTTED\": -5,\n \"BOYCOTTING\": -5,\n \"BOYCOTTS\": -5,\n \"BREAK\": -5,\n \"BREAKAGE\": -5,\n \"BREAKAGES\": -5,\n \"BREAKDOWN\": -5,\n \"BREAKDOWNS\": -5,\n \"BREAKING\": -5,\n \"BREAKS\": -5,\n \"BRIBE\": -5,\n \"BRIBED\": -5,\n \"BRIBERIES\": -5,\n \"BRIBERY\": -5,\n \"BRIBES\": -5,\n \"BRIBING\": -5,\n \"BRIDGE\": -5,\n \"BROKEN\": -5,\n \"BURDEN\": -5,\n \"BURDENED\": -5,\n \"BURDENING\": -5,\n \"BURDENS\": -5,\n \"BURDENSOME\": -5,\n \"BURNED\": -5,\n \"CALAMITIES\": -5,\n \"CALAMITOUS\": -5,\n \"CALAMITY\": -5,\n \"CANCEL\": -5,\n \"CANCELED\": -5,\n \"CANCELING\": -5,\n \"CANCELLATION\": -5,\n \"CANCELLATIONS\": -5,\n \"CANCELLED\": -5,\n \"CANCELLING\": -5,\n \"CANCELS\": -5,\n \"CARELESS\": -5,\n \"CARELESSLY\": -5,\n \"CARELESSNESS\": -5,\n \"CATASTROPHE\": -5,\n \"CATASTROPHES\": -5,\n \"CATASTROPHIC\": -5,\n \"CATASTROPHICALLY\": -5,\n \"CAUTION\": -5,\n \"CAUTIONARY\": -5,\n \"CAUTIONED\": -5,\n \"CAUTIONING\": -5,\n \"CAUTIONS\": -5,\n \"CEASE\": -5,\n \"CEASED\": -5,\n \"CEASES\": -5,\n \"CEASING\": -5,\n \"CENSURE\": -5,\n \"CENSURED\": -5,\n \"CENSURES\": -5,\n \"CENSURING\": -5,\n \"CHALLENGE\": -5,\n \"CHALLENGED\": -5,\n \"CHALLENGES\": -5,\n \"CHALLENGING\": -5,\n \"CHARGEOFFS\": -5,\n \"CIRCUMVENT\": -5,\n \"CIRCUMVENTED\": -5,\n \"CIRCUMVENTING\": -5,\n \"CIRCUMVENTION\": -5,\n \"CIRCUMVENTIONS\": -5,\n \"CIRCUMVENTS\": -5,\n \"CLAIMING\": -5,\n \"CLAIMS\": -5,\n \"CLAWBACK\": -5,\n \"CLOSED\": -5,\n \"CLOSEOUT\": -5,\n \"CLOSEOUTS\": -5,\n \"CLOSING\": -5,\n \"CLOSINGS\": -5,\n \"CLOSURE\": -5,\n \"CLOSURES\": -5,\n \"COERCE\": -5,\n \"COERCED\": -5,\n \"COERCES\": -5,\n \"COERCING\": -5,\n \"COERCION\": -5,\n \"COERCIVE\": -5,\n \"COLLAPSE\": -5,\n \"COLLAPSED\": -5,\n \"COLLAPSES\": -5,\n \"COLLAPSING\": -5,\n \"COLLISION\": -5,\n \"COLLISIONS\": -5,\n \"COLLUDE\": -5,\n \"COLLUDED\": -5,\n \"COLLUDES\": -5,\n \"COLLUDING\": -5,\n \"COLLUSION\": -5,\n \"COLLUSIONS\": -5,\n \"COLLUSIVE\": -5,\n \"COMPLAIN\": -5,\n \"COMPLAINED\": -5,\n \"COMPLAINING\": -5,\n \"COMPLAINS\": -5,\n \"COMPLAINT\": -5,\n \"COMPLAINTS\": -5,\n \"COMPLICATE\": -5,\n \"COMPLICATED\": -5,\n \"COMPLICATES\": -5,\n \"COMPLICATING\": -5,\n \"COMPLICATION\": -5,\n \"COMPLICATIONS\": -5,\n \"COMPULSION\": -5,\n \"CONCEALED\": -5,\n \"CONCEALING\": -5,\n \"CONCEDE\": -5,\n \"CONCEDED\": -5,\n \"CONCEDES\": -5,\n \"CONCEDING\": -5,\n \"CONCERN\": -5,\n \"CONCERNED\": -5,\n \"CONCERNS\": -5,\n \"CONCILIATING\": -5,\n \"CONCILIATION\": -5,\n \"CONCILIATIONS\": -5,\n \"CONDEMN\": -5,\n \"CONDEMNATION\": -5,\n \"CONDEMNATIONS\": -5,\n \"CONDEMNED\": -5,\n \"CONDEMNING\": -5,\n \"CONDEMNS\": -5,\n \"CONDONE\": -5,\n \"CONDONED\": -5,\n \"CONFESS\": -5,\n \"CONFESSED\": -5,\n \"CONFESSES\": -5,\n \"CONFESSING\": -5,\n \"CONFESSION\": -5,\n \"CONFINE\": -5,\n \"CONFINED\": -5,\n \"CONFINEMENT\": -5,\n \"CONFINEMENTS\": -5,\n \"CONFINES\": -5,\n \"CONFINING\": -5,\n \"CONFISCATE\": -5,\n \"CONFISCATED\": -5,\n \"CONFISCATES\": -5,\n \"CONFISCATING\": -5,\n \"CONFISCATION\": -5,\n \"CONFISCATIONS\": -5,\n \"CONFLICT\": -5,\n \"CONFLICTED\": -5,\n \"CONFLICTING\": -5,\n \"CONFLICTS\": -5,\n \"CONFRONT\": -5,\n \"CONFRONTATION\": -5,\n \"CONFRONTATIONAL\": -5,\n \"CONFRONTATIONS\": -5,\n \"CONFRONTED\": -5,\n \"CONFRONTING\": -5,\n \"CONFRONTS\": -5,\n \"CONFUSE\": -5,\n \"CONFUSED\": -5,\n \"CONFUSES\": -5,\n \"CONFUSING\": -5,\n \"CONFUSINGLY\": -5,\n \"CONFUSION\": -5,\n \"CONSPIRACIES\": -5,\n \"CONSPIRACY\": -5,\n \"CONSPIRATOR\": -5,\n \"CONSPIRATORIAL\": -5,\n \"CONSPIRATORS\": -5,\n \"CONSPIRE\": -5,\n \"CONSPIRED\": -5,\n \"CONSPIRES\": -5,\n \"CONSPIRING\": -5,\n \"CONTEMPT\": -5,\n \"CONTEND\": -5,\n \"CONTENDED\": -5,\n \"CONTENDING\": -5,\n \"CONTENDS\": -5,\n \"CONTENTION\": -5,\n \"CONTENTIONS\": -5,\n \"CONTENTIOUS\": -5,\n \"CONTENTIOUSLY\": -5,\n \"CONTESTED\": -5,\n \"CONTESTING\": -5,\n \"CONTRACTION\": -5,\n \"CONTRACTIONS\": -5,\n \"CONTRADICT\": -5,\n \"CONTRADICTED\": -5,\n \"CONTRADICTING\": -5,\n \"CONTRADICTION\": -5,\n \"CONTRADICTIONS\": -5,\n \"CONTRADICTORY\": -5,\n \"CONTRADICTS\": -5,\n \"CONTRARY\": -5,\n \"CONTROVERSIAL\": -5,\n \"CONTROVERSIES\": -5,\n \"CONTROVERSY\": -5,\n \"CONVICT\": -5,\n \"CONVICTED\": -5,\n \"CONVICTING\": -5,\n \"CONVICTION\": -5,\n \"CONVICTIONS\": -5,\n \"CORRECTED\": -5,\n \"CORRECTING\": -5,\n \"CORRECTION\": -5,\n \"CORRECTIONS\": -5,\n \"CORRECTS\": -5,\n \"CORRUPT\": -5,\n \"CORRUPTED\": -5,\n \"CORRUPTING\": -5,\n \"CORRUPTION\": -5,\n \"CORRUPTIONS\": -5,\n \"CORRUPTLY\": -5,\n \"CORRUPTNESS\": -5,\n \"COSTLY\": -5,\n \"COUNTERCLAIM\": -5,\n})\n\n\ndef get_config():\n return vader\n","sub_path":"services/reddit/sentiment.py","file_name":"sentiment.py","file_ext":"py","file_size_in_byte":15918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"357478742","text":"print('欢迎来到MekOs')\nprint('输入c以查看关于,输入s以跳过。')\n\ncs = True\nwhile cs:\n css = input('请输入: ')\n if css == 'c':\n print('我喜欢你,拿滴克来。')\n cs = False\n elif css == 's':\n print('也要看!!!信不信我上了你!')\n cs = False\n else:\n print('请选择正确的选项!')\n\nun = True\nwhile un:\n unn = input('请输入用户名: ')\n if unn == 'Etsuya':\n print('用户名正确。')\n un = False\n elif unn != 'Etsuya':\n print('用户名错误!请重新输入!')\n \npw = True\nwhile pw:\n pww = input('请输入密码: ')\n if pww == 'fnndp':\n print('密码正确,所以.....诶嘿嘿。')\n pw = False\n elif pww != 'fnndp':\n print('密码错误!请重新输入!')\n \n#这次比之前的那次好多了qwq\n","sub_path":"登录到EtsuyaⅡ(if,while).py","file_name":"登录到EtsuyaⅡ(if,while).py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"147548121","text":"#!/usr/bin/env python\n\n\"\"\"\n@Time : 18/07/28 12:59\n@Author : Bob\n@Desc : \n\"\"\"\n\nfrom channels.auth import AuthMiddlewareStack\nfrom channels.routing import ProtocolTypeRouter, URLRouter\n\nfrom djchat.routing import *\n\napplication = ProtocolTypeRouter({\n # (http->django views is added by default)\n 'websocket': AuthMiddlewareStack(\n URLRouter(\n websocket_urlpatterns\n )\n ),\n})\n","sub_path":"sdfh_rest/routing.py","file_name":"routing.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"157931997","text":"#!/usr/bin/env python3\n\"\"\"\nPrediction for HHMM\nMost recent version as of 07/28/2019\n\"\"\"\n\nimport argparse\nimport os\n# import logging\nimport sys\n### Libraries ###\nimport pickle\nimport time\nimport numpy as np\nfrom matfuncs import expm\nfrom scipy import stats\nfrom scipy import special\nimport matplotlib\nmatplotlib.use('agg')\nimport matplotlib.pyplot as plt\n\n\ndef Initialization():\n global ages_test, testTypes_test, observations_test, treatment_indx_test, censor_ages_test, death_state_test, ind, nTests, inv, n_inv, MPmatrixs, nPatients_test\n global out_path, out_folder, max_steps_em, max_steps_optim, model, autograd_optim, p, args, n_test\n global currPars, curr_parameter_vector\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--name\", help=\"name of the experiment\", default=\"prediction_hierarchical\")\n parser.add_argument(\"--min_age\", help=\"minimum age\", type=int, default=16)\n parser.add_argument(\"--dataset\", help=\"data specification: data_1000 are available\", default=\"data_1000\")\n parser.add_argument(\"--age_inv\", help=\"age interval sepecification\", default=\"inv4\")\n parser.add_argument(\"--model\", help=\"discrete or continuous model\", default=\"continuous\")\n parser.add_argument(\"--test\", help=\"boolean indicator for testing\", action='store_true')\n parser.add_argument(\"--Z_prior\", help=\"prior probability of Model 1\", type=np.float32, default=0.5)\n\n args = parser.parse_args()\n\n try:\n os.chdir(os.path.dirname(__file__))\n except:\n pass\n\n if args.test:\n out_folder = args.name + '_' + str(\n args.min_age) + '_' + args.dataset + '_' + args.age_inv + '_' + args.model + '_test'\n else:\n out_folder = args.name + '_' + str(args.min_age) + '_' + args.dataset + '_' + args.age_inv + '_' + args.model\n\n min_age = args.min_age\n do_truncate_ages = True if min_age > 16 else False\n dataset = args.dataset\n inv_indx = args.age_inv\n model = args.model\n p = args.Z_prior\n\n ##########################\n ##### Initialization #####\n ##########################\n nStates_0 = 2\n nStates_1 = 4\n nTests = 3\n\n ind = [\"Alpha\", \"Eta\", \"W\",\n \"C\"] # ind specifies which parameters need to be optimized:x [\"Alpha\", \"W\", \"Gamma\", \"Zeta\", \"Eta\", \"A\", \"C\"]\n inv_list = {\"inv14\": [20, 23, 27, 30, 33, 37, 40, 43, 47, 50, 53, 57, 60, 200],\n \"inv13\": [20, 23, 27, 30, 33, 37, 40, 43, 47, 50, 55, 60, 200],\n \"inv12\": [20, 23, 27, 30, 33, 37, 40, 43, 47, 50, 60, 200],\n \"inv11\": [20, 23, 27, 30, 33, 37, 40, 45, 50, 60, 200],\n \"inv10\": [19, 22, 25, 30, 35, 40, 45, 50, 55, 200], # expert advice\n \"inv9\": [23, 25, 30, 35, 40, 45, 50, 60, 200], # expert advice\n \"inv8\": [20, 25, 30, 35, 40, 50, 60, 200], # best AIC and Likelihood with 3000 procs.\n \"inv7\": [20, 25, 30, 40, 50, 60, 200], # best AIC with 300 procs\n \"inv6\": [23, 30, 40, 50, 60, 200],\n \"inv5\": [23, 35, 45, 60, 200],\n \"inv4\": [23, 30, 60, 200],\n \"inv3\": [29, 69, 200], # close second AIC with 300 procs\n \"inv2\": [23, 200],\n \"inv1\": [200]}\n inv = inv_list[inv_indx]\n n_inv = len(inv)\n\n if dataset == 'data_1000':\n data_location = '../../data/data_1000/'\n else:\n print(\"dataset {} is not available\".format(dataset))\n\n # load data\n testTypes = pickle.load(open(data_location + \"mcmcPatientTestTypes\", 'rb'), encoding=\"bytes\")\n observations = pickle.load(open(data_location + \"mcmcPatientObservations\", 'rb'), encoding=\"bytes\")\n ages = pickle.load(open(data_location + \"mcmcPatientAges\", 'rb'), encoding=\"bytes\")\n treatment_indx = pickle.load(open(data_location + \"mcmcPatientTreatmentIndx\", 'rb'), encoding=\"bytes\")\n censor_ages = pickle.load(open(data_location + \"mcmcPatientCensorDates\", 'rb'), encoding=\"bytes\")\n death_states = pickle.load(open(data_location + \"mcmcPatientDeathStates\", 'rb'), encoding=\"bytes\")\n\n # Testing data\n # n_test: number of testing data\n n_test = 20000\n testTypes_test = testTypes[-n_test:]\n observations_test = observations[-n_test:]\n ages_test = ages[-n_test:]\n treatment_indx_test = treatment_indx[-n_test:]\n censor_ages_test = censor_ages[-n_test:]\n death_state_test = death_states[-n_test:]\n\n # define Markov Process topology with MPmatrix. The diagonal should be zeros.\n # A one in element (i,j) indicates a possible transition between states i and j.\n MPmatrix_0 = np.zeros([nStates_0 + 1, nStates_0 + 1])\n MPmatrix_0[0, 1] = MPmatrix_0[1, 0] = MPmatrix_0[0, 2] = MPmatrix_0[1, 2] = 1\n MPmatrix_1 = np.zeros([nStates_1 + 1, nStates_1 + 1])\n MPmatrix_1[0, 1] = MPmatrix_1[1, 0] = MPmatrix_1[1, 2] = MPmatrix_1[2, 1] = MPmatrix_1[2, 3] = MPmatrix_1[:-1,\n -1] = 1\n MPmatrixs = [MPmatrix_0, MPmatrix_1]\n\n nPatients_test = len(ages_test)\n print('Number of patients for testing: ', nPatients_test)\n\n ### Set informative initial parameters\n temp = 4\n currAlpha_0 = [np.zeros([nStates_0, 4]), np.zeros([nStates_0, 4]), np.zeros([nStates_0, 2])]\n currAlpha_0[0][0, 0] = currAlpha_0[0][1, 1] = temp\n currAlpha_0[1][0, 0] = currAlpha_0[1][1, 1] = temp\n currAlpha_1 = [np.zeros([nStates_1, 4]), np.zeros([nStates_1, 4]), np.zeros([nStates_1, 2])]\n currAlpha_1[0][0, 0] = currAlpha_1[0][1, 1] = currAlpha_1[0][2, 2] = currAlpha_1[0][3, 3] = temp\n currAlpha_1[1][0, 0] = currAlpha_1[1][1, 1] = currAlpha_1[1][2, 2] = currAlpha_1[1][3, 3] = temp\n currAlpha_1[2][3, 0] = -2\n currAlpha_1[2][3, 1] = 2\n currAlpha = [currAlpha_0, currAlpha_1]\n currEta_0 = np.zeros([nStates_0, 3])\n currEta_1 = np.zeros([nStates_1, 3])\n currEta = [currEta_0, currEta_1]\n if model == \"continuous\":\n currW_0 = np.zeros([4, n_inv])\n currW_0[1, :] = -temp\n currW_0[3, :] = -temp\n currW_1 = np.zeros([9, n_inv])\n currW_1[1, :] = -temp\n currW_1[4, :] = -temp\n currW_1[7, :] = -temp\n elif model == \"discrete\":\n currW_0 = -4 * np.ones([4, n_inv])\n currW_1 = -4 * np.ones([9, n_inv])\n currW = [currW_0, currW_1]\n currC_0 = np.zeros([nStates_0, n_inv])\n currC_1 = np.zeros([nStates_1, n_inv])\n currC = [currC_0, currC_1]\n\n return 0\n\n\ndef Load_EM_res(verbose=False):\n global currPars\n with open(\"../../data/data_2400/EM_16_updated_data_inv4_continuous_240000/res\", \"rb\") as em_res:\n res = pickle.load(em_res, encoding=\"bytes\")\n currAlpha = res[2]\n currEta = res[3]\n currW = res[4]\n currC = res[5]\n currPars = [currAlpha, currEta, currW, currC]\n\n if verbose:\n print(\n \"EM results have been loaded with Pars: Alpha: {}, Eta: {}, W: {}, C:{}.\".format(currAlpha, currEta, currW,\n currC))\n return 0\n\n\ndef Compute_pos_Z_test(p, verbose=False): ### given no state Z | -\n global Z_pos\n # It is a Bernouli(p)\n\n ts = time.time()\n Z_pos = []\n for indx in range(nPatients_test):\n if indx % 100 == 99:\n print(\"{}/{} has been completed\".format(indx + 1, nPatients_test))\n loglik_0 = Loglikelihood_obs0_test(indx, 0, currPars)\n loglik_1 = Loglikelihood_obs0_test(indx, 1, currPars)\n tilde_p = np.exp(np.log(p) + loglik_1 - np.log((1 - p) * np.exp(loglik_0) + p * np.exp(loglik_1)))\n Z_pos.append(tilde_p)\n\n print('Compute the posterior of Z costs {}s'.format(time.time() - ts))\n if verbose:\n for indx in range(nPatients_test):\n print(\"Patient {}: model index probabilites: {}\".format(indx, Z_pos[indx]))\n return 0\n\n\ndef Loglikelihood_obs0_test(indx, Z, Pars, verbose=False):\n Alpha = Pars[0][Z]\n Eta = Pars[1][Z]\n W = Pars[2][Z]\n C = Pars[3][Z]\n MPmatrix = MPmatrixs[Z]\n\n patient_ages = ages_test[indx]\n patient_tests = testTypes_test[indx]\n patient_observations = observations_test[indx]\n patient_treatment_indx = treatment_indx_test[indx]\n patient_censor_age = censor_ages_test[indx]\n patient_death_state = death_state_test[indx]\n\n if len(patient_treatment_indx) == 1:\n j = patient_treatment_indx[0]\n loglik0 = Loglikelihood_group_obs0(patient_tests[:(j + 1)], patient_observations[:(j + 1)],\n patient_ages[:(j + 1)], 0, patient_censor_age, patient_death_state, Z, Alpha,\n Eta, W, C, ind, inv, verbose)\n if j < (len(patient_ages) - 1):\n loglik1 = Loglikelihood_group_obs0(patient_tests[j:-1], patient_observations[j:-1], patient_ages[j:-1], 1,\n patient_censor_age, patient_death_state, Z, Alpha, Eta, W, C, ind, inv,\n verbose)\n else:\n loglik1 = 0\n loglik = loglik0 + loglik1\n elif len(patient_treatment_indx) > 1:\n loglik = 0\n j = patient_treatment_indx[0]\n loglik0 = Loglikelihood_group_obs0(patient_tests[:(j + 1)], patient_observations[:(j + 1)],\n patient_ages[:(j + 1)], 0, patient_censor_age, patient_death_state, Z, Alpha,\n Eta, W, C, ind, inv, verbose)\n loglik += loglik0\n for i in range(len(patient_treatment_indx) - 1):\n j = patient_treatment_indx[i]\n k = patient_treatment_indx[i + 1] + 1\n logliki = Loglikelihood_group_obs0(patient_tests[j:k], patient_observations[j:k], patient_ages[j:k], 1,\n patient_censor_age, patient_death_state, Z, Alpha, Eta, W, C, ind, inv,\n verbose)\n loglik += logliki\n j = patient_treatment_indx[-1]\n if j < (len(patient_ages) - 1):\n loglik1 = Loglikelihood_group_obs0(patient_tests[j:-1], patient_observations[j:-1], patient_ages[j:-1], 1,\n patient_censor_age, patient_death_state, Z, Alpha, Eta, W, C, ind, inv,\n verbose)\n else:\n loglik1 = 0\n loglik += loglik1\n else:\n loglik = Loglikelihood_group_obs0(patient_tests[:-1], patient_observations[:-1], patient_ages[:-1], 0,\n patient_censor_age, patient_death_state, Z, Alpha, Eta, W, C, ind, inv,\n verbose)\n return loglik\n\n\ndef Loglikelihood_group_obs0(patient_tests, patient_observations, patient_ages, patient_treatment_status, patient_censor_age, patient_death_state, Z, Alpha, Eta, W, C, ind, inv, verbose=False, do_last=False):\n if Z == 0:\n nStates = 2\n else:\n nStates = 4\n MPmatrix = MPmatrixs[Z]\n\n nvisits = len(patient_ages)\n ### Initialization ###\n ### Q[s] ~ Pr[S0=s, O0]\n Q = np.zeros(nStates)\n patient_age = patient_ages[0]\n patient_test = patient_tests[0]\n patient_observation = patient_observations[0]\n if patient_treatment_status == 0:\n for s in range(nStates):\n Q[s] = np.log(ddirichlet_categorical(s, np.exp(C[:, Age2Comp(patient_age, inv)])))\n # Q[s] = np.log(C[s, Age2Comp(patient_age, inv)])\n Q[s] += np.sum(stats.poisson.logpmf(patient_test, np.exp(Eta[s, :])))\n # Q[s] += np.sum(stats.poisson.logpmf(patient_test, Eta[s,:]))\n for k in range(nTests):\n if k == 2:\n # Q[s] += multinomial_logpmf(patient_observations[0][k, :2], Alpha[k][s, :])\n Q[s] += np.log(ddirichlet_mutilnominal(patient_observations[0][k, :2], np.exp(Alpha[k][s, :])))\n else:\n # Q[s] += multinomial_logpmf(patient_observations[0][k, :], Alpha[k][s, :])\n Q[s] += np.log(ddirichlet_mutilnominal(patient_observations[0][k, :], np.exp(Alpha[k][s, :])))\n # P(S0, O0)\n Q = np.exp(Q)\n else:\n Q[0] = 1\n log_Q = np.log(Q)\n\n ####################\n ### Forward Pass ###\n ####################\n # P_forward_matrices P(Sj-1, Sj, O0-j)\n P_forward_matrices = [np.zeros([nStates, nStates]) for patient_age in patient_ages]\n for j in range(1, nvisits):\n p_transition = ProbTransition(MPmatrix, W, patient_ages[j - 1], patient_ages[j], inv)\n log_prob_obs = np.zeros(nStates)\n for s in range(nStates):\n log_prob_obs[s] += np.sum(stats.poisson.logpmf(patient_tests[j], np.exp(Eta[s, :])))\n # log_prob_obs[s] += np.sum(stats.poisson.logpmf(patient_tests[j], Eta[s,:]))\n for k in range(nTests):\n if k == 2:\n # log_prob_obs[s] += multinomial_logpmf(patient_observations[j][k, :2], Alpha[k][s, :])\n log_prob_obs[s] += np.log(\n ddirichlet_mutilnominal(patient_observations[j][k, :2], np.exp(Alpha[k][s, :])))\n else:\n # log_prob_obs[s] += multinomial_logpmf(patient_observations[j][k, :], Alpha[k][s, :])\n log_prob_obs[s] += np.log(\n ddirichlet_mutilnominal(patient_observations[j][k, :], np.exp(Alpha[k][s, :])))\n\n log_P_forward_matrix = np.repeat(log_Q, nStates).reshape([nStates, nStates]) + np.transpose(\n np.repeat(log_prob_obs, nStates).reshape([nStates, nStates])) + np.log(p_transition[:nStates, :nStates])\n P_forward_matrix = np.exp(log_P_forward_matrix)\n #\n P_forward_matrices[j] = P_forward_matrix\n #\n Q = np.sum(P_forward_matrix, 0) / np.sum(P_forward_matrix)\n log_Q = np.log(Q)\n\n ## P(S_T, O)\n if nvisits > 1:\n PP = np.sum(P_forward_matrices[nvisits - 1], 0)\n else:\n PP = Q\n log_PP = np.log(PP)\n\n # print (\"P_forward_matrices\", P_forward_matrices)\n # print (\"log_PP\", log_PP)\n\n ## P(S_T, S_last, O)\n if do_last:\n # Add the censor statue\n if patient_censor_age < patient_ages[-1]:\n # this can happen due to some rounding errors when death is very close to last screening.\n # Just move the censor date a few month after last visit.\n patient_censor_age = patient_ages[-1] + 0.25\n p_transition = ProbTransition(MPmatrix, W, patient_ages[-1], patient_censor_age, inv)\n if patient_death_state > 0: # this means censor age is age of 'death', not end of observations.\n log_PP += np.log(p_transition[:nStates, -1])\n else: # this means censor age is age of end of observations, not 'death'. So we know they are still alive at the time the study ended.\n log_PP += np.log(1. - p_transition[:nStates, -1])\n\n # print (\"log_PP\", log_PP)\n\n return np.log(np.sum(np.exp(log_PP)))\n\n\ndef Compute_pos_last2(Pars):\n global last2s\n\n ts = time.time()\n last2s = []\n for indx in range(nPatients_test):\n last2 = last2_z(indx, Pars, verbose=False)\n # print(last2_z0.sum(), last2_z1.sum())\n last2s.append(last2)\n # print(last2s)\n print('Compute the predictive distribution of S*_I costs {}s'.format(time.time() - ts))\n return 0\n\n\ndef last2_z(indx, Pars, verbose=False):\n Alpha = Pars[0]\n Eta = Pars[1]\n W = Pars[2]\n C = Pars[3]\n Z = 1\n\n patient_ages = ages_test[indx]\n patient_tests = testTypes_test[indx]\n patient_observations = observations_test[indx]\n patient_treatment_indx = treatment_indx_test[indx]\n patient_censor_age = censor_ages_test[indx]\n patient_death_state = death_state_test[indx]\n\n if len(patient_treatment_indx) >= 1:\n j = patient_treatment_indx[-1]\n res = prob_last2_z_group(patient_tests[:-1], patient_observations[:-1], patient_ages[:-1], 1,\n patient_censor_age, patient_death_state, Z, Alpha, Eta, W, C, ind, inv, verbose)\n else:\n res = prob_last2_z_group(patient_tests[:-1], patient_observations[:-1], patient_ages[:-1], 0,\n patient_censor_age, patient_death_state, Z, Alpha, Eta, W, C, ind, inv, verbose)\n\n if verbose:\n print(indx, patient_treatment_indx, patient_tests[:-1], patient_observations[:-1], patient_ages[:-1],\n patient_censor_age, patient_death_state)\n\n return res\n\n\ndef prob_last2_z_group(patient_tests, patient_observations, patient_ages, patient_treatment_status, patient_censor_age, patient_death_state, Z, Alpha, Eta, W, C, ind, inv, verbose=False):\n if Z == 0:\n nStates = 2\n else:\n nStates = 4\n MPmatrix = MPmatrixs[Z]\n\n nvisits = len(patient_ages)\n ### Initialization ###\n ### Q[s] ~ Pr[S0=s, O0]\n Q = np.zeros(nStates)\n patient_age = patient_ages[0]\n patient_test = patient_tests[0]\n patient_observation = patient_observations[0]\n if patient_treatment_status == 0:\n for s in range(nStates):\n Q[s] = np.log(ddirichlet_categorical(s, np.exp(C[:, Age2Comp(patient_age, inv)])))\n # Q[s] = np.log(C[s, Age2Comp(patient_age, inv)])\n Q[s] += np.sum(stats.poisson.logpmf(patient_test, np.exp(Eta[s, :])))\n # Q[s] += np.sum(stats.poisson.logpmf(patient_test, Eta[s,:]))\n for k in range(nTests):\n if k == 2:\n # Q[s] += multinomial_logpmf(patient_observations[0][k, :2], Alpha[k][s, :])\n Q[s] += np.log(ddirichlet_mutilnominal(patient_observations[0][k, :2], np.exp(Alpha[k][s, :])))\n else:\n # Q[s] += multinomial_logpmf(patient_observations[0][k, :], Alpha[k][s, :])\n Q[s] += np.log(ddirichlet_mutilnominal(patient_observations[0][k, :], np.exp(Alpha[k][s, :])))\n # P(S0, O0)\n Q = np.exp(Q)\n else:\n Q[0] = 1\n log_Q = np.log(Q)\n\n ####################\n ### Forward Pass ###\n ####################\n # P_forward_matrices P(Sj-1, Sj, O0-j)\n P_forward_matrices = [np.zeros([nStates, nStates]) for patient_age in patient_ages]\n for j in range(1, nvisits):\n p_transition = ProbTransition(MPmatrix, W, patient_ages[j - 1], patient_ages[j], inv)\n log_prob_obs = np.zeros(nStates)\n for s in range(nStates):\n log_prob_obs[s] += np.sum(stats.poisson.logpmf(patient_tests[j], np.exp(Eta[s, :])))\n # log_prob_obs[s] += np.sum(stats.poisson.logpmf(patient_tests[j], Eta[s,:]))\n for k in range(nTests):\n if k == 2:\n # log_prob_obs[s] += multinomial_logpmf(patient_observations[j][k, :2], Alpha[k][s, :])\n log_prob_obs[s] += np.log(\n ddirichlet_mutilnominal(patient_observations[j][k, :2], np.exp(Alpha[k][s, :])))\n else:\n # log_prob_obs[s] += multinomial_logpmf(patient_observations[j][k, :], Alpha[k][s, :])\n log_prob_obs[s] += np.log(\n ddirichlet_mutilnominal(patient_observations[j][k, :], np.exp(Alpha[k][s, :])))\n\n log_P_forward_matrix = np.repeat(log_Q, nStates).reshape([nStates, nStates]) + np.transpose(\n np.repeat(log_prob_obs, nStates).reshape([nStates, nStates])) + np.log(p_transition[:nStates, :nStates])\n P_forward_matrix = np.exp(log_P_forward_matrix)\n P_forward_matrices[j] = P_forward_matrix\n Q = np.sum(P_forward_matrix, 0) / np.sum(P_forward_matrix)\n\n if nvisits == 1:\n Q /= Q.sum()\n\n return Q\n\n\ndef Compute_pos_last(Pars, verbose=False):\n global lasts\n\n ts = time.time()\n lasts = []\n Z = 1\n W = Pars[2]\n MPmatrix = MPmatrixs[Z]\n\n for indx in range(nPatients_test):\n last2_z1 = last2s[indx]\n patient_ages = ages_test[indx]\n\n # compute S_I+1|z=1, O*, hat_psi\n p_transition = ProbTransition(MPmatrix, W, patient_ages[-2], patient_ages[-1], inv)\n P_transition = p_transition[:-1, :-1]\n P_transition /= P_transition.sum(axis=1)[:, None]\n last_z1 = last2_z1.dot(P_transition) # dim 4\n\n if verbose:\n print(\"{}th patient, last2_z1: {}, last_z1: {}\".format(indx, last2_z1, last_z1))\n last = last_z1\n lasts.append(last_z1)\n\n if verbose:\n for indx in range(nPatients_test):\n print(\"{}th patient, state probs: {}, res: {}\".format(indx, lasts[indx], observations_test[indx][-1]))\n print(\"Computing the last state probability costs {}s\".format(time.time()-ts))\n\n\ndef ProbTransition_interval(MPmatrix, dt, W):\n '''\n 'MPmatrix' should be a square N-by-N matrix of ones and zeros that defines the intensity matrix of the markov process.\n A 1 at element ij indicates a possible transition between states i and j.\n A 0 at element ij means no possible transition between states i and j.\n\n -- Because this is a continuous time Markov Process the diagonals are forced to be zero.\n -- 'lambdas' is an array of transition intensities for the given patient at a given time interval.\n -- dt is a scalar. It is the difference in time between two observations.\n\n '''\n matrix = np.array(MPmatrix, copy=True)\n\n if model == 'continuous':\n matrix_filled = np.zeros_like(matrix, dtype=np.float32)\n matrix_filled[np.where(matrix > 0)] = np.exp(W)\n for i in range(matrix.shape[0]):\n matrix_filled[i, i] = - np.sum(matrix_filled[i, :])\n out = expm(dt * matrix_filled) # so far so good...\n elif model == 'discrete':\n n_dim = MPmatrix.shape[0]\n matrix_filled = np.zeros_like(matrix, dtype=np.float32)\n matrix_filled[np.where(matrix == 1)] = W\n np.fill_diagonal(matrix, 1)\n matrix = np.matmul(np.diag(1 + np.arange(n_dim)), matrix)\n for indx_row in range(n_dim):\n matrix_filled[np.where(matrix == 1 + indx_row)] = Softmax(matrix_filled[np.where(matrix == 1 + indx_row)])\n out = np.linalg.matrix_power(matrix_filled, int(round(dt * 12)) if int(\n round(dt * 12)) > 0 else 1) # Assume the screening interval is at least one month\n\n # Normalize the probablity matrix\n out = np.where(out < 0, 0., out)\n out = np.where(out > 1, 1., out)\n norm = np.repeat(np.sum(out, 1), out.shape[0]).reshape(out.shape)\n out = out / norm\n return out\n\n\ndef ProbTransition(MPmatrix, W, start, end, inv):\n '''\n 'matrix' should be a square N-by-N matrix of ones and zeros that defines the intensity matrix of the markov process.\n A 1 at element ij indicates a possible transition between states i and j.\n A 0 at element ij means no possible transition between states i and j.\n\n Because this is a continuous time Markov Process the diagonals are forced to be zero.\n\n hpv_status is 0,1 or -1. If -1, then status is unknown.\n treatment_status is 0 or 1.\n\n '''\n temp = start\n matrix = np.eye(MPmatrix.shape[0])\n\n while (temp < end):\n temp_component = Age2Comp(temp, inv)\n end_component = Age2Comp(end, inv)\n if temp_component < end_component:\n dt = (inv[temp_component] - temp)\n temp_W = W[:, temp_component]\n matrix = np.dot(matrix, ProbTransition_interval(MPmatrix, dt, temp_W))\n temp = inv[temp_component]\n else:\n dt = end - temp\n temp_W = W[:, temp_component]\n matrix = np.dot(matrix, ProbTransition_interval(MPmatrix, dt, temp_W))\n temp = inv[temp_component]\n\n out = matrix\n # Normalize the probability matrix\n out = np.where(out < 0, 0., out)\n out = np.where(out > 1, 1., out)\n norm = np.repeat(np.sum(out, 1), out.shape[0]).reshape(out.shape)\n out = out / norm\n return out\n\n\ndef Softmax(x):\n \"\"\"Compute softmax values for each sets of scores in x.\"\"\"\n e_x = np.exp(x - np.max(x))\n return e_x / np.sum(e_x)\n\n\ndef ddirichlet_mutilnominal(x, alpha):\n n = np.sum(x)\n alpha0 = sum(alpha)\n if n == 0:\n return 1\n else:\n return n * special.beta(alpha0, n) / np.prod(\n np.array([special.beta(alphak, xk) * xk for alphak, xk in zip(alpha, x) if xk > 0]))\n\n\ndef ddirichlet_categorical(k, alpha):\n alpha0 = sum(alpha)\n res = special.beta(alpha0, 1) / special.beta(alpha[k], 1)\n return res\n\n\ndef Age2Comp(age, inv): # This function is to specify the intensity component for the certain age(value) and certain transition index. Interval looks like [ ).\n temp = 0\n while age >= inv[temp]:\n temp += 1\n return (temp)\n\n\ndef Predict_SR(Pars, lasts):\n \"\"\"\n compute the average predictive probability given the number of tests\n :param Pars: estimated parameters\n :param lasts: estimated probability of the last state\n :return: average predictive probability for cytology, histology and HPV.\n \"\"\"\n Alpha = Pars[0]\n cytology_pred_scores = []\n histology_pred_scores = []\n hpv_pred_scores = []\n\n indx =0\n for last, patient_observations, patient_tests in zip(lasts, observations_test, testTypes_test):\n indx += 1\n if indx % 1000 == 999:\n print(\"{}/{} individuals has been completed.\".format(indx + 1, n_test))\n T_cyt = patient_tests[-1][0]\n T_hist = patient_tests[-1][1]\n T_hpv = patient_tests[-1][2]\n if T_cyt > 0:\n cyt_score = 0\n for S in range(4):\n cyt_score += ddirichlet_mutilnominal(x=patient_observations[-1][0, :], alpha=np.exp(Alpha[0])[S, :])*last[S]\n cytology_pred_scores.append(cyt_score)\n if T_hist > 0:\n hist_score = 0\n for S in range(4):\n hist_score += ddirichlet_mutilnominal(x=patient_observations[-1][1, :], alpha=np.exp(Alpha[1])[S, :])*last[S]\n histology_pred_scores.append(hist_score)\n if T_hpv > 0:\n hpv_score = 0\n for S in range(4):\n hpv_score += ddirichlet_mutilnominal(x=patient_observations[-1][2, :2], alpha=np.exp(Alpha[2])[S, :])*last[S]\n hpv_pred_scores.append(hpv_score)\n print(cytology_pred_scores)\n print(histology_pred_scores)\n print(hpv_pred_scores)\n cytology_pred_avgscore = np.mean(np.asarray(cytology_pred_scores))\n histology_pred_avgscore = np.mean(np.asarray(histology_pred_scores))\n hpv_pred_avgscore = np.mean(np.asarray(hpv_pred_scores))\n return cytology_pred_avgscore, histology_pred_avgscore, hpv_pred_avgscore\n\n\n\nif __name__ == \"__main__\":\n #################################\n ####### Initialization ##########\n #################################\n Initialization()\n\n #################################\n ######## Load EM estimates ######\n #################################\n Load_EM_res(verbose=True)\n\n #################################\n ####### HHMM Prediction #########\n #################################\n # # Compute predictive distribution of last second state given model index z\n # Compute_pos_last2(currPars)\n # # Compute predictive distribution of last state\n # Compute_pos_last(currPars, verbose=True)\n\n ################################\n ######## Save Results ##########\n ################################\n # with open(\"../../res/EM_2400/prediction_LS.pickle\", \"wb\") as res:\n # pickle.dump(lasts, res)\n\n ############################\n #######Load Results ########\n ############################\n with open(\"../../res/EM_2400/hierarchical_prediction_LS.pickle\", \"rb\") as res:\n lasts = pickle.load(res)\n\n\n ts = time.time()\n print(Predict_SR(currPars, lasts))\n print(\"prediction costs {}s\".format(time.time() - ts))","sub_path":"src/Model_prediction/EM_prediction_SR.py","file_name":"EM_prediction_SR.py","file_ext":"py","file_size_in_byte":27745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"209588323","text":"from glob import glob\nimport pandas as pd\nfrom multiprocessing import cpu_count, Pool\nfrom os.path import isdir, join, isfile\nfrom functools import partial\nfrom os import scandir\nfrom collections.abc import Iterable\nfrom sqlalchemy import (create_engine, engine, Column,\n Text, Table, MetaData, String,\n Boolean, DateTime, Integer,\n Float, ForeignKey, CheckConstraint, PrimaryKeyConstraint)\nfrom numpy import dtype\nfrom subprocess import Popen, PIPE\n\n\nclass DataModel:\n\n def __init__(self, file_paths_or_dataframe, files_format=None, cpu=None, **kwargs):\n\n self.extension = files_format\n self.load_function = kwargs\n self.cores = cpu\n self.data = file_paths_or_dataframe\n\n @property\n def cores(self):\n\n return self._cpu\n\n @property\n def data(self):\n\n return self._data\n\n @property\n def load_function(self):\n\n return self._load_function\n\n @property\n def extension(self):\n\n return self._extension\n\n @cores.setter\n def cores(self, cpu):\n\n if not cpu:\n self._cpu = cpu_count()\n else:\n self._cpu = cpu\n\n @data.setter\n def data(self, files_path_or_data):\n\n if isinstance(files_path_or_data, (pd.DataFrame, pd.Series)):\n self._data = files_path_or_data\n else:\n if isinstance(files_path_or_data, str):\n if isdir(files_path_or_data):\n self.input = glob(join(files_path_or_data, '*{}'.format(self.extension)))\n elif isfile(files_path_or_data):\n self.input = [files_path_or_data, ]\n elif isinstance(files_path_or_data, (list, tuple)):\n self.input = files_path_or_data\n else:\n raise Exception('file_paths_or_dataframe format is not valid')\n if self.input:\n self._data = self.__get_data()\n\n @load_function.setter\n def load_function(self, kwargs):\n func = self.__get_function()\n if not func:\n self._load_function = None\n else:\n self._load_function = partial(self.func, function=partial(self.__get_function(), **kwargs))\n\n @extension.setter\n def extension(self, format_str):\n\n if format_str is None:\n self._extension = format_str\n elif format_str.lower() in ['json', 'csv', 'xlsx', 'feather', 'parquet']:\n self._extension = '.{}'.format(format_str)\n else:\n raise Exception('extension not valid should be: ')\n\n @staticmethod\n def func(item, function):\n\n try:\n temp_data = function(item)\n if isinstance(temp_data, pd.Series):\n temp_columns = temp_data.index\n else:\n temp_columns = temp_data.columns\n # print(item)\n return temp_columns.tolist(), temp_data.values\n except (pd.errors.ParserError, pd.errors.EmptyDataError, Exception) as error:\n # Logic to catch and log errors in a multiprocessing pool to be implemented\n # pass statement is currently deemed acceptable\n pass\n\n def __convert_to_df(func):\n\n def _wrapped_convert_to_df(self):\n\n output_list = func(self)\n output_list_filtered = [*self.filter_by_type(output_list, Iterable)]\n max_index = len(output_list_filtered)-1\n check_headers = True\n index = 0\n while check_headers:\n headers = output_list_filtered[index][0]\n if headers:\n check_headers = False\n else:\n index += 1\n if index == max_index and not output_list_filtered[index][0]:\n raise Exception('No valid headers found')\n\n data_list = [data_values for columns, data_values\n in output_list_filtered if columns == headers]\n return pd.DataFrame(data_list, columns=headers)\n\n return _wrapped_convert_to_df\n\n @staticmethod\n def filter_by_type(sequence, data_type):\n for element in sequence:\n if isinstance(element, data_type):\n yield element\n\n def __wrapper_parallel_load(func):\n\n def wrapped_parallel_load(self):\n variables, function, n_cpu = func(self)\n pool = Pool(n_cpu)\n multiprocess_output = pool.map(function, variables, n_cpu)\n pool.close()\n pool.join()\n return multiprocess_output\n\n return wrapped_parallel_load\n\n @__convert_to_df\n @__wrapper_parallel_load\n def __get_data(self):\n\n return self.input, self.load_function, self.cores\n\n def split_by(self, granularity):\n \"\"\"\n Splits and remove duplicates from the loaded table based on a columns list\n :param granularity:\n Type: list\n A list of columns for keep\n :return: pandas DataFrame\n \"\"\"\n return self.data[granularity].drop_duplicates().reset_index(drop=True)\n\n def __get_function(self):\n\n functions_dict = {'.json': pd.read_json,\n '.csv': pd.read_csv,\n '.xlsx': pd.read_excel,\n '.feather': pd.read_feather,\n '.parquet': pd.read_parquet}\n if not self.extension:\n return None\n else:\n return functions_dict.get(self.extension)\n\n\nclass DatabaseManagement:\n\n dtypes_dict = {'object': String,\n 'str': String,\n 'int64': Integer,\n 'int': Integer,\n 'float64': Float,\n 'float': Float,\n 'datetime64': DateTime,\n 'bool':\tBoolean}\n\n def __init__(self, username, password, dialect,\n host, port, database_name=None):\n\n self.url = engine.url.URL(**{'password': password,\n 'username': username,\n 'drivername': dialect,\n 'host': host,\n 'port': port,\n 'database': database_name})\n self.engine = self.url\n\n self.meta = MetaData()\n\n @property\n def engine(self):\n\n return self._engine\n\n @engine.setter\n def engine(self, url):\n\n self._engine = create_engine(url)\n\n def to_sql_copy(self, table_name, from_table, columns_kwargs):\n\n if isinstance(from_table, pd.DataFrame):\n\n columns_dict_base = self.__get_parameters_dict(from_table.dtypes.to_dict(),\n columns_kwargs)\n\n for key, item in columns_dict_base.items():\n columns_dict_base[key]['type'] = self.__pandas_to_sql_types(item['type'])\n\n selectable_columns = [self.__column_parameters(items) for items in columns_dict_base.items()]\n\n object_table = Table(table_name, self.meta, *selectable_columns)\n\n if not self.engine.dialect.has_table(self.engine, table_name):\n\n self.meta.create_all(self.engine)\n\n self.__copy_to_table(table_name, from_table, '#')\n\n def __copy_to_table(self, table_name, data, delimiter):\n\n self._open_process()\n statement = \"\\COPY {} from STDIN DELIMITER '{}';\\n\".format(table_name, delimiter)\n print(statement)\n # # COPY DATA IN NEWLY CREATED TABLE\n data = data.apply(lambda col: col.str.replace(delimiter, ' ') if col.dtype == 'object' else col, axis=0)\n data_str = data.to_csv(sep=delimiter, index=False, header=False).split('\\n')[:-1]\n self.psql.stdin.write(bytes(statement, 'utf-8'))\n [self.psql.stdin.write(line) for line in map(lambda row: bytes(row+'\\n', 'utf-8'), data_str)]\n self.psql.stdin.write(bytes(\"\\.\\n\", 'utf-8'))\n\n @staticmethod\n def __get_parameters_dict(main_dict, additional_dict, level_1_key='type'):\n\n output_dict = dict(zip(main_dict.keys(),\n zip(len(main_dict)*[level_1_key, ], main_dict.values())))\n\n output_dict = {key: [value, ] for key, value in output_dict.items()}\n\n for key in output_dict.keys():\n if key in additional_dict.keys():\n for item in additional_dict.get(key).items():\n output_dict.get(key).append(item)\n\n output_dict_w_kwargs = {key: dict(value) for key, value in output_dict.items()}\n\n return output_dict_w_kwargs\n\n @staticmethod\n def __column_parameters(items):\n\n column_name, args = items\n column_type = args.get('type')\n del args['type']\n extra_constraints = []\n if 'CheckConstraint' in args.keys():\n extra_constraints.append(CheckConstraint(args['CheckConstraint']))\n del args['CheckConstraint']\n\n return Column(column_name, column_type, *extra_constraints, **args)\n\n def _open_process(self):\n\n self.psql = Popen(['psql', str(self.url)], stdout=PIPE, stdin=PIPE)\n\n def __pandas_to_sql_types(self, type_to_convert):\n\n if isinstance(type_to_convert, dtype):\n\n type_to_convert = type_to_convert\n\n elif isinstance(type_to_convert, type):\n\n type_to_convert = type_to_convert.__name__\n\n return self.dtypes_dict.get(str(type_to_convert), Text)\n\n def drop_table(self):\n pass\n\n\nif __name__ == '__main__':\n \n # THIS IS A WIP SCRIPT USED TO MOVE DATA FROM INDIVIDUAL FILES\n # TO A POSTRES DATABASE IN THE CLOUD\n # data is on disk; few 100k files; each file represents a song\n\n paths = [i.path for idx, i in enumerate(scandir(r'/Users/********/PycharmProjects/udacity/data')) if idx < 500000]\n\n # data_for_upload = DataModel(paths, 'json', **{'typ': 'series'})\n\n # data has already been harvested and consolidated into a csv\n data_for_upload = DataModel(pd.read_csv('test.csv'))\n\n artists_data = data_for_upload.split_by(['artist_id', 'song_id', 'title', 'duration', 'year'])\n\n # Initializing the DatabaseNanagement class\n # db is hosted in by AWS RDS\n\n db = DatabaseManagement('********', '********',\n 'postgresql', '*******.cvrvhtkqtojs.us-east-2.rds.amazonaws.com',\n 5432, 'postgres')\n\n # COPY 50K RECORDS IN DB IN 5s\n # CREATES TABLE IF DOESNT EXIST\n\n db.to_sql_copy(\"songs_table\", artists_data, columns_kwargs={'artist_id':{'primary_key':False},\n 'song_id':{'nullable':False},\n 'year':{'nullable': True}})\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"453583838","text":"\"\"\"MultipleAppsProject URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.10/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url, include\nfrom django.contrib import admin\n\nurlpatterns = [\n url(r'^courses/', include('apps.courses.urls', namespace='courses')),\n url(r'^login_reg/',include('apps.login_reg.urls', namespace='login_reg')),\n url(r'^random_word/',include('apps.random_word_generator.urls', namespace='random_word')),\n url(r'^survey/',include('apps.survey.urls',namespace='survey')),\n url(r'^timedisplay/',include('apps.timedisplay.urls',namespace='timed'))\n]\n","sub_path":"Python/Django/MultipleAppsProject/MultipleAppsProject/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"319076985","text":"import pandas as pd\nimport freehead as fh\nimport numpy as np\nfrom scipy.signal import savgol_filter\nfrom collections import OrderedDict\nimport warnings\n\n\ndef prepend_nan(arr, axis=0, n=1):\n pad_shape = [s if i != axis else n for i, s in enumerate(arr.shape)]\n pad = np.full(pad_shape, np.nan, dtype=arr.dtype)\n return np.concatenate((pad, arr), axis=axis)\n\n\ndef apply_analysis_pipeline_for_all_trials(df: pd.DataFrame):\n\n warnings.filterwarnings('ignore', category=np.RankWarning)\n \n df.rename(columns={'shift_percent_approx': 'shift_percent'}, inplace=True)\n\n fh.array_apply(\n df,\n OrderedDict([\n # chosen so that to target direction is positive (right to left is positive angle in mathematics)\n ('direction_sign', lambda r: -1 if r['left_to_right'] else +1),\n ('fixation_led', lambda r: r['fixation_led'] if r['left_to_right'] else 254 - r['fixation_led']),\n (('df', 'target_led'), lambda df: df['fixation_led'] - df['direction_sign'] * df['amplitude']),\n (('df', 'starget_led'), lambda df: df['target_led'] - df['direction_sign'] * df['shift']),\n ('is_outward_response', lambda r: r['response'] == ('right' if r['left_to_right'] else 'left')),\n ('response_ward', lambda r: 'outward' if r['is_outward_response'] else 'inward'),\n ('correct_response', lambda r: None if r['shift'] == 0 else 'right' if (r['shift'] > 0) == r['left_to_right'] else 'left'),\n ('is_correct', lambda r: None if r['correct_response'] is None else r['correct_response'] == r['response']),\n ('shift_percent_uni', lambda r: r['shift_percent'] if r['left_to_right'] else -r['shift_percent']),\n # new time index for upsampling\n ('t_sacc', lambda r: np.arange(-400, 801, 5)),\n # pupil data in around saccade interval upsampled\n ('p_data_upsampled', lambda r: fh.interpolate_a_onto_b_time(r['p_data'][:, 2:5],\n 1000 * (r['p_data'][:, 0] - r['t_saccade_started']),\n r['t_sacc'], kind='linear')),\n # optotrak data upsampled\n ('o_data_upsampled', lambda r: fh.interpolate_a_onto_b_time(r['o_data'][:, 3:15],\n 1000 * (r['o_data'][:, 30] - r['t_saccade_started']),\n r['t_sacc'], kind='linear')),\n # latency of pupil signal\n ('pupil_latency', lambda r: fh.interpolate_a_onto_b_time(r['p_data'][:, 1] - r['p_data'][:, 0], 1000 * (\n r['p_data'][:, 0] - r['t_saccade_started']), r['t_sacc'], kind='linear')),\n # rotation of head rigidbody\n ('R_head_world', lambda r: r['helmet'].solve(r['o_data_upsampled'].reshape((-1, 4, 3)))[0]),\n # yaw pitch roll head rigidbody\n ('ypr_head_world', lambda r: fh.to_yawpitchroll(r['R_head_world'])),\n # reference positions of head rigidbody\n ('Ts_head_world', lambda r: r['helmet'].solve(r['o_data_upsampled'].reshape((-1, 4, 3)))[1]),\n # position of fixation led\n ('fixation_pos', lambda r: r['rig'][r['fixation_led'], :]),\n # position of target led\n ('target_pos', lambda r: r['rig'][r['target_led'], :]),\n # position of shifted target led\n ('starget_pos', lambda r: r['rig'][r['starget_led'], :]),\n # vector from eye to target position\n ('eye_to_fixation', lambda r: fh.to_unit(r['fixation_pos'] - r['Ts_head_world'][:, 3, :])),\n # vector from eye to target position\n ('eye_to_target', lambda r: fh.to_unit(r['target_pos'] - r['Ts_head_world'][:, 3, :])),\n # vector from eye to shifted target position\n ('eye_to_starget', lambda r: fh.to_unit(r['starget_pos'] - r['Ts_head_world'][:, 3, :])),\n # gaze vector in head without distortion correction\n ('gaze_in_head_distorted', lambda r: (r['R_eye_head'] @ r['p_data_upsampled'].T).T),\n # gaze vector in head with distortion correction\n ('gaze_in_head',\n lambda r: fh.normals_nonlinear_angular_transform(r['gaze_in_head_distorted'], r['nonlinear_parameters'])),\n # gaze angles in head\n ('gaze_in_head_ang', lambda r: np.rad2deg(fh.to_azim_elev(r['gaze_in_head']))),\n # gaze vector in world\n ('gaze_in_world', lambda r: np.einsum('tij,tj->ti', r['R_head_world'], r['gaze_in_head'])),\n # gaze angles in world\n ('gaze_in_world_ang', lambda r: np.rad2deg(fh.to_azim_elev(r['gaze_in_world']))),\n # angles from eye to target in world\n ('eye_to_target_ang', lambda r: np.rad2deg(fh.to_azim_elev(r['eye_to_target']))),\n # difference of eye to target angles and gaze in world\n ('gaze_angle_vs_target', lambda r: r['gaze_in_world_ang'] - r['eye_to_target_ang']),\n # angles from eye to shifted target in world\n ('eye_to_starget_ang', lambda r: np.rad2deg(fh.to_azim_elev(r['eye_to_starget']))),\n # difference of eye to shifted target angles and gaze in world\n ('gaze_angle_vs_starget', lambda r: r['gaze_in_world_ang'] - r['eye_to_starget_ang']),\n # angles from eye to fixation in world\n ('eye_to_fixation_ang', lambda r: np.rad2deg(fh.to_azim_elev(r['eye_to_fixation']))),\n # difference of eye to fixation angles and gaze in world\n ('gaze_angle_vs_fixation', lambda r: r['gaze_in_world_ang'] - r['eye_to_fixation_ang']),\n # time steps\n ('dt', lambda r: fh.padded_diff(r['t_sacc'])),\n # velocity of difference of eye to target angles and gaze in world\n ('gaze_angvel_vs_target', lambda r: fh.padded_diff(r['gaze_angle_vs_target']) / r['dt'][:, None]),\n ('gaze_angvel_vs_target_savgol',\n lambda r: prepend_nan(\n savgol_filter(r['gaze_angvel_vs_target'][1:, ...], 3, 1, axis=0),\n axis=0)),\n # saccade detection engbert & mergenthaler\n ('eng_merg', lambda r: fh.sacc_dec_engb_merg_horizontal(r['gaze_angle_vs_target'][:, 0],\n r['gaze_angvel_vs_target_savgol'][:, 0], 6, 5)),\n ]),\n add_inplace=True,\n print_log=True\n )\n\n df.drop(\n columns=[\n 'p_data',\n 'o_data',\n # 'helmet',\n 'o_data_upsampled',\n 'p_data_upsampled',\n 'gaze_in_head_distorted',\n ],\n inplace=True\n )\n","sub_path":"freehead/analysis/apply_analysis_pipeline_for_all_trials.py","file_name":"apply_analysis_pipeline_for_all_trials.py","file_ext":"py","file_size_in_byte":6775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"12658281","text":"\"\"\"\r\nValidate.\r\n\r\nHolds validate information.\r\n\r\nAttributes:\r\n - error (List)\r\n\r\nProperties:\r\n - success\r\n\"\"\"\r\n\r\n\r\nclass Validate:\r\n \"\"\"Validate.\"\"\"\r\n\r\n errors = []\r\n\r\n @property\r\n def success(self):\r\n \"\"\"Return bool if the validation was a sucess.\"\"\"\r\n if self.errors:\r\n return False\r\n return True\r\n","sub_path":"integrationhelper/validate.py","file_name":"validate.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"241834516","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# Make some random data to represent your r, g, b bands.\r\nny, nx = 2, 3\r\nr, g, b = [np.random.random(ny*nx).reshape((ny, nx)) for _ in range(3)]\r\n\r\nc = np.dstack([r,g,b])\r\nprint (c)\r\n\r\nplt.imshow(c, interpolation='nearest')\r\nplt.show()","sub_path":"animacja.py","file_name":"animacja.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"14236161","text":"#\n# Updated: 22-Aug-2018\n#\n\nfrom PIL import Image\nimport os\nimport imghdr\nfrom os import listdir\nfrom os.path import isfile, join\nimport ntpath\nimport errno\n\n\ndef is_jpg(some_file):\n result = False\n if imghdr.what(some_file) == 'jpeg':\n result = True\n return result\n\n\ndef is_png(some_file):\n result = False\n if imghdr.what(some_file) == 'png':\n result = True\n return result\n\n\ndef is_valid_image(some_file):\n result = True\n try:\n im = Image.open(some_file)\n im.close()\n except IOError:\n result = False\n return result\n\n\ndef is_valid_jpg(some_file):\n result = False\n if is_valid_image(some_file) and is_jpg(some_file):\n result = True\n return result\n\n\ndef is_valid_png(some_file):\n result = False\n if is_valid_image(some_file) and is_png(some_file):\n result = True\n return result\n\n\ndef make_white_bg_transparent(img_file):\n img = Image.open(img_file)\n os.remove(img_file)\n img = img.convert(\"RGBA\")\n datas = img.getdata()\n\n newData = []\n for item in datas:\n if item[0] > 253 and item[1] > 253 and item[2] > 253:\n newData.append((255, 255, 255, 0))\n else:\n newData.append(item)\n\n img.putdata(newData)\n new_file_name = os.path.splitext(img_file)[0]+'.png'\n img.save(new_file_name, \"PNG\")\n return new_file_name\n\n\ndef convert_image_file_to_jpg(img_file):\n \"\"\"\n Creates JPEG file from any image file\n img_file : String\n The name of source file\n \"\"\"\n img = Image.open(img_file).convert('RGB')\n os.remove(img_file)\n new_file_name = os.path.splitext(img_file)[0]+'.jpg'\n img.save(new_file_name, 'jpeg')\n return new_file_name\n\n\ndef convert_image_file_to_png(img_file):\n \"\"\"\n Creates PNG file from any image file\n img_file : String\n The name of source file\n \"\"\"\n img = Image.open(img_file)\n os.remove(img_file)\n new_file_name = os.path.splitext(img_file)[0]+'.png'\n img.save(new_file_name, 'png')\n return new_file_name\n\n\ndef get_files_names_in_folder(some_folder):\n return [f for f in listdir(some_folder) if isfile(join(some_folder, f))]\n\n\ndef get_subfolders(some_folder):\n return [f for f in listdir(some_folder) if os.isdir(join(some_folder, f))]\n\n\ndef get_files_in_folder(some_folder):\n result = []\n for this_file in get_files_names_in_folder(some_folder):\n this_file_path = some_folder + \"/\" + this_file\n result.append(this_file_path)\n return result\n\n\ndef get_valid_pngs(some_folder):\n result = []\n all_files = get_files_names_in_folder(some_folder)\n for this_file in all_files:\n file_path = some_folder + \"/\" + this_file\n if is_valid_png(file_path):\n result.append(file_path)\n return result\n\n\ndef sort_images(some_folder):\n result = {'jpg': [], 'png': [], 'None': []}\n for some_file in get_files_in_folder(some_folder):\n if is_valid_image(some_file):\n if is_jpg(some_file):\n result['jpg'].append(some_file)\n else:\n if is_png(some_file):\n result['png'].append(some_file)\n else:\n result['None'].append(some_file)\n else:\n result['None'].append(some_file)\n return result\n\n\ndef get_file_name_from_path(some_path):\n return ntpath.basename(some_path)\n\n\ndef rotated_copy(original_image_file, folder_to_store, rotation_angle):\n img_pre = Image.open(original_image_file)\n img = img_pre.rotate(rotation_angle, expand=True)\n original_name_ext_cut = os.path.splitext(get_file_name_from_path(\n original_image_file))[0]\n new_img_name = folder_to_store + \\\n \"/\" + original_name_ext_cut + \\\n \"_\" + str(rotation_angle) + \".jpg\"\n img.save(new_img_name)\n return new_img_name\n\n\ndef rotated_copies(original_image_file, folder_to_store, rotation_angles):\n result = []\n for some_angle in rotation_angles:\n result.append(\n rotated_copy(\n original_image_file, folder_to_store, some_angle))\n return result\n\n\ndef mirror_top_bottom_copy(original_image_file, folder_to_store):\n img = Image.open(original_image_file).transpose(Image.FLIP_TOP_BOTTOM)\n original_name_ext_cut = os.path.splitext(\n get_file_name_from_path(original_image_file))[0]\n new_img_name = folder_to_store + \"/\" + \\\n original_name_ext_cut + \"_ft\" + \".jpg\"\n img.save(new_img_name)\n return new_img_name\n\n\ndef grayscale_copy(original_image_file, folder_to_store):\n img = Image.open(original_image_file).convert('LA').convert('RGB')\n original_name_ext_cut = os.path.splitext(\n get_file_name_from_path(original_image_file))[0]\n new_img_name = folder_to_store + \"/\" + original_name_ext_cut + \\\n \"_gs\" + \".jpg\"\n img.save(new_img_name, 'jpeg')\n return new_img_name\n\n\ndef monochrome_copy(original_image_file, folder_to_store):\n img = Image.open(original_image_file).convert('1').convert('RGB')\n original_name_ext_cut = os.path.splitext(\n get_file_name_from_path(original_image_file))[0]\n new_img_name = folder_to_store + \"/\" + original_name_ext_cut + \\\n \"_mc\" + \".jpg\"\n img.save(new_img_name, 'jpeg')\n return new_img_name\n\n\ndef resize_file(original_image_file, output_image_file, maxw, maxh):\n \"\"\"\n Creates resized image file from given one\n original_image_file : String\n The name of source file\n output_image_file : String\n The name of file to save the result\n maxw :\n Max allowed width\n maxw :\n Max allowed height\n \"\"\"\n im = Image.open(original_image_file)\n width, height = im.size\n ratio = min(float(maxw) / int(width), float(maxh) / int(height))\n im = im.resize((int(width*ratio), int(height*ratio)), Image.ANTIALIAS)\n im.save(output_image_file, \"JPEG\")\n return output_image_file\n\n\ndef put_into_rect(original_image_file, output_image_file, rw, rh):\n im = Image.open(original_image_file)\n width, height = im.size\n ratio = min(float(rw) / int(width), float(rh) / int(height))\n im = im.resize((int(width*ratio), int(height*ratio)), Image.ANTIALIAS)\n\n resim = Image.new('RGB', (rw, rh), (255, 255, 255))\n width, height = im.size\n offset = ((rw - width) / 2, (rh - height) / 2)\n resim.paste(im, offset)\n resim.save(output_image_file, \"JPEG\")\n return output_image_file\n\n\ndef cut_area_around(original_image_file, x, y, w, h, output_file=False):\n \"\"\"\n Razor area around the dot (x, y)\n \"\"\"\n im = Image.open(original_image_file)\n width, height = im.size\n left = max(int(round(x-(w/2))), 0)\n box_width = min(w, width-left)\n top = max(int(round(y-(h/2))), 0)\n box_height = min(h, height-top)\n croped = im.crop((left, top, box_width+left, box_height+top))\n mode_type = \"PNG\" if is_png(original_image_file) else \"JPEG\"\n dw, dh = get_dimensions(croped)\n result = croped if dw*dh > 0 else False\n if output_file and result:\n save_image(croped, output_file, mode_type)\n return result\n\n\ndef get_dimensions(image):\n \"\"\"\n Return image dimensions tuple\n Usage example:\n width, height = imm.get_dimensions(image_file)\n or\n width, height = imm.get_dimensions(image_object)\n \"\"\"\n im = image\n if isinstance(image, basestring):\n im = Image.open(image)\n return im.size\n\n\ndef save_image(image_object, file_path, mode_type=\"JPEG\"):\n \"\"\"\n Saves image object to the file.\n In will create the directory if one does not exist.\n \"\"\"\n if not os.path.exists(os.path.dirname(file_path)):\n try:\n os.makedirs(os.path.dirname(file_path))\n except OSError as exc: # Guard against race condition\n if exc.errno != errno.EEXIST:\n raise\n image_object.save(file_path, mode_type)\n\n\ndef cut_tending_area(original_image_file, x, y, w, h, output_file=False):\n \"\"\"\n Cuts rectangle area around the dot (x, y). If area boundaries are out of\n image dimenssions then area center will be moved on order to put the area\n into image.\n original_image_file : String\n The name of source file\n output_file : String [optional]\n The name of file to save the result\n It is False by default, you may leave it empty if you don't need to\n save file.\n w :\n Rectangle area width\n h :\n Rectangle area height\n \"\"\"\n im = Image.open(original_image_file)\n width, height = im.size\n result = False\n if w <= width and h <= height:\n if x < w/2:\n x = int(round(w/2))\n if x + w/2 > width:\n x = int(width - round(w/2))\n if y < h/2:\n y = int(round(h/2))\n if y + h/2 > height:\n y = int(round(height - h/2))\n box_x = int(round(x-w/2))\n box_y = int(round(y-h/2))\n croped = im.crop((box_x, box_y, box_x+w, box_y+h))\n mode_type = \"PNG\" if is_png(original_image_file) else \"JPEG\"\n if output_file:\n save_image(croped, output_file, mode_type)\n result = croped\n return result\n","sub_path":"imm.py","file_name":"imm.py","file_ext":"py","file_size_in_byte":9106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"116071354","text":"import random\nimport sys\nimport os\n\nimport datavars\nimport dataprovider\n\nsys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '..'))\nfrom commonfunc import get_timestamp_by_time\n\n\nclass QosBufferingCleaned(dataprovider.Dataprovider):\n\n tablename = 'input_qos_buffering_cleaned'\n\n @classmethod\n def gettablename(cls):\n return cls.tablename\n\n def makedata(self):\n data_format = '%s,%d,%s,%s,itsavvidstring,%s,1111,222,%d,%d\\n'\n with open(os.path.abspath(os.path.dirname(__file__)) + '/QosBufferingCleaned.txt', 'w') as filedemanddata:\n for i in range(24):\n for j in [2, 6, 15, 26]:\n id = datavars.id_range[random.randint(0,14)]\n peerid = datavars.peeid_range[random.randint(0,9)]\n timestamp = get_timestamp_by_time(datavars.time_format% (i, j))\n url = datavars.url_range[random.randint(0,4)]\n type = datavars.type_range[random.randint(0, 3)]\n line = data_format % (\n id, int(timestamp), peerid, url, type, int(timestamp)+random.randint(1,100),\n int(timestamp) + random.randint(100,10000))\n filedemanddata.write(line)\n return os.path.abspath(os.path.dirname(__file__)) + '/QosBufferingCleaned.txt'\n","sub_path":"lib/platform/dataprocess/testdata/QosBufferingCleaned.py","file_name":"QosBufferingCleaned.py","file_ext":"py","file_size_in_byte":1353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"299705461","text":"# coding=utf-8\r\nfrom __future__ import unicode_literals, print_function\r\nimport pymongo\r\nfrom base import SinaBaseObject\r\nimport sina_weibo\r\nimport sina_people\r\nimport sys\r\nreload(sys)\r\nsys.setdefaultencoding('utf-8')\r\n\r\n\r\n# 类转化为字典\r\ndef class_to_dict(obj):\r\n is_list = obj.__class__ == [].__class__\r\n is_set = obj.__class__ == set().__class__\r\n\r\n if is_list or is_set:\r\n obj_arr = []\r\n for o in obj:\r\n dict1 = {}\r\n dict1.update(o.__dict__)\r\n obj_arr.append(dict1)\r\n return obj_arr\r\n else:\r\n dict1 = {}\r\n dict1.update(obj.__dict__)\r\n return dict1\r\n\r\n\r\nclass SinaStore(SinaBaseObject):\r\n def __init__(self):\r\n super(SinaStore, self).__init__()\r\n self.is_first = True\r\n\r\n self.mongo_client = pymongo.MongoClient('localhost', 27017)\r\n self.db = self.mongo_client['Weibo']\r\n self.weibo_table = self.db['try3']\r\n\r\n # 递归分解传入的类 直至到原子项\r\n def analyze_data(self, data, dict0={}):\r\n\r\n if isinstance(data, list):\r\n for _item in data:\r\n self.analyze_data(_item)\r\n elif hasattr(data, '__dict__'):\r\n for name, value in vars(data).items():\r\n try:\r\n dict0[name] = ''\r\n self.analyze_data(value, dict0=dict0[name])\r\n except:\r\n pass\r\n else:\r\n pass\r\n return data\r\n\r\n def store_in_mongodb(self, data):\r\n result = {}\r\n # 存储新浪用户类\r\n if isinstance(data, sina_people.SinaPeople):\r\n for name, value in vars(data).items():\r\n if unicode(name) != unicode('weibo_list'):\r\n if not isinstance(value, list):\r\n result[str(name)] = str(value)\r\n else:\r\n result[str(name)] = {}\r\n for index, item in enumerate(value):\r\n result[str(name)][str(index)] = {}\r\n for name2, value2 in item.items():\r\n result[str(name)][str(index)][str(name2)] = str(value2)\r\n else:\r\n result[str(name)] = {}\r\n print(type(value))\r\n for index0, item0 in enumerate(value):\r\n result[str(name)][str(index0)] = {}\r\n for name2, value2 in vars(item0).items():\r\n if not isinstance(value2, list):\r\n result[str(name)][str(index0)][str(name2)] = str(value2)\r\n else:\r\n for index, item in enumerate(value2):\r\n result[str(name)][str(index0)][str(name2)] = {}\r\n result[str(name)][str(index0)][str(name2)][str(index)] = {}\r\n for name3, value3 in item.items():\r\n result[str(name)][str(index0)][str(name2)][str(index)][str(name3)] = str(value3)\r\n\r\n # 存储新浪微博类\r\n elif isinstance(data, sina_weibo.SinaWeibo):\r\n for name, value in vars(data).items():\r\n print(name, type(value))\r\n if not isinstance(value, list):\r\n result[str(name)] = str(value)\r\n else:\r\n result[str(name)] = {}\r\n for index, item in enumerate(value):\r\n print(index, type(item))\r\n result[str(name)][str(index)] = {}\r\n for name2, value2 in item.items():\r\n result[str(name)][str(index)][str(name2)] = str(value2)\r\n\r\n elif isinstance(data, dict):\r\n result = data\r\n else:\r\n raise TypeError+\"非法类型!\"\r\n\r\n self.weibo_table.insert_one(result)\r\n\r\n def get_human_info(self):\r\n for data in self.weibo_table.find():\r\n yield data\r\n\r\n def get_stored_information(self):\r\n for data in self.weibo_table.find():\r\n yield data\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"wbcls/sina_store.py","file_name":"sina_store.py","file_ext":"py","file_size_in_byte":4203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"390223984","text":"# -*- coding: utf-8 -*-\n\nimport logging\nfrom logging.config import dictConfig\n\ndef config(software, level):\n root = logging.getLogger()\n root.setLevel(level)\n if software == 'GoogleAppEngine':\n return\n dictConfig({\n 'version': 1,\n 'formatters': {'default': {\n 'format': '%(asctime)s '\n '%(levelname)8s: '\n '%(message)s '\n '<%(name)s:%(filename)s:%(lineno)d>',\n 'datefmt': '%Y-%m-%d %H:%M:%S',\n }},\n 'handlers': {\n 'default': {\n 'class': 'logging.StreamHandler',\n 'stream': 'ext://sys.stdout',\n 'formatter': 'default'\n },\n },\n 'root': {\n 'handlers': ['default']\n }\n })\n # chardet decode() logs TMI on DEBUG level.\n chardet_logger = logging.getLogger('chardet.charsetprober')\n chardet_logger.setLevel('WARNING')\n urllib3_logger = logging.getLogger('urllib3.connectionpool')\n urllib3_logger.setLevel('WARNING')\n werkzeug = logging.getLogger('werkzeug')\n werkzeug.setLevel('WARNING')\n if software.startswith('gunicorn/'):\n '''\n The logger of logging is about how logs are inputted.\n The handler of logging is about how logs are outputted.\n So if you want to write logs by root logger, and print them by gunicorn,\n you should register gunicorn handlers(output) on root logger(input).\n Logger class : gunicorn.glogging.Logger\n '''\n gunicorn_logger = logging.getLogger('gunicorn.error')\n root.handlers = gunicorn_logger.handlers\n root.setLevel(gunicorn_logger.level)\n","sub_path":"apps/common/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":1688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"113192698","text":"import json\nimport re\nimport os\nimport glob\nfrom matplotlib import pyplot as plt\n\n\ndef read_json(file_name):\n f = open(file_name, \"r\")\n json_dict = json.load(f)\n\n return json_dict['SNR'], json_dict['BER']\n\n\ndef main2():\n fig = plt.figure()\n ax = fig.add_subplot(111)\n\n fn_list = glob.glob(\"./*.json\")\n for fn in fn_list:\n snr, ber = read_json(fn)\n ax.plot(snr, ber, label=fn)\n\n ax.set_yscale(\"log\")\n ax.set_xlim([0, 30])\n ax.set_ylim([1e-5, 1])\n\n ax.set_xlabel(\"SNR\")\n ax.set_ylabel(\"BER\")\n\n ax.legend()\n ax.grid()\n\n plt.savefig(re.sub(\".py\", \"\", os.path.basename(__file__))+\".png\")\n\n\ndef main():\n snr, ber = read_json(\"./BER_MMSE\")\n\n fig = plt.figure()\n ax = fig.add_subplot(111)\n\n ax.plot(snr, ber)\n\n ax.set_yscale(\"log\")\n ax.set_xlim([0, 30])\n ax.set_ylim([1e-5, 1])\n\n ax.text(x=15, y=5*(1e-4),\n s=\"SNR=\" + str(int(snr[0]))+\" -> BER=\"+str(ber[0]),\n ha='center', fontsize=12)\n\n ax.text(x=15, y=2*(1e-4),\n s=\"SNR=\" + str(int(snr[-1]))+\" -> BER=\"+str(ber[-1]),\n ha='center', fontsize=12)\n\n ax.set_xlabel(\"SNR\")\n ax.set_ylabel(\"BER\")\n\n ax.grid()\n\n plt.savefig(re.sub(\".py\", \"\", os.path.basename(__file__))+\".png\")\n\nif __name__ == '__main__':\n main2()\n","sub_path":"3教科書/MU-MIMOの基礎/src/昔の/BER_SIC/plt_BER_SIC_MMSE.py","file_name":"plt_BER_SIC_MMSE.py","file_ext":"py","file_size_in_byte":1295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"360387529","text":"# searcher.py\nimport json\nfrom flask import Flask\nimport pymongo\nfrom nltk.corpus import stopwords\nfrom collections import Counter\nstop_words = set(stopwords.words('english'))\nfrom math import log10\nfrom sklearn.metrics.pairwise import cosine_similarity\n\nclass Searcher():\n\n def __init__(self):\n self.search = \"\"\n\n def tf_idf_query(self, db):\n tf_idfDict = {}\n searchQuery = self.queryWordFreqCounter(self.search)\n for word, count in searchQuery.items():\n collection = db[word].find_one({\"idf\": {\"$gt\": 0}})\n if collection != None:\n idf = collection['idf']\n tf = (1 + log10(count))\n tf_idf = tf * idf\n tf_idfDict[word]= tf_idf\n else:\n pass\n return tf_idfDict\n\n def cosine_similarity(self, db):\n scores = []\n tf_idfQueDict = self.tf_idf_query(db)\n for word, tf_idfQue in tf_idfQueDict.items():\n for collection in db[word].find({\"tf_idf\": {\"$gt\": 0}}):\n loc = collection['location']\n tf_idfDoc = collection['tf_idf']\n docLen = collection['docLen']\n score = (tf_idfQue * tf_idfDoc)/collection['docLen']\n scores.append([loc, score])\n scores = sorted(scores, key=lambda score:score[1], reverse=True)\n finalScores = Counter(score[0] for score in scores)\n [score for score in scores if finalScores[score[0]] == 1]\n return finalScores\n\n def queryWordFreqCounter(self, query):\n searchWords = []\n words = query.split()\n for word in words:\n if len(word) > 0 and word.isalnum() and word not in stop_words:\n searchWords.append(word)\n return dict(Counter(searchWords))\n\n def getSearchInput(self):\n search = \"\"\n search = input(\"Input Search:\\n\")\n self.search = search\n\n def tf(self, wordFrequency):\n return(1 + log10(wordFrequency))\n\n def results(self, db, search):\n if len(search.split()) > 1:\n return(self.cosine_similarity(db))\n else:\n scores = []\n for files in db[search].find():\n scores.append([files['location'], self.tf(files['frequency'])])\n scores = sorted(scores, key=lambda score:score[1], reverse=True)\n return scores\n\n\n\nif __name__ == \"__main__\":\n client = pymongo.MongoClient(\"mongodb://localhost:27017/\")\n db = client[\"WEBPAGES\"]\n\n engine = Searcher()\n engine.getSearchInput()\n scores = dict(engine.results(db, engine.search))\n with open('{json file of webpage name and number from given data}') as bookkeeping:\n book = json.load(bookkeeping)\n\n print(\"========================\")\n print(\"====== Results =========\")\n counter = 1\n for key, value in scores.items():\n print(\"\\n\", counter, \". \", book[key])\n counter = counter + 1\n print(\"========================\")\n","sub_path":"searcher.py","file_name":"searcher.py","file_ext":"py","file_size_in_byte":2978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"291993171","text":"\"\"\"\nHW3: 3D Meshes\nComp 630 W'16 - Computer Graphics\nPhillips Academy\n2015-1-8\n\nBy Jenny Huang\n\"\"\"\n\nfrom gfx_helper_mayavi import *\n\ndef main():\n \"\"\"\n Plots several 3D shapes in different octants of space.\n \"\"\"\n fig = setUpFigure()\n\n (cubeVerts, cubeTris) = cube()\n (ellVerts, ellTris) = ell()\n (prismVerts, prismTris) = prism(5)\n (cylinderVerts, cylinderTris) = prism(12)\n (sphereVerts, sphereTris) = sphere(6)\n (torusVerts, torusTris) = torus(4)\n\n drawTriMesh(cubeVerts + np.array([[2.5, 2.5, 2.5]]).T, cubeTris, fig,\n edges=True, normals=True)\n drawTriMesh(ellVerts + np.array([[-2.5, 2.5, 2.5]]).T, ellTris, fig,\n edges=True, normals=True)\n drawTriMesh(prismVerts + np.array([[-2.5, -2.5, 2.5]]).T, prismTris, fig,\n edges=True, normals=True)\n drawTriMesh(cylinderVerts + np.array([[2.5, -2.5, 2.5]]).T, cylinderTris, fig,\n edges=True, normals=True)\n drawTriMesh(sphereVerts + np.array([[2.5, 2.5, -2.5]]).T, sphereTris, fig,\n edges=True, normals=True)\n drawTriMesh(torusVerts + np.array([[-2.5, 2.5, -2.5]]).T, torusTris, fig,\n edges=True, normals=True)\n\n showFigure(fig)\n\n fig2 = setUpFigure()\n (jhuangVerts, jhuangTris) = jhuang_shape(4)\n drawTriMesh(jhuangVerts, jhuangTris, fig2, edges=True, normals=True)\n showFigure(fig2)\n\n\ndef cube():\n \"\"\"\n Returns a 2-tuple (verts, tris) representing a triangle mesh of the surface\nof a \"unit cube\". verts is 3x8 and tris is 12x3. See cubeVerts().\n \"\"\"\n tris = np.array([[0,1,2],\n [0,2,3],\n [5,6,1],\n [6,2,1],\n [4,6,5],\n [7,6,4],\n [0,7,4],\n [0,3,7],\n [5,1,4],\n [1,0,4],\n [2,6,3],\n [3,6,7]])\n return (cubeVerts(), tris)\n\n\ndef cubeVerts():\n \"\"\"\n Returns a 3x8 array of the eight vertices of the \"unit cube\". In analogy with\nthe unit circle, it has \"radius\" 1 --- that is, the edges all have length 2.\n \"\"\"\n return np.array([[ 1, 1, 1],\n [-1, 1, 1],\n [-1,-1, 1],\n [ 1,-1, 1],\n [ 1, 1,-1],\n [-1, 1,-1],\n [-1,-1,-1],\n [ 1,-1,-1]]).T\n\ndef ell():\n \"\"\"\n Returns a 2-tuple (verts, tris) representing a triangle mesh of the surface of\nan L shape. verts is 3x12 and tris is 20x3. See ellVerts().\n \"\"\"\n tris = np.array([[0,1,2],\n [0,2,3],\n [0,3,4],\n [0,4,5],\n [8,7,6],\n [9,8,6],\n [10,9,6],\n [11,10,6],\n [7,8,1],\n [8,2,1],\n [9,2,8],\n [3,2,9],\n [4,9,10],\n [3,9,4],\n [10,11,4],\n [4,11,5],\n [5,11,6],\n [5,6,0],\n [6,7,1],\n [6,1,0]])\n return (ellVerts(), tris)\n\n\ndef ellVerts():\n \"\"\"\n Returns a 3x12 array of the 12 vertices of an L shape, like three cubes\nattached to each other. The edge length of each cube is 1, the whole shape is\ncentered on the origin, and the L lies parallel to the X-Y plane.\n \"\"\"\n L = np.array([[ 0, 0, 0.5],\n [ 0, 1, 0.5],\n [-1, 1, 0.5],\n [-1,-1, 0.5],\n [ 1,-1, 0.5],\n [ 1, 0, 0.5]]).T\n return np.concatenate((L, L + np.array([[0,0,-1]]).T), 1)\n\n\ndef prism(K):\n \"\"\"\n Returns a 2-tuple (verts, tris) representing a triangle mesh of the surface\nof a regular K-gon prism. verts is 3x(2K) and tris is (4K-4)x3. See\nprismVerts().\n \"\"\"\n top = np.fliplr(fanDiskTriangles(K,0))\n bottom = fanDiskTriangles(K,K)\n\n sideBot = np.arange(K)\n sideTop = np.arange(K) + K\n preSide = triangleStrip(sideBot, sideTop)\n lastTris = np.array([[2*K-1,K-1,0],[K,2*K-1, 0]])\n side = np.concatenate((preSide, lastTris),0)\n\n tris = np.concatenate((top, bottom, side), 0)\n return (prismVerts(K), tris)\n\n\ndef prismVerts(K):\n \"\"\"\n Returns a 3x(2K) array representing vertices of a regular K-gon prism. The\nprism is centered on the origin, has height 2 along an axis parallel to the Y-\naxis, and has \"radius\" 1: all the vertices are a distance 1 from this axis. The\npoints (1,1,0) and (1,-1,0) should always be vertices of the prism.\n \"\"\"\n cap = np.concatenate((\n [np.cos(np.linspace(0, 2*np.pi, K, False))],\n np.ones((1,K)),\n [np.sin(np.linspace(0, 2*np.pi, K, False))]\n ), 0);\n return np.concatenate((cap, cap + np.array([[0,-2,0]]).T), 1)\n\n\ndef sphere(K):\n \"\"\"\n Returns a 2-tuple (verts, tris) representing a triangle mesh of the surface of\na unit sphere. verts is 3x(2 + (K+1)(K+3)) and tris is ((2K+2)(K+3))x3. See\nsphereVerts().\n \"\"\"\n\n # Top and Bottom of sphere.\n bottom = wheelDiskTriangles(K+3)\n top = np.fliplr(wheelDiskTriangles(K+3, 1+ (K+1)*(K+3), (K+1)*(K+3) -(K+1)-1))\n\n # Create triangle strip based on top and bottom arrays.\n t = (np.arange(K*(K+3)+1)+1)%(2 + (K+1)*(K+3))\n b = (np.arange(K*(K+3)+1) + K+3 + 1)%(2 + (K+1)*(K+3))\n sides = triangleStrip(b,t)\n\n # Adjust so the triangles are consistent with the spherical cycle.\n sides = sides[:-1]\n last = (np.array([[K+3, K+4, 1]]))\n sides = np.concatenate((last, sides),0)\n\n # Combine all together.\n tris = np.concatenate((bottom, sides, top), 0)\n return (sphereVerts(K), tris)\n\n\ndef sphereVerts(K):\n \"\"\"\n Returns a 3x(2 + (K+1)(K+3)) array representing vertices on the surface of the\nunit sphere, centered at the origin. The sampling on the sphere follows a\n\"latitude/longitude\" pattern: there are K+1 lines of latitude, and K+3 lines of\nlongitude, equally distributed around the sphere. There's one vertex at each\npole (2 verts total), plus one more at each lat/lon intersection (that's\n(K+1)(K+3) additional verts).\n The north and south poles are at (0,1,0) and (0,-1,0), respectively, and the\n\"prime meridian\" (which should always be included) runs between the poles\nthrough the point (1,0,0). (This means that your sphere should always include\nat least K+3 points whose Z-coordinate is 0 and whose X-coordinate is\nnon-negative: the poles, plus the K+1 vertices along the prime meridian.)\n \"\"\"\n grid_XZ = (\n np.concatenate((\n np.cos(np.linspace(0, 2*np.pi, K+3, False))[None, :, None],\n np.sin(np.linspace(0, 2*np.pi, K+3, False))[None, :, None]), 2) *\n np.cos(np.linspace(-np.pi/2, np.pi/2, K+2, False))[1:, None, None]\n ).reshape((-1,2))\n grid_Y = (\n np.ones((1, K+3, 1)) *\n np.sin(np.linspace(-np.pi/2, np.pi/2, K+2, False))[1:, None, None]\n ).reshape((-1,1))\n grid = np.concatenate((grid_XZ[:,0,None], grid_Y, grid_XZ[:,1,None]), 1)\n return np.concatenate(([[0,-1,0]], grid, [[0,1,0]]), 0).T\n\n\ndef torus(K):\n \"\"\"\n Returns a 2-tuple (verts, tris) representing a triangle mesh of the surface of\na torus. verts is 3x((K+3)^2) and tris is (2(K+3)^2)x3. See torusVerts().\n \"\"\"\n t = (np.arange((K+3)**2+1))%((K+3)**2)\n b = (np.arange((K+3)**2+1) + K+3)%((K+3)**2)\n tris = triangleStrip(b, t)\n return (torusVerts(K), tris)\n\n\ndef torusVerts(K):\n \"\"\"\n Returns a 3x((K+3)^2) array representing vertices on the surface of a torus\nlying parallel to the X-Y plane, centered at the origin. The overall diameter\nis 2, and the diameter of the inner hole is 2/3. The point (1,0,0) should\nalways be included --- this is the intersection of two circles, other points on\nwhich should also be included in the torus surface. One circle is the unit\ncircle in the X-Y plane, and the other is perpendicular to it, in the X-Z plane,\nwith radius 1/3.\n \"\"\"\n wand = np.concatenate((\n (np.cos(np.linspace(0, 2*np.pi, K+3, False))[None, :, None] + 2)/3,\n (np.cos(np.linspace(0, 2*np.pi, K+3, False))[None, :, None] + 2)/3,\n np.sin(np.linspace(0, 2*np.pi, K+3, False))[None, :, None]/3\n ), 2)\n sweep = np.concatenate((\n np.cos(np.linspace(0, 2*np.pi, K+3, False))[:, None, None],\n np.sin(np.linspace(0, 2*np.pi, K+3, False))[:, None, None],\n np.ones((K+3, 1, 1))\n ), 2)\n return (wand * sweep).reshape((-1,3)).T\n\ndef jhuang_shape(K):\n \"\"\"\n Returns a 2-tuple (verts, tris) representing a triangle mesh of the surface of\na J shape. verts is 3x(2K+14) and tris is (4K+16)x3. See jhuang_verts().\n \"\"\"\n # Triangles for straight edge sections.\n edges = np.array([[0,1,6],\n [6,1,5],\n [1,2,3],\n [1,3,4],\n [7,0,6],\n [7,8,0],\n [0,8,1],\n [8,9,1],\n [9,2,1],\n [2,9,10],\n [2,10,3],\n [10,11,4],\n [3,10,4],\n [6,5,13],\n [13,5,12],\n [13,12,7],\n [7,12,8],\n [9,8,10],\n [8,11,10],\n [7,6,13]])\n\n # Triangles for curve section.\n # Wheel that does not loop around.\n front = wheelDiskTriangles(K,1,14)[:-1]\n back = np.fliplr(wheelDiskTriangles(K, 8, K+14))[:-1]\n\n # Side triangle strip.\n sideBot = np.arange(K) + 14\n sideTop = np.arange(K) + K+14\n side = np.fliplr(triangleStrip(sideBot, sideTop))\n\n tris = np.concatenate((edges, front, back, side), 0)\n return (jhuang_verts(K), tris)\n\n\ndef jhuang_verts(K):\n \"\"\"\n Returns a 3x(2K+14) array representing vertices on the surface of the letter\nJ lying parallel to the X-Y plane, centered at the origin. The shape has a\nthickness of 1, height of 2, and width of 1.5. The J is made up of a quarter\ncylinder at the corner with rectangular prism legs. There are K vertices that\nmake up the curve from the top/bottom of the quarter cylinder.\n \"\"\"\n edges = np.array([[ 0.5, 1, 0.5],\n [ 0.5, -0.5, 0.5],\n [-0.5, -0.5, 0.5],\n [-0.5, -1, 0.5],\n [ 0.5, -1, 0.5],\n [ 1, -.5, 0.5],\n [1, 1, 0.5]]).T\n edges = np.concatenate((edges, edges + np.array([[0,0,-1]]).T), 1)\n\n # Finds equally distributed angles for quarter circle.\n angles = np.linspace(np.pi*3.0/2, 2*np.pi, K)\n\n # Finds respective points according to angle\n xValues = 0.5*(np.cos(angles)) + 0.5\n yValues = 0.5*np.sin(angles) - 0.5\n zValues = np.repeat([0.5],K).T\n curve = np.concatenate(([xValues], [yValues], [zValues]), 0)\n curve = np.concatenate((curve, curve + np.array([[0,0,-1]]).T), 1)\n\n return np.concatenate((edges, curve), 1)\n\n\ndef fanDiskTriangles(K, start=0, flip=False):\n \"\"\"\n Returns a 3x(K-2) array of vertex indices for the triangulation of a K-polygon\nin the plane, with indices numbered counterclockwise. Arguments:\n - K: number of vertices in the polygon.\n - start (default 0): the starting index of the K consecutive indices around\n the polygon.\n - flip (default False): when False, triangles are oriented right-handed /\n counterclockwise; when True, they are left-handed / clockwise.\n \"\"\"\n row1 = np.repeat(start, K-2).reshape(-1,1)\n a = np.array([start+1,start+2])\n b = np.arange(K-2).reshape(-1,1)\n tris = np.concatenate((row1, a+b), 1)\n if flip:\n tris = np.fliplr(tris)\n return tris\n\ndef wheelDiskTriangles(K, hub=0, start=1, flip=False):\n \"\"\"\n Returns a 3xK array of vertex indices for the triangulation of a K-polygon\nin the plane, with a central \"hub\" vertex and K vertices in a loop around it,\nnumbered counterclockwise. Arguments:\n - K: number of vertices around the outside of the polygon.\n - hub (default 0): the index of the vertex in the middle of the disk.\n - start (default 1): the starting index of the K consecutive indices around\n the polygon.\n - flip (default False): when False, triangles are oriented right-handed /\n counterclockwise; when True, they are left-handed / clockwise.\n \"\"\"\n row1 = np.repeat(hub, K-1).reshape(-1,1)\n a = np.array([start,start+1])\n b = np.arange(K-1).reshape(-1,1)\n notTris = np.concatenate((row1, a+b), 1)\n lastTri = np.array([[hub,K + start-1, start]])\n tris = np.concatenate((notTris, lastTri), 0)\n if flip:\n tris = np.fliplr(tris)\n return tris\n\n\ndef indexLoop(idx):\n \"\"\"\n Given a 1-D array or list, returns the same as a 1-D array with element #0\nrepeated at the end.\n \"\"\"\n return np.concatenate((idx, [idx[0]]), 0)\n\ndef triangleStrip(bot, top):\n \"\"\"\n Given two 1-D arrays or lists (each of length N) of vertex indices (bot and\ntop), returns a 3x(2(N-1)) array of indices, each row of which is a triangle in\na zigzagging strip between these parallel sets of indices:\n\n 0 1 2 3 4 5\n top -> *--*--*--*--*--*\n | /| /| /| /| /|\n |/ |/ |/ |/ |/ |\n bot -> *--*--*--*--*--*\n 0 1 2 3 4 5\n\n The triangles are oriented so that their right-hand-rule outward directions\nare all facing out of the page.\n \"\"\"\n a1 = top[:-1].reshape(-1,1)\n a2 = bot[:-1].reshape(-1,1)\n a3 = top[1:].reshape(-1,1)\n b3 = bot[1:].reshape(-1,1)\n\n tri1 = np.concatenate((a1, a2, a3), 1)\n tri2 = np.concatenate((a3, a2, b3), 1)\n\n tris = np.concatenate((tri1, tri2), 0)\n return tris\n\n\n# This calls main() when the program is invoked from the command line.\nif __name__ == \"__main__\":\n main()\n","sub_path":"meshes.py","file_name":"meshes.py","file_ext":"py","file_size_in_byte":13235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"404137811","text":"import re\nimport yaml\nfrom django.http import HttpResponse, Http404\nfrom django.shortcuts import render\nfrom django.conf import settings\nfrom pymongo.mongo_client import MongoClient\n\nspace_nums =[\n ('yuki_plus', 1),\n ('siokya', 2),\n ('MMM37', 3),\n ('iede_02', 4),\n ('COP__', 5),\n ('kiriuru', 6),\n ('teppan38', 7),\n ('coromo_saku2', 7),\n ('cafemoca19', 7),\n ('k4n6m9', 8),\n ('miyukisum', 9),\n ('ripo_day', 10),\n ('harapeco_pymr', 10),\n ('yuki8p', 11),\n ('ringosh_', 12),\n ('ISANAinUSA', 13),\n ('rikuK993', 14),\n ('puripash', 15),\n ('MyaMyaru', 16),\n ('nurumi_p', 17),\n ('EPI_prism', 17),\n ('jyojyojyo_', 18),\n ('kinta_ex', 19),\n ('418sds', 19),\n ('koshia_rl', 20),\n ('vamddkijg', 21),\n ('VegA__AnastasiA', 22),\n ('pa_sh_pr', 23),\n ('k_y_ma_', 23),\n ('popn_mitsuki', 24),\n ('rio_tarantella', 25),\n ('kk_sub', 26),\n ('kumodoriren', 27),\n ('mtk1600', 28),\n ('kirakira_tter08', 29),\n ('sakachico', 29),\n ('l0kinann', 30),\n ('an_dan_te074', 30),\n ('ANATANO_ARATANI', 31),\n ('tekkoubondo', 32),\n ('kondokodanuki', 33),\n ('naomachi1800ml', 34),\n ('houiP', 35),\n ('Fureiya14', 36),\n ('oremaka_000', 37),\n ('azuma333', 37),\n ('sasa_0416', 38),\n ('nanaox16', 39),\n ('eifonen', 40),\n ('chiharutosayaka', 41),\n ('White_0422', 42),\n ('qEouo', 43),\n ('indigohr_25', 44),\n ('shiopoko_6o6', 45),\n ('hutarun', 46),\n ('wt_prism', 1000),\n ('ino_zip', 1000),\n ('akarin1971', 1000),\n]\n\ndef index(request, page='1', edit=None):\n page = int(page)\n cols = MongoClient().prikoso_2016.tweets\n users = []\n for name, num in sorted(space_nums, key=lambda x: x[1]): # numでソート\n # ページ外のユーザを除外\n if not 10 * (page - 1) <= num < 10 * page: # ex. page=2 ならば #10-19 を表示\n continue\n \n user = cols.find_one({'tweet.user.screen_name': name})\n if user:\n user = user['tweet']['user']\n if edit: # 編集するときは全件表示する\n pins = cols.find({\n 'tweet.user.screen_name': name,\n 'tweet.extended_entities': {'$exists': True},\n 'tweet.text': {'$not': re.compile(r'^RT ')},\n 'pin': {'$exists': True},\n }).sort('tweets.id')\n tweets = cols.find({\n 'tweet.user.screen_name': name,\n 'tweet.extended_entities': {'$exists': True},\n 'tweet.text': {'$not': re.compile(r'^RT ')},\n 'pin': {'$exists': False},\n }).sort('tweets.id')\n print(name, pins.count() + tweets.count())\n \n else: # 通常時はdisabaleされたものを除外する\n pins = cols.find({\n 'tweet.user.screen_name': name,\n 'tweet.extended_entities': {'$exists': True},\n 'tweet.text': {'$not': re.compile(r'^RT ')},\n 'disable': {'$exists': False},\n 'pin': {'$exists': True},\n }).sort('tweets.id')\n tweets = cols.find({\n 'tweet.user.screen_name': name,\n 'tweet.extended_entities': {'$exists': True},\n 'tweet.text': {'$not': re.compile(r'^RT ')},\n 'disable': {'$exists': False},\n 'pin': {'$exists': False},\n }).sort('tweets.id')\n\n if edit:\n users.append({\n 'space_num': num,\n 'user': user,\n 'tweets_list': [pins, tweets[:30 - pins.count()]],\n })\n else: # editモードでない時は、表示ツイート数を制限する\n users.append({\n 'space_num': num,\n 'user': user,\n 'tweets_list': [pins, tweets[:max(0, 6 - pins.count())]],\n })\n\n return render(request, 'prikoso_2016_circle_checker/index.html', {'users': users, 'edit': edit})\n\ndef disable(request):\n id = request.POST.get('id')\n cols = MongoClient().prikoso_2016.tweets\n cols.update({'tweet.id_str': id}, {'$set': {'disable': True}})\n print('disabled:', id)\n return HttpResponse('')\n\ndef enable(request):\n id = request.POST.get('id')\n cols = MongoClient().prikoso_2016.tweets\n cols.update({'tweet.id_str': id}, {'$unset': {'disable': ''}})\n print('enabled:', id)\n return HttpResponse('')\n\ndef pin(request):\n id = request.POST.get('id')\n cols = MongoClient().prikoso_2016.tweets\n cols.update({'tweet.id_str': id}, {'$set': {'pin': True}})\n print('pinned:', id)\n return HttpResponse('')\n\ndef unpin(request):\n id = request.POST.get('id')\n cols = MongoClient().prikoso_2016.tweets\n cols.update({'tweet.id_str': id}, {'$unset': {'pin': ''}})\n print('unpinned:', id)\n return HttpResponse('')\n","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"314867614","text":"import logging\nimport random\n\nBOARD = \"board\"\nBCM = \"bcm\"\nOUT = \"out\"\nIN = \"in\"\nHIGH = \"high\"\nLOW = \"low\"\nRISING = 10\n\ndefinedPin = {}\n\nclass pwmClass(object):\n def __init__(self, pin, maxValue):\n self.pin = pin\n self.maxValue = maxValue\n\n def start(self, value):\n logging.info(\"PWM START, Pin {0} : Value {1}\".format(self.pin, value))\n\n def ChangeDutyCycle(self, frequency):\n logging.info(\"PWM Change, Pin {0} : Value {1}\".format(self.pin, frequency))\n\n\ndef output(pin, value):\n try:\n if definedPin[pin] == \"out\":\n logging.info(\"{0} : {1}\".format(pin, value))\n else:\n raise ValueError(\"GPIO Pin {} has not been set to OUT\".format(pin))\n\n except KeyError:\n raise ValueError(\"GPIO Pin {} has not been setup\".format(pin))\n\n\ndef input(pin):\n try:\n if definedPin[pin] == \"in\":\n return bool(random.getrandbits(1))\n else:\n raise ValueError(\"GPIO Pin {} has not been set to OUT\".format(pin))\n\n except KeyError:\n raise ValueError(\"GPIO Pin {} has not been setup\".format(pin))\n\n\ndef setmode(mode):\n logging.info(mode)\n\n\ndef setup(pin, value):\n try:\n definedPin[pin]\n raise ValueError(\"GPIO Pin {} has already been setup\".format(pin))\n except KeyError:\n definedPin[pin] = value\n logging.info(\"{0} : {1}\".format(pin, value))\n\n\ndef PWM(pin, maxValue):\n try:\n if definedPin[pin] == \"out\":\n logging.info(\"PWM Define, Pin {0}: maxValue {1}\".format(pin, maxValue))\n return pwmClass(pin, maxValue)\n else:\n raise ValueError(\"GPIO Pin {} has not been set to OUT\".format(pin))\n\n except KeyError:\n raise ValueError(\"GPIO Pin {} has not been setup\".format(pin))\n\ndef add_event_detect(pin1, pin2, callback=10, **kw):\n pass\n\n\ndef cleanup():\n logging.info(\"clean-up\")\n\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.DEBUG)\n\n import random\n\n\n setmode(BCM)\n setup(12, OUT)\n\n a = PWM(12, 100)\n a.start(1)\n a.ChangeDutyCycle(50)\n","sub_path":"RaspberryEmulaters/GPIO.py","file_name":"GPIO.py","file_ext":"py","file_size_in_byte":2076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"527825840","text":"# -*- coding: utf-8 -*-\n# @File : lagrange.py\n# @AUTH : swxs\n# @Time : 2018/7/28 14:33\n\nfrom scipy.interpolate import lagrange\n\n\ndef ployinterp_column(s, n, k=5):\n '''\n\n :param s: 列向量\n :param n: 插值的位置\n :param k: 去前后数据的个数\n :return: 插值\n '''\n y = s[list(range(n - k, n)) + list(range(n + 1, n + 1 + k))]\n y = y[y.notnull()]\n return lagrange(y.index, list(y))(n)\n\n","sub_path":"store/Python/learn/learn_scipy/lagrange.py","file_name":"lagrange.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"620221238","text":"'''\nCreated on Feb 21, 2018\n\n@author: Anthony Bell\n'''\nimport os\nimport datetime\nimport socket\nfrom sqlalchemy.ext.declarative.api import declarative_base\nfrom sqlalchemy import create_engine, text\nfrom sqlalchemy.orm import sessionmaker\n\nfrom model.Device import Device\nfrom model.MinuteData import MinuteData\nfrom model.HourData import HourData\nfrom model.DailyData import DailyData\nfrom model.Notification import Notification\nfrom model.Emailer import Emailer\n\nclass Database(object):\n '''\n The Database class is a convenience class for\n interacting with the sqlite3 database.\n This class acts primarily as a wrapper for SQLAlchemy with the addition\n of some application specific helper functions.\n '''\n\n\n def __init__(self, params=None):\n '''\n Constructor\n Establishes session to sqlite database\n\n Args:\n None\n\n Returns:\n Database object\n '''\n Base = declarative_base()\n basedir = os.path.join(os.path.abspath(os.path.dirname(__file__)), '..')\n self.engine = create_engine('sqlite:///'+os.path.join(basedir, 'TrickleTerminators.db'))\n self.session = sessionmaker(expire_on_commit=False, autoflush=False)\n self.session.configure(bind=self.engine)\n Base.metadata.create_all(self.engine)\n self.s = self.session()\n self.emailer = Emailer(recipients=['anthony.bell.us@ieee.org'])\n\n #Getter functions\n def get_devices(self):\n '''\n Returns all devices in the database\n\n Args:\n None\n\n Returns:\n None\n '''\n return self.s.query(Device)\n\n def get_hour_data(self):\n '''\n Gets all the hourly data from the database\n\n Args:\n None\n\n Returns:\n list of HourData objects\n '''\n return self.s.query(HourData)\n\n def get_current_hour(self, device):\n '''\n Gets the flow data for the current hour for the specified device\n\n Args:\n Device (str): name of the device to be queried\n\n Returns:\n HourData table entry for the current flow data of the device\n '''\n query = self.s.query(HourData).filter(HourData.device == device).order_by(desc(HourData.timestamp)).limit(1).all()\n return query\n\n def get_current_day(self, device):\n '''\n Gets the flow data for the current day for the specified device\n\n Args:\n Device (str): name of the device to be queried\n\n Returns:\n DailyData table entry for the current flow data of the device\n '''\n query = self.s.query(DailyData).filter(DailyData.device == device).order_by(desc(DailyData.timestamp)).limit(1).all()\n return query\n\n def get_daily_data(self):\n '''\n Gets all the daily data from the database\n\n Args:\n None\n\n Returns:\n list of DailyData objects\n '''\n return self.s.query(HourData)\n\n def get_minute_data(self):\n '''\n Gets all the minute by minute data from the database\n\n Args:\n None\n\n Returns:\n list of MinuteData objects\n '''\n return self.s.query(MinuteData)\n\n def get_device(self, device):\n '''\n Gets the device specified by the given name\n\n Args:\n device (str): the name of the device that is being requested\n\n Returns:\n Device object\n '''\n _device = self.s.query(Device).filter(Device.device == device).first()\n return _device\n\n def get_notifications(self):\n return self.s.query(Notification)\n\n\n #Setter functions\n def set_next_id(self):\n '''\n Sets the stored_id values so that database collisions do not occur, call on startup\n\n Args:\n None\n\n Returns:\n None\n '''\n try:\n DailyData.stored_id = self.s.query(DailyData).order_by('id').all()[-1].id + 1\n except:\n pass\n try:\n HourData.stored_id = self.s.query(HourData).order_by('id').all()[-1].id + 1\n except:\n pass\n try:\n MinuteData.stored_id = self.s.query(MinuteData).order_by('id').all()[-1].id + 1\n except:\n pass\n try:\n Device.stored_id = self.s.query(Device).order_by('id').all()[-1].id + 1\n except:\n pass\n try:\n Notification.stored_id = self.s.query(Notification).order_by('id').all()[-1].id + 1\n except:\n pass\n\n\n #Helper functions\n def update_hourly_data(self, device):\n '''\n Updates the database with the current flow for the past hour for a given device\n\n Args:\n Device (str): name of the device to be updated\n\n Returns:\n hourly_flow (int): total flow for the previous hour\n '''\n past_hour = datetime.datetime.now() - datetime.timedelta(hours=1)\n minute_entries = self.s.query(MinuteData).filter(MinuteData.device == device).filter(MinuteData.minute > past_hour)\n hourly_flow = 0\n for entry in minute_entries:\n hourly_flow += entry.flow\n self.s.add(HourData(device, hourly_flow))\n _device = self.s.query(Device).filter(Device.device == device).first()\n if _device.max_flow <= hourly_flow:\n pass #Shut off valve and update db\n self.s.commit()\n return hourly_flow\n\n def update_daily_data(self, device):\n '''\n Updates the database with the current flow for the past 24 hours for a given device\n\n Args:\n Device (str): name of the device to be updated\n\n Returns:\n None\n '''\n past_day = datetime.datetime.now() - datetime.timedelta(days=1)\n minute_entries = self.s.query(MinuteData).filter(MinuteData.device == device).filter(MinuteData.minute > past_day)\n daily_flow = 0\n for entry in minute_entries:\n daily_flow += entry.flow\n self.s.add(DailyData(device, daily_flow))\n self.s.commit()\n\n\n def add_minute_data(self, device, flow=0):\n '''\n Adds minute flow data to the database and updates hourly and daily data\n\n Args:\n device (str): device for which data is being logged\n flow (int): Flow data for the device (default = 0)\n\n Returns:\n hourly_flow (int): flow for the last hour\n '''\n self.s.add(MinuteData(device, flow))\n hourly_flow = self.update_hourly_data(device)\n self.update_daily_data(device)\n self.s.commit()\n return hourly_flow\n\n def add_notification(self, device, message):\n '''\n Adds a notification to the database\n\n Args:\n device (str): device for which notification is being logged\n message (str): notification message\n\n Returns:\n None\n '''\n if message == \"burst\":\n _message = \"There has been a burst at \" + device\n elif message == \"flow\":\n _message = device + \" has exceeded the maximum flow allowed\"\n elif message == \"remove\":\n _message = device + \" has been removed\"\n elif message == \"add\":\n _message = device + \" has been added\"\n self.s.add(Notification(device, _message))\n self.s.commit()\n self.emailer.send_message(template=message, message=_message)\n\n def add_device(self, name, ip=\"0.0.0.0\"):\n '''\n Adds a device to the database\n\n Args:\n name (str): the name of the device being added\n ip (str): the ip address of the device being added\n\n Returns:\n None\n '''\n _exists = self.s.query(Device).filter(Device.device == name).all()\n if _exists:\n return None\n self.s.rollback()\n new_device = Device(name=name,ip=ip)\n self.s.add(new_device)\n self.s.commit()\n self.add_notification(name, \"add\")\n\n def remove_device(self, name):\n '''\n Removes a device from the database\n\n Args:\n name (str): the name of the device being removed\n\n Returns:\n None\n '''\n query = self.s.query(Device).fliter(Device.device == name)\n query.delete()\n s.commit()\n\n def update_device(self, device, flow=None, status=None):\n '''\n Updates the flow settings for a specified device\n\n Args:\n device (str): the name of the device being updated\n flow (int): the maximum flow value in L/Hr\n status (str): the status of the device (\"on\" or \"off\")\n\n Returns:\n None\n '''\n _device = self.s.query(Device).filter(Device.device == device).first()\n if flow is not None:\n _device.max_flow = flow\n self.s.commit()\n if status is not None:\n _device.status = status\n self.s.commit()\n\n def close(self):\n '''\n Closes the database\n\n Args:\n None\n\n Returns:\n None\n '''\n self.s.close()\n","sub_path":"model/Database.py","file_name":"Database.py","file_ext":"py","file_size_in_byte":9168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"388568440","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n# Ornothologist produces 6 tab-delimited UTF-8 files and one directory per query.\n# See README.md for details.\n# By: Ericka Menchen-Trevino http://www.ericka.cc/\n\n# python2/3 interoperability\nfrom __future__ import print_function\n\n# Variables to fill in\n# argument parsing, so people don't have to edit this file\nimport argparse\n\n# for URL encoding search terms\nimport urllib\n\n# using this python module to access the Twitter API https://github.com/bear/python-twitter\nimport twitter\n\n#to handle UTF-8\nimport codecs\n\n#to process tweet text\nimport re\n\n#to get timestamp\nfrom datetime import tzinfo, datetime\n\n# to be able to create directories\nimport os\n\nimport sys\n\n# read relevant keys from config file\ntry:\n with open('ornithologist.conf', 'r') as config:\n c = config.readlines()\n assert len(c) == 4, \"\"\"ornithologist.conf not in the right format. Need 'API key', 'API secret', 'Access token' and 'Access token secret', each in a single line\"\"\"\n consumer_key = c[0].strip()\n consumer_secret = c[1].strip()\n access_token_key = c[2].strip()\n access_token_secret = c[3].strip()\nexcept OSError:\n print('Config file not found. Please refer to README.', file=sys.stderr)\n\n# this is to make sure help instead of usage gets printed on error\nclass ArgumentParser(argparse.ArgumentParser):\n def error(self, message):\n print('error: %s\\n' % message, file=sys.stderr)\n self.print_help()\n sys.exit(2)\n\nparser = ArgumentParser(description='retrieves Twitter data via the Twitter API for further analysis')\nparser.add_argument('--term', dest='searchterm', help='search term', required=True)\nparser.add_argument('--file', dest='fileName', help='For file name to append, e.g. student name', required=True)\nparser.add_argument('--lang', dest='language', default='', help='e.g. \"en\", \"nl\" (default: None)')\nparser.add_argument('--before', dest='before', default='', help='get tweets before this date YYYY-MM-DD (default: now)')\nparser.add_argument('--type', dest='resultType', default='recent', help='result type: options are recent, popular, mixed, see API documentation. (default: recent)')\n\nargs = parser.parse_args()\nsearchterm = urllib.quote_plus(args.searchterm) #handle URL encoding\nfileName = args.fileName\nlanguage = args.language\nbefore = args.before\nresultType = args.resultType\n\n# Twitter authentication\napi = twitter.Api(consumer_key=consumer_key,\n consumer_secret=consumer_secret,\n access_token_key=access_token_key,\n access_token_secret=access_token_secret)\n\n#do the actual search\nstatuses = api.GetSearch(term=searchterm, result_type=resultType, include_entities=True, count=100, lang=language, until=before)\n\ncurrentTime = datetime.utcnow()\n\n#open and write a file with search-level data\nsldFileName = searchterm + \"-\" + fileName + \"-searchLevelData.txt\"\nif os.path.isfile(sldFileName) is True:\n info = codecs.open(sldFileName, encoding='utf-8', mode='a')\n info.write (\"\\n\" + searchterm + \"\\t\" + language + \"\\t\" + fileName + \"\\t\" + before + \"\\t\" + str(currentTime) + \" UTC\" + '\\t' + resultType)\nelse:\n info = codecs.open(sldFileName, encoding='utf-8', mode='w+')\n info.write(\"search term\\tlanguage\\tfile name\\tbefore\\tgathered\\tresult type\\n\" + searchterm + \"\\t\" + language + \"\\t\" + fileName + \"\\t\" + before + \"\\t\" + str(currentTime) + \" UTC\" + '\\t' + resultType)\n\n#loop through each result\nfor s in statuses:\n #take out any tabs or new lines in the tweets\n takeTabNewlines = re.compile(r'[\\t\\r\\n]')\n strip = takeTabNewlines.sub('', s.text)\n \n #get tweets to users (user begins the tweet)\n toUserSearch = re.compile(r'@(\\w*\\b)', re.U)\n toUserMatch = toUserSearch.match(strip)\n toUserList = []\n if toUserMatch:\n toUserList.append(toUserMatch.group(1))\n \n userFileName = searchterm + \"-\" + fileName + \"-userEdges.txt\"\n \n if os.path.isfile(userFileName) is True:\n userNet = codecs.open(userFileName, encoding='utf-8', mode='a')\n userNet.write(unicode(s.user.screen_name) + \"\\t\" + unicode(toUserMatch.group(1)) + \"\\t\" + unicode(s.id) + \"\\n\")\n else:\n # open a file to write the to user network\n userNet = codecs.open(userFileName, encoding='utf-8', mode='w+')\n #Source is user, target is user mentioned\n userNet.write(\"Source\\tTarget\\ttweet id\\n\")\n else:\n toUserList.append('')\n \n #get retweet user\n rtSearch = re.compile(r'RT @(\\w*\\b)', re.U)\n rtMatch = rtSearch.match(strip)\n rtList = []\n rtFileName = searchterm + \"-\" + fileName + \"-rtEdges.txt\"\n if rtMatch:\n rtList.append(rtMatch.group(1))\n if os.path.isfile(rtFileName) is True:\n rt = codecs.open(rtFileName, encoding='utf-8', mode='a')\n rt.write(unicode(s.user.screen_name) + \"\\t\" + unicode(rtMatch.group(1)) + \"\\t\" + unicode(s.id) + \"\\n\")\n else:\n # open a file to write the RT network\n rt = codecs.open(rtFileName, encoding='utf-8', mode='w+')\n #Source is user, target is user retweeted\n rt.write(\"Source\\tTarget\\ttweet id\\n\")\n rt.write(unicode(s.user.screen_name) + \"\\t\" + unicode(rtMatch.group(1)) + \"\\t\" + unicode(s.id) + \"\\n\")\n else:\n rtList.append('')\n \n #get all user mentions\n mentionList = re.findall(r'@(\\w*\\b)', strip)\n \n #get all hashtags\n hashtagList = re.findall(r'#\\w*\\b', strip)\n \n #get all links\n linkList = re.findall(r'https?://[\\w\\./]*\\b', strip)\n \n #strip source of HTML\n tweetSource= re.sub('<[^<]+?>', '', s.source)\n \n #read in the date 'Mon Sep 08 05:43:10 +0000 2014' as a date object and output as '20140908 05:43:10'\n dateObject = datetime.strptime(s.created_at, '%a %b %d %H:%M:%S +0000 %Y')\n unixDate = dateObject.strftime('%Y-%m-%d %H:%M:%S')\n \n tweetFileName = searchterm + \"-\" + fileName + \"-tweets.txt\"\n \n if os.path.isfile(tweetFileName) is True:\n #open a file to write the tweet-level data\n t = codecs.open(tweetFileName, encoding='utf-8', mode='a')\n # write one line of data to tweet file\n t.write(unicode(currentTime) + \"\\t\" + unicode(s.id) + \"\\t\" + unicode(s.user.id) + \"\\t\" + unicode(s.user.screen_name) + \"\\t\" + unixDate + \"\\t\" + unicode(s.retweet_count) + \"\\t\" + str(s.favorite_count) + \"\\t\" + unicode(tweetSource) + \"\\t\" + unicode(s.lang) + \"\\t\" + unicode(s.withheld_in_countries) + \"\\t\" + unicode(strip) + \"\\t\" + ', '.join(toUserList) + \"\\t\" + ', '.join(rtList) + \"\\t\" + ', '.join(mentionList) + \"\\t\" + ', '.join(hashtagList) + \"\\t\" + ', '.join(linkList) + \"\\n\")\n else:\n t = codecs.open(tweetFileName, encoding='utf-8', mode='w+')\n # Write the header row\n t.write(\"gathered\\ttweet id\\tuser id\\tuser name\\ttime created\\tretweets\\tfavorites\\ttweet source\\tlanguage\\twithheld from\\ttweet\\tto user\\tretweet of\\tall user mentions\\thashtags\\tlinks\\n\")\n # write one line of data to tweet file\n t.write(unicode(currentTime) + \"\\t\" + unicode(s.id) + \"\\t\" + unicode(s.user.id) + \"\\t\" + unicode(s.user.screen_name) + \"\\t\" + unixDate + \"\\t\" + unicode(s.retweet_count) + \"\\t\" + str(s.favorite_count) + \"\\t\" + unicode(tweetSource) + \"\\t\" + unicode(s.lang) + \"\\t\" + unicode(s.withheld_in_countries) + \"\\t\" + unicode(strip) + \"\\t\" + ', '.join(toUserList) + \"\\t\" + ', '.join(rtList) + \"\\t\" + ', '.join(mentionList) + \"\\t\" + ', '.join(hashtagList) + \"\\t\" + ', '.join(linkList) + \"\\n\")\n \n hashtagFileName = searchterm + \"-\" + fileName + \"-hashtagEdges.txt\"\n \n for h in hashtagList:\n if os.path.isfile(hashtagFileName) is True:\n #open a file to write the hashtag-level data\n hash = codecs.open(hashtagFileName, encoding='utf-8', mode='a')\n hash.write(unicode(s.user.screen_name) + \"\\t\" + unicode(h) + \"\\t\" + unicode(s.id) + \"\\n\")\n else:\n #open a file to write the hashtag-level data\n hash = codecs.open(hashtagFileName, encoding='utf-8', mode='w+')\n #Source is user and target is hashtag\n hash.write(\"Source\\tTarget\\ttweet id\\n\")\n hash.write(unicode(s.user.screen_name) + \"\\t\" + unicode(h) + \"\\t\" + unicode(s.id) + \"\\n\")\n\nt.close() #save the tweet-level data file\nhash.close() #save the hashtag-level data file\n\nuserFileName = searchterm + \"-\" + fileName + \"-users.txt\"\n\nif os.path.isfile(userFileName) is True:\n u = codecs.open(userFileName, encoding='utf-8', mode='a')\n #loop through each result\n userList = []\n for s in statuses:\n #take out any tabs or new lines in the user descriptions\n takeTabNewlinesDesc = re.compile(r'[\\t\\r\\n]')\n stripDesc = takeTabNewlinesDesc.sub('', s.user.description)\n userList.append(unicode(s.user.id) + \"\\t\" + unicode(s.user.screen_name) + \"\\t\" + s.user.location + \"\\t\" + str(s.user.time_zone) + \"\\t\" + str(s.user.utc_offset) + \"\\t\" + str(s.user.profile_image_url) + \"\\t\" + stripDesc)\n #deduplicate the user list before printing\n userList = list(set(userList))\n u.write('\\n'.join(userList))\nelse:\n #open a file to write the user-level data to\n u = codecs.open(userFileName, encoding='utf-8', mode='w+')\n #write the header row to the file\n u.write(\"user id\\tscreen name\\tlocation\\ttime zone\\tutc offset\\tprofile image URL\\tdescription\\n\")\n #loop through each result\n userList = []\n for s in statuses:\n #take out any tabs or new lines in the user descriptions\n takeTabNewlinesDesc = re.compile(r'[\\t\\r\\n]')\n stripDesc = takeTabNewlinesDesc.sub('', s.user.description)\n userList.append(unicode(s.user.id) + \"\\t\" + unicode(s.user.screen_name) + \"\\t\" + s.user.location + \"\\t\" + str(s.user.time_zone) + \"\\t\" + str(s.user.utc_offset) + \"\\t\" + str(s.user.profile_image_url) + \"\\t\" + stripDesc)\n #deduplicate the user list before printing\n userList = list(set(userList))\n u.write('\\n'.join(userList))\n\nu.close()\n\n# directory of each tweet as a file with ID as name for NLP\n\nfor s in statuses:\n # create directory (if needed) and open a file to write each tweet to\n filename = searchterm + \"-\" + fileName + \"-\" + \"tweets\" + \"/\" + str(s.id) + \".txt\"\n if not os.path.exists(os.path.dirname(filename)):\n os.makedirs(os.path.dirname(filename))\n with codecs.open(filename, encoding='utf-8', mode=\"w+\") as f:\n f.write(unicode(s.text))\nf.close()\n","sub_path":"ornithologist.py","file_name":"ornithologist.py","file_ext":"py","file_size_in_byte":10089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"303822308","text":"\n\"\"\"Calculates how much time it will take to pay down\nan amount owed for a monthly amount paid\"\"\"\n\nimport datetime\nimport calendar\n\n\ndef time_till_repaid(total_owed=0,\n interest_rate=0.00,\n monthly_payement=1,\n show_progress=False):\n\n today = datetime.date.today()\n\n # Start date is first day of next month\n days_in_month = calendar.monthrange(today.year, today.month)[1]\n days_left_in_month = days_in_month - today.day\n\n start_date = today + datetime.timedelta(days=days_left_in_month + 1)\n\n end_date = start_date\n\n while total_owed > 0:\n\n total_owed += (interest_rate / 12) * total_owed\n total_owed -= monthly_payement\n total_owed = 0 if total_owed < 0 else round(total_owed, 2)\n\n if show_progress is True:\n print(f'{end_date}\t${total_owed:.2f}')\n\n # Increment 'end_date' by the amount of days in the month\n days_in_month = calendar.monthrange(end_date.year, end_date.month)[1]\n end_date = end_date + datetime.timedelta(days=days_in_month)\n\n # Get the difference in time between the start and end dates\n years = round((end_date - start_date).days / 365, 1)\n months = int(round(round(years - int(years), 2) * 12, 0))\n\n # Print amount of time it will take to pay the amount owed\n s_ = '' if months < 2 else 's'\n if years > 1:\n s = '' if years < 2 else 's'\n print(f'{years:.0f} year{s}, {months} month{s_}')\n else:\n print(f'{months:.0f} month{s_}')\n\n\n# Constants to plug\ntotal_owed = 10000\ninterest_rate = 0.00\nmonthly_payement = 100.50\nshow_progress = False\n\ntime_till_repaid(total_owed, interest_rate, monthly_payement, show_progress)\n","sub_path":"Python/PythonArchive/time_till_debt_paid.py","file_name":"time_till_debt_paid.py","file_ext":"py","file_size_in_byte":1719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"569145080","text":"from lightgui import mygui\nimport os\nprogram_dir = os.path.dirname(os.path.realpath(__file__))\nCELL_DIM = [35,35]\n#made by Mary Mokuolu using GarageBand\ndrop_sound = mygui.create_sound(os.path.join(program_dir, \"drop_sound.wav\"))\ndrop_sound.set_volume(.4)\n\n#https://www.freesound.org/people/grunz/sounds/109662/\nclear_sound = mygui.create_sound(os.path.join(program_dir, \"success_cleared.wav\")) \nclear_sound.set_volume(.5)\n","sub_path":"attr.py","file_name":"attr.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"141072397","text":"import numpy as np\nimport tensorflow as tf \nimport pandas as pd\nfrom keras_preprocessing.image import ImageDataGenerator\nimport random\nimport CONFIG\nimport csv\nfrom tensorflow.keras.models import load_model\nimport tensorflow.keras.backend as K\n\n\n#a custom metric (sort of ) -> it is actually the accu of one hot with single label\ndef arg(y_true, y_pred):\n return K.cast(K.equal(K.argmax(y_true, axis=-1),\n K.argmax(y_pred, axis=-1)),\n K.floatx())\n\n\n#extact match accu \ndef multi_label_accu(y_true, y_pred):\n comp = K.equal(y_true, K.round(y_pred))\n return K.cast(K.all(comp, axis=-1), K.floatx())\n \n#the method to get guiding files\ndef gen(num, form):\n with open('t.txt', 'w') as writeFile:\n for i in range(num):\n s = '{}.{}\\t1\\n'.format(i, form)\n writeFile.write(s)\n\n writeFile.close()\n destination = open('test.csv', 'a')\n in_txt = csv.reader(open('t.txt', \"r\"), delimiter = '\\t')\n out_csv = csv.writer(destination)\n first_row = ['filename', 'labels']\n out_csv.writerow(first_row)\n out_csv.writerows(in_txt)\n destination.close()\n df = pd.read_csv('test.csv')\n return df\n \n\ndef predict():\n #set up data generator\n test_datagen = ImageDataGenerator(rescale=1./255.)\n\n #read file\n test_generator=test_datagen.flow_from_dataframe(\n dataframe= gen(CONFIG.TEST_NUM, CONFIG.TEST_FORMAT),\n directory= CONFIG.TEST_DIR,\n x_col= \"filename\",\n batch_size= 1,\n seed= 42,\n shuffle= False,\n class_mode= None,\n target_size= (CONFIG.IMAGE_SIZE,CONFIG.IMAGE_SIZE))\n\n #load model\n model = load_model(CONFIG.MODEL, custom_objects = {'arg': arg, 'arg2': multi_label_accu})\n\n #to restore order\n test_generator.reset()\n\n #feed in data\n pred=model.predict_generator(test_generator,\n steps=test_generator.n//test_generator.batch_size,\n verbose=1)\n\n #numpy it\n pred = np.array(pred)\n\n #select the one with max prob\n am = np.argmax(pred, axis = -1)\n\n\n predictions=[]\n\n #get the dictionary\n labels = CONFIG.LABELS\n\n\n for i in am:\n predictions.append(labels[i])\n\n \n \n filenames=test_generator.filenames\n results=pd.DataFrame({\"Filename\":filenames,\n \"Predictions\":predictions})\n results.to_csv(\"Predicted_labels.csv\",index=False)\n \n file1 = open(\"../Output/Predicted_labels.txt\",\"a\")\n\n with open('Predicted_labels.csv', 'r') as f:\n reader = csv.reader(f)\n i = 0\n for row in reader:\n if(i == 0):\n i += 1\n continue\n s = '{}\\t{}\\n'.format(row[0], row[1])\n file1.write(s)\n \n file1.close()\n\n\n\n\nif __name__ == '__main__':\n\n predict()\n \n","sub_path":"Code/Algorithm/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":3200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"372852368","text":"import pytest\nimport os\nimport brightway2 as bw2\n\nTEST_MODEL_NAME = \"Test_model\"\n\n@pytest.fixture(scope=\"session\", autouse=True)\ndef setup_fixtures(request):\n\n\tprint('RUNNING SETUP FIXTURE')\n\n\tif TEST_MODEL_NAME in bw2.projects:\n\t\tbw2.projects.delete_project(name=TEST_MODEL_NAME, delete_dir=True)\n\n\tbw2.projects.set_current(TEST_MODEL_NAME)\n\tbw2.bw2setup()\n\t\n\n\tscript_path = os.path.dirname(os.path.realpath(__file__))\n\tecospold_folder = os.path.join(\"tests\", \"assets\", \"datasets\")\n\tecospold_path = os.path.join(script_path, ecospold_folder)\n\tprint(ecospold_path)\n\n\tei = bw2.SingleOutputEcospold2Importer(ecospold_path, \"Ecoinvent3_3_cutoff\")\n\tei.apply_strategies()\n\tei.statistics()\n\tei.write_database()\n\n\tbw2.projects.set_current('default')\n\t\n\tdef teardown_fixtures():\n\t\tprint('TEAR IT DOWN!!')\n\t\tbw2.projects.set_current('default')\n\t\t\n\t\tif TEST_MODEL_NAME in bw2.projects:\n\t\t\tbw2.projects.delete_project(name=TEST_MODEL_NAME, delete_dir=True)\n\t\n\trequest.addfinalizer(teardown_fixtures)\n\n\n\n\n","sub_path":"conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"239817964","text":"# stdlib imports\n\nimport os\nimport numpy as np\nimport urllib\nimport json\nfrom datetime import timedelta, datetime\nimport collections\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\n# import numpy as np\nimport sqlite3 as lite\nimport pandas as pd\n\n# local imports\nfrom mapio.shake import getHeaderData\nfrom libcomcat.search import get_event_by_id, search\nfrom mapio.multihaz import MultiHazardGrid\nfrom gfail.stats import get_rangebeta, get_pdfbeta\nfrom mapio.gdal import GDALGrid\nfrom mapio.gmt import GMTGrid\n\n\n# Don't delete this, it's needed in an eval function\nimport matplotlib.cm as cm # DO NOT DELETE\n# DO NOT DELETE ABOVE LINE\n\n# Define bin edges (lower and upper are clipped here but\n# are not clipped in reality)\nlshbins = [0.1, 1., 10., 100., 1000.]\nlspbins = [10., 100., 1000., 10000., 1e5]\nlqhbins = [1., 10., 100., 1000., 10000.]\nlqpbins = [100., 1000., 10000., 100000., 1e6]\n\n\ndef is_grid_point_source(grid):\n \"\"\"Was the shakemap grid constructed with a point source?\n\n This makes use of the 'urat' layer, which is the ratio of the predicted\n ground motion standard deviation to the GMPE standard deviation. The only\n reason this could ever be greater than 1.0 is if the uncertainty of the\n prediction is inflated due to the point source approxmiation; further,\n if a point source was used, there will always be some\n locations with 'urat' > 1.0.\n\n Args:\n grid (ShakeGrid): A ShakeGrid object from MapIO.\n\n Returns:\n bool: True if point rupture.\n \"\"\"\n data = grid.getData()\n urat = data['urat'].getData()\n max_urat = np.max(urat)\n if max_urat > (1 + np.finfo(float).eps):\n return True\n else:\n return False\n\n\ndef get_event_comcat(shakefile, timewindow=60, degwindow=0.3, magwindow=0.2):\n \"\"\"\n Find an event in comcat, searching first by event id and if that\n fails searching by magnitude, time, and location.\n\n Args:\n shakefile (str): path to shakemap .xml file of event to find\n timewindow (float): width of time window to search around time defined\n in shakefile (in seconds)\n degwindow (float): width of area to search around location specified in\n shakefile (in degrees).\n magwindow (float): width of magnitude window to search around the\n magnitude specified in shakefile.\n\n Returns:\n None if event not found, else tuple (info, detail, shakemap) where,\n * info: json formatted dictionary of info.json for the event\n * detail: event detail from comcat\n * shakemap: shakemap of event found (from comcat)\n\n \"\"\"\n header_dicts = getHeaderData(shakefile)\n grid_dict = header_dicts[0]\n event_dict = header_dicts[1]\n #version = grid_dict['shakemap_version']\n shaketime = grid_dict['process_timestamp']\n try:\n eid = event_dict['event_id']\n net = 'us'\n if 'event_network' in event_dict:\n net = event_dict['event_network']\n if not eid.startswith(net):\n eid = net + eid\n detail = get_event_by_id(eid, includesuperseded=True)\n except Exception as e:\n lat = event_dict['lat']\n lon = event_dict['lon']\n mag = event_dict['magnitude']\n time = event_dict['event_timestamp']\n starttime = time - timedelta(seconds=timewindow)\n endtime = time + timedelta(seconds=timewindow)\n minlat = lat - degwindow\n minlon = lon - degwindow\n maxlat = lat + degwindow\n maxlon = lon + degwindow\n minmag = max(0, mag - magwindow)\n maxmag = min(10, mag + magwindow)\n events = search(starttime=starttime,\n endtime=endtime,\n minmagnitude=minmag,\n maxmagnitude=maxmag,\n minlatitude=minlat,\n minlongitude=minlon,\n maxlatitude=maxlat,\n maxlongitude=maxlon)\n if not len(events):\n return None\n detail = events[0].getDetailEvent()\n allversions = detail.getProducts('shakemap', version='all')\n # Find the right version\n dates1 = [allv.product_timestamp for allv in allversions]\n dates = np.array([datetime.fromtimestamp(int(str(dat)[:10])) for dat in dates1])\n idx = np.argmin(np.abs(dates-shaketime))\n #vers = [allv.version for allv in allversions]\n #idx = np.where(np.array(vers) == version)[0][0]\n shakemap = allversions[idx]\n infobytes, url = shakemap.getContentBytes('info.json')\n info = json.loads(infobytes.decode('utf-8'))\n\n return info, detail, shakemap\n\n\ndef parseConfigLayers(maplayers, config, keys=None):\n \"\"\"\n Parse things that need to coodinate with each layer (like lims, logscale,\n colormaps etc.) from config file, in right order, where the order is from\n maplayers.\n\n Args:\n maplayers (dict): Dictionary containing model output.\n config (ConfigObj): Config object describing options for specific\n model.\n keys (list): List of keys of maplayers to process, e.g. ``['model']``.\n\n Returns:\n tuple: (plotorder, logscale, lims, colormaps, maskthreshes) where:\n * plotorder: maplayers keys in order of plotting.\n * logscale: list of logscale options from config corresponding to\n keys in plotorder (same order).\n * lims: list of colorbar limits from config corresponding to keys\n in plotorder (same order).\n * colormaps: list of colormaps from config corresponding to keys\n in plotorder (same order),\n * maskthreshes: list of mask thresholds from config corresponding\n to keys in plotorder (same order).\n\n \"\"\"\n # TODO:\n # - Add ability to interpret custom color maps.\n\n # get all key names, create a plotorder list in case maplayers is not an\n # ordered dict, making sure that anything called 'model' is first\n if keys is None:\n keys = list(maplayers.keys())\n plotorder = []\n\n configkeys = list(config.keys())\n\n try:\n limits = config[configkeys[0]]['display_options']['lims']\n lims = []\n except:\n lims = None\n limits = None\n\n try:\n colors = config[configkeys[0]]['display_options']['colors']\n colormaps = []\n except:\n colormaps = None\n colors = None\n\n try:\n logs = config[configkeys[0]]['display_options']['logscale']\n logscale = []\n except:\n logscale = False\n logs = None\n\n try:\n masks = config[configkeys[0]]['display_options']['maskthresholds']\n maskthreshes = []\n except:\n maskthreshes = None\n masks = None\n\n try:\n default = \\\n config[configkeys[0]]['display_options']['colors']['default']\n default = eval(default)\n except:\n default = None\n\n for i, key in enumerate(keys):\n plotorder += [key]\n if limits is not None:\n found = False\n for lim1 in limits:\n if lim1 in key:\n if type(limits[lim1]) is list:\n getlim = np.array(limits[lim1]).astype(np.float)\n else:\n try:\n getlim = eval(limits[lim1])\n except:\n getlim = None\n lims.append(getlim)\n found = True\n if not found:\n lims.append(None)\n\n if colors is not None:\n found = False\n for c in colors:\n if c in key:\n getcol = colors[c]\n colorobject = eval(getcol)\n if colorobject is None:\n colorobject = default\n colormaps.append(colorobject)\n found = True\n if not found:\n colormaps.append(default)\n\n if logs is not None:\n found = False\n for g in logs:\n getlog = False\n if g in key:\n if logs[g].lower() == 'true':\n getlog = True\n logscale.append(getlog)\n found = True\n if not found:\n logscale.append(False)\n\n if masks is not None:\n found = False\n for m in masks:\n if m in key:\n getmask = eval(masks[m])\n maskthreshes.append(getmask)\n found = True\n if not found:\n maskthreshes.append(None)\n\n # Reorder everything so model is first, if it's not already\n if plotorder[0] != 'model':\n indx = [idx for idx, key in enumerate(plotorder) if key == 'model']\n if len(indx) == 1:\n indx = indx[0]\n firstpo = plotorder.pop(indx)\n plotorder = [firstpo] + plotorder\n firstlog = logscale.pop(indx)\n logscale = [firstlog] + logscale\n firstlim = lims.pop(indx)\n lims = [firstlim] + lims\n firstcol = colormaps.pop(indx)\n colormaps = [firstcol] + colormaps\n\n return plotorder, logscale, lims, colormaps, maskthreshes\n\n\ndef text_to_json(input1):\n \"\"\"Simplification of text_to_json from shakelib.rupture.factory\n\n Args:\n input1 (str): url or filepath to text file\n\n Returns:\n json formatted stream of input1\n \"\"\"\n if os.path.exists(input1):\n with open(input1, 'r') as f:\n lines = f.readlines()\n else:\n with urllib.request.urlopen(input1) as f:\n lines = f.readlines()\n\n x = []\n y = []\n z = []\n reference = ''\n # convert to geojson\n for line in lines:\n sline = line.strip()\n if sline.startswith('#'):\n reference += sline.strip('#').strip('Source: ')\n continue\n if sline.startswith('>'):\n if len(x): # start of new line segment\n x.append(np.nan)\n y.append(np.nan)\n z.append(np.nan)\n continue\n else: # start of file\n continue\n if not len(sline.strip()):\n continue\n parts = sline.split()\n\n y.append(float(parts[0]))\n x.append(float(parts[1]))\n if len(parts) >= 3:\n z.append(float(parts[2]))\n else:\n print('Fault file has no depths, assuming zero depth')\n z.append(0.0)\n coords = []\n poly = []\n for lon, lat, dep in zip(x, y, z):\n if np.isnan(lon):\n coords.append(poly)\n poly = []\n else:\n poly.append([lon, lat, dep])\n if poly != []:\n coords.append(poly)\n\n d = {\n \"type\": \"FeatureCollection\",\n \"metadata\": {\n 'reference': reference\n },\n \"features\": [\n {\n \"type\": \"Feature\",\n \"properties\": {\n \"rupture type\": \"rupture extent\"\n },\n \"geometry\": {\n \"type\": \"MultiPolygon\",\n \"coordinates\": [coords]\n }\n }\n ]\n }\n return json.dumps(d)\n\n\ndef write_floats(filename, grid2d):\n \"\"\"Create a binary (with acc. header file) version of a Grid2D object.\n\n Args:\n filename (str): String filename to write (i.e., 'probability.flt')\n grid2d (Grid2D): MapIO Grid2D object.\n\n Returns:\n Given a filename input of \"probability.flt\", this function will\n create that file, plus a text file called \"probability.hdr\".\n \"\"\"\n geodict = grid2d.getGeoDict().asDict()\n array = grid2d.getData().astype('float32')\n np.save(filename, array)\n npyfilename = filename + '.npy'\n os.rename(npyfilename, filename)\n fpath, fname = os.path.split(filename)\n fbase, _ = os.path.splitext(fname)\n hdrfile = os.path.join(fpath, fbase + '.hdr')\n f = open(hdrfile, 'wt')\n for key, value in geodict.items():\n if isinstance(value, int):\n fmt = '%s = %i\\n'\n elif isinstance(value, float):\n fmt = '%s = %.4f\\n'\n else:\n fmt = '%s = %s\\n'\n f.write(fmt % (key, value))\n f.close()\n\n\ndef savelayers(grids, filename):\n \"\"\"\n Save ground failure layers object as a MultiHazard HDF file, preserving\n metadata structures. All layers must have same geodictionary.\n\n Args:\n grids: Ground failure layers object.\n filename (str): Path to where you want to save this file.\n\n Returns:\n .hdf5 file containing ground failure layers\n \"\"\"\n layers = collections.OrderedDict()\n metadata = collections.OrderedDict()\n for key in list(grids.keys()):\n layers[key] = grids[key]['grid'].getData()\n metadata[key] = {\n 'description': grids[key]['description'],\n 'type': grids[key]['type'],\n 'label': grids[key]['label']\n }\n origin = {}\n header = {}\n mgrid = MultiHazardGrid(layers, grids[key]['grid'].getGeoDict(),\n origin,\n header,\n metadata=metadata)\n mgrid.save(filename)\n\n\ndef loadlayers(filename):\n \"\"\"\n Load a MultiHazard HDF file back in as a ground failure layers object in\n active memory (must have been saved for this purpose).\n Args:\n filename (str): Path to layers file (hdf5 extension).\n\n Returns:\n Ground failure layers object\n \"\"\"\n mgrid = MultiHazardGrid.load(filename)\n grids = collections.OrderedDict()\n for key in mgrid.getLayerNames():\n grids[key] = {\n 'grid': mgrid.getData()[key],\n 'description': mgrid.getMetadata()[key]['description'],\n 'type': mgrid.getMetadata()[key]['type'],\n 'label': mgrid.getMetadata()[key]['label']\n }\n\n return grids\n\n\ndef get_alert(paramalertLS, paramalertLQ, parampopLS, parampopLQ,\n hazbinLS=[1., 10., 100.], popbinLS=[100, 1000, 10000],\n hazbinLQ=[10., 100., 1000.], popbinLQ=[1000, 10000, 100000]):\n \"\"\"\n Get alert levels\n\n Args:\n paramalertLS (float): Hazard statistic of preferred landslide model\n paramalertLQ (float): Hazard statistic of preferred liquefaction model\n parampopLS (float): Exposure statistic of preferred landslide model\n parampopLQ (float): Exposure statistic of preferred liquefaction model\n hazbinLS (list): 3 element list of bin edges for landslide\n hazard alert between Green and Yellow, Yellow and Orange, and\n Orange and Red.\n popbinLS (list): same as above but for population exposure\n hazbinLQ (list): 3 element list of bin edges for liquefaction hazard\n alert between Green and Yellow, Yellow and Orange, and Orange\n and Red.\n popbinLQ (list): same as above but for population exposure\n\n Returns:\n Returns:\n tuple: (hazLS, popLS, hazLQ, popLQ, LS, LQ) where:\n * hazLS: the landslide hazard alert level (str)\n * popLS: the landslide population alert level (str)\n * hazLQ: the liquefaction hazard alert level (str)\n * popLQ: the liquefaction population alert level (str)\n * LS: the overall landslide alert level (str)\n * LQ: the overall liquefaction alert level (str)\n\n \"\"\"\n if paramalertLS is None:\n hazLS = None\n elif paramalertLS < hazbinLS[0]:\n hazLS = 'green'\n elif paramalertLS >= hazbinLS[0] and paramalertLS < hazbinLS[1]:\n hazLS = 'yellow'\n elif paramalertLS >= hazbinLS[1] and paramalertLS < hazbinLS[2]:\n hazLS = 'orange'\n elif paramalertLS > hazbinLS[2]:\n hazLS = 'red'\n else:\n hazLS = None\n\n if parampopLS is None:\n popLS = None\n elif parampopLS < popbinLS[0]:\n popLS = 'green'\n elif parampopLS >= popbinLS[0] and parampopLS < popbinLS[1]:\n popLS = 'yellow'\n elif parampopLS >= popbinLS[1] and parampopLS < popbinLS[2]:\n popLS = 'orange'\n elif parampopLS >= popbinLS[2]:\n popLS = 'red'\n else:\n popLS = None\n\n if paramalertLQ is None:\n hazLQ = None\n elif paramalertLQ < hazbinLQ[0]:\n hazLQ = 'green'\n elif paramalertLQ >= hazbinLQ[0] and paramalertLQ < hazbinLQ[1]:\n hazLQ = 'yellow'\n elif paramalertLQ >= hazbinLQ[1] and paramalertLQ < hazbinLQ[2]:\n hazLQ = 'orange'\n elif paramalertLQ >= hazbinLQ[2]:\n hazLQ = 'red'\n else:\n hazLQ = None\n\n if parampopLQ is None:\n popLQ = None\n elif parampopLQ < popbinLQ[0]:\n popLQ = 'green'\n elif parampopLQ >= popbinLQ[0] and parampopLQ < popbinLQ[1]:\n popLQ = 'yellow'\n elif parampopLQ >= popbinLQ[1] and parampopLQ < popbinLQ[2]:\n popLQ = 'orange'\n elif parampopLQ >= popbinLQ[2]:\n popLQ = 'red'\n else:\n popLQ = None\n\n num2color = {\n '1': 'green',\n '2': 'yellow',\n '3': 'orange',\n '4': 'red'\n }\n col2num = dict((v, k) for k, v in num2color.items())\n\n if popLS is not None and hazLS is not None:\n LSnum1 = col2num[hazLS]\n LSnum2 = col2num[popLS]\n LSnum = str(np.max([int(LSnum1), int(LSnum2)]))\n LS = num2color[LSnum]\n else:\n LS = None\n if popLQ is not None and hazLQ is not None:\n LQnum1 = col2num[hazLQ]\n LQnum2 = col2num[popLQ]\n LQnum = str(np.max([int(LQnum1), int(LQnum2)]))\n LQ = num2color[LQnum]\n else:\n LQ = None\n\n return hazLS, popLS, hazLQ, popLQ, LS, LQ\n\n\ndef view_database(database, starttime=None, endtime=None,\n minmag=None, maxmag=None, eventids=None,\n realtime=False, currentonly=False, numevents=None,\n LShazmin=None, LShazmax=None, LSpopmin=None,\n LSpopmax=None, LQhazmin=None, LQhazmax=None,\n LQpopmin=None, LQpopmax=None, verbose=False,\n printcols=None, csvfile=None, printsummary=True,\n printsuccess=False, printfailed=False,\n printnotmet=False, maxcolwidth=100,\n alertreport='value', realtime_maxsec=259200.):\n \"\"\"\n Prints out information from the ground failure database based on\n search criteria and other options. If nothing is defined except the\n database, it will print out a summary and details on the successful\n event runs only.\n\n Args:\n database (str): file path to event database (.db file)\n starttime (str): earliest earthquake time to include in the search,\n can be any string date recognizable by np.datetime\n endtime (str): latest earthquake time to include in the search,\n can be any string date recognizable by datetime\n minmag (float): minimum magnitude to include in search\n maxmag (float): maximum magnitude to include in search\n eventids (list): list of specific event ids to include (optional)\n realtime (bool): if True, will only include events that were run in\n near real time (defined by delay time less than realtime_maxsec)\n currentonly (bool): if True, will only include the most recent run\n of each event\n numevents (int): Include the numevents most recent events that meet\n search criteria\n LShazmin: minimum landslide hazard alert color ('green', 'yellow',\n 'orange', 'red') or minimum hazard alert statistic value\n LShazmax: same as above but for maximum landslide hazard alert\n value/color\n LSpopmin: same as above but for minimum landslide population alert\n value/color\n LSpopmax: same as above but for maximum landslide population alert\n value/color\n LQhazmin: same as above but for minimum liquefaction hazard alert\n value/color\n LQhazmax: same as above but for maximum liquefaction hazard alert\n value/color\n LQpopmin: same as above but for minimum liquefaction population alert\n value/color\n LQpopmax: same as above but for maximum liquefaction population alert\n value/color\n verbose (bool): if True, will print all columns (overridden if\n printcols is assigned)\n printcols (list): List of columns to print out (choose from id,\n eventcode, shakemap_version, note, version, lat, lon, depth,\n time, mag, location, starttime, endtime, eventdir,\n finitefault, HaggLS, ExpPopLS, HaggLQ, ExpPopLQ\n csvfile: If defined, saves csvfile of table of all events found\n (includes all fields and failed/non-runs)\n printsummary (bool): if True (default), will print summary of events\n found to screen\n printsuccess (bool): if True (default), will print out database entries\n for successful event runs found\n printfailed (bool): if True (default False), will print out information\n about failed event runs\n printnotmet (bool): if True (default False), will print out information\n about event runs that didn't meet criteria to run ground failure\n maxcolwidth (int): maximum column width for printouts of database\n entries.\n alertreport (str): 'value' if values of alert statistics should be\n printed, or 'color' if alert level colors should be printed\n realtime_maxsec (float): if realtime is True, this is the maximum delay\n between event time and processing end time in seconds\n to consider an event to be run in realtime\n\n Returns:\n Prints summaries and database info to screen as requested, saves a\n csv file if requested. Also returns a tuple where (success, fail,\n notmet, stats, criteria) where\n * success: pandas dataframe of selected events that ran\n successfully\n * fail: pandas dataframe of selected events that failed to run\n due to an error\n * notmet: pandas dataframe of selected events that failed to run\n because they did not meet the criteria to run ground failure\n * stats: dictionary containing statistics summarizing selected\n events where\n * aLSg/y/o/r is the number of overall alerts of green/yellow\n orange or red for landslides. If LS is replaced with LQ,\n it is the same but for liquefaction.\n * hazLSg/y/o/r same as above but for hazard alert level totals\n * popLSg/y/o/r same as above but for population alert level\n totals\n * nsuccess is the number of events that ran successfully\n * nfail is the number of events that failed to run\n * nnotmet is the number of events that didn't run because they\n did not meet criteria to run ground failure\n * nunique is the number of unique earthquake events run\n * nunique_success is the number of unique earthquake events\n that ran successfully\n * nrealtime is the number of events that ran in near-real-time\n * delay_median_s is the median delay time for near-real-time\n events (earthquake time until first GF run), also the same\n for mean, min, max, and standard deviation\n * criteria: dictionary containing info on what criteria were used\n for the search\n \"\"\"\n import warnings\n warnings.filterwarnings(\"ignore\")\n\n formatters = {\"time\": \"{:%Y-%m-%d}\".format,\n \"shakemap_version\": \"{:.0f}\".format,\n \"version\": \"{:.0f}\".format,\n \"starttime\": \"{:%Y-%m-%d %H:%M}\".format,\n \"endtime\": \"{:%Y-%m-%d %H:%M}\".format}\n\n criteria = dict(locals())\n # Define alert bins for later use\n hazbinLS = dict(green=[0., 1], yellow=[1., 10.], orange=[10., 100.],\n red=[100., 1e20])\n popbinLS = dict(green=[0., 100], yellow=[100., 1000.],\n orange=[1000., 10000.], red=[10000., 1e20])\n hazbinLQ = dict(green=[0., 10], yellow=[10., 100.], orange=[100., 1000.],\n red=[1000., 1e20])\n popbinLQ = dict(green=[0., 1000], yellow=[1000., 10000.],\n orange=[10000., 100000.], red=[100000., 1e20])\n\n connection = None\n connection = lite.connect(database)\n\n pd.options.display.max_colwidth = maxcolwidth\n\n # Read in entire shakemap table, do selection using pandas\n df = pd.read_sql_query(\"SELECT * FROM shakemap\", connection)\n\n df['starttime'] = pd.to_datetime(df['starttime'], utc=True)\n df['endtime'] = pd.to_datetime(df['endtime'], utc=True)\n df['time'] = pd.to_datetime(df['time'], utc=True)\n\n # Print currently running info to screen\n print('-------------------------------------------------')\n curt = df.loc[df['note'].str.contains('Currently running', na=False)]\n if len(curt) > 0:\n ccols = ['eventcode', 'time', 'shakemap_version', 'note', 'starttime']\n ccols2 = ['eventcode', 'time', 'shake_v', 'note', 'startrun']\n print('Currently running - %d runs' % len(curt))\n print('-------------------------------------------------')\n print(curt.to_string(columns=ccols, index=False,\n justify='left', header=ccols2,\n formatters=formatters))\n # Remove currently running from list\n df.drop(curt.index, inplace=True)\n\n else:\n print('No events currently running')\n print('-------------------------------------------------')\n\n okcols = list(df.keys())\n\n if eventids is not None:\n if not hasattr(eventids, '__len__'):\n eventids = [eventids]\n df = df.loc[df['eventcode'].isin(eventids)]\n\n if minmag is not None:\n df = df.loc[df['mag'] >= minmag]\n if maxmag is not None:\n df = df.loc[df['mag'] <= maxmag]\n\n # Narrow down the database based on input criteria\n\n # set default values for start and end\n endt = pd.to_datetime('now', utc=True)\n stt = pd.to_datetime('1700-01-01', utc=True)\n if starttime is not None:\n stt = pd.to_datetime(starttime, utc=True)\n if endtime is not None:\n endt = pd.to_datetime(endtime, utc=True)\n df = df.loc[(df['time'] > stt) & (df['time'] <= endt)]\n\n # Winnow down based on alert\n # Assign numerical values if colors were used\n\n if LShazmin is not None or LShazmax is not None:\n if LShazmin is None:\n LShazmin = 0.\n if LShazmax is None:\n LShazmax = 1e20\n if isinstance(LShazmin, str):\n LShazmin = hazbinLS[LShazmin][0]\n if isinstance(LShazmax, str):\n LShazmax = hazbinLS[LShazmax][1]\n df = df.loc[(df['HaggLS'] >= LShazmin) & (df['HaggLS'] <= LShazmax)]\n\n if LQhazmin is not None or LQhazmax is not None:\n if LQhazmin is None:\n LQhazmin = 0.\n if LQhazmax is None:\n LQhazmax = 1e20\n if isinstance(LQhazmin, str):\n LQhazmin = hazbinLQ[LQhazmin][0]\n if isinstance(LQhazmax, str):\n LQhazmax = hazbinLQ[LQhazmax][1]\n df = df.loc[(df['HaggLQ'] >= LQhazmin) & (df['HaggLQ'] <= LQhazmax)]\n\n if LSpopmin is not None or LSpopmax is not None:\n if LSpopmin is None:\n LSpopmin = 0.\n if LSpopmax is None:\n LSpopmax = 1e20\n if isinstance(LSpopmin, str):\n LSpopmin = popbinLS[LSpopmin][0]\n if isinstance(LSpopmax, str):\n LSpopmax = popbinLS[LSpopmax][1]\n df = df.loc[(df['ExpPopLS'] >= LSpopmin) &\n (df['ExpPopLS'] <= LSpopmax)]\n\n if LQpopmin is not None or LQpopmax is not None:\n if LQpopmin is None:\n LQpopmin = 0.\n if LQpopmax is None:\n LQpopmax = 1e20\n if isinstance(LQpopmin, str):\n LQpopmin = popbinLQ[LQpopmin][0]\n if isinstance(LQpopmax, str):\n LQpopmax = popbinLQ[LQpopmax][1]\n df = df.loc[(df['ExpPopLQ'] >= LQpopmin) &\n (df['ExpPopLQ'] <= LQpopmax)]\n\n # Figure out which were run in real time\n delays = []\n event_codes = df['eventcode'].values\n elist, counts = np.unique(event_codes, return_counts=True)\n keep = []\n rejects = []\n for idx in elist:\n vers = df.loc[df['eventcode'] == idx]['shakemap_version'].values\n if len(vers) == 0:\n rejects.append(idx)\n delays.append(float('nan'))\n continue\n sel1 = df.loc[df['eventcode'] == idx]\n # vermin = np.nanmin(vers)\n # sel1 = df.loc[(df['eventcode'] == idx) &\n # (df['shakemap_version'] == vermin)]\n if len(sel1) > 0:\n dels = []\n for index, se in sel1.iterrows():\n dels.append(np.timedelta64(se['endtime'] - se['time'], 's').astype(int))\n delay = np.nanmin(dels)\n if delay <= realtime_maxsec:\n keep.append(idx)\n delays.append(delay)\n else:\n delays.append(float('nan'))\n else:\n rejects.append(idx)\n delays.append(float('nan'))\n if realtime: # Keep just realtime events\n df = df.loc[df['eventcode'].isin(keep)]\n\n # Remove any bad/incomplete entries\n df = df.loc[~df['eventcode'].isin(rejects)]\n\n # Get only latest version for each event id if requested\n if currentonly:\n df.insert(0, 'Current', 0)\n ids = np.unique(df['eventcode'])\n for id1 in ids:\n # Get most recent one for each\n temp = df.loc[df['eventcode'] == id1].copy()\n dels2 = []\n for index, te in temp.iterrows():\n dels2.append(np.timedelta64(te['endtime'] - te['time'], 's').astype(int))\n idx = np.argmax(dels2)\n df.loc[df['endtime'] == temp.iloc[idx]['endtime'], 'Current'] = 1\n df = df.loc[df['Current'] == 1]\n df.drop_duplicates(inplace=True)\n\n # Keep just the most recent number requested\n if numevents is not None and numevents < len(df):\n df = df.iloc[(numevents*-1):]\n\n # Now that have requested dataframe, make outputs\n success = df.loc[(df['note'] == '') |\n (df['note'].str.contains('adjusted to'))]\n fail = df.loc[df['note'].str.contains('fail')]\n notmet = df.loc[(~df['note'].str.contains('fail')) & (df['note'] != '') &\n (~df['note'].str.contains('adjusted to'))]\n\n if len(df) == 0:\n print('No matching GF runs found')\n return\n cols = []\n if printcols is not None:\n for p in printcols:\n if p in okcols:\n cols.append(p)\n else:\n print('column %s defined in printcols does not exist in the '\n 'database' % p)\n elif verbose:\n cols = okcols\n else: # List of what we usually want to see\n cols = ['eventcode', 'mag', 'location', 'time', 'shakemap_version',\n 'version', 'HaggLS', 'ExpPopLS', 'HaggLQ', 'ExpPopLQ']\n\n # Compute overall alert stats (just final for each event)\n\n # get unique event code list of full database\n codes = df['eventcode'].values\n allevids, count = np.unique(codes, return_counts=True)\n nunique = len(allevids)\n\n # get unique event code list for success\n event_codes = success['eventcode'].values\n elist2, count = np.unique(event_codes, return_counts=True)\n nunique_success = len(elist2)\n # Get delays just for these events\n delays = np.array(delays)\n del_set = []\n for el in elist2:\n del_set.append(delays[np.where(elist == el)][0])\n\n # get final alert values for each\n hazalertLS = []\n hazalertLQ = []\n popalertLS = []\n popalertLQ = []\n alertLS = []\n alertLQ = []\n\n # Currently includes just the most current one\n for idx in elist2:\n vers = np.nanmax(success.loc[success['eventcode'] == idx]\n ['shakemap_version'].values)\n # endt5 = np.nanmax(success.loc[success['eventcode'] == idx]\n # ['endtime'].values)\n sel1 = success.loc[(success['eventcode'] == idx) &\n (success['shakemap_version'] == vers)]\n out = get_alert(sel1['HaggLS'].values[-1],\n sel1['HaggLQ'].values[-1],\n sel1['ExpPopLS'].values[-1],\n sel1['ExpPopLQ'].values[-1])\n hazLS, popLS, hazLQ, popLQ, LS, LQ = out\n hazalertLS.append(hazLS)\n hazalertLQ.append(hazLQ)\n popalertLS.append(popLS)\n popalertLQ.append(popLQ)\n alertLS.append(LS)\n alertLQ.append(LQ)\n\n origsuc = success.copy() # Keep copy\n\n # Convert all values to alert colors\n for index, row in success.iterrows():\n for k, bins in hazbinLS.items():\n if row['HaggLS'] >= bins[0] and row['HaggLS'] < bins[1]:\n success.loc[index, 'HaggLS'] = k\n for k, bins in hazbinLQ.items():\n if row['HaggLQ'] >= bins[0] and row['HaggLQ'] < bins[1]:\n success.loc[index, 'HaggLQ'] = k\n for k, bins in popbinLS.items():\n if row['ExpPopLS'] >= bins[0] and row['ExpPopLS'] < bins[1]:\n success.loc[index, 'ExpPopLS'] = k\n for k, bins in popbinLQ.items():\n if row['ExpPopLQ'] >= bins[0] and row['ExpPopLQ'] < bins[1]:\n success.loc[index, 'ExpPopLQ'] = k\n\n # Compile stats\n stats = dict(aLSg=len([a for a in alertLS if a == 'green']),\n aLSy=len([a for a in alertLS if a == 'yellow']),\n aLSo=len([a for a in alertLS if a == 'orange']),\n aLSr=len([a for a in alertLS if a == 'red']),\n hazLSg=len([a for a in hazalertLS if a == 'green']),\n hazLSy=len([a for a in hazalertLS if a == 'yellow']),\n hazLSo=len([a for a in hazalertLS if a == 'orange']),\n hazLSr=len([a for a in hazalertLS if a == 'red']),\n popLSg=len([a for a in popalertLS if a == 'green']),\n popLSy=len([a for a in popalertLS if a == 'yellow']),\n popLSo=len([a for a in popalertLS if a == 'orange']),\n popLSr=len([a for a in popalertLS if a == 'red']),\n aLQg=len([a for a in alertLQ if a == 'green']),\n aLQy=len([a for a in alertLQ if a == 'yellow']),\n aLQo=len([a for a in alertLQ if a == 'orange']),\n aLQr=len([a for a in alertLQ if a == 'red']),\n hazLQg=len([a for a in hazalertLQ if a == 'green']),\n hazLQy=len([a for a in hazalertLQ if a == 'yellow']),\n hazLQo=len([a for a in hazalertLQ if a == 'orange']),\n hazLQr=len([a for a in hazalertLQ if a == 'red']),\n popLQg=len([a for a in popalertLQ if a == 'green']),\n popLQy=len([a for a in popalertLQ if a == 'yellow']),\n popLQo=len([a for a in popalertLQ if a == 'orange']),\n popLQr=len([a for a in popalertLQ if a == 'red']),\n nsuccess=len(success),\n nfail=len(fail),\n nnotmet=len(notmet),\n nruns=len(df),\n nunique=nunique,\n nunique_success=nunique_success,\n nrealtime=np.sum(np.isfinite(del_set)),\n delay_median_s=float('nan'),\n delay_mean_s=float('nan'),\n delay_min_s=float('nan'),\n delay_max_s=float('nan'),\n delay_std_s=float('nan')\n )\n\n if np.sum(np.isfinite(del_set)) > 0:\n stats['delay_median_s'] = np.nanmedian(del_set)\n stats['delay_mean_s'] = np.nanmean(del_set)\n stats['delay_min_s'] = np.nanmin(del_set)\n stats['delay_max_s'] = np.nanmax(del_set)\n stats['delay_std_s'] = np.nanstd(del_set)\n\n # If date range not set by user\n if starttime is None:\n starttime = np.min(df['starttime'].values)\n if endtime is None:\n endtime = np.max(df['endtime'].values)\n\n # Now output selections in text, csv files, figures\n if csvfile is not None:\n name, ext = os.path.splitext(csvfile)\n if ext == '':\n csvfile = '%s.csv' % name\n if os.path.dirname(csvfile) == '':\n csvfile = os.path.join(os.getcwd(), csvfile)\n # make sure it's a path\n if os.path.isdir(os.path.dirname(csvfile)):\n df.to_csv(csvfile)\n else:\n raise Exception('Cannot save csv file to %s' % csvfile)\n\n # Print to screen\n if stats['nsuccess'] > 0 and printsuccess:\n print('Successful - %d runs' % stats['nsuccess'])\n print('-------------------------------------------------')\n cols2 = np.array(cols).copy()\n cols2[cols2 == 'shakemap_version'] = 'shake_v' # to save room printing\n cols2[cols2 == 'version'] = 'gf_v' # to save room printing\n cols2[cols2 == 'time'] = 'date' # to save room printing\n\n if alertreport == 'color':\n print(success.to_string(columns=cols, index=False, justify='left',\n header=list(cols2),\n formatters=formatters))\n else:\n print(origsuc.to_string(columns=cols, index=False, justify='left',\n header=list(cols2),\n formatters=formatters))\n print('-------------------------------------------------')\n\n if printfailed:\n if stats['nfail'] > 0:\n failcols = ['eventcode', 'location', 'mag', 'time',\n 'shakemap_version', 'note', 'starttime', 'endtime']\n failcols2 = ['eventcode', 'location', 'mag', 'time',\n 'shake_v', 'note', 'startrun', 'endrun']\n# if 'note' not in cols:\n# cols.append('note')\n print('Failed - %d runs' % stats['nfail'])\n print('-------------------------------------------------')\n print(fail.to_string(columns=failcols, index=False,\n formatters=formatters, justify='left', header=failcols2))\n else:\n print('No failed runs found')\n print('-------------------------------------------------')\n\n if printnotmet:\n if stats['nnotmet'] > 0:\n failcols = ['eventcode', 'location', 'mag', 'time',\n 'shakemap_version', 'note', 'starttime', 'endtime']\n failcols2 = ['eventcode', 'location', 'mag', 'time',\n 'shake_v', 'note', 'startrun', 'endrun']\n print('Criteria not met - %d runs' % stats['nnotmet'])\n print('-------------------------------------------------')\n print(notmet.to_string(columns=failcols, index=False,\n justify='left', header=failcols2,\n formatters=formatters))\n else:\n print('No runs failed to meet criteria')\n\n print('-------------------------------------------------')\n\n if printsummary:\n print('Summary %s to %s' % (str(starttime)[:10], str(endtime)[:10]))\n print('-------------------------------------------------')\n print('Of total of %d events run (%d unique)' % (stats['nruns'],\n stats['nunique']))\n print('\\tSuccessful: %d (%d unique)' % (stats['nsuccess'],\n stats['nunique_success']))\n print('\\tFailed: %d' % stats['nfail'])\n print('\\tCriteria not met: %d' % stats['nnotmet'])\n print('\\tRealtime: %d' % stats['nrealtime'])\n print('\\tMedian realtime delay: %1.1f mins' %\n (stats['delay_median_s']/60.,))\n print('-------------------------------------------------')\n print('Landslide overall alerts')\n print('-------------------------------------------------')\n print('Green: %d' % stats['aLSg'])\n print('Yellow: %d' % stats['aLSy'])\n print('Orange: %d' % stats['aLSo'])\n print('Red: %d' % stats['aLSr'])\n print('-------------------------------------------------')\n print('Liquefaction overall alerts')\n print('-------------------------------------------------')\n print('Green: %d' % stats['aLQg'])\n print('Yellow: %d' % stats['aLQy'])\n print('Orange: %d' % stats['aLQo'])\n print('Red: %d' % stats['aLQr'])\n print('-------------------------------------------------')\n print('Landslide hazard alerts')\n print('-------------------------------------------------')\n print('Green: %d' % stats['hazLSg'])\n print('Yellow: %d' % stats['hazLSy'])\n print('Orange: %d' % stats['hazLSo'])\n print('Red: %d' % stats['hazLSr'])\n print('-------------------------------------------------')\n print('Landslide population alerts')\n print('-------------------------------------------------')\n print('Green: %d' % stats['popLSg'])\n print('Yellow: %d' % stats['popLSy'])\n print('Orange: %d' % stats['popLSo'])\n print('Red: %d' % stats['popLSr'])\n print('-------------------------------------------------')\n print('Liquefaction hazard alerts')\n print('-------------------------------------------------')\n print('Green: %d' % stats['hazLQg'])\n print('Yellow: %d' % stats['hazLQy'])\n print('Orange: %d' % stats['hazLQo'])\n print('Red: %d' % stats['hazLQr'])\n print('-------------------------------------------------')\n print('Liquefaction population alerts')\n print('-------------------------------------------------')\n print('Green: %d' % stats['popLQg'])\n print('Yellow: %d' % stats['popLQy'])\n print('Orange: %d' % stats['popLQo'])\n print('Red: %d' % stats['popLQr'])\n print('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')\n\n if alertreport == 'value':\n return origsuc, fail, notmet, stats, criteria\n else:\n return success, fail, notmet, stats, criteria\n\n\ndef alert_summary(database, starttime=None, endtime=None,\n minmag=None, maxmag=None, realtime=True, currentonly=True,\n filebasename=None,\n summarytypes='all'):\n \"\"\"\n Print summary plot of alerts that have been issued for set of events met\n by defined criteria\n\n Args:\n database (str): file path to event database (.db file)\n starttime (str): earliest earthquake time to include in the search,\n can be any string date recognizable by np.datetime\n endtime (str): latest earthquake time to include in the search,\n can be any string date recognizable by datetime\n minmag (float): minimum magnitude to include in search\n maxmag (float): maximum magnitude to include in search\n realtime (bool): if True, will only include events that were run in\n near real time (defined by delay time less than realtime_maxsec)\n currentonly (bool): if True, will only include the most recent run\n of each event\n filebasename (str): If defined, will save a file with a modified\n version of this name depending on which alert is displayed, if no\n path is given it will save in current directory.\n summarytypes (str): if 'all', will create three figures, one for\n overall alerts, one for hazard alerts, and one for population\n alerts. If 'overall', 'hazard', or 'population' it will create\n just the one selected.\n\n Returns:\n List of figure handles in order ['overall', 'hazard', 'population']\n Figure files of alert level summaries\n\n \"\"\"\n\n out = view_database(database, starttime=starttime, endtime=endtime,\n minmag=minmag, maxmag=maxmag, realtime=realtime,\n currentonly=currentonly, printsummary=False,\n printsuccess=False, alertreport='color')\n stats = out[3]\n statsLS = []\n statsLQ = []\n types = []\n\n if summarytypes == 'overall' or summarytypes == 'all':\n statsLS.append([stats['aLSg'], stats['aLSy'], stats['aLSo'],\n stats['aLSr']])\n statsLQ.append([stats['aLQg'], stats['aLQy'], stats['aLQo'],\n stats['aLQr']])\n types.append('overall')\n if summarytypes == 'hazard' or summarytypes == 'all':\n statsLS.append([stats['hazLSg'], stats['hazLSy'], stats['hazLSo'],\n stats['hazLSr']])\n statsLQ.append([stats['hazLQg'], stats['hazLQy'], stats['hazLQo'],\n stats['hazLQr']])\n types.append('hazard')\n if summarytypes == 'population' or summarytypes == 'all':\n statsLS.append([stats['popLSg'], stats['popLSy'], stats['popLSo'],\n stats['popLSr']])\n statsLQ.append([stats['popLQg'], stats['popLQy'], stats['popLQo'],\n stats['popLQr']])\n types.append('population')\n figs = []\n for sLS, sLQ, typ in zip(statsLS, statsLQ, types):\n fig, ax = plt.subplots()\n index = np.arange(4)\n bar_width = 0.35\n fontsize = 12\n rects1 = ax.bar(index, sLS, bar_width,\n alpha=0.3,\n color='g',\n label='Landslide Alerts')\n\n rects2 = ax.bar(index + bar_width, sLQ, bar_width,\n alpha=0.7,\n color='g',\n label='Liquefaction Alerts')\n\n colors = ['g', 'y', 'orange', 'r']\n\n for r1, r2, c in zip(rects1, rects2, colors):\n if c == 'g':\n val = 1.00\n else:\n val = 1.05\n r1.set_color(c)\n r1.set_hatch('.')\n height = r1.get_height()\n ax.text(r1.get_x() + r1.get_width()/2., val*height,\n '%d' % int(height),\n ha='center', va='bottom', color=c,\n size=fontsize-2)\n r2.set_color(c)\n r2.set_hatch('/')\n height = r2.get_height()\n ax.text(r2.get_x() + r2.get_width()/2., val*height,\n '%d' % int(height),\n ha='center', va='bottom', color=c,\n size=fontsize-2)\n\n ax.set_xlabel('Alert', fontsize=fontsize)\n ax.set_ylabel('Total Events', fontsize=fontsize)\n\n ax.legend(fontsize=fontsize)\n\n plt.title('Ground failure %s alerts' % typ, fontsize=fontsize)\n plt.xticks(index + bar_width/2, ('Green', 'Yellow', 'Orange', 'Red'),\n fontsize=fontsize-2)\n plt.yticks(fontsize=fontsize-2)\n plt.show()\n\n if filebasename is not None:\n name, ext = os.path.splitext(filebasename)\n if ext == '':\n ext = '.png'\n fig.savefig('%s_%s%s' % (name, typ, ext), bbox_inches='tight')\n figs.append(fig)\n return figs\n\n\ndef plot_evolution(database, starttime=None, endtime=None,\n minmag=None, maxmag=None, eventids=None,\n filebasename=None, changeonly=True,\n percrange=None):\n \"\"\"\n Make a plot and print stats showing delay times and changes in alert\n statistics over time\n\n Args:\n database (str): file path to event database (.db file)\n starttime (str): earliest earthquake time to include in the search,\n can be any string date recognizable by np.datetime\n endtime (str): latest earthquake time to include in the search,\n can be any string date recognizable by datetime\n minmag (float): minimum magnitude to include in search\n maxmag (float): maximum magnitude to include in search\n eventids (list): list of specific event ids to include (optional)\n filebasename (str): If defined, will save a file with a modified\n version of this name depending on which alert is displayed, if no\n path is given it will save in current directory.\n changeonly (bool): if True will only show events that changed alert\n level at least once in the time evolution plots (unless eventids\n are defined, then all will show)\n percrange: percentile to use for error bars to show uncertainty\n as value <1 (e.g., 0.95). If None, errors will not be shown\n \n\n Returns:\n Figures showing alert changes over time and delay and alert change\n statistics\n \"\"\"\n fontsize = 10\n out = view_database(database, starttime=starttime, endtime=endtime,\n minmag=minmag, maxmag=maxmag, realtime=True,\n currentonly=False, printsummary=False,\n printsuccess=False, alertreport='value',\n eventids=eventids)\n if out is None:\n raise Exception('No events found that meet criteria')\n if eventids is not None:\n changeonly = False\n success = out[0].sort_values('starttime')\n elist = np.unique(success['eventcode'].values)\n HaggLS = []\n HaggLQ = []\n ExpPopLS = []\n ExpPopLQ = []\n eventtime = []\n times = []\n alertLS = []\n alertLQ = []\n descrip = []\n rangeHLS = []\n rangeHLQ = []\n rangeELS = []\n rangeELQ = []\n for idx in elist:\n sel1 = success.loc[success['eventcode'] == idx]\n hls = sel1['HaggLS'].values\n hlq = sel1['HaggLQ'].values\n pls = sel1['ExpPopLS'].values\n plq = sel1['ExpPopLQ'].values\n als = []\n alq = []\n for s, q, ps, pq in zip(hls, hlq, pls, plq):\n _, _, _, _, als1, alq1 = get_alert(s, q, ps, pq)\n als.append(als1)\n alq.append(alq1)\n alertLS.append(als)\n alertLQ.append(alq)\n HaggLS.append(hls)\n HaggLQ.append(hlq)\n ExpPopLS.append(pls)\n ExpPopLQ.append(plq)\n times.append(sel1['endtime'].values)\n eventtime.append(sel1['time'].values[-1])\n temp = success.loc[success['eventcode'] == idx]\n date = str(temp['time'].values[-1]).split('T')[0]\n descrip.append('M%1.1f %s (%s)' % (temp['mag'].values[-1],\n temp['location'].values[-1].title(), date))\n if percrange is not None:\n if percrange > 1 or percrange < 0.:\n raise Exception('uncertrange must be between 0 and 1')\n # Get range for input percentile\n # range for H\n range1 = get_rangebeta(sel1['PH_LS'], sel1['QH_LS'],\n prob=percrange, maxlim=sel1['HlimLS'])\n temp1 = [hls-range1[0], range1[1]-hls]\n temp1[0][temp1[0] < 0.] = 0 # zero out any negative values\n rangeHLS.append(temp1)\n range2 = get_rangebeta(sel1['PH_LQ'], sel1['QH_LQ'],\n prob=percrange, maxlim=sel1['HlimLQ'])\n temp2 = [hlq-range2[0], range2[1]-hlq]\n temp2[0][temp2[0] < 0.] = 0 # zero out any negative values\n rangeHLQ.append(temp2)\n # range for E\n # range for H\n range3 = get_rangebeta(sel1['PE_LS'], sel1['QE_LS'],\n prob=percrange, maxlim=sel1['ElimLS'])\n temp3 = [pls-range3[0], range3[1]-pls]\n temp3[0][temp3[0] < 0.] = 0\n rangeELS.append(temp3)\n range4 = get_rangebeta(sel1['PE_LQ'], sel1['QE_LQ'],\n prob=percrange, maxlim=sel1['ElimLQ'])\n temp4 = [plq-range4[0], range4[1]-plq]\n temp4[0][temp4[0] < 0.] = 0 # zero out any negative values\n rangeELQ.append(temp4)\n else:\n nanmat = np.empty((2, len(sel1)))\n nanmat[:] = np.NaN\n rangeHLS.append(nanmat)\n rangeHLQ.append(nanmat)\n rangeELS.append(nanmat)\n rangeELQ.append(nanmat)\n\n # Plot of changes over time to each alert level\n fig1, axes = plt.subplots(2, 1) # , figsize=(10, 10))\n ax1, ax2 = axes\n ax1.set_title('Landslide Summary Statistics', fontsize=fontsize)\n ax1.set_ylabel(r'Area Exposed to Hazard ($km^2$)', fontsize=fontsize)\n ax2.set_ylabel('Population Exposure', fontsize=fontsize)\n\n fig2, axes = plt.subplots(2, 1) # , figsize=(10, 10))\n ax3, ax4 = axes\n ax3.set_title('Liquefaction Summary Statistics', fontsize=fontsize)\n ax3.set_ylabel(r'Area Exposed to Hazard ($km^2$)', fontsize=fontsize)\n ax4.set_ylabel('Population Exposure', fontsize=fontsize)\n\n ax2.set_xlabel('Hours after earthquake', fontsize=fontsize)\n ax4.set_xlabel('Hours after earthquake', fontsize=fontsize)\n\n lqplot = 0\n lsplot = 0\n lsch = 0\n lqch = 0\n mindel = []\n\n zipped = zip(HaggLS, HaggLQ, ExpPopLS, ExpPopLQ, alertLS, alertLQ,\n descrip, times, eventtime)\n i = 0\n for hls, hlq, pls, plq, als, alq, des, t, et in zipped:\n resS = np.unique(als)\n resL = np.unique(alq)\n delays = [np.timedelta64(t1 - et, 's').astype(float) for t1 in t]\n mindel.append(np.min(delays))\n # Set to lower edge of green bin if zero so ratios will show up\n hls = np.array(hls)\n hls[hls == 0.] = lshbins[0]\n hlq = np.array(hlq)\n hlq[hlq == 0.] = lqhbins[0]\n pls = np.array(pls)\n pls[pls == 0.] = lspbins[0]\n plq = np.array(plq)\n plq[plq == 0.] = lqpbins[0]\n\n if (len(resS) > 1 or 'green' not in resS) or\\\n (len(resL) > 1 or 'green' not in resL):\n if len(resS) > 1 or not changeonly:\n if percrange is not None:\n ax1.errorbar(np.array(delays)/3600., hls,\n yerr=rangeHLS[i], label=des)\n ax2.errorbar(np.array(delays)/3600., pls, yerr=rangeELS[i])\n ax1.set_xscale(\"log\", nonposx='clip')\n ax1.set_yscale(\"log\", nonposy='clip')\n ax2.set_xscale(\"log\", nonposx='clip')\n ax2.set_yscale(\"log\", nonposy='clip')\n else:\n ax1.loglog(np.array(delays)/3600., hls, '.-', label=des)\n ax2.loglog(np.array(delays)/3600., pls, '.-')\n ax1.set_ylim([lshbins[0], np.max((lshbins[-1], np.max(hls)))])\n ax2.set_ylim([lspbins[0], np.max((lspbins[-1], np.max(pls)))])\n if changeonly:\n lsch += 1\n lsplot += 1\n if len(resL) > 1 or not changeonly:\n if percrange is not None:\n ax3.errorbar(np.array(delays)/3600., hlq, yerr=rangeHLQ[i],\n label=des)\n ax4.errorbar(np.array(delays)/3600., plq, yerr=rangeELQ[i])\n ax3.set_xscale(\"log\", nonposx='clip')\n ax3.set_yscale(\"log\", nonposy='clip')\n ax4.set_xscale(\"log\", nonposx='clip')\n ax4.set_yscale(\"log\", nonposy='clip')\n else:\n ax3.loglog(np.array(delays)/3600., hlq, '.-', label=des)\n ax4.loglog(np.array(delays)/3600., plq, '.-')\n ax3.set_ylim([lqhbins[0], np.max((lqhbins[-1], np.max(hlq)))])\n ax4.set_ylim([lqpbins[0], np.max((lqpbins[-1], np.max(plq)))])\n if changeonly:\n lqch += 1\n lqplot += 1\n i += 1\n print('%d of %d events had a liquefaction overall alert that changed' %\n (lqch, len(elist)))\n print('%d of %d events had a landslide overall alert that changed' %\n (lsch, len(elist)))\n\n if lsplot < 5:\n ax1.legend(fontsize=fontsize-3)\n if lqplot < 5:\n ax3.legend(fontsize=fontsize-3)\n ax1.tick_params(labelsize=fontsize-2)\n ax2.tick_params(labelsize=fontsize-2)\n ax3.tick_params(labelsize=fontsize-2)\n ax4.tick_params(labelsize=fontsize-2)\n ax1.grid(True)\n ax2.grid(True)\n ax3.grid(True)\n ax4.grid(True)\n\n alert_rectangles(ax1, lshbins)\n alert_rectangles(ax2, lspbins)\n alert_rectangles(ax3, lqhbins)\n alert_rectangles(ax4, lqpbins)\n\n if filebasename is not None:\n name, ext = os.path.splitext(filebasename)\n if ext == '':\n ext = '.png'\n fig1.savefig('%s_LSalert_evolution%s' % (name, ext),\n bbox_inches='tight')\n fig2.savefig('%s_LQalert_evolution%s' % (name, ext),\n bbox_inches='tight')\n\n\ndef time_delays(database, starttime=None, endtime=None,\n minmag=None, maxmag=None, eventids=None,\n filebasename=None):\n \"\"\"\n Make a plot and print stats showing delay times and changes in alert\n statistics over time\n\n Args:\n database (str): file path to event database (.db file)\n starttime (str): earliest earthquake time to include in the search,\n can be any string date recognizable by np.datetime\n endtime (str): latest earthquake time to include in the search,\n can be any string date recognizable by datetime\n minmag (float): minimum magnitude to include in search\n maxmag (float): maximum magnitude to include in search\n eventids (list): list of specific event ids to include (optional)\n filebasename (str): If defined, will save a file with a modified\n version of this name depending on which alert is displayed, if no\n path is given it will save in current directory.\n\n Returns:\n Figure showing delay and alert change statistics\n \"\"\"\n out = view_database(database, starttime=starttime, endtime=endtime,\n minmag=minmag, maxmag=maxmag, realtime=True,\n currentonly=False, printsummary=False,\n printsuccess=False, alertreport='value',\n eventids=eventids)\n\n success = out[0]\n elist = np.unique(success['eventcode'].values)\n HaggLS = []\n HaggLQ = []\n ExpPopLS = []\n ExpPopLQ = []\n eventtime = []\n times = []\n alertLS = []\n alertLQ = []\n descrip = []\n for idx in elist:\n sel1 = success.loc[success['eventcode'] == idx]\n hls = sel1['HaggLS'].values\n hlq = sel1['HaggLQ'].values\n pls = sel1['ExpPopLS'].values\n plq = sel1['ExpPopLQ'].values\n als = []\n alq = []\n for s, q, ps, pq in zip(hls, hlq, pls, plq):\n _, _, _, _, als1, alq1 = get_alert(s, q, ps, pq)\n als.append(als1)\n alq.append(alq1)\n alertLS.append(als)\n alertLQ.append(alq)\n HaggLS.append(hls)\n HaggLQ.append(hlq)\n ExpPopLS.append(pls)\n ExpPopLQ.append(plq)\n times.append(sel1['endtime'].values)\n eventtime.append(sel1['time'].values[-1])\n temp = success.loc[success['eventcode'] == idx]\n date = str(temp['time'].values[-1]).split('T')[0]\n descrip.append('M%1.1f %s (%s)' % (temp['mag'].values[-1],\n temp['location'].values[-1].title(), date))\n\n mindel = []\n delstableLS = []\n delstableLQ = []\n ratHaggLS = []\n ratHaggLQ = []\n ratPopLS = []\n ratPopLQ = []\n zipped = zip(HaggLS, HaggLQ, ExpPopLS, ExpPopLQ, alertLS, alertLQ,\n descrip, elist, times, eventtime)\n for hls, hlq, pls, plq, als, alq, des, el, t, et in zipped:\n delays = [np.timedelta64(t1 - et, 's').astype(float) for t1 in t]\n mindel.append(np.min(delays))\n delstableLS.append(delays[np.min(np.where(np.array(als) == als[-1]))])\n delstableLQ.append(delays[np.min(np.where(np.array(alq) == alq[-1]))])\n # Set to lower edge of green bin if zero so ratios will show up\n hls = np.array(hls)\n hls[hls == 0.] = 0.1\n ratHaggLS.append(hls[-1]/hls[0])\n hlq = np.array(hlq)\n hlq[hlq == 0.] = 1.\n ratHaggLQ.append(hlq[-1]/hlq[0])\n pls = np.array(pls)\n pls[pls == 0.] = 10.\n ratPopLS.append(pls[-1]/pls[0])\n plq = np.array(plq)\n plq[plq == 0.] = 100.\n ratPopLQ.append(plq[-1]/plq[0])\n\n # Don't bother making this plot when eventids are specified\n if eventids is None or len(eventids) > 25:\n # Histograms of delay times etc.\n fig, axes = plt.subplots(2, 2, figsize=(10, 10), sharey='col')\n ax1 = axes[0, 0]\n bins = np.logspace(np.log10(0.1), np.log10(1000.), 15)\n ax1.hist(np.array(mindel)/3600., color='k', edgecolor='k', alpha=0.5,\n bins=bins)\n\n ax1.set_xscale(\"log\")\n ax1.set_xlabel('Time delay to first run (hours)')\n ax1.set_ylabel('Number of events')\n vals = (np.nanmean(mindel)/3600., np.nanmedian(mindel)/3600.,\n np.nanstd(mindel)/3600.)\n # ax1.text(0.8, 0.8, 'mean: %1.1f hr\\nmedian: %1.1f hr\\nstd: %1.1f hr' %\n # vals, transform=ax1.transAxes, ha='center', va='center')\n ax1.text(0.8, 0.8, 'median: %1.1f hr' %\n vals[1], transform=ax1.transAxes, ha='center', va='center')\n delstableLS = np.array(delstableLS)\n delstableLQ = np.array(delstableLQ)\n delstable = np.max([delstableLS, delstableLQ], axis=0)\n\n ax2 = axes[1, 0]\n ax2.hist(np.array(delstable)/3600., color='k', edgecolor='k',\n alpha=0.5, bins=bins)\n ax2.set_xscale(\"log\")\n ax2.set_xlabel('Time delay till final alert color reached (hours)')\n ax2.set_ylabel('Number of events')\n vals = (np.nanmean(delstable)/3600., np.nanmedian(delstable)/3600.,\n np.nanstd(delstable)/3600.)\n # ax2.text(0.8, 0.8, 'mean: %1.1f hr\\nmedian: %1.1f hr\\nstd: %1.1f hr' %\n # vals, transform=ax2.transAxes, ha='center', va='center')\n ax2.text(0.8, 0.8, 'median: %1.1f hr' %\n vals[1], transform=ax2.transAxes, ha='center', va='center')\n\n print('Liquefaction overall alerts that changed stablized after a '\n 'median of %1.2f hours' %\n (np.median(delstableLQ[delstableLQ > 0.])/3600.))\n print('Landslide overall alerts that changed stablized after a median '\n 'of %1.2f hours' %\n (np.median(delstableLS[delstableLS > 0.])/3600.))\n\n ratHaggLS = np.array(ratHaggLS)\n ratHaggLQ = np.array(ratHaggLQ)\n ax3 = axes[0, 1]\n bins = np.logspace(np.log10(0.01), np.log10(100.), 9)\n ax3.hist(ratHaggLS[ratHaggLS != 1.], hatch='.', edgecolor='k',\n alpha=0.5, fill=False, label='Landslides',\n bins=bins)\n ax3.hist(ratHaggLQ[ratHaggLQ != 1.], hatch='/', edgecolor='k',\n alpha=0.5, fill=False, label='Liquefaction',\n bins=bins)\n ax3.set_xscale(\"log\")\n # ax3.set_xlabel(r'$H_{agg}$ final/$H_{agg}$ initial')\n ax3.set_xlabel(r'Area Exposed to Hazard $H_{final}/H_{initial}$')\n ax3.set_ylabel('Number of events')\n ax3.axvline(1., lw=2, color='k')\n arrowprops = dict(facecolor='black', width=1., headwidth=7.,\n headlength=7.)\n ax3.annotate('No change:\\nLS=%d\\nLQ=%d' %\n (len(ratHaggLS[ratHaggLS == 1.]),\n len(ratHaggLQ[ratHaggLQ == 1.])),\n xy=(0.5, 0.6), xycoords='axes fraction',\n textcoords='axes fraction', ha='center', va='center',\n xytext=(0.3, 0.6),\n arrowprops=arrowprops)\n ax3.legend(handlelength=2, handleheight=3, loc='upper right')\n\n ratPopLS = np.array(ratPopLS)\n ratPopLQ = np.array(ratPopLQ)\n ax4 = axes[1, 1]\n bins = np.logspace(np.log10(0.01), np.log10(100.), 9)\n ax4.hist(ratPopLS[ratPopLS != 1.], hatch='.', edgecolor='k',\n alpha=0.5, fill=False, bins=bins)\n ax4.hist(ratPopLQ[ratPopLQ != 1.], bins=bins,\n hatch='/', edgecolor='k', alpha=0.5, fill=False)\n ax4.set_xscale(\"log\")\n ax4.set_xlabel(r'Population Exposure $E_{final}/E_{initial}$')\n ax4.set_ylabel('Number of events')\n ax4.axvline(1., lw=2, color='k')\n ax4.annotate('No change:\\nLS=%d\\nLQ=%d' %\n (len(ratPopLS[ratPopLS == 1.]),\n len(ratPopLQ[ratPopLQ == 1.])),\n xy=(0.5, 0.75), xycoords='axes fraction',\n textcoords='axes fraction', xytext=(0.3, 0.75),\n arrowprops=arrowprops, ha='center', va='center')\n\n # Add letters\n ax1.text(0.02, 0.98, 'a)', transform=ax1.transAxes, ha='left',\n va='top', fontsize=14)\n ax2.text(0.02, 0.98, 'b)', transform=ax2.transAxes, ha='left',\n va='top', fontsize=14)\n ax3.text(0.02, 0.98, 'c)', transform=ax3.transAxes, ha='left',\n va='top', fontsize=14)\n ax4.text(0.02, 0.98, 'd)', transform=ax4.transAxes, ha='left',\n va='top', fontsize=14)\n\n plt.show()\n if filebasename is not None:\n name, ext = os.path.splitext(filebasename)\n fig.savefig('%s_alertdelay_stats%s' % (name, ext),\n bbox_inches='tight')\n\n\ndef plot_uncertainty(database, eventid, currentonly=True, filebasename=None,\n bars=False, percrange=0.95):\n \"\"\"\n Make a plot and print stats showing delay times and changes in alert\n statistics over time\n\n Args:\n database (str): file path to event database (.db file)\n eventid (str): event ids to plot\n currentonly (bool): if True, will only plot newest version, if False\n will plot all versions with different colors\n filebasename (str): If defined, will save a file with a modified\n version of this name depending on which alert is displayed, if no\n path is given it will save in current directory.\n bars (bool): if True, will use bars spanning percrange\n percrange (float): percentile to use for error bars to show uncertainty\n as value <1 (e.g., 0.95).\n\n Returns:\n Figure showing uncertainty\n \"\"\"\n\n fontsize = 12\n out = view_database(database, eventids=[eventid], currentonly=currentonly,\n printsummary=False)\n if out is None:\n raise Exception('No events found that meet criteria')\n\n success = out[0]\n nvers = len(success)\n # Get plots ready\n\n fig, axes = plt.subplots(2, 2, sharey=True, figsize=(14, 5))\n \n colors = np.flipud(np.linspace(0., 0.7, nvers))\n widths = np.ones(len(colors))\n # make last one thicker\n widths[-1] = 2.\n\n # Fill in plot\n i = 0\n offset = 0\n for index, row in success.iterrows():\n xvalsHLS, yvalsHLS, probsHLS = get_pdfbeta(row['PH_LS'], row['QH_LS'],\n lshbins,\n maxlim=row['HlimLS'])\n if bars:\n offset = i * 0.1\n valmin, valmax = get_rangebeta(row['PH_LS'], row['QH_LS'],\n prob=percrange,\n maxlim=row['HlimLS'])\n axes[0, 0].hlines(offset+0.1, valmin, valmax,\n color=str(colors[i]), lw=2)\n else:\n offset = 0.\n axes[0, 0].plot(xvalsHLS, yvalsHLS/np.max(yvalsHLS),\n color=str(colors[i]), lw=widths[i])\n axes[0, 0].plot(np.max((lshbins[0], row['HaggLS'])), offset, marker=7,\n color=str(colors[i]), markersize=11)\n #axes[0,0].text(row['HaggLS'], 0.13, '%1.0f' % row['version'],\n # color=str(colors[i]), ha='center')\n xvalsHLQ, yvalsHLQ, probsHLQ = get_pdfbeta(row['PH_LQ'], row['QH_LQ'],\n lqhbins,\n maxlim=row['HlimLQ'])\n if bars:\n valmin, valmax = get_rangebeta(row['PH_LQ'], row['QH_LQ'],\n prob=percrange,\n maxlim=row['HlimLQ'])\n axes[0, 1].hlines(offset+0.1, valmin, valmax,\n color=str(colors[i]), lw=2)\n else:\n axes[0, 1].plot(xvalsHLQ, yvalsHLQ/np.max(yvalsHLQ),\n color=str(colors[i]), lw=widths[i])\n axes[0, 1].plot(np.max((lqhbins[0], row['HaggLQ'])), offset, marker=7,\n color=str(colors[i]), markersize=11)\n #axes[0,1].text(row['HaggLQ'], 0.13, '%1.0f' % row['version'],\n # color=str(colors[i]), ha='center')\n xvalsELS, yvalsELS, probsELS = get_pdfbeta(row['PE_LS'], row['QE_LS'],\n lspbins,\n maxlim=row['ElimLS'])\n if bars:\n valmin, valmax = get_rangebeta(row['PE_LS'], row['QE_LS'],\n prob=percrange,\n maxlim=row['ElimLS'])\n axes[1, 0].hlines(offset+0.1, valmin, valmax,\n color=str(colors[i]), lw=2)\n else:\n axes[1, 0].plot(xvalsELS, yvalsELS/np.max(yvalsELS),\n color=str(colors[i]), lw=widths[i])\n axes[1, 0].plot(np.max((lspbins[0], row['ExpPopLS'])), offset,\n marker=7, color=str(colors[i]), markersize=11)\n #axes[1,0].text(row['ExpPopLS'], 0.13, '%1.0f' % row['version'],\n # color=str(colors[i]), ha='center')\n xvalsELQ, yvalsELQ, probsELQ = get_pdfbeta(row['PE_LQ'], row['QE_LQ'],\n lqpbins,\n maxlim=row['ElimLQ'])\n if bars:\n valmin, valmax = get_rangebeta(row['PE_LQ'], row['QE_LQ'],\n prob=percrange,\n maxlim=row['ElimLQ'])\n axes[1, 1].hlines(offset+0.1, valmin, valmax,\n color=str(colors[i]), lw=2)\n else:\n axes[1, 1].plot(xvalsELQ, yvalsELQ/np.max(yvalsELQ),\n color=str(colors[i]), lw=widths[i])\n axes[1, 1].plot(np.max((lqpbins[0], row['ExpPopLQ'])), offset,\n marker=7, color=str(colors[i]), markersize=11)\n #axes[1,1].text(row['ExpPopLQ'], 0.13, '%1.0f' % row['version'],\n # color=str(colors[i]), ha='center')\n\n i += 1\n \n if not bars:\n offset = 0.9\n elif offset < 0.7:\n offset = 0.7\n \n if nvers == 1:\n vals = [0.125, 0.375, 0.625, 0.875]\n for i in range(4):\n axes[0, 0].text(vals[i], 0.1, '%.2f' % probsHLS[i], ha='center',\n va='center', transform=axes[0, 0].transAxes)\n axes[0, 1].text(vals[i], 0.1, '%.2f' % probsHLQ[i], ha='center',\n va='center', transform=axes[0, 1].transAxes)\n axes[1, 0].text(vals[i], 0.1, '%.2f' % probsELS[i], ha='center',\n va='center', transform=axes[1, 0].transAxes)\n axes[1, 1].text(vals[i], 0.1, '%.2f' % probsELQ[i], ha='center',\n va='center', transform=axes[1, 1].transAxes)\n\n alertcolors = ['g', 'y', 'orange', 'r']\n for i in range(4):\n axes[0, 0].add_patch(patches.Rectangle((lshbins[i], -0.3),\n lshbins[i+1] - lshbins[i], 0.3,\n color=alertcolors[i], ec='k'))\n axes[1, 0].add_patch(patches.Rectangle((lspbins[i], -0.3),\n lspbins[i+1] - lspbins[i], 0.3,\n color=alertcolors[i], ec='k'))\n axes[0, 1].add_patch(patches.Rectangle((lqhbins[i], -0.3),\n lqhbins[i+1] - lqhbins[i], 0.3,\n color=alertcolors[i], ec='k'))\n axes[1, 1].add_patch(patches.Rectangle((lqpbins[i], -0.3),\n lqpbins[i+1] - lqpbins[i], 0.3,\n color=alertcolors[i], ec='k'))\n \n axes[0, 0].set_xlabel(r'Estimated Area Exposed to Hazard ($km^2$)',\n fontsize=fontsize)\n axes[1, 0].set_xlabel('Estimated Population Exposure', fontsize=fontsize)\n axes[0, 1].set_xlabel(r'Estimated Area Exposed to Hazard ($km^2$)',\n fontsize=fontsize)\n axes[1, 1].set_xlabel('Estimated Population Exposure', fontsize=fontsize)\n axes[0, 0].set_title('Landslides', fontsize=fontsize+2)\n axes[0, 1].set_title('Liquefaction', fontsize=fontsize+2)\n\n axes[0, 0].set_xlim([lshbins[0], lshbins[-1]])\n axes[1, 0].set_xlim([lspbins[0], lspbins[-1]])\n axes[0, 1].set_xlim([lqhbins[0], lqhbins[-1]])\n axes[1, 1].set_xlim([lqpbins[0], lqpbins[-1]])\n fig.canvas.draw()\n for ax in axes:\n for ax1 in ax:\n ax1.set_xscale('log')\n ax1.set_ylim([-0.3, offset+.2])\n ax1.tick_params(labelsize=fontsize)\n plt.setp(ax1.get_yticklabels(), visible=False)\n ax1.set_yticks([])\n ax1.axhline(0, color='k')\n# labels = [item.get_text() for item in ax1.get_xticklabels()]\n# labels[0] = '$\\leq$%s' % labels[0]\n# labels[-1] = '$\\geq$%s' % labels[-1]\n# ax1.set_xticklabels(labels)\n ax1.text(-0.065, -0.13, '<', transform=ax1.transAxes)\n ax1.text(0.95, -0.13, '>', transform=ax1.transAxes)\n\n plt.subplots_adjust(hspace=0.5)\n \n fig.suptitle('%4.f - M%1.1f - %s' % (row['time'].year,\n row['mag'], row['location']),\n fontsize=fontsize+2)\n plt.show()\n if filebasename is not None:\n name, ext = os.path.splitext(filebasename)\n fig.savefig('%s_uncertainty%s' % (name, ext),\n bbox_inches='tight')\n return fig\n\n\ndef alert_rectangles(ax, bins):\n \"\"\"\n Function used to color bin levels in background of axis\n \"\"\"\n colors = ['g', 'yellow', 'orange', 'r']\n xlims = ax.get_xlim()\n ylims = ax.get_ylim()\n for i, col in enumerate(colors):\n y = bins[i]\n y2 = bins[i+1]\n if col == 'g':\n corners = [[xlims[0], ylims[0]], [xlims[0], y2], [xlims[1], y2],\n [xlims[1], ylims[0]]]\n elif col == 'r':\n corners = [[xlims[0], y], [xlims[0], ylims[1]],\n [xlims[1], ylims[1]], [xlims[1], y]]\n else:\n corners = [[xlims[0], y], [xlims[0], y2], [xlims[1], y2],\n [xlims[1], y]]\n # add rectangle\n rect = patches.Polygon(corners, closed=True, facecolor=col,\n transform=ax.transData, alpha=0.2)\n ax.add_patch(rect)\n\n\ndef getFileType(filename):\n \"\"\"\n Determine whether input file is a shapefile or a grid (ESRI or GMT).\n\n Args:\n filename (str): Path to candidate filename.\n\n Returns:\n str: 'shapefile', 'grid', or 'unknown'.\n \"\"\"\n # TODO MOVE TO MAPIO.\n if os.path.isdir(filename):\n return 'dir'\n ftype = GMTGrid.getFileType(filename)\n if ftype != 'unknown':\n return 'gmt'\n # Skip over ESRI header files\n if filename.endswith('.hdr'):\n return 'unknown'\n try:\n GDALGrid.getFileGeoDict(filename)\n return 'esri'\n except:\n pass\n return 'unknown'\n","sub_path":"gfail/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":75800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"201587024","text":"\n\n\n\n\"\"\"\nGiven a stair with ‘n’ steps, implement a method to count how many \npossible ways are there to reach the top of the staircase, given that, \nat every step you can either take 1 step, 2 steps, or 3 steps.\n\nExample 1:\n\nNumber of stairs (n) : 3\nNumber of ways = 4\nExplanation: Following are the four ways we can climb : {1,1,1}, {1,2}, {2,1}, {3} \nExample 2:\n\nNumber of stairs (n) : 4\nNumber of ways = 7\nExplanation: Following are the seven ways we can climb : {1,1,1,1}, {1,1,2}, {1,2,1}, {2,1,1}, \n{2,2}, {1,3}, {3,1}\n\n\"\"\"\n\n\n# Time: O(N) Space: O(N)\ndef count_ways(n):\n dp = [0 for x in range(n+1)]\n return count_ways_recursive(dp, n)\n\n\ndef count_ways_recursive(dp, n):\n if n == 0:\n return 1 # base case, we don't need to take any step, so there is only one way\n\n if n == 1:\n return 1 # we can take one step to reach the end, and that is the only way\n\n if n == 2:\n return 2 # we can take one step twice or jump two steps to reach at the top\n\n if dp[n] == 0:\n # if we take 1 step, we are left with 'n-1' steps;\n take1Step = count_ways_recursive(dp, n - 1)\n # similarly, if we took 2 steps, we are left with 'n-2' steps;\n take2Step = count_ways_recursive(dp, n - 2)\n # if we took 3 steps, we are left with 'n-3' steps;\n take3Step = count_ways_recursive(dp, n - 3)\n\n dp[n] = take1Step + take2Step + take3Step\n\n return dp[n]\n\n\ndef main():\n\n print(count_ways(3))\n print(count_ways(4))\n print(count_ways(5))\n\n\nmain()\n","sub_path":"coding patterns/dynamic programming/fibonacci_numbers/staircase_topDownMemo.py","file_name":"staircase_topDownMemo.py","file_ext":"py","file_size_in_byte":1464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"145932976","text":"\n# -*- coding: utf-8 -*-\n\nfrom webapp2 import WSGIApplication\nfrom core.sugar import SugarRequestHandler\n\n\nclass MessageManagementHandler(SugarRequestHandler):\n\n def post(self):\n\n \"\"\"\n Obtiene los mensajes del buzón correspondiente al día recién cerrado.\n \"\"\"\n\n from core.logger import Logger\n from json import loads\n from clients.gmail_api import GmailApiClient\n\n try:\n # Obtenemos los datos de la petición.\n sender = loads(self.request.get(\"sender_account\"))\n recipients = loads(self.request.get(\"recipient_accounts\"))\n # Obtenemos los mensajes de la cuenta emisora.\n messages = self.find_messages(sender[\"email\"])\n resource = GmailApiClient(sender[\"email\"]).messages()\n if messages:\n # Por cada mensaje encontrado.\n for message in messages:\n # Creamos un mensaje.\n mssg = GmailApiClient.Message(resource.get(id=message[\"id\"]))\n # Creamos un mensaje para mappear el mensaje obtenido.\n mssg2 = GmailApiClient.MessageMapper()\n Logger.info(u\"From address: {}\".format(mssg.get_from()))\n Logger.info(u\"Sender address: {}\".format(mssg.get_sender()))\n # Seteamos los campos que nos interesan.\n mssg2.set_html_body(mssg.get_html_body())\n mssg2.set_subject(mssg.get_from() + \"$ \" + mssg.get_subject())\n mssg2.add_header(\"Return-Path\", u\"{}\".format(mssg.get_from()))\n mssg2.add_header(\"X-Env-Sender\", u\"{}\".format(mssg.get_from()))\n mssg2.from_address = u\"{}\".format(mssg.get_from())\n Logger.info(u\"New from: {}\".format(mssg2.from_address))\n # Agregamos los buzones receptores.\n for recipient in recipients:\n mssg2.add_recipient(recipient[\"email\"])\n sender_email = sender[\"email\"]\n response = GmailApiClient(sender_email).send_message(mssg2, sender_email)\n # Si obtenemos respuesta, borramos los mensajes del buzón emisor.\n if response:\n GmailApiClient(sender_email).messages().delete(\n id=message[\"id\"],\n userId=sender_email\n )\n\n except Exception as e:\n Logger.error(e)\n\n @classmethod\n def find_messages(cls, email):\n\n \"\"\"\n Obtiene la lista de mensajes recibidos en el buzón.\n :param email: Buzón de correo.\n :return: La lista de mensajes.\n \"\"\"\n\n from clients.gmail_api import GmailApiClient\n from core.logger import Logger\n\n try:\n messages = []\n resource = GmailApiClient(email).messages()\n page_token = None\n while True:\n response = resource.list(\n pageToken=page_token,\n includeSpamTrash=False,\n q=\"in:inbox is:unread\"\n )\n if \"messages\" in response:\n for message in response[\"messages\"]:\n if not any(x for x in messages if x[\"id\"] == message[\"id\"]):\n messages.append(message)\n if \"nextPageToken\" in response:\n page_token = response[\"nextPageToken\"]\n else:\n break\n except Exception as e:\n Logger.error(e)\n raise e\n return messages\n\n\nclass MessageLabelingHandler(SugarRequestHandler):\n\n def post(self):\n\n \"\"\"\n Etiqueta los mensajes del día recién cerrado.\n \"\"\"\n\n from json import loads\n from core.logger import Logger\n from clients.gmail_api import GmailApiClient\n from managers.rules import RulesManager\n\n try:\n # Obtenemos los datos de la petición.\n recipient = loads(self.request.get(\"recipient_account\"))\n messages = MessageManagementHandler.find_messages(recipient[\"email\"])\n resource = GmailApiClient(recipient[\"email\"]).messages()\n for message in messages:\n mssg = GmailApiClient.Message(resource.get(id=message[\"id\"]))\n # Por cada label existente en cada buzón receptor.\n for label in recipient[\"labels\"]:\n # Aplicamos la regla existente por cada label.\n for rule in label[\"rules\"]:\n rule = RulesManager(rule_id=rule[\"id\"]).get()\n if self.apply_rule(\n rule.rule,\n mssg.get_plain_body() if rule.field == \"body\" else\n mssg.get_from() if rule.field == \"to\" else\n mssg.get_subject(),\n message[\"id\"],\n label[\"gmail_id\"],\n resource\n ):\n break\n\n except Exception as e:\n Logger.error(e)\n\n def apply_rule(self, rule, field, message_id, label_id, resource):\n\n \"\"\"\n Busca una regla a aplicar en el subject del mensaje.\n :param rule: Regla a aplicar.\n :param field: Campo a aplicar la regla.\n :param message_id: Identificador del mensaje.\n :param label_id: Identificador de la label.\n :param resource: Recurso Gmail API.\n \"\"\"\n\n from re import MULTILINE, IGNORECASE, search\n from core.logger import Logger\n\n matches = search(rule, field, MULTILINE | IGNORECASE)\n if matches:\n Logger.info(\"Labeling message: {}\".format(message_id))\n # Modificamos el mensaje.\n resource.modify(\n id=message_id,\n body={\n \"addLabelIds\": [label_id], # Añadimos la etiqueta indicada.\n \"removeLabelIds\": [\"INBOX\"] # Quitamos el mensaje del inbox.\n }\n )\n return True\n return False\n\napp = WSGIApplication(\n routes=[\n (r\"^/tasks/message/management$\", MessageManagementHandler),\n (r\"^/tasks/message/labeling$\", MessageLabelingHandler)\n ],\n debug=True\n)\n","sub_path":"handlers/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":6425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"637237363","text":"#Author: Lzj\n#mail: harry_lee2683@outlook.com\n#Author: Lzj\n#mail: harry_lee2683@outlook.com\nimport time\ndef menu():\n print('''\n ------------Book Manager System--------------\n 1. registe book\n 2. borrow book\n 3. return book\n 4. search book\n 5. quit\n ''')\n jud = input(\"your number:\")\n\n if jud == \"1\":\n bm.registe()\n\n if jud == \"2\":\n bm.borrow()\n\n if jud == \"3\":\n bm.returnb()\n\n if jud == \"4\":\n bm.search()\n\n if jud == \"5\":\n exi()\n\nclass Book():\n def __init__(self,name,status=\"normal\",date=\"0000\"):\n self.name=name\n self.status=status\n self.date=date\n def __str__(self):\n return \"Book name is {}, date is {}, status is {}\".format(self.name,self.date,self.status)\n\nclass manager():\n\n def registe(self):\n inp=input(\"book name:\")\n dictbd=tod\n dictb=Book(name=inp,date=dictbd)\n dictbook[dictb.name]=dictb\n print(dictbook[dictb.name].date)\n CorE()\n\n def borrow(self):\n a=input(\"Input the book name: \")\n res = bm.check(a)\n if res == 0:\n print(\"Sorry, no book found....!\")\n else:\n\n if dictbook[a].status == \"borrowed\":\n print(\"The book {} has already >> {}\".format(a,res.status))\n else:\n dictbook[a].status=\"borrowed\"\n dictbook[a].date=tod\n print(\"----Updated----\")\n bm.check(a)\n CorE()\n\n def returnb(self):\n a = input(\"Input the book name: \")\n res = bm.check(a)\n if res == 0:\n print(\"Sorry, no book found....!\")\n else:\n if dictbook[a].status == \"normal\":\n print(\"The book is not borrowed\")\n else:\n dictbook[a].status = \"normal\"\n dictbook[a].date = tod\n print(\"----Updated----\")\n bm.check(a)\n CorE()\n\n def search(self):\n a=input(\"Book name: \")\n res=bm.check(a)\n if res == 0:\n print(\"Sorry, no book found....!\")\n CorE()\n\n def check(self, a):\n for i in dictbook:\n if i == a:\n print(dictbook[i])\n return dictbook[i]\n return 0\n\ndef CorE():\n jud=input(\"(C)ontinue or (E)xit\")\n if jud != \"E\":\n menu()\n else:\n exi()\ndef exi():\n print(\"Thank you. End.\")\n exit()\n\nbm = manager()\ndictbook = {}\ntod=time.strftime(\"%m%d\")\nmenu()\n","sub_path":"Linux-Oldboy-practical/L4-Python/realproject/day7/g20.py","file_name":"g20.py","file_ext":"py","file_size_in_byte":2499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"342771366","text":"for t in range(1, int(input())+1):\n n, m = map(int, input().split())\n arr = list(map(int, input().split()))\n pizza = []\n for k in range(1, n+1):\n pizza.append([k, arr.pop(0)])\n i = 0\n while len(pizza):\n d = i%n\n pizza[d][1] //= 2\n if not pizza[d][1]:\n if arr:\n k += 1\n pizza[d] = [k, arr.pop(0)]\n else:\n ans = pizza.pop(d)\n n -= 1\n i = d\n continue\n i += 1\n print(f'#{t} {ans[0]}')","sub_path":"class/hw/6주차/5099.py","file_name":"5099.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"470906609","text":"import tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\nLR = 0.1\nREAL_PARAMS = [1.2 , 2.5]\nINIT_PARAMS = [[5 , 4],\n [5 , 1],\n [2 , 4.5]]\nINIT_PARAMS = INIT_PARAMS[0] # \n\nx = np.linspace(-1 , 1 , 200 , dtype = np.float32) # x data\n\n#Test (1): Visualize a simple linear function with two parameters,\n#you can change LR to 1 to see the different pattern in gradient descent.\n\n#def y_fun(a , b , x): return a * x + b\n#def tf_y_fun(a , b , x): return a * x + b\ndef y_fun(a , b , x): return np.sin(b * np.cos(a * x))\ndef tf_y_fun(a , b , x): return tf.sin(b * tf.cos(a * x))\n\nnoise = np.random.randn(200) / 10 \ny = y_fun(REAL_PARAMS[0] , REAL_PARAMS[1] , x) + noise # target\n\n# tensorflow graph\nt_variable = [[] , []]\nfor p in range(0 , 2):\n t_variable[p] = tf.Variable(initial_value = INIT_PARAMS[p] , dtype = tf.float32)\n\npred = tf_y_fun(t_variable[0] , t_variable[1] , x)\nmse = tf.reduce_mean(tf.square(y - pred))\ntrain_op = tf.train.GradientDescentOptimizer(LR).minimize(mse)\nsess = tf.Session()\nsess.run(tf.global_variables_initializer())\na_list , b_list , cost_list = [] , [] , []\nfor t in range(1000):\n a_ , b_ , mse_ = sess.run([t_variable[0] , t_variable[1] , mse])\n a_list.append(a_)\n b_list.append(b_)\n cost_list.append(mse_) # record parameter changes\n result , _ = sess.run([pred , train_op]) # training\n\n\n# visualization codes:\nprint('a = ', a_, 'b = ', b_)\nplt.figure(1)\nplt.scatter(x , y , c = 'b') # plot data\nplt.plot(x , result , 'r-' , lw=2) # plot line fitting\n\n# 3D cost figure\nfig = plt.figure(2)\nax = Axes3D(fig)\na3D , b3D = np.meshgrid(np.linspace(-2 , 7 , 30) , np.linspace(-2 , 7 , 30)) # parameter space\n#cost3D = np.array([np.mean(np.square(y_fun(a_ , b_ , x) - y)) for a_ , b_ in zip(a3D.flatten() , b3D.flatten())]).reshape(a3D.shape)\ncost3D = np.zeros(a3D.shape)\nfor i in range(0 , a3D.shape[0]):\n for j in range(0 , a3D.shape[0]):\n cost3D[i , j] = np.mean(np.square(y_fun(a3D[i , j] , b3D[i , j] , x) - y))\nax.plot_surface(a3D , b3D , cost3D , rstride = 1 , cstride = 1 , cmap = plt.get_cmap('rainbow') , alpha = 0.7)\nax.scatter(a_list[0] , b_list[0] , zs=cost_list[0] , s = 1000 , c = 'r') # initial parameter place\nax.set_xlabel('a')\nax.set_ylabel('b')\nax.plot(a_list , b_list , zs = cost_list , zdir = 'z', c = 'g' , lw = 3) # plot 3D gradient descent\nplt.show()","sub_path":"Tensorflow_進階/03_Visualization_Gradient_Descent/visualization_gradient_descent.py","file_name":"visualization_gradient_descent.py","file_ext":"py","file_size_in_byte":2452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"4"}
+{"seq_id":"33297059","text":"from telegram.ext import Updater, CommandHandler\n\ndef start (update, context):\n\tupdate.message.reply_text('hola walter clavo')\n\nif __name__=='__main__':\n\n\tupdater = Updater(token='1655048016:AAFkysh83LjUHD47yEDclBupy0TXpcZ4r1s', use_context='True')\n\n\tdp = updater.dispatcher\n\tdp.add_handler(CommandHandler ('start', start))\n\n\tupdater.start_polling()\n\tupdater.idle()\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"544046078","text":"student = 'Mateusz'\nstypendium = 950\nwydatki = 920\n\nassert type(student) == str, \"Student == tekst\"\nassert type(stypendium) == int, \"Stypendium == liczba\"\nassert type(wydatki) == int, \"Wydatki == liczba\"\nassert wydatki < stypendium, \"Wy < st\"\nprint('Student: {}'.format(student.upper()))\nprint('stypendium: {} zł'.format(stypendium))\nprint('Wydatki: {} zł'.format(wydatki))\nprint('Oszczędności: {} zł'.format(stypendium-wydatki))","sub_path":"09-DefensiveProgramming/15.py","file_name":"15.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"223781139","text":"import tkinter as tk\n\n#----------VARIABLE DECLARATIONS----------\n\nroot = tk.Tk()\nroot.title('Disco Zoo Layouts')\n\n# 2D array for the 5x5 tile layout\ntiles = []\nfor i in range(5):\n tiles.append([0, 0, 0, 0, 0])\n\nselectedAnimals = []\n\ntotalLayouts = 0\n\nnumOfAnimals = 0\nlocationName = 'filler'\nanimalOptions = []\n\n#----------CLASS DECLARATIONS-----------\n\nclass pattern:\n class farm:\n sheep = [[1, 1, 1, 1]]\n pig = [[1, 1], [1, 1]]\n rabbit = [[1], [1], [1], [1]]\n horse = [[1], [1], [1]]\n cow = [[1, 1, 1]]\n unicorn = [[1, 0, 0], [0, 1, 1]]\n class outback:\n kangaroo = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]\n platypus = [[1, 1, 0], [0, 1, 1]]\n crocodile = [[1, 1, 1, 1]]\n koala = [[1, 1], [0, 1]]\n cockatoo = [[1, 0], [0, 1], [0, 1]]\n tiddalik = [[0, 1, 0], [1, 0, 1]]\n class savanna:\n zebra = [[0, 1, 0], [1, 0, 1], [0, 1, 0]]\n hippo = [[1, 0, 1], [0, 0, 0], [1, 0, 1]]\n giraffe = [[1], [1], [1], [1]]\n lion = [[1, 1, 1]]\n elephant = [[1, 1], [1, 0]]\n gryphon = [[1, 0, 1], [0, 1, 0]]\n class northern:\n bear = [[1, 1], [0, 1], [0, 1]]\n skunk = [[0, 1, 1], [1, 1, 0]]\n beaver = [[0, 0, 1], [1, 1, 0], [0, 0, 1]]\n moose = [[1, 0, 1], [0, 1, 0]]\n fox = [[1, 1, 0], [0, 0, 1]]\n sasquatch = [[1], [1]]\n class polar:\n penguin = [[0, 1, 0], [0, 1, 0], [1, 0, 1]]\n seal = [[1, 0, 0, 0], [0, 1, 0, 1], [0, 0, 1, 0]]\n muskox = [[1, 1, 0], [1, 0, 1]]\n polar_bear = [[1, 0, 1], [0, 0, 1]]\n walrus = [[1, 0, 0], [0, 1, 1]]\n yeti = [[1], [0], [1]]\n class jungle:\n monkey = [[1, 0, 1, 0], [0, 1, 0, 1]]\n toucan = [[0, 1], [1, 0], [0, 1], [0, 1]]\n gorilla = [[1, 0, 1], [1, 0, 1]]\n panda = [[0, 0, 1], [1, 0, 0], [0, 0, 1]]\n tiger = [[1, 0, 1, 1]]\n phoenix = [[1, 0, 0], [0, 0, 0], [0, 0, 1]]\n class jurassic:\n diplodocus = [[1, 0, 0], [0, 1, 1], [0, 1, 0]]\n stegosaurus = [[0, 1, 1, 0], [1, 0, 0, 1]]\n raptor = [[1, 1, 0], [0, 1, 0], [0, 0, 1]]\n t_rex = [[1, 0], [0, 0], [1, 1]]\n triceraptops = [[1, 0, 0], [0, 0, 1], [1, 0, 0]]\n dragon = [[1, 0, 0], [0, 0, 1]]\n class ice_age:\n wooly_rhino = [[0, 0, 1, 0], [1, 0, 0, 1], [0, 1, 0, 0]]\n giant_sloth = [[1, 0, 0], [0, 0, 1], [1, 0, 1]]\n dire_wolf = [[0, 1, 0, 0], [1, 0, 0, 1], [0, 1, 0, 0]]\n saber_tooth = [[1, 0, 0], [0, 0, 1], [0, 1, 0]]\n mammoth = [[0, 1, 0], [1, 0, 0], [0, 0, 1]]\n akhlut = [[0, 0, 1], [1, 0, 0], [0, 0, 1]]\n class city:\n raccoon = [[1, 0, 1, 0], [1, 0, 0, 1]]\n pigeon = [[1, 0, 0], [0, 1, 0], [0, 1, 1]]\n rat = [[1, 1, 0, 0], [0, 1, 0, 1]]\n squirrel = [[0, 0, 1], [1, 0, 0], [0, 1, 0]]\n opossum = [[1, 0, 0], [1, 0, 1]]\n sewer_turtle = [[1, 1]]\n class moon:\n moonkey = [[1, 0, 0], [1, 0, 1], [0, 0, 1]]\n lunar_tick = [[0, 1, 0], [0, 0, 0], [0, 1, 0], [1, 0, 1]]\n tribble = [[0, 1, 0], [1, 1, 1]]\n moonicorn = [[1, 0], [1, 1]]\n luna_moth = [[1, 0, 1], [0, 0, 0], [0, 1, 0]]\n jade_rabbit = [[1, 0], [0, 0], [0, 1]]\n class mountain:\n goat = [[1, 0, 0], [1, 1, 1]]\n cougar = [[1, 0, 0], [0, 1, 0], [1, 0, 1]]\n elk = [[1, 0, 1], [0, 1, 1]]\n eagle = [[1, 0], [1, 0], [0, 1]]\n coyote = [[1, 1, 0], [0, 0, 1]]\n aatxe = [[0, 0, 1], [1, 0, 0]]\n class mars:\n rock = [[1, 1], [1, 1]]\n marsmot = [[0, 1], [0, 1], [1, 1]]\n marsmoset = [[1, 0, 1], [0, 0, 1], [0, 1, 0]]\n rover = [[0, 1, 0], [1, 0, 1]]\n martian = [[1, 0, 1], [0, 1, 0]]\n marsmallow = [[1], [0], [1]]\n\n\n#----------FUNCTIONS----------\n\nclass buttons:\n class animalNums:\n def button_1():\n global numOfAnimals\n numOfAnimals = 1\n def button_2():\n global numOfAnimals\n numOfAnimals = 2\n def button_3():\n global numOfAnimals\n numOfAnimals = 3\n \n class locations:\n def farm():\n global locationName\n locationName = 'farm'\n def outback():\n global locationName\n locationName = 'outback'\n def savanna():\n global locationName\n locationName = 'savanna'\n def northern():\n global locationName\n locationName = 'northern'\n def polar():\n global locationName\n locationName = 'polar'\n def jungle():\n global locationName\n locationName = 'jungle'\n def jurassic():\n global locationName\n locationName = 'jurassic'\n def ice_age():\n global locationName\n locationName = 'ice_age'\n def city():\n global locationName\n locationName = 'city'\n def moon():\n global locationName\n locationName = 'moon'\n def mountain():\n global locationName\n locationName = 'mountain'\n def mars():\n global locationName\n locationName = 'mars'\n\n class animalOptionsClass:\n def animal_0():\n global selectedAnimals, animalOptions\n selectedAnimals.append(animalOptions[0])\n del animalOptions[0]\n def animal_1():\n global selectedAnimals, animalOptions\n selectedAnimals.append(animalOptions[1])\n del animalOptions[1]\n def animal_2():\n global selectedAnimals, animalOptions\n selectedAnimals.append(animalOptions[2])\n del animalOptions[2]\n def animal_3():\n global selectedAnimals, animalOptions\n selectedAnimals.append(animalOptions[3])\n del animalOptions[3]\n def animal_4():\n global selectedAnimals, animalOptions\n selectedAnimals.append(animalOptions[4])\n del animalOptions[4]\n def animal_5():\n global selectedAnimals, animalOptions\n selectedAnimals.append(animalOptions[5])\n del animalOptions[5]\n\n class phases:\n # ask how many animals will be chosen\n def phase1():\n clearScreen()\n\n label_askNumOfAnimals = tk.Label(root, text = 'How many animals are you going to chose?')\n label_askNumOfAnimals.grid(row=0, column=0)\n\n numButtons = [\n tk.Button(root, text='1', command = lambda:[buttons.animalNums.button_1(), buttons.phases.phase2()]),\n tk.Button(root, text='2', command = lambda:[buttons.animalNums.button_2(), buttons.phases.phase2()]),\n tk.Button(root, text='3', command = lambda:[buttons.animalNums.button_3(), buttons.phases.phase2()])\n ]\n\n for i in range(len(numButtons)):\n numButtons[i].grid(row = i+1, column = 0)\n\n # ask for the location\n def phase2():\n clearScreen()\n\n label_askLocation = tk.Label(root, text = 'What location do you want to choose animals from?')\n label_askLocation.grid(row=0, column=0)\n\n locationButtons = [\n tk.Button(root, text = 'Farm', command = lambda:[buttons.locations.farm(), buttons.phases.phase3a()]),\n tk.Button(root, text = 'Outback', command = lambda:[buttons.locations.outback(), buttons.phases.phase3a()]),\n tk.Button(root, text = 'Savanna', command = lambda:[buttons.locations.savanna(), buttons.phases.phase3a()]),\n tk.Button(root, text = 'Northern', command = lambda:[buttons.locations.northern(), buttons.phases.phase3a()]),\n tk.Button(root, text = 'Polar', command = lambda:[buttons.locations.polar(), buttons.phases.phase3a()]),\n tk.Button(root, text = 'Jungle', command = lambda:[buttons.locations.jungle(), buttons.phases.phase3a()]),\n tk.Button(root, text = 'Jurassic', command = lambda:[buttons.locations.jurassic(), buttons.phases.phase3a()]),\n tk.Button(root, text = 'Ice Age', command = lambda:[buttons.locations.ice_age(), buttons.phases.phase3a()]),\n tk.Button(root, text = 'City', command = lambda:[buttons.locations.city(), buttons.phases.phase3a()]),\n tk.Button(root, text = 'Moon', command = lambda:[buttons.locations.moon(), buttons.phases.phase3a()]),\n tk.Button(root, text = 'Mountain', command = lambda:[buttons.locations.mountain(), buttons.phases.phase3a()]),\n tk.Button(root, text = 'Mars', command = lambda:[buttons.locations.mars(), buttons.phases.phase3a()])\n ]\n\n for i in range(len(locationButtons)):\n locationButtons[i].grid(row = i+1, column = 0)\n \n # ask for chosen animal 1\n def phase3a():\n global animalOptions\n\n clearScreen()\n\n animalOptions = calcAnimalOptions(locationName)\n\n label_askLocation = tk.Label(root, text = 'What is animal #1')\n label_askLocation.grid(row=0, column=0)\n\n animalButtons = []\n for i in range(len(animalOptions)):\n animalButtons.append(tk.Button(root, text = animalOptions[i], command = lambda:[eval('buttons.animalOptionsClass.animal_' + str(i)), buttons.phases.phase3b()]))\n \n for i in range(len(animalButtons)):\n animalButtons[i].grid(row = i+1, column = 0)\n \n # ask for chosen animal 2, if there is one\n def phase3b():\n global animalOptions\n \n if numOfAnimals >= 2:\n clearScreen()\n\n label_askLocation = tk.Label(root, text = 'What is animal #2')\n label_askLocation.grid(row=0, column=0)\n\n animalButtons = []\n for i in range(len(animalOptions)):\n animalButtons.append(tk.Button(root, text = animalOptions[i], command = lambda:[eval('buttons.animalOptionsClass.animal_' + str(i)), buttons.phases.phase3c()]))\n \n for i in range(len(animalButtons)):\n animalButtons[i].grid(row = i+1, column = 0)\n else:\n buttons.phases.phase3c()\n \n # ask for chosen animal 3, if there is one\n def phase3c():\n global animalOptions\n \n if numOfAnimals >= 3:\n clearScreen()\n\n label_askLocation = tk.Label(root, text = 'What is animal #3')\n label_askLocation.grid(row=0, column=0)\n\n animalButtons = []\n for i in range(len(animalOptions)):\n animalButtons.append(tk.Button(root, text = animalOptions[i], command = lambda:[eval('buttons.animalOptionsClass.animal_' + str(i)), buttons.phases.phase4()]))\n \n for i in range(len(animalButtons)):\n animalButtons[i].grid(row = i+1, column = 0)\n else:\n buttons.phases.phase4()\n \n def phase4():\n clearScreen()\n\n print('phase 4 activated')\n\n\ndef clearScreen():\n widget_list = root.winfo_children()\n\n for item in widget_list :\n if item.winfo_children() :\n widget_list.extend(item.winfo_children())\n \n for item in widget_list:\n item.grid_remove()\n\n\ndef combineArrays(baseArray, arrayToAdd, offset=(0, 0)):\n array1 = baseArray.copy()\n array2 = arrayToAdd.copy()\n \n offX = offset[1]\n offY = offset[0]\n \n newArray = []\n for i in range(len(array1)):\n newArray.append(array1[i].copy())\n\n for i in range(len(array2)):\n for j in range(len(array2[0])):\n newArray[i+offX][j+offY] = array1[i+offX][j+offY] + array2[i][j]\n \n return newArray\n\n\ndef calcAnimalOptions(location):\n if location == 'farm':\n animals = ['sheep', 'pig', 'rabbit', 'horse', 'cow', 'unicorn']\n elif location == 'outback':\n animals = ['kangaroo', 'platypus', 'crocodile', 'koala', 'cockatoo', 'tiddalik']\n elif location == 'savanna':\n animals = ['zebra', 'hippo', 'giraffe', 'lion', 'elephant', 'gryphon']\n elif location == 'northern':\n animals = ['bear', 'skunk', 'beaver', 'moose', 'fox', 'sasquatch']\n elif location == 'polar':\n animals = ['penguin', 'seal', 'muskox', 'polar bear', 'walrus', 'yeti']\n elif location == 'jungle':\n animals = ['monkey', 'toucan', 'gorilla', 'panda', 'tiger', 'phoenix']\n elif location == 'jurassic':\n animals = ['diplodocus', 'stegosaurus', 'raptor', 't-rex', 'triceraptops', 'dragon']\n elif location == 'ice_age':\n animals = ['wooly rhino', 'giant sloth', 'dire wolf', 'saber tooth', 'mammoth', 'akhlut']\n elif location == 'city':\n animals = ['raccoon', 'pigeon', 'rat', 'squirrel', 'opossum', 'sewer turtle']\n elif location == 'moon':\n animals = ['lunar tick', 'moonkey', 'tribble', 'luna moth', 'moonicorn', 'jade rabbit']\n elif location == 'mountain':\n animals = ['goat', 'cougar', 'elk', 'eagle', 'coyote', 'aatxe']\n elif location == 'mars':\n animals = ['rock', 'marsmot', 'marsmoset', 'rover', 'martian', 'marsmallow']\n \n return animals\n\n\ndef identifyAnimals():\n global selectedAnimals\n\n #locationName = input('Locations are farm, outback, savanna, northern, polar, jungle, jurassic, ice age, city, moon, mountain, and mars. What location do you want to choose animals from?: ').lower()\n #locationName = locationName.replace(' ', '_')\n #numOfAnimals = int(input('How many animals are you going to choose? Options are 1-3: '))\n\n for i in range(numOfAnimals):\n animalOptions = calcAnimalOptions(locationName)\n \n inputMSG = '{} animals are {}. What is animal number {}?: '.format(locationName.capitalize(), animalOptions, i+1)\n animal = input(inputMSG).lower().replace(' ', '_').replace('-', '_')\n \n selectedAnimals.append([animal, getattr(eval('pattern.'+locationName), animal)])\n\n\ndef checkForValidLayout(layout):\n possibleLayout = True\n\n for i in range(5):\n for j in range(5):\n if layout[i][j] > 1:\n possibleLayout = False\n\n if possibleLayout:\n return True\n else:\n return False\n\n\ndef findAllLayouts():\n global totalLayouts\n\n # how many times to go across x\n for x1 in range(6 - len(selectedAnimals[0][1][0])):\n # how many times to go across y\n for y1 in range(6 - len(selectedAnimals[0][1])):\n tiles1 = combineArrays(tiles, selectedAnimals[0][1], (x1, y1))\n\n # runs if theres more than 1 animal\n if len(selectedAnimals) > 1:\n # how many times to go across x\n for x2 in range(6 - len(selectedAnimals[1][1][0])):\n # how many times to go across y\n for y2 in range(6 - len(selectedAnimals[1][1])):\n tiles2 = combineArrays(tiles1, selectedAnimals[1][1], (x2, y2))\n\n # runs if the layout works for the first 2 animals\n if checkForValidLayout(tiles2):\n # runs if theres more than 2 animals\n if len(selectedAnimals) > 2:\n # how many times to go across x\n for x3 in range(6 - len(selectedAnimals[2][1][0])):\n # how many times to go across y\n for y3 in range(6 - len(selectedAnimals[2][1])):\n tiles3 = combineArrays(tiles2, selectedAnimals[2][1], (x3, y3))\n \n if checkForValidLayout(tiles3):\n totalLayouts += 1\n else:\n totalLayouts += 1\n else:\n totalLayouts += 1\n \n\ndef printTotalLayouts():\n if len(selectedAnimals) == 1:\n print('There are', str(totalLayouts), 'total layouts for the animal', selectedAnimals[0][0])\n elif len(selectedAnimals) == 2:\n print('There are', str(totalLayouts), 'total layouts for the animals', selectedAnimals[0][0], 'and', selectedAnimals[1][0])\n else:\n print('There are', str(totalLayouts), 'total layouts for the animals', selectedAnimals[0][0] + ',', selectedAnimals[1][0] + ',', 'and a', selectedAnimals[2][0])\n\n\n#----------THE MAIN STUFF----------\n\nbutton_start = tk.Button(root, text = 'start', command = buttons.phases.phase1)\nbutton_start.grid(row=0, column=0)\n\nroot.mainloop()\n'''\nidentifyAnimals()\nfindAllLayouts()\nprintTotalLayouts()\n'''","sub_path":"DiscoZooLayouts.py","file_name":"DiscoZooLayouts.py","file_ext":"py","file_size_in_byte":16854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"626664621","text":"import discord\nfrom discord import *\nimport asyncio\nimport tldextract\nimport requests\nimport json\nfrom urllib.parse import urlparse\nfrom utils import cprint, url_validator, load_paywalls, load_token, and_includes, or_includes, strip\nimport random\nfrom ast import literal_eval\nfrom datetime import datetime, timedelta\n\n# load paywalled sites\npaywalled_sites = load_paywalls()\n\n# load bot token\ntoken = load_token()\n\n# creates discord Client object\nclient = discord.Client()\n\n#check last rate limiter check in time\nlast_check_in = None\n\n# all responses triggered by a message are thrown in here\n@client.event\nasync def on_message(message: Message):\n \n \n\n global paywalled_sites # include list of paywalled site inside this function\n global last_check_in\n \n #rate limiter\n if message:\n try:\n #TODO: Put some random fuzz on the checkin timedelta\n #TODO: Lower the checkin time delta based on the subsequent frequency\n if not last_check_in or last_check_in < (message.created_at - timedelta(seconds = 60)):\n #grab the non-bot members\n memb_ls=[m async for m in message.guild.fetch_members(limit=None) if not m.bot]\n #grab the last ten minutes of messages, up to 600 messages\n last_check_in = message.created_at\n ten_min_ago = message.created_at - timedelta(seconds = 600)\n messages = await message.channel.history(limit = 600, after = ten_min_ago).flatten()\n #get the history of message authors who aren't bots\n human_authors_history = [m.author for m in messages if m.author in memb_ls] \n #get the unique authors\n human_author_set = set(human_authors_history)\n #if two users are talking\n prefix = None\n if len(human_author_set) == 2:\n prefix = f\"{list(human_author_set)[0].mention} and {list(human_author_set)[1].mention} are \"\n #if one user is talking to themself\n elif len(human_author_set) == 1:\n prefix = f\"{list(human_author_set)[0].mention} is \"\n if prefix:\n if len(messages) > 100:\n await message.channel.send(prefix + \"going at it. Wow!\")\n if len(messages) > 200:\n await message.channel.send(prefix + \"getting into some serious behavior.\")\n if len(messages) > 300:\n await message.channel.send(prefix + \"setting a record!\")\n if len(messages) > 400:\n await message.channel.send(prefix + \"very serious about this!\")\n if len(messages) > 500:\n await message.channel.send(prefix + \", shut up. Please.\")\n except:\n pass\n\n if message.content.startswith('!paywall'):\n # Manually link to archive.is\n # Format: `!paywall URL` will link to archive.is/URL\n words = message.content.split(\" \")\n await message.channel.send(f\"https://www.archive.is/{words[1]}\")\n\n if and_includes(message.content, 'thank', 'soros'):\n # Responds to Sal when he says 'Thanks Soros'\n # (note: not antisemitic joke, used to mock the antisemitic globalist Soros stories)\n await message.channel.send('No problemo buckaroo, anything for a fellow reptile.')\n \n if and_includes(message.content, 'who', 'horrible'):\n # You know what this does\n await message.channel.send(f\"Why, {message.author.mention} of course!\")\n\n if or_includes(message.content, 'socialis', 'communis'):\n # You know what this does\n await message.channel.send(f\"AJ is the real commie here!\")\n \n if or_includes(message.content, 'shane', 'metricity', 'the best') and (message.author != client.user):\n await message.channel.send(f\"Shane really is the best.\")\n \n if or_includes(message.content, \"suck\", \"sux\") and (message.author != client.user):\n # ya know what this does too\n await message.channel.send(\"You know what else sucks? Salex Bexman.\")\n\n if url_validator(message.content):\n # Checks if message is a valid URL and a paywalled domain. If it is, returns the archive.is link.\n raw_url = message.content\n url = tldextract.extract(message.content)\n if url.domain in paywalled_sites:\n await message.channel.send(f\"https://www.archive.is/{raw_url}\")\n \n if message.content.startswith('!add'):\n # Add new domains to list of paywalled domains\n # Format: `!add DOMAIN_1 DOMAIN_2 ... DOMAIN_n` will add DOMAIN_1 thru DOMAIN_n to list\n # of paywalled sites and respond with a confirmation message.\n new_paywalls = message.content.split(\" \")[1:]\n paywalled_sites += new_paywalls\n paywalled_sites = list(set(paywalled_sites))\n paywalled_sites = [i for i in paywalled_sites if i != \"\"]\n with open('paywalled', 'w') as file:\n sites = \"\\n\".join(paywalled_sites)\n file.write(sites)\n await message.channel.send('**Added the following domains:**' + \"\\n\" + cprint(new_paywalls))\n\n if message.content.startswith('!delete'):\n # Delete domains to list of paywalled domains\n # Format: `!add DOMAIN_1 DOMAIN_2 ... DOMAIN_n` will add DOMAIN_1 thru DOMAIN_n to list\n # of paywalled sites and respond with a confirmation message.\n new_paywalls = message.content.split(\" \")[1:]\n paywalled_sites = [i for i in paywalled_sites if i not in new_paywalls]\n with open('paywalled', 'w') as file:\n sites = \"\\n\".join(paywalled_sites)\n file.write(sites)\n await message.channel.send('**Deleted the following domains:**' + \"\\n\" + cprint(new_paywalls))\n \n if message.content.startswith(\"!list paywalls\"):\n # Displays list of all sites on the current paywall list\n await message.channel.send(\"**Paywalled sites:**\" + \"\\n\" + cprint(sorted(paywalled_sites)))\n \n if message.content.startswith(\"!test\"):\n await message.channel.send(\"Stop spamming the fucking chat with your damn tests u chode.\")\n \n if message.content.startswith(\"!gif\"):\n async with message.channel.typing(): #makes the channel say the bot is typing\n scope = 1\n melee = False\n num_gifs = 1\n parsed = message.content.split(\" \")\n if parsed[1] == 'melee':\n melee = True\n stripped = [strip(word) for word in parsed[2:]]\n else:\n stripped = [strip(word) for word in parsed[1:]]\n search = \"+\".join(stripped)\n try:\n scope_str = parsed[0][4:]\n scope = int(scope_str)\n if melee:\n num_gifs = scope\n except:\n pass\n choice = random.randint(1, scope)\n response = requests.get(f\"https://api.giphy.com/v1/gifs/search?q={search}&api_key=WiLstLIo2SInusTmGDDkhhY0tU6xKNEl&limit={num_gifs}&offset={choice}\")\n if response.status_code != 200:\n await message.channel.send(\"U stupid bruh, bad request.\")\n else:\n gifs = response.json()['data']\n gif_urls = [gif['url'] for gif in gifs]\n for url in gif_urls:\n await message.channel.send(url)\n\n if message.content.startswith(\"!calc\"):\n async with message.channel.typing(): #makes the channel say the bot is typing\n terms = \" \".join(message.content.split(\" \")[1:])\n await message.channel.send(eval(terms))\n\nif __name__ == \"__main__\":\n client.run(token)","sub_path":"archivist.py","file_name":"archivist.py","file_ext":"py","file_size_in_byte":7776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"94399098","text":"\"\"\"\nConstructing and loading dictionaries\n\"\"\"\nimport pickle as pkl\nimport numpy\nfrom collections import OrderedDict\nimport argparse\nimport time\n\ndef build_dictionary(text):\n \"\"\"\n Build a dictionary\n text: list of sentences (pre-tokenized)\n \"\"\"\n wordcount = {}\n for cc in text:\n words = cc.split()\n for w in words:\n if w not in wordcount:\n wordcount[w] = 0\n wordcount[w] += 1\n words = list(wordcount.keys())\n freqs = list(wordcount.values())\n sorted_idx = numpy.argsort(freqs)[::-1]\n\n worddict = OrderedDict()\n for i, idx in enumerate(sorted_idx):\n worddict[words[idx]] = i+2 # 0: , 1: \n\n return worddict, wordcount\n\ndef load_dictionary(loc='dictionary.pkl'):\n \"\"\"\n Load a dictionary\n \"\"\"\n with open(loc, 'rb') as f:\n worddict = pkl.load(f)\n wordcount = pkl.load(f)\n return worddict\n\ndef save_dictionary(worddict, wordcount, loc):\n \"\"\"\n Save a dictionary to the specified location \n \"\"\"\n with open(loc, 'wb') as f:\n pkl.dump(worddict, f)\n pkl.dump(wordcount, f)\n\n\ndef readFile(filename):\n sentences = []\n with open(filename) as f:\n for line in f:\n if line == '':\n continue\n \n if '.' in line:\n sentences.extend(line.split('.'))\n else:\n sentences.append(line)\n return sentences\n\n\ndef cutSentences(lsentences):\n toAdd = []\n for i, fsent in enumerate(lsentences):\n if fsent == '':\n lsentences.pop(i)\n if '. ' in fsent:\n toAdd.extend(fsent.split('. '))\n lsentences.pop(i)\n lsentences.extend(toAdd)\n \ndef removeWords(worddict, wordcount, count=30):\n klist = list(worddict.keys())\n for key in klist:\n if wordcount[key] < count:\n worddict.pop(key, None)\n return worddict\n \n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('-f','--sentences_file', help=\"File containing sentences\",\n default=\"/data/wiki+leboncoin_pre.txt\")\n parser.add_argument('-d','--dictionary_name', help=\"Path to save dictionary\",\n default='dictionary.pkl')\n args = parser.parse_args()\n \n print('Loading sentences file')\n t0 = time.time()\n sentences = readFile(args.sentences_file)\n print('File read in', time.time() - t0, ' sec')\n\n print(\"Creating dictionary\")\n dic, count = build_dictionary(sentences)\n print(\"Saving dictionary\")\n removeWords(dic, count)\n save_dictionary(dic, count, args.dictionary_name)\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\n\n\n","sub_path":"training/vocab.py","file_name":"vocab.py","file_ext":"py","file_size_in_byte":2675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"498040956","text":"# Copyright 2018 HTCondor Team, Computer Sciences Department,\n# University of Wisconsin-Madison, WI.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport functools\nimport time\nimport itertools\nimport subprocess\nfrom pathlib import Path\n\nimport pytest\n\nimport htmap\nfrom htmap.options import get_base_options_dict\nfrom htmap.settings import BASE_SETTINGS\n\n# start with base settings (ignore user settings for tests)\nhtmap.settings.replace(BASE_SETTINGS)\n\n\n@pytest.fixture(scope = 'session', autouse = True)\ndef set_transplant_dir(tmpdir_factory):\n path = Path(tmpdir_factory.mktemp('htmap_transplant_dir'))\n htmap.settings['TRANSPLANT.PATH'] = path\n\n\n@pytest.fixture(\n params = [\n 'assume',\n 'transplant',\n 'docker',\n ],\n)\ndef delivery_methods(request):\n htmap.settings['DELIVERY_METHOD'] = request.param\n\n\ndef get_base_options_for_tests(map_id, map_dir, delivery, test_id = None):\n opts = get_base_options_dict(map_id, map_dir, delivery)\n opts['+htmap_test_id'] = str(test_id)\n\n return opts\n\n\nids = itertools.count()\n\n\n# todo: break this into two fixtures, one for setting htmap_dir, one for test_id and cleanup\n@pytest.fixture(scope = 'function', autouse = True)\ndef set_htmap_dir_and_clean_after(tmpdir_factory, mocker):\n \"\"\"Use a fresh HTMAP_DIR for every test.\"\"\"\n path = Path(tmpdir_factory.mktemp('htmap_dir'))\n htmap.settings['HTMAP_DIR'] = path\n\n test_id = next(ids)\n mocker.patch(\n 'htmap.options.get_base_options_dict',\n functools.partial(get_base_options_for_tests, test_id = test_id),\n )\n\n yield\n\n subprocess.run(\n [\n 'condor_rm',\n f'--constraint htmap_test_id=={test_id}',\n ],\n stdout = subprocess.DEVNULL,\n stderr = subprocess.DEVNULL,\n )\n\n\n@pytest.fixture(scope = 'session')\ndef doubler():\n def doubler(x):\n return 2 * x\n\n return doubler\n\n\n@pytest.fixture(scope = 'session')\ndef mapped_doubler(doubler):\n mapper = htmap.htmap(doubler)\n return mapper\n\n\n@pytest.fixture(scope = 'session')\ndef power():\n def power(x = 0, p = 0):\n return x ** p\n\n return power\n\n\n@pytest.fixture(scope = 'session')\ndef mapped_power(power):\n mapper = htmap.htmap(power)\n return mapper\n\n\n@pytest.fixture(scope = 'session')\ndef sleepy_double():\n def sleepy_double(x):\n time.sleep(5)\n return 2 * x\n\n return sleepy_double\n\n\n@pytest.fixture(scope = 'session')\ndef mapped_sleepy_double(sleepy_double):\n mapper = htmap.htmap(sleepy_double)\n return mapper\n\n\n@pytest.fixture(scope = 'session')\ndef mapped_exception():\n @htmap.htmap\n def fail(x):\n raise Exception(str(x))\n\n return fail\n\n\ndef exception_msg(exc_info) -> str:\n return str(exc_info.value)\n","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":3253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"601192951","text":"# bot.py\nimport cfg\nimport token\nimport socket\nimport time\nimport re\n\n\ndef chat(sock, msg):\n print(\"Sending Message: \" + msg)\n sock.send('PRIVMSG {} :{}\\r\\n'.format(cfg.CHAN, msg).encode(\"utf-8\"))\n\n\ndef respondPrivately(sock, usr, msg):\n print(\"Sending Private Message To \" + usr + \": \" + msg)\n sock.send('PRIVMSG #jtv :.w {} {}\\r\\n'.format(usr, msg).encode(\"utf-8\"))\n\n\n#def ban(sock, user):\n# chat(sock, \".ban {}\".format(user))\n\n\n#def timeout(sock, user, secs=60):\n# chat(sock, \".timeout {}\".format(user, secs))\n\n\nCHAT_MSG = re.compile(r\"^:\\w+!\\w+@\\w+\\.tmi\\.twitch\\.tv PRIVMSG #\\w+ :\")\n\n\n# network functions go here\ns = socket.socket()\ns.connect((cfg.HOST, cfg.PORT))\ns.send(\"PASS {}\\r\\n\".format(token.PASS).encode(\"utf-8\"))\ns.send(\"NICK {}\\r\\n\".format(cfg.NICK).encode(\"utf-8\"))\ns.send(\"JOIN {}\\r\\n\".format(cfg.CHAN).encode(\"utf-8\"))\ns.send(\"CAP REQ :twitch.tv/commands\\n\".encode(\"utf-8\"))\n\n\nwhile True:\n response = s.recv(1024).decode(\"utf-8\")\n #print(\"Input: \" + response)\n messagetype = response.split(' ')[1]\n print(\"Input Type: \" + messagetype)\n if response == \"PING :tmi.twitch.tv\\r\\n\":\n s.send(\"PONG :tmi.twitch.tv\\r\\n\".encode(\"utf-8\"))\n print(\"Pong\")\n else:\n username = re.search(r\"\\w+\", response).group(0) # return the entire match\n message = CHAT_MSG.sub(\"\", response)\n print(username + \": \" + message)\n for pattern in cfg.PATT:\n if re.match(pattern, message):\n chat(s, \"Hello \" + username + \"!\")\n #respondPrivately(s, username, \"Heyya!\")\n time.sleep(1 / cfg.RATE)","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"26362505","text":"#! /usr/bin/python3\n\n# Reads new emails and performs tasks if certain commands are found\n\nimport poplib\nimport smtplib\nimport ssl\nfrom urllib.request import urlopen\nimport time\nfrom datetime import datetime\nfrom subprocess import call\nimport threading\nimport traceback\n\n# Constants and Settings\nFROM_NAME = \"Raspi Notification\" # A name for the from email account\nPI_NAME = \"Raspi:\" # A name for the server, this preceeds the subject in every email\nUSER_NAME = \"\" # user@gmail.com\nPASSWORD = \"\" # account password\nSEND_TO = \"\" # reciever email\nRIP_SCRIPTS = {\"Trance\": \"/home/pi/ripTrance.sh\", \"Dubbase.FM\": \"/home/pi/ripDub.sh\"} # Genres and script locations for streamripper\n\n# A dictionary that keeps track if a rip is already in progress for that genre\nis_rip_locked = {}\n\n\n# Read new emails from an account for commands\ndef read_emails():\n done = False\n messages = \"\"\n while not done:\n try:\n # Connect to gmail and send credentials\n pop_conn = poplib.POP3_SSL(\"pop.gmail.com\")\n pop_conn.user(USER_NAME)\n pop_conn.pass_(PASSWORD)\n\n # Connect to server and get new emails\n messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]\n\n # Close server connection and exit the while loop\n pop_conn.quit()\n done = True\n except Exception as e:\n \t# In case of errors, wait a minute then try again\n error_message = \"No arguments found with exception.\"\n if e.args[0]:\n error_message = e.args[0]\n log(\"Read Email Error: \" + str(error_message))\n time.sleep(60)\n # End Read Loop\n\n # Turn the emails into a lower case string\n messages = str(messages).lower()\n\n # Look for key phrases in the emails\n # Uses multi-threading for tasks to keep things moving asyncronously during long tasks.\n\n # Reboots the computer\n if \"reboot\" in messages:\n reboot_pi()\n\n # Exits cmdMail.py\n if \"stop listening\" in messages:\n log(\"No longer listening.\")\n\n # Build and send an email\n sub = PI_NAME + \" Not listening\"\n msg = \"I am no longer listening.\"\n send_email(sub, msg)\n\n # Exit the program\n exit(0)\n\n # Returns the global IP address\n if \"home ip\" in messages:\n t = threading.Thread(target=send_ip_email)\n t.start()\n\n # Wakes a computer over LAN using external program wakeonlan, \n # copy this section and use a different name to allow multiple computers\n if \"wake liten\" in messages:\n t = threading.Thread(target=wake_on_lan, args=(\"Liten\",))\n t.start()\n\n # Rips an internet radio stream using external streamripper program\n if \"rip trance\" in messages:\n genre = \"Trance\"\n t = threading.Thread(target=rip, args=(genre,))\n t.start()\n\n # Rips an internet radio stream using external streamripper progam\n if \"rip dub\" in messages:\n # sleep for 5 seconds to prevent thread overlap with email and log functions when started simultaneously\n time.sleep(5)\n genre = \"Dubbase.FM\"\n t = threading.Thread(target=rip, args=(genre,))\n t.start()\n\n\n# Send an email on script start to notify about a reboot\ndef send_boot_mail():\n # 2 minute delay to allow drivers and internet connection to get going\n time.sleep(120)\n\n log(\"Booting up.\", True)\n\n # Build and send the email\n sub = PI_NAME + \" Startup complete\"\n msg = \"I have successfully booted up.\\n\" + get_home_ip() + \".\"\n send_email(sub, msg)\n\n\n# Send an email with the global IP address in it\ndef send_ip_email():\n log(\"IP requested.\")\n\n # Build and send the email\n sub = PI_NAME + \" Home IP\"\n msg = get_home_ip() + \".\"\n send_email(sub, msg)\n\n# Returns a string with the home global IP\ndef get_home_ip():\n return \"Home IP address: \" + str(urlopen(\"http://ipecho.net/plain\").read().decode(\"utf-8\"))\n\n# Wakes a computer up over LAN network\ndef wake_on_lan(hostname):\n log(\"Waking Liten.\")\n\n # Try waking Liten 4 times\n for x in range(4):\n call([\"wakeonlan\", \"\"])\n print()\n\n # Build and send the email\n sub = PI_NAME + \" WOL \" + str(hostname)\n msg = \"I have woken \" + str(hostname) + \".\"\n send_email(sub, msg)\n\n # Try waking Liten another 4 times\n for x in range(4):\n call([\"wakeonlan\", \"\"])\n print()\n\n\n# Starts a new streamripper of dubstep music, the script will send an email when it is done\ndef rip(genre):\n global is_rip_locked\n\n # If there is already a stream being downloaded, it will have a true value in this dictionary\n # A new stream will delete and corrupt the current one.\n if is_rip_locked[genre]:\n log(genre + \" is locked, aborting rip.\")\n\n # Build and send and email, then exit this function\n sub = PI_NAME + \" \" + genre + \" ripper stream locked\"\n msg = \"Another process is ripping \" + genre + \". So I won't start a new rip.\"\n send_email(sub, msg)\n else:\n \t# The value returned false and so a streamrip can be started\n log(\"Ripping \" + genre + \".\")\n\n # Build and send the email confirming the command\n sub = PI_NAME + \" \" + genre + \" Streamripper started\"\n msg = \"I have started the \" + genre + \" stream rip.\"\n send_email(sub, msg)\n\n # Lock the genre from being ripped multiple times\n is_rip_locked[genre] = True\n\n # Start the ripper, the thread will wait here until the rip is finished\n call([RIP_SCRIPTS[genre]])\n\n # Unlock the genre so it can be ripped again\n is_rip_locked[genre] = False\n\n log(\"Finished Ripping \" + genre + \".\")\n\n # Build and send the email when the rip is done\n sub = PI_NAME + \" \" + genre + \" Streamripper done\"\n msg = \"I just wanted to let you know that your \" + genre + \" stream is saved.\"\n send_email(sub, msg)\n\n\n# Reboot the device\ndef reboot_pi():\n log(\"Rebooting now.\")\n\n # Build and send the email confirming the command\n sub = PI_NAME + \" Rebooting\"\n msg = \"cmdMail has requested a reboot. I will be back online in a few... hopefully.\"\n send_email(sub, msg)\n\n # Wait 15 seconds for the mail to finish sending\n time.sleep(15)\n call([\"sudo reboot\"])\n\n\n# Send an email\ndef send_email(subject, message=\" \"):\n\t# Construct the email in single-string format\n eml = \"\\r\\n\".join([\"From: %s\" % FROM_NAME, \"To: %s\" % SEND_TO, \"Subject: %s\" % subject, \"\", message])\n\n # Keep trying until the email is successfully sent\n sent = False\n while not sent:\n try:\n # Log in and send, magic.\n server = smtplib.SMTP(\"smtp.gmail.com\", 587)\n server.ehlo()\n server.starttls()\n server.login(USER_NAME, PASSWORD)\n server.sendmail(FROM_NAME, [SEND_TO], eml)\n server.quit()\n # Sent ends the loop\n sent = True\n except smtplib.SMTPException as e:\n \t# In case of errors, wait a minute and then resend\n \t# Subject can help identify what function tried to send the email\n log(\"Send Email Error: \" + subject + \", \" + str(e.strerror) + \".\")\n time.sleep(60)\n # End Send Loop\n\n\n# Write a new line to the log file\ndef log(entry, on_boot=False):\n # Create a new file if log doesn't exist, otherwise append a log entry\n with open(\"/home/pi/cmdMail_log.txt\", \"a\") as f:\n\n \t# Visible separation for new boot up.\n if on_boot:\n f.write(\"\\n\\n\\n\")\n\n \t# Construct a timestamp\n d = datetime.now()\n\n # Write the line using a date/time stamp and the message\n f.write(d.strftime(\"%c\") + \" - \" + entry + \"\\n\")\n # Log File is closed\n\n\n# ENTRY POINT\ndef main():\n\tglobal is_rip_locked\n\n\t# Make the is_rip_locked dictionary\n\tfor station in RIP_SCRIPTS:\n\t is_rip_locked[station] = False\n\n\t# Ensure the user has setup the script\n\tif USER_NAME == \"\" or SEND_TO == \"\":\n\t\tlog(\"Emails variables are not setup.\")\n\t\texit(1)\n\n\t# Start by sending a boot up email.\n\tsend_boot_mail()\n\n\t# Continuously monitor email for new commands, pausing every 30 seconds\n\ttry:\n\t while True:\n\t read_emails()\n\t time.sleep(30)\n\texcept:\n\t\t# In case of an uncaught exception, get stacktrace for diag and exit.\n\t trace_string = traceback.format_exc()\n\n\t # log it locally in case internet is down\n\t log(\"Something happened, I have crashed:\\n\" + trace_string)\n\n\t # Build and send an email\n\t sub = PI_NAME + \" cmdMail crashed\"\n\t msg = \"Something went wrong with cmdMail, here is the stack trace:\\n\\n\" + trace_string\n\t send_email(sub, msg)\n\n\t # Exit the program with error code 1\n\t exit(1)\n\nmain()","sub_path":"cmdMail.py","file_name":"cmdMail.py","file_ext":"py","file_size_in_byte":8710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"506233308","text":"import pandas as pd\nimport time\nimport re\nimport requests\nimport scrapy\nfrom scrapy.http import TextResponse\nfrom scrapy_naver_news_2years.items import ScrapyNaverNews2YearsItem\n\nclass ScrapyNaverNews2YearsSpider(scrapy.Spider):\n name = 'scrapy_naver_news_2years'\n allow_domain=[\"https://news.naver.com\"]\n user_agent= 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36'\n categ = {#'정치': '100',\n '101':'economy',\n '102': 'soci',\n '103': 'culture',\n #'세계': '104',\n '105': 'IT'}\n\n def __init__(self, categ = 101, *args, **kwargs): \n self.categ_path = self.categ[str(categ)] + '.csv'\n print(self.categ_path)\n ScrapyNaverNews2YearsSpider.__init__(self)\n\n def start_requests(self):\n #df = pd.read_csv('article_url_1.csv')\n df = pd.read_csv(self.categ_path)\n rows = df.iloc\n date_ex = '202011'\n \n for row in rows:\n date_ = str(row['date'])\n date_ = str(date_)[0:7]\n if date_ != date_ex:\n time.sleep(2)\n #print(row['categ'], row['date'], row['last_p'])\n for page in range(1, int(row['last_p'])+1):\n url = 'https://news.naver.com/main/list.nhn?mode=LSD&mid=sec&listType=title&sid1={}&date={}&page={}'.format(row['categ'], row['date'], page)\n yield scrapy.Request(url, callback=self.parse)\n date_ex = str(date_)[0:7]\n \n def parse(self, resp):\n links = resp.xpath('//*[@id=\"main_content\"]/div[2]/ul/li/a/@href').extract()\n \n # links = [resp.urljoin(link) for link in links]\n for link in links:\n yield scrapy.Request(link, callback=self.parse_content)\n \n def parse_content(self, resp):\n item = ScrapyNaverNews2YearsItem()\n title = resp.xpath('//*[@id=\"articleTitle\"]/text() | //*[@id=\"content\"]/div[1]/div/h2/text() | \\\n //h4[@class=\"title\"]/text()')[0].extract()\n date = resp.xpath('//*[@id=\"main_content\"]/div[1]/div[3]/div/span[@class=\"t11\"]/text() | \\\n //div[@class=\"article_info\"]/span[@class=\"author\"]/em/text()|\\\n //div[@class=\"info\"]/span[1]/text()')[0].extract()\n content = resp.xpath('//*[@id=\"articleBodyContents\"]/text() | \\\n //*[@id=\"articleBodyContents\"]/strong/text() | \\\n //*[@id=\"articleBodyContents\"]/div/text() | \\\n //*[@id=\"articleBodyContents\"]/div/div/text() | \\\n //*[@id=\"articleBodyContents\"]/font/text() | \\\n //*[@id=\"articleBodyContents\"]/div[2]/ul/li/span/span/text() | \\\n //*[@id=\"newsEndContents\"]/text() | \\\n //*[@id=\"articeBody\"]/text()').extract()\n content = [text.replace('\\xa0', ' ').strip() for text in content]\n categ_num = resp.url.split('sid1=')[1].split('&')[0]\n \n item['date'] = re.findall('[0-9]{4}[.][0-9]{2}[.][0-9]{2}', date)[0]\n item['category'] = self.categ[categ_num]\n item['press_agency'] = resp.xpath('//a[@class=\"nclicks(atp_press)\"]/img/@title | //div[@class=\"press_logo\"]/a/img/@alt | \\\n //*[@id=\"pressLogo\"]/a/img/@alt')[0].extract()\n item['link'] = resp.url\n item['title'] = title.strip()\n item['content'] = '\\n'.join(content).strip()\n \n yield item","sub_path":"01_crawling/scrapy_naver_news_2years/scrapy_naver_news_2years/spiders/spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":3502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"457693212","text":"from django.urls import path\nfrom rest_framework.urlpatterns import format_suffix_patterns\nfrom app import views\n\nurlpatterns = [\n path('product/', views.ProductList.as_view()),\n path('product//', views.ProductDetail.as_view()),\n path('product//highlight/', views.ProductDetail.as_view(), name='product-highlight'),\n path('cart/', views.CartList.as_view()),\n path('cart//', views.CartList.as_view())\n]\n\nurlpatterns = format_suffix_patterns(urlpatterns)\n","sub_path":"app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"462028145","text":"x = int(input())\ncnt = 1\ncnt1 = 1\nprev = x\nwhile x != 0:\n x = int(input())\n if x == 0:\n cnt = max(cnt1, cnt)\n print(cnt)\n break\n elif x != prev:\n prev = x\n if cnt1 <= cnt:\n cnt1 = cnt\n cnt = 1\n elif x == prev:\n cnt += 1\n","sub_path":"W2HW28.py","file_name":"W2HW28.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"252311675","text":"import json\nimport logging\nimport random\nimport time\nfrom datetime import datetime\n\nfrom django.core.management import BaseCommand\nfrom kafka import KafkaProducer\nfrom kafka.errors import KafkaError\n\nfrom cno.settings.base import LOGGING\nfrom runner.config import KAFKA_API_VERSION, KAFKA_SERVER\nfrom simulation.constants import mano\n\nlogging.config.dictConfig(LOGGING)\nlogger = logging.getLogger(__name__)\n\n\ndef publish_metrics_for_qoe():\n # Kafka Producer Set Up\n # https://kafka-python.readthedocs.io/en/master/apidoc/KafkaProducer.html\n producer = KafkaProducer(bootstrap_servers=KAFKA_SERVER, api_version=KAFKA_API_VERSION,\n value_serializer=lambda v: json.dumps(v).encode('utf-8'))\n while True:\n # Push the metric values in batch per container ID\n prep_metric = {\n 'mano': mano,\n 'measurements':\n {\n 'working_fps': 11,\n 'output_mesh_size_bytes': 45000,\n 'output_textures_size_bytes': 25000,\n 'container_network_transmit_packets_dropped_total': random.uniform(0, 2)\n },\n 'timestamp': datetime.now().isoformat()\n }\n request = producer.send('ns.instances.prep', key=b'qoe', value=prep_metric)\n try:\n request.get(timeout=60)\n except KafkaError as ke:\n logger.error(ke)\n\n time.sleep(30)\n\n\nclass Command(BaseCommand):\n def handle(self, *args, **options):\n publish_metrics_for_qoe()\n","sub_path":"simulation/management/commands/publish_metrics_for_qoe.py","file_name":"publish_metrics_for_qoe.py","file_ext":"py","file_size_in_byte":1542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"456102405","text":"from django.conf.urls import url\n\nfrom . import views\n\napp_name = \"board\"\nurlpatterns = [\n url(r\"^$\", views.index, name=\"index\"),\n url(r\"^(?P[0-9]+)$\", views.index, name=\"paginated_index\"),\n url(r\"^thread/(?P[0-9]+)(#[0-9]+)?$\", views.thread, name=\"thread\"),\n url(r\"^reply/$\", views.reply, name=\"reply\"),\n url(r\"^new_thread/$\", views.new_thread, name=\"new_thread\"),\n]\n","sub_path":"two_chong/board/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"20967316","text":"import unittest\n\nfrom vector.Vector import Vector\n\n\nclass TestVectorSum(unittest.TestCase):\n def test_add(self):\n x = Vector((3, 6))\n y = Vector((2, 4))\n\n self.assertEqual((5, 10), x.add(y).coordinates(), 'Vector addition is incorrect')\n\n def test_subtract(self):\n x = Vector((3, 6))\n y = Vector((2, 4))\n\n self.assertEqual((1, 2), x.subtract(y).coordinates(), 'Vector subtraction is incorrect')\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"exercises/matrices/test/vector/test_VectorSum.py","file_name":"test_VectorSum.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"106499390","text":"import unicodedata\nimport string\nimport re\nimport random\nimport time\nimport datetime\nimport math\nimport socket\nhostname = socket.gethostname() # 用来得到主机的名字, 但是这是为了什么目的呢\n\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nfrom torch import optim\nimport torch.nn.functional as F\nfrom torch.nn.utils.rnn import pad_packed_sequence, pack_padded_sequence#, masked_cross_entropy\nfrom masked_cross_entropy import * \n# 其实使用 packedSequence 直接规避掉这个或许会更好, 先 pack 通过 RNN 然后再次 pad\n\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as ticker\nimport numpy as np\nget_ipython().magic('matplotlib inline')\n\n\nUSE_CUDA = torch.cuda.is_available() #True\n\n\n\nPAD_token = 0\nSOS_token = 1\nEOS_token = 2\n\nclass Lang:\n def __init__(self, name):\n self.name = name\n self.trimmed = False\n self.word2index = {}\n self.word2count = {}\n self.index2word = {0: \"PAD\", 1: \"SOS\", 2: \"EOS\"}\n self.n_words = 3 # Count default tokens\n\n def index_words(self, sentence):\n for word in sentence.split(' '):\n self.index_word(word)\n\n def index_word(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\n # Remove words below a certain count threshold\n def trim(self, min_count):\n if self.trimmed: return\n self.trimmed = True\n \n keep_words = []\n \n for k, v in self.word2count.items():\n if v >= min_count:\n keep_words.append(k)\n\n print('keep_words %s / %s = %.4f' % (\n len(keep_words), len(self.word2index), len(keep_words) / len(self.word2index)\n ))\n\n # Reinitialize dictionaries\n self.word2index = {}\n self.word2count = {}\n self.index2word = {0: \"PAD\", 1: \"SOS\", 2: \"EOS\"}\n self.n_words = 3 # Count default tokens\n\n for word in keep_words:\n self.index_word(word)\n\n# Turn a Unicode string to plain ASCII, thanks to http://stackoverflow.com/a/518232/2809427\ndef unicode_to_ascii(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\ndef normalize_string(s):\n s = unicode_to_ascii(s.lower().strip())\n s = re.sub(r\"([,.!?])\", r\" \\1 \", s)\n s = re.sub(r\"[^a-zA-Z,.!?]+\", r\" \", s)\n s = re.sub(r\"\\s+\", r\" \", s).strip()\n return s\n\n\ndef read_langs(lang1, lang2, reverse=False):\n print(\"Reading lines...\")\n\n # Read the file and split into lines\n# filename = '../data/%s-%s.txt' % (lang1, lang2)\n filename = '../data/%s-%s.txt' % (lang1, lang2)\n lines = open(filename).read().strip().split('\\n')\n\n # Split every line into pairs and normalize\n pairs = [[normalize_string(s) for s in l.split('\\t')] for l in lines]\n\n # Reverse pairs, make Lang instances\n if reverse:\n pairs = [list(reversed(p)) for p in pairs]\n input_lang = Lang(lang2)\n output_lang = Lang(lang1)\n else:\n input_lang = Lang(lang1)\n output_lang = Lang(lang2)\n\n return input_lang, output_lang, pairs\n\n\n# In[6]:\n\nMIN_LENGTH = 3\nMAX_LENGTH = 25\n\ndef filter_pairs(pairs):\n filtered_pairs = []\n for pair in pairs:\n if len(pair[0]) >= MIN_LENGTH and len(pair[0]) <= MAX_LENGTH and len(pair[1]) >= MIN_LENGTH and len(pair[1]) <= MAX_LENGTH:\n filtered_pairs.append(pair)\n return filtered_pairs\n\ndef prepare_data(lang1_name, lang2_name, reverse=False):\n input_lang, output_lang, pairs = read_langs(lang1_name, lang2_name, reverse)\n print(\"Read %d sentence pairs\" % len(pairs))\n \n pairs = filter_pairs(pairs)\n print(\"Filtered to %d pairs\" % len(pairs))\n \n print(\"Indexing words...\")\n for pair in pairs:\n input_lang.index_words(pair[0])\n output_lang.index_words(pair[1])\n \n print('Indexed %d words in input language, %d words in output' % (input_lang.n_words, output_lang.n_words))\n return input_lang, output_lang, pairs\n\ninput_lang, output_lang, pairs = prepare_data('eng', 'fra', True)\n\n\n# In[8]:\n\nprint(input_lang.word2count['the'])\nprint(input_lang.trimmed) # 并没有使用 trim 所以应该没有什么问题\n\nimport copy\ninput_lang2 = copy.deepcopy(input_lang)\ninput_lang2.trim(20)\nprint(input_lang.word2count['the'])\nprint(input_lang2.word2count['the']) # 这么 trim 过了一次之后, word2count 就失去了意义。\n\n\nMIN_COUNT = 5\n\ninput_lang.trim(MIN_COUNT)\noutput_lang.trim(MIN_COUNT)\n\n\nkeep_pairs = []\n\nfor pair in pairs:\n input_sentence = pair[0]\n output_sentence = pair[1]\n keep_input = True\n keep_output = True\n \n for word in input_sentence.split(' '):\n if word not in input_lang.word2index:\n keep_input = False\n break\n\n for word in output_sentence.split(' '):\n if word not in output_lang.word2index:\n keep_output = False\n break\n\n # Remove if pair doesn't match input and output conditions\n if keep_input and keep_output:\n keep_pairs.append(pair)\n\nprint(\"Trimmed from %d pairs to %d, %.4f of total\" % (len(pairs), len(keep_pairs), len(keep_pairs) / len(pairs)))\npairs = keep_pairs\n\n\n# Return a list of indexes, one for each word in the sentence, plus EOS\ndef indexes_from_sentence(lang, sentence):\n return [lang.word2index[word] for word in sentence.split(' ')] + [EOS_token]\n\n\n# Pad a with the PAD symbol\ndef pad_seq(seq, max_length):\n seq += [PAD_token for i in range(max_length - len(seq))]\n return seq\n\ndef random_batch(batch_size):\n input_seqs = []\n target_seqs = []\n\n # Choose random pairs\n for i in range(batch_size):\n pair = random.choice(pairs)\n input_seqs.append(indexes_from_sentence(input_lang, pair[0]))\n target_seqs.append(indexes_from_sentence(output_lang, pair[1]))\n\n # Zip into pairs, sort by length (descending), unzip\n seq_pairs = sorted(zip(input_seqs, target_seqs), key=lambda p: len(p[0]), reverse=True) \n # 好简洁 返回结果是 list(tuple)\n input_seqs, target_seqs = zip(*seq_pairs) # unzip 过程如此\n \n # For input and target sequences, get array of lengths and pad with 0s to max length\n input_lengths = [len(s) for s in input_seqs]\n input_padded = [pad_seq(s, max(input_lengths)) for s in input_seqs]\n target_lengths = [len(s) for s in target_seqs]\n target_padded = [pad_seq(s, max(target_lengths)) for s in target_seqs]\n\n # Turn padded arrays into (batch_size x max_len) tensors, transpose into (max_len x batch_size)\n input_var = Variable(torch.LongTensor(input_padded)).transpose(0, 1)\n target_var = Variable(torch.LongTensor(target_padded)).transpose(0, 1)\n \n if USE_CUDA:\n input_var = input_var.cuda()\n target_var = target_var.cuda()\n \n return input_var, input_lengths, target_var, target_lengths\n\n\nrandom_batch(2)\n\n\nclass EncoderRNN(nn.Module):\n def __init__(self, input_size, hidden_size, n_layers=1, dropout=0.1):\n super(EncoderRNN, self).__init__()\n \n self.input_size = input_size\n self.hidden_size = hidden_size\n self.n_layers = n_layers\n self.dropout = dropout\n \n self.embedding = nn.Embedding(input_size, hidden_size)\n self.gru = nn.GRU(hidden_size, hidden_size, n_layers, dropout=self.dropout, bidirectional=True)\n # 注意, 默认是双向 RNN, 所以output的时候是形状是 (T,B,DH) 或者 (S,DH), hidden 是 (LD, B, H)\n \n def forward(self, input_seqs, input_lengths, hidden=None):\n # Note: we run this all at once (over multiple batches of multiple sequences)\n embedded = self.embedding(input_seqs) # (T, B, H)\n packed = torch.nn.utils.rnn.pack_padded_sequence(embedded, input_lengths) # (S, H)\n outputs, hidden = self.gru(packed, hidden) # (S, DH) , (LD, B, H)\n outputs, output_lengths = torch.nn.utils.rnn.pad_packed_sequence(outputs) # unpack (back to padded)\n outputs = outputs[:, :, :self.hidden_size] + outputs[:, : ,self.hidden_size:] # Sum bidirectional outputs\n return outputs, hidden #(T,B,H), (LD,B,H)\n\n\nclass Attn(nn.Module):\n def __init__(self, method, hidden_size):\n super(Attn, self).__init__()\n \n self.method = method\n self.hidden_size = hidden_size\n \n if self.method == 'general':\n self.attn = nn.Linear(self.hidden_size, hidden_size)\n\n elif self.method == 'concat':\n self.attn = nn.Linear(self.hidden_size * 2, hidden_size)\n self.v = nn.Parameter(torch.FloatTensor(1, hidden_size))\n\n def forward(self, hidden, encoder_outputs): # hidden(H,B), encoder_outputs(T,B,H)\n max_len = encoder_outputs.size(0)\n this_batch_size = encoder_outputs.size(1)\n\n # Create variable to store attention energies\n attn_energies = Variable(torch.zeros(this_batch_size, max_len)) # B x S\n\n if USE_CUDA:\n attn_energies = attn_energies.cuda()\n\n # For each batch of encoder outputs\n for b in range(this_batch_size):\n # Calculate energy for each encoder output\n for i in range(max_len):\n attn_energies[b, i] = self.score(hidden[:, b], encoder_outputs[i, b].unsqueeze(0))\n\n # Normalize energies to weights in range 0 to 1, resize to 1 x B x S\n return F.softmax(attn_energies, dim=-1).unsqueeze(1)\n \n def score(self, hidden, encoder_output):\n \n if self.method == 'dot':\n energy = hidden.dot(encoder_output)\n return energy\n \n elif self.method == 'general':\n energy = self.attn(encoder_output)\n energy = hidden.dot(energy)\n return energy\n \n elif self.method == 'concat':\n energy = self.attn(torch.cat((hidden, encoder_output), 1))\n energy = self.v.dot(energy)\n return energy\n \n# A different implementation of the global attention which avoids for-loop\nclass Attn2(nn.Module):\n def __init__(self, method, hidden_size):\n super(Attn2, self).__init__()\n \n self.method = method\n self.hidden_size = hidden_size\n \n if self.method == 'general':\n self.attn = nn.Linear(self.hidden_size, hidden_size)\n\n elif self.method == 'concat':\n self.attn = nn.Linear(self.hidden_size * 2, hidden_size)\n self.v = nn.Parameter(torch.FloatTensor(1, hidden_size))\n \n def forward(self, hidden, encoder_outputs):\n # hidden (LD, B, H), encoder_outputs (T, B, H)\n if self.method == 'general':\n attn_energies = torch.bmm(hidden.transpose(0,1), \n at.attn(encoder_outputs).transpose(0,1).transpose(1,2))\n if self.method == 'dot':\n attn_energies = torch.bmm(hidden.transpose(0,1), \n encoder_outputs.transpose(0,1).transpose(1,2))\n if self.mehod == 'concat':\n attn_energies = torch.stack([v]* encoder_outputs.size(1)).bmm(\n at2.attn(torch.cat((torch.stack([hidden.transpose(0,1)] * encoder_outputs.size(0)), \n encoder_outputs), dim=2)).transpose(0,1).transpose(1,2))\n F.softmax(attn_energies, dim=-1)\n\n\n# This is a buggy implementation it doesnot work at all\nclass BahdanauAttnDecoderRNN(nn.Module):\n def __init__(self, hidden_size, output_size, n_layers=1, dropout_p=0.1):\n super(BahdanauAttnDecoderRNN, self).__init__()\n \n # Define parameters\n self.hidden_size = hidden_size\n self.output_size = output_size\n self.n_layers = n_layers\n self.dropout_p = dropout_p\n self.max_length = MAX_LENGTH\n \n # Define layers\n self.embedding = nn.Embedding(output_size, hidden_size)\n self.dropout = nn.Dropout(dropout_p)\n self.attn = Attn('concat', hidden_size)\n self.gru = nn.GRU(hidden_size, hidden_size, n_layers, dropout=dropout_p)\n self.out = nn.Linear(hidden_size, output_size)\n \n def forward(self, word_input, last_hidden, encoder_outputs):\n # Note: we run this one step at a time\n # TODO: FIX BATCHING\n \n # Get the embedding of the current input word (last output word)\n word_embedded = self.embedding(word_input).view(1, 1, -1) # S=1 x B x N\n word_embedded = self.dropout(word_embedded)\n \n # Calculate attention weights and apply to encoder outputs\n attn_weights = self.attn(last_hidden[-1], encoder_outputs)\n context = attn_weights.bmm(encoder_outputs.transpose(0, 1)) # B x 1 x N\n context = context.transpose(0, 1) # 1 x B x N\n \n # Combine embedded input word and attended context, run through RNN\n rnn_input = torch.cat((word_embedded, context), 2)\n output, hidden = self.gru(rnn_input, last_hidden)\n \n # Final output layer\n output = output.squeeze(0) # B x N\n output = F.log_softmax(self.out(torch.cat((output, context), 1)))\n \n # Return final output, hidden state, and attention weights (for visualization)\n return output, hidden, attn_weights\n\n\nclass LuongAttnDecoderRNN(nn.Module):\n def __init__(self, attn_model, hidden_size, output_size, n_layers=1, dropout=0.1):\n super(LuongAttnDecoderRNN, self).__init__()\n\n # Keep for reference\n self.attn_model = attn_model\n self.hidden_size = hidden_size\n self.output_size = output_size\n self.n_layers = n_layers\n self.dropout = dropout\n\n # Define layers\n self.embedding = nn.Embedding(output_size, hidden_size)\n self.embedding_dropout = nn.Dropout(dropout)\n self.gru = nn.GRU(hidden_size, hidden_size, n_layers, dropout=dropout)\n self.concat = nn.Linear(hidden_size * 2, hidden_size)\n self.out = nn.Linear(hidden_size, output_size)\n \n # Choose attention model\n if attn_model != 'none':\n self.attn = Attn(attn_model, hidden_size)\n\n def forward(self, input_seq, last_hidden, encoder_outputs):\n # Note: we run this one step at a time\n\n # Get the embedding of the current input word (last output word)\n batch_size = input_seq.size(0) # 就是得到了 batch_size, 形状可能是 (B,1) 或者 (B)\n embedded = self.embedding(input_seq)\n embedded = self.embedding_dropout(embedded)\n embedded = embedded.view(1, batch_size, self.hidden_size) # S=1 x B x N #embedded(1,B,H)\n\n # Get current hidden state from input word and last hidden state\n rnn_output, hidden = self.gru(embedded, last_hidden) # (1,B,DH), (LD,B,H) #(1,B,H), (L,B,H)\n\n # Calculate attention from current RNN state and all encoder outputs;\n # apply to encoder outputs to get weighted average\n attn_weights = self.attn(rnn_output, encoder_outputs) #(B,1,T)\n context = attn_weights.bmm(encoder_outputs.transpose(0, 1)) # B x S=1 x N # (B, 1, H)\n\n # Attentional vector using the RNN hidden state and context vector\n # concatenated together (Luong eq. 5)\n rnn_output = rnn_output.squeeze(0) # S=1 x B x N -> B x N #(B,H)\n context = context.squeeze(1) # B x S=1 x N -> B x N #(B,H)\n concat_input = torch.cat((rnn_output, context), 1) #(B,2H)\n concat_output = F.tanh(self.concat(concat_input)) #(B,H)\n\n # Finally predict next token (Luong eq. 6, without softmax)\n output = self.out(concat_output) #(B,O), not logsoftmaxed\n\n # Return final output, hidden state, and attention weights (for visualization)\n return output, hidden, attn_weights # (B,O), (L,B,H), (B,1,T)\n\n\nsmall_batch_size = 3\ninput_batches, input_lengths, target_batches, target_lengths = random_batch(small_batch_size)\n\nprint('input_batches', input_batches.size()) # (max_len x batch_size)\nprint('target_batches', target_batches.size()) # (max_len x batch_size)\n\n\n\n\nsmall_hidden_size = 8\nsmall_n_layers = 2\n\nencoder_test = EncoderRNN(input_lang.n_words, small_hidden_size, small_n_layers)\ndecoder_test = LuongAttnDecoderRNN('general', small_hidden_size, output_lang.n_words, small_n_layers)\n# decoder_test = BahdanauAttnDecoderRNN(small_hidden_size, output_lang.n_words, small_n_layers)\n\nif USE_CUDA:\n encoder_test.cuda()\n decoder_test.cuda()\n\n\n\nencoder_outputs, encoder_hidden = encoder_test(input_batches, input_lengths, None)\n\nprint('encoder_outputs', encoder_outputs.size()) # max_len x batch_size x hidden_size #(T,B,DH)\nprint('encoder_hidden', encoder_hidden.size()) # n_layers * 2 x batch_size x hidden_size #(LD,B,H)\n\n\n\nmax_target_length = max(target_lengths)\n\n# Prepare decoder input and outputs\ndecoder_input = Variable(torch.LongTensor([SOS_token] * small_batch_size)) #(B)\ndecoder_hidden = encoder_hidden[:decoder_test.n_layers] # Use last (forward) hidden state from encoder \n# 所以从上面可以直到事实上 LD 维度的组合方式是先Layer后Direction, forward在前面, backward 在后面 (L,B,H)\nall_decoder_outputs = Variable(torch.zeros(max_target_length, small_batch_size, decoder_test.output_size))\n#(T_o, B,O)\n\nif USE_CUDA:\n all_decoder_outputs = all_decoder_outputs.cuda()\n decoder_input = decoder_input.cuda()\n\n# Run through decoder one time step at a time\nfor t in range(max_target_length):\n decoder_output, decoder_hidden, decoder_attn = decoder_test(\n decoder_input, decoder_hidden, encoder_outputs\n ) #(B,O), (L,B,H), (B,1,H)\n all_decoder_outputs[t] = decoder_output # Store this step's outputs\n decoder_input = target_batches[t] # Next input is current target (B) teacher forcing\n\n# Test masked cross entropy loss\nloss = masked_cross_entropy(\n all_decoder_outputs.transpose(0, 1).contiguous(), #(B, T_o, O)\n target_batches.transpose(0, 1).contiguous(), #(B, T_o)\n target_lengths #(B)\n)\nprint('loss', loss.data[0])\n\n\ndef train(input_batches, input_lengths, target_batches, target_lengths, encoder, \n decoder, encoder_optimizer, decoder_optimizer, criterion, max_length=MAX_LENGTH):\n \n # Zero gradients of both optimizers\n encoder_optimizer.zero_grad()\n decoder_optimizer.zero_grad()\n loss = 0 # Added onto for each word\n\n # Run words through encoder\n encoder_outputs, encoder_hidden = encoder(input_batches, input_lengths, None)\n \n # Prepare input and output variables\n decoder_input = Variable(torch.LongTensor([SOS_token] * batch_size))\n decoder_hidden = encoder_hidden[:decoder.n_layers] # Use last (forward) hidden state from encoder\n\n max_target_length = max(target_lengths)\n all_decoder_outputs = Variable(torch.zeros(max_target_length, batch_size, decoder.output_size))\n\n # Move new Variables to CUDA\n if USE_CUDA:\n decoder_input = decoder_input.cuda()\n all_decoder_outputs = all_decoder_outputs.cuda()\n\n # Run through decoder one time step at a time\n for t in range(max_target_length):\n decoder_output, decoder_hidden, decoder_attn = decoder(\n decoder_input, decoder_hidden, encoder_outputs\n )\n\n all_decoder_outputs[t] = decoder_output\n decoder_input = target_batches[t] # Next input is current target\n\n # Loss calculation and backpropagation\n loss = masked_cross_entropy(\n all_decoder_outputs.transpose(0, 1).contiguous(), # -> batch x seq\n target_batches.transpose(0, 1).contiguous(), # -> batch x seq\n target_lengths\n )\n loss.backward()\n \n # Clip gradient norms\n ec = torch.nn.utils.clip_grad_norm(encoder.parameters(), clip)\n dc = torch.nn.utils.clip_grad_norm(decoder.parameters(), clip)\n\n # Update parameters with optimizers\n encoder_optimizer.step()\n decoder_optimizer.step()\n \n return loss.data[0], ec, dc\n\n\n\n# Configure models\nattn_model = 'dot'\nhidden_size = 500\nn_layers = 2\ndropout = 0.1\nbatch_size = 100\nbatch_size = 50\n\n# Configure training/optimization\nclip = 50.0\nteacher_forcing_ratio = 0.5\nlearning_rate = 0.0001\ndecoder_learning_ratio = 5.0\nn_epochs = 50000\nepoch = 0\nplot_every = 20\nprint_every = 100\nevaluate_every = 1000\n\n# Initialize models\nencoder = EncoderRNN(input_lang.n_words, hidden_size, n_layers, dropout=dropout)\ndecoder = LuongAttnDecoderRNN(attn_model, hidden_size, output_lang.n_words, n_layers, dropout=dropout)\n\n# Initialize optimizers and criterion\nencoder_optimizer = optim.Adam(encoder.parameters(), lr=learning_rate)\ndecoder_optimizer = optim.Adam(decoder.parameters(), lr=learning_rate * decoder_learning_ratio)\ncriterion = nn.CrossEntropyLoss()\n\n# Move models to GPU\nif USE_CUDA:\n encoder.cuda()\n decoder.cuda()\n\nimport sconce\njob = sconce.Job('seq2seq-translate', {\n 'attn_model': attn_model,\n 'n_layers': n_layers,\n 'dropout': dropout,\n 'hidden_size': hidden_size,\n 'learning_rate': learning_rate,\n 'clip': clip,\n 'teacher_forcing_ratio': teacher_forcing_ratio,\n 'decoder_learning_ratio': decoder_learning_ratio,\n})\njob.plot_every = plot_every\njob.log_every = print_every\n\n# Keep track of time elapsed and running averages\nstart = time.time()\nplot_losses = []\nprint_loss_total = 0 # Reset every print_every\nplot_loss_total = 0 # Reset every plot_every\n\n\n\ndef as_minutes(s):\n m = math.floor(s / 60)\n s -= m * 60\n return '%dm %ds' % (m, s)\n\ndef time_since(since, percent):\n now = time.time()\n s = now - since\n es = s / (percent)\n rs = es - s\n return '%s (- %s)' % (as_minutes(s), as_minutes(rs))\n\n\ndef evaluate(input_seq, max_length=MAX_LENGTH):\n input_lengths = [len(input_seq)]\n input_seqs = [indexes_from_sentence(input_lang, input_seq)]\n input_batches = Variable(torch.LongTensor(input_seqs), volatile=True).transpose(0, 1)\n \n if USE_CUDA:\n input_batches = input_batches.cuda()\n \n # Set to not-training mode to disable dropout\n encoder.train(False)\n decoder.train(False)\n \n # Run through encoder\n encoder_outputs, encoder_hidden = encoder(input_batches, input_lengths, None)\n\n # Create starting vectors for decoder\n decoder_input = Variable(torch.LongTensor([SOS_token]), volatile=True) # SOS\n decoder_hidden = encoder_hidden[:decoder.n_layers] # Use last (forward) hidden state from encoder\n \n if USE_CUDA:\n decoder_input = decoder_input.cuda()\n\n # Store output words and attention states\n decoded_words = []\n decoder_attentions = torch.zeros(max_length + 1, max_length + 1)\n \n # Run through decoder\n for di in range(max_length):\n decoder_output, decoder_hidden, decoder_attention = decoder(\n decoder_input, decoder_hidden, encoder_outputs\n )\n decoder_attentions[di,:decoder_attention.size(2)] += decoder_attention.squeeze(0).squeeze(0).cpu().data\n\n # Choose top word from output\n topv, topi = decoder_output.data.topk(1)\n ni = topi[0][0]\n if ni == EOS_token:\n decoded_words.append('')\n break\n else:\n decoded_words.append(output_lang.index2word[ni])\n \n # Next input is chosen word\n decoder_input = Variable(torch.LongTensor([ni]))\n if USE_CUDA: decoder_input = decoder_input.cuda()\n\n # Set back to training mode\n encoder.train(True)\n decoder.train(True)\n \n return decoded_words, decoder_attentions[:di+1, :len(encoder_outputs)]\n\n\n\ndef evaluate_randomly():\n [input_sentence, target_sentence] = random.choice(pairs)\n evaluate_and_show_attention(input_sentence, target_sentence)\n\n\nimport io\nimport torchvision\nfrom PIL import Image\nimport visdom\nvis = visdom.Visdom()\n\ndef show_plot_visdom():\n buf = io.BytesIO()\n plt.savefig(buf)\n buf.seek(0)\n attn_win = 'attention (%s)' % hostname\n vis.image(torchvision.transforms.ToTensor()(Image.open(buf)), win=attn_win, opts={'title': attn_win})\n\n\n\ndef show_attention(input_sentence, output_words, attentions):\n # Set up figure with colorbar\n fig = plt.figure()\n ax = fig.add_subplot(111)\n cax = ax.matshow(attentions.numpy(), cmap='bone')\n fig.colorbar(cax)\n\n # Set up axes\n ax.set_xticklabels([''] + input_sentence.split(' ') + [''], rotation=90)\n ax.set_yticklabels([''] + output_words)\n\n # Show label at every tick\n ax.xaxis.set_major_locator(ticker.MultipleLocator(1))\n ax.yaxis.set_major_locator(ticker.MultipleLocator(1))\n\n show_plot_visdom()\n plt.show()\n plt.close()\n\n\ndef evaluate_and_show_attention(input_sentence, target_sentence=None):\n output_words, attentions = evaluate(input_sentence)\n output_sentence = ' '.join(output_words)\n print('>', input_sentence)\n if target_sentence is not None:\n print('=', target_sentence)\n print('<', output_sentence)\n \n show_attention(input_sentence, output_words, attentions)\n \n # Show input, target, output text in visdom\n win = 'evaluted (%s)' % hostname\n text = '> %s
= %s
< %s
' % (input_sentence, target_sentence, output_sentence)\n vis.text(text, win=win, opts={'title': win})\n\n\n\n# Begin!\necs = []\ndcs = []\neca = 0\ndca = 0\n\nwhile epoch < n_epochs:\n epoch += 1\n \n # Get training data for this cycle\n input_batches, input_lengths, target_batches, target_lengths = random_batch(batch_size)\n\n # Run the train function\n loss, ec, dc = train(\n input_batches, input_lengths, target_batches, target_lengths,\n encoder, decoder,\n encoder_optimizer, decoder_optimizer, criterion\n )\n\n # Keep track of loss\n print_loss_total += loss\n plot_loss_total += loss\n eca += ec\n dca += dc\n \n job.record(epoch, loss)\n\n if epoch % print_every == 0:\n print_loss_avg = print_loss_total / print_every\n print_loss_total = 0\n print_summary = '%s (%d %d%%) %.4f' % (time_since(start, epoch / n_epochs), epoch, epoch / n_epochs * 100, print_loss_avg)\n print(print_summary)\n \n if epoch % evaluate_every == 0:\n evaluate_randomly()\n\n if epoch % plot_every == 0:\n plot_loss_avg = plot_loss_total / plot_every\n plot_losses.append(plot_loss_avg)\n plot_loss_total = 0\n \n # TODO: Running average helper\n ecs.append(eca / plot_every)\n dcs.append(dca / plot_every)\n ecs_win = 'encoder grad (%s)' % hostname\n dcs_win = 'decoder grad (%s)' % hostname\n vis.line(np.array(ecs), win=ecs_win, opts={'title': ecs_win})\n vis.line(np.array(dcs), win=dcs_win, opts={'title': dcs_win})\n eca = 0\n dca = 0\n\n\ndef show_plot(points):\n plt.figure()\n fig, ax = plt.subplots()\n loc = ticker.MultipleLocator(base=0.2) # put ticks at regular intervals\n ax.yaxis.set_major_locator(loc)\n plt.plot(points)\n\nshow_plot(plot_losses)\n\n\n# In[ ]:\n\noutput_words, attentions = evaluate(\"je suis trop froid .\")\nplt.matshow(attentions.numpy())\nshow_plot_visdom()\n\nevaluate_and_show_attention(\"elle a cinq ans de moins que moi .\")\n\n\nevaluate_and_show_attention(\"elle est trop petit .\")\n\n\nevaluate_and_show_attention(\"je ne crains pas de mourir .\")\n\nevaluate_and_show_attention(\"c est un jeune directeur plein de talent .\")\n\nevaluate_and_show_attention(\"est le chien vert aujourd hui ?\")\n\nevaluate_and_show_attention(\"le chat me parle .\")\n\nevaluate_and_show_attention(\"des centaines de personnes furent arretees ici .\")\n\nevaluate_and_show_attention(\"des centaines de chiens furent arretees ici .\")\n\nevaluate_and_show_attention(\"ce fromage est prepare a partir de lait de chevre .\")\n\n\n\n\n","sub_path":"seq2seq-translation/seq2seq-translation-batched.py","file_name":"seq2seq-translation-batched.py","file_ext":"py","file_size_in_byte":27724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"66763721","text":"#!/usr/bin/env python\n##############################################################################\n# EVOLIFE www.dessalles.fr/Evolife Jean-Louis Dessalles #\n# Telecom ParisTech 2014 www.dessalles.fr #\n##############################################################################\n\n\n##############################################################################\n# xy_game #\n##############################################################################\n\n\t##############################################\n\n\nimport sys\nif __name__ == '__main__': sys.path.append('../..') # for tests\n\n######################################\n# specific variables and functions #\n######################################\n\nimport random\nfrom Evolife.Scenarii.Default_Scenario import Default_Scenario\nfrom Evolife.Tools.Tools import percent\nimport random\n\n\n\nclass Scenario(Default_Scenario):\n\t\n\t\n\n\n\tdef initialization(self):\n\t\tself.level_of_trust = 98.0\n\t\tself.percentage_x = 0 \n\t\tself.average = 50\n\t\tself.score = 0 \n\t\tself.choice = []\n\t\tself.scores = [0] *6\n\t\tself.maximum =0\n\t\tself.num_of_rounds = 0\n\t\tself.maximal_score =0\n\n\tdef make_choice(self):\n\t# make_choice makes the choice for all the different players, and puts their choice (x & y) in a list.\n\t\tchoice=[]\n\t\tx_in_list = 100 - self.level_of_trust\n\t\ty_in_list = self.level_of_trust\n\t\tmy_list = ['x'] * int(x_in_list) + ['y'] * int(y_in_list)\n\t\tfor each in range(6): #5 can be changed in the number of players as parameter\n\t\t\tchoice.append(random.choice(my_list))\n\t\tself.choice = choice\n\t\treturn choice\n\n\tdef calculate_percentage_of_x(self):\n\t\ttemp = self.make_choice()\n\t\tnumber_of_x = temp.count('x')\n\t\tnum_of_players = len(self.make_choice())\n\t\tself.percentage_x = 100 / num_of_players * number_of_x\n\t\treturn self.percentage_x\t\n\n\tdef update_level_of_trust(self):\n\t\tif self.choice.count('x') > 0:\n\t\t\ttemp_level = self.level_of_trust - 0.1\n\t\tif self.choice.count('x') == 0:\n\t\t\ttemp_level = self.level_of_trust\t\t\n\t\ta = self.percentage_x\n\t\tif temp_level>100:\n\t\t\tself.level_of_trust = 95\n\t\t\treturn self.level_of_trust\n\t\telse:\n\t\t\tself.level_of_trust = temp_level\n\n\t\t\treturn self.level_of_trust\n\n\tdef calculate_individual_score(self):\n\t\ttemp = self.choice\n\t\ttemp_list =[]\n\t\tXs = temp.count('x')\n\t\tif Xs >0:\n\t\t\tfor i,j in enumerate(temp):\n\t\t\t\tif j == 'x':\n\t\t\t\t\ttemp_list.append(i)\n\t\t\tfor each in temp_list:\n\t\t\t\tself.scores[each] += 1\n\t\treturn self.scores\n\n\tdef calculate_average_score(self):\n\t\tself.average = sum(self.scores)/6\n\t\treturn self.average\n\n\tdef calculate_maximum_score(self):\n\t\tself.maximum = max(self.scores)\n\t\treturn self.maximum\n\n\n\tdef display_(self):\n\t\tdisp = [('black', 'self.level_of_trust')]\t\t\n\t\tdisp += [('white','self.maximum')] \n\t\tdisp += [('red','self.average')]\n\t\t#disp += [('blue','self.maximal_score')]\n\t\treturn disp\t\t\n\n\tdef local_display(self,VariableID):\n\t\tif VariableID == 'self.level_of_trust':\n\t\t\treturn self.level_of_trust\n\t\telif VariableID == 'self.maximum':\n\t\t\treturn self.percentage_x\n\t\telif VariableID == 'self.average':\n\t\t\treturn self.average\n\t\t#elif VariableID == 'self.maximal_score':\n\t\t#\treturn self.maximal_score\n\n\tdef maximal_scoring(self):\n\t\tscore = self.num_of_rounds *6\n\t\tself.maximal_score = score\n\t\treturn self.maximal_score\n\n\tdef start_game(self, members):\n\n\t\tself.calculate_percentage_of_x()\n\t\tself.calculate_individual_score()\n\t\tself.update_level_of_trust()\n\t\tself.num_of_rounds = self.num_of_rounds + 1\n\t\tself.calculate_average_score()\n\t\tself.calculate_maximum_score()\n\t\tself.maximal_scoring()\n\n\t\tif self.num_of_rounds == 1000:\n\t\t\tself.level_of_trust = 95 \n\t\t\tself.percentage_x = 0 \n\t\t\tself.average = 50\n\t\t\tself.score = 0 \n\t\t\tself.choice = []\n\t\t\tself.scores = [0] *6\n\t\t\tself.maximum =0\n\t\t\tself.num_of_rounds = 0\n\n\nif __name__ == \"__main__\":\n\tScenario()\n\tprint(__doc__ + '\\n')\n\t#raw_input('[Return]')\n\t\n","sub_path":"Scenarii/S_XYGAME.py","file_name":"S_XYGAME.py","file_ext":"py","file_size_in_byte":3897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"493462372","text":"# Copyright 2001-2016 Crytek GmbH / Crytek Group. All rights reserved.\r\n\r\ndef build(bld):\r\n\r\n\tsuppress_vs_warnings = ['/W0']\r\n\tif bld.env['MSVC_VERSION'] == '14.0':\r\n\t\tsuppress_vs_warnings = [ '/W0', '/Wv:18' ]\r\n\r\n\tbld.CryEngineStaticModule( \r\n\t\ttarget = 'oculus', \r\n\t\tvs_filter = 'Libs',\r\n\t\tfile_list = 'oculus.waf_files',\r\n\t\texclude_from_static_code_analyzer = True,\r\n\r\n\t\twin_cxxflags = [ '/FI' + bld.CreateRootRelativePath('Code/Libs/Oculus/PatchOculusSDK.h') ] + suppress_vs_warnings,\r\n\t\twin_cflags = [ '/FI' + bld.CreateRootRelativePath('Code/Libs/Oculus/PatchOculusSDK.h') ] + suppress_vs_warnings,\r\n\t\tincludes = [\r\n\t\t\tPath('Code/SDKs/OculusSDK/LibOVR/Include'),\r\n\t\t\tPath('Code/SDKs/OculusSDK/LibOVRKernel/Src'),\r\n\t\t\t],\r\n\r\n\t\twin_lib = ['OleAut32'],\r\n\r\n\t\tmodule_provides = dict(\r\n\t\t\tincludes = [ Path('Code/SDKs/OculusSDK/LibOVR/Include'), ],\r\n\t\t\tdefines = [ 'INCLUDE_OCULUS_SDK' ],\r\n\t\t),\r\n\t)\r\n","sub_path":"code/Libs/oculus/wscript","file_name":"wscript","file_ext":"","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"456986778","text":"# -*- coding: utf-8 -*-\n\"\"\" module description \"\"\"\nimport sys\nimport os\nfrom pathlib import Path\n# path_of_this_module = os.path.dirname(__file__)\npath_of_this_module = Path(__file__).parent\nsys.path.append(path_of_this_module)\nfrom PyQt5.QtWidgets import QApplication, QMainWindow\nfrom PyQt5.uic import loadUi\n\n\n\n# sqlite3 操作数据库\n\nclass MainWindow(QMainWindow):\n \"\"\" 主窗口类 \"\"\"\n def __init__(self, parent=None):\n \"\"\" 构造函数 \"\"\"\n super(MainWindow, self).__init__(parent)\n loadUi(path_of_this_module.__str__() + '/' + 'MainWindow.ui', self)\n self.setAction()\n def setAction(self):\n \"\"\" 添加 UI 信号与槽 \"\"\"\n self.label.setText('Ni')\n # pushButton_Culc 计算按钮\n # self.pushButton_Culc.setText('Hello')\n\ndef main():\n \"\"\" 运行程序 \"\"\"\n myApp = QApplication(sys.argv)\n window = MainWindow()\n window.show()\n sys.exit(myApp.exec())\n\nif __name__ == \"__main__\":\n \"\"\" 在本模块测试程序 \"\"\"\n os.system('cls')\n main()\n","sub_path":"Qt/mainWindow.py","file_name":"mainWindow.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"358227332","text":"from network import *\r\nimport random\r\nfrom math import e\r\nfrom copy import deepcopy\r\n\r\ndef sigmoid(x): #input -inf to +inf, output 0 to 1\r\n try:\r\n return 1/(1+e**(-x))\r\n \r\n except OverflowError:\r\n if x > 0:\r\n return 1\r\n else:\r\n return 0\r\n \r\n\r\ndef step(x): #input -inf to +inf, output 0 to 1\r\n if x > 0:\r\n return 1\r\n else:\r\n return 0\r\n\r\ndef normalise(value):\r\n # value is between 0 and 1\r\n # returns value between -1 and 1\r\n return round(value*2 - 1, ndigits=3)\r\n\r\nclass AI:\r\n def __init__(self, netPattern): #netPattern is the pattern of the nn\r\n if len(netPattern) < 2:\r\n raise Exception(\"Need at least 2 layers in nueral network\")\r\n \r\n net = Network(Node(\"start\"))\r\n for x, numLayerNodes in enumerate(netPattern):\r\n previousLayer = net.depthNodes(x)\r\n #print(x, previousLayer)\r\n for y in range(numLayerNodes):\r\n newNode = Node(str(x)+\".\"+str(y))\r\n newNode.setInfo([randInt() for _ in range(len(previousLayer)+1)])\r\n \r\n for parent in previousLayer:\r\n net.addchild(parent, newNode)\r\n \r\n self._net = net\r\n self._inputNodes = self._net.depthNodes(1)\r\n self._outputNodes = self._net.depthNodes(-1)\r\n self._netPattern = netPattern\r\n self._learningfunction = lambda x:normalise(sigmoid(x))\r\n #self._learningfunction = step\r\n \r\n def predict(self, values): #type(value) == str, int(value) does not raise error\r\n if not isinstance(values, list):\r\n raise TypeError(\"value should be of type str\")\r\n elif len(values) != len(self._inputNodes):\r\n raise ValueError(\"value should be length of inputNodes\")\r\n \r\n outputs = {}\r\n for i, value in enumerate(values):\r\n outputs[self._inputNodes[i]] = value\r\n \r\n for layerNum in range(2, len(self._net)):\r\n #print(layerNum)\r\n #print(self._net.depthNodes(layerNum))\r\n \r\n for i, node in enumerate(self._net.depthNodes(layerNum)):\r\n info = node.info\r\n \r\n weights, bias = info[:-1], info[-1]\r\n parentOutputs = [outputs[i] for i in node.parents]\r\n assert len(weights) == len(parentOutputs)\r\n #weights from -100 to 100\r\n #parentOutputs from -64 to 64\r\n nodeOutput = sum([weights[i] * parentOutputs[i] for i in range(len(weights))])/len(weights) + bias\r\n #print([weights[i] * parentOutputs[i] for i in range(len(weights))], \"/\", len(weights), bias)\r\n #print(nodeOutput, self._learningfunction(nodeOutput))\r\n outputs[node] = self._learningfunction(nodeOutput)\r\n \r\n return [outputs[outputNode] for outputNode in self._outputNodes]\r\n \r\n def getMutation(self):\r\n new = deepcopy(self._net)\r\n for layer in new:\r\n for node in layer:\r\n info = node.info\r\n newInfo = [getMutation(i) for i in info]\r\n node.setInfo(newInfo)\r\n return new\r\n \r\n def save(self, filename):\r\n \"\"\"with open(filename, \"r\") as f:\r\n f.write(netPattern)\r\n for layer in self._net:\r\n for \"\"\"\r\n pass\r\n\r\ndef randInt():\r\n # is there a better way to do this\r\n #return random.random()*2 - 1 #random number between 1 and -1\r\n return random.choice([-100, 100, -8, 8, -5, 5, -3.3, 3.3, -3.2, 3.2, -1, 1])\r\n\r\ndef randBoard():\r\n board = []\r\n for i in range(64):\r\n board.append(randInt())\r\n return board\r\n\r\n#random.seed(69)\r\nNN = AI([64, 79, 79, 79, 79, 2])\r\n\r\nprint(NN.predict(randBoard()))\r\n \r\n","sub_path":"evolution/evolutionTraining.py","file_name":"evolutionTraining.py","file_ext":"py","file_size_in_byte":3845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"230985919","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Aug 10 09:51:26 2018\n\n@author: Utente\n\"\"\"\n\n#old main\ndef main_simulation(N1 = 100, N2 = 100, rip = 10, p = 0.33, parent_dir = 'C:/Users/Utente/Anaconda3/Cooperazione'):\n from simul_with_err import R_simul_with_err, N_simul_with_err\n from init_simulation import init_simulation\n import statistics\n import time\n import my_print as my\n import math\n import numpy as np\n start = time.time()\n dir_name = parent_dir + '/'+ repr(N1)+'-'+repr(N2)+'-'+repr(rip)\n name = 'p'+format(p,'.2f')\n S1 = int(math.sqrt(N1))\n S2 = int(math.sqrt(N2))\n print('Calcolo il tempo medio di assorbimento...')\n # CALCOLO IL TEMPO MEDIO DI ASSORBIMENTO/CONVERGENZA A N FISSATO\n t = []\n for i in range(0,5):\n t_conv = init_simulation(N1)\n t.append(t_conv)\n t_mean = int(statistics.mean(t))\n print('t_mean = {}'.format(t_mean))\n #attenzione qui che potrebbe essere un tempo spropositato\n tot_step = int(t_mean)*10\n finish = time.time()\n t_tot = round((finish-start)/60,2)\n print('Tempo impiegato per calcolare t_conv = {}'.format(t_tot), 'min\\n')\n \n t0 = time.time()\n \n #RANDOM SIMULATION\n R_start_time = round((time.time() - start)/60,2)\n print('R_start_time = ', R_start_time)\n R_eps_S = R_simul_with_err(N1, N2,rip, p, tot_step, dir_name, R_start_time = R_start_time)\n t2 = time.time()\n t_seconda = round((t2 - t0)/60 , 2)\n print('Tempo esecuzione simulazioni random = {}'.format(t_seconda), 'min\\n')\n \n #NESTED SIMULATION\n N_start_time = round((time.time()-start)/60,2)\n print('N_start_time = ', N_start_time)\n N_eps_S = N_simul_with_err(N1, N2, rip, p, tot_step, dir_name, N_start_time = N_start_time)\n t3 = time.time()\n t_N = round((t3-t2)/60,2)\n print('Tempo esecuzione simulazioni nested = {}'.format(t_N), 'min\\n')\n \n #plot finali\n #info1 = {'tit1': 'S(eps) nested con C = 0.35', 'tit2': 'S(eps) random con C = 0.35',\n # 'xlab': 'epsilon' , 'ylab_1': 'S_1', 'ylab_2' : 'S_2'}\n #info2 = {'tit' : '(S_nest - S_rnd)/S0 in funzione di eps per C = 0.35',\n # 'ylab_3' : '(delta S1)/S0', 'ylab_4': 'delta S2'}\n #my.eps_print(R_eps_S, N_eps_S, name, dir_name, info1, info2, S1, S2)\n #u\"\\u03C4\" tau\n N_info = {'ylab' : 'Abbondanze n delle S1 specie', 'tit': 'n('+u\"\\u03C4\"+') per '}\n R_info = {'ylab' : 'Abbondanze n delle S2 specie', 'tit': 'n('+u\"\\u03C4\"+') per '}\n #kappas = np.linspace(0, 0.7, 8)\n #epsilons = []\n #for i in range(len(kappas)):\n # eps1 = (kappas[i]/(1-kappas[i]))/(p*math.sqrt(N1))\n # epsilons.append(round(eps1,4))\n epsilons = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]\n my.n_plot(dir_name, format(p,'.2f'), epsilons, N_info, R_info)\n \n t_f = time.time()\n t_simul = round((t_f-start)/60,2)\n my.overview(N1, tot_step, rip, t_simul, dir_name)\n print('main eseguita con successo. \\n')\n\n#only this function needed\ndef tau_conv(N):\n from init_simulation import init_simulation\n import statistics as stat\n tau = []\n for i in range(5):\n tau_i = init_simulation(N)\n tau.append(tau_i)\n tau_mean = stat.mean(tau)\n tau_dev = stat.stdev(tau)\n print('tau_mean = ', round(tau_mean,1))\n print('tau_dev = ', round(tau_dev,1))\n tau_conv = int(round(tau_mean + 10*tau_dev, 0))\n print('tau_conv = tau_mean + 5*tau_dev = ', tau_conv, '\\n')\n \n return tau_conv","sub_path":"Older versions/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"617783865","text":"#list of all the courses I have been required to take at Walsh College\ncourses = [\"acc 300\", \"ecn 201\", \"mgt 201\", \"com 300\", \"com 210\", \"it 201\", \"it 402\", \"qm 301\"]\n\ncourses.sort()\n\n#Looping thorugh the courses and marking them with I have taken message. Also converting courses to caps\nfor course in courses:\n message = \"I have taken \"\n message_1 = \" at Walsh College\"\n course_print = message + course.upper() + message_1 \n print(course_print)\n\n#Upcoming courses and merging two lists into one complete list \ncourses_upcoming = [\"com 340\",\"it 408\", \"it 412\", \"it 417\"] \ncourses_complete = courses + courses_upcoming \ncourses_complete.sort()\nprint(courses_complete)\n\n#Upcoming courses or courses I am taking right now \nfor i in courses_upcoming:\n message_2 = \"This is my course of study with upcoming courses added: \"\n message_3 = message_2 + i.upper()\n print(message_3)\n\n#clearing the original list of courses that were taken and then marking them as such \nfor courses_taken in courses_complete:\n courses.clear() \n message_4 = \"I do not have to take these courses: \"\n message_5 = message_4 + courses_taken\n print(message_5)\n\n#Using the list to tell you that i am taking these courses in the upcoming term.\nfor upcoming in courses_upcoming:\n message_6 = \"I plan to take the following courses next term \"\n message_7 = message_6 + upcoming\n print(message_7)\n\n#list with numbers in range from 0 to 1000\nnumbers =list(range(0,1000))\n\n#showing the list of numbers that are divisible by 6 \nnum = []\nfor value in range(6,1000,6):\n six = value \n num.append(six)\n message_8 = \"Here are twenty numbers divisible by 6:\"\n\n#printing the first 20 numbers that are divisible by 6 \nprint(message_8 , num[0:20])\n\n#max value in the list\nprint(\"The maximum value in th list is: \" , max(numbers))\n\n#sum of the number between 10 and 50 \nmessage_9 = \"Here is the sum of several values in the list: \"\nprint(message_9 ,sum(numbers[10:50]))\n\n#overwriting my original list of courses with my range of numbers \ncourses = numbers\nprint(courses)","sub_path":"Week_1/assignment_2.py","file_name":"assignment_2.py","file_ext":"py","file_size_in_byte":2066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"536618789","text":"from flask import Blueprint, jsonify, request, abort\nfrom ..exercises.models import Exercise\nfrom ..teams.models import Team\nfrom ..emitters.models import Emitter\nfrom .models import Report, create_job_id\nfrom .validators import ReportValidator, report_create_schema, report_edit_schema\nfrom sqlalchemy import desc\nfrom sqlalchemy.orm import contains_eager, aliased\nfrom .. import db, socketio\nfrom .tasks import generate_report\n\nreports = Blueprint('reports', __name__)\n\n\n@reports.route('/exercise//reports/list')\ndef list_reports(exercise_slug):\n\n # table aliases to facilitate sorting/etc\n # might be able to be global to avoid creating them every time, looking into it\n tx = aliased(Emitter)\n rx = aliased(Emitter)\n team = aliased(Team)\n\n # Query parameters\n offset = request.args.get('page', 1, type=int)\n sort_field = request.args.get('sort', 'team')\n sort_order = request.args.get('sortOrder', 'asc')\n\n # set up order by clause based on supplied parameter\n sorts = {\n 'team': team.name,\n 'tx': tx.name,\n 'rx': rx.name,\n 'minute': Report.minute,\n 'd_plus': Report.d_plus,\n 'hour': Report.hour,\n 'scheduleType': Report.schedule_type\n }\n sort = sorts.get(sort_field, team.name)\n\n # descending sorts\n if sort_order == 'desc':\n sort = desc(sort)\n\n page = (Report.query\n .join(Exercise)\n .filter(Exercise.slug == exercise_slug)\n .join(team, Report.team)\n .outerjoin(rx, Report.rx_emitter)\n .join(tx, Report.tx_emitter)\n .options(contains_eager(Report.team, alias=team),\n contains_eager(Report.tx_emitter, alias=tx),\n contains_eager(Report.rx_emitter, alias=rx))\n .order_by(sort)\n .paginate(page=offset, per_page=25)\n )\n\n return jsonify({'per_page': 25,\n 'current_page': offset,\n 'total': page.total,\n 'reports': [r.serialize() for r in page.items],\n 'exercise': exercise_slug})\n\n\n@reports.route('/exercise//reports/create', methods=['POST'])\ndef create_report(exercise_slug):\n v = ReportValidator(report_create_schema(exercise_slug))\n if v.validate(request.json):\n r = Report()\n v.populate_report(r)\n ex = Exercise.query.filter_by(slug=exercise_slug).first()\n ex.reports.append(r)\n r.update_schedule()\n db.session.add(r)\n db.session.commit()\n msg = r.serialize()\n socketio.emit('report-created', msg)\n return jsonify(msg), 201\n return jsonify(v.errors), 400\n\n\n@reports.route('/exercise//reports/edit', methods=['POST'])\ndef edit_report(exercise_slug):\n v = ReportValidator(report_edit_schema(exercise_slug))\n if v.validate(request.json):\n r = Report.query.get(request.json['id'])\n v.populate_report(r)\n r.update_schedule()\n db.session.add(r)\n db.session.commit()\n msg = r.serialize()\n socketio.emit('report-edited', msg)\n return jsonify(msg), 201\n return jsonify(v.errors), 400\n\n\n@reports.route('/exercise//reports/delete/')\ndef delete_report(exercise_slug, report_id):\n r = Report.query.get_or_404(report_id)\n if r.exercise.slug != exercise_slug:\n abort(400)\n db.session.delete(r)\n db.session.commit()\n msg = {'deleted': r.id}\n socketio.emit('report-deleted', msg)\n return jsonify(msg)\n\n\n@reports.route('/exercise//reports/play/')\ndef play_report(exercise_slug, report_id):\n r = Report.query.get_or_404(report_id)\n if r.schedule_type != 'interval' or r.exercise.slug != exercise_slug:\n abort(400)\n r.repeat_running = True\n r.update_schedule()\n db.session.add(r)\n db.session.commit()\n msg = r.serialize()\n socketio.emit('report-edited', msg)\n return jsonify(msg)\n\n\n@reports.route('/exercise//reports/pause/')\ndef pause_report(exercise_slug, report_id):\n r = Report.query.get_or_404(report_id)\n if r.schedule_type != 'interval' or r.exercise.slug != exercise_slug:\n abort(400)\n r.repeat_running = False\n r.update_schedule()\n db.session.add(r)\n db.session.commit()\n msg = r.serialize()\n socketio.emit('report-edited', msg)\n return jsonify(msg)\n\n\n@reports.route('/exercise//reports/send/')\ndef send_report(exercise_slug, report_id):\n r = Report.query.get_or_404(report_id)\n if r.schedule_type != 'ondemand' or r.exercise.slug != exercise_slug:\n abort(400)\n r.job_id = create_job_id()\n db.session.add(r)\n db.session.commit()\n generate_report.apply_async(task_id=r.job_id)\n return jsonify({})\n\n","sub_path":"backend/app/reports/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"517076975","text":"from Super_Pen import *\n\n\n### Global Variable defaults ###\nh=0.05; # Time step\nz=0.0 ## z is damping factor gamma - q was already in use\nb=1 ## b = g/l\nF=0 # Forcing\nomega_d=2/3 # the freq of driving\ninitial_displacement=0.01\noscillations=170\ngraph_os = 10\nsample_os = 20\n\n\n\n\n\ndef period_vs_forcing(init_d = 0.01, num= 10, h=0.05, omega_d=2/3, \\\n oscillations=1000,z=0.5, os_shown=30):\n\tf_vec = [0.5, 1.2, 1.44, 1.465]\n\tperiod = []\n\tdisplacements = []\n\tvelocities = []\n\tfor f in f_vec:\n\t\tp, y, y_dot, y_t, E, E_t = Super_Pen(init= init_d,h=h, \\\n\t\t oscillations= oscillations,\\\n\t\t\t\t\t\t\t\t\t\t\t os_sampled= oscillations/2,\\\n\t\t\t\t\t\t\t\t\t\t\t omega_d=omega_d,\\\n\t\t\t\t\t\t\t\t\t\t\t F = f,\\\n\t\t\t\t\t\t\t\t\t\t\t z = z)\n\t\tperiod.append(p)\n\t\tdisplacements.append(y)\n\t\tvelocities.append(y_dot)\n\t\tprint(\"Forcing:\t\" + str(f)+\"\tPeriod:\t\"+str(period[-1]) +\"\tseconds\")\n\tplt.plot(f_vec, period, color='blue', marker='+')\n\tplt.xlabel('Forcing')\n\tplt.xlim([0.0, np.pi])\n\tplt.ylabel('Period (seconds)')\n\tplt.title(r\"Apparent Period vs Forcing for an Undamped Pendulum in steady state\")\n\tplt.savefig('D_Forcing_Period_q0.5_Steady_State.pdf')\n\tplt.clf()\n\tfor i in range(len(displacements)):\n\t\tplt.plot(y_t, displacements[i], label='F ='+str(f_vec[i])+'')\n\tplt.legend()\n\tplt.xlabel('Time (seconds)')\n\tplt.ylabel('Displacement (Radians)')\n\tplt.title('Steady State Forced Oscillations with q=0.5 ')\n\tplt.savefig('E_Forcing_Displacement_q0.5_Steady_State.pdf')\n\tplt.clf()\n\tfor i in range(len(displacements)):\n\t\tplt.plot(y_t, velocities[i], label='F ='+str(f_vec[i])+'')\n\tplt.legend()\n\tplt.xlabel('Time (seconds)')\n\tplt.ylabel('Velocity (Radians per Second)')\n\tplt.title('Steady State Forced Oscillations with q=0.5 ')\n\tplt.savefig('F_Forcing_Angular_Velocity_q0.5_Steady_State.pdf')\n\tplt.clf()\n\nperiod_vs_forcing()\n\ndef displacement_vs_damping(init_d = 0.01, num= 100, h=0.05, omega_d=0, \\\n oscillations=10, z=0.5, f=0):\n\tz_vec = [0,1,5,10]\n\tperiod = []\n\tdisplacements = []\n\tfor z in z_vec:\n\t\tp, y, y_dot, y_t, E, E_t = Super_Pen(init= init_d,h=h, \\\n\t\t oscillations= oscillations,\\\n\t\t\t\t\t\t\t\t\t\t\t omega_d=omega_d,\\\n\t\t\t\t\t\t\t\t\t\t\t F = f,\n\t\t\t\t\t\t\t\t\t\t\t z=z)\n\t\tdisplacements.append(y)\n\tfor i in range(len(displacements)):\n\t\tplt.plot(y_t, displacements[i], label='q ='+str(z_vec[i])+'')\n\t\tplt.legend()\n\tplt.xlabel('Time (seconds)')\n\tplt.ylabel('Displacement (radians)')\n\tplt.title('Undriven Initial Oscillations with Varied Damping')\n\tplt.savefig('G_Initial_Oscillations_Varied_Damping.pdf')\n\tplt.clf()\n\n\ndisplacement_vs_damping()\n","sub_path":"ex2/main/2_Task2Pendulum.py","file_name":"2_Task2Pendulum.py","file_ext":"py","file_size_in_byte":2602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"225994564","text":"__all__ = ('addon', 'data', 'lattice', 'math', 'mesh', 'modal', 'modifier', 'object', 'ray', 'screen', 'view3d')\r\n\r\nimport traceback\r\n\r\nimport bpy\r\n\r\nfrom bl_ui.space_toolsystem_common import activate_by_id as activate_tool\r\nfrom bl_ui.space_toolsystem_toolbar import VIEW3D_PT_tools_active as view3d_tools\r\n\r\n\r\nname = __name__.partition('.')[0]\r\n\r\n# TODO: create collections for these in preferences\r\nvertice_presets = [3, 6, 8, 32, 64]\r\narray_presets = [2, 4, 6, 8, 10]\r\nwidth_presets = [0.02, 0.05, 0.1]\r\nsegment_presets = [1, 2, 3, 4, 6]\r\nangle_presets = [5, 15, 30, 45, 90]\r\n\r\nnames = {\r\n 'cut': 'Cut',\r\n 'slice': 'Slice',\r\n 'inset': 'Inset',\r\n 'join': 'Join',\r\n 'make': 'Make',\r\n 'knife': 'Knife',\r\n 'snap': 'Snap',\r\n 'negative': 'Negative',\r\n 'bbox': 'Bbox',\r\n 'dot': 'Dot',\r\n 'dot_highlight': 'Highlight',\r\n 'wire': 'Wire',\r\n 'show_shape_wire': 'Show Shape Wire',\r\n 'wire_width': 'Wire Width',\r\n 'bounds': 'Show Bounds',\r\n 'allow_selection': 'Allow Selection',\r\n 'sort_modifiers': 'Sort Modifiers',\r\n 'keep_modifiers': 'Keep Modifiers',\r\n 'ngon_snap_angle': 'Ngon Snap Angle',\r\n 'auto_smooth': 'Auto Smooth',\r\n 'join_flip_z': 'Join Flip Z',\r\n 'use_multi_edit': 'Use Mult-Edit',\r\n 'make_active': 'Shift to Active',\r\n 'show_shape': 'Show Shape',\r\n 'parent_shape': 'Parent Shape',\r\n 'apply_slices': 'Apply Slices',\r\n 'make_align_z': 'Make on Z',\r\n 'offset': 'Offset',\r\n 'destructive_menu': 'Destructive Menu',\r\n 'mode_label': 'Mode Label',\r\n 'shape_label': 'Shape Label',\r\n 'operation_label': 'Operation Label',\r\n 'surface_label': 'Surface Label',\r\n 'wire_only': 'Wires Only',\r\n 'thick_wire': 'Thick Wire',\r\n 'circle_vertices': 'Circle Vertices',\r\n 'bevel_width': 'Bevel Width',\r\n 'bevel_segments': 'Bevel Segments',\r\n 'quad_bevel': 'Quad Bevel',\r\n 'straight_edges': 'Straight Corner Flow',\r\n 'inset_thickness': 'Inset Thickness',\r\n 'solidify_thickness': 'Solidify Thickness',\r\n 'array_count': 'Array Count',\r\n 'lazorcut_limit': 'Lazorcut Limit',\r\n 'quick_execute': 'Quick Execute',\r\n 'simple_trace': 'Simple Trace',\r\n 'edit_disable_modifiers': 'Disable Ctrl & Shift LMB (Edit Mode)',\r\n 'enable_surface_toggle': 'Enable Surface Toggle',\r\n 'cursor': 'Cursor',\r\n 'transform_gizmo': 'Transform Gizmo',\r\n 'reduce_opacity_editmode': 'Reduce Opacity in Edit',\r\n 'scroll_adjust_circle': 'Scroll Adjust Circle',\r\n 'cursor_axis': 'Cursor Axis'}\r\n\r\n\r\ndef active_tool():\r\n return view3d_tools.tool_active_from_context(bpy.context)\r\n\r\n\r\ndef activate_by_name(name):\r\n activate_tool(bpy.context, 'VIEW_3D', name)\r\n\r\n\r\ndef method_handler(method,\r\n arguments = tuple(),\r\n identifier = str(),\r\n exit_method = None,\r\n exit_arguments= tuple(),\r\n return_result = False,\r\n return_value = {'CANCELLED'}):\r\n '''\r\n method: method to call\r\n arguments: method arguments\r\n identifier: optional identifer for printout\r\n exit_method: optional exit method to call on exception\r\n exit_arguments: exit method arguments\r\n return_result: allows return of the method and values\r\n return_value: return value on exception\r\n '''\r\n identifier = identifier + ' ' if identifier else ''\r\n try:\r\n if return_result:\r\n return method(*arguments)\r\n else:\r\n method(*arguments)\r\n except Exception:\r\n print(F'\\n{name} {identifier}Method Failed:\\n')\r\n traceback.print_exc()\r\n\r\n if exit_method:\r\n try:\r\n if return_result:\r\n return exit_method(*exit_arguments)\r\n else:\r\n exit_method(*exit_arguments)\r\n except Exception:\r\n print(F'\\n{name} {identifier}Exit Method Failed:\\n')\r\n traceback.print_exc()\r\n\r\n if return_result:\r\n try: return return_value\r\n except Exception:\r\n print(F'\\n{name} {identifier}Exit Return Value Failed:\\n')\r\n traceback.print_exc()\r\n","sub_path":"addon/utility/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"309043027","text":"'''\nДан файл с таблицей в формате TSV с информацией о росте школьников разных классов.\nНапишите программу, которая прочитает этот файл и подсчитает для каждого класса средний рост учащегося.\nФайл состоит из набора строк, каждая из которых представляет собой три поля:\nКласс Фамилия Рост\nКласс обозначается только числом. Буквенные модификаторы не используются. Номер класса может быть от 1 до 11 включительно. В фамилии нет пробелов, а в качестве роста используется натуральное число, но при подсчёте среднего требуется вычислить значение в виде вещественного числа.\nВыводить информацию о среднем росте следует в порядке возрастания номера класса (для классов с первого по одиннадцатый). Если про какой-то класс нет информации, необходимо вывести напротив него прочерк.\nВ качестве ответа прикрепите файл с полученными данными о среднем росте.\n'''\n#---\n'''\nwith open('/home/asumin/Загрузки/dataset_3380_5.txt', 'r', encoding='utf-8') as file: # read file\n arr = [[j for j in i.strip().split() ] for i in file.readlines()]\n # создаем 2d массив [['6', 'Tracey', '155'],['3', 'Lewin', '140'],....]\n print(arr)\n#---\ndict_medium = {}\nfor i in arr:\n dict_medium[i[0]] = dict_medium.setdefault(i[0], 0) + int(i[2])\nprint(dict_medium)\n#---\ndict_count = {}\ndict_count2 = {}\nfor i in arr:\n if i[0] not in dict_count2:\n dict_count2[i[0]] = [1, int(i[2])]\n else:\n dict_count2[i[0]][0] += 1\n dict_count2[i[0]][1] += int(i[2])\n count = 0\nprint(dict_count2)\nfor i in range(1, 12):\n if str(i) not in dict_count2.keys():\n print(i,'-')\n else:\n print(i, (dict_count2[str(i)][1]/dict_count2[str(i)][0]))'''\n#----------------------------------------------------------------------------------------------------------\n'''Реализуйте программу, которая будет эмулировать работу с пространствами имен. \nНеобходимо реализовать поддержку создания пространств имен и добавление в них переменных.\nВ данной задаче у каждого пространства имен есть уникальный текстовый идентификатор – его имя.\n-----------------------------------------------------------------------------------------------------------\nВашей прогр��мме на вход подаются следующие запросы:\n create – создать новое пространство имен с именем \n внутри пространства \n add – добавить в пространство переменную \n get – получить имя пространства, из которого будет взята переменная \n при запросе из пространства , или None, если такого пространства не существует\n Во пример вложенных пространств имено global, foo, bar:\nnamesp = {\n 'global': {\n 'parent': None,\n 'vars': set('a'),\n 'foo': {\n 'parent': 'global',\n 'vars': set('b'),\n 'bar': {\n 'parent': 'foo', \n 'vars': set('a')}\n }\n }\n}\n2. Количество команд считывал через n = int(input()). Затем в цикле while n != 0 считывал команды, \nсразу деля их на 3 переменные cmd, nmsp, var = input().split() и в зависимости \nот if cmd == я выполнял ту или иную функцию и передавал в нее остальные 2 переменные nmsp и var.\n3. У меня было 3 основные функции \n- def get(namespace, var),\n- def add(namespace,var),\n a['vars'].add(var)\n- def create(namespace, parent)\n a[namespace] = {'parent':parent, 'vars':set()}\n4. Для создания окружения я использовал рекурсивную функцию, \nкоторая ищет ключ словаря который будет родительским пространством для нового.\ndef finditem(obj, key):\n if key in obj:\n return obj[key]\n5. Для поиска переменных я создал рекурсивную функцию \ndef findvar(obj, namespace, var):\n if namespace in obj:\n if var in obj[namespace]['vars']:\n return namespace\n--------------------------------------------------------------------------\nили 2d массив [global, var, parrent]\n [ ... ... .... ]\n'''\n#-- пример\ndg = {'global':\n {'parrent':None, 'vars': set('w'),\n 'foo':{'parrent':'global', 'vars': set('a'),\n 'bar':{'parrent':'foo', 'vars': set('r'),\n 'ree':{'parrent':'bar', 'vars': set('s')}}}} }\n#------------------------------------------------------------------------------------\narr_keys = ['global'] # ключи для словаря\ndict_namespace = {'global': {'parrent': 'None', 'var': set()}} # Помещаем все namespace, vars в словарь\n#\n#-- Ф-ция для добавл. var: {'namespace': { var:''}} в словарь\ndef add_var(name, namespace):\n for key in dict_namespace:\n if key == name:\n dict_namespace[key]['var'].add(namespace)\n#\n#--Ф-ция для добавл. key, namespace : {'key': {'parrent': 'namespace'}} в словарь\ndef create_def(arr_keys, namespace):\n for key in arr_keys:\n if key not in dict_namespace:\n dict_namespace[key] = {}\n dict_namespace[key]['parrent'] = namespace\n dict_namespace[key]['var'] = set()\n#\n#-- Ф-я для поиска переменных, ф-ций, namespa-ов.\n\n#dict_namespace = {'global': {'parrent': 'global', 'var': ['a','x']}, 'foo': {'parrent': 'global', 'var': ['b']}, 'boo': {'parrent': 'foo', 'var': ['c','d']}}\ndef get(name, namespace, dict_namespace):\n list_key = arr_keys[::-1] # revers list\n\n index = list_key.index(name)\n #print(list_key[index:])\n count = index\n while count < len(list_key):\n #print(list_key)\n #print(len(list_key))\n #print(list_key[count:])\n #print(dict_namespace[list_key[count]])\n\n if namespace in dict_namespace[list_key[count]]['var']:\n ##print(namespace in dict_namespace[name]['var'])\n print(list_key[count]); return\n #\n else:\n if dict_namespace[list_key[count]]['parrent'] == 'None':\n print('None'); return\n parrent = dict_namespace[list_key[count]]['parrent']\n #print(parrent, list_key.index(parrent),'*')\n #print(namespace in dict_namespace[parrent]['var'])\n #print(dict_namespace[parrent]['var'], '**')\n\n if namespace in dict_namespace[parrent]['var']:\n print(parrent); return\n count = list_key.index(parrent); continue\n #print('None *'); return\n print('None'); return\n\n#-------------------------------\n\n#------------- Основное тело программы -читаем из файла тесты----------------\n#path = '/home/asumin/Документы/Программирование Python/Stepic.org/Основы и применение/test'\npath = '/home/asumin/Документы/Программирование Python/stepik.org/Основы и применение/tests'\narr = []\nwith open(path,'r') as file:\n for i in file.readlines():\n arr.append(i.strip('\\n').split())\n#-----------------------\n count = 1\n while count < len(arr):\n if arr[count][0] == 'add':\n add_var(arr[count][1], arr[count][2]) # Выз. ф-ю. add_var\n elif arr[count][0] == 'create':\n arr_keys.append(arr[count][1]) # доб. в список\n #print(arr_keys)\n create_def(arr_keys, arr[count][2]) # выз. ф. create_def\n elif arr[count][0] == 'get':\n get(arr[count][1], arr[count][2], dict_namespace) # выз. ф. get\n count +=1\n#\n print('`'*20)\n for k,v in dict_namespace.items(): print(k, v)\n\n#--------------------------------------------------------\n#\naw = {f'{int(a + 1)} {\"май\"}' :a for a in range(5)}\n#\n","sub_path":"Global area/global_area.py","file_name":"global_area.py","file_ext":"py","file_size_in_byte":9201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"412670723","text":"import argparse\nimport torch\nimport pickle\nimport preprocess_data\nfrom model import model_FL\nfrom torch import optim\nfrom pathlib import Path\nfrom matplotlib import pyplot as plt\nimport numpy as np\nfrom sklearn.svm import SVR\nfrom sklearn.model_selection import GridSearchCV\nfrom anomalyDetector import fit_norm_distribution_param\nfrom anomalyDetector import anomalyScore\nfrom anomalyDetector import get_precision_recall\nfrom anomalyDetector import get_precision_recall_zsx_2\nfrom anomalyDetector import get_f1\nfrom utils.eval_methods import calc_point2point\nfrom utils.distri2Th import DistriTailNoise2Th\nfrom utils.eval_methods import adjust_predicts_zsx\n\n\n# 有save-fig参数\n\nparser = argparse.ArgumentParser(description='PyTorch RNN Anomaly Detection Model')\nparser.add_argument('--prediction_window_size', type=int, default=10,\n help='prediction_window_size')\nparser.add_argument('--data', type=str, default='ecg',\n help='type of the dataset (ecg, gesture, power_demand, space_shuttle, respiration, nyc_taxi')\nparser.add_argument('--filename', type=str, default='chfdb_chf13_45590.pkl',\n help='filename of the dataset')\nparser.add_argument('--save_fig', action='store_true',\n help='save results as figures')\nparser.add_argument('--compensate', action='store_true',\n help='compensate anomaly score using anomaly score esimation')\nparser.add_argument('--beta', type=float, default=1.0,\n help='beta value for f-beta score')\n\n# 为了DistriTailNoise2Th这个函数的参数,再添加几个参数\n# DistriTailNoise2Th(testScore,difTh,avgNum,meanMulCoefficient,binNum,followNum)\nparser.add_argument('--difTh',type=float,default=-5)\nparser.add_argument('--avgNum',type=int ,default=5)\nparser.add_argument('--meanMulCoefficient',type=float,default=100)\nparser.add_argument('--binNum',type=int,default=60)\nparser.add_argument('--followNum',type=int,default=4)\n\nargs_ = parser.parse_args()\nprint('-' * 89)\nprint(\"=> loading checkpoint \")\ncheckpoint = torch.load(str(Path('save', args_.data, 'checkpoint', args_.filename).with_suffix('.pth')))\nargs = checkpoint['args']\nargs.prediction_window_size = args_.prediction_window_size\nargs.beta = args_.beta\nargs.save_fig = args_.save_fig\nargs.compensate = args_.compensate\nprint(\"=> loaded checkpoint\")\n\n# Set the random seed manually for reproducibility.\ntorch.manual_seed(args.seed)\ntorch.cuda.manual_seed(args.seed)\n\n###############################################################################\n# Load data\n###############################################################################\nTimeseriesData = preprocess_data.PickleDataLoad(data_type=args.data, filename=args.filename, augment_test_data=False)\ntrain_dataset = TimeseriesData.batchify(args, TimeseriesData.trainData[:TimeseriesData.length], bsz=1)\ntest_dataset = TimeseriesData.batchify(args, TimeseriesData.testData, bsz=1)\n\n# 注意,这个时候batchsize都是1\n# [length,1,feature_dim]\n\nfeature_dim = 8+8+8\n\n\n###############################################################################\n# Build the model\n###############################################################################\n#nfeatures = TimeseriesData.trainData.size(-1) # 10\nfeature_data = TimeseriesData.trainData.size(-1) # 10\n\n\nencoder_client_0 = model_FL.encoder_client(enc_client_dims=[[4,8],[8,8]],layer_num=2).to(args.device)\nencoder_client_1 = model_FL.encoder_client(enc_client_dims=[[3,8],[8,8]],layer_num=2).to(args.device)\nencoder_client_2 = model_FL.encoder_client(enc_client_dims=[[3,8],[8,8]],layer_num=2).to(args.device)\n\ndecoder_client_0 = model_FL.encoder_client(enc_client_dims=[[8,8],[8,4]],layer_num=2).to(args.device)\ndecoder_client_1 = model_FL.encoder_client(enc_client_dims=[[8,8],[8,3]],layer_num=2).to(args.device)\ndecoder_client_2 = model_FL.encoder_client(enc_client_dims=[[8,8],[8,3]],layer_num=2).to(args.device)\n\nmodel_server_0 = model_FL.model_server(rnn_type = args.model,\n enc_inp_size=feature_dim,\n rnn_inp_size=args.emsize,\n rnn_hid_size=args.nhid,\n dec_out_size=feature_dim,\n nlayers=args.nlayers,\n res_connection=args.res_connection).to(args.device)\n\n\n\nmodel_server_0.load_state_dict(checkpoint['state_dict']['model_server_0']) # 载入数据参数!\n\nencoder_client_0.load_state_dict(checkpoint['state_dict']['encoder_client_0'])\nencoder_client_1.load_state_dict(checkpoint['state_dict']['encoder_client_1'])\nencoder_client_2.load_state_dict(checkpoint['state_dict']['encoder_client_2'])\ndecoder_client_0.load_state_dict(checkpoint['state_dict']['decoder_client_0'])\ndecoder_client_1.load_state_dict(checkpoint['state_dict']['decoder_client_1'])\ndecoder_client_2.load_state_dict(checkpoint['state_dict']['decoder_client_2'])\n\ndimensions_client_0 = [0,1,2,3]\ndimensions_client_1 = [4,5,6]\ndimensions_client_2 = [7,8,9]\n\nrecover_dimensions_client_0 = [0,1,2,3,4,5,6,7]\nrecover_dimensions_client_1 = [8,9,10,11,12,13,14,15]\nrecover_dimensions_client_2 = [16,17,18,19,20,21,22,23]\n\nconfig={}\nconfig['dimensions_client_0'] = dimensions_client_0\nconfig['dimensions_client_1'] = dimensions_client_1\nconfig['dimensions_client_2'] = dimensions_client_2\n\nconfig['recover_dimensions_client_0'] = recover_dimensions_client_0\nconfig['recover_dimensions_client_1'] = recover_dimensions_client_1\nconfig['recover_dimensions_client_2'] = recover_dimensions_client_2\n\n# del checkpoint\n\nscores, predicted_scores, precisions, recalls, f_betas = list(), list(), list(), list(), list()\ntargets, mean_predictions, oneStep_predictions, Nstep_predictions = list(), list(), list(), list()\ntry:\n # For each channel in the dataset\n\n predList = []\n testScoreList = []\n \n for channel_idx in range(feature_data):\n ''' 1. Load mean and covariance if they are pre-calculated, if not calculate them. '''\n # Mean and covariance are calculated on train dataset.\n if 'means' in checkpoint.keys() and 'covs' in checkpoint.keys():\n print('=> loading pre-calculated mean and covariance')\n mean, cov = checkpoint['means'][channel_idx], checkpoint['covs'][channel_idx]\n else:\n print('=> calculating mean and covariance')\n mean, cov = fit_norm_distribution_param(args, model_server_0,encoder_client_0,encoder_client_1,encoder_client_2,\n decoder_client_0,decoder_client_1,decoder_client_2,\n train_dataset, channel_idx=0,config=config)\n\n ''' 2. Train anomaly score predictor using support vector regression (SVR). (Optional) '''\n # An anomaly score predictor is trained\n # given hidden layer output and the corresponding anomaly score on train dataset.\n # Predicted anomaly scores on test dataset can be used for the baseline of the adaptive threshold.\n if args.compensate: # 默认False\n # compensate anomaly score using anomaly score esimation\n print('=> training an SVR as anomaly score predictor')\n train_score, _, _, hiddens, _ = anomalyScore(args, model_server_0,encoder_client_0,encoder_client_1,encoder_client_2,\n decoder_client_0,decoder_client_1,decoder_client_2,\n train_dataset, mean, cov, channel_idx=0, config=config)\n score_predictor = GridSearchCV(SVR(), cv=5,\n param_grid={\"C\": [1e0, 1e1, 1e2], \"gamma\": np.logspace(-1, 1, 3)})\n score_predictor.fit(torch.cat(hiddens, dim=0).numpy(), train_score.cpu().numpy())\n else:\n score_predictor = None\n\n ''' 3. Calculate anomaly scores'''\n # Anomaly scores are calculated on the test dataset\n # given the mean and the covariance calculated on the train dataset\n print('=> calculating anomaly scores')\n \n #train_score, _, _, hiddens, _ = anomalyScore(args, model_server_0,encoder_client_0,encoder_client_1,encoder_client_2,\n # decoder_client_0,decoder_client_1,decoder_client_2,\n # train_dataset, mean, cov, channel_idx=0, config=config)\n \n score, sorted_prediction, sorted_error, _, predicted_score = anomalyScore(args, model_server_0,\n encoder_client_0,encoder_client_1,encoder_client_2,\n decoder_client_0,decoder_client_1,decoder_client_2,\n test_dataset, mean, cov,\n score_predictor=score_predictor,\n channel_idx=channel_idx,\n config=config)\n # score [length,] 异常分数,越大说明越是异常\n # sorted_prediction [time_length,10] 每个时刻的10个预测值\n # sorted_error [time_length,10] 每个时刻的预测误差\n # prediction_score 默认的话是空数组\n\n ''' 4. Evaluate the result '''\n # The obtained anomaly scores are evaluated by measuring precision, recall, and f_beta scores\n # The precision, recall, f_beta scores are are calculated repeatedly,\n # sampling the threshold from 1 to the maximum anomaly score value, either equidistantly or logarithmically.\n print('=> calculating precision, recall, and f_beta')\n # precision, recall, f_beta = get_precision_recall(args, score, num_samples=1000, beta=args.beta,\n # label=TimeseriesData.testLabel.to(args.device))\n #anomaly_temp = get_precision_recall_zsx_2(args, score, num_samples=1000, beta=args.beta,\n # label=TimeseriesData.testLabel.to(args.device))\n \n score[score<0.0] = 0.0\n\n predict = DistriTailNoise2Th(score.cpu().numpy(),args_.difTh,args_.avgNum,args_.meanMulCoefficient,args_.binNum,args_.followNum)\n predList.append(predict)\n\n testScoreList.append(score.cpu().numpy())\n\n print(\"已完成第\",channel_idx,\"维度的检测\")\n\n\n\n predList = np.array(predList)\n testScoreList = np.array(testScoreList)\n \n predListPath = Path(\"save\", args.data, \"anomalypred\")\n predListPath.mkdir(parents=True, exist_ok=True)\n torch.save(predList, str(predListPath.joinpath(args.filename.split('.')[0]+\"_predList\").with_suffix(\".pth\")))\n \n torch.save(testScoreList, str(predListPath.joinpath(args.filename.split('.')[0]+\"_testScoreList\").with_suffix(\".pth\")))\n\n lastPred = np.sum(predList,axis=0)\n lastPred = lastPred.astype(bool)\n torch.save(lastPred, str(predListPath.joinpath(args.filename.split('.')[0]+\"_lastPred\").with_suffix(\".pth\")))\n\n lastPredAdjust = adjust_predicts_zsx(lastPred,TimeseriesData.testLabel.cpu().numpy())\n torch.save(lastPredAdjust, str(predListPath.joinpath(args.filename.split('.')[0]+\"_lastPredAdjust\").with_suffix(\".pth\")))\n\n f1 = calc_point2point(lastPredAdjust,TimeseriesData.testLabel.cpu().numpy())\n ResultPath = Path(\"save\", args.data, \"Result\")\n ResultPath.mkdir(parents=True, exist_ok=True)\n torch.save(f1, str(ResultPath.joinpath(args.filename.split('.')[0]+\"_Result\").with_suffix(\".pth\")))\n print(\"f1_score=\",f1)\n\n\nexcept KeyboardInterrupt:\n print('-' * 89)\n print('Exiting from training early')","sub_path":"Anomaly_detection_VFL/RNN-Time-series-Anomaly-Detection-master_FL-selfMethod-v1.1/.ipynb_checkpoints/2_2_anomaly_detection_FL-checkpoint.py","file_name":"2_2_anomaly_detection_FL-checkpoint.py","file_ext":"py","file_size_in_byte":12047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"600730319","text":"def Parsetxt(txt_path):\n file_list=[]\n label_list=[]\n with open(txt_path,'r') as f:\n for line in f:\n file_list.append(line.split(' ')[0])\n label_list.append(int(line.split(' ')[1]))\n return file_list, label_list \n\n#list to txt\ndef list2txt(txt_list,txt_path):\n with open(txt_path,'w') as f :\n for line in txt_list:\n f.write(line+'\\n')\n\nfile,label = Parsetxt('test_probe.txt')\nlist2txt(file,'/home/nikoong/Algorithm_test/dgd_person_reid/interface/txt/probe(origin).txt')\n","sub_path":"interface/txt/dellabel.py","file_name":"dellabel.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"321261784","text":"from datetime import date\n\nname = input(\"Enter Name\")\nage = input(\"Enter Age\")\n\nif age.isalpha():\n print(\"Enter Age Number\")\nelse:\n final = 100 - int(age)\n current = date.today()\n print(name + \"is 100 years at \" + str(current.year + final))\n","sub_path":"1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"188023117","text":"from time import sleep\n\nfrom airflow.contrib.hooks.emr_hook import EmrHook\nfrom airflow.contrib.operators.emr_add_steps_operator import EmrAddStepsOperator\nfrom airflow.exceptions import AirflowException, AirflowSensorTimeout\nfrom airflow.utils import timezone\nfrom airflow.utils.decorators import apply_defaults\n\n\nclass EmrRunStepOperator(EmrAddStepsOperator):\n \"\"\"\n An operator that adds one step to an existing EMR job_flow and then monitors it's execution.\n\n :param job_flow_id: id of the JobFlow to add step to (templated)\n :type job_flow_id: str\n :param aws_conn_id: aws connection to use\n :type aws_conn_id: str\n :param step: EMR step description (templated)\n :type step: dict\n :param poke_interval: interval to check EMR step status\n :type poke_interval: int\n :param timeout: timeout when to stop poking the step\n :type timeout: int\n \"\"\"\n\n template_fields = ['job_flow_id', 'step']\n\n NON_TERMINAL_STATES = ['PENDING', 'RUNNING', 'CONTINUE', 'CANCEL_PENDING']\n FAILED_STATE = ['CANCELLED', 'FAILED', 'INTERRUPTED']\n POKE_INTERVAL = 15 # 15 seconds\n TIMEOUT = 60 * 60 * 5 # 5 hours\n\n @apply_defaults\n def __init__(\n self,\n job_flow_id: str,\n aws_conn_id: str = 'aws_default',\n step: dict = None,\n poke_interval: int = POKE_INTERVAL,\n timeout: int = TIMEOUT,\n *args, **kwargs):\n super(EmrAddStepsOperator, self).__init__(*args, **kwargs)\n self.aws_conn_id = aws_conn_id\n self.job_flow_id = job_flow_id\n if step:\n self.step = step\n else:\n raise AirflowException('EMR step has to be provided')\n self.poke_interval = poke_interval\n self.timeout = timeout\n self.emr = None\n self.step_id = None\n\n def add_emr_step(self):\n self.log.info(f'Adding step to cluster {self.job_flow_id}')\n response = self.emr.add_job_flow_steps(JobFlowId=self.job_flow_id, Steps=self.step)\n\n if not response['ResponseMetadata']['HTTPStatusCode'] == 200:\n raise AirflowException('Adding step failed: %s' % response)\n\n self.log.info(f'Step {response[\"StepIds\"]} added to JobFlow')\n\n return response['StepIds'][0]\n\n def poke_emr_step(self):\n self.log.info(f'Poking step {self.step_id} on EMR cluster {self.job_flow_id}')\n response = self.emr.describe_step(ClusterId=self.job_flow_id, StepId=self.step_id)\n\n if not response['ResponseMetadata']['HTTPStatusCode'] == 200:\n self.log.info(f'Bad HTTP response: {response}')\n return False\n\n state = response['Step']['Status']['State']\n self.log.info(f'Step currently is in {state} state')\n\n if state in self.NON_TERMINAL_STATES:\n return True\n\n if state in self.FAILED_STATE:\n failure_message = self.failure_message_from_response(response)\n raise AirflowException('EMR step failed ' + failure_message)\n\n return False\n\n @staticmethod\n def failure_message_from_response(response):\n failure_details = response['Step']['Status'].get('FailureDetails')\n if failure_details:\n return f'for reason {failure_details.get(\"Reason\")} ' \\\n f'with message {failure_details.get(\"Message\")} ' \\\n f'and log file {failure_details.get(\"LogFile\")}'\n return ''\n\n def execute(self, context):\n self.emr = EmrHook(aws_conn_id=self.aws_conn_id).get_conn()\n\n # Add step to EMR cluster\n self.step_id = self.add_emr_step()\n\n # Monitor EMR step\n self.log.info(f'Start watching step [{self.step_id}]')\n started_at = timezone.utcnow()\n\n while self.poke_emr_step():\n if (timezone.utcnow() - started_at).total_seconds() > self.timeout:\n raise AirflowSensorTimeout('Snap. Time is OUT.')\n self.log.info(f'Sleeping for {self.poke_interval} seconds...')\n sleep(self.poke_interval)\n\n self.log.info(f\"Step [{self.step_id}] completed successfully. Exiting...\")\n","sub_path":"aws/emr/emr_plugin/operators/emr_run_step_operator.py","file_name":"emr_run_step_operator.py","file_ext":"py","file_size_in_byte":4115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"7279306","text":"\"\"\"\n問題文\n正の整数Xが以下の条件を満たすとき、Xはルンルン数であると言います。\nXを(leading zeroなしで)十進数表記した際に、隣り合うどの2つの桁の値についても、差の絶対値が 1以下\n例えば、1234, 1, 334 などはルンルン数ですが、\n31415, 119, 13579 などはルンルン数ではありません。\n\n正の整数Kが与えられます。小さい方から K番目のルンルン数を求めてください。\n\n制約\n1≤K≤10^5\n入力はすべて整数である。\n\n===================\nimprovement:\n3桁のルンルン数で、上2桁が12なら、3桁目は 1 or 2 or 3 。\n小さいほうからルンルン数を列挙していくなら、そのルンルン数に末尾1桁、隣り合う数字を足してもルンルン数になる。\nこれを繰り返すことでルンルン数だけを列挙することができる。\n言われてみればこの実装で動くのは理解できるが、\n時間内にこれを思いつくことが出来なかった。悔しい。\n特にdequeを使う動きは思いつかなかった、次回に活かしたい。\n\"\"\"\n\n# === improvement ===\nfrom collections import deque\n\nK = int(input())\n\nq = deque(range(1, 10))\n\nfor i in range(K):\n x = q.popleft()\n r = x % 10\n y = 10 * x + r\n if r != 0:\n q.append(y - 1)\n q.append(y)\n if r != 9:\n q.append(y + 1)\n\nprint(x)\n","sub_path":"ABC161/D.py","file_name":"D.py","file_ext":"py","file_size_in_byte":1416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"418961655","text":"# 1338. Reduce Array Size to The Half\n# 每日一题。\n\n\n# 2021/07/06\n# Runtime: 568 ms, faster than 82.54% of Python3 online submissions for Reduce Array Size to The Half.\n# Memory Usage: 31.3 MB, less than 65.35% of Python3 online submissions for Reduce Array Size to The Half.\n\n# 数学逻辑题\n# 从频数最大的开始remove,直到去掉一半以上的数为止。\n\n\nclass Solution:\n def minSetSize(self, arr: List[int]) -> int:\n counts = {}\n for a in arr:\n counts[a] = counts.get(a, 0) + 1\n counts = sorted( counts.values(), reverse = True)\n k = len(arr) // 2\n sums, ans = 0, 0\n for c in counts:\n sums += c\n ans += 1\n if sums >= k:\n return ans\n\n# 2021/12/26\n# vwc 174\n# Runtime: 592 ms, faster than 68.63% of Python3 online submissions for Reduce Array Size to The Half.\n# Memory Usage: 30.4 MB, less than 89.66% of Python3 online submissions for Reduce Array Size to The Half.\n\n# sort, greedy\n# start from removing the number with the most frequency\n\n\nclass Solution:\n def minSetSize(self, arr: List[int]) -> int:\n counts = {}\n for a in arr:\n counts[a] = counts.get(a, 0) + 1\n sums = 0\n nums = sorted(counts.keys(), key=lambda x: counts[x], reverse=True)\n ans = 1\n for num in nums:\n sums += counts[num]\n if sums * 2 >= len(arr):\n return ans\n ans += 1\n return ans\n\n","sub_path":"1338. Reduce Array Size to The Half.py","file_name":"1338. Reduce Array Size to The Half.py","file_ext":"py","file_size_in_byte":1491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"238252579","text":"import logging\n\nimport scrapy\n\nfrom steamSpider.items import Game\nfrom steamSpider.utils.basicUtils import strip_string, strip_tag\n\n\nclass GameSpider(scrapy.Spider):\n \"\"\"\n The main component of the spider that extracts info from web pages\n \"\"\"\n name = \"game\"\n # Scrape all games in the Action section\n start_urls = [\"http://store.steampowered.com/tag/en/Action/#p=0&tab=TopSellers\",\n # \"http://store.steampowered.com/tag/en/Action/#p=1&tab=TopSellers\",\n # \"http://store.steampowered.com/tag/en/Action/#p=2&tab=TopSellers\",\n # \"http://store.steampowered.com/tag/en/Action/#p=3&tab=TopSellers\"\n ]\n\n def parse(self, response):\n s = response.url\n if \"tag\" in s: # Search pages\n logging.info(\"Entering search page\")\n # print(response.body)\n print(\"length is: \" + str(len(response.xpath('//div[@id=\"TopSellersRows\"]//a/@href').extract())))\n for target in response.xpath('//div[@id=\"TopSellersRows\"]//a/@href').extract():\n logging.info(\"Target urls are:\" + target)\n yield scrapy.Request(target, callback=self.parse)\n elif \"app\" in s and \"agecheck\" not in s: # make sure we are not stuck at the age check page\n logging.info(\"Scraping game\")\n # print(response.body)\n\n game = Game()\n\n game['game_name'] = strip_string(response.xpath(\"//div[@class='apphub_AppName']/text()\").extract_first())\n game['developer'] = response.xpath(\"//div[@class='details_block']/a/text()\").extract()[1]\n game['release_date'] = response.xpath(\"//span[@class='date']/text()\").extract_first()\n\n # deal with Steam discount; needs to be upgraded when a single page contains more than one price\n # such as starter edition and franchise etc...\n price = response.xpath(\"//div[@class='game_purchase_price price']/text()\").extract_first()\n if price is None:\n price = response.xpath(\"//div[@class='discount_final_price']/text()\").extract_first()\n else:\n price = strip_string(price)\n game['price'] = price\n\n description = strip_string(response.xpath(\"//div[@id='game_area_description']\").extract_first())\n description = strip_tag(description)\n game['full_description'] = description\n\n # Since not all System Requirement sections are of the same format, we just store the paragraph and the\n # cleaning of string is saved when using the data; first part is minimum and the second part is\n\n req = response.xpath(\"//div[@class='sysrec_contents']//ul[@class='bb_ul']/li\").extract()\n r = \"\"\n for s in req:\n r += strip_string(strip_tag(strip_string(s)))\n game['system_requirement'] = r\n\n # Some new releases does not have user reviews, so we just put in 0 and No User Comment\n rating = response.xpath(\"//div[@class='summary column']/span/text()\").extract()\n # rater = response.xpath(\"//span[@class='responsive_hidden']/text()\").extract()\n if len(rating) == 0 or rating is None:\n game[\"rater_short\"] = game[\"rater_long\"] = \"0\"\n game[\"rating_short\"] = game[\"rating_long\"] = \"No User Comment\"\n\n else:\n game[\"rating_short\"] = strip_string(rating[0])\n game['rater_short'] = strip_string(rating[1])\n game[\"rating_long\"] = strip_string(rating[3])\n game[\"rater_long\"] = strip_string(rating[4])\n\n # Store the cover image url; can store all the image links in the\n game[\"image_url\"] = response.xpath(\"//img[@class='game_header_image_full']/@src\").extract_first()\n\n logging.info(\"Game scraped\")\n yield game\n # Will implement another crawler to find comments and store in another database\n\n elif \"sub\" in s and \"agecheck\" not in s: # deal with package page\n for target in response.xpath('//a[@class=\"tab_item_overlay\"]/@href').extract():\n logging.info(\"Target url is:\" + target)\n yield scrapy.Request(target, callback=self.parse)\n elif \"agecheck\" in s:\n logging.info(\"Redirecting from agecheck page\")\n yield scrapy.Request(response.url, callback=self.parse)\n else:\n pass\n","sub_path":"steamSpider/spiders/gameSpider.py","file_name":"gameSpider.py","file_ext":"py","file_size_in_byte":4467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"609385824","text":"import os\nfrom re import M\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\nos.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true'\nfrom sklearn.preprocessing import LabelEncoder\nfrom matplotlib import gridspec\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.models import Sequential, Model\nimport numpy as np\nfrom keras.layers import Input, Conv2D, MaxPooling2D, Dense, Dropout, Flatten\nfrom keras.metrics import Precision, Recall\nfrom keras.callbacks import TensorBoard, Callback\n\n\nclass KernelsCallback(Callback):\n def __init__(self, eps):\n self.eps = eps\n self.lays = [] \n \n def set_model(self, model): \n self.model = model \n for i in range(len(model.layers)):\n if 'conv' in model.layers[i].name:\n self.lays.append(i)\n \n def on_epoch_end(self, epoch, logs=None):\n for layer in self.lays: \n if epoch in self.eps:\n filters, biases = model.layers[layer].get_weights()\n \n f_min, f_max = filters.min(), filters.max()\n filters = (filters - f_min) / (f_max - f_min)\n \n out_channels = filters.shape[3]\n in_channels = filters.shape[2]\n \n for i in range(out_channels):\n f = filters[:,:,:,i] \n ind = 1\n for j in range(in_channels):\n flt = plt.subplot(1, in_channels, ind)\n flt.set_xticks([])\n flt.set_yticks([])\n plt.imshow(f[:,:,j], cmap='gray')\n plt.savefig(f'imgs/{layer+1}_{i+1}_{epoch+1}.png') \n ind += 1 \n plt.clf() \n # <слой>_<фильтр>_<эпоха>\n\n\ndef gen_rect(SIZE=50):\n img = np.zeros([SIZE, SIZE])\n x = np.random.randint(0, SIZE)\n y = np.random.randint(0, SIZE)\n w = np.random.randint(SIZE // 10, SIZE // 2)\n h = np.random.randint(SIZE // 10, SIZE // 2)\n img[x:x + w, y:y + h] = 1\n return img\n\n\ndef gen_circle(SIZE=50):\n img = np.zeros([SIZE, SIZE])\n x = np.random.randint(0, SIZE)\n y = np.random.randint(0, SIZE)\n r = np.random.randint(SIZE // 10, SIZE // 3)\n for i in range(0, SIZE):\n for j in range(0, SIZE):\n if (i-x)**2 + (j-y)**2 <= r**2:\n img[i, j] = 1\n return img\n\n\ndef gen_data(SIZE=500, IMG_SIZE=50):\n c1 = SIZE // 2\n c2 = SIZE - c1\n label_c1 = np.full([c1, 1], 'Square')\n data_c1 = np.array([gen_rect(IMG_SIZE) for i in range(c1)])\n label_c2 = np.full([c2, 1], 'Circle')\n data_c2 = np.array([gen_circle(IMG_SIZE) for i in range(c2)])\n data = np.vstack((data_c1, data_c2))\n label = np.vstack((label_c1, label_c2))\n return data, label\n\n\ndef data_preprocessing(X, Y):\n encoder = LabelEncoder()\n y = encoder.fit_transform(Y.ravel())\n\n idx = np.random.permutation(len(X))\n X, y = X[idx], y[idx]\n\n val_split = 0.1\n test_num = round((1-val_split)*len(X))\n val_num = round(test_num*(1-val_split))\n train_data, train_labels = X[:val_num], y[:val_num]\n val_data, val_labels = X[val_num:test_num], y[val_num:test_num]\n test_data, test_labels = X[test_num:], y[test_num:]\n train_data = np.expand_dims(train_data, axis=3)\n val_data = np.expand_dims(val_data, axis=3)\n test_data = np.expand_dims(test_data, axis=3)\n return (train_data, val_data, test_data), (train_labels, val_labels, test_labels)\n\n\ndef draw_results(H):\n loss = H.history['loss']\n val_loss = H.history['val_loss']\n acc = H.history['accuracy']\n val_acc = H.history['val_accuracy']\n epochs = range(1, len(loss) + 1)\n\n fig = plt.figure(figsize=(12, 6))\n gs = gridspec.GridSpec(1, 2, width_ratios=[3, 3])\n plt.subplot(gs[0])\n plt.plot(epochs, loss, 'r--', label='Training loss')\n plt.plot(epochs, val_loss, 'g--', label='Validation loss')\n plt.title('Training and validation loss')\n plt.xlabel('Epochs')\n plt.ylabel('Loss')\n plt.legend()\n\n plt.subplot(gs[1])\n plt.plot(epochs, acc, 'r--', label='Training acc')\n plt.plot(epochs, val_acc, 'g--', label='Validation acc')\n plt.title('Training and validation accuracy')\n plt.xlabel('Epochs')\n plt.ylabel('Accuracy')\n plt.legend()\n\n plt.tight_layout()\n plt.show()\n\n\nIMG_SIZE = 50\nSIZE = 1000\nBATCH_SIZE = 15\nNUM_EPOCHS = 10\n\nFILTERS_EPOCHS = [0,5,9]\n\ndata, labels = gen_data(SIZE, IMG_SIZE)\n(train_data, val_data, test_data), (train_labels,\n val_labels, test_labels) = data_preprocessing(data, labels)\n\nmodel = Sequential([\n Input(shape=(IMG_SIZE, IMG_SIZE, 1)),\n Conv2D(8, (3, 3), padding='same', activation='relu'),\n MaxPooling2D((2, 2)),\n Conv2D(16, (3, 3), padding='same', activation='relu'),\n MaxPooling2D((2, 2)),\n Flatten(),\n Dense(128, activation='relu'),\n Dropout(0.5),\n Dense(1, activation='sigmoid')\n])\nmodel.compile(loss='binary_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\nH = model.fit(train_data, train_labels,\n batch_size=BATCH_SIZE, epochs=NUM_EPOCHS,\n verbose=2, validation_data=(val_data, val_labels), callbacks=[KernelsCallback(FILTERS_EPOCHS)])\nmodel.evaluate(test_data, test_labels, verbose=1)\n# draw_results(H)\n","sub_path":"8383/Kireev/pr/8/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":5431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"576566211","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\ndef pie_chart(data, title = \"Non-Title\"):\n labels = []\n fracs = []\n for label, frac in data.items():\n labels.append(label)\n fracs.append(frac)\n fig, axs = plt.subplots(1, 1)\n\n # Shift the second slice using explode\n axs.pie(fracs, labels=labels, autopct='%.2f%%',shadow=True,\n explode=(0.05,) * len(labels))\n plt.title(title, fontsize=16, weight = 'bold');\n\n plt.show()\n\ndef bar_chart(data, xlable, ylabel, title):\n labels = []\n fracs = []\n for label, frac in data.items():\n labels.append(label)\n fracs.append(frac)\n\n x_pos = [i for i, _ in enumerate(labels)]\n plt.bar(x_pos, fracs, color='red')\n plt.xlabel(xlable)\n plt.ylabel(ylabel)\n plt.title(title)\n\n plt.xticks(x_pos, labels)\n","sub_path":"code/visualization.py","file_name":"visualization.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"364617402","text":"# Gen v0.1\n# A generic, JSON-based asset pipeline for heterogeneous setups and\n# unusual configurations.\n#\n# This is free and unencumbered software released into the public domain.\n# For more information, please refer to \n\nimport os\nimport shutil\nimport json\nimport subprocess\nimport jinja2\nimport jinja2.meta\nimport sys\nimport imp\nimport argparse\nimport logging\nimport copy\nimport time\n\n# Helper functions\ndef in_out_file(asset_root, dist_root, f):\n return os.path.join(asset_root, f), os.path.join(dist_root, f)\ndef is_newer(i_file, o_file):\n if (not os.path.exists(o_file) or\n os.path.getmtime(i_file) > os.path.getmtime(o_file)):\n return True\n return False\n\ndef find_asset_object(assets, directory):\n directory = os.path.normpath(directory)\n # Go as long as we don't repeat ourselves.\n while directory != os.path.dirname(directory):\n for cur_asset in assets:\n if cur_asset['root'] == directory:\n return cur_asset\n # Remove the last component of the directory, effectively pointing to\n # it's parent.\n directory = os.path.dirname(directory)\n return None\n\n# Exceptions\nclass AssetRootNotFound(Exception):\n pass\n\nclass ValidationError(Exception):\n def __init__(self, msg, obj):\n super().__init__(msg)\n self.obj = obj\nclass InputTypeError(ValidationError):\n def __init__(self, obj, expected_type):\n super().__init__(\"Input object '{0}' must be type: '{1}'\"\n .format(repr(obj), str(expected_type)), obj)\n self.expected_type = expected_type\nclass InputAttributeError(ValidationError):\n def __init__(self, obj, attr):\n super().__init__(\"Input object '{0}' must have attribute: '{1}'\"\n .format(repr(obj), str(attr)), obj)\n self.attr = attr\nclass SourceNotFoundError(ValidationError):\n def __init__(self, obj, fname):\n super().__init__(\"Source file '{0}' doesn't exist.\".format(fname), obj)\n self.fname = fname\n\nclass Environment:\n def __init__(self, root, dist_root):\n \"\"\"Initialize the root and the dist root with given values.\"\"\"\n self.root = os.path.abspath(root)\n self.dist_root = os.path.abspath(dist_root)\n\nclass Output:\n def __init__(self, logger=None):\n self.log = logger or logging.getLogger(__name__)\n self.log.addHandler(logging.StreamHandler(sys.stdout))\n self.log.setLevel(logging.WARNING)\n\n def on_transform(self, in_file, out_file):\n self.log.info(os.path.relpath(in_file) + ' => ' +\n os.path.relpath(out_file))\n\n def on_skip(self, out_file):\n self.log.debug('Skipping ' + os.path.relpath(out_file))\n\n def on_command(self, args):\n self.log.info('Running: ' + ' '.join(args))\n\n def on_error(self, msg):\n self.log.error(msg)\n\n def on_remove(self, filename, **kwargs):\n adj = kwargs.get('adj', '') + ' '\n filetype = kwargs.get('filetype') or 'file'\n self.log.info(\"Removing \" + adj + filetype + ': ' + filename)\n\nclass Operations:\n def __init__(self, out=None):\n self.out = out or Output()\n\n def copy(self, input_file, output_file):\n # Make sure the destination directory exists.\n os.makedirs(os.path.dirname(output_file), exist_ok=True)\n # Copy the file\n shutil.copy(input_file, output_file)\n shutil.copystat(input_file, output_file)\n # Notify the environment\n self.out.on_transform(input_file, output_file)\n\n def file_from_content(self, input_file, content, output_file):\n os.makedirs(os.path.dirname(output_file), exist_ok=True)\n with open(output_file, \"w\") as f:\n f.write(content)\n shutil.copystat(input_file, output_file)\n self.out.on_transform(input_file, output_file)\n\n def subprocess_transform(self, prg, options, input_file, output_file):\n args = [prg, input_file, output_file]\n args[1:1] = options\n\n os.makedirs(os.path.dirname(output_file), exist_ok=True)\n\n self.out.on_command(args)\n if subprocess.call(args):\n self.out.on_transform(input_file, output_file)\n shutil.copystat(input_file, output_file)\n\nclass BaseAsset:\n def __init__(self, root, dist, inputs, ops, options, env):\n self.root = os.path.abspath(root)\n self.dist = os.path.abspath(dist)\n\n # Validate each input.\n for i in range(len(inputs)):\n try:\n self.validate(inputs[i])\n except ValidationError as e:\n # Rethrow with a modified message.\n tb = sys.exc_info()[2]\n e.args[0] = 'input[{0}]: '.format(i) + e.args[0]\n raise e.with_traceback(tb)\n except NotImplementedError:\n # If validation isn't implemented that doesn't really matter.\n # Just bail.\n break\n # If there was validation, it passed.\n self.inputs = inputs\n\n self.operations = ops\n self.options = options\n self.env = env\n\n def list_output(self):\n raise NotImplementedError\n def get_dependencies(self, fname):\n \"\"\"Return a list of files relative to self.root that fname requires.\"\"\"\n raise NotImplementedError\n def install(self, filename):\n raise NotImplementedError\n def validate(self, input_obj):\n raise NotImplementedError\n\n def install_all(self):\n \"\"\"Install all files and return what files were installed.\"\"\"\n to_install = self.list_output()\n for f in to_install:\n self.install(f)\n return to_install\n\nclass StaticAsset(BaseAsset):\n def validate(self, fname):\n # Make sure it's a string.\n if not isinstance(fname, str):\n raise InputTypeError(fname, str)\n # Make sure the file exists!\n if not os.path.exists(os.path.join(self.root, fname)):\n raise SourceNotFoundError(fname, fname)\n\n def _get_source_list(self, input_obj):\n # If we are given a directory, use all the files in that directory.\n abs_input = os.path.join(self.root, input_obj)\n if os.path.isdir(abs_input):\n files = []\n for child in os.listdir(abs_input):\n child = os.path.join(abs_input, child)\n files.extend(self._get_source_list(os.path.normpath(child)))\n return files\n # Otherwise it's just a file, easy.\n else:\n return [os.path.relpath(abs_input, self.root)]\n\n def get_dependencies(self, filename):\n return [filename]\n\n def list_output(self):\n files = []\n for i in self.inputs:\n files.extend(self._get_source_list(i))\n return files\n\n def install(self, filename):\n in_f, out_f = in_out_file(self.root, self.dist, filename)\n self.operations.copy(in_f, out_f)\n\nclass Jinja2Asset(BaseAsset):\n def validate(self, input_obj):\n # Here we expect an object with a filename and parameters.\n if not isinstance(input_obj, dict):\n raise InputTypeError(input_obj, dict)\n\n # Make sure we have a filename and that it exists.\n f = input_obj.get('filename', None)\n if f is None:\n raise InputAttributeError(input_obj, 'filename')\n if not os.path.exists(os.path.join(self.root, f)):\n raise SourceNotFoundError(input_obj, f)\n\n def get_dependencies(self, filename):\n depends = [filename]\n\n source = os.path.join(self.root, filename)\n ast = jinja2.Environment().parse(open(source).read())\n template_depends = jinja2.meta.find_referenced_templates(ast)\n for dependency in template_depends:\n if dependency:\n dependency = os.path.join(os.path.dirname(source), dependency)\n dependency = os.path.normpath(dependency)\n dependency = os.path.relpath(dependency, self.root)\n depends.extend(self.get_dependencies(dependency))\n return depends\n\n def list_output(self):\n output = []\n for i in self.inputs:\n output.append(i['filename'])\n return output\n\n def install(self, filename):\n # Set up our Jinja2 environment.\n loader = jinja2.FileSystemLoader(self.root)\n self.__jinja2env = jinja2.Environment(loader=loader)\n\n # Find the asset object based off it's filename.\n # TODO Make this process automatic in the base class.\n input_obj = None\n for i in self.inputs:\n if i['filename'] == filename:\n input_obj = i\n break\n if input_obj is None:\n raise ValueError(\"Cannot find input object with filename: '{0}'\"\n .format(filename))\n\n # The filename is relative to the asset root, but that is where Jinja2\n # looks, so it works out.\n template = self.__jinja2env.get_template(filename)\n\n if 'parameters' in input_obj:\n rendered_template = template.render(input_obj['parameters'])\n else:\n rendered_template = template.render()\n\n in_f, out_f = in_out_file(self.root, self.dist, filename)\n self.operations.file_from_content(in_f, rendered_template, out_f)\n\nclass ScssAsset(StaticAsset):\n def get_dependencies(self, filename):\n return [os.path.splitext(filename)[0] + '.scss']\n def list_output(self):\n output = super().list_output()\n for i in range(len(output)):\n output[i] = os.path.splitext(output[i])[0] + '.css'\n return output\n\n def install(self, filename):\n in_f = os.path.join(self.root, os.path.splitext(filename)[0] + '.scss')\n out_f = os.path.join(self.dist, filename)\n\n # Check for search paths provided.\n search_paths = self.options.get('search_paths', [])\n command_options = []\n for path in search_paths:\n command_options.extend(['--load-path',\n os.path.join(self.env.dist_root, path)])\n\n self.operations.subprocess_transform('scss', command_options,\n in_f, out_f)\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n parser.add_argument('-f', '--assets-file', default=None,\n help=\"Specify the assets json file \" +\n \"(default ./assets.json).\")\n parser.add_argument('-w', '--watch', action=\"store_true\", default=False,\n help=\"Stay open and watch for file changes.\")\n parser.add_argument('-v', '--verbose', action=\"count\", default=0,\n help=\"Log files copied to stderr.\")\n arguments = parser.parse_args()\n\n out = Output()\n if arguments.verbose == 1:\n out.log.setLevel(logging.INFO)\n elif arguments.verbose > 1:\n out.log.setLevel(logging.DEBUG)\n\n # Parse the assets.json file.\n try:\n assets_json_filename = arguments.assets_file or 'assets.json'\n assets_json = json.load(open(assets_json_filename))\n except OSError:\n out.on_error(\"Failed to open '\" + assets_json_filename + \"'!\")\n sys.exit(1)\n\n env = Environment(os.getcwd(),\n os.path.abspath(assets_json.get('dist', 'dist/')))\n\n transformations = {'static': StaticAsset, 'jinja2': Jinja2Asset,\n 'scss': ScssAsset}\n\n while True:\n # Load up our cached modification times.\n try:\n cache = json.load(open('.gencache.json'))\n except OSError:\n cache = {}\n\n cache_to_write = copy.copy(cache)\n\n output = []\n for asset in assets_json.get('assets', []):\n # Find the asset-specific dist dir.\n asset_dist = os.path.join(env.dist_root,\n asset.get('dist', asset['root']))\n asset_dist = os.path.normpath(asset_dist)\n\n # Find our asset class!\n asset_type = transformations.get(asset['type'])\n if asset_type:\n try:\n asset_obj = asset_type\n asset_obj = asset_type(asset['root'], asset_dist,\n asset['input'], Operations(out),\n asset.get('type_options', {}), env)\n except ValidationError as e:\n out.on_error(e)\n continue\n else:\n out.on_error(\"No plugin available to handle '\" +\n asset['type'] + \"' assets.\")\n continue\n\n for f in asset_obj.list_output():\n depends = asset_obj.get_dependencies(f)\n regeneration_required = False\n for dependency in depends:\n dependency_source = os.path.join(asset['root'], dependency)\n dependency_mtime = os.path.getmtime(dependency_source)\n # If the dependency has been changed:\n if cache.get(dependency, 0) < dependency_mtime:\n # Update the cache.\n cache_to_write[dependency] = dependency_mtime\n # Make sure we regenerate the output file later.\n regeneration_required = True\n\n if regeneration_required:\n asset_obj.install(f)\n else:\n out.on_skip(f)\n output.append(os.path.join(asset_dist, f))\n\n # Write the cache.\n json.dump(cache_to_write, open('.gencache.json', 'w'))\n\n for dirname, dirs, files in os.walk(env.dist_root, topdown=False):\n for f in files:\n # Check if the file should be there.\n f = os.path.join(dirname, f)\n if f not in output:\n out.on_remove(os.path.relpath(f), adj='old')\n os.remove(os.path.join(env.dist_root, f))\n\n # Also remove empty children directories.\n for d in dirs:\n d = os.path.join(dirname, d)\n if len(os.listdir(d)) == 0:\n out.on_remove(os.path.relpath(f), adj='empty',\n filetype='directory')\n os.rmdir(d)\n\n time.sleep(.25)\n if not arguments.watch:\n break\n","sub_path":"gen.py","file_name":"gen.py","file_ext":"py","file_size_in_byte":14437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"29340385","text":"'''\nCreated on 19/03/2015\n\n@author: jaj\n'''\nimport unittest\nfrom java.javareader import JavaSourceReader\n\n\nclass TestJavaSourceReader(unittest.TestCase):\n\n def setUp(self):\n self.reader = JavaSourceReader()\n\n def tearDown(self):\n pass\n\n def testReadPackage_ok(self):\n content = '' # arquivo sem package\n self.reader.beforeRead(content)\n self.reader.readPackage(content)\n self.assertIsNone(self.reader.package)\n \n content = 'package p.Test1;' # teste sem nova linha\n self.reader.readPackage(content)\n self.assertEqual('p.Test1', self.reader.package)\n \n content = 'package p.Test1;\\n' # teste com nova linha\n self.reader.readPackage(content)\n self.assertEqual('p.Test1', self.reader.package)\n\n\n def testReadImports(self):\n content = '''import p.Test1;\n import p.Test2;\n '''\n self.reader.readImports(content)\n self.assertTrue(len(self.reader.imports) == 2)\n self.assertEqual('p.Test1', self.reader.imports[0])\n self.assertEqual('p.Test2', self.reader.imports[1])\n\n\n def testReadPublicClass(self):\n content = 'public class A {'\n self.reader.readPublicClass(content)\n self.assertEqual('A', self.reader.publicClassName)\n \n content = 'public class A extends class.B {'\n self.reader.readPublicClass(content)\n self.assertEqual('A', self.reader.publicClassName)\n \n content = 'public class A extends class.B implements class.C {'\n self.reader.readPublicClass(content)\n self.assertEqual('A', self.reader.publicClassName)\n \n content = 'public class A implements class.B {'\n self.reader.readPublicClass(content)\n self.assertEqual('A', self.reader.publicClassName)\n \n content = 'public class A> {'\n self.reader.readPublicClass(content)\n self.assertEqual('A', self.reader.publicClassName)\n \n \n def testReadClasses(self):\n content = '''public class A {\n public class B {\n }\n static class C {\n }\n class D {\n }\n }\n '''\n self.reader.readClasses(content)\n self.assertTrue(len(self.reader.classes) == 3, \n 'a primeira classe publica deve ser ignorada')\n self.assertEqual('B', self.reader.classes[0])\n self.assertEqual('C', self.reader.classes[1])\n self.assertEqual('D', self.reader.classes[2])\n \n \n def testReadMethods(self):\n content = '''public void m1(){\n }\n private void m2(){\n }\n protected void m3(){\n }\n void m4(){\n }\n '''\n self.reader.readMethods(content)\n self.assertTrue(len(self.reader.methods) == 4)\n self.assertEqual('m1', self.reader.methods[0])\n self.assertEqual('m2', self.reader.methods[1])\n self.assertEqual('m3', self.reader.methods[2])\n self.assertEqual('m4', self.reader.methods[3])\n \n \nif __name__ == \"__main__\":\n #import sys;sys.argv = ['', 'Test.testName']\n unittest.main()\n \n","sub_path":"tests/javareader.py","file_name":"javareader.py","file_ext":"py","file_size_in_byte":3160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"95671195","text":"\"\"\"\n mbed CMSIS-DAP debugger\n Copyright (c) 2006-2015 ARM Limited\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\"\"\"\n\nfrom pyOCD.target.target import TARGET_RUNNING\nimport logging\nfrom struct import unpack\nfrom time import time\nfrom flash_builder import FLASH_PAGE_ERASE, FLASH_CHIP_ERASE, FlashBuilder\n\nDEFAULT_PAGE_PROGRAM_WEIGHT = 0.130\nDEFAULT_PAGE_ERASE_WEIGHT = 0.048\nDEFAULT_CHIP_ERASE_WEIGHT = 0.174\n\n# Program to compute the CRC of sectors. This works on cortex-m processors.\n# Code is relocatable and only needs to be on a 4 byte boundary.\n# 200 bytes of executable data below + 1024 byte crc table = 1224 bytes\n# Usage requirements:\n# -In memory reserve 0x600 for code & table\n# -Make sure data buffer is big enough to hold 4 bytes for each page that could be checked (ie. >= num pages * 4)\nanalyzer = (\n 0x2180468c, 0x2600b5f0, 0x4f2c2501, 0x447f4c2c, 0x1c2b0049, 0x425b4033, 0x40230872, 0x085a4053,\n 0x425b402b, 0x40534023, 0x402b085a, 0x4023425b, 0x085a4053, 0x425b402b, 0x40534023, 0x402b085a,\n 0x4023425b, 0x085a4053, 0x425b402b, 0x40534023, 0x402b085a, 0x4023425b, 0x085a4053, 0x425b402b,\n 0x40534023, 0xc7083601, 0xd1d2428e, 0x2b004663, 0x4663d01f, 0x46b4009e, 0x24ff2701, 0x44844d11,\n 0x1c3a447d, 0x88418803, 0x4351409a, 0xd0122a00, 0x22011856, 0x780b4252, 0x40533101, 0x009b4023,\n 0x0a12595b, 0x42b1405a, 0x43d2d1f5, 0x4560c004, 0x2000d1e7, 0x2200bdf0, 0x46c0e7f8, 0x000000b6,\n 0xedb88320, 0x00000044,\n )\n\ndef _msb( n ):\n ndx = 0\n while ( 1 < n ):\n n = ( n >> 1 )\n ndx += 1\n return ndx\n\nclass PageInfo(object):\n\n def __init__(self):\n self.erase_weight = None # Time it takes to erase a page\n self.program_weight = None # Time it takes to program a page (Not including data transfer time)\n self.size = None # Size of page\n self.crc_supported = None # Is the function computeCrcs supported?\n\nclass FlashInfo(object):\n\n def __init__(self):\n self.rom_start = None # Starting address of ROM\n self.erase_weight = None # Time it takes to perform a chip erase\n\nclass Flash(object):\n \"\"\"\n This class is responsible to flash a new binary in a target\n \"\"\"\n\n def __init__(self, target, flash_algo):\n self.target = target\n self.flash_algo = flash_algo\n if flash_algo is not None:\n self.end_flash_algo = flash_algo['load_address'] + len(flash_algo)*4\n self.begin_stack = flash_algo['begin_stack']\n self.begin_data = flash_algo['begin_data']\n self.static_base = flash_algo['static_base']\n self.page_size = flash_algo['page_size']\n else:\n self.end_flash_algo = None\n self.begin_stack = None\n self.begin_data = None\n self.static_base = None\n self.page_size = None\n\n def init(self):\n \"\"\"\n Download the flash algorithm in RAM\n \"\"\"\n self.target.halt()\n self.target.setTargetState(\"PROGRAM\")\n\n # download flash algo in RAM\n self.target.writeBlockMemoryAligned32(self.flash_algo['load_address'], self.flash_algo['instructions'])\n if self.flash_algo['analyzer_supported']:\n self.target.writeBlockMemoryAligned32(self.flash_algo['analyzer_address'], analyzer)\n\n # update core register to execute the init subroutine\n self.updateCoreRegister(0, 0, 0, 0, self.flash_algo['pc_init'])\n # resume and wait until the breakpoint is hit\n self.target.resume()\n while(self.target.getState() == TARGET_RUNNING):\n pass\n\n # check the return code\n result = self.target.readCoreRegister('r0')\n if result != 0:\n logging.error('init error: %i', result)\n\n return\n\n def computeCrcs(self, sectors):\n\n data = []\n\n # Convert address, size pairs into commands\n # for the crc computation algorithm to preform\n for addr, size in sectors:\n size_val = _msb(size)\n addr_val = addr // size\n # Size must be a power of 2\n assert (1 << size_val) == size\n # Address must be a multiple of size\n assert (addr % size) == 0\n val = (size_val << 0) | (addr_val << 16)\n data.append(val)\n\n self.target.writeBlockMemoryAligned32(self.begin_data, data)\n\n # update core register to execute the subroutine\n self.updateCoreRegister(self.begin_data, len(data), 0, 0, self.flash_algo['analyzer_address'])\n\n # resume and wait until the breakpoint is hit\n self.target.resume()\n while(self.target.getState() == TARGET_RUNNING):\n pass\n\n # Read back the CRCs for each section\n data = self.target.readBlockMemoryAligned32(self.begin_data, len(data))\n return data\n\n def eraseAll(self):\n \"\"\"\n Erase all the flash\n \"\"\"\n\n # update core register to execute the eraseAll subroutine\n self.updateCoreRegister(0, 0, 0, 0, self.flash_algo['pc_eraseAll'])\n\n # resume and wait until the breakpoint is hit\n self.target.resume()\n while(self.target.getState() == TARGET_RUNNING):\n pass\n\n # check the return code\n result = self.target.readCoreRegister('r0')\n if result != 0:\n logging.error('eraseAll error: %i', result)\n\n return\n\n def erasePage(self, flashPtr):\n \"\"\"\n Erase one page\n \"\"\"\n\n # update core register to execute the erasePage subroutine\n self.updateCoreRegister(flashPtr, 0, 0, 0, self.flash_algo['pc_erase_sector'])\n\n # resume and wait until the breakpoint is hit\n self.target.resume()\n while(self.target.getState() == TARGET_RUNNING):\n pass\n\n # check the return code\n result = self.target.readCoreRegister('r0')\n if result != 0:\n logging.error('erasePage error: %i', result)\n\n return\n\n def programPage(self, flashPtr, bytes):\n \"\"\"\n Flash one page\n \"\"\"\n\n # prevent security settings from locking the device\n bytes = self.overrideSecurityBits(flashPtr, bytes)\n\n # first transfer in RAM\n self.target.writeBlockMemoryUnaligned8(self.begin_data, bytes)\n\n # update core register to execute the program_page subroutine\n self.updateCoreRegister(flashPtr, self.page_size, self.begin_data, 0, self.flash_algo['pc_program_page'])\n\n # resume and wait until the breakpoint is hit\n self.target.resume()\n while(self.target.getState() == TARGET_RUNNING):\n pass\n\n # check the return code\n result = self.target.readCoreRegister('r0')\n if result != 0:\n logging.error('programPage error: %i', result)\n\n return\n\n def getPageInfo(self, addr):\n \"\"\"\n Get info about the page that contains this address\n\n Override this function if variable page sizes are supported\n \"\"\"\n info = PageInfo()\n info.erase_weight = DEFAULT_PAGE_ERASE_WEIGHT\n info.program_weight = DEFAULT_PAGE_PROGRAM_WEIGHT\n info.size = self.flash_algo['page_size']\n return info\n\n def getFlashInfo(self):\n \"\"\"\n Get info about the flash\n\n Override this function to return differnt values\n \"\"\"\n info = FlashInfo()\n info.rom_start = 0\n info.erase_weight = DEFAULT_CHIP_ERASE_WEIGHT\n info.crc_supported = self.flash_algo['analyzer_supported']\n return info\n\n def getFlashBuilder(self):\n return FlashBuilder(self, self.getFlashInfo().rom_start)\n\n def flashBlock(self, addr, data, smart_flash = True, chip_erase = None, progress_cb = None):\n \"\"\"\n Flash a block of data\n \"\"\"\n start = time()\n\n flash_start = self.getFlashInfo().rom_start\n fb = FlashBuilder(self, flash_start)\n fb.addData(addr, data)\n operation = fb.program(chip_erase, progress_cb, smart_flash)\n\n end = time()\n logging.debug(\"%f kbytes flashed in %f seconds ===> %f kbytes/s\" %(len(data)/1024, end-start, len(data)/(1024*(end - start))))\n return operation\n\n def flashBinary(self, path_file, flashPtr = 0x0000000, smart_flash = True, chip_erase = None, progress_cb = None):\n \"\"\"\n Flash a binary\n \"\"\"\n f = open(path_file, \"rb\")\n\n with open(path_file, \"rb\") as f:\n data = f.read()\n data = unpack(str(len(data)) + 'B', data)\n self.flashBlock(flashPtr, data, smart_flash, chip_erase, progress_cb)\n\n def updateCoreRegister(self, r0, r1, r2, r3, pc):\n self.target.writeCoreRegister('pc', pc)\n self.target.writeCoreRegister('r0', r0)\n self.target.writeCoreRegister('r1', r1)\n self.target.writeCoreRegister('r2', r2)\n self.target.writeCoreRegister('r3', r3)\n self.target.writeCoreRegister('r9', self.static_base)\n self.target.writeCoreRegister('sp', self.begin_stack)\n self.target.writeCoreRegister('lr', self.flash_algo['load_address'] + 1)\n return\n\n def overrideSecurityBits(self, address, data):\n return data\n","sub_path":"pyOCD/flash/flash.py","file_name":"flash.py","file_ext":"py","file_size_in_byte":9690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"360800244","text":"from abaqus import *\nfrom abaqusConstants import *\n\nwidth = 20.0\nheight = 5.0\norigin = (15.0, 0.0)\npitch = 50.0\nnumTurns = 2.0\n\ns = mdb.models['Model-1'].ConstrainedSketch(name='rect', sheetSize=200.0)\ng = s.geometry\ns.setPrimaryObject(option=STANDALONE)\ncl = s.ConstructionLine(point1=(0.0, -100.0), point2=(0.0, 100.0))\ns.FixedConstraint(entity=g[2])\ns.FixedConstraint(entity=g[cl.id])\ns.rectangle(point1=(origin[0], origin[1]), point2=(origin[0]+width, origin[1]+height))\n\np = mdb.models['Model-1'].Part(name='Part-1', dimensionality=THREE_D, \n type=DEFORMABLE_BODY)\np = mdb.models['Model-1'].parts['Part-1']\n\np.BaseSolidRevolve(sketch=s, angle=numTurns*360.0, flipRevolveDirection=OFF, \n pitch=pitch, flipPitchDirection=OFF, moveSketchNormalToPath=OFF) \n #In above command try changing the following member: moveSketchNormalToPath=ON\n\ns.unsetPrimaryObject()\n\nsession.viewports['Viewport: 1'].setValues(displayedObject=p)","sub_path":"Abaqus_Input_Script.py","file_name":"Abaqus_Input_Script.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"12907522","text":"\"\"\"\r\n输入学生考试成绩计算平均分\r\n\r\n\"\"\"\r\n\r\n\r\ndef main():\r\n\tnum = int(input('请输入学生人数:'))\r\n\tnames = [None] * num\r\n\tscores = [None] * num\r\n\tfor index in range(len(names)):\r\n\t\tnames[index] = input('请输入第%d个学生的名字: ' % (index+1))\r\n\t\tscores[index] = float(input('请输入第%d个学生的成绩: ' % (index+1)))\r\n\ttotal = 0 \r\n\tfor index in range(len(names)):\r\n\t\tprint('%s:%d' % (names[index], scores[index]))\r\n\t\ttotal += scores[index]\r\n\r\n\tprint('学生的平均成绩%.1f分' % (total/num))\r\n\r\nif __name__ == '__main__':\r\n\tprint(main())","sub_path":"python_exercise/project/基础练手/列表 字典/score.py","file_name":"score.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"557245079","text":"from django.http import HttpResponse\nimport cv2 \nimport numpy as np \nimport face_recognition\nimport datetime\nimport time\nfrom django.shortcuts import render\nfrom .forms import *\nfrom .models import Student,AttendanceTable\nimport os\n\ndef index(request):\n\tpath=\"attendance/images\"+\"college_pic.jpg\"\n\tprint(path)\n\treturn render(request,\"attendance/index.html\",{'path':path})\n\ndef registerStudent(request):\n\tif request.method == 'POST':\n\t\tform = RegistrationForm(request.POST, request.FILES)\n\t\tif form.is_valid():\n\t\t\tname = form.cleaned_data['name']\n\t\t\tdob = form.cleaned_data['dob']\n\t\t\tdepartment = form.cleaned_data['department']\n\t\t\tsemester = form.cleaned_data['semester']\n\t\t\troll_no = form.cleaned_data['roll_no']\n\t\t\temail = form.cleaned_data['email']\n\t\t\tphoto = form.cleaned_data['photo']\n\t\t\tform.save()\t\n\t\t\tstudents = Student.objects.all()\n\t\t\trecords = {}\n\t\t\tfor i in range(len(students)):\n\t\t\t\tt = students[i]\n\t\t\t\trecords[i+1]={'roll':t.roll_no,'name':t.name,'department':t.department,'semester':t.semester}\n\t\t\treturn render(request,\"attendance/show_student.html\",{'context':records})\n\telse:\n\t\tform = RegistrationForm()\n\treturn render(request, 'attendance/registration.html', {'form' : form})\n\n\ndef markAttendance(request):\n\tstudents = Student.objects.all()\n\timages = []\n\timagesNames = []\n\timagesRoll = []\n\twindow_width = 450\n\twindow_height = 450\n\tpath = os.getcwd()\n\tfor s in students:\n\t\tsurl = s.photo.url\n\t\tname = s.name\n\t\troll = s.roll_no\n\t\timg = cv2.imread(path+\"/\"+surl)\n\t\timages.append(img)\n\t\timagesNames.append(name)\n\t\timagesRoll.append(roll)\n\n\t\n\tdef findEncodings(imagesList):\n\t\tencodedList = []\n\t\tfor img in imagesList:\n\t\t\timg = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)\n\t\t\tenc = face_recognition.face_encodings(img)[0]\n\t\t\tencodedList.append(enc)\n\t\t\tprint(\"Encoding in progress\")\n\t\treturn encodedList\n\tencodeListKnown = findEncodings(images)\n\tcap = cv2.VideoCapture(0)\n\tFlag = True\n\tmarkedFlag = False\n\tname = None\n\twhile Flag:\n\t\tsuccess, img = cap.read()\n\t\t#reduce size of image - scale .25,0.25, 1/4th of image\n\t\timgS = cv2.resize(img,(0,0),None,0.25,0.25)\n\t\timgS = cv2.cvtColor(imgS,cv2.COLOR_BGR2RGB)\n\t\tcv2.putText(img,\"Press ESC to Close\",(100,100),cv2.FONT_HERSHEY_COMPLEX,1,(255,0,0),2)\n\t\t#in web cam we can see many faces so find the loc of faces\n\t\tfacesCurFrame = face_recognition.face_locations(imgS)\n\t\tencodesCurFrame = face_recognition.face_encodings(imgS,facesCurFrame)\n\n\n\t\tfor encodeFace,faceLoc in zip(encodesCurFrame,facesCurFrame):\n\t\t\tmatches = face_recognition.compare_faces(encodeListKnown,encodeFace)\n\t\t\t#faceDis give distance of all the known face from web face\n\t\t\tfaceDis = face_recognition.face_distance(encodeListKnown,encodeFace)\n\t\t\tprint(faceDis)\n\t\t\t#index of min face\n\t\t\tmatchIndex = np.argmin(faceDis)\n\t\t\tif matches[matchIndex]:\n\t\t\t\tname = imagesNames[matchIndex].upper()\n\t\t\t\troll= imagesRoll[matchIndex]\n\t\t\t\ty1,x2,y2,x1 = faceLoc\n\t\t\t\ty1 *=4\n\t\t\t\tx1 *=4\n\t\t\t\ty2 *=4\n\t\t\t\tx2 *=4\n\t\t\t\t#scale up face loc\n\t\t\t\tcv2.rectangle(img,(x1,y1),(x2,y2),(0,255,0),2)\n\t\t\t\tcv2.rectangle(img,(x1,y2-35),(x2,y2),(0,255,0),cv2.FILLED)\n\t\t\t\tcv2.putText(img,\"Mr \"+name,(x1+6,y2-6),cv2.FONT_HERSHEY_COMPLEX,1,(255,0,0),2)\n\t\t\t\t\n\t\t\t\tcurStudent = Student.objects.get(pk=roll)\n\t\t\t\tif not AttendanceTable.objects.filter(student__roll_no = roll,date__day=datetime.date.today().day):\n\t\t\t\t\tb = AttendanceTable(date =datetime.date.today() ,time=datetime.datetime.now().time(),student=curStudent)\n\t\t\t\t\tb.save()\n\t\t\t\t\tmarkedFlag = 1\n\t\t\t\tif markedFlag:\n\t\t\t\t\tcv2.rectangle(img,(x1,y1),(x2,y2),(0,255,0),2)\n\t\t\t\t\tcv2.rectangle(img,(x1,y2-35),(x2,y2),(0,255,0),cv2.FILLED)\n\t\t\t\t\tcv2.putText(img,\"Mr \"+name,(x1+6,y2-6),cv2.FONT_HERSHEY_COMPLEX,1,(255,0,0),2)\n\t\t\t\t\tcv2.putText(img,\"Attendance Marked for Mr \"+name,(x1+6,y2-56),cv2.FONT_HERSHEY_COMPLEX,1,(255,0,255),2)\n\t\t\t\t\tFlag = 0\n\t\t\t\t\ttime.sleep(2)\n\t\t\t\t\tcap.release()\n\t\t\t\t\tcv2.destroyAllWindows()\n\t\t\t\t\treturn render(request,\"attendance/index.html\",{'name':name})\n\t\t\t\t# cv2.resizeWindow('Resized Window', window_width, window_height)\n\t\tcv2.imshow('Webcam',img)\n\t\tk = cv2.waitKey(1)\n\t\tif k%256 == 27:\n\t\t\tFlag = 0\n\t\t\tcap.release()\n\t\t\tcv2.destroyAllWindows()\n\t\t\treturn render(request,\"attendance/index.html\",{'name':name})\n\n\ndef showStudentList(request):\n\tstudents = Student.objects.all()\n\trecords = {}\n\tfor i in range(len(students)):\n\t\tt = students[i]\n\t\trecords[i+1]={'roll':t.roll_no,'name':t.name,'department':t.department,'semester':t.semester}\n\treturn render(request,\"attendance/show_student.html\",{'context':records})\n\ndef getStudentByID(request,id):\n\tdaysAttended = AttendanceTable.objects.filter(student__roll_no = id)\n\t\n\tctx = {\n\t\t\t\t\n\t\t\t'student': Student.objects.get(pk=id),\n\t\t}\n\tif daysAttended:\n\t\tctx['daysattended'] = len(daysAttended)\n\treturn render(request,\"attendance/display_student.html\",ctx)\n\ndef showAttendanceRecord(request):\n\tattendance = AttendanceTable.objects.all()\n\trecords = {}\n\tfor rec in range(len(attendance)):\n\t\tt = attendance[rec]\n\t\trecords[rec+1]={'date':t.date,'time':t.time,'roll':t.student.roll_no,'name':t.student.name,'department':t.student.department}\n\tprint(records)\n\treturn render(request,\"attendance/attendance_record.html\",{\"context\":records})","sub_path":"attendance/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"67537353","text":"from __future__ import annotations\n\nimport logging\nimport ssl\nimport sys\nfrom pathlib import Path\n\nimport anyio\nimport anyio.abc\nimport paho.mqtt.client as mqtt\nimport pytest\n\nfrom asyncio_mqtt import Client, ProtocolVersion, TLSParameters, Topic, Wildcard, Will\nfrom asyncio_mqtt.types import PayloadType\n\npytestmark = pytest.mark.anyio\n\nHOSTNAME = \"test.mosquitto.org\"\nOS_PY_VERSION = sys.platform + \"_\" + \".\".join(map(str, sys.version_info[:2]))\nTOPIC_HEADER = OS_PY_VERSION + \"/tests/asyncio_mqtt/\"\n\n\nasync def test_topic_validation() -> None:\n \"\"\"Test that Topic raises Exceptions for invalid topics.\"\"\"\n with pytest.raises(TypeError):\n Topic(True) # type: ignore[arg-type]\n with pytest.raises(TypeError):\n Topic(1.0) # type: ignore[arg-type]\n with pytest.raises(TypeError):\n Topic(None) # type: ignore[arg-type]\n with pytest.raises(TypeError):\n Topic([]) # type: ignore[arg-type]\n with pytest.raises(ValueError, match=\"Invalid topic: \"):\n Topic(\"a/b/#\")\n with pytest.raises(ValueError, match=\"Invalid topic: \"):\n Topic(\"a/+/c\")\n with pytest.raises(ValueError, match=\"Invalid topic: \"):\n Topic(\"#\")\n with pytest.raises(ValueError, match=\"Invalid topic: \"):\n Topic(\"\")\n with pytest.raises(ValueError, match=\"Invalid topic: \"):\n Topic(\"a\" * 65536)\n\n\nasync def test_wildcard_validation() -> None:\n \"\"\"Test that Wildcard raises Exceptions for invalid wildcards.\"\"\"\n with pytest.raises(TypeError):\n Wildcard(True) # type: ignore[arg-type]\n with pytest.raises(TypeError):\n Wildcard(1.0) # type: ignore[arg-type]\n with pytest.raises(TypeError):\n Wildcard(None) # type: ignore[arg-type]\n with pytest.raises(TypeError):\n Wildcard([]) # type: ignore[arg-type]\n with pytest.raises(ValueError, match=\"Invalid wildcard: \"):\n Wildcard(\"a/#/c\")\n with pytest.raises(ValueError, match=\"Invalid wildcard: \"):\n Wildcard(\"a/b+/c\")\n with pytest.raises(ValueError, match=\"Invalid wildcard: \"):\n Wildcard(\"a/b/#c\")\n with pytest.raises(ValueError, match=\"Invalid wildcard: \"):\n Wildcard(\"\")\n with pytest.raises(ValueError, match=\"Invalid wildcard: \"):\n Wildcard(\"a\" * 65536)\n\n\nasync def test_topic_matches() -> None:\n \"\"\"Test that Topic.matches() does and doesn't match some test wildcards.\"\"\"\n topic = Topic(\"a/b/c\")\n assert topic.matches(\"a/b/c\")\n assert topic.matches(\"a/+/c\")\n assert topic.matches(\"+/+/+\")\n assert topic.matches(\"+/#\")\n assert topic.matches(\"#\")\n assert topic.matches(\"$share/group/a/b/c\")\n assert topic.matches(\"$share/group/a/b/+\")\n assert not topic.matches(\"abc\")\n assert not topic.matches(\"a/b\")\n assert not topic.matches(\"a/b/c/d\")\n assert not topic.matches(\"a/b/z\")\n assert not topic.matches(\"$share/a/b/c\")\n assert not topic.matches(\"$test/group/a/b/c\")\n\n\nasync def test_multiple_messages_generators() -> None:\n \"\"\"Test that multiple Client.messages() generators can be used at the same time.\"\"\"\n topic = TOPIC_HEADER + \"multiple_messages_generators\"\n\n async def handler(tg: anyio.abc.TaskGroup) -> None:\n async with client.messages() as messages:\n async for message in messages:\n assert str(message.topic) == topic\n tg.cancel_scope.cancel()\n\n async with Client(HOSTNAME) as client:\n async with anyio.create_task_group() as tg:\n await client.subscribe(topic)\n tg.start_soon(handler, tg)\n tg.start_soon(handler, tg)\n await anyio.wait_all_tasks_blocked()\n await client.publish(topic)\n\n\nasync def test_client_filtered_messages() -> None:\n topic_header = TOPIC_HEADER + \"filtered_messages/\"\n good_topic = topic_header + \"good\"\n bad_topic = topic_header + \"bad\"\n\n async def handle_messages(tg: anyio.abc.TaskGroup) -> None:\n async with client.filtered_messages(good_topic) as messages:\n async for message in messages:\n assert message.topic == good_topic\n tg.cancel_scope.cancel()\n\n async with Client(HOSTNAME) as client:\n async with anyio.create_task_group() as tg:\n await client.subscribe(topic_header + \"#\")\n tg.start_soon(handle_messages, tg)\n await anyio.wait_all_tasks_blocked()\n await client.publish(bad_topic, 2)\n await client.publish(good_topic, 2)\n\n\nasync def test_client_unfiltered_messages() -> None:\n topic_header = TOPIC_HEADER + \"unfiltered_messages/\"\n topic_filtered = topic_header + \"filtered\"\n topic_unfiltered = topic_header + \"unfiltered\"\n\n async def handle_unfiltered_messages(tg: anyio.abc.TaskGroup) -> None:\n async with client.unfiltered_messages() as messages:\n async for message in messages:\n assert message.topic == topic_unfiltered\n tg.cancel_scope.cancel()\n\n async def handle_filtered_messages() -> None:\n async with client.filtered_messages(topic_filtered) as messages:\n async for message in messages:\n assert message.topic == topic_filtered\n\n async with Client(HOSTNAME) as client:\n async with anyio.create_task_group() as tg:\n await client.subscribe(topic_header + \"#\")\n tg.start_soon(handle_filtered_messages)\n tg.start_soon(handle_unfiltered_messages, tg)\n await anyio.wait_all_tasks_blocked()\n await client.publish(topic_filtered, 2)\n await client.publish(topic_unfiltered, 2)\n\n\nasync def test_client_unsubscribe() -> None:\n topic_header = TOPIC_HEADER + \"unsubscribe/\"\n topic1 = topic_header + \"1\"\n topic2 = topic_header + \"2\"\n\n async def handle_messages(tg: anyio.abc.TaskGroup) -> None:\n async with client.unfiltered_messages() as messages:\n is_first_message = True\n async for message in messages:\n if is_first_message:\n assert message.topic == topic1\n is_first_message = False\n else:\n assert message.topic == topic2\n tg.cancel_scope.cancel()\n\n async with Client(HOSTNAME) as client:\n async with anyio.create_task_group() as tg:\n await client.subscribe(topic1)\n await client.subscribe(topic2)\n tg.start_soon(handle_messages, tg)\n await anyio.wait_all_tasks_blocked()\n await client.publish(topic1, 2)\n await client.unsubscribe(topic1)\n await client.publish(topic1, 2)\n await client.publish(topic2, 2)\n\n\n@pytest.mark.parametrize(\n \"protocol, length\",\n [(ProtocolVersion.V31, 22), (ProtocolVersion.V311, 0), (ProtocolVersion.V5, 0)],\n)\nasync def test_client_id(protocol: ProtocolVersion, length: int) -> None:\n client = Client(HOSTNAME, protocol=protocol)\n assert len(client.id) == length\n\n\nasync def test_client_will() -> None:\n topic = TOPIC_HEADER + \"will\"\n event = anyio.Event()\n\n async def launch_client() -> None:\n with anyio.CancelScope(shield=True) as cs:\n async with Client(HOSTNAME) as client:\n await client.subscribe(topic)\n event.set()\n async with client.filtered_messages(topic) as messages:\n async for message in messages:\n assert message.topic == topic\n cs.cancel()\n\n async with anyio.create_task_group() as tg:\n tg.start_soon(launch_client)\n await event.wait()\n async with Client(HOSTNAME, will=Will(topic)) as client:\n client._client._sock_close() # type: ignore[attr-defined]\n\n\nasync def test_client_tls_context() -> None:\n topic = TOPIC_HEADER + \"tls_context\"\n\n async def handle_messages(tg: anyio.abc.TaskGroup) -> None:\n async with client.filtered_messages(topic) as messages:\n async for message in messages:\n assert message.topic == topic\n tg.cancel_scope.cancel()\n\n async with Client(\n HOSTNAME,\n 8883,\n tls_context=ssl.SSLContext(protocol=ssl.PROTOCOL_TLS),\n ) as client:\n async with anyio.create_task_group() as tg:\n await client.subscribe(topic)\n tg.start_soon(handle_messages, tg)\n await anyio.wait_all_tasks_blocked()\n await client.publish(topic)\n\n\nasync def test_client_tls_params() -> None:\n topic = TOPIC_HEADER + \"tls_params\"\n\n async def handle_messages(tg: anyio.abc.TaskGroup) -> None:\n async with client.filtered_messages(topic) as messages:\n async for message in messages:\n assert message.topic == topic\n tg.cancel_scope.cancel()\n\n async with Client(\n HOSTNAME,\n 8883,\n tls_params=TLSParameters(\n ca_certs=str(Path.cwd() / \"tests\" / \"mosquitto.org.crt\")\n ),\n ) as client:\n async with anyio.create_task_group() as tg:\n await client.subscribe(topic)\n tg.start_soon(handle_messages, tg)\n await anyio.wait_all_tasks_blocked()\n await client.publish(topic)\n\n\nasync def test_client_username_password() -> None:\n topic = TOPIC_HEADER + \"username_password\"\n\n async def handle_messages(tg: anyio.abc.TaskGroup) -> None:\n async with client.filtered_messages(topic) as messages:\n async for message in messages:\n assert message.topic == topic\n tg.cancel_scope.cancel()\n\n async with Client(HOSTNAME, username=\"\", password=\"\") as client:\n async with anyio.create_task_group() as tg:\n await client.subscribe(topic)\n tg.start_soon(handle_messages, tg)\n await anyio.wait_all_tasks_blocked()\n await client.publish(topic)\n\n\nasync def test_client_logger() -> None:\n logger = logging.getLogger(\"asyncio-mqtt\")\n async with Client(HOSTNAME, logger=logger) as client:\n assert logger is client._client._logger # type: ignore[attr-defined]\n\n\nasync def test_client_max_concurrent_outgoing_calls(\n monkeypatch: pytest.MonkeyPatch,\n) -> None:\n topic = TOPIC_HEADER + \"max_concurrent_outgoing_calls\"\n\n class MockPahoClient(mqtt.Client):\n def subscribe(\n self,\n topic: str\n | tuple[str, mqtt.SubscribeOptions]\n | list[tuple[str, mqtt.SubscribeOptions]]\n | list[tuple[str, int]],\n qos: int = 0,\n options: mqtt.SubscribeOptions | None = None,\n properties: mqtt.Properties | None = None,\n ) -> tuple[int, int]:\n assert client._outgoing_calls_sem is not None\n assert client._outgoing_calls_sem.locked()\n return super().subscribe(topic, qos, options, properties)\n\n def unsubscribe(\n self, topic: str | list[str], properties: mqtt.Properties | None = None\n ) -> tuple[int, int]:\n assert client._outgoing_calls_sem is not None\n assert client._outgoing_calls_sem.locked()\n return super().unsubscribe(topic, properties)\n\n def publish( # noqa: PLR0913\n self,\n topic: str,\n payload: PayloadType | None = None,\n qos: int = 0,\n retain: bool = False,\n properties: mqtt.Properties | None = None,\n ) -> mqtt.MQTTMessageInfo:\n assert client._outgoing_calls_sem is not None\n assert client._outgoing_calls_sem.locked()\n return super().publish(topic, payload, qos, retain, properties)\n\n monkeypatch.setattr(mqtt, \"Client\", MockPahoClient)\n\n async with Client(HOSTNAME, max_concurrent_outgoing_calls=1) as client:\n await client.subscribe(topic)\n await client.unsubscribe(topic)\n await client.publish(topic)\n\n\nasync def test_client_websockets() -> None:\n topic = TOPIC_HEADER + \"websockets\"\n\n async def handle_messages(tg: anyio.abc.TaskGroup) -> None:\n async with client.filtered_messages(topic) as messages:\n async for message in messages:\n assert message.topic == topic\n tg.cancel_scope.cancel()\n\n async with Client(\n HOSTNAME,\n 8080,\n transport=\"websockets\",\n websocket_path=\"/\",\n websocket_headers={\"foo\": \"bar\"},\n ) as client:\n async with anyio.create_task_group() as tg:\n await client.subscribe(topic)\n tg.start_soon(handle_messages, tg)\n await anyio.wait_all_tasks_blocked()\n await client.publish(topic)\n\n\n@pytest.mark.parametrize(\"pending_calls_threshold\", [10, 20])\nasync def test_client_pending_calls_threshold(\n pending_calls_threshold: int, caplog: pytest.LogCaptureFixture\n) -> None:\n topic = TOPIC_HEADER + \"pending_calls_threshold\"\n\n async with Client(HOSTNAME) as client:\n client.pending_calls_threshold = pending_calls_threshold\n nb_publish = client.pending_calls_threshold + 1\n\n async with anyio.create_task_group() as tg:\n for _ in range(nb_publish):\n tg.start_soon(client.publish, topic)\n\n assert caplog.record_tuples == [\n (\n \"mqtt\",\n logging.WARNING,\n f\"There are {nb_publish} pending publish calls.\",\n )\n ]\n\n\n@pytest.mark.parametrize(\"pending_calls_threshold\", [10, 20])\nasync def test_client_no_pending_calls_warnings_with_max_concurrent_outgoing_calls(\n pending_calls_threshold: int,\n caplog: pytest.LogCaptureFixture,\n) -> None:\n topic = (\n TOPIC_HEADER + \"no_pending_calls_warnings_with_max_concurrent_outgoing_calls\"\n )\n\n async with Client(HOSTNAME, max_concurrent_outgoing_calls=1) as client:\n client.pending_calls_threshold = pending_calls_threshold\n nb_publish = client.pending_calls_threshold + 1\n\n async with anyio.create_task_group() as tg:\n for _ in range(nb_publish):\n tg.start_soon(client.publish, topic)\n\n assert caplog.record_tuples == []\n","sub_path":"tests/test_client.py","file_name":"test_client.py","file_ext":"py","file_size_in_byte":14093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"72190283","text":"import netket as nk\nimport numpy as np\nimport Individual\nimport geneticMain\n\n\n\nclass Population():\n\n def __init__(self, list_of_individuals: [Individual]):\n self.__list_of_individuals = list_of_individuals\n self.__generation = 0\n\n @staticmethod\n def create_random_population():\n list_of_individuals = []\n for _ in range(geneticMain.POPULATION_SIZE):\n list_of_individuals.append(Individual.Individual.random_individual())\n random_population = Population(list_of_individuals=list_of_individuals)\n return random_population\n\n @staticmethod\n def create_all():\n possibilities = 2**geneticMain.BIT_LENGTH_CHROMOSOME\n list_of_individuals = []\n for i in range(possibilities):\n bit_string = format(i,\"0%db\" %(geneticMain.BIT_LENGTH_CHROMOSOME))\n list_of_individuals.append(Individual.Individual(bit_string))\n if nk.MPI.rank() == 0:\n print(\"%s created\" %(bit_string))\n\n @staticmethod\n def two_point_crossover(parent1: Individual, parent2: Individual):\n bit_length_chromosome = geneticMain.BIT_LENGTH_CHROMOSOME\n crossover_prob = geneticMain.CROSSOVER_PROP\n parent_1_genes = parent1.give_genes().bin\n parent_2_genes = parent2.give_genes().bin\n\n if (crossover_prob > np.random.rand()):\n first_co_point = np.random.randint(0, bit_length_chromosome)\n second_co_point = np.random.randint(0, bit_length_chromosome)\n if (first_co_point > second_co_point):\n temp = first_co_point\n first_co_point = second_co_point\n second_co_point = temp\n\n parent_1_genes_cutted = [parent_1_genes[0:first_co_point], parent_1_genes[first_co_point:second_co_point],\n parent_1_genes[second_co_point:]]\n parent_2_genes_cutted = [parent_2_genes[0:first_co_point], parent_2_genes[first_co_point:second_co_point],\n parent_2_genes[second_co_point:]]\n\n genes_offspring_1 = parent_1_genes_cutted[0]\n genes_offspring_1 += parent_2_genes_cutted[1]\n genes_offspring_1 += parent_1_genes_cutted[2]\n\n genes_offspring_2 = parent_2_genes_cutted[0]\n genes_offspring_2 += parent_1_genes_cutted[1]\n genes_offspring_2 += parent_2_genes_cutted[2]\n\n return True, Individual.Individual(genes_offspring_1), Individual.Individual(genes_offspring_2)\n else:\n return False, parent1, parent2\n\n def print_genes(self):\n if (nk.MPI.rank() == 0):\n sum_fitness = 0\n print(\"generation \" + str(self.__generation))\n for counter, indiv in enumerate(self.__list_of_individuals):\n print(str(counter)+\": \" + \"genome: \" +str(indiv.give_genes().bin) + \" fitness: \" + str(indiv.give_fitness()))\n sum_fitness += indiv.give_fitness()\n print(\"sum fitness: \" + str(sum_fitness))\n fittest = self.give_fittest_individual()\n print(\"fittest genome: \" + str(fittest.give_genes().bin) + \" fitness: \" + str(fittest.give_fitness()))\n print(\"---------------------------------\")\n else:\n pass\n\n def sum_fitness(self):\n sum_fitness = 0\n for indiv in self.__list_of_individuals:\n sum_fitness += indiv.give_fitness()\n return sum_fitness\n\n def selection_tournament(self):\n population_size = geneticMain.POPULATION_SIZE\n mating_pool_size = geneticMain.POPULATION_SIZE\n tournament_size = geneticMain.TOURNAMENT_SIZE\n mating_pool = []\n for i in range(mating_pool_size):\n tournament_pool = []\n for _ in range(tournament_size):\n r = np.random.randint(0,population_size)\n tournament_pool.append(self.__list_of_individuals[r])\n fittest_indiv = tournament_pool[0]\n\n for indiv in tournament_pool: #find fittest individual in tournament pool\n if indiv.give_fitness() > fittest_indiv.give_fitness():\n fittest_indiv = indiv\n mating_pool.append(fittest_indiv)\n return mating_pool\n\n def new_generation(self):\n new_population_list = []\n mating_pool = self.selection_tournament()\n\n for _ in range(int(geneticMain.POPULATION_SIZE/2)):\n r1 = np.random.randint(0,len(mating_pool))\n r2 = np.random.randint(0,len(mating_pool))\n mated, new1, new2 = self.two_point_crossover(mating_pool[r1],mating_pool[r2])\n new_population_list.append(new1)\n new_population_list.append(new2)\n\n for indiv in new_population_list:\n indiv.mutate()\n\n self.__list_of_individuals = new_population_list\n self.__generation += 1\n\n def give_generation(self):\n return self.__generation\n\n def give_fittest_individual(self):\n fittest = self.__list_of_individuals[0]\n for indiv in self.__list_of_individuals:\n if indiv.give_fitness() > fittest.give_fitness():\n fittest = indiv\n\n return fittest\n","sub_path":"HeisenbergS1/Genetic/Population.py","file_name":"Population.py","file_ext":"py","file_size_in_byte":5199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"101445856","text":"N, K = map(int, input().split())\n\nif N == 0:\n exit(print(0))\n\ndef to_ten(num):\n ret = 0\n num_str = str(num)\n for s in num_str:\n ret += int(s)\n ret *= 8\n ret //= 8\n\n return ret\n\n\ndef nineth_adic(num):\n ret = \"\"\n while num:\n num, rem = num//9, num%9\n ret += str(rem)\n\n return ret[::-1]\n\ndef eight_to_five(num_st):\n num_st = num_st.replace(\"8\", \"5\")\n return int(num_st)\n\nfor _ in range(K):\n N = to_ten(N)\n N = nineth_adic(N)\n N = eight_to_five(N)\n\nprint(N)\n","sub_path":"pysol/067.py","file_name":"067.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"553786772","text":"#!/usr/bin/env python3\n\n# from datetime import datetime\nimport argparse\nimport logging\nimport os\nimport subprocess\nimport sys\n\n# from typing import Dict\nfrom typing import Optional\nfrom typing import List\nfrom typing import Sequence\nfrom typing import TextIO\nfrom typing import Any\nfrom typing import Union\nfrom typing import cast\nfrom dataclasses import dataclass, field\n\n_header = \"\"\"\n -`\n ... .o+`\n .+++s+ .h`. `ooo/\n`+++%++ .h+++ `+oooo:\n+++o+++ .hhs++. `+oooooo:\n+s%%so%.hohhoo' 'oooooo+:\n`+ooohs+h+sh++`/: ++oooo+:\n hh+o+hoso+h+`/++++.+++++++:\n `+h+++h.+ `/++++++++++++++:\n `/+++ooooooooooooo/`\n ./ooosssso++osssssso+`\n .oossssso-````/osssss::`\n -osssssso. :ssss``to.\n :osssssss/ Mike osssl +\n /ossssssss/ 8a +sssslb\n `/ossssso+/:- -:/+ossss'.-\n `+sso+:-` `.-/+oso:\n `++:. `-/+/\n .` `/\n\"\"\"\n\n_VERSION = \"0.1.0\"\n_AUTHOR = \"Mike\"\n\n_log: logging.Logger\n# _SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))\n_SCRIPTNAME = os.path.basename(__file__)\n_log_file: Optional[str] = os.path.splitext(_SCRIPTNAME)[0] + \".log\"\n\n_verbose = False\n# _is_windows = os.name == 'nt'\n# _home = os.environ['USERPROFILE' if _is_windows else 'HOME']\n\n\n@dataclass\nclass Job(object):\n \"\"\"docstring for Job\"\"\"\n\n cmd: Sequence[str]\n stdout: List[str] = field(init=False, repr=False)\n stderr: List[str] = field(init=False, repr=False)\n pid: int = field(init=False)\n rc: int = field(init=False)\n\n # # NOTE: Needed it with python < 3.7\n # def __init__(self, cmd: Sequence[str]):\n # \"\"\"Create a shell command wrapper\n #\n # Args:\n # cmd (Sequence[str]): command with its arguments, first element must\n # be and executable or a path to the executable\n # \"\"\"\n # self.cmd = cmd\n\n def head(self, size: int = 10) -> List[str]:\n \"\"\"Emulate head shell util\n\n Args:\n size (int): first N elements of the stdout\n\n Returns:\n List of string with the first N elements\n \"\"\"\n if size <= 0:\n raise Exception(\"Size cannot be less than 0\")\n return self.stdout[0:size]\n\n def tail(self, size: int = 10) -> List[str]:\n \"\"\"Emulate tail shell util\n\n Args:\n size (int): last N elements of the stdout\n\n Returns:\n List of string with the last N elements\n \"\"\"\n if size <= 0:\n raise Exception(\"Size cannot be less than 0\")\n return self.stdout[::-1][0:size]\n\n def execute(self, background: bool = True, cwd: Optional[str] = None) -> int:\n \"\"\"Execute the cmd\n\n Args:\n background (bool): execute as async process\n cwd (Optional[str]): path where the cmd is execute, default to CWD\n\n Returns:\n Return-code integer of the cmd\n \"\"\"\n # Verbose always overrides background output\n background = background if not _verbose else False\n cwd = \".\" if cwd is None else cwd\n\n _log.debug(f\"Executing cmd: {self.cmd}\")\n _log.debug(\"Sending job to background\" if background else \"Running in foreground\")\n process = subprocess.Popen(self.cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, cwd=cwd)\n self.pid = process.pid\n\n self.stdout = []\n self.stderr = []\n\n while True:\n stdout = cast(TextIO, process.stdout).readline()\n stderr = cast(TextIO, process.stderr).readline()\n if (stdout == \"\" and stderr == \"\") and process.poll() is not None:\n break\n elif stdout:\n stdout = stdout.strip().replace(\"\\n\", \"\")\n self.stdout.append(stdout)\n if background:\n _log.debug(stdout)\n else:\n _log.info(stdout)\n elif stderr:\n stderr = stderr.strip().replace(\"\\n\", \"\")\n self.stderr.append(stderr)\n _log.error(stderr)\n\n # self.rc = process.poll()\n self.rc = process.returncode\n\n if self.rc != 0:\n _log.error(f\"Command exited with {self.rc}\")\n\n if self.stdout is not None and len(self.stdout) > 0:\n _log.debug(f\"stdout: {self.stdout}\")\n\n if self.stderr is not None and len(self.stderr) > 0:\n _log.error(f\"stderr: {self.stderr}\")\n\n return self.rc\n\n\ndef createLogger(\n stdout_level: int = logging.INFO,\n file_level: int = logging.DEBUG,\n color: bool = True,\n filename: Optional[str] = \"dummy.log\",\n name: str = \"MainLogger\",\n):\n \"\"\"Creaters logging obj\n\n Args:\n stdout_level: logging level displayed into the terminal\n file_level: logging level saved into the logging file\n color: Enable/Disable color console output\n\n Returns:\n Logger with file and tty handlers\n\n \"\"\"\n logger = logging.getLogger(name)\n logger.setLevel(logging.DEBUG)\n\n ColorFormatter: Any = None\n Formatter: Any = None\n try:\n from colorlog import ColoredFormatter\n\n Formatter = ColoredFormatter\n ColorFormatter = ColoredFormatter\n except ImportError:\n\n class PrimitiveFormatter(logging.Formatter):\n \"\"\"Logging colored formatter, adapted from https://stackoverflow.com/a/56944256/3638629\"\"\"\n\n def __init__(self, fmt, log_colors=None):\n super().__init__()\n self.fmt = fmt\n\n colors = {\n \"grey\": \"\\x1b[38;21m\",\n \"green\": \"\\x1b[32m\",\n \"magenta\": \"\\x1b[35m\",\n \"purple\": \"\\x1b[35m\",\n \"blue\": \"\\x1b[38;5;39m\",\n \"yellow\": \"\\x1b[38;5;226m\",\n \"red\": \"\\x1b[38;5;196m\",\n \"bold_red\": \"\\x1b[31;1m\",\n \"reset\": \"\\x1b[0m\",\n }\n\n if log_colors is None:\n log_colors = {}\n\n log_colors[\"DEBUG\"] = log_colors[\"DEBUG\"] if \"DEBUG\" in log_colors else \"magenta\"\n log_colors[\"INFO\"] = log_colors[\"INFO\"] if \"INFO\" in log_colors else \"green\"\n log_colors[\"WARNING\"] = log_colors[\"WARNING\"] if \"WARNING\" in log_colors else \"yellow\"\n log_colors[\"ERROR\"] = log_colors[\"ERROR\"] if \"ERROR\" in log_colors else \"red\"\n log_colors[\"CRITICAL\"] = log_colors[\"CRITICAL\"] if \"CRITICAL\" in log_colors else \"bold_red\"\n\n self.FORMATS = {\n logging.DEBUG: colors[log_colors[\"DEBUG\"]] + self.fmt + colors[\"reset\"],\n logging.INFO: colors[log_colors[\"INFO\"]] + self.fmt + colors[\"reset\"],\n logging.WARNING: colors[log_colors[\"WARNING\"]] + self.fmt + colors[\"reset\"],\n logging.ERROR: colors[log_colors[\"ERROR\"]] + self.fmt + colors[\"reset\"],\n logging.CRITICAL: colors[log_colors[\"CRITICAL\"]] + self.fmt + colors[\"reset\"],\n }\n\n def format(self, record):\n log_fmt = self.FORMATS.get(record.levelno)\n formatter = logging.Formatter(log_fmt)\n return formatter.format(record)\n\n Formatter = PrimitiveFormatter\n\n # This means both 0 and 100 silence all output\n stdout_level = 100 if stdout_level == 0 else stdout_level\n\n has_color = ColorFormatter is not None and color\n\n stdout_handler = logging.StreamHandler(sys.stdout)\n stdout_handler.setLevel(stdout_level)\n logformat = \"{color}%(levelname)-8s | %(message)s\"\n logformat = logformat.format(\n color=\"%(log_color)s\" if has_color else \"\",\n # reset='%(reset)s' if has_color else '',\n )\n stdout_format = Formatter(\n logformat,\n log_colors={\n \"DEBUG\": \"purple\",\n \"INFO\": \"green\",\n \"WARNING\": \"yellow\",\n \"ERROR\": \"red\",\n \"CRITICAL\": \"red\",\n },\n )\n stdout_handler.setFormatter(stdout_format)\n\n logger.addHandler(stdout_handler)\n\n if file_level > 0 and file_level < 100 and filename is not None:\n\n with open(filename, \"a\") as log:\n log.write(_header)\n # log.write(f'\\nDate: {datetime.datetime.date()}')\n log.write(f\"\\nAuthor: {_AUTHOR}\\nVersion: {_VERSION}\\n\\n\")\n\n file_handler = logging.FileHandler(filename=filename)\n file_handler.setLevel(file_level)\n file_format = logging.Formatter(\"%(levelname)-8s | %(filename)s: [%(funcName)s] - %(message)s\")\n file_handler.setFormatter(file_format)\n\n logger.addHandler(file_handler)\n\n return logger\n\n\ndef _str_to_logging(level: Union[int, str]) -> int:\n \"\"\"Convert logging level string to a logging number\n\n Args:\n level: integer representation or a valid logging string\n - debug/verbose\n - info\n - warn/warning\n - error\n - critical\n All non valid integer or logging strings defaults to 0 logging\n\n Returns:\n logging level of the given string\n \"\"\"\n\n if isinstance(level, int):\n level = abs(level - 100)\n elif isinstance(level, str):\n try:\n level = abs(int(level) - 100)\n except Exception:\n level = cast(str, level).lower()\n if level == \"debug\" or level == \"verbose\":\n level = logging.DEBUG\n elif level == \"info\":\n level = logging.INFO\n elif level == \"warn\" or level == \"warning\":\n level = logging.WARN\n elif level == \"error\":\n level = logging.ERROR\n elif level == \"critical\":\n level = logging.CRITICAL\n else:\n level = 100\n\n return level\n\n\ndef _parseArgs():\n \"\"\"Parse CLI arguments\n\n Returns\n argparse.ArgumentParser class instance\n\n \"\"\"\n\n class NegateAction(argparse.Action):\n def __call__(self, parser, ns, values, option):\n global _protocol\n if len(option) == 2:\n setattr(ns, self.dest, True)\n else:\n setattr(ns, self.dest, option[2:4] != \"no\")\n\n class ChangeLogFile(argparse.Action):\n def __call__(self, parser, ns, values, option):\n if option[2:4] == \"no\":\n setattr(ns, self.dest, None)\n else:\n pass\n setattr(ns, self.dest, values)\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\n \"--color\",\n \"--nocolor\",\n \"--no-color\",\n dest=\"color\",\n action=NegateAction,\n default=True,\n nargs=0,\n help=\"Disable colored output\",\n )\n\n parser.add_argument(\n \"--log\",\n \"--nolog\",\n \"--no-log\",\n dest=\"logfile\",\n action=ChangeLogFile,\n default=_log_file,\n nargs=\"?\",\n type=str,\n help=\"Log filename or disable log file\",\n )\n\n parser.add_argument(\n \"--version\",\n dest=\"show_version\",\n action=\"store_true\",\n help=\"Print script version and exit\",\n )\n\n parser.add_argument(\n \"--verbose\",\n dest=\"verbose\",\n action=\"store_true\",\n default=False,\n help=\"Turn on console debug messages\",\n )\n\n parser.add_argument(\n \"--quiet\",\n dest=\"quiet\",\n action=\"store_true\",\n default=False,\n help=\"Turn off all console messages\",\n )\n\n parser.add_argument(\n \"-l\",\n \"--logging\",\n dest=\"stdout_logging\",\n default=\"info\",\n type=str,\n help=\"Console logger verbosity\",\n )\n\n parser.add_argument(\n \"-f\",\n \"--file-logging\",\n dest=\"file_logging\",\n default=\"debug\",\n type=str,\n help=\"File logger verbosity\",\n )\n\n return parser.parse_args()\n\n\ndef main():\n \"\"\"Main function\n\n Returns\n exit code, 0 in success any other integer in failure\n\n \"\"\"\n global _log\n\n args = _parseArgs()\n\n if args.show_version:\n print(f\"{_header}\\nAuthor: {_AUTHOR}\\nVersion: {_VERSION}\")\n return 0\n\n stdout_level = args.stdout_logging if not args.verbose else \"debug\"\n file_level = args.file_logging if not args.verbose else \"debug\"\n\n stdout_level = stdout_level if not args.quiet else 0\n file_level = file_level if not args.quiet else 0\n\n _log = createLogger(\n stdout_level=_str_to_logging(stdout_level),\n file_level=_str_to_logging(file_level),\n color=args.color,\n filename=args.logfile,\n )\n\n # _log.debug('This is a DEBUG message')\n # _log.info('This is a INFO message')\n # _log.warning('This is a WARNing message')\n # _log.error('This is a ERROR message')\n\n errors = 0\n try:\n pass\n except (Exception, KeyboardInterrupt) as e:\n _log.exception(f\"Halting due to {str(e.__class__.__name__)} exception\")\n errors = 1\n\n return errors\n\n\nif __name__ == \"__main__\":\n exit(main())\nelse:\n _log = createLogger(\n stdout_level=_str_to_logging(\"INFO\"),\n file_level=_str_to_logging(\"DEBUG\"),\n color=True,\n filename=_log_file,\n )\n","sub_path":"skeletons/skeleton.py","file_name":"skeleton.py","file_ext":"py","file_size_in_byte":13327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"435432320","text":"# -*- coding: utf-8 -*-\n\"\"\"General and basic API for models in HydroMT\"\"\"\n\nfrom abc import ABCMeta, abstractmethod\nimport os\nfrom os.path import join, isdir, isfile, abspath\nimport xarray as xr\nimport numpy as np\nimport geopandas as gpd\nfrom shapely.geometry import box\nimport logging\nfrom pathlib import Path\nimport inspect\n\nfrom ..data_adapter import DataCatalog\nfrom .. import config\n\n__all__ = [\"Model\"]\n\nlogger = logging.getLogger(__name__)\n\n\nclass Model(object, metaclass=ABCMeta):\n \"\"\"General and basic API for models in HydroMT\"\"\"\n\n # FIXME\n _DATADIR = \"\" # path to the model data folder\n _NAME = \"modelname\"\n _CONF = \"model.ini\"\n _CF = dict() # configreader kwargs\n _GEOMS = {\"\": \"\"}\n _MAPS = {\"\": \"\"}\n _FOLDERS = [\"\"]\n\n def __init__(\n self,\n root=None,\n mode=\"w\",\n config_fn=None,\n data_libs=None,\n deltares_data=None,\n artifact_data=None,\n logger=logger,\n ):\n from . import ENTRYPOINTS # load within method to avoid circular imports\n\n self.logger = logger\n ep = ENTRYPOINTS.get(self._NAME, None)\n version = ep.distro.version if ep is not None else \"\"\n dist = ep.distro.name if ep is not None else \"unknown\"\n self.logger.info(f\"Initializing {self._NAME} model from {dist} (v{version}).\")\n\n # link to data\n self.data_catalog = DataCatalog(\n data_libs=data_libs,\n deltares_data=deltares_data,\n artifact_data=artifact_data,\n logger=self.logger,\n )\n\n # placeholders\n self._staticmaps = xr.Dataset()\n self._staticgeoms = dict() # dictionnary of gdp.GeoDataFrame\n self._forcing = dict() # dictionnary of xr.DataArray\n self._config = dict() # nested dictionary\n self._states = dict() # dictionnary of xr.DataArray\n self._results = dict() # dictionnary of xr.DataArray and/or xr.Dataset\n\n # model paths\n self._config_fn = self._CONF if config_fn is None else config_fn\n self.set_root(root, mode)\n\n def _check_get_opt(self, opt):\n \"\"\"Check all opt keys and raise sensible error messages if unknonwn.\"\"\"\n for method in opt.keys():\n m = method.strip(\"0123456789\")\n if not callable(getattr(self, m, None)):\n if not hasattr(self, m) and hasattr(self, f\"setup_{m}\"):\n raise DeprecationWarning(\n f'Use full name \"setup_{method}\" instead of \"{method}\"'\n )\n else:\n raise ValueError(f'Model {self._NAME} has no method \"{method}\"')\n return opt\n\n def _run_log_method(self, method, *args, **kwargs):\n \"\"\"Log method paramters before running a method\"\"\"\n method = method.strip(\"0123456789\")\n func = getattr(self, method)\n signature = inspect.signature(func)\n for i, (k, v) in enumerate(signature.parameters.items()):\n v = kwargs.get(k, v.default)\n if v is inspect.Parameter.empty:\n if len(args) >= i + 1:\n v = args[i]\n else:\n continue\n self.logger.info(f\"{method}.{k}: {v}\")\n return func(*args, **kwargs)\n\n def build(\n self, region: dict, res: float = None, write: bool = True, opt: dict = None\n ):\n \"\"\"Single method to setup and write a full model schematization and\n configuration from scratch\n\n Parameters\n ----------\n region: dict\n Description of model region. See :py:meth:`~hydromt.workflows.parse_region`\n for all options.\n res: float, optional\n Model restolution. Use only if applicable to your model. By default None.\n write: bool, optional\n Write the complete model schematization after setting up all model components.\n By default True.\n opt: dict, optional\n Model setup configuration. This is a nested dictionary where the first-level\n keys are the names of model spedific setup methods and the second-level\n keys the arguments of the method:\n\n ```{\n : {\n : , : \n }\n : {\n ...\n }\n }\n }```\n \"\"\"\n opt = self._check_get_opt(opt)\n\n # run setup_config and setup_basemaps first!\n self._run_log_method(\"setup_config\", **opt.pop(\"setup_config\", {}))\n kwargs = opt.pop(\"setup_basemaps\", {})\n kwargs.update(region=region)\n\n if res is not None: # res is optional\n kwargs.update(res=res)\n self._run_log_method(\"setup_basemaps\", **kwargs)\n\n # then loop over other methods\n for method in opt:\n self._run_log_method(method, **opt[method])\n\n # write\n if write:\n self.write()\n\n def update(self, model_out=None, write=True, opt=None):\n \"\"\"Single method to setup and write a full model schematization and\n configuration from scratch\n\n\n Parameters\n ----------\n model_out: str, path, optional\n Desitation folder to write the model schematization after updating\n the model. If None the updated model components are overwritten in the\n current model schematization if these exist. By defualt None.\n write: bool, optional\n Write the updated model schematization to disk. By default True.\n opt: dict, optional\n Model update configuration. This is a nested dictionary where the first-level\n keys are the names of model spedific setup methods and the second-level\n keys the arguments of the method:\n\n ```{\n : {\n : , : \n }\n : {\n ...\n }\n }```\n \"\"\"\n opt = self._check_get_opt(opt)\n\n # read current model\n if not self._write:\n if model_out is None:\n raise ValueError(\n '\"model_out\" directory required when updating in \"read-only\" mode'\n )\n self.read()\n self.set_root(model_out, mode=\"w\")\n\n # check if model has a region\n if self.region is None:\n raise ValueError(\n 'Model region not found, setup basemaps using \"build\" method first.'\n )\n\n # remove setup_basemaps from options and throw warning\n if \"setup_basemaps\" in opt:\n opt.pop(\"setup_basemaps\") # remove from opt\n self.logger.warning(\n '\"setup_basemaps\" can only be called when building a model.'\n )\n\n # loop over other methods from ini file\n self._run_log_method(\"setup_config\", **opt.pop(\"setup_config\", {}))\n for method in opt:\n self._run_log_method(method, **opt[method])\n\n # write\n if write:\n self.write()\n\n ## file system\n\n @property\n def root(self):\n \"\"\"Path to model folder.\"\"\"\n if self._root is None:\n raise ValueError(\"Root unknown, use set_root method\")\n return self._root\n\n def set_root(self, root, mode=\"w\"):\n \"\"\"Initialized the model root.\n In read mode it checks if the root exists.\n In write mode in creates the required model folder structure\n\n Parameters\n ----------\n root : str, optional\n path to model root\n mode : {\"r\", \"r+\", \"w\"}, optional\n read/write-only mode for model files\n \"\"\"\n if mode not in [\"r\", \"r+\", \"w\"]:\n raise ValueError(f'mode \"{mode}\" unknown, select from \"r\", \"r+\" or \"w\"')\n old_root = getattr(self, \"_root\", None)\n self._root = root if root is None else abspath(root)\n self._read = mode.startswith(\"r\")\n self._write = mode != \"r\"\n if root is not None:\n if self._write:\n for name in self._FOLDERS:\n path = join(self._root, name)\n if not isdir(path):\n os.makedirs(path)\n elif not self._read:\n self.logger.warning(\n \"Model dir already exists and \"\n f\"files might be overwritten: {path}.\"\n )\n # check directory\n elif not isdir(self._root):\n raise IOError(f'model root not found at \"{self._root}\"')\n\n ## I/O\n\n @abstractmethod\n def read(self):\n \"\"\"Method to read the complete model schematization and configuration from file.\"\"\"\n self.read_config()\n self.read_staticmaps()\n\n @abstractmethod\n def write(self):\n \"\"\"Method to write the complete model schematization and configuration to file.\"\"\"\n self.write_config()\n self.write_staticmaps()\n\n def _configread(self, fn):\n return config.configread(fn, abs_path=False)\n\n def _configwrite(self, fn):\n return config.configwrite(fn, self.config)\n\n def read_config(self, config_fn=None):\n \"\"\"Parse config from file. If no config file found a default config file is\n read in writing mode.\"\"\"\n prefix = \"User defined\"\n if config_fn is None: # prioritize user defined config path (new v0.4.1)\n if not self._read: # write-only mode > read default config\n config_fn = join(self._DATADIR, self._NAME, self._CONF)\n prefix = \"Default\"\n elif self.root is not None: # append or write mode > read model config\n config_fn = join(self.root, self._config_fn)\n prefix = \"Model\"\n cfdict = dict()\n if config_fn is not None:\n if isfile(config_fn):\n cfdict = self._configread(config_fn)\n self.logger.debug(f\"{prefix} config read from {config_fn}\")\n else:\n self.logger.error(f\"{prefix} config file not found at {config_fn}\")\n self._config = cfdict\n\n def write_config(self, config_name=None, config_root=None):\n \"\"\"Write config to \"\"\"\n if not self._write:\n raise IOError(\"Model opened in read-only mode\")\n if config_name is not None:\n self._config_fn = config_name\n elif self._config_fn is None:\n self._config_fn = self._CONF\n if config_root is None:\n config_root = self.root\n fn = join(config_root, self._config_fn)\n self.logger.info(f\"Writing model config to {fn}\")\n self._configwrite(fn)\n\n @abstractmethod\n def read_staticmaps(self):\n \"\"\"Read staticmaps at and parse to xarray Dataset\"\"\"\n # to read gdal raster files use: hydromt.open_mfraster()\n # to read netcdf use: xarray.open_dataset()\n if not self._write:\n # start fresh in read-only mode\n self._staticmaps = xr.Dataset()\n raise NotImplementedError()\n\n @abstractmethod\n def write_staticmaps(self):\n \"\"\"Write staticmaps at in model ready format\"\"\"\n # to write to gdal raster files use: self.staticmaps.raster.to_mapstack()\n # to write to netcdf use: self.staticmaps.to_netcdf()\n if not self._write:\n raise IOError(\"Model opened in read-only mode\")\n raise NotImplementedError()\n\n @abstractmethod\n def read_staticgeoms(self):\n \"\"\"Read staticgeoms at and parse to dict of geopandas\"\"\"\n if not self._write:\n # start fresh in read-only mode\n self._staticgeoms = dict()\n raise NotImplementedError()\n\n @abstractmethod\n def write_staticgeoms(self):\n \"\"\"Write staticmaps at in model ready format\"\"\"\n # to write use self.staticgeoms[var].to_file()\n if not self._write:\n raise IOError(\"Model opened in read-only mode\")\n raise NotImplementedError()\n\n @abstractmethod\n def read_forcing(self):\n \"\"\"Read forcing at and parse to dict of xr.DataArray\"\"\"\n if not self._write:\n # start fresh in read-only mode\n self._forcing = dict()\n raise NotImplementedError()\n\n @abstractmethod\n def write_forcing(self):\n \"\"\"write forcing at in model ready format\"\"\"\n if not self._write:\n raise IOError(\"Model opened in read-only mode\")\n raise NotImplementedError()\n\n @abstractmethod\n def read_states(self):\n \"\"\"Read states at and parse to dict of xr.DataArray\"\"\"\n if not self._write:\n # start fresh in read-only mode\n self._states = dict()\n raise NotImplementedError()\n\n @abstractmethod\n def write_states(self):\n \"\"\"write states at in model ready format\"\"\"\n if not self._write:\n raise IOError(\"Model opened in read-only mode\")\n raise NotImplementedError()\n\n @abstractmethod\n def read_results(self):\n \"\"\"Read results at and parse to dict of xr.DataArray\"\"\"\n if not self._write:\n # start fresh in read-only mode\n self._results = dict()\n raise NotImplementedError()\n\n ## model configuration\n\n @property\n def config(self):\n \"\"\"Returns parsed model configuration.\"\"\"\n if not self._config:\n self.read_config() # initialize default config\n return self._config\n\n def set_config(self, *args):\n \"\"\"Update the config dictionary at key(s) with values.\n\n Parameters\n ----------\n args : key(s), value tuple, with minimal length of two\n keys can given by multiple args: ('key1', 'key2', 'value')\n or a string with '.' indicating a new level: ('key1.key2', 'value')\n\n Examples\n --------\n >> # self.config = {'a': 1, 'b': {'c': {'d': 2}}}\n\n >> set_config('a', 99)\n >> {'a': 99, 'b': {'c': {'d': 2}}}\n\n >> set_config('b', 'c', 'd', 99) # identical to set_config('b.d.e', 99)\n >> {'a': 1, 'b': {'c': {'d': 99}}}\n \"\"\"\n if len(args) < 2:\n raise TypeError(\"set_config() requires a least one key and one value.\")\n args = list(args)\n value = args.pop(-1)\n if len(args) == 1 and \".\" in args[0]:\n args = args[0].split(\".\") + args[1:]\n branch = self.config # reads config at first call\n for key in args[:-1]:\n if not key in branch or not isinstance(branch[key], dict):\n branch[key] = {}\n branch = branch[key]\n branch[args[-1]] = value\n\n def setup_config(self, **cfdict):\n \"\"\"Update config with a dictionary\"\"\"\n # TODO rename to update_config\n if len(cfdict) > 0:\n self.logger.debug(f\"Setting model config options.\")\n for key, value in cfdict.items():\n self.set_config(key, value)\n\n def get_config(self, *args, fallback=None, abs_path=False):\n \"\"\"Get a config value at key(s).\n\n Parameters\n ----------\n args : tuple or string\n keys can given by multiple args: ('key1', 'key2')\n or a string with '.' indicating a new level: ('key1.key2')\n fallback: any, optional\n fallback value if key(s) not found in config, by default None.\n abs_path: bool, optional\n If True return the absolute path relative to the model root, by deafult False.\n NOTE: this assumes the config is located in model root!\n\n Returns\n value : any type\n dictionary value\n\n Examples\n --------\n >> # self.config = {'a': 1, 'b': {'c': {'d': 2}}}\n\n >> get_config('a')\n >> 1\n\n >> get_config('b', 'c', 'd') # identical to get_config('b.c.d')\n >> 2\n\n >> get_config('b.c') # # identical to get_config('b','c')\n >> {'d': 2}\n \"\"\"\n args = list(args)\n if len(args) == 1 and \".\" in args[0]:\n args = args[0].split(\".\") + args[1:]\n branch = self.config # reads config at first call\n for key in args[:-1]:\n branch = branch.get(key, {})\n if not isinstance(branch, dict):\n branch = dict()\n break\n value = branch.get(args[-1], fallback)\n if abs_path and isinstance(value, str):\n value = Path(value)\n if not value.is_absolute():\n value = Path(abspath(join(self.root, value)))\n return value\n\n ## model parameter maps, geometries and spatial properties\n\n @property\n def staticmaps(self):\n \"\"\"xarray.Dataset representation of all static parameter maps\"\"\"\n if len(self._staticmaps) == 0:\n if self._read:\n self.read_staticmaps()\n return self._staticmaps\n\n def set_staticmaps(self, data, name=None):\n \"\"\"Add data to staticmaps.\n\n All layers of staticmaps must have identical spatial coordinates.\n\n Parameters\n ----------\n data: xarray.DataArray or xarray.Dataset\n new map layer to add to staticmaps\n name: str, optional\n Name of new map layer, this is used to overwrite the name of a DataArray\n or to select a variable from a Dataset.\n \"\"\"\n if name is None:\n if isinstance(data, xr.DataArray) and data.name is not None:\n name = data.name\n elif not isinstance(data, xr.Dataset):\n raise ValueError(\"Setting a map requires a name\")\n elif name is not None and isinstance(data, xr.Dataset):\n data_vars = list(data.data_vars)\n if len(data_vars) == 1 and name not in data_vars:\n data = data.rename_vars({data_vars[0]: name})\n elif name not in data_vars:\n raise ValueError(\"Name not found in DataSet\")\n else:\n data = data[[name]]\n if isinstance(data, xr.DataArray):\n data.name = name\n data = data.to_dataset()\n if len(self._staticmaps) == 0: # new data\n self._staticmaps = data\n else:\n if isinstance(data, np.ndarray):\n if data.shape != self.shape:\n raise ValueError(\"Shape of data and staticmaps do not match\")\n data = xr.DataArray(dims=self.dims, data=data, name=name).to_dataset()\n for dvar in data.data_vars.keys():\n if dvar in self._staticmaps:\n if self._read:\n self.logger.warning(f\"Replacing staticmap: {dvar}\")\n self._staticmaps[dvar] = data[dvar]\n\n @property\n def staticgeoms(self):\n \"\"\"geopandas.GeoDataFrame representation of all model geometries\"\"\"\n if not self._staticgeoms:\n if self._read:\n self.read_staticgeoms()\n return self._staticgeoms\n\n def set_staticgeoms(self, geom, name):\n \"\"\"Add geom to staticmaps\"\"\"\n gtypes = [gpd.GeoDataFrame, gpd.GeoSeries]\n if not np.any([isinstance(geom, t) for t in gtypes]):\n raise ValueError(\n \"First parameter map(s) should be geopandas.GeoDataFrame or geopandas.GeoSeries\"\n )\n if name in self._staticgeoms:\n if self._read:\n self.logger.warning(f\"Replacing staticgeom: {name}\")\n self._staticgeoms[name] = geom\n\n @property\n def forcing(self):\n \"\"\"dict of xarray.dataarray representation of all forcing\"\"\"\n if not self._forcing:\n if self._read:\n self.read_forcing()\n return self._forcing\n\n def set_forcing(self, data, name=None):\n \"\"\"Add data to forcing attribute which is a dictionary of xarray.DataArray.\n The dictionary key is taken from the variable name. In case of a DataArray\n without name, the name can be passed using the optional name argument.\n\n Arguments\n ---------\n data: xarray.Dataset or xarray.DataArray\n New forcing data to add\n name: str, optional\n Variable name, only in case data is of type DataArray\n \"\"\"\n # check dataset dtype\n dtypes = [xr.DataArray, xr.Dataset]\n if not np.any([isinstance(data, t) for t in dtypes]):\n raise ValueError(\"Data type not recognized\")\n if isinstance(data, xr.DataArray):\n # NOTE name can be different from data.name !\n if data.name is None and name is not None:\n data.name = name\n elif name is None and data.name is not None:\n name = data.name\n elif data.name is None and name is None:\n raise ValueError(\"Name required for forcing DataArray.\")\n data = {name: data}\n for name in data:\n if name in self._forcing:\n self.logger.warning(f\"Replacing forcing: {name}\")\n self._forcing[name] = data[name]\n\n @property\n def states(self):\n \"\"\"dict xarray.dataarray representation of all states\"\"\"\n if not self._states:\n if self._read:\n self.read_states()\n return self._states\n\n def set_states(self, data, name=None):\n \"\"\"Add data to states attribute which is a dictionary of xarray.DataArray.\n The dictionary key is taken from the variable name. In case of a DataArray\n without name, the name can be passed using the optional name argument.\n\n Arguments\n ---------\n data: xarray.Dataset or xarray.DataArray\n New forcing data to add\n name: str, optional\n Variable name, only in case data is of type DataArray\n \"\"\"\n # check dataset dtype\n dtypes = [xr.DataArray, xr.Dataset]\n if not np.any([isinstance(data, t) for t in dtypes]):\n raise ValueError(\"Data type not recognized\")\n if isinstance(data, xr.DataArray):\n # NOTE name can be different from data.name !\n if data.name is None and name is not None:\n data.name = name\n elif name is None and data.name is not None:\n name = data.name\n elif data.name is None and name is None:\n raise ValueError(\"Name required for forcing DataArray.\")\n data = {name: data}\n for name in data:\n if name in self._states:\n self.logger.warning(f\"Replacing state: {name}\")\n self._states[name] = data[name]\n\n @property\n def results(self):\n \"\"\"dict xarray.dataarray representation of model results\"\"\"\n if not self._results:\n if self._read:\n self.read_results()\n return self._results\n\n def set_results(self, data, name=None, split_dataset=False):\n \"\"\"Add data to results attribute which is a dictionary of xarray.DataArray and/or xarray.Dataset.\n\n The dictionary key is taken from the variable name. In case of a DataArray\n without name, the name can be passed using the optional name argument. In case of\n a Dataset, the dictionnary key is passed using the name argument.\n\n Dataset can either be added as is to the dictionnary (default) or split into several\n DataArrays using the split_dataset argument.\n\n Arguments\n ---------\n data: xarray.Dataset or xarray.DataArray\n New forcing data to add\n name: str, optional\n Variable name, only in case data is of type DataArray or if a Dataset is added as is (split_dataset=False).\n split_dataset: bool, optional\n If data is a xarray.Dataset, either add it as is to results or split it into several xarray.DataArrays.\n \"\"\"\n # check data dtype\n dtypes = [xr.DataArray, xr.Dataset]\n if not np.any([isinstance(data, t) for t in dtypes]):\n raise ValueError(\"Data type not recognized\")\n if isinstance(data, xr.DataArray):\n # NOTE name can be different from data.name !\n if data.name is None and name is not None:\n data.name = name\n elif name is None and data.name is not None:\n name = data.name\n elif data.name is None and name is None:\n raise ValueError(\"Name required for result DataArray.\")\n data = {name: data}\n # Add to results\n if isinstance(data, xr.Dataset) and not split_dataset:\n if name is not None:\n if name in self._results:\n self.logger.warning(f\"Replacing result: {name}\")\n self._results[name] = data\n else:\n raise ValueError(\"Name required to add DataSet directly to results\")\n else:\n for name in data:\n if name in self._results:\n self.logger.warning(f\"Replacing result: {name}\")\n self._results[name] = data[name]\n\n ## properties / methods below can be used directly in actual class\n\n @property\n def crs(self):\n \"\"\"Returns coordinate reference system embedded in staticmaps.\"\"\"\n return self.staticmaps.raster.crs\n\n def set_crs(self, crs):\n \"\"\"Embed coordinate reference system staticmaps metadata.\"\"\"\n return self.staticmaps.raster.set_crs(crs)\n\n @property\n def dims(self):\n \"\"\"Returns spatial dimension names of staticmaps.\"\"\"\n return self.staticmaps.raster.dims\n\n @property\n def coords(self):\n \"\"\"Returns coordinates of staticmaps.\"\"\"\n return self.staticmaps.raster.coords\n\n @property\n def res(self):\n \"\"\"Returns coordinates of staticmaps.\"\"\"\n return self.staticmaps.raster.res\n\n @property\n def transform(self):\n \"\"\"Returns spatial transform staticmaps.\"\"\"\n return self.staticmaps.raster.transform\n\n @property\n def width(self):\n \"\"\"Returns width of staticmaps.\"\"\"\n return self.staticmaps.raster.width\n\n @property\n def height(self):\n \"\"\"Returns height of staticmaps.\"\"\"\n return self.staticmaps.raster.height\n\n @property\n def shape(self):\n \"\"\"Returns shape of staticmaps.\"\"\"\n return self.staticmaps.raster.shape\n\n @property\n def bounds(self):\n \"\"\"Returns shape of staticmaps.\"\"\"\n return self.staticmaps.raster.bounds\n\n @property\n def region(self):\n \"\"\"Returns geometry of region of the model area of interest.\"\"\"\n region = None\n if \"region\" in self.staticgeoms:\n region = self.staticgeoms[\"region\"]\n elif len(self.staticmaps) > 0:\n crs = self.crs\n if crs is None and crs.to_epsg() is not None:\n crs = crs.to_epsg() # not all CRS have an EPSG code\n region = gpd.GeoDataFrame(geometry=[box(*self.bounds)], crs=crs)\n return region\n\n def test_model_api(self):\n \"\"\"Test compliance to model API instances.\n\n Returns\n -------\n non_compliant: list\n List of objects that are non-compliant with the model API structure.\n \"\"\"\n non_compliant = []\n # Staticmaps\n if not isinstance(self.staticmaps, xr.Dataset):\n non_compliant.append(\"staticmaps\")\n # Staticgeoms\n if not isinstance(self.staticgeoms, dict):\n non_compliant.append(\"staticgeoms\")\n elif self.staticgeoms: # non-empty dict\n for name, geom in self.staticgeoms.items():\n if not isinstance(geom, gpd.GeoDataFrame):\n non_compliant.append(f\"staticgeoms.{name}\")\n # Forcing\n if not isinstance(self.forcing, dict):\n non_compliant.append(\"forcing\")\n elif self.forcing: # non-empty dict\n for name, data in self.forcing.items():\n if not isinstance(data, xr.DataArray):\n non_compliant.append(f\"forcing.{name}\")\n # Config\n if not isinstance(self.config, dict):\n non_compliant.append(\"config\")\n # States\n if not isinstance(self.states, dict):\n non_compliant.append(\"states\")\n elif self.states: # non-empty dict\n for name, data in self.states.items():\n if not isinstance(data, xr.DataArray):\n non_compliant.append(f\"states.{name}\")\n # Results\n if not isinstance(self.results, dict):\n non_compliant.append(\"results\")\n elif self.results: # non-empty dict\n dtypes = [xr.DataArray, xr.Dataset]\n for name, data in self.results.items():\n if not np.any([isinstance(data, t) for t in dtypes]):\n non_compliant.append(f\"results.{name}\")\n\n return non_compliant\n","sub_path":"hydromt/models/model_api.py","file_name":"model_api.py","file_ext":"py","file_size_in_byte":29094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"142532488","text":"import pytest\nimport pandas as pd\nfrom collections import OrderedDict as odict\n\nfrom kep.csv2df.specification import Definition, Specification\nfrom kep.csv2df.reader import text_to_list\nfrom kep.csv2df.parser import split_to_tables, parse_tables, Table\n\n\nDOC = \"\"\"Объем ВВП, млрд.рублей / Gross domestic product, bln rubles\n1999\t4823\t901\t1102\t1373\t1447\n2000\t7306\t1527\t1697\t2038\t2044\"\"\"\n\n\ndef create_table():\n rows = text_to_list(DOC)\n tables = list(split_to_tables(rows))\n return tables[0]\n\n\ndef test_split_to_tables():\n assert create_table() == \\\n Table(headers=[['Объем ВВП, млрд.рублей / Gross domestic product, bln rubles']],\n datarows=[['1999', '4823', '901', '1102', '1373', '1447'],\n ['2000', '7306', '1527', '1697', '2038', '2044']]\n )\n\n\nclass Test_Table():\n t = create_table()\n\n def test_extract_values_method_on_table_after_parsing_returns_expected_dicts(\n self):\n # prepare\n self.t.set_splitter(None)\n self.t.varname = 'GDP'\n self.t.unit = 'bln_rub'\n # run\n datapoints = list(self.t.extract_values())\n # compare\n assert datapoints[0] == {'freq': 'a',\n 'label': 'GDP_bln_rub',\n 'time_index': pd.Timestamp('1999-12-31'),\n 'value': 4823}\n assert datapoints[1] == {'freq': 'q',\n 'label': 'GDP_bln_rub',\n 'time_index': pd.Timestamp('1999-03-31'),\n 'value': 901}\n assert datapoints[2] == {'freq': 'q',\n 'label': 'GDP_bln_rub',\n 'time_index': pd.Timestamp('1999-06-30'),\n 'value': 1102}\n assert datapoints[3] == {'freq': 'q',\n 'label': 'GDP_bln_rub',\n 'time_index': pd.Timestamp('1999-09-30'),\n 'value': 1373}\n assert datapoints[4] == {'freq': 'q',\n 'label': 'GDP_bln_rub',\n 'time_index': pd.Timestamp('1999-12-31'),\n 'value': 1447}\n\n\nDOC2 = \"\"\"\tГод Year\tКварталы / Quarters\tЯнв. Jan.\tФев. Feb.\tМарт Mar.\tАпр. Apr.\tМай May\tИюнь June\tИюль July\tАвгуст Aug.\tСент. Sept.\tОкт. Oct.\tНояб. Nov.\tДек. Dec.\n\t\tI\tII\tIII\tIV\n1.7. Инвестиции в основной капитал1), млрд. рублей / Fixed capital investments1), bln rubles\n2015\t14555,9\t1969,7\t3020,8\t3560,2\t6005,2\t516,9\t680,7\t772,1\t812,8\t1004,2\t1203,8\t1078,4\t1209,1\t1272,7\t1703,9\t1592,7\t2708,6\n20162)\t\t2149,4\t3153,3\t3813,4\n\tГод Year\tКварталы / Quarters\tЯнв. Jan.\tФев. Feb.\tМарт Mar.\tАпр. Apr.\tМай May\tИюнь June\tИюль July\tАвгуст Aug.\tСент. Sept.\tОкт. Oct.\tНояб. Nov.\tДек. Dec.\n\t\tI\tII\tIII\tIV\nв % к соответствующему периоду предыдущего года / percent of corresponding period of previous year\n2015\t91,6\t95,2\t91,2\t87,0\t93,6\t95,9\t94,4\t95,4\t93,8\t90,1\t90,4\t88,3\t86,6\t86,3\t96,3\t93,5\t91,9\n2016\t\t95,2\t96,1\t100,3\nв % к предыдущему периоду / percent of previous period\n2015\t\t35,2\t152,1\t108,9\t160,4\t20,7\t129,1\t116,4\t104,2\t123,0\t118,2\t87,8\t105,3\t103,6\t134,3\t92,9\t163,0\n2016\t\t36,9\t147,1\t119,2\n1.7.1. Инвестиции в основной капитал организаций\"\"\"\n\n\nUNITS = odict([ # 1. MONEY\n ('млрд.рублей', 'bln_rub'),\n ('млрд. рублей', 'bln_rub'),\n # 2. RATES OF CHANGE\n ('в % к прошлому периоду', 'rog'),\n ('в % к предыдущему месяцу', 'rog'),\n ('в % к предыдущему периоду', 'rog'),\n ('в % к соответствующему периоду предыдущего года', 'yoy'),\n ('в % к соответствующему месяцу предыдущего года', 'yoy')\n])\n\n\ndef make_definition():\n boundaries = [\n dict(start='1.6. Инвестиции в основной капитал',\n end='1.6.1. Инвестиции в основной капитал организаций'),\n dict(start='1.7. Инвестиции в основной капитал',\n end='1.7.1. Инвестиции в основной капитал организаций')]\n commands = [\n dict(\n var='INVESTMENT',\n header=['Инвестиции в основной капитал'],\n unit=['bln_rub', 'yoy', 'rog'])]\n # mapper dictionary to convert text in table headers to units of\n # measurement\n units = UNITS\n return Definition(commands, units, boundaries)\n\n\ndef create_tables():\n csv_segment = text_to_list(DOC2)\n return split_to_tables(csv_segment)\n\n\nclass Test_parse_tables:\n pdef = make_definition()\n tables = create_tables()\n\n def test_parse_tables(self):\n tables = parse_tables(self.tables, self.pdef)\n # checks\n assert len(tables) == 3\n assert all([t.has_unknown_lines() for t in tables]) is False\n for t in tables:\n assert t.varname == 'INVESTMENT'\n assert [t.unit for t in tables] == ['bln_rub', 'yoy', 'rog']\n\n\nDOC3 = '\\n'.join([DOC, DOC2])\n\n\ndef make_specification():\n commands = [\n dict(\n var='GDP',\n header='Объем ВВП',\n unit='bln_rub')]\n specification = Specification(commands=commands, units=UNITS)\n boundaries1 = [\n dict(start='1.6. Инвестиции в основной капитал',\n end='1.6.1. Инвестиции в основной капитал организаций'),\n dict(start='1.7. Инвестиции в основной капитал',\n end='1.7.1. Инвестиции в основной капитал организаций')]\n commands1 = [\n dict(\n var='INVESTMENT',\n header=['Инвестиции в основной капитал'],\n unit=['bln_rub', 'yoy', 'rog'])]\n specification.append(commands1, boundaries1)\n return specification\n\n\ncontrol_values = [\n {'freq': 'a', 'label': 'GDP_bln_rub',\n 'time_index': pd.Timestamp('1999-12-31'),\n 'value': 4823.0},\n {'freq': 'q',\n 'label': 'GDP_bln_rub',\n 'time_index': pd.Timestamp('2000-12-31'),\n 'value': 2044.0},\n {'freq': 'a',\n 'label': 'INVESTMENT_bln_rub',\n 'time_index': pd.Timestamp('2015-12-31'),\n 'value': 14555.9},\n {'freq': 'q',\n 'label': 'INVESTMENT_rog',\n 'time_index': pd.Timestamp('2016-09-30'),\n 'value': 119.2}\n]\n\n\ndef test_specification_with_2_segments_on_valid_csv_data():\n # setting\n spec = make_specification()\n spec.attach_data(DOC3)\n # call\n values = spec.values\n # check\n for d in control_values:\n assert d in values\n\n\nif __name__ == \"__main__\":\n pytest.main([__file__])\n","sub_path":"src/kep/csv2df/tests/test_parser_and_integration.py","file_name":"test_parser_and_integration.py","file_ext":"py","file_size_in_byte":7116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"618606107","text":"from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nimport time\nimport unittest\n\nclass NewVisitorTest(unittest.TestCase) :\n def setUp(self) :\n self.browser = webdriver.Firefox()\n\n def tearDown(self) :\n self.browser.quit()\n def check_in_table(self, row_text, idtag) :\n table = self.browser.find_element_by_id(idtag)\n rows = table.find_elements_by_tag_name('tr')\n self.assertIn(row_text, [row.text for row in rows])\n\n def check_ids(self, text, idtag) :\n outputs= self.browser.find_elements_by_id(idtag)\n self.assertIn(text, [output.text for output in outputs])\n\n def waitforelement(self, id) :\n try:\n waiter = WebDriverWait(driver, 10)\n waiter.until(EC.presence_of_element_located(By.ID, id))\n finally:\n self.fail('Timedout')\n\n def box(self, id) :\n return self.browser.find_element_by_id(id)\n\n def test_can_build_a_cv(self) :\n #goes to check out cv builder\n self.browser.get('http://127.0.0.1:8000/cv/')\n \n #notices title and header mention cv builder\n self.assertIn('CV Builder', self.browser.title)\n header_text = self.browser.find_element_by_tag_name('h1')\n\n\n\n\n\n #invited to enter name\n inputboxname=self.browser.find_element_by_id('namequest')\n self.assertEqual(self.browser.find_element_by_id('namequestion').text, 'Enter your full name')\n #types James Bartlett into text box\n inputboxname.send_keys('James Bartlett')\n inputboxname.send_keys(Keys.ENTER)\n time.sleep(1)\n self.assertEqual(self.browser.find_element_by_id('namedis').text, 'Name: James Bartlett')\n\n\n #invited to enter email into text box\n inputboxemail = self.browser.find_element_by_id('email')\n self.assertEqual(self.browser.find_element_by_id('emailquestion').text, \"Enter your email\")\n # checks to see if a non email can be entered\n\n\n # enters james@gmail.com\n inputboxemail.send_keys('james@gmail.com')\n inputboxemail.send_keys(Keys.ENTER)\n time.sleep(1)\n # self.waitforelement('email')\n self.assertEqual(self.browser.find_element_by_id('emaildis').text, 'Email: james@gmail.com')\n inputboxemail = self.browser.find_element_by_id('email')\n inputboxemail.send_keys('jameslukebartlett@gmail.com')\n time.sleep(1)\n inputboxemail.send_keys(Keys.ENTER)\n time.sleep(1)\n self.assertEqual(self.browser.find_element_by_id('emaildis').text, 'Email: jameslukebartlett@gmail.com')\n\n #invited to enter mobile number into text box\n inputboxnumber=self.browser.find_element_by_id('number')\n self.assertEqual(self.browser.find_element_by_id('telquestion').text, 'Enter your telephone number')\n #checks a non number can't be entered\n\n\n inputboxnumber.send_keys('111111111')\n inputboxnumber.send_keys(Keys.ENTER)\n time.sleep(1)\n self.assertEqual(self.browser.find_element_by_id('numberdis').text, 'Number: 111111111')\n\n #types 07094534634 in\n inputboxnumber = self.browser.find_element_by_id('number')\n inputboxnumber.send_keys('07094534634')\n inputboxnumber.send_keys(Keys.ENTER)\n time.sleep(1)\n self.assertEqual(self.browser.find_element_by_id('numberdis').text, 'Number: 07094534634')\n\n # when hits enter name, email and number are displayed\n #will need to decide how i want it displayed\n #Personal profile\n\n #Invited towrite a personal profile\n inputboxprofile = self.browser.find_element_by_id('personalprof')\n self.assertEqual(self.browser.find_element_by_id('profquestion').text, 'Enter a personal profile')\n #Types looking for work have a computer sciecne degree and good teamwork skills\n inputboxprofile.send_keys('Looking for work have a computer science degree and good teamwork skills')\n submitprofile = self.browser.find_element_by_id('Profile')\n submitprofile.click()\n time.sleep(1)\n #Upon enter personal profile is displayed\n self.assertEqual(self.browser.find_element_by_id('profiledis').text, 'Looking for work have a computer science degree and good teamwork skills')\n\n inputboxprofile = self.browser.find_element_by_id('personalprof')\n inputboxprofile.send_keys('Looking to study a course to further improve my robotics. I am hard working and work well in a team')\n submitprofile = self.browser.find_element_by_id('Profile')\n submitprofile.click()\n time.sleep(1)\n #Upon enter personal profile is displayed\n self.assertEqual(self.browser.find_element_by_id('profiledis').text, 'Looking to study a course to further improve my robotics. I am hard working and work well in a team')\n\n\n #Skills\n inputboxskills=self.browser.find_element_by_id('skill')\n self.assertEqual(self.browser.find_element_by_id('Skillsquestion').text, 'Enter a skill')\n\n #Invited to enter a skill\n inputboxskills.send_keys('Java')\n inputboxskills.send_keys(Keys.ENTER)\n #Types Java\n time.sleep(1)\n\n # Upon enter java is displayed underskills\n self.check_in_table('Java', 'skillstable')\n # Invited to enter another skill\n\n\n # Types Teamwork\n inputboxskills = self.box('skill')\n inputboxskills.send_keys('Teamwork')\n inputboxskills.send_keys(Keys.ENTER)\n # Upon enter both skills entries are displayed\n time.sleep(1)\n # self.fail('Checking if it gets to this point')\n # self.check_in_table('Java', 'skillstable')\n self.check_in_table('Java', 'skillstable')\n self.check_in_table('Teamwork', 'skillstable')\n\n inputboxskills = self.box('skill')\n inputboxskills.send_keys('C')\n inputboxskills.send_keys(Keys.ENTER)\n time.sleep(1)\n\n self.check_in_table('Java', 'skillstable')\n self.check_in_table('Teamwork', 'skillstable')\n self.check_in_table('C', 'skillstable')\n\n inputboxskills = self.box('skill')\n inputboxskills.send_keys('Attention to detail')\n inputboxskills.send_keys(Keys.ENTER)\n time.sleep(1)\n\n self.check_in_table('Java', 'skillstable')\n self.check_in_table('Teamwork', 'skillstable')\n self.check_in_table('C', 'skillstable')\n self.check_in_table('Attention to detail', 'skillstable')\n\n inputboxskills = self.box('skill')\n inputboxskills.send_keys('Python')\n inputboxskills.send_keys(Keys.ENTER)\n time.sleep(1)\n\n self.check_in_table('Java', 'skillstable')\n self.check_in_table('Teamwork', 'skillstable')\n self.check_in_table('C', 'skillstable')\n self.check_in_table('Attention to detail', 'skillstable')\n self.check_in_table('Python', 'skillstable')\n\n\n\n #Invited to enter a qualification\n inputboxqualification = self.browser.find_element_by_id('qualification')\n self.assertEqual(self.browser.find_element_by_id('Qualificationquestion').text, 'Enter a proffessional qualification')\n\n #Types level 1 java\n inputboxqualification.send_keys('Level 1 Java')\n inputboxqualification.send_keys(Keys.ENTER)\n time.sleep(1)\n\n self.check_in_table('Level 1 Java', 'qualificationstable')\n\n inputboxqualification = self.box('qualification')\n inputboxqualification.send_keys('Level 2 Java')\n inputboxqualification.send_keys(Keys.ENTER)\n time.sleep(1)\n\n self.check_in_table('Level 1 Java', 'qualificationstable')\n self.check_in_table('Level 2 Java', 'qualificationstable')\n\n inputboxqualification = self.box('qualification')\n inputboxqualification.send_keys('BCS Essentials Certificate in Artificial Intelligence')\n inputboxqualification.send_keys(Keys.ENTER)\n time.sleep(1)\n\n self.check_in_table('Level 1 Java', 'qualificationstable')\n self.check_in_table('Level 2 Java', 'qualificationstable')\n self.check_in_table('BCS Essentials Certificate in Artificial Intelligence', 'qualificationstable')\n\n inputboxqualification = self.box('qualification')\n inputboxqualification.send_keys('BSC Computer Science')\n inputboxqualification.send_keys(Keys.ENTER)\n time.sleep(1)\n\n self.check_in_table('Level 1 Java', 'qualificationstable')\n self.check_in_table('Level 2 Java', 'qualificationstable')\n self.check_in_table('BCS Essentials Certificate in Artificial Intelligence', 'qualificationstable')\n self.check_in_table('BSC Computer Science', 'qualificationstable')\n\n inputboxqualification = self.box('qualification')\n inputboxqualification.send_keys('Level 1 Teamwork')\n inputboxqualification.send_keys(Keys.ENTER)\n time.sleep(1)\n\n self.check_in_table('Level 1 Java', 'qualificationstable')\n self.check_in_table('Level 2 Java', 'qualificationstable')\n self.check_in_table('BCS Essentials Certificate in Artificial Intelligence', 'qualificationstable')\n self.check_in_table('BSC Computer Science', 'qualificationstable')\n self.check_in_table('Level 1 Teamwork', 'qualificationstable')\n\n\n\n\n #Project\n inputboxprojecttitle = self.browser.find_element_by_id('projectover')\n self.assertEqual(self.browser.find_element_by_id('ProjectQuestion').text, 'Enter a project name')\n\n inputboxprojectdes = self.browser.find_element_by_id('projectdes')\n self.assertEqual(self.browser.find_element_by_id('ProjectDescription').text, 'Enter the description of the project')\n submitproject = self.browser.find_element_by_id('ProjectSub')\n\n inputboxprojecttitle.send_keys('Image filter in java')\n inputboxprojectdes.send_keys('Used matricies and arrays in java to create different ones by changing the rgb values')\n submitproject.click()\n time.sleep(1)\n\n self.check_ids('Image filter in java', 'projecttitle')\n self.check_ids('Used matricies and arrays in java to create different ones by changing the rgb values', 'projectdescribe')\n\n submitproject = self.box('ProjectSub')\n inputboxprojecttitle = self.box('projectover')\n inputboxprojectdes = self.box('projectdes')\n inputboxprojecttitle.send_keys('Moving robot')\n inputboxprojectdes.send_keys('Programmed a lego robot to follow a black line using color sensors and avoiding obstacles')\n submitproject.click()\n time.sleep(1)\n\n self.check_ids('Image filter in java', 'projecttitle')\n self.check_ids('Used matricies and arrays in java to create different ones by changing the rgb values', 'projectdescribe')\n self.check_ids('Moving robot', 'projecttitle')\n self.check_ids('Programmed a lego robot to follow a black line using color sensors and avoiding obstacles', 'projectdescribe')\n\n inputboxprojecttitle = self.box('projectover')\n inputboxprojectdes = self.box('projectdes')\n submitproject = self.box('ProjectSub')\n inputboxprojecttitle.send_keys('Maze game')\n inputboxprojectdes.send_keys('A game where players move through a maze trying to collect as many coins as possible while fighting other players')\n submitproject.click()\n time.sleep(1)\n\n self.check_ids('Image filter in java', 'projecttitle')\n self.check_ids('Used matricies and arrays in java to create different ones by changing the rgb values', 'projectdescribe')\n self.check_ids('Moving robot', 'projecttitle')\n self.check_ids('Programmed a lego robot to follow a black line using color sensors and avoiding obstacles', 'projectdescribe')\n self.check_ids('Maze game', 'projecttitle')\n self.check_ids('A game where players move through a maze trying to collect as many coins as possible while fighting other players', 'projectdescribe')\n\n #Achievments\n\n # Invited to enter an achievment\n inputboxachievments=self.browser.find_element_by_id('achievment')\n self.assertEqual(self.browser.find_element_by_id('Achievmentquestion').text, 'Enter an achievment')\n\n # Types 1st place in hackathon\n inputboxachievments.send_keys('1st place in hackathon')\n # Upon enter displays ahcivment\n inputboxachievments.send_keys(Keys.ENTER)\n time.sleep(1)\n\n self.check_in_table('1st place in hackathon', 'achtable')\n # Invited to enter another achievent\n\n #Types a levels\n inputboxachievments = self.box('achievment')\n inputboxachievments.send_keys('a levels')\n\n # upon enter displays both ahcivments\n inputboxachievments.send_keys(Keys.ENTER)\n time.sleep(1)\n\n self.check_in_table('1st place in hackathon', 'achtable')\n self.check_in_table('a levels', 'achtable')\n\n inputboxachievments = self.box('achievment')\n inputboxachievments.send_keys('Best in a level maths')\n inputboxachievments.send_keys(Keys.ENTER)\n time.sleep(1)\n\n self.check_in_table('1st place in hackathon', 'achtable')\n self.check_in_table('a levels', 'achtable')\n self.check_in_table('Best in a level maths', 'achtable')\n\n inputboxachievments = self.box('achievment')\n inputboxachievments.send_keys('1st Place in BAE systems CTF')\n inputboxachievments.send_keys(Keys.ENTER)\n time.sleep(1)\n\n self.check_in_table('1st place in hackathon', 'achtable')\n self.check_in_table('a levels', 'achtable')\n self.check_in_table('Best in a level maths', 'achtable')\n self.check_in_table('1st Place in BAE systems CTF', 'achtable')\n\n inputboxachievments = self.box('achievment')\n inputboxachievments.send_keys('Social Secretary for filmsoc between 2019 and 2020')\n inputboxachievments.send_keys(Keys.ENTER)\n time.sleep(1)\n\n self.check_in_table('1st place in hackathon', 'achtable')\n self.check_in_table('a levels', 'achtable')\n self.check_in_table('Best in a level maths', 'achtable')\n self.check_in_table('1st Place in BAE systems CTF', 'achtable')\n self.check_in_table('Social Secretary for filmsoc between 2019 and 2020', 'achtable')\n #Work experience\n\n # Invited to enter name of company\n inputboxcompany = self.browser.find_element_by_id('placeofwork')\n self.assertEqual(self.browser.find_element_by_id('placeofworkq').text, 'Enter the place of work')\n #Enters university of brimigham\n # Invited to enter job role\n inputboxjob = self.browser.find_element_by_id('role')\n self.assertEqual(self.browser.find_element_by_id('roleq').text, 'Enter the job role')\n #Types student ambassador\n #Invited to enter date started\n inputboxstartdatew=self.browser.find_element_by_id('startdatew')\n self.assertEqual(self.browser.find_element_by_id('startdatewq').text, 'Enter the start date of the job')\n\n #Types 01/2019\n #Invited to enter date finished or present\n self.assertEqual(self.browser.find_element_by_id('enddatewq').text, 'Enter the date you finished the role')\n #Types present\n #Invited to enter job description\n inputboxenddatew=self.browser.find_element_by_id('enddatew')\n self.assertEqual(self.browser.find_element_by_id('jobdesq').text, 'Enter the job description details')\n submitworkexp = self.browser.find_element_by_id('WorkExperience')\n inputboxjobdes=self.browser.find_element_by_id('description')\n\n #Types resonsiple to showing students round builidng makeing them feel welcome and setting up events\n inputboxcompany.send_keys(\"University of Birmingham\")\n inputboxjob.send_keys(\"student ambassador\")\n inputboxstartdatew.send_keys('01/01/2019')\n inputboxenddatew.send_keys('03/08/2020')\n inputboxjobdes.send_keys(\"Responsible for showing students round building making them feel welcome and setting up events\")\n submitworkexp.click()\n time.sleep(1)\n #Upon enter company, role, dates and job description are displayed\n self.check_ids(\"Job Role: student ambassador\", \"jobtitled\")\n self.check_ids(\"Company: University of Birmingham\", \"jobcompd\")\n self.check_ids(\"Dates: 01/01/2019 - 03/08/2020\", \"jobdatesd\")\n self.check_ids(\"Responsible for showing students round building making them feel welcome and setting up events\", \"jobdetailsd\")\n\n\n inputboxcompany = self.box('placeofwork')\n inputboxjob = self.box('role')\n inputboxstartdatew = self.box('startdatew')\n inputboxenddatew = self.box('enddatew')\n inputboxjobdes = self.box('description')\n submitworkexp = self.box('WorkExperience')\n\n inputboxcompany.send_keys(\"PGL\")\n inputboxjob.send_keys(\"Activity Instrustuctor / Group Leader\")\n inputboxstartdatew.send_keys('01/07/2019')\n inputboxenddatew.send_keys('01/09/2019')\n inputboxjobdes.send_keys(\"Responsbile for supervising children with thier activitys and occasionally looking after thier needes while providing a high standard of outdoor education\")\n submitworkexp.click()\n time.sleep(1)\n #Upon enter company, role, dates and job description are displayed\n self.check_ids(\"Job Role: student ambassador\",\"jobtitled\")\n self.check_ids(\"Company: University of Birmingham\", \"jobcompd\")\n\n self.check_ids(\"Dates: 01/01/2019 - 03/08/2020\", \"jobdatesd\")\n self.check_ids(\"Responsible for showing students round building making them feel welcome and setting up events\", \"jobdetailsd\")\n\n self.check_ids(\"Job Role: Activity Instrustuctor / Group Leader\", \"jobtitled\")\n self.check_ids(\"Company: PGL\", \"jobcompd\")\n\n self.check_ids(\"Dates: 01/07/2019 - 01/09/2019\", \"jobdatesd\")\n self.check_ids(\"Responsbile for supervising children with thier activitys and occasionally looking after thier needes while providing a high standard of outdoor education\", \"jobdetailsd\")\n\n inputboxcompany = self.box('placeofwork')\n inputboxjob = self.box('role')\n inputboxstartdatew = self.box('startdatew')\n inputboxenddatew = self.box('enddatew')\n inputboxjobdes = self.box('description')\n submitworkexp = self.box('WorkExperience')\n\n inputboxcompany.send_keys(\"Coder Dojo\")\n inputboxjob.send_keys(\"Mentor\")\n inputboxstartdatew.send_keys('01/10/2017')\n inputboxenddatew.send_keys('01/07/2019')\n inputboxjobdes.send_keys(\"Mentored students while they learned to code. Also set up for events and attended various promotoional activities\")\n submitworkexp.click()\n time.sleep(1)\n #Upon enter company, role, dates and job description are displayed\n self.check_ids(\"Job Role: student ambassador\",\"jobtitled\")\n self.check_ids(\"Company: University of Birmingham\", \"jobcompd\")\n\n self.check_ids(\"Dates: 01/01/2019 - 03/08/2020\", \"jobdatesd\")\n self.check_ids(\"Responsible for showing students round building making them feel welcome and setting up events\", \"jobdetailsd\")\n\n self.check_ids(\"Job Role: Activity Instrustuctor / Group Leader\", \"jobtitled\")\n self.check_ids(\"Company: PGL\", \"jobcompd\")\n\n self.check_ids(\"Dates: 01/07/2019 - 01/09/2019\", \"jobdatesd\")\n self.check_ids(\"Responsbile for supervising children with thier activitys and occasionally looking after thier needes while providing a high standard of outdoor education\", \"jobdetailsd\")\n\n self.check_ids(\"Job Role: Mentor\", \"jobtitled\")\n self.check_ids(\"Company: Coder Dojo\", \"jobcompd\")\n\n self.check_ids(\"Dates: 01/10/2017 - 01/07/2019\", \"jobdatesd\")\n self.check_ids(\"Mentored students while they learned to code. Also set up for events and attended various promotoional activities\", \"jobdetailsd\")\n #Education\n\n #Invited to enter place of learning\n inputboxschool=self.browser.find_element_by_id('school')\n self.assertEqual(self.browser.find_element_by_id('schoolq').text, 'Enter the name of the school')\n\n #Enters woodhouse college\n # Invited to enter date started\n inputboxstartdates=self.browser.find_element_by_id('startdates')\n self.assertEqual(self.browser.find_element_by_id('startdatesq').text, 'Enter the date you started at the school')\n\n #Types 09/2016\n #Invited to enter date left\n inputboxenddates=self.browser.find_element_by_id('enddates')\n self.assertEqual(self.browser.find_element_by_id('enddatesq').text, 'Enter the date you finished at the school')\n\n #Types 07/2018\n #Invited to enter qualifications\n inputboxgrades = self.browser.find_element_by_id('grades')\n self.assertEqual(self.browser.find_element_by_id('gradesq').text, 'Enter the grades obtained')\n submiteducation=self.browser.find_element_by_id('EducationSubmit')\n\n #Types Maths A* FUther Maths B, Georgraphy A\n inputboxschool.send_keys('Woodhouse College')\n inputboxstartdates.send_keys('01/09/2016')\n inputboxenddates.send_keys('01/07/2018')\n inputboxgrades.send_keys('Maths A* Further Maths B Georgraphy A')\n # Upon enter school, dates and grades are displayed\n submiteducation.click()\n time.sleep(1)\n\n self.check_ids(\"School/College: Woodhouse College\", 'schoold')\n self.check_ids(\"01/09/2016 - 01/07/2018\", 'schooldatesd')\n self.check_ids(\"Maths A* Further Maths B Georgraphy A\", 'schooldetailsd')\n\n inputboxschool = self.box('school')\n inputboxstartdates = self.box('startdates')\n inputboxenddates = self.box('enddates')\n inputboxgrades = self.box('grades')\n submiteducation = self.box('EducationSubmit')\n\n inputboxschool.send_keys('University of Birmingham')\n inputboxstartdates.send_keys('01/09/2018')\n inputboxenddates.send_keys('Present')\n inputboxgrades.send_keys('BSc Computer Science, predicted 2.1')\n # Upon enter school, dates and grades are displayed\n submiteducation.click()\n time.sleep(1)\n\n self.check_ids(\"School/College: Woodhouse College\", 'schoold')\n self.check_ids(\"01/09/2016 - 01/07/2018\", 'schooldatesd')\n self.check_ids(\"Maths A* Further Maths B Georgraphy A\", 'schooldetailsd')\n\n self.check_ids(\"School/College: University of Birmingham\", 'schoold')\n self.check_ids(\"01/09/2018 - Present\", 'schooldatesd')\n self.check_ids(\"BSc Computer Science, predicted 2.1\", 'schooldetailsd')\n\n #Notes\n inputboxnotes = self.browser.find_element_by_id('Notes')\n self.assertEqual(self.browser.find_element_by_id('PostQuestion').text, 'Enter any other notes')\n\n submitnotes = self.browser.find_element_by_id('NotesSubmit')\n\n inputboxnotes.send_keys('As a reward for my hard work at a charity I was selected for a trip to europe')\n submitnotes.click()\n time.sleep(1)\n\n self.check_ids('As a reward for my hard work at a charity I was selected for a trip to europe', 'notesdetails')\n\n inputboxnotes = self.box('Notes')\n submitnotes = self.box(\"NotesSubmit\")\n inputboxnotes.send_keys('I am a very hard working and commited individual who has got a wide range of experience and would love to come and work for your company')\n submitnotes.click()\n time.sleep(1)\n\n self.check_ids('As a reward for my hard work at a charity I was selected for a trip to europe', 'notesdetails')\n self.check_ids('I am a very hard working and commited individual who has got a wide range of experience and would love to come and work for your company', 'notesdetails')\n\n inputboxnotes = self.box('Notes')\n submitnotes = self.box(\"NotesSubmit\")\n inputboxnotes.send_keys('References from universities and previous employers are available upon request')\n submitnotes.click()\n time.sleep(1)\n\n self.check_ids('As a reward for my hard work at a charity I was selected for a trip to europe', 'notesdetails')\n self.check_ids('I am a very hard working and commited individual who has got a wide range of experience and would love to come and work for your company', 'notesdetails')\n self.check_ids('References from universities and previous employers are available upon request', 'notesdetails')\n\n\n\n\nif __name__ == '__main__' :\n unittest.main(warnings='ignore')\n","sub_path":"functionaltests.py","file_name":"functionaltests.py","file_ext":"py","file_size_in_byte":24755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"140319211","text":"import argparse\nimport os\nimport sys\n\nfrom path import Path\n\nimport ci\nimport ci.cpp\nimport ci.conan\nimport ci.git\n\n\ndef main() -> None:\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--isolate-conan-user-home\",\n action=\"store_true\",\n dest=\"home_isolation\",\n default=False,\n )\n subparsers = parser.add_subparsers(title=\"subcommands\", dest=\"command\")\n\n build_and_test_parser = subparsers.add_parser(\"build-and-test\")\n build_and_test_parser.add_argument(\"--profile\", required=True)\n build_and_test_parser.add_argument(\"--coverage\", action=\"store_true\")\n\n subparsers.add_parser(\"deploy\")\n subparsers.add_parser(\"mirror\")\n\n args = parser.parse_args()\n if args.home_isolation:\n ci.conan.set_home_isolation()\n\n ci.conan.update_config()\n\n if args.command == \"build-and-test\":\n src_path = Path.getcwd()\n build_path = \".\" # ci.cpp.Builder runs ctest from the build directory\n # fmt: off\n ctest_flags = [\n \"--build-and-test\",\n src_path,\n build_path,\n \"--build-generator\", \"Ninja\",\n \"--output-on-failure\",\n \"--test-command\", \"bin/test_tconcurrent\",\n ]\n # fmt: on\n if sys.platform == \"darwin\":\n # When a macOS runner runs the tests, the ones waiting for a specific time will wait longer than requested.\n # Thus the tests fail. Funny thing is that they pass when running them by hand, on the slave...\n ctest_flags.append(\"--test-case-exclude=*[waiting]*\")\n built_path = ci.cpp.build(args.profile, coverage=args.coverage)\n ci.cpp.check(built_path, coverage=args.coverage, ctest_flags=ctest_flags)\n elif args.command == \"deploy\":\n git_tag = os.environ[\"CI_COMMIT_TAG\"]\n version = ci.version_from_git_tag(git_tag)\n ci.bump_files(version)\n ci.cpp.build_recipe(\n Path.getcwd(),\n conan_reference=f\"tconcurrent/{version}@tanker/stable\",\n upload=True,\n )\n elif args.command == \"mirror\":\n ci.git.mirror(github_url=\"git@github.com:TankerHQ/tconcurrent\")\n else:\n parser.print_help()\n sys.exit(1)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"run-ci.py","file_name":"run-ci.py","file_ext":"py","file_size_in_byte":2260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"407774035","text":"import pickle\nimport sys\n\nimport numpy as np\nimport pandas as pd\nfrom hyperopt import hp, tpe, Trials\nfrom hyperopt.fmin import fmin\n\nsys.path.insert(0, '..')\nfrom src.models.model import mase\nimport lightgbm as lgb\nfrom pathlib import Path\n\n\ndef cv_lgboost(model, X_base=None, y=None):\n train_index = X_base.index.year.isin([2016, 2017])\n valid_index = X_base.index.year.isin([2018])\n X_train, X_valid = X_base.iloc[train_index], X_base.iloc[valid_index]\n y_train, y_valid = y.iloc[train_index], y.iloc[valid_index]\n\n model.fit(X_train.values, y_train.values.reshape(-1, ))\n # ntree = model.best_iteration_\n preds = model.predict(X_valid.values)\n oof_scores = mase(preds, y_valid.values)\n return oof_scores\n\n\nproject_dir = Path(__file__).resolve().parents[2]\nprint(project_dir)\ndata_dict = pd.read_pickle(f'{project_dir}/data/processed/data_dict_all.pkl')\n\n# Load the data\nyear = 2019\ntgt = 'rougher.output.recovery'\nX = data_dict[year][f'X_train_tsclean'] # .drop(cols_drop,axis = 1)\ny = data_dict[year]['y_train']\nmask = data_dict[year]['mask']\nX = X.loc[mask.index, :][mask]\ny = y.loc[mask.index, :][mask]\nprint(f'2) train: {X.shape}')\ny = y.loc[X.index, tgt]\nX_filt = X.filter(regex=\"rougher|dayw|hour\", axis=1)\nprint(f'after sample() train: {X.shape}')\n# Load the feature importances\n\nfeature_subset_df = pd.read_csv(f'{project_dir}/notebooks/shap-importance-rougher-diff_deriv_normalized_with_interaction.csv')\nX_sub = X_filt.copy()\nX_sub.columns = [x.replace(\"\\\"\", \"\") for x in X_sub.columns]\n# Actual model training:\nn_array = np.arange(start=50, stop=feature_subset_df.shape[0], step=100, dtype='int')\nfor N in n_array:\n print(f'Evaluating {N} features !')\n feature_subset = feature_subset_df['feature'].head(N)\n X_sub_check = X_sub[feature_subset]\n trials = Trials()\n\n fpath = f'{project_dir}/models/{N}_feats_rougher_Trials.pkl'\n fpath_csv = f'{project_dir}/models/{N}_feats_rougher_Trials.csv'\n def objective(params):\n params = {\n # 'max_depth': int(params['max_depth']),\n 'num_leaves': int(params['num_leaves']), # int(max(2**(int(params['max_depth'])) - params['num_leaves'],0)),\n 'feature_fraction': \"{:.3f}\".format(params['feature_fraction']),\n 'bagging_fraction': '{:.3f}'.format(params['bagging_fraction']),\n 'lambda_l1': params['lambda_l1']\n # \"min_data_in_leaf\": int(params['min_data_in_leaf'])\n }\n m = lgb.LGBMRegressor(objective='mae',n_jobs=8,\n learning_rate=0.05, n_estimators=900, random_state=9,\n **params)\n print(X_sub_check.shape)\n sc = cv_lgboost(m, X_base=X_sub_check, y=y)\n print(\"Score {:.3f} params {}\".format(sc, params))\n return sc\n\n\n space = {\n # 'max_depth': hp.quniform('max_depth', 2, 8, 1),\n 'num_leaves': hp.quniform('num_leaves', 4, 50, 1),\n 'feature_fraction': hp.uniform('feature_fraction', 0.005, 0.9),\n 'bagging_fraction': hp.uniform('bagging_fraction', 0.1, 1.0),\n 'lambda_l1': hp.uniform('lambda_l1', 0.1, 80)\n # \"min_data_in_leaf\": hp.loguniform(\"min_data_in_leaf\",1,8)\n }\n best_lgbm = fmin(fn=objective,\n space=space,\n algo=tpe.suggest,\n max_evals=80,trials = trials)\n losses = [trials.trials[i]['result']['loss'] for i in range(len(trials.trials))]\n params = pd.DataFrame(trials.vals)\n params['loss'] = losses\n params.sort_values('loss', inplace=True)\n params.to_csv(fpath_csv)\n with open(fpath, 'wb') as f:\n pickle.dump(trials, f)","sub_path":"src/models/hyperopt_model_cv2018_rougher.py","file_name":"hyperopt_model_cv2018_rougher.py","file_ext":"py","file_size_in_byte":3643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}
+{"seq_id":"430592791","text":"class Solution:\n def isValidIP4(self, frame):\n try:\n return (0 <= int(frame) < 256 and str(int(frame)) == frame)\n except Exception:\n return False\n\n def isValidIP6(self, frame):\n try:\n return (0 <= int(frame, 16) < 65536 and len(frame) <= 4 and frame[0] != \"-\")\n except Exception:\n return False\n def validIPAddress(self, IP):\n \"\"\"\n :type IP: str\n :rtype: str\n \"\"\"\n result = \"Neither\"\n v4Frame = IP.split(\".\")\n v6Frame = IP.split(\":\")\n if len(v4Frame) == 4 and all(self.isValidIP4(i) for i in v4Frame):\n return \"IPv4\"\n elif len(v6Frame) == 8 and all(self.isValidIP6(i) for i in v6Frame):\n return \"IPv6\"\n return \"Neither\"\n\n\ns = Solution()\na = \"172.16.254.1\"\nb = \"2001:0db8:85a3:0:0:8A2E:0370:7334\"\nprint(s.validIPAddress(b))","sub_path":"python/468_validIPAddress.py","file_name":"468_validIPAddress.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"22"}