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_('