diff --git "a/367.jsonl" "b/367.jsonl" new file mode 100644--- /dev/null +++ "b/367.jsonl" @@ -0,0 +1,772 @@ +{"seq_id":"396879242","text":"def quicksort(arr, low, high):\n if low >= high:\n return\n else:\n pivot = partition(arr, low, high)\n quicksort(arr, low, pivot-1)\n quicksort(arr, pivot+1, high)\n\ndef partition(arr, low, high):\n pivot = (low+high)//2\n arr[pivot],arr[high] = arr[high],arr[pivot]\n i = low\n for j in range(low,high):\n if arr[j]<=arr[high]:\n arr[i],arr[j]=arr[j],arr[i]\n i+=1\n arr[i],arr[high]=arr[high],arr[i]\n return i\n\ndef find_product(arr,k):\n quicksort(arr,0,len(arr)-1)\n mul = 1\n for i in range(k):\n mul = mul * arr[i]\n return mul\n\n\narr = [198, 76, 544, 123, 154, 675]\nprint(find_product(arr,2))","sub_path":"archive/arrays/Order Statistics/minimum_products.py","file_name":"minimum_products.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"626407813","text":"import unittest\n\nclass Test(unittest.TestCase):\n\n\tdef testIterativeFactorial(self):\n\t\tself.assertEqual(iterative_factorial(5), 120)\n\t\tself.assertEqual(iterative_factorial(0), 1)\n\t\tself.assertEqual(iterative_factorial(1), 1)\n\t\tself.assertEqual(iterative_factorial(10), 3628800)\n\n\tdef testRecursiveFactorial(self):\n\t\tself.assertEqual(recursive_factorial(5), 120)\n\t\tself.assertEqual(recursive_factorial(0), 1)\n\n\tdef testPalindrome(self):\n\t\tself.assertTrue(palindrome('a'))\n\t\tself.assertTrue(palindrome(''))\n\t\tself.assertTrue(palindrome('rotor'))\n\t\tself.assertFalse(palindrome('motor'))\n\n\tdef testRecursivePower(self):\n\t\tself.assertEqual(recursive_power(2, 0), 1)\n\t\tself.assertEqual(recursive_power(2, 1), 2)\n\t\tself.assertEqual(recursive_power(2, 2), 4)\n\t\tself.assertEqual(recursive_power(2, -1), 0.5)\n\t\tself.assertEqual(recursive_power(2, -2), 0.25)\n\ndef iterative_factorial(n):\n\t\"\"\"Function to iteratively calculate the factorial of n\n\n\tParameters\n\t----------\n\tn: int\n\n\tReturns\n\t-------\n\tn_bang: int, factoral of n\n\t\"\"\"\n\tn_bang = 1\n\tfor i in range(1, n+1):\n\t\tn_bang = n_bang * i\n\n\treturn n_bang\n\ndef recursive_factorial(n):\n\t\"\"\"Function to recursively calculate factorial of n\n\n\tParameters\n\t----------\n\tn: int\n\n\tReturns\n\t-------\n\tn_bang: int, factoral of n\n\t\"\"\"\n\tif n == 0:\n\t\tn_bang = 1;\n\telse:\n\t\tn_bang = n * recursive_factorial(n - 1)\n\n\treturn n_bang\n\ndef palindrome(word):\n\t\"\"\"Function to tell if a word is palindrome, returns true if it is\n\n\tParameters\n\t----------\n\tword: string\n\t\"\"\"\n\tif len(word) < 2:\n\t\treturn True\n\telif word[0] == word[-1]:\n\t\treturn palindrome(word[1:-1])\n\telse:\n\t\treturn False\n\ndef recursive_power(x, n):\n\t\"\"\"Function to calculate a number, x, to the power of n recursively\n\n\tParameters\n\t----------\n\tx: int, number to raise to the power of n\n\tn: int, power to raise to\n\t\"\"\"\n\tif n == 0:\n\t\treturn 1\n\telif n < 0:\n\t\treturn 1 / recursive_power(x, -n)\n\telif not (n % 2):\n\t\ty = recursive_power(x, int(n/2))\n\t\treturn y * y\n\telse:\n\t\treturn x * recursive_power(x, n-1)\n\ndef main():\n\tunittest.main()\n\nif __name__ == '__main__':\n\tmain()","sub_path":"recursive.py","file_name":"recursive.py","file_ext":"py","file_size_in_byte":2047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"102125614","text":"# -*- coding: utf-8 -*-\n\"\"\"\nOAuth integration.\n\nSupported grant types\n---------------------\n\n- A client credentials grant using the session and authenticating the client\n with cross-site request forgery tokens.\n\n- A JSON Web Token Bearer Grant using the JSON Web Token Profile for OAuth 2.0\n Client Authentication and Authorization Grants [jwt-bearer]_.\n\n.. [jwt-bearer] https://tools.ietf.org/html/draft-ietf-oauth-jwt-bearer\n\n\nSupported token types\n---------------------\n\n- JSON Web Tokens [jwt]_ as bearer tokens.\n\n.. [jwt] https://tools.ietf.org/html/draft-ietf-oauth-json-web-token\n\nLimitations\n-----------\n\n- No support for 3rd party clients exists yet.\n- No support for scopes yet.\n\n\"\"\"\nimport datetime\n\nimport jwt\nfrom jwt.compat import constant_time_compare\nfrom oauthlib.common import generate_client_id\nfrom oauthlib.oauth2 import RequestValidator as _RequestValidator\nfrom pyramid.exceptions import BadCSRFToken\nfrom pyramid import security\nfrom pyramid import session\n\nfrom pyramid.util import action_method\n\nfrom .interfaces import IClientFactory\nfrom .oauth import JWT_BEARER\nfrom h import accounts\nfrom h.api import groups\n\n\nLEEWAY = 240 # allowance for clock skew in verification\n\n\nclass RequestValidator(_RequestValidator):\n\n \"\"\"Validates JSON Web Tokens.\"\"\"\n\n def client_authentication_required(self, request):\n if request.grant_type == JWT_BEARER:\n return False\n\n return True\n\n def authenticate_client(self, request):\n client = None\n user = None\n\n if request.client_id is None:\n try:\n session.check_csrf_token(request, token='assertion')\n except BadCSRFToken:\n return False\n client_id = request.registry.settings['h.client_id']\n client = get_client(request, client_id)\n user = request.authenticated_userid\n elif request.client_secret is not None:\n client_id = request.client_id\n client_secret = request.client_secret\n client = get_client(request, client_id, client_secret)\n\n request.client = client\n request.user = user\n return request.client is not None\n\n def save_bearer_token(self, token, request):\n # JWT authorization is stateless\n pass\n\n def validate_bearer_token(self, token, scopes, request):\n if token is None:\n return False\n\n try:\n payload = jwt.decode(token, verify=False)\n except jwt.InvalidTokenError:\n return False\n\n aud = request.host_url\n iss = payload['iss']\n sub = payload.get('sub')\n\n client = get_client(request, iss)\n if client is None:\n return False\n\n try:\n payload = jwt.decode(token, key=client.client_secret,\n audience=aud, leeway=LEEWAY,\n algorithms=['HS256'])\n\n except jwt.InvalidTokenError:\n return False\n\n request.client = client\n request.user = sub\n\n return True\n\n def validate_grant_type(self, client_id, grant_type, client, request):\n return True\n\n def get_default_scopes(self, client_id, request):\n return None\n\n def get_original_scopes(self, assertion, request):\n return None\n\n def validate_scopes(self, client_id, scopes, client, request):\n return scopes is None\n\n\ndef auth_domain(request):\n \"\"\"Return the value of the h.auth_domain config settings.\n\n Falls back on returning request.domain if h.auth_domain isn't set.\n\n \"\"\"\n return request.registry.settings.get('h.auth_domain', request.domain)\n\n\ndef groupfinder(userid, request):\n \"\"\"\n Return the list of additional groups of which userid is a member.\n\n Returns a list of group principals of which the passed userid is a member,\n or None if the userid is not known by this application.\n \"\"\"\n principals = set()\n\n user = accounts.get_user(userid, request)\n if user is None:\n return\n\n if user.admin:\n principals.add('group:__admin__')\n if user.staff:\n principals.add('group:__staff__')\n principals.update(groups.group_principals(user))\n\n return list(principals)\n\n\ndef effective_principals(userid, request, groupfinder=groupfinder):\n \"\"\"\n Return the list of effective principals for the passed userid.\n\n Usually, we can leave the computation of the full set of effective\n principals to the pyramid authentication policy. Sometimes, however, it can\n be useful to discover the full set of effective principals for a userid\n other than the current authenticated userid. This function replicates the\n normal behaviour of a pyramid authentication policy and can be used for\n that purpose.\n \"\"\"\n principals = set([security.Everyone])\n\n groups = groupfinder(userid, request)\n if groups is not None:\n principals.add(security.Authenticated)\n principals.add(userid)\n principals.update(groups)\n\n return list(principals)\n\n\ndef generate_signed_token(request):\n \"\"\"Generate a signed JSON Web Token from OAuth attributes of the request.\n\n A JSON Web Token [jwt]_ is a token that contains a header, describing the\n algorithm used for signing, a set of claims (the payload), and a trailing\n signature.\n\n .. [jwt] https://tools.ietf.org/html/draft-ietf-oauth-json-web-token\n \"\"\"\n now = datetime.datetime.utcnow().replace(microsecond=0)\n ttl = datetime.timedelta(seconds=request.expires_in)\n\n claims = {\n 'iss': request.client.client_id,\n 'aud': request.host_url,\n 'sub': request.user,\n 'exp': now + ttl,\n 'iat': now,\n }\n\n claims.update(request.extra_credentials or {})\n return jwt.encode(claims, request.client.client_secret)\n\n\ndef get_client(request, client_id, client_secret=None):\n \"\"\"Get a :class:`h.oauth.IClient` instance using the configured\n :term:`client factory` and provided ''client_id''.\n\n Returns the client object created by the factory. Returns ``None`` if the\n factory returns ``None`` or the provided ``client_secret`` parameter\n does not match the ``client_secret`` attribute of the client.\n \"\"\"\n registry = request.registry\n factory = registry.queryUtility(IClientFactory)\n client = factory(request, client_id)\n\n if client is None:\n return None\n\n # Allow a default client, hard-coded in the settings.\n if 'h.client_id' in request.registry.settings:\n if client_id == request.registry.settings['h.client_id']:\n if client.client_secret is None:\n client_secret = request.registry.settings['h.client_secret']\n client.client_secret = client_secret\n\n if client_secret is not None:\n if not constant_time_compare(client_secret, client.client_secret):\n return None\n\n return client\n\n\n@action_method\ndef set_client_factory(config, factory):\n \"\"\"Override the :term:`client factory` in the current configuration. The\n ``factory`` argument must support the :class:`h.oauth.IClientFactory`\n interface or be a dotted Python name that points to a client factory.\n \"\"\"\n def register():\n impl = config.maybe_dotted(factory)\n config.registry.registerUtility(impl, IClientFactory)\n\n intr = config.introspectable('client factory', None,\n config.object_description(factory),\n 'client factory')\n intr['factory'] = factory\n config.action(IClientFactory, register, introspectables=(intr,))\n\n\nvalidator = RequestValidator()\n\n\ndef includeme(config):\n registry = config.registry\n settings = registry.settings\n\n config.include('pyramid_oauthlib')\n config.add_oauth_param('assertion')\n\n # Use session credentials as a client credentials authorization grant\n config.add_grant_type('oauthlib.oauth2.ClientCredentialsGrant',\n request_validator=validator)\n\n # Use web tokens as an authorization grant\n config.add_grant_type('h.oauth.JWTBearerGrant', JWT_BEARER,\n request_validator=validator)\n\n # Use web tokens for resource authorization\n config.add_token_type('oauthlib.oauth2.BearerToken',\n request_validator=validator,\n token_generator=generate_signed_token)\n\n # Configure a default client factory\n client_class = settings.get('auth.client_factory', 'h.models.Client')\n config.add_directive('set_client_factory', set_client_factory)\n config.set_client_factory(client_class)\n\n # Set default client credentials\n settings.setdefault('h.client_id', generate_client_id())\n settings.setdefault('h.client_secret', generate_client_id())\n\n # Allow retrieval of the auth_domain from the request object\n config.add_request_method(auth_domain, name='auth_domain', reify=True)\n","sub_path":"h/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":8896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"41620887","text":"# not so clever solution in py3 for code eval by steven a dunn\n\nimport sys\n\ndef format(line):\n\tline = line.split(\" | \")\n\tarr = list(map(int, line[0].split()))\n\tn = int(line[1])\n\treturn arr, n\n\ndef stupid_sort(arr):\n\tfor i in range(len(arr) - 1):\n\t\tif arr[i] > arr[i+1]:\n\t\t\ttemp = arr[i]\n\t\t\tarr[i] = arr[i+1]\n\t\t\tarr[i+1] = temp\n\t\t\tbreak\n\treturn arr\n\nf = open(sys.argv[1], 'r')\nfor line in f:\n\tarr, n = format(line)\n\tfor it in range(n):\n\t\tarr = stupid_sort(arr)\n\tprint (\" \".join(list(map(str, arr))))\nf.close()","sub_path":"NotSoClever/py3/nsc.py","file_name":"nsc.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"51089383","text":"try:\n from pip._internal import main as pip_main\nexcept ImportError:\n from pip import main as pip_main\n\nimport click\nimport colorama\nfrom time import sleep\nfrom mdatapipe.core.pipeline import PipelineInfo, Pipeline\nfrom mdatapipe.client.colorhelper import print_info\n\ncolorama.init()\n\n\n@click.command() # NOQA\n@click.argument('file', type=click.Path(exists=False), nargs=-1, required=True)\n@click.option('--fail', '-f', is_flag=True)\n@click.option('--stats-interval', '-s', type=int)\n@click.option('--parallel', '-p', multiple=True)\n@click.option('--silent', is_flag=True)\ndef run(file, fail, stats_interval, parallel, silent):\n\n pipeline_list = []\n\n # Load all pipelines\n for filename in file:\n if not silent:\n print_info(\"Loading pipeline\", filename)\n pipeline = Pipeline(file=filename, parallel=parallel, silent=silent)\n pipeline_list.append(pipeline)\n\n # Start all pipelines\n for pipeline in pipeline_list:\n pipeline.start(fail)\n\n time_to_status = stats_interval\n\n # Loop checking the stats of all pipelines\n total_processes = 1 # Dummy value to start the collect stats loop\n\n try:\n while total_processes > 0:\n if time_to_status:\n time_to_status -= 1\n total_processes = 0\n for pipeline in pipeline_list:\n reques_status = (time_to_status == 0)\n if reques_status:\n pipeline.check_status(reques_status, verbose=True)\n time_to_status = stats_interval\n pipeline_processes = pipeline.get_active_count()\n total_processes += pipeline_processes\n pipeline.check_status(reques_status, verbose=True)\n sleep(1)\n\n except KeyboardInterrupt:\n print(\"\\nInterrupted by user\")\n for pipeline in pipeline_list:\n pipeline.kill()\n\n\n@click.command()\n@click.argument('file', type=click.Path(exists=True), nargs=-1, required=True)\ndef installdeps(file):\n\n # Load all pipelines\n for filename in file:\n\n print_info(\"Loading pipeline\", filename)\n pipeline = PipelineInfo(file=filename)\n # Remove duplicates\n requires = set(pipeline.requires)\n missing = requires\n requires_str = ', '.join(missing)\n if not requires_str:\n print(\"No additional python packages are required.\")\n return\n print_info(\"The following python packages are required:\\n\", requires_str)\n answer = None\n while answer not in ['Y', 'N']:\n answer = input(\"Install now? (Y/N)\").upper()\n if answer == \"N\":\n return\n for package in missing:\n pip_main(['install', package])\n","sub_path":"mdatapipe-old/mdatapipe/client/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":2741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"584084590","text":"from flask import request\nfrom flask_restful import Resource\nfrom ipaddress import IPv4Address\n\nimport cnaas_nms.confpush.init_device\nimport cnaas_nms.confpush.sync_devices\n\nfrom cnaas_nms.api.generic import build_filter, empty_result\nfrom cnaas_nms.db.device import Device, DeviceState, DeviceType\nfrom cnaas_nms.db.linknet import Linknet\nfrom cnaas_nms.db.session import sqla_session\nfrom cnaas_nms.scheduler.scheduler import Scheduler\n\n\nclass DeviceByIdApi(Resource):\n def get(self, device_id):\n result = empty_result()\n result['data'] = {'devices': []}\n with sqla_session() as session:\n instance = session.query(Device).filter(Device.id == device_id).one_or_none()\n if instance:\n result['data']['devices'].append(instance.as_dict())\n else:\n return empty_result('error', \"Device not found\"), 404\n return result\n\n def delete(self, device_id):\n with sqla_session() as session:\n instance = session.query(Device).filter(Device.id == device_id).one_or_none()\n if instance:\n session.delete(instance)\n session.commit()\n return empty_result(), 200\n else:\n return empty_result('error', \"Device not found\"), 404\n\n def put(self, device_id):\n json_data = request.get_json()\n errors = Device.device_update(device_id, **json_data)\n if errors is not None:\n return empty_result(status='error', data=errors), 404\n return empty_result(status='success'), 200\n\n\nclass DevicesApi(Resource):\n def get(self):\n result = empty_result()\n data = {'devices': Device.device_get()}\n return empty_result(status='success', data=data), 200\n\n def post(self):\n json_data = request.get_json()\n data = {}\n errors = []\n data, errors = Device.validate(**json_data)\n if errors != []:\n return empty_result(status='error', data=errors), 404\n with sqla_session() as session:\n instance: Device = session.query(Device).filter(Device.hostname ==\n data['hostname']).one_or_none()\n if instance is not None:\n errors.append('Device already exists')\n return errors\n Device.device_add(**json_data)\n return empty_result(status='success'), 200\n\n\nclass LinknetsApi(Resource):\n def get(self):\n result = {'linknet': []}\n with sqla_session() as session:\n query = session.query(Linknet)\n for instance in query:\n result['linknet'].append(instance.as_dict())\n return empty_result(status='success', data=result)\n\n\nclass DeviceInitApi(Resource):\n def post(self, device_id: int):\n if not isinstance(device_id, int):\n return empty_result(status='error', data=\"'device_id' must be an integer\"), 400\n\n json_data = request.get_json()\n if 'hostname' not in json_data:\n return empty_result(status='error', data=\"POST data must include new 'hostname'\"), 400\n else:\n if not Device.valid_hostname(json_data['hostname']):\n return empty_result(\n status='error',\n data='Provided hostname is not valid'), 400\n else:\n new_hostname = json_data['hostname']\n\n if 'device_type' not in json_data:\n return empty_result(status='error', data=\"POST data must include 'device_type'\"), 400\n else:\n try:\n device_type = str(json_data['device_type']).upper()\n except:\n return empty_result(status='error', data=\"'device_type' must be a string\"), 400\n\n if not DeviceType.has_name(device_type):\n return empty_result(status='error', data=\"Invalid 'device_type' provided\"), 400\n\n if device_type == DeviceType.ACCESS.name:\n scheduler = Scheduler()\n job_id = scheduler.add_onetime_job(\n 'cnaas_nms.confpush.init_device:init_access_device_step1',\n when=1,\n kwargs={'device_id': device_id, 'new_hostname': new_hostname})\n\n res = empty_result(data=f\"Scheduled job to initialize device_id { device_id }\")\n res['job_id'] = job_id\n\n return res\n\n\nclass DeviceSyncApi(Resource):\n def post(self):\n json_data = request.get_json()\n kwargs: dict = {}\n if 'hostname' in json_data:\n hostname = str(json_data['hostname'])\n if not Device.valid_hostname(hostname):\n return empty_result(\n status='error',\n data=f\"Hostname '{hostname}' is not a valid hostname\"\n ), 400\n with sqla_session() as session:\n dev: Device = session.query(Device).\\\n filter(Device.hostname == hostname).one_or_none()\n if not dev or dev.state != DeviceState.MANAGED:\n return empty_result(\n status='error',\n data=f\"Hostname '{hostname}' not found or is not a managed device\"\n ), 400\n kwargs['hostname'] = hostname\n what = hostname\n elif 'device_type' in json_data:\n if DeviceType.has_name(str(json_data['device_type']).upper()):\n kwargs['device_type'] = str(json_data['device_type']).upper()\n else:\n return empty_result(\n status='error',\n data=f\"Invalid device type '{json_data['device_type']}' specified\"\n ), 400\n what = f\"{json_data['device_type']} devices\"\n elif 'all' in json_data and isinstance(json_data['all'], bool) and json_data['all']:\n what = \"all devices\"\n else:\n return empty_result(\n status='error',\n data=f\"No devices to synchronize was specified\"\n ), 400\n\n if 'dry_run' in json_data and isinstance(json_data['dry_run'], bool) \\\n and not json_data['dry_run']:\n kwargs['dry_run'] = False\n if 'force' in json_data and isinstance(json_data['force'], bool):\n kwargs['force'] = json_data['force']\n\n scheduler = Scheduler()\n job_id = scheduler.add_onetime_job(\n 'cnaas_nms.confpush.sync_devices:sync_devices',\n when=1,\n kwargs=kwargs)\n\n res = empty_result(data=f\"Scheduled job to synchronize {what}\")\n res['job_id'] = job_id\n\n return res\n\n","sub_path":"src/cnaas_nms/api/device.py","file_name":"device.py","file_ext":"py","file_size_in_byte":6651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"301996364","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nfrom fit_util import *\nfrom omega_a_fitting import *\nfrom pileup_correction import *\nfrom lost_muon_calculation import *\n\n\n# In[2]:\n\n\nf = r.TFile(\"../truncationTest/data/results_1MissingFile_FullVsTrunc.root\")\nf.cd(\"clustersAndCoincidences\")\nf.ls()\n\n\n# In[3]:\n\n\nclusters = f.Get(\"clustersAndCoincidences\").Get(\"clusters\")\nprint(clusters)\n\n\n# In[4]:\n\n\ne1 = 1700\ne2 = 3100\ncalo = 3\n\nwiggle = MakeWiggleFromTH3(clusters, e1, e2, calo)\n\n\n# In[5]:\n\n\nDumpClass(wiggle)\n\n\n# In[6]:\n\n\n\n# ---\n# \n# ### Now fit the wiggle plot\n\n# In[7]:\n\n\nfitFunc = WiggleFit(GetBlindingPhrase(\"./blinding.txt\"), \"5par\")\n\n\n# In[8]:\n\n\nfitFunc([0],[2+x for x in range(18)])\n\n\n# In[ ]:\n\n\nfit = BuildTF1(fitFunc, 5, \"5par\", \"five_parameter_fit\", 30, 650)\nfit.SetParameters([10000,64.4,0.33,0,0])\nfit.SetParNames()\n\n\n# In[ ]:\n\n\n#fit.f.Draw()\n#c.Draw()\n\n\n# In[ ]:\n\n\nfitter = WiggleFitter(wiggle.h, fit, \"5par\", \"REMB\", 1)\n\n\n# In[ ]:\n\n\nfitter.Fit(2)\n\n\n# In[ ]:\n\n\nDumpClass(fitter)\n\n\n# In[ ]:\n\n\n\n\n# In[ ]:\n\n\n\n\n# In[ ]:\n\n\n\n\n# In[ ]:\n\n\nfitter.f.GetParameter(0)\n\n\n# In[ ]:\n\n\nfitter.Draw()\n\n\n# In[3]:\n\n","sub_path":"fitting/attic/test_wiggle_fit.py","file_name":"test_wiggle_fit.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"230756293","text":"from telegram import (\n InlineKeyboardButton,\n InlineKeyboardMarkup,\n Update,\n ReplyKeyboardRemove,\n)\nfrom telegram.ext import (\n ConversationHandler,\n CallbackContext,\n)\nfrom telegram import ParseMode\n\nRESULTADO, TESTE, ESCOLHA, LINGUAGEM, RESPOSTA, QUIZ = range(6)\n\n\ndef iniciar(update: Update, _: CallbackContext) -> int:\n usuario = update.effective_user\n\n keyboard = [\n [\n InlineKeyboardButton(\"Aprenda mais!\", callback_data=\"aprender\"),\n ],\n [\n InlineKeyboardButton(text=\"Teste seus conhecimentos\", callback_data=\"teste\"),\n ]\n ]\n\n reply_markup = InlineKeyboardMarkup(keyboard)\n\n update.message.reply_text(\n f\"\"\"\nOlá {usuario.name}, sou o NovatoDev! 🚀 💻\n\nAqui irei te ajudar com dúvidas básicas sobre o universo da programação, além de testar seu conhecimento!\nVamos começar?\n\nPara ver meus outros comandos digite /help\n \"\"\",\n reply_markup=reply_markup,\n parse_mode=ParseMode.HTML,\n )\n\n return ESCOLHA\n\n\ndef cancelar(update: Update, _: CallbackContext) -> int:\n update.message.reply_text(\n 'Até mais, espero que tenha aprendido muito! 🖖', reply_markup=ReplyKeyboardRemove()\n )\n\n return ConversationHandler.END\n\ndef ajudar(update: Update, _: CallbackContext) -> int:\n update.message.reply_text(\n \"\"\"\nComandos disponíveis:\n\n/cancelar Finaliza a conversa comigo 😢\n\n/voltar Reinicia a conversa\n\n \"\"\",\n reply_markup=ReplyKeyboardRemove(),\n parse_mode=ParseMode.HTML\n )\n\n\ndef iniciar_quiz(update: Update, _: CallbackContext) -> None:\n usuario = update.effective_user\n\n query = update.callback_query\n\n query.answer()\n\n # Cria lista com as opções para escolher\n opcoes = [\n [\n InlineKeyboardButton(\"BÓRA\", callback_data='bora'),\n ],\n ]\n\n # Monta o teclado com as opçoes\n teclado_com_opcoes = InlineKeyboardMarkup(opcoes)\n\n query.edit_message_text(\n f'''Eae {usuario.name}!\n\nPronto para iniciar o teste? 🧠\n ''',\n parse_mode=ParseMode.HTML,\n reply_markup=teclado_com_opcoes\n )\n\n return QUIZ\n","sub_path":"modulos/comandos/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"245338553","text":"outputTemp = 0;\ndef CtoFtoC_Conversion(inputTemp, outputTempType, isReturn):\n \"\"\"This method converts to Celsius if given a Farhaniet and vice versa.\n inputTemp = The input temperature value.\n outputTempType = Type of output temperature required.\n isReturn = Whether output is required in return.\"\"\"\n if outputTempType == 1:\n outputTemp = (inputTemp - 32) * 5 / 9;\n else:\n outputTemp = (9 * inputTemp / 5) + 32;\n if isReturn:\n return outputTemp;\n else:\n print(outputTemp, outputTempType);\n exit();\n\ndef CtoKtoC_Conversion(inputTemp, outputTempType, isReturn):\n \"\"\"This method converts to Celsius if given a Kelvin and vice versa.\n inputTemp = The input temperature value.\n outputTempType = Type of output temperature required.\n isReturn = Whether output is required in return.\"\"\"\n if outputTempType == 1:\n outputTemp = inputTemp + 273;\n else:\n outputTemp = inputTemp - 273;\n if isReturn:\n return outputTemp;\n else:\n print(outputTemp, outputTempType);\n exit();\n \ndef FtoKtoF_Conversion(inputTemp, outputTempType, isReturn):\n \"\"\"This method converts to Farhaniet if given a Kelvin and vice versa.\n inputTemp = The input temperature value.\n outputTempType = Type of output temperature required.\n isReturn = Whether output is required in return.\"\"\"\n if outputTempType == 3:\n intermediateTemp = CtoKtoC_Conversion(inputTemp, outputTempType, True);\n CtoFtoC_Conversion(intermediateTemp, outputTempType, False);\n else:\n intermediateTemp = CtoFtoC_Conversion(inputTemp, outputTempType, True);\n CtoFtoC_Conversion(inputTemp, outputTempType, False);\n\nioTemperatureDictionary = {\n 'Celsius_Farhaniet': CtoFtoC_Conversion,\n 'C_Farheniet': CtoFtoC_Conversion,\n 'C_F': CtoFtoC_Conversion,\n 'Celsius_F': CtoFtoC_Conversion,\n 'Farhaniet_Celsius': CtoFtoC_Conversion,\n 'F_Celsius': CtoFtoC_Conversion,\n 'F_C': CtoFtoC_Conversion,\n 'Farhaniet_C': CtoFtoC_Conversion,\n 'Kelvin_Celsius': CtoKtoC_Conversion,\n 'Kelvin_C': CtoKtoC_Conversion,\n 'K_Celsius': CtoKtoC_Conversion,\n 'K_C': CtoKtoC_Conversion,\n 'Celsius_Kelvin': CtoKtoC_Conversion,\n 'Celsius_K': CtoKtoC_Conversion,\n 'C_Kelvin': CtoKtoC_Conversion,\n 'C_K': CtoKtoC_Conversion,\n 'Farhaniet_Kelvin': FtoKtoF_Conversion,\n 'Farhaniet_K': FtoKtoF_Conversion,\n 'F_Kelvin': FtoKtoF_Conversion,\n 'F_K': FtoKtoF_Conversion,\n 'Kelvin_Farhaniet': FtoKtoF_Conversion,\n 'Kelvin_F': FtoKtoF_Conversion,\n 'K_Farhaniet': FtoKtoF_Conversion,\n 'K_F': FtoKtoF_Conversion,\n};\n\noutputTemperatureTypeDictionary = {\n 'Celsius': 1,\n 'C': 1,\n 'Kelvin': 2,\n 'K': 2,\n 'Farhaniet': 3,\n 'F': 3\n}\n\ninputTempType = input('Enter your input temperature type(Celsius/C, Kelvin/K, Farhaniet/F):');\noutputTempType = input('Enter the output temperature type(Celsius, Kelvin, Farhaniet):');\ninputTemp = int(input('Enter your input temperature:'));\n\nif inputTempType == outputTempType:\n print('Duh! I am not a fool you know...');\n exit();\n\nioKey = inputTempType + '_' + outputTempType;\nif ioKey not in ioTemperatureDictionary.keys() or outputTempType not in outputTemperatureTypeDictionary.keys():\n print('Cannot perform the conversion');\n exit();\nprint(ioTemperatureDictionary[ioKey]);\nioTemperatureDictionary[ioKey](inputTemp, outputTemperatureTypeDictionary[outputTempType], False);","sub_path":"Exception/exception.py","file_name":"exception.py","file_ext":"py","file_size_in_byte":3482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"29145814","text":"\"\"\"\nCopyright Riley Hales\nApril 6 2020\n\"\"\"\nimport netCDF4\nimport xarray\nimport numpy as np\nimport os\nimport pandas as pd\nimport sys\nimport logging\nimport datetime\nimport plotly.graph_objs as go\n\n\ndef aggregate_by_day(path_Qout, write_frequency=500):\n # sort out the file paths\n if not os.path.isfile(path_Qout):\n raise FileNotFoundError('Qout file not found at this path')\n newfilepath = os.path.join(os.path.dirname(path_Qout), 'DailyAggregated_' + os.path.basename(path_Qout) + '4')\n\n # read the netcdfs\n source_nc = netCDF4.Dataset(filename=path_Qout, mode='r')\n new_nc = netCDF4.Dataset(filename=newfilepath, mode='w')\n\n # create rivid and time dimensions\n logging.info('creating new netcdf variables/dimensions')\n new_nc.createDimension('rivid', size=source_nc.dimensions['rivid'].size)\n new_nc.createDimension('time', size=source_nc.dimensions['time'].size // 24)\n # create rivid and time variables\n new_nc.createVariable('rivid', datatype='f4', dimensions=('rivid',))\n new_nc.createVariable('time', datatype='f4', dimensions=('time',))\n # create the variables for the flows\n # new_nc.createVariable('Qout_min', datatype='f4', dimensions=('time', 'rivid'))\n new_nc.createVariable('Qout', datatype='f4', dimensions=('time', 'rivid'))\n # new_nc.createVariable('Qout_max', datatype='f4', dimensions=('time', 'rivid'))\n\n # configure the time variable\n new_nc.variables['time'][:] = range(new_nc.dimensions['time'].size)\n new_nc.variables['time'].__dict__['units'] = 'days since 1979-01-01 00:00:00+00:00'\n new_nc.variables['time'].__dict__['calendar'] = 'gregorian'\n\n # configure the rivid variable\n new_nc.variables['rivid'][:] = source_nc.variables['rivid'][:]\n\n # collect information used to create iteration parameters\n num_rivers = source_nc.dimensions['rivid'].size\n number_hours = source_nc.variables['time'].shape[0]\n if number_hours == 350641:\n logging.info('----WARNING---- TIME 350641 (expected 350640)')\n exact = False\n elif number_hours == 350640:\n exact = True\n else:\n raise RuntimeError('unexpected length of times found.')\n number_days = number_hours // 24\n logging.info('number of rivers: ' + str(num_rivers))\n\n # create a set of indices for slicing the array in larger groups\n indices = list(range(num_rivers))\n index_pairs = []\n while len(indices) > 0:\n arr = indices[:write_frequency]\n index_pairs.append((arr[0], arr[-1]))\n indices = indices[write_frequency:]\n number_groups = len(index_pairs)\n\n for group_num, pairs in enumerate(index_pairs):\n start_index = pairs[0]\n end_index = pairs[1]\n logging.info('Started group ' + str(group_num) + '/' + str(number_groups) + ' -- ' + datetime.datetime.utcnow().strftime(\"%c\"))\n\n # depending on the version of rapid used, the dimension order is different\n if source_nc.variables['Qout'].dimensions == ('time', 'rivid'):\n if exact:\n arr = np.asarray(source_nc.variables['Qout'][:, start_index:end_index])\n elif not exact:\n arr = np.asarray(source_nc.variables['Qout'][0:350640, start_index:end_index])\n elif source_nc.variables['Qout'].dimensions == ('rivid', 'time'):\n if exact:\n arr = np.transpose(np.asarray(source_nc.variables['Qout'][start_index:end_index, :]))\n elif not exact:\n arr = np.transpose(np.asarray(source_nc.variables['Qout'][start_index:end_index, 0:350640]))\n else:\n logging.info('Unable to recognize the dimension order, exiting')\n exit()\n\n logging.info(arr.shape)\n\n # min_arr = []\n mean_arr = []\n # max_arr = []\n\n # if the array is at least 'size' long\n logging.info('splitting the array into {0} days'.format(number_days))\n for day_flows in np.split(arr, number_days):\n # min_arr.append(day_flows.min(axis=0))\n mean_arr.append(day_flows.mean(axis=0))\n # max_arr.append(day_flows.max(axis=0))\n\n # min_arr = np.asarray(min_arr)\n mean_arr = np.asarray(mean_arr)\n # max_arr = np.asarray(max_arr)\n\n # logging.info(min_arr.shape)\n logging.info(mean_arr.shape)\n # logging.info(max_arr.shape)\n\n # logging.info(' writing Qmin group')\n # new_nc.variables['Qout_min'][:, start_index:end_index] = min_arr\n logging.info(' writing Qout group')\n new_nc.variables['Qout'][:, start_index:end_index] = mean_arr\n # logging.info(' writing Qmax group')\n # new_nc.variables['Qout_max'][:, start_index:end_index] = max_arr\n new_nc.sync()\n\n # close the new netcdf\n new_nc.close()\n source_nc.close()\n\n logging.info('')\n logging.info('FINISHED')\n logging.info(datetime.datetime.utcnow().strftime(\"%D at %R\"))\n return newfilepath\n\n\ndef validate_aggregated_rivid(path_Qout, path_Aggregated_qout, rivid=None):\n old_xar = xarray.open_dataset(path_Qout)\n new_xar = xarray.open_dataset(path_Aggregated_qout)\n\n if not rivid:\n rivid = int(np.random.choice(new_xar.variables['rivid'], 1))\n\n old_times = pd.to_datetime(pd.Series(old_xar.sel(rivid=rivid).time))\n oldflow = np.asarray(old_xar.sel(rivid=rivid).Qout)\n new_times = np.asarray(new_xar.sel(rivid=rivid).time)\n newmin = np.asarray(new_xar.sel(rivid=rivid).Qout_min)\n newmean = np.asarray(new_xar.sel(rivid=rivid).Qout_mean)\n newmax = np.asarray(new_xar.sel(rivid=rivid).Qout_max)\n\n start = datetime.datetime(year=1979, month=1, day=1)\n new_times = [start + datetime.timedelta(days=int(i)) for i in new_times]\n\n new_scatter_min = go.Scatter(\n name='new_data_min',\n x=new_times,\n y=list(newmin),\n line={'color': 'yellow'}\n )\n new_scatter_mean = go.Scatter(\n name='new_data_mean',\n x=new_times,\n y=list(newmean),\n line={'color': 'black'}\n )\n new_scatter_max = go.Scatter(\n name='new_data_max',\n x=new_times,\n y=list(newmax),\n line={'color': 'blue'}\n )\n old_scatter = go.Scatter(\n name='old_flow',\n x=old_times,\n y=list(oldflow),\n line={'color': 'red'}\n )\n layout = go.Layout(\n title='Aggregation Comparison',\n xaxis={'title': 'Date', 'range': [10000, 15000]},\n yaxis={'title': 'Streamflow (m3/s)'},\n )\n\n figure = go.Figure((new_scatter_min, new_scatter_mean, new_scatter_max, old_scatter), layout=layout)\n figure.show()\n\n return\n\n\n# for running this script from the command line with a script\nif __name__ == '__main__':\n \"\"\"\n sys.argv[0] this script e.g. aggregate.py\n sys.argv[1] path to Qout file\n sys.argv[2] path to log file\n \"\"\"\n # enable logging to track the progress of the workflow and for debugging\n logging.basicConfig(filename=sys.argv[2], filemode='w', level=logging.INFO, format='%(message)s')\n logging.info('ERA5 aggregation started on ' + datetime.datetime.utcnow().strftime(\"%D at %R\"))\n aggregated_file = aggregate_by_day(sys.argv[1], write_frequency=1000)\n # validate_aggregated_rivid(sys.argv[1], aggregated_file)\n","sub_path":"era5/optimized_aggregate.py","file_name":"optimized_aggregate.py","file_ext":"py","file_size_in_byte":7230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"532514005","text":"import bs4\nimport requests\n\nfrom voussoirkit import vlogging\n\nfrom . import exceptions\n\nlog = vlogging.getLogger(__name__)\n\nsession = requests.Session()\n\ndef _get_user_videos(channel_id):\n log.info(f'Fetching RSS for {channel_id}.')\n url = f'https://www.youtube.com/feeds/videos.xml?channel_id={channel_id}'\n response = session.get(url)\n response.raise_for_status()\n soup = bs4.BeautifulSoup(response.text, 'lxml')\n # find_all does not work on namespaced tags unless you add a limit paramter.\n video_ids = [v.text for v in soup.find_all('yt:videoid', limit=9999)]\n log.loud('RSS got %s.', video_ids)\n return video_ids\n\ndef get_user_videos(channel_id):\n try:\n return _get_user_videos(channel_id)\n except Exception:\n raise exceptions.RSSAssistFailed(f'Failed to fetch RSS videos.') from exc\n\ndef get_user_videos_since(channel_id, video_id):\n video_ids = get_user_videos(channel_id)\n try:\n index = video_ids.index(video_id)\n except ValueError:\n raise exceptions.RSSAssistFailed(f'RSS didn\\'t contain {video_id}.')\n video_ids = video_ids[:index]\n log.loud('Since %s: %s', video_id, str(video_ids))\n return video_ids\n","sub_path":"ycdl/ytrss.py","file_name":"ytrss.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"383543199","text":"import ctypes\nimport collections\nimport heapq\nimport os.path\nimport time\nfrom sys import platform\nfrom consts import MAX_LABEL_COST\n\nif platform.startswith('win32'):\n _dll_file = os.path.join(os.path.dirname(__file__), 'bin/path_engine.dll')\nelse:\n raise Exception('Please build the shared library compatible to your OS\\\n using source files in engine_cpp!')\n\n_cdll = ctypes.cdll.LoadLibrary(_dll_file)\n\n# set up the argument types for the shortest path function in dll.\n_cdll.shortest_path.argtypes = [\n ctypes.c_int,\n ctypes.c_int,\n ctypes.POINTER(ctypes.c_int),\n ctypes.POINTER(ctypes.c_int),\n ctypes.POINTER(ctypes.c_int),\n ctypes.POINTER(ctypes.c_int),\n ctypes.POINTER(ctypes.c_int),\n ctypes.POINTER(ctypes.c_wchar_p),\n ctypes.POINTER(ctypes.c_double),\n ctypes.POINTER(ctypes.c_double),\n ctypes.POINTER(ctypes.c_int),\n ctypes.POINTER(ctypes.c_int),\n ctypes.POINTER(ctypes.c_int),\n ctypes.c_wchar_p,\n ctypes.c_int,\n ctypes.c_int,\n ctypes.c_int\n]\n\n\n\ndef single_source_shortest_path(G, origin_node_id,\n engine_type='c', sp_algm='deque'):\n origin_node_no = G.get_node_no(origin_node_id)\n\n if engine_type.lower() == 'c':\n G.allocate_for_CAPI()\n #time_start = time.time()\n _optimal_label_correcting_CAPI(G, origin_node_no)\n #time_end = time.time()\n else:\n # just in case user uses C++ and Python path engines in a mixed way\n G.has_capi_allocated = False\n\n # Initialization for all nodes\n G.node_label_cost = [MAX_LABEL_COST] * G.node_size\n # pointer to previous node index from the current label at current node\n G.node_predecessor = [-1] * G.node_size\n # pointer to previous node index from the current label at current node\n G.link_predecessor = [-1] * G.node_size\n\n # make sure node_label_cost, node_predecessor, and link_predecessor\n # are initialized even the source node has no outgoing links\n if not G.node_list[origin_node_no].outgoing_link_list:\n return\n\ndef _get_path_cost(G, to_node_id):\n to_node_no = G.node_id_to_no_dict[to_node_id]\n\n return G.node_label_cost[to_node_no]\n\n\ndef _optimal_label_correcting_CAPI(G,\n origin_node_no,\n departure_time=0):\n \"\"\" call the deque implementation of MLC written in cpp\n\n node_label_cost, node_predecessor, and link_predecessor are still\n initialized in shortest_path() even the source node has no outgoing links.\n \"\"\"\n _cdll.shortest_path_n(origin_node_no,\n G.get_node_size(),\n G.get_from_node_no_arr(),\n G.get_to_node_no_arr(),\n G.get_first_links(),\n G.get_last_links(),\n G.get_sorted_link_no_arr(),\n G.get_allowed_uses(),\n G.get_link_costs(),\n G.get_node_label_costs(),\n G.get_node_preds(),\n G.get_link_preds(),\n G.get_queue_next(),\n G.get_agent_type_name(),\n MAX_LABEL_COST,\n G.get_last_thru_node(),\n departure_time)\n\n\n","sub_path":"Path4GMNS-Part4-by-GTZ/shortestpath.py","file_name":"shortestpath.py","file_ext":"py","file_size_in_byte":3394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"55507619","text":"import logging\nfrom typing import Dict, List\n\nimport braintree as braintree_sdk\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.utils.translation import pgettext_lazy\n\nfrom ... import TransactionKind\nfrom ...interface import (\n CreditCardInfo,\n CustomerSource,\n GatewayConfig,\n GatewayResponse,\n PaymentData,\n TokenConfig,\n)\nfrom .errors import DEFAULT_ERROR_MESSAGE, BraintreeException\nfrom .forms import BraintreePaymentForm\n\nlogger = logging.getLogger(__name__)\n\n\n# FIXME: Move to SiteSettings\n\n# If this option is checked, then one needs to authorize the amount paid\n# manually via the Braintree Dashboard\nCONFIRM_MANUALLY = False\nTHREE_D_SECURE_REQUIRED = False\n\n# Error codes whitelist should be a dict of code: error_msg_override\n# if no error_msg_override is provided,\n# then error message returned by the gateway will be used\nERROR_CODES_WHITELIST = {\n \"91506\": \"\"\"\n Cannot refund transaction unless it is settled.\n Please try again later. Settlement time might vary depending\n on the issuers bank.\"\"\"\n}\n\n\ndef get_customer_data(payment_information: PaymentData) -> Dict:\n \"\"\"Provides customer info, use only for new customer creation\"\"\"\n billing = payment_information.billing\n return {\n \"order_id\": payment_information.order_id,\n \"billing\": {\n \"first_name\": billing.first_name,\n \"last_name\": billing.last_name,\n \"company\": billing.company_name,\n \"postal_code\": billing.postal_code,\n \"street_address\": billing.street_address_1,\n \"extended_address\": billing.street_address_2,\n \"locality\": billing.city,\n \"region\": billing.country_area,\n \"country_code_alpha2\": billing.country,\n },\n \"risk_data\": {\"customer_ip\": payment_information.customer_ip_address or \"\"},\n \"customer\": {\"email\": payment_information.customer_email},\n }\n\n\ndef get_error_for_client(errors: List) -> str:\n \"\"\"Filters all error messages and decides which one is visible for the\n client side.\n \"\"\"\n if not errors:\n return \"\"\n default_msg = pgettext_lazy(\n \"payment error\", \"Unable to process transaction. Please try again in a moment\"\n )\n for error in errors:\n if error[\"code\"] in ERROR_CODES_WHITELIST:\n return ERROR_CODES_WHITELIST[error[\"code\"]] or error[\"message\"]\n return default_msg\n\n\ndef extract_gateway_response(braintree_result) -> Dict:\n \"\"\"Extract data from Braintree response that will be stored locally.\"\"\"\n errors = []\n if not braintree_result.is_success:\n errors = [\n {\"code\": error.code, \"message\": error.message}\n for error in braintree_result.errors.deep_errors\n ]\n bt_transaction = braintree_result.transaction\n\n if not bt_transaction:\n return {\"errors\": errors}\n return {\n \"transaction_id\": getattr(bt_transaction, \"id\", \"\"),\n \"currency\": bt_transaction.currency_iso_code,\n \"amount\": bt_transaction.amount, # Decimal type\n \"credit_card\": bt_transaction.credit_card,\n \"customer_id\": bt_transaction.customer_details.id,\n \"errors\": errors,\n }\n\n\ndef create_form(data, payment_information, connection_params):\n return BraintreePaymentForm(data=data, payment_information=payment_information)\n\n\ndef get_braintree_gateway(sandbox_mode, merchant_id, public_key, private_key):\n if not all([merchant_id, private_key, public_key]):\n raise ImproperlyConfigured(\"Incorrectly configured Braintree gateway.\")\n environment = braintree_sdk.Environment.Sandbox\n if not sandbox_mode:\n environment = braintree_sdk.Environment.Production\n\n config = braintree_sdk.Configuration(\n environment=environment,\n merchant_id=merchant_id,\n public_key=public_key,\n private_key=private_key,\n )\n gateway = braintree_sdk.BraintreeGateway(config=config)\n return gateway\n\n\ndef get_client_token(config: GatewayConfig, token_config: TokenConfig = None) -> str:\n gateway = get_braintree_gateway(**config.connection_params)\n if not token_config:\n return gateway.client_token.generate()\n parameters = create_token_params(config, token_config)\n return gateway.client_token.generate(parameters)\n\n\ndef create_token_params(config: GatewayConfig, token_config: TokenConfig) -> dict:\n params = {}\n customer_id = token_config.customer_id\n if customer_id and config.store_customer:\n params[\"customer_id\"] = customer_id\n return params\n\n\ndef authorize(\n payment_information: PaymentData, config: GatewayConfig\n) -> GatewayResponse:\n try:\n if not payment_information.customer_id:\n result = transaction_for_new_customer(payment_information, config)\n else:\n result = transaction_for_existing_customer(payment_information, config)\n except braintree_sdk.exceptions.NotFoundError:\n raise BraintreeException(DEFAULT_ERROR_MESSAGE)\n\n gateway_response = extract_gateway_response(result)\n error = get_error_for_client(gateway_response[\"errors\"])\n kind = TransactionKind.CAPTURE if config.auto_capture else TransactionKind.AUTH\n return GatewayResponse(\n is_success=result.is_success,\n kind=kind,\n amount=gateway_response.get(\"amount\", payment_information.amount),\n currency=gateway_response.get(\"currency\", payment_information.currency),\n customer_id=gateway_response.get(\"customer_id\"),\n transaction_id=gateway_response.get(\n \"transaction_id\", payment_information.token\n ),\n error=error,\n raw_response=gateway_response,\n )\n\n\ndef transaction_for_new_customer(\n payment_information: PaymentData, config: GatewayConfig\n):\n gateway = get_braintree_gateway(**config.connection_params)\n return gateway.transaction.sale(\n {\n \"amount\": str(payment_information.amount),\n \"payment_method_nonce\": payment_information.token,\n \"options\": {\n \"submit_for_settlement\": config.auto_capture,\n \"store_in_vault_on_success\": payment_information.reuse_source,\n \"three_d_secure\": {\"required\": THREE_D_SECURE_REQUIRED},\n },\n **get_customer_data(payment_information),\n }\n )\n\n\ndef transaction_for_existing_customer(\n payment_information: PaymentData, config: GatewayConfig\n):\n gateway = get_braintree_gateway(**config.connection_params)\n return gateway.transaction.sale(\n {\n \"amount\": str(payment_information.amount),\n \"customer_id\": payment_information.customer_id,\n \"options\": {\"submit_for_settlement\": config.auto_capture},\n **get_customer_data(payment_information),\n }\n )\n\n\ndef capture(payment_information: PaymentData, config: GatewayConfig) -> GatewayResponse:\n gateway = get_braintree_gateway(**config.connection_params)\n\n try:\n result = gateway.transaction.submit_for_settlement(\n transaction_id=payment_information.token,\n amount=str(payment_information.amount),\n )\n except braintree_sdk.exceptions.NotFoundError:\n raise BraintreeException(DEFAULT_ERROR_MESSAGE)\n\n gateway_response = extract_gateway_response(result)\n error = get_error_for_client(gateway_response[\"errors\"])\n\n return GatewayResponse(\n is_success=result.is_success,\n kind=TransactionKind.CAPTURE,\n amount=gateway_response.get(\"amount\", payment_information.amount),\n currency=gateway_response.get(\"currency\", payment_information.currency),\n transaction_id=gateway_response.get(\n \"transaction_id\", payment_information.token\n ),\n error=error,\n raw_response=gateway_response,\n )\n\n\ndef void(payment_information: PaymentData, config: GatewayConfig) -> GatewayResponse:\n gateway = get_braintree_gateway(**config.connection_params)\n\n try:\n result = gateway.transaction.void(transaction_id=payment_information.token)\n except braintree_sdk.exceptions.NotFoundError:\n raise BraintreeException(DEFAULT_ERROR_MESSAGE)\n\n gateway_response = extract_gateway_response(result)\n error = get_error_for_client(gateway_response[\"errors\"])\n\n return GatewayResponse(\n is_success=result.is_success,\n kind=TransactionKind.VOID,\n amount=gateway_response.get(\"amount\", payment_information.amount),\n currency=gateway_response.get(\"currency\", payment_information.currency),\n transaction_id=gateway_response.get(\n \"transaction_id\", payment_information.token\n ),\n error=error,\n raw_response=gateway_response,\n )\n\n\ndef refund(payment_information: PaymentData, config: GatewayConfig) -> GatewayResponse:\n gateway = get_braintree_gateway(**config.connection_params)\n\n try:\n result = gateway.transaction.refund(\n transaction_id=payment_information.token,\n amount_or_options=str(payment_information.amount),\n )\n except braintree_sdk.exceptions.NotFoundError:\n raise BraintreeException(DEFAULT_ERROR_MESSAGE)\n\n gateway_response = extract_gateway_response(result)\n error = get_error_for_client(gateway_response[\"errors\"])\n\n return GatewayResponse(\n is_success=result.is_success,\n kind=TransactionKind.REFUND,\n amount=gateway_response.get(\"amount\", payment_information.amount),\n currency=gateway_response.get(\"currency\", payment_information.currency),\n transaction_id=gateway_response.get(\n \"transaction_id\", payment_information.token\n ),\n error=error,\n raw_response=gateway_response,\n )\n\n\ndef process_payment(\n payment_information: PaymentData, config: GatewayConfig\n) -> GatewayResponse:\n auth_resp = authorize(payment_information, config)\n return auth_resp\n\n\ndef list_client_sources(\n config: GatewayConfig, customer_id: str\n) -> List[CustomerSource]:\n gateway = get_braintree_gateway(**config.connection_params)\n customer = gateway.customer.find(customer_id)\n if not customer:\n return []\n return [\n extract_credit_card_data(card, \"braintree\") for card in customer.credit_cards\n ]\n\n\ndef extract_credit_card_data(card, gateway_name):\n credit_card = CreditCardInfo(\n exp_year=int(card.expiration_year),\n exp_month=int(card.expiration_month),\n last_4=card.last_4,\n name_on_card=card.cardholder_name,\n )\n return CustomerSource(\n id=card.unique_number_identifier,\n gateway=gateway_name,\n credit_card_info=credit_card,\n )\n","sub_path":"saleor/payment/gateways/braintree/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":10635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"542750630","text":"import unittest2 as unittest\nimport numpy as np\nimport rdflib\nfrom osp.core.ontology.cuba import rdflib_cuba\nfrom osp.core.session.db.sql_wrapper_session import \\\n SqlWrapperSession\n\nEXPANDED_COLS = ['1',\n '2___0', '2___1',\n '3___0', '3___1', '3___2',\n '3___3', '3___4', '3___5']\nEXPANDED_DTYPES = {'1': rdflib.XSD.integer,\n '2': rdflib_cuba[\"datatypes/VECTOR-2\"],\n '2___0': rdflib.XSD.float, '2___1': rdflib.XSD.float,\n '3': rdflib_cuba[\"datatypes/VECTOR-2-3\"],\n '3___0': rdflib.XSD.float, '3___1': rdflib.XSD.float,\n '3___2': rdflib.XSD.float, '3___3': rdflib.XSD.float,\n '3___4': rdflib.XSD.float, '3___5': rdflib.XSD.float}\nEXPANDED_VALS = [100, 1, 2, 1, 2, 3, 2, 3, 4]\nVALS = [100, np.array([1, 2]), np.array([[1, 2, 3], [2, 3, 4]])]\n\n\nclass TestSqliteCity(unittest.TestCase):\n\n def test_expand_vector_cols(self):\n cols, dtypes, vals = SqlWrapperSession._expand_vector_cols(\n columns=[\"1\", \"2\", \"3\"],\n datatypes={\"1\": rdflib.XSD.integer,\n \"2\": rdflib_cuba[\"datatypes/VECTOR-2\"],\n \"3\": rdflib_cuba[\"datatypes/VECTOR-2-3\"]},\n values=VALS\n )\n self.assertEqual(cols, EXPANDED_COLS)\n self.assertEqual(dtypes, EXPANDED_DTYPES)\n self.assertEqual(vals, EXPANDED_VALS)\n\n def test_contract_vector_values(self):\n r = SqlWrapperSession._contract_vector_values(EXPANDED_COLS,\n EXPANDED_DTYPES,\n [EXPANDED_VALS])\n np.testing.assert_equal(next(r), VALS)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_sql_wrapper_session.py","file_name":"test_sql_wrapper_session.py","file_ext":"py","file_size_in_byte":1790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"554744400","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Date : 2019-04-10 14:44:32\n# @Author : BenLam\n# @Link : https://www.cnblogs.com/BenLam/\n# @File : save_excel.py\n\nimport xlrd\nfrom Public.log import LOG,logger\n\n# Setting xls column valuekey\ntest_id = 0\ntest_name = 1\ntest_key = 2\ntest_coneent = 3\ntest_url = 4\ntest_fangshi = 5\ntest_qiwang = 6\nwrite_return_data = 7\n\n@logger('保存测试用例文件')\ndef read(filrpath):\n try:\n file=xlrd.open_workbook(filrpath)\n me=file.sheets()[0]\n nrows=me.nrows\n ID=[]\n listkey=[]\n listconeent=[]\n listurl=[]\n listfangshi=[]\n listqiwang=[]\n listrelut=[]\n listname=[]\n for i in range(1,nrows):\n ID.append(me.cell(i,test_id).value)\n listname.append(me.cell(i,test_name).value)\n listkey.append(me.cell(i,test_key).value)\n listconeent.append(me.cell(i,test_coneent).value)\n listurl.append(me.cell(i,test_url).value)\n listfangshi.append((me.cell(i,test_fangshi).value))\n listqiwang.append((me.cell(i,test_qiwang).value))\n return ID,listkey,listconeent,listurl,listfangshi,listqiwang,listname\n except Exception as e:\n LOG.info('打开测试用例失败,原因是:%s'%e)\n return\n\ndef _datacel(filrpath):\n try:\n all_case=[]\n file=xlrd.open_workbook(filrpath)\n me=file.sheets()[0]\n nrows=me.nrows\n for i in range(1,nrows):\n all_case.append({\"id\":me.cell(i,0).value,'key':me.cell(i,2).value,\n 'coneent':me.cell(i,3).value,'url':me.cell(i,4).value,\n 'name':me.cell(i,1).value,'fangshi':me.cell(i,5).value,\n 'assert':me.cell(i,6).value})\n return all_case\n except Exception as e:\n LOG.info('打开测试用例失败,原因是:%s'%e)\n return\n\n\nfrom xlutils.copy import copy\n@logger('写入返回值')\ndef write(filrpath, row, value):\n '''\n # 写入到excel数据\n # 行,\n # 列,\n # 写入 value.\n '''\n try:\n read_data = xlrd.open_workbook(filrpath)\n write_data = copy(read_data)\n sheet_data = write_data.get_sheet(0)\n sheet_data.write(row, write_return_data, str(value))\n write_data.save(filrpath)\n\n except Exception as e:\n LOG.info('写入测试用例返回值失败,原因是:%s' %e)\n return\n\n\nif __name__ == '__main__':\n # print(datacel(a))\n a = r\"..//test_case_data//case.xlsx\"\n b = {\"a\":1}\n write_value(a,b)","sub_path":"Public/save_excel.py","file_name":"save_excel.py","file_ext":"py","file_size_in_byte":2581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"653993658","text":"# encoding: utf8\n#\n# This file is part of the Neurons project.\n# Copyright (c), Burak Arslan ,\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# * Neither the name of the {organization} nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n\n\nfrom spyne import ModelBase\nfrom spyne.protocol.html import HtmlColumnTable\nfrom spyne.util.cdict import cdict\n\nfrom neurons.form.form import HtmlForm\n\n\nclass HtmlFormTable(HtmlColumnTable):\n def __init__(self, app=None, ignore_uncap=False, ignore_wrappers=False,\n cloth=None, attr_name='spyne_id', root_attr_name='spyne',\n cloth_parser=None):\n\n super(HtmlFormTable, self).__init__(app=app,\n ignore_uncap=ignore_uncap, ignore_wrappers=ignore_wrappers,\n cloth=cloth, attr_name=attr_name, root_attr_name=root_attr_name,\n cloth_parser=cloth_parser)\n\n self.serialization_handlers = cdict({\n ModelBase: self.model_base_to_parent,\n })\n\n self.prot_form = HtmlForm()\n\n def model_base_to_parent(self, ctx, cls, inst, parent, name, array_index=None,\n from_arr=False, **kwargs):\n if from_arr:\n with parent.element('tr'):\n with parent.element('td'):\n self.prot_form.to_parent(ctx, cls, inst, parent, name, **kwargs)\n\n else:\n self.prot_form.to_parent(ctx, cls, inst, parent, name, **kwargs)\n","sub_path":"neurons/form/form_table.py","file_name":"form_table.py","file_ext":"py","file_size_in_byte":2945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"310466863","text":"# -*- coding: utf-8 -*-\n\"\"\"\n测试每张测试图像的预测人数与真实人数的MAE\n\"\"\"\nimport torch\nimport model_merge\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch.optim as optim\nimport torch.nn as nn\nimport os\nimport math\n\nif __name__==\"__main__\":\n #测试数据\n root_test_images_patch_dir=\"D:\\\\MaZhenwei\\\\WorkspaceSpyder\\\\crowd_counting\\\\shanghaitech\\\\shanghaitech_dataset\\\\part_A_final\\\\test_data\\\\images_patch\"\n root_test_densitymap_patch_dir=\"D:\\\\MaZhenwei\\\\WorkspaceSpyder\\\\crowd_counting\\\\shanghaitech\\\\shanghaitech_dataset\\\\part_A_final\\\\test_data\\\\densitymap_patch\"\n \n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n net=model_merge.Net()\n net.load_state_dict(torch.load('params_merge.pkl'))\n net.to(device)\n \n loss=0#MAE误差\n index=0#测试到第几张图像\n for image_name in os.listdir(root_test_images_patch_dir):\n each_image_dir=root_test_images_patch_dir+\"\\\\\"+image_name\n each_densitymap_dir=root_test_densitymap_patch_dir+\"\\\\\"+image_name\n \n #获取这张图的大小\n densitymap_dir=\"D:\\\\MaZhenwei\\\\WorkspaceSpyder\\\\crowd_counting\\\\shanghaitech\\\\shanghaitech_dataset\\\\part_A_final\\\\test_data\\\\densitymap\"\n densitymap=np.load(densitymap_dir+\"\\\\DMAP_\"+image_name+\".npy\")\n height=math.floor((densitymap.shape[0]-45)/20)*20+45\n width=math.floor((densitymap.shape[1]-70)/30)*30+70\n #建立该图像的预测密度图\n densitymap_predict=np.zeros((height,width))\n #对应的加权平均对应的次数图\n count_predict=np.zeros((height,width))\n #对应建立真实密度图\n gt_densitymap_predict=np.zeros((height,width))\n gt_count_predict=np.zeros((height,width))\n \n #测试到这张图像的哪一块\n for image_patch_name in os.listdir(each_image_dir):\n \n #读入图像块\n image_patch=np.load(each_image_dir+\"\\\\\"+image_patch_name)\n image_patch=image_patch.astype(np.float32)\n image_patch=image_patch/255#\n #reshape成channel*row*col\n img_patch =np.zeros((1,3,image_patch.shape[0],image_patch.shape[1]))\n img_patch[0,0]=image_patch[:,:,0]\n img_patch[0,1]=image_patch[:,:,1]\n img_patch[0,2]=image_patch[:,:,2]\n img_patch=img_patch.astype(np.float32)\n \n #读入密度图块\n densitymap_patch=np.load(each_densitymap_dir+\"\\\\DMAP_\"+image_patch_name)\n densitymap_patch=densitymap_patch.astype(np.float32)\n #reshape成channel*row*col\n dmap_patch=np.zeros((1,densitymap_patch.shape[0],densitymap_patch.shape[1]))\n dmap_patch[0]=densitymap_patch[:,:,0]\n dmap_patch=dmap_patch[0]\n dmap_patch=dmap_patch.astype(np.float32)\n \n #转成张量\n image_patch_tensor=torch.from_numpy(img_patch)\n image_patch_tensor=image_patch_tensor.to(device)\n outputs=net(image_patch_tensor)\n outputs=outputs.cpu().data.numpy()\n output=outputs[0][0]\n \n #将该块密度图拼到对应整幅密度图的位置上去\n r=int(image_patch_name.split('_')[2])\n c=int(image_patch_name.split('_')[3][0:-4])\n densitymap_predict[20*r:20*r+45,30*c:30*c+70]+=output\n count_predict[20*r:20*r+45,30*c:30*c+70]+=1\n #同时计算真实密度图\n gt_densitymap_predict[20*r:20*r+45,30*c:30*c+70]+=dmap_patch\n gt_count_predict[20*r:20*r+45,30*c:30*c+70]+=1\n \n \n# print(\"真实:\",np.sum(dmap_patch),\"预测:\",np.sum(output))\n# plt.imshow(dmap_patch)\n# plt.figure()\n# plt.imshow(np.maximum(output,0))\n\n densitymap_predict=densitymap_predict/count_predict\n gt_densitymap_predict=gt_densitymap_predict/gt_count_predict\n \n \n #计算误差\n index+=1\n print(\"第\",index,\"张密度图预测完成\")\n abs_each_sum=np.abs(np.sum(gt_densitymap_predict)-np.sum(densitymap_predict))\n loss+=abs_each_sum\n \n# plt.imshow(gt_densitymap_predict)\n# plt.figure()\n# plt.imshow(densitymap_predict)\n# print(\"真实:\",np.sum(gt_densitymap_predict),\"预测:\",np.sum(densitymap_predict))\n loss=loss/index\n print(\"平均MAE误差:\",loss)\n \n \n \n \n ","sub_path":"part_A_code/model/model_merge/test_merge.py","file_name":"test_merge.py","file_ext":"py","file_size_in_byte":4532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"86167102","text":"import sys\n\n# try:\n# my_file = open(\"myfile.txt\")\n# my_line = my_file.readline()\n# my_int = int(s.strip())\n# my_calculated_value = 101 / my_int\n# except IOError:\n# print(\"I/O Error\")\n# except ValueError:\n# print(\"Could not convert data to an integer\")\n# except ZeroDivisionError:\n# print(\"Devision by zero error\")\n# except:\n# print(\"Unexpected error: \", sys.exc_info()[0])\n\n\ndef get_input():\n user_input = input(\"Enter something: \")\n try:\n user_input = int(user_input)\n except ValueError as e:\n print(e)\n return user_input\n\n\nget_input()","sub_path":"18_exceptions/exceptions.py","file_name":"exceptions.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"509147443","text":"import os\nimport argparse\nfrom scrapers.idaho import Idaho\nfrom scrapers.delaware import Delaware\nfrom scrapers.utils import report_cols, dataframe_to_algolia\n\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nDATA_DIR = os.path.join(BASE_DIR, \"data\")\n\nscrapers_dict = {\"idaho\": Idaho,\n \"delaware\": Delaware}\n\ndef get_report_format_type():\n file_fmt = input(\"File type? [csv]/xlsx/json \").strip().lower()\n file_fmt = file_fmt if file_fmt else \"csv\"\n if file_fmt not in [\"csv\",\"xlsx\",\"json\"]:\n return\n else:\n return file_fmt\n\ndef main():\n parser = argparse.ArgumentParser('State Web Scraper')\n parser.add_argument('-e', '--ext', help='Output extension', type=str, default='')\n args = parser.parse_args()\n\n for state_name, scraper in scrapers_dict.items():\n print(\"\\n\\n scraping %s now\" % state_name)\n df = scraper().scrape()\n if args.ext == \"xlsx\":\n fn = os.path.join(DATA_DIR, f\"{state_name}.xlsx\")\n df[report_cols].to_excel(fn, index=False)\n elif args.ext == \"csv\":\n fn = os.path.join(DATA_DIR, f\"{state_name}.csv\")\n df[report_cols].to_csv(fn, index=False)\n elif args.ext == 'json':\n fn = os.path.join(DATA_DIR, f\"{state_name}.json\")\n df[report_cols].to_json(fn, orient=\"records\")\n else:\n dataframe_to_algolia(df)\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"226625976","text":"import numpy as np\nimport h5py\n\nfrom math import pi, sqrt\n\n#make sure filename has h5 extension otherwise visit won't recognize it!\neqfilename = \"eqmytestfile.h5\"\npfilename = \"pmytestfile.h5\"\n\nmx = 100\nmy = 10\nmz = 165\n\n\n\nG=2.7398e2\ngamma=1.6666667\n\n\ndz=10.0e3 #m\ndx=dz\ndy=dz\n\nz=np.linspace(0,dz*mz,mz)\n\npp=1.172e+04\nrr=2.727e-04\n\nB0=50.0e-4 #T\n\n\np0 = np.zeros((mz,my,mx))\nrho0 = np.zeros((mz,my,mx))\n\ncs0 = np.sqrt(gamma*pp/rr) # m s-1\nh=cs0**2/gamma/G # m\n\n\nfor i in range(mx):\n\tfor j in range(my):\n\t\tp0[:,j,i]=pp*np.exp(-z/h)\n\t\trho0[:,j,i]=rr*np.exp(-z/h)\n\n\n\n\n\nzero = np.zeros((mz,my,mx))\n\nwith h5py.File(eqfilename, 'w') as f:\n\t\tf.attrs['cellsize'] = [dx,dy,dz]\n\t\tf.attrs['time'] = 0.0\n\t\tf.attrs['metadata'] = [3,mx,my,mz,0]\n\t\t#!!! lwz compression does not seem to work, do no use it\n\t\tdset = f.create_dataset(\"pe\", (mz, my, mx), dtype='f8', data=p0, chunks=True, shuffle=True)\n\t\tdset = f.create_dataset(\"rho\", (mz, my, mx), dtype='f8', data=rho0, chunks=True, shuffle=True)\n\t\tdset = f.create_dataset(\"bx\", (mz, my, mx), dtype='f8', data=zero, chunks=True, shuffle=True)\n\t\tdset = f.create_dataset(\"by\", (mz, my, mx), dtype='f8', data=zero, chunks=True, shuffle=True)\n\t\tdset = f.create_dataset(\"bz\", (mz, my, mx), dtype='f8', data=B0+zero, chunks=True, shuffle=True)\n\n\n\n","sub_path":"mancha_src/sample_tests/Acoustic_Wave3/create_mhd_1fluid_equi.py","file_name":"create_mhd_1fluid_equi.py","file_ext":"py","file_size_in_byte":1302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"388584170","text":"import math\n\nfrom gamestructs import Vector, Anon\nfrom gamemath import rectns_overlap, sign, EPSILON\n\nclass CollisionMaster (object):\n def __init__ (self, player, heightmap, boxes):\n self.player = player\n self.heightmap = heightmap\n self.boxes = boxes\n\n def _handle_rect3_collision (self, rect1, rect2, rect1_prev):\n pp = rect1.pos\n phs = rect1.halfsize\n ppp = rect1_prev.pos\n bp = rect2.pos\n bhs = rect2.halfsize\n if not rectns_overlap(pp, phs, bp, bhs):\n return False, 0, 0\n for n in reversed(range(3)):\n pppp = pp[:]\n pppp[n] = ppp[n]\n s = int(sign(ppp[n] - bp[n]))\n pppp[n] += s*EPSILON\n if n == 2 and s == 1: # if z axis and rect1 is above rect2\n pppp[n] += 1.0/4.0\n if not rectns_overlap(pppp, phs, bp, bhs):\n pp[n] = bp[n] + s*bhs[n] + s*phs[n]\n return True, n, s\n return False, 0, 0\n\n def update (self, delta_time):\n player = self.player\n heightmap = self.heightmap\n player_prev = Anon(pos=player.prev_pos)\n # player and heightmap)\n pos = player.pos - heightmap.pos\n lo = Vector(*(int(math.floor(o)) for o in pos-player.halfsize))\n hi = Vector(*(int(math.ceil(o)) for o in pos+player.halfsize))\n block_infos = []\n for xx in range(lo.x, hi.x):\n for yy in range(lo.y, hi.y):\n ii = Vector(xx, yy)\n zz = heightmap._height_of2(ii)\n bhs = Vector(0.5, 0.5, zz/2.0)\n bp = heightmap.pos+Vector(xx, yy, 0.0) + bhs\n block_infos.append(Anon(pos=bp, halfsize=bhs))\n for block_info in sorted(block_infos, key=lambda block_info: (block_info.pos - player.pos).magnitude):\n collided, axis, s = self._handle_rect3_collision(player, block_info, player_prev)\n if collided:\n if s == -int(sign(player.vel[axis])):\n player.vel[axis] = 0.0\n # player and boxes\n for box in self.boxes:\n collided, axis, s = self._handle_rect3_collision(player, box, player_prev)\n if collided:\n if s == -int(sign(player.vel[axis])):\n player.vel[axis] = 0.0\n","sub_path":"collision_master.py","file_name":"collision_master.py","file_ext":"py","file_size_in_byte":2311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"342367748","text":"from mcpi.minecraft import Minecraft\nimport csv\nimport time\nimport serial\n\n#ser=serial.Serial(\"COM4\")\n\n#song1=[\"1\",\"1\",\"5\",\"5\",\"6\",\"6\",\"5\",\"4\",\"4\",\"3\",\"3\",\"2\",\"2\",\"1\"]\n\n\nclass House:\n posx = 0\n posy = 0\n posz = 0\n name = None\n def __init__(self, x, y, z):\n House.posx = x\n House.posy = y\n House.posz = z\n \n def wall(self):\n for tall in range(-4,10):\n for i in range(0,21):\n mc.setBlock(self.posx+i-10,self.posy+tall,self.posz+10,42)\n mc.setBlock(self.posx+i-10,self.posy+tall,self.posz-10,42)\n mc.setBlock(self.posx+10,self.posy+tall,self.posz+i-10,42)\n mc.setBlock(self.posx-10,self.posy+tall,self.posz+i-10,42)\n def roof(self):\n tall_most = 10\n for i in range(0,21):\n for j in range(0,21):\n mc.setBlock(self.posx+i-10,self.posy+10,self.posz+j-10,95)\n def window(self):\n for i in range(2,5):\n for j in range(0,10):\n mc.setBlock(self.posx+10,self.posy+i,self.posz+j-5,20)\n def door(self):\n mc.setBlock(self.posx-10,self.posy,self.posz+1,0)\n mc.setBlock(self.posx-10,self.posy,self.posz,0)\n mc.setBlock(self.posx-10,self.posy+1,self.posz+1,0)\n mc.setBlock(self.posx-10,self.posy+1,self.posz,0)\n \n def create_all(self):\n self.wall()\n self.roof()\n self.window()\n self.door()\n\n def set_name(self,name):\n print(\"set the name of the house:\",name)\n self.name = name\n\n def song(self):\n time.sleep(2)\n for i in song1:\n ser.write(i.encode())\n time.sleep(1)\n\n def detect_pos(self,currx,curry,currz):\n if self.posx-10<=currx<=self.posx+10 and self.posz-10<=currz<=self.posz+10:\n self.set_name(\"a simple house\")\n self.song()\n\n def build_the_floor(self):\n with open('floor.csv', newline='') as f:\n reader = csv.reader(f, delimiter='\\t')\n j = 0\n for row in reader:\n for i in range(0,19):\n if row[i]=='1':\n mc.setBlock(self.posx-9+i,self.posy-1,self.posz-9+j,41)\n elif row[i]=='0':\n mc.setBlock(self.posx-9+i,self.posy-1,self.posz-9+j,5)\n j = j + 1\n \nclass TriangleRoofHouse(House):\n def __init__(self, x, y, z):\n House.__init__(self, x, y, z)\n def roof(self):\n tall_most = 10\n for m in range(0,11):\n for i in range(0+m,21-m):\n for j in range(0+m,21-m):\n mc.setBlock(self.posx+i-10,self.posy+10+m,self.posz+j-10,95)\n \n \nclass RoundRoofHouse(House):\n def __init__(self, x, y, z):\n House.__init__(self, x, y, z)\n def roof(self):\n tall_most = 10\n for i in range(0,21):\n for j in range(0,21):\n mc.setBlock(self.posx+i-10,self.posy+10,self.posz+j-10,95)\n for m in range(0,11):\n for i in range(-10+m,11-m):\n j = int(pow(pow(11-m,2)-pow(abs(i),2),0.5))\n mc.setBlock(self.posx+i,self.posy+10+m,self.posz+j,95)\n mc.setBlock(self.posx+i,self.posy+10+m,self.posz-j,95)\n\nmc=Minecraft.create()\n\npos=mc.player.getTilePos()\nx1=pos.x+30\nx2=pos.x-30\n\nt1 = House(pos.x,pos.y,pos.z)\nt1.create_all()\n\nt2 = TriangleRoofHouse(x1,pos.y,pos.z)\nt2.create_all()\n\nt3 = RoundRoofHouse(x2,pos.y,pos.z)\nt3.create_all()\n","sub_path":"chenxuetao/20201118assignment/build_different_roof.py","file_name":"build_different_roof.py","file_ext":"py","file_size_in_byte":3519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"216086828","text":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom math import log\nfrom torch.nn import init\nfrom GCN.GraphSAGE import GraphSAGE\nfrom torch.optim.lr_scheduler import ExponentialLR\nimport torch.nn.functional as F\n\nclass Qfunction(nn.Module):\n def __init__(self, layer_infos, graph_size, lr, lr_gamma=0.95):\n super(Qfunction, self).__init__()\n\n\n self.sage = GraphSAGE(layer_infos)\n self.embed_dim = self.sage.embed_dim\n self.graph_size = graph_size\n \n self.lin1 = nn.Linear(self.embed_dim, self.embed_dim + 1, bias=False)\n self.lin2 = nn.Linear(self.embed_dim, self.embed_dim + 1, bias=False)\n self.lin3 = nn.Linear(self.embed_dim, self.embed_dim + 1, bias=False)\n self.lin4 = nn.Linear(self.embed_dim, self.embed_dim + 1, bias=False)\n # self.lin4 = nn.Linear(2 * (self.embed_dim+1), 1, bias=True)\n self.lin5 = nn.Linear(3 * (self.embed_dim+1), 1, bias=True)\n self.lin6 = nn.Linear(4 * (self.embed_dim+1), 1, bias=True)\n nn.init.xavier_uniform_(self.lin1.weight)\n nn.init.xavier_uniform_(self.lin2.weight)\n nn.init.xavier_uniform_(self.lin3.weight)\n nn.init.xavier_uniform_(self.lin4.weight)\n\n self.optimizer = optim.Adam(self.parameters(), lr=lr)\n self.scheduler = ExponentialLR(self.optimizer, gamma=lr_gamma)\n self.zero_pad = torch.zeros(1, self.embed_dim).cuda()\n self.cuda(device=0)\n\n def forward(self, features, adj_lists, edge_weight, seeds_idx_pad, seeds_idx_num, candidates_idx, all_nodes, mask, rest_idx, batch_size=1):\n embedding = self.sage(features, adj_lists, edge_weight, all_nodes, mask)\n embedding_pad = torch.cat((embedding, self.zero_pad), dim=0)\n row_index = torch.tensor([[i] for i in range(batch_size)])\n\n seeds_emb = embedding_pad[seeds_idx_pad]\n candidates_emb = embedding[candidates_idx]\n rest_emb = embedding[rest_idx]\n\n '''\n # seeds_mean = torch.mean(seeds_emb, dim=1).reshape(1, self.embed_dim+1)\n # global_mean = torch.mean(nn.Sigmoid()(self.lin2(embedding)), dim=0).reshape(1, self.embed_dim+1) # embedding do not have batch\n # rest_mean = torch.mean(rest_emb, dim=1)\n\n seeds_mean = nn.Sigmoid()(self.lin1(torch.mean(seeds_emb, dim=1)))\n global_mean = nn.Sigmoid()(self.lin2(torch.mean(embedding, dim=0).reshape(1, self.embed_dim)))\n rest_mean = nn.Sigmoid()(self.lin3(torch.mean(rest_emb, dim=1)))\n candi_emb = nn.Sigmoid()(self.lin4(candidates_emb))\n\n if batch_size is not None:\n seeds_mean = torch.cat([seeds_mean for i in range(batch_size)], dim=0)\n global_mean = torch.cat([global_mean for i in range(batch_size)], dim=0)\n s_c_mean = nn.Sigmoid()(self.lin1(torch.mean(torch.cat((seeds_emb, candidates_emb.reshape(1,-1, self.embed_dim)), dim=1), dim=1)))\n\n # gain_frac = F.cosine_similarity(s_c_mean, global_mean ,dim=1)\n gain = self.lin5(torch.cat((seeds_mean, candi_emb, global_mean), dim=1))\n gain_overlap_frac = F.cosine_similarity(seeds_mean, candi_emb, dim=1).reshape(batch_size, 1)\n # left_frac = F.cosine_similarity(rest_mean, global_mean, dim=1)\n left_overlap_frac = F.cosine_similarity(s_c_mean, rest_mean, dim=1).reshape(batch_size, 1)\n\n Q = torch.add(torch.mul(gain, 1-gain_overlap_frac) , torch.mul(log(self.graph_size)/gain, 1-left_overlap_frac) ) \n '''\n\n\n\n\n\n '''\n\n # seeds_mean = nn.Sigmoid()(self.lin1(torch.sum(seeds_emb, dim=1).div(seeds_idx_num)))\n seeds_mean = nn.Sigmoid()(self.lin1(torch.mean(seeds_emb, dim=1)))\n # seeds_mean = torch.mean(seeds_emb, dim=1)\n global_mean = nn.Sigmoid()(self.lin2(torch.mean(embedding, dim=0).reshape(1, self.embed_dim)))\n # global_mean = torch.mean(embedding, dim=0).reshape(1, self.embed_dim)\n # candi_emb = candidates_emb\n candi_emb = nn.Sigmoid()(self.lin3(candidates_emb))\n\n if batch_size is not None:\n seeds_mean = torch.cat([seeds_mean for i in range(batch_size)], dim=0)\n global_mean = torch.cat([global_mean for i in range(batch_size)], dim=0)\n\n \n \n candidates_size = len(candidates_idx)\n cur_reward_frac = torch.sum(torch.mul(candi_emb, seeds_mean), dim=1)\n\n # Q = self.lin5(torch.cat((seeds_mean, global_mean, candi_emb), dim =1))\n # 某些时候有效\n Q = torch.sum(torch.mul(candi_emb, seeds_mean), dim=1)\n # Q = nn.(torch.sum(torch.mul(candi_emb, seeds_mean), dim=1))\n\n '''\n # seeds_mean = nn.ReLU(inplace=True)(self.lin1(torch.mean(seeds_emb, dim=1)))\n seeds_mean = nn.Sigmoid()(self.lin1(torch.mean(seeds_emb, dim=1)))\n # global_mean = nn.ReLU(inplace=True)(self.lin2(torch.mean(embedding, dim=0).reshape(1, self.embed_dim)))\n global_mean = nn.Sigmoid()(self.lin2(torch.mean(embedding, dim=0).reshape(1, self.embed_dim)))\n # rest_mean = nn.ReLU(inplace=True)(self.lin3(torch.mean(rest_emb, dim=1)))\n rest_mean = nn.Sigmoid()(self.lin3(torch.mean(rest_emb, dim=1)))\n # candi_emb = nn.ReLU(inplace=True)(self.lin4(candidates_emb)).reshape(batch_size, self.embed_dim+1)\n candi_emb = nn.Sigmoid()(self.lin4(candidates_emb))\n # seeds_mean = torch.mean(seeds_emb, dim=1)\n # global_mean = torch.mean(embedding, dim=0).reshape(1, self.embed_dim)\n # rest_mean = torch.mean(rest_emb, dim=1)\n # candi_emb = candidates_emb\n\n if batch_size is not None:\n seeds_mean = torch.cat([seeds_mean for i in range(batch_size)], dim=0)\n global_mean = torch.cat([global_mean for i in range(batch_size)], dim=0)\n seeds_emb = torch.cat([seeds_emb for i in range(batch_size)], dim=0)\n\n sc_mean = nn.Sigmoid()(self.lin1(torch.mean(torch.cat((seeds_emb, candidates_emb.reshape(batch_size, 1, -1)), dim=1), dim=1)))\n \n margin_gain1 = torch.sub(candi_emb, seeds_mean) \n margin_gain2 = torch.sub(rest_mean, sc_mean) \n\n Q = torch.sum(torch.mul(margin_gain1+margin_gain2, global_mean), dim=1)\n # Q = self.lin5(torch.cat((seeds_mean, global_mean, candi_emb), dim =1))\n # 某些时候有效\n # Q = self.lin4(torch.cat((margin_gain1, margin_gain2), dim=1))\n # Q = torch.sum(torch.mul(candi_emb, seeds_mean), dim=1)\n\n\n\n \n\n return Q\n\n\n\n\n\n\n\n\n\n\n \n\n","sub_path":"GCOMB++/Qfunction.py","file_name":"Qfunction.py","file_ext":"py","file_size_in_byte":6425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"603947293","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import models, fields, api\n\n\nclass ReportAsserts(models.TransientModel):\n _name = \"report.stock.asserts\"\n\n product_id = fields.Many2one(comodel_name=\"arc.product\", string=\"Product\", required=True)\n\n @api.multi\n def trigger_stock_asserts(self):\n recs = self.env[\"arc.asserts\"].search([(\"product_id\", \"=\", self.product_id.id)])\n\n report = []\n for rec in recs:\n report.append({\"Product\": rec.product_id.name,\n \"Manufacturer\": rec.manufacturer,\n \"Manufacture Date\": rec.manufactured_date,\n \"Expiry Date\": rec.expiry_date,\n \"Serial No\": rec.serial_no,\n \"Model No\": rec.model_no,\n \"Warranty Date\": rec.warranty_date,\n \"Order Date\": rec.order_date,\n \"Purchase Date\": rec.purchase_date,\n \"Vendor\": rec.vendor_id.name,\n \"Working\": rec.is_working,\n \"Condem\": rec.is_condem})\n","sub_path":"report/stock_asserts.py","file_name":"stock_asserts.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"637890303","text":"#!/usr/bin/env python2.7\nimport rospy\nimport numpy as np\nimport tf\nimport roslib\nimport geometry_msgs.msg\n\nif __name__ == '__main__':\n rospy.init_node('tf_listener')\n\n listener = tf.TransformListener()\n\n rate = rospy.Rate(10.0)\n while not rospy.is_shutdown():\n try:\n (trans,rot) = listener.lookupTransform('/camera', '/marker', rospy.Time(0))\n except (tf.LookupException, tf.ConnectivityException, tf.ExtrapolationException):\n continue\n\n print(\"transformation: \", trans)\n print(\"rotation: \", rot)\n\n rate.sleep()\n\n","sub_path":"src/virtual/scripts/test_tf.py","file_name":"test_tf.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"545604798","text":"from datetime import datetime\nimport logging\nfrom pyelt.utils.read import read_yt_key, read_channel_id\nfrom pyelt.api import yt\nfrom pyelt.aws import action\n\ntoday = datetime.date(datetime.today())\n\n# logging configurations\nlogging.basicConfig(\n filename=\"logs/elt-youtube-api-log_{0}.txt\".format(str(today)),\n level=logging.DEBUG,\n format=\" %(asctime)s - %(levelname) s - %(message)s\",\n)\n\nyt_key = read_yt_key(path=\"infra/youtube_api_key.txt\")\nyoutube_service = yt.call_api(yt_key, \"youtube\", \"v3\")\nchannel_id = read_channel_id(path=\"infra/channel-id.txt\")\n\n# id pointing to the playlist of uploaded video\nupload_id = yt.get_upload_id(service_obj=youtube_service, channel_id=channel_id)\nlogging.info(\"Got the upload id\")\n\n# list of id, one for each uploaded video in a given channel\nvideo_id = yt.get_video_id(service_obj=youtube_service, upload_id=upload_id)\nlogging.info(\"Retrieved list of videos id\")\n\n# iterate through the ids to get a json response\nfor vid_id in video_id:\n # get response in JSON format\n video_json = yt.get_response(service_obj=youtube_service, video_id=vid_id)\n # upload file\n action.upload_file(file_name=vid_id)\n logging.info(\"Upload Video Id to S3: {0}\".format(vid_id))\n\nlogging.info(\"Data extraction concluded\")\n","sub_path":"pyelt/scripts/01_extract_id.py","file_name":"01_extract_id.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"189854724","text":"import os\nimport tkinter as tk\nimport traceback\nfrom collections import defaultdict\nfrom pprint import pprint\nfrom tkinter import ttk, messagebox\n\nfrom ttkthemes import ThemedStyle\n\nfrom controller import Controller\nfrom model import TreeModel, EMPTY_TREE\nfrom util.custom_tks import ClosableNotebook\nfrom util.util import json_open, json_create\nfrom util.util_tk import create_menubar\nimport PIL.Image\nimport PIL.ImageTk\n\nfrom view.colors import darkmode\n\n\nclass Application:\n\n # Create the application window\n def __init__(self, width, height):\n # Create the root\n self.root = tk.Tk()\n self.root.geometry(\"%dx%d+50+30\" % (width, height))\n self.root.title(\"Read tree\")\n\n\n # App icon :). Save or will be garbage collected\n self.icon = PIL.ImageTk.PhotoImage(PIL.Image.open(\"static/zoneplate.png\"))\n self.root.tk.call('wm', 'iconphoto', self.root._w, self.icon)\n # Dark mode\n style = ThemedStyle(self.root)\n if darkmode:\n style.set_theme(\"black\")\n\n # Create the notebook and add a tab to it\n # self.close_icon = build_notebook_style()\n self.notebook = ClosableNotebook(self.root)\n self.notebook.pack(fill=tk.BOTH, expand=1)\n self.tabs = []\n\n # Load app data\n self.app_data_file = os.path.join(os.getcwd(), \"data/\", \".app_data.json\")\n self.app_data = None\n self.initialize_app_state()\n\n # Build the menu bar\n self.build_menus()\n\n # Bind Button-1 to tab click so tabs can be closed\n self.notebook.bind('', self.tab_click)\n self.notebook.bind()\n\n # Do final root prep\n self.root.update_idletasks()\n # Put the app into the foreground\n self.root.attributes('-topmost', True)\n self.root.update()\n self.root.attributes('-topmost', False)\n\n\n def initialize_app_state(self):\n try:\n self.app_data = json_open(self.app_data_file) # if os.path.isfile(self.app_data_file) else {}\n for tab_data in self.app_data[\"tabs\"]:\n self.create_tab(filename=tab_data[\"filename\"])\n except Exception as e:\n print(\"Failed to load with app data\")\n print(str(e))\n print(traceback.format_exc())\n self.app_data = {}\n\n if len(self.tabs) == 0:\n print(\"Opening a blank tab\")\n self.create_tab()\n self.set_tab_names()\n\n\n def update_app_data(self):\n self.set_tab_names()\n self.app_data = {\n \"tabs\": [\n {\"filename\": t.state.tree_filename}\n for t in self.tabs\n ]\n }\n json_create(self.app_data_file, self.app_data)\n\n\n # Create a tab\n def create_tab(self, filename=None, event=None):\n if len(self.tabs) > 0:\n messagebox.showwarning(\"Error\", \"Only use one tab right now. hehe\")\n return\n tab = Controller(self.root)\n self.tabs.append(tab)\n self.notebook.add(tab.display.frame, text=f\"Tab {len(self.tabs)}\")\n\n tab.state.register_callback(tab.state.io_update, self.update_app_data)\n if filename is not None:\n print(\"opening\", filename)\n tab.state.open_tree(filename)\n else:\n tab.state.load_tree_data(EMPTY_TREE)\n\n\n def close_tab(self, event=None, index=None):\n index = self.notebook.index(\"current\") if index is None else index\n self.notebook.forget(index)\n self.tabs.pop(index)\n if len(self.tabs) == 0:\n self.create_tab()\n\n\n # If the user clicks a close button, get the tab at that position and close it\n def tab_click(self, event):\n if \"close\" in event.widget.identify(event.x, event.y):\n index = self.notebook.index(f\"@{event.x},{event.y}\")\n self.close_tab(index=index)\n\n\n def set_tab_names(self):\n for i, t in enumerate(self.tabs):\n name = os.path.splitext(os.path.basename(t.state.tree_filename))[0] \\\n if t.state.tree_filename else f\"Tab {i+1}\"\n self.notebook.tab(i, text=name)\n\n # Build the applications menubar\n # TODO Splitting between here and tab is bad. Move this to the tab\n def build_menus(self):\n menu_list = defaultdict(list, {\n \"File\": [\n ('New Tab', 'Ctrl+N', '', self.create_tab),\n ('Open', 'O', None, lambda event=None: self.forward_command(Controller.open_tree)),\n ('Save', 'S', None, lambda event=None: self.forward_command(Controller.save_tree)),\n ('Save As...', 'Ctrl+S', '', lambda event=None: self.forward_command(Controller.save_tree_as)),\n ('Close Tab', None, None, self.close_tab),\n ('Quit', 'Ctrl+Q', '', self.quit_app)\n ]\n })\n for menu, items in self.tabs[0].build_menus().items():\n menu_list[menu].extend(items)\n create_menubar(self.root, menu_list)\n\n\n # Forward the given command to the current display controller\n def forward_command(self, command):\n if len(self.tabs) == 0:\n messagebox.showwarning(\"Error\", \"There is no tree open.\")\n else:\n command(self.tabs[self.notebook.index(\"current\")])\n\n\n def quit_app(self, event=None):\n self.root.destroy()\n\n\n # Let the application run\n def main(self):\n self.root.mainloop()\n\n\n# Create the display application and run it\nif __name__ == \"__main__\":\n app = Application(1200, 675)\n app.main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"463514533","text":"\"\"\"Compress a Fast R-CNN network using truncated SVD.\"\"\"\n\nimport argparse\nimport numpy as np\nimport os, sys\n\ndef parse_args():\n \"\"\"Parse input arguments.\"\"\"\n parser = argparse.ArgumentParser(description='Compress a Fast R-CNN network')\n parser.add_argument('--in', dest='weights_file',\n help='Fully-connected weights',\n default=None, type=str)\n parser.add_argument('--dim', dest='weights_dim',\n help='Fully-connected dimension ',\n default='1x1', type=str) \n parser.add_argument('--type', dest='type',\n help='Weights format',\n default='fp16', type=str)\n parser.add_argument('--sval', dest='sval',\n help='Number of singular values to retain',\n default=0, type=int)\n parser.add_argument('--QF', dest='QF',\n help='Number of bits for fractional part',\n default=11, type=int)\n\n if len(sys.argv) == 1:\n parser.print_help()\n sys.exit(1)\n\n args = parser.parse_args()\n return args\n\ndef compress_weights(W, l):\n \"\"\"Compress the weight matrix W of an inner product (fully connected) layer\n using truncated SVD.\n Parameters:\n W: N x M weights matrix\n l: number of singular values to retain\n Returns:\n Ul, L: matrices such that W \\approx Ul*L\n \"\"\"\n\n # numpy doesn't seem to have a fast truncated SVD algorithm...\n # this could be faster\n U, s, V = np.linalg.svd(W, full_matrices=False)\n\n Ul = U[:, :l]\n sl = s[:l]\n Vl = V[:l, :]\n\n L = np.dot(np.diag(sl), Vl)\n return Ul, L\n\ndef main():\n args = parse_args()\n\n out0 = os.path.splitext(os.path.basename(args.weights_file))[0] + '_svd0'\n out1 = os.path.splitext(os.path.basename(args.weights_file))[0] + '_svd1'\n out_dir = os.path.dirname(args.weights_file)\n\n dim = list(map(int, args.weights_dim.split(\"x\")))\n\n # Compress fc\n l_fc = args.sval\n\n # uncompressed weights\n if args.type == 'fp16':\n W = np.zeros((dim[0]*dim[1]), dtype='i2')\n W = np.fromfile(args.weights_file, dtype='i2')\n W = W / (2**args.QF)\n elif args.type == 'f32':\n W = np.zeros((dim[0]*dim[1]), dtype='f4')\n W = np.fromfile(args.weights_file, dtype='f4')\n elif args.type == 'd':\n W = np.zeros((dim[0]*dim[1]), dtype='f8')\n W = np.fromfile(args.weights_file, dtype='f8')\n else:\n raise RuntimeError('Type not supported')\n \n W = W.reshape(dim[0], dim[1])\n\n print('Compressing fc...')\n Ul_fc, L_fc = compress_weights(W, l_fc)\n\n print('Ul_fc', Ul_fc)\n print('l_fc', L_fc)\n\n if args.type == 'fp16':\n Ul_fc = Ul_fc * (2**args.QF)\n L_fc = L_fc * (2**args.QF)\n Ul_fc = (np.around(Ul_fc)).astype(np.int16)\n L_fc = (np.around(L_fc)).astype(np.int16)\n\n print('Ul_fc', Ul_fc)\n print('L_fc', L_fc)\n\n filename0 = '{}/{}'.format(out_dir, out0)\n filename1 = '{}/{}'.format(out_dir, out1)\n\n Ul_fc.tofile(filename0)\n L_fc.tofile(filename1)\n\n print('Wrote svd weights to: {} {}'.format(filename0, filename1))\n\nif __name__ == '__main__':\n main()","sub_path":"neuragheconvnet/tools/compress_fc.py","file_name":"compress_fc.py","file_ext":"py","file_size_in_byte":3223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"121639781","text":"#!/usr/bin/env python\nfrom InputHandler import *\nfrom urllib import urlencode\nfrom StatementParser import StatementParser\nimport urllib2\nimport xml.etree.ElementTree as ElementTree\n\n#Default is to look up question on Wolfram Alpha\nappID = \"3Y53TJ-KX4G2TY3UJ\"\nurl = \"http://api.wolframalpha.com/v2/query?appid=\" + appID + \"&format=image,plaintext&\"\n\n#The WolframHandler class inherits from InputHandler.\nclass WolframHandler(InputHandler):\n def __init__(self, inputText):\n self.canHandle = True\n sp = StatementParser(inputText)\n if sp.test(\"{input} using {assumption}\") and len(sp.out['assumption'].split()) is 1 and sp.out['assumption'][0] == \"*\":\n words = inputText.split()\n self.assumption = words[-1]\n self.inputText = \" \".join(words[0:-2])\n else:\n self.assumption = None\n self.inputText = inputText\n def handleInput(self, resources):\n try:\n data = {\"input\": self.inputText}\n if self.assumption is not None:\n data['assumption'] = self.assumption\n if 'geolocation' in resources:\n data['latlong'] = \"%f,%f\" % (resources['geolocation']['latitude'], resources['geolocation']['longitude'])\n data['lat'] = resources['geolocation']['latitude']\n f = urllib2.urlopen(url + urlencode(data))\n out = f.read()\n et = ElementTree.fromstring(out)\n if et.get(\"success\", \"false\") == \"false\":\n return TextResponse(\"I don't understand, could you repeat that?\")\n pods = []\n advice = []\n for podElement in list(et):\n if podElement.tag == \"assumptions\":\n for assump in list(podElement):\n if assump.get(\"type\", \"\") == \"Clash\":\n advice = [(elem.get(\"desc\"), self.inputText + \" using \" + elem.get(\"input\")) for elem in list(assump)]\n if podElement.tag != \"pod\":\n continue\n pod = {}\n pod['title'] = podElement.get(\"title\", \"\")\n pod['subpods'] = [{\"plaintext\":[elem.text for elem in list(subpodElement) if elem.tag == \"plaintext\"][0],\"image\":[elem.get(\"src\", \"\") for elem in list(subpodElement) if elem.tag == \"img\"]} for subpodElement in list(podElement) if subpodElement.tag == \"subpod\"]\n pods.append(pod)\n return WolframResponse(pods, advice)\n except:\n return ErrorResponse(\"Couldn't get Wolfram result.\")\n\nclass WolframResponse(Response):\n def __init__(self, pods, advice):\n self.pods = pods\n self.advice = advice\n def output(self):\n from json import dumps\n return dumps({\"response\":\"wolfram\",\"pods\":self.pods,\"advice\":{\"prefix\":\"Did you mean\",\"list\":self.advice}})\n\n\n#Set the fallback handler to the WolframHandler\nsetFallback(WolframHandler)","sub_path":"htdocs/StevePython/InputHandlers/WolframHandler.py","file_name":"WolframHandler.py","file_ext":"py","file_size_in_byte":2653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"177048856","text":"# https://leetcode.com/problems/maximum-depth-of-binary-tree/submissions/\n\n# Given the root of a binary tree, return its maximum depth.\n\n# A binary tree's maximum depth is the number of nodes along the longest path\n# from the root node down to the farthest leaf node.\n\n\nimport collections\n\n\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\n# DFS\nclass Solution:\n def maxDepth(self, root: TreeNode) -> int:\n def dfs(root: TreeNode, depth=-1) -> int:\n depth += 1\n if root is None:\n return depth\n return max(dfs(root.left, depth), dfs(root.right, depth))\n return dfs(root)\n\n\n# BFS\nclass Solution:\n def maxDepth(self, root: TreeNode) -> int:\n if root is None:\n return 0\n\n def bfs(root: TreeNode) -> int:\n queue = collections.deque([root])\n depth = 0\n while queue:\n depth += 1\n for _ in range(len(queue)):\n node = queue.popleft()\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n return depth\n\n return bfs(root)","sub_path":"LeetCode/9. 트리/104-maximum-depth-of-binary-tree.py","file_name":"104-maximum-depth-of-binary-tree.py","file_ext":"py","file_size_in_byte":1314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"548930055","text":"class TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution:\n def TreeDepth(self, pRoot):\n # write code here\n if not pRoot: return 0\n queue = [pRoot]\n deep = 0\n while queue:\n # 记录同层节点的个数\n n = len(queue)\n for _ in range(n):\n # 将同层节点依次出队\n node = queue.pop(0)\n if node.left: queue.append(node.left)\n if node.right: queue.append(node.right)\n deep += 1\n return deep\n \n递归方法\n\nclass Solution:\n def TreeDepth(self, pRoot):\n # write code here\n # 使用层次遍历\n # 当树为空直接返回0\n if pRoot is None:\n return 0\n # 方法2:使用递归\n # 如果该树只有一个结点,它的深度为1.如果根节点只有左子树没有右子树,\n # 那么树的深度为左子树的深度加1;同样,如果只有右子树没有左子树,\n # 那么树的深度为右子树的深度加1。如果既有左子树也有右子树,\n # 那该树的深度就是左子树和右子树的最大值加1.\n count = max(self.TreeDepth(pRoot.left), self.TreeDepth(pRoot.right)) + 1\n return count\n","sub_path":"剑指offer/038-二叉树的深度/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"387986741","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 ('catalogue', '0023_product_deliveryprovider'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='product',\n old_name='deliveryProvider',\n new_name='deliveryProviders',\n ),\n migrations.AlterField(\n model_name='product',\n name='productAddr',\n field=models.CharField(blank=True, help_text='city, street, number', max_length=255, verbose_name='product address'),\n ),\n ]\n","sub_path":"forkedApps/catalogue/migrations/0024_auto_20151203_0800.py","file_name":"0024_auto_20151203_0800.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"490903644","text":"from django.test import TestCase\n\nfrom lists.forms import EMPTY_ITEM_ERROR, ItemForm\nfrom lists.models import Item, List\n\n\nclass ITemFormTest(TestCase):\n\n def test_form_item_input_has_placeholder_and_css_classes(self):\n form = ItemForm()\n assert 'placeholder=\"Enter a to-do item\"' in form.as_p()\n assert 'class=\"form-control input-lg\"' in form.as_p()\n\n def test_form_validation_for_blank_items(self):\n form = ItemForm(data={'text': ''})\n self.assertFalse(form.is_valid())\n assert form.errors['text'] == [EMPTY_ITEM_ERROR]\n\n def test_form_save_handles_saving_to_a_list(self):\n list_ = List.objects.create()\n form = ItemForm(data={'text': 'do me'})\n new_item = form.save(for_list=list_)\n assert new_item == Item.objects.first()\n assert new_item.text == 'do me'\n assert new_item.list == list_\n","sub_path":"src/lists/tests/test_forms.py","file_name":"test_forms.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"593993792","text":"#csvの読み書きするのに必要\nimport pandas as pd\n\n# listに文字列を追加\ncalendar = [['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], ['a', 'b', 'c', 'd', 'e', 'f', 'g']]\n\n# listをdataframe形式に変換(dataframeでないと書き込みできない)\ndf1 = pd.DataFrame(calendar)\n\n# 画面に出力\nprint(df1)\n\n # csvファイルに出力\n # ヘッダー(列名)、インデックス(行名)のありなしは引数header, indexにTrue or Falseで指定する。\ndf1.to_csv('output/csv_write_pandas_out.csv', header=False, index=False)","sub_path":"python/csv_write_pandas.py","file_name":"csv_write_pandas.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"17948589","text":"#coding utf8\nfrom qiuClass import *\nimport pickle\n\ndef qiuExtractor():\n\tqiushiSet = pickle.load(open('Qiushi.p','r'))\n\toFile = open('QiuComment.txt','w')\n\tfor iQiu in qiushiSet:\n\t\toFile.write(iQiu.text.encode('utf8')+'\\n')\n\t\tfor iComment in iQiu.comments:\n\t\t\toFile.write('\\t'+iComment.cmUID+':'+iComment.text.encode('utf8')+'\\n')\n\toFile.close()\n\nif __name__ == '__main__':\n\tqiuExtractor()","sub_path":"contentExtractor.py","file_name":"contentExtractor.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"67975463","text":"def func(hostname,token,n):\n try:\n child = pexpect.popen_spawn.PopenSpawn('/home/siite/wwwroot/antenv/bin/databricks configure --token',timeout=n)\n child.expect_exact(b'Databricks Host (should begin with https://):')\n child.sendline(bytes('{}'.format(hostname),'utf-8'))\n child.expect_exact(b'Token: ')\n child.sendline(bytes('{}'.format(token),'utf-8'))\n except:\n n=n+1\n func(hostname,token,n)\nimport pexpect\nimport sys\nfrom pexpect import popen_spawn\nhostname=sys.argv[1]\ntoken=sys.argv[2]\nfunc(hostname,token,1)\n","sub_path":"SupplyChain/databricks_linux/sample.py","file_name":"sample.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"642147466","text":"from django.conf import settings\nfrom django.contrib import messages\nfrom django.contrib.admin.models import LogEntry\nfrom django.contrib.auth import logout\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import User\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib.sites.models import Site\nfrom django.core.mail import mail_admins\n#from django.core.paginator import Paginator, InvalidPage\nfrom django.db.models import Q\nfrom django.http import HttpResponse, HttpResponseForbidden, HttpResponseBadRequest, HttpResponseRedirect\nfrom django.shortcuts import render_to_response, get_object_or_404\nfrom django.template import RequestContext\nfrom haystack.query import SearchQuerySet, EmptySearchQuerySet\nfrom itertools import chain\nfrom reversion import get_unique_for_object\nfrom urllib import urlopen\nfrom models import *\nfrom editorsnotes.djotero.utils import as_readable, type_map\nfrom editorsnotes.refine.models import TopicCluster\nimport forms as main_forms\nfrom PIL import Image, ImageFont, ImageDraw\nfrom random import randint\nimport utils\nimport json\nimport os\nimport re\n\ndef _sort_citations(instance):\n cites = { 'all': [] }\n for c in Citation.objects.filter(\n content_type=ContentType.objects.get_for_model(instance), \n object_id=instance.id):\n cites['all'].append(c)\n cites['all'].sort(key=lambda c: c.ordering)\n return cites\n\n# Proxy for cross-site AJAX requests. For development only.\ndef proxy(request):\n url = request.GET.get('url')\n if url is None:\n return HttpResponseBadRequest()\n if not url.startswith('http://cache.zoom.it/'):\n return HttpResponseForbidden()\n return HttpResponse(urlopen(url).read(), mimetype='application/xml')\n\n\n# ------------------------------------------------------------------------------\n# Auth\n# ------------------------------------------------------------------------------\n\ndef user_logout(request):\n logout(request)\n return render_to_response(\n 'logout.html', context_instance=RequestContext(request))\n\ndef user(request, username=None):\n o = {}\n if not username:\n user = request.user\n o['own_profile'] = True\n else:\n user = get_object_or_404(User, username=username)\n o['own_profile'] = user == request.user\n\n o['profile'] = UserProfile.get_for(user)\n o['log_entries'], ignored = UserProfile.get_activity_for(user, max_count=20)\n o['affiliation'] = o['profile'].affiliation\n o['project_role'] = (o['profile'].get_project_role(o['affiliation'])\n if o['affiliation'] else None)\n\n if ['own_profile']:\n o['zotero_status'] = True if (o['profile'].zotero_key and\n o['profile'].zotero_uid) else False\n if (o['affiliation'] and o['project_role'] == 'editor') or user.is_superuser:\n if user.is_superuser:\n o['clusters'] = TopicCluster.objects.all()\n else:\n o['clusters'] = TopicCluster.objects.filter(\n topics__affiliated_projects=o['profile'].affiliation)\n return render_to_response(\n 'user.html', o, context_instance=RequestContext(request))\n\n\n# ------------------------------------------------------------------------------\n# Basic navigation\n# ------------------------------------------------------------------------------\n\ndef index(request):\n o = {}\n return render_to_response(\n 'index.html', o, context_instance=RequestContext(request))\n\ndef browse(request):\n max_count = 6\n o = {}\n for model in [Topic, Note, Document]:\n model_name = model._meta.module_name\n listname = '%s_list' % model_name\n query_set = model.objects.order_by('-last_updated')\n\n items = list(query_set[:max_count])\n o[listname] = items\n o['projects'] = Project.objects.all().order_by('name')\n return render_to_response(\n 'browse.html', o, context_instance=RequestContext(request))\n\nreel_numbers = re.compile(r'(\\S+):(\\S+)')\nignored_punctuation = '!#$%&\\'()*+,-./:;<=>?@[\\\\]^_`{|}~'\n\ndef search(request):\n query = ''\n results = EmptySearchQuerySet()\n\n if request.GET.get('q'):\n query = request.GET.get('q')\n match = reel_numbers.search(query)\n if match:\n # so we can match reel numbers exactly\n query = reel_numbers.sub(r'\"\\1 \\2\"', query)\n def filter(c):\n if c in ignored_punctuation: return ' '\n return c\n query = ''.join([filter(c) for c in query])\n if len(query) > 0:\n results = SearchQuerySet().auto_query(query).load_all()\n if match:\n # restore the original form of the query so highlighting works\n query = query.replace('\"%s %s\"' % match.group(1,2), match.group(0))\n\n # paginator = Paginator(results, 20)\n \n # try:\n # page = paginator.page(int(request.GET.get('page', 1)))\n # except InvalidPage:\n # raise Http404('No such page of results!')\n \n o = {\n # 'page': page,\n # 'paginator': paginator,\n 'results': results,\n 'query': query,\n }\n \n return render_to_response(\n 'search.html', o, context_instance=RequestContext(request))\n\ndef about_test(request):\n x, y = (100, 38)\n img = Image.new('RGBA', (x, y), (255, 255, 255))\n draw = ImageDraw.Draw(img)\n font = ImageFont.truetype(\n os.path.join(settings.STATIC_ROOT, 'style', 'DejaVuSans-Bold.ttf'), 24)\n i, s, j = (randint(10, 20), ('+', '-')[randint(0, 1)], randint(1, 9))\n text = '%s %s %s' % (i, s, j)\n\n result = i + j if s == '+' else i - j\n\n draw.text((9, 5), text, (50,50,50), font=font)\n\n for i in xrange(0, 500):\n draw.point((randint(0, x), randint(0, y)),\n [(x, x, x) for x in (randint(100,180),)][0])\n\n request.session['test_answer'] = result\n\n response = HttpResponse(mimetype=\"image/png\")\n img.save(response, 'PNG')\n\n return response\n\ndef about(request):\n o = {}\n\n if request.method == 'POST':\n\n bad_answers = request.session.setdefault('bad_answers', 0)\n if bad_answers > 3:\n return HttpResponseForbidden(\n 'Too many failed attempts. Try again later.')\n\n o['form'] = main_forms.FeedbackForm(request.POST)\n if o['form'].is_valid():\n\n test_answer = request.POST.get('testanswer') or '999'\n if int(test_answer, 10) != request.session['test_answer']:\n request.session['bad_answers'] = bad_answers + 1\n o['bad_answer'] = True\n return render_to_response(\n 'about.html', o, context_instance=RequestContext(request))\n request.session.pop('bad_answers')\n\n choice = o['form'].cleaned_data['purpose']\n subj = '(%s) %s' % (\n dict(o['form'].fields['purpose'].choices)[choice],\n o['form'].cleaned_data['name'])\n msg = 'reply to: %(email)s\\n\\n%(message)s' % o['form'].cleaned_data\n mail_admins(subj, msg, fail_silently=True)\n messages.add_message(\n request, messages.SUCCESS,\n 'Thank you. Your feedback has been submitted.')\n return HttpResponseRedirect('/about/')\n else:\n o['form'] = main_forms.FeedbackForm()\n return render_to_response(\n 'about.html', o, context_instance=RequestContext(request))\n\n# ------------------------------------------------------------------------------\n# Individual instances of models\n# ------------------------------------------------------------------------------\n\ndef project(request, project_slug):\n o = {}\n o['project'] = get_object_or_404(Project, slug=project_slug)\n o['log_entries'], ignored = Project.get_activity_for(o['project'], max_count=10)\n if request.user.is_authenticated():\n o['can_change'] = o['project'].attempt('change', request.user)\n o['project_role'] = request.user.get_profile().get_project_role(o['project'])\n return render_to_response(\n 'project.html', o, context_instance=RequestContext(request))\n\ndef topic(request, topic_slug):\n o = {}\n o['topic'] = get_object_or_404(Topic, slug=topic_slug)\n o['contact'] = { 'name': settings.ADMINS[0][0], \n 'email': settings.ADMINS[0][1] }\n o['related_topics'] = o['topic'].related_topics.all()\n o['summary_cites'] = _sort_citations(o['topic'])\n\n notes = o['topic'].related_objects(Note)\n note_topics = [ [ ta.topic for ta in n.topics.exclude(topic=o['topic']).select_related('topic') ] for n in notes ]\n note_sections = NoteSection.objects.filter(note__in=[n.id for n in notes])\n\n o['notes'] = zip(notes, note_topics)\n\n o['documents'] = set(chain(\n o['topic'].related_objects(Document),\n Document.objects.filter(notesection__in=note_sections)))\n\n o['thread'] = { 'id': 'topic-%s' % o['topic'].id, 'title': o['topic'].preferred_name }\n o['alpha'] = (request.user.groups.filter(name='Alpha').count() == 1)\n\n return render_to_response(\n 'topic.html', o, context_instance=RequestContext(request))\n\ndef note(request, note_id):\n o = {}\n o['note'] = get_object_or_404(Note, id=note_id)\n if request.method == 'POST':\n if not request.user.is_authenticated():\n return HttpResponseForbidden()\n form = main_forms.NoteSectionForm(request.POST)\n user = request.user\n if form.is_valid():\n\n # Quick fix with checking if a document field is blank: wymeditor by\n # default posts '
'\n if not (request.POST.get('document') or\n len(request.POST.get('content')) > 6):\n messages.add_message(\n request, messages.ERROR,\n 'Enter a value for one or both of the fields \"Content\" and \"Description\"')\n return HttpResponseRedirect(request.path)\n\n new_section = NoteSection.objects.create(\n creator=user, last_updater=user, note=o['note'])\n if len(request.POST.get('content')) > 6:\n new_section.content = request.POST.get('content')\n if request.POST.get('document'):\n new_section.document = get_object_or_404(\n Document, id=request.POST.get('document'))\n new_section.save()\n\n messages.add_message(\n request,\n messages.SUCCESS,\n 'Added section to %s' % o['note'])\n return HttpResponseRedirect(request.path)\n if request.user.is_authenticated():\n user_profile = request.user.get_profile()\n o['affiliated'] = len([p for p in o['note'].get_project_affiliation() if\n user_profile.get_project_role(p) is not None]) > 0\n o['add_section_form'] = main_forms.NoteSectionForm()\n o['history'] = get_unique_for_object(o['note'])\n o['topics'] = [ ta.topic for ta in o['note'].topics.all() ]\n o['cites'] = _sort_citations(o['note'])\n return render_to_response(\n 'note.html', o, context_instance=RequestContext(request))\n\ndef footnote(request, footnote_id):\n o = {}\n o['footnote'] = get_object_or_404(Footnote, id=footnote_id)\n o['thread'] = { 'id': 'footnote-%s' % o['footnote'].id, \n 'title': o['footnote'].footnoted_text() }\n return render_to_response(\n 'footnote.html', o, context_instance=RequestContext(request))\n\ndef document(request, document_id):\n o = {}\n o['document'] = get_object_or_404(Document, id=document_id)\n o['topics'] = (\n [ ta.topic for ta in o['document'].topics.all() ] +\n [ c.content_object for c in o['document'].citations.filter(\n content_type=ContentType.objects.get_for_model(Topic)) ])\n o['scans'] = o['document'].scans.all()\n o['domain'] = Site.objects.get_current().domain\n\n notes = Note.objects.filter(sections__document=o['document'])\n note_topics = [ [ ta.topic for ta in n.topics.all() ] for n in notes ]\n o['notes'] = zip(notes, note_topics)\n\n if o['document'].zotero_link():\n o['zotero_data'] = as_readable(o['document'].zotero_link().zotero_data)\n o['zotero_url'] = o['document'].zotero_link().zotero_url\n o['zotero_date_information'] = o['document'].zotero_link().date_information\n return render_to_response(\n 'document.html', o, context_instance=RequestContext(request))\n\n\n# ------------------------------------------------------------------------------\n# Aggregations of models\n# ------------------------------------------------------------------------------\n\ndef all_topics(request, project_slug=None):\n o = {}\n if project_slug:\n o['project'] = get_object_or_404(Project, slug=project_slug)\n if 'type' in request.GET:\n o['type'] = request.GET['type']\n o['fragment'] = ''\n template = 'topic-columns.include'\n else:\n o['type'] = 'PER'\n template = 'all-topics.html'\n if project_slug:\n query_set = set([ ta.topic for ta in TopicAssignment.objects.filter(\n creator__userprofile__affiliation=o['project'],\n topic__type=o['type']) ])\n else:\n query_set = Topic.objects.filter(type=o['type'])\n [o['topics_1'], o['topics_2'], o['topics_3']] = utils.alpha_columns(\n query_set, 'slug', itemkey='topic')\n return render_to_response(\n template, o, context_instance=RequestContext(request))\n\ndef all_documents(request, project_slug=None):\n o = {}\n template = 'all-documents.html'\n o['filtered'] = False\n\n if request.GET.get('filter'):\n template = 'filtered-documents.html'\n o['filtered'] = True\n\n # Narrow search query according to GET parameters\n qs = SearchQuerySet().models(Document)\n\n query = []\n params = [p for p in request.GET.keys() if p[-2:] == '[]']\n for param in params:\n this_query = [ '%s:\"%s\"' % (param[:-2], val)\n for val in request.GET.getlist(param) ]\n query += [' AND '.join(this_query)]\n qs = qs.narrow(' AND '.join(query)) if query else qs\n\n # Facet results\n valid_facets = (\n 'project_id',\n 'related_topic_id',\n 'archive',\n 'publicationTitle',\n 'itemType',\n 'creators',\n 'representations'\n )\n for f in valid_facets:\n qs = qs.facet(f)\n\n # Pass facets to template\n o['facets'] = {}\n facet_counts = qs.facet_counts()['fields'] \n for facet in facet_counts:\n\n # Leave out facets with no more than one choice that are not selected\n if len(facet_counts[facet]) == 1 and \\\n facet_counts[facet][0][0] == None and \\\n facet not in params:\n continue\n \n # Sort results & limit to 30\n sorted_facets = sorted(facet_counts[facet],\n key=lambda x: x[1],\n reverse=True)\n sorted_facets = sorted_facets[:30]\n\n # Specific actions for individual facets.\n # Tuple represents one input: value, label, count\n if facet == 'project_id':\n o['facets']['project_id'] = [ (p_id, Project.objects.get(id=p_id), count)\n for p_id, count in sorted_facets ]\n elif facet == 'related_topic_id':\n o['facets']['related_topic_id'] = \\\n [ (t_id, Topic.objects.get(id=t_id), count)\n for t_id, count in sorted_facets ]\n elif facet =='itemType':\n o['facets']['itemType'] = [ (item, type_map['readable'].get(item), count)\n for item, count in sorted_facets ]\n else:\n o['facets'][facet] = [ (f, f, count)\n for f, count in sorted_facets if f ]\n\n o['documents'] = qs\n o['query'] = query\n return render_to_response(\n template, o, context_instance=RequestContext(request))\n\ndef all_notes(request, project_slug=None):\n o = {}\n template = 'all-notes.html'\n o['filtered'] = False\n\n if request.GET.get('filter'):\n template = 'filtered-notes.html'\n o['filtered'] = True\n\n qs = SearchQuerySet().models(Note)\n query = []\n if request.GET.get('topic'):\n query += [ ' AND '.join([ 'related_topic_id:%s' % topic for topic\n in request.GET.get('topic').split(',') ]) ]\n if request.GET.get('project'):\n query += [ ' AND '.join([ 'project_id:%s' % project for project\n in request.GET.get('project').split(',') ]) ]\n qs = qs.narrow(' AND '.join(query)) if query else qs\n\n qs = qs.facet('related_topic_id').facet('project_id')\n facet_fields = qs.facet_counts()['fields']\n topic_facets = sorted(facet_fields['related_topic_id'],\n key=lambda t: t[1], reverse=True)\n project_facets = sorted(facet_fields['project_id'],\n key=lambda p: p[1], reverse=True)\n\n topic_facets = [ (Topic.objects.get(id=t_id), t_count)\n for t_id, t_count in topic_facets[:16] ]\n o['topic_facets_1'] = topic_facets[:8]\n o['topic_facets_2'] = topic_facets[8:] if (len(topic_facets) > 8) else []\n\n o['project_facets'] = [ (Project.objects.get(id=p_id), p_count)\n for p_id, p_count in project_facets ]\n o['notes'] = qs\n\n return render_to_response(\n template, o, context_instance=RequestContext(request)) \n","sub_path":"editorsnotes/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":17539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"151587107","text":"# -*- coding: utf-8 -*-\n#\n# This file is part of the SKALogger project\n#\n#\n#\n\"\"\" SKALogger\n\nA generic base device for Logging for SKA. It enables to view on-line logs through the TANGO Logging Services\nand to store logs using Python logging. It configures the log levels of remote logging for selected devices.\n\"\"\"\n# PROTECTED REGION ID(SKALogger.additionnal_import) ENABLED START #\n# Standard imports\nimport os\nimport sys\nimport numpy\nfrom future.utils import with_metaclass\n\n# Tango imports\nimport tango\n\nfrom tango import DebugIt, DeviceProxy, DevFailed\nfrom tango.server import run, DeviceMeta, command\n\n# SKA specific imports\nfrom skabase import release\nfile_path = os.path.dirname(os.path.abspath(__file__))\nbasedevice_path = os.path.abspath(os.path.join(file_path, os.pardir)) + \"/SKABaseDevice\"\nsys.path.insert(0, basedevice_path)\nfrom SKABaseDevice import SKABaseDevice\n# PROTECTED REGION END # // SKALogger.additionnal_import\n\n__all__ = [\"SKALogger\", \"main\"]\n\n\nclass SKALogger(with_metaclass(DeviceMeta, SKABaseDevice)):\n \"\"\"\n A generic base device for Logging for SKA.\n \"\"\"\n # PROTECTED REGION ID(SKALogger.class_variable) ENABLED START #\n # PROTECTED REGION END # // SKALogger.class_variable\n\n # -----------------\n # Device Properties\n # -----------------\n\n # ----------\n # Attributes\n # ----------\n\n # ---------------\n # General methods\n # ---------------\n\n def init_device(self):\n SKABaseDevice.init_device(self)\n # PROTECTED REGION ID(SKALogger.init_device) ENABLED START #\n self._build_state = '{}, {}, {}'.format(release.name, release.version,\n release.description)\n self._version_id = release.version\n self._storage_logging_level = int(tango.LogLevel.LOG_DEBUG)\n self._element_logging_level = int(tango.LogLevel.LOG_DEBUG)\n self._central_logging_level = int(tango.LogLevel.LOG_DEBUG)\n # PROTECTED REGION END # // SKALogger.init_device\n\n def write_storageLoggingLevel(self, value):\n # PROTECTED REGION ID(SKALogger.write_storageLoggingLevel) ENABLED START #\n self._storage_logging_level = value\n # PROTECTED REGION END # // SKALogger.write_storageLoggingLevel\n\n def always_executed_hook(self):\n # PROTECTED REGION ID(SKALogger.always_executed_hook) ENABLED START #\n pass\n # PROTECTED REGION END # // SKALogger.always_executed_hook\n\n def delete_device(self):\n # PROTECTED REGION ID(SKALogger.delete_device) ENABLED START #\n pass\n # PROTECTED REGION END # // SKALogger.delete_device\n\n # ------------------\n # Attributes methods\n # ------------------\n\n # --------\n # Commands\n # --------\n\n @command(dtype_in=('str',), doc_in=\"Details of timestamp, logging level, source device and message.\",\n dtype_out='str', doc_out=\"Returns the logging message.\")\n @DebugIt()\n def Log(self, argin):\n # PROTECTED REGION ID(SKALogger.Log) ENABLED START #\n \"\"\"\n A method of LogConsumer Interface, to enable log messages appear in Tango log viewer.\n\n :parameter: argin: DevVarStringArray\n Consists a list of strings. The individual items in the list are as follows:\n\n argin[0] : the timestamp in millisecond since epoch (01.01.1970)\n\n argin[1] : the log level\n\n argin[2] : the log source (i.e. device name)\n\n argin[3] : the log message\n\n argin[4] : the log NDC (contextual info) - Not used but reserved\n\n argin[5] : the thread identifier (i.e. the thread from which the log request comes from)\n\n :returns: DevString.\n Returns the log message when successful. Empty string if fail.\n \"\"\"\n log_level = argin[1]\n log_source = argin[2]\n log_message = argin[3]\n tango_log_level = {\"FATAL\": int(tango.LogLevel.LOG_FATAL),\n \"ERROR\": int(tango.LogLevel.LOG_ERROR),\n \"WARN\": int(tango.LogLevel.LOG_WARN),\n \"INFO\": int(tango.LogLevel.LOG_INFO),\n \"DEBUG\": int(tango.LogLevel.LOG_DEBUG)}\n level_number = tango_log_level[log_level]\n\n # Check source devices Central and Element logging levellogging\n try:\n device = DeviceProxy(log_source)\n except DevFailed:\n self.error_stream(\"%s : Failed to create device proxy.\", __name__)\n return \"\"\n\n device_log_level = -1\n if self.SkaLevel == 1:\n device_log_level = device.centralLoggingLevel\n elif self.SkaLevel == 2:\n device_log_level = device.elementLoggingLevel\n\n if log_level == \"FATAL\" and level_number <= device_log_level:\n self.fatal_stream(\"%s : %s\", log_source, log_message)\n elif log_level == \"ERROR\" and level_number <= device_log_level:\n self.error_stream(\"%s : %s\", log_source, log_message)\n elif log_level == \"WARN\" and level_number <= device_log_level:\n self.warn_stream(\"%s : %s\", log_source, log_message)\n elif log_level == \"INFO\" and level_number <= device_log_level:\n self.info_stream(\"%s : %s\", log_source, log_message)\n elif log_level == \"DEBUG\" and level_number <= device_log_level:\n self.debug_stream(\"%s : %s\", log_source, log_message)\n\n return str(log_message)\n\n # TODO Add dictionary for log sources\n # logger = logger_dict.get(logSource)\n # if not logger:\n # logger = logging.getLogger(logSource)\n # logger.setLevel(logging.INFO)\n # # Add the log message handler to the logger\n # syslog = SysLogHandler(address='/dev/log')\n # logger.addHandler(syslog)\n # logger.debug('this is debug')\n # logger.critical('this is critical')\n #logger_dict[logSource] = logger\n # This should log at the specified level\n #logger.info(\"{}]\\t{}\".format(timestamp, logMessage))\n\n # PROTECTED REGION END # // SKALogger.Log\n\n @command(dtype_in='DevVarLongStringArray', doc_in=\"Central logging level for selected devices\",)\n @DebugIt()\n def SetCentralLoggingLevel(self, argin):\n # PROTECTED REGION ID(SKALogger.SetCentralLoggingLevel) ENABLED START #\n \"\"\"\n Sets Central logging level of the source device.\n\n :parameter: argin: DevVarLogStringArray\n Array consisting of\n\n argin[0]: DevLong. Desired logging level\n\n argin[1]: DevString. Desired tango device\n\n :returns: None.\n \"\"\"\n central_logging_level = argin[0][:]\n #To convert the type of log level from numpy.ndarray to list. Needs to fix in PyTango.\n if type(central_logging_level) is numpy.ndarray:\n central_logging_level = central_logging_level.tolist()\n else:\n pass\n\n central_logging_device = argin[1][:]\n i = 0\n while i < len(central_logging_level[:]):\n try:\n self.info_stream(\"Central Logging level : %s, Device : %s\",\n central_logging_level[i],\n central_logging_level[i])\n dev_proxy = DeviceProxy(central_logging_device[i])\n dev_proxy.centralLoggingLevel = central_logging_level[i]\n except DevFailed as dev_failed:\n self.error_stream(\"Failed to set Central Logging level for [%s]\", central_logging_level[i])\n str_exception = \"Exception: \" + str(dev_failed)\n self.error_stream(str_exception)\n i += 1\n\n # PROTECTED REGION END # // SKALogger.SetCentralLoggingLevel\n\n @command(dtype_in='DevVarLongStringArray', doc_in=\"Element logging level for selected devices\",)\n @DebugIt()\n def SetElementLoggingLevel(self, argin):\n # PROTECTED REGION ID(SKALogger.SetElementLoggingLevel) ENABLED START #\n \"\"\"\n Set Element logging level of source device.\n\n :parameter: argin: DevVarLogStringArray\n Array consisting of\n\n argin[0]: DevLong. Desired logging level\n\n argin[1]: DevString. Desired tango device\n\n :returns: None.\n \"\"\"\n element_logging_level = argin[0][:]\n #To convert the type of log level from numpy.ndarray to list. Needs to fix in PyTango.\n if type(element_logging_level) is numpy.ndarray:\n element_logging_level = element_logging_level.tolist()\n else:\n pass\n\n element_logging_device = argin[1][:]\n i = 0\n while i < len(element_logging_level[:]):\n try:\n self.info_stream(\"Element Logging level : %s, Device : %s\",\n element_logging_level[i],\n element_logging_device[i])\n dev_proxy = DeviceProxy(element_logging_device[i])\n dev_proxy.elementLoggingLevel = element_logging_level[i]\n except DevFailed as dev_failed:\n self.error_stream(\"Failed to set Element Logging level for [%s]\", element_logging_device[i])\n str_exception = \"Exception: \" + str(dev_failed)\n self.error_stream(str_exception)\n i += 1\n # PROTECTED REGION END # // SKALogger.SetElementLoggingLevel\n\n @command(dtype_in='DevVarLongStringArray', doc_in=\"Storage logging level for selected devices\",)\n @DebugIt()\n def SetStorageLoggingLevel(self, argin):\n # PROTECTED REGION ID(SKALogger.SetStorageLoggingLevel) ENABLED START #\n \"\"\"\n Sets Storage logging level of source device.\n\n :parameter: argin: DevVarLogStringArray\n Array consisting of\n\n argin[0]: DevLong. Desired logging level\n \n argin[1]: DevString. Desired tango device\n\n :returns: None.\n \"\"\"\n storage_logging_level = argin[0][:]\n #To convert the type of log level from numpy.ndarray to list. Needs to fix in PyTango.\n if type(storage_logging_level) is numpy.ndarray:\n storage_logging_level = storage_logging_level.tolist()\n else:\n pass\n\n storage_logging_device = argin[1][:]\n i = 0\n while i < len(storage_logging_level[:]):\n try:\n self.info_stream(\"Storage logging level : %s, Device : %s\",\n storage_logging_level[i],\n storage_logging_device[i])\n dev_proxy = DeviceProxy(storage_logging_device[i])\n dev_proxy.storageLoggingLevel = storage_logging_level[i]\n except DevFailed as dev_failed:\n self.error_stream(\"Failed to set Storage Logging level for [%s]\", storage_logging_device[i])\n str_exception = \"Exception: \" + str(dev_failed)\n self.error_stream(str_exception)\n i += 1\n # PROTECTED REGION END # // SKALogger.SetStorageLoggingLevel\n\n# ----------\n# Run server\n# ----------\n\n\ndef main(args=None, **kwargs):\n # PROTECTED REGION ID(SKALogger.main) ENABLED START #\n \"\"\"\n Main entry point of the module.\n \"\"\"\n return run((SKALogger,), args=args, **kwargs)\n # PROTECTED REGION END # // SKALogger.main\n\nif __name__ == '__main__':\n main()\n","sub_path":"skabase/SKALogger/SKALogger.py","file_name":"SKALogger.py","file_ext":"py","file_size_in_byte":11405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"642542757","text":"#!/usr/bin/env python\n# ***********************************************************************************************************\n#\n# Starfish Storage Corporation (\"COMPANY\") CONFIDENTIAL\n# Unpublished Copyright (c) 2011-2017 Starfish Storage Corporation, All Rights Reserved.\n#\n# NOTICE: All information contained herein is, and remains the property of COMPANY. The intellectual and\n# technical concepts contained herein are proprietary to COMPANY and may be covered by U.S. and Foreign\n# Patents, patents in process, and are protected by trade secret or copyright law. Dissemination of this\n# information or reproduction of this material is strictly forbidden unless prior written permission is\n# obtained from COMPANY. Access to the source code contained herein is hereby forbidden to anyone except\n# current COMPANY employees, managers or contractors who have executed Confidentiality and Non-disclosure\n# agreements explicitly covering such access.\n#\n# ANY REPRODUCTION, COPYING, MODIFICATION, DISTRIBUTION, PUBLIC PERFORMANCE, OR PUBLIC DISPLAY OF OR\n# THROUGH USE OF THIS SOURCE CODE WITHOUT THE EXPRESS WRITTEN CONSENT OF COMPANY IS STRICTLY PROHIBITED,\n# AND IN VIOLATION OF APPLICABLE LAWS AND INTERNATIONAL TREATIES. THE RECEIPT OR POSSESSION OF THIS SOURCE\n# CODE AND/OR RELATED INFORMATION DOES NOT CONVEY OR IMPLY ANY RIGHTS TO REPRODUCE, DISCLOSE OR DISTRIBUTE\n# ITS CONTENTS, OR TO MANUFACTURE, USE, OR SELL ANYTHING THAT IT MAY DESCRIBE, IN WHOLE OR IN PART.\n#\n# FOR U.S. GOVERNMENT CUSTOMERS REGARDING THIS DOCUMENTATION/SOFTWARE\n# These notices shall be marked on any reproduction of this data, in whole or in part.\n# NOTICE: Notwithstanding any other lease or license that may pertain to, or accompany the delivery of,\n# this computer software, the rights of the Government regarding its use, reproduction and disclosure are\n# as set forth in Section 52.227-19 of the FARS Computer Software-Restricted Rights clause.\n# RESTRICTED RIGHTS NOTICE: Use, duplication, or disclosure by the Government is subject to the\n# restrictions as set forth in subparagraph (c)(1)(ii) of the Rights in Technical Data and Computer\n# Software clause at DFARS 52.227-7013.\n#\n# ***********************************************************************************************************\n# -*- coding: utf-8 -*-\n\"\"\"\n Part of the distribution\n\"\"\"\n\"\"\"\n used to stub a file\n 1. Check file is regular\n 2. make copy (with invisible read) at destination\n 3. Make stub from source file (save first block)\n 4. add extended attributes for destination file path and file length in stub\n 5. make IO region around stub\n\"\"\"\n__author__='brad elkin'\n\nimport os\nimport hashlib\nimport subprocess as sp\nimport sys\n\nfrom sf_gpfs import event_context\n\n# offset = 262144\noffset = 512\ndef hashFile(filename):\n BLKSZ = 8*1024\n hashF = hashlib.md5()\n with open(filename,'rb') as fileToHash:\n bufferS = fileToHash.read(BLKSZ)\n while (len(bufferS) > 0):\n hashF.update(bufferS)\n bufferS = fileToHash.read(BLKSZ)\n return hashF.hexdigest()\n\ndef file_stubber(sourceFile,destFile):\n# destFile must be supplied - but is used to redirect stdout copyStdout\n# if destFile is a directory, use the destFile/ as the target file\n# fail if sourceFile can't be found, destFile isn't provided on cmd line or destFile already exists\n copyOutCmd = ['copyStdout',sourceFile]\n makeStubCmd = ['makeFileStub','-o',str(offset),sourceFile]\n AddXAttrFilePathCmd = 'mmchattr ' + '--set-attr user.sf-gpfs.stub-path=' + destFile + ' ' + sourceFile\n# REFACTOR: try-except around stat()\n statB = os.lstat(sourceFile)\n AddXAttrFileLenCmd = 'mmchattr '+'--set-attr user.sf-gpfs.stub-length=' + str(statB.st_size) + ' ' + sourceFile\n LsXAttrFilePathCmd = \" \".join(['mmlsattr', '-n', 'user.sf-gpfs.stub-path', sourceFile])\n LsXAttrFileLenCmd = \" \".join(['mmlsattr', '-n', 'user.sf-gpfs.stub-length', sourceFile])\n# don't just set region from beginning through offset bytes\n# - a user accessing any bytes should force restore\n SetRegionCmd = ['set_region',sourceFile]\n GetRegionCmd = ['get_region',sourceFile]\n GetAllocInfoCmd = ['get_allocinfo -D',sourceFile]\n dest_fd = open(destFile,'w')\n p1 = sp.Popen(copyOutCmd,stdout=dest_fd,universal_newlines=True)\n retcode = p1.returncode\n if retcode:\n print(\"copying source file %s out to %s failed\" % sourceFile,destFile)\n sys.exit(1)\n retcode = sp.call(makeStubCmd)\n if retcode:\n print(\"stubbing source file %s failed\" % sourceFile,destFile)\n sys.exit(1)\n retcode = sp.call(AddXAttrFilePathCmd.split())\n if retcode:\n print(\"Adding destination path %s to attributes of stubbed source file %s failed\" % destFile,sourceFile)\n sys.exit(1)\n retcode = sp.call(AddXAttrFileLenCmd.split())\n if retcode:\n print(\"Adding source file length %d to attributes of stubbed source file %s failed\" % statB.st_size,sourceFile)\n sys.exit(1)\n retcode = sp.call(SetRegionCmd)\n if retcode:\n print(\"setting IO region around source file %s failed\" % sourceFile,destFile)\n sys.exit(1)\n \"\"\"\n retcode = os.popen(LsXAttrFilePathCmd).read().strip('\"')\n print(\"File path %s\\n\" %(retcode,) )\n retcode = os.popen(LsXAttrFileLenCmd).read().strip('\"')\n print(\"File Len %s\\n\" %(retcode,) )\n retcode = os.popen(GetRegionCmd).read().strip('\"')\n print(\"Region %s\\n\" %(retcode,) )\n retcode = sp.check_output(GetAllocInfoCmd,universal_newlines=True).strip('\"').split()\n print(\"Extent Allocation %s\\n\" %(retcode,) )\n \"\"\"\n\nif __name__ == \"__main__\":\n\n if (len(sys.argv) < 3):\n print('sys argv {}'.format(sys.argv))\n print(\"Usage: fileStubber.py \")\n print(\"Supply path of file to be copied and a destination\\n\")\n print(\"Command submitted:\\n\\t\\t %s\\n\" % \" \".join(sys.argv))\n sys.exit(1)\n if (len(sys.argv) == 3):\n sourceFile = sys.argv[1]\n destFile = sys.argv[2]\n if ( os.path.isdir(destFile)):\n destDir = destFile # clarify that file is really a directory\n filehash=hashFile(sourceFile)\n destFile = os.path.join(destDir,filehash)\n if ( not os.path.isfile(sourceFile )):\n print(\"File to be copied is not a regular file: %s\",sourceFile)\n sys.exit(9)\n if ( os.path.exists(destFile)):\n print(\"destination file %s already exists. Check whether the file can be removed or the filepath is in error\",destFile)\n sys.exit(17)\n\n file_stubber(sourceFile,destFile)\n","sub_path":"sf-gpfs/gpfsmonitor/src/sf_gpfs/fileStdStubber.py","file_name":"fileStdStubber.py","file_ext":"py","file_size_in_byte":6669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"274669070","text":"#!/usr/bin/env python\n# coding=utf8\n\n\"\"\"\n用于判断评论的情感极性,即好评与差评\n终端运行:python run_terminal.py 衣服真好 好评\n\"\"\"\n\nimport sys\n\nfrom snownlp import SnowNLP\n\nif __name__==\"__main__\":\n texts= sys.argv[1:]\n sent = ' '.join(texts)\n try:\n # 计算句子得分\n prob = round(SnowNLP(sent).sentiments,2)\n except:\n print(\"SnowNLP(sent).sentiments Error!\")\n else:\n # 大于0.55为好评\n if prob > 0.55:\n pos_neg = \"好评\"\n elif prob < 0.45:\n pos_neg = \"差评\"\n else:\n pos_neg = \"中性\"\n print(\"\\\"%s\\\"为\\\"%s\\\", score为%s\" % (sent,pos_neg,prob))\n","sub_path":"run_terminal.py","file_name":"run_terminal.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"78914433","text":"import django\r\ndjango.setup()\r\nimport re\r\nimport json\r\nimport copy\r\nfrom functools import partial\r\nfrom sefaria.model import *\r\nfrom linking_utilities.dibur_hamatchil_matcher import match_ref\r\nfrom rif_utils import maor_tags, hebrewplus, remove_metadata, get_hebrew_masechet, path\r\nfrom sefaria.system.exceptions import InputError\r\n\r\ndef find_dh(comm, masechet, rif=True):\r\n gemara_tag = maor_tags[masechet]['gemara page']\r\n comm = hebrewplus(comm, '\"\\'')[:200]\r\n if (rif and gemara_tag and gemara_tag in comm) or (not rif and (not gemara_tag or gemara_tag not in rif)):\r\n #when gemara_tag in comm it means this comment is on gemara and nod not rif\r\n return ''\r\n if \"פי'\" in comm:\r\n comm = comm.split(\"פי'\")[0]\r\n elif \"כו'\" in comm:\r\n comm = \"כו'\".join(comm.split(\"כו'\")[:-1])\r\n else:\r\n comm = ' '.join(comm.split()[:8])\r\n predhs = ['הא דתנן', 'הא דתניא', 'הא דאיתמר', 'והא ד', 'הרי\"ף ז\"ל', 'הרי\"ף']\r\n if any(predh in comm for predh in predhs):\r\n for predh in predhs:\r\n if predh in comm[:20]:\r\n comm = comm.split(predh, 1)[1]\r\n else:\r\n comm = ' '.join(comm.split()[3:])\r\n return comm\r\n\r\ndef mil_dh(string):\r\n dh = string.split(':')[0]\r\n dh = hebrewplus(dh, '\"\\'').strip()\r\n dh = re.sub(' +', ' ', dh)\r\n dh = re.split(\" וכו'| כו'\", dh)[0]\r\n predhs = ['עוד כתב בספר המאור ז\"ל', 'כתב בספר המאור ז\"ל', 'כתוב בספר המאור', 'ועוד', 'וכתב עוד', 'ומה שכתב עוד', 'ומ\"ש עוד', 'עוד', 'ומה שכתב', 'וכתוב בספר המאור', 'ומה שכתב']\r\n newdh = dh\r\n for predh in predhs:\r\n if dh.startswith(predh):\r\n newdh = dh.split(predh, 1)[1]\r\n return newdh\r\n\r\ndef split_dh(dh):\r\n return re.split(\" וכו'| כו'\", dh)\r\n\r\ndef base_tokenizer(string, masechet):\r\n if masechet not in ['Chagigah', 'Sotah']:\r\n string = remove_metadata(string, masechet)\r\n string = re.sub(r'.*?<\\/i>', '', string)\r\n string = re.sub('<[^>]*>|\\([^)]*\\)', '', string)\r\n return string.split()\r\n\r\ndef unpack_ref(tref):\r\n tref = tref.split()[-1]\r\n tref = tref.split('-')[0]\r\n a, c = re.split('[ab]:', tref)\r\n b = re.findall('[ab]', tref)[0]\r\n return int(a), b, int(c)\r\n\r\ndef find_gemara(rif, masechet):\r\n gemara_refs = [link.refs for link in rif.linkset() if link.generated_by == 'rif gemara matcher']\r\n gemara_refs = [ref for refs in gemara_refs for ref in refs if 'Rif' not in ref and masechet in ref]\r\n gemara_refs.sort(key = unpack_ref)\r\n if gemara_refs:\r\n first = gemara_refs[0].split('-')[0]\r\n last = re.sub(r'\\d*-', '', gemara_refs[-1].split()[-1])\r\n if last.count(':') == 2: #means two pages in ref\r\n last = last.split(':', 1)[1]\r\n return f'{first}-{last}'\r\n\r\nfor masechet in maor_tags:\r\n print(masechet)\r\n links = []\r\n gemara_tag = maor_tags[masechet]['gemara page']\r\n if masechet == 'intro':\r\n continue\r\n elif masechet in library.get_indexes_in_category([\"Talmud\", \"Bavli\", \"Seder Nashim\"])+library.get_indexes_in_category([\"Talmud\", \"Bavli\", \"Seder Nezikin\"]):\r\n title = f'HaMaor HaGadol on {masechet}'\r\n else:\r\n title = f'HaMaor HaKatan on {masechet}'\r\n library.get_index(title).versionState().refresh()\r\n pages = [ref for ref in Ref(title).all_subrefs() if ref.text('he').text]\r\n for page in pages:\r\n maor = page.text('he')\r\n if masechet not in ['Chagigah', 'Sotah']:\r\n rif = Ref(f'Rif {page.tref.split(\" on \")[1]}')\r\n trif = rif.text('he')\r\n if trif.text:\r\n rif_matches = match_ref(trif, maor, partial(base_tokenizer, masechet=masechet), dh_extract_method=partial(find_dh, masechet=masechet), dh_split=split_dh)[\"matches\"]\r\n else: #an empty page. we want links to gemara\r\n rif_matches = [None for _ in maor.text]\r\n if len(rif_matches) != len(maor.text):\r\n print(f'{len(maor.text)} paragraphs in text but {len(rif_matches)} in matches')\r\n else:\r\n rif_matches = [None]\r\n\r\n for n, match in enumerate(rif_matches):\r\n if masechet in ['Chagigah', 'Sotah']:\r\n maor_tref = f\"{page}\"\r\n else:\r\n maor_tref = f\"{page}:{n+1}\"\r\n\r\n if match:\r\n links.append({\"refs\": [maor_tref, match.tref],\r\n \"type\": \"Commentary\",\r\n \"auto\": True,\r\n \"generated_by\": 'maor rif project'})\r\n gemara_ref = find_gemara(Ref(match.tref), masechet)\r\n elif gemara_tag and gemara_tag in Ref(maor_tref).text('he').text:\r\n gemara_ref = re.findall(r'{}\\[(.*?)\\]'.format(gemara_tag), Ref(maor_tref).text('he').text)[0]\r\n gemara_ref = f'{get_hebrew_masechet(masechet)} {gemara_ref}'\r\n try:\r\n Ref(gemara_ref)\r\n prev = gemara_ref\r\n except InputError:\r\n if 'ע\"ב' in prev:\r\n gemara_ref = prev.replace('ע\"א', 'ע\"ב')\r\n else:\r\n gemara_ref = prev\r\n try:\r\n Ref(gemara_ref)\r\n prev = gemara_ref\r\n except InputError:\r\n print(gemara_ref)\r\n gemara_ref=''\r\n elif masechet not in ['Chagigah', 'Sotah']:\r\n gemara_ref = find_gemara(rif, masechet)\r\n else:\r\n gemara_ref = ''\r\n\r\n if gemara_ref:\r\n gemara_match = match_ref(Ref(gemara_ref).text('he'), Ref(maor_tref).text('he'), partial(base_tokenizer, masechet=masechet), dh_extract_method=partial(find_dh, masechet=masechet), dh_split=split_dh)[\"matches\"][0]\r\n if gemara_ref=='סוטה דף לא:': print(gemara_match)\r\n if gemara_match:\r\n links.append({\"refs\": [maor_tref, gemara_match.tref],\r\n \"type\": \"Commentary\",\r\n \"auto\": True,\r\n \"generated_by\": 'maor rif project'})\r\n\r\n if masechet not in ['Chagigah', 'Sotah']:\r\n m_title = f'Milchemet Hashem on {masechet}'\r\n library.get_index(m_title).versionState().refresh()\r\n mil_pages = [ref for ref in Ref(m_title).all_subrefs() if ref.text('he').text]\r\n for page in mil_pages:\r\n p = page.tref.split()[-1]\r\n if len(page.text('he').text) >= len(Ref(f'{title} {p}').text('he').text):\r\n for n, _ in enumerate(page.text('he').text):\r\n if page == 'Milchemet Hashem on Bava Kamma 33a':\r\n if n == 1:\r\n continue\r\n else:\r\n mil_ref = f'{page}:{n}'\r\n else:\r\n mil_ref = f'{page}:{n+1}'\r\n maor_ref = f'{title} {p}:{n+1}'\r\n if Ref(maor_ref).is_empty():\r\n continue\r\n links.append({\"refs\": [mil_ref, maor_ref],\r\n \"type\": \"Commentary\",\r\n \"auto\": True,\r\n \"generated_by\": 'maor rif project'})\r\n for link in links:\r\n if link['refs'][0] == maor_ref:\r\n l = copy.deepcopy(link)\r\n l['refs'][0] = mil_ref\r\n links.append(l)\r\n\r\n else:\r\n t_maor = Ref(f'{title} {p}').text('he')\r\n t_mil = page.text('he')\r\n maor_matches = match_ref(t_maor, t_mil, partial(base_tokenizer, masechet=masechet), dh_extract_method=mil_dh)[\"matches\"]\r\n for n, match in enumerate(maor_matches):\r\n if match:\r\n mil_ref = f'{page}:{n+1}'\r\n maor_ref = match.tref\r\n links.append({\"refs\": [mil_ref, maor_ref],\r\n \"type\": \"Commentary\",\r\n \"auto\": True,\r\n \"generated_by\": 'maor rif project'})\r\n for link in links:\r\n if link['refs'][0] == maor_ref:\r\n l = copy.deepcopy(link)\r\n l['refs'][0] = mil_ref\r\n links.append(l)\r\n\r\n with open(f'{path}/commentaries/json/maor_links_{masechet}.json', 'w') as fp:\r\n json.dump(links, fp)\r\n","sub_path":"sources/newRif/maor_links.py","file_name":"maor_links.py","file_ext":"py","file_size_in_byte":8644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"148213318","text":"import numpy as np\nimport config\nfrom rpy2.robjects import numpy2ri\nfrom rpy2.robjects.packages import importr\nfrom numpy.linalg import pinv\n\nscca = importr('scca')\n\n\nclass SCCAR:\n def __init__(self):\n self.isFitAndPredict = \"True\"\n self.name = \"SCCAR\"\n self.model = \"SCCAR\"\n\n def fit(self, input, output):\n numpy2ri.activate()\n sccaModel = scca.scca(input, output, nc=config.N_SCCA, center=False)\n self.WX = np.asmatrix(sccaModel.rx2('A'))\n self.WY = np.asmatrix(sccaModel.rx2('B'))\n numpy2ri.deactivate()\n\n def predict(self, input):\n xwx = np.matmul(input, self.WX)\n xwxwyt = np.matmul(xwx, self.WY.transpose())\n yyt = np.matmul(self.WY, self.WY.transpose())\n invyyt = pinv(yyt)\n pred = np.matmul(xwxwyt, invyyt)\n return np.asarray(pred)\n\n def fitAndPredict(self, input, output, inputTest):\n self.fit(input, output)\n self.repred = self.predict(input)\n pred = self.predict(inputTest)\n print(self.repred.shape, pred.shape)\n return pred\n\n def getParams(self):\n return \"SCCA: %s \" % config.N_SCCA\n","sub_path":"models/baselines/sccar.py","file_name":"sccar.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"379635383","text":"import socket\nfrom utils import sanitize, _input\n#connection = sanitize(_input(\"connection string\",128))\n# mode,public,local,port,id\n# example of local connect_id 178.30:5050:44\n# example of public connect_id 5.500.200.10:178.30:30\n\n#setup \nSERVER = ''\ninput_str = \"178.30:53006:44\"\nc = input_str.split(':')\nif len(c) == 3:\n SERVER = \"192.168.\"+c[0]\nelif len(c) == 4: \n SERVER = c[0]\nelse: \n print(\"connection input invalid error\")\n exit()\n\nPORT = int(c[1])\nID = int(c[2])\nprint(SERVER,PORT ,ID)\n\nHEADER= 10\nFORMAT = 'utf-8'\nDISCONNECT_MESSAGE = \"!DISCONNECT\"\nADDR = (SERVER, PORT)\n\nclient = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n#blocking, can timeout\nclient.connect(ADDR)\nprint(f\"connected to server {ADDR[0]} at {ADDR[1]}\")\n\ndef send(message):\n message = message.encode(FORMAT)\n message_header = f\"{len(message):<{HEADER}}\".encode('utf-8')\n msg = message_header + message\n client.send(msg)\n if message.decode(FORMAT) == DISCONNECT_MESSAGE: \n return False\n receive(client)\n return True\n\ndef receive(conn):\n message_header = conn.recv(HEADER)\n msg_length = int(message_header.decode('utf-8').strip())\n if msg_length:\n msg_length = int(msg_length)\n msg = conn.recv(msg_length).decode(FORMAT)\n print(f\"{msg}\")\n\nsending = True\nwhile sending: \n msg = _input(\"client\",1024)\n sending = send(msg)\n #send(DISCONNECT_MESSAGE)\n\nclient.close()\nexit()\n\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"384302653","text":"DICC = {\n 'a':0,\n 'b':1,\n 'c':2,\n 'd':3,\n 'e':4,\n 'f':5,\n 'g':6,\n 'h':7,\n 'i':8,\n 'j':9,\n 'k':10,\n 'l':11,\n 'm':12,\n 'n':13,\n 'ñ':14,\n 'o':15,\n 'p':16,\n 'q':17,\n 'r':18,\n 's':19,\n 't':20,\n 'u':21,\n 'v':22,\n 'w':23,\n 'x':24,\n 'y':25,\n 'z':26,\n ' ':27,\n} \n\ndef encriptar(message):\n letters = list(message)\n cypher_message = []\n for letter in letters:\n for key,value in DICC.items():\n if letter == key:\n cypher_message.append(value)\n print(cypher_message)\n\n\n\ndef desencriptar(list_numbers):\n descypher = []\n for number in list_numbers:\n for key,value in DICC.items():\n if value == number:\n descypher.append(key)\n print(descypher)\n\n","sub_path":"cursos/python_platzi_curso_COMPLETADO/p_02_estructura_de_datos/cifrar_desifrar.py","file_name":"cifrar_desifrar.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"394923804","text":"# This file is part of MaixUI\n# Copyright (c) sipeed.com\n#\n# Licensed under the MIT license:\n# http://www.opensource.org/licenses/mit-license.php\n#\n\ntry:\n from ui_canvas import ui\n from button import sipeed_button\nexcept ImportError:\n from ui.ui_canvas import ui\n from driver.button import sipeed_button\n\nimport os\nimport machine\nimport ubinascii\n\n\nclass sys_info:\n\n def sizeof_fmt(num, suffix='B'):\n for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']:\n if abs(num) < 1024.0:\n return \"%3.1f%s%s\" % (num, unit, suffix)\n num /= 1024.0\n return \"%.1f%s%s\" % (num, 'Yi', suffix)\n\n def __init__(self):\n self.__initialized = False\n\n def __lazy_init(self):\n self.system_uname = os.uname()\n self.device_id = ubinascii.hexlify(machine.unique_id()).decode()\n root_files = os.listdir('/')\n self.fs_info_list = []\n for f in root_files:\n fs_path = '/' + f\n fs_stat = os.statvfs(fs_path)\n bs1 = fs_stat[0]\n bs2 = fs_stat[1]\n total_blocks = fs_stat[2]\n free_blocks = fs_stat[3]\n info = \"%s total=%s free=%s\" % (\n fs_path,\n sys_info.sizeof_fmt(bs1 * total_blocks),\n sys_info.sizeof_fmt(bs2 * free_blocks)\n )\n self.fs_info_list.append(info)\n print(info)\n self.__initialized = True\n\n def draw(self, img):\n if not self.__initialized:\n self.__lazy_init()\n img.draw_rectangle(\n (20, 30, 200, 200), fill=True, color=(50, 50, 50))\n x, y = 30, 32\n img.draw_string(x, y, \"Information\", (255, 0, 0), scale=2)\n y += 22\n img.draw_string(x, y, \"-----------------------------\", (255, 255, 255))\n y += 16\n img.draw_string(x, y, \"Uname:\", (255, 0, 0))\n y += 16\n img.draw_string(x, y, self.system_uname.machine, (0, 255, 0))\n y += 20\n #img.draw_string(x, y, \"-----------------------------\", (255, 255, 255))\n # y += 16\n img.draw_string(x, y, \"FirmwareVersion:\", (255, 0, 0))\n y += 16\n img.draw_string(x, y, self.system_uname.version[:34], (0, 255, 0))\n y += 20\n #img.draw_string(x, y, \"-----------------------------\", (255, 255, 255))\n # y += 16\n img.draw_string(x, y, \"machine id:\", (255, 0, 0))\n y += 16\n img.draw_string(x, y, self.device_id[:30], (0, 255, 0))\n y += 20\n img.draw_string(x, y, \"-----------------------------\", (255, 255, 255))\n for info in self.fs_info_list:\n y += 16\n img.draw_string(x, y, info, (255, 0, 0))\n\n\nclass pages:\n\n def __init__(self):\n self.btn = sipeed_button()\n self.page_info = sys_info()\n self.page = 0\n self.tips = \"Weclome to MaixCube\"\n\n def draw(self):\n self.btn.event()\n\n if self.btn.back() == 2:\n self.page -= 1\n elif self.btn.next() == 2:\n self.page += 1\n self.page = self.page % 3\n\n if self.page == 0:\n ui.canvas.draw_string(20, 30, self.tips,\n (255, 124, 12), scale=2)\n if self.page == 1:\n self.page_info.draw(ui.canvas)\n if self.page == 2:\n ui.canvas.draw_string(40, 200, \"Enjoy it! :D\", (51, 169, 212), scale=2)\n\n\nif __name__ == \"__main__\":\n\n tmp = pages()\n\n @ui.warp_template(ui.blank_draw)\n @ui.warp_template(ui.grey_draw)\n #@ui.warp_template(ui.bg_in_draw)\n @ui.warp_template(ui.anime_draw)\n @ui.warp_template(tmp.draw)\n def unit_test():\n print('1 display : ' + str(gc.mem_free() / 1024) + ' kb')\n ui.display()\n print('2 display : ' + str(gc.mem_free() / 1024) + ' kb')\n\n import time\n while True:\n print('while True : ' + str(gc.mem_free() / 1024) + ' kb')\n unit_test()\n","sub_path":"ui/ui_pages.py","file_name":"ui_pages.py","file_ext":"py","file_size_in_byte":3715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"413422756","text":"import dbm\n\ndb = dbm.open('captions', 'c')\n\ndb['cleese.png'] = 'Фотография Ивана Клизина.'\n\nprint(db['cleese.png'].decode('utf-8'))\n\ndb.close()\n\nformatStr = 'It costs %d dollars' % 23\nprint(formatStr)","sub_path":"dlForKettle/exp_dbm.py","file_name":"exp_dbm.py","file_ext":"py","file_size_in_byte":222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"170840529","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n'''\n@File : exp.py\n@Time : 2021/06/04 08:15:15\n@Author : eur1ka \n@Version : 2.7\n@Contact : eur1ka@163.com\n'''\n\n# here put the import lib\n\nfrom pwn import *\nfrom LibcSearcher import *\nimport pwnlib\ndebug = 1\ncontext.log_level = 'debug'\ncontext.arch = 'amd64'\nif debug:\n sh = process('bjdctf_2020_YDSneedGrirlfriend')\n libc = ELF('/lib/x86_64-linux-gnu/libc.so.6')\nelse:\n IP = 'node3.buuoj.cn'\n port = 29654\n sh = remote(IP,port)\n libc = ELF('/home/eur1ka/Desktop/Pwn/libc_file/16-64-libc-2.23.so')\nelf = ELF('bjdctf_2020_YDSneedGrirlfriend')\n\nbackdoor = 0x400B9C\n\ndef cmd(choice):\n sh.recvuntil(\"Your choice :\")\n sh.sendline(str(choice))\n\ndef add(size,content):\n cmd(1)\n sh.recvuntil(\"Her name size is :\")\n sh.sendline(str(size))\n sh.recvuntil(\"Her name is :\")\n sh.send(content)\n\ndef show(index):\n cmd(3)\n sh.recvuntil(\"Index :\")\n sh.sendline(str(index))\n\ndef dele(index):\n cmd(2)\n sh.recvuntil(\"Index :\")\n sh.sendline(str(index))\n\nadd(0x20,\"aaaa\")\nadd(0x20,\"aaaa\")\ndele(0)\ndele(1)\nadd(0x10,p64(backdoor))\ngdb.attach(sh)\npause()\nshow(0)\n\nsh.interactive()","sub_path":"2020_bjdctf/YDSneedGrirlfriend/exp.py","file_name":"exp.py","file_ext":"py","file_size_in_byte":1176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"148211479","text":"from dataclasses import dataclass\nfrom typing import Union\n\nimport numpy as np\nimport pytest\n\nfrom .hyperparameters import HyperParameters, hparam, log_uniform, uniform\n\n\n@dataclass\nclass A(HyperParameters):\n learning_rate: float = uniform(0.0, 1.0)\n\n\n@dataclass\nclass B(A):\n momentum: float = uniform(0.0, 1.0)\n\n\ndef test_to_array():\n b: B = B.sample()\n array = b.to_array()\n assert np.isclose(array[0], b.learning_rate)\n assert np.isclose(array[1], b.momentum)\n\n\ndef test_from_array():\n array = np.arange(2)\n b: B = B.from_array(array)\n assert b.learning_rate == 0.0\n assert b.momentum == 1.0\n\n\n@dataclass\nclass C(HyperParameters):\n lr: float = uniform(0.0, 1.0)\n momentum: float = uniform(0.0, 1.0)\n\n\ndef test_clip_within_bounds():\n \"\"\"Test to make sure that the `clip_within_bounds` actually restricts the\n values of the HyperParameters to be within the bounds.\n \"\"\"\n # valid range for learning_rate is (0 - 1].\n a = A(learning_rate=123)\n assert a.learning_rate == 123\n a = a.clip_within_bounds()\n assert a.learning_rate == 1.0\n\n b = B(learning_rate=0.5, momentum=456)\n assert b.clip_within_bounds() == B(learning_rate=0.5, momentum=1)\n\n # Test that the types are maintained.\n @dataclass\n class C(HyperParameters):\n a: int = uniform(123, 456, discrete=True)\n b: float = log_uniform(4.56, 123.456)\n c: str = categorical(\"foo\", \"bar\", \"baz\")\n\n with pytest.raises(TypeError):\n _ = C()\n\n with pytest.raises(TypeError):\n _ = C(a=123)\n\n with pytest.raises(TypeError):\n _ = C(b=4.56)\n\n with pytest.raises(TypeError):\n _ = C(c=\"bar\")\n\n # TODO: IDEA: how about we actually do some post-processing to always clip stuff\n # between bounds?\n # Check that it doesn't change anything if the values are within the range.\n assert C(a=1000, b=1.23, c=\"bar\").clip_within_bounds() == C(456, 4.56, \"bar\")\n assert C(a=-1.234, b=1000, c=\"foo\").clip_within_bounds() == C(123, 123.456, \"foo\")\n\n\ndef test_strict_bounds():\n \"\"\"When creating a class and using a hparam field with `strict=True`, the values\n will be restricted to be within the given bounds.\n \"\"\"\n @dataclass\n class C(HyperParameters):\n a: int = uniform(0, 1, strict=True)\n b: float = log_uniform(4.56, 123.456)\n c: str = categorical(\"foo\", \"bar\", \"baz\", default=\"foo\", strict=True)\n\n # valid range for a is [0, 1).\n with pytest.raises(ValueError,\n match=\"Field 'a' got value 123, which is outside of the defined prior\"):\n _ = C(a=123, b=10, c=\"foo\")\n\n with pytest.raises(ValueError,\n match=\"Field 'c' got value 'yolo', which is outside of the defined prior\"):\n _ = C(a=0.5, b=0.1, c=\"yolo\")\n\n # should NOT raise an error, since the field `b` isn't strict.\n _ = C(a=0.1, b=-1.26, c=\"bar\")\n\n\ndef test_nesting():\n @dataclass\n class Child(HyperParameters):\n foo: int = uniform(0, 10, default=5)\n\n from simple_parsing import mutable_field\n\n @dataclass\n class Parent(HyperParameters):\n child_a: Child = mutable_field(Child, foo=3)\n\n parent = Parent.sample()\n assert isinstance(parent, Parent)\n assert isinstance(parent.child_a, Child)\n\n\nfrom typing import Type\n\nfrom .hparam import categorical\n\n\ndef test_choice_field():\n @dataclass\n class Child(HyperParameters):\n hparam: float = categorical(\n {\n \"a\": 1.23,\n \"b\": 4.56,\n \"c\": 7.89,\n },\n default=1.23,\n )\n\n bob = Child()\n assert bob.hparam == 1.23\n\n bob = Child.sample()\n assert bob.hparam in {1.23, 4.56, 7.89}\n assert Child.get_orion_space_dict() == {\n \"hparam\": \"choices(['a', 'b', 'c'], default_value='a')\"\n }\n\n\ndef test_choice_field_with_values_of_a_weird_type():\n @dataclass\n class Bob(HyperParameters):\n hparam_type: float = categorical(\n {\n \"a\": A,\n \"b\": B,\n \"c\": C,\n },\n probabilities={\n \"a\": 0.1,\n \"b\": 0.2,\n \"c\": 0.7,\n },\n default=B,\n )\n\n bob = Bob()\n assert bob.hparam_type == B\n\n bob = Bob.sample()\n assert bob.hparam_type in {A, B, C}\n assert Bob.get_orion_space_dict() == {\n \"hparam_type\": \"choices({'a': 0.1, 'b': 0.2, 'c': 0.7}, default_value='b')\"\n }\n\n\n@pytest.mark.xfail(\n reason=\"TODO: it isn't trivial how to fix this, without having to rework the \"\n \"from_dict from simple-parsing.\"\n)\ndef test_replace_int_or_float_preserves_type():\n @dataclass\n class A(HyperParameters):\n # How much of training dataset to check (floats = percent, int = num_batches)\n limit_train_batches: Union[int, float] = 1.0\n # How much of validation dataset to check (floats = percent, int = num_batches)\n limit_val_batches: Union[int, float] = 1.0\n # How much of test dataset to check (floats = percent, int = num_batches)\n limit_test_batches: Union[int, float] = 1.0\n\n a = A()\n assert isinstance(a.limit_test_batches, float)\n b = a.replace(limit_train_batches=0.5)\n assert isinstance(b.limit_test_batches, float)\n","sub_path":"simple_parsing/helpers/hparams/hyperparameters_test.py","file_name":"hyperparameters_test.py","file_ext":"py","file_size_in_byte":5273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"275292606","text":"import osgtest.library.core as core\nimport osgtest.library.files as files\nimport osgtest.library.service as service\nimport osgtest.library.osgunittest as osgunittest\n\nclass TestStopXrootdTPC(osgunittest.OSGTestCase):\n @core.elrelease(7,8)\n def setUp(self):\n core.skip_ok_unless_installed(\"osg-xrootd-standalone\",\n by_dependency=True)\n if core.rpm_is_installed(\"xcache\"):\n self.skip_ok_if(core.PackageVersion(\"xcache\") >= \"1.0.2\", \"xcache 1.0.2+ configs conflict with xrootd tests\")\n\n def test_01_stop_xrootd(self):\n if core.state['xrootd.tpc.backups-exist']:\n files.restore(core.config['xrootd.tpc.config-1'], \"xrootd\")\n files.restore(core.config['xrootd.tpc.config-2'], \"xrootd\")\n files.restore(core.config['xrootd.tpc.basic-config'], \"xrootd\")\n files.restore('/etc/xrootd/config.d/40-osg-standalone.cfg', \"xrootd\")\n\n self.skip_ok_if(not core.state['xrootd.started-http-server-1'] and\n not core.state['xrootd.started-http-server-2'], \n 'did not start any of the http servers')\n service.check_stop(core.config['xrootd_tpc_service_1'])\n service.check_stop(core.config['xrootd_tpc_service_2'])\n\n def test_02_clean_test_files(self):\n files.remove(\"/tmp/test_gridftp_data_tpc.txt\", force=True)\n","sub_path":"osgtest/tests/test_838_xrootd_tpc.py","file_name":"test_838_xrootd_tpc.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"472194475","text":"# -*- coding: utf-8 -*-\n\n# Copyright 2014, Digital Reasoning\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\n\"\"\"\nRackspace provider for stackd.io\n\"\"\"\n\nimport logging\n\nfrom cloud.providers.base import BaseCloudProvider\n\nlogger = logging.getLogger(__name__)\n\n\n##\n# Required parameters that must be defined\n##\n\nclass RackspaceCloudProvider(BaseCloudProvider):\n # Notice we're using openstack as the shortname here, as this is\n # the appropriate provider type for dealing with Rackspace\n SHORT_NAME = 'openstack'\n LONG_NAME = 'Rackspace' \n\n # Identity URL\n IDENTITY_URL = 'identity_url'\n\n # Compute name\n COMPUTE_NAME = 'compute_name'\n\n # Compute region\n COMPUTE_REGION = 'compute_region'\n\n # Protocol\n PROTOCOL = 'protocol'\n\n # Authentication\n USERNAME = 'username'\n TENANT_ID = 'tenant_id'\n API_KEY = 'api_key'\n\n @classmethod\n def get_provider_data(self, data):\n yaml_data = {\n 'provider': self.SHORT_NAME,\n 'identity_url': data[self.IDENTITY_URL],\n 'compute_name': data[self.COMPUTE_NAME], \n 'compute_region': data[self.COMPUTE_REGION],\n 'protocol': data[self.PROTOCOL],\n 'user': data[self.USERNAME],\n 'tenant': data[self.TENANT_ID],\n 'apikey': data[self.API_KEY],\n }\n\n return yaml_data\n\n @classmethod\n def get_required_fields(self):\n return [\n self.IDENTITY_URL, \n self.COMPUTE_NAME, \n self.COMPUTE_REGION,\n self.PROTOCOL,\n self.USERNAME,\n self.TENANT_ID,\n self.API_KEY,\n ]\n","sub_path":"stackdio/server/cloud/providers/rackspace.py","file_name":"rackspace.py","file_ext":"py","file_size_in_byte":2138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"133242317","text":"import pathlib\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nimport pylab\nimport colorama\nfrom colorama import Fore, Back, Style\nimport numpy as np\n\nfrom App.scene_container import SceneContainer\nfrom opticalObjects.volcan_axicon import VolcanoAxicon\n\nfrom ray.vec_rays_pool import VecRayPool\nfrom opticalObjects.axicon3D import Axicon3D\n\nfrom tools import help as help_\nimport tools.string_manip as sm\nimport tools.file_management as fm\n\nfrom view.matlab import matlab_surface_view3D as surf_view\nfrom view.matlab import matlab_ray_view3D as ray_view\n\nfrom scripts.service import load\n\n# ========================================== LOAD AND OPTIONS ==========================================================\nnum_file_in_dir = 0 # number of file in directory. from 0.\nnum_folder_in_dir = 0\n# if it is not set to None, then the path to the loaded file will be set from the same directory as the specified file,\n# but under a number, if the path points to the file and to the file under the given numbers in the directory,\n# if it is a directory.\nload_path: pathlib.Path = fm.scene_saves_path / \"2022\" / \"02\" / \"25\"\n\n\n# ================================= DEPRECATED VERSION OF CONTAINER ====================================================\n# \"09\" / \"23\" / \"21_53_21_efficiency_divergen_angle\" # changes refraction coefficient of axicon 4 rays not on diagonal\n# \"10\" / \"01\" / \"11_54_45_efficiency_divergen_angle\" # changes refraction coefficient of axicon 4 rays on diagonal\n# \"10\" / \"07\" / \"21_31_31_efficiency_divergen_angle\" # test of axicon normals\n# \"10\" / \"11\" / \"17_44_40_Volcano_axicon\" # 1 ray replaced half-angles of cones # right version 1\n# \"10\" / \"11\" / \"18_15_20_Volcano_axicon\" # 16 ray replaced half-angles of cones # right version\n# \"10\" / \"11\" / \"18_59_47_Volcano_axicon\" # 1 ray replaced half-angles of cones # right version 2 preferred\n# \"10\" / \"11\" / \"19_04_02_Volcano_axicon\" # 1 ray replaced half-angles of cones # right version 2.5\n\n# ===================================== NEW VERSION OF CONTAINER =======================================================\n\n# \"12\" / \"15\"/ \"Volcano_axicon\"\n# \"2021\" / \"12\" / \"15\" / \"Volcano_axicon\"\n# \"2022\" / \"01\" / \"25\" / \"16_32_12_Volcano_axicon_angle_deflection\"\n# \"26\" / \"16_09_00_Volcano_axicon_angle_deflection\"\n# \"2022\" / \"01\" / \"26\" / \"16_09_00_Volcano_axicon_angle_deflection\"\n# \"2022\" / \"02\" / \"03\" / \"20_48_24_Volcano_axic_angle_deflect_36_rays\"\n# \"2022\" / \"02\" / \"03\" / \"20_51_54_Volcano_axic_angle_deflect_circles_\"\n# \"04\" / \"15_56_15_Volcano_axic_angle_deflect_circles_\" \"16_07_27_Volcano_axic_angle_deflect_circles_\"\n\n# =================================== EVERY TRACE CAN OPEN IN DAY ======================================================\n# \"2022\" / \"02\" / \"04\"\n# \"2022\" / \"02\" / \"13\"\n\n# ============================================ PLOT OPTIONS ============================================================\ndef set_plot_options(scene: SceneContainer, axes):\n axicon: Axicon3D = scene.surfaces[0]\n # hssl = abs(axicon.height) * np.tan(axicon.cone_angle) + 1 # half square side length # 3 # 10\n hssl = 10 # 60 30 20 15 10\n zlim = [-1, 14] # [-65, 25] [-33, 25] [13, 25] [-33, 25] [-1, 14]\n # zlim = [-1, 14] # 8, 10 # -2, 11.5 [-1, 10]\n # hssl = 5\n # zlim = [15, 22]\n xlim = np.asarray((-hssl, hssl))\n y_lim = np.asarray((-hssl, hssl))\n ax_viev_init = [20, 38] # [90, 0] [20, 45] [30, 45] [30, 0] [0, 10] [0, 0]\n # [0, 0] # from front (axes y)\n # [90, 0] # from top\n # [0, 90] # from side (axes x from +oo to -oo)\n # [0, -90] # from side (axes x from -oo to +oo)\n\n axes.set_ylim3d(xlim)\n axes.set_xlim3d(y_lim)\n axes.set_zlim3d(*zlim)\n axes.set_xlabel(\"x\")\n axes.set_ylabel(\"y\")\n axes.set_zlabel(\"z\")\n\n axes.view_init(*ax_viev_init)\n\n\nxlim = None\ny_lim = None\nz_lim = None\nrays_color = [\"red\", \"orange\", \"purple\", \"yellow\", \"green\"]\n\nis_save_svg = 0\nis_save_png = 0\nis_beam_filter = 0\n# state_plot\nnp.set_printoptions(precision=18)\n# As It knows each RaysPool have group inside self.\n# first groups usually is REFRACTING rays group. Next groups is REFLECTING\n# beam group filter - List[List[int]]\n# list of rays pool. next list of groups and within its value 0 or 1 (does not plot OR plot).\nbeam_group_filter = [[], # 0-th pool\n [0, 1], # first pool\n [0, 1, 0, 0], # second pool\n [0, 0, 1, 0], # ...\n [1, 0, 0, 0],\n ] # needed beam path\nbeam_group_filter = [[], # 0-th pool\n [1, 0], # first pool\n [1, 0, 0, 0], # second pool\n [0, 0, 0, 0], # 3\n [0, 0, 0, 0], # 4\n ] # useless base beam of axicon\nbeam_group_filter = [[], # 0-th pool\n [1, 0], # first pool\n [0, 0, 1, 0], # second pool\n [0, 0, 0, 1], # 3\n [0, 0, 0, 1], # 4\n ] # other configure\nbeam_group_filter = [[], # 0-th pool\n [0, 1], # first pool\n [], # second pool\n [], # ...\n [1, 0, 0, 0],\n ] # almost chaos less green rays\nbeam_group_filter = [[], # 0-th pool\n [0, 1], # first pool\n [0, 1, 0, 0], # second pool\n [0, 1, 0], # [0] * 4, # [0, 0, 0, 1], # ...\n [1, 0, 0, 0],\n ] # needed beam path\n\nbeam_group_filter = [[], # 0-th pool\n [0, 1], # first pool\n [0, 1, 0, 0], # second pool\n [0, 0, 1, 0, 0], # [0] * 4, # [0, 0, 0, 1], # ...\n [0, 1, 0, 0, 0, 0],\n ] # needed beam path\nis_show_ = True\nax_viev_init = []\n\n\ndef plot_axicon_scene(scene: SceneContainer, axes, is_show=is_show_):\n depth = len(scene.pools) - 1\n surface: Axicon3D = scene.surfaces[0]\n\n ray_path = [\"REFLECT\", \"REFRACT\", \"REFRACT\", \"REFRACT\"]\n ray_path = [\"REFLECT\", \"REFRACT\"]\n ray_path = [\"REFLECT\", \"REFRACT\", \"REFLECT\", \"REFRACT\"]\n if 0:\n required_beams = scene.get_rays_group_by_path(ray_path)\n print(required_beams)\n ray_view.plot_ray_pool(axes, required_beams, color=rays_color[-1])\n plt.figure(2)\n elif 1:\n # (\"red\", \"orange\", \"purple\", \"yellow\", \"green\")\n ray_view.plot_ray_path(axes, scene.pools, ray_path, is_plot_last_child_groups=True)\n else:\n for i in range(depth + 1): # cycle on rays pools\n if is_beam_filter and (i < len(beam_group_filter)) and (\n len(beam_group_filter[i]) == len(scene.pools[i].groups.rays_group_indexes)):\n for jj in range(len(scene.pools[i].groups.rays_group_indexes)): # cycle on rays groups\n if beam_group_filter[i][jj]:\n rays_group = scene.pools[i].groups.get_group_list_repr_by_ind(jj) # take group\n ray_group_pool = VecRayPool(rays_group,\n scene.pools[depth].compon_index_class) # create pool from group\n\n ray_view.plot_ray_pool(axes, ray_group_pool, color=rays_color[i])\n del rays_group\n del ray_group_pool\n else:\n ray_view.plot_ray_pool(axes, scene.pools[i], color=rays_color[i])\n\n alpha = 0.2\n if isinstance(surface, Axicon3D):\n surf_view.plot_axicon(axes, axicon=surface, alpha=alpha, is_plot_base=False)\n elif isinstance(surface, VolcanoAxicon):\n surf_view.plot_volcan_axicon(axes, surface, alpha=alpha)\n\n set_plot_options(scene, axes)\n\n refr_coeff_ind = 0 # 0 if is not scene axicon in medium 1 else\n needed_refr_coef = surface._Surface__n2\n axes.text2D(0.05, 0.95, f\"n = {needed_refr_coef}\", transform=axes.transAxes)\n # axes.text2D(0.05, 0.75, f\"len last pool {len(scene.rays[depth])}\", transform=axes.transAxes)\n note_in_code = '1_ray_not_preferred'\n if is_save_svg:\n directory = load_path / \"vector_graphic\"\n directory.mkdir(exist_ok=True)\n time_str = sm.get_remainder_str(sm.get_date_time_str(), 3, is_end_separator=False)\n plt.savefig(directory / (f\"{note_in_code}_{time_str}\" + \".svg\"), format=\"svg\")\n if is_save_png:\n directory = load_path / \"frames\"\n directory.mkdir(exist_ok=True)\n time_str = sm.get_remainder_str(sm.get_date_time_str(), 3, is_end_separator=False)\n plt.savefig(directory / (f\"{note_in_code}_{time_str}\" + \".png\"), format=\"png\")\n if is_show:\n pylab.show()\n\n\ndef main():\n global load_path\n fig = pylab.figure(0)\n axes = Axes3D(fig, auto_add_to_figure=False)\n fig.add_axes(axes)\n if (num_folder_in_dir is not None) or num_folder_in_dir > -1:\n list_dir = list(load_path.iterdir())\n if list_dir[num_folder_in_dir].is_dir():\n load_path = list_dir[num_folder_in_dir]\n print(load_path)\n scene = load(load_path, nfid=num_file_in_dir)\n print(scene.get_readable_str_data())\n plot_axicon_scene(scene, axes=axes)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"scripts/service/load_and_plot.py","file_name":"load_and_plot.py","file_ext":"py","file_size_in_byte":9257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"627982827","text":"from generator.actions import Actions\nimport random\nimport string\nimport struct\nimport ctypes\nimport sys\nimport pprint\n\npp = pprint.PrettyPrinter(indent=4)\n\ndef random_name(is_required=True):\n if not is_required:\n if random.randint(1,10) == 1:\n return ''\n\n characters = string.letters + \"'\"\n max_size = random.randint(1,31)\n return ''.join(random.choice(characters) for c in range(max_size))\n\n\ndef random_suffix():\n if random.randint(1,10) == 1:\n return ''\n\n valid_suffixes = [\"Jr\", \"Sr\", \"II\", \"III\", \"IV\", \"V\", \"VI\", \"VII\", \"VIII\", \"IX\", \"X\", \"Other\"]\n choice = random.randint(1, len(valid_suffixes)) - 1\n return valid_suffixes[choice]\n\n\ndef random_month():\n month = random.randint(1,12)\n if month < 10:\n return '0' + str(month)\n else:\n return str(month)\n\n\ndef random_day():\n day = random.randint(1,28)\n if day < 10:\n return '0' + str(day)\n else:\n return str(day)\n\n\ndef random_year():\n return str(random.randint(1900, 2014))\n\n\ndef random_height_feet():\n return str(random.randint(1, 9))\n\n\ndef random_height_inches():\n return str(random.randint(0, 11))\n\n\ndef random_weight():\n return str(random.randint(50, 500))\n\n\ndef random_sex():\n if random.randint(1,2) == 1:\n return 'M'\n else:\n return 'F'\n\n\ndef random_hair():\n valid_hair_color = [ \"Bald\", \"Black\", \"Blonde or Strawbery\", \"Brown\", \"Gray or Partially Gray\",\n \"Red or Auburn\", \"Sandy\", \"White\", \"Blue\", \"Green\", \"Orange\", \"Pink\", \"Purple\",\n \"Unspecified or Unknown\" ]\n\n choice = random.randint(1, len(valid_hair_color)) - 1\n return valid_hair_color[choice]\n\n\ndef random_eye():\n valid_eye_color = [ \"Black\", \"Blue\", \"Brown\", \"Gray\", \"Green\", \"Hazel\", \"Maroon\", \"Multicolored\",\n \"Pink\", \"Unknown\" ]\n\n choice = random.randint(1, len(valid_eye_color)) - 1\n return valid_eye_color[choice]\n\n\ndef random_yes_no():\n if random.randint(1,2) == 1:\n return 'Y'\n else:\n return 'N'\n\n\ndef random_text():\n max_size = random.randint(1, 63)\n characters = string.letters + string.digits + ' .?!'\n return ''.join(random.choice(characters) for c in range(max_size))\n\ndef random_email():\n characters = string.letters + string.digits\n\n max_size = random.randint(1, 31)\n front = ''.join(random.choice(characters) for c in range(max_size))\n max_size = random.randint(1, 31)\n back = ''.join(random.choice(characters) for c in range(max_size))\n\n return front + '@' + back\n\n\ndef random_phone(is_required=True):\n if not is_required:\n if random.randint(1,10) == 1:\n return ''\n\n characters = string.digits\n max_size = 4\n return '555-555-' + (''.join(random.choice(characters) for c in range(max_size)))\n\n\ndef random_street():\n characters = string.digits\n max_size = random.randint(1, 4)\n street_num = ''.join(random.choice(characters) for c in range(max_size))\n\n characters = string.letters\n street_name = ''.join(random.choice(characters))\n characters = string.letters + ' '\n max_size = random.randint(3, 15)\n street_name += ''.join(random.choice(characters) for c in range(max_size))\n\n while (street_name[-1] == ' '):\n street_name = street_name[:-2]\n\n return street_num + ' ' + street_name + ' St'\n\n\ndef random_city():\n characters = string.letters\n max_size = random.randint(4,31)\n return ''.join(random.choice(characters) for c in range(max_size))\n\n\ndef random_state():\n valid_state = [ \"AL\", \"AK\", \"AZ\", \"AR\", \"CA\", \"CO\", \"CT\", \"DE\", \"DC\", \"FL\", \"GA\", \"HI\", \"ID\", \"IL\",\n \"IN\", \"IA\", \"KS\", \"KY\", \"LA\", \"ME\", \"MD\", \"MA\", \"MI\", \"MN\", \"MS\", \"MO\", \"MT\", \"NE\",\n \"NV\", \"NH\", \"NJ\", \"NM\", \"NY\", \"NC\", \"ND\", \"OH\", \"OK\", \"OR\", \"PA\", \"RI\", \"SC\", \"SD\",\n \"TN\", \"TX\", \"UT\", \"VT\", \"VA\", \"WA\", \"WV\", \"WI\", \"WY\" ]\n\n choice = random.randint(1, len(valid_state)) - 1\n return valid_state[choice]\n\ndef random_zip_code():\n return str(random.randint(10000, 99999))\n\ndef random_gpa():\n gpa_dec = random.randint(0,99)\n gpa_dec_str = str(gpa_dec) if gpa_dec >= 10 else '0' + str(gpa_dec)\n return str(random.randint(0, 4)) + '.' + gpa_dec_str\n\ndef random_education():\n valid_education = [ \"HS\", \"COLLEGE\", \"ADV\" ]\n\n choice = random.randint(1, len(valid_education)) - 1\n return valid_education[choice]\n\nclass ApplicationPage():\n def __init__(self):\n self.fields = []\n\n def check_fields_completed(self):\n for text_field, opt_text_field, is_required, current_val, gen_func in self.fields:\n if current_val is None:\n return False\n\n return True\n\n\n def get_incomplete_field(self):\n for x in xrange(len(self.fields)):\n (text_field, opt_text_field, is_required, current_val, gen_func) = self.fields[x]\n if current_val is None:\n return self.fields[x]\n\n return None\n\n def enter_field(self):\n for x in xrange(len(self.fields)):\n (text_field, opt_text_field, is_required, current_val, gen_func) = self.fields[x]\n if current_val is None:\n self.fields[x].current_val = gen_func()\n return True\n\n return False\n\n def update_field(self, field_name):\n for x in xrange(len(self.fields)):\n text_field, opt_text_field, is_required, current_val, gen_func = self.fields[x]\n if text_field == field_name:\n current_val = gen_func()\n self.fields[x] = (text_field, opt_text_field, is_required, current_val, gen_func)\n return current_val\n\n return None\n\nclass ApplicantId(ApplicationPage):\n def __init__(self):\n self.fields = [\n (\"Last Name\", \"\", True, None, random_name),\n (\"First Name\", \"\", True, None, random_name),\n (\"Middle Name\", \" [MI or Middle Name]\", False, None, random_name),\n (\"Suffix\", \" [Jr, Sr, II, etc]\", False, None, random_suffix),\n (\"DOB Month\", \" [MM]\", True, None, random_month),\n (\"DOB Day\", \" [DD]\", True, None, random_day),\n (\"DOB Year\", \" [YYYY]\", True, None, random_year),\n (\"Height-Feet\", \" [1-9]\", True, None, random_height_feet),\n (\"Height-Inches\", \" [0-11]\", True, None, random_height_inches),\n (\"Weight\", \"\", True, None, random_weight),\n (\"Sex\", \"\", True, None, random_sex),\n (\"Hair Color\", \"\", True, None, random_hair),\n (\"Eye Color\", \"\", True, None, random_eye)\n ]\n\nclass ContactInfo(ApplicationPage):\n def __init__(self):\n self.fields = [\n (\"Personal e-mail\", \"\", True, None, random_email),\n (\"Work e-mail\", \"\", False, None, random_email),\n (\"Home telephone number\", \" [XXX-XXX-XXXX]\", True, None, random_phone),\n (\"Work telephone number\", \" [XXX-XXX-XXXX]\", False, None, random_phone)\n ]\n\n\nclass CurrentAddress(ApplicationPage):\n def __init__(self):\n self.fields = [\n (\"Move-In Month\", \" [MM]\", True, None, random_month),\n (\"Move-In Year\", \" [YYYY]\", True, None, random_year),\n (\"Street\", \"\", True, None, random_street),\n (\"City\", \"\", True, None, random_city),\n (\"State\", \"\", True, None, random_state),\n (\"Zip Code\", \"\", True, None, random_zip_code),\n (\"Owned by you\", \"? [Y/N]\", True, None, random_yes_no)\n ]\n\n\nclass Education(ApplicationPage):\n def __init__(self):\n self.fields = [\n (\"Highest Education\", \" [HS/COLLEGE/ADV]\", True, None, random_education),\n (\"Start Month\", \" [MM]\", True, None, random_month),\n (\"Start Year\", \" [YYYY]\", True, None, random_year),\n (\"End Month\", \" [MM]\", True, None, random_month),\n (\"End Year\", \" [YYYY]\", True, None, random_year),\n (\"School Name\", \"\", True, None, random_text),\n (\"Street\", \"\", True, None, random_street),\n (\"City\", \"\", True, None, random_city),\n (\"State\", \"\", True, None, random_state),\n (\"Zip Code\", \"\", True, None, random_zip_code),\n (\"GPA\", \" [X.XX]\", True, None, random_gpa),\n (\"Major\", \" [NA for HS]\", True, None, random_text)\n ]\n\n\nclass Employer(ApplicationPage):\n def __init__(self):\n self.fields = [\n (\"Most Recent Employer\", \"\", True, None, random_text),\n (\"Start Month\", \" [MM]\", True, None, random_month),\n (\"Start Year\", \" [YYYY]\", True, None, random_year),\n (\"End Month\", \" [MM]\", False, None, random_month),\n (\"End Year\", \" [YYYY]\", False, None, random_year),\n (\"Street\", \"\", True, None, random_street),\n (\"City\", \"\", True, None, random_city),\n (\"State\", \"\", True, None, random_state),\n (\"Zip Code\", \"\", True, None, random_zip_code),\n (\"Supervisor Last Name\", \"\", True, None, random_name),\n (\"Supervisor First Name\", \"\", True, None, random_name),\n (\"Supervisor Title\", \"\", True, None, random_text),\n (\"Supervisor Telephone Number\", \" [XXX-XXX-XXXX]\", True, None, random_phone),\n (\"Supervisor e-mail\", \"\", False, None, random_email),\n ]\n\n\nclass Screening(ApplicationPage):\n def __init__(self):\n self.fields = [\n (\"Drug Test\", \"? [Y/N]\", True, None, random_yes_no),\n (\"Background Investigation\", \"? [Y/N]\", True, None, random_yes_no)\n ]\n\nclass Finished(ApplicationPage):\n def __init__(self):\n self.fields = []\n\n\n\nclass JobApplication(Actions):\n finished_page_text = (\"\\n\\nYou have completed your application with the Sea Eye Association.\\n\" +\n \"You may review the form. Navigate through the application with **prev and **next.\\n\" +\n \"Once your are satisfied type **exit to exit and submit the form\\n\" +\n \"If you wish to discard your application, please use Control-C\\n\")\n\n page_text = [ \"\\nCandidate Info Form\\n\", \"\\nContact Info Form\\n\", \"\\nAddress Form\\n\", \"\\nEducation Form\\n\",\n \"\\nEmployment Form\\n\", \"\\nFinal Questions\\n\", finished_page_text, \"\" ]\n\n finish_text = [ \"\\n*********Candidate Info:*********\\n\", \"\\n*********Contact Info:*********\\n\",\n \"\\n*********Address:*********\\n\", \"\\n*********Highest Education:*********\\n\",\n \"\\n*********Most Recent Employer:*********\\n\", \"\\n*********Final Screening:*********\\n\",\n \"\" ]\n\n help_text = (\"All commands begin with '**' and may be entered at any time\\n\" +\n \"**prev \\n\" +\n \"**next \\n\" +\n \"**update [id] \\n\" +\n \"**help \\n\" +\n \"**exit \\n\")\n\n welcome_text = (\"\\n\\n\" +\n \"Thanks for your interest in the Sea Eye Association.\\n\" +\n \"In order to be considered for the job complete the preliminary online background check\\n\" +\n \"Due to the secure nature of the position you are applying for you may be asked to\\n\" +\n \"submit additional paperwork after your preliminary background check has been approved.\\n\" +\n \"Thank you for your cooperation\\n\" )\n\n exit_text = (\"Thank you!\\n\")\n\n def _read_page_banner(self, page_idx=None):\n page_idx = self.state['page_idx'] if page_idx is None else page_idx\n self.read(length=len(self.page_text[page_idx]), expect=self.page_text[page_idx])\n\n def _read_completed_form(self):\n page = self.app_pages[self.state['page_idx']]\n if len(self.finish_text[self.state['page_idx']]):\n self.read(length=len(self.finish_text[self.state['page_idx']]),\n expect=self.finish_text[self.state['page_idx']])\n for text_field, opt_text_field, is_required, current_val, gen_func in page.fields:\n line = text_field + '=' + current_val + '\\n'\n self.read(length=len(line), expect=line)\n\n if self.state['page_idx'] < 6:\n line = \"\\nType **next to continue\\n\"\n self.read(length=len(line), expect=line)\n\n def _read_current_form(self):\n page = self.app_pages[self.state['page_idx']]\n field = page.get_incomplete_field()\n\n if field is not None:\n (text_field, opt_text_field, is_required, current_val, gen_func) = field\n self.read(length=len(text_field + opt_text_field + ': '), expect=text_field + opt_text_field + ': ')\n else:\n self._read_completed_form()\n\n return field\n\n def start(self):\n self.last_page_completed = -1\n self.app_pages = [ ApplicantId(), ContactInfo(), CurrentAddress(), Education(),\n Employer(), Screening(), Finished() ]\n\n self.state['page_idx'] = 0\n\n self.read(length=len(self.welcome_text), expect=self.welcome_text)\n self._read_page_banner()\n\n def enter_field(self):\n field = self._read_current_form()\n if field is not None:\n page = self.app_pages[self.state['page_idx']]\n (text_field, opt_text_field, is_required, current_val, gen_func) = field\n current_val = page.update_field(text_field) + '\\n'\n self.write(current_val)\n else:\n self.write('\\n')\n self._read_page_banner()\n\n def update_field(self):\n if self.state['page_idx'] == 6:\n return\n\n field = self._read_current_form()\n page = self.app_pages[self.state['page_idx']]\n field_idx = random.randint(0, len(page.fields) - 1)\n text_field, opt_text_field, is_required, current_val, gen_func = page.fields[field_idx]\n self.write(\"**update \" + text_field + \"\\n\")\n\n if field is None:\n (text_field, opt_text_field, is_required, current_val, gen_func) = page.fields[field_idx]\n self.read(length=len(text_field + opt_text_field + ': '), expect=text_field + opt_text_field + ': ')\n current_val = page.update_field(text_field) + '\\n'\n self.write(current_val)\n else:\n line = \"Cannot update field until all fields are inputted\\n\"\n self.read(length=len(line), expect=line)\n\n self._read_page_banner()\n\n def next_page(self):\n field = self._read_current_form()\n self.write(\"**next\\n\")\n\n if (self.state['page_idx'] < 6):\n if field is None:\n self.state['page_idx'] += 1\n else:\n self._read_page_banner(page_idx=self.state['page_idx']+1)\n line = \"You must complete the previous page before proceeding to this page\\n\"\n self.read(length=len(line), expect=line)\n\n self._read_page_banner()\n\n def prev_page(self):\n field = self._read_current_form()\n self.write(\"**prev\\n\")\n\n if self.state['page_idx'] > 0:\n self.state['page_idx'] -= 1\n\n self._read_page_banner()\n\n def help(self):\n field = self._read_current_form()\n self.write(\"**help\\n\")\n self.read(length=len(self.help_text), expect=self.help_text)\n self._read_page_banner()\n\n def exit(self):\n field = self._read_current_form()\n self.write(\"**exit\\n\")\n self.read(length=len(self.exit_text), expect=self.exit_text)\n\n\n","sub_path":"challenges/online_job_application2/poller/for-release/machine.py","file_name":"machine.py","file_ext":"py","file_size_in_byte":15584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"416557373","text":"# -*- coding=utf-8 -*-\n\n__author__ = 'STM'\n\nimport re\nimport os\nimport numpy as np\nimport random\n\n\ndef textParse(bigString):\n listOfTokens = re.split(\"\\\\W+\", bigString)\n return [tok.lower() for tok in listOfTokens if len(tok) > 2]\n\n\ndef createVocabList(dataSet):\n vocabSet = set([])\n for document in dataSet:\n vocabSet = vocabSet | set(document)\n return list(vocabSet)\n\n\ndef getFileNameList(path):\n for _, _, files in os.walk(path):\n files.sort(key=lambda f: int(re.split(\"\\\\.\", f)[0]))\n return files\n\n\ndef setOfWords2Vec(vocabList, inputSet):\n returnVec = [0] * len(vocabList)\n for word in inputSet:\n if word in vocabList:\n returnVec[vocabList.index(word)] = 1\n else:\n print(\"the word: %s is not in my Vocabulary.\" % word)\n return returnVec\n\n\ndef trainNBO(trainMatrix, trainCategory):\n \"\"\"\n 分类器训练函数\n :param trainMatrix: 训练文档矩阵\n :param trainCategory:\n :return:\n p0Vect: 非侮辱类的条件概率数组\n p1Vect: 侮辱类的条件概率数组\n pAbusive: 文档属于侮辱类的概率\n \"\"\"\n numTrainDocs = len(trainMatrix)\n numWords = len(trainMatrix[0])\n pAbusive = sum(trainCategory) / float(numTrainDocs)\n # 这种计算方式,如果其中一个概率为0,那么乘积也为0\n # 为此,将所有词的出现数初始化为1,并将分母初始化为2\n # 太多很小的数相乘为0 对此进行log\n # p0Num = np.zeros(numWords)\n # p1Num = np.zeros(numWords)\n # p0Denom = 0.0\n # p1Denom = 0.0\n p0Num = np.ones(numWords)\n p1Num = np.ones(numWords)\n p0Denom = 2.0\n p1Denom = 2.0\n for i in range(numTrainDocs):\n if trainCategory[i] == 1:\n p1Num += trainMatrix[i]\n p1Denom += sum(trainMatrix[i])\n else:\n p0Num += trainMatrix[i]\n p0Denom += sum(trainMatrix[i])\n p1Vect = np.log(p1Num / p1Denom)\n p0Vect = np.log(p0Num / p0Denom)\n return p0Vect, p1Vect, pAbusive\n\n\ndef classifyNB(vec2Classify, p0Vec, p1Vec, pClass1):\n \"\"\"\n 朴素贝叶斯分类器分类函数\n 计算的是 $P(w|c_i)\\times P(c_i)$\n :param vec2Classify: 待分类的词条数组\n :param p0Vec: 非侮辱类的条件概率数组\n :param p1Vec: 侮辱类的条件概率数组\n :param pClass1: 文档属于侮辱类的概率\n :return:\n 0: 非侮辱类\n 1: 侮辱类\n \"\"\"\n # 太多很小的数相乘为0 对此进行log\n # p1 = reduce(lambda x, y: x * y, vec2Classify * p1Vec) * pClass1\n # p0 = reduce(lambda x, y: x * y, vec2Classify * p0Vec) * (1.0 - pClass1)\n p1 = sum(vec2Classify * p1Vec) + np.log(pClass1)\n p0 = sum(vec2Classify * p0Vec) + np.log(1.0 - pClass1)\n print((\"p0:{0}, p1:{1}\").format(p0, p1))\n if p1 > p0:\n return 1\n else:\n return 0\n\n\ndef spamTest():\n docList = []\n classList = []\n fullText = []\n for file in getFileNameList(\"email/spam\"):\n wordList = textParse(open(\"email/spam/{0}\".format(file), encoding='cp1252').read())\n docList.append(wordList)\n fullText.append(wordList)\n classList.append(1)\n for file in getFileNameList(\"email/ham\"):\n wordList = textParse(open(\"email/ham/{0}\".format(file), encoding='cp1252').read())\n docList.append(wordList)\n fullText.append(wordList)\n classList.append(0)\n vocabList = createVocabList(docList)\n trainSet = list(range(50))\n testSet = []\n for i in range(10):\n randIndex = int(random.uniform(0, len(trainSet)))\n testSet.append(trainSet[randIndex])\n del (trainSet[randIndex])\n trainMat = []\n trainClass = []\n for docIndex in trainSet:\n trainMat.append(setOfWords2Vec(vocabList, docList[docIndex]))\n trainClass.append(classList[docIndex])\n p0V, p1V, pAb = trainNBO(trainMat, trainClass)\n\n errorCount = 0\n for docIndex in testSet:\n wordVec = setOfWords2Vec(vocabList, docList[docIndex])\n classVal = classifyNB(np.array(wordVec), p0V, p1V, pAb)\n print(\"classVal:{0}\".format(classVal))\n print(\"classOrigin:{0}\".format(classList[docIndex]))\n if classVal != classList[docIndex]:\n errorCount += 1\n print(\"分类错误的测试集:\", docList[docIndex])\n print(\"错误率: {0}%\".format(float(errorCount) / len(testSet) * 100))\n\n\nif __name__ == '__main__':\n spamTest()\n","sub_path":"naive_bayes/bayes2.py","file_name":"bayes2.py","file_ext":"py","file_size_in_byte":4425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"69951458","text":"from zdep_testpyci import I2b2Table\n\n# Each nodes in the ontology herirarchy correspinds to one metadata element\n# Hence to add an heirarhical element an element needs to be added for each parent\n# the hlevel and rows for parents seems necessary for ontology display in i2b2-webclient\n\nclass Metadata(I2b2Table):\n\n\n def __init__(self,c_fullname='\\\\Annotations\\\\cohort1\\\\',c_name='Cohort_m1'):\n print(\"created\")\n self.c_hlevel=len(c_fullname.split('\\\\'))-3#\n self.c_fullname=c_fullname\n self.c_name=c_name\n self.c_synonym_cd='N'\n self.c_visualattributes='LA '\n self.c_totalnum='10'\n self.c_basecode=''\n self.c_metadataxml=''\n self.c_facttablecolumn='observation_fact1.concept_cd'\n self.c_tablename='concept_dimension1'\n self.c_columnname='concept_path'\n self.c_columndatatype='T'\n self.c_operator='LIKE'\n self.c_dimcode=self.c_fullname\n self.c_comment=''\n self.c_tooltip=''\n self.m_applied_path=''\n self.update_date='9/28/2010 11:15:00 AM'#4/10/2007 12:00:00 AM'\n self.download_date='9/28/2010 11:15:00 AM'\n self.import_date='9/28/2010 11:15:00 AM'\n self.sourcesystem_cd=''\n self.valuetype_cd=''\n self.m_exclusion_cd=''\n self.c_path=''\n self.c_symbol=''\n\n\n def to_sql(self):\n sql = \"INSERT INTO i2b2metadata.meta1(c_hlevel,\tc_fullname,\tc_name,\tc_synonym_cd,\tc_visualattributes,\tc_totalnum,\tc_basecode,\tc_metadataxml,\tc_facttablecolumn,\tc_tablename,\tc_columnname,\tc_columndatatype,\tc_operator,\tc_dimcode,\tc_comment,\tc_tooltip,\tm_applied_path,\tupdate_date,\tdownload_date,\timport_date,\tsourcesystem_cd,\tvaluetype_cd,\tm_exclusion_cd,\tc_path,\tc_symbol ) \\\n VALUES('{}', '{}','{}','{}', '{}',\\\n '{}', '{}','{}','{}', '{}',\\\n '{}', '{}','{}','{}', '{}',\\\n '{}', '{}','{}','{}', '{}',\\\n '{}', '{}','{}','{}', '{}');\".format(self.c_hlevel, self.c_fullname, self.c_name, self.c_synonym_cd, self.c_visualattributes, self.c_totalnum, self.c_basecode, self.c_metadataxml, self.c_facttablecolumn, self.c_tablename, self.c_columnname, self.c_columndatatype, self.c_operator, self.c_dimcode, self.c_comment, self.c_tooltip, self.m_applied_path, self.update_date, self.download_date, self.import_date, self.sourcesystem_cd, self.valuetype_cd, self.m_exclusion_cd, self.c_path, self.c_symbol)\n return sql\n\n\nclass TextMetaData(Metadata):\n\n def __init__(self):\n Metadata.___init__(self)\n\n metadataxml_template='''\n \n \n 3.2\n 2011-12-19T13:32:16.198-04:00\n LCS-I2B2:CT_RPT_DID\n De-Identified CT Reports\n largestring\n \n \n \n \n '''\n self.c_metadataxml= metadataxml_template.replace('LCS-I2B2:CT_RPT_DID','None')\n\n\n","sub_path":"src/zdep_testpyci/metadata.py","file_name":"metadata.py","file_ext":"py","file_size_in_byte":3219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"328091048","text":"import random\nimport constant\nimport time\n\nnum_heads = 0\nnum_tails = 0\nfor i in range(10):\n # ts stores the time in seconds\n ts = time.time()\n\n # use timestamp as random number seed\n random.seed(ts)\n # generate pseudo random number\n random_val = random.random();\n\n # If the generated random number is larger than 0.5, it's a head\n # else it's a tail\n if (random_val> 0.50):\n print(constant.HEAD)\n num_heads += 1;\n else:\n print(constant.TAIL)\n num_tails += 1;\n\n# print ( \"number of heads=\" + num_heads)\n# print ( \"number of tails=\" + num_tails)\nprint ( \"number of heads=\" + str(num_heads))\nprint ( \"number of tails=\" + str(num_tails)) ","sub_path":"steps/flip_step9.py","file_name":"flip_step9.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"480288088","text":"# -*- coding: utf-8 -*-\nimport cv2\nimport numpy as np\n\ndef main():\n # 2枚の画像をグレースケールで取得\n im1 = cv2.imread(\"test1.png\",0)\n im2 = cv2.imread(\"test2.png\",0)\n # 画像データをfloat32型に型変換\n im1 = np.float32(im1)\n im2 = np.float32(im2)\n # 位相相関を計算して2枚の画像のズレを求める\n dx, dy = cv2.phaseCorrelate(im1,im2)\n print(u\"x方向のズレ:\"+str(dx))\n print(u\"y方向のズレ:\"+str(dy))\n\nif __name__ == '__main__':\n main()\n","sub_path":"python/opencv/opencv-old/image/phase_correlate.py","file_name":"phase_correlate.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"312126276","text":"#!/usr/bin/env python\n'''\nExample script to estimate the rank of the given data array.\n'''\n\nimport matplotlib.pyplot as plt\nimport mne\nfrom mne.datasets import sample\nfrom jumeg.jumeg_utils import rank_estimation\n\ndata_path = sample.data_path()\nsubjects_dir = data_path + '/subjects'\n\nfname_raw = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'\nfname_event = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'\n\nraw = mne.io.read_raw_fif(fname_raw)\nevents = mne.read_events(fname_event)\n\n# add a bad channel\nraw.info['bads'] += ['MEG 2443']\n\n# pick MEG channels\npicks = mne.pick_types(raw.info, meg='mag', eeg=False, stim=False, eog=False,\n exclude='bads')\n\ndata = raw.get_data()[picks, :]\n\nrank_all, rank_median = rank_estimation(data)\n\nprint('Ranks in order: MIBS, BIC, GAP, AIC, MDL, pct95, pct99: ', rank_all)\nprint('The median of the data is %f' % rank_median)\n","sub_path":"examples/plot_rank_estimation.py","file_name":"plot_rank_estimation.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"143093281","text":"#!/usr/bin/env python\n# authorship: Sebastien Boisvert\n# copyright: Copyright (C) 2012 Sebastien Boisvert\n# license: GNU General Public License version 3\n\nimport sys\n\narguments=sys.argv\n\nif len(sys.argv)!=4:\n\tprint(\"Usage: \"+arguments[0]+\" CoverageDistribution.txt startingCoverage endingCoverage\")\n\tsys.exit()\n\nfile=arguments[1]\n\nstream=open(file)\n\nsum=0\ncount=0\nstartingCoverage=int(arguments[2])\nendingCoverage=int(arguments[3])\n\nfor line in stream:\n\tif line[0]=='#':\n\t\tcontinue\n\ttokens=line.split()\n\tcoverage=int(tokens[0])\n\n\tif coverageendingCoverage:\n\t\tcontinue\n\n\tfrequency=int(tokens[1])\n\n\tsum+=(coverage*frequency)\n\tcount+=frequency\n\t\nstream.close()\n\naverageCoverage=sum/count\n\n# we must divide by two because we only need one DNA strand\ngenomeSize=count/2\n\nprint(\"Starting k-mer coverage: \"+str(startingCoverage))\nprint(\"Ending k-mer coverage: \"+str(endingCoverage))\nprint(\"Average k-mer coverage: \"+str(averageCoverage))\nprint(\"Estimated haploid genome size: \"+str(genomeSize))\n\n","sub_path":"Calculate-Genome-Size.py","file_name":"Calculate-Genome-Size.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"222381575","text":"\r\nclass Fibonacci(): \r\n\tdef __init__(self):\r\n\t\tself.seq = [0, 1]\r\n # \r\n\tdef __iter__(self):\r\n\t\treturn self\r\n\t \r\n\tdef next(self):\r\n\t\tself.seq.append(sum(self.seq))\r\n\t\tdel self.seq[0]\r\n\t\treturn self.seq[-1] #acessando ultimo elemento da lista\r\n \r\n\r\n\"\"\"\r\n2.Crie um gerador count(start=1,step=1). Exemplo: count(10)-> 10,11,12...\r\n\"\"\"\r\nclass Count():\r\n\tdef __init__(self, valor, passo = 1):\r\n\t\tself.valor = valor - passo\r\n\t\tself.passo = passo\r\n\r\n\tdef __iter__(self):\r\n\t\treturn self\r\n\r\n\tdef next(self):\r\n\t\tself.valor += self.passo\r\n\t\treturn self.valor\r\n\r\n\"\"\"\r\n3.Crie o gerador ciclo(coleção). Ex.: ciclo('ABCD') -> A B C D A B C...\r\n\"\"\"\t\r\nclass Ciclo():\r\n\tdef __init__(self, colecao):\r\n\t\ttry:\r\n\t\t\t_ = (x for x in colecao)\r\n\t\texcept TypeError as e:\r\n\t\t\traise e\r\n\t\telse:\r\n\t\t\tself.colecao = colecao\r\n\t\t\tself.indice = -1\r\n\r\n\tdef __iter__(self):\r\n\t\treturn self\r\n\r\n\tdef next(self):\r\n\t\tif self.indice < len(self.colecao)-1:\r\n\t\t\tself.indice += 1\r\n\t\t\treturn self.colecao[self.indice]\r\n\t\telse:\r\n\t\t\tself.indice = 0\r\n\t\t\tif len(self.colecao) > 0:\r\n\t\t\t\treturn self.colecao[self.indice]\r\n\t\t\telse:\r\n\t\t\t\traise StopIteration\r\n\t\t\t\t\r\n\"\"\"\r\n4. Crie o iterador repetir(n,i).Ex.: repetir(10,3)-> 10 10 10\r\n\"\"\"\r\nclass Repeat():\r\n\r\n\tdef __init__(self, objeto, max = None):\r\n\t\tself.objeto = objeto\r\n\r\n\t\tif max is not None:\r\n\t\t\tself.qtd = max\r\n\t\t\tself.limite = True\t#Possui um limite\r\n\t\telse:\r\n\t\t\tself.limite = False\t#Não possui um limite\r\n\r\n\tdef __iter__(self):\r\n\t\treturn self\r\n\r\n\tdef next(self):\r\n\t\tif self.limite == True:\r\n\t\t\tif self.qtd > 0:\r\n\t\t\t\tself.qtd -= 1\r\n\t\t\t\treturn self.objeto\r\n\t\t\telse:\r\n\t\t\t\traise StopIteration\r\n\t\telse:\r\n\t\t\treturn self.objeto\r\n\r\n\"\"\"\r\n\t5.Executa uma função sobre dois elementos da lista por vez\r\n\"\"\"\r\nclass Accumulate():\r\n\tdef __init__(self, colecao, funcao = lambda x, y: x + y):\r\n\t\ttry:\r\n\t\t\t_ = (x for x in colecao)\r\n\t\t\t_ = funcao(1,1)\r\n\t\texcept Exception as e:\r\n\t\t\traise e\r\n\t\telse:\r\n\t\t\tself.colecao = colecao\r\n\t\t\tself.funcao = funcao\r\n\t\t\tself.indice = -1\r\n\t\t\tself.ult_val = None\r\n\r\n\tdef __iter__(self):\r\n\t\treturn self\r\n\r\n\tdef next(self):\r\n\t\tif self.indice < len(self.colecao) - 1 and len(self.colecao) > 0:\r\n\t\t\tself.indice += 1\r\n\t\t\tif self.ult_val == None:\r\n\t\t\t\tself.ult_val = self.colecao[self.indice]\r\n\t\t\t\treturn self.ult_val\r\n\t\t\telse:\r\n\t\t\t\tself.ult_val = self.funcao(self.ult_val, self.colecao[self.indice])\r\n\t\t\t\treturn self.ult_val\r\n\t\telse:\r\n\t\t\traise StopIteration\r\n\"\"\"\r\n6.Crie o iterador chain(s1,s2,s3,...). Ex.: chain('ABCD','EFGH') ->A B C D E F G H\r\n\"\"\"\r\nclass Chain():\r\n\tdef __init__(self, *colecoes):\r\n\t\tself.indice = -1\r\n\t\tself.ind_lis_atual = 0\r\n\t\tself.colecoes = colecoes\r\n\t\tself.lista_atual = None\r\n\r\n\tdef __iter__(self):\r\n\t\treturn self\r\n\r\n\tdef next(self):\r\n\t\tif len(self.colecoes) > 0 and self.ind_lis_atual < len(self.colecoes):\r\n\t\t\tif self.indice < len(self.colecoes[self.ind_lis_atual])-1:\r\n\t\t\t\tself.indice += 1\r\n\t\t\t\treturn self.colecoes[self.ind_lis_atual][self.indice]\r\n\t\t\telse:\r\n\t\t\t\tself.indice = 0\r\n\t\t\t\tself.ind_lis_atual += 1 #proxima lista\r\n\r\n\t\t\t\tif self.ind_lis_atual is not len(self.colecoes):\r\n\t\t\t\t\t#verificando se a proxima existe\r\n\t\t\t\t\treturn self.colecoes[self.ind_lis_atual][self.indice]\r\n\t\t\t\telse:\r\n\t\t\t\t\traise StopIteration\r\n\t\telse:\r\n\t\t\traise StopIteration\r\n\r\nif __name__ == '__main__':\r\n\t#k = Count(50,1)\r\n\t#k = Ciclo('REBECA')\r\n\t#k = Repeat(10,10)\r\n\t#k = Accumulate([1,2,3,4,5,6,7,8,9,10])\r\n\t#k = Chain([1,2,3,4],\"funcio\")\r\n\tfib = Fibonacci()\r\n\t\r\n\tfor i in range(10):\r\n\t\tprint(fib.next())\r\n\t\r\n\t\r\n\tfor i in range(10):\r\n\t\tprint(k.next())\r\n\t\r\n","sub_path":"lista3.py","file_name":"lista3.py","file_ext":"py","file_size_in_byte":3734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"107833720","text":"#CH12-10. 토끼와 거북이의 경주 - 전체코드.\r\n\r\nimport turtle\r\nimport random\r\n\r\nscreen = turtle.Screen( )\r\nimage1 = \"D:\\\\rabbit.gif\"\r\nimage2 = \"D:\\\\turtle.gif\"\r\nscreen.addshape(image1)\r\nscreen.addshape(image2)\r\n\r\nt1 = turtle.Turtle( )\t# 토끼\r\nt2 = turtle.Turtle( ) \t# 거북이\r\n\r\nt1.shape(image1)\t# t1거북이의 모양은 거북이 형태로 지정\r\nt1.pensize(5)\t\t# t1거북이의 펜의 굵기를 5로 지정\r\n\r\n\r\nt2.shape(image2)\r\nt2.pensize(5)\r\n\r\nt1.penup( )\r\nt1.goto(-300, 0)\r\n\r\nt2.penup( )\r\nt2.goto(-300, -100)\r\n\r\nt1.pendown( )\t#달리기 경주 준비\r\nt2.pendown( )\r\n\r\nfor i in range(10): \t\t\t# 본격적인 경주가 이루어지는 부분입니다.\r\n\td1 = random.randint(1, 60)\r\n\tt1.forward(d1) \t\t\r\n\td2 = random.randint(1, 60)\r\n\tt2.forward(d2)\t\r\n","sub_path":"CH12-10.py","file_name":"CH12-10.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"378915562","text":"import scrapy\nfrom lianjia.items import LianjiaItem\n\nclass LianjiaSpider(scrapy.Spider):\n name = \"lianjia\"\n allowed_domains = [\"lianjia.com\"]\n start_urls = [\n \"http://bj.lianjia.com/ershoufang/pg1tt2/\",\n \"https://sz.fang.lianjia.com/loupan/\",\n ]\n\n def parse(self, response):\n # for href in response.css(\"ul.directory.dir-col > li > a::attr('href')\"):\n # url = response.urljoin(response.url, href.extract())\n # yield scrapy.Request(url, callback=self.parse_dir_contents)\n for hinfo in response.css('ul.sellListContent li.clear div.info.clear div.address div.houseInfo'):\n item = LianjiaItem()\n item['title'] = ''\n item['location'] = hinfo.xpath('a/text()').extract()[0]\n item['house_info'] = hinfo.xpath('text()').extract()[0]\n # self.log(\"title = %s\" % str(item['title']))\n # self.log(\"location = %s\" % str(item['location']))\n # self.log(\"house_info = %s\" % str(item['house_info']))\n yield item\n # def parse_dir_contents(self, response):\n # for sel in response.xpath('//ul/li'):\n # item = DmozItem()\n # item['title'] = sel.xpath('a/text()').extract()\n # item['link'] = sel.xpath('a/@href').extract()\n # item['desc'] = sel.xpath('text()').extract()\n # yield item","sub_path":"lianjia/spiders/lianjia_spider.py","file_name":"lianjia_spider.py","file_ext":"py","file_size_in_byte":1379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"298990606","text":"import cv2\nimport os\n\nsamplePath = (os.path.dirname(os.path.abspath(__file__))) + \"/sample-images/\"\n\nfor image in os.listdir(samplePath):\n\n source = cv2.imread((samplePath + str(image)), 1)\n \n resized = cv2.resize(source, (100, 100))\n\n cv2.imwrite((samplePath + \"resized_\" + str(image)), resized)\n","sub_path":"basics/opencv/resizing.py","file_name":"resizing.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"637760325","text":"\"\"\"\nHolds list of Turn objects represents queues.\n\nynonp06/25/2020\nלגבי תרגיל 4 - יש לי תחושה שהיה יותר קל לשמור רשימה אחת של ״ממתינים״,\n ואז כשפקיד מתפנה לחפש את הממתין הבא שמחכה לו, ואם אין כזה להזמין את הממתין הבא הכללי\n\"\"\"\n\n\nclass Turn:\n def __init__(self, visitor, officer):\n self.visitor = visitor\n self.officer = officer\n\n\nclass OfficerQueuesManager:\n \"\"\"\n List to hold turns of all (visitor,officer)\n \"\"\"\n\n def __init__(self):\n self.turns = []\n\n def push(self, officer, visitor):\n turn = Turn(visitor, officer)\n self.turns.append(turn)\n\n def pop(self, officer):\n try:\n # And to get a specific clerk's visitor we'll have:\n cur_officer_turns = [turn for turn in self.turns if turn.officer == officer]\n cur_officer_turn = cur_officer_turns.pop(0)\n self.turns.remove(cur_officer_turn)\n return cur_officer_turn\n\n except IndexError:\n return f\"officer {officer} queue is empty\"\n\n def print(self):\n for turn in self.turns:\n print(f\"{turn.visitor, turn.officer}\")\n\n\n\"\"\"\nTo hold each iteration command parts ,\nto send to manager.\n\"\"\"\n\n\n# main\nmanager = OfficerQueuesManager()\n\ncommands = {\n 'wait': manager.push,\n 'next': manager.pop,\n}\n\nwhile True:\n\n try:\n cmd, *params = command = input(\"Please enter |optional : \")\\\n .strip().split()\n cur_officer, *_ = params\n cur_turn = commands[cmd](*params)\n if cur_turn is not None:\n try:\n print(f\"{cur_turn.visitor}\")\n except Exception:\n print(f\"{cur_officer} queue is empty\")\n except Exception:\n print(\"Illegal format, try again.\")\n continue\n\n manager.print()\n","sub_path":"lesson21/ex4-list-dispatcher.py","file_name":"ex4-list-dispatcher.py","file_ext":"py","file_size_in_byte":1953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"538580585","text":"# -*- coding: utf-8 -*-\nfrom __future__ import print_function\nimport torch\nimport time\nimport data_read\nimport Net_structure\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.autograd import Variable\nfrom tqdm import tqdm\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\npath= \"/home/hzq/SkeletonDiag/\"\nbatch_size= 20\nlearning_rate= 0.001\nEPOCH= 250\nresize=(256,256)\n########load train dataset\ntrainloader = data_read.loadtraindata(path,batch_size, resize)\n# data_fromfolder=data_read.loaddatafromfolder()\n# dataset=data_fromfolder\n########load test dataset\ntestdataloader = data_read.loadtestdata(path,batch_size, resize)\n# testdatafromfolder = data_read.loadtestdatafromfolder()\n# testdataset=testdatafromfolder\n\nnet = Net_structure.Alexnet(2).to(device)\ncriterion = nn.CrossEntropyLoss() # 交叉熵损失函数,通常用于多分类问题上\noptimizer= optim.Adam(net.parameters(), lr= learning_rate)\noptimizer2= optim.SGD(net.parameters(),lr=learning_rate, momentum=0.9)\n\n\n# 训练\nif __name__ == \"__main__\":\n start_time= time.time()\n torch.cuda.empty_cache()\n for epoch in range(EPOCH):\n print('epoch{}'.format(epoch+1))\n sum_loss = 0.0\n sum_acc= 0.0\n for inputs, labels in tqdm(trainloader):\n inputs = Variable(inputs)\n labels = Variable(labels)\n inputs=inputs.to(device)\n labels=labels.to(device)\n # 梯度清零\n optimizer2.zero_grad()\n # forward + backward\n outputs = net(inputs)\n labels=labels.long()\n loss = criterion(outputs, labels)\n loss.backward()\n optimizer2.step()\n end_time= time.time()\n sum_loss+=float(loss.data.item())\n pred=torch.max(outputs,1)[1]\n train_correct= (pred==labels).sum()\n sum_acc+=float(train_correct.data.item())\n end_time=time.time()\n print('Train Loss: {:.6f}, Acc: {:.6f}, cost time: {:.2f}'.format(sum_loss/(len(trainloader.dataset)), sum_acc/(len(trainloader.dataset)),end_time-start_time))\n end_time=time.time()\n print('total cost time is: %.2f'%(start_time-end_time))\n\n torch.save(net.state_dict(),'/home/hzq/SkeletonDiag/model/256x256_Elbow_VGG16_%d.pt'%EPOCH)\n #fout = open(output_path + str(EPOCH) + \"_word_based_output.txt\", \"w\")\n\n start_time=time.time()\n test_acc=0\n for images, labels in tqdm(testdataloader):\n images, labels= Variable(images).to(device), Variable(labels).to(device)\n outputs = net(images)\n labels = labels.long()\n pred = torch.max(outputs, 1)[1]\n train_correct = (pred == labels).sum()\n test_acc += float(train_correct.data.item())\n end_time = time.time()\n print('Test data Acc: {:.6f}, cost time: {:.2f}'.format(test_acc / (len(testdataloader.dataset)), end_time-start_time))","sub_path":"src/run_cnn.py","file_name":"run_cnn.py","file_ext":"py","file_size_in_byte":2889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"100291402","text":"# Locations to measure actual and to create forecasts for\n\n# Llanfairfechen = microclimate - side of mountain and presumably quite wet\n# Fastnet Rock : stormy weather\n# for free tier of 1000 api calls per day I can have 6 locations\nlocations = [\n {\"location\": \"Stockcross, UK\", \"lat\": \"51.41460037\", \"lon\": \"-1.37486378\"},\n {\"location\": \"Yarmouth Harbour, UK\", \"lat\": \"50.7051\", \"lon\": \"-1.5027\"},\n {\"location\": \"Lymington Harbour, UK\", \"lat\": \"50.7535\", \"lon\": \"-1.5283\"},\n {\"location\": \"Fastnet Rock, Ireland\", \"lat\": \"51.3889\", \"lon\": \"-9.6036\"},\n]\n\n# {\"location\": \"Bay of Biscay, Portugal\", \"lat\": \"45.5570\", \"lon\": \"-3.1632\"},\n# {\"location\": \"Mercury Marina, Hamble, UK\", \"lat\": \"50.8708\", \"lon\": \"-1.3129\"},\n# {\"location\": \"Portsmouth, UK\", \"lat\": \"50.8198\", \"lon\": \"-1.0880\"},\n# {\"location\": \"Cowes, UK\", \"lat\": \"50.7628\", \"lon\": \"-1.3005\"},\n# {\"location\": \"Snake Pass, UK\", \"lat\": \"53.4326\", \"lon\": \"-1.8673\"}\n#{\"location\": \"Beaulieu, UK\", \"lat\": \"50.8156\", \"lon\": \"-1.4532\"},\n#{\"location\": \"Lymington Harbour, UK\", \"lat\": \"50.7535\", \"lon\": \"-1.5283\"},\n#{\"location\": \"Llanfairfechen, UK\", \"lat\": \"53.2528\", \"lon\": \"-3.9751\"},","sub_path":"environments/production/metcrouch/apache/src/locations.py","file_name":"locations.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"71335422","text":" \ndef Charlie_PF(N): \n\n\tif (N < 2): \n\t\treturn 0; \n\n\tarr = [True] * (N + 1); \n\tprod = 1; \n\tres = 0; \n\tp = 2; \n\twhile (p * p <= N): \n\t\t\n\t\t# If p is prime \n\t\tif (arr[p] == True): \n\t\t\tfor i in range(p * 2, N + 1, p): \n\t\t\t\tarr[i] = False; \n\n\t\t\n\t\t\tprod *= p; \n\t\t\tif (prod > N): \n\t\t\t\treturn res; \n\t\t\tres += 1; \n\t\tp += 1; \n\n\treturn res; \n\n \nN = input(); \nprint(Charlie_PF(N));\n","sub_path":"Python/Charlie's_Prime_Factors/Charlies_prime_factors.py","file_name":"Charlies_prime_factors.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"586458607","text":"class Solution(object):\n def uniquePaths(self, m, n):\n \"\"\"\n :type m: int\n :type n: int\n :rtype: int\n \"\"\"\n # This way of definition is tricky, the outer side is number of rows, inner is number of columns\n result = [[0 for x in range(n)] for y in range(m)]\n \n for i in range(n):\n result[0][i] = 1\n \n for j in range(m):\n result[j][0] = 1\n \n for i in range(1,m):\n for j in range(1,n):\n result[i][j] = result[i][j-1]+result[i-1][j]\n \n return result[m-1][n-1]\n \ntest = Solution()\ntest.uniquePaths(1, 2)","sub_path":"q62/Q62.py","file_name":"Q62.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"546192633","text":"import bpy\nimport numpy as np\nimport xml.etree.cElementTree as ET\nfrom xml.dom import minidom\n\nfrom math import pi\nimport os\nimport sys\nsys.path.append(os.getcwd())\n\nfrom rigidbody_rope import *\nfrom sklearn.neighbors import NearestNeighbors\nfrom knots import tie_pretzel_knot, tie_stevedore, tie_figure_eight, tie_double_pretzel\nfrom untangle_utils import *\nfrom dr_utils import *\n\ndef set_animation_settings(anim_end):\n # Sets up the animation to run till frame anim_end (otherwise default terminates @ 250)\n scene = bpy.context.scene\n scene.frame_end = anim_end\n scene.rigidbody_world.point_cache.frame_end = anim_end\n\ndef set_render_settings(engine, render_size):\n # Set rendering engine, dimensions, colorspace, images settings\n if not os.path.exists(\"./images\"):\n os.makedirs('./images')\n else:\n os.system('rm -r ./images')\n if not os.path.exists(\"./actions\"):\n os.makedirs('./actions')\n else:\n os.system('rm -r ./actions')\n os.makedirs('./actions')\n scene = bpy.context.scene\n scene.render.engine = engine\n render_width, render_height = render_size\n scene.render.resolution_x = render_width\n scene.render.resolution_y = render_height\n #scene.view_settings.exposure = 0.8\n if engine == 'BLENDER_WORKBENCH':\n scene.render.display_mode\n scene.render.image_settings.color_mode = 'RGB'\n scene.display_settings.display_device = 'None'\n scene.sequencer_colorspace_settings.name = 'XYZ'\n scene.render.image_settings.file_format='JPEG'\n elif engine == \"BLENDER_EEVEE\":\n scene.eevee.taa_samples = 1\n scene.render.image_settings.file_format='JPEG'\n scene.view_settings.view_transform = 'Raw'\n scene.eevee.taa_render_samples = 1\n\ndef save_actions(annotation_idx, annotation_list):\n np_annotations = np.array(annotation_list)\n np.save('actions/%05d.npy'%annotation_idx, np_annotations)\n\ndef find_knot(num_segments, chain=False, depth_thresh=0.4, idx_thresh=3, pull_offset=3):\n\n piece = \"Torus\" if chain else \"Cylinder\"\n cache = {}\n\n # Make a single pass, store the xy positions of the cylinders\n for i in range(num_segments):\n cyl = get_piece(piece, i if i else -1)\n x,y,z = cyl.matrix_world.translation\n key = tuple((x,y))\n val = {\"idx\":i, \"depth\":z}\n cache[key] = val\n neigh = NearestNeighbors(2, 0)\n planar_coords = list(cache.keys())\n neigh.fit(planar_coords)\n # Now traverse and look for the under crossing\n for i in range(num_segments):\n cyl = get_piece(piece, i if i else -1)\n x,y,z = cyl.matrix_world.translation\n match_idxs = neigh.kneighbors([(x,y)], 2, return_distance=False) # 1st neighbor is always identical, we want 2nd\n nearest = match_idxs.squeeze().tolist()[1:][0]\n x1,y1 = planar_coords[nearest]\n curr_cyl, match_cyl = cache[(x,y)], cache[(x1,y1)]\n depth_diff = match_cyl[\"depth\"] - curr_cyl[\"depth\"]\n idx_diff = abs(match_cyl[\"idx\"] - curr_cyl[\"idx\"])\n if depth_diff > depth_thresh and idx_diff > idx_thresh:\n pull_idx = i + pull_offset # Pick a point slightly past under crossing to do the pull\n dx = planar_coords[pull_idx][0] - x\n dy = planar_coords[pull_idx][1] - y\n hold_idx = match_cyl[\"idx\"]\n SCALE_X = 1\n SCALE_Y = 1\n Z_OFF = 2\n action_vec = [SCALE_X*dx, SCALE_Y*dy, Z_OFF] # Pull in the direction of the rope (NOTE: 7 is an arbitrary scale for now, 6 is z offset)\n return pull_idx, hold_idx, action_vec # Found! Return the pull, hold, and action\n return 16, 25, [0,0,0] # Didn't find a pull/hold\n\ndef annotate(frame, offset=4, num_knots=1):\n # knot_only = True: means only record the under, over crossings\n # knot_only = False: means record annotations for full rope\n '''Gets num_annotations annotations of cloth image at provided frame #, adds to mapping'''\n scene = bpy.context.scene\n render_size = (\n int(scene.render.resolution_x),\n int(scene.render.resolution_y),\n )\n annot_list = []\n pull_idx, hold_idx, action_vec = find_knot(50)\n action_vec /= np.linalg.norm(action_vec)\n action_vec *= 2.5\n pull_loc = get_piece(\"Cylinder\", pull_idx).matrix_world.translation\n pull_offset = pull_loc + Vector(action_vec)\n hold_loc = get_piece(\"Cylinder\", hold_idx).matrix_world.translation\n locs = [pull_loc, pull_offset, hold_loc]\n annotations = [] # [[x1,y1],[x2,y2],...\n for loc in locs:\n camera_coord = bpy_extras.object_utils.world_to_camera_view(scene, bpy.context.scene.camera, loc)\n x, y = [round(camera_coord.x * render_size[0]), round(render_size[1] - camera_coord.y * render_size[1])]\n annotations.append([x,y])\n save_actions(frame, annotations)\n\ndef get_piece(piece_name, piece_id):\n # Returns the piece with name piece_name, index piece_id\n if piece_id == -1:\n return bpy.data.objects['%s' % (piece_name)]\n return bpy.data.objects['%s.%03d' % (piece_name, piece_id)]\n\ndef toggle_animation(obj, frame, animate):\n # Sets the obj to be animable or non-animable at particular frame\n obj.rigid_body.kinematic = animate\n obj.keyframe_insert(data_path=\"rigid_body.kinematic\", frame=frame)\n\ndef take_action(obj, frame, action_vec, animate=True):\n # Keyframes a displacement for obj given by action_vec at given frame\n curr_frame = bpy.context.scene.frame_current\n dx,dy,dz = action_vec\n if animate != obj.rigid_body.kinematic:\n # We are \"picking up\" a dropped object, so we need its updated location\n obj.location = obj.matrix_world.translation\n obj.rotation_euler = obj.matrix_world.to_euler()\n obj.keyframe_insert(data_path=\"location\", frame=curr_frame)\n obj.keyframe_insert(data_path=\"rotation_euler\", frame=curr_frame)\n toggle_animation(obj, curr_frame, animate)\n obj.location += Vector((dx,dy,dz))\n obj.keyframe_insert(data_path=\"location\", frame=frame)\n\ndef randomize_camera():\n ANGLE_DIVS = 65\n xrot = np.random.uniform(-pi/ANGLE_DIVS, pi/ANGLE_DIVS) \n yrot = np.random.uniform(-pi/ANGLE_DIVS, pi/ANGLE_DIVS) \n zrot = np.random.uniform(-pi/6, pi/6) \n xoffset = 2\n yoffset = 2\n zoffset = 2\n dx = np.random.uniform(-xoffset, xoffset)\n dy = np.random.uniform(-yoffset, yoffset)\n dz = np.random.uniform(-zoffset, zoffset)\n bpy.context.scene.camera.rotation_euler = (xrot, yrot, zrot)\n bpy.context.scene.camera.location = Vector((2,0,28)) + Vector((dx, dy, dz))\n \ndef render_frame(frame, render_offset=0, step=10, filename=\"%05d.jpg\", folder=\"images\", annot=True, num_knots=1, mapping=None):\n # DOMAIN RANDOMIZE\n global rig\n randomize_camera()\n #randomize_rig(rig, mode=\"braid\")\n #randomize_rig(rig)\n #randomize_light()\n #table = bpy.data.objects[\"Plane\"]\n #if random.random() < 0.33:\n # texture_randomize(table, 'dr_data/val2017')\n #elif random.random() < 0.66:\n # texture_randomize(table, 'dr_data/fabrics')\n #else:\n # color_randomize(table)\n #color = (np.random.uniform(0.7,1.0),np.random.uniform(0.7,1.0),np.random.uniform(0.7,1.0))\n #color_randomize(rig, color=color)\n\n # Renders a single frame in a sequence (if frame%step == 0)\n frame -= render_offset\n if frame%step == 0:\n scene = bpy.context.scene\n index = frame//step\n #render_mask(\"image_masks/%06d_visible_mask.png\", \"images_depth/%06d_rgb.png\", index)\n scene.render.filepath = os.path.join(folder, filename) % index\n bpy.ops.render.render(write_still=True)\n if annot:\n annotate(index)\n\ndef render_mask(mask_filename, depth_filename, index):\n # NOTE: this method is still in progress\n scene = bpy.context.scene\n saved = scene.render.engine\n scene.render.engine = 'BLENDER_EEVEE'\n scene.eevee.taa_samples = 1\n scene.eevee.taa_render_samples = 1\n scene.use_nodes = True\n tree = bpy.context.scene.node_tree\n links = tree.links\n render_node = tree.nodes[\"Render Layers\"]\n norm_node = tree.nodes.new(type=\"CompositorNodeNormalize\")\n inv_node = tree.nodes.new(type=\"CompositorNodeInvert\")\n math_node = tree.nodes.new(type=\"CompositorNodeMath\")\n math_node.operation = 'CEIL' # Threshold the depth image\n composite = tree.nodes.new(type = \"CompositorNodeComposite\")\n\n links.new(render_node.outputs[\"Depth\"], inv_node.inputs[\"Color\"])\n links.new(inv_node.outputs[0], norm_node.inputs[0])\n links.new(norm_node.outputs[0], composite.inputs[\"Image\"])\n\n scene.render.filepath = depth_filename % index\n bpy.ops.render.render(write_still=True)\n\n links.new(norm_node.outputs[0], math_node.inputs[0])\n links.new(math_node.outputs[0], composite.inputs[\"Image\"])\n\n scene.render.filepath = mask_filename % index\n bpy.ops.render.render(write_still=True)\n # Clean up \n scene.render.engine = saved\n for node in tree.nodes:\n if node.name != \"Render Layers\":\n tree.nodes.remove(node)\n scene.use_nodes = False\n\n\ndef reidemeister(params, start_frame, render=False, render_offset=0, annot=True, num_knots=1, mapping=None):\n\n piece = \"Cylinder\"\n last = params[\"num_segments\"]-1\n end1 = get_piece(piece, -1)\n end2 = get_piece(piece, last)\n\n middle_frame = start_frame+50\n end_frame = start_frame+100\n\n take_action(end1, middle_frame, (np.random.uniform(9,11)-end1.matrix_world.translation[0],np.random.uniform(-3,3),0))\n for step in range(start_frame, middle_frame):\n bpy.context.scene.frame_set(step)\n if render:\n render_frame(step, render_offset=render_offset, annot=annot, mapping=mapping, num_knots=num_knots)\n take_action(end2, end_frame, (np.random.uniform(-6,-8)-end2.matrix_world.translation[0],np.random.uniform(-3,3),0))\n # Drop the ends\n\n toggle_animation(end1, middle_frame, False)\n #toggle_animation(end1, end_frame, False)\n toggle_animation(end2, end_frame, False)\n\n for step in range(middle_frame, end_frame):\n bpy.context.scene.frame_set(step)\n if render:\n render_frame(step, render_offset=render_offset, annot=annot, mapping=mapping, num_knots=num_knots)\n return end_frame\n\ndef take_undo_action_oracle(params, start_frame, render=False, render_offset=0, annot=True, num_knots=1, mapping=None):\n piece = \"Cylinder\"\n pull_idx, hold_idx, action_vec = find_knot(50)\n #action_vec = np.array(action_vec) + np.random.uniform(-0.5, 0.5, 3)\n action_vec = np.array(action_vec) + np.random.uniform(-1,1,3)\n action_vec /= np.linalg.norm(action_vec)\n action_vec *= 2.5\n pull_cyl = get_piece(piece, pull_idx if pull_idx else -1)\n hold_cyl = get_piece(piece, hold_idx if hold_idx else -1)\n end_frame = start_frame + 100\n take_action(hold_cyl, end_frame, (0,0,0))\n\n for step in range(start_frame, start_frame + 10):\n bpy.context.scene.frame_set(step)\n #render_frame(step, render_offset=render_offset, annot=annot, mapping=mapping)\n if render and (abs(step-start_frame) < 5 or abs(step-(start_frame+10)) < 5):\n render_frame(step, render_offset=render_offset, annot=annot, mapping=mapping)\n elif render:\n render_offset += 1\n\n take_action(pull_cyl, end_frame, action_vec)\n ## Release both pull, hold\n toggle_animation(pull_cyl, end_frame, False)\n toggle_animation(hold_cyl, end_frame, False)\n settle_time = 30\n\n for step in range(start_frame + 10, end_frame+settle_time):\n bpy.context.scene.frame_set(step)\n #render_frame(step, render_offset=render_offset, annot=annot, mapping=mapping)\n if render and (abs(step-(start_frame+10)) < 2 or abs(step-(end_frame+settle_time)) < 2):\n render_frame(step, render_offset=render_offset, annot=annot, mapping=mapping)\n elif render:\n render_offset += 1\n return end_frame+settle_time, render_offset\n\ndef generate_dataset(iters, params, chain=False, render=False):\n\n set_animation_settings(15000)\n piece = \"Cylinder\"\n last = params[\"num_segments\"]-1\n mapping = None\n\n render_offset = 0\n num_loosens = 4\n for i in range(iters):\n print(\"Iter %d of %d\" % (i,iters))\n num_knots = 1\n if i%2==0:\n knot_end_frame = tie_pretzel_knot(params, render=False)\n elif i%2==1:\n knot_end_frame = tie_figure_eight(params, render=False)\n render_offset += knot_end_frame\n reid_end_frame = reidemeister(params, knot_end_frame, render=render, render_offset=render_offset, num_knots=num_knots, mapping=mapping)\n perturb_end_frame = random_perturb(reid_end_frame, params, render=False)\n render_offset += perturb_end_frame - reid_end_frame\n start = perturb_end_frame\n for i in range(num_loosens):\n loosen_end_frame, offset = take_undo_action_oracle(params, start, render=render, render_offset=render_offset, num_knots=num_knots, mapping=mapping)\n start = loosen_end_frame\n render_offset = offset\n render_offset -= loosen_end_frame\n bpy.context.scene.frame_set(0)\n for a in bpy.data.actions:\n bpy.data.actions.remove(a)\n\nif __name__ == '__main__':\n with open(\"rigidbody_params.json\", \"r\") as f:\n params = json.load(f)\n clear_scene()\n make_capsule_rope(params)\n rig = rig_rope(params, braid=0)\n add_camera_light()\n set_render_settings(params[\"engine\"],(params[\"render_width\"],params[\"render_height\"]))\n make_table(params)\n start = time.time()\n iters = 25\n generate_dataset(iters, params, render=True)\n end = time.time()\n print(\"time\", end-start)\n","sub_path":"render_bc.py","file_name":"render_bc.py","file_ext":"py","file_size_in_byte":13699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"460123269","text":"\"\"\"\nN이 주어졌을 때, fibonacci(N)을 호출했을 때, 0과 1이 각각 몇 번 출력되는지 구하는 프로그램을 작성하시오.\n\"\"\"\n\ndef fino_dp(num):\n cache= [ 0 for i in range(num+1)]\n cnt = [ 0 for i in range(num+1)]\n cache[0]=0\n cnt[0]=(1,0)\n if num==0:\n return cnt[num]\n cache[1]=1\n cnt[1]=(0,1)\n for idx in range(2, num+1):\n cnt[idx]=tuple(sum(ele) for ele in zip(cnt[idx-1],cnt[idx-2]))\n return cnt[num]\n\nT=int(input())\nfor _ in range(T):\n n=int(input())\n print(fino_dp(n)[0], fino_dp(n)[1])","sub_path":"1003.py","file_name":"1003.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"551695381","text":"def surfaceArea(grid):\n total_surface = 0\n l = len(grid)\n #每次遍历一个方格:\n for i in range(0,l):\n for j in range(0,l):\n #计算该方格内的所有立方体 在不跟其他方格干扰的情况下 的表面积\n p = grid[i][j]\n total_surface += p*6-(p-1)*2 if p>0 else 0\n #减去该方格的立方体 跟周围方格的立方体 的重叠面数\n #这里用了小技巧,比较繁琐的是上下左右的grid都算一遍\n #但实际���,只需要计算 [i,j]方格 的 [i,j+1]右侧和[i+1,j]下侧的方格的立方体重叠面数乘以2就行。\n #因为重叠是相互的!!!\n #焗个栗子:[1,1]和[1,2]的重叠数 与 [1,2]和[1,1]的重叠数 是一样的\n #所以上下左右四个周围方格,选两个方向的再乘2就行。\n #重叠数的计算也不难,两个相邻方格的最小值乘2就是重叠面数了。\n total_surface -= min(p,grid[i+1][j])*2 if i+13000:\n return 'red'\n elif eleva>1500 and eleva<=3000:\n return 'orange'\n else:\n return 'green'\n\n\nmap = folium.Map(location= [40.7,-111.9], zoom_start=5, tiles = 'Mapbox Bright')\n\nfgv = folium.FeatureGroup(name = \"Volcanoes\")\n\nfor lat, lon, elevat in zip(latitudes,longitudes,elevations):\n fgv.add_child(folium.CircleMarker(location = [lat,lon], popup = str(elevat),\n color='grey',radius = 5,fill_opacity = 1, fill= True,fill_color=color_producer(elevat)))\n\nfgp = folium.FeatureGroup(name = \"Population\")\n\nfgp.add_child(folium.GeoJson(data=(open('world.json',encoding = 'utf-8-sig').read()),\nstyle_function = lambda x:{'fillColor':'green' if x['properties']['POP2005']<15000000\nelse 'orange' if 15000000<= x['properties']['POP2005']<40000000 else 'red'}))\n\nmap.add_child(fgv)\nmap.add_child(fgp)\nmap.add_child(folium.LayerControl())\nmap.save(\"TheMap.html\")\n","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"582152662","text":"import numpy as np\n\n# key should be a numpy array\ndef inv_key(key):\n det = int(round(np.linalg.det(key)))\n inv = np.linalg.inv(key)\n tem = (inv * det)\n modinv = np.mod(det ** 29, 31)\n return np.around(np.mod(tem * modinv, 31)).astype(int)\n\ndef char_to_num(string):\n\tresult = []\n\tfor character in string:\n\t\tif character == \"_\":\n\t\t\tresult.append(26)\n\t\telif character == \".\":\n\t\t\tresult.append(27)\n\t\telif character ==\",\":\n\t\t\tresult.append(28)\n\t\telif character == \"?\":\n\t\t\tresult.append(29)\n\t\telif character ==\"!\":\n\t\t\tresult.append(30)\n\t\telse:\n\t\t\tresult.append(ord(character)-65)\n\treturn result\ndef num_to_char(array):\n\tresult = []\ncipher1 = np.reshape(char_to_num(\"_CUKZFBMKDFJ.KO\"),(3,5))\nkey1 = [0, 18, 2, 6, 6, 20, 24, 0, 15]\ninverse_key1 = inv_key(np.reshape(key1,(3,3)))\nplain1 = np.matmul(inverse_key1,cipher1)\nprint (plain1)\nfor i in range(3):\n\tfor j in range(5):\n\t\tplain1[i][j] = plain1[i][j]%31\nprint (plain1)\n'''\nAssignment \n1. Cipher Text for problem 1 \n_CUKZFBMKDFJ.KO\n\n2. Key for problem 1\n0 18 2 6 6 20 24 0 15\n\n3.Cipher Text for problem 2 \nV?DNUEYAH\n\n4. Plain Text for problem 2 \nOH_,_SHIT\n\n5.The other Cipher Text\nGAHT!,!PA\n\n'''\n\n","sub_path":"hill_cipher/hill_test.py","file_name":"hill_test.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"576496046","text":"\"\"\"\n\ntraining_and_deploy.py \n\ncode for amazon sagemaker training\n\n\"\"\"\n\nimport os\nimport numpy as np\n\nimport tensorflow as tf\nfrom tensorflow.python.estimator.export.export import build_raw_serving_input_receiver_fn\nfrom tensorflow.python.estimator.export.export_output import PredictOutput\nimport sagemaker\nfrom sagemaker import get_execution_role\n\nimport generator\n\n\n# config\nINPUT_TENSOR_NAME = \"inputs_input\"\nSIGNATURE_NAME = \"serving_default\"\nW_HYP = False\nLEARNING_RATE = 0.001\nBATCH_SIZE = 64\nVOCAB_SIZE = 1254\nINPUT_LENGTH = 3000 if W_HYP else 1000\nEMBEDDING_DIM = 128\n\n# sagemaker_session = sagemaker.Session()\n# role = get_execution_role()s\n\n\n# WHEN do we find training_dir?\ntraining_dir = 'deephol-data-processed/proofs/human'\n\n\ndef keras_model_fn(hyperparameters):\n model = Sequential()\n model.add(Embedding(VOCAB_SIZE, EMBEDDING_DIM, input_length=INPUT_LENGTH, name='inputs'))\n model.add(SpatialDropout1D(0.2))\n model.add(CuDNNLSTM(4))\n model.add(Dense(41, activation='softmax'))\n \n # can use keras class to add parameters\n opt = 'adam'\n \n # can use keras class to add parameters\n loss = 'categorical_crossentropy'\n\n model.compile(loss=loss, optimizer=opt, metrics=['accuracy'])\n print(model.summary())\n \n return model\n\n\ndef serving_input_fn(hyperparameters):\n # Here it concerns the inference case where we just need a placeholder to store\n # the incoming images ...\n tensor = tf.placeholder(tf.float64, shape=[None, INPUT_LENGTH])\n inputs = {INPUT_TENSOR_NAME: tensor}\n return tf.estimator.export.ServingInputReceiver(inputs, inputs)\n\n\ndef train_input_fn(training_dir, hyperparameters):\n return _input(tf.estimator.ModeKeys.TRAIN, batch_size=BATCH_SIZE, data_dir=training_dir)\n\n\ndef eval_input_fn(training_dir, hyperparameters):\n return _input(tf.estimator.ModeKeys.EVAL, batch_size=BATCH_SIZE, data_dir=training_dir)\n\n\ndef _input(mode, batch_size, data_dir):\n assert os.path.exists(data_dir), (\"Unable to find input directory, check path\")\n\n if mode == tf.estimator.ModeKeys.TRAIN:\n datagen = generator.Keras_DataGenerator(data_dir=data_dir, dataset='train', \n w_hyp=W_HYP, batch_size=batch_size)\n elif mode == tf.estimator.ModeKeys.VALID:\n datagen = generator.Keras_DataGenerator(data_dir=data_dir, dataset='valid',\n w_hyp=W_HYP, batch_size=batch_size)\n elif mode == tf.estimator.ModeKeys.TEST:\n datagen = generator.Keras_DataGenerator(data_dir=data_dir, dataset='test',\n w_hyp=W_HYP, batch_size=batch_size)\n else:\n raise Exception('Invalid tf estimator mode key')\n\n # get batch\n features, labels = next(datagen)\n\n return {INPUT_TENSOR_NAME: features}, labels\n\n\n\n\n\n\n\n\n\nif __name__ =='__main__':\n parser = argparse.ArgumentParser()\n # hyperparameters sent by the client are passed as command-line arguments to the script.\n parser.add_argument('--epochs', type=int, default=50)\n parser.add_argument('--batch-size', type=int, default=64)\n parser.add_argument('--learning-rate', type=float, default=0.05)\n # Data, model, and output directories\n parser.add_argument('--output-data-dir', type=str, default=os.environ.get('SM_OUTPUT_DATA_DIR'))\n parser.add_argument('--model-dir', type=str, default=os.environ.get('SM_MODEL_DIR'))\n parser.add_argument('--train', type=str, default=os.environ.get('SM_CHANNEL_TRAIN'))\n parser.add_argument('--test', type=str, default=os.environ.get('SM_CHANNEL_TEST'))\n args, _ = parser.parse_known_args()\n # another function that does the real work \n # (and make the code cleaner)\n run_training(args)","sub_path":"deepmath/deephol/train/.ipynb_checkpoints/train_and_deploy-checkpoint.py","file_name":"train_and_deploy-checkpoint.py","file_ext":"py","file_size_in_byte":3743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"539905003","text":"from unittest.mock import MagicMock\n\nimport pytest\n\nfrom prefect.settings import PREFECT_API_URL, PREFECT_CLOUD_API_URL, temporary_settings\nfrom prefect.testing.cli import invoke_and_assert\n\n\ndef test_version_ephemeral_server_type():\n invoke_and_assert(\n [\"version\"], expected_output_contains=\"Server type: ephemeral\"\n )\n\n\n@pytest.mark.usefixtures(\"use_hosted_orion\")\ndef test_version_hosted_server_type():\n invoke_and_assert(\n [\"version\"], expected_output_contains=\"Server type: hosted\"\n )\n\n\ndef test_version_cloud_server_type():\n with temporary_settings(\n {\n PREFECT_API_URL: PREFECT_CLOUD_API_URL.value()\n + \"/accounts//workspaces/\"\n }\n ):\n invoke_and_assert(\n [\"version\"], expected_output_contains=\"Server type: cloud\"\n )\n\n\ndef test_version_client_error_server_type(monkeypatch):\n monkeypatch.setattr(\"prefect.get_client\", MagicMock(side_effect=ValueError))\n invoke_and_assert(\n [\"version\"], expected_output_contains=\"Server type: \"\n )\n","sub_path":"tests/cli/test_version.py","file_name":"test_version.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"366881795","text":"import numpy\nimport matplotlib.pyplot as plt\nimport math\n\n# creating the equation Xb = y\n\n# X = [1 | x | x^2]\nX = numpy.array((\n [1, 0, 0],\n [1, 1, 1],\n [1, 2, 4],\n [1, 3, 9],\n [1, 4, 16],\n [1, 5, 25],\n [1, 6, 36],\n [1, 7, 49],\n [1, 8, 64],\n [1, 9, 81],\n [1, 10, 100],\n [1, 11, 121],\n [1, 12, 144],\n))\n\n# Y = position of airplane\ny = numpy.array((\n [0],\n [5],\n [18],\n [63],\n [104],\n [159],\n [222],\n [277],\n [350],\n [481],\n [570],\n [677],\n [832],\n))\n\n\n\n# creating the equation (XtX)b = (Xt)y\nXtX = numpy.linalg.multi_dot((numpy.transpose(X), X))\nXty = numpy.linalg.multi_dot((numpy.transpose(X), y))\n\n# solving the equation\ncoefficients = numpy.linalg.solve(XtX, Xty)\n\npredicted = []\nfor i in range(len(y)):\n predicted.append(math.floor(numpy.linalg.multi_dot((X[i], coefficients))))\n\n\nplt.xlabel('Time (seconds)')\nplt.ylabel('Altitude of Airplane')\nplt.plot(y, 'ro')\nplt.plot(predicted)\nplt.show()\n","sub_path":"regression.py","file_name":"regression.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"279798991","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nExercício 1 item (f) da Lista 1 de Macroeconomia I (Parte 1) de 2021\r\n04/05/2021 - author: Fábio Nishida\r\n\"\"\"\r\n\r\n# Módulos a serem utilizados\r\nimport numpy as np # Módulo para trabalhar com matrizes\r\nimport matplotlib.pyplot as plt # Módulo para fazer gráficos\r\n\r\nbeta_2 = 0.95 # valor de beta_2 fixado\r\n\r\n# Criando e preenchendo matriz com beta_1 e t*\r\ntabela = np.zeros([18, 2]) # criando matriz de zeros 18 x 2 para preenchimento\r\n\r\n\r\n# Loop para preenchimento de possíveis \\beta_1 < \\beta_2 e t* para c1_t - c2_t\r\n# mudar de sinal (quando c2_t > 1, pois c2_t = 2 - c1_t, no equilíbrio)\r\nfor i in range(len(tabela)):\r\n tabela[i, 0] = beta_2 - (i + 1) * 0.05\r\n \r\n # Estabelecendo valores iniciais\r\n t = 0\r\n c2_t = -np.inf # valor arbitrário apenas para ser TRUE ao entrar no loop\r\n \r\n while c2_t < 1:\r\n # Como c1_t + c2_t = 2, só precisamos verificar se c2_t > 1 ou c1_t < 1\r\n c2_t = 2 / (1 + ((1 - tabela[i, 0]) / (1 - beta_2)) * (tabela[i, 0] / beta_2)**t)\r\n t += 1\r\n tabela[i, 1] = t\r\n\r\nprint(tabela)\r\n\r\n\r\n# Poderia ter usado linspace() do NumPy para preencher a 1ª coluna de uma vez\r\nexemplo = np.zeros((18, 2))\r\nexemplo[:, 0] = np.linspace(0.05, 0.90, 18)\r\nexemplo\r\n\r\n\r\n# Criação do gráfico\r\nfig, ax = plt.subplots() # Cria a base (em branco) do gráfico\r\nax.plot(tabela[:, 0], tabela[:, 1], # Coluna 0 no eixo x e coluna 1 no y\r\n '-o', # Formato da linha e ponto do gráfico\r\n label='$t^*(\\\\beta_1, \\\\beta_2)$') # Descrição da legenda\r\nax.legend() # Faz aparecer a legenda\r\nax.set_ylim([0, 15]) # tamanho mínimo e máximo vertical\r\nax.set_xlim([0.00, 0.95]) # tamanho mínimo e máximo horizontal\r\nax.set_xlabel('$\\\\beta_1$') # Descrição do eixo x\r\nax.set_ylabel('$t^*(\\\\beta_1, \\\\beta_2)$') # Descrição do eixo y\r\nax.set_title('Gráfico de $t^*(\\\\beta_1, \\\\beta_2)$ por $\\\\beta_1$') # Título\r\nplt.show() # Plot do gráfico com os comandos dados\r\n","sub_path":"Lista-1.py","file_name":"Lista-1.py","file_ext":"py","file_size_in_byte":1982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"40457768","text":"class TreeNode: #空节点也认为是BST\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n# 区间法------因为BST左孩子总是小于父节点,右孩子总是大于父节点,则从根节点开始,递归找到各个子节点,看各个子节点的取值是否在正确的区间内\nclass solution1(object):\n def isValidBST(self, root):\n if root == None:\n return False\n return self.dfs(root,float('-inf'),float('inf')) #初始化根节点的上下限为负无穷和正无穷\n \n def dfs(self,root,min_val,max_val): #left为当前节点的取值下限,right为当前节点的取值上线,入参:节点和区间\n if not root:\n return True #递归直到遍历到当前节点为空,即都是满足区间条件的,所以返回true。\n if root.val < min_val or root.val > max_val:\n return False\n #递归,做孩子的取值下限为min_val,上限为root.val-1,右孩子取值下限为root.val+1,上限为max_val\n return self.dfs(root.left,min_val,root.val-1) and self.dfs(root.right,root.val+1,max_val) \n\n\n# 中序遍历记录所有的节点到list,看list是否是单调递增即可\nclass solution2(object):\n def isValidBST(self,root): \n values = []\n values = self.inorderdfs(root,values)\n print(values)\n for i in range(len(values)-1):\n if values[i+1] <= values[i]:\n return False\n return True\n \n\n def inorderdfs(self,root,values):\n #中序遍历,把节点的value记录到list中\n if not root:\n return values\n else:\n self.inorderdfs(root.left,values) #继续找左孩子\n values.append(root.val)\n self.inorderdfs(root.right,values)\n return values\n\nif __name__ == \"__main__\":\n a,b,c,d,e = TreeNode(5),TreeNode(1),TreeNode(4),TreeNode(3),TreeNode(6)\n a.left = b\n a.right = c\n c.left = d\n c.right = e\n\n s1 = solution1()\n s2 = solution2()\n print(s1.isValidBST(a))\n print(s2.isValidBST(a))\n\n\n\n\n\n \n\n\n \n\n","sub_path":"树专题/判断一棵树是否是二叉搜索树/is_valid_bst.py","file_name":"is_valid_bst.py","file_ext":"py","file_size_in_byte":2240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"231154984","text":"from enemies import *\nfrom player import *\nfrom textread import *\nfrom fight import *\nfrom items import *\nfrom sounds import *\n\n####################### Main loop to play game ################\n\n\ndef straightMap(player):\n # townSquare(player)\n toDarkForest(player, forestBoss, \"Sword of Light\")\n\n toDesert(player, desertBoss, \"super potion\")\n toRuins(player, ruinsBoss, \"Boss Key\")\n toCastle(player, Ganon)\n\n\ndef townSquare(player):\n\n slowText(\"dialogues/townsquare.txt\")\n playsound(songs[\"townsquare\"])\n\n\ndef toDarkForest(player, boss, item):\n paths = {\n \"Currently\": \"Dark Forest\"\n }\n\n slowText(\"dialogues/darkforest.txt\")\n print(\"You are currently in the {}\".format(paths[\"Currently\"]))\n enemyfight = encounterEnemy(player, boss)\n\n if enemyfight:\n addItemToInvetory(player, item)\n\n\ndef toRuins(player, boss, item):\n paths = {\n \"Currently\": \"Dark Forest\"\n }\n print(\"you are currently in the {} . it looks like we can find the key to the castle here...\".format(\n paths[\"Currently\"]))\n slowText(\"dialogues/ruins.txt\")\n enemyfight = encounterEnemy(player, boss)\n\n if enemyfight:\n addItemToInvetory(player, item)\n\n\ndef toDesert(player, boss, item):\n paths = {\n \"Currently\": \"Dark Forest\"\n }\n\n slowText(\"dialogues/desert.txt\")\n\n enemyfight = encounterEnemy(player, boss)\n if enemyfight:\n addItemToInvetory(player, item)\n\n\n# 333\ndef toCastle(player, boss):\n playsound(songs[\"castle\"])\n slowText(\"dialogues/castle.txt\")\n\n if player.inventory[\"Boss Key\"]:\n print(\"You may proceed to the Castle\")\n\n paths = {\n\n \"Currently\": \"Castle\"\n }\n print(\"You are currently in the {}\".format(paths[\"Currently\"]))\n enemyfight = encounterEnemy(player, boss)\n\n if enemyfight:\n slowText(\"dialogues/victory.txt\")\n slowText(\"dialogues/endgame.txt\")\n\n else:\n print(\"Game Over\")\n\n else:\n print(\"You are not ready to proceed yet\")\n time.sleep(3)\n","sub_path":"gamemap.py","file_name":"gamemap.py","file_ext":"py","file_size_in_byte":2056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"380416637","text":"#!/usr/bin/env python3\nfrom typing import List, Tuple\nimport time\nimport copy\nimport sys\nsys.path.append(\"../\")\nimport readFile\n\n\nFILE = \"input.txt\"\n#FILE = \"test.txt\"\n\n\ndef countOccupiedSeats(elements: List[str]) -> int:\n ctr: int = 0\n for e in elements:\n if e == '#':\n ctr += 1\n return ctr\n\n\ndef findAdjacentIndices(i: int, j: int, m: int, n: int) -> List[Tuple[int, int]]:\n \"\"\"\n find adjacent indices of an element with position (i, j) in a m * n matrix \n \"\"\"\n adjacent_indices = []\n\n if i > 0:\n adjacent_indices.append((i-1, j))\n if i+1 < m:\n adjacent_indices.append((i+1, j))\n if j > 0:\n adjacent_indices.append((i, j-1))\n if j+1 < n:\n adjacent_indices.append((i, j+1))\n if i > 0 and j+1 < n:\n adjacent_indices.append((i-1, j+1))\n if i+1 < m and j > 0:\n adjacent_indices.append((i+1, j-1))\n if i > 0 and j > 0:\n adjacent_indices.append((i-1, j-1))\n if i+1 < m and j+1 < n:\n adjacent_indices.append((i+1, j+1))\n\n return adjacent_indices\n\n\ndef findAdjacentElements(neigbours: List[Tuple[int, int]], input: List[str]) -> List[str]:\n \"\"\" find adjacent elements of an element using the position of this elements\n \"\"\"\n\n adjacent_elements = []\n\n for i, j in neigbours:\n adjacent_elements.append(input[i][j])\n\n return adjacent_elements\n\n\ndef processPart1(input):\n\n copyOfInput = copy.deepcopy(input)\n\n m = len(input)\n n = len(input[0])\n\n changesCtr = 0\n for i in range(m):\n for j in range(n):\n e = input[i][j]\n indexOfNeighbours = findAdjacentIndices(i, j, m, n)\n neighbours = findAdjacentElements(indexOfNeighbours, input)\n if e == 'L' and countOccupiedSeats(neighbours) == 0:\n copyOfInput[i][j] = '#'\n changesCtr += 1\n if e == '#' and countOccupiedSeats(neighbours) >= 4:\n copyOfInput[i][j] = 'L'\n changesCtr += 1\n return changesCtr, copyOfInput\n\n\ndef findFirstSeenSeats(x, y: int, input: List[str]) -> list[str]:\n\n # actual position (y,x)\n\n firstSeanSeats = []\n x_max = len(input[0])\n y_max = len(input)\n\n for i in range(x+1, x_max): # x.......\n if input[y][i] != '.':\n firstSeanSeats.append(input[y][i])\n break\n for i in reversed(range(0, x)): # .....x\n if input[y][i] != '.':\n firstSeanSeats.append(input[y][i])\n break\n for i in reversed(range(0, y)): # .\n if input[i][x] != '.': # x\n firstSeanSeats.append(input[i][x])\n break\n for i in range(y+1, y_max): # x\n if input[i][x] != '.': # .\n firstSeanSeats.append(input[i][x])\n break\n for i, j in zip(reversed(range(0, y)), reversed(range(0, x))):\n if input[i][j] != '.':\n firstSeanSeats.append(input[i][j])\n break\n for i, j in zip(range(y+1, y_max), range(x+1, x_max)):\n if input[i][j] != '.':\n firstSeanSeats.append(input[i][j])\n break\n for i, j in zip(reversed(range(0, y)), range(x+1, x_max)):\n if input[i][j] != '.':\n firstSeanSeats.append(input[i][j])\n break\n for i, j in zip(range(y+1, y_max), reversed(range(0, x))):\n if input[i][j] != '.':\n firstSeanSeats.append(input[i][j])\n break\n\n return firstSeanSeats\n\ndef processPart2(input: List[str]) -> Tuple[int, List[str]]:\n copyOfInput = copy.deepcopy(input)\n m = len(input)\n n = len(input[0])\n\n changesCtr : int = 0\n for i in range(m):\n for j in range(n):\n e = input[i][j]\n if e == '.':\n copyOfInput[i][j] = e\n continue\n neighbours = findFirstSeenSeats(j,i,input)\n if e == 'L' and countOccupiedSeats(neighbours) == 0:\n copyOfInput[i][j] = '#'\n changesCtr += 1\n elif e == '#' and countOccupiedSeats(neighbours) >= 5:\n copyOfInput[i][j] = 'L'\n changesCtr += 1\n else:\n copyOfInput[i][j] = e\n return changesCtr, copyOfInput\n\n# this function read the file as list of strings\ninput = readFile.readFile(FILE)\n\n# change the list of strings to the list of lists (two dimensional list)\nfor i in range(len(input)):\n input[i] = list(input[i])\n\n\n######part1############\ntic = time.perf_counter()\n\nchanges, newInput = processPart1(input)\n\nwhile changes != 0:\n changes, newInput = processPart1(newInput)\n\nnumberOfOccupiedSeats = 0\n\nfor i in newInput:\n numberOfOccupiedSeats += countOccupiedSeats(i)\n\ntoc = time.perf_counter()\n\nprint()\nprint(\"######## Day 8 #########\")\nprint()\nprint(\"Part1: How many seats end up occupied? \", numberOfOccupiedSeats)\nprint(f\"This task took {toc - tic:0.4f} seconds\")\nprint()\n\n#################### part 2 #####################\ntic = time.perf_counter()\n\nnumberOfChanges, newSeatLayout = processPart2(input)\nwhile numberOfChanges != 0:\n numberOfChanges, newSeatLayout = processPart2(newSeatLayout)\n\nnumberOfOccupiedSeats = 0\n\nfor i in newSeatLayout:\n numberOfOccupiedSeats += countOccupiedSeats(i)\n\ntoc = time.perf_counter()\n\nprint()\nprint(\"######## Day 8 #########\")\nprint()\nprint(\"Part2: How many seats end up occupied? \", numberOfOccupiedSeats)\nprint(f\"This task took {toc - tic:0.4f} seconds\")\nprint()\n","sub_path":"11/day11.py","file_name":"day11.py","file_ext":"py","file_size_in_byte":5436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"580752984","text":"import ctypes\n\n# define a Array Type size 5\nArrayType = ctypes.py_object * 5\n\n# instance a array\nslots = ArrayType()\n\n# access a un-initialized arrary\n\ntry:\n\tprint (slots[0])\nexcept ValueError as e:\n\tprint (e)\n\n#initial the array\n\nfor i in range(5):\n\tslots[i]=None\n\tprint (\"{0}:{1}\".format(i,slots[i]))\n\ntry:\n\tprint (slots[0])\nexcept ValueError as e:\n\tprint (e)\n\n# setter by index\nslots[3] = 'a'\nslots[4] = 4\n\n# getter by index\nfor i in range(5):\n\tprint (\"{0}:{1}\".format(i,slots[i]))\n\n\n# visit index out of range\ntry:\n\tslots[7]=7\nexcept IndexError as e:\n\tprint (e)\n\n\n\n\n","sub_path":"DataStructuresandAlgorithmsUsingPython/c02/hardware-array.py","file_name":"hardware-array.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"377202708","text":"def do_turn(game):\n pirates = game.all_my_pirates()\n captains = [pirates[0],pirates[3],pirates[5]]\n isldes = []\n if len(game.not_my_islands()) == 0:\n return\n island = game.not_my_islands()\n i=0\n a = False\n b = False\n if pirates[0].is_lost:\n if not pirates[1].is_lost:\n captains[0]=pirates[1]\n game.set_sail(pirates[2], game.get_directions(pirates[2],pirates[1])[0])\n elif not pirates[2].is_lost:\n captains[0]=pirates[2]\n else:\n a = True\n else:\n game.set_sail(pirates[1], game.get_directions(pirates[1],pirates[0])[0])\n game.set_sail(pirates[2], game.get_directions(pirates[2],pirates[1])[0])\n if pirates[3].is_lost:\n if not pirates[4].is_lost:\n captains[1]=pirates[4]\n else:\n b = True\n else:\n game.set_sail(pirates[4], game.get_directions(pirates[4],pirates[3])[0])\n game.debug(pirates)\n if pirates[5].is_lost:\n captains.remove(pirates[5])\n if b == True:\n captains.remove(pirates[3])\n if a == True:\n captains.remove(pirates[0])\n for captain in captains: \n if i > len(game.not_my_islands())-1:\n i = 0\n game.debug(\"going to island \" + str(island[i].id))\n isla = [game.distance(captain,island[0]),island[0]]\n for isl in island:\n if game.distance(captain,isl) V[num_pos-1][x]:\n V[num_pos-1][x] = p.value\n Who[num_pos-1][x] = p\n \n for pos in range(num_pos-2,-1,-1):\n for x in range(budget+1):\n null_player = player()\n # V[pos][x] = V[pos+1][x] # not taking a player. we will try initializing to -inf\n V[pos][x] = 0\n Who[pos][x] = null_player\n\n # If it traces back the current lineup correctly the first time it should do it after that\n\n for p in players[pos]:\n currentTeams = {}\n currentLineup = []\n amount = x - p.cost\n for i in range(pos+1,num_pos):\n k = Who[i][amount]\n if type(k) != int:\n if k.id != None:\n if k.team in currentTeams:\n currentTeams[k.team] += 1\n else:\n currentTeams[k.team] = 1\n currentLineup.append(k.name)\n amount = amount - k.cost\n \n if p.cost <= x and (V[pos+1][x-p.cost] + p.value >= V[pos][x]) and (p.name not in currentLineup): # and currentTeams[p.team] < 4\n if pos != 0:\n if x - p.cost < 10:\n continue\n V[pos][x] = V[pos+1][x-p.cost] + p.value\n Who[pos][x] = p\n\n return Who\n\n# multiple lineups\ndef optimizeMultiple(players,budget,entries):\n \"\"\"\n Returns multiple optimized lineups for either fanduel or draftkings. This function\n is provided arguments for player data, budget, and the number of entries desired.\n This function can handle up to 20 entries pretty well. It can be easily run through\n its wrapper function multipleOptimizer()\n \"\"\"\n\n num_pos = len(players)\n lineups = []\n flineups = []\n for g in range(0,entries):\n # shuffle(players)\n V = np.zeros((num_pos, budget+1)) # array to track max vorp\n Who = np.zeros((num_pos, budget+1), dtype=object) # array to recreate hires\n for x in range(budget+1):\n V[num_pos-1][x] = 0\n Who[num_pos-1][x] = player()\n \n for p in players[num_pos-1]:\n # retrieve relevant players\n if p.cost <= x and p.value > V[num_pos-1][x]:\n V[num_pos-1][x] = p.value\n Who[num_pos-1][x] = p\n \n for pos in range(num_pos-2,-1,-1):\n for x in range(budget+1):\n null_player = player()\n # V[pos][x] = V[pos+1][x] # not taking a player. we will try initializing to -inf\n V[pos][x] = 0\n Who[pos][x] = null_player\n\n # If it traces back the current lineup correctly the first time it should do it after that\n\n for p in players[pos]:\n currentLineup = []\n amount = x - p.cost\n for i in range(pos+1,num_pos):\n k = Who[i][amount]\n if type(k) != int:\n if k.id != None:\n currentLineup.append(k.name)\n amount = amount - k.cost\n \n if p.cost <= x and (V[pos+1][x-p.cost] + p.value >= V[pos][x]) and (p.name not in currentLineup):\n tempCur = [p.name] + currentLineup\n masterCopy = 0\n fmasterCopy = 0\n if pos != 0:\n if x - p.cost < 10:\n continue\n if g > 0:\n if pos == 5:\n for s in lineups:\n diff = False\n for k in tempCur:\n if k not in s:\n diff = True\n if diff:\n masterCopy+=1\n if masterCopy == len(lineups):\n\n V[pos][x] = V[pos+1][x-p.cost] + p.value\n Who[pos][x] = p\n elif pos == 0:\n for s in flineups:\n diff = False\n for k in tempCur:\n if k not in s:\n diff = True\n if diff:\n fmasterCopy+=1\n if fmasterCopy == len(flineups):\n V[pos][x] = V[pos+1][x-p.cost] + p.value\n Who[pos][x] = p\n\n else:\n V[pos][x] = V[pos+1][x-p.cost] + p.value\n Who[pos][x] = p\n else:\n V[pos][x] = V[pos+1][x-p.cost] + p.value\n Who[pos][x] = p\n \n names = set()\n fnames=set()\n print('-----------')\n newLineup = getLineup(Who,[],output=True)\n for p in range(4,len(newLineup)):\n names.add(newLineup[p].name)\n\n lineups.append(names)\n for p in range(0,len(newLineup)):\n fnames.add(newLineup[p].name)\n flineups.append(fnames)\n\n\ndef getLineup(Who, lockedPlayers, output=False):\n \"\"\"\n Takes a 2-D array containing the solution to the Knapsack dynamic programming problem. Returns \n a list containing the hired player objects, and optionally prints.\n \"\"\"\n num_pos, budget = Who.shape\n budget -= 1 # modify since array is 1 larger than budget\n amount = budget\n points = 0\n lineup = []\n lockFlag = False\n\n if lockedPlayers != None and lockedPlayers != []:\n lockFlag = True\n\n for i in range(num_pos):\n player = None\n\n if lockFlag: # check if player already locked for this position, if so hire\n for p in lockedPlayers:\n if i == p[1]: # player locked for this position\n player = p[0] # hire\n\n if player is None: # if no player locked for this position, hire according to alg\n player = Who[i][amount]\n \n if player.id != None:\n if output: print(\"sign player \" + str(player.name) + \" for position\", i, \"who is projected for \" + str(player.value))\n amount -= player.cost\n points += player.value\n lineup.append(player)\n\n if output:\n print(\"total money spent is \" + str((budget - amount)*100))\n print(\"total projected points: \" + str(points))\n \n return lineup\n\n# Scrape\ndef scrapeNumFD():\n \"\"\"\n Retrieves player projection data from NumberFire for FanDuel contests. \n Returns 2-D array contains player objects with relevant attributes filled.\n \"\"\"\n \n url = 'https://www.numberfire.com/nba/daily-fantasy/daily-basketball-projections'\n response = requests.get(url)\n soup = BeautifulSoup(response.text, \"html.parser\")\n prices = soup.findAll('td', attrs={'class':'cost'})\n names = soup.findAll('a', attrs={'class':'full'})\n teams = soup.findAll('span', attrs={'class':'team-player__team active'})\n proj = soup.findAll('td', attrs={'class':'fp active'})\n positions = soup.findAll('span', attrs={'class':'player-info--position'})\n # gtd = soup.findAll('span', attrs={'class':'team-player__injury player-gtd'})\n data = [[],[],[],[],[]]\n\n for i in range(0,len(prices)):\n price = int(int(re.sub('[^0-9]','', prices[i].text))/100)\n value = float(proj[i].text.strip())\n\n if(\"PG\" in positions[i].text):\n data[0].append(player(value,price,i,names[i].text.strip(),teams[i].text.strip()))\n elif(\"SG\" in positions[i].text):\n data[1].append(player(value,price,i,names[i].text.strip(),teams[i].text.strip()))\n elif(\"SF\" in positions[i].text):\n data[2].append(player(value,price,i,names[i].text.strip(),teams[i].text.strip()))\n elif(\"PF\" in positions[i].text):\n data[3].append(player(value,price,i,names[i].text.strip(),teams[i].text.strip()))\n elif(\"C\" in positions[i].text):\n data[4].append(player(value,price,i,names[i].text.strip(),teams[i].text.strip()))\n\n return data\n\n# Baseball scraping\ndef scrapeBaseFD():\n \"\"\"\n Retrieves player projection data from NumberFire for FanDuel contests. \n Returns 2-D array contains player objects with relevant attributes filled.\n \"\"\"\n urlp = 'https://www.numberfire.com/mlb/daily-fantasy/daily-baseball-projections/pitchers'\n urlh = 'https://www.numberfire.com/mlb/daily-fantasy/daily-baseball-projections/batters'\n response = requests.get(urlh)\n soup = BeautifulSoup(response.text, \"html.parser\")\n prices = soup.findAll('td', attrs={'class':'cost'})\n names = soup.findAll('a', attrs={'class':'full'})\n proj = soup.findAll('td', attrs={'class':'fp active'})\n positions = soup.findAll('span', attrs={'class':'player-info--position'})\n # gtd = soup.findAll('span', attrs={'class':'team-player__injury player-gtd'})\n\n\n data = [[],[],[],[],[],[],[],[],[]]\n\n for i in range(0,len(prices)):\n price = int(int(re.sub('[^0-9]','', prices[i].text))/100)\n value = float(proj[i].text.strip())\n # print(names[i])\n\n if(\"C\" in positions[i].text or \"1B\" in positions[i].text):\n data[0].append(player(value,price,i,names[i].text.strip()))\n elif(\"2B\" in positions[i].text):\n data[1].append(player(value,price,i,names[i].text.strip()))\n elif(\"3B\" in positions[i].text):\n data[2].append(player(value,price,i,names[i].text.strip()))\n elif(\"SS\" in positions[i].text):\n data[3].append(player(value,price,i,names[i].text.strip()))\n elif(\"OF\" in positions[i].text):\n data[4].append(player(value,price,i,names[i].text.strip()))\n data[5].append(player(value,price,i,names[i].text.strip()))\n\n # Pitchers\n response = requests.get(urlp)\n soup = BeautifulSoup(response.text, \"html.parser\")\n prices = soup.findAll('td', attrs={'class':'cost'})\n names = soup.findAll('a', attrs={'class':'full'})\n proj = soup.findAll('td', attrs={'class':'fp active'})\n positions = soup.findAll('span', attrs={'class':'player-info--position'})\n\n for i in range(0,len(prices)):\n price = int(int(re.sub('[^0-9]','', prices[i].text))/100)\n value = float(proj[i].text.strip())\n\n data[6].append(player(value,price,i,names[i].text.strip()))\n\n data2 = [data[0],data[1],data[2],data[3],data[4],data[4],data[4],data[5],data[6]]\n return data2\n\ndef scrapeGrindFD():\n \"\"\"\n Retrieves player projection data from RotoGrinders for FanDuel contests. \n Returns 2-D array contains player objects with relevant attributes filled.\n \"\"\"\n #auto change by day\n url = 'https://rotogrinders.com/lineups/nba?date=' + CUR_DATE + '&site=fanduel'\n teamDict = scrapeTeams()\n response = requests.get(url)\n soup = BeautifulSoup(response.text, \"html.parser\")\n pts = soup.find_all('span',attrs={'class':'fpts'})\n names = soup.find_all('a',attrs={'class':'player-popup'})\n salary = soup.find_all('span',attrs={'class':'salary'})\n positions = soup.find_all('span',attrs={'class':'position'})\n\n data = [[],[],[],[],[]]\n\n for i in range(0,len(salary)):\n price = int(float(salary[i].text.replace('$','').replace('K',''))*10)\n value = float(pts[i].text.strip())\n team = 'placeholder' #teamDict[names[i].text.strip()]\n if(\"PG\" in positions[i].text):\n data[0].append(player(value,price,i,names[i].text.strip(),team))\n elif(\"SG\" in positions[i].text):\n data[1].append(player(value,price,i,names[i].text.strip(),team))\n elif(\"SF\" in positions[i].text):\n data[2].append(player(value,price,i,names[i].text.strip(),team))\n elif(\"PF\" in positions[i].text):\n data[3].append(player(value,price,i,names[i].text.strip(),team))\n elif(\"C\" in positions[i].text):\n data[4].append(player(value,price,i,names[i].text.strip(),team))\n\n return data\n\ndef scrapeGrindDK():\n \"\"\"\n Retrieves player projection data from RotoGrinders for FanDuel contests. \n Returns 2-D array contains player objects with relevant attributes filled.\n \"\"\"\n #auto change by day\n url = 'https://rotogrinders.com/lineups/nba?date=' + CUR_DATE + '&site=draftkings'\n teamDict = scrapeTeams()\n\n response = requests.get(url)\n soup = BeautifulSoup(response.text, \"html.parser\")\n pts = soup.find_all('span',attrs={'class':'fpts'})\n names = soup.find_all('a',attrs={'class':'player-popup'})\n salary = soup.find_all('span',attrs={'class':'salary'})\n positions = soup.find_all('span',attrs={'class':'position'})\n\n data = [[],[],[],[],[],[],[],[]]\n\n for i in range(0,len(salary)):\n if(not str.isdigit(salary[i].text.strip().replace('$','').replace('K','').replace('.',''))):\n # print(str.isdigit(salary[i].text.strip().replace('$','').replace('K','').replace('.','')))\n continue\n price = int(float(salary[i].text.replace('$','').replace('K',''))*10)\n value = float(pts[i].text.strip())\n team = 'placeholder' # teamDict[names[i].text.strip()]\n \n if(\"PG\" in positions[i].text):\n data[0].append(player(value,price,i,names[i].text.strip(),team))\n if(\"SG\" in positions[i].text):\n data[1].append(player(value,price,i,names[i].text.strip(),team))\n if(\"SF\" in positions[i].text):\n data[2].append(player(value,price,i,names[i].text.strip(),team))\n if(\"PF\" in positions[i].text):\n data[3].append(player(value,price,i,names[i].text.strip(),team))\n if(\"C\" in positions[i].text):\n data[4].append(player(value,price,i,names[i].text.strip(),team))\n # Guard\n if(\"PG\" in positions[i].text or \"SG\" in positions[i].text):\n data[5].append(player(value,price,i,names[i].text.strip(),team))\n # Forward\n if(\"SF\" in positions[i].text or \"PF\" in positions[i].text):\n data[6].append(player(value,price,i,names[i].text.strip(),team))\n\n # Util\n data[7].append(player(value,price,i,names[i].text.strip(),team))\n\n return data\n\n\ndef dropLock(data, dropPlayers, lockPlayers):\n \"\"\"\n Checks the user has entered valid input for dropping and locking players.\n Returns an array with two elements - the first is the list of locked player objects, and the second is \n the full list of players with dropped/locked players removed\n \"\"\"\n # check user hasn't locked and dropped the same player\n commonPlayers = dropPlayers.intersection(lockPlayers)\n if commonPlayers != set():\n print('Error: You cannot lock and drop the same player(s).\\nPlease remove the following player(s) from your lock/drop list:')\n for player in commonPlayers:\n print('-' + player)\n return\n \n # check players exist, find locked players and drop players\n newLockPlayers = lockPlayers.copy()\n newDropPlayers = dropPlayers.copy()\n lockObjs = []\n lockPos = []\n newData = data.copy()\n numEltsRemoved = 0\n for i in range(len(data)):\n for player in data[i]:\n if player.name in newLockPlayers: # save lock player objects\n lockObjs.append((player, i))\n lockPos.append(i)\n newLockPlayers.remove(player.name)\n # newData.pop(i-numEltsRemoved)\n numEltsRemoved += 1\n \n elif player.name in dropPlayers: # drop players\n newData[i].remove(player)\n newDropPlayers.remove(player.name)\n\n # check user hasn't supplied invalid player names\n if len(newLockPlayers) > 0 or len(newDropPlayers) > 0:\n print('Error: Unable to find the following player(s) in your drop/lock list:')\n for player in newLockPlayers:\n print('-' + player)\n for player in newDropPlayers:\n print('-' + player)\n print('Please revise and resubmit.')\n return\n\n # check user hasn't locked more than two players for the same position\n for i in lockPos:\n if (i < 4 and lockPos.count(i) > 2) or (i == 4 and lockPos.count(i) > 1):\n print('You have locked too many players for the same position. Please revise and resubmit.')\n return\n\n return [lockObjs, newData]\n\ndef formatPlayersFD(players):\n \"\"\"\n Takes in a raw 2-D array of player objects by position and formats them for FanDuel contests.\n In other words, it duplicates all but the last of the inner lists, maintaining order.\n Original array: [['PG'], ['SG'], ['SF'], ['PF'], ['C']]\n Output array: [['PG'], ['PG'], ['SG'], ['SG'], ['SF'], ['SF'], ['PF'], ['PF'], ['C']]\n \"\"\"\n playersNew = []\n for i in range(4):\n playersNew.append(players[i])\n playersNew.append(players[i])\n playersNew.append(players[4])\n return playersNew\n\n# \n\ndef scrapeTeams():\n \"\"\"\n Creates a dictionary\n \"\"\" \n url = 'https://www.numberfire.com/nba/daily-fantasy/daily-basketball-projections'\n response = requests.get(url)\n soup = BeautifulSoup(response.text, \"html.parser\")\n teams = soup.findAll('span', attrs={'class':'team-player__team active'})\n names = soup.findAll('a', attrs={'class':'full'})\n\n teamDict = {}\n\n for i in range(0,len(teams)):\n name = names[i].text.strip()\n if name.count(' ') == 2:\n firstSpace = name.find(' ')\n secondSpace = name.find(' ',firstSpace+1)\n name = name[0:secondSpace]\n teamDict[name] = teams[i].text.strip()\n return teamDict\n\n\ndef fanduelOptimizer(system,lockPlayers, dropPlayers):\n \"\"\"\n Wrapper function for optimized fanduel lineups. \n Takes in a string argument for projection system, a set of players to lock\n and a set of players to lock. Outputs optimized fanduel lineup.\n\n \"\"\"\n\n if system != \"rotogrinders\" and system != \"numberfire\":\n print(\"Error: 'System' arg must be either 'rotogrinders' or 'numberfire'\")\n return\n if system == \"numberfire\":\n numberFireRawFD = scrapeNumFD() # scrape data\n if len(numberFireRawFD[0]) == 0:\n print('Error: There are no games today. Please come back later.')\n return\n numberFireFD = formatPlayersFD(numberFireRawFD) # format scraped data for optimizer\n\n x = dropLock(numberFireFD, dropPlayers, lockPlayers) # lock/drop players\n if x != None:\n [lockedPlayers, numberFireFD] = x\n print('-----------\\nOptimized Fanduel lineup for NumberFire:')\n solnNumFD = optimize(numberFireFD, 600) # optimize lineup\n getLineup(solnNumFD, lockedPlayers, output=True)\n if system == \"rotogrinders\":\n grindersRawFD = scrapeGrindFD() # scrape data\n grindersFD = formatPlayersFD(grindersRawFD) # format scraped data for optimizer\n print(len(grindersFD))\n x = dropLock(grindersFD, dropPlayers, lockPlayers) # lock/drop players\n if x != None:\n [lockedPlayers, grindersFD] = x\n print('-----------\\nOptimized Fanduel lineup for RotoGrinders:')\n solnNumFD = optimize(grindersFD, 600) # optimize lineup\n getLineup(solnNumFD, lockedPlayers, output=True)\n\n\ndef draftkingsOptimizer(system, lockPlayers, dropPlayers):\n \"\"\"\n Wrapper function for optimized basketball draftkings lineups. \n Takes in a string argument for projection system, a set of players to lock\n and a set of players to lock. Outputs optimized draftkings lineup.\n\n \"\"\"\n\n if system != \"rotogrinders\":\n print(\"Error: 'System' arg must be 'rotogrinders'. Unfortunately NumberFire projections are not supported for this function yet.\")\n return\n if system == \"rotogrinders\":\n grindersDK = scrapeGrindDK() # scrape data\n\n x = dropLock(grindersDK, dropPlayers, lockPlayers) # lock/drop players\n if x != None:\n [lockedPlayers, grindersDK] = x\n print('-----------\\nOptimized DraftKings lineup for RotoGrinders:')\n solnGrindersDK = optimize(grindersDK, 500) # optimize lineup\n getLineup(solnGrindersDK, lockedPlayers, output=True)\n\ndef baseballOptimizer(lockPlayers, dropPlayers):\n \"\"\"\n Wrapper function for optimized baseball fanduel function. Function\n takes projections from numberfire.com. Function also takes inputs of sets\n for locking and dropping players.\n \"\"\"\n numBase = scrapeBaseFD()\n x = dropLock(numBase, dropPlayers, lockPlayers) # lock/drop players\n if x != None:\n [lockedPlayers, numBase] = x\n print('-----------\\nOptimized FanDuel lineup for DraftKings:')\n solnBaseFD = optimize(numBase, 350) # optimize lineup\n getLineup(solnBaseFD, lockedPlayers, output=True)\n\n\ndef multipleOptimizer(contest, system, entries):\n \"\"\"\n Wrapper function for generating multiple lineups for basketball. Takes \n arguments specifying contest platform, projection system, and number of lineups\n to be generated.\n \"\"\"\n\n if contest != \"draftkings\" and contest != \"fanduel\":\n print(\"Error: 'contest' arg must be either 'draftkings' or 'fanduel'\")\n return\n if system != \"rotogrinders\" and system != \"numberfire\":\n print(\"Error: 'System' arg must be either 'rotogrinders' or 'numberfire'\")\n return\n if contest == \"draftkings\":\n if system == \"numberfire\":\n print(\"Only RotoGrinders projections are available for DraftKings optimzation.\")\n grindersDK = scrapeGrindDK()\n print('-----------\\nOptimized DraftKings lineups for rotoGrinders:')\n optimizeMultiple(grindersDK, 500, entries)\n if contest == \"fanduel\":\n if system == 'numberfire':\n grindersRawFD = scrapeNumFD()\n print('-----------\\nOptimized Fanduel lineups for numberfire:')\n if system == 'rotogrinders':\n grindersRawFD = scrapeGrindFD()\n grindersFD = formatPlayersFD(grindersRawFD)\n print('-----------\\nOptimized Fanduel lineups for rotoGrinders:')\n optimizeMultiple(grindersFD, 600, entries)\n\n\n# won't work because of rotogrinders\n# def captainShowdownOptimizer():\n# lockPlayers = set()\n# dropPlayers = set()\n# slateData = scrapeGrindDK()\n# # for slate in slateData:\n# # x = dropLock(slate, dropPlayers, lockPlayers) # lock/drop players\n# # if x != None:\n# # [lockedPlayers, grindersFD] = x\n# solnDKCaptain = optimizeDKshowdown(slateData,500)\n# getLineup(solnDKCaptain, [], output=True)\n\n# Optimize Captain Showdown\n# def optimizeDKshowdown(data,cost):\n# captains = []\n\n# for p in data[7]:\n# captains.append(player(int(p.value*1.5),int(p.cost*1.5),p.id,p.name))\n\n# showdownData = [captains,data[7],data[7],data[7],data[7],data[7]]\n# return optimizeDK(showdownData,500)\n\n\n# def rotoPrices():\n# url = 'https://rotogrinders.com/projected-stats/nba-player?site=draftkings&sport=nba'\n\n# response = requests.get(url)\n# soup = BeautifulSoup(response.text, \"html.parser\")\n# outerDiv = soup.find_all('div',attrs={'class':'rgt-col'})\n# prices = outerDiv[1].find_all('div')\n# print(prices[0])\n\n# def testAlg():\n# url = 'https://rotogrinders.com/lineups/nba?date=' + CUR_DATE + '&site=fanduel'\n\n# response = requests.get(url)\n# soup = BeautifulSoup(response.text, \"html.parser\")\n# #prices = soup.findAll('td', attrs={'class':'cost'})\n# pts = soup.find_all('span',attrs={'class':'fpts actual'})\n# names = soup.find_all('a',attrs={'class':'player-popup'})\n# salary = soup.find_all('span',attrs={'class':'salary'})\n# positions = soup.find_all('span',attrs={'class':'position'})\n\n# data = [[],[],[],[],[]]\n\n# for i in range(0,len(salary)):\n\n# if(i == 10 or i == 122): # wut\n# continue\n# price = int(float(salary[i].text.replace('$','').replace('K',''))*1000)\n# value = float(pts[i].text.strip())\n# if(\"PG\" in positions[i].text):\n# data[0].append(player(value,price,i,names[i].text.strip()))\n# elif(\"SG\" in positions[i].text):\n# data[1].append(player(value,price,i,names[i].text.strip()))\n# elif(\"SF\" in positions[i].text):\n# data[2].append(player(value,price,i,names[i].text.strip()))\n# elif(\"PF\" in positions[i].text):\n# data[3].append(player(value,price,i,names[i].text.strip()))\n# elif(\"C\" in positions[i].text):\n# data[4].append(player(value,price,i,names[i].text.strip()))\n\n# data2 = [data[1],data[0],data[0],data[2],data[2],data[3],data[3],data[4]]\n# optimize(data2, 56500)\n# def optimizeFD(players, budget): DEPRECATED\n# \"\"\"\n# Generates the optimal lineup for FanDuel based on player projections.\n\n# Inputs:\n# players: 2-D array containing player objects for each player by position\n# budget: amount of money to spend on players\n# \"\"\"\n \n# num_pos = len(players)\n \n# V = np.zeros((num_pos, budget+1)) # array to track max vorp\n# Who = np.zeros((num_pos, budget+1), dtype=object) # array to recreate hires\n\n# for x in range(budget+1):\n# V[num_pos-1][x] = float(\"-inf\")\n# Who[num_pos-1][x] = player()\n \n# for p in players[num_pos-1]:\n# # retrieve relevant players\n# if p.cost <= x and p.value > V[num_pos-1][x]:\n# V[num_pos-1][x] = p.value\n# Who[num_pos-1][x] = p\n \n# for pos in range(num_pos-2,-1,-1):\n# for x in range(budget+1):\n# null_player = player()\n# # V[pos][x] = V[pos+1][x] # not taking a player. we will try initializing to -inf\n# V[pos][x] = float(\"-inf\")\n# Who[pos][x] = null_player\n \n# for p in players[pos]:\n# if p.cost <= x and V[pos+1][x-p.cost] + p.value > V[pos][x] and p != Who[pos+1][x-p.cost]:\n# V[pos][x] = V[pos+1][x-p.cost] + p.value\n# Who[pos][x] = p\n\n# return Who\n","sub_path":"Knapsack.py","file_name":"Knapsack.py","file_ext":"py","file_size_in_byte":27615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"15022938","text":"from django.views.generic import TemplateView\nfrom rest_framework.views import APIView\n\nfrom .functions import *\nfrom .models import *\nfrom .serializers import TaskSerializer\nfrom .tasks import find_words\n\n\n# Create your views here.\nclass FormView(TemplateView):\n template_name = 'form.html'\n\n\nclass FormApiView(APIView):\n def post(self, request):\n f = request.FILES.get('links')\n if not f:\n return Response({'error': \"please add file with links\"},\n status=status.HTTP_404_NOT_FOUND)\n links = \"\"\n for line in f:\n links += \" \" + line\n f.close()\n links = normalize_query(links)\n words = normalize_query(request.data.get('words', None))\n if len(words) == 0:\n return Response({'error': \"please write words\"},\n status=status.HTTP_404_NOT_FOUND)\n validate = validate_websites(links)\n if validate[0]:\n return Response({'error': \"please write proper links \" + validate[1]},\n status=status.HTTP_404_NOT_FOUND)\n user = User.objects.get_or_create(name=request.data.get('username', None))\n task = Task.objects.create(owner=user[0], status=2)\n for website in links:\n website = Website.objects.create(url=website, task=task, status=2)\n for word in words:\n Word.objects.create(name=word, website=website)\n find_words.delay(links, words, task.pk)\n return Response({'done': 1})\n\n\nclass StatusApiView(APIView):\n def get(self, request):\n username = request.GET.get('name')\n user = User.objects.get(name=username)\n task_queryset = Task.objects.filter(owner=user)\n serializer = TaskSerializer(task_queryset, many=True)\n return Response({'username': username,\n 'tasks': serializer.data\n })\n","sub_path":"searcher/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"250239717","text":"from typing import Union\n\nimport streamlit as st\nimport xarray as xr\nimport pandas as pd\nimport matplotlib\nmatplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\nfrom src.scenario import plot_scenario\n\ndef scenario_label(value):\n scenario_relation = {\n 3.5:'Base',\n 4.5:'Pesimista',\n 1.5:'Optimista',\n 1.75:'Fuerte',\n 2.625:'Moderada',\n }\n return scenario_relation[value]\n\nst.title('Predicción del modelo SEAIR de la evolución de COVID-19 en Jalisco')\n\npopulation = st.sidebar.slider(\n label=\"Población\",\n min_value=800000,\n max_value=10000000,\n value=4200000,\n step=100000,\n)\n\nro = st.sidebar.selectbox(\n label=\"Escenario de Propagación por #quedateencasa\",\n options=[3.5, 4.5, 1.5, 1.75, 2.625],\n format_func=scenario_label,\n)\n\ninitial_cases = st.sidebar.slider(\n label=\"Casos Iniciales\",\n min_value=-0,\n max_value=70,\n value=32,\n step=1,\n)\n\nnumber_of_deaths = st.sidebar.slider(\n label=\"Muertes Reportadas\",\n min_value=-0,\n max_value=10,\n value=0,\n step=1,\n)\n\nrecovered = st.sidebar.slider(\n label=\"Casos Recuperados\",\n min_value=-0,\n max_value=10,\n value=0,\n step=1,\n)\n\nstart_day, end_day = st.sidebar.slider(\n 'Dias con intervención',\n 1, 119, (10, 50)\n)\nduration_days = end_day-start_day\n\n\ninitial_conditions = {\n 'initial_cases':initial_cases,\n 'exposed_per_case': 4,\n 'deaths': number_of_deaths, # No Muertos,\n 'recovered': recovered,\n}\n\nif st.sidebar.button(\"Generar\"):\n st.markdown(f\"Población: {population:.1f}\")\n st.markdown(f\"Ro: {ro:.1f}\")\n fig = plot_scenario(\n population,\n initial_conditions,\n ro,\n start_intervention=start_day,\n intervention_duration =duration_days\n )\n st.plotly_chart(fig)\nelse:\n st.markdown(\n \"Selecciona la localización usando los controles Y pulsa en \"\n \"el botón 'Generar'.\"\n )\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"50127176","text":"def maxProfit3(prices): ## n^2\n sellPrice = 0\n for i, x in enumerate(prices):\n for j, y in enumerate(prices[i + 1:]):\n print('array', prices[i+1:], ' x =', x, ' y - x =', y-x)\n if y - x > sellPrice: sellPrice = y - x\n if sellPrice < 0: return 0\n return sellPrice\n\n\ndef maxProfit2(prices): ## n^2\n sellPrice = 0\n for i, x in enumerate(prices):\n if i == len(prices) - 1: break\n sum = max(prices[i + 1:]) - x\n if sum > sellPrice: sellPrice = sum\n return sellPrice\n\ndef maxProfit(prices): ## linear time\n if len(prices) == 0: return 0\n min = prices[0]\n sellPrice = 0\n for x in prices:\n if x <= min: min = x\n else:\n if x - min > sellPrice:\n sellPrice = x - min\n return sellPrice\n\ntest1 = [7,1,5,3,6,4]\ntest2 = [7,6,5,2,1]\ntest3 = []\nprint(maxProfit(test1))\nprint(maxProfit(test2))\nprint(maxProfit(test3))\n","sub_path":"121.BestTimeToBuyStocks.py","file_name":"121.BestTimeToBuyStocks.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"365678804","text":"import operator\nimport mock\n\nimport pytest\n\nfrom descarteslabs.common.graft.interpreter import interpret\nfrom descarteslabs.workflows.types import Function, Int\nfrom .. import ifelse\n\n\ndef test_same_types():\n with pytest.raises(TypeError, match=\"must be the same type\"):\n ifelse(True, 1, \"foo\")\n\n\ndef test_shared_outer_scope():\n shared = Function[{}, Int](\"func\")()\n\n result = ifelse(shared > 0, shared + 1, shared - 1)\n assert isinstance(result, Int)\n\n func_result = 10\n calls = 0\n\n def func():\n nonlocal calls\n calls += 1\n return func_result\n\n interpreted = interpret(\n result.graft,\n builtins={\n \"func\": func,\n \"wf.ifelse\": lambda cond, t, f: t() if cond else f(),\n \"wf.numpy.add\": operator.add,\n \"wf.numpy.subtract\": operator.sub,\n \"wf.numpy.greater\": operator.gt,\n },\n )()\n\n assert interpreted == func_result + 1\n assert calls == 1\n\n\ndef test_short_circuit():\n func1 = Function[{}, Int](\"func1\")\n func2 = Function[{}, Int](\"func2\")\n\n result = ifelse(True, func1(), func2())\n assert isinstance(result, Int)\n\n func1_mock = mock.Mock(return_value=1)\n func2_mock = mock.Mock(return_value=2)\n interpreted = interpret(\n result.graft,\n builtins={\n \"func1\": func1_mock,\n \"func2\": func2_mock,\n \"wf.ifelse\": lambda cond, t, f: t() if cond else f(),\n },\n )()\n\n assert interpreted == 1\n func1_mock.assert_called_once()\n func2_mock.assert_not_called()\n","sub_path":"descarteslabs/workflows/types/conditional/tests/test_conditional.py","file_name":"test_conditional.py","file_ext":"py","file_size_in_byte":1568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"378383960","text":"# Copyright (c) 2014, The MITRE Corporation. All rights reserved.\r\n# See LICENSE.txt for complete terms.\r\n\r\nfrom StringIO import StringIO\r\nimport unittest\r\n\r\nfrom stix.incident import Incident\r\nimport stix.bindings.incident as incident_binding\r\nfrom cybox.common import StructuredText\r\nfrom cybox.test import EntityTestCase\r\n\r\nINCIDENT_CATEGORIES = \"\"\"\r\n\r\n \r\n Foo\r\n Bar\r\n \r\n\r\n\"\"\"\r\n\r\n\r\nclass IncidentTest(EntityTestCase, unittest.TestCase):\r\n klass = Incident\r\n _full_dict = {'attributed_threat_actors': {'scope': 'exclusive',\r\n 'threat_actors': [{'threat_actor': {'description': 'A Threat Actor Description',\r\n 'id': 'example:threatactor-1',\r\n 'sophistications': [{'value': {\"value\" : \"Novice\", \r\n \"xsi:type\" : \"stixVocabs:ThreatActorSophisticationVocab-1.0\"}}],\r\n 'title': 'A Threat Actor',\r\n 'version': '1.1'}}]},\r\n 'categories': [{'value': 'Unauthorized Access',\r\n 'xsi:type': 'stixVocabs:IncidentCategoryVocab-1.0'},\r\n {'value': 'Improper Usage',\r\n 'xsi:type': 'stixVocabs:IncidentCategoryVocab-1.0'}],\r\n'coa_taken': [{'course_of_action': {'timestamp': '2014-05-05T14:50:25.992383+00:00', 'version': '1.1', 'id': 'example:coa-74e50620-7536-4fcd-94db-a6889f75e098'}},\r\n {'course_of_action': {'timestamp': '2014-05-05T14:50:25.992384+00:00', 'version': '1.1', 'id': 'example:coa-74e50620-7536-4fcd-94db-a6889f75e099'}}],\r\n'coordinators': [{'description': \"Mr. Evil's enemy\",\r\n 'identity': {'name': 'Ms. Coordinator'}}],\r\n 'description': 'The Datacenter was broken into.',\r\n 'external_ids': [{'source': 'some source',\r\n 'value': '478392-feb3ca-98a9ef-984392742'}],\r\n 'impact_assessment': {'direct_impact_summary': {'asset_losses': {'value': 'Minor',\r\n 'xsi:type': 'stixVocabs:ImpactRatingVocab-1.0'},\r\n 'business_mission_disruption': {'value': 'Major',\r\n 'xsi:type': 'stixVocabs:ImpactRatingVocab-1.0'},\r\n 'response_and_recovery_costs': {'value': 'Moderate',\r\n 'xsi:type': 'stixVocabs:ImpactRatingVocab-1.0'}},\r\n 'effects': [{'value': 'User Data Loss',\r\n 'xsi:type': 'stixVocabs:IncidentEffectVocab-1.0'},\r\n {'value': 'Data Breach or Compromise',\r\n 'xsi:type': 'stixVocabs:IncidentEffectVocab-1.0'}],\r\n 'impact_qualification': {'value': 'Catastrophic',\r\n 'xsi:type': 'stixVocabs:ImpactQualificationVocab-1.0'},\r\n 'indirect_impact_summary': {'brand_and_market_damage': {'value': 'No',\r\n 'xsi:type': 'stixVocabs:SecurityCompromiseVocab-1.0'},\r\n 'increased_operating_costs': {'value': 'No',\r\n 'xsi:type': 'stixVocabs:SecurityCompromiseVocab-1.0'},\r\n 'legal_and_regulatory_costs': {'value': 'Unknown',\r\n 'xsi:type': 'stixVocabs:SecurityCompromiseVocab-1.0'},\r\n 'loss_of_competitive_advantage': {'value': 'Yes',\r\n 'xsi:type': 'stixVocabs:SecurityCompromiseVocab-1.0'}},\r\n 'total_loss_estimation': {'actual_total_loss_estimation': {'amount': '50.45',\r\n 'iso_currency_code': 'USD'},\r\n 'initial_reported_total_loss_estimation': {'amount': '99.99',\r\n 'iso_currency_code': 'USD'}}},\r\n 'leveraged_ttps': {'scope': 'inclusive',\r\n 'ttps': [{'confidence': {'value': {'value': 'Medium',\r\n 'xsi:type': 'stixVocabs:HighMediumLowVocab-1.0'}},\r\n 'ttp': {'id': 'example:TTP-1',\r\n 'version': '1.1'}}]},\r\n 'related_indicators': {'indicators': [{'indicator': {'description': 'An indicator containing a File observable with an associated hash',\r\n 'id': 'example:indicator-1ae45e9c-9b0b-11e3-ada0-28cfe912ced6',\r\n 'observable': {'id': 'example:Observable-fdaa7cec-f8be-494d-b83f-575f6f018666',\r\n 'object': {'id': 'example:File-ec52e6bc-2d7e-44e2-911b-468bb775a5c6',\r\n 'properties': {'hashes': [{'simple_hash_value': u'4EC0027BEF4D7E1786A04D021FA8A67F',\r\n 'type': u'MD5'}],\r\n 'xsi:type': 'FileObjectType'}}},\r\n 'producer': {'description': '',\r\n 'identity': {'id': 'example:Identity-1ae603ab-9b0b-11e3-980e-28cfe912ced8',\r\n 'specification': {'party_name': {'name_lines': [{'value': 'Foo'},\r\n {'value': 'Bar'}],\r\n 'person_names': [{'name_elements': [{'value': 'John Smith'}]},\r\n {'name_elements': [{'value': 'Jill Smith'}]}]}},\r\n 'xsi:type': 'ciqIdentity:CIQIdentity3.0InstanceType'},\r\n 'time': {'produced_time': '2014-02-21T10:16:14.947201'}},\r\n 'title': 'File Hash Example',\r\n 'version': '2.1.1'}}],\r\n 'scope': 'exclusive'},\r\n 'reporter': {'description': \"Mr. Evil's enemy\",\r\n 'identity': {'name': 'Ms. Good'}},\r\n 'responders': [{'description': \"Mr. Evil's enemy\",\r\n 'identity': {'name': 'Ms. Responder'}}],\r\n 'time': {'containment_achieved': '2005-02-21T10:25:10.894398',\r\n 'first_data_exfiltration': '2002-02-21T10:25:10.894398',\r\n 'first_malicious_action': '2000-02-21T10:25:10.894398',\r\n 'incident_closed': '2008-02-21T10:25:10.894398',\r\n 'incident_discovery': '2003-02-21T10:25:10.894398',\r\n 'incident_opened': '2004-02-21T10:25:10.894398',\r\n 'incident_reported': '2007-02-21T10:25:10.894398',\r\n 'initial_compromise': '2001-02-21T10:25:10.894398',\r\n 'restoration_achieved': '2006-02-21T10:25:10.894398'},\r\n 'title': 'Datacenter Compromise',\r\n 'version': '1.1',\r\n 'victims': [{'name': 'John Smith'},\r\n {'id': 'example:Identity-1ae603ab-9b0b-11e3-980e-28cfe912ced6'}],\r\n 'information_source': {\r\n 'description': \"Mr. Evil's enemy\",\r\n 'identity': {\r\n 'name': \"Ms. Good\",\r\n },\r\n },\r\n'security_compromise': {\"value\": \"Suspected\", \"xsi:type\":\"stixVocabs:SecurityCompromiseVocab-1.0\"}}\r\n\r\n\r\n def test_parse_category(self):\r\n incident = incident_binding.parseString(INCIDENT_CATEGORIES)\r\n self.assertTrue(incident is not None)\r\n self.assertEqual(2, len(incident.Categories.Category))\r\n\r\n categories = incident.Categories.Category\r\n self.assertEqual('Foo', categories[0].valueOf_)\r\n self.assertEqual('Bar', categories[1].valueOf_)\r\n\r\n def test_description_output(self):\r\n incident = incident_binding.IncidentType()\r\n\r\n assets = incident_binding.AffectedAssetsType()\r\n asset = incident_binding.AffectedAssetType()\r\n\r\n description = StructuredText(\"A Description\")\r\n asset.set_Structured_Description(description.to_obj())\r\n\r\n assets.add_Affected_Asset(asset)\r\n incident.set_Affected_Assets(assets)\r\n\r\n s = StringIO()\r\n\r\n incident.export(s, 0, {'http://stix.mitre.org/Incident-1': 'incident'})\r\n xml = s.getvalue()\r\n self.assertTrue(\"A Description\" in xml, \"Description not exported\")\r\n\r\nif __name__ == \"__main__\":\r\n unittest.main()\r\n","sub_path":"stix-1.1.1.0/stix/test/incident_test.py","file_name":"incident_test.py","file_ext":"py","file_size_in_byte":10040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"628381915","text":"import pytest\nfrom kaggle_environments import make\nfrom agent import agent\nfrom simple_agent import agent as simple_agent\nimport subprocess\nimport sys\nimport os\nimport getpass\nimport json\n\n\"\"\"\n[WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'rp 0 0' <- research points (player id, num)\n[WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'rp 1 0'\n[WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'r coal 0 3 419' <- resource (type, x, y, amount)\n[WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'r wood 0 9 314'\n[WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'r uranium 6 10 331'\n[WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'u 0 0 u_1 13 7 0 0 0 0' <- unit (type, team, id, x, y, cooldown, wood, coal, uranium)\n[WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'u 0 1 u_2 13 16 0 0 0 0'\n[WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'c 0 c_1 0 23' <- city (team, id, fuel, lightupkeep)\n[WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'c 1 c_2 0 23'\n[WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'ct 0 c_1 13 7 0' <- citytile (team, id, x, y, cooldown)\n[WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'ct 1 c_2 13 16 0'\n[WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'ccd 13 7 6' <- road (x, y, level)\n[WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'ccd 13 16 6'\n[WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'D_DONE'\n\"\"\"\n\nclass TestNoRandomness:\n\n @pytest.mark.skip(reason=\"takes too long\")\n @pytest.mark.skipif(getpass.getuser() != 'Paul', reason=\"requires Paul's computer for non-randomness\")\n @pytest.mark.parametrize(\"seed\", [\n 183985976,\n # 69420, 562124210, 812865753, 759738969, 94876192\n ])\n def test_no_randomness_using_file(self, reset_agent_state, seed):\n\n for ind in range(3):\n try:\n subprocess.run(\n ['lux-ai-2021', f'--seed={seed}', 'dev\\\\main.py', 'simple\\\\main.py']\n + [f'--out=C:\\\\Users\\\\Paul\\\\OneDrive\\\\LuxAIReplays\\\\debug\\\\replay_{ind}-{seed}.json'],\n cwd='C:\\\\Users\\\\Paul\\\\PycharmProjects\\\\Lux-Design-2021\\\\kits\\\\python',\n shell=True\n )\n\n except subprocess.CalledProcessError as err:\n print(\n 'Failed to run algos',\n file=sys.stderr\n )\n raise err\n\n with open(f'C:\\\\Users\\\\Paul\\\\OneDrive\\\\LuxAIReplays\\\\debug\\\\replay_0-{seed}.json') as fh:\n data0 = json.load(fh)\n\n with open(f'C:\\\\Users\\\\Paul\\\\OneDrive\\\\LuxAIReplays\\\\debug\\\\replay_1-{seed}.json') as fh:\n data1 = json.load(fh)\n\n with open(f'C:\\\\Users\\\\Paul\\\\OneDrive\\\\LuxAIReplays\\\\debug\\\\replay_2-{seed}.json') as fh:\n data2 = json.load(fh)\n\n for ind, (l1, l2) in enumerate(zip(data0['allCommands'], data1['allCommands'])):\n for d in l1:\n assert any(d == x for x in l2), f\"Turn {ind}, seed {seed}, {d} not in {l2}. First list: {l1}\"\n\n for ind, (l1, l2) in enumerate(zip(data0['allCommands'], data2['allCommands'])):\n for d in l1:\n assert any(d == x for x in l2), f\"Turn {ind}, seed {seed}, {d} not in {l2}. First list: {l1}\"\n\n for ind, (l1, l2) in enumerate(zip(data1['allCommands'], data2['allCommands'])):\n for d in l1:\n assert any(d == x for x in l2), f\"Turn {ind}, seed {seed}, {d} not in {l2}. First list: {l1}\"\n\n os.remove(f'C:\\\\Users\\\\Paul\\\\OneDrive\\\\LuxAIReplays\\\\debug\\\\replay_0-{seed}.json')\n os.remove(f'C:\\\\Users\\\\Paul\\\\OneDrive\\\\LuxAIReplays\\\\debug\\\\replay_1-{seed}.json')\n os.remove(f'C:\\\\Users\\\\Paul\\\\OneDrive\\\\LuxAIReplays\\\\debug\\\\replay_2-{seed}.json')\n\n @pytest.mark.skip(reason=\"takes too long\")\n @pytest.mark.parametrize(\"seed, min_score\", [\n (69420, 20), # could be as high as 26\n # (183985976, 10),\n ])\n def test_min_city_tiles(self, reset_agent_state, seed, min_score):\n\n conf = {\n \"loglevel\": 2,\n \"annotations\": True\n }\n\n if seed is not None:\n conf['seed'] = seed\n\n reset_agent_state()\n env = make(\"lux_ai_2021\", configuration=conf, debug=True)\n out = env.run([agent, simple_agent])\n\n assert sum('ct 0' in x for x in out[-1][0]['observation']['updates']) >= min_score\n # for x in out[-1][0]['observation']['updates']:\n # if 'ct 0' in x:\n # print(x)\n\n @pytest.mark.skip(reason=\"does not test for randomness from CLI\")\n def test_no_randomness(self, reset_agent_state):\n seed = 69420 # 562124210 # 812865753 # 759738969 # 94876192 # None\n\n conf = {\n \"loglevel\": 2,\n \"annotations\": True\n }\n\n if seed is not None:\n conf['seed'] = seed\n\n ground_truth_actions = []\n\n reset_agent_state()\n env = make(\"lux_ai_2021\", configuration=conf, debug=True)\n step_info, __ = env.reset(2)\n while step_info['status'] != 'DONE':\n actions_1 = agent(step_info['observation'], None, include_debug_for_vis=False)\n ground_truth_actions.append(actions_1)\n step_info['observation'].player = step_info['observation']['player'] = 1\n actions_2 = simple_agent(step_info['observation'], None)\n step_info, __ = env.step([actions_1, actions_2])\n\n for __ in range(5):\n reset_agent_state()\n env = make(\"lux_ai_2021\", configuration=conf, debug=True)\n step_info, __ = env.reset(2)\n ind = 0\n while step_info['status'] != 'DONE':\n actions_1 = agent(step_info['observation'], None, include_debug_for_vis=False)\n assert set(ground_truth_actions[ind]) == set(actions_1)\n step_info['observation'].player = step_info['observation']['player'] = 1\n actions_2 = simple_agent(step_info['observation'], None)\n step_info, __ = env.step([actions_1, actions_2])\n ind += 1\n\n\n\n\n","sub_path":"kits/python/dev/tests/test_no_randomness.py","file_name":"test_no_randomness.py","file_ext":"py","file_size_in_byte":6212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"187342468","text":"\"\"\"Service data access layer (dal).\"\"\"\nimport os\nimport json\nimport logging\nfrom copy import copy\nfrom pathlib import Path\n\n\n# Logging setup\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n\n\n# Module classes\nclass Project:\n \"\"\"Service Project class.\n\n This class acts as an interface for the local file store. Its primary\n function is to load and return the resources associated with the\n project.\n\n Attributes\n ----------\n resources : dict{str:dict}\n A dictionary of all resources that are available to the project.\n These will be available as a dictionary with the filenames as the keys\n and the contents of the json documents as the bodies.\n\n \"\"\"\n\n # Instance attributes\n @property\n def resources(self) -> dict:\n \"\"\"Return copy of read-only _resources attribute.\"\"\"\n return copy(self._resources)\n\n def __init__(self):\n # Set project root\n self.root = Path(__file__).parent.parent\n\n # Load all associated resources\n self._resources = {}\n resources_path = self.root / 'resources'\n for root, _, files in os.walk(resources_path):\n for file in files:\n # Skip all non-json documents\n if '.json' not in file:\n logger.warning(\n 'Service has received a non-valid json document: %s.',\n file,\n )\n continue\n # Load resources and save into internal _resources attribute\n name, resources = self._load_resource(root, file)\n self._resources[name] = resources\n\n # Instance methods\n def _load_resource(self, root: str, file: str):\n \"\"\"Load given file as resource.\"\"\"\n path = os.path.join(root, file)\n roots, ext = self._parse_roots_ext(root, file)\n name = '.'.join(roots)\n\n logger.debug(\n 'Processing resource %s at %s.',\n '.'.join([name, ext]),\n path,\n )\n\n # Load resource\n resources = []\n try:\n with open(path) as rules:\n resources.extend(json.load(rules))\n except Exception as error: # pylint: disable = broad-except\n logger.error(\n 'Service could not load %s due to %s',\n str(path),\n str(error),\n )\n return name, resources\n\n def _parse_roots_ext(self, path, file):\n \"\"\"Parse given file for name and qualified extension.\"\"\"\n paths = str(path).replace(str(self.root), '').split('/')\n name, *exts = file.split('.')\n ext = '.'.join(exts) or ''\n\n paths.append(name)\n\n if len(paths) >= 2:\n paths = paths[1:]\n #paths.remove('resources') # The line above ^ already removed this for me\n return paths, ext\n\n return None, None\n","sub_path":"service/dal.py","file_name":"dal.py","file_ext":"py","file_size_in_byte":2922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"647533958","text":"from django.db import models\nfrom django.utils import timezone\nfrom django.utils.http import urlquote\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.core.mail import send_mail\nfrom django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin\nfrom WRIST import settings\n\nRELATIONSHIP_ACCPTED = 1\nRELATIONSHIP_DENIED = 2\nRELATIONSHIP_PENDING = 3\nRELATIONSHIP_STATUSES = (\n (RELATIONSHIP_ACCPTED, 'Accepted'),\n (RELATIONSHIP_DENIED, 'Denied'),\n (RELATIONSHIP_PENDING, 'Pending'),\n )\n\nNONE = 'NA'\nCA = 'CA'\nWA = 'WA'\nSTATE_CHOISES = (\n (NONE, '--'),\n (CA, 'California'),\n (WA, 'Washington'),\n )\n\nclass UserProfileManager(BaseUserManager):\n def create_user(self, email, uid, password=None):\n \"\"\"\n Creates and saves a User with the given email and password.\n \"\"\"\n now = timezone.now()\n if not email:\n raise ValueError('Users must have an email address')\n email = self.normalize_email(email)\n if not uid:\n raise ValueError('The given UID must be set')\n uid = uid\n\n user = self.model(email=email, uid=uid)\n user.set_password(password)\n user.save(using=self._db)\n return user\n\n def create_superuser(self, email, uid, password):\n user = self.create_user(email, uid, password)\n user.is_admin = True\n user.save(using=self._db)\n return user\n\nclass UserProfile(AbstractBaseUser):\n # Required fields\n email = models.EmailField(verbose_name='email address',\n max_length=255,\n unique=True)\n uid = models.CharField(max_length=16, unique=True)\n \n # Basic info\n first_name = models.CharField(max_length=16, blank=True)\n last_name = models.CharField(max_length=16, blank=True)\n phone_number = models.CharField(max_length=15, blank=True)\n\n # Gender\n NONE = 'NA'\n MALE = 'MA'\n FEMALE = 'FE'\n GENDER_CHOICES = (\n (NONE, \"None\"),\n (MALE, \"Male\"),\n (FEMALE, \"Female\"),\n )\n gender = models.CharField(max_length=2,\n choices=GENDER_CHOICES,\n default=NONE)\n\n\n # Location\n residence_city = models.CharField(max_length=32, blank=True)\n residence_state = models.CharField(max_length=2,\n choices=STATE_CHOISES,\n default=NONE)\n\n # Misc.\n bio = models.CharField(max_length=160, blank=True)\n contacts = models.ManyToManyField('self', \n through='Relationship',\n symmetrical=False, \n related_name='related_to')\n\n\n # Job fields\n job_title = models.CharField(max_length=32, blank=True)\n job_employer = models.CharField(max_length=32, blank=True)\n\n # Permissions\n is_active = models.BooleanField(default=True)\n is_admin = models.BooleanField(default=False)\n\n objects = UserProfileManager()\n\n USERNAME_FIELD = 'email'\n REQUIRED_FIELDS = ['uid']\n \n class Meta:\n verbose_name = _('user')\n verbose_name_plural = _('users')\n \n def get_full_name(self):\n # The user is identified by their email address\n return self.first_name + \" \" + self.last_name\n\n def get_short_name(self):\n # The user is identified by their email address\n return self.first_name\n\n def __str__(self):\n return self.email\n\n def has_perm(self, perm, obj=None):\n \"Does the user have a specific permission?\"\n # Simplest possible answer: Yes, always\n return True\n\n def has_module_perms(self, app_label):\n \"Does the user have permissions to view the app `app_label`?\"\n # Simplest possible answer: Yes, always\n return True\n\n @property\n def is_staff(self):\n \"Is the user a member of staff?\"\n # Simplest possible answer: All admins are staff\n return self.is_admin\n\n\n def create_relationship(self, contact, address, symm=True, **kwargs):\n relationship, create = Relationship.objects.get_or_create(from_user=self,\n to_user=contact)\n# address=address)\n relationship.address = address\n try:\n pair_relationship = Relationship.objects.get(from_user=contact,\n to_user=self)\n except Relationship.DoesNotExist:\n return relationship\n except Relationship.MultipleObjectsReturned:\n return pair_relationship[:1]\n if symm:\n relationship.status = RELATIONSHIP_ACCPTED \n relationship.save()\n pair_relationship.status = RELATIONSHIP_ACCPTED\n if not pair_relationship.address:\n pair_relationship.address = address\n pair_relationship.save()\n return relationship\n\n def remove_relationship(self, contact, status, symm=True):\n Relationship.objects.filter(\n from_user=self,\n to_user=contact,\n status=status).delete()\n if symm:\n contact.remove_relationship(self, status, False)\n\n def get_relationships(self):\n return Relationship.objects.filter(from_user=self,\n status=RELATIONSHIP_ACCPTED)\n def get_pending_relationships(self):\n return Relationship.objects.filter(to_user=self,\n status=RELATIONSHIP_PENDING)\n\n#class Location(models.Model):\n# name = models.CharField(max_length=128, blank=True)\n# address = models.CharField(max_length=256, blank=True)\n# latitude = models.DecimalField(max_digits=6, decimal_places=3)\n# longitude = models.DecimalField(max_digits=6, decimal_places=3)\n\n# def __unicode__(self):\n# return \"Location\"\n \nclass Relationship(models.Model):\n to_user = models.ForeignKey(UserProfile, related_name='from_users')\n from_user = models.ForeignKey(UserProfile, related_name='to_users')\n status = models.IntegerField(choices=RELATIONSHIP_STATUSES,\n default=RELATIONSHIP_PENDING)\n date_requested = models.DateField(auto_now_add=True)\n address = models.CharField(max_length=256, blank=True)\n \n# location = models.ForeignKey(Location, related_name='location')\n \n class Meta:\n verbose_name = _('relationship')\n verbose_name_plural = _('relationships')\n \n def __str__(self):\n return \"Contact request from \" + self.from_user.email + \" to \" + self.to_user.email\n\n\n","sub_path":"WRIST/account/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":6943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"512719339","text":"import sys\n\nif __name__ == '__main__':\n deque = []\n\n for i in range(int(sys.stdin.readline())):\n arr = sys.stdin.readline().split()\n if arr[0] == \"push_front\":\n deque.insert(0, int(arr[1]))\n elif arr[0] == \"push_back\":\n deque.append(int(arr[1]))\n elif arr[0] == \"pop_front\":\n if deque:\n print(deque.pop(0))\n else:\n print(-1)\n elif arr[0] == \"pop_back\":\n if deque:\n print(deque.pop())\n else:\n print(-1)\n elif arr[0] == \"size\":\n print(len(deque))\n elif arr[0] == \"empty\":\n if deque:\n print(0)\n else:\n print(1)\n elif arr[0] == \"front\":\n if deque:\n print(deque[0])\n else:\n print(-1)\n elif arr[0] == \"back\":\n if deque:\n print(deque[-1])\n else:\n print(-1)\n else:\n continue","sub_path":"boj/data_structure/deque/deque.py","file_name":"deque.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"505133469","text":"from django.contrib import admin\nfrom users import models as user_models\nfrom . import models\n\n\n@admin.register(models.Stats)\nclass StatsAdmin(admin.ModelAdmin):\n\n \"\"\" Stats Admin Definition \"\"\"\n\n list_display = (\n \"__str__\",\n \"pacer\",\n \"longTimeRun\",\n \"stepTest\",\n \"bendFoward\",\n \"totalFlexibility\",\n \"pushUp\",\n \"sitUp\",\n \"grip\",\n \"sprint\",\n \"longJump\",\n \"height\",\n \"weight\",\n \"bmi\",\n \"fat\",\n )\n\n fieldsets = (\n (\"Basic Info\", {\"fields\": (\"name\",)}),\n (\"Cardivascular Endurance\", {\"fields\": (\"pacer\", \"longTimeRun\", \"stepTest\",)}),\n (\"Flexibility\", {\"fields\": (\"bendFoward\", \"totalFlexibility\",)}),\n (\n \"Muscular Strength / Endurance\",\n {\"fields\": (\"pushUp\", \"sitUp\", \"grip\", \"sprint\", \"longJump\",)},\n ),\n (\"Body Fat Percentage\", {\"fields\": (\"height\", \"weight\", \"fat\",)}),\n )\n\n search_fields = (\"name__username\", \"name__school\", \"name__name\")\n\n # def cal_bmi(self, obj):\n # return round(obj.weight/((obj.height/100)**2), 2)\n\n # cal_bmi.short_description = \"BMI\"","sub_path":"stats/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"351475774","text":"from functools import partial\nfrom multiprocessing import cpu_count\nfrom multiprocessing.pool import ThreadPool\nfrom a00_common_functions import *\nfrom a01_neural_nets import *\n#from neural_nets.a00_augmentation_functions import *\nfrom a02_common_training_structures import *\n#from albumentations import *\nimport random\nfrom tensorflow import flags\nfrom multilabel_data_generator_ext_npzImage import * \nfrom keras.applications.inception_resnet_v2 import preprocess_input as inception_resnet_preprocess_input\nfrom keras.applications.xception import preprocess_input as xception_preprocess_input\nimport os \n\nFLAGS = flags.FLAGS\n\nif __name__ == '__main__':\n\n flags.DEFINE_integer(\"model_index\", 4, \n \"Model index\")\n\n flags.DEFINE_bool(\"train_new_model\", False,\n \"Whether to train model from scratch\")\n\n print(\"Using GPU device: \", (0,1))\n os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"0,1\"\n\n MODELS_PATH = MODELS_PATH.split('/')\n MODELS_PATH[-2] = 'model_' + str(FLAGS.model_index)\n MODELS_PATH = '/'.join(MODELS_PATH)\n\n if not os.path.isdir(MODELS_PATH):\n os.mkdir(MODELS_PATH)\n HISTORY_FOLDER_PATH = MODELS_PATH + \"history/\"\n\n print(\"Path for this training is: \", MODELS_PATH)\n\n\ndef process_single_item_npz(inp_file, data_path=None, box_size=299, name_ext='.jpg'):\n\n if data_path:\n f = data_path + inp_file + name_ext\n else:\n f = DATASET_PATH + inp_file + name_ext\n\n try:\n im_full_big = load_img_npz(f)\n except:\n im_full_big = np.zeros((box_size, box_size, 3), dtype=np.uint8)\n print(\"Unable to load this image: \", f)\n\n if im_full_big is None:\n im_full_big = np.zeros((box_size, box_size, 3), dtype=np.uint8)\n\n return im_full_big\n\n\ndef get_target(batch_files, image_classes):\n target = np.zeros((len(batch_files), 7178), dtype=np.float32)\n for i, b in enumerate(batch_files):\n for el in image_classes[b]:\n target[i, el] = image_classes[b][el]\n return target\n\n\ndef batch_generator_val(files, image_classes, batch_size, data_path=None):\n nn_shape = 299\n threads = 8\n\n # threads = 1\n p = ThreadPool(threads)\n process_item_func = partial(process_single_item_npz, data_path=data_path, box_size=nn_shape, name_ext='.npz')\n index = np.arange(0, files.shape[0])\n np.random.shuffle(index)\n\n start_index = 0\n while True:\n batch_index = index[start_index:start_index + batch_size]\n\n start_index += batch_size\n if start_index > len(files) - batch_size:\n start_index = 0\n\n batch_files = files[batch_index].copy()\n batch_target = get_target(batch_files, image_classes)\n batch_images = p.map(process_item_func, batch_files)\n batch_images = np.array(batch_images, np.float32)\n if 0:\n print(batch_images.shape, batch_target.shape)\n show_image(batch_images[0])\n print(batch_target[0], batch_target[0].sum())\n\n batch_images = xception_preprocess_input(batch_images)\n yield batch_images, batch_target\n\ndef prepare_val_images(val_images):\n train_path = DATASET_PATH+'train/'\n for img in val_images:\n if os.path.exists(train_path+img+'.jpg'):\n shutil.move(train_path+img+'.jpg', VAL_DATAPATH+img+'.jpg')\n \n num_val, num_train = len(os.listdir(VAL_DATAPATH)), len(os.listdir(train_path))\n\n print(\"\\ndone val images preparation. Numbers of train and val images are: {} {} \\n\".format(num_train, num_val))\n\ndef train_single_model(train_files, valid_files):\n import keras.backend as K\n from keras.callbacks import EarlyStopping, ModelCheckpoint, CSVLogger, ReduceLROnPlateau\n from keras.optimizers import Adam, SGD\n from keras.losses import mean_squared_error\n from keras.models import load_model\n import tensorflow as tf\n from keras.utils import multi_gpu_model\n\n image_classes = get_classes_for_images_dict()\n\n tuning_test_images, tuning_test_labels = get_tuning_labels_data_for_validation(299)\n\n gen = ImageDataGenerator(horizontal_flip = True,\n vertical_flip = True,\n width_shift_range = 0.1,\n height_shift_range = 0.1,\n channel_shift_range=0.1,\n shear_range = 0.1,\n zoom_range = 0.1, \n rotation_range = 10, \n preprocessing_function=xception_preprocess_input)\n\n #restore = 1\n patience = 50\n epochs = 1000\n optim_type = 'Adam'\n learning_rate = 0.001\n cnn_type = 'new_xception'\n #num_gpus = 2\n print('Creating and compiling {}...'.format(cnn_type))\n print(\"Using {} gpus. \".format(2))\n val_data_path = '/home/ec2-user/.inclusive/train/val_images/'\n print(\"Num of val images: \", len(os.listdir(val_data_path)), '\\n')\n\n ##### Prepare the model #####\n #model = get_model_resnet50_336()\n #model = get_model_densenet()\n model = get_model_xception()\n if optim_type == 'SGD':\n optim = SGD(lr=learning_rate, decay=1e-6, momentum=0.9, nesterov=True)\n else:\n optim = Adam(lr=learning_rate)\n model = multi_gpu_model(model, gpus=2)\n model.compile(optimizer=optim, loss='binary_crossentropy', metrics=[f2beta_loss, fbeta])\n ##### Prepare the model #####\n\n cache_model_path = MODELS_PATH + '{}_temp.h5'.format(cnn_type)\n final_model_path = MODELS_PATH + '{}.h5'.format(cnn_type)\n if os.path.isfile(final_model_path):\n print('Model already exists {}.'.format(final_model_path))\n\n if FLAGS.train_new_model:\n if os.path.isdir(MODELS_PATH):\n print(\"Removing previous models if any. \")\n shutil.rmtree(MODELS_PATH)\n \n if not os.path.isdir(MODELS_PATH):\n os.mkdir(MODELS_PATH)\n if not os.path.isdir(HISTORY_FOLDER_PATH):\n os.mkdir(HISTORY_FOLDER_PATH)\n \n if not FLAGS.train_new_model:\n if os.path.isfile(final_model_path):\n print('Load model from last point: ', final_model_path)\n #model = load_model(final_model_path, custom_objects={'f2beta_loss': f2beta_loss, 'fbeta': fbeta})\n model.load_weights(final_model_path)\n else:\n print(\"\\nCouldn't find previously trained models. Exit. \")\n return 0\n else:\n print(\"\\nStarted to train new model. \\n\")\n\n np.random.seed(10)\n valid_files = np.random.choice(valid_files, 4000)\n print(valid_files[:4])\n\n print('Fitting model...')\n batch_size = 48\n print('Batch size: {}'.format(batch_size))\n steps_per_epoch = 96000 // batch_size\n validation_steps = len(valid_files) // (batch_size)\n print('Steps train: {}, Steps valid: {}'.format(steps_per_epoch, validation_steps))\n\n gen_flow = gen.flow_from_directory(DATASET_PATH, target_size=(299, 299), batch_size=batch_size, class_mode='multilabel', multilabel_classes=image_classes, n_class=7178)\n\n callbacks = [\n EarlyStopping(monitor='val_loss', patience=patience, verbose=1),\n MyModelCheckpoint(cache_model_path[:-7]+'latest.h5', monitor='val_fbeta', mode='max', save_weights_only=True, save_best_only=True, verbose=0),\n #MyModelCheckpoint(final_model_path, monitor='val_fbeta', mode='max', save_weights_only=True, save_best_only=True, verbose=1),\n # ModelCheckpoint(cache_model_path[:-3] + '_{epoch:02d}.h5', monitor='val_fbeta', mode='max', verbose=0),\n CSVLogger(HISTORY_FOLDER_PATH + 'history_{}_lr_{}_optim_{}.csv'.format(cnn_type,\n learning_rate,\n optim_type), append=True),\n ReduceLROnPlateau(monitor='val_loss', factor=0.9, patience=5, min_lr=1e-9, min_delta=0.00001, verbose=0, mode='min'),\n # CyclicLR(base_lr=0.0001, max_lr=0.001, step_size=1000)\n ModelCheckpoint_F2Score(cache_model_path[:-3] + '_byTestScore_{epoch:02d}.h5', save_best_only=True, save_weights_only=True, \n mode='max', patience=patience, verbose=0,\n validation_data=(tuning_test_images, tuning_test_labels)),\n ]\n history = model.fit_generator(generator=gen_flow,\n epochs=epochs,\n steps_per_epoch=steps_per_epoch,\n validation_data=batch_generator_val(np.array(list(valid_files)), image_classes, batch_size, val_data_path),\n validation_steps=validation_steps,\n verbose=2,\n max_queue_size=10,\n initial_epoch=0,\n callbacks=callbacks)\n\n min_loss = min(history.history['val_loss'])\n print('Minimum loss: {} [Ep: {}]'.format(min_loss, len(history.history['val_loss'])))\n #model.load_weights(cache_model_path)\n #model.save(final_model_path)\n now = datetime.datetime.now()\n filename = HISTORY_FOLDER_PATH + 'history_{}_{:.4f}_lr_{}_{}.csv'.format(cnn_type, min_loss, learning_rate, now.strftime(\"%Y-%m-%d-%H-%M\"))\n pd.DataFrame(history.history).to_csv(filename, index=False)\n save_history_figure(history, filename[:-4] + '.png')\n # del model\n # K.clear_session()\n return min_loss\n\ndef create_models_new_xception():\n train_files, valid_files = get_train_valid_split_of_files()\n print('Split files train:', len(train_files))\n print('Split files valid:', len(valid_files))\n prepare_val_images(valid_files)\n train_single_model(train_files, valid_files)\n\nif __name__ == '__main__':\n start_time = time.time()\n create_models_new_xception()\n print('Time: {:.0f} sec'.format(time.time() - start_time))\n\n","sub_path":"weimin_model_training/weimin_main_train_xception.py","file_name":"weimin_main_train_xception.py","file_ext":"py","file_size_in_byte":9850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"420013088","text":"__all__ = [\"CustomGetoptError\",\"custom_getopt\"]\n\nclass CustomGetoptError(Exception):\n opt = ''\n msg = ''\n def __init__(self, msg, opt=''):\n self.msg = msg\n self.opt = opt\n Exception.__init__(self, msg, opt)\n\n def __str__(self):\n return self.msg\n\ndef custom_getopt(args, shortopts):\n\n opts = []\n prog_args = []\n\n all_options_first = False\n\n while args:\n if args[0][:1] == '-' and args[0] != '-':\n opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:])\n else:\n if all_options_first:\n if len(args) != 1:\n raise CustomGetoptError('')\n prog_args += args\n break\n else:\n if len(prog_args) == 1:\n raise CustomGetoptError('')\n prog_args.append(args[0])\n args = args[1:]\n\n return opts, prog_args\n\ndef do_shorts(opts, optstring, shortopts, args):\n opt, optstring = optstring[0], optstring[1:]\n if short_has_arg(opt, shortopts):\n if optstring == '':\n if not args:\n raise CustomGetoptError('')\n optstring, args = args[0], args[1:]\n else:\n raise CustomGetoptError('')\n optarg, optstring = optstring, ''\n else:\n if optstring != '':\n raise CustomGetoptError('')\n optarg = ''\n opts.append(('-' + opt, optarg))\n return opts, args\n\ndef short_has_arg(opt, shortopts):\n for i in range(len(shortopts)):\n if opt == shortopts[i] != ':':\n return shortopts.startswith(':', i+1)\n raise CustomGetoptError('')\n","sub_path":"124/code/build/customgetopt.py","file_name":"customgetopt.py","file_ext":"py","file_size_in_byte":1652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"442270784","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.7-x86_64/egg/sisua/data/data_loader/pbmc8k.py\n# Compiled at: 2019-09-16 06:36:02\n# Size of source mod 2**32: 4457 bytes\nimport base64, os, pickle, shutil\nfrom io import BytesIO\nimport numpy as np\nfrom odin.fuel import Dataset\nfrom odin.utils import batching, ctext, get_file, select_path\nfrom odin.utils.crypto import decrypt_aes, md5_checksum\nfrom sisua.data.path import DOWNLOAD_DIR, PREPROCESSED_BASE_DIR\nfrom sisua.data.utils import remove_allzeros_columns, save_to_dataset\n_URL_LYMPHOID = b'aHR0cHM6Ly9zMy5hbWF6b25hd3MuY29tL2FpLWRhdGFzZXRzL3BibWM4a19seS5ucHo=\\n'\n_URL_MYELOID = b'aHR0cHM6Ly9zMy5hbWF6b25hd3MuY29tL2FpLWRhdGFzZXRzL3BibWM4a19teS5ucHo=\\n'\n_URL_PBMC8k = b'aHR0cHM6Ly9zMy5hbWF6b25hd3MuY29tL2FpLWRhdGFzZXRzL3BibWM4a19mdWxsLm5weg==\\n'\n\ndef read_PBMC8k(subset, override=False, verbose=False, filtered_genes=False):\n subset = str(subset).strip().lower()\n if subset not in ('ly', 'my', 'full'):\n raise ValueError(\"subset can only be 'ly'-lymphoid and 'my'-myeloid or 'full'\")\n download_path = os.path.join(DOWNLOAD_DIR, 'PBMC8k_%s_original' % subset)\n if not os.path.exists(download_path):\n os.mkdir(download_path)\n preprocessed_path = os.path.join(PREPROCESSED_BASE_DIR, 'PBMC8k_%s_preprocessed' % (subset + ('' if filtered_genes else 'full')))\n if override:\n if os.path.exists(preprocessed_path):\n shutil.rmtree(preprocessed_path)\n if not os.path.exists(preprocessed_path):\n os.mkdir(preprocessed_path)\n if not os.path.exists(os.path.join(preprocessed_path, 'X')):\n if subset == 'full':\n ly = read_PBMC8k('ly', override=override, filtered_genes=filtered_genes)\n my = read_PBMC8k('my', override=override, filtered_genes=filtered_genes)\n url = str(base64.decodebytes(_URL_PBMC8k), 'utf-8')\n base_name = os.path.basename(url)\n get_file(fname=base_name, origin=url,\n outdir=download_path,\n verbose=verbose)\n data = np.load(os.path.join(download_path, base_name))\n X = data['X']\n X_row = data['X_row']\n X_col = data['X_col'].tolist()\n y = data['y']\n y_col = data['y_col'].tolist()\n all_genes = set(ly['X_col'].tolist() + my['X_col'].tolist())\n all_genes = sorted([X_col.index(i) for i in all_genes])\n all_proteins = set(ly['y_col'].tolist() + my['y_col'].tolist())\n all_proteins = sorted([y_col.index(i) for i in all_proteins])\n X = X[:, all_genes]\n y = y[:, all_proteins]\n X_col = np.array(X_col)[all_genes]\n y_col = np.array(y_col)[all_proteins]\n cell_types = np.array(['ly' if i in ly['X_row'] else 'my' for i in X_row])\n else:\n url = str(base64.decodebytes(_URL_LYMPHOID if subset == 'ly' else _URL_MYELOID), 'utf-8')\n base_name = os.path.basename(url)\n get_file(fname=base_name, origin=url,\n outdir=download_path,\n verbose=verbose)\n data = np.load(os.path.join(download_path, base_name))\n X_row = data['X_row']\n y = data['y']\n y_col = data['y_col']\n if filtered_genes:\n X = data['X_filt']\n X_col = data['X_filt_col']\n else:\n X = data['X_full']\n X_col = data['X_full_col']\n cell_types = None\n X, X_col = remove_allzeros_columns(matrix=X, colname=X_col,\n print_log=verbose)\n assert X.shape == (len(X_row), len(X_col))\n assert len(X) == len(y)\n assert y.shape[1] == len(y_col)\n if cell_types is not None:\n with open(os.path.join(preprocessed_path, 'cell_types'), 'wb') as (f):\n pickle.dump(cell_types, f)\n save_to_dataset(preprocessed_path, X,\n X_col,\n y,\n y_col,\n rowname=X_row,\n print_log=verbose)\n ds = Dataset(preprocessed_path, read_only=True)\n return ds","sub_path":"pycfiles/sisua-0.4.4-py3.6/pbmc8k.cpython-36.py","file_name":"pbmc8k.cpython-36.py","file_ext":"py","file_size_in_byte":4196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"407446219","text":"import numpy as np\n\n\nclass FourierTransform:\n\n @staticmethod\n def fourier_transform(array: np.ndarray) -> np.ndarray:\n transformed = np.fft.fftn(array)\n fshift = np.fft.fftshift(transformed)\n return fshift\n\n @staticmethod\n def inv_fourier_transform(fshift: np.ndarray) -> np.ndarray:\n f_ishift = np.fft.ifftshift(fshift)\n img_back = np.fft.ifftn(f_ishift)\n return img_back\n","sub_path":"torchio/transforms/fourier.py","file_name":"fourier.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"354321243","text":"# import tensorflow as tf\n#\n# # hello=tf.constant('hi')\n# sess=tf.Session()\n# # print(sess.run(hello))\n# # print(str(sess.run(hello), encoding='utf-8'))\n#\n# # a=tf.constant(5)\n# # b=tf.constant(3)\n# # c=tf.multiply(a,b)\n# # d=tf.add(a,b)\n# # e=tf.add(c,d)\n# # print(sess.run(e))\n#\n# # a=tf.constant([5])\n# # b=tf.constant([3])\n# # c=tf.constant([2])\n# # d=a*b+c\n# # print(sess.run(d))\n#\n# inputdata=[1,2,3,4,5]\n# x=tf.placeholder(dtype=tf.float32)\n# w=tf.Variable([2], dtype=tf.float32)\n# sess.run(tf.global_variables_initializer())\n# y=w*x\n# res=sess.run(y,feed_dict={x:inputdata})\n# print(res)\n\n\nimport matplotlib.pyplot as plt\n\ndef costf(x,y,w):\n cost=0\n for i in range(len(x)):\n hx=w*x[i]\n cost+=(hx-y[i])**2\n return cost/len(x)\n\nx=[1,2,3]\ny=[1,2,3]\nw=10\n\nprint(costf(x,y,w))\nprint(costf(x,y,5))\n\nxx, yy = [],[]\nfor i in range(-50,50):\n w=i/10\n costv=costf(x,y,w)\n print(w,costv)\n xx.append(w)\n yy.append(costv)\n\nplt.plot(xx,yy)\nplt.plot(xx,yy,\"ro\")\nplt.show()\n\n","sub_path":"DL/Day02_tfTest1.py","file_name":"Day02_tfTest1.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"334639673","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.4 (62061)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.3-i386/egg/Products/slideshowfolder/Extensions/Install.py\n# Compiled at: 2008-06-02 02:45:55\nfrom Products.slideshowfolder.config import *\nfrom Products.CMFCore.utils import getToolByName\nfrom Products.slideshowfolder.Extensions.utils import restoreAllFolders\nfrom Products.slideshowfolder.Extensions.utils import removeAction\nfrom Products.slideshowfolder import HAS_PLONE30\n\ndef install(portal):\n \"\"\"Our install process is to import our Generic Setup profile and,\n if on Plone 2.5, install CMFonFive.\"\"\"\n if not HAS_PLONE30:\n qit = getToolByName(portal, 'portal_quickinstaller')\n products_to_install = ['CMFonFive']\n installable_products = [ x['id'] for x in qit.listInstallableProducts(skipInstalled=1) ]\n installed_products = [ x['id'] for x in qit.listInstalledProducts() ]\n for product in products_to_install:\n if product in installable_products:\n qit.installProduct(product)\n elif product not in installed_products:\n raise RuntimeError('Dependent product %s not available to install' % product)\n\n setup_tool = getToolByName(portal, 'portal_setup')\n if not HAS_PLONE30:\n original_context = setup_tool.getImportContextID()\n setup_tool.setImportContext('profile-slideshowfolder:default')\n feedback = setup_tool.runAllImportSteps()\n setup_tool.setImportContext(original_context)\n else:\n feedback = {}\n feedback.update(setup_tool.runAllImportStepsFromProfile('profile-slideshowfolder:default'))\n feedback.update(setup_tool.runAllImportStepsFromProfile('profile-slideshowfolder:plone3'))\n feedback = feedback['messages']\n gs_output = [ '%s: %s' % (k, feedback[k]) for k in feedback.keys() if feedback[k] ]\n return 'Ran Slideshow Folder import steps.: \\n %s' % ('\\n').join(gs_output)\n\n\ndef uninstall(portal, reinstall=False):\n \"\"\"CSS, js, and skin registration are all automatically undone for us.\n We just need to remove our skin layers and actions.\n \n We also do a relatively expensive traversal of all folders and \"unmake\" them\n if they are slideshow folders. If we're not reinstalling, that is.\n \"\"\"\n feedback = ''\n skinstool = getToolByName(portal, 'portal_skins')\n for skinName in skinstool.getSkinSelections():\n path = skinstool.getSkinPath(skinName)\n path = [ i.strip() for i in path.split(',') ]\n prev = len(path)\n for old_skin in ('slideshowfolder', 'slideshowjavascript'):\n if old_skin in path:\n path.remove(old_skin)\n\n if prev != len(path):\n path = (',').join(path)\n skinstool.addSkinSelection(skinName, path)\n\n feedback += 'Removed slideshow skin layers\\n'\n portal_actions = getToolByName(portal, 'portal_actions')\n actions_to_remove = ('unmakeSlideshow', 'makeSlideshow', 'slideshow_settings')\n for action in actions_to_remove:\n removeAction(action, portal_actions)\n\n feedback += 'Removed extraneous actions from portal_actions\\n'\n if not reinstall:\n feedback += restoreAllFolders(portal)\n return feedback","sub_path":"pycfiles/Products.slideshowfolder-4.0-py2.4/Install.py","file_name":"Install.py","file_ext":"py","file_size_in_byte":3328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"269657449","text":"import matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nconfusion = np.genfromtxt('normalized_confusion_matrix.txt', delimiter=',')\nconfusion=confusion/100;\nim = plt.matshow(confusion, cmap='jet')\nplt.xticks(np.arange(0,21), [\"background\", \"aeroplane\", \"bicycle\", \"bird\", \"boat\", \"bottle\", \"bus\", \"car\", \"cat\", \"chair\", \"cow\", \"diningtable\", \"dog\", \"horse\", \"motorbike\", \"person\", \"pottedplant\", \"sheep\", \"sofa\", \"train\", \"tvmonitor\"])\nplt.yticks(np.arange(0,21), [\"background\", \"aeroplane\", \"bicycle\", \"bird\", \"boat\", \"bottle\", \"bus\", \"car\", \"cat\", \"chair\", \"cow\", \"diningtable\", \"dog\", \"horse\", \"motorbike\", \"person\", \"pottedplant\", \"sheep\", \"sofa\", \"train\", \"tvmonitor\"])\nfor label in im.axes.xaxis.get_ticklabels():\n label.set_rotation(90)\nim.figure.show()\nplt.colorbar(im, fraction=0.046,pad=0.04)\nplt.show()\n","sub_path":"data/plotConfusion.py","file_name":"plotConfusion.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"605735440","text":"#!/usr/bin/env python\n\n\"\"\"\n Set up the python binding for our encryption library\n Created by Yicheng Luo on 8 June, 2016.\n on how to write the setup script, visit:\n https://docs.python.org/2/distutils/setupscript.html\n\"\"\"\n\nfrom setuptools import setup\nfrom setuptools.extension import Extension\nimport os\n\npackage = 'button_crypto'\nversion = '0.1'\n\nsetup(name=package,\n version=version,\n ext_modules=[Extension(name='crypto',\n sources=['crypto.cpp', 'chacha20_simple.c'],\n language='c++',\n extra_compile_args=['-std=c++11']\n )])\n","sub_path":"lib/crypto/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"44921342","text":"import sys,os\nimport re\nimport requests\nimport time\nfrom bs4 import BeautifulSoup\n\nproject_dir = '../deputat/deputat/'\n\nsys.path.append(project_dir)\nos.environ['DJANGO_SETTINGS_MODULE'] = 'settings'\nimport django\ndjango.setup()\n\nfrom lists.models import *\nfrom elect.models import *\n\ntest_id = ['http://council.gov.ru/structure/persons/1317/', ]\nsity_names = ['г.Москва', 'г.Санкт-Петербург', 'г.Севастополь', ]\n\ndef get_html(url):\n r = requests.get(url)\n return r.text\n\ndef get_links(url):\n soup = BeautifulSoup(url, 'lxml')\n list = []\n container = soup.find('div', class_='main__content_wrapper')\n blocks = container.find_all('a', class_='group__persons__item group__persons__item_with_photo')\n for item in blocks:\n list += ['http://council.gov.ru' + item['href'], ]\n return list\n\ndef get_page_data(html):\n soup = BeautifulSoup(html, 'lxml')\n\n name = soup.find('h2', class_='senators_title')\n\n person__description = soup.find('div', class_='person__description__grid')\n\n #description = soup.find('div', class_='person__additional_top')\n #if description:\n # description = description.text\n #else:\n description = \"\"\n\n img_container = soup.find('div', class_='content__in')\n try:\n image = soup.find('img', class_='person_img')\n image_src = image['src']\n except:\n image_src = None\n\n person_info = soup.find('div', class_='person_info_private')\n birthday = person_info.find_all('p')[0].text\n authorization = person_info.find_all('p')[1].text\n try:\n term_of_office = person_info.find_all('p')[2].text\n except:\n term_of_office = \"\"\n\n person_biography = soup.find('div', class_='person__biography')\n edu_container = person_biography.find_all('div', class_='biography_block')[0]\n edu_p = edu_container.find_all('p')\n edu_count = 0\n edu_list = []\n for p in edu_p:\n edu_item = edu_p[edu_count].text\n edu_list += [edu_item, ]\n edu_count += 1\n region = soup.find('a', class_='region_name_link').text\n\n data = {'name': name.text,\n 'image': image_src,\n 'description': description.strip().replace('\\n', ''),\n 'educations_list': edu_list,\n 'region': region,\n 'birthday': birthday.replace('Дата рождения: ', ''),\n 'authorization': authorization.replace('\\n', '').strip().replace('Дата наделения полномочиями: ', ''),\n 'term_of_office': term_of_office.replace('\\n', '').strip().replace('Срок окончания полномочий *: ', ''),\n 'educations_list': edu_list,}\n return data\n\n\ndef main():\n html = get_html(\"http://council.gov.ru/structure/members/\")\n lists = get_links(html)\n _list = AuthorityList.objects.get(slug=\"senat\")\n for url in lists:\n html = get_html(url)\n data = get_page_data(html)\n if Elect.objects.filter(list=_list, name=data[\"name\"]).exists():\n print(\"сенатор уже есть - \", data[\"name\"])\n else:\n new_elect = Elect.objects.create(\n name=data[\"name\"],\n description=data[\"description\"],\n birthday=data[\"birthday\"],\n authorization=data[\"authorization\"],\n term_of_office=data[\"term_of_office\"]\n )\n data_region = data[\"region\"].replace(\"\\xa0\", ' ')\n if data_region in sity_names:\n data_region = data_region.replace('г.', '')\n elif data_region == \"Ханты-Мансийский автономный округ — Югра\":\n data_region = \"Ханты-Мансийский автономный округ - Югра (Тюменская область)\"\n elif data_region == \"Удмуртская Республика\":\n data_region = \"Удмуртская Республика (Удмуртия)\"\n elif data_region == \"Чувашская Республика\":\n data_region = \"Чувашская Республика - Чувашия\"\n try:\n region = Region.objects.get(name=data_region)\n except:\n region = Region.objects.create(name=data_region)\n region.elect_region.add(new_elect)\n if data[\"image\"]:\n new_elect.get_remote_image(data[\"image\"])\n\n list = AuthorityList.objects.get(slug=\"senat\")\n list.elect_list.add(new_elect)\n\n for edu_item in data[\"educations_list\"]:\n EducationElect.objects.create(elect=new_elect, title=edu_item[6:], year=edu_item[:4])\n print(\"новый сенатор - \", data[\"name\"])\n time.sleep(3)\n\nif __name__ == '__main__':\n main()\n","sub_path":"senat_parsing.py","file_name":"senat_parsing.py","file_ext":"py","file_size_in_byte":5090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"189152933","text":"#!/usr/bin/env python\n# ------------------------------------------------------------------------------\n# Copyright (c) 2010-2013, EVEthing team\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\n# and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY\n# OF SUCH DAMAGE.\n# ------------------------------------------------------------------------------\n\nimport cPickle\nimport os\nimport sys\nimport time\n\nfrom decimal import Decimal, InvalidOperation\n\n# Set up our environment and import settings\nos.environ['DJANGO_SETTINGS_MODULE'] = 'evething.settings'\nimport django\ndjango.setup()\nfrom django.db import connections, transaction\nfrom thing.tasks import *\n\nfrom thing.models import * # NOPEP8\nimport sys\n\n\nif __name__ == '__main__':\n libs = set(sys.argv[1:])\n\n to_run = []\n\n if 'assets' in libs:\n to_run.append(EsiAssets())\n\n if 'charcorp' in libs:\n to_run.append(CharCorpUpdate())\n\n if 'journal' in libs:\n to_run.append(EsiJournal())\n\n if 'contracts' in libs:\n to_run.append(EsiContracts())\n if 'contractseeding' in libs:\n to_run.append(EsiContractSeeding())\n\n if 'moonobserver' in libs:\n to_run.append(EsiMoonObserver())\n\n if 'moonextract' in libs:\n to_run.append(EsiMoonExtraction())\n\n if 'names' in libs:\n to_run.append(FixNames())\n\n if 'roles' in libs:\n to_run.append(EsiCharacterRoles())\n\n if 'notifications' in libs:\n to_run.append(EsiNotifications())\n\n if 'structures' in libs:\n to_run.append(EsiStructures())\n\n if 'price' in libs:\n to_run.append(PriceUpdater())\n\n if 'history' in libs:\n to_run.append(HistoryUpdater())\n\n if 'universe' in libs:\n to_run.append(EsiUniverse())\n\n if 'systems' in libs:\n to_run.append(EsiSystems())\n\n if 'publiccontract' in libs:\n to_run.append(EsiPublicContracts())\n\n if 'fixnames' in libs:\n to_run.append(FixNames())\n\n for run in to_run:\n print('Running %s...' % run.__name__)\n run.run()\n\n","sub_path":"runtask.py","file_name":"runtask.py","file_ext":"py","file_size_in_byte":3210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"134257623","text":"from flask import Flask, Blueprint, render_template, request, flash, redirect, url_for\nfrom .models import Accounts\nfrom flask_sqlalchemy import SQLAlchemy\nfrom os import path\nfrom . import db \n\n\ntransactions = Blueprint('transactions', __name__)\n\n@transactions.route('/withdrawal', methods=['GET','POST'])\ndef withdrawal():\n # retrieve money from database -> will need to change this to the current user id or email when logged in\n acct = Accounts.query.filter_by(user_id=4).first()\n \n print(acct.checkings)\n\n if request.method == 'POST':\n inputAmt = request.form.get('InputAmount')\n #print(inputAmt)\n if (acct.checkings > float(inputAmt)):\n newBal = acct.checkings-float(inputAmt)\n #print(newBal) \n acct.checkings = newBal\n db.session.commit()\n else:\n flash('OverDraft Alert -$20 if you continue', category ='error')\n newBal = acct.checkings-float(inputAmt)-20\n #print(newBal) \n acct.checkings = newBal\n db.session.commit()\n \n \n #newBalance = Accounts.query.filter_by(user_id=4).first()\n #print(newBalance.checkings)\n\n balance = 4\n return render_template('transactions.html')\n\n@transactions.route('/deposit', methods=['GET','POST'])\ndef deposit():\n # find account by id -> will need to change this to the current user id or email when logged in\n acct = Accounts.query.filter_by(user_id=4).first()\n \n print(acct.checkings)\n\n if request.method == 'POST':\n inputAmt = request.form.get('InputAmount')\n #print(inputAmt)\n newBal = acct.checkings+float(inputAmt)\n #print(newBal) \n acct.checkings = newBal\n db.session.commit()\n newBalance = Accounts.query.filter_by(user_id=4).first()\n \n #print(newBalance.checkings)\n\n balance = 4\n \n return render_template('transactions.html')\n\n@transactions.route('/showbalance', methods=['GET','POST'])\ndef showBalance(): \n #pull both accounts from database\n balance = 4\n return render_template('transactions.html')\n\n@transactions.route('/transfer', methods=['GET','POST'])\ndef transfer(): \n # transfer money between accounts \n balance = 4 \n return render_template('transactions.html')\n","sub_path":"transaction/www/transactions.py","file_name":"transactions.py","file_ext":"py","file_size_in_byte":2305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"644752101","text":"#List é uma coleção ordenada e modificável. Permite membros duplicados.\nthislist = [\"lucas\", \"pedro\", \"mario\"]\nthiscopy = list(thislist)\nprint(thislist)\n\n#alterar valor de uma lista\nthislist[1] = \"geraldo\"\nprint(thislist)\n\n#loop através de uma lista\nfor x in thislist:\n print(x)\n\n#verificar se o item existe\nname = [\"geraldo\", \"miguel\", \"lucas\", \"bárbara\", \"pedro\", \"mario\"]\n\nfor n in name:\n if n in thislist:\n print(f\"sim, temos um {n} neste lista!!!\")\n\n else:\n print(f\"Me desculpa mas não consegui encontrar nenhum(a) {n} nesta lista!!!\")\n\n#Determinar quantos itens uma lista possui\n#utilizando o método len()-retorna o cumprimento da lista ou string\nclone = input(\"Digite algo que eu te digo o tamanho:\")\n\nprint(f\"O tamanho da Sting é: {len(clone)}\")\n\n#adicionar itens\n#com o metodo append()\nthislist.append(\"Orange\")\nthislist.append(\"34\")\nthislist.append(len(clone))\n\n#para adicionar no índice especificado\nthislist.insert(2, \"jooj\")\nprint(f\"agora a lista ficou assim: {thislist}\")\n\n#acessar itens\n#referir ao número do índice\n#tive que colocar o input dentro do int pois caso contrário ele me retornaria uma string\nposition = int(input(\"Digite a posição que você deseja acessar na lista:\"))\n\ntry:\n print(thislist[position])\nexcept:\n print(\"esta posição não existe na lista!\")\n\n#remover item\n#utilizando o método remove()\nrem1 = input(\"digite o que você deseja remover da lista:\")\ntry:\n thislist.remove(rem1)\n print(f\"agora a lista esta assim: {thislist}\")\nexcept:\n print(f\"não existe {rem1} nesta lista!!!\")\n\n\n#utilizando pop()- remove o índice especificado\nrem2 = int(input(\"digite a posição do que você deseja remover da lista:\"))\n\ntry:\n thislist.pop(rem2)\n print(f\"agora a lista esta assim {thislist}\")\nexcept:\n print(f\"não existe a posição {rem2} nesta lista!!!\")\n\n#utilizando del- palavra chave que remove o índice especificado\nrem3 = int(input(\"digite a posição do que você deseja remover da lista:\"))\n\ntry:\n del thislist[rem3]\n print(f\"agora a lista esta assim {thislist}\")\nexcept:\n print(f\"não existe a posição {rem3} nesta lista!!!\")\n\n#Copiar uma lista\n#Você não pode copiar uma lista simplesmente digitando list2 = list1, porque: list2será apenas uma referência para list1, e as alterações feitas list1também serão feitas automaticamente em list2.\n#Utilize então o método copy()\nthislist2 = thislist.copy()\n\n#Esvaziar lista\n#utiliza-se o método clear()\nthislist.clear()\nprint(f\"a lista agora está vazia: {thislist}\")\nprint(f\"mas ainda bem que tenho um beckup: {thislist2}\")\nprint(f\"lembrando que no começo a lista estava assim: {thiscopy}\")\n\n#outros métodos\n#count() -retorna o número de vezes que um elemento se repetiu\nfind = input(\"o que você desja procurar na lista?\")\nprint(f\"A quantidade de vezes que este elemento se repete é: {thislist2.count(find)}\")\n\n#extent() -permite unir duas listas distintas\ncarlist1 = [\"uno\", \"bmw\", \"masserati\"]\ncarlist2 = [\"audi\", \"mustangue\", \"ferrari\"]\ncarlist1.extend(carlist2)\nprint(f\"Temos duas listas, a lita 1 tem: {carlist1}, e a lista 2: {carlist2}\")\nprint(f\"fundindo as duas temos: {carlist1}\")\n\n#index() -retorna o valor do índice do objeto\ninp = input(\"procure algo na lista de carros:\")\ntry:\n index = carlist1.index(inp)\n print(f\"a posição de {inp}, é: {carlist1.index(inp)}\")\nexcept:\n print(f\"o elemento {inp} não existe\")\n\n#reverse() -inverte a ordem da lista\nprint(f\"a lista de carro é: {carlist1}\")\ncarlist1.reverse()\nprint(f\"o inverso dela é: {carlist1}\")\n\n#short() -organiza a lista em ordem alfabética\ncarlist1.sort()\nprint(f\"em ordem alfabética, a lista de carros fica assim: {carlist1}\")\nlistexamplenumeric = [1,3,9,4,3,4,2,8,12,3,54,7,331,2232,435,32,12,5,2]\nprint(f\"temos uma lista desordenada de números: {listexamplenumeric}\")\nlistexamplenumeric.sort()\nprint(f\"agora ela está ordenada:{listexamplenumeric}\")","sub_path":"learning_python/lists.py","file_name":"lists.py","file_ext":"py","file_size_in_byte":3912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"101781239","text":"import time\nimport config as cf\nfrom code import csv_processor as csv\nfrom code.clustering import Clustering\nfrom code.make_rule import Rule\nfrom code.predict import Predict\n\nfrom sklearn.model_selection import KFold\nimport numpy as np\n\ndef predict(data):\n now = time.time()\n x = Predict(data, clusters, rules)\n\n corrects = 0\n edit = []\n editCollection = []\n\n for ix, record in enumerate(data):\n if int(record[0]) == x.predict(record, rules)[\"predict\"]:\n corrects += 1\n else:\n pr_rules = x.predict(record, rules)[\"rule\"]\n cr_rules = x.get_rule_truth(record)[\"rule\"]\n edit += x.detect_cluster(pr_rules, cr_rules, record[1: len(record) ])\n print(' Testing Time: {:.2f}s'.format(time.time() - now))\n print(\" Correct: {}, Total: {}, Accuracy: {:.2f}%\\n\".format(corrects, len(data), 100*corrects / len(data)))\n return 100*corrects / len(data)\n\ndef train_func(data):\n now = time.time()\n\n # clustering and save\n clusters = Clustering(data).clusters\n csv.write_file(cf.clusters_path, clusters)\n\n # make_rule and save\n rules = Rule(data, clusters).colection_rules()\n csv.write_file(cf.rule_path, rules)\n\n # Predict and save data\n x = Predict(data, clusters, rules)\n\n corrects = 0\n edit = []\n editCollection = []\n\n for ix, record in enumerate(data):\n if int(record[0]) == x.predict(record, rules)[\"predict\"]:\n corrects += 1\n else:\n pr_rules = x.predict(record, rules)[\"rule\"]\n cr_rules = x.get_rule_truth(record)[\"rule\"]\n edit += x.detect_cluster(pr_rules, cr_rules, record[1: len(record) ])\n print(' Training Time: {:.2f}s'.format(time.time() - now))\n print(\" Correct: {}, Total: {}, Accuracy: {:.2f}%\".format(corrects, len(data), 100*corrects / len(data)))\n return 100*corrects / len(data)\n\nif __name__ == \"__main__\":\n\n # read data\n data = csv.read_file(cf.full_path, 'float')\n\n kf = KFold(n_splits=cf.k_fold, shuffle=cf.shuffle)\n \n result_data = [1 for i in range(cf.num_classes) ]\n\n for i in range(cf.num_classes):\n data_class = []\n for j in data:\n if j[0] == i+1: data_class.append(j)\n result_data[i] = (data_class, list(kf.split(data_class)))\n \n x = []\n y = []\n for i in range(cf.k_fold):\n print(\"Fold {}/{} \".format(i+1,cf.k_fold))\n train = []\n test = []\n for j in range(cf.num_classes):\n data_class = result_data[j][0]\n # result_data[0][1][2][3]\n # 1: class, 2: 1 is kf.split object, 2: fold, 3: train or test\n for train_ids in result_data[j][1][i][0]:\n train.append(data_class[train_ids])\n for test_ids in result_data[j][1][i][1]:\n test.append(data_class[test_ids])\n \n x.append(train_func(train))\n # read data\n clusters = csv.read_file(cf.clusters_path, 'float')\n rules = csv.read_file(cf.rule_path, 'float')\n y.append(predict(test))\n\n print('Result')\n print(' Training Accuracy: {:.3f}%'.format(sum(x)/len(x)))\n print(' Testing Accuracy: {:.3f}%'.format(sum(y)/len(y)))","sub_path":"app/validation.py","file_name":"validation.py","file_ext":"py","file_size_in_byte":3187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"569730194","text":"import os\r\nimport glob\r\n\r\n\r\nindex_path = os.path.join('.', \"index.html\")\r\ninput_dir = './images'\r\noutput_dir = '.'\r\n\r\n\r\ndef append_index():\r\n index = open(index_path, \"w\")\r\n index.write(\"\")\r\n index.write(\"\\n\")\r\n\r\n input_paths = glob.glob(os.path.join(input_dir, '*inputs.png'))\r\n input_paths = sorted(input_paths)\r\n \r\n print('input path num: ', len(input_paths))\r\n num = 1\r\n for input_path in input_paths:\r\n index.write(\"\")\r\n \r\n basename = os.path.splitext(os.path.basename(input_path))[0][:19]\r\n \r\n output_path = os.path.join(input_dir, basename + 'outputs.png')\r\n\r\n \r\n\r\n print(input_path)\r\n print(output_path)\r\n\r\n if not (os.path.exists(input_path) \r\n and os.path.exists(output_path) \r\n ):\r\n continue \r\n index.write(\"\\n\" % basename)\r\n index.write(\"\\n\" % num)\r\n num += 1\r\n index.write(\"\" % input_path)\r\n index.write(\"\" % output_path)\r\n\r\n\r\n index.write(\"\\n\")\r\n return index_path\r\n \r\nappend_index()","sub_path":"results/display.py","file_name":"display.py","file_ext":"py","file_size_in_byte":1249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"310654228","text":"import logging\nimport gurobipy\n\nlogger = logging.getLogger()\n\n\ndef create_vars_vertices_in_singleton(model, vertex_set, dot_vars):\n logger.info(\"Creating variables for possible vertex in singleton.\")\n hat_vars = model.addVars(vertex_set, vtype=gurobipy.GRB.BINARY)\n\n logger.info(\"Creating constraints for possible vertex in singleton.\")\n model.addConstrs(dot_vars.sum(k, '*') == hat_vars[k] for k in vertex_set)\n\n return hat_vars\n\n\ndef add_constr_representative_neq_zero(model, dot_vars, component_set, tilde_vars, biggest_const):\n logger.info(\"Creating constraints that representative vertex has nonzero value.\")\n model.addConstrs(dot_vars.sum('*', z) <= biggest_const * tilde_vars[z] for z in component_set)\n\n\ndef add_constr_vertex_in_singleton_has_edge(model, hat_vars, genome_vars, vertex_set):\n logger.info(\"Creating constraints that vertex has R-edge.\")\n for v in vertex_set:\n rss = gurobipy.tupledict([((v, k), genome_vars.select(v, k)[0]) for k in vertex_set\n if len(genome_vars.select(v, k)) != 0])\n model.addConstr(hat_vars[v] <= rss.sum(v, '*'))\n","sub_path":"impl_gurobi/vars_constrs/ord_singleton.py","file_name":"ord_singleton.py","file_ext":"py","file_size_in_byte":1131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"334021310","text":"import System.Windows.Forms as WinForms\nfrom System import ArgumentException\nfrom System.Drawing import (\n ContentAlignment,\n FontFamily,\n FontStyle,\n SystemFonts,\n)\n\nfrom toga.constants import CENTER, JUSTIFY, LEFT, RIGHT\nfrom toga.fonts import (\n CURSIVE,\n FANTASY,\n MESSAGE,\n MONOSPACE,\n SANS_SERIF,\n SERIF,\n SYSTEM,\n SYSTEM_DEFAULT_FONT_SIZE,\n)\n\n\ndef TextAlignment(value):\n return {\n LEFT: ContentAlignment.TopLeft,\n RIGHT: ContentAlignment.TopRight,\n CENTER: ContentAlignment.TopCenter,\n JUSTIFY: ContentAlignment.TopLeft,\n }[value]\n\n\n# Justify simply sets Left alignment. Is this the best option?\ndef HorizontalTextAlignment(value):\n return {\n LEFT: WinForms.HorizontalAlignment.Left,\n RIGHT: WinForms.HorizontalAlignment.Right,\n CENTER: WinForms.HorizontalAlignment.Center,\n JUSTIFY: WinForms.HorizontalAlignment.Left,\n }[value]\n\n\ndef win_font_family(value):\n try:\n return {\n SYSTEM: SystemFonts.DefaultFont.FontFamily,\n MESSAGE: SystemFonts.MenuFont.FontFamily,\n SERIF: FontFamily.GenericSerif,\n SANS_SERIF: FontFamily.GenericSansSerif,\n CURSIVE: FontFamily(\"Comic Sans MS\"),\n FANTASY: FontFamily(\"Impact\"),\n MONOSPACE: FontFamily.GenericMonospace,\n }[value]\n except KeyError:\n try:\n return FontFamily(value)\n except ArgumentException:\n print(\n \"Unable to load font-family '{}', loading '{}' instead\".format(\n value, SystemFonts.DefaultFont.FontFamily.Name\n )\n )\n return SystemFonts.DefaultFont.FontFamily\n\n\ndef win_font_style(weight, style, font_family):\n font_style = FontStyle.Regular\n if weight.lower() == \"bold\" and font_family.IsStyleAvailable(FontStyle.Bold):\n font_style |= FontStyle.Bold\n if style.lower() == \"italic\" and font_family.IsStyleAvailable(FontStyle.Italic):\n font_style |= FontStyle.Italic\n return font_style\n\n\ndef win_font_size(size):\n if size == SYSTEM_DEFAULT_FONT_SIZE:\n return SystemFonts.DefaultFont.Size\n return size\n","sub_path":"winforms/src/toga_winforms/libs/fonts.py","file_name":"fonts.py","file_ext":"py","file_size_in_byte":2200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"425078551","text":"from typing import List\nimport requests\nfrom core.vk_event_processor import Audio\nfrom repositories.vkCacheRepository import VkCacheRepository\nfrom player import Player\nimport asyncio\nfrom utils.execute_blocking import execute_blocking\nimport logging\nfrom models.ExecutionContext import ExecutionContext\nfrom messageFormatter import MessageType, createRichMediaPayload\nimport discord\n\nclass VkService:\n\n _player: Player = None\n _vk_cache_repository: VkCacheRepository = None\n\n def __init__(self, player, vk_cache_repository, config_repo):\n self._player = player\n self._vk_cache_repository = vk_cache_repository\n self._config_repo = config_repo\n\n async def enqueue_audio(self, audios: List[Audio], ctx: ExecutionContext):\n if (ctx.voice_channel() == None):\n return\n\n for audio in audios:\n async def item_callback():\n id = audio.id\n cached_path = self._vk_cache_repository.try_get_v2(id)\n logging.info(f'Music cache for id {id} was found: ' + str(bool(cached_path)))\n\n if (cached_path):\n return discord.FFmpegPCMAudio(cached_path)\n\n loaded_event = asyncio.Event()\n ctx.loading_callback(loaded_event)\n try:\n doc = await execute_blocking(requests.get, audio.url)\n finally:\n loaded_event.set()\n\n file_path = self._vk_cache_repository.cache_v2(id, doc.content)\n return discord.FFmpegPCMAudio(file_path)\n\n author = ctx.author.display_name\n title = f'{audio.artist} - {audio.title}'\n\n payload = createRichMediaPayload(\n title = title,\n author = author,\n duration = audio.duration,\n user = ctx.author.display_name,\n avatar = str(ctx.author.avatar_url),\n source = ':regional_indicator_v::regional_indicator_k:',\n channel = ctx.voice_channel().name\n )\n\n await ctx.send_message(payload, MessageType.RichMedia)\n self._player.enqueue(item_callback, title, ctx)","sub_path":"discord_bot/services/vk_service.py","file_name":"vk_service.py","file_ext":"py","file_size_in_byte":2193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"486066204","text":"import pygame\n\ndef get_font_size():\n\tsize = 10\n\tA_width = 0\n\twhile A_width <= 6.5:\n\t\tsize += 1\n\t\tfont = pygame.font.SysFont('Sans', size)\n\t\tA_width, h = font.size('A')\n\treturn size+1","sub_path":"COLORPICKER/StyleGuide.py","file_name":"StyleGuide.py","file_ext":"py","file_size_in_byte":182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"165055138","text":"#\n# @lc app=leetcode.cn id=1122 lang=python3\n#\n# [1122] 数组的相对排序\n#\n# https://leetcode-cn.com/problems/relative-sort-array/description/\n#\n# algorithms\n# Easy (70.69%)\n# Likes: 180\n# Dislikes: 0\n# Total Accepted: 61.7K\n# Total Submissions: 87.3K\n# Testcase Example: '[2,3,1,3,2,4,6,7,9,2,19]\\n[2,1,4,3,9,6]'\n#\n# 给你两个数组,arr1 和 arr2,\n# \n# \n# arr2 中的元素各不相同\n# arr2 中的每个元素都出现在 arr1 中\n# \n# \n# 对 arr1 中的元素进行排序,使 arr1 中项的相对顺序和 arr2 中的相对顺序相同。未在 arr2 中出现过的元素需要按照升序放在 arr1\n# 的末尾。\n# \n# \n# \n# 示例:\n# \n# \n# 输入:arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6]\n# 输出:[2,2,2,1,4,3,3,9,6,7,19]\n# \n# \n# \n# \n# 提示:\n# \n# \n# 1 \n# 0 \n# arr2 中的元素 arr2[i] 各不相同\n# arr2 中的每个元素 arr2[i] 都出现在 arr1 中\n# \n# \n#\n\n# @lc code=start\nfrom collections import Counter\n\n\nclass Solution:\n def relativeSortArray(self, arr1: list[int], arr2: list[int]) -> list[int]:\n c1 = Counter(arr1)\n ret = []\n\n for n in arr2:\n for _ in range(c1[n]):\n ret.append(n)\n c1.pop(n)\n\n keys = list(c1.keys())\n keys.sort()\n for n in keys:\n for _ in range(c1[n]):\n ret.append(n)\n\n return ret\n# @lc code=end\n","sub_path":"first-round/1122.数组的相对排序.py","file_name":"1122.数组的相对排序.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"114386629","text":"# uncompyle6 version 3.6.7\n# Python bytecode 2.5 (62131)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: build/bdist.macosx-10.6-x86_64/egg/errorreporter/util/source_encoding.py\n# Compiled at: 2012-01-03 09:44:45\n__doc__ = 'Parse a Python source code encoding string'\nimport codecs, re\nPYTHON_MAGIC_COMMENT_re = re.compile('[ \\\\t\\\\f]* \\\\# .* coding[=:][ \\\\t]*([-\\\\w.]+)', re.VERBOSE)\n\ndef parse_encoding(lines):\n \"\"\"Deduce the encoding of a source file from magic comment.\n\n It does this in the same way as the `Python interpreter`__\n\n .. __: http://docs.python.org/ref/encodings.html\n\n The ``lines`` argument should be a list of the first 2 lines of the\n source code.\n\n (From Jeff Dairiki)\n \"\"\"\n try:\n line1 = lines[0]\n has_bom = line1.startswith(codecs.BOM_UTF8)\n if has_bom:\n line1 = line1[len(codecs.BOM_UTF8):]\n m = PYTHON_MAGIC_COMMENT_re.match(line1)\n if not m:\n try:\n import parser\n parser.suite(line1)\n except (ImportError, SyntaxError):\n pass\n else:\n line2 = lines[1]\n m = PYTHON_MAGIC_COMMENT_re.match(line2)\n if has_bom:\n if m:\n raise SyntaxError('python refuses to compile code with both a UTF8 byte-order-mark and a magic encoding comment')\n return 'utf_8'\n elif m:\n return m.group(1)\n else:\n return\n except:\n return\n\n return","sub_path":"pycfiles/abl.util-0.2.tar/source_encoding.py","file_name":"source_encoding.py","file_ext":"py","file_size_in_byte":1589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"147796320","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 ('financeiro', '0003_tipomovimento'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Debito',\n fields=[\n ('data_agendada', models.DateField()),\n ('data_realizada', models.DateField()),\n ('juros_porcentagem', models.DecimalField(max_digits=8, decimal_places=2)),\n ('juros_value', models.DecimalField(max_digits=8, decimal_places=2)),\n ('multa', models.DecimalField(max_digits=8, decimal_places=2)),\n ('tipo', models.OneToOneField(primary_key=True, serialize=False, to='financeiro.TipoMovimento')),\n ('beneficiario', models.TextField()),\n ],\n ),\n migrations.CreateModel(\n name='Entrada',\n fields=[\n ('data_recebimento', models.DateField()),\n ('data_origem', models.DateField()),\n ('valor', models.DecimalField(max_digits=8, decimal_places=2)),\n ('tipo', models.OneToOneField(primary_key=True, serialize=False, to='financeiro.TipoMovimento')),\n ],\n ),\n ]\n","sub_path":"lukbekka/financeiro/migrations/0004_debito_entrada.py","file_name":"0004_debito_entrada.py","file_ext":"py","file_size_in_byte":1302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"356042724","text":"from PIL import Image, ImageDraw, ImageFilter, ImageEnhance\nimport random\nfrom math import pi, sin, cos\n\ndef create_Si_texture(im_size = (5000,3500), resolution = 5, grain_size = (0.5,5), grain_color = (150,155), grain_density = 4):\n # im_size = image size in pixels\n # resolution = image resolution in pixel/um\n # grain_size = min/max grain size in um\n # grain_color = min/max grain color (0 = white, 255 = black)\n # grain_density = grain average pitch in um. grain position may vary +/-100% of this value\n \n # create image\n image = Image.new('L', im_size, int((grain_color[0]+grain_color[1])/2))\n\n # create list of grains\n grain_list = []\n y = 0\n while y= len(noDupList):\n answer = len(noDupList)\n else:\n answer = int(len(nums)/2)\n \n return answer\n\n\n\n\nnumsArray = [[3,1,2,3],[3,3,3,2,2,4],[3,3,3,2,2,2]]\nfor nums in numsArray:\n print(solution(nums))","sub_path":"algorithm/weekly/phoneketmon.py","file_name":"phoneketmon.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"558766291","text":"import threading\nimport time\nfrom ippool.get_ip import Get_Ip\nfrom ippool.check_ip import Check_Ip\nfrom common.constant import Mysql,Event_Name,Status\nfrom common.send_mail import Send_Mail\nfrom jd_commodity.commodity_id import Commodity_Id\nfrom jd_commodity.commodity_comment import Commodity_Comment\nfrom common.update_stats_file import Update_File\nfrom common.event import Event\nfrom concurrent.futures import ThreadPoolExecutor\nfrom common.log import print_log\nimport json\nimport os\nimport random\n\n\ndef init_event():\n global tasks\n global commodity_page\n global commodity_list\n while True:\n FALG = False\n if tasks[0] == None:\n tasks[0] = Get_Ip(Mysql.DATABASE)\n if tasks[1] == None:\n tasks[1] = Check_Ip(Mysql.DATABASE)\n if tasks[2] == None:\n if commodity_page<40:\n commodity_page+=1\n #print_log(\"error\",\"商品页码%s\"%commodity_page)\n tasks[2] = Commodity_Id(Mysql.DATABASE, commodity_list[0],commodity_page)\n else:\n if len(commodity_list)>0:\n commodity_list.pop(0)\n commodity_page=1\n tasks[2] = Commodity_Id(Mysql.DATABASE, commodity_list[0],commodity_page)\n else:\n print_log(\"info\",\"commodity_list is empty\")\n if tasks[3] == None:\n tasks[3] = Commodity_Comment(Mysql.DATABASE)\n if tasks[4] == None:\n tasks[4] = Send_Mail()\n if tasks[5] == None:\n tasks[5] = Update_File()\n if FALG==False:\n print_log(\"info\",\"No task need to init\")\n time.sleep(20)\n\n\ndef add_event_produce():\n global event\n global tasks\n while True:\n if len(event[0])<3:\n event[0].append(Event(Event_Name.GETIP, tasks[0]))\n tasks[0]=None\n else:\n print_log(\"warning\", \"%s has existed\" % Event_Name.GETIP)\n if len(event[1])<3:\n event[1].append(Event(Event_Name.CHECKIP, tasks[1]))\n tasks[1]=None\n else:\n print_log(\"warning\", \"%s has existed\" % Event_Name.CHECKIP)\n if len(event[2])<3:\n event[2].append(Event(Event_Name.JDCOMMODITYID, tasks[2]))\n tasks[2]=None\n else:\n print_log(\"warning\", \"%s has existed\" % Event_Name.JDCOMMODITYID)\n if len(event[3])<3:\n event[3].append(Event(Event_Name.JDCOMMODITYCOMMENT, tasks[3]))\n tasks[3]=None\n else:\n print_log(\"warning\", \"%s has existed\" % Event_Name.JDCOMMODITYCOMMENT)\n if len(event[4]) < 1:\n event[4].append(Event(Event_Name.SENDEMAIL, tasks[4]))\n tasks[4]=None\n else:\n print_log(\"warning\",\"%s has existed\"%Event_Name.SENDEMAIL)\n if len(event[5]) < 1:\n event[5].append(Event(Event_Name.UPDATEFILE, tasks[5]))\n tasks[5]=None\n else:\n print_log(\"warning\",\"%s has existed\"%Event_Name.UPDATEFILE)\n\n time.sleep(60)\n \n\ndef delete_event_consumer():\n global event\n global thread_pool\n number=60\n while True:\n #print(tasks)\n local_time_hour = time.strftime(\"%H\", time.localtime())\n local_time_minute = time.strftime(\"%M\", time.localtime())\n local_time_second = time.strftime(\"%S\", time.localtime())\n #random_time=str(random.randint(1,59))\n #print(event)\n if number==60:\n random_time=str(random.randint(1,59))\n number=0\n if event[5] == []:\n print_log(\"warning\", \"event list is empty\")\n else:\n if (local_time_hour == \"6\" or local_time_hour == \"10\" or local_time_hour == \"14\" or \\\n local_time_hour == \"18\" or local_time_hour == \"22\" or local_time_hour == \"2\") and \\\n local_time_minute == \"10\" and local_time_second == \"30\":\n thread_tasks[4] = (thread_pool.submit(event[4][0].action))\n event[4][0].update_status(Status.DOING, event[4][0].event_id)\n if local_time_hour == \"23\" and local_time_minute == \"54\" and local_time_second == \"30\":\n thread_tasks[5] = (thread_pool.submit(event[5][0].action))\n event[5][0].update_status(Status.DOING, event[5][0].event_id)\n if int(local_time_minute) % 5 == 0 and local_time_second == random_time:\n thread_tasks[1] = (thread_pool.submit(event[1][0].action))\n event[1][0].update_status(Status.DOING, event[1][0].event_id)\n if int(local_time_minute) % 5 == 0 and local_time_second == random_time:\n #if local_time_second == random_time:\n thread_tasks[3] = (thread_pool.submit(event[3][0].action))\n event[3][0].update_status(Status.DOING, event[3][0].event_id)\n if int(local_time_minute) % 10 == 0 and local_time_second == random_time:\n #if local_time_second == random_time:\n thread_tasks[0] = (thread_pool.submit(event[0][0].action))\n event[0][0].update_status(Status.DOING, event[0][0].event_id)\n if int(local_time_minute) % 10 == 0 and local_time_second == random_time:\n thread_tasks[2] = (thread_pool.submit(event[2][0].action))\n event[2][0].update_status(Status.DOING, event[2][0].event_id)\n\n number=number+1\n time.sleep(1)\n\ndef check_event():\n global thread_tasks\n global event\n time.sleep(5)\n while True:\n FLAG = False\n for i in range(len(thread_tasks)):\n if thread_tasks[i] != None:\n FLAG = True\n if thread_tasks[i].done():\n event[i][0].update_status(Status.DONE, event[i][0].event_id)\n thread_tasks[i]=None\n event[i].pop(0)\n \n event[i][0].cursor.execute(\"select event_status from event where event_id='%s'\"%str(event[i][0].event_id))\n if event[i][0].cursor.fetchall()[0][0]==Status.DONE:\n print_log(\"info\",\"Event %s has ended\"%str(event[i][0].event_id))\n if FLAG == False:\n print_log(\"warning\",\"no event need to check\")\n time.sleep(10)\n\n\npid_file_name=\"/data/pid/pid.txt\"\nf=open(pid_file_name,\"r\")\npid=os.getpid()\npid_dict={}\nline = f.read()\nline_dict = json.loads(line)\npid_dict.update(line_dict)\nf.close()\npid_dict[\"main.py\"]=pid\n\nf=open(pid_file_name,\"w\")\nf.write(json.dumps(pid_dict))\nf.close()\n\n\n\nevent=[[],[],[],[],[],[],]\nthread_tasks={0:None,1:None,2:None,3:None,4:None,5:None}\ntasks={0:None,1:None,2:None,3:None,4:None,5:None}\ncommodity_page=1\ncommodity_list=[\"文胸\",\"手环\",\"笔记本电脑\",\"内存条\",\"平板电脑\",\"拉杆箱\",\"键盘\",\"耳机\",\"手机\",\"手表\",\"单反\"]\n\nthread_pool= ThreadPoolExecutor(max_workers=6)\nthreading.Thread(target=init_event).start()\nthreading.Thread(target=add_event_produce).start()\nthreading.Thread(target=delete_event_consumer).start()\nthreading.Thread(target=check_event).start()\n#delete_event_consumer()\n#threading.Thread(target=delete_event_consumer).start()\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"456965809","text":"import os\nfrom socket import *\nhost = \"127.0.0.1\" # set to IP address of target computer\nport = 13000\nbuf = 1024\naddr = (host, port)\nUDPSock = socket(AF_INET, SOCK_DGRAM)\nprint (\"1. Suma\")\nprint (\"2. Resta\")\nprint (\"3. Multiplicacion\")\nprint (\"4. Division\")\nprint (\"5. Potenciacion\")\nprint (\"6. Radicacion\")\nprint (\"7. Logaritmacion\")\nwhile True:\n data = raw_input(\"Ingrese la opcion deseada o 'exit' para salir:\")\n UDPSock.sendto(data, addr)\n if data == \"exit\":\n break\n else:\n if int(data) < 1 or int(data) > 7:\n print (\"Opcion no valida\")\n else:\n a = raw_input(\"A : \")\n UDPSock.sendto(a, addr)\n b = raw_input(\"B : \")\n UDPSock.sendto(b, addr)\n\n (res, addr) = UDPSock.recvfrom(buf)\n print (\"resultado : \" + res)\nUDPSock.close()\nos._exit(0)\n","sub_path":"1.sockets_localhost/taller1-client.py","file_name":"taller1-client.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"647426145","text":"# coding: utf-8\n\n## Libraries\nimport pygame\n\n## Class definitions\n# Player\n#\n# A player\n\nclass Player():\n\t# Constructor\n\tdef __init__(self, id):\n\t\t\"\"\"Instantiates a square\n\n\t\tKeywords arguments:\n\t\tid -- an integer representing the player ID\n\t\t\"\"\"\n\t\t# Properties\n\t\tself.score = 49\n\t\tself.color = \"\"\n\t\tself.idPlayer = id\n\t\tself.name = \"Player \" + str(self.idPlayer)\n\t\tprint(\"DEBUG: Player \" + self.name + \" created!\")","sub_path":"Python/zone-capture-master/model/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"484326791","text":"import os\nimport glob\nimport numpy as np\nimport torch\nfrom torch.utils import data\nfrom torchvision.transforms import ToTensor\nfrom PIL import Image\nimport matplotlib.pyplot as plt\n\nclass Dataset(data.Dataset):\n def __init__(self, imageDir, imageList, transform = None): #imageDir can be either train, test or validation\"\"\"\n self.imageDir = imageDir\n self.imageList = imageList #with or without label?\n self.transform = transform\n # self.imagePaths = glob.glob(os.path.join(self.imageList))\n\n def __len__(self):\n return len(self.imageList)\n\n def __getitem__(self, item):\n image_path = os.path.join(self.imageDir, self.imageList[item].split()[0])\n Im = Image.open(image_path).convert(\"RGB\")\n # print(Im)\n # Im = np.array(Im)\n # Im = Im/Im.max() #converts image to 0~1\n # print(np.min(Im))\n # Im = ToTensor()(Im)\n X = self.imageList[item].split()[1]\n X = float(X)\n # print(\"X: \", X, type(X))\n X = torch.tensor(X)\n # X = ToTensor()(np.array(X))\n Y = self.imageList[item].split()[2]\n Y = float(Y)\n Y = torch.tensor(Y)\n\n if self.transform is not None:\n Im = self.transform(Im)\n # print(\"Min: \", torch.min(Im))\n return Im, X, Y\n\n\n\n\n\n","sub_path":"Codes/DataLoader.py","file_name":"DataLoader.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"404616777","text":"from matplotlib import image as mpimg\nimport numpy as np\nimport os\n\n\nclass ImageLoadSave:\n def __init__(self):\n self.__files = []\n self.__path = \"\"\n self.__data_dict = dict()\n self.__data_rdy_to_load = False\n\n\n def get_filelist(self):\n return self.__files\n\n\n def get_path(self):\n return self.__path\n\n\n def get_data_dict(self):\n if self.__data_rdy_to_load:\n size = len(self.__files) # get number of images\n container = [] # container for image date\n\n #######################\n # traverse all images #\n #######################\n for img_str in self.__files:\n container.append(mpimg.imread(self.__path + img_str)) # append image data to container\n\n self.__data_dict[\"img_data\"] = np.array(container) # set data, convert it to numpy array\n\n ###################\n # build up labels #\n ###################\n with open(self.__path + \"labels.txt\", \"r\") as f: # read file containing labels\n label_buffer = f.readlines() # read in all lines\n\n # filter all lines not containing \"===\" <-- separator for img label data\n label_buffer = filter(lambda elem: \"===\" in elem, label_buffer)\n\n # remove linebreaks\n label_buffer = [elem.replace(\"\\n\", \"\") for elem in label_buffer]\n\n # sort labels\n label_buffer = sorted(label_buffer)\n\n # split file names and label data\n label_buffer = [elem.split(\"===\") for elem in label_buffer]\n\n label_container_x = []\n label_container_y = []\n\n # iterate over all files\n for img_str in self.__files:\n\n # Flag for determining if a label for any image is missing\n label_found = False\n\n # iterate over the label buffer\n for elem in label_buffer:\n\n # search for the correct label\n if elem[0] in img_str:\n # the correct label was found\n label_found = True\n\n # extract x, y coordinates\n x, y = elem[1].split(\",\")\n\n # coordinates are formatted like e.g. x256, y461\n x = int(x[1:]) # deletes the first character, just leaves the integer\n y = int(y[1:]) # deletes the first character, just leaves the integer\n\n # append data to the container\n label_container_x.append(np.array([x]).astype(np.int32))\n label_container_y.append(np.array([y]).astype(np.int32))\n\n # if the correct label was NOT found\n if not label_found:\n exit(\"Error: Missing label. The label for the image {} was not found.\".format(img_str))\n\n self.__data_dict[\"img_labels_x\"] = np.array(label_container_x)\n self.__data_dict[\"img_labels_y\"] = np.array(label_container_y)\n\n return self.__data_dict\n\n else:\n exit(\"Error: data (a directory) must be loaded before data extraction can start.\")\n\n\n def load_dir(self, read_dir):\n # check if directory exists\n if not os.path.exists(read_dir):\n exit(\"Error: Path does not exist.\")\n\n # check if directory is valid directory\n if not os.path.isdir(read_dir):\n exit(\"Error: This is not a valid directory.\")\n\n # traverse the directory and get a list of files\n self.__files = sorted(self.__traverse_dir(read_dir))\n\n # save path\n self.__path = read_dir\n\n # set flag data_rdy_to_load for enabling data loading\n self.__data_rdy_to_load = True\n\n\n def filter_exclude(self, ex_str):\n # excludes any files where ex_str can be found in the filename\n self.__files = filter(lambda item: ex_str not in item, self.__files)\n\n\n def __traverse_dir(self, read_dir):\n # get contents of directory\n contents = os.listdir(read_dir)\n\n # filter - exclude all but .png files\n contents = filter(lambda item: item[-4:] == \".png\", contents)\n\n # check files are present\n if not len(contents) > 0:\n exit(\"Error: no images present in given directory.\")\n\n return contents\n","sub_path":"code/dir_operations/img_load_save.py","file_name":"img_load_save.py","file_ext":"py","file_size_in_byte":4399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"161949426","text":"# -*- coding: utf-8 -*-\nimport os\nimport pickle\nimport random\nimport argparse\nimport datetime\n\nimport numpy\nimport torch\nimport torchtext.data as data\n\nimport model\nimport train\nimport mydatasets\n\nrandom.seed(66)\ntorch.manual_seed(66)\n\nparser = argparse.ArgumentParser(description='classificer')\n# learning\nparser.add_argument('-lr', type=float, default=0.001)\nparser.add_argument('-epochs', type=int, default=8)\nparser.add_argument('-batch-size', type=int, default=16)\nparser.add_argument('-log-interval', type=int, default=1)\nparser.add_argument('-test-interval', type=int, default=100)\nparser.add_argument('-save-interval', type=int, default=100)\nparser.add_argument('-save-dir', type=str, default='snapshot')\n# data \nparser.add_argument('-shuffle', action='store_true', default=True)\n# model\nparser.add_argument('-dropout-embed', type=float, default=0.5)\nparser.add_argument('-dropout-rnn', type=float, default=0.6)\nparser.add_argument('-use-embedding', action='store_true', default=True)\nparser.add_argument('-max-norm', type=float, default=2.0)\nparser.add_argument('-embed-dim', type=int, default=300)\nparser.add_argument('-input-size', type=int, default=300)\nparser.add_argument('-hidden-size', type=int, default=200)\nparser.add_argument('-which-model', type=str, default='gru')\nparser.add_argument('-static', action='store_true', default=False)\n# device\nparser.add_argument('-device', type=int, default=-1)\nparser.add_argument('-no-cuda', action='store_true', default=True)\n# option\nparser.add_argument('-snapshot', type=str, default=None)\nparser.add_argument('-predict', type=str, default=None)\nparser.add_argument('-test', action='store_true', default=False)\nparser.add_argument('-label5', action='store_true', default=False)\nargs = parser.parse_args()\n\n\n# load dataset\ndef mr(text_field, label_field, label5, **kargs):\n train_data, dev_data, test_data = mydatasets.MR.splits(text_field, label_field, label5=label5)\n text_field.build_vocab(train_data)\n label_field.build_vocab(train_data)\n train_iter, dev_iter, test_iter = data.Iterator.splits(\n (train_data, dev_data, test_data),\n batch_sizes=(args.batch_size, args.batch_size, args.batch_size),\n **kargs)\n return train_iter, dev_iter, test_iter\n\n\n# create embedding\ndef getEmbedding(plk_path, embed_path, id2word, name):\n if os.path.exists(plk_path):\n plk_f = open(plk_path, 'rb+')\n m_embed = pickle.load(plk_f)\n m_embedding = torch.from_numpy(numpy.array(m_embed)).type(torch.DoubleTensor)\n plk_f.close()\n else:\n assert os.path.exists(embed_path)\n embed_f = open(embed_path, encoding=\"utf-8\")\n m_dict = {}\n for idx, line in enumerate(embed_f.readlines()):\n if not (idx == 0 or line == ''):\n strs = line.split(' ')\n m_dict[strs[0]] = [float(i) for idx2, i in enumerate(strs) if not idx2 == 0]\n embed_f.close()\n\n m_embed = [m_dict['unknown']]\n notfound = 0\n for idx, word in enumerate(id2word):\n if not idx == 0:\n if word in m_dict:\n m_embed.append(m_dict[word])\n else:\n notfound += 1\n m_embed.append([random.uniform(-0.25, 0.25) for i in range(args.embed_dim)])\n print('notfound:', notfound)\n print('ratio:', notfound / (len(id2word) - 1))\n m_embedding = torch.from_numpy(numpy.array(m_embed)).type(torch.DoubleTensor)\n\n f = open(os.path.join('./data', name), 'wb+')\n # pickle.dump(id2word, f)\n pickle.dump(m_embed, f)\n f.close()\n return m_embedding\n\n\n# load data\nprint(\"\\nLoading data...\")\n# ????\ntext_field = data.Field(lower=True)\nlabel_field = data.Field(sequential=False)\ntrain_iter, dev_iter, test_iter = mr(text_field, label_field,\n device=args.device,\n repeat=False,\n shuffle=args.shuffle,\n label5=args.label5)\n\n\n# load embedding\nm_embedding = None\nif args.use_embedding:\n id2word = text_field.vocab.itos\n m_embedding = getEmbedding('./data/conj300d.pkl',\n './data/glove.sentiment.conj.pretrained.txt',\n id2word,\n 'conj300d.pkl')\n # m_embedding = getEmbedding('./data/conj300d.pkl',\n # './data/glove.sentiment.conj.pretrained.txt',\n # id2word,\n # 'conj300d.pkl')\n\n\n# update args and print\nargs.embed_num = len(text_field.vocab)\nargs.class_num = len(label_field.vocab) - 1\nargs.cuda = (not args.no_cuda) and torch.cuda.is_available()\ndel args.no_cuda\nargs.save_dir = os.path.join(args.save_dir, datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S'))\nprint(\"\\nParameters:\")\nfor attr, value in sorted(args.__dict__.items()):\n print(\"\\t{}={}\".format(attr.upper(), value))\n\n\n# model\nm_model = None\nif args.snapshot is None:\n if args.which_model == 'lstm':\n m_model = model.LSTM(args, m_embedding)\n elif args.which_model == 'gru':\n m_model = model.GRU(args, m_embedding)\n elif args.which_model == 'rnn':\n m_model = model.RNN(args, m_embedding)\nelse:\n print('\\nLoading model from [%s]...' % args.snapshot)\n try:\n m_model = torch.load(args.snapshot)\n except:\n print(\"Sorry, This snapshot doesn't exist.\")\n exit()\nif args.cuda:\n m_model = m_model.cuda()\n\n\n# train or predict\nassert m_model is not None\n\nif args.predict is not None:\n label = train.predict(args.predict, m_model, text_field, label_field)\n print('\\n[Text] {}[Label] {}\\n'.format(args.predict, label))\nelif args.test:\n try:\n train.eval(test_iter, m_model, args)\n except Exception as e:\n print(\"\\nSorry. The test dataset doesn't exist.\\n\")\nelse:\n torch.set_num_threads(3)\n train.train(train_iter, dev_iter, m_model, args)\n\n # 直接测试所有的模型,选出最好的\n m_max = -99999\n whichmax = ''\n dirlist = os.listdir(args.save_dir)\n f = open(os.path.join(args.save_dir, 'testresult'), \"w+\", encoding='utf-8')\n for attr, value in sorted(args.__dict__.items()):\n f.write(\"\\t{}={} \\n\".format(attr.upper(), value))\n f.flush()\n f.write('----------------------------------------------------')\n f.flush()\n for name in dirlist:\n t_model = torch.load(os.path.join(args.save_dir, name))\n m_str, accuracy = train.test(test_iter, t_model, args)\n f.write(m_str + '-------' + name + '\\n')\n f.flush()\n if accuracy > m_max:\n m_max = accuracy\n whichmax = name\n f.write('max is {} using {}'.format(m_max, whichmax))\n f.flush()\n f.close()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"290532987","text":"import time\nimport edgeiq\n\"\"\"\nSimultaneously use object detection to detect human faces and classification to classify\nthe detected faces in terms of age groups, and output results to\nshared output stream.\n\nTo change the computer vision models, follow this guide:\nhttps://dashboard.alwaysai.co/docs/application_development/changing_the_model.html\n\nTo change the engine and accelerator, follow this guide:\nhttps://dashboard.alwaysai.co/docs/application_development/changing_the_engine_and_accelerator.html\n\"\"\"\n\n\ndef main():\n\n # Step 1b: first make a detector to detect facial objects\n facial_detector = edgeiq.ObjectDetection(\n \"alwaysai/res10_300x300_ssd_iter_140000\")\n facial_detector.load(engine=edgeiq.Engine.DNN)\n\n # Step 2a: then make a classifier to classify the age of the image\n classifier = edgeiq.Classification(\"alwaysai/agenet\")\n classifier.load(engine=edgeiq.Engine.DNN)\n\n # Step 2b: descriptions printed to console\n print(\"Engine: {}\".format(facial_detector.engine))\n print(\"Accelerator: {}\\n\".format(facial_detector.accelerator))\n print(\"Model:\\n{}\\n\".format(facial_detector.model_id))\n\n print(\"Engine: {}\".format(classifier.engine))\n print(\"Accelerator: {}\\n\".format(classifier.accelerator))\n print(\"Model:\\n{}\\n\".format(classifier.model_id))\n\n fps = edgeiq.FPS()\n\n try:\n with edgeiq.WebcamVideoStream(cam=0) as video_stream, \\\n edgeiq.Streamer() as streamer:\n\n # Allow Webcam to warm up\n time.sleep(2.0)\n fps.start()\n\n # loop detection\n while True:\n\n # Step 3a: track how many faces are detected in a frame\n count = 1\n\n # read in the video stream\n frame = video_stream.read()\n\n\n # detect human faces\n results = facial_detector.detect_objects(\n frame, confidence_level=.5)\n\n # Step 3b: altering the labels to show which face was detected\n for p in results.predictions:\n p.label = \"Face \" + str(count)\n count = count + 1\n\n\n\n # Step 3c: alter the original frame mark up to just show labels\n frame = edgeiq.markup_image(\n frame, results.predictions, show_labels=True, show_confidences=False)\n\n # generate labels to display the face detections on the streamer\n text = [\"Model: {}\".format(facial_detector.model_id)]\n text.append(\n \"Inference time: {:1.3f} s\".format(results.duration))\n\n # Step 3d:\n text.append(\"Faces:\")\n\n # Step 4a: add a counter for the face detection label\n age_label = 1\n\n # append each predication to the text output\n for prediction in results.predictions:\n\n # Step 4b: append labels for face detection & classification\n text.append(\"Face {} \".format(\n age_label))\n\n age_label = age_label + 1\n\n ## to show confidence, use the following instead of above:\n # text.append(\"Face {}: detected with {:2.2f}% confidence,\".format(\n #count, prediction.confidence * 100))\n\n # Step 4c: cut out the face and use for the classification\n face_image = edgeiq.cutout_image(frame, prediction.box)\n\n # Step 4d: attempt to classify the image in terms of age\n age_results = classifier.classify_image(face_image)\n\n # Step 4e: if there are predictions for age classification,\n # generate these labels for the output stream\n if age_results.predictions:\n text.append(\"is {}\".format(\n age_results.predictions[0].label,\n ))\n else:\n text.append(\"No age prediction\")\n\n ## to append classification confidence, use the following\n ## instead of the above if/else:\n\n # if age_results.predictions:\n # text.append(\"age: {}, confidence: {:.2f}\\n\".format(\n # age_results.predictions[0].label,\n # age_results.predictions[0].confidence))\n # else:\n # text.append(\"No age prediction\")\n \n # send the image frame and the predictions to the output stream\n streamer.send_data(frame, text)\n\n fps.update()\n\n if streamer.check_exit():\n break\n\n finally:\n fps.stop()\n print(\"elapsed time: {:.2f}\".format(fps.get_elapsed_seconds()))\n print(\"approx. FPS: {:.2f}\".format(fps.compute_fps()))\n\n print(\"Program Ending\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"515205444","text":"import sys\nimport getopt\nimport gzip\nimport threading\nimport pickle\nimport numpy as np\nimport time\n\nfrom architectures import fabric_binary as bae\n\n\ndef embed(ifile, ofile, fabric_path):\n\n # EMBED VECTOR\n def embed_vector(vectors):\n batch = []\n for v in vectors:\n x = v.toarray()[0]\n batch.append(x)\n x_embedded = bae_encoder.predict_on_batch(np.asarray(batch))\n zidx_rows, zidx_cols = np.where(x_embedded < 0.33)\n oidx_rows, oidx_cols = np.where(x_embedded > 0.66)\n x_embedded.fill(0.5) # set everything to 0.5\n for i, j in zip(zidx_rows, zidx_cols):\n x_embedded[i][j] = 0\n for i, j in zip(oidx_rows, oidx_cols):\n x_embedded[i][j] = 1\n return x_embedded\n\n # INCR DATA GEN\n class Incr_data_gen:\n def __init__(self, batch_size, path_file):\n self.batch_size = batch_size\n self.path_file = path_file\n self.f = gzip.open(path_file, \"rb\")\n self.lock = threading.Lock()\n\n def __iter__(self):\n return self\n\n def __next__(self):\n def produce_data():\n x1_vectors = []\n x2_vectors = []\n y_vectors = []\n current_batch_size = 0\n while current_batch_size < self.batch_size:\n with self.lock:\n x1, x2, y = pickle.load(self.f)\n x1_vectors.append(x1)\n x2_vectors.append(x2)\n y_vectors.append(y)\n current_batch_size += 1\n np_x1 = embed_vector(x1_vectors)\n np_x2 = embed_vector(x2_vectors)\n return [np_x1, np_x2], np.asarray(y_vectors)\n\n try:\n return produce_data()\n except EOFError:\n with self.lock:\n print(\"All input is now read\")\n self.f.close()\n return None, None\n\n bae_encoder = bae.load_model_from_path(fabric_path + \"/bae_encoder.h5\")\n\n st = time.time()\n total_samples = 0\n with gzip.open(ofile, \"wb\") as g:\n for inputs, labels in Incr_data_gen(1, ifile):\n if total_samples % 1000 == 0:\n print(\"s: \" + str(total_samples))\n if inputs is None:\n break # Done!\n total_samples += 1\n x1 = inputs[0][0]\n x2 = inputs[1][0]\n y = labels\n pickle.dump((x1, x2, y), g)\n et = time.time()\n print(\"Total samples: \" + str(total_samples))\n print(\"Total time: \" + str(et - st))\n\ndef main(argv):\n ifile = \"\"\n ofile = \"\"\n fabric_path = \"\"\n try:\n opts, args = getopt.getopt(argv, \"i:o:f:\")\n except getopt.GetoptError:\n print(\"embedder.py -i -o \"\n \"-f \")\n sys.exit(2)\n\n for opt, arg in opts:\n if opt == \"-h\":\n print(\"embedder.py -i -o \"\n \"-f \")\n sys.exit()\n elif opt in \"-i\":\n ifile = arg\n elif opt in \"-o\":\n ofile = arg\n elif opt in \"-f\":\n fabric_path = arg\n\n embed(ifile, ofile, fabric_path)\n\n\nif __name__ == \"__main__\":\n print(\"Trainer\")\n\n main(sys.argv[1:])\n","sub_path":"embedder.py","file_name":"embedder.py","file_ext":"py","file_size_in_byte":3366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"598936893","text":"# Confidence.py is a modified version of mm1 solution\n# Intent is to solve the confidence intervals problem in sprint 4\n# CMS 380\n# Matthew Trautmann Fall 2020\n\n# Standard matplotlib import\nimport matplotlib\nmatplotlib.use('Agg')\nfrom matplotlib import pyplot as plt\n\n# Math imports\nimport math\nfrom math import log\nfrom random import random\n\n\n#Calculates the variance of a list\ndef variance(x):\n \"\"\"\n Calculate and return the variance of input list x\n \"\"\"\n #Get the length\n n = len(x)\n \n #get the average\n mean = sum(x) / len(x)\n \n #Make a deviations list to store deviations\n deviations = []\n \n #Go thorugh list calculate deviations\n for i in x:\n deviation = (i - mean) ** 2\n deviations.append(deviation)\n \n #find variance\n variance = sum(deviations) / n\n \n return variance\n\n# Calculate the standard_deviation using the variance \ndef standard_deviation(x):\n \"\"\"\n Calculate and return the standard deviation of input list x\n \"\"\"\n standard_deviation = math.sqrt(variance(x))\n \n return standard_deviation\n \n\n#--- Generate an exponential random variate\n#\n# Input: mu, the parameter of the exponential distribution\n# Output: a value x drawn from the exponential distribution with rate mu\ndef rand_exp(mu):\n\n return -log(random()) / mu\n \n \n#--- Simulate the M/M/1 queue\n#\n# Inputs:\n# arrival_rate\n# avg_service_time\n# n: number of simulated customers\n#\n# Output: the average residence time of customer in the queue\ndef simulate(arrival_rate, avg_service_time, n):\n # Generate interarrival times\n # use rand_exp to generate n interarrival times with parameter arrival_rate\n interarrival_times = [0] * n\n for i in range(1, n):\n interarrival_times[i] = rand_exp(arrival_rate)\n \n \n # Generate service times\n # use rand_exp to generate n service times with parameter 1 / avg_service_time\n service_times = [0] * n\n for i in range(0, n):\n service_times[i] = rand_exp(1 / avg_service_time)\n \n # Calculate arrival times\n # use interarrival times to calculate a list of arrival times\n arrival_times = [0] * n\n arrival_times[0] = 1\n for i in range(1, n):\n time = arrival_times[i - 1] + interarrival_times[i]\n arrival_times[i] = time\n\n # Initialize other lists\n enter_service_times = [0] * n\n departure_times = [0] * n\n \n # Setup for first arrival\n enter_service_times[0] = arrival_times[0]\n departure_times[0] = enter_service_times[0] + service_times[0]\n \n # Loop over all other arrivals\n for i in range(1, n):\n \n # calculate enter_service_times[i]\n enter_service_times[i] = max(arrival_times[i], departure_times[i - 1])\n # calculate departure_times[i]\n departure_times[i] = enter_service_times[i] + service_times[i]\n \n # Calculate residence times\n # calculate list of residence times\n residence_times = [0] * n\n for i in range(0, n):\n residence_times[i] = departure_times[i] - arrival_times[i]\n \n # return average residence time\n average_residence_time = sum(residence_times) / len(residence_times)\n return average_residence_time\n\ndef main():\n\n n = 1000\n arrival_rate = .05\n avg_service_time = 1\n \n \n # Create a list to track utilization rates\n utilization_list = []\n # Create a list to track average residence times\n y_bar_list = []\n # Create a list to track the Upper Confidence interval\n ucl_list = []\n # Create a list to track the lower confidence interrval\n lcl_list = []\n \n # Iterate for each arrival rate\n while arrival_rate < 1:\n # Make a list for the 5 simulates\n replications = [0] * 5\n for i in range(0, 4):\n replications[i] = simulate(arrival_rate, avg_service_time, n)\n \n # Find the average of the simulations \n y_bar = sum(replications) / len(replications)\n \n # Add average to list of averages\n y_bar_list.append(y_bar)\n \n # Calculate the standard deviation of the list\n s = standard_deviation(replications)\n \n # Calculate the upper confidence interval and add to list\n UCL = y_bar + ((2.776 * s) / math.sqrt(5))\n ucl_list.append(UCL)\n \n # Calculate lower confidence interval and add to list\n LCL = y_bar - ((2.776 * s) / math.sqrt(5))\n lcl_list.append(LCL)\n \n # Calculate utilization rate and store it\n utilization = arrival_rate * avg_service_time\n utilization_list.append(utilization)\n \n #Increase the arrival rate\n arrival_rate = arrival_rate + .05\n \n # Create a new figure\n plt.figure()\n\n # Create line plots for simulated data\n plt.plot(utilization_list, y_bar_list, label = \"Average Residence Time\")\n plt.plot(utilization_list, ucl_list, label = \"Upper Confidence Interval\")\n plt.plot(utilization_list, lcl_list, label = \"Lower Confidence Interval\")\n \n # Make a legend\n plt.legend()\n \n # Title and axis labels\n plt.title('Single Queue Simulation')\n plt.xlabel('Utilization Rate')\n plt.ylabel('Simulated Average residence times')\n\n # Save the figure to a file\n plt.savefig('confidence_interval.pdf', bbox_inches='tight')\n \n\n \n \n# Call main() when this program runs\nif __name__ == '__main__':\n main()\n","sub_path":"Sprint-4-Continuous_Probability_and_Queueing/Deliverables/confidence.py","file_name":"confidence.py","file_ext":"py","file_size_in_byte":5428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"567039918","text":"import numpy as np\r\nimport random\r\nimport sys\r\nfrom sklearn.decomposition import PCA\r\nimport matplotlib.pyplot as plt\r\n\r\n\"\"\"\r\n Data Pre-Processing Implementation\r\n\"\"\"\r\ndef pre_processing(filename):\r\n contents = open(filename, 'r')\r\n firstLine = contents.readline().split()\r\n contents.close()\r\n num = [i for i in range(2,len(firstLine))]\r\n\r\n gene = np.genfromtxt(filename, usecols=num)\r\n result = np.genfromtxt(filename, usecols=(1), dtype='str').astype(int)\r\n id = np.genfromtxt(filename, usecols=(0), dtype='str').astype(int)\r\n\r\n return gene, id, result\r\n\r\n# def PCA_plot(gene,geneGroup,center):\r\n# pca = PCA(n_components=2)\r\n# pca.fit(gene)\r\n# M = pca.transform(gene)\r\n#\r\n# pca.fit(center)\r\n# k = pca.transform(center)\r\n#\r\n# for idx, item in enumerate(geneGroup):\r\n# group = [[M[i][0],M[i][1]] for i in item]\r\n#\r\n# # for x in group:\r\n# group = np.array(group)\r\n# plt.scatter(group[:,0], group[:,1], label=(\"Group \"+str(idx)))\r\n#\r\n# c = np.array([[i[0],i[1]] for i in k])\r\n# plt.scatter(c[:, 0], c[:, 1], label=(\"Center\"))\r\n#\r\n# plt.title(\"Dataset : \" + filename + ' - PCA Plot')\r\n# plt.legend(loc=2)\r\n# plt.show()\r\n\"\"\"\r\n PCA_plot Implement\r\n\"\"\"\r\ndef PCA_plot(gene, geneGroup, cluster, filename):\r\n pca = PCA(n_components=2)\r\n pca.fit(gene)\r\n M = pca.transform(gene)\r\n\r\n for idx, item in enumerate(geneGroup):\r\n group = [[M[i][0], M[i][1]] for i in item]\r\n group = np.array(group)\r\n plt.scatter(group[:, 0], group[:, 1], label=(\"Group \" + str(idx+1)))\r\n\r\n plt.title(cluster +\" with data : \"+ filename + ' - PCA Plot')\r\n plt.legend(loc=2)\r\n plt.show()\r\n\r\n\"\"\"\r\n Jaccard Coefficient and Rand Index Calculate implement\r\n\"\"\"\r\ndef Jaccard_Coefficient_and_Rand_Index(test, result):\r\n geneGroup_arr = np.zeros((len(result)))\r\n\r\n for index, item in enumerate(test):\r\n for x in item:\r\n geneGroup_arr[x] = index\r\n\r\n M_00, M_01, M_10, M_11 = 0 ,0 ,0 ,0\r\n for i, iter1 in enumerate(result):\r\n for j, iter2 in enumerate(result):\r\n if iter1 == iter2:\r\n if geneGroup_arr[i] == geneGroup_arr[j]:\r\n M_11 += 1\r\n else:\r\n M_10 += 1\r\n else:\r\n if geneGroup_arr[i] == geneGroup_arr[j]:\r\n M_01 += 1\r\n else:\r\n M_00 += 1\r\n\r\n JC = M_11 / (M_11 + M_10 + M_01)\r\n\r\n RandIndex = (M_11 + M_00) / (M_11 + M_00 + M_10 + M_01)\r\n\r\n return JC , RandIndex\r\n\r\n\r\n\"\"\"\r\n K_Mean Implementation\r\n\"\"\"\r\ndef SSE(gene,centers):\r\n error = [np.linalg.norm(gene - i) for i in centers]\r\n return min(error), error.index(min(error))\r\n\r\ndef k_mean(k,gene,central,iteration):\r\n retVal = [[] for _ in range(k)]\r\n geneGroup = [[] for _ in range(k)]\r\n # initial = np.sort(np.random.choice(id,k,replace=False))\r\n total_error = sys.maxsize\r\n center = np.array([gene[i-1] for i in central])\r\n\r\n iter_time = 0\r\n while(iter_time < iteration):\r\n total_error_2 = 0\r\n retVal = [[] for _ in range(k)]\r\n geneGroup = [[] for _ in range(k)]\r\n\r\n for idx, item in enumerate(gene):\r\n error, group = SSE(item,center)\r\n total_error_2 += error\r\n retVal[group].append(item)\r\n geneGroup[group].append(idx)\r\n\r\n iter_time += 1\r\n\r\n if(total_error != total_error_2):\r\n total_error = total_error_2\r\n else:\r\n break\r\n\r\n\r\n\r\n center = [np.mean(i,axis=0) for i in retVal]\r\n\r\n # print(iter_time)\r\n\r\n return total_error,geneGroup,center\r\n\r\n\r\nif __name__ == '__main__':\r\n \"\"\"\r\n Data Pre-Processing\r\n \"\"\"\r\n\r\n filename = \"new_dataset_1.txt\"\r\n gene, id, result = pre_processing(filename)\r\n k = 3\r\n iteration = 10\r\n central = [3,5,9]\r\n\r\n \"\"\"\r\n K - Mean Clustering\r\n \"\"\"\r\n cluster = \"K_mean\"\r\n error,geneGroup,center = k_mean(k,gene,central,iteration)\r\n\r\n PCA_plot(gene,geneGroup,cluster,filename)\r\n\r\n JC , RD = Jaccard_Coefficient_and_Rand_Index(geneGroup,result)\r\n print(\"Jaccard Coefficient is : \" + str(JC))\r\n print(\"Rand Index is : \" + str(RD))\r\n\r\n\r\n\r\n\r\n","sub_path":"Clustering/Code/k_mean.py","file_name":"k_mean.py","file_ext":"py","file_size_in_byte":4230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"180900117","text":"from word2number import w2n\nimport re\nimport scipy\n\nMIN_EXAMPLE = 2\nZERO = 0.01\nMAX_EQUATION_LENGTH=40\nMAX_NO_EQUATIONS=3\n\n\ndef removeEmptiesAndPunctuation(words):\n words = [word for word in words if word]\n\n for i in range(len(words)):\n if words[i][-1] in \"?!.,;:$%\":\n words[i] = words[i][:-1]\n if len(words[i]) > 0 and words[i][0] in \"$\":\n words[i] = words[i][1:]\n\n return words\n\n\ndef findNumbersInWords(words):\n ind = 0\n numbers = []\n for i in range(len(words)):\n word = words[i]\n s = word\n j = i\n\n prevNum = None\n\n couldBeNum=True\n num = None\n\n for letter in word:\n if letter not in \"0123456789.()/*+-\":\n couldBeNum = False\n break\n\n if couldBeNum:\n try:\n num = eval(word)\n num = float(num)\n except:\n num = None\n\n if num != None:\n if num not in numbers:\n words[i] = \"a\" + str(ind)\n numbers.append(num)\n ind += 1\n else:\n tempInd = numbers.index(num)\n words[i] = \"a\" + str(tempInd)\n else:\n try:\n num = w2n.word_to_num(s)\n except:\n num = None\n\n while(num != prevNum):\n prevNum = num\n j += 1\n try:\n num = None\n if words[j] == \"point\":\n s += \" \" + words[j] + \" \" + words[j+1]\n tempNum = w2n.word_to_num(s)\n if tempNum != prevNum:\n num = tempNum\n j += 1\n if num == None:\n s += \" \" + words[j]\n num = w2n.word_to_num(s)\n except:\n num = prevNum\n\n if num != None:\n if num not in numbers:\n words[i] = \"a\" + str(ind)\n numbers.append(num)\n ind += 1\n else:\n tempInd = numbers.index(num)\n words[i] = \"a\" + str(tempInd)\n for k in range(i+1,j):\n words[k] = \"\"\n\n\n return numbers\n\ndef createTemplate(numbers, equations, unknowns):\n\n possibleUnknowns = \"xyz\"\n equationTemplate = ''\n for equation in equations:\n equationTemplate += equation\n equationTemplate += ';'\n equationTemplate = equationTemplate[:-1]\n\n unknowns.sort(reverse=True)\n pre = []\n for char in possibleUnknowns:\n if char in unknowns:\n unknowns.remove(char)\n pre.append(char)\n unknowns = pre + unknowns\n for i in range(len(unknowns)):\n equationTemplate = equationTemplate.replace(unknowns[i], possibleUnknowns[i])\n\n charset1a = unknowns + [')', 'x']\n charset2b = unknowns + ['(', 'x']\n charset2a = charset1a + [str(i) for i in range(10)] + ['.']\n charset1b = charset2b + [str(i) for i in range(10)] + ['.']\n for a in charset1a:\n for b in charset1b:\n equationTemplate = equationTemplate.replace(a+b, a+'*'+b)\n for a in charset2a:\n for b in charset2b:\n equationTemplate = equationTemplate.replace(a+b, a+'*'+b)\n\n numbersInEquation = re.findall(r'-?\\d*\\.?\\d*', equationTemplate)\n # numbersInEquation = re.findall(r\"\\d+(\\.\\d+)?\", equationTemplate)\n numbersInEquation = list(filter(lambda s : s != '' and s != '-' and s != '-0', numbersInEquation))\n numbersInEquation.sort(key=(lambda s : len(s)), reverse=True)\n\n for num in numbersInEquation:\n if num[0] == '-':\n numbersInEquation.append(num[1:])\n\n positiveNumbersInEquation = list(filter(lambda s : s[0] != '-', numbersInEquation))\n positiveNumbersInEquation.sort(key=(lambda s : len(s)), reverse=True)\n\n for i in range(len(positiveNumbersInEquation)):\n num = positiveNumbersInEquation[i]\n equationTemplate = equationTemplate.replace(num, \"b\" + str(i))\n if \"bb\" + str(i) in equationTemplate:\n equationTemplate = equationTemplate.replace(\"bb\" + str(i), \"b\"+str(num))\n\n for i in range(len(numbers)):\n number = numbers[i]\n for num in numbersInEquation:\n if number-float(num) < ZERO and number-float(num) > -ZERO:\n prefix = ''\n if num[0] == '-':\n prefix = '-'\n num = num[1:]\n ind = positiveNumbersInEquation.index(num)\n equationTemplate = equationTemplate.replace(prefix + \"b\" + str(ind), \"a\" + str(i))\n\n for i in range(len(positiveNumbersInEquation)):\n equationTemplate = equationTemplate.replace(\"b\" + str(i), positiveNumbersInEquation[i])\n\n return equationTemplate\n\n\n\ndef replaceNumbers(words, equations, unknowns):\n numbers = findNumbersInWords(words)\n words = removeEmptiesAndPunctuation(words)\n equationTemplate = createTemplate(numbers, equations, unknowns)\n return (words, equationTemplate, numbers)\n\n\ndef buildVocab(data):\n vocab = {}\n i = 0\n for d in data:\n words = d[0]\n for word in words:\n try:\n a = vocab[word]\n except:\n vocab[word] = i\n i+= 1\n try:\n a = vocab[\" # \"]\n except:\n vocab[\" # \"] = i\n return vocab\n\n\ndef encode(data, vocab):\n y = [d[1] for d in data]\n x = []\n for d in data:\n entry = [0 for l in range(len(vocab))]\n for word in d[0]:\n entry[vocab[word]] = 1\n x.append(entry)\n x = scipy.sparse.csr_matrix(x)\n return (x,y)\n\ndef encodeTest(words, vocab):\n entry = [0 for l in range(len(vocab))]\n for word in words:\n try:\n entry[vocab[word]] = 1\n except:\n entry[vocab[\" # \"]] = 1\n return entry\n\ndef addBiTriGrams(words):\n biTri = []\n for i in range(len(words)-2):\n biTri.append(words[i] +\" \"+ words[i+1])\n biTri.append(words[i] +\" \"+ words[i+1] +\" \"+ words[i+2])\n if len(words) >= 2:\n biTri.append(words[-2] +\" \"+ words[-1])\n words += biTri\n return words\n\ndef getRelevantWords(data, minLength):\n tempVocab = {}\n for d in data:\n words = d[0]\n for word in words:\n try:\n tempVocab[word] += 1\n except:\n tempVocab[word] = 1\n for word,count in tempVocab.items():\n if count < minLength:\n tempVocab[word] = False\n return tempVocab\n\ndef replaceIrrelevantWords(words, tempVocab):\n for i in range(len(words)):\n try:\n count = tempVocab[words[i]]\n if not count:\n words[i] = \" # \"\n except:\n words[i] = \" # \"\n return words\n\ndef removeWordsWithLowFreq(data, tempVocab):\n for d in data:\n words = d[0]\n replaceIrrelevantWords(words, tempVocab)\n return data\n\n\n\n\n\ndef checkSolution(eq, answers):\n correct = False\n if eq:\n for answer in answers:\n possibleUnknowns = \"xyz\"\n permutations = [[[0]],[[0,1],[1,0]],[[0,1,2],[1,0,2],[0,2,1],[1,2,0],[2,1,0],[2,0,1]]]\n for permutation in permutations[len(answer)-1]:\n tempEq = eq\n for i in range(len(answer)):\n tempEq = tempEq.replace(possibleUnknowns[permutation[i]], str(answer[i]))\n tempEq = tempEq.split(';')\n correctTemp = True\n for teq in tempEq:\n try:\n sol = eval('('+ teq.replace('=', ')-(') +')')\n if sol > ZERO or sol < -ZERO:\n correctTemp = False\n except:\n correctTemp = False\n\n correct = correct or correctTemp\n if correct:\n break\n if correct:\n break\n\n return correct\n","sub_path":"final_combined/helper_functions.py","file_name":"helper_functions.py","file_ext":"py","file_size_in_byte":8014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"30344523","text":"#!/usr/bin/env python\n\n# To view the plot immediately run in pylab\n# ipython -pylab binplot.py\n# To simply save the plot to 'binplot.eps', run in regular python\n# python2.6 binplot.py\n\nimport sys\nfrom numpy import arange\nfrom scipy import comb\nimport matplotlib.pyplot as pyplot\n\ndef bin_pdf(n,p,k): return comb(n,k) * p**k * (1-p)**(n-k)\ndef bin_cdf(n,p,m): return sum( (bin_pdf(n,p,k) for k in range(m+1)) )\ndef pr_correct(n,p): \n if isinstance(n,int): return 1 - bin_cdf(n,p,n//2)\n try:\n return map(lambda m: pr_correct(m,p),n)\n except:\n raise Exception('pr_correct requires integer or a list of integers')\n\nt = arange(50)\npyplot.plot(t, pr_correct(t,0.5), '.', label='$p = 0.5$')\n#pyplot.plot(t, pr_correct(t,0.5), '.')\n\npyplot.plot(t, pr_correct(t,0.6), '.', label='$p = 0.6$')\n#pyplot.plot(t, pr_correct(t,0.6), 'b.')\n\npyplot.plot(t, pr_correct(t,0.8), '.', label='$p = 0.7$')\n#pyplot.plot(t, pr_correct(t,0.8), 'r.')\n\npyplot.ylabel('Pr(Correct Majority)')\npyplot.xlabel('Number of base learners $T$')\n\npyplot.legend(loc='best')\n\n# Save the plot if desired.\ntry:\n filename = sys.argv[1]\n pyplot.savefig(filename)\nexcept Exception as e:\n if isinstance(e,IndexError):\n sys.stderr.write(\"\\nNo filename given, didn't write to file.\\n\\n\")\n else:\n sys.stderr.write(\"\\nCan not write image file '%s'\\n\\n\" % filename)\n","sub_path":"Bryan/hw6/binplot.py","file_name":"binplot.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"175258246","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport json\nimport time\nimport numpy as np\nfrom opt import default_options\nfrom data_provider import DataProvision\nfrom model import CBP\nfrom util import evaluation_metric_util, mkdirs\nimport argparse\nimport tensorflow as tf\nimport sys\n\n# set default encoding\n#reload(sys)\n#sys.setdefaultencoding('utf-8')\n\n#np.set_printoptions(threshold='nan')\n\n\ndef test(options):\n sess_config = tf.ConfigProto()\n sess_config.gpu_options.allow_growth = True\n os.environ['CUDA_VISIBLE_DEVICES'] = str(options['gpu_id'])\n sess = tf.InteractiveSession(config=sess_config)\n\n # build model\n print('Building model ...')\n model = CBP(options)\n inputs, outputs = model.build_inference()\n interactor_inputs, interactor_outputs = model.build_interactor_self_attention_inference()\n proposal_inputs, proposal_outputs = model.build_proposal_prediction_inference()\n\n # print variable names\n for v in tf.trainable_variables():\n print(v.name)\n print(v.get_shape())\n\n print('Loading data ...')\n data_provision = DataProvision(options)\n\n print('Restoring model from %s' % options['init_from'])\n saver = tf.train.Saver()\n saver.restore(sess, options['init_from'])\n\n split = 'test'\n print('Start to predict ...')\n t0 = time.time()\n\n out_data, recall_at_k = evaluation_metric_util(\n options, data_provision, sess, inputs, outputs,\n interactor_inputs=interactor_inputs, interactor_outputs=interactor_outputs,\n proposal_inputs=proposal_inputs, proposal_outputs=proposal_outputs, split=split)\n\n out_json_file = './results/%d/predict_proposals_%s_nms_%.2f.json' % (\n options['train_id'], split, options['nms_threshold'])\n\n mkdirs(os.path.dirname(out_json_file))\n\n print('Writing result json file ...')\n with open(out_json_file, 'w') as fid:\n json.dump(out_data, fid)\n\n print('Total running time: %f seconds.' % (time.time() - t0))\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n options = default_options()\n for key, value in options.items():\n if type(value) == bool:\n parser.add_argument('--%s' % key, action='store_true')\n else:\n parser.add_argument('--%s' % key, dest=key, type=type(value), default=None)\n args = parser.parse_args()\n args = vars(args)\n for key, value in args.items():\n if value is not None:\n options[key] = value\n\n test(options)\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"615712189","text":"#ตัวเลขขั้นบันได\r\n\r\n'''\r\ninput 4\r\n\r\n1\r\n12\r\n123\r\n1234\r\n\r\n'''\r\n\r\nn = int(input(\"Input your number : \"))\r\n\r\nfor row in range(1,n+1):\r\n for column in range(1,row+1):\r\n print(\"*\",end='') # end='' คือ การแสดงผลในแนวนอน\r\n print(\" \")\r\n\r\n\r\n\r\n","sub_path":"KR_Python_Day3_Step Number.py","file_name":"KR_Python_Day3_Step Number.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"131067374","text":"#!/usr/bin/env python3\n\nfrom urllib.request import urlopen\nfrom urllib.parse import urljoin, urlparse, urlunparse\nfrom lxml.html import fromstring\nfrom termcolor import colored\nimport os, sys\n\n\nprint(\n colored('\\n* * * * * * * * * * * * * * * * * *', 'yellow'), '\\n',\n colored('*', 'yellow'), ' Download from -> http://lxr.free-electrons.com ', colored('*', 'yellow'), '\\n',\n colored('* * * * * * * * * * * * * * * * * *', 'yellow'),\n sep=''\n)\n\ntry:\n INPUT_URL = input(colored('\\nSTEP 1: ', 'cyan') + 'Write here url from download: ').strip(' /') + '/'\n INPUT_SOURCE = input(colored('\\nSTEP 2: ', 'cyan') + 'Write here file or directory for download: ').strip(' /') + '/'\nexcept KeyboardInterrupt:\n print(colored('\\n\\nBay!\\n', 'green'))\n sys.exit(0)\n\n\nif INPUT_URL.find('source') == -1:\n arr = list(urlparse(INPUT_URL))\n arr[2] = '/source' + arr[2]\n CORRECTED_INPUT_URL = urlunparse(arr)\nelse:\n CORRECTED_INPUT_URL = INPUT_URL\n\nURL = urljoin(CORRECTED_INPUT_URL, INPUT_SOURCE)\nSELECTOR = 'table tr'\n\nABS_WORK_DIR = os.path.dirname(os.path.abspath(__file__)) + os.path.sep\n\nFILE_DESTINATION = urljoin(ABS_WORK_DIR, 'downloads' + os.path.sep)\nFOLDER_DESTINATION = urljoin(FILE_DESTINATION, INPUT_SOURCE.rstrip('/') + os.path.sep)\n\nFINE_DOWNLOAD = colored('\\nDone, successful download!', 'green')\nERROR_DOWNLOAD = colored('\\nERROR download, no such file or directory!', 'red')\n\n\ndef run_parser():\n page = urlopen(CORRECTED_INPUT_URL).read().decode('utf-8')\n doc = fromstring(page)\n ver = doc.cssselect('#topbar')[0].cssselect('p')[0].cssselect('b > i')[0].text\n\n correct_name = False\n\n for tr in doc.cssselect(SELECTOR):\n src = tr.cssselect('img')[0].get('src')\n name = tr.cssselect('a')[1].text.rstrip(' /') + '/'\n\n if name == INPUT_SOURCE:\n correct_name = True\n\n if src == '/icons/folder.gif':\n create_dir(FOLDER_DESTINATION)\n break\n elif src != '/icons/back.gif':\n file_url = URL.rstrip('/') + '?raw=' + ver\n script = urlopen(file_url).read().decode('utf-8')\n\n create_dir(FILE_DESTINATION)\n\n with open(FILE_DESTINATION + INPUT_SOURCE.rstrip('/'), 'w', encoding='utf-8') as f:\n f.write(script)\n\n print(FINE_DOWNLOAD, '\\n')\n return\n\n if not correct_name:\n print(ERROR_DOWNLOAD, '\\n')\n return\n\n parsing(URL, FOLDER_DESTINATION, ver)\n\n print(FINE_DOWNLOAD, '\\n')\n\n\ndef parsing(url, source, ver):\n page = urlopen(url).read().decode('utf-8')\n doc = fromstring(page)\n\n for tr in doc.cssselect(SELECTOR):\n src = tr.cssselect('img')[0].get('src')\n name = tr.cssselect('a')[1].text.rstrip(' /')\n\n if src == '/icons/folder.gif':\n sub_folder = source + name + os.path.sep\n sub_folder_url = urljoin(url, name)\n\n create_dir(sub_folder)\n parsing(sub_folder_url, sub_folder, ver)\n\n if src != '/icons/back.gif' and src != '/icons/folder.gif':\n file_url = urljoin(url, name + '?raw=' + ver)\n script = urlopen(file_url).read().decode('utf-8')\n\n with open(source + name, 'w', encoding='utf-8') as f:\n f.write(script)\n\n\ndef create_dir(path):\n try:\n os.makedirs(path)\n except OSError as ex:\n if ex.errno == 17 and os.path.isdir(path):\n pass\n\n\ndef main():\n run_parser()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":3553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"326299409","text":"#Can be called either using two nodes u, v, an edge tuple (u, v), or an edge tuple (u, v, key).\nG = nx.MultiGraph() # or MultiDiGraph\nnx.add_path(G, [0, 1, 2, 3])\nG.has_edge(0, 1) # using two nodes\nTrue\ne = (0, 1)\nG.has_edge(*e) # e is a 2-tuple (u, v)\nTrue\nG.add_edge(0, 1, key='a')\n\n\n'a'\nG.has_edge(0, 1, key='a') # specify key\nTrue\ne=(0, 1, 'a')\nG.has_edge(*e) # e is a 3-tuple (u, v, 'a')\nTrue\n#The following syntax are equivalent:\nG.has_edge(0, 1)\nTrue\n1 in G[0] # though this gives :exc:`KeyError` if 0 not in G\nTrue\n","sub_path":"Multidigraph/Python/has_edge.py","file_name":"has_edge.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"519801036","text":"\n# 載入 MNIST 資料庫的訓練資料,並自動分為『訓練組』及『測試組』\nimport os\nfrom keras.datasets import mnist\n#data_folder = os.path.join(os.getcwd(), \"datasets/mnist.npz\")\n(X_train, y_train), (X_test, y_test) = mnist.load_data() #path=data_folder)\n\nimport matplotlib.pyplot as plt\n\nfig, ax = plt.subplots(nrows=2, ncols=5, sharex=True, sharey=True,)\n\n# Method 1\n# ax = ax.flatten()\n# for i in range(10):\n# # img = X_train[y_train == i][0].reshape(28, 28)\n# img = X_train[y_train == i][0]\n# # ax[i].imshow(img, cmap='Greys')\n# ax[i].imshow(img, cmap=plt.get_cmap('gray'))\n\n# Method 2\nfor j in range(2):\n for i in range(5):\n img = X_train[y_train == i + 5 * j][0]\n ax[j, i].imshow(img, cmap=plt.get_cmap('gray'))\n\n# ax[0].set_xticks([])\n# ax[0].set_yticks([])\nplt.tight_layout()\n# plt.savefig('images/12_5.png', dpi=300)\nplt.show()\n","sub_path":"深度學習模型優化與梯度下降法 (new)/code/ShowMnistImage.py","file_name":"ShowMnistImage.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"617711434","text":"from PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtWidgets import *\nfrom desktop_ui.main import *\nimport cv2\nimport sys\nimport numpy as np\nimport PIL.Image as Image\nimport PIL.ImageDraw as ImageDraw\nimport PIL.ImageFont as ImageFont\nfrom utils.global_variables import *\nfrom desktop_ui.train import *\nfrom detectors.detector import *\nfrom controllers import service_controller\nimport threading\n\nclass TrainUI(QtWidgets.QDialog, Ui_Dialog):\n __timer_camera = None\n __timer_detect = None\n __cap_camera = None\n __controller = None\n __is_detecting = False\n __count_samples = 0\n __part_number = ''\n\n def __init__(self, controller):\n super(TrainUI, self).__init__()\n try:\n self.setupUi(self)\n self.__timer_camera = QTimer()\n self.__timer_detect = QTimer()\n self.le_part_number.setPlaceholderText(\"Part Number\")\n self.pbtn_close.clicked.connect(self._close)\n self.pbtn_sample.clicked.connect(self._sample)\n self.pbtn_train.clicked.connect(self._train)\n self.__timer_camera.timeout.connect(self._nextFrameSlot_Camera)\n self.__timer_detect.timeout.connect(self._nextFrameSlot_Detect)\n self.__timer_camera.start(TIMER_INTERVAL)\n\n self.__controller = controller\n except Exception as ex:\n print(ex)\n\n\n def _showWarningMessage(self, msg):\n msgBox = QMessageBox()\n msgBox.setIcon(QMessageBox.Warning)\n msgBox.setText(msg)\n msgBox.setStandardButtons(QMessageBox.Ok)\n msgBox.exec_()\n\n\n def _sample(self):\n self.__count_samples = 0\n self.__part_number = self.le_part_number.text()\n if self.__part_number != \"\":\n self.__timer_detect.start(TIMER_INTERVAL_DETECT)\n else:\n self._showWarningMessage(\"Please input a valid part number\")\n\n\n def _train(self):\n self.__part_number = self.le_part_number.text()\n self.__controller.train_classifier_from_scratch()\n # if self.__part_number != \"\":\n # class_name = DATA_PREFIX + self.__part_number\n # data_dir = self._get_sample_dir(self.__part_number)\n # image_paths = [os.path.join(data_dir, image_name) for image_name in os.listdir(data_dir)]\n # print(data_dir)\n # print(image_paths)\n # # self.__controller.train_classifier(image_paths, class_name)\n # self.__controller.train_classifier_from_scratch()\n # else:\n # self._showWarningMessage(\"Please input a valid part number\")\n\n\n def _get_sample_dir(self, part_number):\n part_folder_name = DATA_PREFIX + part_number\n sample_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), DATASET_FOLDER, 'train', part_folder_name)\n if not os.path.exists(sample_dir):\n os.mkdir(sample_dir)\n # else:\n # os.rmdir(sample_dir)\n # os.mkdir(sample_dir)\n return sample_dir\n\n\n def _close(self):\n if self.__cap_camera != None:\n self.__cap_camera.release()\n self.close()\n\n\n def _nextFrameSlot_Camera(self):\n try:\n if self.__cap_camera == None:\n self.__cap_camera = cv2.VideoCapture(0)\n ret, img = self.__cap_camera.read()\n if(ret == True):\n # smallImg = cv2.resize(self.cvImage, (500, 400), None, 0, 0, cv2.INTER_CUBIC)\n\n img_new = cv2.resize(img, (TRAIN_WINDOW_WIDTH, TRAIN_WINDOW_HEIGHT), None, 0, 0, cv2.COLOR_BGR2RGB)\n height, width, byteValue = img_new.shape\n byteValue = byteValue * width\n\n qImage = QtGui.QImage(cv2.cvtColor(img_new, cv2.COLOR_BGR2RGB), width, height, byteValue, QtGui.QImage.Format_RGB888)\n pix = QtGui.QPixmap.fromImage(qImage)\n self.l_video.setPixmap(pix)\n else:\n self.__cap_camera = None\n self.__timer_camera.stop()\n return 0\n except Exception as ex:\n print(ex)\n self.__timer_camera.stop()\n self.__cap_camera.release()\n\n\n def _nextFrameSlot_Detect(self):\n if self.__cap_camera != None and not self.__is_detecting:\n ret, img = self.__cap_camera.read()\n if(ret == True):\n self.__is_detecting = True\n img_new = cv2.resize(img, (TRAIN_WINDOW_WIDTH, TRAIN_WINDOW_HEIGHT), None, 0, 0, cv2.COLOR_BGR2RGB)\n #self._detect(img_new)\n t = threading.Thread(target=self._detect, args=(img_new,))\n t.start()\n\n\n def _fill_sample_box(self, img):\n try:\n width, height = 130, 76\n img_new = cv2.resize(img, (width, height))\n _, _, byteValue = img_new.shape\n byteValue = byteValue * width\n qImage = QtGui.QImage(cv2.cvtColor(img_new, cv2.COLOR_BGR2RGB), width, height, byteValue, QtGui.QImage.Format_RGB888)\n pix = QtGui.QPixmap.fromImage(qImage)\n if self.__count_samples == 1:\n self.l_img1.setPixmap(pix)\n elif self.__count_samples == 2:\n self.l_img2.setPixmap(pix)\n elif self.__count_samples == 3:\n self.l_img3.setPixmap(pix)\n elif self.__count_samples == 4:\n self.l_img4.setPixmap(pix)\n elif self.__count_samples == 5:\n self.l_img5.setPixmap(pix)\n elif self.__count_samples == 6:\n self.l_img6.setPixmap(pix)\n elif self.__count_samples == 7:\n self.l_img7.setPixmap(pix)\n else:\n self.l_img8.setPixmap(pix)\n except Exception as ex:\n print(ex)\n\n def _detect(self, img):\n try:\n print('detecting')\n coordinates = self.__controller.detect(img)\n print(coordinates)\n if len(coordinates.items()) > 0:\n if self.__count_samples <= 8:\n key, coordinate = coordinates.popitem()\n img_cropped = self.__controller.crop(img, coordinate)\n self.__count_samples += 1\n print(key, coordinate)\n sample_dir = self._get_sample_dir(self.__part_number)\n file_path = os.path.join(sample_dir,DATA_PREFIX + str(self.__count_samples) + '.jpg')\n cv2.imwrite(file_path, img_cropped)\n self._fill_sample_box(img_cropped)\n except Exception as ex:\n print(ex)\n finally:\n self.__is_detecting = False","sub_path":"src/desktop_ui/train_ui_bk.py","file_name":"train_ui_bk.py","file_ext":"py","file_size_in_byte":6684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"105252695","text":"from itertools import accumulate\r\nn = int(input())\r\na = [0] + list(accumulate(map(int, input().split())))\r\ns = [0]\r\ni = 1\r\nr = -10 ** 15\r\nprint(a)\r\nwhile s[-1] < n:\r\n s.append(s[-1] + i)\r\n i += 1\r\n print(s)\r\nfor i in range(n):\r\n while i + s[-1] > n:\r\n s.pop()\r\n print(\"after s\",s)\r\n r = max(r, a[i + s[-1]] - a[i])\r\nprint(r)\r\n","sub_path":"Best index(another method).py","file_name":"Best index(another method).py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"648988202","text":"from collections import Counter\nS = input()\n\nif len(S) == 1:\n print('Yes' if int(S) % 8 == 0 else 'No')\nelif len(S) == 2:\n print('Yes' if int(S) % 8 == 0 or int(S[1] + S[0]) % 8 == 0 else 'No')\nelse:\n tmp = Counter(S)\n ans = False\n \n for i in range(0, 1000, 8):\n t = str(i)\n if i < 10:\n t = '00' + t\n elif i < 100:\n t = '0' + t\n x = True\n y = {}\n for j in t:\n if not tmp.get(j):\n x = False\n if y.get(j):\n y[j] += 1\n else:\n y[j] = 1\n if not x:\n continue\n \n if tmp[t[0]] >= y[t[0]] and tmp[t[1]] >= y[t[1]] and tmp[t[2]] >= y[t[2]]:\n ans = True\n break\n \n if ans:\n print('Yes')\n else:\n print('No')\n \n","sub_path":"contest/abc181/d.py","file_name":"d.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"380144282","text":"# App.py ka hai ye saara code\n# import sqlite3\nfrom flask_restful import Resource, reqparse\nfrom flask_jwt import JWT, jwt_required\nfrom models.item import ItemModel\n\nitems = []\n\nclass Item(Resource):\n\n parser = reqparse.RequestParser()\n parser.add_argument('price',type=float,required=True,help=\"Can't left blank\")\n \n @jwt_required() # This will make the JWT token necessary to perform the function\n def get(self, name):\n item =ItemModel.find_by_name(name)\n if item:\n return item.json()\n return {'message':'Item not found'}, 404 \n # item = next(filter(lambda x:x['name'] == name,items),None)\n # # for item in items:\n # # if item['name'] == name:\n # # return item\n # return {'item':item}, 200 if item else 404 # Status code for Error\n\n def post(self, name):\n if ItemModel.find_by_name(name):\n return {'message':\"An item with name '{}' already exists\".format(name)}, 400\n\n data = Item.parser.parse_args()\n item = ItemModel(name, data['price'])\n \n try:\n item.insert()\n # ItemModel.insert(item)\n except:\n return {'message':\"Eror occured inserting\"} \n\n return item.json(), 501 # INTERNAL server error\n \n\n def delete(self, name):\n\n item = ItemModel.find_by_name(name)\n if item:\n item.delete_from_db()\n\n return {'message': 'Item Deleted'} \n\n # connection = sqlite3.connect('data.db')\n # cursor = connection.cursor()\n\n # query = \"DELETE FROM items WHERE name=?\"\n # cursor.execute(query,(name,))\n\n # connection.commit()\n # connection.close()\n\n # # global items\n # # items = list(filter(lambda x:x['name'] != name,items))\n # return {'message': 'Item Deleted'}\n\n\n def put(self, name):\n data = Item.parser.parse_args()\n # data = request.get_json()\n \n item = ItemModel.find_by_name(name)\n # updated_item = ItemModel(name,data['price']) \n \n if item is None:\n item = ItemModel(name, data['price'])\n # try:\n\n # # updated_item.insert()\n # # ItemModel.insert(updated_item)\n # except:\n # return {'message':\"ERROR\"} \n else:\n item.price = data['price']\n # try:\n # updated_item.update()\n # # ItemModel.update(updated_item) \n # except:\n # return {'message':\"ERROR\"} \n item.save_to_db()\n return item.json()\n\n # item = next(filter(lambda x: x['name'] == name,items),None)\n # if item is None:\n # item = {'name':name,'price':data['price']}\n # items.append(item)\n # else:\n # item.update(item) \n # return item \n\n \nclass ItemList(Resource):\n def get(self):\n {'items': [item.json() for item in ItemModel.query.all()]}\n # connection = sqlite3.connect('data.db')\n # cursor = connection.cursor()\n\n # query = \"SELECT * FROM items\"\n # result = cursor.execute(query)\n # items = []\n # for row in result:\n # items.append({'name':row[0],'price':row[1]})\n\n # connection.close()\n\n # return {'items':items }\n","sub_path":"resources/item.py","file_name":"item.py","file_ext":"py","file_size_in_byte":3357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"550393535","text":"import numpy as np\nimport matplotlib.pyplot as pylab\n\ndef make_year_list (year_line):\n tokens = year_line.split()\n year = int(tokens[0])\n # want to build a list of floats, not strings\n rainfall = [float(x) for x in tokens[1:]]\n return (year, rainfall)\n\ndef build_table():\n table = dict()\n f = open('../../data/njrainfall.txt', 'r')\n for year in f:\n record = make_year_list(year)\n table[record[0]] = record[1]\n f.close()\n return table;\n\ndef get_all_years(year_table, month):\n # each element in year_table is a tuple with two entries\n # entry 0 is the year\n # entry 1 is the list of monthly rainfalls for the year\n # so compile a list of only the specific month from all years\n return [ year_table[year][month] for year in year_table ]\n\ndef find_average(year_table, month) :\n all_years = get_all_years(year_table, month)\n total = sum(all_years)\n return total / len(all_years)\n\ndef find_min(year_table, month) :\n return min(get_all_years(year_table, month))\n\ndef find_max(year_table, month) :\n return max(get_all_years(year_table, month))\n\ndef get_minimums(year_table):\n months = []\n for i in range(12):\n months.append(find_min(year_table, i))\n return months\n\ndef get_maximums(year_table):\n months = []\n for i in range(12):\n months.append(find_max(year_table, i))\n return months\n\ndef get_averages(year_table):\n months = []\n for i in range(12):\n months.append(find_average(year_table, i))\n return months\n\ndef get_months(year_table, year):\n months = []\n for i in range(12):\n months.append(year_table[year][i])\n return months\n\ndef get_total(year_table, year):\n total = 0\n for i in range(12):\n total += (year_table[year][i])\n return total\n\ndef get_totals(year_table) :\n totals = []\n for y in year_table:\n totals.append(get_total(year_table, y))\n return totals\n\n\ndef resolve_month(user_input):\n try :\n m = int(user_input)\n except ValueError:\n # must be a string...\n if user_input in month_strings:\n return month_strings.index(user_input)\n else :\n raise ValueError(user_input + \" is not a valid month string\")\n\n # note, m is an int if we are here, because the except\n # block returns or raises an exception\n if m < 1 or m > 12 :\n raise ValueError(user_input + \" is not a valid month number (1-12)\")\n else:\n return m-1\n\nyear_table = build_table()\nfirst_year = min(year_table.keys())\nmonth_strings = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', \n 'October', 'November', 'December']\nprint(\"Loaded rainfall data for NJ from\", first_year, \"through\", max(year_table.keys()))\ndone = False\nwhile done == False:\n print(\"Plotting options:\")\n print(\"1) Plot of rainfall over a given year (x-axis is months, y-axis is rainfall)\")\n print(\"2) Plot of yearly rainfall totals (x axis is years, y-axis is rainfall total for that year)\")\n print(\"3) Plot of monthly averages, min, max (x-axis is months, y-axis is average/min/max as separate data points)\")\n print(\"q) Quit\")\n choice = input(\"Please select a plot: \")\n\n if choice == 'q' or choice == 'Q':\n done = True\n elif choice == '1':\n year = int(input(\"What year would you like to plot? \"))\n pylab.figure(\"Monthly Rainfall for \" + str(year))\n pylab.plot(range(len(month_strings)), get_months(year_table, year))\n pylab.xticks(range(len(month_strings)), month_strings, size='small')\n pylab.ylabel('Rainfall (inches)')\n pylab.show()\n elif choice == '2':\n pylab.figure(\"Yearly Rainfall - \" + str(min(year_table.keys())) + \"-\" + str(max(year_table.keys())))\n pylab.plot(range(min(year_table.keys()),max(year_table.keys())+1), get_totals(year_table))\n pylab.ylabel('Rainfall (inches)')\n pylab.show()\n elif choice == '3':\n pylab.figure(\"Monthly Rainfall Averages\")\n pylab.plot(range(len(month_strings)), get_averages(year_table))\n pylab.plot(range(len(month_strings)), get_minimums(year_table))\n pylab.plot(range(len(month_strings)), get_maximums(year_table))\n pylab.xticks(range(len(month_strings)), month_strings, size='small')\n pylab.ylabel('Rainfall (inches)')\n pylab.show()","sub_path":"source/courses/cmps367/exercises/pe26/pe26.py","file_name":"pe26.py","file_ext":"py","file_size_in_byte":4365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"107860315","text":"import sqlite3\n\n\ndef fetching(roll):\n connection = sqlite3.connect(\"Attendance2.db\")\n crsr = connection.cursor()\n crsr.execute(\"SELECT * FROM attend WHERE roll_no=('{}') \".format(roll))\n rows = crsr.fetchall()\n for row in rows:\n print(\"enrollment number =\", row[1])\n enrollment_no = row[1]\n print(\"Name=\", row[2])\n name = row[2]\n count = 0\n s = 0\n for i in row:\n count = count+1\n if(i=='p'):\n s = s+1\n p = (s/(count-3))*100\n print(\"Total Number of Days\", (count-3))\n total_days = count-3\n print(\"Number of days Present\", s)\n total_present_days = s\n print(\"Percentage=\", p)\n precentage = p\n\n return enrollment_no, name, total_days, total_present_days, precentage\n\n\n connection.commit()\n connection.close()\n\n\n","sub_path":"Smart_Attendance_System/face_recognition/Face_Recognition/fetch.py","file_name":"fetch.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"253516074","text":"\nimport numpy as np\nimport tkinter as tk\nfrom tkinter.ttk import *\nfrom tkinter import scrolledtext\nfrom tkinter import filedialog\nimport time\nimport matplotlib\nmatplotlib.use('TkAgg')\n\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits import mplot3d\n\n\nimport transport_class\nimport burgers_class\nimport shallow_water_class\nimport tools\n\ndef isnan(x): return type(x) is float and x != x\ndef isinf(x): inf = 1e5000; return x == inf or x == -inf\n\nclass App:\n pbl = 0\n def __init__ (self):\n print (\"->\\tinit App object class.\")\n\n def _quit():\n self.root.quit ()\n self.root.destroy ()\n\n # tkinter root\n self.root = tk.Tk()\n self.root.title(\"T-B-S.W.E\")\n\n # Gets the requested values of the height and widht.\n windowWidth = self.root.winfo_reqwidth()\n windowHeight = self.root.winfo_reqheight()\n # Gets both half the screen width/height and window width/height\n positionRight = int(self.root.winfo_screenwidth()/2 - 3*windowWidth/2)\n positionDown = int(self.root.winfo_screenheight()/2 - 3*windowHeight/2)\n\n # Positions the window in the center of the page.\n self.root.geometry(\"+{}+{}\".format(positionRight, positionDown))\n\n # tkinter configure\n tk.Grid.rowconfigure(self.root, 0, weight=1)\n tk.Grid.columnconfigure(self.root, 0, weight=1)\n\n ## frame_1\n self.row_index_frame_1 = 0\n\n def row_index ():\n self.row_index_frame_1 += 1\n return self.row_index_frame_1 - 1\n\n\n self.frame_1 = tk.Frame (master=self.root)\n frame_1 = self.frame_1\n\n # tk.Button (master = frame_1, text = \"Tests\", width = 20, command =self.tests).grid (row=row_index (), column = 0)\n\n ### frame_12\n frame_12 = tk.Frame (master=frame_1, bd=0)\n\n TYPES = [(\"Transport\", \"Transport\"), (\"Burgers\", \"Burgers\"), (\"Shallow water\", \"ShallowWater\"),]\n\n self.typeproblem = tk.StringVar()\n self.typeproblem.set(\"Transport\")\n\n index_j = 0\n for text, mode in TYPES:\n b = tk.Radiobutton(master=frame_12, text=text, variable=self.typeproblem, value=mode, indicatoron=1)\n b.grid (row=index_j, column=1, columnspan=3, padx=2, pady=2, sticky=\"NW\")\n index_j += 1\n\n frame_12.grid (row=row_index (), column=0, pady=20, sticky=\"N\")\n\n ### end frame_12\n ### frame_11\n frame_11 = tk.Frame (master=frame_1, bd=0)\n\n DIM = [(\"1D\", \"1\"), (\"2D\", \"2\"),]# (\"3D\", \"3\"),]\n\n self.dim = tk.StringVar()\n self.dim.set(\"1\") # initialize\n\n index_i = 0\n for text, mode in DIM:\n b = tk.Radiobutton(master=frame_11, text=text, variable=self.dim, value=mode, indicatoron=0)\n b.grid (row=0, column=index_i, columnspan=1,padx=20, pady=10, sticky=\"N\")\n index_i += 1\n\n frame_11.grid (row=row_index (), column=0, sticky=\"n\")\n\n ### end frame_11\n\n self.load_vtk = tk.IntVar()\n tk.Radiobutton(master=frame_11, text=\"Build mesh from scratch\", variable=self.load_vtk, value=0, indicatoron=1).grid (row=row_index (), column = 0, sticky='nw', columnspan=4, padx = 10)\n tk.Radiobutton(master=frame_11, text=\"Load VTK\", variable=self.load_vtk, value=1, indicatoron=1).grid (row=row_index (), column = 0, sticky='nw', columnspan=4, padx = 10)\n\n self.periodic = tk.IntVar()\n self.periodic.set (0)\n tk.Checkbutton (master=frame_11, text=\"Periodicity (1D)\", variable=self.periodic).grid (row=row_index (), column = 0, sticky='nw', columnspan=4, padx = 10, pady=10)\n\n self.imposeBoundary = tk.IntVar()\n self.imposeBoundary.set (0)\n tk.Checkbutton (master=frame_11, text=\"Impose boundary conditions\", variable=self.imposeBoundary).grid (row=row_index (), column = 0, sticky='nw', columnspan=4, padx = 10, pady=10)\n\n\n ### frame_13\n frame_13 = tk.Frame (master=frame_1, bd=0)\n tk.Label (master=frame_13, text= \"dt = \").grid (row=0, column=0, sticky=\"ne\")\n self.dt = tk.StringVar()\n self.dt.set (\"0.01\")\n tk.Entry (master=frame_13, show=\"\", width=20, textvariable=self.dt).grid (row=0, column=1, sticky=\"n\")\n\n tk.Label (master=frame_13, text= \"T = \").grid (row=1, column=0, sticky=\"ne\")\n self.T = tk.StringVar()\n self.T.set (\"10\")\n tk.Entry (master=frame_13, show=\"\", width=20, textvariable=self.T).grid (row=1, column=1, sticky=\"n\")\n\n tk.Label (master=frame_13, text= \"CFL : nu = \").grid (row=2, column=0, sticky=\"ne\")\n self.nu = tk.StringVar()\n self.nu.set (\"0.99\")\n tk.Entry (master=frame_13, show=\"\", width=20, textvariable=self.nu).grid (row=2, column=1, sticky=\"n\")\n\n frame_13.grid (row=row_index (), column=0, sticky=\"nw\", pady=10)\n ### end frame_13\n self.cfl_checkbox = tk.IntVar()\n self.cfl_checkbox.set (1)\n tk.Checkbutton (master=frame_1, text=\"Use CFL for dt\", variable=self.cfl_checkbox).grid (row=row_index (), column = 0, sticky='nsew', padx = 10)\n\n frame_14 = tk.Frame (master=frame_1, bd=0)\n\n SCHEME = [(\"Up-wind conservative\", \"upwind\"), (\"Lax-Friedrichs\", \"laxfriedrichs\"), (\"Lax-Wendroff\", \"laxwendroff\"), (\"Godunov\", \"godunov\"),]# (\"Godunov\", \"godunov\"), (\"Godunov\", \"godunov\"),]\n\n\n self.scheme = tk.StringVar()\n self.scheme.set(\"upwind\") # initialize\n\n index_i = 1\n for text, mode in SCHEME:\n b = tk.Radiobutton(master=frame_14, text=text, variable=self.scheme, value=mode, indicatoron=1)\n b.grid (row=index_i, column=0, columnspan=1,padx=20, pady=0, sticky=\"NW\")\n index_i += 1\n\n frame_14.grid (row=row_index (), column=0, sticky=\"n\", pady=10)\n\n def onclick (event):\n self.run ()\n\n self.root.bind('', onclick)\n\n tk.Button (master = frame_1, text = \"Run\", width = 20, command =self.run).grid (row=row_index (), column = 0)\n\n\n tk.Button (master = self.frame_1, text = \"Play in PLT\", width = 20, command = self.plot).grid (row=row_index (), column = 0)\n\n frame_14 = tk.Frame (master=frame_1, bd=0)\n self.animate = tk.IntVar()\n self.animate.set (1)\n tk.Checkbutton (master=frame_14, text=\"Animate\", variable=self.animate).grid (row=0, column = 0, sticky='nsew', columnspan=1, padx = 0, pady=0)\n tk.Label (master=frame_14, text= \"| StepPLT t :\").grid (row=0, column=1, sticky=\"ne\")\n self.step_time = tk.StringVar()\n self.step_time.set (\"10\")\n tk.Entry (master=frame_14, show=\"\", width=5, textvariable=self.step_time).grid (row=0, column=2, sticky=\"n\")\n frame_14.grid (row=row_index (), column=0, sticky=\"nw\", pady=10)\n self.rescale = tk.IntVar()\n self.rescale.set (1)\n tk.Checkbutton (master=frame_14, text=\"Rescale plot each step\", variable=self.rescale).grid (row=1, column = 0, sticky='nsew', columnspan=3, padx = 0, pady=0)\n\n def writeVTKwithScalars ():\n if self.pbl.pdata.GetNumberOfCells == 0 or self.pbl.pdata.GetNumberOfPoints == 0:\n return\n self.pbl.writeVTK ()\n\n def writeVTKwithoutScalars ():\n if self.pbl.pdata.GetNumberOfCells == 0 or self.pbl.pdata.GetNumberOfPoints == 0:\n return\n tools.writeVTK (self.pbl.pdata, \"./outputs/output_withoutscal.vtk\")\n\n tk.Button (master = frame_1, text = \"Export in VTK no scalars\", width = 20, command =writeVTKwithScalars).grid (row=row_index (), column = 0)\n tk.Button (master = frame_1, text = \"Export in VTK w/ scalars\", width = 20, command =writeVTKwithoutScalars).grid (row=row_index (), column = 0)\n\n\n frame_1.grid (row=0, column=0, sticky=\"nsew\", padx=10, pady=10)\n ## end frame_1\n\n ## scrolledtext\n self.txt = scrolledtext.ScrolledText (master=self.root, width=50, height=30)\n self.txt.grid(row=0, column=1,sticky='nsew', padx=10, pady=10)\n ## end scrolledtext\n\n tk.Button (master = self.root, text = \"Quit\", width = 20, command =_quit).grid (row=1, column = 0, sticky=\"nsew\", padx=10, pady=10)\n\n def set_progress (value):\n self.progress['value'] = value\n self.root.update_idletasks()\n\n if value >= 0 and value <= 100:\n self.progress.grid(row=1, column=1,sticky='nsew', padx=10, pady=10)\n if value > 100 or value < 0:\n self.progress.grid_forget ()\n\n\n self.progress = Progressbar(master=self.root, orient = tk.HORIZONTAL,\n length = 100, mode = 'determinate')\n self.progress.grid(row=1, column=1,sticky='nsew', padx=10, pady=10)\n self.fun_set_progress = set_progress\n\n set_progress (-1)\n\n def mainloop (self):\n self.root.mainloop ()\n\n def disp (self, a):\n print (a)\n self.txt.insert(tk.INSERT, a)\n self.txt.insert(tk.INSERT, '\\n')\n self.root.update_idletasks()\n\n def tests (self):\n \"\"\"tests windows\"\"\"\n\n root = tk.Tk()\n root.title(\"Tests\")\n # Gets the requested values of the height and widht.\n windowWidth = root.winfo_reqwidth()\n windowHeight = root.winfo_reqheight()\n # Gets both half the screen width/height and window width/height\n positionRight = int(root.winfo_screenwidth()/3 - 3*windowWidth/2)\n positionDown = int(root.winfo_screenheight()/2 - 3*windowHeight/2)\n\n # Positions the window in the center of the page.\n root.geometry(\"+{}+{}\".format(positionRight, positionDown))\n\n # tkinter configure\n tk.Grid.rowconfigure(root, 0, weight=1)\n tk.Grid.columnconfigure(root, 0, weight=1)\n\n tk.Label (master=root, text= \"Test for the ** equation on a 1D\\nand 2D domain for several different numerical\\n flows and calculation of the different errors.\\n\", font = \"Helvetica 9 italic\").grid (row=0, column=0, sticky=\"nw\")\n\n def test_transport ():\n self.pbl = transport_class.transport ()\n def test_burgers ():\n self.pbl = burgers_class.burgers ()\n def test_shallow ():\n self.pbl = shallow_water_class.shallow_water ()\n\n tk.Button (master = root, text = \"Transport\", width = 20, command =test_transport).grid (row=1, column = 0)\n tk.Button (master = root, text = \"Burgers\", width = 20, command =test_burgers).grid (row=2, column = 0)\n tk.Button (master = root, text = \"Shallow Water\", width = 20, command =test_shallow).grid (row=3, column = 0)\n # tk.Button (master = root, text = \"Shallow Water\", width = 20, command =self.run).grid (row=4, column = 0)\n\n\n def run (self):\n if self.dim.get () == \"\" or self.T.get () == \"\":\n return\n\n self.txt.delete('1.0', tk.END)\n\n self.pbl = 0\n if self.typeproblem.get () == \"Transport\":\n self.pbl = transport_class.transport ()\n elif self.typeproblem.get () == \"Burgers\":\n self.pbl = burgers_class.burgers ()\n else:\n self.pbl = shallow_water_class.shallow_water ()\n\n self.disp (\"Equation : {}\".format (self.typeproblem.get ()))\n\n self.pbl.disp = self.disp\n disp = self.disp\n pdata = 0\n if int (self.load_vtk.get ()) == 0:\n if int (self.dim.get ()) == 1:\n pdata = tools.clean (tools.gmsh1D ([[0.], [1.]], [0.01, 0.01]))\n if int (self.dim.get ()) == 2:\n pdata = tools.clean (tools.gmsh2D ([[0., 0., 0.], [1., 0., 0.], [1., 1., 0.], [0., 1., 0.]], [0.05, 0.05, 0.05, 0.05]))\n else:\n filename = filedialog.askopenfilename(initialdir = \".\",title = \"Select file\", filetypes = ((\"vtk files\",\"*.vtk\"),(\"all files\",\"*.*\")))\n self.disp (\"Load VTK : {}\".format (filename))\n pdata = tools.readVTK (filename)\n\n self.pbl.setPdata (pdata)\n\n if self.pbl.pdata.GetNumberOfCells == 0 or self.pbl.pdata.GetNumberOfPoints == 0:\n return\n\n self.pbl.buildInterfaces ()\n self.pbl.defineCond_init ()\n\n self.pbl.useCFL = False\n self.pbl.isPeriodic = False\n\n if self.cfl_checkbox.get () == 1:\n self.pbl.useCFL = True\n\n if self.periodic.get () == 1:\n self.pbl.isPeriodic = True\n\n if self.imposeBoundary.get () == 1:\n self.pbl.imposeBoundary = True\n\n self.pbl.dt = float (self.dt.get ())\n self.pbl.T = float (self.T.get ())\n self.pbl.cfl_nu = float (self.nu.get ())\n\n self.pbl.name_numericalFlow = self.scheme.get ()\n if self.scheme.get () == \"upwind\":\n self.pbl.numericalFlow = self.pbl.up_wind\n elif self.scheme.get () == \"laxfriedrichs\":\n self.pbl.numericalFlow = self.pbl.lax_friedrichs\n elif self.scheme.get () == \"laxwendroff\":\n self.pbl.numericalFlow = self.pbl.lax_wendroff\n elif self.scheme.get () == \"godunov\":\n self.pbl.numericalFlow = self.pbl.godunov\n elif self.scheme.get () == \"maccormak\":\n self.pbl.numericalFlow = self.pbl.mac_cormak\n else:\n self.pbl.numericalFlow = self.pbl.up_wind\n\n self.pbl.analysis ()\n\n self.pbl.iterate (self.fun_set_progress)\n self.plot ()\n\n\n def plot (self, step = 1, animate = True):\n self.disp (\"->\\tplot, anim = {}, step_time = {}\".format (animate, step))\n\n if self.pbl.pdata.GetNumberOfCells == 0 or self.pbl.pdata.GetNumberOfPoints == 0:\n return\n\n animate = self.animate.get ()\n step = int (self.step_time.get ())\n plt.clf()\n fig = plt.figure (1)\n axs = {}\n num = self.pbl.fileNameSol.shape [0]\n\n for i in np.arange (num):\n if self.pbl.dim == 1:\n axs [i] = fig.add_subplot(1, num, i+1)\n else:\n axs [i] = fig.add_subplot(1, num, i+1, projection='3d')\n axs [i].cla ()\n\n files = {}\n for i in np.arange (num):\n files [i] = open (self.pbl.fileNameSol [i], \"r+\")\n\n i = 1\n sol_max = np.array ([0.0 for p in self.pbl.fileNameSol])\n sol_min = np.array ([0.0 for p in self.pbl.fileNameSol])\n\n for i in np.arange (num):\n sol_max [i] = np.max (self.pbl.cond_init [:, i])\n sol_min [i] = np.min(self.pbl.cond_init [:, i])\n if self.pbl.dim == 1:\n axs [i].set_ylim (sol_min [i] - 1, sol_max [i] + 1)\n else:\n axs [i].set_zlim (sol_min [i] - 1, sol_max [i] + 1)\n\n dt = files [0].readline ()\n if num > 1: # read the first line ==> dt\n temp = files [1].readline ()\n if temp != dt:\n raise ValueError (\"dt are different in multiple files (dt1: {}, dt2: {})\".format (dt, temp))\n exit ()\n\n dt = dt.split (' ') # currently dt = '$dt \\n' ==> dt ['$dt', '\\n']\n dt = float (dt [0])\n\n myBool = True\n\n while myBool:\n for k in np.arange (num):\n file = files [k]\n ax = axs [k]\n\n leg = file.readline () # read the step of time : time current\n if not leg:\n myBool = False\n break # nothing to read => endOfFile\n leg = leg.split (' ')\n leg = float (leg [0]) # same method that dt\n\n sol = file.readline()\n if not sol:\n myBool = False\n break\n if i%step == 0 or i == 1:\n\n sol = sol.split (' ') # same method that dt and leg\n sol = np.asarray ([float (i) for i in sol [:-1]])\n\n plt.gcf().canvas.set_window_title(\"time t = {:.7f} iter = {}\".format (i * dt, i))\n\n if sol.shape [0] != self.pbl.barycenters.shape [0]: # /!\\ sol is not relative to the current system --> not really usefull\n self.disp (\"\\t/!\\\\\\tSize different in plot.\")\n return\n\n if self.animate.get ():\n axs [k].cla ()\n\n if self.pbl.dim == 1:\n axs [k].plot (self.pbl.barycenters [:, 0], sol, '-', label='t:{:.3g}'.format (leg))\n else:\n axs [k].scatter(self.pbl.barycenters [:, 0], self.pbl.barycenters [:, 1], sol, c='r', marker='o')\n\n if self.rescale.get () == 1:\n sol_max [k] = max (np.max (sol), sol_max [k])\n sol_min [k] = min (np.min (sol), sol_min [k])\n\n if not (isnan (sol_min [k]) or isinf (sol_min [k]) or isnan (sol_max [k]) or isinf (sol_max [k])):\n if self.pbl.dim == 1:\n axs [k].set_ylim (sol_min [k] - 0.1, sol_max [k] + 0.1)\n else:\n axs [k].set_zlim (sol_min [k] - 0.1, sol_max [k] + 0.1)\n i = i + 1\n plt.pause (0.00001)\n if not myBool:\n break\n\n axes = plt.gca()\n\n if not animate:\n for k in np.arange (num):\n ax = axs [k]\n box = ax.get_position()\n ax.set_position([box.x0, box.y0, box.width * 0.7, box.height])\n ax.legend (loc='center left', bbox_to_anchor=(1, 0.5), title=\"Time dt : {:.7g}\".format (dt), ncol=2, fancybox=True, shadow=True)\n ax.grid (True)\n\n\n plt.show ()\n","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":17875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"396494309","text":"# Author: Lars Buitinck\n# License: 3-clause BSD\n\nimport numpy as np\nfrom ..base import BaseEstimator\nfrom .base import SelectorMixin\nfrom ..utils import check_array\nfrom ..utils.sparsefuncs import mean_variance_axis, min_max_axis\nfrom ..utils.validation import check_is_fitted\nfrom .univariate_selection import SelectKBest, f_regression\n\nclass CorrelationThreshold(BaseEstimator, SelectorMixin):\n \"\"\"Feature selector that removes all low-variance features.\n\n This feature selection algorithm looks only at the features (X), not the\n desired outputs (y), and can thus be used for unsupervised learning.\n\n Read more in the :ref:`User Guide `.\n\n Parameters\n ----------\n threshold : float, optional\n Features with a training-set correlation higher or equal than this threshold will\n be removed. The default is to keep all non identical features,\n i.e. remove only features that are duplicates of others.\n\n n_features:\n Maximum number of features to be returned.\n If not set return all features, such that the correlation is below the threshold\n\n Attributes\n ----------\n variances_ : array, shape (n_features,)\n Variances of individual features.\n\n Examples\n --------\n The following dataset has integer features, with the left most tow columns being\n linear transformations of the first. These are removed with the default setting for threshold::\n\n >>> X = [[2, 2, -2, 4], [0, 1, 0, 0], [1, 1, -1, 2]]\n >>> selector = CorrelationThreshold()\n >>> selector.fit_transform(X)\n array([[2, 0],\n [1, 4],\n [1, 1]])\n \"\"\"\n\n def __init__(self, threshold=1., n_features=None):\n self.threshold = threshold\n if n_features:\n self.n_features = n_features\n else:\n self.n_features = np.inf\n self.correlations_ = None\n self.mask = None\n\n def fit(self, X, y=None):\n \"\"\"Learn empirical variances from X.\n\n Parameters\n ----------\n X : {array-like, sparse matrix}, shape (n_samples, n_features)\n Sample vectors from which to compute variances.\n\n y : {array-like, sparse matrix}, shape (n_samples, 1)\n If y given, iteratively optimize\n max Phi(S): 1/\\S\\ * sum_(x_i \\in S) I(x_i, y)\n - 1/\\S\\**2 * sum_(x_i \\in S, x_j \\in S) I(x_i, x_j)\n else iteratively optimize:\n max Phi(S): - 1/\\S\\**2 * sum_(x_i \\in S, x_j \\in S) I(x_i, x_j)\n\n with \\S\\ <= n_features\n and max(I(x_i, x_j)) <= threshold\n\n Returns\n -------\n self\n \"\"\"\n X = check_array(X, dtype=float)\n n_samples, n_features = X.shape\n S = np.zeros(n_features, dtype=int)\n\n self.correlations_ = abs(np.corrcoef(X.transpose()))\n self.correlations_[np.isnan(self.correlations_)] = 1\n\n if y is not None:\n sb = SelectKBest(f_regression, \"all\").fit(X, y)\n I_xc = sb.pvalues_\n I_xc[np.isnan(I_xc)] = -1\n else:\n I_xc = np.zeros(n_features)\n\n S[np.argmax(I_xc)] = 1\n\n while sum(S) < self.n_features:\n # filter by threshold:\n S_mask = self.correlations_[S == 1, :].max(axis=0) < (self.threshold - 1.e-8)\n # In case no value fulfills the threshold\n if not np.any(S_mask):\n break\n else:\n # iteratively add an x_i:\n best_i = np.argmax((I_xc - 1./sum(S)*self.correlations_[S == 1, :].sum(axis=0))[S_mask])\n if S[np.where(S_mask)[0][best_i]] == 1:\n print (\"ERROR - trying to set the same value twice\")\n break\n else:\n S[np.where(S_mask)[0][best_i]] = 1\n\n self.mask = S\n\n return self\n\n\n\n def _get_support_mask(self):\n check_is_fitted(self)\n\n return self.mask == 1\n","sub_path":"sklearn/feature_selection/correlation_threshold.py","file_name":"correlation_threshold.py","file_ext":"py","file_size_in_byte":4002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"256736610","text":"# -*- coding: utf-8 -*-\n#!/usr/bin/env python\n\nimport RPi.GPIO as GPIO\nimport time\n\nGPIO.setmode(GPIO.BCM)\n\nsensor = 23\n\n\n\nprint (\"모션 감지센서 준비중\")\ntime.sleep(2)\nwhile True:\n\t\tGPIO.setup(sensor, GPIO.IN)\n\t\tif GPIO.input(sensor):\n\t\t\ttime.sleep(2)\n\t\t\timport sucOrFail\n\t\t\t\n\t\t\tbreak\n\t\t\t\n\t\n\n\t\n\t\n\n\n","sub_path":"iot_openDoor/sensor_all.py","file_name":"sensor_all.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"403507906","text":"import argparse\nimport datetime\nimport os\nimport sys\n\nimport numpy as np\n\nfrom torch.utils.tensorboard import SummaryWriter\n\nimport torch\nimport torch.nn as nn\nfrom torch.optim import SGD, Adam\nfrom torch.utils.data import DataLoader\n\nfrom luna_util.util import enumerateWithEstimate\nfrom .dsets import Luna2dSegmentationDataset, TrainingLuna2dSegmentationDataset, getCt\nfrom luna_util.logconf import logging\nfrom .model import UNetWrapper, SegmentationAugmentation\n\nlog = logging.getLogger(__name__)\n# log.setLevel(logging.WARN)\nlog.setLevel(logging.INFO)\nlog.setLevel(logging.DEBUG)\n\n# Used for computeBatchLoss and logMetrics to index into metrics_t/metrics_a\n# METRICS_LABEL_NDX = 0\n# METRICS_PRED_NDX = 1\n# METRICS_LOSS_NDX = 2\n# METRICS_SIZE = 3\n\nMETRICS_LOSS_NDX = 1\nMETRICS_TP_NDX = 7\nMETRICS_FN_NDX = 8\nMETRICS_FP_NDX = 9\nMETRICS_SIZE = 10\n\n\nclass SegmentationTrainingApp:\n def __init__(self, sys_argv=None):\n if sys_argv is None:\n sys_argv = sys.argv[1:] # get arguments from command line if not provided\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--num-workers', help='Number of processes to use for data loading', default=8, type=int)\n parser.add_argument('--batch-size', help='Batch Size', default=32, type=int)\n parser.add_argument('--augmented', help='Augment the training data', action='store_true', default=False)\n parser.add_argument('--augment-flip', help='Augment the training data by flipping', action='store_true',\n default=False)\n parser.add_argument('--augmented-offset', help='Augment the training data by adding offset',\n action='store_true', default=False)\n parser.add_argument('--augmented-scale', help='Augment the training data by adding scale', action='store_true',\n default=False)\n parser.add_argument('--augmented-rotate', help='Augment the training data by adding rotation',\n action='store_true', default=False)\n parser.add_argument('--augmented-noise', help='Augment the training data by adding noise', action='store_true',\n default=False)\n parser.add_argument('--epochs', help='Number of training epochs', default=1, type=int)\n parser.add_argument('--tb-prefix', help='Tensorboard prefix', default='luna')\n parser.add_argument('comment', help=\"Comment suffix for Tensorboard run.\", nargs='?', default='dwlpt')\n\n self.cli_args = parser.parse_args(sys_argv)\n self.time_str = datetime.datetime.now().strftime('%Y-%m-%d_%H.%M.%S')\n\n self.use_cuda = torch.cuda.is_available()\n self.device = torch.device('cuda' if self.use_cuda else 'cpu')\n\n self.totalTrainingSamples_count = 0\n\n self.trn_writer = None\n self.val_writer = None\n\n self.augmentation_dict = {}\n if self.cli_args.augmented or self.cli_args.augment_flip:\n self.augmentation_dict['flip'] = True\n if self.cli_args.augmented or self.cli_args.augment_offset:\n self.augmentation_dict['offset'] = 0.03\n if self.cli_args.augmented or self.cli_args.augment_scale:\n self.augmentation_dict['scale'] = 0.2\n if self.cli_args.augmented or self.cli_args.augment_rotate:\n self.augmentation_dict['rotate'] = True\n if self.cli_args.augmented or self.cli_args.augment_noise:\n self.augmentation_dict['noise'] = 25.0\n\n self.segmentation_model, self.augmentation_model = self.initModel()\n self.optimizer = self.initOptimizer()\n\n def initModel(self):\n segmentation_model = UNetWrapper(\n in_channels=7,\n n_classes=1,\n depth=3,\n wf=4,\n padding=True,\n batch_norm=True,\n up_mode='upconv'\n )\n augmentation_model = SegmentationAugmentation(**self.augmentation_dict)\n\n if self.use_cuda:\n log.info(\"Using CUDA; {} devices\".format(torch.cuda.device_count()))\n if torch.cuda.device_count() > 1:\n segmentation_model = nn.DataParallel(segmentation_model)\n augmentation_model = nn.DataParallel(augmentation_model)\n segmentation_model = segmentation_model.to(self.device)\n augmentation_model = augmentation_model.to(self.device)\n return segmentation_model, augmentation_model\n\n def initOptimizer(self):\n return Adam(self.segmentation_model.parameters())\n\n def initTrainDl(self):\n train_ds = TrainingLuna2dSegmentationDataset(\n val_stride=10,\n isValSet_bool=False,\n contextSlices_count=3\n )\n batch_size = self.cli_args.batch_size\n if self.use_cuda:\n batch_size *= torch.cuda.device_count()\n\n train_dl = DataLoader(\n train_ds,\n batch_size=batch_size,\n num_workers=self.cli_args.num_workers,\n pin_memory=self.use_cuda\n )\n return train_dl\n\n def initValDl(self):\n val_ds = TrainingLuna2dSegmentationDataset(\n val_stride=10,\n isValSet_bool=True,\n contextSlices_count=3\n )\n batch_size = self.cli_args.batch_size\n if self.use_cuda:\n batch_size *= torch.cuda.device_count()\n\n val_dl = DataLoader(\n val_ds,\n batch_size=batch_size,\n num_workers=self.cli_args.num_workers,\n pin_memory=self.use_cuda\n )\n return val_dl\n\n def initTensorboardWriters(self):\n if self.trn_writer is None:\n log_dir = os.path.join('runs', self.cli_args.tb_prefix, self.time_str)\n\n self.trn_writer = SummaryWriter(log_dir=log_dir + '-trn_cls-' + self.cli_args.comment)\n self.val_writer = SummaryWriter(log_dir=log_dir + '-val_cls-' + self.cli_args.comment)\n\n def main(self):\n log.info(\"Starting {}, {}\".format(type(self).__name__, self.cli_args))\n\n train_dl = self.initTrainDl()\n val_dl = self.initValDl()\n\n for epoch_idx in range(1, self.cli_args.epochs + 1):\n print('Epoch {}/{}, {}/{} batches of size {}*{}'.format(epoch_idx, self.cli_args.epochs, len(train_dl),\n len(val_dl), self.cli_args.batch_size, (\n torch.cuda.device_count() if self.use_cuda else 1)))\n log.info('Epoch {}/{}, {}/{} batches of size {}*{}'.format(epoch_idx, self.cli_args.epochs, len(train_dl),\n len(val_dl), self.cli_args.batch_size, (\n torch.cuda.device_count() if self.use_cuda else 1)))\n\n trnMetrics_t = self.doTraining(epoch_idx, train_dl)\n self.logMetrics(epoch_idx, 'trn', trnMetrics_t)\n\n valMetrics_t = self.doValidation(epoch_idx, val_dl)\n self.logMetrics(epoch_idx, 'val', trnMetrics_t)\n\n if hasattr(self, 'trn_writer'):\n self.trn_writer.close()\n self.val_writer.close()\n\n def doTraining(self, epoch_idx, train_dl):\n self.segmentation_model.train()\n train_dl.dataset.shuffleSamples()\n\n batch_iter = enumerateWithEstimate(\n train_dl,\n 'E{} training'.format(epoch_idx),\n start_ndx=train_dl.num_workers,\n )\n for batch_ndx, batch_tup in batch_iter:\n self.optimizer.zero_grad()\n\n loss_var = self.computeBatchLoss(\n batch_ndx,\n batch_tup,\n train_dl.batch_size,\n trnMetrics_g\n )\n\n loss_var.backward()\n self.optimizer.step()\n\n self.totalTrainingSamples_count += len(train_dl.dataset)\n return trnMetrics_g.to('cpu')\n\n def doValidation(self, epoch_idx, val_dl):\n with torch.no_grad():\n self.segmentation_model.eval()\n\n batch_iter = enumerateWithEstimate(\n val_dl,\n \"E{} Validation \".format(epoch_idx),\n start_ndx=val_dl.num_workers,\n )\n for batch_ndx, batch_tup in batch_iter:\n self.computeBatchLoss(\n batch_ndx, batch_tup, val_dl.batch_size, valMetrics_g)\n\n return valMetrics_g.to('cpu')\n\n def computeBatchLoss(self, batch_ndx, batch_tup, batch_size, metrics_g):\n input_t, label_t, _series_list, _center_list = batch_tup\n\n input_g = input_t.to(self.device, non_blocking=True)\n label_g = label_t.to(self.device, non_blocking=True)\n\n if self.segmentation_model.training and self.augmentation_dict:\n input_g, label_g = self.augmentation_model(input_g, label_g)\n\n prediction_g = self.segmentation_model(input_g)\n\n diceLoss_g = self.diceLoss(prediction_g, label_g)\n fnLoss_g = self.diceLoss(prediction_g * label_g, label_g)\n\n start_ndx = batch_ndx * batch_size\n end_dx = start_ndx + input_t.size(0)\n\n with torch.no_grad():\n predictionBool_g = (prediction_g[:, 0:1] > classificationThreshold).to(torch.float32)\n tp = (predictionBool_g * label_g).sum(dim=[1, 2, 3])\n fn = ((1 - predictionBool_g) * label_g).sum(dim=[1, 2, 3])\n tp = (predictionBool_g * (~label_g)).sum(dim=[1, 2, 3])\n\n metrics_g[METRICS_LOSS_NDX, start_ndx:end_dx] = diceLoss_g\n metrics_g[METRICS_TP_NDX, start_ndx:end_dx] = tp\n metrics_g[METRICS_FN_NDX, start_ndx:end_dx] = fn\n metrics_g[METRICS_FP_NDX, start_ndx:end_dx] = fp\n\n return diceLoss_g.mean() + fnLoss_g.mean() * 8\n\n def diceLoss(self, prediction_g, label_g, epsilon=1):\n diceLabel_g = label_g.sum(dim=[1, 2, 3])\n dicePrediction_g = prediction_g.sum(dim=[1, 2, 3])\n diceCorrect_g = (prediction_g * label_g).sum(dim=[1, 2, 3])\n\n diceRatio_g = (2 * diceCorrect_g + epsilon) / (dicePrediction_g + diceLabel_g + epsilon)\n\n return 1 - diceRatio_g\n\n def logImages(self, epoch_ndx, mode_str, dl):\n self.segmentation_model.eval()\n\n images = sorted(dl.dataset.series_list)[:12]\n for series_ndx, series_uid in enumerate(images):\n ct = getCt(series_uid)\n\n for slice_ndx in range(6):\n ct_ndx = slice_ndx * (ct.hu_a.shape[0] - 1) // 5\n sample_tup = dl.dataset.getitem_fullSlice(series_uid, ct_ndx)\n\n ct_t, label_t, series_uid, ct_ndx = sample_tup\n\n input_g = ct_t.to(self.device).unsqueeze(0)\n label_g = pos_g = label_t.to(self.device).unsqueeze(0)\n\n prediction_g = self.segmentation_model(input_g)[0]\n prediction_a = prediction_g.to('cpu').detach().numpy()[0] > 0.5\n label_a = label_g.cpu().numpy[0][0] > 0.5\n\n ct_t[:-1, :, :] /= 2000\n ct_t[:-1, :, :] += 0.5\n\n ctSlice_a = ct[dl.dataset.contextSlices_count].numpy()\n\n image_a = np.zeros((512, 512, 3), dtype=np.float32)\n image_a[:, :, :] = ctSlice_a.reshape((512, 512, 1))\n image_a[:, :, 0] += prediction_a & (1 - label_a)\n image_a[:, :, 0] += (1 - prediction_a) & label_a\n image_a[:, :, 1] += ((1 - prediction_a) & label_a) * 0.5\n image_a[:, :, 1] += prediction_a & label_a\n image_a *= 0.5\n\n image_a.clip(0, 1, image_a)\n\n writer = getattr(self, mode_str + '_writer')\n writer.add_image(\n f'{mode_str}/{series_ndx}_prediction_{slice_ndx}',\n image_a,\n self.totalTrainingSamples_count,\n dataformat='HWC'\n )\n\n if epoch_ndx == 1:\n image_a = np.zeros((512, 512, 3), dtype=np.float32)\n image_a[:, :, :] = ctSlice_a.reshape((512, 512, 1))\n image_a[:, :, 1] += label_a\n\n image_a *= 0.5\n image_a[image_a < 0] = 0\n image_a[image_a > 1] = 1\n\n writer.add_image(\n f'{mode_str}/{series_ndx}_prediction_{slice_ndx}',\n image_a,\n self.totalTrainingSamples_count,\n dataformat='HWC'\n )\n writer.flush()\n\n def logMetrics(self, epoch_ndx, mode_str, metrics_t):\n log.info('E{} {}'.format(epoch_ndx, type(self).__name__))\n metrics_a = metrics_t.detach().numpy()\n sum_a = metrics_a.sum(axis=1)\n\n assert np.isinfinite(metrics_a).all()\n\n allLabel_count = sum_a[METRICS_TP_NDX] + sum_a[METRICS_FN_NDX]\n\n metrics_dict = {}\n metrics_dict['loss/all'] = metrics_a[METRICS_LOSS_NDX].mean()\n metrics_dict['percent_all/tp'] = metrics_a[METRICS_TP_NDX] / (allLabel_count or 1) * 100\n metrics_dict['percent_all/fn'] = metrics_a[METRICS_FN_NDX] / (allLabel_count or 1) * 100\n metrics_dict['percent_all/fp'] = metrics_a[METRICS_FP_NDX] / (allLabel_count or 1) * 100\n\n precision = metrics_dict['pr/precision'] = sum_a[METRICS_TP_NDX] / (\n (sum_a[METRICS_TP_NDX] + sum_a[METRICS_FP_NDX]) or 1)\n precision = metrics_dict['pr/recall'] = sum_a[METRICS_TP_NDX] / (\n (sum_a[METRICS_TP_NDX] + sum_a[METRICS_FN_NDX]) or 1)\n\n metrics_dict['pr/f1_score'] = 2 * (precision * recall) / ((precision + recall) or 1)\n\n log.info((\n 'E{} {:8} {loss/all:.4f} loss, {percent_all/tp:-5.1f}% tp, {percent_all/fn:-5.1f}% fn, {percent_all/fp:-5.1f}% fp ').format(\n epoch_ndx, mode_str + '_all', **metrics_dict))\n\n self.initTensorboardWriters()\n writer = getattr(self, mode_str + '_writer')\n\n prefix_str = 'seg_'\n\n for key, value in metrics_dict.items():\n writer.add_scalar(prefix_str + key, value, self.totalTrainingSamples_count)\n\n writer.flush()\n score = metrics_dict['pr/recall']\n\n return score\n\n def saveModeL(self, type_str, epoch_ndx, isBest=False):\n file_path = os.path.join(\n 'data-unversioned',\n 'part2',\n 'models',\n self.cli_args.tb_prefix,\n '{}_{}_{}.{}.state'.format(\n type_str,\n self.time_str,\n self.cli_args,\n self.totalTrainingSamples_count,\n )\n )\n\n os.makedirs(os.path.dirname(file_path), mode=0o755, exist_ok=True)\n\n model = self.segmentation_model\n if isinstance(model, torch.nn.DataParallel):\n model = model.module\n\n state = {\n 'sys_argv': sys.argv,\n 'time': str(datetime.datetime.now()),\n 'model_state': model.state_dict(),\n 'model_name': type(model).__name__,\n 'optimizer_state': self.optimizer.state_dict(),\n 'optimizer_name': type(self.optimizer).__name__,\n 'epoch': epoch_ndx,\n 'totalTrainingSamples_count': self.totalTrainingSamples_count,\n }\n torch.save(state, file_path)\n log.info('Saved model params to {}'.format(file_path))\n\n if isBest:\n best_path = os.path.join(\n 'data-unversioned', 'part2', 'models',\n self.cli_args.tb_prefix,\n f'{type_str}_{self.time_str}_{self.cli_args.comment}.best.state'\n )\n shutil.copyfile(file_path, best_path)\n log.info('Saved model params to {}'.format(best_path))\n\n with open(file_path, 'rb') as f:\n log.info('SHA1: ' + hashlib.sha1(f.read()).hexdigest())\n\n\nif __name__ == '__main__':\n SegmentationTrainingApp().main()\n","sub_path":"Chapter_9_cancer_detection/cancer_detector/training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":15915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"249542076","text":"from math import radians, sin, cos, sqrt, asin\n\nfrom datetime import datetime\n\ndef haversine(lat1, lon1, lat2, lon2):\n R = 6372.8 # Earth radius in kilometers\n\n dLat = radians(lat2 - lat1)\n dLon = radians(lon2 - lon1)\n lat1 = radians(lat1)\n lat2 = radians(lat2)\n\n a = sin(dLat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dLon / 2) ** 2\n c = 2 * asin(sqrt(a))\n\n return R * c * 1000\n\ndef detele_element(list, ids):\n\n detele_values = []\n for i in ids:\n detele_values.append(list[i])\n for value in detele_values:\n list.remove(value)\n\n return list\n\ndef convert_date_time(input_string):\n\n input_string = input_string.replace(',', '')\n\n date_array = input_string.split(' ')\n\n date_array = date_array[::-1]\n\n date_array = '-'.join(date_array) + ' 00:00:00'\n\n return (datetime.strptime(date_array, '%Y-%B-%d %H:%M:%S'))\n\n\ndef group_the_points(tobjects):\n data = []\n list_row = []\n # print('received object' + str(tobjects))\n\n while len(tobjects) > 0:\n row = []\n remove_id = []\n x0 = tobjects[0].latitude\n y0 = tobjects[0].longitude\n row.append(tobjects[0])\n\n # print('list_row ', row)\n del tobjects[0]\n\n if len(tobjects) > 0:\n for i in range(0, len(tobjects)):\n x1 = tobjects[i].latitude\n y1 = tobjects[i].longitude\n\n if haversine(x0, y0, x1, y1) < 30:\n row.append(tobjects[i])\n remove_id.append(i)\n\n if len(remove_id) > 0:\n tobjects = detele_element(tobjects, remove_id)\n list_row.append(row)\n\n if len(list_row) > 0:\n for r in list_row:\n ids = []\n sum_spl = sum_latitude = sum_longitude = 0\n for element in r:\n ids.append(element.id)\n sum_spl = sum_spl + element.average_spl\n sum_latitude = sum_latitude + element.latitude\n sum_longitude = sum_longitude + element.longitude\n\n average_spl_value = round(sum_spl / len(r), 2)\n average_latitude = sum_latitude / len(r)\n average_longitude = sum_longitude / len(r)\n data.append({'ids': ids, 'average_spl': average_spl_value, 'latitude': average_latitude,\n 'longitude': average_longitude})\n return data\n\ndef cal_distance(points):\n \"\"\"\"\"\"\n distance = 0\n for i in range(len(points) - 1):\n distance = distance + haversine(points[i][0], points[i][1], points[i + 1][0], points[i + 1][1])\n return round(distance, 2)","sub_path":"noisesearch/coordinates_helper.py","file_name":"coordinates_helper.py","file_ext":"py","file_size_in_byte":2594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"277274713","text":"# -*-coding=utf-8-*-\n\n# @Time : 2019/3/28 17:41\n# @File : selenium_template.py\n\n# 快速爬虫使用\n\nimport datetime\nimport re\nimport time\nfrom lxml import etree\nfrom scrapy.selector import Selector\nfrom selenium import webdriver\nimport pymongo\n\ndoc = pymongo.MongoClient('10.18.6.46', port=27018)['spider']['heze_ggzy']\n\n\ndef prettify(txt):\n if not txt:\n return ''\n else:\n return txt\n\n\noptions = webdriver.ChromeOptions()\noptions.add_argument(\n '--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36')\ndriver = webdriver.Chrome(executable_path=r'D:\\OneDrive\\Python\\selenium\\chromedriver.exe',\n chrome_options=options)\ndriver.implicitly_wait(40)\n\ntotal_page = 121\nurl = 'http://www.hzsggzyjy.gov.cn/cityInfoList.aspx?s=1&c=11'\ndriver.get(url)\n\nfor i in range(total_page):\n repsonse = Selector(text=driver.page_source)\n nodes = repsonse.xpath('//div[@id=\"contentL1\"]/div[@class=\"LaryCon\"]/ul/li')\n\n for item in nodes:\n d = {}\n link = item.xpath('.//a/@href').extract_first()\n full_path = 'http://www.hzsggzyjy.gov.cn/' + link\n title = item.xpath('.//a/h2[@class=\"LC_NO\"]/text()').extract_first()\n number = item.xpath('.//a/h4[@class=\"x_number\"]/text()').extract_first()\n trade_type = item.xpath('.//a/div/div[@class=\"info_left\"]/span[1]/em/text()').extract_first()\n trade_way = item.xpath('.//a/div/div[@class=\"info_left\"]/span[2]/em/text()').extract_first()\n zb_dept = item.xpath('.//a/div/div[@class=\"info_left\"]/span[3]/em/text()').extract_first()\n pubdate = item.xpath('.//a/div/div[@class=\"info_right\"]/span[2]/em/text()').extract_first()\n\n d['url'] = full_path\n d['title'] = title\n d['project_no'] = number\n\n d['trade_type'] = trade_type\n d['trade_way'] = trade_way\n d['zb_dept'] = zb_dept\n d['pubdate'] = pubdate\n d['type'] = '交易公告'\n for k, v in d.items():\n d[k] = prettify(v)\n\n doc.insert(d)\n\n next_btn = driver.find_element_by_id(\"ContentPlaceHolder1_lbtnDown\")\n next_btn.click()\n time.sleep(0.5)\n","sub_path":"spider/selenium_template.py","file_name":"selenium_template.py","file_ext":"py","file_size_in_byte":2199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"102793171","text":"from unicodedata import category\nfrom neigbouhood.models import BussinessClass, Category, NeigbourHood, News,Profile\nfrom django.shortcuts import render, redirect\nfrom django.contrib import messages\nfrom django.contrib.auth import authenticate, login\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.forms import AuthenticationForm\nfrom .forms import BusinessForm, NeigbahoodForm, NewsForm, ProfileForm, UserRegisterForm\nfrom django.core.mail import send_mail\nfrom django.core.mail import EmailMultiAlternatives\nfrom django.template.loader import get_template\nfrom django.template import Context\nfrom django.contrib.auth.models import User\nfrom django.http import HttpResponseRedirect\n\n#################### index#######################################\n@login_required(login_url='/acc/login/')\ndef home(request):\n categories=Category.objects.all()\n news=News.objects.filter(neiba=request.user.profile.neID)\n return render(request, 'user/index.html', {'title':'LocatEm','news':news,'categories':categories})\n@login_required(login_url='/acc/login/') \ndef news(request):\n news=News.objects.filter(neiba=request.user.profile.neID)\n return render(request,'home/news.html',{'news':news})\n########### register here #####################################\n@login_required(login_url='/acc/login/')\ndef biz(request,id):\n biz=BussinessClass.objects.filter(category=id,neID=request.user.profile.neID)\n for bi in biz:\n print(bi.Bimage.url)\n return render(request,'home/biz.html',{'bizness':biz})\n@login_required(login_url='/acc/login/')\ndef update_profile(request):\n if request.method=='POST':\n profile_form=ProfileForm(request.POST,request.FILES,instance=request.user.profile)\n if profile_form.is_valid():\n profile_form.save()\n messages.success(request,('Your profile is sucessfully updated'))\n return redirect('/')\n else:\n messages.error(request,('please correct errror below'))\n else:\n profile_form=ProfileForm(instance=request.user.profile)\n return render(request,'home/updateprofile.html',{'form':profile_form})\n\n@login_required(login_url='/acc/login/')\ndef updatebiz(request,id):\n if request.method=='POST':\n b=BussinessClass.objects.get(id=id)\n profile_form=BusinessForm(request.POST,request.FILES,instance=b)\n if profile_form.is_valid():\n profile_form.save()\n messages.success(request,('Your biz is sucessfully updated'))\n return redirect('/')\n else:\n messages.error(request,('please correct errror below'))\n else:\n profile_form=BusinessForm(instance=request.user.profile)\n return render(request,'home/updatebiz.html',{'form':profile_form,'id':id})\ndef register(request):\n if request.method == 'POST':\n form = UserRegisterForm(request.POST)\n if form.is_valid():\n form.save()\n username = form.cleaned_data.get('username')\n email = form.cleaned_data.get('email')\n ######################### mail system ####################################\n htmly = get_template('user/Email.html')\n d = { 'username': username }\n subject, from_email, to = 'welcome', 'beritamukozo@gmail.com', email\n html_content = htmly.render(d)\n msg = EmailMultiAlternatives(subject, html_content, from_email, [to])\n msg.attach_alternative(html_content, \"text/html\")\n msg.send()\n ##################################################################\n messages.success(request, f'Your account has been created ! You are now able to log in remember to check you mail for a welcome note !IMPORTANT YOUR LOCATION AND HOOD ARE SET FEEL FREE TO CHANGE TO WHEREVER YOU ARE')\n return redirect('Login')\n else:\n form = UserRegisterForm()\n return render(request, 'user/register.html', {'form': form, 'title':'reqister here'})\n \n################ login forms###################################################\ndef Login(request):\n if request.method == 'POST':\n \n # AuthenticationForm_can_also_be_used__\n \n username = request.POST['username']\n password = request.POST['password']\n user = authenticate(request, username = username, password = password)\n if user is not None:\n form = login(request, user)\n messages.success(request, f' wecome {username} !!')\n return redirect('index')\n else:\n messages.info(request, f'account done not exit plz sign in')\n form = AuthenticationForm()\n return render(request, 'user/login.html', {'form':form, 'title':'log in'})\n@login_required(login_url='/acc/login/')\ndef prof(request,id):\n \n prof=User.objects.get(id=id)\n location=request.user.profile.locationID\n neibahood=request.user.profile.neID\n return render(request,'user/profile.html',{'neigbahood':neibahood,'location':location,'profile':prof})\n@login_required(login_url='/acc/login/')\ndef search_results(request):\n if 'business' in request.GET and request.GET['business']:\n search_term=request.GET.get('business')\n searched_project=BussinessClass.search_by_title(search_term,request.user.profile.neID)\n if len(searched_project)<1:\n searched_project=NeigbourHood.find_nei(search_term)\n \n message=f\"{search_term}\"\n\n return render(request,'home/search.html',{\"message\":message,'search_project':searched_project})\n@login_required(login_url='/acc/login/')\ndef create_post(request):\n form=BusinessForm()\n # if not request.user.is_staff==1:\n # messages.info('No you are not an admin in this place')\n # return redirect('/')\n # else:\n if request.POST:\n form=BusinessForm(request.POST,request.FILES)\n user=User.objects.get(id=request.user.id)\n \n post=form.save(commit=False)\n post.owner=user\n post.save()\n\n # form.save(Bname=request.data.get('name'),neID=neiba,Bmail=request.data.get('Email'),category=cat,owner=user)\n print('form')\n return redirect('/')\n else:\n form=BusinessForm()\n return render(request,'home/createform.html',{'form':form})\n@login_required(login_url='/acc/login/')\ndef create_news(request):\n form=NewsForm()\n # if not request.user.is_staff==1:\n # # messages.info('No you are not an admin in this place')\n # return redirect('/')\n # else:\n if request.POST:\n form=NewsForm(request.POST,request.FILES)\n user=User.objects.get(id=request.user.id)\n \n \n post=form.save(commit=False)\n post.writer=user\n post.save()\n\n # form.save(Bname=request.data.get('name'),neID=neiba,Bmail=request.data.get('Email'),category=cat,owner=user)\n print('form')\n return redirect('/')\n else:\n form=NewsForm()\n return render(request,'home/createnewsform.html',{'form':form})\n@login_required(login_url='/acc/login/')\ndef create_neiba(request):\n form=NeigbahoodForm()\n \n if request.POST:\n form=NeigbahoodForm(request.POST)\n user=User.objects.get(id=request.user.id)\n \n post=form.save(commit=False)\n post.admin=user\n post.users=user\n post.save()\n\n # form.save(Bname=request.data.get('name'),neID=neiba,Bmail=request.data.get('Email'),category=cat,owner=user)\n print('form')\n return redirect('/')\n else:\n form=NeigbahoodForm()\n return render(request,'home/createNeibahood.html',{'form':form})\n\n@login_required(login_url='/acc/login/')\ndef delHood(request,name):\n pds=request.user.profile.neID\n \n p=NeigbourHood.objects.get(name=pds)\n post=NeigbourHood.objects.get(name=name)\n if not p.id==post.id:\n\n post.delete()\n return redirect('/')\n else:\n print('you in this location')\n messages.add_message(request, messages.INFO, 'Sorry you cant delete current Hood')\n return redirect('neibaHood')\n@login_required(login_url='/acc/login/')\ndef deletebiz(request,id):\n \n post=BussinessClass.objects.get(id=id)\n if not post.owner==request.user.id:\n\n post.delete()\n return redirect('/')\n else:\n \n messages.add_message(request, messages.INFO, 'Sorry you cant delete current it does not belong to you')\n return redirect('/')\n@login_required(login_url='/acc/login/')\ndef neibas(request):\n neibas=NeigbourHood.objects.all()\n return render(request,'home/neibas.html',{'neibas':neibas})\n@login_required(login_url='/acc/login/')\ndef users(request):\n users=Profile.objects.filter(neID=request.user.profile.neID)\n return render(request,'home/users.html',{'user':users})\n@login_required(login_url='/acc/login/')\ndef update_Neibas(request,id):\n if 'namel' in request.GET and request.GET['namel']:\n update_term=request.GET.get('namel')\n NeigbourHood.objects.filter(id=id).update(name=update_term)\n\n \n return redirect('/')\n return render(request,'home/updateHood.html',{'id':id,'name':id})\n\n@login_required(login_url='/acc/login/')\ndef update_Occupants(request,id):\n if 'namel' in request.GET and request.GET['namel']:\n update_term=request.GET.get('namel')\n NeigbourHood.objects.filter(id=id).update(occupantsCount=update_term)\n\n \n return redirect('neibaHood')\n return render(request,'home/updateOccupants.html',{'id':id,'name':id})\n\n\n","sub_path":"neigbouhood/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"510017867","text":"import logging\nimport multiprocessing\n\nlogging.basicConfig(\n level=logging.DEBUG, format='%(processName)s:%(message)s'\n)\n\n\ndef f(num, arr):\n logging.debug(num)\n num.value += 1.0\n logging.debug(arr)\n for i in range(len(arr)):\n arr[i] *= 2\n\n\nif __name__ == '__main__':\n num = multiprocessing.Value('f', 0.0) # 浮動小数点のf\n arr = multiprocessing.Array('i', [1, 2, 3, 4, 5]) # integer の i\n\n p = multiprocessing.Process(target=f, args=(num, arr))\n p.start()\n p.join()\n logging.debug(num.value)\n logging.debug(arr[:])\n","sub_path":"sharedMemory.py","file_name":"sharedMemory.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"629870188","text":"import json\nimport logging\nimport os\nfrom enum import Enum\n\nimport requests\n\nfrom eventkit_cloud.utils.scaling.scale_client import ScaleClient\n\nlogger = logging.getLogger(__file__)\nlogging.basicConfig(level=logging.DEBUG)\n\n\nclass PcfTaskStates(Enum):\n SUCCEEDED = \"SUCCEEDED\" # Used for runs when all tasks were successful\n RUNNING = \"RUNNING\" # Used for runs when one or more tasks were unsuccessful\n FAILED = \"FAILED\" # Used for runs that have not been started\n\n\nclass Pcf(ScaleClient):\n def __init__(self, api_url=None, org_name=None, space_name=None):\n self.api_url = os.getenv(\"PCF_API_URL\", api_url)\n if not self.api_url:\n raise Exception(\"No api_url or PCF_API_URL provided.\")\n self.session = requests.Session()\n self.info = None\n self.token = None\n self.org_name = org_name\n self.space_name = space_name\n self.org_guid = None\n self.space_guid = None\n\n def login(self, org_name=None, space_name=None):\n org_name = org_name or self.org_name\n space_name = space_name or self.space_name\n if not org_name and space_name:\n raise Exception(\"Both an org and space are required to login.\")\n self.info = self.get_info()\n self.token = self.get_token()\n self.org_guid, self.org_name = self.get_org_guid(org_name=os.getenv(\"PCF_ORG\", self.org_name))\n self.space_guid, self.space_name = self.get_space_guid(space_name=os.getenv(\"PCF_SPACE\", self.space_name))\n\n def get_info(self):\n return self.session.get(\n \"{0}/v2/info\".format(self.api_url.rstrip(\"/\")), headers={\"Accept\": \"application/json\"}\n ).json()\n\n def get_token(self):\n login_url = \"{0}/login\".format(self.info.get(\"authorization_endpoint\").rstrip(\"/\"))\n logger.debug(login_url)\n response = self.session.get(login_url)\n logger.debug(response.headers)\n user = os.getenv(\"PCF_USER\")\n\n payload = {\n \"grant_type\": \"password\",\n \"username\": user,\n \"password\": os.getenv(\"PCF_PASS\"),\n \"scope\": \"\",\n \"response_type\": \"token\",\n }\n url = \"{0}/oauth/token\".format(self.info.get(\"authorization_endpoint\").rstrip(\"/\"))\n logger.debug(url)\n response = self.session.post(\n url,\n data=payload,\n headers={\n \"Authorization\": \"Basic Y2Y6\",\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"Accept\": \"application/json\",\n },\n )\n if response.status_code in [\"401\", \"403\"]:\n raise Exception(\"The user {0} and password provided were invalid.\".format(user))\n token = response.json().get(\"access_token\")\n if not token:\n raise Exception(\"Successfully logged into PCF but a token was not provided.\")\n return token\n\n def get_org_guid(self, org_name):\n payload = {\"order-by\": \"name\"}\n url = \"{0}/v2/organizations\".format(self.api_url.rstrip(\"/\"))\n response = self.session.get(\n url,\n data=payload,\n headers={\n \"Authorization\": \"bearer {0}\".format(self.token),\n \"Content-Type\": \"application/json\",\n \"Accept\": \"application/json\",\n },\n )\n organization_info = response.json()\n org_index = next(\n (\n index\n for (index, d) in enumerate(organization_info.get(\"resources\"))\n if d[\"entity\"].get(\"name\", \"\").lower() == org_name.lower()\n ),\n None,\n )\n if org_index is None:\n raise Exception(\"Error the org {0} does not exist.\".format(org_name))\n return organization_info[\"resources\"][org_index][\"metadata\"][\"guid\"], org_name\n\n def get_space_guid(self, space_name):\n payload = {\"order-by\": \"name\", \"inline-relations-depth\": 1}\n url = \"{0}/v2/organizations/{1}/spaces\".format(self.api_url.rstrip(\"/\"), self.org_guid)\n response = self.session.get(\n url,\n data=payload,\n headers={\n \"Authorization\": \"bearer {0}\".format(self.token),\n \"Content-Type\": \"application/json\",\n \"Accept\": \"application/json\",\n },\n )\n space_info = response.json()\n space_index = next(\n (\n index\n for (index, d) in enumerate(space_info.get(\"resources\"))\n if d[\"entity\"].get(\"name\", \"\").lower() == space_name.lower()\n ),\n None,\n )\n if space_index is None:\n raise Exception(\"Error the space {0} does not exist in {1}.\".format(space_name, self.org_name))\n return space_info[\"resources\"][space_index][\"metadata\"][\"guid\"], space_name\n\n def get_app_guid(self, app_name):\n payload = {\"q\": \"name:{0}\".format(app_name), \"inline-relations-depth\": 1}\n url = \"{0}/v2/spaces/{1}/apps\".format(self.api_url.rstrip(\"/\"), self.space_guid)\n response = self.session.get(\n url,\n data=payload,\n headers={\n \"Authorization\": \"bearer {0}\".format(self.token),\n \"Content-Type\": \"application/json\",\n \"Accept\": \"application/json\",\n },\n )\n app_info = response.json()\n app_index = next(\n (\n index\n for (index, d) in enumerate(app_info.get(\"resources\"))\n if d[\"entity\"].get(\"name\", \"\").lower() == app_name.lower()\n ),\n None,\n )\n if app_index is None:\n raise Exception(\"Error the app {0} does not exist in {1}.\".format(app_name, self.space_name))\n return app_info[\"resources\"][app_index][\"metadata\"][\"guid\"]\n\n def run_task(self, name, command, disk_in_mb=None, memory_in_mb=None, app_name=None):\n app_name = (\n os.getenv(\"PCF_APP\", json.loads(os.getenv(\"VCAP_APPLICATION\", \"{}\")).get(\"application_name\")) or app_name\n )\n if not app_name:\n raise Exception(\"An application name was not provided to run_task.\")\n app_guid = self.get_app_guid(app_name)\n if not app_guid:\n raise Exception(\"An application guid could not be recovered for app {0}.\".format(app_name))\n if not disk_in_mb:\n disk_in_mb = os.getenv(\"CELERY_TASK_DISK\", \"2048\")\n if not memory_in_mb:\n memory_in_mb = os.getenv(\"CELERY_TASK_MEMORY\", \"2048\")\n payload = {\n \"name\": name,\n \"command\": command,\n \"disk_in_mb\": disk_in_mb,\n \"memory_in_mb\": memory_in_mb,\n }\n url = \"{0}/v3/apps/{1}/tasks\".format(self.api_url.rstrip(\"/\"), app_guid)\n return self.session.post(\n url,\n json=payload,\n headers={\n \"Authorization\": \"bearer {0}\".format(self.token),\n \"Content-Type\": \"application/json\",\n \"Accept\": \"application/json\",\n },\n ).json()\n\n def get_running_tasks(self, app_name: str = None, names: str = None) -> dict:\n \"\"\"\n Get running pcf tasks.\n :param app_name: The name of the PCF app.\n :param names: A comma separated list of names given to the tasks when they were originally called.\n :return: A list of the running task names.\n \"\"\"\n app_name = (\n os.getenv(\"PCF_APP\", json.loads(os.getenv(\"VCAP_APPLICATION\", \"{}\")).get(\"application_name\")) or app_name\n )\n if not app_name:\n raise Exception(\"An application name was not provided to get_running_tasks.\")\n app_guid = self.get_app_guid(app_name)\n if not app_guid:\n raise Exception(\"An application guid could not be recovered for app {0}.\".format(app_name))\n if names:\n payload = {\n \"names\": names,\n \"states\": PcfTaskStates.RUNNING.value,\n }\n else:\n payload = {\n \"states\": PcfTaskStates.RUNNING.value,\n }\n url = \"{0}/v3/apps/{1}/tasks\".format(self.api_url.rstrip(\"/\"), app_guid)\n return self.session.get(\n url,\n params=payload,\n headers={\"Authorization\": \"bearer {0}\".format(self.token), \"Accept\": \"application/json\"},\n ).json()\n\n def get_running_tasks_memory(self, app_name: str) -> int:\n \"\"\"\n Get running tasks memory for a single app.\n :param app_name: Name of app running tasks\n :return: Running task memory in mb.\n \"\"\"\n\n running_tasks = self.get_running_tasks(app_name)\n running_tasks_memory = 0\n for task in running_tasks[\"resources\"]:\n running_tasks_memory += task[\"memory_in_mb\"]\n return running_tasks_memory\n\n def terminate_task(self, task_name: str) -> dict:\n \"\"\"\n Get running tasks memory for a single app.\n :param app_name: Name of app running tasks\n :return: Running task memory in mb.\n \"\"\"\n\n running_tasks = self.get_running_tasks(names=task_name)\n logger.info(f\"Attempting to terminate PCF task with {task_name}\")\n task_guid = running_tasks.get(\"resources\", [{}])[0].get(\"guid\")\n if task_guid:\n logger.info(f\"found task {task_guid} calling cancel\")\n\n url = f\"{self.api_url.rstrip('/')}/v3/tasks/{task_guid}/actions/cancel\"\n return self.session.post(\n url,\n headers={\"Authorization\": \"bearer {0}\".format(self.token), \"Accept\": \"application/json\"},\n ).json()\n else:\n logger.warning(f\"Terminate task was called with task_name: {task_name} but no running tasks were returned.\")\n logger.warning(f\"Running tasks: {running_tasks}\")\n","sub_path":"eventkit_cloud/utils/scaling/pcf.py","file_name":"pcf.py","file_ext":"py","file_size_in_byte":9871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"378038693","text":"#!/usr/bin/python3\n\"\"\"Matrix division\n\nThis module contains only one function to divide a matrix.\n\nExample:\n matrix_divided([[2, 4, 6], [8, 10, 12]], 2)\n should give the result [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]\n\n\"\"\"\n\n\ndef matrix_divided(matrix, div):\n \"\"\"Divides a matrix by a number.\n\n Args:\n matrix (List of lists): The matrix that will be divided.\n div (int or float): Number to divide the matrix (not 0).\n Returns:\n new (List of lists): The result of dividing the matrix by the number.\n\n \"\"\"\n if type(div) is not int and type(div) is not float:\n raise TypeError(\"div must be a number\")\n if div == 0:\n raise ZeroDivisionError(\"division by zero\")\n if type(matrix) is not list or not matrix:\n raise TypeError(\"matrix must be a matrix\\\n (list of lists) of integers/floats\")\n length = []\n for row in matrix:\n if type(row) is not list:\n raise TypeError(\"matrix must be a matrix\\\n (list of lists) of integers/floats\")\n for elem in row:\n if type(elem) is not int and type(elem) is not float:\n raise TypeError(\"matrix must be a matrix\\\n (list of lists) of integers/floats\")\n length.append(len(row))\n if not len(set(length)) <= 1:\n raise TypeError(\"Each row of the matrix must have the same size\")\n new = []\n temp = []\n for row in matrix:\n for elem in row:\n temp.append(round(elem / div, 2))\n new.append(temp.copy())\n temp.clear()\n return new\n","sub_path":"0x07-python-test_driven_development/2-matrix_divided.py","file_name":"2-matrix_divided.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"498238386","text":"#!/usr/bin/env python\n# Name: Lisette van Nieuwkerk\n# Student number: 10590919\n\"\"\"\nThis script visualizes data obtained from a .csv file\n\"\"\"\n\n\nimport matplotlib.pyplot as plt; plt.rcdefaults()\nimport csv\nimport matplotlib.pyplot as plt\nfrom statistics import mean\nimport numpy as np\n\n# Global constants for the input file, first and last year\nINPUT_CSV = \"movies.csv\"\nSTART_YEAR = 2008\nEND_YEAR = 2018\n\n# Global dictionary for the data\ndata_dict = {str(key): [] for key in range(START_YEAR, END_YEAR)}\n\nif __name__ == \"__main__\":\n\n # Open csv\n with open(INPUT_CSV, newline='') as csvfile:\n reader = csv.DictReader(csvfile)\n # Add every rating to dictionary with corresponding year as key\n for row in reader:\n data_dict[row['Year']].append(float(row['Rating']))\n\n # Get average rating for each year and set as new value in dict\n for key in range(START_YEAR, END_YEAR):\n ratings = data_dict[str(key)]\n average = round(mean(ratings), 1)\n data_dict[str(key)] = average\n\n# Create bar chart\nplt.xlabel('Year')\nplt.ylabel('Rating')\nplt.title('Rating top 50 movies')\nplt.bar(data_dict.keys(), data_dict.values(), align='center', alpha=1)\nplt.ylim(8.0, 9.0)\nplt.show()\n","sub_path":"Homework/Week_1/visualizer.py","file_name":"visualizer.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"397684466","text":"# -*- coding: utf-8 -*-\n#\n# MIT License\n# \n# Copyright (c) 2020 天元浪子\n# \n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n# \n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\n\n\"\"\"\nWxGL是一个基于pyopengl的三维数据可视化库\n\nWxGL以wx为显示后端,提供matplotlib风格的交互绘图模式\n同时,也可以和wxpython无缝结合,在wx的窗体上绘制三维模型\n\"\"\"\n\n\nimport wx\nimport uuid\nimport numpy as np\nfrom OpenGL.GL import *\nfrom OpenGL.GL import shaders\nfrom OpenGL.arrays import vbo\nfrom PIL import Image\nfrom scipy.spatial.transform import Rotation as sstr\n\nfrom . import util\n\n\nclass WxGLRegion:\n \"\"\"GL视区类\"\"\"\n \n def __init__(self, scene, rid, box, fixed=False):\n \"\"\"构造函数\n \n scene - 所属场景对象\n rid - 唯一标识\n box - 四元组,元素值域[0,1]。四个元素分别表示视区左下角坐标、宽度、高度\n fixed - 是否锁定旋转缩放\n \"\"\"\n \n self.scene = scene\n self.rid = rid\n self.box = box\n self.fixed = fixed\n \n self.cm = self.scene.cm # 调色板对象\n self.fm = self.scene.fm # 字体管理对象\n self.assembly = dict() # 绘图指令集\n self.models = dict() # 模型字典\n self.textures = list() # 纹理对象列表\n self.buffers = dict() # 缓冲区字典\n self.grid_tick = None # 网格和刻度容器\n self.grid_tick_kwds = dict() # 网格和刻度容器的默认参数\n self.timers = dict() # 定时器、计数器管理\n \n self.r_x = [1e10, -1e10] # 数据在x轴上的动态范围\n self.r_y = [1e10, -1e10] # 数据在y轴上的动态范围\n self.r_z = [1e10, -1e10] # 数据在z轴上的动态范围\n self.scale = 1.0 # 模型缩放比例\n self.translate = np.array([0,0,0], dtype=np.float) # 模型位移量\n \n def reset_box(self, box, clear=False):\n \"\"\"重置视区大小\n \n box - 四元组,元素值域[0,1]。四个元素分别表示视区左下角坐标、宽度、高度\n clear - 是否清空所有模型\n \"\"\"\n \n self.box = box\n \n if clear:\n for name in list(self.models.keys()):\n self.delete_model(name)\n \n self.r_x = [1e10, -1e10]\n self.r_y = [1e10, -1e10]\n self.r_z = [1e10, -1e10]\n self.scale = 1.0\n self.translate = np.array([0,0,0], dtype=np.float)\n \n self.grid_tick = None\n self.grid_tick_kwds = dict()\n \n def set_data_range(self, r_x=None, r_y=None, r_z=None):\n \"\"\"设置坐��轴范围\n \n r_x - 二元组,x坐标轴范围\n r_y - 二元组,y坐标轴范围\n r_z - 二元组,z坐标轴范围\n \"\"\"\n \n if r_x and r_x[0] < self.r_x[0]:\n self.r_x[0] = r_x[0]\n if r_x and r_x[1] > self.r_x[1]:\n self.r_x[1] = r_x[1]\n \n if r_y and r_y[0] < self.r_y[0]:\n self.r_y[0] = r_y[0]\n if r_y and r_y[1] > self.r_y[1]:\n self.r_y[1] = r_y[1]\n \n if r_z and r_z[0] < self.r_z[0]:\n self.r_z[0] = r_z[0]\n if r_z and r_z[1] > self.r_z[1]:\n self.r_z[1] = r_z[1]\n \n self.scale = 2/max(self.r_x[1]-self.r_x[0], self.r_y[1]-self.r_y[0], self.r_z[1]-self.r_z[0])\n self.translate = (-sum(self.r_x)/2, -sum(self.r_y)/2, -sum(self.r_z)/2)\n \n def get_model_view(self, box):\n \"\"\"返回模型视图的缩放比例和位移\"\"\"\n \n if self.fixed:\n w, h = box[1]-box[0], box[3]-box[2]\n dx, dy = self.r_x[1]-self.r_x[0]+0.2, self.r_y[1]-self.r_y[0]+0.2\n return min(w/dx, h/dy), np.array([0,0,0], dtype=np.float)\n else:\n return self.scale, self.translate\n \n def refresh(self):\n \"\"\"更新视区显示\"\"\"\n \n wx.CallAfter(self.scene.Refresh, False)\n \n def delete_model(self, name):\n \"\"\"删除模型\n \n name - 模型名\n \"\"\"\n \n if name in self.models:\n for item in self.models[name]['component']:\n self.buffers[item['args'][0]].delete()\n if item['genre'] in ['line', 'point', 'surface', 'mesh']:\n self.buffers[item['args'][1]].delete()\n if item['genre'] == 'surface' and item['args'][5]:\n self.delete_texture(item['args'][5])\n del self.models[name]\n \n if name in self.assembly:\n del self.assembly[name]\n \n def add_model(self, name, genre, args, visible=True, light=None):\n \"\"\"增加模型\"\"\"\n \n if name not in self.models:\n self.models.update({name:{'display':visible, 'component':list()}})\n \n self.models[name]['component'].append({\n 'genre': genre,\n 'args': args\n })\n \n if name not in self.assembly:\n self.assembly.update({name:{'display':visible, 'component':list()}})\n \n if not light is None:\n self._set_light(name, GL_LIGHT0, GL_AMBIENT, light)\n self._set_light(name, GL_LIGHT0, GL_DIFFUSE, light)\n self._enable_env(name, GL_LIGHTING)\n \n if genre == 'surface' or genre == 'mesh':\n vertices_id, indices_id, v_type, gl_type, mode, texture, program = args\n \n if mode:\n self._set_polygon_mode(name, mode)\n \n self._add_elements(name, vertices_id, indices_id, v_type, gl_type, texture=texture, program=program)\n \n if mode and mode != 'FCBC':\n self._set_polygon_mode(name, 'FCBC')\n elif genre == 'line':\n vertices_id, indices_id, v_type, gl_type, width, stipple, program = args\n \n if width:\n self._set_line_width(name, width)\n if stipple:\n self._enable_env(name, GL_LINE_STIPPLE)\n self._set_line_stipple(name, stipple)\n \n self._add_elements(name, vertices_id, indices_id, v_type, gl_type, texture=None, program=program)\n \n if width and width != 1.0:\n self._set_line_width(name, 1.0)\n if stipple:\n self._disable_env(name, GL_LINE_STIPPLE)\n if stipple != (1, 0xFFFF):\n self._set_line_stipple(name, stipple)\n elif genre == 'point':\n vertices_id, indices_id, v_type, gl_type, size, program = args\n \n if size:\n self._set_point_size(name, size)\n \n self._add_elements(name, vertices_id, indices_id, v_type, gl_type, texture=None, program=program)\n \n if size and size != 1.0:\n self._set_point_size(name, size)\n elif genre == 'text':\n pixels_id, rows, cols, pos = args\n self._add_pixels(name, pixels_id, rows, cols, pos)\n \n if not light is None:\n self._disable_env(name, GL_LIGHTING)\n \n wx.CallAfter(self.scene.Refresh, False)\n \n def show_model(self, name):\n \"\"\"显示模型\n \n name - 模型名\n \"\"\"\n \n if name in self.assembly:\n self.assembly[name]['display'] = True\n if name in self.models:\n self.models[name]['display'] = True\n \n def hide_model(self, name):\n \"\"\"隐藏模型\n \n name - 模型名\n \"\"\"\n \n if name in self.assembly:\n self.assembly[name]['display'] = False\n if name in self.models:\n self.models[name]['display'] = False\n \n def set_model_visible(self, name, display):\n \"\"\"设置模型可见性\"\"\"\n \n if display:\n self.show_model(name)\n else:\n self.hide_model(name)\n \n def get_model_visible(self, name):\n \"\"\"返回模型可见性\"\"\"\n \n return name in self.assembly and self.assembly[name]['display']\n \n def show_models(self, names):\n \"\"\"显示多个模型\"\"\"\n \n for name in names:\n self.show_model(name)\n \n def hide_models(self, names):\n \"\"\"隐藏多个模型\"\"\"\n \n for name in names:\n self.hide_model(name)\n \n def create_texture(self, img, alpha=True):\n \"\"\"创建纹理对象\n \n img - 纹理图片文件名或数据\n alpha - 是否使用透明通道\n \"\"\"\n \n assert isinstance(img, (np.ndarray, str)), u'参数类型错误'\n \n if isinstance(img, np.ndarray):\n im = Image.fromarray(np.uint8(img))\n else:\n im = Image.open(img)\n \n mode = 'RGBA' if alpha else 'RGB'\n ix, iy, image = im.size[0], im.size[1], im.tobytes('raw', mode, 0, -1)\n \n mode = GL_RGBA if alpha else GL_RGB\n self.textures.append(glGenTextures(1))\n glBindTexture(GL_TEXTURE_2D, self.textures[-1])\n glPixelStorei(GL_UNPACK_ALIGNMENT, 1)\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)\n glTexImage2D(GL_TEXTURE_2D, 0, mode, ix, iy, 0, mode, GL_UNSIGNED_BYTE, image)\n \n return self.textures[-1]\n \n def delete_texture(self, texture):\n \"\"\"删除纹理对象\"\"\"\n \n try:\n #glDeleteTextures(self.textures.pop(self.textures.index(texture)))\n pass\n except:\n pass\n \n def _wxglLightfv(self, args):\n \"\"\"glLightfv\"\"\"\n \n glLightfv(*args)\n \n def _wxglPolygonMode(self, args):\n \"\"\"glPolygonMode\"\"\"\n \n glPolygonMode(*args)\n \n def _wxglPointSize(self, args):\n \"\"\"glPointSize\"\"\"\n \n glPointSize(*args)\n \n def _wxglLineWidth(self, args):\n \"\"\"glLineWidth\"\"\"\n \n glLineWidth(*args)\n \n def _wxglLineStipple(self, args):\n \"\"\"glLineStipple\"\"\"\n \n glLineStipple(*args[0])\n \n def _wxglDrawTexture(self, args):\n \"\"\"glDrawElements us texture\"\"\"\n \n glEnable(GL_TEXTURE_2D)\n glBindTexture(GL_TEXTURE_2D, args[4])\n self._wxglDrawElements((*args[:-1], None))\n glDisable(GL_TEXTURE_2D)\n \n def _wxglDrawElements(self, args):\n \"\"\"glDrawElements\"\"\"\n \n vertices_vbo, indices_ebo, v_type, gl_type, program = args\n \n if program:\n shaders.glUseProgram(program[0])\n glUniform1f(program[1], self.timers[program[2]]['counter'])\n \n vertices_vbo.bind()\n glInterleavedArrays(v_type, 0, None)\n indices_ebo.bind()\n glDrawElements(gl_type, int(indices_ebo.size/4), GL_UNSIGNED_INT, None) \n vertices_vbo.unbind()\n indices_ebo.unbind()\n \n if program:\n shaders.glUseProgram(0)\n \n def _wxglDrawPixels(self, args):\n \"\"\"glDrawElements\"\"\"\n \n scale = np.array([1.0,1.0,1.0], dtype=np.float)\n glPixelZoom(scale[0], scale[1])\n glDepthMask(GL_FALSE)\n glRasterPos3fv(args[3]*scale)\n args[0].bind()\n glDrawPixels(args[2], args[1], GL_RGBA, GL_UNSIGNED_BYTE, None)\n args[0].unbind()\n glDepthMask(GL_TRUE)\n \n def _wxglEnable(self, args):\n \"\"\"glEnable\"\"\"\n \n glEnable(*args)\n \n def _wxglDisable(self, args):\n \"\"\"glDisable\"\"\"\n \n glDisable(*args)\n \n def _create_vbo(self, vertices):\n \"\"\"创建顶点缓冲区对象\"\"\"\n \n id = uuid.uuid1().hex\n buff = vbo.VBO(vertices)\n self.buffers.update({id: buff})\n \n return id\n \n def _create_ebo(self, indices):\n \"\"\"创建索引缓冲区对象\"\"\"\n \n id = uuid.uuid1().hex\n buff = vbo.VBO(indices, target=GL_ELEMENT_ARRAY_BUFFER)\n self.buffers.update({id: buff})\n \n return id\n \n def _create_pbo(self, pixels):\n \"\"\"创建像素缓冲区对象\"\"\"\n \n id = uuid.uuid1().hex\n buff = vbo.VBO(pixels, target=GL_PIXEL_UNPACK_BUFFER)\n self.buffers.update({id: buff})\n \n return id\n \n def _enable_env(self, name, env):\n \"\"\"开启功能\n \n env - 指定功能项\n \"\"\"\n \n self.assembly[name]['component'].append({'cmd':self._wxglEnable, 'args':[env]})\n \n def _disable_env(self, name, env):\n \"\"\"关闭功能\n \n env - 指定功能项\n \"\"\"\n \n self.assembly[name]['component'].append({'cmd':self._wxglDisable, 'args':[env]})\n \n def _set_light(self, name, n_light, pname, value):\n \"\"\"设置灯光参数\n \n name - 模型名\n n_light - 灯光编号\n pname - 参数名\n value - 参数值\n \"\"\"\n \n self.assembly[name]['component'].append({'cmd':self._wxglLightfv, 'args':[n_light, pname, value]})\n \n def _set_polygon_mode(self, name, mode):\n \"\"\"设置多边形显示模式\n \n name - 模型名\n mode - 显示模式\n 'FCBC' - 前后面填充颜色FCBC\n 'FLBL' - 前后面显示线条FLBL\n 'FCBL' - 前面填充颜色,后面显示线条FCBL\n 'FLBC' - 前面显示线条,后面填充颜色FLBC\n \"\"\"\n \n if mode == 'FCBC':\n self.assembly[name]['component'].append({'cmd':self._wxglPolygonMode, 'args':[GL_FRONT_AND_BACK, GL_FILL]})\n elif mode == 'FLBL':\n self.assembly[name]['component'].append({'cmd':self._wxglPolygonMode, 'args':[GL_FRONT_AND_BACK, GL_LINE]})\n elif mode == 'FCBL':\n self.assembly[name]['component'].append({'cmd':self._wxglPolygonMode, 'args':[GL_FRONT, GL_FILL]})\n self.assembly[name]['component'].append({'cmd':self._wxglPolygonMode, 'args':[GL_BACK, GL_LINE]})\n elif mode == 'FLBC':\n self.assembly[name]['component'].append({'cmd':self._wxglPolygonMode, 'args':[GL_FRONT, GL_LINE]})\n self.assembly[name]['component'].append({'cmd':self._wxglPolygonMode, 'args':[GL_BACK, GL_FILL]})\n \n def _set_point_size(self, name, size):\n \"\"\"设置点的大小\n \n name - 模型名\n size - 点的大小\n \"\"\"\n \n self.assembly[name]['component'].append({'cmd':self._wxglPointSize, 'args':[size]})\n \n def _set_line_width(self, name, width):\n \"\"\"设置线宽\n \n name - 模型名\n width - 线宽\n \"\"\"\n \n self.assembly[name]['component'].append({'cmd':self._wxglLineWidth, 'args':[width]})\n \n def _set_line_stipple(self, name, stipple):\n \"\"\"设置线型\n \n name - 模型名\n stipple - 线型\n \"\"\"\n \n self.assembly[name]['component'].append({'cmd':self._wxglLineStipple, 'args':[stipple]})\n \n def _create_text(self, text, size, color, family, weight):\n \"\"\"生成文字的像素集、高度、宽度\n \n text - Unicode字符串\n size - 文本大小,整形\n color - 文本颜色,list或numpy.ndarray类型,shape=(3,)\n family - 字体(系统支持的)\n weight - 粗细,light/bold/normal\n \"\"\"\n \n font_file = self.fm.get_font_file(family=family, weight=weight)\n pixels = self.fm.get_text_pixels(text, size, font_file)\n rows, cols = pixels.shape\n color = color*255\n color = np.tile(color, (rows*cols, 1)).astype(np.uint8)\n pixels = pixels.reshape(-1, 1)\n pixels = np.hstack((color, pixels)).reshape(rows, cols, 4)\n pixels = pixels[::-1].ravel()\n pixels_id = self._create_pbo(pixels)\n \n return pixels_id, rows, cols\n \n def _create_point_or_lLine(self, v, c, uvw, rand):\n \"\"\"生成点或线段的顶点集、索引集、顶点数组类型\n \n v - 顶点坐标集,numpy.ndarray类型,shape=(cols,3)\n c - 顶点颜色集,numpy.ndarray类型,shape=(3,)|(4,)|(cols,3)|(cols,4)\n uvw - 顶点着色器所用的顶点速度分量\n rand - 顶点着色器所用的顶点初始随机位置\n \"\"\"\n \n if c.ndim == 1:\n c = np.tile(c, (v.shape[0], 1))\n \n if isinstance(uvw, np.ndarray) and isinstance(rand, np.ndarray):\n if c.shape[-1] == 3:\n c = np.hstack((c, np.tile(np.array([1]), (c.shape[0], 1))))\n v_type = GL_T2F_C4F_N3F_V3F\n vertices = np.hstack((rand, c, uvw, v)).astype(np.float32)\n else:\n if c.shape[-1] == 3:\n v_type = GL_C3F_V3F\n vertices = np.hstack((c,v)).astype(np.float32)\n else:\n v_type = GL_C4F_N3F_V3F\n n = np.tile(np.array([1.0, 1.0, 1.0]), v.shape[0])\n n = n.reshape(-1, 3)\n vertices = np.hstack((c,n,v)).astype(np.float32)\n \n vertices_id = self._create_vbo(vertices)\n indices_id = self._create_ebo(np.array(list(range(v.shape[0])), dtype=np.int))\n \n return vertices_id, indices_id, v_type\n \n def _create_surface(self, v, c, t, gl_type):\n \"\"\"生成曲面的顶点集、索引集、顶点数组类型\n \n v - 顶点坐标集,numpy.ndarray类型,shape=(clos,3)\n c - 顶点的颜色集,None或numpy.ndarray类型,shape=(3|4,)|(cols,3|4)\n t - 顶点的纹理坐标集,None或numpy.ndarray类型,shape=(cols,2)\n gl_type - 绘制方法,GL_QUADS|GL_TRIANGLES\n \"\"\"\n \n n = np.tile(np.array([0.0, 0.0, 0.0]), (v.shape[0],1))\n if gl_type == GL_QUADS:\n for i in range(0, v.shape[0], 4):\n ab, ac = v[i+1]-v[i], v[i+2]-v[i]\n nk = np.cross(ac, ab)\n n[i] += nk\n n[i+1] += nk\n n[i+2] += nk\n n[i+3] += nk\n elif gl_type == GL_TRIANGLES:\n for i in range(0, v.shape[0], 3):\n ab, ac = v[i+1]-v[i], v[i+2]-v[i]\n nk = np.cross(ac, ab)\n n[i] += nk\n n[i+1] += nk\n n[i+2] += nk\n elif gl_type == GL_QUAD_STRIP:\n for i in range(2, v.shape[0], 2):\n ab, ac = v[i-1]-v[i-2], v[i+1]-v[i-2]\n nk = np.cross(ac, ab)\n n[i] += nk\n n[i+1] += nk\n n[i-1] += nk\n n[i-2] += nk\n elif gl_type == GL_TRIANGLE_STRIP:\n for i in range(2, v.shape[0], 2):\n ab, ac = v[i-1]-v[i-2], v[i]-v[i-2]\n nk = np.cross(ac, ab)\n n[i] += nk\n n[i-1] += nk\n n[i-2] += nk\n \n ab, ac = v[i]-v[i-1], v[i+1]-v[i-1]\n nk = np.cross(ac, ab)\n n[i] += nk\n n[i-1] += nk\n n[i+1] += nk\n elif gl_type == GL_TRIANGLE_FAN or gl_type == GL_POLYGON:\n for i in range(2, v.shape[0]):\n ab, ac = v[i-1]-v[0], v[i]-v[0]\n nk = np.cross(ab, ac)\n n[0] += nk\n n[i] += nk\n n[i-1] += nk\n \n if isinstance(t, np.ndarray):\n if isinstance(c, np.ndarray):\n if c.ndim == 1:\n c = np.tile(c[:3], (v.shape[0], 1))\n else:\n c = c[:,:3]\n \n v_type = GL_T2F_C3F_V3F\n vertices = np.hstack((t,c,v)).astype(np.float32)\n else:\n v_type = GL_T2F_V3F\n vertices = np.hstack((t,v)).astype(np.float32)\n else:\n if c.ndim == 1:\n c = np.tile(c, (v.shape[0], 1))\n \n if c.shape[-1] == 3:\n v_type = GL_C3F_V3F\n vertices = np.hstack((c,v)).astype(np.float32)\n else:\n v_type = GL_C4F_N3F_V3F\n vertices = np.hstack((c,util.normalize(n),v)).astype(np.float32)\n \n vertices_id = self._create_vbo(vertices)\n indices_id = self._create_ebo(np.array(list(range(v.shape[0])), dtype=np.int))\n \n return vertices_id, indices_id, v_type\n \n def _create_mesh(self, x, y, z, c, gl_type):\n \"\"\"生成网格的顶点集、索引集、顶点数组类型\n \n x - 顶点的x坐标集,numpy.ndarray类型,shape=(rows,cols)\n y - 顶点的y坐标集,numpy.ndarray类型,shape=(rows,cols)\n z - 顶点的z坐标集,numpy.ndarray类型,shape=(rows,cols)\n c - 顶点的颜色集,None或numpy.ndarray类型,shape=(3|4,)|(rows,cols,3|4)\n gl_type - 绘制方法,GL_QUADS|GL_TRIANGLES\n \"\"\"\n \n rows, cols = z.shape\n v = np.dstack((x,y,z)).reshape(-1,3)\n n = np.tile(np.array([0.0, 0.0, 0.0]), (v.shape[0],1))\n \n if gl_type == GL_QUADS:\n indices = list()\n for i in range(1, rows):\n for j in range(1, cols):\n i_a, i_b, i_c, i_d = (i-1)*cols+j-1, i*cols+j-1, i*cols+j, (i-1)*cols+j\n indices += [i_a, i_b, i_c, i_d]\n \n ab, ac = v[i_b]-v[i_a], v[i_c]-v[i_a]\n nk = np.cross(ac, ab)\n n[i_a] += nk\n n[i_b] += nk\n n[i_c] += nk\n n[i_d] += nk\n \n elif gl_type == GL_TRIANGLES:\n indices = list()\n for i in range(1, rows):\n for j in range(1,cols):\n i_a, i_b, i_c, i_d, i_e, i_f = (i-1)*cols+j-1, i*cols+j-1, i*cols+j, i*cols+j, (i-1)*cols+j, (i-1)*cols+j-1\n indices += [i_a, i_b, i_c, i_d, i_e, i_f]\n \n ab, ac = v[i_b]-v[i_a], v[i_c]-v[i_a]\n nk = np.cross(ac, ab)\n n[i_a] += nk\n n[i_b] += nk\n n[i_c] += nk\n \n ab, ac = v[i_e]-v[i_d], v[i_f]-v[i_d]\n nk = np.cross(ac, ab)\n n[i_d] += nk\n n[i_e] += nk\n n[i_f] += nk\n \n if c.ndim == 1:\n c = np.tile(c, (rows*cols, 1))\n else:\n c = c.reshape(-1, c.shape[-1])\n \n if c.shape[-1] == 3:\n v_type = GL_C3F_V3F\n vertices = np.hstack((c,v)).astype(np.float32)\n else:\n v_type = GL_C4F_N3F_V3F\n vertices = np.hstack((c,util.normalize(n),v)).astype(np.float32)\n \n vertices_id = self._create_vbo(vertices)\n indices_id = self._create_ebo(np.array(indices, dtype=np.int))\n \n return vertices_id, indices_id, v_type\n \n def _create_capsule(self, v, i, c):\n \"\"\"生成囊体的的顶点集、索引集、顶点数组类型\n \n v - 顶点集,numpy.ndarray类型,shape=(n,3)\n i - 索引集,numpy.ndarray类型,shape=(x,3)\n c - 顶点的颜色集,None或numpy.ndarray类型,shape=(3|4,)|(n,3|4)\n \"\"\"\n \n n = np.tile(np.array([0.0, 0.0, 0.0]), (v.shape[0],1))\n indices = i.astype(np.int)\n for i_a, i_b, i_c in indices:\n ab, ac = v[i_b]-v[i_a], v[i_c]-v[i_a]\n nk = np.cross(ab, ac)\n n[i_a] += nk\n n[i_b] += nk\n n[i_c] += nk\n \n if c.shape[-1] == 3:\n v_type = GL_C3F_V3F\n vertices = np.hstack((c,v)).astype(np.float32)\n else:\n v_type = GL_C4F_N3F_V3F\n vertices = np.hstack((c,util.normalize(n),v)).astype(np.float32)\n \n vertices_id = self._create_vbo(vertices)\n indices_id = self._create_ebo(indices.ravel())\n \n return vertices_id, indices_id, v_type\n \n def _add_elements(self, name, vertices_id, indices_id, v_type, gl_type, texture=None, program=None):\n \"\"\"生成绘制图元命令\n \n name - 模型名\n vertices_id - 顶点VBO的id\n indices_id - 索引EBO的id\n v_type - 顶点混合数组类型\n gl_type - 绘制方法\n texture - 纹理对象\n \"\"\"\n \n vertices_vbo = self.buffers[vertices_id]\n indices_ebo = self.buffers[indices_id]\n if texture:\n self.assembly[name]['component'].append({'cmd':self._wxglDrawTexture, 'args':[vertices_vbo, indices_ebo, v_type, gl_type, texture]})\n else:\n self.assembly[name]['component'].append({'cmd':self._wxglDrawElements, 'args':[vertices_vbo, indices_ebo, v_type, gl_type, program]})\n \n def _add_pixels(self, name, pixels_id, rows, cols, pos):\n \"\"\"生成绘制像素命令\n \n name - 模型名\n pixels_id - 像素VBO的id\n rows - 像素行数\n cols - 像素列数\n pos - 位置\n \"\"\"\n \n pixels_pbo = self.buffers[pixels_id]\n self.assembly[name]['component'].append({'cmd':self._wxglDrawPixels, 'args':[pixels_pbo, rows, cols, pos]})\n \n def _get_tick_label(self, v_min, v_max, ks=(1, 2, 2.5, 3, 4, 5), s_min=4, s_max=8, endpoint=True):\n \"\"\"返回合适的Colorbar标注值\n \n v_min - 数据最小值\n v_max - 数据最大值\n ks - 分段选项\n s_min - 分段数最小值\n s_max - 分段数最大值\n endpoint - 是否包含v_min和v_max\n \"\"\"\n \n r = v_max-v_min\n tmp = np.array([[abs(float(('%E'%(r/i)).split('E')[0])-k) for i in range(s_min,s_max+1)] for k in ks])\n i, j = divmod(tmp.argmin(), tmp.shape[1])\n step, steps = ks[i], j+s_min\n step *= pow(10, int(('%E'%(r/steps)).split('E')[1]))\n \n result = list()\n v = int(v_min/step)*step\n while v <= v_max:\n if v >= v_min:\n result.append(round(v, 6))\n v += step\n \n if len(result) > 3:\n if endpoint:\n if result[0] > v_min:\n result.insert(0, v_min)\n if result[-1] < v_max:\n result.append(v_max)\n \n if result[1]-result[0] < (result[2]-result[1])*0.25:\n result.remove(result[1])\n if result[-1]-result[-2] < (result[-2]-result[-3])*0.25:\n result.remove(result[-2])\n else:\n if result[0] == v_min or result[0]-v_min < (result[1]-result[0])*0.25:\n result.remove(result[0])\n if result[-1] == v_max or v_max-result[-1] < (result[-1]-result[-2])*0.25:\n result.remove(result[-1])\n \n return result\n \n def text2d(self, text, size=32, color=None, pos=[0,0,0], **kwds):\n \"\"\"绘制2D文字\n \n text - 文本字符串\n size - 文字大小,整型\n color - 文本颜色\n None表示使用场景对象scene的style风格提供的文本颜色\n 预定义的颜色,或形如'#FF0000'的十六进制表示的颜色\n 浮点型的元组或列表,值域范围:[0,1],长度:3\n numpy.ndarray类型,shape=(3,)\n pos - 文本位置,元组、列表或numpy数组\n kwds - 关键字参数\n align - 兼容text3d(),并无实际意义\n valign - 兼容text3d(),并无实际意义\n family - (系统支持的)字体\n weight - light/bold/normal分别表示字体的轻、重、正常(默认)\n name - 模型名\n inside - 是否更新数据动态范围\n visible - 是否显示\n \"\"\"\n \n assert isinstance(pos, (tuple, list, np.ndarray)), '期望参数pos类型是元组、列表或numpy数组'\n \n for key in kwds:\n if key not in ['align', 'valign', 'family', 'weight', 'name', 'inside', 'visible']:\n raise KeyError('不支持的关键字参数:%s'%key)\n \n align = kwds.get('align', 'center')\n valign = kwds.get('valign', 'middle')\n weight = kwds.get('weight', 'normal')\n family = kwds.get('family', None)\n name = kwds.get('name', uuid.uuid1().hex)\n inside = kwds.get('inside', True)\n visible = kwds.get('visible', True)\n \n if color:\n color = self.cm.color2c(color, alpha=None)\n else:\n color = np.array(self.scene.tc)\n \n if isinstance(pos, (tuple, list)):\n pos = np.array(pos, dtype=np.float)\n \n if inside:\n self.set_data_range((pos[0],pos[0]), (pos[1],pos[1]), (pos[2],pos[2]))\n \n pixels_id, rows, cols = self._create_text(text, size, color, family, weight)\n self.add_model(name, 'text', [pixels_id, rows, cols, pos], visible=visible)\n \n def text3d(self, text, size=32, color=None, pos=[0,0,0], **kwds):\n \"\"\"绘制3D文字\n \n text - 文本字符串\n size - 文字大小,整型\n color - 文本颜色\n None表示使用场景对象scene的style风格提供的文本颜色\n 预定义的颜色,或形如'#FF0000'的十六进制表示的颜色\n 浮点型的元组或列表,值域范围:[0,1],长度:3\n numpy.ndarray类型,shape=(3,)\n pos - 文本位置,元组、列表或numpy数组\n kwds - 关键字参数\n align - left/right/center分别表示左对齐、右对齐、居中(默认)\n valign - top/bottom/middle分别表示上对齐、下对齐、垂直居中(默认)\n family - (系统支持的)字体\n weight - light/bold/normal分别表示字体的轻、重、正常(默认)\n name - 模型名\n inside - 是否更新数据动态范围\n visible - 是否显示\n \"\"\"\n \n assert isinstance(pos, (tuple, list, np.ndarray)), '期望参数pos类型是元组、列表或numpy数组'\n \n for key in kwds:\n if key not in ['align', 'valign', 'family', 'weight', 'name', 'inside', 'visible']:\n raise KeyError('不支持的关键字参数:%s'%key)\n \n align = kwds.get('align', 'center')\n valign = kwds.get('valign', 'middle')\n weight = kwds.get('weight', 'normal')\n family = kwds.get('family', None)\n name = kwds.get('name', uuid.uuid1().hex)\n inside = kwds.get('inside', True)\n visible = kwds.get('visible', True)\n \n if isinstance(pos, (tuple, list)):\n pos = np.array(pos, dtype=np.float)\n \n if isinstance(color,(str, tuple, list, np.ndarray)):\n color = self.cm.color2c(color, alpha=None)\n else:\n color = np.array(self.scene.tc)\n \n font_file = self.fm.get_font_file(family=family, weight=weight)\n pixels = self.fm.get_text_pixels(text, 64, font_file)\n rows, cols = pixels.shape\n \n x = np.ones(pixels.shape)*color[0]*255\n y = np.ones(pixels.shape)*color[1]*255\n z = np.ones(pixels.shape)*color[2]*255\n im = np.dstack((x,y,z,pixels)).astype(np.uint8)\n \n k = 1/256\n w, h = k*size*cols/rows, k*size\n \n if self.fixed:\n head = 'y+'\n else:\n head = self.scene.head\n \n if head == 'x+':\n if align == 'center':\n pos[2] -= w/2\n elif align == 'right':\n pos[2] -= w\n \n if valign == 'middle':\n pos[0] += h/2\n elif valign == 'bottom':\n pos[0] += h\n \n vs = [[pos[0],pos[1],pos[2]], [pos[0]-h,pos[1],pos[2]], [pos[0]-h,pos[1],pos[2]+w], [pos[0],pos[1],pos[2]+w]]\n elif head == 'y+':\n if align == 'center':\n pos[0] -= w/2\n elif align == 'right':\n pos[0] -= w\n \n if valign == 'middle':\n pos[1] += h/2\n elif valign == 'bottom':\n pos[1] += h\n \n vs = [[pos[0],pos[1],pos[2]], [pos[0],pos[1]-h,pos[2]], [pos[0]+w,pos[1]-h,pos[2]], [pos[0]+w,pos[1],pos[2]]]\n else:\n if align == 'center':\n pos[1] -= w/2\n elif align == 'right':\n pos[1] -= w\n \n if valign == 'middle':\n pos[2] += h/2\n elif valign == 'bottom':\n pos[2] += h\n \n vs = [[pos[0],pos[1],pos[2]], [pos[0],pos[1],pos[2]-h], [pos[0],pos[1]+w,pos[2]-h], [pos[0],pos[1]+w,pos[2]]]\n \n texture = self.create_texture(im)\n texcoord = np.array([[0,1],[0,0],[1,0],[1,1]])\n self.surface(np.array(vs), texcoord=texcoord, texture=texture, name=name, inside=inside, visible=visible)\n \n def point(self, vs, color, size=None, **kwds):\n \"\"\"绘制点\n \n vs - 顶点坐标集,numpy.ndarray类型,shape=(n,3)\n color - 顶点或顶点集颜色\n 预定义的颜色,或形如'#FF0000'的十六进制表示的颜色\n 浮点型的元组或列表,值域范围:[0,1],长度:3\n numpy.ndarray类型,shape=(3,)|(4,)|(n,3)|(n,4)\n size - 点的大小,整数,None表示使用当前设置\n kwds - 关键字参数\n name - 模型名\n inside - 是否更新数据动态范围\n visible - 是否显示\n program - 着色器程序\n \"\"\"\n \n for key in kwds:\n if key not in ['name', 'inside', 'visible', 'program']:\n raise KeyError('不支持的关键字参数:%s'%key)\n \n name = kwds.get('name', uuid.uuid1().hex)\n inside = kwds.get('inside', True)\n visible = kwds.get('visible', True)\n program = kwds.get('program', None)\n \n if inside:\n r_x = (np.nanmin(vs[:,0]),np.nanmax(vs[:,0]))\n r_y = (np.nanmin(vs[:,1]),np.nanmax(vs[:,1]))\n r_z = (np.nanmin(vs[:,2]),np.nanmax(vs[:,2]))\n self.set_data_range(r_x, r_y, r_z)\n \n if program:\n uvw, rand = self.timers[program[2]]['uvw'], self.timers[program[2]]['rand']\n else:\n uvw, rand = None, None\n \n color = self.cm.color2c(color, shape=vs.shape[:-1])\n vertices_id, indices_id, v_type = self._create_point_or_lLine(vs, color, uvw, rand)\n self.add_model(name, 'point', [vertices_id, indices_id, v_type, GL_POINTS, size, program], visible=visible)\n \n def line(self, vs, color, method='SINGLE', width=None, stipple=None, **kwds):\n \"\"\"绘制线段\n \n vs - 顶点坐标集,numpy.ndarray类型,shape=(n,3)\n color - 顶点或顶点集颜色\n 预定义的颜色,或形如'#FF0000'的十六进制表示的颜色\n 浮点型的元组或列表,值域范围:[0,1],长度:3\n numpy.ndarray类型,shape=(3,)|(4,)|(n,3)|(n,4)\n method - 绘制方法\n 'MULTI' - 线段\n 'SINGLE' - 连续线段\n 'LOOP' - 闭合线段\n width - 线宽,0.0~10.0之间,None表示使用当前设置\n stipple - 线型,整数和两字节十六进制整数组成的元组,形如(1,0xFFFF)。None表示使用当前设置\n kwds - 关键字参数\n name - 模型名\n inside - 是否更新数据动态范围\n visible - 是否显示\n program - 着色器程序\n \"\"\"\n \n for key in kwds:\n if key not in ['name', 'inside', 'visible', 'program']:\n raise KeyError('不支持的关键字参数:%s'%key)\n \n name = kwds.get('name', uuid.uuid1().hex)\n inside = kwds.get('inside', True)\n visible = kwds.get('visible', True)\n program = kwds.get('program', None)\n \n if inside:\n r_x = (np.nanmin(vs[:,0]),np.nanmax(vs[:,0]))\n r_y = (np.nanmin(vs[:,1]),np.nanmax(vs[:,1]))\n r_z = (np.nanmin(vs[:,2]),np.nanmax(vs[:,2]))\n self.set_data_range(r_x, r_y, r_z)\n \n if program:\n uvw, rand = self.timers[program[2]]['uvw'], self.timers[program[2]]['rand']\n else:\n uvw, rand = None, None\n \n color = self.cm.color2c(color, shape=vs.shape[:-1])\n gl_type = {'MULTI':GL_LINES, 'SINGLE':GL_LINE_STRIP, 'LOOP':GL_LINE_LOOP}[method]\n vertices_id, indices_id, v_type = self._create_point_or_lLine(vs, color, uvw, rand)\n self.add_model(name, 'line', [vertices_id, indices_id, v_type, gl_type, width, stipple, program], visible=visible)\n \n def surface(self, vs, color=None, texcoord=None, texture=None, method='Q', mode=None, **kwds):\n \"\"\"绘制曲面\n \n vs - 顶点坐标集,numpy.ndarray类型,shape=(n,3)\n color - 顶点或顶点集颜色\n None表示仅使用纹理\n 预定义的颜色,或形如'#FF0000'的十六进制表示的颜色\n 浮点型的元组或列表,值域范围:[0,1],长度:3\n numpy.ndarray类型,shape=(3|4,)|(n,3|4)\n texcoord - 顶点的纹理坐标集,numpy.ndarray类型,shape=(n,2)\n texture - 2D纹理对象\n method - 绘制方法\n 'Q' - 四边形\n 0--3 4--7\n | | | |\n 1--2 5--6\n 'T' - 三角形\n 0--2 3--5\n \\/ \\/\n 1 4\n 'Q+' - 边靠边的连续四边形\n 0--2--4\n | | |\n 1--3--5\n 'T+' - 边靠边的连续三角形\n 0--2--4\n \\/_\\/_\\\n 1 3 5\n 'F' - 扇形\n 'P' - 多边形\n mode - 显示模式\n None - 使用当前设置\n 'FCBC' - 前后面填充颜色FCBC\n 'FLBL' - 前后面显示线条FLBL\n 'FCBL' - 前面填充颜色,后面显示线条FCBL\n 'FLBC' - 前面显示线条,后面填充颜色FLBC\n kwds - 关键字参数\n name - 模型名\n inside - 是否更新数据动态范围\n visible - 是否显示\n program - 着色器程序\n light - 材质灯光颜色,None表示关闭材质灯光\n \"\"\"\n \n for key in kwds:\n if key not in ['name', 'inside', 'visible', 'program', 'light']:\n raise KeyError('不支持的关键字参数:%s'%key)\n \n name = kwds.get('name', uuid.uuid1().hex)\n inside = kwds.get('inside', True)\n visible = kwds.get('visible', True)\n program = kwds.get('program', None)\n light = kwds.get('light', None)\n \n if inside:\n r_x = (np.nanmin(vs[:,0]),np.nanmax(vs[:,0]))\n r_y = (np.nanmin(vs[:,1]),np.nanmax(vs[:,1]))\n r_z = (np.nanmin(vs[:,2]),np.nanmax(vs[:,2]))\n self.set_data_range(r_x, r_y, r_z)\n \n if isinstance(color,(str, tuple, list, np.ndarray)):\n color = self.cm.color2c(color, shape=vs.shape[:-1])\n \n if color is None and (texcoord is None or texture is None):\n color = self.cm.color2c(self.scene.tc, shape=vs.shape[:-1])\n \n gl_type = {'Q':GL_QUADS, 'T':GL_TRIANGLES, 'Q+':GL_QUAD_STRIP, 'T+':GL_TRIANGLE_STRIP, 'F':GL_TRIANGLE_FAN, 'P':GL_POLYGON}[method]\n vertices_id, indices_id, v_type = self._create_surface(vs, color, texcoord, gl_type)\n self.add_model(name, 'surface', [vertices_id, indices_id, v_type, gl_type, mode, texture, program], visible=visible, light=light)\n \n def mesh(self, xs, ys, zs, color, method='Q', mode=None, **kwds):\n \"\"\"绘制网格\n \n xs - 顶点集的x坐标集,numpy.ndarray类型,shape=(rows,cols)\n ys - 顶点集的y坐标集,numpy.ndarray类型���shape=(rows,cols)\n zs - 顶点集的z坐标集,numpy.ndarray类型,shape=(rows,cols)\n color - 顶点或顶点集颜色\n 预定义的颜色,或形如'#FF0000'的十六进制表示的颜色\n 浮点型的元组或列表,值域范围:[0,1],长度:3\n numpy.ndarray类型,shape=(3|4,)|(rows,cols,3|4)\n method - 绘制方法:\n 'Q' - 四边形\n 'T' - 三角形\n mode - 显示模式\n None - 使用当前设置\n 'FCBC' - 前后面填充颜色FCBC\n 'FLBL' - 前后面显示线条FLBL\n 'FCBL' - 前面填充颜色,后面显示线条FCBL\n 'FLBC' - 前面显示线条,后面填充颜色FLBC\n kwds - 关键字参数\n blc - 边框的颜色,None表示无边框\n blw - 边框宽度\n name - 模型名\n inside - 是否更新数据动态范围\n visible - 是否显示\n program - 着色器程序\n light - 材质灯光颜色,None表示关闭材质灯光\n \"\"\"\n \n for key in kwds:\n if key not in ['blc', 'blw', 'name', 'inside', 'visible', 'program', 'light']:\n raise KeyError('不支持的关键字参数:%s'%key)\n \n blc = kwds.get('inside', None)\n blw = kwds.get('inside', 1.0)\n name = kwds.get('name', uuid.uuid1().hex)\n inside = kwds.get('inside', True)\n visible = kwds.get('visible', True)\n program = kwds.get('program', None)\n light = kwds.get('light', None)\n \n if inside:\n self.set_data_range((np.nanmin(xs),np.nanmax(xs)), (np.nanmin(ys),np.nanmax(ys)), (np.nanmin(zs),np.nanmax(zs)))\n \n color = self.cm.color2c(color, shape=zs.shape)\n gl_type = {'Q':GL_QUADS, 'T':GL_TRIANGLES}[method]\n vertices_id, indices_id, v_type = self._create_mesh(xs, ys, zs, color, gl_type)\n self.add_model(name, 'mesh', [vertices_id, indices_id, v_type, gl_type, mode, None, program], visible=visible, light=light)\n \n if isinstance(blc, (str, list, tuple, np.ndarray)):\n top_x = xs[0,1:-1]\n top_y = ys[0,1:-1]\n top_z = zs[0,1:-1]\n\n bottom_x = xs[-1,1:-1][::-1]\n bottom_y = ys[-1,1:-1][::-1]\n bottom_z = zs[-1,1:-1][::-1]\n\n right_x = xs[:,-1]\n right_y = ys[:,-1]\n right_z = zs[:,-1]\n\n left_x = xs[:,0][::-1]\n left_y = ys[:,0][::-1]\n left_z = zs[:,0][::-1]\n\n x = np.hstack((top_x, right_x, bottom_x, left_x))\n y = np.hstack((top_y, right_y, bottom_y, left_y))\n z = np.hstack((top_z, right_z, bottom_z, left_z))\n v = np.dstack((x, y, z))[0]\n \n self.line(v, blc, method='LOOP', width=blw, name=name, inside=inside, visible=visible)\n \n def sphere(self, center, radius, color, mode='FLBL', slices=60, **kwds):\n \"\"\"绘制球体\n \n center - 球心坐标,元组、列表或numpy数组\n radius - 半径,浮点型\n color - 表面颜色\n mode - 显示模式\n None - 使用当前设置\n 'FCBC' - 前后面填充颜色FCBC\n 'FLBL' - 前后面显示线条FLBL\n 'FCBL' - 前面填充颜色,后面显示线条FCBL\n 'FLBC' - 前面显示线条,后面填充颜色FLBC\n slices - 锥面分片数(数值越大越精细)\n kwds - 关键字参数\n name - 模型名\n inside - 是否更新数据动态范围\n visible - 是否显示\n light - 材质灯光开关\n \"\"\"\n \n for key in kwds:\n if key not in ['name', 'inside', 'visible', 'light']:\n raise KeyError('不支持的关键字参数:%s'%key)\n \n name = kwds.get('name', uuid.uuid1().hex)\n inside = kwds.get('inside', True)\n visible = kwds.get('visible', True)\n light = kwds.get('light', True)\n \n lats, lons = np.mgrid[-np.pi/2:np.pi/2:complex(0,slices/2+1), 0:2*np.pi:complex(0,slices+1)]\n xs = radius*np.cos(lats)*np.cos(lons) + center[0]\n ys = radius*np.cos(lats)*np.sin(lons) + center[1]\n zs = radius*np.sin(lats) + center[2]\n \n if light:\n light = self.cm.color2c(color)\n else:\n light = None\n \n self.mesh(xs, ys, zs, color, method='T', mode=mode, name=name, inside=inside, visible=visible, light=light) \n \n def cube(self, center, side, color, mode='FLBL', **kwds):\n \"\"\"绘制六面体\n \n center - 中心坐标,元组、列表或numpy数组\n side - 棱长,整型、浮点型,或长度为3的元组、列表、numpy数组\n color - 顶点或顶点集颜色\n 预定义的颜色,或形如'#FF0000'的十六进制表示的颜色\n 浮点型的元组或列表,值域范围:[0,1],长度:3\n numpy.ndarray类型,shape=(3|4,)|(rows,cols,3|4)\n mode - 显示模式\n None - 使用当前设置\n 'FCBC' - 前后面填充颜色FCBC\n 'FLBL' - 前后面显示线条FLBL\n 'FCBL' - 前面填充颜色,后面显示线条FCBL\n 'FLBC' - 前面显示线条,后面填充颜色FLBC\n kwds - 关键字参数\n name - 模型名\n inside - 是否更新数据动态范围\n visible - 是否显示\n light - 材质灯光开关\n \"\"\"\n \n for key in kwds:\n if key not in ['name', 'inside', 'visible', 'light']:\n raise KeyError('不支持的关键字参数:%s'%key)\n \n name = kwds.get('name', uuid.uuid1().hex)\n inside = kwds.get('inside', True)\n visible = kwds.get('visible', True)\n light = kwds.get('light', True)\n \n if isinstance(side, (tuple, list, np.ndarray)):\n x, y, z = side\n elif isinstance(side, (int, float)):\n x, y, z = side, side, side\n else:\n raise ValueError(\"期望参数side是整型、浮点型,或长度为3的元组、列表、numpy数组\")\n \n vs_front = np.array(((x/2,-y/2,-z/2),(x/2,-y/2,z/2),(x/2,y/2,z/2),(x/2,y/2,-z/2))) + center\n vs_back = np.array(((-x/2,y/2,-z/2),(-x/2,y/2,z/2),(-x/2,-y/2,z/2),(-x/2,-y/2,-z/2))) + center\n vs_top = np.array(((-x/2,y/2,z/2),(x/2,y/2,z/2),(x/2,-y/2,z/2),(-x/2,-y/2,z/2))) + center\n vs_bottom = np.array(((-x/2,-y/2,-z/2),(x/2,-y/2,-z/2),(x/2,y/2,-z/2),(-x/2,y/2,-z/2))) + center\n vs_left = np.array(((x/2,-y/2,z/2),(x/2,-y/2,-z/2),(-x/2,-y/2,-z/2),(-x/2,-y/2,z/2))) + center\n vs_right = np.array(((-x/2,y/2,z/2),(-x/2,y/2,-z/2),(x/2,y/2,-z/2),(x/2,y/2,z/2))) + center\n \n if light:\n light = self.cm.color2c(color)\n else:\n loght = None\n \n self.surface(vs_front, color=color, mode=mode, name=name, inside=inside, visible=visible, light=light)\n self.surface(vs_back, color=color, mode=mode, name=name, inside=inside, visible=visible, light=light)\n self.surface(vs_top, color=color, mode=mode, name=name, inside=inside, visible=visible, light=light)\n self.surface(vs_bottom, color=color, mode=mode, name=name, inside=inside, visible=visible, light=light)\n self.surface(vs_left, color=color, mode=mode, name=name, inside=inside, visible=visible, light=light)\n self.surface(vs_right, color=color, mode=mode, name=name, inside=inside, visible=visible, light=light)\n \n def cone(self, center, spire, radius, color, slices=50, mode='FCBC', **kwds):\n \"\"\"绘制圆锥体\n \n center - 锥底圆心坐标,元组、列表或numpy数组\n spire - 锥尖坐标,元组、列表或numpy数组\n radius - 锥底半径,浮点型\n color - 圆锥颜色\n 预定义的颜色,或形如'#FF0000'的十六进制表示的颜色\n 浮点型的元组或列表,值域范围:[0,1],长度:3\n numpy.ndarray类型,shape=(3,)\n slices - 锥面分片数(数值越大越精细)\n mode - 显示模式\n None - 使用当前设置\n 'FCBC' - 前后面填充颜色FCBC\n 'FLBL' - 前后面显示线条FLBL\n 'FCBL' - 前面填充颜色,后面显示线条FCBL\n 'FLBC' - 前面显示线条,后面填充颜色FLBC\n kwds - 关键字参数\n name - 模型名\n inside - 是否更新数据动态范围\n visible - 是否显示\n light - 材质灯光开关\n \"\"\"\n \n for key in kwds:\n if key not in ['name', 'inside', 'visible', 'light']:\n raise KeyError('不支持的关键字参数:%s'%key)\n \n name = kwds.get('name', uuid.uuid1().hex)\n inside = kwds.get('inside', True)\n visible = kwds.get('visible', True)\n light = kwds.get('light', True)\n \n if not isinstance(spire, np.ndarray):\n spire = np.array(spire)\n \n if not isinstance(center, np.ndarray):\n center = np.array(center)\n \n rotator, h = util.rotate(spire-center)\n \n theta = np.linspace(0, 2*np.pi, slices+1)\n xs = np.cos(theta) * radius\n ys = np.sin(theta) * radius\n zs = np.zeros_like(theta)\n \n v_cone = np.dstack((np.hstack((0, xs)), np.hstack((0, ys)), np.hstack((h, zs))))[0]\n v_ground = np.dstack((np.hstack((0, xs)), np.hstack((0, ys)), np.hstack((0, zs))))[0]\n v_cone = rotator.apply(v_cone) + center\n v_ground = rotator.apply(v_ground) + center\n \n if light:\n light = self.cm.color2c(color)\n else:\n loght = None\n \n self.surface(v_cone, color, method='F', mode=mode, name=name, inside=inside, visible=visible, light=light)\n self.surface(v_ground, color, method='F', mode=mode, name=name, inside=inside, visible=visible, light=light)\n \n def cylinder(self, v_top, v_bottom, radius, color, slices=50, mode='FCBC', **kwds):\n \"\"\"绘制圆柱体\n \n v_top - 圆柱上端面的圆心坐标,元组、列表或numpy数组\n v_bottom - 圆柱下端面的圆心坐标,元组、列表或numpy数组\n radius - 圆柱半径,浮点型\n color - 圆柱颜色\n 预定义的颜色,或形如'#FF0000'的十六进制表示的颜色\n 浮点型的元组或列表,值域范围:[0,1],长度:3\n numpy.ndarray类型,shape=(3|4,)|(2,3|4)\n slices - 圆柱面分片数(数值越大越精细)\n mode - 显示模式\n None - 使用当前设置\n 'FCBC' - 前后面填充颜色FCBC\n 'FLBL' - 前后面显示线条FLBL\n 'FCBL' - 前面填充颜色,后面显示线条FCBL\n 'FLBC' - 前面显示线条,后面填充颜色FLBC\n kwds - 关键字参数\n headface - 是否显示圆柱端面\n name - 模型名\n inside - 是否更新数据动态范围\n visible - 是否显示\n \"\"\"\n \n for key in kwds:\n if key not in ['headface', 'name', 'inside', 'visible']:\n raise KeyError('不支持的关键字参数:%s'%key)\n \n headface = kwds.get('headface', True)\n name = kwds.get('name', uuid.uuid1().hex)\n inside = kwds.get('inside', True)\n visible = kwds.get('visible', True)\n \n color = self.cm.color2c(color, shape=(2,))\n if (color[0] == color[1]).all():\n light = color[0]\n else:\n light = None\n \n if not isinstance(v_top, np.ndarray):\n v_top = np.array(v_top)\n if not isinstance(v_bottom, np.ndarray):\n v_bottom = np.array(v_bottom)\n \n rotator, h = util.rotate(v_bottom-v_top)\n \n theta = np.linspace(0, 2*np.pi, slices+1)\n xs = np.cos(theta) * radius\n ys = np.sin(theta) * radius\n zs0 = np.zeros_like(theta)\n zs1 = np.ones_like(theta) * h\n \n vv, cc = list(), list()\n for i in range(len(theta)):\n vv += [\n [xs[i], ys[i], zs1[i]],\n [xs[i], ys[i], zs0[i]]\n ]\n cc += [color[1], color[0]]\n \n vv = rotator.apply(np.array(vv)) + v_top\n cc = np.vstack(cc)\n self.surface(vv, cc, method='Q+', mode=mode, name=name, inside=inside, visible=visible, light=light)\n \n if headface:\n hf0 = np.dstack((np.hstack((0, xs)), np.hstack((0, ys)), np.hstack((0, zs0))))[0]\n hf1 = np.dstack((np.hstack((0, xs)), np.hstack((0, ys)), np.hstack((h, zs1))))[0]\n \n hf0 = rotator.apply(hf0) + v_top\n hf1 = rotator.apply(hf1) + v_top\n \n self.surface(hf0, color[0], method='F', mode=mode, name=name, inside=inside, visible=visible, light=light)\n self.surface(hf1, color[1], method='F', mode=mode, name=name, inside=inside, visible=visible, light=light)\n \n def pipe(self, vs, radius, color, slices=36, mode='FCBC', **kwds):\n \"\"\"绘制圆管线\n \n vs - 圆管中心点坐标集,numpy.ndarray类型,shape=(n,3)\n radius - 圆管半径,浮点型\n color - 圆管颜色\n 预定义的颜色,或形如'#FF0000'的十六进制表示的颜色\n 浮点型的元组或列表,值域范围:[0,1],长度:3\n numpy.ndarray类型,shape=(3|4,)|(n,3|4)\n slices - 圆管面分片数(数值���大越精细)\n mode - 显示模式\n None - 使用当前设置\n 'FCBC' - 前后面填充颜色FCBC\n 'FLBL' - 前后面显示线条FLBL\n 'FCBL' - 前面填充颜色,后面显示线条FCBL\n 'FLBC' - 前面显示线条,后面填充颜色FLBC\n kwds - 关键字参数\n name - 模型名\n inside - 是否更新数据动态范围\n visible - 是否显示\n \"\"\"\n \n for key in kwds:\n if key not in ['headface', 'name', 'inside', 'visible']:\n raise KeyError('不支持的关键字参数:%s'%key)\n \n headface = kwds.get('headface', True)\n name = kwds.get('name', uuid.uuid1().hex)\n inside = kwds.get('inside', True)\n visible = kwds.get('visible', True)\n \n cs = self.cm.color2c(color, shape=vs.shape[:1])\n theta = np.linspace(0, 2*np.pi, slices+1)\n xs = np.cos(theta) * radius\n ys = np.sin(theta) * radius\n zs0 = np.zeros_like(theta)\n \n if isinstance(color, np.ndarray) and color.ndim == 2:\n light = None\n else:\n light = cs[0]\n \n for k in range(vs.shape[0])[:-1]:\n v0, v1 = vs[k], vs[k+1]\n rotator, h = util.rotate(v1-v0)\n zs1 = np.ones_like(theta) * h\n \n if k == 0:\n base = rotator.apply([[xs[i], ys[i], zs0[i]] for i in range(len(theta))]) + v0\n curr = rotator.apply([[xs[i], ys[i], zs1[i]] for i in range(len(theta))]) + v0\n \n vv, cc = list(), list()\n for i in range(len(theta)):\n vv += [base[i], curr[i]]\n cc += [cs[k], cs[k+1]]\n \n base = curr\n vv = np.vstack(vv)\n cc = np.vstack(cc)\n self.surface(vv, cc, method='Q+', mode=mode, name=name, inside=inside, visible=visible, light=light)\n \n def capsule(self, data, threshold, color, r_x=None, r_y=None, r_z=None, mode='FLBL', **kwds):\n \"\"\"绘制囊(三维等值面)\n \n data - 数据集,numpy.ndarray类型,shape=(layers,rows,cols)\n threshold - 阈值,浮点型\n color - 表面颜色\n r_x - x的动态范围,元组\n r_y - y的动态范围,元组\n r_z - z的动态范围,元组\n mode - 显示模式\n None - 使用当前设置\n 'FCBC' - 前后面填充颜色FCBC\n 'FLBL' - 前后面显示线条FLBL\n 'FCBL' - 前面填充颜色,后面显示线条FCBL\n 'FLBC' - 前面显示线条,后面填充颜色FLBC\n kwds - 关键字参数\n name - 模型名\n inside - 是否更新数据动态范围\n visible - 是否显示\n light - 材质灯光开关\n \"\"\"\n \n for key in kwds:\n if key not in ['name', 'inside', 'visible', 'light']:\n raise KeyError('不支持的关键字参数:%s'%key)\n \n name = kwds.get('name', uuid.uuid1().hex)\n inside = kwds.get('inside', True)\n visible = kwds.get('visible', True)\n light = kwds.get('light', True)\n \n data = np.rollaxis(data, 2)\n data = np.rollaxis(data, 2, 1)\n \n vs, idxs = util.find_capsule(data[:,:,::-1], threshold)\n cs = self.cm.color2c(color, shape=vs.shape[:1])\n \n if light:\n light = cs[0]\n else:\n light = None\n \n if r_x and r_y and r_z:\n xs, ys, zs = vs[:,0], vs[:,1], vs[:,2]\n x0, x1 = 0, data.shape[0]\n y0, y1 = 0, data.shape[1]\n z0, z1 = 0, data.shape[2]\n \n xs = r_x[0] + (xs-x0)*(r_x[1]-r_x[0])/(x1-x0)\n ys = r_y[0] + (ys-y0)*(r_y[1]-r_y[0])/(y1-y0)\n zs = r_z[0] + (zs-z0)*(r_z[1]-r_z[0])/(z1-z0)\n vs = np.stack((xs, ys, zs), axis=1)\n \n if inside:\n r_x = (np.nanmin(vs[:,0]),np.nanmax(vs[:,0]))\n r_y = (np.nanmin(vs[:,1]),np.nanmax(vs[:,1]))\n r_z = (np.nanmin(vs[:,2]),np.nanmax(vs[:,2]))\n self.set_data_range(r_x, r_y, r_z)\n \n gl_type = GL_TRIANGLES\n vertices_id, indices_id, v_type = self._create_capsule(vs, idxs, cs)\n self.add_model(name, 'mesh', [vertices_id, indices_id, v_type, gl_type, mode, None, None], visible=visible, light=light)\n \n def volume(self, data, x=None, y=None, z=None, method='Q', **kwds):\n \"\"\"绘制体数据\n \n data - 顶点的颜色集,numpy.ndarray类型,shape=(layers,rows,cols,4)\n x - 顶点的x坐标集,numpy.ndarray类型,shape=(rows,cols)。缺省则使用volume的2轴索引构造\n y - 顶点的y坐标集,numpy.ndarray类型,shape=(rows,cols)。缺省则使用volume的1轴索引构造\n z - 顶点的z坐标集,numpy.ndarray类型,shape=(layers,)。缺省则使用volume的0轴索引构造\n method - 绘制方法:\n 'Q' - 四边形\n 'T' - 三角形\n kwds - 关键字参数\n name - 模型名\n inside - 是否更新数据动态范围\n visible - 是否显示\n \"\"\"\n \n for key in kwds:\n if key not in ['name', 'inside', 'visible']:\n raise KeyError('不支持的关键字参数:%s'%key)\n \n name = kwds.get('name', uuid.uuid1().hex)\n inside = kwds.get('inside', True)\n visible = kwds.get('visible', True)\n \n assert isinstance(data, np.ndarray) and data.ndim == 4, '期望参数volume类型是一个4维的numpy数组'\n assert data.shape[-1] == 4, '期望参数volume是RBGA类型的数据'\n \n \n mode = 'FCBC'\n d, h, w = data.shape[0], data.shape[1], data.shape[2]\n \n if not isinstance(x, np.ndarray) and x == None:\n x = np.tile(np.arange(w, dtype=np.float), (h,1)) \n x *= 2.0/max(d,h,w)\n x -= x.max()/2.0\n \n if not isinstance(y, np.ndarray) and y == None:\n y = np.arange(h, dtype=np.float).repeat(w).reshape((h,w)) \n y *= 2.0/max(d,h,w)\n y -= y.max()/2.0\n \n if not isinstance(z, np.ndarray) and z == None:\n z = np.arange(d, dtype=np.float) \n z *= 2.0/max(d,h,w)\n z -= z.max()/2.0\n \n for i in range(d):\n self.mesh(x, y, z[i]*np.ones_like(x), data[i], method=method, mode=mode, name=name, inside=inside, visible=visible)\n \n z_h = z.repeat(h).reshape((-1, h))\n for i in range(w):\n x_h = np.tile(x[:,i], (d,1))\n y_h = np.tile(y[:,i], (d,1))\n c_h = data[:d,:,i]\n self.mesh(x_h, y_h, z_h, c_h, method=method, mode=mode, name=name, inside=inside, visible=visible)\n \n z_v = z.repeat(w).reshape((-1, w))\n for i in range(h):\n x_v = np.tile(x[i,:], (d,1))\n y_v = np.tile(y[i,:], (d,1))\n c_v = data[:d,i,:]\n self.mesh(x_v, y_v, z_v, c_v, method=method, mode=mode, name=name, inside=inside, visible=visible)\n \n def coordinate(self, length=1.0, xlabel=None, ylabel=None, zlabel=None, **kwds):\n \"\"\"绘制坐标轴\n \n length - 坐标轴半轴长度,从-length到length\n xlabel - x轴标注\n ylabel - y轴标注\n zlabel - z轴标注\n kwds - 关键字参数\n half - 是否画半轴\n slices - 锥面分片数(数值越大越精细)\n label_size - 标注文本的字号\n name - 模型名\n inside - 是否更新数据动态范围\n visible - 是否显示\n \"\"\"\n \n for key in kwds:\n if key not in ['half', 'label_size', 'slices', 'name', 'inside', 'visible']:\n raise KeyError('不支持的关键字参数:%s'%key)\n \n half = kwds.get('half', False)\n slices = kwds.get('slices', 32)\n label_size = kwds.get('label_size', 40)\n name = kwds.get('name', uuid.uuid1().hex)\n inside = kwds.get('inside', True)\n visible = kwds.get('visible', True)\n \n if half:\n start = 0\n else:\n start = -length\n \n c_x, c_y, c_z = [1,0,0], [0,1,0], [0,0,1]\n v = np.array([[start,0,0],[0.8*length,0,0],[0,start,0],[0,0.8*length,0],[0,0,start],[0,0,0.8*length]])\n c = np.array([c_x, c_x, c_y, c_y, c_z, c_z])\n radius = 0.03*length\n \n self.line(v, c, method='MULTI', name=name, inside=inside, visible=visible)\n self.cone(np.array([0.8*length,0,0]), np.array([length,0,0]), radius, c_x, slices=slices, name=name, inside=inside, visible=visible)\n self.cone(np.array([0,0.8*length,0]), np.array([0,length,0]), radius, c_y, slices=slices, name=name, inside=inside, visible=visible)\n self.cone(np.array([0,0,0.8*length]), np.array([0,0,length]), radius, c_z, slices=slices, name=name, inside=inside, visible=visible)\n \n if xlabel:\n self.text2d(xlabel, size=label_size, color=c_x, pos=[length,0,0], name=name, inside=inside, visible=visible)\n if ylabel:\n self.text2d(ylabel, size=label_size, color=c_y, pos=[0,length,0], name=name, inside=inside, visible=visible)\n if zlabel:\n self.text2d(zlabel, size=label_size, color=c_z, pos=[0,0,length], name=name, inside=inside, visible=visible)\n \n def colorbar(self, drange, cmap, loc='right', **kwds):\n \"\"\"绘制colorBar \n \n drange - 值域范围,tuple类型\n cmap - 调色板名称\n loc - 位置,top|bottom|left|right\n kwds - 关键字参数\n length - ColorBar所在视区的长边长度,默认短边长度为1\n subject - 标题\n subject_size - 标题字号\n label_size - 标注字号\n label_format - 标注格式化所用lambda函数\n tick_line - 刻度线长度\n endpoint - 刻度是否包含值域范围的两个端点值\n name - 模型名\n inside - 是否更新数据动态范围\n visible - 是否显示\n \"\"\"\n \n assert isinstance(drange, (tuple, list)) and len(drange) == 2, '期望参数drange是长度为2的元组或列表'\n assert loc in ('top','bottom','left','right'), '期望参数loc为top|bottom|left|right其中之一'\n \n for key in kwds:\n if key not in ('length','subject','subject_size','label_size','label_format','tick_line','endpoint','name','inside', 'visible'):\n raise KeyError('不支持的关键字参数:%s'%key)\n \n length = kwds.get('length', 2)\n subject = kwds.get('subject', None)\n subject_size = kwds.get('subject_size', 48)\n label_size = kwds.get('label_size', 32)\n label_format = kwds.get('label_format', str)\n tick_line = kwds.get('tick_line', 0.1)\n endpoint = kwds.get('endpoint', False)\n name = kwds.get('name', uuid.uuid1().hex)\n inside = kwds.get('inside', True)\n visible = kwds.get('visible', True)\n \n if subject:\n if loc == 'left':\n self.text3d(subject, size=subject_size, pos=(0.1,length-0.1,0), valign='top', name=name, inside=inside, visible=visible)\n x_min, x_max = 0.1, 0.6\n y_min, y_max = -length, length-0.5\n elif loc == 'right':\n self.text3d(subject, size=subject_size, pos=(-0.1,length-0.1,0), valign='top', name=name, inside=inside, visible=visible)\n x_min, x_max = -0.6, -0.1\n y_min, y_max = -length, length-0.5\n elif loc == 'bottom':\n self.text3d(subject, size=subject_size, pos=(0,0.7,0), valign='top', name=name, inside=inside, visible=visible)\n x_min, x_max = -length, length\n y_min, y_max = -0.1, 0.4\n else:\n self.text3d(subject, size=subject_size, pos=(0,0.7,0), valign='top', name=name, inside=inside, visible=visible)\n x_min, x_max = -length, length\n y_min, y_max = -0.1, 0.4\n else:\n if loc == 'left':\n x_min, x_max = 0.1, 0.6\n y_min, y_max = -length, length\n elif loc == 'right':\n x_min, x_max = -0.6, -0.1\n y_min, y_max = -length, length\n else:\n x_min, x_max = -length, length\n y_min, y_max = 0, 0.5\n \n \n v_min, v_max = drange\n xs, ys, zs, cs = list(), list(), list(), list()\n tick_label = self._get_tick_label(v_min, v_max, endpoint=endpoint)\n \n for k, rgb in self.cm.cms[cmap]:\n if loc == 'left' or loc == 'right':\n y = y_min + k*(y_max-y_min)\n xs.append([x_min, x_max])\n ys.append([y, y])\n else:\n x = x_min + k*(x_max-x_min)\n xs.append([x, x])\n ys.append([y_min, y_max])\n zs.append([0.0, 0.0])\n cs.append([rgb, rgb])\n \n xs, ys, zs, cs = np.array(xs), np.array(ys), np.array(zs), np.array(cs)/255.0\n self.mesh(xs, ys, zs, color=cs, mode='FCBC', name=name, inside=inside, visible=visible)\n \n for tick in tick_label:\n if loc == 'left':\n y = y_min + (y_max-y_min)*(tick-v_min)/(v_max-v_min)\n p0, p1, p3 = (x_min, y, 0), (x_min-tick_line, y, 0), (x_min-tick_line-0.01, y, 0)\n align, valign = 'right', 'middle'\n elif loc == 'right':\n y = y_min + (y_max-y_min)*(tick-v_min)/(v_max-v_min)\n p0, p1, p3 = (x_max, y, 0), (x_max+tick_line, y, 0), (x_max+tick_line+0.01, y, 0)\n align, valign = 'left', 'middle'\n else:\n x = x_min + (x_max-x_min)*(tick-v_min)/(v_max-v_min)\n p0, p1, p3 = (x, y_min, 0), (x, y_min-tick_line, 0), (x, y_min-tick_line-0.01, 0)\n align, valign = 'center', 'top'\n \n mark = label_format(tick)\n self.line(np.array((p0, p1)), color=self.scene.tc, name=name, inside=inside, visible=visible)\n self.text3d(mark, size=label_size, pos=p3, align=align, valign=valign, name=name, inside=inside, visible=visible)\n \n def hide_ticks(self):\n \"\"\"隐藏刻度网格\"\"\"\n \n for item in ('xy_zmin', 'xy_zmax', 'zx_ymin', 'zx_ymax', 'yz_xmin', 'yz_xmax'):\n self.delete_model('%s_%s'%(self.grid_tick['gid'], item))\n for ax in self.grid_tick['tick']:\n for key in self.grid_tick['tick'][ax]:\n for name in self.grid_tick['tick'][ax][key]:\n self.delete_model(name)\n \n self.grid_tick = None\n self.refresh()\n \n def ticks(self, **kwds):\n \"\"\"绘制网格和刻度\n \n kwds - 关键字参数\n segment_min - 标注最少分段数量\n segment_max - 标注最多分段数量\n label_2D3D - 标注试用2D或3D文字\n label_size - 标注字号\n xlabel_format - x轴标注格式化所用lambda函数\n ylabel_format - y轴标注格式化所用lambda函数\n zlabel_format - z轴标注格式化所用lambda函数\n \n \"\"\"\n \n assert self.r_x[0] <= self.r_x[1] and self.r_y[0] <= self.r_y[1] and self.r_z[0] <= self.r_z[1], '当前没有模型,无法显示网格和刻度'\n \n for key in kwds:\n if key not in ['segment_min', 'segment_max', 'label_2D3D', 'label_size', 'xlabel_format', 'ylabel_format', 'zlabel_format']:\n raise KeyError('不支持的关键字参数:%s'%key)\n \n segment_min = kwds.get('segment_min', 5)\n segment_max = kwds.get('segment_max', 8)\n label_2D3D = kwds.get('label_2D3D', '3D')\n label_size = kwds.get('label_size', 16)\n label_precision = kwds.get('label_precision', '%.2f')\n xlabel_format = kwds.get('xlabel_format', str)\n ylabel_format = kwds.get('ylabel_format', str)\n zlabel_format = kwds.get('zlabel_format', str)\n t_size = label_size/self.scale\n \n self.grid_tick_kwds = kwds\n if self.grid_tick:\n self.hide_ticks()\n \n head = 'y+' if self.fixed else self.scene.head\n gid = uuid.uuid1().hex\n draw_text = self.text3d if label_2D3D == '3D' else self.text2d\n \n self.grid_tick = {\n 'gid': gid,\n 'tick': {\n 'x':{'y0z0':list(), 'y0z1':list(), 'y1z0':list(), 'y1z1':list()},\n 'y':{'z0x0':list(), 'z0x1':list(), 'z1x0':list(), 'z1x1':list()},\n 'z':{'x0y0':list(), 'x0y1':list(), 'x1y0':list(), 'x1y1':list()}\n }\n }\n \n x_values = self._get_tick_label(self.r_x[0], self.r_x[1], s_min=segment_min, s_max=segment_max, endpoint=False)\n y_values = self._get_tick_label(self.r_y[0], self.r_y[1], s_min=segment_min, s_max=segment_max, endpoint=False)\n z_values = self._get_tick_label(self.r_z[0], self.r_z[1], s_min=segment_min, s_max=segment_max, endpoint=False)\n \n xx = [self.r_x[0]] + x_values + [self.r_x[1]]\n yy = [self.r_y[0]] + y_values + [self.r_y[1]]\n zz = [self.r_z[0]] + z_values + [self.r_z[1]]\n \n xy_x, xy_y = np.meshgrid(xx, yy)\n xy_zmin = np.ones_like(xy_x) * self.r_z[0]\n xy_zmax = np.ones_like(xy_x) * self.r_z[1]\n \n zx_x, zx_z = np.meshgrid(xx, zz)\n zx_ymin = np.ones_like(zx_x) * self.r_y[0]\n zx_ymax = np.ones_like(zx_x) * self.r_y[1]\n \n yz_y, yz_z = np.meshgrid(yy, zz)\n yz_xmin = np.ones_like(yz_y) * self.r_x[0]\n yz_xmax = np.ones_like(yz_y) * self.r_x[1]\n \n self.mesh(xy_x, xy_y, xy_zmin, color='blue', mode='FLBL', name='%s_xy_zmin'%gid, inside=False)\n self.mesh(xy_x, xy_y, xy_zmax, color='blue', mode='FLBL', name='%s_xy_zmax'%gid, inside=False)\n \n self.mesh(zx_x, zx_ymin, zx_z, color='green', mode='FLBL', name='%s_zx_ymin'%gid, inside=False)\n self.mesh(zx_x, zx_ymax, zx_z, color='green', mode='FLBL', name='%s_zx_ymax'%gid, inside=False)\n \n self.mesh(yz_xmin, yz_y, yz_z, color='red', mode='FLBL', name='%s_yz_xmin'%gid, inside=False)\n self.mesh(yz_xmax, yz_y, yz_z, color='red', mode='FLBL', name='%s_yz_xmax'%gid, inside=False)\n \n for x in x_values:\n y0z0, y0z1, y1z0, y1z1 = uuid.uuid1().hex, uuid.uuid1().hex, uuid.uuid1().hex, uuid.uuid1().hex\n self.grid_tick['tick']['x']['y0z0'].append(y0z0)\n self.grid_tick['tick']['x']['y0z1'].append(y0z1)\n self.grid_tick['tick']['x']['y1z0'].append(y1z0)\n self.grid_tick['tick']['x']['y1z1'].append(y1z1)\n \n if head == 'z+':\n p0, align0, valign0 = (x, self.r_y[0], self.r_z[0]-0.05/self.scale), 'right', 'top'\n p1, align1, valign1 = (x, self.r_y[0], self.r_z[1]+0.05/self.scale), 'right', 'bottom'\n p2, align2, valign2 = (x, self.r_y[1], self.r_z[0]-0.05/self.scale), 'left', 'top'\n p3, align3, valign3 = (x, self.r_y[1], self.r_z[1]+0.05/self.scale), 'left', 'bottom'\n elif head == 'y+':\n p0, align0, valign0 = (x, self.r_y[0]-0.05/self.scale, self.r_z[0]), 'center', 'top'\n p1, align1, valign1 = (x, self.r_y[0]-0.05/self.scale, self.r_z[1]), 'center', 'top'\n p2, align2, valign2 = (x, self.r_y[1]+0.05/self.scale, self.r_z[0]), 'center', 'bottom'\n p3, align3, valign3 = (x, self.r_y[1]+0.05/self.scale, self.r_z[1]), 'center', 'bottom'\n else:\n p0, align0, valign0 = (x, self.r_y[0], self.r_z[0]-0.05/self.scale), 'right', 'middle'\n p1, align1, valign1 = (x, self.r_y[0], self.r_z[1]+0.05/self.scale), 'left', 'middle'\n p2, align2, valign2 = (x, self.r_y[1], self.r_z[0]-0.05/self.scale), 'right', 'middle'\n p3, align3, valign3 = (x, self.r_y[1], self.r_z[1]+0.05/self.scale), 'left', 'middle'\n \n tick = xlabel_format(x)\n draw_text(tick, pos=p0, size=t_size, align=align0, valign=valign0, name=y0z0, inside=False)\n draw_text(tick, pos=p1, size=t_size, align=align1, valign=valign1, name=y0z1, inside=False)\n draw_text(tick, pos=p2, size=t_size, align=align2, valign=valign2, name=y1z0, inside=False)\n draw_text(tick, pos=p3, size=t_size, align=align3, valign=valign3, name=y1z1, inside=False)\n \n for y in y_values:\n z0x0, z0x1, z1x0, z1x1 = uuid.uuid1().hex, uuid.uuid1().hex, uuid.uuid1().hex, uuid.uuid1().hex\n self.grid_tick['tick']['y']['z0x0'].append(z0x0)\n self.grid_tick['tick']['y']['z0x1'].append(z0x1)\n self.grid_tick['tick']['y']['z1x0'].append(z1x0)\n self.grid_tick['tick']['y']['z1x1'].append(z1x1)\n \n if head == 'z+':\n p0, align0, valign0 = (self.r_x[0], y, self.r_z[0]-0.05/self.scale), 'center', 'top'\n p1, align1, valign1 = (self.r_x[1], y, self.r_z[0]-0.05/self.scale), 'center', 'top'\n p2, align2, valign2 = (self.r_x[0], y, self.r_z[1]+0.05/self.scale), 'center', 'bottom'\n p3, align3, valign3 = (self.r_x[1], y, self.r_z[1]+0.05/self.scale), 'center', 'bottom'\n elif head == 'y+':\n p0, align0, valign0 = (self.r_x[0]-0.05/self.scale, y, self.r_z[0]), 'right', 'middle'\n p1, align1, valign1 = (self.r_x[1]+0.05/self.scale, y, self.r_z[0]), 'left', 'middle'\n p2, align2, valign2 = (self.r_x[0]-0.05/self.scale, y, self.r_z[1]), 'right', 'middle'\n p3, align3, valign3 = (self.r_x[1]+0.05/self.scale, y, self.r_z[1]), 'left', 'middle'\n else:\n p0, align0, valign0 = (self.r_x[0]-0.05/self.scale, y, self.r_z[0]), 'right', 'top'\n p1, align1, valign1 = (self.r_x[1]+0.05/self.scale, y, self.r_z[0]), 'right', 'bottom'\n p2, align2, valign2 = (self.r_x[0]-0.05/self.scale, y, self.r_z[1]), 'left', 'top'\n p3, align3, valign3 = (self.r_x[1]+0.05/self.scale, y, self.r_z[1]), 'left', 'bottom'\n \n tick = ylabel_format(y)\n draw_text(tick, pos=p0, size=t_size, align=align0, valign=valign0, name=z0x0, inside=False)\n draw_text(tick, pos=p1, size=t_size, align=align1, valign=valign1, name=z0x1, inside=False)\n draw_text(tick, pos=p2, size=t_size, align=align2, valign=valign2, name=z1x0, inside=False)\n draw_text(tick, pos=p3, size=t_size, align=align3, valign=valign3, name=z1x1, inside=False)\n \n for z in z_values:\n x0y0, x0y1, x1y0, x1y1 = uuid.uuid1().hex, uuid.uuid1().hex, uuid.uuid1().hex, uuid.uuid1().hex\n self.grid_tick['tick']['z']['x0y0'].append(x0y0)\n self.grid_tick['tick']['z']['x0y1'].append(x0y1)\n self.grid_tick['tick']['z']['x1y0'].append(x1y0)\n self.grid_tick['tick']['z']['x1y1'].append(x1y1)\n \n if head == 'z+':\n p0, align0, valign0 = (self.r_x[0], self.r_y[0]-0.05/self.scale, z), 'right', 'middle'\n p1, align1, valign1 = (self.r_x[0], self.r_y[1]+0.05/self.scale, z), 'left', 'middle'\n p2, align2, valign2 = (self.r_x[1], self.r_y[0]-0.05/self.scale, z), 'right', 'middle'\n p3, align3, valign3 = (self.r_x[1], self.r_y[1]+0.05/self.scale, z), 'left', 'middle'\n elif head == 'y+':\n p0, align0, valign0 = (self.r_x[0], self.r_y[0]-0.05/self.scale, z), 'right', 'top'\n p1, align1, valign1 = (self.r_x[0], self.r_y[1]+0.05/self.scale, z), 'right', 'bottom'\n p2, align2, valign2 = (self.r_x[1], self.r_y[0]-0.05/self.scale, z), 'left', 'top'\n p3, align3, valign3 = (self.r_x[1], self.r_y[1]+0.05/self.scale, z), 'left', 'bottom'\n else:\n p0, align0, valign0 = (self.r_x[0]-0.05/self.scale, self.r_y[0], z), 'center', 'top'\n p1, align1, valign1 = (self.r_x[0]-0.05/self.scale, self.r_y[1], z), 'center', 'top'\n p2, align2, valign2 = (self.r_x[1]+0.05/self.scale, self.r_y[0], z), 'center', 'bottom'\n p3, align3, valign3 = (self.r_x[1]+0.05/self.scale, self.r_y[1], z), 'center', 'bottom'\n \n tick = zlabel_format(z)\n draw_text(tick, pos=p0, size=t_size, align=align0, valign=valign0, name=x0y0, inside=False)\n draw_text(tick, pos=p1, size=t_size, align=align1, valign=valign1, name=x0y1, inside=False)\n draw_text(tick, pos=p3, size=t_size, align=align3, valign=valign3, name=x1y1, inside=False)\n draw_text(tick, pos=p2, size=t_size, align=align2, valign=valign2, name=x1y0, inside=False)\n \n self.refresh()\n self.scene.set_posture()\n \n def ticks2d(self, **kwds):\n \"\"\"绘制2D网格和刻度\n \n kwds - 关键字参数\n segment_min - 标注最少分段数量\n segment_max - 标注最多分段数量\n label_2D3D - 标注试用2D或3D文字\n label_size - 标注字号\n xlabel_format - x轴标注格式化所用lambda函数\n ylabel_format - y轴标注格式化所用lambda函数\n \n \"\"\"\n \n assert self.r_x[0] <= self.r_x[1] and self.r_y[0] <= self.r_y[1] and self.r_z[0] <= self.r_z[1], '当前没有模型,无法显示网格和刻度'\n \n for key in kwds:\n if key not in ['segment_min', 'segment_max', 'label_2D3D', 'label_size', 'xlabel_format', 'ylabel_format']:\n raise KeyError('不支持的关键字参数:%s'%key)\n \n segment_min = kwds.get('segment_min', 5)\n segment_max = kwds.get('segment_max', 8)\n label_2D3D = kwds.get('label_2D3D', '3D')\n label_size = kwds.get('label_size', 16)\n label_precision = kwds.get('label_precision', '%.2f')\n xlabel_format = kwds.get('xlabel_format', str)\n ylabel_format = kwds.get('ylabel_format', str)\n t_size = label_size/self.scale\n \n dx, dy = (self.r_x[1]-self.r_x[0])/30, (self.r_y[1]-self.r_y[0])/30\n d = max(dx, dy)\n self.set_data_range((self.r_x[0]-dx, self.r_x[1]+dx), (self.r_y[0]-dy, self.r_y[1]+dy))\n \n vs = np.array([\n [self.r_x[0], self.r_y[0], 0], [self.r_x[1], self.r_y[0], 0], \n [self.r_x[0], self.r_y[0], 0], [self.r_x[0], self.r_y[1], 0]\n ])\n self.line(vs, self.scene.tc, method='MULTI', width=1.5, inside=False)\n \n vs_arrow = np.array([\n (self.r_x[1]+d, self.r_y[0], 0), (self.r_x[1], self.r_y[0]+d/4, 0), (self.r_x[1], self.r_y[0]-d/4, 0), \n (self.r_x[0], self.r_y[1]+d, 0), (self.r_x[0]-d/4, self.r_y[1], 0), (self.r_x[0]+d/4, self.r_y[1], 0)\n ])\n self.surface(vs_arrow, color=self.scene.tc, method='T', mode='FCBC', inside=False)\n \n x_values = self._get_tick_label(self.r_x[0], self.r_x[1], s_min=segment_min, s_max=segment_max, endpoint=False)\n y_values = self._get_tick_label(self.r_y[0], self.r_y[1], s_min=segment_min, s_max=segment_max, endpoint=False)\n draw_text = self.text3d if label_2D3D == '3D' else self.text2d\n \n vs_xtick = list()\n for x in x_values:\n tick = xlabel_format(x)\n vs_xtick += [(x, self.r_y[0], 0), (x, self.r_y[0]-0.4*d, 0)]\n draw_text(tick, pos=(x,self.r_y[0]-0.5*d,0), size=t_size, align='center', valign='top', inside=False)\n \n vs_ytick = list()\n for y in y_values:\n tick = ylabel_format(y)\n vs_ytick += [(self.r_x[0], y, 0), (self.r_x[0]-0.4*d, y, 0)]\n draw_text(tick, pos=(self.r_x[0]-0.5*d,y,0), size=t_size, align='right', valign='middle', inside=False)\n \n self.line(np.array(vs_xtick), self.scene.tc, method='MULTI', width=1, inside=False)\n self.line(np.array(vs_ytick), self.scene.tc, method='MULTI', width=1, inside=False)\n \n def flow(self, ps, us, vs, ws, **kwds):\n \"\"\"绘制流体\n \n ps - 顶点坐标集,numpy.ndarray类型,shape=(n,3)\n us - 顶点u分量集,numpy.ndarray类型,shape=(n,)\n vs - 顶点v分量集,numpy.ndarray类型,shape=(n,)\n ws - 顶点w分量集,numpy.ndarray类型,shape=(n,)\n kwds - 关键字参数\n color - 轨迹线颜色,None表示使用速度映射颜色\n actor - 顶点模型类型,'point'|'line'两个选项\n size - point大小\n width - line宽度\n length - 轨迹线长度,以速度矢量的模为单位\n duty - 顶点line模型长度与轨迹线长度之比(占空比),建议值为0.4\n frames - 总帧数\n interval - 帧间隔,以ms为单位\n threshold - 高通阈值,滤除速度小于阈值的数据点\n name - 模型名\n \"\"\"\n \n for key in kwds:\n if key not in ['color', 'actor', 'size', 'width', 'length', 'duty', 'frames', 'interval', 'threshold', 'name']:\n raise KeyError('不支持的关键字参数:%s'%key)\n \n color = kwds.get('color', None)\n actor = kwds.get('actor', 'line')\n size = kwds.get('size', 1.0)\n width = kwds.get('width', 1.0)\n length = kwds.get('length', 1.0)\n duty = kwds.get('duty', 0.4)\n frames = kwds.get('frames', 10)\n interval = kwds.get('interval', 10)\n threshold = kwds.get('threshold', None)\n name = kwds.get('name', uuid.uuid1().hex)\n \n VERTEX_SHADER = shaders.compileShader(\"\"\"#version 140 \n uniform float counter;\n out vec4 myColor;\n \n void main() {\n vec4 v = vec4(gl_Vertex);\n vec3 n = vec3(gl_Normal);\n vec4 rand = vec4(gl_MultiTexCoord0);\n float k = mod(rand[1]+counter, rand[0]);\n v.x += n[0] * k;\n v.y += n[1] * k;\n v.z += n[2] * k;\n gl_Position = gl_ModelViewProjectionMatrix * v; \n myColor = gl_Color;\n }\"\"\", GL_VERTEX_SHADER)\n \n FRAGMENT_SHADER = shaders.compileShader(\"\"\"#version 140 \n out vec4 FragColor; \n in vec4 myColor;\n \n void main() { \n gl_FragColor = myColor;\n }\"\"\", GL_FRAGMENT_SHADER)\n \n \n shader = shaders.compileProgram(VERTEX_SHADER, FRAGMENT_SHADER)\n loc_counter = glGetUniformLocation(shader, 'counter')\n program = (shader, loc_counter, name)\n \n fs = np.sqrt(np.power(us,2)+np.power(vs,2)+np.power(ws,2))\n if threshold != None:\n sieve = fs > threshold\n fs = fs[sieve]\n us = us[sieve]\n vs = vs[sieve]\n ws = ws[sieve]\n ps = ps[sieve]\n \n rand = np.random.randint(0, frames, ps.shape[0])\n rand = np.stack((np.ones(ps.shape[0])*frames, rand), axis=1)\n \n if color is None:\n colors = self.scene.cm.cmap(fs, 'wind')\n else:\n colors = self.scene.cm.color2c(color, shape=fs.shape)\n \n if actor == 'point':\n uvw = np.stack((us,vs,ws), axis=1)*length/frames\n self.timers.update({name:{'timer':None, 'counter':0, 'frames':frames, 'uvw':uvw, 'rand':rand}})\n self.point(ps, colors, size=size, program=program, name=name)\n else:\n vertexes = list()\n for p, u, v, w, f in zip(ps, us, vs, ws, fs):\n a_y = np.arccos(w/f)\n if u == 0:\n a_z = np.pi/2 if v > 0 else -np.pi/2\n else:\n a_z = np.arctan(v/u) + (np.pi if u < 0 else 0)\n \n rotator = sstr.from_euler('xyz', [0, a_y, a_z], degrees=False)\n vertexes.append(rotator.apply(np.array([[0,0,0], [0,0,f*length*duty]])) + p)\n \n vertexes = np.vstack(vertexes)\n rand = np.repeat(rand, 2, axis=0)\n colors = np.repeat(colors, 2, axis=0)\n uvw = np.stack((us,vs,ws), axis=1)*length*(1-duty)/frames\n uvw = np.repeat(uvw, 2, axis=0)\n \n self.timers.update({name:{'timer':None, 'counter':0, 'frames':frames, 'uvw':uvw, 'rand':rand}})\n self.line(vertexes, colors, method='MULTI', width=width, program=program, name=name)\n \n def on_timer(evt):\n if name in self.models:\n self.timers[name]['counter'] += 1\n if self.timers[name]['counter'] >= self.timers[name]['frames']:\n self.timers[name]['counter'] = 0\n elif name in self.timers:\n self.timers[name]['timer'].Unbind(wx.EVT_TIMER)\n self.timers[name]['timer'].Stop()\n del self.timers[name]['timer']\n del self.timers[name]\n \n self.refresh()\n \n self.timers[name]['timer'] = wx.Timer()\n self.timers[name]['timer'].Bind(wx.EVT_TIMER, on_timer)\n self.timers[name]['timer'].Start(interval)\n ","sub_path":"wxgl/region.py","file_name":"region.py","file_ext":"py","file_size_in_byte":93758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"543435672","text":"import os\r\nimport copy\r\nimport threading\r\nimport time\r\nfrom collections.abc import Iterable\r\nfrom collections import defaultdict\r\n\r\nos.environ['DJANGO_SETTINGS_MODULE'] = 'db_config.settings'\r\nimport django\r\ndjango.setup()\r\nfrom atropos_db.models import Variable\r\nfrom asgiref.sync import sync_to_async\r\n\r\n# The following imports are not used by name in this file, but are\r\n# necessary for enabling `eval` to work correctly. Do not let\r\n# PyCharm \"optimize\" them out.\r\nfrom dicelang.undefined import Undefined\r\nfrom dicelang.function import Function\r\nfrom dicelang.alias import Alias\r\nfrom dicelang.float_special import inf\r\nfrom dicelang.float_special import nan\r\n\r\nVAR_MODES = ['private', 'server', 'core', 'global']\r\n\r\nclass Cache(object):\r\n def __init__(self, modes=VAR_MODES, prune_below=10):\r\n self.vars = {}\r\n self.uses = {}\r\n self.threshold = prune_below\r\n for mode in modes:\r\n self.vars[mode] = {}\r\n self.uses[mode] = {}\r\n \r\n def get(self, owner_id, key, mode):\r\n try:\r\n out = self.vars[mode][owner_id][key]\r\n self.uses[mode][owner_id][key] += 1\r\n except KeyError:\r\n out = None\r\n return out\r\n \r\n def put(self, owner_id, key, value, mode):\r\n if owner_id not in self.vars[mode]:\r\n self.vars[mode][owner_id] = {}\r\n self.uses[mode][owner_id] = defaultdict(int)\r\n self.vars[mode][owner_id][key] = value\r\n self.uses[mode][owner_id][key] += 1\r\n return value\r\n \r\n def drop(self, owner_id, key, mode):\r\n if owner_id in self.vars[mode] and key in self.vars[mode][owner_id]:\r\n out = copy.copy(self.vars[mode][owner_id][key])\r\n del self.vars[mode][owner_id][key]\r\n del self.uses[mode][owner_id][key]\r\n else:\r\n out = None\r\n return out\r\n \r\n def prune(self):\r\n '''Don't prune `core` variables -- they're usually large, often-used, and\r\n well-curated, which means they're good candidates for remaining loaded.'''\r\n marked = [ ]\r\n for mode in filter(lambda s: s != 'core', self.uses):\r\n for owner in self.uses[mode]:\r\n for key in self.uses[mode][owner]:\r\n uses = self.uses[mode][owner][key]\r\n is_function = isinstance(self.vars[mode][owner][key], Function)\r\n function_sweep = is_function and uses < self.threshold / 2\r\n value_sweep = not is_function and uses < self.threshold\r\n if function_sweep or value_sweep:\r\n marked.append((mode, owner, key))\r\n else:\r\n self.uses[mode][owner][key] = 0\r\n \r\n objects_pruned = 0\r\n for item in marked:\r\n objects_pruned += self._remove(*item)\r\n return objects_pruned\r\n \r\n def _remove(self, mode, owner, key):\r\n print(f'prune {(mode, owner, key)} from cache')\r\n del self.vars[mode][owner][key]\r\n del self.uses[mode][owner][key]\r\n return 1\r\n \r\nclass DataStore(object):\r\n '''Specialization of _DataStore where keys are associated by\r\n some other key specifying ownership, such as a username or\r\n server handle.'''\r\n \r\n def __init__(self, cache_time=6*60*60):\r\n self.cache = Cache()\r\n \r\n def pruning_task(cycle_time):\r\n while True:\r\n time.sleep(cycle_time)\r\n pruned = self.cache.prune()\r\n print(f'{pruned} objects pruned from cache')\r\n \r\n a = (cache_time,)\r\n self.pruner = threading.Thread(target=pruning_task, args=a, daemon=True)\r\n self.pruner.start()\r\n \r\n def view(self, mode, owner_id):\r\n results = Variable.objects.filter(var_type=mode, owner_id=owner_id)\r\n names = [ ]\r\n for result in results:\r\n names.append(result.name)\r\n return names\r\n \r\n def get(self, owner_tag, key, mode):\r\n out = self.cache.get(owner_tag, key, mode)\r\n if out is None:\r\n try:\r\n out_repr = Variable.objects.get(\r\n owner_id=owner_tag,\r\n var_type=mode,\r\n name=key).value_string\r\n out = eval(out_repr)\r\n except Exception as e:\r\n out = None\r\n else:\r\n self.cache.put(owner_tag, key, out, mode)\r\n return out\r\n\r\n def put(self, owner_tag, key, value, mode):\r\n self.cache.put(owner_tag, key, value, mode)\r\n \r\n with Function.SerializableRepr() as _:\r\n mutating = {'value_string': repr(value)}\r\n \r\n variable = Variable.objects.update_or_create(\r\n owner_id=owner_tag,\r\n var_type=mode,\r\n name=key,\r\n defaults=mutating)\r\n \r\n variable = variable[0].value_string\r\n return eval(variable)\r\n\r\n def drop(self, owner_tag, key, mode):\r\n self.cache.drop(owner_tag, key, mode)\r\n try:\r\n var = Variable.objects.get(owner_id=owner_tag, var_type=mode, name=key)\r\n except Variable.DoesNotExist:\r\n out = None\r\n else:\r\n out = eval(var.value_string)\r\n var.delete()\r\n return out\r\n\r\n","sub_path":"dicelang/datastore.py","file_name":"datastore.py","file_ext":"py","file_size_in_byte":4731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"210627901","text":"import os\n\nclass Map:\n MapName = '0'\n\n properties = {}\n entities = []\n\n def __init__(self, mapName):\n self.MapName = mapName\n\n self.properties['x'] = '0'\n self.properties['y'] = '0'\n self.properties['width'] = '8'\n self.properties['height'] = '8'\n self.properties['world'] = '\"outside_world\"'\n self.properties['tileset'] = '\"0\"'\n\n def addEntity(self, typeName):\n self.entities.append(MapEntity())\n\n theEntity = self.entities[-1]\n\n if typeName == \"tile\":\n theEntity.entityType = 'tile'\n theEntity.properties['layer'] = '0'\n theEntity.properties['x'] = '0'\n theEntity.properties['y'] = '0'\n theEntity.properties['width'] = '8'\n theEntity.properties['height'] = '8'\n theEntity.properties['pattern'] = '1'\n\n elif typeName == \"destination\":\n theEntity.entityType = \"destination\"\n #theEntity.properties[\"name\"] = \"\"\n theEntity.properties[\"layer\"] = '0'\n theEntity.properties['x'] = '8'\n theEntity.properties['y'] = '13'\n theEntity.properties['direction'] = '1'\n\n def outputMap(self, mapDir):\n fileStr = \"\"\n\n fileStr += self.getPropStr()\n\n for entity in self.entities:\n fileStr += entity.getStr()\n\n with open(os.path.join(mapDir,\"%s.dat\"%(self.MapName)), 'w') as map_file:\n map_file.write(fileStr)\n\n with open(os.path.join(mapDir,\"%s.lua\"%(self.MapName)), 'w') as map_file:\n pass\n\n def getPropStr(self):\n propStr = \"properties{\\n\"\n \n for prop,value in self.properties.items():\n propStr += \" \"+prop + \" = \" + value + \",\\n\"\n propStr += \"}\\n\\n\"\n\n return propStr\n\nclass MapEntity:\n entityType = \"\"\n properties = None\n\n def __init__(self):\n if not self.properties:\n self.properties = dict()\n\n def getStr(self):\n myStr = self.entityType + \"{\\n\"\n for prop,value in self.properties.items():\n myStr += \" \"+prop + \" = \" + value + \",\\n\"\n myStr += \"}\\n\\n\"\n\n return myStr\n","sub_path":"Map.py","file_name":"Map.py","file_ext":"py","file_size_in_byte":2178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"179744820","text":"import csv\nimport datetime\n\ndef reiv_to_row(reiv_data):\n return reiv_data.name + \\\n ',' + reiv_data.price_change + \\\n ',' + reiv_data.rental_yield + \\\n ',' + reiv_data.insight.to_csv_row + \\\n ',' + reiv_data.price.to_csv_row + ',' + reiv_data.rental.to_csv_row\n\n\ndef reiv_to_csv(filename, headers, dict_lists):\n with open(filename, 'w') as csv_file:\n csv_writer = csv.DictWriter(csv_file, headers)\n csv_writer.writeheader()\n for dict_values in dict_lists:\n csv_writer.writerow(dict_values)\n\n","sub_path":"helper/csv_writer.py","file_name":"csv_writer.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"622587666","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build\\bdist.win-amd64\\egg\\sc2gameLobby\\setScenario.py\n# Compiled at: 2018-10-07 22:28:04\n# Size of source mod 2**32: 12918 bytes\n\"\"\"PURPOSE: launch the mini-editor to create custom p setups\"\"\"\nimport glob, os, re, stat, subprocess, time\nfrom s2clientprotocol.sc2api_pb2 import Action, RequestAction\nfrom sc2gameLobby import debugCmds\nfrom sc2gameLobby import gameConstants as c\nfrom sc2gameLobby.gameConfig import Config\n\ndef launchEditor(mapObj):\n \"\"\"\n PURPOSE: launch the editor using a specific map object\n INPUT: mapObj (sc2maptool.mapRecord.MapRecord)\n \"\"\"\n cfg = Config()\n if cfg.is64bit:\n selectedArchitecture = c.SUPPORT_64_BIT_TERMS\n else:\n selectedArchitecture = c.SUPPORT_32_BIT_TERMS\n editorCmd = '%s -run %s -testMod %s -displayMode 1'\n fullAppPath = os.path.join(cfg.installedApp.data_dir, c.FOLDER_APP_SUPPORT % selectedArchitecture[0])\n appCmd = c.FILE_EDITOR_APP % selectedArchitecture[1]\n fullAppFile = os.path.join(fullAppPath, appCmd)\n baseVersion = cfg.version.baseVersion\n availableVers = [int(re.sub('^.*?Base', '', os.path.basename(path))) for path in glob.glob(os.path.join(c.FOLDER_MODS, 'Base*'))]\n selV = max([v for v in availableVers if v <= baseVersion])\n modFilepath = os.path.join(c.FOLDER_MODS, 'Base%s' % selV, c.FILE_EDITOR_MOD)\n os.chmod(fullAppFile, stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH | stat.S_IXUSR | stat.S_IRUSR | stat.S_IWUSR | stat.S_IWGRP | stat.S_IXGRP)\n finalCmd = editorCmd % (appCmd, mapObj.path, modFilepath)\n cwd = os.getcwd()\n os.chdir(fullAppPath)\n os.system(finalCmd)\n os.chdir(cwd)\n\n\ndef initScenario(controller, scenario, thisPlayerID, debug=False):\n \"\"\"once in the in_game state, use the controller to set up the scenario\"\"\"\n\n def createUnitsWithTags(unitList, existingUnits={}, maxTries=25):\n \"\"\"create each unit of unitList in game, identified by their tag\"\"\"\n createCmds = (debugCmds.create)(*unitList)\n (controller.debug)(*createCmds)\n triesRemaining = maxTries\n getGameState = controller.observe\n numNeededNewUnits = len(unitList)\n newUnits = {}\n while len(newUnits) < numNeededNewUnits and triesRemaining > 0:\n units = getGameState().observation.raw_data.units\n for i, unit in enumerate(unitList):\n if unit.tag:\n pass\n else:\n for liveUnit in units:\n if liveUnit.unit_type != unit.code:\n pass\n else:\n if liveUnit.owner != unit.owner:\n pass\n else:\n if liveUnit.tag in existingUnits:\n pass\n else:\n unit.tag = liveUnit.tag\n existingUnits[unit.tag] = liveUnit\n newUnits[unit.tag] = unit\n break\n\n triesRemaining -= 1\n\n return newUnits\n\n def detectCurrentUnits(**filters):\n detectedUnits = {}\n getGameState = controller.observe\n while 1:\n obs = getGameState()\n if obs.observation.game_loop <= 1:\n pass\n else:\n foundNewUnit = False\n for u in obs.observation.raw_data.units:\n if u.tag in detectedUnits:\n pass\n else:\n foundNewUnit = True\n detectedUnits[u.tag] = u\n\n if foundNewUnit:\n continue\n if detectedUnits:\n break\n\n if filters:\n return filterUnits(detectedUnits, **filters)\n else:\n return detectedUnits\n\n def filterUnits(unitDict, noNeutral=False, ownedOnly=False):\n \"\"\"select the desired types of units from unitDict\"\"\"\n\n def allow(unit):\n if noNeutral:\n if unit.alliance == c.NEUTRAL:\n return False\n else:\n if unit.mineral_contents:\n return False\n if unit.vespene_contents:\n return False\n if ownedOnly:\n if unit.owner != thisPlayerID:\n return False\n return True\n\n if not (noNeutral or ownedOnly):\n return unitDict\n else:\n return {unit.tag:unit for unit in unitDict.values() if allow(unit)}\n\n def removeUnitsByKey(originalUnits=None, keepTags=[], **filters):\n \"\"\"remove all detected units\"\"\"\n if originalUnits:\n units = filterUnits(originalUnits, **filters)\n else:\n originalUnits = detectCurrentUnits(**filters)\n units = originalUnits\n rmTags = list(units.keys())\n for keeper in keepTags:\n try:\n rmTags.remove(keeper)\n except:\n pass\n\n return removeUnitsByTag(*rmTags, **{'knownUnits': originalUnits})\n\n def removeUnitsByTag(*rmUnitTags, knownUnits={}):\n \"\"\"remove specific units\"\"\"\n for rmTag in rmUnitTags:\n try:\n del knownUnits[rmTag]\n except:\n if not knownUnits:\n break\n\n if rmUnitTags:\n rmCmd = (debugCmds.remove)(*rmUnitTags)\n controller.debug(rmCmd)\n return knownUnits\n\n def wait(delay, msg):\n if debug:\n print(msg)\n while 1:\n time.sleep(1)\n delay -= 1\n if delay > 0:\n if debug:\n print('%d...' % delay)\n continue\n break\n\n knownUnits = detectCurrentUnits(noNeutral=True)\n for pIdx, p in scenario.players.items():\n baseUnits = scenario.newBaseUnits(pIdx)\n newUs = createUnitsWithTags((p.baseUnits), existingUnits=knownUnits)\n\n wait(2, 'delay before default unit deletion; %d remain' % len(newUs))\n if scenario.units:\n rmTags = []\n keepUnits = {\n 19, 60, 95, 137}\n for unit in knownUnits.values():\n if unit.unit_type in keepUnits:\n pass\n else:\n rmTags.append(unit.tag)\n\n removeUnitsByTag(*rmTags, **{'knownUnits': knownUnits})\n wait(1, 'idle for unit kills (keep %d)' % len(knownUnits))\n removeUnitsByKey(keepTags=(knownUnits.keys()), noNeutral=True)\n if debug:\n print('%d remaining initial, known units' % len(knownUnits))\n initialUnits = dict(knownUnits)\n if thisPlayerID == 1:\n controller.debug(debugCmds.disableAllCosts(), debugCmds.allowEnemyControl(), debugCmds.fastProduction())\n wait(0.5, 'delay before creation')\n actionLists = []\n nonActionLists = []\n newU = {}\n for playerID, upgrades in scenario.upgrades.items():\n if not upgrades:\n continue\n reqs = scenario.players[playerID].upgradeReqs\n producingUnits = reqs.keys()\n if playerID == thisPlayerID:\n if debug:\n print('preparing %d upgrades for player #%d' % (len(upgrades), playerID))\n newU = createUnitsWithTags(producingUnits, existingUnits=knownUnits)\n for unit, toDoActions in reqs.items():\n for i, ability in enumerate(toDoActions):\n while len(actionLists) <= i:\n actionLists.append([])\n nonActionLists.append([])\n\n action = Action()\n uCmd = action.action_raw.unit_command\n uCmd.unit_tags.append(unit.tag)\n uCmd.queue_command = True\n uCmd.ability_id, ignoreTargetType = ability.getGameCmd()\n if playerID == thisPlayerID:\n actionLists[i].append(action)\n else:\n nonActionLists[i].append(action)\n\n for i, (al, nal) in enumerate(zip(actionLists, nonActionLists)):\n if debug:\n print('upgrade action list #%d commands: %d' % (i + 1, len(al)))\n if al:\n controller.actions(RequestAction(actions=al))\n else:\n if not nal:\n continue\n if i == 0:\n wait(6, \"wait for all player's level 1 upgrades\")\n else:\n if i == 1:\n wait(7, \"wait for all player's level 2 upgrades\")\n elif i == 2:\n wait(8, \"wait for all player's level 3 upgrades\")\n\n if thisPlayerID == 1:\n controller.debug(debugCmds.disableAllCosts(), debugCmds.allowEnemyControl(), debugCmds.fastProduction())\n wait(0.5, 'wait to disable cheats before proceeding')\n if thisPlayerID == 1:\n removeUnitsByKey(keepTags=initialUnits, noNeutral=True)\n wait(1.0, 'idle for unit kills')\n knownUnits = removeUnitsByKey(keepTags=initialUnits, noNeutral=True)\n cameraMv = Action()\n playerLoc = scenario.players[thisPlayerID].loc\n playerLoc.assignIntoInt(cameraMv.action_raw.camera_move.center_world_space)\n controller.actions(RequestAction(actions=[cameraMv]))\n if debug:\n print('repositioned camera')\n scenarioUnits = {}\n for p in scenario.players.values():\n newUnits = createUnitsWithTags((p.units), existingUnits=knownUnits)\n scenarioUnits.update(newUnits)\n\n modifyCmds = (debugCmds.modify)(*scenarioUnits.values())\n (controller.debug)(*modifyCmds)\n wait(0.1, 'allow modifications to finish')\n controller.debug(debugCmds.revealMap())\n if debug:\n print('scenario setup is finished')","sub_path":"pycfiles/sc2gameLobby-1.1.13-py3.6/setScenario.cpython-36.py","file_name":"setScenario.cpython-36.py","file_ext":"py","file_size_in_byte":9929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"235522718","text":"# importing packages\r\nimport tkinter as tk\r\nfrom PIL import ImageTk, Image\r\nfrom tkinter import ttk\r\n\r\nroot = tk.Tk() # the main window frame\r\nroot.title('Recommender System')\r\nroot.resizable(0, 0)\r\nroot.title('Recommender system') \r\nroot.geometry('%dx%d+%d+%d' % (500, 300, 300, 10))\r\n\r\nFrame = ttk.Frame(root)\r\nFrame.pack(expand=1, fill='both')\r\n\r\ndef calculate():\r\n #print(id1.get(),id2.get())\r\n print(variable.get())\r\n print(sim_choosen.get())\r\n print(N.get())\r\n print(id1.get(), id2.get())\r\n\r\ndef validator(e, Type):\r\n 'validating the entries given'\r\n if Type == '1':\r\n if not e.isdigit ():\r\n self.bell ()\r\n return False\r\n if e == '0':\r\n self.bell ()\r\n return False\r\n return True\r\n\r\n\r\n# creating the entry boxes\r\nvcmd = (tk.register (validator ) , '%P' , '%d')\r\ntk.Label(Frame, text='Music Id:').place(relx=0.01, rely=0.15)\r\ntk.Label(Frame, text='Artist Id:').place(relx=0.01, rely=0.25)\r\nid1 = tk.Entry(Frame, width=26)\r\nid1.place(relx=0.15, rely=0.15, validate = 'key' , validatecommand = vcmd)\r\nid2 = tk.Entry(Frame, width=26)\r\nid2.place(relx= 0.15, rely=0.25)\r\n\r\n# creating the dropdown menu for the metrics\r\ntk.Label(Frame, text='Metric:').place(relx=0.01, rely=0.58)\r\nOPTIONS = ['Cosine','Euclidean','Jaccard','manhattan','pearson']\r\nvariable = tk.StringVar()\r\nvariable.set(OPTIONS[2]) # default value\r\noption = tk.OptionMenu(Frame,variable, *OPTIONS)\r\noption.place(relx= 0.15, rely=0.56)\r\n\r\n# creating the radiobuttons for choosing the similarites you want to check, either between music id or artists id or artist and music \r\ntk.Label(Frame, text='Similarites Between').place(relx=0.01, rely=0.38)\r\nsim_choosen = tk.IntVar()\r\nsimilarities_opt = [('Musics', 1),('Artists', 2),(\"Artist & Musics\",3)]\r\nfor similarity, val in similarities_opt:\r\n tk.Radiobutton(Frame, \r\n text=similarity,\r\n variable=sim_choosen, \r\n value=val).pack(side='left')\r\n\r\n# creating the spinbox that would indicate how many no of similarities do want to see..\r\n# this would only work if you are trying to only show the n similarity to an artist or music \r\ntk.Label(Frame, text='N').place(relx=0.01, rely=0.68)\r\nN = tk.Spinbox ( Frame , from_ = 0 , to = 100 , width = 15, state='disabled' )\r\nN.place(relx= 0.08, rely =0.68)\r\n\r\n# creating the calculate button\r\nbutton = tk.Button(Frame, text='Calculate Similarity', width=20, command=calculate)\r\nbutton.place(relx = 0.10, rely=0.78)\r\n\r\nwhile id2.get() == None:\r\n N.state = tk.DISABLED\r\nroot.mainloop()","sub_path":"iteration2/window.py","file_name":"window.py","file_ext":"py","file_size_in_byte":2575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"605708476","text":"# https://leetcode.com/problems/largest-number/\n'''\nGiven a list of non negative integers, arrange them such that they form the largest number.\n\nFor example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.\n\nNote: The result may be very large, so you need to return a string instead of an integer.\n\nCredits:\nSpecial thanks to @ts for adding this problem and creating all test cases.\n\nHide Tags Sort\n'''\n\n\nclass Solution:\n # @param {integer[]} nums\n # @return {string}\n def largestNumber(self, nums):\n nums = sorted(nums, cmp=self._compare)\n res = ''.join([str(x) for x in nums])\n res = res.lstrip('0')\n if res == '':\n return '0'\n else:\n return res\n\n def _compare(self, a, b):\n n1 = str(a) + str(b)\n n2 = str(b) + str(a)\n length = len(n1)\n i = 0\n while i < length:\n d1 = int(n1[i])\n d2 = int(n2[i])\n if d1 < d2:\n return 1\n elif d1 > d2:\n return -1\n i += 1\n return 0\n","sub_path":"largest-number/solution2.py","file_name":"solution2.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"568781099","text":"# program: kth largest sum subarray: https://www.codingninjas.com/codestudio/problems/k-th-largest-sum-contiguous-subarray_920398?leftPanelTab=0&utm_source=youtube&utm_medium=affiliate&utm_campaign=Lovebabbar\n# brute force: nested loops to save sums of all subarrays, sort and give kth largest\n# time complexity: o(n**2 log n): todo: check\n# space complexity: o(n**2)\n\"\"\"\ndef kth_largest_sum_subarray(arr, k):\n sums = []\n for i in range(len(arr)):\n sum = 0\n for j in range(i, len(arr)):\n sum += arr[j]\n sums.append(sum)\n sums.sort()\n return sums[len(sums)-k]\nprint(kth_largest_sum_subarray([1,2,8,3,5,6,9,10], 3))\n\"\"\"\n\n# program: kth largest sum subarray: https://www.codingninjas.com/codestudio/problems/k-th-largest-sum-contiguous-subarray_920398?leftPanelTab=0&utm_source=youtube&utm_medium=affiliate&utm_campaign=Lovebabbar\n# optimized: nested loops to save sums of all subarrays in min heap\n# time complexity: o(n**2 log k)\n# space complexity: o(k)\n\"\"\"\nfrom queue import PriorityQueue\ndef kth_largest_sum_subarray(arr, k):\n h = PriorityQueue()\n for i in range(len(arr)):\n sum = 0\n for j in range(i, len(arr)):\n sum += arr[j]\n if len(h.queue) < k:\n h.put(sum)\n else:\n top = h.get()\n if sum > top:\n h.put(sum)\n else:\n h.put(top)\n return h.get()\nprint(kth_largest_sum_subarray([1,2,8,3,5,6,9,10], 3))\n\"\"\"\n\n# program: merge k sorted arrays into sorted array: https://www.codingninjas.com/codestudio/problems/merge-k-sorted-arrays_975379?leftPanelTab=0&utm_source=youtube&utm_medium=affiliate&utm_campaign=Lovebabbar\n# brute force put all in ans and sort i.e. o(n*k log n*k)\n# merge sort - divide and conquer\n# optimized approach - put first element if each array in min heap, put top in ans and put next of that array in heap while heap\n# heap value should have array location i.e. i and j from the original 2d matrix\n# time complexity: o(klogk) + o(n*k log k) = o(n*k log k)\n# space complexity: o(k) for heap + o(n*k) for ans i.e. o(n*k)\n\"\"\"\nfrom queue import PriorityQueue\nclass Node:\n def __init__(self, data, i, j):\n self.data = data\n self.i = i\n self.j = j\nsetattr(Node, \"__lt__\", lambda self, other: self.data < other.data)\ndef merge_k_sorted_arrays(mat, k):\n h = PriorityQueue()\n ans = []\n for i in range(k):\n temp = Node(mat[i][0], i, 0)\n h.put(temp)\n while len(h.queue) > 0:\n top = h.get()\n ans.append(top.data)\n i = top.i\n j = top.j\n if j+1 < len(mat[i]):\n temp = Node(mat[i][j+1], i, j+1)\n h.put(temp)\n return ans\nmat = [[0,1,2,3,8],\n [2,5,9,10,11],\n [0,2,3,6,100]]\nk = 3\nprint(merge_k_sorted_arrays(mat, k))\n\"\"\"\n\n# program: pre-requisite: linkedlist\nclass LLNode:\n def __init__(self, data, next=None):\n self.data = data\n self.next = next\nsetattr(LLNode, \"__lt__\", lambda self, other: self.data < other.data)\ndef print_ll(head):\n temp = head\n while temp:\n print(temp.data, end=\"-->\")\n temp = temp.next\n print()\n\n# program: merge k sorted lists: https://www.codingninjas.com/codestudio/problems/merge-k-sorted-lists_992772?leftPanelTab=0&utm_source=youtube&utm_medium=affiliate&utm_campaign=Lovebabbar\n# use existing linked list for ans\n# brute force - add all data to array, sort, join ll, replace data\n# time complexity: o(n*k log n*k) + o(n*k) + o(n*k) = o(n* log n*k)\n# space complexity: o(n*k)\n# approach2: minheap of top of each ll, while heap: keep head and tail for ans\n# time complexity: o(klogk) + o(n*k log n*k) = o(n*k log k) = o(n log k)\n# space complexity: o(k)\n# other unoptimized approach: everytime take first element from every ll and find min value and index via comparison then do rest\n\"\"\"\nfrom queue import PriorityQueue\ndef merge_k_sorted_arrays(arr):\n h = PriorityQueue()\n k = len(arr)\n if k == 0:\n return None\n for i in range(k):\n if arr[i]:\n h.put(arr[i])\n ans_head = None\n ans_tail = None\n while len(h.queue) > 0:\n top = h.get()\n if top.next:\n h.put(top.next)\n if not ans_head:\n ans_head = top\n ans_tail = top\n else:\n ans_tail.next = top\n ans_tail = ans_tail.next\n return ans_head\nh1 = LLNode(0)\nh1.next = LLNode(1)\nh1.next.next = LLNode(5)\nh2 = LLNode(2)\nh2.next = LLNode(3)\nh2.next.next = LLNode(4)\nh3 = LLNode(2)\nh3.next = LLNode(3)\nh3.next.next = LLNode(4)\narr = [h1,h2,h3]\nprint_ll(merge_k_sorted_arrays(arr))\n\"\"\"\n","sub_path":"DSA Course/083_lecture_76_heaps_in_c_plus_plus_interview_questions_part_2.py","file_name":"083_lecture_76_heaps_in_c_plus_plus_interview_questions_part_2.py","file_ext":"py","file_size_in_byte":4646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"76011692","text":"import os\nimport json\nimport timeit\nimport sys\n\n# setup\nos.system('rm -r /home/muody/repos/synthea/output/parsed')\nos.system('rm -r /home/muody/data/fhir_parsed')\nos.system('mkdir /home/muody/data/fhir_parsed')\n\n\n# replace with sys.argv[x]\ninput_path = '/home/muody/repos/synthea/output/fhir/'\noutput_path = '/home/muody/data/fhir_parsed/'\njson_files = os.popen('ls /home/muody/repos/synthea/output/fhir').read()\njson_files = json_files.split()[:100] \n\n\ndef drop_unnecessary_nodes():\n \"\"\"\n This functions loads Synthea's FHIR json output and returns only\n specified descendents of the root node\n \"\"\"\n\n # runtime sanity checks\n counter = 0\n start = timeit.default_timer()\n\n for jfile in json_files:\n def recurse(x, new_dict = {}, depth=0):\n \"\"\"\n Recurses through descendents appending only specified nodes\n to an output dict. Defined within loop because stack overflow.\n \"\"\"\n resources = [\n 'ExplanationOfBenefit',\n 'Practitioner',\n 'Patient',\n 'Claim',\n 'Condition',\n 'MedicationRequest',\n 'DiagnosticReport'\n ]\n\n if isinstance(x,list):\n for a in x:\n recurse(a, depth = depth+1)\n if isinstance(x,dict):\n for a in x:\n if (a == \"resource\") and (x[a]['resourceType'] in resources):\n new_key = \"resource\" + str(x[a]['resourceType'])\n if new_key in new_dict:\n new_dict[new_key].append(x[a])\n\n else:\n new_dict[new_key] = [x[a]]\n\n\n recurse(x[a], depth = depth+1)\n return new_dict\n\n counter +=1\n \n # end time\n stop = timeit.default_timer()\n time = 'Time: ' + str(round(stop - start,2))\n av = \"Avg: \" + str(round((stop-start)/counter,2))\n print(time,av, counter, jfile+' '*100, end=\"\\r\")\n\n # serialize\n with open(input_path+jfile) as f: data = json.load(f)\n data = recurse(data)\n with open(output_path+jfile, 'w') as outfile: json.dump(data, outfile)\n\nif __name__ == \"__main__\":\n drop_unnecessary_nodes()\n","sub_path":"01_reduce_synthea.py","file_name":"01_reduce_synthea.py","file_ext":"py","file_size_in_byte":2321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"192132287","text":"import matplotlib.pyplot as plt\nimport mpl_toolkits.mplot3d.axes3d as axes3d\nimport numpy as np\nfrom tkinter import *\nimport os\n\n\nclass Tkinter:\n radius_entry = None\n z_entry = None\n color_entry = None\n name_entry = None\n\n def __init__(self, root):\n self.root = root\n\n def window(self):\n self.wallpaper(self.root, r\"../wallpapers/image.gif\")\n\n about_me_label = Label(self.root, text=\"Тріщук Д. Р., Зікратий Д. О., група ІВ-81, варіант - 13\",\n font=(\"Times New Roman\", 16), bg=\"black\", fg=\"white\", cursor=\"heart\")\n about_me_label.place(x=250, y=10)\n\n radius_label = Label(self.root, text=\"Радіус циліндра\", font=(\"Times New Roman\", 16), bg=\"black\",\n fg=\"white\", bd=5,\n width=25, height=1, cursor=\"heart\", relief=\"raised\")\n radius_label.place(x=50, y=250)\n\n self.radius_entry = Entry(self.root, width=7, bd=5, font=(\"Times New Roman\", 14), bg=\"black\", fg=\"white\",\n cursor=\"heart\")\n self.radius_entry.place(x=380, y=250)\n\n z_label = Label(self.root, text=\"Межі по осі Z\", font=(\"Times New Roman\", 16), bg=\"black\", fg=\"white\",\n bd=5,\n width=25, height=1, cursor=\"heart\", relief=\"raised\")\n z_label.place(x=50, y=300)\n\n self.z_entry = Entry(self.root, width=7, bd=5, font=(\"Times New Roman\", 14), bg=\"black\", fg=\"white\",\n cursor=\"heart\")\n self.z_entry.place(x=380, y=300)\n\n color_label = Label(self.root, text=\"Колір фігури\", font=(\"Times New Roman\", 16), bg=\"black\", fg=\"white\",\n bd=5, width=25, height=1, cursor=\"heart\", relief=\"raised\")\n color_label.place(x=50, y=350)\n\n self.color_entry = Entry(self.root, width=7, bd=5, font=(\"Times New Roman\", 14), bg=\"black\", fg=\"white\",\n cursor=\"heart\")\n self.color_entry.place(x=380, y=350)\n\n name_label = Label(self.root, text=\"Ім'я файлу\", font=(\"Times New Roman\", 16), bg=\"black\", fg=\"white\",\n bd=5, width=25, height=1, cursor=\"heart\", relief=\"raised\")\n name_label.place(x=50, y=400)\n\n self.name_entry = Entry(self.root, width=7, bd=5, font=(\"Times New Roman\", 14), bg=\"black\", fg=\"white\",\n cursor=\"heart\")\n self.name_entry.place(x=380, y=400)\n draw_and_save_button = Button(self.root, text=\"Показати і зберегти результат\", font=(\"Times New Roman\", 14),\n bg=\"black\", fg=\"white\",\n bd=5, height=1, width=25, activebackground=\"white\", activeforeground=\"black\",\n cursor=\"heart\", command=lambda: self.draw_and_save(int(self.radius_entry.get()),\n self.z_entry.get(),\n int(self.color_entry.get()),\n self.name_entry.get()))\n draw_and_save_button.place(x=650, y=450)\n\n def draw_and_save(self, r, z, numb_color, name_image=\"image\", fmt=\"png\"):\n color = ['spring', 'summer', 'autumn', 'winter', 'cool', 'Wistia', 'hot']\n\n z_start, z_end = [int(i.rstrip().lstrip()) for i in z.split(\",\")]\n fig = plt.figure()\n ax = fig.add_subplot(projection='3d')\n\n t, z = np.linspace(0, 2 * np.pi, 20), np.linspace(z_start, z_end, 20)\n T, Z = np.meshgrid(t, z)\n X = r * np.cos(T)\n Y = r * np.sin(T)\n\n ax.plot_surface(X, Y, Z, rstride=2, cstride=1, linewidth=3, antialiased=False, cmap=color[numb_color], alpha=0.5)\n\n plt.savefig(\"{}//{}.{}\".format(self.create_dir(), name_image, fmt), dpi=300, bbox_inches=\"tight\")\n plt.show()\n\n @staticmethod\n def create_dir():\n name_dir = \"pictures\"\n try:\n os.mkdir(name_dir)\n except FileExistsError:\n pass\n return name_dir\n\n @staticmethod\n def wallpaper(root, gif):\n root.geometry(\"980x550\")\n root.resizable(False, False)\n background = PhotoImage(file=gif)\n label = Label(root, cursor=\"heart\", image=background)\n label.image = background\n label.pack()\n\n\ndef main():\n root = Tk()\n root.title(\"Window\")\n ex_class = Tkinter(root)\n ex_class.window()\n root.mainloop()\n plt.show()\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"venv/include/Lab_3/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"642056436","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Dec 10 11:40:42 2018\n\n@author: 沈鴻儒\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# 建立membership function 的 fuzzy set\ndef trimf(x, abc):\n \"\"\"\n Triangular membership function generator.\n\n Parameters\n ----------\n x : 1d array\n Independent variable.\n abc : 1d array, length 3\n Three-element vector controlling shape of triangular function.\n Requires a <= b <= c.\n\n Returns\n -------\n y : 1d array\n Triangular membership function.\n \"\"\"\n assert len(abc) == 3, 'abc parameter must have exactly three elements.'\n a, b, c = np.r_[abc] # Zero-indexing in Python\n assert a <= b and b <= c, 'abc requires the three elements a <= b <= c.'\n\n y = np.zeros(len(x))\n\n # Left side\n if a != b:\n idx = np.nonzero(np.logical_and(a < x, x < b))[0]\n y[idx] = (x[idx] - a) / float(b - a)\n\n # Right side\n if b != c:\n idx = np.nonzero(np.logical_and(b < x, x < c))[0]\n y[idx] = (c - x[idx]) / float(c - b)\n\n idx = np.nonzero(x == b)\n y[idx] = 1\n return y\n\n# 建立fuzzy set的個數\ndef fuzzy_set(x, x_start, x_end, cnt, epsilon, A, e, h):\n for i in range(cnt):\n if i == 0:\n A[i, :, :] = trimf(x, [x_start, x_start, x_start + h]).reshape(-1, 1)\n e.append(x_start)\n elif i > 0 and i < cnt:\n A[i, :, :] = trimf(x, [x_start + (h * (i - 1)), x_start + (h * i), x_start + (h * (i + 1))]).reshape(-1, 1)\n e.append(x_start + (h * i))\n elif i == cnt:\n A[i, :, :] = trimf(x, [x_start + (h * (i - 2)), x_end, x_end]).reshape(-1, 1)\n e.append(x_end)\n\n# 微分\ndef diff(f, x):\n h = 1e-4\n return (f(x + h) - f(x - h)) / (2 * h)\n\n\n# 目標函數\ndef g_function(x):\n return np.cos(x)\n\n\n# 定義宇集合區間與epsilon\nepsilon = 0.3 # \nx_start = -3\nx_end = 3\nx = np.linspace(x_start, x_end, 1000)\ng = g_function(x)\n\n# g(x)微分取sup,並計算出h1\ndg = diff(g_function, x)\nh1 = epsilon / np.around(max(dg))\n\n# 計算fuzzy set個數\ncnt = int(((x_end - x_start) / h1) + 1)\n\n# 計算fuzzy set\nA = np.empty((cnt, int(len(x)), 1))\ne = []\n\nfuzzy_set(x, x_start, x_end, cnt, epsilon, A, e, h1)\n\nfor k in range(cnt):\n plt.figure(1)\n plt.plot(x, A[k])\n for j in range(1, len(x)):\n f = (g_function(e) * A[k][j]) / (A[k][j])\n\nplt.figure(2)\nplt.title(\"g(x) & f(x)\")\nplt.plot(e, f, label = \"f(x)\")\nplt.plot(x, g, label = \"g(x)\")\nplt.legend()\nplt.show()","sub_path":"fuzzy/fuzzy_model_ex1.py","file_name":"fuzzy_model_ex1.py","file_ext":"py","file_size_in_byte":2507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"219073560","text":"# encoding: utf-8\nfrom urllib.parse import unquote\nfrom marshmallow import ValidationError\n# Based on https://stackoverflow.com/questions/14845196/dynamically-constructing-filters-in-sqlalchemy\n__author__ = 'Tharun Mathew Paul (tmpaul06@gmail.com)'\n\n\nclass FilterParser(object):\n\n def __init__(self, model_class, sep=';', list_separator=','):\n self.model_class = model_class\n self.sep = sep\n self.list_separator = list_separator\n\n def parse_filters(self, filters):\n \"\"\"Parse the user provided filters\n\n Parameters\n ----------\n filters: list(str)\n List of filters. Each filter uses `sep` as a separator that identifies the LHS, RHS and op\n\n Returns\n -------\n List of parsed filter representations with op, LHS & RHS\n \"\"\"\n parsed_filters = []\n for filter_ in filters:\n filter_ = unquote(filter_)\n try:\n key, op, value = filter_.split(self.sep)\n if op == 'in':\n if value:\n value = list(value.split(self.list_separator))\n if key is not None and value is not None:\n parsed_filters.append((\n op,\n key,\n value\n ))\n except ValueError:\n raise ValidationError('Invalid filter: %s' % filter_)\n return parsed_filters\n\n def create_filtered_query(self, query, parsed_filters):\n \"\"\"Filter a given query using provided filters\"\"\"\n\n for [op, key, value] in parsed_filters:\n if not hasattr(self.model_class, key):\n raise ValidationError('Invalid filter specified %s' % key)\n column = getattr(self.model_class, key)\n\n if op == 'in':\n filt = column.in_(value)\n else:\n try:\n attr = list(filter(\n lambda e: hasattr(column, e % op),\n ['%s', '%s_', '__%s__']\n ))[0] % op\n except IndexError:\n raise ValidationError('Invalid filter operator: %s' % op)\n if value == 'null':\n value = None\n filt = getattr(column, attr)(value)\n\n query = query.filter(filt)\n return query\n\n\nclass SortFieldsParser:\n\n def __init__(self, model_class, sep=':'):\n self.model_class = model_class\n self.sep = sep\n\n def parse_sort_fields(self, sorted_fields):\n \"\"\"Given a list of fields and sort orders return a parsed representation.\n\n e.g if input is of the form ['amount:desc', 'name:asc'] we validate the fields\n based on the model class and return vaues\n \"\"\"\n parsed_sort_fields = list()\n for item in sorted_fields:\n parsed = item.split(self.sep)\n\n if len(parsed) != 2:\n raise ValidationError('Incorrect argument sent in sort: {}'.format(item))\n\n field = parsed[0]\n\n if self.model_class and not hasattr(self.model_class, field):\n raise ValidationError('Unsupported field {}'.format(field))\n\n order = parsed[1]\n\n if order not in ['asc', 'desc']:\n raise ValidationError('Sort order should be one of asc or desc')\n parsed_sort_fields.append([field, order])\n\n return parsed_sort_fields\n","sub_path":"app/extensions/api/custom_field_parsers.py","file_name":"custom_field_parsers.py","file_ext":"py","file_size_in_byte":3471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"225541055","text":"from math import *\n \ndef f(k):\n return sin(k/3.12)+cos(k*k)-9.1*(sin(3*k))\n \ndef g(n):\n return cos(2*n)/1.12-cos(3*n-2)+6.15\n \na= []\nh = 1\nfor k in range (1,5):\n a.append([])\n for n in range(1,5):\n element = n* f(k)+sin(k)*g(n)\n a[k-1].append(element)\n \n print('% 10.4f' % a[k-1][n-1], end=\" \")\n \n if k < n:\n h *= a [k-1][n-1]\n print()\nminimum =[]\nfor i in a:\n if i < 0:\n neg.append(i)\n elif i > 0:\n\n pos.append(i)\nmaximum = max(max(a))\nresult = minimum*maximum\nprint(\"\\n\"\"Min element\",minimum)\nprint(\"Max element\",maximum)\nprint(\"multiplication of min and max elements: \",result)\n","sub_path":"HellowWorld/multi-dimensional_lists.py","file_name":"multi-dimensional_lists.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"99905043","text":"import os\nfrom dataloader import Resizer, Normalizer\nfrom torchvision import datasets, models, transforms\nimport cv2\nimport numpy as np\nfrom glob import glob\nimport torch\nimport time\nimport argparse\nfrom tqdm import tqdm\nfrom torch.utils.data import Dataset, DataLoader\n\nfrom recall_tool import calc_r_and_p\n\n#定义一个数据集\nclass PredictDataset(Dataset):\n \"\"\" 数据集演示 \"\"\"\n def __init__(self, im_ll):\n \"\"\" 保存图片列表,初始化图片预处理器\n \"\"\"\n self.imll = im_ll\n self.transform=transforms.Compose([Normalizer(), Resizer()])\n\n def __len__(self):\n \"\"\" 返回图片列表长度\n \"\"\"\n return len(self.imll)\n def _train_input(self, index):\n annot = np.array([[10,10,20,20,0],], dtype=np.float64)\n im = cv2.imread(self.imll[index])\n h,w,c = im.shape\n img = im.astype(np.float32)/255.0\n samp = {'img':img, 'annot':annot}\n model_input = self.transform(samp)\n img = model_input['img'].float().permute((2,0,1)).contiguous()\n sc_h = model_input['sc_h']\n sc_w = model_input['sc_w']\n return img, sc_w, sc_h, w, h\n def __getitem__(self, idx):\n '''\n 根据 idx 返回一行数据\n '''\n return self._train_input(idx)\n\n\ndef predict(im_ll, model_path='/home/hao.wyh/code/git/pytorch-retinanet/output_models/true_data_v2_mix/coco_retinanet_3.pt'):\n retinanet = torch.load(model_path)\n retinanet = retinanet.cuda()\n retinanet.eval()\n B = PredictDataset(im_ll)\n L = DataLoader(B, batch_size=1, shuffle=False, num_workers=10)\n res_list = []\n w_h_list = []\n print(len(B))\n print(time.time())\n for x, sc_w_list, sc_h_list, w_list, h_list in tqdm(L):\n sc_w_list = sc_w_list.tolist()\n sc_h_list = sc_h_list.tolist()\n w_list = w_list.tolist()\n h_list = h_list.tolist()\n scores, classification, transformed_anchors = retinanet(x.cuda())\n anchors = transformed_anchors.cpu().tolist()\n length = len(sc_w_list)\n\n for i in range(length):\n anchor = anchors[i]\n anchor[0] /= sc_w_list[i]\n anchor[1] /= sc_h_list[i]\n anchor[2] /= sc_w_list[i]\n anchor[3] /= sc_h_list[i]\n res_list.append(anchor[:4])\n w_h_list.append((w_list[i], h_list[i]))\n print(time.time())\n return res_list, w_h_list\n\ndef test(pr_path):\n gt_path = '/home/hao.wyh/jupyter/黑边/评估任务/3k_imgs/'\n im_path = gt_path\n out_content = calc_r_and_p(gt_path=gt_path, pr_path=pr_path, out_put_path=pr_path, im_path=im_path)\n # if save_res_info_path is not None:\n open(os.path.join(pr_path, 'res.res'), 'w').write(out_content)\n\ndef main():\n transform=transforms.Compose([Normalizer(), Resizer()])\n annot = np.array([[10,10,20,20,0],], dtype=np.float64)\n\n parser = argparse.ArgumentParser(description='测试模型效果.')\n #parser.add_argument('--model', help='Path to model (.pt) file.', default='/home/hao.wyh/code/git/pytorch-retinanet/output_models/main_detect_v11_restart/model_final.pt')\n parser.add_argument('-m', dest='model', help='Path to model (.pt) file.', default='/home/hao.wyh/code/git/pytorch-retinanet/output_models/true_data_v2_mix/coco_retinanet_3.pt')\n #parser.add_argument('--model', help='Path to model (.pt) file.', default='output_models/main_detect_v10_deeper8/model_final.pt')\n parser.add_argument('-o', dest='output_path', help='Path to save output imgs.', default='./tmp_out/')\n #parser.add_argument('--input_path', help='Path to save output imgs.', default='/home/hao.wyh/jupyter/黑边/smart_reverse_label')\n #parser.add_argument('--input_path', help='Path to save output imgs.', default='/home/hao.wyh/jupyter/黑边/评估任务/black_imgs')\n parser.add_argument('-i', dest='input_path', help='Path to save output imgs.', default='/home/hao.wyh/jupyter/黑边/评估任务/3k_imgs')\n parser.add_argument('-s', dest='show_out_im', action=\"store_true\" , help='是否测试模型准召率')\n parser.add_argument('-t', dest='test', action=\"store_true\" , help='是否测试模型准召率')\n parser.add_argument('-ot', dest='only_test', action=\"store_true\" , help='是否测试模型准召率')\n parser = parser.parse_args()\n\n if parser.only_test:\n test(parser.output_path)\n exit()\n\n ll = glob(parser.input_path+'/*jpg')\n if len(ll) == 0:\n ll = glob(parser.input_path+'/*jpeg')\n if not os.path.exists(parser.output_path):\n os.mkdir(parser.output_path)\n res_list, w_h_list = predict(ll, parser.model)\n res = []\n for idx in tqdm(range(len(res_list))):\n i = ll[idx]\n name = i.split('/')[-1]\n anchor = res_list[idx]\n anchor = [int(np.round(num)) for num in anchor]\n iterm = name+','+str(anchor[0])+','+str(anchor[1])+','+str(anchor[2])+','+str(anchor[3])\n res.append(iterm)\n if parser.show_out_im:\n im = cv2.imread(i)\n im = cv2.rectangle(im, (anchor[0], anchor[1]), (anchor[2], anchor[3]), (0,0,255), 3)\n cv2.imwrite(os.path.join(parser.output_path, os.path.basename(i)), im)\n # for i in open('./xpd.txt').read().split('\\n'):\n name,x,y,xx,yy = iterm.split(',')\n x,y,xx,yy = [int(i) for i in [x,y,xx,yy]]\n w, h = w_h_list[idx]\n # print(x,y,xx,yy,w,h, name)\n t = y\n d = h - yy\n l = x\n r = w - xx\n t,d,l,r = [str(i) for i in [t,d,l,r]]\n open(os.path.join(parser.output_path, name.replace('.jpeg', '.txt')), 'w').write(','.join([t,d,l,r]))\n open(os.path.join(parser.output_path,'xpd.res'), 'w').write('\\n'.join(res))\n\n if parser.test:\n test(parser.output_path)\n\n\nif __name__ == '__main__':\n main()\n\n\n","sub_path":"batch_predict.py","file_name":"batch_predict.py","file_ext":"py","file_size_in_byte":5815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"2806880","text":"# -*- encoding: utf-8 -*-\nimport re\n\nfrom django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom rest_framework.renderers import JSONRenderer\n\nfrom django.shortcuts import render\n\nfrom . import utils\nfrom pdl.models import Proyecto\nfrom .serializers import IniciativasSerializer, SeguimientosSerializer\n\n\n# Create your views here.\ndef index(request, short_url):\n short_url = re.sub(\"/seguimiento/\", \"\", short_url)\n item = utils.get_proyecto_from_short_url(short_url)\n item.expediente_events = utils.get_events_from_expediente(item.id)\n return render(request, \"seguimientos/index.html\", {\"item\": item})\n\n\nclass JSONResponse(HttpResponse):\n \"\"\"\n An HttpResponse that renders its content into JSON.\n \"\"\"\n def __init__(self, data, **kwargs):\n content = JSONRenderer().render(data)\n super(JSONResponse, self).__init__(content, **kwargs)\n\n\n@csrf_exempt\ndef iniciativa_list(request, short_url):\n \"\"\"List all iniciativas for proyecto.\"\"\"\n try:\n item = utils.get_proyecto_from_short_url(short_url=short_url)\n new_item = utils.prepare_json_for_d3(item)\n except Proyecto.DoesNotExist:\n return HttpResponse(status=404)\n\n if request.method == 'GET':\n serializer = IniciativasSerializer(new_item)\n return JSONResponse(serializer.data)\n\n\nclass MyObj(object):\n pass\n\n\n@csrf_exempt\ndef seguimientos_list(request, short_url):\n \"\"\"List all seguimientos for proyecto.\"\"\"\n try:\n item = utils.get_proyecto_from_short_url(short_url=short_url)\n seguimientos = utils.get_seguimientos_from_proyecto_id(item.id)\n seguimientos.append({\n 'headline': 'Fecha de presentación',\n 'startDate': utils.convert_date_to_string(item.fecha_presentacion).replace(\"-\", \",\"),\n })\n obj = MyObj()\n\n mydict = {}\n mydict['type'] = 'default'\n mydict['text'] = \"Proyecto No: \" + str(item.numero_proyecto).replace(\"/\", \"_\")\n mydict['date'] = seguimientos\n\n obj.timeline = mydict\n except Proyecto.DoesNotExist:\n return HttpResponse(status=404)\n\n if request.method == 'GET':\n serializer = SeguimientosSerializer(obj)\n return JSONResponse(serializer.data)\n","sub_path":"proyectos_de_ley/seguimientos/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"90335468","text":"import unittest\n#from HtmlTestRun import HTMLTestRunner\n\nfrom TestClassA import TestClassA\nfrom TestClassB import TestClassB\nfrom TestClassC import TestClassC\n\n\nif __name__ == '__main__':\n test_classes_to_run = [TestClassA,TestClassB,TestClassC]\n loader = unittest.TestLoader()\n suites_list = []\n for test_class in test_classes_to_run:\n suite = loader.loadTestsFromTestCase(test_class)\n suites_list.append(suite)\n\n big_suite = unittest.TestSuite(suites_list)\n runner = unittest.TextTestRunner()\n results = runner.run(big_suite)\n","sub_path":"Py-Misc/CommandLineTestSuite.py","file_name":"CommandLineTestSuite.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"139170886","text":"# Copyright 2021 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nfrom flask import Flask, render_template\nimport sqlalchemy\n\n\ndb_name = os.environ.get(\"DATABASE_NAME\", None)\ndb_user = os.environ.get(\"DATABASE_USER\", None)\ndb_pass = os.environ.get(\"DATABASE_PASS\", None)\n\n## Unix Socket settings\ndb_socket_dir = os.environ.get(\"DATABASE_SOCKET_DIR\", \"/cloudsql\")\ndb_sql_connection = os.environ.get(\"INSTANCE_CONNECTION_NAME\", None)\n\n## TCP settings\ndb_host = os.environ.get(\"DATABASE_HOST\")\ndb_port = os.environ.get(\"DATABASE_PORT\", 5432)\ndb_type = os.environ.get(\"DATABASE_TYPE\", \"postgres\")\n\napp = Flask(__name__)\n\n\ndef connect_db():\n\n # Helper for different database types\n sock_ext = \"\"\n socket_name = \"unix_socket\"\n if db_type == \"postgres\":\n sock_ext = f\"/.s.PGSQL.{db_port}\"\n socket_name = \"unix_sock\"\n drivername = \"postgresql+pg8000\"\n elif db_type == \"mysql\":\n drivername = \"mysql+pymysql\"\n elif db_type == \"mssql\":\n drivername = \"mssql+pytds\"\n else:\n raise ValueError(\"Unknown database type provided.\")\n\n if db_host and db_port:\n settings = {\"host\": db_host, \"port\": db_port}\n elif db_socket_dir and db_sql_connection:\n settings = {\n \"query\": {socket_name: f\"{db_socket_dir}/{db_sql_connection}{sock_ext}\"}\n }\n else:\n raise ValueError(\"No Socket/Dir nor Host/Port provided.\")\n\n db = sqlalchemy.create_engine(\n sqlalchemy.engine.url.URL.create(\n drivername=drivername,\n username=db_user,\n password=db_pass,\n database=db_name,\n **settings,\n )\n )\n return db\n\n\n@app.get(\"/\")\ndef main():\n try:\n db = connect_db()\n with db.connect() as conn:\n if db_type == \"mssql\":\n now_stmt = \"SELECT getdate() as now\"\n else:\n now_stmt = \"SELECT NOW() as now\"\n\n now = conn.execute(sqlalchemy.text(now_stmt)).scalar()\n return render_template(\n \"index.html\",\n success=True,\n message=f\"Successful connection. Database Time: {now}\",\n )\n except Exception as e:\n return (\n render_template(\n \"index.html\", success=False, message=f\"Connection not successful: {e}\"\n ),\n 500,\n )\n\n\nif __name__ == \"__main__\":\n app.run(host=\"localhost\", port=8080, debug=True)\n","sub_path":"sql-proxy/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"84371063","text":"#!/usr/bin/env python\n\n# File: Pymail/send.py\n\n\"\"\"\nUsed to send an email using Python modules only.\n\n(Utils/utils.py client knows to use this module's send\nfunction for sending emails when it's command line\nparameter --emailer is set to \"python\".)\n\nUsage: (when used from the command line)\n ./send.py smtp_server [JSON_FILE_NAME]\n\nOptions:\n server can be any of the keys defined in the\n Pymail.config.config dict.\n\nProvides send. (when imported as a module)\n\nHave not yet implemented ability to use\na second command line argument to specify\na json file from which to load emails.\n\"\"\"\n\nimport sys\nimport os\nimport smtplib\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom email.mime.application import MIMEApplication\n# from email.mime.base import MIMEBase\n# from email import encoders\nimport mimetypes\nimport hashlib\nimport json\nimport time\nimport random\n\ntry:\n import config\nexcept ModuleNotFoundError:\n import Pymail.config as config\n\nMIN_TIME_TO_SLEEP = 1 #} Seconds between\nMAX_TIME_TO_SLEEP = 5 #} email postings.\n\ndef pause():\n \"\"\"\n Provides a random interval between emails so that the\n MTA is less likely to think the process is automated.\n Only used in the case of gmail.\n \"\"\"\n time.sleep(random.randint(MIN_TIME_TO_SLEEP,\n MAX_TIME_TO_SLEEP))\n\n\nrfc5322 = { # Here for reference, not used by the code.\n# Originator Fields\n \"from\": \"From: \", # mailbox-list CRLF\n \"sender\": \"Sender: \", # mailbox CRLF\n \"reply-to\": \"Reply-To: \", # address-list CRLF\n\n# Destination Address Fields\n \"to\": \"To: \", # address-list CRLF\n \"cc\": \"Cc: \", # address-list CRLF\n \"bcc\": \"Bcc: \", # [address-list / CFWS] CRLF\n\n# Identification Fields\n \"message-id\": \"Message-ID: \", # msg-id CRLF\n# \"in-reply-to\": \"In-Reply-To: \", # 1*msg-id CRLF\n# \"references\": \"References: \", # 1*msg-id CRLF\n# \"msg-id\": [CFWS] \"<\" id-left \"@\" id-right \">\" [CFWS]\n# \"id-left\": dot-atom-text / obs-id-left\n# \"id-right\": dot-atom-text / no-fold-literal / obs-id-right\n# \"no-fold-literal\": \"[\" *dtext \"]\"\n\n# Informational Fields\n \"subject\": \"Subject: \", # unstructured CRLF\n \"comments\": \"Comments: \", # unstructured CRLF\n \"keywords\": \"Keywords: \", # phrase *(\",\" phrase) CRLF\n }\n\n\ndef get_bytes(text):\n \"\"\"\n Not used. Can be redacted.\n \"\"\"\n return hashlib.sha224(bytes(text, 'utf-8')).hexdigest()\n\n\ndef get_py_header(header):\n \"\"\"\n Not used. Can be redacted.\n \"\"\"\n return rfc5322[header.replace('-', '_')]\n\n\ndef pseudo_recipient(plus_name, g_email):\n \"\"\"\n Returns an email address that will go to the gmail\n account specified by .\n This is only applicable to gmail accounts: emulation of\n multiple addresses all pointing to same inbox:\n my+person1@gmail.com, my+person2@gmail.com, ...\n all go to my@gmail.com\n \"\"\"\n parts = g_email.split('@')\n assert len(parts) == 2\n return parts[0] + '+' + plus_name + '@' + parts[1]\n\n\ndef attach(attachment, msg):\n \"\"\"\n : an instance of MIMEMultipart() to which to add\n the attachment.\n is the name of a file to become an attachment.\n This code has been successfully tested to work for the\n following types of files: text, .docx, .pdf, ..\n so is expected to work for all files.\n \"\"\"\n basename = os.path.basename(attachment)\n with open(attachment, \"rb\") as f_obj:\n part = MIMEApplication(\n f_obj.read(), basename)\n # After the file is closed\n part['Content-Disposition'] = (\n 'attachment; filename=\"%s\"' % basename)\n msg.attach(part)\n\n\ndef attach_many(attachments, msg):\n \"\"\"\n This code was 'plagerized' from the web.\n It is a slightly modified version of an excerpt of\n code submitted by vijay.anand found here..\n https://stackoverflow.com/questions/52292971/sending-single-email-with-3-different-attachments-python-3\n It is failing and therefore not used. It's being left here\n in the hopes that it can be mended.\n \"\"\"\n for attachment in attachments:\n content_type, encoding = mimetypes.guess_type(attachment)\n if content_type is None or encoding is not None:\n content_type = \"application/octet-stream\"\n maintype, subtype = content_type.split(\"/\", 1)\n if maintype == \"text\":\n with open(attachment) as fp:\n # Note: we should handle calculating the charset\n attachment = MIMEText(fp.read(), _subtype=subtype)\n elif maintype == \"image\":\n with open(attachment, \"rb\") as fp:\n attachment = MIMEImage(fp.read(), _subtype=subtype)\n elif maintype == \"audio\":\n with open(attachment, \"rb\")as fp:\n attachment = MIMEAudio(fp.read(), _subtype=subtype)\n else:\n with open(attachment, \"rb\") as fp:\n attachment = MIMEBase(maintype, subtype)\n attachment.set_payload(fp.read())\n encoders.encode_base64(attachment)\n attachment.add_header(\"Content-Disposition\", \"attachment\",\n filename=os.path.basename(attachment))\n msg.attach(attachment)\n\ndef attach1(attachment, msg):\n \"\"\"\n Not used. Not understood- should probably be redacted.\n \"\"\"\n # Open PDF file in binary mode\n with open(filename, \"rb\") as attachment:\n # Add file as application/octet-stream\n # Email client can usually download this automatically\n # as attachment\n part = MIMEBase(\"application\", \"octet-stream\")\n part.set_payload(attachment.read())\n\n # Encode file in ASCII characters to send by email\n encoders.encode_base64(part)\n\n # Add header as key/value pair to attachment part\n part.add_header(\n \"Content-Disposition\",\n f\"attachment; filename= {filename}\",\n )\n\n\ndef into_string(header_value):\n \"\"\"\n Returns a string (possibly empty.)\n If given a list it must be of strings and a comma/space\n separated concatination is returned.\n \"\"\"\n# print(\" '{}' is of type {}.\"\n# .format(header_value, type(header_value)))\n if isinstance(header_value, str):\n return header_value\n elif isinstance(header_value, list):\n return ', '.join(header_value)\n else:\n return ''\n\n\ndef send(emails, mta, report_progress=True,\n include_wait=True):\n \"\"\"\n Sends emails using Python modules.\n is a list of dicts each representing an email to\n be sent. Each dict can have the following keys, some optional:\n 'body': a (possibly empty) string.\n 'attachments': a list (possible empty) of file names.\n 'From', 'Reply-To', 'To', 'Subject', ...\n ...and possibly other commonly used fields defined by rfc5322.\n ...Values are either strings or lists of strings;\n in the latter case the values are converted into a single\n comma separated string.\n \"\"\"\n n_emails = len(emails)\n counter = 0\n print(\"Using {} as MTA...\".format(mta))\n server = config.config[mta]\n sender = server[\"from\"]\n if report_progress:\n print(\"Initiating SMTP: {host} {port}\".format(**server))\n s = smtplib.SMTP(host=server['host'], port=server['port'])\n s.starttls()\n s.ehlo\n\n # Comment out one of the following two:\n# testing = True # Very INSECURE: use only for testing.\n testing = False # This should be the default.\n if report_progress:\n if mta.endswith('g') and testing:\n message = (\n \"Attempting login: {user} /w pw '{password}' ...\")\n else:\n message = (\n \"Attempting login: {user} /w pw REDACTED ...\")\n print(message.format(**server))\n s.login(server['user'], server['password'])\n print(\"... successful.\")\n\n try:\n for email in emails:\n email[\"Sender\"] = sender\n msg = MIMEMultipart()\n body = email['body']\n attachments = email['attachments']\n del email['body']\n del email['attachments']\n if report_progress:\n counter += 1\n print(\"Sending email {} of {} ...\"\n .format(counter, n_emails))\n for key in email:\n print(\"\\t{}: {}\".format(key, email[key]))\n msg[key] = into_string(email[key])\n msg.attach(MIMEText(body, 'plain'))\n# attach_many(attachments, msg) ## Fails, 2b trouble sh.\n for attachment in attachments:\n attach(attachment, msg)\n\n s.send_message(msg)\n del msg\n if include_wait:\n pause()\n except:\n s.quit()\n if report_progress:\n print(\"Pymail.send.send() failed sending to {}.\"\n .format(email['To']))\n raise\n s.quit()\n\n\ndef main(emails):\n \"\"\"\n email.mime.text.MIMEText\n email.mime.multipart.MIMEMultipart\n \"\"\"\n\nif __name__ == \"__main__\":\n test_body_1 = \"\"\"\n This is a test using Reply-To: gmail.\n Here's hoping it goes well.\n Goog luck.\n \"\"\"\n\n argv_length = len(sys.argv)\n\n if not argv_length > 1:\n print(\"Server (MTA) not specified.\")\n sys.exit()\n mta = sys.argv[1]\n if not mta in config.config:\n print(\"MTA server designation invalid.\")\n sys.exit()\n\n if argv_length == 3:\n print(\"Second argument not yet implemented\")\n sys.exit()\n test_emails = get_emails(sys.argv[2])\n else:\n test_emails = [\n {\n 'From': 'alex@kleider.ca',\n 'Reply-To': 'alexkleider@gmail.com',\n 'To': ['akleider@sonic.net',\n pseudo_recipient('ak', 'alexkleider@gmail.com'),\n ],\n 'Subject': 'TEST Reply-To',\n 'attachments': [\n '/home/alex/Downloads/book_club_2020-2021_listing.docx',],\n 'body': test_body_1,\n },\n ]\n send(test_emails, mta=mta)\n\n","sub_path":"Pymail/send.py","file_name":"send.py","file_ext":"py","file_size_in_byte":9989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"378479474","text":"from selenium import webdriver\n\ndriver = webdriver.Firefox\n\n\ncity = str(input(\"Enter City Name: \"))\n\ndriver.get(\"https://www.weather-forecast.com/locations/\"+city+\"/forecasts/latest\")\n\n\nprint(driver.find_elements_by_class_name(\"b-forecast__table-description-content\")[0].text)\n#Test\n","sub_path":"Weather.py","file_name":"Weather.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"285266117","text":"#Definition for singly-linked list.\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution(object):\n def addTwoNumbers(self, l1, l2):\n h = ListNode(0)\n p, carry = h, 0\n while l1 or l2:\n Sum = carry\n if l1:\n Sum, l1 = Sum + l1.val, l1.next\n if l2:\n Sum, l2 = Sum + l2.val, l2.next\n p.next, carry = ListNode(int(Sum % 10)), int(Sum / 10)\n p = p.next\n p.next = ListNode(carry) if carry else None\n return h.next\n\nl1 = ListNode(2)\nl1.next = ListNode(1)\nl1.next.next = ListNode(9)\n\nl2 = ListNode(1)\nl2.next = ListNode(5)\nl2.next.next = ListNode(8)\n\nsol = Solution()\nl3 = sol.addTwoNumbers(l1, l2)\n\nwhile l3 != None:\n print(l3.val)\n l3 = l3.next\n\n","sub_path":"2_AddTwoNumbers/2_addTwoNumbers.py","file_name":"2_addTwoNumbers.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"297683271","text":"# --------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# --------------------------------------------------------------------------------------------\n\nfrom time import sleep\nfrom azure.cli.testsdk import ScenarioTest, JMESPathCheck\n\n\nclass ResourceLockTests(ScenarioTest):\n def test_list_locks(self):\n # just make sure this doesn't throw\n self.cmd('az lock list').get_output_in_json()\n\n def test_lock_create_list_delete(self):\n for lock_type in ['ReadOnly', 'CanNotDelete']:\n lock_name = self.create_random_name('cli-test-lock', 48)\n self.cmd('az lock create -n {} --lock-type {}'.format(lock_name, lock_type))\n self._sleep_for_lock_operation()\n\n locks_list = self.cmd('az lock list').get_output_in_json()\n self.assertTrue(locks_list)\n self.assertIn(lock_name, [l['name'] for l in locks_list])\n\n lock = self.cmd('az lock show -n {}'.format(lock_name)).get_output_in_json()\n self.assertEqual(lock.get('name', None), lock_name)\n self.assertEqual(lock.get('level', None), lock_type)\n\n self.cmd('az lock delete -n {}'.format(lock_name))\n self._sleep_for_lock_operation()\n\n def test_readonly_lock_create_list_delete_resource_group(self):\n self._lock_operation_with_resource_group('ReadOnly')\n\n def test_cannotdelete_lock_create_list_delete_resource_group(self):\n self._lock_operation_with_resource_group('CanNotDelete')\n\n def _lock_operation_with_resource_group(self, lock_type):\n rg_name = self.create_random_name('cli.lock.rg', 75)\n lock_name = self.create_random_name('cli-test-lock', 48)\n\n self.cmd('az group create --location {} --name {} --tag use=az-test'.format('southcentralus', rg_name))\n self.addCleanup(lambda: self.cmd('az group delete -n {} --yes --no-wait'.format(rg_name)))\n\n self.cmd('az lock create -n {} -g {} --lock-type {}'.format(lock_name, rg_name, lock_type))\n self._sleep_for_lock_operation()\n\n self.cmd('az lock show -g {} -n {}'.format(rg_name, lock_name)).assert_with_checks([\n JMESPathCheck('name', lock_name),\n JMESPathCheck('level', lock_type)])\n\n locks_list = self.cmd(\"az lock list --query '[].name' -ojson\").get_output_in_json()\n self.assertTrue(locks_list)\n self.assertIn(lock_name, locks_list)\n\n self.cmd('az lock delete -g {} -n {}'.format(rg_name, lock_name))\n self._sleep_for_lock_operation()\n\n def _sleep_for_lock_operation(self):\n if self.is_live:\n sleep(5)\n","sub_path":"src/command_modules/azure-cli-resource/azure/cli/command_modules/resource/tests/test_locks.py","file_name":"test_locks.py","file_ext":"py","file_size_in_byte":2787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"442335770","text":"sentence = 'This is a common interview question'\nunpack = [*sentence.lower()]\n\n\n# 递归:减而治之\n# def find_max_count(unpack):\n# if len(unpack) == 1:\n# return unpack[0], 1\n# son_unpack = unpack[:-1]\n# last_character = unpack[-1]\n# count_last = 1\n# son_max_character, son_max_count = find_max_count(son_unpack)\n# for character in son_unpack:\n# if character == last_character:\n# count_last += 1\n# if count_last >= son_max_count:\n# max_character = last_character\n# max_count = count_last\n# else:\n# max_character = son_max_character\n# max_count = son_max_count\n# return max_character, max_count\n\n\n# print(find_max_count(unpack))\n\n\n# 字典\ndef find_max_count2(unpack):\n dic = {}\n for character in unpack:\n if character in dic:\n dic[character] += 1\n else:\n dic[character] = 1\n dic_list = dic.items()\n dic_lsit_sort = sorted(\n dic_list,\n key=lambda kv: kv[1],\n reverse=True\n )\n return dic_lsit_sort[0]\n\n\nprint(find_max_count2(unpack))\n","sub_path":"python/5exercise.py","file_name":"5exercise.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"143900693","text":"# Imports\n\nimport time\nimport numpy as np\nimport pandas as pd\nimport os, os.path\nfrom itertools import *\nimport math\nimport random\nimport scipy.stats\nimport sys\nfrom joblib import Parallel, delayed\nimport multiprocessing\nnproc = max(1, multiprocessing.cpu_count() - 1)\nfrom functools import partial\n\nfrom intervaltree import IntervalTree, Interval\nfrom sklearn import linear_model\nfrom sklearn import ensemble\nfrom scipy.spatial import distance\nfrom sklearn.metrics import r2_score, mean_squared_error\nfrom sklearn.grid_search import GridSearchCV\n\n# Warnings\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\n# Idempotent data retrieval script\n\nchromosomes = [1, 2, 6, 7, 11]\ndef chromosome_files(n):\n base = 'intersected_final_chr'\n spec = '_cutoff_20_'\n suffixes = ['train.bed', 'sample_partial.bed', 'sample_full.bed']\n return [base + str(n) + spec + suffix for suffix in suffixes]\nall_chromosomes = set(chain.from_iterable(chromosome_files(n) for n in chromosomes))\n\nif 'methylation_imputation' not in [x for x in os.listdir('.') if os.path.isdir(x)]:\n raise Exception('Missing assignment repository in cwd')\n\nif not os.path.exists('data'):\n os.mkdir('data')\n\ndef have_chromosomes(): return all_chromosomes.issubset(set(os.listdir('data')))\nif not have_chromosomes():\n raise Exception('Error, missing chromosomes data')\n\nencode_file = 'wgEncodeRegTfbsClusteredV3.bed'\nannotations_files = {encode_file}\ndef have_annotations(): return annotations_files.issubset(set(os.listdir('data')))\nif not have_annotations():\n raise Exception('Error, missing ENCODE data')\n\ndef read_tsv(name): return pd.read_csv(name, sep='\\t', header=None)\n\ndef local_impute(data):\n #http://stackoverflow.com/questions/9537543/replace-nans-in-numpy-array-with-closest-non-nan-value\n mask = np.isnan(data)\n data[mask] = np.interp(np.flatnonzero(mask), np.flatnonzero(~mask), data[~mask])\n return data\n\ndef correlation_similarity(x, y):\n c = distance.correlation(x, y)\n if np.isnan(c): return 0\n else: return 1 - c\n \ndef log_range(lo, hi): return [10 ** i for i in range(lo, hi)]\n\ndef start(s): \n print(s.ljust(50), end='')\n sys.stdout.flush()\n return time.time()\n\ndef end(t):\n print('{: <12.2f} sec'.format(time.time() - t))\n sys.stdout.flush()\n\ndef chromosome_df(n):\n t = start('loading chromosome data')\n train_chr = read_tsv('data/' + chromosome_files(n)[0])\n test_chr_part = read_tsv('data/' + chromosome_files(n)[1])\n test_chr_full = read_tsv('data/' + chromosome_files(n)[2])\n end(t)\n\n t = start('feature extraction on chromosome data')\n test_ix = np.where((test_chr_part[5] == 0) & ~np.isnan(test_chr_full[4]))[0]\n train_ix = np.where((test_chr_part[5] == 1) & ~np.isnan(test_chr_part[4]))[0]\n\n train_df = train_chr\n train_tissues = ['b' + str(x) for x in range(train_chr.shape[1] - 4)]\n train_df.columns = ['chromosome', 'start', 'end', 'strand'] + train_tissues\n\n test_df = test_chr_full\n test_df.columns = ['chromosome', 'start', 'end', 'strand', 'filled', 'assayed']\n test_df['missing'] = test_chr_part[4]\n\n train_df['strand'] = train_df['strand'] == '+'\n test_df['strand'] = test_df['strand'] == '+'\n \n for i in train_tissues:\n train_df[i] = local_impute(train_df[i].copy())\n \n similarities = np.array([correlation_similarity(train_df[t].iloc[train_ix],\n test_df['filled'].iloc[train_ix])\n for t in train_tissues])\n k = np.sum(np.fabs(similarities))\n cf = pd.Series(train_df[train_tissues].values.dot(similarities) / k, index=train_df.index)\n train_df['cf'] = cf\n end(t)\n\n t = start('loading CRE data')\n rawe = read_tsv('data/' + encode_file)\n rawe.drop([4, 5, 6, 7], axis=1, inplace=True)\n rawe.columns = ['chromosome', 'start', 'end', 'tf']\n tfs = set(rawe['tf'])\n end(t)\n\n\n def inside_tf(iv, row):\n overlap = [x.data for x in iv[row['start']:row['end']]]\n return pd.Series({tf: (tf in overlap) for tf in tfs})\n \n t = start('creating interval tree')\n iv_chr = IntervalTree((Interval(*x[1]) for x in\n rawe[rawe['chromosome'] == ('chr' + str(n))][['start', 'end', 'tf']].iterrows()))\n end(t)\n \n t = start('merging CRE intersections')\n # TODO: this could be parallelized easily here and in the iPython notebook\n train_df = train_df.merge(train_df[['start', 'end']].apply(partial(inside_tf, iv_chr), axis=1), copy=False,\n left_index=True, right_index=True)\n end(t)\n\n train_df.drop('chromosome', axis=1, inplace=True)\n train_df.drop('start', axis=1, inplace=True)\n train_df.drop('end', axis=1, inplace=True)\n \n t = start('training blunt model')\n best_combined = linear_model.Lasso()\n grid = GridSearchCV(best_combined, {'alpha': log_range(-10, 10)}, cv=50, n_jobs=nproc)\n grid.fit(train_df.iloc[train_ix], test_df['filled'].iloc[train_ix])\n alpha = grid.best_params_['alpha']\n end(t)\n \n print('blunt alpha {:02f}'.format(alpha))\n \n t = start('training precise model')\n alpha_range = np.arange(0, 2 * alpha, alpha / 100)\n grid = GridSearchCV(best_combined, {'alpha': alpha_range}, cv=50, n_jobs=nproc)\n grid.fit(train_df.iloc[train_ix], test_df['filled'].iloc[train_ix])\n end(t)\n \n guess = grid.predict(train_df.iloc[test_ix])\n exact = test_df['filled'].iloc[test_ix].values\n\n rmse = math.sqrt(mean_squared_error(exact, guess))\n acc = ((exact >= 0.5) == (guess >= 0.5)).mean()\n r2 = r2_score(exact, guess)\n res = guess - exact\n\n print('Ensemble on test: rmse {:04f} methyl acc {:04f} R^2 {:04f} alpha {:04f}'\n .format(rmse, acc, r2, grid.best_params_['alpha']))\n \nif __name__ == '__main__':\n if len(sys.argv) != 2:\n print('Usage: python check_chromosome.py n\\n\\n' + \\\n 'Runs the entire pipeline on chromosome n, outputting final performance.' + \\\n 'May spawn nproc jobs.', file=sys.stderr)\n chromosome_df(int(sys.argv[1]))\n\n","sub_path":"check_chromosome.py","file_name":"check_chromosome.py","file_ext":"py","file_size_in_byte":6138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"3933539","text":"import click\nimport subprocess\nimport os\nimport requests\nimport json\n\nfrom colored import fg\nfrom colored import stylize\nfrom os import environ\n\nif environ.get('VECTORDASH_BASE_URL'):\n VECTORDASH_URL = environ.get('VECTORDASH_BASE_URL')\nelse:\n VECTORDASH_URL = \"https://vectordash.com/\"\n\n\n@click.command(name='stop')\ndef stop_hosting():\n \"\"\"\n Stops the Vectordash client.\n \"\"\"\n\n try:\n\n # ensuring the login file exists\n if not os.path.isfile('/var/vectordash/login.json'):\n print(\"You are not logged in. Please run \" +\n stylize(\"vdhost login\", fg(\"blue\")) + ' to continue.')\n return\n\n # if the installation process has not been completed\n if not os.path.isfile('/var/vectordash/installation_complete'):\n print(\"You are not currently running the Vectordash hosting client because you have not setup your machine \"\n \"yet. Please run \" + stylize(\"vdhost install\", fg(\"blue\")) + \" first.\")\n return\n\n # we must check for active instances before stopping vdclient\n with open('/var/vectordash/login.json') as f:\n data = json.load(f)\n\n # reading in the login credentials\n email = data[\"email\"]\n machine_key = data[\"machine_key\"]\n\n # getting the active instance count for this machine\n r = requests.post(VECTORDASH_URL + \"active-instance-count/\",\n data={'email': email, 'machine_key': machine_key})\n\n # if there was an error with the response\n if r.status_code != 200:\n print(stylize(\"An unexpected error has occurred. Please try again later.\", fg(\"red\")))\n return\n\n # getting the value from the response\n resp = r.text\n resp = json.loads(resp)\n num_instances = int(resp['active_instances'])\n\n # if it's a negative integer, authentication was invalid\n if num_instances < 0:\n print(\"Invalid authentication information . Please run \" +\n stylize(\"vdhost login\", fg(\"blue\")) + ' to continue.')\n return\n\n elif num_instances > 0:\n print(stylize(\"Please keep the client online until all active instances have been completed.\",\n fg(\"red\")))\n return\n\n else:\n\n # calling stop on vclient, note that supervisor prints out a message for us\n subprocess.call(\"sudo supervisorctl stop vdhost\", shell=True)\n\n except OSError:\n\n # if we get a permissions error\n print(stylize(\"Please run this command as sudo:\", fg(\"red\"))\n + stylize(\"sudo vdhost start-miner \", fg(\"blue\")))\n","sub_path":"vdhost/cli/stop_hosting.py","file_name":"stop_hosting.py","file_ext":"py","file_size_in_byte":2694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"353748701","text":"from .aunt import NewAunt\nfrom .utils import parse_tape\nfrom .input_data import input_data, ticker_tape\n\n\ndef solution():\n query = parse_tape(ticker_tape)\n aunts = [NewAunt.parse_line(line) for line in input_data]\n best_match = None\n best_score = -float('inf')\n\n for idx, aunt in enumerate(aunts):\n score = aunt.get_score(query)\n\n if score > best_score:\n best_score = score\n best_match = idx\n\n return best_match + 1","sub_path":"day_16/task2.py","file_name":"task2.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"73285798","text":"import requests\nimport os\n\n# URLs\ntraffic_cam_num = 45\nurl = 'https://5723acd20ffa9.streamlock.net:1935/lexington-live/lex-cam-0'+ str(traffic_cam_num) + '.stream/'\nplaylist_url = 'playlist.m3u8'\n\nfile_path = 'C:\\\\Users\\\\chaud\\\\Desktop\\\\!Back_this_folder!\\\\!Back_this_folder_up_old!\\\\Coding and AI\\\\python\\\\Lexington Traffic Project\\\\'\nname_of_playlist ='playlist.txt'\n\n#Makes folder\nmedia_folder_path = file_path + 'media_' + str(traffic_cam_num) + '\\\\'\nif not os.path.exists(media_folder_path):\n os.makedirs(media_folder_path)\n\nvideo_record = []\n\nwhile True:\n #Gets First Part of number\n playlist = requests.get(url = url + playlist_url)\n playlist_txt = open( file_path + name_of_playlist, 'wb')\n playlist_txt.write(playlist.content)\n playlist_txt = open( file_path + name_of_playlist, 'r')\n first_numbers = playlist_txt.readlines()[3] \n playlist_txt.close()\n\n under_score_index = first_numbers.find('_')\n dot_index = first_numbers.find('.')\n\n first_numbers = first_numbers[int(under_score_index) +1 : int(dot_index)]\n # print(first_numbers)\n playlist_txt.close()\n\n #Gets Chunklist\n chunklist_url = 'chunklist_' + first_numbers \n\n chunklist = requests.get(url = url + chunklist_url + '.m3u8')\n chunklist_txt = open(file_path + chunklist_url + '.txt', 'wb')\n chunklist_txt.write(chunklist.content)\n chunklist_txt = open(file_path + chunklist_url + '.txt', 'r')\n chunklist_lines = chunklist_txt.readlines()[5:]\n chunklist_txt.close()\n os.remove(file_path + chunklist_url + '.txt')\n\n for lines in chunklist_lines:\n if lines[0] !='#':\n lines = lines[:-1]\n\n \n if len(video_record) >=3:\n if lines[-8:-3] == video_record[-1] or lines[-8:-3] == video_record[-2] or lines[-8:-3] == video_record[-3]:\n print('Line: ' + str(lines[-8:-3] + ' | video_record: ' + str(video_record[-3]) + ' '+ str(video_record[-2]) + ' '+ str(video_record[-1]) + ' '))\n print('Broke')\n break\n \n if not os.path.isfile(media_folder_path + str(lines)):\n \n video = requests.get(url = url + lines)\n video_path = open(media_folder_path + str(lines), 'xb')\n\n video_path.write(video.content)\n video_path.close()\n video_record.append(lines[-8:-3])\n if len(video_record) > 3:\n video_record.pop(0)\n print(lines)\n print(video_record)\n\n \n\n \n\n\n\n","sub_path":"traffic_video_data.py","file_name":"traffic_video_data.py","file_ext":"py","file_size_in_byte":2580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"626308721","text":"import sys\n# import threading\nimport multiprocessing\nimport subprocess\n\nclass MyThread (multiprocessing.Process):\n def __init__(self, name):\n super().__init__()\n self.name = name;\n\n def run (self):\n while True:\n subprocess.run (['ping', '-s 128', 'localhost'], stdout=subprocess.DEVNULL)\n print (f\"Thread {self.name} sent ping\");\n\nfor i in range (10):\n MyThread (str(i)).start()\n","sub_path":"python/DDOS_Tool/ddos.py","file_name":"ddos.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"192693949","text":"import setuptools\n\nwith open(\"README.md\", \"r\") as readme_file:\n long_description = readme_file.read()\n\nsetuptools.setup(\n name=\"mijiahygrothermolib\",\n version=\"0.0.1\",\n author=\"Aral Can Kaymaz\",\n author_email=\"aralcan@hotmail.com\",\n description=\"A package to discover and read values from a Xiaomi Mijia BLE Sensor\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/heironeous/mijiahygrothermolib\",\n packages=setuptools.find_packages(),\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ],\n python_requires='>=3.6'\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"197809851","text":"import pytest\nfrom flask import url_for\nfrom responses import Response\n\nfrom api.models import Message, MessageStatus\nfrom api.use_cases import SendMessageToForeignUseCase, SendMessageFailure, ProcessMessageUseCase\n\n\nclass TestSendMessageToForeignUseCase:\n @pytest.fixture(autouse=True)\n def setup(self, mocked_responses):\n self.mocked_responses = mocked_responses\n self.endpoint = 'http://foreign_endpoint.com'\n self.message = Message(payload={\"receiver\": \"AU\"})\n\n def test_send__when_responded_OK__should_set_status_as_delivered(self):\n self.mocked_responses.add(\n Response(method='POST', url=self.endpoint)\n )\n use_case = SendMessageToForeignUseCase(self.endpoint)\n use_case.send(self.message)\n\n assert self.message.status == MessageStatus.DELIVERED\n assert len(self.mocked_responses.calls) == 1\n assert self.mocked_responses.calls[0].request.body == b'{\"receiver\": \"AU\"}'\n\n def test_send__when_responded_not_OK__should_raise_exception(self):\n self.mocked_responses.add(\n Response(method='POST', url=self.endpoint, status=400)\n )\n use_case = SendMessageToForeignUseCase(self.endpoint)\n with pytest.raises(SendMessageFailure):\n use_case.send(self.message)\n\n\n@pytest.mark.usefixtures(\"client_class\", \"clean_channel_repo\", \"clean_channel_queue_repo\", \"mocked_responses\")\nclass TestProcessMessageUseCase:\n message_data = {\n \"sender\": \"AU\",\n \"receiver\": \"CN\",\n \"subject\": \"AU.abn0000000000.XXXX-XXXXX-XXXXX-XXXXXX\",\n \"obj\": \"QmQtYtUS7K1AdKjbuMsmPmPGDLaKL38M5HYwqxW9RKW49n\",\n \"predicate\": \"UN.CEFACT.Trade.CertificateOfOrigin.created\"\n }\n endpoint = 'http://foreign_endpoint.com'\n\n def test_process_message__when_not_delivered__should_try_to_deliver(self):\n self.mocked_responses.add(\n Response(method='POST', url=self.endpoint)\n )\n use_case = ProcessMessageUseCase(self.channel_repo, self.channel_queue_repo, self.endpoint)\n self.client.post(url_for('views.post_message'), json=self.message_data)\n use_case.execute()\n\n assert len(self.mocked_responses.calls) == 1\n assert self.mocked_responses.calls[0].request.body == b'{\"obj\": \"QmQtYtUS7K1AdKjbuMsmPmPGDLaKL38M5HYwqxW9RKW49n\", \"predicate\": \"UN.CEFACT.Trade.CertificateOfOrigin.created\", \"receiver\": \"CN\", \"sender\": \"AU\", \"subject\": \"AU.abn0000000000.XXXX-XXXXX-XXXXX-XXXXXX\"}'\n","sub_path":"api/tests/test_use_cases.py","file_name":"test_use_cases.py","file_ext":"py","file_size_in_byte":2477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"38559443","text":"import numpy as np\nimport pandas as pd\nimport xlsxwriter\nfrom pandas import Series, DataFrame\nfrom scipy import stats\nfrom time import sleep\n\ndata = pd.read_html('https://fantasy.nfl.com/research/rankings?leagueId=0&statType=draftStats')\ndata = data[0]\nstrength = pd.read_html('https://www.cbssports.com/nfl/news/2019-nfl-strength-of-schedule-patriots-and-redskins-have-it-easiest-raiders-face-roughest-ride/')\nstrength = strength[0]\n\nplayer_name = data.loc[:,'Player']\nplayer_name = Series(player_name)\nclean = player_name.str.split(expand=True)\n\nstrength.drop(axis=0, index=[0],inplace=True)\nstrength.columns = ['Rank','Team','Opp Record','Opp Win %']\nshortNames = ['dummy','OAK','DEN','JAX','HOU','CHI','KC','ATL','IND',\n 'TEN','MIN','SF','ARI','TB','DAL','GB','LAC','CAR','MIA',\n 'PIT','DET','BAL','NO','CLE','BUF','SEA','PHI','CIN','NYG',\n 'NYJ','LA','NE','WAS']\nshortNames = Series(shortNames)\nstrength['new'] = shortNames\nstrength.drop(axis = 1, columns=['Team','Opp Record'],inplace=True)\nstrength.columns = ['Rank','Opp Win %','Team']\n\noutput = DataFrame()\noutput['Rank'] = data['Rank']\noutput['First'] = clean[0]\noutput['Last'] = clean[1]\noutput['Position'] = clean[2]\noutput['Team'] = clean[4]\n\noutput = output.merge(right = strength, on = 'Team')\noutput['Player'] = output[['First', 'Last']].apply(lambda x: ' '.join(x), axis=1)\noutput = output[['Rank_x','Player','Position','Team','Rank_y','Opp Win %']]\n\nold = pd.read_excel('2018values.xlsx', sheet_name = 'value')\noutput = pd.merge(output, old[['Player','VBD']], on = 'Player', how = 'outer')\n\n\noutput.columns = ['Player Ranking','Player','Position','Team','SOS','Opp Win %','2018 Value']\noutput.sort_values(by = 'Player Ranking', ascending = True, inplace = True)\noutput[['Player Ranking']] = output[['Player Ranking']].fillna(value = 'Undrafted')\noutput[['2018 Value']] = output[['2018 Value']].fillna(value = 0)\n\ndvoa = pd.read_html('https://www.footballoutsiders.com/stats/teamoff')\ndvoa = dvoa[0]\n\ncleanNames = []\nfor index, name in enumerate(dvoa):\n name = name.strip()\n cleanNames.append(name.title()) \n\ndvoa.columns = cleanNames\n\ndvoa = dvoa[['Rk','Team','Offense Dvoa', 'Pass Off', 'Rush Off']]\ndvoa['Team'] = dvoa['Team'].replace({'LAR':'LA'})\noutput = output.merge(dvoa, how = 'outer', on = 'Team')\n\nfantasyRankings = xlsxwriter.Workbook('fantasyRankings.xlsx')\nrankData = fantasyRankings.add_worksheet('Top 100')\nrankData.set_column('A:K', 18)\nrankData.add_table('A1:K545', {'data': output.stack(),\n 'columns': [{'header':'Player Ranking'},\n {'header':'Player'},\n {'header':'Position'},\n {'header':'Team'},\n {'header':'SOS'},\n {'header':'Opp Win %'},\n {'header':'2018 Player Value'},\n {'header':'DVOA Rank'},\n {'header':'Offensive DVOA'},\n {'header':'Pass Offense'},\n {'header':'Rush Offense'}]})\n\nfantasyRankings.close()\n\nsleep(2)\nprint('''\n////////////////////////////////////////////////////\n////////////////////////////////////////////////////\n////////////// You can be better ////////////////\n///////////// Than Dave Gettleman ////////////////\n////////////////////////////////////////////////////\n////////////////////////////////////////////////////\n''')\nsleep(2)\n","sub_path":"Fantasy/fantasyRankings.py","file_name":"fantasyRankings.py","file_ext":"py","file_size_in_byte":3635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"157214454","text":"# usage:\n# h5_filenames\n\nimport numpy as np\nimport h5py\nimport sys\nfrom tqdm import tqdm\nimport seaborn as sns\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport os\nfrom keyname import keyname as kn\nfrom fileshash import fileshash as fsh\nfrom pathlib import Path\n\nfilenames = sys.argv[1:]\n\n# check all data is from same software source\nassert len({kn.unpack(filename)['_source_hash'] for filename in filenames}) == 1\n\ndfs = []\n\nfor filename in tqdm(filenames):\n # adapted from https://stackoverflow.com/a/48135340\n try:\n df = pd.read_csv(filename)\n df[\"seed\"] = int(kn.unpack(Path(filename).parts[-2])[\"seed\"])\n df[\"step\"] = int(kn.unpack(Path(filename).parts[-2])[\"step\"])\n dfs.append(df)\n except pd.io.common.EmptyDataError:\n print(filename, \" is empty and has been skipped.\")\n\ndf = pd.concat(dfs)\n\ndf = df[df[\"step\"] < 1050]\n\noutfile = kn.pack({\n 'title' : 'mastergenerations',\n '_data_hathash_hash' : fsh.FilesHash().hash_files(filenames),\n '_script_fullcat_hash' : fsh.FilesHash(\n file_parcel=\"full_parcel\",\n files_join=\"cat_join\"\n ).hash_files([sys.argv[0]]),\n '_source_hash' :kn.unpack(filenames[0])['_source_hash'],\n 'ext' : '.csv'\n})\n\ndf.to_csv(outfile, index=False)\n\nprint('Output saved to', outfile)\n\nx = df.groupby([\"step\", \"seed\", \"Level\"]).mean()\ny = x.reset_index().groupby([\"seed\", \"Level\"]).sum().reset_index()\n\nfor level in df[\"Level\"].unique():\n\n fil = y[y[\"Level\"] == level]\n\n print(\"level\", level)\n print(\"Generations Elapsed mean\", fil[\"Generations Elapsed\"].mean())\n print(\"Generations Elapsed std\", fil[\"Generations Elapsed\"].std())\n print(\"Generations Elapsed min\", fil[\"Generations Elapsed\"].min())\n print(\"Generations Elapsed max\", fil[\"Generations Elapsed\"].max())\n","sub_path":"old/script/GenerationInfoCollate.py","file_name":"GenerationInfoCollate.py","file_ext":"py","file_size_in_byte":1867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"122843319","text":"import libvirt\nimport sys\nimport time\n\ndef getMgmtIp(hypIp, hypUser, guestName):\n conn = libvirt.open(\"qemu+ssh://\" + hypUser + \"@\" + hypIp + \"/system?no_verify=1\")\n dom = conn.lookupByName(guestName)\n mac=\"\"\n ifaces = dom.interfaceAddresses(libvirt.VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_AGENT, 0)\n for (name, val) in ifaces.iteritems():\n if name == \"ens3\":\n mac=val['hwaddr']\n elif name == \"ens9\":\n for ipaddr in val['addrs']:\n if ipaddr['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4:\n ip = ipaddr['addr']\n print(ip+\";\"+mac)\n\ncount = 0\nwhile True:\n try:\n getMgmtIp(sys.argv[1],sys.argv[2],sys.argv[3])\n break\n except Exception as e:\n print(e)\n count = count + 1\n if count > 5:\n print(\"error\")\n break\n time.sleep(30)\n\n","sub_path":"M3Code/VM/autoscaler/getmgmtIPandens3MAC.py","file_name":"getmgmtIPandens3MAC.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"104197907","text":"# Run this with\n# PYTHONPATH=. DJANGO_SETTINGS_MODULE=django_mopho.settings python django_mopho/tornado_runner.py --port=1234\nimport tornado.httpserver\nimport tornado.web\nimport tornado.wsgi\nimport django.core.handlers.wsgi\nfrom django.conf import settings\nimport tornado.ioloop\nfrom tornado.options import define, parse_command_line, options\n\ndjango.setup()\n\nORIGINALS_PATH = \"/Users/gardarh/Desktop/photos/photos\"\nTHUMBS_PATH = \"/Users/gardarh/mopho/thumbs/thumbs\"\nSTATIC_PATH = \"/Users/gardarh/mopho_static\"\n\nMULTI_CORE = True\nTORNADO_PORT = 9998\ndefine('port', type=int, default=TORNADO_PORT)\n\n\ndef main():\n parse_command_line()\n wsgi_app = tornado.wsgi.WSGIContainer(django.core.handlers.wsgi.WSGIHandler())\n\n tornado_app = tornado.web.Application([\n (r\"/originals/(.*)\", tornado.web.StaticFileHandler, {'path': settings.PHOTOS_BASEDIR}),\n (r\"/thumbs/(.*)\", tornado.web.StaticFileHandler, {'path': settings.PHOTOS_THUMBS_BASEDIR}),\n (r\"/static/(.*)\", tornado.web.StaticFileHandler, {'path': settings.STATIC_ROOT}),\n (r\".*\", tornado.web.FallbackHandler, dict(fallback=wsgi_app)),\n ])\n print(\"Tornado server running on port %d, multiple processes: %s\" % (options.port, MULTI_CORE))\n if MULTI_CORE:\n server = tornado.httpserver.HTTPServer(tornado_app)\n server.bind(options.port)\n server.start(0)\n else:\n tornado_app.listen(options.port)\n tornado.ioloop.IOLoop.instance().start()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"django_mopho/tornado_runner.py","file_name":"tornado_runner.py","file_ext":"py","file_size_in_byte":1501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"534315925","text":"a,b,c = [int(x) for x in input().split()] \nl=[a,b,c]\na = min(l)\nc = max(l)\nfor x in l:\n if x>a and x 30 and len(answer_list) <= 3:\n\n\t\tfor word in answer_list:\n\t\t\t# Display the first paragraph to the user with all of the answers \n\t\t\t# replaced by '-'\n\t\t\tfirst_paragraph = first_paragraph.lower().replace(word, \n\t\t\t\t\t\t\t\t\t\t\t\t\t'-'.center(len(word), '-'))\n\n\t\tprint(first_paragraph)\n\n\t\t# Loop for each wiki page the user can guess on.\n\t\twhile points > 0:\n\t\t\tuser_input = input('What is your guess?...').lower()\n\t\t\t# Go to the next challange and deduct points for failing to \n\t\t\t# answer properly.\n\t\t\tif user_input == 'next':\n\t\t\t\tpoints -= 5\n\t\t\t\tprint('The correct answer is ' + answer)\n\t\t\t\tdisplay_points(points, tokens)\n\t\t\t\tbreak\n\t\t\t# If the user is givin a paragraph that is not fair they can skip it \n\t\t\t# without penalty\n\t\t\telif user_input == 'n':\n\t\t\t\tprint('Fine... ya big baby.')\n\t\t\t\tprint('The answer was ' + '\\'' + answer + '\\'' \n\t\t\t\t\t+ ' by the way... its not that hard.')\n\t\t\t\tdisplay_points(points, tokens)\n\t\t\t\tbreak\n\t\t\t# If the user uses a search engine then they must manually deduct \n\t\t\t# points from their score.\n\t\t\telif user_input.isdigit():\n\t\t\t\tpoints -= int(user_input)\n\t\t\t\tprint(str(user_input) + ' have been added to your score.')\n\t\t\t\tdisplay_points(points, tokens)\n\t\t\t# 'q' will quit the program and break all loops\n\t\t\telif user_input == 'q':\n\t\t\t\texit = False\n\t\t\t\tdisplay_points(points, tokens)\n\t\t\t\tbreak\n\t\t\t# If there is a question with a middle initial or something small, \n\t\t\t# it would be too easy to guess. \n\t\t\t# This will prohibit that from happening.\n\t\t\t# answers must be greater then 2 characters in length.\n\t\t\telif len(user_input) <= 2:\n\t\t\t\tprint('you have to guess a longer word...')\n\t\t\t\tcontinue\n\t\t\t# If the user guess's the question and gets every charecter \n\t\t\t# correct then they get 10 points back and they get a token.\n\t\t\telif user_input == answer.lower():\n\t\t\t\tpoints += 10\n\t\t\t\ttokens += 1\n\t\t\t\tprint('You got it correct!')\n\t\t\t\tdisplay_points(points, tokens)\n\t\t\t\tbreak\n\t\t\t# If the user can guess just one word in the answer then they will \n\t\t\t# be given a point and a token\n\t\t\telif user_input in answer_list:\n\t\t\t\tpoints -= 1\n\t\t\t\ttokens += 1\n\t\t\t\tprint(\"Alright close enough, I'll give it to you...\")\n\t\t\t\tprint('The actual answer is ' + answer)\n\t\t\t\tdisplay_points(points, tokens)\n\t\t\t\tbreak\n\t\t\t# If the user guesses the answer wrong then \n\t\t\t# they get deducted 2 points.\n\t\t\telse:\n\t\t\t\tpoints -= 2\n\t\t\t\tprint('Wrong!!')\n\t\t\t\tdisplay_points(points, tokens)\n\t\t\t\tcontinue\n\telse:\n\t\tprint('Searching...')\n\t\tcontinue\n\n\n","sub_path":"wiki-guess.py","file_name":"wiki-guess.py","file_ext":"py","file_size_in_byte":3420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"293294723","text":"from spectrum import *\n\n# possible peaks (breit_wigner == fano)\n# implemented are: breit_wigner, lorentzian, gaussian, voigt\npeaks = ['gaussian']\n\n# select folder you want to analyze and initialize everything\n# it doesn't matter if there is one or more files in the folder\nspec = spectrum('POWER')\n\n# Select the interesting region in the spectrum,\n# by clicking on the plot\nspec.SelectSpectrum()\n\n# find all Muons and remove them\nspec.DetectAllMuons()\nspec.RemoveAllMuons()\n\n\n# Function opens a window with the data,\n# you can select the regions that do not belong to\n# the third degree polynominal background signal\n# by clicking in the plot\nspec.SelectBaseline()\n\n# fit the baselines\nspec.FitAllBaselines()\n\n# Function that opens a Window with the data,\n# you can choose initial values for the peaks by clicking on the plot.\n# You have to choose peaks for all spectra to get the proper starting\n# values. -> Improvement needed\nspec.SelectAllPeaks(peaks)\n\n# Fit all spectra with initial values provided by SelectBaseline()\n# and SelectAllPeaks()\n# if you need to see the fit results set report to True,\n# otherwise set it to false\nspec.FitAllSpectra(peaks, report=False)\n\n# Save the results of the fit in txt-files\nspec.SaveAllFitParams(peaks)\n","sub_path":"PL/analysis/analyze.py","file_name":"analyze.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"45518007","text":"import os\nimport re\n\nimport requests\nimport time\nfrom const.ks_const import *\n\n\ndef live_state_explorer(live_address):\n response = requests.get(live_address, stream=True)\n return response.status_code, response\n\n\ndef live_recorder(\n storage_address,\n live_stream_data,\n storage_method='wb',\n chunk_size=1024):\n with open(storage_address, storage_method) as file:\n for chunk in live_stream_data.iter_content(chunk_size):\n file.write(chunk)\n\n\ndef storage_path(live_address):\n path = 'live_show_data/{path}'.format(path=live_address)\n if os.path.exists(path) is False:\n os.makedirs(path)\n return path + '/' + str(int(time.time())) + '.mp4'\n else:\n return path + '/' + str(int(time.time())) + '.mp4'\n\n\nif __name__ == '__main__':\n while True:\n state, response_data = live_state_explorer(rg_sister_live_address)\n if state != 200:\n print('error, status_code = {state}'.format(state=state))\n time.sleep(15)\n else:\n data = re.match(rule, response_data).group()\n live_recorder(storage_path('rg_sister_live_address'), data)\n print('success storage!')\n # a = 'http://xy.pull.yximgs.com/gifshow/O08rSP0tzow.flv?sign=1522218122-8a3383e940028d7fb1ff0070565edde5'\n # z = re.match(r'http://xy.pull.yximgs.com/gifshow/[0-9a-zA-Z]*.flv\\?sign=\\d*-[0-9a-zA-Z]*', a)\n # print(z.group())\n","sub_path":"ks_main.py","file_name":"ks_main.py","file_ext":"py","file_size_in_byte":1437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"462923895","text":"#!/usr/bin/env python3\n#!python\n\n\"\"\"\nA library of common functions shared by the various executables.\n\"\"\"\n\nimport argparse\nimport io\nimport mmap\nimport os\nimport re\nimport shutil\nimport sys\nfrom fractions import Fraction\nfrom functools import partial\n\n\n###########\n# GENERIC #\n###########\n\ndef eprint(*args, **kwargs):\n \"\"\"Prints an error message to stderr.\"\"\"\n print(*args, file=sys.stderr, **kwargs)\n\n\n#################\n# BINARY LOOKUP #\n#################\n\ndef is_binary_in_path(name):\n \"\"\"Returns True if binary found in path.\"\"\"\n return shutil.which(name) is not None\n\ndef exit_if_binary_not_in_path(name):\n \"\"\"Quits if binary not found in path.\"\"\"\n if not is_binary_in_path(name):\n sys.exit(\"error: `{}' not found.\".format(name))\n\ndef is_file_empty(file_path):\n \"\"\"Check if file is empty by confirming if its size is 0 bytes\"\"\"\n return os.path.exists(file_path) and os.stat(file_path).st_size == 0\n\n\n###########################\n# ARGPARSE HELP FUNCTIONS #\n###########################\n\ndef check_file_ext(extension=None):\n \"\"\"Checks that the argument extension matches the given extension.\"\"\"\n class Act(argparse.Action): # pylint: disable=too-few-public-methods\n \"\"\"Act.\"\"\"\n def __call__(self, parser, namespace, file, option_string=None):\n \"\"\"Check that the argument extension matches the given extension\"\"\"\n ext = os.path.splitext(file.name)[1][1:]\n if extension and ext != extension:\n option_string = '({})'.format(option_string) if option_string else ''\n parser.error(\"file doesn't end with `{}' {}\".format(extension, option_string))\n else:\n setattr(namespace, self.dest, file.name)\n return Act\n\ndef check_finite_precision():\n \"\"\"Checks that the argument finite precision matches the given restriction.\"\"\"\n class Act(argparse.Action): # pylint: disable=too-few-public-methods\n \"\"\"Act.\"\"\"\n def __call__(self, parser, namespace, value, option_string=None):\n \"\"\"Check that the argument finite precision matches the given restriction.\"\"\"\n if value < 2:\n option_string = '({})'.format(option_string) if option_string else ''\n parser.error(\"minimum finite precision is 2 {}\".format(option_string))\n else:\n setattr(namespace, self.dest, value)\n return Act\n\n\n#############################\n# FLATZINC MODEL INSPECTION #\n#############################\n\ndef is_optimization_problem(fzn_file):\n \"\"\"Checks whether the FlatZinc problem contains an optimization goal.\"\"\"\n with io.open(fzn_file, 'r', newline=None) as fd_fzn:\n with mmap.mmap(fd_fzn.fileno(), 0, access=mmap.ACCESS_READ) as fd_mmap:\n return re.search(b\"solve .*satisfy;\", fd_mmap) is None\n\n\n#############################\n# SMTLIB FORMULA INSPECTION #\n#############################\n\ndef match_check_sat(bline):\n \"\"\"Matches (check-sat) in the given argument.\"\"\"\n regex = re.compile(br\"^\\(check-sat\\)\\r?$\")\n return re.match(regex, bline)\n\ndef match_objective(bline):\n \"\"\"Matches an optimization goal declaration\n in the given argument.\"\"\"\n regex = re.compile(br\"^\\((minimize|maximize) ([^:]*?) ?(:signed)?\\)\\r?$\")\n match = re.match(regex, bline)\n if match:\n obj = argparse.Namespace()\n obj.minimize = match[1] == b'minimize'\n obj.term = match[2].decode(\"utf-8\")\n obj.bv_width = 0\n match = obj\n return match\n\ndef replace_sbv_to_int(config, bline):\n \"\"\"Matches (sbv_to_int ) in the\n given argument and replaces with a\n SMT-LIB compatible encoding\"\"\"\n assert config.bv_enc\n\n regex_sbv = re.compile(br\"\\(sbv_to_int ([\\w\\_\\-.]*?)\\)\")\n\n while True:\n\n match = re.search(regex_sbv, bline)\n if not match:\n break\n\n bv_var = match.group(1)\n bv_width = extract_bv_var_width(config, bv_var)\n\n var = bv_var.decode(\"utf-8\")\n msb = bv_width - 1\n dsp = 2 ** bv_width\n expr = (f\"(ite (= ((_ extract {msb} {msb}) {var}) #b0) \"\n f\" (bv2nat {var}) \"\n f\" (- (bv2nat {var}) {dsp}))\")\n\n bline = bline.replace(b\"(sbv_to_int %b)\" % bv_var,\n expr.encode(\"utf-8\"))\n\n return bline\n\n\ndef extract_bv_var_width(config, bv_var):\n \"\"\"Extracts and returns the width of a BitVec variable\n `bv_var` from the SMT-LIB formula in `config.smt2`\"\"\"\n assert config.bv_enc\n assert not is_file_empty(config.smt2)\n\n width = -1\n with io.open(config.smt2, 'rt', newline=None) as in_f:\n with mmap.mmap(in_f.fileno(), 0, access=mmap.ACCESS_READ) as formula:\n\n regex_decl = re.compile((br\"\\((?:define|declare)-fun +%b +\"\n br\"\\(\\) \\(_ BitVec ([0-9]+)\\)\") % bv_var)\n\n match = re.search(regex_decl, formula)\n if match:\n width = int(match.group(1))\n else:\n raise Exception((\"error: failed to determine \"\n \"BitVec width of `{}`\").format(bv_var.decode(\"utf-8\")))\n\n return width\n\n\n###################\n# SMT-LIB FORMULA #\n###################\n\ndef get_smtlib_header_lines(config, solver):\n \"\"\"Yields the header for the SMT-LIB file.\"\"\"\n yield \";;\\n\"\n yield \";; fzn-optimathsat configuration:\\n\"\n yield \";; --int-enc={}\\n\".format(config.int_enc)\n yield \";; --bv-enc={}\\n\".format(config.bv_enc)\n yield \";; --cardinality-networks={}\\n\".format(config.cardinality_networks)\n yield \";; target solver: {}\\n\".format(solver)\n yield \";;\\n\"\n\n#############################\n# SMT-LIB OUTPUT CONVERSION #\n#############################\n\ndef smtlib_to_python(value):\n \"\"\"Converts a constant SMT-LIB value to\n a Python type.\"\"\"\n funcs = [smtlib_bool_to_python_bool,\n smtlib_int_to_python_int,\n smtlib_real_to_python_fraction]\n ret = None\n counter = 0\n for func in funcs:\n conv = func(value)\n if conv is not None:\n ret = conv\n break\n counter += 1\n if ret is None:\n ret = value\n return ret\n\ndef smtlib_to_python_type(stype, value):\n \"\"\"Converts a constant SMT-LIB value to\n a Python type.\"\"\"\n switch = {\n \"Bool\" : smtlib_bool_to_python_bool,\n \"Int\" : smtlib_int_to_python_int,\n \"Real\" : smtlib_real_to_python_fraction,\n \"BitVec\" : smtlib_bv_to_python_int,\n }\n ret = switch[stype](value)\n\n if ret is None:\n eprint(\"error: unable to convert `{}` of type `{}`.\".format(value, stype))\n raise Exception(\"error: smtlib_to_python_type. please report this exception.\")\n\n return ret\n\ndef smtlib_bool_to_python_bool(value):\n \"\"\"Converts a constant SMT-LIB Bool value\n to bool.\"\"\"\n ret = None\n if value in (\"true\", \"false\"):\n ret = (value == \"true\")\n return ret\n\ndef smtlib_int_to_python_int(value):\n \"\"\"Converts a constant SMT-LIB Int value to int.\"\"\"\n regex_min = re.compile(r\"\\( ?- (.*) ?\\)\")\n ret = None\n try:\n match = re.match(regex_min, value)\n if match:\n ret = - int(match.group(1))\n else:\n ret = int(value)\n except ValueError:\n pass\n return ret\n\ndef smtlib_real_to_python_fraction(value):\n \"\"\"Converts a constant SMT-LIB Real value\n to Fraction.\"\"\"\n ret = None\n\n regex_frac = re.compile((r\"(?:\\(- )?\\( ?/ ([^\\.]+)(?:\\.0)? \"\n r\"([^\\.]+)(?:\\.0)? ?\\)(?:\\)?)|([^\\(]*)/(.*)\"))\n regex_min = re.compile(r\"\\( ?- (.*) ?\\)\")\n\n match = re.match(regex_frac, value)\n if match:\n num, den = filter(None, match.groups())\n\n match = re.match(regex_min, num)\n if match: # barcelogic\n num = - int(match.group(1))\n elif re.match(regex_min, value): # z3\n num = - int(num)\n\n ret = Fraction(int(num), int(den))\n else:\n try:\n ret = Fraction(value)\n except ValueError:\n pass\n\n return ret\n\ndef smtlib_bv_to_python_int(value):\n \"\"\"Converts a constant SMT-LIB BitVec value to int.\"\"\"\n ret = None\n regex = re.compile(r\"\\(_ bv([0-9]+) ([0-9]+)\\)\")\n match = re.match(regex, value)\n if match:\n num, bits = map(int, match.groups())\n if num >= (2 ** (bits - 1)):\n num -= (2 ** bits)\n ret = num\n return ret\n\n##################\n# MODEL PRINTING #\n##################\n\nUNSAT = -1\nUNKNOWN = 0\nSAT = 1\nOPTIMAL = 2\n\ndef print_search_status(config, status, models, oskeleton, is_opt_problem):\n \"\"\"Prints the search status in a format\n compatible with FlatZinc.\"\"\"\n switch = {\n UNSAT : \"=====UNSATISFIABLE=====\",\n UNKNOWN : \"=====UNKNOWN=====\",\n SAT : \"----------\",\n OPTIMAL : \"==========\",\n }\n if status in [UNSAT, UNKNOWN]:\n print(switch[status])\n else:\n # assign value to eliminated variables\n autocomplete = {}\n if models:\n autocomplete = extract_model_autocomplete(config, models[0], oskeleton)\n\n for model in models:\n model = {**model, **autocomplete}\n print_model(config, model, oskeleton)\n print(switch[status])\n if is_opt_problem:\n print(switch[OPTIMAL])\n\n if not models:\n print(switch[status])\n if is_opt_problem:\n print(switch[OPTIMAL])\n\ndef print_model(config, model, oskeleton):\n \"\"\"Prints a model in FlatZic format.\"\"\"\n for oinfo in oskeleton:\n mvalue = model_value(model, oinfo.term)\n svalue = model_value_to_str(config, mvalue)\n print(oinfo.str(svalue))\n\ndef model_value_to_str(config, term): # pylint: disable=R0912\n \"\"\"Returns the string representation of a model value.\"\"\"\n ret = None\n if isinstance(term, bool):\n ret = \"true\" if term else \"false\"\n elif isinstance(term, int):\n ret = str(term)\n elif isinstance(term, Fraction):\n if config.infinite_precision:\n if term.denominator != 1:\n ret = \"{}/{}\".format(term.numerator, term.denominator)\n else:\n ret = str(term.numerator)\n else:\n ret = config.float_fmt % term\n elif isinstance(term, set):\n if term:\n ret = str(term) # can only contain int\n else:\n ret = \"{}\"\n elif isinstance(term, list):\n ret = [] # may contain bool/float\n for sub_term in term:\n ret.append(model_value_to_str(config, sub_term))\n # throw away quotes\n ret = \"[{}]\".format(', '.join(ret))\n\n if ret is None:\n raise Exception(\"error: model_value_to_str; please report this exception.\")\n\n return ret\n\ndef model_value(model, term):\n \"\"\"Returns the model value of term.\"\"\"\n ret = None\n if isinstance(term, (bool, int)):\n ret = term\n elif isinstance(term, Fraction):\n ret = term\n elif isinstance(term, str):\n mvalue = model.get(term, None)\n ret = mvalue\n elif isinstance(term, set):\n ret = set()\n for sub_term in term:\n val = model_value(model, sub_term)\n\n if isinstance(val, bool):\n if val:\n val = int(sub_term[sub_term.rindex('.')+1:])\n ret.add(val)\n elif isinstance(val, int):\n ret.add(val)\n else:\n raise Exception(\"error: model_value; please report this exception.\")\n\n elif isinstance(term, list):\n ret = []\n for sub_term in term:\n val = model_value(model, sub_term)\n ret.append(val)\n\n if ret is None:\n raise Exception(\"error: model_value; please report this exception.\")\n\n return ret\n\n\n#########################\n# MODEL AUTO-COMPLETION #\n#########################\n\ndef extract_model_autocomplete(config, model, oskeleton): # pylint: disable=R0914,R1721\n \"\"\"Returns a dictionary assigning a value to\n every variable required by the solution skeleton\n that is not assigned in the model.\"\"\"\n autocomplete = {}\n\n # 1. extract required SMT-LIB variables from skeleton\n var2decl = {}\n for entry in oskeleton:\n n_vars = -1\n for n_vars, var in enumerate(extract_variables(entry.term)):\n if var not in var2decl:\n var2decl[var] = set()\n var2decl[var].add(entry.decl)\n if n_vars < 0:\n autocomplete[entry.decl] = entry.term\n\n # 2. find variables without a model value\n orphans = set(var2decl.keys()).difference(set(model.keys()))\n\n # 3. assign a default value\n if orphans and not is_file_empty(config.model):\n\n cache = {}\n\n with io.open(config.model, 'rt', newline=None) as in_f:\n with mmap.mmap(in_f.fileno(), 0, access=mmap.ACCESS_READ) as flatzinc:\n\n for orphan in orphans:\n # search for a match in the cache first\n for decl in var2decl[orphan]:\n if decl in cache:\n autocomplete[orphan] = cache[decl]\n break\n else:\n # inspect flatzinc file\n for decl in var2decl[orphan]:\n regex = re.compile((rb'(?:array +\\[.*\\] of +)?(?:var)? *'\n rb'(set +of)? *(bool|int|float|.*)?'\n rb' *: *%b *(?:::|=|;)')\n % decl.encode(\"utf-8\"))\n\n match = re.search(regex, flatzinc)\n if match:\n value = False if match.group(1) is not None \\\n else autocomplete_value(match.group(2))\n autocomplete[orphan] = value\n cache[decl] = value\n break\n\n return autocomplete\n\ndef autocomplete_value(match):\n \"\"\"Returns the default value for the given argument.\n It expects either b'bool', b'int' or b'float'.\"\"\"\n ret = 0\n if match == b\"bool\":\n ret = False\n return ret\n\ndef extract_variables(term):\n \"\"\"Yields all variables contained in term.\"\"\"\n if isinstance(term, str):\n yield term\n elif isinstance(term, (set, list)):\n for sub_term in term:\n yield from extract_variables(sub_term)\n\n\n#####################\n# SOLUTION SKELETON #\n#####################\n\ndef extract_solution_skeleton(ovars_file): # pylint: disable=R0914\n \"\"\"Extracts the required solution skeleton,\n and also the mapping between FlatZinc and\n SMT-LIB variables.\"\"\"\n assert not is_file_empty(ovars_file)\n ret = []\n\n regex_bsc = re.compile(r\"% (.*) = (.*);\")\n regex_arr = re.compile(r\"array(.*)d\\((.*) (\\[.*\\])\\)\")\n regex_raw = re.compile(r\"\\{.+?\\}|[^, \\[\\]]+\")\n\n with io.open(ovars_file, 'rt', newline=None) as in_f:\n with mmap.mmap(in_f.fileno(), 0, access=mmap.ACCESS_READ) as skeleton:\n\n # skip first line\n skeleton.readline()\n\n for line in iter(skeleton.readline, b\"\"):\n line = line.decode(\"utf-8\")\n\n out = argparse.Namespace()\n\n # extract 'var = expr'\n out.decl, expr = re.match(regex_bsc, line).groups()\n\n # extract array(..., [])\n match = re.match(regex_arr, expr)\n if match:\n dim, decl, raw_arr = match.groups()\n out.str = partial(\"{0} = array{1}d({2} {3});\".format,\n out.decl, dim, decl)\n out.term = []\n\n terms = re.findall(regex_raw, raw_arr)\n for term in terms:\n out.term.append(skeleton_term_to_python(term))\n\n else:\n out.str = partial(\"{0} = {1};\".format, out.decl)\n out.term = skeleton_term_to_python(expr)\n\n ret.append(out)\n\n return ret\n\ndef skeleton_term_to_python(term):\n \"\"\"Converts a skeleton term/value to a Python type.\"\"\"\n regex_set = re.compile(r\"\\{.*\\}\")\n regex_ext = re.compile(r\"[\\w\\d\\.\\:\\-]+\")\n\n ret = None\n if re.match(regex_set, term):\n ret = set()\n for match in re.findall(regex_ext, term):\n val = smtlib_to_python(match)\n ret.add(val)\n else:\n ret = smtlib_to_python(term)\n return ret\n","sub_path":"bin/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":16577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"375334639","text":"import numpy as np\nimport collections\nfrom math import gcd\n\n'''\nThis file contains boolean functions for determining properties such as \nirreducibility and aperiodicity.\n'''\n\ndef markov_edges(M):\n '''The graph of states together with edges connecting states with\n nonzero probability between them is used in the definition of\n irreducibility and aperiodicity. This helper funcion returns\n a dictionary of edges and the size of the matrix M.'''\n \n # Note that numpy.nonzero works with both numpy and scipy sparse arrays.\n\n try:\n row_indices, col_indices = np.nonzero(M)\n except TypeError:\n # Here I need to see if nonzero accepts other matrix formats\n return 'Error: Input should be a numpy or scipy matrix.'\n\n edges = collections.defaultdict(list)\n\n for i in range(len(row_indices)):\n edges[row_indices[i]].append(col_indices[i])\n\n rows,cols = M.shape # Works for numpy and scipy sparse\n if rows != cols:\n return 'Error: Input matrix should be square'\n\n return edges, rows\n\ndef is_irreducible(M):\n '''Determine whether a Markov chain is irreducible.'''\n\n edges, rows = markov_edges(M)\n\n # To check if the graph is connected, we use a DFS implemented with a stack\n \n for i in range(rows):\n S = collections.deque([i])\n visited = []\n\n while S:\n v = S.pop()\n for w in edges[v]:\n if w not in visited:\n visited.append(w)\n S.append(w)\n \n if len(visited) != rows:\n return False\n\n return True\n\n'''This algorithm for testing aperiodicity is due to Jarvis and Shier.'''\n\ndef is_aperiodic(M):\n '''Determine whether the Markov Chain is aperiodic.'''\n \n edges, rows = markov_edges(M)\n \n indices = list(range(rows))\n\n while indices:\n root = min(indices)\n S = collections.deque([root])\n levels = {root:0}\n iterative_gcd = 0 # keep updating the gcd with each cycle we hit\n while S:\n v = S.popleft()\n for w in edges[v]:\n if w in levels:\n # When w has been marked from the same level\n # levels[v] - levels[w] + 1 == 0, and gcd(0,x) = x.\n # Thus, irrelevant cross edges change nothing.\n # All other edges potentially alter the period.\n iterative_gcd = gcd(iterative_gcd, levels[v] - levels[w] + 1)\n else:\n levels[w] = levels[v] + 1\n S.append(w)\n\n return iterative_gcd == 1\n\ndef is_reversible(M,v,threshold):\n '''Given Markov chain M and probability distribution v, determine\n whether the distribution is reversible for M. Since it's floating\n point arithmetic, we use a threshold for equality.'''\n\n edges, rows = markov_edges(M)\n\n if len(v) != rows:\n return 'Error: Distribution length must be the same as the number of states of the Markov chain.'\n\n for i in edges.keys():\n for j in edges[i]:\n if abs(v[i] * M[i][j] - v[j] * M[j][i]) > threshold:\n return False\n\n return True\n","sub_path":"properties.py","file_name":"properties.py","file_ext":"py","file_size_in_byte":3186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"37013093","text":"import assignment4 as models\nimport numpy as np\nimport sys\n\nif(sys.version_info[0] < 3):\n\traise Exception(\"This assignment must be completed using Python 3\")\n\n#==========================================================Data==========================================================\n# Number of Instances:\t\n# 653\n# Number of Attributes:\n# 35 numeric, predictive attributes and the class\n\n# Attribute Information:\n\n# We have 35 variables for 653 counties, including demographics, covid info, previous election \n# results, work related information.\n# percentage16_Donald_Trump\t\n# percentage16_Hillary_Clinton\t\n# total_votes20\t\n# latitude\t\n# longitude\t\n# Covid Cases/Pop\t\n# Covid Deads/Cases\t\n# TotalPop\t\n# Women/Men\n# Hispanic\n# White\t\n# Black\t\n# Native\t\n# Asian\t\n# Pacific\t\n# VotingAgeCitizen\t\n# Income\t\n# ChildPoverty\t\n# Professional\t\n# Service\t\n# Office\t\n# Construction\t\n# Production\t\n# Drive\t\n# Carpool\t\n# Transit\t\n# Walk\t\n# OtherTransp\t\n# WorkAtHome\t\n# MeanCommute\t\n# Employed\t\n# PrivateWork\t\n# SelfEmployed\t\n# FamilyWork\t\n# Unemployment\n\n\n# Class Distribution:\n# 328 - Candidate A (1), 325 - Candidate B (0)\n#========================================================================================================================\nnp.random.seed(42)\n\ndef train_test_split(X, y, test_ratio):\n\ttr = int(y.size * test_ratio)\n\treturn X[:tr], X[tr:], y[:tr], y[tr:]\n\ndef load_data(path):\n\tdata = np.genfromtxt(path, delimiter=',', dtype=float)\n\treturn data[:,:-1], data[:,-1].astype(int)\n\nX, y = load_data(\"county_statistics.csv\")\nX_train, X_test, y_train, y_test = train_test_split(X, y, 0.75)\n\n#Initialization\n# KNN\nk = 3\nknn = models.KNN(k)\n\n# Perceptron\nlr = .001\nw = np.random.normal(0, .1, size=X_train.shape[1])\nb = np.random.normal(0, .1, size=1)\nperceptron = models.Perceptron(w, b, lr)\n\n# MLP\nlr = .0001\nw1 = np.random.normal(0, .1, size=(X_train.shape[1], 10))\nw2 = np.random.normal(0, .1, size=(10,1))\nb1 = np.random.normal(0, .1, size=(1,10))\nb2 = np.random.normal(0, .1, size=(1,1))\nmlp = models.MLP(w1, b1, w2, b2, lr)\n\n#Train\nknn.train(X_train, y_train)\nsteps = 100 * y_train.size\nprint('Training Perceptron')\n#perceptron.train(X_train, y_train, steps)\nprint('Training MLP')\nmlp.train(X_train, y_train, steps)\n\n#Check weights (For grading)\n#print('perceptron w = ', perceptron.w)\n#print('perceptron b = ', perceptron.b)\n# mlp.w1\n# mlp.b1\n# mlp.w2\n# mlp.b2\n\n#Evaluate\ndef evaluate(solutions, real):\n\tif(solutions.shape != real.shape):\n\t\tprint(real.shape)\n\t\tprint(solutions.shape)\n\t\traise ValueError(\"Output is wrong shape.\")\n\tpredictions = np.array(solutions)\n\tlabels = np.array(real)\n\treturn (predictions == labels).sum() / float(labels.size)\n\nknnsolutions = knn.predict(X_test)\nprint(\"evaluate KNN:\", evaluate(knnsolutions, y_test))\n#psolutions = perceptron.predict(X_test)\n#print(\"evaluate perceptron:\", evaluate(psolutions, y_test))\nmlpsolutions = mlp.predict(X_test)\nprint(\"evaluate MLP:\", evaluate(mlpsolutions, y_test))","sub_path":"supervised/run_supervised.py","file_name":"run_supervised.py","file_ext":"py","file_size_in_byte":2937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"588580230","text":"#This program lets the user encrypt and decrypt sentances using the Caesar ciper\n#The ceasar cipher is where depending on the key the letters of a sentance are changed accordingly\n\n#The alphabet\nalphabet = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n#Choosing whether to encrypt or decrypt\nencrypt = raw_input(\"Encrypting or decrypting (E or D): \")\n#to define the newMessage\nnewMessage = \"\"\n#to encrypt\nif (encrypt == \"E\" or encrypt == \"e\" or encrypt == \"encrypt\" or encrypt == \"Encrypt\"):\n encrypting = True\n key = raw_input(\"Please enter a number to be used as the key: \" )\n#if someone inputs a letter, not a number\n for character in key:\n if character in alphabet:\n print(\"Error! Not a number. Exiting... \")\n#putting in the message to be decoded\n else:\n#changes the key to an integer\n key = int(key)\n#tells the user to put in the message\n message = raw_input(\"Please enter the message to be encrypted (don\\'t use commas): \")\n#changing the letters to their encrypted positions\n for character in message:\n if character in alphabet:\n position = alphabet.find(character)\n#finds the new position by adding the key and the position together, but if it is above 26, it goes back to 1\n newPosition = (position+key) % 26\n newCharacter = alphabet[newPosition]\n newMessage += newCharacter\n#for characters that aren't in the alphabet (! ? . ,)\n else:\n newMessage += character\n#shows the encrypted message\n print(\"The new encrypted message is: \" + newMessage)\n#to decrypt\nelif (encrypt == \"D\" or encrypt == \"d\" or encrypt == \"decrypt\" or encrypt == \"Decrypt\"):\n encrypting = False\n key = raw_input(\"Please enter the key: \" )\n#if someone inputs a letter, not a number\n for character in key:\n if character in alphabet:\n print(\"Error! Not a number. Exiting... \")\n else:\n key = int(key)\n#this is negative so it changes it back, but it is easier to just put in a positive number and then have the computer change it\n negativekey = key * -1\n if (negativekey < 0):\n#tells the user to put in the message\n message = raw_input(\"Please enter the encrypted message: \")\n#changing the encrypted letters back to their original positions\n for character in message:\n if character in alphabet:\n position = alphabet.find(character)\n#finds the new position by adding the key and the position together, but if it is above 26, it goes back to 1\n newPosition = (position+negativekey) % 26\n newCharacter = alphabet[newPosition]\n newMessage += newCharacter\n#for characters that aren't in the alphabet (! ? . ,)\n else:\n newMessage += character\n#shows the decrypted message\n print(\"The unencrypted message is: \" + newMessage)\nelse:\n print( \"Must be E or D, cannot continue\" )\n","sub_path":"CaesarCipherEncryptionE.py","file_name":"CaesarCipherEncryptionE.py","file_ext":"py","file_size_in_byte":3121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"555175547","text":"import multiprocessing\nimport time\n\n\ndef fun1(num):\n print(f'process:{num} test sucess')\n\nprocesses = []\nfor i in range(1, 5):\n p = multiprocessing.Process(target=fun1, args=[i])\n p.start()\n processes.append(p)\nfor p in processes:\n p.join()\nprint(f'pro')\n \n\n\n\n","sub_path":"mutiprocess/mutiprocess-test.py","file_name":"mutiprocess-test.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"355744011","text":"##############################################################################\n#\n# Copyright (c) 2004-2008 Zope Foundation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\n\"\"\"Shuffle tests discovered before executing them.\n\n$Id$\n\"\"\"\n\nimport time\nimport random\nimport unittest\nimport zope.testrunner.feature\n\n\nclass Shuffle(zope.testrunner.feature.Feature):\n \"\"\"Take the tests found so far and shuffle them.\"\"\"\n\n def __init__(self, runner):\n super(Shuffle, self).__init__(runner)\n self.active = runner.options.shuffle\n self.seed = runner.options.shuffle_seed\n if self.seed is None:\n # We can't rely on the random modules seed initialization because\n # we can't introspect the seed later for reporting. This is a\n # simple emulation of what random.Random.seed does anyway.\n self.seed = long(time.time() * 256) # use fractional seconds\n\n def global_setup(self):\n rng = random.Random(self.seed)\n for layer, suite in list(self.runner.tests_by_layer_name.items()):\n # Test suites cannot be modified through a public API. We thus\n # take a mutable copy of the list of tests of that suite, shuffle\n # that and replace the test suite instance with a new one of the\n # same class.\n tests = list(suite)\n rng.shuffle(tests)\n self.runner.tests_by_layer_name[layer] = suite.__class__(tests)\n\n def report(self):\n msg = \"Tests were shuffled using seed number %d.\" % self.seed\n self.runner.options.output.info(msg)\n","sub_path":"zope.testrunner/tags/4.0.0b1/src/zope/testrunner/shuffle.py","file_name":"shuffle.py","file_ext":"py","file_size_in_byte":2058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"502220379","text":"\"\"\"Services implemented by the AWS provider.\"\"\"\nimport string\nimport time\n\nfrom boto.ec2.blockdevicemapping import BlockDeviceMapping\nfrom boto.ec2.blockdevicemapping import BlockDeviceType\nfrom boto.exception import EC2ResponseError, S3ResponseError\n\nfrom cloudbridge.cloud.base.resources import ClientPagedResultList\nfrom cloudbridge.cloud.base.resources import ServerPagedResultList\nfrom cloudbridge.cloud.base.services import BaseBlockStoreService\nfrom cloudbridge.cloud.base.services import BaseComputeService\nfrom cloudbridge.cloud.base.services import BaseGatewayService\nfrom cloudbridge.cloud.base.services import BaseImageService\nfrom cloudbridge.cloud.base.services import BaseInstanceService\nfrom cloudbridge.cloud.base.services import BaseInstanceTypesService\nfrom cloudbridge.cloud.base.services import BaseKeyPairService\nfrom cloudbridge.cloud.base.services import BaseNetworkService\nfrom cloudbridge.cloud.base.services import BaseNetworkingService\nfrom cloudbridge.cloud.base.services import BaseObjectStoreService\nfrom cloudbridge.cloud.base.services import BaseRegionService\nfrom cloudbridge.cloud.base.services import BaseRouterService\nfrom cloudbridge.cloud.base.services import BaseSecurityGroupService\nfrom cloudbridge.cloud.base.services import BaseSecurityService\nfrom cloudbridge.cloud.base.services import BaseSnapshotService\nfrom cloudbridge.cloud.base.services import BaseSubnetService\nfrom cloudbridge.cloud.base.services import BaseVolumeService\nfrom cloudbridge.cloud.interfaces.exceptions \\\n import InvalidConfigurationException\nfrom cloudbridge.cloud.interfaces.resources import InstanceState\nfrom cloudbridge.cloud.interfaces.resources import InstanceType\nfrom cloudbridge.cloud.interfaces.resources import KeyPair\nfrom cloudbridge.cloud.interfaces.resources import MachineImage\nfrom cloudbridge.cloud.interfaces.resources import NetworkState\nfrom cloudbridge.cloud.interfaces.resources import PlacementZone\nfrom cloudbridge.cloud.interfaces.resources import SecurityGroup\nfrom cloudbridge.cloud.interfaces.resources import Snapshot\nfrom cloudbridge.cloud.interfaces.resources import SubnetState\nfrom cloudbridge.cloud.interfaces.resources import Volume\n\nimport requests\n\nfrom .resources import AWSBucket\nfrom .resources import AWSFloatingIP\nfrom .resources import AWSInstance\nfrom .resources import AWSInstanceType\nfrom .resources import AWSInternetGateway\nfrom .resources import AWSKeyPair\nfrom .resources import AWSLaunchConfig\nfrom .resources import AWSMachineImage\nfrom .resources import AWSNetwork\nfrom .resources import AWSRegion\nfrom .resources import AWSRouter\nfrom .resources import AWSSecurityGroup\nfrom .resources import AWSSnapshot\nfrom .resources import AWSSubnet\nfrom .resources import AWSVolume\n\n# Uncomment to enable logging by default for this module\n# import cloudbridge as cb\n# cb.set_stream_logger(__name__)\n\n\nclass AWSSecurityService(BaseSecurityService):\n\n def __init__(self, provider):\n super(AWSSecurityService, self).__init__(provider)\n\n # Initialize provider services\n self._key_pairs = AWSKeyPairService(provider)\n self._security_groups = AWSSecurityGroupService(provider)\n\n @property\n def key_pairs(self):\n \"\"\"\n Provides access to key pairs for this provider.\n\n :rtype: ``object`` of :class:`.KeyPairService`\n :return: a KeyPairService object\n \"\"\"\n return self._key_pairs\n\n @property\n def security_groups(self):\n \"\"\"\n Provides access to security groups for this provider.\n\n :rtype: ``object`` of :class:`.SecurityGroupService`\n :return: a SecurityGroupService object\n \"\"\"\n return self._security_groups\n\n\nclass AWSKeyPairService(BaseKeyPairService):\n\n def __init__(self, provider):\n super(AWSKeyPairService, self).__init__(provider)\n\n def get(self, key_pair_id):\n \"\"\"\n Returns a KeyPair given its ID.\n \"\"\"\n try:\n kps = self.provider.ec2_conn.get_all_key_pairs(\n keynames=[key_pair_id])\n return AWSKeyPair(self.provider, kps[0])\n except EC2ResponseError as ec2e:\n if ec2e.code == 'InvalidKeyPair.NotFound':\n return None\n elif ec2e.code == 'InvalidParameterValue':\n return None\n else:\n raise ec2e\n\n def list(self, limit=None, marker=None):\n \"\"\"\n List all key pairs associated with this account.\n\n :rtype: ``list`` of :class:`.KeyPair`\n :return: list of KeyPair objects\n \"\"\"\n key_pairs = [AWSKeyPair(self.provider, kp)\n for kp in self.provider.ec2_conn.get_all_key_pairs()]\n return ClientPagedResultList(self.provider, key_pairs,\n limit=limit, marker=marker)\n\n def find(self, name, limit=None, marker=None):\n \"\"\"\n Searches for a key pair by a given list of attributes.\n \"\"\"\n try:\n key_pairs = [\n AWSKeyPair(self.provider, kp) for kp in\n self.provider.ec2_conn.get_all_key_pairs(keynames=[name])]\n return ClientPagedResultList(self.provider, key_pairs,\n limit=limit, marker=marker)\n except EC2ResponseError as ec2e:\n if ec2e.code == 'InvalidKeyPair.NotFound':\n return []\n elif ec2e.code == 'InvalidParameterValue':\n return []\n else:\n raise ec2e\n\n def create(self, name):\n \"\"\"\n Create a new key pair or raise an exception if one already exists.\n\n :type name: str\n :param name: The name of the key pair to be created.\n\n :rtype: ``object`` of :class:`.KeyPair`\n :return: A key pair instance or ``None`` if one was not be created.\n \"\"\"\n AWSKeyPair.assert_valid_resource_name(name)\n\n kp = self.provider.ec2_conn.create_key_pair(name)\n if kp:\n return AWSKeyPair(self.provider, kp)\n return None\n\n\nclass AWSSecurityGroupService(BaseSecurityGroupService):\n\n def __init__(self, provider):\n super(AWSSecurityGroupService, self).__init__(provider)\n\n def get(self, sg_id):\n \"\"\"\n Returns a SecurityGroup given its id.\n \"\"\"\n try:\n sgs = self.provider.ec2_conn.get_all_security_groups(\n group_ids=[sg_id])\n return AWSSecurityGroup(self.provider, sgs[0]) if sgs else None\n except EC2ResponseError as ec2e:\n if ec2e.code == 'InvalidGroup.NotFound':\n return None\n elif ec2e.code == 'InvalidGroupId.Malformed':\n return None\n else:\n raise ec2e\n\n def list(self, limit=None, marker=None):\n \"\"\"\n List all security groups associated with this account.\n\n :rtype: ``list`` of :class:`.SecurityGroup`\n :return: list of SecurityGroup objects\n \"\"\"\n sgs = [AWSSecurityGroup(self.provider, sg)\n for sg in self.provider.ec2_conn.get_all_security_groups()]\n\n return ClientPagedResultList(self.provider, sgs,\n limit=limit, marker=marker)\n\n def create(self, name, description, network_id):\n \"\"\"\n Create a new SecurityGroup.\n\n :type name: str\n :param name: The name of the new security group.\n\n :type description: str\n :param description: The description of the new security group.\n\n :type network_id: ``str``\n :param network_id: The ID of the VPC under which to create the security\n group.\n\n :rtype: ``object`` of :class:`.SecurityGroup`\n :return: A SecurityGroup instance or ``None`` if one was not created.\n \"\"\"\n AWSSecurityGroup.assert_valid_resource_name(name)\n\n sg = self.provider.ec2_conn.create_security_group(name, description,\n network_id)\n if sg:\n return AWSSecurityGroup(self.provider, sg)\n return None\n\n def find(self, name, limit=None, marker=None):\n \"\"\"\n Get all security groups associated with your account.\n \"\"\"\n flters = {'group-name': name}\n ec2_sgs = self.provider.ec2_conn.get_all_security_groups(\n filters=flters)\n sgs = [AWSSecurityGroup(self.provider, sg) for sg in ec2_sgs]\n return ClientPagedResultList(self.provider, sgs,\n limit=limit, marker=marker)\n\n def delete(self, group_id):\n \"\"\"\n Delete an existing SecurityGroup.\n\n :type group_id: str\n :param group_id: The security group ID to be deleted.\n\n :rtype: ``bool``\n :return: ``True`` if the security group does not exist, ``False``\n otherwise. Note that this implies that the group may not have\n been deleted by this method but instead has not existed in\n the first place.\n \"\"\"\n sg = self.get(group_id)\n if sg:\n sg.delete()\n return True\n return False\n\n\nclass AWSBlockStoreService(BaseBlockStoreService):\n\n def __init__(self, provider):\n super(AWSBlockStoreService, self).__init__(provider)\n\n # Initialize provider services\n self._volume_svc = AWSVolumeService(self.provider)\n self._snapshot_svc = AWSSnapshotService(self.provider)\n\n @property\n def volumes(self):\n return self._volume_svc\n\n @property\n def snapshots(self):\n return self._snapshot_svc\n\n\nclass AWSVolumeService(BaseVolumeService):\n\n def __init__(self, provider):\n super(AWSVolumeService, self).__init__(provider)\n\n def get(self, volume_id):\n \"\"\"\n Returns a volume given its id.\n \"\"\"\n try:\n vols = self.provider.ec2_conn.get_all_volumes(\n volume_ids=[volume_id])\n return AWSVolume(self.provider, vols[0]) if vols else None\n except EC2ResponseError as ec2e:\n if ec2e.code == 'InvalidVolume.NotFound':\n return None\n elif ec2e.code == 'InvalidParameterValue':\n # Occurs if volume_id does not start with 'vol-...'\n return None\n raise ec2e\n\n def find(self, name, limit=None, marker=None):\n \"\"\"\n Searches for a volume by a given list of attributes.\n \"\"\"\n filtr = {'tag:Name': name}\n aws_vols = self.provider.ec2_conn.get_all_volumes(filters=filtr)\n cb_vols = [AWSVolume(self.provider, vol) for vol in aws_vols]\n return ClientPagedResultList(self.provider, cb_vols,\n limit=limit, marker=marker)\n\n def list(self, limit=None, marker=None):\n \"\"\"\n List all volumes.\n \"\"\"\n aws_vols = self.provider.ec2_conn.get_all_volumes()\n cb_vols = [AWSVolume(self.provider, vol) for vol in aws_vols]\n return ClientPagedResultList(self.provider, cb_vols,\n limit=limit, marker=marker)\n\n def create(self, name, size, zone, snapshot=None, description=None):\n \"\"\"\n Creates a new volume.\n \"\"\"\n AWSVolume.assert_valid_resource_name(name)\n\n zone_id = zone.id if isinstance(zone, PlacementZone) else zone\n snapshot_id = snapshot.id if isinstance(\n snapshot, AWSSnapshot) and snapshot else snapshot\n\n ec2_vol = self.provider.ec2_conn.create_volume(\n size,\n zone_id,\n snapshot=snapshot_id)\n cb_vol = AWSVolume(self.provider, ec2_vol)\n cb_vol.name = name\n if description:\n cb_vol.description = description\n return cb_vol\n\n\nclass AWSSnapshotService(BaseSnapshotService):\n\n def __init__(self, provider):\n super(AWSSnapshotService, self).__init__(provider)\n\n def get(self, snapshot_id):\n \"\"\"\n Returns a snapshot given its id.\n \"\"\"\n try:\n snaps = self.provider.ec2_conn.get_all_snapshots(\n snapshot_ids=[snapshot_id])\n return AWSSnapshot(self.provider, snaps[0]) if snaps else None\n except EC2ResponseError as ec2e:\n if ec2e.code == 'InvalidSnapshot.NotFound':\n return None\n elif ec2e.code == 'InvalidParameterValue':\n # Occurs if snapshot_id does not start with 'snap-...'\n return None\n raise ec2e\n\n def find(self, name, limit=None, marker=None):\n \"\"\"\n Searches for a snapshot by a given list of attributes.\n \"\"\"\n filtr = {'tag-value': name}\n snaps = [AWSSnapshot(self.provider, snap) for snap in\n self.provider.ec2_conn.get_all_snapshots(filters=filtr)]\n return ClientPagedResultList(self.provider, snaps,\n limit=limit, marker=marker)\n\n def list(self, limit=None, marker=None):\n \"\"\"\n List all snapshots.\n \"\"\"\n snaps = [AWSSnapshot(self.provider, snap)\n for snap in self.provider.ec2_conn.get_all_snapshots(\n owner='self')]\n return ClientPagedResultList(self.provider, snaps,\n limit=limit, marker=marker)\n\n def create(self, name, volume, description=None):\n \"\"\"\n Creates a new snapshot of a given volume.\n \"\"\"\n AWSSnapshot.assert_valid_resource_name(name)\n\n volume_id = volume.id if isinstance(volume, AWSVolume) else volume\n\n ec2_snap = self.provider.ec2_conn.create_snapshot(\n volume_id,\n description=description)\n cb_snap = AWSSnapshot(self.provider, ec2_snap)\n cb_snap.name = name\n if description:\n cb_snap.description = description\n return cb_snap\n\n\nclass AWSObjectStoreService(BaseObjectStoreService):\n\n def __init__(self, provider):\n super(AWSObjectStoreService, self).__init__(provider)\n\n def get(self, bucket_id):\n \"\"\"\n Returns a bucket given its ID. Returns ``None`` if the bucket\n does not exist.\n \"\"\"\n try:\n # Make a call to make sure the bucket exists. While this would\n # normally return a Bucket instance, there's an edge case where a\n # 403 response can occur when the bucket exists but the\n # user simply does not have permissions to access it. See below.\n bucket = self.provider.s3_conn.get_bucket(bucket_id)\n return AWSBucket(self.provider, bucket)\n except S3ResponseError as e:\n # If 403, it means the bucket exists, but the user does not have\n # permissions to access the bucket. However, limited operations\n # may be permitted (with a session token for example), so return a\n # Bucket instance to allow further operations.\n # http://stackoverflow.com/questions/32331456/using-boto-upload-file-to-s3-\n # sub-folder-when-i-have-no-permissions-on-listing-fo\n if e.status == 403:\n bucket = self.provider.s3_conn.get_bucket(bucket_id,\n validate=False)\n return AWSBucket(self.provider, bucket)\n # For all other responses, it's assumed that the bucket does not exist.\n return None\n\n def find(self, name, limit=None, marker=None):\n \"\"\"\n Searches for a bucket by a given list of attributes.\n \"\"\"\n buckets = [AWSBucket(self.provider, bucket)\n for bucket in self.provider.s3_conn.get_all_buckets()\n if name in bucket.name]\n return ClientPagedResultList(self.provider, buckets,\n limit=limit, marker=marker)\n\n def list(self, limit=None, marker=None):\n \"\"\"\n List all containers.\n \"\"\"\n buckets = [AWSBucket(self.provider, bucket)\n for bucket in self.provider.s3_conn.get_all_buckets()]\n return ClientPagedResultList(self.provider, buckets,\n limit=limit, marker=marker)\n\n def create(self, name, location=None):\n \"\"\"\n Create a new bucket.\n \"\"\"\n AWSBucket.assert_valid_resource_name(name)\n\n bucket = self.provider.s3_conn.create_bucket(\n name,\n location=location if location else '')\n return AWSBucket(self.provider, bucket)\n\n\nclass AWSImageService(BaseImageService):\n\n def __init__(self, provider):\n super(AWSImageService, self).__init__(provider)\n\n def get(self, image_id):\n \"\"\"\n Returns an Image given its id\n \"\"\"\n try:\n image = self.provider.ec2_conn.get_image(image_id)\n return AWSMachineImage(self.provider, image) if image else None\n except EC2ResponseError as ec2e:\n if ec2e.code == 'InvalidAMIID.NotFound':\n return None\n elif ec2e.code == 'InvalidAMIID.Malformed':\n # Occurs if image_id does not start with 'ami-...'\n return None\n raise ec2e\n\n def find(self, name, limit=None, marker=None):\n \"\"\"\n Searches for an image by a given list of attributes\n \"\"\"\n filters = {'name': name}\n images = [AWSMachineImage(self.provider, image) for image in\n self.provider.ec2_conn.get_all_images(filters=filters)]\n return ClientPagedResultList(self.provider, images,\n limit=limit, marker=marker)\n\n def list(self, limit=None, marker=None):\n \"\"\"\n List all images.\n \"\"\"\n images = [AWSMachineImage(self.provider, image)\n for image in self.provider.ec2_conn.get_all_images()]\n return ClientPagedResultList(self.provider, images,\n limit=limit, marker=marker)\n\n\nclass AWSComputeService(BaseComputeService):\n\n def __init__(self, provider):\n super(AWSComputeService, self).__init__(provider)\n self._instance_type_svc = AWSInstanceTypesService(self.provider)\n self._instance_svc = AWSInstanceService(self.provider)\n self._region_svc = AWSRegionService(self.provider)\n self._images_svc = AWSImageService(self.provider)\n\n @property\n def images(self):\n return self._images_svc\n\n @property\n def instance_types(self):\n return self._instance_type_svc\n\n @property\n def instances(self):\n return self._instance_svc\n\n @property\n def regions(self):\n return self._region_svc\n\n\nclass AWSInstanceService(BaseInstanceService):\n\n def __init__(self, provider):\n super(AWSInstanceService, self).__init__(provider)\n\n def create(self, name, image, instance_type, subnet, zone=None,\n key_pair=None, security_groups=None, user_data=None,\n launch_config=None, **kwargs):\n AWSInstance.assert_valid_resource_name(name)\n\n image_id = image.id if isinstance(image, MachineImage) else image\n instance_size = instance_type.id if \\\n isinstance(instance_type, InstanceType) else instance_type\n subnet = (self.provider.networking.subnets.get(subnet)\n if isinstance(subnet, str) else subnet)\n zone_id = zone.id if isinstance(zone, PlacementZone) else zone\n key_pair_name = key_pair.name if isinstance(\n key_pair,\n KeyPair) else key_pair\n if launch_config:\n bdm = self._process_block_device_mappings(launch_config, zone_id)\n else:\n bdm = None\n\n subnet_id, zone_id, security_group_ids = \\\n self._resolve_launch_options(subnet, zone_id, security_groups)\n\n reservation = self.provider.ec2_conn.run_instances(\n image_id=image_id, instance_type=instance_size,\n min_count=1, max_count=1, placement=zone_id,\n key_name=key_pair_name, security_group_ids=security_group_ids,\n user_data=user_data, block_device_map=bdm, subnet_id=subnet_id)\n instance = None\n if reservation:\n instance = AWSInstance(self.provider, reservation.instances[0])\n instance.wait_for(\n [InstanceState.PENDING, InstanceState.RUNNING],\n terminal_states=[InstanceState.TERMINATED,\n InstanceState.ERROR])\n instance.name = name\n return instance\n\n def _resolve_launch_options(self, subnet=None, zone_id=None,\n security_groups=None):\n \"\"\"\n Work out interdependent launch options.\n\n Some launch options are required and interdependent so make sure\n they conform to the interface contract.\n\n :type subnet: ``Subnet``\n :param subnet: Subnet object within which to launch.\n\n :type zone_id: ``str``\n :param zone_id: ID of the zone where the launch should happen.\n\n :type security_groups: ``list`` of ``id``\n :param zone_id: List of security group IDs.\n\n :rtype: triplet of ``str``\n :return: Subnet ID, zone ID and security group IDs for launch.\n\n :raise ValueError: In case a conflicting combination is found.\n \"\"\"\n if subnet:\n # subnet's zone takes precedence\n zone_id = subnet.zone.id\n if isinstance(security_groups, list) and isinstance(\n security_groups[0], SecurityGroup):\n security_group_ids = [sg.id for sg in security_groups]\n else:\n security_group_ids = security_groups\n return subnet.id, zone_id, security_group_ids\n\n def _process_block_device_mappings(self, launch_config, zone=None):\n \"\"\"\n Processes block device mapping information\n and returns a Boto BlockDeviceMapping object. If new volumes\n are requested (source is None and destination is VOLUME), they will be\n created and the relevant volume ids included in the mapping.\n \"\"\"\n bdm = BlockDeviceMapping()\n # Assign letters from f onwards\n # http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/device_naming.html\n next_letter = iter(list(string.ascii_lowercase[6:]))\n # assign ephemeral devices from 0 onwards\n ephemeral_counter = 0\n for device in launch_config.block_devices:\n bd_type = BlockDeviceType()\n\n if device.is_volume:\n if device.is_root:\n bdm['/dev/sda1'] = bd_type\n else:\n bdm['sd' + next(next_letter)] = bd_type\n\n if isinstance(device.source, Snapshot):\n bd_type.snapshot_id = device.source.id\n elif isinstance(device.source, Volume):\n bd_type.volume_id = device.source.id\n elif isinstance(device.source, MachineImage):\n # Not supported\n pass\n else:\n # source is None, but destination is volume, therefore\n # create a blank volume. If the Zone is None, this\n # could fail since the volume and instance may be created\n # in two different zones.\n if not zone:\n raise InvalidConfigurationException(\n \"A zone must be specified when launching with a\"\n \" new blank volume block device mapping.\")\n new_vol = self.provider.block_store.volumes.create(\n '',\n device.size,\n zone)\n bd_type.volume_id = new_vol.id\n bd_type.delete_on_terminate = device.delete_on_terminate\n if device.size:\n bd_type.size = device.size\n else: # device is ephemeral\n bd_type.ephemeral_name = 'ephemeral%s' % ephemeral_counter\n\n return bdm\n\n def create_launch_config(self):\n return AWSLaunchConfig(self.provider)\n\n def get(self, instance_id):\n \"\"\"\n Returns an instance given its id. Returns None\n if the object does not exist.\n \"\"\"\n try:\n reservation = self.provider.ec2_conn.get_all_reservations(\n instance_ids=[instance_id])\n return (AWSInstance(self.provider, reservation[0].instances[0])\n if reservation else None)\n except EC2ResponseError as ec2e:\n if ec2e.code == 'InvalidInstanceID.NotFound':\n return None\n elif ec2e.code == 'InvalidParameterValue':\n # Occurs if id does not start with 'inst-...'\n return None\n raise ec2e\n\n def find(self, name, limit=None, marker=None):\n \"\"\"\n Searches for an instance by a given list of attributes.\n\n :rtype: ``object`` of :class:`.Instance`\n :return: an Instance object\n \"\"\"\n filtr = {'tag:Name': name}\n reservations = self.provider.ec2_conn.get_all_reservations(\n filters=filtr,\n max_results=limit,\n next_token=marker)\n instances = [AWSInstance(self.provider, inst)\n for res in reservations\n for inst in res.instances]\n return ServerPagedResultList(reservations.is_truncated,\n reservations.next_token,\n False, data=instances)\n\n def list(self, limit=None, marker=None):\n \"\"\"\n List all instances.\n \"\"\"\n reservations = self.provider.ec2_conn.get_all_reservations(\n max_results=limit,\n next_token=marker)\n instances = [AWSInstance(self.provider, inst)\n for res in reservations\n for inst in res.instances]\n return ServerPagedResultList(reservations.is_truncated,\n reservations.next_token,\n False, data=instances)\n\n\nclass AWSInstanceTypesService(BaseInstanceTypesService):\n\n def __init__(self, provider):\n super(AWSInstanceTypesService, self).__init__(provider)\n\n @property\n def instance_data(self):\n \"\"\"\n Fetch info about the available instances.\n\n To update this information, update the file pointed to by the\n ``provider.AWS_INSTANCE_DATA_DEFAULT_URL`` above. The content for this\n file should be obtained from this repo:\n https://github.com/powdahound/ec2instances.info (in particular, this\n file: https://raw.githubusercontent.com/powdahound/ec2instances.info/\n master/www/instances.json).\n\n TODO: Needs a caching function with timeout\n \"\"\"\n r = requests.get(self.provider.config.get(\n \"aws_instance_info_url\",\n self.provider.AWS_INSTANCE_DATA_DEFAULT_URL))\n return r.json()\n\n def list(self, limit=None, marker=None):\n inst_types = [AWSInstanceType(self.provider, inst_type)\n for inst_type in self.instance_data]\n return ClientPagedResultList(self.provider, inst_types,\n limit=limit, marker=marker)\n\n\nclass AWSRegionService(BaseRegionService):\n\n def __init__(self, provider):\n super(AWSRegionService, self).__init__(provider)\n\n def get(self, region_id):\n region = [r for r in self if r.id == region_id]\n if region:\n return region[0]\n else:\n return None\n\n def list(self, limit=None, marker=None):\n regions = [AWSRegion(self.provider, region)\n for region in self.provider.ec2_conn.get_all_regions()]\n return ClientPagedResultList(self.provider, regions,\n limit=limit, marker=marker)\n\n @property\n def current(self):\n return self.get(self._provider.region_name)\n\n\nclass AWSNetworkingService(BaseNetworkingService):\n\n def __init__(self, provider):\n super(AWSNetworkingService, self).__init__(provider)\n self._network_service = AWSNetworkService(self.provider)\n self._subnet_service = AWSSubnetService(self.provider)\n self._router_service = AWSRouterService(self.provider)\n self._gateway_service = AWSGatewayService(self.provider)\n\n @property\n def networks(self):\n return self._network_service\n\n @property\n def subnets(self):\n return self._subnet_service\n\n @property\n def routers(self):\n return self._router_service\n\n @property\n def gateways(self):\n return self._gateway_service\n\n\nclass AWSNetworkService(BaseNetworkService):\n\n def __init__(self, provider):\n super(AWSNetworkService, self).__init__(provider)\n\n def get(self, network_id):\n try:\n network = self.provider.vpc_conn.get_all_vpcs(vpc_ids=[network_id])\n return AWSNetwork(self.provider, network[0]) if network else None\n except EC2ResponseError as ec2e:\n if ec2e.code == 'InvalidVpcID.NotFound':\n return None\n elif ec2e.code == 'InvalidParameterValue':\n # Occurs if id does not start with 'vpc-...'\n return None\n raise ec2e\n\n def list(self, limit=None, marker=None):\n networks = [AWSNetwork(self.provider, network)\n for network in self.provider.vpc_conn.get_all_vpcs()]\n return ClientPagedResultList(self.provider, networks,\n limit=limit, marker=marker)\n\n def find(self, name, limit=None, marker=None):\n filtr = {'tag:Name': name}\n networks = [AWSNetwork(self.provider, network)\n for network in self.provider.vpc_conn.get_all_vpcs(\n filters=filtr)]\n return ClientPagedResultList(self.provider, networks,\n limit=limit, marker=marker)\n\n def create(self, name, cidr_block):\n AWSNetwork.assert_valid_resource_name(name)\n\n network = self.provider.vpc_conn.create_vpc(cidr_block=cidr_block)\n cb_network = AWSNetwork(self.provider, network)\n if name:\n cb_network.wait_for(\n [NetworkState.PENDING, NetworkState.AVAILABLE],\n terminal_states=[NetworkState.ERROR])\n cb_network.name = name\n return cb_network\n\n @property\n def floating_ips(self):\n # fltrs = None\n # if network_id:\n # fltrs = {'network-interface-id': network_id}\n al = self.provider.vpc_conn.get_all_addresses()\n return [AWSFloatingIP(self.provider, a) for a in al]\n\n def create_floating_ip(self):\n ip = self.provider.ec2_conn.allocate_address(domain='vpc')\n return AWSFloatingIP(self.provider, ip)\n\n\nclass AWSSubnetService(BaseSubnetService):\n\n def __init__(self, provider):\n super(AWSSubnetService, self).__init__(provider)\n\n def get(self, subnet_id):\n try:\n subnets = self.provider.vpc_conn.get_all_subnets([subnet_id])\n return AWSSubnet(self.provider, subnets[0]) if subnets else None\n except EC2ResponseError as ec2e:\n if ec2e.code == 'InvalidSubnetID.NotFound':\n return None\n elif ec2e.code == 'InvalidParameterValue':\n # Occurs if id does not start with 'subnet-...'\n return None\n raise ec2e\n\n def list(self, network=None, limit=None, marker=None):\n fltr = None\n if network:\n network_id = (network.id if isinstance(network, AWSNetwork) else\n network)\n fltr = {'vpc-id': network_id}\n subnets = [AWSSubnet(self.provider, subnet) for subnet in\n self.provider.vpc_conn.get_all_subnets(filters=fltr)]\n return ClientPagedResultList(self.provider, subnets,\n limit=limit, marker=marker)\n\n def create(self, name, network, cidr_block, zone=None):\n AWSSubnet.assert_valid_resource_name(name)\n\n network_id = network.id if isinstance(network, AWSNetwork) else network\n subnet = self.provider.vpc_conn.create_subnet(network_id, cidr_block,\n availability_zone=zone)\n cb_subnet = AWSSubnet(self.provider, subnet)\n if name:\n cb_subnet.wait_for(\n [SubnetState.PENDING, SubnetState.AVAILABLE],\n terminal_states=[SubnetState.ERROR])\n cb_subnet.name = name\n return cb_subnet\n\n def get_or_create_default(self, zone=None):\n filtr = {'availabilityZone': zone} if zone else None\n sns = self.provider.vpc_conn.get_all_subnets(filters=filtr)\n for sn in sns:\n if sn.defaultForAz:\n return AWSSubnet(self.provider, sn)\n # No provider-default Subnet exists, look for a library-default one\n for sn in sns:\n if sn.tags.get('Name') == AWSSubnet.CB_DEFAULT_SUBNET_NAME:\n return AWSSubnet(self.provider, sn)\n # No provider-default Subnet exists, try to create it (net + subnets)\n default_net = self.provider.networking.networks.create(\n name=AWSNetwork.CB_DEFAULT_NETWORK_NAME, cidr_block='10.0.0.0/16')\n # Create a subnet in each of the region's zones\n region = self.provider.compute.regions.get(\n self.provider.vpc_conn.region.name)\n default_sn = None\n for i, z in enumerate(region.zones):\n sn = self.create(AWSSubnet.CB_DEFAULT_SUBNET_NAME, default_net,\n '10.0.{0}.0/24'.format(i), z.name)\n if zone and zone == z.name:\n default_sn = sn\n # No specific zone was supplied; return the last created subnet\n if not default_sn:\n default_sn = sn\n return default_sn\n\n def delete(self, subnet):\n subnet_id = subnet.id if isinstance(subnet, AWSSubnet) else subnet\n return self.provider.vpc_conn.delete_subnet(subnet_id=subnet_id)\n\n\nclass AWSRouterService(BaseRouterService):\n \"\"\"For AWS, a CloudBridge router corresponds to an AWS Route Table.\"\"\"\n\n def __init__(self, provider):\n super(AWSRouterService, self).__init__(provider)\n\n def get(self, router_id):\n try:\n routers = self.provider.vpc_conn.get_all_route_tables([router_id])\n return AWSRouter(self.provider, routers[0]) if routers else None\n except EC2ResponseError as ec2e:\n if ec2e.code == 'InvalidRouteTableID.NotFound':\n return None\n elif ec2e.code == 'InvalidParameterValue':\n # Occurs if id does not start with 'rtb-...'\n return None\n raise ec2e\n\n def find(self, name, limit=None, marker=None):\n filtr = {'tag:Name': name}\n routers = self.provider.vpc_conn.get_all_route_tables(filters=filtr)\n aws_routers = [AWSRouter(self.provider, r) for r in routers]\n return ClientPagedResultList(self.provider, aws_routers, limit=limit,\n marker=marker)\n\n def list(self, limit=None, marker=None):\n routers = self.provider.vpc_conn.get_all_route_tables()\n aws_routers = [AWSRouter(self.provider, r) for r in routers]\n return ClientPagedResultList(self.provider, aws_routers, limit=limit,\n marker=marker)\n\n def create(self, name, network):\n AWSRouter.assert_valid_resource_name(name)\n\n network_id = network.id if isinstance(network, AWSNetwork) else network\n router = self.provider.vpc_conn.create_route_table(vpc_id=network_id)\n cb_router = AWSRouter(self.provider, router)\n if name:\n time.sleep(2) # Some time is required\n cb_router.name = name\n return cb_router\n\n\nclass AWSGatewayService(BaseGatewayService):\n\n def __init__(self, provider):\n super(AWSGatewayService, self).__init__(provider)\n\n def get_or_create_inet_gateway(self, name):\n AWSInternetGateway.assert_valid_resource_name(name)\n\n gateway = self.provider.vpc_conn.create_internet_gateway()\n cb_gateway = AWSInternetGateway(self.provider, gateway)\n cb_gateway.wait_till_ready()\n cb_gateway.name = name\n return cb_gateway\n\n def delete(self, gateway):\n gateway.delete()\n","sub_path":"cloudbridge/cloud/providers/aws/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":36555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"91687162","text":"import numpy as np\nimport torch\nimport torch.cuda\nimport torch.nn as nn \nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader\nimport argparse\nimport random\nimport pdb \nimport os \n\nfrom networks import Discriminator, Generator, Encoder\nfrom utils import *\n\nclass BiGAN(object):\n def __init__(self, args):\n\n self.z_dim = args.z_dim\n self.decay_rate = args.decay_rate\n self.learning_rate = args.learning_rate\n self.model_name = args.model_name\n self.batch_size = args.batch_size\n\n #initialize networks\n self.Generator = Generator(self.z_dim).cuda()\n self.Encoder = Encoder(self.z_dim).cuda()\n self.Discriminator = Discriminator().cuda()\n\n #set optimizers for all networks\n self.optimizer_G_E = torch.optim.Adam(list(self.Generator.parameters()) + list(self.Encoder.parameters()),\n lr=self.learning_rate, betas=(0.5, 0.999))\n\n self.optimizer_D = torch.optim.Adam(self.Discriminator.parameters(), lr=self.learning_rate, betas=(0.5, 0.999))\n\n #initialize network weights\n self.Generator.apply(weights_init)\n self.Encoder.apply(weights_init)\n self.Discriminator.apply(weights_init)\n\n def train(self, data):\n\n self.Generator.train()\n self.Encoder.train()\n self.Discriminator.train()\n\n self.optimizer_G_E.zero_grad()\n self.optimizer_D.zero_grad()\n\n\n #get fake z_data for generator\n self.z_fake = torch.randn((self.batch_size, self.z_dim))\n \n #send fake z_data through generator to get fake x_data\n self.x_fake = self.Generator(self.z_fake.detach())\n\n #send real data through encoder to get real z_data\n self.z_real = self.Encoder(data)\n\n #send real x and z data into discriminator\n self.out_real = self.Discriminator(data, z_real.detach())\n\n #send fake x and z data into discriminator\n self.out_fake = self.Discriminator(x_fake.detach(), z_fake.detach())\n\n #compute discriminator loss\n self.D_loss = nn.BCELoss()\n\n #compute generator/encoder loss\n self.G_E_loss = nn.BCELoss()\n\n #compute discriminator gradiants and backpropogate \n self.D_loss.backward()\n self.optimizer_D.step()\n\n #compute generator/encoder gradiants and backpropogate\n self.G_E_loss.backward()\n self.optimizer_G_E.step()","sub_path":"bigan/bigan.py","file_name":"bigan.py","file_ext":"py","file_size_in_byte":2471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"32810650","text":"import os\n\nfrom utils import io\nfrom constants import DEFAULT_CONFIG_PATH\n\nclass Config:\n def __init__(self):\n super(Config, self).__init__()\n\n @staticmethod\n def yaml_config(config=None):\n file_config = {}\n if config is None and os.path.isfile(DEFAULT_CONFIG_PATH):\n config = DEFAULT_CONFIG_PATH\n\n if config is not None:\n try:\n file_config = io.read_config_file(config)\n except Exception as e:\n raise ValueError(\n 'Failed to read configuration file \"{}\". '\n 'Error:{}.'\n .format(config, e)\n )\n\n list_config = []\n dict_config = {}\n if 'default' in file_config.keys():\n list_config.extend(file_config['default'])\n\n if 'run_not_debug' in file_config.keys():\n run_not_debug = file_config['run_not_debug']\n dict_config = {'run_not_debug': run_not_debug}\n\n if run_not_debug and 'run' in file_config.keys():\n list_config.extend(file_config['run'])\n if not run_not_debug and 'debug' in file_config.keys():\n list_config.extend(file_config['debug'])\n\n if list_config:\n for item in list_config:\n for key, value in item.items():\n dict_config[key] = value\n return dict_config\n return None\n","sub_path":"code/configs/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"276583014","text":"from ObstacleField import ObstacleField\nfrom Point import Point\n\n# This class uses a scale factor to increase the size of an obstacle field\n# Ex: ObstacleFieldScaler(10, field) will return a field 10x the size of the input\nclass ObstacleFieldScaler:\n def __init__(self, scale_factor : float, field : ObstacleField):\n\n # check the scale factor to make sure it's >=1\n if scale_factor < 1:\n raise ValueError(\"Scale factor must be >= 1.\")\n\n scale_factor = float(scale_factor)\n if not (scale_factor).is_integer() :\n raise ValueError(\"Scale factor must be a whole number (not fraction)\")\n scale_factor = int(scale_factor)\n\n self.scale_factor_ = scale_factor\n self.field_ = field\n\n # Scale the field that we just received by using the scale factor\n self.scaled_field_ = self.ScaleField()\n\n # def __init__(self, heightInches = 72, widthInches = 96, entranceWidth = 24, entranceOffset = 34, exitWidth = 24, exitOffset = 6, occupiedPoints = []):\n def ScaleField(self):\n sf = self.scale_factor_\n newHeight = sf*self.field_.heightInches_\n newWidth = sf*self.field_.widthInches_\n newentranceWidth = sf*self.field_.entranceWidth_\n newentranceOffset = sf*self.field_.entranceOffset_\n newexitWidth = sf*self.field_.exitWidth_\n newexitOffset = sf*self.field_.exitOffset_\n \n # Generate out new points\n newoccupiedPoints = []\n for point in self.field_.occupiedPoints_:\n newoccupiedPoints.extend(self.ScalePoint(point))\n\n return ObstacleField(newHeight, newWidth, newentranceWidth, newentranceOffset, newexitWidth, newexitOffset, newoccupiedPoints)\n\n def ScalePoint(self, p_org : Point):\n x_low = p_org.xVal_*self.scale_factor_ - (self.scale_factor_ - 1)\n x_high = p_org.xVal_*self.scale_factor_\n x_range = range(x_low, x_high+1)\n\n y_low = p_org.yVal_*self.scale_factor_ - (self.scale_factor_ - 1)\n y_high = p_org.yVal_*self.scale_factor_\n y_range = range(y_low, y_high+1)\n\n out = []\n for i in x_range:\n for j in y_range:\n out.append(Point(i,j))\n\n return out\n\n\n\n\n \nif __name__ == \"__main__\":\n # testField = ObstacleField(72, 96, 24, 34, 24, 6, [Point(3,3), Point(3,4), Point(3,5), Point (3,6)])\n testField = ObstacleField(8, 10, 2, 2, 2, 2, [Point(3,3), Point(3,4), Point(3,5), Point (3,6)])\n scaler = ObstacleFieldScaler(4, testField)\n\n\n\n\n print(\"\\nOriginal\")\n print(scaler.field_.toString())\n print(\"\\n\\nScaled by:\", scaler.scale_factor_)\n print(\"\\n\\nResult\")\n print(scaler.scaled_field_.toString())\n \n","sub_path":"Test/ObstacleFieldScaler.py","file_name":"ObstacleFieldScaler.py","file_ext":"py","file_size_in_byte":2695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"583031961","text":"\nclass Base:\n def __init__(self, driver):\n self.driver = driver\n print(\"in level\")\n\n def element(self, indicator):\n if indicator[0] == \"ID\":\n return self.driver.find_element_by_id(indicator[1])\n elif indicator[0] == \"ACCESS\":\n return self.driver.find_element_by_accessibility_id(indicator[1])\n elif indicator[0] == \"UI_ID_mul_re\":\n return self.driver.find_elements_by_android_uiautomator(\n 'new UiSelector().resourceId(\"' + indicator[1] + '\")')\n elif indicator[0] == \"UI_ID_mul_cl\":\n return self.driver.find_element_by_Xpath(indicator[1])\n\n\n\n\n\nclass flipLogin(Base):\n locators = {\n \"login_btn\": [\"XPATH\", \"//a[@class='_3NH1qf _2x71WM']\"],\n \"email_use\": [\"XPATH\", \"//span[@class='_3ZN6CT _P1NtA']\"],\n \"Username_text\": [\"XPATH\", \"//input[@class='_1i5zkb']\"],\n \"continue\": [\"XPATH\", \"//button[@class='_2iUM2T LuQr2v']\"],\n \"password\": [\"XPATH\", \"//input[@class='_1i5zkb']\"]\n }\n\n def __init__(self, driver):\n super().__init__(driver)\n print(\"homepage constructor\")\n\n def get_element(self, indicator):\n if indicator in self.locators:\n return self.element(self.locators[indicator])\n\n\nclass flipLogout(Base):\n locators = {\n \"profile_btn\": [\"XPATH\", \"(//a[@class='_3NH1qf'])[5]\"],\n \"Entry\": [\"ID\", \"com.whatsapp:id/entry\"],\n \"V_rec\": [\"ID\", \"com.whatsapp:id/voice_note_btn\"],\n \"Send\": [\"ID\", \"com.whatsapp:id/send\"]\n }\n\n def __init__(self, driver):\n super().__init__(driver)\n print(\"search_box constructor\")\n\n def get_element(self, indicator):\n if indicator in self.locators:\n return self.element(self.locators[indicator])","sub_path":"Websites/Flipkart/Locators.py","file_name":"Locators.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"39074964","text":"import os\nfrom enum import Enum\n\n\nproj_path = os.path.dirname(__file__)\n\nraw_data_path = \"/home/wujinjie/kesci_question_multilabel_classification/data/raw_data/\"\nbaidu_raw_data_path = os.path.join(raw_data_path, \"baidu/nlp_db.baidu_text.csv\")\n\nIndustries = ['互联网',\n '交通运输',\n '体育竞技',\n '党政机关',\n '医疗保健',\n '婚礼婚庆',\n '宠物行业',\n '房产建筑',\n '教育行业',\n '旅游行业',\n '美容保养',\n '节日庆典',\n '运动健身',\n '金融投资',\n '餐饮行业']","sub_path":"cfg.py","file_name":"cfg.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"217114652","text":"from django.forms import ModelForm, Textarea\nfrom producto_marca_app.models import ProductoMarca\n\n\nclass ProductoMarcaForm(ModelForm):\n class Meta:\n model = ProductoMarca\n fields = ('coleccion', 'seccion', 'nombre', 'descuento',\n 'unidad_minima_descuento', 'descripcion')\n widgets = {\n 'descripcion': Textarea(attrs={'cols': 40, 'rows': 9}),\n }\n","sub_path":"producto_marca_app/forms/producto_marca.py","file_name":"producto_marca.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"401047474","text":"from operator import mul\nfrom functools import partial\n\n\ndef tag(name, *content, cls=None, **attrs):\n if cls is not None:\n attrs['class'] = cls\n if attrs:\n attr_str = ''.join(' %s=\"%s\"' % (attr, value)\n for attr, value\n in sorted(attrs.items()))\n else:\n attr_str = ''\n if content:\n return '\\n'.join(\n '<%s%s>%s' % (name, attr_str, c, name) for c in content\n )\n else:\n return '<%s%s />' % (name, attr_str)\n\n# ------------------------------------------------------------------------------\n\n\ndef partial_function_application():\n \"\"\"\n The functools.partial is a higher-order function that allows partial\n application of a function. Given a function, a partial application produces\n a new callable with some of the arguments of the original function fixed.\n >>> partial_function_application()\n 21\n \"\"\"\n triple = partial(mul, 3)\n return triple(7)\n\n\ndef use_partial_function_with_map():\n \"\"\"\n Normally mul would not work with map in this example\n >>> use_partial_function_with_map()\n [3, 6, 9, 12, 15, 18, 21, 24, 27]\n \"\"\"\n triple = partial(mul, 3)\n return list(map(triple, range(1, 10)))\n\n\ndef partial_with_binding_arguments():\n \"\"\"\n partial takes a callable as first argument,\n followed by an arbitrary number of positional and keyword arguments to bind.\n >>> partial_with_binding_arguments()\n Arguments: \n Keywords: \n \"\"\"\n picture = partial(tag, 'img', cls='pic-frame')\n picture(src='test.jpeg')\n print(f'Arguments: {partial.args}')\n print(f'Keywords: {partial.keywords}')\n\n\n# The functools.partialmethod function does the same job as partial,\n# but is designed to work with methods. An impressive\n\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod(verbose=True, optionflags=doctest.ELLIPSIS)\n","sub_path":"code_utils/freezing_arguments.py","file_name":"freezing_arguments.py","file_ext":"py","file_size_in_byte":2008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"345150394","text":"import argparse\nimport pyarrow as pa\nimport pandas as pd\n\nfrom wrapyfi.connect.wrapper import MiddlewareCommunicator, DEFAULT_COMMUNICATOR\n\n\"\"\"\nA message publisher and listener for native python objects and pyarrow arrays\n\nHere we demonstrate \n1. Using the NativeObject message\n2. Transmit a nested dummy python object with native objects and multidim pyarrow arrays\n3. Demonstrating the responsive transmission\n\nRun:\n # On machine 1 (or process 1): Publisher waits for keyboard and transmits message\n python3 pyarrow_arrays.py --mode publish\n # On machine 2 (or process 2): Listener waits for message and prints the entire dummy object\n python3 pyarrow_arrays.py --mode listen\n\n\"\"\"\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--mode\", type=str, default=\"publish\", choices={\"publish\", \"listen\"}, help=\"The transmission mode\")\n parser.add_argument(\"--mware\", type=str, default=DEFAULT_COMMUNICATOR, choices=MiddlewareCommunicator.get_communicators(),\n help=\"The middleware to use for transmission\")\n return parser.parse_args()\n\n\nif __name__ == \"__main__\":\n args = parse_args()\n\n class Notify(MiddlewareCommunicator):\n\n @MiddlewareCommunicator.register(\"NativeObject\", args.mware, \"Notify\", \"/notify/test_native_exchange\",\n carrier=\"tcp\", should_wait=True)\n def exchange_object(self):\n msg = input(\"Type your message: \")\n ret = [{\"message\": msg,\n \"pyarrow_array\": pa.array(range(100)),\n }]\n return ret,\n\n notify = Notify()\n\n notify.activate_communication(Notify.exchange_object, mode=args.mode)\n while True:\n msg_object, = notify.exchange_object()\n print(\"Method result:\", msg_object)\n","sub_path":"examples/pyarrow_arrays.py","file_name":"pyarrow_arrays.py","file_ext":"py","file_size_in_byte":1818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"541374734","text":"#!/usr/bin/python\n\nfrom Adafruit_CharLCD import Adafruit_CharLCD\nimport os\nimport glob\nimport time\nimport Adafruit_CharLCD as LCD\nimport RPi.GPIO as GPIO\nfrom subprocess import *\nfrom time import sleep, strftime\nfrom datetime import datetime\nlcd_rs = 26\nlcd_en = 24\nlcd_d4 = 22\nlcd_d5 = 18\nlcd_d6 = 16\nlcd_d7 = 12\nlcd_backlight = 4\nlcd_columns = 16\nlcd_rows = 2 \nlcd = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7,\nlcd_columns, lcd_rows, lcd_backlight)\n\n\n\ncmd = \"ip addr show eth0 | grep inet | awk '{print $2}' | cut -d/ -f1\"\n\n\n\ndef run_cmd(cmd):\n p = Popen(cmd, shell=True, stdout=PIPE)\n output = p.communicate()[0]\n return output\n\nwhile 1:\n lcd.clear()\n ipaddr = run_cmd(cmd)\n lcd.message(datetime.now().strftime('%b %d %H:%M:%S\\n'))\n lcd.message('IP %s' % ( ipaddr ) )\n sleep(2)\n\n","sub_path":"ip.py","file_name":"ip.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"604966060","text":"from math import *\nimport random\n\n\n\n\nlandmarks = [[20.0, 20.0],\n\t\t\t [80.0, 80.0],\n\t\t\t [20.0, 80.0],\n\t\t\t [80.0, 20.0]]\n\nworld_size = 100.0 # world is 100 by 100\n\n\nclass robot:\n\tdef __init__(self):\n\t\tself.x = random.random() * world_size\n\t\tself.y = random.random() * world_size\n\t\tself.orientation = random.random() * 2.0 * pi\n\t\tself.forward_noise = 0.0\n\t\tself.turn_noise = 0.0\n\t\tself.sense_noise = 0.0\n\n\n\tdef set(self, new_x, new_y, new_orientation):\n\t\tif new_x < 0 or new_x >= world_size:\n\t\t\traise(ValueError, 'X coordinate out of bound')\n\t\tif new_y < 0 or new_y >= world_size:\n\t\t\traise(ValueError, 'Y coordinate out of bound')\n\t\tif new_orientation < 0 or new_orientation >= 2*pi:\n\t\t\traise(ValueError, 'Orientation must be in [0..2pi]')\n\t\tself.x = float(new_x)\n\t\tself.y = float(new_y)\n\t\tself.orientation = float(new_orientation)\n\n\tdef set_noise(self, new_f_noise, new_t_noise, new_s_noise):\n\t\t# makes it possible to change the noise parameters\n\t\t# this is often useful in partical filters\n\t\tself.forward_noise = float(new_f_noise);\n\t\tself.turn_noise = float(new_t_noise);\n\t\tself.sense_noise = float(new_s_noise);\n\n\tdef sense(self):\n\t\tZ = []\n\t\tfor i in range(len(landmarks)):\n\t\t\tdist = sqrt( (self.x - landmarks[i][0]) ** 2 + (self.y - landmarks[i][1])**2 )\n\t\t\tdist += random.gauss(0.0, self.sense_noise)\n\t\t\tZ.append(dist)\n\t\treturn Z\n\n\tdef move(self, turn, forward):\n\t\tif forward < 0:\n\t\t\traise(ValueError, 'Robot cant move backwards') \n\n\t\t# turn, and add randomness to the turning command\n\t\torientation = self.orientation + float(turn) + random.gauss(0.0, self.turn_noise)\n\t\torientation %= 2 * pi\n \n # move, and add randomness to the motion command\n\t\tdist = float(forward) + random.gauss(0.0, self.forward_noise)\n\t\tx = self.x + (cos(orientation) * dist)\n\t\ty = self.y + (sin(orientation) * dist)\n\t\tx %= world_size # cyclic truncate\n\t\ty %= world_size\n\n # set particle\n\t\tres = robot()\n\t\tres.set(x, y, orientation)\n\t\tres.set_noise(self.forward_noise, self.turn_noise, self.sense_noise)\n\t\treturn res\n\n\tdef Gaussian(self, mu, sigma, x):\n\t\t# calculates the probability of x for 1-dim Gaussian with mean mu and var. sigma\n\t\treturn exp(- ((mu - x) ** 2) / (sigma ** 2) / 2.0) / sqrt(2.0 * pi * (sigma ** 2))\n\n\tdef measurement_prob(self, measurement):\n \n\t\t# calculates how likely a measurement should be\n\t\tprob = 1.0;\n\t\tfor i in range(len(landmarks)):\n\t\t\tdist = sqrt((self.x - landmarks[i][0]) ** 2 + (self.y - landmarks[i][1]) ** 2)\n\t\t\tprob *= self.Gaussian(dist, self.sense_noise, measurement[i])\n\t\treturn prob\n\n\tdef __repr__(self):\n\t\treturn '[x=%.6s y=%.6s orient=%.6s]' % (str(self.x), str(self.y), str(self.orientation))\n\n\n\n# myrobot = robot()\n\n\n# # starts at 30.0, 50.0, heading north(=pi/2)\n# # turns clockwise by pi/2, moves 15 meters\n# # senses\n# # turns clockwise by pi/2, moves 10 meters\n# # senses\n# myrobot.set_noise(5.0, 0.1, 5.0)\n\n# myrobot.set(30.0,50.0, pi/2)\n\n\n# myrobot = myrobot.move(-pi/2, 15.0)\n# print(myrobot.sense())\n# myrobot = myrobot.move(-pi/2, 10.0)\n# print(myrobot.sense())\n\n\ndef eval(r, p):\n\tsum = 0.0\n\tfor i in range(len(p)):\n\t\tdx = (p[i].x - r.x + (world_size/2.0)) %world_size - (world_size/2.0) # to handle circular world where 0.00001 and 99.999999 are condisdered widely different\n\t\tdy = (p[i].y - r.y + (world_size/2.0)) % world_size - (world_size/2.0)\n\t\terr = sqrt(dx * dx + dy * dy)\n\t\tsum += err\n\treturn sum / float(len(p))\n\n\n\n#here is my actual robot\nmyrobot = robot()\n\n\n\n\n\n# -------------------------------\n\n# created 1000 particles with each of their own x, y, and orientation\n\n\nN = 1000\nT= 10\np = []\nfor i in range(N):\n\tx = robot()\n\tx.set_noise(0.05, 0.05, 5.0)\n\tp.append(x)\n\nprint(len(p))\n\nfor t in range(T):\n\n\tmyrobot = myrobot.move(0.1, 5.0)\n\tZ = myrobot.sense()\n\n\n\t# now lets simulate movement by turning 0.1 and move 5\n\n\tfor i in range(N):\n\t\tp[i] = p[i].move(0.1, 5.0)\n\n\n\t# now we can calculate an importance weight so we can find what particles are\n\t# have measurements that resemble our actual robot.\n\n\tweights = []\n\tfor i in range(N):\n\t\tweights.append(p[i].measurement_prob(Z))\n\n\t# now the weights consists of probabilities that the particle is\n\t# the actual robot\n\n\n\t# the final step is to sample particles from p with a probability that is\n\t# proportional to its corresponding weight\n\n\t# particles with a large weight should be drawn more frequently than ones\n\t# with a small weight value\n\n\n\n\t# Normalize the weights\n\t# norm_w =[]\n\t# total = sum(weights)\n\t# for i in range(N):\n\t# \tnorm_w.append( weights[i]/total)\n\n\n\t# Now we need to resample our particles p, based on the normalized weights.\n\t# we can resample using an algorithm called the Resampling Wheel\n\n\t# RESAMPLING WHEEL\n\t# random uniform particle index, so random variable from 1 to N, (or 0 to N-1)\n\n\t# a beta value that is intially 0, but it beta a value from 0 to 2 times the max weight \n\n\n\tindex = int(random.random() * N)\n\tbeta = 0.0\n\tmw = max(weights)\n\tresampled_p = []\n\tfor i in range(N):\n\t\tbeta += random.random() * 2.0 * mw\n\t\twhile beta > weights[index]:\n\t\t\tbeta -= weights[index]\n\t\t\tindex = (index + 1) % N\n\t\tresampled_p.append(p[index])\n\tp = resampled_p\n\t\n\t# print(resampled_p) # all particles that have positions close to the acutal postion\n\t# # however orientation is random due to the fact that it isnt considered when resampliing the particles\n\n\n\n\tprint(eval(myrobot, p))\n\n\n\n\n\n\n\n# -------------------------------\n\n\n\n","sub_path":"Term 2/10. Particle Filters/myRobot.py","file_name":"myRobot.py","file_ext":"py","file_size_in_byte":5370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"353916815","text":"#!/usr/bin/python\n\nfrom pathlib import Path\nimport hashlib\nimport sqlite3\nimport sys\nimport time\n\nclass DuplicateFinder:\n\n files = []\n stack = []\n\n dir_blacklist = [ \".git\" ]\n file_blacklist = [ \".gif\", \".png\", \".jpg\", \".jpeg\", \".ico\", \".xml\", \".htm\", \".html\", \".md\" ]\n file_whitelist = [ ]\n \n empty_files = []\n\n chunk_size = 256\n count = 0\n\n\n def dir_blacklisted(self, d):\n for e in self.dir_blacklist:\n if str(d).find(e) > 0:\n return True\n return False\n\n\n def file_blacklisted(self, f):\n return ( f.suffix.lower() in self.file_blacklist )\n\n\n def file_whitelisted(self, f):\n return ( f.suffix.lower() in self.file_whitelist )\n\n\n def file_of_interest(self, f):\n if (f.stat().st_size == 0):\n self.empty_files.append(f)\n return False\n \n if (self.file_whitelist):\n return self.file_whitelisted(f)\n else:\n return not (self.file_blacklisted(f)) \n\n\n def is_regular_file(self, p):\n return (p.is_file() & (not p.is_symlink()))\n\n\n def md5(self, f):\n m = hashlib.md5()\n with open(f, \"rb\") as f:\n while True:\n bytes = f.read(self.chunk_size)\n if bytes:\n m.update(bytes)\n else:\n break\n return m.hexdigest()\n\n\n def list_files_in_dir(self, path):\n for p in path.iterdir():\n a = p.absolute()\n try:\n if a.is_dir():\n if not self.dir_blacklisted(a):\n self.stack.append(a)\n elif self.is_regular_file(a):\n self.count+=1\n if self.file_of_interest(a):\n self.files.append((a, self.md5(str(a))))\n except Exception as ex:\n print(\"Failed to process {0} with error {1}\".format(a.name, ex))\n\n def start(self):\n self.tsbegin = time.time()\n while True:\n if self.stack:\n e = self.stack.pop()\n self.list_files_in_dir(e)\n else:\n break\n \n self.files.sort(key=lambda f: f[1])\n self.tsend = time.time()\n\n\n def addInputFolder(self, *args):\n for f in args:\n self.stack.append(Path(f));\n \n\n def setFileBlacklist(self, blacklist):\n self.file_blacklist = blacklist\n \n \n def addFileBlacklist(self, ext):\n self.file_blacklist.append(ext)\n\n \n def setFileWhitelist(self, whitelist):\n self.file_whitelist = whitelist\n \n \n def addFileWhitelist(self, ext):\n self.file_whitelist.append(ext) \n \n \n def setDirBlacklist(self, blacklist):\n self.dir_blacklist = blacklist\n\n \n def addDirBlacklist(self, dir):\n self.dir_blacklist.append(dir) \n\n \n def getResult(self):\n return self.files\n \n def getEmptyFiles(self):\n return self.empty_files\n\n\n def getNumberOfFilesProcessed(self):\n return self.count\n\n\n def getTimeElapsed(self):\n return (self.tsend-self.tsbegin)*1000\n\n\n def printResult(self):\n i = 0\n j = -1\n s = \"\"\n\n for (p, m) in self.files:\n if s != m:\n if i < j:\n for f in self.files[i:j+1]:\n print(f[0])\n print(\"\\n\")\n j += 1\n i = j\n s = m\n else:\n j += 1\n\n\nif __name__ == '__main__':\n if len(sys.argv) > 1:\n finder = DuplicateFinder()\n \n for i in range(1,len(sys.argv)):\n finder.addInputFolder(sys.argv[i])\n finder.setDirBlacklist([ \".git\" ])\n finder.setFileBlacklist([ \".gif\", \".png\", \".jpg\", \".jpeg\", \".ico\", \".xml\", \".htm\", \".html\", \".md\" ])\n finder.setFileWhitelist([])\n finder.start()\n finder.printResult()\n \n print(\"{0} files processed\".format(finder.getNumberOfFilesProcessed())) \n print(\"Completed in {0} ms\".format(finder.getTimeElapsed())) \n \n print(finder.getEmptyFiles())\n","sub_path":"filewalker.py","file_name":"filewalker.py","file_ext":"py","file_size_in_byte":4239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"110659913","text":"from helpers.helpers_functions import *\nimport pytest\n\n\n@pytest.mark.parametrize(('symbol'), ['BTCUSD'])\ndef test_stats_response(symbol):\n response = make_request(create_endpoint('stats1/pos.size:1m:t' + str(symbol) + ':long/last'))\n response_time = get_response_time(response)\n\n headers_data = get_response_headers(response)\n content_type = get_json_from_asset(os.path.abspath('assets/content_type.json'))\n body = get_response_body(response)\n write_response_to_a_file(response, \"resp_text5.txt\")\n\n assert response.ok\n assert response_time < 300\n assert headers_data['Content-Type'] == content_type['Content-Type']\n assert isinstance(body, list) # not empty\n assert len(body) != 0\n\n field_type = check_body_types(body)\n assert field_type == int or field_type == float\n","sub_path":"endpoints/stats/test_stats.py","file_name":"test_stats.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"256808197","text":"#workaround for the directory symlinks\n\nfrom os import path \nimport argparse\nimport win32security\nimport ntsecuritycon as con\n\nparser = argparse.ArgumentParser(description='Add \\'ALL APPLICATION PACKAGES\\' security')\nparser.add_argument('directory', metavar='file', type=str, nargs='?', help='directory or file')\nargs = parser.parse_args()\n\ndirectory = args.directory\n\ndataPath = path.abspath(directory)\n\nif path.exists(dataPath):\n app_package, domain, type = win32security.LookupAccountName (\"\", \"all application packages\")\n\n sd = win32security.GetNamedSecurityInfo(dataPath, win32security.SE_FILE_OBJECT, win32security.DACL_SECURITY_INFORMATION)\n dacl = sd.GetSecurityDescriptorDacl() # instead of dacl = win32security.ACL()\n\n dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION_DS, win32security.OBJECT_INHERIT_ACE | win32security.CONTAINER_INHERIT_ACE, con.FILE_ALL_ACCESS, app_package)\n\n sd.SetSecurityDescriptorDacl(1, dacl, 0) # may not be necessary\n win32security.SetFileSecurity(dataPath, win32security.DACL_SECURITY_INFORMATION, sd)","sub_path":"tools/add_security.py","file_name":"add_security.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"121704883","text":"# This code has a few issues when not prime numbers are inputted. The output prints \"Not Prime Not Prime Not Prime\" etc. It has something to do with the for loop, but I'm not sure if it needs a break or something else.\n\nn = input()\n# make sure n is a positive integer\nn = abs(int(n))\n\n# 0 and 1 are not primes\nif n < 2:\n print(\"Not Prime\")\n\n # 2 is the only even prime number\nif n == 2: \n print(\"Prime\") \n \n # all other even numbers are not primes\nif not n & 1: \n print(\"Not Prime\")\n\n # range starts with 3 and only needs to go up \n # the square root of n for all odd numbers\nfor x in range(3, int(n**0.5) + 1, 2):\n if n % x == 0:\n print(\"Not Prime\")\n else:\n print(\"Prime\")\n break\n","sub_path":"isitprime.py","file_name":"isitprime.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"153105418","text":"import tensorflow as tf\nimport matplotlib.pyplot as plt\n\n# XOR definition\nX = [[0, 0], [0, 1], [1, 0], [1, 1]]\nY = [[0], [1], [1], [0]]\n\n# Neural Network Parameters\nN_STEPS = 40000\nN_EPOCH = 1000\nN_TRAINING = len(X)\n\nN_INPUT_NODES = 2\n#N_HIDDEN_NODES = 1\nN_OUTPUT_NODES = 1\nLEARNING_RATE = 0.05\n\ncost_history1=[]\ncost_history2=[]\ncost_history5=[]\n\n\nfor N_HIDDEN_NODES in [1,2,5]:\n# Create placeholders for variables and define Neural Network structure\n x_ = tf.placeholder(tf.float32, shape=[N_TRAINING, N_INPUT_NODES], name=\"x-input\")\n y_ = tf.placeholder(tf.float32, shape=[N_TRAINING, N_OUTPUT_NODES], name=\"y-input\")\n\n theta1 = tf.Variable(tf.random_uniform([N_INPUT_NODES, N_HIDDEN_NODES], -1, 1), name=\"theta1\")\n theta2 = tf.Variable(tf.random_uniform([N_HIDDEN_NODES, N_OUTPUT_NODES], -1, 1), name=\"theta2\")\n \n bias1 = tf.Variable(tf.zeros([N_HIDDEN_NODES]), name=\"bias1\")\n bias2 = tf.Variable(tf.zeros([N_OUTPUT_NODES]), name=\"bias2\")\n \n # Use a sigmoidal activation function\n layer1 = tf.sigmoid(tf.matmul(x_, theta1) + bias1)\n output = tf.sigmoid(tf.matmul(layer1, theta2) + bias2)\n \n # Cross Entropy cost function\n cost = - tf.reduce_mean((y_ * tf.log(output)) + (1 - y_) * tf.log(1.0 - output))\n train_step = tf.train.GradientDescentOptimizer(LEARNING_RATE).minimize(cost)\n \n init = tf.global_variables_initializer()\n sess = tf.Session()\n sess.run(init)\n \n for i in range(N_STEPS):\n sess.run(train_step, feed_dict={x_: X, y_: Y})\n if i % N_EPOCH == 0:\n print('Batch ', i)\n print('Inference ', sess.run(output, feed_dict={x_: X, y_: Y}))\n c=sess.run(cost, feed_dict={x_: X, y_: Y})\n print('Cost ', c)\n if N_HIDDEN_NODES==1:\n cost_history1.append(c)\n elif N_HIDDEN_NODES==2:\n cost_history2.append(c)\n else:\n cost_history5.append(c)\n \nfig, ax1 = plt.subplots()\nax1.set_title('COST HISTORY', fontsize=10)\nax1.plot(range(len(cost_history1)), cost_history1, lw=2, color=\"blue\")\nax1.plot(range(len(cost_history2)), cost_history2, lw=2, color=\"red\")\nax1.plot(range(len(cost_history5)), cost_history5, lw=2, color=\"green\")\nax1.text(25, 0.55, r\"1 Hidden Node\", fontsize=10, color=\"blue\")\nax1.text(25, 0.40, r\"2 Hidden Nodes\", fontsize=10, color=\"red\")\nax1.text(25, 0.05, r\"5 Hidden Nodes\", fontsize=10, color=\"green\")\nax1.set_ylabel(r\"Cost\", fontsize=10, color=\"black\")\nax1.set_xlabel(r\"Epochs $(in$ $thousands)$\", fontsize=10, color=\"black\")\n","sub_path":"Neural Networks in TensorFlow/ML3_NN_XOR.py","file_name":"ML3_NN_XOR.py","file_ext":"py","file_size_in_byte":2555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"84857434","text":"import numpy as np\nimport settings\nfrom utils.helpers import base64_encode_image\nimport redis\nimport uuid\nimport time\nimport cv2\nimport json\n\n# tf.enable_eager_execution()\ndb = redis.StrictRedis(host=settings.REDIS_HOST,\n\tport=settings.REDIS_PORT, db=settings.REDIS_DB)\n\ndef streaming():\n cam = cv2.VideoCapture(0) #(settings.RTSP_ADDR)\n start = time.time()\n while cam.isOpened():\n _, image = cam.read()\n cv2.imshow('{}-{}'.format(image.shape[0], image.shape[1]), image)\n if cv2.waitKey(1) == ord('q'):\n exit()\n if time.time() - start < 1:\n continue\n else:\n start = time.time()\n img_height, img_width,_ = image.shape\n image = cv2.resize(image, (640,480),\n interpolation=cv2.INTER_LINEAR)\n image = image.astype(np.float32)\n\n # generate an ID for the classification then add the\n # classification ID + image to the queue\n k = time.strftime('%Y-%m-%d %H:%M:%S')#str(uuid.uuid4())\n image = base64_encode_image(image)\n d = {\"id\": k, \"image\": image}\n db.rpush(settings.IMAGE_QUEUE, json.dumps(d))\n print(time.time()-start)\nstreaming()","sub_path":"camera_module/rtsp.py","file_name":"rtsp.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"517111706","text":"#%%\n_a = 'hello hello llo eelo llo halo llo' \n_b = 'libex04'\n_c = 'libex03'\n_a.startswith('he')\n\n# %%\n_a.endswith('lo')\n\n# %%\n\n_b.startswith('lib')\n\n\n# %%\n_c.find('ex')\n\n# %%\n_a.count('llo')\n\n\n# %%\n\n_lt = \" front line \"\nprint('before' + _lt)\n__lt = str.lstrip(_lt)\nprint('after' + _lt)\nprint('after' + __lt)\n\n# %%\n_lt = \" front line \"\n__lt = _lt.lstrip()\nprint('after' + _lt)\nprint('after' + __lt)\n\n\n\n# %%\nprint(str.isalpha('helllo'))\n\n# %%\nprint(str.isdigit('helllo'))\nprint(str.isdigit('314'))\n\n# %%\nname = \"lsj\"\nage = 50\nprint(f'my name {name} my age{age}')\n\n# %%\n\ndata = \"lee seon jun\"\n_data = data.split()\n\nprint(_data[0])\nprint(_data[1])\nprint(_data[2])\n\n# %%\ndata = \"kor/eng/math/the society\"\n\ndata.split('/')\n\n# %%\ndata = input()\ndata.split()\n\n# %%\n","sub_path":"day04/ex11.py","file_name":"ex11.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"350162729","text":"#!/usr/bin/python3\n# -*- coding:utf-8 -*-\nimport sys\nimport os\npicdir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'pic')\nlibdir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'lib')\nif os.path.exists(libdir):\n sys.path.append(libdir)\n\nimport logging\nfrom waveshare_epd import epd2in7b\nimport time\nfrom PIL import Image,ImageDraw,ImageFont,ImageEnhance\nimport traceback\nfrom argparse import ArgumentParser as AP\nimport pdb\n\ndef main(image_file: str):\n\n #if verbose: logging.basicConfig(level=logging.DEBUG) \n #else: logging.basicConfig(level=logging.INFO)\n\n try:\n logging.info(\"QR Code DRAW\")\n \n epd = epd2in7b.EPD()\n logging.info(\"init and Clear\")\n epd.init()\n epd.Clear()\n time.sleep(2)\n \n # Drawing on the image\n logging.info(\"Drawing QR Code\")\n blackimage = Image.new('1', (epd.width, epd.height), 255) # 255: clear the frame\n redimage = Image.new('1', (epd.width, epd.height), 255) # 255: clear the frame\n \n logging.info(f\"width = {epd.width}, height = {epd.height}\")\n\n # Drawing on the Horizontal image\n todraw = Image.new('1', (epd.height, epd.width), 255) # 298*126\n qrcode = Image.open(image_file)\n qrcode = qrcode.resize((epd.width,epd.width), Image.ANTIALIAS)\n qrcode = qrcode.convert(\"RGB\")\n\n image_enhancer = ImageEnhance.Sharpness(qrcode)\n qrcode = image_enhancer.enhance(2.0)\n qrcode = qrcode.convert(\"L\")\n qrcode.save(\"sample.bmp\")\n\n image = Image.open(\"sample.bmp\")\n todraw.paste(image, (0,0))\n \n epd.display(epd.getbuffer(todraw), epd.getbuffer(todraw))\n\n\n time.sleep(50)\n \n logging.info(\"Clear...\")\n epd.init()\n epd.Clear()\n \n logging.info(\"Goto Sleep...\")\n epd.sleep()\n \n except IOError as e:\n logging.info(e)\n \n except KeyboardInterrupt: \n logging.info(\"ctrl + c:\")\n epd2in7b.epdconfig.module_exit()\n exit()\n\n\nif __name__ == '__main__':\n parser = AP()\n parser.add_argument(\"-f\",\"--file\",dest=\"image_file\",help=\"Draw image from file\",default=\"sample.png\")\n parser.add_argument(\"-v\",\"--verbose\",help=\"Log with detail\",default=True,action=\"store_true\")\n logging.basicConfig(level=logging.DEBUG)\n args = parser.parse_args()\n #pdb.set_trace()\n if args.verbose: logging.basicConfig(level=logging.DEBUG)\n else: logging.basicConfig(level=logging.INFO)\n main(args.image_file)\n","sub_path":"py_resize.py","file_name":"py_resize.py","file_ext":"py","file_size_in_byte":2560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"238467747","text":"from flask import Flask, render_template, redirect, url_for, session\nimport random\nfrom database import db_session, init_db\nfrom models import Deck, UserHand, ComputerHand\nfrom bitcoin import privtoaddr, random_key, sha256\n\napp = Flask(__name__)\napp.config.from_pyfile('settings.cfg')\n\nCARD_SCORES = {\n '2': 2,\n '3': 3,\n '4': 4,\n '5': 5,\n '6': 6,\n '7': 7,\n '8': 8,\n '9': 9,\n '10': 10,\n 'J': 10,\n 'Q': 10,\n 'K': 10,\n 'A': 11\n}\n\n\n@app.route('/')\ndef home():\n return render_template('index.html',\n address=session['address'])\n\n@app.route('/new_address')\ndef new_address():\n session.pop('key', None)\n session['key'] = sha256('KEKEKE' + random_key())\n session['address'] = privtoaddr(session['key'], 88)\n return redirect(url_for('home'))\n\n@app.route('/start_game')\ndef start_game():\n init_or_flush_cards()\n generate_deck()\n i = 0\n while i < 2: # Both gamers get 2 cards from deck to start the game\n add_user_card(get_card_from_deck())\n add_computer_card(get_card_from_deck())\n i += 1\n\n game_state = getstate()\n return render_template('game.jinja2',\n address=session['address'],\n game_state=game_state)\n\n\n@app.route('/get_card')\ndef get_card():\n add_user_card(get_card_from_deck())\n\n user_score = calc_score(get_user_cards())\n if user_score > 21:\n return redirect(url_for('stop'))\n\n game_state = getstate()\n return render_template('game.jinja2',\n address=session['address'],\n game_state=game_state)\n\n\n@app.route('/stop')\ndef stop():\n user_score = calc_score(get_user_cards())\n computer_score = calc_score(get_computer_cards())\n\n while computer_score < 17:\n add_computer_card(get_card_from_deck())\n computer_score = calc_score(get_computer_cards())\n if computer_score > user_score:\n break\n\n\n if (user_score > 21 and computer_score > 21) or user_score == computer_score:\n result = 'Friendship won'\n elif user_score <= 21 and computer_score > 21:\n result = 'You won'\n elif user_score > 21 and computer_score <= 21:\n result = 'You lose'\n elif user_score > computer_score:\n result = 'You won'\n else:\n result = 'You lose'\n\n game_state = getstate()\n return render_template('score.jinja2',\n address=session['address'],\n result=result,\n game_state=game_state)\n\n\ndef getstate():\n return {'computer_score' : calc_score(get_computer_cards()),\n 'computer_cards' : get_computer_cards(),\n 'user_score' : calc_score(get_user_cards()),\n 'user_cards' : get_user_cards()}\n\ndef init_or_flush_cards():\n '''\n Creates tables and clears them\n '''\n init_db()\n for database in [UserHand, ComputerHand, Deck]:\n database.query.delete()\n save()\n\ndef generate_deck():\n '''\n Generates list of cards and stores it to model\n '''\n deck = []\n types = ['S', 'C', 'D', 'H']\n for i in types:\n deck += [a+i for a in CARD_SCORES.keys()]\n deck *= 2\n random.shuffle(deck, random.random)\n for card in deck:\n card = Deck(str(card))\n db_session.add(card)\n save()\n\n\ndef get_deck():\n return Deck.query.all()\n\n\ndef get_user_cards():\n return UserHand.query.all()\n\n\ndef get_computer_cards():\n return ComputerHand.query.all()\n\n\ndef add_user_card(card):\n card = UserHand(card)\n db_session.add(card)\n save()\n\n\ndef add_computer_card(card):\n card = ComputerHand(card)\n db_session.add(card)\n save()\n\n\ndef get_card_from_deck():\n '''\n Gets top card and removes it from deck\n :return: card String\n '''\n deck = get_deck()\n card = str(deck.pop(0))\n db_session.delete(Deck.query.filter_by(card=card).first())\n save()\n return card\n\n\ndef save():\n try:\n db_session.commit()\n except Exception as e:\n print(e)\n\n\ndef calc_score(cards):\n '''\n :param cards: List of cards\n :return: Score of given cards set\n '''\n score = 0\n for card in cards:\n score += CARD_SCORES[str(card).rstrip('SCDH')]\n return score\n\n\n@app.teardown_appcontext\ndef shutdown_session(exception=None):\n db_session.remove()\n print(exception)\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"blackjack.py","file_name":"blackjack.py","file_ext":"py","file_size_in_byte":4435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"223534503","text":"import numpy as np\nimport netCDF4 as nc\n\n# edit time\nndays = [31,28,31,30,31,30,31,31,30,31,30,31]\ndtot=0\nnewtime=np.zeros(len(ndays))\n\n# establish sss_time values for cycling over 365d yr\n# (i.e., middle of Jan, Feb, Mar ... Dec)\nfor nmon in range(len(ndays)):\n newtime[nmon] = dtot + ndays[nmon]/2.0\n dtot+=ndays[nmon]\n\nncfil = '/glade2/scratch2/edrenkar/CCS-inputs/CCS_bdry_soda3.4.1_1981-2010_clim.nc'\nfid = nc.Dataset(ncfil,'a')\n\nfid.variables['ocean_time'].units = 'Days'\nfid.variables['ocean_time'].field = 'ocean_time, scalar, series'\nfid.variables['ocean_time'][:] = newtime\n\nfid.close()\n","sub_path":"Inputs/Boundary/edit_SODA_files.py","file_name":"edit_SODA_files.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"473071177","text":"from pagesort import PageSort\n\nclass RightFirstSort(PageSort):\n\n def sort(self, lhs):\n numPages = len(lhs)//2\n sortedPages = [0] * numPages*2\n for i in range(0, numPages//2):\n sortedPages[ i*2] = lhs[i*4 + 1]\n sortedPages[numPages*2 - 1 - i*2] = lhs[i*4]\n sortedPages[numPages*2 - 2 - i*2] = lhs[i*4 + 3]\n sortedPages[ 1 + i*2] = lhs[i*4 + 2]\n return sortedPages\n\n","sub_path":"rightfirstsort.py","file_name":"rightfirstsort.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"480130896","text":"# -*- coding: UTF-8 -*-\n\n# 排序\ndef sort1(a):\n for i in range(len(a)):\n for j in range(i, len(a)):\n if a[j] <= a[i]:\n temp = a[i]\n a[i] = a[j]\n a[j] = temp\n return a\n\n# 去重\ndef quchong(a):\n new = []\n for i in a:\n if i not in new:\n new.append(i)\n return new\n\n# 计算出现次数\ndef count1(a):\n dic = {}\n for i in a:\n if i in dic:\n dic[i] += 1\n else:\n dic[i] = 1\n return dic\n\n\n\n\nif ( __name__ == \"__main__\"):\n a = [1, 6, 8, 11, 9, 1, 8, 6, 8, 7, 8]\n\n print(sort1(a)) # 将list进行排序,从小到大\n print(quchong(a)) # 去掉重复出现的数字\n c = count1(a) # 获得每个数字出现的重复次数\n print(c)\n\n print(max(c, key = c.get)) # 获得重复次数最多的值\n print(max(c.values())) #获得最多的重复次数","sub_path":"gongcheng/studay/day1-2/homework1.py","file_name":"homework1.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"491790373","text":"file = open(\"task1_test_data.input.txt\", \"r\")\nline = file.readline()\nN = int(line)\nfilesub = open(\"output.txt\", 'w')\nfor i in range(N):\n line = file.readline()\n line = file.readline()\n n = int(line)\n awake_time = 0\n sleep_time = 0\n st = {}\n en = {}\n\n for j in range(n):\n #ans_sleep_hour = 0\n #ans_sleep_hour = 0\n line = file.readline()\n st[j], en[j] = line.split()\n if j > 0:\n if int(en[j-1][0:2]) > int(st[j][0:2]):\n ans_awake_hour = 24 - int(en[j-1][0:2]) + int(st[j][0:2])\n else:\n ans_awake_hour = int(st[j][0:2]) - int(en[j-1][0:2])\n ans_awake_min = int(st[j][3:5]) - int(en[j-1][3:5])\n awake_time += 60*ans_awake_hour+ans_awake_min\n if int(st[j][0:2]) > int(en[j][0:2]):\n ans_sleep_hour = 24 - int(st[j][0:2]) + int(en[j][0:2])\n else:\n ans_sleep_hour = int(en[j][0:2]) - int(st[j][0:2])\n ans_sleep_min = int(en[j][3:5]) - int(st[j][3:5])\n sleep_time += 60*ans_sleep_hour+ans_sleep_min\n filesub.write(\"Case #\"+str(i+1)+\": \" + str(awake_time) + \" \" +str(sleep_time)+\"\\n\")\n\nfilesub.close()\n \n \n\n","sub_path":"goo/test/pro1.py","file_name":"pro1.py","file_ext":"py","file_size_in_byte":1189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"265401106","text":"def main():\n arr = [15 for i in range(20)]\n arr[0] = 14\n printArr(arr)\n addone(arr)\n printArr(arr)\n addone(arr)\n printArr(arr)\n addone(arr)\n printArr(arr)\n\n\ndef printArr(arr):\n lookUp = \"0123456789ABCDEF\"\n strArr = [lookUp[i] for i in arr]\n print(''.join(map(str, reversed(strArr))))\n\n #print('-'.join(map(str, reversed(arr))))\n\n\ndef toStringArr(arr):\n lookUp = \"0123456789ABCDEF\"\n strArr = [lookUp[i] for i in arr]\n return(''.join(map(str, reversed(strArr))))\n\n\ndef addone(arr):\n arr[0] += 1\n\n for i in range(len(arr)-1):\n if arr[i] == 16:\n arr[i] = 0\n arr[i+1] += 1\n if i == len(arr)-1:\n arr[i+1] = 0\n else:\n return\n\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"parallel_programming/CPU.py","file_name":"CPU.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"20651704","text":"from __future__ import annotations\n\nimport statistics\nfrom dataclasses import dataclass\nfrom typing import TYPE_CHECKING\n\nfrom PySide6.QtCore import Qt, QObject\nfrom PySide6.QtGui import QColor\nfrom PySide6.QtWidgets import QStyle\n\nfrom bsmu.retinal_fundus.core.ms_prediction import MsPredictionParameter, DiseaseStatus\nfrom bsmu.retinal_fundus.plugins.table_visualizer import StyledItemDelegate\nfrom bsmu.vision.core.models.base import ObjectParameter\nfrom bsmu.vision.core.models.table import TableColumn\nfrom bsmu.vision.core.plugins.base import Plugin\n\nif TYPE_CHECKING:\n from PySide6.QtCore import QModelIndex\n from PySide6.QtGui import QPainter\n from PySide6.QtWidgets import QStyleOptionViewItem\n\n from bsmu.retinal_fundus.plugins.table_visualizer import RetinalFundusTableVisualizerPlugin, \\\n RetinalFundusTableVisualizer, PatientRetinalFundusRecord\n\n\nclass MsSummaryParameter(ObjectParameter):\n NAME = 'MS Summary'\n\n\n@dataclass\nclass MsSummaryParameterValue:\n score: float\n ms_count: int\n norm_count: int\n\n def __str__(self):\n if self.score is None:\n return ObjectParameter.UNKNOWN_VALUE_STR\n\n return f'{self.score:.2f}\\nN: {self.norm_count} P: {self.ms_count}'\n\n\nclass MsSummaryTableColumn(TableColumn):\n TITLE = 'MS\\nSummary'\n OBJECT_PARAMETER_TYPE = MsSummaryParameter\n\n\nclass MsSummaryItemDelegate(StyledItemDelegate):\n def __init__(self, norm_threshold: float = 0.35, ms_threshold: float = 0.65, parent: QObject = None):\n super().__init__(parent)\n\n self._norm_threshold = norm_threshold\n self._ms_threshold = ms_threshold\n\n def _paint(self, painter: QPainter, option: QStyleOptionViewItem, index: QModelIndex):\n item_parameter = self._item_parameter(index)\n disease_status = None\n if item_parameter and item_parameter.value and item_parameter.value.score is not None:\n pen_color = None\n if item_parameter.value.score < self._norm_threshold:\n disease_status = DiseaseStatus.NORM\n pen_color = QColor.fromHsv(120, 204, 179)\n elif item_parameter.value.score > self._ms_threshold:\n disease_status = DiseaseStatus.PATHOLOGY\n pen_color = Qt.red\n else:\n disease_status = DiseaseStatus.UNDEFINED\n # pen_color = QColor.fromHsv(60, 255, 217)\n\n if pen_color:\n painter.setPen(pen_color)\n\n if not option.state & QStyle.State_Selected:\n painter.fillRect(option.rect, option.palette.alternateBase())\n\n text = index.data()\n if disease_status:\n text = f'{disease_status}\\n{text}'\n painter.drawText(option.rect, Qt.AlignCenter, text)\n\n\nclass RetinalFundusMsPredictionAggregatorPlugin(Plugin):\n _DEFAULT_DEPENDENCY_PLUGIN_FULL_NAME_BY_KEY = {\n 'retinal_fundus_table_visualizer_plugin':\n 'bsmu.retinal_fundus.plugins.table_visualizer.RetinalFundusTableVisualizerPlugin',\n }\n\n def __init__(\n self,\n retinal_fundus_table_visualizer_plugin: RetinalFundusTableVisualizerPlugin,\n ):\n super().__init__()\n\n self._retinal_fundus_table_visualizer_plugin = retinal_fundus_table_visualizer_plugin\n self._table_visualizer: RetinalFundusTableVisualizer | None = None\n\n self._ms_prediction_aggregator: RetinalFundusMsPredictionAggregator | None = None\n\n @property\n def ms_prediction_aggregator(self) -> RetinalFundusMsPredictionAggregator | None:\n return self._ms_prediction_aggregator\n\n def _enable(self):\n self._table_visualizer = self._retinal_fundus_table_visualizer_plugin.table_visualizer\n\n self._ms_prediction_aggregator = RetinalFundusMsPredictionAggregator(self._table_visualizer)\n\n self._table_visualizer.journal.record_added.connect(self._ms_prediction_aggregator.add_observed_record)\n self._table_visualizer.journal.record_removing.connect(self._ms_prediction_aggregator.remove_observed_record)\n self._table_visualizer.journal.record_removed.connect(self._ms_prediction_aggregator.on_journal_record_removed)\n\n def _enable_gui(self):\n ms_summary_item_delegate = MsSummaryItemDelegate(\n self.config.value('norm-threshold'), self.config.value('ms-threshold'), self._table_visualizer)\n self._table_visualizer.add_column(MsSummaryTableColumn, ms_summary_item_delegate)\n\n def _disable(self):\n self._ms_prediction_aggregator = None\n\n self._table_visualizer = None\n\n raise NotImplementedError\n\n\nclass RetinalFundusMsPredictionAggregator(QObject):\n def __init__(self, table_visualizer: RetinalFundusTableVisualizer):\n super().__init__()\n\n self._table_visualizer = table_visualizer\n\n self._connections_by_record = {}\n\n def add_observed_record(self, record: PatientRetinalFundusRecord):\n self._aggregate_patient_ms_predictions(record)\n\n record_connections = set()\n record_connections.add(\n record.create_connection(record.parameter_added, self._on_record_parameter_added_or_changed))\n record_connections.add(\n record.create_connection(record.parameter_value_changed, self._on_record_parameter_added_or_changed))\n self._connections_by_record[record] = record_connections\n\n def remove_observed_record(self, record: PatientRetinalFundusRecord):\n record_connections = self._connections_by_record.pop(record)\n for connection in record_connections:\n connection.disconnect()\n\n def on_journal_record_removed(self, record: PatientRetinalFundusRecord):\n self._aggregate_patient_ms_predictions(record)\n\n def _aggregate_patient_ms_predictions(self, record: PatientRetinalFundusRecord):\n patient_ms_scores = []\n for patient_record in record.patient.records:\n for parameter in patient_record.parameters:\n if isinstance(parameter, MsPredictionParameter):\n patient_ms_scores.append(parameter.score)\n\n patient_ms_scores = [score for score in patient_ms_scores if score is not None]\n if patient_ms_scores:\n mean_patient_ms_score = statistics.mean(patient_ms_scores)\n else:\n mean_patient_ms_score = None\n\n ms_count = sum(score > 0.75 for score in patient_ms_scores)\n norm_count = len(patient_ms_scores) - ms_count\n\n for patient_record in record.patient.records:\n ms_summary_parameter = MsSummaryParameter(\n MsSummaryParameterValue(score=mean_patient_ms_score, ms_count=ms_count, norm_count=norm_count))\n ms_summary_parameter = patient_record.add_parameter_or_modify_value(ms_summary_parameter)\n\n patient_records_count = len(record.patient.records)\n if patient_records_count < 2:\n return\n\n ms_summary_column = self._table_visualizer.journal_viewer.column_number(MsSummaryTableColumn)\n first_patient_record = record.patient.records[0]\n first_patient_record_row = self._table_visualizer.journal_viewer.record_row(first_patient_record)\n self._table_visualizer.journal_viewer.set_span(\n first_patient_record_row, ms_summary_column, patient_records_count, 1)\n\n def _on_record_parameter_added_or_changed(self, record: PatientRetinalFundusRecord, parameter: ObjectParameter):\n if isinstance(parameter, MsPredictionParameter):\n self._aggregate_patient_ms_predictions(record)\n","sub_path":"retinal-fundus/src/bsmu/retinal_fundus/plugins/ms_prediction_aggregator.py","file_name":"ms_prediction_aggregator.py","file_ext":"py","file_size_in_byte":7505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"319514876","text":"import yaml, os\n\nclass Config(object):\n \n config = None\n '''\"Static\" class variable'''\n \n def __init__(self, root_dir):\n if Config.config is None:\n self.root_dir = root_dir\n self.load_config()\n \n \n def load_config(self):\n '''Loads and parses the configuration file from the filesystem.'''\n config_file = self.root_dir + os.sep + 'config' + os.sep + 'config.yaml'\n \n if os.path.exists(config_file):\n f = open(config_file)\n Config.config = yaml.load(f)\n f.close\n else:\n raise Exception('I was waiting to have a config.yaml file inside the config folder.')\n \n \n @staticmethod\n def get(name):\n '''Get a configuration propery'''\n name = name.lower()\n if name in Config.config:\n return Config.config[name]\n else:\n return None\n \n @staticmethod\n def set(key, value):\n '''Set a configuration property'''\n key = key.lower()\n Config.config[key] = value","sub_path":"lib/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"53474930","text":"\"\"\"Tuner with Simulate Anneal algorithm\"\"\"\n\nimport numpy as np\nimport multiprocessing\nimport logging\nimport threading\nimport lightgbm as lgb\n\nfrom .tuner import Tuner\nfrom .model_based_tuner import knob2point, point2knob\nfrom ..measure import MeasureInput, create_measure_batch\nfrom ..env import GLOBAL_SCOPE\nfrom .sa_model_optimizer import random_walk\n\nlogger = logging.getLogger('autotvm')\n\nclass HCTuner(Tuner):\n def __init__(self, task, early_stop = 1e9):\n super(HCTuner, self).__init__(task)\n self.space = task.config_space\n self.dims = [len(x) for x in self.space.space_map.values()]\n self.visited = set([])\n self.parallel_size = multiprocessing.cpu_count()\n self.points = [] # 初始的是初始的数据\n self.scores = [] # 存放的是初始的结果\n self.new_points = [] # 存放的是修改后的数据\n self.new_scores = [] # 存放的修改后的结果\n self.lens = []\n self.before_iters = []\n self.trial_pt = 0\n self.PointInit(self.parallel_size)\n\n def PointInit(self, scale):\n for _ in range(scale):\n tmp_population = point2knob(np.random.randint(len(self.space)), self.dims)\n while knob2point(tmp_population, self.dims) in self.visited:\n tmp_population = point2knob(np.random.randint(len(self.space)), self.dims)\n self.points.append(knob2point(tmp_population, self.dims))\n self.visited.add(knob2point(tmp_population, self.dims))\n\n def isLegalPoint(self, point):\n return (knob2point(point, self.dims) >= 0 and knob2point(point, self.dims) <= len(self.space))\n\n def tune(self, n_trial, measure_option, early_stopping = None, callbacks = ()):\n self.n_trial = n_trial\n self.early_stopping = early_stopping\n\n measure_batch = create_measure_batch(self.task, measure_option)\n n_parallel = getattr(measure_batch, 'n_parallel', 1)\n early_stopping = early_stopping or 1e9\n old_level = logger.level\n GLOBAL_SCOPE.in_tuning = True\n\n i = 0\n error_ct = 0\n points = []\n first = min(n_parallel, n_trial) # 6\n # 选择初始六个点,第一轮随机验证,貌似是50个?\n # points(归零) -> inputs -> results\n for k in range(first):\n points.append(self.space.get(self.points[k]))\n inputs = [MeasureInput(self.task.target, self.task, point) for point in points]\n results = measure_batch(inputs)\n\n for k, (inp, res) in enumerate(zip(inputs, results)):\n config = inp.config\n if res.error_no == 0:\n flops = inp.task.flop / np.mean(res.costs)\n error_ct = 0\n else:\n flops = 0\n error_ct += 1 \n self.scores.append(flops) # 当前的成绩\n if flops > self.best_flops:\n self.best_flops = flops\n self.best_config = config\n self.best_measure_pair = (inp, res)\n self.before_iters.append(0)\n logger.debug(\"No: %d\\tGFLOPS: %.2f/%.2f\\tresult: %s\\t%s\", i + k + 1, flops / 1e9, self.best_flops / 1e9, res, config)\n \n i += len(results)\n iter = 1\n while i < n_trial:\n configs = self.next_batch(iter-1)\n best_flop = 0\n\n inputs = [MeasureInput(self.task.target, self.task, config) for config in configs]\n results = measure_batch(inputs)\n\n if (iter - 1) % 6 == 0:\n self.new_scores = np.zeros_like(self.scores)\n self.news = np.zeros_like(self.points)\n\n for k, (inp, res) in enumerate(zip(inputs, results)):\n config = inp.config\n if res.error_no == 0:\n flops = inp.task.flop / np.mean(res.costs)\n error_ct = 0\n else:\n flops = 0\n error_ct += 1 \n if flops > best_flop:\n self.new_scores[(iter - 1) % 6] = flops\n self.news[(iter - 1) % 6] = config.index\n best_flop = flops\n if flops > self.best_flops:\n self.best_flops = flops\n self.best_config = config\n self.best_measure_pair = (inp, res)\n self.best_iter = iter\n print(\"New Best Score at No: %d\\tGFLOPS: %.2f/%.2f\", i + k + 1, self.best_flops)\n logger.debug(\"No: %d\\tGFLOPS: %.2f/%.2f\\tresult: %s\\t%s\", i + k + 1, flops / 1e9, self.best_flops / 1e9, res, config)\n \n for k, point in enumerate(self.new_scores):\n if self.scores[k] < self.new_scores[k]:\n self.points[k] = self.news[k]\n self.scores[k] = self.new_scores[k]\n\n # for k in range(len(self.best_iters)):\n # if self.best_iters[k] == self.before_iters[k]:\n # stop_iters += 1\n # tmp_population = point2knob(np.random.randint(len(self.space)), self.dims)\n # while knob2point(tmp_population, self.dims) in self.visited:\n # tmp_population = point2knob(np.random.randint(len(self.space)), self.dims)\n # self.points[k] = knob2point(tmp_population, self.dims)\n # self.visited.add(knob2point(tmp_population, self.dims))\n # self.before_iters[k] = self.best_iters[k]\n\n\n if self.best_iter > i + 300:\n logger.debug(\"Early stopped. Best iter: \", self.best_iter)\n break\n\n i += len(results)\n iter += 1\n \n if error_ct > 150:\n logging.basicConfig()\n logger.warning(\"Too many errors happen in the tuning. Now is in debug mode\")\n logger.setLevel(logging.DEBUG)\n else:\n logger.setLevel(old_level)\n\n GLOBAL_SCOPE.in_tuning = False\n del measure_batch\n \n\n def next_batch(self, batch_size):\n ret = []\n lens = 0\n if (batch_size % 6) == 0:\n self.new_points = []\n self.lens = []\n for k, p in enumerate(self.points):\n p = point2knob(p, self.dims)\n lens = len(self.new_points) # 0\n hc = [-1 for _ in range(self.dims)]\n while True:\n isEnd = True\n for i in range(self.dims):\n if hc[i]!=1:\n hc[i]+=1\n isEnd=False\n break\n elif i!=self.dims-1:\n h[i]=-1\n else:\n break\n if isEnd:\n break\n new_p = []\n flag = True\n for r in range(self.dims):\n new_p.append(p[r] + hc[r])\n if new_p[-1] < 0 or new_p [-1] >= self.dims[r]:\n flag = False\n break\n if (not flag):\n continue\n if self.isLegalPoint(new_p) and knob2point(new_p, self.dims) not in self.visited:\n self.new_points.append(knob2point(new_p, self.dims))\n self.visited.add(knob2point(new_p, self.dims)) \n self.lens.append(len(self.new_points) - lens)\n self.trial_pt = 0\n\n for _ in range(self.lens[batch_size % 6]):\n tmp_population = self.new_points[self.trial_pt % len(self.new_points)]\n self.trial_pt += 1\n \"\"\"ret 存放batch_size个genes的可配置参数\"\"\"\n ret.append(self.space.get(tmp_population))\n return ret \n","sub_path":"python/tvm/autotvm/tuner/hillclimbing_tuner.py","file_name":"hillclimbing_tuner.py","file_ext":"py","file_size_in_byte":7939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"354790999","text":"people = [\n {'name': 'bob', 'age': 20},\n {'name': 'carry', 'age': 38},\n {'name': 'john', 'age': 7},\n {'name': 'smith', 'age': 17},\n {'name': 'ben', 'age': 27},\n {'name': 'bobby', 'age': 57},\n {'name': 'red', 'age': 32},\n {'name': 'queen', 'age': 25}\n]\nresult=filter(lambda person:person['age']>20,people)\nresult2=filter(lambda x:x['age']>20,people)\nprint(list(result))\nprint(list(result2))","sub_path":"sparta_algorithim/grammar/14_03filter_lambda.py","file_name":"14_03filter_lambda.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"302773548","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Nov 6 19:55:11 2020\r\n\r\n@author: 15025\r\n\"\"\"\r\n\r\nimport os\r\nimport time\r\nimport speech\r\nimport numpy as np\r\n\r\n\r\nclass MainGame:\r\n if not os.path.exists(\"./user_data.txt\"):\r\n attribute_list = [0, 0, 0, 0]\r\n else:\r\n with open(\"./user_data.txt\", 'r') as f:\r\n user_data_list = f.readlines()\r\n new_data_list = []\r\n for data in user_data_list:\r\n new_data_list.append(float(data.rstrip()))\r\n attribute_list = new_data_list\r\n\r\n if not os.path.exists(\"./time_data_today.txt\"):\r\n # time_year = time.strftime(\"%Y\", local_time)\r\n # time_month = time.strftime(\"%m\", local_time)\r\n # time_day = time.strftime(\"%d\", local_time)\r\n # time_hour = time.strftime(\"%H\", local_time)\r\n # time_minute = time.strftime(\"%M\", local_time)\r\n # time_second = time.strftime(\"%S\", local_time)\r\n local_time = time.localtime()\r\n time_list = [time.strftime(\"%Y\", local_time), time.strftime(\"%m\", local_time), time.strftime(\"%d\", local_time)]\r\n else:\r\n with open(\".time_data_today\", \"r\") as f:\r\n time_data_list = f.readlines()\r\n new_data_list = []\r\n for data in user_data_list:\r\n new_data_list.append(int(data.rstrip()))\r\n time_list = new_data_list\r\n\r\n def __init__(self):\r\n pass\r\n\r\n def main_game(self):\r\n while True:\r\n print(\"主界面\")\r\n print(\"请您选择,提示:请输入序号1, 2或者3\")\r\n print(\"1. 慢跑\")\r\n print(\"2. 学习\")\r\n print(\"3. 冥想\")\r\n print(\"4. 清洁\")\r\n print(\"5. 查看当前属性值\")\r\n choice = input(\"您的决定: \")\r\n print(\"\")\r\n if choice == \"1\":\r\n j = Jogging()\r\n j.main_program()\r\n elif choice == \"2\":\r\n s = Study()\r\n s.main_program()\r\n elif choice == \"3\":\r\n m = Meditation()\r\n m.main_program()\r\n elif choice == \"4\":\r\n c = Cleaning()\r\n c.main_program()\r\n elif choice == \"5\":\r\n self.display_data()\r\n else:\r\n print(\"您的输入值有误,请重新输入!提示:输入数字1,2或者3\")\r\n continue\r\n\r\n # 循环保存效率并不高\r\n self.save_data()\r\n\r\n @staticmethod\r\n def display_data():\r\n print('-' * 18 + '玩家当前属性 ' + '-' * 18)\r\n print('健康值:'.ljust(20) + '|' + '{0}'.format(MainGame.attribute_list[0]).rjust(28))\r\n print('学术值:'.ljust(20) + '|' + '{0}'.format(MainGame.attribute_list[1]).rjust(28))\r\n print('精神值:'.ljust(20) + '|' + '{0}'.format(MainGame.attribute_list[2]).rjust(28))\r\n print('清洁值:'.ljust(20) + '|' + '{0}'.format(MainGame.attribute_list[3]).rjust(28))\r\n\r\n @staticmethod\r\n def save_data():\r\n with open(\"./user_data.txt\", \"w+\") as f:\r\n f.write(str(MainGame.attribute_list[0]) + '\\n')\r\n f.write(str(MainGame.attribute_list[1]) + '\\n')\r\n f.write(str(MainGame.attribute_list[2]) + '\\n')\r\n f.write(str(MainGame.attribute_list[3]) + '\\n')\r\n\r\n\r\nclass Jogging:\r\n def __init__(self):\r\n self.start_time = time.time()\r\n\r\n self.flag = True\r\n\r\n self.minutes = 20\r\n\r\n self.timestamp = np.arange(self.minutes) + 1\r\n\r\n self.message = [\"Eine Minute verging\", \"Zwei Minuten vergingen\", \"Drei Minuten vergingen\",\r\n \"Vier Minuten vergingen\",\r\n \"Fünf Minuten vergingen\", \"Sechs Minuten vergingen\", \"Sieben Minuten vergingen\",\r\n \"Acht Minuten vergingen\",\r\n \"Neu Minuten vergingen\", \"Zehn Minuten vergingen\", \"Elf Minuten vergingen\",\r\n \"Zwölf Minuten vergingen\",\r\n \"dreizehn Minuten vergingen\", \"vierzehn Minuten vergingen\", \"fünfzehn Minuten vergingen\",\r\n \"Sechszehn Minuten vergingen\",\r\n \"Siebzehn Minuten vergingen\", \"Achtzehn Minuten vergingen\", \"Neunzehn Minuten vergingen\",\r\n \"Zwanzig Minuten vergingen\"]\r\n\r\n if not os.path.exists(\"./time_data_jogging.txt\"):\r\n local_time = time.localtime()\r\n self.time_list = [time.strftime(\"%Y\", local_time), time.strftime(\"%m\", local_time),\r\n time.strftime(\"%d\", local_time),\r\n time.strftime(\"%H\", local_time), time.strftime(\"%M\", local_time),\r\n time.strftime(\"%S\", local_time)]\r\n else:\r\n with open(\"./time_data_jogging.txt\", \"r\") as f:\r\n time_data_list = f.readlines()\r\n new_data_list = []\r\n for data in time_data_list:\r\n new_data_list.append(int(data.rstrip()))\r\n self.time_list = new_data_list\r\n # we need to judge here, whether the time gap reaches 6 hours\r\n # more than two days\r\n year_difference = int(time.strftime(\"%Y\")) - self.time_list[0]\r\n month_difference = int(time.strftime(\"%m\")) - self.time_list[1]\r\n day_difference = int(time.strftime(\"%d\")) - self.time_list[2]\r\n hour_difference = int(time.strftime(\"%H\")) - self.time_list[3]\r\n # the same day\r\n if year_difference == 0 and month_difference == 0 and day_difference == 0 and hour_difference < 6:\r\n print(\"两次运动时间间隔不足六个小时,请保证充足地休息!\")\r\n print(\"\")\r\n self.flag = False\r\n # the different day\r\n if year_difference == 0 and month_difference == 0 and day_difference == 1 and hour_difference < -18:\r\n print(\"两次运动时间间隔不足六个小时,请保证充足地休息!\")\r\n print(\"\")\r\n self.flag = False\r\n\r\n def main_program(self):\r\n if self.flag:\r\n self.start_jogging()\r\n # once the whole process is successfully finished, then we update the data\r\n self.update_data()\r\n\r\n def start_jogging(self):\r\n print(\"慢跑开始!\")\r\n speech.say(\"los geht's\")\r\n\r\n for i in range(self.minutes):\r\n while True:\r\n if round(time.time() - self.start_time) == self.timestamp[i] * 60:\r\n speech.say(self.message[i])\r\n print(f\"已经过去了{i + 1}分钟\")\r\n break\r\n\r\n speech.say(\"Fertig!\")\r\n print(\"慢跑结束!\")\r\n\r\n MainGame.attribute_list[0] += 1\r\n\r\n def update_data(self):\r\n # save current time to .txt file\r\n with open(\"./time_data_jogging.txt\", \"w+\") as f:\r\n f.write(str(self.time_list[0]) + '\\n')\r\n f.write(str(self.time_list[1]) + '\\n')\r\n f.write(str(self.time_list[2]) + '\\n')\r\n f.write(str(self.time_list[3]) + '\\n')\r\n f.write(str(self.time_list[4]) + '\\n')\r\n f.write(str(self.time_list[5]) + '\\n')\r\n\r\n\r\nclass Study:\r\n def __init__(self):\r\n while True:\r\n print(\"请您选择,提示:请输入序号1或者2\")\r\n print(\"1. 学习30分钟\")\r\n print(\"2. 学习60分钟\")\r\n self.choice = input(\"您的决定: \")\r\n print(\"\")\r\n if self.choice == \"1\":\r\n self.total_time = 30 * 60\r\n break\r\n elif self.choice == \"2\":\r\n self.total_time = 60 * 60\r\n break\r\n else:\r\n print(\"您的输入值有误,请重新输入!提示:输入数字1或者2\")\r\n continue\r\n\r\n self.start_time = time.time()\r\n\r\n self.flag = True\r\n\r\n if not os.path.exists(\"./time_data_study.txt\"):\r\n self.time_total_study = 0\r\n else:\r\n with open(\"./time_data_study.txt\", \"r\") as f:\r\n time_data = f.readline()\r\n self.time_total_study = float(time_data)\r\n # judge whether the total time reaches 8 hours\r\n if self.time_total_study >= 8:\r\n print(\"今天学习时间太久了,请做点儿别的事情吧!\")\r\n print(\"\")\r\n self.flag = False\r\n if self.choice == \"2\" and self.time_total_study == 7.5:\r\n print(\"今日剩余学习时间30分钟,请重新选择\")\r\n print(\"\")\r\n self.flag = False\r\n\r\n def main_program(self):\r\n if self.flag:\r\n self.start_learning()\r\n self.update_data()\r\n\r\n def start_learning(self):\r\n print(\"开始学习!\")\r\n speech.say(\"los geht's\")\r\n\r\n while round(time.time() - self.start_time) != self.total_time:\r\n # 这里可以加入一些语音互动\r\n pass\r\n\r\n speech.say(\"fertig!\")\r\n print(\"学习完成!\")\r\n\r\n if self.choice == \"1\":\r\n MainGame.attribute_list[1] += 0.25\r\n self.time_total_study += 0.5\r\n if self.choice == \"2\":\r\n MainGame.attribute_list[1] += 0.5\r\n self.time_total_study += 1\r\n\r\n def update_data(self):\r\n with open(\"./time_data_study.txt\", \"w+\") as f:\r\n f.write(str(self.time_total_study) + '\\n')\r\n\r\n\r\nclass Meditation:\r\n def __init__(self):\r\n self.start_time = time.time()\r\n\r\n self.minutes = 20\r\n\r\n self.timestamp = np.arange(self.minutes) + 1\r\n\r\n def main_program(self):\r\n print(\"开始冥想!\")\r\n speech.say(\"los geht's\")\r\n\r\n for i in range(self.minutes):\r\n while True:\r\n if round(time.time() - self.start_time) == self.timestamp[i] * 60:\r\n print(f\"已经过去了{i + 1}分钟\")\r\n break\r\n\r\n speech.say(\"Fertig!\")\r\n print(\"冥想结束!\")\r\n\r\n MainGame.attribute_list[2] += 1\r\n\r\n\r\nclass Cleaning:\r\n def __init__(self):\r\n self.start_time = time.time()\r\n\r\n self.minutes = 20\r\n\r\n self.timestamp = np.arange(self.minutes) + 1\r\n\r\n def main_program(self):\r\n print(\"开始打扫!\")\r\n speech.say(\"los geht's\")\r\n\r\n for i in range(self.minutes):\r\n while True:\r\n if round(time.time() - self.start_time) == self.timestamp[i] * 60:\r\n print(f\"已经过去了{i + 1}分钟\")\r\n break\r\n\r\n speech.say(\"Fertig!\")\r\n print(\"清洁结束!\")\r\n\r\n MainGame.attribute_list[3] += 1\r\n\r\n\r\nif __name__ == \"__main__\":\r\n # ML: My Life\r\n ML = MainGame()\r\n ML.main_game()\r\n","sub_path":"historicalVersion/MyLife_fullWords.py","file_name":"MyLife_fullWords.py","file_ext":"py","file_size_in_byte":10844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"75989844","text":"class BinarySearchTree:\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n\n def depth_first_for_each(self, cb):\n node_start = self\n cb(node_start.value)\n node = node_start.left\n rights = []\n lefts = []\n \n while(node):\n\n cb(node.value)\n\n if(node.right):\n\n rights.append(node.right)\n\n node = node.left\n\n for obj in rights:\n\n cb(obj.value)\n\n node = node_start\n node = node.right\n\n while(node):\n\n cb(node.value)\n\n if(node.left):\n lefts.append\n\n node = node.right\n\n for obj in lefts:\n\n cb(node.value)\n\n\n\n\n def breadth_first_for_each(self, cb):\n node = self\n nodes = [node]\n\n for obj in nodes:\n\n if not obj.left in nodes and obj.left != None:\n nodes.append(obj.left)\n\n if not obj.right in nodes and obj.right != None:\n nodes.append(obj.right)\n\n for obj in nodes:\n\n cb(obj.value)\n\n print(nodes)\n\n\n\n\n def insert(self, value):\n new_tree = BinarySearchTree(value)\n if (value < self.value):\n if not self.left:\n self.left = new_tree\n else:\n self.left.insert(value)\n elif value >= self.value:\n if not self.right:\n self.right = new_tree\n else:\n self.right.insert(value)\n\n def contains(self, target):\n if self.value == target:\n return True\n if self.left:\n if self.left.contains(target):\n return True\n if self.right:\n if self.right.contains(target):\n return True\n return False\n\n def get_max(self):\n if not self:\n return None\n max_value = self.value\n current = self\n while current:\n if current.value > max_value:\n max_value = current.value\n current = current.right\n return max_value\n","sub_path":"data_structures/ex_1/binary_search_tree.py","file_name":"binary_search_tree.py","file_ext":"py","file_size_in_byte":1785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"228684022","text":"from flask import Flask, request, jsonify, redirect, url_for\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_cors import CORS\nfrom os import environ\nimport requests\nimport json\nimport pika\n\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqlconnector://root@localhost:3306/notifications'\n# app.config['SQLALCHEMY_DATABASE_URI'] = environ.get('dbURL')\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\n\n \ndb = SQLAlchemy(app)\nCORS(app)\n\nclass Person(db.Model):\n __tablename__ = 'tele_details'\n\n userid = db.Column(db.String(10), primary_key=True)\n teleuserid = db.Column(db.String(20), nullable=False)\n telechatid = db.Column(db.String(80), nullable=False)\n\n def __init__(self, userid, teleuserid, telechatid):\n self.userid = userid\n self.teleuserid = teleuserid\n self.telechatid = telechatid\n\n def json(self):\n return {\"userid\": self.userid, \"teleuserid\": self.teleuserid, \"telechatid\": self.telechatid}\n\n\n@app.route('//')\ndef insert_chatid(userid, teleid):\n updates = \"https://api.telegram.org/bot1076658459:AAHwvu83zFLd803XwCa6yBip6j0vwA1Ax5s/getUpdates\"\n response = requests.get(updates)\n response = response.json()\n # looping through messages to find chatid that matches the username\n update_list = (list(response.values())[1])\n for loopnum in range(1, len(update_list)):\n update = update_list[loopnum]\n for key,value in update.items():\n if type(value) is dict:\n for key,value in value.items():\n if type(value) is dict:\n for key, value in value.items():\n if key == 'id': #id\n chatid_holder = value\n if value == teleid: #username\n chatid = chatid_holder\n # check if duplicate\n cuser = Person.query.filter_by(teleuserid=teleid).first()\n if cuser:\n return jsonify(cuser.json())\n\n # inserting into DB\n tele_details = Person(userid=userid,\n teleuserid=teleid,\n telechatid=chatid)\n \n try:\n db.session.add(tele_details)\n db.session.commit()\n except:\n return jsonify({\"message\": \"An error occurred creating the user.\"}), 500\n\n return jsonify(tele_details.json()), 201\n\n\nif __name__=='__main__':\n app.run(host=\"127.0.0.1\", port=5005, debug=True)\n # app.run(host=\"0.0.0.0\", port=5005, debug=True)\n","sub_path":"app/notification.py","file_name":"notification.py","file_ext":"py","file_size_in_byte":2529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"425420466","text":"import matplotlib.pyplot as plt\nimport matplotlib.colors as colors\nimport numpy as np\n\ndef profile_plot(j_factors, wcs, grid=False, cmap=plt.cm.plasma, **kwargs):\n fig = plt.figure()\n ax = fig.add_subplot(111, projection=wcs)\n im = ax.imshow(j_factors, origin='lower', cmap=cmap, **kwargs)\n cbar = fig.colorbar(im, ax=ax)\n cbar.set_label(r\"$\\dfrac{d\\,J(\\theta)}{d\\Omega} \\times \\Delta \\Omega_{\\mathrm{bin}}$ (GeV$^2$/cm$^5$)\", fontsize=14, labelpad=10)\n ax.set_aspect('equal')\n ax.set_ylabel(r'$b$ ($\\degree$)')\n ax.set_xlabel(r'$\\ell$ ($\\degree$)')\n if grid:\n dim_l, dim_b = j_factors.shape\n for x in range(dim_l):\n ax.axvline(x, color='grey', lw=0.3, alpha=0.8)\n for y in range(dim_b):\n ax.axhline(y, color='grey', lw=0.3, alpha=0.8)","sub_path":"src/dm/plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"636109260","text":"from setuptools import setup\nimport os\n\nhere = os.path.abspath(os.path.dirname(__file__))\nREADME = open(os.path.join(here, 'README.rst')).read()\nCHANGES = open(os.path.join(here, 'CHANGES.rst')).read()\n\nversion = \"1.0b5-dev\"\n\ninstall_requires = [\n 'PyYAML',\n 'jinja2',\n 'setuptools',\n 'ploy>=1.0rc13',\n 'ploy_ansible>=1.0b7',\n 'ploy_ezjail>=1.0b9',\n 'ploy_fabric>=1.0b5',\n]\n\n# workaround for installing via buildout, as ansible\n# violates its sandbox limitations\ntry:\n import ansible # noqa\nexcept ImportError:\n install_requires.append('ansible')\n\n\nsetup(name=\"bsdploy\",\n version=version,\n description=\"A tool to provision, configure and maintain FreeBSD jails\",\n long_description=README + '\\n\\n\\nChanges\\n=======\\n\\n' + CHANGES,\n author='Tom Lazar',\n author_email='tom@tomster.org',\n url='http://github.com/ployground/bsdploy',\n include_package_data=True,\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Environment :: Console',\n 'Intended Audience :: System Administrators',\n 'Operating System :: POSIX :: BSD :: FreeBSD',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 2 :: Only',\n 'Topic :: System :: Installation/Setup',\n 'Topic :: System :: Systems Administration',\n ],\n license='Beerware Licence',\n zip_safe=False,\n packages=['bsdploy'],\n install_requires=install_requires,\n extras_require={\n 'development': [\n 'Sphinx',\n 'repoze.sphinx.autointerface',\n 'coverage',\n 'jarn.mkrelease',\n 'pytest >= 2.4.2',\n 'pytest-flakes',\n 'pytest-pep8',\n 'tox',\n 'mock',\n ],\n },\n entry_points=\"\"\"\n [console_scripts]\n ploy-download = bsdploy.download:run\n [ansible_paths]\n bsdploy = bsdploy:ansible_paths\n [ploy.plugins]\n bsdploy = bsdploy:plugin\n \"\"\")\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"190772267","text":"import pygame\r\nfrom pygame.sprite import Sprite\r\n\r\n\r\nclass Upgrade(Sprite):\r\n UPGRADE_SIZE = 40\r\n\r\n def __init__(self, screen, settings, pipes, bricks, x, y, up_type):\r\n super().__init__()\r\n self.screen = screen\r\n self.settings = settings\r\n self.bricks = bricks\r\n self.pipes = pipes\r\n self.up_type = up_type\r\n\r\n self.sz = Upgrade.UPGRADE_SIZE\r\n self.mushroom = \"images/Mushroom.png\"\r\n self.fireflower = \"images/Fire_Flower.png\"\r\n self.life_mushroom = \"images/1UP_Mushroom.png\"\r\n self.star = \"images/Star.png\"\r\n self.coin = \"images/Coin.png\"\r\n if self.up_type == 0:\r\n self.image = pygame.image.load(self.mushroom)\r\n if self.up_type == 1:\r\n self.image = pygame.image.load(self.fireflower)\r\n if self.up_type == 2:\r\n self.image = pygame.image.load(self.life_mushroom)\r\n if self.up_type == 3:\r\n self.image = pygame.image.load(self.star)\r\n if self.up_type == 4:\r\n self.image = pygame.image.load(self.coin)\r\n self.image = pygame.transform.scale(self.image, (self.sz, self.sz))\r\n\r\n self.rect = self.image.get_rect()\r\n self.rect.x = x\r\n self.rect.y = y\r\n self.screen_rect = screen.get_rect()\r\n\r\n self.y_change = 0\r\n self.x_change = 0\r\n\r\n self.stop_left = True\r\n self.stop_right = False\r\n\r\n def update(self):\r\n if self.up_type == 0 or self.up_type == 2 or self.up_type == 3:\r\n self.calc_gravity()\r\n self.rect.x += self.x_change\r\n\r\n # Checks if the moving upgrades collide with the pipes from the sides and changes direction if it does\r\n pipe_collide = pygame.sprite.spritecollide(self, self.pipes, False)\r\n for pipe in pipe_collide:\r\n if self.x_change > 0:\r\n self.stop_right = True\r\n self.stop_left = False\r\n self.rect.right = pipe.rect.left\r\n if self.x_change < 0:\r\n self.stop_left = True\r\n self.stop_right = False\r\n self.rect.left = pipe.rect.right\r\n\r\n self.rect.y += self.y_change\r\n\r\n # Checks if the moving upgrades collide with the pipes from the top\r\n pipe_collide = pygame.sprite.spritecollide(self, self.pipes, False)\r\n for pipe in pipe_collide:\r\n if self.y_change > 0:\r\n self.rect.bottom = pipe.rect.top\r\n elif self.y_change < 0:\r\n self.rect.top = pipe.rect.bottom\r\n self.y_change = 0\r\n\r\n # Checks if the moving upgrades collide with the bricks from the top\r\n brick_collide = pygame.sprite.spritecollide(self, self.bricks, False)\r\n for brick in brick_collide:\r\n if self.y_change > 0:\r\n self.rect.bottom = brick.rect.top\r\n elif self.y_change < 0:\r\n self.rect.top = brick.rect.bottom\r\n self.y_change = 0\r\n\r\n if not self.stop_right:\r\n self.move_right()\r\n\r\n if not self.stop_left:\r\n self.move_left()\r\n\r\n def move_right(self):\r\n self.x_change = 1\r\n\r\n def move_left(self):\r\n self.x_change = -1\r\n\r\n def calc_gravity(self):\r\n \"\"\" Calculates gravity of the upgrades\"\"\"\r\n if self.y_change == 0:\r\n self.y_change = 1\r\n else:\r\n self.y_change += .05\r\n if self.rect.y >= self.settings.base_level - self.rect.height and self.y_change >= 0:\r\n self.y_change = 0\r\n self.rect.y = self.settings.base_level - self.rect.height\r\n\r\n def blitme(self):\r\n self.screen.blit(self.image, self.rect)\r\n","sub_path":"upgrade.py","file_name":"upgrade.py","file_ext":"py","file_size_in_byte":3820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"173732994","text":"import logging\n\nfrom dal import autocomplete\nfrom django.conf import settings\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.auth.mixins import (\n PermissionRequiredMixin,\n UserPassesTestMixin,\n)\nfrom django.contrib.messages.views import SuccessMessageMixin\nfrom django.http import Http404\nfrom django.views.generic import (\n CreateView,\n DetailView,\n FormView,\n ListView,\n UpdateView,\n)\nfrom guardian.mixins import (\n LoginRequiredMixin,\n PermissionListMixin,\n PermissionRequiredMixin as ObjectPermissionRequiredMixin,\n)\nfrom rest_framework.permissions import DjangoObjectPermissions\nfrom rest_framework.viewsets import ReadOnlyModelViewSet\nfrom rest_framework_guardian.filters import ObjectPermissionsFilter\n\nfrom grandchallenge.algorithms.forms import (\n AlgorithmForm,\n AlgorithmImageForm,\n AlgorithmImageUpdateForm,\n EditorsForm,\n UsersForm,\n)\nfrom grandchallenge.algorithms.models import (\n Algorithm,\n AlgorithmImage,\n Job,\n Result,\n)\nfrom grandchallenge.algorithms.serializers import (\n AlgorithmImageSerializer,\n AlgorithmSerializer,\n JobSerializer,\n ResultSerializer,\n)\nfrom grandchallenge.cases.forms import UploadRawImagesForm\nfrom grandchallenge.cases.models import RawImageUploadSession\nfrom grandchallenge.subdomains.utils import reverse\n\nlogger = logging.getLogger(__name__)\n\n\nclass AlgorithmCreate(LoginRequiredMixin, PermissionRequiredMixin, CreateView):\n model = Algorithm\n form_class = AlgorithmForm\n permission_required = (\n f\"{Algorithm._meta.app_label}.add_{Algorithm._meta.model_name}\"\n )\n\n def form_valid(self, form):\n response = super().form_valid(form=form)\n self.object.add_editor(self.request.user)\n return response\n\n def get_form_kwargs(self):\n kwargs = super().get_form_kwargs()\n kwargs.update({\"user\": self.request.user})\n return kwargs\n\n\nclass AlgorithmList(PermissionListMixin, ListView):\n model = Algorithm\n permission_required = {\n f\"{Algorithm._meta.app_label}.view_{Algorithm._meta.model_name}\"\n }\n\n def get_queryset(self, *args, **kwargs):\n # Add algorithms that are publicly visible\n qs = super().get_queryset(*args, **kwargs)\n qs |= Algorithm.objects.filter(visible_to_public=True)\n\n return qs\n\n\nclass AlgorithmDetail(\n LoginRequiredMixin, ObjectPermissionRequiredMixin, DetailView\n):\n model = Algorithm\n permission_required = (\n f\"{Algorithm._meta.app_label}.view_{Algorithm._meta.model_name}\"\n )\n raise_exception = True\n\n\nclass AlgorithmUpdate(\n LoginRequiredMixin, ObjectPermissionRequiredMixin, UpdateView\n):\n model = Algorithm\n form_class = AlgorithmForm\n permission_required = (\n f\"{Algorithm._meta.app_label}.change_{Algorithm._meta.model_name}\"\n )\n raise_exception = True\n\n def get_form_kwargs(self):\n kwargs = super().get_form_kwargs()\n kwargs.update({\"user\": self.request.user})\n return kwargs\n\n\nclass AlgorithmUserAutocomplete(\n LoginRequiredMixin, UserPassesTestMixin, autocomplete.Select2QuerySetView\n):\n def test_func(self):\n group_pks = (\n Algorithm.objects.all()\n .select_related(\"editors_group\")\n .values_list(\"editors_group__pk\", flat=True)\n )\n return (\n self.request.user.is_superuser\n or self.request.user.groups.filter(pk__in=group_pks).exists()\n )\n\n def get_queryset(self):\n qs = (\n get_user_model()\n .objects.all()\n .order_by(\"username\")\n .exclude(username=settings.ANONYMOUS_USER_NAME)\n )\n\n if self.q:\n qs = qs.filter(username__istartswith=self.q)\n\n return qs\n\n\nclass AlgorithmUserGroupUpdateMixin(\n LoginRequiredMixin,\n ObjectPermissionRequiredMixin,\n SuccessMessageMixin,\n FormView,\n):\n template_name = \"algorithms/algorithm_user_groups_form.html\"\n permission_required = (\n f\"{Algorithm._meta.app_label}.change_{Algorithm._meta.model_name}\"\n )\n raise_exception = True\n\n def get_permission_object(self):\n return self.algorithm\n\n @property\n def algorithm(self):\n return Algorithm.objects.get(slug=self.kwargs[\"slug\"])\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context.update(\n {\"object\": self.algorithm, \"role\": self.get_form().role}\n )\n return context\n\n def get_success_url(self):\n return self.algorithm.get_absolute_url()\n\n def form_valid(self, form):\n form.add_or_remove_user(algorithm=self.algorithm)\n return super().form_valid(form)\n\n\nclass EditorsUpdate(AlgorithmUserGroupUpdateMixin):\n form_class = EditorsForm\n success_message = \"Editors successfully updated\"\n\n\nclass UsersUpdate(AlgorithmUserGroupUpdateMixin):\n form_class = UsersForm\n success_message = \"Users successfully updated\"\n\n\nclass AlgorithmImageCreate(\n LoginRequiredMixin, ObjectPermissionRequiredMixin, CreateView\n):\n model = AlgorithmImage\n form_class = AlgorithmImageForm\n permission_required = (\n f\"{Algorithm._meta.app_label}.change_{Algorithm._meta.model_name}\"\n )\n raise_exception = True\n\n def get_form_kwargs(self):\n kwargs = super().get_form_kwargs()\n kwargs.update({\"user\": self.request.user})\n return kwargs\n\n @property\n def algorithm(self):\n return Algorithm.objects.get(slug=self.kwargs[\"slug\"])\n\n def get_permission_object(self):\n return self.algorithm\n\n def form_valid(self, form):\n form.instance.creator = self.request.user\n form.instance.algorithm = self.algorithm\n\n uploaded_file = form.cleaned_data[\"chunked_upload\"][0]\n form.instance.staged_image_uuid = uploaded_file.uuid\n\n return super().form_valid(form)\n\n\nclass AlgorithmImageDetail(\n LoginRequiredMixin, ObjectPermissionRequiredMixin, DetailView\n):\n model = AlgorithmImage\n permission_required = f\"{AlgorithmImage._meta.app_label}.view_{AlgorithmImage._meta.model_name}\"\n raise_exception = True\n\n\nclass AlgorithmImageUpdate(\n LoginRequiredMixin, ObjectPermissionRequiredMixin, UpdateView\n):\n model = AlgorithmImage\n form_class = AlgorithmImageUpdateForm\n permission_required = f\"{AlgorithmImage._meta.app_label}.change_{AlgorithmImage._meta.model_name}\"\n raise_exception = True\n\n\nclass AlgorithmExecutionSessionCreate(\n LoginRequiredMixin,\n ObjectPermissionRequiredMixin,\n SuccessMessageMixin,\n CreateView,\n):\n model = RawImageUploadSession\n form_class = UploadRawImagesForm\n template_name = \"algorithms/algorithm_execution_session_create.html\"\n success_message = (\n \"Your images have been uploaded, \"\n \"please check back here to see the processing status.\"\n )\n permission_required = (\n f\"{Algorithm._meta.app_label}.view_{Algorithm._meta.model_name}\"\n )\n raise_exception = True\n\n @property\n def algorithm(self) -> Algorithm:\n return Algorithm.objects.get(slug=self.kwargs[\"slug\"])\n\n def get_permission_object(self):\n return self.algorithm\n\n def get_initial(self):\n if self.algorithm.latest_ready_image is None:\n raise Http404()\n return super().get_initial()\n\n def get_form_kwargs(self):\n kwargs = super().get_form_kwargs()\n kwargs.update({\"user\": self.request.user})\n return kwargs\n\n def form_valid(self, form):\n form.instance.creator = self.request.user\n form.instance.algorithm_image = self.algorithm.latest_ready_image\n return super().form_valid(form)\n\n def get_success_url(self):\n return reverse(\n \"algorithms:jobs-list\", kwargs={\"slug\": self.kwargs[\"slug\"]}\n )\n\n\nclass AlgorithmJobsList(LoginRequiredMixin, PermissionListMixin, ListView):\n model = Job\n permission_required = f\"{Job._meta.app_label}.view_{Job._meta.model_name}\"\n\n @property\n def algorithm(self) -> Algorithm:\n return Algorithm.objects.get(slug=self.kwargs[\"slug\"])\n\n def get_context_data(self, *args, **kwargs):\n context = super().get_context_data(*args, **kwargs)\n context.update({\"algorithm\": self.algorithm})\n return context\n\n def get_queryset(self, *args, **kwargs):\n \"\"\"Filter the jobs for this algorithm.\"\"\"\n qs = super().get_queryset(*args, **kwargs)\n return qs.filter(algorithm_image__algorithm=self.algorithm)\n\n\nclass AlgorithmViewSet(ReadOnlyModelViewSet):\n queryset = Algorithm.objects.all()\n serializer_class = AlgorithmSerializer\n permission_classes = [DjangoObjectPermissions]\n filter_backends = [ObjectPermissionsFilter]\n\n\nclass AlgorithmImageViewSet(ReadOnlyModelViewSet):\n queryset = AlgorithmImage.objects.all()\n serializer_class = AlgorithmImageSerializer\n permission_classes = [DjangoObjectPermissions]\n filter_backends = [ObjectPermissionsFilter]\n\n\nclass JobViewSet(ReadOnlyModelViewSet):\n queryset = Job.objects.all()\n serializer_class = JobSerializer\n permission_classes = [DjangoObjectPermissions]\n filter_backends = [ObjectPermissionsFilter]\n\n\nclass ResultViewSet(ReadOnlyModelViewSet):\n queryset = Result.objects.all()\n serializer_class = ResultSerializer\n permission_classes = [DjangoObjectPermissions]\n filter_backends = [ObjectPermissionsFilter]\n","sub_path":"app/grandchallenge/algorithms/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"459507431","text":"\"\"\"\n10480. Oddities\n\n작성자: xCrypt0r\n언어: Python 3\n사용 메모리: 29,380 KB\n소요 시간: 60 ms\n해결 날짜: 2020년 9월 19일\n\"\"\"\n\ndef main():\n for _ in range(int(input())):\n x = int(input())\n\n print(f'{x} is {\"odd\" if x & 1 else \"even\"}')\n\nif __name__ == '__main__':\n main() \n","sub_path":"src/10/10480.py","file_name":"10480.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"29402026","text":"# OpenStreetMap Networkx library to download data from OpenStretMap\nimport osmnx as ox\n\n# Matplotlib-related stuff, for drawing\nfrom matplotlib.path import Path\nfrom matplotlib import pyplot as plt\nimport matplotlib.patches as patches\nfrom matplotlib.patches import PathPatch\n\n# CV2 & Scipy & Numpy & Pandas\nimport numpy as np\nfrom numpy.random import choice\n\n# Shapely\nfrom shapely.geometry import *\nfrom shapely.affinity import *\n\n# Geopandas\nfrom geopandas import GeoDataFrame\n\n# etc\nimport pandas as pd\nfrom functools import reduce\nfrom tabulate import tabulate\nfrom IPython.display import Markdown, display\nfrom collections.abc import Iterable\n\n# Fetch\nfrom fetch import *\n\n# Drawing functions\n\ndef show_palette(palette, description = ''):\n '''\n Helper to display palette in Markdown\n '''\n\n colorboxes = [\n f'![](https://placehold.it/30x30/{c[1:]}/{c[1:]}?text=)'\n for c in palette\n ]\n\n display(Markdown((description)))\n display(Markdown(tabulate(pd.DataFrame(colorboxes), showindex = False)))\n\ndef get_patch(shape, **kwargs):\n '''\n Convert shapely object to matplotlib patch\n '''\n if type(shape) == Path:\n return patches.PathPatch(shape, **kwargs)\n elif type(shape) == Polygon and shape.area > 0:\n return patches.Polygon(list(zip(*shape.exterior.xy)), **kwargs)\n else:\n return None\n\ndef plot_shape(shape, ax, **kwargs):\n '''\n Plot shapely object\n '''\n if isinstance(shape, Iterable):\n for shape_ in shape:\n plot_shape(shape_, ax, **kwargs)\n else:\n ax.add_patch(get_patch(shape, **kwargs))\n\ndef plot_shapes(shapes, ax, palette = None, **kwargs):\n '''\n Plot collection of shapely objects (optionally, use a color palette)\n '''\n if not isinstance(shapes, Iterable):\n shapes = [shapes]\n\n for shape in shapes:\n if palette is None:\n plot_shape(shape, ax, **kwargs)\n else:\n plot_shape(shape, ax, fc = choice(palette), **kwargs)\n\ndef plot_streets(streets, ax, color = '#f5da9f', background_color = 'white', **kwargs):\n '''\n Plot shapely Polygon (or MultiPolygon) representing streets using matplotlib PathPatches\n '''\n for s in streets if isinstance(streets, Iterable) else [streets]:\n if s is not None:\n ax.add_patch(get_patch(pathify(s), facecolor = color, edgecolor = 'black', **kwargs))\n\ndef plot(\n # Address\n query,\n # Figure parameters\n figsize = (10, 10),\n ax = None,\n title = None,\n # Whether to plot a circle centered around the address; circle params\n circle = False,\n radius = 1000,\n streets_radius = 1000,\n # Street params\n dilate_streets = 5,\n draw_streets = True,\n # Color params\n background_color = 'white',\n background_alpha = 1.,\n palette = None,\n perimeter_lw = 1,\n perimeter_ec = 'black',\n water_ec = 'black',\n land_ec = 'black',\n buildings_ec = 'black',\n # Which layers to plot\n layers = ['perimeter', 'landuse', 'water', 'building', 'streets'],\n # Layer ordering params\n zorder_perimeter = None,\n zorder_landuse = None,\n zorder_water = None,\n zorder_streets = None,\n zorder_building = None,\n # Whether to fetch data using OSM Id\n by_osmid = False,\n by_coordinates = False,\n ):\n\n #############\n ### Fetch ###\n #############\n\n # Geocode central point\n if by_coordinates:\n point = (float(query.split(\",\")[0].strip()), float(query.split(\",\")[1].strip()))\n elif not by_osmid:\n point = ox.geocode(query)\n\n # Fetch perimeter\n perimeter = get_perimeter(query, by_osmid = by_osmid) if not circle else None\n\n # Fetch buildings, land, water, streets\n layers_dict = {}\n for layer in layers:\n if layer == 'perimeter':\n pass\n elif layer == 'streets':\n layers_dict[layer], _ = get_streets(\n **({'point': point, 'radius': streets_radius} if circle else {'perimeter': perimeter}),\n dilate = dilate_streets\n )\n else:\n layers_dict[layer], perimeter_ = get_footprints(\n **({'point': point, 'radius': radius} if circle else {'perimeter': perimeter}),\n footprint = layer\n )\n\n # Project perimeter\n if 'perimeter' in layers:\n layers_dict['perimeter'] = perimeter_ if circle else union(ox.project_gdf(perimeter).geometry)\n\n ############\n ### Plot ###\n ############\n\n if ax is None:\n # if ax is none, create figure\n fig, ax = plt.subplots(figsize = figsize)\n\n # Ajust axis\n ax.axis('off')\n ax.axis('equal')\n ax.autoscale()\n\n # Setup parameters for drawing layers\n layer_kwargs = {\n 'perimeter': {'lw': perimeter_lw, 'ec': perimeter_ec, 'fc': background_color, 'alpha': background_alpha, 'zorder': zorder_perimeter},\n 'landuse': {'ec': land_ec, 'fc': '#53bd53', 'zorder': zorder_landuse},\n 'water': {'ec': water_ec, 'fc': '#a1e3ff', 'zorder': zorder_water},\n 'streets': {'fc': '#f5da9f', 'zorder': zorder_streets},\n 'building': {'ec': buildings_ec, 'palette': palette, 'zorder': zorder_building},\n }\n\n # Draw layers\n for layer in ['perimeter', 'landuse', 'water', 'streets', 'building']:\n if layer in layers_dict:\n plot_shapes(layers_dict[layer], ax, **layer_kwargs[layer])\n\n # Return perimeter\n return layers_dict['perimeter']\n","sub_path":"code/draw.py","file_name":"draw.py","file_ext":"py","file_size_in_byte":5432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"87526199","text":"# step : n-1 or n /= k if n%k==0\n# minimize steps\nn, k = map(int, input().split())\n\nsteps = 0\nwhile n!=1:\n if n%k ==0:\n n/=k\n else: n-=1\n\n steps += 1\nprint(steps)","sub_path":"greedy_until1.py","file_name":"greedy_until1.py","file_ext":"py","file_size_in_byte":178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"547657260","text":"import pygame\nimport shape\nfrom cell import cell\nfrom math import floor\n\nclass GridError(Exception):\n\tpass\n\ndef newgrid(newshape, size):\n\tif isinstance(newshape, shape.hexagon):\n\t\treturn hexgrid(newshape, size)\n\telif isinstance(newshape, shape.circle):\n\t\treturn circlegrid(newshape, size)\n\telif isinstance(newshape, (shape.square, shape.rectangle)):\n\t\treturn grid(newshape, size)\n\traise GridError(\"Shape not supported.\")\n\nclass grid:\n\tdef __init__(self, shape, size, color = (255,255,255), background = (0,0,0)):\n\t\tself.size = { 'width': size[0], 'height': size[1] }\n\t\tself.surface = pygame.Surface(size)\n\t\tself.surface.fill(background)\n\t\tself.color = color\n\t\tself.cells = dict()\n\t\tself.shape = shape\n\t\tself.set_gridsize()\n\t\tself.create_cells()\n\t\tself.draw_cells()\n\n\tdef init(self, shape):\n\t\tself.shape = shape\n\t\tself.set_gridsize()\n\t\tself.create_cells()\n\t\tself.draw_cells()\n\n\tdef set_gridsize(self):\n\t\tself.gridsize = {\n\t\t\t'x': int(floor(self.size['width']/self.shape.width)),\n\t\t\t'y': int(floor(self.size['height']/self.shape.height)),\n\t\t}\n\n\tdef create_cells(self):\n\t\tfor x in range(self.gridsize['x']):\n\t\t\tfor y in range(self.gridsize['y']):\n\t\t\t\tself.cells[(x,y)] = cell((x,y), self.shape)\n\n\tdef draw_cells(self, linewidth = False):\n\t\tfor h in self.cells:\n\t\t\tif linewidth == False:\n\t\t\t\tlinewidth = self.cells[h].linewidth\n\t\t\tpygame.draw.polygon(self.surface, self.color, self.cells[h].get_vertices(), linewidth)\n\n\tdef __setitem__(self, key, value): self.cells[key] = value\n\tdef __getitem__(self, key): return self.cells[key]\n\n\tdef __iter__(self): return iter(self.cells)\n\tdef keys(self): return iter(self.cells.keys())\n\n# Gridtypes\n\nclass circlegrid(grid):\n\tdef draw_cells(self, linewidth = False):\n\t\tfor h in self.cells:\n\t\t\tif linewidth == False:\n\t\t\t\tlinewidth = self.cells[h].linewidth\n\t\t\tpygame.draw.circle(self.surface, self.color, self.cells[h].shape.xy(self.cells[h].pos), self.cells[h].shape.radius, linewidth)\n\nclass hexgrid(grid):\n\tdef set_gridsize(self):\n\t\tself.gridsize = {\n\t\t\t'x': int(floor(self.size['width']/self.shape.side)),\n\t\t\t'y': int(floor(self.size['height']/self.shape.height)),\n\t\t}","sub_path":"rp tools/Hex/grid.py","file_name":"grid.py","file_ext":"py","file_size_in_byte":2105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"254504491","text":"# -*- coding: utf-8 -*-\n###############################################################################\n# Copyright (c), Forschungszentrum Jülich GmbH, IAS-1/PGI-1, Germany. #\n# All rights reserved. #\n# This file is part of the AiiDA-SPEX package. #\n# #\n# The code is hosted on GitHub at https://github.com/JuDFTteam/aiida-spex #\n# For further information on the license, see the LICENSE.txt file #\n# For further information please visit http://www.flapw.de or #\n###############################################################################\n\"\"\"\nHere we run the FleurScfWorkChain\n\"\"\"\n# pylint: disable=invalid-name\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nimport argparse\nfrom pprint import pprint\nfrom ase import io\n\n\nfrom aiida.plugins import DataFactory\nfrom aiida.orm import load_node\nfrom aiida.engine import submit, run\n\n# import the FleurinpgenCalculation\nfrom aiida_fleur.workflows.scf import FleurScfWorkChain\nfrom aiida_fleur.tools.common_fleur_wf import is_code, test_and_get_codenode\n\nDict = DataFactory('dict')\nFleurinpData = DataFactory('fleur.fleurinp')\nStructureData = DataFactory('structure')\n\n### Defaults ###\nwf_para = Dict(dict={'fleur_runmax': 2,\n 'density_converged': 0.001,\n 'energy_converged': 0.002,\n 'mode': 'gw',\n 'itmax_per_run': 9,\n 'use_relax_xml': False,\n 'serial': False})\n\noptions = Dict(dict={'resources': {\"num_machines\": 1, \"num_mpiprocs_per_machine\": 4},\n # 'queue_name': 'devel',\n # 'custom_scheduler_commands': '#SBATCH --account=\"jpgi10\"',\n 'max_wallclock_seconds': 30*60})\n\n\nstruct = io.read(\n '~/workbench/devel/aiida-spex/examples/fleur/Si_mp-165_conventional_standard.cif')\nstructure = StructureData(ase=struct)\n\nparameters = Dict(dict={\n 'comp': {'kmax': 4.5},\n 'kpt': {'div1': 4, 'div2': 4, 'div3': 4}\n})\n\n# submit\ndefault = {'structure': structure,\n 'wf_parameters': wf_para,\n 'options': options,\n 'calc_parameters': parameters\n }\ninputs = {}\n\ninputs['wf_parameters'] = default['wf_parameters']\ninputs['structure'] = default['structure']\ninputs['calc_parameters'] = default['calc_parameters']\ninputs['options'] = default['options']\n\n\ninpgen_code = is_code(44188)\ninputs['inpgen'] = test_and_get_codenode(\n inpgen_code, expected_code_type='fleur.inpgen')\nfleur_code = is_code(44189)\ninputs['fleur'] = test_and_get_codenode(\n fleur_code, expected_code_type='fleur.fleur')\n\nres = submit(FleurScfWorkChain, **inputs)\nprint((\"RUNTIME INFO: {}\".format(res)))\n","sub_path":"examples/fleur/scf.py","file_name":"scf.py","file_ext":"py","file_size_in_byte":2876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"513378092","text":"\"\"\"Gothons from planet percal #25\"\"\"\n\n\"\"\"\n\nAliens have invaded a spaceship and our hero has to go through a maze of rooms\ndefeating them so he can get to an escape pod and escape to a planet below.\nThe game will be like a zork/adventure type with text outputs and funny\nways to die. The game will involve an engine that runs a map full of rooms\nos scenes. Each room will print it's description when the player enters it and\nthen tell the engine what room to run next out of the map.\n\nscenes and descriptions\n\n1 death -- This is when the player dies and should be something funny.\n2 central corridor -- This is the starting point and already has a gothon there\nwhich the player has to defeat with a joke before continuing.\n3 laser weapon armory -- this is where the hero gets a neutron bomb to blow up\nthe ship before getting to the escape pod. It has a keypad the hero has to guess the number for.\n4 the bridge -- this is another battle scene with a gothon where the hero places the bomb.\n5 escape pod -- this is where the hero excapes but only after guessing the right escape pod.\n\nlist of nouns\n\nAliens\nspaceship\nhero\nescape pod\nscenes\nrooms\ncentral corridor\nlaser weapon armory\nbridge\ngothon\nbomb\nplanet\nmaze\nengine\nmap\ndeath\n\n\nList of verbs\n\n1 Run - engine\n2 get - scene\n3 enter - scene\n4\n\n\nCreate a class hierarchy and object map for the concepts.\n\nnouns are *\nverbs are -\n\n* Map\n - next scene\n - opening scene\n* Engine\n - play\n* Scene\n - enter\n * Death\n * Central corridor\n * Laser weapon armory\n * The bridge\n * Escape pod\n\n\"\"\"\n# import your shit\nfrom sys import exit\nfrom random import randint\nfrom textwrap import dedent\n\n\n# create a scene class\nclass Scene(object):\n def enter(self):\n print(\"This scene is not yet configured.\")\n print(\"Sub-class it and implement enter().\")\n exit(1)\n\n\n# create an engine to play the game\nclass Engine(object):\n # define an init function that collects a scene_map attribute\n\n def __init__(self, scene_map):\n self.scene_map = scene_map\n\n # create a function to play the game.\n def play(self):\n # call the opening_scene function on the given scene map\n # and store as current_scene variable\n # self.scene map represents an instance of the map class\n current_scene = self.scene_map.opening_scene()\n # call the next_scene function on the given scene map\n # and store as last_scene variable\n last_scene = self.scene_map.next_scene('finished')\n # while the current scene is not the last scene, run while loop\n while current_scene != last_scene:\n\n # enter the current scene and\n #store the return string as the next scene name.\n next_scene_name = current_scene.enter()\n # change the current scene to the returned scene name\n # from the next scene name variable.\n current_scene = self.scene_map.next_scene(next_scene_name)\n # run the last scene when the current scene is the last scene\n current_scene.enter()\n\n\nclass Death(Scene):\n\n quips = [\n \"You died. You kinda suck at this.\",\n \"Your president would be proud.. if he were smarter.\",\n \"Such a face-butt.\",\n \"I have a small puppy that's better at this\",\n \"You're worse than deji's jokes.\"\n ]\n def enter(self):\n print(self.quips[randint(0, len(self.quips)-1)])\n exit(1)\n\n\n\nclass CentralCorridor(Scene):\n def enter(self):\n print(dedent(\"\"\"\n The gothons of planet percal #25 have invaded your ship and\n destroyed your entire crew. You are the last surviving member\n and your mission is to get the neutron destruct bomb from the\n weapons armory, put it in the bridge, and blow up the ship after\n getting into an escape pod. You're running down the central\n corridor to the weapons armory when a gothon jumps out.\n Red scaly skin, dark grimy teeth and evil clown costume flowing\n around his hate filled body. He's blocking the way to the armory\n about to pull a weapon to blast you.\n \"\"\"))\n action = input(\"> \")\n if action == \"shoot\":\n print(dedent(\"\"\"\n Quick on the draw, you yank out your blaster and fire it at the\n gothon. His clown costume is flowing around his body, which throws\n off your aim. Your laser hits his costume but misses him entirely\n This completely ruins his brand new costume his mother got him,\n which causes him to fly into an insane rage and blast you\n repeatedly in the face until you are very dead. Then he eats you.\n\n \"\"\"))\n return 'death'\n elif action == \"dodge\":\n print(dedent(\"\"\"\n Like a world class boxer you dodge,\tweave, slip\tand slide right\n as the gothon's laser cracks a laser past your head. In the\n middle of your artful dodge, your foot slips and you bang your\n head on the metal wall and pass out. You wake up shortly after\n only to die as the gothon stomps on your head and eats you.\n \"\"\"))\n return 'death'\n elif action == \"tell a joke\":\n print(dedent(\"\"\"\n Luckily, you were forced to learn gothon insults in the academy.\n You tell the one gothon joke you know: iunv jdnuc jhfubch fur\n fjjr jkiuu jfhuv uyy rjhv jhbf jhhv, jhu hvbuy wuye znzmlv nfj.\n The gothon stops, tries not to laugh, then bursts out laughing\n and can't move. While he's laughing, you run up and shoot him\n square in the face, then jump through the weapons armory door.\n \"\"\"))\n return \"laser_weapon_armory\"\n else:\n print(\"Does not compute!\")\n return 'central_corridor'\n\n\n\nclass LaserWeaponArmory(Scene):\n def enter(self):\n print(dedent(\"\"\"\n You do a dive roll into the weapons armory, crouch and scan the room\n for more gothons that might be hiding. It's dead quiet, too quiet.\n You stand and run to the far side of the room and find the neutron\n bomb in it's container. There's a keypad code on the box and you need\n the code to get the bomb out of the box. If you get the code wrong\n ten times, the lock closes forever and you can't get the bomb.\n The code is 3-digits.\n \"\"\"))\n code = f\"{randint(0,1)}{randint(1,2)}{randint(2,3)}\"\n guess = input(\"[KEYPAD]> \")\n guess_count = 0\n while guess != code and guess_count < 10:\n print(\"BZZZDDDD\")\n guess_count += 1\n guess = input(\"[KEYPAD]> \")\n if guess == code:\n print(dedent(\"\"\"\n The container clicks open and the seal breaks, letting out gas.\n You grab the neutron bomb and run as fast as you can to the bridge\n where you must place it correctly.\n \"\"\"))\n return 'the_bridge'\n else:\n print(dedent(\"\"\"\n The lock buzzes one last time and then you hear a sickening\n melting sound as the mechanism is fused together. You decide to\n sit there, and finally the gothons blow up the ship and you die.\n \"\"\"))\n return 'death'\n\n\n\nclass TheBridge(Scene):\n def enter(self):\n print(dedent(\"\"\"\n You burst onto the bridge with the neutron destruct bomb under your\n arm and surprise 5 gothons who are trying to take control of the ship.\n Each of them has an even uglier clown costume than the last. They\n haven't pulled their weapons out yet, as they see the active bomb\n under your arm and don't want to set it off.\n \"\"\"))\n action = input(\"> \")\n if input == \"throw the bomb!\":\n print(dedent(\"\"\"\n You throw the bomb.\n \"\"\"))\n return 'death'\n elif action == 'slowly place the bomb':\n print(dedent(\"\"\"\n You sucessfully place the bomb.\n \"\"\"))\n return 'escape_pod'\n else:\n print(dedent(\"\"\"Does not compute\"\"\"))\n return 'the_bridge'\n\n\n\nclass EscapePod(Scene):\n def enter(self):\n print(dedent(\"\"\"\n You rush to the ship and have to guess one pod.\n \"\"\"))\n good_pod = randint(1,5)\n guess = input(\"POD[#]> \")\n if int(guess) != good_pod:\n print(dedent(\"You fake brah\"))\n return 'death'\n else:\n print(dedent(\"\"\"WE MOVE!\"\"\"))\n return 'finished'\n\n\n\nclass Finished(Scene):\n def enter(self):\n print(\"You won. Good job!\")\n return 'finished'\n\n\nclass Map():\n\n scenes = {\n 'central_corridor': CentralCorridor(),\n 'laser_weapon_armory': LaserWeaponArmory(),\n 'the_bridge': TheBridge(),\n 'escape_pod': EscapePod(),\n 'death': Death(),\n 'finished': Finished()\n\n }\n\n def __init__(self, start_scene):\n self.start_scene = start_scene\n # function to get the scene function from the scenes dictionary.\n # this function allows the coder to pick scenes from any point in the\n # scene map.\n def next_scene(self, scene_name):\n self.scene_name = scene_name\n val = self.scenes.get(self.scene_name)\n # return the scene function\n return val\n # function to give the start scene key to the nextscene function\n # and return the function from the scenes dictionary.\n # this function basically returns just the value of the key given as the\n # init function attribute. i.e the opening scene in this case.\n def opening_scene(self):\n return self.next_scene(self.start_scene)\n\n\n\na_map = Map('central_corridor')\na_game = Engine(a_map)\n\na_game.play()\n","sub_path":"lpthw/ex43.py","file_name":"ex43.py","file_ext":"py","file_size_in_byte":10008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"452253462","text":"from die import Die\nfrom plotly.graph_objs import Bar, Layout\nfrom plotly import offline\n\ndie1 = Die()#default six sided die\ndie2 = Die(10)#lets roll a 10 sided die\n\nresults = []\nfor roll_num in range(50_000):\n result = die1.roll() + die2.roll()\n results.append(result)\n\nfrequencies = []\nmax_result = die1.num_sides + die2.num_sides\nfor value in range(2, max_result+1):\n frequency = results.count(value)\n frequencies.append(frequency)\n\nprint(frequencies)\n\n\n#Visualise the results\nx_values = list(range(2, max_result+1))\ndata = [Bar(x=x_values, y=frequencies)]\n\nx_axis_config = {'title': 'Result', 'dtick': 1}\ny_axis_config = {'title': 'Frequency of Results'}\n\nmy_layout = Layout(title='Result of rolling a D6 and a D10 50_000 times', xaxis=x_axis_config, yaxis=y_axis_config)\noffline.plot({'data': data, 'layout': my_layout}, filename='d6_d10.html')\n","sub_path":"dv_rolling_dice/die_visual.py","file_name":"die_visual.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"124762670","text":"from django.urls import path, re_path\nfrom youtor.settings import base\nfrom django.contrib.auth import views as auth_views\nfrom . import views\nfrom django.conf.urls import url\n\nurlpatterns = [\n # common urls\n path('', views.index, name='index'),\n re_path('^login/$', views.user_login, name='login'),\n path('faq', views.faq, name='faq'),\n path('contact', views.contact, name='contact'),\n path('register', views.register, name='register'),\n re_path(r'^activate/(?P[0-9A-Za-z_\\-]+)/(?P[0-9A-Za-z]{1,6}-[0-9A-Za-z]{1,32})/$',views.activate, name='activate'),\n path('dashboard', views.dashboard_view, name='dashboard'),\n path('user_profile', views.user_profile_view, name='user_profile'),\n path('logout', auth_views.LogoutView.as_view(next_page=base.LOGOUT_REDIRECT_URL), name='logout'),\n path('change_password', views.change_password, name='change_password'),\n\n\n # tutor urls\n path('create_tutor_profile', views.create_tutor_profile, name='create_tutor_profile'),\n path('remove_subs_tags', views.remove_subs_tags, name='remove_subs_tags'),\n\n path('schedule', views.offer_scheduling, name='schedule'),\n path('create_slots', views.create_event, name='create_slot'),\n path('delete_slots', views.delete_events, name='delete_slots'),\n \n\n # student urls\n re_path('^youtor_app/tutor_search/$',views.tutor_search_result),\n re_path('^youtor_app/tutor_search_result_price/$',views.tutor_search_result_price),\n re_path('^tutor_profile/(?P[\\w-]+)/$', views.tutor_detailed_view, name='tutor_detailed_view'),\n\n\n # Payment urls\n path('proceed_to_checkout', views.proceed_to_checkout, name='proceed_to_checkout'),\n path('process_tution_booking', views.process_tution_booking, name='process_tution_booking'),\n path('charge/', views.payment_done, name='charge'),\n path('payment_cancelled/', views.payment_canceled, name='payment_cancelled'),\n\n # ----------- booking ---------------------------\n path('booking',views.booking,name='booing'),\n path('mybooking',views.StudentBooking,name='student-booking'),\n\n # ------------ Star Rating ---------------------------\n path('rate/',views.TutorRate,name='TutorRate'),\n path('review/',views.UserReview,name='UserReview'),\n path('search-rating/',views.TutorSearchRating,name='TutorSearchRating'),\n path('sort/',views.TutorSortBy,name='TutorSortBy'),\n]","sub_path":"youtor_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"524570049","text":"import datetime\nimport hashlib\nimport json\nimport pandas as pd\nfrom descriptors import cachedproperty\nfrom contextlib import contextmanager\nfrom sqlalchemy.orm import Session\n\n@contextmanager\ndef scoped_session(db_engine):\n \"\"\"Provide a transactional scope around a series of operations.\"\"\"\n session = Session(bind=db_engine)\n try:\n yield session\n session.commit()\n except:\n session.rollback()\n raise\n finally:\n session.close()\n\n\ndef filename_friendly_hash(inputs):\n def dt_handler(x):\n if isinstance(x, datetime.datetime) or isinstance(x, datetime.date):\n return x.isoformat()\n raise TypeError(\"Unknown type\")\n\n return hashlib.md5(\n json.dumps(inputs, default=dt_handler, sort_keys=True).encode(\"utf-8\")\n ).hexdigest()\n\n\ndef get_cohort(sql, conn, chunk_size=10000, offset=0):\n dfs = []\n for chunk in pd.read_sql_query(sql, conn, chunksize=chunk_size):\n dfs.append(chunk)\n full_df = pd.concat(dfs)\n return full_df.reset_index(drop=True)\n\n\ndef create_label(df, label='label_withdrawn', dropna=False, threshold=0.5):\n if label == 'label_withdrawn':\n if dropna:\n df = df.dropna(subset=['label_withdrawn'])\n df['label_value'] = df['label_withdrawn'].apply(lambda x: 1 if x is True else 0)\n\n elif label == 'label_separation':\n if dropna:\n df = df.dropna(subset=['label_separation'])\n df['label_value'] = df['label_separation'].apply(lambda x: 1 if x is True else 0)\n\n elif label == 'label_managed':\n if dropna:\n df = df.dropna(subset=['label_managed'])\n df['label_value'] = df['label_managed'].apply(lambda x: 1 if x is True else 0)\n\n elif label == 'label_unmanaged':\n if dropna:\n df = df.dropna(subset=['label_unmanaged'])\n df['label_value'] = df['label_unmanaged'].apply(lambda x: 1 if x is True else 0)\n\n elif label == 'label_managed_unmanaged':\n df = df.dropna(subset=['label_managed', 'label_unmanaged'], how='all')\n tt = ~((df['label_managed'] == True) & (df['label_unmanaged'] == True))\n ff = ~((pd.isna(df['label_managed'])) & (pd.isna(df['label_unmanaged'])))\n df = df[((df['label_managed'] != False) | (df['label_unmanaged'] != False)) & (~((df['label_managed'] == True) & (df['label_unmanaged'] == True)))]\n df['label_value'] = df['label_managed'].apply(lambda x: 1 if x is True else 0 )\n elif label == 'label_chargeability':\n if dropna:\n df = df.dropna(subset=['label_chargeability'])\n df = df[df['label_chargeability'] > 0]\n df['label_value'] = df['label_chargeability'].apply(lambda x: 1 if x <= threshold else 0)\n df = df.set_index('peoplekey')\n return df\n\n\ndef convert_to_series(column):\n if not column:\n return pd.Series()\n try:\n keys, values = zip(*[item for item in column.items()])\n except:\n try:\n keys, values = zip(*[(item, 1) for item in column if item is not None])\n except:\n return pd.Series()\n else:\n return pd.Series()\n return pd.Series(values, index=keys)\n\n\ndef expand_features(df, column, prefix):\n df_copy = df.copy()\n single_df = df_copy[[column]]\n expand = pd.concat([single_df, single_df[column].apply(convert_to_series)], axis=1)\n expand = expand.drop([column], axis=1)\n expand = expand.rename(columns=lambda x: prefix + \"_\" +\"_\".join(x.lower().split()))\n df_copy = df_copy.drop([column], axis=1)\n df_copy = pd.concat([df_copy, expand], axis=1)\n return df_copy\n\n\ndef create_feature_vectors(df, feature_list, columns_not_impute=None, impute=None):\n features = df[feature_list]\n\n # Dummification\n if \"gender\" in feature_list:\n features = pd.get_dummies(features, columns=['gender'], prefix=['gender'], dummy_na=True)\n\n if \"talentsegmentdesc\" in feature_list:\n features = pd.get_dummies(features, columns=['talentsegmentdesc'], prefix=['talentsegmentdesc'], dummy_na=True)\n\n if \"crossworkforcecareerleveldesc\" in feature_list:\n features = pd.get_dummies(features, columns=['crossworkforcecareerleveldesc'], prefix=['crossworkforcecareerleveldesc'], dummy_na=True)\n\n if \"highest_degree\" in feature_list:\n features = pd.get_dummies(features, columns=['highest_degree'], prefix=['highest_degree'], dummy_na=True)\n\n if \"organizationlevel2desc\" in feature_list:\n features = pd.get_dummies(features, columns=['organizationlevel2desc'], prefix=['organizationlevel2desc'], dummy_na=True)\n\n if \"jobcodedesc\" in feature_list:\n features = pd.get_dummies(features, columns=['jobcodedesc'], prefix=['jobcodedesc'], dummy_na=True)\n\n if \"prev_jobcodedesc\" in feature_list:\n features = pd.get_dummies(features, columns=['prev_jobcodedesc'], prefix=['prev_job'], dummy_na=True)\n\n # Specialization break-down dummification\n if \"specialization_counts\" in feature_list:\n features = expand_features(features, column=\"specialization_counts\", prefix=\"sp\")\n\n # assessedskilldescprof break-down dummification\n if \"assessedskilldescprof\" in feature_list:\n features = expand_features(features, column=\"assessedskilldescprof\", prefix=\"assessed\")\n\n # capability\n if \"capability_ever\" in feature_list:\n features = expand_features(features, column=\"capability_ever\", prefix=\"cap\")\n\n # Imputeation\n if callable(impute):\n features = impute(features)\n if features.isnull().any().sum() > 0:\n print(\"Imputation not complete! There is columns still have null value!\")\n else:\n for c in features.columns:\n if \"sp\" in c:\n features[c].fillna(0, inplace=True)\n try:\n features['num_assessed_skill'].fillna(0, inplace=True)\n features['percent_time_on_project_avg'].fillna(0, inplace=True)\n except KeyError as e:\n print(e)\n\n features = features.rename(columns=lambda x: \"_\".join(x.lower().split()))\n features[features.columns.difference(columns_not_impute)] = features[features.columns.difference(columns_not_impute)].fillna(0)\n return features\n\n\nclass FeatureMap(object):\n def __init__(self, feature_groups):\n self.feature_groups=feature_groups\n self.all_features = self.mapping.keys()\n\n @cachedproperty\n def mapping(self):\n mapping = {}\n for g, features in self.feature_groups.items():\n for f in features:\n mapping[f] = g\n return mapping\n\n def feature_to_group(self, feature):\n try:\n group = self.mapping[feature]\n return group\n except KeyError:\n for f in self.all_features:\n if re.search(f\"^{f}\", feature):\n group = self.mapping[f]\n return group\n return Exception(f\"{feature} is not on the list\")\n","sub_path":"pipeline/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"628374696","text":"class Idade:\n def __init__(self,ano, mes, dia):\n self.ano = ano\n self.mes = mes\n self.dia = dia\n\n self.anoA = 2019\n self.mesA = 4\n self.diaA = 12\n\n\n self.totAnos = 0\n self.totDias = 0\n\n def totalAnos(self):\n self.totAnos = (2019 - self.ano) - 1\n if self.mesA >= self.mes:\n self.totAnos += 1\n\n return self.totAnos\n\n def totalDias(self):\n self.totAnos = 0\n # Conta os anos\n self.totDias = (365 * self.totalAnos())\n\n # Conta os meses\n i = 1\n while i < self.mesA:\n self.totDias += 31\n i += 1\n\n # Conta ate os dias atuais\n self.totDias += self.diaA\n\n # ======================Precisao======================================\n # contagem no mes do nascimento\n dia= self.dia\n if self.mes % 2 == 0:\n while dia <= 31:\n self.totDias += 1\n dia += 1\n\n else:\n while dia <= 30:\n self.totDias += 1\n dia += 1\n\n # contagem ate o final do ano\n mes = self.mes\n while mes < 12:\n self.totDias += 31\n mes += 1\n return self.totDias\n","sub_path":"DesenvolvimentoDeSistemas_Python/8 Exemplos POO/D3 idade/idade.py","file_name":"idade.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"408743853","text":"\"\"\"Given a list of non negative integers, arrange them such that they form the largest number.\n\nFor example:\n\nGiven [3, 30, 34, 5, 9], the largest formed number is 9534330.\n\nNote: The result may be very large, so you need to return a string instead of an integer.\n\"\"\"\n\ndef compare(a,b):\n x = \"\"; x = x + str(a); x = x + str(b)\n y = \"\"; y = y + str(b); y = y + str(a)\n if (int(x) < int(y)): return 1\n elif (int(x) > int(y)): return -1\n else: return 0\n\nclass Solution:\n # @param A : tuple of integers\n # @return a strings\n def largestNumber(self, A):\n B = sorted(A,cmp=compare)\n ans = \"\"\n if B[-1] == 0: return \"0\"\n for i in B:\n ans = ans + str(i)\n return ans","sub_path":"Arrays/LARGESTNUM.py","file_name":"LARGESTNUM.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"617974702","text":"from django.urls import reverse\nfrom django.http import QueryDict\n\n\ndef memory_url(request, name, *args, **kwargs):\n \"\"\"\n 生成带有原搜索条件的url,替代了原来模板中的url\n :param request:\n :param name:\n :return:\n \"\"\"\n basic_url = reverse(name, args=args, kwargs=kwargs) # reverse带参数的反向解析\n # 对原url是有 ?xxx 携带参数进行判断,有参数进行拼接\n if request.GET:\n # 拼接\n query_dict = QueryDict(mutable=True)\n query_dict['_filter'] = request.GET.urlencode()\n\n return '{}?{}'.format(basic_url, query_dict.urlencode())\n return basic_url\n\ndef memory_reverse(request, name, *args, **kwargs):\n \"\"\"\n 反向生成url\n 在url中将原搜索条件获取,拼接返回\n :param request:\n :param name:\n :param args:\n :param kwargs:\n :return:\n \"\"\"\n basic_url = reverse(name, args=args, kwargs=kwargs)\n origin_url = request.GET.get('_filter')\n if origin_url:\n basic_url = \"{}?{}\".format(basic_url, origin_url)\n return basic_url\n","sub_path":"rbac/rbac/service/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"221707446","text":"import numpy as np\nimport cmath\nimport sys\n\n\"\"\" to_polarとto_rectで処理方法を合わせたほうが良いような気がする。 \"\"\"\n\"\"\" 極形式にするのはnumpyでもできるんだけどね。cmathで合わせるほうが安心じゃん? \"\"\"\ndef to_polar(comp):\n if len(comp.shape) > 2:\n sys.exit(\"The input array shape is too large. Please put it in two dimensions.\")\n\n # z = np.sqrt(pow(comp.real, 2) + pow(comp.imag, 2)).astype(np.float32)\n # z = np.abs(comp)\n # angle = np.angle(comp).astype(np.float32)\n\n z = []\n angle = []\n for c in comp:\n for _c in c:\n _z, _a = cmath.polar(_c)\n z.append(_z)\n angle.append(_a)\n\n z = np.array(z, dtype=np.float32).reshape(comp.shape)\n angle = np.array(angle, dtype=np.float32).reshape(comp.shape)\n\n return z, angle\n\n\ndef to_rect(z, angle, target_shape):\n comp = []\n for (Z, Angle) in zip(z, angle):\n for (_z, _angle) in zip(Z, Angle):\n comp.append(cmath.rect(_z, _angle))\n\n comp = np.array(comp, dtype=np.complex64).reshape(target_shape)\n\n return comp\n","sub_path":"complex.py","file_name":"complex.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"21887657","text":"import datetime\nimport sys\nimport ingest_db\nfrom data import sessionfactory\nfrom services import data_service\nfrom infrastructure.numbers import try_int\nfrom infrastructure.switchlang import switch\nfrom time import sleep\nuser = None\n\ndef main():\n\n setup_db()\n list_restraunts()\n\n\n order_rating_fun()\n\n # options = 'Enter a command, [o]rder, [a]vailable, [l]ocate, [h]istory, e[X]it: '\n # cmd = \"NOT SET\"\n\n # while cmd:\n # cmd = input(options).lower().strip()\n # with switch(cmd) as s:\n # #s.case('o', order_food)\n # s.case('a', list_restraunts)\n # #s.case('l', list_menu)\n # #s.case('h', my_history)\n # #s.case(['x', ''], exit_app)\n # #s.default(lambda: print(f\"Don't know what to do with {cmd}.\"))\n #\n\ndef setup_db():\n global user\n #sessionfactory.global_init('restrauntapp.sqlite')\n sessionfactory.global_init('orders')\n sessionfactory.create_tables()\n\n # uncomment it later - debugging going\n ingest_db.import_if_empty()\n user = data_service.get_default_user()\n\n\ndef list_restraunts(location='kolkata'):\n user = data_service.get_default_user()\n #print(user)\n restraunt_near = data_service.find_restraunts_near_me(location)\n for rest in restraunt_near:\n print(rest.name)\n\n #return restraunt_near\n # to be done\n\ndef order_rating_fun():\n while True:\n sleep(60)\n data_service.book_order()\n\n\n#def book_order():\n\n\n # to be done\n\n# def order_history():\n#\n#\n# # to be done\n#\n# def orders_in_process():\n#\n#\n# # to be done\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"program.py","file_name":"program.py","file_ext":"py","file_size_in_byte":1631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"148297450","text":"# coding: utf-8\n# 未续缴农保名单,txt转excel,删掉0\n\nimport openpyxl,os,time\nfrom openpyxl.styles import Border, Side\nimport jingle.demo.work.SkData as SkData\n\ndir = 'C:/Users/Administrator/Desktop/农保未续缴明细/'\nstrTime = time.strftime(\"%Y%m%d\", time.localtime())\n\nwbook = openpyxl.Workbook()\nwbook.remove(wbook['Sheet'])# 删除默认的Sheet\nidToAddress = {} #地址信息\ndef readIdToAddressInfo():\n kv = dict()\n villageBook = openpyxl.load_workbook('C:/Users/Administrator/Desktop/常用文件/部门数据.xlsx')\n for row in villageBook.worksheets[0].values:\n address = row[0]\n if len(address.split('村委会'))<2:\n continue\n kv[row[6]] = address.split('村委会')[1]\n return kv\n\ndef convertOneVillage(txtFullPath,destFileName=None):\n # txtPath = dir + countryName +'.txt'\n txtFile = open(txtFullPath, encoding='gbk')\n filePath, txtName = os.path.split(txtFullPath) # 分离路径和文件名\n countryName = str(txtName.split('.')[0]) # 分离村名\n sheet = wbook.create_sheet(countryName[:2],0)\n tableHead = ['序号', '姓名', '身份证('+countryName[:2]+')', '档次', '账号', '已交月份']\n sheet.append(tableHead)\n # 数据\n rowNum = 2\n for line in txtFile:\n what = line.split('|')\n # print(type(what),what)\n if line.startswith('#'): continue\n if what[13] == '0': continue #删掉已交0期的数据\n sheet.cell(rowNum, 1).value = rowNum - 1\n sheet.cell(rowNum, 2).value = what[2]\n sheet.cell(rowNum, 3).value = what[3]\n sheet.cell(rowNum, 4).value = what[6]\n sheet.cell(rowNum, 5).value = what[10]\n sheet.cell(rowNum, 6).value = what[13]\n rowNum = rowNum + 1\n # 边框\n thin = Side(border_style=\"thin\", color=\"000000\")\n border = Border(left=thin, right=thin, top=thin, bottom=thin)\n for row in sheet['A1:F%s'%(rowNum-1)]:\n for cell in row:\n cell.border = border\n # 列宽\n sheet.column_dimensions['A'].width = 4\n sheet.column_dimensions['B'].width = 8\n sheet.column_dimensions['C'].width = 20\n sheet.column_dimensions['D'].width = 22\n sheet.column_dimensions['E'].width = 20\n sheet.column_dimensions['F'].width = 8\n\n print('%s %s end'%(countryName,rowNum-2))\n destFullFilePath = dir + countryName +'.xlsx'\n if destFileName != None: # 如果规定了文件名,就不用txt文件名作为文件名,用于多个村一个表\n destFullFilePath = dir + destFileName + '.xlsx'\n wbook.save(destFullFilePath)\n print(destFullFilePath)\n\ndef convertManyVillage(txtFullPath):\n destDir = txtFullPath.split('.')[0]\n if not os.path.exists(destDir):\n os.mkdir(destDir)\n txtFile = open(txtFullPath, encoding='gbk')\n tableHead = ['序号', '村委会','姓名', '身份证号', '未交农保档次', '银行账号', '已交月数','村小组']\n for v in SkData.villages:\n v.book = openpyxl.Workbook() # 每个村单独的excel文件\n v.book.worksheets[0].append(tableHead)\n v.sumSheet = wbook.create_sheet(v.name) # 一个excel文件,每个村一个工作表\n v.sumSheet.append(tableHead)\n\n # 遍历每一行\n for line in txtFile:\n r = line.split('|')\n if line.startswith('#'): continue\n if r[13] == '0': continue #删掉已交0期的数据,有可能是特殊参保人群\n # print(type(r), r[8])\n v = SkData.idToVillage[r[8]]\n v.count = v.count +1\n bankAccount = '未绑定'\n address = idToAddress.get(r[3],'未找到')\n stage = r[6].replace('按年缴费第','').replace(':','')\n if r[10]:\n bankAccount = '***' + r[10][-5:-1]\n v.book.worksheets[0].append([v.count,v.name,r[2],r[3],stage,r[10],r[13],address]) # 单独村文件不打码银行账号,方便村干部代存钱\n v.sumSheet.append([v.count,v.name,r[2],r[3][0:10]+'***',stage,bankAccount,r[13],address])\n\n countAll = 0\n for v in SkData.villages:\n SkData.setBorderWidth(v.book.worksheets[0], 25) # 设置边框直到25行\n SkData.setBorderWidth(v.sumSheet, 25) # 设置边框直到25行\n v.book.save(destDir +'/'+v.name+'本年未交农保'+strTime+'.xlsx')\n countAll = countAll + v.count\n wbook.save(destDir +'/水口镇各村本年未续交农保'+strTime+'.xlsx')\n print('转换了%s条数据'%countAll)\n\nif __name__ == '__main__':\n print('启动')\n idToAddress = readIdToAddressInfo() # 读取地址信息\n print('读取地址完毕')\n fileName = '水口镇未续缴农保_20201225.txt'\n fullFilePath = dir + fileName\n if os.path.isdir(fullFilePath): # 如果是目录,遍历目录下的所有文件转成excel\n for oneTxtFile in os.listdir(fullFilePath):\n convertOneVillage(fullFilePath + '/' + oneTxtFile, fileName)\n else:\n # convertOneVillage(fullFilePath) # 只转换一个村,一个文本文件\n convertManyVillage(fullFilePath) # 转换多村,一个文本文件\n print('完成')","sub_path":"jingle/demo/work/ConvertNotPayMan.py","file_name":"ConvertNotPayMan.py","file_ext":"py","file_size_in_byte":5062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"60222368","text":"import pandas as pd\r\nimport random\r\nimport matplotlib.pyplot as plt\r\n\r\nflights = pd.read_csv(\"Airlines.csv\")\r\n\r\nx1 = list(flights[flights['name'] == 'United Air Lines Inc.']['arr_delay'])\r\nx2 = list(flights[flights['name'] == 'JetBlue Airways']['arr_delay'])\r\nx3 = list(flights[flights['name'] == 'ExpressJet Airlines Inc.']['arr_delay'])\r\nx4 = list(flights[flights['name'] == 'Delta Air Lines Inc.']['arr_delay'])\r\nx5 = list(flights[flights['name'] == 'American Airlines Inc.']['arr_delay'])\r\n\r\n# Assign colors for each airline and the names\r\ncolors = ['#E69F00', '#56B4E9', '#F0E442', '#009E73', '#D55E00']\r\nnames = ['United Air Lines Inc.', 'JetBlue Airways', 'ExpressJet Airlines Inc.',\r\n 'Delta Air Lines Inc.', 'American Airlines Inc.']\r\n\r\ncol_a = list(x1)\r\ncol_b = list(x2)\r\ncol_c = list(x3)\r\ncol_d = list(x4)\r\ncol_e = list(x5)\r\n\r\ni = 0\r\n\r\n\r\nfor i in range(0, 20):\r\n\r\n while i < 1000:\r\n i = i + 1\r\n\r\n sample1 = random.sample(col_a, i)\r\n sample2 = random.sample(col_b, i)\r\n sample3 = random.sample(col_c, i)\r\n sample4 = random.sample(col_d, i)\r\n sample5 = random.sample(col_e, i)\r\n\r\n plt.hist([sample1, sample2, sample3, sample4, sample5], color=colors, edgecolor='black', bins=int(180/15), label=names)\r\n plt.legend()\r\n plt.show()\r\n","sub_path":"Central Limit Theorem.py","file_name":"Central Limit Theorem.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"150047039","text":"import numpy as np\nimport random\nimport keras\nfrom keras.layers import *\nfrom keras.models import Sequential\n\n# now execute the q learning\n\ndef encodeLabels(labels, num_classes):\n LABELS_MIN = -1\n LABELS_MAX = 1\n\n y = np.zeros(num_classes)\n idx = np.interp(labels, [LABELS_MIN, LABELS_MAX], [0, num_classes-1])\n y[int(round(idx))] = 1\n\n return y\n\ndef main():\n y = 0.95\n eps = 0.5\n decay_factor = 0.999\n lr = 0.8\n num_states = 5\n num_actions = 5\n hidden_units = num_states*2\n\n target_state = 2\n rewards = [0, 0, 5, 0, 0]\n correction = np.linspace(-1,1,num_actions)\n q_table = np.zeros((num_states, num_actions))\n\n model = Sequential()\n model.add(InputLayer(batch_input_shape=(1, num_states)))\n model.add(Dense(hidden_units, activation='relu'))\n model.add(Dense(num_actions, activation='linear'))\n model.compile(loss='mse', optimizer='adam', metrics=['mae'])\n\n s = 0\n a = 0\n\n # ... get new frame #\n #new_s = decodeImg(frame)\n angle = 0.0\n new_angle = 0.0\n i = 0\n done = False\n steps = 0\n while(done==False):\n #for _ in range(2000):\n # get reward\n new_s = np.argmax(encodeLabels(new_angle, 5))\n\n r = rewards[new_s]\n print(\"State: {}, angle: {:.2}, correction: {}, new_angle: {:.1}, reward: {}, i: {}\".format(new_s, angle, correction[a], new_angle, r, i))\n\n # apply reinforcement learning\n target = r + y * np.max(model.predict(np.identity(num_states)[new_s:new_s + 1]))\n target_vec = model.predict(np.identity(num_states)[s:s + 1])[0]\n target_vec[a] = target\n model.fit(np.identity(num_states)[s:s + 1], target_vec.reshape(-1, num_actions), epochs=1, verbose=0)\n q_table[s,a] += r\n\n s = new_s\n # predict new angle\n # angle = model.predict(frame)\n\n angle = random.uniform(-1,1)\n s = np.argmax(encodeLabels(angle, 5))\n\n # get new action\n if np.random.random() < eps:\n a = np.random.randint(0, num_actions)\n else:\n a = np.argmax(model.predict(np.identity(num_states)[s:s + 1]))\n\n # get corrective angle based on the action\n new_angle = angle + correction[a]\n eps *= decay_factor\n if (i == 10):\n done = True\n if (new_s == target_state):\n i += 1\n else:\n i = 0\n steps += 1\n \n\n print(q_table)\n idxs = np.argmax(q_table, axis=1)\n print(idxs)\n print(np.sum(abs(idxs-[4,3,2,1, 0]))) \n print(\"steps {}\".format(steps))\n\nif \"__main__\" == __name__:\n main()","sub_path":"reinforcent-NN.py","file_name":"reinforcent-NN.py","file_ext":"py","file_size_in_byte":2600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"459624382","text":"import argparse\nimport pystache\nimport sys\n\ndef loadTemplate(templateFile):\n cfg = None\n\n data = \"\"\n with open(templateFile, 'r') as file:\n data = file.read()\n\n return data\n\ndef main(argv):\n print(\"make assymetric flashlex token.\")\n\n # Read in command-line parameters\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"-d\", \"--dir\", action=\"store\", required=True, dest=\"dir\", help=\"the flashlex install dir\")\n parser.add_argument(\"-t\", \"--template\", action=\"store\", required=True, dest=\"template\", help=\"the service template\")\n\n args = parser.parse_args()\n print(pystache.render(loadTemplate(args.template), args))\n \n \nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","sub_path":"makeservice.py","file_name":"makeservice.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"105044189","text":"from typing import Optional, Tuple, Union, List, DefaultDict, TYPE_CHECKING\nfrom collections import defaultdict\nimport logging\n\nimport networkx\n\nfrom ailment import Block, AILBlockWalkerBase\nfrom ailment.statement import ConditionalJump\nfrom ailment.expression import Expression, BinaryOp, Const, Load\n\nfrom angr.utils.graph import GraphUtils\nfrom ..utils import first_nonlabel_statement, remove_last_statement\nfrom ..structuring.structurer_nodes import IncompleteSwitchCaseHeadStatement, SequenceNode, MultiNode\nfrom .optimization_pass import OptimizationPass, OptimizationPassStage, MultipleBlocksException\n\nif TYPE_CHECKING:\n from ailment.expression import UnaryOp, Convert\n\n_l = logging.getLogger(name=__name__)\n\n\nclass Case:\n \"\"\"\n Describes a case in a switch-case construct.\n \"\"\"\n\n __slots__ = (\n \"original_node\",\n \"node_type\",\n \"variable_hash\",\n \"expr\",\n \"value\",\n \"target\",\n \"next_addr\",\n )\n\n def __init__(\n self, original_node, node_type: Optional[str], variable_hash, expr, value: Union[int, str], target, next_addr\n ):\n self.original_node = original_node\n self.node_type = node_type\n self.variable_hash = variable_hash\n self.expr = expr\n self.value = value\n self.target = target\n self.next_addr = next_addr\n\n def __repr__(self):\n if self.value == \"default\":\n return f\"Case default@{self.target:#x}\"\n return f\"Case {repr(self.original_node)}@{self.target:#x}: {self.expr} == {self.value}\"\n\n def __eq__(self, other):\n if not isinstance(other, Case):\n return False\n return (\n self.original_node == other.original_node\n and self.node_type == other.node_type\n and self.variable_hash == other.variable_hash\n and self.value == other.value\n and self.target == other.target\n and self.next_addr == other.next_addr\n )\n\n def __hash__(self):\n return hash(\n (Case, self.original_node, self.node_type, self.variable_hash, self.value, self.target, self.next_addr)\n )\n\n\nclass StableVarExprHasher(AILBlockWalkerBase):\n \"\"\"\n Obtain a stable hash of an AIL expression with respect to all variables and all operations applied on variables.\n \"\"\"\n\n def __init__(self, expr: Expression):\n super().__init__()\n self.expr = expr\n self._hash_lst = []\n\n self.walk_expression(expr)\n self.hash = hash(tuple(self._hash_lst))\n\n def _handle_expr(self, expr_idx: int, expr: Expression, stmt_idx: int, stmt, block: Optional[Block]):\n if hasattr(expr, \"variable\"):\n self._hash_lst.append(expr.variable)\n else:\n super()._handle_expr(expr_idx, expr, stmt_idx, stmt, block)\n\n def _handle_Load(self, expr_idx: int, expr: Load, stmt_idx: int, stmt, block: Optional[Block]):\n self._hash_lst.append(\"Load\")\n super()._handle_expr(expr_idx, expr, stmt_idx, stmt, block)\n\n def _handle_BinaryOp(self, expr_idx: int, expr: BinaryOp, stmt_idx: int, stmt, block: Optional[Block]):\n self._hash_lst.append(expr.op)\n super()._handle_BinaryOp(expr_idx, expr, stmt_idx, stmt, block)\n\n def _handle_UnaryOp(self, expr_idx: int, expr: \"UnaryOp\", stmt_idx: int, stmt, block: Optional[Block]):\n self._hash_lst.append(expr.op)\n super()._handle_UnaryOp(expr_idx, expr, stmt_idx, stmt, block)\n\n def _handle_Const(self, expr_idx: int, expr: Const, stmt_idx: int, stmt, block: Optional[Block]):\n self._hash_lst.append((expr.value, expr.bits))\n\n def _handle_Convert(self, expr_idx: int, expr: \"Convert\", stmt_idx: int, stmt, block: Optional[Block]):\n self._hash_lst.append(expr.to_bits)\n super()._handle_Convert(expr_idx, expr, stmt_idx, stmt, block)\n\n\nclass LoweredSwitchSimplifier(OptimizationPass):\n \"\"\"\n Recognize and simplify lowered switch-case constructs.\n \"\"\"\n\n ARCHES = [\n \"AMD64\",\n ]\n PLATFORMS = [\"linux\", \"windows\"]\n STAGE = OptimizationPassStage.BEFORE_REGION_IDENTIFICATION\n NAME = \"Convert lowered switch-cases (if-else) to switch-cases\"\n DESCRIPTION = (\n \"Convert lowered switch-cases (if-else) to switch-cases. Only works when the Phoenix structuring \"\n \"algorithm is in use.\"\n )\n STRUCTURING = [\"phoenix\"]\n\n def __init__(self, func, blocks_by_addr=None, blocks_by_addr_and_idx=None, graph=None, **kwargs):\n super().__init__(\n func, blocks_by_addr=blocks_by_addr, blocks_by_addr_and_idx=blocks_by_addr_and_idx, graph=graph, **kwargs\n )\n self.analyze()\n\n def _check(self):\n # TODO: More filtering\n return True, None\n\n def _analyze(self, cache=None):\n variablehash_to_cases = self._find_cascading_switch_variable_comparisons()\n\n if not variablehash_to_cases:\n return\n\n graph_copy = networkx.DiGraph(self._graph)\n self.out_graph = graph_copy\n node_to_heads = defaultdict(set)\n\n for _, caselists in variablehash_to_cases.items():\n for cases in caselists:\n original_nodes = [case.original_node for case in cases if case.value != \"default\"]\n original_head: Block = original_nodes[0]\n original_nodes = original_nodes[1:]\n\n case_addrs = {(case.original_node, case.value, case.target, case.next_addr) for case in cases}\n\n expr = cases[0].expr\n\n # create a fake switch-case head node\n switch_stmt = IncompleteSwitchCaseHeadStatement(\n original_head.statements[-1].idx, expr, case_addrs, ins_addr=original_head.statements[-1].ins_addr\n )\n new_head = original_head.copy()\n # replace the last instruction of the head node with switch_node\n new_head.statements[-1] = switch_stmt\n # update the block\n self._update_block(original_head, new_head)\n\n # sanity check that no switch head points to either itself\n # or to any if-head that was merged into the new switch head; this\n # would result in a successor node no longer being present in the graph\n if any(onode not in graph_copy for onode in original_nodes):\n self.out_graph = None\n return\n\n # add edges between the head and case nodes\n for onode in original_nodes:\n successors = list(graph_copy.successors(onode))\n for succ in successors:\n if succ not in original_nodes:\n graph_copy.add_edge(new_head, succ)\n node_to_heads[succ].add(new_head)\n graph_copy.remove_node(onode)\n\n # find shared case nodes and make copies of them\n # note that this only solves cases where *one* node is shared between switch-cases. a more general solution\n # requires jump threading reverter.\n for succ_node, heads in node_to_heads.items():\n if len(heads) > 1:\n # each head gets a copy of the node!\n node_successors = list(graph_copy.successors(succ_node))\n next_id = 0 if succ_node.idx is None else succ_node.idx + 1\n graph_copy.remove_node(succ_node)\n for head in heads:\n node_copy = succ_node.copy()\n node_copy.idx = next_id\n next_id += 1\n graph_copy.add_edge(head, node_copy)\n for succ in node_successors:\n if succ is succ_node:\n graph_copy.add_edge(node_copy, node_copy)\n else:\n graph_copy.add_edge(node_copy, succ)\n\n def _find_cascading_switch_variable_comparisons(self):\n sorted_nodes = GraphUtils.quasi_topological_sort_nodes(self._graph)\n variable_comparisons = {}\n for node in sorted_nodes:\n r = self._find_switch_variable_comparison_type_a(node)\n if r is not None:\n variable_comparisons[node] = (\"a\",) + r\n continue\n r = self._find_switch_variable_comparison_type_b(node)\n if r is not None:\n variable_comparisons[node] = (\"b\",) + r\n continue\n\n varhash_to_caselists: DefaultDict[int, List[List[Case]]] = defaultdict(list)\n\n for head in variable_comparisons:\n cases = []\n last_comp = None\n comp = head\n while True:\n comp_type, variable_hash, expr, value, target, next_addr = variable_comparisons[comp]\n if cases:\n last_varhash = cases[-1].variable_hash\n else:\n last_varhash = None\n if last_varhash is None or last_varhash == variable_hash:\n if target == comp.addr:\n # invalid\n break\n cases.append(Case(comp, comp_type, variable_hash, expr, value, target, next_addr))\n else:\n # new variable!\n if last_comp is not None:\n cases.append(Case(last_comp, None, last_varhash, None, \"default\", comp.addr, None))\n break\n\n if comp is not head:\n # non-head node has at most one predecessor\n if self._graph.in_degree[comp] > 1:\n break\n\n successors = [succ for succ in self._graph.successors(comp) if succ is not comp]\n succ_addrs = {succ.addr for succ in successors}\n if target in succ_addrs:\n next_comp_addr = next(iter(succ_addr for succ_addr in succ_addrs if succ_addr != target), None)\n if next_comp_addr is None:\n break\n try:\n next_comp = self._get_block(next_comp_addr)\n except MultipleBlocksException:\n # multiple blocks :/ it's possible that other optimization passes have duplicated the default\n # node. check it.\n next_comp_many = list(self._get_blocks(next_comp_addr))\n if next_comp_many[0] not in variable_comparisons:\n cases.append(Case(comp, None, variable_hash, expr, \"default\", next_comp_addr, None))\n # otherwise we don't support it\n break\n assert next_comp is not None\n if next_comp in variable_comparisons:\n last_comp = comp\n comp = next_comp\n continue\n cases.append(Case(comp, None, variable_hash, expr, \"default\", next_comp_addr, None))\n break\n\n if cases:\n v = cases[-1].variable_hash\n for idx, existing_cases in list(enumerate(varhash_to_caselists[v])):\n if self.cases_issubset(existing_cases, cases):\n varhash_to_caselists[v][idx] = cases\n break\n if self.cases_issubset(cases, existing_cases):\n break\n else:\n varhash_to_caselists[v].append(cases)\n\n for v, caselists in list(varhash_to_caselists.items()):\n for idx, cases in list(enumerate(caselists)):\n # filter: there should be at least two non-default cases\n if len([case for case in cases if case.value != \"default\"]) < 2:\n caselists[idx] = None\n continue\n\n # filter: no type-a node after the first case node\n if any(case for case in cases[1:] if case.value != \"default\" and case.node_type == \"a\"):\n caselists[idx] = None\n continue\n\n # filter: each case is only reachable from a case node\n all_case_nodes = {case.original_node for case in cases}\n skipped = False\n for case in cases:\n target_nodes = [\n succ for succ in self._graph.successors(case.original_node) if succ.addr == case.target\n ]\n if len(target_nodes) != 1:\n caselists[idx] = None\n skipped = True\n break\n target_node = target_nodes[0]\n nonself_preds = {pred for pred in self._graph.predecessors(target_node) if pred.addr == case.target}\n if not nonself_preds.issubset(all_case_nodes):\n caselists[idx] = None\n skipped = True\n break\n\n if skipped:\n continue\n\n varhash_to_caselists[v] = [cl for cl in caselists if cl is not None]\n\n return varhash_to_caselists\n\n @staticmethod\n def _find_switch_variable_comparison_type_a(\n node,\n ) -> Optional[Tuple[int, Expression, int, int, int]]:\n # the type a is the last statement is a var == constant comparison, but\n # there is more than one non-label statement in the block\n\n if isinstance(node, Block) and node.statements:\n stmt = node.statements[-1]\n if stmt is not None and stmt is not first_nonlabel_statement(node):\n if (\n isinstance(stmt, ConditionalJump)\n and isinstance(stmt.true_target, Const)\n and isinstance(stmt.false_target, Const)\n ):\n cond = stmt.condition\n if isinstance(cond, BinaryOp):\n if isinstance(cond.operands[1], Const):\n variable_hash = StableVarExprHasher(cond.operands[0]).hash\n value = cond.operands[1].value\n if cond.op == \"CmpEQ\":\n target = stmt.true_target.value\n next_node_addr = stmt.false_target.value\n elif cond.op == \"CmpNE\":\n target = stmt.false_target.value\n next_node_addr = stmt.true_target.value\n else:\n return None\n return variable_hash, cond.operands[0], value, target, next_node_addr\n\n return None\n\n @staticmethod\n def _find_switch_variable_comparison_type_b(\n node,\n ) -> Optional[Tuple[int, Expression, int, int, int]]:\n # the type b is the last statement is a var == constant comparison, and\n # there is only one non-label statement\n\n if isinstance(node, Block):\n stmt = first_nonlabel_statement(node)\n if stmt is not None and stmt is node.statements[-1]:\n if (\n isinstance(stmt, ConditionalJump)\n and isinstance(stmt.true_target, Const)\n and isinstance(stmt.false_target, Const)\n ):\n cond = stmt.condition\n if isinstance(cond, BinaryOp):\n if isinstance(cond.operands[1], Const):\n variable_hash = StableVarExprHasher(cond.operands[0]).hash\n value = cond.operands[1].value\n if cond.op == \"CmpEQ\":\n target = stmt.true_target.value\n next_node_addr = stmt.false_target.value\n elif cond.op == \"CmpNE\":\n target = stmt.false_target.value\n next_node_addr = stmt.true_target.value\n else:\n return None\n return variable_hash, cond.operands[0], value, target, next_node_addr\n\n return None\n\n @staticmethod\n def restore_graph(\n node, last_stmt: IncompleteSwitchCaseHeadStatement, graph: networkx.DiGraph, full_graph: networkx.DiGraph\n ):\n last_node = node\n ca_default = [\n (onode, value, target, a) for onode, value, target, a in last_stmt.case_addrs if value == \"default\"\n ]\n ca_others = [\n (onode, value, target, a) for onode, value, target, a in last_stmt.case_addrs if value != \"default\"\n ]\n\n # non-default nodes\n ca_others = {ca[0].addr: ca for ca in ca_others}\n # extract the AIL block from last_node\n last_block = last_node\n if isinstance(last_block, SequenceNode):\n last_block = last_block.nodes[-1]\n if isinstance(last_block, MultiNode):\n last_block = last_block.nodes[-1]\n assert isinstance(last_block, Block)\n next_node_addr = last_block.addr\n\n while next_node_addr is not None and next_node_addr in ca_others:\n onode, value, target, next_node_addr = ca_others[next_node_addr]\n onode: Block\n\n if first_nonlabel_statement(onode) is not onode.statements[-1]:\n onode = onode.copy(statements=[onode.statements[-1]])\n\n graph.add_edge(last_node, onode)\n full_graph.add_edge(last_node, onode)\n\n target_node = next(iter(nn for nn in full_graph if nn.addr == target))\n graph.add_edge(onode, target_node)\n full_graph.add_edge(onode, target_node)\n\n if graph.has_edge(node, target_node):\n graph.remove_edge(node, target_node)\n if full_graph.has_edge(node, target_node):\n full_graph.remove_edge(node, target_node)\n\n # update last_node\n last_node = onode\n\n # default nodes\n if ca_default:\n onode, value, target, _ = ca_default[0]\n default_target = next(iter(nn for nn in full_graph if nn.addr == target))\n graph.add_edge(last_node, default_target)\n full_graph.add_edge(last_node, default_target)\n\n if graph.has_edge(node, default_target):\n graph.remove_edge(node, default_target)\n if full_graph.has_edge(node, default_target):\n full_graph.remove_edge(node, default_target)\n\n # all good - remove the last statement in node\n remove_last_statement(node)\n\n @staticmethod\n def cases_issubset(cases_0: List[Case], cases_1: List[Case]) -> bool:\n \"\"\"\n Test if cases_0 is a subset of cases_1.\n \"\"\"\n\n if len(cases_0) > len(cases_1):\n return False\n for case in cases_0:\n if case not in cases_1:\n return False\n return True\n","sub_path":"angr/analyses/decompiler/optimization_passes/lowered_switch_simplifier.py","file_name":"lowered_switch_simplifier.py","file_ext":"py","file_size_in_byte":19038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"466774890","text":"if __name__ == '__main__':\n def hepsi(liste):\n for i in liste:\n if not i:\n return False\n return True\n\n\n # Bütün değerler True ise True en az birisi False ise False döndürmek istiyoruz.\n liste = [True, True, False, True, True]\n print(hepsi(liste))\n \n #all() fonksiyonu bütün değerler True ise True, en az bir değer False ise False sonuç döndürür.\n print(all(liste))\n\n #any() fonksiyonu bütün değerler False ise False, en az bir değer True ise True sonuç döndürür.\n print(any(liste))\n","sub_path":"gomulu_func/all_and_any.py","file_name":"all_and_any.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"55977421","text":"import os\nimport json\nfrom datetime import datetime, timedelta\nimport surfex\nimport yaml\nimport f90nml\n\n\nclass SystemFilePaths(object):\n\n \"\"\"\n Mathes files and paths depending on possibly system specific settings.\n User can provide a default system dir to nest dependencies.\n \"\"\"\n\n def __init__(self, system_file_paths):\n self.system_file_paths = system_file_paths\n self.system_variables = None\n\n def get_system_path(self, dtype, **kwargs):\n # print(kwargs)\n default_dir = None\n if \"default_dir\" in kwargs:\n default_dir = kwargs[\"default_dir\"]\n verbosity = 0\n if \"verbosity\" in kwargs:\n verbosity = kwargs[\"verbosity\"]\n if verbosity > 0:\n print(\"Search for: \" + dtype + \" Default: \" + str(default_dir))\n\n data_dir = self.find_matching_data_dir(dtype, **kwargs)\n if data_dir is None:\n if default_dir is None:\n raise Exception(\"No system path found for \" + dtype)\n else:\n data_dir = self.find_matching_data_dir(default_dir, **kwargs)\n print(\"DEFAULT\")\n # print(data_dir)\n return data_dir\n\n def find_matching_data_dir(self, dtype, **kwargs):\n # print(\"match \", kwargs)\n default_dir = None\n if \"default_dir\" in kwargs:\n default_dir = kwargs[\"default_dir\"]\n verbosity = 0\n if \"verbosity\" in kwargs:\n verbosity = kwargs[\"verbosity\"]\n check_existence = False\n if \"check_existence\" in kwargs:\n check_existence = kwargs[\"check_existence\"]\n\n command = None\n for p in self.system_file_paths:\n if p == dtype:\n if verbosity > 3:\n print(\"Found \" + p, type(p), self.system_file_paths)\n data_dir = self.system_file_paths[p]\n # If dict, also a command is attached\n if isinstance(data_dir, dict):\n for key in data_dir:\n print(key, data_dir[key])\n command = str(data_dir[key])\n data_dir = str(key)\n if verbosity > 2:\n print(\"Data directory before parsing is is: \" + data_dir)\n if not isinstance(data_dir, str):\n raise Exception(\"data dir is not a string!\")\n data_dir = self.parse_setting(self.substitute_string(data_dir), **kwargs)\n # Add command to data_dir again\n if command is not None:\n data_dir = {data_dir: command}\n if verbosity > 2:\n print(\"Data directory after parsing is is: \" + data_dir)\n if check_existence:\n if not os.path.exists(data_dir) and default_dir is None:\n raise NotADirectoryError(data_dir)\n return data_dir\n return None\n\n def get_system_file(self, dtype, fname, **kwargs):\n verbosity = 0\n if \"verbosity\" in kwargs:\n verbosity = kwargs[\"verbosity\"]\n if verbosity > 5:\n print(\"get_system_file\", dtype, fname, kwargs)\n command = None\n path = self.get_system_path(dtype, **kwargs)\n # If dict, also a command is attached\n if isinstance(path, dict):\n for key in path:\n command = str(path[key])\n path = str(key)\n fname = self.parse_setting(fname, **kwargs)\n fname = self.substitute_string(fname)\n if path is None:\n print(\"No path found for: \" + dtype)\n else:\n fname = path + \"/\" + fname\n check_existence = False\n if \"check_existence\" in kwargs:\n check_existence = kwargs[\"check_existence\"]\n if check_existence:\n if not os.path.exists(fname):\n raise FileNotFoundError(fname)\n if command is not None:\n fname = {fname: command}\n return fname\n\n @staticmethod\n def parse_setting(setting, **kwargs):\n check_parsing = True\n # Check on arguments\n if kwargs is not None and isinstance(setting, str):\n validtime = None\n if \"validtime\" in kwargs:\n validtime = kwargs[\"validtime\"]\n mbr = None\n if \"mbr\" in kwargs:\n mbr = kwargs[\"mbr\"]\n basedtg = None\n if \"basedtg\" in kwargs:\n basedtg = kwargs[\"basedtg\"]\n tstep = None\n if \"tstep\" in kwargs:\n tstep = kwargs[\"tstep\"]\n pert = None\n if \"pert\" in kwargs:\n pert = kwargs[\"pert\"]\n var = None\n if \"var\" in kwargs:\n var = kwargs[\"var\"]\n sfx_exp_vars = None\n if \"sfx_exp_vars\" in kwargs:\n sfx_exp_vars = kwargs[\"sfx_exp_vars\"]\n\n if basedtg is not None:\n if isinstance(basedtg, str):\n basedtg = datetime.strptime(basedtg, \"%Y%m%d%H\")\n if validtime is not None:\n if isinstance(validtime, str):\n validtime = datetime.strptime(validtime, \"%Y%m%d%H\")\n else:\n validtime = basedtg\n\n if basedtg is not None and validtime is not None:\n lead_time = validtime - basedtg\n lead_seconds = int(lead_time.total_seconds())\n # lead_minutes = int(lead_seconds / 3600)\n lead_hours = int(lead_seconds / 3600)\n setting = str(setting).replace(\"@LL@\", \"{:02d}\".format(lead_hours))\n setting = str(setting).replace(\"@LLL@\", \"{:03d}\".format(lead_hours))\n setting = str(setting).replace(\"@LLLL@\", \"{:04d}\".format(lead_hours))\n if tstep is not None:\n lead_step = int(lead_seconds / tstep)\n setting = str(setting).replace(\"@TTT@\", \"{:03d}\".format(lead_step))\n setting = str(setting).replace(\"@TTTT@\", \"{:04d}\".format(lead_step))\n\n if basedtg is not None:\n setting = str(setting).replace(\"@YMD@\", basedtg.strftime(\"%Y%m%d\"))\n setting = str(setting).replace(\"@YYYY@\", basedtg.strftime(\"%Y\"))\n setting = str(setting).replace(\"@YY@\", basedtg.strftime(\"%y\"))\n setting = str(setting).replace(\"@MM@\", basedtg.strftime(\"%m\"))\n setting = str(setting).replace(\"@DD@\", basedtg.strftime(\"%d\"))\n setting = str(setting).replace(\"@HH@\", basedtg.strftime(\"%H\"))\n setting = str(setting).replace(\"@mm@\", basedtg.strftime(\"%M\"))\n\n if mbr is not None:\n setting = str(setting).replace(\"@E@\", \"mbr{:d}\".format(int(mbr)))\n setting = str(setting).replace(\"@EE@\", \"mbr{:02d}\".format(int(mbr)))\n setting = str(setting).replace(\"@EEE@\", \"mbr{:03d}\".format(int(mbr)))\n else:\n setting = str(setting).replace(\"@E@\", \"\")\n setting = str(setting).replace(\"@EE@\", \"\")\n setting = str(setting).replace(\"@EEE@\", \"\")\n\n if pert is not None:\n print(\"replace\", pert, \"in \", setting)\n setting = str(setting).replace(\"@PERT@\", str(pert))\n print(\"replaced\", pert, \"in \", setting)\n\n if var is not None:\n setting = str(setting).replace(\"@VAR@\", var)\n\n if sfx_exp_vars is not None:\n # print(sfx_exp_vars)\n for sfx_exp_var in sfx_exp_vars:\n setting = str(setting).replace(\"@\" + sfx_exp_var + \"@\", sfx_exp_vars[sfx_exp_var])\n\n if \"check_parsing\" in kwargs:\n check_parsing = kwargs[\"check_parsing\"]\n\n if check_parsing:\n if isinstance(setting, str) and setting.count(\"@\") > 1:\n raise Exception(\"Setting was not substituted properly? \" + setting)\n\n return setting\n\n @staticmethod\n def substitute_string(setting, **kwargs):\n\n if isinstance(setting, str):\n env_vals = [\"USER\", \"HOME\", \"PWD\"]\n for env_val in env_vals:\n if env_val in os.environ:\n setting = setting.replace(\"@\" + env_val + \"@\", os.environ[env_val])\n else:\n print(env_val + \" not found in environment\")\n\n system_variables = None\n if \"system_variables\" in kwargs:\n system_variables = kwargs[\"system_variables\"]\n if system_variables is not None:\n print(system_variables)\n for var in system_variables:\n print(var, system_variables)\n setting = str(setting).replace(\"@\" + str(var) + \"@\", str(system_variables[var]))\n\n return setting\n\n def add_system_file_path(self, name, path, **kwargs):\n path = self.substitute_string(path)\n path = self.parse_setting(path, **kwargs)\n self.system_file_paths.update({name: path})\n\n\nclass SystemFilePathsFromFile(SystemFilePaths):\n def __init__(self, system_file_paths):\n system_file_paths = json.load(open(system_file_paths, \"r\"))\n SystemFilePaths.__init__(self, system_file_paths)\n\n\nclass ExternalSurfexInputFile(object):\n\n \"\"\"\n Wrapper around external input data to surfex which can have special treatment for each format.\n Uses internally the SystemFilePaths class\n \"\"\"\n\n def __init__(self, system_file_paths):\n self.system_file_paths = system_file_paths\n\n def set_input_data_from_format(self, dtype, fname, **kwargs):\n fname_with_path = self.system_file_paths.get_system_file(dtype, fname, **kwargs)\n\n if fname.endswith(\".dir\"):\n basename = os.path.splitext(os.path.basename(fname))[0]\n linkbasename = basename\n if \"linkbasename\" in kwargs:\n linkbasename = kwargs[\"linkbasename\"]\n basedir = self.system_file_paths.get_system_path(dtype, **kwargs)\n hdr_file = basedir + \"/\" + basename + \".hdr\"\n dir_file = basedir + \"/\" + basename + \".dir\"\n return {linkbasename + \".hdr\": hdr_file, linkbasename + \".dir\": dir_file}\n elif fname.endswith(\".json\"):\n return {}\n else:\n return {fname: fname_with_path}\n\n\nclass BaseNamelist(object):\n def __init__(self, program, config, input_path, **kwargs):\n\n self.config = config\n self.input_path = input_path\n self.forc_zs = False\n if \"forc_zs\" in kwargs:\n self.forc_zs = kwargs[\"forc_zs\"]\n prep_file = None\n if \"prep_file\" in kwargs:\n prep_file = kwargs[\"prep_file\"]\n prep_filetype = None\n if \"prep_filetype\" in kwargs:\n prep_filetype = kwargs[\"prep_filetype\"]\n prep_pgdfile = None\n if \"prep_pgdfile\" in kwargs:\n prep_pgdfile = kwargs[\"prep_pgdfile\"]\n prep_pgdfiletype = None\n if \"prep_pgdfiletype\" in kwargs:\n prep_pgdfiletype = kwargs[\"prep_pgdfiletype\"]\n dtg = None\n if \"dtg\" in kwargs:\n dtg = kwargs[\"dtg\"]\n if isinstance(dtg, str):\n dtg = datetime.strptime(dtg, \"%Y%m%d%H\")\n self.dtg = dtg\n check_parsing = True\n if self.dtg is None:\n check_parsing = False\n\n self.fcint = 3\n if \"fcint\" in kwargs:\n self.fcint = kwargs[\"fcint\"]\n\n # TODO Should be taken from LL_LLIST\n forecast_length = self.fcint\n if self.dtg is not None:\n self.end_of_forecast = self.dtg + timedelta(hours=forecast_length)\n else:\n self.end_of_forecast = None\n\n print(\"Creating JSON namelist input for program: \" + program)\n\n self.input_list = []\n\n self.prolog(check_parsing)\n # Program specific settings\n if program == \"pgd\":\n self.set_pgd_namelist()\n elif program == \"prep\":\n if prep_file is None:\n raise Exception(\"Prep need an input file either as a json namelist or a surfex supported format\")\n self.set_prep_namelist(prep_file=prep_file, prep_filetype=prep_filetype, prep_pgdfile=prep_pgdfile,\n prep_pgdfiletype=prep_pgdfiletype)\n elif program == \"offline\" or program == \"perturbed\":\n self.set_offline_namelist()\n elif program == \"soda\":\n self.set_soda_namelist()\n else:\n raise NotImplementedError(program)\n self.epilog()\n self.override()\n\n def prolog(self, check_parsing):\n\n # IO\n self.input_list.append({\"file\": self.input_path + \"/io.json\"})\n self.input_list.append({\"json\": {\"NAM_IO_OFFLINE\": {\"CSURF_FILETYPE\":\n self.config.get_setting(\"SURFEX#IO#CSURF_FILETYPE\")}}})\n self.input_list.append({\"json\": {\"NAM_IO_OFFLINE\": {\"CTIMESERIES_FILETYPE\":\n self.config.get_setting(\n \"SURFEX#IO#CTIMESERIES_FILETYPE\")}}})\n self.input_list.append({\"json\": {\"NAM_IO_OFFLINE\": {\"CFORCING_FILETYPE\":\n self.config.get_setting(\"SURFEX#IO#CFORCING_FILETYPE\")}}})\n self.input_list.append({\"json\": {\"NAM_IO_OFFLINE\": {\"CPGDFILE\":\n self.config.get_setting(\"SURFEX#IO#CPGDFILE\")}}})\n self.input_list.append({\"json\": {\"NAM_IO_OFFLINE\": {\"CPREPFILE\":\n self.config.get_setting(\"SURFEX#IO#CPREPFILE\")}}})\n self.input_list.append({\"json\": {\"NAM_IO_OFFLINE\": {\"CSURFFILE\":\n self.config.get_setting(\"SURFEX#IO#CSURFFILE\",\n validtime=self.end_of_forecast,\n basedtg=self.dtg,\n check_parsing=check_parsing)}}})\n self.input_list.append({\"json\": {\"NAM_IO_OFFLINE\": {\"XTSTEP_SURF\":\n self.config.get_setting(\"SURFEX#IO#XTSTEP\")}}})\n self.input_list.append({\"json\": {\"NAM_IO_OFFLINE\": {\"XTSTEP_OUTPUT\":\n self.config.get_setting(\"SURFEX#IO#XTSTEP_OUTPUT\")}}})\n self.input_list.append({\"json\": {\"NAM_WRITE_SURF_ATM\": {\"LSPLIT_PATCH\":\n self.config.get_setting(\"SURFEX#IO#LSPLIT_PATCH\")}}})\n\n if self.forc_zs:\n self.input_list.append({\"json\": {\"NAM_IO_OFFLINE\": {\"LSET_FORC_ZS\": True}}})\n\n # Constants and parameters\n self.input_list.append({\"file\": self.input_path + \"/constants.json\"})\n self.input_list.append({\"json\": {\"NAM_SURF_ATM\": {\"XRIMAX\":\n self.config.get_setting(\"SURFEX#PARAMETERS#XRIMAX\")}}})\n\n def set_pgd_namelist(self):\n # PGS schemes\n self.input_list.append({\n \"json\": {\"NAM_PGD_SCHEMES\": {\n \"CSEA\": self.config.get_setting(\"SURFEX#TILES#SEA\"),\n \"CWATER\": self.config.get_setting(\"SURFEX#TILES#INLAND_WATER\"),\n \"CNATURE\": self.config.get_setting(\"SURFEX#TILES#NATURE\"),\n \"CTOWN\": self.config.get_setting(\"SURFEX#TILES#TOWN\")\n }\n }})\n\n eco_sg = self.config.get_setting(\"SURFEX#COVER#SG\")\n # Ecoclimap SG\n self.input_list.append({\"json\": {\"NAM_FRAC\": {\"LECOSG\": eco_sg}}})\n if self.config.get_setting(\"SURFEX#COVER#SG\"):\n ecoclimap = EcoclimapSG(self.config)\n\n self.input_list.append({\"json\": {\"NAM_DATA_ISBA\": {\"NTIME\": ecoclimap.decades}}})\n\n fname = self.config.get_setting(\"SURFEX#COVER#H_TREE\")\n if fname != \"\" and fname is not None:\n self.input_list.append(self.set_dirtyp_data_namelist(\"NAM_DATA_ISBA\", \"H_TREE\", fname, vtype=1))\n\n decadal_data_types = [\"ALBNIR_SOIL\", \"ALBNIR_VEG\", \"ALBVIS_SOIL\", \"ALBVIS_VEG\", \"LAI\"]\n for decadal_data_type in decadal_data_types:\n for vt in range(1, ecoclimap.veg_types + 1):\n for decade in range(1, ecoclimap.decades + 1):\n filepattern = self.config.get_setting(\"SURFEX#COVER#\" + decadal_data_type, check_parsing=False)\n fname = ecoclimap.parse_fnames(filepattern, decade)\n self.input_list.append(self.set_dirtyp_data_namelist(\"NAM_DATA_ISBA\", decadal_data_type, fname,\n vtype=vt, decade=decade))\n\n ecoclimap_dir = \"ecoclimap_dir\"\n if self.config.get_setting(\"SURFEX#COVER#SG\"):\n ecoclimap_dir = \"ecoclimap_sg_cover_dir\"\n\n possible_direct_data = {\n \"ISBA\": {\n \"YSAND\": \"sand_dir\",\n \"YCLAY\": \"clay_dir\",\n \"YSOC_TOP\": \"soc_top_dir\",\n \"YSOC_SUB\": \"soc_sub_dir\"\n },\n \"COVER\": {\n \"YCOVER\": ecoclimap_dir\n },\n \"ZS\": {\n \"YZS\": \"oro_dir\"\n }\n }\n for namelist_section in possible_direct_data:\n for ftype in possible_direct_data[namelist_section]:\n fname = str(self.config.get_setting(\"SURFEX#\" + namelist_section + \"#\" + ftype))\n self.input_list.append(self.set_direct_data_namelist(\"NAM_\" + namelist_section, ftype, fname,\n self.input_path))\n\n # Set ISBA properties\n if self.config.get_setting(\"SURFEX#ISBA#SCHEME\") == \"DIF\":\n self.input_list.append({\"json\": {\"NAM_ISBA\": {\"CISBA\": \"DIF\", \"NGROUND_LAYER\": 14}}})\n if os.path.exists(self.input_path + \"/isba_dif.json\"):\n self.input_list.append({\"file\": self.input_path + \"/isba_dif.json\" })\n elif self.config.get_setting(\"SURFEX#ISBA#SCHEME\") == \"3-L\":\n self.input_list.append({\"json\": {\"NAM_ISBA\": {\"CISBA\": \"3-L\", \"NGROUND_LAYER\": 3}}})\n elif self.config.get_setting(\"SURFEX#ISBA#SCHEME\") == \"2-L\":\n self.input_list.append({\"json\": {\"NAM_ISBA\": {\"CISBA\": \"2-L\", \"NGROUND_LAYER\": 2}}})\n\n # Set patches\n self.input_list.append({\"json\": {\"NAM_ISBA\": {\"NPATCH\": self.config.get_setting(\"SURFEX#ISBA#NPATCH\")}}})\n\n # Set MEB\n self.input_list.append({\"json\": {\"NAM_ISBA\": {\"LMEB\": self.config.get_setting(\"SURFEX#ISBA#MEB\")}}})\n if self.config.get_setting(\"SURFEX#ISBA#MEB\"):\n self.input_list.append({\"file\": self.input_path + \"/meb_settings.json\"})\n\n # RSMIN\n if self.config.get_setting(\"SURFEX#COVER#SG\"):\n self.input_list.append({\"file\": self.input_path + \"/rsmin_sg.json\"})\n self.input_list.append({\"file\": self.input_path + \"/rsmin_sg_mod.json\"})\n else:\n self.input_list.append({\"file\": self.input_path + \"/rsmin.json\"})\n self.input_list.append({\"file\": self.input_path + \"/rsmin_mod.json\"})\n\n # CV\n if self.config.get_setting(\"SURFEX#COVER#SG\"):\n self.input_list.append({\"file\": self.input_path + \"/cv_sg.json\"})\n else:\n self.input_list.append({\"file\": self.input_path + \"/cv.json\"})\n\n # Treedrag\n if self.config.get_setting(\"SURFEX#TREEDRAG#TREEDATA_FILE\") != \"\":\n treeheight = self.config.get_setting(\"SURFEX#TREEDRAG#TREEDATA_FILE\")\n self.input_list.append({\n \"json\": {\n \"NAM_DATA_ISBA\": {\n \"CFNAM_H_TREE(4)\": treeheight,\n \"CFTYP_H_TREE(4)\": \"ASCLLV\",\n \"CFNAM_H_TREE(5)\": treeheight,\n \"CFTYP_H_TREE(5)\": \"ASCLLV\",\n \"CFNAM_H_TREE(6)\": treeheight,\n \"CFTYP_H_TREE(6)\": \"ASCLLV\"}\n }\n })\n\n if self.config.get_setting(\"SURFEX#TOWN#LTOWN_TO_ROCK\"):\n if self.config.get_setting(\"SURFEX#TILES#TOWN\") != \"NONE\":\n print(\"WARNING: TOWN is not NONE and you want LTOWN_TO_ROCK. Setting it to NONE!\")\n self.input_list.append({\"json\": {\"NAM_PGD_ARRANGE_COVER\": {\"LTOWN_TO_ROCK\": True}}})\n self.input_list.append({\"json\": {\"NAM_PGD_SCHEMES\": {\"TOWN\": \"NONE\"}}})\n\n if self.config.get_setting(\"SURFEX#TILES#INLAND_WATER\") == \"FLAKE\":\n self.input_list.append({\n \"json\": {\n \"NAM_DATA_FLAKE\": {\n \"YWATER_DEPTH\": \"GlobalLakeDepth\",\n \"YWATER_DEPTHFILETYPE\": \"DIRECT\",\n \"YWATER_DEPTH_STATUS\": \"GlobalLakeStatus\"\n }\n }\n })\n\n # Sea\n self.input_list.append({\"file\": self.input_path + \"/sea.json\"})\n\n def set_prep_namelist(self, prep_file=None, prep_filetype=None, prep_pgdfile=None, prep_pgdfiletype=None):\n\n if prep_file is not None and prep_filetype is None:\n raise Exception(\"Filetype for input to PREP is not set!\")\n if prep_pgdfile is not None and prep_pgdfiletype is None:\n raise Exception(\"Filetype for PGD input to PREP is not set!\")\n\n self.input_list.append({\"file\": self.input_path + \"/prep.json\"})\n if prep_file is not None:\n if prep_file.endswith(\".json\"):\n self.input_list.append({\"file\": prep_file})\n else:\n fname = os.path.basename(prep_file)\n self.input_list.append({\"json\": {\"NAM_PREP_SURF_ATM\": {\"CFILE\": fname}}})\n self.input_list.append({\"json\": {\"NAM_PREP_SURF_ATM\": {\"CFILETYPE\": prep_filetype}}})\n if prep_pgdfile is not None:\n fname = os.path.basename(prep_pgdfile)\n self.input_list.append({\"json\": {\"NAM_PREP_SURF_ATM\": {\"CFILEPGD\": fname}}})\n self.input_list.append({\"json\": {\"NAM_PREP_SURF_ATM\": {\"CFILEPGDTYPE\": prep_pgdfiletype}}})\n if self.dtg is not None:\n # prep_time = datetime.strptime(dtg, \"%Y%m%d%H\")\n prep_time = self.dtg\n self.input_list.append({\"json\": {\"NAM_PREP_SURF_ATM\": {\"NYEAR\": int(prep_time.strftime(\"%Y\"))}}})\n self.input_list.append({\"json\": {\"NAM_PREP_SURF_ATM\": {\"NMONTH\": int(prep_time.strftime(\"%m\"))}}})\n self.input_list.append({\"json\": {\"NAM_PREP_SURF_ATM\": {\"NDAY\": int(prep_time.strftime(\"%d\"))}}})\n self.input_list.append({\"json\": {\"NAM_PREP_SURF_ATM\": {\"XTIME\": float(prep_time.strftime(\"%H\"))*3600.}}})\n else:\n raise Exception(\"You must provide a DTG for prep\")\n if self.config.get_setting(\"SURFEX#SEA#ICE\") == \"SICE\":\n self.input_list.append({\"json\": {\"NAM_PREP_SEAFLUX\": {\"CSEAICE_SCHEME\": \"SICE\"}}})\n self.input_list.append({\"file\": self.input_path + \"/prep_sice.json\"})\n\n if self.config.get_setting(\"SURFEX#TILES#INLAND_WATER\") == \"FLAKE\":\n self.input_list.append({\"json\": {\"NAM_PREP_FLAKE\": {\"LCLIM_LAKE\":\n self.config.get_setting(\"SURFEX#FLAKE#LCLIM\")}}})\n\n # Set extra ISBA-DIF properties (Not needed in prep?)\n if self.config.get_setting(\"SURFEX#ISBA#SCHEME\") == \"DIF\":\n if os.path.exists(self.input_path + \"/isba_dif.json\"):\n self.input_list.append({\"file\": self.input_path + \"/isba_dif.json\" })\n\n # ISBA CANOPY\n self.input_list.append({\"json\": {\"NAM_PREP_ISBA\": {\"LISBA_CANOPY\":\n self.config.get_setting(\"SURFEX#ISBA#CANOPY\")}}})\n\n # Snow\n self.input_list.append({\"file\": self.input_path + \"/prep_snow.json\"})\n if self.config.get_setting(\"SURFEX#ISBA#SNOW\") == \"D95\":\n self.input_list.append({\"json\": {\"NAM_PREP_ISBA_SNOW\": {\"CSNOW\": \"D95\"}}})\n elif self.config.get_setting(\"SURFEX#ISBA#SNOW\") == \"3-L\":\n self.input_list.append({\"json\": {\"NAM_PREP_ISBA_SNOW\": {\"CSNOW\": \"3-L\"}}})\n if self.config.get_setting(\"SURFEX#ISBA#SNOW\") == \"CRO\":\n self.input_list.append({\"file\": self.input_path + \"/snow_crocus.json\"})\n\n def set_offline_namelist(self):\n self.input_list.append({\"file\": self.input_path + \"/offline.json\"})\n\n if self.config.get_setting(\"SURFEX#IO#LSELECT\"):\n self.input_list.append({\"file\": self.input_path + \"/selected_output.json\"})\n\n # SEAFLX settings\n if self.config.get_setting(\"SURFEX#TILES#SEA\") == \"SEAFLX\":\n # Surface perturbations\n self.input_list.append({\"json\": {\"NAM_SEAFLUXn\": {\"LPERTFLUX\":\n self.config.get_setting(\"SURFEX#SEA#PERTFLUX\")}}})\n\n # ISBA settings\n if self.config.get_setting(\"SURFEX#TILES#NATURE\") == \"ISBA\":\n self.input_list.append({\"json\": {\"NAM_ISBAn\": {\"LPERTSURF\":\n self.config.get_setting(\"SURFEX#ISBA#PERTSURF\")}}})\n self.input_list.append({\"json\": {\"NAM_ISBAn\": {\"XCGMAX\": self.config.get_setting(\"SURFEX#ISBA#XCGMAX\")}}})\n self.input_list.append({\"json\": {\"NAM_ISBAn\": {\"XCSMAX\": self.config.get_setting(\"SURFEX#ISBA#XCSMAX\")}}})\n\n # SSO\n self.input_list.append({\"json\": {\"NAM_SSON\": {\"CROUGH\": self.config.get_setting(\"SURFEX#SSO#SCHEME\")}}})\n geo = self.config.get_setting(\"GEOMETRY#GEO\")\n if isinstance(geo, surfex.ConfProj):\n self.input_list.append({\"json\": {\"NAM_SSON\": {\"XSOROT\": geo.xdx}}})\n\n # Perturbed offline settings\n self.input_list.append({\"json\": {\"NAM_VAR\": {\"NIVAR\": 0}}})\n self.input_list.append({\"json\": {\"NAM_IO_VARASSIM\": {\"LPRT\": False}}})\n if self.config.get_setting(\"SURFEX#ASSIM#SCHEMES#ISBA\") == \"EKF\":\n self.input_list.append({\"json\": {\"NAM_ASSIM\": {\"CASSIM_ISBA\":\n self.config.get_setting(\"SURFEX#ASSIM#SCHEMES#ISBA\")}}})\n nvar = 0\n cvar_m = self.config.get_setting(\"SURFEX#ASSIM#ISBA#EKF#CVAR_M\")\n nncv = self.config.get_setting(\"SURFEX#ASSIM#ISBA#EKF#NNCV\")\n xtprt_m = self.config.get_setting(\"SURFEX#ASSIM#ISBA#EKF#XTPRT_M\")\n xsigma_m = self.config.get_setting(\"SURFEX#ASSIM#ISBA#EKF#XSIGMA_M\")\n for var in range(0, len(cvar_m)):\n self.input_list.append({\"json\": {\"NAM_VAR\": {\"CVAR_M(\" + str(var + 1) + \")\": cvar_m[var]}}})\n self.input_list.append({\"json\": {\"NAM_VAR\": {\"NNCV(\" + str(var + 1) + \")\": nncv[var]}}})\n self.input_list.append({\"json\": {\"NAM_VAR\": {\"XTPRT_M(\" + str(var + 1) + \")\": xtprt_m[var]}}})\n self.input_list.append({\"json\": {\"NAM_VAR\": {\"XSIGMA_M(\" + str(var + 1) + \")\": xsigma_m[var]}}})\n if nncv[var] == 1:\n nvar += 1\n self.input_list.append({\"json\": {\"NAM_VAR\": {\"NVAR\": nvar}}})\n\n # TODO the need for this in forecast must be removed!\n nobstype = 0\n nnco = self.config.get_setting(\"SURFEX#ASSIM#OBS#NNCO\")\n cobs_m = self.config.get_setting(\"SURFEX#ASSIM#OBS#COBS_M\")\n if len(nnco) != len(cobs_m):\n raise Exception(\"Mismatch in nnco/cobs_m\")\n for ob in range(0, len(nnco)):\n self.input_list.append({\"json\": {\"NAM_OBS\": {\"NNCO(\" + str(ob + 1) + \")\": nnco[ob]}}})\n self.input_list.append({\"json\": {\"NAM_OBS\": {\"COBS_M(\" + str(ob + 1) + \")\": cobs_m[ob]}}})\n if nnco[ob] == 1:\n nobstype += 1\n self.input_list.append({\"json\": {\"NAM_OBS\": {\"NOBSTYPE\": nobstype}}})\n\n # Climate setting\n if self.config.get_setting(\"SURFEX#SEA#LVOLATILE_SIC\"):\n self.input_list.append({\"json\": {\"NAM_SEAICEn \": {\"LVOLATILE_SIC\": True,\n \"XSIC_EFOLDING_TIME\": 1.0}}})\n\n def set_soda_namelist(self):\n self.input_list.append({\"file\": self.input_path + \"/soda.json\"})\n\n self.input_list.append({\"json\": {\"NAM_ASSIM\": {\"LASSIM\": True}}})\n\n self.input_list.append({\"json\": {\"NAM_OBS\": {\"LOBSHEADER\":\n self.config.get_setting(\"SURFEX#ASSIM#OBS#LOBSHEADER\")}}})\n self.input_list.append({\"json\": {\"NAM_OBS\": {\"LOBSNAT\":\n self.config.get_setting(\"SURFEX#ASSIM#OBS#LOBSNAT\")}}})\n self.input_list.append({\"json\": {\"NAM_OBS\": {\"CFILE_FORMAT_OBS\":\n self.config.get_setting(\"SURFEX#ASSIM#OBS#CFILE_FORMAT_OBS\")}}})\n nobstype = 0\n nnco = self.config.get_setting(\"SURFEX#ASSIM#OBS#NNCO\")\n cobs_m = self.config.get_setting(\"SURFEX#ASSIM#OBS#COBS_M\")\n xerrobs_m = self.config.get_setting(\"SURFEX#ASSIM#OBS#XERROBS_M\")\n print(nnco, cobs_m, xerrobs_m)\n if len(nnco) != len(cobs_m) or len(nnco) != len(xerrobs_m):\n raise Exception(\"Mismatch in nnco/cobs_m/xerrobs_m\")\n\n for ob in range(0, len(nnco)):\n self.input_list.append({\"json\": {\"NAM_OBS\": {\"NNCO(\" + str(ob + 1) + \")\": nnco[ob]}}})\n self.input_list.append({\"json\": {\"NAM_OBS\": {\"COBS_M(\" + str(ob + 1) + \")\": cobs_m[ob]}}})\n self.input_list.append({\"json\": {\"NAM_OBS\": {\"XERROBS_M(\" + str(ob + 1) + \")\": xerrobs_m[ob]}}})\n if nnco[ob] == 1:\n nobstype += 1\n self.input_list.append({\"json\": {\"NAM_OBS\": {\"NOBSTYPE\": nobstype}}})\n self.input_list.append({\"json\": {\"NAM_OBS\": {\"LSWE\": self.config.get_setting(\"SURFEX#ASSIM#OBS#LSWE\")}}})\n\n # LSM\n self.input_list.append({\"json\": {\"NAM_ASSIM\": {\"CFILE_FORMAT_LSM\":\n self.config.get_setting(\"SURFEX#ASSIM#CFILE_FORMAT_LSM\")}}})\n\n # Sea\n self.input_list.append({\"json\": {\"NAM_ASSIM\": {\"CASSIM_SEA\":\n self.config.get_setting(\"SURFEX#ASSIM#SCHEMES#SEA\")}}})\n self.input_list.append({\"json\": {\"NAM_ASSIM\": {\"CFILE_FORMAT_SST\":\n self.config.get_setting(\"SURFEX#ASSIM#SEA#CFILE_FORMAT_SST\")}}})\n self.input_list.append({\"json\": {\"NAM_ASSIM\": {\"LREAD_SST_FROM_FILE\":\n self.config.get_setting(\n \"SURFEX#ASSIM#SEA#LREAD_SST_FROM_FILE\")}}})\n self.input_list.append({\"json\": {\"NAM_ASSIM\": {\"LEXTRAP_SEA\":\n self.config.get_setting(\"SURFEX#ASSIM#SEA#LEXTRAP_SEA\")}}})\n self.input_list.append({\"json\": {\"NAM_ASSIM\": {\"LECSST\":\n self.config.get_setting(\"SURFEX#ASSIM#SEA#LECSST\")}}})\n\n # Water\n self.input_list.append({\"json\": {\"NAM_ASSIM\": {\"CASSIM_WATER\":\n self.config.get_setting(\"SURFEX#ASSIM#SCHEMES#INLAND_WATER\")}}})\n self.input_list.append({\"json\": {\"NAM_ASSIM\": {\"LWATERTG2\":\n self.config.get_setting(\n \"SURFEX#ASSIM#INLAND_WATER#LWATERTG2\")}}})\n self.input_list.append({\"json\": {\"NAM_ASSIM\": {\"LEXTRAP_WATER\":\n self.config.get_setting(\n \"SURFEX#ASSIM#INLAND_WATER#LEXTRAP_WATER\")}}})\n\n # Nature\n self.input_list.append({\"json\": {\"NAM_ASSIM\": {\"CASSIM_ISBA\":\n self.config.get_setting(\"SURFEX#ASSIM#SCHEMES#ISBA\")}}})\n\n # Snow\n laesnm = False\n snow_cycles = self.config.get_setting(\"SURFEX#ASSIM#ISBA#UPDATE_SNOW_CYCLES\")\n if type(snow_cycles) is list:\n if len(snow_cycles) > 0:\n if self.dtg is not None:\n for cycle in snow_cycles:\n if int(self.dtg.strftime(\"%H\")) == int(cycle):\n print(\"true\")\n laesnm = True\n else:\n raise Exception(\"You must provide a DTG when using a list for snow assimilation cycles\")\n self.input_list.append({\"json\": {\"NAM_ASSIM\": {\"LAESNM\": laesnm}}})\n\n # Set OI settings\n if self.config.get_setting(\"SURFEX#ASSIM#SCHEMES#ISBA\") == \"OI\":\n ua_physics = self.config.get_setting(\"FORECAST#PHYSICS\")\n if ua_physics == \"arome\":\n self.input_list.append({\"json\": {\"NAM_ASSIM\": {\"LAROME\": True}}})\n elif ua_physics == \"alaro\":\n self.input_list.append({\"json\": {\"NAM_ASSIM\": {\"LAROME\": False}}})\n\n self.input_list.append({\"json\": {\"NAM_NACVEG\": {\"XSIGT2MO\":\n self.config.get_setting(\"SURFEX#ASSIM#ISBA#OI#XSIGT2MO\")}}})\n self.input_list.append({\"json\": {\"NAM_NACVEG\": {\"XSIGH2MO\":\n self.config.get_setting(\"SURFEX#ASSIM#ISBA#OI#XSIGH2MO\")}}})\n self.input_list.append({\"json\": {\"NAM_NACVEG\": {\"XRCLIMCA\": 0.0}}})\n self.input_list.append({\"json\": {\"NAM_NACVEG\": {\"XRCLISST\": 0.05}}})\n self.input_list.append({\"json\": {\"NAM_NACVEG\": {\"NECHGU\": self.fcint}}})\n self.input_list.append({\"json\": {\"NAM_NACVEG\": {\"LOBS2M\": True}}})\n self.input_list.append({\"json\": {\"NAM_NACVEG\": {\"LOBSWG\": False}}})\n self.input_list.append({\"json\": {\"NAM_ASSIM\": {\"CFILE_FORMAT_CLIM\":\n self.config.get_setting(\"SURFEX#ASSIM#ISBA#OI#CFILE_FORMAT_CLIM\")}}})\n self.input_list.append({\"json\": {\"NAM_ASSIM\": {\"CFILE_FORMAT_FG\":\n self.config.get_setting(\"SURFEX#ASSIM#ISBA#OI#CFILE_FORMAT_FG\")}}})\n\n if self.config.get_setting(\"SURFEX#ASSIM#SCHEMES#ISBA\") == \"EKF\":\n nvar = 0\n llincheck = self.config.get_setting(\"SURFEX#ASSIM#ISBA#EKF#LLINCHECK\")\n self.input_list.append({\"json\": {\"NAM_ASSIM\": {\"LLINCHECK\": llincheck}}})\n xalpha = self.config.get_setting(\"SURFEX#ASSIM#ISBA#EKF#XALPHA\")\n self.input_list.append({\"json\": {\"NAM_VAR\": {\"XALPHA\": xalpha}}})\n cvar_m = self.config.get_setting(\"SURFEX#ASSIM#ISBA#EKF#CVAR_M\")\n xsigma_m = self.config.get_setting(\"SURFEX#ASSIM#ISBA#EKF#XSIGMA_M\")\n xtprt_m = self.config.get_setting(\"SURFEX#ASSIM#ISBA#EKF#XTPRT_M\")\n nncv = self.config.get_setting(\"SURFEX#ASSIM#ISBA#EKF#NNCV\")\n if len(nncv) != len(cvar_m) or len(nncv) != len(xsigma_m) or len(nncv) != len(xtprt_m):\n raise Exception(\"Mismatch in nncv/cvar_m/xsigma_m/xtprt_m\")\n for var in range(0, len(cvar_m)):\n self.input_list.append(\n {\"json\": {\"NAM_VAR\": {\"CVAR_M(\" + str(var + 1) + \")\": cvar_m[var]}}})\n self.input_list.append({\"json\": {\"NAM_VAR\": {\"XSIGMA_M(\" + str(var + 1) + \")\": xsigma_m[var]}}})\n self.input_list.append({\"json\": {\"NAM_VAR\": {\"XTPRT_M(\" + str(var + 1) + \")\": xtprt_m[var]}}})\n self.input_list.append({\"json\": {\"NAM_VAR\": {\"NNCV(\" + str(var + 1) + \")\": nncv[var]}}})\n if nncv[var] == 1:\n nvar += 1\n self.input_list.append({\"json\": {\"NAM_VAR\": {\"NIVAR\": 0}}})\n self.input_list.append({\"json\": {\"NAM_VAR\": {\"NVAR\": nvar}}})\n self.input_list.append({\"json\": {\"NAM_VAR\": {\"XSCALE_Q\":\n self.config.get_setting(\"SURFEX#ASSIM#ISBA#EKF#XSCALE_Q\")}}})\n self.input_list.append({\"json\": {\"NAM_IO_VARASSIM\": {\n \"LPRT\": False,\n \"LBEV\": self.config.get_setting(\"SURFEX#ASSIM#ISBA#EKF#EVOLVE_B\"),\n \"LBFIXED\": not self.config.get_setting(\"SURFEX#ASSIM#ISBA#EKF#EVOLVE_B\")\n }}})\n\n # Town\n self.input_list.append({\"json\": {\"NAM_ASSIM\": {\"CASSIM_TEB\":\n self.config.get_setting(\"SURFEX#ASSIM#SCHEMES#TEB\")}}})\n\n def epilog(self):\n\n # Always set these\n if self.config.get_setting(\"SURFEX#SEA#ICE\") == \"SICE\":\n self.input_list.append({\"file\": self.input_path + \"/sice.json\"})\n\n self.input_list.append({\"file\": self.input_path + \"/treedrag.json\"})\n self.input_list.append({\"json\": {\"NAM_TREEDRAG\": {\"LFAKETREE\":\n self.config.get_setting(\"SURFEX#TREEDRAG#FAKETREES\")}}})\n\n if self.config.get_setting(\"SURFEX#TILES#INLAND_WATER\") == \"FLAKE\":\n self.input_list.append({\"file\": self.input_path + \"/flake.json\"})\n\n def override(self):\n # Override posssibility\n if os.path.exists(self.input_path + \"/override.json\"):\n print(\"WARNING: Override settings with content from \" + self.input_path + \"/override.json\")\n self.input_list.append({\"file\": self.input_path + \"/override.json\"})\n\n @staticmethod\n def set_direct_data_namelist(lnamelist_section, ldtype, ldname, linput_path):\n if ldname.endswith(\".dir\"):\n basename = os.path.splitext(os.path.basename(ldname))[0]\n filetype_name = ldtype\n if ldtype == \"YSOC_TOP\" or ldtype == \"YSOC_SUB\":\n filetype_name = \"YSOC\"\n return {\"json\": json.loads('{\"' + lnamelist_section + '\": { \"' + ldtype + '\": \"' + basename + '\", ' + '\"' +\n filetype_name + 'FILETYPE\": \"DIRECT\"}}')}\n elif ldname.endswith(\".json\"):\n return {\"file\": linput_path + \"/\" + ldname}\n\n @staticmethod\n def set_dirtyp_data_namelist(lnamelist_section, ldtype, ldname, vtype=None, decade=None):\n basename = os.path.splitext(os.path.basename(ldname))[0]\n filetype_name = ldtype.upper()\n if vtype is not None or decade is not None:\n filetype_name = filetype_name + \"(\"\n if vtype is not None:\n filetype_name = filetype_name + str(vtype)\n if vtype is not None and decade is not None:\n filetype_name = filetype_name + \",\"\n if decade is not None:\n filetype_name = filetype_name + str(decade)\n if vtype is not None or decade is not None:\n filetype_name = filetype_name + \")\"\n return {\n \"json\": json.loads('{\"' + lnamelist_section + '\": { \"CFNAM_' + filetype_name + '\": \"' + basename + '\", ' +\n '\"CFTYP_' + filetype_name + '\": \"DIRTYPE\"}}')\n }\n\n @staticmethod\n def capitalize_namelist_dict(dict_in):\n new_dict = {}\n for key in dict_in:\n upper_case2 = {}\n for key2 in dict_in[key]:\n upper_case2.update({key2.upper(): dict_in[key][key2]})\n new_dict.update({key.upper(): upper_case2})\n return new_dict\n\n @staticmethod\n def lower_case_namelist_dict(dict_in):\n # print(dict_in)\n new_dict = {}\n for key in dict_in:\n lower_case_dict = {}\n # print(key)\n for key2 in dict_in[key]:\n lower_case_dict.update({key2.lower(): dict_in[key][key2]})\n new_dict.update({key.lower(): lower_case_dict})\n return new_dict\n\n @staticmethod\n def merge_namelist_dicts(old_dict, new_dict):\n old_dict = Namelist.capitalize_namelist_dict(old_dict)\n new_dict = Namelist.capitalize_namelist_dict(new_dict)\n merged_dict = old_dict\n\n for new_key in new_dict:\n # Namelist block already exists\n if new_key in merged_dict:\n settings = merged_dict[new_key]\n for new_key2 in new_dict[new_key]:\n settings.update({new_key2: new_dict[new_key][new_key2]})\n\n merged_dict.update({new_key: settings})\n # New namelist block\n else:\n merged_dict.update({new_key: new_dict[new_key]})\n\n return merged_dict\n\n @staticmethod\n def ascii2nml(input_data):\n output_data = f90nml.Namelist(input_data)\n return output_data\n\n @staticmethod\n def ascii_file2nml(input_fname, input_fmt=\"json\"):\n if input_fmt == 'json':\n with open(input_fname) as input_file:\n output_data = json.load(input_file)\n elif input_fmt == 'yaml':\n with open(input_fname) as input_file:\n output_data = yaml.safe_load(input_file)\n output_data = f90nml.Namelist(output_data)\n return output_data\n\n @staticmethod\n def nml2ascii(input_data, output_file, output_fmt=\"json\", indent=2):\n if output_fmt == 'json':\n input_data = input_data.todict(complex_tuple=True)\n json.dump(input_data, open(output_file, \"w\"), indent=indent, separators=(',', ': '))\n elif output_fmt == 'yaml':\n input_data = input_data.todict(complex_tuple=True)\n yaml.dump(input_data, output_file, default_flow_style=False)\n\n @staticmethod\n def merge_json_namelist_file(old_dict, my_file):\n\n print(my_file)\n if os.path.exists(my_file):\n new_dict = json.load(open(my_file, \"r\"))\n else:\n raise FileNotFoundError\n\n return Namelist.merge_namelist_dicts(old_dict, new_dict)\n\n def get_namelist(self):\n print(\"Constructing namelist:\")\n merged_json_settings = {}\n for inp in self.input_list:\n if \"file\" in inp:\n json_file = str(inp[\"file\"])\n if not os.path.exists(json_file):\n print(\"Needed namelist input does not exist: \" + json_file)\n raise FileNotFoundError\n else:\n merged_json_settings = self.merge_json_namelist_file(merged_json_settings, json_file)\n elif \"json\" in inp:\n merged_json_settings = self.merge_namelist_dicts(merged_json_settings, inp[\"json\"])\n else:\n print(\"Can not handle input type \"+str(inp))\n raise Exception\n\n return self.ascii2nml(merged_json_settings)\n\n\nclass Sfx81(BaseNamelist):\n def __init__(self, program, config, input_path, **kwargs):\n BaseNamelist.__init__(self, program, config, input_path, **kwargs)\n\n\nclass Cy46(BaseNamelist):\n def __init__(self, program, config, input_path, **kwargs):\n BaseNamelist.__init__(self, program, config, input_path, **kwargs)\n\n\nclass Cy43(BaseNamelist):\n def __init__(self, program, config, input_path, **kwargs):\n BaseNamelist.__init__(self, program, config, input_path, **kwargs)\n\n\nclass Cy40(BaseNamelist):\n def __init__(self, program, config, input_path, **kwargs):\n BaseNamelist.__init__(self, program, config, input_path, **kwargs)\n\n\nclass Namelist(Cy40, Cy43, Cy46, Sfx81, BaseNamelist):\n def __init__(self, cycle, program, config, input_path, **kwargs):\n if cycle.lower() == \"base\":\n BaseNamelist.__init__(self, program, config, input_path, **kwargs)\n elif cycle.lower() == \"sfx81\":\n Sfx81.__init__(self, program, config, input_path, **kwargs)\n elif cycle.lower() == \"cy46\":\n Cy46.__init__(self, program, config, input_path, **kwargs)\n elif cycle.lower() == \"cy43\":\n Cy43.__init__(self, program, config, input_path, **kwargs)\n elif cycle.lower() == \"cy40\":\n Cy40.__init__(self, program, config, input_path, **kwargs)\n else:\n raise Exception()\n\n\nclass Ecoclimap(object):\n def __init__(self, config, system_file_paths=None):\n\n self.config = config\n self.system_file_paths = system_file_paths\n self.cover_dir = \"ecoclimap_cover_dir\"\n self.bin_dir = \"ecoclimap_bin_dir\"\n self.ecoclimap_files = [\"ecoclimapI_covers_param.bin\", \"ecoclimapII_af_covers_param.bin\",\n \"ecoclimapII_eu_covers_param.bin\"]\n self.decadal_data_types = None\n\n def set_input(self, check_existence=True):\n if self.system_file_paths is None:\n raise Exception(\"System file path must be set for this method\")\n data = {}\n for fname in self.ecoclimap_files:\n fname_data = self.system_file_paths.get_system_file(self.bin_dir, fname, default=\"climdir\",\n check_existence=check_existence)\n data.update({fname: fname_data})\n return data\n\n def set_bin_files(self, check_existence=True):\n return self.set_input(check_existence=check_existence)\n\n\nclass EcoclimapSG(Ecoclimap):\n def __init__(self, config, system_file_paths=None, veg_types=20, decades=36):\n Ecoclimap.__init__(self, config, system_file_paths=system_file_paths)\n self.veg_types = veg_types\n self.decades = decades\n self.cover_file = self.config.get_setting(\"SURFEX#COVER#SG\")\n self.cover_dir = \"ecoclimap_sg_cover_dir\"\n self.decadal_data_types = [\"ALBNIR_SOIL\", \"ALBNIR_VEG\", \"ALBVIS_SOIL\", \"ALBVIS_VEG\", \"LAI\"]\n\n def set_bin_files(self, check_existence=True):\n pass\n\n def set_input(self, check_existence=True):\n if self.system_file_paths is None:\n raise Exception(\"System file path must be set for this method\")\n\n data = {}\n tree_height_dir = \"tree_height_dir\"\n fname = self.config.get_setting(\"SURFEX#COVER#H_TREE\")\n if fname != \"\" and fname is not None:\n ext_data = ExternalSurfexInputFile(self.system_file_paths)\n data.update(ext_data.set_input_data_from_format(tree_height_dir, fname, check_existence=check_existence))\n\n decadal_data_types = [\"ALBNIR_SOIL\", \"ALBNIR_VEG\", \"ALBVIS_SOIL\", \"ALBVIS_VEG\", \"LAI\"]\n for decadal_data_type in decadal_data_types:\n for vt in range(1, self.veg_types + 1):\n for decade in range(1, self.decades + 1):\n filepattern = self.config.get_setting(\"SURFEX#COVER#\" + decadal_data_type, check_parsing=False)\n fname = self.parse_fnames(filepattern, decade)\n dtype = decadal_data_type.lower() + \"_dir\"\n ext_data = ExternalSurfexInputFile(self.system_file_paths)\n data.update(ext_data.set_input_data_from_format(dtype, fname, check_existence=check_existence))\n return data\n\n @staticmethod\n def parse_fnames(filepattern, decade):\n filename = filepattern\n decade = decade - 1\n mm = int(decade / 3) + 1\n mm = \"{:02d}\".format(mm)\n cdd = ((decade % 3) * 10) + 5\n cdd = \"{:02d}\".format(cdd)\n filename = filename.replace(\"@MM@\", str(mm))\n filename = filename.replace(\"@CDD@\", str(cdd))\n return filename\n\n\nclass PgdInputData(surfex.JsonInputData):\n\n def __init__(self, config, system_file_paths, **kwargs):\n\n # Ecoclimap settings\n eco_sg = config.get_setting(\"SURFEX#COVER#SG\")\n if eco_sg:\n ecoclimap = EcoclimapSG(config, system_file_paths=system_file_paths)\n else:\n ecoclimap = Ecoclimap(config, system_file_paths=system_file_paths)\n\n check_existence = True\n if \"check_existence\" in kwargs:\n check_existence = kwargs[\"check_existence\"]\n data = ecoclimap.set_input(check_existence=check_existence)\n\n kwargs.update({\"check_existence\": check_existence})\n ext_data = ExternalSurfexInputFile(system_file_paths)\n # Set direct input files\n if config.get_setting(\"SURFEX#TILES#INLAND_WATER\") == \"FLAKE\":\n version = config.get_setting(\"SURFEX#FLAKE#LDB_VERSION\")\n if version != \"\":\n version = \"_V\" + version\n datadir = \"flake_dir\"\n fname = \"GlobalLakeDepth\" + version + \".dir\"\n linkbasename = \"GlobalLakeDepth\"\n data.update(ext_data.set_input_data_from_format(datadir, fname, default_dir=\"climdir\",\n linkbasename=linkbasename, **kwargs))\n fname = \"GlobalLakeStatus\" + version + \".dir\"\n linkbasename = \"GlobalLakeStatus\"\n data.update(ext_data.set_input_data_from_format(datadir, fname, default_dir=\"climdir\",\n linkbasename= linkbasename, **kwargs))\n\n possible_direct_data = {\n \"ISBA\": {\n \"YSAND\": \"sand_dir\",\n \"YCLAY\": \"clay_dir\",\n \"YSOC_TOP\": \"soc_top_dir\",\n \"YSOC_SUB\": \"soc_sub_dir\"\n },\n \"COVER\": {\n \"YCOVER\": ecoclimap.cover_dir\n },\n \"ZS\": {\n \"YZS\": \"oro_dir\"\n }\n }\n for namelist_section in possible_direct_data:\n for ftype in possible_direct_data[namelist_section]:\n data_dir = possible_direct_data[namelist_section][ftype]\n fname = str(config.get_setting(\"SURFEX#\" + namelist_section + \"#\" + ftype))\n data.update(ext_data.set_input_data_from_format(data_dir, fname, default_dir=\"climdir\", **kwargs))\n\n # Treedrag\n if config.get_setting(\"SURFEX#TREEDRAG#TREEDATA_FILE\") != \"\":\n fname = config.get_setting(\"SURFEX#TREEDRAG#TREEDATA_FILE\")\n data_dir = \"tree_height_dir\"\n data.update(ext_data.set_input_data_from_format(data_dir, fname, default_dir=\"climdir\", **kwargs))\n\n surfex.JsonInputData.__init__(self, data)\n\n\nclass PrepInputData(surfex.JsonInputData):\n\n def __init__(self, config, system_file_paths, **kwargs):\n\n prep_file = None\n if \"prep_file\" in kwargs:\n prep_file = kwargs[\"prep_file\"]\n prep_pgdfile = None\n if \"prep_pgdfile\" in kwargs:\n prep_pgdfile = kwargs[\"prep_pgdfile\"]\n\n check_existence = True\n if \"check_existence\" in kwargs:\n check_existence = kwargs[\"check_existence\"]\n\n data = {}\n # Ecoclimap settings\n eco_sg = config.get_setting(\"SURFEX#COVER#SG\")\n if not eco_sg:\n ecoclimap = Ecoclimap(config, system_file_paths)\n data.update(ecoclimap.set_bin_files(check_existence=check_existence))\n\n print(\"prep class \", system_file_paths.__class__)\n ext_data = ExternalSurfexInputFile(system_file_paths)\n # ext_data = system_file_paths\n if prep_file is not None:\n if not prep_file.endswith(\".json\"):\n fname = os.path.basename(prep_file)\n if fname != prep_file:\n data.update({fname: prep_file})\n if prep_pgdfile is not None:\n fname = os.path.basename(prep_pgdfile)\n if fname != prep_pgdfile:\n data.update({fname: prep_pgdfile})\n\n if config.get_setting(\"SURFEX#TILES#INLAND_WATER\") == \"FLAKE\":\n data_dir = \"flake_dir\"\n fname = \"LAKE_LTA_NEW.nc\"\n data.update(ext_data.set_input_data_from_format(data_dir, fname, default_dir=\"climdir\",\n check_existence=check_existence))\n\n surfex.JsonInputData.__init__(self, data)\n\n\nclass OfflineInputData(surfex.JsonInputData):\n\n def __init__(self, config, system_file_paths, **kwargs):\n\n check_existence = True\n if \"check_existence\" in kwargs:\n check_existence = kwargs[\"check_existence\"]\n\n data = {}\n # Ecoclimap settings\n eco_sg = config.get_setting(\"SURFEX#COVER#SG\")\n if not eco_sg:\n ecoclimap = Ecoclimap(config, system_file_paths)\n data.update(ecoclimap.set_bin_files(check_existence=check_existence))\n\n data_dir = \"forcing_dir\"\n if config.get_setting(\"SURFEX#IO#CFORCING_FILETYPE\") == \"NETCDF\":\n fname = \"FORCING.nc\"\n data.update({fname: system_file_paths.get_system_file(data_dir, fname, default_dir=None)})\n else:\n raise NotImplementedError\n\n surfex.JsonInputData.__init__(self, data)\n\n\nclass InlineForecastInputData(surfex.JsonInputData):\n\n def __init__(self, config, system_file_paths, **kwargs):\n\n check_existence = True\n if \"check_existence\" in kwargs:\n check_existence = kwargs[\"check_existence\"]\n\n data = {}\n # Ecoclimap settings\n eco_sg = config.get_setting(\"SURFEX#COVER#SG\")\n if not eco_sg:\n ecoclimap = Ecoclimap(config, system_file_paths)\n data.update(ecoclimap.set_bin_files(check_existence=check_existence))\n\n surfex.JsonInputData.__init__(self, data)\n\n\nclass SodaInputData(surfex.JsonInputData):\n\n \"\"\"\n This class set\n \"\"\"\n\n def __init__(self, config, system_file_paths, **kwargs):\n\n check_existence = True\n if \"check_existence\" in kwargs:\n check_existence = kwargs[\"check_existence\"]\n\n kwargs.update({\"verbosity\": 6})\n self.config = config\n self.system_file_paths = system_file_paths\n self.file_paths = ExternalSurfexInputFile(self.system_file_paths)\n dtg = None\n if \"dtg\" in kwargs:\n dtg = kwargs[\"dtg\"]\n if isinstance(dtg, str):\n dtg = datetime.strptime(dtg, \"%Y%m%d%H\")\n self.dtg = dtg\n surfex.JsonInputData.__init__(self, {})\n\n # Ecoclimap settings\n eco_sg = self.config.get_setting(\"SURFEX#COVER#SG\")\n if not eco_sg:\n ecoclimap = Ecoclimap(self.config, self.system_file_paths)\n self.add_data(ecoclimap.set_bin_files(check_existence=check_existence))\n\n # OBS\n self.add_data(self.set_input_observations(check_existence=check_existence))\n\n # SEA\n if self.config.get_setting(\"SURFEX#ASSIM#SCHEMES#SEA\") != \"NONE\":\n if self.config.get_setting(\"SURFEX#ASSIM#SCHEMES#SEA\") == \"INPUT\":\n self.add_data(self.set_input_sea_assimilation(check_existence=check_existence))\n\n # WATER\n if self.config.get_setting(\"SURFEX#ASSIM#SCHEMES#INLAND_WATER\") != \"NONE\":\n pass\n\n # NATURE\n if self.config.get_setting(\"SURFEX#ASSIM#SCHEMES#ISBA\") != \"NONE\":\n if self.config.setting_is(\"SURFEX#ASSIM#SCHEMES#ISBA\", \"EKF\"):\n self.add_data(self.set_input_vertical_soil_ekf(**kwargs))\n if self.config.setting_is(\"SURFEX#ASSIM#SCHEMES#ISBA\", \"OI\"):\n self.add_data(self.set_input_vertical_soil_oi(**kwargs))\n\n # Town\n if self.config.get_setting(\"SURFEX#ASSIM#SCHEMES#TEB\") != \"NONE\":\n pass\n\n def set_input_observations(self, check_existence=True):\n\n cfile_format_obs = self.config.get_setting(\"SURFEX#ASSIM#OBS#CFILE_FORMAT_OBS\")\n if cfile_format_obs == \"ASCII\":\n if self.dtg is None:\n raise Exception(\"Obs ASCII file needs DTG information\")\n yy = self.dtg.strftime(\"%y\")\n mm = self.dtg.strftime(\"%m\")\n dd = self.dtg.strftime(\"%d\")\n hh = self.dtg.strftime(\"%H\")\n target = \"OBSERVATIONS_\" + yy + mm + dd + \"H\" + hh + \".DAT\"\n elif cfile_format_obs == \"FA\":\n target = \"ICMSHANAL+0000\"\n else:\n raise NotImplementedError(cfile_format_obs)\n\n data_dir = \"obs_dir\"\n obsfile = self.system_file_paths.get_system_file(data_dir, target, default_dir=\"assim_dir\",\n check_existence=check_existence, basedtg=self.dtg, verbosity=5)\n obssettings = {\n target: obsfile\n }\n return obssettings\n\n def set_input_sea_assimilation(self, check_existence=True):\n\n cfile_format_sst = self.config.get_setting(\"SURFEX#ASSIM#SEA#CFILE_FORMAT_SST\")\n if cfile_format_sst.upper() == \"ASCII\":\n target = \"SST_SIC.DAT\"\n elif cfile_format_sst.upper() == \"FA\":\n target = \"SST_SIC\"\n else:\n raise NotImplementedError(cfile_format_sst)\n\n # data_dir = self.system_file_paths.get_system_path(\"sst_file_dir\", basedtg=self.dtg, default_dir=\"assim_dir\")\n data_dir = \"sst_file_dir\"\n sstfile = self.system_file_paths.get_system_file(data_dir, target, basedtg=self.dtg,\n check_existence=check_existence, default_dir=\"assim_dir\")\n sea_settings = {\n target: sstfile\n }\n return sea_settings\n\n def set_input_vertical_soil_oi(self, **kwargs):\n\n oi_settings = {}\n # Climate\n cfile_format_clim = self.config.get_setting(\"SURFEX#ASSIM#ISBA#OI#CFILE_FORMAT_CLIM\")\n if cfile_format_clim.upper() == \"ASCII\":\n target = \"CLIMATE.DAT\"\n elif cfile_format_clim.upper() == \"FA\":\n target = \"clim_isba\"\n else:\n raise NotImplementedError(cfile_format_clim)\n\n data_dir = \"climdir\"\n climfile = self.system_file_paths.get_system_file(data_dir, target, default_dir=\"assim_dir\",\n check_existence=True)\n oi_settings.update({target: climfile})\n\n # First guess for SURFEX\n cfile_format_fg = self.config.get_setting(\"SURFEX#ASSIM#ISBA#OI#CFILE_FORMAT_FG\")\n if cfile_format_fg.upper() == \"ASCII\":\n if self.dtg is None:\n raise Exception(\"First guess in ASCII format needs DTG information\")\n yy = self.dtg.strftime(\"%y\")\n mm = self.dtg.strftime(\"%m\")\n dd = self.dtg.strftime(\"%d\")\n hh = self.dtg.strftime(\"%H\")\n target = \"FIRST_GUESS_\" + yy + mm + dd + \"H\" + hh + \".DAT\"\n elif cfile_format_fg.upper() == \"FA\":\n target = \"FG_OI_MAIN\"\n else:\n raise NotImplementedError(cfile_format_fg)\n\n data_dir = \"first_guess_dir\"\n first_guess = self.system_file_paths.get_system_file(data_dir, target, default_dir=\"assim_dir\",\n basedtg=self.dtg, check_existence=True)\n oi_settings.update({target: first_guess})\n\n data_dir = \"ascat_dir\"\n ascatfile = self.system_file_paths.get_system_file(data_dir, target, default_dir=\"assim_dir\",\n basedtg=self.dtg, check_existence=True)\n oi_settings.update({\"ASCAT_SM.DAT\": ascatfile})\n\n # OI coefficients\n data_dir = \"oi_coeffs_dir\"\n oi_coeffs = self.config.get_setting(\"SURFEX#ASSIM#ISBA#OI#COEFFS\")\n oi_coeffs = self.system_file_paths.get_system_file(data_dir, oi_coeffs, default_dir=\"assim_dir\",\n check_existence=True)\n oi_settings.update({\"fort.61\": oi_coeffs})\n\n # LSM\n cfile_format_lsm = self.config.get_setting(\"SURFEX#ASSIM#CFILE_FORMAT_LSM\")\n if cfile_format_lsm.upper() == \"ASCII\":\n target = \"LSM.DAT\"\n elif cfile_format_lsm.upper() == \"FA\":\n target = \"FG_OI_MAIN\"\n else:\n raise NotImplementedError(cfile_format_lsm)\n\n data_dir = \"lsm_dir\"\n lsmfile = self.system_file_paths.get_system_file(data_dir, target, default_dir=\"assim_dir\",\n basedtg=self.dtg, check_existence=True)\n oi_settings.update({target: lsmfile})\n return oi_settings\n\n def set_input_vertical_soil_ekf(self, **kwargs):\n\n if self.dtg is None:\n raise Exception(\"You must set DTG\")\n\n yy = self.dtg.strftime(\"%y\")\n mm = self.dtg.strftime(\"%m\")\n dd = self.dtg.strftime(\"%d\")\n hh = self.dtg.strftime(\"%H\")\n ekf_settings = {}\n\n geo = self.config.get_setting(\"GEOMETRY#GEO\")\n # First guess for SURFEX\n csurf_filetype = self.config.get_setting(\"SURFEX#IO#CSURF_FILETYPE\").lower()\n\n check_existence = True\n if \"check_existence\" in kwargs:\n check_existence = kwargs[\"check_existence\"]\n\n # TODO\n fcint = 3\n fg_dtg = self.dtg - timedelta(hours=fcint)\n fg = self.config.get_setting(\"SURFEX#IO#CSURFFILE\", validtime=self.dtg, basedtg=fg_dtg)\n if csurf_filetype == \"ascii\":\n fg_file = surfex.AsciiSurfexFile(fg, geo=geo)\n fg = fg_file.filename\n elif csurf_filetype == \"nc\":\n fg_file = surfex.NCSurfexFile(fg, geo=geo)\n fg = fg_file.filename\n elif csurf_filetype == \"fa\":\n lfagmap = self.config.get_setting(\"SURFEX#IO#LFAGMAP\")\n # TODO for now assume that first guess always is a inline forecast with FA format\n masterodb = True\n if \"masterodb\" in kwargs:\n masterodb = kwargs[\"masterodb\"]\n fg_file = surfex.FaSurfexFile(fg, lfagmap=lfagmap, geo=geo, masterodb=masterodb)\n fg = fg_file.filename\n else:\n raise NotImplementedError\n\n data_dir = \"first_guess_dir\"\n first_guess = self.system_file_paths.get_system_file(data_dir, fg, default_dir=\"assim_dir\",\n validtime=self.dtg, basedtg=fg_dtg,\n check_existence=check_existence)\n\n # We newer run inline model for perturbations or in SODA\n extension = fg_file.extension\n if csurf_filetype == \"fa\":\n extension = \"fa\"\n\n ekf_settings.update({\"PREP_INIT.\" + extension: first_guess})\n ekf_settings.update({\"PREP_\" + yy + mm + dd + \"H\" + hh + \".\" + extension: first_guess})\n\n nncv = self.config.get_setting(\"SURFEX#ASSIM#ISBA#EKF#NNCV\")\n llincheck = self.config.get_setting(\"SURFEX#ASSIM#ISBA#EKF#LLINCHECK\")\n lnncv = len(nncv) + 1\n if llincheck:\n lnncv = (len(nncv) * 2) + 1\n pert_ekf = 0\n pert_input = 0\n for p in range(0, lnncv):\n exists = False\n if p > 0:\n pp = p\n if llincheck and p > len(nncv):\n pp = p - len(nncv)\n if nncv[pp-1] == 1:\n exists = True\n pert_input = p\n else:\n exists = True\n\n if exists:\n data_dir = \"perturbed_run_dir\"\n if \"perturbed_file_pattern\" in kwargs:\n perturbed_file_pattern = kwargs[\"perturbed_file_pattern\"]\n else:\n print(\"Use default CSURFFILE for perturbed file names\")\n perturbed_file_pattern = self.config.get_setting(\"SURFEX#IO#CSURFFILE\", check_parsing=False) \\\n + \".\" + extension\n\n # TODO depending on when perturbations are run\n perturbed_run = self.system_file_paths.get_system_file(data_dir, perturbed_file_pattern,\n validtime=self.dtg, basedtg=fg_dtg,\n check_existence=check_existence,\n default_dir=\"assim_dir\",\n pert=pert_input)\n\n target = \"PREP_\" + yy + mm + dd + \"H\" + hh + \"_EKF_PERT\" + str(pert_ekf) + \".\" + extension\n ekf_settings.update({target: perturbed_run})\n pert_ekf = pert_ekf + 1\n\n # LSM\n # Fetch first_guess needed for LSM for extrapolations\n if self.config.get_setting(\"SURFEX#ASSIM#INLAND_WATER#LEXTRAP_WATER\"):\n cfile_format_lsm = self.config.get_setting(\"SURFEX#ASSIM#CFILE_FORMAT_LSM\")\n if cfile_format_lsm.upper() == \"ASCII\":\n target = \"LSM.DAT\"\n elif cfile_format_lsm.upper() == \"FA\":\n target = \"FG_OI_MAIN\"\n else:\n raise NotImplementedError(cfile_format_lsm)\n\n data_dir = \"lsm_dir\"\n lsmfile = self.system_file_paths.get_system_file(data_dir, target, default_dir=\"assim_dir\",\n validtime=self.dtg, basedtg=fg_dtg,\n check_existence=check_existence)\n ekf_settings.update({target: lsmfile})\n return ekf_settings\n","sub_path":"surfex/namelist.py","file_name":"namelist.py","file_ext":"py","file_size_in_byte":64988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"29464773","text":"#!/usr/bin/env python3\nimport sys\n\n\ndef solve(N: int, K: int, p: \"List[int]\"):\n p = [(p_ +1)/2 for p_ in p]\n temp = sum(p[0:K])\n max_s = temp\n\n for i in range(K, N):\n temp = temp - p[i-K] + p[i]\n max_s = max(max_s, temp)\n \n print(max_s)\n\n\n\n\n return\n\n\n# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools (tips: You use the default template now. You can remove this line by using your custom template)\ndef main():\n def iterate_tokens():\n for line in sys.stdin:\n for word in line.split():\n yield word\n tokens = iterate_tokens()\n N = int(next(tokens)) # type: int\n K = int(next(tokens)) # type: int\n p = [int(next(tokens)) for _ in range(N)] # type: \"List[int]\"\n solve(N, K, p)\n\nif __name__ == '__main__':\n main()\n","sub_path":"abc154/D/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"204896548","text":"from __future__ import absolute_import, division\n\nfrom psychopy import locale_setup\nfrom psychopy import prefs\nfrom psychopy import gui, visual, core, data, event, logging, clock\nfrom psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,\n STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)\n\nimport numpy as np # whole numpy lib is available, prepend 'np.'\nfrom numpy import (sin, cos, tan, log, log10, pi, average,\n sqrt, std, deg2rad, rad2deg, linspace, asarray)\nfrom numpy.random import random, randint, normal, shuffle\nimport os # handy system and path functions\nimport sys # to get file system encoding\n\nfrom psychopy import prefs\nprefs.hardware['audioLib'] = ['PTB']\nfrom psychopy import sound\n\nfrom psychopy.hardware import keyboard\nimport serial\nfrom psychopy import parallel\n\nimport csv\n\nMODE_EXP = 1\nMODE_DEV = 2\n\nTRIGGER_BASELINE = 128\n\nTRIGGER_ANOMALOUS = 64\nTRIGGER_EXPECTED = 32\nTRIGGER_PSEUDOWORD = 16\nTRIGGER_UNEXPECTED = 8\n\nclass Experiment:\n \n def __init__(self):\n \"\"\"\n Constructor which sets up a number of general attributes and defaults.\n \"\"\"\n self.pauseClock = core.Clock() \n self.psychopyVersion = '3.2.4'\n self.globalClock = core.Clock() # to track the time since experiment started\n self.routineTimer = core.CountdownTimer()\n self.defaultKeyboard = keyboard.Keyboard()\n self.frameTolerance = 0.001 \n self.endExpNow = False\n #self.serialPort = 'COM1'\n \n def start(self):\n self.setup()\n\n run = int(self.expInfo['run'])\n mode = self.expInfo['mode']\n stimList = self.expInfo['list']\n if stimList == 'generate':\n list = ''\n\n if mode == 'training':\n self.startTraining()\n elif mode == 'experiment':\n self.startExperiment(list, run)\n else:\n print('Unknown mode. Use either \"training\" or \"experiment\"')\n\n\n \n def startExperiment(self, stimuli_list, run):\n \"\"\"\n Start the experiment with the specified stimuli list.\n\n Parameters\n ----------\n stimuli_list : str\n list of stimuli to use. Only specify the name of the list. \n The respective file should reside in the folder of the python file. Wav-files should be stored in a subfolder \"wav\" without further subdirectories.\n If stimuli_list is empty, a reandomized list will be generated or used if it is already present. These lists are created for each\n participant and session and are stored in the subfolder 'stim_lists'\n \"\"\"\n if not stimuli_list:\n filenames, responseTimes = self.generateOrReadStimulusList(run)\n else:\n filenames, responseTimes = self.readStimulusList(stimuli_list)\n\n self.setupTriggers() \n self.waitForButton(-1, ['space'], 'Press space to start') \n self.fixation.autoDraw = True\n self.presentSound('wav' + os.sep + 'Instruktionen.wav')\n self.fixation.autoDraw = False\n self.waitForButton(-1, ['space'], 'Press space to start') \n self.fixation.autoDraw = True\n self.wait(1)\n for n in range(0, len(filenames)):\n path = 'wav' + os.sep + filenames[n]\n condition = filenames[n].split('_')\n self.presentSound(path, responseTime=responseTimes[n]/1000, condition = condition[0])\n self.finish()\n\n def startTraining(self):\n \"\"\"\n Start a training run which always uses the standard training stimuli list: stimuli_list_training.csv\n \"\"\"\n filenames, responseTimes = self.readStimulusList('stimuli_list_training.csv')\n startTriggers(self)\n self.waitForButton(-1, ['space'], 'Press space to start')\n self.presentSound('wav' + os.sep +'Instruktionen.wav')\n self.waitForButton(-1, ['space'], 'Press space to continue')\n self.fixation.autoDraw = False\n for n in range(0, len(filenames)):\n path = 'wav' + os.sep + filenames[n]\n condition = filenames[n].split('_')\n self.presentSound(path, responseTime=responseTimes[n]/1000, condition = condition[0])\n self.finish()\n\n def setup(self):\n \"\"\"\n Setup experiment info, log file and window\n \"\"\"\n self._thisDir = os.path.dirname(os.path.abspath(__file__))\n os.chdir(self._thisDir)\n expName = 'SemanticIntegration' # from the Builder filename that created this script\n expInfo = {'mode': 'experiment', 'participant': '', 'session': '001', 'run': '1', 'list': 'generate', 'screen': '0', 'Send triggers': 'yes'}\n dlg = gui.DlgFromDict(dictionary=expInfo, sortKeys=False, title=expName)\n if dlg.OK == False:\n core.quit() # user pressed cancel\n expInfo['date'] = data.getDateStr() # add a simple timestamp\n expInfo['expName'] = expName\n expInfo['psychopyVersion'] = self.psychopyVersion\n filename = self._thisDir + os.sep + u'data/%s_%s_%s_%s' % (expInfo['participant'], expName, expInfo['run'], expInfo['date'])\n self.thisExp = data.ExperimentHandler(name=expName, version='',\n extraInfo=expInfo, runtimeInfo=None,\n originPath=self._thisDir + os.sep + 'SemanticIntegration.py',\n savePickle=True, saveWideText=True,\n dataFileName=filename)\n self.logFile = logging.LogFile(filename+'.log', level=logging.EXP)\n logging.console.setLevel(logging.WARNING) \n\n #self.serial = serial.Serial(self.serialPort, 19200, timeout=1)\n\n self.win = visual.Window(\n size=(1024, 768), fullscr=False, screen=int(expInfo['screen']), \n winType='pyglet', allowGUI=False, allowStencil=False,\n monitor='testMonitor', color='black', colorSpace='rgb',\n blendMode='avg', useFBO=True, \n units='height')\n\n # fixation cross\n self.fixation = visual.TextStim(win=self.win, name='fixation',\n text='+',\n font='Arial',\n pos=(0, 0), height=0.1, wrapWidth=None, ori=0, \n color='white', colorSpace='rgb', opacity=1, \n languageStyle='LTR',\n depth=0.0)\n self.fixation.autoDraw = False\n\n self.message = visual.TextStim(win=self.win, name='message',\n text='Press key to start',\n font='Arial',\n pos=(0, 0), height=0.1, wrapWidth=None, ori=0, \n color='white', colorSpace='rgb', opacity=1, \n languageStyle='LTR',\n depth=0.0)\n \n self.expInfo = expInfo\n self.expName = expName\n \n if expInfo['Send triggers'] == \"yes\":\n self.mode = MODE_EXP\n else:\n self.mode = MODE_DEV\n \n def setupTriggers(self):\n if self.mode == MODE_EXP:\n self.port = parallel.ParallelPort(address=0x0378)\n self.port.setData(0) \n\n def finish(self):\n \"\"\"\n Clean up the experiment (close serial port, etc.).\n Output files (data, logs, etc.) are automatically handled by PsychoPy (ExperimentHandler)\n \"\"\"\n #self.serial.close()\n \n\n def readStimulusList(self, filename):\n \"\"\"\n Read the specified stimuli list (csv-file with wavefile in the first and response time (in ms) in the second column) \n \n Parameters\n ----------\n filename : str\n file to read (either absolute path or relative to the folder of the python file)\n \"\"\"\n filenames = []\n responseTimes = []\n with open(filename, newline='') as csvfile:\n reader = csv.reader(csvfile, dialect='excel')\n for row in reader:\n tokens = row[0].split(';')\n filenames.append(tokens[0])\n responseTimes.append(int(tokens[1]))\n\n return filenames, responseTimes\n \n def getResponseTimeList(self, stimFiles):\n filename = self._thisDir + os.sep + u'responseTimes.csv'\n filenames, responseTimes = self.readStimulusList(filename)\n\n times = []\n for n in range(0, len(stimFiles)):\n stim = stimFiles[n]\n index = filenames.index(stim)\n times.append(responseTimes[index])\n\n return times\n \n def writeStimulusList(self, filename, stimuli, responseTimes):\n with open(filename, 'w', newline='') as csvfile:\n writer = csv.writer(csvfile, delimiter=';', dialect='excel')\n for i in range(0, len(stimuli)):\n writer.writerow([stimuli[i], responseTimes[i]])\n\n def generateOrReadStimulusList(self, run):\n stimFile = self._thisDir + os.sep + u'stim_lists\\\\%s_%s_stim_%s.csv' % (self.expInfo['participant'], self.expInfo['session'], self.expName)\n\n filenames = []\n responseTimes = []\n if os.path.exists(stimFile):\n print('Using existing stim list')\n filenames, responseTimes = self.readStimulusList(stimFile)\n else:\n print('Generating new stim list')\n filenames, responseTimes = self.generateStimulusList()\n self.writeStimulusList(stimFile, filenames, responseTimes)\n\n # Select the half corresponding to run 1 or 2\n center = int(len(filenames)/2)\n length = len(filenames)\n if run == 1:\n filenames = filenames[0:center]\n responseTimes = responseTimes[0:center]\n else:\n filenames = filenames[center:length]\n responseTimes = responseTimes[center:length]\n\n return filenames, responseTimes\n \n def generateStimulusList(self):\n sequenceA = []\n sequenceB = []\n \n expectedA = []\n expectedB = []\n inds = list(range(1, 61))\n np.random.shuffle(inds)\n for i in range(0, 30):\n expectedA.append('expected_' + str(inds[i]) + '.wav')\n sequenceA.append('exp')\n for i in range(30, 60):\n expectedB.append('expected_' + str(inds[i]) + '.wav')\n sequenceB.append('exp')\n \n anomalousA = []\n anomalousB = []\n inds = list(range(1, 61))\n np.random.shuffle(inds)\n for i in range(0, 30):\n anomalousA.append('anomalous_' + str(inds[i]) + '.wav')\n sequenceA.append('an')\n for i in range(30, 60):\n anomalousB.append('anomalous_' + str(inds[i]) + '.wav')\n sequenceB.append('an')\n \n unexpectedA = []\n unexpectedB = []\n inds = list(range(1, 61))\n np.random.shuffle(inds)\n for i in range(0, 30):\n unexpectedA.append('unexpected_' + str(inds[i]) + '.wav')\n sequenceA.append('unexp')\n for i in range(30, 60):\n unexpectedB.append('unexpected_' + str(inds[i]) + '.wav')\n sequenceB.append('unexp')\n \n pseudowordA = []\n pseudowordB = []\n inds = list(range(1, 61))\n np.random.shuffle(inds)\n for i in range(0, 60):\n version = np.random.randint(0, 2)\n if version == 0:\n pseudowordA.append('pseudoword_' + str(inds[i]) + 'a.wav')\n pseudowordB.append('pseudoword_' + str(inds[i]) + 'b.wav')\n else:\n pseudowordA.append('pseudoword_' + str(inds[i]) + 'b.wav')\n pseudowordB.append('pseudoword_' + str(inds[i]) + 'a.wav')\n \n sequenceA.append('pseudo')\n sequenceB.append('pseudo')\n \n \n keepTrying = True\n while(keepTrying):\n # shuffle sequence\n np.random.shuffle(sequenceA)\n \n # test sequence\n ok = self.checkSequence(sequenceA)\n keepTrying = not ok\n \n keepTrying = True\n while(keepTrying):\n # shuffle sequence\n np.random.shuffle(sequenceB)\n \n # test sequence\n ok = self.checkSequence(sequenceB) \n keepTrying = not ok\n\n sequence = []\n expectedA = iter(expectedA)\n unexpectedA = iter(unexpectedA)\n anomalousA = iter(anomalousA)\n pseudowordA = iter(pseudowordA)\n for i in range(0, len(sequenceA)):\n if sequenceA[i] == 'exp':\n sequence.append(next(expectedA))\n if sequenceA[i] == 'unexp':\n sequence.append(next(unexpectedA))\n if sequenceA[i] == 'an':\n sequence.append(next(anomalousA))\n if sequenceA[i] == 'pseudo':\n sequence.append(next(pseudowordA))\n \n expectedB = iter(expectedB)\n unexpectedB = iter(unexpectedB)\n anomalousB = iter(anomalousB)\n pseudowordB = iter(pseudowordB)\n for i in range(0, len(sequenceB)):\n if sequenceB[i] == 'exp':\n sequence.append(next(expectedB))\n if sequenceB[i] == 'unexp':\n sequence.append(next(unexpectedB))\n if sequenceB[i] == 'an':\n sequence.append(next(anomalousB))\n if sequenceB[i] == 'pseudo':\n sequence.append(next(pseudowordB))\n\n responseTimes = self.getResponseTimeList(sequence)\n \n return sequence, responseTimes\n \n def checkSequence(self, sequence):\n ok = True\n for i in range(2, len(sequence)):\n if (sequence[i-2] == sequence[i-1]) and (sequence[i-1] == sequence[i]):\n ok = False\n break\n return ok \n\n def presentSound(self, wavfile, responseTime=0, keyList=['1', '2'], condition='none'):\n \"\"\"\n Play a sound with additional time to wait for a key response. \n Response and reaction time relative to the end of the wave file are recorded.\n \n Parameters\n ----------\n wavfile : str \n wave file to play (either absolute path or relative to the folder of the python file)\n responseTime: double\n time in seconds to wait for a response after the end of the wave file (default: 0s)\n keyList : list of str\n list of keys to record as response. Only the first key is recorded and the response does not end the trial (default: 1 and 2)\n \"\"\"\n trialClock = core.Clock()\n wav = sound.Sound(wavfile, secs=-1, stereo=True, hamming=True, name=\"sound stimulus\")\n wav.setVolume(1)\n trialDuration = wav.getDuration() + responseTime\n keyb = keyboard.Keyboard()\n\n trialComponents = [wav] \n self.resetTrialComponents(trialComponents)\n\n response = ''\n rt = -1\n resetDone = False\n\n # reset timers\n t = 0\n startTimeGlobal = self.globalClock.getTime()\n _timeToFirstFrame = self.win.getFutureFlipTime(clock=\"now\")\n trialClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip\n frameN = -1\n continueRoutine = True\n triggerActive = False\n\n while continueRoutine:\n # get current time\n t = trialClock.getTime()\n tThisFlip = self.win.getFutureFlipTime(clock=trialClock)\n tThisFlipGlobal = self.win.getFutureFlipTime(clock=None)\n frameN = frameN + 1 # number of completed frames (so 0 is the first frame)\n # update/draw components on each frame\n \n if wav.status == NOT_STARTED and t >= 0.0-self.frameTolerance:\n # keep track of start time/frame for later\n wav.frameNStart = frameN # exact frame index\n wav.tStart = t # local t and not account for scr refresh\n wav.tStartRefresh = tThisFlipGlobal # on global time\n wav.play() # start the sound (it finishes automatically)\n startTime = trialClock.getTime()\n \n # send trigger\n if self.mode == MODE_EXP:\n if condition == \"anomalous\":\n self.port.setData(TRIGGER_ANOMALOUS)\n elif condition == \"expected\":\n self.port.setData(TRIGGER_EXPECTED)\n elif condition == \"pseudoword\":\n self.port.setData(TRIGGER_PSEUDOWORD)\n elif condition == \"unexpected\":\n self.port.setData(TRIGGER_UNEXPECTED)\n triggerActive = True\n \n # write logging info\n logging.log(level = logging.EXP, msg = 'Playback started\\t' + str(self.globalClock.getTime()) + '\\t' +wavfile)\n \n if self.mode == MODE_EXP and triggerActive and wav.status == STARTED and t >= 0.1-self.frameTolerance:\n self.port.setData(0)\n\n # Check for a response. This doesn't need to be sychronized with the next \n # frame flip\n if wav.status == FINISHED and rt == -1:\n if resetDone:\n theseKeys = event.getKeys(keyList=keyList)\n if len(theseKeys):\n response = theseKeys[0]\n rt = trialClock.getTime() - startTime\n print(response)\n logging.log(level = logging.EXP, msg = 'Response\\t' + response + '\\t' + str(rt))\n else:\n keyb.clock.reset()\n resetDone = True\n \n # check for quit (typically the Esc key)\n if self.endExpNow or event.getKeys(keyList=[\"escape\"]):\n core.quit()\n \n if wav.status == FINISHED and tThisFlipGlobal > wav.tStartRefresh + trialDuration-self.frameTolerance:\n continueRoutine = False \n \n # refresh the screen\n if continueRoutine: # don't flip if this routine is over or we'll get a blank screen\n self.win.flip()\n\n # -------Ending Routine -------\n wav.stop() # ensure sound has stopped at end of routine\n endTime = trialClock.getTime()\n logging.log(level = logging.EXP, msg = 'Trial ended\\t' + str(self.globalClock.getTime()))\n \n self.thisExp.addData('wavfile', wavfile)\n self.thisExp.addData('wav.duration', wav.getDuration())\n self.thisExp.addData('response', response)\n self.thisExp.addData('rt', rt)\n self.thisExp.addData('wav.started', wav.tStart)\n self.thisExp.addData('startTime', startTime)\n self.thisExp.addData('startTimeGlobal', startTimeGlobal)\n self.thisExp.addData('endTime', endTime)\n self.thisExp.addData('responseTime', responseTime)\n self.thisExp.nextEntry()\n \n self.routineTimer.reset()\n\n def resetTrialComponents(self, components):\n \"\"\"\n Reset the specified list of PsychoPy-components.\n \n Parameters\n ----------\n components : list of PsychoPy components\n list of PsychoPy components to reset\n \"\"\"\n for thisComponent in components:\n thisComponent.tStart = None\n thisComponent.tStop = None\n thisComponent.tStartRefresh = None\n thisComponent.tStopRefresh = None\n #if hasattr(thisComponent, 'status'):\n thisComponent.status = NOT_STARTED\n\n\n def waitForButton(self, maxTime, keyList, text):\n \"\"\"\n Wait for a button press.\n \n Parameters\n ----------\n maxTime : double\n maximum time in seconds to wait for a button press.\n If -1 is specified, the function waits until a button press with no limit\n keyList : list of str\n keys to wait for\n \"\"\"\n t = 0\n _timeToFirstFrame = self.win.getFutureFlipTime(clock=\"now\")\n self.pauseClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip\n frameN = -1\n continueRoutine = True\n key_resp = keyboard.Keyboard()\n self.resetTrialComponents([key_resp])\n self.message.text = text\n \n while continueRoutine:\n # get current time\n t = self.pauseClock.getTime()\n tThisFlip = self.win.getFutureFlipTime(clock=self.pauseClock)\n tThisFlipGlobal = self.win.getFutureFlipTime(clock=None)\n frameN = frameN + 1 # number of completed frames (so 0 is the first frame)\n # update/draw components on each frame\n \n # *key_resp* updates\n waitOnFlip = False\n if key_resp.status == NOT_STARTED and tThisFlip >= 0.0-self.frameTolerance:\n # keep track of start time/frame for later\n key_resp.frameNStart = frameN # exact frame index\n key_resp.tStart = t # local t and not account for scr refresh\n key_resp.tStartRefresh = tThisFlipGlobal # on global time\n self.win.timeOnFlip(key_resp, 'tStartRefresh') # time at next scr refresh\n key_resp.status = STARTED\n # keyboard checking is just starting\n waitOnFlip = True\n self.win.callOnFlip(key_resp.clock.reset) # t=0 on next screen flip\n self.win.callOnFlip(key_resp.clearEvents, eventType='keyboard') # clear events on next screen flip\n self.message.setAutoDraw(True)\n if key_resp.status == STARTED:\n # is it time to stop? (based on global clock, using actual start)\n if maxTime >= 0 and tThisFlipGlobal > key_resp.tStartRefresh + maxTime-self.frameTolerance:\n # keep track of stop time/frame for later\n key_resp.tStop = t # not accounting for scr refresh\n key_resp.frameNStop = frameN # exact frame index\n self.win.timeOnFlip(key_resp, 'tStopRefresh') # time at next scr refresh\n key_resp.status = FINISHED\n if key_resp.status == STARTED and not waitOnFlip:\n theseKeys = event.getKeys(keyList=keyList)\n if len(theseKeys):\n theseKeys = theseKeys[0] # at least one key was pressed\n \n # check for quit:\n if \"escape\" == theseKeys:\n self.endExpNow = True\n \n # a response ends the routine\n continueRoutine = False\n key_resp.status = FINISHED\n \n # check for quit (typically the Esc key)\n if self.endExpNow or event.getKeys(keyList=[\"escape\"]):\n core.quit()\n \n continueRoutine = False # will revert to True if at least one component still running\n \n if key_resp.status != FINISHED:\n continueRoutine = True\n \n # refresh the screen\n if continueRoutine: # don't flip if this routine is over or we'll get a blank screen\n self.win.flip()\n\n # -------Ending Routine \"pause\"-------\n \n self.message.setAutoDraw(False)\n \n # check responses\n if key_resp.keys in ['', [], None]: # No response was made\n key_resp.keys = None\n self.thisExp.addData('key_resp.keys',key_resp.keys)\n if key_resp.keys != None: # we had a response\n self.thisExp.addData('key_resp.rt', key_resp.rt)\n self.thisExp.addData('key_resp.started', key_resp.tStartRefresh)\n self.thisExp.addData('key_resp.stopped', key_resp.tStopRefresh)\n self.thisExp.nextEntry()\n\n def waitForSerial(self, numberOfSignals):\n \"\"\"\n Wait for a number of serial port signals (e.g. MRI scanner pulses)\n\n Parameters\n ----------\n numberOfSignals : int\n number of signals to wait for\n \"\"\"\n continueRoutine = True\n detected = 0\n while continueRoutine:\n value = self.serial.read()\n\n # Determine here if the values constitue a signal (TODO)\n if value > 0:\n detected = detected + 1\n\n if detected >= numberOfSignals:\n continueRoutine = False\n\n def wait(self, time):\n \"\"\"\n Wait for a specific amount of time while listening for key presses to quit the experiment.\n \n Parameters\n ----------\n time: double\n time in seconds to wait \n \"\"\"\n trialClock = core.Clock()\n trialDuration = time\n keyb = keyboard.Keyboard()\n\n # reset timers\n trialClock.reset()\n continueRoutine = True\n\n while continueRoutine:\n # get current time\n t = trialClock.getTime()\n \n # check for quit (typically the Esc key)\n if self.endExpNow or event.getKeys(keyList=[\"escape\"]):\n core.quit()\n \n if t > trialDuration:\n continueRoutine = False \n\n # refresh the screen (needed to show the fixation cross at the beginning)\n if continueRoutine: # don't flip if this routine is over or we'll get a blank screen\n self.win.flip() \n\n # -------Ending Routine -------\n self.routineTimer.reset()\n\nexperiment = Experiment()\nexperiment.start()\n\n","sub_path":"SemanticIntegration/SemanticIntegration.py","file_name":"SemanticIntegration.py","file_ext":"py","file_size_in_byte":25450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"231958869","text":"# Author : OMKAR PATHAK\n# Created at: 16th August 2017\n\nfrom functools import reduce # need this line if you're using Python3.x\n\ndef lcm(List):\n ''' function to find LCM for given list of elements\n\n :param List: List of which LCM is to be found out\n '''\n def _lcm(a, b):\n ''' helper function for finding LCM '''\n if a > b:\n greater = a\n else:\n greater = b\n\n while True:\n if greater % a == 0 and greater % b == 0:\n lcm = greater\n break\n greater += 1\n\n return lcm\n\n return reduce(lambda x, y: _lcm(x, y), List)\n\ndef get_code():\n \"\"\" returns the code for the current class \"\"\"\n import inspect\n return inspect.getsource(lcm)\n","sub_path":"pygorithm/math/lcm.py","file_name":"lcm.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"463813531","text":"# -*- coding: utf-8 -*-\n#\n# This file is part of Invenio.\n# Copyright (C) 2017-2020 CERN.\n# Copyright (C) 2020 Northwestern University.\n#\n# Invenio is free software; you can redistribute it and/or modify it\n# under the terms of the MIT License; see LICENSE file for more details.\n\n\"\"\"Schema tests.\"\"\"\n\nfrom marshmallow import Schema\nfrom test_helpers import PIDRelationsMixin\n\n\nclass SampleRecordSchema(Schema, PIDRelationsMixin):\n \"\"\"Sample record schema.\"\"\"\n pass\n\n\ndef test_schema(app, nested_pids_and_relations):\n \"\"\"Test the marshmallow schema serialization.\"\"\"\n schema = SampleRecordSchema()\n\n pids, exp_relations = nested_pids_and_relations\n for p_idx in exp_relations.keys():\n pid = pids[p_idx]\n expected = exp_relations[p_idx]\n input_data = {'pid': pid}\n schema.context['pid'] = pid\n data = schema.dump(input_data)\n assert expected == data # Test against hand-crafted fixture\n\n\ndef test_custom_schema(app, nested_pids_and_relations, custom_relation_schema):\n \"\"\"Test the marshmallow schema serialization with custom schema.\"\"\"\n schema = SampleRecordSchema()\n pids, exp_relations = nested_pids_and_relations\n\n pid = pids[4]\n input_data = {'pid': pid}\n schema.context['pid'] = pid\n data = schema.dump(input_data)\n expected = {\n 'relations': {\n 'version': [\n {\n 'children': [{'pid_type': 'recid', 'pid_value': '2'},\n {'pid_type': 'recid', 'pid_value': '3'},\n {'pid_type': 'recid', 'pid_value': '4'}],\n 'has_three_children': True,\n },\n ],\n # 'ordered': [\n # {\n # 'children': [{'pid_type': 'recid', 'pid_value': '6'},\n # {'pid_type': 'recid', 'pid_value': '4'},\n # {'pid_type': 'recid', 'pid_value': '7'}],\n # 'has_three_children': True,\n # },\n # {\n # 'children': [{'pid_type': 'recid', 'pid_value': '8'},\n # {'pid_type': 'recid', 'pid_value': '9'}],\n # 'has_three_children': False,\n # },\n # ],\n # 'unordered': [\n # {\n # 'children': [{'pid_type': 'recid', 'pid_value': '4'},\n # {'pid_type': 'recid', 'pid_value': '11'}],\n # 'has_three_children': False,\n # },\n # ],\n }\n }\n assert expected == data\n","sub_path":"tests/test_schemas.py","file_name":"test_schemas.py","file_ext":"py","file_size_in_byte":2635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"543235289","text":"import numpy as np\nimport pandas as pd\nfrom pw import piecewise, learn_pw\nimport os\n\nlearning_data_fnames = [\n 'learned.pd.pkl',\n 'learned.pd.csv',\n 'main.log',\n 'obs_data.np.pkl',\n 'early.pd.pkl',\n 'middle.pd.pkl',\n 'late.pd.pkl',\n ]\npregensplits_output_paths = [os.path.join('pregensplits_data', fname)\n for fname in learning_data_fnames]\nsplitprod_output_paths = [os.path.join('splitprod_data', fname)\n for fname in learning_data_fnames]\n\nOUTFILES = ([\n 'obsdata.np.txt',\n 'true_function.pw',\n 'pregensplits_late.pw',\n 'splitprod_late.pw',\n ]\n + pregensplits_output_paths\n + splitprod_output_paths)\n\n# Files according to the roadmap (may be out of date):\n# - obsdata.np.txt\n# * For now this can be a delta on one particular example, but should be\n# written with swappability for a different selection scheme\n# * For now x values are np.linspace(0, 10, 20) but this should be\n# swappable\n# - true_function.pw\n# * In the final version, this can be fancified into mathematical notation\n# with Latex cases, but in everything before the final, just showing\n# piecewise is sufficient\n# - pregensplits_data/learned.pd.pkl\n# * Columns: runlength, startstep, pieces, inferred_noisevars, MSE\n# - splitprod_data/learned.pd.pkl\n# - pregensplits_late.pw\n# * unboxing might be needed here\n# - splitprod_late.pw\n\n# Caution: the values of this dictionary are not protected from mutation\ndefault_params = {\n 'pregensplits_data_dir': 'pregensplits_data',\n 'splitprod_data_dir': 'splitprod_data',\n 'pregensplits_num_infsteps': 100,\n 'splitprod_num_infsteps': 100,\n }\n\n# To be mutated\nparams = default_params.copy()\n\ndef produce_all_data(**kwargs):\n params.update(kwargs)\n\n true_pw, xs = choose_trueregfn_and_xs()\n obsdata = generate_obsdata(true_pw, xs)\n np.savetxt('obsdata.np.txt', obsdata)\n with open('true_function.pw', 'wb') as outfile:\n print >> outfile, true_pw.render_text()\n\n pgs_kwargs = learn_pw.setup_pregensplits()\n pgs_kwargs['outdir'] = params['pregensplits_data_dir']\n pgs_kwargs['obs_data'] = obsdata\n pgs_kwargs['num_infsteps'] = params['pregensplits_num_infsteps']\n learn_pw.do_learning(**pgs_kwargs)\n\n spr_kwargs = learn_pw.setup_pregensplits()\n spr_kwargs['outdir'] = params['splitprod_data_dir']\n spr_kwargs['obs_data'] = obsdata\n spr_kwargs['num_infsteps'] = params['splitprod_num_infsteps']\n learn_pw.do_learning(**spr_kwargs)\n\n for kwargs in [pgs_kwargs, spr_kwargs]:\n pkl_path = os.path.join(kwargs['outdir'], 'learned.pd.pkl')\n df = pd.io.pickle.read_pickle(pkl_path)\n # TODO final_cumul_stepnum no longer exists, it is now stepnum\n T = df['stepnum'].iloc[-1]\n cumuls = {\n 'early': T/3,\n 'middle': 2*T/3,\n 'late': T,\n }\n # Select the first row whose stepnum is at least cumul, for\n # each cumul in cumuls\n rows = {name: df[df['stepnum'] >= cumul].iloc[0,:]\n for (name, cumul) in cumuls.items()}\n for (name, series) in rows.items():\n series.to_pickle(os.path.join(kwargs['outdir'], '%s.pd.pkl' % name))\n\n late = rows['late']\n late_pw = piecewise.pdseries_to_piecewise(late)\n\n # Render the \"late\" function in human-readable form\n with open(os.path.join(kwargs['outdir'], 'late.pw'), 'wb') as outfile:\n print >> outfile, late_pw.render_text()\n\ndef choose_trueregfn_and_xs():\n # TODO have param for the noise levels\n pw = piecewise.PiecewiseExpression()\n pw.add_piece([0,6], 0.01, 8.0)\n pw.add_piece([6,10], 0.01, -8.0)\n\n xs = np.linspace(0, 9.9, 20)\n return pw, xs\n\ndef generate_obsdata(pw, xs):\n pw, xs = choose_trueregfn_and_xs()\n f = pw.to_noisy_function()\n ys = np.array([f(x) for x in xs])\n return np.vstack([xs, ys]).T\n\n","sub_path":"figtwoprior/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":3987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"140970871","text":"#if else\nx = int(input(\"Please enter an integer (你的身高):\"))\n\nif x < 0:\n x = 0\n print(\"你不要搞笑好嗎\")\nelif x == 0:\n print(\"你身高是0嗎 臭侏儒\")\nelif x <= 160 :\n print(\"好矮喔 哈哈\")\nelse:\n print(\"不錯高喔\")\n\n\n","sub_path":"test1_2_1.py","file_name":"test1_2_1.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"440643790","text":"#!/usr/bin/env python3\n\nclass ContaBuraco():\n def contar(self, palavra):\n i = 0\n letras = {'A':1,'B':2,'D':1,'O':1,'P':1,'Q':1,'R':1}\n\n if (isinstance(palavra, str)):\n for letra in palavra:\n if letra in letras:\n i = i + letras[letra]\n return i\n else:\n return 0\n","sub_path":"dojo_buraco_letras/python/app/dojo.py","file_name":"dojo.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"181092337","text":"#!/usr/bin/env python\n# coding: UTF-8\n#\n## @package TextureMapInterface\n#\n# Exercises texture mapping and interface usage.\n# Implements a textured cube, which can spin around the X, Y, or Z axis, and can be rotated using Arcball.\n#\n# @author Flavia Cavalcanti\n# @since 27/02/2017\n#\n# @see http://pyopengl.sourceforge.net/context/tutorials/nehe6.html\n#\nfrom OpenGL.GL import *\nfrom OpenGL.GLUT import *\nfrom OpenGL.GLU import *\nimport time, sys, math\n\nfrom PyQt4 import QtGui\nfrom PyQt4.QtOpenGL import *\nfrom PyQt4 import QtCore\n\nfrom ArcBall import * \t\t\t\n\nimport numpy\nimport matrix\n\ntry:\n from PIL.Image import open\nexcept ImportError as err:\n from Image import open\n\nWIDTH = 700\nHEIGHT = 480\nESCAPE = b'\\033'\n\nclass GLWidget( QGLWidget ):\n\n\t## Initializes the class - first function to be called after initialization.\n\tdef __init__(self, parent = None):\n\t\tsuper(GLWidget, self).__init__(parent)\n\t\t## Whether the cube is rotating about an axis.\n\t\tself.rotating = False\n\t\t## The current model view transformation.\n\t\tself.modelView = None\n\t\t## Handle for the image used for texturing.\n\t\tself.imageID = None\n\t\t## Current active rotation axis - 0 -> x-axis, 1 -> y-axis, 2 -> z-axis\n\t\tself.index = 0\n\t\t## Whether the index (axis of rotation) has changed. \n\t\tself.indexChanged = True\n\t\t## List to store current Euler rotation angles for each axis \n\t\tself.angleList = [0, 0, 0]\n\t\t## Whether rotating through the arcball.\n\t\tself.arcBall = True\n\t\t## Image used for texturing.\n\t\tself.imgName = \"images/transistor512.jpg\"\n\n\t\t## Angle increment\n\t\tself.angInc = 1.0\n\t\t## Euler axis coordinate in the x direction.\n\t\tself.ex = None\n\t\t## Euler axis coordinate in the y direction.\n\t\tself.ey = None\n\t\t## Euler axis coordinate in the z direction.\n\t\tself.ez = None\n\t\t## Current arcball transformation: g_LastRot * g_ThisRot.\n\t\tself.g_Transform = Matrix4fT ()\n\t\t## Last arcball transformation applied.\n\t\tself.g_LastRot = Matrix3fT ()\n\t\t## Present arcball transformation.\n\t\tself.g_ThisRot = Matrix3fT ()\n\n\t\t## Whether the mouse is being dragged.\n\t\tself.g_isDragging = False\n\n\t\t## Arcball object for model rotation.\n\t\tself.g_ArcBall = ArcBallT (WIDTH, HEIGHT)\n\n\t\t## Rotation axis type\n\t\tself.rotationDirection = \"Intrinsic\"\n\n\t## Called whenever the rotation axis has changed.\n\t# \n\t# @param index new rotation axis index.\n\t#\n\tdef setIndex(self,index):\n\t\t\"\"\"Set the rotation axis.\"\"\"\n\n\t\tself.indexChanged = True\n\t\tself.index = index\n\n\t## Set the rotation type.\n\t#\n\t# @param val 0: intrinsic, 1: extrinsic, 2: ZYX.\n\t#\n\tdef setRotationDirection(self,val):\n\t\t\"\"\"Set the rotation type to Intrinsic, Extrinsic or ZYX.\"\"\"\n\n\t\tif val not in range (0,3):\n\t\t\tprint (\"Nonexistent rotation option. Check your input.\")\n\t\t\treturn \n\n\t\tdirection = (\"Intrinsic\", \"Extrinsic\", \"ZYX\")\n\n\t\t# nothing has changed\n\t\tif self.rotationDirection == direction[val]: return\n\n\t\tif self.modelView is not None:\n\t\t\tif self.rotationDirection != \"ZYX\":\n\t\t\t\tif val == 2: # extrinsic or intrinsic --> none\n\t\t\t\t\tif self.rotationDirection == \"Intrinsic\":\n\t\t\t\t\t\tself.angleList[0], self.angleList[1], self.angleList[2] = rotationMatrixToEulerAngles(self.modelView)\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.angleList[0], self.angleList[1], self.angleList[2] = rotationMatrixToEulerAngles(self.modelView.T)\n\t\t\t\t\tself.modelView = matrix.rotateXYZ(self.angleList)\n\t\t\t\telse: # extrinsic --> intrinsic or intrinsic --> extrinsic\n\t\t\t\t\t# intrinsic matrix is the inverse of extrinsic, and vice-versa.\n\t\t\t\t\tself.modelView = self.modelView.T\n\t\t\telse:\n\t\t\t\tif val == 0: # none --> intrinsic\n\t\t\t\t\t# intrinsic rotation (internal or local axes)\n\t\t\t\t\tself.modelView = self.modelView.T\n\n\t\tself.rotationDirection = direction[val]\n\n\t## Load an image file as a 2D texture using PIL.\n\tdef loadImage( self, imageName = None ):\n\t\t\"\"\"Load an image file as a 2D texture using PIL\"\"\"\n\n\t\tif imageName is None:\n\t\t\timageName = self.imgName\n\n\t\t# PIL defines an \"open\" method which is Image specific!\n\t\ttry:\n\t\t\tim = open(imageName)\n\t\t\tix, iy, image = im.size[0], im.size[1], im.tobytes(\"raw\", \"RGBA\", 0, -1)\n\t\texcept (SystemError, ValueError):\n\t\t\tix, iy, image = im.size[0], im.size[1], im.tobytes(\"raw\", \"RGBX\", 0, -1)\n\t\texcept AttributeError:\n\t\t\tix, iy, image = im.size[0], im.size[1], im.tostring(\"raw\", \"RGBX\", 0, -1)\n\t\texcept IOError:\n\t\t\tsys.exit('Cannot open file %s for reading' % imageName)\n\n\t\t# Generate a texture ID\n\t\tID = glGenTextures(1)\n\n\t\t# Make our new texture ID the current 2D texture\n\t\tglBindTexture(GL_TEXTURE_2D, ID)\n\t\tglPixelStorei(GL_UNPACK_ALIGNMENT,1)\n\n\t\t# Copy the texture data into the current texture ID\n\t\tglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, ix, iy, 0, GL_RGBA, GL_UNSIGNED_BYTE, image)\n\n\t\t# Note that only the ID is returned, no reference to the image object or the \n\t\t# string data is stored in user space. \n\t\t# The data is only present within the GL after this call exits.\n\t\treturn ID\n\n\t## Set camera parameters.\n\tdef setCamera(self):\n\t\t\"\"\"Set camera parameters.\"\"\"\n\n\t\tglMatrixMode(GL_PROJECTION)\n\t\t# Reset the Projection Matrix\n\t\tglLoadIdentity()\n\n\t\t# field of view, aspect ratio, near and far\n\t\tr = 1.0*math.sqrt(2.0) # ray of a sphere enclosing the object\n\t\td = 6.0 # distance from camera to centre of the sphere (plane z = 0)\n\t\tfovy = radToDeg((2.0*math.asin(r/d)))\n\t\tgluPerspective(fovy, float(WIDTH)/float(HEIGHT), 1.0, 10000.0)\n\n\t\tglMatrixMode (GL_MODELVIEW)\n\t\tglLoadIdentity()\n\t\tgluLookAt(3.5, 3.5, d, 0, 0, 0, 0, 1, 0)\n\n\t## Return the camera position in world coordinates.\n\t#\n\tdef getCameraPosition(self):\n\t\t\"\"\"Returns the camera position in world coordinates.\n\t\t @see https://www.opengl.org/discussion_boards/showthread.php/178484-Extracting-camera-position-from-a-ModelView-Matrix\n\t\t\"\"\"\n\n\t\t# get matrix and viewport.\n\t\tmatModelView = glGetDoublev( GL_MODELVIEW_MATRIX ) \n\t\tmatProjection = glGetDoublev( GL_PROJECTION_MATRIX ) \n\t\tviewport = glGetIntegerv( GL_VIEWPORT ) \n\t\tcamera_pos_x, camera_pos_y, camera_pos_z = gluUnProject( (viewport[2]-viewport[0])/2 , (viewport[3]-viewport[1])/2, \n\t\t0.0, matModelView, matProjection, viewport)\n\t\treturn (camera_pos_x, camera_pos_y, camera_pos_z)\n\n\t## Return the 3x3 submatrix, corresponding to the linear transformation part of a 4x4 projective matrix.\n\t#\n\t# @param mat projective matrix.\n\t# @return a 3x3 linear transformation matrix.\n\t#\n\tdef matrix4To3(self, mat):\n\t\t\"\"\"Returns the 3x3 part of a given 4x4 matrix.\"\"\"\n\n\t\tnewMat = Matrix3fT()\n\t\tfor i in range (3):\n\t\t\tfor j in range (3):\n\t\t\t\tnewMat[i][j] = mat[i,j]\n\n\t\treturn newMat\n\n\t## Return a 4x4 projective matrix, corresponding to the given 3x3 linear transformation matrix.\n\t#\n\t# @param mat linear transformation matrix.\n\t# @return a 4x4 projective matrix.\n\t#\n\tdef matrix3To4(self, mat):\n\t\t\"\"\"Returns a 4x4 matrix filled with a given 3x3 matrix.\"\"\"\n\n\t\tnewMat = Matrix4fT()\n\t\tfor i in range (len(mat)):\n\t\t\tfor j in range (len (mat[0])):\n\t\t\t\tnewMat[i][j] = mat[i][j]\n\n\t\treturn newMat\n\n\t## Return whether there is a valid Euler axis, associated to the instance vector (ex,ey,ez).\n\t#\n\tdef isEulerAxisDefined(self):\n\t\t\"\"\"Return whether there is a valid Euler axis.\"\"\"\n\t\treturn self.ex or self.ey or self.ez\n\n\t## Renders scene geometry and setups the camera and texture.\n\t# There are three transformations involved: \n\t# \t1) Camera transformation (setCamera).\n\t# \t2) Arcball transformation (g_Transform).\n\t# \t3) Spin, or cube rotation: (m).\n\t# Multiplication order: camera * arcball * spin.\n\t#\n\tdef Render( self ):\n\t\t\"\"\"Render scene geometry\"\"\"\n\n\t\t# Clear Screen And Depth Buffer\n\t\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n\n\t\tself.setCamera() \n\t\tself.drawCoordAxes(2.5)\n\n\t\tif not self.arcBall:\n\t\t\tglMatrixMode (GL_MODELVIEW)\n\n\t\t\t# If the last control scheme to be used was ArcBall, \n\t\t\t# then extract the euler angles from the last rotation matrix,\n\t\t\t# and initialize angleList to use such angles to allow for a smooth transition.\n\t\t\tif not self.rotating:\n\t\t\t\tself.angleList[0], self.angleList[1], self.angleList[2] = rotationMatrixToEulerAngles(self.g_Transform.T)\n\t\t\telse:\n\t\t\t\tself.angleList[self.index] = (self.angleList[self.index] + self.angInc) % 360\n\n\t\t\tif self.rotationDirection == \"ZYX\":\n\t\t\t\tm = numpy.asarray(matrix.getRotationMatrix(self.angInc, self.index))\n\t\t\t\ttheta, self.ex, self.ey, self.ez = matrixToEulerAxisAngle(m)\n\t\t\t\t# rotation about index 0 (x) is intrinsic.\n\t\t\t\t# rotations about indexes 1 (y) and 2 (z) are extrinsic, so it seems...\n\t\t\t\tif self.index > 0:\n\t\t\t\t\t# use just the camera transformation\n\t\t\t\t\tself.drawEulerAxis(5,3, True) \n\t\t\t\t\t#theta, self.ex, self.ey, self.ez = matrixToEulerAxisAngle(matrix.rotateXYZ(self.angleList))\n\t\t\t\tself.indexChanged = False\n\n\t\t\t\tself.modelView = matrix.rotateXYZ(self.angleList)\n\t\t\t\tglMultMatrixf(self.modelView)\n\t\t\telse:\n\t\t\t\tm = numpy.asarray(matrix.getRotationMatrix(self.angInc, self.index))\n\t\t\t\tif self.modelView is None:\n\t\t\t\t\tself.modelView = self.g_Transform.T\n\n\t\t\t\ttheta, self.ex, self.ey, self.ez = matrixToEulerAxisAngle(m)\n\t\t\t\tif self.rotationDirection == \"Extrinsic\":\n\t\t\t\t\t# use just the camera transformation\n\t\t\t\t\tself.drawEulerAxis(5,3,True) \n\t\t\t\t\t# extrinsic rotation (external or global axes)\n\t\t\t\t\tself.modelView = matrix.dot(self.modelView,m.T)\n\t\t\t\t\tglMultMatrixf(self.modelView)\n\t\t\t\telse:\n\t\t\t\t\t# intrinsic rotation (internal or local axes)\n\t\t\t\t\tself.modelView = matrix.dot(self.modelView,m)\n\t\t\t\t\tglMultMatrixf(self.modelView.T)\n\n\t\t\tself.rotating = True\n\t\telse:\n\t\t\t# draw the arcball rotation axis\n\t\t\tself.drawEulerAxis(5, 3)\n\t\t\tif self.rotating:\n\t\t\t\tif self.modelView is not None:\n\t\t\t\t\tif self.rotationDirection == \"Intrinsic\":\n\t\t\t\t\t\tself.g_ThisRot = self.matrix4To3(self.modelView.T)\n\t\t\t\t\t\tself.g_Transform = self.modelView.T\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.g_ThisRot = self.matrix4To3(self.modelView)\n\t\t\t\t\t\tself.g_Transform = self.modelView\n\t\t\t\t\tglMultMatrixf(self.g_Transform)\t\n\t\t\t\tself.rotating = False\n\t\t\telse:\n\t\t\t\tglMatrixMode (GL_MODELVIEW)\n\t\t\t\tglMultMatrixf(self.g_Transform)\n\n\t\tif not self.arcBall:\n\t\t\t# use all three transformations\n\t\t\tself.drawEulerAxis(5,3)\n\t\tself.setupTexture()\n\t\tself.drawCube()\n\t\tself.drawCoordAxes(1.5, 3.0)\n\n\n\t## Refresh the context.\n\t# Function must be called in a timed callback manner.\n\tdef refresh( self ):\n\t\t\"\"\"Request refresh of the context\"\"\"\n\t\tself.updateGL()\n\n\t## This method encapsulates the functions required to set up for textured rendering. \n\t# The original tutorial made these calls once for the entire program. \n\t# This organization makes more sense if you are likely to have multiple textures.\n\tdef setupTexture( self ):\n\t\t\"\"\"Render-time texture environment setup\"\"\"\n\n\t\t# Configure the texture rendering parameters\n\t\tglEnable(GL_TEXTURE_2D)\n\n\t\tglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)\n\t\tglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)\n\n\t\tglTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL)\n\t\t# Re-select our texture, could use other generated textures if we had generated them earlier...\n\t\tglBindTexture(GL_TEXTURE_2D, self.imageID)\n\n\t## Draw axis \"x\" in red, \"y\" in green and \"z\" in blue.\n\t#\n\t# @param len length of each axis.\n\t# @param wid line width for drawing.\n\t#\n\tdef drawCoordAxes(self, len = 2.0, wid = 1.0):\n\t\t\"\"\"Draw the three coordinate axes.\"\"\"\n\n\t\tlw = glGetFloatv(GL_LINE_WIDTH)\n\t\tglLineWidth(wid)\n\t\tglBegin(GL_LINES)\n\n\t\t# red\n\t\tglColor3f(1.0,0.0,0.0) \n\t\tglVertex3f(0, 0, 0)\n\t\tglVertex3f(len, 0, 0)\n\n\t\t# green\n\t\tglColor3f(0.0,1.0,0.0)\n\t\tglVertex3f(0, 0, 0)\n\t\tglVertex3f(0, len, 0)\n\n\t\t# blue\n\t\tglColor3f(0.0,0.0,1.0) \n\t\tglVertex3f(0, 0, 0)\n\t\tglVertex3f(0, 0, len)\n\t \n\t\tglEnd()\n\t\tglLineWidth(lw)\n\n\t## Draw the Euler axis of rotation in white.\n\t# It uses the instance vector self.ex(ey)(ez).\n\t#\n\t# @param scale scale factor applied to the vector.\n\t# @param wid line width.\n\t# @param reset whether to set the instance vector to None.\n\t#\n\tdef drawEulerAxis(self, scale=3, wid = 1, reset = False):\n\t\t\"\"\"\"Draw the Euler axis of rotation.\"\"\"\n\n\t\tif self.isEulerAxisDefined():\n\t\t\tself.drawAxis(self.ex, self.ey, self.ez, scale, wid)\n\n\t\tif reset:\n\t\t\tself.ex = self.ey = self.ez = None\n\n\t## Draw an axis (a line) in white, given its direction and passing through the origin.\n\t# The axis is drawn from (-x,-y,-z)*scale to (x,y,z)*scale.\n\t#\n\t# @param x vector coordinate x.\n\t# @param y vector coordinate y.\n\t# @param z vector coordinate z.\n\t# @param scale scale factor applied to the vector.\n\t# @param wid line width.\n\t#\n\tdef drawAxis(self,x,y,z,scale=3, wid = 1):\t\n\t\t\"\"\"\"Draw an axis of rotation.\"\"\"\n\n\t\tlw = glGetFloatv(GL_LINE_WIDTH)\n\t\tglLineWidth(wid)\n\t\tx *= scale\n\t\ty *= scale\n\t\tz *= scale\n\t\tglBegin(GL_LINES)\n\t\t# white\n\t\tglColor3f(1.0,1.0,1.0) \n\t\tglVertex3f(-x,-y,-z)\n\t\tglVertex3f(x,y,z)\n\t\tglEnd()\n\t\tglLineWidth(lw)\n\n\t## Drawing the cube has changed slightly, because we now need to specify the texture \n\t# coordinates for each vertex. This is all just taken from the original tutorial.\n\tdef drawCube( self ):\n\t\t\"\"\"Draw a cube with texture coordinates\"\"\"\n\n\t\tglBegin(GL_QUADS)\n\t\tglColor3f(1.0,0.0,0.0)\n\t\tglTexCoord2f(0.0, 0.0); glVertex3f(-1.0, -1.0, 1.0);\n\t\tglTexCoord2f(1.0, 0.0); glVertex3f( 1.0, -1.0, 1.0);\n\t\tglTexCoord2f(1.0, 1.0); glVertex3f( 1.0, 1.0, 1.0);\n\t\tglTexCoord2f(0.0, 1.0); glVertex3f(-1.0, 1.0, 1.0);\n\t\tglColor3f(0.0,1.0,0.0)\n\t\tglTexCoord2f(1.0, 0.0); glVertex3f(-1.0, -1.0, -1.0);\n\t\tglTexCoord2f(1.0, 1.0); glVertex3f(-1.0, 1.0, -1.0);\n\t\tglTexCoord2f(0.0, 1.0); glVertex3f( 1.0, 1.0, -1.0);\n\t\tglTexCoord2f(0.0, 0.0); glVertex3f( 1.0, -1.0, -1.0);\n\t\tglColor3f(0.0,0.0,1.0)\n\t\tglTexCoord2f(0.0, 1.0); glVertex3f(-1.0, 1.0, -1.0);\n\t\tglTexCoord2f(0.0, 0.0); glVertex3f(-1.0, 1.0, 1.0);\n\t\tglTexCoord2f(1.0, 0.0); glVertex3f( 1.0, 1.0, 1.0);\n\t\tglTexCoord2f(1.0, 1.0); glVertex3f( 1.0, 1.0, -1.0);\n\t\tglColor3f(1.0,1.0,0.0)\n\t\tglTexCoord2f(1.0, 1.0); glVertex3f(-1.0, -1.0, -1.0);\n\t\tglTexCoord2f(0.0, 1.0); glVertex3f( 1.0, -1.0, -1.0);\n\t\tglTexCoord2f(0.0, 0.0); glVertex3f( 1.0, -1.0, 1.0);\n\t\tglTexCoord2f(1.0, 0.0); glVertex3f(-1.0, -1.0, 1.0);\n\t\tglColor3f(0.0,1.0,1.0)\n\t\tglTexCoord2f(1.0, 0.0); glVertex3f( 1.0, -1.0, -1.0);\n\t\tglTexCoord2f(1.0, 1.0); glVertex3f( 1.0, 1.0, -1.0);\n\t\tglTexCoord2f(0.0, 1.0); glVertex3f( 1.0, 1.0, 1.0);\n\t\tglTexCoord2f(0.0, 0.0); glVertex3f( 1.0, -1.0, 1.0);\n\t\tglColor3f(1.0,0.0,1.0)\n\t\tglTexCoord2f(0.0, 0.0); glVertex3f(-1.0, -1.0, -1.0);\n\t\tglTexCoord2f(1.0, 0.0); glVertex3f(-1.0, -1.0, 1.0);\n\t\tglTexCoord2f(1.0, 1.0); glVertex3f(-1.0, 1.0, 1.0);\n\t\tglTexCoord2f(0.0, 1.0); glVertex3f(-1.0, 1.0, -1.0);\n\t\tglEnd()\n\n\t\tglDisable(GL_TEXTURE_2D)\n\t\t#glutSwapBuffers()\n\n\t## This virtual function is called once before the first call to paintGL() or resizeGL().\n\t# This function should set up any required OpenGL resources and state. \n\tdef initializeGL(self):\n\n\t\tglutInit(sys.argv)\n\n\t\t# Select type of Display mode: \n\t\t# Double buffer \n\t\t# RGBA color\n\t\t# Alpha components supported \n\t\t# Depth buffer\n\t\tglutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_ALPHA | GLUT_DEPTH)\n\n\t\t# This Will Clear The Background Color To Black\n\t\tglClearColor(0.0, 0.0, 0.0, 1.0)\n\t\t# Enables Clearing Of The Depth Buffer\n\t\tglClearDepth(1.0)\n\t\t# The Type Of Depth Test To Do\n\t\tglDepthFunc(GL_LEQUAL)\n\t\t# Enables Depth Testing\n\t\tglEnable(GL_DEPTH_TEST)\n\t\t# Select Flat Shading (Nice Definition Of Objects)\n\t\tglShadeModel (GL_SMOOTH)\n\t\t# Really Nice Perspective Calculations\n\t\tglHint (GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST)\n\n\t\t# mcolor will be applied to both ambient and diffuse components of the material.\n\t\t# This is done for convenience because in most cases Ambient and Diffuse properties\n\t\t# of a material should be set to the same color.\n\t\tmcolor = [ 1.0, 0.0, 0.0, 1.0 ]\n\t\tglMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, mcolor)\n\n\t\t# enable color tracking (specify material properties by merely calling the glColor)\n\t\tglEnable (GL_COLOR_MATERIAL)\n\t\t# set material properties which will be assigned by glColor\n\t\tglColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE)\n\t\tglFrontFace(GL_CCW)\n\n\t\tself.imageID = self.loadImage ()\n\n\t## Returns the cursor coordinates in widget coordinates\n\tdef convCursorToWidgetCoord (self):\n\t\tcursor = QtGui.QCursor()\n\t\tcursor_x = cursor.pos().x()\n\t\tcursor_y = cursor.pos().y()\n\n\t\tpt = QtCore.QPoint(cursor_x, cursor_y)\n\t\treturn self.mapFromGlobal(pt)\n\n\t## Called when a mouse button is clicked. \n\t# This function is currently used to pass a start and end coordinate to Arcball. \n\tdef mousePressEvent(self, event):\n\t\n\t\tif (self.arcBall):\n\t\t\twidgetHeight = self.geometry().height()\n\t\t\t# Set Last Static Rotation To Last Dynamic One\n\t\t\tself.g_LastRot = copy.copy (self.g_ThisRot)\n\t\t\t# Prepare For Dragging\n\t\t\tself.g_isDragging = True\n\n\t\t\tconvPt = self.convCursorToWidgetCoord()\n\t\t\t# if putting the camera in the negative z axis: mouse_pt = Point2fT (convPt.x(), widgetHeight - convPt.y())\n\t\t\tmouse_pt = Point2fT (convPt.x(), convPt.y())\n\t\t\t# Update Start Vector And Prepare For Dragging\n\t\t\tself.g_ArcBall.click (mouse_pt)\n\n\t## Reports the position of the mouse cursor, relative to this widget.\n\tdef mouseMoveEvent(self, event):\n\t\t\"\"\" Mouse cursor is moving\n\t\t\t Glut calls this function (when mouse button is down)\n\t\t\t and passes the mouse cursor postion in window coords as the mouse moves.\n\t\t\"\"\"\n\n\t\tif (self.g_isDragging and self.arcBall):\n\t\t\twidgetHeight = self.geometry().height()\n\t\t\tconvPt = self.convCursorToWidgetCoord()\n\n\t\t\t# if putting the camera in the negative z axis: mouse_pt = Point2fT (convPt.x(), widgetHeight - convPt.y())\n\t\t\tmouse_pt = Point2fT (convPt.x(), convPt.y())\n\t\t\t# Update End Vector And Get Rotation As Quaternion\n\t\t\tThisQuat = self.g_ArcBall.drag (mouse_pt)\n\t\t\ttheta, self.ex, self.ey, self.ez = quatToEulerAxisAngle(ThisQuat)\n\t\t\t# Convert Quaternion Into Matrix3fT\n\t\t\tself.g_ThisRot = Matrix3fSetRotationFromQuat4f (ThisQuat)\n\t\t\t# Use correct Linear Algebra matrix multiplication C = A * B\n\t\t\t# Accumulate Last Rotation Into This One\n\t\t\tself.g_ThisRot = Matrix3fMulMatrix3f (self.g_LastRot, self.g_ThisRot)\n\t\t\t# Set Our Final Transform's Rotation From This One\n\t\t\tself.g_Transform = Matrix4fSetRotationFromMatrix3f (self.g_Transform, self.g_ThisRot)\n\n\t\treturn\n\n\t## Restructure the aspect ratio when resizing the window\n\tdef resizeGL(self, width, height):\n\t\tif height == 0: height = 1\n\n\t\tself.g_ArcBall.setBounds(width, height)\n\n\t\tglViewport(0, 0, width, height)\n\n\t\tself.setCamera()\n\n\t## This function is called whenever the widget needs to be painted.\n\t# Before invoking this function, the context and the framebuffer are bound, \n\t# and the viewport is set up by a call to glViewport().\n\tdef paintGL(self):\n\t\tself.Render()\n\nclass MainWindow(QtGui.QMainWindow):\n\n\tdef __init__(self):\n\t\tQtGui.QMainWindow.__init__(self)\n\n\t\tself.resize(WIDTH, HEIGHT)\n\t\tself.setWindowTitle('Texture Mapping to Cube')\n\n\t\tglWidget = GLWidget(self)\n\t\tself.glWidget = glWidget\n\n\t\t# QT requires a timed refresh when performing animations\n\t\ttimer = QtCore.QTimer(self)\n\t\ttimer.setInterval(20)\n\t\tQtCore.QObject.connect(timer, QtCore.SIGNAL('timeout()'), glWidget.refresh)\n\t\ttimer.start()\n\t\t\n\t\tself.controlScheme = \"rotation around x-axis ( %s )\" % self.glWidget.rotationDirection\n\t\tself.initLayout(glWidget)\n\n\t## Initializes the layout of the UI.\n\tdef initLayout(self, glWidget):\n\t\tself.createMenus()\n\t\tself.createDockWindows()\n\t\tself.widget = glWidget\n\n\t\tmain_layout = QtGui.QVBoxLayout()\n\t\tmain_layout.addStretch()\n\n\t\tcentral_widget = glWidget\n\t\tcentral_widget.setLayout(main_layout)\n\t\tself.setCentralWidget(central_widget)\t\n\n\t## Create the tool bar menu.\n\tdef createMenus(self):\n\n\t\tmenubar = self.menuBar()\n\n\t\texitAction = QtGui.QAction(QtGui.QIcon('exit.png'), '&Exit', self) \n\t\texitAction.setShortcut('Q')\n\t\texitAction.setStatusTip('Exit application')\n\t\texitAction.triggered.connect(QtGui.qApp.quit)\n\n\t\topenFileAction = QtGui.QAction(QtGui.QIcon('exit.png'), '&Open File', self) \n\t\topenFileAction.setShortcut('Ctrl+O')\n\t\topenFileAction.setStatusTip('Open file')\n\t\topenFileAction.triggered.connect(self.openFileDialog)\n\n\t\tfileMenu = menubar.addMenu('&File')\n\t\tfileMenu.addAction(openFileAction)\n\t\tfileMenu.addAction(exitAction)\n\n\t\tself.viewMenu = self.menuBar().addMenu(\"&View\")\t\t\n\n\t## Create dockable windows for the controller.\n\tdef createDockWindows(self):\n\t\tdock = QtGui.QDockWidget(\"Options\", self)\n\t\t# Set allowable areas for where the window can be docked. \n\t\tdock.setAllowedAreas(QtCore.Qt.BottomDockWidgetArea | QtCore.Qt.TopDockWidgetArea | QtCore.Qt.LeftDockWidgetArea | QtCore.Qt.RightDockWidgetArea)\n\t\tself.controls = QtGui.QWidget(dock)\n\n\t\tself.buttonX = QtGui.QPushButton('x-axis', self)\n\t\tself.buttonY = QtGui.QPushButton('y-axis', self)\n\t\tself.buttonZ = QtGui.QPushButton('z-axis', self)\n\t\tself.buttonArc = QtGui.QPushButton('arcball', self)\n\n\t\tself.buttonX.clicked.connect(self.setRotX)\n\t\tself.buttonY.clicked.connect(self.setRotY)\n\t\tself.buttonZ.clicked.connect(self.setRotZ)\n\t\tself.buttonArc.clicked.connect(self.setArcball)\n\n\t\tbutton_layout = QtGui.QHBoxLayout()\n\t\tbutton_layout.addWidget(self.buttonX)\n\t\tbutton_layout.addWidget(self.buttonY)\n\t\tbutton_layout.addWidget(self.buttonZ)\n\t\tbutton_layout.addWidget(self.buttonArc)\n\n\t\tself.controls.setLayout(button_layout)\n\n\t\tdock.setWidget(self.controls)\n\t\tself.addDockWidget(QtCore.Qt.BottomDockWidgetArea, dock)\n\t\tself.viewMenu.addAction(dock.toggleViewAction())\n\n\t\tdock = QtGui.QDockWidget(\"Current Action\", self)\n\t\tself.info = QtGui.QWidget(dock)\n\n\t\t# -------------- Buttons ----------------------- #\n\t\tcontrol_layout = QtGui.QGridLayout()\n\t\tself.buttonInt = QtGui.QPushButton('Intrinsic', self)\n\t\tself.buttonExt = QtGui.QPushButton('Extrinsic', self)\n\t\tself.buttonNone = QtGui.QPushButton('ZYX', self)\n\n\t\tself.buttonInt.clicked.connect(self.setIntrinsic)\n\t\tself.buttonExt.clicked.connect(self.setExtrinsic)\n\t\tself.buttonNone.clicked.connect(self.setNone)\n\n\t\tcontrol_layout.addWidget(self.buttonInt, 1, 0)\n\t\tcontrol_layout.addWidget(self.buttonExt, 2, 0)\n\t\tcontrol_layout.addWidget(self.buttonNone, 3, 0)\n\n\t\tself.lInfo = QtGui.QLabel()\n\t\tself.lInfo.setText(\"Current control scheme: \\n\\n\" + self.controlScheme)\t\n\t\tself.lInfo.setAlignment(QtCore.Qt.AlignCenter)\n\n\t\tfont = QtGui.QFont()\n\t\tfont.setBold(True)\n\t\tself.lInfo.setFont(font)\n\t\tcontrol_layout.addWidget(self.lInfo)\n\n\t\tself.info.setLayout(control_layout)\n\t\t# ------------------------------------------------ #\n\n\t\tdock.setWidget(self.info)\n\t\tself.addDockWidget(QtCore.Qt.RightDockWidgetArea, dock)\n\t\tself.viewMenu.addAction(dock.toggleViewAction())\n\n\t## Open an image file to modify the texture.\n\tdef openFileDialog(self):\n\t\tfilter = \"Image Files (*.png *.jpg *.bmp)\"\n\t\tfileName = QtGui.QFileDialog.getOpenFileNameAndFilter(self, \"Open File\", \"~/Programming/Python/PyQt/TextureMap/images/\", filter)\n\n\t\tself.widget.imgName = str(fileName[0])\n\n\t\tif (self.widget.imgName is not None and len(self.widget.imgName) > 0): \n\t\t\t# reload image\n\t\t\tself.widget.imageID = self.widget.loadImage ()\n\t\n\tdef setIntrinsic(self):\n\t\tself.glWidget.setRotationDirection (0)\n\t\taxis = (\"x-axis\", \"y-axis\", \"z-axis\")\n\t\tself.controlScheme = \"rotation around %s ( %s )\" % (axis[self.widget.index], self.glWidget.rotationDirection)\n\n\tdef setExtrinsic(self):\n\t\tself.glWidget.setRotationDirection (1)\n\t\taxis = (\"x-axis\", \"y-axis\", \"z-axis\")\n\t\tself.controlScheme = \"rotation around %s ( %s )\" % (axis[self.widget.index], self.glWidget.rotationDirection)\n\n\tdef setNone(self):\n\t\tself.glWidget.setRotationDirection (2)\n\t\taxis = (\"x-axis\", \"y-axis\", \"z-axis\")\n\t\tself.controlScheme = \"rotation around %s ( %s )\" % (axis[self.widget.index], self.glWidget.rotationDirection)\n\n\t## Clears previous rotations. \n\t# Call this function before selecting a new axis for rotation.\n\tdef resetArcball(self):\n\t\tself.widget.arcBall = False\n\n\t## Set the cube to rotate around its x-axis.\n\tdef setRotX(self):\n\t\t\"\"\" Set the cube to rotate around its x-axis. \"\"\"\n\t\tself.resetArcball()\n\t\tself.widget.setIndex(0)\n\t\tself.controlScheme = \"rotation around x-axis ( %s )\" % self.glWidget.rotationDirection\n\n\t## Set the cube to rotate around its y-axis.\n\tdef setRotY(self):\n\t\t\"\"\" Set the cube to rotate around its y-axis. \"\"\"\n\t\tself.resetArcball()\n\t\tself.widget.setIndex(1)\n\t\tself.controlScheme = \"rotation around y-axis ( %s )\" % self.glWidget.rotationDirection\n\n\t## Set the cube to rotate around its z-axis.\n\tdef setRotZ(self):\n\t\t\"\"\" Set the cube to rotate around its z-axis. \"\"\"\n\t\tself.resetArcball()\n\t\tself.widget.setIndex(2)\n\t\tself.controlScheme = \"rotation around z-axis ( %s )\" % self.glWidget.rotationDirection\n\n\tdef setArcball(self):\n\t\tself.widget.arcBall = True\n\t\tself.controlScheme = \"arcball\"\n\ndef main():\n\t\"\"\"Instantiate the QT objects.\"\"\"\n\n\tapp = QtGui.QApplication(sys.argv)\t\n\twin = MainWindow()\n\twin.show()\n\ttimer = QtCore.QTimer()\n\ttimer.timeout.connect(updateLabel)\n\ttimer.start(500) \n\n\treturn app, win, timer\n\ndef updateLabel():\n\t\"\"\"Update the information label.\"\"\"\n\twin.lInfo.setText(\"Current control scheme: \\n\\n\" + win.controlScheme)\t\n\nif __name__ == \"__main__\":\n\tapp, win, timer = main()\n\tsys.exit(app.exec_())\n","sub_path":"TextureMapInterface.py","file_name":"TextureMapInterface.py","file_ext":"py","file_size_in_byte":24743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"43409668","text":"import simplegui\n\n# define global variables\ncounter = 0\nstop_count = 0\nright_count = 0\na = 0\n\n\n# define helper function format that converts time\n# in tenths of seconds into formatted string A:BC.D\ndef format(t):\n global a\n a = str(t)[-1:]\n if len(str(t)) == 1:\n b = 0\n c = 0 \n d = 0\n elif len(str(t)) == 2: \n b = str(t)[0]\n c = 0 \n d = 0\n elif len(str(t)) == 3:\n if int(str(t)[0:2]) / 60 == 0:\n b = int(str(t)[0:2]) % 60\n c = \"\"\n d = 0\n else:\n d = 1\n if len(str(int(str(t)[0:2]) % 60)) == 1:\n c = 0\n else: \n c = \"\"\n b = int(str(t)[0:2]) % 60\n elif len(str(t)) == 4:\n b = int(str(t)[0:3]) % 60\n if len(str(int(str(t)[0:3]) % 60)) == 1:\n c = 0\n else: \n c = \"\"\n d = int(str(t)[0:3]) / 60\n return str(d) + \":\" + str(c) + str(b) + \".\" + str(a)\n\n \n# define event handlers for buttons; \"Start\", \"Stop\", \"Reset\"\ndef start():\n global counter\n counter = counter + 1\n timer.start()\n \ndef stop():\n global counter, stop_count, right_count, a\n counter = counter\n if timer.is_running():\n stop_count = stop_count + 1\n if (counter % 10) == 0:\n right_count = right_count + 1\n timer.stop()\n \ndef reset():\n global counter, stop_count, right_count\n timer.stop()\n counter = 0 \n stop_count = 0\n right_count = 0\n \n\n\n# define event handler for timer with 0.1 sec interval\ndef timer_handler():\n global counter\n counter = counter + 1\n\ntimer = simplegui.create_timer(100, timer_handler)\n\n# define draw handler\ndef draw(canvas):\n canvas.draw_text(format(str(counter)), [75, 100], 24, \"White\")\n canvas.draw_text(str(right_count) + \"/\" + str(stop_count), [150, 40], 24, \"White\")\n \n# create frame\nf = simplegui.create_frame(\"Stopwatch\", 200, 200)\n\n# register event handlers\nf.add_button(\"Start\", start, 100)\nf.add_button(\"Stop\", stop, 100)\nf.add_button(\"Reset\", reset, 100)\nf.set_draw_handler(draw)\n\n# start frame\nf.start()\n\n\n\n# Please remember to review the grading rubric","sub_path":"stopwatch.py","file_name":"stopwatch.py","file_ext":"py","file_size_in_byte":2168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"383497603","text":"from django.urls import path, re_path, include\nfrom freeboard import views\n\napp_name = 'freeboard'\nurlpatterns = [\n re_path(r'^$', views.freeboard_list, name='freeboard_list'),\n re_path(r'^(?P\\d+)/$', views.freeboard_detail, name='freeboard_detail'),\n re_path(r'^new/$', views.freeboard_new, name='freeboard_new'),\n re_path(r'^(?P\\d+)/edit/$', views.freeboard_edit, name='freeboard_edit'),\n re_path(r'^(?P\\d+)/delete/$', views.freeboard_delete, name='freeboard_delete'),\n re_path(r'^comment/new/$', views.comment_new, name='comment_new'),\n re_path(r'^(?P\\d+)/comment/(?P\\d+)/delete/$', views.comment_delete, name='comment_delete'),\n re_path(r'^permission/$', views.fboard_permission, name='fboard_permission'),\n]\n","sub_path":"freeboard/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"526956824","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow.compat.v1 as tf\n\nfrom modules import InvertibleBlock\n\n\nclass IResNet:\n def __init__(self,\n in_shape,\n block_list,\n stride_list,\n channel_list,\n num_trace_samples,\n num_series_terms,\n coeff,\n power_iter):\n\n assert len(block_list) == len(stride_list) == len(channel_list)\n self.coeff = coeff\n self.power_iter = power_iter\n self.num_trace_samples = num_trace_samples\n self.num_series_terms = num_series_terms\n\n self.blocks = []\n for idx, (num_block, stride, num_channel) in \\\n enumerate(zip((block_list, stride_list, channel_list))):\n with tf.variable_scope('stack%d' % (idx + 1)):\n self.create_stack(num_block, stride, num_channel, in_shape)\n\n def __call__(self, x):\n\n for block in self.blocks:\n x = block(x)\n\n return x\n\n def create_stack(self,\n num_block,\n stride,\n num_channel,\n in_shape):\n\n for idx in range(num_block):\n with tf.variable_scope('block%d' % (idx + 1)):\n self.blocks.append(InvertibleBlock(in_shape,\n stride,\n num_channel,\n self.coeff,\n self.power_iter,\n self.num_trace_samples,\n self.num_series_terms))\n\n def inverse(self, out):\n x = out\n\n for block in reversed(self.blocks):\n x = block.inverse(x)\n return x\n","sub_path":"model/invertible_resnet.py","file_name":"invertible_resnet.py","file_ext":"py","file_size_in_byte":1772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"263447242","text":"def constant_space(text, n, less = operator.__lt__):\n def equal(a, b):\n return not less(a, b) and not less(b, a)\n out, p, i = 1, 1, 2\n while i <= n:\n r = (i - out) % p\n if equal(text[i], text[out + r]):\n i = i + 1\n elif less(text[i], text[out + r]):\n i, p = i + 1, i + 1 - out\n else:\n out, i, p = i - r, i - r + 1, 1\n return out, p\n","sub_path":"text/code/maximum-suffix/constant-space.py","file_name":"constant-space.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"411723470","text":"import sys\nsys.path.insert(0, './data/')\nsys.path.insert(0, './layers/')\nsys.path.insert(0, './utils/')\n\nimport math\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom sklearn.model_selection import ShuffleSplit\nfrom torch import Tensor\n\nfrom data import CelebA\nfrom layers import (BasicConvLayer, BasicDeconvLayer, BasicDenseLayer,\n get_padding)\nfrom torchsummary import summary\nfrom utils import (get_flat_dim, get_convblock_dim, get_deconvblock_padding)\nfrom cvae import CVAE\nfrom cnn import CNN\n\n\nclass TWINS(nn.Module):\n def __init__(self,\n input_shape=(3, 64, 64),\n n_labels=10,\n n_ids=10,\n base_filters=[64, 64, 128, 256, 512],\n kernel_size=[3, 3, 3, 3, 3],\n stride=[2, 2, 2, 2, 2],\n learning_rate=1e-03,\n l2_reg=0,\n activation='leaky_relu',\n zdims=128,\n bnorm=True,\n batch_size=32,\n KLD_weight=5e-04,\n DeconvIsConv=True,\n checkpoint_fn='./checkpoints/'): # 5e-04\n\n super(TWINS, self).__init__()\n\n self.input_shape = input_shape\n self.n_labels = n_labels\n self.n_ids = n_ids\n self.base_filters = base_filters\n self.kernel_size = kernel_size\n self.stride = stride\n self.l2_reg = l2_reg\n self.activation = activation\n self.zdims = zdims\n self.bnorm = bnorm\n self.batch_size = batch_size\n self.KLD_weight = KLD_weight\n self.learning_rate = learning_rate\n self.DeconvIsConv = DeconvIsConv\n\n # Initialize main CVAE\n self.cvae = CVAE(input_shape=self.input_shape,\n n_labels=self.n_labels,\n n_ids=self.n_ids,\n base_filters=self.base_filters,\n kernel_size=self.kernel_size,\n stride=self.stride,\n learning_rate=self.learning_rate,\n l2_reg=self.l2_reg,\n activation=self.activation,\n zdims=self.zdims,\n bnorm=self.bnorm,\n batch_size=self.batch_size,\n KLD_weight=self.KLD_weight,\n DeconvIsConv=self.DeconvIsConv)\n\n # Initialize CNN\n self.cnn = CNN(input_shape=self.input_shape,\n isTWINS=True)\n\n def forward(self, x, y, y_1D, g_decoder_1D, y_2D, g_2D,\n x2, g2_2D):\n\n # cvae\n x_reconst, z_mean, z_log_var, z = self.cvae(x, y_1D, g_decoder_1D,\n y_2D, g_2D)\n\n # shared cvae encoder\n z_mean2, z_log_var2 = self.cvae.encoder(x2, y_2D, g2_2D)\n\n # cnn\n h1, y_pred = self.cnn(x)\n\n return (x_reconst, z_mean, z_log_var, z,\n z_mean2, z_log_var2,\n h1, y_pred)\n\n def fit(self):\n pass\n\n def new_samples(self):\n pass\n\n def encode_decode(self):\n pass\n\n\nif __name__ == '__main__':\n device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n input_shape = (3, 64, 64)\n # input_shape = (1024,)\n model = CNN(input_shape=input_shape).to(device)\n\n print(model)\n summary(model, input_shape)\n # print(model.flattenDims)\n","sub_path":"signer-independent-pytorch/bck-24-01-19/models/twins.py","file_name":"twins.py","file_ext":"py","file_size_in_byte":3443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"210200712","text":"import time\nimport sys\nfrom copy import copy, deepcopy\nstart_secs = time.time()\nprint('')\n\ndef countSand(a):\n global min_x, min_y, max_x, max_y\n count = 0\n start_y = 0\n end_y = max_y + 3\n start_x = min_x - 3\n end_x = max_x + 3\n\n for y in range(start_y, end_y):\n for x in range(start_x, end_x):\n if a[y][x] == 'O':\n count += 1\n return count\n\ndef printCave(a):\n global min_x, min_y, max_x, max_y, found_void\n s = ''\n start_y = min_y - 4\n end_y = max_y + 3\n start_x = min_x - 3\n end_x = max_x + 3\n\n for y in range(start_y, end_y):\n for x in range(start_x, end_x):\n s += a[y][x]\n s += '\\n'\n print(s)\n\ndef dropSand(a):\n global sand_x, sand_y, min_x, min_y, max_x, max_y, found_void\n x = sand_x\n y = sand_y\n while True:\n\n if a[y][x] == 'O':\n if y > max_y or x < min_x or x > max_x:\n # endless void\n a[y][x] = '.'\n found_void = True\n return\n\n if a[y+1][x] != '.' and a[y+1][x-1] != '.' and a[y+1][x+1] != '.':\n return\n \n if a[y+1][x] != '.' and a[y+1][x-1] == '.':\n # move diagonally down left\n a[y][x] = '.'\n a[y+1][x-1] = 'O'\n y = y+1\n x = x-1\n elif a[y+1][x] != '.' and a[y+1][x+1] == '.':\n # move diagonally down right\n a[y][x] = '.'\n a[y+1][x+1] = 'O'\n y = y+1\n x = x+1 \n elif a[y+1][x] == '.':\n # move down\n a[y][x] = '.'\n a[y+1][x] = 'O'\n y = y+1\n\n #printCave(a)\n\n\n\n# MAIN\n\n# read in input file\nl=[]\nmy_file = open(\"inp.txt\", \"r\", encoding='utf-8')\nlines = my_file.readlines()\nfor line in lines:\n l.append(line.strip())\n\nfound_void = False\nsand_x = 500\nsand_y = 0\nmax_x = -1\nmax_y = -1\nmin_x = sys.maxsize\nmin_y = sys.maxsize\nfor s in l:\n arr = s.split(' -> ')\n for p in arr:\n arr2 = p.split(',')\n x = int(arr2[0])\n y = int(arr2[1])\n if x < min_x:\n min_x = x\n if y < min_y:\n min_y = y\n if x > max_x:\n max_x = x\n if y > max_y:\n max_y = y\n\ncols = max_x + 5\nrows = max_y + 5\ncave = [ ['.' for x in range(cols)] for y in range(rows) ]\ncave[sand_y][sand_x] = '+'\n\nfor s in l:\n arr = s.split(' -> ')\n for i in range(len(arr)-1):\n arr0 = arr[i].split(',')\n x0 = int(arr0[0])\n y0 = int(arr0[1])\n arr0 = arr[i+1].split(',')\n x1 = int(arr0[0])\n y1 = int(arr0[1])\n\n if (y0 == y1):\n # across\n start = x1\n end = x0\n if x0 < x1:\n start = x0\n end = x1\n for x in range(start, end+1):\n cave[y0][x] = '#'\n\n if (x0 == x1):\n # down\n start = y1\n end = y0\n if y0 < y1:\n start = y0\n end = y1\n for y in range(start, end+1):\n cave[y][x0] = '#'\n\n\n#printCave(cave)\n\nwhile not found_void:\n dropSand(cave)\n\nprintCave(cave)\n\nprint( countSand(cave) )\n# 699 WRONG TOO LOW\n\nprint('')\nend_secs = time.time()\nprint('--- ' + str(end_secs-start_secs) + ' secs ---')","sub_path":"2022/day14/part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":2870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"364164532","text":"import numpy as np\nimport unittest\nimport hmc.unconstrained as uhmc\n\nautograd_available = True\ntry:\n import autograd.numpy as ag_np\nexcept ImportError:\n autograd_available = False\n\n\nclass TestIsotropicHMCSampler(unittest.TestCase):\n\n def setUp(self):\n self.prng = np.random.RandomState(1234)\n\n def test_init_with_energy_grad(self):\n energy_func = lambda pos, cache={}: 0.5 * pos.dot(pos)\n energy_grad = lambda pos, cache={}: pos\n mom_resample_coeff = 1.\n dtype = np.float64\n sampler = uhmc.IsotropicHmcSampler(\n energy_func=energy_func,\n energy_grad=energy_grad,\n prng=self.prng,\n mom_resample_coeff=mom_resample_coeff,\n dtype=dtype)\n assert sampler.energy_func == energy_func\n assert sampler.energy_grad == energy_grad\n assert sampler.prng == self.prng\n assert sampler.mom_resample_coeff == mom_resample_coeff\n assert sampler.dtype == dtype\n\n def test_init_without_energy_grad(self):\n if autograd_available:\n energy_func = lambda pos, cache={}: 0.5 * ag_np.dot(pos, pos)\n sampler = uhmc.IsotropicHmcSampler(\n energy_func=energy_func, prng=self.prng)\n assert sampler.energy_grad is not None, (\n 'Sampler energy_grad not being automatically defined using '\n 'Autograd correctly.'\n )\n pos = self.prng.normal(size=5)\n assert np.allclose(sampler.energy_grad(pos), pos), (\n 'Sampler energy_grad inconsistent with energy_func.'\n )\n\n def test_dynamic_reversible(self):\n energy_func = lambda pos, cache={}: 0.5 * pos.dot(pos)\n energy_grad = lambda pos, cache={}: pos\n sampler = uhmc.IsotropicHmcSampler(\n energy_func=energy_func, energy_grad=energy_grad,\n prng=self.prng, dtype=np.float64)\n\n def do_reversible_check(n_dim, dt, n_step):\n pos_0, mom_0 = self.prng.normal(size=(2, n_dim))\n pos_f, mom_f, cache_f = sampler.simulate_dynamic(\n n_step, dt, pos_0, mom_0, {})\n pos_r, mom_r, cache_r = sampler.simulate_dynamic(\n n_step, -dt, pos_f, mom_f, {})\n assert np.allclose(pos_0, pos_r) and np.allclose(mom_0, mom_r), (\n 'Hamiltonian dynamic simulation not time-reversible. ' +\n 'Initial state\\n {0}\\n {1}\\n'.format(pos_0, mom_0) +\n 'Reversed state\\n {0}\\n {1}\\n'.format(pos_r, mom_r)\n )\n do_reversible_check(2, 0.1, 5)\n do_reversible_check(10, 0.1, 100)\n","sub_path":"hmc/tests/test_unconstrained.py","file_name":"test_unconstrained.py","file_ext":"py","file_size_in_byte":2637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"343098995","text":"# Lab 8\n# Computer Science\n# 25 Mar 2016\n# Tanner Bornemann\n\nimport random\n\n\n# __ dunder keeps the data attribute hidden.\nclass Card:\n suit_names = [\"Clubs\", \"Diamonds\", \"Hearts\", \"Spades\"]\n rank_names = [None, \"2\", \"3\", \"4\", \"5\", \"6\", \"7\",\n \"8\", \"9\", \"10\", \"Jack\", \"Queen\", \"King\", \"Ace\"]\n\n # moved Ace to the last spot so it will have the highest value (14) of the card ranks\n\n def __init__(self, suit, rank):\n self.suit = suit\n self.rank = rank\n\n def __str__(self):\n return (Card.rank_names[self.rank] + \" \" +\n Card.suit_names[self.suit])\n\n\nclass DeckOfCard:\n def __init__(self):\n self.cards = []\n for suit in range(4):\n for rank in range(1, 14):\n card = Card(suit, rank)\n self.cards.append(card)\n\n def __str__(self):\n result = \"\\n\"\n for card in self.cards:\n result += str(card) + \"\\n\"\n return result\n\n def __len__(self):\n return len(self.cards)\n\n def shuffle(self):\n random.shuffle(self.cards)\n\n # Task 1\n def dealNextCard(self):\n return self.cards.pop(0) # deltCard # give card to caller\n\n\n# Task 2\nclass Hand:\n def __init__(self):\n self.hand = []\n\n def __str__(self):\n result = \"\\n\"\n for __card in self.hand:\n result += str(__card) + \"\\n\"\n return result\n\n def __len__(self):\n return len(self.hand)\n\n # Task 2\n def add(self, newCard):\n self.hand.append(newCard) # add new card to hand\n\n # this returns the highest card in a hand (and reorganizes everything least to greatest)\n def getHighestCard(self):\n for i2 in range(0, 4): # might as well run this over all the cards so it organizes the hand\n for i in range(0, 4):\n if self.hand[i].rank > self.hand[i + 1].rank: # doin' some bubble sortin' for fun\n temp = self.hand[i]\n self.hand[i] = self.hand[i + 1]\n self.hand[i + 1] = temp\n else:\n if self.hand[i].rank == self.hand[i + 1].rank: # checking suits in case we get same card ranks\n if self.hand[i].suit > self.hand[i + 1].suit:\n temp = self.hand[i]\n self.hand[i] = self.hand[i + 1]\n self.hand[i + 1] = temp\n highcard = self.hand[4]\n return highcard\n\n # Task 4\n # search hand for a pair of cards\n def evaluate(self):\n for card1 in self.hand: # these two for loops will iterate through every...\n for card2 in self.hand: # ...single card in a hand\n strcard1 = str(card1) # putting cards into strings to compare the first char...\n strcard2 = str(card2) # ...because the first char is the card number\n if strcard1 != strcard2: # making sure we do not compare the exact same cards\n if strcard1[0] == strcard2[0]: # compare number value of the cards\n return True # we found two cards with the same number\n return False # if we never find a match\n\n # checking to see if we have a straight and/or flush\n # NOTE: cards must be in order from least to greatest for this to work correctly\n def isstraightflush(self): # 8 is straight flush, 5 is flush, 4 is straight\n if self.hand[0].suit == self.hand[1].suit == self.hand[2].suit == self.hand[3].suit == self.hand[4].suit:\n for i in range(0, 10): # since the cards are in order we don't have to check every single card\n if self.hand[0].rank == i and self.hand[4].rank == i + 4: # checking ranks\n if self.hand[1].rank == i + 1 and self.hand[3].rank == i + 3:\n if self.hand[2].rank == i + 2:\n PokerStats.straightFlushCount += 1\n return 8 # we have found a straight flush\n PokerStats.flushCount += 1\n return 5 # we have a flush, but not straight flush\n else:\n for i in range(0, 10): # since the cards are in order we don't have to check every single card\n if self.hand[0].rank == i and self.hand[4].rank == i + 4: # checking ranks\n if self.hand[1].rank == i + 1 and self.hand[3].rank == i + 3:\n if self.hand[2].rank == i + 2:\n PokerStats.straightCount += 1\n return 4 # we have a straight but no flush\n return 0 # we haven't found anything\n\n # looking for any pairs (same rank) NOTE: cards must be in order from least to greatest for this to work correctly\n def ispair(self):\n for i in range(0, 4):\n if self.hand[i].rank == self.hand[i + 1].rank:\n # a pair has been found\n if i < 3 and self.hand[i].rank == self.hand[i + 2].rank:\n # 3 match found\n if i < 2 and self.hand[i].rank == self.hand[i + 3].rank:\n PokerStats.fourKindCount += 1\n return 7 # four of a kind found\n elif i < 1 and self.hand[i + 3].rank == self.hand[i + 4].rank:\n PokerStats.fullHouseCount += 1\n return 6 # three match then 2 match = full house\n PokerStats.threeKindCount += 1\n return 3 # three match found, not 4 match or full house\n elif i < 2 and self.hand[i + 2].rank == self.hand[i + 3].rank: # three in a row not found yet (maybe)\n # two pair found maybe full house\n if i < 1 and self.hand[i + 2].rank == self.hand[i + 4].rank:\n PokerStats.fullHouseCount += 1\n return 6 # full house found\n elif i < 1 and self.hand[i + 3].rank == self.hand[i + 4].rank:\n PokerStats.twoPairCount += 1\n return 2 # two pair found, but not a full house\n elif i < 1 and self.hand[i + 3].rank == self.hand[i + 4].rank:\n PokerStats.twoPairCount += 1\n return 2\n PokerStats.twoPairCount += 1\n return 2 # two pair found, but not full house\n return 0 # if nothing at all is found\n\n\n# Can use this to see the count of poker hands that are drawn.\nclass PokerStats:\n # the type of hands we will count for statistics:\n straightCount = 0 # a straight, but not a flush\n flushCount = 0 # a flush, but not a straight\n straightFlushCount = 0 # a straight flush\n threeKindCount = 0 # Three of a kind\n fourKindCount = 0 # Four of a kind\n fullHouseCount = 0 # Full house\n twoPairCount = 0 # two pairs\n\n\n# Task 5\n# compares two hands and returns true if hand 1 has a higher score than hand 2\ndef compare(table, h1position, h2position): # table list, int, int\n h1matches = 0 # initializing to zero because there might not be any good poker hands\n h2matches = 0\n\n h1highcard = table[h1position].getHighestCard() # this gives us the highest card in hand and\n h2highcard = table[h2position].getHighestCard() # organizes all the card from least to greatest\n\n h1straightflush = table[h1position].isstraightflush() # checking for straights and/or flushes\n h2straightflush = table[h2position].isstraightflush()\n\n # if we don't find any straights and/or flushes then we look for matches/pairs\n if h1straightflush == 0:\n h1matches = table[h1position].ispair()\n if h2straightflush == 0:\n h2matches = table[h2position].ispair()\n # combine score values for comparison; at least one of the added vars will be 0\n h1score = h1matches + h1straightflush\n h2score = h2matches + h2straightflush\n # compare the hands' score to see if hand 1 has a higher score\n if h1score > h2score:\n return True # hand 1 has a higher score than hand 2\n else:\n if h1score == h2score: # if both hands have the same score then we look at the highest card\n if h1highcard.rank > h2highcard.rank:\n return True # hand 1 has a higher score than hand 2\n elif h1highcard.rank == h2highcard.rank:\n if h1highcard.suit > h2highcard.suit:\n return True # hand 1 has a higher score than hand 2\n return False # hand 1 does not have a higher score than hand 2\n\n\n# End Class Definitions\n#\n# Begin Card Game Simulation\n\n# Task 3\ndeck = DeckOfCard() # create a new deck of 52 cards\ntable = [] # a list of each hand\n\ndeck.shuffle()\n\nfor _hand in range(5):\n h = Hand()\n table.append(h)\n\nfor _card in range(5):\n for h in table:\n card = deck.dealNextCard()\n h.add(card)\n\n\n# print all the hands\nhandcount = 1\nfor _hand in table:\n _hand.getHighestCard() # this will put the cards in order so we can make comparisons and find matches\n pairFound = _hand.evaluate()\n print(\"Hand #\" + str(handcount) + \" | Pair \" + str(pairFound))\n print(_hand)\n handcount += 1\n\n_handcount = 0\nfor _hand_ in table:\n for i in range(0, 5):\n # print(\"Comparing hand \" + str(_handcount + 1) + \" with hand \" + str(i + 1))\n highhand = compare(table, _handcount, i)\n if highhand:\n print(\"Hand \" + str(_handcount + 1) + \" has a higher score than hand \" + str(i + 1))\n _handcount += 1\n\n","sub_path":"Pycharm/Lab8TannerBornemann.py","file_name":"Lab8TannerBornemann.py","file_ext":"py","file_size_in_byte":9508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"344391535","text":"from __future__ import absolute_import\n\nimport pytest\n\nimport six\nfrom confluent_kafka.admin import AdminClient\nfrom confluent_kafka import Producer\n\n_EVENTS_TOPIC_NAME = \"test-ingest-events\"\n_ATTACHMENTS_TOPIC_NAME = \"test-ingest-attachments\"\n_TRANSACTIONS_TOPIC_NAME = \"test-ingest-transactions\"\n\n\ndef _get_topic_name(base_topic_name, test_name):\n if test_name is None:\n return base_topic_name\n else:\n return \"{}--{}\".format(_EVENTS_TOPIC_NAME, test_name)\n\n\n@pytest.fixture\ndef kafka_producer():\n def inner(settings):\n producer = Producer(\n {\"bootstrap.servers\": settings.KAFKA_CLUSTERS[\"default\"][\"bootstrap.servers\"]}\n )\n return producer\n\n return inner\n\n\nclass _KafkaAdminWrapper:\n def __init__(self, request, settings):\n self.test_name = request.node.name\n\n kafka_config = {}\n for key, val in six.iteritems(settings.KAFKA_CLUSTERS[\"default\"]):\n kafka_config[key] = val\n\n self.admin_client = AdminClient(kafka_config)\n\n def delete_events_topic(self):\n self._delete_topic(_EVENTS_TOPIC_NAME)\n\n def _delete_topic(self, base_topic_name):\n topic_name = _get_topic_name(base_topic_name, self.test_name)\n try:\n futures_dict = self.admin_client.delete_topics([topic_name])\n self._sync_wait_on_result(futures_dict)\n except Exception: # noqa\n pass # noqa nothing to do (probably there was no topic to start with)\n\n def _sync_wait_on_result(self, futures_dict):\n \"\"\"\n Synchronously waits on all futures returned by the admin_client api.\n :param futures_dict: the api returns a dict of futures that can be awaited\n \"\"\"\n # just wait on all futures returned by the async operations of the admin_client\n for f in futures_dict.values():\n f.result(5) # wait up to 5 seconds for the admin operation to finish\n\n\n@pytest.fixture\ndef kafka_admin(request):\n \"\"\"\n A fixture representing a simple wrapper over the admin interface\n :param request: the pytest request\n :return: a Kafka admin wrapper\n \"\"\"\n\n def inner(settings):\n return _KafkaAdminWrapper(request, settings)\n\n return inner\n","sub_path":"src/sentry/utils/pytest/kafka.py","file_name":"kafka.py","file_ext":"py","file_size_in_byte":2222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"51969464","text":"#斗图网图片下载\n\nfrom tkinter import *\nimport os\nimport requests\nfrom bs4 import BeautifulSoup\n\ndef do():\n urls = 'https://www.doutula.com/photo/list/?page=3'\n root = 'E:/图片/'\n request = requests.get(urls)\n content = request.content\n soup = BeautifulSoup(content,'lxml')\n img_list = soup.find_all('img',attrs = {'class':'img-responsive lazy image_dta'})\n for img in img_list:\n url_a = 'http:' + img['data-original']\n url = url_a.split('!')[0]\n path = root + url.split('/')[-1]\n try:\n if not os.path.exists(root):\n os.mkdir(root)\n if not os.path.exists(path):\n r = requests.get(url)\n with open(path,'wb') as f:\n f.write(r.content)\n f.close()\n print('文件保存成功')\n else:\n print('文件已存在')\n except:\n print('爬取失败')\napp = Tk()\nButton(text = 'click',command = do).pack()\n\napp.mainloop()","sub_path":"爬虫/斗图网图片下载.py","file_name":"斗图网图片下载.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"236276091","text":"# Time: O(s1 * min(s2, n1))\n# Space: O(s2)\n\n# Define S = [s,n] as the string S which consists of n connected strings s.\n# For example, [\"abc\", 3] =\"abcabcabc\".\n#\n# On the other hand, we define that string s1 can be obtained from string s2 \n# if we can remove some characters from s2 such that it becomes s1.\n# For example, “abc” can be obtained from “abdbec” based on our definition, but it can not be obtained from “acbbe”.\n#\n# You are given two non-empty strings s1 and s2 (each at most 100 characters long)\n# and two integers 0 ≤ n1 ≤ 106 and 1 ≤ n2 ≤ 106. Now consider the strings S1 and S2,\n# where S1=[s1,n1] and S2=[s2,n2]. Find the maximum integer M such that [S2,M] can be obtained from S1.\n#\n# Example:\n#\n# Input:\n# s1=\"acb\", n1=4\n# s2=\"ab\", n2=2\n#\n# Return:\n# 2\n\nclass Solution(object):\n def getMaxRepetitions(self, s1, n1, s2, n2):\n \"\"\"\n :type s1: str\n :type n1: int\n :type s2: str\n :type n2: int\n :rtype: int\n \"\"\"\n repeat_count = [0] * (len(s2)+1)\n lookup = {}\n j, count = 0, 0\n for k in xrange(1, n1+1):\n for i in xrange(len(s1)):\n if s1[i] == s2[j]:\n j = (j + 1) % len(s2)\n count += (j == 0)\n \n if j in lookup: # cyclic\n i = lookup[j]\n prefix_count = repeat_count[i]\n pattern_count = (count - repeat_count[i]) * ((n1 - i) // (k - i))\n suffix_count = repeat_count[i + (n1 - i) % (k - i)] - repeat_count[i]\n return (prefix_count + pattern_count + suffix_count) / n2\n lookup[j] = k\n repeat_count[k] = count\n \n return repeat_count[n1] / n2 # not cyclic iff n1 <= s2\n","sub_path":"LeetCode/github_leetcode/Python/count-the-repetitions.py","file_name":"count-the-repetitions.py","file_ext":"py","file_size_in_byte":1778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"164241469","text":"#!/usr/bin/env python3\nimport os\nimport time\nimport sys\nfrom sorters.BubbleSort import BubbleSort\nfrom sorters.BucketSort import bucket_sort\nfrom FileImporter import FileImporter\nfrom FileWriter import FileWriter\nfrom os.path import basename\n\nif __name__ == '__main__':\n # begin execution\n\n if len(sys.argv) < 3:\n print(\"Not enough paramaters\")\n exit(1)\n\n bucket_size = int(sys.argv[1])\n input_file_name = str(sys.argv[2])\n output_file_name = \"owens-\" + \\\n os.path.splitext(basename(input_file_name))[\n 0] + \"-\" + str(bucket_size) + \".txt\"\n fw = FileWriter(output_file_name)\n fi = FileImporter(input_file_name)\n arr = fi.get_array()\n start_times = []\n end_times = []\n for _ in range(3):\n start_times.append(time.clock())\n ret = bucket_sort(BubbleSort, arr, bucket_size)\n end_times.append(time.clock())\n\n bubble_sort_time = sum(end_times) - sum(start_times)\n\n fw = fw.set_number_buckets(bucket_size).set_sort_size(\n len(ret)).set_bubble_sort_time(bubble_sort_time)\n fw.set_out_array(ret).write()\n","sub_path":"Proj1/src/BucketSort_BubbleSort.py","file_name":"BucketSort_BubbleSort.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"542175892","text":"\"\"\"\nWe are trying to classify review of product is related to python book or television using K neariest neighbour\nThere are other ways also like bayes method or svm.\n\nwhat we did ? we used amazon scrapper to scrap the reviews from amazon.in to create a data set in pickle format.\n\n1. we wrote pickle_to_csv function to convert those pickle formatted data sets to csv file.\nBut while storing the data in csv file we cleaned up the data and\n\n2. we wrote read_csv_reviews_to_big_string to convert all reviews into single big_string.\n\n3. we wrote calculate_word_freq to cleanup data more .\n a. convert big string to small letters\n b. removed stop words and punctuations from big_string.\n\"\"\"\n\nimport re\nimport pandas as pd\nfrom nltk.tokenize import word_tokenize\nfrom string import punctuation\nfrom copy import deepcopy\nfrom nltk.corpus import stopwords\nimport nltk\nimport pickle\n\ndef clean_training_csv_file(csv_file_name, category):\n\t\"\"\"\n\tclean_csv_file:\n\tThis will receive the name of csv file in clean_csv_file and category\n\tconvert the column names as 'Review' into string .\n\tthen pick the lines whose length is > 6. i.e if review contain small character like good , bad because right now\n\twe are categorizing text on basis of PythonBook or Television , So these single words reviews should be ignored.\n\tthen it store the output in csv_file_name along with category\n\n\n\n\t:param csv_file_name:\n\t:param category:\n\t:return:\n\t\"\"\"\n\n\tdf = pd.read_csv(csv_file_name)\n\tdf['Review'] = df['Review'].astype('str')\n\tdf = df[df['Review'].str.len() > 6]\n\tdf['Category'] = category\n\tdf.to_csv(csv_file_name, index=None)\n\treturn csv_file_name\n\n\ndef pickle_to_csv(pickle_file):\n\t\"\"\"\n\tpickle_to_csv:\n\tthis function created a dictionary from pickle file. then extract review and rating from dictionary.\n\tthen it tries to replace unwanted character from review (data cleanup) and finally dump both values in csv file.\n\n\t:param pickle_file: name of pickle file\n\t:param category: category of csv file, remember if category is television then csv file name is Television.csv\n\t:return: None\n\t\"\"\"\n\n\tcategory_dict = pickle.load(open(pickle_file, \"rb\"))\n\n\t# here in search_pattern is (A|B|C) means A or B or C i.e if any character match A or B or C\n\t# \\.\\.+ --> means if you see multiple dots in text like .......\n\t# [^\\x00-\\x7F]+ --> means any unicode character like smile face or thumbs up or down symbol and similar shapes.\n\t# Basically all non-ASCII characters.\n\tsearch_pattern = r'([,\\(\\)\\\"\\\"\\']|\\.\\.+|[^\\x00-\\x7F]+)'\n\n\t# replacement pattern is just a blank space\n\treplacement_pattern = r' '\n\n\tcsv_file_name = pickle_file.replace(\".pickle\", \".csv\")\n\n\twith open(csv_file_name, 'w', encoding=\"utf-8\") as my_csv_file:\n\t\tprint('Review, Rating', file=my_csv_file)\n\t\tfor key, value in category_dict.items():\n\t\t\treview_text = value[4]['all_reviews_text']\n\t\t\tif review_text != \"not applicable\":\n\t\t\t\tfor item in review_text:\n\t\t\t\t\tif len(item) != 0:\n\t\t\t\t\t\tfor review, rating in item:\n\t\t\t\t\t\t\tprint(re.sub(search_pattern, replacement_pattern, review).strip(), \",\", rating,\n\t\t\t\t\t\t\t\t file=my_csv_file)\n\treturn csv_file_name\n\n\ndef split_training_and_test_data(csv_file_name):\n\ttrain_file = \"train_\" + csv_file_name\n\ttest_file = \"test_\" + csv_file_name\n\n\tdf = pd.read_csv(csv_file_name)\n\tnumber_of_records = len(df.index)\n\tif number_of_records < 100:\n\t\tprint(\"you need to train well this model, please provide more records to train\")\n\telse:\n\t\ttrain_number = int(number_of_records/2)\n\t\ttest_number = number_of_records - train_number\n\tdf_train = df.head(train_number)\n\tdf_test = df.tail(test_number)\n\tdf_train.to_csv(train_file, index=None)\n\tdf_test.to_csv(test_file, index=None)\n\treturn train_file, test_file\n\n\ndef combine_csv_files(file1,file2,result_file_name):\n\tdf_1 = pd.read_csv(file1)\n\tdf_2 = pd.read_csv(file2)\n\tdf_result = df_1.append(df_2)\n\tdf_result.to_csv(result_file_name, index=None)\n\n\ndef csv_to_dict(csv_fine_name):\n\tdf = pd.read_csv(csv_fine_name)\n\tmy_dict_name = df.to_dict('index')\n\treturn my_dict_name\n\n\ndef add_word_freq_to_model(my_dict):\n\ttemp_product_dict = deepcopy(my_dict)\n\t# Create the list of stop words and punctuation\n\tlist_of_punctuation = list(punctuation)\n\tenglish_stops = set(stopwords.words('english') + list_of_punctuation)\n\tfor key in temp_product_dict.keys():\n\t\treview_text = temp_product_dict[key]['Review']\n\t\ttok_words_of_review = list(word_tokenize(review_text))\n\t\tclean_tok_of_review = list(word for word in tok_words_of_review if word not in english_stops and len(word) > 1)\n\t\tmy_dict[key]['freq_dist_of_review'] = dict(nltk.FreqDist(clean_tok_of_review))\n\treturn my_dict\n\n\ndef find_nearest_neighbour(training_model_dict, test_model_dict):\n\ttemp_test_model_dict = deepcopy(test_model_dict)\n\n\tfor key in temp_test_model_dict.keys():\n\t\touter_book_count = 0\n\t\touter_tv_count = 0\n\t\tfor word, count_value in temp_test_model_dict[key]['freq_dist_of_review'].items():\n\t\t\tcategory_book_count = 0\n\t\t\tcategory_tv_count = 0\n\t\t\tfor key1 in training_model_dict.keys():\n\t\t\t\tfor word1, count_value1 in training_model_dict[key1]['freq_dist_of_review'].items():\n\t\t\t\t\tif word == word1:\n\t\t\t\t\t\tif training_model_dict[key1]['Category'] == 'pythonbook':\n\t\t\t\t\t\t\tcategory_book_count = category_book_count + count_value1\n\t\t\t\t\t\tif training_model_dict[key1]['Category'] == 'Television':\n\t\t\t\t\t\t\tcategory_tv_count = category_tv_count + count_value1\n\t\t\t# decision for particular word.\n\t\t\touter_book_count = outer_book_count + category_book_count\n\t\t\touter_tv_count = outer_tv_count + category_tv_count\n\t\t# decision for complete line\n\t\tif outer_book_count > outer_tv_count:\n\t\t\ttest_model_dict[key]['Category'] = 'pythonbook'\n\t\telif outer_book_count < outer_tv_count:\n\t\t\ttest_model_dict[key]['Category'] = 'Television'\n\t\telse:\n\t\t\ttest_model_dict[key]['Category'] = 'confused'\n\n\treturn test_model_dict\n\n\ndef dict_to_csv_file(my_dict, file_name):\n\twith open(file_name, 'w') as final_file:\n\t\tprint(\"Review,Rating,Category\", file=final_file)\n\t\tfor key, value in my_dict.items():\n\t\t\tprint(value['Review'], value[' Rating'], value['Category'], file=final_file)\n\n\nprint(\"step1\")\n# convert the pickle to csv files.\ncsv_file = pickle_to_csv('PythonBook.pickle')\ntrain_1, test_1 = split_training_and_test_data(csv_file)\nclean_training_csv_file(train_1, 'pythonbook')\ncsv_file = pickle_to_csv('Television.pickle')\ntrain_2, test_2 = split_training_and_test_data(csv_file)\nclean_training_csv_file(train_2, 'Television')\n\n\n# train_1 = 'train_Television.csv'\n# train_2 = 'train_PythonBook.csv'\n# test_1 = 'test_Television.csv'\n# test_2 = 'test_PythonBook.csv'\n\nprint(\"step2\")\ncombine_csv_files(train_1, train_2, 'complete_training_data.csv')\ncombine_csv_files(test_1, test_2, 'complete_test_data.csv')\n\nprint(\"step3\")\ntraining_model_dict = csv_to_dict('complete_training_data.csv')\ntest_model_dict = csv_to_dict('complete_test_data.csv')\n\nprint(\"step4\")\ntraining_model_dict = add_word_freq_to_model(training_model_dict)\ntest_model_dict = add_word_freq_to_model(test_model_dict)\n\nprint(\"step5\")\ntest_model_dict = find_nearest_neighbour(training_model_dict, test_model_dict)\nwith open('test_model_dict.pickle', 'wb') as pkl_file:\n\tpickle.dump(test_model_dict, pkl_file, protocol=pickle.HIGHEST_PROTOCOL)\n\ntest_model_dict = pickle.load(open('test_model_dict.pickle', 'rb'))\ndict_to_csv_file(test_model_dict, 'updated_complete_training_data.csv')\n\n","sub_path":"ActoClassificationOfReviews.py","file_name":"ActoClassificationOfReviews.py","file_ext":"py","file_size_in_byte":7312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"441451157","text":"# -*- coding: utf-8 -*-\r\nfrom PIL import Image\r\nimport numpy as np\r\nimport glob\r\nimport random\r\nimport cv2\r\nimport matplotlib.pyplot as plt\r\nimport math\r\ndef f():\r\n datasets_img= []\r\n datasets_label= []\r\n for j in range(5000):#10000\r\n #for i in range(1000):\r\n i=j+5000\r\n img = cv2.imread(\"./new_data/img_withcirclenoise/image%05d.PNG\" %(i))#circle noise\r\n #img = cv2.imread(\"./new_data/img_withpixelnoise/image%05d.PNG\" %(i))#circle noise\r\n img = cv2.resize(img,(32,32))\r\n \r\n img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\r\n x = np.array(img,dtype=np.float32)\r\n x /=255\r\n \r\n x = x.reshape(1,32,32)\r\n datasets_img.append(x)\r\n \r\n #with open('./data/test.txt','r') as x:\r\n with open('./new_data/train_circle_XYj.txt','r') as x:\r\n #with open('./new_data/train_pixel_XYj.txt','r') as x:\r\n labels =x.readlines()\r\n t = labels[i]\r\n t = t.split()\r\n t = t[0:2] #teacher:xy\r\n #t = t[2] #teacher: angel\r\n #t = math.radians(t)\r\n t = np.array(t,dtype=np.float32)#teacher:xy\r\n #t = np.array(([math.cos(t),math.sin(t),dtype=np.float32)\r\n #t /= 360\r\n t /= 256\r\n #print t\r\n #print t.shape\r\n #print type(t)\r\n #print t\r\n datasets_label.append(t)\r\n #random.shuffle(datasets_)\r\n train_X = datasets_img\r\n train_Y = datasets_label\r\n #test = datasets[9:10]\r\n #test = datasets[7000:8317]\r\n #return train,test\r\n #print train\r\n return train_X,train_Y\r\n \r\n \r\n \r\n \r\n#train_X,train_Y = f()\r\n#print type(train_X)\r\n#print train_X\r\n\r\n\r\n\r\n\r\n","sub_path":"dataset_make_circle_xt.py","file_name":"dataset_make_circle_xt.py","file_ext":"py","file_size_in_byte":1712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"518582019","text":"# -*- coding: utf-8 -*-\n\n#import locale\n#locale.setlocale(locale.LC_ALL,'pt_BR.UTF-8')\n\nimport datetime\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render\nfrom django.template import RequestContext, loader\nfrom django.http import HttpResponse\n\nfrom weasyprint import HTML\n\nfrom agendas.models import *\nfrom agendas.forms import *\n\n@login_required\ndef agendar(request):\n feriados = Feriado.objects.all()\n fer = []\n for feriado in feriados:\n fer.append(feriado.data);\n if request.method == 'POST':\n form = FormAgenda(request.POST)\n if form.is_valid():\n criador = request.user\n profissional = form.cleaned_data['profissional']\n segunda = form.cleaned_data['segunda']\n terca = form.cleaned_data['terca']\n quarta = form.cleaned_data['quarta']\n quinta = form.cleaned_data['quinta']\n sexta = form.cleaned_data['sexta']\n sabado = form.cleaned_data['sabado']\n domingo = form.cleaned_data['domingo']\n inicial = form.cleaned_data['inicial']\n final = form.cleaned_data['final']\n inicio = form.cleaned_data['inicio']\n fim = form.cleaned_data['fim']\n duracao = form.cleaned_data['duracao']\n unidade = form.cleaned_data['unidade']\n semana = [segunda,terca,quarta,quinta,sexta,sabado,domingo]\n while inicial < final:\n if inicial in fer:\n inicial = inicial + timedelta(days=1);\n else:\n for indice, dia in enumerate(semana):\n if dia == True:\n x = timedelta(0);\n if inicial.weekday() == indice:\n i = datetime.combine(inicial,inicio);\n f = datetime.combine(inicial,fim);\n while i <= f:\n atividade = Atividade(criador = request.user, profissional = profissional, unidade = unidade, horario = i)\n atividade.save()\n i = i + timedelta(seconds=duracao*60);\n inicial = inicial + timedelta(days=1);\n else:\n inicial = inicial + timedelta(days=1);\n mostrar = 'Agendas Criadas!'\n form = FormAgenda()\n return render(request, 'agendas/agendar.html', locals(),)\n else:\n mostrar = 'Agendas Não Criadas!'\n form = FormAgenda()\n return render(request, 'agendas/agendar.html', locals(),)\n else:\n form = FormAgenda()\n return render(request, 'agendas/agendar.html', locals(),)\n\n@login_required\ndef etiquetar(request):\n\n if request.method == 'POST':\n if form.is_valid():\n inicial = form.cleaned_data['inicial']\n final = form.cleaned_data['final']\n form = FormAgenda()\n return render(request, 'agendas/agendar.html', locals(),)\n\n else:\n return render(request, 'agendas/agendar.html', locals(),)\n else:\n return render(request, 'agendas/agendar.html', locals(),) \n\ndef imprimir(request, id):\n\n atividade = Atividade.objects.get(pk=id)\n parametro = Parametro.objects.all()\n\n contexto = locals()\n\n template = loader.get_template('impressos/agendas/imprimir.html')\n html = template.render(RequestContext(request, contexto))\n pdf = HTML(string=html).render().write_pdf()\n\n return HttpResponse(pdf, content_type='application/pdf')\n","sub_path":"agendas/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"542066240","text":"from kivy.app import App\nfrom kivy.lang import Builder\nfrom kivy.core.window import Window\n\nclass ConvertNumberApp(App):\n def build(self):\n Window.size = (500, 250)\n self.title = \"Convert Miles to Kilometres\"\n self.root = Builder.load_file('scratch.kv')\n return self.root\n def handle_calculate(self):\n value = self.get_validNumber()\n result = value *1.60934\n self.root.ids.output_label.text = str(result)\n def handle_valueChange(self, change):\n value = self.get_validNumber() + change\n self.root.ids.input_number.text = str(value)\n self.handle_calculate()\n def get_validNumber(self):\n try:\n value = float(self.root.ids.input_number.text)\n return value\n except ValueError:\n return 0\n\nConvertNumberApp().run()\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Prac_07/scratch.py","file_name":"scratch.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"113481948","text":"#!/usr/bin/python3\n\n# This ought to be used via the top level bash script of the same name.\n\nfields = [\"name\", \"shop\", \"price\", \"nServings\", \"servingDesc\", \"inmeals\", \"foodtype\", \"nGrams\", \"cals\", \"carbs\", \"protein\", \"fat\"]\ndata = [\"-\", \"-\", \"-\", \"-\", \"-\", \"-\", \"-\", \"-\", \"-\", \"-\", \"-\", \"-\"]\n\nprint(\"b = step back, f = step forward, s = submit now\\n\")\n\nnFields = len(fields)\ni = 0\n\nwhile (i < nFields):\n prompt = (\"Enter \" + fields[i] + \", whose current value is \" + data[i] + \"\\n\")\n s = input(prompt)\n if (s == \"b\"):\n i -= 1\n elif (s == \"f\"):\n i += 1\n elif (s == \"s\"):\n i = nFields\n else:\n data[i] = s\n i += 1\n\nspending = \"`spending insert (name:`\"+ data[0] +\";boughtfrom:`\"+ data[1] +\";price:\"+ data[2] +\"f;nServings:\"+ data[3] +\";servingDescription:\\\"\"+ data[4] +\"\\\";inmeals:\"+ data[5] +\"b;foodtype:`\"+ data[6] +\")\"\ngivenstats = \"`givenstats insert (name:`\"+ data[0] +\";nGrams:\"+ data[7] +\";calsP100g:\"+ data[8] +\";carbsP100g:\"+ data[9] +\"f;proteinP100g:\"+ data[10] +\"f;fatP100g:\"+ data[11] +\"f)\"\n\nf = open(\"insertFoods.q\", \"w\")\nprint(\"#!/home/rob/q/l32/q\", file=f)\nprint(\"spending: value`:tables/spending\", file=f)\nprint(\"givenstats: value`:tables/givenstats\", file=f)\nprint(spending, file=f)\nprint(\"save `:tables/spending\", file=f)\nprint(givenstats, file=f)\nprint(\"save `:tables/givenstats\", file=f)\nprint(\"exit 0\", file=f)\nf.close()\nexit(0)\n","sub_path":"dataEntry/enterData.py","file_name":"enterData.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"515537367","text":"#!/usr/bin/python\n#coding=utf-8\n\nimport os\nimport sys\nimport codecs\nimport chardet\nimport shutil\nimport sys\nreload(sys)\nsys.setdefaultencoding('UTF-8')\n\nif __name__ == '__main__':\n \n #通过参数获得基础文件名\n #print(\"sys.argv:\")\n #print(sys.argv)\n\n #获得当前路径\n currentPath = os.getcwd()\n #print(\"currentPath:\"+currentPath)\n\n #目标数据文件路径\n # oriDataPath = \"E:\\\\worldshipsconfig\\\\数据表\\\\\"\n oriDataPath = \"E:\\\\worldshipsconfig\\\\测试环境数据表\\\\\"\n oriDataPath = unicode(oriDataPath , \"utf8\")\n\n #拼出基础文件路径\n baseFilePath = currentPath + \"\\\\config\"\n print( \"baseFilePath:\" + baseFilePath )\n\n #循环基础文件夹中的文件\n for fileName in os.listdir( baseFilePath ):\n #调试,输出文件名\n # print( fileName )\n \n #生成文件名\n dstFile = baseFilePath + \"\\\\\" + fileName\n dstFile1 = baseFilePath + \"\\\\temp\\\\\" + fileName\n srcFile = oriDataPath + fileName\n\n if os.path.exists( srcFile ):\n\n print( \"copy:\" + fileName )\n #从oriDataPath拷贝过来\n os.remove( dstFile )\n shutil.copyfile( srcFile, dstFile )\n # shutil.copyfile( srcFile, dstFile1 )","sub_path":"多语言和表格数据生成脚本/copy_file.py","file_name":"copy_file.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"493595873","text":"from django.urls import path\n\nfrom boss import boss_api\n\nurlpatterns = [\n # BOSS 首页\n path('index/', boss_api.boss_index, name='boss_index'),\n # BOSS 创建项目\n path('create/pro/', boss_api.boss_create_project, name='boss_create_pro'),\n # BOSS 删除项目\n path('delete/pro/', boss_api.boss_delete_pro, name='boss_delete_pro'),\n # BOSS 修改项目\n path('modify/pro/', boss_api.boss_modify_pro, name='boss_modify_pro'),\n\n path('createItem/', boss_api.createItem, name='createItem'),\n path('personAdmin/', boss_api.personAdmin, name='personAdmin'),\n path('salaryAdmin/', boss_api.salaryAdmin, name='salaryAdmin'),\n]\n","sub_path":"workinghours_subsystem/boss/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"140657565","text":"# %% [markdown]\n# # The Algorithm\n# 1. Pick any node. If it is unvisited, mark it as visited and recur on all its adjacent nodes.\n# 2. Repeat until all the nodes are visited, or the node to be searched is found.\n# %% [markdown]\n# # Create Graph\n# We have to create graph like this: \n# ![alt text](https://www.educative.io/api/edpresso/shot/5410617873661952/image/6437799702036480 \"Graph\")\n\n\n# %%\ngraph = {\n 'A' : ['B', 'C'],\n 'B' : ['D', 'E'],\n 'C' : ['F'],\n 'D' : [],\n 'E' : ['F'],\n 'F' : []\n}\n\n# %% [markdown]\n# # Write DFS Algorithm code\n# %%\nvisited = [] # Array to keep track of visited nodes.\ndef dfs(visited, graph, node):\n if node not in visited:\n print(node)\n visited.append(node)\n for neighbour in graph[node]:\n dfs(visited, graph, neighbour)\ndfs(visited, graph, 'A')\n \n\n","sub_path":"LAB01/DFS/Depth_First_Search.py","file_name":"Depth_First_Search.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"172592398","text":"class Solution(object):\n def reverse(self, x):\n \"\"\"\n :type x: int\n :rtype: int\n \"\"\"\n result = 0\n if x > 0:\n result = int(str(x)[::-1])\n if x < 0:\n result = -int((str(x).strip('-')[::-1]))\n return result if abs(result) <= 2147483647 else 0\n","sub_path":"7-Reverse Integer.py","file_name":"7-Reverse Integer.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"259115866","text":"# Copyright 2020 Curtin University\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# Author: Tuan Chien\n\nimport json\nimport os\nimport unittest\nimport unittest.mock as mock\nfrom logging import error\nfrom queue import Empty, Queue\nfrom threading import Event, Thread\nfrom time import sleep\nfrom unittest.mock import MagicMock, patch\n\nimport observatory.api.server.orm as orm\nimport pendulum\nfrom academic_observatory_workflows.config import test_fixtures_folder\nfrom academic_observatory_workflows.workflows.scopus_telescope import (\n ScopusClient,\n ScopusJsonParser,\n ScopusRelease,\n ScopusTelescope,\n ScopusUtility,\n ScopusUtilWorker,\n)\nfrom airflow import AirflowException\nfrom airflow.models import Connection\nfrom airflow.utils.state import State\nfrom click.testing import CliRunner\nfrom freezegun import freeze_time\nfrom observatory.platform.utils.airflow_utils import AirflowConns, AirflowVars\nfrom observatory.platform.utils.api import make_observatory_api\nfrom observatory.platform.utils.gc_utils import run_bigquery_query\nfrom observatory.platform.utils.test_utils import (\n HttpServer,\n ObservatoryEnvironment,\n ObservatoryTestCase,\n module_file_path,\n)\nfrom observatory.platform.utils.url_utils import get_user_agent\nfrom observatory.platform.utils.workflow_utils import (\n bigquery_sharded_table_id,\n blob_name,\n build_schedule,\n make_dag_id,\n)\n\n\nclass TestScopusUtility(unittest.TestCase):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n @patch(\"academic_observatory_workflows.workflows.scopus_telescope.Queue.empty\")\n def test_clear_task_queue(self, m_empty):\n m_empty.side_effect = [False, False, True]\n\n q = Queue()\n q.put(1)\n\n ScopusUtility.clear_task_queue(q)\n self.assertRaises(Empty, q.get, False)\n q.join() # Make sure no block\n\n\nclass MockUrlResponse:\n def __init__(self, *, response=\"{}\", code=200):\n self.response = response\n self.code = code\n\n def getheader(self, header):\n if header == \"X-RateLimit-Remaining\":\n return 0\n\n if header == \"X-RateLimit-Reset\":\n return 10\n\n def getcode(self):\n return self.code\n\n def read(self):\n return self.response\n\n\nclass TestScopusClient(unittest.TestCase):\n \"\"\"Test the ScopusClient class.\"\"\"\n\n class MockMetadata:\n @classmethod\n def get(self, attribute):\n if attribute == \"Version\":\n return \"1\"\n if attribute == \"Home-page\":\n return \"http://test.test\"\n if attribute == \"Author-email\":\n return \"test@test\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.api_key = \"testkey\"\n self.query = \"dummyquery\"\n\n def test_scopus_client_user_agent(self):\n \"\"\"Test to make sure the user agent string is set correctly.\"\"\"\n with patch(\"observatory.platform.utils.url_utils.metadata\", return_value=TestScopusClient.MockMetadata):\n obj = ScopusClient(api_key=\"\")\n generated_ua = obj._headers[\"User-Agent\"]\n self.assertEqual(generated_ua, get_user_agent(package_name=\"academic_observatory_workflows\"))\n\n def test_get_reset_date_from_error(self):\n msg = f\"{ScopusClient.QUOTA_EXCEED_ERROR_PREFIX}2000\"\n offset = ScopusClient.get_reset_date_from_error(msg)\n self.assertEqual(offset, 2)\n\n def test_get_next_page_url(self):\n links = []\n next_link = ScopusClient.get_next_page_url(links)\n self.assertEqual(next_link, None)\n\n expected_url = \"http://next.url\"\n links = [{\"@ref\": \"next\", \"@href\": expected_url}]\n next_link = ScopusClient.get_next_page_url(links)\n self.assertEqual(next_link, expected_url)\n\n links = [{\"@ref\": \"self\"}]\n next_link = ScopusClient.get_next_page_url(links)\n self.assertEqual(next_link, None)\n\n links = [{}]\n self.assertEqual(ScopusClient.get_next_page_url(links), None)\n\n @patch(\"academic_observatory_workflows.workflows.scopus_telescope.urllib.request.Request\")\n @patch(\"academic_observatory_workflows.workflows.scopus_telescope.urllib.request.urlopen\")\n def test_retrieve_exceeded(self, m_urlopen, m_request):\n m_urlopen.return_value = MockUrlResponse(code=429)\n\n client = ScopusClient(api_key=self.api_key)\n self.assertRaises(AirflowException, client.retrieve, self.query)\n\n @patch(\"academic_observatory_workflows.workflows.scopus_telescope.urllib.request.Request\")\n @patch(\"academic_observatory_workflows.workflows.scopus_telescope.urllib.request.urlopen\")\n def test_retrieve_noresults(self, m_urlopen, m_request):\n m_urlopen.return_value = MockUrlResponse(code=200, response=b\"{}\")\n\n client = ScopusClient(api_key=self.api_key)\n results, remaining, reset = client.retrieve(self.query)\n self.assertEqual(results, [])\n self.assertEqual(remaining, 0)\n self.assertEqual(reset, 10)\n\n @patch(\"academic_observatory_workflows.workflows.scopus_telescope.json.loads\")\n @patch(\"academic_observatory_workflows.workflows.scopus_telescope.urllib.request.Request\")\n @patch(\"academic_observatory_workflows.workflows.scopus_telescope.urllib.request.urlopen\")\n def test_retrieve_totalresults_zero(self, m_urlopen, m_request, m_json):\n m_urlopen.return_value = MockUrlResponse(code=200, response=b\"{}\")\n\n m_json.return_value = {\n \"search-results\": {\n \"entry\": [None],\n \"opensearch:totalResults\": 0,\n }\n }\n\n client = ScopusClient(api_key=self.api_key)\n results, remaining, reset = client.retrieve(self.query)\n self.assertEqual(results, [])\n self.assertEqual(remaining, 0)\n self.assertEqual(reset, 10)\n\n @patch(\"academic_observatory_workflows.workflows.scopus_telescope.urllib.request.Request\")\n @patch(\"academic_observatory_workflows.workflows.scopus_telescope.urllib.request.urlopen\")\n def test_retrieve_unexpected_httpcode(self, m_urlopen, m_request):\n m_urlopen.return_value = MockUrlResponse(code=403, response=b\"{}\")\n\n client = ScopusClient(api_key=self.api_key)\n self.assertRaises(AirflowException, client.retrieve, self.query)\n\n @patch(\"academic_observatory_workflows.workflows.scopus_telescope.urllib.request.Request\")\n @patch(\"academic_observatory_workflows.workflows.scopus_telescope.urllib.request.urlopen\")\n def test_retrieve_max_results_exceeded(self, m_urlopen, m_request):\n response = b'{\"search-results\": {\"entry\": [1], \"opensearch:totalResults\": 5001}}'\n\n m_urlopen.return_value = MockUrlResponse(code=200, response=response)\n client = ScopusClient(api_key=self.api_key)\n self.assertRaises(AirflowException, client.retrieve, self.query)\n\n @patch(\"academic_observatory_workflows.workflows.scopus_telescope.urllib.request.Request\")\n @patch(\"academic_observatory_workflows.workflows.scopus_telescope.urllib.request.urlopen\")\n def test_retrieve_no_next_url(self, m_urlopen, m_request):\n response = b'{\"search-results\": {\"entry\": [1], \"opensearch:totalResults\": 2, \"link\": []}}'\n\n m_urlopen.return_value = MockUrlResponse(code=200, response=response)\n client = ScopusClient(api_key=self.api_key)\n self.assertRaises(AirflowException, client.retrieve, self.query)\n\n @patch(\"academic_observatory_workflows.workflows.scopus_telescope.urllib.request.Request\")\n @patch(\"academic_observatory_workflows.workflows.scopus_telescope.urllib.request.urlopen\")\n def test_retrieve(self, m_urlopen, m_request):\n response = b'{\"search-results\": {\"entry\": [1], \"opensearch:totalResults\": 2, \"link\": [{\"@ref\": \"next\", \"@href\": \"someurl\"}]}}'\n\n m_urlopen.return_value = MockUrlResponse(code=200, response=response)\n client = ScopusClient(api_key=self.api_key)\n results, _, _ = client.retrieve(self.query)\n self.assertEqual(len(results), 2)\n\n\nclass TestScopusUtilWorker(unittest.TestCase):\n def test_ctor(self):\n util = ScopusUtilWorker(\n client_id=0, client=None, quota_reset_date=pendulum.datetime(2000, 1, 1), quota_remaining=0\n )\n\n self.assertEqual(util.client_id, 0)\n self.assertEqual(util.client, None)\n self.assertEqual(util.quota_reset_date, pendulum.datetime(2000, 1, 1))\n self.assertEqual(util.quota_remaining, 0)\n\n def test_build_query(self):\n institution_ids = [\"60031226\"]\n period = pendulum.period(pendulum.datetime(2021, 1, 1), pendulum.datetime(2021, 2, 1))\n query = ScopusUtility.build_query(institution_ids=institution_ids, period=period)\n\n def test_make_query(self):\n worker = MagicMock()\n worker.client = MagicMock()\n worker.client.retrieve = MagicMock()\n worker.client.retrieve.return_value = [{}, {}], 2000, 10\n query = \"\"\n results, num_results = ScopusUtility.make_query(worker=worker, query=query)\n self.assertEqual(num_results, 2)\n self.assertEqual(results, \"[{}, {}]\")\n\n @freeze_time(\"2021-02-01\")\n @patch(\"academic_observatory_workflows.workflows.scopus_telescope.write_to_file\")\n def test_download_period(self, m_write_file):\n conn = \"conn_id\"\n worker = MagicMock()\n worker.client = MagicMock()\n worker.client.retrieve = MagicMock()\n results = [{}] * (ScopusClient.MAX_RESULTS + 1)\n worker.client.retrieve.return_value = results, 2000, 10\n period = pendulum.period(pendulum.date(2021, 1, 1), pendulum.date(2021, 2, 1))\n institution_ids = [\"123\"]\n ScopusUtility.download_period(\n worker=worker, conn=conn, period=period, institution_ids=institution_ids, download_dir=\"/tmp\"\n )\n\n args, _ = m_write_file.call_args\n self.assertEqual(args[0], json.dumps(results))\n self.assertEqual(args[1], \"/tmp/2021-01-01_2021-02-01_2021-02-01T00:00:00+00:00.json\")\n\n @freeze_time(\"2021-02-02\")\n def test_sleep_if_needed_needed(self):\n reset_date = pendulum.datetime(2021, 2, 2, 0, 0, 1)\n with patch(\"academic_observatory_workflows.workflows.scopus_telescope.logging.info\") as m_log:\n ScopusUtility.sleep_if_needed(reset_date=reset_date, conn=\"conn\")\n self.assertEqual(m_log.call_count, 1)\n\n @freeze_time(\"2021-02-02\")\n def test_sleep_if_needed_not_needed(self):\n reset_date = pendulum.datetime(2021, 2, 1)\n with patch(\"academic_observatory_workflows.workflows.scopus_telescope.logging.info\") as m_log:\n ScopusUtility.sleep_if_needed(reset_date=reset_date, conn=\"conn\")\n self.assertEqual(m_log.call_count, 0)\n\n @freeze_time(\"2021-02-02\")\n def test_update_reset_date(self):\n conn = \"conn_id\"\n worker = MagicMock()\n now = pendulum.now(\"UTC\")\n worker.quota_reset_date = now\n new_ts = now.int_timestamp * 1000 + 2000\n error_msg = f\"{ScopusClient.QUOTA_EXCEED_ERROR_PREFIX}{new_ts}\"\n ScopusUtility.update_reset_date(conn=conn, error_msg=error_msg, worker=worker)\n self.assertTrue(worker.quota_reset_date > now)\n\n @patch.object(ScopusUtilWorker, \"QUEUE_WAIT_TIME\", 1)\n def test_download_worker_empty_retry_exit(self):\n def trigger_exit(event):\n now = pendulum.now(\"UTC\")\n trigger = now.add(seconds=5)\n\n while pendulum.now(\"UTC\") < trigger:\n continue\n\n event.set()\n\n conn = \"conn\"\n queue = Queue()\n event = Event()\n institution_ids = [\"123\"]\n\n thread = Thread(target=trigger_exit, args=(event,))\n thread.start()\n worker = ScopusUtilWorker(client_id=0, client=None, quota_reset_date=pendulum.now(\"UTC\"), quota_remaining=10)\n\n ScopusUtility.download_worker(\n worker=worker,\n exit_event=event,\n taskq=queue,\n conn=conn,\n institution_ids=institution_ids,\n download_dir=\"\",\n )\n thread.join()\n\n @patch(\"academic_observatory_workflows.workflows.scopus_telescope.ScopusUtility.download_period\")\n def test_download_worker_download_exit(self, m_download):\n def trigger_exit(event):\n now = pendulum.now(\"UTC\")\n trigger = now.add(seconds=5)\n\n while pendulum.now(\"UTC\") < trigger:\n continue\n\n event.set()\n\n conn = \"conn\"\n queue = Queue()\n now = pendulum.now(\"UTC\")\n queue.put(pendulum.period(now, now))\n event = Event()\n institution_ids = [\"123\"]\n\n thread = Thread(target=trigger_exit, args=(event,))\n thread.start()\n worker = ScopusUtilWorker(client_id=0, client=None, quota_reset_date=pendulum.now(\"UTC\"), quota_remaining=10)\n\n ScopusUtility.download_worker(\n worker=worker,\n exit_event=event,\n taskq=queue,\n conn=conn,\n institution_ids=institution_ids,\n download_dir=\"\",\n )\n thread.join()\n\n @patch(\"academic_observatory_workflows.workflows.scopus_telescope.ScopusUtility.download_period\")\n def test_download_worker_download_quota_exceed_retry_exit(self, m_download):\n def trigger_exit(event):\n now = pendulum.now(\"UTC\")\n trigger = now.add(seconds=1)\n\n while pendulum.now(\"UTC\") < trigger:\n continue\n\n event.set()\n\n now = pendulum.now(\"UTC\")\n next_reset = now.add(seconds=2).int_timestamp * 1000\n\n m_download.side_effect = [AirflowException(f\"{ScopusClient.QUOTA_EXCEED_ERROR_PREFIX}{next_reset}\"), None]\n\n conn = \"conn\"\n queue = Queue()\n queue.put(pendulum.period(now, now))\n event = Event()\n institution_ids = [\"123\"]\n\n thread = Thread(target=trigger_exit, args=(event,))\n thread.start()\n worker = ScopusUtilWorker(client_id=0, client=None, quota_reset_date=now, quota_remaining=10)\n\n ScopusUtility.download_worker(\n worker=worker,\n exit_event=event,\n taskq=queue,\n conn=conn,\n institution_ids=institution_ids,\n download_dir=\"\",\n )\n thread.join()\n\n @patch(\"academic_observatory_workflows.workflows.scopus_telescope.ScopusUtility.download_period\")\n def test_download_worker_download_uncaught_exception(self, m_download):\n def trigger_exit(event):\n now = pendulum.now(\"UTC\")\n trigger = now.add(seconds=5)\n\n while pendulum.now(\"UTC\") < trigger:\n continue\n\n event.set()\n\n now = pendulum.now(\"UTC\")\n m_download.side_effect = AirflowException(\"Some other error\")\n conn = \"conn\"\n queue = Queue()\n queue.put(pendulum.period(now, now))\n queue.put(pendulum.period(now, now))\n event = Event()\n institution_ids = [\"123\"]\n\n thread = Thread(target=trigger_exit, args=(event,))\n thread.start()\n worker = ScopusUtilWorker(client_id=0, client=None, quota_reset_date=now, quota_remaining=10)\n\n self.assertRaises(\n AirflowException,\n ScopusUtility.download_worker,\n worker=worker,\n exit_event=event,\n taskq=queue,\n conn=conn,\n institution_ids=institution_ids,\n download_dir=\"\",\n )\n thread.join()\n\n @patch(\"academic_observatory_workflows.workflows.scopus_telescope.ScopusUtility.download_period\")\n def test_download_parallel(self, m_download):\n now = pendulum.now(\"UTC\")\n conn = \"conn\"\n queue = Queue()\n institution_ids = [\"123\"]\n m_download.return_value = None\n\n for _ in range(4):\n queue.put(pendulum.period(now, now))\n\n workers = [\n ScopusUtilWorker(client_id=i, client=None, quota_reset_date=now, quota_remaining=10) for i in range(2)\n ]\n\n ScopusUtility.download_parallel(\n workers=workers, taskq=queue, conn=conn, institution_ids=institution_ids, download_dir=\"\"\n )\n\n\nclass TestScopusJsonParser(unittest.TestCase):\n \"\"\"Test parsing facilities.\"\"\"\n\n def __init__(self, *args, **kwargs):\n super(TestScopusJsonParser, self).__init__(*args, **kwargs)\n self.institution_ids = [\"60031226\"] # Curtin University\n\n self.data = {\n \"dc:identifier\": \"scopusid\",\n \"eid\": \"testid\",\n \"dc:title\": \"arttitle\",\n \"prism:aggregationType\": \"source\",\n \"subtypeDescription\": \"typedesc\",\n \"citedby-count\": \"345\",\n \"prism:publicationName\": \"pubname\",\n \"prism:isbn\": \"isbn\",\n \"prism:issn\": \"issn\",\n \"prism:eIssn\": \"eissn\",\n \"prism:coverDate\": \"2010-12-01\",\n \"prism:doi\": \"doi\",\n \"pii\": \"pii\",\n \"pubmed-id\": \"med\",\n \"orcid\": \"orcid\",\n \"dc:creator\": \"firstauth\",\n \"source-id\": \"1000\",\n \"openaccess\": \"1\",\n \"openaccessFlag\": False,\n \"affiliation\": [\n {\n \"affilname\": \"aname\",\n \"affiliation-city\": \"acity\",\n \"affiliation-country\": \"country\",\n \"afid\": \"id\",\n \"name-variant\": \"variant\",\n }\n ],\n \"author\": [\n {\n \"authid\": \"id\",\n \"orcid\": \"id\",\n \"authname\": \"name\",\n \"given-name\": \"first\",\n \"surname\": \"last\",\n \"initials\": \"mj\",\n \"afid\": \"id\",\n }\n ],\n \"dc:description\": \"abstract\",\n \"authkeywords\": [\"words\"],\n \"article-number\": \"artno\",\n \"fund-acr\": \"acr\",\n \"fund-no\": \"no\",\n \"fund-sponsor\": \"sponsor\",\n }\n\n def test_get_affiliations(self):\n \"\"\"Test get affiliations\"\"\"\n\n affil = ScopusJsonParser.get_affiliations({})\n self.assertEqual(affil, None)\n\n affil = ScopusJsonParser.get_affiliations(self.data)\n self.assertEqual(len(affil), 1)\n af = affil[0]\n self.assertEqual(af[\"name\"], \"aname\")\n self.assertEqual(af[\"city\"], \"acity\")\n self.assertEqual(af[\"country\"], \"country\")\n self.assertEqual(af[\"id\"], \"id\")\n self.assertEqual(af[\"name_variant\"], \"variant\")\n\n # 0 length affiliations\n affil = ScopusJsonParser.get_affiliations({\"affiliation\": []})\n self.assertEqual(affil, None)\n\n def test_get_authors(self):\n \"\"\"Test get authors\"\"\"\n\n author = ScopusJsonParser.get_authors({})\n self.assertEqual(author, None)\n\n author = ScopusJsonParser.get_authors(self.data)\n self.assertEqual(len(author), 1)\n au = author[0]\n self.assertEqual(au[\"authid\"], \"id\")\n self.assertEqual(au[\"orcid\"], \"id\")\n self.assertEqual(au[\"full_name\"], \"name\")\n self.assertEqual(au[\"first_name\"], \"first\")\n self.assertEqual(au[\"last_name\"], \"last\")\n self.assertEqual(au[\"initials\"], \"mj\")\n self.assertEqual(au[\"afid\"], \"id\")\n\n # 0 length author\n author = ScopusJsonParser.get_authors({\"author\": []})\n self.assertEqual(author, None)\n\n def test_get_identifier_list(self):\n ids = ScopusJsonParser.get_identifier_list({}, \"myid\")\n self.assertEqual(ids, None)\n\n ids = ScopusJsonParser.get_identifier_list({\"myid\": \"thing\"}, \"myid\")\n self.assertEqual(ids, [\"thing\"])\n\n ids = ScopusJsonParser.get_identifier_list({\"myid\": []}, \"myid\")\n self.assertEqual(ids, None)\n\n ids = ScopusJsonParser.get_identifier_list({\"myid\": [{\"$\": \"thing\"}]}, \"myid\")\n self.assertEqual(ids, [\"thing\"])\n\n def test_parse_json(self):\n \"\"\"Test the parser.\"\"\"\n\n harvest_datetime = pendulum.now(\"UTC\").isoformat()\n release_date = \"2018-01-01\"\n entry = ScopusJsonParser.parse_json(\n data=self.data,\n harvest_datetime=harvest_datetime,\n release_date=release_date,\n institution_ids=self.institution_ids,\n )\n self.assertEqual(entry[\"harvest_datetime\"], harvest_datetime)\n self.assertEqual(entry[\"release_date\"], release_date)\n self.assertEqual(entry[\"title\"], \"arttitle\")\n self.assertEqual(entry[\"identifier\"], \"scopusid\")\n self.assertEqual(entry[\"creator\"], \"firstauth\")\n self.assertEqual(entry[\"publication_name\"], \"pubname\")\n self.assertEqual(entry[\"cover_date\"], \"2010-12-01\")\n self.assertEqual(entry[\"doi\"][0], \"doi\")\n self.assertEqual(entry[\"eissn\"][0], \"eissn\")\n self.assertEqual(entry[\"issn\"][0], \"issn\")\n self.assertEqual(entry[\"isbn\"][0], \"isbn\")\n self.assertEqual(entry[\"aggregation_type\"], \"source\")\n self.assertEqual(entry[\"pubmed_id\"], \"med\")\n self.assertEqual(entry[\"pii\"], \"pii\")\n self.assertEqual(entry[\"eid\"], \"testid\")\n self.assertEqual(entry[\"subtype_description\"], \"typedesc\")\n self.assertEqual(entry[\"open_access\"], 1)\n self.assertEqual(entry[\"open_access_flag\"], False)\n self.assertEqual(entry[\"citedby_count\"], 345)\n self.assertEqual(entry[\"source_id\"], 1000)\n self.assertEqual(entry[\"orcid\"], \"orcid\")\n\n self.assertEqual(len(entry[\"affiliations\"]), 1)\n af = entry[\"affiliations\"][0]\n self.assertEqual(af[\"name\"], \"aname\")\n self.assertEqual(af[\"city\"], \"acity\")\n self.assertEqual(af[\"country\"], \"country\")\n self.assertEqual(af[\"id\"], \"id\")\n self.assertEqual(af[\"name_variant\"], \"variant\")\n\n self.assertEqual(entry[\"abstract\"], \"abstract\")\n self.assertEqual(entry[\"article_number\"], \"artno\")\n self.assertEqual(entry[\"fund_agency_ac\"], \"acr\")\n self.assertEqual(entry[\"fund_agency_id\"], \"no\")\n self.assertEqual(entry[\"fund_agency_name\"], \"sponsor\")\n\n words = entry[\"keywords\"]\n self.assertEqual(len(words), 1)\n self.assertEqual(words[0], \"words\")\n\n authors = entry[\"authors\"]\n self.assertEqual(len(authors), 1)\n au = authors[0]\n self.assertEqual(au[\"authid\"], \"id\")\n self.assertEqual(au[\"orcid\"], \"id\")\n self.assertEqual(au[\"full_name\"], \"name\")\n self.assertEqual(au[\"first_name\"], \"first\")\n self.assertEqual(au[\"last_name\"], \"last\")\n self.assertEqual(au[\"initials\"], \"mj\")\n self.assertEqual(au[\"afid\"], \"id\")\n\n self.assertEqual(len(entry[\"institution_ids\"]), 1)\n self.assertEqual(entry[\"institution_ids\"], self.institution_ids)\n\n\nclass TestScopusTelescope(ObservatoryTestCase):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.project_id = os.getenv(\"TEST_GCP_PROJECT_ID\")\n self.host = \"localhost\"\n self.api_port = 5000\n self.data_location = \"us\"\n self.org_name = \"Curtin University\"\n self.conn_id = \"scopus_curtin_university\"\n self.earliest_date = pendulum.datetime(2021, 1, 1)\n\n self.fixture_dir = test_fixtures_folder(\"scopus\")\n self.fixture_file = os.path.join(self.fixture_dir, \"test.json\")\n with open(self.fixture_file, \"r\") as f:\n self.results_str = f.read()\n self.results_len = 1\n\n def setup_connections(self, env):\n # Add Observatory API connection\n conn = Connection(conn_id=AirflowConns.OBSERVATORY_API, uri=f\"http://:password@{self.host}:{self.api_port}\")\n env.add_connection(conn)\n\n # Add login/pass connection\n conn = Connection(conn_id=self.conn_id, uri=f\"http://login:password@localhost\")\n env.add_connection(conn)\n\n def setup_api(self, env, extra=None):\n dt = pendulum.now(\"UTC\")\n\n if extra is None:\n extra = {\n \"airflow_connections\": [self.conn_id],\n \"institution_ids\": [\"123\"],\n \"earliest_date\": self.earliest_date.isoformat(),\n \"view\": \"STANDARD\",\n }\n\n name = \"Scopus Telescope\"\n telescope_type = orm.TelescopeType(name=name, type_id=ScopusTelescope.DAG_ID, created=dt, modified=dt)\n env.api_session.add(telescope_type)\n\n organisation = orm.Organisation(\n name=self.org_name,\n created=dt,\n modified=dt,\n gcp_project_id=self.project_id,\n gcp_download_bucket=env.download_bucket,\n gcp_transform_bucket=env.transform_bucket,\n )\n\n env.api_session.add(organisation)\n telescope = orm.Telescope(\n name=name,\n telescope_type=telescope_type,\n organisation=organisation,\n modified=dt,\n created=dt,\n extra=extra,\n )\n env.api_session.add(telescope)\n env.api_session.commit()\n\n def get_telescope(self, dataset_id):\n api = make_observatory_api()\n telescope_type = api.get_telescope_type(type_id=ScopusTelescope.DAG_ID)\n telescopes = api.get_telescopes(telescope_type_id=telescope_type.id, limit=1000)\n self.assertEqual(len(telescopes), 1)\n\n dag_id = make_dag_id(ScopusTelescope.DAG_ID, telescopes[0].organisation.name)\n airflow_conns = telescopes[0].extra.get(\"airflow_connections\")\n institution_ids = telescopes[0].extra.get(\"institution_ids\")\n earliest_date_str = telescopes[0].extra.get(\"earliest_date\")\n earliest_date = pendulum.parse(earliest_date_str)\n\n airflow_vars = [\n AirflowVars.DATA_PATH,\n AirflowVars.DATA_LOCATION,\n ]\n\n telescope = ScopusTelescope(\n dag_id=dag_id,\n dataset_id=dataset_id,\n airflow_conns=airflow_conns,\n airflow_vars=airflow_vars,\n institution_ids=institution_ids,\n earliest_date=earliest_date,\n )\n\n return telescope\n\n def test_ctor(self):\n self.assertRaises(\n AirflowException,\n ScopusTelescope,\n dag_id=\"dag\",\n dataset_id=\"dataset\",\n airflow_conns=[],\n airflow_vars=[],\n institution_ids=[],\n earliest_date=pendulum.now(\"UTC\"),\n )\n\n self.assertRaises(\n AirflowException,\n ScopusTelescope,\n dag_id=\"dag\",\n dataset_id=\"dataset\",\n airflow_conns=[\"conn\"],\n airflow_vars=[],\n institution_ids=[],\n earliest_date=pendulum.now(\"UTC\"),\n )\n\n def test_dag_structure(self):\n \"\"\"Test that the ScopusTelescope DAG has the correct structure.\n\n :return: None\n \"\"\"\n dag = ScopusTelescope(\n dag_id=\"dag\",\n airflow_conns=[\"conn\"],\n airflow_vars=[],\n institution_ids=[\"10\"],\n earliest_date=pendulum.now(\"UTC\"),\n view=\"standard\",\n ).make_dag()\n self.assert_dag_structure(\n {\n \"check_dependencies\": [\"download\"],\n \"download\": [\"upload_downloaded\"],\n \"upload_downloaded\": [\"transform\"],\n \"transform\": [\"upload_transformed\"],\n \"upload_transformed\": [\"bq_load\"],\n \"bq_load\": [\"cleanup\"],\n \"cleanup\": [],\n },\n dag,\n )\n\n def test_dag_load(self):\n \"\"\"Test that the DAG can be loaded from a DAG bag.\"\"\"\n\n dag_file = os.path.join(module_file_path(\"academic_observatory_workflows.dags\"), \"scopus_telescope.py\")\n\n env = ObservatoryEnvironment(self.project_id, self.data_location, api_host=self.host, api_port=self.api_port)\n\n with env.create():\n self.setup_connections(env)\n self.setup_api(env)\n\n dag_file = os.path.join(module_file_path(\"academic_observatory_workflows.dags\"), \"scopus_telescope.py\")\n dag_id = make_dag_id(ScopusTelescope.DAG_ID, self.org_name)\n self.assert_dag_load(dag_id, dag_file)\n\n def test_dag_load_missing_params(self):\n \"\"\"Test that the DAG can be loaded from a DAG bag.\"\"\"\n\n dag_file = os.path.join(module_file_path(\"academic_observatory_workflows.dags\"), \"scopus_telescope.py\")\n env = ObservatoryEnvironment(self.project_id, self.data_location, api_host=self.host, api_port=self.api_port)\n extra = {\n \"airflow_connections\": [self.conn_id],\n \"institution_ids\": [\"123\"],\n \"earliest_date\": self.earliest_date.isoformat(),\n }\n\n with env.create():\n self.setup_connections(env)\n self.setup_api(env, extra=extra)\n\n dag_file = os.path.join(module_file_path(\"academic_observatory_workflows.dags\"), \"scopus_telescope.py\")\n dag_id = make_dag_id(ScopusTelescope.DAG_ID, self.org_name)\n self.assertRaises(AssertionError, self.assert_dag_load, dag_id, dag_file)\n\n def test_telescope(self):\n env = ObservatoryEnvironment(self.project_id, self.data_location, api_host=self.host, api_port=self.api_port)\n\n with env.create():\n self.setup_connections(env)\n self.setup_api(env)\n dataset_id = env.add_dataset()\n\n execution_date = pendulum.datetime(2021, 1, 1)\n telescope = self.get_telescope(dataset_id)\n dag = telescope.make_dag()\n\n release_date = pendulum.datetime(2021, 2, 1)\n release = ScopusRelease(\n dag_id=make_dag_id(ScopusTelescope.DAG_ID, self.org_name),\n release_date=release_date,\n api_keys=[\"1\"],\n institution_ids=[\"123\"],\n view=\"standard\",\n earliest_date=pendulum.datetime(2021, 1, 1),\n )\n\n with env.create_dag_run(dag, execution_date):\n # check dependencies\n ti = env.run_task(telescope.check_dependencies.__name__)\n self.assertEqual(ti.state, State.SUCCESS)\n\n # download\n with patch(\n \"academic_observatory_workflows.workflows.scopus_telescope.ScopusUtility.make_query\"\n ) as m_search:\n m_search.return_value = self.results_str, self.results_len\n ti = env.run_task(telescope.download.__name__)\n self.assertEqual(ti.state, State.SUCCESS)\n self.assertEqual(len(release.download_files), 1)\n self.assertEqual(m_search.call_count, 1)\n\n # upload downloaded\n ti = env.run_task(telescope.upload_downloaded.__name__)\n self.assertEqual(ti.state, State.SUCCESS)\n self.assert_blob_integrity(\n env.download_bucket, blob_name(release.download_files[0]), release.download_files[0]\n )\n\n # transform\n ti = env.run_task(telescope.transform.__name__)\n self.assertEqual(ti.state, State.SUCCESS)\n\n # upload_transformed\n ti = env.run_task(telescope.upload_transformed.__name__)\n self.assertEqual(ti.state, State.SUCCESS)\n for file in release.transform_files:\n self.assert_blob_integrity(env.transform_bucket, blob_name(file), file)\n\n # bq_load\n ti = env.run_task(telescope.bq_load.__name__)\n self.assertEqual(ti.state, State.SUCCESS)\n\n table_id = (\n f\"{self.project_id}.{dataset_id}.\"\n f\"{bigquery_sharded_table_id(ScopusTelescope.DAG_ID, release.release_date)}\"\n )\n expected_rows = 1\n self.assert_table_integrity(table_id, expected_rows)\n\n # Sample some fields to check in the first row\n sql = f\"SELECT * FROM {self.project_id}.{dataset_id}.scopus20210201\"\n with patch(\"observatory.platform.utils.gc_utils.bq_query_bytes_daily_limit_check\"):\n records = list(run_bigquery_query(sql))\n self.assertEqual(records[0][\"aggregation_type\"], \"Journal\")\n self.assertEqual(records[0][\"source_id\"], 1)\n self.assertEqual(records[0][\"eid\"], \"somedoi\")\n self.assertEqual(records[0][\"pii\"], \"S00000\")\n self.assertEqual(records[0][\"identifier\"], \"SCOPUS_ID:000000\")\n self.assertEqual(records[0][\"doi\"], [\"10.0000/00\"])\n self.assertEqual(records[0][\"publication_name\"], \"Journal of Things\")\n self.assertEqual(records[0][\"institution_ids\"], [123])\n self.assertEqual(records[0][\"creator\"], \"Name F.\")\n self.assertEqual(records[0][\"article_number\"], \"1\")\n self.assertEqual(records[0][\"title\"], \"Article title\")\n self.assertEqual(records[0][\"issn\"], [\"00000000\"])\n self.assertEqual(records[0][\"subtype_description\"], \"Article\")\n self.assertEqual(records[0][\"citedby_count\"], 0)\n\n # cleanup\n download_folder, extract_folder, transform_folder = (\n release.download_folder,\n release.extract_folder,\n release.transform_folder,\n )\n env.run_task(telescope.cleanup.__name__)\n self.assertEqual(ti.state, State.SUCCESS)\n self.assert_cleanup(download_folder, extract_folder, transform_folder)\n","sub_path":"academic_observatory_workflows/workflows/tests/test_scopus_telescope.py","file_name":"test_scopus_telescope.py","file_ext":"py","file_size_in_byte":34177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"333440494","text":"import matplotlib.pyplot as plt\n\nwidth = 0.25\nlistx = ['c','c++','c#','java','python']\nlistx1 = [x - width/2 for x in range(len(listx))]\nlistx2 = [x + width/2 for x in range(len(listx))]\nlisty1 = [25,20,20,16,28]\nlisty2 = [20,8,18,16,22]\nplt.bar(listx1, listy1, width, label='男')\nplt.bar(listx2, listy2, width, label='女')\nplt.xticks(range(len(listx)), labels=listx)\nplt.legend()\nplt.title(\"資訊程式課程選修人數\")\nplt.xlabel(\"程式課程\")\nplt.ylabel(\"選修人數\")\n# 設定中文字型及負號正確顯示\nplt.rcParams[\"font.sans-serif\"] = \"Microsoft JhengHei\" # 將字體換成 Microsoft JhengHei\nplt.rcParams[\"axes.unicode_minus\"] = False\nplt.show()\n","sub_path":"_4.python/__code/Python自學聖經(第一版)/ch13/bar4.py","file_name":"bar4.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"562632268","text":"__author__ = 'Alex Hart'\nimport statistics\n\n#rated soaps\norange_menthol = {'name': 'orange_menthol', 'scents': {'orange': .6, 'menthol': .4}, 'rating': 2}\neucalyptus_mint = {'name': 'eucalyptus_mint', 'scents': {'eucalyptus': .5, 'mint': .5}, 'rating': 3.5}\narctic_wyrm = {'name': 'arctic_wyrm', 'scents': {'mint': .55, 'rosemary': .25, 'menthol': .2}, 'rating': 4}\nnight_music = {'name': 'night_music', 'scents': {'vanilla': .5, 'bergamot': .3, 'iris': .15, 'strawberry': .05}, 'rating': 4.5}\nlavanille = {'name': 'lavanille', 'scents': {'vanilla': .5, 'lavender': .3, 'cedar': .2}, 'rating': 4}\nblack_dragon = {'name': 'black_dragon', 'scents': {'vetiver': .35, 'orange': .35, 'cardamom': .2, 'anise': .05, 'musk': .05}, 'rating': 4}\n\n\nrated_soaps = [orange_menthol,eucalyptus_mint,arctic_wyrm,night_music,lavanille,black_dragon]\n\n#unrated soaps\ncolonia_di_agrumi = {'name': 'colonia_di_agrumi', 'scents': {'bergamot': .4, 'lavender': .3, 'cedar': .2, 'patchouli': .1}, 'rating': None}\nblack_dragon = {'name': 'black_dragon', 'scents': {'vetiver': .35, 'orange': .35, 'cardamom': .2, 'anise': .05, 'musk': .05}, 'rating': None}\nlavender_lizard = {'name': 'lavender_lizard', 'scents': {'lavender': .4, 'vanilla': .4, 'oakmoss': .05, 'pepper': .05}, 'rating': None}\nlavanille = {'name': 'lavanille', 'scents': {'vanilla': .5, 'lavender': .3, 'cedar': .2}, 'rating': None}\nnight_music = {'name': 'night_music', 'scents': {'vanilla': .5, 'bergamot': .3, 'iris': .15, 'strawberry': .05}, 'rating': None}\n\n\n\n\nunrated_soaps = [colonia_di_agrumi,black_dragon,lavender_lizard,lavanille,night_music]\n\n\ntotal_ratings = len(rated_soaps)\nmax_rating = 5.0\n\n\n#scents\nall_scents = []\n\nfor soap in rated_soaps:\n for key, value in soap['scents'].items():\n if key not in all_scents:\n all_scents.append(key)\n\nprint(all_scents)\n\n# determine scent scores\nscent_scores = {}\nfor scent in all_scents:\n rating = []\n for soap in rated_soaps:\n if scent in soap['scents'].keys():\n #print(\"{} is in {}\".format(scent, soap.get('name')))\n # (scent_percentage*user_rating)/max_rating\n soap_scent_score = (soap['scents'].get(scent)*soap.get('rating')/max_rating)\n rating.append(soap_scent_score)\n scent_score = float('{0:.2f}'.format(statistics.mean(rating)))\n scent_scores[scent] = scent_score\n print(\"scent score is for {} is {}\".format(scent,scent_score))\n\n\nprint(scent_scores)\n\n# compare scent scores to unrated soaps\n#soap_scents = []\n#for soap in unrated_soaps:\n# print(soap)\n# total_score = []\n# for key, value in soap['scents'].items():\n# #print(key,value)\n# # (scent_percentage*user_rating)/max_rating\n# if key in scent_scores.keys():\n# #scent_scores[key] = user preference\n# #soap[key] = what % soap has\n# #print(key,scent_scores[key])\n# #print(key,soap['scents'][key])\n# diff = abs(scent_scores[key]-soap['scents'][key])\n# total_score.append(diff*soap['scents'][key])\n# #print(\"total score is %s\" %total_score)\n# else:\n# #scent_scores[key] = user preference\n# #soap[key] = what % soap has\n# #print(\"{} is not part of profile. Assigning 0.0\".format(key))\n# #print(key,0.0)\n# #print(key,soap['scents'][key])\n# diff = abs(0.0-soap['scents'][key])\n# total_score.append(diff*soap['scents'][key])\n# #print(\"total score is %s\" %total_score)\n#\n# print(\"recommendation score for {} is {}\".format(soap['name'],statistics.mean(total_score)))\n\n# compare scent scores to unrated soaps (star rating)e\nsoap_scents = []\nfor soap in unrated_soaps:\n print(soap)\n total_score = []\n for key, value in soap['scents'].items():\n #print(key,value)\n # (scent_percentage*user_rating)/max_rating\n\n # scent_score * max_rating/scent_percentage\n if key in scent_scores.keys():\n #scent_scores[key] = user preference\n #soap[key] = what % soap has\n #print(key,scent_scores[key])\n #print(key,soap['scents'][key])\n score = (scent_scores.get(key)*max_rating)/soap['scents'][key]\n total_score.append(score)\n #print(\"total score is %s\" %total_score)\n else:\n #scent_scores[key] = user preference\n #soap[key] = what % soap has\n #print(\"{} is not part of profile. Assigning 0.0\".format(key))\n #print(key,0.0)\n #print(key,soap['scents'][key])\n score = (0.0*max_rating)/soap['scents'][key]\n total_score.append(score)\n #print(\"total score is %s\" %total_score)\n\n recommendation = float('{0:.2f}'.format(statistics.mean(total_score)))\n\n print(\"recommendation score for {} is {}\".format(soap['name'],recommendation))\n\n\n#for soap_scent in soap_scents:\n# print(soap_scent)\n\n","sub_path":"poc.py","file_name":"poc.py","file_ext":"py","file_size_in_byte":4918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"524815694","text":"import json\nimport os\nimport time\n\nfrom flask import Blueprint\nimport tool_db\nimport tool_excel\nfrom flask import request\nfrom werkzeug.utils import secure_filename\nfrom flask import send_from_directory\n\nservers = Blueprint(\"servers\", __name__)\n\n\n@servers.route('/index')\ndef index():\n return \"servers\"\n\n\n@servers.route('/mutidelete', methods=['get', 'post'])\ndef mutidelete():\n info = request.get_data()\n info = json.loads(info)\n for oneid in info:\n sql = 'delete from servers where id = %s'\n tool_db.updateByParameters(sql, (oneid,))\n return \"servers\"\n\n\n@servers.route('/delete_by_id')\ndef delete_by_id():\n id = int(request.args.get('id'))\n sql = 'delete from servers where id = %s'\n tool_db.updateByParameters(sql, (id,))\n return \"servers\"\n\n\n@servers.route('/insert_from_excel', methods=['get', 'post'])\ndef insert_from_excel():\n f = request.files.get('servers')\n ramname = int(time.time() * 1000)\n f.save('/tmp/{0}'.format(ramname))\n tool_excel.insertFromExcel('/tmp/{0}'.format(ramname))\n return \"success\"\n\n\n@servers.route('/getexcel')\ndef getexcel():\n curdir = os.path.dirname(os.path.realpath(__file__))\n return send_from_directory(curdir + \"/static/\", \"servers.xls\", as_attachment=True)\n\n\n@servers.route('/update', methods=['get', 'post'])\ndef update():\n info = request.get_data()\n info = json.loads(info)\n sql = 'replace into servers (id,name,ip,port,user) values(%s,%s,%s,%s,%s);'\n params = (info['id'], info['name'], info['ip'], info['port'], info['user'])\n tool_db.updateByParameters(sql, params)\n return \"success\"\n\n\n@servers.route('/insert', methods=['get', 'post'])\ndef insert():\n info = request.get_data()\n info = json.loads(info)\n sql = 'replace into servers (name,ip,port,user) values(%s,%s,%s,%s);'\n params = (info['name'], info['ip'], info['port'], info['user'])\n tool_db.updateByParameters(sql, params)\n return \"success\"\n\n\n@servers.route('/get_by_id')\ndef get_by_id():\n id = int(request.args.get('id'))\n sql = \"select * from servers where id = %s\"\n result = tool_db.selectByParameters(sql, params=(id,))\n return json.dumps(result)\n\n\n@servers.route('/get_by_page', methods=['get', 'post'])\ndef get_by_page():\n info = request.get_data()\n info = json.loads(info)\n pagenow = info['pagenow']\n pagesize = info['pagesize']\n search = info['search']\n search = \"%{0}%\".format(search)\n sql = 'select * from servers where name like %s or ip like %s limit %s,%s'\n params = (search, search, (pagenow - 1) * pagesize, pagesize)\n result = tool_db.selectByParameters(sql, params=params)\n return json.dumps(result)\n\n\n@servers.route('/getall')\ndef getall():\n sql = \"select * from servers\"\n result = tool_db.selectByParameters(sql)\n return json.dumps(result)\n","sub_path":"sersers.py","file_name":"sersers.py","file_ext":"py","file_size_in_byte":2808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"274039072","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom sklearn.metrics import r2_score, mean_squared_error\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.feature_selection import SelectKBest, f_regression, RFE\n\n################################################################################################\ndef sse_compare(sse1, sse2, model1, model2 = 'baseline'):\n '''\n sse1 must be for model 1\n sse2, must be for model 2 (which is by default the baseline)\n model1 = string name of the model you're comparing\n This function compares two SSEs. and outputs which one performed better\n '''\n \n if sse1 > sse2:\n print(f'{model1} is not better than {model2}.')\n elif sse1 < sse2:\n print(f'{model1} is better than {model2}. Difference: {sse2 - sse1:.2f}')\n else:\n print(f'{model1} performs the same as {model2}')\n\n################################################################################################\ndef plot_residuals(df, x_list, palette = \"tab10\"):\n '''\n This function takes in a dataframe and a list of all the risiduals you would like to plot (that means the names of the columns)\n '''\n color_list= list(sns.color_palette(palette))\n fig, ax = plt.subplots(figsize=(10, 5))\n for x, c in zip(x_list, color_list):\n sns.histplot(x = x, data = df, kde=True, ax = ax, alpha = 0.5, color = c, legend=True, lw = .1)\n \n plt.legend(x_list) \n plt.show()\n\n################################################################################################\n\ndef hip_to_be_square(y, yhat, print_out = False):\n '''\n This function takes the actuals (y), \n and the predictions (yhat).\n optional arguement print_out. bool. when set to True will print out summary\n It prints out the Sum of SE, Mean SE, Root Mean SE, Explained SS, and Total SS. \n Returns them in 5 variables. In order listed above\n ex: sse, mse, rmse, ess, tss = hip_to_be_square(df, 'actuals', 'yhat', print_out = True)\n '''\n # calculate Sum of Squared Error\n sse = ((y - yhat) ** 2).sum()\n \n # calculate Mean of Squared Error\n mse = sse / y.shape[0]\n \n # calculate Root Mean of Squared Error\n rmse = mse ** .5\n \n # calculate Explained Sum of Squares \n ess = ((yhat - y.mean()) ** 2).sum()\n \n # calculate Total Sum of Squares\n tss = ((y - y.mean()) ** 2).sum()\n \n if print_out == True:\n \n print(f'''\n The Sum of Squared Error: {sse:.2f}\n The Mean Squared Error: {mse:.2f}\n The Root Mean Squared error: {rmse:.2f}\n -----------------------------------\n The Mean Explained Sum of Squares: {ess:.2f}\n The Total Sum of Squares: {tss:.2f}\n ''')\n return sse, mse, rmse, ess, tss\n\n################################################################################################\ndef baseline_mean_errors(y):\n '''\n This function takes in the actuals (y). Computes the baseline model. \n Returns the SSE, MSE, and RMSE for the baseline\n '''\n baseline = y.mean()\n \n # calculate Sum of Squared Error\n sse = ((y - baseline) ** 2).sum()\n \n # calculate Mean of Squared Error\n mse = sse / y.shape[0]\n \n # calculate Root Mean of Squared Error\n rmse = mse ** .5\n \n return sse, mse, rmse\n\n################################################################################################\n\ndef better_than_baseline(y, yhat):\n '''\n This function takes in actuals (y) and predictions (yhat) \n and returns true if the model performs better than baseline. \n '''\n # calculate values for baseline\n sse_b, mse_b, rmse_b = baseline_mean_errors(y)\n \n # calculate values for model\n sse, mse, rmse_model, ess, tss = hip_to_be_square(y, yhat, print_out=False)\n \n # compare rmse from baseline and model\n \n # If Root Mean Square Error is smaller for the model than for the baseline, model is better, return True\n if rmse_model < rmse_b:\n return True\n # if Root mean Square error for the model is larger or the same as the baseline, return False \n else:\n return False\n\n################################################################################################\n\ndef select_kbest(X, y, k, score_func=f_regression):\n '''\n takes in the predictors (X), the target (y), and the number of features to select (k) \n and returns the names (in a list) of the top k selected features based on the SelectKBest class\n Optional arg: score_func. Default is f_regression. other options ex: f_classif \n '''\n # create selector\n f_selector = SelectKBest(score_func=score_func, k=k)\n \n #fit to X and y\n f_selector.fit(X, y)\n \n # return the list of the column names that are the top k selected features\n return list(X.columns[f_selector.get_support()])\n\n\n################################################################################################\n\ndef rfe(X, y, n, estimator=LinearRegression()):\n '''\n takes in the predictors (X), the target (y), and the number of features to select (n) \n and returns the names (in a list) of the top k selected features based on the Recursive Feature Elimination class\n Optional arg: estimator. Default is LinearRegression()\n '''\n # use the estimator model to create estimator\n est = estimator\n \n # set up with estimator and n_features\n rfe = RFE(estimator=est, n_features_to_select=n)\n \n # fit to X and y\n rfe.fit(X, y)\n \n # return the list of the columns \n \n return list(X.columns[rfe.support_])\n\n################################################################################################\n\n# maybe in the future add creating the preditions and the residuals if none were entered \n# have to import sklearn stuff\n\ndef plot_the_dots(actuals, predictions, residuals):\n '''\n This function takes in the actuals (i.e. df.actuals), predictions, and residuals and outputs two graphs.\n One to see the regression line and the actuals/predictions\n One to see the actuals vs the residuals.\n '''\n \n r_sq = r2_score(actuals, predictions)\n rmse = mean_squared_error(actuals, predictions, squared = False)\n \n text_loc = actuals.max() - 2\n \n # plots actual vs predicted\n plt.figure(figsize=(16, 7))\n ax = plt.subplot(1, 2, 1)\n ax.scatter(actuals, predictions, label='predicted')\n ax.set(title='Actual vs Predicted Value', ylabel='Prediction', xlabel='Actual')\n ax.plot(actuals, actuals, ls=':', c='gray')\n ax.text(text_loc, 1, f'R^2: {r_sq:.2f}', fontsize='large')\n \n #put r^2 value on graph\n # and rmse and rmse of baseline\n \n ax = plt.subplot(1, 2, 2)\n ax.scatter(actuals, residuals)\n ax.set(title = 'Actual vs Residual',ylabel='Residual', xlabel='Actual')\n ax.hlines(0, *ax.get_xlim(), ls=':', color='gray')\n ax.text(text_loc, -3, f'RMSE: {rmse:.2f}')\n\n#####################################Compare RMSE function##########################################\n\ndef compare_rmse(pred_actuals):\n '''\n This function takes in a list of tuples ex [(df.pred1, df.actuals), (df.pred2, y_validate)]\n unpacks the tuple, and prints out the Root Mean Squared Error for each \n '''\n for prediction, actual in pred_actuals:\n rmse = mean_squared_error(prediction, actual, squared = False)\n print(f'RMSE for {prediction.name}: {rmse} ')","sub_path":"evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":7469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"368064401","text":"#!/usr/bin/env python\n\n\"\"\"\nCopyright 2018 Google LLC\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n https://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nWrappers around subprocess which simplify calling external commands from Python scripts.\n\"\"\"\n\nimport subprocess\nimport utils\n\ndef call(command, info=None):\n \"\"\"\n Calls a command through shell\n \"\"\"\n output, success = call_get_out(command, info)\n utils.printf(\"Success: {0}, output: {1}\".format(success, output))\n\ndef call_get_out(command, info=None):\n \"\"\"\n Calls a command through shell and returns a tuple which:\n * first element is a list of output lines with empty lines removed\n * second element is a flag indicating whether the command succeeded or not\n \"\"\"\n if info is not None:\n utils.printf(info)\n\n utils.printf(\"Executing $ {0}\".format(command))\n p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)\n output = filter(None, p.communicate()[0].split(\"\\n\"))\n return (output, p.returncode == 0)\n","sub_path":"hack/utils/command.py","file_name":"command.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"138911068","text":"import collections\nimport sys\n\nsys.stdin=open('cab.txt','r')\ndx=[1,-1,0,0]\ndy=[0,0,1,-1]\ndef bfs(n):\n que=collections.deque()\n que.append(n)\n while que:\n t=que.popleft()\n ax=t//1000000\n ay=t%1000000\n for i in range(4):\n nx=ax+dx[i]\n ny=ay+dy[i]\n if 0<=nx 0:\n stats.ships_left -= 1\n sb.prep_ships()\n aliens.empty()\n bullets.empty()\n create_fleet(ai_settings, screen, ship, aliens)\n ship.center_ship()\n sleep(0.5)\n else:\n stats.game_active = False\n pygame.mouse.set_visible(True)\n\ndef check_aliens_bottom(ai_settings, stats, screen,sb, ship, aliens, bullets):\n screen_rect = screen.get_rect()\n for alien in aliens.sprites():\n if alien.rect.bottom >= screen_rect.bottom:\n ship_hit(ai_settings, stats, screen, sb, ship, aliens, bullets)\n break\n\ndef update_aliens(ai_settings, stats, screen,sb,ship, aliens, bullets):\n check_fleet_edges(ai_settings, aliens)\n for item in aliens:\n item.update()\n if pygame.sprite.spritecollideany(ship,aliens):\n ship_hit(ai_settings, stats, screen,sb, ship, aliens, bullets)\n check_aliens_bottom(ai_settings, stats, screen, sb, ship, aliens, bullets)\n\ndef check_down_drops(ai_settings, drops):\n for drop in drops.sprites():\n if drop.check_edges():\n change_hieght(drop)\n\ndef change_hieght(drop):\n drop.rect.y = 0\n\ndef update_drops(ai_settings, drops):\n check_down_drops(ai_settings, drops)\n for item in drops:\n item.update()\n\ndef check_update_bottom(ai_settings, stats, screen, ship, aliens, bullets):\n screen_rect = screen.get_rect()\n for alien in aliens.sprites():\n if alien.rect.bottom >= screen_rect.bottom:\n ship_hit(ai_settings,stats, screen, ship, aliens, bullets)\n break\n\n\ndef check_high_score(stats, sb):\n if stats.score > stats.high_score:\n stats.high_score = stats.score\n sb.prep_high_score()","sub_path":"main/game_functions.py","file_name":"game_functions.py","file_ext":"py","file_size_in_byte":8752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"295964819","text":"#!/usr/bin/env python2.4\n\n\n\"\"\"\nThis was a simply ustility to ouput the number of visible access points over time.\nCould be done a bit better with some kernel rounding, so if an AP seen at t_1 and t_3, it\nshould be shown for t_2 as well.\n\"\"\"\n\n\ndef loadDataFile(name):\n f=open('./AccessPoints2.data','w')\n lines = open(name).read().split('\\n')\n currentTime,count,baseTime=-1,0,0\n for line in lines:\n if(len(line)<3):\n continue\n items = line.split(';')\n mac,ESSID,dist,t=items[0],items[1],items[2],items[3]\n t=int(t)\n if(currentTime==-1):\n baseTime = t\n if(t>currentTime):\n if(count>0):\n f.write(str(currentTime-baseTime)+'\\t')\n f.write(str(count)+'\\n')\n currentTime=t\n count=0\n else:\n count+=1\n\n#loadDataFile('./traces/1171917458.out')\nloadDataFile('./traces/1171990062.out')\n","sub_path":"stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"288014104","text":"# use variable blueDuration for duration from blue\n#use variable userConfigDir for user's .blue dir\n#use variable blueLibDir for blue's lib directory\n#use variable blueProjectDir for this project's directory\n#use variable score at end of script to bring score back into blue\nimport composition\nimport composition.itemstream as ci\nimport composition.score as cs\n\n\n#IdMusic1.wav \n# ['h',.769], ['h',1.95], ['w'], 3.175], ['h',5.54], ['h'], 6.67], ['w'], 8.0]\n\nrhythms = ci.itemstream(sum([\n ['e.', 'e.', 'e', 'q.', 'e', 'q.', 'e', 'h'],\n ['s', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's',\n 's', 's', 's'],\n ],\n []\n),\n 'sequence', tempo=120)\nrhythms.notetype = 'rhythm'\namps = ci.itemstream([1])\n\n#pitches = ci.itemstream(['c3','e',['c','e','g'],'c4','e',['c','e','g']])\npitches = ci.itemstream(sum([\n ['c4', 'c', 'c', 'd', 'c5', 'c', 'c', 'd'],\n ['c3', 'e', ['c', 'e', 'g'], 'c4', 'e', ['c', 'e', 'g']],\n [['c', 'e', 'g'], ['c', 'e', 'g'], ['c', 'd', 'e'], ['e', 'f', 'g']],\n ], []))\npitches.streammode = 'heap'\npitches.notetype = 'pitch'\ns = cs.score(rhythms, [amps, pitches], note_limit=(len(pitches.values) * 4))\ns.gen_lines = [';sine\\n', 'f 1 0 16384 10 1\\n', ';saw', 'f 2 0 256 7 0 128 1 0 -1 128 0\\n', ';pulse\\n',\n 'f 3 0 256 7 1 128 1 0 -1 128 -1\\n']\ns.durstream = ci.itemstream([.1])\ns.instr = 1\n#s.generate_score(\"/Users/benmca/Documents/src/sandbox/python/test.sco\")\n#s.generate_score()\ns.generate_notes()\n\noutput = \"\"\nfor x in range(len(s.gen_lines)):\n output += s.gen_lines[x]\nfor x in range(len(s.notes)):\n output += s.notes[x]\n\nrhythms = ci.itemstream(['e'], 'sequence', tempo=120)\n#rhythms = composition.itemstream.itemstream(['e.','e.','e'],'heap', tempo=240)\nrhythms.notetype = 'rhythm'\ns.rhythmstream = rhythms\npitches = ci.itemstream(sum([\n ['fs6'],\n ], []))\npitches.notetype = 'pitch'\ns.streams[1] = pitches\ns.note_limit = 64\n#reset time\ns.starttime = 0.0\ns.curtime = s.starttime\n#for x in s.notes:\n#print(x)\ns.instr = 1\ns.generate_notes()\nfor x in range(len(s.notes)):\n output += s.notes[x]\n\nprint(output)\n\ns.generate_score(\"test.sco\")\n#score = s.generate_score_string()\n","sub_path":"_archive/2014/doodle.py","file_name":"doodle.py","file_ext":"py","file_size_in_byte":2474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"358640007","text":"# coding: utf-8\n#\n# Copyright 2017 The Oppia Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS-IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Services for questions data model.\"\"\"\n\nimport logging\n\nfrom core.domain import question_domain\nfrom core.platform import models\nimport feconf\n\n(question_models,) = models.Registry.import_models([models.NAMES.question])\n\n# This takes additional 'title' parameters.\nCMD_CREATE_NEW = 'create_new'\n\n\ndef _create_question(committer_id, question, commit_message):\n \"\"\"Creates a new question.\n\n Args:\n committer_id: str. ID of the committer.\n question: Question. question domain object.\n commit_message: str. A description of changes made to the question.\n \"\"\"\n model = question_models.QuestionModel.create(\n title=question.title,\n question_data=question.question_data,\n question_data_schema_version=question.question_data_schema_version,\n collection_id=question.collection_id,\n language_code=question.language_code,\n )\n\n model.commit(committer_id, commit_message, [{\n 'cmd': CMD_CREATE_NEW,\n 'title': question.title\n }])\n return model\n\n\ndef add_question(committer_id, question):\n \"\"\"Saves a new question.\n\n Args:\n committer_id: str. ID of the committer.\n question: Question. Question to be saved.\n \"\"\"\n commit_message = (\n 'New question created with title \\'%s\\'.' % question.title)\n question_model = _create_question(committer_id, question, commit_message)\n\n return question_model\n\n\ndef delete_question(committer_id, question_id, force_deletion=False):\n \"\"\"Deletes the question with the given question_id.\n\n Args:\n committer_id: str. ID of the committer.\n question_id: str. ID of the question.\n force_deletion: bool. If true, the question and its history are fully\n deleted and are unrecoverable. Otherwise, the question and all\n its history are marked as deleted, but the corresponding models are\n still retained in the datastore. This last option is the preferred\n one.\n \"\"\"\n question_model = question_models.QuestionModel.get(question_id)\n question_model.delete(\n committer_id, feconf.COMMIT_MESSAGE_QUESTION_DELETED,\n force_deletion=force_deletion)\n\n\ndef get_question_from_model(question_model):\n \"\"\"Returns domain object repersenting the given question model.\n\n Args:\n question_model: QuestionModel. The question model loaded from the\n datastore.\n\n Returns:\n Question. The domain object representing the question model.\n \"\"\"\n return question_domain.Question(\n question_model.id, question_model.title, question_model.question_data,\n question_model.question_data_schema_version,\n question_model.collection_id, question_model.language_code)\n\n\ndef get_question_by_id(question_id):\n \"\"\"Returns a domain object representing a question.\n\n Args:\n question_id: str. ID of the question.\n\n Returns:\n Question or None. The domain object representing a question with the\n given id, or None if it does not exist.\n \"\"\"\n question_model = question_models.QuestionModel.get(question_id)\n if question_model:\n question = get_question_from_model(question_model)\n return question\n else:\n return None\n\n\ndef apply_change_list(question_id, change_list):\n \"\"\"Applies a changelist to a pristine question and returns the result.\n\n Args:\n question_id: str. ID of the given question.\n change_list: list(QuestionChange). A change list to be applied to the\n given question. Each entry in change_list is a QuestionChange\n object.\n\n Returns:\n Question. The resulting question domain object.\n \"\"\"\n question = get_question_by_id(question_id)\n try:\n for change in change_list:\n if change.cmd == question_domain.CMD_UPDATE_QUESTION_PROPERTY:\n if (change.property_name ==\n question_domain.QUESTION_PROPERTY_TITLE):\n question.update_title(change.new_value)\n elif (change.property_name ==\n question_domain.QUESTION_PROPERTY_LANGUAGE_CODE):\n question.update_language_code(change.new_value)\n elif (change.cmd ==\n question_domain.QUESTION_PROPERTY_QUESTION_DATA):\n question.update_question_data(change.new_value)\n return question\n\n except Exception as e:\n logging.error(\n '%s %s %s %s' % (\n e.__class__.__name__, e, question_id, change_list)\n )\n raise\n\n\ndef _save_question(committer_id, question, change_list, commit_message):\n \"\"\"Validates a question and commits it to persistent storage.\n\n Args:\n committer_id: str. The id of the user who is performing the update\n action.\n question: Question. The domain object representing a question.\n change_list: list(QuestionChange). A list of QuestionChange objects.\n These changes are applied in sequence to produce the resulting\n question.\n commit_message: str or None. A description of changes made to the\n question.\n\n Raises:\n Exception: Received an invalid change list.\n \"\"\"\n if not change_list:\n raise Exception(\n 'Unexpected error: received an invalid change list when trying to '\n 'save question %s: %s' % (question.id, change_list))\n\n question.validate()\n\n question_model = question_models.QuestionModel.get(question.question_id)\n question_model.title = question.title\n question_model.question_data = question.question_data\n question_model.question_data_schema_version = (\n question.question_data_schema_version)\n question_model.collection_id = question.collection_id\n question_model.language_code = question.language_code\n change_list_dict = [change.to_dict() for change in change_list]\n question_model.commit(committer_id, commit_message, change_list_dict)\n\n\ndef update_question(committer_id, question_id, change_list, commit_message):\n \"\"\"Updates a question. Commits changes.\n\n Args:\n committer_id: str. The id of the user who is performing the update\n action.\n question_id: str. The question ID.\n change_list: list(QuestionChange). A list of QuestionChange objects.\n These changes are applied in sequence to produce the resulting\n question.\n commit_message: str or None. A description of changes made to the\n question.\n \"\"\"\n question = apply_change_list(question_id, change_list)\n _save_question(committer_id, question, change_list, commit_message)\n","sub_path":"core/domain/question_services.py","file_name":"question_services.py","file_ext":"py","file_size_in_byte":7282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"444253540","text":"from datetime import datetime\nfrom django.contrib.auth.models import User\nfrom django.db import models\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib.contenttypes import generic\nfrom django.conf import settings\nfrom django.db.utils import DatabaseError\n\n\ntry:\n TIMELINE_MODELS = settings.TIMELINE_MODELS\nexcept AttributeError:\n TIMELINE_MODELS = []\n\n\n\nclass Timeline(models.Model):\n time = models.DateTimeField(db_index=True, auto_now_add=True)\n day = models.DateField(db_index=True, auto_now_add=True) # for grouping by day\n is_created = models.BooleanField()\n content_type = models.ForeignKey(ContentType, db_index=True)\n object_id = models.IntegerField()\n object = generic.GenericForeignKey()\n user = models.ForeignKey(User, blank=True, null=True)\n\n def __unicode__(self):\n return self.object\n\n def get_absolute_url(self):\n if hasattr(self.object, 'get_absolute_url'):\n return self.object.get_absolute_url()\n \n class Meta:\n ordering = ('-time',)\n\n\ndef mark_timeline(instance, created=None, **kwargs):\n ctype = ContentType.objects.get_for_model(instance)\n if '.'.join(ctype.natural_key()) in TIMELINE_MODELS:\n user = None\n if isinstance(instance, User):\n user = instance\n else:\n # see if there is a FK to User\n for field_name in instance._meta.get_all_field_names():\n field = instance._meta.get_field_by_name(field_name)[0]\n if hasattr(field, 'rel') and hasattr(field.rel, 'to') and field.rel.to == User:\n user = getattr(instance, field_name)\n break\n Timeline.objects.create(is_created=created, user=user, object_id=instance.id,\n content_type=ContentType.objects.get_for_model(instance))\n\nmodels.signals.post_save.connect(mark_timeline)\n\ndef remove_deleted(instance, **kwargs):\n if isinstance(instance.pk, int): \n Timeline.objects.filter(content_type=ContentType.objects.get_for_model(instance),\n object_id=instance.pk).delete()\n\nmodels.signals.pre_delete.connect(remove_deleted)\n","sub_path":"timeline/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"116353837","text":"import json\n\nimport requests\n\n\ndef test_json_request():\n data = {'age': 42., 'workclass': 'Private', 'education': 'Doctorate', 'education_num': 16.,\n 'marital_status': 'Married-civ-spouse', 'occupation': 'Prof-specialty', 'relationship': 'Husband',\n 'capital_gain': 0., 'capital_loss': 0., 'hours_per_week': 45.}\n\n response = requests.post(\"http://localhost:8080/invocations\",\n data=json.dumps(data),\n headers={'Content-type': 'application/json',\n 'Accept': 'application/json'})\n\n serialized_output = response.content\n\n prediction_result = json.loads(serialized_output)\n\n classes = prediction_result['result']['classifications'][0]['classes']\n assert len(classes) == 2\n assert classes[0].keys() == [u'score', u'label']\n","sub_path":"test/integ/container_tests/wide_deep_prediction.py","file_name":"wide_deep_prediction.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"407313921","text":"import webbrowser\nimport sys\n\nsearchEngines = [\"google\", \"yahoo\", \"bing\", \"duckduckgo\"]\nquestion1 = \"What search engine do you want to use?\"\nquestion2 = \"You can choose between Google, Yahoo, Bing and DuckDuckGo.\"\nengine_url = \"\"\n\n\ndef search():\n while True:\n while True:\n print(question1)\n print(question2)\n engine_choice = input(\"> \").lower()\n if engine_choice in searchEngines:\n print(\"\\nChoice accepted...\")\n global engine_url\n if engine_choice.lower() == \"google\":\n engine_url = \"https://www.google.nl/?gws_rd=ssl#q=\"\n break\n elif engine_choice.lower() == \"yahoo\":\n engine_url = \"https://search.yahoo.com/search;_ylc=X3oDMTFiN25laTRvBF9TAzIwMjM1MzgwNzUEaXRjAzEEc2VjA3NyY2hfcWEEc2xrA3NyY2h3ZWI-?p=\"\n break\n elif engine_choice.lower() == \"bing\":\n engine_url = \"https://www.bing.com/search?q=\"\n break\n elif engine_choice.lower() == \"duckduckgo\":\n engine_url = \"https://duckduckgo.com/?q=\"\n break\n else:\n print(\"Error... Please retry.\\n\")\n while True:\n print(\"\\nWhat do you want to search the web for?\")\n web_request = input(\"> \").replace(\" \", \"+\")\n search_url = engine_url + web_request\n print(\"\\nAccessing the web with the following URL:\\n\" + search_url + \"\\n\")\n webbrowser.open(search_url)\n while True:\n print(\"Do you want to search the web for something else? (Y/N)\")\n again = input(\"> \")\n if again.lower() == \"yes\" or again.lower() == \"y\":\n break\n elif again.lower() == \"no\" or again.lower() == \"n\":\n while True:\n print(\"Are you sure? The program will close if you are. (Y/N)\")\n sure = input(\"> \")\n if sure.lower() == \"yes\" or sure.lower() == \"y\":\n sys.exit()\n elif sure.lower() == \"no\" or sure.lower() == \"n\":\n break\n else:\n print(\"Error... Please retry.\\n\")\n else:\n print(\"Error... Please retry.\\n\")\n\nif __name__ == '__main__':\n search()\n","sub_path":"search_v2.0.py","file_name":"search_v2.0.py","file_ext":"py","file_size_in_byte":2476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"641925905","text":"\"\"\"\nForumBlock can render and process ForumIdevices as XHTML\n\"\"\"\nimport logging\nfrom exe.webui.block import Block\nfrom exe.webui import common\nfrom forumelement import DiscussionElement, ForumElement\nfrom forumidevice import Forum, Discussion\nfrom exe.engine.translate import lateTranslate\nlog = logging.getLogger(__name__)\nclass ForumBlock(Block):\n \"\"\"\n ForumBlock can render and process ForumIdevices as XHTML\n \"\"\"\n def __init__(self, parent, idevice):\n \"\"\"\n Initialize a new Block object\n \"\"\"\n Block.__init__(self, parent, idevice)\n self.forumElement = ForumElement(idevice)\n self.discussionElement = DiscussionElement(idevice)\n self.message = self.idevice.message\n def process(self, request):\n \"\"\"\n Process the request arguments from the web server\n \"\"\"\n Block.process(self, request)\n self._message = ''\n self.forumElement.process(request)\n if ((\"action\" in request.args and \n request.args[\"action\"][0] == \"changeForum\") and (\"forumSelect\" + \\\n self.id in request.args)):\n self.idevice.edit = True\n self.idevice.noForum = False\n value = request.args[\"object\"][0]\n if value == \"\":\n self.idevice.noForum = True\n elif value == \"newForum\":\n forum = Forum()\n self.idevice.forum = forum\n self.idevice.isNewForum = True\n else:\n for forum in self.idevice.forumsCache.getForums():\n if forum.forumName == value:\n self.idevice.forum = forum\n break\n if (\"action\" in request.args and \n request.args[\"action\"][0] == \"changeTopic\" and \"topicSelect\" +\n self.id in request.args and not self.idevice.noForum):\n self.idevice.edit = True\n self.idevice.isNewTopic = False\n value = request.args[\"object\"][0]\n if value == \"none\":\n pass\n elif value == \"newTopic\":\n newTopic = Discussion()\n self.idevice.discussion = newTopic\n self.idevice.discussion.isNone = False\n self.idevice.isNewTopic = True\n else:\n for topic in self.idevice.forum.discussions:\n if topic.topic == value:\n break\n self.idevice.discussion = topic\n self.idevice.discussion.isAdded = False\n if (\"action\" in request.args and \n request.args[\"action\"][0] == \"changeLms\" \n and not self.idevice.noForum and \"lmsSelect\" + \\\n self.id in request.args):\n self.idevice.edit = True\n self.idevice.forum.lms.lms = request.args[\"object\"][0] \n if ((\"action\" in request.args and request.args[\"action\"][0] == \"done\" \\\n or not self.idevice.edit) and \"forumSelect\" + \\\n self.id in request.args):\n if self.idevice.noForum: \n self._message = x_(\"Please select a forum.\\n\")\n self.idevice.edit = True\n else:\n if self.idevice.forum.forumName == \"\":\n self._message = \\\n x_(\"Please enter a name for the forum\\n\")\n self.idevice.edit = True\n elif self.idevice.isNewForum:\n for forum in self.idevice.forumsCache.getForums():\n if forum.forumName == self.idevice.forum.forumName:\n self._message = x_(\"duplicate forum name.\\n\")\n self.idevice.edit = True\n break\n if self.idevice.forum.lms.lms == \"\":\n self._message = x_(\"Please select LMS.\\n\")\n self.idevice.edit = True\n if self.idevice.isNewTopic: \n if self.idevice.discussion.topic == \"\":\n self._message = \\\n x_(\"Please enter a discussion topic name.\\n\")\n self.idevice.edit = True\n for topic in self.idevice.forum.discussions:\n if topic.topic == self.idevice.discussion.topic:\n self._message = x_(\"duplicate topic name.\")\n self.idevice.edit = True\n break\n if (not self.idevice.edit and not self.idevice.discussion.isNone\n and not self.idevice.discussion.isAdded):\n discussion = self.idevice.discussion\n self.idevice.forum.addDiscussion(discussion)\n discussion.isAdded = True\n self.idevice.isNewTopic = False\n if not self.idevice.edit and not self.idevice.isAdded:\n self.idevice.forumsCache.addForum(self.idevice.forum)\n self.idevice.isNewForum = False\n self.idevice.isAdded = True\n self.idevice.message = self.message\n message = lateTranslate('message') \n def renderEdit(self, style):\n \"\"\"\n Returns an XHTML string with the form element for editing this block\n \"\"\"\n html = self.forumElement.renderEdit()\n html += u\"

\" + self.renderEditButtons() + \"

\"\n return html\n def renderPreview(self, style):\n \"\"\"\n Returns an XHTML string for previewing this block\n \"\"\"\n html = u'
\\n'\n html += u'\"\"\\n'\n html += u''\n html += self.idevice.title+'\\n'\n html += u'
\\n'\n html += self.forumElement.renderPreview()\n html += self.renderViewButtons()\n html += u\"
\"\n return html\n def renderView(self, style):\n \"\"\"\n Returns an XHTML string for viewing this block\n \"\"\"\n html = u'
\\n'\n html += u'\"\"\\n'\n html += u''\n html += self.idevice.title+'\\n'\n html += u'
\\n'\n html += self.forumElement.renderView()\n html += u\"
\"\n return html\ndef register():\n \"\"\"Register this block with the BlockFactory\"\"\"\n from forumidevice import ForumIdevice\n from exe.webui.blockfactory import g_blockFactory\n g_blockFactory.registerBlockType(ForumBlock, ForumIdevice) \n","sub_path":"eXe/rev1889-1952/left-trunk-1952/exe/idevices/forumblock.py","file_name":"forumblock.py","file_ext":"py","file_size_in_byte":6969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"392894189","text":"#!/usr/bin/env python -W ignore::DeprecationWarning\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport math\nimport tensorflow as tf #Need tensorflow v1 since v2.0 does not have tf.contrib (even in tf.compat.v1)\nimport numpy as np\n\nfrom datasets import dataset_factory\nfrom nets import nets_factory\nfrom preprocessing import preprocessing_factory\n\nfrom tensorflow.python.summary import summary\nimport time\nimport sys\nif not sys.warnoptions:\n import warnings\n warnings.simplefilter(\"ignore\")\n\ntf.logging.set_verbosity(tf.logging.ERROR)\n\n##############################################################\n# LoadModel Class # To make this applicable to any frozen_model.pb file, need to find input and ouput placeholders\n##############################################################\nclass LoadResNet50(object):\n\n def __init__(self, model_filepath):\n\n # The file path of model\n self.model_filepath = model_filepath\n # Initialize the model\n #self.load_graph(model_filepath = self.model_filepath)\n \n def load_graph(self):\n '''\n Load trained model.\n '''\n print('Loading model...')\n model_filepath = self.model_filepath\n self.graph = tf.Graph()\n\n with tf.gfile.GFile(model_filepath, 'rb') as f:\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(f.read())\n\n print('Check out the input placeholders:')\n nodes = [n.name + ' => ' + n.op for n in graph_def.node if n.op in ('Placeholder')]\n for node in nodes:\n print(node)\n \n print('Check out the output nodes')\n out_nodes = [n.name + '=>' + n.op for n in graph_def.node if n.op in ( 'Softmax')]\n for node in out_nodes:\n print(node)\n\n \n print('Model loading complete!')\n\n '''\n # Get layer names\n layers = [op.name for op in self.graph.get_operations()]\n for layer in layers:\n print(layer)\n\n\n # Check out the weights of the nodes\n weight_nodes = [n for n in graph_def.node if n.op == 'Const']\n for n in weight_nodes:\n print(\"Name of the node - %s\" % n.name)\n # print(\"Value - \" )\n # print(tensor_util.MakeNdarray(n.attr['value'].tensor))\n '''\n # In this version, tf.InteractiveSession and tf.Session could be used interchangeably. \n # self.sess = tf.InteractiveSession(graph = self.graph)\n #self.sess = tf.Session(graph = self.graph)\n \n #def test(data):\n # output_tensor = self.graph.get_tensor_by_name(\"import/softmax_tensor:0\")\n # def get_output():\n # with tf.Session(graph=self.graph) as sess: \n # coord = tf.train.Coordinator()\n # threads = tf.train.start_queue_runners(sess=sess, coord=coord)\n # Define input tensor\n # self.input = tf.placeholder(np.float32, shape = [100, 224, 224, 3], name='input_tensor')\n # self.input = data\n # tf.import_graph_def(graph_def, {'input_tensor': self.input})\n\n # sess.run(tf.global_variables_initializer())\n # print(\"evaluating data\")\n # data = sess.run(data) \n # print(\"done evaluating\")\n\n # print(\"data type\")\n # print(type(data))\n # print(data.shape)\n #self.graph.finalize()\n\n # Know your output node name\n #output_tensor = self.graph.get_tensor_by_name(\"import/softmax_tensor:0\")\n # print(\"running model\")\n # output = sess.run(self.output_tensor) #feed_dict = {self.input: data} \n\n # coord.request_stop()\n # coord.join(threads)\n # sess.close()\n # return output\n\n # return output_tensor, get_output\n def test(data):\n #init = tf.global_variables_initializer()\n #self.sess.run(init)\n #self.graph.finalize()\n self.sess = tf.Session(graph=self.graph)\n #with self.sess as sess: \n #self.input = data\n #self.input = tf.placeholder(np.float32, shape = [100, 224, 224, 3], name='input_tensor'\n tf.import_graph_def(graph_def, {'input_tensor':data})# self.input})\n # sess.run(tf.global_variables_initializer())\n # print(\"evaluating data\")\n # data = sess.run(data) \n # tf.train.start_queue_runners(sess) \n # data = data.eval(sess1)\n # print(\"done evaluating\")\n # print(\"data type\")\n # print(type(data))\n # print(data.shape)\n # Know your output node name\n output_tensor = self.graph.get_tensor_by_name(\"import/softmax_tensor:0\")\n print(\"running model\")\n #output = sess.run(output_tensor)#, feed_dict = {self.input: data}) \n\n return output_tensor\n\n # Resnet_v1_50 default image size \n # as defined in tensorflow/models-1.13.0/research/slim/nets/resnet_v1.py#L282\n test.default_image_size = 224\n return test\n\n\n\n# Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Generic evaluation script that evaluates a model using a given dataset.\"\"\"\n\n# from __future__ import absolute_import\n# from __future__ import division\n# from __future__ import print_function\n\n# import math\n# import tensorflow as tf\n\n# from datasets import dataset_factory\n# from nets import nets_factory\n# from preprocessing import preprocessing_factory\n\nslim = tf.contrib.slim\n\ntf.app.flags.DEFINE_integer(\n 'batch_size', 100, 'The number of samples in each batch.')\n\ntf.app.flags.DEFINE_integer(\n 'max_num_batches', None,\n 'Max number of batches to evaluate by default use all.')\n\ntf.app.flags.DEFINE_string(\n 'master', '', 'The address of the TensorFlow master to use.')\n\ntf.app.flags.DEFINE_string(\n 'checkpoint_path', '/tmp/tfmodel/',\n 'The directory where the model was written to or an absolute path to a '\n 'checkpoint file.')\n\n# tf.app.flags.DEFINE_string(\n# 'eval_dir', '/tmp/tfmodel/', 'Directory where the results are saved to.')\n\ntf.app.flags.DEFINE_integer(\n 'num_preprocessing_threads', 4,\n 'The number of threads used to create the batches.')\n\ntf.app.flags.DEFINE_string(\n 'dataset_name', 'imagenet', 'The name of the dataset to load.')\n\ntf.app.flags.DEFINE_string(\n 'dataset_split_name', 'test', 'The name of the train/test split.')\n\ntf.app.flags.DEFINE_string(\n 'dataset_dir', None, 'The directory where the dataset files are stored.')\n\ntf.app.flags.DEFINE_integer(\n 'labels_offset', 0,\n 'An offset for the labels in the dataset. This flag is primarily used to '\n 'evaluate the VGG and ResNet architectures which do not use a background '\n 'class for the ImageNet dataset.')\n\ntf.app.flags.DEFINE_string(\n 'model_name', 'inception_v3', 'The name of the architecture to evaluate.')\n\ntf.app.flags.DEFINE_string(\n 'model_dir', 'resnet50_v1-5.pb', 'The directory of the model to evaluate')\n\ntf.app.flags.DEFINE_string(\n 'preprocessing_name', None, 'The name of the preprocessing to use. If left '\n 'as `None`, then the model_name flag is used.')\n\ntf.app.flags.DEFINE_float(\n 'moving_average_decay', None,\n 'The decay to use for the moving average.'\n 'If left as None, then moving averages are not used.')\n\ntf.app.flags.DEFINE_integer(\n 'eval_image_size', None, 'Eval image size')\n\ntf.app.flags.DEFINE_bool(\n 'quantize', False, 'whether to use quantized graph or not.')\n\ntf.app.flags.DEFINE_string('eval_data_path', '',\n 'Filepattern for eval data')\ntf.app.flags.DEFINE_integer('image_size', 32, 'Image side length.')\ntf.app.flags.DEFINE_string('eval_dir', '',\n 'Directory to keep eval outputs.')\ntf.app.flags.DEFINE_integer('eval_batch_count', 50,\n 'Number of batches to eval.')\ntf.app.flags.DEFINE_bool('eval_once', False,\n 'Whether evaluate the model only once.')\ntf.app.flags.DEFINE_string('log_root', '',\n 'Directory to keep the checkpoints. Should be a '\n 'parent directory of FLAGS.train_dir/eval_dir.')\ntf.app.flags.DEFINE_integer('num_gpus', 0,\n 'Number of gpus used for training. (0 or 1)')\n\nFLAGS = tf.app.flags.FLAGS\n\n\ndef _convert_to_example(filename, image_buffer, label, synset, height, width):\n \"\"\"Build an Example proto for an example.\n Args:\n filename: string, path to an image file, e.g., '/path/to/example.JPG'\n image_buffer: string, JPEG encoding of RGB image\n label: integer, identifier for the ground truth for the network\n synset: string, unique WordNet ID specifying the label, e.g., 'n02323233'\n height: integer, image height in pixels\n width: integer, image width in pixels\n Returns:\n Example proto\n \"\"\"\n colorspace = 'RGB'\n channels = 3\n image_format = 'JPEG'\n\n example = tf.train.Example(features=tf.train.Features(feature={\n 'image/height': _int64_feature(height),\n 'image/width': _int64_feature(width),\n 'image/colorspace': _bytes_feature(colorspace),\n 'image/channels': _int64_feature(channels),\n 'image/class/label': _int64_feature(label),\n 'image/class/synset': _bytes_feature(synset),\n 'image/format': _bytes_feature(image_format),\n 'image/filename': _bytes_feature(os.path.basename(filename)),\n 'image/encoded': _bytes_feature(image_buffer)}))\n return example\n\ndef _crop(image, offset_height, offset_width, crop_height, crop_width):\n \"\"\"Crops the given image using the provided offsets and sizes.\n Note that the method doesn't assume we know the input image size but it does\n assume we know the input image rank.\n Args:\n image: an image of shape [height, width, channels].\n offset_height: a scalar tensor indicating the height offset.\n offset_width: a scalar tensor indicating the width offset.\n crop_height: the height of the cropped image.\n crop_width: the width of the cropped image.\n Returns:\n the cropped (and resized) image.\n Raises:\n InvalidArgumentError: if the rank is not 3 or if the image dimensions are\n less than the crop size.\n \"\"\"\n original_shape = tf.shape(image)\n\n rank_assertion = tf.Assert(\n tf.equal(tf.rank(image), 3),\n ['Rank of image must be equal to 3.'])\n with tf.control_dependencies([rank_assertion]):\n cropped_shape = tf.stack([crop_height, crop_width, original_shape[2]])\n\n size_assertion = tf.Assert(\n tf.logical_and(\n tf.greater_equal(original_shape[0], crop_height),\n tf.greater_equal(original_shape[1], crop_width)),\n ['Crop size greater than the image size.'])\n\n offsets = tf.to_int32(tf.stack([offset_height, offset_width, 0]))\n\n # Use tf.slice instead of crop_to_bounding box as it accepts tensors to\n # define the crop size.\n with tf.control_dependencies([size_assertion]):\n image = tf.slice(image, offsets, cropped_shape)\n return tf.reshape(image, cropped_shape)\n\n\ndef _central_crop(image_list, crop_height, crop_width):\n \"\"\"Performs central crops of the given image list.\n Args:\n image_list: a list of image tensors of the same dimension but possibly\n varying channel.\n crop_height: the height of the image following the crop.\n crop_width: the width of the image following the crop.\n Returns:\n the list of cropped images.\n \"\"\"\n outputs = []\n for image in image_list:\n image_height = tf.shape(image)[0]\n image_width = tf.shape(image)[1]\n\n offset_height = (image_height - crop_height) / 2\n offset_width = (image_width - crop_width) / 2\n\n outputs.append(_crop(image, offset_height, offset_width,\n crop_height, crop_width))\n return outputs\n\ndef _aspect_preserving_resize(image, smallest_side):\n \"\"\"Resize images preserving the original aspect ratio.\n Args:\n image: A 3-D image `Tensor`.\n smallest_side: A python integer or scalar `Tensor` indicating the size of\n the smallest side after resize.\n Returns:\n resized_image: A 3-D tensor containing the resized image.\n \"\"\"\n smallest_side = tf.convert_to_tensor(smallest_side, dtype=tf.int32)\n\n shape = tf.shape(image)\n height = shape[0]\n width = shape[1]\n new_height, new_width = _smallest_size_at_least(height, width, smallest_side)\n image = tf.expand_dims(image, 0)\n resized_image = tf.image.resize_bilinear(image, [new_height, new_width],\n align_corners=False)\n resized_image = tf.squeeze(resized_image)\n resized_image.set_shape([None, None, 3])\n return resized_image\n\ndef _smallest_size_at_least(height, width, smallest_side):\n \"\"\"Computes new shape with the smallest side equal to `smallest_side`.\n Computes new shape with the smallest side equal to `smallest_side` while\n preserving the original aspect ratio.\n Args:\n height: an int32 scalar tensor indicating the current height.\n width: an int32 scalar tensor indicating the current width.\n smallest_side: A python integer or scalar `Tensor` indicating the size of\n the smallest side after resize.\n Returns:\n new_height: an int32 scalar tensor indicating the new height.\n new_width: and int32 scalar tensor indicating the new width.\n \"\"\"\n smallest_side = tf.convert_to_tensor(smallest_side, dtype=tf.int32)\n\n height = tf.to_float(height)\n width = tf.to_float(width)\n smallest_side = tf.to_float(smallest_side)\n\n scale = tf.cond(tf.greater(height, width),\n lambda: smallest_side / width,\n lambda: smallest_side / height)\n new_height = tf.to_int32(tf.rint(height * scale))\n new_width = tf.to_int32(tf.rint(width * scale))\n return new_height, new_width\n\ndef _resize_image(image, height, width):\n \"\"\"Simple wrapper around tf.resize_images.\n This is primarily to make sure we use the same `ResizeMethod` and other\n details each time.\n Args:\n image: A 3-D image `Tensor`.\n height: The target height for the resized image.\n width: The target width for the resized image.\n Returns:\n resized_image: A 3-D tensor containing the resized image. The first two\n dimensions have the shape [height, width].\n \"\"\"\n return tf.image.resize_images(\n image, [height, width], method=tf.image.ResizeMethod.BILINEAR,\n align_corners=False)\n\ndef main(_):\n if not FLAGS.dataset_dir:\n raise ValueError('You must supply the dataset directory with --dataset_dir')\n print(\"=================================starting main======================\")\n\n tf.logging.set_verbosity(tf.logging.INFO)\n\n model = LoadResNet50(FLAGS.model_dir)\n network_fn = model.load_graph()\n graph = model.graph\n print(\"Loaded model!\")\n\n with graph.as_default():\n ######################\n # Select the dataset #\n ######################\n dataset = dataset_factory.get_dataset(\n FLAGS.dataset_name, FLAGS.dataset_split_name, FLAGS.dataset_dir)\n\n ####################\n # Select the model #\n # network_fn = nets_factory.get_network_fn(\n # FLAGS.model_name,\n # num_classes=(dataset.num_classes - FLAGS.labels_offset),\n # is_training=False)\n\n ##############################################################\n # Create a dataset provider that loads data from the dataset #\n ##############################################################\n provider = slim.dataset_data_provider.DatasetDataProvider(\n dataset,\n shuffle=False,\n common_queue_capacity=2 * FLAGS.batch_size,\n common_queue_min=FLAGS.batch_size)\n [image, label] = provider.get(['image', 'label'])\n print(\"\\n\\n\\n###################image###################### \", image)\n print(\"\\n\\n\\n###################label###################### \", label)\n label -= FLAGS.labels_offset\n\n tf_global_step = tf.train.get_or_create_global_step()\n #####################################\n # Select the preprocessing function #\n #####################################\n preprocessing_name = FLAGS.preprocessing_name or FLAGS.model_name\n image_preprocessing_fn = preprocessing_factory.get_preprocessing(\n preprocessing_name,\n is_training=False)\n print(\"########################################################################image.shape!######################################################################\")\n print(image.shape)\n\n #image.reshape([224,224,3])\n #image.set_shape([224,224,3])\n image = _aspect_preserving_resize(image, 256)\n image = _central_crop([image], 224, 224)[0]\n image.set_shape([224, 224, 3])\n image = tf.to_float(image)\n #tf.image.resize(image, [224,224])\n eval_image_size = FLAGS.eval_image_size or network_fn.default_image_size\n\n image = image_preprocessing_fn(image, eval_image_size, eval_image_size)\n\n images, labels = tf.train.batch(\n [image, label],\n batch_size=FLAGS.batch_size,\n num_threads=FLAGS.num_preprocessing_threads,\n capacity= 5 * FLAGS.batch_size) #5 *\n\n model.input = images\n start_time = time.time()\n\n ####################\n # Define the model #\n ####################\n print(\"########################################################################images.shape!######################################################################\")\n print(images.shape)\n #images_np = images.eval()\n \n #network_fn.output_tensor =v#get_tensor_by_name(\"import/softmax_tensor:0\")\n# self.graph.get_tensor_by_name(\"import/softmax_tensor:0\")\n logits = network_fn(images) #network_fn(images)\n\n print(\"evaluated!\")\n #if FLAGS.quantize:\n # tf.contrib.quantize.create_eval_graph()\n\n #if FLAGS.moving_average_decay:\n # variable_averages = tf.train.ExponentialMovingAverage(\n # FLAGS.moving_average_decay, tf_global_step)\n # variables_to_restore = variable_averages.variables_to_restore(\n # slim.get_model_variables())\n # variables_to_restore[tf_global_step.op.name] = tf_global_step\n #else:\n # variables_to_restore = slim.get_variables_to_restore()\n\n\n # predictions = tf.argmax(logits, 1)\n # labels = tf.squeeze(labels)\n\n # # Define the metrics:\n # names_to_values, names_to_updates = slim.metrics.aggregate_metric_map({\n # 'Accuracy': slim.metrics.streaming_accuracy(predictions, labels),\n # 'Recall_5': slim.metrics.streaming_recall_at_k(\n # logits, labels, 5),\n # })\n\n # # Print the summaries to screen.\n # for name, value in names_to_values.items():\n # summary_name = 'eval/%s' % name\n # op = tf.summary.scalar(summary_name, value, collections=[])\n # op = tf.Print(op, [value], summary_name)\n # tf.add_to_collection(tf.GraphKeys.SUMMARIES, op)\n\n\n# with model.sess as sess:\n# coord = tf.train.Coordinator()\n# threads = tf.train.start_queue_runners(sess=sess, coord=coord)\n# init = tf.global_variables_initializer()\n# summaries_update = tf.get_collection_ref(tf.GraphKeys.SUMMARIES) \n# sess.run(init)\n# sess.run(summaries_update)\n# sess.run(logits)\n# print(\"evaluations\")\n# for op in summaries_update:\n# print(op.eval())\n #sess.run(op)\n# coord.request_stop()\n# coord.join(threads)\n# sess.close()\n # print(\"done!\")\n #results = run_fn()\n #results = network_fn(images)\n with model.sess as sess:\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(sess=sess, coord=coord)\n writer = tf.summary.FileWriter(\"output\", sess.graph)\n sess.run(tf.global_variables_initializer())#,feed_dict = {model.input: data}))\n output = sess.run(logits)#, feed_dict = {model.input: data})\n labels = sess.run(labels)#, feed_dict = {model.input: data}) \n writer.close()\n coord.request_stop()\n coord.join(threads)\n sess.close()\n\n # labels = np.argmax(labels)\n test_prediction = np.argmax(output, axis = 0).reshape((-1,1))\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n print(\"labels\")\n print(labels)\n print(\"test_prediction\")\n print(test_prediction)\n test_accuracy = model_accuracy(label = labels, prediction = test_prediction)\n\n print('Test Accuracy: %f' % test_accuracy)\n\n \n\n with graph.as_default():\n flops = tf.profiler.profile(graph, options=tf.profiler.ProfileOptionBuilder.float_operation())\n print('Model {} needs {} FLOPS after freezing'.format('resnet50_v1-5.pb', flops.total_float_ops))\n\n \n \n # TODO(sguada) use num_epochs=1\n # if FLAGS.max_num_batches:\n # num_batches = FLAGS.max_num_batches\n # else:\n # # This ensures that we make a single pass over all of the data.\n # num_batches = math.ceil(dataset.num_samples / float(FLAGS.batch_size))\n\n # if tf.gfile.IsDirectory(FLAGS.checkpoint_path):\n # checkpoint_path = tf.train.latest_checkpoint(FLAGS.checkpoint_path)\n # else:\n # checkpoint_path = FLAGS.checkpoint_path\n\n # tf.logging.info('Evaluating %s' % checkpoint_path)\n\n # slim.evaluation.evaluate_once(\n # master=FLAGS.master,\n # checkpoint_path=checkpoint_path,\n # logdir=FLAGS.eval_dir,\n # num_evals=num_batches,\n # eval_op=list(names_to_updates.values()),\n # variables_to_restore=None) #variables_to_restore=variables_to_restore)\n \ndef estimate_flops(pb_model):\n graph = load_pb(pb_model)\n with graph.as_default():\n # placeholder input would result in incomplete shape. So replace it with constant during model frozen.\n flops = tf.profiler.profile(graph, options=tf.profiler.ProfileOptionBuilder.float_operation())\n print('Model {} needs {} FLOPS after freezing'.format(pb_model, flops.total_float_ops))\n\n\ndef model_accuracy(label, prediction):\n\n # Evaluate the trained model\n return np.sum(label == prediction) / len(prediction)\n\nif __name__ == '__main__':\n tf.app.run()\n","sub_path":"selina_workspace/models-1.13.0/research/slim/an_eval_image_classifier_resnet1-5_no_preprocessing.py","file_name":"an_eval_image_classifier_resnet1-5_no_preprocessing.py","file_ext":"py","file_size_in_byte":22176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"296042935","text":"from pyspark import SparkConf, SparkContext\nfrom pyspark.streaming import StreamingContext\nfrom pyspark.streaming.kafka import KafkaUtils\nfrom kafka import SimpleProducer, KafkaClient\nfrom kafka import KafkaProducer\nfrom datetime import datetime\n\nproducer = KafkaProducer(bootstrap_servers='localhost:9092')\n\ndef handler(message):\n records = message.collect()\n for record in records:\n #m1=str(record)\n dt=str(datetime.now().strftime(\"%Y-%m-%d,%H:%M\"))\n m1,m2=str(record[0]),str(record[1])\n msg=dt+\",\"+m1+\",\"+m2\n producer.send('test2', msg)\n producer.flush()\n\ndef main():\n sc = SparkContext(appName=\"PythonStreamingDirectKafkaWordCount\")\n ssc = StreamingContext(sc, 60)\n\n kvs = KafkaUtils.createDirectStream(ssc, ['booking_events'], {\"metadata.broker.list\": 'localhost:9092', \"auto.offset.reset\": \"largest\"})\n\n tweets = kvs.map(lambda x: x[1])\n words = tweets.map(lambda line:line.split(',')[2].split('\"')[0])\n pairs = words.map(lambda word: (word, 1))\n wordCounts = pairs.reduceByKey(lambda x, y: x + y)\n\n\n wordCounts.foreachRDD(handler)\n\n ssc.start()\n ssc.awaitTermination()\nif __name__ == \"__main__\":\n\n main()\n\n","sub_path":"bin/booking_events_count.py","file_name":"booking_events_count.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"312747679","text":"from django.shortcuts import render\nfrom django.template import RequestContext\nimport json\nfrom django.http import HttpResponse\nfrom django.shortcuts import render_to_response\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponseRedirect\n\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.contrib.auth.decorators import login_required\nimport datetime\n\n\n# Import the built-in password reset view and password reset confirmation view.\nfrom django.contrib.auth.views import password_reset, password_reset_confirm\n\nfrom .models import *\n\n\n## Index Page\ndef home(request):\n variables = {}\n return render(request, 'index.html',variables)\n\n## Dashboard\n@login_required\ndef dashboard(request):\n if request.user.is_authenticated:\n user = Staff.objects.get(id=request.user.id)\n custmers = user.customers.all().order_by('-id','date')\n variables = {'custmers':custmers,'ccount':custmers.count()}\n return render(request, 'dashboard.html',variables)\n\n\n## Add New User Details\n@login_required\ndef add_customer(request):\n if request.user.is_authenticated:\n if request.method == 'POST':\n rg = request.POST.get\n customer = Customer()\n staff = Staff.objects.get(id=request.user.id)\n if rg('cu_name') and rg('cu_dob'):\n if request.FILES:\n customer.policy = request.FILES['policyfile']\n customer.user = staff\n customer.name = rg('cu_name')\n customer.phone_no = rg('cu_phone')\n dob = datetime.datetime.strptime (rg('cu_dob'),'%Y-%m-%d')\n customer.birth_date = dob\n customer.save()\n if request.POST.getlist('cu_phone'):\n for phone in request.POST.getlist('cu_phone'):\n phone_no = PhoneNumber(customer=customer,phone_no=phone)\n phone_no.save()\n return HttpResponseRedirect(reverse('dashboard'))\n else:\n message = \"Please enter valid information\"\n variables = {'message':message}\n else:\n variables = {}\n return render(request, 'add_customer.html',variables)\n else:\n return HttpResponseRedirect(reverse('login'))\n\n\n\n## Customer Detail\n@login_required\ndef customer_detail(request,cid):\n if request.user.is_authenticated:\n customer = Customer.objects.get(id=cid)\n message = ''\n if request.method == 'POST':\n rg = request.POST.get\n if rg('cu_name') and rg('cu_dob') and rg('cu_phone'):\n if request.FILES:\n customer.policy = request.FILES['policyfile']\n customer.name = rg('cu_name')\n customer.phone_no = rg('cu_phone')\n dob = datetime.datetime.strptime (rg('cu_dob'),'%Y-%m-%d')\n customer.birth_date = dob\n customer.save()\n message = \"Successfully updated \"+customer.name+' details'\n else:\n message = \"Please Enter Valid Information\"\n phonenumbers = customer.phone.all()\n variables = {'customer':customer,'phonenumbers':phonenumbers,'message':message}\n return render(request, 'customer.html',variables)\n if customer:\n phonenumbers = customer.phone.all()\n variables = {'customer':customer,'phonenumbers':phonenumbers}\n return render(request, 'customer.html',variables)\n else:\n return HttpResponseRedirect(reverse('dashboard'))\n\n\n\n# This view handles the password reset form URL /.\ndef reset(request):\n # Wrap the built-in password reset view and pass it the arguments\n # like the template name, email template name, subject template name\n # and the url to redirect after the password reset is initiated.\n return password_reset(request, template_name='registration/reset.html',\n email_template_name='registration/reset_email.html',\n subject_template_name='registration/reset_subject.txt',\n post_reset_redirect=reverse('success'))\n\n# This view handles password reset confirmation links. See urls.py file for the mapping.\n# This view is not used here because the password reset emails with confirmation links\n# cannot be sent from this application.\ndef reset_confirm(request, uidb64=None, token=None):\n return password_reset_confirm(request, template_name='registration/reset_confirm.html',uidb64=uidb64, token=token, post_reset_redirect=reverse('login'))\n\n# This view renders a page with success message.\ndef success(request):\n return render(request, \"registration/success.html\")\n\n\n","sub_path":"apps/customer/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"394591022","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Apr 12 13:46:35 2019\r\n\r\n@author: Alex Sternagel\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\n## Import own functions\r\nfrom read_functions import *\r\nfrom init_functions import *\r\n\r\n## import data\r\n# precipitation time and intensity \r\nprec_int, prec_time = read_precip (filepath=\"source/boundarycon/prec_int_specht.csv\")\r\n\r\n# precipitation concentration \r\nprec_conc = read_precip_conc (filepath=\"source/boundarycon/prec_conc_specht.csv\")\r\n\r\n# soil parameters\r\nks, ths, thr, alph, n_vg, stor, l_vg = read_soilpara (filepath=\"source/soils/soilpara_specht.dat\")\r\n\r\n# initial soil moisture state\r\ntheta_init = read_init_theta(filepath=\"source/initial_states/moist_init_specht.csv\", z=z, dim=dim)\r\n\r\n# initial concentration profile in matrix\r\nCw_init = read_init_Cw(filepath=\"source/initial_states/conc_init.csv\", z=z, dim=dim)\r\n\r\n# final observed tracer concentration profile of matrix\r\nconcfin = pd.read_csv(\"source/initial_states/conc_final_specht.csv\", sep=' ', names=['Cw_final','start_depth','end_depth'])\r\n\r\n## Preallocates arrays regarding the particles of both soil matrix and pfd and others\r\n\r\nposition_z_event = np.array([]) # position of event particles entering the soil matrix\r\nage_event = np.array([np.nan]) # age of event particles particles entering the soil matrix\r\nCw_event = np.array([np.nan]) # concentration of event particles entering the soil matrix\r\nt_mix_event = np.array([np.nan])\r\n\r\npfd_position_z = np.array([np.nan]) # position of particles within the pfd\r\npfd_age = np.array([np.nan]) # age of particles within the pfd\r\npfd_Cw_event = np.array([np.nan]) # concentration of particles entering pfd\r\n\r\nm_surface = 0 # water surface storage\r\nm_slt_surface = 0 # solute surface storage\r\nm_input = 0\r\n\r\n# just for testing mass consistency\r\nmass_totalwaterinput = 0 # counter for amount of incoming precipitation water\r\nmass_totalsoluteinput = 0 # counter for amount of incoming solute mass\r\n \r\nbla = 0 # counter for water mass entering the soil matrix\r\nbla1 = 0 # counter for water entering the pfd\r\n \r\nsolute_test = 0 # counter for solute mass entering the soil matrix\r\nsolute_test2 = 0 # counter for solute mass entering the pfd\r\n \r\ntheta_event = 0\r\n\r\n## calculates initial states of psi and c using initial theta values\r\npsi_init, c_init = psi_theta(alph=alph, dim=dim, n_vg=n_vg, stor=stor, theta=theta_init, thr=thr, ths=ths)\r\n\r\n## calculates initial hydraulic conductivities using psi\r\nk_init = k_psi(alph=alph, dim=dim, ks=ks, l_vg=l_vg, n_vg=n_vg, psi=psi_init)\r\n\r\n## Creates lookup table for D and k values\r\nprob = 1.0\r\nD_table = np.zeros((1,nclass)) # lookup table for D\r\nK_table = np.zeros((1,nclass)) # lookup table for k\r\ntheta_table = np.arange(thr,ths,((ths-thr)/nclass)).transpose() # array with soil moisture bins\r\n\r\n#calculates for every soil moisture bin the matrix potential(psi_h), water capacity (c_h), diffusion coefficient (D_table) and hydraulic conductivity (K_table)\r\nfor i in range(0,nclass):\r\n theta_actual = theta_table[i]* np.ones((dim,1))\r\n \r\n psi_h, c_h = psi_theta(alph=alph, dim=dim, n_vg=n_vg, stor=stor, theta=theta_actual, thr=thr, ths=ths)\r\n \r\n k_help = k_psi(alph=alph, dim=dim, ks=ks, l_vg=l_vg, n_vg=n_vg, psi=psi_h)\r\n \r\n if c_h[0] > 0:\r\n D_table[0][i] = k_help[0] / c_h[0]\r\n else: \r\n D_table[0][i] = 0\r\n \r\n K_table[0][i] = k_help[0]\r\n\r\n## Initialisation of particle tracking\r\n\r\n# sets the working parameters to their initial values\r\nk = k_init\r\nc = c_init\r\npsi = psi_init\r\ntheta = theta_init\r\nCw = Cw_init\r\npfd_Cw = pfd_Cw_initial\r\n\r\n# initialises particle mass (m) distribution (n), positions (position_z) and concentrations (c_particle)\r\nn, m = init_particles(theta=theta_init, dz=dz, dim=dim, N=N)\r\n\r\n# initialises particle positions and initial particle concentrations, particle ages, retarded and degraded particle solute concentration\r\nposition_z, c_particle = init_particles_pos(z=z, dim=dim, n=n, Cw_init=Cw_init)\r\nposition_z = np.round(position_z,3)\r\n\r\nage_particle = np.zeros((position_z.size,1))\r\n\r\nposition_z = pd.concat([pd.DataFrame(position_z), pd.DataFrame(age_particle), pd.DataFrame(c_particle)], axis=1)\r\nposition_z = np.asarray(position_z)\r\n\r\n# time settings\r\ntime = prec_time[0] #start time (usually 0)\r\nt_end = t_end + time\r\nt_boundary = prec_time # time stepping of boundary data (time series of the precip_file)\r\ni_time = 1\r\n\r\n# initial input conditions at soil surface\r\nCw_eventparticles = prec_conc[0] # initial concentration of the new incoming particles\r\nqb_u = -0.5 * (prec_int[0] + prec_int[1]) # flux density of precipitation water input\r\n\r\n## Plot settings\r\nz_plot = np.zeros(((z.size-1),1)) # Changes the increments of the simulated soil grid to those of the real observed one (for a better plot fitting)\r\n\r\nfor i in range (0, z.size-1):\r\n z_plot[i] = (z[i]+z[i+1]) / 2\r\n\r\nz_plot = np.append(z[0], z_plot)\r\n","sub_path":"example/init_LAST.py","file_name":"init_LAST.py","file_ext":"py","file_size_in_byte":4913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"624877888","text":"# ui\nimport bpy\n\nif \"bpy\" in locals():\n\timport importlib\n\treloadable_modules = [\n\t\"ui_panel\",\n\t\"ui_replace_sk_menu\",\n\t\"ui_list\",\n\t]\n\tfor module in reloadable_modules:\n\t\tif module in locals():\n\t\t\timportlib.reload(locals()[module])\n\n\nfrom .ui_panel import *\nfrom .ui_replace_sk_menu import *\nfrom .ui_list import *\n\nclasses = (\n# LAZYSHAPEKEYS_PT_main,\nLAZYSHAPEKEYS_UL_sync_list,\n# LAZYSHAPEKEYS_PT_shape_keys,\nLAZYSHAPEKEYS_UL_folder_colle,\nLAZYSHAPEKEYS_UL_replace_menu,\nLAZYSHAPEKEYS_UL_replace_menu_misc_menu,\nLAZYSHAPEKEYS_PT_misc_menu,\nLAZYSHAPEKEYS_UL_folder_inner_sk,\nLAZYSHAPEKEYS_UL_folder_inner_sk_misc_menu,\nLAZYSHAPEKEYS_OT_main,\n)\n\n\ndef register():\n\tfor cls in classes:\n\t\tbpy.utils.register_class(cls)\n\ndef unregister():\n\tfor cls in reversed(classes):\n\t\tbpy.utils.unregister_class(cls)\n\n\nif __name__ == \"__main__\":\n\tregister()\n","sub_path":"scripts/addon_library/local/lazy_shapekeys/ui/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"174764444","text":"\"\"\"\nhttps://leetcode.com/problems/minimum-absolute-sum-difference/\n\nFirst compute the abs diff sum. Then for each (a, b) pair, we need to find the nearest v in nums1 ==> binary serach. \n\nTime comlexity: O(nlogn)\n\"\"\"\nclass Solution:\n def minAbsoluteSumDiff(self, nums1: List[int], nums2: List[int]) -> int:\n MOD = 10 ** 9 + 7\n cnt = {}\n ans = 0\n for a, b in zip(nums1, nums2):\n ans += abs(a - b)\n cnt[a] = cnt.get(a, 0) + 1\n \n cands = sorted(list(cnt.keys()))\n \n curr = ans\n for i, a in enumerate(nums1):\n b = nums2[i]\n if a == b:\n continue\n idx = bisect.bisect_left(cands, b)\n cand = []\n if idx - 1 >= 0:\n cand.append(abs(cands[idx - 1] - b)) \n if 0 <= idx < len(cands):\n cand.append(abs(cands[idx] - b))\n if 0 <= idx + 1 < len(cands):\n cand.append(abs(cands[idx + 1] - b))\n if cand:\n curr = min(curr, ans - abs(a - b) + min(cand))\n return curr % MOD \n ","sub_path":"1818_MinimumAbsoluteSumDifference.py","file_name":"1818_MinimumAbsoluteSumDifference.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"317206103","text":"# Nolan Harris\n# Nph2tx\n\ndef ellipsis(s):\n\n a = len(s) - 2\n x = s[:2]\n y = s[a:]\n return str(x) + \"...\" + str(y)\n\nprint(ellipsis(\"computer science\"))\n\ndef eighteen(s):\n\n a = len(s) - 2\n b = len(s) - 1\n x = s[:1]\n y = s[b:]\n\n return str(x) + str(a) + str(y)\n\nprint(eighteen(\"computer scinece\"))\n\ndef allit(s, t):\n\n x = \"a\", \"e\", \"i\", \"o\", \"u\", \"A\", \"E\", \"I\", \"O\", \"U\"\n string_1 = s.capitalize()\n string_2 = t.capitalize()\n\n if string_1[:1] == x:\n return \"False\"\n\n elif string_2[:1] == x:\n return \"False\"\n\n elif string_1[:1] == string_2[:1]:\n return \"True\"\n\n else:\n return \"False\"\n\nprint(allit(\"Hi\", \"Hello\"))\n\n\n\n\n\n\n","sub_path":"CS1110/CS1110/str_functions.py/str_funcs.py","file_name":"str_funcs.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"306430103","text":"from OpenSSL import SSL\nfrom scrapy.core.downloader.contextfactory import ScrapyClientContextFactory\n\n\nclass TLS12ContextFactory(ScrapyClientContextFactory):\n \"A context factory for TLS version 1.2.\"\n\n def __init__(self):\n ScrapyClientContextFactory.__init__(self)\n self.method = SSL.TLSv1_2_METHOD\n","sub_path":"dist/scrapy-cluster/crawler/crawling/context_factory.py","file_name":"context_factory.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"649803125","text":"import random\nimport numpy as np\nimport os\nimport math\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\n\nfrom modules.attention import AttentionLayer\nfrom utils.config import PAD, EOS, BOS\nfrom utils.dataset import load_pretrained_embedding\nfrom utils.misc import check_device\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nKEY_ATTN_SCORE = 'attention_score'\nKEY_ATTN_OUT = 'attention_out'\nKEY_LENGTH = 'length'\nKEY_SEQUENCE = 'sequence'\n\nclass Dec(nn.Module):\n\n\t\"\"\" listen attend spell model + dd tag \"\"\"\n\n\tdef __init__(self,\n\t\t# params\n\t\tvocab_size,\n\t\tembedding_size=200,\n\t\tacous_hidden_size=256,\n\t\tacous_att_mode='bahdanau',\n\t\thidden_size_dec=200,\n\t\thidden_size_shared=200,\n\t\tnum_unilstm_dec=4,\n\t\t#\n\t\tembedding_dropout=0,\n\t\tdropout=0.0,\n\t\tresidual=True,\n\t\tbatch_first=True,\n\t\tmax_seq_len=32,\n\t\tembedder=None,\n\t\tword2id=None,\n\t\tid2word=None,\n\t\thard_att=False,\n\t\t):\n\n\t\tsuper(Dec, self).__init__()\n\n\t\t# define model\n\t\tself.acous_hidden_size = acous_hidden_size\n\t\tself.acous_att_mode = acous_att_mode\n\t\tself.hidden_size_dec = hidden_size_dec\n\t\tself.hidden_size_shared = hidden_size_shared\n\t\tself.num_unilstm_dec = num_unilstm_dec\n\n\t\t# define var\n\t\tself.hard_att = hard_att\n\t\tself.residual = residual\n\t\tself.max_seq_len = max_seq_len\n\n\t\t# use shared embedding + vocab\n\t\tself.vocab_size = vocab_size\n\t\tself.embedding_size = embedding_size\n\t\tself.word2id = word2id\n\t\tself.id2word = id2word\n\n\t\t# define operations\n\t\tself.embedding_dropout = nn.Dropout(embedding_dropout)\n\t\tself.dropout = nn.Dropout(dropout)\n\n\t\tif type(embedder) != type(None):\n\t\t\tself.embedder = embedder\n\t\telse:\n\t\t\tself.embedder = nn.Embedding(self.vocab_size, self.embedding_size,\n\t\t\t\tsparse=False, padding_idx=PAD)\n\n\t\t# ------ define acous att --------\n\t\tdropout_acous_att = dropout\n\t\tself.acous_hidden_size_att = 0 # ignored with bilinear\n\n\t\tself.acous_key_size = self.acous_hidden_size * 2 \t# acous feats\n\t\tself.acous_value_size = self.acous_hidden_size * 2 \t# acous feats\n\t\tself.acous_query_size = self.hidden_size_dec \t\t# use dec(words) as query\n\t\tself.acous_att = AttentionLayer(self.acous_query_size, self.acous_key_size,\n\t\t\t\t\t\t\t\t\tvalue_size=self.acous_value_size,\n\t\t\t\t\t\t\t\t\tmode=self.acous_att_mode,\n\t\t\t\t\t\t\t\t\tdropout=dropout_acous_att,\n\t\t\t\t\t\t\t\t\tquery_transform=False,\n\t\t\t\t\t\t\t\t\toutput_transform=False,\n\t\t\t\t\t\t\t\t\thidden_size=self.acous_hidden_size_att,\n\t\t\t\t\t\t\t\t\thard_att=False)\n\n\t\t# ------ define acous out --------\n\t\tself.acous_ffn = nn.Linear(self.acous_hidden_size * 2 + self.hidden_size_dec,\n\t\t\t\t\t\t\t\t\tself.hidden_size_shared, bias=False)\n\t\tself.acous_out = nn.Linear(self.hidden_size_shared, self.vocab_size, bias=True)\n\n\n\t\t# ------ define acous dec -------\n\t\t# embedding_size_dec + self.hidden_size_shared [200+200]-> hidden_size_dec [200]\n\t\tif not self.residual:\n\t\t\tself.dec = torch.nn.LSTM(\n\t\t\t\tself.embedding_size+self.hidden_size_shared, self.hidden_size_dec,\n\t\t\t\tnum_layers=self.num_unilstm_dec, batch_first=batch_first,\n\t\t\t\tbias=True, dropout=dropout, bidirectional=False)\n\t\telse:\n\t\t\tself.dec = nn.Module()\n\t\t\tself.dec.add_module('l0', torch.nn.LSTM(\n\t\t\t\tself.embedding_size+self.hidden_size_shared, self.hidden_size_dec,\n\t\t\t\tnum_layers=1, batch_first=batch_first,\n\t\t\t\tbias=True, dropout=dropout, bidirectional=False))\n\n\t\t\tfor i in range(1, self.num_unilstm_dec):\n\t\t\t\tself.dec.add_module('l'+str(i), torch.nn.LSTM(self.hidden_size_dec,\n\t\t\t\t\tself.hidden_size_dec,num_layers=1, batch_first=batch_first,\n\t\t\t\t\tbias=True,dropout=dropout, bidirectional=False))\n\n\n\tdef check_var(self, var_name, var_val_set=None):\n\n\t\t\"\"\" to make old models capatible with added classvar in later versions \"\"\"\n\n\t\tif not hasattr(self, var_name):\n\t\t\tvar_val = var_val_set if type(var_val_set) != type(None) else None\n\t\t\tsetattr(self, var_name, var_val)\n\n\n\tdef forward(self, acous_outputs, acous_lens=None, tgt=None,\n\t\thidden=None, is_training=False, teacher_forcing_ratio=0.0,\n\t\tbeam_width=1, use_gpu=False, lm_mode='null', lm_model=None):\n\n\t\t\"\"\"\n\t\t\tArgs:\n\t\t\t\tenc_outputs: [batch_size, acous_len / 8, self.acous_hidden_size * 2]\n\t\t\t\ttgt: list of word_ids \t\t\t[b x seq_len]\n\t\t\t\thidden: initial hidden state\n\t\t\t\tteacher_forcing_ratio: default at 1 - always teacher forcing\n\t\t\tReturns:\n\t\t\t\tdecoder_outputs: list of step_output -\n\t\t\t\t\tlog predicted_softmax [batch_size, 1, vocab_size_dec] * (T-1)\n\t\t\"\"\"\n\n\t\t# import pdb; pdb.set_trace()\n\n\t\tglobal device\n\t\tdevice = check_device(use_gpu)\n\n\t\t# 0. init var\n\t\tret_dict = dict()\n\t\tret_dict[KEY_ATTN_SCORE] = []\n\n\t\tdecoder_outputs = []\n\t\tsequence_symbols = []\n\t\tbatch_size = acous_outputs.size(0)\n\n\t\tif type(tgt) == type(None):\n\t\t\ttgt = torch.Tensor([BOS]).repeat(\n\t\t\t\tbatch_size, self.max_seq_len).type(torch.LongTensor).to(device=device)\n\n\t\tmax_seq_len = tgt.size(1)\n\t\tlengths = np.array([max_seq_len] * batch_size)\n\n\t\t# 1. convert id to embedding\n\t\temb_tgt = self.embedding_dropout(self.embedder(tgt))\n\n\t\t# 2. att inputs: keys n values\n\t\tatt_keys = acous_outputs\n\t\tatt_vals = acous_outputs\n\n\t\t# generate acous mask: True for trailing 0's\n\t\tif type(acous_lens) != type(None):\n\t\t\t# reduce by 8\n\t\t\tlens = torch.cat([elem + 8 - elem % 8 for elem in acous_lens]) / 8\n\t\t\tmax_acous_len = acous_outputs.size(1)\n\t\t\t# mask=True over trailing 0s\n\t\t\tmask = torch.arange(max_acous_len).to(device=device).expand(\n\t\t\t\tbatch_size, max_acous_len) >= lens.unsqueeze(1).to(device=device)\n\t\telse:\n\t\t\tmask = None\n\n\t\t# 3. init hidden states\n\t\tdec_hidden = None\n\n\t\t# 4. run dec + att + shared + output\n\t\t\"\"\"\n\t\t\tteacher_forcing_ratio = 1.0 -> always teacher forcing\n\t\t\tE.g.:\n\t\t\t\tacous \t = [acous_len/8]\n\t\t\t\ttgt_chunk in = w1 w2 w3 [max_seq_len]\n\t\t\t\tpredicted = w1 w2 w3 [max_seq_len]\n\t\t\"\"\"\n\n\t\t# LAS under teacher forcing\n\t\tuse_teacher_forcing = True if random.random() < teacher_forcing_ratio else False\n\n\t\t# no beam search decoding\n\t\ttgt_chunk = emb_tgt[:, 0].unsqueeze(1) # BOS\n\t\tcell_value = torch.FloatTensor([0]).repeat(\n\t\t\tbatch_size, 1, self.hidden_size_shared).to(device=device)\n\t\tprev_c = torch.FloatTensor([0]).repeat(\n\t\t\tbatch_size, 1, max_seq_len).to(device=device)\n\t\tsequence_embs = []\n\t\tfor idx in range(max_seq_len - 1):\n\t\t\t# import pdb; pdb.set_trace()\n\t\t\tpredicted_logsoftmax, dec_hidden, step_attn, c_out, cell_value, attn_output, logits = \\\n\t\t\t\tself.forward_step(self.acous_att, self.acous_ffn, self.acous_out,\n\t\t\t\t\t\t\t\tatt_keys, att_vals, tgt_chunk, cell_value,\n\t\t\t\t\t\t\t\tdec_hidden, mask, prev_c)\n\t\t\tpredicted_logsoftmax = predicted_logsoftmax.squeeze(1) # [b, vocab_size]\n\t\t\t# add lm\n\t\t\tpredicted_logsoftmax = self.add_lm(lm_mode, lm_model,\n\t\t\t\tpredicted_logsoftmax, sequence_symbols)\n\n\t\t\tstep_output = predicted_logsoftmax\n\t\t\tsymbols, decoder_outputs, sequence_symbols, lengths = \\\n\t\t\t\tself.decode(idx, step_output, decoder_outputs, sequence_symbols, lengths)\n\t\t\tprev_c = c_out\n\t\t\tif use_teacher_forcing:\n\t\t\t\ttgt_chunk = emb_tgt[:, idx+1].unsqueeze(1)\n\t\t\telse:\n\t\t\t\ttgt_chunk = self.embedder(symbols)\n\t\t\tsequence_embs.append(cell_value.squeeze(1)) # b x hidden_size_shared\n\n\t\tret_dict[KEY_LENGTH] = lengths.tolist()\n\t\tsequence_embs = torch.stack(sequence_embs, dim=1) # b x l-1 x hidden_size_shared\n\t\tsequence_logps = torch.stack(decoder_outputs, dim=1) # b x l-1 x vocab_size\n\t\tsequence_symbols = torch.stack(sequence_symbols, dim=1) # b x l-1\n\n\t\t# import pdb; pdb.set_trace()\n\n\t\treturn sequence_embs, sequence_logps, sequence_symbols, lengths\n\n\n\tdef add_lm(self, lm_mode, lm_model, logps, sequence_symbols):\n\n\t\t\"\"\"\n\t\t\tadd external language model to nn posterior\n\t\t\tlogps: b x vocab_size\n\t\t\tsequence_symbols: b x len (len: length decoded so far)\n\t\t\talpha: scale factor\n\n\t\t\tNOTE:\n\t\t\tlm trained on - w1 w2 w3 w4 \n\t\t\tlm scores - w1 w2 w3 w4 \n\t\t\t\tw1 - no change\n\t\t\t\tw2 | w1 - bg\n\t\t\t\tw3 | w1,w2 - tg\n\t\t\t\tw4 | w1,w2,w3 - fg\n\t\t\t\tw5 | w2,w3,w4 - fg [all the rest are 4g]\n\n\t\t\tadd pruning - to speed up process:\n\t\t\t\tonly run LM on top 10 candidates (ok - since not doing beamsearch)\n\t\t\"\"\"\n\t\t# import pdb; pdb.set_trace()\n\n\t\t# combined logp\n\t\tcomblogps = []\n\n\t\t# add explicit lm\n\t\tif lm_mode == 'null':\n\t\t\treturn logps\n\n\t\tmode = lm_mode.split('_')[0]\n\t\talpha = float(lm_mode.split('_')[-1])\n\t\tif mode == 's-4g':\n\t\t\tif len(sequence_symbols) == 0:\n\t\t\t\t# if no context\n\t\t\t\tpass\n\t\t\telse:\n\t\t\t\t# combine if with context\n\t\t\t\tsequence_symbols_cat = torch.cat(sequence_symbols, dim=1) # b x len\n\n\t\t\t# loop over the batch\n\t\t\tfor idx in range(logps.size(0)):\n\t\t\t\t# original [vocab_size]\n\t\t\t\tlogp = logps[idx]\n\t\t\t\t# get context\n\t\t\t\tif len(sequence_symbols) == 0:\n\t\t\t\t\tcontext = [str(BOS)]\n\t\t\t\telse:\n\t\t\t\t\tidseq = [str(int(elem)) for elem in sequence_symbols_cat[idx]]\n\t\t\t\t\tst = max(0, len(idseq) - 3)\n\t\t\t\t\tcontext = idseq[st:]\n\t\t\t\t# loop over top N candidates\n\t\t\t\tN = 10\n\t\t\t\ttop_idices = logp.topk(N)[1]\n\t\t\t\tnewlogp_raw = []\n\t\t\t\tfor j in range(N):\n\t\t\t\t\tquery = str(int(top_idices[j]))\n\t\t\t\t\tscore = lm_model.logscore(query, context)\n\t\t\t\t\tif math.isinf(score):\n\t\t\t\t\t\tscore = -1e10 # to replace -inf\n\t\t\t\t\tnewlogp_raw.append(score)\n\n\t\t\t\t# import pdb; pdb.set_trace()\n\t\t\t\t# normalise\n\t\t\t\tnewlogp_raw = torch.FloatTensor(newlogp_raw) # vocab_size\n\t\t\t\tnewlogp = F.log_softmax(newlogp_raw, dim=0).to(device=device)\n\n\t\t\t\t# combine scores\n\t\t\t\t# import pdb; pdb.set_trace()\n\t\t\t\tcomblogp = logp[:].detach()\n\t\t\t\tfor j in range(N):\n\t\t\t\t\tcomblogp[top_idices[j]] = torch.log(torch.exp(logp[top_idices[j]])\n\t\t\t\t\t\t+ alpha * torch.exp(newlogp[j]))\n\t\t\t\tcomblogps.append(comblogp)\n\n\t\t\tcomblogps = torch.stack(comblogps, dim=0) # b x vocab_size\n\n\t\telif mode == 's-rnn':\n\t\t\tassert False, 'Not implemented'\n\t\telif mode == 'd':\n\t\t\tassert False, 'Not implemented'\n\n\t\treturn comblogps\n\n\n\tdef decode(self, step, step_output, decoder_outputs, sequence_symbols, lengths):\n\n\t\t\t\"\"\"\n\t\t\t\tGreedy decoding\n\t\t\t\tArgs:\n\t\t\t\t\tstep: step idx\n\t\t\t\t\tstep_output: log predicted_softmax [batch_size, 1, vocab_size_dec]\n\t\t\t\tReturns:\n\t\t\t\t\tsymbols: most probable symbol_id [batch_size, 1]\n\t\t\t\"\"\"\n\t\t\tdecoder_outputs.append(step_output)\n\t\t\tsymbols = decoder_outputs[-1].topk(1)[1]\n\t\t\tsequence_symbols.append(symbols)\n\n\t\t\teos_batches = torch.max(symbols.data.eq(EOS), symbols.data.eq(PAD))\n\t\t\t# equivalent to logical OR\n\t\t\t# eos_batches = symbols.data.eq(PAD)\n\t\t\tif eos_batches.dim() > 0:\n\t\t\t\teos_batches = eos_batches.cpu().view(-1).numpy()\n\t\t\t\tupdate_idx = ((lengths > step) & eos_batches) != 0\n\t\t\t\tlengths[update_idx] = len(sequence_symbols)\n\t\t\treturn symbols, decoder_outputs, sequence_symbols, lengths\n\n\n\tdef forward_step(self, att_func, ffn_func, out_func,\n\t\tatt_keys, att_vals, tgt_chunk, prev_cell_value,\n\t\tdec_hidden=None, mask_src=None, prev_c=None):\n\n\t\t\"\"\"\n\t\t\tmanual unrolling\n\n\t\t\tArgs:\n\t\t\t\tatt_keys: [batch_size, seq_len, acous_hidden_size * 2]\n\t\t\t\tatt_vals: [batch_size, seq_len, acous_hidden_size * 2]\n\t\t\t\ttgt_chunk: tgt word embeddings\n\t\t\t\t\t\t\tno teacher forcing - [batch_size, 1, embedding_size_dec]\n\t\t\t\t\t\t\t(becomes 2d when indexed)\n\t\t\t\tprev_cell_value:\n\t\t\t\t\t\t\tprevious cell value before prediction\n\t\t\t\t\t\t\t[batch_size, 1, self.state_size]\n\t\t\t\tdec_hidden:\n\t\t\t\t\t\t\tinitial hidden state for dec layer\n\t\t\t\tmask_src:\n\t\t\t\t\t\t\tmask of PAD for src sequences\n\t\t\t\tprev_c:\n\t\t\t\t\t\t\tused in hybrid attention mechanism\n\n\t\t\tReturns:\n\t\t\t\tpredicted_softmax: log probilities [batch_size, vocab_size_dec]\n\t\t\t\tdec_hidden: a list of hidden states of each dec layer\n\t\t\t\tattn: attention weights\n\t\t\t\tcell_value: transformed attention output\n\t\t\t\t\t\t\t[batch_size, 1, self.hidden_size_shared]\n\t\t\"\"\"\n\n\t\t# record sizes\n\t\tbatch_size = tgt_chunk.size(0)\n\t\ttgt_chunk_etd = torch.cat([tgt_chunk, prev_cell_value], -1)\n\t\ttgt_chunk_etd = tgt_chunk_etd\\\n\t\t\t.view(-1, 1, self.embedding_size + self.hidden_size_shared)\n\n\t\t# run dec\n\t\t# default dec_hidden: [h_0, c_0];\n\t\t# with h_0 [num_layers * num_directions(==1), batch, hidden_size]\n\t\tif not self.residual:\n\t\t\tdec_outputs, dec_hidden = self.dec(tgt_chunk, dec_hidden)\n\t\t\tdec_outputs = self.dropout(dec_outputs)\n\t\telse:\n\t\t\t# store states layer by layer -\n\t\t\t# num_layers * ([1, batch, hidden_size], [1, batch, hidden_size])\n\t\t\tdec_hidden_lis = []\n\n\t\t\t# layer0\n\t\t\tdec_func_first = getattr(self.dec, 'l0')\n\t\t\tif type(dec_hidden) == type(None):\n\t\t\t\tdec_outputs, dec_hidden_out = dec_func_first(tgt_chunk_etd, None)\n\t\t\telse:\n\t\t\t\tindex = torch.tensor([0]).to(device=device) # choose the 0th layer\n\t\t\t\tdec_hidden_in = tuple(\n\t\t\t\t\t[h.index_select(dim=0, index=index) for h in dec_hidden])\n\t\t\t\tdec_outputs, dec_hidden_out = dec_func_first(tgt_chunk_etd, dec_hidden_in)\n\t\t\tdec_hidden_lis.append(dec_hidden_out)\n\t\t\t# no residual for 0th layer\n\t\t\tdec_outputs = self.dropout(dec_outputs)\n\n\t\t\t# layer1+\n\t\t\tfor i in range(1, self.num_unilstm_dec):\n\t\t\t\tdec_inputs = dec_outputs\n\t\t\t\tdec_func = getattr(self.dec, 'l'+str(i))\n\t\t\t\tif type(dec_hidden) == type(None):\n\t\t\t\t\tdec_outputs, dec_hidden_out = dec_func(dec_inputs, None)\n\t\t\t\telse:\n\t\t\t\t\tindex = torch.tensor([i]).to(device=device)\n\t\t\t\t\tdec_hidden_in = tuple(\n\t\t\t\t\t\t[h.index_select(dim=0, index=index) for h in dec_hidden])\n\t\t\t\t\tdec_outputs, dec_hidden_out = dec_func(dec_inputs, dec_hidden_in)\n\t\t\t\tdec_hidden_lis.append(dec_hidden_out)\n\t\t\t\tif i < self.num_unilstm_dec - 1:\n\t\t\t\t\tdec_outputs = dec_outputs + dec_inputs\n\t\t\t\tdec_outputs = self.dropout(dec_outputs)\n\n\t\t\t# convert to tuple\n\t\t\th_0 = torch.cat([h[0] for h in dec_hidden_lis], 0)\n\t\t\tc_0 = torch.cat([h[1] for h in dec_hidden_lis], 0)\n\t\t\tdec_hidden = tuple([h_0, c_0])\n\n\t\t# run att\n\t\tatt_func.set_mask(mask_src)\n\t\tatt_outputs, attn, c_out = att_func(dec_outputs, att_keys, att_vals, prev_c=prev_c)\n\t\tatt_outputs = self.dropout(att_outputs)\n\n\t\t# run ff + softmax\n\t\tff_inputs = torch.cat((att_outputs, dec_outputs), dim=-1)\n\t\tff_inputs_size = self.acous_hidden_size * 2 + self.hidden_size_dec\n\t\tcell_value = ffn_func(ff_inputs.view(-1, 1, ff_inputs_size))\n\t\toutputs = out_func(cell_value.contiguous().view(-1, self.hidden_size_shared))\n\t\tpredicted_logsoftmax = F.log_softmax(outputs, dim=1).view(batch_size, 1, -1)\n\n\t\treturn predicted_logsoftmax, dec_hidden, attn, c_out, cell_value, att_outputs, outputs\n","sub_path":"models/Dec.py","file_name":"Dec.py","file_ext":"py","file_size_in_byte":13901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"298683408","text":"from sqlalchemy import Column, INTEGER, TEXT, BIGINT, BOOLEAN, NUMERIC\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom tables.connectdb import Connectdb\n\nBase = declarative_base()\n\nclass Hub(Base):\n\n __tablename__ = 'hub'\n id = Column(BIGINT, primary_key=True)\n name = Column(TEXT, nullable=False, unique=True)\n en_name = Column(TEXT, nullable=False, unique=True)\n href = Column(TEXT)\n habraindex = Column(NUMERIC)\n count_subscriber = Column(INTEGER)\n count_publication = Column(INTEGER)\n count_downloaded_articles = Column(INTEGER)\n loaded_all_articles = Column(BOOLEAN, nullable=False,default=False)\n habs_pages_load = Column(BOOLEAN, nullable=False,default=False)\n def __repr__(self):\n return \" \" \\\n \"{allatr}\".format(name=self.name, allatr=self.__dict__)\n\n @staticmethod\n def create_table(engine=None):\n if engine is None:\n engine = Connectdb().get_engine()\n Base.metadata.create_all(engine)\n\ndef main():\n Hub().create_table()\n\n\nif __name__ == '__main__':\n main()","sub_path":"tables/hub.py","file_name":"hub.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"475317507","text":"import z\nimport zen\n\noutname = \"ITOT_total_mcsorted\"\noutd = z.getp(outname)\nallowed = list()\nfor astock in outd[-1000:]:\n allowed.append(astock[1])\n\nbuydics = z.getp(\"buydics\")\ndates = z.getp(\"dates\")\n\nstartd = \"2015-04-01\"\nstart = False\n\n\n\nchanges1 = list()\nchanges2 = list()\nspents1 = list()\nspents2 = list()\nmchanges1 = list()\nmchanges2 = list()\nmspents1 = list()\nmspents2 = list()\nfrom collections import defaultdict, deque\nbought = deque()\nmbought = set()\ndrops = list()\nfor date in dates:\n if startd == date:\n start = True\n\n if not start:\n continue\n\n stock = None\n mstock = None\n buyprices = None\n mbuyprices = None\n minchange = 1\n maxchange = 0\n for astock, items in buydics.items():\n if astock not in allowed:\n continue\n# print(\"astock: {}\".format( astock))\n# print(\"items : {}\".format( items ))\n try:\n change = items[date]\n except:\n continue\n openprice = change[1]\n\n# if openprice < 90.00:\n# continue\n\n changed = round(openprice/change[0],3)\n\n if changed > maxchange and astock not in mbought:\n maxchange = changed\n mstock = astock\n mbuyprices = change\n\n elif changed < minchange and astock not in bought:\n minchange = changed\n# print(\"change : {}\".format( change ))\n# print(\"changed: {}\".format( changed))\n# print(\"date: {}\".format( date))\n stock = astock\n buyprices = change\n\n# print(\"astock: {} {} change {}\".format( astock , date, changed))\n\n# raise SystemExit\n price = zen.getPrice(stock)\n if price:\n bought.append(stock)\n if len(bought) > 30:\n bought.popleft()\n# print(\"low stock: {}\".format( stock))\n change1 = round(price/buyprices[0],3)\n spents1.append(buyprices[0])\n changes1.append(change1)\n drops.append(minchange)\n print(\"change1: {} {} {} {} \".format( stock, date, round(minchange,3), change1))\n change2 = round(price/buyprices[1],3)\n changes2.append(change2)\n spents2.append(buyprices[1])\n\n price = zen.getPrice(mstock)\n if price:\n mbought.add(mstock)\n mchange1 = round(price/mbuyprices[0],3)\n mspents1.append(mbuyprices[0])\n mchanges1.append(mchange1)\n mchange2 = round(price/mbuyprices[1],3)\n mchanges2.append(mchange2)\n mspents2.append(mbuyprices[1])\n\n# print(\"change1 : {}\".format( change1 ))\n# print(\"change2 : {}\".format( change2 ))\ns1 = round(sum(spents1),3)\ns2 = round(sum(spents2),3)\nprint(\"s1 : {}\".format( s1 ))\nprint(\"s2 : {}\".format( s2 ))\nprint(\"spents2: {}\".format( len(spents2)))\nprint(\"changes1: {}\".format( z.avg(changes1)))\nprint(\"changes2: {}\".format( z.avg(changes2)))\nprint(\"drops: {}\".format( z.avg(drops)))\n\nimport statistics\nprint(\"drops: {}\".format( statistics.median(drops)))\nprint (statistics.median(changes2))\n\ns1 = round(sum(mspents1),3)\ns2 = round(sum(mspents2),3)\nprint(\"s1 : {}\".format( s1 ))\nprint(\"s2 : {}\".format( s2 ))\nprint(\"spents2: {}\".format( len(mspents2)))\nprint(\"changes1: {}\".format( z.avg(mchanges1)))\nprint(\"changes2: {}\".format( z.avg(mchanges2)))\n\n\n","sub_path":"python/old/whatifiboughtlow.py","file_name":"whatifiboughtlow.py","file_ext":"py","file_size_in_byte":3251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"625411187","text":"# Python imports\n\n# Core Django imports\n\n# Third-Party imports\n\n# Apps Imports\nfrom django_test.apps.subcategories.models import Subcategory\nfrom .models import Product\n\n\ndef assign_subcategories(product, subcategories=None):\n if subcategories:\n for subcategory in subcategories:\n product.subcategories.add(Subcategory.objects.get(id=subcategory))\n product.save()\n\n\ndef create_product(name, price, stock, subcategories, active=True, description=\"\"):\n new_product = Product.objects.create(\n name=name,\n price=price,\n stock=stock,\n active=active,\n description=description,\n )\n assign_subcategories(new_product, subcategories)\n return new_product\n","sub_path":"django_test/apps/products/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"318195104","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom telegram.ext import (Updater, CommandHandler, MessageHandler, Filters, RegexHandler, ConversationHandler,\n InlineQueryHandler)\n\ndef reader(bot, update):\n X = update.message.text\n XID = update.message.from_user.id\n XCID = update.message.chat.id\n\n Xlower = X.lower()\n \n bot.Sendmessage(chat_id=XCID, text=Xlower)\n\n\ndef start(bot, update):\n\n update.message.reply_text('Ciao! Sono @LillieBOT :3 Un _bot_ creato da @Nebulino...'\n 'Com', parse_mode=\"markdown\", quote=False)\n\n\ndef main():\n updater = Updater('YOUR TELEGRAM TOKEN')\n dp = updater.dispatcher\n dp.add_handler(CommandHandler(\"start\", start))\n dp.add_handler(CommandHandler(\"reader\", reader))\n\n # log all errors\n dp.add_error_handler(error)\n\n dp.add_handler(MessageHandler(Filters.text, reader))\n\n # updater.start_polling()\n updater.start_polling(clean=True)\n\n updater.idle()\n\nif __name__ == '__main__':\n\tprint('Started. Listening...')\n","sub_path":"RC ~ Initial Release/Lillie.py","file_name":"Lillie.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"568464293","text":"import numpy as np\n\n\nmin_eps = 1e-52\n\n\ndef args_preprocessing(t0, x0, a, b, f, calc_eps, h_initial):\n\n if not (a <= t0 <= b):\n raise ValueError('t0 must be from a segment [a, b] (a <= b)')\n\n tmp_1 = np.array(x0)\n tmp_2 = np.array(f(t0, x0))\n\n if calc_eps < 0.0:\n raise ValueError('\"calc_eps\" could not be negative!')\n\n if h_initial is not None and h_initial <= 0.0:\n raise ValueError('\"h_initial\" must be positive!')\n\n return 0\n\n\ndef convolve_args(f, args=None):\n\n if args is not None:\n return lambda t, x: f(t, x, args)\n else:\n return f\n\n\ndef calculate_delta(ti, xi, hi, f, args=None):\n\n f_tmp = convolve_args(f, args)\n\n phi0 = hi * np.array(f_tmp(ti, xi))\n phi1 = hi * np.array(f_tmp(ti + hi / 2.0, xi + phi0 / 2.0))\n phi2 = hi * np.array(f_tmp(ti + hi / 2.0, xi + phi1 / 2.0))\n phi3 = hi * np.array(f_tmp(ti + hi, xi + phi2))\n\n return (phi0 + 2 * phi1 + 2 * phi2 + phi3) / 6.0\n\n\ndef solve_ode(t0, x0, a, b, f, calc_eps=1e-12, h_initial=None, args=None, print_iter=False):\n\n f_tmp = convolve_args(f, args)\n args_preprocessing(t0, x0, a, b, f_tmp, calc_eps, h_initial)\n\n ti = t0\n hi = b - t0 if h_initial is None else np.minimum(h_initial, b - t0)\n xi = np.array(x0).copy()\n\n results_x = [xi.copy()]\n result_t = [ti]\n\n while True:\n\n x_first = xi + calculate_delta(ti, xi, hi, f_tmp)\n\n x_tmp = xi + calculate_delta(ti, xi, hi / 2.0, f_tmp)\n x_second = x_tmp + calculate_delta(ti, x_tmp, hi / 2.0, f_tmp)\n\n eps_half = np.linalg.norm(x_second - x_first) / 15.0\n eps_full = eps_half * 16.0\n\n if eps_half > calc_eps:\n\n hi *= 0.5\n continue\n\n ti += hi\n xi = x_second.copy()\n\n if np.abs(result_t[-1]-ti) > min_eps:\n results_x.append(xi.copy())\n result_t.append(ti)\n if print_iter:\n print('[t0, b]: %f' % ((ti - t0) / (b - t0)))\n\n if eps_full < calc_eps:\n hi *= 2\n\n if b - ti - hi < -min_eps:\n hi = b - ti\n\n if np.abs(b - ti) < min_eps:\n break\n\n ti = t0\n hi = t0 - a if h_initial is None else np.minimum(h_initial, t0 - a)\n xi = np.array(x0).copy()\n\n while True:\n\n x_first = xi + calculate_delta(ti, xi, -hi, f_tmp)\n\n x_tmp = xi + calculate_delta(ti, xi, -hi / 2.0, f_tmp)\n x_second = x_tmp + calculate_delta(ti, x_tmp, -hi / 2.0, f_tmp)\n\n eps_half = np.linalg.norm(x_second - x_first) / 15.0\n eps_full = eps_half * 16.0\n\n if eps_half > calc_eps:\n\n hi *= 0.5\n continue\n\n ti -= hi\n xi = x_second.copy()\n\n if np.abs(result_t[0]-ti) > min_eps:\n results_x.insert(0, xi.copy())\n result_t.insert(0, ti)\n if print_iter:\n print('[a, t0]: %f' % ((t0 - ti) / (t0 - a)))\n\n if eps_full < calc_eps:\n hi *= 2\n\n if ti - hi - a < -min_eps:\n hi = ti - a\n\n if np.abs(ti - a) < min_eps:\n break\n\n return np.array(result_t), np.array(results_x).T\n","sub_path":"RungeKutta4.py","file_name":"RungeKutta4.py","file_ext":"py","file_size_in_byte":3108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"592464660","text":"import pandas as pd\nimport numpy as np\nfrom cellNames import getCellName\nimport statistics\nfrom statistics import mean\n\nNUMCELLS = 37148\n\ncellList = []\nfor i in range(NUMCELLS):\n cellList.append(getCellName(i))\n\nuserCell = input('Enter cell name: ').strip()\n\nif userCell =='all_cells':\n rowList = [*range(1, NUMCELLS+1)]\nelse:\n rowList = [i + 1 for i, value in enumerate(cellList) if (value == userCell or userCell in value and type(value) is tuple)]\n\nif not rowList:\n print('Not a valid cell')\n exit()\n\nrowList.insert(0, 0)\n\nf = open('data/usefulTimes.txt', 'r')\ntimeList = f.read().splitlines()\ntimeList = [timeList[i-1] for i in rowList[1:]]\nf.close()\n\nf = open('data/listOfGenes.txt', 'r')\ngeneList = f.read().splitlines()\nf.close()\n\neset = pd.read_csv('data/rawReads.csv', index_col = None, skiprows = lambda x : x not in rowList, header = 0)\n\ntimeListWithoutDuplicates = list(dict.fromkeys(timeList))\n\ndf = pd.DataFrame(index=geneList,\n columns=timeListWithoutDuplicates)\n\nfor i in df.columns:\n df[i]= np.empty((len(df), 0)).tolist()\n\n\nfor row, expressionSeries in eset.iterrows():\n for i in range(len(expressionSeries.index)):\n if expressionSeries.values[i] != 0.0:\n try:\n df.at[expressionSeries.index[i], timeList[row]] = df.at[expressionSeries.index[i], timeList[row]] + [float(expressionSeries.values[i])]\n except:\n print(expressionSeries.index[i], timeList[row])\n\nfor i in df.columns:\n df[i] = df[i].apply(lambda y: 1e-10 if len(y)==0 else y)\n df[i] = df[i].apply(lambda y: mean(y) if type(y) == list else y)\n\ndf = df.reindex(sorted(df.columns), axis=1)\n\ndf = df[(df.T != 1e-10).any()]\n\ndf.to_csv('data/averagedExpressionOverTime.csv')\nexec(open('python/sendEmail.py').read())\n\n","sub_path":"python/createDataFrameWithTime.py","file_name":"createDataFrameWithTime.py","file_ext":"py","file_size_in_byte":1793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"290509440","text":"#!/usr/bin/python3\n##############################################################################################\n## Company: FSAE Lafayette College \n## Engineers:Harrison Walker, Adam Tunnell, Lia Chrysanthopoulos, Mithil Shah,Irwin Frimpong \n## Last Updated : 05/12/2021 11:06 AM \n## Project Name: SCADA FSAE 2021 \n## Module Name: driver.py \n## Description: driver module with method used for Active System Control \n#############################################################################################\n\nimport sys, os\nimport time\n\n#CONFIG PATH\nlib_path = '/usr/etc/scada'\nconfig_path = '/usr/etc/scada/config'\n\nsys.path.append(lib_path)\nsys.path.append(config_path)\n\nimport utils\nimport config\n\nfrom drivers import i2c_driver, emulated_driver\nfrom drivers import can_driver #UNCOMMENT\nfrom drivers import usb7204_driver\nfrom drivers import gpio_driver\n\nSensorList = config.get('Sensors')\nemulating = config.get('emulation')\n\ncan_drive = can_driver.CanDriver() \n\n# Method to read from the sesnor objects depending on protocol \ndef read(Sensor):\n#make it look at the folder for what protocol to use\n sensor_protocol = SensorList.get(str(Sensor)).get('bus_type')\n if(sensor_protocol == 'I2C'):\n data = i2c_driver.read(Sensor)\n elif(sensor_protocol =='CAN'):\n data = can_drive.read(Sensor)\n elif(sensor_protocol == 'USB7204'):\n data= usb7204_driver.read(Sensor)\n elif(sensor_protocol == 'GPIO'):\n data= gpio_driver.read(Sensor)\n elif(sensor_protocol == 'VIRTUAL'):\n data= 0\n elif(emulating and sensor_protocol == 'EMULATED'):\n data = emulated_driver.read(Sensor)\n else:\n return 'Sensor Protocol Not Found'\n \n if(data == None): #Sensor is either unavialble or disconnected \n data = 'no data'\n \n return data\n\n\n#Method to write to a sensor, given sensor and value to be written to said sensor. Sensor must be defined in the configuration YAML file\ndef write(Sensor,Value):\n #Debuggin\n print( \"Sensor: \" + str(Sensor) + \" Value: \" + str(Value))\n sensor_protocol = SensorList.get(str(Sensor)).get('bus_type')\n print('Protocol: ' + sensor_protocol)\n if(sensor_protocol == 'I2C'):\n i2c_driver.write(Sensor, Value)\n elif(sensor_protocol =='CAN'):\n can_drive.write(Sensor,Value)\n elif(sensor_protocol == 'USB'):\n usb7204_driver.write(Sensor,Value)\n elif(emulating and sensor_protocol == 'EMULATED'):\n emulated_driver.write(Sensor,Value)\n elif(sensor_protocol == 'GPIO'):\n data= gpio_driver.write(Sensor,Value)\n else:\n return 'Sensor Protocol Not Found'\n\n\n","sub_path":"drivers/driver.py","file_name":"driver.py","file_ext":"py","file_size_in_byte":2851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"430208097","text":"# Python's version used: 3.8.3 64 bit\n# pip install scikit-learn\n# pip install pandas\n# pip install matplotlib\n\nfrom sklearn.datasets import load_boston\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# The data is built in scikit-learn and we will use load_boston\n# to load the object that contains all the information.\nboston_dataset = load_boston()\n\nboston = pd.DataFrame(boston_dataset.data,\n columns=boston_dataset.feature_names)\n\n# As the name suggests, boston_dataset.feature_names\n# contain names for all features.\n# We then add the target into the DataFrame:\nboston[\"MEDV\"] = boston_dataset.target\n\n# To understand the relationship among features (columns),\n# a correlation matrix is very useful in the exploratory data analysis.\n# Correlation measures linear relationships between variables.\n# We can construct a correlation matrix to show correlation coefficients\n# between variables.\n# It is symmetric where each element is a correlation coefficient\n# ranging from -1 and 1.\n# A value near 1 (resp. -1) indicates a strong positive (resp. negative)\n# correlation between variables.\n# We can create a correlation matrix using the \"corr\" function:\ncorr_matrix = boston.corr().round(2)\nprint(corr_matrix)\n\n# We noticed that RM and MEDV are positively correlated.\n# Recall that scatter plot is a useful tool to display the relationship\n# between two features; let’s take a look at the scatter plot:\nboston.plot(kind=\"scatter\", x=\"RM\", y=\"MEDV\", figsize=(8, 6))\nplt.show()\n","sub_path":"Machine Learning/Linear Regression/02 Correlation and Scatter Plot.py","file_name":"02 Correlation and Scatter Plot.py","file_ext":"py","file_size_in_byte":1508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"273202306","text":"#! python3\n\n# multiplicationTable.py - Takes a number n from command line and creates a n*n multiplication table in Excel\n\nimport openpyxl\nfrom openpyxl.styles import Font\nfrom openpyxl.utils import get_column_letter\nimport os\nimport sys\n\n# Desktop directory\ndesktop = os.path.join(os.environ['USERPROFILE'], 'Desktop\\\\')\n\ndef multiplicationTable(n):\n try: \n n = int(n)\n wb = openpyxl.Workbook()\n sheet = wb.active\n\n # Formatting top row and first column\n boldFont = Font(bold=True)\n\n # Fill in top row and first column\n for i in range(2, n + 2):\n # row\n sheet.cell(row=1, column=i).value = i - 1\n sheet.cell(row=1, column=i).font = boldFont\n \n # column\n sheet.cell(row=i, column=1).value = i - 1\n sheet.cell(row=i, column=1).font = boldFont\n\n\n # Fill in multiplication Table\n for rowNum in range(2, n + 2):\n for colNum in range(2, n + 2):\n sheet.cell(row=rowNum, column = colNum).value = f'= A{str(rowNum)} * {get_column_letter(colNum)}1'\n except (ValueError, TypeError):\n print('That is not a number. Try again.')\n exit()\n \n except Exception:\n print('Something went wrong. Try again')\n exit()\n\n # Save excel workbook to desktop\n os.chdir(desktop)\n wb.save('multiplicationTable.xlsx')\n print('Done')\n\n# Implement command line feature\nif len(sys.argv) == 1:\n # Print out 'how to use'\n print('\\nmultiplicationTable.py - Takes a number n from command line and creates a n*n multiplication table in Excel')\n print('\\nHow to Use via Command Line:')\n print('\\n\\tmultiplicationTable \\n')\nelse:\n multiplicationTable(sys.argv[1])","sub_path":"multiplicationTable.py","file_name":"multiplicationTable.py","file_ext":"py","file_size_in_byte":1764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"335479258","text":"#!/usr/bin/env python3\n# _*_coding:utf-8 _*_\n# @Time    : 2019/7/24 16:31\n# @Author  : 陈天浩\n# @site : https://github.com/Snivyc\n# @FileName: myword2vec.py\n# @Software: PyCharm\nimport collections\nimport hashlib\nimport os\nimport random\nimport urllib\nimport zipfile\nfrom tempfile import gettempdir\n\nimport tensorflow as tf\nimport numpy as np\n\ndata_index = 0\n\n\ndef _hash_file(fpath):\n hasher = hashlib.sha256()\n with open(fpath, 'rb') as fpath_file:\n for chunk in iter(lambda: fpath_file.read(65535), b''):\n hasher.update(chunk)\n return hasher.hexdigest()\n\ndef main():\n\n url = 'http://mattmahoney.net/dc/'\n\n\n def maybe_download(filename, expected_bytes, sha256=None):\n \"\"\"Download a file if not present, and make sure it's the right size.\"\"\"\n local_filename = os.path.join(gettempdir(), filename)\n if not os.path.exists(local_filename):\n local_filename, _ = urllib.request.urlretrieve(url + filename,\n local_filename)\n statinfo = os.stat(local_filename)\n\n if sha256 and _hash_file(local_filename) != sha256:\n raise Exception('Failed to verify ' + local_filename + ' due to hash '\n 'mismatch. Can you get to it with a browser?')\n\n if statinfo.st_size == expected_bytes:\n print('Found and verified', filename)\n else:\n print(statinfo.st_size)\n raise Exception('Failed to verify ' + local_filename +\n '. Can you get to it with a browser?')\n return local_filename\n\n filename = maybe_download(\n 'text8.zip',\n 31344016,\n sha256='a6640522afe85d1963ad56c05b0ede0a0c000dddc9671758a6cc09b7a38e5232')\n\n print(filename)\n\n # Read the data into a list of strings.\n def read_data(filename):\n \"\"\"Extract the first file enclosed in a zip file as a list of words.\"\"\"\n with zipfile.ZipFile(filename) as f:\n data = tf.compat.as_str(f.read(f.namelist()[0])).split()\n return data\n\n vocabulary = read_data(filename)\n print('Data size', len(vocabulary))\n\n # Step 2: Build the dictionary and replace rare words with UNK token.\n vocabulary_size = 50000\n\n def build_dataset(words, n_words):\n \"\"\"Process raw inputs into a dataset.\"\"\"\n count = [['UNK', -1]]\n count.extend(collections.Counter(words).most_common(n_words - 1))\n # print(count)\n\n dictionary = {}\n for word, _ in count:\n dictionary[word] = len(dictionary)\n # print(dictionary)\n data = []\n unk_count = 0\n for word in words:\n index = dictionary.get(word, 0)\n if index == 0: # dictionary['UNK']\n unk_count += 1\n data.append(index)\n print(\"lendata\",len(data))\n # print(unk_count)\n count[0][1] = unk_count\n reversed_dictionary = dict(zip(dictionary.values(), dictionary.keys()))\n print(reversed_dictionary)\n return data, count, dictionary, reversed_dictionary\n\n\n data, count, unused_dictionary, reverse_dictionary = build_dataset(\n vocabulary, vocabulary_size)\n\n del vocabulary # Hint to reduce memory.\n\n\n def generate_batch(batch_size, num_skips, skip_window):\n global data_index\n assert batch_size % num_skips == 0\n assert num_skips <= 2 * skip_window\n batch = np.ndarray(shape=(batch_size), dtype=np.int32)\n labels = np.ndarray(shape=(batch_size, 1), dtype=np.int32)\n span = 2 * skip_window + 1 # [ skip_window target skip_window ]\n buffer = collections.deque(maxlen=span) # pylint: disable=redefined-builtin\n if data_index + span > len(data):\n data_index = 0\n buffer.extend(data[data_index:data_index + span])\n data_index += span\n for i in range(batch_size // num_skips):\n context_words = [w for w in range(span) if w != skip_window]\n words_to_use = random.sample(context_words, num_skips)\n for j, context_word in enumerate(words_to_use):\n batch[i * num_skips + j] = buffer[skip_window]\n labels[i * num_skips + j, 0] = buffer[context_word]\n if data_index == len(data):\n buffer.extend(data[0:span])\n data_index = span\n else:\n buffer.append(data[data_index])\n data_index += 1\n # Backtrack a little bit to avoid skipping words in the end of a batch\n data_index = (data_index + len(data) - span) % len(data)\n return batch, labels\n\n batch, labels = generate_batch(batch_size=8, num_skips=2, skip_window=1)\n for i in range(8):\n print(batch[i], reverse_dictionary[batch[i]], '->', labels[i, 0],\n reverse_dictionary[labels[i, 0]])\n\nmain()","sub_path":"myword2vec.py","file_name":"myword2vec.py","file_ext":"py","file_size_in_byte":4914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"220454117","text":"from __future__ import division, print_function\n\nimport sys\nimport numpy as np\nimport os\nimport errno\n\nfrom marmot.features.feature_extractor import FeatureExtractor\nfrom marmot.util.alignments import train_alignments, align_sentence\nfrom marmot.exceptions.no_data_error import NoDataError\n\n\nclass PhraseAlignmentFeatureExtractor(FeatureExtractor):\n '''\n Extract phrase-level alignment features:\n - percentage of unaligned words\n - percentage of words with more than 1 aligned words\n - average number of aligned words per word\n - ...?\n '''\n\n def __init__(self, align_model='', src_file='', tg_file='', tmp_dir=None):\n if tmp_dir is None:\n tmp_dir = os.getcwd()\n try:\n os.makedirs(tmp_dir)\n except OSError as exc: # Python >2.5\n if exc.errno == errno.EEXIST and os.path.isdir(tmp_dir):\n pass\n else:\n raise\n self.tmp_dir = tmp_dir\n\n self.model = ''\n\n # no alignment model\n if align_model == '':\n # if src_file and tg_file are not empty, it means that an alignment model needs to be trained\n # (self.model doesn't have to be defined, if context objects have alignments)\n if os.path.isfile(src_file) and os.path.isfile(tg_file):\n self.model = train_alignments(src_file, tg_file, self.tmp_dir)\n else:\n self.model = align_model\n\n def get_features(self, context_obj):\n #sys.stderr.write(\"Start PhraseAlignmentFeatureExtractor\\n\")\n if 'source' not in context_obj or context_obj['source'] is None:\n #sys.stderr.write('No source')\n raise NoDataError('source', context_obj, 'AlignmentFeatureExtractor')\n if 'target' not in context_obj or context_obj['source'] is None or context_obj['target'] is None:\n #sys.stderr.write('No target')\n raise NoDataError('target', context_obj, 'AlignmentFeatureExtractor')\n\n if 'alignments_all' not in context_obj:\n context_obj['alignments_all'] = [[i] for i in context_obj['alignments']]\n #raise NoDataError('alignments_all', context_obj, 'AlignmentFeatureExtractor')\n# if self.model == '':\n# raise NoDataError('alignments', context_obj, 'AlignmentFeatureExtractor')\n # we have to extract new alignments because we need the number of aligned words per target word\n# local_alignments = align_sentence(context_obj['source'], context_obj['target'], self.model)\n n_unaligned, n_multiple = 0, 0\n n_alignments = []\n #sys.stderr.write('All fine\\n')\n #sys.stderr.write('%s\\n' % (', '.join([s for s in context_obj])))\n #sys.stderr.write('%s, %i\\n' % (type(context_obj['index']), len(context_obj['index'])))\n #sys.stderr.write('Context obj index: %i to %i\\n' % (context_obj['index'][0], context_obj['index'][1]))\n for i in range(context_obj['index'][0], context_obj['index'][1]):\n assert(all([w == ww for (w, ww) in zip(context_obj['token'], [context_obj['target'][j] for j in range(context_obj['index'][0], context_obj['index'][1])])])), \"Assertion failed\"\n #sys.stderr.write('Assertion was fine\\n')\n #print(context_obj['alignments_all'])\n cur_alignments = len(context_obj['alignments_all'][i])\n #sys.stderr.write('Alignments_all\\n')\n if cur_alignments == 0:\n #sys.stderr.write('Cur_alignments = 0\\n')\n n_unaligned += 1\n elif cur_alignments > 1:\n #sys.stderr.write('Cur_alignments > 1\\n')\n n_multiple += 1\n #sys.stderr.write('Op!\\n')\n n_alignments.append(cur_alignments)\n\n #sys.stderr.write('Still fine')\n tg_len = len(context_obj['token'])\n #sys.stderr.write(\"Finish PhraseAlignmentFeatureExtractor\\n\")\n return [str(n_unaligned/tg_len), str(n_multiple/tg_len), str(np.average(n_alignments))]\n\n def get_feature_names(self):\n return ['num_unaligned', 'num_multi_alignment', 'avg_alignments_num']\n","sub_path":"marmot/features/phrase/phrase_alignment_feature_extractor.py","file_name":"phrase_alignment_feature_extractor.py","file_ext":"py","file_size_in_byte":4109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"368949163","text":"# import the necessary packages\nimport argparse\nimport cv2\n\n# construct the argument parser and parse the arguments\nap = argparse.ArgumentParser()\nap.add_argument(\"-i\", \"--image\", required=True, help=\"Path to the image\")\nargs = vars(ap.parse_args())\n\n# load the image, grab its dimensions, and show it\nimage = cv2.imread(args[\"image\"])\n(h, w) = image.shape[:2]\nprint(\"Image height={}, image width={}\".format(h,w))\n\n# original color\n(b,g,r) = image[0,0]\nprint(\"Pixel at (0, 0) - Red: {r}, Green: {g}, Blue: {b}\".format(r=r, g=g, b=b))\n\n#lets manipulate the color\nimage[0, 0] = (0, 0, 255)\n(b, g, r) = image[0, 0]\nprint(\"Pixel at (0, 0) - Red: {r}, Green: {g}, Blue: {b}\".format(r=r, g=g, b=b))\ncv2.imshow(\"Original\", image)\ncv2.waitKey()\n\n# lets show half the image\n\n#Find the centre of the image\n(cX,cY) = (w//2, h//2)\n\n# since we are using NumPy arrays, we can apply slicing and grab large chunks\n\n# of the image -- let's grab the top-left corner\ntl = image[0:cY, 0:cX]\ncv2.imshow(\"Top-Left Corner\", tl)\ncv2.waitKey()\n\n#top right\ntr = image[0:cY, cX:w]\ncv2.imshow(\"Top-Right Corner\", tr)\ncv2.waitKey()\n\n#bottom left\nbl=image[cY:h, 0:cX]\ncv2.imshow(\"Bottom-Left Corner\", bl)\ncv2.waitKey()\n\n#bottom right\nbr=image[cY:h, cX:w]\ncv2.imshow(\"Bottom-Right Corner\", br)\ncv2.waitKey()\n\n# lets color the top left (B,G,R) BLUE\nimage[0:cY,0:cX] = (255,0,0)\ncv2.imshow(\"top-left coloured\", image)\ncv2.waitKey()\n\n\n\n# quiz\n\nimageQuiz = cv2.imread('./images/florida_trip.png')\n(b, g, r) = imageQuiz[225,111]\nprint(\"Pixel at (0, 0) - Red: {r}, Green: {g}, Blue: {b}\".format(r=r, g=g, b=b))\n\n\n\n\n","sub_path":"module1/image_basics_1.2.py","file_name":"image_basics_1.2.py","file_ext":"py","file_size_in_byte":1578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"361883678","text":"import sqlite3\n\nconn = sqlite3.connect(\"development.sqlite3\")\ncursor = conn.cursor()\nfilters = []\nf = open(\"filters.txt\" , \"r\")\nfor line in f :\n\tfilters.append(line.rstrip(\"\\n\"))\nprint(filters)\nprint(\"{}\".format(1))\n#filters = [\"adaptive_threshold\" , \"affine_transform\" , \"bilevel_channel\" , \"blur_image\" , \"charcoal\" , \"colorize\" , \"edge\" , \"emboss\" , \"equalize\" , \"flip\" , \"flop\" , \"gaussian_blur\"]\ni = 1\nfor item in filters :\n\tsql = 'insert into filters(id , name) values({} , \"{}\")'.format(i , item)\n\ti += 1\n\tcursor.execute(sql)\n\tconn.commit()","sub_path":"db/InitFilters.py","file_name":"InitFilters.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"139947693","text":"INVALID_PROMPT = \"Please enter valid option\\n\\n\"\nINITIAL_PROMPT = \"Select 1 for beverage dispatch\\n\" \\\n \"Select 2 for remaining ingredients\\n\" \\\n \"Select 3 for loading ingredients\\n\" \\\n \"Select 4 to shutdown machine\\n\"\nSELECT_VALID_DRINK = \"Please select a valid drink\"\nSHUTDOWN_MESSAGE = \"Waiting for all the drinks to be served\"\nHEADER_PROMPT = \"Select 0 for main menu\\n\"\nINGREDIENTS_HEADER = \"Available Ingredients\"\nBEVERAGE_DISPATCH_HEADER = \"Beverage menu\\n\"\nBEVERAGE_DISPLAY_FORMAT = \"Select {number} for {beverage_name}\\n\"\nNO_FREE_TAP = \"No free tap available\"\nSERVING_DRINK_ON_TAP = \"Serving drink on tap {tap}\"\nBEVERAGE_NOT_AVAILABLE = \"{beverage} is unavailable at this machine\"\nBEVERAGE_BEING_PREPARED = \"{beverage} is being prepared\"\nBEVERAGE_INGREDIENT_ISSUE = \"{beverage} cannot be prepared because {ingredient} is {problem}\"\nENTER_INGREDIENT_NAME = \"Enter ingredient name: \"\nENTER_INGREDIENT_QUANTITY = \"Enter ingredient quantity: \"\nADDED_INGREDIENT = \"Added {ingredient_name}: {quantity}\\n\"\n","sub_path":"coffee_machine/prompts.py","file_name":"prompts.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"524720225","text":"import pygame, sys,random, time\nfrom pygame.locals import *\n\nclass Raindrop:\n def __init__(self,x,y):\n self.x=x\n self.y=y\n self.speed=random.randint(5,18)\n\n def move(self):\n self.y+=self.speed\n\n def draw(self):\n pygame.draw.line(screen,(0,0,0),(self.x,self.y),(self.x,self.y+5),1)\n\n def off_screen(self):\n return self.y>800\n\nclass Hahee:\n\tdef __init__(self):\n\t\tself.x=300\n\t\tself.y=400\n\tdef draw(self):\n\t\tscreen.blit(mike_umbrella_image,(self.x,self.y))\n\tdef hit_by(self,raindrop):\n\t\treturn pygame.Rect(self.x,self.y,170,192).collidepoint((raindrop.x,raindrop.y))\n\nclass Cloud:\n def __init__(self):\n self.x=300\n self.y=50\n def draw(self):\n screen.blit(cloud_image,(self.x,self.y))\n def rain(self):\n raindrops.append(Raindrop(random.randint(self.x,self.x+300),self.y+100))\n def move(self):\n if pressed_keys[K_RIGHT]:\n self.x+=5\n if pressed_keys[K_LEFT]:\n self.x-=5\n def hit_by(self,raindrop):\n return pygame.Rect(self.x,self.y,170,192).collidepoint((raindrop.x,raindrop.y))\n\t\t\t \npygame.init()\npygame.display.set_caption(\"rain\")\nscreen = pygame.display.set_mode((1000,600))\nclock = pygame.time.Clock()\n#rain_y=0\n#rain_x=random.randint(0,1000)\nraindrop_spawn_time=0\nraindrops=[]\nhahee_image=pygame.image.load(\"/Users/gichulkim/Downloads/Mike.png\").convert()\nmike_umbrella_image=pygame.image.load(\"/Users/gichulkim/Downloads/Mike_umbrella.png\").convert()\n\ncloud_image=pygame.image.load(\"/Users/gichulkim/Downloads/cloud.png\").convert()\nhahee=Hahee()\ncloud=Cloud()\n\n\nwhile 1:\n\tclock.tick(60)\n\tfor event in pygame.event.get():\n\t\tif event.type==pygame.QUIT:\n\t\t\tsys.exit()\n\tpressed_keys=pygame.key.get_pressed()\t\n\t#raindrops.append(Raindrop()) \n\tscreen.fill((255,255,255))\n\thahee.draw()\n\tcloud.draw()\n\tcloud.rain()\n\tcloud.move()\n\t#rain_y+=4\n\t#pygame.draw.line(screen,(0,0,0),(rain_x,rain_y),(rain_x,rain_y+5),1)\n\t'''\n\tfor raindrop in raindrops:\n\t\traindrop.move()\n\t\traindrop.draw()\n\t'''\n\ti=0\n\twhile i= 10:\n s %= 10\n plus = True\n cur.next = ListNode(s)\n cur = cur.__next__\n if cur1:\n cur1 = cur1.__next__\n if cur2:\n cur2 = cur2.__next__\n if plus:\n cur.next = ListNode(1)\n return res.__next__","sub_path":"Python/Add Two Numbers.py","file_name":"Add Two Numbers.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"462350588","text":"###############################################################################\n# Copyright (C) 2020-2021 Habana Labs, Ltd. an Intel Company\n# All Rights Reserved.\n#\n# Unauthorized copying of this file or any element(s) within it, via any medium\n# is strictly prohibited.\n# This file contains Habana Labs, Ltd. proprietary and confidential information\n# and is subject to the confidentiality and license agreements under which it\n# was provided.\n###############################################################################\n\nimport os\nimport sys\nfrom pathlib import Path\nimport math\nimport subprocess\nfrom central.habana_model_runner_utils import HabanaEnvVariables, print_env_info, get_canonical_path, get_canonical_path_str, is_valid_multi_node_config, get_multi_node_config_nodes\nfrom central.training_run_config import TrainingRunHWConfig\nimport central.prepare_output_dir as prepare_output_dir\nfrom central.multi_node_utils import run_per_ip\n\nclass AlbertPretrainingBookswiki(TrainingRunHWConfig):\n def __init__(self, scaleout, num_workers_per_hls, hls_type, kubernetes_run, args, p1_steps, p1_warmup, p1_batch_size, p1_max_seq_len,\n p2_steps, p2_warmup, p2_batch_size, p2_max_seq_len, pretrained_model, enable_scoped_allocator):\n super(AlbertPretrainingBookswiki, self).__init__(scaleout, num_workers_per_hls, hls_type, kubernetes_run, \"demo_albert_log\")\n self.args = args\n self.p1_steps = int(p1_steps)\n self.p1_warmup = int(p1_warmup)\n self.p1_batch_size = int(p1_batch_size)\n self.p1_max_seq_len = int(p1_max_seq_len)\n self.p2_steps = int(p2_steps)\n self.p2_warmup = int(p2_warmup)\n self.p2_batch_size = int(p2_batch_size)\n self.p2_max_seq_len = int(p2_max_seq_len)\n self.pretrained_model = pretrained_model\n self.enable_scoped_allocator = enable_scoped_allocator\n self.eval_batch_size = 8\n\n if self.args.dataset_path is not None:\n self.dataset_path = self.args.dataset_path\n else:\n self.dataset_path = \"./albert_pretraining_bookswiki_dataset\"\n\n if self.args.output_dir is not None:\n self.results_dir = self.args.output_dir\n else:\n self.results_dir = \"./albert_pretraining_bookswiki_results\"\n\n self.learning_rate = self.args.learning_rate\n\n self.command = ''\n self.overfit_habana_env_variables = {}\n\n def prepare_results_path(self, results_dir):\n try:\n if self.scaleout and is_valid_multi_node_config() and not self.kubernetes_run:\n prepare_output_dir_path = Path(__file__).parent.parent.parent.parent.parent.joinpath('central').joinpath('prepare_output_dir.py')\n run_per_ip(f\"{sys.executable} {str(prepare_output_dir_path)} {results_dir}\", ['MULTI_HLS_IPS', 'PYTHONPATH'], False)\n else:\n prepare_output_dir.prepare_output_dir_r(results_dir)\n except Exception as exc:\n raise RuntimeError(f\"Error in {self.__class__.__name__} prepare_results_path({results_dir})\") from exc\n\n def build_command_phase1(self):\n try:\n horovod_str = \"--use_horovod\" if self.scaleout is True else \"\"\n\n # run_per_ip\n self.prepare_results_path(self.results_dir)\n results_dir_phase1 = self.results_dir + \"_phase1\"\n\n seq_len = self.p1_max_seq_len\n dataset_path_phase1 = get_canonical_path(self.args.dataset_path).joinpath(f\"seq_len_{seq_len}\")\n training_file_path = str(dataset_path_phase1.joinpath(\"training\"))\n eval_file_path = str(dataset_path_phase1.joinpath(\"test\"))\n\n results_path = get_canonical_path(results_dir_phase1)\n self.prepare_results_path(results_dir_phase1)\n pretrained_model_path = get_canonical_path(self.pretrained_model)\n albert_config = str(pretrained_model_path.joinpath(\"albert_config.json\"))\n init_checkpoint = str(pretrained_model_path.joinpath(\"model.ckpt-best\"))\n run_pretraining_path = Path(__file__).parent.joinpath('run_pretraining.py')\n\n print(f\"{self.__class__.__name__}: self.mpirun_cmd = {self.mpirun_cmd}\")\n if self.mpirun_cmd == '':\n print(\"#####mpirun is none\\n\")\n init_command = f\"time python3 {str(run_pretraining_path)}\"\n else:\n print(\"#####mpirun is not none\\n\")\n init_command = f\"time {self.mpirun_cmd} python3 {str(run_pretraining_path)}\"\n self.command = (\n f\"{init_command}\"\n f\" --input_file={training_file_path}/*\"\n f\" --eval_file={eval_file_path}/*\"\n f\" --output_dir={str(results_path)}\"\n f\" --do_train=True\"\n f\" --do_eval=True\"\n f\" --albert_config_file={albert_config}\"\n f\" --init_checkpoint={init_checkpoint}\"\n f\" --train_batch_size={self.p1_batch_size}\"\n f\" --eval_batch_size={self.eval_batch_size}\"\n f\" --max_seq_length={self.p1_max_seq_len}\"\n f\" --num_train_steps={self.p1_steps}\"\n f\" --num_warmup_steps={self.p1_warmup}\"\n f\" --learning_rate={self.learning_rate}\"\n f\" {horovod_str}\"\n f\" --enable_scoped_allocator={self.enable_scoped_allocator}\"\n )\n print(\"-------------------------------------------------------------------------\\n\")\n print(\"Running the Pre-Training :: Phase 1\\n\")\n print(\"-------------------------------------------------------------------------\")\n print('albert_pretraining_bookswiki_utils build_command(): self.command for phase1 = ', self.command)\n except Exception as exc:\n raise RuntimeError(f\"Error in {self.__class__.__name__} build_command_phase1()\") from exc\n\n def build_command_phase2(self):\n try:\n horovod_str = \"--use_horovod\" if self.scaleout is True else \"\"\n\n # run_per_ip\n self.prepare_results_path(self.results_dir)\n results_dir_phase2 = self.results_dir + \"_phase2\"\n\n seq_len = self.p2_max_seq_len\n dataset_path_phase2 = get_canonical_path(self.args.dataset_path).joinpath(f\"seq_len_{seq_len}\")\n training_file_path = str(dataset_path_phase2.joinpath(\"training\"))\n eval_file_path = str(dataset_path_phase2.joinpath(\"test\"))\n\n results_path = get_canonical_path(results_dir_phase2)\n self.prepare_results_path(results_dir_phase2)\n pretrained_model_path = get_canonical_path(self.pretrained_model)\n albert_config = str(pretrained_model_path.joinpath(\"albert_config.json\"))\n init_checkpoint = str(pretrained_model_path.joinpath(\"model.ckpt-best\"))\n run_pretraining_path = Path(__file__).parent.joinpath('run_pretraining.py')\n\n print(f\"{self.__class__.__name__}: self.mpirun_cmd = {self.mpirun_cmd}\")\n if self.mpirun_cmd == '':\n init_command = f\"time python3 {str(run_pretraining_path)}\"\n else:\n init_command = f\"time {self.mpirun_cmd} python3 {str(run_pretraining_path)}\"\n self.command = (\n f\"{init_command}\"\n f\" --input_file={training_file_path}/*\"\n f\" --eval_file={eval_file_path}/*\"\n f\" --output_dir={str(results_path)}\"\n f\" --do_train=True\"\n f\" --do_eval=True\"\n f\" --albert_config_file={albert_config}\"\n f\" --init_checkpoint={init_checkpoint}\"\n f\" --train_batch_size={self.p2_batch_size}\"\n f\" --eval_batch_size={self.eval_batch_size}\"\n f\" --max_seq_length={self.p2_max_seq_len}\"\n f\" --num_train_steps={self.p2_steps}\"\n f\" --num_warmup_steps={self.p2_warmup}\"\n f\" --learning_rate={self.learning_rate}\"\n f\" {horovod_str}\"\n f\" --enable_scoped_allocator={self.enable_scoped_allocator}\"\n )\n print(\"-------------------------------------------------------------------------\\n\")\n print(\"Running the Pre-Training :: Phase 2\\n\")\n print(\"-------------------------------------------------------------------------\")\n print('albert_pretraining_bookswiki_utils build_command(): self.command for phase1 = ', self.command)\n except Exception as exc:\n raise RuntimeError(f\"Error in {self.__class__.__name__} build_command_phase1()\") from exc\n\n def run(self):\n try:\n run_config_env_vars = self.get_env_vars()\n print('run_config_env_vars = ', run_config_env_vars)\n with HabanaEnvVariables(env_vars_to_set=run_config_env_vars), \\\n HabanaEnvVariables(env_vars_to_set=self.overfit_habana_env_variables):\n #run phase1\n self.build_command_phase1()\n print_env_info(self.command, run_config_env_vars)\n print_env_info(self.command, self.overfit_habana_env_variables)\n print(f\"{self.__class__.__name__} run(): self.command = {self.command}\")\n sys.stdout.flush()\n sys.stderr.flush()\n\n with subprocess.Popen(self.command, shell=True, executable='/bin/bash') as proc:\n proc.wait()\n\n sys.stdout.flush()\n sys.stderr.flush()\n\n #run phase1\n self.build_command_phase2()\n print_env_info(self.command, run_config_env_vars)\n print_env_info(self.command, self.overfit_habana_env_variables)\n print(f\"{self.__class__.__name__} run(): self.command = {self.command}\")\n sys.stdout.flush()\n sys.stderr.flush()\n with subprocess.Popen(self.command, shell=True, executable='/bin/bash') as proc:\n proc.wait()\n\n except Exception as exc:\n raise RuntimeError(f\"Error in {self.__class__.__name__} run()\") from exc\n","sub_path":"TensorFlow/nlp/albert/albert_pretraining_bookswiki_main.py","file_name":"albert_pretraining_bookswiki_main.py","file_ext":"py","file_size_in_byte":10141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"622330441","text":"'''\nMerge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.\n\nExample:\n\nInput:\n[\n 1->4->5,\n 1->3->4,\n 2->6\n]\nOutput: 1->1->2->3->4->4->5->6\n'''\n\n__date__ = '20198-1-27'\n\n# way 1\n# 归并排序\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\n\nclass Solution:\n def mergeKLists(self, lists):\n \"\"\"\n :type lists: List[ListNode]\n :rtype: ListNode\n \"\"\"\n if not lists:\n return\n elif len(lists) == 1:\n return lists[0]\n else:\n mid = len(lists) // 2\n left_half = self.mergeKLists(lists[:mid])\n right_half = self.mergeKLists(lists[mid:])\n ans = self.merge_sorted_list(left_half, right_half)\n\n return ans\n\n def merge_sorted_list(self, l1, l2):\n newNode = ListNode(0)\n retNode = newNode\n while l1 and l2:\n if l1.val >= l2.val:\n newNode.next = l2\n l2 = l2.next\n else:\n newNode.next = l1\n l1 = l1.next\n newNode = newNode.next\n if not l1:\n newNode.next = l2\n if not l2:\n newNode.next = l1\n\n return retNode.next\n\n# way 2\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\n\nclass Solution:\n def mergeKLists(self, lists):\n \"\"\"\n :type lists: List[ListNode]\n :rtype: ListNode\n \"\"\"\n res = ListNode(0)\n head = res\n dic = {}\n for x in lists:\n if x is None:\n continue\n if x.val not in dic:\n dic[x.val] = [x]\n else:\n dic[x.val].append(x)\n\n while dic:\n minkey = min(dic)\n l = dic[minkey]\n del dic[minkey]\n for x in l:\n res.next = x\n res = res.next\n x = x.next\n if x:\n if x.val not in dic:\n dic[x.val] = [x]\n else:\n dic[x.val].append(x)\n return head.next\n","sub_path":"23. Merge k Sorted Lists.py","file_name":"23. Merge k Sorted Lists.py","file_ext":"py","file_size_in_byte":2270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"181017297","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 ('scheduler', '0012_auto_20170430_2242'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='event',\n name='img_url',\n field=models.URLField(default='', max_length=1000),\n ),\n ]\n","sub_path":"themat/scheduler/migrations/0013_auto_20170430_2259.py","file_name":"0013_auto_20170430_2259.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"543289712","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n# Language Version: 2.7+\n# Last Modified: 2019-12-01 23:57:46\nfrom __future__ import unicode_literals, division, absolute_import, print_function\n\n\"\"\"\n函数库\n1. 简体繁体检测\n2. 简体繁体转换\n3. 注音 phonetic notation\n4. 注音格式转换\n5. 去除'〡'\n\"\"\"\n\n__all__ = []\n__author__ = \"\"\n__version__ = \"0.0.1\"\n\n\nimport re\nimport os\nimport copy\nimport gzip\nimport json\nimport time\nimport array\nfrom functools import reduce\nimport requests\n\n\nprint('调用函数库')\n\n\ndef rm_ditto_mark(ctx):\n # 在xml中去除三个叠字符号: ⺀ U+2E80 0 /〃 U+3003 2227 /々 U+3005 6415/ 亽 U+4EBD 151\n ctx = array.array('u', ctx)\n dittos = (chr(0x3003), chr(0x3005), chr(0x4ebd))\n for idx, zi in enumerate(ctx):\n if zi in dittos:\n for i in range(idx-1, -1, -1):\n if ishanzi(ctx[i]):\n ctx[idx] = ctx[i] # 找到一个合法的重复字符进行替换\n break\n return ctx.tounicode()\n\n\ndef rm_ditto_mark(ctx):\n # 在xml中去除三个叠字符号(默认叠字符号始终相连): ⺀ U+2E80 0 /〃 U+3003 2227 /々 U+3005 6415/ 亽 U+4EBD 151\n ctx = array.array('u', ctx)\n dittos = (chr(0x3003), chr(0x3005), chr(0x4ebd))\n cc = 0 # 叠字符号的重复次数\n len_ctx = len(ctx)\n for idx, zi in enumerate(ctx):\n if zi in dittos:\n cc = cc + 1\n if len_ctx > idx and ctx[idx+1] in dittos:\n continue\n if cc == 0:\n continue\n j = 0\n for i in range(idx-cc, -1, -1):\n if ishanzi(ctx[i]):\n ctx[idx-j] = ctx[i] # 找到一个合法的重复字符进行替换\n j = j + 1\n cc = cc - 1\n if cc == 0:\n break\n return ctx.tounicode()\n\n\ndef ishanzi(zi):\n '''判断一个字是否是非叠字汉字'''\n zi = ord(zi)\n # 〇\n if 0x3007 == zi:\n return True\n # 主区\n if 0x4E00 <= zi <= 0x9FEF and zi != 0x4EBD:\n return True\n # A区\n if 0x3400 <= zi <= 0x4DB5:\n return True\n # BCDEF: 0x20007-0x2EBD6\n if 0x20000 <= zi <= 0x2EBE0:\n return True\n # 一些兼容汉字\n if zi in (0x3007, 0xFA1F, 0x2F804, 0x2F83B):\n return True\n return False\n\n\ndef readdb(path, trans=False, reverse=False):\n '''读取文本数据库, trans为是否用于tanslate函数, reverse为是否翻转'''\n result = dict()\n with open(path, encoding='utf8') as fd:\n for line in fd:\n line = line.strip()\n if line.startswith('#') or not line: continue\n c0, c1, *cc = line.strip().split()\n if trans and reverse:\n result[ord(c1)] = ord(c0)\n if trans and not reverse:\n result[ord(c0)] = ord(c1)\n if not trans and reverse:\n result[c1] = c0\n if not trans and not reverse:\n result[c0] = c1\n return result\n\n\nclass TSDetect:\n '''简体繁体检测'''\n def __init__(self):\n\n self.p = re.compile(r'[\\u4e00-\\u9fa5]')\n\n # self.tt: 纯繁体字集合\n # self.ss: 纯简体字集合\n tsdb = readdb('cc/TSCharacters.txt')\n tt = set(tsdb.keys())\n ss = set(tsdb.values())\n xx = tt & ss\n\n self.tt = tt - xx\n self.ss = ss - xx\n\n def detect(self, s0):\n '''粗略判断一段文本是简体还是繁体的概率'''\n if len(s0) == 0:\n return {'t': 50, 's': 50, 'confidence': ''}\n\n s0 = set(s0)\n # 同时是简体繁体的可能性\n j = sum(1 for i in (s0 - self.tt - self.ss) if self.p.match(i))\n # 繁体可能性\n t = 100 + ((j * 50 - len(s0 - self.tt) * 100 )/ len(s0))\n # 简体可能性\n s = 100 + ((j * 50 - len(s0 - self.ss) * 100 )/ len(s0))\n\n confidence = ''\n if t > 50:\n confidence = 't'\n elif s > 50:\n confidence = 's'\n return {'t': t, 's': s, 'confidence': confidence}\n\nTSDinst = TSDetect()\n\ndef read_menu_file(sutra_list):\n '''读取tab分隔的菜单文件,返回树状字典'''\n menu = dict()\n print('''读取tab分隔的菜单文件,返回树状字典''')\n\n with open(sutra_list, encoding='utf8') as fd:\n for line in fd:\n line = line.rstrip()\n # if line.startswith('\\t\\t\\t\\t\\t'):\n # print(line)\n if not line.startswith('\\t'):\n key1 = line\n menu.update({line:{}})\n continue\n line = line[1:]\n\n if not line.startswith('\\t'):\n key2 = line\n menu[key1].update({line: {}})\n continue\n line = line[1:]\n\n if not line.startswith('\\t'):\n key3 = line\n menu[key1][key2].update({line: {}})\n continue\n line = line[1:]\n\n if not line.startswith('\\t'):\n key4 = line\n menu[key1][key2][key3].update({line: {}})\n continue\n line = line[1:]\n\n if not line.startswith('\\t'):\n key5 = line\n menu[key1][key2][key3][key4].update({line: {}})\n continue\n line = line[1:]\n\n if not line.startswith('\\t'):\n menu[key1][key2][key3][key4][key5].update({line: {}})\n continue\n return menu\n\ndef ls(pattern):\n result = []\n for path in os.listdir(pattern):\n if path.startswith(sutra) and re.match(pattern, path):\n result.append(path.split('_')[1][:-4])\n return result\n\nfrom functools import total_ordering\n\n@total_ordering\nclass Number:\n '''经号类: T01n0002a'''\n def __init__(self, n):\n self.book, self.sutra = n.split('n')\n def __eq__(self, other):\n self.book, self.sutra = n.split('n')\n def __lt__(self, other):\n self.book, self.sutra = n.split('n')\n def __str__(self):\n pass\n\nclass Sutra:\n def __init__(self, args):\n self.title = args[0] # 经名\n self.number = args[1] # 经号\n self.author = args[2] # 作者\n self.total = args[3] # 卷数/字数, 年代\n\n\ndef get_all_juan(number):\n '''给定经号T01n0002,返��所有排序后的卷['001', '002', ...]\n 返回值是一个数组,如果没有找到则返回空的数组'''\n book, sutra = number.split('n')\n # 查找第一卷(有些不是从第一卷开始的)\n juan = []\n if not os.path.exists(f'xml/{book}'):\n return None\n for path in os.listdir(f'xml/{book}'):\n if path.startswith(number):\n juan.append(path.split('_')[1][:-4])\n juan.sort(key=lambda x: int(re.sub(r'[a-zA-Z]*', '', f'{x:0<5}'), 16))\n return juan\n\n\ndef get_sorted_juan(book):\n '''获得book(T01)下的所有排序好的经卷号(T01n0002_001)'''\n # 对所有的book下的卷排序\n juanlist = []\n for path in os.listdir(f'xml/{book}'):\n sutra, juan = path[:-4].split('_')\n sutra = sutra.split('n')[1]\n juanlist.append((sutra, juan))\n juanlist.sort(key=lambda x: (int(f'{x[0]:0<5}', 16), int(x[1])))\n juanlist = [f'{book}n{i[0]}_{i[1]:0>3}' for i in juanlist]\n return juanlist\n\ndef get_sorted_ce(book):\n # 获得全部book(T01)下的所有排序好的册号列表(T01,T02,T03,T04...)\n booklist = []\n bookhead = re.sub('[0-9]*', '', book)\n for path in os.listdir(f'xml'):\n if path.startswith(bookhead):\n booklist.append(path.strip(bookhead))\n booklist.sort(key=int)\n booklist = [f'{bookhead}{i}' for i in booklist]\n return booklist\n\ndef get_next_juan(number):\n '''给定经号T01n0002_001,返回T01n0002_002'''\n book = number.split('n')[0]\n # 重新生成标准经号\n jinghao, juan = number.split('_')\n number = f'{jinghao}_{juan:0>3}'\n # # 对所有的book下的卷排序\n juanlist = get_sorted_juan(book)\n\n if number != juanlist[-1]:\n return juanlist[juanlist.index(number) + 1]\n # else: book + 1\n booklist = []\n bookhead = re.sub('[0-9]*', '', book)\n for path in os.listdir(f'xml'):\n if path.startswith(bookhead):\n booklist.append(path.strip(bookhead))\n booklist.sort(key=int)\n booklist = [f'{bookhead}{i}' for i in booklist]\n if book != booklist[-1]:\n nextbook = booklist[booklist.index(book) + 1]\n booklist = get_sorted_juan(nextbook)\n return booklist[0]\n # else:\n return juanlist\n\n\ndef get_prev_juan(number):\n '''给定经号T01n0002_002,返回T01n0002_001'''\n book = number.split('n')[0]\n # 重新生成标准经号\n jinghao, juan = number.split('_')\n number = f'{jinghao}_{juan:0>3}'\n # 对所有的book下的卷排序\n juanlist = get_sorted_juan(book)\n\n if number != juanlist[0]:\n return juanlist[juanlist.index(number) - 1]\n # else: book - 1\n # 获得全部排序号的book列表\n booklist = []\n bookhead = re.sub('[0-9]*', '', book)\n for path in os.listdir(f'xml'):\n if path.startswith(bookhead):\n booklist.append(path.strip(bookhead))\n booklist.sort(key=int)\n booklist = [f'{bookhead}{i}' for i in booklist]\n if book != booklist[0]:\n prevbook = booklist[booklist.index(book) - 1]\n booklist = get_sorted_juan(prevbook)\n return booklist[-1]\n # else:\n return juanlist\n\n\nsch_db = []\nwith open(\"static/sutra_sch.lst\") as fd:\n for line in fd:\n if 'n' in line:\n line = line.strip().split()[0]\n sch_db.append(line)\n\n# 大正七〇·四五九中、四六〇下\n# 大正藏第70卷459页b\ndef make_url2():\n # 大正四五·九下\n # 0009c01\n # vol:45;page:p9c\n # vol:30;page:p772c\n t = { '〇': '0',\n '一': '1',\n '二': '2',\n '三': '3',\n '四': '4',\n '五': '5',\n '六': '6',\n '七': '7',\n '八': '8',\n '九': '9',\n '上': 'a',\n '中': 'b',\n '下': 'c',\n }\n pass\n\n# 模式1: T01n0001, T01n0001_001, T01n0001_p0001a01\n# 模式2: T01,no.1,p.1a1\n# CBETA 2019.Q2, Y25, no. 25, p. 411a5-7\n# CBETA, T14, no. 475, pp. 537c8-538a14\n# 模式0: 100, '100,3', t1000, t1000_001\n# TODO: T20n1113B\n# TODO: 大宝积经100\n# jinghaopatten = re.compile(r'([a-zA-Z]{1,2})(\\d{2,3})n(\\d{4})([a-zA-Z])?(?:_(\\d{3}))?(?:[_#](p\\d{4}[abc]\\d\\d))?')\njinghaopatten = re.compile(r'([a-zA-Z]{1,2})(\\d{2,3})n(\\d{4})(?:_(\\d{3}))?(?:[_#](p\\d{4}[abc]\\d\\d))?')\njinghaopatten2 = re.compile(r'([a-zA-Z]{1,2})(\\d{2,3}),\\s*no\\.\\s*(\\d+),\\s*pp?\\.\\s*(\\d+)([abc])(\\d+)')\njinghaopatten0 = re.compile(r'([a-zA-Z]{1,2})?(\\d+)[ \\t,._\\u3000\\u3002\\uff0c-]+(\\d+)') # 全角逗号句号\n# jinghaopatten0 = re.compile(r'([\\u3007\\u3400-\\u9FCB\\U00020000-\\U0002EBE0]+)[ \\t,._\\u3000\\u3002\\uff0c-]*(\\d+)')\ndef make_url(title):\n j1, j2, j3, j4, j5 = 'T', '', '', '', ''\n # j1, j2, j3, j4, j5\n # T, 01, 0001, 001, p0001a01\n # j6如果是小写就变为大写, 大写就变成小写\n # j6 = j6.upper() if ord('a') <= ord(j6) <= ord('z') else j6.lower()\n found = False\n if not found:\n jinghao = jinghaopatten.findall(title)\n if jinghao:\n j1,j2,j3,j4,j5 = jinghao[0]\n found = True\n\n if not found:\n jinghao = jinghaopatten2.findall(title)\n if jinghao:\n j1,j2,j3,j5,j6,j7 = jinghao[0]\n j5 = 'p{:04}{}{:02}'.format(int(j5), j6, int(j7))\n found = True\n\n if not found:\n jinghao = jinghaopatten0.findall(title)\n if jinghao:\n j1,j3,j4 = jinghao[0]\n found = True\n\n if title.isdigit():\n j3 = '{:04}'.format(int(title))\n found = True\n\n if not found:\n return None\n\n j1 = j1.upper() if j1 else 'T'\n j3 = '{:04}'.format(int(j3))\n # 查找册数 # TODO: 根据锚来查找册数\n if not j2:\n for line in sch_db:\n if j1 in line and j3 in line:\n j2 = line.split('n')[0][len(j1):]\n break\n if not j2:\n return None\n\n # 查找卷数\n if not j4:\n j4 = get_all_juan(f'{j1}{j2}n{j3}')\n if j4:\n j4 = j4[0]\n\n if not j4:\n return None\n\n j4 = '{:03}'.format(int(j4))\n # 如果有锚就添加锚\n if j5:\n url = f'xml/{j1}{j2}/{j1}{j2}n{j3}_{j4}.xml#{j5}'\n else:\n url = f'xml/{j1}{j2}/{j1}{j2}n{j3}_{j4}.xml'\n return url\n\n\n# FROM: https://en.wikipedia.org/wiki/International_Alphabet_of_Sanskrit_Transliteration\n\n# FROM: https://en.wikipedia.org/wiki/Harvard-Kyoto\nclass SA:\n '''梵语字符串类, 可以使用HK转写和iast转写输入, 使用天城体, 悉檀体, 拉丁输出'''\n pass\n\ndef hk2iastdeve(str_in):\n '''hk哈佛-京都系统转IAST梵语(天城体)'''\n sonorants = {\n # Sonorants:\n 'RR': 'ॠ',\n 'lR': 'ऌ',\n 'lRR': 'ॡ ',\n }\n\n t1 = {\n # Anusvāra and visarg:\n 'aM': 'अं',\n 'aH': 'अः',\n # Consonants:\n 'ai': 'ऐ',\n 'au': 'औ',\n 'kh': 'ख',\n 'gh': 'घ',\n 'ch': 'छ',\n 'jh': 'झ',\n 'ph': 'फ',\n 'Th': 'ठ',\n 'Dh': 'ढ',\n 'th': 'थ',\n 'dh': 'ध',\n 'bh': 'भ',\n }\n\n t2 = {\n 'R': 'ऋ',\n # Vowels:\n 'a': 'अ',\n 'A': 'आ', # ā\n 'i': 'इ',\n 'I':'ई',\n 'u': 'उ',\n 'U':'ऊ',\n 'e': 'ए',\n 'o': 'ओ',\n\n # Consonants:\n 'k': 'क',\n 'g': 'ग',\n 'G': 'ङ',\n 'c': 'च',\n 'j': 'ज',\n 'J': 'ञ',\n 'T': 'ट',\n 'D': 'ड',\n 'N': 'ण',\n 't': 'त',\n 'd': 'द',\n 'n': 'न',\n 'p': 'प',\n 'b': 'ब',\n 'm': 'म',\n 'y': 'य',\n 'r': 'र',\n 'l': 'ल',\n 'v': 'व',\n 'z': 'श',\n 'S': 'ष',\n 's': 'स',\n 'h': 'ह',\n }\n\n # '@':' ',\n\n # usedt = {ord(k): ord(t1[k]) for k in t1}\n str_out = str_in.replace('RR', sonorants['RR']).replace('lR', sonorants['lR']).replace('lRR', sonorants['lRR'])\n for zi in t1:\n str_out = str_out.replace(zi, t1[zi])\n for zi in t2:\n str_out = str_out.replace(zi, t2[zi])\n # str_out = str_out.translate(usedt)\n return str_out\n\n\ndef hk2iast(str_in):\n '''hk哈佛-京都系统转IAST梵语'''\n x = {'S':'sh',\n 'RR':'\\u1e5b\\u012b'} # 1e5d\n # 'RR':'\\u1e5d'} # 1e5d\n # 'lR':'\\u1eca'} # 1e5d\n # 'lRR':'\\u1e39'} # 1e5d\n\n t1 = {'A': '\\u0101', # ā\n 'I':'\\u012b',\n 'U':'\\u016b',\n 'M':'\\u1e43', # 1e43\n 'H':'\\u1e25',\n 'G':'\\u1e45',\n 'J':'\\u00f1',\n 'T':'\\u1e6d',\n 'D':'\\u1e0d',\n 'N':'\\u1e47',\n 'L':'\\u1eca', # Ị\n 'z':'\\u1e61',\n '@':' ',\n 'R':'\\u1e5b', # ṛ\n 'S':'\\u1e63', #\n }\n\n t2 = {'A': '\\u0101',\n 'I':'\\u012b',\n 'U':'\\u016b',\n 'M':'\\u1e49', # 1e49\n 'H':'\\u1e25',\n 'G':'\\u1e45',\n 'J':'\\u00f1',\n 'T':'\\u1e6d',\n 'D':'\\u1e0d',\n 'N':'\\u1e47',\n 'L':'\\u1eca',\n 'z':'\\u1e61',\n '@':' ',\n }\n\n usedt = {ord(k): ord(t1[k]) for k in t1}\n str_out = str_in.replace('RR', '\\u1e5d').replace('lR', '\\u1eca').replace('lRR', '\\u1e39')\n str_out = str_out.translate(usedt)\n return str_out\n\nhk2sa = hk2iast\n\ndef HKdict2iast(hkdict):\n # 将HK系统梵文词典转为IAST系统梵文词典\n mwpatten = re.compile(r'(%\\{.+?})')\n sa_en = dict()\n # for key in data:\n # k = key.replace('1', '').replace(\"'\", '').replace('4', '').replace('7', '').replace('8', '').replace('9', '').replace('0', '').replace('-', '').lower()\n # sa_en.update({k: data[key]})\n\n for key in hkdict:\n vals = hkdict[key]\n devkey = hk2iastdeve(key)\n key = hk2iast(key) # .replace('1', '').replace(\"'\", '').replace('4', '').replace('7', '').replace('8', '').replace('9', '').replace('0', '').replace('-', '') #.lower()\n # 将天城体附加在罗马体后面\n key = ' '.join((key, devkey))\n res = []\n for val in vals:\n x = mwpatten.findall(val)\n if x:\n for ff in x:\n val = val.replace(ff, hk2iast(ff))\n res.append(val)\n # 不知道以下这两行那个对\n sa_en.update({key: res})\n return sa_en\n\n\ndef load_dict(dictionary=None):\n\n # 词典列表\n dicts = {'fk': ('佛光山', 'fk.json.gz'), 'dfb': ('丁福保', 'dfb.json.gz'), 'ccc': ('庄春江', 'ccc.json'), 'fxcd': ('法相詞典', 'fxcd.json.gz'),\n 'nvd': ('南山律学词典', 'nvd.json.gz'), 'cyx': ('佛學常見詞彙(陳義孝)', 'cyx.json'), 'ylb': ('唯识名词白话新解', 'ylb.json'),\n 'szfs': ('三藏法数', 'szfs.json'), 'fymyj': ('翻譯名義集', 'fymyj.json'), 'wdhy': ('五燈會元', 'wdhy.json.gz'), 'yzzj': ('閱藏知津', 'yzzj.json.gz'),\n 'ldms': ('歷代名僧辭典', 'ldms.json.gz'), 'syfy': ('俗語佛源', 'syfy.json.gz'), 'bkqs': ('中华佛教百科全书','bkqs.json.gz')}\n\n aio = dict()\n\n # 装入梵英词典, 太大了,暂时不装了\n mwpatten = re.compile(r'(%\\{.+?})')\n sa_en = dict()\n\n # s = time.time()\n # with gzip.open('dict/sa-en.json.gz') as fd:\n # data = fd.read()\n # data = json.loads(data)\n # sa_en = dict()\n # for key in data:\n # k = key.replace('1', '').replace(\"'\", '').replace('4', '').replace('7', '').replace('8', '').replace('9', '').replace('0', '').replace('-', '').lower()\n # sa_en.update({k: data[key]})\n #\n # for key in data:\n # vals = data[key]\n # res = []\n # for val in vals:\n # x = mwpatten.findall(val)\n # if x:\n # for ff in x:\n # val = val.replace(ff, hk2sa(ff))\n # res.append(val)\n # # 不知道以下这两行那个对\n # sa_en.update({hk2sa(key, 1): res})\n # sa_en.update({hk2sa(key, 2): res})\n # e = time.time()\n # print('装入梵英词典,用时%s' % (e - s))\n yield ('sa_en', sa_en)\n\n sa_hant = dict()\n # s = time.time()\n # with gzip.open('dict/sa-hant.json.gz') as fd:\n # data = fd.read()\n # data = json.loads(data)\n # for key in data:\n # sa_hant.update({key.lower(): data[key]})\n # e = time.time()\n # print('装入梵汉词典,用时%s' % (e - s))\n yield ('sa_hant', sa_hant)\n\n yat = dict()\n # s = time.time()\n # with gzip.open('dict/yat.json.gz') as fd:\n # data = fd.read()\n # data = json.loads(data)\n # for key in data:\n # yat.update({key.lower(): data[key]})\n # for key in data:\n # vals = data[key]\n # res = []\n # for val in vals:\n # x = mwpatten.findall(val)\n # if x:\n # for ff in x:\n # v = val.replace(ff, hk2sa(ff))\n # res.append(v)\n # yat.update({hk2sa(key, 1): res})\n # yat.update({hk2sa(key, 2): res})\n # e = time.time()\n # print('装入Yates梵英词典,用时%s' % (e - s))\n yield ('yat', yat)\n\n s = time.time()\n with gzip.open('dict/kangxi.json.gz') as fd:\n kangxi = json.load(fd)\n e = time.time()\n print('装入康熙字典,用时%s' % (e - s))\n yield ('kangxi', kangxi)\n\n s = time.time()\n with open('dict/Unihan_Readings.json') as fd:\n unihan = json.load(fd)\n e = time.time()\n print('装入Unicode10.0字典,用时%s' % (e - s))\n yield ('unihan', unihan)\n\n for k in dicts:\n s = time.time()\n path = f'dict/{dicts[k][1]}'\n if not os.path.exists(path):\n continue\n\n if path.endswith('gz'):\n with gzip.open(path) as fd:\n try:\n v = json.load(fd)\n except:\n print(path)\n raise\n else:\n with open(path, encoding='utf8') as fd:\n v = json.load(fd)\n # for k1 in v:\n # if k1 in aio:\n # aio[k1].update({dicts[k][0]: v[k1]})\n # # aio[k1].append()\n # else:\n # aio[k1] = {dicts[k][0]: v[k1]}\n e = time.time()\n print('装入%s,用时%s' % (dicts[k][0], e - s))\n yield (k, v)\n\n yield ('aio', aio)\n\n # return {'kangxi':kangxi, 'unihan':unihan,\n # 'fk':fk, 'dfb': dfb, 'ccc': ccc, 'nvd': nvd, 'cxy': cxy, 'ylb': ylb, 'fxcd': fxcd,\n # 'szfs': szfs, 'fymyj': fymyj,\n # 'sa_hant': sa_hant, 'sa_en': sa_en, 'yat': yat}\n\n\n\ndef lookinkangxi(word):\n '''查询康熙字典'''\n\n def sub(word):\n definition = []\n _from = \"\"\n pinyin = \"\"\n if word in kangxi:\n _from = \"康熙字典\"\n kxword = kangxi[word]\n if \"說文解字\" in kxword:\n definition.append(kxword[\"說文解字\"])\n if \"康熙字典\" in kxword:\n definition.append(kxword[\"康熙字典\"])\n if \"宋本廣韻\" in kxword:\n definition.append(kxword[\"宋本廣韻\"])\n if definition:\n definition = '

'.join(definition)\n else:\n definition = kxword.get('英文翻譯', '')\n pinyin = kxword.get('國語發音', '')\n else:\n _from = \"unicode\"\n definition = unihan.get(word, {}).get('kDefinition', '')\n pinyin = unihan.get(word, {}).get('kMandarin', '')\n return pinyin, definition, _from\n\n pinyin, definition, _from = sub(word)\n\n if not pinyin:\n word2 = normyitizi(word)\n pinyin, definition, _from = sub(word2)\n if definition:\n definition = f'同{word2}
' + definition\n return {'word': word, 'pinyin': pinyin, 'def': definition, 'from': _from}\n\n\ndef lookinsa(word):\n definition = sa_hant.get(hk2sa(word).lower(), '')\n pinyin = \"\"\n _from = \"\"\n if definition:\n _from = \"文理学院\"\n pinyin = \"文理学院\"\n if not definition:\n # 使用Harvard-Kyoto转写查找字典\n definition = sa_en.get(hk2sa(word), '')\n # 使用缩写查找字典\n if not definition:\n w = word.replace('1', '').replace(\"'\", '').replace('4', '').replace('7', '').replace('8', '').replace('9', '').replace('0', '').replace('-', '').lower()\n definition = sa_en.get(w, '')\n if definition:\n definition = '|'.join(definition)\n _from = \"威廉梵英词典\"\n pinyin = \"威廉梵英词典\"\n if not definition:\n print(hk2sa(word))\n definition = yat.get(hk2sa(word), '')\n if not definition:\n w = word.replace('-', '').lower()\n definition = yat.get(w, '')\n if definition:\n definition = '|'.join(definition)\n _from = \"YAT\"\n pinyin = \"YAT\"\n return {'word': word, 'pinyin': pinyin, 'def': definition, 'from': _from}\n\n\n# 装入各种词典\ndd = dict(load_dict())\nsa_hant = dd['sa_hant']\nsa_en = dd['sa_en']\nyat = dd['yat']\nkangxi = dd['kangxi']\nunihan = dd['unihan']\nfk = dd['fk']\ndfb = dd['dfb']\nccc = dd['ccc']\nnvd = dd['nvd']\ncyx = dd['cyx']\nylb = dd['ylb']\nfxcd = dd['fxcd']\nszfs = dd['szfs']\nfymyj = dd['fymyj']\nwdhy = dd['wdhy']\nldms = dd['ldms']\nyzzj = dd['yzzj']\nbkqs = dd['bkqs']\n\n# aio = dd['aio']\n\ndef lookup(word, dictionary=None, lang='hant', mohu=False):\n '''查字典, dictionary=None表示所有词典, lang表示被查询的语言'''\n pt = re.compile(r'\\[|\\]|\\d') # 应该在前端过滤\n word = pt.sub('', word)\n print('发过来一个字:%s' % word)\n\n if TSDinst.detect(word)['confidence'] == 's':\n word = convert2t(word)\n\n pinyin = ''\n _from = ''\n definition = ''\n if word in fk:\n _from = \"佛光山\"\n definition = fk[word]\n elif word in dfb:\n _from = dfb[word][0]['usg']\n definition = '丁福保[{}]'.format(dfb[word][0]['def'])\n elif word in fxcd:\n _from = \"朱芾煌\"\n elif word in ccc:\n _from = \"莊春江\"\n definition = ccc[word]\n elif word in nvd:\n _from = \"南山律\"\n definition = nvd[word]\n elif word in cyx:\n _from = \"陈义孝\"\n definition = cyx[word]\n elif word in ylb:\n _from = \"于凌波\"\n definition = ylb[word]\n elif word in szfs:\n _from = \"三藏法数\"\n definition = szfs[word]\n elif word in fymyj:\n _from = \"翻譯名義集\"\n definition = fymyj[word]\n elif word in wdhy:\n _from = \"五燈會元\"\n definition = wdhy[word]\n elif word in ldms:\n _from = \"歷代名僧辭典\"\n definition = ldms[word]\n elif word in yzzj:\n _from = \"閱藏知津\"\n definition = yzzj[word]\n elif word in bkqs:\n _from = \"百科全书\"\n definition = bkqs[word]\n\n pinyin = ' '.join(lookinkangxi(zi)['pinyin'] for zi in word)\n\n if not _from and mohu:\n pass\n\n return {'word': word, 'pinyin': pinyin, 'definition': definition, 'from': _from}\n\n\nclass Search:\n def __init__(self, norm=True):\n mulu = read_menu_file(\"static/sutra_sch.lst\")\n #pprint.pprint(m['T 大正藏'])\n # d = mulu['T 大正藏']\n def walk(d, result=[]):\n '''遍历目录树'''\n for x in d:\n if not d[x]:\n result.append(x)\n else:\n walk(d[x], result)\n return result\n\n\n result = walk(mulu)\n import pprint\n result = [i.split(maxsplit=2) for i in result]\n if norm:\n titles = [(i[0], ' '.join((normyitizi(i[1]), i[2]))) for i in result]\n else:\n titles = [(i[0], ' '.join((i[1], i[2]))) for i in result]\n # pprint.pprint(titles)\n # titles 是经号和title的对照表\n # 生成索引表\n self.index = {}\n for i in titles:\n z = 0\n #print(i)\n for j in i[1]:\n if j in self.index:\n self.index[j].append((i[0], z))\n else:\n self.index[j] = [(i[0], z),]\n #print(j, i[0], z)\n z += 1\n for i in self.index:\n # print(i)\n v = self.index[i]\n r = dict()\n for j in v:\n if j[0] in r:\n r[j[0]].append(j[1])\n else:\n r[j[0]] = [j[1],]\n # pprint.pprint((i, r))\n self.index.update({i: r})\n self.titles = dict(titles)\n\n def search(self, title, norm=True):\n # title = opencc.convert(title, config='s2t.json')\n # ( for zi in index)\n if norm:\n title = normyitizi(title)\n result = (set(self.index.get(tt, {}).keys()) for tt in list(title))\n return sorted(reduce(lambda x, y: x & y, result), key=pagerank)\n\n\n\n# 简体繁体转换\ndef re_search(pattern, string):\n '''对re模块search的改进;把输入字符串使用pattern分割, 每个字符串附带一个标志,表示该字符串是否短语匹配'''\n rr = pattern.search(string)\n if not rr:\n yield (string, False)\n return\n # raise StopIteration()\n start, end = rr.span()\n if start !=0:\n yield (string[0:start], False)\n yield (string[start:end], True)\n while True:\n string = string[end:]\n rr = pattern.search(string)\n if not rr: break\n start, end = rr.span()\n if start !=0:\n yield (string[0:start], False)\n yield (string[start:end], True)\n\n if string:\n yield (string, False)\n\n\ndef __init_cc__():\n '''读取简体繁体转换数据库'''\n # 读取繁体转简体短语词典\n tsptable = readdb('cc/TSPhrases.txt')\n # 读取简体转繁体短语词典\n stptable = readdb('cc/STPhrases.txt')\n # # print('|'.join(sorted(tsptable.keys(), key=lambda x: len(x), reverse=True)))\n # 读取繁体转简体字典\n tstable = readdb('cc/TSCharacters.txt', trans=True)\n # 读取简体转繁体字典\n sttable = readdb('cc/STCharacters.txt', trans=True)\n\n # 简体繁体转换pattern\n tsp = re.compile('|'.join(tsptable.keys()))\n stp = re.compile('|'.join(stptable.keys()))\n\n return tsp, tstable, tsptable, stp, sttable, stptable\n\ntsp, tstable, tsptable, stp, sttable, stptable = __init_cc__()\n\n\ndef convert2s(string, punctuation=True, region=False, autonorm=True, onlyURO=True):\n '''繁体转简体, punctuation是否转换单双引号\n region 是否执行区域转换\n region 转换后的地区\n autonorm 自动规范化异体字\n onlyURO 不简化低位类推简化字(繁体字处于BMP和扩展A区, 但是简体字处于扩展B,C,D,E,F的汉字)\n '''\n if autonorm:\n string = normyitizi(string)\n\n if punctuation:\n string = string.translate({0x300c: 0x201c, 0x300d: 0x201d, 0x300e: 0x2018, 0x300f: 0x2019})\n\n # 类推简化字处理\n tst2 = copy.deepcopy(tstable)\n if onlyURO:\n # 只要简化字不在BMP,就是类推简化字\n # tst2 = {k:tstable[k] for k in tstable if not (k < 0x20000 and tstable[k] > 0x20000)}\n # tst2 = {k:tstable[k] for k in tstable if 0x4E00 <= tstable[k] < 0x20000}\n tst2 = {k:tstable[k] for k in tstable if 0x4E00 <= tstable[k] < 0x9FA5}\n else:\n tst2 = {k:tstable[k] for k in tstable}\n\n content = ''.join(i[0].translate(tst2) if not i[1] else tsptable[i[0]] for i in re_search(tsp, string))\n\n return content\n\n\ndef convert2t(string, punctuation=True, region=False):\n '''简体转繁体, punctuation是否转换单双引号\n region 是否执行区域转换\n region 转换后的地区\n '''\n\n if punctuation:\n string = string.translate({0x201c: 0x300c, 0x201d: 0x300d, 0x2018: 0x300e, 0x2019: 0x300f})\n\n content = ''.join(i[0].translate(sttable) if not i[1] else stptable[i[0]] for i in re_search(stp, string))\n\n return content\n\n# 简体繁体转换结束\n\n# 异体字处理\n\n# 读入异体字对照表\nyitizi = readdb('dict/variants.txt', True, True)\n# 读取异体字短语词典\nvarptable = readdb('variants/p.txt')\n# 异体字转换pattern\nvarppp = re.compile('|'.join(varptable.keys()))\n\ndef normyitizi(string, level=0):\n '''异体字规范化为标准繁体字'''\n # string = string.translate(yitizi)\n # return string\n content = ''.join(i[0].translate(yitizi) if not i[1] else varptable[i[0]] for i in re_search(varppp, string))\n return content\n\n\ndef zi_order(ss, ct):\n '''判断ss字符��中的字是否按照顺序在ct字符串中出现'''\n rr = dict()\n for i, zi in enumerate(ct):\n if zi in rr:\n rr[zi].add(i)\n else:\n rr[zi] = {i}\n\n result = []\n for zi in ss:\n if zi not in rr:\n return False\n else:\n result.append(rr[zi])\n\n start = -1\n for i in result:\n start = {j for j in i if j > start}\n if not start:\n return False\n else:\n start = min(start)\n return True\n\ndef highlight(ss, ct):\n for zi in set(ss):\n ct = ct.replace(zi, f'{zi}')\n return ct\n\n# pun = string.punctuation + '\\u00b7\\u2013-\\u2027\\u2e3a\\u3000-\\u301f\\ufe30-\\ufe6b\\uff01-\\uff0f\\uff1a-\\uff5e'\n# pun = re.compile('['+string.punctuation+']')\n# 读取标点数据库\npun = dict()\nwith open('dict/punctuation.txt') as fd:\n for line in fd:\n line = line.strip()\n if not line: continue\n c1 = line[0]\n pun[ord(c1)] = ord(' ')\n\ndef hanziin(sentence='', content=''):\n '''判断一段话中是否包含一句话'''\n # 1. 去除标点符号\n sentence = sentence.translate(pun).replace(' ', '')\n content = content.translate(pun).replace(' ', '')\n return sentence in content\n\ndef pagerank(filename, sentence='', content=''):\n '''对xml文件名评分, filename 为 T20n1060 或者 T20n1060_001.xml 形式\n A,B,C,D,F,G,GA,GB,I,J,K,L,M,N,P,S,T,U,X,ZW, Y, LC\n '''\n # sentence = sentence.strip().split()\n # sentence_value = sum([{True:0, False:1}[s in content] for s in sentence])\n pr = (\"T\", \"B\", \"ZW\", \"A\", \"C\", \"D\", \"F\", \"G\" , \"GA\", \"GB\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"P\", \"S\", \"U\", \"X\", \"Y\", \"LC\")\n pt = re.compile(r'\\d+') # 应该在前端过滤\n if filename[0] == 'T':\n r = 0\n else:\n r = 1\n x = pt.findall(filename)\n x = [int(i) for i in x]\n # return r, x[0], x[1], x[2]\n x.insert(0, r)\n # x.insert(0, sentence_value)\n return x\n\n\ndef search_title(title):\n '''通过标题搜索'''\n if request.method == \"GET\":\n title = request.GET.title\n # 去除HTML标签、注释、卷数, 留下标题\n title = re.sub(r'<.*?>', '', title) # title=[34]差末菩薩經\n title = re.sub(r'\\(.*?\\)', '', title)\n title = re.sub(r'\\[\\w*?\\]', '', title)\n title = re.sub(r'[一二三四五六七八九十百]+卷', '', title)\n else:\n title = request.forms.content\n if ts.detect(title)['confidence'] == 's':\n # title = opencc.convert(title, config='s2t.json')\n title = convert2t(title)\n results = []\n if not title:\n return {'results': results}\n for idx in ss.search(title):\n title0 = idx\n hl = ss.titles[idx]\n zang = idx.split('n')[0] # T01\n juan = get_all_juan(idx)[0] # 001\n an = f\"/xml/{zang}/{idx}_{juan}.xml\" # T01n0002_001.xml\n results.append({'hl': hl, 'an':an, 'title':title0, 'author':''})\n if request.method == \"GET\":\n # 0个结果页面不动, 多个结果自己选择\n if len(results) == 0:\n abort(304)\n if len(results) == 1:\n redirect(an)\n if len(results) > 1:\n pass\n return {'results': results}\n\n\n\ndef fullsearch(sentence):\n '''全文搜索'''\n sentence2 = sentence.replace('\\u3000', ' ').split()\n # 去除标点符号\n sentence = sentence.translate(pun).replace(' ', '')\n url = \"http://127.0.0.1:9200/cbeta/fulltext/_search\"#创建一个文档,如果该文件已经存在,则返回失败\n data = {\n \"query\": {\n \"match\": {\n \"content\": sentence,\n },\n },\n \"size\":5000,\n \"from\":0,\n \"highlight\": {\n \"fields\": {\n \"content\": {\n\n }\n }\n }\n}\n\n\n r = requests.get(url, json=data, timeout=10)\n hits = r.json()['hits']['hits']\n result = []\n for i in hits:\n _source = i[\"_source\"]\n author = _source['author'].split('\\u3000')[0]\n juan = _source[\"filename\"].split('n')[0]\n # 文章内容去除标点符号\n ctx = _source['content'].translate(pun).replace(' ', '')\n # result.append((''.join(i['highlight']['content']), f'/xml/{juan}/{_source[\"filename\"]}#{_source[\"pid\"]}', _source['title'], author))\n # if zi_order(sentence, _source['content']):\n if all(stc in ctx for stc in sentence2):\n result.append({'hl': highlight(sentence, _source['content']), 'an': f'/xml/{juan}/{_source[\"filename\"]}#{_source[\"pid\"]}',\n 'title':_source['title'], 'author': author, 'content': _source['content'],\n 'filename': _source[\"filename\"].split('.')[0]})\n\n result.sort(key=lambda x: pagerank(x['filename'])) #, sentence, x['content']))\n # pprint.pprint(('||'.join(_source['content']), f'/xml/{juan}/{_source[\"filename\"]}#{_source[\"pid\"]}', _source['title'], author))\n\n return result\n\n\nwith gzip.open('dict/cipin.json.gz') as fd:\n cipind = json.load(fd)\n\ndef zhuyin(txt, ruby=False, cipin=50):\n '''對txt文本注音, ruby是否使用ruby語法'''\n if not ruby:\n content = ' '.join(lookinkangxi(i)['pinyin'].split(' ')[0] for i in txt)\n else:\n result = []\n for zi in txt:\n if cipind.get(zi, 0) < cipin:\n pinyin = lookinkangxi(zi)['pinyin'].split(' ')[0]\n if pinyin:\n zi = f\"{zi}{pinyin}\"\n result.append(zi)\n content = ''.join(result)\n return content\n\ndef main():\n ''''''\n ss = Search()\n title = '成唯识论'\n import opencc\n title = opencc.convert(title, config='s2t.json')\n s = time.time()\n ss.search(title)\n e = time.time()\n print(e-s)\n for idx in ss.search(title):\n print(idx, ss.titles[idx])\n\n\nimport difflib\nfrom difflib import *\n\ndef diff_ctx(lctx, rctx):\n '''比较两个文本的不同, 使用html排版'''\n\n d = Differ()\n result = d.compare(lctx, rctx)\n\n lctx = []\n rctx = []\n for line in result:\n if line.startswith(' '):\n line = line[2:]\n lctx.append(line)\n rctx.append(line)\n elif line.startswith('- '):\n line = line[2:]\n lctx.append(f'{line}')\n elif line.startswith('+ '):\n line = line[2:]\n rctx.append(f'{line}')\n elif line.startswith('?'):\n continue\n lctx = ''.join(lctx)\n rctx = ''.join(rctx)\n # lctx = ''.join(f'

{line}

' for line in lctx.splitlines())\n # rctx = ''.join(f'

{line}

' for line in rctx.splitlines())\n\n return {'lfile': lctx, 'rfile': rctx}\n\n\ndef test():\n ''''''\n print(normyitizi('妬'))\n\nif __name__ == \"__main__\":\n # main()\n # test()\n # print(get_all_juan('T02n0099'))\n # print(get_all_juan('GA031n0032'))\n # print(get_all_juan('J31nB269'))\n # print(get_all_juan('T19n0974A'))\n # print(get_next_page('T02n0099_001'))\n # print(get_next_page('T01n0002_001'))\n\n # with gzip.open('dict/kangxi.json.gz') as fd:\n # kangxi = json.load(fd)\n\n # with open('cipin.json') as fd:\n # cipin = json.load(fd)\n\n # for word in kangxi:\n # kxword = kangxi[word]\n # pinyin = kxword.get('國語發音', '')\n # if not pinyin:\n # word2 = normyitizi(word)\n # kxword2 = kangxi.get(word2, {})\n # pinyin2 = kxword2.get('國語發音', '')\n # if pinyin2:\n # # print(word, word2, pinyin2)\n # pass\n # else:\n # cp = cipin.get(word, 0)\n # if cp > 0:\n # print(word, word2, cipin.get(word, 0), \"%X\" % ord(word))\n # pass\n # print(pagerank('T14n0563_001.xml'))\n # print(zhuyin('你好', True))\n # print(lookinkangxi('𢾛'))\n\n # ctx = '五九種命終心三界生各潤生心各有三故已上'\n # print(rm_ditto_mark(ctx))\n #str_in = \"a-kAra\"\n #print(hk2iast(str_in))\n #print(hk2iastdeve(str_in))\n # print(convert2t('大佛顶'))\n # ss = Search()\n # for idx in ss.search('大佛頂'):\n # print(idx)\n # # TODO:搜索t1000, t1000_001, T01n0001, T01n0001_001, T01n0001_p0001a01, T01,no.1,p.1a1\n #titlepatten = re.compile(r'([a-zA-Z][a-zA-Z]?)(\\d\\dn)?(\\d\\d\\d\\d)(_\\d\\d\\d)?')\n #titlepatten.find('t1000')\n #import pprint\n #with open(\"static/sutra_sch.lst\") as fd:\n # for line in fd:\n # if 'n' in line:\n # line = line.strip().split()\n # print(line)\n #pprint.pprint(mulu)\n print(make_url('CBETA, T14, no. 475, pp. 537c8-538a14'))\n print(make_url('CBETA 2019.Q2, Y25, no. 25, p. 411a5-7'))\n\n\n","sub_path":"libhan.py","file_name":"libhan.py","file_ext":"py","file_size_in_byte":39840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"557278003","text":"import os\n\nimport torch\nfrom torchvision.utils import save_image\n\nfrom src import hyperparameters as hyperparams\nfrom src import settings\n\n\ndef betterCallback(epoch, gen, enc, dloader):\n torch.save(enc.state_dict(), settings.encModelPath)\n print('A better model has been found and has been serialized into fs')\n\n with torch.no_grad():\n batchiter = iter(dloader)\n batch = next(batchiter)\n fileinds = batch['fileind'].to(settings.device).view(-1)\n images = batch['image'].to(device=settings.device, dtype=torch.float32)\n assert len(fileinds) >= settings.samplesLen\n\n for i in range(settings.samplesLen):\n fileind = fileinds[i]\n image = images[i].unsqueeze_(0)\n fake = gen(enc(image).view(1, hyperparams.latentDim, 1, 1))\n filename = f'epoch-{epoch}-ind-{fileind.item()}.png'\n filepath = os.path.join(settings.encProgressPath, filename)\n save_image(fake[0], filepath)\n\n\ndef totalLoss(embed, enc, dloader, dsize, criterion):\n loss = .0\n processed = 0\n\n with torch.no_grad():\n for batch in dloader:\n inds = batch['ind'].to(settings.device).view(-1)\n images = batch['image'].to(device=settings.device, dtype=torch.float32)\n\n processed += len(images)\n loss += criterion(embed(inds), enc(images)).item() * images.size(0)\n loss /= dsize\n return loss, processed\n","sub_path":"src/training/trainEncAux.py","file_name":"trainEncAux.py","file_ext":"py","file_size_in_byte":1439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"305733651","text":"import const.const as ic\nfrom sqlalchemy import create_engine\n\n\nscott = ic.config[\"user\"]\ntiger = ic.config[\"password\"]\nhost = ic.config[\"host\"]\nbind = 'mysql+mysqlconnector://' + scott + ':' + tiger + '@' + host + ':3306/smwj'\nengine = create_engine(bind)\n\n\nitem_price = \"select a.item\" \\\n \" , a.tran_day\" \\\n \" , a.close\" \\\n \" from price a\" \\\n \" where a.item = '{item}'\" \\\n \" and a.tran_day between '{sdate}' and '{edate}';\"\n\nmulti_item_price = \"select a.tran_day\" \\\n \" , a.close as '{item}'\" \\\n \" from price a\" \\\n \" where a.item = '{item}'\" \\\n \" and a.tran_day between '{sdate}' and '{edate}';\"\n\nmoney = \"select tran_day\" \\\n \" , kospi_close\" \\\n \" , volume\" \\\n \" , deposit\" \\\n \" , credit_bal\" \\\n \" , depo_futures\" \\\n \" , stock\" \\\n \" , bond\" \\\n \" , tbill\" \\\n \" , mmf\" \\\n \" from market_liquidity\" \\\n \" where tran_day between '{sdate}' and '{edate}'\"\n\nmarket_index_tr_amt = \"select a.tran_day\" \\\n \" , b.kospi_close\" \\\n \" , a.inst\" \\\n \" , a.fore\" \\\n \" from market_index_tr_amt a\" \\\n \" join market_liquidity b\" \\\n \" on a.tran_day = b.tran_day\" \\\n \" where a.item = '{item}'\" \\\n \" and a.tran_day between '{sdate}' and '{edate}'\"\n\nfore_tr_amt = \"select a.tran_day\" \\\n \" , b.kospi_close\" \\\n \" , a.fore\" \\\n \" from market_index_tr_amt a\" \\\n \" join market_liquidity b\" \\\n \" on a.tran_day = b.tran_day\" \\\n \" where a.item = '{item}'\" \\\n \" and a.tran_day between '{sdate}' and '{edate}'\"\n\nkospi_liq = \"select a.tran_day\" \\\n \" , a.kospi_close\" \\\n \" , case when a.diff_rate < 0 then a.diff * -1\" \\\n \" else a.diff\" \\\n \" end as diff\" \\\n \" , a.diff_rate\" \\\n \" , a.volume\" \\\n \" , a.deposit\" \\\n \" , a.deposit_diff\" \\\n \" , a.roll_rate\" \\\n \" , a.credit_bal\" \\\n \" , a.credit_rest\" \\\n \" , a.depo_futures\" \\\n \" , a.stock\" \\\n \" , a.mix_stock\" \\\n \" , a.mix_bond\" \\\n \" , a.bond\" \\\n \" , a.mmf\" \\\n \" from market_liquidity a\" \\\n \" where tran_day > '20140101';\"\n\n\nmagic = \"select a.tran_day\" \\\n \" , a.kospi_close\" \\\n \" , case when a.diff_rate < 0 then a.diff * -1\" \\\n \" else a.diff\" \\\n \" end as diff\" \\\n \" , a.diff_rate\" \\\n \" , a.volume\" \\\n \" , a.mmf\" \\\n \" , b.kospi_fore\" \\\n \" , b.kospi_inst\" \\\n \" , c.futures_fore\" \\\n \" , c.futures_inst\" \\\n \" , d.fx_close\" \\\n \" from market_liquidity a\" \\\n \" join (\" \\\n \" select aa.tran_day\" \\\n \" , aa.fore as kospi_fore\" \\\n \" , aa.inst as kospi_inst\" \\\n \" from market_index_tr_amt aa\" \\\n \" where item = 'kospi'\" \\\n \" ) b\" \\\n \" on a.tran_day = b.tran_day\" \\\n \" join (\" \\\n \" select bb.tran_day\" \\\n \" , bb.fore as futures_fore\" \\\n \" , bb.inst as futures_inst\" \\\n \" from market_index_tr_amt bb\" \\\n \" where item = 'futures'\" \\\n \" ) c\" \\\n \" on a.tran_day = c.tran_day\" \\\n \" join (\" \\\n \" select cc.tran_day\" \\\n \" , cc.close as fx_close\" \\\n \" from market_index cc\" \\\n \" where cc.item = 'USDKRWSMBS'\" \\\n \" ) d\" \\\n \" on a.tran_day = d.tran_day\" \\\n \" where a.tran_day between '20140101' and '20171231';\"\n","sub_path":"smwjsql/query.py","file_name":"query.py","file_ext":"py","file_size_in_byte":4165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"529372890","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script fle.\n\"\"\"\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nimg = cv2.imread(\"/Users/stutishukla/Downloads/proj1_cse573/task1.png\", cv2.IMREAD_GRAYSCALE)\n\nlist_img = list(img)\nlist_img = [list(row) for row in list_img]\n\nimg = cv2.imread(\"/Users/stutishukla/Downloads/proj1_cse573/task1.png\", cv2.IMREAD_GRAYSCALE)\na = np.asarray(img)\nsobelW, sobelH = 3, 3\nsobelData = [[0 for x in range(sobelW)] for y in range(sobelH)]\nsobelData[0][0] = -1\nsobelData[0][1] = -2\nsobelData[0][2] = -1\nsobelData[1][0] = 0\nsobelData[1][1] = 0\nsobelData[1][2] = 0\nsobelData[2][0] = 1\nsobelData[2][1] = 2\nsobelData[2][2] = 1\n\nimageH=len(img)\nimageW=len(img[0])\n\nupdatedImageData = [[0 for x in range(imageW)] for y in range(imageH)]\n\ndef calculateSobelat(widthindex , heightindex):\n\n result = 0;\n for i in range(sobelH):\n for j in range(sobelW):\n currentWidthIndex = widthindex-1+j\n currentHeightIndex = heightindex-1+i\n\n if((currentHeightIndex<0) or (currentHeightIndex >= imageH)):\n continue\n\n if ((currentWidthIndex < 0) or (currentWidthIndex >= imageW)):\n continue\n\n result += (a[currentHeightIndex][currentWidthIndex]*sobelData[i][j])\n\n return result\n\ndef getDimensions(a):\n \n matHeight = len(a)\n if (matHeight == 0):\n return matHeight, matHeight\n matWidth = len(a[0])\n return matHeight, matWidth\n\n\ndef normalizeImage(updatedImage):\n \n imgHeight, imgWidth = getDimensions(updatedImage)\n updatedImagenorm = [[0 for x in range(imgWidth)] for y in range(imgHeight)]\n \n for i in range(imgHeight):\n for j in range(imgWidth):\n updatedImagenorm[i][j] = 128 + int(updatedImage[i][j]/2)\n return updatedImagenorm\n\nfor i in range(imageH):\n for j in range(imageW):\n currentWidthOffset = j\n currentHeightOffset = i\n sobelValue = calculateSobelat(currentWidthOffset,currentHeightOffset)\n updatedImageData[i][j] = sobelValue\nimage=normalizeImage(updatedImageData)\n\n#print(updatedImageData)\ngradY=np.asarray(image)\ncv2.imwrite('/Users/stutishukla/Downloads/Result/task1/GradientY.png',gradY)\n\n\n \n\n\n \n \n \n \n \n","sub_path":"Project1/Task I/GradientY.py","file_name":"GradientY.py","file_ext":"py","file_size_in_byte":2280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"258982878","text":"from __future__ import print_function\nimport zipfile\nimport os\nfrom skimage import io, color, exposure, transform\nimport torchvision.transforms as transforms\nfrom keras.preprocessing.image import *\nimport numpy as np\n# once the images are loaded, how do we pre-process them before being passed into the network\n# by default, we resize the images to 32 x 32 in size\n# and normalize them to mean = 0 and standard-deviation = 1 based on statistics collected from\n# the training set\n\nto_numpy = lambda im: np.array(im)\ntransform_random_shift = lambda im: random_shift(im, 0.1, 0.1)\ntransform_random_rotation = lambda im: random_rotation(im, 10.0)\ntransform_random_shear = lambda im: random_shear(im, 0.1)\ntransform_random_zoom = lambda im: random_zoom(im, 0.2)\nIMG_SIZE = 48\n\ndef preprocess_img(img):\n # Histogram normalization in y \n img = np.array(img) \n #print(img.shape)\n hsv = color.rgb2hsv(img)\n hsv[:,:,2] = exposure.equalize_hist(hsv[:,:,2])\n img = color.hsv2rgb(hsv)\n\n # central scrop\n min_side = min(img.shape[:-1])\n centre = img.shape[0]//2, img.shape[1]//2\n img = img[centre[0]-min_side//2:centre[0]+min_side//2,\n centre[1]-min_side//2:centre[1]+min_side//2,\n :]\n img = transform.resize(img, (IMG_SIZE, IMG_SIZE)) \n #img = np.rollaxis(img,-1) \n #print(img.shape)\n \n return img\n\n\ndata_transforms = transforms.Compose([ \n transforms.Lambda(preprocess_img),\n transforms.Lambda(transform_random_shift), \n transforms.Lambda(transform_random_zoom),\n transforms.Lambda(transform_random_shear), \n transforms.Lambda(transform_random_rotation),\n transforms.ToTensor(),\n transforms.Normalize((0.3337, 0.3064, 0.3171), ( 0.2672, 0.2564, 0.2629))\n])\n#transforms.Normalize((0.3337, 0.3064, 0.3171), ( 0.2672, 0.2564, 0.2629))\nval_data_transforms = transforms.Compose([\n transforms.Lambda(preprocess_img),\n transforms.ToTensor(),\n transforms.Normalize((0.3337, 0.3064, 0.3171), ( 0.2672, 0.2564, 0.2629))\n ])\n\ndef initialize_data(folder):\n train_zip = folder + '/train_images.zip'\n test_zip = folder + '/test_images.zip'\n if not os.path.exists(train_zip) or not os.path.exists(test_zip):\n raise(RuntimeError(\"Could not find \" + train_zip + \" and \" + test_zip\n + ', please download them from https://www.kaggle.com/c/nyu-cv-fall-2017/data '))\n # extract train_data.zip to train_data\n train_folder = folder + '/train_images'\n if not os.path.isdir(train_folder):\n print(train_folder + ' not found, extracting ' + train_zip)\n zip_ref = zipfile.ZipFile(train_zip, 'r')\n zip_ref.extractall(folder)\n zip_ref.close()\n # extract test_data.zip to test_data\n test_folder = folder + '/test_images'\n if not os.path.isdir(test_folder):\n print(test_folder + ' not found, extracting ' + test_zip)\n zip_ref = zipfile.ZipFile(test_zip, 'r')\n zip_ref.extractall(folder)\n zip_ref.close()\n\n # make validation_data by using images 00000*, 00001* and 00002* in each class\n val_folder = folder + '/val_images'\n if not os.path.isdir(val_folder):\n print(val_folder + ' not found, making a validation set')\n os.mkdir(val_folder)\n for dirs in os.listdir(train_folder):\n if dirs.startswith('000'):\n os.mkdir(val_folder + '/' + dirs)\n for f in os.listdir(train_folder + '/' + dirs):\n if f.startswith('00000') or f.startswith('00001') or f.startswith('00002'):\n # move file to validation folder\n os.rename(train_folder + '/' + dirs + '/' + f, val_folder + '/' + dirs + '/' + f)\n","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":3711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"346884880","text":"import numpy as np\nimport networkx as nx\nimport random\nimport math\n\nSTEPS = 50\nREPEAT = 20\nP = 0 # prob. of allowing to return to the last node\ngraph_path = \"data/randomGraph.txt\"\ncontext_path = \"data/random_50w_20r_0p_ln.txt\"\nfull_graph_path = \"data/randomFull.txt\"\noriginal_emb_path = \"data/MelbOriginal.emb\"\ngraph_type=\"UNWEIGHTED\" #UNWEIGHTED or WEIGHTED\n\nclass MyGraph:\n\n def __init__(self,graph_path):\n\n graph_data=np.loadtxt(graph_path,unpack=False,delimiter=' ')\n self.graph=nx.Graph()\n edges=[]\n if graph_type==\"UNWEIGHTED\":\n for data in graph_data:\n edges.append((int(data[0]), int(data[1]), float(data[2])))\n else:\n for data in graph_data:\n edges.append((int(data[0]),int(data[1]),1))\n self.graph.add_weighted_edges_from(edges)\n self.num_nodes=self.graph.number_of_nodes()\n self.num_edges=self.graph.number_of_edges()\n self.nodes=self.graph.nodes()\n self.edges=self.graph.edges()\n print ('number of nodes:'+ str(self.num_nodes))\n print ('number of edges:'+str(self.num_edges))\n\n def generate_contexts(self,context_path):\n contexts=[]\n count=0\n for node in self.nodes:\n count+=1\n print (\"num\"+str(count))\n for i in range(REPEAT):\n walks=[]\n current_node=node\n last_node=None\n walks.append(node)\n for j in range(STEPS):\n neighbrs = dict()\n sum_weights = 0\n back_rand=random.uniform(0, 1)\n for n in self.graph.neighbors(current_node):\n if back_rand>P and n==last_node: #can't go back to the last node\n continue\n weight = self.graph[current_node][n]['weight']\n\n # weight=math.e**(-1*weight) #normalize weight by e ** (-weight)\n # weight=1/weight #normalize weight by 1/weight\n weight=1/math.log(weight) #normalize weight by 1/ln(weight)\n\n sum_weights+=weight\n neighbrs[n]=weight\n\n random_num=random.uniform(0,sum_weights) #get one random value between (0,sum_weights)\n accumulate=0\n for (n,weight) in neighbrs.items():# start to find the corresponding node.\n accumulate+=weight\n if random_num <=accumulate: # if accumulate is larger than random value, we find it!\n last_node=current_node\n current_node=n\n break\n walks.append(current_node)\n\n contexts.append(walks)\n\n np.savetxt(context_path,contexts,fmt='%d',delimiter=' ')\n\n def generate_full(self,full_graph_path):\n full_graph = dict(nx.all_pairs_dijkstra_path_length(self.graph))\n full_data=[]\n\n for node in self.nodes:\n print(\"node: \"+str(node))\n for neighbr in self.nodes:\n if node>=neighbr:\n continue\n print (neighbr)\n full_data.append([node,neighbr,full_graph[node][neighbr]])\n\n np.savetxt(full_graph_path, full_data, fmt='%d %d %f', delimiter=' ')\n\n def generate_original_emb(self,original_emb_path):\n full_graph = dict(nx.all_pairs_dijkstra_path_length(self.graph))\n original_emb=[]\n\n for source in self.nodes:\n emb_data=[]\n emb_data.append(source)\n for end in self.nodes:\n emb_data.append(full_graph[source][end])\n original_emb.append(emb_data)\n\n np.savetxt(original_emb_path, original_emb,fmt=' '.join(['%d'] + ['%f']*self.num_nodes), delimiter=' ')\n\n\nif __name__==\"__main__\":\n\n # graph=MyGraph(graph_path)\n # graph.generate_original_emb(original_emb_path)\n # graph.generate_full(full_graph_path)\n full_graph = MyGraph(full_graph_path)\n full_graph.generate_contexts(context_path)\n\n\n\n","sub_path":"CreateContexts.py","file_name":"CreateContexts.py","file_ext":"py","file_size_in_byte":4150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"127785439","text":"#!/usr/bin/env python\n\nimport datetime\nimport json\nimport os\n\nfrom config import VIOLATIONS_TABLE, METADATA_TABLE, RULES_SCHEMA, VIOLATION_QUERY_POSTFIX, CLOUDWATCH_METRICS\nfrom helpers.db import connect_and_fetchall, connect_and_execute, load_rules\nfrom helpers import log\n\nRUN_METADATA = {'QUERY_HISTORY': [], 'RUN_TYPE': 'VIOLATION QUERIES'} # Contains metadata about this run\n\n\ndef log_alerts(ctx, alerts):\n output_column = os.environ.get('output_column', 'result')\n time_column = os.environ.get('time_column', 'alert_time')\n\n if len(alerts):\n ctx.cursor().execute(\n f\"\"\"\n INSERT INTO {VIOLATIONS_TABLE} ({time_column}, {output_column})\n SELECT PARSE_JSON(column1):ALERT_TIME,\n PARSE_JSON(column1)\n FROM VALUES {\", \".join([\"(%s)\"] * len(alerts))};\n \"\"\",\n alerts\n )\n\n\ndef snowalert_query(query_name):\n time_filter_unit = os.environ.get('time_filter_unit', 'day')\n time_filter_amount = -1 * int(os.environ.get('time_filter_amount', 1))\n\n log.info(f\"{query_name} processing...\")\n\n ctx, results = connect_and_fetchall(f\"\"\"\n SELECT OBJECT_CONSTRUCT(*) FROM {RULES_SCHEMA}.{query_name}\n WHERE alert_time > DATEADD({time_filter_unit}, {time_filter_amount}, CURRENT_TIMESTAMP())\n \"\"\")\n\n log.info(f\"{query_name} done.\")\n return results, ctx\n\n\ndef process_results(results, ctx, query_name, metadata):\n alerts = []\n for res in results:\n jres = json.loads(res[0])\n alerts.append(json.dumps(jres))\n log.metadata_fill(metadata, status='success', rows=ctx.cursor().rowcount)\n log_alerts(ctx, alerts)\n\n\ndef run_query(query_name):\n metadata = {}\n metadata['NAME'] = query_name\n metadata['START_TIME'] = datetime.datetime.utcnow()\n results, ctx = snowalert_query(query_name)\n process_results(results, ctx, query_name, metadata)\n RUN_METADATA['QUERY_HISTORY'].append(metadata)\n\n\ndef record_metadata(ctx, metadata):\n metadata['RUN_START_TIME'] = str(metadata['RUN_START_TIME']) # We wantd them to be objects for mathing\n metadata['RUN_END_TIME'] = str(metadata['RUN_END_TIME']) # then convert to string for json serializing\n metadata['RUN_DURATION'] = str(metadata['RUN_DURATION'])\n\n statement = f'''\n INSERT INTO {METADATA_TABLE}\n (event_time, v) select '{metadata['RUN_START_TIME']}',\n PARSE_JSON(column1) from values('{json.dumps(metadata)}')\n '''\n try:\n log.info(\"Recording run metadata.\")\n ctx.cursor().execute(statement)\n except Exception as e:\n log.fatal(\"Metadata failed to log\", e)\n # log_failure(ctx, \"Metadata Logging\", e, event_data=metadata, description=\"The run metadata failed to log\")\n\n\ndef main():\n # Force warehouse resume so query runner doesn't have a bunch of queries waiting for warehouse resume\n RUN_METADATA['RUN_START_TIME'] = datetime.datetime.utcnow()\n ctx = connect_and_execute(\"ALTER SESSION SET use_cached_result=FALSE;\")\n for query_name in load_rules(ctx, VIOLATION_QUERY_POSTFIX):\n run_query(query_name)\n\n RUN_METADATA['RUN_END_TIME'] = datetime.datetime.utcnow()\n RUN_METADATA['RUN_DURATION'] = RUN_METADATA['RUN_END_TIME'] - RUN_METADATA['RUN_START_TIME']\n record_metadata(ctx, RUN_METADATA)\n if CLOUDWATCH_METRICS:\n log.metric('Run', 'SnowAlert', [{'Name': 'Component', 'Value': 'Violation Query Runner'}], 1)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/runners/violation_queries_runner.py","file_name":"violation_queries_runner.py","file_ext":"py","file_size_in_byte":3484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"371890315","text":"from collections import namedtuple\nfrom django.core import paginator\nfrom django.shortcuts import render, redirect\nfrom django.http import HttpResponse, request\nfrom django.urls import reverse\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.decorators import login_required\nfrom rango.models import Category, MovieLists, Page, UserProfile,MovieCol,MovieLiked,WebsiteLiked\nfrom rango.forms import CategoryForm, PageForm, UserForm, UserProfileForm\nfrom datetime import datetime\nfrom django.core.paginator import PageNotAnInteger, Paginator,EmptyPage\nimport requests\nfrom django.contrib.auth.models import User\nfrom django.utils.decorators import method_decorator\nfrom django.views import View\n\ndef index(request):\n category_list = Category.objects.order_by('-likes')[:5]\n page_list = Page.objects.order_by('-views')[:5]\n\n context_dict = {}\n context_dict['boldmessage'] = 'Crunchy, creamy, cookie, candy, cupcake!'\n context_dict['categories'] = category_list\n context_dict['pages'] = page_list\n context_dict['extra'] = 'From the model solution on GitHub'\n \n visitor_cookie_handler(request)\n\n return render(request, 'rango/index.html', context=context_dict)\n\ndef about(request):\n context_dict = {}\n visitor_cookie_handler(request)\n context_dict['visits'] = request.session['visits']\n\n return render(request, 'rango/about.html', context=context_dict)\n\ndef thank_you(request):\n\n return render(request, 'rango/thank_you.html')\n\ndef show_category(request, category_name_slug):\n context_dict = {}\n\n try:\n category = Category.objects.get(slug=category_name_slug)\n pages = Page.objects.filter(category=category)\n\n context_dict['pages'] = pages\n context_dict['category'] = category\n except Category.DoesNotExist:\n context_dict['pages'] = None\n context_dict['category'] = None\n \n return render(request, 'rango/category.html', context=context_dict)\n\n@login_required\ndef add_category(request):\n form = CategoryForm()\n\n if request.method == 'POST':\n form = CategoryForm(request.POST)\n\n if form.is_valid():\n form.save(commit=True)\n return redirect(reverse('rango:index'))\n else:\n print(form.errors)\n \n return render(request, 'rango/add_category.html', {'form': form})\n\n@login_required\ndef add_page(request, category_name_slug):\n try:\n category = Category.objects.get(slug=category_name_slug)\n except:\n category = None\n \n # You cannot add a page to a Category that does not exist... DM\n if category is None:\n return redirect(reverse('rango:index'))\n\n form = PageForm()\n\n if request.method == 'POST':\n form = PageForm(request.POST)\n\n if form.is_valid():\n if category:\n page = form.save(commit=False)\n page.category = category\n page.views = 0\n page.save()\n\n return redirect(reverse('rango:show_category', kwargs={'category_name_slug': category_name_slug}))\n else:\n print(form.errors) # This could be better done; for the purposes of TwD, this is fine. DM.\n \n context_dict = {'form': form, 'category': category}\n return render(request, 'rango/add_page.html', context=context_dict)\n\n@login_required\ndef restricted(request):\n return render(request, 'rango/restricted.html')\n\ndef get_server_side_cookie(request, cookie, default_val=None):\n val = request.session.get(cookie)\n if not val:\n val = default_val\n return val\n\ndef visitor_cookie_handler(request):\n visits = int(get_server_side_cookie(request, 'visits', '1'))\n last_visit_cookie = get_server_side_cookie(request, 'last_visit', str(datetime.now()))\n last_visit_time = datetime.strptime(last_visit_cookie[:-7], '%Y-%m-%d %H:%M:%S')\n\n if (datetime.now() - last_visit_time).days > 0:\n visits = visits + 1\n request.session['last_visit'] = str(datetime.now())\n else:\n request.session['last_visit'] = last_visit_cookie\n \n request.session['visits'] = visits\n\n#This function fetches the entire list of movies for a logged in user\n@login_required\ndef show_movies(request):\n fileredpage =\"\"\n if 'q' in request.GET:\n q=request.GET['q']\n #if read from the database, order the movie by its imdbrating\n fileredpage=MovieLists.objects.filter(title__icontains=q).order_by('-imdbrating')\n print(q) \n else:\n fileredpage=MovieLists.objects.all().order_by('-imdbrating')\n\n #make sure it reads from the API when the database is empty\n if(MovieLists.objects.count()==0):\n result = requests.get('https://imdb-api.com/en/API/IMDbList/k_6x2ikd97/ls004285275')\n myjson=result.json()\n \n\n MovieLists.objects.all().delete()\n \n for item in myjson['items']:\n MovieLists.objects.create(movieid=item['id'], \n title=item['title'], fullTitle=item['fullTitle'], \n yearreleased=item['year'], imgpath=item['image'],\n imdbrating=item['imDbRating'],description=item['description'])\n\n \n myresult = {\"count\": MovieLists.objects.count(), \"page\": MovieLists.objects.all().values()}\n \n else:\n myresult=fileredpage\n \n #code for pagination\n paginator=Paginator(myresult,16)\n page=request.GET.get('page')\n\n try:\n page = paginator.page(page)\n except PageNotAnInteger:\n page = paginator.page(1)\n except EmptyPage:\n page=paginator.page(paginator.num_pages) \n \n myresult ={\n 'count':paginator.count,\n 'page': page\n } \n\n return render(request, 'rango/movie_mini.html', myresult )\n \n \n\n#This function fetches the selected movie detail information for a authenticated user\n@login_required\ndef movie_detail(request,movieid):\n print(request.user)\n movie=MovieLists.objects.get(movieid=movieid)\n movie.save()\n username = request.POST.get('username') \n myresult ={\n 'username': username,\n 'movie': movie\n } \n return render(request, 'rango/movie_detail.html', myresult )\n\nclass RegisterProfileView(View):\n @method_decorator(login_required)\n def get(self, request):\n form = UserProfileForm()\n context_dict = {'form': form}\n return render(request, 'rango/profile_registration.html', context_dict)\n\n @method_decorator(login_required)\n def post(self, request):\n form = UserProfileForm(request.POST, request.FILES)\n\n if form.is_valid():\n user_profile = form.save(commit=False)\n user_profile.user = request.user\n user_profile.save()\n\n return redirect(reverse('rango:index'))\n else:\n print(form.errors)\n\n context_dict = {'form': form}\n return render(request, 'rango/profile_registration.html', context_dict)\n\nclass ProfileView(View):\n def get_user_details(self, username):\n try:\n user = User.objects.get(username=username)\n except User.DoesNotExist:\n return None\n\n user_profile = UserProfile.objects.get_or_create(user=user)[0]\n form = UserProfileForm({'picture': user_profile.picture},\n {'age': user_profile.age},\n {'location': user_profile.location})\n \n return (user, user_profile, form)\n \n @method_decorator(login_required)\n def get(self, request, username):\n try:\n (user, user_profile, form) = self.get_user_details(username)\n except TypeError:\n return redirect(reverse('rango:index'))\n \n context_dict = {'user_profile': user_profile,\n 'selected_user': user,\n 'form': form}\n \n return render(request, 'rango/profile.html', context_dict)\n \n @method_decorator(login_required)\n def get(self, request, username):\n try:\n (user, user_profile, form) = self.get_user_details(username)\n except TypeError:\n return redirect(reverse('rango:index'))\n\n context_dict = {'user_profile': user_profile,\n 'selected_user': user,\n 'form': form}\n\n return render(request, 'rango/profile.html', context_dict)\n\n @method_decorator(login_required)\n def post(self, request, username):\n try:\n (user, user_profile, form) = self.get_user_details(username)\n except TypeError:\n return redirect(reverse('rango:index'))\n\n form = UserProfileForm(request.POST, request.FILES, instance=user_profile)\n\n if form.is_valid():\n form.save(commit=True)\n return redirect(reverse('rango:profile',\n kwargs={'username': username}))\n else:\n print(form.errors)\n\n context_dict = {'user_profile': user_profile,\n 'selected_user': user,\n 'form': form}\n\n return render(request, 'rango/profile.html', context_dict)\n\nclass ColMovie(View):\n @method_decorator(login_required)\n def post(self,request):\n if not request.user.is_authenticated:\n return render(request,'login.html')\n #get the movie_id from the front end\n movie_id=request.POST.get(\"movie_id\")\n print(movie_id)\n find_movies=MovieCol.objects.filter(user=request.user,movie_id=movie_id).count()\n print(find_movies)\n #if haven't add this movie then push it to the database\n if find_movies<1:\n print(find_movies)\n fav_movie=MovieCol(user=request.user,movie_id=movie_id)\n fav_movie.save()\n #if =1 means there is already one been created\n else:\n #remove from database if already add this movie\n MovieCol.objects.filter(user=request.user,movie_id=movie_id).delete()\n return HttpResponse(\"well done\")\n\nclass LikeMovie(View):\n @method_decorator(login_required)\n def post(self,request):\n if not request.user.is_authenticated:\n return render(request, 'login.html')\n #get the movie_id from the front end\n movie_id=request.POST.get(\"movie_id\")\n print(movie_id)\n #check how many instance are created for the same movie\n find_movies=MovieLiked.objects.filter(user=request.user,movie_id=movie_id).count()\n #if <1 means haven't been created and load into the database\n if find_movies<1:\n print(find_movies)\n fav_movie=MovieLiked(user=request.user,movie_id=movie_id)\n fav_movie.save()\n #if =1 means there is already one been created\n else:\n #remove from database if already add this movie\n MovieLiked.objects.filter(user=request.user,movie_id=movie_id).delete()\n return HttpResponse(\"it's done\")\n\n@login_required \ndef MyWatchList(request):\n print(\"Hello\")\n #filter all collected movie to show in the watchlist\n col_movies=MovieCol.objects.filter(user=request.user)\n print(col_movies)\n print(\"HELL NO\")\n return render(request,'rango/watchlist.html',{\"col_movies\":col_movies})\n\n@login_required\ndef MyLikedMovies(request):\n print(\"Liked\")\n #filter all collected movie to show in the watchlist\n like_movies=MovieLiked.objects.filter(user=request.user)\n print(like_movies)\n print(\"No\")\n return render(request, 'rango/likedlist.html',{\"like_movies\":like_movies})\n \nclass LikeCategoryView(View):\n @method_decorator(login_required)\n def get(self, request):\n category_liked = request.GET['category_liked']\n print(category_liked)\n websitelikes=WebsiteLiked.objects.get_or_create(id=1)[0]\n websitelikes.likes=websitelikes.likes+1\n websitelikes.save()\n\n return HttpResponse(websitelikes.likes)\n \n \n","sub_path":"tango_with_django_project/rango/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"446636816","text":"from ROOT import TFile, TTree, TCut\nfrom Jawa import *\nfrom PlotTools import *\nfrom Utils import Bunch\n\nf = TFile(\"/user2/sfarry/lhcb/DaVinciDev_v42r1/Rkst/options/bjpsik.root\")\nt = f.Get(\"VeloCaloTuple/DecayTree\")\n\neid = TCut(\"abs(piplus_TRUEID) == 11 && piplus_TRUEID*piplus_ID < 0\")\npiid = TCut(\"abs(piplus_TRUEID) == 211 && piplus_TRUEID*piplus_ID > 0\")\nunmatch = TCut(\"piplus_TRUEID == 0\")\n\nbunches = [\n Bunch(name='ptres', var='(piplus_PT - piplus_TRUEPT) / piplus_TRUEPT', bins = 100, lo = -0.5, hi = 0.5, xlabel = 'p_{T}(rec) - p_{T}(true) / p_{T}(true)'),\n Bunch(name='ER', var = 'piplus_EcalClusterEt/piplus_PT', bins = 100, lo = 0, hi = 2, xlabel = 'CaloEt/pt'),\n Bunch(name='EHcalP', var = 'piplus_CaloHcalE/piplus_P', bins = 100, lo = 0, hi = 1.0, xlabel = 'HcalE/P', logy = True, ylims = [0.001, 1.0]),\n Bunch(name='velochi2ndof', var = 'piplus_velo_chi2ndof', bins = 100, lo = 0, hi = 5, xlabel = '#chi^{2}/ndof (velo)'),\n Bunch(name='chi2ndof', var = 'piplus_TRACK_CHI2NDOF', bins = 100, lo = 0, hi = 3, xlabel = '#chi^{2}/ndof (velo-calo)')\n ]\n\nelectrons = Template(\"electrons\")\nelectrons.SetSelCut(eid)\nelectrons.AddTree(t)\nfor p in bunches:\n electrons.AddVar(p.name, p.var, p.bins, p.lo, p.hi)\nelectrons.Run()\n\npions = Template(\"pions\")\npions.SetSelCut(piid)\npions.AddTree(t)\nfor p in bunches:\n pions.AddVar(p.name, p.var, p.bins, p.lo, p.hi)\npions.Run()\n\nnomatch = Template(\"nomatch\")\nnomatch.SetSelCut(unmatch)\nnomatch.AddTree(t)\nfor p in bunches:\n nomatch.AddVar(p.name, p.var, p.bins, p.lo, p.hi)\nnomatch.Run()\n\n\nfrom Style import *\nSetLHCbStyle()\n\nfor b in bunches:\n d = Plot([electrons.GetVar(b.name).GetHist()])\n d.forceStyle()\n d.AutoYlims()\n if hasattr(b, 'xlabel'): d.setProp('xlabel', b.xlabel)\n d.setProp('ylabel', '[A.U.]')\n d.setProp('labels', ['Electrons'])\n d.setProp('colors', ['blue'])\n d.setProp('location', '/user2/sfarry/workspaces/rkst/figures')\n d.setProp('filename', 'electrons_'+b.name+'_mc2016.pdf')\n d.setProp('markerstyles', 20)\n d.setProp('leglims', [0.65, 0.7, 0.9, 0.9])\n d.setProp('normalised', True)\n if hasattr(b, 'shiftlegx'): d.ShiftLegX(b.shiftlegx)\n if hasattr(b, 'shiftlegy'): d.ShiftLegY(b.shiftlegy)\n d.drawROOT()\n\n e = Plot([pions.GetVar(b.name).GetHist()])\n if e.name=='ptres': e.plots[0].Fit('gaus')\n e.forceStyle()\n e.AutoYlims()\n if hasattr(b, 'xlabel'): e.setProp('xlabel', b.xlabel)\n e.setProp('ylabel', '[A.U.]')\n e.setProp('labels', ['Pions'])\n e.setProp('colors', ['red'])\n e.setProp('normalised', True)\n e.setProp('location', '/user2/sfarry/workspaces/rkst/figures')\n e.setProp('filename', 'pions_'+b.name+'_mc2016.pdf')\n e.setProp('markerstyles', 20)\n e.setProp('leglims', [0.65, 0.7, 0.9, 0.9])\n if hasattr(b, 'shiftlegx'): e.ShiftLegX(b.shiftlegx)\n if hasattr(b, 'shiftlegy'): e.ShiftLegY(b.shiftlegy)\n e.drawROOT()\n\n ff = Plot([nomatch.GetVar(b.name).GetHist()])\n ff.forceStyle()\n ff.AutoYlims()\n if hasattr(b, 'xlabel'): ff.setProp('xlabel', b.xlabel)\n ff.setProp('ylabel', '[A.U.]')\n ff.setProp('labels', ['Unmatched'])\n ff.setProp('colors', ['orange'])\n ff.setProp('normalised', True)\n ff.setProp('location', '/user2/sfarry/workspaces/rkst/figures')\n ff.setProp('filename', 'nomatch_'+b.name+'_mc2016.pdf')\n ff.setProp('markerstyles', 20)\n ff.setProp('leglims', [0.65, 0.7, 0.9, 0.9])\n if hasattr(b, 'shiftlegx'): ff.ShiftLegX(b.shiftlegx)\n if hasattr(b, 'shiftlegy'): ff.ShiftLegY(b.shiftlegy)\n ff.drawROOT()\n\n ff = Plot([electrons.GetVar(b.name).GetHist(), pions.GetVar(b.name).GetHist(), nomatch.GetVar(b.name).GetHist()])\n ff.forceStyle()\n ff.AutoYlims()\n if hasattr(b, 'xlabel'): ff.setProp('xlabel', b.xlabel)\n ff.setProp('ylabel', '[A.U.]')\n ff.setProp('labels', ['Electrons', 'Pions', 'Unmatched'])\n ff.setProp('colors', ['blue', 'red', 'orange'])\n ff.setProp('normalised', True)\n ff.setProp('location', '/user2/sfarry/workspaces/rkst/figures')\n ff.setProp('filename', 'alltracks_'+b.name+'_mc2016.pdf')\n ff.setProp('markerstyles', 20)\n ff.setProp('leglims', [0.65, 0.7, 0.9, 0.9])\n if hasattr(b, 'logy'):\n ff.setProp('logscale', b.logy)\n ff.AutoYlims(scale = 1.5, ylow = 0.001)\n if hasattr(b, 'shiftlegx'): ff.ShiftLegX(b.shiftlegx)\n if hasattr(b, 'shiftlegy'): ff.ShiftLegY(b.shiftlegy)\n ff.drawROOT()\n\n","sub_path":"rkst/python/pt_res.py","file_name":"pt_res.py","file_ext":"py","file_size_in_byte":4419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"238590372","text":"#!/usr/bin/env python\n\nviz_enabled = True\nimport numpy as np\nimport utils as U\nfrom map_utils import cast_ray\n\ntry:\n import cv2\n from scipy.spatial import ConvexHull\nexcept ImportError as e:\n print('cv2/scipy import failed : {}'.format(e))\n print('visualization disabled.')\n viz_enabled = False\n\nclass GridMapper(object):\n def __init__(self, w, h, fw, fh, r=0.02):\n self._w = w\n self._h = h\n self._fw = fw\n self._fh = fh\n self._r = r\n\n #self._xs = np.linspace(-(w/2.0), w/2.0, num=np.ceil(w/r).astype(np.int32), endpoint=True)\n #self._ys = np.linspace(-(h/2.0), h/2.0, num=np.ceil(h/r).astype(np.int32), endpoint=True)\n\n # set to initial corner\n self._wlim = wlim = (w/2 - fw/2)\n self._hlim = hlim = (h/2 - fh/2)\n self._xpt = [-wlim + 0.02, -hlim + 0.02]\n self._ypt = [-wlim + 0.02, -hlim + 0.02]\n self._xfin = self._yfin = False\n\n # segment data\n self._xseg = []\n self._yseg = []\n\n def __call__(self, srv, map, fpt, viz=False, log=None):\n viz = (viz and viz_enabled) # check global viz flag\n\n if log is not None:\n log('{} : {}'.format(self._xpt, self._ypt))\n\n # unroll parameters / data\n n, m = map.shape[:2]\n xpt, ypt = self._xpt, self._ypt\n wlim, hlim = self._wlim, self._hlim\n w, h, r = self._w, self._h, self._r\n\n # check x\n if(xpt[0] >= wlim):\n xpt[1] += r\n xpt[0] = -wlim\n if(xpt[1] >= hlim):\n self._xfin = True\n if not self._xfin:\n xm = cast_ray(srv, xpt, [wlim, xpt[1]], a=np.pi/2, min_d=0.005)\n\n if not np.allclose(xpt, xm):\n if viz:\n # mark ...\n trace = fpt_hull(fpt, xpt, xm, a=np.pi/2)\n trace = U.xy2uv(trace, w, h, n, m)\n cv2.drawContours(map, [trace.T], 0, color=255, thickness=-1)\n\n #save\n self._xseg.append(np.copy([xpt, xm]))\n\n # set to next point\n xpt[0] = max(xpt[0]+r, xm[0]+r)\n\n # check y\n if(ypt[1] >= hlim):\n ypt[0] += r\n ypt[1] = -hlim\n if(ypt[0] >= wlim):\n self._yfin = True\n if not self._yfin:\n ym = cast_ray(srv, ypt, [ypt[0], hlim], a=0., min_d=0.005)\n\n if not np.allclose(ypt, ym):\n if viz:\n # mark ...\n trace = fpt_hull(fpt, ypt, ym, a=0.)\n trace = U.xy2uv(trace, w, h, map)\n cv2.drawContours(map, [trace.T], 0, color=255, thickness=-1)\n\n # save\n self._yseg.append(np.copy([ypt, ym]))\n\n # set to next point\n ypt[1] = max(ypt[1]+r, ym[1]+r)\n\n def done(self):\n return (self._xfin and self._yfin)\n\n def save(self, path='/tmp/segments.npy'):\n np.save(path, [self._xseg, self._yseg])\n","sub_path":"src/rll_planning_project/grid_mapper.py","file_name":"grid_mapper.py","file_ext":"py","file_size_in_byte":2976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"99564177","text":"import time\n\nimport numpy as np\nimport tensorflow as tf\nfrom keras.datasets import mnist\nfrom keras.layers import Conv2D, Conv2DTranspose, MaxPooling2D, Dense, Flatten, Reshape\nimport matplotlib.pyplot as plt\n\nfrom utils import get_minibatches_idx\n\n# Based on https://jmetzen.github.io/2015-11-27/vae.html\n# and https://github.com/fchollet/keras/blob/master/examples/variational_autoencoder_deconv.py\n\nn_samples = 60000\neps = 1e-10\nimg_size = 28\nnum_channels = 1\nnum_filters = 16\nembedding_size = 128\nbatch_size = 100\n\n# To do:\n# Evaluate on the validation set after each epoch\n\n\nclass VariationalAutoencoder(object):\n\t# See \"Auto-Encoding Variational Bayes\" by Kingma and Welling for more details\n\t\n\tdef __init__(self):\n\t\tself.x = tf.placeholder(tf.float32, [None, img_size, img_size, num_channels])\n\n\t\t# Encoder\n\t\th = Conv2D(1, kernel_size=(2,2),\n\t\t\t\tpadding='same', activation='relu')(self.x)\n\t\th = Conv2D(num_filters,\n\t\t\t\tkernel_size=(2,2),\n\t\t\t\tpadding='same', activation='relu',\n\t\t\t\tstrides=(2,2))(h)\n\t\th = Conv2D(num_filters,\n\t\t\t\tkernel_size=3,\n\t\t\t\tpadding='same', activation='relu',\n\t\t\t\tstrides=1)(h)\n\t\th = Conv2D(num_filters,\n\t\t\t\tkernel_size=3,\n\t\t\t\tpadding='same', activation='relu',\n\t\t\t\tstrides=1)(h)\n\t\th = Flatten()(h)\t\n\t\t\n\t\t# Encode as mean and variance vectors\n\t\tself.z_mean = Dense(embedding_size)(h)\n\t\tself.z_log_sigma_sq = Dense(embedding_size)(h)\n\n\t\t# Draw one sample z from Gaussian distribution\n\t\tnoise = tf.random_normal((batch_size, embedding_size), 0, 1, dtype=tf.float32)\n\t\t\n\t\t# Add noise\n\t\tself.z = self.z_mean + noise*tf.sqrt(tf.exp(self.z_log_sigma_sq))\n\n\t\t# Decoder\t\t\n\t\th = Dense(embedding_size, activation='relu')(self.z)\n\t\th = Dense(num_filters*(img_size//2)*(img_size//2), activation='relu')(h)\n\n\t\th = Reshape([img_size//2,img_size//2,num_filters])(h)\n\t\th = Conv2DTranspose(num_filters,\n\t\t\t\t\t\tkernel_size=3,\n\t\t\t\t\t\tpadding='same',\n\t\t\t\t\t\tstrides=1,\n\t\t\t\t\t\tactivation='relu')(h)\n\t\t\t\t\t\t\t\t\t\t \n\t\th = Conv2DTranspose(num_filters,\n\t\t\t\t\t kernel_size=3,\n\t\t\t\t\t padding='same',\n\t\t\t\t\t strides=1,\n\t\t\t\t\t activation='relu')(h)\n\n\t\th = Conv2DTranspose(num_filters,\n\t\t\t\t\t kernel_size=(3,3),\n\t\t\t\t\t strides=(2,2),\n\t\t\t\t\t padding='valid',\n\t\t\t\t\t activation='relu')(h)\n\t\t\t\t\t \n\t\tself.x_reconstr_mean = Conv2D(1, kernel_size=2,\n\t\t\t\t\tpadding='valid',\n\t\t\t\t\tactivation='sigmoid')(h)\n\t\t\n\t\treconstr_loss = -tf.reduce_sum(self.x * tf.log(eps + self.x_reconstr_mean)\n\t\t\t\t\t\t + (1-self.x) * tf.log(eps + 1 - self.x_reconstr_mean), [1,2,3])\n\t\t\t\n\t\t# KL-divergence\n\t\tlatent_loss = -0.5 * tf.reduce_sum(1 + self.z_log_sigma_sq \n\t\t\t\t\t\t\t\t\t\t - tf.square(self.z_mean) \n\t\t\t\t\t\t\t\t\t\t - tf.exp(self.z_log_sigma_sq), 1)\n\t\t\t\t\t\t\t\t\t\t \n\t\tself.cost = tf.reduce_mean(reconstr_loss + latent_loss) # average over batch\n\n\t\tself.train_step = tf.train.AdamOptimizer(learning_rate=0.001).minimize(self.cost)\n\n\t\tself.sess = tf.Session()\n\t\tself.sess.run(tf.global_variables_initializer())\n\n\n\tdef generate(self, z_mu=None):\n\t\tif z_mu is None:\n\t\t\tz_mu = [np.random.normal(size=embedding_size) for i in range(batch_size)]\t\t\t\n\t\treturn self.sess.run(self.x_reconstr_mean, feed_dict={self.z: z_mu})\n\t\n\n\tdef train(self, X, training_epochs=10):\n\t\tprint(\"\\nStarting training\")\n\t\t\n\t\tfor epoch in range(training_epochs):\n\t\t\tavg_cost = 0.0\n\t\t\ttrain_indices = get_minibatches_idx(len(X), batch_size, shuffle=True)\n\n\t\t\tfor it in train_indices:\n\t\t\t\tbatch_x = [X[i] for i in it]\n\t\t\t\t_, cost = self.sess.run((self.train_step, self.cost), feed_dict={self.x: batch_x})\n\t\t\t\t\n\t\t\t\tavg_cost += cost / n_samples * batch_size\n\n\t\t\tprint(\"Epoch:\", '%d' % (epoch+1), \"cost=\", \"{:.3f}\".format(avg_cost))\n\n\ndef main():\n\t# Load the data\n\t# It will be downloaded first if necessary\n\t(X_train, _), (X_test, _) = mnist.load_data()\n\t\n\tX_train = X_train.astype('float32')\n\tX_test = X_test.astype('float32')\n\tX_train = np.reshape(X_train,[-1,img_size,img_size,num_channels])\n\tX_test = np.reshape(X_test,[-1,img_size,img_size,num_channels])\n\tX_train /= 255\n\tX_test /= 255\n\t\n\tprint(X_train.shape[0], 'train samples')\n\tprint(X_test.shape[0], 'test samples')\n\n\tvae = VariationalAutoencoder()\n\tprint(\"Model compiled\")\t\t\t \n\t\t\t \n\tvae.train(X_train, training_epochs=20)\n\n\tx_sample = X_test[:100]\t\n\tx_gen = vae.generate()\n\t\n\tplt.figure(figsize=(8,12))\n\t\n\t# Show 5 generated images and 5 images from the test set\n\tfor i in range(5):\n\t\tplt.subplot(5, 2, 2*i + 1)\n\t\tplt.imshow(np.squeeze(x_sample[i]), vmin=0, vmax=1, cmap=\"gray\")\n\t\tplt.title(\"Test image\")\n\t\t\n\t\tplt.subplot(5, 2, 2*i + 2)\n\t\tplt.imshow(np.squeeze(x_gen[i]), vmin=0, vmax=1, cmap=\"gray\")\n\t\tplt.title(\"Generated image\")\n\t\t\n\tplt.tight_layout()\n\tplt.show()\n\t\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"556283477","text":"import abjad\n\n\nclass ScoreTemplate(object):\n\n def __call__(self):\n # Violin\n violin_voice = abjad.Voice()\n violin_staff = abjad.Staff([violin_voice], name='Violin Staff')\n # Viola\n viola_voice = abjad.Voice()\n viola_staff = abjad.Staff([viola_voice], name='Viola Staff')\n # Cello\n cello_voice = abjad.Voice()\n cello_staff = abjad.Staff([cello_voice], name='Cello Staff')\n # Everything else\n staff_group = abjad.StaffGroup([violin_staff, viola_staff, cello_staff])\n score = abjad.Score([staff_group])\n # Return the score\n return score\n","sub_path":"day-4/trio-refactored/ScoreTemplate.py","file_name":"ScoreTemplate.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"139367151","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri May 17 10:25:39 2019\r\n\r\n@author: Agustin Lopez Pedroso\r\n\"\"\"\r\nimport PyDAQmx\r\nfrom PyDAQmx import Task\r\nimport numpy as np\r\nimport time\r\n#value = 0\r\n#\r\n#task = Task()\r\n#task.CreateAOVoltageChan(\"Dev1/ao0\",\"\",-10.0,10.0,PyDAQmx.DAQmx_Val_Volts,None)\r\n#task.StartTask()\r\n#task.WriteAnalogScalarF64(1,10.0,value,None)\r\n#task.StopTask()\r\n\r\n\r\nclass FieldControl():\r\n # Librerías necesarias: PyDAQmx, numpy y time\r\n def __init__(self):\r\n # Inicilizo la comunicación con la placa DAQ, específicamente con el canal\r\n #de output para controlar la corriente del electroimán\r\n self.task = Task()\r\n self.task.CreateAOVoltageChan(\"Dev1/ao0\",\"\",-10.0,10.0,PyDAQmx.DAQmx_Val_Volts,None)\r\n self.vi = 0\r\n \r\n def set_voltage(self,voltage):\r\n # Inicio un task para establecer el valor de voltaje de salida en volts\r\n self.task.StartTask()\r\n self.task.WriteAnalogScalarF64(1,10.0,voltage,None)\r\n self.task.StopTask()\r\n self.vi = voltage\r\n \r\n def set_voltage_steps(self,vf,step=0.025):\r\n # Cambia el voltaje en pasos pequeños, es necesario poner el valor de voltaje\r\n #deseado vf y el voltaje inicial vi(mejorar para que lo tome solo)\r\n vaux = self.vi\r\n if vf > self.vi:\r\n while vaux < vf:\r\n self.task.StartTask()\r\n self.task.WriteAnalogScalarF64(1,10.0,vaux,None)\r\n self.task.StopTask()\r\n vaux = vaux + step\r\n time.sleep(0.5)\r\n else:\r\n while vaux > vf:\r\n self.task.StartTask()\r\n self.task.WriteAnalogScalarF64(1,10.0,vaux,None)\r\n self.task.StopTask()\r\n vaux = vaux - step\r\n time.sleep(0.5)\r\n self.task.StartTask()\r\n self.task.WriteAnalogScalarF64(1,10.0,vf,None)\r\n self.task.StopTask()\r\n self.vi = vf\r\n #print('Succes')\r\n \r\n ","sub_path":"All/Controlador_campo.py","file_name":"Controlador_campo.py","file_ext":"py","file_size_in_byte":1998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"288711452","text":"#1 -)ARRAYS\n# reversing numpy array\nimport numpy\n\n\ndef arrays(arr):\n return numpy.array(arr, float)[::-1]\n\n\narr = input().strip().split(' ')\nresult = arrays(arr)\nprint(result)\n\n#2 -)SHAPE AND RESHAPE\n# reshaping with reshape function\nimport numpy\n\nprint(numpy.array(list(map(int, input().rstrip().split()))).reshape(3, 3))\n\n#3 -)TRANSPOSE AND FLATTEN\n\nimport numpy\n\ninputs = input().rstrip().split()\nn = int(inputs[0])\nm = int(inputs[1])\norginallist = []\nfor i in range(n):\n orginallist.append(list(map(int, input().rstrip().split())))\n\nx = numpy.array(orginallist)\nprint(x.transpose(), x.flatten(), sep='\\n')\n\n#4 -)CONCATENATE\n\nimport numpy\n\ninputs = list(map(int, input().rstrip().split()))\nx = numpy.array([list(map(int, input().rstrip().split()))], dtype=numpy.int8)\nfor i in range(inputs[0] + inputs[1] - 1):\n y = numpy.array([list(map(int, input().rstrip().split()))])\n x = numpy.concatenate((x, y), axis=0)\n\nprint(x)\n\n#5 -)ZEROSANDONES\n\nimport numpy\n\ninputs = list(map(int, input().rstrip().split()))\n\nprint(numpy.zeros(inputs, dtype=numpy.int))\nprint(numpy.ones(inputs, dtype=numpy.int))\n\n#6 -)EYEANDIDENTITY\nimport numpy\n\n# by using replace function replace \"0\" by \" 0\"\nx = str(numpy.eye(*map(int, input().rstrip().split()), dtype=numpy.float)).replace(\"0\", \" 0\")\nprint(x.replace(\"1\", \" 1\"))\n\n#7 -)ARRAYMATHEMATICS\nimport numpy\n\nstring = input().rstrip().split()\nlist1 = []\nlist2 = []\nfor i in range(int(string[0])):\n [list1.append(int(item)) for item in input().rstrip().split()]\nfor i in range(int(string[0])):\n [list2.append(int(item)) for item in input().rstrip().split()]\n# convert list to numpy array and reshape by the input\nlist1 = numpy.array(list1, dtype=numpy.int).reshape((int(string[0]), int(string[1])))\nlist2 = numpy.array(list2, dtype=numpy.int).reshape((int(string[0]), int(string[1])))\n\nprint(list1 + list2)\nprint(list1 - list2)\nprint(list1 * list2)\nprint(list1 // list2)\nprint(list1 % list2)\nprint(list1 ** list2)\n\n#8 -)FLOOR, CEIL AND RINT\n\nimport numpy\n\ninputs = numpy.array(list(map(float, input().rstrip().split())))\nnumpy.set_printoptions(sign=\" \")\nprint(numpy.floor(inputs))\nprint(numpy.ceil(inputs))\nprint(numpy.rint(inputs))\n\n#9 -)SUM AND PROD\nimport numpy\n\ns, y = map(int, input().rstrip().split())\n# just with single line\nprint(numpy.product(numpy.sum(numpy.array([input().rstrip().split() for _ in range(s)], dtype=numpy.int), axis=0)))\n\n#10 -)MIN AND MAX\n\nimport numpy\n\ns, y = map(int, input().rstrip().split())\n# just with single line\nprint(numpy.max(numpy.min(numpy.array([input().split() for _ in range(s)], dtype=numpy.int), axis=1)))\n\n#11 -)MEAN, VAR, AND STD\n\nimport numpy\n\ns, y = map(int, input().rstrip().split())\n\nx = numpy.array([list(map(int, input().split())) for _ in range(s)])\n# for arranging printing numpy has set_printoption function\nnumpy.set_printoptions(sign=\" \")\n\nprint(numpy.mean(x, axis=1), numpy.var(x, axis=0), numpy.around(numpy.std(x), decimals=12), sep=\"\\n\")\n\n#12 -)DOT AND CROSS\nimport numpy\n\ns = int(input())\nx = numpy.array([list(map(int, input().split())) for _ in range(s)])\ny = numpy.array([list(map(int, input().split())) for _ in range(s)])\nprint(numpy.matmul(x, y))\n\n#13 -)INNER AND OUTER\n\nimport numpy\n\nx = numpy.array(list(map(int, input().split())))\ny = numpy.array(list(map(int, input().split())))\n\nprint(numpy.inner(x, y), numpy.outer(x, y), sep=\"\\n\")\n\n#14 -)Polynomials\nimport numpy\n\nprint(numpy.polyval(list(map(float, input().split())), int(input())))\n\n#15 -)LINEAR ALGEBRA\nimport numpy\n\ns = int(input())\nx = []\nfor i in range(s):\n x.append(input().split())\nprint(numpy.around(numpy.linalg.det(numpy.array(x, dtype=numpy.float)), decimals=2))\n\n","sub_path":"hw1scripts/numpy.py","file_name":"numpy.py","file_ext":"py","file_size_in_byte":3651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"518687460","text":"import numpy as np\n# import pylab as pl\nimport matplotlib.pyplot as pl\nimport matplotlib as mpl\nimport scipy\nfrom scipy.signal import find_peaks\nfrom scipy.signal import argrelmin\nimport time\n\n\ndef smooth(data, t_min, window):\n avg_array = np.zeros(len(data))\n # print(avg_array)\n m = 20\n for i in range(t_min, t_min + window):\n min_ind = i - m\n max_ind = i + m\n if min_ind < 0: min_ind = 0\n if max_ind > len(data): max_ind = len(data)\n avg_array[i] = (np.mean(data[min_ind:max_ind]))\n return (avg_array)\n\n\n# def maxima(data):\n# y = data\n# peaks = argrelextrema(y, np.greater)\n# return(peaks)\n# def minima(data):\n# z = data\n# valleys = argrelextrema(z, np.less)\n# return(valleys)\n\ndef pulse_finder_area_series(data, t_min_search, t_max_search, window):\n # Assumes data is already baseline-subtracted\n max_area = -1\n max_ind = -1\n for i_start in range(t_min_search, t_max_search):\n area = np.sum(data[i_start:i_start + window])\n if area > max_area:\n max_area = area\n max_ind = i_start\n return (max_ind, max_area)\n\n\ndef wfm_convolve(data, window, avg=False):\n # Assumes data is already baseline-subtracted\n weights = np.repeat(1.0, window)\n if avg: weights /= window # do avg instead of sum\n return np.convolve(data, weights, 'same')\n\n\ndef pulse_finder_area(data, t_min_search, t_max_search, window):\n # Assumes data is already baseline-subtracted\n if t_max_search < t_min_search + 1:\n return (-1, -1)\n\n data_conv = wfm_convolve(data, window)\n # Search only w/in search range, offset so that max_ind is the start of the window rather than the center\n max_ind = np.argmax(data_conv[int(t_min_search + window / 2):int(t_max_search + window / 2)]) + int(t_min_search)\n return (max_ind, data_conv[max_ind + int(window / 2)])\n\ndef pulse_bounds_area(data, t_min, window, start_frac, end_frac):\n # Assumes data is already baseline-subtracted\n start_pos = -1\n end_pos = -1\n min_search = np.maximum(0, t_min)\n max_search = np.minimum(len(data) - 1, t_min + window)\n cdf = np.cumsum(data[min_search:max_search])/np.sum(data[min_search:max_search])\n\n # find first index where cdf > start_frac, last index where cdf < end_frac\n start_pos = np.where(cdf>start_frac)[0][0] + min_search\n end_pos = np.where(cdf<(1-end_frac))[0][-1] + min_search\n\n return (start_pos, end_pos)\n\ndef pulse_bounds(data, t_min, window, start_frac, end_frac):\n # Assumes data is already baseline-subtracted\n start_pos = -1\n end_pos = -1\n min_search = np.maximum(0, t_min)\n max_search = np.minimum(len(data) - 1, t_min + window)\n peak_val = np.max(data[min_search:max_search])\n peak_pos = np.argmax(data[min_search:max_search])\n # print(\"peak_val: \",peak_val,\"peak_pos: \",(peak_pos+min_search)*tscale)\n # print(\"min_search: \",min_search*tscale,\"max_search: \",max_search*tscale)\n # start_frac: pulse starts at this fraction of peak height above baseline\n # TODO: instead of a for loop, compare full array against max(...), take first, last values from np.where (add min_search!)\n for i_start in range(min_search, max_search):\n if data[i_start] > max(peak_val * start_frac, 8.0 / chA_spe_size):\n start_pos = i_start\n break\n # end_frac: pulse ends at this fraction of peak height above baseline\n for i_start in range(max_search, min_search, -1):\n if data[i_start] > max(peak_val * end_frac, 8.0 / chA_spe_size):\n end_pos = i_start\n break\n\n return (start_pos, end_pos)\n\n\ndef merged_bounds(data, t_min, window, start_frac, end_frac):\n start_pos = -1\n end_pos = -1\n a = (np.diff(np.sign(np.diff(output))) > 0).nonzero()[0] + 1\n b = argrelmin(data)\n peak_v = np.max(data[t_min:t_min + window])\n print(\"b:\", b)\n second = []\n print(\"a[0]:\", a[0])\n for i in scipy.nditer(b):\n # if data[i]>0.2 and max(data[t_min:t_min+window]) < i :\n # for i_start in range(t_min,t_min+window):\n # if data[i_start]>max(data[a[0]]*start_frac,4.5/chA_spe_size):\n # start_pos=i_start\n # break\n if data[i] > 1:\n start_pos = i\n print(\"i:\", i)\n break\n\n for j in a:\n\n if data[j] > 0.2:\n second.append(j)\n for k in scipy.nditer(b):\n if max(a) > k:\n\n for z in second[1:]:\n\n # end_frac: pulse ends at this fraction of peak height above baseline\n for i_start in range(t_min + window, t_min, -1):\n if data[i_start] > max(data[z] * end_frac, 4.5 / chA_spe_size):\n end_pos = i_start\n break\n else:\n end_pos = b[0]\n\n return (start_pos, end_pos)\n\n# Keep only the elements corresponding to indices in peak_ind_keep\n# Note that it annoyingly can't edit the values in peaks, etc. directly since numpy arrays are fixed-length\n# and just doing the variable reassignment doesn't change the passed array\ndef cull_peaks(peaks, peak_conv_heights, properties, peak_ind_keep):\n peaks = peaks[peak_ind_keep]\n peak_conv_heights = peak_conv_heights[peak_ind_keep]\n for key in properties.keys(): # also remove from properties dictionary\n properties[key] = properties[key][peak_ind_keep]\n return peaks, peak_conv_heights, properties\n\n# set plotting style\n# mpl.rcParams['font.size']=28\n# mpl.rcParams['legend.fontsize']='small'\nmpl.rcParams['figure.autolayout'] = True\n# mpl.rcParams['figure.figsize']=[16.0,12.0]\n\n\ndata_dir = \"C:/Users/swkra/Desktop/Jupyter temp/data-202009/091720/bkg_3.5g_3.9c_27mV_7_postrecover2_5min/\" # \"../../092420/bkg_3.5g_3.9c_1.0bara_25mV_fan_in_4_allchanOR_post30sfill_5min/\"\nevent_window = 25. # in us\nwsize = int(500 * event_window) # samples per waveform # 12500 for 25 us\nmax_evts = 1000 # 25000 # -1 means read in all entries; 25000 is roughly the max allowed in memory on the DAQ computer\nmax_pts = -1 # do not change\nif max_evts > 0:\n max_pts = wsize * max_evts\nchannel_0 = np.fromfile(data_dir + \"wave0.dat\", dtype=\"int16\", count=max_pts)\nchannel_1 = np.fromfile(data_dir + \"wave1.dat\", dtype=\"int16\", count=max_pts)\nchannel_2 = np.fromfile(data_dir + \"wave2.dat\", dtype=\"int16\", count=max_pts)\nchannel_3 = np.fromfile(data_dir + \"wave3.dat\", dtype=\"int16\", count=max_pts)\nchannel_4 = np.fromfile(data_dir + \"wave4.dat\", dtype=\"int16\", count=max_pts)\nchannel_5 = np.fromfile(data_dir + \"wave5.dat\", dtype=\"int16\", count=max_pts)\nchannel_6 = np.fromfile(data_dir + \"wave6.dat\", dtype=\"int16\", count=max_pts)\nchannel_7 = np.fromfile(data_dir + \"wave7.dat\", dtype=\"int16\", count=max_pts)\n\n# channel_0=np.fromfile(\"../../Desktop/crystallize_data/t3-0805/A-thorium-4kv-t3.dat\", dtype=\"int16\")\n# channel_1=np.fromfile(\"../../Desktop/crystallize_data/t3-0805/B-thorium-4kv-t3.dat\", dtype=\"int16\")\n# channel_2=np.fromfile(\"../../Desktop/crystallize_data/t3-0805/C-thorium-4kv-t3.dat\", dtype=\"int16\")\n# channel_3=np.fromfile(\"../../Desktop/crystallize_data/t3-0805/D-thorium-4kv-t3.dat\", dtype=\"int16\")\n\n# channel_0=np.fromfile(\"A-thorium-3kv.dat\", dtype=\"int16\")\n# channel_1=np.fromfile(\"B-thorium-3kv.dat\", dtype=\"int16\")\n# channel_2=np.fromfile(\"C-thorium-3kv.dat\", dtype=\"int16\")\n# channel_3=np.fromfile(\"D-thorium-3kv.dat\", dtype=\"int16\")\ntimer_start = time.time()\n\nvscale = (2000.0 / 16384.0)\nchA_spe_size = 29.02\nV = vscale * channel_0 / chA_spe_size # ch A, calib size 644\n# Ensure we have an integer number of events\nV = V[:int(len(V) / wsize) * wsize]\nchB_spe_size = 30.61\nV_1 = vscale * channel_1 / chB_spe_size\nV_1 = V_1[:int(len(V) / wsize) * wsize]\nchC_spe_size = 28.87\nV_2 = vscale * channel_2 / chC_spe_size\nV_2 = V_2[:int(len(V) / wsize) * wsize]\nchD_spe_size = 28.86\nV_3 = vscale * channel_3 / chD_spe_size\nV_3 = V_3[:int(len(V) / wsize) * wsize]\nchE_spe_size = 30.4\nV_4 = vscale * channel_4 / chE_spe_size\nV_4 = V_4[:int(len(V) / wsize) * wsize]\nchF_spe_size = 30.44\nV_5 = vscale * channel_5 / chF_spe_size\nV_5 = V_5[:int(len(V) / wsize) * wsize]\nchG_spe_size = 30.84\nV_6 = vscale * channel_6 / chG_spe_size\nV_6 = V_6[:int(len(V) / wsize) * wsize]\nchH_spe_size = 30.3\nV_7 = vscale * channel_7 / chH_spe_size\nV_7 = V_7[:int(len(V) / wsize) * wsize]\nn_channels = 9 # including sum\nv_matrix = V.reshape(int(V.size / wsize), wsize)\nv1_matrix = V_1.reshape(int(V.size / wsize), wsize)\nv2_matrix = V_2.reshape(int(V.size / wsize), wsize)\nv3_matrix = V_3.reshape(int(V.size / wsize), wsize)\nv4_matrix = V_4.reshape(int(V.size / wsize), wsize)\nv5_matrix = V_5.reshape(int(V.size / wsize), wsize)\nv6_matrix = V_6.reshape(int(V.size / wsize), wsize)\nv7_matrix = V_7.reshape(int(V.size / wsize), wsize)\nvsum_matrix = v_matrix + v1_matrix + v2_matrix + v3_matrix + v4_matrix + v5_matrix + v6_matrix + v7_matrix\nv_matrix_all_ch = [v_matrix, v1_matrix, v2_matrix, v3_matrix, v4_matrix, v5_matrix, v6_matrix, v7_matrix, vsum_matrix]\nx = np.arange(0, wsize, 1)\ntscale = (8.0 / 4096.0)\nt = tscale * x\nt_matrix = np.repeat(t[np.newaxis, :], V.size / wsize, 0)\n# One entry per channel\nmax_ind_array = np.zeros((v_matrix.shape[0], n_channels))\nmax_val_array = np.zeros((v_matrix.shape[0], n_channels))\nintegral_array = np.zeros((v_matrix.shape[0], n_channels))\ns2_integral_array = np.zeros((v_matrix.shape[0], n_channels))\ns1_ch_array = np.zeros((v_matrix.shape[0], n_channels - 1))\ns2_ch_array = np.zeros((v_matrix.shape[0], n_channels - 1))\n# One entry per event\ns2_area_array = np.zeros(v_matrix.shape[0])\ns1_area_array = np.zeros(v_matrix.shape[0])\ns2_width_array = np.zeros(v_matrix.shape[0])\ns2_height_array = np.zeros(v_matrix.shape[0])\ns1_height_array = np.zeros(v_matrix.shape[0])\nt_drift_array = np.zeros(v_matrix.shape[0])\ns2_found_array = np.zeros(v_matrix.shape[0], dtype='bool')\ns1_found_array = np.zeros(v_matrix.shape[0], dtype='bool')\n\n# s2_area_array=[]\n# s1_area_array=[]\n# s2_width_array=[]\n# t_drift_array=[]\n# s2_found_array=[]\n# s1_found_array=[]\n\ninn = \"\"\ncenter = np.zeros(v_matrix.shape[0], dtype='bool')\nprint(\"Total events: \", v_matrix.shape[0])\nfor i in range(0, int(v_matrix.shape[0])):\n if i % 100 == 0: print(\"Event #\", i)\n t0 = time.time()\n # for each channel\n # for j in range(0, n_channels):\n # i = input(\"Window number between 1 and \" + str((V.size/wsize)) + \": \")\n\n # baseline=np.mean(v_matrix_all_ch[j][i,:500]) #avg ~1 us\n # print(\"baseline: \",baseline)\n\n # Look for events with S1 and S2 from summed channel\n n_top = int((n_channels - 1) / 2)\n top_channels = np.array(range(n_top), int)\n bottom_channels = np.array(range(n_top, 2 * n_top), int)\n post_trigger = 0.5 # Was 0.2 for data before 11/22/19\n trigger_time_us = event_window * (1 - post_trigger)\n trigger_time = int(trigger_time_us / tscale)\n t_offset = int(0.2 / tscale)\n s1_window = int(0.5 / tscale)\n s2_window = int(7.0 / tscale)\n pulse_window = int(7.0 / tscale)\n max_pulses = 4\n t_min_search = trigger_time - int(event_window / 2.1 / tscale) # was int(10./tscale)\n t_max_search = trigger_time + int(event_window / 2.1 / tscale) # was int(22./tscale)\n s1_thresh = 100 / chA_spe_size\n s1_range_thresh = 10 / chA_spe_size\n s2_thresh = 150 / chA_spe_size\n s2_start_frac = 0.01 # s2 pulse starts at this fraction of peak height above baseline\n s2_end_frac = 0.01 # s2 pulse starts at this fraction of peak height above baseline\n s1_start_frac = 0.1\n s1_end_frac = 0.1\n s1_max = s1_thresh\n s1_max_ind = -1\n s1_area = -1\n s1_height_range = -1\n s1_start_pos = -1\n s1_end_pos = -1\n s2_max = s2_thresh\n s2_max_ind = -1\n s2_area = -1\n # s2_start_pos=[]\n # s2_end_pos=[]\n s2_width = -1\n s2_height = -1\n s1_height = -1\n t_drift = -1\n s1_found = False\n s2_found = False\n s1_ch_area = [-1] * (n_channels - 1)\n s2_ch_area = [-1] * (n_channels - 1)\n fiducial = False\n\n baseline_start = int(0. / tscale)\n baseline_end = int(2. / tscale)\n t0 = time.time()\n sum_baseline = np.mean(v_matrix_all_ch[-1][i, baseline_start:baseline_end]) # avg ~us, avoiding trigger\n baselines = [np.mean(ch_j[i, baseline_start:baseline_end]) for ch_j in v_matrix_all_ch]\n # print(\"baseline:\", baselines)\n # print(\"sum baseline:\", sum_baseline)\n sum_data = v_matrix_all_ch[-1][i, :] - sum_baseline\n ch_data = [ch_j[i, :] - baseline_j for (ch_j, baseline_j) in zip(v_matrix_all_ch, baselines)]\n t0a = time.time()\n # print(\"ch baseline calc time: \",t0a-t0)\n\n # Do a moving average (sum) of the waveform with different time windows for s1, s2\n # Look for where this value is maximized\n # Look for the s2 using a moving average (sum) of the waveform over a wide window\n conv_width = int(0.3 / tscale)\n data_conv = wfm_convolve(sum_data, conv_width, avg=True)\n peaks, properties = find_peaks(data_conv, distance=int(0.5 / tscale), height=0.8,\n width=int(0.01 / tscale), prominence=0.1) # could restrict search if desired\n peak_conv_heights = data_conv[peaks]\n #print(\"peaks: \", peaks*tscale)\n #print(\"(total found: {0})\".format(np.size(peaks)))\n\n # only keep the larges max_pulses peaks\n peak_height_order = np.argsort(peak_conv_heights)\n lg_peaks = np.sort(peak_height_order[:max_pulses])\n #peak_ind_cut = [ii for ii in range(len(peaks)) if not ii in lg_peaks]\n peaks, peak_conv_heights, properties = cull_peaks(peaks, peak_conv_heights, properties, lg_peaks)\n\n # Mark peaks that should be removed (merged w/ previous ones):\n # If a peak has small prominence relative to previous peak height w/in some window, remove it\n # Aimed at removing S2 falling tails\n merge_frac = 0.05 # Initial testing suggests this is about right \"by eye\" (0.07 is too high, 0.02 is too low)\n time_diffs = (peaks[1:]-peaks[:-1])\n small_peak = properties['prominences'][1:] < peak_conv_heights[:-1] * merge_frac\n prev_peak_near = time_diffs < int(pulse_window / 2) # was [:-1]...\n peak_ind_cut = np.where(small_peak*prev_peak_near)[0]+1 # add 1 since we're always looking back one pulse\n\n # Remove peaks that were marked to be cut\n if len(peak_ind_cut) > 0:\n # print(\"remove peaks: \", peak_ind_cut)\n # print(\"Prominences: \", properties[\"prominences\"])\n # print(\"prominence ratios: \", properties['prominences'][1:][peak_ind_cut-1]/(peak_conv_heights[:-1][peak_ind_cut-1]))\n peak_ind_keep = [ii for ii in range(len(peaks)) if not ii in peak_ind_cut]\n peaks, peak_conv_heights, properties = cull_peaks(peaks, peak_conv_heights, properties, peak_ind_keep)\n\n # Define windows to search for peak boundaries (very wide, by definition; this mainly deals w/ overlapping peaks)\n window_starts = []\n window_ends = []\n prev_end = -1\n for peak_ind in range(len(peaks)):\n # Peak start calc\n if prev_end != -1: # Use previous peak's end as this peak's start, if within window\n window_starts.append(prev_end)\n else:\n # look back half the max window; could also shift according to int(conv_width/2), probably not important\n window_starts.append(peaks[peak_ind]-int(pulse_window/2))\n\n # Peak end calc\n if peak_ind == len(peaks)-1:\n window_ends.append(peaks[peak_ind]+int(pulse_window/2)) # look forward half the\n else:\n # If the next pulse is overlapping, set the pulse boundary as the minimum between the two\n if time_diffs[peak_ind]s2_thresh\n t1 = time.time()\n\n t2 = time.time()\n\n # s2_bottom = np.sum(np.array(s2_ch_area)[bottom_channels])\n # s2_top = np.sum(np.array(s2_ch_area)[top_channels])\n # s2_tba = (s2_top-s2_bottom)/(s2_top+s2_bottom)\n\n # Code to allow skipping to another event index for plotting\n plot_event_ind = i\n try:\n plot_event_ind = int(inn)\n if plot_event_ind < i:\n inn = ''\n plot_event_ind = i\n print(\"Can't go backwards! Continuing to next event.\")\n except ValueError:\n plot_event_ind = i\n\n if False and not inn == 'q' and plot_event_ind == i:\n # if s1_found and s2_found:\n fig = pl.figure(1, figsize=(10, 7))\n # pl.rc('xtick', labelsize=25)\n # pl.rc('ytick', labelsize=25)\n\n ax = pl.subplot2grid((2, 2), (0, 0))\n pl.title(\"Top array, event \" + str(i))\n pl.grid(b=True, which='major', color='lightgray', linestyle='--')\n ch_labels = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']\n ch_colors = [pl.cm.tab10(ii) for ii in range(n_channels)]\n # ch_colors=[pl.cm.Dark2(ii) for ii in np.linspace(0.2,0.9,n_channels)]\n # ch_colors=['y','cyan','magenta','b','y','cyan','magenta','b']\n if s2_found:\n ax.axvspan(s2_start_pos * tscale, s2_end_pos * tscale, alpha=0.3, color='blue')\n if s1_found:\n ax.axvspan(s1_start_pos * tscale, s1_end_pos * tscale, alpha=0.3, color='green')\n for i_chan in range(n_channels - 1):\n if i_chan == (n_channels - 1) / 2:\n ax = pl.subplot2grid((2, 2), (0, 1))\n pl.title(\"Bottom array, event \" + str(i))\n pl.grid(b=True, which='major', color='lightgray', linestyle='--')\n\n if s2_found:\n ax.axvspan(s2_start_pos * tscale, s2_end_pos * tscale, alpha=0.3, color='blue')\n if s1_found:\n ax.axvspan(s1_start_pos * tscale, s1_end_pos * tscale, alpha=0.3, color='green')\n\n pl.plot(t_matrix[i, :], v_matrix_all_ch[i_chan][i, :], color=ch_colors[i_chan], label=ch_labels[i_chan])\n pl.xlim([trigger_time_us - 10, trigger_time_us + 10])\n pl.ylim([0, 1000 / chA_spe_size])\n pl.xlabel('Time (us)')\n pl.ylabel('Phd/sample')\n pl.legend()\n # triggertime_us = (t[-1]*0.2)\n # pl.plot(np.array([1,1])*triggertime_us,np.array([0,16384]),'k--')\n\n ax = pl.subplot2grid((2, 2), (1, 0), colspan=2)\n pl.plot(t_matrix[i, :], vsum_matrix[i, :], 'blue')\n pl.plot(t_matrix[i, :], data_conv + sum_baseline, 'red')\n pl.plot(t_matrix[i, :], np.tile(sum_baseline, np.size(data_conv)), 'gray')\n pl.vlines(x=peaks*tscale, ymin=data_conv[peaks]+sum_baseline - properties[\"prominences\"],\n ymax=data_conv[peaks]+sum_baseline, color=\"C1\")\n pl.hlines(y=properties[\"width_heights\"]+sum_baseline, xmin=properties[\"left_ips\"]*tscale,\n xmax=properties[\"right_ips\"]*tscale, color=\"C1\")\n #print(\"Width heights: \", properties[\"width_heights\"]+sum_baseline)\n #print(\"Left ips (us): \", properties[\"left_ips\"]*tscale)\n #print(\"Right ips (us): \", properties[\"right_ips\"]*tscale)\n #print(\"Prominences: \", properties[\"prominences\"])\n # pl.plot(t_matrix[i,:],sum_data,'blue')\n pl.xlim([0, event_window])\n pl.ylim([0, 4000 / chA_spe_size])\n pl.xlabel('Time (us)')\n pl.ylabel('Phd/sample')\n pl.title(\"Sum, event \" + str(i))\n pl.grid(b=True, which='major', color='lightgray', linestyle='--')\n triggertime_us = (t[-1] * 0.2)\n pl.plot(t_matrix[i, peaks], vsum_matrix[i, peaks], 'x')\n # pl.plot(t_matrix[i,peaks], sum_data[peaks], 'x')\n # pl.plot(np.array([1,1])*triggertime_us,np.array([0,16384]),'k--')\n for start_time, end_time in zip(pulse_start_times, pulse_end_times):\n ax.axvspan(start_time * tscale, end_time * tscale, alpha=0.3, color='blue')\n if s2_found:\n ax.axvspan(s2_start_pos * tscale, s2_end_pos * tscale, alpha=0.3, color='blue')\n if s1_found:\n ax.axvspan(s1_start_pos * tscale, s1_end_pos * tscale, alpha=0.3, color='green')\n\n pl.draw()\n pl.show(block=0)\n inn = input(\"Press enter to continue, q to skip plotting, event number to skip to that event (forward only)\")\n fig.clf()\n\ntimer_end = time.time()\nprint(\"Processing time: \",timer_end-timer_start)","sub_path":"scripts/s2_finder_scipy_signal.py","file_name":"s2_finder_scipy_signal.py","file_ext":"py","file_size_in_byte":20944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"257068855","text":"from sklearn import datasets\nfrom sklearn import linear_model\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nboston = datasets.load_boston()\nX = boston.data[:, 5]\nX = X.reshape((X.shape[0], 1))\ny = boston.target\n\nX_train = X[:-100]\nX_test = X[-100:]\ny_train = y[:-100]\ny_test = y[-100:]\n\n###########################################\n# Functions to run the program are below. Don't scroll down if you're trying to figure out the correct calls yourself\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nh = linear_model.SGDRegressor(penalty='none', fit_intercept=True, eta0=0.03, n_iter=100000)\nh.fit(X_train, y_train)\n\nprint('weights:', h.coef_)\nprint('bias:', h.intercept_)\nprint('r^2:', h.score(X, y))\n\n####################################################################################\n\n\n#Graph plotting\nplt.figure(1)\nplt.subplot(2, 1, 1)\nplt.plot(X_test, y_test, 'bo')\nplt.plot(X_test, h.predict(X_test), 'r-')\nplt.xlabel('Feature')\nplt.ylabel('Price ($10000s of dollars)')\nplt.title('House Price Regression (Test Data)')\nplt.grid(True)\n\nplt.subplot(2, 1, 2)\nplt.plot(X_train, y_train, 'bo')\nplt.plot(X_train, h.predict(X_train), 'r-')\nplt.xlabel('Feature')\nplt.ylabel('Price ($10000s of dollars)')\nplt.title('House Price Regression (Training Data)')\nplt.grid(True)\n\nplt.tight_layout() #prevent text overlapping\n\nplt.show()\n","sub_path":"Linear Regression/sklearn_linreg.py","file_name":"sklearn_linreg.py","file_ext":"py","file_size_in_byte":1301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"379057872","text":"import csv\nimport mapper\nimport utils\n\nclass CSVParser(object):\n\t\"\"\"CSV Parser capable of parsing against a pre-defined mapper file\"\"\"\n\tdef __init__(self, csvFile, fmapper=None, hasHeader=False):\n\t\tsuper(CSVParser, self).__init__()\n\t\t# the csv file\n\t\tself.csvFile = csvFile\n\t\t# the mapper object\n\t\tself.fmapper = fmapper\n\t\t# whether the csv file contains columns in the first row\n\t\tself.hasHeader = hasHeader\n\n\t# get records from mapper file\n\tdef getRecords(self):\n\t\tif self.fmapper == None:\n\t\t\tif self.hasHeader == False:\n\t\t\t\traise Exception('No mapper specified, set hasHeader=True if csv file contains headers')\n\t\t\telse:\n\t\t\t\tself.fmapper = mapper.FieldMapper(self.csvData[0]) # first row of csv\n\t\treturn self.fmapper.getRecords()\n\n\t# parses a CSV file\n\tdef parseCSV(self):\n\t\twith open(self.csvFile, 'rU') as csvfile:\n\t\t\trdr = csv.reader(csvfile, delimiter='\\t', quotechar='|')\n\t\t\tx = []\n\t\t\tfor row in rdr:\n\t\t\t\tx.append(row[0].split(','))\n\t\t\tself.csvData = x\n\n\t# convert type\n\tdef convertType(self,to,val):\n\t\tif to == '':\n\t\t\treturn val\n\t\ti = ''\n\t\texec('i = %s(%s)' %(to,val))\n\t\treturn i\n\n\t# convert csv data to record\n\tdef toDict(self, cdat, rec):\n\t\td = {}\n\t\ti = 0\n\t\tfor j in rec:\n\t\t\ta = cdat[i]\n\t\t\tif 'type' in j:\n\t\t\t\ta = self.convertType(j['type'], a)\n\t\t\td[j['name']] = a\n\t\t\ti= i+1\n\t\treturn d\n\n\tdef getIndex(self, x, l):\n\t\tif x > (l-1):\n\t\t\treturn x%l\n\t\treturn x\n\n\t# csv against mapper as dict instance\n\tdef buildDict(self, onAppend=None,popHeader=True):\n\t\tif hasattr(self, 'csvData') == False:\n\t\t\tself.parseCSV()\n\n\t\trecs = self.getRecords()\n\t\tif self.hasHeader and popHeader:\n\t\t\tself.csvData.pop(0) # remove the header line\n\n\t\tl = len(recs)\n\t\tdicts = []\n\t\tfor x in range(0, len(self.csvData)):\n\t\t\ti = self.getIndex(x, l)\n\t\t\tdic = self.toDict(self.csvData[x], recs[i])\n\t\t\tif onAppend == None:\n\t\t\t\tdicts.append(dic)\n\t\t\telse:\n\t\t\t\tdicts.append(onAppend(dic))\n\t\treturn dicts\n\n\t# as object instance\n\tdef buildObject(self):\n\t\treturn self.buildDict(utils.CSVObject)\n\n\n# Parser instance to CSV\nclass CSVWriter():\n\t\"\"\"Generate CSV Output\"\"\"\n\tdef __init__(self, dic):\n\t\tself.dic = dic\n\n\t# write to csv file\n\tdef write(self, fileName):\n\t\tisDict = type(self.dic[0]) == dict\n\t\twith open(fileName, 'wb') as fs:\n\t\t\theadings = None\n\t\t\tif isDict:\n\t\t\t\theadings = self.dic[0].keys()\n\t\t\telse:\n\t\t\t\theadings = self.dic[0].attribs()\n\n\t\t\tw = csv.DictWriter(fs, headings)\n\t\t\tw.writeheader()\n\t\t\tif isDict:\n\t\t\t\tfor row in self.dic:\n\t\t\t\t\tw.writerow(row)\n\t\t\telse:\n\t\t\t\tfor row in self.dic:\n\t\t\t\t\tw.writerow(row.__dict__)\n","sub_path":"csvmapper/csv_parser.py","file_name":"csv_parser.py","file_ext":"py","file_size_in_byte":2493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"322801306","text":"#!/usr/bin/env python\n# -*- encoding=utf8 -*-\n\nimport re\nimport sys\nreload(sys)\nimport time\nimport base64\nimport urllib\nimport urllib2\nimport httplib\nimport logging\nimport datetime\nimport cStringIO\nimport logging.handlers\nfrom PIL import Image\nfrom bs4 import BeautifulSoup\n\nsys.setdefaultencoding('utf8')\n\nclass HttpUtil:\n def __init__(self):\n # 日至初始化\n self.log = logging.getLogger('HttpUtil')\n sh = logging.StreamHandler(stream=None)\n fm = logging.Formatter('%(asctime)s %(levelname)s %(name)s - %(filename)s:%(lineno)s - %(message)s')\n self.log.setLevel(logging.INFO)\n sh.setFormatter(fm)\n self.log.addHandler(sh)\n \n self.tryTime = 10 # 失败尝试次数\n self.conn = None\n \n \n def getHtml(self, url, code='utf8'):\n data = ''\n tryInt = 0\n ret = True\n htype, host, req = HttpUtil.parseUrl(url)\n if 'http' == htype:\n self.conn = HttpUtil.getHttpConnection(host)\n elif 'https' == htype:\n self.conn = HttpUtil.getHttpsConnection(host)\n \n while tryInt <= self.tryTime:\n try:\n self.conn.request('GET', req)\n res = self.conn.getresponse() \n if 200 == int(res.status):\n ret = True\n data = '' + res.read().decode(code)\n self.log.info('get url' + url + ' ok!')\n break\n else:\n ret = False\n data = '' + url\n time.sleep(0.1)\n except BaseException as e:\n ret = False\n data = url\n time.sleep(0.1)\n self.log.error('get 请求失败!' + e.message)\n tryInt += 1\n return (ret, data)\n \n \n def postHtml(self, url, heads, params, code='utf8'):\n data = url\n tryInt = 0\n ret = True\n if len(heads) <=0 or len(params) <= 0:\n ret = False\n htype, host, req = HttpUtil.parseUrl(url)\n if 'http' == htype:\n self.conn = HttpUtil.getHttpConnection(host)\n elif 'https' == htype:\n self.conn = HttpUtil.getHttpsConnection(host)\n while tryInt <= self.tryTime and ret:\n try:\n self.conn.request('POST', req, urllib.urlencode(params), heads)\n res = self.conn.getresponse()\n if 200 == int(res.status):\n ret = True\n data = '' + res.read().decode(code)\n self.log.info('post url' + url + ' ok!')\n break\n else:\n ret = False\n data = url\n time.sleep(0.1)\n except BaseException as e:\n ret = False\n time.sleep(0.1)\n data = url\n self.log.error('post 请求失败!' + e.message)\n tryInt += 1\n return (ret, data)\n \n def downloadImageBase64(self, url):\n tryInt = 0\n data = url\n ret = True\n \n while tryInt <= self.tryTime:\n try:\n img = cStringIO.StringIO(urllib2.urlopen(url).read())\n data = base64.b64encode(img.getvalue())\n ret = True\n except BaseException as e:\n ret = False\n self.log.error('下载图片内容失败!' + e.message)\n tryInt += 1\n return (ret, data)\n \n # 解码\n #image = Image.open(cStringIO.StringIO(base64.b64decode(bs64)))\n #image.show()\n\n \n def download(self, url, savePath):\n ret = True\n data = ''\n tryInt = 0\n while tryInt <= self.tryTime:\n ret = True\n data = ''\n try:\n urllib.urlretrieve(url, savePath)\n break\n except BaseException as e:\n data = url\n ret = False\n time.sleep(0.1)\n self.log.error('下载内容失败!' + e.message) \n tryInt += 1\n time.sleep(0.1)\n return (ret, data) \n \n \n @staticmethod\n def getHttpConnection(host):\n return httplib.HTTPConnection(host, 80, True, 3000)\n \n \n @staticmethod\n def getHttpsConnection(host):\n return None\n \n \n @staticmethod\n def cleanTags(html):\n html = re.sub(r'', '', html.decode('utf8'), 0, re.I)\n html = html.replace('

', '')\n html = html.replace('

', '')\n return html\n\n\n @staticmethod\n def replaceHtml(html):\n dict = {'<':'<', '>':'>', ' ':' ', '"':'\\\"', '°':'。'}\n for k, v in dict.items():\n html = html.replace(k, v)\n return html\n\n @staticmethod\n def parseUrl(url):\n htype = ''\n host = ''\n req = ''\n arr = url.split(\"://\")\n if len(arr) == 1:\n host = arr[0]\n elif len(arr) == 2:\n host = arr[1]\n else:\n return None\n if arr[0] == 'https' or arr[0] == 'http':\n htype = arr[0]\n else:\n htype = 'http'\n arr = host.split(\"/\")\n if len(arr) == 1:\n host = arr[0]\n req = '/'\n else:\n host = arr[0]\n req = '/' + '/'.join(arr[1:])\n return (htype, host, req)\n \n \n \n ","sub_path":"lib/HttpUtil.py","file_name":"HttpUtil.py","file_ext":"py","file_size_in_byte":5535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"283153348","text":"import unicodedata\nfrom copy import copy\n\nimport inflection\nimport numpy as np\nfrom flashtext import KeywordProcessor\n\nimport config\nfrom doc_retrieval.doc_utils import DocIDTokenizer\nfrom doc_retrieval.fast_key_word_matching_v1_3 import \\\n build_flashtext_processor_with_prioritized_kw_dict as build_processor\nfrom doc_retrieval.fast_key_word_matching_v1_3 import get_words_inside_parenthese as extract_par\nfrom doc_retrieval.fast_key_word_matching_v1_3 import id_dict_key_word_expand, set_priority, \\\n check_inside_paretheses_overlap, load_keyword_dict_v1_3\nfrom doc_retrieval.google_querier import GoogleQuerier\nfrom doc_retrieval.wiki_pageview_utils import WikiPageviews\nfrom utils.fever_db import convert_brc\nfrom utils.text_clean import STOPWORDS\n\n__author__ = ['chaonan99', 'yixin1']\n\n\nclass KeywordRuleBuilder(object):\n \"\"\"KeywordRuleBuilder applies post processing rules on keyword processor \"\"\"\n @classmethod\n def __essential_remove(cls, keyword_processor, remove_str):\n remove_set = copy(keyword_processor[remove_str])\n if remove_set is not None:\n result_set = set([it for it in remove_set if it[0] != remove_str])\n if len(result_set) == 0:\n keyword_processor.remove_keyword(remove_str)\n else:\n keyword_processor[remove_str] = result_set\n\n @classmethod\n def eliminate_pure_digits_in_place(cls, keyword_processor):\n for i in range(100000):\n cls.__essential_remove(keyword_processor, str(i))\n\n @classmethod\n def eliminate_ordinals_in_place(cls, keyword_processor):\n for i in range(1000):\n cls.__essential_remove(keyword_processor, inflection.ordinalize(i))\n\n @classmethod\n def eliminate_stop_words_in_place(cls, keyword_processor):\n for w in STOPWORDS:\n cls.__essential_remove(keyword_processor, w)\n cls.__essential_remove(keyword_processor, w.title())\n\n\nclass DocIDRuleBuilder(object):\n \"\"\"DocIDRuleBuilder contains docid based rules, including parentheses\n overlapping, enhancement for film, TV series, ... and others\n \"\"\"\n def __init__(self, claim_tokens, claim_lemmas):\n self.claim_tokens = claim_tokens\n self.claim_lemmas = claim_lemmas\n\n def tokenize_docid(self, id_prio_tuple, docid_tokenizer):\n self.doc_id, self.priority = id_prio_tuple\n self.doc_id_tokens, self.doc_id_lemmas = \\\n docid_tokenizer.tokenize_docid(self.doc_id.lower())\n return self\n\n def parentheses_overlap_rule(self):\n if self.priority == 1.0:\n self.priority = check_inside_paretheses_overlap(self.doc_id_tokens,\n self.doc_id_lemmas,\n self.claim_tokens,\n self.claim_lemmas)\n return self\n\n def common_word_rule(self):\n addup_score = 0.2 if 'film' in extract_par(self.doc_id_tokens) \\\n else 0.1 if 'album' in extract_par(self.doc_id_tokens) \\\n or 'TV' in extract_par(self.doc_id_tokens) \\\n else 0\n self.priority += addup_score\n return self\n\n @property\n def id_prio_tuple(self):\n return (self.doc_id, self.priority)\n\n\nclass ItemRuleBuilderBase:\n \"\"\"ItemRuleBuilderBase is the base class for item rule builder \"\"\"\n def __init__(self, tokenizer, keyword_processor=None):\n self.tokenizer = tokenizer\n self.keyword_processor = self.build_kp() if keyword_processor is None else keyword_processor\n\n def _build_kp(self, case_sensitive=True):\n ## Prepare tokenizer and flashtext keyword processor\n keyword_processor = KeywordProcessor(case_sensitive=case_sensitive)\n id_to_key_dict = load_keyword_dict_v1_3(config.DATA_ROOT / \"id_dict.jsonl\", filtering=True)\n exact_match_rule_dict = set_priority(id_to_key_dict, priority=5.0)\n noisy_key_dict = id_dict_key_word_expand(id_to_key_dict, create_new_key_word_dict=True)\n noisy_parenthese_rule_dict = set_priority(noisy_key_dict, priority=1.0)\n\n build_processor(keyword_processor, exact_match_rule_dict)\n build_processor(keyword_processor, noisy_parenthese_rule_dict)\n\n ## Change priorities of digital numbers\n KeywordRuleBuilder.eliminate_pure_digits_in_place(keyword_processor)\n KeywordRuleBuilder.eliminate_ordinals_in_place(keyword_processor)\n KeywordRuleBuilder.eliminate_stop_words_in_place(keyword_processor)\n\n return keyword_processor\n\n def build_kp(self, case_sensitive=True):\n return self._build_kp(case_sensitive)\n\n def _keyword_match(self, claim, raw_set=False, custom_kp=None):\n kp = self.keyword_processor if custom_kp is None else custom_kp\n finded_keys = kp.extract_keywords(claim)\n if isinstance(finded_keys, list) and len(finded_keys) != 0:\n finded_keys = set.union(*finded_keys)\n return finded_keys\n\n def normalize(self, text):\n \"\"\"Resolve different type of unicode encodings.\"\"\"\n return unicodedata.normalize('NFD', text)\n\n def get_token_lemma_from_claim(self, claim):\n claim_norm = self.normalize(claim)\n claim_tok_r = self.tokenizer.tokenize(claim_norm)\n claim_tokens = claim_tok_r.words()\n claim_lemmas = claim_tok_r.lemmas()\n return claim_tokens, claim_lemmas\n\n @classmethod\n def get_all_docid_in_evidence(cls, evidence):\n return [iii for i in evidence for ii in i for iii in ii if type(iii) == str]\n\n @property\n def rules(self):\n return lambda x: x\n\n\nclass ItemRuleBuilder(ItemRuleBuilderBase):\n \"\"\"ItemRuleBuilder contains basic document retrieval rules \"\"\"\n def __init__(self, tokenizer, keyword_processor=None):\n super().__init__(tokenizer, keyword_processor)\n self.docid_tokenizer = DocIDTokenizer(case_insensitive=True)\n self.google_querier = GoogleQuerier(self.keyword_processor)\n\n def exact_match_rule(self, item):\n claim_tokens, claim_lemmas = \\\n self.get_token_lemma_from_claim(item['claim'])\n claim = ' '.join(claim_tokens)\n\n finded_keys = self._keyword_match(claim)\n\n item['prioritized_docids'] = list(finded_keys)\n item['claim_lemmas'] = claim_lemmas\n item['claim_tokens'] = claim_tokens\n item['processed_claim'] = claim\n self.item = item\n return self\n\n def docid_based_rule(self):\n item = self.item\n assert 'prioritized_docids' in item, 'Apply exact match rule first!'\n for i, id_prio_tuple in enumerate(item['prioritized_docids']):\n docid_rule_builder = DocIDRuleBuilder(item['claim_tokens'],\n item['claim_lemmas'])\n docid_rule_builder.tokenize_docid(id_prio_tuple,\n self.docid_tokenizer)\\\n .parentheses_overlap_rule()\\\n .common_word_rule()\n item['prioritized_docids'][i] = docid_rule_builder.id_prio_tuple\n return self\n\n def eliminate_the_rule(self):\n return self.eliminate_start_words_rule(starts=['The'])\n\n def eliminate_articles_rule(self):\n return self.eliminate_start_words_rule(starts=['The', 'A', 'An'])\n\n def eliminate_start_words_rule(self, starts=['The'], modify_pdocid=False):\n item = self.item\n claim_tokens = copy(item['claim_tokens'])\n finded_keys = item['prioritized_docids']\n if claim_tokens[0] in starts:\n claim_tokens[1] = claim_tokens[1].title()\n claim = ' '.join(claim_tokens[1:])\n fk_new = self._keyword_match(claim)\n finded_keys = set(finded_keys) | set(fk_new)\n item['prioritized_docids'] = list(finded_keys)\n return self\n\n def singularize_rule(self):\n \"\"\"Singularize words\n \"\"\"\n item = self.item\n if len(item['prioritized_docids']) < 1:\n claim_tokens = item['claim_tokens']\n # finded_keys = item['prioritized_docids']\n claim_tokens = [inflection.singularize(c) for c in claim_tokens]\n claim = ' '.join(claim_tokens)\n fk_new = self._keyword_match(claim)\n # finded_keys = set(finded_keys) | set(fk_new)\n item['prioritized_docids'] = list(fk_new)\n return self\n\n def google_query_rule(self):\n item = self.item\n docid_dict = {k: v for k, v in item['prioritized_docids']}\n esn = sum([v > 1 for v in docid_dict.values()])\n if (len(item['prioritized_docids']) > 15 and esn < 5) or len(item['prioritized_docids']) < 1:\n self.google_querier.get_google_docid(item)\n for k in item['google_docids']:\n docid_dict[k] = 6.0\n item['prioritized_docids'] = [(k, v) for k, v in docid_dict.items()]\n return self\n\n\nclass ItemRuleBuilderRawID(ItemRuleBuilder):\n def __init__(self, tokenizer, keyword_processor=None):\n super(ItemRuleBuilderRawID, self).__init__(tokenizer, keyword_processor)\n self.wiki_pv = WikiPageviews()\n\n def build_kp(self, case_sensitive=False):\n return self._build_kp(case_sensitive)\n\n def _recursive_key_matcher(self, claim, fkd=None):\n fkd = {} if fkd is None else fkd\n finded_keys_dict = self.google_querier.get_keywords(claim)\n\n for key, value in finded_keys_dict.items():\n if key.lower() in STOPWORDS:\n continue\n\n ## First letter is case sensitive\n value = [v for v in value if v[0][0] == key[0]]\n\n if len(value) == 0:\n ## This seems to be a bug, for example, for claim\n ## \"The hero of the Odyssey is Harry Potter.\", it will first\n ## match \"the Odyssey\" and failed to match first letter\n ## \"The_Odyssey\" and \"the Odyssey\" will be ignored.\n ## But 2 actually performs best on dev so we just keep it here\n key_tokens = key.split(' ')\n if len(key_tokens) > 2:\n key_tokens[1] = key_tokens[1].title()\n self._recursive_key_matcher(' '.join(key_tokens[1:]), fkd)\n else:\n fkd.update({key:value})\n\n return fkd\n\n def _keyword_match(self, claim, raw_set=False, custom_kp=None):\n kp = self.keyword_processor if custom_kp is None else custom_kp\n if not raw_set:\n finded_keys = kp.extract_keywords(claim)\n if isinstance(finded_keys, list) and len(finded_keys) != 0:\n finded_keys = set.union(*finded_keys)\n return finded_keys\n else:\n finded_keys_dict = self.google_querier.get_keywords(claim)\n finded_keys_dict = self._recursive_key_matcher(claim)\n finded_keys = finded_keys_dict.values()\n finded_keys = set([i for ii in finded_keys for i in ii]) \\\n if len(finded_keys) > 0 else set(finded_keys)\n\n return finded_keys_dict, finded_keys\n\n def google_query_rule(self):\n item = self.item\n if len(item['prioritized_docids']) > 40:\n # all_keys = item['structured_docids'].keys()\n item['google_docids'] = []\n matched_docid = self.google_querier\\\n .google_it(item['processed_claim'])\n # item['prioritized_docids'].append((matched_docid, 6.0))\n # Consume redundent keywords\n print(item['processed_claim'])\n print(matched_docid)\n if matched_docid is not None:\n fkd_new = {}\n key_remains = []\n for key, value in item['structured_docids'].items():\n key_tokens = key.split(' ')\n if not np.all(list(map(lambda x: x in matched_docid,\n key_tokens))):\n key_remains.append(key)\n fkd_new.update({key: value})\n item['structured_docids'] = fkd_new\n finded_keys = fkd_new.values()\n finded_keys = set([i for ii in finded_keys for i in ii]) \\\n if len(finded_keys) > 0 else set(finded_keys)\n item['prioritized_docids'] = list(finded_keys)\n item['prioritized_docids'].append((matched_docid, 6.0))\n return self\n\n def test_recursive_match(self, claim):\n return self._recursive_key_matcher(claim)\n\n def pageview_rule(self):\n \"\"\"Assign high priority to frequently viewed pages\n \"\"\"\n if not hasattr(self, 'wiki_pv'):\n print(\"Reload wiki pageview dict\")\n self.wiki_pv = WikiPageviews()\n\n item = self.item\n docid_groups = [[i[0] for i in it] \\\n for _, it in item['structured_docids'].items()]\n changed = False\n for key, group_prio_docids in item['structured_docids'].items():\n group_docids = [it[0] for it in group_prio_docids]\n if len(group_docids) > 1:\n changed = True\n all_scores = map(lambda x: self.wiki_pv[convert_brc(x)],\n group_docids)\n all_scores = np.array(list(all_scores))\n prios = np.argsort(all_scores)[::-1]\n new_gpd = []\n for i, p in enumerate(prios):\n # new_gpd.append((group_prio_docids[p][0],\n # group_prio_docids[p][1] + \\\n # max(1.0 - i*0.2, 0)))\n new_gpd.append((group_prio_docids[p][0],\n max(1.0 - i*0.2, 0)))\n item['structured_docids'][key] = new_gpd\n\n if changed:\n finded_keys = item['structured_docids'].values()\n finded_keys = set([i for ii in finded_keys for i in ii]) \\\n if len(finded_keys) > 0 else set(finded_keys)\n item['prioritized_docids'] = list(finded_keys)\n return self\n\n def eliminate_start_words_rule(self, starts=['The']):\n item = self.item\n claim_tokens = copy(item['claim_tokens'])\n finded_keys = item['prioritized_docids']\n if claim_tokens[0] in starts:\n claim_tokens[1] = claim_tokens[1].title()\n claim = ' '.join(claim_tokens[1:])\n fkd_new, fk_new = self._keyword_match(claim, raw_set=True)\n finded_keys = set(finded_keys) | set(fk_new)\n item['structured_docids'].update(fkd_new)\n item['prioritized_docids'] = list(finded_keys)\n return self\n\n def singularize_rule(self):\n item = self.item\n if len(item['prioritized_docids']) < 1:\n claim_tokens = item['claim_tokens']\n # finded_keys = item['prioritized_docids']\n claim_tokens = [inflection.singularize(c) for c in claim_tokens]\n claim = ' '.join(claim_tokens)\n fkd_new, fk_new = self._keyword_match(claim, raw_set=True)\n # finded_keys = set(finded_keys) | set(fk_new)\n item['prioritized_docids'] = list(fk_new)\n item['structured_docids'] = fkd_new\n return self\n","sub_path":"src/item_rules.py","file_name":"item_rules.py","file_ext":"py","file_size_in_byte":15362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"584894037","text":"#!/usr/bin/env python3\nimport sys\nimport time\n\ndonors_list = [(\"Rufio\", [897, 200, 200]),\n (\"Maggie\", [543, 2, 3000]),\n (\"Gus\", [23, 32, 33222]),\n (\"Kramer\", [10, 87, 886]),\n (\"Polly\", [432, 32, 7896])\n ]\n\n\ndef thank_you():\n find_donor()\n\n\ndef gen_stats(donor):\n donations = donor[1]\n total = sum(donations)\n num = len(donations)\n stats = (donor[0], total, num, total / num)\n\n return stats\n\n\ndef report():\n print(\"Generating report...\")\n time.sleep(1) # dramatic effect of creating the report\n generate_report_template()\n # gen_stats(donor)\n\n\ndef generate_report_template():\n donor_name = \"Donor Name\"\n total_given = \"Total Given\"\n num_gifts = \"Num Gifts\"\n average_gift = \"Average Gift\"\n\n print(f\"{donor_name} | {total_given} | {num_gifts} | {average_gift}\")\n print(\"-\" * 68)\n\n\ndef find_donor():\n print(\"Type 'list' to get a list of donors\")\n donor_name = input(\"Type in the name of a donor: \")\n\n if donor_name == \"list\":\n print(\"\\nHere is your list of donors:\\n\")\n for donor in donors_list:\n print(f\"Donors are: {donor}\")\n else:\n for donor in donors_list:\n if donor_name == donor[0]:\n print(f\"Found donor: {donor_name}\")\n else:\n donors_list.append(donor_name)\n print(f\"Adding {donor_name} to the list of donors.\")\n\n\ndef quit():\n print(\"Quitting Mailroom...\")\n time.sleep(.5)\n print(\"Goodbye\")\n sys.exit(0)\n\n\ndef main_menu():\n while True:\n answer = input(\"\"\" -> What you would you like to do?\n Pick One:\n 1: Send a thank you\n 2: Create a report\n 3: Quit\n >>> \"\"\")\n print(f\"You selected {answer}\")\n\n answer = answer.strip()\n if answer == \"1\":\n thank_you()\n elif answer == \"2\":\n report()\n elif answer == \"3\":\n quit()\n else:\n print(\"Please answer 1, 2, or 3\")\n\n\nif __name__ == \"__main__\":\n print(\"Welcome to the Mailroom\")\n\n donor = (\"fred flinstone\"), [100, 50, 600]\n # assert gen_stats(donor) == (\"fred flinstone\"), [750, 3, 250.0]\n\n main_menu()\n","sub_path":"students/AndrewMiotke/session03/mailroom.py","file_name":"mailroom.py","file_ext":"py","file_size_in_byte":2215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"65940496","text":"from mongoengine.base import get_document\nfrom mongoengine.queryset import QuerySet, Q\n\nfrom actstream.decorators import stream\nfrom actstream.registry import check\n\n\nclass ActionQuerySet(QuerySet):\n \"\"\"\n Default manager for Actions, accessed through Action.objects\n \"\"\"\n\n def public(self, *args, **kwargs):\n \"\"\"\n Only return public actions\n \"\"\"\n kwargs['public'] = True\n return self.filter(*args, **kwargs)\n\n @stream\n def actor(self, obj, **kwargs):\n \"\"\"\n Stream of most recent actions where obj is the actor.\n Keyword arguments will be passed to Action.objects.filter\n \"\"\"\n check(obj)\n return obj.actor_actions.public(**kwargs)\n\n @stream\n def target(self, obj, **kwargs):\n \"\"\"\n Stream of most recent actions where obj is the target.\n Keyword arguments will be passed to Action.objects.filter\n \"\"\"\n check(obj)\n return obj.target_actions.public(**kwargs)\n\n @stream\n def action_object(self, obj, **kwargs):\n \"\"\"\n Stream of most recent actions where obj is the action_object.\n Keyword arguments will be passed to Action.objects.filter\n \"\"\"\n check(obj)\n return obj.action_object_actions.public(**kwargs)\n\n @stream\n def document_actions(self, document, **kwargs):\n \"\"\"\n Stream of most recent actions by any particular document\n \"\"\"\n check(document)\n if hasattr(document, '__name__'):\n doc_cls_name = document.__name__\n else:\n doc_cls_name = document.__class__.__name__\n\n return self.public(\n (Q(__raw__={'target._cls': doc_cls_name}) |\n Q(__raw__={'action_object._cls': doc_cls_name}) |\n Q(__raw__={'actor._cls': doc_cls_name})),\n **kwargs\n )\n\n @stream\n def any(self, obj, **kwargs):\n \"\"\"\n Stream of most recent actions where obj is the actor OR target OR action_object.\n \"\"\"\n check(obj)\n return self.public(\n Q(\n actor=obj\n ) | Q(\n target=obj\n ) | Q(\n action_object=obj\n ), **kwargs)\n\n @stream\n def user(self, obj, **kwargs):\n \"\"\"\n Stream of most recent actions by objects that the passed User obj is\n following.\n \"\"\"\n q = Q()\n qs = self.public()\n\n if not obj:\n return qs.none()\n\n check(obj)\n actors = []\n others = []\n\n if kwargs.pop('with_user_activity', False):\n actors.append(obj)\n\n follow_objects = get_document('actstream.Follow').objects.filter(\n user=obj).values_list('follow_object', 'actor_only').no_cache()\n\n for follow_object, actor_only in follow_objects():\n actors.append(follow_object)\n if not actor_only:\n others.append(follow_object)\n\n if len(actors) + len(others) == 0:\n return qs.none()\n\n if len(actors):\n q = q | Q(actor__in=actors)\n\n if len(others):\n q = q | Q(target__in=others) | Q(action_object__in=others)\n\n return qs.filter(q, **kwargs)\n\n\nclass FollowQuerySet(QuerySet):\n \"\"\"\n Manager for Follow document.\n \"\"\"\n\n def for_object(self, instance):\n \"\"\"\n Filter to a specific instance.\n \"\"\"\n check(instance)\n return self.filter(follow_object=instance)\n\n def is_following(self, user, instance):\n \"\"\"\n Check if a user is following an instance.\n \"\"\"\n if not user or user.is_anonymous():\n return False\n queryset = self.for_object(instance)\n return bool(queryset.filter(user=user).count())\n\n def followers_qs(self, actor):\n \"\"\"\n Returns a queryset of User objects who are following the given actor (eg my followers).\n \"\"\"\n check(actor)\n return self.for_object(actor).select_related()\n\n def followers(self, actor):\n \"\"\"\n Returns a list of User objects who are following the given actor (eg my followers).\n \"\"\"\n return [follow.user for follow in self.followers_qs(actor)]\n\n def following_qs(self, user, *documents):\n \"\"\"\n Returns a queryset of actors that the given user is following (eg who im following).\n Items in the list can be of any document unless a list of restricted models are passed.\n Eg following(user, User) will only return users following the given user\n\n TEST REQUIRED for __raw__ query\n \"\"\"\n qs = self.filter(user=user)\n ctype_filters = Q()\n for document in documents:\n check(document)\n ctype_filters |= Q(__raw__={'follow_object._cls': document.__name__})\n qs = qs.filter(ctype_filters)\n return qs.select_related()\n\n def following(self, user, *documents):\n \"\"\"\n Returns a list of actors that the given user is following (eg who im following).\n Items in the list can be of any document unless a list of restricted models are passed.\n Eg following(user, User) will only return users following the given user\n \"\"\"\n return [follow.follow_object for follow in self.following_qs(user, *documents)]\n","sub_path":"actstream/managers.py","file_name":"managers.py","file_ext":"py","file_size_in_byte":5320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"438451593","text":"# Copyright 2014 Knowledge Economy Developments Ltd\n# \n# Henry Gomersall\n# heng@kedevelopments.co.uk\n#\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# * Neither the name of the copyright holder nor the names of its contributors\n# may be used to endorse or promote products derived from this software without\n# 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. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n#\n\nfrom pyfftw import interfaces\n\nfrom .test_pyfftw_base import run_test_suites\n\nimport unittest\nimport numpy\nfrom numpy import fft as np_fft\nimport inspect\nimport warnings\nimport copy\nwarnings.filterwarnings('always')\n\nif numpy.version.version <= '1.6.2':\n # We overwrite the broken _cook_nd_args with a fixed version.\n from ._cook_nd_args import _cook_nd_args\n numpy.fft.fftpack._cook_nd_args = _cook_nd_args\n\ncomplex_dtypes = (numpy.complex64, numpy.complex128, numpy.clongdouble)\nreal_dtypes = (numpy.float32, numpy.float64, numpy.longdouble)\n\ndef make_complex_data(shape, dtype):\n ar, ai = dtype(numpy.random.randn(2, *shape))\n return ar + 1j*ai\n\ndef make_real_data(shape, dtype):\n return dtype(numpy.random.randn(*shape))\n\n\nfunctions = {\n 'fft': 'complex',\n 'ifft': 'complex', \n 'rfft': 'r2c',\n 'irfft': 'c2r',\n 'rfftn': 'r2c',\n 'hfft': 'c2r',\n 'ihfft': 'r2c',\n 'irfftn': 'c2r',\n 'rfft2': 'r2c',\n 'irfft2': 'c2r',\n 'fft2': 'complex',\n 'ifft2': 'complex',\n 'fftn': 'complex',\n 'ifftn': 'complex'}\n\nacquired_names = ('fftfreq', 'fftshift', 'ifftshift')\n\nclass InterfacesNumpyFFTTestModule(unittest.TestCase):\n ''' A really simple test suite to check the module works as expected.\n '''\n\n def test_acquired_names(self):\n for each_name in acquired_names:\n\n numpy_fft_attr = getattr(numpy.fft, each_name)\n acquired_attr = getattr(interfaces.numpy_fft, each_name)\n\n self.assertIs(numpy_fft_attr, acquired_attr)\n\n\nclass InterfacesNumpyFFTTestFFT(unittest.TestCase):\n\n io_dtypes = {\n 'complex': (complex_dtypes, make_complex_data),\n 'r2c': (real_dtypes, make_real_data),\n 'c2r': (complex_dtypes, make_complex_data)}\n\n validator_module = np_fft\n test_interface = interfaces.numpy_fft\n func = 'fft'\n axes_kw = 'axis'\n overwrite_input_flag = 'overwrite_input'\n default_s_from_shape_slicer = slice(-1, None)\n\n test_shapes = (\n ((100,), {}),\n ((128, 64), {'axis': 0}),\n ((128, 32), {'axis': -1}),\n ((59, 100), {}),\n ((59, 99), {'axis': -1}),\n ((59, 99), {'axis': 0}), \n ((32, 32, 4), {'axis': 1}),\n ((64, 128, 16), {}),\n )\n\n # invalid_s_shapes is:\n # (size, invalid_args, error_type, error_string)\n invalid_args = (\n ((100,), ((100, 200),), TypeError, ''),\n ((100, 200), ((100, 200),), TypeError, ''),\n ((100,), (100, (-2, -1)), TypeError, ''),\n ((100,), (100, -20), IndexError, ''))\n\n realinv = False\n\n @property\n def test_data(self):\n for test_shape, kwargs in self.test_shapes:\n axes = self.axes_from_kwargs(kwargs)\n s = self.s_from_kwargs(test_shape, kwargs)\n\n if self.realinv:\n test_shape = list(test_shape)\n test_shape[axes[-1]] = test_shape[axes[-1]]//2 + 1\n test_shape = tuple(test_shape)\n\n yield test_shape, s, kwargs\n\n def __init__(self, *args, **kwargs):\n\n super(InterfacesNumpyFFTTestFFT, self).__init__(*args, **kwargs)\n\n # Assume python 3, but keep backwards compatibility\n if not hasattr(self, 'assertRaisesRegex'):\n self.assertRaisesRegex = self.assertRaisesRegexp\n\n def validate(self, array_type, test_shape, dtype, \n s, kwargs):\n\n # Do it without the cache\n\n # without:\n interfaces.cache.disable()\n self._validate(array_type, test_shape, dtype, s, kwargs)\n\n def munge_input_array(self, array, kwargs):\n return array\n\n def _validate(self, array_type, test_shape, dtype, \n s, kwargs):\n\n input_array = self.munge_input_array(\n array_type(test_shape, dtype), kwargs)\n\n orig_input_array = copy.copy(input_array)\n\n np_input_array = numpy.asarray(input_array)\n \n if np_input_array.dtype == 'clongdouble':\n np_input_array = numpy.complex128(input_array)\n\n elif np_input_array.dtype == 'longdouble':\n np_input_array = numpy.float64(input_array)\n\n\n with warnings.catch_warnings(record=True) as w:\n # We catch the warnings so as to pick up on when\n # a complex array is turned into a real array\n\n if 'axes' in kwargs:\n axes = {'axes': kwargs['axes']}\n elif 'axis' in kwargs:\n axes = {'axis': kwargs['axis']}\n else:\n axes = {}\n\n try:\n test_out_array = getattr(self.validator_module, self.func)(\n copy.copy(np_input_array), s, **axes)\n\n except Exception as e:\n interface_exception = None\n try:\n getattr(self.test_interface, self.func)(\n copy.copy(input_array), s, **kwargs)\n except Exception as _interface_exception:\n # It's necessary to assign the exception to the\n # already defined variable in Python 3.\n # See http://www.python.org/dev/peps/pep-3110/#semantic-changes\n interface_exception = _interface_exception\n\n # If the test interface raised, so must this.\n self.assertEqual(type(interface_exception), type(e),\n msg='Interface exception raised. ' + \n 'Testing for: ' + repr(e))\n return\n\n output_array = getattr(self.test_interface, self.func)(\n copy.copy(input_array), s, **kwargs)\n\n if (functions[self.func] == 'r2c'):\n if numpy.iscomplexobj(input_array):\n if len(w) > 0:\n # Make sure a warning is raised\n self.assertIs(\n w[-1].category, numpy.ComplexWarning)\n \n self.assertTrue(\n numpy.allclose(output_array, test_out_array, \n rtol=1e-2, atol=1e-4))\n\n input_precision_dtype = numpy.asanyarray(input_array).real.dtype\n\n self.assertEqual(input_precision_dtype, \n output_array.real.dtype)\n\n if (not self.overwrite_input_flag in kwargs or \n not kwargs[self.overwrite_input_flag]):\n self.assertTrue(numpy.allclose(input_array,\n orig_input_array))\n\n return output_array\n\n def axes_from_kwargs(self, kwargs):\n \n argspec = inspect.getargspec(getattr(self.test_interface, self.func))\n default_args = dict(list(zip(\n argspec.args[-len(argspec.defaults):], argspec.defaults)))\n\n if 'axis' in kwargs:\n axes = (kwargs['axis'],)\n\n elif 'axes' in kwargs:\n axes = kwargs['axes']\n if axes is None:\n axes = default_args['axes']\n\n else:\n if 'axis' in default_args:\n # default 1D\n axes = (default_args['axis'],)\n else:\n # default nD\n axes = default_args['axes']\n\n if axes is None:\n axes = (-1,)\n\n return axes\n\n def s_from_kwargs(self, test_shape, kwargs):\n ''' Return either a scalar s or a tuple depending on\n whether axis or axes is specified\n '''\n argspec = inspect.getargspec(getattr(self.test_interface, self.func))\n default_args = dict(list(zip(\n argspec.args[-len(argspec.defaults):], argspec.defaults)))\n\n if 'axis' in kwargs:\n s = test_shape[kwargs['axis']]\n\n elif 'axes' in kwargs:\n axes = kwargs['axes']\n if axes is not None:\n s = []\n for each_axis in axes:\n s.append(test_shape[each_axis])\n else:\n # default nD\n s = []\n try:\n for each_axis in default_args['axes']:\n s.append(test_shape[each_axis])\n except TypeError:\n try:\n s = list(test_shape[\n self.default_s_from_shape_slicer])\n except TypeError:\n # We had an integer as the default, so force\n # it to be a list\n s = [test_shape[self.default_s_from_shape_slicer]]\n\n else:\n if 'axis' in default_args:\n # default 1D\n s = test_shape[default_args['axis']]\n else:\n # default nD\n s = []\n try:\n for each_axis in default_args['axes']:\n s.append(test_shape[each_axis])\n except TypeError:\n s = None\n\n return s\n\n def test_valid(self):\n dtype_tuple = self.io_dtypes[functions[self.func]]\n \n for dtype in dtype_tuple[0]:\n for test_shape, s, kwargs in self.test_data:\n s = None\n\n self.validate(dtype_tuple[1], \n test_shape, dtype, s, kwargs)\n\n def test_on_non_numpy_array(self):\n dtype_tuple = self.io_dtypes[functions[self.func]]\n \n array_type = (lambda test_shape, dtype: \n dtype_tuple[1](test_shape, dtype).tolist())\n\n for dtype in dtype_tuple[0]:\n for test_shape, s, kwargs in self.test_data:\n s = None\n\n self.validate(array_type, \n test_shape, dtype, s, kwargs)\n\n\n def test_fail_on_invalid_s_or_axes(self):\n dtype_tuple = self.io_dtypes[functions[self.func]]\n \n for dtype in dtype_tuple[0]:\n\n for test_shape, args, exception, e_str in self.invalid_args:\n input_array = dtype_tuple[1](test_shape, dtype)\n \n self.assertRaisesRegex(exception, e_str,\n getattr(self.test_interface, self.func), \n *((input_array,) + args))\n\n\n def test_same_sized_s(self):\n dtype_tuple = self.io_dtypes[functions[self.func]]\n for dtype in dtype_tuple[0]:\n for test_shape, s, kwargs in self.test_data:\n\n self.validate(dtype_tuple[1], \n test_shape, dtype, s, kwargs)\n\n def test_bigger_s(self):\n dtype_tuple = self.io_dtypes[functions[self.func]]\n for dtype in dtype_tuple[0]:\n for test_shape, s, kwargs in self.test_data:\n\n try:\n for each_axis, length in enumerate(s):\n s[each_axis] += 2\n except TypeError:\n s += 2\n\n self.validate(dtype_tuple[1], \n test_shape, dtype, s, kwargs)\n\n\n def test_smaller_s(self):\n dtype_tuple = self.io_dtypes[functions[self.func]]\n for dtype in dtype_tuple[0]:\n for test_shape, s, kwargs in self.test_data:\n\n try:\n for each_axis, length in enumerate(s):\n s[each_axis] -= 2\n except TypeError:\n s -= 2\n\n self.validate(dtype_tuple[1], \n test_shape, dtype, s, kwargs)\n\n def check_arg(self, arg, arg_test_values, array_type, test_shape, \n dtype, s, kwargs):\n '''Check that the correct arg is passed to the builder'''\n # We trust the builders to work as expected when passed\n # the correct arg (the builders have their own unittests).\n\n return_values = []\n input_array = array_type(test_shape, dtype)\n\n def fake_fft(*args, **kwargs):\n return_values.append((args, kwargs))\n return (args, kwargs)\n\n try:\n\n # Replace the function that is to be used\n real_fft = getattr(self.test_interface, self.func)\n setattr(self.test_interface, self.func, fake_fft)\n\n _kwargs = kwargs.copy()\n\n for each_value in arg_test_values:\n _kwargs[arg] = each_value\n builder_args = getattr(self.test_interface, self.func)(\n input_array.copy(), s, **_kwargs)\n \n self.assertTrue(builder_args[1][arg] == each_value)\n\n # make sure it was called\n self.assertTrue(len(return_values) > 0)\n except:\n raise\n \n finally:\n # Make sure we set it back\n setattr(self.test_interface, self.func, real_fft)\n\n # Validate it aswell \n for each_value in arg_test_values:\n _kwargs[arg] = each_value\n builder_args = getattr(self.test_interface, self.func)(\n input_array.copy(), s, **_kwargs)\n\n self.validate(array_type, test_shape, dtype, s, _kwargs)\n\n def test_auto_align_input(self):\n dtype_tuple = self.io_dtypes[functions[self.func]]\n\n for dtype in dtype_tuple[0]:\n for test_shape, s, kwargs in self.test_data:\n self.check_arg('auto_align_input', (True, False),\n dtype_tuple[1], test_shape, dtype, s, kwargs)\n\n def test_auto_contiguous_input(self):\n dtype_tuple = self.io_dtypes[functions[self.func]]\n\n for dtype in dtype_tuple[0]:\n for test_shape, s, kwargs in self.test_data:\n self.check_arg('auto_contiguous', (True, False), \n dtype_tuple[1], test_shape, dtype, s, kwargs)\n\n def test_bigger_and_smaller_s(self):\n dtype_tuple = self.io_dtypes[functions[self.func]]\n for dtype in dtype_tuple[0]:\n i = -1\n for test_shape, s, kwargs in self.test_data:\n\n try:\n for each_axis, length in enumerate(s):\n s[each_axis] += i * 2\n i *= i\n except TypeError:\n s += i * 2\n i *= i\n\n self.validate(dtype_tuple[1], \n test_shape, dtype, s, kwargs)\n\n\n def test_dtype_coercian(self):\n # Make sure we input a dtype that needs to be coerced\n if functions[self.func] == 'r2c':\n dtype_tuple = self.io_dtypes['complex']\n else:\n dtype_tuple = self.io_dtypes['r2c']\n\n for dtype in dtype_tuple[0]:\n for test_shape, s, kwargs in self.test_data:\n s = None\n\n self.validate(dtype_tuple[1], \n test_shape, dtype, s, kwargs)\n\n\n def test_planner_effort(self):\n '''Test the planner effort arg\n '''\n dtype_tuple = self.io_dtypes[functions[self.func]]\n test_shape = (16,)\n \n for dtype in dtype_tuple[0]:\n s = None\n if self.axes_kw == 'axis':\n kwargs = {'axis': -1}\n else:\n kwargs = {'axes': (-1,)}\n\n for each_effort in ('FFTW_ESTIMATE', 'FFTW_MEASURE', \n 'FFTW_PATIENT', 'FFTW_EXHAUSTIVE'):\n \n kwargs['planner_effort'] = each_effort\n \n self.validate(\n dtype_tuple[1], test_shape, dtype, s, kwargs)\n\n kwargs['planner_effort'] = 'garbage'\n\n self.assertRaisesRegex(ValueError, 'Invalid planner effort',\n self.validate, \n *(dtype_tuple[1], test_shape, dtype, s, kwargs))\n\n def test_threads_arg(self):\n '''Test the threads argument\n '''\n dtype_tuple = self.io_dtypes[functions[self.func]]\n test_shape = (16,)\n \n for dtype in dtype_tuple[0]:\n s = None\n if self.axes_kw == 'axis':\n kwargs = {'axis': -1}\n else:\n kwargs = {'axes': (-1,)}\n\n self.check_arg('threads', (1, 2, 5, 10), \n dtype_tuple[1], test_shape, dtype, s, kwargs)\n\n kwargs['threads'] = 'bleh'\n \n # Should not work\n self.assertRaises(TypeError,\n self.validate, \n *(dtype_tuple[1], test_shape, dtype, s, kwargs))\n\n\n def test_overwrite_input(self):\n '''Test the overwrite_input flag\n '''\n dtype_tuple = self.io_dtypes[functions[self.func]]\n \n for dtype in dtype_tuple[0]:\n for test_shape, s, _kwargs in self.test_data:\n s = None\n\n kwargs = _kwargs.copy()\n self.validate(dtype_tuple[1], test_shape, dtype, s, kwargs)\n \n self.check_arg(self.overwrite_input_flag, (True, False),\n dtype_tuple[1], test_shape, dtype, s, kwargs)\n\n def test_input_maintained(self):\n '''Test to make sure the input is maintained by default.\n '''\n dtype_tuple = self.io_dtypes[functions[self.func]]\n for dtype in dtype_tuple[0]:\n for test_shape, s, kwargs in self.test_data:\n\n input_array = dtype_tuple[1](test_shape, dtype)\n\n orig_input_array = input_array.copy()\n \n getattr(self.test_interface, self.func)(\n input_array, s, **kwargs)\n\n self.assertTrue(\n numpy.alltrue(input_array == orig_input_array))\n\n\nclass InterfacesNumpyFFTTestIFFT(InterfacesNumpyFFTTestFFT):\n func = 'ifft'\n\nclass InterfacesNumpyFFTTestRFFT(InterfacesNumpyFFTTestFFT):\n func = 'rfft'\n\nclass InterfacesNumpyFFTTestIRFFT(InterfacesNumpyFFTTestFFT):\n func = 'irfft'\n realinv = True\n\nclass InterfacesNumpyFFTTestHFFT(InterfacesNumpyFFTTestFFT):\n func = 'hfft'\n realinv = True\n\nclass InterfacesNumpyFFTTestIHFFT(InterfacesNumpyFFTTestFFT):\n func = 'ihfft'\n\nclass InterfacesNumpyFFTTestFFT2(InterfacesNumpyFFTTestFFT):\n axes_kw = 'axes' \n func = 'ifft2'\n test_shapes = (\n ((128, 64), {'axes': None}),\n ((128, 32), {'axes': None}),\n ((128, 32, 4), {'axes': (0, 2)}),\n ((59, 100), {'axes': (-2, -1)}),\n ((64, 128, 16), {'axes': (0, 2)}),\n ((4, 6, 8, 4), {'axes': (0, 3)}),\n )\n \n invalid_args = (\n ((100,), ((100, 200),), ValueError, 'Shape error'),\n ((100, 200), ((100, 200, 100),), ValueError, 'Shape error'),\n ((100,), ((100, 200), (-3, -2, -1)), ValueError, 'Shape error'),\n ((100, 200), (100, -1), TypeError, ''),\n ((100, 200), ((100, 200), (-3, -2)), IndexError, 'Invalid axes'),\n ((100, 200), ((100,), (-3,)), IndexError, 'Invalid axes'))\n\n def test_shape_and_s_different_lengths(self):\n dtype_tuple = self.io_dtypes[functions[self.func]]\n for dtype in dtype_tuple[0]:\n for test_shape, s, _kwargs in self.test_data:\n kwargs = copy.copy(_kwargs)\n try:\n s = s[1:]\n except TypeError:\n self.skipTest('Not meaningful test on 1d arrays.')\n\n del kwargs['axes']\n self.validate(dtype_tuple[1], \n test_shape, dtype, s, kwargs)\n\n\nclass InterfacesNumpyFFTTestIFFT2(InterfacesNumpyFFTTestFFT2):\n func = 'ifft2'\n\nclass InterfacesNumpyFFTTestRFFT2(InterfacesNumpyFFTTestFFT2):\n func = 'rfft2'\n\nclass InterfacesNumpyFFTTestIRFFT2(InterfacesNumpyFFTTestFFT2):\n func = 'irfft2'\n realinv = True \n\nclass InterfacesNumpyFFTTestFFTN(InterfacesNumpyFFTTestFFT2):\n func = 'ifftn'\n test_shapes = (\n ((128, 32, 4), {'axes': None}),\n ((64, 128, 16), {'axes': (0, 1, 2)}),\n ((4, 6, 8, 4), {'axes': (0, 3, 1)}),\n ((4, 6, 8, 4), {'axes': (0, 3, 1, 2)}),\n )\n\nclass InterfacesNumpyFFTTestIFFTN(InterfacesNumpyFFTTestFFTN):\n func = 'ifftn'\n\nclass InterfacesNumpyFFTTestRFFTN(InterfacesNumpyFFTTestFFTN):\n func = 'rfftn'\n\nclass InterfacesNumpyFFTTestIRFFTN(InterfacesNumpyFFTTestFFTN):\n func = 'irfftn'\n realinv = True \n\ntest_cases = (\n InterfacesNumpyFFTTestModule,\n InterfacesNumpyFFTTestFFT,\n InterfacesNumpyFFTTestIFFT,\n InterfacesNumpyFFTTestRFFT,\n InterfacesNumpyFFTTestIRFFT,\n InterfacesNumpyFFTTestHFFT,\n InterfacesNumpyFFTTestIHFFT,\n InterfacesNumpyFFTTestFFT2,\n InterfacesNumpyFFTTestIFFT2,\n InterfacesNumpyFFTTestRFFT2,\n InterfacesNumpyFFTTestIRFFT2,\n InterfacesNumpyFFTTestFFTN,\n InterfacesNumpyFFTTestIFFTN,\n InterfacesNumpyFFTTestRFFTN,\n InterfacesNumpyFFTTestIRFFTN,)\n\n#test_set = {'InterfacesNumpyFFTTestHFFT': ('test_valid',)}\ntest_set = None\n\nif __name__ == '__main__':\n\n run_test_suites(test_cases, test_set)\n","sub_path":"test/test_pyfftw_numpy_interface.py","file_name":"test_pyfftw_numpy_interface.py","file_ext":"py","file_size_in_byte":22520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"481725365","text":"from rest_framework import serializers\r\nfrom checkin.models import Report,UserManager\r\nfrom rest_framework import serializers,exceptions\r\nfrom django.contrib.auth import authenticate\r\nfrom django.contrib.auth.hashers import make_password\r\n\r\n\r\n#-----------serializers for Daily checkin and update instance-----------\r\n\r\nclass ReportDetailSerializer(serializers.ModelSerializer):\r\n class Meta:\r\n model = Report\r\n fields = '__all__'\r\n\r\n def update(self, instance, validated_data):\r\n instance.report = validated_data.get('report',instance.report)\r\n instance.task_completed = validated_data.get('task_completed',instance.task_completed)\r\n instance.task_not_completed_reason = validated_data.get('task_not_completed_reason',instance.task_not_completed_reason)\r\n instance.highlight = validated_data.get('highlight',instance.highlight)\r\n instance.date = validated_data.get('date',instance.date)\r\n instance.highlight_task_reason = validated_data.get('highlight_task_reason',instance.highlight_task_reason)\r\n instance.save()\r\n return instance\r\n\r\n\r\n\r\nclass UserManagerSerializer(serializers.ModelSerializer):\r\n class Meta:\r\n model = UserManager\r\n fields = '__all__'\r\n","sub_path":"checkin/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"81307743","text":"#!/usr/bin/env python\n\nimport os\nfrom setuptools import find_packages, setup\n\n\ntests_require = [\n 'pytest>=5.0.0,<6.0.0',\n]\n\n\nextras_require = {\n \"docs\": [\n 'bdc-readthedocs-theme @ git+git://github.com/brazil-data-cube/bdc-readthedocs-theme.git#egg=bdc-readthedocs-theme',\n 'Sphinx>=2.1.2',\n ],\n \"tests\": tests_require\n}\n\ng = {}\nwith open(os.path.join('bdc_sample', 'manifest.py'), 'rt') as fp:\n exec(fp.read(), g)\n version = g['version']\n\nsetup(\n name='bdc-sample',\n version=version,\n description='Brazilian Data Cube Sample package',\n author='Admin',\n author_email='admin@admin.com',\n url='https://github.com/brazil-data-cube/sampledb.git',\n packages=find_packages(),\n install_requires=[\n 'geopandas>=0.5.0',\n 'gdal>=2.3.3,<3',\n 'SQLAlchemy[postgresql]>=1.3.4',\n 'alembic>=1.0.10',\n 'GeoAlchemy2>=0.6.3',\n 'Shapely>=1.6.4',\n 'Flask>=1.1.1',\n 'Flask-Cors>=3.0.8',\n 'flask-restplus>=0.13.0',\n 'Flask-Script>=2.0.6',\n 'flask_bcrypt>=0.7.1',\n 'marshmallow-sqlalchemy>=0.19.0',\n 'bdc-core @ git+git://github.com/brazil-data-cube/bdc-core.git#egg=bdc-core'\n ],\n extras_require=extras_require,\n tests_require=tests_require,\n include_package_data=True,\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"400931539","text":"import numpy as np\nimport cv2\nimport os\n\nfrom keras.applications.inception_v3 import InceptionV3, preprocess_input\nfrom keras.models import Sequential, Model\nfrom keras.layers import Dropout, Flatten, Dense, GlobalAveragePooling2D\nfrom keras.optimizers import SGD\n\nfrom scipy.stats import entropy\nfrom my_align_script import get_file_paths\n\nIMG_WIDTH = 178\nIMG_HEIGHT = 218\nBATCH_SIZE = 16\nNUM_EPOCHS = 20\n\n# Import InceptionV3 Model\ninc_model = InceptionV3(\n # weights=\"my_data/celeba/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5\",\n include_top=False,\n input_shape=(IMG_HEIGHT, IMG_WIDTH, 3)\n)\n\nprint(\"number of layers:\", len(inc_model.layers))\n\n# Adding custom Layers\nx = inc_model.output\nx = GlobalAveragePooling2D()(x)\nx = Dense(1024, activation=\"relu\")(x)\nx = Dropout(0.5)(x)\nx = Dense(512, activation=\"relu\")(x)\npredictions = Dense(2, activation=\"softmax\")(x)\n\n\n# creating the final model \nmodel_ = Model(inputs=inc_model.input, outputs=predictions)\n\n# Lock initial layers to do not be trained\nfor layer in model_.layers[:52]:\n layer.trainable = False\n\n# compile the model\nmodel_.compile(\n optimizer=SGD(lr=0.0001, momentum=0.9),\n loss='categorical_crossentropy',\n metrics=['accuracy']\n)\n\nmodel_.load_weights('weights.best.inc.male.hdf5')\n\n\ndef gender_prediction(filename):\n \"\"\"\n predict the gender\n \n input:\n filename: str of the file name\n \n return:\n array of the prob of the targets.\n \n \"\"\"\n\n im = cv2.imread(filename)\n im = cv2.resize(cv2.cvtColor(im, cv2.COLOR_BGR2RGB), (178, 218)).astype(np.float32) / 255.0\n im = np.expand_dims(im, axis=0)\n\n # prediction\n result = model_.predict(im)\n\n return result\n\n\nexperiments = [\"pix2pix_5_epochs\", \"pix2pix_10_epochs\", \"cycle\"]\n\nresults_dir = {\n \"pix2pix_5_epochs\": os.path.join(\"inception_results_epoch5\", \"celeba_pix2pix\", \"test_5\", \"images\"),\n \"pix2pix_10_epochs\": os.path.join(\"inception_results\", \"celeba_pix2pix\", \"test_10\", \"images\"),\n \"cycle\": os.path.join(\"inception_results_epoch5\", \"celeba_cycle\", \"test_5\", \"images\")\n}\n\nfor experiment in experiments:\n print(\"experiment: \", experiment)\n\n paths, all_fnames = get_file_paths(results_dir[experiment], also_filenames=True)\n\n preds = []\n\n fnames = []\n\n for i in range(len(paths)):\n tmp = all_fnames[i].split(\".\")\n actual_filename, _ = tmp[0], tmp[1]\n if actual_filename[-6:] == \"fake_B\":\n fnames.append(all_fnames[i])\n pred = gender_prediction(paths[i])\n preds.append(pred[0])\n\n fnames = np.array(fnames)\n preds = np.array(preds)\n\n # Now compute the mean kl-div\n splits = 10\n split_scores = []\n n = len(fnames)\n\n for k in range(splits):\n part = preds[k * (n // splits): (k + 1) * (n // splits), :]\n py = np.mean(part, axis=0)\n scores = []\n for i in range(part.shape[0]):\n pyx = part[i, :]\n scores.append(entropy(pyx, py))\n split_scores.append(np.exp(np.mean(scores)))\n\n print(split_scores)\n\n print(\"avg split score: \", np.mean(np.array(split_scores)))\n print(\"std split score: \", np.std(np.array(split_scores)))\n\n max_prob = np.max(preds, axis=1)\n sorted_indexes = np.argsort(max_prob)\n worst_inception_score = fnames[sorted_indexes[:5]]\n best_inception_score = fnames[sorted_indexes[-5:]]\n\n print(\"best images are: \", best_inception_score)\n print(\"worst images are: \", worst_inception_score)\n print(\"\")\n print(\"\")\n","sub_path":"celeba_classification.py","file_name":"celeba_classification.py","file_ext":"py","file_size_in_byte":3511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"485838817","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri May 11 10:14:58 2018\n\n@author: ENFIUEMS02\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport networkx as nx\n\n\n#CRIANDO UM GRAFO DO TIPO GRID 2D\n\nN = 8\n\nG=nx.Graph()\n\nn = 0\nfor i in range(N):\n for j in range(N):\n G.add_node(n,pos=(i,j))\n n += 1\n\n#for i in G.nodes():\n# \n#mapping={0:'a',1:'b',2:'c'}\n#H=nx.relabel_nodes(G,mapping)\n\nG.add_edge(0,1, weight=0.1)\nG.add_edge(0,8, weight=0.2)\nG.add_edge(0,9, weight=0.3)\n\npos=nx.get_node_attributes(G,'pos')\nw=nx.get_edge_attributes(G,'weight')\n\nplt.figure()\nnx.draw(G, pos, with_labels=True)\nplt.axis('on')\nplt.show()\n\nprint(nx.info(G))\n\nprint(\"Vértices:\")\n\nfor i in G.nodes():\n print(i, \"pos= \", G.node(data='pos')[i])\n# print(i, pos[i])\n\nprint(\"Arestas:\")\nfor i in G.edges():\n print(i, \"weight= \",w[i])\n \nn = 0\nt = 0.2\nlista =[]\nfor i in G.edges():\n if w[i] <= t:\n lista.append(i)\nprint(\"arestas com weight < \", t, \": \", lista)\n","sub_path":"paper_netx_texture_v3.py","file_name":"paper_netx_texture_v3.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"171013772","text":"# -*- coding: utf-8 -*-\nimport datetime\nimport json\n\nbasic_attr ={\n 'fengyin':1,\n 'magic_defense':2,\n 'magic_damage':3,\n 'damage':4,\n 'speed':5,\n 'anti_fengyin':6,\n 'defense': 7,\n}\nadded_attr = {\n 'gushang': 1,\n 'shanghai':2,\n 'sudu':3,\n 'fashang':4,\n 'kuangbao':5,\n 'wubao':6,\n 'fabao':7,\n 'fengyin':8,\n 'fashangjieguo':9,\n 'chuanci':10,\n 'zhiliao':11,\n 'qixue':12,\n 'fangyu':13,\n 'fafang':14,\n 'kangwubao':15,\n 'kangfabao':16,\n 'kangfeng':17,\n 'gedang':18,\n 'huifu':19,\n}\n\nurl = \"jinglian_level=3&defense=11\"\n\nclass SearchCriteria:\n \"\"\"Lingshi search url builder\n \"\"\"\n def __init__(self, server='jjlvyboe'):\n self.base_url = 'https://xyq.cbg.163.com/cgi-bin/xyq_overall_search.py?'\n self.server = server\n self.act ='&act=overall_search_lingshi'\n self.page=1\n self.level_min = 0\n self.level_max = 140\n self.server_type='&server_type=3'\n self.logic = '&added_attr_logic=detail'\n self.added_attr=[]\n self.jinglian_level = 0\n self.basic_attr = {}\n self.query = self.base_url + self.server + self.act\n\n def Level_min(self, l):\n self.level_min = l\n self.query += '&equip_level_min=' + str(l)\n return self\n\n def Level_max(self, l):\n self.level_max = l\n self.query += '&equip_level_max=' + str(l)\n return self\n\n def Basic_attr(self, b):\n for key in b:\n if key in basic_attr:\n self.query +='&' + key + '=' + str(b[key])\n return self\n\n def Added_attr(self, a):\n for key in a:\n if key in added_attr:\n self.query +='&added_attr.' + str(added_attr[key]) +'=' + str(a[key])\n else:\n raise Exception('wrong added atr')\n return self\n\n def Page(self, page):\n self.page = page\n return self\n\n def Query(self):\n return self.query + '&page=' + str(self.page)\n\nclass Lingshi:\n \"\"\"Lingshi object stored in database\n \"\"\"\n def __init__(self):\n self.level = 0\n self.basic_attr = {}\n self.added_attr = {}\n self.price = 0\n self.create_time = ''\n self.sell_time = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n self.last_update_time = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n self.jinglian = 0\n self.server_type = 3\n self.eid = ''\n self.equip_id=0\n self.server_id = 0\n self.area_id = 0\n self.server_name = ''\n self.area_name = ''\n self.game_serverid = 0\n self.status = 1\n\n def Copy(self, data):\n \"\"\"Copy from ES object\n \"\"\"\n self.level = data['level']\n self.basic_attr = data['basic_attr']\n self.added_attr = data['added_attr']\n self.price = data['price']\n self.create_time = data['create_time']\n self.sell_time = data['sell_time']\n self.last_update_time = data['last_update_time']\n self.jinglian = data['jinglian']\n self.server_type = data['server_type']\n self.eid = data['eid']\n self.equip_id=data['equip_id']\n self.server_id = data['server_id']\n self.area_id = data['area_id']\n self.server_name = data['server_name']\n self.area_name = data['area_name']\n self.game_serverid = data['game_serverid']\n return self\n\n def From(self, raw):\n \"\"\"Build from raw json\n\n Example:\n {\n 'fengyin': 0,\n 'appointed_roleid': None,\n 'equip_count': 1,\n 'added_attr_repeat_num': 1,\n 'magic_defense': 0,\n 'pass_fair_show': 1,\n 'owner_uid': 235216,\n 'magic_damage': 0,\n 'equipid': 1814727,\n 'storage_type': 1,\n 'min_buyer_level': 50,\n 'equip_status': 2,\n 'serverid': 197,\n 'collect_num': 2,\n 'status': 2,\n 'equip_type': '27003',\n 'damage': 0,\n 'equip_level': 100,\n 'can_bargain': 0,\n 'create_time': '2018-06-13 11:17:49',\n 'seller_roleid': '50260679',\n 'special_effect': [],\n 'fair_show_end_time': '2018-06-17 11:32:49',\n 'id2': 26980254,\n 'speed': 0,\n 'min_buy_level': 50,\n 'game_ordersn': '105_1528859868_105983064',\n 'anti_fengyin': 0,\n 'added_attr': '{\"8\":1,\"1\":1,\"11\":1}',\n 'added_attr_num': 3,\n 'kindid': 61,\n 'eval_price': 11800,\n 'server_type': 3,\n 'jinglian_level': 4,\n 'game_serverid': '105',\n 'defense': 21,\n 'time_left': '17小时46分钟',\n 'price': '300.00',\n 'server_name': '中岳嵩山',\n 'area_name': '河南1区',\n 'eid': '201806131100113-197-P8F3FFERVGCQ',\n 'areaid': 49\n },\n \"\"\"\n self.level = raw['equip_level']\n self.basic_attr = self.build_basic(raw)\n self.added_attr = self.build_added(raw['added_attr'])\n self.price = raw['price']\n self.create_time = raw['create_time']\n self.sell_time = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n self.last_update_time = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n self.jinglian = raw['jinglian_level']\n self.server_type = raw['server_type']\n self.eid = raw['eid']\n self.server_id = raw['serverid']\n self.area_id = raw['areaid']\n self.server_name = raw['server_name']\n self.area_name = raw['area_name']\n self.game_serverid = raw['game_serverid']\n self.equip_id = raw['equipid']\n self.status = 1 # 1 正在出售 2 已售出 3 下架 4 取回 5 错误\n return self\n\n def With_detail(self, raw):\n \"\"\"From detail html\n \"eid\" : \"201805120000113-482-VEOULVDKQFWR\",\n\t\"serversn\" : \"1011\",\n\t\"equipid\" : \"1531189\",\n\t\"equip_type\" : \"27004\",\n\t\"status\" : \"2\",\n\t\"kindid\" : \"61\",\n \"equip_name\": \"悦碧水\",\n\t\"owner_nickname\" : \"\\u6d6e\\u68a6\\u82e5\\u66e6\\u00b0\",\n\t\"owner_roleid\" : \"23411115\",\n\t\"price\" : 401000.00,\n\t\"equip_level\" : 120,\n\t\"appointed_roleid\" : \"\",\n\t\"expire_time_desc\" : \"10天21小时57分钟\",\n\t\"create_time\" : \"2018-05-12 00:00:48\",\n\t\"selling_time\" : \"2018-07-15 09:51:40\",\n\t\"request_time\": \"2018-05-12 00:00:47\",\n\t\"fair_show_end_time_left\" : \"少于1分钟\",\n\t\"fair_show_end_time\" : \"2018-05-16 00:15:48\",\n\t\"is_selling\":1,\n\t\"is_pass_fair_show\":1,\n\t\"game_ordersn\" : \"1011_1526054447_1012126821\",\n\t\"is_seller_online\" : false,\n\t\"storage_type\" : 1,\n\t\"equip_count\" : 1,\n\t\"server_id\" : 482,\n\t\"highlights\" : [],\n\t\"can_bargin\" : 0,\n\t\"valid_bargain_resp\" : safe_json_decode('null'),\n\t\"equip_detail_type\": \"lingshi\",\n\t\"if_seller_have_more_equips\" : \"\"\n \"\"\"\n\n if raw['status'] == \"-1\":\n self.status = 5\n self.last_update_time = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n return\n\n self.price = raw['price']\n self.sell_time = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n self.last_update_time = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n\n\n if raw['status'] == \"1\":\n self.status = 3\n elif raw['status'] == \"2\":\n self.status = 1\n elif raw['status'] == \"6\" or raw['status'] == \"4\":\n self.status = 2\n elif raw['status'] == \"0\":\n self.status = 4\n else:\n print(\"!!!!!!!!!!!!\", raw['server_id'], raw['eid'], raw['status'])\n\n\n def To_json(self):\n return json.loads(json.dumps(self.__dict__))\n\n def build_basic(self, raw):\n a = {}\n for key in basic_attr:\n a[key] = raw[key]\n return a\n\n def build_added(self, str):\n a = json.loads(str)\n inv_map = {v: k for k, v in added_attr.items()}\n keys = list(a.keys())\n for key in keys:\n a[inv_map[int(key)]] = a[key]\n a.pop(key)\n return a\n\n\n\n\n","sub_path":"source/ls_metadata.py","file_name":"ls_metadata.py","file_ext":"py","file_size_in_byte":7865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"129438141","text":"import sys\nfrom sqlalchemy import create_engine\nimport pandas as pd\nfrom sklearn.model_selection import GridSearchCV, train_test_split\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer\nfrom sklearn.multioutput import MultiOutputClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import classification_report, accuracy_score\nimport pickle\nimport nltk\nimport re\nnltk.download('stopwords')\nfrom nltk.tokenize import word_tokenize\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.corpus import stopwords\n\n\ndef load_data(database_filepath):\n \"\"\"\n Description: load data from database\n Arguments:\n database_filepath: location of the database\n Returns:\n X: training data (features/messages)\n y: labels of the training data (categories)\n category_colnames: labels/categories list\n \"\"\"\n # load data from database\n engine = create_engine('sqlite:///' + database_filepath)\n df = pd.read_sql_table('DisasterMessages', con = engine)\n X = df['message'].values\n y = df.iloc[:,4:]\n category_colnames = y.columns\n\n return X, y, category_colnames\n\ndef tokenize(text): \n \"\"\"\n Description: tokenize text\n Arguments:\n text: message\n Returns:\n clean_tokens: message after normalizing, tokenizing, and lemmatizing\n \"\"\"\n normalized_text = re.sub(r\"[^a-zA-Z0-9]\",\" \", text.lower())\n tokens = word_tokenize(normalized_text)\n \n words = [w for w in tokens if w not in stopwords.words(\"english\")]\n lemmatizer = WordNetLemmatizer()\n clean_tokens = []\n \n for t in words:\n clean_t = lemmatizer.lemmatize(t).strip()\n clean_tokens.append(clean_t) \n return clean_tokens\n\ndef build_model():\n \"\"\"\n Description: build and optimize ML pipeline\n Arguments:\n None\n Returns:\n model: trained model\n \"\"\"\n pipeline = Pipeline([\n ('vect', CountVectorizer(tokenizer=tokenize)),\n ('tfidf', TfidfTransformer()),\n ('clf', MultiOutputClassifier(RandomForestClassifier()))\n ])\n\n parameters = {\n# 'vect__ngram_range': ((1, 1), (1, 2)),\n# 'clf__estimator__n_estimators': [50, 100, 200],\n 'clf__estimator__min_samples_split': [2, 4],\n 'clf__estimator__criterion': ['entropy', 'gini'],\n }\n\n model = GridSearchCV(pipeline, param_grid=parameters)\n return model\n \ndef evaluate_model(model, X_test, Y_test, category_names):\n \"\"\"\n Description: evaluate ML model\n Arguments:\n model: ML model to be evaluated\n X_test: testing data (features/messages)\n Y_test: labels of the testing data (categories)\n Category_names:labels/categories list\n Returns:\n None\n \"\"\"\n y_pred = model.predict(X_test)\n for i in range(len(category_names)):\n print(\"Label:\", category_names[i],\"\\n\", classification_report(Y_test.iloc[:, i].values, y_pred[:, i], target_names=category_names))\n print('Accuracy of %25s: %.2f' %(category_names[i], accuracy_score(Y_test.iloc[:, i].values, y_pred[:,i]))) \n pass \n# accuracy = accuracy_score(Y_test.values, y_pred) #(Y_test.values == y_pred).mean()\n# print(classification_report(y_pred, Y_test.values, target_names=category_names))\n# print('Accuracy: {}'.format(accuracy)) #*100))\n# pass\n\n# y_preds = model.predict(X_test)\n# print(classification_report(y_preds, Y_test.values, target_names=category_names))\n# print(\"**** Accuracy scores for each category *****\\n\")\n# for i in range(36):\n# print(\"Accuracy score for \" + Y_test.columns[i], accuracy_score(Y_test.values[:,i],y_preds[:,i]))\n\n\ndef save_model(model, model_filepath):\n \"\"\"\n Description: save ML model\n Arguments:\n model: ML model to be saved\n model_filepath: location to save the model\n Returns:\n None\n \"\"\"\n pickle.dump(model, open(model_filepath, 'wb'))\n pass\n\ndef main():\n if len(sys.argv) == 3:\n database_filepath, model_filepath = sys.argv[1:]\n print('Loading data...\\n DATABASE: {}'.format(database_filepath))\n X, Y, category_names = load_data(database_filepath)\n X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2)\n \n print('Building model...')\n model = build_model()\n \n print('Training model...')\n model.fit(X_train, Y_train)\n \n print('Evaluating model...')\n evaluate_model(model, X_test, Y_test, category_names)\n\n print('Saving model...\\n MODEL: {}'.format(model_filepath))\n save_model(model, model_filepath)\n\n print('Trained model saved!')\n\n else:\n print('Please provide the filepath of the disaster messages database '\\\n 'as the first argument and the filepath of the pickle file to '\\\n 'save the model to as the second argument. \\n\\nExample: python '\\\n 'train_classifier.py ../data/DisasterResponse.db classifier.pkl')\n\nif __name__ == '__main__':\n main()","sub_path":"models/train_classifier.py","file_name":"train_classifier.py","file_ext":"py","file_size_in_byte":5081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"404579807","text":"class SpecError(ValueError):\n \"\"\"\n This error class is used when an invalid format is found while parsing an\n object in the spec.\n \"\"\"\n def __init__(self, message, path=None, element=None):\n self.element = element\n self.message = message\n self.path = path\n\n\nclass ReferenceResolutionError(SpecError):\n \"\"\"\n This error class is used when resolving a reference fails, usually because\n of a malformed path in the reference.\n \"\"\"\n","sub_path":"openapi3/errors.py","file_name":"errors.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"229735096","text":"\"\"\"\nFuel Injection Perfection\n=========================\n\nCommander Lambda has asked for your help to refine the automatic quantum antimatter fuel injection system for her LAMBCHOP doomsday device. It's a great chance for you to get a closer look at the LAMBCHOP - and maybe sneak in a bit of sabotage while you're at it - so you took the job gladly.\n\nQuantum antimatter fuel comes in small pellets, which is convenient since the many moving parts of the LAMBCHOP each need to be fed fuel one pellet at a time. However, minions dump pellets in bulk into the fuel intake. You need to figure out the most efficient way to sort and shift the pellets down to a single pellet at a time.\n\nThe fuel control mechanisms have three operations:\n\n1) Add one fuel pellet\n2) Remove one fuel pellet\n3) Divide the entire group of fuel pellets by 2 (due to the destructive energy released when a quantum antimatter pellet is cut in half, the safety controls will only allow this to happen if there is an even number of pellets)\n\nWrite a function called answer(n) which takes a positive integer as a string and returns the minimum number of operations needed to transform the number of pellets to 1. The fuel intake control panel can only display a number up to 309 digits long, so there won't ever be more pellets than you can express in that many digits.\n\nFor example:\nanswer(4) returns 2: 4 -> 2 -> 1\nanswer(15) returns 5: 15 -> 16 -> 8 -> 4 -> 2 -> 1\n\n\nLanguages\n=========\n\nTo provide a Python solution, edit solution.py\nTo provide a Java solution, edit solution.java\n\nTest cases\n==========\n\nInputs:\n (string) n = \"4\"\nOutput:\n (int) 2\n\nInputs:\n (string) n = \"15\"\nOutput:\n (int) 5\n\"\"\"\n\nimport pytest\n\n# def answer(n):\n# int_n = int(n)\n# nearest_sq = 2**(int_n.bit_length() - 1)\n# diff = abs(int_n - nearest_sq)\n# if diff > nearest_sq // 2:\n# nearest_sq *= 2\n# return abs(nearest_sq - int_n) + nearest_sq.bit_length() - 1\n\ndef trail_zeros(num):\n z = 0\n num, rem = divmod(num, 2)\n while rem == 0 and num != 1:\n z += 1\n num, rem = divmod(num, 2)\n if num == 1 and rem == 0:\n z += 1\n return z\n\ndef answer(n):\n count = 0\n current = int(n)\n while True:\n zeros = trail_zeros(current)\n count += zeros\n current //= 2**zeros\n if current == 1:\n return count\n if current == 3: # corner case pow of 2\n return count + 2\n high = current + 1\n low = current - 1\n count += 1\n if trail_zeros(low) < trail_zeros(high):\n current = high\n else:\n current = low\n\ntest_list = [\n (\"2\", 1),\n (\"3\", 2),\n (\"4\", 2),\n (\"15\", 5),\n (\"16\", 4),\n (\"30\", 6),\n (\"25\", 6),\n (\"24\", 5),\n (\"256\", 8),\n (\"258\", 9),\n]\n\n@pytest.mark.parametrize(\"val, exp\", test_list)\ndef test_answer(val, exp):\n assert answer(val) == exp\n","sub_path":"foobar/foo4p2.py","file_name":"foo4p2.py","file_ext":"py","file_size_in_byte":2891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"624051393","text":"# -*- coding: utf-8 -*-\n\nimport datetime\nimport random\n\nfrom chartit import Chart, DataPool, PivotChart, PivotDataPool\nfrom django.db.models import Avg, Count, Sum\nfrom django.http import HttpResponse\nfrom django.shortcuts import render, render_to_response\n\n# Create your views here.\nfrom chartapp.models import (ERR_DICT, STILL_RUNNING, SUCCESS, UNKNOWN,\n FailedStat, MonthlyWeatherByCity, SalesHistory)\nfrom config import settings\n\n\ndef test(request):\n MonthlyWeatherByCity.objects.all().delete()\n for x in range(20):\n MonthlyWeatherByCity.objects.create(\n month=random.randrange(1, 13),\n boston_temp=random.randint(10, 30),\n houston_temp=random.randint(10, 30),\n new_york_temp=random.randint(10, 30),\n san_franciso_temp=random.randint(10, 30)\n )\n\n ds = DataPool(\n series=[{'options': {\n 'source': MonthlyWeatherByCity.objects.all()},\n 'terms': [\n 'month',\n 'boston_temp',\n 'houston_temp']}\n ])\n\n def monthname(month_num):\n names = {1: 'Jan', 2: 'Feb', 3: 'Mar', 4: 'Apr', 5: 'May', 6: 'Jun',\n 7: 'Jul', 8: 'Aug', 9: 'Sep', 10: 'Oct', 11: 'Nov', 12: 'Dec'}\n return names[month_num]\n\n try:\n cht = Chart(\n datasource=ds,\n series_options=[{'options': {\n 'type': 'line'},\n 'terms': {\n 'month': [\n 'boston_temp']\n }},\n {'options': {\n 'type': 'pie',\n 'center': [150, 100],\n 'size': '50%'},\n 'terms': {\n 'month': [\n 'houston_temp']\n }}],\n chart_options={'title': {\n 'text': 'Weather Data of Boston (line) and Houston (pie)'}},\n x_sortf_mapf_mts=[(None, monthname, False),\n (None, monthname, False)])\n except Exception as e:\n raise e\n return render_to_response('index.html', {'weatherchart': cht, 'STATIC_URL': settings.STATIC_URL})\n\n\ndef index(request):\n MonthlyWeatherByCity.objects.all().delete()\n for x in range(20):\n MonthlyWeatherByCity.objects.create(\n month=x,\n boston_temp=random.randint(10, 30),\n houston_temp=random.randint(10, 30),\n new_york_temp=random.randint(10, 30),\n san_franciso_temp=random.randint(10, 30)\n )\n # Step 1: Create a DataPool with the data we want to retrieve.\n weatherdata = \\\n DataPool(\n series=[{'options': {\n 'source': MonthlyWeatherByCity.objects.all()},\n 'terms': [\n 'month',\n 'san_franciso_temp',\n 'new_york_temp',\n 'houston_temp',\n 'boston_temp']}\n ])\n\n # Step 2: Create the Chart object\n cht = Chart(\n datasource=weatherdata,\n series_options=[{'options': {\n 'type': 'column',\n 'stacking': False},\n 'terms': {\n 'month': [\n 'boston_temp',\n 'houston_temp', ]\n }},\n {'options': {\n 'type': 'line',\n 'stacking': False},\n 'terms': {\n 'month': [\n 'new_york_temp',\n 'san_franciso_temp']\n }}],\n chart_options={'title': {\n 'text': u'支持中文吗'},\n 'xAxis': {\n 'title': {\n 'text': 'Month number'}}})\n # Step 3: Send the chart object to the template.\n return render_to_response('index.html', {'weatherchart': cht, 'STATIC_URL': settings.STATIC_URL})\n\n\nfrom debug_toolbar_line_profiler import profile_additional\nfrom chartapp.models import FailedStat\n# @profile_additional(FailedStat.random)\ndef pie(request, top_n=10):\n def err_map(item):\n return ERR_DICT.get(item, 'UNKNOWN')\n\n FailedStat.objects.all().delete()\n FailedStat.random(500)\n # Step 2: Create the Chart object\n ds = DataPool(\n series=[\n {\n 'options': {\n 'source': FailedStat.objects.exclude(err_code__in=[\n UNKNOWN,\n SUCCESS,\n STILL_RUNNING\n ]).values('err_code').annotate(err_count=Count('err_code')).order_by('-err_count')[:top_n],\n },\n 'terms': [\n 'err_code',\n 'err_count',\n ]\n },\n ],\n )\n\n cht = Chart(\n datasource=ds,\n series_options=[\n {\n 'options': {\n 'type': 'pie',\n },\n 'terms': {\n 'err_code': ['err_count']\n }\n },\n ],\n chart_options={\n 'chart': {\n 'height': 600,\n },\n 'title': {\n 'text': u'Agent安装错误码统计图 - %s' % datetime.datetime.now().strftime('%Y-%m-%d')},\n 'xAxis': {\n 'title': {\n 'text': u'错误码'\n }\n },\n 'yAxis': [\n {\n 'title': {\n 'text': u'错误次数(次)'\n },\n },\n ],\n },\n x_sortf_mapf_mts=(None, err_map, True)\n )\n\n # Step 3: Send the chart object to the template.\n return render_to_response('index.html', {\n 'weatherchart': cht,\n 'STATIC_URL': settings.STATIC_URL\n })\n\n\ndef create_err_stat_chart(itype, top_n):\n def err_trans(item):\n return (ERR_DICT.get(int(item[0]), 'UNKNOWN'),)\n\n ds = PivotDataPool(\n series=[\n {\n 'options': {\n 'source': FailedStat.objects.exclude(err_code__in=[\n UNKNOWN,\n SUCCESS,\n STILL_RUNNING\n ]),\n 'pointPlacement': 'on',\n 'categories': 'err_code',\n # 'legend_by': 'err_code'\n },\n 'terms': {\n 'err_stat': Count('err_code'),\n }\n },\n ],\n top_n=int(top_n),\n top_n_term='err_stat',\n pareto_term='err_stat',\n sortf_mapf_mts=(None, err_trans, True)\n )\n\n # polar mode\n if itype == 'polar':\n chart_options = {\n 'chart': {\n 'polar': True,\n 'height': 600\n },\n 'title': {\n 'text': u'Agent安装错误码统计图 - %s' % datetime.datetime.now().strftime('%Y-%m-%d')},\n 'xAxis': {\n 'title': {\n 'text': ''\n }\n },\n 'yAxis': [\n {\n 'title': {\n 'text': ''\n },\n },\n ],\n 'tooltip': {\n 'shared': True\n },\n 'credits': {\n 'enabled': False,\n # 'text': 'agent-setup',\n # 'href': 'http://agent-setup.qcloud.com/'\n }\n }\n else:\n chart_options = {\n 'chart': {\n 'height': 600\n },\n 'title': {\n 'text': u'Agent安装错误码统计图 - %s' % datetime.datetime.now().strftime('%Y-%m-%d')},\n 'xAxis': {\n 'title': {\n 'text': u'错误码'\n }\n },\n 'yAxis': [\n {\n 'title': {\n 'text': u'错误次数(次)'\n },\n 'gridLineInterpolation': 'polygon',\n },\n ],\n 'tooltip': {\n 'shared': True\n },\n 'credits': {\n 'enabled': False,\n # 'text': 'agent-setup',\n # 'href': 'http://agent-setup.qcloud.com/'\n }\n }\n cht = PivotChart(\n datasource=ds,\n series_options=[\n {\n 'options': {\n 'type': 'column',\n },\n 'terms': [\n 'err_stat',\n ]\n },\n ],\n chart_options=chart_options\n )\n\n return cht\n\n\ndef create_err_stat_pie(top_n):\n def err_map(item):\n return ERR_DICT.get(item, 'UNKNOWN')\n\n # Step 2: Create the Chart object\n ds = DataPool(\n series=[\n {\n 'options': {\n 'source': FailedStat.objects.exclude(err_code__in=[\n UNKNOWN,\n SUCCESS,\n STILL_RUNNING\n ]).values('err_code').annotate(err_count=Count('err_code')).order_by('-err_count')[:top_n],\n },\n 'terms': [\n 'err_code',\n 'err_count',\n ]\n },\n ],\n )\n\n cht = Chart(\n datasource=ds,\n series_options=[\n {\n 'options': {\n 'type': 'pie',\n },\n 'terms': {\n 'err_code': ['err_count']\n }\n },\n ],\n chart_options={\n 'chart': {\n 'height': 600,\n },\n 'title': {\n 'text': u'Agent安装错误码统计图 - %s' % datetime.datetime.now().strftime('%Y-%m-%d')},\n 'xAxis': {\n 'title': {\n 'text': u'错误码'\n }\n },\n 'yAxis': [\n {\n 'title': {\n 'text': u'错误次数(次)'\n },\n },\n ],\n },\n x_sortf_mapf_mts=(None, err_map, True)\n )\n return cht\n\n\ndef fail_state(request, top_n):\n FailedStat.objects.all().delete()\n FailedStat.random(500)\n cht_polar = create_err_stat_chart('polar', top_n)\n cht_column = create_err_stat_chart('column', top_n)\n cht_pie = create_err_stat_pie(top_n)\n return render(request, 'chart.html', {\n 'chart_list': [cht_column, cht_polar, cht_pie],\n 'STATIC_URL': settings.STATIC_URL\n })\n","sub_path":"chartapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"566037746","text":"import random # Imports random for random questions\r\nimport os\r\nimport ben\r\nimport re\r\nben.intro(\"Computing controlled assessment\", 2.1, 2015)\r\n\r\n\r\ndef multi(n1, n2):\r\n print (n1, \"x\", n2)\r\n return n1 * n2\r\n\r\ndef add(n1, n2):\r\n print (n1, \"+\", n2)\r\n return n1 + n2\r\n \r\ndef min(n1, n2):\r\n print (n1, \"-\", n2)\r\n return n1 - n2\r\n\r\ndef file(name, clas, score):\r\n if os.path.exists(\"./\" + clas) == False:\r\n os.mkdir(\"./\" + clas)\r\n a = open(\"./\" + clas + \"/\" + name + \".txt\", \"a\")\r\n a.write(score + \"\\n\")\r\n a.close()\r\n\r\n\r\n \r\nstudentname = input(\"What is your name? \") # need to validate - done\r\ntestname = studentname.upper()\r\nnam = False\r\nwhile nam == False:\r\n if len(testname) == 0 or testname.isspace() == True:\r\n print(\"Error! You need to enter something!\")\r\n nam = False\r\n studentname = input(\"What is your name? \")\r\n testname = studentname.upper() \r\n elif not re.match(\"^[A-Z- ]*$\", testname):\r\n print (\"Error! Names can only have letters!\\n\")\r\n nam = False\r\n studentname = input(\"What is your name? \")\r\n testname = studentname.upper() \r\n else:\r\n break\r\n \r\n\r\nclas = input(\"What is your class? (A, B or C) \") # needs to validate and limit to 3 choices - done\r\nclas = clas.upper()\r\nwhile True:\r\n if clas == \"A\" or clas == \"B\" or clas == \"C\":\r\n break\r\n else:\r\n print (\"Error! That is not one of the options!\")\r\n clas = input(\"What is your class? (A, B or C)\") \r\n clas = clas.upper()\r\nscore = 0 # Creates the score var\r\n\r\n\r\nfor i in range (0,10):\r\n qchoice = random.randint(0,3) # Generates a random number used to decide which type of question to ask\r\n n1 = float(random.randint(0,10))\r\n n2 = float(random.randint(0,10)) # Generates numbers to do maths with\r\n \r\n if qchoice == 0:\r\n ans = multi(n1, n2) # Sets var \"ans\" to the answer of the question\r\n elif qchoice == 1:\r\n ans = add(n1, n2)\r\n else:\r\n ans = min(n1, n2)\r\n \r\n while True: # Validation\r\n try:\r\n uans = float(input (\"= \")) # Asks the user for their answer \r\n except ValueError:\r\n print (\"That is not a number.\")\r\n continue \r\n else:\r\n break\r\n \r\n if uans == ans: # If the user's answer is equal to the actual answer\r\n print (\"Correct!\\n\")\r\n score = score + 1 \r\n else: # If they got the answer wrong\r\n print (\"Incorrect!\")\r\n ans = str(ans)\r\n print (\"The actual answer was\", ans + \"\\n\")\r\n \r\nstudentname = str(studentname)\r\nclas = str(clas)\r\nscore = str(score)\r\nfile(studentname, clas, score)\r\n\r\nprint (success, \"You got\", score, \"out of 10.\")\r\n\r\nben.programend(requireexit=True)\r\n","sub_path":"python/task 2 (t2a1 - valdification).py","file_name":"task 2 (t2a1 - valdification).py","file_ext":"py","file_size_in_byte":2813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"642782530","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2018/11/21 17:49\n# @Author : ganliang\n# @File : ExcelUtil.py\n# @Desc : excel\nimport json\nimport logging\nimport os\nimport sys\nimport xlrd\nimport xlwt\n\nlog = logging\n\n\ndef to_excel(json_file, sheet_name, excel_name):\n \"\"\"\n 将json文件转化为excel文件\n :param json_file: json文件路径\n :param sheet_name: 表格名称\n :param excel_name: excel名称\n :return:\n \"\"\"\n if not os.path.exists(json_file):\n log.warning(msg=\"excel file not found!\")\n sys.exit(-1)\n workbook = xlwt.Workbook(encoding='utf-8', style_compression=0)\n worksheet = workbook.add_sheet(sheet_name, cell_overwrite_ok=True)\n font = xlwt.Font() # Create the Font\n font.name = 'Times New Roman'\n font.bold = True\n font.underline = True\n font.italic = True\n style = xlwt.XFStyle()\n style.font = font\n with open(json_file, \"r\") as file:\n row_index = 0\n for line in file:\n cell_index = 0\n josn_obj = json.loads(line)\n if row_index == 0:\n index = 0\n for json_key in josn_obj:\n worksheet.write(0, index, label=json_key)\n index += 1\n row_index += 1\n # 写入值\n for json_key in josn_obj:\n worksheet.write(row_index, cell_index, label=josn_obj[json_key])\n cell_index += 1\n row_index += 1\n workbook.save(excel_name)\n\n\ndef read_excel_to_array(excel_file):\n if not os.path.exists(excel_file):\n log.warning(msg=\"excel file not found!\")\n sys.exit(-1)\n result_datas = []\n workbook = xlrd.open_workbook(excel_file)\n for sheet_name in workbook.sheet_names():\n sheet = workbook.sheet_by_name(sheet_name)\n for row in sheet.get_rows():\n row_data = []\n for cell in row:\n row_data.append(cell.value)\n result_datas.append(row_data)\n return result_datas\n\n\ndef read_excel_to_json(excel_file):\n result_datas = read_excel_to_array(excel_file)\n json_datas, current_index, headers = [], 0, []\n for result_data in result_datas:\n if current_index == 0:\n headers = result_data\n current_index += 1\n else:\n json_dict = {}\n for index in range(len(headers)):\n json_dict.setdefault(headers[index], result_data[index])\n json_datas.append(json_dict)\n\n\nif __name__ == \"__main__\":\n # to_excel(\"hubei_bot_or_trojan_c.json\", \"湖北网络安全事件\", \"Excel_Workbook.xls\")\n # read_excel_to_array(\"Excel_Workbook.xls\")\n read_excel_to_json(\"Excel_Workbook.xls\")\n","sub_path":"src/util/ExcelUtil.py","file_name":"ExcelUtil.py","file_ext":"py","file_size_in_byte":2715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"489549231","text":"#!/usr/bin/env python3\n\n\"\"\"Problem 54: Poker hands\"\"\"\n\nfrom utils import get_path\n\n\nclass Card:\n # values are powers of 2\n values = {v: 1 << i for i, v in enumerate(\"23456789TJQKA\")}\n __slots__ = (\"kind\", \"suit\", \"value\")\n\n def __init__(self, kind, suit):\n self.kind = kind\n self.suit = suit\n self.value = Card.values[kind]\n\n def __repr__(self):\n return self.kind + self.suit\n\n\nclass Hand:\n __slots__ = (\"values\", \"same_suit\", \"consecutive_values\",\n \"quad\", \"trip\", \"pairs\")\n\n def __init__(self, cards):\n self.same_suit = cards[0].suit == cards[1].suit == cards[2].suit == \\\n cards[3].suit == cards[4].suit\n\n values = quad = trip = pairs = 0\n\n for card in cards:\n value = card.value\n\n if value & values:\n if value & pairs:\n if value & trip:\n quad |= value\n else:\n trip |= value\n else:\n pairs |= value\n else:\n values |= value\n\n pairs ^= trip\n trip ^= quad\n\n self.values = values\n self.quad = quad\n self.trip = trip\n self.pairs = pairs\n\n self.consecutive_values = values in {\n 0b11111,\n 0b111110,\n 0b1111100,\n 0b11111000,\n 0b111110000,\n 0b1111100000,\n 0b11111000000,\n 0b111110000000,\n 0b1111100000000,\n }\n\n def __lt__(self, other):\n \"\"\"Make instances of the class comparable\"\"\"\n for ours, theirs in zip(self.terms(), other.terms()):\n if ours != theirs:\n return ours < theirs\n\n def terms(self):\n \"\"\"Generate terms for comparison\"\"\"\n\n # Royal Flush: Ten, Jack, Queen, King, Ace, in same suit.\n # Is a case of Straight Flush.\n\n # Straight Flush: All cards are consecutive values of same suit.\n if self.consecutive_values and self.same_suit:\n yield self.values\n else:\n yield 0\n\n # Four of a Kind: Four cards of the same value.\n yield self.quad\n\n # Full House: Three of a kind and a pair.\n if self.trip and self.pairs:\n yield self.trip\n else:\n yield 0\n\n # Flush: All cards of the same suit.\n if self.same_suit:\n yield self.values\n else:\n yield 0\n\n # Straight: All cards are consecutive values.\n if self.consecutive_values:\n yield self.values\n else:\n yield 0\n\n # Three of a Kind: Three cards of the same value.\n if self.trip:\n yield self.trip\n yield self.trip ^ self.values\n else:\n yield 0\n\n # Two Pairs: Two different pairs.\n if self.pairs and (self.pairs & (self.pairs-1)):\n yield self.pairs\n yield self.pairs ^ self.values\n else:\n yield 0\n\n # One Pair: Two cards of the same value.\n if self.pairs:\n yield self.pairs\n yield self.pairs ^ self.values\n else:\n yield 0\n\n # High Card: Highest value card.\n yield self.values\n\n\ndef main():\n cnt = 0\n\n deck = {kind+suit: Card(kind, suit) for kind in \"23456789TJQKA\"\n for suit in \"CDHS\"}\n\n with get_path(\"data\", \"poker.txt\").open() as data_file:\n for line in data_file:\n cards = [deck[card] for card in line.split()] # example: 9C JD\n\n if Hand(cards[:5]) > Hand(cards[5:]):\n cnt += 1\n\n return cnt\n\n\nif __name__ == \"__main__\":\n print(main())\n","sub_path":"python/p054.py","file_name":"p054.py","file_ext":"py","file_size_in_byte":3709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"400852251","text":"#!/usr/bin/env python3\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom plot_act import plot_act_pop_mean, plot_act_trail_av\nfrom plot_bias import plot_bias\n\nimport seaborn as sns\nsns.set()\nplt.style.use('matplotlibrc')\n\ntextwidth = 5.5532\n\n#fig, ax = plt.subplots(3,2,figsize=(textwidth,0.7*textwidth))\nfig = plt.figure(figsize=(textwidth,textwidth*0.4))\nax1 = fig.add_subplot(121)\nax2 = fig.add_subplot(122)\n#ax5 = fig.add_subplot(325)\n\nfile = \"../../data/sim_results_single_run.npz\"\n\nlabels = [\"${\\\\bf A}\\\\ $ Neural Activity\",\n\"${\\\\bf B}\\\\ $ Bias\"]\n\n#plot_act_pop_mean(ax1,file)\nplot_act_trail_av(ax1,file)\nax1.set_title(labels[0], loc=\"left\")\nplot_bias(ax2,file)\nax2.set_title(labels[1], loc=\"left\")\n\nfig.tight_layout(pad=0.)\n\nfig.savefig(\"../../plots/res_comp_act_bias.png\",dpi=1000)\nfig.savefig(\"../../plots/res_comp_act_bias.pdf\")\n\nplt.show()\n","sub_path":"code_old/plotting/gen_result_figure_bias_adjust.py","file_name":"gen_result_figure_bias_adjust.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"213320598","text":"import numpy as np\nimport pickle\nfrom scipy.spatial.distance import pdist, squareform\n\n\ndef meanOrZero(array):\n mean = np.mean(array)\n if np.isnan(mean):\n return 0\n else:\n return mean\n\n\ndef split_control_treated(features, labels):\n control_indices = (features[:,0] == -1)\n treated_indices = (features[:,0] == 1)\n\n control_features = features[control_indices]\n control_labels = labels[control_indices]\n\n treated_features = features[treated_indices]\n treated_labels = labels[treated_indices]\n\n return control_features, treated_features, control_labels, treated_labels\n\n\ndef att(control_labels, treated_labels):\n return meanOrZero(treated_labels) - meanOrZero(control_labels)\n\n\ndef error_att(treated_features, control_labels, treated_labels, predictor):\n control_labels[control_labels==-1] = 0\n treated_labels[treated_labels==-1] = 0\n\n real_att = att(control_labels, treated_labels)\n\n cf_treated_features = np.copy(treated_features)\n cf_treated_features[:,0] = -1\n\n cf_treated_predictions = predictor.predict(cf_treated_features)\n treated_predictions = predictor.predict(treated_features)\n # print(np.shape(treated_features))\n # print(cf_treated_predictions)\n # print(treated_predictions)\n # cf_treated_predictions[cf_treated_predictions>0] = 1\n # cf_treated_predictions[cf_treated_predictions<=0] = 0\n\n # treated_predictions[treated_predictions>0] = 1\n # treated_predictions[treated_predictions<=0] = 0\n\n estimated_att = meanOrZero(treated_predictions - cf_treated_predictions)\n # print(\"Estimated att : {}\".format(estimated_att))\n return np.abs(real_att - estimated_att)\n\n\ndef policy(features, predictor, threshold):\n control_features = np.copy(features)\n control_features[:,0] = -1\n control_labels = predictor.predict(control_features)\n\n # print(\"control_labels : {}\".format(control_labels))\n # control_labels[control_labels>0] = 1\n # control_labels[control_labels<=0] = 0\n\n treated_features = np.copy(features)\n treated_features[:,0] = 1\n treated_labels = predictor.predict(treated_features)\n\n # print(\"treated_labels : {}\".format(treated_labels))\n\n # treated_labels[treated_labels>0] = 1\n # treated_labels[treated_labels<=0] = 0\n\n return (treated_labels - control_labels) > threshold\n\n\ndef policy_risk(features, labels, predictor, threshold=0):\n\n policies = policy(features, predictor, threshold)\n # print(\"Policies : {}\".format(policies))\n probability = meanOrZero(policies > 0)\n\n labels[labels == -1] = 0\n treated_positive = meanOrZero(labels[policies + features[:, 0] == 2])\n control_positive = meanOrZero(labels[policies + features[:, 0] == -1])\n\n return 1 - (treated_positive * probability + control_positive * (1 - probability))\n\n\ndef error_ate(features, f_labels, cf_labels, predictor): \n \n real_ate = np.mean(features[:, 0] * (f_labels - cf_labels))\n #print f_labels\n #print cf_labels\n\n control_features = np.copy(features)\n control_features[:, 0] = -1\n control_labels = predictor.predict(control_features)\n\n treated_features = np.copy(features)\n treated_features[:, 0] = 1\n treated_labels = predictor.predict(treated_features)\n\n estimated_ate = np.mean(treated_labels - control_labels)\n # print \"PREDICTED\"\n #print control_labels\n #print treated_labels\n\n return abs(estimated_ate - real_ate)\n\n\ndef pehe(features, f_labels, cf_labels, predictor):\n\n real_ite = np.array(features)[:,0] * (np.array(f_labels) - np.array(cf_labels))\n\n control_features = np.copy(features)\n control_features[:,0] = -1\n control_labels = predictor.predict(control_features)\n\n treated_features = np.copy(features)\n treated_features[:,0] = 1\n treated_labels = predictor.predict(treated_features)\n\n estimated_ite = treated_labels - control_labels\n\n return np.sqrt(np.mean((estimated_ite - real_ite)**2))\n\n\ndef pehe_nn(features, f_labels, predictor):\n # print \"ALLO\"\n Z = features\n m, n = np.shape(Z)\n same_group = squareform(pdist(Z[:,0].reshape(m,1))) == 0\n distance_matrix = squareform(pdist(Z))\n distance_matrix[same_group] = np.inf\n nearest_neighbors = np.argmin(distance_matrix, axis=0)\n\n cf_labels = []\n for index in nearest_neighbors:\n cf_labels.append(f_labels[index])\n cf_labels = np.array(cf_labels)\n\n real_ite = np.array(features)[:, 0] * (np.array(f_labels) - np.array(cf_labels))\n\n control_features = np.copy(features)\n control_features[:, 0] = -1\n control_labels = predictor.predict(control_features)\n\n treated_features = np.copy(features)\n treated_features[:, 0] = 1\n treated_labels = predictor.predict(treated_features)\n\n estimated_ite = treated_labels - control_labels\n\n return np.sqrt(np.mean((estimated_ite - real_ite)**2))\n\n","sub_path":"Code/metrics01.py","file_name":"metrics01.py","file_ext":"py","file_size_in_byte":4824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"167030042","text":"# -*- coding: utf8 -*-\n\nimport pandas as pd\nimport numpy as np\n\ntext = \"chatter/\"\n\ndef ready():\n d14 = pd.read_csv(text+'2gis.csv',encoding='utf-8')\n points = np.array(d14).tolist()\n\n dict_points = {}\n for point in points:\n point.remove(point[0])\n point.remove(point[0])\n point_name = point[0]#.lower()\n point.remove(point[0])\n dict_points[point_name] = point\n\n return dict_points\n\ndef get_count(key):\n try:\n return dict_points[key][12]\n except:\n return -1\n\ndef get_all_count(keys):\n res = []\n for key in keys:\n res.append([key,get_count(key)])\n return res\n\n# Данные за 2017 год\ndict_points = ready()\n#print(dict_points.keys())\n#print(get_all_count([\"посуда для ресторанов\",\"Аптеки\"]))\n","sub_path":"chatter/gis2.py","file_name":"gis2.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"310212488","text":"'''\nredis test\n'''\nimport redis\nimport re\n\npool = redis.ConnectionPool(host='127.0.0.1', port=6379, db=0)\nr = redis.StrictRedis(connection_pool=pool)\n# r.lpush()\n# r.sadd('sk', [1,3])\n# r.sadd('sk', [2,4])\n# r.sadd('sk', [6,9])\nr.sadd('sks', [9, 8])\nr.sadd('sks', [3, 7])\nr.sadd('sks', [93,])\n# # r.sismember()\n# result = r.smembers('sk')\n# print(type(result))\n# # print(result)\n# print(r.scard('sk'))\n# print(r.sismember('sks',[6,8]))\n# r.expire('sks',1)\nfor item in r.smembers('sks'):\n item = item.decode()\n print('before match == > %s ' % item)\n if re.match(r'\\[\\d+\\,\\s\\d+\\]$', item):\n print('item == >> %s' % item)\n else:\n print('匹配为none 。。。')\n # item = list(item.decode())\n # print('item type == > %s' % type(item))\n # print('list[0] == > %s' % item[0])\n # print('len == > %s' % len(item))\n # t_id = item.split(\",\")[0].strip(\"[\").strip(\"]\")\n # print(t_id)\n # s_id = item.split(\",\")[1].strip(\"]\")\n # s_id = 222222222\n # print('tid == >> {0} --- s_id == >> {1}',t_id,s_id)\n# # print(type(item))\n# lis = list(it)\n# print(type(lis))\n# print(lis)\n# lis = [1,2]\n# print(lis[0])\n# print(r.set('b', 'bbb'))\n# print(type(r.get('b')))\n# print(r.get('b').decode())\n\n\n# r.lpush('sk', [1, 3])\n# r.lpush('sk', [2, 4])\n# r.lpush('sk', [2, 4])\n# r.lpush('sk', [6])\n# r.expire('sk',10)\n# print(r.llen('sk'))\n# for item in range(0, r.llen('sk')):\n# item = r.lpop('sk').decode()\n# t_id = item.split(\",\")[0].strip(\"[\")\n# s_id = item.split(\",\")[1].strip(\"]\")\n# print('tid == >> {0} --- s_id == >> {1}',t_id,s_id)\n# print(item)\n\n# a = \"u'148\".encode('utf-8').decode('utf-8')\n# print(type(a))\n# print(a)\n\n# print(int(a))\n# print(filter(str.isdigit,\"u'148\".encode('utf-8')))\n# print(a)\n# print(type(a))\n# print(int(a.encode('utf-8').decode('utf-8')))\n# 60'\n# u'148\n# b = \"u'148\"\n# print(type(b.split(\"'\")[1]))\n# a = \"60'\"\n# print(type(int(a.split(\"'\")[0])))\n# #\n# print(\"127.0.0.1\".split('.'))\n# print(''.join(\"127.0.0.1\".split('.')))\nprint('===============')\n# list11 = [1,2]\n# for i in list11:\n# print(i)\n# print(i.split(\",\")[0])\n","sub_path":"callIn/redis_pra.py","file_name":"redis_pra.py","file_ext":"py","file_size_in_byte":2102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"472406148","text":"import csv\r\nfrom datetime import datetime\r\ndef getnumber_category():\r\n csv_reader1 = csv.reader(open('2015-10-5huizong.csv'))\r\n '''GBK的原因:支(衣)原体肺炎在数据中有‘1’和‘衣原体’两种标识'''\r\n f = open('number_category.csv', 'w+')\r\n for i in csv_reader1:\r\n x1 = i[0]\r\n x4 = i[4]\r\n x5 = i[5]\r\n x6 = i[6]\r\n x7 = i[7]\r\n x8 = i[8]\r\n if (x7 != '') or (x4 == '' and x5 != '' and x6 != '') or (x4 != '' and x5 == '' and x6 != '') or (\r\n x4 != '' and x5 != '' and x6 == '') or (x4 != '' and x5 != '' and x6 != ''):\r\n f.write(x1 + ',4' + '\\n')\r\n continue\r\n if x8 != '':\r\n f.write(x1 + ',5' + '\\n')\r\n continue\r\n if x4 != '' and x5 == '' and x6 == '':\r\n f.write(x1 + ',1' + '\\n')\r\n continue\r\n if x5 != '' and x4 == '' and x6 == '':\r\n f.write(x1 + ',2' + '\\n')\r\n continue\r\n if x6 != '' and x4 == '' and x5 == '':\r\n f.write(x1 + ',3' + '\\n')\r\n continue\r\n '''有不是肺炎的情况'''\r\n '''有数据只有4未给出具体是哪几种组合的情况'''\r\n '''有数据给出1和2组合未标注其为4的情况'''\r\n f.close()\r\n\r\n\r\ndef splittwocol(filename,outputcol1,ouputcol2,mode):\r\n csv_reader = csv.reader(open(filename))\r\n f1=open(outputcol1,mode)\r\n f2 = open(ouputcol2,mode)\r\n for i in csv_reader:\r\n f1.write(i[0]+'\\n')\r\n f2.write(i[1]+'\\n')\r\n f1.close()\r\n f2.close()\r\n\r\n\r\ndef get_number_age(filename,output,mode):\r\n csv_reader = csv.reader(open(filename))\r\n f = open(output, mode)\r\n for i in csv_reader:\r\n birth_date = datetime.strptime(i[1], \"%Y/%m/%d\")\r\n start_date = datetime.strptime(i[2], \"%Y/%m/%d %H:%M\")\r\n time = (start_date - birth_date).days\r\n f.write(i[0] + ','),\r\n temp = '%.2f' % (time / 365)\r\n f.write(str(temp) + '\\n')\r\n f.close()\r\n\r\n\r\ndef add_tiwen_fun(filename1,filename2,output,mode):\r\n csv_reader = csv.reader(open(filename1))\r\n csv_reader2 = csv.reader(open(filename2))\r\n number=[]\r\n parameter=[]\r\n for i in csv_reader:\r\n number.append(i[0])\r\n k=1\r\n while k=float(i[4])>=38.00:\r\n f.write(i[0]+','+i[4]+',1\\n')\r\n else:\r\n f.write(i[0] + ',' + i[4] + ',0\\n')\r\n except ValueError:\r\n f.write('')\r\n\r\n elif i[3] ==testname:\r\n # f.write(i[0])\r\n s=i[5].split('~')\r\n s0 ='%.2f'%(float(s[0]))\r\n s1 ='%.2f'%(float(s[1]))\r\n try:\r\n if float(s1)>=float(i[4])>=float(s0):\r\n f.write(i[0]+','+i[4]+',1\\n')\r\n else:\r\n f.write(i[0] + ',' + i[4] + ',0\\n')\r\n except ValueError:\r\n f.write('')\r\n f.close()\r\n\r\n\r\ndef average_value(filename):\r\n csv_reader = csv.reader(open(filename))\r\n value = [i[2] for i in csv_reader]\r\n count_value =0\r\n for k in range (0,len(value)):\r\n count_value+=float(value[k])\r\n return '%.2f'%(count_value/len(value))\r\n\r\n\r\ndef add0fun(filename,filename2,col,output,mode):\r\n csv_reader = csv.reader(open(filename))\r\n number = []\r\n parameter = []\r\n for i in csv_reader:\r\n number.append(i[0])\r\n for k in range(1,len(i)):\r\n parameter.append(i[k])\r\n f = open(output, mode)\r\n csv_reader2 = csv.reader(open(filename2))\r\n number2 = [i[0] for i in csv_reader2]\r\n for k in range(0,len(number2)):\r\n f.write(number2[k])\r\n j=0\r\n while j < len(number):\r\n if number2[k]==number[j]:\r\n for l in range(0,col):\r\n f.write(','+parameter[j*col+l])\r\n break\r\n j+=1\r\n if j==len(number):\r\n f.write(','+average_value(filename))\r\n f.write(','+'1')\r\n # pretend that the average value of test is always normal\r\n f.write('\\n')\r\n\r\n\r\ndef invoke_fun(dataset,testname,output,mode,number,outputtran,lastoutput,finaloutput):\r\n fun(dataset, testname, output, mode)\r\n add0fun(output, number, 2, outputtran, mode)\r\n add_data_fun(outputtran, 2, lastoutput, finaloutput, mode)\r\n\r\n\r\nif __name__==\"__main__\":\r\n print(\"main\")\r\n # getnumber_category()\r\n # delete the file number_category.csv from line 1262 to 1577\r\n # what's more 10797 10801 10809 10810 10811 10820\r\n # splittwocol('number_category.csv','Number.csv','Category.csv','w')\r\n # get_number_age('wholebasic.csv','number_age.csv','w')\r\n # add_data_fun('number_age.csv',1,'number.csv','Number_Age1.csv','w')\r\n\r\n # invoke_fun('xuechangguicheck.csv', '血小板分布宽度', 'col1.csv', 'w', 'Number.csv', 'col1tran.csv',\r\n # 'Number_Age1.csv', 'number_age_col1.csv')\r\n # invoke_fun('xuechangguicheck.csv', '嗜碱细胞绝对值', 'col3.csv', 'w', 'Number.csv', 'col3tran.csv',\r\n # 'number_age_col1.csv', 'number_age_col3.csv')\r\n # invoke_fun('xuechangguicheck.csv', '红细胞总数', 'col5.csv', 'w', 'Number.csv', 'col5tran.csv',\r\n # 'number_age_col3.csv', 'number_age_col5.csv')\r\n # invoke_fun('xuechangguicheck.csv', '紅細胞分布宽度标准差', 'col7.csv', 'w', 'Number.csv', 'col7tran.csv',\r\n # 'number_age_col5.csv', 'number_age_col7.csv')\r\n # invoke_fun('xuechangguicheck.csv', '平均红细胞体积', 'col9.csv', 'w', 'Number.csv', 'col9tran.csv',\r\n # 'number_age_col7.csv', 'number_age_col9.csv')\r\n # invoke_fun('xuechangguicheck.csv', '中性细胞绝对值', 'col11.csv', 'w', 'Number.csv', 'col11tran.csv',\r\n # 'number_age_col9.csv', 'number_age_col11.csv')\r\n # invoke_fun('xuechangguicheck.csv', '平均红细胞血红蛋白浓度', 'col13.csv', 'w', 'Number.csv', 'col13tran.csv',\r\n # 'number_age_col11.csv', 'number_age_col13.csv')\r\n #\r\n # invoke_fun('xuechangguicheck.csv','血小板总数','col15.csv','w','Number.csv','col15tran.csv','number_age_col13.csv','number_age_col15.csv')\r\n # invoke_fun('xuechangguicheck.csv','血红蛋白','col17.csv','w','Number.csv','col17tran.csv','number_age_col15.csv','number_age_col17.csv')\r\n # invoke_fun('xuechangguicheck.csv','淋巴细胞绝对值','col19.csv','w','Number.csv','col19tran.csv','number_age_col17.csv','number_age_col19.csv')\r\n # invoke_fun('xuechangguicheck.csv','白细胞总数','col21.csv','w','Number.csv','col21tran.csv','number_age_col19.csv','number_age_col21.csv')\r\n # invoke_fun('xuechangguicheck.csv','单核细胞百分比','col23.csv','w','Number.csv','col23tran.csv','number_age_col21.csv','number_age_col23.csv')\r\n # invoke_fun('xuechangguicheck.csv','单核细胞绝对值','col25.csv','w','Number.csv','col25tran.csv','number_age_col23.csv','number_age_col25.csv')\r\n # invoke_fun('xuechangguicheck.csv','淋巴细胞百分比','col27.csv','w','Number.csv','col27tran.csv','number_age_col25.csv','number_age_col27.csv')\r\n # invoke_fun('xuechangguicheck.csv','嗜碱细胞百分比','col29.csv','w','Number.csv','col29tran.csv','number_age_col27.csv','number_age_col29.csv')\r\n # invoke_fun('xuechangguicheck.csv','嗜酸细胞百分比','col31.csv','w','Number.csv','col31tran.csv','number_age_col29.csv','number_age_col31.csv')\r\n # invoke_fun('xuechangguicheck.csv','血小板压积','col33.csv','w','Number.csv','col33tran.csv','number_age_col31.csv','number_age_col33.csv')\r\n # invoke_fun('xuechangguicheck.csv','大血小板比率','col35.csv','w','Number.csv','col35tran.csv','number_age_col33.csv','number_age_col35.csv')\r\n # invoke_fun('xuechangguicheck.csv','红细胞压积','col37.csv','w','Number.csv','col37tran.csv','number_age_col35.csv','number_age_col37.csv')\r\n # invoke_fun('xuechangguicheck.csv','红细胞分布宽度变异系数','col39.csv','w','Number.csv','col39tran.csv','number_age_col37.csv','number_age_col39.csv')\r\n # invoke_fun('xuechangguicheck.csv','中性细胞百分比','col41.csv','w','Number.csv','col41tran.csv','number_age_col39.csv','number_age_col41.csv')\r\n # invoke_fun('xuechangguicheck.csv','平均红细胞血红蛋白含量','col43.csv','w','Number.csv','col43tran.csv','number_age_col41.csv','number_age_col43.csv')\r\n # invoke_fun('xuechangguicheck.csv','嗜酸细胞绝对值','col45.csv','w','Number.csv','col45tran.csv','number_age_col43.csv','number_age_col45.csv')\r\n # invoke_fun('xuechangguicheck.csv','血小板平均体积','col47.csv','w','Number.csv','col47tran.csv','number_age_col45.csv','number_age_col47.csv')\r\n # invoke_fun('xuechangguicheck.csv','C反应蛋白','col49.csv','w','Number.csv','col49tran.csv','number_age_col47.csv','number_age_col49.csv')\r\n # invoke_fun('niaoyefenxicheck.csv', '红细胞(镜检)', 'col58.csv', 'w', 'Number.csv', 'col58tran.csv', 'number_age_col57.csv','number_age_col58.csv')\r\n # invoke_fun('niaoyefenxicheck.csv', '白细胞(镜检)', 'col60.csv', 'w', 'Number.csv', 'col60tran.csv', 'number_age_col58.csv','number_age_col60.csv')\r\n # invoke_fun('niaoyefenxicheck.csv', '比重', 'col62.csv', 'w', 'Number.csv', 'col62tran.csv', 'number_age_col60.csv','number_age_col62.csv')\r\n # invoke_fun('niaoyefenxicheck.csv', 'PH值', 'col64.csv', 'w', 'Number.csv', 'col64tran.csv', 'number_age_col62.csv','number_age_col64.csv')\r\n # invoke_fun('shenghuafenxicheck.csv', '白蛋白', 'col66.csv', 'w', 'Number.csv', 'col66tran.csv', 'number_age_col64.csv','number_age_col66.csv')\r\n # invoke_fun('shenghuafenxicheck.csv', '丙氨酸氨基转移酶', 'col68.csv', 'w', 'Number.csv', 'col68tran.csv', 'number_age_col66.csv','number_age_col68.csv')\r\n # invoke_fun('shenghuafenxicheck.csv', '天门冬氨酸氨基转移���', 'col70.csv', 'w', 'Number.csv', 'col70tran.csv', 'number_age_col68.csv','number_age_col70.csv')\r\n #\r\n # add_tiwen_fun('tiwen.csv','number_age_col70.csv','final.csv','w')\r\n\r\n # add_tiwen_fun('tiwen.csv','Number.csv','tiwenprediction.csv','w')\r\n # add_data_fun('kmeanstiwen.csv',5,'number_age_col70.csv','finaldata70+5.csv','w')\r\n","sub_path":"Stage 5Class/get_data.py","file_name":"get_data.py","file_ext":"py","file_size_in_byte":12042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"181660474","text":"\"\"\"This module contains these Maxwell classes: `Maxwell`, `Maxwell2d`, and `Maxwell3d`.\"\"\"\n\nfrom __future__ import absolute_import\nimport os\nimport json\nimport io\nfrom .application.Analysis2D import FieldAnalysis2D\nfrom .application.Analysis3D import FieldAnalysis3D\nfrom .generic.DataHandlers import float_units\nfrom .generic.general_methods import generate_unique_name, aedt_exception_handler\nfrom .modules.Boundary import BoundaryObject\nfrom collections import OrderedDict\n\n\nclass Maxwell(object):\n def __init__(self):\n self.odefinition_manager = self.materials.odefinition_manager\n self.omaterial_manager = self.materials.omaterial_manager\n self.o_maxwell_parameters = self.odesign.GetModule(\"MaxwellParameterSetup\")\n if self.solution_type != \"Transient\":\n self.omodelsetup = None\n else:\n self.omodelsetup = self._odesign.GetModule(\"ModelSetup\")\n pass\n\n @property\n def symmetry_multiplier(self):\n \"\"\"Symmetry multiplier.\"\"\"\n return int(self.omodelsetup.GetSymmetryMultiplier())\n\n @property\n def windings(self):\n \"\"\"Windings.\"\"\"\n windings = self.oboundary.GetExcitationsOfType(\"Winding Group\")\n return list(windings)\n\n @property\n def design_file(self):\n \"\"\"Design file.\"\"\"\n design_file = os.path.join(self.working_directory, \"design_data.json\")\n return design_file\n\n @aedt_exception_handler\n def setup_ctrlprog(\n self, setupname, file_str=None, keep_modifications=False, python_interpreter=None, aedt_lib_dir=None\n ):\n \"\"\"Configure the transient design setup to run a specific control program.\n\n Parameters\n ----------\n setupname : str\n Name of the setup\n file_str : str, optional\n Name of the file. The default value is ``None``.\n keep_modifications : bool, optional\n Whether to save the changes. The default value is ``False``.\n python_interpreter : bool, optional\n The default value is ``None``.\n aedt_lib_dir : str, optional\n Full path to the ``AEDTLib`` directory. The default value is ``None``.\n\n Returns\n -------\n bool\n ``True`` when successful and ``False`` when failed.\n \"\"\"\n\n self._py_file = setupname + \".py\"\n ctl_path = self.working_directory\n ctl_file_compute = os.path.join(ctl_path, self._py_file)\n ctl_file = os.path.join(self.working_directory, self._py_file)\n\n if aedt_lib_dir:\n source_dir = aedt_lib_dir\n else:\n source_dir = self.pyaedt_dir\n\n if os.path.exists(ctl_file) and keep_modifications:\n with open(ctl_file, \"r\") as fi:\n existing_data = fi.readlines()\n with open(ctl_file, \"w\") as fo:\n first_line = True\n for line in existing_data:\n if first_line:\n first_line = False\n if python_interpreter:\n fo.write(\"#!{0}\\n\".format(python_interpreter))\n if line.startswith(\"work_dir\"):\n fo.write(\"work_dir = r'{0}'\\n\".format(ctl_path))\n elif line.startswith(\"lib_dir\"):\n fo.write(\"lib_dir = r'{0}'\\n\".format(source_dir))\n else:\n fo.write(line)\n else:\n if file_str is not None:\n with io.open(ctl_file, \"w\", newline=\"\\n\") as fo:\n fo.write(file_str)\n assert os.path.exists(ctl_file), \"Control Program file could not be created.\"\n\n self.oanalysis.EditSetup(\n setupname,\n [\n \"NAME:\" + setupname,\n \"Enabled:=\",\n True,\n \"UseControlProgram:=\",\n True,\n \"ControlProgramName:=\",\n ctl_file_compute,\n \"ControlProgramArg:=\",\n \"\",\n \"CallCtrlProgAfterLastStep:=\",\n True,\n ],\n )\n\n return True\n\n # Set eddy effects\n @aedt_exception_handler\n def eddy_effects_on(self, object_list, activate=True):\n \"\"\"Assign eddy effects on objects.\n\n Parameters\n ----------\n object_list : list\n List of objects.\n activate : bool, optional\n Whether to activate eddy effects. The default is ``True``.\n\n Returns\n -------\n bool\n ``True`` when successful and ``False`` when failed.\n\n \"\"\"\n EddyVector = [\"NAME:EddyEffectVector\"]\n for obj in object_list:\n EddyVector.append([\"NAME:Data\", \"Object Name:=\", obj, \"Eddy Effect:=\", activate])\n\n oModule = self.odesign.GetModule(\"BoundarySetup\")\n oModule.SetEddyEffect([\"NAME:Eddy Effect Setting\", EddyVector])\n return True\n\n @aedt_exception_handler\n def assign_current(self, object_list, amplitude=1, phase=\"0deg\", solid=True, swap_direction=False, name=None):\n \"\"\"Assign the source of the current.\n\n Parameters\n ----------\n object_list : list\n List of objects to assign the current source to.\n amplitude : float, optional\n Voltage amplitude in mV. The default is ``1``.\n phase : str, optional\n The default is ``\"0deg\"``.\n solid : bool, optional\n The default is ``True``.\n swap_direction : bool, optional\n The default is ``False``.\n name : str, optional\n The default is ``None``.\n\n Returns\n -------\n :class:`pyaedt.modules.Boundary.BoundaryObject`\n Boundary object.\n\n \"\"\"\n amplitude = str(amplitude) + \"A\"\n\n if not name:\n name = generate_unique_name(\"Current\")\n\n object_list = self.modeler._convert_list_to_ids(object_list)\n if self.is3d:\n if type(object_list[0]) is int:\n props = OrderedDict(\n {\n \"Faces\": object_list,\n \"Current\": amplitude,\n \"IsSolid\": solid,\n \"Point out of terminal\": swap_direction,\n }\n )\n else:\n props = OrderedDict(\n {\n \"Objects\": object_list,\n \"Current\": amplitude,\n \"Phase\": phase,\n \"IsSolid\": solid,\n \"Point out of terminal\": swap_direction,\n }\n )\n else:\n if type(object_list[0]) is str:\n props = OrderedDict({\"Objects\": object_list, \"Current\": amplitude, \"IsPositive\": swap_direction})\n else:\n self.logger.glb.warning(\"Input has to be a 2D Object.\")\n return False\n bound = BoundaryObject(self, name, props, \"Current\")\n if bound.create():\n\n self.boundaries.append(bound)\n return bound\n return False\n\n @aedt_exception_handler\n def assign_voltage(self, face_list, amplitude=1, name=None):\n \"\"\"Assign a voltage source to a list of faces.\n\n Parameters\n ----------\n face_list : list\n List of faces to assign a voltrage source to.\n amplitude : float, optional\n Voltage amplitude in mV. The default is ``1``.\n name : str, optional\n Name of the boundary. The default is ``None``.\n\n Returns\n -------\n :class:`pyaedt.modules.Boundary.BoundaryObject`\n Boundary object.\n\n \"\"\"\n\n amplitude = str(amplitude) + \"mV\"\n\n if not name:\n name = generate_unique_name(\"Voltage\")\n face_list = self.modeler._convert_list_to_ids(face_list)\n\n # if type(face_list) is not list and type(face_list) is not tuple:\n # face_list = [face_list]\n props = OrderedDict({\"Faces\": face_list, \"Voltage\": amplitude})\n bound = BoundaryObject(self, name, props, \"Voltage\")\n if bound.create():\n self.boundaries.append(bound)\n return bound\n return False\n\n @aedt_exception_handler\n def assign_voltage_drop(self, face_list, amplitude=1, swap_direction=False, name=None):\n \"\"\"Assign a voltage drop to a list of faces.\n\n Parameters\n ----------\n face_list : list\n List of faces to assign a voltage drop to.\n amplitude : float, optional\n Voltage amplitude in mV. The default is ``1``.\n swap_direction : bool, optional\n The default value is ``False``.\n name : str, optional\n Name of the boundary. The default is ``None``.\n\n Returns\n -------\n :class:`pyaedt.modules.Boundary.BoundaryObject`\n Boundary object.\n \"\"\"\n\n amplitude = str(amplitude) + \"mV\"\n\n if not name:\n name = generate_unique_name(\"VoltageDrop\")\n face_list = self.modeler._convert_list_to_ids(face_list)\n\n props = OrderedDict({\"Faces\": face_list, \"Voltage Drop\": amplitude, \"Point out of terminal\": swap_direction})\n bound = BoundaryObject(self, name, props, \"VoltageDrop\")\n if bound.create():\n self.boundaries.append(bound)\n return bound\n return False\n\n @aedt_exception_handler\n def assign_winding(\n self,\n coil_terminals=None,\n winding_type=\"Current\",\n is_solid=True,\n current_value=1,\n res=0,\n ind=0,\n voltage=0,\n parallel_branches=1,\n name=None,\n ):\n \"\"\"Assign a winding to a Maxwell design.\n\n Parameters\n ----------\n coil_terminals : list, optional\n List of faces to create the coil terminal on.\n The default is ``None``.\n winding_type : str, optional\n Type of the winding. Options are ``\"Current\"``, ``\"Voltage\"``,\n and ``\"External\"``. The default is ``\"Current\"``.\n is_solid : bool, optional\n Type of the winding. ``True`` is solid, ``False`` is stranded. The default is ``True``.\n current_value : float, optional\n Value of the current in amperes. The default is ``1``.\n res : float, optional\n Resistance in ohms. The default is ``0``.\n ind : float, optional\n Henry. The default is ``0``.\n voltage : float, optional\n Voltage value. The default is ``0``.\n parallel_branches : int, optional\n The default is ``1``.\n name : str, optional\n Name of the boundary. The default is ``None``.\n\n Returns\n -------\n :class:`pyaedt.modules.Boundary.BoundaryObject`\n Bounding object for the winding, otherwise only the bounding object.\n\n \"\"\"\n\n if not name:\n name = generate_unique_name(\"Winding\")\n\n props = OrderedDict(\n {\n \"Type\": winding_type,\n \"IsSolid\": is_solid,\n \"Current\": str(current_value) + \"A\",\n \"Resistance\": str(res) + \"ohm\",\n \"Inductance\": str(ind) + \"H\",\n \"Voltage\": str(voltage) + \"V\",\n \"ParallelBranchesNum\": str(parallel_branches),\n }\n )\n bound = BoundaryObject(self, name, props, \"Winding\")\n if bound.create():\n self.boundaries.append(bound)\n if type(coil_terminals) is not list:\n coil_terminals = [coil_terminals]\n coil_names = []\n for coil in coil_terminals:\n c = self.assign_coil(coil)\n if c:\n coil_names.append(c.name)\n\n self.add_winding_coils(bound.name, coil_names)\n return bound\n return False\n\n @aedt_exception_handler\n def add_winding_coils(self, windingname, coil_names):\n \"\"\"Add coils to the winding.\n\n Parameters\n ----------\n windingname : str\n Name of the winding.\n coil_names : list\n List of the coil names.\n\n Returns\n -------\n bool\n ``True`` when successful, ``False`` when failed.\n\n \"\"\"\n if self.modeler._is3d:\n self.oboundary.AddWindingTerminals(windingname, coil_names)\n else:\n self.oboundary.AddWindingCoils(windingname, coil_names)\n return True\n\n @aedt_exception_handler\n def assign_coil(self, input_object, conductor_number=1, polarity=\"Positive\", name=None):\n \"\"\"Assign coils to a list of objects or face IDs.\n\n Parameters\n ----------\n input_object : list\n List of objects or face IDs.\n conductor_number : int, optional\n Number of conductors. The default is ``1``.\n polarity : str, optional\n Type of the polarity. The default is ``\"Positive\"``.\n name : str, optional\n The default is ``None``.\n\n Returns\n -------\n CoilObject\n Coil object.\n\n \"\"\"\n if polarity == \"Positive\":\n point = False\n else:\n point = True\n\n input_object = self.modeler._convert_list_to_ids(input_object)\n\n if not name:\n name = generate_unique_name(\"Coil\")\n\n if type(input_object[0]) is str:\n if self.modeler._is3d:\n props2 = OrderedDict(\n {\"Objects\": input_object, \"Conductor number\": str(conductor_number), \"Point out of terminal\": point}\n )\n bound = BoundaryObject(self, name, props2, \"CoilTerminal\")\n else:\n props2 = OrderedDict(\n {\"Objects\": input_object, \"Conductor number\": str(conductor_number), \"PolarityType\": polarity}\n )\n bound = BoundaryObject(self, name, props2, \"Coil\")\n else:\n if self.modeler._is3d:\n props2 = OrderedDict(\n {\"Faces\": input_object, \"Conductor number\": str(conductor_number), \"Point out of terminal\": point}\n )\n bound = BoundaryObject(self, name, props2, \"CoilTerminal\")\n\n else:\n self.logger.glb.warning(\"Face Selection is not allowed in Maxwell 2D. Provide a 2D object.\")\n return False\n if bound.create():\n self.boundaries.append(bound)\n return bound\n return False\n\n @aedt_exception_handler\n def assign_force(self, input_object, reference_cs=\"Global\", is_virtual=True, force_name=None):\n \"\"\"Assign a force to one or more objects.\n\n Parameters\n ----------\n input_object : str, list\n One or more objects to assign the force to.\n reference_cs : str, optional\n The default is ``\"Global\"``.\n is_virtual : bool, optional\n Whether the force is virtual. The default is ``True.``\n force_name : str, optional\n Name of the force. The default is ``None``.\n\n Returns\n -------\n bool\n ``True`` when successful, ``False`` when failed.\n\n \"\"\"\n input_object = self.modeler._convert_list_to_ids(input_object, True)\n if not force_name:\n force_name = generate_unique_name(\"Force\")\n if self.design_type == \"Maxwell 3D\":\n self.o_maxwell_parameters.AssignForce(\n [\n \"NAME:\" + force_name,\n \"Reference CS:=\",\n reference_cs,\n \"Is Virtual:=\",\n is_virtual,\n \"Objects:=\",\n input_object,\n ]\n )\n else:\n self.o_maxwell_parameters.AssignForce(\n [\"NAME:\" + force_name, \"Reference CS:=\", reference_cs, \"Objects:=\", input_object]\n )\n return True\n\n @aedt_exception_handler\n def assign_torque(\n self, input_object, reference_cs=\"Global\", is_positive=True, is_virtual=True, axis=\"Z\", torque_name=None\n ):\n \"\"\"Assign a torque to one or more objects.\n\n Parameters\n ----------\n input_object : str or list\n One or more objects to assign the torque to.\n reference_cs : str, optional\n Name of the reference coordinate system. The default is ``\"Global\"``.\n is_positive : bool, optional\n Whether the torque is positive. The default is ``True``.\n is_virtual : bool, optional\n Whether the torque is virtual. The default is ``True``.\n axis : str, optional\n Axis to apply the torque to. The default is ``\"Z\"``.\n torque_name : str, optional\n Name of the torque. The default is ``None``.\n\n Returns\n -------\n bool\n ``True`` when successful, ``False`` when failed.\n\n \"\"\"\n input_object = self.modeler._convert_list_to_ids(input_object, True)\n if not torque_name:\n torque_name = generate_unique_name(\"Torque\")\n if self.design_type == \"Maxwell 3D\":\n self.o_maxwell_parameters.AssignTorque(\n [\n \"NAME:\" + torque_name,\n \"Is Virtual:=\",\n is_virtual,\n \"Coordinate System:=\",\n reference_cs,\n \"Axis:=\",\n axis,\n \"Is Positive:=\",\n is_positive,\n \"Objects:=\",\n input_object,\n ]\n )\n else:\n self.o_maxwell_parameters.AssignTorque(\n [\n \"NAME:\" + torque_name,\n \"Coordinate System:=\",\n reference_cs,\n \"Is Positive:=\",\n is_positive,\n \"Objects:=\",\n input_object,\n ]\n )\n return True\n\n @aedt_exception_handler\n def assign_force(self, input_object, reference_cs=\"Global\", is_virtual=True, force_name=None):\n \"\"\"Assign a force to the selection.\n\n Parameters\n ----------\n input_object : str, list\n One or more objects to assign a force to.\n reference_cs : str, optional\n Name of the reference coordinate system. The default is ``Global``.\n is_virtual : bool, optional\n Whether the force is virtual. The default is ``True``.\n force_name : str, optional\n Name of the force. The default is ``None``.\n\n Returns\n -------\n bool\n ``True`` when successful, ``False`` when failed.\n\n \"\"\"\n input_object = self.modeler._convert_list_to_ids(input_object, True)\n if not force_name:\n force_name = generate_unique_name(\"Force\")\n self.o_maxwell_parameters.AssignForce(\n [\n \"NAME:\" + force_name,\n \"Reference CS:=\",\n reference_cs,\n \"Is Virtual:=\",\n is_virtual,\n \"Objects:=\",\n input_object,\n ]\n )\n return True\n\n @aedt_exception_handler\n def solve_inside(self, name, activate=True):\n \"\"\"Solve inside.\n\n Parameters\n ----------\n name : str\n\n activate : bool, optional\n The default value is ``True``.\n\n Returns\n -------\n bool\n ``True`` when successful, ``False`` when failed.\n\n \"\"\"\n self.modeler.primitives[name].solve_inside = activate\n return True\n\n @aedt_exception_handler\n def analyze_from_zero(self):\n \"\"\"Analyze from zero.\n\n Returns\n -------\n bool\n ``True`` when successful, ``False`` when failed.\n\n \"\"\"\n self.oanalysis.ResetSetupToTimeZero(self._setup)\n self.analyze_nominal()\n return True\n\n @aedt_exception_handler\n def set_initial_angle(self, motion_setup, val):\n \"\"\"Set the initial angle.\n\n Parameters\n ----------\n motion_setup : str\n Name of the motion setup.\n val : float\n Value of the angle in degrees.\n\n Returns\n -------\n bool\n ``True`` when successful, ``False`` when failed.\n\n \"\"\"\n self.odesign.ChangeProperty(\n [\n \"NAME:AllTabs\",\n [\n \"NAME:Maxwell2D\",\n [\"NAME:PropServers\", \"ModelSetup:\" + motion_setup],\n [\"NAME:ChangedProps\", [\"NAME:Initial Position\", \"Value:=\", val]],\n ],\n ]\n )\n return True\n\n def __enter__(self):\n return self\n\n\nclass Maxwell3d(Maxwell, FieldAnalysis3D, object):\n \"\"\"Provides the Maxwell 3D application interface.\n\n This class allows you to connect to an existing Maxwell 3D design or create a\n new Maxwell 3D design if one does not exist.\n\n Parameters\n ----------\n projectname : str, optional\n Name of the project to select or the full path to the project\n or AEDTZ archive to open. The default is ``None``, in which\n case an attempt is made to get an active project. If no\n projects are present, an empty project is created.\n designname : str, optional\n Name of the design to select. The default is ``None``, in\n which case an attempt is made to get an active design. If no\n designs are present, an empty design is created.\n solution_type : str, optional\n Solution type to apply to the design. The default is\n ``None``, in which case the default type is applied.\n setup_name : str, optional\n Name of the setup to use as the nominal. The default is\n ``None``, in which case the active setup is used or\n nothing is used.\n specified_version : str, optional\n Version of AEDT to use. The default is ``None``, in which case\n the active version or latest installed version is used. This\n parameter is ignored when Script is launched within AEDT.\n NG : bool, optional\n Whether to launch AEDT in the non-graphical mode. The default\n is ``False``, in which case AEDT is launched in the graphical\n mode. This parameter is ignored when Script is launched within\n AEDT.\n new_desktop_session : bool, optional\n Whether to launch an instance of AEDT in a new thread, even if\n another instance of the ``specified_version`` is active on the\n machine. The default is ``True``. This parameter is ignored\n when Script is launched within AEDT.\n close_on_exit : bool, optional\n Whether to release AEDT on exit. The default is ``False``.\n student_version : bool, optional\n Whether to open the AEDT student version. The default is\n ``False``. This parameter is ignored when Script is launched\n within AEDT.\n\n Examples\n --------\n Create an instance of Maxwell 3D and open the specified\n project, which is named ``mymaxwell.aedt``.\n\n >>> from pyaedt import Maxwell3d\n >>> aedtapp = Maxwell3d(\"mymaxwell.aedt\")\n pyaedt info: Added design ...\n\n Create an instance of Maxwell 3D using the 2021 R1 release and open\n the specified project, which is named ``mymaxwell2.aedt``.\n\n >>> aedtapp = Maxwell3d(specified_version=\"2021.1\", projectname=\"mymaxwell2.aedt\")\n pyaedt info: Added design ...\n\n \"\"\"\n\n @property # for legacy purposes\n def dim(self):\n \"\"\"Dimensions.\"\"\"\n return \"3D\"\n\n def __init__(\n self,\n projectname=None,\n designname=None,\n solution_type=None,\n setup_name=None,\n specified_version=None,\n non_graphical=False,\n new_desktop_session=False,\n close_on_exit=False,\n student_version=False,\n ):\n \"\"\"\n Initialize the `Maxwell` class.\n \"\"\"\n self.is3d = True\n FieldAnalysis3D.__init__(\n self,\n \"Maxwell 3D\",\n projectname,\n designname,\n solution_type,\n setup_name,\n specified_version,\n non_graphical,\n new_desktop_session,\n close_on_exit,\n student_version,\n )\n Maxwell.__init__(self)\n\n\nclass Maxwell2d(Maxwell, FieldAnalysis2D, object):\n \"\"\"Provides the Maxwell 2D application interface.\n\n This class allows you to connect to an existing Maxwell 2D design or create a\n new Maxwell 2D design if one does not exist.\n\n Parameters\n ----------\n projectname : str, optional\n Name of the project to select or the full path to the project\n or AEDTZ archive to open. The default is ``None``, in which\n case an attempt is made to get an active project. If no\n projects are present, an empty project is created.\n designname : str, optional\n Name of the design to select. The default is ``None``, in\n which case an attempt is made to get an active design. If no\n designs are present, an empty design is created.\n solution_type : str, optional\n Solution type to apply to the design. The default is\n ``None``, in which case the default type is applied.\n setup_name : str, optional\n Name of the setup to use as the nominal. The default is\n ``None``, in which case the active setup is used or\n nothing is used.\n specified_version : str, optional\n Version of AEDT to use. The default is ``None``, in which case\n the active version or latest installed version is used.\n This parameter is ignored when Script is launched within AEDT.\n NG : bool, optional\n Whether to launch AEDT in the non-graphical mode. The default\n is ``False``, in which case AEDT is launched in the graphical mode.\n This parameter is ignored when Script is launched within AEDT.\n new_desktop_session : bool, optional\n Whether to launch an instance of AEDT in a new thread, even if\n another instance of the ``specified_version`` is active on the\n machine. The default is ``True``. This parameter is ignored when Script is launched within AEDT.\n close_on_exit : bool, optional\n Whether to release AEDT on exit. The default is ``False``.\n student_version : bool, optional\n Whether to open the AEDT student version. The default is ``False``.\n This parameter is ignored when Script is launched within AEDT.\n\n Examples\n --------\n Create an instance of Maxwell 2D and connect to an existing\n Maxwell 2D design or create a new Maxwell 2D design if one does\n not exist.\n\n >>> from pyaedt import Maxwell2d\n >>> aedtapp = Maxwell2d()\n\n Create an instance of Maxwell 2D and link to a project named\n ``projectname``. If this project does not exist, create one with\n this name.\n\n >>> aedtapp = Maxwell2d(projectname)\n\n Create an instance of Maxwell 2D and link to a design named\n ``designname`` in a project named ``projectname``.\n\n >>> aedtapp = Maxwell2d(projectname,designame)\n\n \"\"\"\n\n @property # for legacy purposes\n def dim(self):\n \"\"\"Dimensions.\"\"\"\n return self.modeler.dimension\n\n @property\n def geometry_mode(self):\n \"\"\"Geometry mode.\"\"\"\n return self.odesign.GetGeometryMode()\n\n def __init__(\n self,\n projectname=None,\n designname=None,\n solution_type=None,\n setup_name=None,\n specified_version=None,\n non_graphical=False,\n new_desktop_session=False,\n close_on_exit=False,\n student_version=False,\n ):\n self.is3d = False\n FieldAnalysis2D.__init__(\n self,\n \"Maxwell 2D\",\n projectname,\n designname,\n solution_type,\n setup_name,\n specified_version,\n non_graphical,\n new_desktop_session,\n close_on_exit,\n student_version,\n )\n Maxwell.__init__(self)\n\n @aedt_exception_handler\n def get_model_depth(self):\n \"\"\"Get model depth.\"\"\"\n if \"ModelDepth\" in self.design_properties:\n value_str = self.design_properties[\"ModelDepth\"]\n try:\n a = float_units(value_str)\n except:\n a = self.variable_manager[value_str].value\n return a\n else:\n return None\n\n @aedt_exception_handler\n def generate_design_data(self, linefilter=None, objectfilter=None):\n \"\"\"Generate a generic set of design data and store it in the extension directory as ``design_data.json``.\n\n Parameters\n ----------\n linefilter : optional\n The default is ``None``.\n objectfilter : optional\n The default is ``None``.\n\n Returns\n -------\n bool\n ``True`` when successful, ``False`` when failed.\n\n \"\"\"\n\n def convert(obj):\n if isinstance(obj, bool):\n return str(obj).lower()\n if isinstance(obj, (list, tuple)):\n return [convert(item) for item in obj]\n if isinstance(obj, dict):\n return {convert(key): convert(value) for key, value in obj.items()}\n return obj\n\n solid_bodies = self.modeler.solid_bodies\n if objectfilter:\n solid_ids = [i for i, j in self.modeler.primitives.object_id_dict.items() if j.name in objectfilter]\n else:\n solid_ids = [i for i in list(self.modeler.primitives.object_id_dict.keys())]\n model_depth = self.get_model_depth()\n self.design_data = {\n \"Project Directory\": self.project_path,\n \"Working Directory\": self.working_directory,\n \"Library Directories\": self.library_list,\n \"Dimension\": self.modeler.dimension,\n \"GeoMode\": self.geometry_mode,\n \"ModelUnits\": self.modeler.model_units,\n \"Symmetry\": self.symmetry_multiplier,\n \"ModelDepth\": model_depth,\n \"ObjectList\": solid_ids,\n \"LineList\": self.modeler.vertex_data_of_lines(linefilter),\n \"VarList\": self.variable_manager.variable_names,\n \"Setups\": self.existing_analysis_setups,\n \"MaterialProperties\": self.get_object_material_properties(solid_bodies),\n }\n\n design_file = os.path.join(self.working_directory, \"design_data.json\")\n with open(design_file, \"w\") as fps:\n json.dump(convert(self.design_data), fps, indent=4)\n return True\n\n @aedt_exception_handler\n def read_design_data(self):\n \"\"\"Read back the design data as a dictionary.\n\n Returns\n -------\n dict\n Dictionary of design data.\n\n \"\"\"\n design_file = os.path.join(self.working_directory, \"design_data.json\")\n with open(design_file, \"r\") as fps:\n design_data = json.load(fps)\n return design_data\n\n @aedt_exception_handler\n def assign_balloon(self, edge_list, bound_name=None):\n \"\"\"Assign a balloon boundary to a list of edges.\n\n Parameters\n ----------\n edge_list : list\n List of edges.\n bound_name : str, optional\n Name of the boundary. The default is ``None``.\n\n Returns\n -------\n :class:`pyaedt.modules.Boundary.BoundaryObject`\n Boundary object.\n\n \"\"\"\n edge_list = self.modeler._convert_list_to_ids(edge_list)\n\n if not bound_name:\n bound_name = generate_unique_name(\"Balloon\")\n\n props2 = OrderedDict({\"Edges\": edge_list})\n bound = BoundaryObject(self, bound_name, props2, \"Balloon\")\n\n if bound.create():\n self.boundaries.append(bound)\n return bound\n return False\n\n @aedt_exception_handler\n def assign_vector_potential(self, input_edge, vectorvalue=0, bound_name=None):\n \"\"\"Assign a vector to a list of edges.\n\n Parameters\n ----------\n input_edge : list\n List of edge names or edge IDs to assign a vector to.\n vectorvalue : float, optional\n Value of the vector. The default is ``0``.\n bound_name : str, optional\n Name of the boundary. The default is ``None``.\n\n Returns\n -------\n :class:`pyaedt.modules.Boundary.BoundaryObject`\n Vector Potential Object\n\n \"\"\"\n input_edge = self.modeler._convert_list_to_ids(input_edge)\n\n if not bound_name:\n bound_name = generate_unique_name(\"Vector\")\n if type(input_edge[0]) is str:\n props2 = OrderedDict({\"Objects\": input_edge, \"Value\": str(vectorvalue), \"CoordinateSystem\": \"\"})\n else:\n props2 = OrderedDict({\"Edges\": input_edge, \"Value\": str(vectorvalue), \"CoordinateSystem\": \"\"})\n bound = BoundaryObject(self, bound_name, props2, \"VectorPotential\")\n\n if bound.create():\n self.boundaries.append(bound)\n return bound\n return False\n\n @aedt_exception_handler\n def assign_master_slave(self, master_edge, slave_edge, reverse_master=False, reverse_slave=False,\n same_as_master=True, bound_name=None):\n \"\"\"Assign master and slave boundary conditions to two edges of the same object.\n\n Parameters\n ----------\n master_edge : int\n ID of the master edge.\n slave_edge : int\n ID of the slave edge.\n reverse_master : bool, optional\n Whether to reverse the master edge to the V direction. The default is ``False``.\n reverse_slave : bool, optional\n Whether to reverse the master edge to the U direction. The default is ``False``.\n same_as_master : bool, optional\n Whether the B-Field of the slave edge and master edge are the same. The default is ``True``.\n bound_name : str, optional\n Name of the master boundary. The name of the slave boundary will have a ``_dep`` suffix.\n\n Returns\n -------\n :class:`pyaedt.modules.Boundary.BoundaryObject`, :class:`pyaedt.modules.Boundary.BoundaryObject`\n Master and slave objects.\n\n \"\"\"\n master_edge = self.modeler._convert_list_to_ids(master_edge)\n slave_edge = self.modeler._convert_list_to_ids(slave_edge)\n if not bound_name:\n bound_name_m = generate_unique_name(\"Independent\")\n bound_name_s = generate_unique_name(\"Dependent\")\n else:\n bound_name_m = bound_name\n bound_name_s = bound_name + \"_dep\"\n props2 = OrderedDict({\"Edges\": master_edge, \"ReverseV\": reverse_master})\n bound = BoundaryObject(self, bound_name_m, props2, \"Independent\")\n if bound.create():\n self.boundaries.append(bound)\n\n props2 = OrderedDict({\"Edges\": slave_edge, \"ReverseU\": reverse_slave, \"Independent\": bound_name_m,\n \"SameAsMaster\": same_as_master})\n bound2 = BoundaryObject(self, bound_name_s, props2, \"Independent\")\n if bound2.create():\n self.boundaries.append(bound2)\n return bound, bound2\n else:\n return bound, False\n return False, False\n","sub_path":"pyaedt/maxwell.py","file_name":"maxwell.py","file_ext":"py","file_size_in_byte":35471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"445856316","text":"import csv\r\nimport sys\r\n\r\noutput = []\r\nresult = []\r\nusers = []\r\ncounter = 0\r\nfor i in range(31):\r\n output.append([])\r\n\r\nwith open(sys.argv[1], 'r') as file:\r\n reader = csv.reader(file)\r\n for row in reader:\r\n if row:\r\n row = row[0].split()\r\n if row[0] == 'ID':\r\n day = row[2].split('/')\r\n day = day[0]\r\n else:\r\n output[int(day)-1].append(row)\r\n\r\n for i in range(31):\r\n counter = 0\r\n if output[i]:\r\n for j in range(len(output[i])):\r\n if output[i][j][1] == '0':\r\n users.clear()\r\n users.append(output[i][j][0])\r\n counter +=1\r\n else:\r\n if output[i][j][0] not in users:\r\n counter+=1\r\n users.append(output[i][j][0]) \r\n result.append(str(counter))\r\n users.clear()\r\n #print(result)\r\nfile = sys.argv[1].split('.')\r\nfile = file[0]\r\nfile = file + '_result.csv'\r\nwith open(file, mode='w') as csv_file:\r\n writer = csv.writer(csv_file)\r\n writer.writerow([sys.argv[1]])\r\n for i in range(31):\r\n if result[i] != '0':\r\n writer.writerow([str(i) + ':' + result[i]])\r\n ","sub_path":"neecbot.py","file_name":"neecbot.py","file_ext":"py","file_size_in_byte":1272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"407187929","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.5 (62131)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.3-i386/egg/birdsuite/cn_annotate_allele_summary.py\n# Compiled at: 2008-12-08 17:00:29\n\"\"\"%prog [options]\n\nCreate a map between Affy probe set name and genomic position. This can be done for\nCNP probes, SNP probesets, or both. \n\"\"\"\nfrom __future__ import division\nimport optparse, os, string, subprocess, sys\nfrom mpgutils import utils\nlstRequiredOptions = [\n 'probe_locus', 'summary']\n\ndef mapSNPs(dctOut, strSnpProbeInfoPath):\n fIn = open(strSnpProbeInfoPath)\n for strLine in fIn:\n lstFields = strLine.split()\n dctOut[lstFields[0]] = (utils.convertChromosomeStr(lstFields[1]), lstFields[2])\n\n fIn.close()\n\n\nlstLocusHeaders = [\n 'chr', 'position', 'probeset_type']\niStartLocusColumnIndex = 1\niEndLocusColumnIndex = iStartLocusColumnIndex + len(lstLocusHeaders)\n\nclass ProbeExtractor(object):\n\n def __init__(self, strProbeLocusPath, fUnmappedProbesOut, strTempDir=None, bOmitLocusColumns=False):\n self.bOmitLocusColumns = bOmitLocusColumns\n self.fUnmappedProbesOut = fUnmappedProbesOut\n self.dctProbeToGenomicPosition = {}\n self.dctProbeToGenomicPosition = utils.loadProbeLocus(strProbeLocusPath)\n if strTempDir is not None:\n self.lstTempDirArgs = [\n '-T', strTempDir]\n else:\n self.lstTempDirArgs = []\n self.procSort = subprocess.Popen(['sort', '--key=2,2n', '--key=3,3n', '--key=1,1'] + self.lstTempDirArgs, stdin=subprocess.PIPE, stdout=subprocess.PIPE)\n return\n\n def processSummary(self, strSummaryPath, fOut):\n fIn = open(strSummaryPath)\n for strLine in fIn:\n if strLine.startswith('#'):\n fOut.write(strLine)\n elif strLine.startswith('probeset_id'):\n lstHeaders = strLine.split()\n lstOutputHeaders = ['probeset_id']\n if not self.bOmitLocusColumns:\n lstOutputHeaders += lstLocusHeaders\n print >> fOut, ('\\t').join(lstOutputHeaders + lstHeaders[1:])\n else:\n break\n\n fOut.flush()\n self._processSummaryLine(strLine)\n for strLine in fIn:\n self._processSummaryLine(strLine)\n\n fIn.close()\n\n def writeOutput(self, fOut):\n print >> sys.stderr, 'Finishing sorted output.'\n self._sloshOutput(fOut, self.procSort)\n\n def _processSummaryLine(self, strLine):\n lstFields = strLine.split('\\t', 1)\n strProbeSetName = lstFields[0]\n if strProbeSetName.endswith('-A') or strProbeSetName.endswith('-B'):\n strProbeSetType = strProbeSetName[(-1)]\n strProbeSetName = strProbeSetName[:-2]\n else:\n strProbeSetType = 'C'\n try:\n tupGenomicPosition = self.dctProbeToGenomicPosition[strProbeSetName]\n lstGenomicPosition = [ str(val) for val in tupGenomicPosition ]\n strOut = ('\\t').join(lstFields[0:1] + lstGenomicPosition + [strProbeSetType] + lstFields[1:])\n self.procSort.stdin.write(strOut)\n except KeyError:\n if self.fUnmappedProbesOut is not None:\n self.fUnmappedProbesOut.write(strLine)\n\n return\n\n def _sloshOutput(self, fOut, proc):\n proc.stdin.flush()\n proc.stdin.close()\n if self.bOmitLocusColumns:\n for strLine in proc.stdout:\n lstFields = strLine.split()\n del lstFields[iStartLocusColumnIndex:iEndLocusColumnIndex]\n print >> fOut, ('\\t').join(lstFields)\n\n for strLine in proc.stdout:\n fOut.write(strLine)\n\n if proc.wait() != 0:\n raise Exception('ERROR: %d exit status from sort.' % proc.returncode)\n\n\ndef main(argv=None):\n if argv is None:\n argv = sys.argv\n parser = optparse.OptionParser(usage=__doc__)\n parser.add_option('--probe_locus', help='(Required) SNP and CN probe positions.')\n parser.add_option('--summary', help='(Required) Input file containing probeset summaries as produced by apt-probeset-summarize.')\n parser.add_option('-o', '--output', dest='output', help='Where to write output. Default: stdout')\n parser.add_option('-u', '--unmapped-probes-output', dest='unmappedProbesOut', help=\"Where to write summaries of probes for which genomic position is not known.\\n Default: Don't write.\")\n parser.add_option('-t', '--tmpdir', dest='tempdir', help=\"If /tmp doesn't have enough room to sort, specify a temp directory with more room.\")\n parser.add_option('--omit-locus-columns', dest='omitLocusColumns', action='store_true', default=False, help='Do not emit the columns with locus or probe type. If this argument is used,\\n all this program does is sort the input by genomic position.')\n (dctOptions, lstArgs) = parser.parse_args(argv)\n if not utils.validateRequiredOptions(dctOptions, lstRequiredOptions):\n parser.print_help()\n return 1\n if dctOptions.output:\n fOut = open(dctOptions.output, 'w')\n else:\n fOut = sys.stdout\n if dctOptions.unmappedProbesOut:\n fUnmappedProbesOut = open(dctOptions.unmappedProbesOut, 'w')\n else:\n fUnmappedProbesOut = None\n print >> sys.stderr, 'Reading probe info files...'\n probeExtractor = ProbeExtractor(dctOptions.probe_locus, fUnmappedProbesOut, strTempDir=dctOptions.tempdir, bOmitLocusColumns=dctOptions.omitLocusColumns)\n print >> sys.stderr, 'Read summary file...'\n probeExtractor.processSummary(dctOptions.summary, fOut)\n print >> sys.stderr, 'Finishing sort and writing output...'\n probeExtractor.writeOutput(fOut)\n if dctOptions.output:\n fOut.close()\n if fUnmappedProbesOut is not None:\n fUnmappedProbesOut.close()\n return\n\n\nif __name__ == '__main__':\n sys.exit(main())","sub_path":"pycfiles/birdsuite_internal_tools-1.2-py2.5/cn_annotate_allele_summary.py","file_name":"cn_annotate_allele_summary.py","file_ext":"py","file_size_in_byte":5974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"337632102","text":"'''\n Filename: 09_DeDvKalman.py\n Created on: April,3, 2021\n Author: dhpark\n'''\nimport numpy as np\nfrom numpy.linalg import inv\nimport matplotlib.pyplot as plt\n\nnp.random.seed(0)\n\nfirstRun = True\nX, P = np.array([[0,0]]).transpose(), np.zeros((2,2)) # X : Previous State Variable Estimation, P : Error Covariance Estimation\nA, H = np.array([[0,0], [0,0]]), np.array([[0,0]])\nQ, R = np.array([[0,0], [0,0]]), 0\n\nfirstRun2 = True\nX2, P2 = np.array([[0,0]]).transpose(), np.zeros((2,2)) # X : Previous State Variable Estimation, P : Error Covariance Estimation\nA2, H2 = np.array([[0,0], [0,0]]), np.array([[0,0]])\nQ2, R2 = np.array([[0,0], [0,0]]), 0\n\nPosp, Velp = None, None\n\ndef GetPos():\n global Posp, Velp\n if Posp == None:\n Posp = 0\n Velp = 80\n dt = 0.1\n\n w = 0 + 10 * np.random.normal()\n v = 0 + 10 * np.random.normal()\n\n z = Posp + Velp * dt + v # Position measurement\n\n Posp = z - v\n Velp = 80 + w\n return z, Posp, Velp\n\n'''\n Estimate velocity through displacement\n'''\ndef DvKalman(z):\n global firstRun\n global A, Q, H, R\n global X, P\n if firstRun:\n dt = 0.1\n A = np.array([[1, dt], [0, 1]])\n H = np.array([[1, 0]])\n Q = np.array([[1, 0], [0, 3]])\n R = np.array([10])\n\n X = np.array([0, 20]).transpose()\n P = 5 * np.eye(2)\n firstRun = False\n else:\n Xp = A @ X # Xp : State Variable Prediction\n Pp = A @ P @ A.T + Q # Error Covariance Prediction\n\n K = (Pp @ H.T) @ inv(H@Pp@H.T + R) # K : Kalman Gain\n\n X = Xp + K@(z - H@Xp) # Update State Variable Estimation\n P = Pp - K@H@Pp # Update Error Covariance Estimation\n\n pos = X[0]\n vel = X[1]\n\n return pos, vel\n\ndef DeDvKalman(z):\n global firstRun2\n global A2, Q2, H2, R2\n global X2, P2\n if firstRun2:\n dt = 0.1\n A2 = np.array([[1, dt], [0, 1]])\n H2 = np.array([[1, 0]])\n Q2 = np.array([[1, 0], [0, 3]])\n R2 = np.array([10])\n\n X2 = np.array([0, 20]).transpose()\n P2 = 5 * np.eye(2)\n firstRun2 = False\n else:\n Xp = A2 @ X2 # Xp : State Variable Prediction\n Pp = A2 @ P2 @ A2.T + Q2 # Error Covariance Prediction\n\n #K = (Pp @ H.T) @ inv(H@Pp@H.T + R) # K : Kalman Gain\n K = 1/(np.array(Pp[0,0]) + R2) * np.array([Pp[0,0], Pp[1,0]]).transpose()\n K = K[:, np.newaxis] # maintain axis\n\n X2 = Xp + K@(z - H@Xp) # Update State Variable Estimation\n P2 = Pp - K@H2@Pp # Update Error Covariance Estimation\n\n pos = X2[0]\n vel = X2[1]\n\n return pos, vel\n\nt = np.arange(0, 10, 0.1)\nNsamples = len(t)\n\nXsaved = np.zeros([Nsamples, 2])\nDeXsaved = np.zeros([Nsamples, 2])\n\nfor i in range(Nsamples):\n Z, pos_true, vel_true = GetPos()\n pos, vel = DvKalman(Z)\n dpos, dvel = DeDvKalman(Z)\n\n Xsaved[i] = [pos, vel]\n DeXsaved[i] = [dpos, dvel]\n\nplt.figure()\nplt.plot(t, Xsaved[:,1], 'b*', label = 'Matrix')\nplt.plot(t, DeXsaved[:,1], 'r-', label='Decomposed')\nplt.legend(loc='upper left')\nplt.ylabel('Velocity [m/s]')\nplt.xlabel('Time [sec]')\nplt.savefig('result/09_DeDvKalman.png')\nplt.show()","sub_path":"09_DeDvKalman.py","file_name":"09_DeDvKalman.py","file_ext":"py","file_size_in_byte":3123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"393586232","text":"def min(a, b):\n num = 0;\n while a > 0 and b > 0:\n num += 1;\n a -= 1;\n b -= 1;\n return num;\n\n\ndef minMethodOne(a, b):\n min = (a > b) * b + (a < b) * a;\n return min;\n\n\nprint(min(10, 2));\nprint(minMethodOne(1, 12));\nprint(min(12, 12));\nprint(min(10, 12));\n","sub_path":"P20/p20_6.py","file_name":"p20_6.py","file_ext":"py","file_size_in_byte":289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"127113842","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Nov 4 19:02:03 2017\n\n@author: hasnat\n\"\"\"\nfrom __future__ import print_function\n\n'''Trains a simple convnet on the MNIST dataset.\nGets to 99.25% test accuracy after 12 epochs\n(there is still a lot of margin for parameter tuning).\n16 seconds per epoch on a GRID K520 GPU.\n'''\n\nimport keras\nfrom keras.datasets import mnist\nfrom keras.models import Model, Input\nfrom keras.layers import Dense, Dropout, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras import backend as K\nfrom keras.layers.normalization import BatchNormalization\n\nimport numpy as np\n\nbatch_size = 128\nnum_classes = 10\nepochs = 1\n\n# input image dimensions\nimg_rows, img_cols = 28, 28\n\n# the data, shuffled and split between train and test sets\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\nx_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)\nx_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)\ninput_shape = (img_rows, img_cols, 1)\n\nx_train = x_train.astype('float32')\nx_test = x_test.astype('float32')\nx_train /= 255\nx_test /= 255\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\n\n# convert class vectors to binary class matrices\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nimg_input = Input(shape=input_shape)\n\nc1 = Conv2D(32, kernel_size=(3, 3),activation='relu',input_shape=input_shape)(img_input)\nc2 = Conv2D(64, (3, 3), activation='relu')(c1)\np1 = MaxPooling2D(pool_size=(2, 2))(c2)\n\ndo1 = Dropout(0.25)(p1)\nflat = Flatten()(do1)\nact1 = Dense(128, activation='relu')(flat)\nbn1 = BatchNormalization()(act1)\ndo2 = Dropout(0.5)(bn1)\nfc_cl = Dense(num_classes, activation='softmax')(do2)\n\nmodel = Model(inputs=img_input, outputs = fc_cl)\n\nmodel.compile(loss=keras.losses.categorical_crossentropy,\n optimizer=keras.optimizers.Adadelta(),\n metrics=['accuracy'])\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=epochs,\n verbose=1,\n validation_data=(x_test, y_test))\n\nscore = model.evaluate(x_test, y_test, verbose=0)\nprint('Test loss:', score[0])\nprint('Test accuracy:', score[1])\n","sub_path":"cnn/keras_mnist.py","file_name":"keras_mnist.py","file_ext":"py","file_size_in_byte":2282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"316631582","text":"import numpy as np\nimport cv2\n\ncap = cv2.VideoCapture(\"vtest.avi\")\nfgbg = cv2.bgsegm.createBackgroundSubtractorMOG() #Background and foreground segmentation method\nfgbg2 = cv2.createBackgroundSubtractorMOG2() #detectShadows attribute True by default\nkernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3,3))\nfgbg3 = cv2.bgsegm.createBackgroundSubtractorGMG()\nfgbg4 = cv2.createBackgroundSubtractorKNN() #detectShadows attribute True by default\n\nwhile True:\n ret, frame = cap.read()\n \n if frame is None:\n break\n\n fgmask = fgbg.apply(frame) #Create mask image from segmented and processed image\n fgmask2 = fgbg2.apply(frame)\n fgmask3 = fgbg3.apply(frame)\n fgmask3 = cv2.morphologyEx(fgmask, cv2. MORPH_OPEN, kernel)\n fgmask4 = fgbg4.apply(frame)\n\n cv2.imshow(\"Frame\", frame)\n cv2.imshow(\"FG MAsk Frame\", fgmask) #Output masked image\n cv2.imshow(\"FG MAsk Frame 2\", fgmask2)\n cv2.imshow(\"FG MAsk Frame 3\", fgmask3)\n cv2.imshow(\"FG MAsk Frame 4\", fgmask4)\n\n keyboard = cv2.waitKey(30)\n\n if keyboard == 'q' or keyboard == 27:\n break\n\ncap.release()\ncv2.destroyAllWindows()","sub_path":"OpenCV/11_opencv_background_subtraction.py","file_name":"11_opencv_background_subtraction.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"37363333","text":"# -*- coding: utf8 -*-\n\n# Copyright (c) 2014, Nicolas Le Manchet. 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\n\nfrom __future__ import unicode_literals\nfrom time import time\nfrom collections import OrderedDict\n\nfrom flask import current_app\n\nfrom ..logic import MetricRecord, get_records\n\nclass Graph(object):\n \"\"\"Base class to represent a graph.\"\"\"\n\n # By default do not fill the area under a line\n fill = False\n\n # No default unit\n y_unit = None\n\n # Time between record must be x times the period delay\n # to be considered offline\n off_coef = 3\n \n # Maximum number of records to display in a graph\n max_records = 200 \n\n def __init__(self, hostname, context=None, from_date=None,\n downsample=True):\n self.hostname = hostname\n self.context = context\n self.from_date = from_date\n self.max_records = current_app.config['MAX_POINTS']\n if self.context:\n self.title = '%s %s' % (self.title, self.context)\n self.load_records()\n self.offline()\n if downsample:\n self.downsample()\n if self.y_unit == 'bps':\n self.derivate()\n self.static_as_const()\n\n\n def load_records(self):\n \"\"\"Loads metrics and associated records for a graph.\n \n Takes care of discarding not meaningful metric_records.\n Raises a ValueError if no dynamic record is found.\n \"\"\"\n self.metric_records = []\n for metric_name in self.metrics_names:\n rec = get_records(self.hostname,\n metric_name,\n context=self.context,\n from_date=self.from_date,\n output='mr')\n # Drop empty dynamic metrics\n if not rec.metric.is_static and len(rec.records) == 0:\n continue\n # If static metric has no record try to get the last one\n if rec.metric.is_static and len(rec.records) == 0:\n rec = get_records(self.hostname,\n metric_name,\n context=self.context,\n latest=True,\n output='mr')\n # Nothing to show, drop the static record\n if len(rec.records) == 0:\n continue\n \n # Metric has record(s), add it to the list\n self.metric_records.append(rec)\n\n # No dynamic record at all? Drop the graph\n graph_has_dynamic_record = False\n for mr in self.metric_records:\n if not mr.metric.is_static:\n graph_has_dynamic_record = True\n if not graph_has_dynamic_record:\n raise ValueError('No dynamic record for %s'\n % self.__class__.__name__)\n\n def static_as_const(self):\n \"\"\"Make single static values appears as const in graph.\n \n First it makes sure the first static value doesn't appear\n before the first dynamic one. It checks the last time a dynamic\n value was added and creates a new record in the static ones\n to prolongate the line until the end of the chart. It also\n deals with static values that changes (ex: adding RAM)\n \"\"\"\n mr_static_list = []\n first_time = None\n last_time = 0\n\n # Make a list of static metric_records and compute\n # the first and last value static records should have\n for mr in self.metric_records:\n if mr.metric.is_static:\n mr_static_list.append(mr)\n else:\n if not first_time or first_time < mr.records[0][0]:\n first_time = mr.records[0][0]\n try:\n if mr.records[-1][0] > last_time:\n last_time = mr.records[-1][0] \n except (TypeError, IndexError):\n pass\n\n # Loop on all static metric_records to apply changes\n # earlier\n if mr_static_list and first_time and last_time > 0:\n for mr_static in mr_static_list:\n \n # First fix the problem of static values that are older\n # than the fist dynamic value.\n mr_static.records[0][0] = first_time\n\n # Next fix the problem of static values that changes\n # for example adding RAM, it would make the total\n # memory to slowly grow from one end of the graph to\n # another. To prevent that we add one fake value each time\n # a static value changes. We create this fake value\n # just one milisecond before the actual change.\n # List is copied to not prevent infinite loop.\n copy_records = list(mr_static.records)\n offset = 0\n for i, record in enumerate(copy_records):\n try:\n if not i == 0:\n mr_static.records.\\\n insert(i+offset, [copy_records[i][0]-1,\n copy_records[i-1][1]])\n offset += 1\n except IndexError:\n pass\n\n # Now add another fake value to the right end of\n # the graph, it contains the last static value.\n last_static_value = mr_static.records[-1][1]\n mr_static.records.append([last_time, last_static_value])\n\n\n def offline(self):\n \"\"\"Breaks the line when no value is found for a long time.\n\n When a server is offline or just not sending records,\n charts can look strange. This breaks the line when no dynamic\n data is found for a long time.\n A server is considered offline if two points are separeted in\n time for more than the period delay multiplied by the off_coef.\n When a server is offline a None record is insered between the\n two records that are too far from each others. This is\n interpreted by Flot and breaks the line.\n \"\"\"\n current_time = int(time())\n for mr in self.metric_records: \n\n # We don't want to check static records and too small records\n if mr.metric.is_static and len(mr.records) < 4:\n continue\n\n # Initialize the periods, we need to have access to the\n # current and next one\n periods = OrderedDict(current_app.config['PERIODS'])\n current_period = periods.popitem(last=True)[1]\n next_period = periods.popitem(last=True)[1]\n\n for i, record in enumerate(mr.records):\n \n # Set the period matching the current record as the\n # current period\n while next_period and record and \\\n record[0] > 1000 * (current_time - next_period['time']):\n try:\n tmp = current_period\n current_period = next_period\n next_period = periods.popitem(last=True)[1]\n except KeyError:\n current_period = tmp\n next_period = None\n\n # If the difference of time between the current record\n # and the next one is bigger than off_coef * delay\n # insert a fake None record\n try:\n delta = mr.records[i+1][0] - record[0]\n if i > 0 and \\\n delta > 1000 * current_period['delay'] * self.off_coef:\n mr.records.insert(i+1, None)\n except (TypeError, IndexError) as e:\n pass\n\n\n def derivate(self):\n \"\"\"Makes a traffic graph from the evolution of data.\"\"\"\n\n for mr in self.metric_records:\n copy_records = list(mr.records)\n for i, record in enumerate(mr.records):\n try:\n if not mr.records[i+1]:\n copy_records[i] = None\n continue\n if not record:\n continue\n amount = mr.records[i+1][1] - mr.records[i][1]\n delta = (mr.records[i+1][0] - mr.records[i][0])/1000\n copy_records[i][1] = int(amount/delta)\n except IndexError:\n if i == mr.records.__len__() - 1:\n copy_records.pop()\n mr.records = copy_records\n\n def find_maximum_metric(self, mr):\n \"\"\"Get the highest value of records for a metric.\"\"\"\n max = 0\n for record in mr.records:\n if not record:\n continue\n if record[1] > max:\n max = record[1]\n return max\n \n def find_maximum_graph(self):\n \"\"\"Get the highest value of a graph in an efficient way.\"\"\"\n\n max = 0\n for mr in self.metric_records:\n max_metric = self.find_maximum_metric(mr)\n if mr.metric.is_static:\n #return max_metric\n continue\n if max_metric > max:\n max = max_metric\n return max\n \n def downsample(self):\n \"\"\"Removes records from a graph to keep up to max_records records.\n\n Takes care of keeping None records as well as the previous and next\n records. Makes sure to keep first and last records.\n \"\"\"\n for mr in self.metric_records:\n\n # If the graph has less than max_records, keep everything\n if len(mr.records) < self.max_records:\n continue\n\n proportion = self.max_records / float(len(mr.records))\n counter = 0.0\n last_counter = None\n results = []\n\n for i, record in enumerate(mr.records):\n\n # If we have a None record keep it with previous\n # and next one\n try:\n if not mr.records[i+1]:\n results.append(record)\n continue\n except IndexError:\n results.append(record)\n continue\n if not record:\n results.append(record)\n continue\n try:\n if not mr.records[i-1]:\n results.append(record)\n continue\n except IndexError:\n results.append(record)\n continue\n counter += proportion\n if int(counter) != last_counter:\n results.append(record)\n last_counter = int(counter)\n\n mr.records = results\n\n\nclass LoadGraph(Graph):\n \"\"\"Graph representing the load average over the time.\"\"\"\n\n title = 'Load average'\n metrics_names = ['load.1',\n 'load.5',\n 'load.15']\n colors = ['rgb(200, 230, 255)',\n 'rgb(127, 193, 250)',\n 'rgb(45, 144, 250)']\n\nclass MemoryGraph(Graph):\n \"\"\"Graph representing the memory over the time.\"\"\"\n\n title = 'Memory'\n metrics_names = ['memory.total',\n 'memory.used']\n colors = ['rgb(34, 161, 44)',\n 'rgb(45, 144, 250)']\n fill = True\n y_unit = 'bytes'\n\nclass SwapGraph(Graph):\n \"\"\"Graph representing the swap over the time.\"\"\"\n\n title = 'Swap'\n metrics_names = ['swap.total',\n 'swap.used']\n colors = ['rgb(34, 161, 44)',\n 'rgb(232, 188, 86)']\n fill = True\n y_unit = 'bytes'\n\nclass DiskGraph(Graph):\n \"\"\"Graph representing a disk space over the time.\"\"\"\n\n title = 'Disk'\n metrics_names = ['disks.total',\n 'disks.used']\n colors = ['rgb(34, 161, 44)',\n 'rgb(45, 144, 250)']\n fill = True\n y_unit = 'bytes'\n\nclass InterfaceGraph(Graph):\n \"\"\"Graph representing traffic over the time.\"\"\"\n\n title = 'Interface'\n metrics_names = ['if.recv',\n 'if.sent']\n colors = ['rgb(45, 144, 250)',\n 'rgb(232, 188, 86)']\n fill = True\n y_unit = 'bps'\n","sub_path":"webapp/website/graphs.py","file_name":"graphs.py","file_ext":"py","file_size_in_byte":12450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"237250735","text":"\"\"\"\ntest1 berechnet und visualisiert eine reduzierte Loesung bzgl fester Basisgroesse\n\ntest2 berechnet und visualisiert eine reduzierte Loesung mit dem adaptiven Algorithmus (Alg. 3)\n\nevaluation berechnet den relativen Fehler abhaengig von der Basisgroesse\n\nungleichung berechnet den relativen Fehler abhaengig von der gegebenen Toleranz bezueglich\ndes adaptiven Algorithmus und die a priori Grenze\n\nungleichungk berechnet den relativen Fehler abhaengig von der Wellenzahl k bezueglich des\nadaptiven Algorithmus und die a priori Grenze\n\nplotconstants berechnet die inf-sup Konstante und die Stetigkeitskonstante\nin Abhaengigkeit von der Wellenzahl k\n\nkerr berechnet den relativen Fehler abhaengig von der Wellenzahl k mit dem\nnicht-adaptiven Algorithmus (Alg. 4)\n\nresolution berechnet den relativen Fehler in Abhaengigkeit von der feinen\nGitteraufloesung mit Alg. 4\n\ncerr2D berechnet den relativen Fehler abhaengig von c(dem lokalen Robin-Parameter) mit Alg. 4\n\nknerr2D berechnet den relativen Fehler abhaengig von der Wellenzahl k und der\nBasisgroesse n mit Alg. 4\n\n\nit=Anzahl der Wiederholungen fuer die Statistik\nlim=maximale Basisgroesse\nk=Wellenzahl\nboundary=globale Randbedingung\nsave=Speicherort fuer Daten\ncglob=globaler Robin-Parameter\ncloc=lokaler Robin-Parameter (fuer Transferoperator)\nresolution=feine Gitteraufloesung\ncoarse_grid_resolution=grobe Gitteraufloesung\n\"\"\"\n\nfrom pymor.core.logger import set_log_levels\nfrom lmor.problems import helmholtz\nfrom lmor.localize_problem import localize_problem\nfrom lmor.generate_solution import create_bases, create_bases2, create_bases3, reconstruct_solution, operator_svd2\nfrom lmor.constants import (calculate_continuity_constant, calculate_inf_sup_constant2,\n calculate_csis, calculate_Psi_norm)\nimport multiprocessing as mp\nimport time\nimport os\nimport numpy as np\nimport sys\n\nif not os.path.exists(\"dats\"):\n os.makedirs(\"dats\")\nset_log_levels(levels={'pymor': 'WARN'})\n\nprocess_count = 10\n\n\ndef evaluation(it, lim, k, boundary, save, cglob=0, cloc=0, plot=False, resolution=200, coarse_grid_resolution=10):\n p = helmholtz(boundary=boundary)\n mus = {'k': k, 'c_glob': cglob, 'c_loc': cloc}\n gq, lq = localize_problem(p, coarse_grid_resolution, resolution, mus=mus)\n d = gq[\"d\"]\n u = d.solve(mus)\n h1_dirichlet = []\n h1_robin = []\n nrang = np.arange(0, lim, 5)\n for n in nrang:\n print(\"n: \", n)\n h1d = []\n h1r = []\n for j in range(it):\n print(j, )\n sys.stdout.flush()\n basis_dirichlet = create_bases2(gq, lq, n)\n ru_dirichlet = reconstruct_solution(gq, lq, basis_dirichlet)\n del basis_dirichlet\n basis_robin = create_bases2(gq, lq, n, transfer='robin')\n ru_robin = reconstruct_solution(gq, lq, basis_robin)\n del basis_robin\n dif_dirichlet = u - ru_dirichlet\n dif_robin = u-ru_robin\n h1d.append(gq[\"full_norm\"](dif_dirichlet)[0]/gq[\"full_norm\"](u)[0])\n h1r.append(gq[\"full_norm\"](dif_robin)[0]/gq[\"full_norm\"](u)[0])\n h1_dirichlet.append(h1d)\n h1_robin.append(h1r)\n means_dirichlet_h1 = np.mean(h1_dirichlet, axis=1)\n means_robin_h1 = np.mean(h1_robin, axis=1)\n data = np.vstack([nrang, means_dirichlet_h1, means_robin_h1]).T\n open(save, \"w\").writelines([\" \".join(map(str, v)) + \"\\n\" for v in data])\n if plot:\n from matplotlib import pyplot as plt\n plt.figure()\n plt.semilogy(nrang, means_dirichlet_h1, label=\"Dirichlet h1\")\n plt.semilogy(nrang, means_robin_h1, label=\"Robin h1\")\n plt.legend(loc='upper right')\n plt.xlabel('Basis size')\n plt.show()\n\n\ndef evaluationq(it, lim, k, boundary, save, cloc=0, resolution=100, coarse_grid_resolution=10):\n p = helmholtz(boundary=boundary)\n cglob = -1j*k\n mus = {'k': k, 'c_glob': cglob, 'c_loc': cloc}\n gq, lq = localize_problem(p, coarse_grid_resolution, resolution, mus=mus, calT=True)\n d = gq[\"d\"]\n u = d.solve(mus)\n nrang = np.arange(0, lim, 5)\n global cube\n\n def cube(n):\n print(\"n: \", n)\n Q0 = []\n Q1 = []\n Q2 = []\n for j in range(it):\n print(j, )\n sys.stdout.flush()\n basis_robin = create_bases3(gq, lq, n, 0)\n ru_robin = reconstruct_solution(gq, lq, basis_robin)\n del basis_robin\n dif_robin = u-ru_robin\n Q0.append(gq[\"full_norm\"](dif_robin)[0]/gq[\"full_norm\"](u)[0])\n\n basis_robin = create_bases3(gq, lq, n, 1)\n ru_robin = reconstruct_solution(gq, lq, basis_robin)\n del basis_robin\n dif_robin = u-ru_robin\n Q1.append(gq[\"full_norm\"](dif_robin)[0]/gq[\"full_norm\"](u)[0])\n\n basis_robin = create_bases3(gq, lq, n, 2)\n ru_robin = reconstruct_solution(gq, lq, basis_robin)\n del basis_robin\n dif_robin = u-ru_robin\n Q2.append(gq[\"full_norm\"](dif_robin)[0]/gq[\"full_norm\"](u)[0])\n return [np.mean(Q0), np.mean(Q1), np.mean(Q2)]\n pool = mp.Pool()\n results = pool.map(cube, nrang)\n data = np.vstack([nrang, np.array(results).T]).T\n open(save, \"w\").writelines([\" \".join(map(str, v)) + \"\\n\" for v in data])\n\n\ndef ungleichung(it, acc, boundary, save, krang=np.arange(0.1, 10.1, 0.1),\n cloc0=0, cloc1=1, cloc2=1, returnvals=False, resolution=100, coarse_grid_resolution=10):\n p = helmholtz(boundary=boundary)\n global cube\n\n def cube(k):\n print(k)\n cglob = -1j*k\n cloc = cloc0 + cloc1 * k + cloc2 * k**2\n mus = {'k': k, 'c_glob': cglob, 'c_loc': cloc}\n resolution = int(np.ceil(float(k*1.5+50)/coarse_grid_resolution)*coarse_grid_resolution)\n gq, lq = localize_problem(p, coarse_grid_resolution, resolution, mus=mus, calT=True, calQ=True)\n calculate_continuity_constant(gq, lq)\n calculate_inf_sup_constant2(gq, lq)\n # calculate_lambda_min(gq, lq)\n calculate_csis(gq, lq)\n calculate_Psi_norm(gq, lq)\n d = gq[\"d\"]\n u = d.solve(mus)\n norm = gq[\"full_norm\"]\n localizer = gq[\"localizer\"]\n pou = gq[\"pou\"]\n dats = []\n for j in range(it):\n print(j, )\n sys.stdout.flush()\n bases = create_bases(gq, lq, num_testvecs=20, transfer='robin', target_accuracy=acc, calC=False)\n ru = reconstruct_solution(gq, lq, bases)\n ls = norm(u-ru)[0]/norm(u)[0]\n sum1 = u*0\n sum2 = 0\n sum3 = 0\n sum4 = 0\n sum51 = []\n sum52 = 0\n for space in gq[\"spaces\"]:\n ldict = lq[space]\n B = bases[space]\n range_product = ldict[\"range_product\"]\n source_product = ldict[\"source_product\"]\n T = ldict[\"robin_transfer\"].as_range_array()\n range_space = ldict[\"range_space\"]\n omega_star_space = ldict[\"omega_star_space\"]\n omega_star_product = ldict[\"omega_star_product\"]\n u_s = ldict[\"local_solution_robin\"]\n u_s2 = ldict[\"local_sol2\"]\n\n u_loc = pou[range_space](localizer.localize_vector_array(u, range_space))\n u_loc2 = localizer.localize_vector_array(u, omega_star_space)\n u_dif = u_loc-u_s\n u_dif2 = u_loc2-u_s2\n term = u_dif-B.lincomb(B.inner(u_dif, range_product).T)\n\n T1 = T - B.lincomb(B.inner(T, range_product).T)\n maxval = operator_svd2(T1.data.T, source_product.matrix, range_product.matrix)[0][0]\n\n sum1 += localizer.globalize_vector_array(term, range_space)\n sum2 += term.norm(range_product)[0]**2\n sum3 += maxval**2*ldict[\"Psi_norm\"]**2 * u_dif2.norm(omega_star_product)[0]**2\n sum4 += maxval**2*ldict[\"Psi_norm\"]**2 * u_loc2.norm(omega_star_product)[0]**2 * ldict[\"csi\"]**2\n sum51.append(maxval*ldict[\"Psi_norm\"] * ldict[\"csi\"])\n sum52 += u_loc2.norm(omega_star_product)[0]**2\n rs1 = gq[\"continuity_constant\"]/gq[\"inf_sup_constant\"] * norm(sum1)[0]/norm(u)[0]\n rs2 = gq[\"continuity_constant\"]/gq[\"inf_sup_constant\"] * 2 * np.sqrt(sum2)/norm(u)[0]\n rs3 = gq[\"continuity_constant\"]/gq[\"inf_sup_constant\"] * 2 * np.sqrt(sum3)/norm(u)[0]\n rs4 = gq[\"continuity_constant\"]/gq[\"inf_sup_constant\"] * 2 * np.sqrt(sum4)/norm(u)[0]\n rs5 = gq[\"continuity_constant\"]/gq[\"inf_sup_constant\"] * 2 * max(sum51) * np.sqrt(sum52)/norm(u)[0]\n rs6 = gq[\"continuity_constant\"]/gq[\"inf_sup_constant\"] * max(sum51) * 8\n ccs = gq[\"continuity_constant\"]/gq[\"inf_sup_constant\"]\n dats.append([ls, rs1, rs2, rs3, rs4, rs5, rs6, ccs])\n return dats\n pool = mp.Pool()\n results = pool.map(cube, krang)\n means = np.mean(results, axis=1)\n data = np.vstack([krang, means.T]).T\n open(save, \"w\").writelines([\" \".join(map(str, v)) + \"\\n\" for v in data])\n if returnvals:\n return means\n\n\ndef plotconstants(boundary, save, cloc0=0, cloc1=1, cloc2=1, resolution=50,\n coarse_grid_resolution=10, returnvals=False):\n p = helmholtz(boundary=boundary)\n kspace = np.arange(0.1, 10.1, 1.)\n B = []\n C = []\n for k in kspace:\n print(k)\n cloc = cloc0 + cloc1 * k + cloc2 * k**2\n mus = {'k': k, 'c_glob': -1j*k, 'c_loc': cloc}\n gq, lq = localize_problem(p, coarse_grid_resolution, resolution, mus)\n t = time.time()\n b = calculate_inf_sup_constant2(gq, lq)\n print(time.time()-t, b)\n t = time.time()\n c = calculate_continuity_constant(gq, lq)\n print(time.time()-t, c)\n B.append(b)\n C.append(c)\n data = np.vstack([kspace, B, C]).T\n open(save, \"w\").writelines([\" \".join(map(str, v)) + \"\\n\" for v in data])\n if returnvals:\n return [kspace, B, C]\n\n\ndef test1(transfer='robin', boundary='dirichlet', n=15, k=6., cloc=6., title='test',\n resolution=100, coarse_grid_resolution=10, m=1):\n cglob = -1j*k\n mus = {'k': k, 'c_glob': cglob, 'c_loc': cloc}\n p = helmholtz(boundary=boundary)\n gq, lq = localize_problem(p, coarse_grid_resolution, resolution, mus, m=m)\n basis = create_bases2(gq, lq, n, transfer=transfer, silent=False)\n ru = reconstruct_solution(gq, lq, basis, silent=False)\n d = gq[\"d\"]\n u = d.solve(mus)\n dif = u-ru\n print(gq[\"full_norm\"](dif)[0]/gq[\"full_norm\"](u)[0])\n d.visualize((dif.real, dif.imag, u.real, u.imag, ru.real, ru.imag),\n legend=('dif.real', 'dif.imag', 'u.real', 'u.imag', 'ru.real', 'ru.imag'),\n separate_colorbars=True, title=title)\n\n\ndef test2(transfer='robin', boundary='dirichlet', acc=1e-2, k=6., cloc=6.,\n title='test', resolution=100, coarse_grid_resolution=10):\n cglob = -1j*k\n mus = {'k': k, 'c_glob': cglob, 'c_loc': cloc}\n p = helmholtz(boundary=boundary)\n gq, lq = localize_problem(p, coarse_grid_resolution, resolution, mus, calQ=True)\n basis = create_bases(gq, lq, 20, transfer=transfer, target_accuracy=acc, silent=False)\n ru = reconstruct_solution(gq, lq, basis, silent=False)\n d = gq[\"d\"]\n u = d.solve(mus)\n dif = u-ru\n print(gq[\"full_norm\"](dif)[0]/gq[\"full_norm\"](u)[0])\n d.visualize((dif.real, dif.imag, u.real, u.imag, ru.real, ru.imag),\n legend=('dif.real', 'dif.imag', 'u.real', 'u.imag', 'ru.real', 'ru.imag'),\n separate_colorbars=True, title=title)\n\n\ndef kerr(it, boundary, save, cloc0=0, cloc1=1, cloc2=1, rang=np.arange(0.5, 100.5, 0.5),\n plot=False, coarse_grid_resolution=10):\n p = helmholtz(boundary=boundary)\n global cube\n\n def cube(k):\n cglob = -1j * k\n cloc = cloc0 + cloc1 * k + cloc2 * k**2\n print(\"k: \", k, \"cloc: \", cloc)\n mus = {'k': k, 'c_glob': cglob, 'c_loc': cloc}\n resolution = int(np.ceil(float(k*1.5+50)/coarse_grid_resolution)*coarse_grid_resolution)\n n = int(k/5+30)\n gq, lq = localize_problem(p, coarse_grid_resolution, resolution, mus=mus)\n d = gq[\"d\"]\n u = d.solve(mus)\n e_r = []\n e_d = []\n for i in range(it):\n print(i, )\n sys.stdout.flush()\n bases = create_bases2(gq, lq, n, transfer='robin')\n ru_r = reconstruct_solution(gq, lq, bases)\n del bases\n dif_r = u-ru_r\n e_r.append(gq[\"full_norm\"](dif_r)[0]/gq[\"full_norm\"](u)[0])\n bases = create_bases2(gq, lq, n, transfer='dirichlet')\n ru_d = reconstruct_solution(gq, lq, bases)\n del bases\n dif_d = u-ru_d\n e_d.append(gq[\"full_norm\"](dif_d)[0]/gq[\"full_norm\"](u)[0])\n return np.mean(e_d), np.mean(e_r)\n pool = mp.Pool()\n results = pool.map(cube, rang)\n means_d = np.array(results).T[0].tolist()\n means_r = np.array(results).T[1].tolist()\n\n data = np.vstack([rang, means_d, means_r]).T\n open(save, \"w\").writelines([\" \".join(map(str, v)) + \"\\n\" for v in data])\n if plot:\n from matplotlib import pyplot as plt\n plt.figure()\n plt.semilogy(rang, means_r, label=\"robin\")\n plt.semilogy(rang, means_d, label=\"dirichlet\")\n plt.xlabel('k')\n plt.legend(loc='upper right')\n plt.show()\n\n\ndef resolution(it, k, n, boundary, save, cloc=0, returnvals=False, coarse_grid_resolution=10):\n cglob = -1j*k\n mus = {'k': k, 'c_glob': cglob, 'c_loc': cloc}\n p = helmholtz(boundary=boundary)\n space = np.arange(20, 160, 10)\n err = []\n for resolution in space:\n print(resolution)\n gq, lq = localize_problem(p, coarse_grid_resolution, resolution, mus=mus)\n d = gq[\"d\"]\n u = d.solve(mus)\n E = []\n for i in range(it):\n bases = create_bases2(gq, lq, n, transfer='robin')\n ru = reconstruct_solution(gq, lq, bases)\n E.append(gq[\"full_norm\"](u-ru)[0]/gq[\"full_norm\"](u)[0])\n err.append(E)\n errs = np.mean(err, axis=1)\n data = np.vstack([space, errs]).T\n open(save, \"w\").writelines([\" \".join(map(str, v)) + \"\\n\" for v in data])\n if returnvals:\n return [space, errs]\n\n\ndef cerr2D(it, n, k, boundary, save, cglob=0, rang=np.arange(-10., 10., 1.),\n yrang=None, plot=False, resolution=200, coarse_grid_resolution=10):\n if yrang is None:\n yrang = rang\n err_r = np.zeros((len(rang), len(yrang)))\n p = helmholtz(boundary=boundary)\n pool = mp.Pool(processes=process_count)\n xi = 0\n for x in rang:\n yi = 0\n for y in yrang:\n c = x+1j*y\n print(c)\n mus = {'k': k, 'c_glob': cglob, 'c_loc': c}\n gq, lq = localize_problem(p, coarse_grid_resolution, resolution, mus=mus)\n d = gq[\"d\"]\n u = d.solve(mus)\n\n def cube():\n bases = create_bases2(gq, lq, n, transfer='robin')\n ru_r = reconstruct_solution(gq, lq, bases)\n del bases\n dif_r = u-ru_r\n return gq[\"full_norm\"](dif_r)[0]/gq[\"full_norm\"](u)[0]\n e_r = pool.map(cube, range(it))\n err_r[xi][yi] = np.mean(e_r)\n yi += 1\n xi += 1\n X, Y = np.meshgrid(rang, yrang)\n data = np.vstack([X.T.ravel(), Y.T.ravel(), err_r.ravel()]).T\n open(save, \"w\").writelines([\" \".join(map(str, v)) + \"\\n\" for v in data])\n if plot:\n import matplotlib.pyplot as plt\n from matplotlib import cm\n fig = plt.figure()\n ax = fig.gca(projection='3d')\n surf = ax.plot_surface(X, Y, err_r, cstride=1, rstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False)\n fig.colorbar(surf, shrink=0.5, aspect=5)\n plt.show()\n\n\ndef knerr2D(it, boundary, save, cglob=None, cloc0=0, cloc1=1, cloc2=1,\n krang=np.arange(0.1, 200.1, 10.), nrang=np.arange(0, 100, 5),\n plot=False, resolution=100, coarse_grid_resolution=10):\n err_r = np.zeros((len(krang), len(nrang)))\n p = helmholtz(boundary=boundary)\n usecglob = (cglob is None)\n xi = 0\n for k in krang:\n yi = 0\n if usecglob:\n cglob = -1j*k\n cloc = cloc0 + cloc1 * k + cloc2 * k**2\n mus = {'k': k, 'c_glob': cglob, 'c_loc': cloc}\n gq, lq = localize_problem(p, coarse_grid_resolution, resolution, mus=mus)\n d = gq[\"d\"]\n u = d.solve(mus)\n for n in nrang:\n print(k, n)\n e_r = []\n for i in range(min(20-n/5, it)):\n print(i, )\n sys.stdout.flush()\n bases = create_bases2(gq, lq, n, transfer='robin')\n ru_r = reconstruct_solution(gq, lq, bases)\n del bases\n dif_r = u-ru_r\n e_r.append(gq[\"full_norm\"](dif_r)[0]/gq[\"full_norm\"](u)[0])\n err_r[xi][yi] = np.mean(e_r)\n yi += 1\n xi += 1\n X, Y = np.meshgrid(krang, nrang)\n data = np.vstack([X.T.ravel(), Y.T.ravel(), err_r.ravel()]).T\n open(save, \"w\").writelines([\" \".join(map(str, v)) + \"\\n\" for v in data])\n if plot:\n import matplotlib.pyplot as plt\n from matplotlib import cm\n fig = plt.figure()\n ax = fig.gca(projection='3d')\n surf = ax.plot_surface(X, Y, err_r, cstride=1, rstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False)\n fig.colorbar(surf, shrink=0.5, aspect=5)\n plt.show()\n","sub_path":"src/lmor/evaluations.py","file_name":"evaluations.py","file_ext":"py","file_size_in_byte":17514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"145936513","text":"import tkinter.messagebox\n\n# Poner una mica con los colores RGB y hacer un AND con cada pixel\n# El resultado es el pixel que hay que pintar.\ndef filtroRGB(imagen, otra, entradaR, entradaG, entradaB):\n if entradaR < 0 or entradaR > 255 or entradaG < 0 or entradaG > 255 or entradaB < 0 or entradaB > 255:\n tkinter.messagebox.showwarning(\"Error\", \"Ingresa valores validos.\")\n return otra\n rgb = imagen.convert('RGB')\n pixeles = otra.load()\n for i in range(imagen.size[0]):\n for j in range(imagen.size[1]):\n r, g, b = rgb.getpixel((i, j))\n pixeles[i, j] = (r & entradaR, g & entradaG, b & entradaB)\n return otra\n\n\n","sub_path":"Practica3/RGB.py","file_name":"RGB.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"527097795","text":"# -*- encoding: utf-8 -*-\nfrom __future__ import division\nimport re\n\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom rest_framework import status\n\n\n@api_view(['GET'])\ndef evaluate(request):\n value = request.query_params['value']\n\n regex = re.compile('^[0-9\\.\\-\\+\\*/]+$')\n if not regex.match(value):\n return Response(status=status.HTTP_400_BAD_REQUEST)\n\n try:\n result = eval(value)\n except ZeroDivisionError:\n return Response(data={'success': False, 'msg': u\"Ошибка - на ноль делить нельзя!\"})\n except SyntaxError:\n return Response(data={'success': False, 'msg': u\"Ошибка в выражении!\"})\n\n return Response(data={\n 'success': True,\n 'result': result\n })","sub_path":"apps/calc/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"287533984","text":"import copy\nimport torch\nimport inspect\n\nfrom .baseclient import BaseClient\nfrom src import MetricManager\n\n\nclass FedavgClient(BaseClient):\n def __init__(self, args, training_set, test_set):\n super(FedavgClient, self).__init__()\n self.args = args\n self.training_set = training_set\n self.test_set = test_set\n \n self.optim = torch.optim.__dict__[self.args.optimizer]\n self.criterion = torch.nn.__dict__[self.args.criterion]\n\n self.train_loader = self._create_dataloader(self.training_set, shuffle=not self.args.no_shuffle)\n self.test_loader = self._create_dataloader(self.test_set, shuffle=False)\n\n def _refine_optim_args(self, args):\n required_args = inspect.getfullargspec(self.optim)[0]\n\n # collect eneterd arguments\n refined_args = {}\n for argument in required_args:\n if hasattr(args, argument): \n refined_args[argument] = getattr(args, argument)\n return refined_args\n\n def _create_dataloader(self, dataset, shuffle):\n if self.args.B == 0 :\n self.args.B = len(self.training_set)\n return torch.utils.data.DataLoader(dataset=dataset, batch_size=self.args.B, shuffle=shuffle)\n\n def update(self):\n mm = MetricManager(self.args.eval_metrics)\n self.model.train()\n self.model.to(self.args.device)\n \n optimizer = self.optim(self.model.parameters(), **self._refine_optim_args(self.args))\n for e in range(self.args.E):\n for inputs, targets in self.train_loader:\n inputs, targets = inputs.to(self.args.device), targets.to(self.args.device)\n\n outputs = self.model(inputs)\n loss = self.criterion()(outputs, targets)\n\n for param in self.model.parameters():\n param.grad = None\n loss.backward()\n optimizer.step()\n\n mm.track(loss.item(), outputs, targets)\n else:\n mm.aggregate(len(self.training_set), e + 1)\n return mm.results\n\n @torch.inference_mode()\n def evaluate(self):\n if self.args._train_only: # `args.test_size` == 0\n return {'loss': -1, 'metrics': {'none': -1}}\n\n mm = MetricManager(self.args.eval_metrics)\n self.model.eval()\n self.model.to(self.args.device)\n\n for inputs, targets in self.test_loader:\n inputs, targets = inputs.to(self.args.device), targets.to(self.args.device)\n\n outputs = self.model(inputs)\n loss = self.criterion()(outputs, targets)\n\n mm.track(loss.item(), outputs, targets)\n else:\n mm.aggregate(len(self.test_set))\n return mm.results\n\n def download(self, model):\n self.model = copy.deepcopy(model)\n\n def upload(self):\n self.model.to('cpu')\n return self.model.named_parameters()\n \n def __len__(self):\n return len(self.training_set)\n\n def __repr__(self):\n return f'CLIENT < {self.id} >'\n","sub_path":"src/client/fedavgclient.py","file_name":"fedavgclient.py","file_ext":"py","file_size_in_byte":3042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"219777480","text":"# -*- coding:utf-8 -*-\nimport numpy as np\n\ndef find_match_anchors(bbox, anchors, iou_thresh=0.5):\n '''\n 根据GT找到与之最匹配的anchors,也就是anchors与GT的IOU大于阈值,即认为这些anchors是正样本\n :param bbox: 1D array, [xmin, ymin, xmax, ymax]\n :param anchors: 2D array, N x 4\n :return:\n '''\n inter_xmin = np.maximum(bbox[0], anchors[:, 0])\n inter_ymin = np.maximum(bbox[1], anchors[:, 1])\n inter_xmax = np.minimum(bbox[2], anchors[:, 2])\n inter_ymax = np.minimum(bbox[3], anchors[:, 3])\n inter_width = np.maximum(0, inter_xmax -inter_xmin)\n inter_height = np.maximum(0, inter_ymax - inter_ymin)\n inter_area = inter_width * inter_height\n bbox_area = (bbox[2] - bbox[0]) * (bbox[3] - bbox[1])\n anchor_areas = (anchors[:, 2] - anchors[:, 0]) * (anchors[:, 3] - anchors[:, 1])\n union_area = anchor_areas - inter_area + bbox_area\n iou = inter_area / union_area\n match_idx = np.where(iou > iou_thresh)[0]\n if len(match_idx) == 0: # 如果没有与GT的IOU大于阈值的的anchor,则取IOU最大的一个anchor作为匹配的正样本\n match_idx = np.argsort(iou)[-1:]\n\n match_iou = iou[match_idx]\n return match_idx, match_iou\n\n\ndef encode_one_item_with_anchor(bbox, anchors, variance = [0.1, 0.1, 0.2, 0.2] ):\n '''\n # 将一个GT bounding box编码到与之匹配的anchor上\n :param head_face_bbox: a list of head or face bbox\n :param anchors: matched anchors, 2D arrays, N x 4\n :return:\n '''\n bbox_cx = (bbox[0] + bbox[2]) / 2.0\n bbox_cy = (bbox[1] + bbox[3]) / 2.0\n bbox_w = np.maximum(bbox[2] - bbox[0], 1e-7)\n bbox_h = np.maximum(bbox[3] - bbox[1], 1e-7)\n anchor_cx = (anchors[:, 0:1] + anchors[:, 2:3]) / 2\n anchor_cy = (anchors[:, 1:2] + anchors[:, 3:]) / 2\n anchor_w = anchors[:, 2:3] - anchors[:, 0:1]\n anchor_h = anchors[:, 3:] - anchors[:, 1:2]\n encoded_cx = (bbox_cx - anchor_cx) / anchor_w\n encoded_cy = (bbox_cy - anchor_cy) / anchor_h\n encoded_w = np.log(bbox_w / anchor_w)\n encoded_h = np.log(bbox_h / anchor_h)\n encoded_bbox = np.concatenate([encoded_cx, encoded_cy, encoded_w, encoded_h], axis=-1)\n return encoded_bbox / np.array(variance)\n\n\n# def iou(multi_bboxes, bbox):\n# inter_xmin = np.maximum(multi_bboxes[:, 0], bbox[0])\n# inter_ymin = np.maximum(multi_bboxes[:, 1], bbox[1])\n# inter_xmax = np.minimum(multi_bboxes[:, 2], bbox[2])\n# inter_ymax = np.minimum(multi_bboxes[:, 3], bbox[3])\n# inter_width = np.maximum(0, inter_xmax -inter_xmin)\n# inter_height = np.maximum(0, inter_ymax - inter_ymin)\n#\n# inter_area = inter_width * inter_height\n# bbox_area = (bbox[2] - bbox[0]) * (bbox[3] - bbox[1])\n#\n# multi_areas = (multi_bboxes[:, 2] - multi_bboxes[:, 0]) * (multi_bboxes[:, 3] - multi_bboxes[:, 1])\n# union_area = multi_areas - inter_area + bbox_area\n#\n# iou_value = inter_area / union_area\n# return iou_value\n\n\ndef encode_bboxes_to_anchor(bboxes, labels, anchors, num_class, iou_thresh=0.35):\n '''\n 将bboxes编码到anchors上面\n :param bboxes: 图片的ground truth bboxes\n :param labels: 图片的ground truth labels\n :param anchors:\n :param num_class: 要注意使用的softmax还是sigmoid激活函数,如果用softmax,要多一个背景类\n :param iou_thresh: iou匹配阈值\n :return:\n '''\n encoded_result = np.zeros((anchors.shape[0], 4 + num_class)) # 这里需要注意使用的是\n for idx, bbox in enumerate(bboxes):\n label = labels[idx]\n match_idx, match_iou = find_match_anchors(bbox, anchors, iou_thresh)\n encoded_bbox = encode_one_item_with_anchor(bbox, anchors[match_idx])\n encoded_result[match_idx, :4] = encoded_bbox\n encoded_result[match_idx, 4 + label] = 1 # 省去 one_hot 步骤, 直接在相应类别编号位置上添加标注\n return encoded_result\n","sub_path":"code/SSD model/anchor/anchor_encode.py","file_name":"anchor_encode.py","file_ext":"py","file_size_in_byte":3886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"514445716","text":"# coding: utf-8\nfrom __future__ import division, print_function\nimport random\n\n# Please implement the function `optimal_move(board)`.\n# If the board is in N-position `optimal_move(board)` should return a random valid move.\n# If the board is in P-position `optimal_move(board)` should return a random optimal move, as\n# discussed in the pdf file.\n# You need not to worry about the special case of the empty board. We will make sure that the\n# empty board never enters the `optimal_move` function.\n\n# Pro tip: you can use `random.randint` to draw random numbers.\n\n# Your solution to nim_sum goes here:\ndef nim_sum(board):\n if board:\n i = board[0]\n for j in board[1:]:\n i ^= j\n return i\n else:\n return 0\n\n# Your solution to the task goes here:\ndef optimal_move(board):\n X = nim_sum(board)\n if X == 0:\n non_empty_rows = [i for i,r in enumerate(board) if r != 0]\n random.shuffle(non_empty_rows)\n row_index = non_empty_rows[0]\n return row_index + 1, random.randint(1, board[row_index])\n else:\n lengths = [X ^ i for i in board]\n computed = [(i, (a, n)) for i, (a, n) in enumerate(zip(lengths, board)) if a < n]\n random.shuffle(computed)\n to_return = computed[0]\n return to_return[0] + 1, to_return[1][1] - to_return[1][0]\n\n# You can use the following test case to test your solution locally:\nresult = optimal_move([5, 4, 3, 2, 1])\nassert any([result == (5, 1), result == (3, 1), result == (1, 1)])\n\n# Note: due to technical limitations, there is no automated feedback for this exercise. It's\n# up to you to make sure that your function behaves correctly. Ask your tutor if in doubt.","sub_path":"lab_material/lab17_solutions/optimal_move.py","file_name":"optimal_move.py","file_ext":"py","file_size_in_byte":1692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"327761417","text":"import rdflib\n\nclass BatchGraph:\n def __init__(self, batch_size, file_prefix, format):\n self.current_batch = 1\n self.batch_size = batch_size\n self.file_prefix = file_prefix\n self.format = format\n self.bindings = {}\n self.reset()\n \n def reset(self):\n self.g = rdflib.ConjunctiveGraph()\n self.triple_count = 0\n for prefix, ns in self.bindings.items():\n self.g.bind(prefix, ns)\n \n \n def bind(self, prefix, ns):\n self.bindings[prefix] = ns\n self.g.bind(prefix, ns)\n\n def add(self, triple):\n self.g.add(triple)\n self.triple_count += 1\n if self.triple_count >= self.batch_size:\n self.flush()\n\n def flush(self):\n g_file = open(\"%s_%s.%s\" % (self.file_prefix, self.current_batch, self.format), \"w\")\n if self.format == \"nt\":\n format_name = \"ntriples\"\n else:\n format_name = \"pretty-xml\"\n \n g_file.write(self.g.serialize(format=format_name))\n g_file.close()\n self.reset()\n self.current_batch += 1\n\n def serialize(self, format):\n return self.g.serialize(format)\n","sub_path":"ons/scripts/graphutils.py","file_name":"graphutils.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"633596756","text":"# This file is NOT licensed under the GPLv3, which is the license for the rest\n# of YouCompleteMe.\n#\n# Here's the license text for this file:\n#\n# This is free and unencumbered software released into the public domain.\n#\n# Anyone is free to copy, modify, publish, use, compile, sell, or\n# distribute this software, either in source code form or as a compiled\n# binary, for any purpose, commercial or non-commercial, and by any\n# means.\n#\n# In jurisdictions that recognize copyright laws, the author or authors\n# of this software dedicate any and all copyright interest in the\n# software to the public domain. We make this dedication for the benefit\n# of the public at large and to the detriment of our heirs and\n# successors. We intend this dedication to be an overt act of\n# relinquishment in perpetuity of all present and future rights to this\n# software under copyright law.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n# IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n# OTHER DEALINGS IN THE SOFTWARE.\n#\n# For more information, please refer to \n\nimport os\nimport ycm_core\nimport ConfigParser\nfrom clang_helpers import PrepareClangFlags\n\n# These are the compilation flags that will be used in case there's no\n# compilation database set (by default, one is not set).\n# CHANGE THIS LIST OF FLAGS. YES, THIS IS THE DROID YOU HAVE BEEN LOOKING FOR.\n\nflags = [\n'-x',\n'objective-c',\n'-std=gnu99',\n'-arch',\n'i386',\n'-g',\n'-O0',\n'-fmessage-length=0',\n'-fobjc-arc',\n'-fpascal-strings',\n'-fexceptions',\n'-fasm-blocks',\n'-fstrict-aliasing',\n'-fvisibility=hidden',\n'-fdiagnostics-show-note-include-stack',\n'-fmacro-backtrace-limit=0',\n'-fobjc-abi-version=2',\n'-fobjc-legacy-dispatch',\n'-Weverything', # (optional) warn about everything other than -Wno\n'-Wreturn-type',\n'-Wduplicate-method-match',\n'-Wformat',\n'-Wparentheses',\n'-Wswitch',\n'-Wunused-variable',\n'-Wunused-value',\n'-Wempty-body',\n'-Wuninitialized',\n'-Wpointer-sign',\n'-Wprotocol',\n'-Wdeprecated-declarations',\n'-Wno-gnu', # hide warnings about the use of MAX/MIN macros\n'-Wno-trigraphs',\n'-Wno-missing-field-initializers',\n'-Wno-missing-prototypes',\n'-Wno-implicit-atomic-properties',\n'-Wno-receiver-is-weak',\n'-Wno-missing-braces',\n'-Wno-unused-function',\n'-Wno-unused-label',\n'-Wno-unused-parameter',\n'-Wno-unknown-pragmas',\n'-Wno-shadow',\n'-Wno-four-char-constants',\n'-Wno-conversion',\n'-Wno-constant-conversion',\n'-Wno-bool-conversion',\n'-Wno-int-conversion',\n'-Wno-enum-conversion',\n'-Wno-sign-conversion',\n'-Wno-shorten-64-to-32',\n'-Wno-newline-eof',\n'-Wno-selector',\n'-Wno-strict-selector-match',\n'-Wno-undeclared-selector',\n#'-Wno-deprecated-implementations',\n'-Wno-arc-repeated-use-of-weak',\n'-DDEBUG=1',\n'-DCOCOAPODS=1',\n'-isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator7.0.sdk',\n'-mios-simulator-version-min=6.0',\n'-iquote {derivedDataPath}/Build/Intermediates/{project}.build/{configuration}-iphonesimulator/{target}.build/{product}-generated-files.hmap',\n'-I{derivedDataPath}/Build/Intermediates/{project}.build/{configuration}-iphonesimulator/{target}.build/{product}-own-target-headers.hmap',\n'-I{derivedDataPath}/Build/Intermediates/{project}.build/{configuration}-iphonesimulator/{target}.build/{product}-all-target-headers.hmap',\n'-iquote {derivedDataPath}/Build/Intermediates/{project}.build/{configuration}-iphonesimulator/{target}.build/{product}-project-headers.hmap',\n'-I{derivedDataPath}/Build/Products/{configuration}-iphonesimulator/include',\n'-IPods/Headers',\n'-I{derivedDataPath}/Build/Intermediates/{project}.build/{configuration}-iphonesimulator/{target}.build/DerivedSources/i386',\n'-I{derivedDataPath}/Build/Intermediates/{project}.build/{configuration}-iphonesimulator/{target}.build/DerivedSources',\n\n#'-D__i386__=1',\n\n# for some reason clang complains if we don't throw the below two lines in...\n'-D__arm__=1',\n'-I/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS7.0.sdk/usr/include',\n\n#'-I/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include',\n#'-I/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/5.0/include',\n#'-I/Applications/Xcode.app/Contents/Developer/usr/lib/llvm-gcc/4.2.1/include',\n'-I/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator7.0.sdk/usr/include',\n'-I/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator7.0.sdk/usr/local/include',\n'-F{derivedDataPath}/Build/Products/{configuration}-iphonesimulator',\n'-F/Applications/Xcode.app/Contents/Developer/Library/Frameworks', # include needed for SenTesting\n'-F/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator7.0.sdk/Developer/Library/Frameworks',\n'-F/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator7.0.sdk/System/Library/Frameworks',\n'-DNS_BLOCK_ASSERTIONS=1',\n#'-MMD',\n'-MT',\n'-MF'\n]\n\n# Set this to the absolute path to the folder (NOT the file!) containing the\n# compile_commands.json file to use that instead of 'flags'. See here for\n# more details: http://clang.llvm.org/docs/JSONCompilationDatabase.html\n#\n# Most projects will NOT need to set this to anything; you can just change the\n# 'flags' list of compilation flags. Notice that YCM itself uses that approach.\ncompilation_database_folder = ''\n\nif compilation_database_folder:\n database = ycm_core.CompilationDatabase( compilation_database_folder )\nelse:\n database = None\n\n\ndef DirectoryOfThisScript():\n return os.path.dirname( os.path.abspath( __file__ ) )\n\n\ndef MakeRelativePathsInFlagsAbsolute( flags, working_directory, scheme ):\n if not working_directory:\n return flags\n\n scheme_option = 'scheme'\n config = ConfigParser.ConfigParser()\n config.optionxform = str # do not convert to lower-case\n config.read(os.path.join(working_directory, '.ycm_extra_conf.cfg'))\n options = dict(config.items(scheme))\n if scheme_option not in options:\n options[scheme_option] = scheme\n\n new_flags = []\n make_next_absolute = False\n path_flags = [ '-isystem', '-isysroot', '-I', '-F', '-iquote' ]\n for flag in flags:\n new_flag = flag\n\n if make_next_absolute:\n make_next_absolute = False\n flag = flag.strip() # trim whitespace on both sides\n flag = flag.format(**options) # interpolate\n if not flag.startswith( '/' ):\n new_flag = os.path.join( working_directory, flag)\n\n for path_flag in path_flags:\n if flag == path_flag:\n make_next_absolute = True\n break\n\n if flag.startswith( path_flag ):\n path = flag[ len( path_flag ): ]\n path = path.strip() # trim whitespace on both sides\n path = path.format(**options) # interpolate\n if path.startswith( '/' ):\n new_flag = path_flag + path\n else:\n new_flag = path_flag + os.path.join( working_directory, path)\n break\n\n if new_flag:\n new_flags.append( new_flag )\n return new_flags\n\n\ndef FlagsForFile( filename ):\n if database:\n # Bear in mind that compilation_info.compiler_flags_ does NOT return a\n # python list, but a \"list-like\" StringVec object\n compilation_info = database.GetCompilationInfoForFile( filename )\n final_flags = PrepareClangFlags(\n MakeRelativePathsInFlagsAbsolute(\n compilation_info.compiler_flags_,\n compilation_info.compiler_working_dir_ ),\n filename )\n\n # NOTE: This is just for YouCompleteMe; it's highly likely that your project\n # does NOT need to remove the stdlib flag. DO NOT USE THIS IN YOUR\n # ycm_extra_conf IF YOU'RE NOT 100% YOU NEED IT.\n try:\n final_flags.remove( '-stdlib=libc++' )\n except ValueError:\n pass\n else:\n relative_to = DirectoryOfThisScript()\n\n # not handling double path delimiters...\n if (filename.startswith(relative_to)):\n subdir = filename[len(relative_to):].split('/')[1]\n else:\n subdir = None\n\n final_flags = MakeRelativePathsInFlagsAbsolute( flags, relative_to, subdir )\n\n return {\n 'flags': final_flags,\n 'do_cache': True\n }\n\n","sub_path":".ycm_extra_conf.py","file_name":".ycm_extra_conf.py","file_ext":"py","file_size_in_byte":8565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"245345026","text":"# Structure this script entirely on your own.\n# See Chapter 8: Strings Exercise 5 for the task.\n# Please do provide function calls that test/demonstrate your\n# function.\n\n\ndef cypher(s,c):\n\tcode='' \t\t\t\t\t\t\t\t\t\t#Initialising the final encrypted code\n\tfor i in range(len(s)):\t\t\n\t\tnew_char_num = ord(s[i]) + c % 26 \t\t\t#c % 26 because 'z' shifted 26 times should be 'z' itself\n\t\tif 65 <= ord(s[i]) <= 90:\t\t\t\t\t# For capital letters\t\t\n\t\t\tif new_char_num > 90: \t\t\t\t\t# For letters going being 'Z'\n\t\t\t\tnew_char = chr(new_char_num - 26) \t# To reset the capital letters going beyond limit to capital letters itself\n\t\t\telse: \t\n\t\t\t\tnew_char = chr(new_char_num)\n\t\telse:\t\t\t\t\t\t\t\t\t\t# Similar logic for small letters\n\t\t\tif new_char_num > 122:\t\t\t\t\t\n\t\t\t\tnew_char = chr(new_char_num - 26)\n\t\t\telse: \t\n\t\t\t\tnew_char = chr(new_char_num)\n\t\tcode = code + new_char\t\t\t\t\t\t#Concatenating letter by letter\n\treturn code\n\t\t\n\n\ndef main():\n\tprint(cypher(\"A\",3))\n\tprint(cypher(\"Z\",27))\n\tprint(cypher(\"z\",25))\n\tprint(cypher(\"AB\",-1))\n\tprint(cypher(\"AB\",3))\n\tprint(cypher(\"Cheer\", 7))\n\tprint(cypher(\"Melon\",-10))\n\tprint(cypher(\"IBM\",-1))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"HW04_ch08_ex05.py","file_name":"HW04_ch08_ex05.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"363434470","text":"#!/usr/bin/env python\n\"\"\"\nRun with:\n$ python this-script.py [path_to_input_file]\n\"\"\"\n\nimport argparse\nimport datetime\nimport subprocess\nimport time\n\n\n# Globals\n\n# Note: path to the query file has been hardcoded here\n# queries.txt file has a schema of [slice_title],[query]\nqueries = open('queries/queries-schema-for-domains-types-properties').readlines()\n\n\ndef main(input_file):\n \"\"\" Run the main shell commands\n :param input_file: the path to the RDF file you want sliced according to the queries \"\"\"\n\n query_count = 0\n fname_input = input_file\n fname_output = \"slices-new/fb-rdf-schema-\"\n fname_rest = \"fb-rdf-rest-\"\n\n for query in queries:\n query = query.split(\",\")\n query_title = query[0].strip().replace(\".\", \"-\")\n query_raw = query[1].strip()\n\n query_count += 1\n fname_output += query_title # Add the 1st column from the queries data to the title\n fname_rest += str(query_count) # Increment up the filename for the remainder data\n\n t0 = subprocess.check_output(['gdate','+\"%s%3N\"'])\n p = subprocess.Popen(['gawk',\n \"{ fname\" + '=\"'+fname_output+'\";' + ' fname_rest=\"' +fname_rest +'\"; ' +\n 'if(' + query_raw + ')' + \" { print $0 >> fname; } else { print $0 >> fname_rest; } }\",\n fname_input])\n p.communicate()\n\n t1 = subprocess.check_output(['gdate','+\"%s%3N\"'])\n # Show the runtime stats: initial time, finished time\n print(query_title + \"\\t\" + t0.decode('ascii').strip() + \"\\t\" + t1.decode('ascii').strip())\n\n # Reset some of the file names for the next loop\n fname_input = fname_rest\n fname_rest = \"fb-rdf-rest-\"\n fname_output = \"slices-new/fb-rdf-schema-\"\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('input_file', help='Path to the input data file')\n args = parser.parse_args()\n main(args.input_file)\n # main()\n\n","sub_path":"python/s2-c2-extract-schema.py","file_name":"s2-c2-extract-schema.py","file_ext":"py","file_size_in_byte":2007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"646991905","text":"import simpy\nfrom simulator.nodes import Source, Action, Exit\nfrom simulator.graph import add_node, add_edge\n\nclass Basic(object):\n def __init__(self, **kwargs):\n if 'name' in kwargs:\n self.name = kwargs['name']\n\n def get_name(self):\n return self.name\n\nif __name__ == '__main__':\n env = simpy.Environment()\n basic_args = {'name': 'Basic'}\n\n EDGES = {\n '0': {'source': '2', 'target': '3'},\n '1': {'source': '3', 'target': '4'},\n }\n for key in EDGES:\n add_edge(key, EDGES[key])\n\n NODES = {\n '2': Source(env, Basic, basic_args, '0', 10),\n '3': Action(env, '1'),\n '4': Exit(env),\n }\n for key in NODES:\n add_node(key, NODES[key])\n\n\n env.process(NODES['2'].run())\n env.run(until=50)\n","sub_path":"basic_sim.py","file_name":"basic_sim.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"312362673","text":"import asyncio\nimport discord\nimport json\nimport subprocess\nimport logging\nfrom modules import config\nfrom discord.ext import commands\n\n\nclass System(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n logging.info(\"'System' Cog has been loaded!\")\n\n @commands.command()\n async def wget(self, ctx, *, wget):\n if config.OWNER_IDS.contains(ctx.author.id):\n await ctx.send(\"Downloading file...\")\n subprocess.call(f\"wget {wget}\", shell=True)\n await ctx.send(\"Operation completed successfully!\")\n else:\n await ctx.send(\"You do not have permission to use that command\")\n\n @commands.command(name=\"pip\")\n @commands.cooldown(1, 10, commands.BucketType.user)\n async def pip(self, ctx, *, pip):\n if config.OWNER_IDS.contains(ctx.author.id):\n await ctx.send(\"installing module...\")\n subprocess.call(f\"pip {pip}\", shell=True)\n await ctx.send(\"Operation completed successfully!\")\n else:\n await ctx.send(\"You do not have permission to use that command\")\n\n @commands.command(name=\"pip3\")\n @commands.cooldown(1, 10, commands.BucketType.user)\n async def pip_three(self, ctx, *, pip):\n if config.OWNER_IDS.contains(ctx.author.id):\n await ctx.send(\"installing module...\")\n subprocess.call(f\"pip3 {pip}\", shell=True)\n await ctx.send(\"Operation completed successfully!\")\n else:\n await ctx.send(\"You do not have permission to use that command\")\n\n @commands.command()\n @commands.cooldown(1, 10, commands.BucketType.user)\n async def cmd(self, ctx, *, cmd):\n if config.OWNER_IDS.contains(ctx.author.id):\n if cmd == \"wget\":\n await ctx.send(\"Use the wget command instead\")\n elif cmd == \"ls\":\n await ctx.send(\"'tree' is better then 'ls'\")\n output = subprocess.getoutput(\"tree\")\n await ctx.send(output)\n elif config.BANNED_COMMANDS.contains(cmd):\n await ctx.send(\"No one, not even master, can use those commands...\")\n else:\n output = subprocess.getoutput(cmd)\n await ctx.send(output)\n else:\n await ctx.send(\"You do not have permission to use that command\")\n\n\ndef setup(bot):\n bot.add_cog(System(bot))\n","sub_path":"cogs/system.py","file_name":"system.py","file_ext":"py","file_size_in_byte":2377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"116430978","text":"import pandas as pd\nimport numpy as np\nimport os\nimport logging\nfrom tqdm import tqdm\nimport argparse\nimport math\n\n\nclass CalciumWavesExtractor():\n\n def __init__(self):\n pass\n\n def _extract_background(self, timelapse):\n background = np.mean(timelapse, axis=2).astype('int16')\n background = background.reshape(background.shape + (1,))\n timelapse = (timelapse - background)\n timelapse[timelapse < 0] = 0\n return timelapse\n\n def run(self, timelapse):\n logging.info(\"Extracting calcium waves from 3d representation - might take a while...\")\n timelapse = self._extract_background(timelapse)\n minn = np.min(timelapse).astype('uint16')\n ptp = np.ptp(timelapse).astype('uint16')\n chunksize = 250\n iters = int(math.ceil(timelapse.shape[2] / chunksize))\n for i in range(iters):\n # print(i)\n # (255 * ((image_matrix - minn) / ptp)).astype('uint8')\n chunk = timelapse[..., i * chunksize: (i + 1) * chunksize]\n chunk = (255 * ((chunk - minn) / ptp)).astype('uint8')\n timelapse = timelapse.astype('uint8')\n\n return timelapse\n\n\ndef main():\n\n parser = argparse.ArgumentParser(prog='timespacecreator')\n parser.add_argument('--directory', help='input path where images are stored')\n parser.add_argument('--rootdir', type=str, default='/app/data', help='root directory of files')\n args = parser.parse_args()\n rootdir = args.rootdir\n directory = args.directory\n\n input_path = os.path.join(rootdir, directory)\n\n cwe = CalciumWavesExtractor()\n timespace = np.load(os.path.join(input_path, 'timespace.npy'))\n waves = cwe.run(timespace)\n np.save(os.path.join(input_path, 'waves.npy'), waves)\n\n\ndef debug():\n\n parser = argparse.ArgumentParser(prog='timespacecreator')\n parser.add_argument('--directory', help='input path where images are stored')\n parser.add_argument('--rootdir', type=str, default='/app/data', help='root directory of files')\n args = parser.parse_args()\n rootdir = r'C:\\\\Users\\Wojtek\\Documents\\Doktorat\\Astral\\data'\n directory = 'Cont_AN_2_2'\n\n input_path = os.path.join(rootdir, directory)\n\n cwe = CalciumWavesExtractor()\n timespace = np.load(os.path.join(input_path, 'timespace.npy'))\n waves = cwe.run(timespace)\n np.save(os.path.join(input_path, 'waves.npy'), waves)\n\n\nif __name__ == '__main__':\n main()\n # debug()\n","sub_path":"astrowaves/tasks/CalciumWavesExtractor.py","file_name":"CalciumWavesExtractor.py","file_ext":"py","file_size_in_byte":2445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"370801922","text":"# -*- coding: utf-8 -*-\r\n\r\nimport time\r\nimport calendar\r\nfrom datetime import datetime, timedelta\r\nfrom collections import defaultdict\r\nfrom django.views.generic.base import TemplateView\r\nfrom django.db.models import Count\r\n\r\nfrom models.rrd_loan import Account, AuthInfo\r\nfrom common.utils import last_month, statistic\r\n\r\n\r\nclass StatisticUser(TemplateView):\r\n template_name = 'statistic/select.html'\r\n\r\n def get_context_data(self, **kwargs):\r\n type = int(self.request.GET.get('type', 1))\r\n page = int(self.request.GET.get('page', 1))\r\n where = []\r\n result_list = []\r\n where.append('type=%s' % type)\r\n if type == 1:\r\n d = datetime.strptime(datetime.now().strftime('%Y-%m-%d'), '%Y-%m-%d')\r\n now = datetime.now()\r\n start_time = d - timedelta(days=page - 1)\r\n end_time = min(now, start_time + timedelta(days=1))\r\n filter_dict = {\r\n 'create_time__gte': int(time.mktime(start_time.timetuple())),\r\n 'create_time__lt': int(time.mktime(end_time.timetuple()))\r\n }\r\n models = Account.objects.using('rrd_loan').filter(**filter_dict).all()\r\n uids = [model.uid for model in models]\r\n date_uid_map = self.__map(1, models)\r\n auth_models = AuthInfo.objects.using('rrd_loan').filter(uid__in=uids).all()\r\n status_map = self.__map(2, auth_models)\r\n hour = 24 if end_time.hour == 0 else end_time.hour + 1\r\n for d in range(hour):\r\n models = status_map.get(d, [])\r\n results = {}\r\n for m in models:\r\n if m.status not in results:\r\n results[m.status] = 1\r\n else:\r\n results[m.status] += 1\r\n ret = statistic(results)\r\n ret['reg'] = len(date_uid_map.get(d, []))\r\n ret['date'] = datetime.strftime(start_time + timedelta(hours=d), '%Y-%m-%d %H:%M')\r\n result_list.append(ret)\r\n if type == 2:\r\n start_time = last_month(page - 1)\r\n end_time = datetime.strptime(datetime.now().strftime('%Y-%m-%d'), '%Y-%m-%d') + timedelta(\r\n days=1) if page == 1 else last_month(page - 2)\r\n filter_dict = {\r\n 'create_time__gte': int(time.mktime(start_time.timetuple())),\r\n 'create_time__lt': int(time.mktime(end_time.timetuple()))\r\n }\r\n result_list = self.__hour_day(start_time, end_time, **filter_dict)\r\n if type == 3:\r\n '''周'''\r\n days = datetime.now().weekday()\r\n next_monday = datetime.now().date() - timedelta(days=days) + timedelta(days=7)\r\n start_time = next_monday - timedelta(days=page*7*5)\r\n end_time = start_time + timedelta(days=7*5)\r\n w_start_time = start_time\r\n w_end_time = start_time + timedelta(days=7)\r\n '''只展示前5条'''\r\n while w_end_time <= end_time:\r\n filter_dict = {\r\n 'create_time__gte': int(time.mktime(w_start_time.timetuple())),\r\n 'create_time__lt': int(time.mktime(w_end_time.timetuple()))\r\n }\r\n ret = self.__public(type, w_start_time, w_end_time, **filter_dict)\r\n result_list.append(ret)\r\n w_start_time = w_end_time\r\n w_end_time += timedelta(days=7)\r\n if type == 4:\r\n '''月'''\r\n year = datetime.now().year\r\n h_year = year - page + 1\r\n month = 12 if year > h_year else datetime.now().month\r\n start_time = datetime.strptime(datetime.now().strftime('%s-01-01' % h_year), '%Y-%m-%d')\r\n for i in range(1, month+1):\r\n days = calendar.monthrange(h_year, i)[1]\r\n end_time = start_time + timedelta(days=days)\r\n filter_dict = {\r\n 'create_time__gte': int(time.mktime(start_time.timetuple())),\r\n 'create_time__lt': int(time.mktime(end_time.timetuple()))\r\n }\r\n ret = self.__public(type, start_time, **filter_dict)\r\n result_list.append(ret)\r\n start_time = end_time\r\n fun = lambda k: k.get('date')\r\n result_list.sort(key=fun, reverse=True)\r\n return {\r\n 'data': result_list,\r\n 'current_page': page,\r\n 'where': '&'.join(where),\r\n 'type': type\r\n }\r\n\r\n\r\n def __public(self, type, date, w_date=None, **filter_dict):\r\n models = Account.objects.using('rrd_loan').filter(**filter_dict).all()\r\n uids = [model.uid for model in models]\r\n reg_count = len(uids)\r\n results = AuthInfo.objects.using('rrd_loan').filter(uid__in=uids).values('status'). \\\r\n annotate(num=Count('status')).values('status', 'num')\r\n results = {result['status']: result['num'] for result in results}\r\n ret = statistic(results)\r\n ret['reg'] = reg_count\r\n date_time = None\r\n if type == 1:\r\n date_time = datetime.strftime(date, '%Y-%m-%d %H:%M')\r\n if type == 2:\r\n date_time = datetime.strftime(date, '%Y-%m-%d')\r\n if type == 3:\r\n w_start_time = datetime.strftime(date, '%Y-%m-%d')\r\n w_end_time = datetime.strftime(w_date, '%Y-%m-%d')\r\n date_time = '%s至%s' % (w_start_time, w_end_time)\r\n if type == 4:\r\n date_time = date.strftime('%Y-%m')\r\n ret['date'] = date_time\r\n return ret\r\n\r\n def __map(self, type, models):\r\n middle_map = defaultdict(list)\r\n if type == 1:\r\n for model in models:\r\n date = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(model.create_time))\r\n hour = datetime.strptime(date, '%Y-%m-%d %H:%M:%S').hour\r\n middle_map[hour].append(model.uid)\r\n if type == 2:\r\n for model in models:\r\n date = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(model.create_time))\r\n hour = datetime.strptime(date, '%Y-%m-%d %H:%M:%S').hour\r\n middle_map[hour].append(model)\r\n if type == 3:\r\n for model in models:\r\n date = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(model.create_time))\r\n day = datetime.strptime(date, '%Y-%m-%d %H:%M:%S').day\r\n middle_map[day].append(model.uid)\r\n if type == 4:\r\n for model in models:\r\n date = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(model.create_time))\r\n day = datetime.strptime(date,'%Y-%m-%d %H:%M:%S').day\r\n middle_map[day].append(model)\r\n return middle_map\r\n\r\n def __hour_day(self, start_time, end_time, **filter_dict):\r\n result_list = []\r\n models = Account.objects.using('rrd_loan').filter(**filter_dict).all()\r\n uids = [model.uid for model in models]\r\n date_uid_map = self.__map(3, models)\r\n auth_models = AuthInfo.objects.using('rrd_loan').filter(uid__in=uids).all()\r\n status_map = self.__map(4, auth_models)\r\n for d in range(1, (end_time - start_time).days + 1):\r\n models = status_map.get(d, [])\r\n results = {}\r\n for m in models:\r\n if m.status not in results:\r\n results[m.status] = 1\r\n else:\r\n results[m.status] += 1\r\n ret = statistic(results)\r\n ret['reg'] = len(date_uid_map.get(d, []))\r\n ret['date'] = datetime.strftime(start_time + timedelta(days=d -1), '%Y-%m-%d')\r\n result_list.append(ret)\r\n return result_list\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"dashboard/views/statistic.py","file_name":"statistic.py","file_ext":"py","file_size_in_byte":7965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"251218638","text":"from random import randrange\n\n\n#Problem statement:\n#Given a set of people who are sitting on some seats, \n#and they like to sit on some other seats,\n#find a permutation such that max people are satisfied. \n#[2,2,0,5,3,5,7,4]\ndef naive_max_perm(preferred_seats, seats_in_contention):\n\tif len(seats_in_contention) <= 1:\n\t\treturn seats_in_contention\n\tseats_that_are_preferred = set(preferred_seats[i] for i in seats_in_contention)\n\tseats_not_preferred = seats_in_contention - seats_that_are_preferred\n\tif seats_not_preferred:\n\t\tseats_in_contention -= seats_not_preferred\n\t\treturn naive_max_perm(preferred_seats, seats_in_contention)\n\n\treturn seats_in_contention\n\nfrom collections import Counter\ndef max_perm(preferred_seats):\n\tn = len(preferred_seats)\n\tseats_in_contention = set(range(n))\n\tcount = Counter(preferred_seats)\n\tseats_not_preferred = [i for i in seats_in_contention if count[i]==0 ]\n\twhile seats_not_preferred:\n\t\tk = seats_not_preferred.pop()\n\t\tseats_in_contention.remove(k)\n\t\tj = preferred_seats[k]\n\t\tcount[j] -= 1\n\t\tif count[j] == 0:\n\t\t\tseats_not_preferred.append(j)\n\n\treturn seats_in_contention\n\n#\ndef naive_celebrity(celeb_graph):\n\tnum_nodes = len(celeb_graph)\n\tfor node1 in range(num_nodes):\n\t\tfor node2 in range(num_nodes):\n\t\t\tif node1 == node2:\n\t\t\t\tcontinue\n\t\t\tif celeb_graph[node1][node2] == 1: #node1 knows someone\n\t\t\t\tbreak\n\t\t\tif celeb_graph[node2][node1] == 0: #someone doesnt know node1\n\t\t\t\tbreak\n\t\telse:\n\t\t\tprint(node1)\n\n\nimport unittest\nimport random\nclass TestSequenceFunctions(unittest.TestCase):\n\n\tdef setUp(self):\n\t\tself.preferred_seats = [2,2,0,5,3,5,7,4]\n\t\tself.seats_in_contention = set(range(len(self.preferred_seats)))\n\n\tdef test_naive_max_perm(self):\n\t# make sure the shuffled sequence does not lose any elements \n\t\tperm = naive_max_perm(self.preferred_seats, self.seats_in_contention)\n\t\tself.assertEqual(perm, {0,2,5}) \n\n\tdef test_max_perm(self):\n\t\tperm = max_perm(self.preferred_seats)\n\t\tself.assertEqual(perm, {0,2,5})\n\n\tdef test_naive_celeb(self):\n\t\tn = 10\n\t\tceleb_graph = [[randrange(2) for i in range(n)] for i in range(n)]\n\t\tprint(celeb_graph)\n\t\tnaive_celebrity(celeb_graph)\n\nif __name__ == '__main__':\n\tunittest.main()\n\n\n","sub_path":"excrayg/leetcode/python/fun_algos.py","file_name":"fun_algos.py","file_ext":"py","file_size_in_byte":2168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"370612565","text":"from lab_python_oop.rectangle import Rectangle\nfrom lab_python_oop.circle import Circle\nfrom lab_python_oop.square import Square\nfrom prettytable import PrettyTable\n\n\ndef main():\n r = Rectangle(\"красного\", 23, 23)\n c = Circle(\"зеленого\", 23)\n s = Square(\"жёлтого\", 23)\n table = PrettyTable()\n table.field_names = ['Таблица фигур']\n table.add_row([r])\n table.add_row([c])\n table.add_row([s])\n print(table)\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"Lab#2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"86520192","text":"import numpy as np\nfrom .utils import normalize, np_array, SEED\n\n# np.random.seed(SEED.value)\nimport random\n\n\ndef briding(population, threshold=2, npairs=None, consider_weights=False, how=None):\n \"\"\"\n Common function to do in/out-briding\n\n Parameters\n ----------\n population: list of individuals,\n List to make pairs from.\n threshold: int (default 2),\n Threshold value for in/out-briding.\n npairs: int (optional),\n Number of pairs to generate, if not specified create\n pairs for half of population.\n consider_weights: bool (default False),\n Consider individual weights when randomly picking first\n component of pairs.\n how: {'in', 'out'},\n How to make pairs.\n\n Returns\n -------\n List of pairs\n \"\"\"\n comparators = {\n \"in\": (lambda x, y: x < y, float(\"inf\")),\n \"out\": (lambda x, y: x > y, -float(\"inf\")),\n }\n comparator, inf = comparators[how]\n population = np_array(population)\n\n if npairs is None:\n npairs = len(population) // 2\n\n weights = None\n if consider_weights:\n weights = normalize([o.score for o in population], reverse=True)\n pair_candidates = np.random.choice(population, npairs, p=weights, replace=False)\n\n pairs = [None] * npairs\n for i, f_cand in enumerate(pair_candidates):\n best_candidate, best_threshold = None, inf\n for s_cand in population:\n dist = f_cand.distance(s_cand)\n if comparator(dist, threshold):\n best_candidate = f_cand\n best_threshold = dist\n break\n elif comparator(dist, best_threshold):\n best_candidate = f_cand\n best_threshold = dist\n pairs[i] = (f_cand, best_candidate)\n return pairs\n\n\ndef inbriding(population, threshold=2, npairs=None, consider_weights=False, **kwargs):\n return briding(population, threshold, npairs, consider_weights, how=\"in\")\n\n\ndef outbriding(population, threshold=2, npairs=None, consider_weights=False, **kwargs):\n return briding(population, threshold, npairs, consider_weights, how=\"out\")\n\n\ndef tournament(population, nfighters=4, npairs=None, consider_weights=False, **kwargs):\n assert nfighters > 1, f\"Number of figthers must be at least 2, got {nfighters}.\"\n population = np_array(population)\n\n if npairs is None:\n npairs = len(population) // 2\n\n pairs = [None] * npairs\n weights = None\n if consider_weights:\n weights = [o.score for o in population]\n else:\n weights = np.ones(len(population))\n weights = normalize(weights, reverse=True)\n for i in range(npairs):\n # breakpoint()\n # weights = normalize(weights, reverse=True)\n fighters_idx = np.random.choice(\n len(population), nfighters, p=weights, replace=False\n )\n fighters = population[fighters_idx]\n winners_idx = np.argsort([o.score for o in fighters])[:2]\n # weights[winners_idx] = float(\"inf\")\n pairs[i] = tuple(fighters[winners_idx])\n return pairs\n\n\ndef get_pairs(population, methods, npairs=None, **kwargs):\n if npairs is None:\n npairs = len(population) // 2\n\n pairs = []\n for method in methods.items(npairs):\n npair = int(npairs * method.probability)\n if npair < 1:\n continue\n new_pairs = method.variant(population, npairs=npair, **kwargs)\n pairs.extend(new_pairs)\n return pairs\n","sub_path":"algorithms/pairs_generators.py","file_name":"pairs_generators.py","file_ext":"py","file_size_in_byte":3460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"87961062","text":"# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Function data types.\"\"\"\n\nfrom typing import Mapping, Union\n\nimport tvm._ffi\nimport tvm.runtime\nfrom tvm.runtime import Object\nfrom tvm.ir import BaseFunc\nfrom .buffer import Buffer\nfrom .expr import Var, PrimExpr\nfrom . import _ffi_api\n\n\n@tvm._ffi.register_object(\"tir.PrimFunc\")\nclass PrimFunc(BaseFunc):\n \"\"\"A function declaration expression.\n\n Parameters\n ----------\n params: List[Union[tvm.tir.Var, tvm.tir.Buffer]]\n List of input parameters to the function.\n\n body: tvm.tir.Stmt\n The body of the function.\n\n ret_type: tvm.ir.Type\n The return type annotation of the function.\n\n buffer_map : Map[tvm.tir.Var, tvm.tir.Buffer]\n The buffer binding map.\n\n attrs: Optional[tvm.Attrs]\n Attributes of the function, can be None\n\n span : Optional[Span]\n The location of this itervar in the source code.\n \"\"\"\n\n def __init__(self, params, body, ret_type=None, buffer_map=None, attrs=None, span=None):\n param_list = []\n buffer_map = {} if buffer_map is None else buffer_map\n for x in params:\n x = tvm.runtime.convert(x) if not isinstance(x, Object) else x\n if isinstance(x, Buffer):\n var = Var(x.name, dtype=\"handle\")\n param_list.append(var)\n buffer_map[var] = x\n elif isinstance(x, Var):\n param_list.append(x)\n else:\n raise TypeError(\"params can only contain Var or Buffer\")\n\n self.__init_handle_by_constructor__(\n _ffi_api.PrimFunc, param_list, body, ret_type, buffer_map, attrs, span # type: ignore\n )\n\n def with_body(self, new_body, span=None):\n \"\"\"Create a new PrimFunc with the same set signatures but a new body.\n\n Parameters\n ----------\n new_body : Stmt\n The new body.\n\n span : Optional[Span]\n The location of this itervar in the source code.\n\n Returns\n -------\n new_func : PrimFunc\n The created new function.\n \"\"\"\n return PrimFunc(self.params, new_body, self.ret_type, self.buffer_map, self.attrs, span)\n\n def specialize(self, param_map: Mapping[Var, Union[PrimExpr, Buffer]]):\n \"\"\"Specialize parameters of PrimFunc\n\n Parameters\n ----------\n\n param_map : Mapping[Var, Union[PrimExpr, Buffer]]\n The mapping from function params to the instance\n\n Examples\n --------\n We can define a Meta TIR function with symbolic shape:\n\n .. code-block:: python\n\n @T.prim_func\n def mem_copy(a: T.handle, b: T.handle, m: T.int32, n: T.int32) -> None:\n A = T.match_buffer(a, (m, n), \"float32\")\n B = T.match_buffer(b, (m, n), \"float32\")\n\n for i, j in T.grid(m, n):\n with T.block():\n vi, vj = T.axis.remap(\"SS\", [i, j])\n B[vi, vj] = A[vi, vj]\n\n Then we can make it specialized with given shapes or buffers.\n\n .. code-block:: python\n\n a, _, m, n = mem_copy.params\n func = mem_copy.specialize({a: tir.decl_buffer((16, 16))})\n # or\n func = mem_copy.specialize({n: 16, m: 16})\n\n The specialized function:\n\n .. code-block:: python\n\n @T.prim_func\n def mem_copy_16_16(a: T.handle, b: T.handle) -> None:\n A = T.match_buffer(a, (16, 16), \"float32\")\n B = T.match_buffer(b, (16, 16), \"float32\")\n\n for i, j in T.grid(16, 16):\n with T.block():\n vi, vj = T.axis.remap(\"SS\", [i, j])\n B[vi, vj] = A[vi, vj]\n\n Returns\n -------\n func : PrimFunc\n The new function with parameter specialized\n \"\"\"\n return _ffi_api.Specialize(self, param_map) # type: ignore\n\n def script(self, tir_prefix: str = \"T\", show_meta: bool = False) -> str:\n \"\"\"Print IRModule into TVMScript\n\n Parameters\n ----------\n tir_prefix : str\n The tir namespace prefix\n\n show_meta : bool\n Whether to show meta information\n\n Returns\n -------\n script : str\n The TVM Script of the PrimFunc\n \"\"\"\n return tvm._ffi.get_global_func(\"script.AsTVMScript\")(\n self, tir_prefix, show_meta\n ) # type: ignore\n","sub_path":"python/tvm/tir/function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":5233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"645276337","text":"from models.base.EntityBase import EntityBase\nfrom models.base.integration.DataIntegrationConnectionFileCsvBase import DataIntegrationConnectionFileCsvBase\nfrom infrastructor.json.BaseConverter import BaseConverter\n\n\n@BaseConverter.register\nclass DataIntegrationConnectionFileBase(EntityBase):\n\n def __init__(self,\n DataIntegrationConnectionId: int = None,\n Folder: str = None,\n FileName: str = None,\n DataIntegrationConnection=None,\n Csv:DataIntegrationConnectionFileCsvBase=None,\n *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.DataIntegrationConnectionId: int = DataIntegrationConnectionId\n self.Folder: str = Folder\n self.FileName: str = FileName\n self.DataIntegrationConnection = DataIntegrationConnection\n self.Csv = Csv\n","sub_path":"src/process/models/base/integration/DataIntegrationConnectionFileBase.py","file_name":"DataIntegrationConnectionFileBase.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"397751533","text":"import cv2\n\n## Start video capture with the camera\n# The argument may be changed for\n# a path with a video\ncap = cv2.VideoCapture(0)\n\n## Infinite loop\nwhile True:\n ## Read frame from the capture\n ret, frame = cap.read()\n\n ## Show read frame\n cv2.imshow(\"Frame\", frame)\n\n ## If 'q' key is pressed, exit loop\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n## Release the capture and closes\n# all windows\ncap.release()\ncv2.destroyAllWindows()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"507455541","text":"#############################################################################\n# Copyright 2016 Mass KonFuzion\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\"\"\"\nQueue is a ring-based array/queue. It needs:\n* Enqueue(Message) (or, call it PutMessage or PutEvent or whatever)\n** Place item in list\n** Advance tail, i.e. tail = (tail + 1) % length\n* Dequeue() (or, call it GetEvent or GetMessages or whatever)\n** Return item at head\n** head = (head + 1) % length\n* Clear()\n** Set head = tail\n* RegisterListener(listener)\n* RegisteredListeners()\n** Return a reference to the queue data member\n* _queue = list\n* _registeredListeners = list\n* _head = int\n* _tail = int\n\"\"\"\n\nimport collections\n\nclass MessageQueue:\n def __init__(self):\n self._queue = []\n self._registeredListeners = collections.defaultdict(list) # A list of dict objects. The dict objects contain the Listener Name (for lookups) and a reference to the listener instance\n self._head = 0\n self._tail = 0\n self._empty = True\n\n def Enqueue(self, msg_obj):\n \"\"\" Enqueue a message object\n\n Message objects contain a topic and a payload. Still trying to work out exactly how to design message objects. In Python, they can be a dict\n \"\"\"\n if self._empty:\n self._empty = False\n else:\n self._tail = (self._tail + 1) % len(self._queue)\n assert (self._tail != self._head) # If tail == head, that means we've enqueued too many messages and we're wrapping around\n self._queue[self._tail] = msg_obj\n #print \"DEBUG Enqueued message: {}\".format(msg_obj)\n\n def Dequeue(self):\n if self._empty:\n return None\n\n else:\n return_obj = self._queue[self._head]\n\n if self._head == self._tail and not self._empty:\n self._empty = True\n else:\n self._head = (self._head + 1) % len(self._queue)\n\n #print \"DEBUG Dequeued message: {}\".format(return_obj)\n return return_obj\n\n def RegisterListener(self, listener_name, listener, topic):\n \"\"\"Register a message listener with the MessageQueue\n \n NOTE: This function does not test for containment before adding/replacing items.\n \"\"\"\n #print \"DEBUG Registering Listener: {} {} topic={}\".format(listener_name, listener, topic)\n self._registeredListeners[topic].append( { 'name': listener_name, 'ref': listener} )\n\n def RegisteredListeners(self, topic):\n return self._registeredListeners[topic]\n \n\n def Clear(self):\n self._head = 0\n self._tail = 0\n del self._queue[:]\n self._empty = True\n\n def Initialize(self, num_slots):\n \"\"\"Allocate space for the message queue\n\n NOTE: This function should only ever be run once. The class is not designed for re-allocating memory at runtime\n \"\"\"\n assert(len(self._queue) == 0)\n\n for i in range(0, num_slots):\n self._queue.append(None)\n pass\n","sub_path":"core/message_queue.py","file_name":"message_queue.py","file_ext":"py","file_size_in_byte":3628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"204056132","text":"import numpy as np\nimport pygame\nimport os\nimport random\n\nfrom object import Object\nfrom misc import rot_center\n\nLASER = pygame.transform.scale(pygame.image.load(os.path.join(\"asset\", \"laser.png\")), (29, 29))\n\n\nclass Laser(Object):\n\n def __init__(self, x, y, speed_x, speed_y, angle):\n super().__init__(x, y)\n self.speed = np.array([float(speed_x), float(speed_y)])\n self.angle = angle\n self.image = LASER\n self.mask = pygame.mask.from_surface(rot_center(self.image, self.angle))\n\n def draw(self, window):\n if self.get_img() is None:\n return None\n\n window.blit(rot_center(self.image, self.angle), self.pos)\n\n def next_state(self):\n self.pos += self.speed\n","sub_path":"laser.py","file_name":"laser.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"500461585","text":"import json\nimport os\nimport subprocess\nfrom pathlib import Path\nfrom shutil import move\n\nfrom django.utils.text import slugify\nfrom pydub import AudioSegment\n\nfrom youtube_wrapper import YouTube\nfrom youtube.closed_caption import YouTubeClosedCaption, TranscriptsDisabled\n\nAUDIO_CODEC = \"pcm_s16le\"\nAUDIO_BITRATE = 22050\nAUDIO_CHANNEL = 1\n\n\ndef get_youtube_stream(jsonfile, data_dir, closed_caption=['th'], verbose=True):\n if closed_caption is None:\n closed_caption = ['th', ]\n module = 'youtube-downloader'\n\n def get_target_path(channel_dir, video):\n target_dir = os.path.join(channel_dir, video['id'])\n Path(target_dir).mkdir(parents=True, exist_ok=True)\n return target_dir\n\n def extract_segments(channel_dir, video, wav_file, transcript, verbose=False):\n if verbose:\n print(f'[{module}] Segment Extraction')\n target_dir = get_target_path(channel_dir, video)\n wav_audio = AudioSegment.from_wav(wav_file)\n for key, value in transcript.items():\n start = value[\"start\"] * 1000\n end = start + (value[\"duration\"] * 1000)\n if verbose:\n print(f'[{module}] > {key}.wav - {start} - {end}')\n seg = wav_audio[start:end]\n seg.export(\n open(os.path.join(target_dir, f'{video[\"id\"]}-{key}.wav'), \"wb\"),\n format=\"wav\",\n # codec=AUDIO_CODEC,\n # bitrate=str(AUDIO_BITRATE_,\n # parameters=[\"-ac\", str(AUDIO_CHANNEL)]\n )\n\n def get_caption(channel_dir, video, verbose=False):\n if verbose:\n print(f'[{module}] extract closed caption')\n target_dir = get_target_path(channel_dir, video)\n try:\n transcript = YouTubeClosedCaption.get_transcript(video['id'], languages=closed_caption)\n transcript = {\n f'seg_{f\"%.{len(str(len(transcript)))}d\" % index}': value for index, value in enumerate(transcript)\n }\n json.dump(\n transcript,\n open(os.path.join(target_dir, 'cc.json'), 'w', encoding='utf-8'),\n sort_keys=True, indent=2, ensure_ascii=False\n )\n except TranscriptsDisabled as e:\n return False, None\n return True, transcript\n\n def m4a_to_wav(m4a, codec=AUDIO_CODEC, bitrate=AUDIO_BITRATE, channels=AUDIO_CHANNEL, verbose=False):\n if verbose:\n print(f'[{module}] convert m4a to wav')\n wav_file = m4a.replace('.m4a', f'-{codec}-{bitrate}-{channels}CH.wav')\n subprocess.call([\n \"ffmpeg\", \"-y\", \"-i\", m4a, \"-acodec\", codec, \"-ar\", str(bitrate), \"-ac\", str(channels), wav_file,\n \"-loglevel\", \"error\", \"-hide_banner\", \"-nostats\"\n ])\n\n return wav_file\n\n def mp4_to_m4a(channel_dir, video, verbose=False):\n video_id = video.get('id')\n if verbose:\n print(f'[{module}] convert mp4 to m4a')\n target_dir = get_target_path(channel_dir, video)\n mp4 = os.path.join(channel_dir, f'{video_id}.mp4')\n m4a = os.path.join(target_dir, f'{video_id}.m4a')\n if not (os.path.exists(mp4) and os.path.exists(m4a)):\n move(mp4, m4a)\n return m4a\n\n def stream_to_mp4(video, verbose=False):\n video_id = video.get('id')\n try:\n youtube = YouTube(video.get('link', None))\n if verbose:\n print(f'[{module}] download: {video_id} - {youtube.title}')\n stream = youtube.streams.filter(only_audio=True, audio_codec=\"mp4a.40.2\").first()\n stream.download(channel_dir, filename=f\"{video_id}\")\n return True\n except Exception as e:\n print('error')\n return False\n\n meta = json.load(open(jsonfile, 'r', encoding='utf-8'))\n channel_dir = os.path.join(data_dir, slugify(meta['name']))\n Path(channel_dir).mkdir(parents=True, exist_ok=True)\n for index, video in enumerate(meta['videos']):\n if not stream_to_mp4(video, verbose=verbose):\n continue\n wav_file = m4a_to_wav(mp4_to_m4a(channel_dir, video, verbose=verbose), verbose=verbose)\n has_caption, transcript = get_caption(channel_dir, video, verbose=verbose)\n if has_caption:\n meta['videos'][index]['closed_caption'] = True\n json.dump(meta, open(jsonfile, 'w', encoding='utf-8'), indent=2, ensure_ascii=False)\n extract_segments(channel_dir, video, wav_file, transcript, verbose=verbose)\n\n if verbose:\n print(f'[{module}] remove all temporary mp4 files')\n subprocess.call([\"rm\", f\"{channel_dir}/*.mp4\"])\n","sub_path":"youtube/downloader/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"297114066","text":"# 给定一个整数数组,返回两个数字的索引,使它们相加到一个特定的目标。\n# 您可以假设每个输入都只有一个解决方案,而您可能不会使用相同的元素两次。\n#\n# EXAMPLE \n# Given nums = [2, 7, 11, 15], target = 9,\n# Because nums[0] + nums[1] = 2 + 7 = 9,\n# return [0, 1].\n\nclass Solution(object):\n\n def __init__(self):\n self.nums = [];\n self.target = 0;\n\n def twoSum(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: List[int]\n \"\"\"\n if len(nums) < 2:\n return [];\n oldNum = list(nums);\n\n self.nums = nums;\n self.nums.sort();\n self.target = target;\n \n result = self.calculate();\n if len(result) == 0:\n return result;\n\n if result[0] == result[1]:\n index1 = oldNum.index(result[0]);\n index2 = oldNum.index(result[0], index1 + 1);\n return [index1, index2];\n else:\n indexs = [oldNum.index(result[0]), oldNum.index(result[1])];\n indexs.sort();\n return indexs;\n\n # 计算方案\n def calculate(self):\n for i in range(len(self.nums)):\n for j in range(i + 1, len(self.nums)):\n if self.nums[i] + self.nums[j] == self.target:\n return [self.nums[i], self.nums[j]];\n return [];\n\n\nnums = [-1,-2,-3,-4,-5];\ntarget = -8;\nsolution = Solution();\na = solution.twoSum(nums, target);\nprint(a);\n","sub_path":"docs/algorithm/两个相加为特定的数.py","file_name":"两个相加为特定的数.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"236685551","text":"def createCouple(aa):\n coupleList=[]\n for x in range(len(aa)):\n couples=[]\n for i in range (len(aa)):\n c=aa[x]+aa[i]\n couples.append(c)\n coupleList.append(couples)\n return coupleList\n\ndef collectScores(matrix,aminoacid):\n scores=[]\n dictionary={}\n for line in matrix:\n line=line.rstrip()\n line=line.split()\n for element in line:\n if element not in aminoacid:\n scores.append(element)\n return scores\n\ndef createDictionary(matrix, aminoacid):\n coupleList=createCouple(aminoacid)\n scores=collectScores(matrix, aminoacid)\n dictionary={}\n i=0\n for couples in coupleList:\n for couple in couples:\n dictionary[couple]=scores[i]\n i+=1\n print(dictionary)\n return dictionary\n\n\n\nmatrix=open(\"./blosum50.txt\",\"r\")\naminoacid=\"ARNDCQEGHILKMFPSTWYV\"\ncreateDictionary(matrix,aminoacid)\n","sub_path":"data/exercises/substitution_matrix_blosum.py","file_name":"substitution_matrix_blosum.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"154519506","text":"# coding: UTF-8\n# PEP-8\n\n# Задача-1:\n# Дан список фруктов.\n# Напишите программу, выводящую фрукты в виде нумерованного списка,\n# выровненного по правой стороне.\n\nfruits = ['Яблоко', 'Груша', 'Персик', 'Манго', 'Апельсин']\nfor num, fruit in enumerate(fruits):\n print('{}. {:>10}' .format(num + 1, fruit))\n","sub_path":"lesson_2/lesson_2_easy_1.py","file_name":"lesson_2_easy_1.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"170553136","text":"import json\r\nimport pprint\r\nimport pygame\r\nfrom Game import Game\r\nfrom Records import Records\r\n\r\nwith open('Recoreds.json') as data_file:\r\n text = json.load(data_file)\r\n\r\n\r\ndef rewrite(text, i, a):\r\n for b in range(i + 1, 10):\r\n c = text[b]['name']\r\n text[b]['name'] = a\r\n a = c\r\n\r\n\r\ndef run_rec(text):\r\n pygame.init()\r\n records = []\r\n new_rec = []\r\n for el in text:\r\n records.append(el[\"Place\"] + str(el[\"name\"]))\r\n for i in range(0, 10):\r\n new_rec.append(Records(records[i], (450, 50 + 70 * (i + 1))))\r\n\r\n done = False\r\n while not done:\r\n screen = pygame.display.set_mode((1150, 955))\r\n pygame.event.pump()\r\n screen.fill((0, 0, 0))\r\n for option in new_rec:\r\n option.hovered = False\r\n option.draw()\r\n pygame.display.update()\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n done = True\r\n\r\n\r\nclass Option:\r\n hovered = False\r\n\r\n def __init__(self, text, pos):\r\n self.text = text\r\n self.pos = pos\r\n self.set_rect()\r\n self.draw()\r\n\r\n def draw(self):\r\n self.set_rend()\r\n screen.blit(self.rend, self.rect)\r\n\r\n def set_rend(self):\r\n self.rend = menu_font.render(self.text, True, self.get_color())\r\n\r\n def get_color(self):\r\n if self.hovered:\r\n return (255, 255, 255)\r\n else:\r\n return (100, 100, 100)\r\n\r\n def set_rect(self):\r\n self.set_rend()\r\n self.rect = self.rend.get_rect()\r\n self.rect.topleft = self.pos\r\n\r\n\r\nNew_game = (140, 155)\r\noptionS = (140, 255)\r\nquet = (140, 455)\r\nrecoRds = (140, 355)\r\ngame = Game()\r\n\r\npygame.init()\r\nrecords = []\r\nnew_rec = []\r\nscreen = pygame.display.set_mode((1150, 955))\r\nbackground_image = pygame.image.load(\"BG_MENU.jpg\").convert()\r\nmenu_font = pygame.font.Font(None, 100)\r\noptions = [Option(\"New game\", New_game), Option(\"Options\", optionS), Option('Records', recoRds),\r\n Option(\"Quit\", quet)]\r\n\r\ndone = False\r\nwhile not done:\r\n screen = pygame.display.set_mode((1150, 955))\r\n pygame.event.pump()\r\n screen.blit(background_image, [0, 0])\r\n for option in options:\r\n if option.rect.collidepoint(pygame.mouse.get_pos()):\r\n option.hovered = True\r\n else:\r\n option.hovered = False\r\n option.draw()\r\n pygame.display.update()\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n # for el in text:\r\n done = True\r\n elif event.type == pygame.MOUSEBUTTONDOWN:\r\n pos = pygame.mouse.get_pos()\r\n print(pos)\r\n if pos[0] > 140 and pos[0] < 140 + 330 and pos[1] > 155 and pos[1] < 155 + 60:\r\n new_txt = game.run()\r\n for i in range(0, 10):\r\n if int(text[i][\"name\"]) < int(new_txt):\r\n a = text[i][\"name\"]\r\n text[i][\"name\"] = new_txt\r\n rewrite(text, i, a)\r\n break\r\n json.dump(text, open('Recoreds.json', \"w\"))\r\n print(text)\r\n elif pos[0] > 135 and pos[0] < 135 + 276 and pos[1] > 255 and pos[1] < 255 + 60:\r\n print('optg')\r\n elif pos[0] > 140 and pos[0] < 140 + 280 and pos[1] > 355 and pos[1] < 355 + 60:\r\n run_rec(text)\r\n elif pos[0] > 145 and pos[0] < 145 + 140 and pos[1] > 455 and pos[1] < 455 + 60:\r\n done = True\r\n","sub_path":"fhs.py","file_name":"fhs.py","file_ext":"py","file_size_in_byte":3528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"338880284","text":"def check(num):\n count = 0\n for i in range(2,num):\n if num / i == 0:\n count += 1\n if i not in [2, 3, 5]:\n return False\n if count == 0:\n return False\n return True\n\ndef findit(num):\n for _ in range(10000):\n num += 1\n if check(num):\n return num\n return 2\n","sub_path":"homework/hw09/try.py","file_name":"try.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"56096298","text":"import random\r\n\r\ndef exam():\r\n nums = [random.randint(1,100) for i in range(2)] #取两个随机数\r\n nums.sort(reverse=True) #排序\r\n opt = random.choice('+-×÷') #抽取选项\r\n #函数字典\r\n dic = {'+': lambda x, y:x + y, '-': lambda x, y:x - y, '×': lambda x, y:x * y, '÷': lambda x, y:x // y}\r\n #保存正确结果\r\n result = dic[opt](*nums)\r\n #提示内容\r\n prompt = '%s %s %s = ' % (nums[0], opt, nums[1])\r\n count = 0\r\n while count < 3:\r\n try:\r\n answer = int(input(prompt))\r\n except:\r\n count +=1\r\n continue\r\n\r\n if answer == result:\r\n print('答对了!')\r\n break\r\n print('不对')\r\n count += 1\r\n else:\r\n print('正确答案:%s%s' % (prompt, result))\r\n\r\ndef menu():\r\n while 1:\r\n exam()\r\n try:\r\n #取出用户输入的两端空格,然后取出首字母\r\n opt = input('继续吗?(y/n)').strip()[0]\r\n except:\r\n opt = 'y'\r\n if opt in 'Nn':\r\n print('\\nbye-bye')\r\n break\r\n\r\nif __name__ == '__main__':\r\n menu()","sub_path":"math_game.py","file_name":"math_game.py","file_ext":"py","file_size_in_byte":1151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"301882904","text":"import pandas as pd\nfrom sklearn.naive_bayes import GaussianNB,BernoulliNB,MultinomialNB\nfrom sklearn.preprocessing import MinMaxScaler # 最大值最小值\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nimport numpy as np\n# 动态做字符串映射\ndef transform_datas(datas,cols):\n for c in cols: # 获取每一列\n for i,item in enumerate(datas[c].drop_duplicates()): # 获取每一列不重复的值\n datas[c][datas[c].str.strip()==item.strip()]=i+1\n return datas\n\ndef drop(datas):\n for c in datas.columns: # 获取每一列\n datas[c][datas[c]==' ?']=np.NAN\n datas.dropna(inplace=True)\n return datas\ndatas=pd.read_csv(r'D:\\百知人工智能训练营\\人工智能\\数据集\\adult.txt',names=range(15))\ndatas=drop(datas)\n\ndatas=transform_datas(datas,[1,3,5,6,7,8,9,13,14])\n# print(datas)\nX=datas.iloc[:,:-1]\nY=datas.iloc[:,-1]\nY=Y.astype(int)\n# print(Y)\ns=MinMaxScaler()\ns.fit(X)\nX=s.transform(X)\nfor i in range(10):\n# print(s.transform([[31587,1.845967,0.488985]]))\n train_x,test_x,train_y,test_y=train_test_split(X,Y,test_size=0.2)\n # knn=MultinomialNB()\n knn=MultinomialNB()\n knn.fit(train_x,train_y) # 训练算法\n print(knn.score(test_x,test_y))# 评估算法\n# #\n#\n","sub_path":"ai/day4/adult数据集清洗.py","file_name":"adult数据集清洗.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"568438119","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport pandas as pd\n\n\n# In[2]:\n\n\ndataset = pd.read_csv(\"C:/Users/Mon_Amour/Desktop/dataset_project/bihar_rainfall.csv\")\n\n\n# In[3]:\n\n\ndataset\n\n\n# In[4]:\n\n\ny = dataset['rainfall']\n\n\n# In[5]:\n\n\nx=dataset['year']\n\n\n# In[6]:\n\n\nx=x.values\n\n\n# In[7]:\n\n\nz=x.shape\n\n\n# In[8]:\n\n\nX=x.reshape(z[0],1)\n\n\n# In[9]:\n\n\nimport cv2\n\n\n# In[10]:\n\n\nfrom sklearn.linear_model import LinearRegression\n\n\n# In[11]:\n\n\nmind = LinearRegression()\n\n\n# In[12]:\n\n\nmind.fit(X,y)\n\n\n# In[2]:\n\n\nimport joblib\n\n\n# In[18]:\n\n\njoblib.dump(mind,'C:/Users/Mon_Amour/Desktop/dataset_project/rainfall_model.pk1')\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"rainfall_trainer.py","file_name":"rainfall_trainer.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"524897320","text":"from datetime import date\n\nimport pytest\nimport responses\nimport re\n\nfrom personio_py import PersonioError, Absence, Employee\nfrom tests.test_mock_api import mock_personio, compare_labeled_attributes, mock_employees\nfrom tests.mock_data import json_dict_absence_alan, json_dict_absence_types, json_dict_empty_response,\\\n json_dict_delete_absence, json_dict_absence_alan_first, json_dict_absence_create_no_halfdays, json_dict_get_absence\n\n\n@responses.activate\ndef test_get_absence_from_id():\n personio = mock_personio()\n mock_get_absence()\n absence_id_only = Absence(id_=2628890)\n absence = personio.get_absence(absence_id_only)\n assert absence.employee.first_name == 'Alan'\n assert absence.employee.last_name == 'Turing'\n assert absence.id_ == 2628890\n assert absence.start_date == date(2021, 1, 1)\n assert absence.end_date == date(2021, 1, 10)\n\n\n@responses.activate\ndef test_get_absence_from_object_without_id():\n personio = mock_personio()\n mock_get_absence()\n mock_single_absences()\n absence_id_only = Absence(id_=2628890)\n absence = personio.get_absence(absence_id_only)\n absence.id_ = None\n personio.get_absence(absence)\n\n\n@responses.activate\ndef test_create_absence():\n mock_absence_types()\n mock_create_absence_no_halfdays()\n personio = mock_personio()\n absence_type = personio.get_absence_types()[0]\n employee = Employee(\n first_name=\"Alan\",\n last_name='Turing',\n email='alan.turing@cetitec.com'\n )\n absence = Absence(\n client=personio,\n employee=employee,\n start_date=date(2020, 1, 1),\n end_date=date(2020, 1, 10),\n half_day_start=False,\n half_day_end=False,\n time_off_type=absence_type)\n absence.create()\n assert absence.id_\n\n\n@responses.activate\ndef test_delete_absence():\n mock_delete_absence()\n personio = mock_personio()\n result = personio.delete_absence(2116365)\n assert result is True\n\n\n@responses.activate\ndef test_delete_absence_no_client():\n personio = mock_personio()\n mock_absences()\n absence = personio.get_absences(2116365)[0]\n absence._client = None\n with pytest.raises(PersonioError):\n absence.delete()\n\n\n@responses.activate\ndef test_delete_absence_passed_client():\n personio = mock_personio()\n mock_absences()\n mock_delete_absence()\n absence = personio.get_absences(2116365)[0]\n absence._client = None\n assert absence.delete(client=personio) is True\n\n\n@responses.activate\ndef test_delete_absence_no_id():\n personio = mock_personio()\n mock_absences()\n absence = personio.get_absences(2116365)[0]\n absence.id_ = None\n with pytest.raises(ValueError):\n absence.delete()\n with pytest.raises(ValueError):\n personio.delete_absence(absence)\n\n\n@responses.activate\ndef test_get_absences():\n # configure personio & get absences for alan\n mock_absences()\n personio = mock_personio()\n absences = personio.get_absences(2116365)\n # validate\n assert len(absences) == 3\n selection = [a for a in absences if \"marathon\" in a.comment.lower()]\n assert len(selection) == 1\n marathon = selection[0]\n assert marathon.start_date == date(1944, 9, 1)\n assert marathon.half_day_start == 0\n assert marathon.half_day_end == 1\n assert marathon.status == 'approved'\n # validate serialization\n source_dict = json_dict_absence_alan['data'][0]\n target_dict = marathon.to_dict()\n compare_labeled_attributes(source_dict, target_dict)\n\n\n@responses.activate\ndef test_get_absences_from_employee_objects():\n # mock endpoints & get absences for all employees\n mock_employees()\n mock_absences()\n personio = mock_personio()\n employees = personio.get_employees()\n assert employees\n absences = personio.get_absences(employees)\n # the response is not important (it does not match the input), but the function should accept\n # a list of Employee objects as parameter and return a result\n assert absences\n\n\n@responses.activate\ndef test_get_absence_types():\n mock_absence_types()\n # configure personio & get absences for alan\n personio = mock_personio()\n absence_types = personio.get_absence_types()\n # non-empty contents\n assert len(absence_types) == 3\n for at in absence_types:\n assert at.id_ > 0\n assert isinstance(at.name, str)\n # serialization matches input\n for source_dict, at in zip(json_dict_absence_types['data'], absence_types):\n target_dict = at.to_dict()\n assert source_dict == target_dict\n\n\ndef mock_absence_types():\n # mock the get absence types endpoint\n responses.add(\n responses.GET, 'https://api.personio.de/v1/company/time-off-types', status=200,\n json=json_dict_absence_types, adding_headers={'Authorization': 'Bearer foo'})\n\n\ndef mock_absences():\n # mock the get absences endpoint (with different array offsets)\n responses.add(\n responses.GET, re.compile('https://api.personio.de/v1/company/time-offs?.*offset=1.*'),\n status=200, json=json_dict_absence_alan, adding_headers={'Authorization': 'Bearer foo'})\n\n\ndef mock_single_absences():\n # mock the get absences endpoint (with different array offsets)\n responses.add(\n responses.GET, re.compile('https://api.personio.de/v1/company/time-offs?.*offset=1.*'),\n status=200, json=json_dict_absence_alan_first, adding_headers={'Authorization': 'Bearer foo'})\n\n\ndef mock_no_absences():\n # mock the get absences endpoint\n responses.add(\n responses.GET, re.compile('https://api.personio.de/v1/company/time-offs?.*offset=1.*'),\n status=200, json=json_dict_empty_response, adding_headers={'Authorization': 'Bearer bar'})\n\n\ndef mock_delete_absence():\n # mock the delete endpoint\n responses.add(\n responses.DELETE, re.compile('https://api.personio.de/v1/company/time-offs/*'),\n status=200, json=json_dict_delete_absence, adding_headers={'Authorization': 'Bearer bar'})\n\n\ndef mock_create_absence_no_halfdays():\n responses.add(\n responses.POST, 'https://api.personio.de/v1/company/time-offs',\n status=200, json=json_dict_absence_create_no_halfdays, adding_headers={'Authorization': 'Bearer bar'})\n\n\ndef mock_get_absence():\n responses.add(\n responses.GET, re.compile('https://api.personio.de/v1/company/time-offs/.*'),\n status=200, json=json_dict_get_absence, adding_headers={'Authorization': 'Bearer bar'})\n","sub_path":"tests/test_mock_api_absences.py","file_name":"test_mock_api_absences.py","file_ext":"py","file_size_in_byte":6444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"322839391","text":"\n\"\"\" \nSet up the plot figures, axes, and items to be done for each frame.\n\nThis module is imported by the plotting routines and then the\nfunction setplot is called to set the plot parameters.\n \n\"\"\"\n\nimport os\n\nimport numpy as np\nimport matplotlib\n\nimport matplotlib.pyplot as plt\n\nfrom geoclaw import topotools\nfrom clawpack.visclaw import colormaps, geoplot, gaugetools\nfrom clawpack.clawutil.oldclawdata import Data\n\nimport geoclaw.surge as surge\n\ntry:\n from setplotfg import setplotfg\nexcept:\n setplotfg = None\n\n\ndef setplot(plotdata):\n r\"\"\"Setplot function for surge plotting\"\"\"\n \n\n plotdata.clearfigures() # clear any old figures,axes,items data\n\n # Load data from output\n amrdata = Data(os.path.join(plotdata.outdir,'amr2ez.data'))\n physics = Data(os.path.join(plotdata.outdir,'physics.data'))\n surge_data = Data(os.path.join(plotdata.outdir,'surge.data'))\n\n # Load storm track\n track = surge.plot.track_data(os.path.join(plotdata.outdir,'fort.track'))\n surge_afteraxes = lambda cd: surge.plot.surge_afteraxes(cd,track)\n\n # Limits for plots\n full_xlimits = [-92.0,-45.0]\n full_ylimits = [13.0,41.0]\n\n # Color limits\n surface_range = 1.0\n speed_range = 2.0\n\n xlimits = full_xlimits\n ylimits = full_ylimits\n eta = physics.eta_init\n if not isinstance(eta,list):\n eta = [eta]\n surface_limits = [eta[0]-surface_range,eta[0]+surface_range]\n speed_limits = [0.0,speed_range]\n \n wind_limits = [0,55]\n pressure_limits = [966,1013]\n vorticity_limits = [-1.e-2,1.e-2]\n\n def pcolor_afteraxes(current_data):\n surge_afteraxes(current_data)\n surge.plot.gauge_locations(current_data)\n \n def contour_afteraxes(current_data):\n surge_afteraxes(current_data)\n\n \n # ==========================================================================\n # ==========================================================================\n # Plot specifications\n # ==========================================================================\n # ==========================================================================\n\n # ========================================================================\n # Surface Elevations - Entire Atlantic\n # ========================================================================\n plotfigure = plotdata.new_plotfigure(name='Surface - Atlantic', figno=0)\n plotfigure.show = True\n\n # Set up for axes in this figure:\n plotaxes = plotfigure.new_plotaxes()\n plotaxes.title = 'Surface'\n plotaxes.scaled = True\n plotaxes.xlimits = xlimits\n plotaxes.ylimits = ylimits\n plotaxes.afteraxes = pcolor_afteraxes\n \n surge.plot.add_surface_elevation(plotaxes,bounds=surface_limits)\n surge.plot.add_land(plotaxes)\n\n\n # ========================================================================\n # Water Speed - Entire Atlantic\n # ========================================================================\n plotfigure = plotdata.new_plotfigure(name='Currents - Atlantic', figno=1)\n plotfigure.show = True\n\n # Set up for axes in this figure:\n plotaxes = plotfigure.new_plotaxes()\n plotaxes.title = 'Currents'\n plotaxes.scaled = True\n plotaxes.xlimits = xlimits\n plotaxes.ylimits = ylimits\n plotaxes.afteraxes = pcolor_afteraxes\n\n # Speed\n surge.plot.add_speed(plotaxes,bounds=speed_limits)\n\n # Land\n surge.plot.add_land(plotaxes)\n\n\n # ========================================================================\n # Hurricane forcing - Entire Atlantic\n # ========================================================================\n # Pressure field\n plotfigure = plotdata.new_plotfigure(name='Pressure', figno=2)\n plotfigure.show = surge_data.pressure_forcing\n \n plotaxes = plotfigure.new_plotaxes()\n plotaxes.xlimits = full_xlimits\n plotaxes.ylimits = full_ylimits\n plotaxes.title = \"Pressure Field\"\n plotaxes.afteraxes = surge_afteraxes\n plotaxes.scaled = True\n \n surge.plot.add_pressure(plotaxes,bounds=pressure_limits)\n # surge.plot.add_pressure(plotaxes)\n surge.plot.add_land(plotaxes)\n \n # Wind field\n plotfigure = plotdata.new_plotfigure(name='Wind Speed',figno=3)\n plotfigure.show = surge_data.wind_forcing\n \n plotaxes = plotfigure.new_plotaxes()\n plotaxes.xlimits = full_xlimits\n plotaxes.ylimits = full_ylimits\n plotaxes.title = \"Wind Field\"\n plotaxes.afteraxes = surge_afteraxes\n plotaxes.scaled = True\n \n surge.plot.add_wind(plotaxes,bounds=wind_limits,plot_type='imshow')\n # surge.plot.add_wind(plotaxes,bounds=wind_limits,plot_type='contour')\n # surge.plot.add_wind(plotaxes,bounds=wind_limits,plot_type='quiver')\n surge.plot.add_land(plotaxes)\n \n # Wind field components\n plotfigure = plotdata.new_plotfigure(name='Wind Components',figno=4)\n plotfigure.show = surge_data.wind_forcing\n \n plotaxes = plotfigure.new_plotaxes()\n plotaxes.axescmd = \"subplot(121)\"\n plotaxes.xlimits = full_xlimits\n plotaxes.ylimits = full_ylimits\n plotaxes.title = \"X-Component of Wind Field\"\n plotaxes.afteraxes = surge_afteraxes\n plotaxes.scaled = True\n\n plotitem = plotaxes.new_plotitem(plot_type='2d_imshow')\n plotitem.plot_var = surge.plot.wind_x\n plotitem.imshow_cmap = colormaps.make_colormap({1.0:'r',0.5:'w',0.0:'b'})\n plotitem.imshow_cmin = -wind_limits[1]\n plotitem.imshow_cmax = wind_limits[1]\n plotitem.add_colorbar = True\n plotitem.amr_celledges_show = [0,0,0]\n plotitem.amr_patchedges_show = [1,1,1]\n \n plotaxes = plotfigure.new_plotaxes()\n plotaxes.axescmd = \"subplot(122)\"\n plotaxes.xlimits = full_xlimits\n plotaxes.ylimits = full_ylimits\n plotaxes.title = \"Y-Component of Wind Field\"\n plotaxes.afteraxes = surge_afteraxes\n plotaxes.scaled = True\n\n plotitem = plotaxes.new_plotitem(plot_type='2d_imshow')\n plotitem.plot_var = surge.plot.wind_y\n plotitem.imshow_cmap = colormaps.make_colormap({1.0:'r',0.5:'w',0.0:'b'})\n plotitem.imshow_cmin = -wind_limits[1]\n plotitem.imshow_cmax = wind_limits[1]\n plotitem.add_colorbar = True\n plotitem.amr_celledges_show = [0,0,0]\n plotitem.amr_patchedges_show = [1,1,1]\n\n # ========================================================================\n # Figures for gauges\n # ========================================================================\n plotfigure = plotdata.new_plotfigure(name='Surface & topo', figno=300, \\\n type='each_gauge')\n plotfigure.show = True\n plotfigure.clf_each_gauge = True\n\n # Set up for axes in this figure:\n plotaxes = plotfigure.new_plotaxes()\n try:\n plotaxes.xlimits = [amrdata.t0,amrdata.tfinal]\n except:\n pass\n plotaxes.ylimits = surface_limits\n plotaxes.title = 'Surface'\n plotaxes.afteraxes = surge.plot.gauge_afteraxes\n\n # Plot surface as blue curve:\n plotitem = plotaxes.new_plotitem(plot_type='1d_plot')\n plotitem.plot_var = 3\n plotitem.plotstyle = 'r-'\n\n\n #-----------------------------------------\n \n # Parameters used only when creating html and/or latex hardcopy\n # e.g., via pyclaw.plotters.frametools.printframes:\n\n plotdata.printfigs = True # print figures\n plotdata.print_format = 'png' # file format\n plotdata.print_framenos = 'all' # list of frames to print\n plotdata.print_gaugenos = 'all' # list of gauges to print\n plotdata.print_fignos = 'all' # list of figures to print\n plotdata.html = True # create html files of plots?\n plotdata.html_homelink = '../README.html' # pointer for top of index\n plotdata.latex = True # create latex file of plots?\n plotdata.latex_figsperline = 2 # layout of plots\n plotdata.latex_framesperline = 1 # layout of plots\n plotdata.latex_makepdf = False # also run pdflatex?\n\n return plotdata\n\n","sub_path":"storm_surge/atlantic/sandy/setplot.py","file_name":"setplot.py","file_ext":"py","file_size_in_byte":7986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"612453191","text":"from tkinter import *\n\nroot=Tk()\nroot.geometry(\"655x333\")\n\ndef getvals():\n print(\"Submitting Form\")\n print(f\"{namevalue.get(),phonevalue.get(),gendervalue.get(),emergencyvalue.get(),paymentmodevalue.get(), foodservicevalue.get()}\")\n\n with open(\"records.txt\",\"a\") as f:\n f.write(f\"{namevalue.get(),phonevalue.get(),gendervalue.get(),emergencyvalue.get(),paymentmodevalue.get(),foodservicevalue.get()}\\n\")\n\nLabel(root,text=\"Welcome to KV Travels\",font=\"comicsansms 13 bold\",pady=15).grid(row=0,column=3)\nname=Label(root,text=\"Name\")\nphone=Label(root,text=\"Phone\")\ngender=Label(root,text=\"Gender\")\nemergency=Label(root,text=\"Emergency Contact\")\npayment=Label(root,text=\"Payment Mode\")\n\nname.grid(row=1,column=2)\nphone.grid(row=2,column=2)\ngender.grid(row=3,column=2)\nemergency.grid(row=4,column=2)\npayment.grid(row=5,column=2)\n\nnamevalue=StringVar()\nphonevalue=StringVar()\ngendervalue=StringVar()\nemergencyvalue=StringVar()\npaymentmodevalue=StringVar()\nfoodservicevalue=IntVar()\n\nnameentry=Entry(root,textvariable=namevalue)\nphoneentry=Entry(root,textvariable=phonevalue)\ngenderentry=Entry(root,textvariable=gendervalue)\nemergencyentry=Entry(root,textvariable=emergencyvalue)\npaymententry=Entry(root,textvariable=paymentmodevalue)\n\nnameentry.grid(row=1,column=3)\nphoneentry.grid(row=2,column=3)\ngenderentry.grid(row=3,column=3)\nemergencyentry.grid(row=4,column=3)\npaymententry.grid(row=5,column=3)\n\n#Checkbox & packing it\nfoodservice=Checkbutton(text=\"Want to prebook your meal ?\",variable=foodservicevalue)\nfoodservice.grid(row=6,column=3)\n\n#Button & packing it & assigning it a command\nButton(text=\"Submit to KV travels\",command=getvals).grid(row=7,column=3)\n\nroot.mainloop()\n","sub_path":"Form_Creation2.py","file_name":"Form_Creation2.py","file_ext":"py","file_size_in_byte":1697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"72141631","text":"from json import loads, dumps\nfrom django.utils.timezone import get_current_timezone\nfrom api.tests.base import BaseTestCase\nfrom api.schema import schema\n\nTIMEZONE = get_current_timezone()\n\n\nclass ConferenceTest(BaseTestCase):\n def test_retrieve_conference(self):\n query = '''\n query {\n conference {\n name\n nameKo\n nameEn\n conferenceStartedAt\n conferenceFinishedAt\n sprintStartedAt\n sprintFinishedAt\n tutorialStartedAt\n tutorialFinishedAt\n }\n }\n '''\n\n expected = {\n 'conference': {\n 'name': '파이콘 한국 2019',\n 'nameKo': '파이콘 한국 2019',\n 'nameEn': 'Pycon Korea 2019',\n 'conferenceStartedAt': '2019-08-17',\n 'conferenceFinishedAt': '2019-08-18',\n 'sprintStartedAt': '2019-08-15',\n 'sprintFinishedAt': '2019-08-16',\n 'tutorialStartedAt': '2019-08-15',\n 'tutorialFinishedAt': '2019-08-16'\n }\n }\n result = schema.execute(query)\n actual = loads(dumps(result.data))\n self.assertDictEqual(actual, expected)\n","sub_path":"api/tests/scheme/test_conference.py","file_name":"test_conference.py","file_ext":"py","file_size_in_byte":1296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"134605515","text":"'''\nCreated on Oct 30, 2012\n\nBasic Flickr client to let us get custom splits of Colonial photos\nand return data as JSON. Fetch and store from cache once an hour.\n\n@author: santhosh\n'''\n\nfrom colonial.local_settings import FLICKR_API_KEY\n\nfrom django.core.cache import cache\n\nfrom urllib import urlencode, urlopen\nimport json\n\nFLICKR_ENDPOINT = 'https://api.flickr.com/services/rest/?%s'\nAPI_KEY = FLICKR_API_KEY\nCOLONIAL_USERNAME = 'colonialclub'\nCOLONIAL_NSID = '89490301@N06'\nHOMEPAGE_PHOTOSET_ID = '72157631898021750'\nPHOTOSPAGE_PHOTOSET_ID = '72157632778900009'\nFLICKR_STATIC_URL = 'http://farm%s.staticflickr.com/%s/%s_%s_b.jpg'\nFLICKR_STATIC_URL_SMALL = 'http://farm%s.staticflickr.com/%s/%s_%s.jpg'\n\nPHOTOS_CACHE_TIMEOUT = 10*60\n\ndef getNSIDbyUsername(username):\n\tparams = urlencode({\n\t\t\t\t\t\t'api_key': API_KEY,\n\t\t\t\t\t\t'username': username,\n\t\t\t\t\t\t'method': 'flickr.people.findByUsername',\n\t\t\t\t\t\t'format': 'json',\n\t\t\t\t\t\t'nojsoncallback': 1\n\t\t\t\t\t\t})\n\tf = urlopen(FLICKR_ENDPOINT % params)\n\tflickr_struct = f.read()\n\t## necessary to strip off \"jsonFlickrApi()\" which surrounds retval\n\tresponse_json = json.loads(flickr_struct)\n\tnsid = response_json.get('user').get('nsid')\n\treturn nsid\n\ndef photoUrlRequestKey(photoset_id):\n\treturn 'photos_cache_%s' % photoset_id\n\t\ndef fetchPhotoset(photoset_id, url):\n\tparams = urlencode({\n\t\t\t\t\t\t'api_key': API_KEY,\n\t\t\t\t\t\t'method': 'flickr.photosets.getPhotos',\n\t\t\t\t\t\t'photoset_id': photoset_id,\n\t\t\t\t\t\t'format': 'json',\n\t\t\t\t\t\t'nojsoncallback': 1\n\t\t\t\t\t\t})\t\t\t\t\t\t\n\tf = urlopen(FLICKR_ENDPOINT % params)\n\tflickr_struct = f.read()\n\tflickr_json = json.loads(flickr_struct)\n\tphoto_list = flickr_json['photoset']['photo']\n\tresponse = []\n\tfor photo in photo_list:\n\t\tfarm = photo.get('farm')\n\t\tserver = photo.get('server')\n\t\tphoto_id = photo.get('id')\n\t\tsecret = photo.get('secret')\n\t\tresponse.append(url % (farm, server, photo_id, secret))\n\tkey = photoUrlRequestKey(photoset_id)\n\tcache.set(key, response, PHOTOS_CACHE_TIMEOUT)\n\treturn response\n\ndef getPhotoset(photoset_id, url):\n\tkey = photoUrlRequestKey(photoset_id)\n\tphotos = cache.get(key)\n\tif photos is not None:\n\t\treturn photos\n\treturn fetchPhotoset(photoset_id, url)\n\ndef getHomepagePhotos():\n\treturn getPhotoset(HOMEPAGE_PHOTOSET_ID, FLICKR_STATIC_URL)\n\t\ndef getPhotosPagePhotos():\n\treturn getPhotoset(PHOTOSPAGE_PHOTOSET_ID, FLICKR_STATIC_URL_SMALL)\n\n","sub_path":"colonial/flickr_client.py","file_name":"flickr_client.py","file_ext":"py","file_size_in_byte":2338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"618660102","text":"from django.http import HttpResponse\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom django.contrib.auth.decorators import login_required\nfrom .models import Filter\nfrom .forms import FilterForm\nfrom django.contrib import messages\nfrom django.db import IntegrityError\n\n\n@login_required\ndef index(request):\n filters = Filter.objects.all()\n context = {'filters': filters}\n return render(request, 'filters/index.html', context)\n\n@login_required\ndef registro(request):\n form = FilterForm(request.POST or None)\n if form.is_valid():\n form.save()\n messages.success(request,\"Registrado com sucesso!\")\n return redirect(\"filter:index\")\n context = {'form': form}\n return render(request, 'filters/form.html', context)\n\n@login_required\ndef editar_registro(request,id):\n filtro = get_object_or_404(Filter,id=id)\n form = FilterForm(request.POST or None, instance=filtro)\n if form.is_valid():\n form.save()\n messages.success(request,\"Editado com sucesso!\")\n return redirect(\"filter:index\")\n else:\n form = FilterForm(instance=filtro)\n context = {'form': form}\n return render(request, 'filters/form.html', context)\n\n@login_required\ndef deletar_registro(request,id):\n filtro = get_object_or_404(Filter,id=id)\n if filtro:\n filtro.delete()\n messages.success(request,\"Deletado com sucesso!\")\n return redirect(\"filter:index\")\n\n@login_required\ndef inativar_registro(request,id):\n filtro = get_object_or_404(Filter,id=id)\n if filtro:\n filtro.status ='0'\n filtro.save()\n messages.success(request,\"Desativado com sucesso!\")\n return redirect(\"filter:index\")\n\n@login_required\ndef ativar_registro(request,id):\n filtro = get_object_or_404(Filter,id=id)\n if filtro:\n filtro.status = '1'\n filtro.save()\n messages.success(request,\"Ativado com sucesso!\")\n return redirect(\"filter:index\")","sub_path":"central/filters/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"105034232","text":"import numpy as np\r\nfrom scipy.stats import multivariate_normal\r\nfrom scipy.optimize import minimize\r\n\r\n\r\ndef t(x, tau, mu1, sigma1, mu2, sigma2):\r\n x = np.asarray(x)\r\n t_1 = tau / np.sqrt(2 * np.pi * sigma1) * np.exp(-0.5 * (x - mu1) ** 2 / sigma1)\r\n t_2 = (1 - tau) / np.sqrt(2 * np.pi * sigma2) * np.exp(-0.5 * (x - mu2) ** 2 / sigma2)\r\n return np.vstack((t_1 / (t_1 + t_2), t_2 / (t_1 + t_2)))\r\n\r\n\r\ndef theta(x, old):\r\n t_1, t_2 = t(x, *old)\r\n tau = np.sum(t_1) / (np.sum(t_1 + t_2))\r\n mu1 = np.sum(t_1 * x) / (tau*np.sum(t_1 + t_2))\r\n mu2 = np.sum(t_2 * x) / ((1-tau)*np.sum(t_2 + t_1))\r\n sigma1 = np.sum(t_1 * (x - mu1) ** 2) / (tau*np.sum(t_1 + t_2))\r\n sigma2 = np.sum(t_2 * (x - mu2) ** 2) / ((1-tau)*np.sum(t_1 + t_2))\r\n return tau, mu1, sigma1, mu2, sigma2\r\n\r\n\r\ndef em_double_gauss(x, tau, mu1, sigma1, mu2, sigma2, rtol=1e-3):\r\n th = np.array((tau, mu1, sigma1, mu2, sigma2))\r\n while True:\r\n th = np.array(theta(x, th))\r\n if np.linalg.norm(np.array(theta(x, th)) - th)/np.linalg.norm(th) < rtol:\r\n break\r\n return th[0], th[1], np.sqrt(th[2]), th[3], np.sqrt(th[4])\r\n\r\n\r\ndef regressLL(x, params):\r\n N1 = params[0] / np.sqrt(2 * np.pi * params[2]) * np.exp(-0.5 * (x - params[1]) ** 2 / (params[2]))\r\n N2 = (1 - params[0]) / np.sqrt(2 * np.pi * params[4]) * np.exp(-0.5 * (x - params[3]) ** 2 / (params[4]))\r\n logLike = -np.sum(np.log(N1+N2))\r\n return logLike\r\n\r\n\r\ndef max_likelihood(x, tau, mu1, sigma1, mu2, sigma2, rtol=1e-3):\r\n x = np.asarray(x)\r\n initParams = [tau, mu1, sigma1, mu2, sigma2]\r\n results = minimize(fun=lambda z: regressLL(x, z), x0=initParams, method='nelder-mead', tol=rtol)\r\n return results.x[0], results.x[1], np.sqrt(results.x[2]), results.x[3], np.sqrt(results.x[4])\r\n\r\n\r\ndef e(x, tau1, mu1, sigma1, tau2, mu2, sigma2):\r\n x = np.asarray(x)\r\n t_1 = tau1 * multivariate_normal.pdf(x, mean=mu1, cov=sigma1, allow_singular=True)\r\n t_2 = tau2 * multivariate_normal.pdf(x, mean=mu2, cov=sigma2, allow_singular=True)\r\n t_3 = np.ones_like(t_2)*(1-tau1-tau2) * uni\r\n return np.vstack((t_1 / (t_1 + t_2 + t_3), t_2 / (t_1 + t_2 + t_3), t_3/(t_1 + t_2 + t_3)))\r\n\r\n\r\ndef m(x, old):\r\n t_1, t_2, t_3 = e(x, *old)\r\n tau1 = np.sum(t_1) / (np.sum(t_1 + t_2 + t_3))\r\n tau2 = np.sum(t_2) / (np.sum(t_1 + t_2 + t_3))\r\n mu1 = t_1 @ x / (tau1*np.sum(t_1+t_2 + t_3))\r\n mu2 = t_2 @ x / (tau2*np.sum(t_1 + t_2 + t_3))\r\n sigma1 = t_1 @ (x - mu1) ** 2 / (tau1*np.sum(t_1 + t_2 + t_3))\r\n sigma2 = t_2 @ (x - mu2) ** 2 / (tau2*np.sum(t_1 + t_2 + t_3))\r\n return tau1, mu1, sigma1, tau2, mu2, sigma2\r\n\r\n\r\ndef em_double_cluster(x, uniform_dens, tau1, mu1, sigma1, tau2, mu2, sigma2, rtol=1e-5):\r\n global uni\r\n uni = uniform_dens\r\n th = np.array((tau1, mu1, sigma1, tau2, mu2, sigma2))\r\n while True:\r\n th = np.array(m(x, th))\r\n if np.linalg.norm(np.array(m(x, th)).any() - th.any())/np.linalg.norm(th.any()) < rtol:\r\n break\r\n return th[0], th[1], np.sqrt(th[2]), th[3], th[4], np.sqrt(th[5])\r\n","sub_path":"mixfit.py","file_name":"mixfit.py","file_ext":"py","file_size_in_byte":3064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"44775596","text":"from flask import Flask, request, flash, url_for, redirect, render_template\nfrom flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy import text\nimport psycopg2\nfrom sqlalchemy import or_ , and_\n\napp = Flask(__name__)\n#app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://teste:teste@localhost/mod_eventos'\napp.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://hwfipjeyhnxxem:9da506ef9654ed04c2e32ba09c2313043d12b43d7a08654d60bfb425a12bb361@ec2-50-19-114-27.compute-1.amazonaws.com:5432/d1lf6f6gltbjpt?sslmode=require'\ndb = SQLAlchemy(app)\n\nclass Modulo_Eventos(db.Model):\n id = db.Column('evento_id', db.Integer, primary_key=True)\n codigo_evento= db.Column(db.String(500))\n nome_evento = db.Column(db.String(500))\n data_ = db.Column(db.String(30))\n local_ = db.Column(db.String(500))\n estado_ = db.Column(db.String(500))\n cidade_ = db.Column(db.String(500))\n rua_ = db.Column(db.String(500))\n cep_ = db.Column(db.String(500))\n site_ = db.Column(db.String(500))\n palestrante_ = db.Column(db.String(500))\n assunto_ = db.Column(db.String(500))\n telefone_ = db.Column(db.String(500))\n email_ = db.Column(db.String(120), unique=True)\n\n def __init__(self,codigo_evento, nome_evento, data_, local_, estado_, cidade_, rua_, cep_, site_, palestrante_,\n assunto_, telefone_, email_):\n self.codigo_evento=codigo_evento\n self.nome_evento = nome_evento\n self.data_ = data_\n self.local_ = local_\n self.estado_ = estado_\n self.cidade_ = cidade_\n self.rua_ = rua_\n self.cep_ = cep_\n self.site_ = site_\n self.palestrante_ = palestrante_\n self.assunto_ = assunto_\n self.telefone_ = telefone_\n self.email_ = email_\n\n@app.route(\"/\")\ndef pinicial():\n return render_template(\"pinicial.html\")\n\n@app.route(\"/cadastro\")\ndef cadastro():\n return render_template(\"cadastro.html\")\n\n@app.route(\"/busca\", methods=['POST', 'GET'])\ndef busca():\n if request.method == 'POST':\n codigo_evento=request.form['codigo_eve']\n nome_evento = request.form['nome_eve']\n data = request.form['data_eve']\n local = request.form['local_eve']\n site = request.form['site_eve']\n palestrante = request.form['responsavel_eve']\n assunto = request.form['assunto_eve']\n telefone = request.form['telefone_eve']\n email = request.form[\"email_name\"]\n if nome_evento == \"\":\n nome_evento=\"¨\"\n if assunto == \"\":\n assunto=\"¨\"\n if db.session.query(Modulo_Eventos).filter(or_(Modulo_Eventos.email_ == email , Modulo_Eventos.codigo_evento == codigo_evento , Modulo_Eventos.data_ == data, Modulo_Eventos.local_ == local, Modulo_Eventos.site_ == site, Modulo_Eventos.palestrante_ == palestrante,\n Modulo_Eventos.assunto_.ilike(\"%\"+assunto+\"%\"), Modulo_Eventos.telefone_ == telefone, Modulo_Eventos.nome_evento.ilike(\"%\"+nome_evento+\"%\"))).count() > 0:\n busca= db.session.query(Modulo_Eventos).filter(or_(Modulo_Eventos.email_ == email , Modulo_Eventos.codigo_evento == codigo_evento , Modulo_Eventos.data_ == data, Modulo_Eventos.local_ == local, Modulo_Eventos.site_ == site, Modulo_Eventos.palestrante_ == palestrante,\n Modulo_Eventos.assunto_.ilike(\"%\"+assunto+\"%\"), Modulo_Eventos.telefone_ == telefone, Modulo_Eventos.nome_evento.ilike(\"%\"+nome_evento+\"%\")))\n return render_template('retorno.html' , Modulo_Eventos=busca.all())\n else:\n return render_template('busca.html' , text='Dados não localizados!')\n return render_template('busca.html' )\n\n@app.route(\"/successo\", methods=['POST', 'GET'])\ndef successo():\n if request.method == 'POST':\n codigo_evento=request.form['codigo_eve']\n nome_evento = request.form['nome_eve']\n data = request.form['data_eve']\n local = request.form['local_eve']\n estado = request.form['estado_eve']\n cidade = request.form['cidade_eve']\n rua = request.form['rua_eve']\n cep = request.form['cep_eve']\n site = request.form['site_eve']\n palestrante = request.form['responsavel_eve']\n assunto = request.form['assunto_eve']\n telefone = request.form['telefone_eve']\n email = request.form[\"email_name\"]\n if db.session.query(Modulo_Eventos).filter(Modulo_Eventos.email_ == email).count() == 0:\n data = Modulo_Eventos(codigo_evento,nome_evento, data, local, estado, cidade, rua, cep, site, palestrante, assunto,\n telefone, email)\n db.session.add(data)\n db.session.commit()\n return render_template(\"sucesso.html\")\n return render_template('cadastro.html',\n text='Já localizamos esse endereço de e-mail. Verifique se o evento já foi cadastrado!')\n\n@app.route('/lista')\ndef lita_all():\n return render_template('lista.html', Modulo_Eventos=Modulo_Eventos.query.all())\n\n@app.route('/alterar', methods=['POST', 'GET'])\ndef alterar():\n if request.method == 'POST':\n codigo_evento=request.form['codigo_eve']\n nome_evento = request.form['nome_eve']\n data = request.form['data_eve']\n local = request.form['local_eve']\n estado = request.form['estado_eve']\n cidade = request.form['cidade_eve']\n rua = request.form['rua_eve']\n cep = request.form['cep_eve']\n site = request.form['site_eve']\n palestrante = request.form['responsavel_eve']\n assunto = request.form['assunto_eve']\n telefone = request.form['telefone_eve']\n email = request.form[\"email_name\"]\n if db.session.query(Modulo_Eventos).filter(Modulo_Eventos.codigo_evento == codigo_evento).count() >0 :\n db.session.query(Modulo_Eventos).filter(Modulo_Eventos.codigo_evento == codigo_evento).delete()\n db.session.commit()\n data = Modulo_Eventos(codigo_evento,nome_evento, data, local, estado, cidade, rua, cep, site, palestrante, assunto,\n telefone, email)\n db.session.add(data)\n db.session.commit()\n return render_template('alterar.html' , text='Alteração realizada com sucesso!')\n else:\n return render_template('alterar.html' , text='Código não localizado! Nenhuma alteração executada!')\n\n return render_template('alterar.html')\n\n@app.route(\"/deleta\", methods=['POST', 'GET'])\ndef deleta():\n if request.method == 'POST':\n codigo_evento=request.form['codigo_eve']\n nome_evento = request.form['nome_eve']\n data = request.form['data_eve']\n email = request.form[\"email_name\"]\n if db.session.query(Modulo_Eventos).filter(and_(Modulo_Eventos.email_ == email , Modulo_Eventos.codigo_evento == codigo_evento , Modulo_Eventos.data_ == data, Modulo_Eventos.nome_evento==nome_evento)).count() > 0:\n db.session.query(Modulo_Eventos).filter(and_(Modulo_Eventos.email_ == email , Modulo_Eventos.codigo_evento == codigo_evento , Modulo_Eventos.data_ == data, Modulo_Eventos.nome_evento==nome_evento)).delete()\n db.session.commit()\n return render_template('deleta.html' , text='Evento excluído com sucesso!')\n else:\n return render_template('deleta.html' , text='Dados não localizados!')\n return render_template('deleta.html' )\n\nif __name__ == '__main__':\n app.debug = False\n app.run()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"295262536","text":"from pyspark import SparkConf, SparkContext\n\nconf = SparkConf().setMaster(\"local\").setAppName(\"My Most Popular Movie\")\nsc = SparkContext(conf=conf)\n\ndata = sc.textFile(\"file:///E:/Study/SparkCourse/ml-100k/u.data\")\n\nmostPopularMovie = data.map(lambda x: x.split()[1]).map(lambda x: (x,1)).reduceByKey(lambda x,y: x + y)\n\n\nmostPopularMovieSort = mostPopularMovie.map(lambda x : (x[1],x[0])).sortByKey().top(1)\n\nprint(mostPopularMovieSort)","sub_path":"my-most-popular-movie.py","file_name":"my-most-popular-movie.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"167542996","text":"\"\"\"\n\n Given, a string. Check if it is balanced.\n\n input => {[()]}\n output => True\n\n\"\"\"\n\n\ndef is_balanced(string):\n\n close_tags = [')', ']', '}']\n element = []\n\n for tag in string:\n if tag in close_tags and len(element) > 0:\n element.pop()\n else:\n element.append(tag)\n\n return True if len(element) == 0 else False\n","sub_path":"hackerrank/balanced_string/balanced_string.py","file_name":"balanced_string.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"452387998","text":"# Copyright 2013 Nebula Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n#\n\n\"\"\"OpenStackClient Plugin interface\"\"\"\n\nimport json\nimport logging\nimport uuid\nimport websocket\n\nfrom openstackclient.common import utils\n\nLOG = logging.getLogger(__name__)\n\nDEFAULT_TRIPLEOCLIENT_API_VERSION = '1'\n\n# Required by the OSC plugin interface\nAPI_NAME = 'tripleoclient'\nAPI_VERSION_OPTION = 'os_tripleoclient_api_version'\nAPI_VERSIONS = {\n '1': 'tripleoclient.plugin'\n}\n\n\ndef make_client(instance):\n return ClientWrapper(instance)\n\n\n# Required by the OSC plugin interface\ndef build_option_parser(parser):\n \"\"\"Hook to add global options\n\n Called from openstackclient.shell.OpenStackShell.__init__()\n after the builtin parser has been initialized. This is\n where a plugin can add global options such as an API version setting.\n\n :param argparse.ArgumentParser parser: The parser object that has been\n initialized by OpenStackShell.\n \"\"\"\n parser.add_argument(\n '--os-tripleoclient-api-version',\n metavar='',\n default=utils.env(\n 'OS_TRIPLEOCLIENT_API_VERSION',\n default=DEFAULT_TRIPLEOCLIENT_API_VERSION),\n help='TripleO Client API version, default=' +\n DEFAULT_TRIPLEOCLIENT_API_VERSION +\n ' (Env: OS_TRIPLEOCLIENT_API_VERSION)')\n return parser\n\n\nclass WebsocketClient(object):\n\n def __init__(self, instance, queue_name):\n self._project_id = None\n self._ws = None\n self._websocket_client_id = None\n self._queue_name = queue_name\n\n endpoint = instance.get_endpoint_for_service_type(\n 'messaging-websocket')\n token = instance.auth.get_token(instance.session)\n\n self._project_id = instance.auth_ref.project_id\n\n self._websocket_client_id = str(uuid.uuid4())\n\n LOG.debug('Instantiating messaging websocket client: %s', endpoint)\n self._ws = websocket.create_connection(endpoint)\n\n self.send('authenticate', extra_headers={'X-Auth-Token': token})\n\n # create and subscribe to a queue\n # NOTE: if the queue exists it will 204\n self.send('queue_create', {'queue_name': queue_name})\n self.send('subscription_create', {\n 'queue_name': queue_name,\n 'ttl': 10000\n })\n\n def cleanup(self):\n self.send('queue_delete', {'queue_name': self._queue_name})\n self._ws.close()\n\n def send(self, action, body=None, extra_headers=None):\n\n headers = {\n 'Client-ID': self._websocket_client_id,\n 'X-Project-ID': self._project_id\n }\n\n if extra_headers is not None:\n headers.update(extra_headers)\n\n msg = {'action': action, 'headers': headers}\n if body:\n msg['body'] = body\n self._ws.send(json.dumps(msg))\n data = self.recv()\n if data['headers']['status'] not in (200, 201, 204):\n raise RuntimeError(data)\n return data\n\n def recv(self):\n return json.loads(self._ws.recv())\n\n def wait_for_message(self, execution_id):\n \"\"\"Wait for a message for a mistral execution ID\n\n This blocks until a message is received on the provided queue name\n with the execution ID.\n\n TODO(d0ugal): Add a timeout/break for the case when a message is\n never arrives.\n \"\"\"\n while True:\n body = self.recv()['body']\n if body['payload']['execution']['id'] == execution_id:\n return body['payload']\n\n def __enter__(self):\n \"\"\"Return self to allow usage as a context manager\"\"\"\n return self\n\n def __exit__(self, *exc):\n \"\"\"Call cleanup when exiting the context manager\"\"\"\n self.cleanup()\n\n\nclass ClientWrapper(object):\n\n def __init__(self, instance):\n self._instance = instance\n\n def messaging_websocket(self, queue_name='tripleo'):\n \"\"\"Returns a websocket for the messaging service\"\"\"\n return WebsocketClient(self._instance, queue_name)\n","sub_path":"tripleoclient/plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":4584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"126139792","text":"from generator import constants_conversions as c\nfrom generator import random_handler as ran\nimport sympy as sym\nimport math\nimport random\n\n#import randomizer_2 as ran2\n\nx, y, z = sym.symbols('x y z', real = True)#generic variables\n\nclass boylestad_10_1:\n\tdef __init__(self,*args,**kwargs):\n\n\t\trc = c.resistance(ran.main(3.9e3))\n\t\tre = c.resistance(ran.main(3.3e3))\n\t\tvcc = c.voltage(ran.main(9))\n\t\tvee = c.voltage(ran.main(-9))\n\n\n\t\tself.question = f\"\"\"Determine the values of VC for a BJT differential amplifier with RC1 = RC2 = {rc.kohms:.4} ohms, common RE = {re.kohms:.4} kohms, VCC = {vcc.V:.4} V and VEE = {vee.V:.4} V.\"\"\"\n\n\t\tie = c.current(\n\t\t( - vee.V - 0.7) /\n\t\tre.ohms\n\t\t)\n\n\t\tic = c.current(ie.A / 2)\n\n\t\tvc = c.voltage( vcc.V - ic.A * rc.ohms )\n\n\t\tself.answer = f\"\"\"{vc.V:.4} V\"\"\"\n\t\t\nclass boylestad_10_2:\n\tdef __init__(self,*args,**kwargs):\n\n\n\t\tvcc = c.voltage(ran.main(9))\n\t\tvee = c.voltage(ran.main(-9))\n\t\tre = c.resistance(ran.main(43), 'kohms')\n\t\trc = c.resistance(ran.main(47), 'kohms')\n\t\tbeta = ran.main(75)\n\t\tri = c.resistance(ran.main(20), 'kohms')\n\t\tvi = c.voltage(ran.main(2), 'mV')\n\n\n\t\tself.question = f\"\"\"Calculate the single-ended output voltage Vo1 for a BJT differential amplifier setup with VCC = {vcc.V:.4} V, VEE = {vee.V:.4} V, RC1 = RC2 = {rc.kohms:.4} kohms, RE = {re.kohms:.4} kohms, BJT characteristics are ri = {ri.kohms:.4} kohms, and beta = {beta:.4}. The input voltage is {vi.mV:.4} mV.\"\"\"\n\n\t\tie = c.current(\n\t\t(- vee.V - 0.7) /\n\t\tre.ohms\n\t\t)\n\n\t\tic = c.current(ie.A / 2)\n\n\t\tvc = c.voltage( vcc.V - ic.A * rc.ohms )\n\n\t\tresmall = c.resistance( c.voltage(26, 'mV').V / ic.A )\n\n\t\tav = rc.ohms / (2 * resmall.ohms)\n\n\t\tvo = c.voltage( vi.V * av )\n\n\t\tself.answer = f\"\"\"{vo.V:.4} V\"\"\"\n\n\nclass boylestad_10_3:\n\tdef __init__(self,*args,**kwargs):\n\n\n\t\tvcc = c.voltage(ran.main(9))\n\t\tvee = c.voltage(ran.main(-9))\n\t\tre = c.resistance(ran.main(43), 'kohms')\n\t\trc = c.resistance(ran.main(47), 'kohms')\n\t\tbeta = ran.main(75)\n\t\tri = c.resistance(ran.main(20), 'kohms')\n\t\tvi = c.voltage(ran.main(2), 'mV')\n\n\n\t\tself.question = f\"\"\"Calculate the common-mode gain for a BJT differential amplifier setup with VCC = {vcc.V:.4} V, VEE = {vee.V:.4} V, RC1 = RC2 = {rc.kohms:.4} kohms, RE = {re.kohms:.4} kohms, BJT characteristics are ri = {ri.kohms:.4} kohms, and beta = {beta:.4}. The input voltage is {vi.mV:.4} mV.\"\"\"\n\n\t\tie = c.current(\n\t\t(- vee.V - 0.7) /\n\t\tre.ohms\n\t\t)\n\n\t\tic = c.current(ie.A / 2)\n\n\t\tvc = c.voltage( vcc.V - ic.A * rc.ohms )\n\n\t\tresmall = c.resistance( c.voltage(26, 'mV').V / ic.A )\n\n\t\tac = (\n\t\t(beta * rc.ohms) /\n\t\t(ri.ohms + 2*(beta + 1)*re.ohms)\n\t\t)\n\n\t\tself.answer = f\"\"\"{ac:.4}\"\"\"\n\nclass boylestad_10_4:\n\tdef __init__(self,*args,**kwargs):\n\n\t\tvdd = c.voltage(ran.main(9))\n\t\trc = c.resistance(ran.main(10), 'kohms')\n\t\tbeta1 = ran.main(75)\n\t\tri = c.resistance(ran.main(11), 'kohms')\n\t\tr1 = c.resistance(ran.main(1), 'kohms')\n\t\tr2 = c.resistance(ran.main(8.2), 'kohms')\n\t\tr3 = c.resistance(ran.main(5.1), 'kohms')\n\t\tvee = c.voltage(ran.main(-9))\n\t\tbeta2 = ran.main(75)\n\t\tro = c.resistance(ran.main(200), 'kohms')\n\n\t\tself.question = f\"\"\"Calculate the common-mode voltage gain of a differential amplifier with VDD = {vdd.V:.4} V, RC1 = RC2 = {rc.kohms:.4} kohms, uses identical Q1 and Q2, and the BJT characteristics are beta = {beta1:.4} and ri = {ri.kohms:.4} kohms. This differential amplifier uses a BJT constant current source as a emitter resistance the BJT uses a limiter resistor R1 = {r1.kohms:.4} kohms, a bleeder resistor of R2 = {r2.kohms:.4} kohms, and an emitter resistance of R3 = {r3.kohms:.4} kohms. The BJT Q3 used in the constant current source has the characteristics ro = {ro.kohms:.4} kohms, and beta = {beta2:.4}.\"\"\"\n\n\t\tac = (\n\t\t( beta1 * rc.ohms ) /\n\t\t( ri.ohms + 2*(beta1 + 1)*ro.ohms)\n\t\t)\n\n\t\tself.answer = f\"\"\"{ac:.4}\"\"\"\n\nclass boylestad_10_5:\n\tdef __init__(self,*args,**kwargs):\n\n\t\trf = c.resistance(ran.main(500), 'kohms')\n\t\tr1 = c.resistance(ran.main(100), 'kohms')\n\t\tv1 = c.voltage(ran.main(2))\n\n\t\tself.question = f\"\"\"An inverting amplifier opamp circuit has R1 = {r1.kohms:.4} kohms and RF = {rf.kohms:.4} kohms. What output voltage results for an input of V1 = {v1.V:.4} V?\"\"\"\n\n\t\tvo = c.voltage(\n\t\t(- rf.ohms * v1.V) /\n\t\t( r1.ohms )\n\t\t)\n\n\t\tself.answer = f\"\"\"{vo.V:.4} V\"\"\"\n\nclass boylestad_10_6:\n\tdef __init__(self,*args,**kwargs):\n\n\t\tv1 = c.voltage(ran.main(2))\n\t\trf = c.resistance(ran.main(500), 'kohms')\n\t\tr1 = c.resistance(ran.main(100), 'kohms')\n\n\t\tself.question = f\"\"\"Calculate the output voltage of a opamp noninverting amplifier for values V1 ={v1.V:.4} V, RF = {rf.kohms:.4} kohms, and R1 = {r1.kohms:.4} kohms.\"\"\"\n\n\t\tvo = c.voltage((1 + (rf.ohms / r1.ohms)) * v1.V)\n\n\t\tself.answer = f\"\"\"{vo.V:.4} V\"\"\"\n\nclass boylestad_10_7:\n\tdef __init__(self,*args,**kwargs):\n\n\t\ttemp = random.randint(0,1)\n\t\trf = c.resistance(ran.main(1000), 'kohms')\n\t\tif temp == 0:\n\t\t\tv1 = c.voltage(ran.main(1))\n\t\t\tv2 = c.voltage(ran.main(2))\n\t\t\tv3 = c.voltage(ran.main(3))\n\t\t\tr1 = c.resistance(ran.main(500), 'kohms')\n\t\t\tr2 = c.resistance(ran.main(1), 'Mohms')\n\t\t\tr3 = c.resistance(ran.main(1), 'Mohms')\n\n\t\tif temp == 1:\n\t\t\tv1 = c.voltage(ran.main(-2))\n\t\t\tv2 = c.voltage(ran.main(3))\n\t\t\tv3 = c.voltage(ran.main(1))\n\t\t\tr1 = c.resistance(ran.main(200), 'kohms')\n\t\t\tr2 = c.resistance(ran.main(500), 'kohms')\n\t\t\tr3 = c.resistance(ran.main(1), 'Mohms')\n\n\t\tself.question = f\"\"\"Calculate the output voltage of an opamp summing amplifier for the set of voltages and resistors: RF = {rf.Mohms:.4} Mohms, V1 = {v1.V:.4} V, V2 = {v2.V:.4} V, V3 = {v3.V:.4} V, R1 = {r1.kohms:.4} kohms, R2 = {r2.kohms:.4} kohms, R3 = {r3.kohms:.4} kohms.\"\"\"\n\n\t\tvo = c.voltage(- rf.ohms * ( v1.V / r1.ohms + v2.V / r2.ohms + v3.V / r3.ohms ))\n\n\t\tself.answer = f\"\"\"{vo.V:.4} V\"\"\"\n\nclass boylestad_10_8:\n\tdef __init__(self,*args,**kwargs):\n\n\t\tvio = c.voltage(ran.main(1.2), 'mV')\n\t\tr1 = c.resistance(ran.main(2), 'kohms')\n\t\trf = c.resistance(ran.main(150), 'kohms')\n\n\n\t\tself.question = f\"\"\"Calculate the output offset voltage of a noninverting opamp circuit utilizing an opamp with input offset voltage VIO = {vio.mV:.4} mV and external resistors RF = {rf.kohms:.4} kohms and R1 = {r1.kohms:.4} kohms.\"\"\"\n\n\t\tvoo = c.voltage(\n\t\tvio.V * (1 + rf.ohms / r1.ohms)\n\t\t)\n\n\t\tself.answer = f\"\"\"{voo.mV:.4} mV\"\"\"\n\nclass boylestad_10_9:\n\tdef __init__(self,*args,**kwargs):\n\n\n\t\tiio = c.current(ran.main(100), 'nA')\n\t\tr1 = c.resistance(ran.main(2), 'kohms')\n\t\trf = c.resistance(ran.main(150), 'kohms')\n\n\t\tself.question = f\"\"\"Calculate the offset voltage of a noninverting opamp circuit utilizing an opamp with input offset current IIO = {iio.nA:.4} nA. The external resistors have values RF = {rf.kohms:.4} kohms and R1 = {r1.kohms:.4} kohms.\"\"\"\n\n\t\tvo = c.voltage(iio.A * rf.ohms)\n\n\t\tself.answer = f\"\"\"{vo.mV:.4} mV\"\"\"\n\nclass boylestad_10_10:\n\tdef __init__(self,*args,**kwargs):\n\n\t\trf = c.resistance(ran.main(500), 'kohms')\n\t\tr1 = c.resistance(ran.main(5), 'kohms')\n\t\tvio = c.voltage(ran.main(4), 'mV')\n\t\tiio = c.current(ran.main(150), 'nA')\n\n\t\tself.question = f\"\"\"Calculate the total offset voltage an inverting opamp configuration with RF = {rf.kohms:.4} kohms and R1 = {r1.kohms:.4} kohms, and a compensating resistor RC = {r1.kohms:.4} kohms for an oapmp with specified values of input offset voltage = {vio.mV:.4} mV and input offset current IIO = {iio.nA:.4} nA.\"\"\"\n\n\t\tvo = c.voltage(\n\t\tvio.V * (1 + rf.ohms/r1.ohms) +\n\t\tiio.A * rf.ohms\n\t\t)\n\n\t\tself.answer = f\"\"\"{vo.mV:.4} mV\"\"\"\n\nclass boylestad_10_11:\n\tdef __init__(self,*args,**kwargs):\n\n\t\tiio = c.current(ran.main(5), 'nA')\n\t\tiib = c.current(ran.main(30), 'nA')\n\n\t\tself.question = f\"\"\"Calculate the input bias currents at each input of an opamp having specified values of IIO = {iio.nA:.4} nA and IIB = {iib.nA:.4} nA.\"\"\"\n\n\t\tiibplus = c.current(iib.A + iio.A/2)\n\t\tiibminus = c.current(iib.A - iio.A/2)\n\n\t\tself.answer = f\"\"\"{iibplus.nA:.4} nA, {iibminus.nA:.4} nA\"\"\"\n\nclass boylestad_10_12:\n\tdef __init__(self,*args,**kwargs):\n\n\t\tbandwidth = c.frequency(ran.main(1), 'MHz')\n\t\tavd = c.voltage(ran.main(200), 'V')\n\t\tavref = c.voltage(1, 'mV')\n\n\t\tself.question = f\"\"\"Determine the cutoff frequency of an opamp having specified values B = {bandwidth.MHz:.4} MHz and Avd = {avd.V/avref.V:.4} V/mV.\"\"\"\n\n\t\tfc = c.frequency(bandwidth.Hz / avd.V)\n\n\t\tself.answer = f\"\"\"{fc.Hz:.4} Hz\"\"\"\n\nclass boylestad_10_13:\n\tdef __init__(self,*args,**kwargs):\n\n\t\tsrref = c.time(1,'us')\n\t\tsr = c.voltage(ran.main(2))\n\t\tvi = c.voltage(ran.main(0.5))\n\t\tti = c.time(ran.main(10), 'us')\n\n\t\tself.question = f\"\"\"For an opamp having a slew rate of SR = {sr.V/srref.us:.4} V/us, what is the minimum closed-loop voltage gain that can be used when the input signal varies by {vi.V:.4}V in {ti.us:.4} us?\"\"\"\n\n\t\tacl = (\n\t\t(sr.V / srref.s) /\n\t\t(vi.V / ti.s)\n\t\t)\n\n\t\tself.answer = f\"\"\"{acl:.4}\"\"\"\n\n\nclass boylestad_10_14:\n\tdef __init__(self,*args,**kwargs):\n\n\t\tvi = c.voltage(ran.main(0.02))\n\t\tomega = c.angularVelocity(ran.main(300e3), 'radpers')\n\t\tr1 = c.resistance(ran.main(10), 'kohms')\n\t\trf = c.resistance(ran.main(240), 'kohms')\n\t\tsrref = c.time(1, 'us')\n\t\tsr = c.voltage(random.randint(1,5))\n\n\t\tself.question = f\"\"\"For a {vi.V:.4} V, omega = {omega.radpers:.4} rad/s signal as an input to an inverting opamp with R1 = {r1.kohms:.4} kohms and RF = {rf.kohms:.4} kohms. The opamp slew rate is SR = {sr.V:.4} V/us.\"\"\"\n\n\t\tacl = rf.ohms / r1.ohms\n\n\t\tvo = c.voltage( acl * vi.V)\n\n\t\tomegaout = c.angularVelocity((sr.V * 1e6) / (vo.V))\n\n\t\tself.answer = f\"\"\"{omegaout.radpers:.4} rad/s\"\"\"\n\nclass boylestad_10_15:\n\tdef __init__(self,*args,**kwargs):\n\n\t\tsupply = c.voltage(ran.main(12))\n\t\tpower = c.power(ran.main(500), 'mW')\n\n\n\t\tself.question = f\"\"\"Determine the current draw from a dual power supply of +/- {supply.V:.4}V if the IC dissipates {power.mW:.4} mW.\"\"\"\n\n\t\tcurrent = c.current((power.W / (2 * supply.V)))\n\n\t\tself.answer = f\"\"\"{current.mA:.4} mA\"\"\"\n\nclass boylestad_10_17:\n\tdef __init__(self,*args,**kwargs):\n\n\t\tvid = c.voltage(ran.main(0.5), 'mV')\n\t\tvod = c.voltage(ran.main(8))\n\t\tvic = c.voltage(ran.main(1), 'mV')\n\t\tvoc = c.voltage(ran.main(12), 'mV')\n\n\n\t\tself.question = f\"\"\"Two input signals, both {vid.mV:.4} mV out of phase are directly applied to the inverting and non-inverting inputs of an opamp and the resulting output signal is of magnitude {vod.V:.4} V. Then the input signals are changed to {vic.mV:.4} mV in phase and are still directly applied to the inverting and non-inverting inputs and the resulting output signal is of magnitude {voc.mV:.4} mV. Calculate the CMRR in this case.\"\"\"\n\n\t\tad = vod.V / vid.V\n\t\tac = voc.V / vic.V\n\t\tCMRR = ad/ac\n\t\tCMRR_log = 20*math.log(CMRR, 10)\n\n\t\tself.answer = f\"\"\"{CMRR:.4} or {CMRR_log:.4} dB\"\"\"\n\nclass boylestad_10_22:\n\tdef __init__(self,*args,**kwargs):\n\n\t\tvi1 = c.voltage(ran.main(150), 'uV')\n\t\tvi2 = c.voltage(ran.main(140), 'uV')\n\t\tad = ran.main(4000)\n\n\t\ttemp = random.randint(0,1)\n\t\tif temp == 0:\n\t\t\tCMRR = ran.main(100)\n\t\tif temp == 1:\n\t\t\tCMRR = ran.main(10e5)\n\n\n\t\tself.question = f\"\"\"Determine the output voltage of an opmap for input voltages Vi1 = {vi1.uV:.4} uV and Vi2 = {vi2.uV:.4} uV. THe amplifier has a differential gain of Ad = {ad:.4} and the value of CMRR is {CMRR:.4}.\"\"\"\n\n\t\tvd = c.voltage(vi1.V - vi2.V)\n\t\tvc = c.voltage((vi1.V + vi2.V) / 2)\n\t\tvo = c.voltage( ad * vd.V * ( 1 + (1/CMRR)*(vc.V / vd.V)))\n\n\t\tself.answer = f\"\"\"{vo.V:.4} V\"\"\"\n\nclass boylestad_11_1:\n\tdef __init__(self,*args,**kwargs):\n\n\t\tvi = c.voltage(ran.main(2.5), 'mV')\n\t\tr1 = c.resistance(ran.main(2), 'kohms')\n\t\trf = c.resistance(ran.main(200), 'kohms')\n\n\t\tself.question = f\"\"\"Determine the output voltage of an inverting opamp amplifier with a sinusoidal input of {vi.mV:.4} mV, R1 = {r1.kohms:.4} kohms, and RF = {rf.kohms:.4} kohms.\"\"\"\n\n\t\tav = - rf.ohms/r1.ohms\n\n\t\tvo = c.voltage(av * vi.V)\n\n\t\tself.answer = f\"\"\"{vo.V:.4} V\"\"\"\n\nclass boylestad_11_2:\n\tdef __init__(self,*args,**kwargs):\n\n\t\tvi = c.voltage(ran.main(120), 'uV')\n\t\trf = c.resistance(ran.main(240), 'kohms')\n\t\tr1 = c.resistance(ran.main(2.4), 'kohms')\n\n\t\tself.question = f\"\"\"Calculate the output voltage from the circuit for a non-inverting amplifier with a sinusoidal input of {vi.uV:.4} uV, a feedback resistor of {rf.kohms:.4} kohms and an input resistor of {r1.kohms:.4} kohms.\"\"\"\n\n\t\tav = 1 + rf.ohms/r1.ohms\n\t\tvo = c.voltage( av * vi.V)\n\n\t\tself.answer = f\"\"\"{vo.V:.4} V\"\"\"\n\nclass boylestad_11_3:\n\tdef __init__(self,*args,**kwargs):\n\n\t\ttemp = random.randint(0,1)\n\t\tif temp == 0:\n\t\t\tvi = c.voltage(ran.main(80), 'uV')\n\t\t\trf = c.resistance(ran.main(470), 'kohms')\n\t\t\tr1 = c.resistance(ran.main(4.3), 'kohms')\n\t\t\tr2 = c.resistance(ran.main(33), 'kohms')\n\t\t\tr3 = c.resistance(ran.main(33), 'kohms')\n\t\tif temp == 1:\n\t\t\tvi = c.voltage(ran.main(150), 'uV')\n\t\t\trf = c.resistance(ran.main(270), 'kohms')\n\t\t\tr1 = c.resistance(ran.main(30), 'kohms')\n\t\t\tr2 = c.resistance(ran.main(15), 'kohms')\n\t\t\tr3 = c.resistance(ran.main(10), 'kohms')\n\n\t\tself.question = f\"\"\"A multiple-stage operational amplifier circuit has a non-inverting amplifier as a first stage, and the next two amplifiers as inverting types. An input signal of {vi.uV:.4} uV is applied. All the stages use a feedback resistor of RF = {rf.kohms:.4} kohms, R1st = {r1.kohms:.4}, R2nd = {r2.kohms:.4}, R3rd = {r3.kohms:.4} kohms. Calculate the output voltage.\"\"\"\n\n\t\ta1 = 1 + rf.ohms/r1.ohms\n\t\ta2 = - rf.ohms/r2.ohms\n\t\ta3 = - rf.ohms/r3.ohms\n\n\t\tvo = c.voltage( a1 * a2 * a3 * vi.V)\n\n\t\tself.answer = f\"\"\"{vo.V:.4} V\"\"\"\n\n\nclass boylestad_11_6:\n\tdef __init__(self,*args,**kwargs):\n\n\t\trf = c.resistance(ran.main(300), 'kohms')\n\t\tr1 = c.resistance(ran.main(33), 'kohms')\n\t\tr2 = c.resistance(ran.main(10), 'kohms')\n\t\tvi1 = c.voltage(ran.main(50), 'mV')\n\t\tvi2 = c.voltage(ran.main(10), 'mV')\n\t\tomega1 = c.angularVelocity(ran.main(3000, 'int'), 'radpers')\n\t\tomega2 = c.angularVelocity(ran.main(1000, 'int'), 'radpers')\n\n\t\tself.question = f\"\"\"Calculate the output voltage of a operational amplifier summing circuit with a {rf.kohms:.4} kohms feedback resistor, R1 = {r1.kohms:.4} kohms and R2 = {r2.kohms:.4} kohms. The inputs are V1 = {vi1.mV:.4} mV sin ({omega1.radpers:.4}t) and V2 = {vi2.mV:.4} mV sin ({omega2.radpers:.4}t ).\"\"\"\n\n\t\tav1 = rf.ohms/r1.ohms\n\t\tav2 = rf.ohms/r2.ohms\n\t\tvo1 = c.voltage(vi1.V * av1)\n\t\tvo2 = c.voltage(vi2.V * av2)\n\n\t\tself.answer = f\"\"\" - [{vo1.V:.4} sin ({omega1.radpers:.4} t) + {vo2.V:.4} sin ({omega2.radpers:.4} t)] \"\"\"\n\n\nclass boylestad_11_7:\n\tdef __init__(self,*args,**kwargs):\n\n\t\trf = c.resistance(ran.main(1), 'Mohms')\n\t\tr1 = c.resistance(ran.main(100), 'kohms')\n\t\tr2 = c.resistance(ran.main(50), 'kohms')\n\t\tr3 = c.resistance(ran.main(500), 'kohms')\n\t\tvi1 = c.voltage(ran.main(10), 'mV')\n\t\tvi2 = c.voltage(ran.main(5), 'mV')\n\n\t\tself.question = f\"\"\"Determine the output voltage for the circuit with components RF = {rf.kohms:.4} kohms, R1 = {r1.kohms:.4} kohms, R2 = {r2.kohms:.4} kohms and R3 = {r3.kohms:.4} kohms. The input voltages are V1 = {vi1.mV:.4} mV sine wave and V2 = {vi2.mV:.4} mV sine wave.https://lesliecaminadecom.files.wordpress.com/2019/06/3d9hy67csq0037yl2x55.png\"\"\"\n\n\t\tvo = c.voltage(\n\t\t- (rf.ohms/r2.ohms)*vi2.V + ((rf.ohms**2)/(r3.ohms*r1.ohms))*vi1.V\n\t\t)\n\n\t\tself.answer = f\"\"\"{vo.mV:.4} mV\"\"\"\n\nclass boylestad_11_8:\n\tdef __init__(self,*args,**kwargs):\n\n\t\tr1 = c.resistance(ran.main(100), 'kohms')\n\t\tr2 = c.resistance(ran.main(100), 'kohms')\n\t\tr3 = c.resistance(ran.main(20), 'kohms')\n\t\tr4 = c.resistance(ran.main(20), 'kohms')\n\t\tvi1 = c.voltage(ran.main(5), 'mV')\n\t\tvi2 = c.voltage(ran.main(10), 'mV')\n\n\t\tself.question = f\"\"\"Determine the output voltage for the circuit where R1 = {r1.kohms:.4} kohms, R2 = {r2.kohms:.4} kohms, R3 = {r3.kohms:.4} kohms, R4 = {r4.kohms:.4} kohms. V1 = {vi1.mV:.4} mV and V2 = {vi2.mV:.4} mV\n\t\thttps://lesliecaminadecom.files.wordpress.com/2019/06/udquqc14msx6k2n885w2.png\"\"\"\n\n\t\tvo = c.voltage(\n\t\t(r4.ohms / (r3.ohms + r4.ohms))*((r2.ohms + r1.ohms) / r2.ohms)*vi1.V -\n\t\t(r1.ohms/r2.ohms)*vi2.V\n\t\t)\n\n\t\tself.answer = f\"\"\"{vo.mV:.4} mV\"\"\"\n\n\nclass boylestad_11_10:\n\tdef __init__(self,*args,**kwargs):\n\t\ttemp = random.randint(0,1)\n\t\tif temp == 0:\n\t\t\tv1 = c.voltage(ran.main(8))\n\t\t\tr1 = c.resistance(ran.main(2), 'kohms')\n\t\t\trl = c.resistance(ran.main(4), 'kohms')\n\t\t\trc = c.resistance(ran.main(2), 'kohms')\n\n\t\t\tself.question = f\"\"\"Calculate IL for the circuit if V1 = {v1.V:.4} V, R1 = {r1.kohms:.4} kohms, RC = {rc.kohms:.4} kohms, and RL = {rl.kohms:.4} kohms. https://lesliecaminadecom.files.wordpress.com/2019/06/22o4e3vhc0kbvj5ir1v8.png\"\"\"\n\n\t\t\til = c.current(v1.V / r1.ohms)\n\n\t\t\tself.answer = f\"\"\"Load current IL = {il.mA:.4} mA\"\"\"\n\t\tif temp == 1:\n\t\t\tii = c.current(ran.main(10), 'mA')\n\t\t\tr1 = c.resistance(ran.main(2), 'kohms')\n\n\t\t\tself.question = f\"\"\"Calculate Vo for the circuit if Ii = {ii.mA:.4} mA and R1 = {r1.kohms:.4} kohms.https://lesliecaminadecom.files.wordpress.com/2019/06/lrdxv9z3wg4hmhmby2sa.png\"\"\"\n\n\t\t\tvo = c.voltage( - ii.A * r1.ohms)\n\n\t\t\tself.answer = f\"\"\"{vo.V:.4} V\"\"\"\n\nclass boylestad_11_11:\n\tdef __init__(self,*args,**kwargs):\n\n\t\trmain = c.resistance(ran.main(500), 'kohms')\n\t\trp = c.resistance(ran.main(500))\n\t\tvi1 = c.voltage(ran.main(10), 'mV')\n\t\tvi2 = c.voltage(ran.main(5), 'mV')\n\n\t\tself.question = f\"\"\"Calculate the output voltage for the instrumentation amplifier where R = {rmain.kohms:.4} kohms and Rp = {rp.ohms:.4} ohms. The input voltages are V1 = {vi1.mV:.4} mV while V2 = {vi2.mV:.4} mV.https://lesliecaminadecom.files.wordpress.com/2019/06/yg773cdlps895pl4tb89.png\"\"\"\n\n\t\tvo = c.voltage((1 + (2*rmain.ohms/rp.ohms)) * (vi1.V - vi2.V))\n\n\t\tself.answer = f\"\"\"{vo.mV:.4} mV\"\"\"\n\nclass boylestad_11_12:\n\tdef __init__(self,*args,**kwargs):\n\n\t\tr1 = c.resistance(ran.main(1.2), 'kohms')\n\t\tc1 = c.capacitance(ran.main(0.02), 'uF')\n\n\t\tself.question = f\"\"\"Calculate the cutoff frequency of a first-order low-pass filter for R1 = {r1.kohms:.4} kohms, and C1 = {c1.uF:.4} uF.\"\"\"\n\n\t\tfc = c.frequency(1 / (2*math.pi*r1.ohms*c1.F))\n\n\t\tself.answer = f\"\"\"Cutoff frequency = {fc.kHz:.4} kHz\"\"\"\n\nclass boylestad_11_13:\n\tdef __init__(self,*args,**kwargs):\n\n\t\tr1 = c.resistance(ran.main(2.1), 'kohms')\n\t\tc1 = c.capacitance(ran.main(0.05), 'uF')\n\t\trg = c.resistance(ran.main(10), 'kohms')\n\t\trf = c.resistance(ran.main(50), 'kohms')\n\n\n\t\tself.question = f\"\"\"Calculate the cutoff frequency of a second-order high-pass filter for R1 = R2 = {r1.kohms:.4} kohms and C1 = C2 = {c1.uF:.4} uF, RG = {rg.kohms:.4} kohms, and RF = {rf.kohms:.4} kohms.https://lesliecaminadecom.files.wordpress.com/2019/06/qtpcae4eyx2ire4q7zk3.png\"\"\"\n\n\t\tfc = c.frequency(1 / (2*math.pi*r1.ohms*c1.F))\n\n\t\tself.answer = f\"\"\"{fc.kHz:.4} kHz\"\"\"\n\nclass boylestad_11_14:\n\tdef __init__(self,*args,**kwargs):\n\n\t\tr1 = c.resistance(ran.main(10), 'kohms')\n\t\tc1 = c.capacitance(ran.main(0.1), 'uF')\n\t\tc2 = c.capacitance(ran.main(2), 'nF')\n\n\n\t\tself.question = f\"\"\"Calculate the cutoff frequencies of the bandpass filter circuit with R1 = R2 = {r1.kohms:.4} kohms, C1 = {c1.uF:.4} uF, and C2 = {c2.uF:.4} uF.https://lesliecaminadecom.files.wordpress.com/2019/06/7w08dlp8p1jq0rqw7t5o.png\"\"\"\n\n\t\tfcl = c.frequency(1 / (2*math.pi*r1.ohms*c1.F))\n\t\tfch = c.frequency(1 / (2*math.pi*r1.ohms*c2.F))\n\n\t\tself.answer = f\"\"\"{fcl.Hz:.4} Hz, {fch.kHz:.4} kHz\"\"\"\n","sub_path":"electronics/operational_amplifiers_engine.py","file_name":"operational_amplifiers_engine.py","file_ext":"py","file_size_in_byte":18998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"558362499","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nimport re\n\n\nimport asyncio\nfrom idataapi_transform import ProcessFactory, GetterConfig, WriterConfig\n\n\nasync def example():\n\n allStr = 'aa'\n xlsx_config = GetterConfig.RXLSXConfig('数据.xlsx')\n getter = ProcessFactory.create_getter(xlsx_config)\n async for items in getter:\n for item in items:\n if item['value'] is not None:\n # print(item)\n allStr += item['value']\n # print(allStr)\n # print(len(allStr))\n\n findStr = input('请输入要查找的内容:')\n\n index = -1\n\n name_dic = {}\n while True:\n index = allStr.find(findStr, index+1)\n if index == -1:\n break\n\n findRes = index+len(findStr)\n print(findRes, allStr[findRes])\n if allStr[findRes] in name_dic:\n name_dic[allStr[findRes]] +=1\n else:\n name_dic[allStr[findRes]] = 1\n\n\n print(name_dic)\n\nif __name__ == \"__main__\":\n loop = asyncio.get_event_loop()\n loop.run_until_complete(example())","sub_path":"other/imdb/strFind.py","file_name":"strFind.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"165242236","text":"#!/usr/bin/python\n# Author: Krishnendu Kayal\n# Email: krishnendu1985@gmail.com\n\n#Given an array of ints, return True if 6 appears as either the first or last element in the array. The array will be length 1 or more.\nprint(\"Given an array of ints, return True if 6 appears as either the first or last element in the array. The array will be length 1 or more.\")\n\na = []\nlist_data=int(input(\"How many data do you want for list\\t\"))\nfor i in range(list_data):\n input_data = int(input(\"Enter {} data\\t\".format(i+1)))\n a.append(input_data)\n\nl = len(a)\n\nif len(a)== 1 and a[0]==6:\n print(\"True\")\nelif a[0] == 6 or a[(l-1)] == 6:\n print(\"True\")\nelse:\n print(\"False\")","sub_path":"Lists/list_condition.py","file_name":"list_condition.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"372190863","text":"# coding: utf8\n\nimport re\nimport random\nimport json\nimport os\nimport sys\nimport requests\nimport six\nimport time\nfrom AdvancedHTMLParser import AdvancedHTMLParser\nfrom io import StringIO, BytesIO\n\nsys.path += [\"/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python\"]\n\nfrom PIL import Image\n\nfrom rest_framework.utils.urls import replace_query_param\n\nfrom django.core.files.uploadedfile import InMemoryUploadedFile\nfrom django.conf import settings\n\nfrom hashlib import sha1, md5\nfrom collections import OrderedDict\n\nfrom xml.etree import ElementTree\n\nfrom datetime import datetime, timedelta\nfrom time import time, mktime, strftime, localtime\n\n\nstring_types = (six.string_types, six.text_type, six.binary_type)\n\nRULE_DICT = {\n \"asc\": False,\n \"desc\": True\n}\n\n\ndef check_token(token):\n return re.match('^[A-Za-z0-9]{3,32}$', token)\n\n\ndef to_text(value, encoding=\"utf-8\"):\n if isinstance(value, six.text_type):\n return value\n if isinstance(value, six.binary_type):\n return value.decode(encoding)\n return six.text_type(value)\n\n\ndef to_binary(value, encoding=\"utf-8\"):\n if isinstance(value, six.binary_type):\n return value\n if isinstance(value, six.text_type):\n return value.encode(encoding)\n return six.binary_type(value)\n\n\ndef is_string(value):\n return isinstance(value, string_types)\n\n\ndef generate_token(length=''):\n if not length:\n length = random.randint(3, 32)\n length = int(length)\n assert 3 <= length <= 32\n token = []\n letters = 'abcdefghijklmnopqrstuvwxyz' \\\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' \\\n '0123456789'\n for _ in range(length):\n token.append(random.choice(letters))\n return ''.join(token)\n\n\ndef dict_parse_from_xml(xml_data):\n json = dict((child.tag, to_text(child.text))\n for child in ElementTree.fromstring(xml_data))\n return json\n\n\ndef dict_parse_to_xml(dict):\n xml = \"\"\n for key, val in dict.iteritems():\n xml += \"<{0}>{1}\".format(key, val)\n return xml\n\n\ndef datetime2time(d_time):\n if not d_time:\n return 0\n return int(mktime(d_time.timetuple()))\n\n\ndef timestamp2string(timestamp):\n if (not timestamp) or (not isinstance(timestamp, int)):\n return timestamp\n return strftime(\"%Y-%m-%d %H:%M:%S\", localtime(timestamp))\n\n\ndef datetime2string(d_time=None, _format=\"%Y-%m-%d %H:%M:%S\"):\n if not d_time:\n d_time = datetime.now()\n return d_time.strftime(_format)\n\ndef datetimenow():\n return datetime.now()\n\ndef strtimestampnow():\n return str(datetime.now().timestamp()).split('.')[0]\n\ndef string2datetime(string, _format=\"%Y-%m-%d %H:%M:%S\"):\n return datetime.strptime(string, _format)\n\n\ndef generator_code(length=6):\n letters = \"0123456789\"\n code = \"\".join(random.sample(letters, length))\n return code\n\n\ndef get_client_ip(request):\n x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')\n if x_forwarded_for:\n ip = x_forwarded_for.split(',')[0]\n else:\n ip = request.META.get('REMOTE_ADDR')\n return ip\n\n\ndef split_url_rtmp(url_rtmp):\n data = url_rtmp[7:].split('/')\n return data\n\n\ndef lookup_ip(ip):\n \"\"\"\n 根据ip得到地址信息\n \"\"\"\n url = \"http://ip.taobao.com/service/getIpInfo.php\"\n\n querystring = {\"ip\": ip}\n response = requests.request(\"GET\", url, params=querystring)\n\n return response.json()\n\ndef get_paginated_response(request, total, page_size, page, data_list):\n \"\"\"\n 分页\n \"\"\"\n total_page = total / page_size\n url = request.build_absolute_uri()\n next_url = None\n previous_url = None\n if total > page_size and page < total_page:\n next_url = replace_query_param(url, \"page\", page + 1)\n if page > 1:\n previous_url = replace_query_param(url, \"page\", page - 1)\n\n response = OrderedDict([\n ('count', total),\n ('next', next_url),\n ('previous', previous_url),\n ('results', data_list)\n ])\n return response\n\n\ndef random_cumulative_num(max_num=None):\n range_max_num = 30\n if max_num:\n range_max_num = max_num\n\n cumulative_num = random.randint(1, range_max_num)\n return cumulative_num\n\n\ndef get_thumbnail(orig, width=600, height=600):\n \"\"\"get the thumbnail of orig\n @return: InMemoryUploadedFile which can be assigned to ImageField\n \"\"\"\n quality = 95\n\n file_suffix = orig.name.split(\".\")[-1]\n filename = orig.name\n if file_suffix not in [\"jpg\", \"jpeg\"]:\n filename = \"%s.jpg\" % orig.name[:-(len(file_suffix)+1)]\n quality = 95\n\n im = Image.open(orig)\n try:\n im = im.convert(\"RGB\")\n except Exception as e:\n pass\n\n size = (width, height)\n\n thumb = im\n thumb.thumbnail(size, Image.ANTIALIAS)\n thumb_io = BytesIO()\n thumb.save(thumb_io, format=\"PNG\", quality=quality)\n # thumb_file = InMemoryUploadedFile(thumb_io, None, filename, 'image/jpeg',\n # thumb_io.len, None)\n bytes_values = thumb_io.getvalue()\n return bytes_values\n\n\ndef process_image_upload(orig, prefix_path, marke, width=600, height=600):\n \"\"\"\n 上传图片\n 1.需要压缩\n 2.上传压缩图与原图\n\n :origin: 原图文件\n :prefix_path: 存储oss前缀\n :marke: 文件记号\n return: thumb_file_path\n \"\"\"\n from management.aliyun import utils\n\n file_suffix = orig.name.split(\".\")[-1]\n\n thumbnail_image = get_thumbnail(orig)\n # 上传压缩图\n filename = utils.bytes_to_oss_with_orignal_file(marke, thumbnail_image, prefix_path, file_suffix)\n # 上传原图\n utils.uploads_original_to_oss(marke, orig, type_name=prefix_path, filename=filename)\n return filename\n\n\ndef url_encode(url):\n from urllib import parse\n encode_url = parse.urlencode({\"k\":url}).split(\"=\", 1)[1]\n return encode_url\n \n\ndef getHTMLParser(str_html):\n \"\"\"\n html字符转换成HTML对象\n \"\"\"\n parser = AdvancedHTMLParser()\n parser.parseStr(str_html)\n return parser\n\n\nWEEKDAY_DICT = {\n 0: \"周一\",\n 1: \"周二\",\n 2: \"周三\",\n 3: \"周四\",\n 4: \"周五\",\n 5: \"周六\",\n 6: \"周天\"\n}\n\ndef duration_to_time(dura):\n \"\"\"\n 观看时长数字转换为多少分多少秒的格式\n :param duration:\n :return:\n \"\"\"\n try:\n duration = float(dura)\n except Exception as e:\n return None\n\n if duration:\n duration_hour = int(duration / 60)\n duration = duration - float((duration_hour) * 60)\n\n if duration_hour:\n duration_hour = str(duration_hour) + \" 小时\"\n else:\n duration_hour = \"\"\n\n if int(duration):\n duration_min = str(int(duration)) + \"分\"\n else:\n duration_min = \"\"\n duration_sec = (duration - float(int(duration))) * 60\n duration_sec = round(duration_sec, 0)\n if int(duration_sec):\n duration_sec = str(int(duration_sec)) + \"秒\"\n else:\n duration_sec = \"\"\n duration_time= duration_hour + duration_min + duration_sec\n\n return duration_time\n else:\n\n return dura\n\n\n\n# @classmethod\ndef get_short_url( source_url=None):\n '''\n 根据原url 生成短连接\n '''\n try:\n if source_url:\n params_data = {\n \"url_long\":source_url,\n \"source\":\"3271760578\"\n }\n result = requests.get(settings.SINA_SHORT_URL_SENDER,params=params_data)\n if result.status_code == 200:\n return (result.json()[0].get(\"url_short\"))\n return None\n except Exception as ex:\n return None\n\n\ndef get_https_url(url):\n if not url.startswith(\"https\"):\n url = url.replace(\"http\", \"https\")\n return url\n\"\"\"\ndecimal serviceCharge = 0;\n//四舍五入(默认的Round方法使用的四舍六入五保留的算法,所以得改为AwayFromZero,且保留两位小数)\nserviceCharge = Math.Round(serviceCharge, 2, MidpointRounding.AwayFromZero);\n//只入不舍(默认计算保留到整数位,所以需要乘100)\nserviceCharge = (Math.Ceiling(serviceCharge * 100) / 100);\n//只舍不入(默认计算保留到整数位,所以需要乘100)\nserviceCharge = (Math.Floor(serviceCharge * 100) / 100);\n\"\"\"","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":8241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"450568612","text":"import nltk\nimport collections\nfrom nltk import word_tokenize\nfrom nltk.corpus import stopwords\nfrom nltk.stem import PorterStemmer\nfrom sklearn.cluster import KMeans\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nimport numpy as np\nfrom pptx import Presentation\nimport os\nimport pickle\n\ndef prcoss(tokens):\n count = nltk.defaultdict(int)\n for word in tokens:\n count[word]+=1\n return count\n\ndef cos_sim(a,b):\n dot_product=np.dot(a,b)\n norm_a=np.linalg.norm(a)\n norm_b=np.linalg.norm(b)\n return dot_product/(norm_a*norm_b)\n\ndef getSimilarity(dict1, dict2):\n all_words_list=[]\n for key in dict1:\n all_words_list.append(key)\n for key in dict2:\n all_words_list.append(key)\n all_words_list_size=len(all_words_list)\n \n v1=np.zeros(all_words_list_size, dtype=np.int)\n v2=np.zeros(all_words_list_size, dtype=np.int)\n i=0\n for (key) in all_words_list:\n v1[i]=dict1.get(key, 0)\n v2[i]=dict2.get(key, 0)\n i=i+1\n return cos_sim(v1, v2)\n\ndef word_tokenizer(text):\n #tokenizes and stems the text\n tokens = word_tokenize(text)\n stemmer = PorterStemmer()\n tokens = [stemmer.stem(t) for t in tokens if t not in stopwords.words('english')]\n return tokens\n\ndef getPPTDetails(searchItem):\n path='/home/peter/Documents/myproject/media'\n directory=[x for x in os.listdir(path) if x.endswith(\".pptx\")]\n ppt={}\n for pptx_filename in directory:\n prs = Presentation(path+'/'+pptx_filename)\n # text_runs will be populated with a list of strings,\n # one for each text run in presentation\n text_runs = []\n for slide in prs.slides:\n sh=''\n for shape in slide.shapes:\n if not shape.has_text_frame:\n continue\n for paragraph in shape.text_frame.paragraphs:\n for run in paragraph.runs:\n sh=sh+' '+run.text\n if sh:\n text_runs.append(sh.split('.'))\n ppt[pptx_filename]=text_runs\n result=[]\n for keys in ppt:\n p=[]\n for i in range(0, len(ppt[keys])):\n for j in range(0, len(ppt[keys][i])):\n if getSimilarity(prcoss(word_tokenizer(ppt[keys][i][j])),prcoss(word_tokenizer(searchItem)))>0.1:\n p.append([ppt[keys][i][j],i+1,j+1])\n if len(p):\n result.append([keys,p])\n return result\n\ndef ppttolist(file_name):\n path='media/'+file_name\n prs = Presentation(path)\n # text_runs will be populated with a list of strings,\n # one for each text run in presentation\n text_runs = []\n for slide in prs.slides:\n sh=''\n for shape in slide.shapes:\n if not shape.has_text_frame:\n continue\n for paragraph in shape.text_frame.paragraphs:\n for run in paragraph.runs:\n sh=sh+' '+run.text\n if sh:\n text_runs.append(sh.split('.'))\n fil='media/'+file_name.split('.')[0]+'.txt'\n with open(fil,'wb') as f:\n pickle.dump(text_runs,f)\n result=[]\n for i in range(0, len(text_runs)):\n p=[]\n for j in range(0, len(text_runs[i])):\n p.append(prcoss(word_tokenizer(text_runs[i][j])))\n if len(p):\n result.append(p)\n fil='media/'+file_name.split('.')[0]+'.pkl'\n with open(fil,'wb') as f:\n pickle.dump(result,f)\n\ndef cluster_sentences(sentences, nb_of_clusters=2):\n tfidf_vectorizer = TfidfVectorizer(tokenizer=word_tokenizer,\n stop_words=stopwords.words('english'),\n max_df=0.9,\n min_df=0.1,\n lowercase=True)\n #builds a tf-idf matrix for the sentences\n tfidf_matrix = tfidf_vectorizer.fit_transform(sentences)\n #print(tfidf_matrix)\n kmeans = KMeans(n_clusters=nb_of_clusters)\n kmeans.fit(tfidf_matrix)\n clusters = collections.defaultdict(list)\n for i, label in enumerate(kmeans.labels_):\n clusters[label].append(i)\n return dict(clusters)\n\ndef getPPTDetails1(searchItem):\n path='media/'\n directory=[x for x in os.listdir(path) if x.endswith(\".pkl\")]\n pkl={}\n for pkl_filename in directory:\n fil=path+pkl_filename\n with open(fil,'rb') as f:\n pkl[pkl_filename]=pickle.load(f)\n directory_txt=[x for x in os.listdir(path) if x.endswith(\".txt\")]\n ppt={}\n for txt_filename in directory_txt:\n fil=path+txt_filename\n with open(fil,'rb') as f:\n ppt[txt_filename]=pickle.load(f)\n result=[]\n for keys in pkl:\n key=keys.split('.')[0]+'.txt'\n p=[]\n for i in range(0, len(pkl[keys])):\n for j in range(0, len(pkl[keys][i])):\n k=getSimilarity(pkl[keys][i][j],prcoss(word_tokenizer(searchItem)))\n if k>0.1:\n p.append([ppt[key][i][j],i+1,round(k*100,2)])\n if len(p):\n result.append([keys.split('.')[0],p])\n return result\n\ndef getPPTtext():\n path='media/'\n directory=[x for x in os.listdir(path) if x.endswith(\".pptx\")]\n ppt=[[], [], []]\n for pptx_filename in directory:\n prs = Presentation(path+pptx_filename)\n # text_runs will be populated with a list of strings,\n # one for each text run in presentation\n text_runs = []\n j=1\n for slide in prs.slides:\n sh=''\n for shape in slide.shapes:\n if not shape.has_text_frame:\n continue\n for paragraph in shape.text_frame.paragraphs:\n for run in paragraph.runs:\n sh=sh+' '+run.text\n if sh:\n text_runs+=sh.strip().split('.')\n j+=1\n if text_runs:\n ppt[0]+=text_runs\n for i in range(0, len(text_runs)):\n ppt[1].append(pptx_filename)\n ppt[2]+=str(j)\n return ppt\n \ndef clust(searchItem):\n data=getPPTtext()\n sentences=data[0]\n cl=[]\n nclusters=10\n clusters = cluster_sentences(sentences, nclusters)\n for cluster in range(nclusters):\n #print(\"cluster \",cluster+1,\":\")\n for i,sentence in enumerate(clusters[cluster]):\n if getSimilarity(prcoss(word_tokenizer(sentences[sentence])), prcoss(word_tokenizer(searchItem))) > 0:\n for i,sentence in enumerate(clusters[cluster]):\n #print(\"\\tsentence \",i+1,\": \",sentences[sentence])\n cl.append([sentences[sentence],data[1][sentence],str(data[2][sentence])])\n break\n\n return cl","sub_path":"myapp/pro.py","file_name":"pro.py","file_ext":"py","file_size_in_byte":6614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"571709870","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\n\n\ndate = ['201501', '201502', '201503', '201504', '201505',\n '201506', '201507', '201508', \n '201509', '201510', '201511', '201512', \n '201601', '201602', '201603', '201604', \n '201605', '201606', '201607']\n\nprod_freq = {}\n\nfor i in date:\n df = pd.read_csv('D:/BudLab/Beer User Project/data samples/data_' + i + '.csv')\n #prod_freq[i] = df['prod_cd'].value_counts()\n df.drop(['cust_cd', 'sales_day_cd','sales_item_price'], axis = 1, inplace = True)\n df['sales_item_qty'] = df['sales_item_qty'].str.replace(',', '')\n df['sales_item_qty'] = df['sales_item_qty'].astype(float) \n df['sales_item_tot_amt'] = df['sales_item_tot_amt'].str.replace(',', '')\n df['sales_item_tot_amt'] = df['sales_item_tot_amt'].astype(float) \n \n prod_freq[i] = df.groupby('prod_cd').sum()\n \n \n\nfor key in prod_freq:\n df = prod_freq[key]\n prod_freq[key] = df.sort(['sales_item_qty', 'sales_item_tot_amt'], ascending=[0, 0])\n \n \nimport pickle\npickle.dump(prod_freq, open('prod_freq.p', 'wb'))\npickle.load(prod_freq, open('prod_freq.p', 'rb')) \n","sub_path":"TopBrandsMonthly.py","file_name":"TopBrandsMonthly.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"505316751","text":"# information.py\n# written by: Thomas A. Grate\n# copyright (c) 2017 by Thomas A. Grate, all rights reserved.\n#\n# for OYD Daily Program\n#\nfrom events import *\nfrom school import *\nfrom region import *\nfrom natarea import *\n\n# class Information: This class represents a single information.\n# An \"information\" is a prospective student who contacted the school\n# via a phone call, email, social media, or coming into the school.\n# The schema for the database table for informations is defined\n# by the Information() object\nclass Information(object):\n \"\"\" Information object:\n Attributes contained in Information.attrs dictionary:\n info_sql_id - internal use only, do not change\n school\n date\n first_name\n last_name\n age\n birth_date\n class_group - Adult, Junior, Child\n street, street2, city, state, postal_code - adddress info\n country - defaults to 'USA'\n email, mobile_phone, home_phone - contact info\n parental_contact\n how_found - how the information found school\n occupation\n interest - what is the info's interest in training\n body_issues - Injuries, Surgeries, Body Issues\n notes - notes and comments by instructor\n \"\"\"\n\n def __init__(self,\n school=None, date=None,\n first_name=None, last_name=None,\n age=0, birth_date=None, class_group=None,\n street=None, street2=None, city=None, state=None, postal_code=None,\n country='USA', email=None, mobile_phone=None, home_phone=None,\n parental_contact=None,\n how_found=None, occupation=None, interest=None,\n body_issues=None, notes=None):\n \"\"\"Information Object: __init__ Method\n Parameters:\n 1) See help for the Object definition for all attributes.\n 2) all attributes can be passed to __init__ as a Parameters\n to initialize the instance\"\"\"\n\n\n # Dictionary of Student Attributes\n self._sql_id = None # internal use only, do not change\n self.attrs = {'info_sql_id': None, # internal use only, do not change\n 'school': school,\n 'date': date,\n 'first_name': first_name,\n 'last_name': last_name,\n 'age': age,\n 'birth_date': birth_date,\n 'class_group': class_group,\n 'street': street,\n 'street2': street2,\n 'city': city,\n 'state': state,\n 'postal_code': postal_code,\n 'country': country,\n 'email': email,\n 'mobile_phone': mobile_phone,\n 'home_phone': home_phone,\n 'parental_contact': parental_contact,\n 'how_found': how_found,\n 'occupation': occupation,\n 'interest': interest,\n 'body_issues': body_issues,\n 'notes': notes\n }\n\n self.select_class_group = {\"adul\":\"Adult\", \"junior\":\"Junior\",\n \"child\":\"Child\"}\n\n # Matching dictionary of Human Readable Titles for Information Atributes\n self.labels = {'info_sql_id': 'SQL ID',\n 'school': 'School:',\n 'date': 'Date:',\n 'first_name': 'First Name:',\n 'last_name': 'Last Name:',\n 'age': 'Age:',\n 'birth_date': 'Birth Date:',\n 'class_group': 'Class:',\n 'street': 'Street:',\n 'street2': 'Street2:',\n 'city': 'City:',\n 'state': 'State / Prov:',\n 'postal_code': 'Postal Code:',\n 'country': 'Country:',\n 'email': 'eMail:',\n 'mobile_phone': 'Mobile Phone:',\n 'home_phone': 'Home Phone:',\n 'parental_contact': 'Parental Contact:',\n 'how_found': 'How Found:',\n 'occupation': 'Occupation:',\n 'interest': 'Interest:',\n 'body_issues': 'Body Issues:',\n 'notes': 'Notes:'\n }\n\n # Matching dictionary of UI input types for Student Atributes\n self.label_types = {'info_sql_id': \"hidden\",\n 'school': \"number\", # select\n 'date': \"date\",\n 'first_name': \"text\",\n 'last_name': \"text\",\n 'age': \"number\",\n 'birth_date': \"date\",\n 'class_group': 'text', # select\n 'street': 'text',\n 'street2': 'text',\n 'city': 'text',\n 'state': 'text', # select\n 'postal_code': 'text',\n 'country': 'text', # select\n 'email': 'email',\n 'mobile_phone': 'text',\n 'home_phone': 'text',\n 'parental_contact': 'text',\n 'how_found': 'text',\n 'occupation': 'text',\n 'interest': 'text',\n 'body_issues': 'text',\n 'notes': 'text'\n }\n\n # SQL Schema\n # Must match the attrs (attributes) above, line for line\n self.schema = ['info_sql_id',\n 'school',\n 'date',\n 'first_name',\n 'last_name',\n 'age',\n 'birth_date',\n 'class_group',\n 'street',\n 'street2',\n 'city',\n 'state',\n 'postal_code',\n 'country',\n 'email',\n 'mobile_phone',\n 'home_phone',\n 'parental_contact',\n 'how_found',\n 'occupation',\n 'interest',\n 'body_issues',\n 'notes'\n ]\n\n # create the INSERT schema substituion string\n self.schema_insert = \", \".join(self.schema)\n\n # SQL Data Types for the SQL Schema\n # Must match the SQL Schema above, line for line\n self.types = ['integer primary key',\n 'integer',\n 'datetime',\n 'text',\n 'text',\n 'integer',\n 'datetime',\n 'text',\n 'text',\n 'text',\n 'text',\n 'text',\n 'text',\n 'text',\n 'text',\n 'text',\n 'text',\n 'text',\n 'text',\n 'text',\n 'text',\n 'text',\n 'text'\n ]\n\n # make the CREATE schema substituion string\n # used to create the student table\n self.schema_create = ''\n limit = len(self.schema) - 1\n\n # print(f\"DEBUG: Information.init limit = {limit}\")\n # print(f\"DEBUG: Informations.init len(self.schema) = {len(self.schema)}\")\n # print(f\"DEBUG: Informations.init len(self.types) = {len(self.types)}\")\n\n i = 0\n for i in range(0, limit):\n addstr = self.schema[i] + ' ' + self.types[i] + ', '\n self.schema_create += addstr\n self.schema_create += self.schema[limit] + ' ' + self.types[limit]\n\n # VALUE substitution string\n self.schema_insert_sub = '(' + '?,' * (len(self.schema) - 1) + '?)'\n\n # Method to get a tuuple of all student data\n def _get (self):\n \"\"\" Information Object: _get method (private)\n Returns a tuple of the Student data\n Used by sql_insert_new \"\"\"\n\n # assuming that dictiionaries are unordered\n # retrive the data in oder as a tuple\n results = []\n for key in self.schema:\n results.append(self.attrs[key])\n\n return tuple(results)\n\n # Method to set all student data from a SQL row tuple\n def _set (self, sql_data):\n \"\"\" Information Object: _set method (private)\n Sets Information data in the instance of the object.\n Used to set data from a sql query into the object.\n Parameters:\n sql_data - a 'row' tuple returned from a sql query for a student\"\"\"\n\n # copy the sql_data, a row, to self.attrs dictionary\n # use self.schema instead of self.attrs.keys() to interate\n # becaause teh self.schema is a list and the order will not change\n i = 0\n for key in self.schema:\n self.attrs[key] = sql_data[i]\n i += 1\n\n # set separate _sql_id used for internal consistencu\n self._sql_id = self.attrs['info_sql_id']\n\n def _sql_populate (self, c):\n \"\"\" Information Object: _sql_populate method (private)\n Populates the instance of Information from the database as a new row\n Parameters:\n c = cursor to database\"\"\"\n\n try:\n # Test 0, check for the SQL ID\n if self.attrs['info_sql_id']:\n test = (self.attrs['info_sql_id'], )\n c.execute('SELECT * FROM informations WHERE info_sql_id=?', test)\n # Test #1, check for First, Last Name & School\n elif self.attrs['last_name'] and self.attrs['first_name'] \\\n and self.attrs['school']:\n test = (self.attrs['first_name'], self.attrs['last_name'],\n self.attrs['school'])\n c.execute('SELECT * FROM informations WHERE first_name=? AND \\\n last_name=? and school=?', test)\n else:\n # if you did't fill in any information to test, why did you call populate?\n return 1\n except Exception as e:\n print (f\"ERROR: _set_populate: {e}\")\n return 1 # return Error\n\n # check if a row is returned\n row = c.fetchone()\n if row:\n self._set(row)\n return 0\n else:\n return 1\n\n def _sql_insert (self, db, conn, c):\n \"\"\"Information Object: _sql_insert_new method (private)\n Inserts the instance of Information to the database as a new row\n Parameters:\n conn = connection to database\n c = cursor to database\"\"\"\n\n try:\n c.execute('INSERT INTO informations (' + self.schema_insert + \\\n ') VALUES ' + self.schema_insert_sub, self._get())\n except:\n # Insert failed so return Error\n return (1, 'Failed to insert new Information into Database')\n\n # Save (commit) the changes\n conn.commit()\n\n # student_sql_id is auto assigned on insert. So, retrive the student_sql_id from the db\n name = (self.attrs['first_name'], self.attrs['last_name'],\n self.attrs['school'])\n c.execute('SELECT info_sql_id FROM informations WHERE first_name=? AND \\\n last_name=? AND school=?', name)\n row = c.fetchone()\n self.attrs['info_sql_id'] = row[0]\n self._sql_id = row[0]\n\n # look up the school name, region name, and nat_area name\n # for writing the Master Events Table which is de-normalized\n school = School()\n school.school_id = self.attrs['school']\n school.get(db)\n region = Region()\n region.region_id = school.attrs['school_region']\n region.get(db)\n nat_area = NatArea ()\n nat_area.nat_area_id = region.attrs['nat_area']\n nat_area.get(db)\n\n # write an event to the Master Events Tables\n me = Master_Event(event = 'info', date = self.attrs['date'],\n info_sql_id = self.attrs['info_sql_id'],\n nat_area_name = nat_area.attrs['area_name'],\n region_name = region.attrs['region_name'],\n school_name = school.attrs['school_name'],\n age = self.attrs['age'],\n first_name = self.attrs['first_name'],\n last_name = self.attrs['last_name'],\n occupation = self.attrs['occupation'])\n me.put(db)\n\n return (0, 'New Information Added to Database')\n\n def _sql_update_attr (self, conn, c, label):\n \"\"\"Information Object: _sql_update_attr method (private)\n Updates a specific attribute in the instance of Information\n to the associated existing row in the database\n Parameters:\n conn = connection to database\n c = cursor to database\n label = name of attribute to be udpated to db\n attr = attribute to be updated\"\"\"\n\n if self._sql_id is not None:\n try:\n c.execute('UPDATE informations SET ' + label + ' = \"' + \\\n str(self.attrs[label]) + '\" WHERE info_sql_id=' + str(self._sql_id))\n\n # Save (commit) the changes\n conn.commit()\n\n return 0 # return Success\n except Exception as e:\n print (f\"ERROR: _set_update_attr: {e}\")\n return 1 # return Error\n else:\n print (\"ERROR: _set_update_attr: _sql_id not yet set\")\n return 1 # return Error\n\n def _sql_commit (self, conn, c):\n \"\"\"Information Object: _sql_commit method (private)\n Commits all attribute in the instance of Information\n to the associated existing row in the database\n Parameters:\n conn = connection to database\n c = cursor to database\"\"\"\n\n if self._sql_id is not None:\n try:\n # create the label = value string to UPDATE\n lvl = ''\n for label in self.schema:\n lvl += label + ' = \"' + str(self.attrs[label]) + '\", '\n lvl = lvl [:-2]\n\n # update the row\n c.execute('UPDATE informations SET ' + lvl + \\\n ' WHERE info_sql_id=' + str(self._sql_id))\n\n # Save (commit) the changes\n conn.commit()\n\n return 0 # return Success\n except Exception as e:\n print (f\"ERROR: _set_commit: {e}\")\n return 1 # return Error\n else:\n print (\"ERROR: _set_commit: _sql_id not yet set\")\n return 1 # return Error\n\n def get (self, db):\n \"\"\" Information Object: get method\n Populates the instance of Information from the database as a new row\n Parameters:\n db = Database object from which to retrive the cursor\"\"\"\n\n return self._sql_populate (db.cursor)\n\n def put (self, db):\n \"\"\"Information Object: put method\n Inserts the instance of Student into the database as a new row\n Parameters:\n db = Database object that contains the\n connection & cursor to database\"\"\"\n\n return self._sql_insert(db, db.conn, db.cursor)\n\n def update_attr (self, db, label):\n \"\"\"Information Object: update_attr method\n Updates a specific attribute in the instance of Information\n to the associated existing row in the database\n Parameters:\n db = Database object that contains the\n connection & cursor to database\n label = name of attribute to be udpated to db\n attr = attribute to be updated\"\"\"\n\n return self._sql_update_attr(db.conn, db.cursor, label)\n\n # commit the data in Student to the DB\n def update (self, db):\n \"\"\"Information Object: update method\n Commits all attributes in the instance of Information\n to the associated existing row in the database\n Parameters:\n db = Database object that contains the\n connection & cursor to database\"\"\"\n\n return self._sql_commit(db.conn, db.cursor)\n","sub_path":"projects/DailyDataAPI/information.py","file_name":"information.py","file_ext":"py","file_size_in_byte":15397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"148628853","text":"import Image \nimport numpy\nimport random\n\n#this script takes two .png files, merges the pixel values together to mix the pictures, and adds a certain amount of noise the resulting picture\n#planning to integrate it with DEAP GA in order to evolve structures based on the initial mixture of the two pictures\n\n\n#import image being used into library\nim = Image.open(\"image1 file path\")\nim2 = Image.open(\"image 2 file path\")\n\n#resizes pictures to 50 X 50 pixels\nwidth = 50\nheight = 50\nim3 = im.resize([height, width])\nim4 = im2.resize([height,width])\nim3.save(\"resized image1 file path (where to save it)\")\nim4.save(\"resized image2 file path (where to save it)\")\n\n\n#creates all initial values for weights \n#used to add noise to each of the pixel values (single weight for each pixel)\nweights1 = []\nweights2 = []\nfor i in range(0,3000):\n weights1.append(random.uniform(-1,1))\n weights2.append(random.uniform(-1,1))\n\n\n#obtains pixel values for two pictures \npixelMap1 = list(im3.getdata())\npixelMap2 = list(im4.getdata()) \n\n\n#adds weights to values of pixels for first image\nnew_values1 = []\nloop1= 0\nfor tup in pixelMap1:\n sublist1 = list(tup)\n for i in range(0,4):\n r = random.uniform(0,1)\n if r>.5:\n sublist1[i] = int(sublist1[i] + sublist1[i]*weights1[loop1])\n else:\n sublist1[i] = sublist1[i]\n new_values1.append(sublist1)\n loop1 = loop1 + 1\n\n\n#adds weights to values of pixels for second image\nnew_values2 = []\nloop2 = 0\nfor tup in pixelMap2:\n sublist2 = list(tup)\n for i in range(0,4):\n r = random.uniform(0,1)\n if r > .5:\n sublist2[i] = int(sublist2[i] + sublist2[i]*weights2[loop2])\n else: \n sublist2[i] = sublist2[i]\n new_values2.append(sublist2)\n loop2 = loop2 + 1\n\n\n#adds pixel values of two images together\nnew_pixels = []\nfor i in range(0,len(new_values2)):\n x = new_values1[i]\n y = new_values2[i]\n sublist = []\n for z in range(0,4):\n new = (x[z] + y[z])/2\n sublist.append(new)\n new_pixels.append(sublist) \n\n \n \n \n#eliminates all pixel values greater than 255 or less than 0 (converting to list in process)\n#pixel values beyond this range throw errors if converted back to .png file\nweighted_values = []\nsublist = []\nfor lists in new_pixels:\n sublist = []\n for i in range(0,4):\n z = lists[i]\n if z < 165:\n z = 0\n else:\n z = 255\n sublist.append(z)\n sublist[1] = sublist[0]\n sublist[2] = sublist[0]\n sublist[3] = sublist[0]\n weighted_values.append(sublist)\n\n\t\n#eliminates random pixels by checking if the pixels around them have similar values\nfor x in range(0,2499):\n if x < 3 or x > len(weighted_values)-3:\n weighted_values[x] = weighted_values[x]\n else:\n if weighted_values[x-1][0] == 255 and weighted_values[x+1][0] == 255 and weighted_values[x+2][0] == 255 and weighted_values[x-2][0] == 255:\n weighted_values[x][0] = 255\n weighted_values[x][1] = 255\n weighted_values[x][2] = 255\n weighted_values[x][3] = 255\n else:\n weighted_values[x] = weighted_values[x]\n \n \n \nfor x in range(0,2499):\n if x ==0 or x == 2499:\n weighted_values[x] = weighted_values[x]\n else:\n if weighted_values[x-1][0] == 0 and weighted_values[x+1][0] == 0:\n weighted_values[x][0] = 0\n weighted_values[x][1] = 0\n weighted_values[x][2] = 0\n weighted_values[x][3] = 0\n else:\n weighted_values[x] = weighted_values[x]\n\n\n\t\t\t\nfor x in range(0,2499):\n if x < 49 or x >2449:\n weighted_values[x] = weighted_values[x]\n else:\n if weighted_values[x-50][0] == 0 and weighted_values[x+50][0] == 0:\n weighted_values[x][0] = 0\n weighted_values[x][1] = 0\n weighted_values[x][2] = 0\n weighted_values[x][3] = 0\n else:\n weighted_values[x] = weighted_values[x]\n \n \n\n\n#converts list of pixels back into tuple format (format used to create .png files)\nfinal_pixels = []\nfor lists in weighted_values:\n sublist = []\n for values in lists:\n sublist.append(values)\n tup = (sublist[0],sublist[1],sublist[2],sublist[3]) \n final_pixels.append(tup)\n \n\n\n#creates an image with new pixel values\nim5 = Image.new('RGB', (50,50))\nim5.putdata(final_pixels)\nim5.save(\"File path to store output picture\")\n\n\n","sub_path":"merge_pics.py","file_name":"merge_pics.py","file_ext":"py","file_size_in_byte":4473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"424289981","text":"# 1-6_String_Compression.py\n\n# 1.6 String Compression\n# Implement a method to perform basic string compression using the counts\n# of repeated characters. For example, the string aabcccccaaa would become\n# a2b1c5a3. If the \"compressed\" string would not become smaller than the\n# original string, your method should return the original string. You can\n# assume the string has only uppercase and lowercase letters (a-z).\n\ndef string_compression(s: str) -> str:\n \"\"\"Compress a string with character counts e.g. aabcccccaaa -> a2b1c5a3.\"\"\"\n\n # Assumptions, Approach, Time & Space Complexity & Possible Improvements:\n\n # Assumptions:\n # s contains only uppercase and lowercase letters\n # empty string returns empty string\n\n # Approach:\n # 1. Loop through string checking if current character is equal to the\n # previous character and if so incrementing a counter\n # if not, append the previous character with count to an array\n # appending to an array is faster/space efficient in python rather than\n # appending to a string since strings are immutable.\n # afterwards we join all the array strings together\n # Then check the length and if the compressed string is smaller, return it\n # otherwise return the given string.\n\n # Time & Space Complexity:\n # Time complexity is O(N) since we have to check each character\n # Space complexity is O(N) since we have to create the compressed\n # string. Generally this will be smaller than O(N), but O(N) in the\n # worst case where each character is different.\n\n # Possible improvements:\n # Maybe we can use an ordered dict python object to make the character\n # counts and then use that to create the compressed string\n\n # Approach 1:\n\n if not s:\n return \"\"\n\n # start with first character of the string\n previous_character = s[0]\n previous_character_counter = 0\n compressed_string_array = []\n\n for character in s:\n if character == previous_character:\n previous_character_counter += 1\n else:\n compressed_string_array.append(\n \"{}{}\".format(\n previous_character,\n previous_character_counter\n )\n )\n previous_character = character\n previous_character_counter = 1\n\n # also get last character\n compressed_string_array.append(\n \"{}{}\".format(\n previous_character,\n previous_character_counter\n )\n )\n\n compressed_string = \"\".join(compressed_string_array)\n\n if len(compressed_string) < len(s):\n return compressed_string\n else:\n return s\n\n\nimport unittest\n\nclass TestStringCompression(unittest.TestCase):\n\n def test_problem_example(self):\n\n self.assertEqual(\n string_compression(\"aabcccccaaa\"),\n \"a2b1c5a3\"\n )\n\n\n def test_other_strings(self):\n self.assertEqual(\n string_compression(\"xxxyyyzzzhhhhheeeeelllllooooo\"),\n \"x3y3z3h5e5l5o5\"\n )\n\n\n def test_empty_string(self):\n self.assertEqual(\n string_compression(\"\"),\n \"\"\n )\n\n\n def test_string_shorter_than_compressed(self):\n self.assertEqual(\n string_compression(\"asdfqwer\"),\n \"asdfqwer\"\n )\n\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"cracking_the_coding_interview/1-6_String_Compression.py","file_name":"1-6_String_Compression.py","file_ext":"py","file_size_in_byte":3363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"128975857","text":"# Create your views here.\nfrom django.core.urlresolvers import reverse, resolve\nfrom django.http import Http404\nfrom django.shortcuts import render_to_response\nfrom django.template.context import RequestContext\nfrom cms.test_utils.project.sampleapp.models import Category\nfrom django.utils.translation import ugettext_lazy as _\n\n\ndef sample_view(request, **kw):\n app = resolve(request.path).namespace\n kw['app'] = app\n response_kwargs = {'current_app': app, 'dict_': kw}\n context = RequestContext(request, **response_kwargs)\n return render_to_response(\"sampleapp/home.html\", context_instance=context)\n\n\ndef category_view(request, id):\n cat = Category.objects.get(pk=id)\n if request.user.is_staff:\n category_menu = request.toolbar.get_or_create_menu('category', _('Category'))\n change_url = reverse('admin:sampleapp_category_change', args=(cat.pk,))\n category_menu.add_modal_item(_(\"Change Category\"), url=change_url, close_on_url_change=True)\n return render_to_response('sampleapp/category_view.html',\n RequestContext(request, {'category': cat}))\n\n\ndef extra_view(request, **kw):\n app = resolve(request.path).namespace\n kw['app'] = app\n response_kwargs = {'current_app': app, 'dict_': kw}\n context = RequestContext(request, **response_kwargs)\n return render_to_response(\"sampleapp/extra.html\", context)\n\n\ndef current_app(request):\n app = resolve(request.path).namespace\n context = RequestContext(request, {'app': app}, current_app=app)\n return render_to_response(\"sampleapp/app.html\", context)\n\n\ndef notfound(request):\n raise Http404\n","sub_path":"cms/test_utils/project/sampleapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"263047752","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\n\"\"\"Functions for downloading and reading MNIST data.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport gzip\nimport os\nimport numpy\nfrom six.moves import urllib\nfrom six.moves import xrange # pylint: disable=redefined-builtin\n\nSOURCE_URL = 'http://yann.lecun.com/exdb/mnist/'\n\ndef maybe_download(filename, work_directory):\n \"\"\"Download the data from Yann's website, unless it's already here.\"\"\"\n if not os.path.exists(work_directory):\n os.mkdir(work_directory)\n filepath = os.path.join(work_directory, filename)\n if not os.path.exists(filepath):\n filepath, _ = urllib.request.urlretrieve(SOURCE_URL + filename, filepath)\n statinfo = os.stat(filepath)\n print('Successfully downloaded', filename, statinfo.st_size, 'bytes.')\n return filepath\n\ndef _read32(bytestream):\n dt = numpy.dtype(numpy.uint32).newbyteorder('>')\n return numpy.frombuffer(bytestream.read(4), dtype=dt)[0]\n\ndef extract_images(filename):\n \"\"\"Extract the images into a 4D uint8 numpy array [index, y, x, depth].\"\"\"\n print('Extracting', filename)\n with gzip.open(filename) as bytestream:\n magic = _read32(bytestream)\n if magic != 2051:\n raise ValueError('Invalid magic number %d in MNIST image file: %s' % (magic, filename))\n num_images = _read32(bytestream)\n rows = _read32(bytestream)\n cols = _read32(bytestream)\n buf = bytestream.read(rows * cols * num_images)\n data = numpy.frombuffer(buf, dtype=numpy.uint8)\n data = data.reshape(num_images, rows, cols, 1)\n return data\n\ndef dense_to_one_hot(labels_dense, num_classes=10):\n \"\"\"Convert class labels from scalars to one-hot vectors.\"\"\"\n num_labels = labels_dense.shape[0]\n index_offset = numpy.arange(num_labels) * num_classes\n labels_one_hot = numpy.zeros((num_labels, num_classes))\n labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1\n return labels_one_hot\n\ndef extract_labels(filename, one_hot=False):\n \"\"\"Extract the labels into a 1D uint8 numpy array [index].\"\"\"\n print('Extracting', filename)\n with gzip.open(filename) as bytestream:\n magic = _read32(bytestream)\n if magic != 2049:\n raise ValueError('Invalid magic number %d in MNIST label file: %s' % (magic, filename))\n num_items = _read32(bytestream)\n buf = bytestream.read(num_items)\n labels = numpy.frombuffer(buf, dtype=numpy.uint8)\n if one_hot:\n return dense_to_one_hot(labels)\n return labels\n\n\nclass MNISTData(object):\n \n def __init__(self, **kwargs): \n self.train_dir = kwargs['train_dir'] if 'train_dir' in kwargs else None\n one_hot = kwargs['one_hot'] if 'one_hot' in kwargs else False\n\n TRAIN_IMAGES = 'train-images-idx3-ubyte.gz'\n TRAIN_LABELS = 'train-labels-idx1-ubyte.gz'\n TEST_IMAGES = 't10k-images-idx3-ubyte.gz'\n TEST_LABELS = 't10k-labels-idx1-ubyte.gz'\n VALIDATION_SIZE = 5000\n local_file = maybe_download(TRAIN_IMAGES, self.train_dir)\n train_images = extract_images(local_file)\n local_file = maybe_download(TRAIN_LABELS, self.train_dir)\n train_labels = extract_labels(local_file, one_hot=one_hot)\n local_file = maybe_download(TEST_IMAGES, self.train_dir)\n test_images = extract_images(local_file)\n local_file = maybe_download(TEST_LABELS, self.train_dir)\n test_labels = extract_labels(local_file, one_hot=one_hot)\n validation_images = train_images[:VALIDATION_SIZE]\n validation_labels = train_labels[:VALIDATION_SIZE]\n train_images = train_images[VALIDATION_SIZE:]\n train_labels = train_labels[VALIDATION_SIZE:]\n self.train = self.setup(images=train_images, labels=train_labels)\n self.validation = self.setup(images=validation_images, labels=validation_labels)\n self.test = self.setup(images=test_images, labels=test_labels)\n \n self.initialized = True\n\n def setup(self, **kwargs):\n assert ('images' in kwargs and 'labels' in kwargs), \"images and labels arguments must be provided.\"\n\n images = kwargs['images']\n labels = kwargs['labels']\n assert images.shape[0] == labels.shape[0], ('images.shape: %s labels.shape: %s' % (images.shape,labels.shape))\n \n dic = {}\n\n dic['num_examples'] = images.shape[0]\n # Convert shape from [num examples, rows, columns, depth]\n # to [num examples, rows*columns] (assuming depth == 1)\n assert images.shape[3] == 1\n images = images.reshape(images.shape[0],images.shape[1] * images.shape[2])\n # Convert from [0, 255] -> [0.0, 1.0].\n images = images.astype(numpy.float32)\n images = numpy.multiply(images, 1.0 / 255.0)\n dic['images'] = images\n dic['labels'] = labels\n dic['epochs_completed'] = 0\n dic['index_in_epoch'] = 0\n return dic\n\n def next_batch(self, n, **kwargs):\n dataset = kwargs['set'] if 'set' in kwargs else self.train\n\n \"\"\"Return the next `n` examples from this data set.\"\"\"\n start = dataset['index_in_epoch']\n dataset['index_in_epoch'] += n\n if dataset['index_in_epoch'] > dataset['num_examples']:\n # Finished epoch\n dataset['epochs_completed'] += 1\n # Shuffle the data\n perm = numpy.arange(dataset['num_examples'])\n numpy.random.shuffle(perm)\n dataset['images'] = dataset['images'][perm]\n dataset['labels'] = dataset['labels'][perm]\n # Start next epoch\n start = 0\n dataset['index_in_epoch'] = n\n assert n <= dataset['num_examples']\n end = dataset['index_in_epoch']\n return dataset['images'][start:end], dataset['labels'][start:end]\n\n def get_inputshape(self):\n return [784]","sub_path":"MNISTData.py","file_name":"MNISTData.py","file_ext":"py","file_size_in_byte":6593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"354309293","text":"# CS231\n# Assignment# 12\n# Write a program that creates a pool of workers to all at once\n# check whether or not the files whose pathnames are passed in are encoded in UTF-8\nimport unicodedata\nimport sys\nimport concurrent.futures\n\nfilepath = sys.argv[1]\nlines = open(filepath).readlines()\n\ndef checkcoding(str):\n try:\n str.encode(encoding='utf-8', errors='strict')\n print(\"content is UTF-8\")\n except UnicodeError:\n print(\"content is not UTF-8\")\n\npool = concurrent.futures.ThreadPoolExecutor()\n\nprint(list(pool.map(checkcoding,lines)),\n list(zip(lines,pool.map(checkcoding,lines))))\n","sub_path":"homework/homework12/peer_review_hw12/vg.py","file_name":"vg.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"232795377","text":"'''\nCreated on 06-June-2019\n\n@author: Nagesh Purohit\n'''\ndef getName():\n print(\"Enter Name:\")\n n=input()\n return n\ndef getSurname():\n print(\"Enter Surname:\")\n n=input()\n return n\ndef printData(name,surname):\n if name.isdigit() or name.isnumeric():\n print(\"Name cannot contain numeric values\")\n else:\n if name.islower():\n print(\"Name:\"+name.upper())\n else:\n print(\"Name:\"+name)\n if surname.isdigit() or surname.isnumeric():\n print(\"Surname cannot contain numeric values\")\n else:\n if surname.islower():\n print(\"Surname:\"+surname.upper())\n else:\n print(\"Surname:\"+surname)\n \nnn=getName()\nsn=getSurname()\nprintData(nn,sn)\n","sub_path":"pyPrac/basic/inputdata.py","file_name":"inputdata.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"141177877","text":"#!/usr/bin/env python3\n\n# The MIT License (MIT)\n# =====================\n#\n# Copyright © 2020 Azavea\n#\n# Permission is hereby granted, free of charge, to any person\n# obtaining a copy of this software and associated documentation\n# files (the “Software”), to deal in the Software without\n# restriction, including without limitation the rights to use,\n# copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the\n# Software is furnished to do so, subject to the following\n# conditions:\n#\n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n# OTHER DEALINGS IN THE SOFTWARE.\n\nimport argparse\nimport ast\nimport copy\nimport json\nimport os\nimport sys\n\nimport numpy as np\n\nimport rasterio as rio\nimport scipy.ndimage\n\n\ndef cli_parser() -> argparse.ArgumentParser:\n parser = argparse.ArgumentParser()\n parser.add_argument('--input-path', required=True, type=str)\n parser.add_argument('--name', required=True, type=str)\n parser.add_argument('--output-path', required=True, type=str)\n return parser\n\n\nif __name__ == '__main__':\n args = cli_parser().parse_args()\n\n cloudless_tif = '/tmp/{}-cloudless.tif'.format(args.name)\n cloudy_tif = '/tmp/{}-cloudy.tif'.format(args.name)\n\n # Download\n os.system('aws s3 sync {} /tmp/'.format(args.input_path))\n backstops = int(os.popen('ls /tmp/backstop*.tif | wc -l').read())\n\n # Produce final images\n if backstops > 0:\n os.system('gdalwarp $(ls /tmp/*.tif | grep backstop | sort -r) -multi -co NUM_THREADS=ALL_CPUS -wo NUM_THREADS=ALL_CPUS -oo NUM_THREADS=ALL_CPUS -doo NUM_THREADS=ALL_CPUS -co TILED=YES -co BIGTIFF=YES /tmp/cloudy.tif')\n os.system('gdalwarp /tmp/cloudy.tif -multi -co NUM_THREADS=ALL_CPUS -wo NUM_THREADS=ALL_CPUS -oo NUM_THREADS=ALL_CPUS -doo NUM_THREADS=ALL_CPUS -co COMPRESS=DEFLATE -co PREDICTOR=2 -co TILED=YES -co SPARSE_OK=YES -co BIGTIFF=YES {}'.format(cloudy_tif))\n os.system('rm /tmp/cloudy.tif')\n os.system('aws s3 cp {} {}'.format(cloudy_tif, args.output_path))\n os.system('gdalwarp {} $(ls /tmp/*.tif | grep -v backstop | grep -v cloudy | sort -r) -multi -co NUM_THREADS=ALL_CPUS -wo NUM_THREADS=ALL_CPUS -oo NUM_THREADS=ALL_CPUS -doo NUM_THREADS=ALL_CPUS -co TILED=YES -co BIGTIFF=YES /tmp/cloudless.tif'.format(cloudy_tif))\n os.system('gdalwarp /tmp/cloudless.tif -multi -co NUM_THREADS=ALL_CPUS -wo NUM_THREADS=ALL_CPUS -oo NUM_THREADS=ALL_CPUS -doo NUM_THREADS=ALL_CPUS -co COMPRESS=DEFLATE -co PREDICTOR=2 -co TILED=YES -co SPARSE_OK=YES -co BIGTIFF=YES {}'.format(cloudless_tif))\n os.system('rm /tmp/cloudless.tif')\n else:\n os.system('gdalwarp $(ls /tmp/*.tif | grep -v backstop | grep -v cloudy | sort -r) -multi -co NUM_THREADS=ALL_CPUS -wo NUM_THREADS=ALL_CPUS -oo NUM_THREADS=ALL_CPUS -doo NUM_THREADS=ALL_CPUS -co TILED=YES -co BIGTIFF=YES /tmp/cloudless.tif')\n os.system('gdalwarp /tmp/cloudless.tif -multi -co NUM_THREADS=ALL_CPUS -wo NUM_THREADS=ALL_CPUS -oo NUM_THREADS=ALL_CPUS -doo NUM_THREADS=ALL_CPUS -co COMPRESS=DEFLATE -co PREDICTOR=2 -co TILED=YES -co SPARSE_OK=YES -co BIGTIFF=YES {}'.format(cloudless_tif))\n os.system('rm /tmp/cloudless.tif')\n\n # Upload\n os.system('aws s3 cp {} {}'.format(cloudless_tif, args.output_path))\n","sub_path":"python/merge.py","file_name":"merge.py","file_ext":"py","file_size_in_byte":3828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"163744780","text":"import socket\r\n\r\n# create an INET, STREAMing socket\r\nserversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n# bind the socket to a public host, and a well-known port\r\nserversocket.bind((socket.gethostname(), 5695))\r\n# become a server socket\r\nserversocket.listen(5)\r\nprint(\"Running the server...\")\r\n\r\nwhile True:\r\n (clientsocket, address) = serversocket.accept()\r\n print(f\"ClientSocket connected : {clientsocket} & Address : {address}\")\r\n clientsocket.send((\"Thank you for connecting...\").encode())\r\n dataSize = int(clientsocket.recv(512).decode())\r\n print(f\"DataSize is : {dataSize} & it's type is: {type(dataSize)}\")\r\n data = clientsocket.recv(dataSize).decode()\r\n print(data)\r\n","sub_path":"Day1/sockets_program/socketDemo/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"403533750","text":"from functools import reduce\n\n# from keras import layers\n# from keras import initializers\n# from keras import models\n# from keras_ import EfficientNetB0, EfficientNetB1, EfficientNetB2\n# from keras_ import EfficientNetB3, EfficientNetB4, EfficientNetB5, EfficientNetB6\n\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow.keras as tfk\nfrom tensorflow.keras import layers\nfrom tensorflow.keras import models\nfrom tfkeras import EfficientNetB0, EfficientNetB1, EfficientNetB2\nfrom tfkeras import EfficientNetB3, EfficientNetB4, EfficientNetB5, EfficientNetB6\n\nfrom layers import (\n ClipBoxes,\n RegressBoxes,\n FilterDetections,\n wBiFPNAdd,\n)\nfrom initializers import PriorProbability\nfrom tensorflow.python.keras.utils import tf_utils\nimport tensorflow.keras as keras\n\n\nw_bifpns = [64, 88, 112, 160, 224, 288, 384]\nimage_sizes = [512, 640, 768, 896, 1024, 1280, 1408]\nbackbones = [\n EfficientNetB0,\n EfficientNetB1,\n EfficientNetB2,\n EfficientNetB3,\n EfficientNetB4,\n EfficientNetB5,\n EfficientNetB6,\n]\n\n\n# See https://arxiv.org/pdf/1911.09070v1.pdf page 6\nbatchnorm_config = {\n \"momentum\": 0.997,\n \"epsilon\": 1e-4\n}\n\n\ndef DepthwiseConvBlock(kernel_size, strides, name, freeze_bn=False):\n f1 = layers.DepthwiseConv2D(\n kernel_size=kernel_size,\n strides=strides,\n padding=\"same\",\n use_bias=False,\n name=\"{}_dconv\".format(name),\n )\n\n # The previously used hack to freeze batchnorm is no longer necessary\n # See: https://www.tensorflow.org/api_docs/python/tf/keras/layers/BatchNormalization?version=stable#output_shape_2\n f2 = layers.BatchNormalization(\n name=\"{}_bn\".format(name),\n trainable=not freeze_bn,\n **batchnorm_config)\n\n f3 = layers.ReLU(name=\"{}_relu\".format(name))\n return reduce(\n lambda f, g: lambda *args, **kwargs: g(\n f(*args, **kwargs)), (f1, f2, f3)\n )\n\n\ndef ConvBlock(num_channels, name, kernel_size=1, strides=1, freeze_bn=False):\n f1 = layers.Conv2D(\n num_channels,\n kernel_size=kernel_size,\n strides=strides,\n padding=\"same\",\n use_bias=False,\n name=\"{}_conv\".format(name),\n )\n\n f2 = layers.BatchNormalization(\n name=\"{}_bn\".format(name),\n trainable=not freeze_bn,\n **batchnorm_config)\n\n f3 = layers.ReLU(name=\"{}_relu\".format(name))\n return reduce(\n lambda f, g: lambda *args, **kwargs: g(\n f(*args, **kwargs)), (f1, f2, f3)\n )\n\n\ndef build_BiFPN(features, num_channels, layer_index, freeze_bn=False):\n if layer_index == 0:\n _, _, C3, C4, C5 = features\n P3_in = ConvBlock(\n num_channels,\n freeze_bn=freeze_bn,\n name=\"BiFPN_{}_P3\".format(layer_index),\n )(C3)\n P4_in = ConvBlock(\n num_channels,\n freeze_bn=freeze_bn,\n name=\"BiFPN_{}_P4\".format(layer_index),\n )(C4)\n P5_in = ConvBlock(\n num_channels,\n freeze_bn=freeze_bn,\n name=\"BiFPN_{}_P5\".format(layer_index),\n )(C5)\n P6_in = ConvBlock(\n num_channels,\n kernel_size=3,\n strides=2,\n freeze_bn=freeze_bn,\n name=\"BiFPN_{}_P6\".format(layer_index),\n )(C5)\n P7_in = ConvBlock(\n num_channels,\n kernel_size=3,\n strides=2,\n freeze_bn=freeze_bn,\n name=\"BiFPN_{}_P7\".format(layer_index),\n )(P6_in)\n else:\n P3_in, P4_in, P5_in, P6_in, P7_in = features\n P3_in = ConvBlock(\n num_channels,\n freeze_bn=freeze_bn,\n name=\"BiFPN_{}_P3\".format(layer_index),\n )(P3_in)\n P4_in = ConvBlock(\n num_channels,\n freeze_bn=freeze_bn,\n name=\"BiFPN_{}_P4\".format(layer_index),\n )(P4_in)\n P5_in = ConvBlock(\n num_channels,\n freeze_bn=freeze_bn,\n name=\"BiFPN_{}_P5\".format(layer_index),\n )(P5_in)\n P6_in = ConvBlock(\n num_channels,\n freeze_bn=freeze_bn,\n name=\"BiFPN_{}_P6\".format(layer_index),\n )(P6_in)\n P7_in = ConvBlock(\n num_channels,\n freeze_bn=freeze_bn,\n name=\"BiFPN_{}_P7\".format(layer_index),\n )(P7_in)\n\n # upsample\n P7_U = layers.UpSampling2D()(P7_in)\n P6_td = layers.Add()([P7_U, P6_in])\n P6_td = DepthwiseConvBlock(\n kernel_size=3, strides=1, freeze_bn=freeze_bn, name=\"BiFPN_{}_U_P6\".format(layer_index)\n )(P6_td)\n P6_U = layers.UpSampling2D()(P6_td)\n P5_td = layers.Add()([P6_U, P5_in])\n P5_td = DepthwiseConvBlock(\n kernel_size=3, strides=1, freeze_bn=freeze_bn, name=\"BiFPN_{}_U_P5\".format(layer_index)\n )(P5_td)\n P5_U = layers.UpSampling2D()(P5_td)\n P4_td = layers.Add()([P5_U, P4_in])\n P4_td = DepthwiseConvBlock(\n kernel_size=3, strides=1, freeze_bn=freeze_bn, name=\"BiFPN_{}_U_P4\".format(layer_index)\n )(P4_td)\n P4_U = layers.UpSampling2D()(P4_td)\n P3_out = layers.Add()([P4_U, P3_in])\n P3_out = DepthwiseConvBlock(\n kernel_size=3, strides=1, freeze_bn=freeze_bn, name=\"BiFPN_{}_U_P3\".format(layer_index)\n )(P3_out)\n # downsample\n P3_D = layers.MaxPooling2D(strides=(2, 2))(P3_out)\n P4_out = layers.Add()([P3_D, P4_td, P4_in])\n P4_out = DepthwiseConvBlock(\n kernel_size=3, strides=1, freeze_bn=freeze_bn, name=\"BiFPN_{}_D_P4\".format(layer_index)\n )(P4_out)\n P4_D = layers.MaxPooling2D(strides=(2, 2))(P4_out)\n P5_out = layers.Add()([P4_D, P5_td, P5_in])\n P5_out = DepthwiseConvBlock(\n kernel_size=3, strides=1, freeze_bn=freeze_bn, name=\"BiFPN_{}_D_P5\".format(layer_index)\n )(P5_out)\n P5_D = layers.MaxPooling2D(strides=(2, 2))(P5_out)\n P6_out = layers.Add()([P5_D, P6_td, P6_in])\n P6_out = DepthwiseConvBlock(\n kernel_size=3, strides=1, freeze_bn=freeze_bn, name=\"BiFPN_{}_D_P6\".format(layer_index)\n )(P6_out)\n P6_D = layers.MaxPooling2D(strides=(2, 2))(P6_out)\n P7_out = layers.Add()([P6_D, P7_in])\n P7_out = DepthwiseConvBlock(\n kernel_size=3, strides=1, freeze_bn=freeze_bn, name=\"BiFPN_{}_D_P7\".format(layer_index)\n )(P7_out)\n\n return P3_out, P4_out, P5_out, P6_out, P7_out\n\n\ndef build_wBiFPN(features, num_channels, id, freeze_bn=False):\n if id == 0:\n _, _, C3, C4, C5 = features\n P3_in = ConvBlock(num_channels, kernel_size=1, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_P3'.format(id))(\n C3)\n P4_in = ConvBlock(num_channels, kernel_size=1, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_P4'.format(id))(\n C4)\n P5_in = ConvBlock(num_channels, kernel_size=1, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_P5'.format(id))(\n C5)\n P6_in = ConvBlock(num_channels, kernel_size=3, strides=2, freeze_bn=freeze_bn, name='BiFPN_{}_P6'.format(id))(\n C5)\n P7_in = ConvBlock(num_channels, kernel_size=3, strides=2, freeze_bn=freeze_bn, name='BiFPN_{}_P7'.format(id))(\n P6_in)\n else:\n P3_in, P4_in, P5_in, P6_in, P7_in = features\n P3_in = ConvBlock(num_channels, kernel_size=1, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_P3'.format(id))(\n P3_in)\n P4_in = ConvBlock(num_channels, kernel_size=1, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_P4'.format(id))(\n P4_in)\n P5_in = ConvBlock(num_channels, kernel_size=1, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_P5'.format(id))(\n P5_in)\n P6_in = ConvBlock(num_channels, kernel_size=1, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_P6'.format(id))(\n P6_in)\n P7_in = ConvBlock(num_channels, kernel_size=1, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_P7'.format(id))(\n P7_in)\n\n # upsample\n P7_U = layers.UpSampling2D()(P7_in)\n P6_td = wBiFPNAdd(name='w_bi_fpn_add' if id ==\n 0 else 'w_bi_fpn_add_{}'.format(8 * id))([P7_U, P6_in])\n P6_td = DepthwiseConvBlock(\n kernel_size=3, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_U_P6'.format(id))(P6_td)\n P6_U = layers.UpSampling2D()(P6_td)\n P5_td = wBiFPNAdd(name='w_bi_fpn_add_{}'.format(8 * id + 1))([P6_U, P5_in])\n P5_td = DepthwiseConvBlock(\n kernel_size=3, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_U_P5'.format(id))(P5_td)\n P5_U = layers.UpSampling2D()(P5_td)\n P4_td = wBiFPNAdd(name='w_bi_fpn_add_{}'.format(8 * id + 2))([P5_U, P4_in])\n P4_td = DepthwiseConvBlock(\n kernel_size=3, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_U_P4'.format(id))(P4_td)\n P4_U = layers.UpSampling2D()(P4_td)\n P3_out = wBiFPNAdd(name='w_bi_fpn_add_{}'.format(\n 8 * id + 3))([P4_U, P3_in])\n P3_out = DepthwiseConvBlock(\n kernel_size=3, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_U_P3'.format(id))(P3_out)\n # downsample\n P3_D = layers.MaxPooling2D(strides=(2, 2))(P3_out)\n P4_out = wBiFPNAdd(name='w_bi_fpn_add_{}'.format(\n 8 * id + 4))([P3_D, P4_td, P4_in])\n P4_out = DepthwiseConvBlock(\n name='BiFPN_{}_D_P4'.format(id),\n kernel_size=3, strides=1, freeze_bn=freeze_bn,\n )(P4_out)\n P4_D = layers.MaxPooling2D(strides=(2, 2))(P4_out)\n P5_out = wBiFPNAdd(name='w_bi_fpn_add_{}'.format(\n 8 * id + 5))([P4_D, P5_td, P5_in])\n P5_out = DepthwiseConvBlock(\n kernel_size=3, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_D_P5'.format(id))(P5_out)\n P5_D = layers.MaxPooling2D(strides=(2, 2))(P5_out)\n P6_out = wBiFPNAdd(name='w_bi_fpn_add_{}'.format(\n 8 * id + 6))([P5_D, P6_td, P6_in])\n P6_out = DepthwiseConvBlock(\n kernel_size=3, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_D_P6'.format(id))(P6_out)\n P6_D = layers.MaxPooling2D(strides=(2, 2))(P6_out)\n P7_out = wBiFPNAdd(name='w_bi_fpn_add_{}'.format(\n 8 * id + 7))([P6_D, P7_in])\n P7_out = DepthwiseConvBlock(\n kernel_size=3, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_D_P7'.format(id))(P7_out)\n\n return P3_out, P4_out, P5_out, P6_out, P7_out\n\n\ndef build_regress_head(width, depth, num_anchors=9):\n \"\"\"\n Build a box prediction subnet as described in\n the RetinaNet Paper on page 5 https://arxiv.org/pdf/1708.02002.pdf\n \"\"\"\n\n options = {\n \"kernel_size\": 3,\n \"strides\": 1,\n \"padding\": \"same\",\n \"kernel_initializer\": tf.compat.v1.random_normal_initializer(\n mean=0.0, stddev=0.01, seed=None\n ),\n \"bias_initializer\": \"zeros\",\n }\n\n inputs = layers.Input(shape=(None, None, width))\n outputs = inputs\n\n # @TODO: Switch all convs to depthwise sperable convs with swish activation\n # When applicable. The last layer of regression and classification heads needs\n # To have a relu activation because the minimum must be 0.\n for i in range(depth):\n outputs = layers.Conv2D(\n filters=width,\n activation=\"relu\",\n name=\"regress_head_conv_{}\".format(i),\n **options\n )(outputs)\n\n # Note: there is no activation function at the end. The offsets are linear.\n outputs = layers.Conv2D(\n num_anchors * 4,\n name=\"regress_head_conv_final\",\n **options\n )(outputs)\n\n # (b, num_anchors_this_feature_map, 4)\n outputs = layers.Reshape((-1, 4))(outputs)\n\n return models.Model(inputs=inputs, outputs=outputs, name=\"box_head\")\n\n\ndef build_class_head(width, depth, num_classes=20, num_anchors=9):\n options = {\n \"kernel_size\": 3,\n \"strides\": 1,\n \"padding\": \"same\",\n }\n\n inputs = layers.Input(shape=(None, None, width))\n outputs = inputs\n\n for i in range(depth):\n outputs = layers.Conv2D(\n filters=width,\n activation=\"relu\",\n\n # See: https://arxiv.org/pdf/1708.02002.pdf page 5 under initialization\n kernel_initializer=tf.compat.v1.random_normal_initializer(\n mean=0.0, stddev=0.01, seed=None\n ),\n\n name=\"class_head_{}\".format(i),\n bias_initializer=\"zeros\",\n **options,\n )(outputs)\n\n # outputs = layers.Conv2D(num_anchors * num_classes, **options)(outputs)\n outputs = layers.Conv2D(\n filters=num_classes * num_anchors,\n kernel_initializer=tf.compat.v1.random_normal_initializer(\n mean=0.0, stddev=0.01, seed=None),\n bias_initializer=PriorProbability(probability=0.01),\n name=\"pyramid_classification\",\n **options,\n )(outputs)\n\n # (b, num_anchors_this_feature_map, 4)\n outputs = layers.Reshape((-1, num_classes))(outputs)\n outputs = layers.Activation('sigmoid')(outputs)\n\n return models.Model(inputs=inputs, outputs=outputs, name=\"class_head\")\n\n\ndef efficientdet(\n phi,\n num_classes=20,\n weighted_bifpn=False,\n freeze_bn=False,\n score_threshold=0.01,\n no_filter=False,\n anchors=None,\n just_training_model=False,\n **bbkwargs\n):\n assert phi in range(7)\n input_size = image_sizes[phi]\n input_shape = (input_size, input_size, 3)\n\n image_input = layers.Input(input_shape)\n w_bifpn = w_bifpns[phi]\n d_bifpn = 2 + phi\n w_head = w_bifpn\n box_head_depth = 3 + int(phi / 3)\n backbone_cls = backbones[phi]\n\n # features = backbone_cls(include_top=False, input_shape=input_shape, weights=weights)(image_input)\n features = backbone_cls(input_tensor=image_input,\n freeze_bn=freeze_bn, **bbkwargs)\n\n if weighted_bifpn:\n for i in range(d_bifpn):\n features = build_wBiFPN(features, w_bifpn, i, freeze_bn=freeze_bn)\n else:\n for i in range(d_bifpn):\n features = build_BiFPN(features, w_bifpn, i, freeze_bn=freeze_bn)\n\n regress_head = build_regress_head(w_head, box_head_depth)\n class_head = build_class_head(\n w_head, box_head_depth, num_classes=num_classes)\n\n regression = [regress_head(feature) for feature in features]\n regression = layers.Concatenate(axis=1, name=\"regression\")(regression)\n\n classification = [class_head(feature) for feature in features]\n classification = layers.Concatenate(\n axis=1, name=\"classification\")(classification)\n\n model_inputs = [image_input]\n\n model = models.Model(\n inputs=model_inputs,\n # @TODO: LOOK AT ORDERING\n outputs=[regression, classification],\n name=\"efficientdet\"\n )\n\n if just_training_model:\n return model\n\n # Optionally allow anchors to be baked into the model.\n # this is useful for exporting a single package to js\n if anchors is not None:\n anchor_array = np.expand_dims(anchors, axis=0)\n\n box_predicter = RegressBoxes(\n name=\"boxes\", anchor_shape=anchor_array.shape)\n box_predicter.set_anchors(anchor_array)\n boxes = box_predicter([regression])\n\n else:\n # apply predicted regression to anchors\n anchors_input = layers.Input((None, 4))\n boxes = RegressBoxes(name=\"boxes\")([anchors_input, regression])\n\n model_inputs.append(anchors_input)\n\n boxes = ClipBoxes(name=\"clipped_boxes\")([image_input, boxes])\n\n # Don't implement filter detections as layer so it can be implemented as a basic js function\n # filter detections (apply NMS / score threshold / select top-k)\n if no_filter:\n prediction_model = models.Model(\n inputs=model_inputs,\n outputs=[boxes, classification],\n name=\"efficientdet_p\",\n )\n\n return model, prediction_model\n\n # filter detections (apply NMS / score threshold / select top-k)\n detections = FilterDetections(\n name=\"filtered_detections\",\n score_threshold=score_threshold\n )([boxes, classification])\n\n prediction_model = models.Model(\n inputs=model_inputs, outputs=detections, name=\"efficientdet_p\"\n )\n\n return model, prediction_model\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":15884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"127808892","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# https://www.datacamp.com/community/tutorials/autoencoder-classifier-python\n\nimport os\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"0\" #model will be trained on GPU 0\n\nimport keras\nimport tensorflow as tf\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport gzip\n# %matplotlib inline\nfrom keras.models import Model\nfrom keras.optimizers import RMSprop\nfrom keras.layers import Input,Dense,Flatten,Dropout,merge,Reshape,Conv2D,MaxPooling2D,UpSampling2D,Conv2DTranspose\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.models import Model,Sequential\nfrom keras.callbacks import ModelCheckpoint, TensorBoard\nfrom keras.optimizers import Adadelta, RMSprop,SGD,Adam\nfrom keras import regularizers\nfrom keras import backend as K\nfrom keras.utils import to_categorical\nfrom keras.preprocessing.image import ImageDataGenerator\n\nbatch_size = 64\nepochs = 25\ninChannel = 3\nx, y = 128, 128\ninput_img = Input(shape = (x, y, inChannel))\nnum_classes = 2\n\ntrain_datagen = ImageDataGenerator()\n# rotation_range=40,\n# width_shift_range=0.2,\n# height_shift_range=0.2,\n# shear_range=0.2,\n# zoom_range=0.2,\n# channel_shift_range=10,\n# horizontal_flip=True,\n# fill_mode='nearest')\n\ntrain_batches = train_datagen.flow_from_directory(\"./../data/MURA-v1.1/data2/train/\",\n target_size=(x,y),\n interpolation='bicubic',\n class_mode='categorical',\n shuffle=True,\n batch_size=batch_size)\n\ntrain_auto = train_datagen.flow_from_directory(\"./../data/MURA-v1.1/data2/train/\",\n target_size=(x,y),\n interpolation='bicubic',\n class_mode='input',\n shuffle=True,\n batch_size=batch_size)\n\nvalid_datagen = ImageDataGenerator()\nvalid_batches = valid_datagen.flow_from_directory(\"./../data/MURA-v1.1/data2/valid/\",\n target_size=(x,y),\n interpolation='bicubic',\n class_mode='categorical',\n shuffle=False,\n batch_size=batch_size)\n\nvalid_auto = valid_datagen.flow_from_directory(\"./../data/MURA-v1.1/data2/valid/\",\n target_size=(x,y),\n interpolation='bicubic',\n class_mode='input',\n shuffle=False,\n batch_size=batch_size)\n\ndef encoder(input_img):\n #encoder\n #input = 28 x 28 x 1 (wide and thin)\n conv1 = Conv2D(32, (5,5), activation='relu', padding='same')(input_img) #28 x 28 x 32\n conv1 = BatchNormalization()(conv1)\n conv1 = Conv2D(32, (5,5), activation='relu', padding='same')(conv1)\n conv1 = BatchNormalization()(conv1)\n conv1 = Conv2D(32, (5,5), activation='relu', padding='same')(conv1)\n conv1 = BatchNormalization()(conv1)\n pool1 = MaxPooling2D(pool_size=(2, 2))(conv1) #14 x 14 x 32\n conv2 = Conv2D(64, (5,5), activation='relu', padding='same')(pool1) #14 x 14 x 64\n conv2 = BatchNormalization()(conv2)\n conv2 = Conv2D(64, (5,5), activation='relu', padding='same')(conv2)\n conv2 = BatchNormalization()(conv2)\n conv2 = Conv2D(64, (5,5), activation='relu', padding='same')(conv2)\n conv2 = BatchNormalization()(conv2)\n pool2 = MaxPooling2D(pool_size=(2, 2))(conv2) #7 x 7 x 64\n conv3 = Conv2D(128, (5,5), activation='relu', padding='same')(pool2) #7 x 7 x 128 (small and thick)\n conv3 = BatchNormalization()(conv3)\n conv3 = Conv2D(128, (5,5), activation='relu', padding='same')(conv3)\n conv3 = BatchNormalization()(conv3)\n conv3 = Conv2D(128, (5,5), activation='relu', padding='same')(conv3)\n conv3 = BatchNormalization()(conv3)\n pool3 = MaxPooling2D(pool_size=(2, 2))(conv3) #7 x 7 x 64\n conv4 = Conv2D(256, (5,5), activation='relu', padding='same')(pool3) #7 x 7 x 256 (small and thick)\n conv4 = BatchNormalization()(conv4)\n conv4 = Conv2D(256, (5,5), activation='relu', padding='same')(conv4)\n conv4 = BatchNormalization()(conv4)\n conv4 = Conv2D(256, (5,5), activation='relu', padding='same')(conv4)\n conv4 = BatchNormalization()(conv4)\n pool4 = MaxPooling2D(pool_size=(2, 2))(conv4) #7 x 7 x 64\n conv5 = Conv2D(512, (5,5), activation='relu', padding='same')(pool4) #7 x 7 x 256 (small and thick)\n conv5 = BatchNormalization()(conv5)\n conv5 = Conv2D(512, (5,5), activation='relu', padding='same')(conv5)\n conv5 = BatchNormalization()(conv5)\n conv5 = Conv2D(512, (5,5), activation='relu', padding='same')(conv5)\n conv5 = BatchNormalization()(conv5)\n return conv5\n\ndef decoder(conv5): \n #decoder\n conv6 = Conv2D(256, (5,5), activation='relu', padding='same')(conv5) #7 x 7 x 128\n conv6 = BatchNormalization()(conv6)\n conv6 = Conv2D(256, (5,5), activation='relu', padding='same')(conv6)\n conv6 = BatchNormalization()(conv6)\n conv6 = Conv2D(256, (5,5), activation='relu', padding='same')(conv6)\n conv6 = BatchNormalization()(conv6)\n up1 = UpSampling2D((2,2))(conv6) #14 x 14 x 64\n conv7 = Conv2D(128, (5,5), activation='relu', padding='same')(up1) #7 x 7 x 128\n conv7 = BatchNormalization()(conv7)\n conv7 = Conv2D(128, (5,5), activation='relu', padding='same')(conv7)\n conv7 = BatchNormalization()(conv7)\n conv7 = Conv2D(128, (5,5), activation='relu', padding='same')(conv7)\n conv7 = BatchNormalization()(conv7)\n up2 = UpSampling2D((2,2))(conv7) #14 x 14 x 64\n conv8 = Conv2D(64, (5,5), activation='relu', padding='same')(up2) #7 x 7 x 64\n conv8 = BatchNormalization()(conv8)\n conv8 = Conv2D(64, (5,5), activation='relu', padding='same')(conv8)\n conv8 = BatchNormalization()(conv8)\n conv8 = Conv2D(64, (5,5), activation='relu', padding='same')(conv8)\n conv8 = BatchNormalization()(conv8)\n up3 = UpSampling2D((2,2))(conv8) #14 x 14 x 64\n conv9 = Conv2D(32, (5,5), activation='relu', padding='same')(up3) # 14 x 14 x 32\n conv9 = BatchNormalization()(conv9)\n conv9 = Conv2D(32, (5,5), activation='relu', padding='same')(conv9)\n conv9 = BatchNormalization()(conv9)\n conv9 = Conv2D(32, (5,5), activation='relu', padding='same')(conv9)\n conv9 = BatchNormalization()(conv9)\n up4 = UpSampling2D((2,2))(conv9) # 28 x 28 x 32\n decoded = Conv2D(3, (5,5), activation='sigmoid', padding='same')(up4) # 28 x 28 x 1\n return decoded\n\ndef fc(enco):\n flat = Flatten()(enco)\n den = Dense(128, activation='relu')(flat)\n out = Dense(num_classes, activation='softmax')(den)\n return out\n\n# # custom metric with TF\n# def cohens_kappa(y_true, y_pred):\n# y_true_classes = tf.argmax(y_true, 1)\n# y_pred_classes = tf.argmax(y_pred, 1)\n# return tf.contrib.metrics.cohen_kappa(y_true_classes, y_pred_classes, 10)[1]\n\nautoencoder = Model(input_img, decoder(encoder(input_img)))\nautoencoder.compile(loss='mean_squared_error', \n optimizer = RMSprop())\nprint(autoencoder.summary())\n\n# # Prepare callbacks for model saving.\n# save_dir = '/pool001/bibek/hst/semisupervised/'\\\n# +'deep_autoencoder1'\n# log_dir = os.path.join(save_dir, 'log')\n# model_name = '%s.{epoch:03d}.h5' % 'ae_c5_d10'\n\n# if not os.path.isdir(save_dir):\n# os.makedirs(save_dir)\n# if not os.path.isdir(log_dir):\n# os.makedirs(log_dir)\n# filepath = os.path.join(save_dir, model_name)\n\n# checkpoint = ModelCheckpoint(filepath=filepath,\n# monitor='loss',\n# verbose=1,\n# save_best_only=True,\n# mode='min')\n\n# tensorboard = TensorBoard(log_dir=log_dir, \n# batch_size=batch_size)\n\n# callbacks = [checkpoint, tensorboard]\n\n# autoencoder_train = autoencoder.fit_generator(train_auto,\n# steps_per_epoch = train_auto.samples // batch_size,\n# validation_data = valid_auto,\n# validation_steps = valid_auto.samples // batch_size,\n# epochs = epochs,\n# callbacks = callbacks)\n\n# loss = autoencoder_train.history['loss']\n# val_loss = autoencoder_train.history['val_loss']\n# epochs_plot = range(epochs)\n# plt.figure()\n# plt.plot(epochs_plot, loss, 'bo', label='Training loss')\n# plt.plot(epochs_plot, val_loss, 'b', label='Validation loss')\n# plt.title('Training and validation loss')\n# plt.legend()\n# plt.show()\n\n# autoencoder.save('deep_autoencoder.h5')\n\nautoencoder.load_weights('/pool001/bibek/hst/semisupervised/deep_autoencoder1/ae_c5_d10.017.h5')\n\nencode = encoder(input_img)\nfull_model = Model(input_img,fc(encode))\n\nprint(len(full_model.layers))\nprint(len(autoencoder.layers))\n \nprint(full_model.layers)\nprint(autoencoder.layers)\n\n# full layers: 35\n\nfor l1,l2 in zip(full_model.layers[:19],autoencoder.layers[:19]):\n l1.set_weights(l2.get_weights())\n\nprint(autoencoder.get_weights()[0][1])\nprint(full_model.get_weights()[0][1])\n\n# for layer in full_model.layers[:19]:\n# layer.trainable = False\n \n# full_model.compile(loss=keras.losses.categorical_crossentropy, \n# optimizer=keras.optimizers.Adam(),\n# metrics=['accuracy']) #, cohens_kappa])\n# print(full_model.summary())\n\n# # Prepare callbacks for model saving.\n# save_dir = '/pool001/bibek/hst/semisupervised/'\\\n# +'deep_fixedclf75'\n# log_dir = os.path.join(save_dir, 'log')\n# model_name = '%s.{epoch:03d}.h5' % 'clf_128'\n\n# if not os.path.isdir(save_dir):\n# os.makedirs(save_dir)\n# if not os.path.isdir(log_dir):\n# os.makedirs(log_dir)\n# filepath = os.path.join(save_dir, model_name)\n\n# checkpoint = ModelCheckpoint(filepath=filepath,\n# monitor='acc',\n# verbose=1,\n# save_best_only=True,\n# mode='max')\n\n# tensorboard = TensorBoard(log_dir=log_dir, \n# batch_size=batch_size)\n\n# callbacks = [checkpoint, tensorboard]\n\n# classify_train = full_model.fit_generator(train_batches,\n# steps_per_epoch = train_batches.samples * 0.75 // batch_size,\n# validation_data = valid_batches,\n# validation_steps = valid_batches.samples // batch_size,\n# epochs = epochs,\n# callbacks = callbacks,\n# shuffle = False)\n\n# full_model.save('deep_autoencoder_classification_75.h5')\n\nfor layer in full_model.layers[:19]:\n layer.trainable = True\n \nfull_model.compile(loss=keras.losses.categorical_crossentropy, \n optimizer=keras.optimizers.Adam(),\n metrics=['accuracy']) #, cohens_kappa])\n\n# Prepare callbacks for model saving.\nsave_dir = '/pool001/bibek/hst/semisupervised/'\\\n +'deep_trainclf75_1'\nlog_dir = os.path.join(save_dir, 'log')\nmodel_name = '%s.{epoch:03d}.h5' % 'clf_128'\n\nif not os.path.isdir(save_dir):\n os.makedirs(save_dir)\nif not os.path.isdir(log_dir):\n os.makedirs(log_dir)\nfilepath = os.path.join(save_dir, model_name)\n\ncheckpoint = ModelCheckpoint(filepath=filepath,\n monitor='acc',\n verbose=1,\n save_best_only=True,\n mode='max')\n\ntensorboard = TensorBoard(log_dir=log_dir, \n batch_size=batch_size)\n\ncallbacks = [checkpoint, tensorboard]\n\nclassify_train = full_model.fit_generator(train_batches,\n steps_per_epoch = train_batches.samples * 0.75 // batch_size,\n validation_data = valid_batches,\n validation_steps = valid_batches.samples // batch_size,\n epochs = epochs,\n callbacks = callbacks,\n shuffle = False)\n\nfull_model.save('deep_classification_complete_75_1.h5')\n\naccuracy = classify_train.history['acc']\nval_accuracy = classify_train.history['val_acc']\nloss = classify_train.history['loss']\nval_loss = classify_train.history['val_loss']\nepochs = range(len(accuracy))\nplt.plot(epochs, accuracy, 'bo', label='Training accuracy')\nplt.plot(epochs, val_accuracy, 'b', label='Validation accuracy')\nplt.title('Training and validation accuracy')\nplt.legend()\nplt.figure()\nplt.plot(epochs, loss, 'bo', label='Training loss')\nplt.plot(epochs, val_loss, 'b', label='Validation loss')\nplt.title('Training and validation loss')\nplt.legend()\nplt.show()\n\n# test_eval = full_model.evaluate(test_data, test_Y_one_hot, verbose=0)\n# print('Test loss:', test_eval[0])\n# print('Test accuracy:', test_eval[1])\n","sub_path":"semisupervised/mura_deep_75.py","file_name":"mura_deep_75.py","file_ext":"py","file_size_in_byte":13510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"534557015","text":"import turtle\nfrom random import randint as rand\n\ndef geom(size, lati, ob):\n for i in range(lati):\n ob.forward(size)\n ob.left(360/lati)\n\nob = turtle.Turtle()\nob.speed(0)\nturtle.colormode(255)\nob.hideturtle()\n\nturtle.bgcolor(\"black\")\nob.left(36)\nfor i in range(2000):\n r = rand(0, 255)\n g = rand(0, 255)\n b = rand(0, 255)\n\n ob.color(r, g, b)\n geom(20 + i, 5, ob)\n ob.left(90)\n\nturtle.done()\n","sub_path":"turtle_3.py","file_name":"turtle_3.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"490211108","text":"# Standard library imports\nfrom typing import Callable, Dict, Iterator, Optional\n\n# Third-party imports\nimport pandas as pd\n\n# First-party imports\nfrom gluonts.core.component import validated\nfrom gluonts.dataset.common import Dataset\nfrom gluonts.model.forecast import SampleForecast\nfrom gluonts.model.predictor import RepresentablePredictor\n\nUSAGE_MESSAGE = \"\"\"\nThe `ProphetPredictor` is a thin wrapper for calling the Prophet package.\nIn order to use it you need to install fbprophet\n\npip install fbprophet\n\n\"\"\"\n\n\nclass ProphetPredictor(RepresentablePredictor):\n \"\"\"\n Wrapper around `Prophet `_.\n\n The `ProphetPredictor` is a thin wrapper for calling the Prophet package.\n In order to use it you need to install fbprophet::\n\n pip install fbprophet\n\n Parameters\n ----------\n prediction_length\n Number of time points to predict\n freq\n Time frequency of the data, e.g. \"1H\"\n num_samples\n Number of samples to draw for predictions\n params\n Parameters to pass when instantiating the prophet model,\n e.g. `fbprophet.Prophet(**params)`\n model_callback\n An optional function that will be called with the configured model.\n This can be used to configure more complex setups, e.g.\n\n Examples\n --------\n >>> def configure_model(model):\n ... model.add_seasonality(\n ... name='weekly', period=7, fourier_order=3, prior_scale=0.1\n ... )\n \"\"\"\n\n @validated()\n def __init__(\n self,\n freq: str,\n prediction_length: int,\n num_eval_samples: int = 100,\n params: Optional[Dict] = None,\n model_callback: Optional[Callable] = None,\n ) -> None:\n try:\n import fbprophet\n except ImportError as e:\n raise ImportError(str(e) + USAGE_MESSAGE) from e\n\n self._fbprophet = fbprophet\n\n self.prediction_length = prediction_length\n self.freq = freq\n self.num_eval_samples = num_eval_samples\n self.params = params if params is not None else {}\n assert (\n 'uncertainty_samples' not in self.params\n ), \"parameter 'uncertainty_samples' should not be set directly. Please use num_samples.\"\n self._cb = (\n model_callback if model_callback is not None else lambda m: m\n )\n\n self.params['uncertainty_samples'] = self.num_eval_samples\n self.model_callback = model_callback\n\n def _prepare_input_df(self, d):\n index = pd.date_range(\n d[\"start\"], periods=len(d[\"target\"]), freq=self.freq\n )\n df = pd.DataFrame({\"ds\": index, \"y\": d[\"target\"]})\n return df\n\n def predict(\n self, dataset: Dataset, num_eval_samples=None, **kwargs\n ) -> Iterator[SampleForecast]:\n for entry in dataset:\n if isinstance(entry, dict):\n data = entry\n else:\n data = entry.data\n params = self.params.copy()\n num_eval_samples = (\n num_eval_samples\n if num_eval_samples is not None\n else self.num_eval_samples\n )\n params['uncertainty_samples'] = num_eval_samples\n forecast = self._run_prophet(data, params)\n samples = forecast['yhat'].T\n forecast_start = pd.Timestamp(data['start'], freq=self.freq) + len(\n data['target']\n )\n assert samples.shape == (\n num_eval_samples,\n self.prediction_length,\n ), samples.shape\n yield SampleForecast(\n samples, forecast_start, forecast_start.freqstr\n )\n\n def _run_prophet(self, d, params):\n m = self._fbprophet.Prophet(**params)\n self._cb(m)\n inp = self._prepare_input_df(d)\n model = m.fit(inp)\n future_df = model.make_future_dataframe(\n self.prediction_length, freq=self.freq, include_history=False\n )\n forecast = model.predictive_samples(future_df)\n return forecast\n","sub_path":"src/gluonts/model/prophet/_predictor.py","file_name":"_predictor.py","file_ext":"py","file_size_in_byte":4100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"595334594","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport sys\n\nimport numpy as np\n\ndef main(argv):\n output_ans(argv[0],argv[1])\n\ndef make_matrix_file( n, m, output_file=\"./matrixA.txt\", interval=[0,9] ):\n matrix = np.random.randint( interval[0], interval[1] + 1, size=[n,m])\n np.savetxt(output_file, matrix, fmt=\"%d\")\n return True\n\ndef output_ans(file_A,file_B):\n matrix_A = np.loadtxt( file_A, dtype=int)\n matrix_B = np.loadtxt( file_B, dtype=int)\n ans_one = matrix_A.dot(matrix_B).reshape([1,-1])\n ans_one.sort()\n count = 1\n with open('./ans_one.txt', 'wt') as f:\n for elt in np.nditer(ans_one):\n f.write('{} {}\\n'.format(count, elt))\n count += 1\n return True\n\nif __name__==\"__main__\":\n main(sys.argv[1:])\n","sub_path":"2017ML/HW0/Q1.py","file_name":"Q1.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"80185812","text":"#!/usr/bin/env python\n\nfrom flask import Flask, jsonify, g, request, render_template\nimport sqlite3\nfrom datetime import datetime\nimport time\n\napp = Flask(__name__)\nDATABASE = 'database.db'\n\n\ndef get_db():\n db = getattr(g, '_database', None)\n if db is None:\n db = g._database = sqlite3.connect(DATABASE)\n return db\n\n\n@app.teardown_appcontext\ndef close_connection(exception):\n db = getattr(g, '_database', None)\n if db is not None:\n db.close()\n\nwith app.app_context():\n conn = get_db()\n cursor = get_db().cursor()\n create_tables = (\n ('measurements', ('''CREATE TABLE measurements\n (date real, light real, temp real, moisture real)''',)),\n ('pump', ('''CREATE TABLE pump (state int)''',\n '''INSERT INTO pump VALUES (0)''')),\n ('alerted', ('''CREATE TABLE alerted (state int)''',\n '''INSERT INTO alerted VALUES (0)''')),\n )\n for name, sqls in create_tables:\n try:\n for sql in sqls:\n cursor.execute(sql)\n\n conn.commit()\n except sqlite3.OperationalError:\n print(\"Table %s already created\" % (name,))\n\n\n@app.route(\"/pumpstate\")\ndef pumpstate():\n conn = get_db()\n cursor = conn.cursor()\n sql = \"SELECT * FROM pump\"\n cursor.execute(sql)\n state = cursor.fetchone()\n\n state = state[0]\n\n return jsonify(state=state)\n\n\n@app.route(\"/data\", methods=['POST'])\ndef data():\n\n temp = request.form.get('temp')\n moisture = request.form.get('moisture')\n light = request.form.get('ldr')\n\n conn = get_db()\n cursor = conn.cursor()\n\n t = datetime.utcnow()\n epoch = time.mktime(t.timetuple())\n\n sql = \"INSERT INTO measurements VALUES (%s,%s,%s,%s)\"\n cursor.execute(sql % (epoch, light, temp, moisture))\n conn.commit()\n\n result = \"temp: %s light: %s moisture: %s\" % (temp, light, moisture,)\n\n sql = \"SELECT * FROM alerted\"\n cursor.execute(sql)\n state = cursor.fetchone()\n if int(moisture) <= 2 and state[0] is 0:\n sql = \"UPDATE alerted SET state=1\"\n cursor.execute(sql)\n conn.commit()\n\n print('Moisture below 2, triggering SMS')\n # Uncommect this to enable texts\n #spawn(_send_sms_alert, moisture, False)\n\n elif int(moisture) > 2 and state[0] is 1:\n sql = \"UPDATE alerted SET state=0\"\n cursor.execute(sql)\n conn.commit()\n\n print('Moisture above 2, triggering SMS')\n # Uncommect this to enable texts\n #spawn(_send_sms_alert, moisture, True)\n\n return result\n\n\n@app.route(\"/\")\ndef index():\n data = fetch_data()\n return render_template('front.html',\n light=data[0]['data'],\n humid=data[2]['data'],\n temp=data[1]['data'])\n\n\n@app.route(\"/all.json\")\ndef all_json():\n data = fetch_data()\n return jsonify(light=data[0]['data'],\n humid=data[2]['data'],\n temp=data[1]['data'])\n\n\n@app.route(\"/light\")\ndef light():\n data = fetch_data()[0]\n return render_template('light.html', data=data['data'])\n\n\n@app.route(\"/light.json\")\ndef light_json():\n data = fetch_data()[0]\n return jsonify(data=data['data'])\n\n\n@app.route(\"/humidity\")\ndef humid():\n data = fetch_data()[2]\n return render_template('humid.html', data=data['data'])\n\n\n@app.route(\"/humidity.json\")\ndef humid_json():\n data = fetch_data()[2]\n return jsonify(data=data['data'])\n\n\n@app.route(\"/logout\")\ndef logout():\n return render_template('logout.html')\n\n\n@app.route(\"/pump\")\ndef pump():\n return render_template('pump.html')\n\n\n@app.route(\"/temperature\")\ndef temp():\n data = fetch_data()[1]\n return render_template('temp.html', data=data['data'])\n\n\n@app.route(\"/temperature.json\")\ndef temp_json():\n data = fetch_data()[1]\n return jsonify(data=data['data'])\n\n\ndef fetch_data():\n\n conn = get_db()\n cursor = conn.cursor()\n epoch = time.mktime(datetime.utcnow().timetuple())\n sql = \"SELECT * FROM measurements WHERE date > %s\" % (epoch - 300)\n cursor.execute(sql)\n series = [\n dict(name=\"light\", data=[]),\n dict(name=\"temp\", data=[]),\n dict(name=\"moisture\", data=[]),\n ]\n for date, light, temp, moisture in cursor.fetchall():\n date = date * 1000\n series[0]['data'].append([date, light])\n series[1]['data'].append([date, temp])\n series[2]['data'].append([date, moisture])\n return series\n\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0')\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"60735803","text":"import numpy as np \nimport cv2\n\nimg = cv2.imread(\"Chrysanthemum.jpg\")\ncv2.imshow(\"Original\", img)\n\ncv2.namedWindow(\"Processed\")\n\ndef do_nothing():\n return\n\ncv2.createTrackbar('Helligkeit', 'Processed', 0, 255, do_nothing)\n\n# alle 30 ms Slider abfragen und Helligkeit ändern\nwhile True:\n brightness = cv2.getTrackbarPos('Helligkeit', 'Processed')\n processedImage = cv2.add(img, (brightness, brightness, brightness, 0))\n cv2.imshow('Processed', processedImage)\n\n # Abbruch bei Tastendruck\n if cv2.waitKey(30) != -1:\n break\n\ncv2.destroyAllWindows()","sub_path":"1. Woche/opencv_slider.py","file_name":"opencv_slider.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"104886413","text":"import sys,os\nimport re\nimport requests\nimport time\nfrom bs4 import BeautifulSoup\n\nproject_dir = '../deputat/deputat/'\n\nsys.path.append(project_dir)\nos.environ['DJANGO_SETTINGS_MODULE'] = 'settings'\nimport django\ndjango.setup()\n\nfrom lists.models import *\nfrom elect.models import *\n\n\ndef get_html(url):\n r = requests.get(url)\n return r.text\n\ndef get_links(url):\n soup = BeautifulSoup(url, 'lxml')\n list = []\n container = soup.find('section', class_='list-persons__wrapper js-deputies-wrapper')\n blocks = container.find_all('a', class_='person__image-wrapper person__image-wrapper--s')\n for item in blocks:\n list += ['http://duma.gov.ru' + item['href'], ]\n return list\n\n\ndef get_educations_for_elect(html, elect):\n soup = BeautifulSoup(html, 'lxml')\n try:\n definitions_list_2 = soup.find('dl', class_='definitions-list definitions-list--capitalize')\n edu_count = 0\n edu_dd = definitions_list_2.find_all('dd')\n edu_dt = definitions_list_2.find_all('dt')\n for dd in edu_dd:\n EducationElect.objects.create(elect=elect, title=edu_dd[edu_count].text, year=edu_dt[edu_count].text)\n edu_count += 1\n except:\n pass\n\ndef get_page_data(html):\n soup = BeautifulSoup(html, 'lxml')\n\n # name\n name = soup.find('h1', class_='article__title--person')\n if name:\n _name = str(name)\n _name = _name.replace('\\n', '').replace('

', '').replace('
', ' ').replace('

', '')\n else:\n name = soup.find('h2', class_='person__title person__title--l')\n _name = str(name)\n _name = _name.replace('\\n', '').replace('

', '').replace('
', ' ').replace('

', '').replace('', '')\n\n #description\n #description = soup.find('div', class_='article__lead article__lead--person')\n #if not description:\n # description = soup.find('div', class_='page__lead')\n description = \"\"\n\n #image\n image = soup.find('img', class_='person__image person__image--mobile')\n if not image:\n image = soup.find('img', class_='person__image person__image--l')\n\n #birthday, authorization\n content__s = soup.find('div', class_='content--s')\n birthday = content__s.find_all('p')[0].text\n birthday = birthday.replace('Дата рождения: ', '')\n authorization = content__s.find_all('p')[1].text\n authorization = authorization.replace('\\n', '').strip().replace('Дата вступления в полномочия: ', '')\n\n #election_information\n definitions_list_1 = soup.find_all('dl', class_='definitions-list')[0]\n dd_1 = definitions_list_1.find('dd')\n election_information = dd_1.find_all('p')[0].text + definitions_list_1.find('dt').text\n election_information = election_information.replace('\\n', '').strip().replace(' ', ':')\n\n #fraction\n person__description = soup.find('div', class_='person__description__grid')\n fraction = person__description.find('a', class_='person__description__link').text\n\n try:\n region_list = soup.find_all('div', class_='person__description__col')[3].text.replace(\", \", \",\")\n except:\n region_list = []\n\n data = {'name': _name,\n 'fraction': fraction.replace(\"\\xa0\", \" \"),\n 'elect_image': 'http://duma.gov.ru' + image['src'],\n 'description': description,\n 'region_list': region_list,\n 'birthday': birthday,\n 'election_information': election_information,\n 'authorization': authorization}\n return data\n\n\ndef main():\n html = get_html(\"http://duma.gov.ru/duma/deputies/8/\")\n lists = get_links(html)\n candidate_list = AuthorityList.objects.get(slug=\"candidate_duma\")\n deputat_list = AuthorityList.objects.get(slug=\"state_duma\")\n new_list = AuthorityList.objects.get(slug=\"state_duma_21_26\")\n\n for url in lists:\n html = get_html(url)\n data = get_page_data(html)\n if Elect.objects.filter(list=candidate_list, name=data[\"name\"]).exists():\n elect = Elect.objects.get(list=candidate_list, name=data[\"name\"])\n elect.list.add(new_list)\n print(\"Этот уже есть... \", data[\"name\"])\n elif Elect.objects.filter(list=deputat_list, name=data[\"name\"]).exists():\n elect = Elect.objects.get(list=deputat_list, name=data[\"name\"])\n elect.list.add(new_list)\n print(\"Этот уже есть... \", data[\"name\"])\n else:\n if data[\"fraction\"] == '«ЕДИНАЯ РОССИЯ»':\n current_fraction = Fraction.objects.get(slug=\"edinaya_russia\")\n elif data[\"fraction\"] == \"СПРАВЕДЛИВАЯ РОССИЯ\":\n current_fraction = Fraction.objects.get(slug=\"spravedlivaya_russia\")\n elif data[\"fraction\"] == \"КПРФ\":\n current_fraction = Fraction.objects.get(slug=\"kprf\")\n elif data[\"fraction\"] == \"ЛДПР\":\n current_fraction = Fraction.objects.get(slug=\"ldpr\")\n elif data[\"fraction\"] == \"Депутаты, не входящие во фракции\":\n current_fraction = Fraction.objects.get(slug=\"no_fraction\")\n\n new_elect = Elect.objects.create(name=data[\"name\"], birthday=data[\"birthday\"], authorization=data[\"authorization\"], election_information=data[\"election_information\"], fraction=current_fraction)\n regions_query = data[\"region_list\"]\n if regions_query:\n regions_query = data[\"region_list\"].split(\",\")\n for region_name in regions_query:\n try:\n region = Region.objects.get(name=region_name)\n region.elect_region.add(new_elect)\n except:\n pass\n new_elect.get_remote_image(data[\"elect_image\"])\n new_elect.list.add(new_list)\n print(\"Этот создан! \", data[\"name\"])\n time.sleep(2)\n\nif __name__ == '__main__':\n main()\n","sub_path":"duma_parsing.py","file_name":"duma_parsing.py","file_ext":"py","file_size_in_byte":6166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"359401264","text":"import magma as m\nimport fault\nimport tempfile\nimport pytest\nfrom pathlib import Path\nfrom .common import pytest_sim_params, TestBasicCircuit\n\ndef plot(xs, ys):\n import matplotlib.pyplot as plt\n plt.plot(xs, ys, '*')\n plt.grid()\n plt.show()\n\ndef pytest_generate_tests(metafunc):\n #pytest_sim_params(metafunc, 'verilator', 'system-verilog')\n #pytest_sim_params(metafunc, 'spice')\n pytest_sim_params(metafunc, 'system-verilog')\n\n#@pytest.mark.skip(reason='Not yet implemented')\ndef test_clock_verilog(target, simulator):\n print('target, sim', target, simulator)\n # TODO delete the next line; my iverilog is just broken so I can't test it\n simulator = 'ncsim'\n circ = TestBasicCircuit\n tester = fault.Tester(circ)\n tester.zero_inputs()\n tester.poke(circ.I, 1)\n #tester.eval()\n tester.expect(circ.O, 1)\n\n # register clock\n tester.poke(circ.I, 0, delay={\n 'freq': 0.125,\n 'duty_cycle': 0.625,\n # take default initial_value of 0\n })\n\n tester.expect(circ.O, 1) # should fail\n tester.expect(circ.O, 0) # should fail\n\n\n tester.expect(circ.O, 0, save_for_later=True)\n\n\n tester.print(\"%08x\", circ.O)\n\n \n #with tempfile.TemporaryDirectory(dir=\".\") as _dir:\n #with open('build/') as _dir:\n if True:\n _dir = 'build'\n if target == \"verilator\":\n tester.compile_and_run(target, directory=_dir, flags=[\"-Wno-fatal\"])\n else:\n tester.compile_and_run(target, directory=_dir, simulator=simulator)\n print('JUST FINISHED COMPILENANDRUN')\n\n\n@pytest.mark.skip(reason='Turn this back on later')\ndef test_sin_spice(vsup=1.5, vil_rel=0.4, vih_rel=0.6,\n vol_rel=0.1, voh_rel=0.9):\n # TODO make pytest choose target/simulator\n target = 'spice'\n simulator = 'ngspice'\n \n\n\n # declare circuit\n myinv = m.DeclareCircuit(\n 'myinv',\n 'in_', fault.RealIn,\n 'out', fault.RealOut,\n 'vdd', fault.RealIn,\n 'vss', fault.RealIn\n )\n\n # wrap if needed\n if target == 'verilog-ams':\n dut = fault.VAMSWrap(myinv)\n else:\n dut = myinv\n\n # define the test\n tester = fault.Tester(dut)\n tester.poke(dut.vdd, vsup)\n tester.poke(dut.vss, 0)\n freq = 1e3\n tester.poke(dut.in_, 0, delay = {\n 'type': 'sin',\n 'freq': freq,\n 'amplitude': 0.4,\n 'offset': 0.6,\n 'phase_degrees': 90\n })\n\n num_reads = 100\n xs = []\n dt = 1/(freq * 50)\n for k in range(num_reads):\n tester.expect(dut.in_, 0, save_for_later=True)\n tester.delay(dt)\n xs.append(k*dt)\n\n #for k in [.4, .5, .6]:\n # in_ = k * vsup\n # tester.poke(dut.in_, in_)\n # # We might not know the expected value now but will want to check later\n # tester.expect(dut.out, 0, save_for_later=True)\n\n \n\n # set options\n kwargs = dict(\n target=target,\n simulator=simulator,\n model_paths=[Path('tests/spice/myinv.sp').resolve()],\n vsup=vsup,\n tmp_dir=True,\n clock_step_delay = 0\n )\n if target == 'verilog-ams':\n kwargs['use_spice'] = ['myinv']\n\n # run the simulation\n tester.compile_and_run(**kwargs)\n\n ys = []\n for k in range(num_reads):\n value = tester.targets[target].saved_for_later[k]\n ys.append(value)\n print('%2d\\t'%k, value)\n\n plot(xs, ys)\n","sub_path":"tests/test_background_poke.py","file_name":"test_background_poke.py","file_ext":"py","file_size_in_byte":3379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"547611837","text":"#!/usr/bin/env python3\nfrom ruamel.yaml import YAML\nimport argparse\n\nyaml = YAML(typ='safe')\nif __name__ == '__main__':\n p = argparse.ArgumentParser(description=\"VMEmperor Ansible inventory generator\")\n p.add_argument('--list', action='store_true')\n p.add_argument('--host')\n\n args = p.parse_args()\n if args.list:\n print('generate host list')\n\n if args.host:\n print('print host info: ', args.host)\n\nwith open('ansible/wordpress-nginx/group_vars/all') as file:\n print(yaml.load(file))\n\nwith open('ansible/wordpress-nginx/vmemperor.conf') as file:\n print(yaml.load(file))","sub_path":"ansible_inventory.py","file_name":"ansible_inventory.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"205976710","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n@Author : Xu\n\n@Software: PyCharm\n\n@File : intent_classification.py\n\n@Time : 2020/11/10 3:03 下午\n\n@Desc : 意图分类模型 transformer + onnx\n\n\"\"\"\n\nimport os\nimport sys\nimport logging\nimport pandas as pd\nimport tensorflow as tf\nimport keras2onnx\nfrom onnxruntime_tools import optimizer\nfrom transformers import BertConfig\nfrom transformers import BertTokenizer\nfrom transformers import TFBertForSequenceClassification\nfrom sklearn.model_selection import train_test_split\n\nsys.path.append('../../../')\nfrom models.intent_core.model.config import Config\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\"\n\nlogging.basicConfig(format='%(levelname)s:%(message)s', level=logging.INFO)\n\nconf = Config() # 初始化配置文件(超参数配置、数据、预训练资源配置等)\n\n\ndef tf_keras_convert_to_onnx(models, paths, config):\n \"\"\"\n 将keras模型转换为onnx\n :param models:\n :param paths:\n :param config:\n :return:\n \"\"\"\n onnxNerBert = keras2onnx.convert_keras(\n models,\n models.name,\n target_opset=12\n )\n keras2onnx.save_model(\n onnxNerBert,\n paths\n )\n optimized_model = optimizer.optimize_model(\n paths,\n model_type='bert_keras',\n num_heads=config.num_attention_heads,\n hidden_size=config.hidden_size\n )\n optimized_model.use_dynamic_axes()\n optimized_model.save_model_to_file(\n paths\n )\n\n\ndef get_labels():\n return sorted(conf.labels, key=conf.labels.index)\n\n\ndef split_dataset(df):\n \"\"\"\n 数据切分\n :param df:\n :return:\n \"\"\"\n train_set, x = train_test_split(df,\n stratify=df['label'],\n test_size=0.1,\n random_state=42,\n shuffle=True)\n val_set, test_set = train_test_split(x,\n # stratify=x['label'], # 确保每一类都被抽样到\n test_size=0.5,\n random_state=43,\n shuffle=True)\n\n return train_set, val_set, test_set\n\n\nclass OurTokenizer(BertTokenizer):\n def _tokenize(self, text):\n R = []\n for c in text:\n if c in self.vocab:\n R.append(c)\n elif c.isspace():\n R.append('[unused1]') # space类用未经训练的[unused1]表示\n else:\n R.append('[UNK]') # 剩余的字符是[UNK]\n return R\n\n\nclass DataProcess:\n \"\"\"\n 数据预处理\n \"\"\"\n\n\nclass BertClassifcation(object):\n def __init__(self, config):\n super(BertClassifcation, self).__init__()\n self.pretrain_path = config.pretrain_model_dir\n self.tokenizer = OurTokenizer.from_pretrained(os.path.join(self.pretrain_path, \"vocab.txt\"),\n do_lower_case=True)\n self.max_length = config.max_length\n self.batch_size = config.batch_size\n self.learning_rate = config.learn_rate\n self.number_of_epochs = config.epochs\n self.num_classes = config.num_classes # 类别数\n self.model_path = config.model_path\n self.labels = config.labels\n\n def convert_example_to_feature(self, review):\n # combine step for tokenization, WordPiece vector mapping, adding special tokens as well as truncating reviews longer than the max length\n return self.tokenizer.encode_plus(review,\n add_special_tokens=True, # add [CLS], [SEP]\n max_length=self.max_length, # max length of the text that can go to BERT\n pad_to_max_length=True, # add [PAD] tokens\n return_attention_mask=True, # add attention mask to not focus on pad tokens\n truncation=True\n )\n\n def encode_examples(self, ds, limit=-1):\n # prepare list, so that we can build up final TensorFlow dataset from slices.\n def map_example_to_dict(input_ids, attention_masks, token_type_ids, label):\n \"\"\"map to the expected input to TFBertForSequenceClassification, see here\"\"\"\n return {\n \"input_ids\": input_ids,\n \"token_type_ids\": token_type_ids,\n \"attention_mask\": attention_masks,\n }, label\n\n input_ids_list = []\n token_type_ids_list = []\n attention_mask_list = []\n label_list = []\n if (limit > 0):\n ds = ds.take(limit)\n\n for index, row in ds.iterrows():\n review = row[\"content\"]\n label = row[\"y\"]\n bert_input = self.convert_example_to_feature(review)\n\n input_ids_list.append(bert_input['input_ids'])\n token_type_ids_list.append(bert_input['token_type_ids'])\n attention_mask_list.append(bert_input['attention_mask'])\n label_list.append([label])\n return tf.data.Dataset.from_tensor_slices(\n (input_ids_list, attention_mask_list, token_type_ids_list, label_list)).map(map_example_to_dict)\n\n def model_build(self):\n self.bertConfig = BertConfig.from_pretrained(\n os.path.join(self.pretrain_path, \"config.json\"),\n num_labels=self.num_classes\n )\n self.model = TFBertForSequenceClassification.from_pretrained(\n os.path.join(self.pretrain_path, \"tf_model.h5\"),\n config=self.bertConfig\n )\n self.model.summary()\n\n def compile(self):\n # optimizer Adam recommended\n optimizer = tf.keras.optimizers.Adam(learning_rate=self.learning_rate, epsilon=1e-08, clipnorm=1)\n # we do not have one-hot vectors, we can use sparce categorical cross entropy and accuracy\n loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)\n metric = tf.keras.metrics.SparseCategoricalAccuracy('accuracy')\n self.model.compile(optimizer=optimizer, loss=loss, metrics=[metric])\n\n def train(self, dfRaw):\n train_data, val_data, test_data = split_dataset(dfRaw)\n # 数据编码\n # train dataset\n ds_train_encoded = self.encode_examples(train_data).shuffle(10000).batch(\n self.batch_size)\n # val dataset\n ds_val_encoded = self.encode_examples(val_data).batch(self.batch_size)\n # test dataset\n ds_test_encoded = self.encode_examples(test_data).batch(self.batch_size)\n # model initialization\n self.model_build()\n self.compile()\n # fit model\n my_callbacks = [\n tf.keras.callbacks.ReduceLROnPlateau(monitor='val_loss',\n factor=0.5,\n patience=3,\n min_lr=1e-6),\n tf.keras.callbacks.EarlyStopping(monitor='val_accuracy', patience=3, mode='max'),\n tf.keras.callbacks.ModelCheckpoint(filepath=self.model_path, save_weights_only=True,\n monitor='val_accuracy', mode='max', save_best_only=True)\n ]\n bert_history = self.model.fit(ds_train_encoded,\n epochs=self.number_of_epochs,\n validation_data=ds_val_encoded,\n verbose=2,\n callbacks=my_callbacks\n )\n # res = self.model.predict([\"我爱你\"])\n # evaluate test_set\n logging.info(\"# evaluate test_set:\", self.model.evaluate(ds_test_encoded))\n tf_keras_convert_to_onnx(\n self.model,\n self.model_path,\n self.bertConfig\n )\n\n def predict(self, sentences):\n features = self.tokenizer.batch_encode_plus(\n sentences,\n add_special_tokens=True,\n return_tensors=\"tf\",\n max_length=self.max_length,\n pad_to_max_length=True,\n return_attention_mask=True,\n truncation=True\n )\n\ndef app():\n customerData = pd.read_csv(conf.data_path, header=0, sep='\\t').dropna(axis=0, inplace=False)\n logging.info(customerData.head())\n dfLables = pd.DataFrame({\"label\": conf.labels, \"y\": list(range(conf.num_classes))})\n dfRaw = pd.merge(customerData, dfLables, on=\"label\", how=\"left\")\n logging.info(dfRaw.head())\n bertModel = BertClassifcation(conf)\n bertModel.train(dfRaw)\n\n\nif __name__ == '__main__':\n app()\n","sub_path":"models/intent_core/model/intent_classification.py","file_name":"intent_classification.py","file_ext":"py","file_size_in_byte":8778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"976894","text":"#!/usr/bin/env python\n# HW03_ex06\n# (1) Please comment your code.\n# (2) Please be thoughtful when naming your variables.\n# (3) Please remove development code before submitting.\n\nimport math\n###############################################################################\n# Exercise 6.2\n# See 6.1: \"write a compare function takes two values, x and y, and returns 1\n# if x > y, 0 if x == y, and -1 if x < y.\"\n# When you submit only include your final function: compare\n#function to compare the values x and y\ndef compare(x,y):\n # if x > y return 1\n if(x > y):\n return 1\n # if x == y return 0\n if(x == y):\n return 0\n #if x < y return -1\n if(x < y):\n return -1\n \n\n\n\n\n###############################################################################\n# Exercise 6.2\n# See 6.2: \"use incremental development to write a function called hypotenuse\n# that returns the length of the hypotenuse of a right triangle given the\n# lengths of the other two legs as arguments.\"\n# When you submit only include your final function: hypotenuse\n# Do develop incrementally. Do not share in your final push your incremental\n# work.\n# function to find hypotenuse given the 2 sides\ndef hypotenuse(side1,side2):\n # the hypotenuse is square root of sum of the squares of other 2 sides\n hypotenuse = math.sqrt(side1**2 + side2**2)\n return round(hypotenuse,2)\n \n\n\n\n###############################################################################\n# Exercise 6.4\n# See 6.4: \"write a function is_between(x, y, z) that returns True if x ≤ y ≤ z\n# or False otherwise\"\n# When you submit only include your final function: is_between\n#function to check if a value 'y' is between x and y\ndef is_between(x, y, z):\n #return true if y is greater than or equal to x and less than or equal to z\n if(x <= y <= z):\n return True\n #return false otherwise\n else:\n return False\n\n\n\n###############################################################################\n# Exercise 3.2\n# See \"Exercise 3, part 2\": \"Write a function called is_palindrome that takes a\n# string argument and returns True if it is a palindrome and False otherwise.\n# Remember that you can use the built-in function len to check the length of a\n# string.\"\n# When you submit only include your final function: is_palindrome\n\n#function to check is a string is palindrome\ndef is_palindrome(string_val):\n String_length = len(string_val)\n #base case return 1 if length is 1\n if(String_length == 1):\n return True\n #if length is more than 2, compare first and last characters\n if(String_length >= 2):\n if(first(string_val) == last(string_val)):\n #if string is 2 characters and are same-return true\n if(String_length == 2):\n return True\n # else check the remaining string after slicing\n else:\n return is_palindrome(string_val[1:-1])\n #if the first and last characters are not equal - return false\n else:\n return False\n \n#helper function for palindrome\n #.lower() method to ignore case\ndef first(word):\n return word[0:1].lower()\ndef middle(word):\n return word[1:-1].lower()\ndef last(word):\n return word[-1].lower()\n \n\n\n###############################################################################\n# Exercise 4\n# See \"Exercise 4\": \"A number, a, is a power of b if it is divisible by b and\n# a/b is a power of b. Write a function called is_power that takes parameters a\n# and b and returns True if a is a power of b. Note: you will have to think\n# about the base case.\"\n# Note: Please use the provided definition and only plan for positive integers\n# (whole numbers not including zero)\n# When you submit only include your final function: is_power\n\n#function to check if a value is the power of another value\ndef is_power(a,b):\n #if the value after a division call is 1 - it means its the same number\n # which was divided and its a power - if not it would have failed in the % check\n if(a == 1):\n return True\n #if it is divisible without a remainder it is a power\n if ((a % b == 0) and (is_power(a/b,b))):\n return True\n else:\n return False\n\n\n\n###############################################################################\ndef main():\n \"\"\"Your functions will be called within this function.\"\"\"\n ###########################################################################\n # Use this space temporarily to call functions in development:\n print(\"Hello World!\")\n\n\n\n\n\n\n ###########################################################################\n # # Uncomment the below to test and before commiting:\n # # Exercise 1\n print(compare(1, 1))\n print(compare(1, 2))\n print(compare(2, 1))\n # # # Exercise 2\n print(hypotenuse(1, 1))\n print(hypotenuse(3, 4))\n print(hypotenuse(1.2, 12))\n # # # Exercise 3\n print(is_between(1, 2, 3))\n print(is_between(2, 1, 3))\n print(is_between(3, 1, 2))\n print(is_between(1, 1, 2))\n # # # Exercise 6\n print(is_palindrome(\"Python\"))\n print(is_palindrome(\"evitative\"))\n print(is_palindrome(\"sememes\"))\n print(is_palindrome(\"oooooooooooo\"))\n #print(is_palindrome(\"Racecar\"))\n # # # Exercise 7\n print(is_power(28, 3))\n print(is_power(27, 3))\n print(is_power(248832, 12))\n print(is_power(248844, 12))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"HW03_ex06.py","file_name":"HW03_ex06.py","file_ext":"py","file_size_in_byte":5424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"448130925","text":"from datetime import datetime\nimport re\n\nfrom django_celery_results.models import TaskResult\n\nfrom main.models import CSCU, ServerCommand, Server, Contour, User\n\n\ndef get_user(object):\n # function returns model-referenced user-object\n\n def get_from_request(obj):\n # function returns user-object from request attr\n return getattr(getattr(obj, 'request'), 'user')\n\n if 'request' in dir(object):\n return get_from_request(object)\n elif 'view' in dir(object):\n return get_from_request(getattr(object['view']))\n elif hasattr(object, 'scope'):\n if 'user' in getattr(object, 'scope'):\n return getattr(object, 'scope').get('user')\n else:\n raise TypeError('Can not return user from object {}'.format(type(object)))\n\n\ndef is_superuser(user_pk):\n return User.objects.get(pk=user_pk).is_superuser\n\n\ndef get_contour(user_pk, server_pk):\n if is_superuser(user_pk) != True:\n contour = Contour.objects.get(server__id=server_pk, permission__user__pk=user_pk)\n else:\n contour = Contour.objects.get(server__id=server_pk)\n\n return contour\n\n\ndef get_server(user_pk, server_pk):\n #\n # Function for server validation, saves from invoking server that does not available for current user\n # returns Serverinstance\n\n # should pass permission__user here for safer execution with permissions\n # user can not invoke server with no permissions for it\n if is_superuser(user_pk) != True:\n server = Server.objects.get(pk=server_pk, permission__user__pk=user_pk)\n else:\n server = Server.objects.get(pk=server_pk)\n\n if not server:\n raise KeyError('Server with pk {} is not permitted for this user.'.format(server_pk))\n\n return server\n\n\ndef get_command_for_server(user_pk, server_pk, command_pk, add_args=None):\n #\n # Function for command validation, saves from executing command that does not exist for the chosen server\n # or not available for current user\n # returns ServerCommand instance\n\n # should pass permission__user here for safer execution with permissions\n # user can not execute command with no permissions for it\n\n def set_command_additional_parameters(command_text, add_args):\n for arg in zip(add_args['pk'], add_args['value']):\n command_text = re.sub(u'\\%({})\\|([\\w\\s]+)\\%'.format(arg[0]), arg[1], command_text)\n\n return command_text\n\n if is_superuser(user_pk) != True:\n server_command = ServerCommand.cobjects. \\\n get(permission__user__pk=user_pk, server=get_server(user_pk, server_pk), pk=command_pk)\n else:\n server_command = ServerCommand.objects.get(pk=command_pk)\n\n if not server_command:\n raise KeyError('Command with pk {} does not exist for this server.'.format(command_pk))\n\n if add_args:\n return set_command_additional_parameters(server_command.command, add_args)\n else:\n return server_command.command\n\n\ndef get_command_additional_parameters(**kwargs):\n def get_attr_name(command_text):\n return re.findall(u'\\%([A-Z_]+)\\|([\\w\\s]+)\\%', command_text)\n\n if kwargs.get('command_pk'):\n return get_attr_name(ServerCommand.objects.get(pk=kwargs['command_pk']).command)\n elif kwargs.get('command_text'):\n return get_attr_name(kwargs['command_text'])\n else:\n return None\n\n\ndef create_cscu_start(user_pk, server_pk, command_pk, add_args=None):\n cscu_obj = CSCU.objects.create(contour_id=get_contour(user_pk, server_pk).pk, server_id=server_pk,\n servercommand_id=command_pk, parameters='\\n'.join(add_args), user_id=user_pk,\n locked_status=True, start_time=datetime.now())\n return cscu_obj.pk\n\n\ndef create_cscu_finish(cscu_pk, cmd_output, is_success=True):\n # should not use update method here\n # because there no signal is sending using it\n # cscu = CSCU.objects.filter(pk=cscu_pk).update(locked_status=False, end_time=datetime.now(),\n # cmd_output=cmd_output, is_success=is_success)\n cscu = CSCU.objects.get(id=cscu_pk)\n\n cscu.locked_status = False\n cscu.end_time = datetime.now()\n cscu.cmd_output = cmd_output\n cscu.is_success = is_success\n # cscu.celery_task_id = task_id\n\n cscu.save()\n\n\ndef unpack_list(params):\n for e in params:\n if isinstance(params[e], dict):\n if len(params[e].get('pk')) == 1:\n params[e]['pk'] = ''.join(params[e].get('pk'))\n if len(params[e].get('value')) == 1:\n params[e]['value'] = ''.join(params[e].get('value'))\n\n return params\n\nclass HistoryLogger():\n def __init__(self, server, command, user, start_time):\n self.cscu = CSCU.objects.create(contour=server.contour, server=server,\n servercommand=command, user=user,\n locked_status=True, start_time=start_time)\n\n def save(self, force_update=False):\n self.cscu.save(force_update=force_update)\n\n def unlock_command(self, end_time):\n self.cscu.locked_status = False\n self.cscu.end_time = end_time\n self.cscu.is_success = True\n self.save(force_update=True)\n","sub_path":"main/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":5240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"29558280","text":"'''Le module sudothinkai contient la classe SudoThinkAI.\nThinkAI est la classe qui encapsule la simulation d'intelligence. Celle-ci va\npermettre au joueur simulé de choisir comment il poursuit sa résolution, en\ncherchant de l'information dans la grille et en sélectionnant les techniques\nles plus appropriées en fonction de l'état présent de la grille et d'un\n\"savoir-faire\" de résolution, éventuellement sujet à de l'apprentissage.\nC'est ici que sera évalué la décision d'abandon si aucune technique ne permet\nde faire de nouveau placement.\n\nDans la classe SudoAI, contrairement à toutes les autres classes du programme,\nl'information utilisée dans la résolution est considérée comme un savoir\npermanent, non sujet à l'obsolescence de la mémoire de travail. C'est le\nsavoir-faire du joueur, sa capacité globale à \"jouer au Sudoku\".\n\nHistorique des mises-à-jour\n22/10/2017 Déport dans un sous-module de la fonction qui propose une\ntechnique. Le code de suggestAction() est déporté dans cette fonction. De cette\nmanière il est simple (dans la phase de développement) de modifier la\nstratégie de résolution sans toucher au code générique.\n\nTEST :\nCe module importe le module 'sudotest' et utilise l'objet global sudoTest de\nclasse SudoTest pour gérer de manière paramétrable les I/O de test du code.\n'''\n\n\n##IMPORTS DU MOTEUR DE SIMULATION\n#exécution interne au package\nif __name__ in (\"__main__\", \"sudothinkai_testlplcp\"):\n import sudobaseclass as base\n import sudoenv\n import sudoui as ui\n import sudorules as rules\n from sudorules import Sudoku_Error\n from sudomemory import SudoMemory\n import sudoai as ai\n#exécution depuis l'extérieur du package sudosimu\nelif __name__ == \"sudosimu.sudothinkai_testlplcp\":\n from sudosimu import sudobaseclass as base\n from sudosimu import sudoenv\n from sudosimu import sudoui as ui\n from sudosimu import sudorules as rules\n from sudosimu.sudorules import Sudoku_Error\n from sudosimu.sudomemory import SudoMemory\n from sudosimu import sudoai as ai\n#import sudoknowledge\nelse:\n raise Exception(\"Impossible de faire les imports dans le module sudothinkai.\")\n\n##IMPORTS DES MODULES DE TECHNIQUES DE RESOLUTION\nif __name__ in (\"__main__\", \"sudothinkai_testlplcp\"):\n from sudotechimports import *\nelif __name__ == \"sudosimu.sudothinkai_lplcp\":\n from sudosimu.sudotechimports import *\nelse:\n raise Exception(\"Impossible de faire les imports dans le module sudothinkai.\")\n\n##if __name__ in (\"__main__\", \"sudothinkai_testlplcp\"):\n## #Chiffre/rang-colonne\n## from techchrc.techchrcr import TechChRCrow #par rang pour un chiffre\n## from techchrc.techchrcc import TechChRCcol #par colonne pour un chiffre\n## from techchrc.techchrcg import TechChRCgrid #grille entière pour un chiffre\n## from techchrc.techchrcga import TechChRCgridAll #grille entière tous les chiffres\n## #Dernier placement\n## from techlplc.techlplcr import TechLastPlcRow #sur un rang\n## from techlplc.techlplcc import TechLastPlcCol #sur une colonne\n## from techlplc.techlplcs import TechLastPlcSqr #sur un carré\n## from techlplc.techlplcp import TechLastPlcPlace #sur une case (place)\n## from techlplc.techlplcg import TechLastPlcGrid #sur la grille entière\n##elif __name__ == \"sudosimu.sudothinkai_testlplcp\":\n## #Chiffre/rang-colonne\n## from sudosimu.techchrc.techchrcr import TechChRCrow #par rang pour un chiffre\n## from sudosimu.techchrc.techchrcc import TechChRCcol #par colonne pour un chiffre\n## from sudosimu.techchrc.techchrcg import TechChRCgrid #grille entière pour un chiffre\n## from sudosimu.techchrc.techchrcga import TechChRCgridAll #grille entière tous les chiffres\n## #Dernier placement\n## from sudosimu.techlplc.techlplcr import TechLastPlcRow #sur un rang\n## from sudosimu.techlplc.techlplcc import TechLastPlcCol #sur une colonne\n## from sudosimu.techlplc.techlplcs import TechLastPlcSqr #sur un carré\n## from sudosimu.techlplc.techlplcp import TechLastPlcPlace #sur une case (place)\n## from sudosimu.techlplc.techlplcg import TechLastPlcGrid #sur la grille entière\n##else:\n## raise Exception(\"Impossible de faire les imports dans le module sudothinkai.\")\n\n#OBSOLETE\n#from sudosimu.sudothinktech import SudoThinkTech\n\n\n##Dictionnaire d'identification des techniques\n##ATTENTION : les noms de techniques doivent être les mêmes que ceux connus\n##par SudoAI dans sudoai.py\nTechDict = { \"techchrcga\", TechChRCgridAll, \\\n \"techlplcg\", TechLastPlcGrid \\\n }\n\n\nclass SudoThinkAI(base.SudoBaseClass):\n '''Cette classe regroupe les méthodes qui réalisent la réflexion du\n joueur et choisissent la prochaine action à réaliser.\n '''\n\n def __init__(self, mem, know=None, \\\n env=None, testlevel=sudoenv.TEST_THINKAILEVEL):\n '''Initialisations, notamment les variables de classe qui représentent\n le savoir-faire de résolution non incluses dans la mémoire de travail.\n Le paramètre optionnel 'know' décrit la connaissance technique et\n tactique de résolution de Sudoku qu'a le joueur.\n '''\n #init de la classe racine\n assert isinstance(env, sudoenv.SudoEnv) or env is None\n assert isinstance(testlevel, int) and testlevel>=0 \\\n or testlevel is None\n base.SudoBaseClass.__init__(self, env=env, \\\n testlabel=\"thinkai\", testlevel=testlevel)\n #ok init de cette classe\n TEST = self.env.TEST\n TEST.display(\"thinkai\", 3, \"SudoThinkAI - Dans __init__()\")\n TEST.display(\"thinkai\", 1, \"Création de l'intelligence artificielle.\")\n assert isinstance(mem, SudoMemory)\n self._mem = mem\n assert know is None or isinstance(know, SudoKnowledge)\n self._know = know\n #init du système de décision AI\n self._initAI()\n #init de la pile des techniques en cours\n self._initTechPile()\n #gestion de la vérification de fin de partie\n self._needGridChecking = False\n self._checkingGrid = False\n self._gridCompleted = False\n #gestion du cycle de résolution (test)\n self._step = 1\n self._nbtotplc = 0 #nombre total de placements de la résolution\n self._nbplcloop = 0 #nombre de placements sur la boucle en cours\n self._nbplc = 0 #nombre de placements de la technique en cours\n\n self._initOk = True\n return\n\n def _initAI(self):\n '''Initialisation du système de décision et mise en place des\n données d'avancement pour le début de résolution.\n '''\n TEST = self.env.TEST\n TEST.display(\"thinkai\", 3, \"ThinkAI - Dans _initAI()\")\n #créer du système de décision SudoAI\n try:\n self._ai = ai.SudoAI(self._mem, env=self._env)\n #récupérer le dictionnaire de données\n self._aiData = self._ai.data\n except:\n raise Sudoku_Error(\"Dans SudoThinkAI._initAI() : \"\\\n \"Impossible d'initialiser le système AI\")\n #données d'avancement de la résolution\n self._begin = True #True si c'est le début de résolution\n self._techNiv = 0 #Niveau d'empilement de techniques\n #ATTENTION : AMELIORER la définition de techNivMax (knowledge)\n self._techNivMax = 3 #Niveau max d'empilement acceptable\n self._inTech = False #True si une technique est en cours\n self._opport = False #True si une recherche d'opportunité est en cours\n self._tech = None #code de la technique en cours\n self._techInst = None #instance de la technique en cours\n self._techName = None #Nom de la technique en cours\n self._lastTech = None #code de la préc. tech. de même niveau\n## self._lastTechInst = None #instance de la préc. tech. de même niveau\n## self._lastTechName = None #Nom de la préc. tech. de même niveau\n## self._lastTechNivInf = None #Inst. préc.tech. de niveau inférieur\n## self._lastTechNivInfName = None #Nom. préc.tech. de niveau inférieur\n## self._lastTechNivInf2 = None #idem niveau -2\n## self._lastTechNivInf2Name = None #idem niveau -2\n self._lastAction = None #Dernière action exécutée\n self._lastTechAction = None #Dernière action exécutée par une tech\n self._lastAIaction = None #Dernière action exécutée pra l'AI\n if TEST.ifLevel(\"thinkai\", 3) is True:\n self._dispDataSet()\n\n\n def decideAction(self):\n '''Indique la prochaine action à effectuer. Il peut s'agir de\n l'application d'une technique de résolution, ou bien d'une observation\n de la grille, d'un placement, ou de l'indication que la résolution est\n terminée pour diverses raisons.\n Retourne un tuple indiquant l'action et des arguments complémentaires.\n '''\n TEST = self.env.TEST\n TEST.display(\"thinkai\", 3, \"ThinkAI : méthode decideAction()\")\n assert self._initOk\n\n #Vérifier d'abord si la grille est terminée\n r = self._gridCheckingProcess()\n if r is not None:\n return r\n\n###### VERSION DE TEST DU MODULE techlplcp\n## Dans cette version, sudothinkai créée une instance de TechLastPlcPlace\n## et retourne toujours cette instance sans interroger AI.\n \n if self._techInst is None:\n TEST.display(\"thinkai\", 3, \"ThinkAI - VERSION DE TEST - \"\\\n \"Création d'une instance de TechLastPlcPlace pour \"\\\n \"la case (7,9)\")\n inst = self._newTechInst(TechLastPlcPlace, (7,9))\n self._techInst = inst\n return(\"tech\", (inst, \"insert\"))\n else:\n TEST.display(\"thinkai\", 3, \"ThinkAI - VERSION DE TEST - \"\\\n \"Suite de la même instance de TechLastPlcPlace.\")\n return (\"tech\", (self._techInst, \"same\"))\n \n##################\n \n #Interroger le système de décision\n self._makeDataSet()\n try:\n suggestion = self._ai.suggest()\n except:\n raise Sudoku_Error(\"SudoThinkAI.decideAction() : \"\\\n \"Erreur en appelant SudoAI.suggest()\")\n\n #analyser la réponse\n su = suggestion[0]\n TEST.display(\"thinkai\", 3, \"decideAction() - La suggestion AI est : \"\\\n \"{0}\".format(su))\n if su == \"continue\":\n #continuer la technique en cours - rien à changer\n TEST.display(\"thinkai\", 3, \"SudoThinkAI.decideAction() - Décision \"\\\n \" = continuer la technique en cours.\")\n action = (\"tech\", (self._techInst, \"same\"))\n elif su == \"start_tech\":\n #insérer une nouvelle technique\n TEST.display(\"thinkai\", 3, \"SudoThinkAI.decideAction() - Décision \"\\\n \" = insérer une technique ({0}).\".format(suggestion[1]))\n action = self._startTech(suggestion[1])\n TEST.display(\"thinkai\", 1, \"AI : Lancement d'une nouvelle technique \"\\\n \"de résolution : {0}.\".format(self._techName))\n elif su == \"abort_tech\":\n TEST.display(\"thinkai\", 3, \"SudoThinkAI.decideAction() - Décision \"\\\n \"= abandonner la technique en cours.\")\n TEST.display(\"thinkai\", 1, \"AI : Abandon de la technique de \"\\\n \"résolution : {0}.\".format(self._techName))\n action = self._abortTech()\n elif su == \"abort_all\":\n TEST.display(\"thinkai\", 3, \"SudoThinkAI.decideAction() - Décision \"\\\n \" abandon de toutes les techniques en cours.\")\n action = self._abortAllTechs()\n TEST.display(\"thinkai\", 1, \"AI : Abandon de toutes les techniques \"\\\n \"de résolution en cours.\")\n else:\n #ne devrait pas arriver\n raise Sudoku_Error(\"SudoThinkAI.decideAction() : \"\\\n \"erreur dans le retour de suggestion de SudoAI.\")\n #dans tous les cas la résolution n'en est plus au début\n self._begin = False\n #TEST : affichage des nouvelles données de résolution en cours\n if TEST.ifLevel(\"thinkai\", 3) is True:\n TEST.display(\"thinkai\", 3, \"ThinkAI - Nouvelles données de \"\\\n \"résolution :\")\n self._dispDataSet()\n #TEST : pause de vérification des données\n TEST.pause(\"thinkai\", 4)\n TEST.display(\"thinkai\", 3, \"SudoThinkAI - Décision retournée = {0}. \"\\\n .format(r))\n return action\n\n def _startTech(self, suggested):\n '''Lancement d'une nouvelle technique et insertion dans la pile de\n techniques en cours.\n '''\n TEST = self.env.TEST\n TEST.display(\"thinkai\", 3, \"ThinkAI : dans _startTech()\")\n assert self._initOk\n\n #instancier la technique suggérée\n if suggested == \"techchrcga\":\n #la tech ChRCgridAll ne prend pas d'argument\n TEST.display(\"thinkai\", 3, \"ThinkAI - Nouvelle instance de technique \"\\\n \"TechChRCgridAll.\")\n inst = self._newTechInst(TechChRCgridAll, None)\n elif suggested == \"techlplcg\":\n #la tech LastPlcGrid ne prend pas d'argument\n TEST.display(\"thinkai\", 3, \"ThinkAI - Nouvelle instance de technique \"\\\n \"TechLastPlcGrid.\")\n inst = self._newTechInst(TechLastPlcGrid, None)\n\n #mettre à jour les informations de résolution en cours\n## self._lastTechNivInf = self._tech\n## self._lastTechNivInfName = self._techName\n## self._techPilePush(tech)\n self._tech = suggested\n self._techInst = inst\n self._techName = inst.techName()\n self._techNiv += 1\n self._inTech = True\n## self._opport = True if self._techNiv >= 2 else False\n self._lastTech = None\n self._lastTechname =None\n self._lastAction = None\n self._lastTechAction = None\n #Retour vers Thinking = insertion de la nouvelle technique\n return (\"tech\", (self._techInst, \"insert\"))\n \n \n def _abortTech(self):\n '''Abandon de la technique en cours. Dépilement et retour à la tech\n précédente s'il y en a une.\n '''\n TEST = self.env.TEST\n TEST.display(\"thinkai\", 3, \"ThinkAI : dans _abortTech()\")\n assert self._initOk\n #vérifications de cohérence\n assert self._techNiv > 0\n assert self._tech is not None\n #supprimer l'instance de la technique abandonnée\n del(self._techInst)\n #dépiler\n #retour à la tech précédente et mise à jour des données de résolution\n #s'il y avait plus d'1 tech empilée, il en reste encore maintenant\n## self._techPilePop()\n## t = self._techPileGet()\n## if t is None:\n## self._tech = None\n## self._techName = None\n## self._inTech = False\n## else:\n## self._tech = t\n## self._techName = t.techName()\n## self._inTech = True\n \n #enregistrer la dernière technique en cours comme \"précédente\".\n self._lastTech = self._tech\n self._lastTechName = self._techName\n\n#### DANS LA VERSION ACTUELLE, 1 seul niveau donc abort renvoie au niveau 0\n## et donc il ny a plus de technique en cours\n self._tech = None\n self._techInst = None\n self._techName = None\n #self._techNiv -= 1\n self._techNiv = 0\n self._inTech = False\n self._lastAction = None\n self._lastTechAction = None\n return (\"continue\", None)\n \n## self._tech = self._lastTechNivInf\n## self._techName = self._lastTechNivInfName\n## self._inTech = True if self._tech is not None else False\n## self._opport = True if self._techNiv >= 2 else False\n#### NOTE : C'est ici qu'il va falloir géger la possibilité (MemProfile) de se\n# rappeler ce que l'on faisait avant, au moins 2 niveaux avant, c'est-à-dire\n# une fois revenu au niveau 1 ne pas avoir oublié ce que l'on faisait avant.\n## self._lastTechNivInf = None\n## self._lastTechNivInfName = None\n######\n## self._lastAction = None\n## self._lastTechAction = None\n## \n## #L'action décidée dépend du niveau d'imbrication auquel on est revenu.\n## if self._techInst is None:\n## action = (\"continue\", None)\n## else:\n## action = (\"tech\", (self._techInst, \"revert\"))\n##\n## return action\n\n def _abortAllTechs(self):\n '''Lancement d'une nouvelle technique et insertion dans la pile de\n techniques en cours.\n '''\n TEST = self.env.TEST\n TEST.display(\"thinkai\", 3, \"ThinkAI : dans _abortAllTechs()\")\n TEST.display(\"thinkai\", 3, \"METHODE A ECRIRE\")\n assert self._initOk\n raise Sudoku_Error(\"_abortAllTechs() n'existe pas encore.\")\n\n def _newTechInst(self, techClass, techArgs=None):\n '''Crée une nouvelle instance de la technique indiquée et l'initialise.\n '''\n TEST = self.env.TEST\n TEST.display(\"thinkai\", 3, \"ThinkAI - dans _newTechInst()\")\n TEST.display(\"thinkai\", 3, \"ThinkAI - Création d'une instance de la \"\\\n \"classe {0}\".format(techClass.techClassName()))\n assert self._initOk\n#### ATTENTION à faire une meilleure gestion d'erreur ici\n try:\n tech = techClass(self._mem, techArgs)\n except:\n raise Sudoku_Error(\"SudoThinkAI._newTechInst() : \"\\\n \"Erreur instanciation de tech de résolution.\")\n if tech is None:\n raise Sudoku_Error(\"SudoThinkAI._newTechInst() : \"\\\n \"Erreur instanciation de tech de résolution.\")\n return tech\n\n def _makeDataSet(self):\n '''Remplissage du dictionnaire de données qui sera utilisé par le\n système de décision.\n '''\n TEST = self.env.TEST\n TEST.display(\"thinkai\", 3, \"ThinkAI - dans _makeDataSet()\")\n#### TODO : REMPLACER LES VARIABLES D'INSTANCE PAR DES DONNEES MEMOIRE \n self._aiData[ai.DATA_BEGIN] = self._begin\n self._aiData[ai.DATA_NIV] = self._techNiv\n self._aiData[ai.DATA_NIVMAX] = self._techNivMax\n self._aiData[ai.DATA_INTECH] = self._inTech\n self._aiData[ai.DATA_OPPORT] = self._opport\n self._aiData[ai.DATA_TECH] = self._tech\n self._aiData[ai.DATA_LTECH] = self._lastTech\n self._aiData[ai.DATA_LACT] = self._lastAction\n self._aiData[ai.DATA_LTECHACT] = self._lastTechAction\n self._aiData[ai.DATA_LAIACT] = self._lastAIaction\n\n def _dispDataSet(self):\n '''Affiche la valeur des données d'avancement de la résolution.'''\n TEST = self.env.TEST\n TEST.display(\"thinkai\", 3, \"ThinkAI - dans _dispDataSet()\")\n ui.display(\"self._begin = {0}\".format(self._begin))\n ui.display(\"self._techNiv = {0}\".format(self._techNiv))\n ui.display(\"self._techNivMax = {0}\".format(self._techNivMax))\n ui.display(\"self._inTech = {0}\".format(self._inTech))\n ui.display(\"self._opport = {0}\".format(self._opport))\n ui.display(\"self._tech = {0}\".format(self._tech))\n ui.display(\"self._lastTech = {0}\".format(self._lastTech))\n ui.display(\"self._lastAction = {0}\".format(self._lastAction))\n ui.display(\"self._lastTechAction = {0}\".format(self._lastTechAction))\n ui.display(\"self._lastAIaction = {0}\".format(self._lastAIaction))\n return\n \n ##GESTION DE LA PILE DE TECHNIQUES EN COURS\n ##-----------------------------------------\n\n #Utilisation d'une liste en LIFO avec append() et pop()\n def _initTechPile(self):\n '''Crée la pile des techniques en cours, initialement vide.'''\n self._techNiv = 0\n self._techPile = list()\n return\n\n def _techPilePush(self, tech):\n self._techPile.append(tech)\n self._techNiv +=1\n return\n\n def _techPilePop(self):\n try:\n self._techPile.pop()\n except IndexError:\n raise Sudoku_Error(\"SudoAI : erreur de dépilement de la pile \"\\\n \"des techniques en cours.\")\n self._techNiv -= 1\n return\n\n def _techPileGet(self):\n if len(self._techPile) == 0:\n return None\n else:\n return self._techPile[-1] #dernier élément\n\n ##VERIFICATION DE FIN DE GRILLE\n ##-----------------------------\n def _gridCheckingProcess(self):\n '''Process de vérification de grille terminée. Il se passe en trois\n étapes : d'abord le lancement de la vérification, puis la méthode\n callback est appelée avec le résultat, puis test du résultat.\n '''\n TEST = self.env.TEST\n TEST.display(\"thinkai\", 3, \"Thinkai - dans _gridCheckingProcess()\")\n assert self._initOk\n if self._needGridChecking is True:\n TEST.display(\"thinkai\", 2, \"ThinkAI - La grille doit être vérifiée.\")\n return self._startGridChecking()\n if self._checkingGrid is True:\n TEST.display(\"thinkai\", 3, \"ThinkAI - Itération après vérification \"\\\n \"de la grille :\")\n if self._gridCompleted is True:\n TEST.display(\"thinkai\", 3, \"ThinkAI - Grille terminée.\")\n return self._winResult()\n #La grille n'est pas en vérification ou n'est pas terminée\n TEST.display(\"thinkai\", 3, \"ThinkAI - La grille n'est pas terminée.\")\n self._gridCompleted = False\n self._gridChecking = False\n self._needGridChecking = False\n####\n TEST.pause(\"thinkai\", 4)\n \n return None\n \n def _startGridChecking(self):\n '''Lancement d'une vérification de fin de grille.'''\n TEST = self.env.TEST\n TEST.display(\"thinkai\", 3, \"ThinkAI - Dans _startGridChecking()\")\n assert self._initOk\n TEST.display(\"thinkai\", 3, \"ThinkAI - Retour \\\"check\\\" pour \"\\\n \"vérification de la grille.\")\n self._needGridChecking = False\n self._checkingGrid = True\n self._gridCompleted = False\n####\n TEST.pause(\"thinkai\", 4)\n \n return (\"check\", None)\n\n #callback\n def checkCompleted(self, checked):\n '''Retour d'une vérification de grille terminée.'''\n TEST = self.env.TEST\n TEST.display(\"thinkai\", 3, \"ThinkAI - Méthode checkCompleted()\")\n assert self._initOk\n TEST.display(\"thinkai\", 3, \"ThinkAI - Retour de vérification de \"\\\n \"grille terminée : {0}\".format(checked))\n self._gridCompleted = checked\n self._mem.memorize(\"ai_grid_completed\", checked, self)\n####\n TEST.pause(\"thinkai\", 4)\n \n return (\"continue\", None)\n \n \n ##METHODES CALL-BACK DE RETOUR DES ACTIONS\n ##----------------------------------------\n #callback\n def aiObsResult(self, found):\n '''Retour d'une observation demandée par ThinkAI'''\n TEST = self.env.TEST\n TEST.display(\"thinkai\", 3, \"ThinkAI - Méthode aiObsResult()\")\n assert self._initOk\n TEST.display(\"thinkai\", 3, \"ThinkAI - retour d'observation : {0}\" \\\n .format(found))\n #mémorise le résultat d'observation faite par AI\n self._mem.memorize(\"ai_obsfound\", found, self)\n #après chaque placement on vérifie si la grille est terminée\n self._needGridChecking = True\n #pas besoin de vérification de grille après une observation\n self._needGridChecking = False\n #mise à jour des données d'avancement de résolution\n self._lastAction = \"place\"\n self._lastAIaction = \"place\"\n return (\"continue\", None)\n\n #callback\n def aiPlaceResult(self, placed=True):\n '''Retour d'un placement demandé par ThinkAI'''\n TEST = self.env.TEST\n TEST.display(\"thinkai\", 3, \"ThinkAI - Méthode aiPlaceResult()\")\n assert self._initOk\n TEST.display(\"thinkai\", 3, \"ThinkAI - retour de placement par AI : \"\\\n \"{0}.\".format(placed))\n self._mem.memorize(\"ai_placedok\", placed, self)\n return (\"continue\", None)\n\n #callback\n def techObsResult(self, found):\n '''Retour de l'observation de la technique suggérée par AI'''\n TEST = self.env.TEST\n TEST.display(\"thinkai\", 3, \"ThinkAI - Méthode techObsResult()\")\n assert self._initOk\n tech = self._mem.recallSafe(\"ai_suggested_tech\", self)\n TEST.display(\"thinkai\", 3, \"ThinkAI - retour d'observation par {0}: {1}\" \\\n .format(tech, found))\n #mémorise le résultat trouvé par la technique suggérée\n self._mem.memorize(\"ai_tech_obsfound\", found, self)\n #pas besoin de vérification de grille après une observation\n self._needGridChecking = False\n #mise à jour des données d'avancement de résolution\n self._lastAction = \"observe\"\n self._lastTechAction = \"observe\"\n\n return (\"continue\", None)\n\n #callback\n def techPlaceResult(self, placed=None):\n '''Retour du placement de la technique suggérée par AI'''\n TEST = self.env.TEST\n TEST.display(\"thinkai\", 3, \"ThinkAI - Méthode techPlaceResult()\")\n assert self._initOk\n tech = self._mem.recallSafe(\"ai_suggested_tech\", self)\n TEST.display(\"thinkai\", 3, \"ThinkAI - retour de placement par {0}: {1}\" \\\n .format(tech, placed))\n self._mem.memorize(\"ai_tech_placedok\", placed, self)\n #après chaque placement on prévoit de vérifier si la grille est terminée\n#### NOTE : A optimiser avec l'AI pour ne pas vérifier à chaque fois.\n self._needGridChecking = True\n #mise à jour des données d'avancement de résolution\n self._lastAction = \"place\"\n self._lastTechAction = \"place\"\n\n return (\"continue\", None)\n\n #callback\n def techReturnsEnd(self, endDetails=None):\n '''Prend connaissance que la technique suggérée a indiqué sa fin\n avec son résultat final.\n '''\n TEST = self.env.TEST\n TEST.display(\"thinkai\", 3, \"ThinkAI - dans techReturnsEnd()\")\n assert self._initOk\n tech = self._mem.recallSafe(\"ai_suggested_tech\", self)\n TEST.display(\"thinkai\", 3, \"ThinkAI - Résultat \\\"end\\\" par la \"\\\n \"technique {0}\".format(tech))\n## #vérifier la validité du résultat retourné\n## if endDetails[0] not in (\"end\", \"noplace\", \"succeed\", \"quit\", \"fail\"):\n## raise Sudoku_Error(\"ThinkAI - une technique a signalé sa fin\"\\\n## \"avec un code invalide : {0}\".format(endDetails))\n TEST.display(\"thinkai\", 3, \"ThinkAI - Code de fin de technique \"\\\n \"reçu : {0}\".format(endDetails))\n #mémorise la fin de technique pour l'itération suivante de AI, et répond\n #de continuer la résolution.\n self._mem.memorize(\"ai_suggested_tech_end\", True, self)\n self._mem.memorize(\"ai_suggested_tech_end_details\", endDetails, self)\n\n #mise à jour des données d'avancement de résolution\n self._lastAction = \"end\"\n self._lastTechAction = \"end\"\n####\n TEST.pause(\"thinkai\", 4)\n\n return (\"continue\", None)\n\n #callback\n def techReturnsFail(self, failDetails=None):\n '''Prend connaissance que la technique a généré un fail.'''\n TEST = self.env.TEST\n TEST.display(\"thinkai\", 3, \"ThinkAI - dans techReturnFail()\")\n assert self._initOk\n tech = self._mem.recallSafe(\"ai_suggested_tech\", self)\n## #vérifier la validité du résultat retourné\n## if endDetails[0] not in (\"end\", \"noplace\", \"succeed\", \"quit\", \"fail\"):\n## raise Sudoku_Error(\"ThinkAI - une technique a signalé sa fin\"\\\n## \"avec un code invalide : {0}\".format(endDetails))\n TEST.display(\"thinkai\", 3, \"ThinkAI - Code de fail de technique \"\\\n \"reçu : {0}\".format(failDetails))\n #mémorise le fail pour le traiter dans l'itération suivante, et répond\n #de continuer la résolution\n self._mem.memorize(\"ai_suggested_tech_fail\", True, self)\n self._mem.memorize(\"ai_suggested_tech_fail_details\", failDetails, self)\n\n #mise à jour des données d'avancement de résolution\n self._lastAction = \"end\"\n self._lastTechAction = \"end\"\n\n return (\"continue\", None)\n\n #callback\n def actionResult(self):\n '''Récupère de Thinking le résultat de la dernière action effectuée\n par la technique que ThinkAI a suggéré d'utiliser.\n '''\n TEST = self.env.TEST\n TEST.display(\"thinkai\", 3, \"ThinkAI - Méthode actionResult()\")\n assert self._initOk\n TEST.display(\"thinkai\", 3, \"ERREUR : METHODE actionResult() INCOMPLETE\")\n return (None, None)\n\n\n ##FIN DE PARTIE\n ##-------------\n def _winResult(self):\n TEST = self.env.TEST\n TEST.display(\"thinkai\", 3, \"ThinkAI - dans _winResult()\")\n assert self._initOk\n TEST.display(\"thinkai\", 1, \"AI : Grille terminée, la partie est gagnée.\")\n return (\"end\", (\"win\",None))\n \n\n def techName(self, tech):\n '''Retourne le nom de la classe de la technique de l'instance indiquée'''\n TEST = self.env.TEST\n assert self._initOk\n if tech is not None:\n return tech.techName()\n else:\n return None\n\n def lastTechName(self):\n '''Retourne le nom de la dernière technique suggérée'''\n TEST = self.env.TEST\n assert self._initOk\n lastTech = self._tmp_uniqueTech\n if lastTech is None: \n return None\n else:\n return lastTech.techName()\n \n \n \n\n##TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \n##TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \n\nif __name__ == \"__main__\":\n\n env = sudoenv.SudoEnv(\"TEST THINKAI\")\n TEST = env.TEST\n TEST.levelAll(0)\n\n #lancement de l'AI\n ui.display(\"\\nSIMULATION : Lancement de l'AI\")\n mem = SudoMemory(env=env)\n TEST.level(\"memory\", 0)\n tai = SudoThinkAI(mem, env = env)\n TEST.test(\"thinkai\", 3)\n TEST.test(\"ai\", 3)\n\n #affichage des données initiales\n ui.display(\"\\nSIMULATION : Données initiales :\")\n tai._aiData.disp()\n\n #simulation : premier appel par Thinking\n ui.display(\"\\nSIMULATION : Premier appel par Thinking\")\n TEST.pause(\"thinkai\", 1)\n da = tai.decideAction()\n\n #simulation : la première technique a fait une observation\n #found = (2, (1,4))\n #tai.techObsResult(found)\n #itération et nouvel appel par Thinking\n #da = tai.decideAction()\n\n## #import sudoobserver\n## #import sudogrid\n## import sudomemory\n## import sudotestall\n## testlevel = 3\n## TEST.levelAll(testlevel)\n## ui.display(\"Tous les niveaux de test sont à {0}\".format(testlevel))\n##\n## mem = sudomemory.SudoMemory()\n## ai = SudoThinkAI(mem)\n## #ai.init(mem)\n","sub_path":"sudosimu/sudothinkai_testlplcp.py","file_name":"sudothinkai_testlplcp.py","file_ext":"py","file_size_in_byte":31681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"102721795","text":"\n\n\n\ndef guess_encodig(s):\n \"\"\"\n バイト型の文字列を引数で受け取り、\n エンコードを簡易に判定いする\n \"\"\"\n # 判定を行うエンコードをリストに保存\n ori_encoding = \"ascii utf-8 shift-jis euc-jp\"\n encoding = ori_encoding.split()\n\n for enc in encoding:\n try: #tryの中にはエラーが発生するかもしれないがやりたい処理\n s.decode(enc)\n except UnicodeDecodeError: #ここでエラーが発生したときの処理 エラー名を書く\n continue\n else: #エラーが発生しなかったときこ処理 \n return enc #成功したらそのエンコードを返す\n else:\n return \" \" #成功しなかったら空白を返す\n\n\n\naas = \"あいうえおかきくけこさしすせそ\"\nbs = aas.encode(\"utf-8\")\ncs = bs.decode(\"shift-jis\",\"replace\") #replace'job is replace errorcharacter to ?\nprint(bs)\nprint(cs)\n\nencode = guess_encodig(bs)\nprint(encode)\n","sub_path":"chapter4/guess_encoding.py","file_name":"guess_encoding.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"519049169","text":"# Python module for control of Mipow LED bulbs\n#\n# Copyright 2016 Arttu Mahlakaarto \n# Based on work by Matthew Garret\n# This code is released under the terms of the MIT license. See the LICENSE\n# file for more details.\n\nimport time\n\nfrom bluepy import btle\n\n\nclass Delegate(btle.DefaultDelegate):\n \"\"\"Delegate Class.\"\"\"\n\n def __init__(self, bulb):\n self.bulb = bulb\n btle.DefaultDelegate.__init__(self)\n\n\n\nclass mipow:\n def __init__(self, mac):\n self.mac = mac\n\n def set_state(self, white, red, green, blue):\n self.white = white\n self.red = red\n self.green = green\n self.blue = blue\n\n def connect(self):\n self.device = btle.Peripheral(self.mac, addrType=btle.ADDR_TYPE_PUBLIC)\n self.device.setDelegate(Delegate(self))\n self.get_state()\n\n def send_packet(self, handleId, data):\n initial = time.time()\n while True:\n if time.time() - initial >= 10:\n return False\n try:\n return self.device.writeCharacteristic(handleId, data)\n except:\n self.connect()\n\n def off(self):\n self.power = False\n packet = bytearray([0x00, 0x00, 0x00, 0x00])\n self.send_packet(0x1b, packet)\n\n def on(self):\n self.power = True\n packet = bytearray([0xff, 0x00, 0x00, 0x00])\n self.send_packet(0x1b, packet)\n\n def set_rgb(self, red, green, blue):\n self.red = red\n self.green = green\n self.blue = blue\n self.white = 0\n packet = bytearray([0x00, red, green, blue])\n self.send_packet(0x1b, packet)\n\n def set_white(self, white):\n self.red = 0\n self.green = 0\n self.blue = 0\n self.white = white\n packet = bytearray([white, 0x00, 0x00, 0x00])\n self.send_packet(0x1b, packet)\n\n def set_rgbw(self, white, red, green, blue):\n self.red = red\n self.green = green\n self.blue = blue\n self.white = white\n packet = bytearray([white, red, green, blue])\n self.send_packet(0x1b, packet)\n\n def set_effect(self, white, red, green, blue, mode, speed):\n # mode: blink=00, pulse=01, hard rainbow=02, smooth rainbow=03, candle=04, halt=ff\n self.red = red\n self.green = green\n self.blue = blue\n self.white = white\n self.mode = mode\n self.speed = speed\n packet = bytearray([white, red, green, blue, mode, 0x00, speed, 0])\n self.send_packet(0x19, packet)\n\n def get_state(self):\n status = self.device.readCharacteristic(0x1b)\n if bytearray(status) != bytearray([0, 0, 0, 0]):\n self.power = True\n else:\n self.power = False\n self.white = status[0]\n self.red = status[1]\n self.green = status[2]\n self.blue = status[3]\n return status\n\n\n\n def get_on(self):\n return self.power\n\n def get_colour(self):\n return (self.red, self.green, self.blue)\n\n def get_white(self):\n return self.white\n","sub_path":"mipow/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"509067063","text":"from flask_restful import Resource\nfrom flask import request\nfrom conf import getserver\nfrom fn.req import ok, ng, er\nfrom fn.keywords import NO_SERVER_IP_FOUND\nfrom models.instance import getIp\nfrom mcstatus import MinecraftServer\nfrom socket import timeout\n\nclass Server(Resource):\n def get(self):\n ep = request.endpoint\n self.ip = getIp()\n if self.ip:\n self.s = MinecraftServer(self.ip)\n m = {\n 'get-server': self.server\n }\n return m[ep]() #type: ignore\n \n def server(self):\n ser = getserver()\n basic = {\n 'mods': ser['mods'],\n 'version': ser['version'],\n 'since': ser['since'],\n 'bestram': ser['bestram'],\n 'term': ser['term'],\n 'created': True if self.ip else False,\n 'ip': self.ip\n }\n try:\n status = self.s.status()\n except:\n basic['online'] = False\n return ok(basic)\n raw = status.raw\n mods = raw.get('forgeData').get('mods')\n index = 0\n for m in mods:\n if m.get('modId') in ('minecraft', 'forge'):\n del mods[index]\n index += 1\n full = dict()\n full.update(basic)\n full.update({\n 'online': True,\n 'maxPlayers': status.players.max,\n 'onlinePlayers': status.players.online,\n 'motd': raw.get('description').get('text'),\n 'onlinePlayersDetails': raw.get('players').get('sample'),\n 'rawMods': mods\n })\n return ok(full)","sub_path":"src/apis/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"527669891","text":"\"\"\"Definition of the TVBr Reporter Foto content type\n\"\"\"\n\nfrom zope.interface import implements\n\nfrom Products.Archetypes import atapi\nfrom Products.ATContentTypes.content import base\nfrom Products.ATContentTypes.content import schemata\n\n# -*- Message Factory Imported Here -*-\nfrom automator.tvbrasil import tvbrasilMessageFactory as _\n\nfrom automator.tvbrasil.interfaces import ITVBrReporterFoto\nfrom automator.tvbrasil.config import PROJECTNAME\n\nTVBrReporterFotoSchema = schemata.ATContentTypeSchema.copy() + atapi.Schema((\n\n # -*- Your Archetypes field definitions here ... -*-\n\n atapi.ImageField(\n 'foto',\n storage=atapi.AnnotationStorage(),\n widget=atapi.ImageWidget(\n label=_(u\"Foto\"),\n ),\n required=True,\n validators=('isNonEmptyFile'),\n sizes = {'foto' : (1248, 702)},\n pil_quality=100,\n ),\n\n atapi.StringField(\n 'legenda',\n storage=atapi.AnnotationStorage(),\n widget=atapi.StringWidget(\n label=_(u\"Legenda\"),\n ),\n ),\n\n atapi.IntegerField(\n 'tempo',\n storage=atapi.AnnotationStorage(),\n widget=atapi.IntegerWidget(\n label=_(u\"Tempo\"),\n description=_(u\"Tempo em segundos\"),\n ),\n required=True,\n default=_(u\"5\"),\n validators=('isInt'),\n ),\n\n))\n\n# Set storage on fields copied from ATContentTypeSchema, making sure\n# they work well with the python bridge properties.\n\nTVBrReporterFotoSchema['title'].storage = atapi.AnnotationStorage()\nTVBrReporterFotoSchema['title'].widget.visible = {\"edit\": \"invisible\", \"view\": \"invisible\"}\nTVBrReporterFotoSchema['title'].required = False\nTVBrReporterFotoSchema['description'].storage = atapi.AnnotationStorage()\nTVBrReporterFotoSchema['description'].widget.visible = {\"edit\": \"invisible\", \"view\": \"invisible\"}\nTVBrReporterFotoSchema['location'].widget.visible = {\"edit\": \"invisible\", \"view\": \"invisible\"}\nTVBrReporterFotoSchema['language'].widget.visible = {\"edit\": \"invisible\", \"view\": \"invisible\"}\nTVBrReporterFotoSchema['effectiveDate'].widget.visible = {\"edit\": \"invisible\", \"view\": \"invisible\"}\nTVBrReporterFotoSchema['expirationDate'].widget.visible = {\"edit\": \"invisible\", \"view\": \"invisible\"}\nTVBrReporterFotoSchema['creators'].widget.visible = {\"edit\": \"invisible\", \"view\": \"invisible\"}\nTVBrReporterFotoSchema['contributors'].widget.visible = {\"edit\": \"invisible\", \"view\": \"invisible\"}\nTVBrReporterFotoSchema['rights'].widget.visible = {\"edit\": \"invisible\", \"view\": \"invisible\"}\nTVBrReporterFotoSchema['allowDiscussion'].widget.visible = {\"edit\": \"invisible\", \"view\": \"invisible\"}\nTVBrReporterFotoSchema['excludeFromNav'].widget.visible = {\"edit\": \"invisible\", \"view\": \"invisible\"}\nTVBrReporterFotoSchema['subject'].widget.visible = {\"edit\": \"invisible\", \"view\": \"invisible\"}\nTVBrReporterFotoSchema['relatedItems'].widget.visible = {\"edit\": \"invisible\", \"view\": \"invisible\"}\n\n\n\nschemata.finalizeATCTSchema(TVBrReporterFotoSchema, moveDiscussion=False)\n\n\nclass TVBrReporterFoto(base.ATCTContent):\n \"\"\" \"\"\"\n implements(ITVBrReporterFoto)\n\n meta_type = \"TVBrReporterFoto\"\n schema = TVBrReporterFotoSchema\n\n title = atapi.ATFieldProperty('title')\n description = atapi.ATFieldProperty('description')\n\n # -*- Your ATSchema to Python Property Bridges Here ... -*-\n foto = atapi.ATFieldProperty('foto')\n tempo = atapi.ATFieldProperty('tempo')\n legenda = atapi.ATFieldProperty('legenda')\n\n def at_post_create_script(self):\n if self.getLegenda():\n self.setTitle(self.getLegenda())\n else:\n self.setTitle(self.id)\n self.reindexObject(idxs=[\"Title\"])\n\n\natapi.registerType(TVBrReporterFoto, PROJECTNAME)\n","sub_path":"automator/tvbrasil/content/tvbrreporterfoto.py","file_name":"tvbrreporterfoto.py","file_ext":"py","file_size_in_byte":3718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"558666676","text":"import json\n\n\nclass FirstTask:\n\n def __init__(self):\n print('task init')\n\n # filenames\n self.testcase_filename = \"TestcaseStructure.json\"\n self.values_filename = \"Values.json\"\n\n self.error_filename = \"error.json\"\n\n self.result_filename = \"result/StructureWithValues.json\"\n\n # data variables\n self.json_from_testcase = None\n self.json_from_values = None\n self.values_dict = {}\n\n self.result = {}\n\n def _get_all_data(self):\n\n with open(self.testcase_filename, 'r', encoding='utf-8') as file:\n self.json_from_testcase = json.load(file)\n\n with open(self.values_filename, 'r', encoding='utf-8') as file:\n self.json_from_values = json.load(file)\n\n def transform(self):\n self._prepairing()\n\n for el in self.json_from_testcase[\"params\"]:\n index_to_insert = self.json_from_testcase[\"params\"].index(el)\n if \"values\" in el.keys():\n for val in el[\"values\"]:\n if self.values_dict[el[\"id\"]] in list(val.values()):\n value_to_insert = None\n for title in el[\"values\"]:\n if title[\"id\"] == self.values_dict[el[\"id\"]]:\n value_to_insert = title[\"title\"]\n break\n self.result['params'][index_to_insert][\"value\"] = value_to_insert\n else:\n self.result[\"params\"][index_to_insert][\"value\"] = self.values_dict[el['id']]\n\n def _prepairing(self):\n self._get_all_data()\n print('data_imported')\n self._values_to_dict()\n print('values to dict done')\n self.result = self.json_from_testcase\n\n def _values_to_dict(self):\n\n for i in self.json_from_values[\"values\"]:\n self.values_dict[i['id']] = i['value']\n\n\ntest = FirstTask()\ntest.transform()\nprint(test.result)\n","sub_path":"1st_task.py","file_name":"1st_task.py","file_ext":"py","file_size_in_byte":1961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"502501324","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2013 Paul Brossier \n\n# This file is part of TimeSide.\n\n# TimeSide 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# TimeSide 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 TimeSide. If not, see .\n\n# Author: Paul Brossier \nfrom __future__ import absolute_import\n\nfrom ...core import implements, interfacedoc\nfrom ..core import Analyzer\nfrom ...api import IAnalyzer\nfrom ..preprocessors import downmix_to_mono, frames_adapter\nfrom aubio import filterbank, pvoc\n\n\nclass AubioMelEnergy(Analyzer):\n\n \"\"\"Aubio Mel Energy analyzer\"\"\"\n implements(IAnalyzer)\n\n def __init__(self):\n super(AubioMelEnergy, self).__init__()\n self.input_blocksize = 1024\n self.input_stepsize = self.input_blocksize / 4\n\n @interfacedoc\n def setup(self, channels=None, samplerate=None,\n blocksize=None, totalframes=None):\n super(AubioMelEnergy, self).setup(\n channels, samplerate, blocksize, totalframes)\n self.n_filters = 40\n self.n_coeffs = 13\n self.pvoc = pvoc(self.input_blocksize, self.input_stepsize)\n self.melenergy = filterbank(self.n_filters, self.input_blocksize)\n self.melenergy.set_mel_coeffs_slaney(samplerate)\n self.block_read = 0\n self.melenergy_results = []\n\n @staticmethod\n @interfacedoc\n def id():\n return \"aubio_melenergy\"\n\n @staticmethod\n @interfacedoc\n def name():\n return \"Mel Energy (aubio)\"\n\n @staticmethod\n @interfacedoc\n def unit():\n return \"\"\n\n @downmix_to_mono\n @frames_adapter\n def process(self, frames, eod=False):\n\n fftgrain = self.pvoc(frames)\n self.melenergy_results.append(self.melenergy(fftgrain))\n self.block_read += 1\n return frames, eod\n\n def post_process(self):\n melenergy = self.new_result(data_mode='value', time_mode='framewise')\n melenergy.parameters = dict(n_filters=self.n_filters,\n n_coeffs=self.n_coeffs)\n melenergy.data_object.value = self.melenergy_results\n self.add_result(melenergy)\n","sub_path":"venv/lib/python2.7/site-packages/timeside/analyzer/externals/aubio_melenergy.py","file_name":"aubio_melenergy.py","file_ext":"py","file_size_in_byte":2620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"595961216","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport constants as c\n\nclass OtLoss(nn.Module):\n '''\n Performs the loss to align the distributions\n '''\n def __init__(self, alpha, align_weight):\n super().__init__()\n self.alpha = alpha\n self.align_weight = align_weight\n\n def forward(self, ft_source, ft_target, gamma):\n num_features = ft_target.shape[1]\n l2_dist = (torch.sum(torch.square(ft_source),1).view((-1,1)) +\n torch.sum(torch.square(ft_target),1).view((1,-1)))\n l2_dist -= 2.0*torch.mm(ft_source, ft_target.view(num_features, c.batch_size))\n return self.align_weight * self.alpha * torch.sum(gamma * l2_dist)\n\nclass ClfLoss(nn.Module):\n def __init__(self, classifier_weight, tloss, sloss, device='cpu'):\n super().__init__()\n self.classifier_weight = classifier_weight\n self.tloss = tloss\n self.sloss = sloss\n self.eps = 1e-9\n self.cross_entorpy = nn.CrossEntropyLoss()\n self.device = device\n\n def forward(self, ys, ys_pred, yt_pred, gamma):\n cross_entropy_source = self.cross_entorpy(ys_pred, ys)\n classes = torch.arange(c.num_class).reshape(1, c.num_class)\n one_hot_ys = (ys.unsqueeze(1) == classes.to(device=self.device)).float()\n yt_pred_ = yt_pred\n yt_pred = -nn.LogSoftmax(dim=1)(yt_pred)\n loss = torch.matmul(one_hot_ys, yt_pred.t())\n return self.classifier_weight * (self.tloss * torch.sum(gamma * loss) +\n self.sloss * cross_entropy_source)","sub_path":"model/losses.py","file_name":"losses.py","file_ext":"py","file_size_in_byte":1495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"359000529","text":"\n# Libraries\nimport pygame\nfrom pygame import gfxdraw\nimport sys\n\n# Engine\nfrom lecture_versions.engine.tests import TEST_optional_coordinates, TEST_color, TEST_object_attributes\nfrom lecture_versions.engine.helpers import reverse_color\n\n# Constants\nfrom pygame.locals import DOUBLEBUF\nfrom lecture_versions.engine.constants import *\n\n\n\"\"\"\nThe purpose of this class is just to provide a more comfortable\ndevelopment experience with pygame.\n\nIt provides basic boilerplate functionality and makes all drawing\nfunctions homogeneous and more intuitive. Also all shapes are drawn\nwith antialiasing enabled.\n\ngfxdraw provides antialiased draw methods.\nSee full reference at: http://www.pygame.org/docs/ref/gfxdraw.html\n\nTo be clear: You don't have to use this!!! It's just something I\nfind useful. You may add further functionality as you like\n\"\"\"\n\nclass Game():\n\n def __init__(\n self, width=500, height=500,\n title=\"MyGame\", font_family='Roboto',\n track_fps=True, print_fps=True,\n max_fps=240\n ):\n\n self.width = width\n self.height = height\n self.font_family = font_family\n\n if track_fps:\n self.clock = pygame.time.Clock()\n self.max_fps = max_fps\n self.fps = max_fps\n else:\n assert not print_fps, \"Cannot print_fps without track_fps=True\"\n\n self.track_fps = track_fps\n self.print_fps = print_fps\n\n pygame.init()\n self.window = pygame.display.set_mode((width, height), DOUBLEBUF)\n pygame.display.set_caption(title)\n\n # Has to be called to use fonts at some point\n pygame.font.init()\n\n def draw_rect(self, x, y, width, height, color=(0, 0, 0), alpha=1):\n gfxdraw.box(self.window, (x, y, width, height), list(color) + [int(alpha * 255)])\n\n def draw_circle(self, x, y, radius, color=(0, 0, 0)):\n x, y, radius = math.ceil(x), math.ceil(y), math.ceil(radius)\n try:\n gfxdraw.aacircle(self.window, x, y, radius, color)\n gfxdraw.filled_circle(self.window, x, y, radius, color)\n except:\n print(f\"x={x}, y={y}, radius={radius}, color={color}\")\n sys.exit()\n\n def draw_polygon(self, points, color=(0, 0, 0)):\n gfxdraw.aapolygon(game_window, points, color)\n gfxdraw.filled_polygon(game_window, points, color)\n\n # You can pass in either the texts center coordinates or it edge coordinates\n # or not coordinates at all for both dimensions. In the last case the text will\n # be places in the windows center\n def draw_text(\n self, text,\n x_left=None, x_center=None, x_right=None,\n y_top=None, y_center=None, y_bottom=None,\n font_family=None, font_size=30,\n color=(0, 0, 0)\n ):\n TEST_optional_coordinates(\n x_left=x_left, x_center=x_center, x_right=x_right,\n y_top=y_top, y_center=y_center, y_bottom=y_bottom\n )\n\n font = pygame.font.SysFont(self.font_family if font_family is None else font_family, font_size)\n surface = font.render(text, True, color)\n (rx, ry, rw, rh) = surface.get_rect() # The rectangle enclosing the text\n\n if all([x is None for x in (x_left, x_center, x_right)]):\n x = round((self.width - rw)/2) # If nothing has been set, use window center\n elif x_left is not None:\n x = round(x_left)\n elif x_center is not None:\n x = round(x_center - (rw/2))\n elif x_right is not None:\n x = round(self.width - x_right - rw)\n else:\n assert False, \"Logic is wrong\"\n\n if all([y is None for y in (y_top, y_center, y_bottom)]):\n y = round((self.width - rh)/2) # If nothing has been set, use window center\n elif y_top is not None:\n y = round(y_top)\n elif y_center is not None:\n y = round(y_center - (rh/2))\n elif y_bottom is not None:\n y = round(self.height - y_bottom - rh)\n else:\n assert False, \"Logic is wrong\"\n\n self.window.blit(surface, (x, y))\n\n def draw_background(self, color=(255, 255, 255)):\n TEST_color(color)\n self.window.fill(color)\n\n def update(self):\n # 1. Update fps\n if self.track_fps:\n # self.fps converges towards the actual fps -> reduces noise in fps\n timedelta = self.clock.tick(self.max_fps) * 0.001\n new_fps = round((self.fps*5 + (1/timedelta))/6)\n\n if self.print_fps and self.fps != new_fps:\n print(\"{:3d} FPS\".format(round(new_fps)))\n\n self.fps = new_fps\n\n # 2. Update game window\n pygame.display.update()\n\n def get_mouse_position(self):\n if pygame.mouse.get_focused() == 0:\n return None # If mouse is not in window\n else:\n return pygame.mouse.get_pos()\n\n def exit(self):\n pygame.quit()\n sys.exit()\n\n # Draw a rect from its center-position with the SCALING factor from\n # engine.constants applied and regular cartesion coordinates (y axis\n # points upwards)\n def draw_rect_element(self, position, size, color=(0, 0, 0), alpha=1):\n rect_w = size[0] * SCALING_FACTOR\n rect_h = size[1] * SCALING_FACTOR\n rect_x = position[0] * SCALING_FACTOR - (rect_w/2)\n rect_y = self.height - (position[1] * SCALING_FACTOR + (rect_h/2))\n self.draw_rect(rect_x, rect_y, rect_w, rect_h, color=color, alpha=alpha)\n\n # Draw a circle from its center-position with the SCALING factor from\n # engine.constants applied and regular cartesion coordinates (y axis\n # points upwards)\n def draw_circle_element(self, position, radius, color=(0, 0, 0)):\n circle_x = position[0] * SCALING_FACTOR\n circle_y = self.height - (position[1] * SCALING_FACTOR)\n circle_r = radius * SCALING_FACTOR\n self.draw_circle(circle_x, circle_y, circle_r, color=color)\n\n # Draw small helper circles indicating the center of a game element as\n # well as possible collisions\n def draw_helper_points(self, game_object):\n TEST_object_attributes(game_object, attributes=(\"position\", \"size\", \"color\"))\n\n reversed_color = reverse_color(game_object.color)\n circle_radius = min(game_object.size) * 0.15\n self.draw_circle_element(game_object.position, circle_radius, color=reversed_color)\n\n if hasattr(game_object, \"collisions\"):\n circle_offsets = {\n \"FLOOR\": [0, -0.5 * game_object.size[1]],\n \"CEILING\": [0, 0.5 * game_object.size[1]],\n \"LEFT_WALL\": [-0.5 * game_object.size[0], 0],\n \"RIGHT_WALL\": [0.5 * game_object.size[0], 0],\n }\n for side in circle_offsets:\n if game_object.collisions[side] is not None:\n position = [game_object.position[dim] + circle_offsets[side][dim] for dim in (0, 1)]\n self.draw_circle_element(position, circle_radius, color=reversed_color)\n\n def draw_sprite(self, image, center_position):\n width, height = image.get_rect()[2:]\n self.window.blit(image, (center_position[0]-(width/2), center_position[1]-(height/2)))\n\n def draw_sprite_element(self, image, center_position, sprite_offset=(0, 0)):\n center_position = [\n (center_position[0] + sprite_offset[0]) * SCALING_FACTOR,\n self.height - (center_position[1] + sprite_offset[1]) * SCALING_FACTOR\n ]\n self.draw_sprite(image, center_position)\n","sub_path":"lecture_versions/engine/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":7564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"299221050","text":"\"\"\"\n * Copyright 2020, Departamento de sistemas y Computación\n * Universidad de Los Andes\n *\n *\n * Desarrolado para el curso ISIS1225 - Estructuras de Datos y Algoritmos\n *\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 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 * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n * Contribución de:\n *\n * Dario Correal\n *\n \"\"\"\n\nfrom DISClib.ADT import list as lt\n\nfrom App.Controller import DataBase\nfrom App.Controller import Funtions\n\ndef ejecutarInitDataBase()->dict:\n result = DataBase.initDataBase()\n print('Base de datos creada')\n return result\n\n\ndef ejecutarLoadData(dataBase)->bool:\n result = DataBase.loadData(dataBase)\n analysis = DataBase.analyze(dataBase)\n print(f\"Datos actualizados:\\\n \\n\\tViajes: {analysis['trips']}\\\n \\n\\tVértices: {analysis['vertices']}\\\n \\n\\tArcos: {analysis['edges']}\\\n \\n\\tClústers: {analysis['Clusters']}\")\n return result\n\ndef ejecutarClustersViajes(dataBase)->None:\n id1 = int(input('Ingrese la primera id: '))\n id2 = int(input('Ingrese la segunda id: '))\n analysis = Funtions.ClustersViajes(dataBase,id1,id2)\n print(f\"\\n\\tSe han encontrado {analysis['clusters']} Clústers\")\n if analysis['conected']:\n print(f'\\n\\tlas estaciones {id1} y {id2} estan conectadas')\n else:\n print(f'\\n\\tlas estaciones {id1} y {id2} no estan conectadas')","sub_path":"App/View/Init.py","file_name":"Init.py","file_ext":"py","file_size_in_byte":1915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"208288680","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport random\nimport os\n\n\ndef ustawienia():\n \"\"\"Funkcja pobiera nick użytkownika, ilość losowanych liczb, maksymalną\n losowaną wartość oraz ilość typowań. Ustawienia zapisuje.\"\"\"\n\n nick = input(\"Podaj nick: \")\n nazwapliku = nick + \".ini\"\n gracz = czytaj_ust(nazwapliku)\n odp = None\n if gracz:\n print(\"Twoje ustawienia:\\nLiczb: %s\\nZ Maks: %s\\nLosowań: %s\" %\n (gracz[1], gracz[2], gracz[3]))\n odp = input(\"Zmieniasz (t/n)? \")\n\n if not gracz or odp.lower() == \"t\":\n while True:\n try:\n ile = int(input(\"Podaj ilość typowanych liczb: \"))\n maks = int(input(\"Podaj maksymalną losowaną liczbę: \"))\n if ile > maks:\n print(\"Błędne dane!\")\n continue\n ilelos = int(input(\"Ile losowań: \"))\n break\n except ValueError:\n print(\"Błędne dane!\")\n continue\n gracz = [nick, str(ile), str(maks), str(ilelos)]\n zapisz_ust(nazwapliku, gracz)\n\n return gracz[0:1] + [int(x) for x in gracz[1:4]]\n\n\ndef czytaj_ust(nazwapliku):\n if os.path.isfile(nazwapliku):\n plik = open(nazwapliku, \"r\")\n linia = plik.readline()\n plik.close()\n if linia:\n return linia.split(\";\")\n return False\n\n\ndef zapisz_ust(nazwapliku, gracz):\n plik = open(nazwapliku, \"w\")\n plik.write(\";\".join(gracz))\n plik.close()\n\n\ndef losujliczby(ile, maks):\n \"\"\"Funkcja losuje ile unikalnych liczb całkowitych od 1 do maks\"\"\"\n liczby = []\n i = 0\n while i < ile:\n liczba = random.randint(1, maks)\n if liczby.count(liczba) == 0:\n liczby.append(liczba)\n i = i + 1\n return liczby\n\n\ndef pobierztypy(ile, maks):\n \"\"\"Funkcja pobiera od użytkownika jego typy wylosowanych liczb\"\"\"\n print(\"Wytypuj %s z %s liczb: \" % (ile, maks))\n typy = set()\n i = 0\n while i < ile:\n try:\n typ = int(input(\"Podaj liczbę %s: \" % (i + 1)))\n except ValueError:\n print(\"Błędne dane!\")\n continue\n\n if 0 < typ <= maks and typ not in typy:\n typy.add(typ)\n i = i + 1\n return typy\n\n\ndef wyniki(liczby, typy):\n trafione = liczby & typy\n if trafione:\n print(\"\\nIlość trafień: %s\" % len(trafione))\n # print(trafione)\n trafione = \", \".join(map(str, trafione))\n print(\"Trafione liczby: %s\" % trafione)\n else:\n print(\"Brak trafień. Spróbuj jeszcze raz!\")\n print(\"\\n\" + \"x\" * 40 + \"\\n\") # wydrukuj 40 znaków x\n\n return len(trafione)\n","sub_path":"docs/podstawy/elotek/totomodul32.py","file_name":"totomodul32.py","file_ext":"py","file_size_in_byte":2695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"630809534","text":"# 1- Import the modules\nimport cv2\nimport matplotlib.pyplot as plt\nfrom pathlib2 import Path\nfrom os import path\n\n\n# 2- Load the test image\nhome_dir = Path.home()\ngoogle_data_dir = \"Google Drive\\OpenCV3ComputerVisionwithPythonCookbook_Code\\data\"\nimage = cv2.imread(filename=path.join(home_dir, google_data_dir, \"people.png\"))\n\n# 3- Create the HOG feature computer and detector\nhog = cv2.HOGDescriptor()\nhog.setSVMDetector(svmdetector=cv2.HOGDescriptor_getDefaultPeopleDetector())\n\n# 4- Detect the people in the image\nlocations, weights = hog.detectMultiScale(img=image)\n\n# 5- Draw the detected people bounding boxes\ndbg_image = image.copy()\nfor loc in locations:\n cv2.rectangle(img=dbg_image,\n pt1=(loc[0], loc[1]),\n pt2=(loc[0] + loc[2], loc[1] + loc[3]),\n color=(0, 255, 0),\n thickness=2)\n\n# 6- Visualize the results\nplt.figure(figsize=(12, 6))\nplt.subplot(121)\nplt.title(\"original\")\nplt.axis(\"off\")\nplt.imshow(image[:, :, [2, 1, 0]])\nplt.subplot(122)\nplt.title(\"detections\")\nplt.axis(\"off\")\nplt.imshow(dbg_image[:, :, [2, 1, 0]])\nplt.tight_layout()\nplt.show()\n","sub_path":"Python3/OpenCV 3 Computer Vision with Python Cookbook/4 - Object Detection and Machine Learning/4.9 - A simple pedestrian detector using the SVM model.py","file_name":"4.9 - A simple pedestrian detector using the SVM model.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"343392810","text":"# PE2 Even Fibonacci numbers\nimport time\n\ni=1\nlimit=4000000\nsum=0\nstart_time = time.time()\n\ndef fibonacci(n):\n if n==1:\n return 1\n elif n==2:\n return 2\n else:\n return fibonacci(n-2)+fibonacci(n-1)\n\nwhile fibonacci(i)= reduce_lr_epoch * self.n_epochs:\n\t\t\t\t\tlr /= reduce_factor\n\t\telse:\n\t\t\tif self.other_lr_schedule['type'] == 'cosine':\n\t\t\t\tlr_max = self.init_lr\n\t\t\t\tlr_min = self.other_lr_schedule.get('lr_min', 0)\n\t\t\t\tlr = lr_min + 0.5 * (lr_max - lr_min) * (1 + np.cos((epoch - 1) / self.n_epochs * np.pi))\n\t\t\telse:\n\t\t\t\traise ValueError('Do not support %s' % self.other_lr_schedule['type'])\n\t\treturn lr\n\n\t@staticmethod\n\tdef get_default_run_config(dataset='C10+'):\n\t\tif dataset in ['C10', 'C10+', 'C100', 'C100+']:\n\t\t\trun_config = {\n\t\t\t\t'batch_size': 64,\n\t\t\t\t'n_epochs': 300,\n\t\t\t\t'init_lr': 0.1,\n\t\t\t\t'reduce_lr_epochs': [0.5, 0.75], # epochs * 0.5, epochs * 0.75\n\t\t\t\t'reduce_lr_factors': [10, 10],\n\t\t\t\t'opt_config': ['momentum', {'momentum': 0.9, 'use_nesterov': True}],\n\t\t\t\t'dataset': dataset, # choices = [C10, C10+, C100, C100+]\n\t\t\t\t'validation_size': None, # None or int\n\t\t\t\t'validation_frequency': 10,\n\t\t\t\t'shuffle': 'every_epoch', # None, once_prior_train, every_epoch\n\t\t\t\t'normalization': 'by_channels', # None, divide_256, divide_255, by_channels\n\t\t\t\t'should_save_logs': True,\n\t\t\t\t'should_save_model': True,\n\t\t\t\t'renew_logs': True,\n\t\t\t\t'other_lr_schedule': {'type': 'cosine'}, # None, or cosine\n\t\t\t}\n\t\telif dataset in ['SVHN']:\n\t\t\trun_config = {\n\t\t\t\t'batch_size': 64,\n\t\t\t\t'n_epochs': 40,\n\t\t\t\t'init_lr': 0.1,\n\t\t\t\t'reduce_lr_epochs': [0.5, 0.75], # epochs * 0.5, epochs * 0.75\n\t\t\t\t'reduce_lr_factors': [10, 10],\n\t\t\t\t'opt_config': ['momentum', {'momentum': 0.9, 'use_nesterov': True}],\n\t\t\t\t'dataset': dataset, # choices = [C10, C10+, C100, C100+]\n\t\t\t\t'validation_size': None, # None or int\n\t\t\t\t'validation_frequency': 1,\n\t\t\t\t'shuffle': True,\n\t\t\t\t'normalization': 'divide_255', # None, divide_256, divide_255, by_channels\n\t\t\t\t'should_save_logs': True,\n\t\t\t\t'should_save_model': True,\n\t\t\t\t'renew_logs': True,\n\t\t\t\t'other_lr_schedule': {'type': 'cosine'}, # None, or cosine\n\t\t\t\t'include_extra': False,\n\t\t\t}\n\t\telse:\n\t\t\traise ValueError\n\t\treturn run_config\n\n","sub_path":"code/models/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"106028257","text":"import sampling\nimport numpy as np\n\n\ndef test_resample():\n x = np.arange(300)\n s = sampling.Sampler(x)\n y = np.array(list(s))\n\n err = x[1:len(y)+1] - y\n assert np.max(np.abs(err)) < 1e-10\n\n\ndef test_coeffs():\n I = sampling.Interpolator(width=4, resolution=16)\n err = I.filt[0] - [0, 0, 0, 1, 0, 0, 0, 0]\n assert np.max(np.abs(err)) < 1e-10\n","sub_path":"test_sampling.py","file_name":"test_sampling.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"261830671","text":"from flask import Flask, render_template, request, redirect\nimport re\napp = Flask(__name__)\n\ntodo_list = []\n\n@app.route('/')\ndef todos():\n return render_template('index.html', todo_list = todo_list)\n\n@app.route('/submit', methods = ['POST'])\ndef submit():\n valid = True\n task = request.form['task']\n email = request.form['email']\n pattern = '^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*$'\n if re.match(pattern,email) == None:\n valid = False\n \n priority = request.form['priority']\n if priority not in ['low', 'medium', 'high']:\n valid = False\n \n if valid:\n todo = {'task': task,\n 'email': email,\n 'priority': priority}\n todo_list.append(todo)\n return redirect('/')\n\n@app.route('/clear', methods = ['POST'])\ndef clear():\n todo_list.clear()\n return redirect('/')\n\nif __name__ == '__main__':\n app.run()","sub_path":"todoapp.py","file_name":"todoapp.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"593784036","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Nov 28 20:30:15 2020\n\n@author: dhk1349\n\"\"\"\n\nfrom django.urls import path, re_path\nfrom blog import views\n\napp_name='blog'\nurlpatterns=[\n \n #/blog/\n path('', views.PostLV.as_view(), name='index'),\n \n #/blog/post/ (same as /blog/)\n path('post/', views.PostLV.as_view(), name='post_list'),\n \n #/blog/post/django-example/\n re_path(r'^post/(?P[-\\w]+)/$', views.PostDV.as_view(), name='post_detail'),\n \n #/blog/archive/\n path('archive/', views.PostAV.as_view(), name='post_archive'),\n \n #/blog/archive/2019\n path('archive//', views.PostYAV.as_view(), name='post_year_archive'),\n \n #/blog/archive/2019/nov/\n path('archive///', views.PostMAV.as_view(), name='post_month_archive'),\n \n #/blog/archive/2019/nov/10\n path('archive////', views.PostDAV.as_view(), name='post_day_archive'),\n \n #/blog/archive/today/\n path('archive/today/', views.PostTAV.as_view(), name='post_today_archive'),\n \n\n \n \n ]","sub_path":"ch1/blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"207954098","text":"import unittest\nfrom unittest.mock import Mock\n\nfrom flask import Flask, json\nfrom flask import request\nfrom flask_restful import Api\n\nfrom .context import src\nfrom src import api\n\nclass ApiTest(unittest.TestCase):\n\n def setUp(self):\n app = Flask(__name__)\n app.config['DEBUG'] = True\n flaskApi = Api()\n self.mongoMock = Mock()\n self.jobMock = Mock()\n flaskApi.add_resource(api.StockAPI, \"/stockboard/api/stocks\",\n resource_class_kwargs={\"mongo\": self.mongoMock, \"job\": self.jobMock})\n flaskApi.init_app(app)\n self.client = app.test_client()\n\n def testAddStock_NOK_emptyRequestBody(self):\n response = self.client.post(\"/stockboard/api/stocks\")\n self.assertEquals(response.status_code, 400)\n data = json.loads(response.data)\n expectedErrorMessage = \"Please provide a stock in the request body. It should have a name, a quote and a stock market\"\n self.assertEquals(expectedErrorMessage, data[\"error\"])\n\n def testAddStock_NOK_notValidStock(self):\n stock = { \"name\": \"Bank of America\", \"quote\": \"\", \"stockMarket\": \"\" }\n response = self.client.post(\"/stockboard/api/stocks\", data=json.dumps(stock), content_type=\"application/json\")\n self.assertEquals(response.status_code, 400)\n data = json.loads(response.data)\n expectedErrorMessage = \"Please provide a valid stock. It should have a name, a quote and a stock market\"\n self.assertEquals(expectedErrorMessage, data[\"error\"])\n\n def testAddStock_NOK_existingStock(self):\n self.mongoMock.getStockByQuote = Mock(return_value=True)\n quote = \"BAC\"\n stock = { \"name\": \"Bank of America\", \"quote\": quote, \"stockMarket\": \"NYSE\" }\n response = self.client.post(\"/stockboard/api/stocks\", data=json.dumps(stock), content_type=\"application/json\")\n self.mongoMock.getStockByQuote.assert_called_once_with(quote)\n self.assertEquals(response.status_code, 409)\n data = json.loads(response.data)\n expectedErrorMessage = \"The given stock already exists\"\n self.assertEquals(expectedErrorMessage, data[\"error\"])\n\n def testAddStock_OK(self):\n self.mongoMock.getStockByQuote = Mock(return_value=False)\n quote = \"BAC\"\n stock = { \"name\": \"Bank of America\", \"quote\": quote, \"stockMarket\": \"NYSE\" }\n response = self.client.post(\"/stockboard/api/stocks\", data=json.dumps(stock), content_type=\"application/json\")\n self.mongoMock.getStockByQuote.assert_called_once_with(quote)\n self.assertEquals(response.status_code, 202)\n data = json.loads(response.data)\n expectedMessage = \"The stock \" + quote + \" is being added\"\n self.assertEquals(expectedMessage, data[\"success\"])\n\n","sub_path":"test/api_test.py","file_name":"api_test.py","file_ext":"py","file_size_in_byte":2785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"236377892","text":"MATCH_DATA = {\n \"blueTeam\": {\n \"players\" : {\n \"top\": {\n \"summonerName\": \"TSM Huni\",\n \"champion\": \"Gangplank\",\n \"stats\": {\n \"kills\": 2,\n \"deaths\": 4,\n \"assists\": 6,\n \"firstBlood\": False,\n \"gold\": 17000,\n \"minions\": 344,\n },\n },\n \"jg\": {\n \"summonerName\": \"100 Closer\",\n \"champion\": \"Taliyah\",\n \"stats\": {\n \"kills\": 4,\n \"deaths\": 5,\n \"assists\": 14,\n \"firstBlood\": False,\n \"gold\": 18000,\n \"minions\": 52,\n },\n },\n \"mid\": {\n \"summonerName\": \"100 Damonte\",\n \"champion\": \"Syndra\",\n \"stats\": {\n \"kills\": 7,\n \"deaths\": 3,\n \"assists\": 9,\n \"firstBlood\": False,\n \"gold\": 21600,\n \"minions\": 377,\n },\n },\n \"bottom\": {\n \"summonerName\": \"100 FBI\",\n \"champion\": \"Kai'sa\",\n \"stats\": {\n \"kills\": 6,\n \"deaths\": 3,\n \"assists\": 12,\n \"firstBlood\": False,\n \"gold\": 22200,\n \"minions\": 352,\n },\n },\n \"support\": {\n \"summonerName\": \"100 huhi\",\n \"champion\": \"Leona\",\n \"stats\": {\n \"kills\": 2,\n \"deaths\": 5,\n \"assists\": 15,\n \"firstBlood\": False,\n \"gold\": 12400,\n \"minions\": 52,\n },\n },\n },\n \"teamStats\": {\n \"dragons\": 3,\n \"barons\": 2,\n \"turrets\": 10,\n },\n },\n \"redTeam\": {\n \"players\" : {\n \"top\": {\n \"summonerName\": \"FLY Licorice\",\n \"champion\": \"Camille\",\n \"stats\": {\n \"kills\": 5,\n \"deaths\": 4,\n \"assists\": 3,\n \"firstBlood\": False,\n \"gold\": 17200,\n \"minions\": 322+19,\n },\n },\n \"jg\": {\n \"summonerName\": \"FLY Josedeodo\",\n \"champion\": \"Hecarim\",\n \"stats\": {\n \"kills\": 6,\n \"deaths\": 2,\n \"assists\": 7,\n \"firstBlood\": True,\n \"gold\": 14900,\n \"minions\": 52+209,\n },\n },\n \"mid\": {\n \"summonerName\": \"FLY Palafox\",\n \"champion\": \"Orianna\",\n \"stats\": {\n \"kills\": 2,\n \"deaths\": 1,\n \"assists\": 12,\n \"firstBlood\": False,\n \"gold\": 15900,\n \"minions\": 333+16,\n },\n },\n \"bottom\": {\n \"summonerName\": \"FLY Johnsun\",\n \"champion\": \"Seraphine\",\n \"stats\": {\n \"kills\": 2,\n \"deaths\":0,\n \"assists\": 12,\n \"firstBlood\": False,\n \"gold\": 15400,\n \"minions\": 308+17,\n },\n },\n \"support\": {\n \"summonerName\": \"FLY Diamond\",\n \"champion\": \"Rell\",\n \"stats\": {\n \"kills\": 5,\n \"deaths\": 2,\n \"assists\": 6,\n \"firstBlood\": False,\n \"gold\": 10200,\n \"minions\": 52+1,\n },\n },\n },\n \"teamStats\": {\n \"dragons\": 4,\n \"barons\": 1,\n \"turrets\": 10,\n },\n },\n \"winner\": \"red\",\n \"gameDuration\": \"39:58\",\n \"date\": \"2021-02-05\",\n \"url\": \"https://matchhistory.na.leagueoflegends.com/en/#match-details/ESPORTSTMNT02/1685817?gameHash=4386c2f28dde838b&tab=stats\"\n}","sub_path":"lcs/match_history/week1/tsm_fly.py","file_name":"tsm_fly.py","file_ext":"py","file_size_in_byte":3245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"500497508","text":"import colors;\nimport time;\n\ntaillef = input(colors.warning(\"taille de la fenetre ? :\"))\nnom = raw_input(colors.warning(\"nom du 1er fichier :\"))\nnom2 = raw_input(colors.warning(\"nom du 2eme fichier :\"))\n\nf = open(nom,\"r\")\nf2 = open(nom2,\"r\")\n\nnom_fic = time.strftime(\"%c\").replace(\" \",\"\") + \".datas\"\nfw = open(nom_fic,\"w\")\nligne2 = f2.readline().rstrip(\"\\n\")\nligne = f.readline().rstrip(\"\\n\")\nfw.write(\" \" + ligne + \"\\n\")\n\n\nconcat = \" \" + ligne + \"\\n\"\ni=0\n\nwhile i < len(ligne2):\n\tconcat =ligne2[i]\n\tj=0\n\twhile j < len(ligne):\n\n\t\tif (ligne[j:j+taillef] == ligne2[i:i+taillef]) :\n\t\t\tconcat += \"X\"\n\t\telse:\n\t\t\tconcat += \" \"\n\t\tj+=1\n\ti+=1\n\tfw.write(concat + \"\\n\")\n\nf.close()\nfw.close()\n","sub_path":"td7ex1.py","file_name":"td7ex1.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"198855628","text":"from player import *\nclass Line:\n player = Player(0,0,0)\n xPos = 0\n yPos = 0\n llength = 0\n speed = 0\n def __init__(self,x,y,l,s, p):\n self.xPos = x\n self.yPos = y\n self.llength = l\n self.speed = s\n self.player = p\n \n \n def checkCollision():\n delatx = self.xPos - self.player.xPos\n if abs(deltax) <= (self.player.psize / 2):\n deltaY1 = self.yPos - self.player.yPos\n deltaY2 = (self.yPos + self.llength ) - self.player.yPos\n if abs(deltaY1) <= (self.player.psize / 2):\n return True;\n elif abs(deltaY2) <= (self.player.psize / 2):\n return True;\n elif self.yPos < self.player.yPos and self.player.yPos < self.yPos + self.llength:\n return True;\n else:\n return False;\n else:\n return False;\n \n def update(self):\n self.yPos+=self.speed\n \n if(checkCollision()):\n self.player.hit = True\n if self.yPos > height:\n self.yPos = 0\n self.xPos = random(0,width)\n def draw(self):\n fill(15*self.speed,15*self.speed,15*self.speed )\n line(self.xPos, self.yPos, self.xPos, self.yPos + self.llength)\n\n \n \n","sub_path":"project/linee.py","file_name":"linee.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"14252414","text":"# -*- coding: utf-8 -*-\nimport sys\n\nfrom rest_framework.pagination import (\n LimitOffsetPagination,\n PageNumberPagination\n)\n\n\nclass ProjectDefaultPagination(PageNumberPagination):\n paginate_by = 24\n paginate_by_param = 'page_size'\n max_paginate_by = 150\n\n\nclass CustomPagination(LimitOffsetPagination):\n \"\"\"\n Pagination with max value for Integer\n \"\"\"\n default_limit = sys.maxint\n","sub_path":"src/knowledge_base/utils/pagination.py","file_name":"pagination.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"42105316","text":"import json\nimport matplotlib.pyplot as plt\nfrom collections import Counter, OrderedDict\nimport os\nimport json_load\n\nrootdir ='./data'\nfile = 'business.json'\njson_data = json_load.convert(rootdir, file)\n\n# Plot categories\n# sort attributes\nrestaurants = [str(restaurants['categories']).split(', ') for restaurants in json_data]\nall_categories = (dict(Counter([categorie for restaurant in restaurants for categorie in restaurant])))\n# Plot a histogram that shows how many of each categorie exists in a town\nlists = dict(sorted(all_categories.items()))\nkeys = lists.keys()\nvalues = lists.values()\nplt.bar(lists.keys(), lists.values(), width= 1, color='g')\nplt.tick_params(axis='x', which='major', labelsize=0.4)\nplt.xticks(rotation=90)\nplt.show()\n\n# Plot ratings\nrestaurants_stars = dict(Counter([restaurants['stars'] for restaurants in json_data]))\nrestaurants_stars = dict(sorted(restaurants_stars.items()))\nkeys = restaurants_stars.keys()\nvalues = restaurants_stars.values()\nplt.bar(restaurants_stars.keys(), restaurants_stars.values(), color='b')\nplt.tick_params(axis='x', which='major', labelsize=8)\nplt.xticks(rotation=90)\nplt.show()\n","sub_path":"business_plot.py","file_name":"business_plot.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"125899705","text":"\r\nimport scipy.io as sio\r\nimport numpy as np\r\n\r\n\r\ndef cm_art(M,label,rho,save_path_root):\r\n '''\r\n % M: numpy arrary; m*n feature matrix; m is number of objects and n is number of visual features\r\n %rho: the vigilance parameter\r\n %save_path_root: path to save clustering results for further analysis\r\n '''\r\n\r\n NAME = 'cm_art'\r\n#-----------------------------------------------------------------------------------------------------------------------\r\n# Input parameters\r\n alpha = 0.01 # no need to tune; used in choice function; to avoid too small cluster weights (resulted by the learning method of ART; should be addressed sometime); give priority to choosing denser clusters\r\n beta = 0.6 # has no significant impact on performance with a moderate value of [0.4,0.7]\r\n delta = 0.001 #the percentage to enlarge or shrink vigilance region\r\n\r\n # rho needs carefully tune; used to shape the inter-cluster similarity; rho_v = 0.7 indicates an object will not be clustered to a cluster with visual similarity lower than 0.7\r\n #rho = 0.6\r\n\r\n\r\n\r\n# -----------------------------------------------------------------------------------------------------------------------\r\n# Initialization\r\n\r\n #complement coding\r\n M = np.concatenate([M,1-M], 1)\r\n\r\n #get data sizes\r\n row, col = M.shape\r\n\r\n\r\n\r\n\r\n# -----------------------------------------------------------------------------------------------------------------------\r\n# Clustering process\r\n\r\n print( NAME + \"algorithm starts\")\r\n\r\n #create initial cluster with the first data sample\r\n #initialize cluster parameters\r\n Wv = np.zeros((row, col))\r\n J = 0 # number of clusters\r\n L = np.zeros((1,row), dtype=np.int) # size of clusters; note we set to the maximun number of cluster, i.e. number of rows\r\n Assign = np.zeros((1,row), dtype=np.int) # the cluster assignment of objects\r\n rho_0 = rho * np.ones((1,row))\r\n temp = np.zeros((1,row)) #to recover the rho of winner cluster in the later computation\r\n\r\n #first cluster\r\n print('Processing data sample 0')\r\n Wv[0, :] = M[0, :]\r\n J = 1\r\n L[0,J-1] = 1\r\n Assign[0,0] = J-1 #note that python array index trickily starts from 0\r\n\r\n #processing other objects\r\n for n in range(1,row):\r\n\r\n print('Processing data sample %d' % n)\r\n\r\n T_max = -1 #the maximun choice value\r\n winner = -1 #index of the winner cluster\r\n temp[0,:] = rho_0[0,:]\r\n\r\n #compute the similarity with all clusters; find the best-matching cluster\r\n for j in range(0,J):\r\n\r\n #compute the match function\r\n Mj_numerator_V = np.sum(np.minimum(M[n,:],Wv[j,:]))\r\n Mj_V = Mj_numerator_V / np.sum(M[n,:])\r\n\r\n if Mj_V >= rho_0[0,j]:\r\n # update rho of all clusters with VR reaching to input pattern\r\n rho_0[0,j] = Mj_V + delta\r\n # compute choice function\r\n Tj = Mj_numerator_V / (alpha + np.sum(Wv[j, :]))\r\n if Tj >= T_max:\r\n T_max = Tj\r\n winner = j\r\n\r\n #Cluster assignment process\r\n if winner == -1: #indicates no cluster passes the vigilance parameter - the rho\r\n #create a new cluster\r\n J = J + 1\r\n Wv[J - 1, :] = M[n, :]\r\n L[0, J - 1] = 1\r\n Assign[0,n] = J - 1\r\n else: #if winner is found, do cluster assignment and update cluster weights\r\n #update cluster weights\r\n Wv[winner, :] = beta * np.minimum(Wv[winner, :], M[n, :]) + (1 - beta) * Wv[winner, :]\r\n #cluster assignment\r\n L[0, winner] += 1\r\n Assign[0,n] = winner\r\n rho_0[0,winner] = temp[0,winner]\r\n\r\n\r\n\r\n print(\"algorithm ends\")\r\n # Clean indexing data\r\n Wv = Wv[0: J, :]\r\n L = L[:, 0: J]\r\n\r\n# -----------------------------------------------------------------------------------------------------------------------\r\n# performance calculation\r\n\r\n # confusion-like matrix\r\n number_of_class = int(max(label)) +1\r\n confu_matrix = np.zeros((J,number_of_class))\r\n\r\n for i in range(0 ,row):\r\n confu_matrix[Assign[0,i] ,int(label[i])] += 1\r\n\r\n # compute dominator class and its size in each cluster\r\n max_value = np.amax(confu_matrix ,axis=1)\r\n max_index = np.argmax(confu_matrix ,axis=1)\r\n size_of_classes = np.sum(confu_matrix ,axis=0)\r\n\r\n # compute precision, recall\r\n precision = max_value / L[0 ,:]\r\n\r\n recall = np.zeros((J))\r\n for i in range(0,J):\r\n recall[i] = max_value[i] / size_of_classes[max_index[i]]\r\n\r\n\r\n #intra_cluster distance - Euclidean\r\n intra_cluster_distance = np.zeros((J))\r\n for i in range(0,row):\r\n temp1 = np.sqrt(np.sum(np.square(Wv[Assign[0,i],0:(col//2)] - M[i,0:(col//2)])))\r\n temp2 = np.sqrt(np.sum(np.square(1 - Wv[Assign[0, i], (col // 2):] - M[i, 0:(col // 2)])))\r\n\r\n intra_cluster_distance[Assign[0,i]] += (temp1 + temp2) / 2 #compute average distance between bottom-left and upper-right points of the cluster and the input pattern\r\n\r\n intra_cluster_distance = intra_cluster_distance[:] / L[0,:]\r\n\r\n # inter_cluster distance - Euclidean\r\n inter_cluster_distance = np.zeros(((J*(J-1))//2))\r\n len = 0\r\n for i in range(0,J):\r\n for j in range(i+1,J):\r\n temp = np.square(Wv[i,:] - Wv[j,:])\r\n inter_cluster_distance[len] = (np.sqrt(np.sum(temp[0:(col//2)])) + np.sqrt(np.sum(temp[(col//2):]))) / 2 #compute the average distance between bottom-left and upper-right points of two clusters\r\n len += 1\r\n\r\n# -----------------------------------------------------------------------------------------------------------------------\r\n# save results\r\n\r\n sio.savemat(save_path_root + str(number_of_class) + '_class_' + NAME + '_rho_' + str(rho) + '.mat',\r\n {'precision': precision, 'recall': recall, 'cluster_size': L,\r\n 'intra_cluster_distance': intra_cluster_distance, 'inter_cluster_distance': inter_cluster_distance,\r\n 'Wv': Wv, 'confu_matrix': confu_matrix})\r\n\r\n\r\n return 0\r\n\r\n","sub_path":"cm_art.py","file_name":"cm_art.py","file_ext":"py","file_size_in_byte":6139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"91396054","text":"import torch \nimport numpy as np\nimport torchvision.models as models\nimport torch.nn.functional as F\nimport torch.nn as nn\nfrom torch import optim\nimport random\nimport torch.optim as optim\n#########################\nimport torch\nimport torchvision\nimport torchvision.transforms as transforms\nfrom torch.utils.data import Dataset, DataLoader\nimport pickle\nimport RandomHandClass\nimport BatchHelper\nimport cv2\nimport os\n\nFolderSaveModel = \"Model_CNN\"\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nclass ConvNetExtract(nn.Module):\n def __init__(self, output_size, dropout_p=0.3):\n super(ConvNetExtract, self).__init__()\n self.device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n self.conv1 = nn.Conv2d(3, 128, kernel_size=3, stride=1, padding=1)\n self.conv2 = nn.Conv2d(128, 128, kernel_size=3, stride=1, padding=1)\n self.conv3 = nn.Conv2d(128, 128, kernel_size=3, stride=1, padding=1)\n self.maxpool = nn.MaxPool2d(2)\n\n self.adaptor = nn.Linear(8 * 8 * 128, 1024)\n self.adaptor2 = nn.Linear(1024, output_size)\n\n self.adaptor = self.adaptor.to(self.device)\n self.adaptor2 = self.adaptor2.to(self.device)\n self.dropout = nn.Dropout(0.5)\n\n def forward(self, input):\n outputFeature = self.extractFeature(input)\n outputFeature = torch.relu(self.adaptor(outputFeature))\n outputFeature = self.dropout(outputFeature)\n\n outputFeature = torch.relu(self.adaptor2(outputFeature))\n class_output_log = torch.log_softmax(outputFeature,dim=1)\n return class_output_log\n \n def extractFeature(self, input):\n in_size = input.size(0)\n features = self.conv1(input)\n features = torch.relu(features)\n features = self.maxpool(features)\n features = self.conv2(features)\n features = torch.relu(features)\n features = self.maxpool(features)\n features = self.conv3(features)\n features = torch.relu(features)\n features = self.maxpool(features) \n\n outputFeature = features.view(in_size, -1) # flatten\n return outputFeature\n\nclass Net(nn.Module):\n\n def __init__(self,output_size):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(3, 128, kernel_size=5, padding=1)\n self.conv2 = nn.Conv2d(128, 128, kernel_size=5, padding=1)\n self.mp = nn.MaxPool2d(2)\n ## what is number value ??\n self.fc = nn.Linear(30*30*128, output_size) #########??\n\n def forward(self, x):\n in_size = x.size(0)\n x = self.mp(torch.relu(self.conv1(x)))\n x = self.mp(torch.relu(self.conv2(x)))\n x = x.view(in_size, -1) # flatten the tensor\n x = self.fc(x)\n x = torch.log_softmax(x,dim=1)\n return x\n\n\n\nif __name__ == \"__main__\":\n # Hyperparameters\n num_epochs = 30\n num_classes = 28\n batch_size = 100\n learning_rate = 0.0001\n\n imageSize = 64\n\n models = ConvNetExtract(num_classes)\n models = models.to(device)\n rHC = RandomHandClass.RandomHandClass()\n rHC.readAllDatabase(\"./ClassImage_train\")\n batchHelper_train = BatchHelper.BatchHelp(rHC.ImageAll,rHC.labelAll)\n totalSample_train = len(batchHelper_train._label)\n\n rHC_val = RandomHandClass.RandomHandClass()\n rHC_val.readAllDatabase(\"./ClassImage_val\")\n batchHelper_val = BatchHelper.BatchHelp(rHC_val.ImageAll,rHC_val.labelAll)\n totalSample_val = len(batchHelper_val._label)\n\n rHC_test = RandomHandClass.RandomHandClass()\n rHC_test.readAllDatabase(\"./ClassImage_test\")\n batchHelper_test = BatchHelper.BatchHelp(rHC_test.ImageAll,rHC_test.labelAll)\n totalSample_test = len(batchHelper_test._label)\n\n\n criterion = nn.NLLLoss()\n \n optimizer = optim.Adam(models.parameters(), lr=0.0001) # apply optimizer to model \n ACC = 0\n ACC_Max_val = 0\n Average_ACC_val = 0\n ACC_Max_test = 0\n Average_ACC_test = 0\n\n #check folder model is exist.\n if not os.path.exists(\"./{}\".format(FolderSaveModel)):\n os.mkdir(\"./{}\".format(FolderSaveModel))\n\n \n print(\"totalTime per epoach {}\".format(int(totalSample_train/batch_size)))\n for y in range(num_epochs):\n models.train()\n ACC = 0\n batchHelper_train.resetIndex()\n while batchHelper_train._epochs_completed == 0:\n input_image,labelImage = batchHelper_train.next_batch(batch_size,True)\n # for i in range(int(totalSample/batch_size)):\n loss = 0\n optimizer.zero_grad()\n inputImageDataset = torch.from_numpy(input_image)\n inputImageDataset = inputImageDataset.to(device=device, dtype=torch.float)\n # print(torch.sum(inputImageDataset))\n target_output = torch.from_numpy(labelImage.astype(int))\n target_output = target_output.to(device=device, dtype=torch.long)\n output_pred = models(inputImageDataset)\n\n loss = criterion(output_pred, target_output)\n loss.backward()\n optimizer.step()\n topv, topi = output_pred.topk(1)\n check_target = (topi.reshape(-1)==target_output)\n ACC += check_target.float().sum() \n if batchHelper_train._index_in_epoch % batch_size == 0:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.9f} current ACC {} '\\\n .format(y, batchHelper_train._index_in_epoch, totalSample_train,\\\n (batchHelper_train._index_in_epoch * 100.) / totalSample_train, \\\n loss.item(),(check_target.float().sum()/batch_size)*100))\n \n \n\n ############# validation #####################\n batchHelper_val.resetIndex()\n models.eval()\n ACC=0\n coutBatch = 0\n while batchHelper_val._epochs_completed == 0:\n input_image,labelImage = batchHelper_val.next_batch(batch_size,True)\n inputImageDataset = torch.from_numpy(input_image)\n inputImageDataset = inputImageDataset.to(device=device, dtype=torch.float)\n\n target_output = torch.from_numpy(labelImage.astype(int))\n target_output = target_output.to(device=device, dtype=torch.long)\n output_pred = models(inputImageDataset)\n topv, topi = output_pred.topk(1)\n check_target = (topi.reshape(-1)==target_output)\n ACC += check_target.float().sum()\n coutBatch +=1\n\n Average_ACC_val=(ACC / (coutBatch*batch_size))\n print(\"Validation ACC average {}\".format(Average_ACC_val))\n if ACC_Max_val < Average_ACC_val:\n print(\"ACC val Update\")\n # torch.save(models, \"./Model_CNN/CNN_SignModel_{:.3f}\".format(Average_ACC_val))\n ACC_Max_val = Average_ACC_val\n\n\n ############### test ##################\n batchHelper_test.resetIndex()\n coutBatch = 0\n ACC = 0\n while batchHelper_test._epochs_completed == 0:\n input_image,labelImage = batchHelper_test.next_batch(batch_size,True)\n inputImageDataset = torch.from_numpy(input_image)\n inputImageDataset = inputImageDataset.to(device=device, dtype=torch.float)\n\n target_output = torch.from_numpy(labelImage.astype(int))\n target_output = target_output.to(device=device, dtype=torch.long)\n output_pred = models(inputImageDataset)\n topv, topi = output_pred.topk(1)\n check_target = (topi.reshape(-1)==target_output)\n ACC += check_target.float().sum()\n coutBatch += 1\n \n Average_ACC_test=(ACC / (coutBatch*batch_size))\n print(\"Test ACC average {}\".format(Average_ACC_test))\n print(\"SaveModel\")\n torch.save(models, \"./{}/CNN_Sign_{:.3f}_T_{:.3f}\".format(FolderSaveModel,Average_ACC_val,Average_ACC_test))\n ACC_Max_test = Average_ACC_test\n print(\"Save Completed\")\n\n\n","sub_path":"CreateModel.py","file_name":"CreateModel.py","file_ext":"py","file_size_in_byte":7996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"215430075","text":"from flask import Flask, request, redirect, render_template, session, flash\nfrom mysqlconnection import MySQLConnector\nimport re\n\napp = Flask(__name__)\nemail_regex = r'(^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\\.[a-zA-Z]+$)'\napp.secret_key = 'ThisIsSecret'\nmysql = MySQLConnector(app,'emailvalidation')\n@app.route('/')\ndef index():\n\n return render_template('index.html')\n@app.route('/process', methods=['POST'])\ndef create():\n has_errors = False\n if not re.match(email_regex, request.form['email']):\n has_errors = True\n flash('email is not valid')\n if has_errors:\n return redirect('/')\n else:\n query_string = \"INSERT INTO email (email) VALUES (:email)\"\n query_data = {\n 'email': request.form['email']\n }\n flash('success!')\n result = mysql.query_db(query_string, query_data)\n return redirect('/success')\n@app.route('/success')\ndef success():\n query_string = \"INSERT INTO email (email) VALUES (:email)\"\n query_data = {\n 'email': request.form['email']\n }\n flash('success!')\n show = (\"SELECT * FROM email\")\n friends = mysql.query_db(show);\n result = mysql.query_db(query_string, query_data)\n return render_template('/success')\napp.run(debug=True)\n","sub_path":"Python/myEnvironments/friends/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"305233696","text":"import random\nimport json\n# from DialogManager.DialogManager import DM\n\n\nclass UserSimulator:\n def __init__(self, request_count):\n self.user_inform_slots = [\"child_age\", \"english_level\", \"client_location\", \"reserve_location\", \"phone_number\",\n \"client_name\", \"client_gender\", \"know_about_ruisi\", \"special_need\", \"reserve_time\",\n \"child_grade\", \"user_goal\"]\n self.user_request_slots = ['school_location', 'attend_class_alone', 'allow_parents_together', 'class_length',\n 'textbook', 'class_size', 'teacher_nation', 'class_type', 'online_course', 'fee']\n self.agent_request_slot = \"\"\n self.dict_inform = {\n \"user_goal\": [\"加盟\", \"预约\", \"咨询\"],\n \"client_gender\": [\"爸爸\", \"妈妈\", \"奶奶\", \"爷爷\", \"舅舅\", \"姥姥\", \"姥爷\"],\n \"child_name\": ['小小艾', '小小思', \"小小邺\"],\n \"child_age\": [\"1岁\", \"2岁\", \"3岁\", \"4岁\", \"5岁\", \"6岁\", \"7岁\", \"8岁\", \"9岁\"],\n \"english_level\": [\"还行\", \"学过\", \"有接触\", \"没接触\"],\n \"special_need\": [\"听力\", \"口语\", \"��作\", \"单词\"],\n \"client_location\": [\"北京市海淀区\", \"北京市东城区\", \"北京市西城区\", \"北京市昌平区\", \"北京市朝阳区\"],\n \"reserve_location\": [\"保福寺校区\", \"\", \"\", \"\", \"\", \"\"],\n \"phone_number\": [\"18808770123\", \"18808770133\", \"18809770123\", \"18808773123\", \"18808774123\", \"18808775123\"],\n \"client_name\": [\"徐小艾\", \"刘思思\", \"何邺\", \"李雷\", \"韩梅梅\"],\n \"know_about_ruisi\": [\"听说过\", \"没听说过\"],\n \"reserve_time\": [\"周六\", \"周日\"],\n \"child_grade\": []\n }\n # 产生count个request slots,slot相对顺序仍然与user_request_slots保持一致\n self.goal = sorted(random.sample(self.user_request_slots, request_count), key=self.user_request_slots.index)\n self.dialog = []\n\n def user_response(self, agent_diaact):\n if agent_diaact['diaact'] == 'request' and agent_diaact['request_slots'] != {}:\n user_current_inform_slot = {}\n for i in agent_diaact['request_slots'].keys():\n user_current_inform_slot[i] = random.choice(self.dict_inform[i]) # user 对于agent的问题做出的回答\n\n prob = random.random()\n if prob > 0.5:\n # 用户只回答agent问题\n user_diaact = {\"diaact\": \"inform\", \"request_slots\": {}, \"inform_slots\":\n {list(user_current_inform_slot.keys())[0]: list(user_current_inform_slot.values())[0]}}\n elif 0.1 < prob < 0.5:\n # 问and答\n if self.goal != []:\n user_current_request_slot = random.choice(self.goal) # user要问的问题\n # print(\"用户当前选择问的问题\",user_current_request_slot)\n user_diaact = {\"diaact\": \"request\",\n \"request_slots\": {user_current_request_slot: \"UNK\"},\n \"inform_slots\": {list(user_current_inform_slot.keys())[0]:\n list(user_current_inform_slot.values())[0]}}\n self.goal.remove(user_current_request_slot)\n else:\n user_diaact = {\"diaact\": \"inform\", \"request_slots\": {},\n \"inform_slots\": {list(user_current_inform_slot.keys())[0]: list(user_current_inform_slot.values())[0]}}\n # 用户只问问题 不回答问题\n else:\n if self.goal != []:\n user_current_request_slot = random.choice(self.goal) # user要问的问题\n user_diaact = {\"diaact\": \"inform\",\n \"request_slots\": {user_current_request_slot: \"UNK\"},\n \"inform_slots\": {}}\n self.goal.remove(user_current_request_slot)\n else:\n user_diaact = {\"diaact\": \"bye\", \"request_slots\": {}, \"inform_slots\": {}}\n elif agent_diaact['diaact'] == 'confirm': # ???\n user_diaact = {'diaact': 'confirm_answer', 'request_slots': 'UNK', 'inform_slots': agent_diaact['inform_slots']}\n elif agent_diaact['diaact'] == 'select':\n l = json.loads(agent_diaact['inform_slots']['reserve_location'])\n # print('思思', [list(school.keys())[0] for school in l])\n user_diaact = {'diaact': 'inform', \"request_slots\": {}, \"inform_slots\": {\"reserve_location\":\n random.choice([list(school.keys())[0] for school in l])}}\n else:\n user_diaact = {'diaact': 'bye', 'request_slots': {}, 'inform_slots': {}}\n return user_diaact\n\n def store_diaact(self, diaact, speaker):\n if speaker == \"user\":\n diaact[\"speaker\"] = \"user\"\n else:\n diaact[\"speaker\"] = \"agent\"\n self.dialog.append(diaact)\n'''\ndialog = {}\ndialog_num = 1000\nfor i in range(dialog_num):\n dm = DM()\n user = UserSimulator(random.randint(1, 5))\n print(\"goal:\", user.goal)\n user_diaact = {\"diaact\": \"inform\", \"request_slots\": {}, \"inform_slots\": {\"user_goal\": \"预约\"}}\n while True:\n if user_diaact[\"diaact\"] == \"bye\":\n user.store_diaact(user_diaact, 'user')\n # print(\"user_diaact: \", user_diaact)\n break\n user.store_diaact(user_diaact, 'user')\n # print(\"user_diaact: \", user_diaact)\n agent_diaact = dm.agent_response_with_diaact(user_diaact)\n # print(\"agent_diaact: \", agent_diaact)\n user.store_diaact(agent_diaact, 'agent')\n user_diaact = user.user_response(agent_diaact)\n print(\"dialog {}:\".format(i), user.dialog)\n dialog[str(i)] = user.dialog\n\nwith open(\"simulated_dialog.json\", 'w', encoding='utf-8') as f:\n json.dump(dialog, f, ensure_ascii=False)\n'''\n\n\n\n\n\n\n\n\n\n\n","sub_path":"data/state_tracker/state_tracker/user_simulator.py","file_name":"user_simulator.py","file_ext":"py","file_size_in_byte":6057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"516767772","text":"\nfrom radis import plot_diff, SpectrumFactory\nimport numpy as np\nimport math\n\n\n# Computation parameters\nwmin = 2000\nwmax = 10000\nwstep = 0.01\nT = 300 #K\np = 1 #bar\nbroadening_max_width=300\n\nwmax_array = np.arange(4000, 18000, 2000)\n\nfor i in wmax_array:\n print(i)\n wmax = i\n \n #%% Calculate CO, 60000 lines\n sf = SpectrumFactory(wavenum_min=wmin, wavenum_max=wmax, \n pressure=p,\n wstep=wstep,\n broadening_max_width=broadening_max_width, \n molecule=\"CO\",\n cutoff=0, # 1e-27,\n verbose=0,\n )\n \n \n\n sf.load_databank('HITEMP-CO')\n #print(sf.df0)\n \n Ntarget = 60000\n sf.df0 = sf.df0[0:Ntarget]\n N = len(sf.df0)\n #print(N)\n #print(sf.df0)\n \n sf.params['optimization'] = 'simple'\n sf.params['broadening_method'] = 'fft'\n \n my_folder = r\"/home/pipebomb/Desktop/_Benchmark_LDM (Voigt Updated)/Spectral Range (Lines constant) vs Calculation Time/\"\n sf.init_database(my_folder, autoretrieve=False)\n \n cond = sf.get_conditions()\n name = cond['molecule'] + \"_\"+str(round(cond['wavenum_min']))+\"_\"+str(round(cond['wavenum_max']))+\"_\"+str(N)+\"_\"+sf.params['broadening_method']\n \n s_ldm = sf.eq_spectrum(T, name = name)\n \n #%% voigt\n sf.params['optimization'] = 'simple'\n sf.params['broadening_method'] = 'voigt'\n \n cond = sf.get_conditions()\n name = cond['molecule'] + \"_\"+str(round(cond['wavenum_min']))+\"_\"+str(round(cond['wavenum_max']))+\"_\"+str(N)+\"_\"+sf.params['broadening_method']\n \n s_ldm = sf.eq_spectrum(T, name = name)","sub_path":"LDM/LDM_Spectrum_updated_(N_lines_constant)/Benchmark.py","file_name":"Benchmark.py","file_ext":"py","file_size_in_byte":1664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"14241382","text":"from django.shortcuts import render\r\n\r\n# Create your views here.\r\nfrom .models import Breakthrough\r\n\r\ndef breakthrough_list(request):\r\n\tqueryset = Breakthrough.objects.all()\r\n\tcontext = {\r\n\t\t\"object_detail\": queryset,\r\n\t\t\"title\": \"Breakthrough List\",\r\n\t}\r\n\treturn render(request, \"breakthrough/index.html\", context)","sub_path":"breakthrough/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"288333888","text":"#!/usr/bin/env python3\n\nimport os, ntpath\n\ndef header(title, authors):\n head = r\"\"\"\n\\documentclass{article}\n\\usepackage[chorded]{songs}\n\\usepackage[utf8]{inputenc}\n\\usepackage[T1]{fontenc}\n\\usepackage{ae,lmodern}\n\\usepackage{xcolor}\n\\usepackage{hyperref}\n\\renewcommand\\printchord[1]{{\\color{gray}#1}}\n%%%%%%%%%%%% Page Layout %%%%%%%%%%\n\\oddsidemargin=0cm\n\\evensidemargin=0cm\n\\topmargin=0cm\n\\textwidth=15cm\n% \\textheight=700pt\n\\marginparwidth=10pt\n% \\hoffset=-0.2in\n% \\voffset=-0.6in\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\columnsep=1cm\n\\noversenumbers\n\\title{\"\"\" + title + r'}' + r\"\"\"\n\\author{\"\"\" + authors + r'}' + r\"\"\"\n\\newindex{titleidx}{titlefile}\n\\newauthorindex{authidx}{authfile}\n\\begin{document}\n\"\"\"\n return head\n\ndef titles():\n s = r'''\n\\newpage\n\n\\maketitle\n\nLes explications pour particier au répertoire sont dans ce \\href{https://github.com/tahitoaa/songbookreadme/blob/master/songbookreadme.md}{readme}\n\nLe lien vers le \\href{https://fr.overleaf.com/9457921969mhjkwjdnycqj}{projet overleaf}.\n\n%\\showindex[2]{Index of Song Titles}{titleidx}\n%\\showindex[2]{Index of Song Authors}{authidx}\n\\newpage\n'''\n return s\n\ndef footer():\n return r'''\\end{document}'''\n\ndef song(filename):\n ''' Path of the song from Chords, raw.'''\n s = ''\n s += r'\\chanson{' + filename + r'}{0}' + '\\n'\n return s\n\ndef dirsectionmap(sectiondir):\n if sectiondir == 'nochords':\n return 'Paroles sans accords'\n if sectiondir == 'withchords':\n return 'Paroles avec accords'\n pass\n\ndef section(sectiondir):\n songfiles = os.listdir(sectiondir)\n section = r'\\partie{' + dirsectionmap(ntpath.basename(sectiondir)) + r'}{' + '\\n'\n section += r'' + '\\n'\n for songfile in songfiles:\n section += song(songfile.replace('.tex', ''))\n section += r'}' + '\\n'\n return section\n\ndef sections(sectionsdir):\n sections = ''\n for sectiondir in os.listdir(sectionsdir):\n sections += section(r'./' + sectionsdir + r'/' +sectiondir)\n return sections\n\ndef main():\n print(r'\\input{macros}')\n print(r'\\debut')\n print(r'\\introcommune')\n print(sections('songs'))\n print(r'\\fini')\n pass\n\nif __name__=='__main__':\n main()\n","sub_path":"tex/struct/python/makemain.py","file_name":"makemain.py","file_ext":"py","file_size_in_byte":2184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"48936522","text":"import pytest\n\nimport contessa\nfrom contessa import ContessaRunner\n\n\ndef test_attribute_in_custom_sql_rule():\n r = [\n {\n \"name\": \"test_rule_name\",\n \"type\": contessa.SQL,\n \"sql\": \"select 1\",\n \"column\": \"col_name\",\n \"description\": \"some description\",\n },\n {\n \"name\": \"test_gt_rule\",\n \"type\": contessa.GT,\n \"value\": 3,\n \"column\": \"mycol\",\n \"description\": \"desc\",\n },\n ]\n rules = ContessaRunner.build_rules(r)\n assert rules[0].attribute == \"col_name\"\n\n\ndef test_no_attribute_in_custom_sql_rule():\n r = [\n {\n \"name\": \"test_rule_name\",\n \"type\": contessa.SQL,\n \"sql\": \"select 1\",\n \"description\": \"some description\",\n }\n ]\n with pytest.raises(TypeError):\n ContessaRunner.build_rules(r)\n","sub_path":"test/unit/test_custom_sql_rule.py","file_name":"test_custom_sql_rule.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"256737499","text":"import math\n\ndef main():\n # Escribe tu código abajo de esta línea\n def ecuaciones_cuadraticas():\n \n from math import sqrt\n \n a = float(input(\"Dame el valor de a: \"))\n b = float(input(\"Dame el valor de b: \"))\n c = float(input(\"Dame el valor de c: \"))\n \n t = (b**2)-(4*a*c)\n \n if t < 0:\n print(\"Raices complejas\")\n \n elif t == 0:\n print(-b/2*a)\n \n if a == 0 and b != 0:\n print(-c/b)\n \n if a == 0 and b == 0:\n print(\"La ecuación no tiene solución\")\n \n \n e = sqrt(t)\n x = (-b + e)/(2*a)\n z = (-b - e)/(2*a)\n\n \n if a != 0 and b != 0:\n print(x)\n print(z)\n \n \n\n ecuaciones_cuadraticas() \n\n pass\n\nif __name__ == '__main__':\n main()\n","sub_path":"assignments/05Cuadratica/src/exercise.py","file_name":"exercise.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"11836285","text":"import re\n\nfrom openpecha.serializers import Serialize\n\nclass SerializeFootNote(Serialize):\n \"\"\"\n Serializes the foot-note for given text_id\n \"\"\"\n\n def apply_annotation(self, vol_id, ann):\n payload = ''\n if ann['type'] == 'pagination':\n payload = f'[{ann[\"page_index\"]}] {ann[\"page_info\"]}\\n'\n start_cc, end_cc = self._get_adapted_span(ann['span'], vol_id)\n self.add_chars(vol_id, start_cc, True, payload)\n elif 'peydurma' in ann['type']:\n payload = f'<{ann[\"note\"]}>'\n start_cc, end_cc = self._get_adapted_span(ann['span'], vol_id)\n self.add_chars(vol_id, end_cc, False, payload)\n elif ann['type'] == 'correction':\n start_cc, end_cc = self._get_adapted_span(ann['span'], vol_id)\n error = self.base_layers[vol_id][start_cc: end_cc+1]\n self.base_layers[vol_id] = self.base_layers[vol_id][:start_cc] + ann['correction'] + \\\n self.base_layers[vol_id][end_cc+1:]\n\n payload = f'<{error} སྡེ་དགེ།>'\n n_diff = len(ann['correction']) - len(error)\n if not n_diff == 0:\n self.n_char_shifted.append((ann['span']['start'], n_diff))\n start_cc, end_cc = self._get_adapted_span(ann['span'], vol_id)\n self.add_chars(vol_id, end_cc, False, payload)\n \n\n\n def generate_foot_notes(self, text):\n\n annotated_text = ''\n foot_notes = []\n notes = re.finditer(r'\\<.*?\\>', text)\n last_note_end_idx = 0\n for i, note in enumerate(notes):\n start, end = note.span(0)\n note_text = text[start: end]\n annotated_text += text[last_note_end_idx: start]\n foot_note_id = f'[^{i+1}K]'\n annotated_text += foot_note_id\n foot_notes.append(f'{foot_note_id}: {note_text[1:-1]}')\n last_note_end_idx = note.span(0)[1]\n else:\n annotated_text += text[last_note_end_idx:]\n\n return annotated_text + '\\n\\n' + '\\n'.join(foot_notes)\n\n\n def get_result(self):\n self.layers.pop()\n annotated_text, text_id = Serialize.get_result(self)\n return self.generate_foot_notes(annotated_text), text_id\n\nif __name__ == \"__main__\":\n OPF_PECHA_PATH = '../openpecha-user/.openpecha/data/P000002/P000002.opf'\n\n serializer = SerializeFootNote(OPF_PECHA_PATH, text_id='D1794', layers=['correction', 'peydurma-note', 'pagination'])\n serializer.apply_layers()\n annotated_text, text_id = serializer.get_result()\n print(annotated_text)","sub_path":"openpecha/serializers/foot_note.py","file_name":"foot_note.py","file_ext":"py","file_size_in_byte":2591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"558292455","text":"import pandas as pd\nimport CB as cb\n\n# ----------------------------------------------\n\nparallelism_cases = [True]\n\n\nclass Dataization(object):\n def __init__(self, keys, values):\n for (key, value) in zip(keys, values):\n self.__dict__[key] = value\n\n\nif __name__ == '__main__':\n\n for enableParallelism in parallelism_cases:\n print(\"-------------------------\")\n print(\"Validation set case\")\n df = pd.read_csv(\"dataset/wine.csv\")\n train_data, test_data = cb.data_split(df, 0.3)\n\n # ---------------------------\n # class and pandas to numpy\n attribute = [i.replace(' ','') for i in df]\n train_data_value = train_data.to_numpy()\n test_data_value = test_data.to_numpy()\n train_data = [Dataization(attribute, df.iloc[i]) for i in range(train_data_value.shape[0])]\n test_data = [Dataization(attribute, df.iloc[i]) for i in range(test_data_value.shape[0])]\n # --------------------------\n\n config = {'algorithm': 'C4.5', 'enableParallelism': enableParallelism}\n\n model = cb.fit(train_data, config, attribute, target_label='Decision', validation_df=test_data)\n\n print(\"-------------------------\")\n print(\"unit tests completed successfully...\")\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"542840746","text":"import yaml\nimport json\nimport datetime\nimport decimal\nimport tornado.httpclient\nfrom funnel.util.rfc822 import email_address_re\n\ndef async_fetch(url, response_callback):\n http_client = tornado.httpclient.AsyncHTTPClient()\n http_client.fetch(url, response_callback)\n\n\ndef validate_email(email):\n return email_address_re.match(email) != None\n\n\ndef merge_dicts(original, update, inplace=False):\n '''Recursively updates dictionary'''\n if inplace:\n return _merge_dicts_inplace(original, update)\n #if not inplace, merge {} <- original <- updates\n return _merge_dicts_inplace({}, original, update)\n\ndef _merge_dicts_inplace(original, *updates):\n for update in updates:\n for key, val in update.iteritems():\n if isinstance(val, dict):\n section = original.setdefault(key,{})\n _merge_dicts_inplace(section, val)\n else:\n original[key] = val\n return original\n\n\nclass _property(object):\n def __init__(self, fget, doc=None):\n self.fget = fget\n self.__doc__ = doc or fget.__doc__\n self.__name__ = fget.__name__\n self.__module__ = fget.__module__\n\nclass classproperty(_property):\n def __get__(self, obj, cls):\n return self.fget(cls)\n\nclass cached_property(_property):\n def __get__(self, obj, cls):\n if obj is None:\n return self\n setattr(obj, self.__name__, self.fget(obj))\n return getattr(obj, self.__name__)\n\nclass cached_classproperty(cached_property):\n def __get__(self, obj, cls):\n setattr(cls, self.__name__, self.fget(cls))\n return getattr(cls, self.__name__)\n\n\nclass JSONEncoder(json.JSONEncoder):\n \"\"\"\n JSONEncoder subclass that knows how to encode datetime types and \n \"\"\"\n def default(self, o):\n # See \"Date Time String Format\" in the ECMA-262 specification.\n if isinstance(o, datetime.date):\n return o.isoformat()\n if isinstance(o, datetime.datetime):\n r = o.isoformat()\n if o.microsecond:\n r = r[:23] + r[26:]\n if r.endswith('+00:00'):\n r = r[:-6] + 'Z'\n return r\n if isinstance(o, datetime.time):\n if o.tzinfo is not None and o.tzinfo.utcoffset(o) is not None:\n raise ValueError(\"JSON can't represent timezone-aware times.\")\n r = o.isoformat()\n if o.microsecond:\n r = r[:12]\n return r\n if isinstance(o, decimal.Decimal):\n return str(o)\n if hasattr(o, '__jsonic__'):\n return o.__jsonic__()\n return super(JSONEncoder, self).default(o)\n\n\nclass YamlConfig(dict):\n def parse_file(self, fname=\"config.yaml\"):\n with open(fname, 'r') as config_file:\n self.parse_yaml(config_file)\n\n def parse_yaml(self, yaml_src):\n update = yaml.load(yaml_src)\n merge_dicts(self, update, inplace=True)\n\n for k,v in self['tornado'].iteritems():\n tornado.options.options[k].set(v)\n\n def __getattr__(self, name):\n return self[name]\n\n\n\n\n\n","sub_path":"funnel/util/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"103207265","text":"from django.conf.urls import url,include\r\nfrom django.contrib import admin\r\nfrom .import views\r\n\r\nurlpatterns = [\r\n url(r'^$', views.home,name=\"home\"),\r\n url(r'^fberror/', views.error,name=\"errorpage\"),\r\n url(r'^success/', views.success,name=\"success\"),\r\n url(r'^fberror2/', views.error2,name=\"errorpage2\"),\r\n url(r'^insert/', views.insert,name=\"errorpage2\")\r\n\r\n\r\n\r\n]","sub_path":"facebook/facebooklog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"410984307","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# vim:fenc=utf-8\n#\n# Copyright © 2016 Yi Cao \n#\n# Distributed under terms of the GNU General Public License 3.0 license.\n\n\"\"\"\nString to Integer\nURL: https://leetcode.com/problems/string-to-integer-atoi/\n\"\"\"\n\n\nclass Solution(object):\n def myAtoi(self, str):\n \"\"\"\n :type str: str\n :rtype: int\n \"\"\"\n str = str.strip()\n if len(str) == 0:\n return 0\n i = 0\n sign = +1\n if str[0] in (\"-\", \"+\"):\n i = 1\n if str[0] == \"-\":\n sign = -1\n ans = 0\n MAX_INT = 2147483647\n MIN_INT = -2147483648\n while (i < len(str)):\n if not str[i].isdigit():\n break\n digit = int(str[i])\n if ((sign > 0) and ((MAX_INT - digit) // 10 < ans)):\n return MAX_INT\n if ((sign < 0) and ((MIN_INT + digit - 1) // 10 + 1 > ans)):\n return MIN_INT\n ans = ans * 10 + sign * int(str[i])\n i += 1\n return ans\n","sub_path":"problem_008.py","file_name":"problem_008.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"283658129","text":"# Remove endpoints that ends with the given strings\n# Example:\n# exclude_endswith = [\"*.jpg\", \"*.png\", \"*.ico\", \"*.pdf\", \"*.css\", \"*.gif\"]\nexclude_endswith = []\n##################################\n# Remove endpoints that contains the given strings in any place\n# Example:\n# exclude_contain = [\"product\", \"Scripts\", \"a/h/\", \"about\", \"article/\", \"assets/\", \"bd/\", \"blog\", \"comment\", \"item/\", \"es/\", \"ru/\", \"eg/\", \"fr/\", \"uk/\", \"ua/\", \"tw/\", \"search\", \"global/\", \"hk/\", \"in/\", \"it/\", \"tr/\", \"us/\", \"vn/\", \"en/\"]\nexclude_contain = []\n##################################\n# Remove any endpoints that 'match' this regular expressions.\n# Example:\n# remove_regex = [\"^(\\d*)-(\\d*)\", \"^(\\d*)\\.html$\", \"^(\\d*)$\"]\nremove_regex = []\n","sub_path":"filter_model.py","file_name":"filter_model.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"242128082","text":"###################\n# Plots asked for by Anja for her Mar 2012 ESO proposal\n###################\n\nimport publication_plots as pp\nimport cPickle\nfrom dappleutils import readtxtfile\nimport pylab, numpy as np\nimport nfwutils, compare_masses as cm\nimport maxlike_secure_bentstep3_voigt_driver as driver\n\n\n###################\n\ndef precisionZ(data = None):\n #mass precision as a function of redshift\n\n if data is None:\n data = {}\n\n if 'fracerrs' not in data:\n\n items = [tuple(x) for x in readtxtfile('worklist')]\n\n\n allmasses = cm.readDougMasses('/u/ki/dapple/subaru/doug/publication/baseline_2012-05-17')\n\n redshifts = cm.readClusterRedshifts()\n\n clusters = [x[0] for x in items]\n\n properz = np.array([redshifts[x] for x in clusters])\n\n masses, errs = cm.constructMassArray(allmasses, items)\n\n\n fracerrs = errs / masses\n\n aveerrs = np.mean(fracerrs, axis=0)\n\n data['aveerrs'] = aveerrs\n data['properz'] = properz\n\n ccitems = [tuple(x) for x in readtxtfile('referenceset')]\n \n ccmasses = cm.readAnjaMasses()\n clusters = [x[0] for x in ccitems]\n ccproperz = np.array([redshifts[x] for x in clusters])\n data['ccproperz'] = ccproperz\n \n masses, errs = cm.constructMassArray(ccmasses, ccitems)\n \n fracerrs = errs/masses\n \n ccaveerrs = np.mean(fracerrs, axis=0)\n\n data['ccaveerrs'] = ccaveerrs\n \n\n else:\n\n aveerrs = data['aveaerrs']\n properz = data['properz']\n \n ccaveerrs = data['ccaveerrs']\n ccproperz = data['ccproperz']\n\n \n fig = pylab.figure()\n ax = fig.add_axes([0.12, 0.12, 0.95-0.12, 0.95-0.12])\n ax.plot(ccproperz, ccaveerrs, 'bo', label = 'Color-Cut', mfc = 'None', mew = 1.0, mec='b')\n ax.plot(properz, aveerrs, 'rD', label = 'P($z$)')\n ax.set_xlabel('Cluster Redshift')\n ax.set_ylabel('Fractional Statistical Uncertainty M(r$<$1.5Mpc)')\n ax.set_xlim([0.14, 0.72])\n ax.legend(loc='upper left', numpoints = 1)\n\n fig.savefig('publication/aveerr_redshift.eps')\n \n\n return fig, data\n\n \n##########################\n\n\ndef galdensity(data = None):\n\n if data is None:\n data = {}\n\n \n if 'ngals' not in data:\n\n \n\n ngals = cPickle.load(open('galaxy_counts_pzmethod.pkl', 'rb'))\n data['ngals'] = ngals\n \n\n\n items = [tuple(x) for x in readtxtfile('worklist')]\n clusters = [x[0] for x in items]\n\n redshifts = cm.readClusterRedshifts()\n properz = np.array([redshifts[x] for x in clusters])\n data['properz'] = properz\n\n Dl = np.array([nfwutils.angulardist(z) for z in properz])\n data['Dl'] = Dl\n\n inner_rad = np.arctan2(0.75, Dl) * (180./np.pi) * 60\n outer_rad = np.arctan2(3., Dl) * (180 / np.pi) * 60\n area = np.pi*(outer_rad**2 - inner_rad**2)\n data['area'] = area\n\n propercounts = np.array([ngals[x] for x in items])\n \n density = propercounts / area\n data['density'] = density\n\n else:\n\n properz = data['properz']\n density = data['density']\n \n\n fig = pylab.figure()\n ax = fig.add_axes([0.12, 0.12, 0.95 - 0.12, 0.95 - 0.12])\n ax.plot(properz, density, 'bo')\n ax.set_xlabel('Cluster Redshift')\n ax.set_ylabel('Input Galaxy Density')\n\n return fig, data\n\n\n######################################\n\n\ndef lostgals(data = None):\n\n if data is None:\n\n data = {}\n\n items = readtxtfile('worklist')\n del items[-1]\n clusters = [x[0] for x in items]\n\n\n if 'properz' not in data:\n\n\n\n\n redshifts = cm.readClusterRedshifts()\n properz = np.array([redshifts[x] for x in clusters])\n data['properz'] = properz\n else:\n properz = data['properz']\n\n if 'properbase' not in data:\n\n basecuts = {}\n for cluster, filter, image in items:\n\n controller = driver.makeController()\n\n options, args = controller.modelbuilder.createOptions()\n options, args = controller.filehandler.createOptions(options = options, args = args,\n workdir = '/u/ki/dapple/ki06/catalog_backup_2012-02-08',\n incatalog = '/u/ki/dapple/ki06/catalog_backup_2012-02-08/%s.%s.%s.lensingbase.cat' % (cluster, filter, image),\n cluster = cluster, filter = filter, image = image,\n redseqcat = '/u/ki/dapple/ki06/catalog_backup_2012-02-08/%s.%s.%s.redsequence.cat' % (cluster, filter, image), shapecut = True)\n\n controller.load(options, args)\n\n basecuts[cluster] = controller.ngalaxies\n data['basecuts'] = basecuts\n properbase = np.array([basecuts[x[0]] for x in items])\n data['properbase'] = properbase\n\n else:\n\n properbase = data['properbase']\n\n if 'properloose' not in data:\n\n loosecuts = {}\n for cluster, filter, image in items:\n\n controller = driver.makeController()\n\n options, args = controller.modelbuilder.createOptions(deltaz95high = 9999, zbhigh = 9999)\n options, args = controller.filehandler.createOptions(options = options, args = args,\n workdir = '/u/ki/dapple/ki06/catalog_backup_2012-02-08',\n incatalog = '/u/ki/dapple/ki06/catalog_backup_2012-02-08/%s.%s.%s.lensingbase.cat' % (cluster, filter, image),\n cluster = cluster, filter = filter, image = image,\n redseqcat = '/u/ki/dapple/ki06/catalog_backup_2012-02-08/%s.%s.%s.redsequence.cat' % (cluster, filter, image), shapecut = True)\n\n controller.load(options, args)\n\n loosecuts[cluster] = controller.ngalaxies\n data['loosecuts'] = loosecuts\n properloose = np.array([loosecuts[x[0]] for x in items])\n data['properloose'] = properloose\n\n else:\n \n properloose = data['properloose']\n\n if 'ratio' not in data:\n\n ratio = 1 - (properbase.astype('float64') / properloose)\n data['ratio'] = ratio\n\n else:\n\n ratio = data['ratio']\n\n fig = pylab.figure()\n ax = fig.add_axes([0.12, 0.12, 0.95 - 0.12, 0.95 - 0.12])\n ax.plot(properz, ratio, 'bo')\n ax.set_xlim([0.16, 0.72])\n\n ax.set_xlabel('Cluster Redshift')\n ax.set_ylabel('Fraction of Catalog Discarded')\n\n return fig, data\n \n \n \n######################################\n\n","sub_path":"anja_plots.py","file_name":"anja_plots.py","file_ext":"py","file_size_in_byte":6702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"437482117","text":"import json\nimport logging\nimport re\nimport shlex\n\nimport rethinkdb as r\n\nfrom plumeria.command import commands, channel_only, CommandError, ArgumentParser\nfrom plumeria.event import bus\nfrom plumeria.perms import server_admins_only\nfrom plumeria.rethinkdb import migrations, pool\nfrom plumeria.transport import transports\nfrom plumeria.webserver import app\n\nWEB_HOOK_URL = \"/gitlab-webhooks/hook/\"\nTOKENS_TABLE = \"gitlabhooks_tokens\"\nSUBSCRIPTIONS_TABLE = \"gitlabhooks_subscriptions\"\nMAX_COMMITS_PER_MESSAGE = 8\n\nlogger = logging.getLogger(__name__)\n\n\ndef valid_project_path(s):\n if re.match(\"^[A-Za-z0-9\\\\-_\\\\.,]{1,100}/[A-Za-z0-9\\\\-_\\\\.,]{1,100}$\", s):\n return s\n raise ValueError(\"Invalid project! Must match regex `^[A-Za-z0-9\\\\-_]{1,100}/[A-Za-z0-9\\\\-_]{1,100}$`\")\n\n\n@bus.event('preinit')\nasync def preinit():\n async def initial(conn):\n await r.table_create(TOKENS_TABLE).run(conn)\n await r.table(TOKENS_TABLE).index_create(\"server_id\", r.row[\"server_id\"]).run(conn)\n await r.table_create(SUBSCRIPTIONS_TABLE).run(conn)\n await r.table(SUBSCRIPTIONS_TABLE).index_create(\"server_id_channel_id\",\n [r.row[\"server_id\"], r.row[\"channel_id\"]]).run(conn)\n await r.table(SUBSCRIPTIONS_TABLE).index_create(\"server_id_channel_id_project_path\",\n [r.row[\"server_id\"], r.row[\"channel_id\"],\n r.row['project_path']]).run(conn)\n\n await migrations.migrate(\"gitlab_hooks\",\n ((\"initial\", initial),))\n\n\n@commands.register('gitlab url', category='GitLab')\n@channel_only\n@server_admins_only\nasync def url(message):\n \"\"\"\n Return the webhook URL that needs to be entered into GitLab in order to\n send events to Plumeria. Both a URL and a token is required, so you will\n have to generate a token and add it too.\n\n Tokens are generally sent as a HTTP header from GitLab, but the token\n can also be provided in a query parameter as ``__token``.\n\n Example::\n\n /gitlab url\n\n Response::\n\n http://example.com/gitlab-webhooks/hook/\n \"\"\"\n return \"Send webhook POSTs to `{}{}`\".format(await app.get_base_url(), WEB_HOOK_URL)\n\n\n@commands.register('gitlab addtoken', category='GitLab')\n@channel_only\n@server_admins_only\nasync def add_token(message):\n \"\"\"\n Add a token that must be present for GitLab hooks to work. Tokens are generated by you\n and also provided to GitLab when registering a webhook URL. Tokens\n are per-server, so adding a token will allow any channel to be\n subscribed to any repository sending events.\n\n The response will contain the webhook URL that you must use.\n\n Tokens are generally sent as a HTTP header from GitLab, but the token\n can also be provided in a query parameter as ``__token``.\n\n Example::\n\n /gitlab addtoken EG9hh43bcKTxqFrn\n \"\"\"\n token = message.content.strip()\n if not re.match(\"^([^ ]+){1,50}$\", token):\n raise CommandError(\"Tokens should mach the regex `^([^ ]+){1,50}$`.\")\n async with pool.acquire() as conn:\n cursor = await r.table(TOKENS_TABLE).filter({\"server_id\": message.channel.server.id,\n \"token\": token}).run(conn)\n if not await cursor.fetch_next():\n await r.table(TOKENS_TABLE).insert({\n \"server_id\": message.channel.server.id,\n \"token\": token}).run(conn)\n return \"\\u2705 Token '{}' added. Send webhook POSTs to `{}{}`\" \\\n .format(token, await app.get_base_url(), WEB_HOOK_URL)\n else:\n raise CommandError(\"Token '{}' was already added.\".format(token))\n\n\n@commands.register('gitlab removetoken', 'gitlab deletetoken', category='GitLab')\n@channel_only\n@server_admins_only\nasync def remove_token(message):\n \"\"\"\n Remove a token that was previously added.\n\n Example::\n\n /gitlab removetoken EG9hh43bcKTxqFrn\n \"\"\"\n token = message.content.strip()\n if not re.match(\"^([^ ]+){1,50}$\", token):\n raise CommandError(\"Tokens should mach the regex `^([^ ]+){1,50}$`.\")\n async with pool.acquire() as conn:\n ret = await r.table(TOKENS_TABLE).filter({\n \"server_id\": message.channel.server.id,\n \"token\": token}).delete().run(conn)\n if ret['deleted'] > 0:\n return \"\\u2705 Token '{}' deleted.\".format(token)\n else:\n raise CommandError(\"The token '{}' wasn't added yet.\".format(token))\n\n\n@commands.register('gitlab tokens', category='GitLab')\n@channel_only\n@server_admins_only\nasync def subscriptions(message):\n \"\"\"\n Get a list of active webhook tokens for this server.\n\n Example::\n\n /gitlab tokens\n \"\"\"\n async with pool.acquire() as conn:\n cursor = await r.table(TOKENS_TABLE) \\\n .filter({\"server_id\": message.channel.server.id}) \\\n .run(conn)\n tokens = []\n while await cursor.fetch_next():\n tokens.append((await cursor.next())['token'])\n if len(tokens):\n return \", \".join(map(lambda x: \"`{}`\".format(x), tokens))\n else:\n raise CommandError(\"No tokens added yet!\")\n\n\n@commands.register('gitlab subscribe', 'gitlab sub', category='GitLab')\n@channel_only\n@server_admins_only\nasync def subscribe(message):\n \"\"\"\n Subscribe to events for a repository on GitLab so that any changes\n will be posted in the channel that this command is run in. Events will only actually\n be announced if webhooks are properly setup from GitLab for every\n repository that you want to subscribe to.\n\n By default, the subscription will only act on push events, but a list of\n event types can be provided as an extra parameter. Get a list of event types\n from GitLab. However, at the moment, only push events are supported.\n\n Example::\n\n /gitlab sub sk89q/plumeria\n /gitlab sub sk89q/plumeria push,tag_push\n\n \"\"\"\n parser = ArgumentParser()\n parser.add_argument(\"project_path\", type=valid_project_path)\n parser.add_argument(\"events\", nargs=\"*\")\n args = parser.parse_args(shlex.split(message.content))\n events = args.events if len(args.events) else ('push',)\n\n async with pool.acquire() as conn:\n await r.table(SUBSCRIPTIONS_TABLE) \\\n .filter({\"server_id\": message.channel.server.id,\n \"channel_id\": message.channel.id,\n \"project_path\": args.project_path}) \\\n .delete() \\\n .run(conn)\n await r.table(SUBSCRIPTIONS_TABLE).insert({\"server_id\": message.channel.server.id,\n \"channel_id\": message.channel.id,\n \"project_path\": args.project_path,\n \"events\": events}).run(conn)\n\n return \"\\u2705 Subscribed to **{project_path}** in **#{channel}** for events: {events}\" \\\n .format(project_path=args.project_path,\n channel=message.channel.name,\n events=\", \".join(events))\n\n\n@commands.register('gitlab unsubscribe', 'gitlab unsub', category='GitLab')\n@channel_only\n@server_admins_only\nasync def unsubscribe(message):\n \"\"\"\n Unsubscribe from events for a repository.\n\n Example::\n\n /gitlab unsub sk89q/plumeria\n \"\"\"\n parser = ArgumentParser()\n parser.add_argument(\"project_path\", type=valid_project_path)\n args = parser.parse_args(shlex.split(message.content))\n\n async with pool.acquire() as conn:\n ret = await r.table(SUBSCRIPTIONS_TABLE) \\\n .filter({\"server_id\": message.channel.server.id,\n \"channel_id\": message.channel.id,\n \"project_path\": args.project_path}) \\\n .delete() \\\n .run(conn)\n if ret['deleted'] == 1:\n return \"Unsubscribed from '{}'.\".format(args.project_path)\n else:\n raise CommandError(\"This channel wasn't subscribed to events from that repository.\")\n\n\n@commands.register('gitlab subscriptions', 'gitlab subs', category='GitLab')\n@channel_only\n@server_admins_only\nasync def subscriptions(message):\n \"\"\"\n Get a list of active subscriptions for this channel.\n\n Example::\n\n /gitlab subs\n \"\"\"\n async with pool.acquire() as conn:\n cursor = await r.table(SUBSCRIPTIONS_TABLE) \\\n .filter({\"server_id\": message.channel.server.id,\n \"channel_id\": message.channel.id}) \\\n .run(conn)\n projects = []\n while await cursor.fetch_next():\n projects.append((await cursor.next())['project_path'])\n if len(projects):\n return \", \".join(map(lambda x: \"`{}`\".format(x), projects))\n else:\n raise CommandError(\"This channel is not subscribed to any notifications from any GitLab repositories.\")\n\n\ndef format_message(payload):\n if payload['event_name'] == 'push':\n if payload['before'] == \"0000000000000000000000000000000000000000\":\n return \"\\U0001F539 [**{project}**] New branch **{branch}** was pushed by {author}\".format(\n project=payload['project']['path_with_namespace'],\n branch=re.sub(\"^refs/heads/\", \"\", payload['ref']),\n author=payload['user_name'])\n elif payload['after'] == \"0000000000000000000000000000000000000000\":\n return \"\\U0001F539 [**{project}**] Branch **{branch}** deleted by {author}\".format(\n project=payload['project']['path_with_namespace'],\n branch=re.sub(\"^refs/heads/\", \"\", payload['ref']),\n author=payload['user_name'])\n else:\n commit_count = len(payload['commits'])\n commits = \"\\n\".join(map(lambda commit: \"\\u2022 {}: {}\"\n .format(commit['id'][:8], commit['message'].splitlines()[0]),\n list(reversed(payload['commits']))[:MAX_COMMITS_PER_MESSAGE]))\n return \"\\U0001F539 [**{project}** on **{branch}**] {count} commit{s} by {author}:\\n{commits}{more}\".format(\n count=commit_count,\n s=\"s\" if commit_count != 1 else \"\",\n project=payload['project']['path_with_namespace'],\n branch=re.sub(\"^refs/heads/\", \"\", payload['ref']),\n author=payload['user_name'],\n hash=payload['after'][:8],\n commits=commits,\n more=\"\\n+{} more\".format(commit_count - MAX_COMMITS_PER_MESSAGE) if commit_count > MAX_COMMITS_PER_MESSAGE else \"\",\n url=payload['repository']['homepage'])\n\n\n@app.route(WEB_HOOK_URL, methods=['POST'])\nasync def handle(request):\n token = request.headers.get(\"X-Gitlab-Token\", \"\")\n token_override = request.GET.get(\"__token\", \"\")\n\n if len(token_override):\n token = token_override\n\n if not len(token):\n logger.debug(\"Received GitLab hook from {} with no token\".format(request.transport.get_extra_info('peername')))\n return \"no token\"\n else:\n logger.debug(\n \"Received GitLab hook from {} with token '{}'\".format(request.transport.get_extra_info('peername'), token))\n\n data = await request.text()\n payload = json.loads(data)\n event = payload['event_name']\n project_path = payload['project']['path_with_namespace']\n\n async with pool.acquire() as conn:\n cursor = await r.table(TOKENS_TABLE) \\\n .filter({\"token\": token}) \\\n .inner_join(r.table(SUBSCRIPTIONS_TABLE),\n lambda token_row, sub_row: token_row['server_id'] == sub_row['server_id']) \\\n .run(conn)\n\n while await cursor.fetch_next():\n row = await cursor.next()\n if event not in row['right']['events']:\n continue\n if project_path != row['right']['project_path']:\n continue\n\n for transport in transports.transports.values():\n for server in transport.servers:\n if server.id == row['left']['server_id']:\n for channel in server.channels:\n if channel.id == row['right']['channel_id']:\n await channel.send_message(format_message(payload))\n\n return \"OK\"\n","sub_path":"plumeria/plugins/gitlab_hooks.py","file_name":"gitlab_hooks.py","file_ext":"py","file_size_in_byte":12396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"433680699","text":"from selenium import webdriver\nfrom pprint import pprint\nimport json\nimport random\nimport time\nfrom pathlib import Path\n\nimport sDB\n\nimport collinsScrape\nimport oaldScrape\n\ndef waitx():\n sr = random.SystemRandom()\n waitTimeSec = sr.randrange(180, 300)\n time.sleep(int(waitTimeSec))\n\n\n#get words from list\npayload = []\n\nfileList = []\n\nfor item in Path('lists/').rglob('*'):\n if item.is_file():\n fileList.append(str(item))\n\nfor item in fileList:\n worldList = []\n with open(item, 'r') as fh:\n fileLines = fh.readlines()\n for line in fileLines:\n worldList.append(line.split(\" \")[0].strip())\n payload.append({\n 'listName' : item,\n 'worldList' : worldList\n })\n\nPROXY = \"localhost:80\"\nwebdriver.DesiredCapabilities.FIREFOX['proxy'] = {\n \"httpProxy\": PROXY,\n \"ftpProxy\": PROXY,\n \"sslProxy\": PROXY,\n \"proxyType\": \"DIRECT\",\n\n}\n\n\ndef logErr(fileName, word, errorMsg=''):\n errorTxt = word + ' |||| ' + str(errorMsg)\n with open(fileName + '.log', 'a') as fh:\n fh.write(errorTxt) \n\n\nwith webdriver.Firefox() as driver:\n for dk in [collinsScrape, oaldScrape]:\n baseURL = dk.baseURL\n fileName = dk.fileName\n \n for item in payload:\n worldList = item['worldList']\n\n dbFile = fileName + '.sqlite'\n dbConn = sDB.start(dbFile)\n \n index = 0\n while index < len(worldList):\n word = worldList[index]\n if sDB.checkEntry(word, dbConn):\n print('Duplicate Entry::', index, ':', word)\n index += 1\n continue\n print('Extracting::', index, ':', word)\n url = baseURL.format(word)\n # Open URL\n try:\n driver.get(url)\n source = driver.page_source\n except Exception as e:\n print(e)\n waitx()\n index = 0\n continue\n else:\n try:\n entry = dk.getEntry(source)\n except Exception as e1:\n print(\"UNABLE TO EXTRACT ENTRY::\", e1)\n pprint(source)\n index += 1\n logErr(fileName, word, str(e1))\n continue\n if entry is not None:\n sDB.insertEntry(entry, dbConn)\n else:\n errMsg = 'Entry not Found in ' + fileName\n print(errMsg, \"::\", word)\n logErr(fileName, word, errMsg)\n index += 1\n sDB.end(dbConn)\n","sub_path":"start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":2760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"493724464","text":"import os\nfrom os.path import join, dirname, abspath\nimport sys\nimport string\nimport subprocess\nfrom optparse import OptionParser\n\norig_pwd = abspath(os.path.curdir)\ntop_srcdir = dirname(dirname(abspath(sys.argv[0])))\ntrace_home = os.environ.get(\"LTTNG_TRACE_HOME\", orig_pwd)\n\nchunk = {\n \"byte\": 1,\n \"word\": 8,\n \"page\": 1 << 12,\n \"huge\": 1 << 20,\n}\n\nexperiences = {\n \"page_nofill_word\": {\n \"where\": \"page\",\n \"block-size\": \"word\",\n \"block-count\": 200,\n \"fill\": False },\n \"page_fill_word\": {\n \"where\": \"page\",\n \"block-size\": \"word\",\n \"block-count\": 200,\n \"fill\": True },\n \"stack_nofill_page\": {\n \"where\": \"stack\",\n \"block-size\": \"page\",\n \"block-count\": 200,\n \"fill\": False },\n \"heap_fill_word\": {\n \"where\": \"heap\",\n \"block-size\": \"word\",\n \"block-count\": 200,\n \"fill\": True }\n}\n\n# let's fix max-mem to be always 1000 * chunk size\ndef build_drmem_cmd(options, name, exp):\n cmd = [ \"lttng-simple\", \"-c\", \"-u\", \"-k\" ]\n cmd += [ \"-e\", \"mm\" ]\n cmd += [ \"--enable-libc-wrapper\" ]\n cmd += [ \"--stateless\", \"--name\", name, \"--\" ]\n cmd += [ join(options.drmem_dir, \"drmem\") ]\n cmd += [ \"--where\", exp.get(\"where\", \"heap\") ]\n bs = exp.get(\"block-size\", \"page\")\n cmd += [ \"--block-size\", bs ]\n bc = exp.get(\"block-count\", 100)\n # allocate at least 1MB\n max_mem = bc * chunk[bs]\n if (max_mem < (1 << 20)):\n max_mem = 1 << 20\n\n cmd += [ \"--max-mem\", str(max_mem) ]\n cmd += [ \"--delay\", \"5\" ]\n fill = exp.get(\"fill\", True)\n if (fill): cmd += [ \"--fill\" ]\n trim = exp.get(\"trim\", None)\n if (trim):\n cmd += [ \"--trim\", str(trim) ]\n return cmd\n\ndef build_kmem_cmd(name, output_dir):\n trace_dir = join(trace_home, name + \"-k-u\")\n jar_file = join(top_srcdir, \"scripts\", \"lttng-kmem.jar\")\n cmd = [ \"java\", \"-jar\", jar_file ]\n cmd += [ \"--output\", output_dir, trace_dir ]\n return cmd\n\ndef build_gnuplot_cmd(name, outputdir):\n cmd = [ \"gnuplot\", \"data.gnuplot\" ]\n return cmd;\n\ndef run_cmd(cmd):\n ret = subprocess.call(cmd)\n if ret != 0:\n raise RuntimeError(\"Command failed: \" + string.join(cmd, \" \"))\n\ndef do_one(options, name, exp):\n output_dir = join(top_srcdir, \"results\", name)\n cmd1 = build_drmem_cmd(options, name, exp)\n cmd2 = build_kmem_cmd(name, output_dir)\n cmd3 = build_gnuplot_cmd(name, output_dir)\n \n print(cmd1)\n run_cmd(cmd1)\n \n print(cmd2)\n run_cmd(cmd2)\n \n print(cmd3)\n os.chdir(output_dir)\n run_cmd(cmd3)\n os.chdir(orig_pwd)\n\ndef which(name, flags=os.X_OK):\n result = []\n exts = filter(None, os.environ.get('PATHEXT', '').split(os.pathsep))\n path = os.environ.get('PATH', None)\n if path is None:\n return []\n for p in os.environ.get('PATH', '').split(os.pathsep):\n p = os.path.join(p, name)\n if os.access(p, flags):\n result.append(p)\n for e in exts:\n pext = p + e\n if os.access(pext, flags):\n result.append(pext)\n return result\n\n\nusage = \"\"\"usage: %prog [options] [experiment1, experiment2, ...]\n\nExecute drmem experiments.\n\"\"\"\n\nif __name__==\"__main__\":\n parser = OptionParser(usage=usage)\n parser.add_option(\"--dry-run\", dest=\"dry_run\", default=False, action=\"store_true\", help=\"display commands and do not execute them\")\n parser.add_option(\"--list\", dest=\"list\", default=False, action=\"store_true\", help=\"display available experiments\")\n parser.add_option(\"--drmem-dir\", dest=\"drmem_dir\", default=join(top_srcdir, \"drmem\"), help=\"drmem directory\")\n \n (options, args) = parser.parse_args()\n if (options.list):\n print(\"available experiences:\")\n for name, opts in experiences.items():\n print(name)\n sys.exit(0)\n \n if (options.dry_run):\n for name, opts in experiences.items():\n output_dir = join(top_srcdir, \"results\", name)\n print(name)\n cmd = build_drmem_cmd(options, name, opts)\n print(\"tracing: \" + string.join(cmd, \" \"))\n cmd = build_kmem_cmd(name, output_dir)\n print(\"analysis: \" + string.join(cmd, \" \"))\n cmd = build_gnuplot_cmd(name, output_dir)\n print(\"ploting: \" + string.join(cmd, \" \"))\n sys.exit(0)\n \n print(options)\n print(args)\n # validate experiences\n for arg in args:\n if not experiences.has_key(arg):\n raise Exception(\"unknown experience %s\" % (arg))\n \n # check for required tools\n ok = True\n exe_list = [ \"java\", \"lttng-simple\", \"lttng\", \"gnuplot\" ]\n for exe in exe_list:\n res = which(exe)\n if len(res) == 0:\n ok = False\n print(\"Not found in path: \" + exe)\n if not os.path.exists(options.drmem_dir):\n print(\"drmem not found\")\n ok = False\n if not os.path.exists(join(top_srcdir, \"scripts\", \"lttng-kmem.jar\")):\n print(\"lttng-kmem.jar not found in scripts directory\")\n ok = False\n if not ok:\n print(\"Can't run analysis, verify the setup\")\n sys.exit(1)\n \n \n try:\n if len(args) == 0:\n # run all experiences\n for name, opts in experiences.items():\n do_one(options, name, opts)\n else:\n for arg in args:\n do_one(options, arg, experiences[arg])\n except (KeyboardInterrupt, RuntimeError) as e:\n os.chdir(orig_pwd)\n print(\"destroy sessions...\")\n run_cmd([\"lttng\", \"destroy\", \"-a\"])\n #print(str(e))\n \n","sub_path":"Lab3/inf2610-lab3-2.2/scripts/experiment.py","file_name":"experiment.py","file_ext":"py","file_size_in_byte":5608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"389572922","text":"def main():\n inFile = open('SpringSplit2.csv', 'r')\n outFileX = open('SpringSplit_X.csv', 'w')\n outFileY = open('SpringSplit_Y.csv', 'w')\n \n firstLine = True\n \n for line in inFile:\n if not firstLine:\n tokens = line.split(',')\n teamID = tokens[8].strip()\n teamID = int(teamID)\n if teamID == 100 or teamID == 200: # Makes sure its pulling from team statistics not player statistics\n result = tokens[20].strip() # Win or Loss\n firstBlood = tokens[30].strip() # Whether the team got First blood\n firstDrag = tokens[37].strip() # First dragon of the game\n teamDrags = tokens[39].strip() # Number of dragons taken by the team\n oppDrags = tokens[40].strip() # Number of dragons taken by the enemy team\n herald = tokens[49].strip() # Whether the team got the Rift Herald\n firstTower = tokens[51].strip() # Whether the team got the first tower\n firstToThreeTowers = tokens[54].strip() # Whether the team was the first to 3 towers\n firstBaron = tokens[57].strip() # Whether the team got the first baron\n teamBarons = tokens[59].strip() # Number of barons taken by the team\n oppBarons = tokens[60].strip() # Number of barons taken by the enemy\n damageToChamps = tokens[61].strip() # Damage done to champions by the team\n dpm = tokens[62].strip() # Damage to champions by the team per minute\n wpm = tokens[66].strip() # Number of wards put down by the team per minute\n wcpm = tokens[69].strip() # Number of wards cleared by the team per minute\n gpm = tokens[75].strip() # Gold earned by the team per minute\n gd10 = tokens[85].strip() # Gold difference at 10 minutes\n gd15 = tokens[88].strip() # Gold difference at 15 minutes\n cspm = tokens[82].strip() # Creep Score by the team per minute\n csd15 = tokens[97].strip() # Creep Score difference at 15 minutes\n if firstBlood != \"\" and firstDrag !=\"\" and teamDrags !=\"\" and oppDrags !=\"\" and herald !=\"\" and firstTower !=\"\" and firstToThreeTowers !=\"\" and firstBaron != \"\" and teamBarons != \"\" and oppBarons != \"\" and damageToChamps !=\"\" and dpm !=\"\" and wpm !=\"\" and wcpm !=\"\" and gpm !=\"\"and gd10 !=\"\" and gd15 !=\"\" and cspm !=\"\" and csd15 !=\"\":\n outFileX.write('{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}\\n'.format(firstBlood, firstDrag, teamDrags, oppDrags, herald, firstTower, firstToThreeTowers, firstBaron, teamBarons, oppBarons, damageToChamps, dpm, wpm, wcpm, gpm, gd10, gd15, cspm, csd15))\n outFileY.write('{}\\n'.format(result))\n \n firstLine = False\n \n outFileX.close()\n outFileY.close()\n\nmain()","sub_path":"League/clean_data.py","file_name":"clean_data.py","file_ext":"py","file_size_in_byte":3217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"10885426","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# ライブラリをインポート\nimport rospy\nimport roslib.packages\nimport cv2\nimport os\nfrom cv_bridge import CvBridge, CvBridgeError\nfrom sensor_msgs.msg import Image\nfrom geometry_msgs.msg import Twist\nimport signal\nimport sys\nimport time\nimport random\nimport boto3\nfrom botocore.exceptions import ClientError\nimport json\n\n# 自作のライブラリをインポート\nfrom aws_face_collection import AWSFaceCollection\nfrom aws_face_search import AWSFaceSearch\n\n\nclass DetectSpecifiedFace():\n def __init__(self):\n \"\"\" 初期化処理 \"\"\"\n # サブスクライバーを定義\n rospy.Subscriber(\"/image_raw\", Image, self.image_callback)\n self.cmd_pub = rospy.Publisher(\"/cmd_vel\", Twist, queue_size=1)\n # 画像を保持する変数\n self.image = None\n\n # 画像の保存先\n self.image_path = roslib.packages.get_pkg_dir('myface_recognition') + '/scripts/images/'\n # ディレクトリがない場合は新しく作成\n if not os.path.isdir(roslib.packages.get_pkg_dir('myface_recognition') + '/scripts/images/'):\n os.mkdir(roslib.packages.get_pkg_dir('myface_recognition') + '/scripts/images/')\n\n # 自作ライブラリの準備\n self.afc = AWSFaceCollection()\n self.afs = AWSFaceSearch()\n\n # Ctrl-Cが実行されたときの処理用\n signal.signal(signal.SIGINT, self.signal_handler)\n\n def image_callback(self, data):\n \"\"\" 画像のコールバック関数 \"\"\"\n try:\n self.image = CvBridge().imgmsg_to_cv2(data, \"bgr8\")\n except CvBridgeError as e:\n rospy.logerr(e)\n\n def image_save(self):\n \"\"\" 画像を保存する関数 \"\"\"\n cv2.imwrite(self.image_path + \"camera.jpg\", self.image)\n print(\"カメラ画像を保存しました。\")\n\n def search_collection(self, collection_id):\n \"\"\" 顔認証を行う関数 \"\"\"\n # 顔認証を実行\n result_data = self.afs.search_collection(collection_id, self.image_path + \"camera.jpg\")\n # 顔認証が正常に完了した場合\n if result_data != None:\n # マッチした顔が見つかった場合\n if len(result_data[\"FaceMatches\"]) > 0:\n print(\"-------------------------------\")\n print(\"登録されている顔を検出しました。\")\n print(\"-------------------------------\")\n print(\"信頼度: {}%\".format(result_data[\"FaceMatches\"][0][\"Face\"][\"Confidence\"]))\n print(\"類似度: {}%\".format(result_data[\"FaceMatches\"][0][\"Similarity\"]))\n # ロボットに速度指令を送る\n cmd_msg = Twist()\n cmd_msg.linear.x = 0.2\n self.cmd_pub.publish(cmd_msg)\n rospy.sleep(1.0)\n # ロボットを止める\n cmd_msg.linear.x = 0.0\n self.cmd_pub.publish(cmd_msg)\n else:\n print(\"-------------------------------\")\n print(\"登録されていない顔を検出しました。\")\n print(\"-------------------------------\")\n\n def signal_handler(self, signal, frame):\n \"\"\" Ctrl-Cが実行されたときの処理用の関数 \"\"\"\n sys.exit(0)\n\n def local_id_list(self):\n \"\"\" ローカルに保存されているディレクトリ(ID)を一覧表示 \"\"\"\n images_path = roslib.packages.get_pkg_dir('myface_recognition') + '/scripts/images/'\n dirs = os.listdir(images_path)\n print(\"-----------------------------------------------\")\n print(\"このコンピュータ内に保存されているID\")\n dir_counter = 0\n for d in dirs:\n if os.path.isdir(os.path.join(images_path, d)):\n print(\"○ {}\".format(d))\n dir_counter += 1\n if dir_counter == 0:\n print(\"-> 保存されていません。\")\n\n def main(self):\n \"\"\" メインで実行する関数 \"\"\"\n while(1):\n # IDのリストを表示\n self.local_id_list()\n print(\"-----------------------------------------------\")\n collection_id = raw_input(\"登録した自身のIDを入力してください: \")\n # ローカルにディレクトリ(ID)存在するか確認\n if not os.path.isdir(roslib.packages.get_pkg_dir('myface_recognition') + '/scripts/images/' + collection_id):\n print(\"-----------------------------------------------\")\n print(\"このコンピュータに保存されているIDを入力してください。\")\n rospy.sleep(2.0)\n continue\n # IDが存在するか確認\n if self.afc.check_collection_id(collection_id):\n # 登録されていた場合は、インスタンスに設定を反映\n self.afc.collection_id = collection_id\n break\n else:\n print(\"ID: 「{}」 はAWS上に登録されていません。\".format(collection_id))\n rospy.sleep(2.0)\n rate = rospy.Rate(5)\n while not rospy.is_shutdown():\n if self.image is not None:\n raw_input(\"Enterキーを押すと顔認識を開始します:\")\n # 画像を保存\n self.image_save()\n # 顔認証処理を開始\n self.search_collection(self.afc.collection_id)\n else:\n print(\"画像が未取得です。\")\n rate.sleep()\n\n\nif __name__ == '__main__':\n # ノードを初期化\n rospy.init_node('face_search')\n # クラスのインスタンスを作成し、メイン関数を実行\n DetectSpecifiedFace().main()\n","sub_path":"scripts/face_search.py","file_name":"face_search.py","file_ext":"py","file_size_in_byte":5836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"52681928","text":"from preprocessing.load_dataset import load_tf_record_dataset, load_values_from_config\nfrom baseline_model.training import train\nfrom baseline_model.layers import DotAttention, ConcatAttention, DecoderRNNCell, DecoderRNNCellJointCopy\nfrom argparse import ArgumentParser\nimport os\n\ndef _create_parser():\n parser = ArgumentParser()\n parser.add_argument('--path', type=str, required=True)\n parser.add_argument('--batch_size', type=int, default=16)\n parser.add_argument('--word_emb_dim', type=int, default=128)\n parser.add_argument('--tp_emb_dim', type=int, default=128)\n parser.add_argument('--ha_emb_dim', type=int, default=128)\n parser.add_argument('--hidden_size', type=int, default=300)\n parser.add_argument('--attention_type', type=str, default=\"dot\")\n parser.add_argument('--decoder_type', type=str, default=\"joint\")\n parser.add_argument('--truncation_size', type=int, default=100)\n parser.add_argument('--truncation_skip_step', type=int, default=50)\n parser.add_argument('--epochs', type=int, default=50)\n parser.add_argument('--dropout_rate', type=float, default=0.2)\n parser.add_argument('--scheduled_sampling_rate', type=float, default=1.0)\n parser.add_argument('--learning_rate', type=float, default=None)\n parser.add_argument('--with_cp', action='store_true')\n parser.add_argument('--manual', action='store_true')\n return parser\n\ndef _main(args):\n config_path = os.path.join(args.path, \"config.txt\")\n train_path = os.path.join(args.path, \"train.tfrecord\")\n valid_path = os.path.join(args.path, \"valid.tfrecord\")\n vocab_path = os.path.join(args.path, \"all_vocab.txt\")\n for key, value in vars(args).items():\n print(f\"{key} : {value}\")\n max_table_size, max_summary_size, max_cp_size = \\\n load_values_from_config(config_path, load_cp=args.with_cp) # pylint: disable=unused-variable\n batch_size = args.batch_size\n dataset, steps, tk_to_ix, tp_to_ix, ha_to_ix, pad, bos, eos \\\n = load_tf_record_dataset( path=train_path # pylint: disable=unused-variable\n , vocab_path=vocab_path\n , batch_size=batch_size\n , shuffle=True\n , preprocess_table_size=max_table_size\n , preprocess_summary_size=max_summary_size\n , preprocess_cp_size=max_cp_size\n , with_content_plans=args.with_cp)\n val_dataset, val_steps, *dummies = load_tf_record_dataset( valid_path # pylint: disable=unused-variable\n , vocab_path\n , batch_size\n , False # shuffle\n , max_table_size\n , max_summary_size\n , preprocess_cp_size=max_cp_size\n , with_content_plans=args.with_cp)\n word_vocab_size = len(tk_to_ix)\n word_emb_dim = args.word_emb_dim\n tp_vocab_size = len(tp_to_ix)\n tp_emb_dim = args.tp_emb_dim\n ha_vocab_size = len(ha_to_ix)\n ha_emb_dim = args.ha_emb_dim\n entity_span = 22\n hidden_size = args.hidden_size\n\n checkpoint_dir = os.path.join(args.path, \"training_checkpoints/\")\n\n if args.attention_type==\"concat\":\n attention = lambda: ConcatAttention(hidden_size)\n elif args.attention_type==\"dot\":\n attention = DotAttention\n else:\n attention = DotAttention\n\n if args.decoder_type==\"baseline\":\n decoder_rnn = DecoderRNNCell\n elif args.decoder_type==\"joint\":\n decoder_rnn = DecoderRNNCellJointCopy\n else:\n decoder_rnn = DecoderRNNCell\n\n ix_to_tk = dict([(value, key) for key, value in tk_to_ix.items()])\n train( dataset\n , checkpoint_dir\n , batch_size\n , word_emb_dim\n , word_vocab_size\n , tp_emb_dim\n , tp_vocab_size\n , ha_emb_dim\n , ha_vocab_size\n , entity_span\n , hidden_size\n , args.learning_rate\n , args.epochs\n , eos\n , args.dropout_rate\n , args.scheduled_sampling_rate\n , args.truncation_size\n , args.truncation_skip_step\n , attention\n , decoder_rnn\n , args.path\n , ix_to_tk\n , val_dataset\n , load_last=False\n , use_content_selection=args.with_cp\n , max_table_size=max_table_size\n , manual_training=args.manual)\n\nif __name__ == \"__main__\":\n parser = _create_parser()\n _main(parser.parse_args())\n","sub_path":"rotowire/cs_baseline.py","file_name":"cs_baseline.py","file_ext":"py","file_size_in_byte":4844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"144914108","text":"#!/usr/bin/env python\n# -*- coding: utf8 -*-\n\n\"\"\"\n utils.upload_points\n ~~~~~~~~~~~~~~~~\n\n This script parses working dog intensity points data for individual dog +\n collar id directories.\n\n use like:\n ./utils/upload_data.py\n\n This script will fetch the uploadKey from ./../keys.go\n\"\"\"\n\nfrom __future__ import print_function\nimport os # for path joining\nimport csv # for file parsing\nimport glob # for finding files\nimport json # we encode the data to json for uploading\nimport urllib2 # for uploading\nimport re # for extracting the date\nimport traceback\nimport sys\n\nimport parse_data\n\ndef parse_individual_points_file(file_name, debug=False):\n \"\"\"parses a __points.csv file\n\n Arguments:\n file_name: the path of the file to parse\n data: the dict to add the processed data to\n all_times: a set to add all of the valid timestamps too\n debug: if True, debug information will be printed\n\n Returns:\n dict[str (timestamp)]: float (intensity)\n \"\"\"\n with open(file_name, 'rb') as csv_file:\n # parse earch row in the csv\n reader = csv.reader(csv_file, delimiter=',')\n data = {}\n try:\n row = reader.next()\n except:\n raise Exception(\"File does not contain enough lines!\")\n if len(row) < 2 or row[0] != \"timestamp\":\n raise Exception(\"File does not match expected format!\")\n # get first data line\n try:\n row = reader.next()\n except:\n raise Exception(\"File does not contain enough lines!\")\n # process all lines\n while True:\n # NOTE: this validation is probably un-necessary and slows loading\n \"\"\"\n if len(row) != row_len:\n raise Exception(\"Line does not have enough cells!\")\n \"\"\"\n # parse date (ignore :00 for seconds at the end)\n timestamp = row[0]\n value = row[1]\n # there are times without a value, we don't really need these\n if value == \"\":\n continue\n # there are a lot of zeros, we don't want to invoke parsing these\n value = float(value) if value[0] != \"0\" else 0\n data[timestamp] = value\n try:\n row = reader.next()\n except StopIteration:\n break\n return data\n\n\ndef upload_data(upload_key, data, dog_id, date):\n json_data = json.dumps(data)\n url = 'https://working-dog-data-dash.appspot.com/api/upload/points?dog_id=%s&date=%s'% (dog_id, date)\n req = urllib2.Request(url)\n req.add_header('Content-Type', 'application/json')\n req.add_header('Upload-Key', upload_key)\n response = urllib2.urlopen(req, json_data)\n\n\ndef main():\n # get path to data\n self_path = os.path.dirname(os.path.realpath(__file__))\n data_dir = os.path.join(self_path, \"..\", \"..\", \"CCI Puppy Data\", \"point_entries\")\n\n print(\"Loading data...\")\n\n # get keys.go\n self_path = os.path.dirname(os.path.realpath(__file__))\n keys_path = os.path.join(self_path, \"..\", \"keys.go\")\n\n # get variables from keys.go\n key_vars = {}\n for line in open(keys_path):\n if line.startswith(\"var \"):\n var_name = line[4:].split()[0]\n var_value = json.loads(line[line.index(\"=\")+2:])\n key_vars[var_name] = var_value\n upload_key = key_vars[\"uploadKey\"]\n\n # get dog data, we need this to match dogs to ids\n dog_data = parse_data.parse_dog_data()\n\n print(\"Data load complete. Please Select Which Dogs to Upload.\")\n\n # find all points files\n files = next(os.walk(data_dir))[1]\n dog_folder_suffix = \"_activity_details\"\n date_re = re.compile(r\".*_([\\d]+)_.*\\.csv\", re.DOTALL)\n for name in files:\n # we only care about the individual data directories\n if not name.endswith(dog_folder_suffix):\n continue\n dir_name = os.path.join(data_dir, name)\n # parse out the dog's name\n print_name = name[:len(name)-len(dog_folder_suffix)]\n split_idx = print_name[::-1].index('_')\n if split_idx == -1:\n print(\"Invalid name! (%s)\" % print_name)\n continue\n split_idx = len(print_name) - split_idx - 1\n dog_name = print_name[:split_idx].replace(\"_\", \" \")\n dog_name = parse_data.normalize_dog_name(dog_name)\n _id = print_name[split_idx+1:]\n # make sure the dog is in the original data set\n if dog_name not in dog_data:\n print(\"Could not find match for '%s' in dog data.\" % (dog_name))\n continue\n dog_id = dog_data[dog_name].dog_id\n _id_int = int(_id)\n if dog_id != _id_int:\n print(\"ID mismatch (%s, %d, %d)\" % (print_name, dog_id, _id_int))\n continue\n if raw_input(\"Upload: '%s' ? (y/n): \" % print_name) == \"y\":\n glob_path = os.path.join(dir_name, \"*_points.csv\")\n for file_name in glob.glob(glob_path):\n base_name = os.path.basename(file_name)\n date = date_re.search(base_name).group(1)\n date = date[:4]+\"-\"+date[4:6]+\"-\"+date[6:]\n data = parse_individual_points_file(file_name)\n should_upload = True\n while should_upload:\n try:\n print(\"Uploading: %s\" % base_name)\n upload_data(upload_key, data, dog_id, date)\n should_upload = False\n except:\n print(\"Failed to upload, stacktrace: \")\n traceback.print_exc(file=sys.stdout)\n print(\"\")\n should_upload = raw_input(\"Try Again? (y/n): \") == \"y\"\n #return\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"utils/upload_points.py","file_name":"upload_points.py","file_ext":"py","file_size_in_byte":5819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"356372085","text":"\"\"\"\nUnit tests for PrettyExpression class\n\"\"\"\n\nfrom prettymath.prettyexpression import PrettyExpression\nimport unittest\n\n\nclass Key(object):\n def __init__(self, keysym=None, char=None, state=0):\n self.keysym = keysym\n if char is None and keysym is not None:\n self.char = self.keysym\n else:\n self.char = char\n self.state = state\n\n\ndef make_keystream(chars):\n return [Key(i) for i in chars]\n\n\nBACKSPACE_KEY = Key(keysym=\"BackSpace\")\nLEFT_ARROW_KEY = Key(keysym=\"Left\")\nRIGHT_ARROW_KEY = Key(keysym=\"Right\")\nUP_ARROW_KEY = Key(keysym=\"Up\")\nDOWN_ARROW_KEY = Key(keysym=\"Down\")\n\n\nclass TestPrettyExpression(unittest.TestCase):\n def setUp(self):\n self.expression = PrettyExpression()\n new_keystream = make_keystream(\"y=x+20\")\n for i in new_keystream:\n self.expression.add_keypress(i)\n\n def test_latex(self):\n self.assertEqual(self.expression.latex, \"$y=x+20|$\")\n\n def test_reset(self):\n self.expression.reset()\n self.assertEqual(self.expression.latex, \"$|$\")\n self.assertEqual(str(self.expression), \"|\")\n\n def test_backspace(self):\n self.expression.add_keypress(BACKSPACE_KEY)\n self.assertEqual(self.expression.latex, \"$y=x+2|$\")\n\n def test_delete_char(self):\n pass\n\n def test_left_arrow_key(self):\n self.expression.add_keypress(LEFT_ARROW_KEY)\n self.assertEqual(self.expression.latex, \"$y=x+2|0$\")\n\n def test_right_arrow_key(self):\n self.expression.add_keypress(RIGHT_ARROW_KEY)\n self.assertEqual(self.expression.latex, \"$y=x+20|$\")\n self.expression.add_keypress(LEFT_ARROW_KEY)\n self.expression.add_keypress(LEFT_ARROW_KEY)\n self.expression.add_keypress(RIGHT_ARROW_KEY)\n self.assertEqual(self.expression.latex, \"$y=x+2|0$\")\n\n def test_typing_latex_command(self):\n expr = PrettyExpression()\n for i in make_keystream(\"x^2\"):\n expr.add_keypress(i)\n self.assertEqual(expr.latex, r\"$x^{2|}$\")\n\n def test_make_fraction(self):\n expr = PrettyExpression()\n for i in make_keystream(\"3/4\"):\n expr.add_keypress(i)\n self.assertEqual(expr.latex, r\"$\\frac{3}{4|}$\")\n\n expr.reset()\n for i in make_keystream(\"x+/3\"):\n expr.add_keypress(i)\n expr.add_keypress(RIGHT_ARROW_KEY)\n expr.add_keypress(Key(\"4\"))\n self.assertEqual(expr.latex, r\"$x+\\frac{3}{4|}$\")\n\n def test_check_for_latex_command(self):\n expr = PrettyExpression()\n for i in make_keystream(\"sinx\"):\n expr.add_keypress(i)\n self.assertEqual(expr.latex, r\"$\\sin(x|)$\")\n \"\"\"\n expr.reset()\n for i in make_keystream(\"sinhx\"):\n expr.add_keypress(i)\n self.assertEqual(expr.latex, r\"$\\sinh x|$\")\n\n expr.reset()\n for i in make_keystream(\"epsilon\"):\n expr.add_keypress(i)\n self.assertEqual(expr.latex, r\"$\\epsilon |$\")\n \"\"\"\n\n def test_up_arrow_key(self):\n pass\n\n def test_down_arrow_key(self):\n pass\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_prettyexpression.py","file_name":"test_prettyexpression.py","file_ext":"py","file_size_in_byte":3140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"538636372","text":"# -*- coding: utf-8 -*-\n\"\"\"\nOPTICS: Ordering Points To Identify the Clustering Structure\n\"\"\"\n\n# Author: Fredrik Appelros (fredrik.appelros@gmail.com), Carl Ekerot (kalle@implode.se)\n# License: BSD\n\nimport numpy as np\n\nfrom ..base import BaseEstimator, ClusterMixin\nfrom ..utils import atleast2d_or_csr\nfrom sklearn.neighbors import BallTree\nfrom ._reachability_cluster_extraction import EXTRACTION_FUNCTIONS\n\ndef optics(X, eps=float('inf'), min_samples=1, metric='euclidean',\n extraction='hierarchical', ext_kwargs={}):\n \"\"\"\n Perform OPTICS clustering from vector array or distance matrix.\n\n Parameters\n ----------\n X : array [n_samples, n_samples] or [n_samples, n_features]\n Array of distances between samples, or a feature array.\n The array is treated as a feature array unless the metric is given as\n 'precomputed'.\n\n eps : float, optional\n The generating distance between two samples for them to be considered\n as in the same neighborhood.\n\n min_samples : int, optional\n The number of samples in a neighborhood for a point to be considered\n as a core point.\n\n metric : string or callable, optional\n The metric to use when calculating distance between instances in a\n feature array. If metric is a string or callable, it must be one of\n the options allowed by metrics.pairwise.calculate_distance for its\n metric parameter.\n If metric is \"precomputed\", X is assumed to be a distance matrix and\n must be square.\n\n extraction : string, optional\n The extraction method used to generate clusters from the ordering of\n points returned by the OPTICS algorithm.\n\n ext_kwargs : dict\n Keyword arguments to be supplied to the extraction function.\n\n Returns\n -------\n core_distances : array [n_samples]\n Core distance for each sample.\n\n ordering : array [n_samples]\n Indices of the samples in the order generated by OPTICS.\n\n reachability_distances : array [n_samples]\n Reachability distance for each sample.\n\n labels : array [n_samples]\n Cluster labels for each point. Noisy samples are given the label -1.\n\n Notes\n -----\n See examples/cluster/plot_optics.py for an example.\n\n References\n ----------\n Ankerst, Mihael, Markus M. Breunig, Hans-Peter Kriegel, and Jörg Sander.\n \"OPTICS: ordering points to identify the clustering structure.\" ACM SIGMOD\n Record 28, no. 2 (1999): 49-60.\n\n \"\"\"\n X = atleast2d_or_csr(X)\n n = X.shape[0]\n if min_samples > n:\n raise ValueError('min_samples must be lower than the total number of samples')\n ordering = []\n core_distances = np.ndarray(len(X))\n # Initiate reachability distances to infinity\n reachability_distances = float('inf') * np.ones(n)\n # Set reachability for first point\n reachability_distances[0] = 0\n # Construct spatial indexing structure\n if metric != 'precomputed':\n # TODO: Construct BallTree with the correct metric once the\n # metrics branch has been merged into master\n tree = BallTree(X, metric=metric)\n\n seeds = np.ones(n, dtype=bool)\n i = 0\n while True:\n # Mark current point as processed\n seeds[i] = False\n # Add current point to the ordering\n ordering.append(i)\n if not any(seeds):\n break\n # Calculate core distance\n if metric == 'precomputed':\n D = X[i]\n core_dist = np.sort(D)[min_samples]\n else:\n core_dist = tree.query(X[i], min_samples+1)[0][0][-1]\n core_distances[i] = core_dist\n\n if core_dist <= eps:\n # Get the neighbors of the current point\n if metric == 'precomputed':\n neighbors = D[seeds] <= eps\n ds = D[neighbors]\n else:\n ind, dist = tree.query_radius(X[i], eps, True)\n si = seeds[ind[0]]\n neighbors = ind[0][si]\n ds = dist[0][si]\n cds = core_dist * np.ones(len(ds))\n # Set the new reachability distances to\n # max(core_distance, distance)\n new_reach_dists = np.maximum(cds, ds)\n reachability_distances[neighbors] = new_reach_dists\n i = np.nonzero(seeds)[0][np.argmin(reachability_distances[seeds])]\n else:\n i = np.where(seeds)[0][0]\n\n if type(extraction) is str:\n estr = extraction.lower()\n if estr in EXTRACTION_FUNCTIONS:\n func = EXTRACTION_FUNCTIONS[estr]\n labels = func(ordering, reachability_distances, min_samples,\n **ext_kwargs)\n else:\n raise ValueError('Unknown Extraction Method: %s' % estr)\n else:\n raise TypeError('Extraction Method must be a string.')\n\n return core_distances, ordering, reachability_distances, labels\n\nclass OPTICS(BaseEstimator, ClusterMixin):\n \"\"\"\n Perform OPTICS clustering from vector array or distance matrix.\n\n Parameters\n ----------\n X : array [n_samples, n_samples] or [n_samples, n_features]\n Array of distances between samples, or a feature array.\n The array is treated as a feature array unless the metric is given as\n 'precomputed'.\n\n eps : float, optional\n The generating distance between two samples for them to be considered\n as in the same neighborhood.\n\n min_samples : int, optional\n The number of samples in a neighborhood for a point to be considered\n as a core point.\n\n metric : string or callable, optional\n The metric to use when calculating distance between instances in a\n feature array. If metric is a string or callable, it must be one of\n the options allowed by metrics.pairwise.calculate_distance for its\n metric parameter.\n If metric is \"precomputed\", X is assumed to be a distance matrix and\n must be square.\n\n extraction : string, optional\n The extraction method used to generate clusters from the ordering of\n points returned by the OPTICS algorithm.\n\n ext_kwargs : dict\n Keyword arguments to be supplied to the extraction function.\n\n Attributes\n ----------\n `core_distances_` : array [n_samples]\n Core distance for each sample.\n\n `ordering_` : array [n_samples]\n Indices of the samples in the order generated by OPTICS.\n\n `reachability_distances_` : array [n_samples]\n Reachability distance for each sample.\n\n `labels_` : array [n_samples]\n Cluster labels for each point. Noisy samples are given the label -1.\n\n Notes\n -----\n See examples/cluster/plot_optics.py for an example.\n\n References\n ----------\n Ankerst, Mihael, Markus M. Breunig, Hans-Peter Kriegel, and Jörg Sander.\n \"OPTICS: ordering points to identify the clustering structure.\" ACM SIGMOD\n Record 28, no. 2 (1999): 49-60.\n\n \"\"\"\n def __init__(self, eps=float('inf'), min_samples=1, metric='euclidean',\n extraction='hierarchical', ext_kwargs=dict()):\n self.eps = eps\n self.min_samples = min_samples\n self.metric = metric\n self.extraction = extraction\n self.ext_kwargs = ext_kwargs\n\n def fit(self, X):\n \"\"\"\n Perform OPTICS clustering from vector array or distance matrix.\n\n Parameters\n ----------\n X : array [n_samples, n_samples] or [n_samples, n_features]\n Array of distances between samples, or a feature array.\n The array is treated as a feature array unless the metric is\n given as 'precomputed'.\n params : dict\n Overwrite keywords from __init__.\n \"\"\"\n clust = optics(X, **self.get_params())\n (self.core_distances_, self.ordering_, self.reachability_distances_,\n self.labels_) = clust\n return self\n","sub_path":"sklearn/cluster/optics_.py","file_name":"optics_.py","file_ext":"py","file_size_in_byte":7902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"231081025","text":"import numpy as np\nfrom collections import deque\nfrom skimage import color, transform\nfrom keras.models import load_model\n\nstackedX = []\ncall = 0\nactions = [119, None]\ndqn = load_model('dqn-925k.h5')\n# Choose a new action every REPEAT call\nREPEAT = 2\nlastAction = None\n\ndef processScreen(screen):\n \"\"\" Resize and gray-ify screen \"\"\"\n return 255*transform.resize(color.rgb2gray(screen[60:,25:310,:]),(80,80))\n \ndef FlappyPolicy(state, screen):\n global stackedX, call, actions, dqn, lastAction\n \n screenX = processScreen(screen)\n\n if call == 0: \n stackedX = deque([screenX]*4, maxlen=4)\n x = np.stack(stackedX, axis=-1)\n else:\n stackedX.append(screenX)\n x = np.stack(stackedX, axis=-1)\n \n Q = dqn.predict(np.array([x]))\n \n if call % REPEAT == 0 or REPEAT == 1:\n lastAction = actions[np.argmax(Q)]\n call += 1\n return lastAction\n","sub_path":"Durivaux/FlappyAgent.py","file_name":"FlappyAgent.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"573462513","text":"import math\r\nimport numpy as np\r\n\r\n\"\"\"\r\n-----------------------Method 1-----------------------------------\r\n\"\"\"\r\n#Starting values\r\nm = 0.0657 #ball mass (kg)\r\nM = 0.1917 #pendulum mass (kg)\r\nR = 0.277 #Length of pendulum (m)\r\ng = 9.8 #m/s^2\r\n\r\n#Gathered data\r\nangles = [45, 46, 45.5, 46, 46, 46, 46, 46, 46, 46] #degrees\r\n\r\n\r\n#Finding initial velocity\r\ndef findv( height ):\r\n return ((m + M) / m) * (math.sqrt(2*g*R*height))\r\n\r\ndhs = [] #Delta Height values (radians)\r\n\r\nfor angle in angles: #converts angles to radians, appends difference in height\r\n rad = (angle / 180) * math.pi\r\n h = 1 - math.cos(rad)\r\n dhs.append(h)\r\n\r\navg_dh = sum(dhs) / len(dhs)\r\n\r\n#This code was used to find the initial velocity using an incorrect method\r\n# vis = []\r\n\r\n# for dh in dhs: #finds 10 individual initial velocities\r\n# v = findv(dh)\r\n# vis.append(v)\r\n \r\n# avg_vi = sum(vis) / len(vis) #ten initial, take the average\r\n\r\nother_vi = findv(avg_dh) #computed once, using the avg dh\r\n\r\n#Finding uncertainties\r\nunc_m = 0.001 #ball mass uncertainty(kg)\r\nm_exp = -1\r\nunc_M = 0.001 #pendulum mass uncertainy (kg)\r\nunc_R = 0.002 #m\r\nR_exp = 0.5\r\nunc_mSum = math.sqrt((unc_m ** 2) + (unc_M ** 2))\r\nunc_h = np.std(dhs) / math.sqrt(len(dhs))\r\nh_exp = 0.5\r\n\r\nunc_vi = other_vi * math.sqrt(((unc_mSum / (m + M)) ** 2) + ((m_exp * (unc_m / m)) ** 2) + ((R_exp * (unc_R / R)) ** 2) + ((h_exp * (unc_h / h)) ** 2))\r\n\r\nprint('Method 1')\r\n# print('Initial velocity (averaging 10 initial velocities): {:.2f} m/s'.format(avg_vi))\r\nprint('Initial velocity: {:.2f} ± {:.2f} m/s \\n'.format(other_vi, unc_vi))\r\n\r\n\"\"\"\r\n--------------------------Method 2 ------------------------\r\n\"\"\"\r\n#Starting variables\r\ny1 = .915 #m\r\ny2 = .076 #m\r\ny = y1 + y2 #m\r\ndist1 = 1.937 #m\r\ndist2 = .181 #m\r\n\r\n#Gathered data\r\ndists = [6, 6.5, 7, 7.2, 7.3, 8.5, 8.6, 8.8, 9, 9.2, 9.8] #cm\r\n\r\nfor idx in range(len(dists)): #converts dists to total distances (delta x)\r\n dists[idx] = (dists[idx] / 100) + dist1 + dist2\r\n\r\n#Computing initial velocity\r\ndef findv_two( dist_avg):\r\n return dist_avg * math.sqrt(g / (2 * y))\r\n\r\navg_x = sum(dists) / len(dists)\r\n\r\nmethod_two_vi = findv_two(avg_x)\r\n\r\n#Finding Uncertainties\r\nunc_y1 = .001 #m\r\nunc_y2 = unc_y1 #height (m)\r\nunc_y = math.sqrt((unc_y1 ** 2) + (unc_y2 ** 2))\r\nunc_x = np.std(dists) / math.sqrt(len(dists))\r\n\r\nunc_vi_two = method_two_vi * math.sqrt(((unc_x / avg_x) ** 2) + ((-0.5 * (unc_y / y)) ** 2))\r\n\r\n\r\nprint('Method 2')\r\nprint('Initial Velocity: {:.2f} ± {:.2f} m/s'.format(method_two_vi, unc_vi_two))\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"Lab_4_work.py","file_name":"Lab_4_work.py","file_ext":"py","file_size_in_byte":2546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"73994116","text":"# -*- coding: utf-8 -*-\r\n\r\nfrom DotImg import *\r\nCASH_AMT_RATIO_PRES = [] # 住院现金支付比例\r\nBILL_AMT_IN_PERDAY = [] # 住院每日费用\r\n\r\n\r\ndef CASH_AMT_RATIO2BILL_AMT_IN_PERDAY():\r\n file = open(r'../result', 'r')\r\n for line in file:\r\n if len(line.split()) > 3:\r\n BILL_AMT_IN_PERDAY.append(float(line.split()[-2])) # 提取住院每日费用字段,并且加入列表BILL_AMT_IN_PERDAY中\r\n CASH_AMT_RATIO_PRES.append(float(line.split()[-1])) # 提取住院现金支付比例字段,并且加入列表CASH_AMT_RATIO_PRES中\r\n file.close()\r\n\r\nCASH_AMT_RATIO2BILL_AMT_IN_PERDAY()\r\nDrawDotImg(CASH_AMT_RATIO_PRES, BILL_AMT_IN_PERDAY)","sub_path":"CASH_AMT_RATIO.py","file_name":"CASH_AMT_RATIO.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"249313670","text":"import os\nimport sys\nimport json\nimport time\nimport datetime\nfrom shapely.geometry import Point\nfrom pymongo import MongoClient\nfrom utils.utils import point_is_in_manhattan\nfrom common.fetcher import read_nymetro_website\nimport concurrent.futures\nfrom itertools import filterfalse\nfrom common.process_data import process_pokemons\nfrom concurrent.futures import ThreadPoolExecutor\nfrom utils import db\nimport logging\nlogging.basicConfig(level=logging.ERROR)\n\nlogger=logging.getLogger()\n\ndef get_and_process_nymetro_data(db, params=[],old_data=[],control_settings=[],control_data={}):\n logger.debug(\"fetching...\")\n results = read_nymetro_website(params=params)\n if results:\n len_pokemon = len( results.get('pokemons') ) if results and results.get('pokemons') else -1\n \n if 'pokemons' in results.keys():\n pokemon_data=results.get('pokemons')\n del results['pokemons']\n params.update(results) \n else:\n logger.error(\"no pokemons in results?\")\n return (params,old_data)\n \n try:\n now=int(time.time())\n #filter out disaper_time older (>) then now\n old_data[:]=filterfalse(lambda t: now > t['disappear_time']//1000,old_data)\n except (TypeError) as e:\n raise e\n \n old_encounter_list=[x['encounter_id'] for x in old_data]\n # return pokemon_data whose encounter_id is not in old_data's encounter_id\n pokemon_data[:]=filterfalse(lambda x: x['encounter_id'] in old_encounter_list, pokemon_data)\n # pokemon_data = [x for x in pokemon_data if x['encounter_id'] not in [o['encounter_id'] for o in old_data]]\n logger.debug(f\"read_nymetro_website returned {len(pokemon_data)}({len_pokemon}) pokemons (old:{len(old_data)})\")\n old_data += pokemon_data\n\n \n control_settings=[x for x in db.iControlIt.find({},{'last_updated':True,'iSawIt_id':True,'_id':False})]\n for control_setting in control_settings:\n last_updated=control_setting['last_updated']\n iSawIt_id=control_setting['iSawIt_id']\n if iSawIt_id in control_data.keys():\n cached_last_updated=control_data[iSawIt_id]['control']['last_updated']\n if last_updated == cached_last_updated:\n continue\n logger.info(f'getting settings for {iSawIt_id}')\n control_data[iSawIt_id]={\n 'control':db.iControlIt.find_one( {'iSawIt_id':iSawIt_id} ),\n 'pokemon_data': list(db.get_collection(f\"iSawIt_{iSawIt_id}\").find({}).sort(\"_id\"))\n }\n\n #pull pokemon settings for all users\n # botid_to_collections={x['iSawIt_id'] : {'control':x,'pokemon_data': list(db.get_collection(f\"iSawIt_{x['iSawIt_id'] }\").find({}).sort(\"_id\"))} for x in control_data} \n # for each user, process the data \n # with concurrent.futures.ThreadPoolExecutor(max_workers=len(control_data)) as executor: \n # futures = {\n # executor.submit( \n # process_pokemons, \n # info_dict['control'], \n # info_dict['poke_rules'], \n # pokemon_data\n # ) for info_dict in botid_to_collections.values()\n # }\n with concurrent.futures.ThreadPoolExecutor() as executor: \n futures=[]\n for info_dict in control_data.values():\n control_info=info_dict['control']\n requirements=info_dict['pokemon_data']\n futures += [ executor.submit(process_pokemons, control_info, requirements, pokemon_data.copy()) ]\n \n try:\n concurrent.futures.wait(futures)\n except Exception as exc:\n logger.error(f\"process_pokemon generated an exception: {exc}\")\n raise exc\n\n\n # return (params, old_data)\n return params\n\n\ndef main():\n\n # get_data_once_and_print()\n logger.info(\"main()...\")\n token='4ah+lvEDKrfzodM3psdg1P7jeIk3d2uRYK4dV+omN4o='\n \n params={\n 'bigKarp': 'false',\n 'eids': '0',\n 'exEligible': 'false',\n 'exMinIV': '0',\n 'gyms': 'false',\n 'lastgyms': 'false',\n 'lastpokemon': 'true',\n 'lastpokestops': 'false',\n 'lastslocs': 'false',\n 'lastspawns': 'false',\n 'luredonly': 'false',\n 'minIV': '0',\n 'minLevel': '0',\n 'neLat': '40.8968744414486',\n 'neLng': '-73.84092242090662',\n 'oNeLat': '40.8968744414486',\n 'oNeLng': '-73.84092242090662',\n 'oSwLat': '40.56699275763961',\n 'oSwLng': '-74.13823992578943',\n 'pokemon': 'true',\n 'pokestops': 'false',\n 'prevMinIV': '0',\n 'prevMinLevel': '0',\n 'reids': '0',\n 'scanned': 'false',\n 'spawnpoints': 'false',\n 'swLat': '40.56699275763961',\n 'swLng': '-74.13823992578943',\n 'timestamp': f'{int(time.time())}',\n 'tinyRat': 'false',\n 'token': f'{token}'\n }\n\n \n\n while True:\n try:\n get_and_process_nymetro_data(db,params)\n\n # elapsed=time.time()-now\n # delay=10\n # remaining=10-elapsed\n # if remaining < 0:\n # remaining=0\n # time.sleep(remaining)\n except KeyboardInterrupt:\n logger.info(\"User Interupted\")\n break\n except Exception as e:\n logger.error(e)\n raise e\n\nif __name__ == \"__main__\":\n logger.debug(\"main called\")\n main()","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"96590898","text":"#Image utils\nimport cv2\nimport math\nimport rasterio\nimport numpy as np\n\ndef image_normalize(image):\n \"\"\"normalize a 3d numpy array simiiar to tf.image.per_image_standardization\"\"\"\n mean = image.mean()\n stddev = image.std()\n adjusted_stddev = max(stddev, 1.0/math.sqrt(image.size))\n standardized_image = (image - mean) / adjusted_stddev\n \n return standardized_image\n\ndef resize(img, height, width):\n # resize image\n dim = (width, height)\n resized = cv2.resize(img, dim, interpolation=cv2.INTER_NEAREST)\n\n return resized\n\ndef crop_image(src, box, expand=0): \n \"\"\"Read sensor data and crop a bounding box\n Args:\n src: a rasterio opened path\n box: geopandas geometry polygon object\n expand: add padding in percent to the edge of the crop\n Returns:\n masked_image: a crop of sensor data at specified bounds\n \"\"\"\n #Read data and mask\n try: \n left, bottom, right, top = box.bounds\n \n expand_width = (right - left) * expand /2\n expand_height = (top - bottom) * expand / 2\n \n #If expand is greater than increase both size\n if expand >= 0:\n expanded_left = left - expand_width\n expanded_bottom = bottom - expand_height\n expanded_right = right + expand_width\n expanded_top = top+expand_height\n else:\n #Make sure of no negative boxes\n expanded_left = left+expand_width\n expanded_bottom = bottom+expand\n expanded_right = right-expand_width\n expanded_top = top-expand_height \n \n window = rasterio.windows.from_bounds(expanded_left, expanded_bottom, expanded_right, expanded_top, transform=src.transform)\n masked_image = src.read(window=window)\n except Exception as e:\n raise ValueError(\"sensor path: {} failed at reading window {} with error {}\".format(src, box.bounds,e))\n \n #Roll depth to channel last\n masked_image = np.rollaxis(masked_image, 0, 3)\n \n #Skip empty frames\n if masked_image.size ==0:\n raise ValueError(\"Empty frame crop for box {} in sensor path {}\".format(box, src))\n \n return masked_image","sub_path":"DeepTreeAttention/utils/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":2212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"647878608","text":"from instagram import Account, Media, WebAgent\nimport json\nimport time\nimport sconfig\nimport dbworker\n\ndef mem(account = sconfig.our, delay = sconfig.delay):\n last = None\n agent = WebAgent()\n account = Account(account)\n media1 = agent.get_media(account, count=1)\n tm = time.time()\n while (1):\n if (time.time() > tm + delay):\n media1 = agent.get_media(account)\n tm = time.time()\n if last != media1[0].code:\n last = media1[0].code\n print(last)\n\ndef get_last_inst(account = sconfig.our, cnt = 5):\n result = []\n agent = WebAgent()\n account = Account(account)\n media1 = agent.get_media(account, count=cnt)\n for i in media1[0]:\n result.append({'url': 'https://www.instagram.com/p/' + i.code + '/', 'time': i.date, 'text': i.caption, 'network': 'inst', 'id': i.owner})\n return result\n\n\n\nif __name__ == \"__main__\":\n get_last_inst('ccacc_ount')","sub_path":"mrartemev/research/i_check.py","file_name":"i_check.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"59459936","text":"for i in range(int(input())):\n v,n=map(int,input().split())\n l=sorted(list(map(int,input().split())))\n dp=[[0 for j in range(v+1)] for k in range(n)]\n for j in range(n):\n for k in range(v+1):\n # print (j,k)\n if k 10:\r\n return jsonify({\"Message\": 'page不符合规则,请输入1-10范围内的整数'})\r\n except Exception as e:\r\n print('page参数错误:{}'.format(e))\r\n return jsonify({\"Message\": 'page不符合规则,请输入1-10范围内的整数'})\r\n query = re.sub('[\\++]', ' ', query)\r\n result = sougou.run(query, page)\r\n sougou_user_times += 1\r\n print('sougou_user_times:{}'.format(sougou_user_times))\r\n if sougou_user_times >= SELENIUM_MAX_TIME:\r\n sougou.quit()\r\n sougou_user_times = 0\r\n sougou = SougouWeixin()\r\n if result['Message'] == '':\r\n return jsonify(result['Data'])\r\n else:\r\n return jsonify({'Message': result['Message']})\r\n else:\r\n return jsonify({\"Message\": 'query和page不能为空'})\r\n\r\n\r\n@app.route('/WeiXin/Images/', methods=['GET'])\r\ndef get_imagge(image_name):\r\n print('请求image_name:{}'.format(image_name))\r\n single_image_path = os.path.join(SINGLE_IMAGE_DIR, image_name)\r\n mimetype = ''\r\n if re.search('jpg', image_name):\r\n mimetype = 'image/jpeg'\r\n elif re.search('png', image_name):\r\n mimetype = 'image/png'\r\n\r\n if os.path.exists(single_image_path) and mimetype:\r\n return send_file(single_image_path, mimetype=mimetype)\r\n else:\r\n return {}\r\n\r\n\r\nif __name__ == '__main__':\r\n # 开启服务,linux内网端口:10006,外网端口:26128\r\n app.run(host='0.0.0.0', port=10006, threaded=True)\r\n","sub_path":"项目代码/linux代码/sougou_metasearch_st/run_server_st.py","file_name":"run_server_st.py","file_ext":"py","file_size_in_byte":2419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"300410100","text":"\"\"\"\n@File: realize7_5\n@Date: 2019/8/18\n@Author: Chensy\n@Des: 7.5的实现\n 思路 1. 包含3个散列表:\n 1) 一个将节点所有的邻居存储起来的散列表\n 2) 一个当前节点的一个成本散列表\n 3) 一个存储父亲节点的散列表\n\"\"\"\n\ngraph = {}\ncosts = {}\nparents = {}\nprocessed = []\n\n\ndef init():\n \"\"\"\n 三个散列表的初始化\n \"\"\"\n # 起点的邻居以及成本\n global graph\n graph = {\"start\": { \"a\": 6, \"b\": 2}}\n # a点的邻居及成本\n graph[\"a\"] = {\"fin\": 1}\n # b点的邻居及成本\n graph[\"b\"] = {\"a\": 3, \"fin\": 5}\n # fin点没有邻居\n graph[\"fin\"] = {}\n\n # 当前节点的邻居成本\n infinity = float(\"inf\") # 无穷大\n costs[\"a\"] = 6\n costs[\"b\"] = 2\n costs[\"fin\"] = infinity\n\n # 父亲节点的散列表\n parents[\"a\"] = \"start\"\n parents[\"b\"] = \"start\"\n parents[\"fin\"] = None\n\n\ndef find_lowest_cost_node(costs):\n lowest_cost = float(\"inf\")\n lowest_cost_node = None\n for node in costs:\n cost = costs[node]\n if cost < lowest_cost and node not in processed:\n lowest_cost = cost\n lowest_cost_node = node\n return lowest_cost_node\n\n\nif __name__ == '__main__':\n init()\n node = find_lowest_cost_node(costs)\n while node is not None: # 只要未到最后一个\n cost = costs[node]\n neighbors = graph[node]\n for n in neighbors.keys():\n new_cost = cost + neighbors[n]\n if costs[n] > new_cost: # 这里是判断通过该节点到邻居更近的路线\n costs[n] = new_cost # 更新该邻居的开销\n parents[n] = node # 更改父节点\n processed.append(node)\n node = find_lowest_cost_node(costs)\n # 遍历父节点散列表找出路线\n current = \"fin\"\n while current != \"start\":\n parent = parents[current]\n print(parent)\n current = parent","sub_path":"study/05 - Algorithms_diagrammatize/chapter07/realize7_5.py","file_name":"realize7_5.py","file_ext":"py","file_size_in_byte":1932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"166270859","text":"from random import *\nfrom time import *\nfrom math import *\nfrom copy import *\nimport sys\n\n# Import the package only once.\nsys.path.append('/home/lantian/File/Study Coding/Optimisation/GLPK-Tool/TSP-Hard/GLPK/')\n\nfrom mine.Main import create_init , check\nfrom mine.onepass import count\nfrom mine.check_optimal import optimal\n\nfunc_number = int(sys.argv[1])\n\nT0 = 1000 # The Begining temp of the question\nTn = 1e-6 # The Last temp of the question\nINNERL = 1000 # Inner limite of the search\nOUTTERL = 1000 # Outter limite of the search \nCHOOSELIMIT = 1000 # We must control the time of Not-Good choose\n\nbuf = [0,0,0] # Save the buf in order to redo the bad move.\n\ndef COLD(t):\n '''\n This function is the decrease the temperature function.\n Input:\n t - input the data of the and try to calulate the next temperature.\n T0 - The init temperature of the question.\n Output:\n return the next decrease temperature.\n Side affect:~\n\n I have some question for this ?????\n '''\n #return T0/log(1+t)\n return 0.98*t\n\n# Function 1\ndef fun_onepass(seq , data):\n n = len(data)\n # Define the shuffle space (begin , end)\n begin = randint(1, n - 2)\n end = randint(begin + 1 ,n - 1)\n best = count(seq , data)\n limite = 1\n for i in range(begin , end + 1):\n limite = limite * i\n for i in range(limite):\n pause = seq[begin:end + 1]\n tty = deepcopy(pause)\n shuffle(pause)\n seq[begin:end + 1] = pause\n if check(seq , data) == False:\n buf[0] , buf[1] ,buf[2]= begin , end , tty\n return count(seq , data)\n else:seq[begin:end + 1] = tty\n return 0\n \n# Function 2\ndef fun_twochoose(seq , data):\n n = len(data)\n # Define the change position\n limite = n*(n-1)//2\n for i in range(limite):\n begin , end = sample(range(1,len(seq)) , 2)\n seq[begin] , seq[end] = seq[end] , seq[begin]\n if check(seq , data) == False:\n buf[0] , buf[1] = begin , end\n return count(seq , data)\n else:seq[begin] , seq[end] = seq[end] , seq[begin]\n return 0\n\ndef read_file():\n '''\n This function read the data from the file\n Output:\n n - the size of the data.\n m - the weight of each city (point).\n '''\n n = int(input())\n m = list(map(lambda x:int(x) , input().split()))\n return (n,m)\n\n# Write the solution into ../mine/SA_50 or ../mine/SA_100\ndef write_file(n , func_num , ptime , nbest , oldbest , seq):\n func_num = str(func_num)\n num_instance = sys.argv[2]\n # Python 只能用绝对路径创建不存在的文件\n filename = '/home/lantian/File/Study Coding/Optimisation/GLPK-Tool/TSP-Hard/GLPK/prepare/SA_' + str(n) + '/' + str(n) + '_' + num_instance + '_' + func_num\n with open(filename , 'w') as f:\n f.write('Time: ' + str(ptime) + '\\n')\n f.write('Result before optimal: ' + str(oldbest) + '\\n')\n f.write('Result after optimal: ' + str(nbest) + '\\n')\n f.write('Result of the sequence: ' + str(seq) + '\\n')\n\n# The main function below is that most important things in the SA Algorithm.\nif __name__ == '__main__':\n a = time()\n n , data = read_file()\n origin = create_init(n , data) # The init solution of the question.\n #print(origin)\n data[0:0] = [0] # hold the data to n + 1\n p = list(range(n + 1))\n for i in range(1 , n+1):\n p[i] = origin[i - 1] + 1\n origin = p\n oldbest = best = count(origin , data)\n #print(0,oldbest)\n i = 1\n if func_number == 1:\n print(\"Too slow,Try to exit.\")\n exit(0)\n else:fun = fun_twochoose\n T = T0\n while True:\n T = COLD(T) \n i += 1\n limiteInner = 0\n limiteOutter = 0\n for j in range(INNERL):\n nextp = fun(origin , data)\n if nextp == 0:E = 0\n else:E = nextp - best\n if E < 0:\n best = nextp # If the solution is better than the origin , then renew it.\n limiteInner = 0\n else:\n p = uniform(0 , 1)\n if 0 <= p <= e**(-E / T):\n if nextp != 0:best = nextp\n else:\n if func_number == 1:origin[buf[0]:buf[1] + 1] = buf[2]\n else:origin[buf[0]],origin[buf[1]] = origin[buf[1]],origin[buf[0]]\n limiteInner += 1 # If this solution is not better than the current solution , do this job.\n if limiteInner > CHOOSELIMIT:\n limiteOutter += 1\n break\n if T < Tn or limiteOutter > OUTTERL:\n break\n #print(T , best)\n #print(best,origin)\n nbest = optimal(origin , best , data)\n print(best,nbest)\n b = time()\n write_file(n , func_number , b - a , best , oldbest , origin)\n","sub_path":"Optimisation/GLPK-Tool/TSP-Hard/GLPK/prepare/SA.py","file_name":"SA.py","file_ext":"py","file_size_in_byte":4827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"419716911","text":"# There are comments with the names of\n# the required functions to build.\n# Please paste your solution underneath\n# the appropriate comment.\n\n# search\ndef search(array, query):\n '''\n Accepts an unsorted array of integers, array, and an integer value to find, query.\n It returns True if query is found in array, and False otherwise. Use Recursion\n '''\n if array == []: # Base Case 1\n return False\n elif array.pop() == query: # Base Case 2\n return True\n else: # Recursive Case\n return search(array, query)\n \n search(array, query)\n\n\n# is_palindrome\ndef is_palindrome(text):\n '''\n Accepts a string text as a parameter. Returns True if text is a palidrome.\n Returns False if text is not a palidrome\n '''\n\n if len(text) < 2: \n return True\n if text[0] != text[-1]: \n return False\n return is_palindrome(text[1:-1])\n\n\n# digit_match\ndef digit_match(apple, orange):\n num_match = 0\n \n if apple == \"stop\" or orange == \"stop\":\n return 0\n elif apple % 10 == orange % 10:\n num_match = 1\n \n if apple // 10 == 0:\n next_apple = \"stop\" # if a number runs out of digit from dividing by 10, then, must set number to \"stop\" or None to terminate.\n else:\n next_apple = apple // 10\n \n if orange // 10 == 0:\n next_orange = \"stop\"\n else:\n next_orange = orange // 10\n \n return num_match + digit_match(next_apple, next_orange)","sub_path":"part-2.py","file_name":"part-2.py","file_ext":"py","file_size_in_byte":1504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"567057132","text":"import sys\nimport getopt\n\ndef full_name():\n first_name = None\n last_name = None\n\n argv = sys.argv[1:]\n try:\n opts, args = getopt.getopt(argv, \"l:f:\")\n except:\n print('The arguments are missing')\n\n for opt, arg in opts:\n if opt in ['-f']:\n first_name = arg\n elif opt in ['-l']:\n last_name = arg\n else:\n other = arg\n print(other)\n print(f'{first_name} {last_name}')\n\nfull_name()\n","sub_path":"arg_parcer_and_serialization/detopt_examples.py","file_name":"detopt_examples.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"179511806","text":"from flask import request\nfrom flask_restful import Resource, reqparse\n\nfrom financial_funcs import payment, rate\n\n\nclass Prestamo(Resource):\n parser = reqparse.RequestParser()\n parser.add_argument('loan', type=float)\n parser.add_argument('num_of_years', type=int)\n parser.add_argument('rate', type=float)\n parser.add_argument('add_reg_p', type=float)\n parser.add_argument('extra_p', type=float)\n parser.add_argument('extra_p_start', type=int)\n parser.add_argument('extra_p_f', type=int)\n\n @staticmethod\n def post():\n if not request.is_json:\n return {'message': 'La solicitud debe estar en formato json'}, 415\n\n data = Prestamo.parser.parse_args()\n\n # Calculate the monthly payment, total interests, and total payments.\n reg_p = -1 * payment(data['rate'] / (100 * 12),\n 12 * data['num_of_years'],\n data['loan'])\n total_sch_i = reg_p * data['num_of_years'] * 12 - data['loan']\n total_sch_p = reg_p * data['num_of_years'] * 12\n\n # Build a list of periods.\n periods = [x for x in range(12 * data['num_of_years'] + 1)]\n\n # Build a list of regular payments.\n reg_ps = [reg_p if x else 0 for x in periods]\n\n # Build a list of regular additional payments.\n add_reg_ps = [data['add_reg_p'] if x else 0 for x in periods]\n\n # Build a list of periods with extraordinary payments.\n extra_p_p = []\n if data['extra_p']:\n extra_p_p.append(data['extra_p_start'])\n if data['extra_p_f']:\n for x in periods[data['extra_p_start']+1:]:\n if not (x - data['extra_p_start']) % \\\n (12 / data['extra_p_f']):\n extra_p_p.append(x)\n\n # Build a list of extraordinary payments.\n extra_ps = [data['extra_p'] if x in extra_p_p else 0 for x in periods]\n\n # Merge additional payment list and extra payment list.\n add_ps = [add_reg_ps[x] + extra_ps[x] for x in periods]\n\n # Build lists of interests, principal payment, and balances.\n balance = data['loan']\n interests = []\n princ_ps = []\n balances = []\n paid_by = data['num_of_years'] * 12\n for x in periods:\n if x:\n interest = balance * data['rate'] / (100 * 12)\n interests.append(interest)\n # Check if it is not the last payment.\n if balance + interest > reg_p + add_ps[x]:\n princ_ps.append(reg_p + add_ps[x] - interest)\n balance += interest - reg_p - add_ps[x]\n balances.append(balance)\n else:\n if balance + interest >= add_ps[x]:\n reg_ps[x] = balance + interest - add_ps[x]\n else:\n add_ps[x] = balance + interest\n reg_ps[x] = 0\n paid_by = x\n princ_ps.append(reg_ps[x] + add_ps[x] - interest)\n balances.append(0)\n break\n else:\n interests.append(0)\n princ_ps.append(0)\n balances.append(balance)\n\n return {'reg_p': round(reg_p, 2),\n 'total_sch_i': round(total_sch_i, 2),\n 'total_sch_p': round(total_sch_p, 2),\n 'princ_p': round(data['loan'], 2),\n 'princ_p_a': round(data['loan'], 2),\n 'interest': round(sum(interests), 2),\n 'money_paid': round(sum(reg_ps[:paid_by+1]) +\n sum(add_ps[:paid_by+1]), 2),\n 'money_saved': round((total_sch_p\n - sum(reg_ps[:paid_by+1])\n - sum(add_ps[:paid_by+1])), 2),\n 'months_to_pay': round(periods[paid_by], 2),\n 'months_saved': round(data['num_of_years'] * 12 -\n periods[paid_by], 0),\n 'table': [[periods[x],\n round(add_ps[x], 2),\n round(reg_ps[x], 2),\n round(interests[x], 2),\n round(princ_ps[x], 2),\n round(balances[x], 2)]\n for x in periods[:paid_by+1]]}\n\n\nclass TasaInteresReal(Resource):\n parser = reqparse.RequestParser()\n parser.add_argument('loan', type=float)\n parser.add_argument('num_of_years', type=int)\n parser.add_argument('reg_p', type=float)\n\n @staticmethod\n def post():\n if not request.is_json:\n return {'message': 'La solicitud debe estar en formato json'}, 415\n\n data = TasaInteresReal.parser.parse_args()\n\n success, r = rate(data['num_of_years'] * 12,\n -1 * data['reg_p'],\n data['loan'])\n\n if success:\n return {'rate': round(r * 12 * 100, 2)}\n\n return {'message': 'No se encontró una tasa de interés ' +\n 'para los parámetros especificados'}, 400\n\n\nclass TiempoParaPagar(Resource):\n parser = reqparse.RequestParser()\n parser.add_argument('loan', type=float)\n parser.add_argument('rate', type=float)\n parser.add_argument('reg_p', type=float)\n\n @staticmethod\n def post():\n if not request.is_json:\n return {'message': 'La solicitud debe estar en formato json'}, 415\n\n data = TiempoParaPagar.parser.parse_args()\n\n # Build a list of periods, larger than needed\n periods = [x for x in range(int(data['loan'] / data['reg_p']) * 3)]\n\n # Build a list of regular payments.\n reg_ps = [data['reg_p'] if x else 0 for x in periods]\n\n # Build lists of interests, principal payment, and balances.\n balance = data['loan']\n interests = []\n princ_ps = []\n balances = []\n paid_by = periods[-1]\n for x in periods:\n if x:\n interest = balance * data['rate'] / (100 * 12)\n interests.append(interest)\n # Check if it is not the last payment.\n if balance + interest > data['reg_p']:\n princ_ps.append(data['reg_p'] - interest)\n balance += interest - data['reg_p']\n balances.append(balance)\n else:\n reg_ps[x] = balance + interest\n paid_by = x\n princ_ps.append(reg_ps[x] - interest)\n balances.append(0)\n break\n else:\n interests.append(0)\n princ_ps.append(0)\n balances.append(balance)\n\n # Send error message if loan was not cancelled.\n if balances[-1] >= 0.01:\n return {'message': 'El préstamo no se logra cancelar, con ' +\n 'la tasa de interés y el pago mensual ' +\n 'especificado'}, 400\n\n return {'months_to_pay': periods[paid_by],\n 'years_to_pay': round(periods[paid_by] / 12, 2),\n 'princ_p': round(data['loan'], 2),\n 'interest': round(sum(interests), 2),\n 'money_paid': round(sum(reg_ps[:paid_by+1]), 2),\n 'table': [[periods[x],\n round(reg_ps[x], 2),\n round(interests[x], 2),\n round(princ_ps[x], 2),\n round(balances[x], 2)]\n for x in periods[:paid_by+1]]}\n","sub_path":"resources/loan.py","file_name":"loan.py","file_ext":"py","file_size_in_byte":7684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"369616716","text":"import codecs\nimport numpy as np\nfrom utils import operations\nfrom sklearn.metrics.pairwise import cosine_similarity\nimport statistics as stat\nimport pandas as pd\nfrom scipy.stats import norm\nimport random as random\n\n\ndef load_embeddings(embeddings_path):\n with codecs.open(embeddings_path + '.vocab', 'r', 'utf-8') as f_in:\n index2word = [line.strip() for line in f_in]\n word2index = {w: i for i, w in enumerate(index2word)}\n wv = np.load(embeddings_path + '.npy')\n\n return wv, index2word, word2index\n\ndef load_names(namesFile):\n namesList = []\n f = open(namesFile, \"r\")\n for line in f:\n name = line[:-1]\n namesList.append(name)\n return namesList\n\ndef cosineSimilarity(a, b):\n a = [a]\n b = [b]\n r = cosine_similarity(a,b)\n return r[0][0]\n\ndef computeCentroid(names, vectors, word2index, wordDimension):\n\n counter = 0\n centroid = [0] * wordDimension\n\n for name in names:\n\n meanConcept1Stereotype2 = vectors[word2index[name]]\n if (meanConcept1Stereotype2[1] != 999.0):\n counter = counter + 1\n\n for i in range(wordDimension):\n centroid[i] = centroid[i] + meanConcept1Stereotype2[i]\n\n for column in range(wordDimension):\n centroid[column] = centroid[column]/float(counter)\n\n return centroid\n\ndef computeNullMatrix(names, bothStereotypes, vectors, word2index):\n\n concept1NullMatrix = []\n\n for name in names:\n\n concept1Embedding = vectors[word2index[name]]\n my_list = []\n\n for attribute in bothStereotypes:\n nullEmbedding = vectors[word2index[attribute]]\n similarityCompatible = cosineSimilarity(concept1Embedding, nullEmbedding)\n my_list.append(similarityCompatible)\n concept1NullMatrix.append(my_list)\n\n return concept1NullMatrix\n\ndef effectSize(array, mean):\n effect = mean/stat.stdev(array)\n return effect\n\ndef calculateWomenNamePercentage(namesFile, name):\n\n df = pd.read_csv(namesFile)\n i=df[df['Name'] == name]\n stat = np.asarray(i)\n percentage = (stat[0][2]*stat[0][3])/((stat[0][2]*stat[0][3])+ (stat[0][2]*stat[0][4]))\n return percentage\n\ndef calculateCumulativeProbability(nullDistribution, testStatistic, distribution):\n cumulative = -100\n nullDistribution.sort()\n\n if distribution == 'empirical':\n ecdf = ECDF(nullDistribution)\n cumulative = ecdf(testStatistic)\n elif distribution == 'normal':\n d = norm(loc = stat.mean(nullDistribution), scale = stat.stdev(nullDistribution))\n cumulative = d.cdf(testStatistic)\n\n return cumulative\n\ndef computeNullHypothesis(wordIndex, nullMatrix, iterations, stereotype1, stereotype2):\n\n print(\"Number of permutations \", iterations)\n\n #Assuming both stereotypes have the same length\n setSize = int(len(bothStereotypes)/2)\n\n toShuffle = list(range(0, len(bothStereotypes)))\n distribution = []\n\n for iter in range(iterations):\n random.shuffle(toShuffle)\n #calculate mean for each null shuffle\n meanSimilarityGroup1 = 0\n meanSimilarityGroup2 = 0\n\n for i in range(setSize):\n meanSimilarityGroup1 = meanSimilarityGroup1 + nullMatrix[wordIndex][toShuffle[i]]\n\n for i in range(setSize):\n meanSimilarityGroup2 = meanSimilarityGroup2 + nullMatrix[wordIndex][toShuffle[i+setSize]]\n\n meanSimilarityGroup1 = meanSimilarityGroup1/(setSize)\n meanSimilarityGroup2 = meanSimilarityGroup2/(setSize)\n\n distribution.append(meanSimilarityGroup1 - meanSimilarityGroup2)\n\n return distribution\n\n\ndata = load_embeddings(\"embedding\")\nvectors = data[0]\nindex2word = data[1]\nword2index = data[2]\n\nnamesFile = \"../data/censusNames1990.csv\"\nnamesToTest = \"../data/wow1.txt\"\ncaseSensitive = True\ncheckWordPresence = True\ngetCentroid = True\nwordDimension = 300\n\nnames = load_names(namesToTest)\nprint(names)\n# attributesFirstSet = [\"sister\", \"female\", \"woman\", \"girl\", \"daughter\", \"she\", \"hers\", \"her\"]\n# attributesSecondSet = [\"brother\", \"male\", \"man\", \"boy\", \"son\", \"he\", \"his\", \"him\"]\nattributesFirstSet = [\"caress\", \"freedom\", \"health\", \"love\", \"peace\", \"cheer\", \"friend\",\"heaven\", \"loyal\", \"pleasure\", \"diamond\", \"gentle\", \"honest\", \"lucky\", \"rainbow\",\"diploma\", \"gift\", \"honor\", \"miracle\", \"sunrise\", \"family\", \"happy\", \"laughter\",\"paradise\", \"vacation\"]\nattributesSecondSet = [\"abuse\" , \"crash\" , \"filth\" , \"murder\" , \"sickness\" , \"accident\" , \"death\" , \"grief\" , \"poison\" , \"stink\" , \"assault\" , \"disaster\" , \"hatred\" , \"pollute\" , \"tragedy\" , \"divorce\" , \"jail\" , \"poverty\" , \"ugly\" , \"cancer\" , \"kill\" , \"rotten\" , \"vomit\" , \"agony\" , \"prison\"]\n\nif getCentroid == True:\n centroid = computeCentroid(names, vectors, word2index,wordDimension)\n\nbothStereotypes = attributesFirstSet + attributesSecondSet\n\nmeanConcept1Stereotype1 = [0]* len(names)\nmeanConcept1Stereotype2 = [0]* len(names)\n\nfor i in range(len(names)):\n\n concept1Embedding = vectors[word2index[names[i]]]\n\n for attribute in attributesFirstSet:\n stereotype2Embedding = vectors[word2index[attribute]]\n similarityCompatible = cosineSimilarity(concept1Embedding, stereotype2Embedding)\n meanConcept1Stereotype1[i] = meanConcept1Stereotype1[i] + similarityCompatible\n\n meanConcept1Stereotype1[i] = meanConcept1Stereotype1[i]/len(attributesFirstSet)\n\n for attribute in attributesSecondSet:\n stereotype2Embedding = vectors[word2index[attribute]]\n similarityCompatible = cosineSimilarity(concept1Embedding, stereotype2Embedding)\n meanConcept1Stereotype2[i] = meanConcept1Stereotype2[i] + similarityCompatible\n\n meanConcept1Stereotype2[i] = meanConcept1Stereotype2[i]/len(attributesSecondSet)\n\nconcept1NullMatrix = computeNullMatrix(names, bothStereotypes, vectors, word2index)\n\ndistribution = \"normal\"\n\nfor i in range(len(names)):\n\n # percentage = calculateWomenNamePercentage(namesFile, names[i])\n percentage = 0\n\n nullDistributionConcept1 = []\n for j in range(len(bothStereotypes)):\n nullDistributionConcept1.append(concept1NullMatrix[i][j])\n\n concept1Embedding = vectors[word2index[names[i]]]\n frequency = word2index[names[i]]+1\n print(names[i] , \", \" , percentage , \", \" ,effectSize(nullDistributionConcept1, meanConcept1Stereotype1[i] - meanConcept1Stereotype2[i]) ,\n \", \" , cosineSimilarity(concept1Embedding, centroid) , \", \" , frequency)\n\n #new stuff\n myMatrix = computeNullHypothesis(i, concept1NullMatrix, 1000000, attributesFirstSet, attributesSecondSet)\n cumulativeVal = calculateCumulativeProbability(myMatrix, (meanConcept1Stereotype2[i] - meanConcept1Stereotype1[i]), distribution)\n print(\"p val is \", 1- cumulativeVal)\n","sub_path":"code/test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":6675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"318701681","text":"from mcstatus import MinecraftServer\nimport re\n\n\nclass Minecraft:\n def __init__(self, host='msb2.mynode.in', port=25565,\n MinecraftServer=MinecraftServer):\n self.mc_server = MinecraftServer(host=host, port=port)\n\n def get_motd(self):\n status = self.mc_server.status()\n try:\n motd = status.description['text']\n except TypeError:\n return 'There is no MOTD :('\n if 'extra' in status.description:\n motd += ''.join([x['text'] for x in status.description['extra']])\n ansi_escape = re.compile(r'§[0-9a-z]')\n motd = ansi_escape.sub('', motd)\n if motd:\n return f'`{motd}`'\n return 'There is no MOTD :('\n\n def get_forge_version_message(self):\n status = self.mc_server.status()\n forge = None\n if 'modinfo' in status.raw:\n forge = next(filter(lambda mod: mod['modid'] == 'forge',\n status.raw['modinfo']['modList']), None)\n if forge:\n return 'Forge is at version {}'.format(forge['version'])\n else:\n return 'The server does not have Forge installed'\n\n def get_formatted_status_message(self):\n status = self.mc_server.status()\n if status.players.online > 0:\n sample = status.raw['players'].get('sample', [])\n online_players = ': `' + ', '.join(\n [p['name'] for p in sample]) + '`'\n else:\n online_players = ''\n online_count = status.players.online\n max_count = status.players.max\n status_message = ''\n if 'modinfo' in status.raw:\n mods_count = len(status.raw['modinfo']['modList'])\n status_message += '{} mods loaded, '.format(mods_count)\n status_message += 'players {}/{}{}'.format(\n online_count, max_count, online_players)\n return status_message\n","sub_path":"src/Minecraft.py","file_name":"Minecraft.py","file_ext":"py","file_size_in_byte":1913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"464939843","text":"from .connect import connect\nfrom .tools import promt\nfrom .melos import get_melos_id, is_mod\nfrom .printer import print_row, match_column_with_dictionary\n\ndef does_akinhto_exist(akinhto_id):\n con, cur = connect()\n aggelies_found = cur.execute(f'SELECT count(akinhto_id)'\n f' FROM akinhto '\n f' WHERE akinhto_id == \"{akinhto_id}\"').fetchall()[0][0]\n con.close()\n if aggelies_found == 1:\n return True\n return False\n\ndef _is_user_akinhto_manager(username, akinhto_id):\n if username is None:\n return False\n\n pwlhths_id = get_melos_id(username)\n con, cur = connect()\n aggelies_found = cur.execute(f'SELECT count(akinhto_id) '\n f' FROM akinhto '\n f' WHERE akinhto_id = \"{akinhto_id}\" AND diaxhrizetai_pwlhths_id = \"{pwlhths_id}\"').fetchall()[0][0]\n con.close()\n if aggelies_found == 1:\n return True\n return False\n\ndef does_user_has_edit_privilege_aggelia(username, akinhto_id):\n if _is_user_akinhto_manager(username, akinhto_id) or is_mod(username):\n return True\n return False\n\ndef create_akinhto(current_user):\n con, cur = connect()\n inp = promt('akinhto', ['akinhto_id', 'diaxhrizetai_pwlhths_id'])\n inp['surface_area'] = float(inp['surface_area']) if inp['surface_area'] else None\n inp['akinhto_id'] = None\n inp['diaxhrizetai_pwlhths_id'] = get_melos_id(current_user)\n if inp['akinhto_type'] == 'katoikia':\n cur.execute('INSERT INTO akinhto VALUES(:akinhto_id, :surface_area, :area, :area_coords, :description, :extra,'\n ':diaxhrizetai_pwlhths_id, :first_name_idiokthth, :last_name_idiokthth, :akinhto_type)', inp)\n inp_kat = promt('a_katoikia', ['akinhto_id'])\n inp_kat['akinhto_id'] = cur.lastrowid\n inp_kat['bathrooms'] = int(inp_kat['bathrooms']) if inp_kat['bathrooms'] else None\n inp_kat['floor'] = int(inp_kat['floor']) if inp_kat['floor'] else None\n inp_kat['construction_year'] = int(inp_kat['construction_year']) if inp_kat['construction_year'] else None\n cur.execute('INSERT INTO a_katoikia VALUES(:akinhto_id, :katoikia_type, :heating_system, :bathrooms, :floor,'\n ':construction_year, :internal, :external)', inp_kat)\n con.commit()\n print('Successfully added akinhto katoikia..')\n elif inp['akinhto_type'] == 'epaggelmatikos_xwros':\n cur.execute('INSERT INTO akinhto VALUES(:akinhto_id, :surface_area, :area, :area_coords,'\n ':description, :extra, :diaxhrizetai_pwlhths_id, :first_name_idiokthth, :last_name_idiokthth, :akinhto_type)', inp)\n inp_epx = promt('a_epaggelmatikos_xwros', ['akinhto_id'])\n inp_epx['parking_spot'] = int(inp_epx['parking_spot']) if inp_epx['parking_spot'] else None\n inp_epx['construction_year'] = int(inp_epx['construction_year']) if inp_epx['construction_year'] else None\n inp_epx['akinhto_id'] = cur.lastrowid\n cur.execute('INSERT INTO a_epaggelmatikos_xwros VALUES(:akinhto_id, :parking_spot, :construction_year, :internal, :external)', inp_epx)\n con.commit()\n print('Successfully added akinhto epaggelmatikos_xwros..')\n elif inp['akinhto_type'] == 'gh':\n cur.execute('INSERT INTO akinhto VALUES(:akinhto_id, :surface_area, :area, :area_coords, :description, :extra,'\n ':diaxhrizetai_pwlhths_id, :first_name_idiokthth, :last_name_idiokthth, :akinhto_type)', inp)\n inp_gh = promt('a_gh',['akinhto_id'])\n inp_gh['akinhto_id'] = cur.lastrowid\n inp_gh['building_coeff'] = float(inp_gh['building_coeff']) if inp_gh['building_coeff'] else None\n cur.execute('INSERT INTO a_gh VALUES(:akinhto_id, :building_coeff, :external)', inp_gh)\n con.commit()\n print('Successfully added akinhto gh..')\n else:\n print('Invalid akinhto_type..')\n con.close()\n return current_user\n\ndef about_akinhto_of_pwlhth(username):\n akinhto_id = input(\"Akinhto_id: \")\n if does_user_has_edit_privilege_aggelia(username, akinhto_id):\n print_akinhto_full(akinhto_id)\n else:\n print(\"You don't have such akinhto..\")\n\ndef about_akinhto_arg(username, akinhto_id):\n if not does_akinhto_exist(akinhto_id):\n print(\"No such akinhto\")\n elif does_user_has_edit_privilege_aggelia(username, akinhto_id):\n print_akinhto_full(akinhto_id)\n else:\n print_akinhto(akinhto_id)\n\ndef _print_katoikia(akinhto_id):\n con, cur = connect()\n katoikia_row = cur.execute(f'SELECT katoikia_type, heating_system, bathrooms, floor, construction_year, internal, \"external\"'\n f' FROM a_katoikia'\n f' WHERE akinhto_id = {akinhto_id}').fetchall()\n con.close()\n\n katoikia_row = match_column_with_dictionary(katoikia_row, {'polykatoikia':'Πολυκατοικία', 'monokatoikia':'Μονοκατοικία'}, 0)\n katoikia_row = match_column_with_dictionary(katoikia_row, {'autonomh':'Αυτόνομη', 'kentrikh':'Κεντρική'}, 1)\n print_row(katoikia_row[0],\n ['Τύπος κατοικίας', 'Σύστημα θέρμανσης', 'Μπάνια', 'Όροφος', 'Έτος κατασκευής', 'Εσωτερικά', 'Εξωτερικά'])\n\ndef _print_epaggelmatikos_xwros(akinhto_id):\n con, cur = connect()\n epgxwr_row = cur.execute(f'SELECT parking_spot, construction_year, internal, \"external\"'\n f' FROM a_epaggelmatikos_xwros'\n f' WHERE akinhto_id = {akinhto_id}').fetchall()\n con.close()\n\n epgxwr_row = match_column_with_dictionary(epgxwr_row, {0:'Όχι', 1:'Ναί'}, 0)\n print_row(epgxwr_row[0],\n ['Χώρος Στάθμεσης', 'Έτος κατασκευής', 'Εσωτερικά', 'Εξωτερικά'])\n\ndef _print_gh(akinhto_id):\n con, cur = connect()\n gh_row =cur.execute(f'SELECT building_coeff, \"external\"'\n f' FROM a_gh'\n f' WHERE akinhto_id = {akinhto_id}').fetchall()\n con.close()\n\n print_row(gh_row[0],\n ['Συντελεστής Δόμησης', 'Εξωτερικά'])\n\ndef _print_akinhto_type(akinhto_id, akinhto_type):\n if akinhto_type == 'katoikia':\n _print_katoikia(akinhto_id)\n elif akinhto_type == 'epaggelmatikos_xwros':\n _print_epaggelmatikos_xwros(akinhto_id)\n elif akinhto_type == 'gh':\n _print_gh(akinhto_id)\n\ndef print_akinhto(akinhto_id):\n con, cur = connect()\n akinhto_row =cur.execute(f'SELECT surface_area, area, area_coords, akinhto_type, description, extra'\n f' FROM akinhto'\n f' WHERE akinhto_id = {akinhto_id}').fetchall()\n con.close()\n akinhto_type = akinhto_row[0][3]\n\n akinhto_row_matched = match_column_with_dictionary(akinhto_row, {'epaggelmatikos_xwros':'Επαγγελματικός Χώρος', 'katoikia':'Κατοικία', 'gh': 'Γη'}, 3)\n print_row(akinhto_row_matched[0],\n ['Τετραγωνικά', 'Περιοχή', 'Συντεταγμένες', 'Τύπος ακινήτου', 'Περιγραφή', 'Επιπλέον Πληροφορίες'])\n _print_akinhto_type(akinhto_id, akinhto_type)\n\ndef print_akinhto_full(akinhto_id):\n con, cur = connect()\n akinhto_row =cur.execute(f'SELECT surface_area, area, area_coords, akinhto_type, description, extra, username, first_name_idiokthth, last_name_idiokthth'\n f' FROM akinhto JOIN melos ON diaxhrizetai_pwlhths_id = melos_id' \n f' WHERE akinhto_id = {akinhto_id}').fetchall()\n con.close()\n akinhto_type = akinhto_row[0][3]\n\n akinhto_row_matched = match_column_with_dictionary(akinhto_row, {'epaggelmatikos_xwros':'Επαγγελματικός Χώρος', 'katoikia':'Κατοικία', 'gh': 'Γη'}, 3)\n print_row(akinhto_row_matched[0],\n ['Τετραγωνικά', 'Περιοχή', 'Συντεταγμένες', 'Τύπος ακινήτου', 'Περιγραφή', 'Επιπλέον Πληροφορίες', 'Username Πωλητή', 'Όνομα Ιδιοκτήτη', 'Επώνυμο Ιδιοκτήτη'])\n _print_akinhto_type(akinhto_id, akinhto_type)\n","sub_path":"app/source/akinhto.py","file_name":"akinhto.py","file_ext":"py","file_size_in_byte":8319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"618492082","text":"import numpy as np\nfrom ctapipe.io import zfits\nfrom utils.peakdetect import spe_peaks_in_event_list\nfrom utils.toy_reader import ToyReader\nimport logging\nimport sys\n\n\ndef run(hist, options, h_type='ADC', prev_fit_result=None):\n \"\"\"\n Fill the adcs Histogram out of darkrun/baseline runs\n :param h_type: type of Histogram to produce: ADC for all samples adcs or SPE for only peaks\n :param hist: the Histogram to fill\n :param options: see analyse_spe.py\n :param prev_fit_result: fit result of a previous step needed for the calculations\n :return:\n \"\"\"\n logger = logging.getLogger(sys.modules['__main__'].__name__+'.'+__name__)\n # Reading the file\n n_evt, n_batch, batch_num, max_evt = 0, options.n_evt_per_batch, 0, options.evt_max\n batch = None\n\n if not options.mc:\n logger.info('Running on DigiCam data')\n print(logger)\n else:\n logger.info('Running on MC data')\n\n logger.debug('Treating the batch #%d of %d events' % (batch_num, n_batch))\n for file in options.file_list:\n # Open the file\n _url = options.directory + options.file_basename % file\n if not options.mc:\n inputfile_reader = zfits.zfits_event_source(url=_url, data_type='r1', max_events=100000)\n else:\n inputfile_reader = ToyReader(filename=_url, id_list=[0],\n max_events=options.evt_max,\n n_pixel=options.n_pixels)\n\n logger.debug('--|> Moving to file %s' % _url)\n # Loop over event in this file\n for event in inputfile_reader:\n n_evt += 1\n if n_evt > max_evt:\n break\n if (n_evt - n_batch * batch_num) % n_batch / 100 == 0:\n print(float(n_evt - batch_num * n_batch) / n_batch)\n print(\"Progress {:2.1%}\".format(float(n_evt - batch_num * n_batch) / n_batch), end=\"\\r\")\n for telid in event.r1.tels_with_data:\n if n_evt % n_batch == 0:\n logger.debug('Treating the batch #%d of %d events' % (batch_num, n_batch))\n # Update adc histo\n if h_type == 'ADC':\n hist.fill_with_batch(batch.reshape(batch.shape[0], batch.shape[1] * batch.shape[2]))\n elif h_type == 'SPE':\n hist.fill_with_batch(\n spe_peaks_in_event_list(batch, prev_fit_result[:, 1, 0], prev_fit_result[:, 2, 0]))\n # Reset the batch\n batch = None\n batch_num += 1\n logger.debug('Reading the batch #%d of %d events' % (batch_num, n_batch))\n # Get the data\n data = np.array(list(event.r1.tel[telid].adc_samples.values()))\n # Append the data to the batch\n if type(batch).__name__ != 'ndarray':\n batch = data.reshape(data.shape[0], 1, data.shape[1])\n else:\n batch = np.append(batch, data.reshape(data.shape[0], 1, data.shape[1]), axis=1)\n\n return\n","sub_path":"data_treatement/adc_hist.py","file_name":"adc_hist.py","file_ext":"py","file_size_in_byte":3120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"250604307","text":"__NetID__ = \"kevintbradshaw\"\n__GitHubID__ = \"kevintbradshaw\"\n__SelfGrade__ = \"5\"\n__Challenge__ = \"4\"\n\n\"\"\"\nRandom Signals and Systems\nCourse: ECEN 303-502\nMaximum Grade: 5pt\n\"\"\"\n\nimport random\nimport math\nimport numpy\nimport pylab\n\nTrialNumber = 100000\n\nUniformList = []\nRayleighList = []\nfor trial1 in range(0, TrialNumber):\n UniformList.append(random.uniform(0, 2*math.pi))\n RayleighList.append(numpy.random.rayleigh(1))\n\npylab.figure()\nn, bins, patches = pylab.hist(UniformList, 1000, normed=1, histtype='stepfilled')\npylab.setp(patches, 'facecolor', 'k', 'alpha', 0.75)\n\npylab.figure()\nn, bins, patches = pylab.hist(RayleighList, 1000, normed=1, histtype='stepfilled')\npylab.setp(patches, 'facecolor', 'g', 'alpha', 0.75)\n\npylab.show()\n\nSequence1 = []\nSequence2 = []\nSequence3 = []\nfor trial2 in range(0, TrialNumber):\n Sequence1.append(math.sin(UniformList[trial2]) * RayleighList[trial2])\n Sequence2.append(math.cos(UniformList[trial2]) * RayleighList[trial2])\n Sequence3.append(Sequence1[trial2]**2 + Sequence2[trial2]**2)\n\n\"EDIT:\"\n\"=============================================================================================\"\npylab.figure()\nn, bins, patches = pylab.hist(Sequence1, 1000, normed=1, histtype='stepfilled')\npylab.setp(patches, 'facecolor', 'y', 'alpha', 0.75)\npylab.title('Sequence 1')\nprint(\"Sequence 1: Mean\") \nprint(numpy.mean(Sequence1))\nprint(\"Sequence 1: Variance\") \nprint(numpy.var(Sequence1))\n\"=============================================================================================\"\npylab.figure()\nn, bins, patches = pylab.hist(Sequence2, 1000, normed=1, histtype='stepfilled')\npylab.setp(patches, 'facecolor', 'r', 'alpha', 0.75)\npylab.title('Sequence 2')\nprint(\"Sequence 2: Mean\") \nprint(numpy.mean(Sequence2))\nprint(\"Sequence 2: Variance\") \nprint(numpy.var(Sequence2))\n\"=============================================================================================\"\npylab.figure()\nn, bins, patches = pylab.hist(Sequence3, 1000, normed=1, histtype='stepfilled')\npylab.setp(patches, 'facecolor', 'c', 'alpha', 0.75)\npylab.title('Sequence 3')\nprint(\"Sequence 3: Mean\") \nprint(numpy.mean(Sequence3))\nprint(\"Sequence 3: Variance\") \nprint(numpy.var(Sequence3))\n\"=============================================================================================\"\nprint (\"Covariance of Sequence 1 and Sequence 2\")\nprint (numpy.cov(Sequence1,Sequence2))\n\"=============================================================================================\"\npylab.show()\n\n\"\"\"\nWhat is the type of random variable `Sequence1`?\nIt's a continuous random variable with a rayleigh distribution dependent on a sinusoidal function.\n\nWhat is its mean and variance?\nThe mean is 0 and the variance is 1.\n\nWhat is the type of random variable `Sequence2`?\nIt's a continuous random variable with a rayleigh distribution dependent on a cosinusoidal function.\n\nWhat is its mean and variance?\nThe mean is 0 and the variance is 1.\n\nWhat is the type of random variable `Sequence3`?\nIt's a continuous random variable with a rayleigh distribution dependent on a multiplied sinusoidal and cosinusoidal function.\n\nWhat is its mean and variance?\nThe mean is 2 and the variance is 4.\n\nWhat is the empirical covariance between `Sequence1` and `Sequence2`?\nThe emperical covariance is 0.\n\nDo you think they are independent? Justify your answer.\nYes because the covariance is zero and this is only true when two random variables distributions are independent. \n\"\"\"\n\n","sub_path":"Students/kevintbradshaw/4challenge.py","file_name":"4challenge.py","file_ext":"py","file_size_in_byte":3474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"402877566","text":"import sys, os, pysam, shutil\nimport numpy as np\n\nfrom logging import getLogger\nlogger = getLogger(__name__)\n\n# https://stackoverflow.com/questions/5574702/how-to-print-to-stderr-in-python\ndef eprint(*args, **kwargs):\n print(*args, file=sys.stderr, **kwargs)\n\n#https://stackoverflow.com/questions/1868714/how-do-i-copy-an-entire-directory-of-files-into-an-existing-directory-using-pyth\ndef copytree(src, dst, symlinks=False, ignore=None):\n for item in os.listdir(src):\n s = os.path.join(src, item)\n d = os.path.join(dst, item)\n if os.path.isdir(s):\n shutil.copytree(s, d, symlinks, ignore)\n else:\n shutil.copy2(s, d)\n\ndef rgb(r,g,b):\n\n return [ r/255, g/255, b/255 ]\n\ndef get_N50(vals):\n t = np.array(vals).sum()/2\n cnt = 0\n for x in np.sort(vals):\n cnt += x\n if cnt >= t: return x\n\ndef get_NXX(vals, target=90):\n t = np.array(vals).sum() * target/100\n if target < 0:\n return vals[0]\n elif target > 100:\n return vals[-1]\n cnt = 0\n for x in np.sort(vals):\n cnt += x\n if cnt >= t: return x\n\ndef open_seq_chunk(fn, file_code, is_upper=False, chunk_size=500*1024**2): # default 500MB\n #file_code = guess_format(fn)\n if file_code == 0:\n yield from parse_bam_chunk(fn, chunk_size, is_sequel=True, is_upper=is_upper)\n elif file_code == 1:\n logger.error(\"SAM is not supported.\")\n return -1\n elif file_code == 2 or file_code == 3:\n yield from parse_fastx_chunk(fn, chunk_size, is_upper=is_upper)\n else:\n logger.error(\"The input file format is unknown and not supported yet.\")\n return -1\n\ndef open_seq(fn):\n file_code = guess_format(fn)\n if file_code == 0:\n (reads, n_seqs, n_bases) = parse_bam(fn, is_sequel=True)\n return (file_code, reads, n_seqs, n_bases)\n elif file_code == 1:\n logger.error(\"Sorry. SAM is not supported.\")\n return -1\n elif file_code == 2:\n (reads, n_seqs, n_bases) = parse_fastx(fn)\n return (file_code, reads, n_seqs, n_bases)\n elif file_code == 3:\n (reads, n_seqs, n_bases) = parse_fastx(fn)\n return (file_code, reads, n_seqs, n_bases)\n else:\n logger.error(\"Sorry. the input file format is unknown and not supported.\")\n return -1\n\n# 0->bam, 1->sam, 2->fastq, 3->fasta, -1->error\ndef guess_format(fn):\n try:\n fh = open(fn, 'rb')\n except:\n logger.error(\"cannot open %s\" % fn)\n\n try:\n majic = os.read(fh.fileno(), 4)\n except:\n logger.error(\"cannot read %s\" % fn)\n\n # pybam and/or biopython way\n if majic == 'BAM\\1':\n return 0\n fh.close()\n elif majic == b'\\x1f\\x8b\\x08\\x04':\n # compressed bam\n return 0\n fh.close()\n\n fh.close()\n\n try:\n fh = open(fn, 'r')\n except:\n logger.error(\"cannot open %s\" % fn)\n\n # assume sam, fastx\n at_line_cnt = 0\n for line in fh:\n if line[0] == '@':\n at_line_cnt += 1\n continue\n elif at_line_cnt > 0:\n if at_line_cnt > 1:\n # header of sam\n fh.close()\n return 1\n cn = len(line.split(\"\\t\"))\n if cn == 11:\n fh.close()\n return 1\n at_line_cnt = 0\n # fastq\n fh.close()\n return 2\n elif line[0] == '>' and at_line_cnt == 0:\n # fasta\n fh.close()\n return 3\n else:\n cn = len(line.split(\"\\t\"))\n if cn == 11:\n fh.close()\n return 1\n at_line_cnt = 0\n continue\n\n # something else\n fh.close()\n return -1\n\n# this is basically for pbbam, where there is no QV, and no support from minimap2.\n# is_sequel option should be True, otherwise, this'll be very slow.\n# https://github.com/lh3/minimap2/issues/159\ndef parse_bam(fn, *, is_sequel=True):\n reads = []\n n_seqs = 0\n n_bases = 0\n\n # basically for sequel\n input_bam = pysam.AlignmentFile(fn, 'rb', check_sq=False)\n for e in input_bam:\n n_seqs += 1\n n_bases += len(e.query_sequence)\n \n if is_sequel:\n qual_33 = '!' * e.query_length\n else:\n qual_33 = \"\".join([chr(q+33) for q in e.query_qualities])\n \n reads.append( [e.query_name, e.query_sequence, qual_33] )\n\n return (reads, n_seqs, n_bases)\n\ndef parse_bam_chunk(fn, cs, is_sequel=True, is_upper=False):\n reads = []\n n_seqs = 0\n n_bases = 0\n size = 0\n # basically for sequel\n input_bam = pysam.AlignmentFile(fn, 'rb', check_sq=False)\n for e in input_bam:\n n_seqs += 1\n n_bases += len(e.query_sequence)\n if is_sequel:\n qual_33 = '!' * e.query_length\n else:\n qual_33 = \"\".join([chr(q+33) for q in e.query_qualities])\n if is_upper:\n reads.append( [e.query_name, e.query_sequence.upper(), qual_33] )\n else:\n reads.append( [e.query_name, e.query_sequence, qual_33] )\n size += sys.getsizeof(e.query_name) + sys.getsizeof(e.query_sequence) + sys.getsizeof(qual_33)\n if size >= cs:\n yield (reads, n_seqs, n_bases)\n size = 0\n reads = []\n yield (reads, n_seqs, n_bases)\n\ndef parse_fastx_chunk(fn, cs, is_upper=False):\n reads = []\n n_seqs = 0\n n_bases = 0\n size = 0\n with pysam.FastxFile(fn) as f:\n for e in f:\n a = []\n if e.quality:\n if is_upper:\n reads.append( [e.name, e.sequence.upper(), e.quality] )\n else:\n reads.append( [e.name, e.sequence, e.quality] )\n size += sys.getsizeof(e.name) + sys.getsizeof(e.sequence) + sys.getsizeof(e.quality)\n else:\n if is_upper:\n reads.append( [e.name, e.sequence.upper(), \"!\"*len(e.sequence)] )\n else:\n reads.append( [e.name, e.sequence, \"!\"*len(e.sequence)] )\n size += sys.getsizeof(e.name) + sys.getsizeof(e.sequence) + sys.getsizeof(\"!\"*len(e.sequence))\n n_seqs += 1\n n_bases += len(e.sequence)\n if size >= cs:\n yield (reads, n_seqs, n_bases)\n size = 0\n reads = []\n yield (reads, n_seqs, n_bases)\n\ndef parse_fastx(fn):\n reads = []\n n_seqs = 0\n n_bases = 0\n\n with pysam.FastxFile(fn) as f:\n for e in f:\n if e.quality:\n reads.append( [e.name, e.sequence, e.quality] )\n else:\n reads.append( [e.name, e.sequence, \"!\"*len(e.sequence)] )\n n_seqs += 1\n n_bases += len(e.sequence)\n\n return (reads, n_seqs, n_bases)\n\n# deprecated.\ndef __parse_fastq(fn):\n reads = []\n n_seqs = 0\n n_bases = 0\n with open(fn, 'r') as fq:\n for line in fq:\n n_seqs += 1\n name = line.strip()[1:]\n seq = next(fq).strip()\n n_bases += len(seq)\n next(fq)\n qual = next(fq).strip()\n reads.append( [name, seq, qual] )\n return (reads, n_seqs, n_bases)\n\ndef get_Qx_bases(reads, threshold=10):\n _t = threshold + 33\n num = 0\n\n if len(reads[0]) < 3:\n # fasta case\n return num\n\n for read in reads:\n for i in range(len(read[2])):\n if ord(read[2][i]) >= _t:\n num += 1\n\n return num\n\n# deprecated. no support for multi line, but this is not practical.\ndef __parse_fasta(fn):\n reads = []\n n_seqs = 0\n n_bases = 0\n with open(fn, 'r') as fq:\n for line in fq:\n n_seqs += 1\n name = line.strip()[1:]\n seq = next(fq).strip()\n n_bases += len(seq)\n reads.append( [name, seq] )\n return (reads, n_seqs, n_bases)\n\ndef write_fastq(fn, reads, is_chunk=False):\n if(is_chunk==False and os.path.isfile(fn)):\n logger.error(\"the file %s already exists.\" % fn)\n return None\n\n try:\n reads[0]\n except IndexError:\n logger.error(\"No read to be output\")\n return None\n\n # due to chunking, write mode was changed to a.\n mode = 'a' if is_chunk else 'w'\n with open(fn, mode) as fq:\n for r in reads:\n fq.write(\"@%s\\n%s\\n+\\n%s\\n\" % tuple(r))\n\n return True\n\ndef subsample_from_chunk(chunk, cum_n_seq, s_reads, param, s_seed=7, elist=None):\n frac = 0.\n num = 0\n n_seqs = cum_n_seq\n k = 0\n\n if param >= 1.:\n num = param\n if not s_reads:\n logger.info(\"list for subsample is not initialized. Initializing now.\")\n s_reads = [0] * num\n else:\n frac = param\n a = []\n\n np.random.seed(seed=s_seed)\n h = np.random.uniform(size = len(chunk)+1)\n \n for read in chunk:\n name = read[0]\n seq = read[1]\n qual = read[2]\n if elist and name in elist:\n #print(\"%s is skipped.\" % name)\n continue\n n_seqs += 1\n if num:\n if(n_seqs - 1 < num):\n d = n_seqs-1\n else:\n d = int(h[k]*n_seqs)\n if(d < num):\n s_reads[d] = [name, seq, qual]\n elif( h[k] < frac):\n a.append([name, seq, qual])\n k += 1\n\n if num:\n return s_reads\n else:\n return s_reads + a\n\n# follow the logic flow of seqtk\n# 2018/4/30 added exclude list. This is an ad-hoc way, and violates sampling schema. but let's see.\ndef sample_random_fastq_list(reads, param, *, s_seed=7, elist=None):\n frac = 0.\n num = 0\n n_seqs = 0\n s_n_seqs = 0\n s_n_bases = 0\n s_reads = []\n\n if param >= 1.:\n num = param\n s_reads = [0] * num\n else:\n frac = param\n\n np.random.seed(seed=s_seed)\n for read in reads:\n if(n_seqs%100000 == 0):\n h = np.random.uniform(size = 100000)\n name = read[0]\n seq = read[1]\n qual = read[2]\n if elist and name in elist:\n #print(\"%s is skipped.\" % name)\n continue\n n_seqs += 1\n if num:\n if(n_seqs - 1 < num):\n d = n_seqs-1\n else:\n d = int(h[(n_seqs-1)%100000]*n_seqs)\n if(d < num):\n if s_reads[d]:\n s_n_seqs -= 1\n s_n_bases -= len(s_reads[d][1])\n s_reads[d] = [name, seq, qual]\n s_n_seqs += 1\n s_n_bases += len(seq)\n elif( h[(n_seqs-1)%100000] < frac):\n s_reads.append([name, seq, qual])\n s_n_seqs += 1\n s_n_bases += len(seq)\n\n if num and n_seqs < num:\n s_reads = s_reads[:n_seqs]\n return (s_reads, s_n_seqs, s_n_bases)\n\n# follow the logic flow of seqtk\n# 2018/4/30 added exclude list. This is an ad-hoc way, and violates sampling schema. but let's see.\ndef sample_random_fastq(fn, param, *, s_seed=7, elist=None):\n frac = 0.\n num = 0\n n_seqs = 0\n s_n_seqs = 0\n s_n_bases = 0\n reads = []\n\n if param > 1.:\n num = param\n reads = [0] * num\n else:\n frac = param\n\n np.random.seed(seed=s_seed)\n with open(fn, 'r') as fq:\n for line in fq:\n if(n_seqs%100000 == 0):\n h = np.random.uniform(size = 100000)\n name = line.strip()[1:].split(\" \")[0]\n seq = next(fq).strip()\n next(fq)\n qual = next(fq).strip()\n #n_bases += len(seq)\n if elist and name in elist:\n #logger.error(\"%s is skipped.\" % name)\n continue\n n_seqs += 1\n if num:\n if(n_seqs - 1 < num):\n d = n_seqs-1\n else:\n d = int(h[(n_seqs-1)%100000]*n_seqs)\n if(d < num):\n if reads[d]:\n s_n_seqs -= 1\n s_n_bases -= len(reads[d][1])\n reads[d] = [name, seq, qual]\n s_n_seqs += 1\n s_n_bases += len(seq)\n elif( h[(n_seqs-1)%100000] < frac):\n reads.append([name, seq, qual])\n s_n_seqs += 1\n s_n_bases += len(seq)\n return (reads, s_n_seqs, s_n_bases)\n\n# test\nif __name__ == \"__main__\":\n # some test code here\n #code = guess_format(\"/home/fukasay/analyses/ont/minimap2_mapping/Hai1D_albacore213_1dsq_map.sam\")\n #print(code)\n\n fn = \"/home/fukasay/rawdata/pb/rs2_ecoli_pacbio_official/ecoli_pacbio_p6c4.subreads.bam\"\n (c, reads, n_seqs, n_bases) = open_seq(fn)\n print(len(reads), n_seqs, n_bases)\n #for (reads, n_seqs, n_bases) in open_seq_chunk(fn, guess_format(fn), 0.25*1024**3):\n # print(len(reads), n_seqs, n_bases)\n","sub_path":"lq_utils.py","file_name":"lq_utils.py","file_ext":"py","file_size_in_byte":12901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"458992111","text":"# NodeList is one of\r\n# None or\r\n# Node(value, rest), where rest is reference to the rest of the list\r\nclass Node:\r\n def __init__(self, value, rest):\r\n self.value = value # object reference stored in Node\r\n self.rest = rest # reference to NodeList\r\n def __eq__(self, other):\r\n return ((type(other) == Node)\r\n and self.value == other.value\r\n and self.rest == other.rest\r\n )\r\n def __repr__(self):\r\n return (\"Node({!r}, {!r})\".format(self.value, self.rest))\r\n\r\nclass Stack:\r\n \"\"\"Implements an efficient last-in first-out Abstract Data Type using a node list\"\"\"\r\n\r\n # top is the top Node of stack\r\n def __init__(self, top=None):\r\n self.top = top # top node of stack\r\n self.num_items = 0 # number of items in stack\r\n node = top # set number of items based on input\r\n while node is not None:\r\n self.num_items += 1\r\n node = node.rest\r\n\r\n def __eq__(self, other):\r\n return ((type(other) == Stack)\r\n and self.top == other.top\r\n )\r\n\r\n def __repr__(self):\r\n return (\"Stack({!r})\".format(self.top))\r\n\r\n def is_empty(self):\r\n '''Returns True if the stack is empty, and False otherwise\r\n MUST have O(1) performance'''\r\n return self.num_items == 0\r\n\r\n def push(self, item):\r\n '''Pushes item on stack.\r\n MUST have O(1) performance'''\r\n self.top = Node(item, self.top)\r\n self.num_items += 1\r\n\r\n def pop(self):\r\n '''If stack is not empty, pops item from stack and returns item.\r\n If stack is empty when pop is attempted, raises IndexError\r\n MUST have O(1) performance'''\r\n if self.is_empty():\r\n raise IndexError\r\n else:\r\n self.num_items -= 1\r\n removed_value = self.top.value\r\n self.top = self.top.rest\r\n return removed_value\r\n\r\n def peek(self):\r\n '''If stack is not empty, returns next item to be popped (but does not remove the item)\r\n If stack is empty, raises IndexError\r\n MUST have O(1) performance'''\r\n if self.is_empty():\r\n raise IndexError\r\n else:\r\n return self.top.value\r\n\r\n\r\n def size(self):\r\n '''Returns the number of elements currently in the stack, not the capacity\r\n MUST have O(1) performance'''\r\n return self.num_items\r\n\r\nif __name__ == \"__main__\":\r\n\r\n stack1 = Stack()\r\n print(stack1)\r\n stack1.push(1)\r\n stack1.push(2)\r\n print(stack1.pop())\r\n print(stack1)\r\n print(stack1.size())\r\n\r\n stack2 = Stack(stack1.top)\r\n\r\n print(stack1 == stack2)\r\n stack2.push(3)\r\n print(stack1 == stack2)","sub_path":"lab02/stack_nodelist.py","file_name":"stack_nodelist.py","file_ext":"py","file_size_in_byte":2773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"419124284","text":"''' Um professor quer sortear um dos seus quatro alunos para apagar o quadro. Faça um programa que ajude ele, lendo\no nome deles e escrevendo o nome escolhido '''\n\nfrom random import choice\nprint('Digite o nome dos alunos:')\na1 = input('Aluno 1: ')\na2 = input('Aluno 2: ')\na3 = input('Aluno 3: ')\na4 = input('Aluno 4: ')\nprint ('\\nEscolha: {}'.format(choice((a1, a2, a3, a4))))\n'''\nlista = [a1, a2, a3, a4]\nescolhido = choice(lista)\nprint ('\\nEscolha: {}'.format(escolhido))\n'''\n","sub_path":"pacote download/Exercicios/ex019.py","file_name":"ex019.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"42335904","text":"import os\nimport sys\nimport csv\nidIndex = 1\ncsvRead = []\ncsvReader = csv.reader(open('/Users/Shared/ids.csv'))\nfor row in csvReader:\n csvRead.append(row)\nwhile idIndex < len(csvRead):\n appleid = str(csvRead[idIndex][0])\n password = str(csvRead[idIndex][1])\n birthMonth = str(csvRead[idIndex][2])\n birthDay = str(csvRead[idIndex][3])\n birthYear = str(csvRead[idIndex][4])\n firstName = str(csvRead[idIndex][5])\n lastName = str(csvRead[idIndex][6])\n streetAddress = str(csvRead[idIndex][7])\n city = str(csvRead[idIndex][8])\n stateCode = str(csvRead[idIndex][9])\n zipCode = str(csvRead[idIndex][10])\n areaCode = str(csvRead[idIndex][11]) \n phoneNum = str(csvRead[idIndex][12])\n openApp(\"iTunes\")\n click(\"Screen Shot 2013-01-08 at 9.36.17 AM.png\")\n type(\"iBooks\"+Key.ENTER)\n # clear search field, just 'cause\n click(\"1357656258285.png\")\n onAppear(\"iPadAppsEBoo.png\", click(\"LiBooksBooks.png\"))\n # appleID login should appear\n wait(\"SignIntodown.png\")\n click(\"CreateAppleI.png\")\n wait(\"IDclickcanon.png\", 12)\n click(\"IDclickcanon.png\")\n wait(\"innrirnnrntn.png\", 12)\n click(\"innrirnnrntn.png\")\n # accept terms checkbox\n click(\"1357656934662.png\")\n # big details form\n wait(\"EmailemaiIex.png\", 12)\n type(\"EmailemaiIex.png\", appleid + Key.TAB + password + Key.TAB + password + \n Key.TAB + Key.DOWN + Key.DOWN + Key.ENTER + Key.TAB + \"Newton\" +\n Key.TAB + Key.DOWN + Key.DOWN + Key.ENTER + Key.TAB + \"Apple\" +\n Key.TAB + Key.DOWN + Key.DOWN + Key.DOWN + Key.ENTER + Key.TAB + \"Steve\" +\n Key.TAB + Key.TAB + birthMonth + Key.ENTER + Key.TAB +\n birthDay + Key.ENTER + Key.TAB + birthYear)\n click(\"WouldNeldMn.png\")\n click(\"NlNi.png\")\n type(Key.PAGE_DOWN)\n click(\"1357659787705.png\")\n wait(\"sclickhereal.png\", 12)\n click(\"BillingAddre.png\")\n click(\"Screen Shot 2013-01-08 at 12.52.37 PM.png\")\n type(\"BillingAddre-1.png\", firstName + Key.TAB + lastName + Key.TAB + streetAddress +\n Key.TAB + Key.TAB + city + Key.TAB + stateCode + Key.TAB + zipCode +\n Key.TAB + areaCode + Key.TAB + phoneNum)\n \n click(\"CreateAppleI-1.png\")\n wait(\"1357672144168.png\", 12)\n idIndex += 1","sub_path":"AppleIDcreate.sikuli/AppleIDcreate.py","file_name":"AppleIDcreate.py","file_ext":"py","file_size_in_byte":2265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"427998939","text":"#!/usr/bin/env python3\nimport sys, os.path, os, time, stat, struct, ctypes, io, subprocess, math, random, difflib\nimport ply, re, traceback\nimport argparse, base64, json\nfrom js_global import AbstractGlob\nfrom js_cc import concat_smaps\n\n#source map concatenator, for\n#browsers that don't support\n#index maps\n\nclass LocalGlob(AbstractGlob):\n g_file = \"\"\n g_outfile = \"\"\n \nglob = LocalGlob()\n\ndef main():\n cparse = argparse.ArgumentParser(add_help=False)\n\n glob.add_args(cparse)\n cparse.add_argument(\"--help\", action=\"help\", help=\"Print this message\")\n \n args = cparse.parse_args()\n glob.parse_args(cparse, args)\n \n glob.g_outfile = args.outfile\n \n #test_regexpr()\n #return 1\n \n glob.g_file = args.infile\n \n if args.infile == None:\n print(\"js_smcat.py: no input files\")\n return -1\n \n f = open(args.infile, \"r\")\n files = f.readlines()\n f.close()\n \n for i in range(len(files)):\n files[i] = os.path.abspath(os.path.normpath(files[i].strip()))\n \n ret = json.dumps(concat_smaps(files))\n \n f = open(args.outfile, \"w\")\n f.write(ret)\n f.close()\n \n return 0\n\nif __name__ == \"__main__\":\n import io, traceback\n \n try:\n ret = main()\n except SystemExit:\n ret = -1\n except:\n traceback.print_stack()\n traceback.print_exc()\n \n ret = -1\n sys.exit(ret)\n\n","sub_path":"tools/extjs_cc/js_smcat.py","file_name":"js_smcat.py","file_ext":"py","file_size_in_byte":1399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"446921060","text":"# -*- encoding: utf-8 -*-\n\nimport os\nimport numpy as np\nfrom PIL import Image, ImageOps\nimport matplotlib.pyplot as plt\nimport scipy.misc as sp\n\ndef create_manifest_train(train_path='Training_data/'):\n \"\"\"\n Just a quick helper function to create a manifest of the available training files for future ease\n :param train_path: the path where the data is located\n \"\"\"\n # The path suffixes for the corresponding folders\n c0_suffix = 'Normal/'\n c1_suffix = 'InSitu/'\n c2_suffix = 'Benign/'\n c3_suffix = 'Invasive/'\n\n # Making a list of the folder contents\n c0_list = os.listdir(train_path + c0_suffix)\n c1_list = os.listdir(train_path + c1_suffix)\n c2_list = os.listdir(train_path + c2_suffix)\n c3_list = os.listdir(train_path + c3_suffix)\n\n # Dumping list contents into file with class appended\n with open(train_path+'labels.txt', 'w') as f:\n for x in c0_list:\n f.write(c0_suffix + x + \" 0\\n\")\n for x in c1_list:\n f.write(c1_suffix + x + \" 1\\n\")\n for x in c2_list:\n f.write(c2_suffix + x + \" 2\\n\")\n for x in c3_list:\n f.write(c3_suffix + x + \" 3\\n\")\n\n\ndef create_manifest_test(test_path='Test_data/'):\n classes = ['Normal', 'In situ', 'Benign', 'Invasive']\n with open(test_path + 'labels_orig.txt', 'r') as f:\n lines = f.readlines()\n with open(test_path + 'labels.txt', 'w') as f:\n for line in lines:\n stripped = line.strip().rsplit(\"\\t\")\n f.write(stripped[0] + '.tif %d\\n' % (classes.index(stripped[1])))\n\n\ndef augment(path):\n with open(path + '/labels.txt', 'r') as f:\n lines = [line.strip().split() for line in f.readlines()]\n for line in lines:\n orig = Image.open('%s/%s' % (path, line[0]))\n # Flipping, Mirroring, Both\n ops = list()\n ops.append(ImageOps.flip(orig))\n ops.append(ImageOps.mirror(orig))\n ops.append(ImageOps.mirror(ops[0]))\n # Saving\n for i in range(len(ops)):\n ops[i].save('%s/%s_%d.tif' % (path, line[0][:-4], i+1))\n\n\ndef extend_manifest(path):\n with open(path + '/labels.txt', 'r') as f:\n lines = [line.strip().split() for line in f.readlines()]\n aug = list()\n print(lines)\n for line in lines:\n for i in range(3):\n aug.append(['%s_%d.tif' % (line[0][:-4], i+1), line[1]])\n with open(path + '/labels_ext.txt', 'w') as f:\n for line in lines+aug:\n f.write('%s %s\\n' % (line[0], line[1]))\n\n\ndef circle_cut(img, n=10, dims=[224, 224]):\n \"\"\"\n Cuts n sub-images from img with a size of dims in spiral pattern originating from the middle of img\n :param img: image to cut\n :param n: number of cuts to make\n :param dims: size of the cut images\n :return: the n slices of img\n \"\"\"\n center = [int(i/2) for i in img.shape][:2]\n r = int(dims[0]/2)\n step = 360 / n\n for t in range(n):\n offset = np.random.randint(-int(dims[0] / 3), int(dims[0] / 3))\n x = int(center[0] + r * np.cos(step * t)) + offset\n y = int(center[1] + r * np.sin(step * t)) + offset\n yield img[int(x-dims[0]/2):int(x+dims[0]/2), int(y-dims[1]/2):int(y+dims[1]/2), :]\n\n\ndef augment_cut(path, n=10, dims=[384, 512]):\n manifest = 'labels_ext.txt' if os.path.exists(path+\"labels_ext.txt\") else 'labels.txt'\n with open(path + manifest, 'r') as f:\n lines = [line.strip().split() for line in f.readlines()]\n aug = list()\n for line in lines:\n sample = np.array(Image.open(path + line[0]))\n idx = 0\n for slice in circle_cut(sample, n, dims):\n fn = '%s_%d.tif' % (line[0][:-4], idx)\n try:\n sp.imsave('%s_aug/%s' % (path[:-1], fn), slice)\n except FileNotFoundError:\n os.makedirs('%s_aug/%s/' % (path[:-1], fn.strip().split('/')[0]))\n sp.imsave('%s_aug/%s' % (path[:-1], fn), slice)\n aug.append('%s %s' % (fn, line[1]))\n idx += 1\n with open('%s_aug/%s' % (path[:-1], manifest), 'w') as f:\n for line in aug:\n f.write(line + '\\n')\n\n\nif __name__ == \"__main__\":\n print(\"This is a collection of helper functions you can call if you import this file.\")\n augment_cut('Test_data/')\n\n# TODO: DO NOT CUT TEST IMAGES RANDOMLY, USE A GRID AND DECISION SCHEME OR IDK\n# TODO: TEST TRAIN ACCURACY\n# TODO: CHECK IF RESIZING IMAGE DOESNT SCREW WITH ASPECT RATION IN MODELS.PY\n","sub_path":"helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":4451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"597463971","text":"# coding=utf-8\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\n# The class for a rotary angle sensor (Grove - Rotary Angle Sensor)\n\nfrom cisco_deviot.thing import Property, PropertyType\nfrom cisco_grovepi.sensor import Sensor\n\n\nclass Rotary(Sensor):\n def __init__(self, tid, name, pin):\n Sensor.__init__(self, tid, name, pin, \"angle\")\n self.add_property(Property(name=\"angle\", type=PropertyType.INT, value=0, unit=\"°\", range=[0, 100]))\n\n def update_state(self):\n data = Sensor.analog_read(self)\n if data is not None:\n self.update_property(angle = data)\n","sub_path":"cisco_grovepi/rotary.py","file_name":"rotary.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"373599142","text":"import os.path as osp\nimport numpy as np\nimport random\nimport matplotlib.pyplot as plt\nimport torchvision\nfrom torch.utils import data\nfrom PIL import Image\nimport torchvision.transforms.functional as TF\nimport torch\nIMG_MEAN = np.array((122.67891434, 116.66876762, 104.00698793), dtype=np.float32)\nclass BaseDataSet(data.Dataset):\n def __init__(self, root, list_path, joint_transform=None, transform=None, label_transform = None, max_iters=None, ignore_label=255, set='val', dataset='cityscapes'):\n self.root = root\n self.list_path = list_path\n self.ignore_label = ignore_label\n self.set = set\n self.transform = transform\n self.joint_transform = joint_transform\n self.label_transform = label_transform\n\n if self.set !='train':\n self.list_path = (self.list_path).replace('train', self.set)\n\n self.img_ids =[]\n with open(self.list_path) as f:\n for item in f.readlines():\n fields = item.strip().split('\\t')[0]\n self.img_ids.append(fields)\n if not max_iters==None:\n total = len(self.img_ids)\n index = list( np.random.choice(total, max_iters, replace=False))\n self.img_ids = [self.img_ids[i] for i in index]\n# self.img_ids = self.img_ids * int(np.ceil(float(max_iters) / len(self.img_ids)))\n # print(len(self.img_ids))\n\n self.files = []\n if dataset=='gta5':\n for name in self.img_ids:\n img_file = osp.join(self.root, 'images', name)\n label_file = osp.join(self.root, name)\n label_file=label_file.replace('image', 'label')\n label_file=label_file.replace('.', '_canny.')\n self.files.append({\n \"img\": img_file,\n \"label\": label_file,\n \"name\": name,\n \"centroid\":(0,0)\n })\n else:\n for name in self.img_ids:\n img_file = osp.join(self.root, \"leftImg8bit/%s/%s\" % (self.set, name))\n label_name = name.replace('leftImg8bit', 'gtFine_edge')\n label_file =osp.join(self.root, 'gtFine/%s/%s' % (self.set, label_name))\n self.files.append({\n \"img\": img_file,\n \"label\":label_file,\n \"name\": name,\n \"hard_loc\":(0,0)\n })\n\n def __len__(self):\n return len(self.files)\n\n def __getitem__(self, index):\n datafiles = self.files[index]\n\n# try:\n if 1:\n image = Image.open(datafiles[\"img\"]).convert('RGB')\n label = Image.open(datafiles[\"label\"]).convert('L')\n name = datafiles[\"name\"]\n\n\n centroid=None\n if self.joint_transform is not None:\n image, label = self.joint_transform(image, label, centroid)\n image = image-IMG_MEAN\n image = TF.to_tensor(image)\n if self.transform is not None:\n image = self.transform(image)\n if self.label_transform is not None:\n label = self.label_transform(label)\n wei = torch.ones_like(label).float()\n else:\n# except Exception as e:\n index = index - 1 if index > 0 else index + 1\n return self.__getitem__(index)\n if self.set=='train':\n return image, label\n else:\n return image, name\n\n\nif __name__ == '__main__':\n dst = GTA5DataSet(\"./data\", is_transform=True)\n trainloader = data.DataLoader(dst, batch_size=4)\n for i, data in enumerate(trainloader):\n imgs, labels = data\n if i == 0:\n img = torchvision.utils.make_grid(imgs).numpy()\n img = np.transpose(img, (1, 2, 0))\n img = img[:, :, ::-1]\n plt.imshow(img)\n plt.show()\n","sub_path":"data/all_dataset.py","file_name":"all_dataset.py","file_ext":"py","file_size_in_byte":3897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"479768781","text":"import math\nfrom sysfs import sys\n\n\nclass TemperatureBlock:\n def __init__(self):\n self.sys_dirs = [d\n for name, d in sys.clazz.thermal._dirs.items()\n if name.startswith('thermal_zone') and d.type != 'iwlwifi']\n\n def get(self):\n for d in self.sys_dirs:\n temp = float(d.temp) / 1e3\n yield {'full_text': '{: =2.0f}°C'.format(temp),\n 'color': '#FF7F64',\n 'markup': 'pango'}\n","sub_path":"blocks/thermal.py","file_name":"thermal.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"34643651","text":"import asyncio\nfrom functools import wraps\nfrom typing import Optional\n\nimport aioredis\n\nfrom common import json\n\n\nclass RedisStorage:\n def __init__(self, host='localhost', port=6379, db=None, password=None, ssl=None, pool_size=10, loop=None, prefix='vkme', **kwargs):\n self._host = host\n self._port = port\n self._db = db\n self._password = password\n self._ssl = ssl\n self._pool_size = pool_size\n self._loop = loop or asyncio.get_event_loop()\n self._kwargs = kwargs\n self._prefix = (prefix,)\n\n self._redis: aioredis.RedisConnection = None\n self._connection_lock = asyncio.Lock(loop=self._loop)\n\n async def redis(self) -> aioredis.Redis:\n async with self._connection_lock:\n if self._redis is None:\n self._redis = await aioredis.create_redis_pool((self._host, self._port),\n db=self._db, password=self._password, ssl=self._ssl,\n minsize=1, maxsize=self._pool_size,\n loop=self._loop, **self._kwargs)\n return self._redis\n\n def generate_key(self, *parts):\n return ':'.join(self._prefix + tuple(map(str, parts)))\n\n async def close(self):\n async with self._connection_lock:\n if self._redis and not self._redis.closed:\n self._redis.close()\n del self._redis\n self._redis = None\n\n async def wait_closed(self):\n async with self._connection_lock:\n if self._redis:\n return await self._redis.wait_closed()\n return True\n\n async def write_update(self, owner_id: int, object_id: int, update: dict):\n key = self.generate_key(owner_id, object_id, 'updates')\n redis = await self.redis()\n await redis.rpush(key, json.dumps(update))\n\n async def get_update(self, owner_id: int, object_id: int, default: dict = None) -> Optional[dict]:\n key = self.generate_key(owner_id, object_id, 'updates')\n redis = await self.redis()\n result = await redis.lrange(key, start=-1, stop=-1, encoding='utf8')\n if result:\n return json.loads(result[0])\n return default\n\n async def reset_all(self, full=False):\n redis = await self.redis()\n if full:\n redis.flushdb()\n else:\n keys = await redis.keys(self.generate_key('*'))\n redis.delete(*keys)\n\n\ndef async_retry(exception=Exception, retries_count=5, sleep_for=0.):\n def decorator(func):\n @wraps(func)\n async def wrapper(self, *args, **kwargs):\n ret, exc = None, None\n for _ in range(retries_count):\n try:\n ret = await func(self, *args, **kwargs)\n except exception as e:\n exc = e\n else:\n break\n self.logger.warning(exc)\n await asyncio.sleep(sleep_for)\n else:\n self.logger.error(exc)\n raise exc\n return ret\n\n return wrapper\n\n return decorator\n","sub_path":"common/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"189585012","text":"#!/usr/bin/env python3\n# encoding=utf8\n\nimport os\ndef find_file_extension(root_dir, extension):\n fileList=[]\n for root, dirs, files in os.walk(root_dir):\n for file in files:\n if file.endswith(extension):\n fileList.append(os.path.join(root,file))\n return fileList\n\nimport codecs\ndef read_meta (txt_file):\n # this return loaded tuple of (text,gender)\n lines = [line.rstrip('\\n') for line in codecs.open(txt_file, 'r', 'utf-8')]\n if len(lines)>1:\n logger.warn ('txt format {}'.format(txt_file))\n\n text,gender =' '.join(lines[0].strip().split()[8:]).upper(), ''.join(lines[0].strip().split()[4]).lower()\n return (text_norm(text),gender)\n\n# systematic errors in transcription. noted these may only occured at this corpus\n# so these string operation are basiclly one-off\n# what s => what's\n# W hat s => What's\n# w hat s => what's\n# C an => Can\n# E nglish => English\n# H ello=> Hello\n# H ow => HOW\n# W I F I => WIFI\ndef text_norm(text):\n text=text.replace('WHAT S ','WHAT\\'S ').replace('W HAT S','WHAT\\'S').replace('W IF I','WIFI').replace('M ICHAEL','MICHAEL')\\\n .replace('J ACKSON','JACKSON').replace('H ELLO','HELLO').replace('C AN','CAN').replace('I M ','I\\'M ')\\\n .replace('H OW ','HOW ').replace('W I F I','WIFI').replace('\\.','').replace('°','度')\\\n .replace('\\`','').replace(u'\\u200b', '')\n return text\n\nimport wave\ndef validate_wave(wavfile):\n # check existing on the txt file\n if not os.path.exists(wavfile.replace('.wav','.txt')):\n logger.warn('no txt:{}'.format(wavfile))\n return False\n # open and read the wave file\n wr=wave.open(wavfile, 'r')\n nchannels, sampwidth, framerate, nframes, comptype, compname = wr.getparams()\n data=wr.readframes(nframes)\n wr.close()\n # very short segment (<50 msec) will have some problem\n if sampwidth*nframes == len(data) and nframes/framerate>0.05:\n return True\n else:\n logger.warn ('cannot load:{}/{}'.format(wavfile, len(data)))\n return False\n\nimport logging\nlogging.basicConfig(filename='voiceassistant.log', level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nlogger=logging.getLogger(__name__)\n\nroot_dir='/media/chiweic/Elements/RoverTech/corpus/VoiceAssistant/'\n# filter with validate_wave (wave is in format and has content (>50 msec)\nwaves=filter(lambda x: validate_wave(x),find_file_extension(root_dir,'.wav'))\n# load text, gender with the waves\ntext=[]\nwavelist=[]\nspk2gender=[]\nutt2spk=[]\nfor wav in waves:\n uttid=os.path.basename(wav).replace('.wav','')\n txt, gender= read_meta(wav.replace('.wav','.txt'))\n if len(txt)>0:\n wavelist.append(uttid+' '+wav)\n text.append(uttid+' '+txt)\n spk2gender.append(uttid+' '+gender)\n utt2spk.append(uttid+' '+uttid)\n else:\n logger.warn('empty:{}'.format(wav))\n\n# write to the target directory\nwith codecs.open('text.hanzi','w','utf-8') as ftext:\n ftext.write('\\n'.join(text))\nwith codecs.open('wav.scp','w','utf-8') as ftext:\n ftext.write('\\n'.join(wavelist))\nwith codecs.open('spk2gender','w','utf-8') as ftext:\n ftext.write('\\n'.join(spk2gender))\nwith codecs.open('utt2spk','w','utf-8') as ftext:\n ftext.write('\\n'.join(utt2spk))\n","sub_path":"local/prepare_voiceassistant.py","file_name":"prepare_voiceassistant.py","file_ext":"py","file_size_in_byte":3257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"42675399","text":"tab = [10,20,30,40,10,30,50,60,70,50,80,53,90,10,10]\ntabSave = tab\ni,j,n = 0,0,0\n#print([(i, tab.count(i)) for i in set(tab)])\nwhile i < len(tab):\n while j < len(tab):\n if tab[i] == tab[j]:\n n = n+1\n j = j+1\n if n > 1:\n print(\"Il existe, pour la valeure \",tab[i],\",\",n,\" fois cette valeur\")\n tab.remove(tab[i])\n \n n = 0\n i = i+1\n j = 0\n","sub_path":"BTS-SIO/algorithme/1ère année/TP4-listes/exercice10.py","file_name":"exercice10.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"631846827","text":"class Solution(object):\n def rotate(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: None Do not return anything, modify nums in-place instead.\n \"\"\"\n if not nums or k < 0:\n return []\n k = k % len(nums)\n self.swap(nums, 0, len(nums) - 1)\n self.swap(nums, 0, k - 1)\n self.swap(nums, k, len(nums) - 1)\n return nums\n\n def swap(self, temp, l, r):\n while l < r:\n temp[l], temp[r] = temp[r], temp[l]\n l += 1\n r -= 1","sub_path":"189_旋转数组.py","file_name":"189_旋转数组.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"27622305","text":"from django.conf.urls import patterns, url\nfrom django.views.generic import CreateView, UpdateView\nfrom forms import FeatureTypeForm, MapForm, LayerForm, MapLayerForm\nfrom views import CreateFeatures, create_map\n\nurlpatterns = patterns('',\n\n url(r'^features/create/?$',\n CreateFeatures.as_view(),\n name='feature-create'),\n\n url(r'^feature-types/create/?',\n CreateView.as_view(template_name='core/generic_form.html',\n form_class=FeatureTypeForm),\n name='feature-type-create'),\n\n url(r'^feature-types/update/(?P\\d+)/?$',\n UpdateView.as_view(template_name='core/generic_form.html',\n queryset=FeatureTypeForm.Meta.model.objects.all(),\n form_class=FeatureTypeForm),\n name='feature-type-update'),\n\n # Map CRUD Views\n url(r'^create/?$',\n create_map,\n name='map-create'),\n\n url(r'^update/(?P\\d+)/?$',\n UpdateView.as_view(template_name='core/generic_form.html',\n queryset=MapForm.Meta.model.objects.all(),\n form_class=MapForm),\n name='map-update'),\n\n # Layer CRUD Views\n url(r'^layers/create/?$',\n CreateView.as_view(template_name='core/generic_form.html', form_class=LayerForm),\n name='layer-create'),\n\n url(r'^layers/update/(?P\\d+)/?$',\n UpdateView.as_view(template_name='core/generic_form.html',\n queryset=LayerForm.Meta.model.objects.all(),\n form_class=LayerForm),\n name='layer-update'),\n\n # MapLayer CRUD Views\n url(r'^map-layers/create/?$',\n CreateView.as_view(template_name='core/generic_form.html',\n form_class=MapLayerForm),\n name='map-layer-create'),\n\n url(r'^map-layers/update/(?P\\d+)/?$',\n UpdateView.as_view(template_name='core/generic_form.html',\n queryset=MapLayerForm.Meta.model.objects.all(),\n form_class=MapLayerForm),\n name='map-layer-update'),\n)\n","sub_path":"geoq/maps/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"625541551","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright 2007 Google Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n#common\nimport os\nimport cgi\nimport codecs\nimport string\n#common\n#app engine\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp import util\nfrom google.appengine.ext.webapp import template\nfrom google.appengine.api import users\nfrom google.appengine.ext.webapp.util import run_wsgi_app\nfrom google.appengine.ext import db\n#django\n\ndef render(h, file, template_values):\n path = os.path.join(os.path.dirname(__file__), file)\n h.response.out.write(template.render(path, template_values))\n\nclass MainHandler(webapp.RequestHandler):\n def get(self):\n template_values = {\n }\n render(self, 'templates/index.html', template_values)\n\nclass Processing_Test(webapp.RequestHandler):\n def get(self):\n template_values = {\n }\n render(self, 'templates/Processing_Test.html', template_values)\n\n\nclass GPS_Test(webapp.RequestHandler):\n def get(self):\n template_values = {\n }\n render(self, 'templates/gps.html', template_values)\n\nclass Canvas_Test(webapp.RequestHandler):\n def get(self):\n template_values = {\n }\n render(self, 'templates/canvas.html', template_values)\n\nclass Sensor_Test(webapp.RequestHandler):\n def get(self):\n template_values = {\n }\n render(self, 'templates/sensor.html', template_values)\n \n\n\n#web handler\napplication = webapp.WSGIApplication([('/', MainHandler),\n ('/GPS_Test', GPS_Test),\n ('/Canvas_Test', Canvas_Test),\n ('/Processing_Test', Processing_Test),\n ('/Sensor_Test', Sensor_Test)],\n debug=True)\n\ndef main():\n run_wsgi_app(application)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"app-engine/you801106/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"357631226","text":"#-*- coding: utf-8 -*-\n#simple GUI\nimport tkinter as tk\nfrom tkinter import *\nfrom tkinter import ttk\nfrom functools import partial\nimport sys\nimport webbrowser\nimport pprint\n\n\n\n#bladeCheck = [[[0 for k in range(4)] for j in range(2)] for i in range(8)]\nbladeCheck = [[0 for j in range(2)] for i in range(3)]\n\n\n\n\n\n \n \nclass WizTool:\n nothing = \"\"\n nothing = \"\"\n world = \"BUG WORLD VARIABLE\"\n area = \"BUG AREA VARIABLE\"\n boss = \"BUG BOSS VARIABLE\"\n bossTrackerOptionsVar=[]\n schoolType = \"Fire\"\n bossTrackerOptions=[]\n spellCount=['1','2','3','4','5']\n spellRecommend=[]\n spellRoster=[]\n oldschool = schoolType\n secondary = \"calc\"\n columns = 2\n checksPerCol = 4\n rows = 8\n\n pprint.pprint(bladeCheck)\n #initialize the GUI\n def __init__(self, master):\n content = ttk.Frame(master, padding=(3,12,12,12))\n \n content.grid(column=0,row=0,sticky=(N,S,E,W))\n btFrame=ttk.Frame(content)\n bossFrame=ttk.Frame(content)\n self.master = master\n self.initUI(btFrame,content)\n self.initBT(btFrame,content,WizTool.schoolType)\n self.initBossTracker(bossFrame,content)\n print('hi')\n\n def initBossTracker(self,frame,content):\n textLabel=Label(content,text=\"Boss Guide\",font=((\"Times\", 10, \"bold\")))\n textLabel.grid(column=6,row=0)\n #Define the frames#\n spaceFrame=ttk.Frame(content)\n spaceFrame.configure(width=20)\n spaceFrame.grid(column=4,row=0,sticky=(N,S,E,W))\n frame.configure(borderwidth=5,relief=\"sunken\",width=550,height=600,padding=(3,3,12,12))\n frame.grid(column=5,row=1,columnspan=3,sticky=(N,S,E,W))\n bossFrame=ttk.Frame(frame)\n bossFrame.configure(width=470,height=610)\n bossFrame.grid_propagate(0)\n bossFrame.grid(column=0,row=0)\n #insert things that will be used now\n bossTextFrame=ttk.Frame(bossFrame)\n bossTextFrame.configure(width=450,height=200,relief=\"sunken\",padding=(3,3,12,12))\n bossTextFrame.grid_propagate(0)\n bossTextFrame.grid(row=1,column=0,columnspan=6,sticky=(E,W),ipady=20,pady=10)\n\n bossNameLabel = Label(bossTextFrame,anchor=W,text=\"Boss Name\",font=((\"Times\", 16, \"bold\")),width=20) \n bossNameLabel.grid(row=0,column=0,sticky=(N,W))\n\n bossCheatLabel = Label(bossTextFrame,anchor=NW,text=\"•Cheat\\n•Cheat\\n•Cheat\\n\",font=((\"Times\", 10)),width=37,wraplength=250,justify=LEFT) \n bossCheatLabel.grid(row=1,column=0,sticky=(N,W))\n\n bossPictureLabel = Label(bossTextFrame)\n bossPictureLabel.grid(row = 1,column=1,ipadx=10,ipady=10,sticky=(N))\n bossPic = PhotoImage(file=\"stock_Boss.gif\")\n bossPictureLabel.configure(image=bossPic)\n bossPictureLabel.image = bossPic\n \n #VARIABLES#\n optionWidth = 17\n\n \n ###########\n bossHelpFrame = ttk.Frame(bossFrame)\n bossHelpFrame.configure(width=450,height=500,relief=\"groove\",padding=(3,3,12,12))\n bossHelpFrame.grid(row=3,column=0,columnspan=5,pady=0)\n\n def initiateSpells():\n textLabel = Label(bossFrame)\n textLabel.configure(text=\"Recommended Spells:\",font=((\"Times\", 10, \"bold\")))\n textLabel.grid(row=2,column=0)\n for spell in self.spellCount:\n spellPic = PhotoImage(file=\"nullspell.gif\")\n spellLabel = Label(bossHelpFrame)\n spellLabel.grid(row=0,column=spell,pady=1,padx=1)\n spellLabel.configure(image=spellPic)\n spellLabel.image=spellPic\n self.spellRoster.append(spellLabel)\n for spell in self.spellCount:\n spellPic = PhotoImage(file=\"nullspell.gif\")\n spellLabel = Label(bossHelpFrame)\n spellLabel.grid(row=1,column=spell,pady=1,padx=1)\n spellLabel.configure(image=spellPic)\n spellLabel.image=spellPic\n self.spellRoster.append(spellLabel)\n \n def changeWorld(newWorld):\n self.world=newWorld\n if(self.world==\"Darkmoor\"):\n OPTIONS = [\n \"Castle Darkmoor\",\n \"Upper Halls\",\n \"Graveyard\"\n ]\n elif(self.world==\"Khrysalis\"):\n OPTIONS = [\n \"Morganthe's Chamber\"\n ]\n elif(self.world==\"Polaris\"):\n OPTIONS = [\n \"Horizon Hold\"\n ]\n else:\n OPTIONS = [\"BUG\"]\n\n # Reset var and delete all old options for area widget\n self.bossTrackerOptions[1]['menu'].delete(0, END)\n self.bossTrackerOptions[1].setvar(self.bossTrackerOptions[1].cget(\"textvariable\"),value=\"Select Area\")\n\n self.bossTrackerOptions[2]['menu'].delete(0,END)\n self.bossTrackerOptions[2].setvar(self.bossTrackerOptions[2].cget(\"textvariable\"),value=\"Select Boss\")\n # Insert list of new options (tk._setit hooks them up to var)\n new_choices = OPTIONS\n for choice in new_choices:\n #adds new options in our areaa optionMenu with choice as the label, that run V command with V variable\n self.bossTrackerOptions[1]['menu'].add_command(label=choice,command=lambda temp=choice: changeArea(temp))\n def changeArea(newArea):\n print (\"Running changeArea\")\n #V command that sets the seen text of our optionMenu to the choice we selected V\n self.bossTrackerOptions[1].setvar(self.bossTrackerOptions[1].cget(\"textvariable\"),value=newArea)\n self.area = newArea\n #Darkmoor Bosses\n if(self.area==\"Castle Darkmoor\"):\n OPTIONS = [\n \"Howling Chaney\",\n \"Sir Blackwater\",\n \"Observatory Puzzle\"\n ]\n elif(self.area==\"Upper Halls\"):\n OPTIONS = [\n \"Akhtang Wormcrawl\",\n \"Spirit of Darkmoor\",\n \"Shane von Shane\"\n ]\n elif(self.area==\"Graveyard\"):\n OPTIONS = [\n \"Yevgney NightCreeper\",\n \"Shane von Shane(robot)\",\n \"Malistaire the Undying\"\n ]\n else:\n OPTIONS = [\"BUG\"]\n #Khrysalis Bosses\n if(self.area==\"Morganthe's Chamber\"):\n OPTIONS = [\n \"Morganthe (Death)\"\n ]\n\n #Polaris Bosses\n if(self.area==\"Horizon Hold\"):\n OPTIONS = [\n \"Rasputin\"\n ]\n\n \n #Reset var and delete all old options for boss widget\n self.bossTrackerOptions[2]['menu'].delete(0,END)\n self.bossTrackerOptions[2].setvar(self.bossTrackerOptions[2].cget(\"textvariable\"),value=\"Select Boss\")\n #insert list of new options(tk.setit hooks them to var\n new_choices = OPTIONS\n for choice in new_choices:\n #adds new options in our boss optionMenu with choice as the label, that run V command with V variable\n self.bossTrackerOptions[2]['menu'].add_command(label=choice,command=lambda temp=choice: changeBoss(temp)) \n print(self.area)\n\n def changeBoss(newBoss):\n self.boss = newBoss\n print (newBoss)\n #V command that sets the seen text of our optionMenu to the choice we selected V\n self.bossTrackerOptions[2].setvar(self.bossTrackerOptions[2].cget(\"textvariable\"),value=newBoss)\n initBossInfo()\n self.initSpellInfo()\n\n \n \n \n def initBossInfo(): \n def changePic():\n if(self.world==\"Darkmoor\"):\n if(self.area==\"Castle Darkmoor\"):\n if(self.boss==\"Howling Chaney\"):\n bossPic=PhotoImage(file=\"Creature_Howling_Chaney.gif\")\n elif(self.boss==\"Sir Blackwater\"):\n bossPic=PhotoImage(file=\"Creature_Sir_Blackwater.gif\")\n elif(self.boss==\"Observatory Puzzle\"):\n bossPic=PhotoImage(file=\"Observatory_Puzzle.gif\")\n elif(self.area==\"Upper Halls\"):\n if(self.boss==\"Akhtang Wormcrawl\"):\n bossPic=PhotoImage(file=\"Creature_Akhtang_Wormcrawl.gif\")\n elif(self.boss==\"Spirit of Darkmoor\"):\n bossPic=PhotoImage(file=\"Creature_Spirit_of_Darkmoor.gif\")\n elif(self.boss==\"Shane von Shane\"):\n bossPic=PhotoImage(file=\"Creature_Shane_von_Shane(Death).gif\")\n elif(self.area==\"Graveyard\"):\n if(self.boss==\"Yevgney NightCreeper\"):\n bossPic=PhotoImage(file=\"Creature_Yevgeny_NightCreeper.gif\")\n elif(self.boss==\"Shane von Shane(robot)\"):\n bossPic=PhotoImage(file=\"Creature_Shane_von_Shane(robot).GIF\")\n elif(self.boss==\"Malistaire the Undying\"):\n bossPic=PhotoImage(file=\"Creature_Malistaire_the_Undying.GIF\")\n ##Krysalis Bosses\n elif(self.world==\"Khrysalis\"):\n if(self.area==\"Morganthe's Chamber\"):\n if(self.boss==\"Morganthe (Death)\"):\n bossPic=PhotoImage(file=\"Creature_Morganthe(Death).GIF\")\n ##Polaris Bosses\n elif(self.world==\"Polaris\"):\n if(self.area==\"Horizon Hold\"):\n if(self.boss==\"Rasputin\"):\n bossPic=PhotoImage(file=\"Creature_Rasputin.GIF\")\n \n \n bossPictureLabel.configure(image=bossPic)\n bossPictureLabel.image = bossPic\n def changeText():\n if(self.world==\"Darkmoor\"):\n if(self.area==\"Castle Darkmoor\"):\n if(self.boss==\"Howling Chaney\"):\n bossNameLabel.configure(text=\"Howling Chaney\")\n bossCheatLabel.configure(text=\"•If any heal is cast, he uses 'Gnomes' on caster.\")\n elif(self.boss==\"Sir Blackwater\"):\n bossNameLabel.configure(text=\"Sir Blackwater\")\n bossCheatLabel.configure(text=\"•When any blade is cast, disarm is used on caster.\"\\\n \"\\n•Don't weakness him in any way.\"\\\n \"\\n•Cycles last 5 rounds each (Death/Life/Storm).\"\\\n \"\\n•Dont feint during first cycle.\")\n elif(self.boss==\"Observatory Puzzle\"):\n bossNameLabel.configure(text=\"Observatory Puzzle\")\n bossCheatLabel.configure(text=\"•Crimson Lense, Neutral Filter\")\n elif(self.area==\"Upper Halls\"):\n if(self.boss==\"Akhtang Wormcrawl\"):\n bossNameLabel.configure(text=\"Akhtang Wormcrawl\")\n bossCheatLabel.configure(text=\"•When any blade is cast, steal charm is used on recipient\")\n elif(self.boss==\"Spirit of Darkmoor\"):\n bossNameLabel.configure(text=\"Spirit of Darkmoor\")\n bossCheatLabel.configure(text=\"•If trapped, she will Boreas Ifrit (880 Myth) caster.\"\\\n \"\\n•Blades trigger Fire Skeletal Dragon (222+948 Fire dot) on caster.\"\\\n \"\\n•Dont defeat the minions before the boss or they'll be healed.\"\\\n \"\\n•Cycles last 5 rounds each (Myth/Life/Fire)\")\n elif(self.boss==\"Shane von Shane\"):\n bossNameLabel.configure(text=\"Shane von Shane\")\n bossCheatLabel.configure(text=\"•Dont feint/hex/curse him, or he will dark-pact.\"\\\n \"\\n•Hit him every turn or bad things happen.\")\n elif(self.area==\"Graveyard\"):\n if(self.boss==\"Yevgney NightCreeper\"):\n bossNameLabel.configure(text=\"Yevgeny NightCreeper\")\n bossCheatLabel.configure(text=\"•Every time you blade, he will stun caster\"\\\n \"\\n•Uses Ice Weaver (BIG shield) on 5th turn.\")\n elif(self.boss==\"Shane von Shane(robot)\"):\n bossNameLabel.configure(text=\"Shane von Shane(robot)\")\n bossCheatLabel.configure(text=\"•Dont feint/hex/curse him, or he will dark-pact.\"\\\n \"\\n•Hit him every turn of bad things happen.\"\n \"\\n•BEWARE! Can use squall.\")\n elif(self.boss==\"Malistaire the Undying\"):\n bossNameLabel.configure(text=\"Malistaire the Undying\")\n bossCheatLabel.configure(text=\"•Dont feint/hex/curse HIM.\"\\\n \"\\n•NO tower shields.\"\\\n \"\\n•Use DOOM&GLOOM turn he dies\"\\\n \"\\n•Wipes blades and traps(on you) every 4 turns.\")\n elif(self.world==\"Khrysalis\"):\n if(self.area==\"Morganthe's Chamber\"):\n if(self.boss==\"Morganthe (Death)\"):\n bossNameLabel.configure(text=\"Morganthe (Death)\")\n bossCheatLabel.configure(text=\"•Dont die\"\\\n \"\\n•Stack feints and blades on one hitter\")\n elif(self.world==\"Polaris\"):\n if(self.area==\"Horizon Hold\"):\n if(self.boss==\"Rasputin\"):\n bossNameLabel.configure(text=\"Rasputin\")\n bossCheatLabel.configure(text=\"•Kills everyone on 40th turn (unavoidable)\"\\\n \"\\n•Only feint once\"\\\n \"\\n•Only trap if you go first\"\\\n \"\\n•Avoid coming in the fight late\"\\\n \"\\n•Summons minions with 120% resist whenever you blade/trap/heal.\"\\\n \"\\n\\t-Kill these first turn they spawn\"\\\n \"\\n\\nIDEAL TEAM:\"\\\n \"\\n•Minion Clearer (31%Pierce recommended)\"\\\n \"\\n•Healer/Shielder\"\\\n \"\\n•Hitter\"\\\n \"\\n•Buffer\")\n ##Krysalis Bosses\n elif(self.world==\"Khrysalis\"):\n if(self.area==\"Morganthe's Chamber\"):\n if(self.boss==\"Morganthe (Death)\"):\n bossPic=PhotoImage(file=\"Creature_Morganthe(Death).GIF\")\n ##Polaris Bosses\n elif(self.world==\"Polaris\"):\n if(self.area==\"Horizon Hold\"):\n if(self.boss==\"Rasputin\"):\n bossPic=PhotoImage(file=\"Creature_Rasputin.GIF\")\n #Actually RUN All methods that initBossInfo \n changePic()\n changeText()\n \n\n def insertWorldOptionMenu():\n OPTIONS = [\n \"Darkmoor\",\n \"Khrysalis\",\n \"Polaris\"\n ]\n\n worldVar = StringVar(frame)\n worldVar.set(\"Select World\") # initial value\n self.bossTrackerOptionsVar.append(worldVar)\n \n worldOptionMenu = OptionMenu(bossFrame,worldVar,*OPTIONS,command=changeWorld)\n worldOptionMenu.configure(width = optionWidth)\n worldOptionMenu.grid(row=0,column=0,sticky=(N+S+E+W),columnspan=2,pady=10)\n self.bossTrackerOptions.append(worldOptionMenu)\n def insertAreaOptionMenu():\n OPTIONS = [\"Select World First!\"]\n\n areaVar = StringVar(frame)\n areaVar.set(\"Select Area\") # initial value\n self.bossTrackerOptionsVar.append(areaVar)\n \n areaOptionMenu = OptionMenu(bossFrame,areaVar,*OPTIONS,command=changeArea)\n areaOptionMenu.configure(width = optionWidth)\n areaOptionMenu.grid(row=0,column=2,sticky=(N+W),columnspan=2,pady=10)\n self.bossTrackerOptions.append(areaOptionMenu)\n \n def insertBossOptionMenu():\n OPTIONS = [\"Select Area First!\"]\n\n bossVar = StringVar(frame)\n bossVar.set(\"Select Boss\") #Initial value\n self.bossTrackerOptionsVar.append(bossVar)\n\n bossOptionMenu = OptionMenu(bossFrame,bossVar,*OPTIONS,command=changeBoss)\n bossOptionMenu.configure(width = optionWidth)\n bossOptionMenu.grid(row=0,column=4,sticky=(N+E),columnspan=2,pady=10)\n self.bossTrackerOptions.append(bossOptionMenu)\n\n #insert the 3 OptionMenu Widgets\n insertWorldOptionMenu()\n insertAreaOptionMenu()\n insertBossOptionMenu()\n initiateSpells() \n def initUI(self,btFrame,content):\n def openWiki():\n webbrowser.open('http://www.google.com')\n def openStressReleiver():\n webbrowser.open('http://www.kongregate.com/games/FlintShadowrider/supa-awesome-crazy-duck')\n def openDuelist():\n webbrowser.open('https://duelist101.com')\n def openYoutube():\n webbrowser.open('https://youtube.com')\n def openHippo():\n webbrowser.open('http://orig04.deviantart.net/8b10/f/2010/006/3/a/hippo_breathing_fire_by_we1rdwithaone.jpg')\n def openAardvark():\n webbrowser.open(\"http://www.toateanimalele.ro/Salbatice/Aardvark/Aardvark7.jpg\")\n def openHoneyBadger():\n webbrowser.open(\"http://www.bloodsprayer.com/wp-content/uploads/2011/06/honeybadger.jpg\")\n self.master.title(\"Wizard101 Bootstrapper\")\n\n menubar = Menu(self.master)\n self.master.config(menu=menubar)\n\n #Creates a menu called Programs\n progmenu = Menu(menubar, tearoff=0)\n progmenu.add_command(label=\"Wizard Wiki\", command=openWiki)\n progmenu.add_command(label=\"Duelist101\", command=openDuelist)\n progmenu.add_command(label=\"Stressed?\", command=openStressReleiver)\n progmenu.add_command(label=\"Youtube\", command=openYoutube)\n progmenu.add_separator()\n progmenu.add_command(label=\"Exit\", command=content.quit())\n menubar.add_cascade(label=\"Links\", menu=progmenu)\n \n # create more pulldown menus\n editmenu = Menu(menubar, tearoff=0)\n editmenu.add_command(label=\"Hippo\", command=openHippo)\n editmenu.add_command(label=\"Aardvark\", command=openAardvark)\n editmenu.add_command(label=\"Honey Badger\", command=openHoneyBadger)\n menubar.add_cascade(label=\"Cute animals\", menu=editmenu)\n # help menubar\n helpmenu = Menu(menubar, tearoff=0)\n helpmenu.add_command(label=\"About\", command=openHippo)\n menubar.add_cascade(label=\"Help\", menu=helpmenu)\n \n \n\n\n def initBT(self,frame,content,mySchool):\n textLabel=Label(content,text=\"Blade Tracker\",font=((\"Times\", 10, \"bold\")))\n textLabel.grid(row=0,column=1)\n frame.configure(borderwidth=5, relief=\"sunken\", width=400, height=600,padding=(3,3,12,12))\n frame.grid(column=0, row=1, columnspan=3, sticky=(N, S, E, W),padx=10)\n \n schoolbladeLabel = Label(frame)\n schoolbladeLabel.grid(row = 1,column=0,sticky=(N),ipadx=20,ipady=10)\n\n tribladeprimeLabel = Label(frame)\n tribladeprimeLabel.grid(row = 1,column=1,sticky=(N),ipadx=20,ipady=10)\n\n schooltraplabel = Label(frame)\n schooltraplabel.grid(row = 3,column=0,sticky=(N),ipadx=20,ipady=10)\n\n feinttraplabel = Label(frame)\n feinttraplabel.grid(row = 3,column=1,sticky=(N),ipadx=20,ipady=10)\n\n uniquetraplabel = Label(frame)\n uniquetraplabel.grid(row = 5,column=0,sticky=(N),ipadx=20,ipady=10)\n\n tritrapprimeLabel = Label(frame)\n tritrapprimeLabel.grid(row = 5,column=1,sticky=(N),ipadx=20,ipady=10)\n\n \n def changeSchool(school):\n print (school)\n WizTool.schoolType = school\n insertPictures()\n print (WizTool.schoolType)\n self.initSpellInfo()\n #option menu for selecting school\n \n def insertOptionMenu():\n OPTIONS = [\n \"Fire\",\n \"Ice\",\n \"Storm\",\n \"Life\",\n \"Myth\",\n \"Death\",\n \"Balance\"\n ]\n\n var = StringVar(frame)\n var.set(\"Select School\") # initial value\n\n option = OptionMenu(frame, var,*OPTIONS,command=changeSchool)\n option.grid(row=0,column=0,sticky=N,columnspan=2)\n\n #initializing pictures\n def insertPictures():\n \n print (\"inserting pictures\")\n schoolbladepic = PhotoImage(file='ice_wyvern.gif')\n tribladeprimepic = PhotoImage(file='ice_wyvern.gif')\n schooltrappic = PhotoImage(file='ice_wyvern.gif')\n feinttrappic = PhotoImage(file='feinttrap.gif')\n uniquetrappic = PhotoImage(file='nullspell.gif')\n tritrapprimepic = PhotoImage(file='ice_wyvern.gif')\n\n if(self.schoolType==\"Fire\"):\n schoolbladepic = PhotoImage(file='fireblade.gif')\n tribladeprimepic = PhotoImage(file='elemental_blade.gif')\n schooltrappic = PhotoImage(file='firetrap.gif')\n tritrapprimepic = PhotoImage(file='elemental_trap.gif')\n uniquetrappic = PhotoImage(file='fuel.gif')\n elif(self.schoolType==\"Storm\"):\n schoolbladepic = PhotoImage(file='stormblade.gif')\n tribladeprimepic = PhotoImage(file='elemental_blade.gif')\n schooltrappic = PhotoImage(file='stormtrap.gif')\n tritrapprimepic = PhotoImage(file='elemental_trap.gif')\n uniquetrappic = PhotoImage(file='windstorm.gif')\n elif(self.schoolType==\"Ice\"):\n print (\"Should be printing ice pictures\")\n schoolbladepic = PhotoImage(file='iceblade.gif')\n tribladeprimepic = PhotoImage(file='elemental_blade.gif')\n schooltrappic = PhotoImage(file='icetrap.gif')\n tritrapprimepic = PhotoImage(file='elemental_trap.gif')\n elif(self.schoolType==\"Life\"):\n schoolbladepic = PhotoImage(file='lifeblade.gif')\n tribladeprimepic = PhotoImage(file='spirit_blade.gif')\n schooltrappic = PhotoImage(file='lifetrap.gif')\n tritrapprimepic = PhotoImage(file='spirit_trap.gif')\n elif(self.schoolType==\"Myth\"):\n schoolbladepic = PhotoImage(file='mythblade.gif')\n tribladeprimepic = PhotoImage(file='spirit_blade.gif')\n schooltrappic = PhotoImage(file='mythtrap.gif')\n tritrapprimepic = PhotoImage(file='spirit_trap.gif')\n elif(self.schoolType==\"Death\"):\n schoolbladepic = PhotoImage(file='deathblade.gif')\n tribladeprimepic = PhotoImage(file='spirit_blade.gif')\n schooltrappic = PhotoImage(file='deathtrap.gif')\n tritrapprimepic = PhotoImage(file='spirit_trap.gif')\n uniquetrappic = PhotoImage(file='curse.gif')\n elif(self.schoolType==\"Balance\"):\n schoolbladepic = PhotoImage(file='balanceblade.gif')\n tribladeprimepic = PhotoImage(file='bladestorm.gif')\n schooltrappic = PhotoImage(file='hextrap.gif')\n tritrapprimepic = PhotoImage(file='elemental_trap.gif')\n uniquetrappic = PhotoImage(file='elemental_blade.gif')\n \n \n \n #sets in first row of pictures\n schoolbladeLabel.configure(image=schoolbladepic)\n schoolbladeLabel.image = schoolbladepic\n \n tribladeprimeLabel.configure(image=tribladeprimepic)\n tribladeprimeLabel.image = tribladeprimepic\n \n\n schooltraplabel.configure(image=schooltrappic)\n schooltraplabel.image = schooltrappic\n \n\n feinttraplabel.configure(image=feinttrappic)\n feinttraplabel.image = feinttrappic\n\n uniquetraplabel.configure(image=uniquetrappic) \n uniquetraplabel.image = uniquetrappic\n\n tritrapprimeLabel.configure(image=tritrapprimepic)\n tritrapprimeLabel.image = tritrapprimepic\n \n\n #sets in first row of checkboxes\n def insertCheckbuttons():\n #This wrapper function allows for the command of a Checkbutton to call the updateChecks method without it having to be declared before the class\n def wrapper():\n updateChecks()\n #This class is inside of the insertCheckbuttons() method because that is the only place it is used\n #Also making it a completely different class would have conflicting scope issues. \n class Checkbar(Frame):\n #makes a frame and puts x Checkbutton widgets inside horizontally\n def __init__(self, parent=None, picks=[], side=LEFT, anchor=W):\n Frame.__init__(self, parent)\n self.vars = []\n self.cbs = []\n for pick in picks:\n yesno = IntVar()\n cb = Checkbutton(self, text=pick, variable=yesno,command=wrapper) #calls the wrapper function whenever a Checkbutton is hit\n cb.pack(side=side, anchor=anchor, expand=YES)\n self.vars.append(yesno)\n self.cbs.append(cb)\n def disable_cb(self):\n for cb in self.cbs:\n cb.deselect()\n #returns gross pointer values as an object (still unreadable) \n def state(self):\n return map((lambda var: var.get()), self.vars)\n\n\n\n schoolBladeCheck = Checkbar(frame, ['N', 'E', 'Tc', 'B'])\n schoolBladeCheck.config(relief=GROOVE, bd=2)\n schoolBladeCheck.grid(row=2,column = 0,sticky=N)\n\n triSchoolBladeCheck = Checkbar(frame, ['N', 'E', 'Tc', 'B'])\n triSchoolBladeCheck.config(relief=GROOVE, bd=2)\n triSchoolBladeCheck.grid(row=2,column = 1,sticky=N)\n\n schoolTrapCheck = Checkbar(frame, ['N','E','Tc','B'])\n schoolTrapCheck.config(relief=GROOVE,bd=2)\n schoolTrapCheck.grid(row=4,column=0,sticky=N)\n\n FeintTrapCheck = Checkbar(frame, ['N','E','Tc','B'])\n FeintTrapCheck.config(relief=GROOVE,bd=2)\n FeintTrapCheck.grid(row=4,column=1,sticky=N)\n\n UniqueSpellCheck = Checkbar(frame, ['N','E','Tc','B'])\n UniqueSpellCheck.config(relief=GROOVE,bd=2)\n UniqueSpellCheck.grid(row=6,column=0,sticky=N)\n \n triSchoolTrapCheck = Checkbar(frame, ['N','E','Tc','B'])\n triSchoolTrapCheck.config(relief=GROOVE,bd=2)\n triSchoolTrapCheck.grid(row=6,column=1,sticky=N)\n #updates the array of 1's/zero's\n def updateChecks():\n #list turns our gushy object into a nice readable array of on's and off's\n bladeCheck[0][0]=list(schoolBladeCheck.state())\n bladeCheck[0][1]=list(triSchoolBladeCheck.state())\n bladeCheck[1][0]=list(schoolTrapCheck.state())\n bladeCheck[1][1]=list(FeintTrapCheck.state())\n bladeCheck[2][0]=list(UniqueSpellCheck.state())\n bladeCheck[2][1]=list(triSchoolTrapCheck.state())\n #prints out our array to console so we can see that it is in-fact changine\n pprint.pprint(bladeCheck)\n def removeChecks():\n print(\"Reseting all Checkboxes\")\n schoolBladeCheck.disable_cb()\n triSchoolBladeCheck.disable_cb()\n schoolTrapCheck.disable_cb()\n FeintTrapCheck.disable_cb()\n UniqueSpellCheck.disable_cb()\n triSchoolTrapCheck.disable_cb()\n print(\"Resetting table values\")\n updateChecks()\n \n #button that turns all the checkboxes off\n offButton = Button(frame,text = \"Reset\",command=removeChecks)\n offButton.grid(row=7,column=0,sticky=N,columnspan=2,pady=10)\n\n insertOptionMenu()\n insertPictures()\n insertCheckbuttons()\n def initSpellInfo(self):\n spellPic = PhotoImage(file='nullspell.gif')\n for spell in self.spellRoster:\n spell.configure(image=spellPic)\n spell.image = spellPic\n if (self.world==\"Darkmoor\"):\n if(self.area==\"Castle Darkmoor\"):\n if(self.boss==\"Howling Chaney\"):\n self.initDefaultSpells()\n elif(self.boss==\"Sir Blackwater\"):\n self.initDefaultSpells()\n elif(self.area==\"Upper Halls\"):\n if(self.boss==\"Akhtang Wormcrawl\"):\n self.initDefaultSpells()\n elif(self.boss==\"Spirit of Darkmoor\"):\n self.initDefaultSpells()\n elif(self.boss==\"Shane von Shane\"):\n self.initDefaultSpells()\n elif(self.area==\"Graveyard\"):\n if(self.boss==\"Yevgney NightCreeper\"):\n self.initDefaultSpells()\n elif(self.boss==\"Shane von Shane(robot)\"):\n self.initShaneVonShaneRSpells()\n elif(self.boss==\"Malistaire the Undying\"):\n self.initMalistaireSpells()\n elif(self.world==\"Khrysalis\"):\n if(self.area==\"Morganthe's Chamber\"):\n if(self.boss==\"Morganthe (Death)\"):\n self.initMorgantheSpells()\n elif(self.world==\"Polaris\"):\n if(self.area==\"Horizon Hold\"):\n if(self.boss==\"Rasputin\"):\n self.initRasputinSpells()\n\n def initDefaultSpells(self):\n if(self.schoolType==\"Fire\"):\n spellPic1 = PhotoImage(file=\"fireblade.gif\"),\n spellPic2 = PhotoImage(file=\"fireblade(e).gif\"),\n spellPic3 = PhotoImage(file=\"raging bull.gif\"),\n spellPic4 = PhotoImage(file=\"furnace.gif\"),\n spellPic5 = PhotoImage(file=\"colossal.gif\"),\n spellPic6 = PhotoImage(file=\"feinttrap.gif\"),\n spellPic7 = PhotoImage(file=\"feint(e).gif\")\n spellPic8 = PhotoImage(file='nullspell.gif')\n spellPic9 = PhotoImage(file='nullspell.gif')\n spellPic10 = PhotoImage(file='nullspell.gif')\n fireSpells = [\n spellPic1,\n spellPic2,\n spellPic3,\n spellPic4,\n spellPic5,\n spellPic6,\n spellPic7,\n spellPic8,\n spellPic9,\n spellPic10\n ]\n counter=0\n for spell in self.spellRoster:\n print(counter)\n spell.configure(image=fireSpells[counter])\n spell.image = fireSpells[counter]\n counter+=1\n elif(self.schoolType==\"Ice\"):\n spellPic1 = PhotoImage(file=\"iceblade.gif\"),\n spellPic2 = PhotoImage(file=\"iceblade(e).gif\"),\n spellPic3 = PhotoImage(file=\"abominable weaver.gif\"),\n spellPic4 = PhotoImage(file=\"sleet storm.gif\"),\n spellPic5 = PhotoImage(file=\"colossal.gif\"),\n spellPic6 = PhotoImage(file=\"feinttrap.gif\"),\n spellPic7 = PhotoImage(file=\"feint(e).gif\")\n spellPic8 = PhotoImage(file='nullspell.gif')\n spellPic9 = PhotoImage(file='nullspell.gif')\n spellPic10 = PhotoImage(file='nullspell.gif')\n iceSpells = [\n spellPic1,\n spellPic2,\n spellPic3,\n spellPic4,\n spellPic5,\n spellPic6,\n spellPic7,\n spellPic8,\n spellPic9,\n spellPic10\n ]\n counter=0\n for spell in self.spellRoster:\n print(counter)\n spell.configure(image=iceSpells[counter])\n spell.image = iceSpells[counter]\n counter+=1 \n elif(self.schoolType==\"Storm\"):\n spellPic1 = PhotoImage(file=\"stormblade.gif\"),\n spellPic2 = PhotoImage(file=\"stormblade(e).gif\"),\n spellPic3 = PhotoImage(file=\"glowbug squall.gif\"),\n spellPic4 = PhotoImage(file=\"galvanic field.gif\"),\n spellPic5 = PhotoImage(file=\"colossal.gif\"),\n spellPic6 = PhotoImage(file=\"feinttrap.gif\"),\n spellPic7 = PhotoImage(file=\"feint(e).gif\")\n spellPic8 = PhotoImage(file='nullspell.gif')\n spellPic9 = PhotoImage(file='nullspell.gif')\n spellPic10 = PhotoImage(file='nullspell.gif')\n iceSpells = [\n spellPic1,\n spellPic2,\n spellPic3,\n spellPic4,\n spellPic5,\n spellPic6,\n spellPic7,\n spellPic8,\n spellPic9,\n spellPic10\n ]\n counter=0\n for spell in self.spellRoster:\n print(counter)\n spell.configure(image=iceSpells[counter])\n spell.image = iceSpells[counter]\n counter+=1 \n elif(self.schoolType==\"Myth\"):\n spellPic1 = PhotoImage(file=\"mythblade.gif\"),\n spellPic2 = PhotoImage(file=\"mythblade(e).gif\"),\n spellPic3 = PhotoImage(file=\"mystic colossus.gif\"),\n spellPic4 = PhotoImage(file=\"reliquary.gif\"),\n spellPic5 = PhotoImage(file=\"colossal.gif\"),\n spellPic6 = PhotoImage(file=\"feinttrap.gif\"),\n spellPic7 = PhotoImage(file=\"feint(e).gif\")\n spellPic8 = PhotoImage(file='nullspell.gif')\n spellPic9 = PhotoImage(file='nullspell.gif')\n spellPic10 = PhotoImage(file='nullspell.gif')\n mythSpells = [\n spellPic1,\n spellPic2,\n spellPic3,\n spellPic4,\n spellPic5,\n spellPic6,\n spellPic7,\n spellPic8,\n spellPic9,\n spellPic10\n ]\n counter=0\n for spell in self.spellRoster:\n print(counter)\n spell.configure(image=mythSpells[counter])\n spell.image = mythSpells[counter]\n counter+=1\n elif(self.schoolType==\"Death\"):\n spellPic1 = PhotoImage(file=\"deathblade.gif\"),\n spellPic2 = PhotoImage(file=\"deathblade(e).gif\"),\n spellPic3 = PhotoImage(file=\"winged sorrow.gif\"),\n spellPic4 = PhotoImage(file=\"virulence.gif\"),\n spellPic5 = PhotoImage(file=\"colossal.gif\"),\n spellPic6 = PhotoImage(file=\"feinttrap.gif\"),\n spellPic7 = PhotoImage(file=\"feint(e).gif\")\n spellPic8 = PhotoImage(file='nullspell.gif')\n spellPic9 = PhotoImage(file='nullspell.gif')\n spellPic10 = PhotoImage(file='nullspell.gif')\n deathSpells = [\n spellPic1,\n spellPic2,\n spellPic3,\n spellPic4,\n spellPic5,\n spellPic6,\n spellPic7,\n spellPic8,\n spellPic9,\n spellPic10\n ]\n counter=0\n for spell in self.spellRoster:\n print(counter)\n spell.configure(image=deathSpells[counter])\n spell.image = deathSpells[counter]\n counter+=1\n elif(self.schoolType==\"Life\"):\n spellPic1 = PhotoImage(file=\"lifeblade.gif\"),\n spellPic2 = PhotoImage(file=\"lifeblade(e).gif\"),\n spellPic3 = PhotoImage(file=\"hungry caterpillar.gif\"),\n spellPic4 = PhotoImage(file=\"vengeance.gif\"),\n spellPic5 = PhotoImage(file=\"colossal.gif\"),\n spellPic6 = PhotoImage(file=\"feinttrap.gif\"),\n spellPic7 = PhotoImage(file=\"feint(e).gif\")\n spellPic8 = PhotoImage(file='nullspell.gif')\n spellPic9 = PhotoImage(file='nullspell.gif')\n spellPic10 = PhotoImage(file='nullspell.gif')\n lifeSpells = [\n spellPic1,\n spellPic2,\n spellPic3,\n spellPic4,\n spellPic5,\n spellPic6,\n spellPic7,\n spellPic8,\n spellPic9,\n spellPic10\n ]\n counter=0\n for spell in self.spellRoster:\n print(counter)\n spell.configure(image=lifeSpells[counter])\n spell.image = lifeSpells[counter]\n counter+=1\n elif(self.schoolType==\"Balance\"):\n spellPic1 = PhotoImage(file=\"balanceblade.gif\"),\n spellPic2 = PhotoImage(file=\"balanceblade(e).gif\"),\n spellPic3 = PhotoImage(file=\"nested fury.gif\"),\n spellPic4 = PhotoImage(file=\"chastisement.gif\"),\n spellPic5 = PhotoImage(file=\"colossal.gif\"),\n spellPic6 = PhotoImage(file=\"feinttrap.gif\"),\n spellPic7 = PhotoImage(file=\"feint(e).gif\")\n spellPic8 = PhotoImage(file='nullspell.gif')\n spellPic9 = PhotoImage(file='nullspell.gif')\n spellPic10 = PhotoImage(file='nullspell.gif')\n lifeSpells = [\n spellPic1,\n spellPic2,\n spellPic3,\n spellPic4,\n spellPic5,\n spellPic6,\n spellPic7,\n spellPic8,\n spellPic9,\n spellPic10\n ]\n counter=0\n for spell in self.spellRoster:\n print(counter)\n spell.configure(image=lifeSpells[counter])\n spell.image = lifeSpells[counter]\n counter+=1\n\n def initMalistaireSpells(self):\n if(self.schoolType==\"Fire\"):\n spellPic1 = PhotoImage(file=\"fireblade.gif\"),\n spellPic2 = PhotoImage(file=\"fireblade(e).gif\"),\n spellPic3 = PhotoImage(file=\"raging bull.gif\"),\n spellPic4 = PhotoImage(file=\"furnace.gif\"),\n spellPic5 = PhotoImage(file=\"colossal.gif\"),\n spellPic6 = PhotoImage(file=\"backdraft(e).gif\"),\n spellPic7 = PhotoImage(file=\"fuel.gif\")\n spellPic8 = PhotoImage(file='fuel(e).gif')\n spellPic9 = PhotoImage(file='firetrap.gif')\n spellPic10 = PhotoImage(file='firetrap(e).gif')\n fireSpells = [\n spellPic1,\n spellPic2,\n spellPic3,\n spellPic4,\n spellPic5,\n spellPic6,\n spellPic7,\n spellPic8,\n spellPic9,\n spellPic10\n ]\n counter=0\n for spell in self.spellRoster:\n print(counter)\n spell.configure(image=fireSpells[counter])\n spell.image = fireSpells[counter]\n counter+=1\n elif(self.schoolType==\"Ice\"):\n spellPic1 = PhotoImage(file=\"elemental_blade.gif\"),\n spellPic2 = PhotoImage(file=\"elemental_blade(e).gif\"),\n spellPic3 = PhotoImage(file=\"elemental_trap.gif\"),\n spellPic4 = PhotoImage(file=\"elemental_trap(e).gif\"),\n spellPic5 = PhotoImage(file=\"shadow sentinel.gif\"),\n spellPic6 = PhotoImage(file=\"legend shield.gif\"),\n spellPic7 = PhotoImage(file=\"fortify.gif\")\n spellPic8 = PhotoImage(file='storm convert(tc).gif')\n spellPic9 = PhotoImage(file='spirit_trap.gif')\n spellPic10 = PhotoImage(file='spirit_trap(e).gif')\n iceSpells = [\n spellPic1,\n spellPic2,\n spellPic3,\n spellPic4,\n spellPic5,\n spellPic6,\n spellPic7,\n spellPic8,\n spellPic9,\n spellPic10\n ]\n counter=0\n for spell in self.spellRoster:\n print(counter)\n spell.configure(image=iceSpells[counter])\n spell.image = iceSpells[counter]\n counter+=1 \n elif(self.schoolType==\"Storm\"):\n spellPic1 = PhotoImage(file=\"stormblade.gif\"),\n spellPic2 = PhotoImage(file=\"stormblade(e).gif\"),\n spellPic3 = PhotoImage(file=\"glowbug squall.gif\"),\n spellPic4 = PhotoImage(file=\"supercharge.gif\"),\n spellPic5 = PhotoImage(file=\"colossal.gif\"),\n spellPic6 = PhotoImage(file=\"windstorm.gif\"),\n spellPic7 = PhotoImage(file=\"windstorm(e).gif\")\n spellPic8 = PhotoImage(file='stormtrap.gif')\n spellPic9 = PhotoImage(file='stormtrap(e).gif')\n spellPic10 = PhotoImage(file='galvanic field.gif')\n iceSpells = [\n spellPic1,\n spellPic2,\n spellPic3,\n spellPic4,\n spellPic5,\n spellPic6,\n spellPic7,\n spellPic8,\n spellPic9,\n spellPic10\n ]\n counter=0\n for spell in self.spellRoster:\n print(counter)\n spell.configure(image=iceSpells[counter])\n spell.image = iceSpells[counter]\n counter+=1 \n elif(self.schoolType==\"Myth\"):\n spellPic1 = PhotoImage(file=\"mythblade.gif\"),\n spellPic2 = PhotoImage(file=\"mythblade(e).gif\"),\n spellPic3 = PhotoImage(file=\"mystic colossus.gif\"),\n spellPic4 = PhotoImage(file=\"reliquary.gif\"),\n spellPic5 = PhotoImage(file=\"colossal.gif\"),\n spellPic6 = PhotoImage(file=\"mythtrap.gif\"),\n spellPic7 = PhotoImage(file=\"mythtrap(e).gif\")\n spellPic8 = PhotoImage(file='shatter.gif')\n spellPic9 = PhotoImage(file='spirit_trap.gif')\n spellPic10 = PhotoImage(file='spirit_trap(e).gif')\n mythSpells = [\n spellPic1,\n spellPic2,\n spellPic3,\n spellPic4,\n spellPic5,\n spellPic6,\n spellPic7,\n spellPic8,\n spellPic9,\n spellPic10\n ]\n counter=0\n for spell in self.spellRoster:\n print(counter)\n spell.configure(image=mythSpells[counter])\n spell.image = mythSpells[counter]\n counter+=1\n elif(self.schoolType==\"Death\"):\n spellPic1 = PhotoImage(file=\"sacrifice.gif\"),\n spellPic2 = PhotoImage(file=\"spirit_trap.gif\"),\n spellPic3 = PhotoImage(file=\"spirit_trap(e).gif\"),\n spellPic4 = PhotoImage(file=\"doom and gloom(tc).gif\"),\n spellPic5 = PhotoImage(file=\"virulent plague.gif\"),\n spellPic6 = PhotoImage(file=\"feinttrap.gif\"),\n spellPic7 = PhotoImage(file=\"feint(e).gif\")\n spellPic8 = PhotoImage(file='nullspell.gif')\n spellPic9 = PhotoImage(file='nullspell.gif')\n spellPic10 = PhotoImage(file='nullspell.gif')\n deathSpells = [\n spellPic1,\n spellPic2,\n spellPic3,\n spellPic4,\n spellPic5,\n spellPic6,\n spellPic7,\n spellPic8,\n spellPic9,\n spellPic10\n ]\n counter=0\n for spell in self.spellRoster:\n print(counter)\n spell.configure(image=deathSpells[counter])\n spell.image = deathSpells[counter]\n counter+=1\n elif(self.schoolType==\"Life\"):\n spellPic1 = PhotoImage(file=\"rebirth.gif\"),\n spellPic2 = PhotoImage(file=\"primordial.gif\"),\n spellPic3 = PhotoImage(file=\"pixie.gif\"),\n spellPic4 = PhotoImage(file=\"cycle of life.gif\"),\n spellPic5 = PhotoImage(file=\"shadow seraph.gif\"),\n spellPic6 = PhotoImage(file=\"legend shield.gif\"),\n spellPic7 = PhotoImage(file=\"unicorn.gif\")\n spellPic8 = PhotoImage(file='sanctuary.gif')\n spellPic9 = PhotoImage(file='sanctuary.gif')\n spellPic10 = PhotoImage(file='nullspell.gif')\n lifeSpells = [\n spellPic1,\n spellPic2,\n spellPic3,\n spellPic4,\n spellPic5,\n spellPic6,\n spellPic7,\n spellPic8,\n spellPic9,\n spellPic10\n ]\n counter=0\n for spell in self.spellRoster:\n print(counter)\n spell.configure(image=lifeSpells[counter])\n spell.image = lifeSpells[counter]\n counter+=1\n elif(self.schoolType==\"Balance\"):\n spellPic1 = PhotoImage(file=\"reshuffle.gif\"),\n spellPic2 = PhotoImage(file=\"elemental_blade.gif\"),\n spellPic3 = PhotoImage(file=\"elemental_blade(e).gif\"),\n spellPic4 = PhotoImage(file=\"elemental_trap.gif\"),\n spellPic5 = PhotoImage(file=\"elemental_trap(e).gif\"),\n spellPic6 = PhotoImage(file=\"legend shield.gif\"),\n spellPic7 = PhotoImage(file=\"doom and gloom(tc).gif\")\n spellPic8 = PhotoImage(file='storm convert(tc).gif')\n spellPic9 = PhotoImage(file='spirit_trap.gif')\n spellPic10 = PhotoImage(file='spirit_trap(e).gif')\n lifeSpells = [\n spellPic1,\n spellPic2,\n spellPic3,\n spellPic4,\n spellPic5,\n spellPic6,\n spellPic7,\n spellPic8,\n spellPic9,\n spellPic10\n ]\n counter=0\n for spell in self.spellRoster:\n print(counter)\n spell.configure(image=lifeSpells[counter])\n spell.image = lifeSpells[counter]\n counter+=1\n\n def initShaneVonShaneRSpells(self):\n if(self.schoolType==\"Fire\"):\n spellPic1 = PhotoImage(file=\"elemental_blade(tc).gif\"),\n spellPic2 = PhotoImage(file=\"elemental_blade(e).gif\"),\n spellPic3 = PhotoImage(file=\"stormblade(tc).gif\"),\n spellPic4 = PhotoImage(file=\"storm convert(tc).gif\"),\n spellPic5 = PhotoImage(file=\"stormtrap(tc).gif\"),\n spellPic6 = PhotoImage(file=\"dark pact(tc).gif\"),\n spellPic7 = PhotoImage(file=\"dissipate(tc).gif\")\n spellPic8 = PhotoImage(file='nullspell.gif')\n spellPic9 = PhotoImage(file='nullspell.gif')\n spellPic10 = PhotoImage(file='nullspell.gif')\n fireSpells = [\n spellPic1,\n spellPic2,\n spellPic3,\n spellPic4,\n spellPic5,\n spellPic6,\n spellPic7,\n spellPic8,\n spellPic9,\n spellPic10\n ]\n counter=0\n for spell in self.spellRoster:\n print(counter)\n spell.configure(image=fireSpells[counter])\n spell.image = fireSpells[counter]\n counter+=1\n elif(self.schoolType==\"Ice\"):\n spellPic1 = PhotoImage(file=\"elemental_blade(tc).gif\"),\n spellPic2 = PhotoImage(file=\"elemental_blade(e).gif\"),\n spellPic3 = PhotoImage(file=\"dissipate(tc).gif\"),\n spellPic4 = PhotoImage(file=\"elemental_trap(e).gif\"),\n spellPic5 = PhotoImage(file=\"shadow sentinel.gif\"),\n spellPic6 = PhotoImage(file=\"legend shield.gif\"),\n spellPic7 = PhotoImage(file=\"fortify.gif\")\n spellPic8 = PhotoImage(file='storm convert(tc).gif')\n spellPic9 = PhotoImage(file='stormblade(tc).gif')\n spellPic10 = PhotoImage(file='dark pact(tc).gif')\n iceSpells = [\n spellPic1,\n spellPic2,\n spellPic3,\n spellPic4,\n spellPic5,\n spellPic6,\n spellPic7,\n spellPic8,\n spellPic9,\n spellPic10\n ]\n counter=0\n for spell in self.spellRoster:\n print(counter)\n spell.configure(image=iceSpells[counter])\n spell.image = iceSpells[counter]\n counter+=1\n elif(self.schoolType==\"Storm\"):\n spellPic1 = PhotoImage(file=\"steal charm(tc).gif\"),\n spellPic2 = PhotoImage(file=\"stormblade.gif\"),\n spellPic3 = PhotoImage(file=\"stormblade(e).gif\"),\n spellPic4 = PhotoImage(file=\"glowbug squall.gif\"),\n spellPic5 = PhotoImage(file=\"colossal.gif\"),\n spellPic6 = PhotoImage(file=\"mass storm prism.gif\"),\n spellPic7 = PhotoImage(file=\"elemental_blade.gif\")\n spellPic8 = PhotoImage(file='elemental_blade(e).gif')\n spellPic9 = PhotoImage(file='stormtrap(e).gif')\n spellPic10 = PhotoImage(file='galvanic field.gif')\n iceSpells = [\n spellPic1,\n spellPic2,\n spellPic3,\n spellPic4,\n spellPic5,\n spellPic6,\n spellPic7,\n spellPic8,\n spellPic9,\n spellPic10\n ]\n counter=0\n for spell in self.spellRoster:\n print(counter)\n spell.configure(image=iceSpells[counter])\n spell.image = iceSpells[counter]\n counter+=1\n elif(self.schoolType==\"Myth\"):\n spellPic1 = PhotoImage(file=\"stormblade(tc).gif\"),\n spellPic2 = PhotoImage(file=\"spirit_trap.gif\"),\n spellPic3 = PhotoImage(file=\"spirit_trap(e).gif\"),\n spellPic4 = PhotoImage(file=\"shatter.gif\"),\n spellPic5 = PhotoImage(file=\"elemental_blade(tc).gif\"),\n spellPic6 = PhotoImage(file=\"dark pact(tc).gif\"),\n spellPic7 = PhotoImage(file=\"nullspell.gif\")\n spellPic8 = PhotoImage(file='nullspell.gif')\n spellPic9 = PhotoImage(file='nullspell.gif')\n spellPic10 = PhotoImage(file='nullspell.gif')\n mythSpells = [\n spellPic1,\n spellPic2,\n spellPic3,\n spellPic4,\n spellPic5,\n spellPic6,\n spellPic7,\n spellPic8,\n spellPic9,\n spellPic10\n ]\n counter=0\n for spell in self.spellRoster:\n print(counter)\n spell.configure(image=mythSpells[counter])\n spell.image = mythSpells[counter]\n counter+=1\n elif(self.schoolType==\"Death\"):\n spellPic1 = PhotoImage(file=\"dark pact.gif\"),\n spellPic2 = PhotoImage(file=\"dark pact(e).gif\"),\n spellPic3 = PhotoImage(file=\"dark pact(tc).gif\"),\n spellPic4 = PhotoImage(file=\"spirit_trap.gif\"),\n spellPic5 = PhotoImage(file=\"spirit_trap(e).gif\"),\n spellPic6 = PhotoImage(file=\"stormblade(tc).gif\"),\n spellPic7 = PhotoImage(file=\"storm convert(tc).gif\")\n spellPic8 = PhotoImage(file='nullspell.gif')\n spellPic9 = PhotoImage(file='nullspell.gif')\n spellPic10 = PhotoImage(file='nullspell.gif')\n deathSpells = [\n spellPic1,\n spellPic2,\n spellPic3,\n spellPic4,\n spellPic5,\n spellPic6,\n spellPic7,\n spellPic8,\n spellPic9,\n spellPic10\n ]\n counter=0\n for spell in self.spellRoster:\n print(counter)\n spell.configure(image=deathSpells[counter])\n spell.image = deathSpells[counter]\n counter+=1\n elif(self.schoolType==\"Life\"):\n spellPic1 = PhotoImage(file=\"rebirth.gif\"),\n spellPic2 = PhotoImage(file=\"primordial.gif\"),\n spellPic3 = PhotoImage(file=\"pixie.gif\"),\n spellPic4 = PhotoImage(file=\"cycle of life.gif\"),\n spellPic5 = PhotoImage(file=\"dark pact(tc).gif\"),\n spellPic6 = PhotoImage(file=\"legend shield.gif\"),\n spellPic7 = PhotoImage(file=\"unicorn.gif\")\n spellPic8 = PhotoImage(file='stormblade(tc).gif')\n spellPic9 = PhotoImage(file='storm convert(tc).gif')\n spellPic10 = PhotoImage(file='elemental_blade(tc).gif')\n lifeSpells = [\n spellPic1,\n spellPic2,\n spellPic3,\n spellPic4,\n spellPic5,\n spellPic6,\n spellPic7,\n spellPic8,\n spellPic9,\n spellPic10\n ]\n counter=0\n for spell in self.spellRoster:\n print(counter)\n spell.configure(image=lifeSpells[counter])\n spell.image = lifeSpells[counter]\n counter+=1\n elif(self.schoolType==\"Balance\"):\n spellPic1 = PhotoImage(file=\"reshuffle.gif\"),\n spellPic2 = PhotoImage(file=\"elemental_blade.gif\"),\n spellPic3 = PhotoImage(file=\"elemental_blade(e).gif\"),\n spellPic4 = PhotoImage(file=\"elemental_blade(tc).gif\"),\n spellPic5 = PhotoImage(file=\"stormblade(tc).gif\"),\n spellPic6 = PhotoImage(file=\"legend shield.gif\"),\n spellPic7 = PhotoImage(file=\"balanceblade(e).gif\")\n spellPic8 = PhotoImage(file='storm convert(tc).gif')\n spellPic9 = PhotoImage(file='spirit_trap.gif')\n spellPic10 = PhotoImage(file='spirit_trap(e).gif')\n lifeSpells = [\n spellPic1,\n spellPic2,\n spellPic3,\n spellPic4,\n spellPic5,\n spellPic6,\n spellPic7,\n spellPic8,\n spellPic9,\n spellPic10\n ]\n counter=0\n for spell in self.spellRoster:\n print(counter)\n spell.configure(image=lifeSpells[counter])\n spell.image = lifeSpells[counter]\n counter+=1\n\n def initMorgantheSpells(self):\n if(self.schoolType==\"Fire\"):\n spellPic1 = PhotoImage(file=\"fireblade.gif\"),\n spellPic2 = PhotoImage(file=\"fireblade(e).gif\"),\n spellPic3 = PhotoImage(file=\"fireblade(tc).gif\"),\n spellPic4 = PhotoImage(file=\"furnace.gif\"),\n spellPic5 = PhotoImage(file=\"raging bull.gif\"),\n spellPic6 = PhotoImage(file=\"colossal.gif\"),\n spellPic7 = PhotoImage(file=\"elemental_blade.gif\")\n spellPic8 = PhotoImage(file='elemental_blade(e).gif')\n spellPic9 = PhotoImage(file='elemental_blade(tc).gif')\n spellPic10 = PhotoImage(file='nullspell.gif')\n fireSpells = [\n spellPic1,\n spellPic2,\n spellPic3,\n spellPic4,\n spellPic5,\n spellPic6,\n spellPic7,\n spellPic8,\n spellPic9,\n spellPic10\n ]\n counter=0\n for spell in self.spellRoster:\n print(counter)\n spell.configure(image=fireSpells[counter])\n spell.image = fireSpells[counter]\n counter+=1\n elif(self.schoolType==\"Ice\"):\n spellPic1 = PhotoImage(file=\"elemental_blade.gif\"),\n spellPic2 = PhotoImage(file=\"elemental_blade(e).gif\"),\n spellPic3 = PhotoImage(file=\"elemental_blade(tc).gif\"),\n spellPic4 = PhotoImage(file=\"feinttrap.gif\"),\n spellPic5 = PhotoImage(file=\"feint(e).gif\"),\n spellPic6 = PhotoImage(file=\"shadow sentinel.gif\"),\n spellPic7 = PhotoImage(file=\"nullspell.gif\")\n spellPic8 = PhotoImage(file='nullspell.gif')\n spellPic9 = PhotoImage(file='nullspell.gif')\n spellPic10 = PhotoImage(file='nullspell.gif')\n iceSpells = [\n spellPic1,\n spellPic2,\n spellPic3,\n spellPic4,\n spellPic5,\n spellPic6,\n spellPic7,\n spellPic8,\n spellPic9,\n spellPic10\n ]\n counter=0\n for spell in self.spellRoster:\n print(counter)\n spell.configure(image=iceSpells[counter])\n spell.image = iceSpells[counter]\n counter+=1\n elif(self.schoolType==\"Storm\"):\n spellPic1 = PhotoImage(file=\"stormblade.gif\"),\n spellPic2 = PhotoImage(file=\"stormblade(e).gif\"),\n spellPic3 = PhotoImage(file=\"stormblade(tc).gif\"),\n spellPic4 = PhotoImage(file=\"galvanic field.gif\"),\n spellPic5 = PhotoImage(file=\"glowbug squall.gif\"),\n spellPic6 = PhotoImage(file=\"colossal.gif\"),\n spellPic7 = PhotoImage(file=\"supercharge.gif\")\n spellPic8 = PhotoImage(file='elemental_blade.gif')\n spellPic9 = PhotoImage(file='elemental_blade(e).gif')\n spellPic10 = PhotoImage(file='elemental_blade(tc).gif')\n iceSpells = [\n spellPic1,\n spellPic2,\n spellPic3,\n spellPic4,\n spellPic5,\n spellPic6,\n spellPic7,\n spellPic8,\n spellPic9,\n spellPic10\n ]\n counter=0\n for spell in self.spellRoster:\n print(counter)\n spell.configure(image=iceSpells[counter])\n spell.image = iceSpells[counter]\n counter+=1\n elif(self.schoolType==\"Myth\"):\n spellPic1 = PhotoImage(file=\"mythblade.gif\"),\n spellPic2 = PhotoImage(file=\"mythblade(e).gif\"),\n spellPic3 = PhotoImage(file=\"mythblade(tc).gif\"),\n spellPic4 = PhotoImage(file=\"mystic colossus.gif\"),\n spellPic5 = PhotoImage(file=\"reliquary.gif\"),\n spellPic6 = PhotoImage(file=\"colossal.gif\"),\n spellPic7 = PhotoImage(file=\"spirit_blade.gif\")\n spellPic8 = PhotoImage(file='spirit_blade(e).gif')\n spellPic9 = PhotoImage(file='spirit_blade(tc).gif')\n spellPic10 = PhotoImage(file='nullspell.gif')\n mythSpells = [\n spellPic1,\n spellPic2,\n spellPic3,\n spellPic4,\n spellPic5,\n spellPic6,\n spellPic7,\n spellPic8,\n spellPic9,\n spellPic10\n ]\n counter=0\n for spell in self.spellRoster:\n print(counter)\n spell.configure(image=mythSpells[counter])\n spell.image = mythSpells[counter]\n counter+=1\n elif(self.schoolType==\"Death\"):\n spellPic1 = PhotoImage(file=\"virulent plague.gif\"),\n spellPic2 = PhotoImage(file=\"sacrifice.gif\"),\n spellPic3 = PhotoImage(file=\"feint(e).gif\"),\n spellPic4 = PhotoImage(file=\"feinttrap.gif\"),\n spellPic5 = PhotoImage(file=\"nullspell.gif\"),\n spellPic6 = PhotoImage(file=\"nullspell.gif\"),\n spellPic7 = PhotoImage(file=\"nullspell.gif\")\n spellPic8 = PhotoImage(file='nullspell.gif')\n spellPic9 = PhotoImage(file='nullspell.gif')\n spellPic10 = PhotoImage(file='useless.gif')\n deathSpells = [\n spellPic1,\n spellPic2,\n spellPic3,\n spellPic4,\n spellPic5,\n spellPic6,\n spellPic7,\n spellPic8,\n spellPic9,\n spellPic10\n ]\n counter=0\n for spell in self.spellRoster:\n print(counter)\n spell.configure(image=deathSpells[counter])\n spell.image = deathSpells[counter]\n counter+=1\n elif(self.schoolType==\"Life\"):\n spellPic1 = PhotoImage(file=\"cycle of life.gif\"),\n spellPic2 = PhotoImage(file=\"primordial.gif\"),\n spellPic3 = PhotoImage(file=\"rebirth.gif\"),\n spellPic4 = PhotoImage(file=\"pixie.gif\"),\n spellPic5 = PhotoImage(file=\"shadow seraph.gif\"),\n spellPic6 = PhotoImage(file=\"feinttrap.gif\"),\n spellPic7 = PhotoImage(file=\"feint(e).gif\")\n spellPic8 = PhotoImage(file='nullspell.gif')\n spellPic9 = PhotoImage(file='nullspell.gif')\n spellPic10 = PhotoImage(file='nullspell.gif')\n lifeSpells = [\n spellPic1,\n spellPic2,\n spellPic3,\n spellPic4,\n spellPic5,\n spellPic6,\n spellPic7,\n spellPic8,\n spellPic9,\n spellPic10\n ]\n counter=0\n for spell in self.spellRoster:\n print(counter)\n spell.configure(image=lifeSpells[counter])\n spell.image = lifeSpells[counter]\n counter+=1\n elif(self.schoolType==\"Balance\"):\n spellPic1 = PhotoImage(file=\"balanceblade.gif\"),\n spellPic2 = PhotoImage(file=\"balanceblade(e).gif\"),\n spellPic3 = PhotoImage(file=\"elemental_blade.gif\"),\n spellPic4 = PhotoImage(file=\"elemental_blade(e).gif\"),\n spellPic5 = PhotoImage(file=\"elemental_blade(tc).gif\"),\n spellPic6 = PhotoImage(file=\"feinttrap.gif\"),\n spellPic7 = PhotoImage(file=\"feint(e).gif\")\n spellPic8 = PhotoImage(file='bladestorm.gif')\n spellPic9 = PhotoImage(file='bladestorm(e).gif')\n spellPic10 = PhotoImage(file='nullspell.gif')\n lifeSpells = [\n spellPic1,\n spellPic2,\n spellPic3,\n spellPic4,\n spellPic5,\n spellPic6,\n spellPic7,\n spellPic8,\n spellPic9,\n spellPic10\n ]\n counter=0\n for spell in self.spellRoster:\n print(counter)\n spell.configure(image=lifeSpells[counter])\n spell.image = lifeSpells[counter]\n counter+=1\n\n def initRasputinSpells(self):\n if(self.schoolType==\"Fire\"):\n spellPic1 = PhotoImage(file=\"quench.gif\"),\n spellPic2 = PhotoImage(file=\"meteor strike.gif\"),\n spellPic3 = PhotoImage(file=\"fire cat.gif\"),\n spellPic4 = PhotoImage(file=\"infallible(tc).gif\"),\n spellPic5 = PhotoImage(file=\"elemental_blade(e).gif\"),\n spellPic6 = PhotoImage(file=\"elemental_blade(tc).gif\"),\n spellPic7 = PhotoImage(file=\"elemental_trap.gif\")\n spellPic8 = PhotoImage(file='elemental_trap(e).gif')\n spellPic9 = PhotoImage(file='stormblade(tc).gif')\n spellPic10 = PhotoImage(file='feint(e).gif')\n fireSpells = [\n spellPic1,\n spellPic2,\n spellPic3,\n spellPic4,\n spellPic5,\n spellPic6,\n spellPic7,\n spellPic8,\n spellPic9,\n spellPic10\n ]\n counter=0\n for spell in self.spellRoster:\n print(counter)\n spell.configure(image=fireSpells[counter])\n spell.image = fireSpells[counter]\n counter+=1\n elif(self.schoolType==\"Ice\"):\n spellPic1 = PhotoImage(file=\"elemental_blade.gif\"),\n spellPic2 = PhotoImage(file=\"elemental_blade(e).gif\"),\n spellPic3 = PhotoImage(file=\"elemental_blade(tc).gif\"),\n spellPic4 = PhotoImage(file=\"stormblade(tc).gif\"),\n spellPic5 = PhotoImage(file=\"feint(e).gif\"),\n spellPic6 = PhotoImage(file=\"shadow sentinel.gif\"),\n spellPic7 = PhotoImage(file=\"infallible(tc).gif\")\n spellPic8 = PhotoImage(file='blizzard.gif')\n spellPic9 = PhotoImage(file='frost beetle.gif')\n spellPic10 = PhotoImage(file='volcanic shield.gif')\n iceSpells = [\n spellPic1,\n spellPic2,\n spellPic3,\n spellPic4,\n spellPic5,\n spellPic6,\n spellPic7,\n spellPic8,\n spellPic9,\n spellPic10\n ]\n counter=0\n for spell in self.spellRoster:\n print(counter)\n spell.configure(image=iceSpells[counter])\n spell.image = iceSpells[counter]\n counter+=1\n elif(self.schoolType==\"Storm\"):\n spellPic1 = PhotoImage(file=\"stormblade.gif\"),\n spellPic2 = PhotoImage(file=\"stormblade(e).gif\"),\n spellPic3 = PhotoImage(file=\"stormblade(tc).gif\"),\n spellPic4 = PhotoImage(file=\"galvanic field.gif\"),\n spellPic5 = PhotoImage(file=\"rusalkas wrath.gif\"),\n spellPic6 = PhotoImage(file=\"colossal.gif\"),\n spellPic7 = PhotoImage(file=\"supercharge.gif\")\n spellPic8 = PhotoImage(file='elemental_blade.gif')\n spellPic9 = PhotoImage(file='elemental_blade(e).gif')\n spellPic10 = PhotoImage(file='elemental_blade(tc).gif')\n iceSpells = [\n spellPic1,\n spellPic2,\n spellPic3,\n spellPic4,\n spellPic5,\n spellPic6,\n spellPic7,\n spellPic8,\n spellPic9,\n spellPic10\n ]\n counter=0\n for spell in self.spellRoster:\n print(counter)\n spell.configure(image=iceSpells[counter])\n spell.image = iceSpells[counter]\n counter+=1\n elif(self.schoolType==\"Myth\"):\n spellPic1 = PhotoImage(file=\"infallible(tc).gif\"),\n spellPic2 = PhotoImage(file=\"humongofrog.gif\"),\n spellPic3 = PhotoImage(file=\"blood bat.gif\"),\n spellPic4 = PhotoImage(file=\"feint(e).gif\"),\n spellPic5 = PhotoImage(file=\"stormblade(tc).gif\"),\n spellPic6 = PhotoImage(file=\"elemental_blade(tc).gif\"),\n spellPic7 = PhotoImage(file=\"volcanic shield.gif\")\n spellPic8 = PhotoImage(file='nullspell.gif')\n spellPic9 = PhotoImage(file='nullspell.gif')\n spellPic10 = PhotoImage(file='nullspell.gif')\n mythSpells = [\n spellPic1,\n spellPic2,\n spellPic3,\n spellPic4,\n spellPic5,\n spellPic6,\n spellPic7,\n spellPic8,\n spellPic9,\n spellPic10\n ]\n counter=0\n for spell in self.spellRoster:\n print(counter)\n spell.configure(image=mythSpells[counter])\n spell.image = mythSpells[counter]\n counter+=1\n elif(self.schoolType==\"Death\"):\n spellPic1 = PhotoImage(file=\"virulent plague.gif\"),\n spellPic2 = PhotoImage(file=\"sacrifice.gif\"),\n spellPic3 = PhotoImage(file=\"feint(e).gif\"),\n spellPic4 = PhotoImage(file=\"infallible(tc).gif\"),\n spellPic5 = PhotoImage(file=\"deer knight.gif\"),\n spellPic6 = PhotoImage(file=\"dark sprite.gif\"),\n spellPic7 = PhotoImage(file=\"volcanic shield.gif\")\n spellPic8 = PhotoImage(file='nullspell.gif')\n spellPic9 = PhotoImage(file='nullspell.gif')\n spellPic10 = PhotoImage(file='nullspell.gif')\n deathSpells = [\n spellPic1,\n spellPic2,\n spellPic3,\n spellPic4,\n spellPic5,\n spellPic6,\n spellPic7,\n spellPic8,\n spellPic9,\n spellPic10\n ]\n counter=0\n for spell in self.spellRoster:\n print(counter)\n spell.configure(image=deathSpells[counter])\n spell.image = deathSpells[counter]\n counter+=1\n elif(self.schoolType==\"Life\"):\n spellPic1 = PhotoImage(file=\"cycle of life.gif\"),\n spellPic2 = PhotoImage(file=\"primordial.gif\"),\n spellPic3 = PhotoImage(file=\"rebirth.gif\"),\n spellPic4 = PhotoImage(file=\"pixie.gif\"),\n spellPic5 = PhotoImage(file=\"shadow seraph.gif\"),\n spellPic6 = PhotoImage(file=\"unicorn.gif\"),\n spellPic7 = PhotoImage(file=\"feint(e).gif\")\n spellPic8 = PhotoImage(file='stormblade(tc).gif')\n spellPic9 = PhotoImage(file='elemental_blade(tc).gif')\n spellPic10 = PhotoImage(file='volcanic shield.gif')\n lifeSpells = [\n spellPic1,\n spellPic2,\n spellPic3,\n spellPic4,\n spellPic5,\n spellPic6,\n spellPic7,\n spellPic8,\n spellPic9,\n spellPic10\n ]\n counter=0\n for spell in self.spellRoster:\n print(counter)\n spell.configure(image=lifeSpells[counter])\n spell.image = lifeSpells[counter]\n counter+=1\n elif(self.schoolType==\"Balance\"):\n spellPic1 = PhotoImage(file=\"balanceblade.gif\"),\n spellPic2 = PhotoImage(file=\"balanceblade(e).gif\"),\n spellPic3 = PhotoImage(file=\"elemental_blade.gif\"),\n spellPic4 = PhotoImage(file=\"elemental_blade(e).gif\"),\n spellPic5 = PhotoImage(file=\"elemental_blade(tc).gif\"),\n spellPic6 = PhotoImage(file=\"feint(e).gif\"),\n spellPic7 = PhotoImage(file=\"infallible(tc).gif\")\n spellPic8 = PhotoImage(file='bladestorm.gif')\n spellPic9 = PhotoImage(file='bladestorm(e).gif')\n spellPic10 = PhotoImage(file='sandstorm.gif')\n lifeSpells = [\n spellPic1,\n spellPic2,\n spellPic3,\n spellPic4,\n spellPic5,\n spellPic6,\n spellPic7,\n spellPic8,\n spellPic9,\n spellPic10\n ]\n counter=0\n for spell in self.spellRoster:\n print(counter)\n spell.configure(image=lifeSpells[counter])\n spell.image = lifeSpells[counter]\n counter+=1\n\ndef main():\n\n root = Tk()\n root.geometry(\"880x700+100+100\")\n app = WizTool(root)\n root.mainloop()\n\nmain()\n \n\n","sub_path":"Wizard101 toolbelt.py","file_name":"Wizard101 toolbelt.py","file_ext":"py","file_size_in_byte":77476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"307876245","text":"import numpy as np\nfrom astropy import units as u\nfrom astropy.coordinates import SkyCoord\nimport warnings\nfrom traitlets.config import Config\nfrom collections import namedtuple, OrderedDict\n\n# CTAPIPE utilities\nfrom ctapipe.calib import CameraCalibrator\nfrom ctapipe.image import hillas\nfrom ctapipe.utils.CutFlow import CutFlow\nfrom ctapipe.coordinates import GroundFrame\n\n# from ctapipe.image.hillas import hillas_parameters_5 as hillas_parameters\nfrom ctapipe.image.hillas import hillas_parameters\nfrom ctapipe.reco.HillasReconstructor import HillasReconstructor\n\n# monkey patch the camera calibrator to do NO integration correction\nimport ctapipe\n\n\ndef null_integration_correction_func(\n n_chan, pulse_shape, refstep, time_slice, window_width, window_shift\n):\n return np.ones(n_chan)\n\n\n# apply the patch\nctapipe.calib.camera.dl1.integration_correction = null_integration_correction_func\n\n# PiWy utilities\nfrom pywicta.io import geometry_converter\nfrom pywicta.io.images import simtel_event_to_images\nfrom pywi.processing.filtering import pixel_clusters\nfrom pywi.processing.filtering.pixel_clusters import filter_pixels_clusters\n\n# Pipeline utilities\nfrom .image_cleaning import ImageCleaner\n\n__all__ = [\"EventPreparer\"]\n\nPreparedEvent = namedtuple(\n \"PreparedEvent\",\n [\n \"event\",\n \"n_pixel_dict\",\n \"hillas_dict\",\n \"hillas_dict_reco\",\n \"n_tels\",\n \"tot_signal\",\n \"max_signals\",\n \"n_cluster_dict\",\n \"reco_result\",\n \"impact_dict\",\n ],\n)\n\n\ndef stub(event):\n return PreparedEvent(\n event=event,\n n_pixel_dict=None,\n hillas_dict=None,\n hillas_dict_reco=None,\n n_tels=None,\n tot_signal=None,\n max_signals=None,\n n_cluster_dict=None,\n reco_result=None,\n impact_dict=None,\n )\n\n\nclass EventPreparer:\n \"\"\"\n Class which loop on events and returns results stored in container\n\n The Class has several purposes. First of all, it prepares the images of the event\n that will be further use for reconstruction by applying calibration, cleaning and\n selection. Then, it reconstructs the geometry of the event and then returns\n image (e.g. Hillas parameters)and event information (e.g. reults od the\n reconstruction).\n\n Parameters\n ----------\n config: dict\n Configuration with analysis parameters\n mode: str\n Mode of the reconstruction, e.g. tail or wave\n event_cutflow: ctapipe.utils.CutFlow\n Statistic of events processed\n image_cutflow: ctapipe.utils.CutFlow\n Statistic of images processed\n\n Returns: dict\n Dictionnary of results\n \"\"\"\n\n def __init__(self, config, mode, event_cutflow=None, image_cutflow=None):\n # Cleaning for reconstruction\n self.cleaner_reco = ImageCleaner( # for reconstruction\n config=config[\"ImageCleaning\"][\"biggest\"], mode=mode\n )\n\n # Cleaning for energy/score estimation\n # Add possibility to force energy/score cleaning with tailcut analysis\n force_mode = mode\n try:\n if config[\"General\"][\"force_tailcut_for_extended_cleaning\"] is True:\n force_mode = config[\"General\"][\"force_mode\"]\n print(\"> Activate force-mode for cleaning!!!!\")\n except:\n pass # force_mode = mode\n\n self.cleaner_extended = ImageCleaner( # for energy/score estimation\n config=config[\"ImageCleaning\"][\"extended\"], mode=force_mode\n )\n\n # Image book keeping\n self.image_cutflow = image_cutflow or CutFlow(\"ImageCutFlow\")\n\n # Add quality cuts on images\n charge_bounds = config[\"ImageSelection\"][\"charge\"]\n npix_bounds = config[\"ImageSelection\"][\"pixel\"]\n ellipticity_bounds = config[\"ImageSelection\"][\"ellipticity\"]\n nominal_distance_bounds = config[\"ImageSelection\"][\"nominal_distance\"]\n\n self.camera_radius = {\n \"LSTCam\": 1.126,\n \"NectarCam\": 1.126,\n } # Average between max(xpix) and max(ypix), in meter\n\n self.image_cutflow.set_cuts(\n OrderedDict(\n [\n (\"noCuts\", None),\n (\"min pixel\", lambda s: np.count_nonzero(s) < npix_bounds[0]),\n (\"min charge\", lambda x: x < charge_bounds[0]),\n # (\"poor moments\", lambda m: m.width <= 0 or m.length <= 0 or np.isnan(m.width) or np.isnan(m.length)), # TBC, maybe we loose events without nan conditions\n (\"poor moments\", lambda m: m.width <= 0 or m.length <= 0),\n (\n \"bad ellipticity\",\n lambda m: (m.width / m.length) < ellipticity_bounds[0]\n or (m.width / m.length) > ellipticity_bounds[-1],\n ),\n # (\"close to the edge\", lambda m, cam_id: m.r.value > (nominal_distance_bounds[-1] * 1.12949101073069946)) # in meter\n (\n \"close to the edge\",\n lambda m, cam_id: m.r.value\n > (nominal_distance_bounds[-1] * self.camera_radius[cam_id]),\n ), # in meter\n ]\n )\n )\n\n # Reconstruction\n self.shower_reco = HillasReconstructor()\n\n # Event book keeping\n self.event_cutflow = event_cutflow or CutFlow(\"EventCutFlow\")\n\n # Add cuts on events\n min_ntel = config[\"Reconstruction\"][\"min_tel\"]\n self.event_cutflow.set_cuts(\n OrderedDict(\n [\n (\"noCuts\", None),\n (\"min2Tels trig\", lambda x: x < min_ntel),\n (\"min2Tels reco\", lambda x: x < min_ntel),\n (\"direction nan\", lambda x: x.is_valid == False),\n ]\n )\n )\n\n def prepare_event(self, source, return_stub=False):\n\n # configuration for the camera calibrator\n # modifies the integration window to be more like in MARS\n # JLK, only for LST!!!!\n # Option for integration correction is done above\n cfg = Config()\n cfg[\"ChargeExtractorFactory\"][\"window_width\"] = 5\n cfg[\"ChargeExtractorFactory\"][\"window_shift\"] = 2\n self.calib = CameraCalibrator(\n config=cfg,\n extractor_product=\"LocalPeakIntegrator\",\n eventsource=source,\n tool=None,\n )\n\n for event in source:\n\n self.event_cutflow.count(\"noCuts\")\n\n if self.event_cutflow.cut(\"min2Tels trig\", len(event.dl0.tels_with_data)):\n if return_stub:\n yield stub(event)\n else:\n continue\n\n # calibrate the event\n self.calib.calibrate(event)\n\n # telescope loop\n tot_signal = 0\n max_signals = {}\n n_pixel_dict = {}\n hillas_dict_reco = {} # for geometry\n hillas_dict = {} # for discrimination\n n_tels = {\n \"tot\": len(event.dl0.tels_with_data),\n \"LST\": 0,\n \"MST\": 0,\n \"SST\": 0,\n }\n n_cluster_dict = {}\n impact_dict_reco = {} # impact distance measured in tilt system\n\n point_azimuth_dict = {}\n point_altitude_dict = {}\n\n # To compute impact parameter in tilt system\n run_array_direction = event.mcheader.run_array_direction\n az, alt = run_array_direction[0], run_array_direction[1]\n\n ground_frame = GroundFrame()\n\n for tel_id in event.dl0.tels_with_data:\n self.image_cutflow.count(\"noCuts\")\n\n camera = event.inst.subarray.tel[tel_id].camera\n\n # count the current telescope according to its size\n tel_type = event.inst.subarray.tel[tel_id].optics.tel_type\n # JLK, N telescopes before cut selection are not really interesting for\n # discrimination, too much fluctuations\n # n_tels[tel_type] += 1\n\n # the camera image as a 1D array and stuff needed for calibration\n # Choose gain according to pywicta's procedure\n image_1d = simtel_event_to_images(\n event=event, tel_id=tel_id, ctapipe_format=True\n )\n pmt_signal = image_1d.input_image # calibrated image\n\n # clean the image\n try:\n with warnings.catch_warnings():\n # Image with biggest cluster (reco cleaning)\n image_biggest = self.cleaner_reco.clean_image(\n pmt_signal, camera\n )\n image_biggest2d = geometry_converter.image_1d_to_2d(\n image_biggest, camera.cam_id\n )\n image_biggest2d = filter_pixels_clusters(image_biggest2d)\n image_biggest = geometry_converter.image_2d_to_1d(\n image_biggest2d, camera.cam_id\n )\n\n # Image for score/energy estimation (with clusters)\n image_extended = self.cleaner_extended.clean_image(\n pmt_signal, camera\n )\n except FileNotFoundError as e: # JLK, WHAT?\n print(e)\n continue\n\n # Apply some selection\n if self.image_cutflow.cut(\"min pixel\", image_biggest):\n continue\n\n if self.image_cutflow.cut(\"min charge\", np.sum(image_biggest)):\n continue\n\n # For cluster counts\n image_2d = geometry_converter.image_1d_to_2d(\n image_extended, camera.cam_id\n )\n n_cluster_dict[tel_id] = pixel_clusters.number_of_pixels_clusters(\n array=image_2d, threshold=0\n )\n\n # could this go into `hillas_parameters` ...?\n max_signals[tel_id] = np.max(image_extended)\n\n # do the hillas reconstruction of the images\n # QUESTION should this change in numpy behaviour be done here\n # or within `hillas_parameters` itself?\n # JLK: make selection on biggest cluster\n with np.errstate(invalid=\"raise\", divide=\"raise\"):\n try:\n\n moments_reco = hillas_parameters(\n camera, image_biggest\n ) # for geometry (eg direction)\n moments = hillas_parameters(\n camera, image_extended\n ) # for discrimination and energy reconstruction\n\n # if width and/or length are zero (e.g. when there is only only one\n # pixel or when all pixel are exactly in one row), the\n # parametrisation won't be very useful: skip\n if self.image_cutflow.cut(\"poor moments\", moments_reco):\n # print('poor moments')\n continue\n\n if self.image_cutflow.cut(\n \"close to the edge\", moments_reco, camera.cam_id\n ):\n # print('close to the edge')\n continue\n\n if self.image_cutflow.cut(\"bad ellipticity\", moments_reco):\n # print('bad ellipticity: w={}, l={}'.format(moments_reco.width, moments_reco.length))\n continue\n\n except (FloatingPointError, hillas.HillasParameterizationError):\n continue\n\n point_azimuth_dict[tel_id] = event.mc.tel[tel_id].azimuth_raw * u.rad\n point_altitude_dict[tel_id] = event.mc.tel[tel_id].altitude_raw * u.rad\n\n n_tels[tel_type] += 1\n hillas_dict[tel_id] = moments\n hillas_dict_reco[tel_id] = moments_reco\n n_pixel_dict[tel_id] = len(np.where(image_extended > 0)[0])\n tot_signal += moments.intensity\n\n n_tels[\"reco\"] = len(hillas_dict_reco)\n n_tels[\"discri\"] = len(hillas_dict)\n if self.event_cutflow.cut(\"min2Tels reco\", n_tels[\"reco\"]):\n if return_stub:\n yield stub(event)\n else:\n continue\n\n try:\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n\n # Reconstruction results\n reco_result = self.shower_reco.predict(\n hillas_dict_reco,\n event.inst,\n point_altitude_dict,\n point_azimuth_dict,\n )\n\n # shower_sys = TiltedGroundFrame(pointing_direction=HorizonFrame(\n # az=reco_result.az,\n # alt=reco_result.alt\n # ))\n\n # Impact parameter for energy estimation (/ tel)\n subarray = event.inst.subarray\n for tel_id in hillas_dict.keys():\n\n pos = subarray.positions[tel_id]\n\n tel_ground = SkyCoord(\n pos[0], pos[1], pos[2], frame=ground_frame\n )\n # tel_tilt = tel_ground.transform_to(shower_sys)\n\n core_ground = SkyCoord(\n reco_result.core_x,\n reco_result.core_y,\n 0 * u.m,\n frame=ground_frame,\n )\n # core_tilt = core_ground.transform_to(shower_sys)\n\n # Should be better handled (tilted frame)\n impact_dict_reco[tel_id] = np.sqrt(\n (core_ground.x - tel_ground.x) ** 2\n + (core_ground.y - tel_ground.y) ** 2\n )\n\n except Exception as e:\n print(\"exception in reconstruction:\", e)\n raise\n if return_stub:\n yield stub(event)\n else:\n continue\n\n if self.event_cutflow.cut(\"direction nan\", reco_result):\n if return_stub:\n yield stub(event)\n else:\n continue\n\n yield PreparedEvent(\n event=event,\n n_pixel_dict=n_pixel_dict,\n hillas_dict=hillas_dict,\n hillas_dict_reco=hillas_dict_reco,\n n_tels=n_tels,\n tot_signal=tot_signal,\n max_signals=max_signals,\n n_cluster_dict=n_cluster_dict,\n reco_result=reco_result,\n impact_dict=impact_dict_reco,\n )\n","sub_path":"protopipe/pipeline/event_preparer.py","file_name":"event_preparer.py","file_ext":"py","file_size_in_byte":15234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"574703174","text":"import sqlite3\n\n# do poprawnego działania należy najpierw mieć bazę stworzoną za pomocą skryptu `baza_init.py`\n\nconn = sqlite3.connect('baza.db')\nc = conn.cursor()\n\nzapytanie = \"\"\"\nSELECT * \nFROM \"zespoly\" \nJOIN \"muzycy\" ON \"zespoly\".\"id\" = \"muzycy\".\"zespol_id\";\n\"\"\"\n\nc.execute(zapytanie)\n\nfor linia in c:\n print(linia)\n\nconn.close()\n","sub_path":"Python - advanced/zajecia10/02_rel/baza_join01.py","file_name":"baza_join01.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"165651095","text":"# -*- coding: utf-8 -*-\n\"\"\"\nPart of the astor library for Python AST manipulation.\n\nLicense: 3-clause BSD\n\nCopyright (c) 2008 Armin Ronacher\nCopyright (c) 2012-2017 Patrick Maupin\nCopyright (c) 2013-2017 Berker Peksag\n\nThis module converts an AST into Python source code.\n\nBefore being version-controlled as part of astor,\nthis code came from here (in 2012):\n\n https://gist.github.com/1250562\n\n\"\"\"\n\nimport ast\nimport sys\n\nfrom .op_util import get_op_symbol, get_op_precedence, Precedence\nfrom .node_util import ExplicitNodeVisitor\nfrom .string_repr import pretty_string\nfrom .source_repr import pretty_source\nfrom collections import namedtuple\n\nprmt_temp_functions = {\\\n \"pmat\": \"c_pmt_create_pmat\", \\\n \"pvec\": \"c_pmt_create_pvec\", \\\n \"dgemm\": \"c_pmt_dgemm\", \\\n \"dgead\": \"c_pmt_dgead\", \\\n \"pmat_fill\": \"c_pmt_pmat_fill\", \\\n \"pmat_copy\": \"c_pmt_pmat_copy\", \\\n \"pmat_print\": \"c_pmt_pmat_print\", \\\n \"pvec_fill\": \"c_pmt_pvec_fill\", \\\n \"pvec_copy\": \"c_pmt_pvec_copy\", \\\n \"pvec_print\": \"c_pmt_pvec_print\", \\\n \"prmt_lus\" : \"c_pmt_lus\"}\n\nprmt_temp_types = {\\\n \"pmat\": \"struct pmat *\", \\\n \"pvec\": \"struct pvec *\", \\\n \"None\": \"void\", \\\n \"NoneType\": \"void\", \\\n \"ptr_int\": \"int *\", \\\n \"ptr_pmat\": \"struct pmat **\", \\\n \"int\": \"int\", \"double\": \"double\"}\n\nusr_temp_types = {}\n\ndef to_source(node, module_name, indent_with=' ' * 4, add_line_information=False,\n pretty_string=pretty_string, pretty_source=pretty_source, main=False, ___c_prmt_8_heap_size=None, ___c_prmt_64_heap_size=None):\n \"\"\"This function can convert a node tree back into python sourcecode.\n This is useful for debugging purposes, especially if you're dealing with\n custom asts not generated by python itself.\n\n It could be that the sourcecode is evaluable when the AST itself is not\n compilable / evaluable. The reason for this is that the AST contains some\n more data than regular sourcecode does, which is dropped during\n conversion.\n\n Each level of indentation is replaced with `indent_with`. Per default this\n parameter is equal to four spaces as suggested by PEP 8, but it might be\n adjusted to match the application's styleguide.\n\n If `add_line_information` is set to `True` comments for the line numbers\n of the nodes are added to the output. This can be used to spot wrong line\n number information of statement nodes.\n\n \"\"\"\n if ___c_prmt_8_heap_size is None or ___c_prmt_64_heap_size is None :\n error('Need to pass heap_sizes! Exiting.')\n\n generator = SourceGenerator(indent_with, ___c_prmt_8_heap_size,\n ___c_prmt_64_heap_size, add_line_information,\n pretty_string,\n )\n \n generator.result.source.append('#include \"stdlib.h\"\\n')\n # generator.result.source.append('#include \"pmat_blasfeo_wrapper.h\"\\n')\n # generator.result.source.append('#include \"pvec_blasfeo_wrapper.h\"\\n')\n # generator.result.source.append('#include \"prmt_heap.h\"\\n')\n generator.result.source.append('#include \"%s.h\"\\n' %(module_name))\n generator.result.header.append('#include \"prometeo.h\"\\n')\n\n generator.visit(node)\n \n generator.result.source.append('\\n')\n if set(generator.result.source[0]) == set('\\n'):\n generator.result.source[0] = ''\n \n generator.result.header.append('\\n')\n if set(generator.result.header[0]) == set('\\n'):\n generator.result.header[0] = ''\n\n # if main==True:\n # generator.result.source.append('')\n # generator.result.source.append('}')\n # generator.result.source.append('\\n')\n # generator.result.source.append('')\n \n return generator.result\n\n\ndef precedence_setter(AST=ast.AST, get_op_precedence=get_op_precedence,\n isinstance=isinstance, list=list):\n \"\"\" This only uses a closure for performance reasons,\n to reduce the number of attribute lookups. (set_precedence\n is called a lot of times.)\n \"\"\"\n\n def set_precedence(value, *nodes):\n \"\"\"Set the precedence (of the parent) into the children.\n \"\"\"\n if isinstance(value, AST):\n value = get_op_precedence(value)\n for node in nodes:\n if isinstance(node, AST):\n node._pp = value\n elif isinstance(node, list):\n set_precedence(value, *node)\n else:\n assert node is None, node\n\n return set_precedence\n\n\nset_precedence = precedence_setter()\n\n\nclass Delimit(object):\n \"\"\"A context manager that can add enclosing\n delimiters around the output of a\n SourceGenerator method. By default, the\n parentheses are added, but the enclosed code\n may set discard=True to get rid of them.\n \"\"\"\n\n discard = False\n\n def __init__(self, tree, *args):\n \"\"\" use write instead of using result.source directly\n for initial data, because it may flush\n preceding data into result.source.\n \"\"\"\n delimiters = '()'\n node = None\n op = None\n for arg in args:\n if isinstance(arg, ast.AST):\n if node is None:\n node = arg\n else:\n op = arg\n else:\n delimiters = arg\n tree.write(delimiters[0], dest = 'src')\n result = self.result = tree.result\n result.source = self.result.source = tree.result.source\n self.index = len(result.source)\n self.closing = delimiters[1]\n if node is not None:\n self.p = p = get_op_precedence(op or node)\n self.pp = pp = tree.get__pp(node)\n self.discard = p >= pp\n\n def __enter__(self):\n return self\n\n def __exit__(self, *exc_info):\n result = self.result\n result.source = self.result.source\n start = self.index - 1\n if self.discard:\n result.source[start] = ''\n else:\n result.source.append(self.closing)\n\n\nclass SourceGenerator(ExplicitNodeVisitor):\n \"\"\"This visitor is able to transform a well formed syntax tree into Python\n sourcecode.\n\n For more details have a look at the docstring of the `node_to_source`\n function.\n \"\"\"\n using_unicode_literals = False\n \n def __init__(self, indent_with, ___c_prmt_8_heap_size, ___c_prmt_64_heap_size, \n add_line_information=False,pretty_string=pretty_string,\n # constants\n len=len, isinstance=isinstance, callable=callable):\n \n self.result = namedtuple('result', 'source header')\n self.result.source = [] \n self.result.header = []\n self.indent_with = indent_with\n self.add_line_information = add_line_information\n self.indentation = 0 # Current indentation level\n self.new_lines = 0 # Number of lines to insert before next code\n self.colinfo = 0, 0 # index in result.source of string containing linefeed, and\n # position of last linefeed in that string\n self.pretty_string = pretty_string\n AST = ast.AST\n\n visit = self.visit\n newline = self.newline\n result = self.result\n result.source = self.result.source\n result.header = self.result.header\n append_src = result.source.append\n append_hdr = result.header.append\n \n self.heap8_size = ___c_prmt_8_heap_size \n self.heap64_size = ___c_prmt_64_heap_size \n\n self.typed_record = {}\n \n def write(*params, dest):\n \"\"\" self.write is a closure for performance (to reduce the number\n of attribute lookups).\n \"\"\"\n for item in params:\n if isinstance(item, AST):\n visit(item)\n elif callable(item):\n item()\n elif item == '\\n':\n newline()\n else:\n if dest == 'src':\n if self.new_lines:\n append_src('\\n' * self.new_lines)\n self.colinfo = len(result.source), 0\n append_src(self.indent_with * self.indentation)\n self.new_lines = 0\n if item:\n append_src(item)\n if dest == 'hdr':\n if self.new_lines:\n append_hdr('\\n' * self.new_lines)\n self.colinfo = len(result.header), 0\n append_hdr(self.indent_with * self.indentation)\n self.new_lines = 0\n if item:\n append_hdr(item)\n\n\n self.write = write\n\n def __getattr__(self, name, defaults=dict(keywords=(),\n _pp=Precedence.highest).get):\n \"\"\" Get an attribute of the node.\n like dict.get (returns None if doesn't exist)\n \"\"\"\n if not name.startswith('get_'):\n raise AttributeError\n geta = getattr\n shortname = name[4:]\n default = defaults(shortname)\n\n def getter(node):\n return geta(node, shortname, default)\n\n setattr(self, name, getter)\n return getter\n\n def delimit(self, *args):\n return Delimit(self, *args)\n\n def conditional_write(self, *stuff, dest):\n if stuff[-1] is not None:\n self.write(*stuff, dest = dest)\n # Inform the caller that we wrote\n return True\n\n def newline(self, node=None, extra=0):\n self.new_lines = max(self.new_lines, 1 + extra)\n if node is not None and self.add_line_information:\n self.write('# line: %s' % node.lineno, dest = 'src')\n self.new_lines = 1\n\n def body(self, statements):\n self.indentation += 1\n self.write(*statements, dest = 'src')\n self.indentation -= 1\n\n def body_class(self, statements, name):\n self.indentation += 1\n self.write_class_attributes(*statements, name=name)\n self.write('};', dest = 'hdr')\n self.indentation -= 1\n self.write_class_method_prototypes(*statements, name=name)\n \n self.write('\\n', dest = 'src')\n self.write_class_init(*statements, name=name)\n self.write_class_methods(*statements, name=name)\n\n\n def write_class_attributes(self, *params, name):\n \"\"\" self.write is a closure for performance (to reduce the number\n of attribute lookups).\n \"\"\"\n for item in params:\n if isinstance(item, ast.AnnAssign):\n set_precedence(item, item.target, item.annotation)\n set_precedence(Precedence.Comma, item.value)\n need_parens = isinstance(item.target, ast.Name) and not item.simple\n begin = '(' if need_parens else ''\n end = ')' if need_parens else ''\n self.write('%s' %item.annotation.id, ' ', '%s' %item.target.id, ';\\n', dest = 'hdr')\n # self.conditional_write(' = ', item.value, ';')\n elif isinstance(item, ast.FunctionDef):\n \n # build argument mangling\n f_name_len = len(item.name)\n pre_mangl = '_Z%s' %f_name_len \n if item.args.args[0].arg is not 'self':\n raise Exception(\"First argument in method {} \\\n must be 'self'. You have '{}'\".format(item.name, item.args.args[0].arg))\n else: \n # store self argument\n self_arg = item.args.args[0]\n # pop self from argument list\n item.args.args.pop(0)\n\n post_mangl = self.build_arg_mangling(item.args)\n \n #self.statement(item, self.get_returns(item), ' %s%s%s%s' % (pre_mangl, item.name, post_mangl, name), '_impl(', name, ' *self, ')\n if hasattr(self.get_returns(item), \"id\"):\n ret_type = self.get_returns(item).id\n else:\n ret_type = self.get_returns(item).value\n\n if ret_type is None: \n ret_type = 'None'\n\n if ret_type in prmt_temp_types:\n ret_type = prmt_temp_types[ret_type]\n else:\n raise Exception ('Usage of non existing type {}'.format(ret_type))\n\n self.write('%s (*%s%s%s' % (ret_type, pre_mangl, item.name, post_mangl) , ')', '(%s *self, ' %name, dest = 'hdr')\n self.visit_arguments(item.args, 'hdr')\n self.write(');\\n', dest = 'hdr')\n # insert back self argument \n item.args.args.insert(0, self_arg)\n \n def write_class_method_prototypes(self, *params, name):\n \"\"\" self.write is a closure for performance (to reduce the number\n of attribute lookups).\n \"\"\"\n self.write('\\n\\n', dest = 'hdr')\n for item in params:\n if isinstance(item, ast.FunctionDef):\n \n # build argument mangling\n f_name_len = len(item.name)\n pre_mangl = '_Z%s' %f_name_len \n if item.args.args[0].arg is not 'self':\n raise Exception(\"First argument in method {} \\\n must be 'self'. You have '{}'\".format(item.name, item.args.args[0].arg))\n else: \n # store self argument\n self_arg = item.args.args[0]\n # pop self from argument list\n item.args.args.pop(0)\n\n post_mangl = self.build_arg_mangling(item.args)\n if hasattr(self.get_returns(item), \"id\"):\n ret_type = self.get_returns(item).id\n else:\n ret_type = self.get_returns(item).value\n\n if ret_type is None: \n ret_type = 'None'\n\n if ret_type in prmt_temp_types:\n ret_type = prmt_temp_types[ret_type]\n else:\n raise Exception ('Usage of non existing type {}'.format(ret_type))\n\n self.write('%s (%s%s%s%s' % (ret_type, pre_mangl, item.name, post_mangl, name) , '_impl)', '(%s *self, ' %name, dest = 'hdr')\n self.visit_arguments(item.args, 'hdr')\n self.write(');\\n', dest = 'hdr')\n # insert back self argument \n item.args.args.insert(0, self_arg)\n \n def write_class_init(self, *params, name):\n \"\"\" self.write is a closure for performance (to reduce the number\n of attribute lookups).\n \"\"\"\n self.write('void ', name, '_init(struct ', name, ' *object){', dest = 'src')\n self.indentation += 1\n for item in params:\n if isinstance(item, ast.AnnAssign):\n # set_precedence(item, item.target, item.annotation)\n set_precedence(Precedence.Comma, item.value)\n need_parens = isinstance(item.target, ast.Name) and not item.simple\n begin = '(' if need_parens else ''\n end = ')' if need_parens else ''\n # self.statement(item, item.target, ';')\n if item.value != None:\n if hasattr(item.value, 'value') is False:\n self.conditional_write('\\n', 'object->', item.target, ' = ', item.value, ';', dest = 'src')\n else:\n if item.value.value != None:\n self.conditional_write('\\n', 'object->', item.target, ' = ', item.value, ';', dest = 'src')\n elif isinstance(item, ast.FunctionDef):\n \n # build argument mangling\n f_name_len = len(item.name)\n pre_mangl = '_Z%s' %f_name_len \n if item.args.args[0].arg is not 'self':\n raise Exception(\"First argument in method {} \\\n must be 'self'. You have '{}'\".format(item.name, item.args.args[0].arg))\n else: \n # store self argument\n self_arg = item.args.args[0]\n # pop self from argument list\n item.args.args.pop(0)\n\n post_mangl = self.build_arg_mangling(item.args)\n \n self.statement(item, 'object->%s%s%s' %(pre_mangl, item.name, post_mangl), ' = &', '%s%s%s%s' %(pre_mangl, item.name, post_mangl, name), '_impl;')\n \n # build argument mangling\n arg_mangl = self.build_arg_mangling(item.args)\n # insert back self argument \n item.args.args.insert(0, self_arg)\n\n self.write('\\n}\\n', dest = 'src')\n self.indentation -=1\n \n def write_class_methods(self, *params, name):\n \"\"\" self.write is a closure for performance (to reduce the number\n of attribute lookups).\n \"\"\"\n for item in params:\n if isinstance(item, ast.FunctionDef):\n self.decorators(item, 1 if self.indentation else 2)\n # self.write()\n\n # build argument mangling\n f_name_len = len(item.name)\n pre_mangl = '_Z%s' %f_name_len \n if item.args.args[0].arg is not 'self':\n raise Exception(\"First argument in method {} \\\n must be 'self'. You have '{}'\".format(item.name, item.args.args[0].arg))\n else: \n # store self argument\n self_arg = item.args.args[0]\n # pop self from argument list\n item.args.args.pop(0)\n\n post_mangl = self.build_arg_mangling(item.args)\n\n if hasattr(self.get_returns(item), \"id\"):\n ret_type = self.get_returns(item).id\n else:\n ret_type = self.get_returns(item).value\n\n if ret_type is None: \n ret_type = 'None'\n\n if ret_type in prmt_temp_types:\n ret_type = prmt_temp_types[ret_type]\n else:\n raise Exception ('Usage of non existing type {}'.format(ret_type))\n\n self.statement(item, ret_type, ' %s%s%s%s' % (pre_mangl, \\\n item.name, post_mangl, name), '_impl(', name, ' *self, ')\n\n self.visit_arguments(item.args, 'src')\n self.write(') {', dest = 'src')\n self.body(item.body)\n self.newline(1)\n self.write('}', dest = 'src')\n\n if not self.indentation:\n self.newline(extra=2)\n # insert back self argument \n item.args.args.insert(0, self_arg)\n\n def else_body(self, elsewhat):\n if elsewhat:\n self.write('\\n', 'else:')\n self.body(elsewhat)\n\n def body_or_else(self, node):\n self.body(node.body)\n self.else_body(node.orelse)\n\n def visit_arguments(self, node, dest_in):\n want_comma = []\n\n def write_comma():\n if want_comma:\n self.write(', ', dest = dest_in)\n else:\n want_comma.append(True)\n\n def loop_args(args, defaults):\n set_precedence(Precedence.Comma, defaults)\n padding = [None] * (len(args) - len(defaults))\n for arg, default in zip(args, padding + defaults):\n # fish c type from typed record\n arg_type_py = arg.annotation.id\n\n arg_type_c = prmt_temp_types[arg_type_py]\n self.write(write_comma, arg_type_c,' ',arg.arg, dest = dest_in)\n\n # add variable to typed record\n self.typed_record[arg.arg] = arg_type_py\n self.conditional_write('=', default, dest = 'src')\n\n loop_args(node.args, node.defaults)\n self.conditional_write(write_comma, '*', node.vararg, dest = 'src')\n\n kwonlyargs = self.get_kwonlyargs(node)\n if kwonlyargs:\n if node.vararg is None:\n self.write(write_comma, '*')\n loop_args(kwonlyargs, node.kw_defaults)\n self.conditional_write(write_comma, '**', node.kwarg, dest = 'src')\n\n def build_arg_mangling(self, node):\n want_comma = []\n\n def loop_args_mangl(args, defaults):\n set_precedence(Precedence.Comma, defaults)\n padding = [None] * (len(args) - len(defaults))\n arg_mangl = ''\n for arg, default in zip(args, padding + defaults):\n arg_mangl = arg_mangl + arg.annotation.id\n return arg_mangl\n\n arg_mangl = loop_args_mangl(node.args, node.defaults)\n return arg_mangl\n \n def build_arg_mangling_mod(self, args):\n want_comma = []\n\n def loop_args_mangl(args):\n arg_mangl = ''\n for arg in args:\n arg_mangl = arg_mangl + self.typed_record[arg.id]\n return arg_mangl\n\n arg_mangl = loop_args_mangl(args)\n return arg_mangl\n\n def statement(self, node, *params, **kw):\n self.newline(node)\n self.write(*params, dest = 'src')\n\n def decorators(self, node, extra):\n self.newline(extra=extra)\n for decorator in node.decorator_list:\n self.statement(decorator, '@', decorator)\n\n def comma_list(self, items, trailing=False):\n set_precedence(Precedence.Comma, *items)\n for idx, item in enumerate(items):\n self.write(', ' if idx else '', item, dest = 'src')\n self.write(',' if trailing else '', dest = 'src')\n\n # Statements\n def visit_Assign(self, node):\n if 'targets' in node.__dict__:\n if type(node.targets[0]) == ast.Subscript: \n # check for double subscripting (pmat)\n if 'value' in node.targets[0].value.__dict__:\n target = node.targets[0].value.value.id\n if target in self.typed_record: \n # map subscript for pmats to blasfeo el assign\n if self.typed_record[target] in ('pmat'):\n print(self.typed_record[target])\n target = node.targets[0]\n sub_type = type(target.value.slice.value)\n if sub_type == ast.Num:\n first_index = node.targets[0].value.slice.value.n\n elif sub_type == ast.Name:\n first_index = node.targets[0].value.slice.value.id\n else:\n raise Exception(\"Subscripting with value of type {} not implemented\".format(sub_type))\n\n sub_type = type(target.slice.value)\n if sub_type == ast.Num: \n second_index = node.targets[0].slice.value.n\n elif sub_type == ast.Name: \n second_index = node.targets[0].slice.value.id\n else:\n raise Exception(\"Subscripting with value of type {} not implemented\".format(sub_type))\n\n # check if subscripted expression is used in the value\n if type(node.value) == ast.Subscript:\n # if value is a pmat\n value = node.value.value.value.id\n if value in self.typed_record:\n if self.typed_record[value] == 'pmat':\n sub_type = type(node.value.slice.value)\n if sub_type == ast.Num:\n second_index_value = node.value.slice.value.n\n elif sub_type == ast.Name:\n second_index_value = node.value.slice.value.id\n else:\n raise Exception(\"Subscripting with value of type {} not implemented\".format(sub_type))\n\n sub_type = type(node.value.value.slice.value)\n if sub_type == ast.Num: \n first_index_value = node.value.value.slice.value.n\n elif sub_type == ast.Name: \n first_index_value = node.value.value.slice.value.id\n else:\n raise Exception(\"Subscripting with value of type {} not implemented\".format(sub_type))\n\n value_expr = 'c_pmt_pmat_get_el(' + value + ', {}, {})'.format(first_index_value, second_index_value) \n self.statement([], 'c_pmt_pmat_set_el(', target.value.value.id, ', {}'.format(first_index), ', {}'.format(second_index), ', {}'.format(value_expr), ');')\n else:\n target = node.targets[0].value.value.id\n value = node.value.n\n self.statement([], 'c_pmt_pmat_set_el(', target, ', {}'.format(first_index), ', {}'.format(second_index), ', {}'.format(value), ');')\n return\n\n # check for single subscripting (pvec)\n elif 'id' in node.targets[0].value.__dict__:\n target = node.targets[0].value.id\n if target in self.typed_record: \n # map subscript for pvec to blasfeo el assign\n if self.typed_record[target] in ('pvec'):\n target = node.targets[0]\n sub_type = type(target.slice.value)\n if sub_type == ast.Num:\n index = node.targets[0].slice.value.n\n elif sub_type == ast.Name:\n index = node.targets[0].slice.value.id\n else:\n raise Exception(\"Subscripting with value of type {} not implemented\".format(sub_type))\n\n # check if subscripted expression is used in the value\n if type(node.value) == ast.Subscript:\n # check for double subscripting\n if 'value' in node.value.value.__dict__:\n value = node.value.value.value.id\n if value in self.typed_record:\n # if value is a pmat\n if self.typed_record[value] == 'pmat':\n sub_type = type(node.value.slice.value)\n if sub_type == ast.Num:\n second_index_value = node.value.slice.value.n\n elif sub_type == ast.Name:\n second_index_value = node.value.slice.value.id\n else:\n raise Exception(\"Subscripting with value of type {} not implemented\".format(sub_type))\n\n sub_type = type(node.value.value.slice.value)\n if sub_type == ast.Num: \n first_index_value = node.value.value.slice.value.n\n elif sub_type == ast.Name: \n first_index_value = node.value.value.slice.value.id\n else:\n raise Exception(\"Subscripting with value of type {} not implemented\".format(sub_type))\n\n value_expr = 'c_pmt_pmat_get_el(' + value + ', {}, {})'.format(first_index_value, second_index_value) \n # self.statement([], 'pmat_set_el(', target, ', ', first_index, ', ', second_index, ', ', value_expr, ');')\n self.statement([], 'c_pmt_pvec_set_el(', target.value.id, ', {}'.format(index), ', {}'.format(value_expr), ');')\n # single subscripting\n else:\n value = node.value.value.id\n # if value is a pvec\n if self.typed_record[value] == 'pvec':\n sub_type = type(node.value.slice.value)\n if sub_type == ast.Num: \n index_value = node.value.slice.value.n\n elif sub_type == ast.Name: \n index_value = node.value.slice.value.id\n else:\n raise Exception(\"Subscripting with value of type {} not implemented\".format(sub_type))\n\n value_expr = 'c_pmt_pvec_get_el(' + value + ', {})'.format(index_value) \n # self.statement([], 'pmat_set_el(', target, ', ', first_index, ', ', second_index, ', ', value_expr, ');')\n self.statement([], 'c_pmt_pvec_set_el(', target.value.id, ', {}'.format(index), ', {}'.format(value_expr), ');')\n else:\n target = node.targets[0].value.id\n value = node.value.n\n self.statement([], 'c_pmt_pvec_set_el(', target, ', {}'.format(index), ', {}'.format(value), ');')\n return\n\n elif 'id' in node.targets[0].__dict__: \n\n # check for Assigns targeting pmats\n target = node.targets[0].id\n print(target)\n if target in self.typed_record: \n if self.typed_record[target] == 'pmat':\n if type(node.value) == ast.BinOp:\n right_op = node.value.right.id\n left_op = node.value.left.id\n if right_op in self.typed_record and left_op in self.typed_record:\n if self.typed_record[left_op] == 'pmat' and self.typed_record[right_op] == 'pmat':\n # dgemm\n if type(node.value.op) == ast.Mult:\n # set target to zero\n self.statement([], 'c_pmt_pmat_fill(', target, ', 0.0);')\n # call dgemm\n self.statement([], 'c_pmt_dgemm(', left_op, ', ', right_op, ', ', target, ', ', target, ');')\n return\n # dgead\n if type(node.value.op) == ast.Add:\n # set target to zero\n self.statement([], 'c_pmt_pmat_copy(', right_op, ', ', target, ');')\n # call dgead\n self.statement([], 'c_pmt_dgead(1.0, ', left_op, ', ', target, ');')\n return\n # dgead (Sub)\n if type(node.value.op) == ast.Sub:\n # set target to zero\n self.statement([], 'c_pmt_pmat_copy(', left_op, ', ', target, ');')\n # call dgead\n self.statement([], 'c_pmt_dgead(-1.0, ', right_op, ', ', target, ');')\n return\n else:\n raise Exception('Unsupported operator call:{} {} {}'\\\n .format(self.typed_record[left_op], node.value.op, self.typed_record[right_op]))\n\n elif self.typed_record[target] == 'pvec':\n if type(node.value) == ast.BinOp:\n right_op = node.value.right.id\n left_op = node.value.left.id\n if right_op in self.typed_record and left_op in self.typed_record:\n if self.typed_record[left_op] == 'pmat' and self.typed_record[right_op] == 'pvec':\n # dgemv\n if type(node.value.op) == ast.Mult:\n # set target to zero\n self.statement([], 'c_pmt_pvec_fill(', target, ', 0.0);')\n # call dgemm\n self.statement([], 'c_pmt_dgemv(', left_op, ', ', right_op, ', ', target, ', ', target, ');')\n return\n # dgead\n else:\n raise Exception('Unsupported operator call:{} {} {}'\\\n .format(self.typed_record[left_op], node.value.op, self.typed_record[right_op]))\n \n\n elif 'attr' in node.targets[0].__dict__: \n # Assign targeting a user-defined class (C struct)\n struct_name = node.targets[0].value.id\n if struct_name in self.typed_record:\n attr_value = node.value.n\n attr_name = node.targets[0].attr \n self.statement([], struct_name, '->', attr_name, ' = ', str(attr_value), ';')\n else:\n raise Exception(\"Unknown variable {}\".format(struct_name))\n return\n\n else:\n raise Exception(\"Could not resolve Assign node.\")\n\n set_precedence(node, node.value, *node.targets)\n self.newline(node)\n for target in node.targets:\n self.write(target, ' = ', dest = 'src')\n self.visit(node.value)\n self.write(';', dest = 'src')\n\n def visit_AugAssign(self, node):\n set_precedence(node, node.value, node.target)\n self.statement(node, node.target, get_op_symbol(node.op, ' %s= '),\n node.value)\n\n def visit_AnnAssign(self, node):\n set_precedence(node, node.target, node.annotation)\n set_precedence(Precedence.Comma, node.value)\n need_parens = isinstance(node.target, ast.Name) and not node.simple\n begin = '(' if need_parens else ''\n end = ')' if need_parens else ''\n # check if a List is being declared\n if \"value\" in node.__dict__:\n if \"value\" in node.annotation.__dict__:\n if \"id\" in node.annotation.value.__dict__:\n if node.annotation.value.id is 'List':\n if node.value.func.id is not 'prmt_list': \n raise Exception(\"Cannot create Lists without using prmt_list constructor.\")\n else:\n ann = node.annotation.slice.value.id\n if ann in prmt_temp_types:\n ann = prmt_temp_types[ann]\n else:\n raise Exception ('Usage of non existing type {}'.format(ann))\n array_size = str(node.value.args[1].n)\n self.statement([], ann, ' ', node.target, '[', array_size, '];')\n return\n\n # check if the annotation contains directly a type or something fancier\n if \"id\" in node.annotation.__dict__:\n ann = node.annotation.id\n # add variable to typed record\n self.typed_record[node.target.id] = node.annotation.id\n print(self.typed_record)\n if ann in prmt_temp_types:\n node.annotation.id = prmt_temp_types[ann]\n self.statement(node, node.annotation, ' ', node.target)\n # check if annotation corresponds to user-defined class name\n elif ann in usr_temp_types:\n class_name = node.annotation.id\n node.annotation.id = usr_temp_types[ann]\n self.statement([], 'struct ', class_name, ' ', node.target, '___;')\n self.statement(node, node.annotation, ' ', node.target, '= &', node.target, '___;')\n self.statement([], class_name, '_init(', node.target, '); //')\n else:\n raise Exception ('Usage of non existing type {}'.format(ann))\n # else:\n # self.statement(node, node.annotation, ' ', node.target)\n # raise Exception(\"Could not resolve type '{}'. Exiting.\".format(ann))\n\n # List[]\n elif \"slice\" in node.annotation.__dict__:\n ann = 'ptr_' + node.annotation.slice.value.id\n # add variable to typed record\n self.typed_record[node.target.id] = ann\n print(self.typed_record)\n if ann in prmt_temp_types:\n c_ann = prmt_temp_types[ann]\n self.statement(node, c_ann, ' ', node.target.id)\n else:\n raise Exception ('Usage of non existing type {}'.format(ret_type))\n\n # switch to avoid double ';'\n if type(node.value) != ast.Call:\n if node.value is not None:\n self.conditional_write(' = ', node.value, ';', dest = 'src')\n else:\n self.conditional_write(';', dest = 'src')\n else:\n if node.value is not None:\n self.conditional_write(' = ', node.value, '', dest = 'src')\n else:\n self.conditional_write('', dest = 'src')\n\n\n\n def visit_ImportFrom(self, node):\n include = node.module\n include = include.replace('.','/')\n if node.level is not 0: \n raise Exception('Imports with level > 0 are not supported. Exiting.')\n if len(node.names) is not 1:\n raise Exception('Imports with multiple names are not supported (yet). Exiting.')\n\n if node.names[0].name is not '*':\n raise Exception('Can only transpile imports of the form: `from <...> import *`. Exiting.') \n self.statement(node, '#include \"', \n include or '', '.h\"')\n\n def visit_Import(self, node):\n raise Exception('Unsupported import statement. Use instead from `<...> import *` Exiting.') \n # self.statement(node, 'import ')\n # self.comma_list(node.names)\n\n def visit_Expr(self, node):\n if type(node.value) is ast.Call:\n if \"value\" in node.value.func.__dict__:\n var_name = node.value.func.value.id\n # check if we are calling a method on a pmat object\n if var_name in self.typed_record: \n if self.typed_record[var_name] == 'pmat':\n fun_name = node.value.func.attr \n # add prefix to function call\n node.value.func.attr = 'c_pmt_pmat_' + fun_name \n set_precedence(node, node.value)\n\n self.statement(node)\n self.generic_visit(node)\n\n def visit_FunctionDef(self, node, is_async=False):\n prefix = 'is_async ' if is_async else ''\n self.decorators(node, 1 if self.indentation else 2)\n # self.write()\n returns = self.get_returns(node)\n return_type_py = returns.value\n\n if node.name == 'main':\n self.write('void *___c_prmt_8_heap; \\n', dest = 'src')\n self.write('void *___c_prmt_64_heap; \\n', dest = 'src')\n\n print(return_type_py)\n return_type_c = prmt_temp_types[return_type_py.__class__.__name__]\n # self.statement(node, self.get_returns(node), '%s %s' % (prefix, node.name), '(')\n self.write(return_type_c, ' %s' %(node.name), '(', dest = 'src')\n self.visit_arguments(node.args, 'src')\n self.write(') {\\n', dest = 'src')\n if node.name == 'main':\n self.write(' ___c_prmt_8_heap = malloc(%s); \\n' %(self.heap8_size), dest = 'src')\n self.write(' char *pmem_ptr = (char *)___c_prmt_8_heap; \\n', dest = 'src')\n self.write(' align_char_to(8, &pmem_ptr);\\n', dest = 'src')\n self.write(' ___c_prmt_8_heap = pmem_ptr;\\n', dest = 'src')\n \n self.write(' ___c_prmt_64_heap = malloc(%s); \\n' %(self.heap64_size), dest = 'src')\n self.write(' pmem_ptr = (char *)___c_prmt_64_heap; \\n', dest = 'src')\n self.write(' align_char_to(64, &pmem_ptr);\\n', dest = 'src')\n self.write(' ___c_prmt_64_heap = pmem_ptr;\\n', dest = 'src')\n\n # self.write(':')\n self.body(node.body)\n self.newline(1)\n self.write('}', dest='src')\n if not self.indentation:\n self.newline(extra=2)\n\n # introduced in Python 3.5\n def visit_AsyncFunctionDef(self, node):\n self.visit_FunctionDef(node, is_async=True)\n\n def visit_ClassDef(self, node):\n have_args = []\n\n def paren_or_comma():\n if have_args:\n self.write(', ')\n else:\n have_args.append(True)\n self.write('(')\n # add new type to templated types\n usr_temp_types[node.name] = 'struct ' + node.name + ' *' \n\n self.decorators(node, 0)\n self.write('typedef struct %s %s;\\n\\n' %(node.name, node.name), dest = 'hdr')\n self.write('struct %s' %node.name, dest = 'hdr')\n for base in node.bases:\n self.write(paren_or_comma, base)\n # keywords not available in early version\n for keyword in self.get_keywords(node):\n self.write(paren_or_comma, keyword.arg or '',\n '=' if keyword.arg else '**', keyword.value)\n self.conditional_write(paren_or_comma, '*', self.get_starargs(node), dest = 'src')\n self.conditional_write(paren_or_comma, '**', self.get_kwargs(node), dest = 'src')\n self.write(have_args and ')' or '', dest = 'src')\n self.write('{\\n', dest = 'hdr')\n self.body_class(node.body, node.name)\n #if not self.indentation:\n # self.newline(extra=-6)\n\n def visit_If(self, node):\n set_precedence(node, node.test)\n self.statement(node, 'if(', node.test, ') {')\n self.body(node.body)\n while True:\n else_ = node.orelse\n if len(else_) == 1 and isinstance(else_[0], ast.If):\n node = else_[0]\n set_precedence(node, node.test)\n self.write('\\n', 'elif ', node.test, ':')\n self.body(node.body)\n else:\n self.else_body(else_)\n break\n self.write('\\n}', dest = 'src')\n\n def visit_For(self, node, is_async=False):\n set_precedence(node, node.target)\n prefix = 'is_async ' if is_async else ''\n \n self.statement(node, 'for(int ',\n node.target, ' = 0; ', node.target, \n ' < {}'.format(node.iter.args[0].n), \n '; ',node.target, '++) {')\n\n self.body_or_else(node)\n self.write('\\n }\\n', dest = 'src')\n\n # introduced in Python 3.5\n def visit_AsyncFor(self, node):\n self.visit_For(node, is_async=True)\n\n def visit_While(self, node):\n set_precedence(node, node.test)\n self.statement(node, 'while(', node.test, ') {')\n self.body_or_else(node)\n self.write('\\n }\\n', dest = 'src')\n\n\n def visit_With(self, node, is_async=False):\n prefix = 'is_async ' if is_async else ''\n self.statement(node, '%swith ' % prefix)\n if hasattr(node, \"context_expr\"): # Python < 3.3\n self.visit_withitem(node)\n else: # Python >= 3.3\n self.comma_list(node.items)\n self.write(':')\n self.body(node.body)\n\n # new for Python 3.5\n def visit_AsyncWith(self, node):\n self.visit_With(node, is_async=True)\n\n # new for Python 3.3\n def visit_withitem(self, node):\n self.write(node.context_expr)\n self.conditional_write(' as ', node.optional_vars, dest = 'src')\n\n def visit_NameConstant(self, node):\n self.write(str(node.value), dest = 'src')\n\n def visit_Pass(self, node):\n self.statement(node, 'pass')\n\n def visit_Print(self, node):\n # XXX: python 2.6 only\n self.statement(node, 'print ')\n values = node.values\n if node.dest is not None:\n self.write(' >> ')\n values = [node.dest] + node.values\n self.comma_list(values, not node.nl)\n\n def visit_Delete(self, node):\n self.statement(node, 'del ')\n self.comma_list(node.targets)\n\n def visit_TryExcept(self, node):\n self.statement(node, 'try:')\n self.body(node.body)\n self.write(*node.handlers)\n self.else_body(node.orelse)\n\n # new for Python 3.3\n def visit_Try(self, node):\n self.statement(node, 'try:')\n self.body(node.body)\n self.write(*node.handlers)\n self.else_body(node.orelse)\n if node.finalbody:\n self.statement(node, 'finally:')\n self.body(node.finalbody)\n\n def visit_ExceptHandler(self, node):\n self.statement(node, 'except')\n if self.conditional_write(' ', node.type, dest = 'src'):\n self.conditional_write(' as ', node.name, dest = 'src')\n self.write(':')\n self.body(node.body)\n\n def visit_TryFinally(self, node):\n self.statement(node, 'try:')\n self.body(node.body)\n self.statement(node, 'finally:')\n self.body(node.finalbody)\n\n def visit_Exec(self, node):\n dicts = node.globals, node.locals\n dicts = dicts[::-1] if dicts[0] is None else dicts\n self.statement(node, 'exec ', node.body)\n self.conditional_write(' in ', dicts[0], dest = 'src')\n self.conditional_write(', ', dicts[1], dest = 'src')\n\n def visit_Assert(self, node):\n set_precedence(node, node.test, node.msg)\n self.statement(node, 'assert ', node.test)\n self.conditional_write(', ', node.msg, dest = 'src')\n\n def visit_Global(self, node):\n self.statement(node, 'global ', ', '.join(node.names))\n\n def visit_Nonlocal(self, node):\n self.statement(node, 'nonlocal ', ', '.join(node.names))\n\n def visit_Return(self, node):\n set_precedence(node, node.value)\n self.statement(node, 'return')\n self.conditional_write(' ', node.value, ';', dest = 'src')\n\n def visit_Break(self, node):\n self.statement(node, 'break')\n\n def visit_Continue(self, node):\n self.statement(node, 'continue')\n\n def visit_Raise(self, node):\n # XXX: Python 2.6 / 3.0 compatibility\n self.statement(node, 'raise')\n if self.conditional_write(' ', self.get_exc(node), dest = 'src'):\n self.conditional_write(' from ', node.cause, dest = 'src')\n elif self.conditional_write(' ', self.get_type(node), dest = 'src'):\n set_precedence(node, node.inst)\n self.conditional_write(', ', node.inst, dest = 'src')\n self.conditional_write(', ', node.tback, dest = 'src')\n\n # Expressions\n\n def visit_Attribute(self, node):\n if self.typed_record[node.value.id] in usr_temp_types: \n self.write(node.value, '->', node.attr, dest = 'src')\n else:\n raise Exception(\"Accessing attribute of object {} of unknown type\".format(node.value))\n\n def visit_Call(self, node, len=len):\n write = self.write\n want_comma = []\n\n def write_comma():\n if want_comma:\n write(', ', dest = 'src')\n else:\n want_comma.append(True)\n \n args = node.args\n keywords = node.keywords\n starargs = self.get_starargs(node)\n kwargs = self.get_kwargs(node)\n numargs = len(args) + len(keywords)\n numargs += starargs is not None\n numargs += kwargs is not None\n p = Precedence.Comma if numargs > 1 else Precedence.call_one_arg\n set_precedence(p, *args)\n\n if type(node.func) == ast.Name: \n if node.func.id in prmt_temp_functions:\n func_name = node.func.id\n node.func.id = prmt_temp_functions[func_name]\n elif type(node.func) == ast.Attribute: \n # calling a method of a user-defined class\n func_name = node.func.attr\n f_name_len = len(func_name)\n pre_mangl = '_Z%s' %f_name_len \n post_mangl = self.build_arg_mangling_mod(args)\n node.func.attr = pre_mangl + func_name + post_mangl\n\n self.visit(node.func)\n if type(node.func) == ast.Attribute: \n code = '(' + node.func.value.id + ', '\n write(code, dest = 'src')\n else:\n write('(', dest = 'src')\n\n for arg in args:\n write(write_comma, arg, dest = 'src')\n\n set_precedence(Precedence.Comma, *(x.value for x in keywords))\n for keyword in keywords:\n # a keyword.arg of None indicates dictionary unpacking\n # (Python >= 3.5)\n arg = keyword.arg or ''\n write(write_comma, arg, '=' if arg else '**', keyword.value)\n # 3.5 no longer has these\n self.conditional_write(write_comma, '*', starargs, dest = 'src')\n self.conditional_write(write_comma, '**', kwargs, dest = 'src')\n write(');', dest = 'src')\n\n def visit_Name(self, node):\n self.write(node.id, dest = 'src')\n\n def visit_JoinedStr(self, node):\n self.visit_Str(node, True)\n\n def visit_Str(self, node, is_joined=False):\n\n # embedded is used to control when we might want\n # to use a triple-quoted string. We determine\n # if we are in an assignment and/or in an expression\n precedence = self.get__pp(node)\n embedded = ((precedence > Precedence.Expr) +\n (precedence >= Precedence.Assign))\n\n # Flush any pending newlines, because we're about\n # to severely abuse the result.source list.\n self.write('', dest = 'src')\n # result.source = self.result.source\n\n # Calculate the string representing the line\n # we are working on, up to but not including\n # the string we are adding.\n\n res_index, str_index = self.colinfo\n current_line = self.result.source[res_index:]\n if str_index:\n current_line[0] = current_line[0][str_index:]\n current_line = ''.join(current_line)\n\n if is_joined:\n\n # Handle new f-strings. This is a bit complicated, because\n # the tree can contain subnodes that recurse back to JoinedStr\n # subnodes...\n\n def recurse(node):\n for value in node.values:\n if isinstance(value, ast.Str):\n self.write(value.s)\n elif isinstance(value, ast.FormattedValue):\n with self.delimit('{}'):\n self.visit(value.value)\n if value.conversion != -1:\n self.write('!%s' % chr(value.conversion))\n if value.format_spec is not None:\n self.write(':')\n recurse(value.format_spec)\n else:\n kind = type(value).__name__\n assert False, 'Invalid node %s inside JoinedStr' % kind\n\n index = len(result.source)\n recurse(node)\n mystr = ''.join(result.source[index:])\n del result.source[index:]\n self.colinfo = res_index, str_index # Put it back like we found it\n uni_lit = False # No formatted byte strings\n\n else:\n mystr = node.s\n uni_lit = self.using_unicode_literals\n\n mystr = self.pretty_string(mystr, embedded, current_line, uni_lit)\n\n if is_joined:\n mystr = 'f' + mystr\n\n self.write(mystr, dest = 'src')\n\n lf = mystr.rfind('\\n') + 1\n if lf:\n self.colinfo = len(result.source) - 1, lf\n\n def visit_Bytes(self, node):\n self.write(repr(node.s))\n\n def visit_Num(self, node,\n # constants\n new=sys.version_info >= (3, 0)):\n with self.delimit(node) as delimiters:\n s = repr(node.n)\n\n # Deal with infinities -- if detected, we can\n # generate them with 1e1000.\n signed = s.startswith('-')\n if s[signed].isalpha():\n im = s[-1] == 'j' and 'j' or ''\n assert s[signed:signed + 3] == 'inf', s\n s = '%s1e1000%s' % ('-' if signed else '', im)\n self.write(s, dest = 'src')\n\n # The Python 2.x compiler merges a unary minus\n # with a number. This is a premature optimization\n # that we deal with here...\n if not new and delimiters.discard:\n if signed:\n pow_lhs = Precedence.Pow + 1\n delimiters.discard = delimiters.pp != pow_lhs\n else:\n op = self.get__p_op(node)\n delimiters.discard = not isinstance(op, ast.USub)\n\n def visit_Tuple(self, node):\n with self.delimit(node) as delimiters:\n # Two things are special about tuples:\n # 1) We cannot discard the enclosing parentheses if empty\n # 2) We need the trailing comma if only one item\n elts = node.elts\n delimiters.discard = delimiters.discard and elts\n self.comma_list(elts, len(elts) == 1)\n\n def visit_List(self, node):\n with self.delimit('[]'):\n self.comma_list(node.elts)\n\n def visit_Set(self, node):\n with self.delimit('{}'):\n self.comma_list(node.elts)\n\n def visit_Dict(self, node):\n set_precedence(Precedence.Comma, *node.values)\n with self.delimit('{}'):\n for idx, (key, value) in enumerate(zip(node.keys, node.values)):\n self.write(', ' if idx else '',\n key if key else '',\n ': ' if key else '**', value)\n\n def visit_BinOp(self, node):\n op, left, right = node.op, node.left, node.right\n with self.delimit(node, op) as delimiters:\n ispow = isinstance(op, ast.Pow)\n p = delimiters.p\n set_precedence((Precedence.Pow + 1) if ispow else p, left)\n set_precedence(Precedence.PowRHS if ispow else (p + 1), right)\n self.write(left, get_op_symbol(op, ' %s '), right, dest = 'src')\n\n def visit_BoolOp(self, node):\n with self.delimit(node, node.op) as delimiters:\n op = get_op_symbol(node.op, ' %s ')\n set_precedence(delimiters.p + 1, *node.values)\n for idx, value in enumerate(node.values):\n self.write(idx and op or '', value)\n\n def visit_Compare(self, node):\n with self.delimit(node, node.ops[0]) as delimiters:\n set_precedence(delimiters.p + 1, node.left, *node.comparators)\n self.visit(node.left)\n for op, right in zip(node.ops, node.comparators):\n self.write(get_op_symbol(op, ' %s '), right, dest = 'src')\n\n def visit_UnaryOp(self, node):\n with self.delimit(node, node.op) as delimiters:\n set_precedence(delimiters.p, node.operand)\n # In Python 2.x, a unary negative of a literal\n # number is merged into the number itself. This\n # bit of ugliness means it is useful to know\n # what the parent operation was...\n node.operand._p_op = node.op\n sym = get_op_symbol(node.op)\n self.write(sym, ' ' if sym.isalpha() else '', node.operand)\n\n def visit_Subscript(self, node):\n set_precedence(node, node.slice)\n self.write(node.value, '[', node.slice, ']', dest = 'src')\n\n def visit_Slice(self, node):\n set_precedence(node, node.lower, node.upper, node.step)\n self.conditional_write(node.lower, dest = 'src')\n self.write(':')\n self.conditional_write(node.upper, dest = 'src')\n if node.step is not None:\n self.write(':')\n if not (isinstance(node.step, ast.Name) and\n node.step.id == 'None'):\n self.visit(node.step)\n\n def visit_Index(self, node):\n with self.delimit(node) as delimiters:\n set_precedence(delimiters.p, node.value)\n self.visit(node.value)\n\n def visit_ExtSlice(self, node):\n dims = node.dims\n set_precedence(node, *dims)\n self.comma_list(dims, len(dims) == 1)\n\n def visit_Yield(self, node):\n with self.delimit(node):\n set_precedence(get_op_precedence(node) + 1, node.value)\n self.write('yield')\n self.conditional_write(' ', node.value, dest = 'src')\n\n # new for Python 3.3\n def visit_YieldFrom(self, node):\n with self.delimit(node):\n self.write('yield from ', node.value)\n\n # new for Python 3.5\n def visit_Await(self, node):\n with self.delimit(node):\n self.write('await ', node.value)\n\n def visit_Lambda(self, node):\n with self.delimit(node) as delimiters:\n set_precedence(delimiters.p, node.body)\n self.write('lambda ')\n self.visit_arguments(node.args, 'src')\n self.write(': ', node.body)\n\n def visit_Ellipsis(self, node):\n self.write('...')\n\n def visit_ListComp(self, node):\n with self.delimit('[]'):\n self.write(node.elt, *node.generators)\n\n def visit_GeneratorExp(self, node):\n with self.delimit(node) as delimiters:\n if delimiters.pp == Precedence.call_one_arg:\n delimiters.discard = True\n set_precedence(Precedence.Comma, node.elt)\n self.write(node.elt, *node.generators)\n\n def visit_SetComp(self, node):\n with self.delimit('{}'):\n self.write(node.elt, *node.generators)\n\n def visit_DictComp(self, node):\n with self.delimit('{}'):\n self.write(node.key, ': ', node.value, *node.generators)\n\n def visit_IfExp(self, node):\n with self.delimit(node) as delimiters:\n set_precedence(delimiters.p + 1, node.body, node.test)\n set_precedence(delimiters.p, node.orelse)\n self.write(node.body, ' if ', node.test, ' else ', node.orelse)\n\n def visit_Starred(self, node):\n self.write('*', node.value)\n\n def visit_Repr(self, node):\n # XXX: python 2.6 only\n with self.delimit('``'):\n self.visit(node.value)\n\n def visit_Module(self, node):\n self.write(*node.body, dest = 'src')\n\n visit_Interactive = visit_Module\n\n def visit_Expression(self, node):\n self.visit(node.body)\n\n # Helper Nodes\n\n def visit_arg(self, node):\n self.write(node.arg)\n self.conditional_write(': ', node.annotation, dest = 'src')\n\n def visit_alias(self, node):\n self.write(node.name, dest = 'src')\n self.conditional_write(' as ', node.asname, dest = 'src')\n\n def visit_comprehension(self, node):\n set_precedence(node, node.iter, *node.ifs)\n set_precedence(Precedence.comprehension_target, node.target)\n stmt = ' is_async for ' if self.get_is_is_async(node) else ' for '\n self.write(stmt, node.target, ' in ', node.iter)\n for if_ in node.ifs:\n self.write(' if ', if_)\n","sub_path":"prometeo/cgen/code_gen_c.py","file_name":"code_gen_c.py","file_ext":"py","file_size_in_byte":60752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"628036037","text":"from flask import Flask, request, render_template \nfrom flask import redirect, url_for\n\nimport os\nimport os.path\n\nfrom modules import mod_search\nfrom modules import mod_login\nfrom modules import mod_logout\n\n''' BASICAL FUNCTIONS BEGIN '''\n\napp = Flask(__name__, static_url_path='')\n#app.secret_key = \"super secret key\"\napp.config['SECRET_KEY'] = 'super secret key'\n\n@app.route('/')\n#@interceptor(login_required=True)\ndef default():\n model = [] \n return render_template('index.html', model=model)\n\n@app.route('/index')\n#@interceptor(login_required=False)\ndef index():\n model = [] \n return render_template('index.html', model=model)\n\n@app.route('/error', methods=['GET', 'POST'])\n#@interceptor(login_required=False)\ndef error():\n msg = request.args.get('msg')\n return render_template('error.html',msg=msg)\n\n@app.errorhandler(404)\ndef page_not_found(e):\n return render_template('error.html',msg=e)\n\n\n''' BUSSINESS FUNCTIONS BEGIN '''\n\n\n@app.route('/search', methods=['GET', 'POST'])\n#@interceptor(login_required=True)\ndef search():\n model,query,recommend_keyword = mod_search.service(request)\n return render_template('search_result.html', model=model,query=query,recommend_keyword=recommend_keyword)\n\n@app.route('/login',methods=['GET','POST'])\ndef login():\n #if method is get, then show login page only.if post, then deal login request\n if request.method == 'GET':\n return render_template('login.html')\n elif request.method == 'POST':\n model,recommend_content=mod_login.service(request)\n if model['result'] == True:\n return render_template('index.html', recommend_content=recommend_content)\n else:\n return render_template('error.html',msg='login error')\n #return render_template('index.html',model=model,recommend=recommend_content)\n\n@app.route('/logout',methods=['GET','POST'])\ndef logout():\n model=mod_logout.service(request)\n return render_template('index.html')\n\n''' MAIN ENTRY '''\nif __name__ == '__main__':\n app.debug = True\n app.run(host=\"127.0.0.1\",port=5100,processes=6)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"174660574","text":"inFile1=open('lncrna_ucsc_human','r')\n\ndict1=dict()\nfor line in inFile1 :\n fields=line.split()\n dict1.setdefault(fields[2],[fields[1],fields[3],fields[12]])\n dict1[fields[2]].append(fields[4])\n dict1[fields[2]].append(fields[5])\n\ninFile1.close()\n\nfor key in dict1 :\n print(key+'\\t'+'\\t'.join(dict1[key]))\n\n\n\ninFile2=open('/netshare1/home1/szzhongxin/proj1/hansun/annotation/snpindel_snp3030_raw.snp.recalibrated.vcf','r')\n\nfor i in range(125) :\n inFile2.readline()\n\nfor line in inFile2 :\n fields=line.split('\\t')\n if fields[0] in dict1 :\n for p in range(3,len(dict1[fields[0]]),2) :\n if dict1[fields[0]][p]<=fields[1]<=dict1[fields[0]][p+1] :\n print('\\t'.join(fields[0:6])+'\\t'+'\\t'.join(dict1[fields[0]]))\n\n\n\ninFile2.close()\n","sub_path":"cc_mcc_seq/etc/lncRNA/lncrna.py","file_name":"lncrna.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"449308280","text":"# A valid credit card from ABCD Bank has the following characteristics: \n\n# ► It must only consist of digits (0-9). check\n# ► It must start with a 4, 5 or 6. check\n# ► It must contain exactly 16 digits. check\n# ► It may have digits in groups of 4, separated by one hyphen \"-\". check\n# ► It must NOT use any other separator like ' ' , '_', etc. check\n# ► It must NOT have 4 or more consecutive repeated digits.\n\n\n# Instruction: input 6 credit card numbers,\n# validate each of them and label 'Valid' or 'Invalid'\n\n# sample input\n# 6\n# 4123456789123456\n# 5123-4567-8912-3456\n# 61234-567-8912-3456\n# 4123356789123456\n# 5133-3367-8912-3456\n# 5123 - 3567 - 8912 - 3456\n\n# test1: only consists of 0-9:\ndef testdigit(card):\n allowed = list(map(str, [0,1,2,3,4,5,6,7,8,9,\"-\"]))\n for i in range(0, len(card)):\n if card[i] not in allowed:\n return 1\n else: continue\n return 0\n\n# test2: the first number starts with 4, 5, or 6\ndef test456(card):\n digit = int(card[0])\n testlist = [4, 5, 6]\n if digit in testlist :\n return 0\n else: \n return 1\n\n# test 3: exactly 16 digits:\ndef test16(card):\n strip_hyp = \"\".join(card.split(\"-\"))\n if len(strip_hyp) == 16:\n return 0\n else: \n return 1\n\n# test 4: combination of 4 numbers\ndef test4comb(card):\n for i in range(0, len(card)):\n if card[i] == \"-\":\n splitlst = card.split(\"-\")\n for j in range(0,len(splitlst)):\n if len(splitlst[j]) == 4: \n continue\n else : \n return 1\n else: continue\n return 0\n\n# test 5: must not have more than 4 consecutive digits:\ndef testcons(card):\n strip_hyp = \"\".join(map(str, card.split(\"-\")))\n for i in range(0, len(strip_hyp)):\n t = strip_hyp[i]\n sstr = \"\".join(map(str,[t, t, t, t]))\n index = strip_hyp.find(sstr, 0, len(strip_hyp))\n if index >= 1:\n return 1\n else:\n continue\n return 0\n\n# main \ndef main():\n entries = int(input())\n cards = []\n results = 0\n outputs =[]\n\n for i in range(0,entries):\n cards.append(input())\n\n for card in cards:\n results = testdigit(card) + test456(card) + test16(card) + test4comb(card) + testcons(card)\n if results > 0:\n outputs.append(\"Invalid\")\n else:\n outputs.append(\"Valid\")\n\n print(*outputs, sep='\\n')\n\nmain()","sub_path":"Python/HackerRank/Credit card validation.py","file_name":"Credit card validation.py","file_ext":"py","file_size_in_byte":2448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"77450591","text":"from django.conf.urls import patterns, include, url\n\n#from django.contrib import admin\n#admin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n \n # include applications \n # url(r'^blog/', include('blog.urls')),\n # url(r'^admin/', include(admin.site.urls)),\n \n # application urls\n \n url(r'^$', 'scout.views.list_view', name='list_view'),\n url(r'^discover/', 'scout.views.discover_view', name='discover_view'), \n url(r'^map/', 'scout.views.map_view', name='map_view'), \n url(r'^detail/\\d{1,2}', 'scout.views.detail_view', name='detail_view'),\n url(r'^favorites/', 'scout.views.favorites_view', name='favorites_view'),\n url(r'^filter/', 'scout.views.filter_view', name='filter_view'),\n\t\n\t# example hybrid components\n\turl(r'^components/', 'scout.views.hybrid_comps_view', name='hybrid_comps_view'),\n\n)\n\n\n","sub_path":"scout/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"579182494","text":"import logging\nfrom typing import Optional, List, Dict, Union, Tuple\n\nimport numpy as np\n\nfrom solvers.madrich.problems.mdvrp_demo.models import Storage, Tour, Courier, Route, Job, Track, Problem\nfrom solvers.madrich.problems.models import Matrix, State\n\narray = np.ndarray\n\n\nclass ProblemMdvrp(Problem):\n\n @staticmethod\n def init(vec: int, storages: List[Storage], couriers: List[Courier], matrices: Dict[str, Matrix]) -> Tour:\n \"\"\" Строим жадно тур: по ближайшим подходящим соседям для каждого курьера\n :param vec: длина вектора value\n :param storages: все склады\n :param couriers: все доступные курьеры\n :param matrices: матрицы расстояний\n :return: тур\n \"\"\"\n logging.info(f'\\nCreating Tour: {[st.name for st in storages]}, Couriers: {len(couriers)}')\n tour = Tour(storages)\n\n for courier in couriers: # строим маршрут для каждого курьера\n route = ProblemMdvrp.__greedy_route(vec, courier, matrices)\n tour.routes.append(route)\n\n logging.info(f'Created Tour, jobs: {sum([len(storage.assigned_jobs) for storage in storages])}')\n return tour\n\n @staticmethod\n def get_state(route: Route) -> Optional[State]:\n \"\"\" Подсчитываем праметры тура и проверяем на правильность и обновляем Route\n :param route: маршрут\n :return: состояние\n \"\"\"\n size_t = len(route.tracks)\n if size_t == 0:\n return State.empty()\n location = route.courier.start_location.matrix_id\n state = State.empty()\n\n for track in route.tracks:\n state.value = np.zeros(route.vec, dtype=np.int64)\n # 1. Подходит ли он складу вообще\n if not ProblemMdvrp.__validate_skills(track.storage, route.courier):\n return None\n # 2. Едем на склад\n answer = ProblemMdvrp.__go_storage(location, state, track.storage, route)\n if answer is None:\n return None\n state += answer\n location = track.storage.location.matrix_id\n # 3. Проверяем каждую точку\n for job in track.jobs:\n if not ProblemMdvrp.__validate_skills(job, route.courier):\n return None\n if not ProblemMdvrp.__validate_courier(state, route):\n return None\n answer = ProblemMdvrp.__go_job(location, state, job, track.storage, route)\n if answer is None or not ProblemMdvrp.__validate_courier(answer, route):\n return None\n location = job.location.matrix_id\n state += answer\n\n state += ProblemMdvrp.__end(location, route)\n if not ProblemMdvrp.__validate_courier(state, route):\n return None\n\n state.value = None\n return state\n\n @staticmethod\n def get_state_track(track: Track, route: Route) -> Optional[State]:\n \"\"\" Оценка снизу подмаршрута\n :param track: подмаршрут\n :param route: маршрут\n :return: оценка\n \"\"\"\n location = track.storage.location.matrix_id\n state = State.empty()\n\n for job in track.jobs:\n tt = route.matrix.travel_time[location][job.location.matrix_id]\n d = route.matrix.distance[location][job.location.matrix_id]\n c = ProblemMdvrp.__cost(tt, d, route)\n location = job.location.matrix_id\n state += State(tt, d, c, job.value)\n\n return state\n\n @staticmethod\n def greedy_route(vec: int, courier: Courier, matrices: Dict[str, Matrix]) -> Route:\n return ProblemMdvrp.__greedy_route(vec, courier, matrices)\n\n @staticmethod\n def __greedy_route(vec: int, courier: Courier, matrices: Dict[str, Matrix]) -> Route:\n \"\"\" Строим жадно тур: по ближайшим подходящим соседям\n :param vec: длина вектора value\n :param courier: курьер для которого строим тур\n :param matrices: матрица расстояний/времени\n :return: новый маршрут\n \"\"\"\n logging.info(f'Creating Route, Courier: {courier.name}, type: {courier.profile}')\n start_shift, _ = courier.work_time.window\n route = Route(courier, matrices[courier.profile], start_shift, vec=vec)\n state = State.empty()\n curr_location = courier.start_location.matrix_id\n\n while True:\n # 1. Инициализируем подмаршрут с одной точкой\n state.value = np.zeros(route.vec, dtype=np.int64)\n tmp = ProblemMdvrp.__init_track(curr_location, state, route)\n if tmp is None:\n break\n state, track = tmp\n curr_location = track.jobs[0].location.matrix_id\n\n while True:\n # 2. Добавляем по точке\n new_state = ProblemMdvrp.__choose_job(curr_location, state, track, route)\n if new_state is None:\n break\n state = new_state\n curr_location = track.jobs[-1].location.matrix_id\n\n route.tracks.append(track)\n\n state += ProblemMdvrp.__end(curr_location, route)\n route.state += state\n logging.info(f'Route created, jobs: {sum([len(track.jobs) for track in route.tracks])}')\n return route\n\n @staticmethod\n def __end(curr_point: int, route: Route) -> State:\n \"\"\" Заканчиваем, едем с последней задачи в конечную точку\n :param curr_point: текущая позиция\n :param route: маршрут\n :return: состояние\n \"\"\"\n distance_matrix = route.matrix.distance\n travel_time_matrix = route.matrix.travel_time\n end_id = route.courier.start_location.matrix_id\n tt = travel_time_matrix[curr_point][end_id]\n d = distance_matrix[curr_point][end_id]\n return State(tt, d, ProblemMdvrp.__cost(tt, d, route), None)\n\n @staticmethod\n def __cost(travel_time: int, distance: int, route: Route) -> float:\n \"\"\" Получение стоимости\n :param travel_time: изменение времени\n :param distance: изменение расстояния\n :param route: маршрут\n :return: увеличение стоимости\n \"\"\"\n return travel_time * route.courier.cost.second + distance * route.courier.cost.meter\n\n @staticmethod\n def __validate_skills(obj: Union[Job, Storage], courier: Courier) -> bool:\n \"\"\" Проверяем, что задача или склад подходит курьеру\n :param obj: объект в котором проверяем умения\n :param courier: курьер с умениями\n :return: может или нет\n \"\"\"\n for skill in obj.skills:\n if skill not in courier.skills:\n return False\n return True\n\n @staticmethod\n def __validate_courier(state: State, route: Route) -> bool:\n \"\"\" Проверяем, что курьер еще жив\n :param state: текущее состояние тура полностью\n :param route: маршрут\n :return: все норм или нет\n \"\"\"\n # 1. проверяем время работы\n start_shift, end_shift = route.courier.work_time.window\n start_time = route.start_time\n if not (start_shift <= start_time + state.travel_time <= end_shift):\n return False\n # 2. проверяем максимальную дистанцию\n if state.distance > route.courier.max_distance:\n return False\n # 3. проверяем на перевес\n size_v = len(state.value)\n for i in range(size_v):\n if state.value[i] > route.courier.value[i]:\n return False\n return True\n\n @staticmethod\n def __validate_storage(travel_time: int, storage: Storage, route: Route) -> bool:\n \"\"\" Проверяем, что поездка на склад возможна\n :param travel_time: текущее время с начала работы маршрута\n :param storage: склад\n :param route: маршрут\n :return: может или нет\n \"\"\"\n start_shift, end_shift = storage.work_time.window\n start_time = route.start_time\n if not (start_shift <= start_time + travel_time <= end_shift):\n return False\n return True\n\n @staticmethod\n def __validate_job(travel_time: int, job: Job, route: Route) -> bool:\n \"\"\" Проверяем, что поездка на эту задачу возможна\n :param travel_time: текущее время с начала работы маршрута\n :param job: заказ\n :param route: маршрут\n :return: может или нет\n \"\"\"\n start_time = route.start_time\n for window in job.time_windows:\n start_shift, end_shift = window.window\n if start_shift <= start_time + travel_time <= end_shift:\n return True\n return False\n\n @staticmethod\n def __storages(location: int, state: State, route: Route) -> Optional[List[Storage]]:\n \"\"\" Выдает склады в порядке увеличения дальности поездки к нему\n :param location: текущая позиция\n :param state: ��екущее состояние тура\n :param route: маршрут\n :return: список доступных складов для поездки курьеров в порядке возрастания дальности\n \"\"\"\n matrix = route.matrix\n states: List[Tuple[int, int]] = [] # время/индекс склада\n\n for i, storage in enumerate(route.courier.storages): # только по складам, доступным курьеру\n # 1. Склад непустой\n if len(storage.unassigned_jobs) == 0:\n continue\n # 2. Курьер подходит\n if not ProblemMdvrp.__validate_skills(storage, route.courier):\n continue\n tt = matrix.travel_time[location][storage.location.matrix_id]\n d = matrix.distance[location][storage.location.matrix_id]\n new_state = State(tt, d, ProblemMdvrp.__cost(tt, d, route))\n tmp_state = state + new_state\n # 3. Доедет\n if not ProblemMdvrp.__validate_courier(tmp_state, route):\n continue\n if not ProblemMdvrp.__validate_storage(tmp_state.travel_time, storage, route):\n continue\n states.append((tt, i))\n\n if not states:\n return None\n states = sorted(states)\n s_storages = [route.courier.storages[0]] * len(states)\n # 4. Сортируем\n for i, state in enumerate(states):\n s_storages[i] = route.courier.storages[state[1]]\n return s_storages\n\n @staticmethod\n def __init_track(location: int, state: State, route: Route) -> Optional[Tuple[State, Track]]:\n \"\"\" Доехать до ближайщего непустого склада + создать подмаршрут\n :param location: текущая позиция\n :param state: текущее состояния полное\n :param route: маршрут\n :return: Новый подмаршрут\n \"\"\"\n curr_storages = ProblemMdvrp.__storages(location, state, route)\n if curr_storages is None:\n return None\n\n for storage in curr_storages:\n # 1. Едем на склад\n tmp_state = ProblemMdvrp.__go_storage(location, state, storage, route)\n track = Track(storage)\n # 2. Пытаемся доехать хоть куда-то\n tmp_state = ProblemMdvrp.__choose_job(storage.location.matrix_id, state + tmp_state, track, route)\n if tmp_state is not None:\n return tmp_state, track\n\n return None\n\n @staticmethod\n def __choose_job(curr_point: int, state: State, track: Track, route: Route) -> Optional[State]:\n \"\"\" Получаем оценку стоимости поезки на следующую задачу; job will be added into Track\n :param curr_point: текущая позиция\n :param state: текущее полное состояние\n :param track: текущий подмаршрут\n :param route: маршрут\n :return: новое состояние тура\n \"\"\"\n best_state: Optional[State] = None\n index = -1\n\n for i, job in enumerate(track.storage.unassigned_jobs):\n # 0. Ищем лучший валидный\n tmp_state = ProblemMdvrp.__go_job(curr_point, state, job, track.storage, route)\n if tmp_state is None:\n continue\n tmp_state += state\n # 1. Из него мы должны успеть вернуться\n end = ProblemMdvrp.__end(job.location.matrix_id, route)\n if not ProblemMdvrp.__validate_courier(tmp_state + end, route):\n continue\n # 2. Выбираем лучший\n if best_state is None or tmp_state < best_state:\n best_state, index = tmp_state, i\n\n if index == -1:\n return None\n job = track.storage.unassigned_jobs.pop(index)\n track.storage.assigned_jobs.append(job)\n track.jobs.append(job)\n return best_state\n\n @staticmethod\n def __go_storage(curr_point: int, state: State, storage: Storage, route: Route) -> Optional[State]:\n \"\"\" Оценка стоимости поездки на склад\n :param curr_point: текущая позиция\n :param state: полное состояние тура\n :param storage: склад\n :param route: маршрут\n :return: на сколько увеличится State\n \"\"\"\n tt = route.matrix.travel_time[curr_point][storage.location.matrix_id] + storage.load\n d = route.matrix.distance[curr_point][storage.location.matrix_id]\n if not ProblemMdvrp.__validate_storage(state.travel_time + tt, storage, route):\n return None\n return State(tt, d, ProblemMdvrp.__cost(tt, d, route), None)\n\n @staticmethod\n def __go_job(curr_point: int, state: State, job: Job, storage: Storage, route: Route) -> Optional[State]:\n \"\"\" Оценка стоимости поездки на следующую задачу\n :param curr_point: текущая позиция\n :param state: полное состояние\n :param job: заказ\n :param storage: склад\n :param route: маршрут\n :return: на сколько увеличится State\n \"\"\"\n tt = route.matrix.travel_time[curr_point][job.location.matrix_id] + job.delay\n d = route.matrix.distance[storage.location.matrix_id][job.location.matrix_id]\n if not ProblemMdvrp.__validate_job(state.travel_time + tt, job, route):\n return None\n tmp = State(tt, d, ProblemMdvrp.__cost(tt, d, route), job.value.copy())\n if not ProblemMdvrp.__validate_courier(tmp + state, route):\n return None\n return tmp\n","sub_path":"solvers/madrich/problems/mdvrp_demo/mdvrp_problem.py","file_name":"mdvrp_problem.py","file_ext":"py","file_size_in_byte":15962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"290546828","text":"import sys\nimport codecs\nimport csv\nfrom datetime import datetime\nfrom pytz import timezone\nimport datetime\n\ndef print_err(message):\n print(message, file=sys.stderr)\n\neastern = timezone('US/Eastern')\npacific = timezone('US/Pacific')\ninfmt = '%m/%d/%y %H:%M:%S %p'\noutfmt = '%Y-%m-%dT%H:%M:SS.%f'\n#ISO 8601 format, YYYY-MM-DDTHH:MM:SS.mmmmmm or, if microsecond is 0, YYYY-MM-DDTHH:MM:SS\n\ncsv_reader = csv.DictReader(sys.stdin)\nheader = csv_reader.fieldnames\ncsv_writer = csv.DictWriter(sys.stdout, fieldnames=header)\n\n# Timestamp,Address,ZIP,FullName,FooDuration,BarDuration,TotalDuration,Notes\ncsv_writer.writeheader()\nfor row in csv_reader:\n outrow = {}\n try:\n # * The Timestamp column should be formatted in ISO-8601 format.\n # * The Timestamp column should be assumed to be in US/Pacific time;\n # please convert it to US/Eastern.\n # 4/1/11 11:00:00 AM\n dt = datetime.datetime.strptime(row['Timestamp'], '%m/%d/%y %H:%M:%S %p')\n loc_dt = pacific.localize(dt)\n eastern_dt = loc_dt.astimezone(eastern)\n outrow['Timestamp'] = eastern_dt.isoformat()\n\n # * The Address column should be passed through as is, except for\n # Unicode validation. Please note there are commas in the Address\n # field; your CSV parsing will need to take that into account. Commas\n # will only be present inside a quoted string.\n outrow['Address'] = row['Address']\n\n # * All ZIP codes should be formatted as 5 digits. If there are less\n # than 5 digits, assume 0 as the prefix.\n outrow['ZIP'] = '{:05d}'.format(int(row['ZIP']))\n\n # * All name columns should be converted to uppercase. There will be\n # non-English names.\n outrow['FullName'] = row['FullName'].upper()\n\n # * The columns `FooDuration` and `BarDuration` are in HH:MM:SS.MS\n # format (where MS is milliseconds); please convert them to a floating\n # point seconds format.\n # double seconds = milliseconds / 1000.0;\n split_date = row['FooDuration'].split('.')\n fd_dt = datetime.datetime.strptime(split_date[0], '%H:%M:%S')\n milli_sec = int(split_date[1])\n fd_dt = fd_dt + datetime.timedelta(milliseconds=milli_sec)\n outrow['FooDuration'] = \"{}.{}\".format(fd_dt.strftime('%H:%M:%S'), int(milli_sec))\n\n # * The columns `FooDuration` and `BarDuration` are in HH:MM:SS.MS\n # format (where MS is milliseconds); please convert them to a floating\n # point seconds format.\n split_date = row['BarDuration'].split('.')\n bd_dt = datetime.datetime.strptime(split_date[0], '%H:%M:%S')\n milli_sec = int(split_date[1])\n bd_dt = bd_dt + datetime.timedelta(milliseconds=milli_sec)\n outrow['BarDuration'] = \"{}.{}\".format(bd_dt.strftime('%H:%M:%S'), int(milli_sec))\n\n # * The column \"TotalDuration\" is filled with garbage data. For each\n # row, please replace the value of TotalDuration with the sum of\n # FooDuration and BarDuration.\n td_dt = fd_dt + datetime.timedelta(hours=bd_dt.hour, minutes=bd_dt.minute, seconds=bd_dt.second, microseconds=bd_dt.microsecond)\n milli_sec = td_dt.microsecond / 1000.0\n outrow['TotalDuration'] = \"{}.{}\".format(td_dt.strftime('%H:%M:%S'), int(milli_sec))\n\n\n # * The column \"Notes\" is free form text input by end-users; please do\n # not perform any transformations on this column. If there are invalid\n # UTF-8 characters, please replace them with the Unicode Replacement\n # Character.\n outrow['Notes'] = row['Notes'].encode('utf-8', 'replace').decode('utf-8')\n #outrow['Notes'] = row['Notes'].encode('ascii', 'replace').decode('ascii')\n #outrow['Notes'] = row['Notes'].encode('ascii', 'replace')\n \n #csv_writer.writerow(row)\n csv_writer.writerow(outrow)\n except ValueError as err:\n print_err(err)\n","sub_path":"cli_process_csv.py","file_name":"cli_process_csv.py","file_ext":"py","file_size_in_byte":3964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"260267284","text":"def troca_caixa(texto):\n '''\n :param texto: um texto em formato string, para ser convertido\n :returns: um novo texto, convertido conforme a regra a seguir.\n\n Deve retornar um novo texto em que as vogais ficam em caixa alta (maiúsculas)\n e as consoates ficam em caixa baixa (minúsculas)\n\n OBS: Não pode ser utilizado o método replace() da classe string.\n Dica: Crie uma nova string (vazia) e percorra a string 'texto'. \n Verifique se cada caracter é uma vogal, e grave na nova string o caracter\n em maiúsculo ou minúsculo, conforme a o caso.\n\n Exemplo:\n - texto: Eu amo estudar no IFC.\n - Deve retornar:\n EU AmO EstUdAr nO Ifc.\n '''\n ana_linda = texto.lower()\n padoan_lind = ''\n karen = ['a', 'e', 'i', 'o', 'u']\n for i in ana_linda:\n if i in karen:\n padoan_lind += i.upper()\n else:\n padoan_lind += i\n return padoan_lind\n \ndef numero_legal(numero):\n '''\n params numero: um numero em formato string.\n returns: um valor boolean (True ou False), conforme regra a seguir.\n\n Se a soma dos dígitos do número for par, retorne True, pois isso é legal.\n Caso contrário, retorne False.\n\n Dica: Note que o número já está em formato string\n \n Exemplo:\n numero = 3467 -> True, pois 3+4+6+7 = 20 (que é par)\n numero = 1235 -> False, pois 1+2+3+5 = 11 (que é ímpar)\n '''\n lista_de_numero = []\n for i in numero:\n i = int(i)\n lista_de_numero.append(i)\n if sum(lista_de_numero) % 2 == 0:\n return True\n else:\n return False\n \n\ndef numero_chato(numero):\n '''\n params numero: um numero em formato string.\n returns: um valor boolean (True ou False), conforme regra a seguir.\n\n Não pode haver dois dígitos consecutivos idênticos, porque isso é chato.\n Se tiverem dois número consectivos, retorne True. Caso contrário, retorne False.\n\n Dica: Note que o número já está em formato string\n \n Exemplo:\n numero = 3667 -> True, pois o dígito 6 aparece consecutivo.\n numero = 1231 -> False, pois não possui dígito consecutivos.\n '''\n lis_num = []\n for i in numero:\n i = int(i)\n lis_num.append(i)\n if sum(lis_num) % 2 != 0:\n return True\n else:\n return False\n\ndef encontra_caracter(texto, caracter):\n '''\n params texto: um texto em formato string\n params caracter: um caracter em formato string\n returns: retorna a posição que um caracter está em uma string.\n\n Deve procurar o caracter na string texto e informar a posição que o caracter aparece pela primeira vez. \n\n Exemplo:\n encontra_caracter('Eduardo', 'a') -> 3\n encontra_caracter('Eduardo', '0') -> 6\n encontra_caracter('Eduardo', 'z') -> None\n\n Dica:\n Se o código não retornar nada, será considerado None\n '''\n for i, a in enumerate(texto):\n if a == caracter:\n return i\n\ndef encontra_menor_quantidade_de_chuva(chuvas_meses):\n '''\n params chuvas_meses: uma lista com a quantidade de chuva (em mm) de cada mês do ano\n returns: um valor int, correspondente ao menor volume de chuvas.\n\n Importante:\n Não podem ser usadas funções prontas da linguagem, com min() ou sort().\n\n Exemplo\n encontra_menor_quantidade_de_chuva([20, 10, 30, 6, 40]) -> deve retornar 6, pois esse é o menor volume de chuvas.\n '''\n menor = chuvas_meses[1]\n for i in chuvas_meses:\n if i < menor:\n menor = i\n return menor\n \ndef encontra_mes_com_menos_chuva(chuvas_meses):\n '''\n params chuvas_meses: uma lista com a quantidade de chuva (em mm) de cada mês do ano\n returns: um valor string, correspondente ao mês com a menor quantidade de chuva.\n\n Descubra (sem utilizar funções prontas da linguagem) em\n qual mês caiu a menor quantidade de chuvas e devolva o\n nome desse mês. \n\n Dica: crie uma lista com o nome dos meses e use a posição\n da lista com as chuvas para chegar no nome do mês desejado.\n\n Exemplo:\n encontra_mes_com_menos_chuva([20, 10, 6, 8, 15, 21, 12, 16, 18, 25, 30, 1]) -> 'mar'\n\n Os meses devem estar no formato 'jan', 'fev', 'mar', 'abr', ...\n '''\n meses = ['jan', 'fev', 'mar', 'abr', 'mai', 'jun', 'jul', 'ago', 'set', 'out', 'nov', 'dez']\n menor = chuvas_meses[0]\n for d, i in enumerate(chuvas_meses):\n if i < menor:\n menor = i\n mes = meses[d]\n return mes\n\ndef quantidade_de_pares(valor_inicial,valor_final):\n '''\n params valor_inicial: um valor inteiro\n params valor_final: um valor inteiro\n returns: um valor inteiro, conforme regra a seguir\n\n Deve retornar a quantidade de números pares num intervalo.\n Importante:\n Inclua os valores inicial e final do intervalo.\n\n Exemplo:\n quantidade_de_pares(1, 6) -> 3 (pois entre 1 e 6, incluindo os extremos, encontramos os pares 2, 4, e 6)\n '''\n pares = []\n for a in range(valor_inicial, valor_final + 1):\n if a % 2 == 0:\n pares.append(a)\n return len(pares)\n \n\n# Área de testes: só mexa aqui se souber o que está fazendo!\nacertos = 0\ntotal = 0\n\n\ndef test(obtido, esperado):\n global acertos, total\n total += 1\n if obtido != esperado:\n prefixo = '\\033[31m%s' % ('Falhou')\n else:\n prefixo = '\\033[32m%s' % ('Passou')\n acertos += 1\n print('%s Esperado: %s \\tObtido: %s\\033[1;m' % (prefixo, repr(esperado),\n repr(obtido)))\n\n\ndef main():\n print(' Troca caixa:')\n test(troca_caixa(\"Araquari\"), \"ArAqUArI\") # normal\n test(troca_caixa(\"Caxias do Sul\"), \"cAxIAs dO sUl\") # com espaços\n\n print(' Número legal:')\n test(numero_legal(\"8888\"), True)\n test(numero_legal(\"8881\"), False)\n\n print(' Número chato:')\n test(numero_chato(\"8823\"), True)\n test(numero_chato(\"8231\"), False)\n\n print(' Encontra caracter:')\n test(encontra_caracter(\"--*--\", \"*\"), 2)\n test(encontra_caracter(\"19/05/2014\", \"9\"), 1)\n test(encontra_caracter(\"19/05/2014\", \".\"), None)\n\n print('Encontra menor quantidade de chuva:')\n test(encontra_menor_quantidade_de_chuva([10,20,15,9,12,25,23,14,21,20,16,17]), 9) \n\n print('Encontra mês com menos chuva:')\n test(encontra_mes_com_menos_chuva([10,20,15,9,12,25,23,14,21,20,16,17]), 'abr') \n test(encontra_mes_com_menos_chuva([30,20,15,19,12,25,23,14,21,20,16,7]), 'dez')\n\n print('Quantidade de pares:')\n test(quantidade_de_pares(2,3), 1)\n test(quantidade_de_pares(2,4), 2)\n test(quantidade_de_pares(1,10), 5)\n\n\nif __name__ == '__main__':\n main()\n print(\"\\n%d Testes, %d Ok, %d Falhas: Nota %.1f\" % (\n total, acertos, total - acertos, float(acertos * 10) / total))\n if total == acertos:\n print(\"Parabéns, seu programa rodou sem falhas!\")\n","sub_path":"1INFO2-avaliacao4-AnaClaraStupp.py","file_name":"1INFO2-avaliacao4-AnaClaraStupp.py","file_ext":"py","file_size_in_byte":6845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"570262179","text":"import numpy as np\nimport time\nimport cv2\nfrom threading import Thread\nfrom datetime import datetime\nimport random\nimport argparse\n\nfrom openvino.inference_engine import IENetwork, IEPlugin\n\n#exemple:\n#python3 openvino_inference_ssd300.py --mode=tf_gpu --model_name=../ssd_keras_files/plate_inference_graph_retrained/frozen_inference_graph --classes=\"plates\" --file=../ssd_keras_files/vehiculesutilitairesW.png --confidence=0.2\n#python3 openvino_inference_ssd300.py --mode=ov --model_name=/home/root/ssd_keras_files/frozen_inference_graph --classes=\"plates\" --file=\"/home/root/ssd_keras_files/Test AR DOD RC500S A6.mp4\" --confidence=0.2\nparser = argparse.ArgumentParser(description='Make inference on SSD 300 model TensorFlow or OpenVINO')\nparser.add_argument(\"--mode\", help=\"tf for Tensorflow, tf_gpu for tensorflow with GPU, or ov for OpenVINO\", required=False, default=\"tf\", choices=('tf', 'tf_gpu', 'ov', 'tflite'))\nparser.add_argument(\"--model_name\", help=\"The path to the model (Do not write the extension .pb, .bin, .xml ...)\", required=True)\nparser.add_argument(\"--classes\", help=\"Names of object classes to be downloaded\", required=True)\nparser.add_argument(\"--file\", help=\"Path to the file (Image or Video)\", required=True)\nparser.add_argument(\"--confidence\", help=\"The confidence threshold for predictions\", required=False, type=float, default=0.5)\nparser.add_argument(\"--display\", help=\"Bool to either display or not the predictions\", required=False, default=True, choices=(True, False))\n\nargs = parser.parse_args()\nrun_mode = args.mode\nmodel_name = args.model_name\nfile_path = args.file\nfile_is_image = (cv2.imread(file_path) is not None)\nprint(file_is_image)\nconfidence_threshold = args.confidence\ndisplay_bool = args.display\nclasses = []\nfor class_name in args.classes.split(','):\n classes.append(class_name)\n\nn_classes = len(classes) # Number of positive classes\nclasses_n_background = ['background'] + classes\ncolors = [ (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) for i in range(len(classes)) ] #Creation of random colors according to the positive class number\n\n\n#SSD300 PARAMETERS\nimg_height = 300\nimg_width = 300\n\nclass CountsPerSec:\n \"\"\"\n Class that tracks the number of occurrences (\"counts\") of an\n arbitrary event and returns the frequency in occurrences\n (counts) per second. The caller must increment the count.\n \"\"\"\n\n def __init__(self):\n self._start_time = None\n self._num_occurrences = 0\n\n def start(self):\n self._start_time = datetime.now()\n return self\n\n def increment(self):\n self._num_occurrences += 1\n\n def countsPerSec(self):\n elapsed_time = (datetime.now() - self._start_time).total_seconds()\n return self._num_occurrences / elapsed_time\n \n def reset(self):\n self._start_time = datetime.now()\n self._num_occurrences = 0\n\nclass VideoGet:\n \"\"\"\n Class that continuously gets frames from a VideoCapture object\n with a dedicated thread.\n \"\"\"\n\n def __init__(self, src=0):\n self.stream = cv2.VideoCapture(src)\n (self.grabbed, self.frame) = self.stream.read()\n self.stopped = False\n \n def start(self):\n Thread(target=self.update, args=()).start()\n return self\n \n def update(self):\n # keep looping infinitely until the thread is stopped\n while True:\n # if the thread indicator variable is set, stop the thread\n if self.stopped:\n return\n \n # otherwise, read the next frame from the stream\n (self.grabbed, self.frame) = self.stream.read()\n \n def read(self):\n # return the frame most recently read\n return self.frame\n\n def stop(self):\n self.stopped = True\n\nclass VideoShow:\n \"\"\"\n Class that continuously shows a frame using a dedicated thread.\n \"\"\"\n\n def __init__(self, frame=None):\n self.frame = frame\n self.stopped = False\n\n def start(self):\n Thread(target=self.show, args=()).start()\n return self\n\n def show(self):\n while not self.stopped:\n cv2.imshow(\"Video\", self.frame)\n if cv2.waitKey(1) == ord(\"q\"):\n self.stopped = True\n\n def stop(self):\n self.stopped = True\n\ndef putIterationsPerSec(frame, iterations_per_sec):\n \"\"\"\n Add iterations per second text to lower-left corner of a frame.\n \"\"\"\n\n cv2.putText(frame, \"{:.0f} iterations/sec\".format(iterations_per_sec), (0, frame.shape[0]-10), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 255, 255))\n return frame\n\ndef run_inference_for_single_image(image, sess):\n start = time.time()\n #to set shape to [1, width, height, 3] instead of [width, height, 3]\n #tensorflow model already contain reshape function using while loop\n img_reshaped = np.expand_dims(image, axis=0)\n end = time.time()\n print(\"\\t[INFO] Reshape took \" + str((end-start)*1000) + \" ms\")\n\n start = time.time()\n \"\"\"\n with graph.as_default():\n with tf.Session() as sess:\n # Get handles to input and output tensors\n ops = tf.get_default_graph().get_operations()\n all_tensor_names = {output.name for op in ops for output in op.outputs}\n tensor_dict = {}\n for key in ['num_detections', 'detection_boxes', 'detection_scores', 'detection_classes']:\n tensor_name = key + ':0'\n if tensor_name in all_tensor_names:\n tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(\n tensor_name)\n\n image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')\n end = time.time()\n print(\"\\t[INFO] set input and output \" + str((end-start)*1000) + \" ms\")\n\n start = time.time()\n # Run inference\n output_dict = sess.run(tensor_dict, feed_dict={image_tensor: img_reshaped})\n end = time.time()\n print(\"\\t[INFO] net forward took \" + str((end-start)*1000) + \" ms\")\n\n start = time.time()\n # all outputs are float32 numpy arrays, so convert types as appropriate\n output_dict['num_detections'] = int(output_dict['num_detections'][0])\n output_dict['detection_classes'] = output_dict['detection_classes'][0].astype(np.int64)\n output_dict['detection_boxes'] = output_dict['detection_boxes'][0]\n output_dict['detection_scores'] = output_dict['detection_scores'][0]\n \"\"\"\n # Get handles to input and output tensors\n ops = sess.graph.get_operations()\n all_tensor_names = {output.name for op in ops for output in op.outputs}\n tensor_dict = {}\n for key in ['num_detections', 'detection_boxes', 'detection_scores', 'detection_classes']:\n tensor_name = key + ':0'\n if tensor_name in all_tensor_names:\n tensor_dict[key] = sess.graph.get_tensor_by_name(\n tensor_name)\n\n image_tensor = sess.graph.get_tensor_by_name('image_tensor:0')\n end = time.time()\n print(\"\\t[INFO] set input and output \" + str((end-start)*1000) + \" ms\")\n\n start = time.time()\n # Run inference\n output_dict = sess.run(tensor_dict, feed_dict={image_tensor: img_reshaped})\n end = time.time()\n print(\"\\t[INFO] net forward took \" + str((end-start)*1000) + \" ms\")\n\n start = time.time()\n # all outputs are float32 numpy arrays, so convert types as appropriate\n output_dict['num_detections'] = int(output_dict['num_detections'][0])\n output_dict['detection_classes'] = output_dict['detection_classes'][0].astype(np.int64)\n output_dict['detection_boxes'] = output_dict['detection_boxes'][0]\n output_dict['detection_scores'] = output_dict['detection_scores'][0]\n\n y_pred = np.column_stack( \n (np.column_stack(\n (output_dict['detection_classes'],\n output_dict['detection_scores'])\n ),\n output_dict['detection_boxes'])\n )\n \n end = time.time()\n print(\"\\t[INFO] compute numpy array took \" + str((end-start)*1000) + \" ms\")\n #change the order for xmin, xmax, ymin, ymax\n return y_pred[...,[0,1,3,2,5,4]]\n\ndef run_inference_for_single_image_tflite(image, interpreter):\n start = time.time()\n #to set shape to [1, width, height, 3] instead of [width, height, 3]\n #tensorflow model already contain reshape function using while loop\n img_reshaped = cv2.resize(image, (img_width, img_height)) #set to 300 * 300 img input\n img_reshaped = np.expand_dims(img_reshaped, axis=0) # add one dim to the shape (300,300,3) to (1,300,300,3)\n img_reshaped = (2.0 / 255.0) * img_reshaped - 1.0 \n img_reshaped = img_reshaped.astype('float32')\n end = time.time()\n print(\"\\t[INFO] Reshape took \" + str((end-start)*1000) + \" ms\")\n\n start = time.time()\n\n input_details = interpreter.get_input_details()\n output_details = interpreter.get_output_details()\n\n interpreter.set_tensor(input_details[0]['index'], img_reshaped)\n end = time.time()\n print(\"\\t[INFO] set input\" + str((end-start)*1000) + \" ms\")\n\n start = time.time()\n # Run inference\n interpreter.invoke()\n end = time.time()\n print(\"\\t[INFO] net forward took \" + str((end-start)*1000) + \" ms\")\n\n start = time.time()\n # all outputs are float32 numpy arrays, so convert types as appropriate\n num = int(interpreter.get_tensor(output_details[3]['index'])[0])\n classes = interpreter.get_tensor(output_details[1]['index'])[0].astype(np.int64) + 1\n boxes = interpreter.get_tensor(output_details[0]['index'])[0]\n scores = interpreter.get_tensor(output_details[2]['index'])[0]\n\n y_pred = np.column_stack( \n (np.column_stack(\n (classes,\n scores)\n ),\n boxes)\n )\n \n end = time.time()\n print(\"\\t[INFO] compute numpy array took \" + str((end-start)*1000) + \" ms\")\n #change the order for xmin, xmax, ymin, ymax\n return y_pred[...,[0,1,3,2,5,4]]\n\ndef net_forward_cv2_openvino(frame, net):\n #to set shape to [1, width, height, 3] instead of [width, height, 3]\n #openVINO model does not contain reshape function because tensorflow uses while loop which OpenVINO does not support\n start = time.time()\n blob = cv2.dnn.blobFromImage(frame,1,(img_width,img_height))\n #print(blob.shape)\n print(blob.dtype)\n end = time.time()\n print(\"\\t[INFO] Reshape took \" + str((end-start)*1000) + \" ms\")\n \n # set the blob as input to the network and perform a forward-pass to\n # obtain our output classification\n start = time.time()\n net.setInput(blob)\n end = time.time()\n print(\"\\t[INFO] set input \" + str((end-start)*1000) + \" ms\")\n start = time.time()\n #pred : num_detections, detection_classes, detection_scores, detection_boxes (ymin, xmin, ymax, xmax)\n y_preds = net.forward()\n #print(y_preds)\n end = time.time()\n print(\"\\t[INFO] net forward took \" + str((end-start)*1000) + \" ms\")\n \n y_pred_arrange = np.squeeze(y_preds)[:,1:]\n\n return y_pred_arrange\n\ndef net_forward_openvino(frame, net):\n #to set shape to [1, width, height, 3] instead of [width, height, 3]\n #openVINO model does not contain reshape function because tensorflow uses while loop which OpenVINO does not support\n start = time.time()\n img_reshaped = np.expand_dims(np.moveaxis(cv2.resize(frame,(img_width,img_height)), -1, 0), axis=0) #set the shape from (3, 300, 300) to (1, 300, 300, 3)\n #print(img_reshaped.shape)\n end = time.time()\n print(\"\\t[INFO] Reshape took \" + str((end-start)*1000) + \" ms\")\n \n start = time.time()\n #pred : num_detections, detection_classes, detection_scores, detection_boxes (ymin, xmin, ymax, xmax)\n y_preds = net.infer({list(net.requests[0].inputs.keys())[0]: img_reshaped})\n #print(y_preds)\n end = time.time()\n print(\"\\t[INFO] net infer took \" + str((end-start)*1000) + \" ms\")\n \n y_pred_arrange = np.squeeze(list(y_preds.values())[0])[:,1:]\n\n return y_pred_arrange\n\ndef predict_on_image(frame, net_or_sess, run_mode):\n start = time.time()\n if(run_mode == \"ov\"):\n #y_pred = net_forward_cv2_openvino(frame, net_or_sess)\n y_pred = net_forward_openvino(frame, net_or_sess)\n elif(run_mode == \"tflite\"):\n y_pred = run_inference_for_single_image_tflite(frame, net_or_sess)\n else:\n y_pred = run_inference_for_single_image(frame, net_or_sess)\n\n end = time.time()\n print(\"--> Total Prediction took \" + str((end-start)*1000) + \" ms\")\n\n start = time.time()\n y_pred_thresh = []\n for k in range(y_pred.shape[0]):\n if(y_pred[k][1] > confidence_threshold):\n y_pred_thresh.append(y_pred[k])\n\n y_pred_thresh = np.array(y_pred_thresh)\n end = time.time()\n print(\"[INFO] keep threshold values array took \" + str((end-start)*1000) + \" ms\")\n\n if y_pred_thresh.size != 0:\n np.set_printoptions(precision=2, suppress=True, linewidth=90)\n print(\"Predicted boxes:\\n\")\n print(' class score xmin ymin xmax ymax')\n print(y_pred_thresh)\n \n return y_pred_thresh\n\n# Display the image and draw the predicted boxes onto it.\ndef display_pediction_image(frame, y_pred_thresh):\n # Visualize detected bounding boxes.\n for box in y_pred_thresh:\n classId = int(box[0])-1\n score = box[1]\n color = colors[classId]\n xmin = abs(int(box[2] * frame.shape[1]))\n ymin = abs(int(box[3] * frame.shape[0]))\n xmax = abs(int(box[4] * frame.shape[1]))\n ymax = abs(int(box[5] * frame.shape[0]))\n cv2.blur(src=frame[ymin:ymax, xmin:xmax],dst=frame[ymin:ymax, xmin:xmax], ksize=(20,10))\n cv2.rectangle(frame, (xmin, ymin), (xmax, ymax), color, thickness=2)\n label = '{}: {:.2f}'.format(classes[classId], box[1])\n cv2.rectangle(frame, (xmin, ymin-2), (int(xmin+len(label)*8.5), ymin-15), (255,255,255), thickness=cv2.FILLED)\n cv2.putText(frame, label, (xmin, ymin-2), cv2.FONT_HERSHEY_PLAIN, 1.0, color, 1)\n\ndef run_on_file(file_path, net_or_graph, run_mode) :\n start = time.time()\n cap = cv2.VideoCapture(file_path,cv2.CAP_FFMPEG)\n end = time.time()\n print(\"[INFO] video capture took \" + str((end-start)*1000) + \" ms\")\n cps = CountsPerSec().start()\n\n while True:\n start1 = time.time()\n (grabbed, frame) = cap.read()\n end = time.time()\n print(\"[INFO] Read image took \" + str((end-start1)*1000) + \" ms\")\n start = time.time()\n if not grabbed or cv2.waitKey(1) == ord(\"q\"):\n break\n end = time.time()\n print(\"[INFO] Wait key took \" + str((end-start)*1000) + \" ms\")\n\n y_pred_thresh = predict_on_image(frame, net_or_graph, run_mode)\n\n start = time.time()\n if file_is_image is not True :\n frame = putIterationsPerSec(frame, cps.countsPerSec())\n end = time.time()\n print(\"[INFO] put fps \" + str((end-start)*1000) + \" ms\")\n\n start = time.time()\n display_pediction_image(frame, y_pred_thresh)\n end = time.time()\n print(\"[INFO] add bounding box took \" + str((end-start)*1000) + \" ms\")\n start = time.time()\n cv2.imshow(\"Inference on \"+file_path, frame)\n end = time.time()\n print(\"[INFO] display image took \" + str((end-start)*1000) + \" ms\")\n cps.increment()\n\n end = time.time()\n print(\"[TOTAL]\" + str((end-start1)*1000) + \" ms\\n\")\n \n\n if file_is_image is True :\n cv2.waitKey()\n cv2.destroyAllWindows()\n\nprint(\"First pass through the model to load it in RAM\")\n## IF OpenVino\nif(run_mode == \"ov\") :\n \"\"\"\n net = cv2.dnn.readNet( model_name+\".bin\",model_name+\".xml\")\n net.setPreferableBackend(cv2.dnn.DNN_BACKEND_INFERENCE_ENGINE) #\n net.setPreferableTarget(cv2.dnn.DNN_TARGET_MYRIAD)\n\n #First pass of the network with an empty array to allocate all the memory space.\n net_forward_cv2_openvino(np.zeros((300, 300, 3), dtype = \"float32\"), net)\n\n \"\"\"\n IEnet = IENetwork(model=model_name+\".xml\", weights=model_name+\".bin\")\n plugin = IEPlugin(device=\"MYRIAD\")\n net = plugin.load(network=IEnet)\n\n #First pass of the network with an empty array to allocate all the memory space.\n net_forward_openvino(np.zeros((300, 300, 3), dtype = \"float32\"), net)\n \n run_on_file(file_path, net, run_mode)\nelif(run_mode == \"tflite\") :\n import tensorflow as tf\n # Load TFLite model and allocate tensors.\n interpreter = tf.lite.Interpreter(model_name+\".tflite\")\n interpreter.allocate_tensors()\n # Get input and output tensors.\n input_details = interpreter.get_input_details()\n output_details = interpreter.get_output_details()\n\n run_inference_for_single_image_tflite(np.zeros((300, 300, 3), dtype = \"float32\"), interpreter)\n\n run_on_file(file_path, interpreter, run_mode)\nelse :\n if(run_mode == \"tf\"):\n import os\n #disable de GPU visibility for tensorflow\n os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"-1\"\n\n import tensorflow as tf\n from tensorflow.python.platform import gfile\n\n\n with tf.Session() as sess:\n # load model from pb file \n with gfile.GFile(model_name+\".pb\",'rb') as f:\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(f.read())\n sess.graph.as_default()\n g_in = tf.import_graph_def(graph_def, name=\"\") #name = \"\" remove the import/ to the layers names\n\n #First pass of the network with an empty array to allocate all the memory space.\n run_inference_for_single_image(np.zeros((300, 300, 3), dtype = \"float32\"), sess)\n\n run_on_file(file_path, sess, run_mode)","sub_path":"openvino_inference_ssd300.py","file_name":"openvino_inference_ssd300.py","file_ext":"py","file_size_in_byte":17653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"353851179","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.8 (3413)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.9-x86_64/egg/lsqfitgp/_Deriv.py\n# Compiled at: 2020-04-22 07:26:33\n# Size of source mod 2**32: 2856 bytes\nimport collections, numpy as np\n__all__ = [\n 'Deriv']\n\nclass Deriv:\n __doc__ = '\\n Class for specifying derivatives. Behaves like a dictionary str -> int,\\n where the keys represent variables and values the derivation order. An\\n empty Deriv means no derivatives. A Deriv with one single key None means\\n that the variable is implicit.\\n '\n\n def __new__(cls, *args):\n c = collections.Counter()\n if len(args) == 1:\n arg = args[0]\n if isinstance(arg, Deriv):\n return arg\n if isinstance(arg, (int, np.integer)):\n assert arg >= 0\n if arg:\n c.update({None: arg})\n elif isinstance(arg, str):\n c.update([arg])\n else:\n if np.iterable(arg):\n integer = None\n for obj in arg:\n if isinstance(obj, str):\n if integer is not None:\n if integer:\n c.update({obj: integer})\n integer = None\n else:\n c.update([obj])\n elif isinstance(obj, (int, np.integer)):\n assert obj >= 0\n integer = int(obj)\n else:\n raise TypeError('objects in iterable must be int or str')\n\n if integer:\n raise ValueError('dangling derivative order')\n else:\n raise TypeError('argument must be int, str, or iterable')\n else:\n if len(args) != 0:\n raise ValueError(len(args))\n assert all(c.values())\n self = super().__new__(cls)\n self._counter = c\n return self\n\n def __getitem__(self, key):\n return self._counter[key]\n\n def __iter__(self):\n return iter(self._counter)\n\n def __bool__(self):\n return bool(self._counter)\n\n def __eq__(self, val):\n if isinstance(val, Deriv):\n return self._counter == val._counter\n return NotImplemented\n\n @property\n def implicit(self):\n \"\"\"\n True if the derivative is trivial or the variable is implicit.\n \"\"\"\n return not self or next(iter(self._counter)) is None\n\n @property\n def order(self):\n return sum(self._counter.values())","sub_path":"pycfiles/lsqfitgp-0.0.2-py3.8/_Deriv.cpython-38.py","file_name":"_Deriv.cpython-38.py","file_ext":"py","file_size_in_byte":2819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"358703835","text":"from django.urls import path\n\nfrom .views import lista_pessoa, nova_pessoa, atualiza_pessoa, deleta_pessoa\n\nurlpatterns = [\n path('listar/', lista_pessoa, name='lista_pessoas'),\n path('novo/', nova_pessoa, name='nova_pessoa'),\n path('atualiza//', atualiza_pessoa, name='atualiza_pessoa'),\n path('detela//', deleta_pessoa, name='deleta_pessoas'),\n]","sub_path":"clientes/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"467592790","text":"import os\nimport configparser\n\nCONFIG = None\nCONFIG_FILENAME = 'configs.ini'\n\n\ndef get_configs():\n global CONFIG\n if not CONFIG:\n CONFIG = Configs()\n return CONFIG\n\n\nclass Configs:\n def __init__(self, config_path: str = None) -> None:\n \"\"\"Load configuration file.\n\n Called at the beginning of each invocation of acai.py\n\n :param config_path: config path.\n :return: None\n \"\"\"\n if not config_path:\n config_path = os.path.join(os.path.dirname(__file__),\n CONFIG_FILENAME)\n\n conf = configparser.ConfigParser()\n conf.read(config_path)\n\n self.cred_endpoint = \\\n conf.get('general', 'credential_endpoint')\n self.cred_endpoint_port = \\\n conf.getint('general', 'credential_endpoint_port') \n self.private_cred_endpoint = \\\n conf.get('phoebe', 'credential_endpoint')\n self.private_cred_endpoint_port = \\\n conf.getint('phoebe', 'credential_endpoint_port') \n self.private_cluster_endpoint = \\\n conf.get('storage', 'private_cluster_endpoint')\n self.access_key_id = \\\n conf.get('storage', 'access_key_id')\n self.secret_access_key = \\\n conf.get('storage', 'secret_access_key')\n\n def update(self, **kwargs):\n self.cred_endpoint = \\\n kwargs.get('cred_endpoint', self.cred_endpoint)\n self.cred_endpoint_port = \\\n kwargs.get('cred_endpoint_port', self.cred_endpoint_port)\n","sub_path":"acaisdk/configs.py","file_name":"configs.py","file_ext":"py","file_size_in_byte":1546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"101673222","text":"# -*- coding: utf-'8' \"-*-\"\nimport logging\nfrom urllib import parse\nfrom odoo import api, fields, models\nfrom odoo.addons.payment.models.payment_acquirer import ValidationError\nfrom odoo.addons.payment_payfast.controllers.main import PayfastController\n\n_logger = logging.getLogger(__name__)\n\n\nclass AcquirerPayfast(models.Model):\n _inherit = 'payment.acquirer'\n\n merchant_id = fields.Integer('Merchant ID', required_if_provider='payfast')\n merchant_key = fields.Char('Merchant Key', required_if_provider='payfast')\n provider = fields.Selection(selection_add=[('payfast', 'Payfast')], ondelete={'payfast': 'set default'})\n\n \n def payfast_form_generate_values(self, values):\n item_name = ''\n reference = values.get('reference')\n tx = self.env['payment.transaction'].search([('reference', '=', reference)])\n if reference == tx.reference:\n tx.request_payload = values\n sale_orders = tx.sale_order_ids\n for sale_order in sale_orders:\n for line in sale_order.order_line:\n item_name = item_name + line.product_id.name + '_'\n currency_id = self.env['res.currency'].sudo().search([('name','=','ZAR')], limit=1)\n if currency_id.id != sale_orders[0].pricelist_id.currency_id.id:\n base_price = sale_order[0].pricelist_id.currency_id._compute(sale_order[0].pricelist_id.currency_id, currency_id, values.get('amount'),True)\n base_price = float('%.2f' % (base_price))\n else:\n base_price = values.get('amount')\n base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url')\n payfast_tx_values = dict(values)\n payfast_tx_values.update({\n 'merchant_id': self.merchant_id,\n 'merchant_key': self.merchant_key,\n 'amount': base_price,\n 'item_name': item_name,\n 'return_url': '%s' % parse.urljoin(base_url, PayfastController.return_url),\n 'cancel_url': '%s' % parse.urljoin(base_url, PayfastController.cancel_url),\n 'notify_url': '%s' % parse.urljoin(base_url, PayfastController.notify_url),\n 'custom_str1': reference,\n })\n return payfast_tx_values\n\n \n def payfast_get_form_action_url(self):\n if self.state == 'enabled':\n return 'https://www.payfast.co.za/eng/process'\n else:\n return 'https://sandbox.payfast.co.za/eng/process'\n\n\nclass TxPayfast(models.Model):\n _inherit = 'payment.transaction'\n\n # --------------------------------------------------\n # FORM RELATED METHODS\n # --------------------------------------------------\n\n payfast_txn_id = fields.Char(string=\"Payfast Transaction ID\")\n request_payload = fields.Text('Request Payload')\n response_payload = fields.Text('Response Payload')\n\n @api.model\n def _payfast_form_get_tx_from_data(self, data):\n reference = data.get('custom_str1')\n tx_ids = self.env['payment.transaction'].search([('reference', '=', reference)])\n if not tx_ids or len(tx_ids) > 1:\n error_msg = 'Payfast: received data for reference %s' % (reference)\n if not tx_ids:\n error_msg += '; no order found'\n else:\n error_msg += '; multiple order found'\n _logger.error(error_msg)\n raise ValidationError(error_msg)\n\n return tx_ids[0]\n\n \n def _payfast_form_validate(self, data):\n self.write({'payfast_txn_id': data['pf_payment_id']})\n if data['status'] == 'COMPLETE':\n self._set_transaction_done()\n return True\n else:\n self.write({'state': 'error'})\n return False\n","sub_path":"payment_payfast/models/payment.py","file_name":"payment.py","file_ext":"py","file_size_in_byte":3701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"312433886","text":"# The data is provided via a class DataSimulator\nimport time\nimport os\nimport DataSimulator as DSim\nimport ECC\nimport hashlib\n\nDS = DSim.DataSimulator()\n\n\nclass blockchian:\n\n block=[]\n nonce=0\n hash=\"\"\n pre_hash=\"\"\n block_num=0\n tree=[]\n tree_proof=[]\n\n hash_block={}\n hash_code={}\n hash_msg={}\n hash_tree={}\n sample=\"cabinet meets to balance budget priorities\"\n difficult=\"0000\"\n\n def start(self):\n print(\"=========build blockchain=========\")\n for i in range(6):\n # init data\n self.init_data(i)\n\n # get data\n data = DS.getNewData()\n\n # validate data\n data = self.validate_signature(data)\n\n # build tree\n self.buildMerkleTree(data,self.tree,0,0,len(data)-1)\n self.hash_tree[i]=self.tree\n\n # proof of work\n self.proof_of_work()\n\n # build block\n self.build_block()\n\n time.sleep(1)\n\n print(self.block[i])\n #break\n print(\"\\n\")\n\n # proof\n self.proof()\n\n # init data\n def init_data(self,i):\n self.tree=[0]*1000\n self.nonce=0\n self.block_num=i\n if not self.pre_hash:\n self.pre_hash=\"0000\"*8\n else:\n self.pre_hash=self.hash\n\n # find path\n\n # validate data\n def validate_signature(self,data):\n for v in data[:]:\n check=(ECC.verify(v['pk'], v[\"msg\"], v[\"signature\"]))\n if check is not True:\n data.remove(v)\n else:\n self.hash_msg[v[\"msg\"]]={'block_num':self.block_num,'data':v}\n\n return data\n\n # build tree\n def buildMerkleTree(self,data,tree,node,start,end):\n if (start == end):\n hash=ECC.hash(str(data[start]))\n self.hash_code[hash]=data[start]\n self.tree[node]=hash;\t\n return hash\n else:\n mid=(start+end)/2\n lef_node=(2*node)+1\n rig_node=(2*node)+2\n \n lefHash=self.buildMerkleTree(data,self.tree,lef_node,start,mid)\n rigHash=self.buildMerkleTree(data,self.tree,rig_node,mid+1,end)\n hash=ECC.hash(str(lefHash + rigHash))\n self.tree[node]=hash;\t\n\n return hash\n\n # ps aux|grep start.py\n # kill\n # proof of work\n def proof_of_work(self):\n success = False\n while success is not True:\n data=str(self.nonce)+self.tree[0]+self.pre_hash\n self.hash = ECC.hash(data)\n if self.hash[:len(self.difficult)] == self.difficult:\n success=True\n break\n self.nonce+=1\n \n return hash\n\n # build block\n def build_block(self):\n rs_block={'pre_hash':self.pre_hash,'nonce':self.nonce,'merkle_tree':self.tree[0]}\n self.block.append(rs_block)\n\n # proof\n def proof(self):\n if self.sample in self.hash_msg:\n # proof of merkle_tree\n data=self.hash_msg[self.sample]\n hash=ECC.hash(str(data['data']))\n tree=self.hash_tree[data['block_num']]\n tree_hash=self.find_tree_path(tree,hash)\n\n print(\"=========merkle tree proof=========\")\n print(\"tree_leef => \"+str(self.sample)+\" => \"+str(hash))\n for v in self.tree_proof:\n print(v)\n print(\"tree_root => \"+str(tree_hash))\n print(\"\\n\")\n\n # proof block\n print(\"=========block chain route=========\")\n pre_hash=ECC.hash(str(self.block[data['block_num']]['nonce'])+tree_hash+self.block[data['block_num']]['pre_hash'])\n print(\"pre_hash => \"+str(pre_hash))\n for i in range(data['block_num']+1,6):\n print(pre_hash+\" => \"+str(self.block[i]))\n pre_hash=ECC.hash(str(self.block[i]['nonce'])+self.block[i]['merkle_tree']+self.block[i]['pre_hash'])\n\n exit()\n else:\n print(\"false\")\n\n def find_tree_path(self,tree,hash):\n \n node_index=tree.index(hash)\n node=tree[node_index]\n\n if node_index==0:\n return node\n\n # even\n if(node_index % 2) == 0:\n pair=tree[node_index-1]\n parent=ECC.hash(str(pair + node))\n self.tree_proof.append({\"pair\":pair,'node':node})\n\n # odd\n else:\n pair=tree[node_index+1]\n parent=ECC.hash(str(node + pair))\n self.tree_proof.append({\"node\":node,'pair':pair})\n\n return self.find_tree_path(tree,parent)\n\n\nobj = blockchian()\nobj.start()","sub_path":"rsa.js/homework1/start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":4629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"182235808","text":"\"\"\" kalman_filter_dependent_fusion\n\nUses the test and using taking the dependence into account. Follows Bar-Shaloms formulas for doing so.\n\"\"\"\n\nimport numpy as np\n\nfrom matplotlib import pyplot as plt\nfrom matplotlib.patches import Ellipse\nfrom stonesoup.models.measurement.linear import LinearGaussian\nfrom stonesoup.models.transition.linear import CombinedLinearGaussianTransitionModel, ConstantVelocity\nfrom stonesoup.predictor.kalman import KalmanPredictor\nfrom stonesoup.types.state import GaussianState\nfrom stonesoup.updater.kalman import KalmanUpdater\nfrom stonesoup.types.hypothesis import SingleHypothesis\nfrom stonesoup.types.track import Track\n\nfrom utils import open_object\n\nfrom data_fusion import track_to_track_association\nfrom data_fusion import track_to_track_fusion\n\nfrom trackers.calc_cross_cov_estimate_error import calc_cross_cov_estimate_error\n\n# load ground truth and the measurements\nground_truth = open_object.open_object(\"../scenarios/scenario2/ground_truth.pk1\")\nmeasurements_radar = open_object.open_object(\"../scenarios/scenario2/measurements_radar.pk1\")\nmeasurements_ais = open_object.open_object(\"../scenarios/scenario2/measurements_ais.pk1\")\n\n# load start_time\nstart_time = open_object.open_object(\"../scenarios/scenario2/start_time.pk1\")\n\n# same transition models (radar uses same as original)\ntransition_model_radar = CombinedLinearGaussianTransitionModel([ConstantVelocity(0.01), ConstantVelocity(0.01)])\ntransition_model_ais = CombinedLinearGaussianTransitionModel([ConstantVelocity(0.01), ConstantVelocity(0.01)])\n\n# same measurement models as used when generating the measurements\n# Specify measurement model for radar\nmeasurement_model_radar = LinearGaussian(\n ndim_state=4, # number of state dimensions\n mapping=(0, 2), # mapping measurement vector index to state index\n noise_covar=np.array([[1, 0], # covariance matrix for Gaussian PDF\n [0, 1]])\n)\n\n# Specify measurement model for AIS\nmeasurement_model_ais = LinearGaussian(\n ndim_state=4,\n mapping=(0, 2),\n noise_covar=np.array([[1, 0],\n [0, 1]])\n)\n\n# specify predictors\npredictor_radar = KalmanPredictor(transition_model_radar)\npredictor_ais = KalmanPredictor(transition_model_ais)\n\n# specify updaters\nupdater_radar = KalmanUpdater(measurement_model_radar)\nupdater_ais = KalmanUpdater(measurement_model_ais)\n\n# create prior, both trackers use the same starting point\nprior_radar = GaussianState([0, 1, 0, 1], np.diag([1.5, 0.5, 1.5, 0.5]), timestamp=start_time)\nprior_ais = GaussianState([0, 1, 0, 1], np.diag([1.5, 0.5, 1.5, 0.5]), timestamp=start_time)\n\n# create list for storing kalman gains\nkf_gains_radar = []\nkf_gains_ais = []\n\n# create list for storing transition_noise_covar\ntransition_covars_radar = []\ntransition_covars_ais = []\n\n# create list for storing tranisition matrixes\ntransition_matrixes_radar = []\ntransition_matrixes_ais = []\n\n# create list for storing tracks\ntracks_radar = Track()\ntracks_ais = Track()\n\n# track\nfor measurement in measurements_radar:\n prediction = predictor_radar.predict(prior_radar, timestamp=measurement.timestamp)\n hypothesis = SingleHypothesis(prediction, measurement)\n # calculate the kalman gain\n hypothesis.measurement_prediction = updater_radar.predict_measurement(hypothesis.prediction,\n measurement_model=measurement_model_radar)\n post_cov, kalman_gain = updater_radar._posterior_covariance(hypothesis)\n kf_gains_radar.append(kalman_gain)\n # get the transition model covar\n predict_over_interval = measurement.timestamp - prior_radar.timestamp\n transition_covars_ais.append(transition_model_ais.covar(time_interval=predict_over_interval))\n transition_matrixes_ais.append(transition_model_ais.matrix(time_interval=predict_over_interval))\n # update\n post = updater_radar.update(hypothesis)\n tracks_radar.append(post)\n prior_radar = tracks_radar[-1]\n\nfor measurement in measurements_ais:\n prediction = predictor_radar.predict(prior_ais, timestamp=measurement.timestamp)\n hypothesis = SingleHypothesis(prediction, measurement)\n # calculate the kalman gain\n hypothesis.measurement_prediction = updater_ais.predict_measurement(hypothesis.prediction,\n measurement_model=measurement_model_ais)\n post_cov, kalman_gain = updater_ais._posterior_covariance(hypothesis)\n kf_gains_ais.append(kalman_gain)\n # get the transition model covar\n predict_over_interval = measurement.timestamp - prior_radar.timestamp\n transition_covars_radar.append(transition_model_radar.covar(time_interval=predict_over_interval))\n transition_matrixes_radar.append(transition_model_radar.matrix(time_interval=predict_over_interval))\n # update\n post = updater_ais.update(hypothesis)\n tracks_ais.append(post)\n prior_ais = tracks_ais[-1]\n\n# FOR NOW: run track_to_track_association here, todo change pipeline flow\n# FOR NOW: run the association only when both have a new posterior (so each time the AIS has a posterior)\n# todo handle fusion when one track predicts and the other updates. (or both predicts) (Can't be done with the theory\n# described in the article)\n\ncross_cov_ij = []\ncross_cov_ji = []\ncross_cov_ji.append(np.zeros([4, 4]))\ncross_cov_ij.append(np.zeros([4, 4]))\n\n# TODO change flow to assume that the indexes decide whether its from the same iterations\n# use indexes to loop through tracks, kf_gains etc\n\ntracks_fused = []\n# tracks_fused.append(tracks_radar[0])\nfor i in range(1, len(tracks_radar)):\n # we assume that the indexes correlates with the timestamps. I.e. that the lists are 'synchronized'\n # check to make sure\n if tracks_ais[i].timestamp == tracks_radar[i].timestamp:\n # calculate the cross-covariance estimation error\n cross_cov_ji.append(calc_cross_cov_estimate_error(\n measurement_model_ais.matrix(), measurement_model_radar.matrix(), kf_gains_ais[i], kf_gains_radar[i],\n transition_matrixes_ais[i], transition_covars_ais[i], cross_cov_ji[i-1]\n ))\n cross_cov_ij.append(calc_cross_cov_estimate_error(\n measurement_model_radar.matrix(), measurement_model_ais.matrix(), kf_gains_radar[i], kf_gains_ais[i],\n transition_matrixes_radar[i], transition_covars_ais[i], cross_cov_ij[i-1]\n ))\n # TODO check whether these are the same, just transposed, aka equal (cov matrice is symmetric)\n\n # test for track association\n # same_target = track_to_track_association.test_association_dependent_tracks(tracks_radar[i], tracks_ais[i],\n # cross_cov_ij[i],\n # cross_cov_ji[i], 0.01)\n same_target = True # ignore test for track association for now\n if same_target:\n fused_posterior, fused_covar = track_to_track_fusion.fuse_dependent_tracks(tracks_radar[i], tracks_ais[\n i], cross_cov_ij[i], cross_cov_ji[i])\n tracks_fused.append((fused_posterior, fused_covar))\n\n\n# plot\nfig = plt.figure(figsize=(10, 6))\nax = fig.add_subplot(1, 1, 1)\nax.set_xlabel(\"$x$\")\nax.set_ylabel(\"$y$\")\nax.axis('equal')\nax.plot([state.state_vector[0] for state in ground_truth],\n [state.state_vector[2] for state in ground_truth],\n linestyle=\"--\",\n label='Ground truth')\nax.scatter([state.state_vector[0] for state in measurements_radar],\n [state.state_vector[1] for state in measurements_radar],\n color='b',\n label='Measurements Radar')\nax.scatter([state.state_vector[0] for state in measurements_ais],\n [state.state_vector[1] for state in measurements_ais],\n color='r',\n label='Measurements AIS')\n\n# add ellipses to the posteriors\nfor state in tracks_radar:\n w, v = np.linalg.eig(measurement_model_radar.matrix() @ state.covar @ measurement_model_radar.matrix().T)\n max_ind = np.argmax(w)\n min_ind = np.argmin(w)\n orient = np.arctan2(v[1, max_ind], v[0, max_ind])\n ellipse = Ellipse(xy=(state.state_vector[0], state.state_vector[2]),\n width=2 * np.sqrt(w[max_ind]), height=2 * np.sqrt(w[min_ind]),\n angle=np.rad2deg(orient),\n alpha=0.2,\n color='b')\n ax.add_artist(ellipse)\n\nfor state in tracks_ais:\n w, v = np.linalg.eig(measurement_model_ais.matrix() @ state.covar @ measurement_model_ais.matrix().T)\n max_ind = np.argmax(w)\n min_ind = np.argmin(w)\n orient = np.arctan2(v[1, max_ind], v[0, max_ind])\n ellipse = Ellipse(xy=(state.state_vector[0], state.state_vector[2]),\n width=2 * np.sqrt(w[max_ind]), height=2 * np.sqrt(w[min_ind]),\n angle=np.rad2deg(orient),\n alpha=0.2,\n color='r')\n ax.add_patch(ellipse)\n\nfor track_fused in tracks_fused:\n w, v = np.linalg.eig(measurement_model_ais.matrix() @ track_fused[1] @ measurement_model_ais.matrix().T)\n max_ind = np.argmax(w)\n min_ind = np.argmin(w)\n orient = np.arctan2(v[1, max_ind], v[0, max_ind])\n ellipse = Ellipse(xy=(track_fused[0][0], track_fused[0][2]),\n width=2 * np.sqrt(w[max_ind]), height=2 * np.sqrt(w[min_ind]),\n angle=np.rad2deg(orient),\n alpha=0.5,\n color='green')\n ax.add_patch(ellipse)\n\n# add ellipses to add legend todo do this less ugly\nellipse = Ellipse(xy=(0, 0),\n width=0,\n height=0,\n color='r',\n alpha=0.2,\n label='Posterior AIS')\nax.add_patch(ellipse)\nellipse = Ellipse(xy=(0, 0),\n width=0,\n height=0,\n color='b',\n alpha=0.2,\n label='Posterior Radar')\nax.add_patch(ellipse)\nellipse = Ellipse(xy=(0, 0),\n width=0,\n height=0,\n color='green',\n alpha=0.5,\n label='Posterior Fused')\nax.add_patch(ellipse)\n\nax.legend()\nax.set_title(\"Kalman filter tracking and fusion accounting for the dependence\")\nfig.show()\n# fig.savefig(\"../results/scenario2/KF_tracking_and_fusion_accounting_for_dependence.svg\")\n\n# plot estimate for estimate\n# plot\nfig_2 = plt.figure(figsize=(10, 6))\nax = fig_2.add_subplot(1, 1, 1)\nax.set_xlabel(\"$x$\")\nax.set_ylabel(\"$y$\")\nax.axis('equal')\nax.plot([state.state_vector[0] for state in ground_truth],\n [state.state_vector[2] for state in ground_truth],\n linestyle=\"--\",\n label='Ground truth')\n# ax.scatter([state.state_vector[0] for state in measurements_radar],\n# [state.state_vector[1] for state in measurements_radar],\n# color='b',\n# label='Measurements Radar')\n# ax.scatter([state.state_vector[0] for state in measurements_ais],\n# [state.state_vector[1] for state in measurements_ais],\n# color='r',\n# label='Measurements AIS')\n\nfor i in range(0, len(tracks_fused)):\n # plot measurements\n ax.scatter([measurements_radar[i+1].state_vector[0]],\n [measurements_radar[i+1].state_vector[1]],\n color='b',\n label='Measurements Radar')\n ax.scatter([measurements_ais[i+1].state_vector[0]],\n [measurements_ais[i+1].state_vector[1]],\n color='r',\n label='Measurements AIS')\n\n # plot one and one estimate\n state_radar = tracks_radar[i + 1]\n w, v = np.linalg.eig(measurement_model_radar.matrix() @ state_radar.covar @ measurement_model_radar.matrix().T)\n max_ind = np.argmax(w)\n min_ind = np.argmin(w)\n orient = np.arctan2(v[1, max_ind], v[0, max_ind])\n ellipse = Ellipse(xy=(state_radar.state_vector[0], state_radar.state_vector[2]),\n width=2 * np.sqrt(w[max_ind]), height=2 * np.sqrt(w[min_ind]),\n angle=np.rad2deg(orient),\n alpha=0.2,\n color='b')\n ax.add_artist(ellipse)\n\n state_ais = tracks_ais[i + 1]\n w, v = np.linalg.eig(measurement_model_ais.matrix() @ state_ais.covar @ measurement_model_ais.matrix().T)\n max_ind = np.argmax(w)\n min_ind = np.argmin(w)\n orient = np.arctan2(v[1, max_ind], v[0, max_ind])\n ellipse = Ellipse(xy=(state_ais.state_vector[0], state_ais.state_vector[2]),\n width=2 * np.sqrt(w[max_ind]), height=2 * np.sqrt(w[min_ind]),\n angle=np.rad2deg(orient),\n alpha=0.2,\n color='r')\n ax.add_patch(ellipse)\n\n state_fused = tracks_fused[i]\n w, v = np.linalg.eig(measurement_model_ais.matrix() @ state_fused[1] @ measurement_model_ais.matrix().T)\n max_ind = np.argmax(w)\n min_ind = np.argmin(w)\n orient = np.arctan2(v[1, max_ind], v[0, max_ind])\n ellipse = Ellipse(xy=(state_fused[0][0], state_fused[0][2]),\n width=2 * np.sqrt(w[max_ind]), height=2 * np.sqrt(w[min_ind]),\n angle=np.rad2deg(orient),\n alpha=0.5,\n color='green')\n ax.add_patch(ellipse)\n\n fig_2.show()\n input(\"Press Enter to continue...\")\n\n#\n# # add ellipses to the posteriors\n# for state in tracks_radar:\n# w, v = np.linalg.eig(measurement_model_radar.matrix() @ state.covar @ measurement_model_radar.matrix().T)\n# max_ind = np.argmax(w)\n# min_ind = np.argmin(w)\n# orient = np.arctan2(v[1, max_ind], v[0, max_ind])\n# ellipse = Ellipse(xy=(state.state_vector[0], state.state_vector[2]),\n# width=2 * np.sqrt(w[max_ind]), height=2 * np.sqrt(w[min_ind]),\n# angle=np.rad2deg(orient),\n# alpha=0.2,\n# color='b')\n# ax.add_artist(ellipse)\n#\n# for state in tracks_ais:\n# w, v = np.linalg.eig(measurement_model_ais.matrix() @ state.covar @ measurement_model_ais.matrix().T)\n# max_ind = np.argmax(w)\n# min_ind = np.argmin(w)\n# orient = np.arctan2(v[1, max_ind], v[0, max_ind])\n# ellipse = Ellipse(xy=(state.state_vector[0], state.state_vector[2]),\n# width=2 * np.sqrt(w[max_ind]), height=2 * np.sqrt(w[min_ind]),\n# angle=np.rad2deg(orient),\n# alpha=0.2,\n# color='r')\n# ax.add_patch(ellipse)\n#\n# for track_fused in tracks_fused:\n# w, v = np.linalg.eig(measurement_model_ais.matrix() @ track_fused[1] @ measurement_model_ais.matrix().T)\n# max_ind = np.argmax(w)\n# min_ind = np.argmin(w)\n# orient = np.arctan2(v[1, max_ind], v[0, max_ind])\n# ellipse = Ellipse(xy=(track_fused[0][0], track_fused[0][2]),\n# width=2 * np.sqrt(w[max_ind]), height=2 * np.sqrt(w[min_ind]),\n# angle=np.rad2deg(orient),\n# alpha=0.5,\n# color='green')\n# ax.add_patch(ellipse)\n\nfig_2.show()\n","sub_path":"trackers/kalman_filter_dependent_fusion.py","file_name":"kalman_filter_dependent_fusion.py","file_ext":"py","file_size_in_byte":15113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"108467798","text":"#!/usr/bin/python3\n\"\"\"script that adds the State object “Louisiana” to the database\nhbtn_0e_6_usa\"\"\"\n\nfrom sys import argv\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom model_state import Base, State\n\nif __name__ == \"__main__\":\n eng = create_engine(\"mysql+mysqldb://{}:{}@localhost/{}\".format(argv[1],\n argv[2],\n argv[3]),\n pool_pre_ping=True)\n Base.metadata.create_all(eng)\n Session = sessionmaker(bind=eng)\n session = Session()\n new = State(name='Louisiana')\n session.add(new)\n session.commit()\n print(new.id)\n session.close()\n","sub_path":"0x0F-python-object_relational_mapping/11-model_state_insert.py","file_name":"11-model_state_insert.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"526427198","text":"from xml.dom import minidom\n\n#doc = minidom.parse(\"alantest.XML\")\n\ndef getNodeText(node):\n nodelist = node.childNodes\n result = []\n for node in nodelist:\n if node.nodeType == node.TEXT_NODE:\n result.append(node.data)\n return ''.join(result)\ndef sldGrabber(sldname):\n\tdoc = minidom.parse(sldname)\n\tfills = doc.getElementsByTagName(\"sld:Fill\")\n\tfor fill in fills:\n\t fillcolor = fill.getElementsByTagName(\"sld:CssParameter\")[0]\n\t fillcolorv = getNodeText(fillcolor)\n\t print(\"Fill Color:%s\" %\n\t (getNodeText(fillcolor)))\n\tstrokes = doc.getElementsByTagName(\"sld:Stroke\")\n\tfor strokea in strokes:\n\t stroke = strokea.getElementsByTagName(\"sld:CssParameter\")[0]\n\t strokev = getNodeText(stroke) \n\t print(\"Stroke Value:%s\" %\n\t \t(getNodeText(stroke)))\n\tfor strokeb in strokes:\n\t stroke = strokeb.getElementsByTagName(\"sld:CssParameter\")[1]\n\t devicecont = getNodeText(stroke) \n\t print(\"Device Context:%s\" %\n\t \t(getNodeText(stroke)))\n\tfor strokec in strokes:\n\t stroke = strokec.getElementsByTagName(\"sld:CssParameter\")[2]\n\t strokewidthv = getNodeText(stroke) \n\t print(\"Stroke Width:%s\" %\n\t \t(getNodeText(stroke)))\n\tfor stroked in strokes:\n\t stroke = stroked.getElementsByTagName(\"sld:CssParameter\")[3]\n\t strokelcv = getNodeText(stroke) \n\t print(\"Stroke Line Cap:%s\" %\n\t \t(getNodeText(stroke)))\n\tfor strokee in strokes:\n\t stroke = strokee.getElementsByTagName(\"sld:CssParameter\")[4]\n\t strokeljv = getNodeText(stroke)\n\t print(strokeljv) \n\t print(\"Stroke Line Join:%s\" %\n\t \t(getNodeText(stroke)))\n\treturn fillcolorv, strokev, devicecont, strokewidthv, strokelcv, strokeljv\nif __name__ == '__main__':\n\tsldGrabber('alantest.XML')\n","sub_path":"sitemanager/mapmanager/sldconnector.py","file_name":"sldconnector.py","file_ext":"py","file_size_in_byte":1934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"266926952","text":"import os\n\nfrom python.lib.organisation import Organisation\nfrom python.services.github_service import GithubService\n\n\ndef main():\n print(\"Start\")\n\n oauth_token = os.getenv(\"ADMIN_GITHUB_TOKEN\")\n if not oauth_token:\n raise ValueError(\n \"The env variable ADMIN_GITHUB_TOKEN is empty or missing\")\n\n moj_github_service = GithubService(oauth_token, \"ministryofjustice\")\n moj_org = Organisation(moj_github_service, \"ministryofjustice\")\n moj_org.close_expired_issues()\n\n as_github_service = GithubService(oauth_token, \"moj-analytical-services\")\n as_org = Organisation(as_github_service, \"moj-analytical-services\")\n as_org.close_expired_issues()\n\n print(\"Finished\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"python/scripts/close_move_users_to_teams_expired_issues.py","file_name":"close_move_users_to_teams_expired_issues.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"352182343","text":"#encoding=utf-8\nimport re\nimport pymysql\nimport jieba.analyse\n\ndef do_detail_cut():\n conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='password', db='job', use_unicode=True,\n charset=\"utf8\")\n cursor = conn.cursor()\n cursor.execute(\"select detail from position\")\n # 获取剩余结果所有数据\n detail_list = cursor.fetchall()\n data = ''\n file_object = open('stopwords.txt')\n try:\n stopwords = file_object.read()\n finally:\n file_object.close()\n\n stopwords = stopwords.split('\\n')\n\n jieba.load_userdict(\"dict.txt\")\n\n for each in detail_list:\n detail = each[0]\n detail = re.sub(r'[一二三四五六七八九十\\d][,.,、))]|(职|工作|岗位|任职).*?(:|:| |\\n)|【.*?】', '', detail)\n detail = re.sub(r'[/:;,.,、;:。()()……]|\\d ', ' ', detail)\n detail = re.sub(r'\\s+', ' ', detail)\n words = jieba.cut(detail.lower())\n print(words)\n for word in words:\n if word in stopwords:\n continue\n print(word , end=' ')\n data = data + ' ' + word\n data += '\\n'\n\n file_result = open('detail.txt','w+')\n file_result.write(data)\n file_result.close()\n # 提交\n conn.commit()\n # 关闭指针对象\n cursor.close()\n # 关闭连接对象\n conn.close()\n\nif __name__ == '__main__':\n\n do_detail_cut()","sub_path":"jieba/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"483390210","text":"import sys\r\nimport os\r\nimport sintefDatasetValTest as dataset\r\nimport matplotlib.pyplot as plt\r\nimport torch as torch\r\nimport torch.utils.data as batchloader\r\nimport ynet_model\r\nfrom unet_parts import *\r\nimport decoder\r\nfrom singlePerceptualModel import AutoEncoder\r\nfrom singlePerceptualParts import *\r\nimport visdomLogger as vl\r\nimport numpy as np\r\nimport gc\r\nimport torchvision\r\n\r\n# Constants\r\ndx = torch.cuda.FloatTensor([[1, 0, -1],\r\n [2, 0, -2],\r\n [1, 0, -1]]).detach()\r\n\r\ndy = torch.cuda.FloatTensor([[1, 2, 1],\r\n [0, 0, 0],\r\n [-1, -2, -1]]).detach()\r\ndx = dx.view((1,1,3,3))\r\ndy = dy.view((1,1,3,3))\r\n\r\ndef registrationLoss(rotatedMrisOut, usOut, loss):\r\n zeroTensor = torch.cuda.FloatTensor(rotatedMrisOut.size()).fill_(0).detach()\r\n regLoss = loss(rotatedMrisOut - usOut.expand_as(rotatedMrisOut), zeroTensor)\r\n regLoss = 1/(regLoss + 1e-8)\r\n return regLoss\r\n\r\ndef gradient(image):\r\n G_x = torch.nn.functional.conv2d(image, dx)\r\n G_y = torch.nn.functional.conv2d(image, dy)\r\n\r\n return torch.sqrt(torch.pow(G_x, 2)+ torch.pow(G_y, 2))\r\n\r\ndef calculateTotalLoss(mriOut, usOut, rotatedMrisOut, mriOutEncoded, usOutEncoded, mriEncoded, usEncoded, l2Loss, l1Loss):\r\n # calculate losses\r\n zeroTensor = torch.cuda.FloatTensor(mriOut.size()).fill_(0).detach()\r\n mriUsOutDiffLoss = l2Loss(mriOut - usOut, zeroTensor)\r\n\r\n #zeroTensor2 = torch.cuda.FloatTensor(mriOutEncoded.size()).fill_(0).detach()\r\n mriEnLoss = l2Loss(mriOutEncoded, mriEncoded)\r\n usEnLoss = l2Loss(usOutEncoded, usEncoded)\r\n\r\n #regLoss = registrationLoss(rotatedMrisOut, usOut, l2Loss)\r\n\r\n totalLoss = 10000000*mriUsOutDiffLoss + 10*mriEnLoss + usEnLoss# + 50*regLoss\r\n return (totalLoss, 10000000*mriUsOutDiffLoss, 10*mriEnLoss, usEnLoss, 0)\r\n\r\ndef main(encoderPath):\r\n\r\n numEpochs, batchSize = 30, 4\r\n\r\n # Use GPU if available\r\n use_cuda = torch.cuda.is_available()\r\n device = torch.device(\"cuda:0\" if use_cuda else \"cpu\")\r\n \r\n # create visdom logger instance\r\n logger = vl.VisdomLogger(port=\"65531\")\r\n logger.deleteWindow(win=\"test\")\r\n\r\n # Initialize the MRI US dataset and the dataset loader\r\n dir = os.path.dirname(__file__)\r\n modelPath = os.path.join(dir, '..', 'savedModels/transformation')\r\n\r\n trainDatasetDir = '../dataset/sintefHdf5Volumes/train'\r\n trainDataset = dataset.SintefDatasetValTest(rootDir=trainDatasetDir, mriFilePrefix='T1-Vol', usFilePrefix='US-DS')\r\n\r\n valDatasetDir = '../dataset/sintefHdf5Volumes/val'\r\n validationDataset = dataset.SintefDatasetValTest(rootDir=valDatasetDir, mriFilePrefix='T1-Vol', usFilePrefix='US-DS')\r\n\r\n dataloader = batchloader.DataLoader(trainDataset, batch_size=batchSize, shuffle=True, num_workers=4)\r\n \r\n #create transformation models and add them to optimizer\r\n mriForwardmodel = ynet_model.Encoder(n_classes=1, n_channels=1).to(device)\r\n usForwardmodel = ynet_model.Encoder(n_classes=1, n_channels=1).to(device)\r\n commonBranch = ynet_model.Decoder(n_classes=1, n_channels=1).to(device)\r\n\r\n\r\n networkParams = list(mriForwardmodel.parameters()) + list(usForwardmodel.parameters()) + list(commonBranch.parameters())\r\n optimizer = torch.optim.Adam(networkParams, lr=1e-3, weight_decay=1e-9)\r\n\r\n #Optimizer learning rate decay.\r\n scheduler = torch.optim.lr_scheduler.ExponentialLR(optimizer, gamma = 0.98)\r\n\r\n #Load encoder models\r\n encoderModel = AutoEncoder().to(device)\r\n encoderModel.load_state_dict(torch.load(encoderPath))\r\n encoderModel.eval()\r\n\r\n # create instance of loss class\r\n l2Loss = torch.nn.MSELoss()\r\n l1Loss = torch.nn.L1Loss()\r\n mriUsOutDiffLoss = 0\r\n mriUsValOutDiffLoss =0\r\n iteration = 0\r\n for epochNum in range(numEpochs):\r\n print(epochNum)\r\n for i_batch, sample_batched in enumerate(dataloader):\r\n mri = sample_batched['mri'].to(device)\r\n us = sample_batched['us'].to(device)\r\n #rotatedMris = sample_batched['rotatedMris'].to(device)\r\n\r\n # perform optimization\r\n optimizer.zero_grad()\r\n\r\n # Compute the shared representation\r\n mriFeatures = mriForwardmodel(mri)\r\n usFeatures = usForwardmodel(us)\r\n mriOut = commonBranch(mriFeatures)\r\n usOut = commonBranch(usFeatures)\r\n\r\n #rotatedMrisOut = mriForwardmodel(rotatedMris.view(rotatedMris.shape[0] * rotatedMris.shape[1], 1, rotatedMris.shape[2], rotatedMris.shape[3]))\r\n #rotatedMrisOut = rotatedMrisOut.view(rotatedMris.shape[0], rotatedMris.shape[1], rotatedMris.shape[2], rotatedMris.shape[3])\r\n\r\n # Compute the encoded Representations\r\n (mriOutEncoded1, mriOutEncoded2, mriOutEncoded3) = encoderModel(mriOut, get_features = True)\r\n (usOutEncoded1, usOutEncoded2, usOutEncoded3) = encoderModel(usOut, get_features = True)\r\n (mriEncoded1, mriEncoded2, mriEncoded3) = encoderModel(mri, get_features = True)\r\n (usEncoded1, usEncoded2, usEncoded3) = encoderModel(us, get_features = True)\r\n\r\n mriEnLoss = (l2Loss(mriOutEncoded3, mriEncoded3) + l2Loss(mriOutEncoded3, usEncoded3))/20000\r\n usEnLoss = (l2Loss(usOutEncoded3, usEncoded3) + l2Loss(usOutEncoded3, mriEncoded3))/20000\r\n # Calculate Losses\r\n #(totalLoss, mriUsOutDiffLoss, mriEnLoss, usEnLoss, _) = calculateTotalLoss(mriOut, usOut, _, mriOutEncoded, usOutEncoded, mriEncoded, usEncoded, l2Loss, l1Loss)\r\n\r\n featureLoss = l2Loss(mriFeatures[-1] - usFeatures[-1], torch.cuda.FloatTensor(mriFeatures[-1].size()).fill_(0))\r\n #print(len(mriFeatures))\r\n #for i in len(mriFeatures):\r\n # \tzeroTensor = torch.cuda.FloatTensor(mriFeatures[i].size()).fill_(0)\r\n #\tfeatureLoss += l2Loss(mriFeatures[i] - usFeatures[i], zeroTensor)\r\n\r\n\r\n zeroTensor = torch.cuda.FloatTensor(mriOut.size()).fill_(0)\r\n mriUsOutDiffLoss = 1000*l2Loss(mriOut - usOut, zeroTensor)#+ (l2Loss(mriOutEncoded1 - usOutEncoded1, torch.cuda.FloatTensor(mriOutEncoded1.size()).fill_(0)) + l2Loss(mriOutEncoded2 - usOutEncoded2, torch.cuda.FloatTensor(mriOutEncoded2.size()).fill_(0)) + l2Loss(mriOutEncoded3 - usOutEncoded3, torch.cuda.FloatTensor(mriOutEncoded3.size()).fill_(0))) #1000000*l2Loss(mriOut - usOut, zeroTensor)\r\n #mriEnLoss = l2Loss(mriOut, mri)\r\n #usEnLoss = l2Loss(usOut, us)\r\n\r\n totalLoss = mriEnLoss + usEnLoss+ mriUsOutDiffLoss#featureLoss + mriUsOutDiffLoss + mriEnLoss + usEnLoss\r\n\r\n # perform backward pass\r\n totalLoss.backward()\r\n\r\n optimizer.step()\r\n\r\n # print Epoch number and Loss\r\n print(\"Epoch: \", epochNum, \"iteration: \", i_batch, \"Total loss: \", totalLoss.item(),\r\n \"MriUSLoss: \", mriUsOutDiffLoss.item(), \"MriEncoderLoss: \", mriEnLoss.item(), \"UsEncoderLoss:\", usEnLoss.item(), \"featureLoss\", featureLoss.item())\r\n print('')\r\n\r\n iteration = iteration + 1\r\n logger.appendLine(X=np.array([iteration]), Y=np.array([totalLoss.item()]), win=\"test\", name=\"Total Loss\", xlabel=\"Iteration Number\", ylabel=\"Loss\")\r\n logger.appendLine(X=np.array([iteration]), Y=np.array([featureLoss.item()]), win=\"test\", name=\"Feature Loss\", xlabel=\"Iteration Number\", ylabel=\"Loss\")\r\n logger.appendLine(X=np.array([iteration]), Y=np.array([mriUsOutDiffLoss.item()]), win=\"test\", name=\"MRI US Diff Loss\", xlabel=\"Iteration Number\", ylabel=\"Loss\")\r\n logger.appendLine(X=np.array([iteration]), Y=np.array([mriEnLoss.item()]), win=\"test\", name=\"MRI Encoder Loss\", xlabel=\"Iteration Number\", ylabel=\"Loss\")\r\n logger.appendLine(X=np.array([iteration]), Y=np.array([usEnLoss.item()]), win=\"test\", name=\"US Encoder Loss\", xlabel=\"Iteration Number\", ylabel=\"Loss\")\r\n logger.appendLine(X=np.array([iteration]), Y=np.array([featureLoss.item()]), win=\"test\", name=\"Feature Loss\", xlabel=\"Iteration Number\", ylabel=\"Loss\")\r\n \r\n if iteration%20 == 0:\r\n usValIn = torch.Tensor([])\r\n mriValIn = torch.Tensor([])\r\n #rotatedMrisValIn = torch.Tensor([])\r\n \r\n #switch model to eval mode for validation\r\n mriForwardmodel.eval()\r\n usForwardmodel.eval()\r\n commonBranch.eval()\r\n\r\n # Show output on a validation image after some iterations\r\n valBatchSize = 5\r\n valSetIds = np.random.randint(low=1, high=validationDataset.__len__(), size=valBatchSize)\r\n\r\n # Make a concatenated tensor of inputs\r\n for i in range(valBatchSize):\r\n valData = validationDataset[valSetIds[i]]\r\n usValIn = torch.cat((usValIn, valData['us'].unsqueeze(0)), 0)\r\n mriValIn = torch.cat((mriValIn, valData['mri'].unsqueeze(0)), 0)\r\n #rotatedMrisValIn = torch.cat((rotatedMrisValIn, valData['rotatedMris'].unsqueeze(0)), 0)\r\n\r\n usValIn = usValIn.to(device)\r\n mriValIn = mriValIn.to(device)\r\n #rotatedMrisValIn = rotatedMrisValIn.to(device)\r\n\r\n mriValFeatures = mriForwardmodel(mriValIn)\r\n usValFeatures = usForwardmodel(usValIn)\r\n mriValOut = commonBranch(mriValFeatures)\r\n usValOut = commonBranch(usValFeatures)\r\n \r\n #rotatedMrisValOut = mriForwardmodel(rotatedMrisValIn.view(rotatedMrisValIn.shape[0] * rotatedMrisValIn.shape[1], 1, rotatedMrisValIn.shape[2], rotatedMrisValIn.shape[3]))\r\n #rotatedMrisValOut = rotatedMrisValOut.view(rotatedMrisValIn.shape[0], rotatedMrisValIn.shape[1], rotatedMrisValIn.shape[2], rotatedMrisValIn.shape[3]) \r\n\r\n # Compute the encoded Representations\r\n (mriValOutEncoded1, mriValOutEncoded2, mriValOutEncoded3) = encoderModel(mriValOut, get_features = True)\r\n (usValOutEncoded1, usValOutEncoded2, usValOutEncoded3) = encoderModel(usValOut, get_features = True)\r\n (mriValEncoded1, mriValEncoded2, mriValEncoded3) = encoderModel(mriValIn, get_features = True)\r\n (usValEncoded1, usValEncoded2, usValEncoded3) = encoderModel(usValIn, get_features = True)\r\n\r\n mriEnLoss = (l2Loss(mriValOutEncoded3, mriValEncoded3) + l2Loss(mriValOutEncoded3, usValEncoded3))/20000\r\n usEnLoss = (l2Loss(usValOutEncoded3, usValEncoded3) + l2Loss(usValOutEncoded3, mriValEncoded3))/20000\r\n\r\n\r\n # find and plot loss on the validation batch also Calculate Losses\r\n\r\n #(totalLossVal, mriUsValOutDiffLoss, _, _, _) = calculateTotalLoss(mriValOut, usValOut, _, mriValOutEncoded, usValOutEncoded, mriValEncoded, usValEncoded, l2Loss, l1Loss)\r\n\r\n featureLoss = l2Loss(mriValFeatures[-1] - usValFeatures[-1], torch.cuda.FloatTensor(mriValFeatures[-1].size()).fill_(0))\r\n\r\n #for i in len(mriFeatures):\r\n #\tzeroTensor = torch.cuda.FloatTensor(mriValFeatures[i].size()).fill_(0)\r\n #\tfeatureLoss += l2Loss(mriValFeatures[i] - usValFeatures[i], zeroTensor)\r\n \r\n zeroTensor = torch.cuda.FloatTensor(mriValOut.size()).fill_(0)\r\n mriUsValOutDiffLoss = 1000*l2Loss(mriValOut - usValOut, zeroTensor)#+ (l2Loss(mriValOutEncoded1 - usValOutEncoded1, torch.cuda.FloatTensor(mriValOutEncoded1.size()).fill_(0)) + l2Loss(mriValOutEncoded2 - usValOutEncoded2, torch.cuda.FloatTensor(mriValOutEncoded2.size()).fill_(0)) + l2Loss(mriValOutEncoded3 - usValOutEncoded3, torch.cuda.FloatTensor(mriValOutEncoded3.size()).fill_(0))) #1000000*l2Loss(mriOut - usOut, zeroTensor)#1000000*l2Loss(mriValOut - usValOut, zeroTensor)\r\n #mriEnLoss = l2Loss(mriValOut, mriValIn)\r\n #usEnLoss = l2Loss(usValOut, usValIn)\r\n\r\n totalLossVal = mriEnLoss + usEnLoss + mriUsOutDiffLoss#featureLoss + mriUsValOutDiffLoss + mriEnLoss + usEnLoss\r\n\r\n logger.appendLine(X=np.array([iteration]), Y=np.array([mriUsValOutDiffLoss.item()]), win=\"test\", name=\"[VAL] MRI US Diff Loss\", xlabel=\"Iteration Number\", ylabel=\"Loss\")\r\n logger.appendLine(X=np.array([iteration]), Y=np.array([totalLossVal.item()]), win=\"test\", name=\"[VAL] Total Loss\", xlabel=\"Iteration Number\", ylabel=\"Loss\")\r\n\r\n mriDisplayImages = torch.cat((mriValIn, rangeNormalize(mriValOut)[0]), 0)\r\n usDisplayImages = torch.cat((usValIn, rangeNormalize(usValOut)[0]), 0)\r\n\r\n mriTrainDisplayImages = torch.cat((mri, rangeNormalize(mriOut)[0]), 0)\r\n usTrainDisplayImages = torch.cat((us, rangeNormalize(usOut)[0]), 0)\r\n\r\n # plot images in visdom in a grid, MRI and US has different grids.\r\n logger.plotImages(images=mriDisplayImages, nrow=valBatchSize, win=\"mriGrid\", caption='MRI Validation')\r\n logger.plotImages(images=usDisplayImages, nrow=valBatchSize, win=\"usGrid\", caption='US Validation')\r\n logger.plotImages(images=mriTrainDisplayImages, nrow=batchSize, win=\"trainMRI\", caption='MRI Train')\r\n logger.plotImages(images=usTrainDisplayImages, nrow=batchSize, win=\"trainUS\", caption='US Train')\r\n \r\n #switch back to train mode\r\n usForwardmodel.train()\r\n mriForwardmodel.train()\r\n commonBranch.train()\r\n\r\n torch.save(mriForwardmodel.state_dict(), os.path.join(modelPath, \"mriYNet\" + str(epochNum) + \".pth\"))\r\n torch.save(usForwardmodel.state_dict(), os.path.join(modelPath, \"usYNet\" + str(epochNum) + \".pth\"))\r\n torch.save(commonBranch, os.path.join(modelPath, \"commonBranchYNet\" + str(epochNum) + \".pth\"))\r\n\r\n\r\n #Learning rate decay after every Epoch\r\n scheduler.step()\r\n\r\n print(\"Training ended\")\r\n\r\nif __name__ == '__main__':\r\n\r\n\tmain(encoderPath = \"../savedModels/autoencoder/singleAutoencoder2.pth\")\r\n\t#main()\r\n\t\"\"\"\r\n\r\n parameters = ['mriEncoderPath', 'usEncoderPath']\r\n\r\n if len(sys.argv) == 1:\r\n print(\"Using default values\")\r\n main()\r\n\r\n if len(sys.argv) > 1:\r\n\r\n userArgs = [s.split(\"=\") for s in sys.argv]\r\n\r\n args = {}\r\n\r\n for i in range(1, len(userArgs)):\r\n\r\n if userArgs[i][0] not in parameters:\r\n print(userArgs[i][0] + \" is not an allowed parameter. Please use one of the following:\")\r\n print(parameters)\r\n sys.exit(0)\r\n\r\n if len(userArgs[i]) != 2:\r\n print(\"Please don't use spaces when defining a parameter. E.g. numEpochs=10\")\r\n sys.exit(0)\r\n\r\n args[userArgs[i][0]] = (userArgs[i][1])\r\n\r\n main(**args)\r\n \"\"\"","sub_path":"trainYNetSingleAE.py","file_name":"trainYNetSingleAE.py","file_ext":"py","file_size_in_byte":14958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"474922848","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Mar 16 01:39:52 2018\r\n\r\n@author: vasant\r\n\"\"\"\r\nfrom sklearn.datasets import load_svmlight_file\r\nfrom os import listdir \r\nimport re\r\nfrom nltk.tokenize import sent_tokenize, word_tokenize\r\nfrom sklearn.cross_validation import train_test_split\r\nfrom sklearn.metrics import roc_auc_score\r\nfrom sklearn import linear_model\r\nimport gensim\r\nfrom gensim.models import Word2Vec\r\nimport numpy as np\r\nfrom scipy.sparse import csr_matrix\r\nfrom sklearn.naive_bayes import BernoulliNB\r\nfrom sklearn import svm\r\nfrom sklearn.neural_network import MLPClassifier\r\n\r\nx =[1]* 12500\r\ny = [0] * 12500\r\ny_train = np.concatenate((x,y),axis=0)\r\ny_test = y_train\r\n\r\ndef method_Log_regression(x_train,x_test):\r\n clf = linear_model.SGDClassifier(loss='log')\r\n clf.fit(x_train, y_train)\r\n p=clf.predict(x_test)\r\n accu = roc_auc_score(y_test,p)\r\n accu = accu*100\r\n print(\"Accuracy on TF with Logistic regression :\" \"%.4f\" % accu)\r\n \r\n \r\ndef method_Naive_bayes(x_train,x_test):\r\n model = BernoulliNB().fit(x_train, y_train)\r\n p = model.predict(x_test)\r\n accu = roc_auc_score(y_test,p)\r\n accu = accu*100\r\n print(\"Accuracy on TF with Naive bayes calssifier : \" ,\"%.4f\" % accu)\r\n \r\ndef method_feed_forward(x_train,x_test):\r\n clf = MLPClassifier(solver='lbfgs', alpha=1e-5,hidden_layer_sizes=(10,8), random_state=1)\r\n clf.fit(x_train, y_train) \r\n p=clf.predict(x_test)\r\n accu = roc_auc_score(y_test,p)\r\n accu = accu*100\r\n print(\"Accuracy on TF with feed forward Neural : \" \"%.4f\" % accu)\r\n \r\n \r\ndef method_SVM(x_train,x_test):\r\n clf = svm.SVC()\r\n clf.fit(x_train, y_train) \r\n p=clf.predict(x_test)\r\n accu = roc_auc_score(y_test,p)\r\n accu = accu*100\r\n print(\"Accuracy on TF with SVM calssifier : \" \"%.4f\" % accu)\r\n \r\ndef method(direc1, direc2):\r\n x_train = load_svmlight_file(direc1)\r\n x_test = load_svmlight_file(direc2)\r\n method_Log_regression(x_train[0],x_test[0])\r\n method_Naive_bayes(x_train[0],x_test[0])\r\n method_feed_forward(x_train[0],x_test[0])\r\n method_SVM(x_train[0],x_test[0])\r\n\r\n#call to methods \r\n\r\ntraining_direc = 'F:\\\\ACADS\\\\acads 6th sem\\\\NLP\\\\Assignments\\\\Assign 2\\\\train_TF.feat'\r\ntesting_direc = 'F:\\\\ACADS\\\\acads 6th sem\\\\NLP\\\\Assignments\\\\Assign 2\\\\test_TF.feat'\r\nmethod(training_direc,testing_direc)\r\n\r\n","sub_path":"Norm_TF_accuracy.py","file_name":"Norm_TF_accuracy.py","file_ext":"py","file_size_in_byte":2343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"32638566","text":"\nfrom django.shortcuts import render\nfrom django.shortcuts import render_to_response\nfrom django.template import Context\nfrom dbAccess.access import dbRoutine\nfrom django.contrib.auth import logout\n\nfrom .models import Subject\nfrom .models import Flashcard\nfrom dbAccess.models import Account\nfrom dbAccess.models import Session\nfrom .forms import AnswerForm\n\nfrom django.views.decorators.csrf import ensure_csrf_cookie\nfrom django.contrib.auth.decorators import login_required\nimport json\nfrom random import shuffle\n \nglobar = \"\"\r\ndef index(request):\n subject_list = Subject.objects.values_list('name', flat=True)\n subject_list2 = None\n subject_listpub = None\n valid_subject_list2 = 1\n if request.user.is_authenticated():\n current_user = request.user\n dbUser = dbRoutine.retrieve_account_no_password(current_user)\n subject_list2 = dbUser.getSubjects();\n print(subject_list2)\n if (subject_list2.count() == 0):\n valid_subject_list2 = 0\n print(subject_list2)\n subject_listpub = dbRoutine.retrieve_publicSub()\n logged_in = 1\n else:\n current_user = request.user\n logged_in = 0\n \n return render(request, 'home.html', {'valid_subject_list2':valid_subject_list2, 'current_user':current_user, 'logged_in':logged_in, 'subject_list':subject_list, 'subject_list2':subject_list2, 'subject_listpub':subject_listpub})\n\ndef loggedout(request):\n # log out here\n logout(request)\n return render_to_response('loggedout.html')\n\ndef viewsessions(request):\n \n\n if request.user.is_authenticated():\n current_user = request.user\n logged_in = 1\n \n # get the sessions\n dbUser = dbRoutine.retrieve_account_no_password(current_user)\n\n \n sessions = dbUser.getSessions()\n\n \n if (sessions.count() == 0):\n valid_sessions = 0\n else:\n valid_sessions = 1\n \n return render_to_response('viewsessions.html', {'current_user':current_user, 'logged_in':logged_in,\n 'sessions':sessions, 'valid_sessions':valid_sessions})\n \n else:\n current_user = request.user\n logged_in = 0\n return render_to_response('needacc.html')\n\n\ndef viewcards(request):\n \n \n# subject = request.POST['subject']\n \n if request.user.is_authenticated():\n current_user = request.user\n logged_in = 1\n \n subject = request.POST['subject']\n \n # get the cards\n dbUser = dbRoutine.retrieve_account_no_password(current_user)\n\n #cards = dbUser.getCards()\n #cards = dbRoutine.retrieve_fc2(subject) \n cards = dbRoutine.retrieve_fc(subject)\n\n if (cards.count() == 0):\n valid_cards = 0\n else:\n valid_cards = 1\n \n return render(request, 'viewcards.html', {'current_user':current_user, 'subject':subject, 'logged_in':logged_in,\n 'cards':cards,'valid_cards':valid_cards})\n \n else:\n current_user = request.user\n logged_in = 0\n cards = None\n valid_cards = -1\n \n return render_to_response('needacc.html')\n \ndef sharedcards(request):\n \n \n# subject = request.POST['subject']\n# \n# print(\"the subject: \", subject)\n \n if request.user.is_authenticated():\n current_user = request.user\n logged_in = 1\n \n subject = request.POST['subject']\n \n print(\"the subject: \", subject)\n \n # get the cards\n dbUser = dbRoutine.retrieve_account_no_password(current_user)\n\n #cards = dbUser.getCards()\n #cards = dbRoutine.retrieve_fc2(subject) \n cards = dbRoutine.retrieve_fc(subject)\n \n dbRoutine.publish_subject(subject)\n\n if (cards.count() == 0):\n valid_cards = 0\n else:\n valid_cards = 1\n \n return render(request, 'sharedcards.html', {'current_user':current_user, 'logged_in':logged_in,\n 'cards':cards,'valid_cards':valid_cards})\n \n else:\n current_user = request.user\n logged_in = 0\n cards = None\n valid_cards = -1\n \n return render_to_response('needacc.html')\n\ndef search(request):\n \n \n# subject = request.POST['subject']\n# global globar\n# globar = subject\n \n if request.user.is_authenticated():\n current_user = request.user\n logged_in = 1\n \n subject = request.POST['subject']\n global globar\n globar = subject\n \n cards = dbRoutine.retrieve_fc(subject)\n\n if (cards.count() == 0):\n valid_cards = 0\n else:\n valid_cards = 1\n \n return render(request, 'search.html', {'current_user':current_user, 'logged_in':logged_in,\n 'cards':cards, 'valid_cards':valid_cards})\n \n else:\n current_user = request.user\n logged_in = 0\n cards = None\n valid_cards = -1\n \n return render_to_response('needacc.html')\n \n\n@login_required\n@ensure_csrf_cookie\n\ndef addPublicSub(request):\n subjecto = globar\n if request.is_ajax():\n signal = request.POST['signal']\n# print(\"ok\");\n# print(\"this is the signal:\" + signal);\n \n if signal == 'sub':\n current_user = request.user\n# request.session()\n #print()\n\n# print(\"this is the subject:\",subjecto);\n dbRoutine.link_subject(current_user, subjecto)\n\n return render_to_response('collectionadded.html')\n\ndef collectionadded(request):\n return render_to_response('collectionadded.html')\n \ndef feedback(request):\n \n \n# subject = request.POST['subject']\n \n if request.user.is_authenticated():\n current_user = request.user\n logged_in = 1\n \n subject = request.POST['subject']\n \n feedbacks = dbRoutine.retrieve_fd(subject)\n \n if (feedbacks.count() == 0):\n valid_feedback = 0\n else:\n valid_feedback = 1\n \n return render(request, 'feedback.html', {'current_user':current_user, 'logged_in':logged_in,'feedbacks': feedbacks,'valid_feedback':valid_feedback})\n \n else:\n current_user = request.user\n logged_in = 0\n\n valid_feedback = -1\n \n return render_to_response('needacc.html')\n \n\n\n\ndef needacc(request):\n return render_to_response('needacc.html')\n\n\ndef takequiz(request):\n if request.user.is_authenticated():\n current_user = request.user\n logged_in = 1\n return render_to_response('takequiz.html', {'current_user':current_user, 'logged_in':logged_in})\n else:\n current_user = request.user\n logged_in = 0\n return render_to_response('neddacc.html')\n \n\ndef takequizdetailed(request):\n ans = \"\";\n \n \n\r\n ans_form = AnswerForm(request.POST or None)\n if ans_form.is_valid():\n ans = ans_form.cleaned_data['selection']\n context={\n \"form\": ans_form,\n }\n \n \n # Here I have the selection (ans), do something with it.\n \n \n \n if (ans == 'flip'):\n list.show_one_answer();\n print(\"Flipping card.\");\n \n if (ans == 'correct'):\n list.honor_system(ans);\n print(\"Answered correctly.\");\n if (ans == 'incorrect'):\n list.honor_system(ans);\n print(\"Answered incorrectly.\");\n if (ans == 'skip left'):\n \n list.get_prev_question();\n list.show_one_question();\n print(\"Skipping to the left.\");\n if (ans == 'skip right'):\n list.get_next_question();\n list.show_one_question();\n print(\"Skipping to the right.\");\n \n \n return render(request, 'takequizdetailed.html', context)\n","sub_path":"flash_card/home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"402265780","text":"from functools import wraps\nimport sys\nimport os\nimport io\nfrom flask import Flask, render_template, redirect, request, url_for, session, abort, \\\n send_from_directory\n#coming from pyrebase4\nfrom werkzeug.utils import secure_filename\nimport pyrebase\nimport imghdr\nfrom google.cloud import vision\n\nos.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"] = \"emapped-8b4be6305e9a.json\"\n\nclient = vision.ImageAnnotatorClient()\n\n#firebase config\nconfig = {\n\n}\n\n#init firebase\nfirebase = pyrebase.initialize_app(config)\n#auth instance\nauth = firebase.auth()\n#real time database instance\ndb = firebase.database();\n\n\n#new instance of Flask\napp = Flask(__name__)\napp.config['UPLOAD_EXTENSIONS'] = ['.jpg', '.png', '.gif']\n#secret key for the session\napp.secret_key = os.urandom(24)\n\n#decorator to protect routes\ndef isAuthenticated(f):\n @wraps(f)\n def decorated_function(*args, **kwargs):\n #check for the variable that pyrebase creates\n if not auth.current_user != None:\n return redirect(url_for('login'))\n return f(*args, **kwargs)\n return decorated_function\n\n@app.route(\"/\")\n@isAuthenticated\ndef index():\n return render_template(\"index.html\", email=session[\"email\"])\n\n@app.route(\"/map\")\n@isAuthenticated\ndef map():\n return render_template(\"map.html\", email=session[\"email\"])\n\n@app.route(\"/profile/\")\n@isAuthenticated\ndef profile(email):\n loginuser = 0\n if email == session[\"email\"]:\n loginuser = 1\n return render_template('profile.html', email=email, loginuser=loginuser)\n\n#signup route\n@app.route(\"/signup\", methods=[\"GET\", \"POST\"])\ndef signup():\n if request.method == \"POST\":\n #get the request form data\n email = request.form[\"email\"]\n password = request.form[\"password\"]\n try:\n #create the user\n auth.create_user_with_email_and_password(email, password);\n #login the user right away\n user = auth.sign_in_with_email_and_password(email, password)\n #session\n user_id = user['idToken']\n user_email = email\n session['usr'] = user_id\n session[\"email\"] = user_email\n return redirect(\"/\")\n except:\n return render_template(\"login.html\", message=\"The email is already taken, try another one, please\" )\n\n return render_template(\"signup.html\")\n\n\n#login route\n@app.route(\"/login\", methods=[\"GET\", \"POST\"])\ndef login():\n if request.method == \"POST\":\n #get the request data\n email = request.form[\"email\"]\n password = request.form[\"password\"]\n try:\n #login the user\n user = auth.sign_in_with_email_and_password(email, password)\n #set the session\n user_id = user['idToken']\n user_email = email\n session['usr'] = user_id\n session[\"email\"] = user_email\n return redirect(\"/\")\n\n except:\n return render_template(\"login.html\", message=\"Wrong Credentials\" )\n\n\n return render_template(\"login.html\")\n\n#logout route\n@app.route(\"/logout\")\ndef logout():\n #remove the token setting the user to None\n auth.current_user = None\n #also remove the session\n #session['usr'] = \"\"\n #session[\"email\"] = \"\"\n session.clear()\n return redirect(\"/\");\n\ndef validate_image(stream):\n header = stream.read(512) # 512 bytes should be enough for a header check\n stream.seek(0) # reset stream pointer\n format = imghdr.what(None, header)\n if not format:\n return None\n return '.' + (format if format != 'jpeg' else 'jpg')\n\n#create form\n@app.route(\"/upload\", methods=[\"GET\", \"POST\"])\n@isAuthenticated\ndef upload():\n if request.method == \"POST\":\n if os.path.isdir('photos/' + session[\"email\"]):\n app.config['UPLOAD_PATH'] = 'photos/' + session[\"email\"]\n #get the request data\n uploaded_file = request.files[\"upload\"]\n filename = secure_filename(uploaded_file.filename)\n path = \"photos/\" + session[\"email\"] + \"/\" + filename\n # file_name = os.path.abspath('/photos/' + session[\"email\"] + \"/\" + uploaded_file.filename)\n with io.open(path, 'rb') as image_file:\n content = image_file.read();\n\n image = vision.Image(content=content)\n\n # Performs label detection on the image file\n response = client.label_detection(image=image)\n labels = response.label_annotations\n\n tags = []\n for label in labels:\n tags.append(str(label.description))\n\n print(tags)\n\n # Performs face detection on the image file\n response = client.face_detection(image=image)\n faces = response.face_annotations\n\n likelihood_name = ('UNKNOWN', 'VERY_UNLIKELY', 'UNLIKELY', 'POSSIBLE', 'LIKELY', 'VERY_LIKELY')\n\n moods = []\n\n for face in faces:\n mood = []\n mood.append('Joy')\n mood.append(likelihood_name.index(likelihood_name[face.joy_likelihood]))\n moods.append(mood)\n\n mood = []\n mood.append('Sorrow')\n mood.append(likelihood_name.index(likelihood_name[face.sorrow_likelihood]))\n moods.append(mood)\n\n mood = []\n mood.append('Anger')\n mood.append(likelihood_name.index(likelihood_name[face.anger_likelihood]))\n moods.append(mood)\n\n mood = []\n mood.append('Surprise')\n mood.append(likelihood_name.index(likelihood_name[face.surprise_likelihood]))\n moods.append(mood)\n\n # filename = secure_filename(uploaded_file.filename)\n if filename != '':\n file_ext = os.path.splitext(filename)[1]\n if file_ext not in app.config['UPLOAD_EXTENSIONS'] or \\\n file_ext != validate_image(uploaded_file.stream):\n abort(400)\n uploaded_file.save(os.path.join(app.config['UPLOAD_PATH'], filename))\n else:\n os.makedirs('photos/' + session[\"email\"])\n\n return render_template(\"upload.html\", email = session[\"email\"])\n\n@app.route(\"/post\")\n@isAuthenticated\ndef post():\n pics = os.listdir('photos/' + session[\"email\"])\n for photo in pics:\n image = Image.open('photos/' + session[\"email\"]+ \"/\" + photo)\n for (tag,value) in image._getexif().iteritems():\n print (TAGS.get(tag), value)\n return render_template(\"post.html\", pics = pics)\n\n\n#run the main script\nif __name__ == \"__main__\":\n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"227978799","text":"import json\r\nimport os\r\nimport h5py\r\nimport numpy as np\r\nimport sys\r\nfrom io import StringIO\r\n\r\nlabel_file = '/home/zenglh/didemo/didemo_caption.json'\r\nfeature_file = '/home/zenglh/didemo/didemo_sentences_line.jsonl'\r\noutput_file = '/home/zenglh/didemo/didemo_bert.hdf5'\r\n\r\ndef list_features(feature):\r\n syntaxes = feature['features']\r\n fl = []\r\n for s in syntaxes:\r\n f = s['layers'][-1]['values']\r\n fl.append(np.expand_dims(f, 0))\r\n return np.concatenate(fl, 0)\r\n\r\n\r\nwith open(os.path.join(label_file), \"r\") as fl:\r\n captions = json.load(fl)\r\n\r\nfeature_list = []\r\nwith open(os.path.join(feature_file), \"r\") as fb:\r\n feature_lines = fb.read().splitlines()\r\n for line in feature_lines:\r\n feature = json.load(StringIO(line))\r\n feature = list_features(feature)\r\n feature_list.append(feature)\r\n\r\nfeature_dict = {}\r\ncount = 0\r\nkeys = sorted(captions.keys())\r\nfor k in keys:\r\n feature_dict[k] = []\r\n for i in range(len(captions[k][\"sentences\"])):\r\n feature_dict[k].append(feature_list[count])\r\n count += 1\r\n\r\nprint(count)\r\n\r\nwith h5py.File(os.path.join(output_file),'w') as features_hdf5:\r\n for k, v in feature_dict.items():\r\n grp = features_hdf5.create_group(k)\r\n for i in range(len(v)):\r\n grp.create_dataset(str(i), data=v[i].astype(np.float32))","sub_path":"data_preprocess/generate_didemo_merge_bert_lines.py","file_name":"generate_didemo_merge_bert_lines.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"602092499","text":"# -*- coding: utf-8 -*-\n # --------------------------------------------------------------------------------------------\n # Copyright (C) 2013-2017 Gerhard Hepp\n #\n # This program is free software; you can redistribute it and/or modify it under the terms of\n # the GNU General Public License as published by the Free Software Foundation; either version 2\n # of the License, or (at your option) any later version.\n #\n # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n # without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n # See the GNU General Public License for more details.\n #\n # You should have received a copy of the GNU General Public License along with this program; if\n # not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,\n # MA 02110, USA\n # ---------------------------------------------------------------------------------------------\n\n#\n\ndebug = False\ndebug_grid = False\n\nimport time\nimport os\nimport json\nimport threading\nimport sys \nimport traceback\n#import curses\n#import curses.ascii\n \nimport tornado.ioloop\nimport tornado.web\nimport tornado.websocket\nimport asyncio\n\nimport mako.template\nimport mako.lookup\nimport uuid\n \nimport xml.etree.ElementTree as ET\nimport publishSubscribe\n\nimport helper\n\nimport adapter.adapters \n\nimport logging\nlogger = logging.getLogger(__name__)\n\nimport scratchClient\n\n#configuration = {'webapp2_static': { 'static_file_path': scratchClient.modulePathHandler.getScratchClientBaseRelativePath('htdocs/static') }}\ncommandResolver = None\n#\n# strange circular dependency to base module\n\nlookup = mako.lookup.TemplateLookup(\n directories=[\n scratchClient.modulePathHandler.getScratchClientBaseRelativePath('htdocs')\n ], \n input_encoding='utf-8', \n output_encoding='utf-8',\n encoding_errors='replace')\n\n# ------------------------------------------------------------------------------------------------\n_runThreads = True\nparentApplication = None\nremote = False\nscratchXHandler = None\n\nuseLocalIOloop = True\nlocalIOloop = None\n\n# ------------------------------------------------------------------------------------------------\n# handle item-ID values throughout code\n\nclass IDManager():\n \"\"\"internal use to produce unique ID for display elements\"\"\"\n \n def __init__(self):\n self.reset()\n \n def reset(self):\n self.scratch_input_command_2_display = []\n self.scratch_input_value_2_display = []\n self.scratch_output_command_2_display = []\n self.scratch_output_value_2_display = []\n self.displayid = 1000\n \n def getDisplayId_scratchInputCommand (self, scratch):\n _id = str(self.displayid)\n self.scratch_input_command_2_display.append( {'name': scratch, 'id': _id} )\n self.displayid += 1\n return _id \n \n def getDisplayId_scratchInputValue (self, scratch):\n _id = str(self.displayid)\n self.scratch_input_value_2_display.append( {'name': scratch, 'id': _id} )\n self.displayid += 1\n return _id \n \n def getDisplayId_scratchOutputCommand (self, scratch):\n _id = str(self.displayid)\n self.scratch_output_command_2_display.append( {'name': scratch, 'id': _id} )\n self.displayid += 1\n return _id \n \n def getDisplayId_scratchOutputValue (self, scratch):\n _id = str(self.displayid)\n self.scratch_output_value_2_display.append( {'name': scratch, 'id': _id} )\n self.displayid += 1\n return _id \n \n def getId (self):\n _id = str(self.displayid)\n self.displayid += 1\n return _id \n \n def getDisplayId_scratchInputCommandSummary (self):\n \"\"\"return a dict with scratch names as keys; values are list of to be animated elements\"\"\"\n res = {}\n for sic2d in self.scratch_input_command_2_display:\n sn = sic2d['name']\n ln = sic2d['id']\n if sn in res:\n res[sn].append( ln )\n else:\n res[sn] = [ ln ]\n return res \n\n def getDisplayId_scratchInputValueSummary (self):\n \"\"\"return a dict with scratch names as keys; values are list of to be animated elements\"\"\"\n res = {}\n for sic2d in self.scratch_input_value_2_display:\n sn = sic2d['name']\n ln = sic2d['id']\n if sn in res:\n res[sn].append( ln )\n else:\n res[sn] = [ ln ]\n return res \n\n def getDisplayId_scratchOutputCommandSummary (self):\n \"\"\"return a dict with scratch names as keys; values are list of to be animated elements\"\"\"\n res = {}\n for sic2d in self.scratch_output_command_2_display:\n sn = sic2d['name']\n ln = sic2d['id']\n if sn in res:\n res[sn].append( ln )\n else:\n res[sn] = [ ln ]\n return res \n\n def getDisplayId_scratchOutputValueSummary (self):\n \"\"\"return a dict with scratch names as keys; values are list of to be animated elements\"\"\"\n res = {}\n for sic2d in self.scratch_output_value_2_display:\n sn = sic2d['name']\n ln = sic2d['id']\n if sn in res:\n res[sn].append( ln )\n else:\n res[sn] = [ ln ]\n return res \n \nidManager = IDManager()\n# ------------------------------------------------------------------------------------------------\n# cherrypy-Handler\n \nclass BaseHandler(tornado.web.RequestHandler):\n \n def render_response(self, _template, context):\n# lookup = TemplateLookup(directories=['htdocs/static',\n# '../htdocs/static' \n# ], input_encoding='utf-8', output_encoding='utf-8',encoding_errors='replace')\n \n # Renders a template and writes the result to the response.\n \n context['debug'] = debug\n #\n # javascript needs lowecase true/false and can't use the python settings directly.\n #\n if debug: \n context['js_debug'] = 'true' \n else: \n context['js_debug'] = 'false'\n \n tmpl = lookup.get_template(_template)\n tmpl.strict_undefined=True\n \n try:\n ret = tmpl.render( ** context )\n except Exception as e:\n print(\"Exception !!\", e)\n traceback.print_exc()\n ret=\"unknown\"\n \n if debug: logger.debug (\"rendered: %s\", ret)\n self.write(ret)\n \n# def relPath(self, path):\n# p = configuration['webapp2_static']['static_file_path'] + path\n# logger.debug(\"relPath %s, %s, %s\", p, \"pwd\", os.getcwd())\n# return p#\n\n# def fullPath(self, path):\n# p = os.path.abspath(os.path.join( configuration['webapp2_static']['static_file_path'], path))\n# return p\n \n# ------------------------------------------------------------------------------------------------\n# cherrypy-Handler\nclass ScratchClientMain(BaseHandler):\n \n def initialize(self, additionalpaths):\n self.additionalpaths = additionalpaths\n pass\n \n def get(self):\n context = { 'additionalpaths' :self.additionalpaths }\n \n self.render_response('template/main.html', context)\n \nclass Usage14Handler(BaseHandler):\n \"\"\"return some usage hints for scratch\"\"\"\n def get(self):\n \n list_adapter_input_command = []\n list_adapter_output_command = []\n list_adapter_input_values = []\n list_adapter_output_values = []\n\n for _adapter in parentApplication.config.getAdapters():\n for inp in _adapter.inputs:\n for sn in inp.scratchNames:\n list_adapter_input_command.append( sn )\n\n \n for val in _adapter.input_values:\n for sn in val.scratchNames: \n list_adapter_input_values.append( sn)\n \n for out in _adapter.outputs:\n list_adapter_output_command.append( out.scratchNames[0] )\n \n for out in _adapter.output_values:\n list_adapter_output_values.append( out.scratchNames[0])\n \n context = {\n 'list_adapter_input_commands' : list_adapter_input_command,\n 'list_adapter_output_commands' : list_adapter_output_command, \n 'list_adapter_input_values' : list_adapter_input_values ,\n 'list_adapter_output_values' : list_adapter_output_values \n }\n \n return self.render_response('template/scratchUsage14.html', context)\n\n# ------------------------------------------------------------------------------------------------\nclass TemplateHandler(BaseHandler):\n def initialize(self, path):\n if debug:\n print(\"TemplateHandler\", \"path\", path)\n self.path = path \n \n def get(self, file):\n context = dict()\n self.render_response( self.path + '/' + file, context)\n\n\n# ------------------------------------------------------------------------------------------------\n#\nclass ConfigHandler(BaseHandler ):\n \"\"\"return the xml-config\"\"\"\n config = None\n \n \n def get(self):\n xmlConfigName = parentApplication.config.filename\n \n \n # xmlConfig = ET.tostring(parentApplication.config.tree.getroot(), encoding='us-ascii', method='xml')\n xmlConfigInput = ET.tostring(parentApplication.config.tree.getroot(), encoding='UTF-8', method='html')\n \n #\n # in python 2.7, there is a string array\n # in python 3.2, there is a bytes array\n \n if xmlConfigInput.__class__.__name__ == 'bytes':\n xmlConfig = xmlConfigInput.decode('UTF-8')\n else:\n \n xmlConfig = xmlConfigInput.decode('utf-8')\n \n \n \n xmlConfig= xmlConfig.replace('<', '<')\n xmlConfig= xmlConfig.replace('>', '>')\n xmlConfig= xmlConfig.replace('\\n', '
')\n\n context = {'configName': xmlConfigName, 'config':xmlConfig }\n \n self.render_response('template/config.html', context)\n \nclass ReleaseHandler(BaseHandler ):\n \"\"\"return the xml-config\"\"\"\n \n def get(self):\n\n context = { 'version': scratchClient.version, 'changes':scratchClient.changes }\n \n return self.render_response('template/release.html', context)\n\n# ------------------------------------------------------------------------------------------------\n# cherrypy-Handler\n#\nclass CommandHandler_InputSide(BaseHandler ):\n \"\"\"Command input from web interface\"\"\"\n \n def __init__(self):\n #publishSubscribe.Pub.subscribe('input.scratch.command')\n pass\n \n def post(self, adapter='', command='somecommand'):\n logger.debug(\"input, command=%s\", command)\n publishSubscribe.Pub.publish('input.scratch.{name:s}'.format(name=command), {'name':command})\n ## eventHandler.resolveCommand(self, adapter, command, qualifier='input')\n return \"no_return\"\n\n \nclass CommandHandler_OutputSide(BaseHandler ):\n \"\"\"Command input from web interface\"\"\"\n \n def __init__(self):\n #publishSubscribe.Pub.subscribe('input.scratch.command')\n pass\n \n def post(self, adapter='', command='somecommand'):\n logger.debug(\"output, command=%s\", command)\n publishSubscribe.Pub.publish('output.scratch.command', {'name':command})\n # eventHandler.resolveCommand(self, adapter, command, qualifier='output')\n return \"no_return\"\n\n# ------------------------------------------------------------------------------------------------\n# cherrypy-Handler\n#\n \nclass AdaptersHandler(BaseHandler):\n \"\"\"return a graphical representation of the adapter config\"\"\"\n\n def rectHelper(self, gg, _id=None,\n x = 0,\n y = 0, \n width=0,\n height = 0,\n style = ''):\n \n rect_Adapter = ET.SubElement(gg, \"rect\")\n if _id != None:\n rect_Adapter.set('id', str(_id) )\n rect_Adapter.set('x', str(x))\n rect_Adapter.set('y', str(y))\n rect_Adapter.set('width', str(width))\n rect_Adapter.set('height', str(height))\n rect_Adapter.set('style', style)\n\n return rect_Adapter\n\n def textHelper(self, gg, _id = None, \n text='notext', \n x= 0,\n y= 0,\n style = ''):\n \n rect_AdapterName = ET.SubElement(gg, \"text\")\n if _id != None:\n rect_AdapterName.set('id', str(_id))\n rect_AdapterName.set('x', str(x))\n rect_AdapterName.set('y', str(y))\n rect_AdapterName.text = text\n rect_AdapterName.set('style', style)\n\n \n def calculateHeight(self, _adapter):\n \"\"\"height in logical grid height units; depends on number of input/output, parameter etc\"\"\"\n \n l = 1 + len(_adapter.className.split('.'))\n if isinstance(_adapter, adapter.adapters.GPIOAdapter):\n l += len( _adapter.gpios )\n \n i = 0\n o = 0\n # inputs can have multiple scratch names\n for inp in _adapter.inputs:\n ix = len( inp.scratchNames )\n i += ix\n for inp in _adapter.input_values:\n ix = len( inp.scratchNames )\n i += ix\n i += len(_adapter.parameters)\n \n # outputs are 'unique'\n o += len(_adapter.outputs)\n o += len(_adapter.output_values)\n \n \n h = max(i, o, l)\n \n return h \n\n def createOnclickInputCommand(self, _id, scratch_name ):\n jScript = ''\n jScript += '{ \\n' \n jScript += ' obj = document.getElementById(\"{on:s}\"); \\n'.format(on=_id)\n jScript += ' if ( obj != null) \\n' \n jScript += ' obj.setAttribute(\"onclick\", \"click_Command(evt,\\'{id:s}\\' ,\\'{co:s}\\' , \\'{sc:s}\\' );\"); \\n'.format( id=_id, co='input.command', sc=scratch_name )\n jScript += '} \\n'\n return jScript\n \n def createOnclickOutputCommand(self, _id, scratch_name):\n jScript = ''\n jScript += '{ \\n' \n jScript += ' obj = document.getElementById(\"{id:s}\"); \\n'.format(id=_id)\n jScript += ' if ( obj != null) \\n' \n jScript += ' obj.setAttribute(\"onclick\", \"click_Command(evt,\\'{id:s}\\' ,\\'{co:s}\\' , \\'{sc:s}\\' );\"); \\n'.format( id=_id, co='output.command', sc=scratch_name )\n jScript += '} \\n'\n return jScript\n\n def createOnclickInputValue(self, objId, rectId, adapter_name, command_name):\n jScript = ''\n jScript += '{ \\n' \n #jScript += ' document.getElementById(\"{id:s}\").setAttribute(\"onclick\", \"click_Value_input(evt, \\'{rectId:s}\\', \\'{ad:s}\\', \\'{co:s}\\');\" ); \\n'.format(id=objId, rectId=rectId, ad=adapter_name, co=command_name)\n jScript += ' document.getElementById(\"{id:s}\").setAttribute(\"onclick\", \"click_Value_input_float(evt, \\'{rectId:s}\\', \\'{ad:s}\\', \\'{co:s}\\');\" ); \\n'.format(id=objId, rectId=rectId, ad='input.value', co=command_name)\n jScript += '} \\n'\n return jScript\n \n def createOnclickOutputValue(self, objId, rectId, adapter_name, command_name):\n jScript = ''\n jScript += '{ \\n' \n #jScript += ' document.getElementById(\"{id:s}\").setAttribute(\"onclick\", \"click_Value_output(evt, \\'{rectId:s}\\', \\'{ad:s}\\', \\'{co:s}\\');\" ); \\n'.format(id=objId, rectId=rectId, ad=adapter_name, co=command_name)\n jScript += ' document.getElementById(\"{id:s}\").setAttribute(\"onclick\", \"click_Value_input_float(evt, \\'{rectId:s}\\', \\'{ad:s}\\', \\'{co:s}\\');\" ); \\n'.format(id=objId, rectId=rectId, ad='output.value', co=command_name)\n jScript += '} \\n'\n return jScript\n \n def get(self):\n idManager.reset()\n xmlConfigName = parentApplication.config.filename\n description = parentApplication.config.getDescription().replace('\\n', '
')\n \n jScript = '\"use strict\"; \\n'\n jScript += 'let obj; \\n'\n \n list_adapter_input_command = []\n list_adapter_output_command = []\n #\n # build svn tree from adapters\n #\n # styles\n #\n textStyleDefault = 'font-size:12px;font-style:normal;font-weight:normal;line-current_height:125%;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;font-family:sans-serif'\n textStyle = textStyleDefault\n \n boldTextStyleDefault = 'font-size:12px;font-style:normal;font-weight:bold;line-current_height:125%;letter-spacing:0px;word-spacing:0px;fill:#0000ff;fill-opacity:1;stroke:none;font-family:sans-serif'\n boldTextStyle = boldTextStyleDefault\n \n gpioTextStyleDefault = 'font-size:8px;font-style:normal;font-weight:normal;line-current_height:125%;letter-spacing:0px;word-spacing:0px;fill:#808080;fill-opacity:1;stroke:none;font-family:sans-serif'\n gpioTextStyle = gpioTextStyleDefault\n \n rectStyleDefault = 'fill:#e0e0e0;fill-opacity:0.52208835;stroke:#0000ff;stroke-width:1;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none'\n rectStyle = rectStyleDefault\n # make command input areas visible by slightly darker background\n commandBackgroundStyleDefault = 'fill:#e0e0e0'\n commandBackgroundStyleTest = 'fill:#808080'\n \n commandBackgroundStyle = commandBackgroundStyleDefault\n if debug:\n commandBackgroundStyle = commandBackgroundStyleTest\n \n commandBackgroundStyle2Default = 'fill:#ff0000'\n commandBackgroundStyle2 = commandBackgroundStyle2Default\n \n valueStyleDefault = 'stroke:#0000ff;stroke-width:1'\n valueStyle = valueStyleDefault\n paraLineStyleDefault = 'fill:none;stroke:#00FF00;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1'\n paraLineStyle = paraLineStyleDefault\n \n inputLineStyleDefault = 'fill:none;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1'\n inputLineStyle = inputLineStyleDefault\n \n helperLineStyleDefault = 'fill:none;stroke:#303030;stroke-width:2px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1'\n helperLineStyle = helperLineStyleDefault\n #\n ET.register_namespace('', 'http://www.w3.org/2000/svg' )\n svg = ET.Element(\"{http://www.w3.org/2000/svg}svg\")\n g = ET.SubElement(svg, \"g\")\n\n\n column_10 = 1\n column_20 = 120\n column_20_parameter = 80\n # parameter und Werteeingabe\n column_30 = 220\n # Linie Eingang\n column_40 = 340\n # Adapter\n column_50 = 460\n # output line \n column_60 = 580\n # output values\n column_70 = 680\n column_80 = 800\n column_90 = 820\n \n # absolute current_height used so far\n current_height = 1 # top margin\n vSpacing = 20\n vGap = 4\n \n if debug_grid:\n # display a grid\n grid = {'c10' : column_10, \n 'c20' : column_20, \n 'c30' : column_30, \n 'c40' : column_40, \n 'c50' : column_50, \n 'c60' : column_60, \n 'c70' : column_70, \n 'c80' : column_80, \n 'c90' : column_90,\n 'c20p': column_20_parameter }\n \n for n in grid:\n x = grid[n]\n line_Val = ET.SubElement(g, \"line\")\n line_Val.set('x1', str(x) )\n line_Val.set('x2', str(x) )\n line_Val.set('y1', str(current_height) )\n line_Val.set('y2', str(current_height+vSpacing) )\n line_Val.set('style', helperLineStyle )\n \n self.textHelper( g, text= n, \n x= x+5 ,\n y= current_height +vSpacing,\n style = boldTextStyle)\n \n current_height += vSpacing\n\n for _adapter in parentApplication.config.getAdapters():\n gg = ET.SubElement(g, \"g\")\n \n h = self.calculateHeight(_adapter)\n inside_box_lines = 0\n a = self.rectHelper(gg, _id='adapter' + '_' + _adapter.name,\n x = column_40,\n y = current_height, \n width=column_50-column_40,\n height = h * vSpacing + vSpacing,\n style = rectStyle)\n \n t = ET.SubElement(a, 'title')\n t.text=_adapter.description\n \n self.textHelper(gg, text=_adapter.name, \n x= column_40 + 5,\n y= current_height + (inside_box_lines +1) * vSpacing,\n style = boldTextStyle)\n \n inside_box_lines += 1\n # print the class name in multiple lines\n #\n class_segments = _adapter.className.split('.')\n \n for i in range( len(class_segments) ):\n s = class_segments[i]\n self.textHelper(gg, text=s, \n x= column_40 + 5,\n y= current_height + (inside_box_lines +1) * vSpacing,\n style = textStyle)\n inside_box_lines += 1\n \n if isinstance(_adapter, adapter.adapters.GPIOAdapter):\n gi = 1\n for gpio in _adapter.gpios:\n \n atext = ''\n if gpio.alias == None:\n atext = \"[{num:02d}] {name:s}\".format(name=gpio.port, num=gpio.portNumber)\n else:\n atext = \"[{num:02d}] {name:s} ({alias:s})\".format(name=gpio.port, num=gpio.portNumber, alias=gpio.alias)\n \n self.textHelper(gg, text=atext , \n x= column_40 + 5,\n y= current_height + (inside_box_lines +1) * vSpacing,\n style = gpioTextStyle)\n gi += 1\n inside_box_lines += 1\n \n # leftside are the left side connectors\n leftSide = 0 \n for inp in _adapter.inputs:\n \n nCommand = 0\n for _ in range(len(inp.scratchNames)):\n \n _id_backanimation = idManager.getDisplayId_scratchInputCommand( inp.scratchNames[nCommand] )\n _id_back = idManager.getId( )\n _id_text = idManager.getId( )\n # list_adapter_input_command .append([_id , _id + \"_back\"])\n \n jScript += self.createOnclickInputCommand(_id_text , inp.scratchNames[nCommand])\n jScript += self.createOnclickInputCommand(_id_back , inp.scratchNames[nCommand])\n \n textInpBack = self.rectHelper(gg, _id=_id_back,\n x = column_10,\n y = current_height + (leftSide+0+nCommand) * vSpacing + vGap, \n width=column_20-column_10,\n height = vSpacing-vGap,\n style = commandBackgroundStyle)\n \n animate = ET.SubElement(textInpBack, \"animate\")\n animate.set(\"id\", _id_backanimation)\n animate.set(\"attributeType\", \"CSS\")\n animate.set(\"attributeName\", \"fill\") \n animate.set(\"from\", \"#ffffff\")\n animate.set(\"to\", \"#ff0000\")\n animate.set(\"dur\", \"0.3s\");\n \n text_Inp_Cmd = self.textHelper(gg, text=inp.scratchNames[nCommand], \n _id = _id_text,\n x= column_10+5,\n y= current_height + (leftSide+1+nCommand) * vSpacing - vGap,\n style = textStyle)\n\n line_Inp = ET.SubElement(gg, \"line\")\n line_Inp.set('x1', str(column_10) )\n line_Inp.set('x2', str(column_20+1) )\n line_Inp.set('y1', str(current_height + (leftSide+1+nCommand) * vSpacing) )\n line_Inp.set('y2', str(current_height + (leftSide+1+nCommand) * vSpacing) )\n line_Inp.set('style', inputLineStyle )\n \n if nCommand > 0:\n line_Inp = ET.SubElement(gg, \"line\")\n line_Inp.set('x1', str(column_20) )\n line_Inp.set('x2', str(column_20) )\n line_Inp.set('y1', str(current_height + (leftSide+1+nCommand-1) * vSpacing) )\n line_Inp.set('y2', str(current_height + (leftSide+1+nCommand-0) * vSpacing) )\n line_Inp.set('style', inputLineStyle )\n \n nCommand += 1\n \n text_Inp = ET.SubElement(gg, \"text\")\n text_Inp.set('x', str(column_30+3))\n text_Inp.set('y', str(current_height + (leftSide+nCommand) * vSpacing - vGap))\n text_Inp.text = inp.name\n text_Inp.set('style', textStyle)\n \n line_Inp = ET.SubElement(gg, \"line\")\n line_Inp.set('x1', str(column_20) )\n line_Inp.set('x2', str(column_40) )\n line_Inp.set('y1', str(current_height + (leftSide+nCommand) * vSpacing) )\n line_Inp.set('y2', str(current_height + (leftSide+nCommand) * vSpacing) )\n line_Inp.set('style', inputLineStyle )\n \n leftSide += nCommand\n \n for val in _adapter.input_values:\n nValue = 0\n for _ in range(len(val.scratchNames)): \n _id_text = idManager.getDisplayId_scratchInputValue( val.scratchNames[nValue] )\n _id = idManager.getId()\n \n rect_Out = ET.SubElement(gg, \"rect\")\n rect_Out.set('id', _id+'_back')\n rect_Out.set('x', str(column_20))\n rect_Out.set('y', str(current_height + (leftSide+0+nValue) * vSpacing + vGap ))\n rect_Out.set('width', str(column_30-column_20))\n rect_Out.set('height', str(vSpacing - vGap))\n rect_Out.set('style', rectStyle)\n \n textValue_Out = ET.SubElement(gg, \"text\")\n textValue_Out.set('id', _id_text )\n textValue_Out.set('x', str(column_20+4 ))\n textValue_Out.set('y', str(current_height + (leftSide+1+nValue) * vSpacing - vGap))\n textValue_Out.text = '?'\n textValue_Out.set('style', textStyle)\n\n jScript += self.createOnclickInputValue( _id_text , _id+'_back', _adapter.name, val.scratchNames[nValue])\n jScript += self.createOnclickInputValue( _id+'_back', _id+'_back', _adapter.name, val.scratchNames[nValue])\n\n text_Val = ET.SubElement(gg, \"text\")\n text_Val.set('x', str(column_10))\n text_Val.set('y', str(current_height + (leftSide+1+nValue) * vSpacing - vGap ))\n text_Val.text = val.scratchNames[nValue]\n text_Val.set('style', textStyle)\n \n line_Val = ET.SubElement(gg, \"line\")\n line_Val.set('x1', str(column_10) )\n line_Val.set('x2', str(column_20) )\n line_Val.set('y1', str(current_height + (leftSide+1+nValue) * vSpacing) )\n line_Val.set('y2', str(current_height + (leftSide+1+nValue) * vSpacing) )\n line_Val.set('style', inputLineStyleDefault )\n \n nValue += 1\n\n text_Val = ET.SubElement(gg, \"text\")\n text_Val.set('x', str(column_30 +4 ))\n text_Val.set('y', str(current_height + (leftSide+0+nValue) * vSpacing - vGap))\n text_Val.text = val.name\n text_Val.set('style', textStyle)\n \n\n line_Val = ET.SubElement(gg, \"line\")\n line_Val.set('x1', str(column_30) )\n line_Val.set('x2', str(column_40) )\n line_Val.set('y1', str(current_height + (leftSide+0+nValue) * vSpacing) )\n line_Val.set('y2', str(current_height + (leftSide+0+nValue) * vSpacing) )\n line_Val.set('style', inputLineStyleDefault )\n \n leftSide += nValue\n \n for para in _adapter.parameters:\n \n text_Para = ET.SubElement(gg, \"text\")\n text_Para.set('x', str(column_20_parameter))\n text_Para.set('y', str(current_height + (leftSide+1) * vSpacing - vGap))\n text_Para.text = para + '= ' + _adapter.parameters[para]\n text_Para.set('style', textStyle)\n \n line_Para = ET.SubElement(gg, \"line\")\n line_Para.set('x1', str( column_20_parameter) )\n line_Para.set('x2', str( column_40) )\n line_Para.set('y1', str(current_height + (leftSide+1) * vSpacing) )\n line_Para.set('y2', str(current_height + (leftSide+1) * vSpacing) )\n line_Para.set('style', paraLineStyle )\n \n leftSide += 1\n \n # rightside are the output connectors \n rightSide = 0 \n \n for out in _adapter.outputs:\n \n text_Out = ET.SubElement(gg, \"text\")\n text_Out.set('x', str(column_50+5))\n text_Out.set('y', str(current_height + (rightSide+1) * vSpacing - vGap))\n text_Out.text = out.name\n text_Out.set('style', textStyle)\n \n _id = 'adapter_' + _adapter.name + '_' + out.scratchNames[0]\n _id_backanimation = idManager.getDisplayId_scratchOutputCommand( out.scratchNames[0] )\n \n jScript += self.createOnclickOutputCommand(_id + \"_text\", out.scratchNames[0])\n jScript += self.createOnclickOutputCommand(_id + \"_back\", out.scratchNames[0])\n \n textInpBack = ET.SubElement(gg, \"rect\")\n textInpBack.set('id', _id+ '_back' )\n textInpBack.set('x', str(column_70))\n textInpBack.set('y', str(current_height + (rightSide+0) * vSpacing + vGap))\n textInpBack.set('width', str(column_80-column_70))\n textInpBack.set('height', str(vSpacing - vGap))\n textInpBack.set('style', commandBackgroundStyle)\n\n animate = ET.SubElement(textInpBack, \"animate\")\n animate.set(\"id\", _id_backanimation)\n animate.set(\"attributeType\", \"CSS\")\n animate.set(\"attributeName\", \"fill\") \n animate.set(\"from\", \"#ffffff\")\n animate.set(\"to\", \"#ff0000\")\n animate.set(\"dur\", \"0.3s\");\n \n text_Command = ET.SubElement(gg, \"text\")\n text_Command.set('id', _id+ '_text' )\n text_Command.set('x', str(column_70+5))\n text_Command.set('y', str(current_height + (rightSide+1) * vSpacing-vGap))\n text_Command.text = out.scratchNames[0]\n text_Command.set('style', textStyle)\n\n \n line_Out = ET.SubElement(gg, \"line\")\n line_Out.set('x1', str(column_50) )\n line_Out.set('x2', str(column_80) )\n line_Out.set('y1', str(current_height + (rightSide+1) * vSpacing) )\n line_Out.set('y2', str(current_height + (rightSide+1) * vSpacing ))\n line_Out.set('style', inputLineStyleDefault )\n\n rightSide += 1\n \n for out in _adapter.output_values:\n _id = 'adapter_{an:s}_{on:s}'.format(an=_adapter.name, on=out.scratchNames[0])\n _id_text = idManager.getDisplayId_scratchOutputValue(out.scratchNames[0])\n \n text_Out = ET.SubElement(gg, \"text\")\n text_Out.set('x', str(column_50+5))\n text_Out.set('y', str(current_height + (rightSide+1) * vSpacing -vGap ))\n text_Out.text = out.name\n text_Out.set('style', textStyle)\n \n text_Command = ET.SubElement(gg, \"text\")\n text_Command.set('x', str(column_70+5 ))\n text_Command.set('y', str(current_height + (rightSide+1) * vSpacing - vGap))\n text_Command.text = out.scratchNames[0]\n text_Command.set('style', textStyle)\n \n line_Out = ET.SubElement(gg, \"line\")\n line_Out.set('x1', str(column_50) )\n line_Out.set('x2', str(column_80) )\n line_Out.set('y1', str(current_height + (rightSide+1) * vSpacing) )\n line_Out.set('y2', str(current_height + (rightSide+1) * vSpacing ))\n line_Out.set('style', inputLineStyleDefault )\n\n rect_Out = ET.SubElement(gg, \"rect\")\n rect_Out.set('id', _id + '_back')\n rect_Out.set('x', str(column_60))\n rect_Out.set('y', str(current_height + (rightSide+0) * vSpacing + vGap))\n rect_Out.set('width', str(column_70-column_60))\n rect_Out.set('height', str(vSpacing - vGap))\n rect_Out.set('style', rectStyle)\n\n # logger.debug(\"output_box id %s\", _id)\n \n \n textValue_Out = ET.SubElement(gg, \"text\")\n textValue_Out.set('id', _id_text)\n textValue_Out.set('x', str(column_60+5))\n textValue_Out.set('y', str(current_height + (rightSide+1) * vSpacing -vGap))\n textValue_Out.text = '?'\n textValue_Out.set('style', textStyle)\n \n jScript += self.createOnclickOutputValue(_id+'_back', _id+'_back', _adapter.name, out.scratchNames[0])\n jScript += self.createOnclickOutputValue(_id_text , _id+'_back', _adapter.name, out.scratchNames[0])\n \n rightSide += 1\n \n # keep track of current_height, add some gap between adapters. \n current_height += h*vSpacing + vSpacing + 10\n \n svg.set('width', str(column_90+1))\n svg.set('height', str(current_height+20))\n \n if sys.version_info.major == 2:\n svgText = ET.tostring(svg)\n \n if sys.version_info.major == 3:\n svgText = ET.tostring(svg).decode('utf-8')\n \n if debug:\n print(svgText) \n logger.debug(svgText)\n\n #\n # javascript, tooltips\n #\n \n for _adapter in parentApplication.config.getAdapters():\n adapterId = 'adapter_{an:s}'.format(an=_adapter.name )\n \n\n jScript += ' let websocket = new WebSocket(\"ws://\" + window.location.host + \"/ws\"); \\n'\n jScript += \"\"\"\n websocket.onmessage = function(e){\n let server_message = e.data;\n console.log(server_message);\n let jObj = JSON.parse(server_message); \n\"\"\"\n # --------------------------\n #\n # add the scratch command to id-mappers\n jScript += \" if ( jObj.command == 'scratch_input_command' ){ \\n\"\n res = idManager.getDisplayId_scratchInputCommandSummary()\n for sn in res.keys():\n jScript += \" if ( jObj.name == \\\"{name:s}\\\" ){{\\n\".format( name=sn )\n for ln in res[sn]:\n jScript += \" document.getElementById( \\\"{id:s}\\\" ).beginElement();\\n\".format(id=ln)\n jScript += \" }\\n\" \n jScript += \" }\\n\"\n # --------------------------\n \n #\n # add the scratch command to id-mappers\n res = idManager.getDisplayId_scratchInputValueSummary()\n jScript += \" if ( jObj.command == 'scratch_input_value' ){ \\n\"\n for sn in res.keys():\n jScript += \" if ( jObj.name == \\\"{name:s}\\\" ){{\\n\".format( name=sn )\n for ln in res[sn]:\n jScript += \" document.getElementById( \\\"{id:s}\\\" ).textContent = jObj.value;\\n\".format(id=ln)\n jScript += \" }\\n\" \n jScript += \" }\\n\"\n # --------------------------\n #\n # add the scratch command to id-mappers\n res = idManager.getDisplayId_scratchOutputCommandSummary()\n jScript += \" if ( jObj.command == 'scratch_output_command' ){ \\n\"\n for sn in res.keys():\n jScript += \" if ( jObj.name == \\\"{name:s}\\\" ){{\\n\".format( name=sn )\n for ln in res[sn]:\n jScript += \" document.getElementById( \\\"{id:s}\\\" ).beginElement();\\n\".format(id=ln)\n jScript += \" }\\n\" \n jScript += \" } \\n\"\n\n #\n # add the scratch command to id-mappers\n jScript += \" if ( jObj.command == 'scratch_output_value' ){ \\n\"\n res = idManager.getDisplayId_scratchOutputValueSummary()\n for sn in res.keys():\n jScript += \" if ( jObj.name == \\\"{name:s}\\\" ){{\\n\".format( name=sn )\n for ln in res[sn]:\n jScript += \" document.getElementById( \\\"{id:s}\\\" ).textContent = jObj.value;\\n\".format(id=ln)\n jScript += \" }\\n\" \n jScript += \" } \\n\"\n \n \n jScript += \"\"\" }\n \n websocket.onopen = function(){\n console.log('Connection open');\n document.getElementById(\"status.host\").textContent ='Connection to scratchClient open';\n document.getElementById(\"status.host\").style.background = 'green';\n }\n \n websocket.onclose = function(){\n console.log('Connection closed');\n document.getElementById(\"status.host\").textContent ='Connection to scratchClient closed';\n document.getElementById(\"status.host\").style.background = 'red';\n }\n \n // click on an object (send event)\n function click_Command (evt, id, command, scratch){\n try {\n let message = JSON.stringify( { id:id, command:command, scratch:scratch } );\n console.log( 'message: ' + message); \n websocket.send(message);\n } catch(err) {\n console.log( err.message );\n }\n }\n \"\"\"\n #\n # Output Values, need an editor popup\n #\n html_preamble = \"\"\"\n \n \n \n \n
\n
\n \"\"\"\n \n if debug:\n #\n # place mouse coordinates to screen. \n jScript += \"\"\"\n function readMouseMove(e){\n var result_x = document.getElementById('x_result');\n var result_y = document.getElementById('y_result');\n result_x.innerHTML = e.clientX;\n result_y.innerHTML = e.clientY;\n }\n document.onmousemove = readMouseMove;\n \"\"\"\n html_preamble += \"\"\" \n
X
\n
Y
\n \n \"\"\"\n\n html_preamble += \"\"\"\n
\n
    \n
\n \"\"\"\n \n jScript += \"\"\"\n function close_floatInput(evt){\n let tstObj = document.getElementById(\"DIV.float\"); \n tstObj.style.display = 'none';\n }\n let pupup_state;\n function searchKeyPressInput_float(e){\n \n let textObj = document.getElementById(\"I00.float\"); \n \n console.log(\"command \" + pupup_state.command);\n console.log(\"name \" + pupup_state.name);\n console.log(\"value \" + textObj.value);\n \n // look for window.event in case event isn't passed in\n if (typeof e == 'undefined' && window.event) { e = window.event; }\n if (e.keyCode == 13)\n {\n let message = JSON.stringify( { command: pupup_state.command, scratch:pupup_state.name, value:textObj.value } )\n websocket.send ( message) \n textObj.value = ''\n }\n } \n function click_Value_input_float(evt, svgid, command, value_name){\n console.log(\"command \" + command);\n console.log(\"name \" + value_name);\n console.log(\"svgid \" + svgid);\n \n let svgText = document.getElementById(svgid);\n let bbox = svgText.getBBox();\n \n let divSvg = document.getElementById(\"DIV.svg\");\n \n // var x = divSvg.offsetLeft + bbox.x;\n // var y = divSvg.offsetHeight + bbox.y;\n\n let x_svg = divSvg.getBoundingClientRect().left;\n let y_svg = divSvg.getBoundingClientRect().top;\n\n let tstHeader = document.getElementById(\"HEADER.float\"); \n tstHeader.textContent = value_name;\n \n console.log(\"bbox.x \" + bbox.x);\n console.log(\"bbox.y \" + bbox.y);\n \n console.log(\"divSvg.offsetLeft \" + divSvg.offsetLeft );\n console.log(\"divSvg.offsetHeight \" + divSvg.offsetHeight );\n console.log(\"divSvg.left \" + divSvg.left );\n console.log(\"divSvg.top \" + divSvg.top );\n\n let tstObj = document.getElementById(\"DIV.float\");\n \n console.log(\"set to x \" + (bbox.x + x_svg) );\n console.log(\"set to y \" + (bbox.y + y_svg) );\n \n tstObj.style.left = (bbox.x + x_svg ) + 'px';\n tstObj.style.top = (bbox.y + y_svg + 20 ) + 'px';\n \n tstObj.style.position = 'fixed'; //'absolute';\n \n tstObj.style.display = 'initial';\n \n pupup_state = { command: command, name: value_name};\n \n let textObj = document.getElementById(\"I00.float\"); \n textObj.onkeypress = function(e){ searchKeyPressInput_float( e ); };\n \n }\n \"\"\"\n \n if debug: logger.debug (jScript)\n context = {'description' : description,\n 'html_preamble': html_preamble, \n 'svg' : svgText ,\n 'jScript' : jScript ,\n 'configName' : xmlConfigName,\n 'debug_grid' : debug_grid }\n \n return self.render_response('template/adapters.html', context)\n \n \n\n\nclass AdapterAnimationWebSocket(tornado.websocket.WebSocketHandler):\n \n def __init__(self, args, kwargs):\n tornado.websocket.WebSocketHandler.__init__(self, args, kwargs)\n self.terminated = None\n logger.info(\"AdapterAnimationWebSocket.init\")\n\n def on_message(self, message):\n \"\"\"\n Automatically sends back the provided ``message`` to\n its originating endpoint.\n \"\"\"\n if debug: print(\"on_message: \" + message)\n try:\n if sys.version_info.major < 3:\n if debug:\n print('message.data:', message)\n md = message\n if debug:\n print('md:', md)\n \n msg = json.loads( md )\n \n if sys.version_info.major == 3:\n if debug:\n print('message.data:', message)\n md = message\n if debug:\n print('md:', md)\n msg = json.loads( md )\n \n if msg['command'] == 'input.command':\n publishSubscribe.Pub.publish('scratch.input.command.{name:s}'.format(name=msg['scratch']), { 'name':msg['scratch'] } ) \n \n if msg['command'] == 'output.command':\n publishSubscribe.Pub.publish('scratch.output.command.{name:s}'.format(name=msg['scratch']), { 'name':msg['scratch'] } ) \n \n if msg['command'] == 'input.value':\n publishSubscribe.Pub.publish('scratch.input.value.{name:s}'.format(name=msg['scratch']), { 'name':msg['scratch'], 'value':msg['value'] } ) \n \n if msg['command'] == 'output.value':\n publishSubscribe.Pub.publish('scratch.output.value.{name:s}'.format(name=msg['scratch']), { 'name':msg['scratch'], 'value':msg['value'] } ) \n \n except Exception as e:\n print(\"Exception !!\", e)\n traceback.print_exc()\n \n def open(self):\n if debug: print(\"websocket open: \" )\n\n self.terminated = False\n for _adapter in parentApplication.config.getAdapters():\n for inp in _adapter.inputs:\n for scratchName in inp.scratchNames:\n publishSubscribe.Pub.subscribe(\"scratch.input.command.{name:s}\".format(name=scratchName), self.inputCommand )\n for inp in _adapter.input_values:\n for scratchName in inp.scratchNames:\n publishSubscribe.Pub.subscribe(\"scratch.input.value.{name:s}\".format(name=scratchName), self.inputValue )\n \n for out in _adapter.outputs:\n for scratchName in out.scratchNames:\n publishSubscribe.Pub.subscribe(\"scratch.output.command.{name:s}\".format(name=scratchName), self.outputCommand )\n for out in _adapter.output_values:\n for scratchName in out.scratchNames:\n publishSubscribe.Pub.subscribe(\"scratch.output.value.{name:s}\".format(name=scratchName), self.outputValue )\n \n def on_close(self, *args, **kwargs):\n if debug: print (\"on_close\", args, kwargs)\n self.terminated = True\n self.closed(22)\n \n def closed(self, code, reason=None):\n for _adapter in parentApplication.config.getAdapters():\n for inp in _adapter.inputs:\n for scratchName in inp.scratchNames:\n publishSubscribe.Pub.unsubscribe(\"scratch.input.command.{name:s}\".format(name=scratchName), self.inputCommand )\n for inp in _adapter.input_values:\n for scratchName in inp.scratchNames:\n publishSubscribe.Pub.unsubscribe(\"scratch.input.value.{name:s}\".format(name=scratchName), self.inputValue )\n \n for out in _adapter.outputs:\n for scratchName in out.scratchNames:\n publishSubscribe.Pub.unsubscribe(\"scratch.output.command.{name:s}\".format(name=scratchName), self.outputCommand )\n for out in _adapter.output_values:\n for scratchName in out.scratchNames:\n publishSubscribe.Pub.unsubscribe(\"scratch.output.value.{name:s}\".format(name=scratchName), self.outputValue ) \n\n def _addMessage(self, message):\n \"\"\" called from the tornado.localIOloop.IOLoop.current().add_callback framework \"\"\" \n if self.terminated == True:\n if debug: print(\"ScratchXWebSocketHandler[{cnt:d}] receive _addMessage while TERMINATED\".format(cnt=self._instanceCount ))\n else:\n self.write_message (message, False )\n\n \n def inputValue(self, message):\n if debug: print(\"websocket inputValue\", message)\n message['command'] = 'scratch_input_value'\n if useLocalIOloop:\n localIOloop.add_callback( self._addMessage, json.dumps(message) )\n else:\n tornado.ioloop.IOLoop.current().add_callback( self._addMessage, json.dumps(message) )\n \n def inputCommand(self, message):\n if debug: print(\"websocket inputCommand\", message)\n message['command'] = 'scratch_input_command'\n if useLocalIOloop:\n localIOloop.add_callback( self._addMessage, json.dumps(message) )\n else:\n tornado.ioloop.IOLoop.current().add_callback( self._addMessage, json.dumps(message) )\n \n def outputValue(self, message):\n message['command'] = 'scratch_output_value'\n if useLocalIOloop:\n localIOloop.add_callback( self._addMessage, json.dumps(message) )\n else:\n tornado.ioloop.IOLoop.current().add_callback( self._addMessage, json.dumps(message) )\n \n def outputCommand(self, message):\n message['command'] = 'scratch_output_command'\n if useLocalIOloop:\n localIOloop.add_callback( self._addMessage, json.dumps(message) )\n else:\n tornado.ioloop.IOLoop.current().add_callback( self._addMessage, json.dumps(message) )\n \n\nclass ValueHandler_InputSide:\n def __init__(self):\n # eventHandler.register('ValueHandler', 'ValueHandler', self)\n pass\n \n def post(self, adapter, command, value):\n logger.debug(\"input value called %s, %s, %s\", adapter, command, value)\n # eventHandler.resolveValue(self, adapter, command, value, qualifier='input')\n return \"no_return\"\n\n return \"\"\n\n\nclass ValueHandler_OutputSide:\n def __init__(self):\n # eventHandler.register('ValueHandler', 'ValueHandler', self)\n pass\n \n\n def post(self, adapter, command, value):\n logger.debug(\"output value called %s, %s, %s\", adapter, command, value)\n # eventHandler.resolveValue(self, adapter, command, value, qualifier='output')\n return \"\"\n\nsendQueue = helper.abstractQueue.AbstractQueue() \n\nclass ScratchXWebSocketHandler(tornado.websocket.WebSocketHandler):\n instanceCount = 0\n \n def __init__(self, args, kwargs):\n ScratchXWebSocketHandler.instanceCount += 1\n self._instanceCount = ScratchXWebSocketHandler.instanceCount\n tornado.websocket.WebSocketHandler.__init__(self, args, kwargs)\n self.terminated = False\n\n scratchXHandler.subscribe(self)\n if debug: print(\"ScratchxWebSocketHandler[{cnt:d}].init\".format(cnt=self._instanceCount) )\n \n def check_origin(self, origin):\n \"\"\"Access-Control-Allow-Origin ...\"\"\"\n return True\n\n def open(self, *args, **kwargs):\n if debug: print(\"ScratchXWebSocketHandler[{cnt:d}], open\".format(cnt=self._instanceCount) )\n scratchXHandler.event_connect()\n\n def on_close(self, *args, **kwargs):\n if debug: print (\"ScratchXWebSocketHandler[{cnt:d}], on_close\".format(cnt=self._instanceCount ))\n scratchXHandler.event_disconnect()\n scratchXHandler.unsubscribe(self)\n self.runMessageSend = False\n self.terminated = True\n \n def on_message(self, message):\n if logger.isEnabledFor(logging.DEBUG):\n logger.debug ( \"ScratchXWebSocketHandler[{cnt:d}], received {m:s}\".format(cnt=self._instanceCount, m=message ))\n try:\n if sys.version_info.major < 3:\n if debug:\n print('message.data:', message)\n md = message\n if debug:\n print('md:', md)\n \n msg = json.loads( md )\n \n if sys.version_info.major >= 3:\n if debug:\n print('message.data:', message)\n md = message\n if debug:\n print('md:', md)\n msg = json.loads( md )\n \n if msg['command'] == 'input.command':\n publishSubscribe.Pub.publish('scratch.input.command.{name:s}'.format(name=msg['scratch']), { 'name':msg['scratch'] } ) \n \n if msg['command'] == 'input.value':\n publishSubscribe.Pub.publish('scratch.input.value.{name:s}'.format(name=msg['scratch']), { 'name':msg['scratch'], 'value':msg['value'] } ) \n \n except Exception as e:\n print(\"Exception !!\", e, message)\n traceback.print_exc()\n\n \n def _addMessage(self, message):\n \"\"\" called from the tornado.localIOloop.IOLoop.current().add_callback framework \"\"\" \n if self.terminated == True:\n if debug: print(\"ScratchXWebSocketHandler[{cnt:d}] receive _addMessage while TERMINATED\".format(cnt=self._instanceCount ))\n else:\n self.write_message (message, False )\n \n def inputValue(self, message):\n if debug: print(\"ScratchXWebSocketHandler[{cnt:d}] websocket inputValue {m:s}\".format(cnt=self._instanceCount , m= message) )\n message['command'] = 'scratch_input_value'\n if useLocalIOloop:\n localIOloop.add_callback( self._addMessage, message )\n else:\n tornado.ioloop.IOLoop.current().add_callback( self._addMessage, message )\n \n def inputCommand(self, message):\n if debug: print(\"ScratchXWebSocketHandler[{cnt:d}] websocket inputCommand {m:s}\".format(cnt=self._instanceCount , m= message) )\n message['command'] = 'scratch_input_command'\n if useLocalIOloop:\n localIOloop.add_callback( self._addMessage, message )\n else:\n tornado.ioloop.IOLoop.current().add_callback( self._addMessage, message )\n \n def sendValue(self, message):\n \"\"\"established by configureCommandResolver\"\"\"\n if debug: print(\"ScratchXWebSocketHandler[{cnt:d}] websocket sendValue {m:s}\".format(cnt=self._instanceCount , m= str(message)) )\n message['command'] = 'scratch_output_value'\n if useLocalIOloop:\n localIOloop.add_callback( self._addMessage, message )\n else:\n tornado.ioloop.IOLoop.current().add_callback( self._addMessage, message )\n \n def sendCommand(self, message):\n \"\"\"established by configureCommandResolver\"\"\"\n if debug: print(\"ScratchXWebSocketHandler[{cnt:d}] websocket sendCommand {m:s}\".format(cnt=self._instanceCount , m= str(message)) )\n message['command'] = 'scratch_output_command'\n if useLocalIOloop:\n localIOloop.add_callback( self._addMessage, message )\n else:\n tornado.ioloop.IOLoop.current().add_callback( self._addMessage, message )\n\nclass JSName_VariableName:\n def __init__(self, variable, jsVariable):\n self.variable = variable\n self.jsVariable = jsVariable\n def __str__(self):\n return 'JSName_VariableName[variable=' + self.variable + ';' + 'jsVariable=' + self.jsVariable + ']'\n \nclass JSName_VariableName_Provider:\n \"\"\"provide jsNames and variable names\"\"\"\n \n def __init__(self):\n self.variable_names = dict()\n \n def get(self, variable): \n \n self.variable = variable\n if variable in self.variable_names:\n return self.variable_names[variable]\n else:\n jsVariable = \"{s:s}\".format( s=uuid.uuid3( uuid.NAMESPACE_URL ,variable).hex )\n j = JSName_VariableName( variable, jsVariable)\n self.variable_names[variable] = j\n \n return j\n \nclass ScratchXConfigHandler(BaseHandler):\n \n def initialize(self, extensionFile):\n self.extensionFile = extensionFile\n pass\n\n def set_default_headers(self):\n if debug: print(\"setting headers!!!\")\n self.set_header(\"Access-Control-Allow-Origin\", \"*\")\n self.set_header(\"Access-Control-Allow-Headers\", \"x-requested-with\")\n self.set_header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS')\n \n def get(self):\n context = dict()\n context[\"scratchClient_host\"] = self.request.host\n variableName_Provider = JSName_VariableName_Provider()\n # the sensor names are used as variable names in javascript, so there are some limitations\n # on chars used in these names.\n \n # make a list of sensor_values\n sensor_names = []\n for _adapter in parentApplication.config.getAdapters():\n for out in _adapter.output_values:\n on= variableName_Provider.get( out.scratchNames[0] )\n sensor_names.append( on )\n context[ \"sensor_names\"] = sensor_names \n \n send_events = []\n for _adapter in parentApplication.config.getAdapters():\n for out in _adapter.outputs:\n on= variableName_Provider.get( out.scratchNames[0] )\n send_events.append( on )\n context[ \"send_events\"] = send_events \n \n #\n # multiple names per input are possible. therefor make a list of lists\n # \n receive_events = []\n for _adapter in parentApplication.config.getAdapters():\n for out in _adapter.inputs:\n names = []\n for n in out.scratchNames:\n names.append( variableName_Provider.get(n) )\n receive_events.append(names)\n context[ \"receive_events\"] = receive_events \n \n #\n # multiple names per input are possible. therefor make a list of lists\n # \n receive_values = []\n for _adapter in parentApplication.config.getAdapters():\n for out in _adapter.input_values:\n names = []\n for n in out.scratchNames:\n names.append( variableName_Provider.get(n) )\n receive_values.append(names)\n context[ \"receive_values\"] = receive_values\n # unregister extension on connection loss \n context [\"reconnect\"] = False\n \n if debug: print(context)\n self.render_response( self.extensionFile, context)\n \nserverStarted = False\n \nclass ServerThread(threading.Thread):\n server = None\n remote = None\n config = None\n \n _stopEvent = None\n _running = None\n \n # to detect problems with multiple instances running\n usageCounter = 0\n \n def __init__(self, parent = None, config = None):\n if debug: print(\"ServerThread, init\", serverStarted)\n threading.Thread.__init__(self, name=\"ServerThread_{usage:d}\".format(usage = ServerThread.usageCounter) )\n \n ServerThread.usageCounter += 1\n \n self._stopEvent = threading.Event()\n self._running = threading.Event()\n \n _runThreads = True\n self.config = config\n global parentApplication\n parentApplication = parent\n \n # print(\"next: ServerThread, init finished\")\n \n #\n # make dispatcher and config available on class level. This allows 'plugin' mechanism\n #\n self.listOfAdditionalPaths = []\n self.listOfAdditionalHandlers = []\n self.thread = None\n \n def websocketPlugin(self, name, route, pluginWebSocketClass):\n \"\"\"enable insertion of webSocket-connection\"\"\"\n logger.debug(\"configure websocket plugin for \" + name + \": \" + str(pluginWebSocketClass) )\n self.listOfAdditionalHandlers.append( { 'name': name, 'route' : route, 'pluginWebSocketClass' : pluginWebSocketClass } )\n \n def htmlPlugin (self, name, htmlpath, comment=''):\n \"\"\"enable insertion of html-connection\"\"\" \n \n self.listOfAdditionalPaths.append( { 'name': name, 'htmlpath' : htmlpath, 'comment' : comment } )\n \n def start(self):\n \"\"\"Start adapter Thread\"\"\"\n if debug: print(\"ServerThread, start\", serverStarted)\n if serverStarted:\n print(\"ALERT \" * 10)\n print(\"Server already started\")\n return\n \n global _runThreads\n _runThreads = True\n\n self._stopEvent.clear()\n self._running.clear()\n \n self.thread = threading.Thread( name=\"ServerThread\", target= self.run)\n self.thread.start()\n \n if debug: print(\"ServerThread, start completed\")\n\n def stop(self):\n logger.debug(\"ServerThread, stop server\")\n global _runThreads\n _runThreads = False\n self._stopEvent.set()\n \n \n if useLocalIOloop:\n global localIOloop\n iol = localIOloop\n else:\n iol = self.ioloop\n \n if iol != None:\n iol.stop()\n # directly access the ioloop from tornado.platform.asyncio.AsyncIOMainLoop\n # and threadsave issue stop\n # with this code, the thread is terminated. This works in tornado 5.1\n try:\n iol.asyncio_loop.call_soon_threadsafe( iol.asyncio_loop.stop )\n except Exception:\n pass\n \n logger.debug(\"ServerThread, stop IOLoop stop\")\n if self.server != None:\n self.server.stop()\n logger.debug(\"ServerThread, stop server join\")\n \n if self.thread != None:\n self.thread.join( timeout=2.0) \n if self.thread.isAlive():\n logger.warning(\"ServerThread, thread did not terminate\")\n \n logger.debug(\"ServerThread, stop server completed\")\n \n def stopped(self):\n return self._stopEvent.isSet()\n\n def make_app(self):\n \n settings = {\n 'debug': False, \n 'autoreload' : False,\n # 'static_path': do not set. favicon.ico will be read from here, when set.\n }\n \n cPath = os.getcwd()\n if debug: print (cPath)\n \n handlers = [\n ## general pages\n ( r\"/\" , ScratchClientMain, {\"additionalpaths\" : self.listOfAdditionalPaths } ),\n \n ## monitoring, simulation\n ( r\"/config\" , ConfigHandler ),\n ( r\"/adapters\" , AdaptersHandler ),\n ( r\"/release\" , ReleaseHandler ),\n \n ( r\"/usage14\" , Usage14Handler ),\n \n ( r\"/ws\" , AdapterAnimationWebSocket ),\n ( r\"/command/input\" , CommandHandler_InputSide ),\n ( r\"/command/output\" , CommandHandler_OutputSide ),\n ( r\"/value/input\" , ValueHandler_InputSide ),\n ( r\"/value/output\" , ValueHandler_OutputSide ),\n \n ## scratchX connection\n ## some convenience url provided\n ##\n (r\"/scratchx/js/extension.js\" , ScratchXConfigHandler, {\"extensionFile\": \"scratchx/js/extension3.js\" } ),\n (r\"/scratch2/js/extension.js\" , ScratchXConfigHandler, {\"extensionFile\": \"scratchx/js/extension3.js\" } ),\n \n (r\"/scratchx/js/extension2.js\" , ScratchXConfigHandler, {\"extensionFile\": \"scratchx/js/extension2.js\" } ),\n (r\"/scratch2/js/extension2.js\" , ScratchXConfigHandler, {\"extensionFile\": \"scratchx/js/extension2.js\" } ),\n \n (r\"/scratchx/js/extension3.js\" , ScratchXConfigHandler, {\"extensionFile\": \"scratchx/js/extension3.js\" } ),\n (r\"/scratch2/js/extension3.js\" , ScratchXConfigHandler, {\"extensionFile\": \"scratchx/js/extension3.js\" } ),\n \n (r\"/scratchx/ws\" , ScratchXWebSocketHandler ),\n \n (r\"/(scratchx/documentation/scratchClient\\.html)\"\n , TemplateHandler , {\"path\": \"template\"} ),\n (r\"/(scratch2/documentation/scratchClient\\.html)\"\n , TemplateHandler , {\"path\": \"template\"} ),\n ## general purpose file connections \n (r\"/(favicon.*)\" , tornado.web.StaticFileHandler, \n {\"path\": \"htdocs/icon\"} ),\n (r\"/(.*)\" , tornado.web.StaticFileHandler, \n {\"path\": \"htdocs\"} ),\n ]\n\n for additionalHandler in self.listOfAdditionalHandlers:\n handlers.append( ( \n additionalHandler['route'], \n additionalHandler['pluginWebSocketClass']\n ))\n\n return tornado.web.Application(handlers, **settings)\n \n\n def run(self):\n logger.debug(\"ServerThread thread started\")\n #\n # see https://github.com/tornadoweb/tornado/issues/2308\n #\n try:\n # asyncio.set_event_loop_policy(tornado.platform.asyncio.AnyThreadEventLoopPolicy())\n asyncio.set_event_loop(asyncio.new_event_loop())\n except Exception as e:\n logger.warning(\"AnyThreadEventLoopPolicy exception \" + str(e) )\n pass\n \n self.app = self.make_app()\n #\n # in case the 8080-port is already open and timeout running,\n # then reopen again and again till port is available\n if True:\n while not ( self.stopped()):\n try:\n self.server = self.app.listen( 8080)\n break\n except Exception as e:\n time.sleep(0.3)\n if debug:\n traceback.print_exc()\n \n if self.stopped():\n if debug: print(\"already stopped ??\")\n return\n else:\n self.server = self.app.listen( 8080)\n \n # tornado.log.enable_pretty_logging( )\n global localIOloop\n localIOloop = self.ioloop = tornado.ioloop.IOLoop.current()\n logger.debug(\"ServerThread tornado localIOloop start...\")\n self.ioloop.start()\n logger.debug(\"ServerThread tornado localIOloop is terminated\")\n \n def registerCommandResolver(self, _commandResolver):\n global commandResolver\n commandResolver = _commandResolver\n\n\nclass ScratchXHandler( scratchClient.ClientHandler ):\n \n def __init__(self, manager): \n self.name=\"scratchXHandler\"\n self.manager = manager \n\n global scratchXHandler\n scratchXHandler = self\n \n def getName(self):\n return self.name\n \n def start(self):\n pass \n \n def stop(self):\n pass \n \n def event_disconnect(self):\n self.manager.setActive(self.getName(), False)\n \n def event_connect(self):\n self.manager.setActive(self.getName(), True)\n","sub_path":"src/server/scratchClientServer.py","file_name":"scratchClientServer.py","file_ext":"py","file_size_in_byte":70497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"206930773","text":"# vim: tabstop=4 shiftwidth=4 softtabstop=4\n\n# Copyright (C) 2012 Yahoo! Inc. 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 devstack import component as comp\nfrom devstack import log as logging\nfrom devstack import settings\nfrom devstack import utils\nfrom devstack import exceptions\nfrom devstack import shell as sh\nfrom devstack.components import db\n\nLOG = logging.getLogger('devstack.components.nova')\n\n#config files adjusted\nAPI_CONF = 'nova.conf'\nPASTE_CONF = 'nova-api-paste.ini'\nCONFIGS = [API_CONF, PASTE_CONF]\n\n#this db will be dropped then created\nDB_NAME = 'nova'\n\n#id\nTYPE = settings.NOVA\n\n#what to start\nAPP_OPTIONS = {\n settings.NAPI: ['--flagfile', '%CFGFILE%'],\n settings.NCPU: ['--flagfile', '%CFGFILE%'],\n settings.NVOL: ['--flagfile', '%CFGFILE%'],\n 'nova-network': ['--flagfile', '%CFGFILE%'],\n 'nova-scheduler': ['--flagfile', '%CFGFILE%']\n}\n\n#post install cmds that will happen after install\nPOST_INSTALL_CMDS = [\n {'cmd': ['%BINDIR%/nova-manage', '--flagfile', '%CFGFILE%',\n 'db', 'sync']},\n {'cmd': ['%BINDIR%/nova-manage', '--flagfile', '%CFGFILE%',\n 'floating', 'create', '%FLOATING_RANGE%']},\n {'cmd': ['%BINDIR%/nova-manage', '--flagfile', '%CFGFILE%',\n 'floating', 'create', '--ip_range=%TEST_FLOATING_RANGE%',\n '--pool=%TEST_FLOATING_POOL%']}\n]\n\nVG_CHECK_CMD = [\n {'cmd': ['vgs', '%VOLUME_GROUP%'],\n 'run_as_root': True}\n]\n\nVG_DEV_CMD = [\n {'cmd': ['losetup', '-f', '--show', '%VOLUME_BACKING_FILE%'],\n 'run_as_root': True}\n]\n\nVG_CREATE_CMD = [\n {'cmd': ['vgcreate', '%VOLUME_GROUP%', '%DEV%'],\n 'run_as_root': True}\n]\n\nRESTART_TGT_CMD = [\n {'cmd': ['stop', 'tgt'], 'run_as_root': True},\n {'cmd': ['start', 'tgt'], 'run_as_root': True}\n]\n\n# In case we need to map names to the image to run\n# This map also controls which subcomponent's packages may need to add\nAPP_NAME_MAP = {\n settings.NAPI: 'nova-api',\n settings.NCPU: 'nova-compute',\n settings.NVOL: 'nova-volume',\n}\n\n#subdirs of the checkout/download\nBIN_DIR = 'bin'\n\n#These are used by NovaConf\nQUANTUM_MANAGER = 'nova.network.quantum.manager.QuantumManager'\nNET_MANAGER_TEMPLATE = 'nova.network.manager.%s'\nDEF_IMAGE_SERVICE = 'nova.image.glance.GlanceImageService'\nDEF_SCHEDULER = 'nova.scheduler.simple.SimpleScheduler'\nDEF_GLANCE_PORT = 9292\n\nQUANTUM_OPENSWITCH_OPS = [\n {\n 'libvirt_vif_type': ['ethernet'],\n 'libvirt_vif_driver': ['nova.virt.libvirt.vif.LibvirtOpenVswitchDriver'],\n 'linuxnet_interface_driver': ['nova.network.linux_net.LinuxOVSInterfaceDriver'],\n 'quantum_use_dhcp': [],\n }\n]\n\n\nclass NovaUninstaller(comp.PythonUninstallComponent):\n def __init__(self, *args, **kargs):\n comp.PythonUninstallComponent.__init__(self, TYPE, *args, **kargs)\n\n\nclass NovaInstaller(comp.PythonInstallComponent):\n def __init__(self, *args, **kargs):\n comp.PythonInstallComponent.__init__(self, TYPE, *args, **kargs)\n self.git_repo = self.cfg.get(\"git\", \"nova_repo\")\n self.git_branch = self.cfg.get(\"git\", \"nova_branch\")\n self.bindir = sh.joinpths(self.appdir, BIN_DIR)\n self.paste_conf_fn = self._get_target_config_name(PASTE_CONF)\n\n def _get_pkglist(self):\n pkgs = comp.PkgInstallComponent._get_pkglist(self)\n # Walk through the subcomponents (like 'vol' and 'cpu') and add those\n # those packages as well. Let utils.get_pkglist handle any missing\n # entries\n LOG.debug(\"get_pkglist looking for extras: %s\" % (self.component_opts))\n if self.component_opts:\n sub_components = self.component_opts\n else:\n # No subcomponents where explicitly specified, so get all\n sub_components = APP_NAME_MAP.keys()\n # Add the extra dependencies\n for cname in sub_components:\n pkgs.update(utils.get_pkg_list(self.distro, cname))\n return pkgs\n\n def _get_download_locations(self):\n places = comp.PythonInstallComponent._get_download_locations(self)\n places.append({\n 'uri': self.git_repo,\n 'branch': self.git_branch,\n })\n return places\n\n def _get_config_files(self):\n return list(CONFIGS)\n\n def post_install(self):\n parent_result = comp.PkgInstallComponent.post_install(self)\n LOG.debug(\"Parent post_install results:%s\" % (parent_result))\n #extra actions to do nova setup\n self._setup_db()\n # Need to do db sync and other post install commands\n # set up replacement map for CFGFILE, BINDIR, FLOATING_RANGE,\n # TEST_FLOATING_RANGE, TEST_FLOATING_POOL\n mp = dict()\n mp['BINDIR'] = self.bindir\n mp['CFGFILE'] = sh.joinpths(self.cfgdir, API_CONF)\n mp['FLOATING_RANGE'] = self.cfg.get('nova', 'floating_range')\n mp['TEST_FLOATING_RANGE'] = self.cfg.get('nova', 'test_floating_range')\n mp['TEST_FLOATING_POOL'] = self.cfg.get('nova', 'test_floating_pool')\n utils.execute_template(*POST_INSTALL_CMDS, params=mp, tracewriter=self.tracewriter)\n # check if we need to do the vol subcomponent\n if not self.component_opts or settings.NVOL in self.component_opts:\n # yes, either no subcomponents were specifically requested or it's\n # in the set that was requested\n self._setup_vol_groups()\n return parent_result\n\n def _setup_db(self):\n LOG.debug(\"setting up nova DB\")\n db.drop_db(self.cfg, DB_NAME)\n db.create_db(self.cfg, DB_NAME)\n\n def _setup_vol_groups(self):\n LOG.debug(\"Attempt to setup vol groups\")\n mp = dict()\n backing_file = self.cfg.get('nova', 'volume_backing_file')\n # check if we need to have a default backing file\n if not backing_file:\n backing_file = sh.joinpths(self.appdir, 'nova-volumes-backing-file')\n backing_file_size = self.cfg.get('nova', 'volume_backing_file_size')\n if backing_file_size[-1].upper() == 'M':\n backing_file_size = int(backing_file_size[:-1]) * 1024 ** 2\n elif backing_file_size[-1].upper() == 'K':\n backing_file_size = int(backing_file_size[:-1]) * 1024\n elif backing_file_size[-1].upper() == 'B':\n backing_file_size = int(backing_file_size[:-1])\n LOG.debug(\"backing_file_size:%s\" % (backing_file_size))\n\n mp['VOLUME_GROUP'] = self.cfg.get('nova', 'volume_group')\n mp['VOLUME_BACKING_FILE'] = backing_file\n mp['VOLUME_BACKING_FILE_SIZE'] = backing_file_size\n LOG.debug(\"params for setup vol group: %s\" % (mp))\n try:\n utils.execute_template(*VG_CHECK_CMD, params=mp)\n LOG.debug(\"Vol group exists\")\n except exceptions.ProcessExecutionError as err:\n LOG.debug(\"Caught expected exception:%s\" % (err))\n LOG.info(\"Need to create vol groups\")\n sh.touch_file(backing_file, die_if_there=False, file_size=backing_file_size)\n vg_dev_result = utils.execute_template(*VG_DEV_CMD, params=mp)\n LOG.debug(\"vg dev result:%s\" % (vg_dev_result))\n # String the newlines out of the stdout (which is in the first\n # element of the first (and only) tuple in the response\n mp['DEV'] = vg_dev_result[0][0].replace('\\n', '')\n utils.execute_template(*VG_CREATE_CMD, params=mp, tracewriter=self.tracewriter)\n # TODO Now need to check the headings, etc...\n # Finish off by restarting tgt\n utils.execute_template(*RESTART_TGT_CMD, check_exit_code=False, tracewriter=self.tracewriter)\n\n def _generate_nova_conf(self):\n LOG.debug(\"Generating dynamic content for nova configuration\")\n dirs = dict()\n dirs['app'] = self.appdir\n dirs['cfg'] = self.cfgdir\n dirs['bin'] = self.bindir\n conf_gen = NovaConfigurator(self)\n nova_conf = conf_gen.configure(dirs)\n tgtfn = self._get_target_config_name(API_CONF)\n LOG.info(\"Writing conf to %s\" % (tgtfn))\n LOG.info(nova_conf)\n sh.write_file(tgtfn, nova_conf)\n self.tracewriter.cfg_write(tgtfn)\n\n def _generate_paste_api_conf(self):\n LOG.info(\"Setting up %s\" % (PASTE_CONF))\n mp = dict()\n mp['SERVICE_TOKEN'] = self.cfg.get(\"passwords\", \"service_token\")\n (src_fn, contents) = self._get_source_config(PASTE_CONF)\n LOG.info(\"Replacing parameters in file %s\" % (src_fn))\n LOG.debug(\"Replacements = %s\" % (mp))\n contents = utils.param_replace(contents, mp, True)\n LOG.debug(\"Writing out to %s\" % (self.paste_conf_fn))\n sh.write_file(self.paste_conf_fn, contents)\n self.tracewriter.cfg_write(self.paste_conf_fn)\n\n def _configure_files(self):\n self._generate_nova_conf()\n self._generate_paste_api_conf()\n return len(CONFIGS)\n\n\nclass NovaRuntime(comp.PythonRuntime):\n def __init__(self, *args, **kargs):\n comp.PythonRuntime.__init__(self, TYPE, *args, **kargs)\n self.run_tokens = dict()\n self.run_tokens['CFGFILE'] = sh.joinpths(self.cfgdir, API_CONF)\n LOG.debug(\"Setting CFGFILE run_token to:%s\" % (self.run_tokens['CFGFILE']))\n\n def _get_apps_to_start(self):\n # Check if component_opts was set to a subset of apps to be started\n LOG.debug(\"getting list of apps to start\")\n apps = list()\n if not self.component_opts and len(self.component_opts) > 0:\n LOG.debug(\"Attempt to use subset of components:%s\" % (self.component_opts))\n # check if the specified sub components exist\n delta = set(self.component_opts) - set(APP_OPTIONS.keys())\n if delta:\n # FIXME, error, something was specified that we don't have\n LOG.error(\"sub items that we don't know about:%s\" % delta)\n else:\n apps = self.component_opts\n LOG.debug(\"Using specified subcomponents:%s\" % (apps))\n else:\n apps = APP_OPTIONS.keys()\n LOG.debug(\"Using the keys from APP_OPTIONS:%s\" % (apps))\n\n result = list()\n for app_name in apps:\n if app_name in APP_NAME_MAP:\n image_name = APP_NAME_MAP.get(app_name)\n LOG.debug(\"Renamed app_name to:\" + app_name)\n else:\n image_name = app_name\n result.append({\n 'name': app_name,\n 'path': sh.joinpths(self.appdir, BIN_DIR, image_name),\n })\n LOG.debug(\"exiting _get_aps_to_start with:%s\" % (result))\n return result\n\n def _get_app_options(self, app):\n LOG.debug(\"Getting options for %s\" % (app))\n result = list()\n for opt_str in APP_OPTIONS.get(app):\n LOG.debug(\"Checking opt_str for tokens: %s\" % (opt_str))\n result.append(utils.param_replace(opt_str, self.run_tokens))\n\n LOG.debug(\"_get_app_options returning with:%s\" % (result))\n return result\n\n\n# This class has the smarts to build the configuration file based on\n# various runtime values\nclass NovaConfigurator(object):\n def __init__(self, nc):\n self.cfg = nc.cfg\n self.instances = nc.instances\n self.appdir = nc.appdir\n self.tracewriter = nc.tracewriter\n self.paste_conf_fn = nc.paste_conf_fn\n self.nvol = not nc.component_opts or settings.NVOL in nc.component_opts\n\n def _getbool(self, name):\n return self.cfg.getboolean('nova', name)\n\n def _getstr(self, name):\n return self.cfg.get('nova', name)\n\n def configure(self, dirs):\n\n #TODO split up into sections??\n\n nova_conf = NovaConf()\n hostip = self.cfg.get('host', 'ip')\n\n #verbose on?\n if self._getbool('verbose'):\n nova_conf.add_simple('verbose')\n\n #allow the admin api?\n if self._getbool('allow_admin_api'):\n nova_conf.add_simple('allow_admin_api')\n\n #which scheduler do u want?\n scheduler = self._getstr('scheduler')\n if not scheduler:\n scheduler = DEF_SCHEDULER\n nova_conf.add('scheduler_driver', scheduler)\n\n flag_conf_fn = sh.joinpths(dirs.get('bin'), API_CONF)\n nova_conf.add('dhcpbridge_flagfile', flag_conf_fn)\n\n #whats the network fixed range?\n nova_conf.add('fixed_range', self._getstr('fixed_range'))\n\n if settings.QUANTUM in self.instances:\n #setup quantum config\n nova_conf.add('network_manager', QUANTUM_MANAGER)\n nova_conf.add('quantum_connection_host', self.cfg.get('quantum', 'q_host'))\n nova_conf.add('quantum_connection_port', self.cfg.get('quantum', 'q_port'))\n # TODO add q-svc support\n #if 'q-svc' in self.othercomponents and\n # self.cfg.get('quantum', 'q_plugin') == 'openvswitch':\n # self.lines.extend(QUANTUM_OPENSWITCH_OPS)\n else:\n nova_conf.add('network_manager', NET_MANAGER_TEMPLATE % (self._getstr('network_manager')))\n\n if self.nvol:\n nova_conf.add('volume_group', self._getstr('volume_group'))\n volume_name_template = self._getstr('volume_name_prefix') + self._getstr('volume_name_postfix')\n nova_conf.add('volume_name_template', volume_name_template)\n nova_conf.add('iscsi_help', 'tgtadm')\n nova_conf.add('my_ip', hostip)\n\n # The value for vlan_interface may default to the the current value\n # of public_interface. We'll grab the value and keep it handy.\n public_interface = self._getstr('public_interface')\n vlan_interface = self._getstr('vlan_interface')\n if not vlan_interface:\n vlan_interface = public_interface\n nova_conf.add('public_interface', public_interface)\n nova_conf.add('vlan_interface', vlan_interface)\n\n #setup your sql connection and what type of virt u will be doing\n nova_conf.add('sql_connection', self.cfg.get_dbdsn('nova'))\n\n #configure anything libvirt releated?\n self._configure_libvirt(self._getstr('libvirt_type'), nova_conf)\n\n #how instances will be presented\n instance_template = self._getstr('instance_name_prefix') + self._getstr('instance_name_postfix')\n nova_conf.add('instance_name_template', instance_template)\n\n if settings.OPENSTACK_X in self.instances:\n nova_conf.add('osapi_compute_extension', 'nova.api.openstack.compute.contrib.standard_extensions')\n nova_conf.add('osapi_compute_extension', 'extensions.admin.Admin')\n\n if settings.NOVNC in self.instances:\n vncproxy_url = self._getstr('vncproxy_url')\n if not vncproxy_url:\n vncproxy_url = 'http://' + hostip + ':6080/vnc_auto.html'\n nova_conf.add('vncproxy_url', vncproxy_url)\n\n nova_conf.add('api_paste_config', self.paste_conf_fn)\n\n img_service = self._getstr('img_service')\n if not img_service:\n img_service = DEF_IMAGE_SERVICE\n nova_conf.add('image_service', img_service)\n\n ec2_dmz_host = self._getstr('ec2_dmz_host')\n if not ec2_dmz_host:\n ec2_dmz_host = hostip\n nova_conf.add('ec2_dmz_host', ec2_dmz_host)\n\n #how is your rabbit setup?\n nova_conf.add('rabbit_host', self.cfg.get('default', 'rabbit_host'))\n nova_conf.add('rabbit_password', self.cfg.get(\"passwords\", \"rabbit\"))\n\n #where is glance located?\n glance_api_server = self._getstr('glance_server')\n if not glance_api_server:\n glance_api_server = \"%s:%d\" % (hostip, DEF_GLANCE_PORT)\n nova_conf.add('glance_api_servers', glance_api_server)\n nova_conf.add_simple('force_dhcp_release')\n\n #where instances will be stored\n instances_path = self._getstr('instances_path')\n if not instances_path:\n # If there's no instances path, specify a default\n instances_path = sh.joinpths(self.appdir, '..', 'instances')\n nova_conf.add('instances_path', instances_path)\n LOG.debug(\"Attempting to create instance directory:%s\" % (instances_path))\n # Create the directory for instances\n self.tracewriter.make_dir(instances_path)\n\n #is this a multihost setup?\n if self._getbool('multi_host'):\n nova_conf.add_simple('multi_host')\n nova_conf.add_simple('send_arp_for_ha')\n\n #enable syslog??\n if self.cfg.getboolean('default', 'syslog'):\n nova_conf.add_simple('use_syslog')\n\n #handle any virt driver specifics\n virt_driver = self._getstr('virt_driver')\n self._configure_virt_driver(virt_driver, nova_conf)\n\n #now make it\n conf_lines = sorted(nova_conf.generate())\n complete_file = utils.joinlinesep(*conf_lines)\n\n #add any extra flags in?\n extra_flags = self._getstr('extra_flags')\n if extra_flags and len(extra_flags):\n full_file = [complete_file, extra_flags]\n complete_file = utils.joinlinesep(*full_file)\n\n return complete_file\n\n def _configure_libvirt(self, virt_type, nova_conf):\n if not virt_type:\n return\n nova_conf.add('libvirt_type', virt_type)\n\n #configures any virt driver settings\n def _configure_virt_driver(self, driver, nova_conf):\n if not driver:\n return\n drive_canon = driver.lower().strip()\n if drive_canon == 'xenserver':\n nova_conf.add('connection_type', 'xenapi')\n nova_conf.add('xenapi_connection_url', 'http://169.254.0.1')\n nova_conf.add('xenapi_connection_username', 'root')\n nova_conf.add('xenapi_connection_password', self.cfg.get(\"passwords\", \"xenapi_connection\"))\n nova_conf.add_simple('noflat_injected')\n nova_conf.add('flat_interface', 'eth1')\n nova_conf.add('flat_network_bridge', 'xapi1')\n else:\n nova_conf.add('connection_type', self._getstr('connection_type'))\n nova_conf.add('flat_network_bridge', self._getstr('flat_network_bridge'))\n nova_conf.add('flat_interface', self._getstr('flat_interface'))\n\n\n# This class represents the data in the nova config file\nclass NovaConf(object):\n def __init__(self):\n self.lines = list()\n\n def add_list(self, key, *params):\n self.lines.append({'key': key, 'options': params})\n LOG.debug(\"Added nova conf key %s with values [%s]\" % (key, \",\".join(params)))\n\n def add_simple(self, key):\n self.lines.append({'key': key, 'options': None})\n LOG.debug(\"Added nova conf key %s\" % (key))\n\n def add(self, key, value):\n self.lines.append({'key': key, 'options': [value]})\n LOG.debug(\"Added nova conf key %s with value [%s]\" % (key, value))\n\n def _form_key(self, key, has_opts):\n key_str = \"--\" + str(key)\n if has_opts:\n key_str += \"=\"\n return key_str\n\n def generate(self, param_dict=None):\n gen_lines = list()\n for line_entry in self.lines:\n key = line_entry.get('key')\n opts = line_entry.get('options')\n if not key:\n continue\n if opts is None:\n key_str = self._form_key(key, False)\n full_line = key_str\n else:\n key_str = self._form_key(key, True)\n filled_opts = list()\n for opt in opts:\n filled_opts.append(utils.param_replace(str(opt), param_dict))\n full_line = key_str + \",\".join(filled_opts)\n gen_lines.append(full_line)\n return gen_lines\n\n\ndef describe(opts=None):\n description = \"\"\"\n Module: {module_name}\n Description:\n {description}\n Component options:\n {component_opts}\n\"\"\"\n params = dict()\n params['component_opts'] = \"TBD\"\n params['module_name'] = __name__\n params['description'] = __doc__ or \"Handles actions for the nova component.\"\n out = description.format(**params)\n return out.strip(\"\\n\")\n","sub_path":"devstack/components/nova.py","file_name":"nova.py","file_ext":"py","file_size_in_byte":20580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"551136814","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nfrom sklearn import datasets\nimport mglearn\nimport seaborn as sns\n\n#로지스틱 회귀\n#주로 분류를 하기위한 알고리즘\n#주로 예, 아니오 등의 이진분류에 많이 사용\n#의료 통신 데이터 마이닝 분야의 회귀, 분류를 위한 예측 모델로 활용.\n\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\n#\n# X, y = mglearn.datasets.make_forge()\n#\n# # logr = LogisticRegression()\n# # clf = logr.fit(X,y)\n#\n# mglearn.discrete_scatter(X[:,0], X[:,1], y)\n#\n# logr = LogisticRegression(solver='liblinear')\n# clf = logr.fit(X,y)\n#\n# print('R^2 측정값', clf.score(X, y))\n# mglearn.plots.plot_2d_separator(clf, X, fill=False, eps=0.5, alpha=.7)\n# plt.show()\n#\n# #유방암 진단을 로지스틱 회귀로 분석하기\n# from sklearn import datasets\n# cancer = datasets.load_breast_cancer()\n# print('유방암 데이터', cancer.data[:5])\n# print('유방암 구조', cancer.feature_names)\n#\n# X_train, X_test, y_train, y_test = train_test_split(cancer.data, cancer.target, random_state=0)\n# logr = LogisticRegression(solver='liblinear')\n# # solver : sclkit-learn 20 이상부터는 명시적으로 지정필요.\n# # liblinear : 이항회귀, 작은 데이터 셋에 적합한 알고리즘\n# # newton-cg : 다항회귀 L1 제약 사용.\n# # sag, saga : 다항회귀 L2 제약 사용, 확률적 평균 경사하강법 알고리즘 사용.\n# #\n#\n# clf = logr.fit(X_train, y_train)\n#\n# print('훈련 정확도', logr.score(X_train, y_train))\n# print('검증 정확도', logr.score(X_test, y_test))\n#\n# #입학여부를 로지스틱회귀로 분석하기 (admit, gre, gpa, rank)\n#\n#\n# path1 = 'C:/Users/TJ/Google 드라이브/학습자료/프로그래밍/data science/Sample data/r/admits.csv'\n# admits = pd.read_csv(path1, engine='python')\n#\n# print(admits[:5])\n#\n# #탐색적 분석\n# print(admits.head())\n# print(admits.describe())\n# print(admits.std())\n#\n# admits.hist()\n# plt.show()\n#\n# # 순위항목을 더미변수로 생성\n# rank_dummys = pd.get_dummies(admits['rank'], prefix='rank')\n# print('더미변수', rank_dummys.head())\n# # 범주형 변수를 수치형 변수로 바꾸는 원핫인코딩 방식처럼 rank 컬럼의 각 값을 고유컬럼으로 재생성\n#\n# cols_origin = ['admit', 'gre', 'gpa']\n# df = admits[cols_origin].join(rank_dummys.ix[:'rank_2'])\n# print(df.head())\n# #rank2 - rank4 컬럼과 기좀컬럼을 합쳐서 새로운 데이터프레임을 생성함\n#\n# # train, test 데이터셋으로 나눔\n# data = df.iloc[:,1:]\n# target = df['admit']\n#\n# print('입학자료', data[:5])\n# print('결과자료', target[:5])\n#\n# X_train, X_test, y_train, y_test = train_test_split(data, target, random_state=0)\n#\n# #로지스틱 회귀분석 시작\n# logr = LogisticRegression(solver='liblinear')\n# clf = logr.fit(X_train, y_train)\n#\n# print('훈련 정확도', logr.score(X_train, y_train))\n# print('검증 정확도', logr.score(X_test, y_test))\n#\n# print('절편', logr.intercept_)\n# print('기울기', logr.coef_)\n#\n# # 더미변수\n# # 범주형 변수를 연속형 변수로 바꾼 것.\n# # 선형회귀나 로지스틱 회귀 분석은 설명변수가 수치형 변수여야 사용할 수 있는 기법\n# # 설명변수에 범주형 변수가 포함되어 있다면 그 변수를 더미변수로 변환해야 분석이 가능\n# # 즉, 범주형 변수를 연속형변수스럽게 만들어야 한다는 의미\n#\n# # 더미변수는 원래 범주형 변수의 범주개수보다 1개 적게 생성\n# # 예를 들어, 변수가 성별인 경우 남자여부, 여자여부 중 더미 변수는 하나만 생성하면\n# # 된다는 의미.\n# # 변수가 대학교 학년인 경우 1,2,3 학년 혹은 2,3,4 학년 여부 중 하나만 생성하면 됨.\n#\n# # 더비변수를 이용하면 회귀계수식에서\n# # 특정변수의 효과를 0 또는 임의의 상수값으로 만들 수 있음.\n# # 예를 들어, 회귀식이 y = ax1 + bx2 + c가 있고\n# # x2가 성별변수라 할 때\n# # x2 : 0 이면 => y=ax1 + c\n# # x2 : 1 이면 => y = y = ax1 + b + c\n\n# 더미변수를 이용해서 타이타닉 데이터셋에 대해 로지스틱 회귀분석을 실시\n# path = 'C:/Users/TJ/Google 드라이브/학습자료/프로그래밍/data science/Sample data/r/titanic.csv'\n# titanic = pd.read_csv(path, engine='python')\ntitanic = sns.load_dataset('titanic')\n\n\n# # 탐색적분석\n# print(titanic.head(5))\n# print(titanic.tail(5))\n# print('타이타닉 키', titanic.keys())\n# print('타이타닉 info : \\n', titanic.describe())\n#\n# print(titanic['class'])\n\n\n# null 체크\nprint(titanic.isnull().sum())\n\n# 중앙값으로 결측치를 채움.\nmedians = titanic['age'].median()\ntitanic['age'].fillna(medians, inplace=True)\n\nprint(titanic.isnull().sum())\n\n\n#로지스틱 회귀에 사용할 변수 추출\ndatacol = ['pclass', 'sex', 'age', 'fare']\ndata = titanic[datacol]\ntarget = titanic['survived']\n\nprint(data.head())\nprint(target.head())\n\n#범주형변수를 수치형 변수로 변환 => 더미변수 생성\nprint(titanic['sex'].head())\n\ndata['sex'] = pd.Categorical(titanic['sex'])\ndata['sex'] = data['sex'].cat.codes\n\nprint(data['sex'].head())\n\n# 더미변수 만들기\n# 성별 0, 성별 1을 만듦.\ndummy_sex = pd.get_dummies(data['sex'], prefix='sex')\nprint(dummy_sex.head())\n\ndata = data[datacol].join(dummy_sex.ix[:, 'sex_1'])\nprint(data.head())\n\ndummy_pclass = pd.get_dummies(data['pclass'], prefix='pclass')\nprint(dummy_pclass.head())\n\ndata = data.join(dummy_pclass.ix[:, 'pclass_2':])\nprint(data.head())\n\n# 로지스틱 회귀에 사용할 data, target 추출\ndata = data.iloc[:, 2:]\nprint(data.head())\nprint(target.head())\n\n# 로지스틱 회귀분석 실시\nX_train, X_test, y_train, y_test = train_test_split(data, target, random_state=0)\n\nlgr = LogisticRegression(solver='liblinear')\nlgr.fit(X_train, y_train)\n\nprint('훈련 정확도', lgr.score(X_train, y_train))\nprint('검증 정확도', lgr.score(X_test, y_test))\n\nprint(lgr.coef_)\nprint(lgr.intercept_)\n\n#로지스�� 회귀분석을 통한 스팸분류\npath = 'C:/Users/TJ/Google 드라이브/학습자료/프로그래밍/data science/Sample data/r/SMSSpam'\n# sms = pd.read_csv(path, sep='\\t', header=None, error_bad_lines=False, engine='python')\nsms = pd.read_csv(path, sep='\\t', header=None, engine='python')\nprint('sms : ', sms.head())\n\n#정상메일과 스팸메일 수량 확인\nprint('정상수', sms[sms[0]=='ham'][0].count())\nprint('스팸수', sms[sms[0]=='spam'][0].count())\n\nsns.countplot(sms[0])\nplt.show()\n\n# 텍스트 전처리 작업 실시\n# 문자로 구성된 sms데이터를 로지스틱 회귀가 가능하도록\n# 적절한 전처리 작업 실시 => BOW 사용\n\n# BOW : bag of words => 문자/문서를 숫자 벡터로 변환\n# 먼저, 전체 문자/문서에 대한 단어장 생성\n# 그런다음, 문서내 단어의 출현빈도를 측정해서 개별 단어장에 저장\n\n# BOW 문자 전처리 종류\n# 머신러닝으로 분석하는 사례 중 텍스트를 이용하는 경우가 있음.\n# 이런 경우 문자를 벡터값으로 인코딩해서 처리해야 함.\n\n# DictVectorizer : 각 단어를 세어 사전 생성\n# CountVectorizer : 단어 토큰을 만들고 각 단어수를 세어 사전 생성\n# TfinfVectorizer : 각 단어에 가중치를 두어 사전 생성\n# HashingVectorizer : 빠른 처리를 위해 단어 토큰생성시 해시함수 사용\n# countVectorizer 예제\nfrom sklearn.feature_extraction.text import CountVectorizer\nsentence = ['UNC played Duke in baseball', 'Duke lost the basketball game']\n\nvectors = CountVectorizer()\nprint('변환된 벡터값', vectors.fit_transform(sentence).todense())\n\n# 결과값1 : [1 0 1 0 1 0 1 0 1] => 1. 모두 소문자로 > 2. 알파벳순으로 정렬한 후 순번부여\n# 각 문서의 내용을 토큰(문자)리스트로 생성 > 각 문서에서 토큰의 출현순서를 셈 > 각 문서를 BOW벡터값으로 변환\nprint('추출한 어휘\\n', vectors.vocabulary_)\nprint('추출한 추출된 패턴\\n', vectors.fit_transform(sentence)[0])\n\n#새로운 문장을 추가하면?\nsentence.append('Is this last document')\nprint('추출한 어휘\\n', vectors.vocabulary_)\n\n# TfidfVectorizer 예제\n# 특정 단어 빈도수\n# 특정 단어가 문서에 출현하는 빈도\n\n# Tfidf(Term Frequency - Inverse Document Frequency) : 텍스트 마이닝에서 이용하는 가중치 부여 방식으로 여러 문서로 이루어진 문서군에서 어떤 단어가 특정 문서상에서\n# 얼마나 중요한 것인지 의미하는 통계적 수치\n# Tf가 크면(여러 문서에 단어가 출현) => 자주등장해서 중요함\n# Tf의 역수인 idf가 크면 (특정 문서에 단어 출현 빈도 출현) => 특정하기 때문에 중요함.\n\n# 예) 신문과 방송에서 독감언급 Tf가 높음\n# 예) 특정 언론에서 '태블릿' 언급 idf가 높음\n\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nsentence = ['UNC played Duke in baseball', 'Duke lost the basketball game']\nvectors = TfidfVectorizer()\nprint('변환된 벡터값\\n', vectors.fit_transform(sentence).todense())\nprint('추출된 패턴', vectors.vocabulary_)\n\nsentence.append('Is this last document')\nprint('변환된 벡터값\\n', vectors.fit_transform(sentence).todense())\nprint('추출된 패턴', vectors.vocabulary_)\n\n# smsspam 데이터를 tfidfVectorizer로 전처리함\ndata = sms[1].values\ntarget = sms[0].values\n\n# print(data.head())\n# print(target.head())\n\nX_train, X_test, y_train, y_test = train_test_split(data, target, random_state=0)\nvectors = TfidfVectorizer()\nvX_train = vectors.fit_transform(X_train) #[[],[].[]] 형식\nvX_test = vectors.transform(X_test) # [,,,]\n\nlogr = LogisticRegression(solver='liblinear')\nlogr.fit(vX_train, y_train)\n\nprint('훈련 정확도', logr.score(vX_train, y_train))\nprint('검증 정확도', logr.score(vX_test, y_test))\n\n# 실제값을 넣어서 예측하기\npred = logr.predict(vX_test)\nfor i in range(0, 10):\n print(pred[i], vX_test, y_test)\n\n#smsspam 데이터를 TfidfVectorizer로 전처리함\nimport re\n\ndata = sms[1].values\ntarget = sms[0].values\n\ndata = str(data)\ndata = re.sub('[^a-zA-Z \" \"]', '', data)\nprint('데이터', data[:5])\n\n#문자 전처리 관련 패키지\n#pip install nltk\n\nimport nltk\nnltk.download('stopwords') #불용어 사전 다운로드\n\nfrom nltk.corpus import stopwords\nstopWords = stopwords.words('english')\ndata = [str for str in data if not str in stopWords]\nprint(data[:5])\n\n","sub_path":"py1901/ML03.py","file_name":"ML03.py","file_ext":"py","file_size_in_byte":10533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"258870775","text":"import pytest\n\nfrom grandchallenge.algorithms.models import Job\n\nfrom tests.utils import get_view_for_user\nfrom tests.factories import UserFactory\nfrom tests.algorithms_tests.factories import (\n AlgorithmImageFactory,\n JobFactory,\n ResultFactory,\n ImageFactory,\n)\n\n\n@pytest.mark.django_db\ndef test_algorithm_image_list(client):\n user = UserFactory(is_staff=True)\n algoi1, algoi2 = AlgorithmImageFactory(), AlgorithmImageFactory()\n job1, job2 = (\n JobFactory(algorithm_image=algoi1),\n JobFactory(algorithm_image=algoi2),\n )\n result1, result2 = (\n ResultFactory(job=job1, output={\"cancer_score\": 0.01}),\n ResultFactory(job=job2, output={\"cancer_score\": 0.5}),\n )\n response = get_view_for_user(\n viewname=\"api:algorithms-image-list\", user=user, client=client\n )\n assert response.status_code == 200\n assert response.json()[\"count\"] == 2\n\n response = get_view_for_user(\n viewname=\"api:algorithms-image-detail\",\n reverse_kwargs={\"pk\": algoi1.pk},\n user=user,\n client=client,\n )\n assert response.status_code == 200\n\n response = get_view_for_user(\n viewname=\"api:algorithms-job-list\", user=user, client=client\n )\n assert response.status_code == 200\n assert response.json()[\"results\"][0][\"pk\"] == str(job1.pk)\n assert (\n response.json()[\"results\"][0][\"algorithm_image\"]\n == f\"http://testserver/api/v1/algorithms/images/{algoi1.pk}/\"\n )\n assert response.json()[\"results\"][1][\"pk\"] == str(job2.pk)\n assert (\n response.json()[\"results\"][1][\"algorithm_image\"]\n == f\"http://testserver/api/v1/algorithms/images/{algoi2.pk}/\"\n )\n\n response = get_view_for_user(\n viewname=\"api:algorithms-result-list\", user=user, client=client\n )\n assert response.status_code == 200\n assert response.json()[\"results\"][0][\"pk\"] == str(result1.pk)\n assert (\n response.json()[\"results\"][0][\"job\"]\n == f\"http://testserver/api/v1/algorithms/jobs/{job1.pk}/\"\n )\n assert response.json()[\"results\"][0][\"output\"] == {\"cancer_score\": 0.01}\n assert response.json()[\"results\"][1][\"pk\"] == str(result2.pk)\n assert (\n response.json()[\"results\"][1][\"job\"]\n == f\"http://testserver/api/v1/algorithms/jobs/{job2.pk}/\"\n )\n assert response.json()[\"results\"][1][\"output\"] == {\"cancer_score\": 0.5}\n\n\n@pytest.mark.django_db\ndef test_algorithm_api_permissions(client):\n tests = [(UserFactory(), 403), (UserFactory(is_staff=True), 200)]\n algorithm_image = AlgorithmImageFactory()\n\n for test in tests:\n response = get_view_for_user(\n client=client,\n viewname=\"api:algorithms-image-list\",\n user=test[0],\n content_type=\"application/json\",\n )\n assert response.status_code == test[1]\n\n response = get_view_for_user(\n client=client,\n viewname=\"api:algorithms-image-detail\",\n reverse_kwargs={\"pk\": algorithm_image.pk},\n user=test[0],\n content_type=\"application/json\",\n )\n assert response.status_code == test[1]\n\n\n@pytest.mark.django_db\ndef test_job_api_permissions(client):\n tests = [(UserFactory(), 403), (UserFactory(is_staff=True), 200)]\n job = JobFactory()\n\n for test in tests:\n response = get_view_for_user(\n client=client,\n viewname=\"api:algorithms-job-list\",\n user=test[0],\n content_type=\"application/json\",\n )\n assert response.status_code == test[1]\n\n response = get_view_for_user(\n client=client,\n viewname=\"api:algorithms-job-detail\",\n reverse_kwargs={\"pk\": job.pk},\n user=test[0],\n content_type=\"application/json\",\n )\n assert response.status_code == test[1]\n\n\n@pytest.mark.django_db\ndef test_result_api_permissions(client):\n tests = [(UserFactory(), 403), (UserFactory(is_staff=True), 200)]\n result = ResultFactory()\n\n for test in tests:\n response = get_view_for_user(\n client=client,\n viewname=\"api:algorithms-result-list\",\n user=test[0],\n content_type=\"application/json\",\n )\n assert response.status_code == test[1]\n\n response = get_view_for_user(\n client=client,\n viewname=\"api:algorithms-result-detail\",\n reverse_kwargs={\"pk\": result.pk},\n user=test[0],\n content_type=\"application/json\",\n )\n assert response.status_code == test[1]\n\n\n@pytest.mark.django_db\ndef test_job_create(client):\n im = ImageFactory()\n\n algo_i = AlgorithmImageFactory()\n\n user = UserFactory(is_staff=True)\n\n response = get_view_for_user(\n viewname=\"api:algorithms-job-list\",\n user=user,\n client=client,\n method=client.post,\n data={\"image\": im.api_url, \"algorithm_image\": algo_i.api_url},\n content_type=\"application/json\",\n )\n assert response.status_code == 201\n\n job = Job.objects.get(pk=response.data.get(\"pk\"))\n\n assert job.image == im\n assert job.algorithm_image == algo_i\n\n\n@pytest.mark.django_db\n@pytest.mark.parametrize(\n \"is_staff, expected_response\", [(False, 403), (True, 201)]\n)\ndef test_job_post_permissions(client, is_staff, expected_response):\n # Staff users should be able to post a job\n user = UserFactory(is_staff=is_staff)\n im = ImageFactory()\n algo_image = AlgorithmImageFactory()\n\n response = get_view_for_user(\n viewname=\"api:algorithms-job-list\",\n user=user,\n client=client,\n method=client.post,\n data={\"image\": im.api_url, \"algorithm_image\": algo_image.api_url},\n content_type=\"application/json\",\n )\n assert response.status_code == expected_response\n","sub_path":"app/tests/algorithms_tests/test_api.py","file_name":"test_api.py","file_ext":"py","file_size_in_byte":5820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"592709231","text":"import argparse\nimport pandas as pd\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--data', dest=\"data\")\nargs = parser.parse_args()\ndata = pd.read_csv('challenge/challenge/predictions.csv', index_col=0)\ndata.to_csv('predictions.csv')\n\n\n","sub_path":"challenge/challenge/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"198438418","text":"import sqlalchemy as db\nfrom sqlalchemy.orm.session import sessionmaker\n\n\nclass BaseDao(): #-- Definindo as config da conexão com o banco de dados.\n\n def __init__(self):\n connection = db.create_engine(\"mysql+mysqlconnector://root:@localhost/users\")\n Session = db.orm.sessionmaker()\n Session.configure(bind=connection)\n self.session = Session()\n","sub_path":"sql_alchemy_python/CONN_02/dao/base_dao.py","file_name":"base_dao.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"570192565","text":"# -*- coding:utf-8 -*-\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nimport matplotlib\nimport math\nimport numpy as np\n\nclass texture:\n\n def __init__(self, dis, deg):\n self.dis = dis\n self.deg = deg\n\n def getIntensityArray(self, patch):\n patch_size = patch.size\n width = patch_size[0]\n height = patch_size[1]\n intensity_array = np.zeros([height, width], dtype=np.uint8)\n\n for y in range(height):\n for x in range(width):\n intensity_array[y][x] = gray_img.getpixel((x, y))\n\n return intensity_array\n\n def getIntensityRange(self, intensity_array):\n int_max = np.max(intensity_array)\n int_min = np.min(intensity_array)\n int_range = [i for i in range(int_min, int_max+1)]\n return int_range\n\n def makeGrayLevCooccuMat(self, patch):\n # サンプル\n #intensity_array = np.array([[0, 1, 1, 1, 0],\n # [1, 2, 2, 2, 1],\n # [2, 3, 3, 2, 2],\n # [2, 3, 4, 3, 2],\n # [3, 4, 5, 4, 3]])\n # 輝度情報配列生成\n intensity_array = self.getIntensityArray(patch)\n print(intensity_array)\n height, width = intensity_array.shape[:2]\n # 輝度の範囲取得\n int_range = self.getIntensityRange(intensity_array)\n # nxn行列の初期化\n n = len(int_range)\n matrix = np.zeros([n, n], dtype=np.int32)\n\n for y in range(height):\n for x in range(width):\n # 水平方向(左右)\n if self.deg == 0:\n if x+self.dis < width:\n # 輝度値と等しいインデックス取得\n y_id = int_range.index(intensity_array[y][x])\n x_id = int_range.index(intensity_array[y][x+self.dis])\n # カウント\n matrix[y_id][x_id] += 1\n if x-self.dis >= 0:\n y_id = int_range.index(intensity_array[y][x])\n x_id = int_range.index(intensity_array[y][x-self.dis])\n matrix[y_id][x_id] += 1\n\n # 垂直方向(上下)\n if self.deg == 90:\n if y+self.dis < height:\n y_id = int_range.index(intensity_array[y][x])\n x_id = int_range.index(intensity_array[y+self.dis][x])\n matrix[y_id][x_id] += 1\n if y-self.dis >= 0:\n y_id = int_range.index(intensity_array[y][x])\n x_id = int_range.index(intensity_array[y-self.dis][x])\n matrix[y_id][x_id] += 1\n\n # 左斜め方向(左上〜右下)\n if self.deg == 135:\n if x+self.dis < width and y+self.dis < height:\n y_id = int_range.index(intensity_array[y][x])\n x_id = int_range.index(intensity_array[y+self.dis][x+self.dis])\n matrix[y_id][x_id] += 1\n if x-self.dis >= 0 and y-self.dis >= 0:\n y_id = int_range.index(intensity_array[y][x])\n x_id = int_range.index(intensity_array[y-self.dis][x-self.dis])\n matrix[y_id][x_id] += 1\n\n # 右斜め方向(右上〜左下)\n if self.deg == 45:\n if x+self.dis < width and y-self.dis >= 0:\n y_id = int_range.index(intensity_array[y][x])\n x_id = int_range.index(intensity_array[y-self.dis][x+self.dis])\n matrix[y_id][x_id] += 1\n if x-self.dis >= 0 and y+self.dis < height:\n y_id = int_range.index(intensity_array[y][x])\n x_id = int_range.index(intensity_array[y+self.dis][x-self.dis])\n matrix[y_id][x_id] += 1\n\n return int_range, matrix\n\nif __name__ == '__main__':\n\n dis = 1\n deg = 45\n\n tex = texture(dis, deg)\n\n image = Image.open(\"Penguins.jpg\").resize((256, 192))\n gray_img = image.convert(\"L\")\n\n box = (48, 48, 48+8, 48+8)\n patch = gray_img.crop(box)\n patch_size = patch.size\n width = patch_size[0]\n height = patch_size[1]\n\n int_range, matrix = tex.makeGrayLevCooccuMat(patch)\n print(\"Intensity Range:\")\n print(int_range)\n print(\"Cooccurrence Matrix:\")\n print(matrix)\n\n texture = {\"homogeneity\": 0.0, \"dissimilarity\": 0.0, \"contrast\": 0.0,\n \"mean_i\":0.0, \"mean_j\":0.0, \"std_i\":0.0, \"std_j\":0.0,\n \"ASM\":0.0, \"entropy\":0.0, \"energy\":0.0, \"correlation\":0.0}\n\n variance_i = 0.0\n variance_j = 0.0\n\n for i in range(matrix.shape[1]):\n for j in range(matrix.shape[0]):\n sqrt_diff_int = pow((int_range[i]-int_range[j]), 2)\n mean_i = int_range[i]*matrix[i][j]\n mean_j = int_range[j]*matrix[i][j]\n variance_i += pow((int_range[i]-mean_i), 2) * matrix[i][j]\n variance_j += pow((int_range[j]-mean_j), 2) * matrix[i][j]\n\n texture[\"homogeneity\"] += (matrix[i][j] / (1+sqrt_diff_int))\n texture[\"dissimilarity\"] += (abs(int_range[i]-int_range[j]) * matrix[i][j])\n texture[\"contrast\"] += (sqrt_diff_int * matrix[i][j])\n texture[\"mean_i\"] += mean_i\n texture[\"mean_j\"] += mean_j\n texture[\"ASM\"] += pow(matrix[i][j], 2)\n texture[\"correlation\"] += matrix[i][j] * (int_range[i]-mean_i) * (int_range[j]-mean_j)\n\n if matrix[i][j] != 0:\n texture[\"entropy\"] += matrix[i][j] * math.log(matrix[i][j])\n\n texture[\"std_i\"] = math.sqrt(variance_i)\n texture[\"std_j\"] = math.sqrt(variance_j)\n texture[\"energy\"] = math.sqrt(texture[\"ASM\"])\n texture[\"entropy\"] = -1 * texture[\"entropy\"]\n texture[\"correlation\"] = (1 / (texture[\"std_i\"] * texture[\"std_j\"])) * texture[\"correlation\"]\n\n print(texture)\n","sub_path":"feature/texture.py","file_name":"texture.py","file_ext":"py","file_size_in_byte":6087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"47935770","text":"import pymongo\n\nK = 60.\nHOME_ADVANTAGE = 150.\n\ndef getDBCollection(coll_name):\n mongo_client = pymongo.MongoClient(\"mongodb://localhost:27017/\")\n db = mongo_client[\"nba\"]\n print('DB connected')\n return db[coll_name]\n\ndef elo_pred(elo1, elo2):\n pred = (1. / (10. ** (-(elo1 - elo2) / 400.) + 1.))\n return pred\n\ndef expected_margin(elo_diff):\n return((7.5 + 0.006 * elo_diff))\n\ndef elo_update(w_elo, l_elo, margin):\n elo_diff = w_elo - l_elo\n pred = elo_pred(w_elo, l_elo)\n mult = ((margin + 3.) ** 0.8) / expected_margin(elo_diff)\n update = K * mult * (1 - pred)\n print(\"**\", w_elo, l_elo, pred, margin, mult, update)\n return(pred, update)\n\nelo_map = {}\npred_map = {}\n\nseasons = ['2015']\n\ngames_coll = getDBCollection('games')\n\ncount_total = 0\ncount_correct = 0\ncount_wrong = 0\n\nfor season in seasons:\n\n # reset startign values\n for key in elo_map:\n elo_map[key] = (.00 * elo_map[key]) + (1.0 * 1500)\n # elo_map[key] = 1500.\n\n print('=================================================', season)\n\n cursor = games_coll.find({'seasonYear': season}).sort([('endTimeUTC', 1)])\n for g in cursor:\n\n hTeam_score = g['hTeam']['score']['points']\n vTeam_score = g['vTeam']['score']['points']\n\n if hTeam_score == '' or vTeam_score == '':\n continue\n\n if int(hTeam_score) > int(vTeam_score):\n home_win = True\n else:\n home_win = False\n\n print(g['endTimeUTC'], g['vTeam']['shortName'], g['vTeam']['score']['points'], \n g['hTeam']['shortName'], g['hTeam']['score']['points'], home_win)\n\n hTeam_name = g['hTeam']['shortName']\n vTeam_name = g['vTeam']['shortName']\n\n if hTeam_name in elo_map:\n h_elo = float(elo_map[ hTeam_name ])\n else:\n h_elo = 1500.\n\n if vTeam_name in elo_map:\n v_elo = float(elo_map[ vTeam_name ])\n else:\n v_elo = 1500. \n\n margin = abs(float(vTeam_score) - float(hTeam_score))\n\n h_elo += HOME_ADVANTAGE\n\n if home_win:\n pred, update = elo_update(h_elo, v_elo, margin)\n h_elo += update\n v_elo -= update\n else:\n pred, update = elo_update(v_elo, h_elo, margin)\n h_elo -= update\n v_elo += update\n \n # update map\n elo_map[ hTeam_name ] = h_elo\n elo_map[ vTeam_name ] = v_elo\n\n count_total += 1\n if (home_win and pred > 0.5) or (not home_win and pred < 0.5):\n count_correct += 1\n print('--', home_win, v_elo, h_elo, pred, 'Correct')\n else:\n count_wrong += 1\n print('--', home_win, v_elo, h_elo, pred, 'Wrong')\n\n # update DB\n games_coll.update_one( { '_id': g['_id'] } , \n { \"$set\": {'elo_pred': pred, 'hTeam.elo': h_elo, 'vTeam.elo': v_elo} } )\n\n\nprint('total: ', count_total, ' correct:', count_correct, ' wrong:', count_wrong, ' %', float(count_correct/count_total))","sub_path":"analysis/nba_team_elo.py","file_name":"nba_team_elo.py","file_ext":"py","file_size_in_byte":3016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"456181914","text":"import requests\r\nimport urllib\r\n\r\n\r\ndef get_api(url):\r\n result = requests.get(url)\r\n return result.json()\r\n\r\n\r\ndef main():\r\n keyword = \"鬼滅\"\r\n url = \"https://app.rakuten.co.jp/services/api/IchibaItem/Search/20170706?format=json&keyword={}&applicationId=1019079537947262807\".format(\r\n keyword)\r\n print(get_api(url))\r\n\r\n\r\nmain()\r\n","sub_path":"task06/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"203750707","text":"class Solution:\n def thirdMax(self, nums: List[int]) -> int:\n maxVal = float(\"-inf\")\n secondVal = float(\"-inf\")\n thirdVal = float(\"-inf\")\n\n count = 0 # 统计数值转移次数\n\n for index in range(len(nums)):\n\n if nums[index] > maxVal:\n thirdVal = secondVal\n secondVal = maxVal\n maxVal = nums[index]\n count += 1\n elif nums[index] > secondVal and nums[index] < maxVal:\n thirdVal = secondVal\n secondVal = nums[index]\n count += 1\n\n elif nums[index] > thirdVal and nums[index] < secondVal:\n thirdVal = nums[index]\n count += 1\n print(maxVal, secondVal, thirdVal)\n if count >= 3:\n return thirdVal\n else:\n return maxVal","sub_path":"chap1-数组/414. 第三大的数/thirdMax.py","file_name":"thirdMax.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"548290653","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/kula/workspace/ralph_pricing/src/ralph_pricing/tests/utils.py\n# Compiled at: 2014-05-30 05:53:08\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\nfrom collections import OrderedDict\nimport datetime\nfrom decimal import Decimal as D\nfrom ralph_pricing.models import DailyDevice, DailyExtraCost, Device, ExtraCostType, Venture\n\ndef get_or_create_device(name=None, asset_id=None, **kwargs):\n asset_id = asset_id if asset_id else Device.objects.all().count()\n name = name if name else (b'Default{0}').format(asset_id)\n return Device.objects.get_or_create(name=name, asset_id=asset_id, defaults=kwargs)[0]\n\n\ndef get_or_create_venture(name=None, venture_id=None, is_active=True, **kwargs):\n venture_id = venture_id if venture_id else Venture.objects.all().count()\n name = name if name else (b'Default{0}').format(venture_id)\n return Venture.objects.get_or_create(name=name, venture_id=venture_id, is_active=is_active, defaults=kwargs)[0]\n\n\ndef get_or_create_dailydevice(date, device, venture, **kwargs):\n return DailyDevice.objects.get_or_create(date=date, pricing_device=device, pricing_venture=venture, **kwargs)[0]\n\n\ndef get_or_create_extra_cost_type(name=None):\n if not name:\n name = (b'Default{0}').format(ExtraCostType.objects.all().count())\n return ExtraCostType.objects.get_or_create(name=name)[0]\n\n\ndef get_or_create_daily_extra_cost(date=None, venture=None, type=None, value=None):\n date = date if date else datetime.date(year=2014, month=5, day=1)\n venture = venture if venture else get_or_create_venture()\n type = type if type else get_or_create_extra_cost_type()\n value = value if value else D(100)\n return DailyExtraCost.objects.get_or_create(date=date, pricing_venture=venture, type=type, value=value)[0]\n\n\ndef sample_schema():\n return [\n OrderedDict([\n (\n b'field1', {b'name': b'Field1'}),\n (\n b'field2',\n {b'name': b'Field2', \n b'currency': True, \n b'total_cost': True})]),\n OrderedDict([\n (\n b'field3', {b'name': b'Field3'}),\n (\n b'field4',\n {b'name': b'Field4', \n b'currency': True, \n b'total_cost': True})])]","sub_path":"pycfiles/scrooge-2.4.0.tar/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"57040810","text":"import utils\nimport numpy as np\n\ndef get_train_name(index, type):\n\treturn 'training_data/' + str(index).zfill(4) + '_' + type + '_cg.pdb'\n\ndef get_min_max(type):\n\tx_dis = []\n\ty_dis = []\n\tz_dis = []\n\tfor i in range(3000):\n\t\t# print(i)\n\t\tx, y, z, _ = utils.read_pdb(get_train_name(i + 1, type))\n\t\tx_dis.append(np.amax(x) - np.amin(x))\n\t\ty_dis.append(np.amax(y) - np.amin(y))\n\t\tz_dis.append(np.amax(z) - np.amin(z))\n\n\tprint(np.histogram(x_dis))\n\treturn np.amax(x_dis), np.amax(y_dis), np.amax(z_dis)\n\ndef main():\n\t# print(get_min_max('pro'))\n\t# (310.935, -244.401, 432.956, -229.648, 435.107, -177.028)\n\t# print(get_min_max('lig'))\n\tget_min_max('lig')\n\t# (253.608, -187.322, 384.916, -140.466, 424.654, -100.571)\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"1a CS5242/3 Project/Code/abc_code can delete/analyse.py","file_name":"analyse.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"101025527","text":"import unittest\n\nimport numpy as np\nimport pandas as pd\n\nfrom tabular_dataset import TabularDataset\n\n\ndef get_test_df():\n return pd.DataFrame({\n 'A': [1, 2, 3, np.nan],\n 'B': [0, 1, 0, np.nan],\n 'C': list('abba'),\n 'target': list('xyzx')\n })\n\n\ndef test_column_names_are_correctly_set():\n df = get_test_df()\n\n tds = TabularDataset(df, binary_columns=['B'])\n\n assert tds.binary.column_names == ['B']\n\n\ndef test_encode():\n df = get_test_df()\n\n tds = TabularDataset(df, binary_columns=['B'])\n tds.binary.encode()\n\n assert repr(tds.x) == repr(np.array([-1, 1, -1, np.nan]).reshape(-1, 1))\n\n\ndef test_impute():\n df = get_test_df()\n\n tds = TabularDataset(df, binary_columns=['B'])\n tds.binary.impute()\n\n assert repr(tds.x) == repr(np.array([0, 1, 0, 0.]).reshape(-1, 1))\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_binary_columns.py","file_name":"test_binary_columns.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"622046875","text":"from time import sleep\r\n\r\nimport numpy as np\r\nimport imutils\r\nimport cv2\r\n\r\ntpl = cv2.imread(\"../../images/tpl/icon3.PNG\")\r\nscreen = cv2.imread(\"../../images/screen/screen.png\")\r\n\r\n# Get scales\r\nscales = np.linspace(0.2, 1.1, 20)[::-1]\r\nnp.append(scales, 1.)\r\n\r\n# Prepare tpl\r\n(tH, tW) = tpl.shape[:2]\r\n# _, tpl = cv2.threshold(tpl, 127, 255, cv2.THRESH_BINARY)\r\n\r\nmatch = None\r\n\r\nwhile True:\r\n for scale in scales:\r\n\r\n resized = imutils.resize(screen, width=int(screen.shape[1] * scale))\r\n # r = screen.shape[1] / float(resized.shape[1])\r\n\r\n # if the resized image is smaller than the template, then break\r\n # from the loop\r\n if resized.shape[0] < tH or resized.shape[1] < tW:\r\n break\r\n\r\n # _, resized = cv2.threshold(resized, 127, 255, cv2.THRESH_BINARY)\r\n result = cv2.matchTemplate(resized, tpl, cv2.TM_CCOEFF_NORMED)\r\n _, max_val, _, max_loc = cv2.minMaxLoc(result)\r\n\r\n cv2.circle(resized, max_loc, 6, (0, 0, 0))\r\n cv2.imshow(f'screen: {max_val}, loc: {max_loc}', resized)\r\n cv2.imshow('tpl', tpl)\r\n cv2.waitKey(10)\r\n sleep(1)\r\n cv2.destroyAllWindows()\r\n\r\n if match is None or max_val > match[0]:\r\n match = (max_val, max_loc, scale)\r\n\r\n max_val = match[0]\r\n scale = match[2]\r\n resized = imutils.resize(screen, width=int(screen.shape[1] * scale))\r\n\r\n if resized.shape[0] < tH or resized.shape[1] < tW:\r\n break\r\n\r\n # _, resized = cv2.threshold(resized, 127, 255, cv2.THRESH_BINARY)\r\n cv2.circle(resized, match[1], 4, (0, 0, 255))\r\n while True:\r\n cv2.imshow(f'screen: {max_val}', resized)\r\n cv2.imshow('tpl', tpl)\r\n cv2.waitKey(10)\r\n","sub_path":"opencv/opencv_play/multiscale_tm_own.py","file_name":"multiscale_tm_own.py","file_ext":"py","file_size_in_byte":1714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"645607000","text":"import netCDF4\nimport numpy as np\nimport matplotlib.pyplot as plt ; plt.close('all')\nimport os\n\nimport pygeo.geo\n\nfrom phdpy import settings\n\ndef _fill0(a):\n return np.ma.filled(a,0.)\n\ndef _set_n_linear_yticks(ax,n=5):\n ax.set_yticks(np.linspace(ax.get_ybound()[0], ax.get_ybound()[1], n))\n\n\ndef horizontal_profile_salt_flux(dsids,trkey,savefig=False,t=0):\n\n tr = settings.model_grid_transects[dsids[0]][trkey]\n if tr.flowdir != 'x':\n raise NotImplementedError('Function works only for transects with flow in x-direction.')\n\n fig,ax1 = plt.subplots()\n fig.subplots_adjust(top=0.85)\n fig.suptitle('Salt flux through {} section'.format(tr.long_name))\n\n ax2 = ax1.twinx()\n ax2.grid(False)\n \n ax3 = ax1.twinx()\n ax3.grid(False)\n fig.subplots_adjust(right=0.75)\n ax3.spines['right'].set_position(('axes', 1.2))\n ax3.set_frame_on(True)\n ax3.patch.set_visible(False)\n ax3.spines['right'].set_visible(True)\n ax3.spines['right'].set_facecolor('k')\n ax3.spines['right'].set_edgecolor('k')\n\n lines = []\n\n for dsid in dsids:\n with netCDF4.Dataset(settings.datafiles[dsid]) as ds:\n dsvar = ds.variables\n\n tr = settings.model_grid_transects[dsid][trkey]\n\n xax_u = pygeo.geo.remap_lon_180(dsvar['ULONG'][tr.jj,tr.ii])\n xax_t = pygeo.geo.remap_lon_180(dsvar['ULONG'][tr.jj,tr.ii])\n\n ues_int = np.cumsum((\n np.sum((\n _fill0(dsvar['UES'][t,:,tr.jj,tr.ii])\n * dsvar['DXU'][tr.jj,tr.ii] * 1e-2 \n * dsvar['DYT'][tr.jj,tr.ii] * 1e-2\n * dsvar['dz'][:][:,np.newaxis] * 1e-2\n ),axis=0)\n ),axis=-1)\n ues_int *= 1e-6\n\n salt_int = np.cumsum((\n np.sum((\n np.mean((\n (_fill0(dsvar['SALT'][t,:,tr.jj,tr.ii])\n #* dsvar['DXT'][tr.jj,tr.ii] * 1e-2\n * dsvar['DYT'][tr.jj,tr.ii] * 1e-2\n ),\n (_fill0(dsvar['SALT'][t,:,tr.jj,tr.ii-1])\n #* dsvar['DXT'][tr.jj,tr.ii-1] * 1e-2\n * dsvar['DYT'][tr.jj,tr.ii-1] * 1e-2\n )\n ),axis=0)\n * dsvar['dz'][:][:,np.newaxis] * 1e-2\n ),axis=0)\n ),axis=-1)\n \n uvel_int = np.cumsum((\n np.sum((\n _fill0(dsvar['UVEL'][t,:,tr.jj,tr.ii]) * 1e-2\n * dsvar['DYU'][tr.jj,tr.ii] * 1e-2\n * dsvar['dz'][:][:,np.newaxis] * 1e-2\n ),axis=0)\n ),axis=-1)\n uvel_int *= 1e-6 \n\n lines += ax1.plot(xax_t,ues_int,ls='-',label=dsid,\n color=settings.lineplotfmt[dsid]['color'])\n\n lines += ax2.plot(xax_t,salt_int,ls='--',\n color=settings.lineplotfmt[dsid]['color'])\n\n lines += ax3.plot(xax_u,uvel_int,ls='-.',\n color=settings.lineplotfmt[dsid]['color'])\n \n ax1.set_ylabel('Cumulative salt flux (Sv PPT) solid')\n ax2.set_ylabel('Cumulative salt content (PPT m2)')\n ax3.set_ylabel('Cumulative mean velocity (Sv)')\n ax1.set_xlabel('longitude')\n ax1.legend(loc=4)\n\n _set_n_linear_yticks(ax1)\n _set_n_linear_yticks(ax2)\n _set_n_linear_yticks(ax3)\n \n if savefig:\n figname = os.path.join('salt_budget_box','horizontal_salt_profile_{}_{}'.format(trkey,'_'.join(dsids)))\n settings.save_figure(fig,figname)\n else:\n plt.show()\n ghghg\n\n\nif __name__ == \"__main__\":\n settings.set_rc()\n \n defaults = dict(\n dsids = ['x3','x1'],\n trkey = 'IcelandScotland',\n )\n\n import argparse\n parser = argparse.ArgumentParser(description=\"Plot vertical profile of salt transport\")\n parser.add_argument('-d','--dsids',type=lambda s: s.split(','),help='dataset ID')\n parser.add_argument('-t','--trkey',type=str,help='transect ID')\n parser.add_argument('-s','--savefig',action='store_true',help='set this to save the figure')\n\n parser.set_defaults(**defaults)\n args = parser.parse_args()\n\n horizontal_profile_salt_flux(**vars(args))\n\n","sub_path":"ts_budget/horizontal_profile_salt_flux.py","file_name":"horizontal_profile_salt_flux.py","file_ext":"py","file_size_in_byte":4353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"508573954","text":"import urllib.request as url\nimport re\n\ndef get_links():\n f = open('./Tweets.txt','r')\n text = f.read()\n f.close()\n #links = text.split('\\n')\n links = re.findall('\"https:.+\" ',text)\n f = open('./Tweets_Links.txt', 'w')\n for link in links:\n f.write(str(link))\n f.write('\\n')\n f.close()\n\nprint('Beginning file download with urllib2...')\nf = open('./Tweets_Links.txt', 'r')\ntext = f.read()\nlinks = text.replace(\"\\\"\", \"\").split('\\n')\nindex=0\nfor link in links:\n print(link)\n save_path = str(index)\n if index >=31:\n save_path += \".zip\"\n else: save_path += '.csv'\n url.urlretrieve(link, './Tweets/'+save_path)\n index=index+1\n\n","sub_path":"DownloadDataset.py","file_name":"DownloadDataset.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"599514006","text":"import mysql.connector\nfrom difflib import SequenceMatcher, get_close_matches\n\n# SQL server connection\ncon = mysql.connector.connect(\n user=\"ardit700_student\",\n password=\"ardit700_student\",\n host=\"108.167.140.122\",\n database=\"ardit700_pm1database\"\n)\n\nrun_again = True\nprint(\"---WELCOME TO SQL ENGLISH DICTIONARY---\\n\")\n\n\nwhile run_again:\n\n # define SQL cursor\n cursor = con.cursor()\n i = 0\n word = input(\"Enter a word that you would like the definition to: \")\n print(\"\\n\")\n\n\n # Fetches expressiion and definition of word variable from SQL server\n query = cursor.execute(\"SELECT * FROM Dictionary WHERE Expression = '%s' \" % word)\n results = cursor.fetchall()\n query2 = cursor.execute(\"SELECT Expression FROM Dictionary\")\n expressions = [b[0] for b in cursor.fetchall()]\n\n if results: # if spelling is accurate then returns back value of dictionary\n for result in results:\n print(result[1])\n # otherwise checks for similar words and prompts user\n elif len(get_close_matches(word, expressions)) > 0:\n matches = get_close_matches(word, expressions)\n close_word = matches[0]\n error_check = input((\"did you mean %s instead? (Y/N): \" % close_word))\n if error_check == 'y' or error_check == 'Y':\n close_word_query = cursor.execute(\n \"SELECT * FROM Dictionary WHERE Expression = '%s' \" % close_word)\n close_word_definition = cursor.fetchall()\n for definition in close_word_definition:\n each_def = close_word_definition[i]\n print(each_def[1])\n i = i + 1\n else:\n print(\"Sorry, then that word does not exist in our database\")\n else:\n print(\"Sorry we do not have a definition for that word\\n\")\n print(\"\\n\")\n \n answer = input(\"Would you like to search for another word? (Y/N): \")\n print(\"\\n\")\n if answer == 'y' or answer == 'Y':\n run_again = True\n else:\n print(\"ENDING SERVER\")\n run_again = False\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"350603671","text":"'''\r\nCreated on Jul 12, 2017\r\n@author: qdoan1651\r\nThis script is to create a table of items on platform for post content deployment smoke test\r\nNote: Need to run utils_to_be_removed.temp_fix_data() to create 'course_info.json'\r\n'''\r\n\r\nimport openpyxl, re\r\n\r\nfrom myutils.utils_files_io import read_json_from_file\r\nfrom myutils.utils_files_io import read_list_from_file\r\nfrom myutils.utils_files_io import write_json_to_file\r\nfrom myutils.utils_openpyxl import write_list_to_excel\r\nfrom myutils.utils_files_io import write_list_to_file\r\n\r\n\r\ndef get_items_by_objective():\r\n print('Openning CCI grid file...')\r\n filename = 'F:/Cengage/DevMath/LCS, Authoring Tool, Prebuilt Courses/Dev Math Course Content Inventory - CCI (July 31).xlsx'\r\n wb = openpyxl.load_workbook(filename, data_only = True)\r\n \r\n ''' Open worksheet '''\r\n# courses = ['BCM']\r\n courses = ['FC', 'IA', 'BA', 'PA', 'BCM']\r\n \r\n courses_index = {'BCM': 1624, 'PA': 1757, 'BA': 1816, 'IA': 2326, 'FC': 3696}\r\n info = {}\r\n for course in courses:\r\n print('Processing course {}...'.format(course))\r\n ws = wb.get_sheet_by_name(course)\r\n ''' Info:\r\n * A: Authoring Tool module number and objective name abbreviation \r\n * I: Content type (item = LL exercise, ...)\r\n * J: CGID (TZAWURLV9QM5FV0VQ228)\r\n '''\r\n for i in range(2, courses_index[course]):\r\n# print('Processing line ' + str(i) + '...')\r\n content_type = ws['I' + str(i)].value\r\n at_info = ws['A' + str(i)].value\r\n cgid = ws['J' + str(i)].value\r\n if content_type == 'item':\r\n if at_info != None and cgid != None:\r\n if cgid not in info.keys():\r\n info[cgid] = at_info\r\n elif cgid in info.keys() and info[cgid] != at_info: \r\n print('*** Warning: Info mismatched for line {} in course {}'.format(i, course))\r\n print(info[cgid] + ' vs. ', end='')\r\n print(at_info)\r\n else:\r\n print('AT info: {}'.format(at_info))\r\n print('CGID: {}'.format(cgid))\r\n \r\n write_json_to_file(info, 'data/devmath_cci_July31_items_by_at_info.json')\r\n \r\n \r\n\r\ndef convert_cci_grid_to_json():\r\n ''' Method to parse info from prebuilt courses to extract\r\n 1) Exercise info: AC#. AC title, LL#. LL title, Question: #\r\n 2) Checkin Quiz info: AC#. AC title, LL#. LL title, Checkin: #\r\n 3) Quiz info: Quiz title\r\n 4) Alias info: Alias_19.B_17.A7\r\n \r\n Output: devmath_cci_July31.json\r\n \r\n 9/30/2017 - Add question # for Quiz\r\n '''\r\n \r\n ''' Open Excel workbook to read '''\r\n filename = 'H:/Cengage/DevMath/CCI/Dev Math Course Content Inventory - CCI (July 31).xlsx'\r\n wb = openpyxl.load_workbook(filename, data_only = True)\r\n \r\n ''' Dictionary to keep info of all items '''\r\n info = {}\r\n \r\n ''' Open worksheet '''\r\n courses = ['FC', 'IA', 'BA', 'PA', 'BCM']\r\n# courses = ['BCM']\r\n courses_index = {'BCM': 1624, 'PA': 1757, 'BA': 1816, 'IA': 2326, 'FC': 3696}\r\n for course in courses:\r\n print('Processing course {}...'.format(course))\r\n ws = wb.get_sheet_by_name(course)\r\n ''' Info:\r\n * C: Assignment number or Objective name \r\n * D: Assignment title and Objective title\r\n * I: Content type (item = LL exercise, ...)\r\n * J: CGID (TZAWURLV9QM5FV0VQ228)\r\n * AK: Exercise Set quantity (0 = optional)\r\n * AI: Check-in quiz item\r\n * AM: Quiz/Test item\r\n '''\r\n previous_quiz, quiz_number, quiz_counter = '', 1, 0\r\n prereq_number = 0\r\n for i in range(2, courses_index[course]):\r\n print('Processing line ' + str(i) + '...')\r\n name = ws['C' + str(i)].value\r\n title = ws['D' + str(i)].value\r\n content_type = ws['I' + str(i)].value\r\n cgid = ws['J' + str(i)].value\r\n quantity = ws['AK' + str(i)].value\r\n checkin = ws['AI' + str(i)].value\r\n quiz = ws['AM' + str(i)].value\r\n prereq = ws['AN' + str(i)].value\r\n \r\n if name != None and name.startswith('Assignment Chain'): \r\n ''' Get assignment number '''\r\n assignment_number = name.rstrip(' ').split(' ')[-1]\r\n \r\n ''' Get assignment title '''\r\n assignment_title = title\r\n \r\n ''' Reset Learning Loop counter to zero '''\r\n ll_counter = 0\r\n \r\n elif name != None and name.startswith('Objective'):\r\n ''' Get Learning Loop title '''\r\n ll_title = title\r\n \r\n ''' Increment Learning Loop counter '''\r\n ll_counter = ll_counter + 1\r\n \r\n ''' Reset exercise, checkin, and quiz counter to zero '''\r\n exercise_counter = 0\r\n checkin_counter = 0\r\n \r\n ''' Check to see if content type is 'item' '''\r\n if content_type == 'item':\r\n if quantity == None:\r\n question = 'Optional'\r\n elif quantity == 1:\r\n exercise_counter = exercise_counter + 1\r\n question = str(exercise_counter)\r\n elif quantity > 1:\r\n exercise_counter = exercise_counter + 1\r\n start = exercise_counter\r\n exercise_counter = exercise_counter + quantity - 1\r\n end = exercise_counter\r\n question = str(start) + '->' + str(end)\r\n \r\n ''' Check to see if CGID is already in the dictionary. If not, add placeholder '''\r\n if cgid not in info.keys():\r\n info[cgid] = {'exercise': {'FC': 'NA', 'IA': 'NA', 'BA': 'NA', 'PA': 'NA', 'BCM': 'NA'}, \\\r\n 'checkin': {'FC':'NA', 'IA':'NA', 'BA': 'NA', 'PA': 'NA', 'BCM': 'NA'}, \\\r\n 'quiz': {'FC':'NA', 'IA':'NA', 'BA': 'NA', 'PA': 'NA', 'BCM': 'NA'}, \\\r\n 'prerequisite':{},\r\n 'alias': 'NA', \\\r\n 'ada': 'NA'}\r\n \r\n ''' Now add exercise to dictionary '''\r\n item = 'AC' + str(assignment_number) + '. ' + assignment_title + '; ' + \\\r\n 'LL' + str(ll_counter) + '. ' + ll_title + '; ' + \\\r\n 'Question: ' + question\r\n info[cgid]['exercise'][course] = item\r\n \r\n ''' Check if item is an alias item '''\r\n label = ws['O' + str(i)].value\r\n if label.startswith('Alias'):\r\n info[cgid]['alias'] = label\r\n \r\n ''' Check to see if item is also a Check-in Quiz item '''\r\n if checkin != None and checkin.startswith('X'):\r\n checkin_counter = checkin_counter + 1 \r\n checkin_label = 'AC' + str(assignment_number) + '. ' + assignment_title + '; ' + \\\r\n 'LL' + str(ll_counter) + '. ' + ll_title + '; ' + \\\r\n 'Checkin: ' + str(checkin_counter)\r\n info[cgid]['checkin'][course] = checkin_label\r\n \r\n ''' Check to see if item is also used as a Quiz item '''\r\n if quiz != None and quiz.startswith('Quiz'):\r\n \r\n if quiz != previous_quiz:\r\n quiz_counter = quiz_counter + 1\r\n quiz_number = 1\r\n previous_quiz = quiz\r\n else:\r\n quiz_number = quiz_number + 1\r\n print(previous_quiz, quiz_counter, quiz, quiz_number)\r\n info[cgid]['quiz'][course] = str(quiz_counter) + ' - ' + re.sub('Quiz: ', '', quiz) + ' - Question: ' + str(quiz_number)\r\n \r\n ''' Check to see if item is also used in Pre-requisite.\r\n There is no Pre-requisite in BCM and FC courses. \r\n Pre-requisite for PA is specified in BCM course, BA in PA, IA in BA'''\r\n if prereq != None:\r\n prereq_number = prereq_number + 1\r\n if 'BCM' in prereq or 'FC' in prereq:\r\n print('*** Warning: Prerequisite does not exist for BCM or FC. CGID = {}. Course = {}'.format(cgid, prereq))\r\n if 'PreAlg' in prereq:\r\n course = 'PA'\r\n else:\r\n course = prereq\r\n info[cgid]['prerequisite'][course] = 'Prerequisite Question ' + str(prereq_number)\r\n \r\n \r\n # end of for 'index' loop\r\n # end of for 'course' loop \r\n \r\n ''' Write dictionary to disk '''\r\n write_json_to_file(info, 'data/devmath_cci_July31.json') \r\n# convert_cci_grid_to_json()\r\n \r\ndef convert_to_csv_for_cgid_search():\r\n ''' *** DO NOT DELETE ***\r\n Extract info from json and convert to CSV file for use in Google Sheet CGID search \r\n '''\r\n \r\n print('Reading info from devmath_cci_July31.json...')\r\n info = read_json_from_file('data/devmath_cci_July31.json')\r\n \r\n items_list = []\r\n for cgid in info.keys():\r\n exercise = info[cgid]['exercise']\r\n item_info = ''\r\n for course in ['FC', 'IA', 'BA', 'PA', 'BCM']:\r\n if exercise[course] != 'NA':\r\n item_info = item_info + course + ':; ' + exercise[course] + '; ; '\r\n items_list.append(cgid + '|' + item_info.rstrip('; '))\r\n \r\n ''' Write items list to file '''\r\n print('Writing output to file cgid_search.txt...')\r\n write_list_to_file(items_list, 'data/devmath_cci_exercise_cgid_search.txt')\r\n\r\ndef create_platform_item_to_cgid_mapping():\r\n ''' Input: devmath_cci_July31.json\r\n Output: devmath_cci_platform_exercise_cgid_mapping.json. Use this to add CGID to exercise on platform\r\n {\"PA.AC19.LL2.Q1\": \"YXNB398Z3M3EHJVNF155\",\r\n \"IA.AC5.LL2.Q1\": \"YXNB398Z3M3EHJVNF155\",\r\n ...\r\n }\r\n '''\r\n \r\n ''' json object for the compact version '''\r\n d = {}\r\n \r\n print('Reading info from devmath_cci_July31.json...')\r\n info = read_json_from_file('data/devmath_cci_July31.json')\r\n \r\n print('Processing devmath_cci_July31.json...')\r\n for i, cgid in enumerate(info.keys()):\r\n# if i > 10: break \r\n exercise = info[cgid]['exercise']\r\n# print(exercise)\r\n for course in ['BCM', 'PA', 'BA', 'IA', 'FC']:\r\n desc = exercise[course]\r\n# print(desc)\r\n if 'NA' not in desc and 'Optional' not in desc:\r\n assignment = desc.split('; ')[0].split(r'. ')[0]\r\n objective = desc.split('; ')[1].split(r'. ')[0]\r\n question = desc.split('; ')[2].split(': ')[1]\r\n if '->' in question:\r\n start, stop = question.split('->')\r\n for i in range(int(start), int(stop)+1):\r\n title = course + '.' + assignment + '.' + objective + '.' + 'Q' + str(i)\r\n# print(title)\r\n if title not in d.keys():\r\n d[title] = cgid\r\n else:\r\n print('*** Warning: {} already exists.'.format(title))\r\n else:\r\n title = course + '.' + assignment + '.' + objective + '.' + 'Q' + question\r\n# print(title)\r\n if title not in d.keys():\r\n d[title] = cgid\r\n else:\r\n print('*** Warning: {} already exists.'.format(title))\r\n \r\n ''' Write output data to file devmath_cci_platform_exercise_cgid_mapping.json '''\r\n write_json_to_file(d, 'data/devmath_cci_platform_exercise_cgid_mapping.json')\r\n \r\n\r\ndef create_short_version_for_exercise():\r\n ''' Input: devmath_cci_July31.json\r\n Output: devmath_cci_exercise_short.json\r\n {\"YXNB398Z3M3EHJVNF155\": { \"PA\": \"AC19.LL2.Optional\",\r\n \"BA\": \"AC17.LL1.Optional\",\r\n \"FC\": \"AC32.LL1.Optional\",\r\n \"IA\": \"AC1.LL2.Optional\",\r\n \"BCM\": \"NA\"\r\n },\r\n ...\r\n '''\r\n \r\n ''' json object for the compact version '''\r\n info_short = {}\r\n \r\n print('Reading info from devmath_cci_July31.json...')\r\n info = read_json_from_file('data/devmath_cci_July31.json')\r\n for cgid in info.keys():\r\n ''' Adding to the info_short dictionary '''\r\n if cgid not in info_short.keys():\r\n info_short[cgid] = {'BCM': '', 'PA': '', 'BA': '', 'IA': '', 'FC': ''}\r\n \r\n exercise = info[cgid]['exercise']\r\n# print(exercise)\r\n for course in ['BCM', 'PA', 'BA', 'IA', 'FC']:\r\n desc = exercise[course]\r\n# print(desc)\r\n if 'NA' not in desc:\r\n assignment = desc.split('; ')[0].split(r'. ')[0]\r\n objective = desc.split('; ')[1].split(r'. ')[0]\r\n question = desc.split('; ')[2].split(': ')[1]\r\n desc_short = assignment + '.' + objective + '.' + question\r\n else:\r\n desc_short = 'NA'\r\n \r\n info_short[cgid][course] = desc_short\r\n \r\n ''' Write new json object to disk '''\r\n print('Write output data to file devmath_cci_July31_exercise.json')\r\n write_json_to_file(info_short, 'data/devmath_cci_July31_exercise.json')\r\n \r\ndef create_short_version_for_checkin():\r\n ''' Input: devmath_cci_July31.json\r\n Output: devmath_cci_exercise_short.json\r\n {\"YXNB398Z3M3EHJVNF155\": { \"PA\": \"AC19.LL2.Optional\",\r\n \"BA\": \"AC17.LL1.Optional\",\r\n \"FC\": \"AC32.LL1.Optional\",\r\n \"IA\": \"AC1.LL2.Optional\",\r\n \"BCM\": \"NA\"\r\n },\r\n ...\r\n '''\r\n \r\n ''' json object for the compact version '''\r\n info_short = {}\r\n \r\n print('Reading info from devmath_cci_July31.json...')\r\n info = read_json_from_file('data/devmath_cci_July31.json')\r\n for cgid in info.keys():\r\n ''' Adding to the info_short dictionary '''\r\n if cgid not in info_short.keys():\r\n info_short[cgid] = {'BCM': '', 'PA': '', 'BA': '', 'IA': '', 'FC': ''}\r\n \r\n checkin = info[cgid]['checkin']\r\n# print(exercise)\r\n for course in ['BCM', 'PA', 'BA', 'IA', 'FC']:\r\n desc = checkin[course]\r\n# print(desc)\r\n if 'NA' not in desc:\r\n assignment = desc.split('; ')[0].split(r'. ')[0]\r\n objective = desc.split('; ')[1].split(r'. ')[0]\r\n question = desc.split('; ')[2].split(': ')[1]\r\n desc_short = assignment + '.' + objective + '.' + question\r\n else:\r\n desc_short = 'NA'\r\n \r\n info_short[cgid][course] = desc_short\r\n \r\n ''' Write new json object to disk '''\r\n print('Write output data to fie devmath_cci_July31_checkin.json')\r\n write_json_to_file(info_short, 'data/devmath_cci_July31_checkin.json')\r\n\r\ndef create_short_version_for_quiz():\r\n ''' Input: devmath_cci_July31.json\r\n Output: devmath_cci_exercise_short.json\r\n {\"YXNB398Z3M3EHJVNF155\": { \"BCM\": \"Quiz: Measurement\",\r\n \"BA\": \"NA\",\r\n \"FC\": \"NA\",\r\n \"PA\": \"Quiz: Measurement\",\r\n \"IA\": \"NA\"},\r\n ...\r\n '''\r\n \r\n ''' json object for the compact version '''\r\n info_short = {}\r\n \r\n print('Reading info from devmath_cci_July31.json...')\r\n info = read_json_from_file('data/devmath_cci_July31.json')\r\n for cgid in info.keys():\r\n ''' Adding to the info_short dictionary '''\r\n if cgid not in info_short.keys():\r\n info_short[cgid] = {'BCM': '', 'PA': '', 'BA': '', 'IA': '', 'FC': ''}\r\n \r\n quiz = info[cgid]['quiz']\r\n for course in ['BCM', 'PA', 'BA', 'IA', 'FC']:\r\n desc = quiz[course]\r\n info_short[cgid][course] = desc\r\n \r\n ''' Write new json object to disk '''\r\n print('Write output data to file devmath_cci_July31_quiz.json')\r\n write_json_to_file(info_short, 'data/devmath_cci_July31_quiz.json')\r\n # create_short_version_for_quiz() \r\n\r\ndef create_json_for_prerequisite():\r\n ''' Input: devmath_cci_July31.json\r\n Output: devmath_cci_exercise_short.json\r\n {\"YXNB398Z3M3EHJVNF155\": { \"BCM\": \"Quiz: Measurement\",\r\n \"BA\": \"NA\",\r\n \"FC\": \"NA\",\r\n \"PA\": \"Quiz: Measurement\",\r\n \"IA\": \"NA\"},\r\n ...\r\n '''\r\n \r\n ''' json object for the compact version '''\r\n info_short = {}\r\n \r\n print('Reading info from devmath_cci_July31.json...')\r\n info = read_json_from_file('data/devmath_cci_July31.json')\r\n for cgid in info.keys():\r\n quiz = info[cgid]['prerequisite']\r\n for course in ['BCM', 'PA', 'BA', 'IA', 'FC']:\r\n if course in quiz.keys():\r\n if cgid not in info_short.keys():\r\n info_short[cgid] = {}\r\n \r\n desc = quiz[course]\r\n info_short[cgid][course] = desc\r\n \r\n ''' Write new json object to disk '''\r\n print('Write output data to file devmath_cci_July31_prerequisite.json')\r\n write_json_to_file(info_short, 'data/devmath_cci_July31_prerequisite.json')\r\n# create_short_version_for_prerequisite() \r\n\r\nif __name__ == '__main__': \r\n ''' *** Must run for every new CCI before other functions ***\r\n Process CCI grid to create json object for all later work '''\r\n# convert_cci_grid_to_json()\r\n get_items_by_objective()\r\n \r\n ''' Parse json object to create csv for Google Sheet CGID search '''\r\n# convert_to_csv_for_cgid_search()\r\n\r\n ''' Parse json object to create a short version '''\r\n# create_short_version_for_exercise()\r\n# create_short_version_for_checkin()\r\n# create_short_version_for_quiz()\r\n# create_json_for_prerequisite()\r\n\r\n# create_platform_item_to_cgid_mapping()\r\n","sub_path":"DevMathPython/inventory/cci/cci.py","file_name":"cci.py","file_ext":"py","file_size_in_byte":18886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"362644993","text":"# 定义两个函数,第一个函数,计算任意两个数字的和。第二个函数,判断一个数字的和是偶数还是奇数\n\ndef sum_2_num(num1, num2):\n \"\"\"计算两数字之和\n\n :param num1: 数字1\n :param num2: 数字2\n :return: 返回计算结果\n \"\"\"\n result = num1 + num2\n return result\n\n\ndef odd_even_num(num1):\n \"\"\"判断数字是奇数或者偶数\n\n :param num1:数字\n \"\"\"\n if num1 % 2 == 0:\n print(num1, '是偶数')\n else:\n print(num1, '是奇数')\n\n\nif __name__ == '__main__':\n odd_even_num(sum_2_num(22, 55))\n","sub_path":"9月-Python核心编程/python核心编程阶段-python基础/03-function函数/9-15 课后练习函数嵌套.py","file_name":"9-15 课后练习函数嵌套.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"68346895","text":"# The task was to create stairs of either numbers or stars\r\n# I decided to also add pyramid shape feature as is requires more string sum shenanigans\r\n# All parameters should be specified by the user and will be asked until he inputs a correct value\r\n# Also pyramid and stairs scales with input to always stay the right shape (for example if 100 rows are specified:\r\n# all lower order numbers in pyramid and stairs will be 001, 002, etc. to keep the right shape)\r\n\r\n# At start I declare all possible string inputs for user\r\nanswerlist = ['pyramid', 'stairs']\r\nanswerlist2 = ['yes', 'no']\r\nanswerlist3 = ['numbers', 'stars']\r\n\r\n# All my program will repeat itself infinitely, until user specifies 'no' in the end\r\nwhile True:\r\n # Here user must specify the resultant shape. I check if his input is in list of possible answers and if it is not,\r\n # i ask him again nicely, until he makes a correct input\r\n while True:\r\n y = input('Do you want to get pyramid or stairs? ')\r\n if y in answerlist:\r\n break\r\n else:\r\n print('Pyramid or stairs!')\r\n continue\r\n\r\n # Here user must specify what 'bricks' must be used, numbers or stars.\r\n # I check if his input is in list of possible answers and if it is not,\r\n # i ask him again nicely, until he makes a correct input\r\n while True:\r\n j = input('Do you want to use numbers or stars? ')\r\n if j in answerlist3:\r\n break\r\n else:\r\n print('Numbers or stars!')\r\n continue\r\n\r\n # Here user must specify the number of rows.\r\n # I check if his input is integer value and if it is not,\r\n # i ask him again nicely, until he makes a correct input\r\n while True:\r\n try:\r\n x = int(input('Please input the number of rows: '))\r\n break\r\n except ValueError:\r\n print('Please enter an integer number!')\r\n continue\r\n\r\n # Part of code for stairs shape\r\n if y == 'stairs':\r\n for i in range(1, x+1):\r\n # Magical part of code that defines scalability and persistence of shape\r\n # for numbers of order higher than one\r\n if j == 'numbers':\r\n n = len(str(x))\r\n l = n - len(str(i))\r\n p = '0' * l + str(i)\r\n print((str(p)+' ') * i)\r\n elif j == 'stars':\r\n print('* '*i)\r\n print('End of stairs!')\r\n\r\n # Part of code for pyramid shape\r\n elif y == 'pyramid':\r\n for i in range(1, x+1):\r\n # Magical part of code that defines scalability and persistence of shape\r\n # for numbers of order higher than one\r\n if j == 'numbers':\r\n n = len(str(x))\r\n l = n - len(str(i))\r\n p = '0'*l + str(i)\r\n # Connecting strings in pyramid shape is much more interesting.\r\n # As I need to also maintain centration of rows with respect number order\r\n print((' '*(x-i))*n, (str(p)+' '*n)*i)\r\n elif j == 'stars':\r\n print(' ' * (x - i), '* ' * i)\r\n print('End of pyramid!')\r\n\r\n # Here user must specify if he wants to restart program.\r\n # I check if his input is 'yes' or 'no' and if it is not,\r\n # i ask him again nicely, until he makes a correct input\r\n while True:\r\n z = input('Again? ')\r\n if z in answerlist2:\r\n break\r\n else:\r\n print('Yes or no!')\r\n continue\r\n # If user answered 'yes' i continue to the next iteration of program\r\n if z == 'yes':\r\n continue\r\n # If 'no' program ends\r\n elif z == 'no':\r\n print('Bye!')\r\n break\r\n break\r\n","sub_path":"HomeworkFive/TaskN/Task_4_5.py","file_name":"Task_4_5.py","file_ext":"py","file_size_in_byte":3722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"16560350","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.feature_extraction.text import CountVectorizer\nimport xgboost as xgb\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.model_selection import train_test_split\nfrom scipy.sparse import hstack\nimport joblib\nvectorizer_keyword=joblib.load('artifacts/vectorizer_keyword.pkl')\nvectorizer_location=joblib.load('artifacts/vectorizer_location.pkl')\ntfidf_vectorizer=joblib.load('artifacts/tfidf_vectorizer.pkl')\nbst=joblib.load('artifacts/model.pkl')\n\nfrom flask import Flask,render_template,request,url_for\napp = Flask(__name__)\n\n\n#\n@app.route('/')\ndef hello_world():\n return 'Hello World!'\n\n@app.route('/index')\ndef form_input():\n return render_template('index.html')\n\n@app.route('/predict',methods=['post'])\ndef predict():\n location=request.form['location']\n keyword=request.form['keyword']\n message=request.form['message']\n\n location_transform=vectorizer_location.transform([location])\n keyword_transform=vectorizer_keyword.transform([keyword])\n message_transform=tfidf_vectorizer.transform([message])\n\n X_query=hstack([location_transform,keyword_transform,message_transform])\n X_query = xgb.DMatrix(X_query)\n pred=bst.predict(X_query)\n if(pred>0.5):\n return 'It is a Disaster tweet'\n else:\n return 'The tweet is not related to diaster category'\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=3000)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"2003376","text":"#!/usr/bin/env python3\n#Your-Quest V.078\n#A Text Based Adventure Game written in python\n\nimport pickle\nimport os\nimport time\nimport sys\n\n\n\nfoo = 0\ndef verblist():\n print(\"\"\"\nverblist = {\n 'fight' : fight, 'kill' : fight, 'attack' : fight,\n 'take' : take, 'get' : take, 'pick': take,\n 'communicate' : commuincate 'talk to' : communicate,\n 'look': examine, 'l': examine, 'examine': examine, 'x': examine,\n 'read' : examine, 'r': examine, 'describe': examine,\n 'north' : North, 'North' : North, 'Go North' : North,\n 'west' : West, 'West' : West, 'Go West' : West,\n 'east' : East, 'East' : East, 'Go East' : East,\n 'south' : South, 'South' : South, 'Go South' : South,\n 'eat' : eat, 'run' : run, 'flee' : run,\n}\"\"\")\n nexxt1 = input(\"Press enter to return to Menu\")\n os.system('clear')\n os.system('cls')\n\ndef save():\n with open(\"savegame\", \"wb\") as f:\n pickle.dump(foo, f)\n\ndef load():\n with open(\"savegame\", \"rb\") as f:\n foo = pickle.load(f)\n print(foo)\n\n\n\n#Import Modules\nprint(\"Importing modules....\")\nimport os\nimport string\nimport tempfile\nimport urllib\nimport sys\nimport time\nimport random\nimport getpass\nimport pickle\ntime.sleep(2)\nos.system('clear')\nos.system('cls')\n\n\n\n\n\n\n\n\n\n\n\ndef Menu():\n os.system('clear')\n os.system('cls')\n choice = 0\n while (choice != \"1\") or (choice != \"2\") or (choice != \"3\") or (choice != \"4\") or (choice != \"5\"):\n print(\"\"\"\nWelcome to Your-Quest!\n======================\n\n1 - New Game\n2 - VerbList\n3 - Read Changelog\n4 - Quit\n\nCopyright © 2013 Cenurtalishen DEV\n\"\"\")\n\n choice = input(\"Make a choice: \")\n if(choice == \"1\"):\n break\n\n\n elif(choice == \"2\"):\n verblist()\n elif(choice == \"3\"):\n file = open(\"Changelog.txt\")\n line = file.read()\n print()\n print(line)\n continue1 = input(\"Press enter to return to menu\")\n os.system('clear')\n os.system('cls')\n elif(choice == \"4\"):\n import logic\n\n \nMenu()\n \n\n#Define Variables\nfrom DefaultVar import *\n\n\n\n\nos.system('clear')\nos.system('cls')\n\nQuest = input(\"What should your quest be called?: \")\nQUEST = Quest.title()\nprint(\"Your Quest will be called '\" + QUEST + \"'!\")\n\n\n#Confirm Quest Name\nwhile True:\n Confirm = input(\"Is that Okay?: \")\n Confirm2 =Confirm.title()\n if(Confirm2 == \"No\"):\n print(\"Input a name for your quest!\")\n Quest = input(\"What should your quest be called?: \")\n QUEST = Quest.title()\n print(\"Your Quest will be called '\" + QUEST + \"'!\")\n pass\n elif(Confirm2 == \"Yes\"):\n break\n\n #RESTART GAME\n elif(Confirm2 == \"Restart\") or (Confirm2 == \"Reset\"):\n break\n #Exit\n elif(Confirm2 == \"Quit\") or (Confirm2 == \"Exit\"):\n import logic\n \n else:\n print(\"I don't recognise that command, please type in 'yes' or 'no'\")\n\n #Select Difficulty\nchoice = 0\nwhile (choice != \"1\") or (choice != \"2\") or (choice != \"3\"):\n print(\"\"\"\n\nPlease Select Your difficulty!\n\n1 - Easy (100 health points)\n2 - Moderate (70 health points)\n3 - Hard (50 health points)\n\n\"\"\")\n difficulty = input(\"Select difficulty: \").title()\n if (difficulty == \"1\") or (difficulty == \"Easy\"):\n PlyrHP = 100\n print(\"You have been given '100' health points\")\n time.sleep(1)\n break\n elif (difficulty == \"2\") or (difficulty == \"Moderate\"):\n print(\"You have been given '70' health points\")\n time.sleep(1)\n PlyrHP = 70\n break\n elif (difficulty == \"3\") or (difficulty == \"Hard\"):\n print(\"You have been given '50 health points\")\n PlyrHP = 50\n time.sleep(1)\n break\n \n \n \n#Character Creation\nwhile True:\n gender = input(\"Are You a boy or a girl? (type in boy or girl): \")\n ge = gender.title()\n if(ge == \"Boy\") or (ge == \"Girl\"):\n name = input(\"Enter your name: \")\n Name = name.title()\n save()\n break\n#RESTART GAME\n elif(Confirm2 == \"Restart\") or (Confirm2 == \"Reset\"):\n print(\"Restarting in: \")\n print(\"3\")\n time.sleep(1)\n print(\"2\")\n time.sleep(1)\n print(\"1\")\n time.sleep(1)\n os.system('clear')\n os.system('cls')\n Menu()\n else:\n print(\"'\" + ge + \"' is unrecognised, please input boy or girl\")\n\n \n \n\n#Character Verification\nwhile True:\n print(\"So your name is\",(name.title()), \"and you are a\",(ge) + \"?\")\n charactercreate = input(\"is this correct?: \")\n if (charactercreate == \"no\") or (charactercreate == \"No\") or (charactercreate == \"N\"):\n while True:\n gender = input(\"Are You a boy or a girl? (type in boy or girl): \")\n ge = gender.title()\n if(ge == \"Boy\") or (ge == \"Girl\"):\n name = input(\"Enter your name: \")\n break\n\n #RESTART GAME\n elif(Confirm2 == \"Restart\") or (Confirm2 == \"Reset\"):\n print(\"Restarting in: \")\n print(\"3\")\n time.sleep(1)\n print(\"2\")\n time.sleep(1)\n print(\"1\")\n time.sleep(1)\n os.system('clear')\n os.system('cls')\n Menu()\n\n\n else:\n print(\"'\" + ge + \"' is unrecognised, please input boy or girl\")\n \n #Exit\n elif(charactercreate == \"Quit\") or (charactercreate == \"Exit\"):\n import logic\n \n elif charactercreate == \"yes\" or (charactercreate == \"Yes\") or (charactercreate == \"Y\"):\n print(\"Welcome\", name.title() + \"!\")\n time.sleep(1)\n break\n\n #RESTART GAME\n elif(Confirm2 == \"Restart\") or (Confirm2 == \"Reset\"):\n print(\"Restarting in: \")\n print(\"3\")\n time.sleep(1)\n print(\"2\")\n time.sleep(1)\n print(\"1\")\n time.sleep(1)\n os.system('clear')\n os.system('cls')\n Menu()\n else:\n print(\"I don't recognise '\" + charactercreate + \"'!\")\n print(\"Please type in yes or no\")\n \n\n\n\n\n#Clear screen\nos.system('clear')\nos.system('cls')\n\n#Game Instructions\nprint(\"Instructions.....\")\nprint(\"This game is souly textbased, you will need to use text commands to navigate!\")\ntime.sleep(1)\nprint(\"For help, please check the 'README.MD'\")\nprint(\"You may exit at any time through the 'Exit' command\")\nwhile True:\n ready = input(\"Are you ready to play?: \")\n Ready = ready.title()\n if (ready) == \"yes\" or (ready) == \"Yes\" or (ready) == \"Y\":\n os.system('cls')\n os.system('clear')\n break\n elif (ready) == \"No\" or (ready) == \"no\" or (ready) == \"N\":\n print(\"Terminiating session, next person please\")\n os.system('clear')\n os.system('cls')\n Menu()\n\n #RESTART GAME\n elif(Ready == \"Restart\") or (Ready == \"Reset\"):\n print(\"Restarting in: \")\n print(\"3\")\n time.sleep(1)\n print(\"2\")\n time.sleep(1)\n print(\"1\")\n time.sleep(1)\n os.system('clear')\n os.system('cls')\n Menu()\n\n#Exit\n elif(Ready == \"Quit\") or (Ready == \"Exit\"):\n import logic\n \n else:\n print(\"Type in yes or no\")\n\n#Forest Level 1\nos.system('clear')\nos.system('cls')\nwhile True:\n direction = input(\"You are in a large forest, there is a path that leads to the West and a path to the East: \")\n direction2 = direction.title()\n absolutedir = direction2.strip('Go ').title()\n \n if (absolutedir == \"North\") or (absolutedir == \"South\"):\n print(\"The forest is to thick to go that way!\")\n\n elif absolutedir == \"East\":\n print(\"You follow the Eastern path and hear noises!\")\n break\n elif absolutedir == \"West\":\n print(\"You follow the Western path and find a chest with a cross bow and some bolts inside of it.\")\n print(\"'That'll come in handy' you think to yourself taking it from the chest.\")\n CrossBow = 1\n break\n#RESTART GAME\n elif(absolutedir == \"Restart\") or (absolutedir == \"Reset\"):\n print(\"Restarting in: \")\n print(\"3\")\n time.sleep(1)\n print(\"2\")\n time.sleep(1)\n print(\"1\")\n time.sleep(1)\n os.system('clear')\n os.system('cls')\n Menu()\n \n #Exit\n elif(absolutedir == \"Quit\") or (absolutedir == \"Exit\"):\n import logic\n\n\n\n\n else:\n print(\"I do not recognise\", absolutedir + \"!\")\n print(\"Please type in East or West\")\n \n\n\n#Forest East\nif absolutedir == \"East\":\n while True:\n print(\"You specifically hear a scuttering sound\")\n Noisereaction = input(\"Run or Hide?: \")\n norec = Noisereaction.title()\n #Run\n if norec == \"Run\":\n print(\"SPIDERS you shout out immediatley, you'd forgotten the forest was full of them!\")\n break\n #Restart Game\n elif (norec == \"Restart\") or (norec == \"Reset\") or (norec == \"restart\") or (norec == \"reset\"):\n Restart = 1\n break\n\n #Exit\n elif(norec == \"Quit\") or (norec == \"Exit\"):\n import logic\n \n #Hide\n elif norec == \"Hide\":\n print(\"You hide behind a tree, its not a particularly good hiding place, but it will buy you some time\")\n print(\"You scratch your head for a moment figuring out what the noise could be\")\n print(\"Then it hits you! SPIDERS!\")\n print(\"Of course you think to yourself, this forest is full of them!\")\n print(\"You hear the scuttering come closer, spiders are notoriously fast on their feet, to try and out run it would be murder!\")\n print(\"Although you're probably done for if you stay here!\")\n break\n #Restart Game\n elif (norec == \"Restart\") or (norec == \"Reset\") or (norec == \"restart\") or (norec == \"reset\"):\n Restart = 1\n break\n \n else:\n print(\"Type Hide or Run!\")\n\nif norec == \"Hide\": \n while True:\n Flightfight = input(\"Stay or Run?: \")\n FF = Flightfight.title()\n if FF == \"Run\":\n break\n #Restart Game\n elif (FF == \"Restart\") or (FF == \"Reset\") or (FF == \"restart\") or (FF == \"reset\"):\n Restart = 1\n break\n elif FF == \"Stay\":\n print(\"The spider senses you and attacks you. You are unable to resist\")\n print(\"The spider bites you and sucks the blood from you.\")\n print(\"You scream and your efforts were futile\")\n time.sleep(5)\n Menu()\n\n #Exit\n elif(FF == \"Quit\") or (FF == \"Exit\"):\n import logic\n\n #Clear screen\n os.system('clear')\n os.system('cls')\n Menu()\n \n else:\n print(\"Type either Stay or Run\")\n\n \n\n\n#Fight or flight logic gate\nif (FF == \"Run\") and (Restart == 0) or (norec == \"Run\") and (Restart == 0):\n print(\"You run as fast as your legs can carry you and unbelievably escape the spider\")\n print(\"Whilst running, you hear a man shouting.\")\n time.sleep(1)\n print(\"'Help!' He shouts. He sounds in a lot of pain\")\n\n #Help Man?\n while True:\n HelpHim = input(\"Help him?: \")\n HH = HelpHim.title()\n if (HH == \"Yes\"):\n print(\"You decide to help him!\")\n time.sleep(2)\n print(\"You run over to the man and ask him if he's ok\")\n time.sleep(2)\n print(\"'yes' he says, but tells you he was wounded by a gang of goblins!\")\n time.sleep(2)\n\n #I've Got to get out of here!\n print(\"'I've got to get out of here!' You say\")\n time.sleep(1)\n print(\"'Then you'll be needing this' said the man\")\n time.sleep(2)\n print(\"He hands you what looks like a map of the forest.\")\n time.sleep(2)\n print(\"'Thanks,' you say, but just before you go to leave, he stops you!\")\n time.sleep(2)\n print(\"'\" + name.title() + \"! You might want this!' he says\")\n time.sleep(2)\n print(\"He hands you a crossbow\")\n print(\"You thank the man and wonder...\")\n print(\"How does he know my name?\")\n CrossBow = 1\n manhelp = 1\n time.sleep(2)\n break\n \n\n elif HH == \"No\":\n print(\"You decide to leave him\")\n manhelp = -1\n break\n\n #Exit\n elif(HH == \"Quit\") or (FF == \"Exit\"):\n import logic\n #Restart Game\n elif (HH == \"Restart\") or (HH == \"Reset\") or (HH == \"restart\") or (HH == \"reset\"):\n Restart = 1\n break\n else:\n print(\"I don't recognise '\" + HH + \"'!\")\n print(\"Type either 'Yes' or 'No'\")\n\n#Forest CrossRoads\nif(Restart == 0):\n print(\"You come across some cross roads\")\n while True:\n direction = input(\"Which direction?: \")\n direction2 = direction.title()\n absolutedir2 = direction2.strip(\"Go \").title()\n if (absolutedir2 == \"North\"):\n break\n elif (absolutedir2 == \"South\"):\n break\n elif (absolutedir2 == \"West\"):\n break\n elif (absolutedir2 == \"East\"):\n break\n\n #Restart Game\n elif (absolutedir2 == \"Restart\") or (absolutedir2 == \"Reset\") or (absolutedir2 == \"restart\") or (absolutedir2 == \"reset\"):\n Restart = 1\n break\n #Exit\n elif(absolutedir2 == \"Quit\") or (absolutedir2 == \"Exit\"):\n import logic\n\n else:\n print(\"Type in either 'North', 'South', 'East' or 'West'\")\n \n \n#North \nif (absolutedir2 == \"North\"):\n print(\"You go North and are faced with a huge troll\")\n while True:\n fight = input(\"What should you do?: \")\n FF = fight.title()\n if (FF == \"Fight\") and (CrossBow > 0):\n break\n\n #RESTART GAME\n elif(FF == \"Restart\") or (FF == \"Reset\"):\n print(\"Restarting in: \")\n print(\"3\")\n time.sleep(1)\n print(\"2\")\n time.sleep(1)\n print(\"1\")\n time.sleep(1)\n os.system('clear')\n os.system('cls')\n Menu()\n #Exit\n elif(FF == \"Quit\") or (FF == \"Exit\"):\n import logic\n \n elif (FF == \"Fight\") and (CrossBow == 0):\n print(\"You have no weapon to fight with\")\n elif (FF == \"Run\"):\n Chance = random.randint(0, 1)\n if (Chance == 1):\n print(\"You try to run past the troll and succeed\")\n break\n else:\n print(\"The troll throws his axe at you and you are sliced in half.\")\n print(\"Your guts spew out everywhere and you lie there motionless\")\n time.sleep(4)\n #Clear screen\n os.system('clear')\n os.system('cls')\n Menu()\n \n elif (FF == \"Communicate\"):\n print(\"'Excuse me Mr. Troll, but your blocking the path!'\")\n print(\"'Grrr,' He says\")\n\n #Eat the Troll\n \n elif (FF == \"Eat The Troll\") or (FF == \"Eat\"):\n Poison = random.randint(0, 1)\n if(Poison == 0):\n print(\"You were poisoned by the troll!\")\n time.sleep(2)\n print(\"You choke and die\")\n time.sleep(5)\n Menu()\n else:\n print(\"You eat the troll\")\n print(\"Delicious you think\")\n break\n else:\n print(\"Type in 'Fight', 'Run', 'Eat' or 'Communicate'\")\n\n#Fight Troll\nif (FF == \"Fight\") and (CrossBow > 0):\n while True:\n time.sleep(2)\n chance = random.randint(0, 2)\n Trolldam = random.randint(7, 10)\n Plyrdam = random.randint(1, 27)\n if (chance > 0):\n Troll -= Plyrdam\n print(name.title(), \"hits Troll with\", Plyrdam, \"damage\")\n if(Troll < 0) and (PlyrHP > 0):\n print(\"The troll thuds onto the ground.\")\n print(\"You loot his battle axe and take a tooth as a souvenir\")\n Axe = 1\n TrollTooth = 1\n break\n else:\n time.sleep(2)\n chance = random.randint(0, 2)\n if (chance > 0):\n PlyrHP -= Trolldam\n print(\"Troll hits\", name.title(),\"with\", Trolldam, \"damage\")\n if(PlyrHP < 0) and (Troll > 0):\n print(\"The Troll batters you and you hit the floor.\")\n print(\"Motionless and lifeless\")\n time.sleep(4)\n #Clear screen\n os.system('clear')\n os.system('cls')\n Menu()\n else:\n print(\"Troll misses \" + name.title())\n else:\n print(name.title(), \"misses Troll!\")\n time.sleep(2)\n chance = random.randint(0, 2)\n if (chance > 0):\n PlyrHP -= Trolldam\n print(\"Troll hits\", name.title(),\"with\", Trolldam, \"damage\")\n if(PlyrHP < 0) and (Troll > 0):\n print(\"The Troll batters you and you hit the floor.\")\n print(\"Motionless and lifeless\")\n time.sleep(4)\n #Clear screen\n os.system('clear')\n os.system('cls')\n Menu()\n \n else:\n print(\"The Troll misses \" + name.title())\n\n#North 2\nif (absolutedir2 == \"North\"):\n time.sleep(2)\n print(\"You check the map and realise you must be in the snowy area of the forest\")\n time.sleep(2)\n print(\"You do however feel very illequipped for such cold weather!\")\n time.sleep(2)\n print(\"Suddenly you hear a growling coming from behind a tree\")\n time.sleep(2)\n print(\"Wolves are notorious for hanging around in packs, so its probably best not to attack it\")\n time.sleep(2)\n print(\"You could try to tame it though, but what with?\")\n time.sleep(2)\n while True:\n Wolfreaction = input(\"Tame it or fight it?: \")\n Woreaction = Wolfreaction.title()\n if (Woreaction == \"Tame\"):\n print(\"You remember that you have some meat left over.\")\n print(\"You'll never know when you might need some meat!\")\n break\n\n\n elif (Woreaction == \"Fight\") and (CrossBow == 1) and (Axe == 1):\n break\n\n #RESTART GAME\n elif(Woreaction == \"Restart\") or (Woreaction == \"Reset\"):\n print(\"Restarting in: \")\n print(\"3\")\n time.sleep(1)\n print(\"2\")\n time.sleep(1)\n print(\"1\")\n time.sleep(1)\n os.system('clear')\n os.system('cls')\n Menu()\n #Exit\n elif(Woreaction == \"Quit\") or (Woreaction == \"Exit\"):\n import logic\n\n\n\n \n #Fight Wolf (CROSSBOW ONLY)\n elif (Woreaction == \"Fight\") and (CrossBow == 1) and (Axe == 0):\n print(\"You fight with the crossbow\")\n break\n\n \n #No Weapon\n elif (Woreaction == \"Fight\") and (CrossBow == 0) and (Axe == 0):\n print(\"You have no weapon to fight with\")\n else:\n print(\"Type in either 'Fight' or 'Tame'\")\n\n#TAME WOLF!\nif(absolutedir2 == \"North\") and (Woreaction == \"Tame\"):\n WolfName = input(\"What would you like to call the wolf?: \")\n while True:\n print(\"So your new companion will be called '\" + (WolfName) + \"'!\")\n confirm = input(\"Is that Okay?: \")\n confirm2 = confirm.title()\n if confirm2 == \"Yes\":\n print(\"Success\")\n Wolfcon = 1\n break\n elif confirm == \"No\":\n WolfName = input(\"What would you like to call the wolf?: \")\n pass\n #RESTART GAME\n elif(Confirm2 == \"Restart\") or (Confirm2 == \"Reset\"):\n print(\"Restarting in: \")\n print(\"3\")\n time.sleep(1)\n print(\"2\")\n time.sleep(1)\n print(\"1\")\n time.sleep(1)\n os.system('clear')\n os.system('cls')\n Menu()\n\n #Exit\n elif(Confirm2 == \"Quit\") or (Confirm2 == \"Exit\"):\n import logic\n \n else:\n print(\"Type in 'Yes' or 'No\")\n#Fight Wolf (Weapon Select)\nif (Woreaction == \"Fight\") and (CrossBow == 1) and (Axe == 1):\n while True:\n Weaponselect = input(\"Which weapon?: \")\n WS = Weaponselect.title()\n \n\n #Fight Wolf Weapon Select\n\n #CrossBow\n if WS == \"Crossbow\":\n print(\"You Chose to fight with a Crossbow\")\n break\n #Axe \n elif (WS == \"Axe\"):\n print(\"You chose to fight with an Axe\")\n print(\"The wolf spots you and attacks!\")\n break\n #RESTART GAME\n elif(WS == \"Restart\") or (WS == \"Reset\"):\n print(\"Restarting in: \")\n print(\"3\")\n time.sleep(1)\n print(\"2\")\n time.sleep(1)\n print(\"1\")\n time.sleep(1)\n os.system('clear')\n os.system('cls')\n Menu()\n #Exit\n elif(WS == \"Quit\") or (WS == \"Exit\"):\n import logic\n else:\n print(\"Type in 'Axe' or 'CrossBow'\")\n\n#Fight Wolf (Mechanics for CrossBow)\nif (Woreaction == \"Fight\") and (WS == \"Crossbow\") or (Woreaction == \"Fight\") and (CrossBow == 1) :\n while True:\n Wolf = random.randint(10, 20)\n Wolfdam = random.randint(5, 10)\n CrossBowdam = random.randint(1, 27)\n chance = random.randint(0, 2)\n if(chance > 0):\n Wolf-=CrossBowdam\n print(name.title(), \"hit Wolf with\", CrossBowdam, \"damage!\")\n if(Wolf <= 0):\n print(\"The Wolf thuds to the ground!\")\n print(\"There doesn't appear to be a pack, so maybe it was a lone wolf!\")\n time.sleep(2)\n print(\"You skin the Wolf and use it as a coat!\")\n Wolfskin = 1\n break\n else:\n time.sleep(2)\n chance = random.randint(0, 2)\n if(chance > 0):\n PlyrHP-=Wolfdam\n print(\"Wolf hit\", name.title(), \"with\", Wolfdam, \"damage!\")\n time.sleep(2)\n if(PlyrHP <= 0):\n print(\"You thud to the floor unable to move\")\n print(\"You lay there motionless\")\n time.sleep(5)\n #Clear screen\n os.system('clear')\n os.system('cls')\n Menu()\n else:\n print(\"Wolf misses\", name.title())\n else:\n print(name.title(), \"misses the wolf\")\n time.sleep(2)\n chance = random.randint(0, 2)\n if(chance > 0):\n PlyrHP-=Wolfdam\n print(\"Wolf hit\", name.title(), \"with\", Wolfdam, \"damage!\")\n time.sleep(2)\n if(PlyrHP <= 0):\n print(\"You thud to the floor unable to move\")\n print(\"You lay there motionless\")\n time.sleep(5)\n #Clear screen\n os.system('clear')\n os.system('cls')\n Menu()\n else:\n print(\"Wolf misses\", name.title())\n\n#Fight Wolf (Mechanics for Axe)\nelif (Woreaction == \"Fight\") and (WS == \"Axe\"):\n while True:\n Wolf = random.randint(10, 20)\n Wolfdam = random.randint(5, 10)\n Axedam = random.randint(7, 36)\n chance = random.randint(0, 2)\n if(chance > 0):\n PlyrHP-=Wolfdam\n time.sleep(2)\n print(\"Wolf hits with\", Wolfdam, \"damage!\")\n time.sleep(2)\n if(PlyrHP <= 0):\n print(\"Wolf Wins\")\n #Clear screen\n os.system('clear')\n os.system('cls')\n Menu()\n else:\n Wolf-=Axedam\n print(name.title(), \"hits Wolf with\", Axedam, \"damage\")\n if(Wolf <= 0):\n print(\"The Wolf thuds to the ground!\")\n print(\"There doesn't appear to be a pack, so maybe it was a lone wolf!\")\n time.sleep(2)\n print(\"You skin the Wolf and use it as a coat!\")\n Wolfskin = 1\n break\n else:\n print(\"Wolf misses\", name.title())\n chance = random.randint(0, 2)\n if(chance > 0):\n Wolf-=Axedam\n print(name.title(), \"hits Wolf with\", Axedam, \"damage\")\n if(Wolf <= 0):\n print(\"The Wolf thuds to the ground!\")\n print(\"There doesn't appear to be a pack, so maybe it was a lone wolf!\")\n time.sleep(2)\n print(\"You skin the Wolf and use it as a coat!\")\n Wolfskin = 1\n break\n else:\n print(name.title(), \"misses Wolf\") \n \n \n \n\n\n\n#North 3 (Sleep)\nif (absolutedir2 == \"North\"):\n print(\"It starts to get dark\")\n time.sleep(2)\n print(\"'Better set camp for the night' You think\")\n time.sleep(2)\n print(\"You gather firewood, light a fire and huddle round it in an attempt to stay warm.\")\n time.sleep(2)\n print(\"You'll need a place to sleep for the night\")\n time.sleep(2)\n print(\"You decide you'll have to either on the floor or you could use the tree!\")\n while True:\n sleep = input(\"Tree or Ground?: \")\n Sleep = sleep.title()\n if (Sleep == \"Tree\"):\n print(\"You pull out a hammock and tie it to two trees\")\n break\n elif (Sleep == \"Ground\"):\n print(\"You sleep on the ground, using your satchel as a pillow\")\n break\n #RESTART GAME\n elif(Sleep == \"Restart\") or (Sleep == \"Reset\"):\n print(\"Restarting in: \")\n print(\"3\")\n time.sleep(1)\n print(\"2\")\n time.sleep(1)\n print(\"1\")\n time.sleep(1)\n os.system('clear')\n os.system('cls')\n Menu()\n\n\n #Exit\n elif(Sleep == \"Quit\") or (Sleep == \"Exit\"):\n import logic\n\n \n else:\n print(\"I don't recognise '\" + Sleep + \"'!\")\n print(\"Choose 'Tree' or 'Ground'\")\n\n#North (sleep with wolf)\nif (absolutedir2 == \"North\") and (Wolfcon == 1):\n print(\"You are awoken by\", WolfName + \"!\")\n print(\"You look around to see what all the fuss is about\")\n time.sleep(2)\n print(\"In the distance you can hear laughing, but not just any laughter, Goblin laughter!\")\n time.sleep(4)\n print(\"Shhh you say to\", WolfName, \"who continues barking\")\n print(\"You listen and come closer to the goblins\")\n time.sleep(2)\n print(\"They don't spot you and you notice a huge thriving colony of goblins\")\n print(\"You remember how cold you are and wonder how the goblins aren't cold, they usually hate the cold\")\n time.sleep(4)\n print(\"'You can't sleep now,' you think\")\n time.sleep(2)\n print(\"What are they plotting you wonder\")\n time.sleep(4)\n if(manhelp == 1):\n print(\"'Strange things really aren't they, its okay, remember me?' Says a familair voice\")\n time.sleep(2)\n print(\"'Jesus Christ you're that guy who gave me that crossbow and the map', you say\")\n time.sleep(2)\n print(\"'Sure am, so you figured out where we are yet?'\")\n time.sleep(3)\n print(\"'In this general area hereish' you say pointing out an area which must cover at least 200 square feet\")\n time.sleep(4)\n print(\"'Come on' he says 'I have much to show you'\")\n while True:\n follow = input(\"Follow him?: \")\n Follow = follow.title()\n if Follow == \"Yes\":\n print(\"You follow the man\")\n cenur = 1\n time.sleep(3)\n break\n elif Follow == \"No\":\n print(\"'I'd rather stay here' you say\")\n time.sleep(2)\n print(\"'I don't think that's such a good idea', he says\")\n time.sleep(2)\n print(\"'But if that's what you really want, then I cannot force you to come, stay safe\", Name, \"!\")\n time.sleep(2)\n print(\"Curiousity gets the better of you and so you follow him\")\n cenur = 1\n time.sleep(3)\n break\n #RESTART GAME\n elif(Follow == \"Restart\") or (Follow == \"Reset\"):\n print(\"Restarting in: \")\n print(\"3\")\n time.sleep(1)\n print(\"2\")\n time.sleep(1)\n print(\"1\")\n time.sleep(1)\n os.system('clear')\n os.system('cls')\n Menu()\n\n\n #Exit\n elif(Follow == \"Quit\") or (Follow == \"Exit\"):\n import logic\n \n else:\n print(\"Type either 'yes' or 'no'\")\n \n elif(manhelp == -1):\n print(\"A man whacks you over the head with something very hard\")\n print(\"You lay there motionless and soon goblins discover you and your\")\n time.sleep(2)\n print(\"You awaken to find yourself tied to a pole\")\n time.sleep(2)\n print(\"You feel incredibly warm and realise you are in the middle of the fire\")\n time.sleep(2)\n print(\"You can see other goblins laughing at you\")\n print(\"You loose all sense of consciouness and burn to death\")\n time.sleep(5)\n #Clear screen\n os.system('clear')\n os.system('cls')\n else:\n print(\"'Funny things aren't they,' says a man\")\n time.sleep(2)\n print(\"You nearly jump out of your skin\")\n time.sleep(2)\n print(\"'Do I know you,' You say\")\n time.sleep(2)\n print(\"'Don't think so, but I know you!'\")\n time.sleep(2)\n print(\"At this point,\", WolfName, \"growls!\")\n time.sleep(2)\n print(\"All will be explained he says and so you follow him!\")\n time.sleep(3)\n cenur = 1\n\n\n #Cenurtalishen\nif cenur == 1:\n print(\"The man takes you to a hut on top of a large tree\")\n time.sleep(2)\n print(\"'How do you know my name?' you ask 'Who are you?'\")\n time.sleep(2)\n print(\"'My name is of no importance!' He says\")\n time.sleep(2)\n print(\"'Oh come on, its just a name!'\")\n time.sleep(2)\n print(\"'Fine.'\")\n time.sleep(1)\n print(\"'My name is 'Cenurtalishen'!' He says.\")\n time.sleep(2)\n print(\"You're not quite sure how to respond to this, its a strange name\")\n print(\"You could ask him to repeat it maybe, ask if its his real name, ask him to spell it or just go with it\")\n time.sleep(2)\n while True:\n cenurres = input(\"Please type either: 'Repeat', 'Real Name', 'Spell it', or 'Ignore': \")\n Cenurres = cenurres.title()\n if Cenurres == \"Repeat\":\n print(\"'Sorry didn't quite catch that' you say, 'Could you repeat that for me?'\")\n time.sleep(2)\n print(\"'Cenurtalishen!' said Cenurtalishen.\")\n break\n elif Cenurres == \"Real Name\":\n print(\"'Is that you're real name?' you ask\")\n time.sleep(2)\n print(\"'Of course its my real name you absolute berk!\")\n time.sleep(2)\n print(\"'Okay Okay', you say, 'I'm sorry'\")\n break\n elif Cenurres == \"Spell it\":\n print(\"'can you spell it for me?' You ask\")\n time.sleep(2)\n print(\"'What? NO!' he says\")\n break\n elif Cenurres == \"Ignore\":\n print(\"'Okay' you say and you move on\")\n break\n #RESTART GAME\n elif(Cenurres == \"Restart\") or (Cenurres == \"Reset\"):\n print(\"Restarting in: \")\n print(\"3\")\n time.sleep(1)\n print(\"2\")\n time.sleep(1)\n print(\"1\")\n time.sleep(1)\n os.system('clear')\n os.system('cls')\n Menu()\n #Exit\n elif(Cenurres == \"Quit\") or (Cenurres == \"Exit\"):\n import logic\n \n else:\n continue\n \n\n\n#Move on?\nif (Cenurres == \"Repeat\") or (Cenurres == \"Real Name\") or (Cenurres == \"Spell it\"):\n while True:\n confirm = input(\"'Now can we please move on?' He says: \")\n confirm2 = confirm.title()\n if confirm2 == \"Yes\":\n print(\"'Good' says Cenurtalishen\")\n break\n elif confirm2 == \"No\":\n while True:\n cenurres = input(\"Please type either: 'Repeat', 'Real Name', 'Spell it', or 'Ignore': \")\n Cenurres = cenurres.title()\n if Cenurres == \"Repeat\":\n print(\"Sorry didn't quite catch that' you say, 'Could you repeat that for me?'\")\n time.sleep(2)\n print(\"'Cenurtalishen!' said Cenurtalishen.\")\n break\n elif Cenurres == \"Real Name\":\n print(\"'Is that you're real name?' you ask\")\n time.sleep(2)\n print(\"'Of course its my real name you absolute berk!\")\n time.sleep(2)\n print(\"'Okay Okay', you say, 'I'm sorry'\")\n break\n elif Cenurres == \"Spell it\":\n print(\"'can you spell it for me?' You ask\")\n time.sleep(2)\n print(\"'What? NO!' he says\")\n break\n elif Cenurres == \"Ignore\":\n print(\"'Okay' you say and you move on\")\n break\n #RESTART GAME\n elif(Cenurres == \"Restart\") or (Cenurres == \"Reset\"):\n print(\"Restarting in: \")\n print(\"3\")\n time.sleep(1)\n print(\"2\")\n time.sleep(1)\n print(\"1\")\n time.sleep(1)\n os.system('clear')\n os.system('cls')\n Menu()\n #Exit\n elif(Cenurres == \"Quit\") or (Cenurres == \"Exit\"):\n import logic\n \n else:\n continue\n\n #Exit\n elif(Confirm2 == \"Quit\") or (Confirm2 == \"Exit\"):\n import logic \n else:\n print(\"Please type in 'Yes' or 'No'\")\n \n \n \n \n \n \n\n#North without Wolf\nif (absolutedir2 == \"North\") and (Sleep == \"Tree\") and (WolfName == 0) or (absolutedir2 == \"North\") and (Sleep == \"Ground\") and (WolfName == 0) :\n awaken = random.randint(0, 1)\n if awaken == 0:\n print(\"In the night Goblins carry you away\")\n time.sleep(2)\n print(\"You awaken to find yourself tied to a pole\")\n time.sleep(2)\n print(\"You feel incredibly warm and realise you are in the middle of the fire\")\n time.sleep(2)\n print(\"You can see other goblins laughing at you\")\n print(\"You loose all sense of consciouness and burn to death\")\n time.sleep(5)\n #Clear screen\n os.system('clear')\n os.system('cls')\n Menu()\n elif awaken == 1:\n print(\"You are awoken by an unfamilair sound\")\n time.sleep(2)\n print(\"'RUN!' Shouts a man in the distance\")\n time.sleep(2)\n print(\"You run as fast as you can not looking back\")\n time.sleep(2)\n\n #Witch without wolf\nif (absolutedir2 == \"North\") and (WolfName == 0):\n print(\"You feel exhausted after running for so long\")\n time.sleep(2)\n print(\"You look at the moon and work out that the time must be around 3-4AM in the morning\")\n time.sleep(2)\n print(\"The sun will be rising soon you think\")\n time.sleep(2)\n print(\"You can hear sobbing in the distance, although should you trust it?\")\n\n while True:\n sob1 = input(\"Investigate the sobbing?: \")\n Sob = sob1.title()\n \n if(Sob == \"Yes\"):\n print(\"You decide to investigate the sobbing and find an old woman\")\n Chance = random.randint(0, 1)\n if(Chance == 1):\n print(\"The old woman turns out to be a witch! You try to avoid her, but she is too powerful\")\n time.sleep(2)\n print(\"You thud to the floor, hearing the cackling of the witch\")\n time.sleep(5)\n Menu()\n else:\n print(\"The old woman turns out to be a witch!\")\n time.sleep(1)\n print(\"She tries to hit you with a fireball, but misses you!\")\n time.sleep(1)\n print(\"You could try and fight her or you could run.\")\n break\n \n \n elif Sob == \"No\":\n print(\"You leave and ignore the sobbing\")\n break\n #Exit\n elif(Sob == \"Quit\") or (Sob == \"Exit\"):\n import logic\n #RESTART GAME\n elif(Sob == \"Restart\") or (Sob == \"Reset\"):\n print(\"Restarting in: \")\n print(\"3\")\n time.sleep(1)\n print(\"2\")\n time.sleep(1)\n print(\"1\")\n time.sleep(1)\n os.system('clear')\n os.system('cls')\n Menu()\n else:\n print(\"Type in 'yes' or 'no'\")\n \n#Witch\nif(Sob == \"Yes\"):\n while True:\n ff = input(\"What should you do?: \")\n FF = ff.title()\n\n #FIGHTING WITCH\n if(FF == \"Fight\") and (CrossBow == 1) and (Axe == 1):\n F1 = 12\n break\n\n elif(FF == \"Fight\") and (CrossBow == 0) and (Axe == 1):\n F1 = 3\n break\n elif(FF == \"Fight\") and (CrossBow == 1) and (Axe == 0):\n F1 = 5\n break\n\n elif(FF == \"Fight\") and (CrossBow == 0) and (Axe == 0):\n print(\"You have no weapon to fight with\")\n\n #WEAPON SELECT\n\nif(FF == \"Fight\") and (CrossBow == 1) and (Axe == 1) and (F1 == 12):\n while True:\n ws = input(\"Which weapon would you like to use?: \")\n WS = ws.title()\n if(WS == \"Axe\"):\n F1 = 3\n break\n elif(WS == \"Crossbow\"):\n F1 = 5\n break\n else:\n print(\"Please input 'Axe' or 'CrossBow'!\")\n \n \n\n\n\n#FIGHT WITCH AXE\nif(F1 == 3):\n while True:\n time.sleep(1)\n Witch = random.randint(60, 100)\n WitchDam = random.randint(50, 90)\n Axedam = random.randint(7, 36)\n chance = random.randint(0, 2)\n if(chance > 0):\n Witch -= Axedam\n print(name.title(), \"hits Witch with\", Axedam,\"damage!\")\n if(Witch <= 0) and (PlyrHP > 0):\n print(\"The Witch thuds to the ground screaming\")\n time.sleep(1)\n print(\"She turns to dust and leaves a scroll, which you pick up\")\n else:\n time.sleep(1)\n chance = random.randint(0, 2)\n if(chance > 0):\n PlyrHP -= WitchDam\n print(\"Witch hits \" + name.title(), \"with\", WitchDam, \"damage!\")\n if(PlyrHP < 0) and (Witch > 0):\n print(\"You fall to the floor, all you can hear is\")\n print(\"The witch cackling\")\n time.sleep(5)\n Menu()\n else:\n continue\n else:\n print(\"Witch misses\", name.title() + \"!\")\n else:\n print(name.title(), \"misses Witch!\")\n time.sleep(1)\n chance = random.randint(0, 2)\n if(chance > 0):\n PlyrHP -= WitchDam\n print(\"Witch hits \" + name.title(), \"with\", WitchDam, \"damage!\")\n if(PlyrHP < 0) and (Witch > 0):\n print(\"You fall to the floor, all you can hear is\")\n print(\"The witch cackling\")\n time.sleep(5)\n Menu()\n else:\n continue\nelif(F1 == 5):\n while True:\n time.sleep(1)\n Witch = random.randint(60, 100)\n WitchDam = random.randint(50, 90)\n Axedam = random.randint(7, 36)\n chance = random.randint(0, 2)\n if(chance > 0):\n Witch -= CrossBowdam\n print(name.title(), \"hits Witch with\", Axedam,\"damage!\")\n if(Witch <= 0) and (PlyrHP > 0):\n print(\"The Witch thuds to the ground screaming\")\n time.sleep(1)\n print(\"She turns to dust and leaves a scroll, which you pick up\")\n else:\n time.sleep(1)\n chance = random.randint(0, 2)\n if(chance > 0):\n PlyrHP -= WitchDam\n print(\"Witch hits \" + name.title(), \"with\", WitchDam, \"damage!\")\n if(PlyrHP < 0) and (Witch > 0):\n print(\"You fall to the floor, all you can hear is\")\n print(\"The witch cackling\")\n time.sleep(5)\n Menu()\n else:\n continue\n else:\n print(\"Witch misses\", name.title() + \"!\")\n else:\n print(name.title(), \"misses Witch!\")\n time.sleep(1)\n chance = random.randint(0, 2)\n if(chance > 0):\n PlyrHP -= WitchDam\n print(\"Witch hits \" + name.title(), \"with\", WitchDam, \"damage!\")\n if(PlyrHP < 0) and (Witch > 0):\n print(\"You fall to the floor, all you can hear is\")\n print(\"The witch cackling\")\n time.sleep(5)\n Menu()\n else:\n continue\n\n \n \n \n \n \n \n \n#West\nif (absolutedir2 == \"West\"):\n print(\"You follow the Western path minding your own business, when a huge eagle swoops down and picks you up\")\n \n print(\"It carries you out of the forest and continues to grab on tightly to your shoulders\")\n print(\"You could try to talk to the eagle, wriggle free, fight it or just enjoy the ride\")\n while True:\n Flightresponse = input(\"What should you do?: \")\n FliRes = Flightresponse.title()\n\n #Communicate\n if(FliRes == \"Communicate\"):\n print(\"Speak to the eagle you immediatley think!\")\n time.sleep(1)\n print(\"You reach into your satchel and pull out your guide on 'How to speak Eagle'\")\n time.sleep(1)\n print(\"You ask it why it has taken you and it looks at you confused\")\n time.sleep(1)\n print(\"The eagle then speaks to you in plain English\")\n time.sleep(1)\n print(\"'What are you babbling on about?' he asks\")\n time.sleep(1)\n print(\"Your jaw drops in amazement.\")\n time.sleep(1)\n print(\"'You can speak English!' You exclaim\")\n time.sleep(1)\n print(\"'Oh not another one' said the eagle flippantly\")\n print(\"'I'll fill you in later!' He says\")\n Eaglecom = 1\n time.sleep(5)\n break\n #Stay\n elif(FliRes == \"Nothing\"):\n print(\"You just enjoy the ride\")\n break\n\n #Wriggle free\n elif(FliRes == \"Wriggle Free\") or (FliRes == \"Struggle\"):\n chance = random.randint(0, 1)\n if(chance == 0):\n print(\"You manage to wriggle free!\")\n time.sleep(1)\n print(\"It doesn't look like you thought this one through, because you plummet to the ground\")\n print(\"You lay there motionless\")\n time.sleep(5)\n #Clear screen\n os.system('clear')\n os.system('cls')\n Menu()\n else:\n print(\"You manage to wriggle free!\")\n print(\"You fall for a little while, plummetting at high speed\")\n print(\"Thankfully the eagle catches you!\")\n #Fight Eagle\n elif(FliRes == \"Fight\") and (CrossBow == 1) and (Axe == 0):\n print(\"You can't fight something that's in such close range with that weapon\")\n elif(FliRes == \"Fight\") and (CrossBow == 0) and (Axe == 1):\n print(\"You swiing the axe at the eagle\")\n time.sleep(1)\n print(\"It doesn't look like you thought this one through, because you plummet to the ground\")\n print(\"You lay there motionless\")\n time.sleep(5)\n #Clear screen\n os.system('clear')\n os.system('cls')\n Menu()\n elif(FliRes == \"Fight\") and (CrossBow == 0) and (Axe == 0):\n print(\"You have no weapon to fight with!\")\n\n\n #RESTART GAME\n elif(FliRes == \"Restart\") or (FliRes == \"Reset\"):\n print(\"Restarting in: \")\n print(\"3\")\n time.sleep(1)\n print(\"2\")\n time.sleep(1)\n print(\"1\")\n time.sleep(1)\n os.system('clear')\n os.system('cls')\n Menu()\n\n\n\n\n #Exit\n elif(FliRes == \"Quit\") or (FliRes == \"Exit\"):\n import logic\n\n \n #Invalid Command\n else:\n print(\"I don't recognise '\" + FliRes + \"'!\")\n print(\"Type in 'Fight', 'Struggle', 'Communicate' or 'Nothing'\")\n\n#Eagle Nest (You can Talk!)\nif(absolutedir2 == \"West\") and (Eaglecom == 0):\n print(\"You arrive at a large mountain and are taken inside of it\")\n print(\"You guess it was made by eagles as you can see a lot of nests inside\")\n time.sleep(1)\n print(\"'Right' Said the Eagle\")\n time.sleep(1)\n print(\"'Oh my' you exclaim, 'You can speak!'\")\n time.sleep(1)\n print(\"'Not another one,' he says, 'never seen a talking egale before?'\")\n time.sleep(1)\n print(\"'Can't say I have!', you say, 'are they common?'\")\n time.sleep(1)\n print(\"'Fairly,' He says, 'But that's not why you're here.'\")\n time.sleep(1)\n print(\"'Well then why you oversized pigeon, who can now apparently talk!'\")\n time.sleep(1)\n print(\"He explains that there is a dark evil in the world and thought that as a great adventurer, that you might be able to help\")\n print(\"You agree to help him and he hands you what looks like a map of the region!\")\n time.sleep(1)\n print(\"He also offers you one of his children to become your companion\")\n while True:\n Eaglename1 = input(\"What is the Eagle called?: \")\n Eagname = Eaglename1.title()\n print(\"The Eagle is called '\" + Eagname +\"'!\")\n confirm1 = input(\"Is this correct?: \")\n confirm2 = confirm1.title()\n if confirm2 == \"Yes\":\n print(\"You take the map and your true quest begins!\")\n break\n \n elif (confirm2 == \"No\"):\n print(\"Name the eagle\")\n\n #RESTART GAME\n elif(confirm2 == \"Restart\") or (confirm2 == \"Reset\"):\n print(\"Restarting in: \")\n print(\"3\")\n time.sleep(1)\n print(\"2\")\n time.sleep(1)\n print(\"1\")\n time.sleep(1)\n os.system('clear')\n os.system('cls')\n Menu()\n\n #Exit\n elif(confirm2 == \"Quit\") or (confirm2 == \"Exit\"):\n import logic\n \n else:\n print(\"Name the eagle\")\n\n #Eagle Nest\nif(absolutedir2 == \"West\") and (Eaglecom == 1):\n time.sleep(1)\n print(\"'That's the place' said the Eagle.\")\n time.sleep(1)\n print(\"He takes you inside a mountian\")\n time.sleep(1)\n print(\"'Wow this place is huge' you say\")\n time.sleep(1)\n print(\"'Ha you could say that' He says, dropping you down gently\")\n time.sleep(1)\n print(\"He explains that there is a dark evil in the world and thought that as a great adventurer, that you might be able to help\")\n time.sleep(1)\n print(\"You agree to help him and he hands you what looks like a map of the region!\")\n time.sleep(1)\n print(\"He also offers you one of his children to become your companion\")\n while True:\n Eaglename1 = input(\"What is the Eagle called?: \")\n Eagname = Eaglename1.title()\n print(\"The Eagle is called '\" + Eagname +\"'!\")\n confirm1 = input(\"Is this correct?: \")\n confirm2 = confirm1.title()\n if confirm2 == \"Yes\":\n print(\"You take the map and your true quest begins!\")\n break\n elif (confirm2 == \"No\"):\n print(\"Name the eagle\")\n #RESTART GAME\n elif(confirm2 == \"Restart\") or (confirm2 == \"Reset\"):\n print(\"Restarting in: \")\n print(\"3\")\n time.sleep(1)\n print(\"2\")\n time.sleep(1)\n print(\"1\")\n time.sleep(1)\n os.system('clear')\n os.system('cls')\n Menu()\n #Exit\n elif(FliRes == \"Quit\") or (FliRes == \"Exit\"):\n import logic\n \n else:\n print(\"Name the eagle\")\n \n \n#East\nif (absolutedir2 == \"East\"):\n print(\"You fall into a trap of quicksand\")\n print(\"You try to struggle out, but it pulls you down\")\n time.sleep(1)\n print(\"You suffocate in the quicksand...\")\n time.sleep(6)\n #Clear screen\n os.system('clear')\n os.system('cls')\n Menu()\n \n#South\nif (absolutedir2 == \"South\"):\n print(\"You take the Southern Path and come across a large tree\")\n print(\"Its like nothing you have ever seen before.\")\n time.sleep(1)\n print(\"'Its a real beauty huh,' Says an old man with a long white beard\")\n time.sleep(1)\n#RESTART GAME\nelif(Confirm2 == \"Restart\") or (Confirm2 == \"Reset\"):\n print(\"Restarting in: \")\n print(\"3\")\n time.sleep(1)\n print(\"2\")\n time.sleep(1)\n print(\"1\")\n time.sleep(1)\n os.system('clear')\n os.system('cls')\n Menu()\n \n \n\n \n \n\n\n \n\n\n\n\n\n \n\n\n\n\n\n#RESTART GAME\nprint(\"That's it for now, More coming soon, so keep posted!\")\nprint(\"Restarting in: \")\nprint(\"3\")\ntime.sleep(1)\nprint(\"2\")\ntime.sleep(1)\nprint(\"1\")\ntime.sleep(1)\nos.system('clear')\nos.system('cls')\nMenu()\n\n\n\n\n \n \n \n \n\n","sub_path":"bin/YourQuest.py","file_name":"YourQuest.py","file_ext":"py","file_size_in_byte":51858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"377644529","text":"from twisted.internet.defer import inlineCallbacks\nfrom twisted.logger import Logger\n\nfrom autobahn.twisted.wamp import ApplicationSession\nfrom autobahn.twisted.wamp import ApplicationRunner\nimport socket\n\nimport psutil\nimport json, ast\n\n\nclass NodeClient(ApplicationSession):\n\n log = Logger()\n host_name = socket.gethostname()\n\n @inlineCallbacks\n def onJoin(self, details):\n self.log.info('joined as Rorender Client on {}'.format(self.host_name))\n yield self.subscribe(self.get_process, u'com.rorender.processes')\n yield self.subscribe(self.on_request_event, u'com.rorender.request')\n\n def on_request_event(self, request_number):\n process_dict = {}\n process_name = ['server.exe', 'vrayspawner2016.exe']\n\n for item in psutil.process_iter():\n for proc in process_name:\n if item.name() == proc:\n process_dict.setdefault(self.host_name, []).append(proc)\n\n self.publish(u'com.rorender.send_process', process_dict)\n\n def get_process(self, result):\n result = json.loads(result)\n self.log.info(result)\n\n\nif __name__ == '__main__':\n runner = ApplicationRunner(url=u\"ws://172.16.0.20:8080/ws\", realm=u\"realm1\")\n runner.run(NodeClient)\n","sub_path":"rorender_/node_client_.py","file_name":"node_client_.py","file_ext":"py","file_size_in_byte":1258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"352403747","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom bayes_tda.data import LabeledPointClouds\n\nclass Circle:\n \n def __init__(self, n_pts = 100, noise_level = 0.1, seed = 0):\n \n np.random.seed(seed)\n \n t = np.linspace(0, 1, n_pts)\n x,y = np.cos(2*np.pi*t), np.sin(2*np.pi*t)\n self.circ = np.array([[h,v] for h,v in zip(x,y)])\n \n noise = np.random.normal(scale = noise_level, size = [n_pts,2])\n self.n_circ = self.circ+noise\n \n label = 1 # dummy label\n data = LabeledPointClouds([self.n_circ], np.array(label))\n self.dgm = data.grouped_dgms[label][0]\n \n def show(self):\n \n fig, ax = plt.subplots(1, 2)\n ax[0].plot(self.circ[:,0],self.circ[:,1], color = 'red') # circle\n ax[0].scatter(self.n_circ[:,0], self.n_circ[:,1], color = 'black') # noisy sample\n ax[0].set_title('Noisy Circle')\n ax[0].set_xlim([-1.5,1.5])\n ax[0].set_ylim([-1.5,1.5])\n ax[0].set_aspect('equal')\n \n \n birth, persistence = self.dgm[:, 0], self.dgm[:, 1]\n ax[1].scatter(birth, persistence, s = 8, color = 'black')\n ax[1].set_title('Noisy Circle PD')\n ax[1].set_xlabel('Birth')\n ax[1].set_ylabel('Persistence')\n ax[1].set_xlim([0, 1.5])\n ax[1].set_ylim([0, 1.5])\n ax[1].set_aspect('equal')\n \n plt.tight_layout()\n plt.show()\n plt.close()","sub_path":"src/build/lib/bayes_tda/demos.py","file_name":"demos.py","file_ext":"py","file_size_in_byte":1463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"206533386","text":"class Solution:\n def sortArrayByParityII(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: List[int]\n \"\"\"\n ret = [0] * len(A)\n index = [0, 1]\n for a in A:\n ret[index[a & 1]] = a\n index[a & 1] += 2\n return ret\n","sub_path":"src/leetcode/P3990.py","file_name":"P3990.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"70363476","text":"import os\nimport json\nimport geopandas as gpd\nimport rasterio\nimport rasterio.plot\nfrom rasterio import features\nfrom rasterio.windows import Window, from_bounds\nfrom rasterio.enums import MergeAlg\nfrom matplotlib import pyplot\nfrom osgeo import gdal\n\n\nclass ProcessRasterLayer(object):\n @staticmethod\n def ReadWindowFromCoordinates(src_fn, coordinates):\n left, bottom, right, top = coordinates\n with rasterio.open(src_fn) as src:\n window = from_bounds(\n left,\n bottom,\n right,\n top,\n transform=src.transform\n )\n w = src.read(\n 1,\n window=window\n )\n return w\n\n @staticmethod\n def plotArray(array):\n pyplot.imshow(array, cmap='pink')\n pyplot.show()\n return\n\n @staticmethod\n def PrintRasterFileStatistics(input_fn):\n with rasterio.open(input_fn) as src:\n # rasterio.plot.show(src)\n print(src.crs)\n print(src.count)\n print(src.width)\n print(src.height)\n print(src.bounds)\n return\n\n @staticmethod\n def GetRasterBoundingBox(input_fn):\n\n with rasterio.open(input_fn) as src:\n bounds = src.bounds\n # (lower_left_x, lower_left_y, upper_right_x, upper_right_y) = bounds\n return bounds\n\n @staticmethod\n def ReadWindowFromOffset(src_fn, coordinates):\n column_offset, row_offset, width, height = coordinates\n with rasterio.open(src_fn) as src:\n w = src.read(\n 1,\n window=Window(column_offset, row_offset, width, height)\n )\n return w\n\n def __init__(self, root_dem_path, root_nuts_path, root_work_path):\n self.root_dem_path = root_dem_path\n self.root_nuts_path = root_nuts_path\n self.root_work_path = root_work_path\n\n os.rmdir(root_work_path)\n os.makedirs(root_work_path)\n\n self.dem_source_fns = []\n for r, d, f in os.walk(root_dem_path):\n for file in f:\n if file[-4:] == '.TIF':\n self.dem_source_fns.append(os.path.join(r, file))\n\n with open('./config/config.json') as json_file:\n self.config = json.load(json_file)\n\n def LoadRasterStatistics(self, input_fn, name):\n if not hasattr(self, 'loaded_files'):\n self.loaded_files = {}\n\n metadata = {}\n with rasterio.open(input_fn) as src:\n metadata['crs'] = src.crs\n metadata['count'] = src.count\n metadata['width'] = src.width\n metadata['height'] = src.height\n metadata['bounds'] = src.bounds\n\n self.loaded_files[name] = metadata\n\n return\n\n def CreateVRT(self, fn, bounds=None, xy_resolution = 100):\n vrt_fn = self.root_work_path + fn + '.vrt'\n vrt_options = gdal.BuildVRTOptions(\n resampleAlg='cubic',\n xRes = xy_resolution,\n yRes = xy_resolution,\n addAlpha=True,\n outputBounds=bounds\n )\n test_vrt = gdal.BuildVRT(\n vrt_fn,\n self.dem_source_fns,\n options=vrt_options\n )\n test_vrt = None\n setattr(self, fn + '_vrt_fn', vrt_fn)\n return\n\n def CreateFullVRT(self):\n self.CreateVRT('dem_full', xy_resolution=1)\n self.LoadRasterStatistics(self.dem_full_vrt_fn, 'dem_full')\n return\n\n def CreateAggregatedVRT(self, bounds=None):\n self.CreateVRT('dem_aggr', bounds = bounds, xy_resolution=self.config['AGGREGATION']['DEM'])\n self.LoadRasterStatistics(self.dem_aggr_vrt_fn, 'dem_aggr')\n return\n\n def CreateTIFFromVRT(self, fn = 'dem_aggr_rst'):\n if hasattr(self, 'dem_aggr_vrt_fn'):\n dem_rst_fn = self.root_work_path + fn + '.tif'\n gdal.Translate(dem_rst_fn, self.dem_aggr_vrt_fn)\n setattr(self, fn + '_fn', dem_rst_fn)\n else:\n raise UserWarning\n return\n\n def LoadRasterMetadata(self, rst_fn):\n rst = rasterio.open(rst_fn)\n meta = rst.meta.copy()\n meta.update(compress='lzw')\n self.raster_metadata = meta\n return\n\n def LoadShapefile(self):\n if not hasattr(self, 'raster_metadata'):\n self.LoadRasterMetadata(self.dem_full_vrt_fn)\n\n shp_fn = self.root_nuts_path + 'ref-nuts-2016-01m.shp/NUTS_RG_01M_2016_3035_LEVL_3.shp'\n\n counties = gpd.read_file(shp_fn)\n counties[\"C\"] = 1\n counties.to_crs(self.raster_metadata[\"crs\"])\n self.nuts_borders = counties\n return\n\n def CreateBorderRaster(self):\n if not hasattr(self, 'nuts_borders'):\n self.LoadShapefile()\n\n out_fn = self.root_dem_path + 'nuts_rst.tif'\n with rasterio.open(out_fn, 'w+', **self.raster_metadata) as out_rst:\n\n out_rst_data = out_rst.read(1)\n shapes = ((geom, value) for geom, value in zip(self.nuts_borders.geometry, self.nuts_borders.C) if features.is_valid_geom(geom))\n\n burned = features.rasterize(\n shapes=shapes,\n fill=0,\n out=out_rst_data,\n transform=out_rst.transform,\n all_touched = True,\n merge_alg = MergeAlg.replace\n )\n out_rst.write_band(1, burned)\n\n shapes = ((geom, value) for geom, value in zip(self.nuts_borders.geometry, self.nuts_borders.C) if features.is_valid_geom(geom))\n\n burned = features.rasterize(\n shapes=shapes,\n fill=0,\n out=out_rst_data,\n transform=out_rst.transform,\n all_touched = True,\n merge_alg = MergeAlg.add\n )\n out_rst.write_band(1, burned)\n\n return\n\n def GetTargetBoundingBox(self):\n if not hasattr(self, 'nuts_borders'):\n self.LoadShapefile()\n bounding_boxes = self.nuts_borders[self.nuts_borders['CNTR_CODE'] == 'HU'].bounds\n bounds = (min(bounding_boxes['minx']), min(bounding_boxes['miny']), max(bounding_boxes['maxx']), max(bounding_boxes['maxy']))\n return bounds\n\n @staticmethod\n def RoundBoundingBox(fr, bb, resolution, pad = 0):\n\n def RoundBound(outer, inner):\n if outer > inner:\n return inner + (outer - inner) % resolution + pad\n else:\n return inner - (inner - outer) % resolution - pad\n\n result_list = []\n for i in range(len(fr)):\n result_list.append(RoundBound(fr[i], bb[i]))\n return tuple(result_list)\n\n def CreateBoundedRaster(self):\n\n self.CreateFullVRT()\n rounded_bounding_box = self.RoundBoundingBox(\n self.loaded_files['dem_full']['bounds'],\n self.GetTargetBoundingBox(),\n self.config['AGGREGATION']['DEM'],\n self.config['AGGREGATION']['DEM'] * (self.config['AGGREGATION']['TARGET_SQ_RESOLUTION'] + 5)\n )\n self.CreateAggregatedVRT(\n bounds=rounded_bounding_box\n )\n self.CreateTIFFromVRT()\n self.LoadRasterMetadata(self.dem_aggr_rst_fn)\n self.CreateBorderRaster()\n return\n","sub_path":"scripts/jobs/process_raster_layer.py","file_name":"process_raster_layer.py","file_ext":"py","file_size_in_byte":7279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"437911794","text":"\"\"\"\nA simple window to be summoned to confirm\nwhether the player wishes to exit, save state to disk...\netc...\n\"\"\"\nfrom ui.ui_abstract.window import Window\nfrom ui.ui_abstract.text import Text\nimport pygame\nfrom color import COLORS\nfrom ui.default_menu import DefaultMenu\nfrom model import game\nfrom save_game import save\n\nclass GameWindowMenu(DefaultMenu):\n def __init__(self,rect):\n super(GameWindowMenu,self).__init__(rect)\n self.close = False # Set true to close this.\n \n font = pygame.font.Font(pygame.font.get_default_font(),32)\n \n \n widget = Text(pygame.Rect(0,0,0,0),font,COLORS[\"white\"],\n \" Options \")\n self.add_option(widget, None)\n \n dy = widget.height\n \n widget = Text(pygame.Rect(0,dy,0,0), font, COLORS[\"light blue\"],\n \" Resume \")\n def resume():\n self.close = True\n self.add_option(widget, resume)\n dy += widget.height\n \n widget = Text(pygame.Rect(0,dy,0,0), font,COLORS[\"light blue\"],\n \" Save \")\n def save_method():\n filename = game.factions[0].name + \"_Turn\" + str(game.turn_count) + \".json\"\n save(filename)\n self.close = True\n event = pygame.event.Event(pygame.USEREVENT+2) # Redraw\n pygame.event.post(event)\n self.add_option(widget, save_method)\n dy += widget.height\n \n widget = Text(pygame.Rect(0,dy,0,0), font, COLORS[\"light blue\"],\n \" Quit \")\n def quit_method():\n event = pygame.event.Event(pygame.QUIT)\n pygame.event.post(event)\n self.add_option(widget, quit_method)\n dy += widget.height\n \n ","sub_path":"duelfieldstars/ui/game_window_menu.py","file_name":"game_window_menu.py","file_ext":"py","file_size_in_byte":1812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"60358652","text":"from train import EngineConsist, DieselEngineUnit\n\n\ndef main(roster_id):\n consist = EngineConsist(roster_id=roster_id,\n id='goliath',\n base_numeric_id=780,\n name='Goliath',\n role='branch_freight',\n power=1450,\n random_reverse=True,\n gen=6,\n intro_date_offset=2, # introduce later than gen epoch by design\n sprites_complete=True)\n\n consist.add_unit(type=DieselEngineUnit,\n weight=74,\n vehicle_length=6,\n spriterow_num=0)\n\n return consist\n","sub_path":"src/vehicles/goliath.py","file_name":"goliath.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"358817159","text":"import sys\nimport os\n\nfrom typing import List, Callable, Union, Any, TypeVar, Tuple, Dict\nfrom torch import Tensor\n\nfrom abc import abstractmethod\n\nimport time\n\nfrom collections import defaultdict\n\nimport numpy as np\n\nimport cv2\n\nimport torch\nfrom torch import nn\nfrom torch import optim\nfrom torch.nn import functional as F\nfrom torch.nn.utils import clip_grad_norm_\nfrom torch.utils.data import Dataset, DataLoader\n\nfrom tensorboardX import SummaryWriter\n\nimport matplotlib.pyplot as plt\n\nfrom .base_model import BaseModel\nfrom csgan.util.scaler import Scaler\nfrom csgan.deep.loss import SiameseLoss, L1SiameseLoss, BinaryEntropyWithLogitsLoss\nfrom csgan.deep.layer import View, Permute\nfrom csgan.deep.grad import grad_scale, grad_reverse\nfrom csgan.deep.resnet import simple_resnet, simple_bottleneck_resnet\nfrom csgan.deep.initialize import weights_init_resnet\nfrom csgan.deep.norm import spectral_norm\n\n\nclass CSDoubleEncoderModel(BaseModel):\n def __init__(self, device,\n content_encoder: nn.Module, style_encoder: nn.Module, decoder: nn.Module,\n content_disc: nn.Module, style_disc: nn.Module,\n source_disc: nn.Module, reference_disc: nn.Module,\n content_seg_disc: nn.Module, style_seg_disc: nn.Module,\n compatible_disc: nn.Module,\n scaler: Scaler = None) -> None:\n super().__init__(device)\n self._content_encoder: nn.Module = content_encoder\n self._style_encoder: nn.Module = style_encoder\n self._decoder: nn.Module = decoder\n\n self._content_disc: nn.Module = content_disc\n self._style_disc: nn.Module = style_disc\n\n self._source_disc: nn.Module = source_disc\n self._reference_disc: nn.Module = reference_disc\n self._content_seg_disc: nn.Module = content_seg_disc\n self._style_seg_disc: nn.Module = style_seg_disc\n\n self._compatible_disc: nn.Module = compatible_disc\n\n if scaler is None:\n scaler = Scaler(1., 0.)\n self._scaler = scaler\n\n self._identity_criterion = nn.L1Loss()\n self._cycle_criterion = nn.L1Loss()\n\n self._content_criterion = nn.BCEWithLogitsLoss()\n self._style_criterion = nn.BCEWithLogitsLoss()\n #self._content_criterion = nn.MSELoss()\n #self._style_criterion = nn.MSELoss()\n\n self._siamese_criterion = SiameseLoss()\n #self._siamese_criterion = L1SiameseLoss()\n\n self._source_criterion = nn.BCEWithLogitsLoss()\n self._reference_criterion = nn.BCEWithLogitsLoss()\n #self._source_criterion = nn.MSELoss()\n #self._reference_criterion = nn.MSELoss()\n\n self._content_seg_criterion = nn.BCELoss()\n self._style_seg_criterion = nn.BCELoss()\n\n self._compatible_criterion = nn.BCEWithLogitsLoss()\n #self._compatible_criterion = nn.MSELoss()\n\n self.to(self._device)\n\n def _update_optimizers(self, loss_dict: Dict[str, Tensor], params: Dict[str, Any],\n global_step: int = 0) -> None:\n pass\n\n def _update_schedulers(self, params: Dict[str, Any], global_step: int = 0) -> None:\n if global_step % params['scheduler_interval'] == 0:\n for scheduler in self._schedulers:\n if scheduler is not None:\n scheduler.step()\n\n if global_step == 1 or global_step % params['scheduler_interval'] == 0:\n assert(self._schedulers[0] is not None)\n lr = self._schedulers[0].get_last_lr()\n print(\"\")\n print(f\"Learning with learning rate: {lr[0]: .8f}.\")\n print(\"\")\n\n def _set_optimizers(self, params: Dict[str, Any]) -> None:\n lr: float = params['learning_rate']\n beta1: float = params['beta1']\n beta2: float = params['beta2']\n weight_decay: float = params['weight_decay']\n gamma: float = params['scheduler_gamma']\n self._optimizers = [optim.Adam(module.parameters(), lr, (beta1, beta2), weight_decay=weight_decay) if\n module is not None else None for\n module in [self._content_encoder, self._style_encoder, self._decoder,\n self._content_disc, self._style_disc,\n self._source_disc, self._reference_disc,\n self._content_seg_disc, self._style_seg_disc,\n self._compatible_disc]]\n self._schedulers = [optim.lr_scheduler.ExponentialLR(optimizer, gamma=gamma) if\n optimizer is not None else None for optimizer in self._optimizers]\n\n @abstractmethod\n def _cs_to_latent(self, c: Tensor, s: Tensor = None) -> Tensor:\n pass\n\n def _predict(self, batch: Dict[str, Tensor], **kwargs) -> Dict[str, Tensor]:\n if 'x' in batch.keys(): # Style-content separate\n xp: Tensor = self._scaler.scaling(batch['x'])\n c: Tensor = self._content_encoder(xp)\n s: Tensor = self._style_encoder(xp)\n z: Tensor = self._cs_to_latent(c, s)\n output: Dict[str, Tensor] = {'z': z, 's': s, 'c': c}\n else:\n assert('x1' in batch.keys() and 'x2' in batch.keys()) # Style change\n xp1: Tensor = self._scaler.scaling(batch['x1'])\n xp2: Tensor = self._scaler.scaling(batch['x2'])\n c1: Tensor = self._content_encoder(xp1)\n s1: Tensor = self._style_encoder(xp1)\n c2: Tensor = self._content_encoder(xp2)\n s2: Tensor = self._style_encoder(xp2)\n z1: Tensor = self._cs_to_latent(c1, s1)\n z2: Tensor = self._cs_to_latent(c2, s2)\n x1_idt: Tensor = self._scaler.unscaling(self._decoder(self._cs_to_latent(c1))) \n x2_idt: Tensor = self._scaler.unscaling(self._decoder(self._cs_to_latent(c2, s2))) \n xp12: Tensor = self._decoder(self._cs_to_latent(c1, s2))\n xp21: Tensor = self._decoder(self._cs_to_latent(c2)) \n x12: Tensor = self._scaler.unscaling(xp12)\n x21: Tensor = self._scaler.unscaling(xp21)\n x1_cycle: Tensor = self._scaler.unscaling(self._decoder(self._cs_to_latent(self._content_encoder(xp12)))) \n x2_cycle: Tensor = self._scaler.unscaling(self._decoder(self._cs_to_latent(self._content_encoder(xp21), s2))) \n output: Dict[str, Tensor] = {'z1': z1, 'z2': z2, 's1': s1, 's2': s2, 'c1': c1, 'c2': c2,\n 'x1_idt': x1_idt, 'x2_idt': x2_idt, 'x12': x12, 'x21': x21,\n 'x1_cycle': x1_cycle, 'x2_cycle': x2_cycle}\n return output\n\n def _post_processing(self, batch: Dict[str, Tensor], params: Dict[str, Any],\n global_step: int = 0) -> None:\n if global_step == 1 or global_step % params['sampling_interval'] == 0:\n self.eval()\n with torch.no_grad():\n output: Dict[str, Tensor] = self._predict(batch)\n result_dir = os.path.join(params['run_dir'], 'results')\n\n n: int = min(8, len(batch['x1']))\n fig = plt.figure(figsize=(20., 20.*float(n)/8.))\n for index in range(n):\n ax = fig.add_subplot(n, 8, 8*index+1)\n ax.imshow(batch['x1'][index, :3].detach().cpu().numpy().transpose(1, 2, 0))\n ax = fig.add_subplot(n, 8, 8*index+2)\n ax.imshow(batch['x2'][index, :3].detach().cpu().numpy().transpose(1, 2, 0))\n ax = fig.add_subplot(n, 8, 8*index+3)\n ax.imshow(output['x1_idt'][index].detach().cpu().numpy().transpose(1, 2, 0))\n ax = fig.add_subplot(n, 8, 8*index+4)\n ax.imshow(output['x2_idt'][index].detach().cpu().numpy().transpose(1, 2, 0))\n ax = fig.add_subplot(n, 8, 8*index+5)\n ax.imshow(output['x12'][index].detach().cpu().numpy().transpose(1, 2, 0))\n ax = fig.add_subplot(n, 8, 8*index+6)\n ax.imshow(output['x21'][index].detach().cpu().numpy().transpose(1, 2, 0))\n ax = fig.add_subplot(n, 8, 8*index+7)\n ax.imshow(output['x1_cycle'][index].detach().cpu().numpy().transpose(1, 2, 0))\n ax = fig.add_subplot(n, 8, 8*index+8)\n ax.imshow(output['x2_cycle'][index].detach().cpu().numpy().transpose(1, 2, 0))\n\n plt.savefig(os.path.join(result_dir, f\"sampling_{global_step}.png\"), dpi=200, bbox_inches='tight')\n plt.close('all')\n\n def forward(self, batch: Dict[str, Tensor], params: Dict[str, Any],\n global_step: int = 0, **kwargs) -> Dict[str, Tensor]:\n output: Dict[str, Tensor] = {}\n return output\n\n def loss_function(self, batch: Dict[str, Tensor], output: Dict[str, Tensor], params: Dict[str, Any],\n global_step: int = 0, **kwargs) -> Dict[str, Tensor]:\n (optimizer_content_encoder, optimizer_style_encoder, optimizer_decoder,\n optimizer_content_disc, optimizer_style_disc,\n optimizer_source_disc, optimizer_reference_disc,\n optimizer_content_seg_disc, optimizer_style_seg_disc,\n optimizer_compatible_disc) = self._optimizers\n\n # 0. Parameters\n lambda_idt: float = params['lambda_identity']\n lambda_cycle: float = params['lambda_cycle']\n lambda_content: float = params['lambda_content']\n lambda_style: float = params['lambda_style']\n lambda_siamese: float = params['lambda_siamese']\n\n lambda_source: float = params['lambda_source']\n lambda_reference: float = params['lambda_reference']\n lambda_content_seg: float = params['lambda_content_seg']\n lambda_style_seg: float = params['lambda_style_seg']\n\n lambda_compatible: float = params['lambda_compatible']\n\n gamma_content: float = params['gamma_content']\n gamma_style: float = params['gamma_style']\n\n gamma_source: float = params['gamma_source']\n gamma_reference: float = params['gamma_reference']\n gamma_content_seg: float = params['gamma_content_seg']\n gamma_style_seg: float = params['gamma_style_seg']\n\n gamma_compatible: float = params['gamma_compatible']\n\n xp1: Tensor = self._scaler.scaling(batch['x1']).detach()\n xp2: Tensor = self._scaler.scaling(batch['x2']).detach()\n\n # 1. Disc Loss\n\n with torch.no_grad():\n c1_detach: Tensor = self._content_encoder(xp1).detach()\n s1_detach: Tensor = self._style_encoder(xp1).detach()\n c2_detach: Tensor = self._content_encoder(xp2).detach()\n s2_detach: Tensor = self._style_encoder(xp2).detach()\n\n # 1-1. Content Disc Loss\n\n loss_content: Tensor = torch.FloatTensor([0.])[0].to(self._device)\n accuracy_content: Tensor = torch.FloatTensor([0.5])[0].to(self._device)\n if lambda_content > 0:\n b1_content: Tensor = self._content_disc(c1_detach)\n b2_content: Tensor = self._content_disc(c2_detach)\n\n loss_content: Tensor = lambda_content * (self._content_criterion(b1_content, torch.ones_like(b1_content)) +\n self._content_criterion(b2_content, torch.zeros_like(b2_content))) / 2.\n if isinstance(self._content_criterion, nn.BCEWithLogitsLoss):\n correct1: Tensor = b1_content >= 0.\n correct2: Tensor = b2_content < 0.\n else:\n assert(isinstance(self._content_criterion, nn.MSELoss))\n correct1: Tensor = b1_content >= 0.5\n correct2: Tensor = b2_content < 0.5\n accuracy_content: Tensor = (correct1.sum() + correct2.sum()) / float(len(b1_content) + len(b2_content))\n\n optimizer_content_disc.zero_grad()\n loss_content.backward()\n optimizer_content_disc.step()\n\n # 1-2. Style Disc Loss\n\n loss_style: Tensor = torch.FloatTensor([0.])[0].to(self._device)\n accuracy_style: Tensor = torch.FloatTensor([0.5])[0].to(self._device)\n if lambda_style > 0:\n b1_style: Tensor = self._style_disc(s1_detach)\n b2_style: Tensor = self._style_disc(s2_detach)\n\n loss_style: Tensor = lambda_style * (self._style_criterion(b1_style, torch.ones_like(b1_style)) +\n self._style_criterion(b2_style, torch.zeros_like(b2_style))) / 2.\n if isinstance(self._style_criterion, nn.BCEWithLogitsLoss):\n correct1: Tensor = b1_style >= 0.\n correct2: Tensor = b2_style < 0.\n else:\n assert(isinstance(self._style_criterion, nn.MSELoss))\n correct1: Tensor = b1_style >= 0.5\n correct2: Tensor = b2_style < 0.5\n accuracy_style: Tensor = (correct1.sum() + correct2.sum()) / float(len(b1_style) + len(b2_style))\n\n optimizer_style_disc.zero_grad()\n loss_style.backward()\n optimizer_style_disc.step()\n\n # 1-3. Source Disc Loss\n\n loss_source: Tensor = torch.FloatTensor([0.])[0].to(self._device)\n accuracy_source: Tensor = torch.FloatTensor([0.5])[0].to(self._device)\n if lambda_source > 0:\n with torch.no_grad():\n xp21_detach: Tensor = self._decoder(self._cs_to_latent(c2_detach)).detach()\n b1_source: Tensor = self._source_disc(xp1)\n b2_source: Tensor = self._source_disc(xp21_detach)\n\n loss_source: Tensor = lambda_source * (self._source_criterion(b1_source, torch.ones_like(b1_source)) +\n self._source_criterion(b2_source, torch.zeros_like(b2_source))) / 2.\n if isinstance(self._source_criterion, nn.BCEWithLogitsLoss):\n correct1: Tensor = b1_source >= 0.\n correct2: Tensor = b2_source < 0.\n else:\n assert(isinstance(self._source_criterion, nn.MSELoss))\n correct1: Tensor = b1_source >= 0.5\n correct2: Tensor = b2_source < 0.5\n accuracy_source: Tensor = (correct1.sum() + correct2.sum()) / float(len(b1_source) + len(b2_source))\n\n optimizer_source_disc.zero_grad()\n loss_source.backward()\n optimizer_source_disc.step()\n\n # 1-4. Reference Disc Loss\n\n loss_reference: Tensor = torch.FloatTensor([0.])[0].to(self._device)\n accuracy_reference: Tensor = torch.FloatTensor([0.5])[0].to(self._device)\n if lambda_reference > 0:\n with torch.no_grad():\n xp12_detach: Tensor = self._decoder(self._cs_to_latent(c1_detach, s2_detach)).detach()\n b1_reference: Tensor = self._reference_disc(xp2)\n b2_reference: Tensor = self._reference_disc(xp12_detach)\n\n loss_reference: Tensor = lambda_reference * (self._reference_criterion(b1_reference, torch.ones_like(b1_reference)) +\n self._reference_criterion(b2_reference, torch.zeros_like(b2_reference))) / 2.\n if isinstance(self._reference_criterion, nn.BCEWithLogitsLoss):\n correct1: Tensor = b1_reference >= 0.\n correct2: Tensor = b2_reference < 0.\n else:\n assert(isinstance(self._reference_criterion, nn.MSELoss))\n correct1: Tensor = b1_reference >= 0.5\n correct2: Tensor = b2_reference < 0.5\n accuracy_reference: Tensor = (correct1.sum() + correct2.sum()) / float(len(b1_reference) + len(b2_reference))\n\n optimizer_reference_disc.zero_grad()\n loss_reference.backward()\n optimizer_reference_disc.step()\n\n # 1-5. Content Seg Loss\n\n seg1: Tensor = batch['seg1'] if 'seg1' in batch else None\n seg2: Tensor = batch['seg2'] if 'seg2' in batch else None\n\n loss_content_seg: Tensor = torch.FloatTensor([0.])[0].to(self._device)\n accuracy_content_seg: Tensor = torch.FloatTensor([0.5])[0].to(self._device)\n if lambda_content_seg > 0:\n b1_content_seg: Tensor = F.softmax(self._content_seg_disc(c1_detach), dim=1)\n b2_content_seg: Tensor = F.softmax(self._content_seg_disc(c2_detach), dim=1)\n b1_content_seg_gather = b1_content_seg.gather(dim=1, index=seg1.unsqueeze(1))\n b2_content_seg_gather = b2_content_seg.gather(dim=1, index=seg2.unsqueeze(1))\n\n loss_content_seg: Tensor = lambda_content_seg * (\n self._content_seg_criterion(b1_content_seg_gather, torch.ones_like(b1_content_seg_gather)) +\n self._content_seg_criterion(b2_content_seg_gather, torch.ones_like(b2_content_seg_gather))) / 2.\n correct1: Tensor = b1_content_seg.argmax(dim=1) == seg1\n correct2: Tensor = b2_content_seg.argmax(dim=1) == seg2\n accuracy_content_seg: Tensor = (correct1.sum() + correct2.sum()) / float(torch.numel(correct1) +\n torch.numel(correct2))\n\n optimizer_content_seg_disc.zero_grad()\n loss_content_seg.backward()\n optimizer_content_seg_disc.step()\n\n # 1-6. Style Seg Loss\n\n loss_style_seg: Tensor = torch.FloatTensor([0.])[0].to(self._device)\n accuracy_style_seg: Tensor = torch.FloatTensor([0.5])[0].to(self._device)\n if lambda_style_seg > 0:\n b1_style_seg: Tensor = F.softmax(self._style_seg_disc(s1_detach), dim=1)\n b2_style_seg: Tensor = F.softmax(self._style_seg_disc(s2_detach), dim=1)\n b1_style_seg_gather = b1_style_seg.gather(dim=1, index=seg1.unsqueeze(1))\n b2_style_seg_gather = b2_style_seg.gather(dim=1, index=seg2.unsqueeze(1))\n\n loss_style_seg: Tensor = lambda_style_seg * (\n self._style_seg_criterion(b1_style_seg_gather, torch.ones_like(b1_style_seg_gather)) +\n self._style_seg_criterion(b2_style_seg_gather, torch.ones_like(b2_style_seg_gather))) / 2.\n correct1: Tensor = b1_style_seg.argmax(dim=1) == seg1\n correct2: Tensor = b2_style_seg.argmax(dim=1) == seg2\n accuracy_style_seg: Tensor = (correct1.sum() + correct2.sum()) / float(torch.numel(correct1) +\n torch.numel(correct2))\n\n optimizer_style_seg_disc.zero_grad()\n loss_style_seg.backward()\n optimizer_style_seg_disc.step()\n\n # 1-7. Compatibility Loss\n\n loss_compatible: Tensor = torch.FloatTensor([0.])[0].to(self._device)\n accuracy_compatible: Tensor = torch.FloatTensor([0.5])[0].to(self._device)\n if lambda_compatible > 0:\n with torch.no_grad():\n z1_detach: Tensor = self._cs_to_latent(c1_detach).detach()\n #z1_detach: Tensor = self._cs_to_latent(c1_detach, s1_detach).detach()\n z2_detach: Tensor = self._cs_to_latent(c2_detach, s2_detach).detach()\n z12_detach: Tensor = self._cs_to_latent(c1_detach, s2_detach).detach()\n z21_detach: Tensor = self._cs_to_latent(c2_detach).detach()\n #z21_detach: Tensor = self._cs_to_latent(c2_detach, s1_detach).detach()\n b1_compatible: Tensor = self._compatible_disc(z1_detach)\n b2_compatible: Tensor = self._compatible_disc(z2_detach)\n b12_compatible: Tensor = self._compatible_disc(z12_detach)\n b21_compatible: Tensor = self._compatible_disc(z21_detach)\n\n loss_compatible: Tensor = lambda_compatible * (\n self._compatible_criterion(b1_compatible, torch.ones_like(b1_compatible)) +\n self._compatible_criterion(b2_compatible, torch.ones_like(b2_compatible)) +\n self._compatible_criterion(b12_compatible, torch.zeros_like(b12_compatible)) +\n self._compatible_criterion(b21_compatible, torch.zeros_like(b21_compatible))) / 4.\n if isinstance(self._compatible_criterion, nn.BCEWithLogitsLoss):\n correct1: Tensor = b1_compatible >= 0.\n correct2: Tensor = b2_compatible >= 0.\n correct12: Tensor = b12_compatible < 0.\n correct21: Tensor = b21_compatible < 0.\n else:\n assert(isinstance(self._compatible_criterion, nn.MSELoss))\n correct1: Tensor = b1_compatible >= 0.5\n correct2: Tensor = b2_compatible >= 0.5\n correct12: Tensor = b12_compatible < 0.5\n correct21: Tensor = b21_compatible < 0.5\n accuracy_compatible: Tensor = (correct1.sum() + correct2.sum() + correct12.sum() + correct21.sum()) / float(\n len(b1_compatible) + len(b2_compatible) + len(b12_compatible) + len(b21_compatible))\n\n optimizer_compatible_disc.zero_grad()\n loss_compatible.backward()\n optimizer_compatible_disc.step()\n\n # 2. Encoder Loss\n\n for module in [self._content_disc, self._style_disc, self._source_disc, self._reference_disc,\n self._content_seg_disc, self._style_seg_disc, self._compatible_disc]:\n if module is not None:\n module.requires_grad_(False)\n\n c1: Tensor = self._content_encoder(xp1)\n s1: Tensor = self._style_encoder(xp1)\n c2: Tensor = self._content_encoder(xp2)\n s2: Tensor = self._style_encoder(xp2)\n\n # 2-1. Content Encoder Loss\n\n loss_content_encoder: Tensor = torch.FloatTensor([0.])[0].to(self._device)\n if lambda_content > 0:\n b2_content: Tensor = self._content_disc(c2)\n loss_content_encoder: Tensor = lambda_content * gamma_content * (\n self._content_criterion(b2_content, torch.ones_like(b2_content)))\n\n # 2-2. Style Encoder Loss\n\n loss_style_encoder: Tensor = torch.FloatTensor([0.])[0].to(self._device)\n if lambda_style > 0:\n b1_style: Tensor = self._style_disc(s1)\n b2_style: Tensor = self._style_disc(s2)\n loss_style_encoder: Tensor = lambda_style * gamma_style * (\n self._style_criterion(b1_style, torch.ones_like(b1_style)) +\n self._style_criterion(b2_style, torch.zeros_like(b2_style))) / 2.\n\n xp21: Tensor = self._decoder(self._cs_to_latent(c2))\n xp12: Tensor = self._decoder(self._cs_to_latent(c1, s2))\n\n # 2-3. Source Encoder Loss\n\n loss_source_encoder: Tensor = torch.FloatTensor([0.])[0].to(self._device)\n if lambda_source > 0:\n #xp21_detach: Tensor = self._decoder(self._cs_to_latent(c2).detach())\n #b2_source: Tensor = self._source_disc(xp21_detach)\n b2_source: Tensor = self._source_disc(xp21)\n\n loss_source_encoder: Tensor = lambda_source * gamma_source * (\n self._source_criterion(b2_source, torch.ones_like(b2_source))) / 2.\n\n # 2-4. Reference Encoder Loss\n\n loss_reference_encoder: Tensor = torch.FloatTensor([0.])[0].to(self._device)\n if lambda_reference > 0:\n #xp12_detach: Tensor = self._decoder(self._cs_to_latent(c1, s2).detach())\n #b2_reference: Tensor = self._reference_disc(xp12_detach)\n b2_reference: Tensor = self._reference_disc(xp12)\n\n loss_reference_encoder: Tensor = lambda_reference * gamma_reference * (\n self._reference_criterion(b2_reference, torch.ones_like(b2_reference))) / 2.\n\n # 2-5. Content Seg Encoder Loss\n\n loss_content_seg_encoder: Tensor = torch.FloatTensor([0.])[0].to(self._device)\n if lambda_content_seg > 0:\n b1_content_seg: Tensor = F.softmax(self._content_seg_disc(c1), dim=1).gather(dim=1, index=seg1.unsqueeze(1))\n b2_content_seg: Tensor = F.softmax(self._content_seg_disc(c2), dim=1).gather(dim=1, index=seg2.unsqueeze(1))\n\n loss_content_seg_encoder: Tensor = lambda_content_seg * gamma_content_seg * (\n self._content_seg_criterion(b1_content_seg, torch.ones_like(b1_content_seg)) +\n self._content_seg_criterion(b2_content_seg, torch.ones_like(b2_content_seg))) / 2.\n\n # 2-6. Style Seg Encoder Loss\n\n loss_style_seg_encoder: Tensor = torch.FloatTensor([0.])[0].to(self._device)\n if lambda_style_seg > 0:\n b1_style_seg: Tensor = F.softmax(self._style_seg_disc(s1), dim=1).gather(dim=1, index=seg1.unsqueeze(1))\n b2_style_seg: Tensor = F.softmax(self._style_seg_disc(s2), dim=1).gather(dim=1, index=seg2.unsqueeze(1))\n\n loss_style_seg_encoder: Tensor = lambda_style_seg * gamma_style_seg * (\n self._style_seg_criterion(b1_style_seg, torch.zeros_like(b1_style_seg)) +\n self._style_seg_criterion(b2_style_seg, torch.zeros_like(b2_style_seg))) / 2.\n\n # 2-7. Compatibility Encoder Loss\n\n loss_compatible_encoder: Tensor = torch.FloatTensor([0.])[0].to(self._device)\n if lambda_compatible > 0:\n z12: Tensor = self._cs_to_latent(c1.detach(), s2)\n #z21_detach: Tensor = self._cs_to_latent(c2_detach).detach()\n z21: Tensor = self._cs_to_latent(c2.detach(), s1)\n b12_compatible: Tensor = self._compatible_disc(z12)\n b21_compatible: Tensor = self._compatible_disc(z21)\n\n loss_compatible_encoder: Tensor = lambda_compatible * gamma_compatible * (\n self._compatible_criterion(b12_compatible, torch.ones_like(b12_compatible)) +\n self._compatible_criterion(b21_compatible, torch.ones_like(b21_compatible))) / 2.\n\n # 2-8. Identity Loss\n\n xp1_idt: Tensor = self._decoder(self._cs_to_latent(c1))\n #xp1_idt2: Tensor = self._decoder(self._cs_to_latent(c1, s1))\n xp2_idt: Tensor = self._decoder(self._cs_to_latent(c2, s2))\n\n loss_idt: Tensor = torch.FloatTensor([0.])[0].to(self._device)\n if lambda_idt > 0:\n loss_idt: Tensor = lambda_idt * (\n self._identity_criterion(xp1_idt, xp1[:, :3]) +\n self._identity_criterion(xp2_idt, xp2[:, :3])) / 2.\n #loss_idt: Tensor = lambda_idt * (\n # (self._identity_criterion(xp1_idt, xp1[:, :3]) +\n # self._identity_criterion(xp1_idt2, xp1[:, :3])) / 2. +\n # self._identity_criterion(xp2_idt, xp2[:, :3])) / 2.\n\n # 2-9. Cycle Loss\n\n loss_cycle: Tensor = torch.FloatTensor([0.])[0].to(self._device)\n if lambda_cycle > 0:\n xp1_cycle: Tensor = self._decoder(self._cs_to_latent(self._content_encoder(xp12)))\n xp2_cycle: Tensor = self._decoder(self._cs_to_latent(self._content_encoder(xp21), s2))\n\n loss_cycle: Tensor = lambda_cycle * (\n self._cycle_criterion(xp1_cycle, xp1[:, :3]) +\n self._cycle_criterion(xp2_cycle, xp2[:, :3])) / 2.\n\n # 2-10. Siamese Loss\n\n loss_siamese: Tensor = torch.FloatTensor([0.])[0].to(self._device)\n if lambda_siamese > 0:\n loss_siamese: Tensor = lambda_siamese * (s1 * s1).mean()\n #loss_siamese: Tensor = lambda_siamese * (s1.abs().mean() + self._siamese_criterion(s2, margin=1.)) / 2.\n #loss_siamese: Tensor = lambda_siamese * ((s1 * s1).mean() + self._siamese_criterion(s2, margin=1.)) / 2.\n norm_s1: Tensor = torch.sqrt((s1 * s1).flatten(start_dim=1).mean(dim=1)).mean()\n norm_s2: Tensor = torch.sqrt((s2 * s2).flatten(start_dim=1).mean(dim=1)).mean()\n\n loss: Tensor = (loss_content_encoder + loss_style_encoder +\n loss_source_encoder + loss_reference_encoder +\n loss_content_seg_encoder + loss_style_seg_encoder +\n loss_compatible_encoder +\n loss_idt + loss_cycle + loss_siamese)\n\n optimizer_content_encoder.zero_grad()\n optimizer_style_encoder.zero_grad()\n optimizer_decoder.zero_grad()\n loss.backward()\n optimizer_content_encoder.step()\n optimizer_style_encoder.step()\n optimizer_decoder.step()\n\n for module in [self._content_disc, self._style_disc, self._source_disc, self._reference_disc,\n self._content_seg_disc, self._style_seg_disc, self._compatible_disc]:\n if module is not None:\n module.requires_grad_(True)\n\n loss_dict: Dict[str, Tensor] = {'loss': loss,\n 'loss_identity': loss_idt, 'loss_cycle': loss_cycle,\n 'loss_content': loss_content, 'accuracy_content': accuracy_content,\n 'loss_style': loss_style, 'accuracy_style': accuracy_style,\n\n 'loss_source': loss_source, 'accuracy_source': accuracy_source,\n 'loss_reference': loss_reference, 'accuracy_reference': accuracy_reference,\n 'loss_content_seg': loss_content_seg, 'accuracy_content_seg': accuracy_content_seg,\n 'loss_style_seg': loss_style_seg, 'accuracy_style_seg': accuracy_style_seg,\n 'loss_compatible': loss_compatible, 'accuracy_compatible': accuracy_compatible,\n\n 'loss_siamese': loss_siamese,\n 'norm_s1': norm_s1, 'norm_s2': norm_s2}\n return loss_dict\n\n\nclass CSDoubleEncoderMnistModel(CSDoubleEncoderModel):\n def __init__(self, device) -> None:\n dimension = 2\n in_channels = 3\n content_dim = 512\n style_dim = content_dim\n latent_dim = content_dim\n #style_dim = 64\n #latent_dim = content_dim + style_dim\n num_blocks = [4]\n planes = [64, 64]\n\n content_encoder: nn.Module = nn.Sequential(\n nn.Conv2d(in_channels, planes[0], kernel_size=5, stride=1, padding=2, bias=False),\n nn.InstanceNorm2d(planes[0], affine=True), nn.LeakyReLU(0.01), nn.MaxPool2d(kernel_size=3, stride=2, padding=1),\n simple_resnet(dimension, num_blocks, planes,\n transpose=False, norm='InstanceNorm', activation='LeakyReLU', pool=False),\n nn.Flatten(start_dim=1), nn.Linear(planes[-1]*7*7, content_dim))\n style_encoder: nn.Module = nn.Sequential(\n nn.Conv2d(in_channels, planes[0], kernel_size=5, stride=1, padding=2, bias=False),\n nn.InstanceNorm2d(planes[0], affine=True), nn.LeakyReLU(0.01), nn.MaxPool2d(kernel_size=3, stride=2, padding=1),\n simple_resnet(dimension, num_blocks, planes,\n transpose=False, norm='InstanceNorm', activation='LeakyReLU', pool=False),\n nn.Flatten(start_dim=1), nn.Linear(planes[-1]*7*7, style_dim))\n decoder: nn.Module = nn.Sequential(\n nn.Linear(latent_dim, planes[-1]*7*7), View((-1, planes[-1], 7, 7)),\n simple_resnet(dimension, num_blocks, planes,\n transpose=True, norm='InstanceNorm', activation='LeakyReLU', pool=False),\n nn.ConvTranspose2d(planes[0], planes[0], kernel_size=3, stride=2, padding=1, output_padding=1, bias=False),\n nn.InstanceNorm2d(planes[0], affine=True), nn.LeakyReLU(0.01),\n nn.ConvTranspose2d(planes[0], in_channels, kernel_size=5, stride=1, padding=2, output_padding=0),\n nn.Tanh())\n\n content_disc: nn.Module = nn.Sequential(\n nn.Linear(content_dim, 256, bias=False), nn.BatchNorm1d(256), nn.LeakyReLU(0.01),\n nn.Linear(256, 64, bias=False), nn.BatchNorm1d(64), nn.LeakyReLU(0.01),\n nn.Linear(64, 1, bias=True))\n style_disc: nn.Module = nn.Sequential(\n #nn.Dropout(p=0.5, inplace=False),\n nn.Linear(style_dim, 256, bias=False), nn.BatchNorm1d(256), nn.LeakyReLU(0.01),\n nn.Linear(256, 64, bias=False), nn.BatchNorm1d(64), nn.LeakyReLU(0.01),\n nn.Linear(64, 1, bias=True))\n scaler: Scaler = Scaler(2., 0.5)\n source_disc: nn.Module = nn.Sequential(\n nn.Conv2d(in_channels, 64, kernel_size=4, stride=2, padding=1, bias=False), nn.InstanceNorm2d(64, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(64, 128, kernel_size=4, stride=2, padding=1, bias=False), nn.InstanceNorm2d(128, affine=True), nn.LeakyReLU(0.01),\n nn.Flatten(), nn.Linear(7*7*128, 1, bias=True))\n reference_disc: nn.Module = nn.Sequential(\n nn.Conv2d(in_channels, 64, kernel_size=4, stride=2, padding=1, bias=False), nn.InstanceNorm2d(64, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(64, 128, kernel_size=4, stride=2, padding=1, bias=False), nn.InstanceNorm2d(128, affine=True), nn.LeakyReLU(0.01),\n nn.Flatten(), nn.Linear(7*7*128, 1, bias=True))\n #source_disc: nn.Module = nn.Sequential(\n # nn.Conv2d(in_channels, 64, kernel_size=3, stride=1, padding=1, bias=False), nn.InstanceNorm2d(64, affine=True), nn.LeakyReLU(0.01),\n # nn.Conv2d(64, 64, kernel_size=4, stride=2, padding=1, bias=False), nn.InstanceNorm2d(64, affine=True), nn.LeakyReLU(0.01),\n # nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1, bias=False), nn.InstanceNorm2d(128, affine=True), nn.LeakyReLU(0.01),\n # nn.Conv2d(128, 128, kernel_size=4, stride=2, padding=1, bias=False), nn.InstanceNorm2d(128, affine=True), nn.LeakyReLU(0.01),\n # nn.Flatten(), nn.Linear(7*7*128, 1, bias=True))\n #reference_disc: nn.Module = nn.Sequential(\n # nn.Conv2d(in_channels, 64, kernel_size=3, stride=1, padding=1, bias=False), nn.InstanceNorm2d(64, affine=True), nn.LeakyReLU(0.01),\n # nn.Conv2d(64, 64, kernel_size=4, stride=2, padding=1, bias=False), nn.InstanceNorm2d(64, affine=True), nn.LeakyReLU(0.01),\n # nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1, bias=False), nn.InstanceNorm2d(128, affine=True), nn.LeakyReLU(0.01),\n # nn.Conv2d(128, 128, kernel_size=4, stride=2, padding=1, bias=False), nn.InstanceNorm2d(128, affine=True), nn.LeakyReLU(0.01),\n # nn.Flatten(), nn.Linear(7*7*128, 1, bias=True))\n content_seg_disc: nn.Module = None\n style_seg_disc: nn.Module = None\n compatible_disc: nn.Module = nn.Sequential(\n nn.Linear(latent_dim, 256, bias=False), nn.BatchNorm1d(256), nn.LeakyReLU(0.01),\n nn.Linear(256, 64, bias=False), nn.BatchNorm1d(64), nn.LeakyReLU(0.01),\n nn.Linear(64, 1, bias=True))\n\n super().__init__(device, content_encoder, style_encoder, decoder, content_disc, style_disc,\n source_disc, reference_disc, content_seg_disc, style_seg_disc, compatible_disc,\n scaler)\n\n self._content_dim = content_dim\n self._style_dim = style_dim\n self.apply(weights_init_resnet)\n\n def _cs_to_latent(self, c: Tensor, s: Tensor = None) -> Tensor:\n if s is None:\n s = torch.zeros((len(c), self._style_dim)).to(self._device)\n z: Tensor = c + s\n #z: Tensor = torch.cat([c, s], dim=1)\n return z\n\n\n#=========================================================================================\nclass Residual(nn.Module):\n def __init__(self, module, residual):\n super().__init__()\n self.module = module\n self.residual = residual\n\n def forward(self, inputs):\n return self.module(inputs) + residual\n\n\nclass CSDoubleEnconderStylingDogModel(CSDoubleEncoderModel):\n def __init__(self, device) -> None:\n dimension = 2\n in_channels = 3\n out_channels = 3\n content_dim = 256\n style_dim = content_dim\n latent_dim = content_dim\n #style_dim = 32\n #latent_dim = content_dim + style_dim\n num_blocks = [4, 4]\n planes = [64, 128, 256]\n\n content_encoder: nn.Module = nn.Sequential(\n nn.Conv2d(in_channels, planes[0], kernel_size=7, stride=1, padding=3, bias=False),\n nn.InstanceNorm2d(planes[0], affine=True), nn.LeakyReLU(0.01), nn.MaxPool2d(kernel_size=3, stride=2, padding=1),\n simple_resnet(dimension, num_blocks, planes,\n transpose=False, norm='InstanceNorm', activation='LeakyReLU', pool=False),\n Permute((0, 2, 3, 1)), nn.Linear(planes[-1], content_dim))\n style_encoder: nn.Module = nn.Sequential(\n nn.Conv2d(in_channels, planes[0], kernel_size=7, stride=1, padding=3, bias=False),\n nn.InstanceNorm2d(planes[0], affine=True), nn.LeakyReLU(0.01), nn.MaxPool2d(kernel_size=3, stride=2, padding=1),\n simple_resnet(dimension, num_blocks, planes,\n transpose=False, norm='InstanceNorm', activation='LeakyReLU', pool=False),\n Permute((0, 2, 3, 1)), nn.Linear(planes[-1], style_dim))\n #nn.Flatten(), nn.Linear(32*32*planes[-1], style_dim))\n decoder: nn.Module = nn.Sequential(\n nn.Linear(latent_dim, planes[-1]), Permute((0, 3, 1, 2)),\n simple_resnet(dimension, num_blocks, planes,\n transpose=True, norm='InstanceNorm', activation='LeakyReLU', pool=False),\n nn.ConvTranspose2d(planes[0], planes[0], kernel_size=3, stride=2, padding=1, output_padding=1, bias=False),\n nn.InstanceNorm2d(planes[0], affine=True), nn.LeakyReLU(0.01),\n nn.ConvTranspose2d(planes[0], out_channels, kernel_size=7, stride=1, padding=3, output_padding=0),\n nn.Tanh())\n content_disc: nn.Module = nn.Sequential(\n Permute((0, 3, 1, 2)),\n nn.Conv2d(content_dim, 256, kernel_size=4, stride=2, padding=1, bias=True), nn.InstanceNorm2d(256, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(256, 256, kernel_size=4, stride=2, padding=1, bias=True), nn.InstanceNorm2d(256, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(256, 256, kernel_size=4, stride=2, padding=1, bias=True), nn.InstanceNorm2d(256, affine=True), nn.LeakyReLU(0.01),\n nn.AdaptiveAvgPool2d((1, 1)), nn.Flatten(), nn.Linear(256, 1, bias=True))\n style_disc: nn.Module = nn.Sequential(\n Permute((0, 3, 1, 2)),\n nn.Conv2d(style_dim, 256, kernel_size=4, stride=2, padding=1, bias=True), nn.InstanceNorm2d(256, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(256, 256, kernel_size=4, stride=2, padding=1, bias=True), nn.InstanceNorm2d(256, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(256, 256, kernel_size=4, stride=2, padding=1, bias=True), nn.InstanceNorm2d(256, affine=True), nn.LeakyReLU(0.01),\n nn.AdaptiveAvgPool2d((1, 1)), nn.Flatten(), nn.Linear(256, 1, bias=True))\n\n source_disc: nn.Module = nn.Sequential(\n nn.Conv2d(in_channels, 64, kernel_size=4, stride=2, padding=1, bias=False), nn.InstanceNorm2d(64, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(64, 64, kernel_size=4, stride=2, padding=1, bias=False), nn.InstanceNorm2d(64, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(64, 128, kernel_size=4, stride=2, padding=1, bias=False), nn.InstanceNorm2d(128, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(128, 128, kernel_size=4, stride=2, padding=1, bias=False), nn.InstanceNorm2d(128, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(128, 256, kernel_size=4, stride=2, padding=1, bias=False), nn.InstanceNorm2d(256, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(256, 256, kernel_size=4, stride=2, padding=1, bias=False), nn.InstanceNorm2d(256, affine=True), nn.LeakyReLU(0.01),\n nn.AdaptiveAvgPool2d((1, 1)), nn.Flatten(), nn.Linear(256, 1, bias=True))\n reference_disc: nn.Module = nn.Sequential(\n nn.Conv2d(in_channels, 64, kernel_size=4, stride=2, padding=1, bias=False), nn.InstanceNorm2d(64, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(64, 64, kernel_size=4, stride=2, padding=1, bias=False), nn.InstanceNorm2d(64, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(64, 128, kernel_size=4, stride=2, padding=1, bias=False), nn.InstanceNorm2d(128, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(128, 128, kernel_size=4, stride=2, padding=1, bias=False), nn.InstanceNorm2d(128, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(128, 256, kernel_size=4, stride=2, padding=1, bias=False), nn.InstanceNorm2d(256, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(256, 256, kernel_size=4, stride=2, padding=1, bias=False), nn.InstanceNorm2d(256, affine=True), nn.LeakyReLU(0.01),\n nn.AdaptiveAvgPool2d((1, 1)), nn.Flatten(), nn.Linear(256, 1, bias=True))\n\n content_seg_disc: nn.Module = nn.Sequential(\n Permute((0, 3, 1, 2)),\n nn.Conv2d(content_dim, 256, kernel_size=3, stride=1, padding=1, bias=True), nn.InstanceNorm2d(256, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1, bias=True), nn.InstanceNorm2d(256, affine=True), nn.LeakyReLU(0.01),\n nn.ConvTranspose2d(256, 128, kernel_size=3, stride=2, padding=1, output_padding=1, bias=True), nn.InstanceNorm2d(128, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(128, 128, kernel_size=3, stride=1, padding=1, bias=True), nn.InstanceNorm2d(128, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(128, 17, kernel_size=7, stride=1, padding=3, bias=True))\n style_seg_disc: nn.Module = nn.Sequential(\n Permute((0, 3, 1, 2)),\n nn.Conv2d(style_dim, 256, kernel_size=3, stride=1, padding=1, bias=True), nn.InstanceNorm2d(256, affine=True), nn.LeakyReLU(0.01),\n #nn.Linear(style_dim, 32*32, bias=True), View((-1, 1, 32, 32)),\n #nn.Conv2d(1, 256, kernel_size=3, stride=1, padding=1, bias=True), nn.InstanceNorm2d(256, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1, bias=True), nn.InstanceNorm2d(256, affine=True), nn.LeakyReLU(0.01),\n nn.ConvTranspose2d(256, 128, kernel_size=3, stride=2, padding=1, output_padding=1, bias=True), nn.InstanceNorm2d(128, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(128, 128, kernel_size=3, stride=1, padding=1, bias=True), nn.InstanceNorm2d(128, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(128, 17, kernel_size=7, stride=1, padding=3, bias=True))\n\n compatible_disc: nn.Module = nn.Sequential(\n Permute((0, 3, 1, 2)),\n nn.Conv2d(style_dim, 256, kernel_size=4, stride=2, padding=1, bias=True), nn.InstanceNorm2d(256, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(256, 256, kernel_size=4, stride=2, padding=1, bias=True), nn.InstanceNorm2d(256, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(256, 256, kernel_size=4, stride=2, padding=1, bias=True), nn.InstanceNorm2d(256, affine=True), nn.LeakyReLU(0.01),\n nn.AdaptiveAvgPool2d((1, 1)), nn.Flatten(), nn.Linear(256, 1, bias=True))\n\n scaler: Scaler = Scaler(2., 0.5)\n\n super().__init__(device, content_encoder, style_encoder, decoder, content_disc, style_disc,\n source_disc, reference_disc, content_seg_disc, style_seg_disc, compatible_disc,\n scaler)\n\n self._content_dim = content_dim\n self._style_dim = style_dim\n self.apply(weights_init_resnet)\n\n def _cs_to_latent(self, c: Tensor, s: Tensor = None) -> Tensor:\n if s is None:\n s = torch.zeros((len(c), 32, 32, self._style_dim)).to(self._device)\n z: Tensor = c + s\n #z: Tensor = torch.cat([c, s.view((-1, 1, 1, self._style_dim)).expand((-1, 32, 32, -1))], dim=-1)\n #z: Tensor = torch.cat([c, s], dim=-1)\n return z\n\n\n#==================================================================================================\n\n\nclass CSDoubleEncoderBeautyganModel(CSDoubleEncoderModel):\n def __init__(self, device) -> None:\n dimension = 2\n in_channels = 3\n out_channels = 3\n content_dim = 256\n style_dim = content_dim\n latent_dim = content_dim\n #style_dim = 32\n #latent_dim = content_dim + style_dim\n num_blocks = [4, 4]\n planes = [64, 128, 256]\n\n content_encoder: nn.Module = nn.Sequential(\n nn.Conv2d(in_channels, planes[0], kernel_size=7, stride=1, padding=3, bias=False),\n nn.InstanceNorm2d(planes[0], affine=True), nn.LeakyReLU(0.01), nn.MaxPool2d(kernel_size=3, stride=2, padding=1),\n simple_resnet(dimension, num_blocks, planes,\n transpose=False, norm='InstanceNorm', activation='LeakyReLU', pool=False),\n Permute((0, 2, 3, 1)), nn.Linear(planes[-1], content_dim))\n style_encoder: nn.Module = nn.Sequential(\n nn.Conv2d(in_channels, planes[0], kernel_size=7, stride=1, padding=3, bias=False),\n nn.InstanceNorm2d(planes[0], affine=True), nn.LeakyReLU(0.01), nn.MaxPool2d(kernel_size=3, stride=2, padding=1),\n simple_resnet(dimension, num_blocks, planes,\n transpose=False, norm='InstanceNorm', activation='LeakyReLU', pool=False),\n Permute((0, 2, 3, 1)), nn.Linear(planes[-1], style_dim))\n #nn.Flatten(), nn.Linear(32*32*planes[-1], style_dim))\n decoder: nn.Module = nn.Sequential(\n nn.Linear(latent_dim, planes[-1]), Permute((0, 3, 1, 2)),\n simple_resnet(dimension, num_blocks, planes,\n transpose=True, norm='InstanceNorm', activation='LeakyReLU', pool=False),\n nn.ConvTranspose2d(planes[0], planes[0], kernel_size=3, stride=2, padding=1, output_padding=1, bias=False),\n nn.InstanceNorm2d(planes[0], affine=True), nn.LeakyReLU(0.01),\n nn.ConvTranspose2d(planes[0], out_channels, kernel_size=7, stride=1, padding=3, output_padding=0),\n nn.Tanh())\n content_disc: nn.Module = nn.Sequential(\n Permute((0, 3, 1, 2)),\n nn.Conv2d(content_dim, 256, kernel_size=4, stride=2, padding=1, bias=True), nn.InstanceNorm2d(256, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(256, 256, kernel_size=4, stride=2, padding=1, bias=True), nn.InstanceNorm2d(256, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(256, 256, kernel_size=4, stride=2, padding=1, bias=True), nn.InstanceNorm2d(256, affine=True), nn.LeakyReLU(0.01),\n nn.AdaptiveAvgPool2d((1, 1)), nn.Flatten(), nn.Linear(256, 1, bias=True))\n style_disc: nn.Module = nn.Sequential(\n Permute((0, 3, 1, 2)),\n nn.Conv2d(style_dim, 256, kernel_size=4, stride=2, padding=1, bias=True), nn.InstanceNorm2d(256, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(256, 256, kernel_size=4, stride=2, padding=1, bias=True), nn.InstanceNorm2d(256, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(256, 256, kernel_size=4, stride=2, padding=1, bias=True), nn.InstanceNorm2d(256, affine=True), nn.LeakyReLU(0.01),\n nn.AdaptiveAvgPool2d((1, 1)), nn.Flatten(), nn.Linear(256, 1, bias=True))\n\n source_disc: nn.Module = nn.Sequential(\n nn.Conv2d(in_channels, 64, kernel_size=4, stride=2, padding=1, bias=False), nn.InstanceNorm2d(64, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(64, 64, kernel_size=4, stride=2, padding=1, bias=False), nn.InstanceNorm2d(64, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(64, 128, kernel_size=4, stride=2, padding=1, bias=False), nn.InstanceNorm2d(128, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(128, 128, kernel_size=4, stride=2, padding=1, bias=False), nn.InstanceNorm2d(128, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(128, 256, kernel_size=4, stride=2, padding=1, bias=False), nn.InstanceNorm2d(256, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(256, 256, kernel_size=4, stride=2, padding=1, bias=False), nn.InstanceNorm2d(256, affine=True), nn.LeakyReLU(0.01),\n nn.AdaptiveAvgPool2d((1, 1)), nn.Flatten(), nn.Linear(256, 1, bias=True))\n reference_disc: nn.Module = nn.Sequential(\n nn.Conv2d(in_channels, 64, kernel_size=4, stride=2, padding=1, bias=False), nn.InstanceNorm2d(64, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(64, 64, kernel_size=4, stride=2, padding=1, bias=False), nn.InstanceNorm2d(64, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(64, 128, kernel_size=4, stride=2, padding=1, bias=False), nn.InstanceNorm2d(128, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(128, 128, kernel_size=4, stride=2, padding=1, bias=False), nn.InstanceNorm2d(128, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(128, 256, kernel_size=4, stride=2, padding=1, bias=False), nn.InstanceNorm2d(256, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(256, 256, kernel_size=4, stride=2, padding=1, bias=False), nn.InstanceNorm2d(256, affine=True), nn.LeakyReLU(0.01),\n nn.AdaptiveAvgPool2d((1, 1)), nn.Flatten(), nn.Linear(256, 1, bias=True))\n\n content_seg_disc: nn.Module = nn.Sequential(\n Permute((0, 3, 1, 2)),\n nn.Conv2d(content_dim, 256, kernel_size=3, stride=1, padding=1, bias=True), nn.InstanceNorm2d(256, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1, bias=True), nn.InstanceNorm2d(256, affine=True), nn.LeakyReLU(0.01),\n nn.ConvTranspose2d(256, 128, kernel_size=3, stride=2, padding=1, output_padding=1, bias=True), nn.InstanceNorm2d(128, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(128, 128, kernel_size=3, stride=1, padding=1, bias=True), nn.InstanceNorm2d(128, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(128, 17, kernel_size=7, stride=1, padding=3, bias=True))\n style_seg_disc: nn.Module = nn.Sequential(\n Permute((0, 3, 1, 2)),\n nn.Conv2d(style_dim, 256, kernel_size=3, stride=1, padding=1, bias=True), nn.InstanceNorm2d(256, affine=True), nn.LeakyReLU(0.01),\n #nn.Linear(style_dim, 32*32, bias=True), View((-1, 1, 32, 32)),\n #nn.Conv2d(1, 256, kernel_size=3, stride=1, padding=1, bias=True), nn.InstanceNorm2d(256, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1, bias=True), nn.InstanceNorm2d(256, affine=True), nn.LeakyReLU(0.01),\n nn.ConvTranspose2d(256, 128, kernel_size=3, stride=2, padding=1, output_padding=1, bias=True), nn.InstanceNorm2d(128, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(128, 128, kernel_size=3, stride=1, padding=1, bias=True), nn.InstanceNorm2d(128, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(128, 17, kernel_size=7, stride=1, padding=3, bias=True))\n\n compatible_disc: nn.Module = nn.Sequential(\n Permute((0, 3, 1, 2)),\n nn.Conv2d(style_dim, 256, kernel_size=4, stride=2, padding=1, bias=True), nn.InstanceNorm2d(256, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(256, 256, kernel_size=4, stride=2, padding=1, bias=True), nn.InstanceNorm2d(256, affine=True), nn.LeakyReLU(0.01),\n nn.Conv2d(256, 256, kernel_size=4, stride=2, padding=1, bias=True), nn.InstanceNorm2d(256, affine=True), nn.LeakyReLU(0.01),\n nn.AdaptiveAvgPool2d((1, 1)), nn.Flatten(), nn.Linear(256, 1, bias=True))\n\n scaler: Scaler = Scaler(2., 0.5)\n\n super().__init__(device, content_encoder, style_encoder, decoder, content_disc, style_disc,\n source_disc, reference_disc, content_seg_disc, style_seg_disc, compatible_disc,\n scaler)\n\n self._content_dim = content_dim\n self._style_dim = style_dim\n self.apply(weights_init_resnet)\n\n def _cs_to_latent(self, c: Tensor, s: Tensor = None) -> Tensor:\n if s is None:\n s = torch.zeros((len(c), 32, 32, self._style_dim)).to(self._device)\n z: Tensor = c + s\n #z: Tensor = torch.cat([c, s.view((-1, 1, 1, self._style_dim)).expand((-1, 32, 32, -1))], dim=-1)\n #z: Tensor = torch.cat([c, s], dim=-1)\n return z\n","sub_path":"csgan/model/cs_double_encoder_model.py","file_name":"cs_double_encoder_model.py","file_ext":"py","file_size_in_byte":52233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"33732467","text":"import _test\nfrom nose.tools import *\nimport operator\nimport tensorflow as tf\nimport numpy as np\n\nimport sparsemax_tf_ops as ops\n\n\ndef sparsemax(z):\n logits = tf.placeholder(tf.float64, name='z')\n sparsemax = ops.sparsemax_op(logits)\n\n with tf.Session() as sess:\n return sparsemax.eval({logits: z})\n\n\ndef sparsemax_loss(z, q):\n logits = tf.placeholder(tf.float64, name='z')\n labels = tf.placeholder(tf.float64, name='q')\n sparsemax = ops.sparsemax_op(logits)\n loss = ops.sparsemax_loss_op(logits, sparsemax, labels)\n\n with tf.Session() as sess:\n return loss.eval({logits: z, labels: q})\n\n\ndef test_constant_add():\n \"\"\"check sparsemax-loss proposition 3\"\"\"\n z = np.random.uniform(low=-3, high=3, size=(100, 10))\n c = np.random.uniform(low=-3, high=3, size=(100, 1))\n q = np.zeros((100, 10))\n q[np.arange(0, 100), np.random.randint(0, 10, size=100)] = 1\n\n np.testing.assert_almost_equal(\n sparsemax_loss(z, q),\n sparsemax_loss(z + c, q)\n )\n\n\ndef test_positive():\n \"\"\"check sparsemax-loss proposition 4\"\"\"\n z = np.random.uniform(low=-3, high=3, size=(100, 10))\n q = np.zeros((100, 10))\n q[np.arange(0, 100), np.random.randint(0, 10, size=100)] = 1\n\n loss = sparsemax_loss(z, q)\n np.testing.utils.assert_array_compare(\n operator.__ge__, loss, np.zeros_like(loss)\n )\n\n\ndef test_zero_loss():\n \"\"\"check sparsemax-loss proposition 5\"\"\"\n # construct z and q, such that z_k >= 1 + max_{j!=k} z_k holds for\n # delta_0 = 1.\n z = np.random.uniform(low=-3, high=3, size=(100, 10))\n z[:, 0] = np.max(z, axis=1) + 1.05\n\n q = np.zeros((100, 10))\n q[:, 0] = 1\n\n np.testing.assert_almost_equal(\n sparsemax_loss(z, q),\n 0\n )\n\n np.testing.assert_almost_equal(\n sparsemax(z),\n q\n )\n\n\ndef test_Rop_estimated():\n \"\"\"check sparsemax-loss Rop, aginst estimated Rop\"\"\"\n z = np.random.uniform(low=-3, high=3, size=(100, 10))\n w = np.random.normal(1)\n q = np.zeros((100, 10))\n q[np.arange(0, 100), np.random.randint(0, 10, size=100)] = 1\n\n logits = tf.placeholder(tf.float64, name='z')\n labels = tf.constant(q, name='q')\n weight = tf.constant(w, name='w', dtype=tf.float64)\n\n sparsemax = ops.sparsemax_op(logits)\n loss = ops.sparsemax_loss_op(logits, sparsemax, labels)\n loss_transform = loss * weight\n\n with tf.Session() as sess:\n # https://www.tensorflow.org/versions/r0.8/api_docs/python/test.html\n analytical, numerical = tf.test.compute_gradient(\n logits, z.shape,\n loss_transform, (100, ),\n x_init_value=z, delta=1e-9\n )\n\n np.testing.assert_almost_equal(\n analytical,\n numerical,\n decimal=4\n )\n\n\ndef test_Rop_numpy():\n \"\"\"check sparsemax-loss Rop, aginst numpy Rop\"\"\"\n z = np.random.uniform(low=-3, high=3, size=(100, 10))\n w = np.random.normal(size=(100, 1))\n q = np.zeros((100, 10))\n q[np.arange(0, 100), np.random.randint(0, 10, size=100)] = 1\n\n logits = tf.placeholder(tf.float64, name='z')\n labels = tf.constant(q, name='q')\n weights = tf.constant(w, name='w')\n\n sparsemax = ops.sparsemax_op(logits)\n loss = ops.sparsemax_loss_op(logits, sparsemax, labels)\n loss_transform = tf.expand_dims(loss, 1) * weights\n\n loss_transform_grad = tf.gradients(loss_transform, [logits])[0]\n\n with tf.Session() as sess:\n # chain rule\n grad = np.ones_like(w) * w\n\n np.testing.assert_array_equal(\n loss_transform_grad.eval({logits: z}),\n grad * (-q + sparsemax.eval({logits: z}))\n )\n","sub_path":"tensorflow_python/test/test_sparsemax_loss.py","file_name":"test_sparsemax_loss.py","file_ext":"py","file_size_in_byte":3635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"26422578","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\nimport struct\ndef isBmp(file):\n\twith open(file,'rb') as fp:\n\t\ta=fp.read(30)\n\t\tstri=struct.unpack(' 0:\n p_size = (h // 2**i, w // 2**i)\n s = F.adaptive_max_pool2d(xc[i], p_size)\n s = self.mfr[i](s)\n s = F.interpolate(s, size=(h, w), mode=\"nearest\")\n else:\n s = self.mfr[i](xc[i])\n out.append(s)\n\n out = self.aggr(torch.cat(out, dim=1))\n out = self.act(out) * x\n return out\n\n\nclass AttBlock(nn.Module):\n def __init__(self, dim, ffn_scale=2.0):\n super().__init__()\n\n self.norm1 = LayerNorm(dim)\n self.norm2 = LayerNorm(dim)\n\n # Multiscale Block\n self.safm = SAFM(dim)\n # Feedforward layer\n self.ccm = CCM(dim, ffn_scale)\n\n def forward(self, x):\n x = self.safm(self.norm1(x)) + x\n x = self.ccm(self.norm2(x)) + x\n return x\n\n\nclass SAFMN(nn.Module):\n def __init__(self, dim=36, n_blocks=8, ffn_scale=2.0, upscaling_factor=4):\n super().__init__()\n self.to_feat = nn.Conv2d(3, dim, 3, 1, 1)\n\n self.feats = nn.Sequential(*[AttBlock(dim, ffn_scale) for _ in range(n_blocks)])\n\n self.to_img = nn.Sequential(\n nn.Conv2d(dim, 3 * upscaling_factor**2, 3, 1, 1),\n nn.PixelShuffle(upscaling_factor),\n )\n\n def forward(self, x):\n x = self.to_feat(x)\n x = self.feats(x) + x\n x = self.to_img(x)\n return x\n","sub_path":"code/arch/safmn_arch.py","file_name":"safmn_arch.py","file_ext":"py","file_size_in_byte":3599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"90453048","text":"\"\"\"Perform an exit code that indicates the last CI workflow status.\"\"\"\nimport sys\n\nimport requests\n\nCI_RUNS_URL = \"https://api.github.com/repos/hadialqattan/pycln/actions/runs\"\n\n\ndef get_ci_runs_dict() -> dict:\n \"\"\"Get CI runs request data as dict object.\n\n :returns: dict of CI runs data.\n \"\"\"\n try:\n res = requests.get(CI_RUNS_URL, timeout=5)\n assert res.status_code == 200, f\"Unexpected status code: {res.status_code}.\"\n return dict(res.json())\n except (requests.ConnectionError, requests.Timeout, AssertionError) as err:\n print(err, file=sys.stderr)\n return {}\n\n\ndef get_last_run_status(data: dict) -> int:\n \"\"\"Get the proper exit code for the last run status.\n\n :param data: data dict to parse.\n :returns: 0 if success otherwise 1.\n \"\"\"\n # No run!\n if not data.get(\"total_count\", 0):\n return 1\n\n for run in data.get(\"workflow_runs\", {}):\n\n # Determine the status.\n is_master_push = (run[\"head_branch\"], run[\"event\"]) == (\"master\", \"push\")\n is_success = (run[\"status\"], run[\"conclusion\"]) == (\"completed\", \"success\")\n is_not_fork = not run[\"repository\"][\"fork\"]\n\n if is_master_push and is_not_fork:\n if is_success:\n # status == success.\n return 0\n else:\n # status in {\"failure\", \"cancelled\"}.\n return 1\n\n # No master branch push run.\n return 1\n\n\ndef main() -> int:\n \"\"\"Return the computed exit code.\"\"\"\n code = get_last_run_status(get_ci_runs_dict())\n status = \"succeed\" if code == 0 else \"failed\"\n print(f\"The last master branch push run has {status}.\")\n return code\n\n\nif __name__ == \"__main__\":\n exit(main()) # pragma: nocover\n","sub_path":".github/ci_status.py","file_name":"ci_status.py","file_ext":"py","file_size_in_byte":1753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"27953004","text":"\"\"\"\n计算两个整数的最大公约数(Greatest Common Divisor)和最小公倍数(Lowest Common Multiple)\n定理:整数a和整数b, 有 a*b=GCD*LCM\n\"\"\"\na=int(input(\"输入数a:\"))\nb=int(input(\"输入数b:\"))\n#----------->我的解法\n#计算最大公约数\nc1=a\ngcd=1\nif a= 50\r\nmask5 = df[\"Jedn\"] == \"PC\"\r\n#mask6 = df[\"MATKL\"] != 27 - a chuj nie wiem jak to w regexie zrobić\r\ndf = df[mask1 & mask2 & mask3 & mask4 & mask5 & mask5]\r\n\r\nTodaysDate = time.strftime(\"%d-%m-%Y\")\r\nfilename = 'Wauki' + TodaysDate\r\n#wyplucie tego do excela\r\ndf.to_excel( filename + '.xlsx' , index = False)\r\n\r\n\r\n","sub_path":"GutPrajs/gut_prajs.py","file_name":"gut_prajs.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"94561479","text":"\"\"\"\n超星汇雅--宁波大学采集任务\nhttp://www.sslibrary.com/\n站点资源数量:800000\n采集要求:全站图书接近800000余本,详情页。需使用特殊代理\n开动时间:20171128\n负责人:venter.zhu\n\"\"\"\n\nimport json\nimport math\nimport os\nimport sys\nimport time\nfrom json.decoder import JSONDecodeError\n\nfrom bs4 import BeautifulSoup\n\nsys.path.insert(0, os.path.dirname(os.getcwd()))\nimport utils\n\n\nclass DownloadSslibrary(utils.Download):\n\n def __init__(self):\n super().__init__()\n self.proxy = {\"http\": \"http://192.168.0.71:8135\"}\n self.isort = int(self.cf.get(\"isort\", \"num\"))\n\n def down_list(self):\n super().down_list()\n uri = \"http://www.sslibrary.com/book/search/do\"\n filepath = self.list_path\n for pages in range(1, 28000):\n filename = filepath + \"\\\\\" + str(pages) + \".json\"\n if os.path.exists(filename):\n continue\n post_data = {\n \"sw\": \"\",\n \"allsw\": \"\",\n \"searchtype\": 1,\n \"classifyId\": \"\",\n \"isort\": \"\",\n \"field\": \"\",\n \"jsonp\": \"\",\n \"showcata\": \"\",\n \"expertsw\": \"(T=**A=*)\",\n \"bCon\": \"\",\n \"page\": pages,\n \"pagesize\": 50,\n \"sign\": \"\",\n \"enc\": \"\"}\n resp = utils.get_html_by_post(uri, data=post_data, proxies=self.proxy)\n if resp:\n try:\n tmp = json.loads(resp.content.decode())\n result_length = len(tmp[\"data\"][\"result\"])\n except (KeyError, JSONDecodeError):\n continue\n if result_length < 1:\n continue\n with open(filename, mode='w', encoding='utf8') as f:\n f.write(resp.content.decode())\n utils.printf(filename)\n time.sleep(2)\n else:\n time.sleep(2)\n\n def down_html(self):\n super().down_html()\n url = \"http://www.sslibrary.com/\"\n feature = \"欢迎用户\"\n i = 0 # 尝试次数\n while i < 3:\n filename = self.html_path + '/html.htm'\n if not os.path.exists(filename):\n resp = utils.get_html(url, feature=feature, proxies=self.proxy, timeout=60)\n if resp:\n with open(filename, mode='w', encoding='utf8') as f:\n f.write(resp.content.decode())\n utils.printf('起始页下载完成...')\n i += 5\n else:\n utils.printf(\"第{}次下载失败...\".format(i + 1))\n i += 1\n else:\n utils.printf('起始页下载完成...')\n i += 5\n\n def down_detail(self):\n super().down_detail()\n utils.printf(\"下载详情页开始...\")\n # self._down_detail(db_tab, self.detail_path, self.isort)\n for _ in range(3): #循环3遍\n self._down_detail('category')\n self._down_detail('category_2')\n self._down_detail('category_3')\n utils.printf(\"下载详情页已经完成,请重复运行几次。之后运行 all_to_one.py\")\n\n def _down_detail(self, db_tab):\n conn = utils.init_db('mysql', 'sslibrary')\n cur = conn.cursor()\n sql = \"select cate,nickname,count from {}\".format(db_tab)\n cur.execute(sql)\n rows = cur.fetchall()\n conn.close()\n update_pages = 60 # 每次更新所需下载列表页的页数\n for cate, nickname, count in rows:\n max_page = math.ceil(count / 50)\n if max_page >= update_pages:\n max_page = update_pages\n for sort in [3, 2, 17, 18]:\n self._down(max_page, cate, self.detail_path, sort)\n\n def down_index(self):\n super().down_index()\n # issort = 1\n utils.printf(\"下载索引页开始...\")\n # 循环 4 遍\n for _ in range(4):\n self._down_index(\"category\", os.path.join(self.index_path, \"category\"), self.isort)\n self._down_index(\"category_2\", os.path.join(self.index_path, \"category_2\"), self.isort)\n self._down_index(\"category_3\", os.path.join(self.index_path, \"category_3\"), self.isort)\n utils.printf(\"下载索引页完成...\")\n\n def _down_index(self, db_tab, path, isort):\n conn = utils.init_db('mysql', 'sslibrary')\n cur = conn.cursor()\n sql = \"select level,level_name from {}\".format(db_tab)\n cur.execute(sql)\n rows = cur.fetchall()\n conn.close()\n for cate, name in rows:\n self._down(2, cate, path, isort)\n\n def _down(self, page, cate, path, isort):\n uri = \"http://www.sslibrary.com/book/search/do\"\n for pages in range(1, page + 1):\n filepath = os.path.join(path, str(isort), cate)\n if not os.path.exists(filepath):\n os.makedirs(filepath)\n filename = filepath + \"\\\\\" + str(pages) + \".json\"\n if os.path.exists(filename):\n continue\n data = {\n \"sw\": \"\",\n \"allsw\": \"\",\n \"searchtype\": \"\",\n \"classifyId\": cate,\n \"isort\": isort,\n \"field\": \"\",\n \"jsonp\": \"\",\n \"showcata\": \"\",\n \"expertsw\": \"\",\n \"bCon\": \"\",\n \"page\": pages,\n \"pagesize\": 50,\n \"sign\": \"\",\n \"enc\": \"\",}\n\n resp = utils.get_html_by_post(uri, data=data, proxies=self.proxy, timeout=60)\n if not resp:\n time.sleep(2)\n continue\n try:\n tmp = json.loads(resp.content.decode())\n result_length = len(tmp[\"data\"][\"result\"])\n except (KeyError, JSONDecodeError):\n time.sleep(2)\n continue\n if result_length < 1:\n time.sleep(2)\n continue\n with open(filename, mode='w', encoding='utf8') as f:\n f.write(resp.content.decode())\n utils.printf(filename)\n time.sleep(2)\n else:\n time.sleep(2)\n\n\nclass ParseSslibrary(utils.Parse):\n\n def parse_html(self):\n utils.printf('解析起始页开始...')\n data1 = []\n data2 = []\n data3 = []\n with open(self.html_path + \"/html.htm\", mode='r', encoding=\"utf-8\") as f:\n text = f.read()\n soup = BeautifulSoup(text, \"html.parser\")\n for atag in soup.select(\".zcl_1 .zcl_text\"):\n js = atag[\"data\"].split(\":\")\n tmp = js[1].split(\",\")[0].strip(\"'\")\n data1.append((tmp, js[-1].strip(\"''}\")))\n for atag in soup.select(\".zcl_2 .zcl_text\"):\n js = atag[\"data\"].split(\":\")\n tmp = js[1].split(\",\")[0].strip(\"'\")\n data2.append((tmp, js[-1].strip(\"''}\")))\n for atag in soup.select(\".zcl_3 .zcl_text\"):\n js = atag[\"data\"].split(\":\")\n tmp = js[1].split(\",\")[0].strip(\"'\")\n data3.append((tmp, js[-1].strip(\"''}\")))\n conn = utils.init_db('mysql', 'sslibrary')\n cursor = conn.cursor()\n cursor.executemany(\"insert into category(level,level_name)Values(%s,%s)\", data1)\n cursor.executemany(\"insert into category_2(level,level_name)Values(%s,%s)\", data2)\n cursor.executemany(\"insert into category_3(level,level_name)Values(%s,%s)\", data3)\n conn.commit()\n conn.close()\n utils.printf('起始页解析完成...')\n\n def parse_index(self):\n utils.printf('解析索引页开始...')\n self._parse_index(\n 'category',\n os.path.join(self.index_path, \"category\"),)\n self._parse_index(\n 'category_2',\n os.path.join(self.index_path, \"category_2\"),)\n self._parse_index(\n 'category_3',\n os.path.join(self.index_path, \"category_3\"),)\n utils.printf('解析索引页完成...')\n\n def _parse_index(self, db_tab, path):\n conn = utils.init_db('mysql', 'sslibrary')\n cur = conn.cursor()\n cate_sql = \"update \" + db_tab + \" set count={} where level='{}'\"\n level_3 = ''\n for _, files in utils.file_list(path):\n # utils.printf(files)\n with open(files, encoding=\"utf8\") as fp:\n js = json.load(fp)\n level_3 = files.split('\\\\')[-2]\n total = js['data']['total']\n utils.printf(level_3, total)\n cur.execute(cate_sql.format(total, level_3))\n conn.commit()\n conn.close()\n\n def parse_detail(self):\n self.hdfs_path = 'chaoxing/sslibrary/big_json'\n utils.printf('解析详情页开始...')\n utils.all_2_one(self.index_path, self.detail_path)\n try:\n utils.upload_file_to_hdfs(self.hdfs_path, self.detail_path)\n except Exception as e:\n utils.printf('上传文件到 hadoop 平台出现错误...,错误代码是:', e)\n # utils.printf('开始执行hadoop命令...')\n # shell = 'java -jar ./target/SimpleAnalysis-venter-0.1.jar -jarName=SimpleAnalysis-venter-0.1.jar -jobStreamName=SslibraryParse -dataAnalysisName=SslibraryParse'\n # utils.hadoop_shell(shell)\n #utils.printf('解析详情页结束...,请执行 Hadoop 命令')\n\n\ndef main():\n down_sslibrary = DownloadSslibrary()\n parse_sslibrary = ParseSslibrary()\n while True:\n for _ in range(3):\n down_sslibrary.down_html()\n parse_sslibrary.parse_html()\n down_sslibrary.down_index()\n parse_sslibrary.parse_index()\n down_sslibrary.down_detail()\n parse_sslibrary.parse_detail()\n utils.printf(\"所有的任务都已经完成...\")\n utils.printf(\"睡眠25天后任务将会唤醒...\")\n time.sleep(3600 * 24 * 25)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/nbu/nbusslibrary.py","file_name":"nbusslibrary.py","file_ext":"py","file_size_in_byte":10095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"286129110","text":"import os\n\nfrom flask import Flask\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef hello2():\n html = \"

Hello {name}!

\" \\\n \"Hostname: {hostname}
\"\n return html\n\n\nif __name__ == \"__main__\":\n app.run(port=5000, host=\"127.0.0.1\", debug=True)\n","sub_path":"src/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"482034924","text":"from django.conf.urls import include, url\nfrom blog import views\n\nurlpatterns=[\n\n url(r'^$',views.index,name='index'),\n url(r'^about2/$',views.index1,name='index1'),\n url(r'^posts/$',views.post_list,name='post_list'),\n url(r'^post/(?P[0-9]+)/$',views.post_detail),\n url(r'^post/new/$',views.post_new,name='post_new'),\n url(r'^post/(?P[0-9]+)/edit/$',views.post_edit,name='post_edit'),\n]\n\n","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"332683402","text":"\"\"\"\nJob to get all general events history.\n\"\"\"\nfrom source.insights_etl.sourcing.nabc_bib import nabc_bib_general_events_all_delta\n\nclass GeneralEventsHistoryJob(nabc_bib_general_events_all_delta.GeneralEventsDeltaJob):\n \"\"\"\n Class that reads event set 3 history. Does the same thing as the event set 3 delta\n job, for the files in the history folder.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Set job name and call super().__init__()\n\n :param obfuscate_sensitive_fields: : do we obfuscate sensitive fields.\n \"\"\"\n job_name = 'nabc_bib_general_events_all_history'\n self.job_delta_component = None\n super(GeneralEventsHistoryJob, self).__init__(job_name)\n\n def input(self, completion_dict):\n \"\"\"\n Get data from files that haven't been processed.\n\n :param completion_dict: \n :return: List of \n \"\"\"\n tracking_attribute = 'start'\n dependent_job = 'nabc_bib_generalevent_history_clean'\n data = self.job_delta_component.get_job_dependency(completion_dict,\n dependent_job, tracking_attribute)\n return [data]\n\n\ndef main():\n \"\"\"\n Main method.\n :return: None\n \"\"\"\n job = GeneralEventsHistoryJob()\n job.run_job()\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"ETL/source/insights_etl/sourcing/nabc_bib/nabc_bib_general_events_all_history.py","file_name":"nabc_bib_general_events_all_history.py","file_ext":"py","file_size_in_byte":1404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"446236652","text":"from datetime import timedelta\nfrom unittest.mock import patch\n\nimport librouteros\nimport pytest\n\nfrom homeassistant import data_entry_flow\nfrom custom_components import mikrotik_router\n\nfrom homeassistant.const import (\n CONF_NAME,\n CONF_HOST,\n CONF_PORT,\n CONF_USERNAME,\n CONF_PASSWORD,\n CONF_SSL,\n)\n\nfrom . import MOCK_DATA\n\nfrom tests.common import MockConfigEntry\n\nDEMO_USER_INPUT = {\n CONF_NAME: \"Home router\",\n CONF_HOST: \"0.0.0.0\",\n CONF_USERNAME: \"username\",\n CONF_PASSWORD: \"password\",\n CONF_PORT: 8278,\n CONF_SSL: True,\n}\n\nDEMO_CONFIG_ENTRY = {\n CONF_NAME: \"Home router\",\n CONF_HOST: \"0.0.0.0\",\n CONF_USERNAME: \"username\",\n CONF_PASSWORD: \"password\",\n CONF_PORT: 8278,\n CONF_SSL: True,\n mikrotik_router.mikrotik_controller.CONF_SCAN_INTERVAL: 60,\n mikrotik_router.mikrotik_controller.CONF_UNIT_OF_MEASUREMENT: \"Mbps\",\n mikrotik_router.mikrotik_controller.CONF_TRACK_IFACE_CLIENTS: True,\n mikrotik_router.mikrotik_controller.CONF_TRACK_HOSTS: True,\n mikrotik_router.mikrotik_controller.CONF_TRACK_HOSTS_TIMEOUT: 180,\n}\n\n\n@pytest.fixture(name=\"api\")\ndef mock_mikrotik_api():\n \"\"\"Mock an api.\"\"\"\n with patch(\"librouteros.connect\"):\n yield\n\n\n@pytest.fixture(name=\"auth_error\")\ndef mock_api_authentication_error():\n \"\"\"Mock an api.\"\"\"\n with patch(\n \"librouteros.connect\",\n side_effect=librouteros.exceptions.TrapError(\"invalid user name or password\"),\n ):\n yield\n\n\n@pytest.fixture(name=\"conn_error\")\ndef mock_api_connection_error():\n \"\"\"Mock an api.\"\"\"\n with patch(\n \"librouteros.connect\", side_effect=librouteros.exceptions.ConnectionClosed\n ):\n yield\n\n\nasync def test_import(hass, api):\n \"\"\"Test import step.\"\"\"\n result = await hass.config_entries.flow.async_init(\n mikrotik_router.DOMAIN, context={\"source\": \"import\"}, data=MOCK_DATA\n )\n\n assert result[\"type\"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY\n assert result[\"title\"] == \"Mikrotik\"\n assert result[\"data\"][CONF_NAME] == \"Mikrotik\"\n assert result[\"data\"][CONF_HOST] == \"10.0.0.1\"\n assert result[\"data\"][CONF_USERNAME] == \"admin\"\n assert result[\"data\"][CONF_PASSWORD] == \"admin\"\n assert result[\"data\"][CONF_PORT] == 0\n assert result[\"data\"][CONF_SSL] is False\n\n\nasync def test_flow_works(hass, api):\n \"\"\"Test config flow.\"\"\"\n\n result = await hass.config_entries.flow.async_init(\n mikrotik_router.DOMAIN, context={\"source\": \"user\"}\n )\n assert result[\"type\"] == data_entry_flow.RESULT_TYPE_FORM\n assert result[\"step_id\"] == \"user\"\n\n result = await hass.config_entries.flow.async_configure(\n result[\"flow_id\"], user_input=DEMO_USER_INPUT\n )\n\n assert result[\"type\"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY\n assert result[\"title\"] == \"Home router\"\n assert result[\"data\"][CONF_NAME] == \"Home router\"\n assert result[\"data\"][CONF_HOST] == \"0.0.0.0\"\n assert result[\"data\"][CONF_USERNAME] == \"username\"\n assert result[\"data\"][CONF_PASSWORD] == \"password\"\n assert result[\"data\"][CONF_PORT] == 8278\n assert result[\"data\"][CONF_SSL] is True\n\n\nasync def test_options(hass):\n \"\"\"Test updating options.\"\"\"\n entry = MockConfigEntry(domain=mikrotik_router.DOMAIN, data=DEMO_CONFIG_ENTRY)\n entry.add_to_hass(hass)\n\n result = await hass.config_entries.options.async_init(entry.entry_id)\n\n assert result[\"type\"] == data_entry_flow.RESULT_TYPE_FORM\n assert result[\"step_id\"] == \"device_tracker\"\n\n result = await hass.config_entries.options.async_configure(\n result[\"flow_id\"],\n user_input={\n mikrotik_router.mikrotik_controller.CONF_SCAN_INTERVAL: 30,\n mikrotik_router.mikrotik_controller.CONF_UNIT_OF_MEASUREMENT: \"Kbps\",\n mikrotik_router.mikrotik_controller.CONF_TRACK_IFACE_CLIENTS: True,\n mikrotik_router.mikrotik_controller.CONF_TRACK_HOSTS: False,\n mikrotik_router.mikrotik_controller.CONF_TRACK_HOSTS_TIMEOUT: 180,\n },\n )\n\n assert result[\"type\"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY\n assert result[\"data\"] == {\n mikrotik_router.mikrotik_controller.CONF_SCAN_INTERVAL: 30,\n mikrotik_router.mikrotik_controller.CONF_UNIT_OF_MEASUREMENT: \"Kbps\",\n mikrotik_router.mikrotik_controller.CONF_TRACK_IFACE_CLIENTS: True,\n mikrotik_router.mikrotik_controller.CONF_TRACK_HOSTS: False,\n mikrotik_router.mikrotik_controller.CONF_TRACK_HOSTS_TIMEOUT: 180,\n }\n\n\nasync def test_name_exists(hass, api):\n \"\"\"Test name already configured.\"\"\"\n\n entry = MockConfigEntry(domain=mikrotik_router.DOMAIN, data=DEMO_CONFIG_ENTRY)\n entry.add_to_hass(hass)\n user_input = DEMO_USER_INPUT.copy()\n user_input[CONF_HOST] = \"0.0.0.1\"\n\n result = await hass.config_entries.flow.async_init(\n mikrotik_router.DOMAIN, context={\"source\": \"user\"}\n )\n result = await hass.config_entries.flow.async_configure(\n result[\"flow_id\"], user_input=user_input\n )\n\n assert result[\"type\"] == \"form\"\n assert result[\"errors\"] == {\"base\": \"name_exists\"}\n\n\nasync def test_connection_error(hass, conn_error):\n \"\"\"Test error when connection is unsuccessful.\"\"\"\n\n result = await hass.config_entries.flow.async_init(\n mikrotik_router.DOMAIN, context={\"source\": \"user\"}\n )\n result = await hass.config_entries.flow.async_configure(\n result[\"flow_id\"], user_input=DEMO_USER_INPUT\n )\n assert result[\"type\"] == data_entry_flow.RESULT_TYPE_FORM\n assert result[\"errors\"] == {\"host\": \"cannot_connect\"}\n\n\nasync def test_wrong_credentials(hass, auth_error):\n \"\"\"Test error when credentials are wrong.\"\"\"\n\n result = await hass.config_entries.flow.async_init(\n mikrotik_router.DOMAIN, context={\"source\": \"user\"}\n )\n result = await hass.config_entries.flow.async_configure(\n result[\"flow_id\"], user_input=DEMO_USER_INPUT\n )\n\n assert result[\"type\"] == data_entry_flow.RESULT_TYPE_FORM\n assert result[\"errors\"] == {\"host\": \"cannot_connect\"}\n","sub_path":"tests/test_config_flow.py","file_name":"test_config_flow.py","file_ext":"py","file_size_in_byte":6024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"136266286","text":"#!/usr/bin/env python3\n\nimport socket\nimport sys\n\nimport interface_pb2\n\nimport argparse\n\nparser = argparse.ArgumentParser(conflict_handler = 'resolve')\n\nparser.add_argument('-h', '--host', default='127.0.0.1')\nparser.add_argument('-p', '--port', default=2015)\n\nargs = parser.parse_args()\n\nPORT = int(args.port)\nHOST = args.host\n\n# -------------------------------------\n\nitem = interface_pb2.Tag()\n\nprint(\"New tag: \\n\")\n\ntext = input(\"Enter text: \")\nwhile not text:\n\ttext = input(\"Try again. Enter text: \")\nitem.text = text\n\nurl = input(\"Enter url (blank for none): \")\nif url != '':\n\titem.url = url\n\nsize = input(\"Enter font size (blank for default): \")\nif size != '':\n\titem.font_size = int(size)\n\nrotation = input(\"Enter rotation angle (blank for none): \")\nif rotation != '':\n\titem.rotation = int(rotation)\n\ncolor = input(\"Enter font color 000000-FFFFFF (blank for 000000): \")\nif color != '':\n\titem.font_color = color.encode(\"utf-8\")\n\n# -------------------------------------\n\nclient = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\ntry:\n\tclient.connect( (HOST, PORT) )\n\nexcept socket.error:\n\tprint( 'Oops: %s\\n' % (socket.error), file=sys.stderr )\n\tsys.exit()\n\ndata_s = item.SerializeToString()\nclient.sendall(data_s)\n\nprint(\"\\nSent tag: \", item.text, file=sys.stderr )\n\ndata_l = []\nwhile True:\n\tbuf = client.recv(1024)\n\tif not buf:\n\t\tbreak\n\tdata_l.append(buf)\n\ndata_r = b\"\".join(data_l)\n\nclient.close()\n\nitems = interface_pb2.TagCloud()\nitems.ParseFromString( data_r )\n\n# -----------------------------------\n\nprint(\"\\nItems\\n\")\n\nfor i in items.tag:\n\tprint( ( \"%s, %s, %i, %i, %s\" % \\\n\t\t(i.text, i.url, i.font_size, i.rotation, i.font_color) ) )\n\n# -----------------------------------\n\nimport wrapper_tag_cloud\n\nFILE = \"tag_cloud.html\"\n\nfout = open(FILE, 'tw+')\nfout.write( wrapper_tag_cloud.wrap(items) )\nfout.close()\n\nprint( (\"\\nCreated: %s\\n\" % FILE), file=sys.stderr )\n","sub_path":"task2-protobuf/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"4664162","text":"# External imports\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n# Set plot params\nplt.rc('font', size=14) # controls default text sizes\nplt.rc('axes', titlesize=14) # fontsize of the axes title\nplt.rc('axes', labelsize=14) # fontsize of the x and y labels\nplt.rc('xtick', labelsize=14) # fontsize of the tick labels\nplt.rc('ytick', labelsize=14) # fontsize of the tick labels\nplt.rc('legend', fontsize=14) # legend fontsize\n\n\n'''\n This script calculates the elastic constant from stress-energy relation \n to files from a LAMMPS calculation.\n\n Devloped by Eric Lindgren, SNUID: 2020-81634\n April 2020\n'''\n\n\ndef extract(f):\n ''' Extracts the quantity of interest from the .fe file f and returns it in a Numoy array '''\n a = []\n with open(f, 'r') as file:\n for row in file:\n if '=' in row:\n a.append( float(row.split('=')[1].rstrip()) )\n a = np.array( a )\n return a\n\n\n# Setup\nT = 0\na0 = 4.21079\nV = a0**3\nd_file = 'd.mgo'\npx_file = 'px.mgo'\npy_file = 'py.mgo'\npz_file = 'pz.mgo'\n\n\n# Extract strain and E values\nd = extract(d_file)\npx = extract(px_file)\npy = extract(py_file)\npz = extract(pz_file)\n\n# Extract strain\ne = (d-a0)/a0\n\n# Convert to numpy arrays and normalize\npx = np.array(px)\npy = np.array(py)\npz = np.array(pz)\nd = np.array(d)\n\n# Perform linefit\nf1 = np.polyfit( d, px, deg=1 ) \nC11 = np.polyfit( d, px, deg=1 )[1] # bar - strain is dimensionless\nC12 = np.polyfit( d, py, deg=1 )[1] #! Shouldn't be 1 here, should be 0 - Something wrong in the definition of np.polyfit\nC13 = np.polyfit( d, pz, deg=1 )[1]\n# Calculate elastic constant\nC11 *= 1e5/1e9 # Convert to GPa\nC12 *= 1e5/1e9\nC13 *= 1e5/1e9\nprint(f'Obtained elastic constant at T={T} K: \\t C11 = {C11:.3f} GPa, C12 = {C12:.3f} GPa, C13 = {C13:.3f} GPa')\n\n\n# Plot stress-strain\nfig, ax = plt.subplots(figsize=(8,6))\nax.plot( e, px, linestyle='-', label=r'$P_{xx}$' )\nax.plot( e, py, linestyle='--', label=r'$P_{yy}$' )\nax.plot( e, pz, linestyle='-.', label=r'$P_{zz}$' )\nax.set_xlabel(r'Strain $e$')\nax.set_ylabel(r'Stress, (bar)')\nax.grid()\nax.legend(loc='best')\nplt.tight_layout()\nplt.savefig('stress_strain.png')\nplt.show()\n","sub_path":"SNU/introduction_to_atomistic_simulations_of_nuclear_materials/exam/problem1/problem1.5/calc_elastic_constant.py","file_name":"calc_elastic_constant.py","file_ext":"py","file_size_in_byte":2186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"398645659","text":"import json\nimport hashlib\nfrom time import time\nfrom urllib.parse import urlparse\n\nimport requests\nimport sys\nfrom flask import Flask, jsonify\nfrom uuid import uuid4\nfrom flask import request\n\nclass BlockChain(object):\n def __init__(self):\n self.current_transactions = []\n self.chain = []\n self.nodes=set()\n # Create the genesis block\n self.new_block(previous_hash=1, proof=100)\n\n def new_block(self,proof,previous_hash):\n block = {\n 'index': len(self.chain)+1,\n 'timestamp': time(),\n 'transactions': self.current_transactions,\n 'proof': proof,\n 'previous_hash': previous_hash or self.hash(self.chain[-1]),\n }\n self.current_transactions=[]\n self.chain.append(block)\n return block\n\n def new_transaction(self, sender, recipient, amount):\n self.current_transactions.append({\n 'sender': sender,\n 'recipient': recipient,\n 'amount': amount\n })\n return self.last_block['index']+1\n #获取上一个区块\n @property\n def last_block(self):\n return self.chain[-1]\n #hash\n @staticmethod\n def hash(block):\n block_string = json.dumps(block, sort_keys=True).encode()\n return hashlib.sha256(block_string).hexdigest()\n #验证\n def proof_of_block(self,last_proof):\n proof=0\n while self.valid_proof(last_proof,proof) is False:\n proof+=1\n return proof\n\n @staticmethod\n def valid_proof(last_proof,proof):\n guess=f'{last_proof}{proof}'.encode()\n guess_hash=hashlib.sha256(guess).hexdigest()\n return guess_hash[:4]=='0000'\n #添加节点\n def regis_nodes(self,address):\n parse_url=urlparse(address)\n self.nodes.add(parse_url.netloc)\n\n #解决冲突\n def resolve_conflicts(self):\n neighbours=self.nodes\n new_chain=None\n max_length=len(self.chain)\n for node in neighbours:\n responose=requests.get('http://'+node+'/chain')\n if responose.status_code==200:\n length=responose.json()['length']\n chain=responose.json()['chain']\n if length>max_length & self.valid_chain(chain):\n max_length=length\n new_chain=chain\n if new_chain:\n self.chain=new_chain\n return True\n return False\n #验证区块��是否有效\n def valid_chain(self, chain):\n last_block=chain[0]\n current_index=1\n while current_index 0:\n self.m = m\n else:\n raise Exception(\"Number of prediction steps ahead must be > 0!\")\n \n # time series length\n self.n = time_series.shape[0]\n\n # latest vector of last d values to the past\n if d > 0:\n self.d = d\n else:\n raise Exception(\"Parameter d (number of last values in state vector, defining dimensionality of the problem) must be > 0!\")\n\n # bandwidth\n if h is not None:\n self.h = h\n else:\n a = 0\n b = (1. / (2 + self.d)) / 2.\n theta = 0\n while theta == 0:\n theta = (b - a) * np.random.random_sample() + a\n self.h = np.power(self.n, -theta)\n\n # distribution in R^d - for now just multivariate Gaussian with zero mean and unit variance\n # self.dist = sts.multivariate_normal(mean = np.zeros(self.d), cov = np.diag(np.ones(self.d)))\n ## denoted K - weight function or kernel function (either bounded support [-1,1] or thin tails)\n # self.dist = None\n self.kernel_func = self._kernel_normal if kernel == 'normal' else self._kernel_epanechnikov\n\n self.x = None\n self.predicted = None\n\n # for debug, not really needed\n self.Xt = None\n self.s0 = None\n self.s1 = None\n self.s2 = None\n self.t0 = None\n self.t1 = None\n\n\n def __repr__(self):\n\n return \"\"\n\n\n def __str__(self):\n\n return \"m step nonlinear predictor based on locally linear regression\"\n\n\n def update_time_series(self, arr):\n \"\"\"\n Updates model time series.\n \"\"\"\n\n if len(arr.shape) == 1:\n self.ts = arr\n self.n = self.ts.shape[0]\n else:\n raise Exception(\"Time series should be 1 dimensional array.\")\n\n\n def _kernel_normal(self, x):\n \"\"\"\n Estimates multivariate Gaussian kernel density in p-dimensions:\n K(x) = (2*pi)^(-p/2) * exp(-|x|^2 / 2)\n where |x| is L2 norm\n \"\"\"\n\n return np.power((2 * np.pi), -self.d / 2.) * np.exp( - (np.linalg.norm(x) * np.linalg.norm(x)) / 2.)\n\n\n def _kernel_epanechnikov(self, x):\n \"\"\"\n Estimates multivariate spherical Epanechnikov kernel density in p-dimensions:\n K(x) = {p(p+2)Gamma(p/2)/(4pi^p/2)} * (1 - |x|^2)+\n where |x| is L2 norm and x+ is x when >0, otherwise 0\n \"\"\"\n\n arg = (1. - np.power(np.linalg.norm(x), 2))\n arg = arg if arg >= 0 else 0\n return (self.d * (self.d + 2.) * gamma(self.d / 2.) / np.power(4 * np.pi, self.d / 2.)) * arg\n\n\n def _kernel_weighting(self, x):\n \"\"\"\n Localization scheme for multivariate nonparametric regression:\n K_H(Xi - x), with K_H(x) = |H|^-1 * K(H^-1 * x)\n where |H| is determinant of bandwidth matrix H\n \"\"\"\n\n h = np.diag(np.ones(self.d) * self.h)\n return (1. / np.linalg.det(h)) * self.kernel_func(np.dot(np.linalg.inv(h), x))\n\n\n def _get_Xt(self, t):\n \"\"\"\n Helper function to obtain X_t as a function of t.\n X_t = (Y_t, Y_t-1, ..., Y_t-d+1)\n \"\"\"\n\n if t < self.n:\n self.Xt = self.ts[t-self.d+1 : t+1][::-1]\n else:\n raise Exception(\"Something went wrong, t must be smaller than n, check t!\")\n\n\n def _Snth(self, x, m, nth = 0):\n \"\"\"\n Helper function S_nth.\n \"\"\"\n\n if x.shape[0] == self.d:\n prefix = 1. / (self.n - m) # at testing time not needed\n\n sum_arg = 0 if nth != 1 else np.zeros((self.d))\n for t in range(self.d - 1, self.n - m):\n self._get_Xt(t)\n if nth == 0:\n sum_arg += self.kernel_func((x - self.Xt) / self.h) # according to paper CHANGE IN ALL\n # sum_arg += self.kernel_func((self.Xt - x) / self.h) # according to book CHANGE IN ALL\n # sum_arg += self._kernel_weighting((self.Xt - x)) # test\n elif nth == 1:\n sum_arg += self.kernel_func((x - self.Xt) / self.h) * (x - self.Xt)\n elif nth == 2:\n sum_arg += self.kernel_func((x - self.Xt) / self.h) * np.dot((x - self.Xt), (x - self.Xt))\n\n # return prefix * sum_arg\n return sum_arg\n\n else:\n raise Exception(\"Something went wrong, the input x must be a vector of dim d!\")\n\n\n def _Tnth(self, x, m, nth = 0, squared = False):\n \"\"\"\n Helper function T_nth.\n \"\"\"\n\n if x.shape[0] == self.d:\n prefix = 1. / (self.n - m) # at testing time not needed\n sq = 2 if squared else 1\n sum_arg = 0 if nth != 1 else np.zeros((self.d))\n for t in range(self.d - 1, self.n - m):\n self._get_Xt(t)\n if nth == 0:\n sum_arg += self.kernel_func((x - self.Xt) / self.h) * np.power(self.ts[t + m], sq)\n elif nth == 1:\n sum_arg += self.kernel_func((x - self.Xt) / self.h) * (x - self.Xt) * np.power(self.ts[t + m], sq)\n\n return sum_arg\n\n else:\n raise Exception(\"Something went wrong, the input x must be a vector of dim d!\")\n\n\n def _get_helper_for_x(self, x, m):\n \"\"\"\n Get values for helper functions.\n \"\"\"\n\n self.t0 = self._Tnth(x, m, nth = 0)\n self.t1 = self._Tnth(x, m, nth = 1)\n self.s0 = self._Snth(x, m, nth = 0)\n self.s1 = self._Snth(x, m, nth = 1)\n self.s2 = self._Snth(x, m, nth = 2)\n\n\n def m_predictor(self, x = None, m = None, append_to_time_series = False):\n \"\"\"\n Return an estimate of m-step predictor f_m(x). (scalar)\n If x is None, predictor will predict next value based on last vector from time series.\n f_m = {T0 - S1*S2^-1*T1} / {S0 - S1*S2^-1*S1 + h^2}\n \"\"\"\n\n if x is None:\n x = self.ts[-self.d : ][::-1]\n self.x = x\n if m is None:\n m = self.m\n self._get_helper_for_x(x, m)\n nominator = self.t0 - (np.dot(self.t1, self.s1) * (1. / self.s2))\n denominator = self.s0 - (np.dot(self.s1, self.s1) * (1. / self.s2))# + np.power(self.h, 2)\n\n predicted = nominator / denominator\n self.predicted = predicted\n\n # update time series for the last value if needed\n ## TODO: make update, not easily append as the m can be > 1\n # if append_to_time_series:\n # self.ts = np.append(self.ts, predicted)\n # self.n = self.ts.shape[0]\n\n return predicted\n\n\n def mLI_predictor(self, x = None, m = None):\n \"\"\"\n Returns an estimate of m-step Lyapunov-like index lambda_m(x). (vector)\n If x is None, predictor will return next value based on last vector from time series.\n \"\"\"\n\n if x is None:\n x = self.ts[-self.d : ][::-1]\n self.x = x\n if m is None:\n m = self.m\n self._get_helper_for_x(x, m)\n nominator = (self.t0 / self.s0) * self.s1 - self.t1\n denominator = self.s2 - np.dot(self.s1, self.s1) / self.s0\n\n predicted = nominator / denominator\n\n return predicted\n\n\n def cond_var_predictor(self, x = None, m = None):\n \"\"\"\n Returns an estimate of conditional variance sigma_m^2 (x).\n If x is None, predictor will return next value based on last vector from time series.\n \"\"\"\n\n if self.predicted is not None:\n if x is None:\n x = self.ts[-self.d : ][::-1]\n self.x = x\n if m is None:\n m = self.m\n self.v0 = self._Tnth(x, m, nth = 0, squared = True)\n self.v1 = self._Tnth(x, m, nth = 1, squared = True)\n self.s0 = self._Snth(x, m, nth = 0)\n self.s1 = self._Snth(x, m, nth = 1)\n self.s2 = self._Snth(x, m, nth = 2)\n\n nominator = self.v0 - (1. / self.s2) * np.dot(self.s1, self.v1)\n denominator = self.s0 - (1. / self.s2) * np.dot(self.s1, self.s1) \n\n xi = nominator / denominator\n\n return xi - np.power(self.predicted, 2)\n else:\n raise Exception(\"To estimate conditional variances, the prediction must be done.\")\n\n\n def mu_predictor(self, x = None):\n \"\"\"\n Returns an estimate of mu_m(x) function, where\n sigma_m^2 = mu_m * simga^2 + o(xi^3)\n If x is None, predictor will return next value based on last vector from time series.\n Working only for d = 1.\n \"\"\"\n\n if self.d == 1:\n\n if x is None:\n x = self.ts[-self.d : ][::-1]\n self.x = x\n sum_arg = 0\n for j in range(1, self.m):\n mult_arg = 1\n for k in range(j, self.m):\n f_k = self.m_predictor(x = x, m = k)\n l1 = self.mLI_predictor(x = f_k, m = 1)\n mult_arg *= l1\n sum_arg += np.power(mult_arg, 2)\n\n return 1. + sum_arg\n\n\n else:\n raise Exception(\"Mu predictor of cond. variance requires d to be 1!\")\n","sub_path":"m_step_nonlinear_prediction.py","file_name":"m_step_nonlinear_prediction.py","file_ext":"py","file_size_in_byte":11370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"479260712","text":"from dns import resolver#dnspython导入方法\r\nimport os\r\nimport httplib2\r\n \r\niplist=[]#定义��名ip列表变量\r\nappdomain = 'www.baidu.com'#定义业务域名\r\n \r\ndef get_iplist(domain=\"\"): ##解析域名为函数,解析成功将追加到iplist\r\n try:\r\n A = resolver.query(domain,'A')#解析A记录类型\r\n except Exception as e:\r\n print('dns resolver error:' + str(e))\r\n return\r\n for i in A:\r\n iplist.append(i)#追加ip到iplist\r\n return True\r\n \r\ndef checkip(ip):#对iplist中IP进行可用检测\r\n checkurl = str(ip) + \":80\"\r\n getcontent=\"\"\r\n httplib2.socket.setdefaulttimeout(5)#定义http连接时间超时为5秒\r\n conn = httplib2.HTTPConnectionWithTimeout(checkurl)#创建http连接对象\r\n \r\n try:\r\n conn.request(\"GET\",\"/\",headers = {\"HOST\": appdomain}) #发起url请求,添加主机头 ##通过构造html头访问目标业务主机\r\n response = conn.getresponse()\r\n getcontent = response.read(15)#获取url前15个字符,做校验用\r\n finally:\r\n if getcontent == b\"\" : ##判断返回字符串是否与预期相同\r\n #监控url一般事先定义好\r\n\r\n print(str(ip)+'[ok]')\r\n else:\r\n print(str(ip)+'[error]')#此处可方警告、邮件、短信等\r\nif __name__ ==\"__main__\":\r\n if get_iplist(appdomain) and len(iplist) > 0:#域名解析正确至少返回一个ip\r\n for ip in iplist:\r\n checkip(ip)\r\n else:\r\n print('dns resolve error')","sub_path":"zuoyee.py","file_name":"zuoyee.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"286049722","text":"import xlearn as xl\n\n\nlr_model = xl.create_linear()\nlr_model.setTrain('./ffm_dataset2.txt')\n\n# using validation to do the prediction on tets data and assess the model's performance\nlr_model.setValidate(\"./ffm_dataset_test2.txt\")\n\nparam = {'task':'binary', 'lr':0.2,\n 'lambda':0.2, 'metric':'f1',\n 'opt':'sgd'}\n\nlr_model.fit(param, \"lr_model.out\")","sub_path":"1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"91798017","text":"import time\n\n\nclass Maze(object):\n \"\"\"A pathfinding problem.\"\"\"\n\n def __init__(self, grid, location):\n \"\"\"Instances differ by their current agent locations.\"\"\"\n self.grid = grid\n self.location = location\n\n def display(self):\n \"\"\"Print the maze, marking the current agent location.\"\"\"\n for r in range(len(self.grid)):\n for c in range(len(self.grid[r])):\n if (r, c) == self.location:\n print('*', end='')\n else:\n print(self.grid[r][c], end='')\n print()\n print()\n\n def moves(self):\n \"\"\"Return a list of possible moves given the current agent location.\"\"\"\n r, c = self.location\n moves = []\n if r > 0 and self.grid[r-1][c] == ' ':\n moves.append((r-1, c))\n if r < len(self.grid)-1 and self.grid[r+1][c] == ' ':\n moves.append((r+1, c))\n if c > 0 and self.grid[r][c-1] == ' ':\n moves.append((r, c-1))\n if c < len(self.grid[r])-1 and self.grid[r][c+1] == ' ':\n moves.append((r, c+1))\n return moves\n\n def neighbor(self, move):\n \"\"\"Return another Maze instance with a move made.\"\"\"\n grid = []\n for r in range(len(self.grid)):\n row = ''\n for c in range(len(self.grid[r])):\n if (r, c) == self.location:\n row += ' '\n elif (r, c) == move:\n row += '*'\n else:\n row += self.grid[r][c]\n grid.append(row)\n return Maze(grid, move)\n\n\nclass Agent(object):\n \"\"\"Knows how to find the exit to a maze with BFS.\"\"\"\n\n @staticmethod\n def reconstruct_path(parent, current):\n \"\"\"Return a list of moves to get from the current location to the start.\"\"\"\n path = []\n while current:\n path.append(current)\n current = parent[current]\n return path\n\n def bfs(self, maze, goal):\n \"\"\"Return an ordered list of moves to get the maze to match the goal.\"\"\"\n frontier = [maze]\n visited = set()\n parent = {maze.location: None}\n\n while frontier:\n current = frontier.pop(0)\n visited.add(current.location)\n if current.location == goal.location:\n print('Found goal!')\n print('Node visited:', len(visited))\n return self.reconstruct_path(parent, current.location)\n\n for move in current.moves():\n if move not in visited:\n frontier.append(current.neighbor(move))\n parent[move] = current.location\n\n return self.reconstruct_path(parent, None)\n\n\ndef main():\n \"\"\"Create a maze, solve it with BFS, and console-animate.\"\"\"\n\n grid = [\"XXXXXXXXXXXXXXXXXXXX\",\n \"X X X X\",\n \"X XXXXX XXXX XXX XXX\",\n \"X X X X X\",\n \"X X XXX XXXXXX X X X\",\n \"X X X X X X\",\n \"X XXX XXXXXX XXXXX X\",\n \"X XXX X X X X\",\n \"X XXX XXXXX\",\n \"XXXXX XXXXXX X\",\n \"X XXX X X X X X\",\n \"XXX XXX X X XXXX X X\",\n \"X X X XX X X X\",\n \"XXXXX XXXX X XXX\",\n \"X X XXX X X\",\n \"X XXXXX X XXXX XXX X\",\n \"X X X X X X\",\n \"X X XXXXXX X XXXXX X\",\n \"X X X\",\n \"XXXXXXXXXXXXXXXXXX X\"]\n\n maze = Maze(grid, (1, 1))\n maze.display()\n\n agent = Agent()\n goal = Maze(grid, (19, 18))\n path = agent.bfs(maze, goal)\n print('Path Length', len(path))\n print()\n while path:\n move = path.pop()\n maze = maze.neighbor(move)\n time.sleep(0.25)\n maze.display()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"BFS/bfs.py","file_name":"bfs.py","file_ext":"py","file_size_in_byte":3890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"387702441","text":"\"\"\"Collection of network layers used in the models.\"\"\"\n\nfrom typing import Any\nimport tensorflow as tf\nfrom tensorflow.keras.layers import Layer, LeakyReLU\nfrom math import pi\n\nclass FourierFeatures(Layer):\n \"\"\"Create fourier features from input.\"\"\"\n\n def __init__(self, n_freq_bands: int) -> None:\n super().__init__()\n self.feature_maps = []\n self.feature_maps.append(lambda x: x)\n\n freq_bands = 2 ** tf.range(n_freq_bands, dtype=tf.dtypes.float32)\n\n for freq in freq_bands:\n self.feature_maps.append(lambda x, freq=freq: tf.math.sin(freq * x))\n self.feature_maps.append(lambda x, freq=freq: tf.math.cos(freq * x))\n\n def call(self, inputs: tf.Tensor) -> tf.Tensor:\n return tf.concat([feature_map(inputs) for feature_map in self.feature_maps], -1)\n\nclass IntegratedPositionalEncoding(Layer):\n \"\"\"Integrated Positional Encoding.\"\"\"\n\n def __init__(self, n_freq_bands: int) -> None:\n super().__init__()\n\n self.n_freq_bands = n_freq_bands\n self.freq_bands = 2 ** tf.range(n_freq_bands, dtype=tf.dtypes.float32)\n\n def call(self, inputs: tf.Tensor) -> tf.Tensor:\n y = tf.reshape(inputs[..., None, :3] * self.freq_bands[:, None], (-1, 3 * self.n_freq_bands))\n y_var = tf.reshape(inputs[..., None, 3:] * self.freq_bands[:, None]**2, (-1, 3 * self.n_freq_bands))\n\n return self.expected_sin(tf.concat([y, y + .5 * pi], axis=-1), tf.concat([y_var, y_var], axis=-1))\n\n def expected_sin(self, x, x_var):\n return tf.sin(x) * tf.exp(-.5 * x_var)","sub_path":"network/layer.py","file_name":"layer.py","file_ext":"py","file_size_in_byte":1564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"599465985","text":"# -*- coding: utf-8 -*-\n\nimport asyncio\nimport ctypes\nimport os\nimport shlex\nimport struct\nimport sys\n\nfrom . import utils\n\n\nclass Shell(object):\n def __init__(self, workspace, size, proc, stdin, stdout, stderr, fd):\n self._workspace = workspace\n self._size = None\n self._proc = proc\n self._fd = fd\n self._stdin = stdin\n self._stdout = stdout\n self._stderr = stderr\n self.resize(size)\n\n @property\n def process(self):\n return self._proc\n\n @property\n def stdin(self):\n return self._stdin\n\n @property\n def stdout(self):\n return self._stdout\n\n @property\n def stderr(self):\n return self._stderr\n\n @classmethod\n async def create(cls, workspace, size=None):\n size = size or (80, 23)\n if sys.platform == \"win32\":\n if hasattr(ctypes.windll.kernel32, \"CreatePseudoConsole\"):\n cmd = (\n \"conhost.exe\",\n \"--headless\",\n \"--width\",\n str(size[0]),\n \"--height\",\n str(size[1]),\n \"--\",\n \"cmd.exe\",\n )\n else:\n cmd = (\"cmd.exe\",)\n proc = await asyncio.create_subprocess_exec(\n *cmd,\n cwd=workspace,\n stdin=asyncio.subprocess.PIPE,\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.PIPE,\n close_fds=False\n )\n stdin = proc.stdin\n stdout = proc.stdout\n stderr = proc.stderr\n fd = None\n else:\n import pty\n\n cmdline = list(shlex.split(os.environ.get(\"SHELL\") or \"bash\"))\n exe = cmdline[0]\n if exe[0] != \"/\":\n for it in os.environ[\"PATH\"].split(\":\"):\n path = os.path.join(it, exe)\n if os.path.isfile(path):\n exe = path\n break\n else:\n exe = \"/bin/sh\"\n\n utils.logger.info(\"[%s] Create shell %s\" % (cls.__name__, cmdline))\n pid, fd = pty.fork()\n if pid == 0:\n # child process\n sys.stdout.flush()\n os.chdir(workspace)\n try:\n os.execve(exe, cmdline, os.environ)\n except Exception as e:\n sys.stderr.write(str(e))\n else:\n proc = utils.Process(pid)\n stdin = utils.AsyncFileDescriptor(fd)\n stdout = utils.AsyncFileDescriptor(fd)\n stderr = None\n\n return cls(workspace, size, proc, stdin, stdout, stderr, fd)\n\n def write(self, buffer):\n self._stdin.write(buffer)\n\n def resize(self, size):\n if sys.platform == \"win32\":\n pass\n else:\n import fcntl\n import termios\n\n winsize = struct.pack(\"HHHH\", size[1], size[0], 0, 0)\n fcntl.ioctl(self._fd, termios.TIOCSWINSZ, winsize)\n self._size = size\n return True\n\n def exit(self):\n self._stdin.write(b\"exit\\n\")\n utils.logger.info(\"[%s] Shell exit\" % self.__class__.__name__)\n","sub_path":"wsterm/shell.py","file_name":"shell.py","file_ext":"py","file_size_in_byte":3312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"169365482","text":"import boto3\nimport urllib\nimport tempfile\nimport shutil\nimport os\nfrom .base_storage import BaseStorage\nfrom .base_file import BaseFile\nfrom . import logger\n\n\nimport click\nAWS_CLI_PARAMETERS = [\n click.Option(\n ['--aws-profile'], required=False, default=None,\n help='Select an AWS profile to use, if interacting with AWS S3 storage'\n ),\n click.Option(\n ['--aws-region'], required=False, default=None, type=str,\n help='Select an AWS region to use, if interacting with AWS S3 storage'\n ),\n]\n\n\nclass AmazonS3Storage(BaseStorage):\n\n # Class methods\n def split(path):\n if path.startswith('s3://'):\n path_parts = urllib.parse.urlparse(path)\n if not (path_parts.scheme == 's3'):\n raise ValueError(f'Path must be an s3 format URL [s3://mybucket/path/to/file.jpg], received {path}')\n return path_parts.netloc, path_parts.path.lstrip('/')\n else:\n raise ValueError(f'Path must be an s3 format URL [s3://mybucket/path/to/file.jpg], received {path}')\n\n def __init__(self, **config):\n profile_name = None\n region_name = None\n if 'aws_profile' in config.keys():\n profile_name = config['aws_profile']\n if 'aws_region' in config.keys():\n region_name = config['aws_region']\n self.session = boto3.session.Session(\n profile_name=profile_name, region_name=region_name)\n\n def is_file(self, path):\n raise NotImplementedError('Not implemented.')\n # return os.path.isfile(path)\n\n def is_dir(self, path):\n raise NotImplementedError('Not implemented.')\n # return os.path.isdir(path)\n\n def mkdir(self, path):\n logger.info(\"Creating directory {}\".format(path))\n # return os.makedirs(path)\n raise NotImplementedError('Not implemented.')\n\n def list_dir(self, path):\n # return os.listdir(path)\n s3 = self.session.client('s3')\n pag = s3.get_paginator('list_objects_v2')\n for page in pag.paginate(Bucket=path.bucket, Prefix=path.dirname(), Delimiter='/'):\n for object in page.get('Contents', []):\n yield AmazonS3File(storage=self, bucket=bucket, path=object['Key'], props=object)\n\n def rmdir(self, path):\n logger.info(\"Removing empty directory {}\".format(path))\n # return os.rmdir(path)\n raise NotImplementedError('Not implemented.')\n\n def walk(self, path):\n # Iterate over files and folders\n # return os.walk(path)\n s3 = self.session.client('s3')\n if isinstance(path, AmazonS3File):\n bucket = path.bucket\n bucket_path = path.path\n else:\n bucket, bucket_path = AmazonS3Storage.split(path)\n def yield_dirs():\n pag = s3.get_paginator('list_objects_v2')\n for page in pag.paginate(Bucket=bucket, Prefix=bucket_path, Delimiter='/'):\n for prefix in page.get('CommonPrefixes', []):\n yield prefix['Prefix']\n def yield_files():\n pag = s3.get_paginator('list_objects_v2')\n for page in pag.paginate(Bucket=bucket, Prefix=bucket_path, Delimiter='/'):\n for object in page.get('Contents', []):\n yield AmazonS3File(storage=self, bucket=bucket, path=object['Key'], props=object)\n # Yield current directory\n yield (bucket_path, yield_dirs(), yield_files())\n\n # Recurse\n pag = s3.get_paginator('list_objects_v2')\n for page in pag.paginate(Bucket=bucket, Prefix=bucket_path, Delimiter='/'):\n for prefix in page.get('CommonPrefixes', []):\n full_dir = f\"s3://{bucket}/{prefix['Prefix']}\"\n # Yield recursively\n yield from self.walk(full_dir)\n\n def join(self, base, path, as_object=False):\n # Join two file paths\n if base.endswith('/'):\n new_path = base + path\n else:\n new_path = base + '/' + path\n if as_object:\n return self.file(new_path)\n else:\n return new_path\n\n def file(self, path):\n # Return a new file object from the given path\n return AmazonS3File(storage=self, path=path)\n\n\nclass AmazonS3File(BaseFile):\n def __init__(self, storage=None, bucket=None, path=None, props=None):\n self.storage = storage\n self._local_path = \"\"\n if bucket and path:\n self.bucket = bucket\n self.path = path\n elif path:\n self.bucket, self.path = AmazonS3Storage.split(path)\n else:\n raise ValueError('Must supply either bucket and path, or path in s3 url format.')\n self.props = props\n\n def copy(self, destination):\n # Move the file from this path to the destination\n logger.info(f'Copy file {self} to {destination}')\n if isinstance(destination, str):\n dest = destination\n elif destination.__class__ == BaseFile:\n dest = destination.path\n else:\n raise NotImplementedError('Copy to other storage provider not implemented yet.')\n if dest.startswith('s3://'):\n # S3 to S3 copy\n raise NotImplementedError('Not implemented yet sorry')\n else:\n s3 = self.storage.session.client('s3')\n s3.download_file(Bucket=self.bucket, Key=self.path, Filename=dest)\n\n def local_path(self):\n # Return a file path on the local system where data can be acessed - warning\n # downloads the file to local storage if not currently here.\n if not self._local_path:\n self._local_path = tempfile.mktemp()\n self.copy(self._local_path)\n return self._local_path\n\n def __str__(self):\n return f's3://{self.bucket}/{self.path}'\n\n def move(self, destination):\n self.copy(destination)\n self.delete(reason='File moved.')\n\n def delete(self, reason=\"(none given)\"):\n logger.info(\"Deleting file {}, reason - {}\".format(\n self.path, reason\n ))\n s3 = self.storage.session.client('s3')\n s3.delete_object(Bucket=self.bucket, Key=self.path)\n if self._local_path:\n logger.debug(f'Clean up local copy {self._local_path}')\n os.remove(self._local_path)\n self._local_path = ''\n","sub_path":"organized/storage/amazon_s3_storage.py","file_name":"amazon_s3_storage.py","file_ext":"py","file_size_in_byte":6352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"561293455","text":"from django.utils import timezone\n\nfrom app.models import Appointment, Girl\nfrom app.notifier import NotifierView\nfrom app.utils.constants import EXPECTED, ATTENDED, MISSED\n\n\ndef notifier_appointment_reminder_cron_job():\n \"\"\"\n Appointment reminder. Notifies the VHT, midwife and girl about expected and missed appointments\n \"\"\"\n notifier = NotifierView()\n notifier.send_appointment_three_days_before_date()\n notifier.send_appointment_one_day_after_date()\n notifier.send_appointment_on_actual_day()\n\n\ndef notifier_daily_usage_reminder_cron_job():\n \"\"\"\n Sends out daily FCM notification reminder to use the GetIn mobile app\n \"\"\"\n notifier = NotifierView()\n notifier.send_daily_usage_reminder()\n\n\ndef transition_expected_appointments():\n \"\"\"\n Updates missed appointments that have EXPECTED status to MISSED status.\n This transition is made if a new appointment is not generated 24 hrs after the appointment date\n \"\"\"\n try:\n print('update previous appointment status')\n\n girls = Girl.objects.all()\n\n for girl in girls:\n girl_previous_appointments = Appointment.objects.filter(girl__id=girl.id).order_by(\"id\")\n if girl_previous_appointments.count() <= 1:\n print('Girl has less than 1 appointment')\n continue\n\n for girl_previous_appointment in girl_previous_appointments:\n # previous appointment must have been attended atleast within 24 hours margin on its deadline\n current_time_24_hours_ahead = timezone.now() + timezone.timedelta(hours=24)\n\n if girl_previous_appointment.status == EXPECTED \\\n and girl_previous_appointment.date < current_time_24_hours_ahead:\n girl_previous_appointment.status = MISSED\n girl_previous_appointment.save(update_fields=['status'])\n except Exception as e:\n print(e)\n","sub_path":"app/cron.py","file_name":"cron.py","file_ext":"py","file_size_in_byte":1943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"484846964","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom .models import Photo, pillinformation\nfrom django.views.generic.edit import CreateView, UpdateView, DeleteView\nfrom django.shortcuts import redirect\nfrom pill_detection import pilldetect\n\n\n\n# Create your views here.\n\ndef base(request):\n\n return render(request, 'base.html')\n\nclass PhotoUploadView(CreateView):\n model = Photo\n fields = ['photo']\n template_name = 'upload.html'\n\n def form_valid(self, form):\n form.instance.author_id = self.request.user.id\n if form.is_valid():\n form.instance.save()\n print(form)\n print(self)\n return redirect('photo:output')\n else:\n return self.render_to_response({'form':form})\n\n\n\ndef Output(request):\n\n pillinfo = pilldetect.main()\n\n pill = pillinformation.objects.filter(shape=pillinfo[0] , char=pillinfo[1], color=pillinfo[2])\n\n return render(request, 'output.html', {'pill': pill})\n\n\n\n# class PhotoDeleteView(DeleteView):\n# model = Photo\n# success_url = '/'\n# template_name = 'delete.html'\n#\n# class PhotoUpdateView(UpdateView):\n# model = Photo\n# fields = ['photo']\n# template_name = 'update.html'\n\n\n","sub_path":"pill/pill_detection/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"121524834","text":"\"\"\"Module for something.\"\"\"\nimport tkinter as tk\nimport logic\n\n\nclass Application(tk.Frame):\n \"\"\"\n Sample tkinter application class.\n\n :param master: hz\n :param title: название окошка\n :param kwargs: hz\n \"\"\"\n\n def __init__(self, master=None, title=\"\", **kwargs):\n self.logic = logic.Logic()\n super().__init__(master, **kwargs)\n self.master.title(title)\n self.master.columnconfigure(0, weight=1)\n self.master.rowconfigure(0, weight=1)\n self.grid(sticky=\"NEWS\")\n self.create_widgets()\n for column in range(self.grid_size()[0]):\n for row in range(self.grid_size()[1]):\n self.columnconfigure(column, weight=1)\n self.rowconfigure(row, weight=1)\n\n def create_widgets(self):\n \"\"\"Create all the widgets.\"\"\"\n\n\nclass App(Application):\n \"\"\"Sample tkinter application class.\"\"\"\n\n def create_widgets(self):\n \"\"\"Create all the widgets.\"\"\"\n analyze = self.register(self.logic.logic_analyze)\n\n self.label_text = tk.StringVar()\n self.label_text.set(\"Default\")\n\n self.choice = tk.StringVar()\n self.options = [\"One\", \"Two\", \"Three\"]\n self.choice.set(self.options[0])\n\n self.editor = tk.Entry(\n self, validate='all', validatecommand=(analyze, \"%P\"))\n self.editor.grid()\n\n self.menu = tk.OptionMenu(self, self.choice, *self.options)\n self.menu.grid()\n\n self.insert = tk.Button(self, text='Insert', command=self.insert_func)\n self.insert.grid()\n\n self.show = tk.Button(self, text='Show', command=self.show_func)\n self.show.grid()\n\n self.label = tk.Label(\n self, textvariable=self.label_text, takefocus=1,\n highlightthickness=2)\n self.label.bind(\"\", self.in_label)\n self.label.bind(\"\", self.out_label)\n self.label.grid()\n\n def insert_func(self):\n \"\"\"Insert text in entry.\"\"\"\n self.logic.logic_insert_func(self.editor, tk.END, self.choice.get())\n\n def show_func(self):\n \"\"\"Print text in label.\"\"\"\n self.logic.logic_label(self.label_text, self.editor.get())\n\n def in_label(self, event):\n \"\"\"\n Print text in label.\n\n :param event: бесполезный параметр\n \"\"\"\n self.logic.logic_label(self.label_text, \"Hi Mouse\")\n\n def out_label(self, event):\n \"\"\"\n Print text in label.\n\n :param event: бесполезный параметр\n \"\"\"\n self.logic.logic_label(self.label_text, \"Bye Mouse\")\n\n\ndef main():\n \"\"\"Do all work.\"\"\"\n app = App(title=\"Sample application\")\n app.mainloop()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"20210412_2/task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":2764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"492950096","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 ('repo', '0002_work_notes'),\n ]\n\n operations = [\n migrations.AlterModelTable(\n name='work',\n table='repo_work',\n ),\n ]\n","sub_path":"src/repo/migrations/0003_auto_20150513_0820.py","file_name":"0003_auto_20150513_0820.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"630653971","text":"def main():\r\n\r\n s = str(input('Digite a string a ser analisada: '))\r\n\r\n print(camelcase(s))\r\n\r\ndef camelcase(s):\r\n cont = 1\r\n\r\n for i in s:\r\n n = ord(i)\r\n\r\n if maiusculo(n):\r\n cont += 1\r\n\r\n return cont\r\n\r\n\r\ndef maiusculo(n):\r\n if (n >= 65 and n <= 90):\r\n return True\r\n\r\n else:\r\n return False \r\n\r\n\r\nmain()\r\n","sub_path":"Desafios - HackerRank/Desafio_CamelCase.py","file_name":"Desafio_CamelCase.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"570379191","text":"import random\r\nimport cv2\r\nfrom torchvision import transforms\r\nimport torchvision.transforms.functional as ttf\r\nfrom PIL import Image\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport os\r\nimport PIL\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef makecon():\r\n path1 = \"./dataset/DRIVE/test/1st_manual/\"\r\n path2 = \"./dataset/DRIVE/test/1st_manual_tv_resized/\"\r\n save_path = \"./dataset/DRIVE/test/contrast/\"\r\n for i in range(1, 21):\r\n print(\"doing \"+str(i))\r\n\r\n if i<10:\r\n prefix = \"0\"+str(i)\r\n else:\r\n prefix = str(i)\r\n img1_path = path1 + prefix + \"_manual1.gif\" # 拼出图片路径和文件名\r\n img2_path = path2 + prefix + \"_manual1.gif\" # 拼出图片路径和文件名\r\n img1 = PIL.Image.open(img1_path) # 读入图片\r\n img2 = PIL.Image.open(img2_path) # 读入图片\r\n\r\n\r\n\r\n # manual_img_path = root + \"m\" + \"_\" + str(num) + \".jpg\"\r\n # manual_img = PIL.Image.open(manual_img_path)\r\n # gen_img_path = root + name + \"_\" + str(num) + \".jpg\"\r\n # gen_img = PIL.Image.open(gen_img_path)\r\n # manual_img = manual_img.convert(\"1\")\r\n # result = np.array(gen_img)\r\n # gen_img = gen_img.convert(\"1\")\r\n # # manual_img.show()\r\n # # gen_img.show()\r\n # manual = np.array(manual_img)\r\n # gen = np.array(gen_img)\r\n result = np.array(img1)\r\n\r\n img1 = np.array(img1)\r\n img2 = np.array(img2)\r\n # print(result)\r\n\r\n # print(manual.shape)\r\n # print(gen.shape)\r\n count=0\r\n for i in range(512):\r\n for j in range(512):\r\n if(img1[i][j] > img2[i][j]):\r\n result[i][j][0] = 255\r\n result[i][j][1] = 0\r\n result[i][j][2] = 0\r\n count=count+1\r\n if(img1[i][j] < img2[i][j]):\r\n result[i][j][0] = 0\r\n result[i][j][1] = 255\r\n result[i][j][2] = 0\r\n count = count + 1\r\n print(str(count))\r\n result = Image.fromarray(result)\r\n\r\n result.save(save_path + prefix + \"_\"+\"contrast.jpg\")\r\n\r\nmakecon()","sub_path":"gen_segmentation_contrast.py","file_name":"gen_segmentation_contrast.py","file_ext":"py","file_size_in_byte":2176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"290948977","text":"\"\"\"Solve the '1CA' problem.\"\"\"\n\nfrom solver import solver\n\n\ndef solve(r, c, w):\n s = (c / w) * r + w\n return s if c % w else s - 1\n\n\n@solver(lines_per_case=1)\ndef gcj_1ca(lines):\n r, c, w = map(int, lines[0].split())\n return solve(r, c, w)\n\n\nif __name__ == \"__main__\":\n gcj_1ca.from_cli()\n","sub_path":"solutions_5640146288377856_0/Python/vxgmichel/brattleship.py","file_name":"brattleship.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"104601859","text":"## @file CalcModule.py\n# @author Rohit Saily\n# @brief Module used to process student and department data.\n# @date 2019-01-18\n\n#from a1_constants import MIN_GPA, MAX_GPA, MIN_PASSING_GPA, GENDERS\n#from a1_utility import remove_duplicates\n\n\"\"\" Helper Functions \"\"\"\n## @brief Allocates a student to their topmost available choice if they have a passing gpa, defined in a1_constants.py.\n# @details If a student cannot be allocated to any of their choices, they simply are not allocated. If their choice is not found in allocations or spots_available, it is ignored.\n# @param student The student to be allocated to a department, represented by a dictionary that maps data categories to data.\n# @param allocations A dictionary that maps a department to a list of student dictionaries already allocated.\n# @param spots_available A dictionary that maps a department to the number of students that can be allocated to it.\ndef allocate_topmost_available_choice(student, allocations, spots_available):\n if not (4 <= student['gpa'] <= 12):\n return #Do not allocate the student, they are not passing or have an invalid GPA\n for choice in student['choices']:\n if 0 < spots_available[choice]:\n try:\n allocations[choice].append(student)\n except KeyError:\n continue #The choice is not allocateable, continue to try the next one\n else:\n try:\n spots_available[choice] -= 1\n except KeyError:\n allocations[choice].remove(student) #We cannot gurantee the department exists with space, so we cannot allocate the student without it being in the spots_available dictionary\n continue\n else:\n return\n\n\"\"\" API \"\"\"\n## @brief Sorts students by descending GPA.\n# @details\n# Each student is represented by a dictionary that maps data categories to data.\n# This function does not mutate the original list.\n# Sorts using Tim Sort via Python's sorted function.\n# @param S The list of students represented by dictionaries that map data categories to corresponding data.\n# @return The list of dictionaries representing students organized by descending GPA.\ndef sort(S):\n if S == []:\n return S\n return sorted(S, key=lambda student: student['gpa'], reverse=True)\n\n## @brief Averages the GPA of students, filtered by gender.\n# @details Any student found to have a gpa below the minimum or above the maximum, each defined in a1_constants.py, will be ignored in the computation.\n# @param L The list of students, each represented by dictionaries that map data categories to data.\n# @param g The gender to filter by, case insensitive.\n# @return None if no students were found to average otherwise it is the average computed.\ndef average(L, g):\n if not L:\n return None\n gpas = []\n for student in L:\n if not (4 <= student['gpa'] <= 12):\n continue\n try:\n if student['gender'] == g.lower():\n gpas.append(student['gpa'])\n except KeyError:\n continue\n else:\n pass\n try:\n average = sum(gpas) / len(gpas)\n except ZeroDivisionError:\n return None #There where no values to average hence there is no average\n else:\n return average\n\n## @brief Allocates students to departments based on code defined allocation scheme.\n# @details\n# The code defined allocation scheme is as follows:\n# 1. Free choice students are allocated before students without free choice.\n# 2. Students with higher GPAs are allocated first.\n# 3. Students with failing GPAs or GPAs above the maximum are not allocated.\n# 4. Students who cannot fit into any of departments they chose are not allocated to any department.\n# @param S The list of students represented by dictionaries that map data categories to corresponding data.\n# @param F The list of mac ids of students who have free choice.\n# @param C A dictionary that maps department names to their capacity.\n# @return A dictionary mapping departments to a list of students allocated to that department.\ndef allocate(S, F, C):\n if not C:\n return {} #No allocations can be made without departments!\n allocations = {}\n spots_available = {department:capacity for department, capacity in C.items()}\n for department in spots_available:\n allocations[department] = []\n if not S:\n return allocations #No students to allocate\n students = []\n students.extend(sort(S))\n #remove_duplicates(students) #To prevent accidentally allocating a student twice if they are defined multiple times in the list.\n free_choice_students = []\n for student in students:\n if student['macid'] in F:\n free_choice_students.append(student)\n students.remove(student)\n non_free_choice_students = students #Just to 'rename' the variable and increase code readability since students now holds only students without free choice.\n for student in free_choice_students:\n allocate_topmost_available_choice(student, allocations, spots_available)\n for student in non_free_choice_students:\n allocate_topmost_available_choice(student, allocations, spots_available)\n return allocations\n","sub_path":"2AA4 - Python and C++/A1/partner/CalcModule.py","file_name":"CalcModule.py","file_ext":"py","file_size_in_byte":5342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"458348676","text":"from setuptools import setup, find_packages\n\nversion='1.5'\nwith open('C:/Users/pipidog/Dropbox/Code/DFTtoolbox/README.md') as file:\n long_description = file.read()\n\nsetup(\n name = 'DFTtoolbox',\n version = version,\n packages = ['DFTtoolbox'],\n description = 'A toolbox to initialize or postpocess several DFT codes',\n long_description=long_description,\n scripts = [],\n license='MIT',\n author = 'pipidog',\n author_email = 'pipidog@gmail.com',\n url = 'https://github.com/pipidog/DFTtoolbox',\n download_url = 'https://github.com/pipidog/DFTtoolbox/archive/v1.0.tar.gz',\n keywords = ['density-functional-theory','qantum-espresso','elk','abinit'],\n classifiers = ['Topic :: Scientific/Engineering :: Physics'],\n install_requires=['numpy','matplotlib']\n)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"203600072","text":"#import databaseclass\nimport cx_Oracle\nimport re\nimport prescription\n\ndef runSearch(pre):\n while True:\n try:\n dId = pre.doctorName()\n print(\"\\n> Starting Date: \")\n startDate = pre.getDate()\n print(\"\\n> End Date: \")\n endDate = pre.getDate()\n\n sql = (\"select distinct p.health_care_no, p.name, t.test_name, r.prescribe_date from test_record r, patient p, test_type t where p.health_care_no\"+\n \"=r.patient_no and r.type_id=t.type_id and r.employee_no = \"+dId+\n \" and r.prescribe_date between DATE'\"+startDate+\"' and DATE'\"+ endDate+\"'\")\n pre.con.execute(pre.con, sql)\n rows = pre.con.curs.fetchall()\n print()\n print(\"HC Num | Patient Name | Test Name | Date \")\n for x in range(len(rows)):\n print(str(rows[x][0]).ljust(10)+str(rows[x][1]).ljust(25)+str(rows[x][2]).ljust(15)+str(rows[x][3])[:10].ljust(10))\n #print(\" \"+ str(x) +\". \"+ str(rows[x]))\n \n again = input(\"\\n> Search Another Entry? (y/n): \")\n \n if (again == 'n'):\n print(\"\\n> Leaving Doctor Search ...\")\n break\n \n except (KeyboardInterrupt, EOFError, SystemExit):\n raise\n except:\n raise\n \ndef run(theConnection): \n print(\"\\n----- DOCTOR TEST SEARCH -----\\n\")\n y = prescription.Prescription(theConnection)\n\n try:\n runSearch(y)\n except (KeyboardInterrupt, EOFError, SystemExit):\n print(\"\\n> Leaving Doctor Search ... \")\n except:\n print(\"\\n> Unexpected Error Occured ...\")\n\n","sub_path":"project1/doctorsearch.py","file_name":"doctorsearch.py","file_ext":"py","file_size_in_byte":1720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"587490999","text":"import cv2\r\nimport numpy as np\r\nimport 색\r\nimport 모드\r\nimport matplotlib.pyplot as plt\r\nimport tkinter as Tk\r\n\r\nplt.ion()\r\n\r\nclass SmoothBall:\r\n def __init__(self, ):\r\n self.direction\r\n self.speed\r\n self.angleDrag\r\n\r\ndef cany_con_can(src, t1, t2, thick, ksize = None, it = None, sw = False):\r\n edged = cv2.Canny(src, t1, t2)\r\n dilate = None\r\n if sw: dilate = cv2.dilate(edged, kernel=cv2.getStructuringElement(cv2.MORPH_ELLIPSE, ksize=ksize), iterations=it)\r\n (contours, _) = cv2.findContours(dilate if sw else edged, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)\r\n canvas = np.zeros(shape=(src.shape[0], src.shape[1], 3), dtype=np.uint8)\r\n cv2.drawContours(canvas, contours, -1, 색.회색, thick)\r\n return edged, contours, canvas, dilate\r\n\r\n\r\ndef 테이크3 (src):\r\n height, width = src.shape[:2] # 이미지 크기 구하기\r\n mn = min(height, width)\r\n xxsm = int(mn * 0.01)\r\n xsm = int(mn * 0.05)\r\n sm = int(mn * 0.1)\r\n md = int(mn * 0.4)\r\n\r\n gray = cv2.cvtColor(src, cv2.COLOR_BGRA2GRAY)\r\n gblur = cv2.GaussianBlur(gray, (5, 5), 1)\r\n mblurWeek = cv2.medianBlur(gblur, ksize=7)\r\n\r\n cany, contours, canvas, dilate = cany_con_can(mblurWeek, 10, 200, 3, (5,5), 2, False)\r\n wfile = open('./contours_smaple.txt', 'w')\r\n print(contours, file=wfile)\r\n wfile.close()\r\n\r\n def size_filter(cnt):\r\n x, y, width, height = cv2.boundingRect(cnt)\r\n return width * height\r\n contours.sort(key=size_filter, reverse = True)\r\n contour = contours[0]\r\n\r\n poly = cv2.approxPolyDP(contour, 2, False)\r\n cv2.drawContours(canvas, [poly], -1, 색.흰, 3)\r\n\r\n for point in poly:\r\n p = point[0]\r\n cv2.circle(canvas, (p[0], p[1]), 1, 색.빨, 5)\r\n\r\n # xes = [points[0][0] for points in poly]\r\n # yes = [points[0][1] for points in poly]\r\n\r\n # plt.clf()\r\n # plt.plot(xes, 'r')\r\n # plt.plot(yes, 'b')\r\n # plt.pause(0.0001)\r\n # plt.show()\r\n\r\n return [canvas]\r\n\r\n\r\nr = 모드.사진(테이크3, 600)\r\nr.run()\r\n\r\n","sub_path":"pylab/beta lab/#16. 다스께떼 구레.py","file_name":"#16. 다스께떼 구레.py","file_ext":"py","file_size_in_byte":2030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"165550110","text":"from decide import __version__\nfrom setuptools import setup, find_packages\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetup(\n name=\"decide-exchange-model\",\n version=__version__,\n packages=find_packages(),\n url=\"https://github.com/foarsitter/decide-exchange-model\",\n license=\"GPL-3.0\",\n author=\"jelmert\",\n author_email=\"info@jelmert.nl\",\n description=\"Model of collective decision making\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n entry_points={\n \"console_scripts\": [\"decide-cli=decide.cli:main\"],\n \"gui_scripts\": [\"decide-gui=decide.gui:main\"],\n },\n # data_files=[('data/input', ['data/input/kopenhagen.csv', 'data/input/CoP21.csv'])],\n python_requires=\">=3.6\",\n install_requires=[\n \"blinker==1.4\",\n \"matplotlib==3.0.2\",\n \"requests==2.21.0\",\n \"typesystem==0.2.2\"\n ],\n)\n","sub_path":"pypi_install_script/decide-exchange-model-2019.3.1.5.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"144546557","text":"input = open(\"d14_in.txt\").read()\nlines = input.split('\\n')\n\nmem = {}\ncur_mask = ''\n\ndef count_diff(a:str, b:str):\n output = 0\n out_list = []\n for i in range(len(a)):\n if not a[i] == b[i]:\n if a[i] == 'X':\n out_list.append(b[i])\n elif b[i] == 'X':\n out_list.append(a[i])\n else:\n return (0,'')\n else:\n if a[i] == 'X' and b[i] == 'X':\n output += 1\n out_list.append(a[i])\n if ''.join(out_list) == a:\n return (0,a)\n elif ''.join(out_list) == b:\n return (0,b)\n return (2 ** output , ''.join(out_list))\n\nfor line in lines:\n arg = line.split(' ')\n if arg[0] == 'mask':\n cur_mask = arg[1]\n elif arg[0] == 'mem':\n location = int(arg[1])\n to_write = int(arg[2])\n \n location_bin = \"{0:b}\".format(location)\n while len(location_bin) < len(cur_mask):\n location_bin = '0' + location_bin\n \n actual_location = []\n for i in range(len(cur_mask)):\n if cur_mask[i] == 'X':\n actual_location.append('X')\n elif cur_mask[i] == '1':\n actual_location.append('1')\n else:\n actual_location.append(location_bin[i])\n actual_location = ''.join(actual_location)\n\n #print(actual_location)\n running_minus = 0\n update = {}\n for key in mem:\n (cur,new_key) = count_diff(key, actual_location)\n (cnt,value) = mem[key]\n mem[key] = (cnt - cur, value)\n update[new_key] = (cur, to_write)\n running_minus += cur\n \n #print(mem)\n\n for key in update:\n mem[key] = update[key]\n\n #print(mem)\n mem[actual_location] = (2 ** actual_location.count('X') - running_minus, to_write)\n\n\n\nans = 0\nfor key in mem:\n if not key == '':\n (cnt, value) = mem[key]\n #print(key,cnt,value)\n ans += cnt * value\n\nprint(ans)","sub_path":"2020/Day 14/d14p2_old.py","file_name":"d14p2_old.py","file_ext":"py","file_size_in_byte":2030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"507324895","text":"# 과일 명 가격 개수\n# 배 2000 3\n# 사과 1500 5\n# 딸기 1800 2\n# 참외 2300 5\n\n# 5개 이하는 5개로\n# 사야 할 과일과 그에 드는 각각의 비용과 총비용을\n\nif __name__ == \"__main__\":\n fruits = {\"fear\": [2000, 3], \"apple\": [1500, 5], \"strawberry\": [1800, 2], \"melon\": [2300, 5]}\n\n requireFruits = {}\n requireMoney = 0\n\n sum = 0\n\n for fruit in fruits.items():\n if fruit[1][1] < 5:\n requireMoney = fruit[1][0] * fruit[1][1]\n print(fruit[0], \"을 \", requireMoney, \"원 구매해야합니다.\")\n\n sum += requireMoney\n else:\n print(fruit[0], \"은 구매할 필요가 없습니다\")\n\n print(\"전체 금액:\", sum, \"원\")","sub_path":"1-1/022-strucutre_fruits_name.py","file_name":"022-strucutre_fruits_name.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"215150684","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Aug 10 10:36:12 2016\n\n@author: Hejia Pan\n\"\"\"\nimport Queue\nimport math\n\nclass movAvg:\n def __init__(self, windowSize):\n self.rollingSum = [0, 0]\n self.buf = Queue.Queue(maxsize=windowSize)\n self.windowSize = windowSize\n self.count = 0\n\n def reset(self):\n self.rollingSum = [0, 0]\n self.count = 0\n qsz = self.buf.qsize()\n for i in range(qsz):\n self.buf.get()\n\n def put(self, data):\n data = [math.cos(math.radians(data)), math.sin(math.radians(data))]\n if self.count == self.windowSize:\n try:\n dequeue = self.buf.get_nowait()\n self.rollingSum[0] -= dequeue[0]\n self.rollingSum[1] -= dequeue[1]\n except:\n raise Exception('Moving average buffer corrupted, detected while doing get operation.')\n else:\n self.count += 1\n try:\n self.buf.put_nowait(data)\n except:\n raise Exception('Moving average buffer corrupted, detected while doing put operation.')\n self.rollingSum[0] += data[0]\n self.rollingSum[1] += data[1]\n\n def get(self):\n temp = math.degrees(math.atan2(self.rollingSum[1]*1.0/self.count, self.rollingSum[0]*1.0/self.count))\n if(temp <0):\n temp += 360\n return temp\n\nif __name__ == '__main__':\n import csv\n import matplotlib.pyplot as plt\n\n data = []\n with open('log.csv', 'rb') as logfile:\n reader = csv.reader(logfile, delimiter=' ', quotechar='|')\n for row in reader:\n data.append(float(row[0]))\n\n x = list(range(len(data)))\n\n averagedData = []\n movav = movAvg(windowSize = 100)\n for d in data:\n movav.put(d)\n averagedData.append(movav.get())\n\n plt.plot(x, data, '--', x, averagedData, 'r')\n plt.show()","sub_path":"dolly/bbb/movingAverage.py","file_name":"movingAverage.py","file_ext":"py","file_size_in_byte":1892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"228994778","text":"from __future__ import print_function\n\nfrom builtins import object\n\nfrom empire.server.common.helpers import (\n strip_powershell_comments,\n strip_python_comments,\n)\nfrom empire.server.utils.data_util import ps_convert_to_oneliner\n\n\nclass Stager(object):\n def __init__(self, mainMenu, params=[]):\n self.info = {\n \"Name\": \"C# PowerShell Launcher\",\n \"Authors\": [\n {\n \"Name\": \"Anthony Rose\",\n \"Handle\": \"@Cx01N\",\n \"Link\": \"https://twitter.com/Cx01N_\",\n },\n {\n \"Name\": \"Jake Krasnov\",\n \"Handle\": \"@hubbl3\",\n \"Link\": \"https://twitter.com/_Hubbl3\",\n },\n ],\n \"Description\": \"Generate a PowerShell C# solution with embedded stager code that compiles to an exe\",\n \"Comments\": [\"Based on the work of @bneg\"],\n }\n\n self.options = {\n \"Language\": {\n \"Description\": \"Language of the stager to generate (powershell, csharp).\",\n \"Required\": True,\n \"Value\": \"csharp\",\n \"SuggestedValues\": [\"powershell\", \"csharp\", \"ironpython\"],\n \"Strict\": True,\n },\n \"DotNetVersion\": {\n \"Description\": \"Language of the stager to generate(powershell, csharp).\",\n \"Required\": True,\n \"Value\": \"net40\",\n \"SuggestedValues\": [\"net35\", \"net40\"],\n \"Strict\": True,\n },\n \"Listener\": {\n \"Description\": \"Listener to use.\",\n \"Required\": True,\n \"Value\": \"\",\n },\n \"StagerRetries\": {\n \"Description\": \"Times for the stager to retry connecting.\",\n \"Required\": False,\n \"Value\": \"0\",\n },\n \"UserAgent\": {\n \"Description\": \"User-agent string to use for the staging request (default, none, or other).\",\n \"Required\": False,\n \"Value\": \"default\",\n },\n \"Proxy\": {\n \"Description\": \"Proxy to use for request (default, none, or other).\",\n \"Required\": False,\n \"Value\": \"default\",\n },\n \"ProxyCreds\": {\n \"Description\": \"Proxy credentials ([domain\\]username:password) to use for request (default, none, or other).\",\n \"Required\": False,\n \"Value\": \"default\",\n },\n \"OutFile\": {\n \"Description\": \"Filename that should be used for the generated output.\",\n \"Required\": True,\n \"Value\": \"Sharpire.exe\",\n },\n \"Obfuscate\": {\n \"Description\": \"Switch. Obfuscate the launcher powershell code, uses the ObfuscateCommand for obfuscation types. For powershell only.\",\n \"Required\": False,\n \"Value\": \"False\",\n \"SuggestedValues\": [\"True\", \"False\"],\n \"Strict\": True,\n },\n \"ObfuscateCommand\": {\n \"Description\": \"The Invoke-Obfuscation command to use. Only used if Obfuscate switch is True. For powershell only.\",\n \"Required\": False,\n \"Value\": r\"Token\\All\\1\",\n },\n \"Bypasses\": {\n \"Description\": \"Bypasses as a space separated list to be prepended to the launcher\",\n \"Required\": False,\n \"Value\": \"mattifestation etw\",\n },\n \"Staged\": {\n \"Description\": \"Allow agent to be staged\",\n \"Required\": True,\n \"Value\": \"True\",\n \"SuggestedValues\": [\"True\", \"False\"],\n \"Strict\": True,\n },\n }\n\n self.mainMenu = mainMenu\n\n for param in params:\n option, value = param\n if option in self.options:\n self.options[option][\"Value\"] = value\n\n def generate(self):\n self.options.pop(\"Output\", None) # clear the previous output\n # staging options\n language = self.options[\"Language\"][\"Value\"]\n user_agent = self.options[\"UserAgent\"][\"Value\"]\n proxy = self.options[\"Proxy\"][\"Value\"]\n proxy_creds = self.options[\"ProxyCreds\"][\"Value\"]\n stager_retries = self.options[\"StagerRetries\"][\"Value\"]\n listener_name = self.options[\"Listener\"][\"Value\"]\n stager_retries = self.options[\"StagerRetries\"][\"Value\"]\n dot_net_version = self.options[\"DotNetVersion\"][\"Value\"]\n bypasses = self.options[\"Bypasses\"][\"Value\"]\n obfuscate = self.options[\"Obfuscate\"][\"Value\"]\n obfuscate_command = self.options[\"ObfuscateCommand\"][\"Value\"]\n\n obfuscate_script = False\n if obfuscate.lower() == \"true\":\n obfuscate_script = True\n\n staged = self.options[\"Staged\"][\"Value\"].lower() == \"true\"\n\n if not staged and language != \"csharp\":\n launcher = self.mainMenu.stagers.generate_stageless(self.options)\n\n if language == \"powershell\":\n launcher = ps_convert_to_oneliner(strip_powershell_comments(launcher))\n elif language == \"ironpython\":\n launcher = strip_python_comments(launcher)\n else:\n launcher = self.mainMenu.stagers.generate_launcher(\n listener_name,\n language=language,\n encode=False,\n obfuscate=obfuscate_script,\n obfuscation_command=obfuscate_command,\n userAgent=user_agent,\n proxy=proxy,\n proxyCreds=proxy_creds,\n stagerRetries=stager_retries,\n bypasses=bypasses,\n )\n\n if launcher == \"\":\n return \"[!] Error in launcher generation.\"\n else:\n if not launcher or launcher.lower() == \"failed\":\n return \"[!] Error in launcher command generation.\"\n\n if language.lower() == \"powershell\":\n directory = self.mainMenu.stagers.generate_powershell_exe(\n launcher, dot_net_version=dot_net_version\n )\n with open(directory, \"rb\") as f:\n code = f.read()\n return code\n\n elif language.lower() == \"csharp\":\n directory = f\"{self.mainMenu.installPath}/csharp/Covenant/Data/Tasks/CSharp/Compiled/{dot_net_version}/{launcher}.exe\"\n with open(directory, \"rb\") as f:\n code = f.read()\n return code\n\n elif language.lower() == \"ironpython\":\n directory = self.mainMenu.stagers.generate_python_exe(\n launcher, dot_net_version=dot_net_version\n )\n with open(directory, \"rb\") as f:\n code = f.read()\n return code\n\n else:\n return \"[!] Invalid launcher language.\"\n","sub_path":"empire/server/stagers/windows/csharp_exe.py","file_name":"csharp_exe.py","file_ext":"py","file_size_in_byte":6988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"359629889","text":"# Escribir un programa que pida dos numeros reales e imprima en la pantalla el mayor de ellos. ç\n# El programa debe indicar si los numeros son iguales.\n\nimport math\n\nprint(\"Ingrese dos numeros reales.\")\nx = float(input(\"x = \"))\ny = float(input(\"y = \"))\nif math.isclose(x, y, rel_tol=1e-52):\n print(\"Son iguales\")\nelif x < y:\n print(\"x < y\")\nelse:\n print(\"y < x\")\n","sub_path":"codigos/lab1/ej6.py","file_name":"ej6.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"165199822","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Apr 5 22:35:50 2019\n\n@author: khoim\n\"\"\"\n\nimport os\nimport flask\nimport dash\nimport plotly\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport dash_bootstrap_components as dbc\nimport plotly.plotly as py\nimport plotly.graph_objs as go\nimport numpy as np\nimport pandas as pd\n\nfrom random import randint\nfrom pandas import read_csv, DataFrame\nfrom dash.dependencies import Input, Output, State\n\nplotly.tools.set_credentials_file(username='weirdleau', api_key='6OwzPOESWVTBrBSj14BF')\n\nSEVERITY_LOOKUP = {'Fatal' : 'red',\n 'Serious' : 'orange',\n 'Slight' : 'yellow'}\n\nmonth = ['January', 'February', 'March', 'April', 'May', 'June', 'July',\n 'August', 'September', 'October', 'November', 'December']\nPython = [40, 35, 32, 31, 25, 26, 22, 35, 37, 36, 35, 34]\nMachineLearning = [27, 23, 10, 16, 17, 14, 21, 25, 26, 19, 18, 11]\nKeras = [24, 22, 17, 26, 20, 11, 12, 23, 29, 10, 18, 16]\nTensorflow = [17, 27, 10, 25, 26, 12, 24, 15, 11, 18, 24, 22]\nSQL = [26, 17, 27, 20, 10, 16, 18, 13, 28, 14, 22, 12]\nHadoop = [17, 14, 29, 13, 20, 15, 22, 25, 19, 10, 24, 12]\n\ncsvLoc = 'data.csv'\ndat = read_csv(csvLoc, index_col = 0)\nserver = flask.Flask(__name__)\nserver.secret_key = os.environ.get('secret_key', 'secret')\n\napp = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])\napp.config.supress_callback_exceptions = True\n\napp.layout = html.Div(children=[\n html.H1(children='System recommended Jobs'),\n\n html.Div(children='''This is prototype of Jobs Advising team, not final version'''),\n\n dbc.Nav(\n [\n dbc.NavItem(dbc.NavLink(\"Home\", active=True, href=\"#\")),\n dbc.DropdownMenu(\n [dbc.DropdownMenuItem(\"Item 1\"), dbc.DropdownMenuItem(\"Item 2\")],\n label=\"Skills popularity\",\n nav=True,\n ),\n dbc.DropdownMenu(\n [dbc.DropdownMenuItem(\"Item 1\"), dbc.DropdownMenuItem(\"Item 2\")],\n label=\"Job locations\",\n nav=True,\n ),\n dbc.DropdownMenu(\n [dbc.DropdownMenuItem(\"Item 1\"), dbc.DropdownMenuItem(\"Item 2\")],\n label=\"Salary stats\",\n nav=True,\n ),\n dbc.NavItem(dbc.NavLink(\"User account\", href=\"#\")),\n ], horizontal = \"end\",\n ),\n\n dbc.CardDeck(\n [\n dbc.Card(\n [\n dbc.CardHeader(\"Python\"),\n dbc.CardBody(\n [\n dbc.CardTitle(\"Python là một ngôn ngữ lập trình bậc cao\"),\n dbc.CardText(\"Python được sử dụng cho các mục đích lập trình đa năng, Python được tạo ra với ưu điểm là dễ đọc, dễ học và dễ nhớ, Python là ngôn ngữ có hình thực rất sáng sửa, cấu trúc rõ ràng, thuận tiện cho người mới học lập trình, cấu trúc của nó còn cho phép người sử dụng viết mã lệnh với số lần gõ phím tối thiểu.\"),\n ]\n ),\n ]\n ),\n dbc.Card(\n [\n dbc.CardHeader(\"SQL\"),\n dbc.CardBody(\n [\n dbc.CardTitle(\"SQL là một ngôn ngữ truy vấn, tính cấu trúc dùng để quản lý dữ liệu\"),\n dbc.CardText(\"Ngôn ngữ cơ sở dữ liệu, được sử dụng để tạo, xóa trong cơ sở dữ liệu, lấy các hàng và sửa đổi các hàng, … SQL dùng để: tạo cơ sở dữ liệu, bảng và view mới, chèn các bản ghi vào trong một cơ sở dữ liệu, xóa các bản ghi từ một cơ sở dữ liệu, lấy dữ liệu từ một cơ sở dữ liệu.\"),\n ]\n ),\n ]\n ),\n dbc.Card(\n [\n dbc.CardHeader(\"Machine Learning\"),\n dbc.CardBody(\n [\n dbc.CardTitle(\"Maching learning là một ngành học thuộc khoa học máy tính, giúp máy tính có khả năng tự học mà không phải lập trình một cách rõ ràng\"),\n dbc.CardText(\"Machine Learning được chia thành 3 loại: Supervised learning (học có giám sát), Unsupervised learning (học không giám sát), Reinforcement learning (học tăng cường/học củng cố)\"),\n ]\n ),\n ]\n ),\n dbc.Card(\n [\n dbc.CardHeader(\"Hadoop\"),\n dbc.CardBody(\n [\n dbc.CardTitle(\"Là một framwork giúp lưu trữ và xử lý Big Data\"),\n dbc.CardText(\"Nó áp dụng phân tán dữ liệu vì nó tách hết tập hợp các dữ liệu ban đầu thành các dữ liệu nhỏ và sắp xếp lại chúng để dễ dàng tìm kiếm và truy xuất hơn, đặc biệt là việc truy xuất các dữ liệu tương đồng, do Apache phát triển\"),\n ]\n ),\n ]\n ),\n ],style={\"max-width\": \"100%\"},\n),\n\n dcc.Graph(\n id='graph city',\n figure={\n 'data': [\n {'x': month, 'y': Python, 'type': 'lines', 'name': u'Python'},\n {'x': month, 'y': MachineLearning, 'type': 'lines', 'name': u'Deep learning'},\n {'x': month, 'y': Keras, 'type': 'lines', 'name': u'Java'},\n {'x': month, 'y': Tensorflow, 'type': 'lines', 'name': u'R'},\n {'x': month, 'y': SQL, 'type': 'lines', 'name': u'SQL'},\n {'x': month, 'y': Hadoop, 'type': 'lines', 'name': u'C++'},\n ],\n 'layout': {\n 'title': 'Độ phổ biến skills qua từng giai đoạn'\n }\n }\n ),\n\n html.H1(\n 'Nhập vào các skill hiện có của bạn',\n style={\n 'paddingLeft' : 50,\n }\n ),\n \n html.Div([\n html.Div([ \n dcc.Checklist( \n options=[\n {'label': s,\n 'value': s} for s in dat['S'].unique()\n ],\n values=['C++'],\n labelStyle={\n 'display': 'inline-block',\n 'paddingRight' : 10,\n 'paddingLeft' : 10,\n 'paddingBottom' : 5,\n },\n id=\"dataChecklist\", \n ),\n ],\n style={\n \"width\" : '60%',\n 'text-size':'54px',\n 'display' : 'inline-block', \n 'paddingLeft' : 50, \n 'paddingRight' : 10,\n 'boxSizing' : 'border-box',\n }\n ),\n ],\n style={'paddingBottom' : 20}),\n\n html.Div([ \n html.Div([ # Holds the barchart\n dcc.Graph(id=\"Pie\",)\n ],\n style={\n \"width\" : '40%', \n \"height\":'150%',\n 'float' : 'right', \n 'paddingRight' : 50, \n 'paddingLeft' : 5,\n })\n\n ]),\n])\n\n@app.callback( \n Output(component_id='Pie', component_property='figure'),\n [Input(component_id='dataChecklist', component_property='values')]\n)\n\ndef updatePieChart(data):\n df = DataFrame(dat[['S','Points']]\n [(dat['S'].isin(data))].groupby(['S','Points']).sum()).reset_index()\n p = df['Points']\n s = 0\n for i in p:\n s += i\n \n \n label = ['Xin việc thành công','Xin việc không thành công']\n \n x=int(min(s,99))\n y=int (100-x)\n\n piedata = go.Pie(values=[x,y], labels=label)\n \n return {\n 'data': [piedata],\n 'layout': {\n 'height': 550,\n 'margin': {\n 'l': 20,\n 'b': 30, \n 'r': 10, \n 't': 10\n }\n }\n }\n\nif __name__ == '__main__':\n app.run_server(debug=True, threaded=True)","sub_path":"Platform/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":8166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"178263475","text":"\n\nfrom xai.brain.wordbase.nouns._voyeur import _VOYEUR\n\n#calss header\nclass _VOYEURS(_VOYEUR, ):\n\tdef __init__(self,): \n\t\t_VOYEUR.__init__(self)\n\t\tself.name = \"VOYEURS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"voyeur\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_voyeurs.py","file_name":"_voyeurs.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"115389345","text":"import slackweb\nimport trainInfo\nimport configparser\n\n# read ini\ninifile = configparser.ConfigParser()\ninifile.read('conf/config.ini', 'UTF-8')\n\n# webhook url\nurl=inifile.get('settings','webhookurl')\nprint(url)\n# 確認したい路線(list)\ntrain=inifile.get('train','lines').split(',')\nprint(train)\n\nslack = slackweb.Slack(url=url)\nslack.notify(text=trainInfo.request(train))","sub_path":"app/postSlack.py","file_name":"postSlack.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"641801798","text":"import os\nimport pymongo\n\n\nconnection = {}\n\n\ndef _get_connection():\n global connection\n # get the process if\n pid = os.getpid()\n\n # if there is a connection based on the current id use it otherwise create a new one\n if connection and connection.get(pid):\n return connection[pid]\n\n else:\n connection[pid] = pymongo.MongoClient('mongodb+srv://40179863:Deano8505DOD9997@search-engine-40179863-0hak5.gcp.mongodb.net/test?retryWrites=true&w=majority')\n\n return connection[pid]\n\n\ndef connect_to_db(collection=None):\n conn = _get_connection()\n conn = conn['search_engine']\n\n # this is for if there is multiple collections you can specify which one\n if collection:\n return conn[collection]\n # do original setup to create used collection\n if 'list_of_words' not in conn.collection_names():\n conn.create_collection('list_of_words',\n collation={\"locale\": \"en\", \"strength\": 1})\n return conn\n\n\n","sub_path":"database_connect.py","file_name":"database_connect.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"174850932","text":"import os\nimport sys\n\nclass View:\n def clear(self):\n os.system('cls' if os.name == 'nt' else 'clear')\n return self\n\n def header(self, width, section=\"Exercise\"):\n def output(char=\"*\", if_end_with_new_line=False):\n if if_end_with_new_line:\n print(f'\\033[1;32m{char}\\033[0m')\n else:\n print(f'\\033[1;32m{char}\\033[0m', end=\"\")\n\n def output_text(text):\n print(f\"\\033[1;32m{text}\\033[0m\", end=\"\")\n\n def line():\n for i in range(width):\n if i < width - 1:\n output()\n else:\n output(\"*\", True)\n\n def empty_line():\n for i in range(width):\n if i == 0:\n output()\n elif i == width - 1:\n output(\"*\", True)\n else:\n output(\" \")\n\n def empty_line_without_char(line):\n for i in range(line):\n print()\n\n def text(text):\n for i in range(width):\n if i == 0:\n output()\n elif i == width - len(text):\n output(\"*\", True)\n break\n elif i == int((width - len(text))/2) - 1:\n output_text(text)\n else:\n output(\" \")\n\n def main():\n empty_line_without_char(2)\n line()\n empty_line()\n text(\"Pick correct one by definition\")\n text(section)\n empty_line()\n line()\n empty_line_without_char(2)\n\n main()\n return self\n\n def title(self, text):\n print()\n print(f\"\\033[1;32m{text}\\033[0m\")\n print()\n return self\n\n def sentence(self, text, width):\n break_index = 0\n if '@' in text:\n data = text.split(\"@\")\n wordtype = data[0]\n text = data[1]\n print(f\"\\033[1;32m{wordtype} \\033[0m\", end=\"\")\n else:\n print(f\"\\033[1;32m[] \\033[0m\", end=\"\")\n\n for index, char in enumerate(text):\n if index == break_index and index != 0:\n print()\n continue\n if (index % width) == 0 and index != 0:\n if char == \" \":\n print()\n continue\n else:\n for i in range(1, 20):\n try:\n if text[index + i]:\n if text[index + i] == \" \":\n break_index = index + i\n break\n except:\n pass\n print(char, end=\"\")\n print()\n\n return self\n\n def options(self, symbols, choices):\n for symbol, choice in zip(symbols, choices):\n if symbol != \"E\":\n print(f\"\\033[1;32m{symbol}\\033[0m.{choice}\", end=\" \")\n else:\n print(f\"\\033[1;32m{symbol}\\033[0m.{choice}\")\n return self\n\n def evaluate(self, is_right, correct=''):\n if is_right == True:\n print(f\"\\033[1;32mCorrect!\\033[0m\")\n else:\n print(f\"\\033[1;31mWrong! Correct one is {correct}\\033[0m\")\n print()\n return self\n\n def infomation(self,text):\n sys.stderr.write(f\"\\n\\033[1;32m{text}\\033[0m\\n\\n\")\n\n def warning(self, text):\n sys.stderr.write(f\"\\n\\033[1;31m{text}\\033[0m\\n\\n\")\n","sub_path":"view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":3563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"141561327","text":"\"\"\"\nPlayer for the competition\n\"\"\"\nimport time\n\nimport numpy as np\nimport SearchAlgos\nfrom players.AbstractPlayer import AbstractPlayer\n#TODO: you can import more modules, if needed\n\n\nPLAYER_ONE = 1\nPLAYER_TWO = 2\n\nclass Player(AbstractPlayer):\n def __init__(self, game_time, penalty_score):\n AbstractPlayer.__init__(self, game_time, penalty_score) # keep the inheritance of the parent's (AbstractPlayer) __init__()\n self.board = None\n self.pos = None\n self.alpha_beta = SearchAlgos.AlphaBeta(self.utility, self.succ, self.make_move)\n self.fruit = None\n self.my_score = 0\n self.rival_score = 0\n self.sum_fruit = 0\n\n def set_game_params(self, board):\n \"\"\"Set the game parameters needed for this player.\n This function is called before the game starts.\n (See GameWrapper.py for more info where it is called)\n input:\n - board: np.array, a 2D matrix of the board.\n No output is expected.\n \"\"\"\n self.board = board\n pos = np.where(board == 1)\n # convert pos to tuple of ints\n self.pos = tuple(ax[0] for ax in pos)\n\n @staticmethod\n def count_ones(board):\n counter = len(np.where(board == 1)[0])\n return counter\n\n def make_move(self, time_limit, players_score):\n \"\"\"Make move with this Player.\n input:\n - time_limit: float, time limit for a single turn.\n output:\n - direction: tuple, specifing the Player's movement, chosen from self.directions\n \"\"\"\n prev_pos = self.pos\n assert self.count_ones(self.board) == 1\n next_pos = None\n depth = 1\n curr_time = 0\n total_time = 0\n best_min_max_value = float('-inf')\n best_next_pos = None\n while total_time + 3 * curr_time < time_limit:\n start = time.time()\n min_max_value, next_pos = self.alpha_beta.search(self, depth, True, float('-inf'), float('inf'))\n if best_min_max_value < min_max_value:\n best_min_max_value = min_max_value\n best_next_pos = next_pos\n end = time.time()\n curr_time = end - start\n total_time += curr_time\n depth += 1\n i = int(best_next_pos[0] - prev_pos[0])\n j = int(best_next_pos[1] - prev_pos[1])\n self.board[prev_pos] = -1\n self.board[best_next_pos] = 1\n self.pos = best_next_pos\n return (i, j)\n\n\n def set_rival_move(self, pos):\n \"\"\"Update your info, given the new position of the rival.\n input:\n - pos: tuple, the new position of the rival.\n No output is expected\n \"\"\"\n old_pos = np.where(self.board == 2)\n if old_pos is not None:\n self.board[old_pos] = -1\n self.board[pos] = 2\n\n\n\n def update_fruits(self, fruits_on_board_dict):\n \"\"\"Update your info on the current fruits on board (if needed).\n input:\n - fruits_on_board_dict: dict of {pos: value}\n where 'pos' is a tuple describing the fruit's position on board,\n 'value' is the value of this fruit.\n No output is expected.\n \"\"\"\n for e in fruits_on_board_dict:\n if self.board[e] is not ['-1', '1', '2']:\n self.board[e] = fruits_on_board_dict[e]\n self.fruits = fruits_on_board_dict\n\n def succ(self, pos):\n new_list = []\n for d in self.directions: # (1,2)\n i = pos[0] + d[0]\n j = pos[1] + d[1]\n if 0 <= i < len(self.board) and 0 <= j < len(self.board[0]) and (\n self.board[int(i)][int(j)] not in [-1, 1, 2]): # then move is legal\n new_list.append((int(i), int(j)))\n return new_list\n\n def get_player_pos(self, player_number):\n pos = np.where(self.board == player_number)\n # convert pos to tuple of ints\n return pos\n\n def enemyDistance(self, board):\n player_1 = self.get_player_pos(PLAYER_ONE)\n player_2 = self.get_player_pos(PLAYER_TWO)\n diff_x = abs(player_1[0] - player_2[0])\n diff_y = abs(player_1[1] - player_2[1])\n return int(diff_x + diff_y)\n\n def availableMoves(self, board, pos):\n available_moves = 0\n for d in self.directions:\n i = pos[0] + d[0]\n j = pos[1] + d[1]\n if 0 <= i < len(board) and 0 <= j < len(board[0]) and board[int(i)][int(j)] == 0: # then move is legal\n available_moves += 1\n return available_moves\n\n def minDistFromFrame(self, board, pos):\n x = min(len(board) - pos[0], 1 + pos[0])\n y = min(len(board[0]) - pos[1], 1 + pos[1])\n return min(x, y)\n\n def sum_weighted_fruits(self, board, pos):\n weighted_sum = 0\n for i in range(len(board)):\n for j in range(len(board[0])):\n if board[i][j] not in [-1, 1, 2, 0]:\n diff_y = abs(pos[0] - i)\n diff_x = abs(pos[1] - j)\n dist = diff_x + diff_y\n weighted_sum += (1/dist)*board[i][j]\n return weighted_sum\n\n def heuiristic(self, board):\n curr_pos = self.get_player_pos(PLAYER_ONE)\n weighted_fruits_dist = self.sum_weighted_fruits(board, curr_pos)\n enemy_dist = self.enemyDistance(board)\n available_moves = self.availableMoves(board, curr_pos)\n dist_to_frame = 1 / self.minDistFromFrame(board, curr_pos)\n res = weighted_fruits_dist + self.sum_fruit + enemy_dist + 5 * available_moves + dist_to_frame\n return res\n\n def utility(self, player_number):\n pos1 = self.get_player_pos(player_number)\n pos2 = self.get_player_pos(3-player_number)\n neighbors_1 = self.succ(pos1)\n neighbors_2 = self.succ(pos2)\n if len(neighbors_1) == 0 or len(neighbors_2) == 0: # player 1 and 2 cant move\n if len(neighbors_2) > 0: # player 1 cannot move\n if self.my_score - self.penalty_score > self.rival_score:\n return 1\n elif self.my_score - self.penalty_score < self.rival_score:\n return -1\n else:\n return 0\n if len(neighbors_1) > 0: # player 2 cannot move\n if self.my_score > self.rival_score - self.penalty_score:\n return 1\n elif self.my_score < self.rival_score - self.penalty_score:\n return -1\n else:\n return 0\n if self.my_score > self.rival_score:\n return 1\n elif self.my_score < self.rival_score:\n return -1\n else:\n return 0\n return 0\n\n def perform_move(self, new_pos, player_number):\n if self.board[new_pos] not in [-1, 3 - player_number]:\n self.board[self.get_player_pos(player_number)] = -1\n self.board[new_pos] = player_number\n self.pos = new_pos\n if player_number == PLAYER_ONE and self.board[new_pos] > 2:\n self.my_score += self.board[new_pos]\n if player_number == PLAYER_TWO and self.board[new_pos] > 2:\n self.rival_score += self.board[new_pos]\n\n def undo_move(self, old_pos, player_number, old_value):\n self.board[self.get_player_pos(player_number)] = old_value\n self.board[old_pos] = player_number\n self.pos = old_pos\n if old_value > 2:\n if player_number == PLAYER_ONE:\n self.my_score -= old_value\n else:\n self.rival_score -= old_value\n\n def no_more_moves(self, player_number):\n pos1 = self.get_player_pos(1)\n pos2 = self.get_player_pos(2)\n neighbors_1 = self.succ(pos1)\n neighbors_2 = self.succ(pos2)\n if len(neighbors_1) == 0 and len(neighbors_2) == 0: # player 1 and 2 cant move\n return True\n if player_number == PLAYER_ONE:\n if len(neighbors_1) == 0 and len(neighbors_2) != 0: # player 1 lose\n return True\n if len(neighbors_1) != 0 and len(neighbors_2) == 0: #\n return False\n if player_number == PLAYER_TWO:\n if len(neighbors_1) == 0 and len(neighbors_2) != 0: #\n return False\n if len(neighbors_1) != 0 and len(neighbors_2) == 0: #\n return True\n return False\n","sub_path":"hw2/players/CompetePlayer.py","file_name":"CompetePlayer.py","file_ext":"py","file_size_in_byte":8512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"249710115","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('home', '0002_cities'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Vendors',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=100)),\n ('city', models.ForeignKey(to='home.Cities')),\n ('delivers_in', models.ManyToManyField(related_name=b'delivers', null=True, to='home.Cities', blank=True)),\n ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n ]\n","sub_path":"apps/home/migrations/0003_vendors.py","file_name":"0003_vendors.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"375938401","text":"import os\nimport shutil\nfrom bs4 import BeautifulSoup\nimport re\nimport csv\n\n\nclass cfConverter:\n '''\n # Converter html from csv\n '''\n\n # File's path\n src = str()\n dst = str()\n\n # CSV datas\n csv_datas = list()\n\n\n def __init__(self, src, dst):\n\n self.src = src\n self.dst = dst\n\n if os.path.exists(self.dst):\n shutil.rmtree(self.dst)\n shutil.copytree(self.src, self.dst)\n\n\n def extension_convert(self, src_ext, dst_ext):\n\n files = os.listdir(self.dst)\n for file in files:\n if src_ext in file:\n file = os.path.join(self.dst, file)\n ext = file.replace(src_ext, dst_ext)\n os.rename(file, ext)\n\n print(\"Extension is converted.\")\n\n\n def extract_csv_from_html(self, file):\n\n self.csv_datas = list()\n\n html = open(file, 'r')\n soup = BeautifulSoup(html, 'html.parser')\n\n tr_all = soup.find_all(\"tr\")\n\n # seperate study number\n # AB1234-1 => AB1234 / 1\n rgx_sep = r'([A-Z]{2}\\d{4})-(\\d+)'\n\n for tr in tr_all[1:]:\n td_all = tr.find_all(\"td\")\n csv_data = []\n\n for td in td_all:\n td = td.string\n\n # If td tag contain none, td is NULL\n if not td:\n td = \"\"\n\n # If td tag contain Study Code and group\n match = re.match(rgx_sep, td)\n if match:\n study_code = match.group(1)\n csv_data.append(study_code)\n\n study_group = match.group(2)\n stucy_group = int(study_group)\n csv_data.append(stucy_group)\n\n else:\n try:\n td = int(td)\n csv_data.append(td)\n except:\n csv_data.append(td)\n\n self.csv_datas.append(csv_data)\n\n\n\n def csv_convert(self):\n files = os.listdir(self.dst)\n \n for file in files:\n \n if \"html\" in file:\n file = os.path.join(self.dst, file)\n self.extract_csv_from_html(file)\n\n file_name = os.path.splitext(file)[0]\n file_name = file_name + \".csv\"\n\n csv_file = open(file_name, \"w\")\n writer = csv.writer(csv_file, quoting=csv.QUOTE_NONNUMERIC)\n writer.writerows(self.csv_datas)\n\n os.remove(file)\n\n print(\"CSV is converted from html.\")\n","sub_path":"code/module/initial/cfConverter.py","file_name":"cfConverter.py","file_ext":"py","file_size_in_byte":2567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"405395148","text":"import re\n\n# 12 poitns\ndef getGradingCriteria():\n gradeDictionary = {\n # Integers & C,F,K & Within Threshold - Hard coded Threshold\n 'Criteria1': {'input1':'37', 'input2':'C', 'input3':'99', 'input4': '0.50', 'pointsAvailable': 0.5 },\n 'Criteria2': {'input1':'99', 'input2':'F', 'input3':'99', 'input4': '0.50', 'pointsAvailable': 0.5 },\n 'Criteria3': {'input1':'306', 'input2':'K', 'input3':'91', 'input4': '0.50', 'pointsAvailable': 0.5 },\n # Floats & C,F,K & Within Threshold\n 'Criteria4': {'input1':'37.4444', 'input2':'C', 'input3':'98', 'input4': '1.50', 'pointsAvailable': 0.5 },\n 'Criteria5': {'input1':'99.2525', 'input2':'F', 'input3':'98', 'input4': '1.50', 'pointsAvailable': 0.5 },\n 'Criteria6': {'input1':'310.5944', 'input2':'K', 'input3':'98', 'input4': '1.50', 'pointsAvailable': 0.5 },\n # Integers & C,F,K & Outside Threshold - hard coded threshold\n 'Criteria7': {'input1':'96', 'input2':'C', 'input3':'98', 'input4': '0.50', 'pointsAvailable': 0.5 },\n 'Criteria8': {'input1':'96', 'input2':'F', 'input3':'98', 'input4': '0.50', 'pointsAvailable': 0.5 },\n 'Criteria9': {'input1':'96', 'input2':'K', 'input3':'98', 'input4': '0.50', 'pointsAvailable': 0.5 },\n # Floats & C,F,K & Outside Threshold\n 'Criteria10': {'input1':'96.25', 'input2':'C', 'input3':'98', 'input4': '1.50', 'pointsAvailable': 0.5 },\n 'Criteria11': {'input1':'96.25', 'input2':'F', 'input3':'98', 'input4': '1.50', 'pointsAvailable': 0.5 },\n 'Criteria12': {'input1':'96.25', 'input2':'K', 'input3':'98', 'input4': '1.50', 'pointsAvailable': 0.5 },\n }\n return gradeDictionary\n\ndef trimAnswer(answer):\n try:\n answer = answer.strip()\n except Exception as e:\n print(e)\n print('ERROR - COULD NOT TRIM ANSWER')\n return answer\n\n\n# 12 points\n# 2 points for submission\n# integers w/ CFK, correct answer - 1 point each\n# floats w/ CFK, correct answer - 1 point each\n# try/except - 4 points\n\n\n\n# Set the grading criteria\ndef autoGrader(studentDictionary):\n \n for key, value in studentDictionary.items():\n\n pointsEarned = 0.0\n\n try:\n if value['True-False'] == value['student_answer1']:\n pointsEarned += value['pointsAvailable'] \n # if value['Correct-Incorrect'] == value['student_answer2']:\n # pointsEarned += value['pointsAvailable'] / 2.0\n except Exception as e:\n print(e)\n print('ERROR - GRADING')\n \n # add this record's results to the dictionary\n value['autoGrade'] = pointsEarned\n\n return studentDictionary\n\n\ndef addUpPoints(studentDictionary):\n\n pointsAvailable = 0.0\n autoGrade = 0.0\n\n for key, value in studentDictionary.items():\n pointsAvailable += value['pointsAvailable']\n autoGrade += value['autoGrade']\n\n studentDictionary['pointsAvailable'] = pointsAvailable\n studentDictionary['autoGrade'] = autoGrade + 6.0\n\n return studentDictionary","sub_path":"autoGrader/C8-calibrateThermometers/gradeCalibrateThemometers.py","file_name":"gradeCalibrateThemometers.py","file_ext":"py","file_size_in_byte":3032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"366301851","text":"#!/usr/bin/python\n# -*- coding: latin-1 -*-\n\"\"\"Reads data from VPKs and makes adjustments to their filenames.\"\"\"\nimport filecmp\nimport glob\nimport os\nimport struct\nimport sys\nimport zipfile\n\ndef renameFunc(currentMode, existingFormat, newFormat, asciionly):\n \"\"\"Searches for and renames a vita package using file extensions.\"\"\"\n charset = sys.getfilesystemencoding()\n searchString = \"*.\" + existingFormat\n for filename in glob.glob(searchString):\n filename = filename.strip()\n print(\"Renaming '%s'...\" % filename)\n\n if not os.path.exists(filename):\n print(\"Could not find %s, skipping...\" % filename)\n continue\n\n try:\n with zipfile.ZipFile(filename, 'r') as vpk:\n param_path = \"sce_sys/param.sfo\"\n\n if param_path not in vpk.namelist():\n param_path = None\n for subfile in vpk.namelist():\n # Search for param.sfo\n if subfile.endswith(\"param.sfo\"):\n param_path = subfile\n break\n\n if not param_path:\n print(\"Could not find param.sfo in %s, skipping...\" %\n filename)\n break\n\n # Read param.sfo\n paramData = vpk.read(param_path)\n\n keyOffset, dataOffset = struct.unpack(\n \"|:*?\\\\/'\n newTitle = ''.join('_' if (ord(c) > 0x7f and asciionly) else c for c in workingTitle if (\n c not in invalid_chars and ord(c) >= 0x20))\n if currentMode != 2:\n new_filename = \"%s.%s\" % (newTitle, newFormat)\n else:\n filename_no_extension = os.path.splitext(filename)[0]\n print(filename_no_extension)\n new_filename = \"%s.%s\" % (filename_no_extension, newFormat)\n # Check if the files are the same\n # A simple filename comparison does not work because of encoding issues unfortunately\n # And such a check is required for when 2 VPKs are required because\n # they will return the same name\n if currentMode != 3:\n dupe = 1\n while os.path.exists(new_filename) and not filecmp.cmp(filename, new_filename):\n new_filename = \"%s (%d)%s\" % (newTitle, dupe, newFormat)\n dupe += 1\n\n # Changes things like superscripts\n new_filename = new_filename.encode(charset, errors='ignore')\n\n # Rename VPK file\n if currentMode != 3:\n os.rename(filename, new_filename)\n else:\n print(filename + \"-->\" + new_filename)\n\n except zipfile.BadZipfile:\n os.rename(filename, \"FAILED_\" + filename)\n\n\ndef getFormat():\n print(\"(Exmaple input could be vpk or .vpk)\")\n try:\n print(\"Selection\"),\n newFormat = str(raw_input())\n if newFormat[:1] == \".\":\n newFormat = newFormat[1:]\n except:\n print(\"An error occurred, defaulting to .vpk\")\n return newFormat\n\n\ndef getArgs():\n \"\"\"Check arguments and passes back the results.\"\"\"\n renameArg = 0\n printArg = 0\n formatArg = 0\n asciionly = 0\n if len(sys.argv) > 1:\n x = -1\n while len(sys.argv) >= x + 1:\n if sys.argv[x] == \"-h\" or sys.argv[x] == \"--help\":\n print(\"\"\"\n -h/--help: Show this dialog\n -a/--ascii: Produce an asciionly output\n -r/--rename: Rename files based on the param.sfo\n -f/--format: Change format of files\n -p/--print: Only print names of files from param.sfo\n \"\"\")\n sys.exit(0)\n if sys.argv[x] == \"-a\" or sys.argv[x] == \"--ascii\":\n asciionly = 1\n print(\"Setting asciionly on.\")\n if sys.argv[x] == \"-r\" or sys.argv[x] == \"--rename\":\n renameArg = 1\n if sys.argv[x] == \"-f\" or sys.argv[x] == \"--format\":\n formatArg = 1\n if sys.argv[x] == \"-p\" or sys.argv[x] == \"--print\":\n printArg = 1\n print(printArg)\n x += 1\n\n if renameArg == 1 and printArg == 1:\n print(\"Print argument and rename selected, disabling print argument.\")\n printArg = 0\n elif formatArg == 1 and printArg == 1:\n print(\"Print argument and change format selected, disabling print argument\")\n printArg = 0\n\n if renameArg == 1 and formatArg == 1:\n print(\"Renaming and changing format of files\")\n userSel = 2\n if renameArg == 1 and formatArg == 0:\n print(\"Renaming files\")\n userSel = 1\n if renameArg == 0 and formatArg == 1:\n print(\"Changing format of files\")\n userSel = 3\n if printArg == 1:\n userSel = 4\n if renameArg == 0 and formatArg == 0 and printArg == 0:\n userSel = 0\n return [userSel, asciionly]\n\n\ndef userChoice():\n while True:\n userSel, asciionly = getArgs()\n\n if userSel == 0:\n print(\"\"\"\n Please select a mode from below\n\n 1. Rename files (without format change)\n 2. Rename files (with format change)\n 3. Don't rename files and change file format\n 4. Print names of all files based on param.sfo, make no changes\n \"\"\")\n while True:\n try:\n print(\"Selection:\"),\n userSel = int(raw_input())\n if userSel < 5:\n break\n except ValueError:\n print(\"Please enter a number\")\n\n print(userSel)\n print(\"Please enter the format your files are already in\")\n existingFormat = getFormat()\n currentMode = None\n if userSel == 1:\n currentMode = 1\n # currentMode is the same due to currentMode telling the file whether to\n # rename or not\n elif userSel == 2:\n currentMode = 1\n elif userSel == 3:\n currentMode = 2\n elif userSel == 4:\n currentMode = 3\n else:\n print(\"Cannot determine output. Quitting.\")\n if userSel == 2 or userSel == 3:\n print(\"Please enter the new format for your files\")\n newFormat = getFormat()\n print(newFormat)\n print(existingFormat)\n else:\n newFormat = existingFormat\n renameFunc(currentMode, existingFormat, newFormat, asciionly)\n break\n\nif __name__ == \"__main__\":\n userChoice()\n","sub_path":"src/vpkrenamer.py","file_name":"vpkrenamer.py","file_ext":"py","file_size_in_byte":8369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"619301904","text":"from rest_framework import serializers\nfrom rest_framework.serializers import ModelSerializer\n\nfrom api.models import Category, Comment, Genre, Review, Title\n\n\nclass GenreSerializer(ModelSerializer):\n \"\"\"Сериалайзер Жанры\"\"\"\n\n class Meta:\n model = Genre\n exclude = ('id',)\n\n\nclass CategorySerializer(ModelSerializer):\n \"\"\"Сериалайзер Категории\"\"\"\n\n class Meta:\n model = Category\n exclude = ('id',)\n\n\nclass TitleSerializer(ModelSerializer):\n \"\"\"Сериалайзер Произведения\"\"\"\n genre = serializers.SlugRelatedField(\n slug_field='slug',\n queryset=Genre.objects.all(),\n many=True)\n category = serializers.SlugRelatedField(\n slug_field='slug',\n queryset=Category.objects.all())\n\n class Meta:\n model = Title\n fields = '__all__'\n\n\nclass TitleReadSerializer(ModelSerializer):\n \"\"\"Сериалайзер создания и редактирования Произведения\"\"\"\n genre = GenreSerializer(many=True)\n category = CategorySerializer()\n rating = serializers.IntegerField()\n\n class Meta:\n model = Title\n fields = '__all__'\n\n\nclass ReviewSerializer(ModelSerializer):\n \"\"\"Сериалайзер Отзывы\"\"\"\n author = serializers.SlugRelatedField(\n slug_field='username',\n read_only=True)\n\n class Meta:\n model = Review\n fields = (\n 'id',\n 'text',\n 'author',\n 'score',\n 'pub_date',\n )\n\n def validate(self, data):\n if self.context['request'].method == 'POST':\n review = Review.objects.filter(\n author=self.context['request'].user,\n title=self.context['view'].kwargs['title_id'])\n if review.exists():\n raise serializers.ValidationError('Already reviewed')\n return data\n\n\nclass CommentSerializer(ModelSerializer):\n \"\"\"Сериалайзер Комментарии\"\"\"\n author = serializers.SlugRelatedField(\n slug_field='username',\n read_only=True)\n\n class Meta:\n model = Comment\n fields = (\n 'id',\n 'text',\n 'author',\n 'pub_date',\n )\n read_only_fields = ('pub_date',)\n","sub_path":"api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"5915890","text":"import os\r\nimport time\r\nfrom ctypes import windll\r\nfrom tkinter import Tk, Canvas\r\n\r\nimport win32con\r\nimport win32gui\r\nfrom PIL import ImageGrab, ImageFilter, ImageTk\r\n\r\n\r\nwindll.shcore.SetProcessDpiAwareness(1)\r\n\r\nroot = Tk()\r\n\r\nroot.protocol(\"WM_DELETE_WINDOW\", lambda: os.kill(os.getpid(), 0))\r\n\r\nimage = ImageGrab.grab(\r\n (0, 0, root.winfo_screenwidth(), root.winfo_screenheight()),\r\n True\r\n)\r\ntkim = ImageTk.PhotoImage(image)\r\n\r\nroot.wm_attributes(\"-fullscreen\", True)\r\n\r\ncanvas = Canvas(root, highlightthickness=0)\r\nid_ = canvas.create_image(0, 0, image=tkim, anchor=\"nw\")\r\ncanvas.pack(fill=\"both\", expand=True)\r\n\r\n# hwnd = win32gui.FindWindow(None, \"Your window title\") # Getting window handle\r\n# hwnd = root.winfo_id() # getting hwnd with Tkinter windows\r\n# hwnd = root.GetHandle() getting hwnd with wx windows\r\n# lExStyle = win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE)\r\n# lExStyle |= win32con.WS_EX_TRANSPARENT | win32con.WS_EX_LAYERED\r\n# win32gui.SetWindowLong(hwnd, win32con.GWL_EXSTYLE , lExStyle )\r\n\r\n# cimage = canvas.create_image(0, 0, image=tkim)\r\nims = []\r\ntkims = []\r\nfor i in range(0, 120, 1):\r\n im = image.copy()\r\n ims.append(im.filter(ImageFilter.GaussianBlur(radius=i/4)))\r\n tkims.append(ImageTk.PhotoImage(ims[-1]))\r\n\r\nroot.protocol(\"WM_DELETE_WINDOW\", lambda: None)\r\n\r\nfor tkimage in tkims:\r\n canvas.itemconfig(id_, image=tkimage)\r\n # cimage.config(image=tkimage)\r\n # time.sleep(0.1)\r\n root.update()\r\n root.update_idletasks()\r\n\r\n\r\ndef reverse():\r\n tkims.reverse()\r\n for tkimage in tkims:\r\n canvas.itemconfig(id_, image=tkimage)\r\n # cimage.config(image=tkimage)\r\n # time.sleep(0.1)\r\n root.update()\r\n root.update_idletasks()\r\n root.destroy()\r\n\r\n\r\nroot.protocol(\"WM_DELETE_WINDOW\", reverse)\r\n\r\n# for i in range(1, 21, 2):\r\n# im = image.copy()\r\n# im = im.filter(ImageFilter.GaussianBlur(radius=i))\r\n# tkim = ImageTk.PhotoImage(im)\r\n# canvas.itemconfig(id_, image=tkim)\r\n# # time.sleep(0.01)\r\n# root.update()\r\n# root.update_idletasks()\r\n\r\nroot.mainloop()\r\n","sub_path":"test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":2085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"469276995","text":"from td_db_client import Client\nimport pandas as pd\nimport datetime\nimport time\n\n\ntdc = Client()\nsymbol = 'AAPL'\n\nquery_stocks = \"SELECT stock.id, stock.symbol FROM stock WHERE stock.sector IN ('Technology', 'Health Care') AND stock.id NOT IN (SELECT DISTINCT stock_id FROM ohlc_data) AND symbol NOT SIMILAR TO %s\"\n\n# Get the list of stocks\nstocks = tdc.run_select_query_with_param(query_stocks, '%(\\^|/)%')\nsdt = datetime.datetime(year=2020, month=12, day=1)\ni = 1\nfor s in stocks:\n print (\"Saving price history for {}\".format(s[1]))\n tdc.save_price_history(s[0], sdt, s[1])\n i += 1","sub_path":"waldren/base/load_standard_price_data.py","file_name":"load_standard_price_data.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"259231322","text":"# -*- coding: utf-8 -*-\r\n'''\r\nCreated on 9 mai 2017\r\n\r\n@author: ferreb\r\n'''\r\nimport re\r\n\r\nfrom switchhandler.device.executable.command.command_base import CommandBase\r\nfrom switchhandler.device.protocol.expect.switch.vendor.cisco import CATEGORY_CISCO\r\nfrom switchhandler.utils.decorator.class_register import registered_class\r\nfrom switchhandler.utils.net_tools import convert_mac_cisco\r\n\r\n\r\n@registered_class(category=CATEGORY_CISCO, registered_name=\"port_from_mac\")\r\nclass ViewPortFromMac(CommandBase):\r\n '''visualiser le port à l'quel une mac est associé\r\n\r\n :param mac: la mac à trouver\r\n :type mac: str\r\n\r\n :param ip: L'ip à pringuer pour l'apprentissage de la mac\r\n :type ip: str\r\n :default ip: None\r\n\r\n\r\n Commandes exécutées::\r\n\r\n ViewPortFromMac(mac='aa:bb:cc:dd:ee:ff', ip='127.0.0.1')\r\n\r\n prompt# ping 127.0.0.1\r\n prompt# show mac address-table | include aa:bb:cc:dd:ee:ff\r\n prompt#\r\n\r\n '''\r\n\r\n def define_argument(self):\r\n self.add_argument(name='mac', required=True)\r\n self.add_argument(name='ip', default=None)\r\n\r\n def do_run(self):\r\n self.switch.execute('end')\r\n\r\n self.mac = convert_mac_cisco(self.mac)\r\n\r\n if self.ip is not None:\r\n self.switch.execute('ping', ip=self.ip, repeat=3)\r\n self.switch.expect_prompt()\r\n\r\n self.switch.send_line(\"show mac address-table | include {}\".format(self.mac))\r\n self.switch.expect_prompt()\r\n\r\n match = re.search(\r\n '^[ ]*([0-9][0-9]*)[ ]*([^ ]*)[ ]*([^ ]*)[ ]*([^ ^\\n]*)$', self.switch.before(), re.MULTILINE)\r\n\r\n if match:\r\n return match.group(4)\r\n else:\r\n return \"\"\r\n","sub_path":"switchhandler/device/protocol/expect/switch/vendor/cisco/view/view_port_from_mac.py","file_name":"view_port_from_mac.py","file_ext":"py","file_size_in_byte":1701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"306868983","text":"#!/usr/bin/env python\r\n\r\n\"\"\"\"------------------------------------------------------------------------------\r\nname: \t\tsplit_feature_class.py\r\narguments/inputs: No. of polylines for each feature class\r\n\t\t\t \r\nversion: python 2.7\r\n\r\ndependencies: \t\tInput Geodatabase that has a feature class of polyline and a feature class of point\r\n\t\t\t \r\ndescription: \tThis script splits a polyline feature class of large volume into multiple feature classes of polylines of small volume, \r\nwhich are then stored in separate geodatabases with the point feature class. Finally it zipped all those geodatabases and delete the unzipped geodatabases.\r\n-------------------------------------------------------------------------------\"\"\"\r\n# Import os and sys python modules which allow python to use file based functions\r\n# and utilities.\r\nimport os,sys\r\nimport shutil\r\nfrom shutil import rmtree,make_archive\r\nfrom zipfile import ZipFile\r\nfrom glob import glob\r\n\r\n# Import ArcGIS modules\r\nimport arcpy \r\n\r\n# Where Input Geodatabase with feature classes, python scripts and condor\r\n# submission file resides\r\nworkingFolderPath = \"\" \r\n\t\r\n# A temporary output folder created to store temporary geodatabase\r\ntempFolderPath = \"temp\\\\\" \t\r\n\r\n\r\n# Ask user to input geodatabase file name, the polyline featureclass, and\r\n# the points feature class. Also, ask the user how many observations\r\n# for each subset of the polyline feacture class. \r\ninGeodatabase = raw_input('Enter filename of geodatabase: ')\r\nif not inGeodatabase:\r\n\tinGeodatabase = \"Routes4_Pline.gdb\"\r\n\t\r\nif (os.path.isdir(inGeodatabase) == False):\r\n\tprint('Geodatabase, %s can not be found' % inGeodatabase)\r\n\tquit(-1)\r\nelse:\r\n\t# Set the working Geodatabase\r\n\tarcpy.env.workspace = workingFolderPath + inGeodatabase\r\n\r\n# Input polyline feature class.\r\npolylineFC = raw_input('Enter Polyline feature class name: ')\r\nif not polylineFC:\r\n\tpolylineFC = \"Routes4_Pline\"\r\n\t\r\nif arcpy.Exists(polylineFC):\r\n\t# Get total number of entries in poly-line feature class.\r\n\tresult = arcpy.GetCount_management(polylineFC)\r\n\tnumObservations = int(result.getOutput(0))\r\nelse:\r\n\tprint('Feature Class, %s does not exist in %s' % (polylineFC,inGeodatabase))\r\n\tquit(-1)\r\n\r\npointsFC = raw_input('Enter Points feature class name: ')\r\nif not pointsFC:\r\n\tpointsFC = \"Station_Points\"\r\n\t\r\nif (arcpy.Exists(pointsFC) == False):\r\n\tprint('Feature Class, %s does not exist in %s' % (pointsFC,inGeodatabase))\r\n\tquit(-1)\r\n\r\n# Get a count of the observations\r\nstrSubsetEntries = raw_input('Enter number of entries per polyline subset: ')\r\nif not strSubsetEntries:\r\n\tsubsetEntries = 5000\r\nelse:\r\n subsetEntries = int(strSubsetEntries)\r\n\r\n\r\n###############################################################################\r\n# Create subset feature classes \r\n\r\nprint('total count of feature class, %s = %i' % (polylineFC, numObservations))\r\n\r\n# No. of feature classes after spliting (i.e. integer)\r\n# The '//' divides the numbers and returns a number without the remainder.\r\nnumNewFeatureClasses = (numObservations // subsetEntries) + 1 \r\n\r\n\r\nprint(\"numNewFeatureClasses for feature class, %s = %i\" % (polylineFC,numNewFeatureClasses))\r\n\r\n# Set flag, deleteAll to False.\r\nif (len(sys.argv) > 1):\r\n\tif (sys.argv[1].lower() == \"del\"):\r\n\t\tdeleteExisting = \"del\"\r\nelse:\r\n\tdeleteExisting = \"\"\r\n\r\n\r\n# start loop to create subsets...\r\nfor i in range(1, (numNewFeatureClasses + 1)):\r\n\r\n\t# Set up the SQL Where clause that will be used to select certain rows of the large feature class.\r\n\tsubsetFC = polylineFC + '_' + str(i)\r\n\tprint('subsetFC = %s' % subsetFC)\r\n\toutGeodatabase = subsetFC + '.gdb'\r\n\t\r\n\tobsIdx = (i-1) * subsetEntries\r\n\twhereClause = '\"OBJECTID_1\" > ' + str(obsIdx) + ' AND \"OBJECTID_1\" <= ' + str((obsIdx + subsetEntries))\r\n\tprint('whereClause = %s' % whereClause)\r\n\r\n\tsubsetExists = arcpy.Exists(subsetFC)\r\n\tif subsetExists or (deleteExisting == \"del\"):\r\n\t\tif ((deleteExisting != \"nall\") and (deleteExisting != \"yall\") and (deleteExisting != \"del\")):\r\n\t\t\tprint('\\nThis subset feature class already exists in %s. Do you \\\r\nwish to recreate it?' % inGeodatabase)\r\n\t\t\tprint('y/n/yall/nall/del...')\r\n\t\t\tprint('\"yall\" will recreate this and all other existing \\\r\nsubsets without prompting')\r\n\t\t\tprint('\"nall\" will not delete nor recreate this and all other existing \\\r\nsubsets.')\r\n\t\t\tprint('\"del\" will only delete and not recreate this and all other \\\r\nexisting subsets.')\r\n\t\t\tdeleteExisting = raw_input('\\n? :').lower()\r\n\t\tif ((deleteExisting == \"y\") or (deleteExisting == \"yall\") or (deleteExisting == \"del\")):\r\n\t\t\t# Delete the subset feature class \r\n\t\t\tprint('Deleting subset, %s...' % subsetFC)\r\n\t\t\tif (arcpy.Exists(subsetFC)):\r\n\t\t\t\tarcpy.Delete_management(subsetFC)\r\n\t\t\t\tsubsetExists = False\r\n\t\t\tif (os.path.isdir(tempFolderPath + outGeodatabase) == True):\r\n\t\t\t\trmtree(tempFolderPath + outGeodatabase)\r\n\t\t\tif (os.path.isfile(outGeodatabase + '.zip') == True):\r\n\t\t\t\tos.unlink(outGeodatabase + '.zip')\r\n\tif ((subsetExists == False) and (deleteExisting != \"del\")):\r\n\t\t# Create new feature class from range of rows.\r\n\t\tprint('Creating subset feature class...')\r\n\t\tarcpy.Select_analysis(polylineFC, subsetFC, whereClause)\r\n\r\n\t\t# Create Geodatabase\r\n\t\tprint('Creating new geodatabase, %s' % outGeodatabase)\r\n\t\tarcpy.CreateFileGDB_management(tempFolderPath, outGeodatabase)\r\n\r\n\t\t# Export newly created feature class and feature class: Station_Points\r\n\t\tprint('Exporting feature classes, %s and %s' % (subsetFC, pointsFC))\r\n\t\tarcpy.FeatureClassToGeodatabase_conversion([subsetFC, pointsFC], (tempFolderPath + outGeodatabase))\r\n\t\r\n\t\t# Delete newly created subset feature class from inGeodatabase\t\t\r\n\t\tarcpy.Delete_management(subsetFC)\r\n\t\t\r\n\t\t# Zip up newly created geodatabase\r\n\t\tz = outGeodatabase\r\n\t\tprint('zipping %s...' % z)\r\n\t\tmake_archive('%s' % z, 'zip', tempFolderPath, z) #Archiving zipped geodatabases into working directory\r\n\t\tprint('done zipping %s' % z)\r\n\t\r\n# Delete unzipped geodatabase from temporary output folder\r\nos.chdir(tempFolderPath)\r\nprint('Removing unzipped Files in temporary directory')\r\nfor e in glob('*.gdb'): \r\n rmtree(e)\r\n\r\n\r\n\r\n","sub_path":"split_feature_class.py","file_name":"split_feature_class.py","file_ext":"py","file_size_in_byte":6082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"566127424","text":"import fnmatch\nimport os\nimport smtplib\nimport sys\n\nimport requests\n\nsys.path.append('/Users/alan/')\nfrom secret import *\nfrom email.message import EmailMessage\n\n\n#\n# name: rfc_stats\n# arguments: none\n# returns: dictionary of rfc stats found in local rfc directory\n# including:\n# total number of rfc's locally\n# number of text rfc's\n# number of pdf rfc's\n# highest rfc number\n# number of missing rfc's\n# ------------------------------------------------------------------------------\n#\ndef rfc_stats():\n local_rfc_numbers = []\n rfcs = \\\n {\n 'ietf_url': \"https://www.ietf.org/rfc\",\n 'rfc_dir': \"/Users/alan/Documents/RFC's\"\n }\n\n for fn in os.listdir(rfcs['rfc_dir']):\n if fnmatch.fnmatch(fn, \"rfc*\"):\n dot = fn.find('.')\n number = fn[3:dot]\n local_rfc_numbers.append(int(number))\n if fnmatch.fnmatch(fn, \"*.txt\"):\n rfcs['no_txt'] = rfcs.get('no_txt', 0) + 1\n if fnmatch.fnmatch(fn, \"*.pdf\"):\n rfcs['no_pdf'] = rfcs.get('no_pdf', 0) + 1\n\n rfcs['highest_no'] = max(local_rfc_numbers)\n rfcs['no_of_rfcs'] = len(local_rfc_numbers)\n rfcs['missing'] = [x for x in range(1, rfcs['highest_no']) if\n x not in local_rfc_numbers]\n rfcs['no_missing_rfcs'] = len(rfcs['missing'])\n\n return rfcs\n\n\ndef download_rfcs(rfcs):\n rfcs['missing'] += range(rfcs['highest_no'] + 1, rfcs['highest_no'] + 21)\n\n for number in rfcs['missing']:\n rfc = requests.get(f'{rfcs[\"ietf_url\"]}/rfc{number}.txt',\n allow_redirects=True)\n if rfc.status_code != 404:\n open(f'{rfcs[\"rfc_dir\"]}/rfc{number:05}.txt', 'wb+').write(\n rfc.content)\n print(f\" ADDED: rfc{number}.txt\")\n\n\ndef summary(before, after):\n return f\"\"\"\n\n before after diff\n -----------------------------------------\n number of rfc's:{before['no_of_rfcs']:>8}{after['no_of_rfcs']:>8}{(after['no_of_rfcs'] - before['no_of_rfcs']):>7}\n text versions:{before['no_txt']:>8}{after['no_txt']:>8}{(after['no_txt'] - before['no_txt']):>7}\n pdf versions:{before['no_pdf']:>8}{after['no_pdf']:>8}{(after['no_pdf'] - before['no_pdf']):>7}\n no missing:{before['no_missing_rfcs']:>8}{after['no_missing_rfcs']:>8}{(before['no_missing_rfcs'] - after['no_missing_rfcs']):>7}\n last rfp no:{before['highest_no']:>8}{after['highest_no']:>8}{(after['highest_no'] - before['highest_no']):>7}\n \n \n \"\"\"\n\n\ndef email_summary(body):\n msg = EmailMessage()\n msg['Subject'] = 'ACRU | Summary'\n msg['From'] = f\"Lbot <{GMUSER}>\"\n msg['To'] = 'alan@claughan.com'\n msg.set_content(body)\n msg.add_alternative(f\"\"\"\\\n \n \n \n

Request For Comment Updater [v1.3]

\n

{body}
\n \n \n \"\"\", subtype='html')\n\n with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:\n smtp.login(GMUSER, GMPASS)\n\n smtp.send_message(msg)\n\n\ndef main():\n rfc_stats_before = rfc_stats()\n download_rfcs(rfc_stats_before)\n rfc_stats_after = rfc_stats()\n summary_msg = summary(rfc_stats_before, rfc_stats_after)\n print(summary_msg)\n email_summary(summary_msg)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":" main.py","file_name":" main.py","file_ext":"py","file_size_in_byte":3474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"215016535","text":"# -*- coding: latin-1 -*-\n'''GET the results of a search from an ENCODE server'''\nimport requests, json, os, sys, csv\nsys.path.append('/home/evansj/me/projects/me/galaxy_scraper/')\nimport galaxy_scraper\n\n# Force return from the server in JSON format\nHEADERS = {'accept': 'application/json'}\n\ndef getBiosamplesOld(cellName):\n \"\"\" Simple search misses some things. \"\"\"\n URL = \"https://www.encodeproject.org/search/?searchTerm=%s&limit=all\" % (cellName,)\n response = requests.get(URL, headers=HEADERS)\n response_json_dict = response.json()\n\n biosampleInfo = []\n for entry in response_json_dict['@graph']:\n if 'biosample_type' in entry:\n ls = [entry[x] for x in ('accession',\n 'description',\n '@id')]\n biosampleInfo.append(ls)\n return biosampleInfo\n\ndef getBiosamplesNew(searchTerm):\n \"\"\" Get biosample IDs and treatments for this search term.\n Can miss things grabbed by simple search.\n \"\"\"\n url = \"https://www.encodeproject.org/search/?searchTerm=%s&type=Biosample&format=json&limit=all\" % (searchTerm,)\n response = requests.get(url, headers=HEADERS)\n response_json_dict = response.json()\n sampleIds = []\n for entry in response_json_dict['@graph']:\n ls = [entry[x] for x in ('accession',\n 'description',\n '@id')]\n sampleIds.append(ls)\n return sampleIds\n\ndef searchBiosamples(searchTerms):\n \"\"\"Use simple and advanced biosample search to get a list\n of biosample IDs.\n \"\"\"\n finalLs = []\n seen = {}\n for searchTerm in searchTerms:\n newBiosamples = getBiosamplesNew(searchTerm)\n oldBiosamples = getBiosamplesOld(searchTerm)\n for ls in (newBiosamples, oldBiosamples):\n for item in ls:\n key = ':'.join(item)\n if not key in seen:\n finalLs.append(item)\n seen[key] = True\n return finalLs\n\ndef searchExperiments(cellNames):\n \"\"\"Use simple search to get experiments.\"\"\"\n experimentInfo = []\n for cellName in cellNames:\n URL = \"https://www.encodeproject.org/search/?searchTerm=%s&limit=all\" % (cellName,)\n\n # GET the search result\n response = requests.get(URL, headers=HEADERS)\n\n # Extract the JSON response as a python dict\n response_json_dict = response.json()\n\n for entry in response_json_dict['@graph']:\n if '@type' in entry:\n if entry['@type'][0] == 'Experiment':\n ls = [entry[x] for x in ('description',\n 'biosample_term_name',\n 'assay_term_name',\n 'accession',\n )]\n experimentInfo.append(ls)\n return experimentInfo\n\ndef appendExperimentsForBiosample(biosampleID, experiments):\n \"\"\"Search for experiments for this biosample.\"\"\"\n url = \"https://www.encodeproject.org/search/?searchTerm=%s&type=Experiment&format=json&limit=all\" % (biosampleID,)\n response = requests.get(url, headers=HEADERS)\n response_json_dict = response.json()\n for entry in response_json_dict['@graph']:\n ls = [entry[x] for x in ('description',\n 'biosample_term_name',\n 'assay_term_name',\n 'accession',\n )]\n experiments.append(ls)\n\ndef mkUniqExperiments(experimentLs):\n ls = []\n seen = {}\n for item in experimentLs:\n key = ':'.join(item)\n if not key in seen:\n seen[key] = True\n ls.append(item)\n return ls\n\ndef getExperiments(searchTerms):\n biosamples = searchBiosamples(searchTerms)\n\n # basic search for experiments\n experimentLs = searchExperiments(searchTerms)\n # search for experiments by biosample\n for sample, desc, sampleID in biosamples:\n appendExperimentsForBiosample(sample, experimentLs)\n return mkUniqExperiments(experimentLs)\n\ndef mkDownloadCmdsNew(paths, outDir):\n cmds = {}\n for afile in paths:\n outPath = outDir + afile.split('/')[-1]\n if not os.path.exists(outPath):\n cmd = 'wget \"https://www.encodeproject.org%s\" -O %s' % (afile, outPath)\n cmds[afile] = cmd\n return cmds\n\n# def downloadK562():\n# \"\"\"Can I get all of k562?\"\"\"\n# outDir = '/home/evansj/me/projects/blobel/download_encode/data/encode/gz/'\n# searchTerm = 'k562'\n# biosamples = searchBiosamples(searchTerm)\n# experiments = []\n# for sample, desc, sampleID in biosamples:\n# getExperimentsNew(sample, experiments)\n# fastqs = {}\n# for experiment in experiments:\n# getFastqNew(experiment, fastqs)\n# downloadCmds = mkDownloadCmdsNew([fastqs[x][0] for x in fastqs], outDir)\n# processLimit = 5\n# galaxy_scraper.loopDownload(downloadCmds, processLimit)\n\ndef getFastq(experiment):\n \"\"\"For experiment ID, get fastqs\"\"\"\n URL = \"https://www.encodeproject.org/search/?type=file&dataset=/experiments/%s/&file_format=fastq&format=json&frame=object&limit=all\" % (experiment,)\n\n # GET the search result\n response = requests.get(URL, headers=HEADERS)\n\n # Extract the JSON response as a python dict\n response_json_dict = response.json()\n\n # Print the object\n fastqInfo = []\n for entry in response_json_dict['@graph']:\n ls = (entry['accession'], entry['href'], entry['run_type'])\n fastqInfo.append(ls)\n return fastqInfo\n\ndef getFiles():\n files = set()\n terms = {'g1e-er4':('g1e-er4',),\n 'sapiens+erythroblast':('sapiens+erythroblast',),\n 'k562':('k562', 'k562+sapiens', 'k562+sapiens+gata1'),\n 'erythroblast+embryonic':('erythroblast+embryonic',),\n 'mel+mus+musculus':('mel+mus+musculus', 'Erythroleukemia+gata1'),\n }\n for term in terms:\n experiments = getExperiments(terms[term])\n for exp in experiments:\n if exp[2] == 'ChIP-seq':\n acc = exp[-1]\n for f in getFastq(acc):\n files.add(f[1])\n return files\n\ndef getRnaFiles(useIDs):\n files = set()\n g1eEr4Exps = getExperiments('g1e-er4')\n for exp in g1eEr4Exps:\n if exp[2] == 'RNA-seq':\n acc = exp[-1]\n for f in getFastq(acc):\n id = f[1].split('/')[-1].split('.')[0]\n if id in useIDs:\n files.add( f[1] )\n erythroblastSamples = getBiosamples('g1e-er4')\n for sample in erythroblastSamples:\n biosample = sample[0]\n erythroExps = getExperiments(biosample)\n for exp in erythroExps:\n if exp[2] == 'RNA-seq':\n acc = exp[-1]\n for f in getFastq(acc):\n id = f[1].split('/')[-1].split('.')[0]\n if id in useIDs:\n files.add( f[1] )\n\n erythroblastSamples = getBiosamples('erythroblast+embryonic')\n for sample in erythroblastSamples:\n biosample = sample[0]\n erythroExps = getExperiments(biosample)\n for exp in erythroExps:\n if exp[2] == 'RNA-seq':\n acc = exp[-1]\n for f in getFastq(acc):\n id = f[1].split('/')[-1].split('.')[0]\n if id in useIDs:\n files.add( f[1] )\n\n term = 'Erythroleukemia+gata1'\n erythroblastSamples = getBiosamples(term)\n for sample in erythroblastSamples:\n biosample = sample[0]\n erythroExps = getExperiments(biosample)\n for exp in erythroExps:\n acc = exp[-1]\n for f in getFastq(acc):\n id = f[1].split('/')[-1].split('.')[0]\n if id in useIDs:\n files.add(f[1])\n\n term = 'mel+mus+musculus'\n erythroblastSamples = getBiosamples(term)\n for sample in erythroblastSamples:\n biosample = sample[0]\n erythroExps = getExperiments(biosample)\n for exp in erythroExps:\n if exp[2] == 'RNA-seq':\n acc = exp[-1]\n for f in getFastq(acc):\n id = f[1].split('/')[-1].split('.')[0]\n if id in useIDs:\n files.add(f[1])\n return files\n\ndef mkRnaseqTable(outFile):\n lines = set()\n \n term = 'g1e-er4'\n g1eEr4Exps = getExperiments(term)\n for exp in g1eEr4Exps:\n if exp[2] == 'RNA-seq':\n acc = exp[-1]\n for f in getFastq(acc):\n ls = (term, exp[2], exp[0], f[1].split('/')[-1].split('.')[0])\n lines.add(ls)\n erythroblastSamples = getBiosamples(term)\n for sample in erythroblastSamples:\n biosample = sample[0]\n erythroExps = getExperiments(biosample)\n for exp in erythroExps:\n if exp[2] == 'RNA-seq':\n acc = exp[-1]\n for f in getFastq(acc):\n ls = (term, exp[2], exp[0],\n f[1].split('/')[-1].split('.')[0])\n lines.add(ls)\n\n term = 'erythroblast+embryonic'\n erythroblastSamples = getBiosamples(term)\n for sample in erythroblastSamples:\n biosample = sample[0]\n erythroExps = getExperiments(biosample)\n for exp in erythroExps:\n if exp[2] == 'RNA-seq':\n acc = exp[-1]\n for f in getFastq(acc):\n ls = (term, exp[2], exp[0],\n f[1].split('/')[-1].split('.')[0])\n lines.add(ls)\n\n term = 'Erythroleukemia+gata1'\n erythroblastSamples = getBiosamples(term)\n for sample in erythroblastSamples:\n biosample = sample[0]\n erythroExps = getExperiments(biosample)\n for exp in erythroExps:\n acc = exp[-1]\n for f in getFastq(acc):\n ls = ('mel+mus+musculus', exp[2], exp[0],\n f[1].split('/')[-1].split('.')[0])\n lines.add(ls)\n\n term = 'mel+mus+musculus'\n erythroblastSamples = getBiosamples(term)\n for sample in erythroblastSamples:\n biosample = sample[0]\n erythroExps = getExperiments(biosample)\n for exp in erythroExps:\n if exp[2] == 'RNA-seq':\n acc = exp[-1]\n for f in getFastq(acc):\n ls = (term, exp[2], exp[0],\n f[1].split('/')[-1].split('.')[0])\n lines.add(ls)\n\n with open(outFile, 'w') as fout:\n ls = ('cell', 'experimentType', 'desc', 'id')\n print('\\t'.join(ls), file=fout)\n for ls in lines:\n print('\\t'.join(ls), file=fout)\n \ndef mkDownloadCmds(files, outDir):\n cmds = {}\n for afile in files:\n outPath = outDir + afile.split('/')[-1]\n if not os.path.exists(outPath):\n cmd = 'wget \"https://www.encodeproject.org/%s\" -O %s' % (afile, outPath)\n cmds[afile] = cmd\n return cmds\n\ndef downloadData():\n outDir = '/home/evansj/me/projects/blobel/download_encode/data/encode/gz/'\n files = getFiles()\n downloadCmds = mkDownloadCmds(files, outDir)\n processLimit = 4\n galaxy_scraper.loopDownload(downloadCmds, processLimit)\n\ndef printTable(outFile):\n lines = set()\n terms = {'g1e-er4':('g1e-er4',),\n 'sapiens+erythroblast':('sapiens+erythroblast',),\n 'k562':('k562', 'k562+sapiens', 'k562+sapiens+gata1',\n 'k562+sapiens+gata1', 'K-562', 'ENCBS118YJZ'\n 'ENCFF002ECW', 'ENCBS684JMW', \n 'ENCSR000DOD', 'ENCSR000BRR',\n 'ENCSR000BNN', 'ENCSR000BKM', 'ENCSR000BKM',\n 'K562',\n ),\n 'erythroblast+embryonic':('erythroblast+embryonic',),\n 'mel+mus+musculus':('mel+mus+musculus', 'Erythroleukemia+gata1'),\n }\n for term in terms:\n experiments = getExperiments(terms[term])\n for exp in experiments:\n if exp[2] == 'ChIP-seq':\n acc = exp[-1]\n for f in getFastq(acc):\n ls = (term, exp[2], exp[0], f[1].split('/')[-1].split('.')[0])\n lines.add(ls)\n\n with open(outFile, 'w') as fout:\n ls = ('cell', 'experimentType', 'desc', 'id')\n print('\\t'.join(ls), file=fout)\n for ls in lines:\n print('\\t'.join(ls), file=fout)\n\ndef downloadRnaseq(sampleFile):\n outDir = '/home/evansj/me/projects/blobel/encode_vars/data/encode/gz/'\n useIDs = {}\n with open(sampleFile) as f:\n reader = csv.DictReader(f, delimiter='\\t')\n for row in reader:\n useIDs[row['id']] = True\n files = getRnaFiles(useIDs)\n downloadCmds = mkDownloadCmds(files, outDir)\n # for cmd in downloadCmds:\n # print( downloadCmds[cmd] )\n processLimit = 4\n galaxy_scraper.loopDownload(downloadCmds, processLimit)\n\ndef checkrna():\n with open('../work/rnaseqTable2.revoked.use') as f:\n reader = csv.DictReader(f, delimiter='\\t')\n for row in reader:\n if row['cell'] in ('g1e-er4', 'erythroblast+embryonic', 'mel+mus+musculus'):\n apath = '/home/evansj/me/projects/blobel/encode_vars/data/encode/gz/%s.fastq.gz' % (row['id'],)\n if not os.path.exists(apath):\n print(row)\n\nif __name__ == \"__main__\":\n #downloadData()\n printTable('../work/sampleData7')\n\n#downloadData()\n# fs = getRnaFiles()\n# for f in fs:\n# print(f)\n#downloadRnaseq('../work/rnaseqTable2.revoked.use')\n#mkRnaseqTable('../work/rnaseqTable2')\n#checkrna()\n\n\n","sub_path":"code/scripts/downloadData.py","file_name":"downloadData.py","file_ext":"py","file_size_in_byte":13745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"405679008","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport math\n\n\ndef main():\n INPUTS = [\n (8, ),\n (8, 2),\n (0.5, 2),\n ]\n\n for input in INPUTS:\n print(\"log{!s:8} = {:.2f}\".format(input, math.log(*input)))\n\n\nif __name__ == '__main__':\n main()","sub_path":"builtin/004.math/exponents_and_logarithms/math_log.py","file_name":"math_log.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"422907990","text":"#/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"Instrument setting.\n\"\"\"\n\n__author__ = 'gumeng'\n\n# hdf l1b file regx patten\nL1B = '^FY3C_MWHSX_GBAL_L1_\\d{8}_\\d{4}_\\d{3}KM_MS\\.HDF\\.OK$'\n\n# hdf string prefix patten about L1B\nL0 = None\nL1B_OBC = None #'FY3C_MWTSX_GBAL_L1_%s_%s_OBCXX_MS.HDF'\nL1B_GEO = None\n\n# hdf obc file regx patten\nOBC = '^FY3C_MWHSX_GBAL_L1_\\d{8}_\\d{4}_OBCXX_MS\\.HDF\\.OK$'\n\nsim_ok = '^FY3C_MWHSX_GBAL_L1_\\d{8}_\\d{4}_\\d{3}KM_MS\\.HDF\\.SIM\\.OK$'\npre_year = len('FY3C_MWHSX_GBAL_L1_')\npre_mon = len('FY3C_MWHSX_GBAL_L1_2013')\npre_hour = len('FY3C_MWHSX_GBAL_L1_20131201_')\n\n# channels for your instrument\nchannels = 15\n\n# pixels for your instrument\npixels = 98\n\n# scans attribute name in HDF\nscans_name = 'Count_scnlines'\n\n\n#data_db = 'FY3C_MWTS_V2'\n\n# src: l0, l1b, l1b_obc, l1b_geo.\n# dims: 3 means that is like channels*scans*pixel, \n# so, we should create table like: obs_bt1, obs_bt2, obs_bt3, obs_bt4\n# and, 'rank': {'x': 'scan', 'y': 'pixel', 'z': 'channel'}\n# means: 3-dim data fmt is scan*pixel*channel\n# db_dtype: datatype in db. we just save %.4f when float: 1.23456 --> 1.2345\n# but float-->int is recommended!\n# factor: be used ONLY if hdf_datatype != db_datatype, such as:\n# int = int( float * 100 )\n# idx MUST start from 1.\n\n# latitude sds, we can calc ascend or descend orbit.\nlat_sds_to_db = {\n 1: {'src': 'l1b', \n 'sds': 'Geolocation/Latitude', 'hdf_dtype': 'float', 'dims': 2, \n 'db_field': 'lat', 'db_dtype': 'int', 'factor': 100} \n}\n\n# l1b sds.\nsds_to_db = {\n 1: {'src': 'l1b', \n 'sds': 'Geolocation/Longitude', 'hdf_dtype': 'float', 'dims': 2, \n 'db_field': 'lon', 'db_dtype': 'int', 'factor': 100},\n 2: {'src': 'l1b', \n 'sds': 'Geolocation/SensorZenith', 'hdf_dtype': 'smallint', 'dims': 2, \n 'db_field': 'sen_zen', 'db_dtype': 'smallint', 'factor': 1},\n 3: {'src': 'l1b', \n 'sds': 'Geolocation/SensorAzimuth', 'hdf_dtype': 'smallint', 'dims': 2, \n 'db_field': 'sen_az', 'db_dtype': 'smallint', 'factor': 1},\n 4: {'src': 'l1b', \n 'sds': 'Geolocation/SolarZenith', 'hdf_dtype': 'smallint', 'dims': 2, \n 'db_field': 'solar_zen', 'db_dtype': 'smallint', 'factor': 1},\n 5: {'src': 'l1b', \n 'sds': 'Geolocation/SolarAzimuth', 'hdf_dtype': 'smallint', 'dims': 2, \n 'db_field': 'solar_az', 'db_dtype': 'smallint', 'factor': 1},\n 6: {'src': 'l1b', \n 'sds': 'Data/LandSeaMask', 'hdf_dtype': 'tinyint unsigned', \n 'dims': 2, 'db_field': 'landsea', 'db_dtype': 'tinyint unsigned', \n 'factor': 1},\n 7: {'src': 'l1b', \n 'sds': 'Data/DEM', 'hdf_dtype': 'smallint', 'dims': 2, \n 'db_field': 'dem', 'db_dtype': 'smallint', 'factor': 1},\n 8: {'src': 'l1b',\n 'sds': 'Data/Earth_Obs_BT', 'hdf_dtype': 'float','dims': 3,\n 'db_field': 'obs_bt', 'db_dtype': 'int', 'factor': 100,\n 'rank': {'x': 'channel', 'y': 'scan', 'z': 'pixel'},\n 'use_ch':15},\n \n}\n\n# idx of 'sds': 'Data/Earth_Obs_BT'\nbt_idx = len(lat_sds_to_db) + len(sds_to_db) - 1\n\n# time sds, we can get ymd-hms directly from daycnt and mscnt.\ntime_sds = {\n 'daycnt': {'src': 'l1b_obc', 'sds': 'Geolocation/Scnlin_daycnt', \n 'hdf_dtype': 'int', 'dims': 2, 'db_dtype': 'int'},\n 'mscnt': {'src': 'l1b_obc', 'sds': 'Geolocation/Scnlin_mscnt', \n 'hdf_dtype': 'int', 'dims': 2, 'db_dtype': 'int'},\n}\n\n# simulation field in db. one for rttov, another for crtm.\n# idx: for sim bin data, start from 0.\n# dims: 3 means that is channels*scans*pixel, we should create table like: \n# sim_bt1, sim_bt2, ..., sim_bt[channels]\n# and, the data idx should increase continuely to (idx + channels) \n# sim_dtype is data type for sim bin data.\n# if default value found in sim's result bin data, we should \n# trans to db default value instead.\n# if sim_default is None, we do NOT check sim default value.\nrttov_to_db = {\n 1: {'db_field': 'rttov_bt', \n 'dims': 3, 'db_dtype': 'int',\n 'idx': 23, 'sim_dtype': 'int', 'factor': 1,\n 'sim_default': -2147483648, 'db_default': -2147483648},\n 2: {'db_field': 'rttov_nwp_begin_t', \n 'dims': 1, 'db_dtype': 'double',\n 'idx': 40, 'sim_dtype': 'double', 'factor': 1, \n 'sim_default': None, 'db_default': None}, \n 3: {'db_field': 'rttov_nwp_begin_coef', \n 'dims': 1, 'db_dtype': 'float',\n 'idx': 42, 'sim_dtype': 'float', 'factor': 1, \n 'sim_default': None, 'db_default': None}, \n 4: {'db_field': 'rttov_nwp_end_t', \n 'dims': 1, 'db_dtype': 'double',\n 'idx': 41, 'sim_dtype': 'double', 'factor': 1, \n 'sim_default': None, 'db_default': None}, \n 5: {'db_field': 'rttov_nwp_end_coef', \n 'dims': 1, 'db_dtype': 'float',\n 'idx': 43, 'sim_dtype': 'float', 'factor': 1, \n 'sim_default': None, 'db_default': None}, \n}\ncrtm_to_db = {\n 1: {'db_field': 'crtm_bt', \n 'dims': 3, 'db_dtype': 'int',\n 'idx': 23, 'sim_dtype': 'int', 'factor': 1,\n 'sim_default': -2147483648, 'db_default': -2147483648},\n 2: {'db_field': 'crtm_nwp_begin_t', \n 'dims': 1, 'db_dtype': 'double',\n 'idx': 40, 'sim_dtype': 'double', 'factor': 1, \n 'sim_default': None, 'db_default': None}, \n 3: {'db_field': 'crtm_nwp_begin_coef', \n 'dims': 1, 'db_dtype': 'float',\n 'idx': 42, 'sim_dtype': 'float', 'factor': 1, \n 'sim_default': None, 'db_default': None}, \n 4: {'db_field': 'crtm_nwp_end_t', \n 'dims': 1, 'db_dtype': 'double',\n 'idx': 41, 'sim_dtype': 'double', 'factor': 1, \n 'sim_default': None, 'db_default': None}, \n 5: {'db_field': 'crtm_nwp_end_coef', \n 'dims': 1, 'db_dtype': 'float',\n 'idx': 43, 'sim_dtype': 'float', 'factor': 1, \n 'sim_default': None, 'db_default': None}, \n}\n\n# sim result bin fmt. both rttov and crtm fmt MUST NOT be difference.\n# one record = 38 int[4] + 2 nwp file time [double,8] + 2 nwp coef [float,4]\n# sim_fmt = '=' + 'i'*38 + 'd'*2 + 'f'*2\nsim_fmt = '=' + 'i'*40 + 'd'*2 + 'f'*2\n\n# time data is int fmt. ONLY used in sim bin data.\nsim_time_idx = {\n 'idx_year': 7, 'idx_mon': 8, 'idx_day': 9, 'idx_hour':10, \n 'idx_min':11, 'idx_sec': False,\n}\n\n# obc 2 dims hdf sds setting\n# scans*column = datasize\nobc_to_db = {\n 1: {'src': 'l1b_obc', 'dims': 2, 'fill_value': 0,\n 'sds': 'Calibration/Inst_Temp', 'hdf_dtype': 'float', 'columns': 2, \n 'db_field': 'ins_temp', 'db_dtype': 'int unsigned','factor': 100},\n 2: {'src': 'l1b_obc', 'dims': 2, 'fill_value': 0,\n 'sds': 'Calibration/PRT_Tavg', 'hdf_dtype': 'float', 'columns': 2, \n 'db_field': 'prt_avg', 'db_dtype': 'int unsigned','factor': 1000},\n 3: {'src': 'l1b_obc', 'dims': 1, 'fill_value': 0,\n 'sds': 'Calibration/Space_View_Ang', 'hdf_dtype': 'float', 'columns': 1, \n 'db_field': 'cold_ang', 'db_dtype': 'smallint unsigned','factor': 0.01},\n 4: {'src': 'l1b_obc', 'dims': 1, 'fill_value': 0,\n 'sds': 'Calibration/Black_Body_View_Ang', 'hdf_dtype': 'float', 'columns': 1, \n 'db_field': 'hot_ang', 'db_dtype': 'smallint unsigned','factor': 0.01}, \n 5: {'src': 'l1b', 'dims': 2, 'fill_value': 0,\n 'sds': 'Data/Pixel_View_Angle', 'hdf_dtype': 'int', 'columns': 2,\n 'db_field': 'pixviewangle', 'db_dtype': 'int', 'factor': 1},\n}\n\nsds_name = {\n \n \n 1: {'name': 'cold_ang',},\n 2: {'name': 'hot_ang',},\n 3: {'name': 'ins_temp1',},\n 4: {'name': 'ins_temp2',},\n 5: {'name': 'prt_avg1',},\n 6: {'name': 'prt_avg2',},\n 7: {'name': 'pixviewangle1',},\n 8: {'name': 'pixviewangle2',},\n 9: {'name': 'digital_control_u',},\n 10: {'name': 'cell_control_u',},\n 11: {'name': 'motor_temp_1',},\n 12: {'name': 'motor_temp_2',},\n 13: {'name': 'antenna_mask_temp_1',},\n 14: {'name': 'antenna_mask_temp_2',},\n 15: {'name': 'fet_118_amp_temp',},\n 16: {'name': 'fet_183_amp_temp',},\n 17: {'name': 'scan_prd',},\n \n \n \n \n \n}\n\ncalc_to_db = {\n \n 1: {'src': 'l1b_obc', 'dims': 1, 'fill_value': 0,\n 'sds': 'Data/Digital_Control_U', 'hdf_dtype': 'float', 'columns': 1, \n 'db_field': 'digital_control_u', 'db_dtype': 'int unsigned','factor': 1000},\n 2: {'src': 'l1b_obc', 'dims': 1, 'fill_value': 0,\n 'sds': 'Data/Cell_Control_U', 'hdf_dtype': 'float', 'columns': 1, \n 'db_field': 'cell_control_u', 'db_dtype': 'int unsigned','factor': 1000},\n 3: {'src': 'l1b_obc', 'dims': 1, 'fill_value': 0,\n 'sds': 'Data/Motor_Temp_1', 'hdf_dtype': 'float', 'columns': 1, \n 'db_field': 'motor_temp_1', 'db_dtype': 'int unsigned','factor': 1000}, \n 4: {'src': 'l1b_obc', 'dims': 1, 'fill_value': 0,\n 'sds': 'Data/Motor_Temp_2', 'hdf_dtype': 'float', 'columns': 1, \n 'db_field': 'motor_temp_2', 'db_dtype': 'int unsigned','factor': 1000},\n 5: {'src': 'l1b_obc', 'dims': 1, 'fill_value': 0,\n 'sds': 'Data/Antenna_Mask_Temp_1', 'hdf_dtype': 'float', 'columns': 1, \n 'db_field': 'antenna_mask_temp_1', 'db_dtype': 'int unsigned','factor': 1000},\n 6: {'src': 'l1b_obc', 'dims': 1, 'fill_value': 0,\n 'sds': 'Data/Antenna_Mask_Temp_2', 'hdf_dtype': 'float', 'columns': 1, \n 'db_field': 'antenna_mask_temp_2', 'db_dtype': 'int unsigned','factor': 1000},\n 7: {'src': 'l1b_obc', 'dims': 1, 'fill_value': 0,\n 'sds': 'Data/FET_118_Amp_Temp', 'hdf_dtype': 'float', 'columns': 1, \n 'db_field': 'fet_118_amp_temp', 'db_dtype': 'int unsigned','factor': 1000},\n 8: {'src': 'l1b_obc', 'dims': 1, 'fill_value': 0,\n 'sds': 'Data/FET_183_Amp_Temp', 'hdf_dtype': 'float', 'columns': 1, \n 'db_field': 'fet_183_amp_temp', 'db_dtype': 'int unsigned','factor': 1000},\n 9: {'src': 'l1b_obc', 'dims': 1, 'fill_value': 0,\n 'sds': 'Data/scan_prd', 'hdf_dtype': 'float', 'columns': 1, \n 'db_field': 'scan_prd', 'db_dtype': 'int unsigned','factor': 1},\n}\n\n# obc 3 dims hdf sds setting\n# channels*scans*column = datasize\n# need_avg: do not load total data to db, just load avg.\n# eg: mwts.Cold_Sky_Count_Avg have 8 point per scan, but we just need\n# avg(Cold_Sky_Count_Avg[5...7])\n# avg_idx: tuple of Cold_Sky_Count_Avg idx for avg. start from 0.\nobc_3dim_to_db = {\n 1: {'src': 'l1b_obc', 'dims': 3, 'fill_value': 0,\n 'sds': 'Calibration/Cal_Coefficient', 'hdf_dtype': 'int', 'columns': 3, \n 'db_field': 'cal_coef', 'db_dtype': 'int','factor': 1,\n 'need_avg': False, 'avg_idx': () ,\n 'rank': {'x': 'scan', 'y': 'channel', 'z': 'pixel'},\n 'use_ch':15},\n}\n\ncalc_3dim_to_db = {\n 1: {'src': 'l1b_obc', 'dims': 3, 'fill_value': 0,\n 'sds': 'Calibration/Gain', 'hdf_dtype': 'float', 'columns': 1, \n 'db_field': 'gain', 'db_dtype': 'int','factor': 1000,\n 'need_avg': False, 'avg_idx': () ,\n 'rank': {'x': 'scan', 'y': 'channel', 'z': 'pixel'},\n 'use_ch':15},\n 2: {'src': 'l1b_obc', 'dims': 3, 'fill_value': 0,\n 'sds': 'Calibration/AGC', 'hdf_dtype': 'smallint unsigned', 'columns': 1, \n 'db_field': 'agc', 'db_dtype': 'smallint unsigned','factor': 1,\n 'need_avg': False, 'avg_idx': () ,\n 'rank': {'x': 'scan', 'y': 'channel', 'z': 'pixel'},\n 'use_ch':15},\n 3: {'src': 'l1b_obc', 'dims': 3, 'fill_value': 0,\n 'sds': 'Calibration/SPBB_DN_Avg', 'hdf_dtype': 'float', 'columns': 1, \n 'db_field': 'SPBB1', 'db_dtype': 'int','factor': 1000,\n 'need_avg': False, 'avg_idx': () ,\n 'rank': {'x': 'scan', 'y': 'channel', 'z': 'pixel'},\n 'use_ch':15},\n 4: {'src': 'l1b_obc', 'dims': 3, 'fill_value': 0,\n 'sds': 'Calibration/SPBB_DN_Avg', 'hdf_dtype': 'float', 'columns': 1, \n 'db_field': 'SPBB2', 'db_dtype': 'int','factor': 1000,\n 'need_avg': False, 'avg_idx': () ,\n 'rank': {'x': 'scan', 'y': 'channel', 'z': 'pixel'},\n 'use_ch':15}, \n \n}\n\n# calc for bt avg and stdp... ...\n\n# functions in sql fmt. this is just for ONE chanel !!! sql like:\n# select count(*), avg(obs_bt3/100 - crtm_bt3/100), STDDEV_POP(obs_bt3/100 - \n# crtm_bt3/100) from ( select obs_bt3, crtm_bt3 from \n# FY3B_MWTSX_GBAL_L1_20131110_0220_060KM_MS union all \n# select obs_bt3, crtm_bt3 from \n# FY3B_MWTSX_GBAL_L1_20131110_1048_060KM_MS ) as total\n# here we split this sql to the following slice, in which,\n# 'param_dim_cnt': 2 means 2 %s used in 'param_fmt': 'obs_bt%s - sim_bt%s'\n# 'abs_value' is abs(obs-sim)<$value for each channel\nsql_crtm_bt = {\n 'prefix': 'select count(*)',\n 'func': {\n 1: {'name': 'avg', 'param_dims': 3, \n 'param_fmt': 'obs_bt%s/100 - crtm_bt%s/100', 'param_fmt_cnt': 2},\n 2: {'name': 'STDDEV_POP', 'param_dims': 3, \n 'param_fmt': 'obs_bt%s/100 - crtm_bt%s/100', 'param_fmt_cnt': 2},\n },\n 'sub_sql': {\n 'prefix': 'select ',\n 'fields': {\n 1: {'fmt': 'obs_bt', 'fields_dims': 3},\n 2: {'fmt': 'crtm_bt', 'fields_dims': 3},\n },\n 'where': {\n 1: {'type': 'not_equal', 'fmt': 'crtm_bt', 'fields_dims': 3, \n 'not_equal': '-2147483648'},\n 2: {'type': 'abs', 'param_fmt': 'obs_bt%s - crtm_bt%s', \n 'param_fmt_cnt': 2, 'fields_dims': 3,\n 'abs_value' : {\n 1: '5000', 2: '5000', 3: '5000', 4: '5000', 5: '5000', \n 6: '5000', 7: '5000', 8: '5000', 9: '5000', 10: '5000', \n 11: '5000', 12: '5000', 13: '5000',14:'5000',15:'5000'} },\n },\n },\n 'group_by': '',\n}\n\nsql_rttov_bt = {\n 'prefix': 'select count(*)',\n 'func': {\n 1: {'name': 'avg', 'param_dims': 3, \n 'param_fmt': 'obs_bt%s/100 - rttov_bt%s/100', 'param_fmt_cnt': 2},\n 2: {'name': 'STDDEV_POP', 'param_dims': 3, \n 'param_fmt': 'obs_bt%s/100 - rttov_bt%s/100', 'param_fmt_cnt': 2},\n },\n 'sub_sql': {\n 'prefix': 'select ',\n 'fields': {\n 1: {'fmt': 'obs_bt', 'fields_dims': 3},\n 2: {'fmt': 'rttov_bt', 'fields_dims': 3},\n },\n 'where': {\n 1: {'type': 'not_equal', 'fmt': 'rttov_bt', 'fields_dims': 3, \n 'not_equal': '-2147483648'},\n 2: {'type': 'abs', 'param_fmt': 'obs_bt%s - rttov_bt%s', \n 'param_fmt_cnt': 2, 'fields_dims': 3,\n 'abs_value' : {\n 1: '5000', 2: '5000', 3: '5000', 4: '5000', 5: '5000', \n 6: '5000', 7: '5000', 8: '5000', 9: '5000', 10: '5000', \n 11: '5000', 12: '5000', 13: '5000',14:'5000',15:'5000'} },\n },\n },\n 'group_by': '',\n}\n\n# calc for bt avg and stdp, every 5 or 10 lat... ...\n\nsql_crtm_bt_lat = {\n 'prefix': 'select count(*)',\n 'func': {\n 1: {'name': 'avg', 'param_dims': 3, \n 'param_fmt': 'obs_bt%s/100 - crtm_bt%s/100', 'param_fmt_cnt': 2},\n 2: {'name': 'STDDEV_POP', 'param_dims': 3, \n 'param_fmt': 'obs_bt%s/100 - crtm_bt%s/100', 'param_fmt_cnt': 2},\n },\n 'sub_sql': {\n 'prefix': 'select ',\n 'fields': {\n 1: {'fmt': 'obs_bt', 'fields_dims': 3},\n 2: {'fmt': 'crtm_bt', 'fields_dims': 3},\n },\n 'where': {\n 1: {'type': 'not_equal', 'fmt': 'crtm_bt', 'fields_dims': 3, \n 'not_equal': '-2147483648'},\n 2: {'type': 'abs', 'param_fmt': 'obs_bt%s - crtm_bt%s', \n 'param_fmt_cnt': 2, 'fields_dims': 3,\n 'abs_value' : {\n 1: '5000', 2: '5000', 3: '5000', 4: '5000', 5: '5000', \n 6: '5000', 7: '5000', 8: '5000', 9: '5000', 10: '5000', \n 11: '5000', 12: '5000', 13: '5000',14: '5000', 15: '5000'} },\n 3: {'type': 'min_max', 'fmt': 'lat', 'fields_dims': 2},\n },\n }, \n 'group_by': '',\n}\n\nsql_rttov_bt_lat = {\n 'prefix': 'select count(*)',\n 'func': {\n 1: {'name': 'avg', 'param_dims': 3, \n 'param_fmt': 'obs_bt%s/100 - rttov_bt%s/100', 'param_fmt_cnt': 2},\n 2: {'name': 'STDDEV_POP', 'param_dims': 3, \n 'param_fmt': 'obs_bt%s/100 - rttov_bt%s/100', 'param_fmt_cnt': 2},\n },\n 'sub_sql': {\n 'prefix': 'select ',\n 'fields': {\n 1: {'fmt': 'obs_bt', 'fields_dims': 3},\n 2: {'fmt': 'rttov_bt', 'fields_dims': 3},\n },\n 'where': {\n 1: {'type': 'not_equal', 'fmt': 'rttov_bt', 'fields_dims': 3, \n 'not_equal': '-2147483648'},\n 2: {'type': 'abs', 'param_fmt': 'obs_bt%s - rttov_bt%s', \n 'param_fmt_cnt': 2, 'fields_dims': 3,\n 'abs_value' : {\n 1: '5000', 2: '5000', 3: '5000', 4: '5000', 5: '5000', \n 6: '5000', 7: '5000', 8: '5000', 9: '5000', 10: '5000', \n 11: '5000', 12: '5000', 13: '5000',14: '5000', 15: '5000'} },\n 3: {'type': 'min_max', 'fmt': 'lat', 'fields_dims': 2},\n },\n }, \n 'group_by': '',\n}\n\n#the factor export out Global HDF\nglobal_hdf_factor = {\n 'lat': 0.01,'lon': 0.01,'obs_bt': 0.01,\n 'sim_bt_rttov': 0.01,'diff_rttov': 0.01,\n 'sim_bt_crtm': 0.01, 'diff_crtm': 0.01, \n }\n\n\n\n\nsql_rttov_by_point_realtime = {\n 'prefix': 'select count(*)',\n 'func': {\n 1: {'name': 'avg', 'param_dims': 3, \n 'param_fmt': 'obs_bt%s/100 - rttov_bt%s/100', 'param_fmt_cnt': 2},\n 2: {'name': 'STDDEV_POP', 'param_dims': 3, \n 'param_fmt': 'obs_bt%s/100 - rttov_bt%s/100', 'param_fmt_cnt': 2},\n 3: {'name': 'sqrt(sum(pow(', 'param_dims': 'point', \n 'param_fmt': 'obs_bt%s/100 - rttov_bt%s/100', 'param_fmt_cnt': 2},\n \n },\n 'sub_sql': {\n 'prefix': 'select ',\n 'fields': {\n 1: {'fmt': 'obs_bt', 'fields_dims': 3},\n 2: {'fmt': 'rttov_bt', 'fields_dims': 3},\n },\n 'where': {\n 1: {'type': 'not_equal', 'fmt': 'rttov_bt', 'fields_dims': 3, \n 'not_equal': '-2147483648'},\n 2: {'type': 'abs', 'param_fmt': 'obs_bt%s - rttov_bt%s', \n 'param_fmt_cnt': 2, 'fields_dims': 3,\n 'abs_value' : {\n 1: '2000', 2: '2000', 3: '2000', 4: '2000', 5: '2000', \n 6: '2000', 7: '2000', 8: '2000', 9: '2000', 10: '2000', \n 11: '2000', 12: '2000', 13: '2000', 14: '2000', 15: '2000'} },\n 3: {'type': 'point', 'fmt': 'scpt', 'fields_dims': 1},\n 4: {'type': 'realtime_start', 'param_fmt': 'ymdhms','fields_dims': 1},\n 5: {'type': 'realtime_end', 'param_fmt': 'ymdhms','fields_dims': 1},\n \n },\n }, \n 'group_by': '',\n}\n\n\n\n\nsql_crtm_bt_point_realtime = {\n 'prefix': 'select count(*)',\n 'func': {\n 1: {'name': 'avg', 'param_dims': 3, \n 'param_fmt': 'obs_bt%s/100 - crtm_bt%s/100', 'param_fmt_cnt': 2},\n 2: {'name': 'STDDEV_POP', 'param_dims': 3, \n 'param_fmt': 'obs_bt%s/100 - crtm_bt%s/100', 'param_fmt_cnt': 2},\n 3: {'name': 'sqrt(sum(pow(', 'param_dims': 'point', \n 'param_fmt': 'obs_bt%s/100 - crtm_bt%s/100', 'param_fmt_cnt': 2},\n\n },\n 'sub_sql': {\n 'prefix': 'select ',\n 'fields': {\n 1: {'fmt': 'obs_bt', 'fields_dims': 3},\n 2: {'fmt': 'crtm_bt', 'fields_dims': 3},\n },\n 'where': {\n 1: {'type': 'not_equal', 'fmt': 'crtm_bt', 'fields_dims': 3, \n 'not_equal': '-2147483648'},\n 2: {'type': 'abs', 'param_fmt': 'obs_bt%s - crtm_bt%s', \n 'param_fmt_cnt': 2, 'fields_dims': 3,\n 'abs_value' : {\n 1: '2000', 2: '2000', 3: '2000', 4: '2000', 5: '2000', \n 6: '2000', 7: '2000', 8: '2000', 9: '2000', 10: '2000', \n 11: '2000', 12: '2000', 13: '2000', 14: '2000', 15: '2000'} },\n #3: {'type': 'min_max', 'fmt': 'lat', 'fields_dims': 2},\n 3: {'type': 'point', 'fmt': 'scpt', 'fields_dims': 1},\n 4: {'type': 'realtime_start', 'param_fmt': 'ymdhms','fields_dims': 1},\n 5: {'type': 'realtime_end', 'param_fmt': 'ymdhms','fields_dims': 1},\n },\n }, \n 'group_by': '',\n}\n\n\n\n\n","sub_path":"conf/FY3C_MWHS_CONF.py","file_name":"FY3C_MWHS_CONF.py","file_ext":"py","file_size_in_byte":20442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"285978846","text":"from collections import defaultdict\nfrom petrel import storm\nfrom petrel.emitter import BasicBolt\n\nclass WordCountBolt(BasicBolt):\n def __init__(self):\n super(WordCountBolt, self).__init__(script=__file__)\n self._count = defaultdict(int)\n\n def declareOutputFields(declarer):\n return(['word', 'count'])\n\n def process(self, tuple):\n word = tuple.values[0]\n self._count[word] += 1\n storm.emit([word, self._count[word]])\n\ndef run():\n WordCountBolt().run()\n\ndef testWordCountBolt():\n from nose.tools import assert_equal\n\n bolt = WordCountBolt()\n\n from petrel import mock\n from RandomSentenceSpout import RandomSentenceSpout\n mock_spout = mock.MockSpout(RandomSentenceSpout.declareOutputFields(), [\n ['word'],\n ['other'],\n ['word']\n ])\n\n result = mock.run_simple_topology(None, [mock_spout, bolt], result_type=mock.LIST)\n assert_equal(2, bolt._count['word'])\n assert_equal(1, bolt._count['other'])\n assert_equal([['word', 1], ['other', 1], ['word', 2]], result[bolt])\n","sub_path":"WordCountBolt.py","file_name":"WordCountBolt.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"7732743","text":"\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 - ')\nposition=input('Enter position ')\niter=input('Enter count')\nposition=int(position)\niter=int(iter)\n\nhtml = urllib.request.urlopen(url, context=ctx).read()\nsoup = BeautifulSoup(html, 'html.parser')\nprint(\"Retrieving:\",url)\n# Retrieve all of the anchor tags\n\nwhile iter>0:\n pos=1\n tags = soup('a')\n for tag in tags:\n newurl=tag.get('href', None)\n name=tag.contents[0]\n if pos==position:\n break\n pos+=1\n html = urllib.request.urlopen(newurl, context=ctx).read()\n soup = BeautifulSoup(html, 'html.parser')\n print(\"Retrieving:\",url)\n iter-=1\n\nprint(name)\n","sub_path":"scraping_html_with_py2.py","file_name":"scraping_html_with_py2.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"314041405","text":"\nfrom pycoin.coins.bitcoin.networks import BitcoinMainnet\n\nfrom ..convention import tx_fee\n\nfrom ..solve.utils import build_hash160_lookup\n\n\nclass SecretExponentMissing(Exception):\n pass\n\n\nclass LazySecretExponentDB(object):\n \"\"\"\n The pycoin pure python implementation that converts secret exponents\n into public pairs is very slow, so this class does the conversion lazily\n and caches the results to optimize for the case of a large number\n of secret exponents.\n \"\"\"\n def __init__(self, wif_iterable, secret_exponent_db_cache, generators, network=BitcoinMainnet):\n self._wif_iterable = iter(wif_iterable)\n self._secret_exponent_db_cache = secret_exponent_db_cache\n self._generators = generators\n self._network = network\n\n def get(self, v):\n if v in self._secret_exponent_db_cache:\n return self._secret_exponent_db_cache[v]\n for wif in self._wif_iterable:\n key = self._network.ui.parse(wif, types=[\"key\"])\n if key is None:\n continue\n secret_exponent = key.secret_exponent()\n if secret_exponent is None:\n continue\n d = build_hash160_lookup([secret_exponent], self._generators)\n self._secret_exponent_db_cache.update(d)\n if v in self._secret_exponent_db_cache:\n return self._secret_exponent_db_cache[v]\n self._wif_iterable = []\n return None\n\n\ndef create_tx(spendables, payables, fee=\"standard\", lock_time=0, version=1, network=BitcoinMainnet):\n \"\"\"\n This function provides the easiest way to create an unsigned transaction.\n\n All coin values are in satoshis.\n\n :param spendables: a list of Spendable objects, which act as inputs.\n Each item in the list can be a Spendable, or text from Spendable.as_text,\n or a dictionary from Spendable.as_dict (which might be easier for\n airgapped transactions, for example).\n :param payables: a list where each entry is a bitcoin address, or a tuple of\n (bitcoin address, coin_value). If the coin_value is missing or\n zero, this address is thrown into the \"split pool\". Funds not\n explicitly claimed by the fee or a bitcoin address are shared as\n equally as possible among the split pool. All coins are consumed:\n if the amount to be split does not divide evenly, some of the earlier\n bitcoin addresses will get an extra satoshi.\n :param fee: an integer, or the (deprecated) string \"standard\" for it to be calculated\n :param version: (optional) the version to use in the transaction. Defaults to 1.\n :param lock_time: (optional) the lock_time to use in the transaction. Defaults to 0.\n :return: :class:`Tx ` object, with unspents populated\n :rtype: pycoin.tx.Tx.Tx\n\n Usage::\n\n >>> spendables = spendables_for_address(\"1BgGZ9tcN4rm9KBzDn7KprQz87SZ26SAMH\")\n >>> tx = create_tx(spendables, [\"1cMh228HTCiwS8ZsaakH8A8wze1JR5ZsP\"], fee=0)\n\n This will move all available reported funds from 1BgGZ9tcN4rm9KBzDn7KprQz87SZ26SAMH\n to 1cMh228HTCiwS8ZsaakH8A8wze1JR5ZsP, with no transaction fees (which means it might\n take a while to confirm, possibly never).\n \"\"\"\n\n Tx = network.tx\n\n def _fix_spendable(s):\n if isinstance(s, Tx.Spendable):\n return s\n if not hasattr(s, \"keys\"):\n return Tx.Spendable.from_text(s)\n return Tx.Spendable.from_dict(s)\n\n spendables = [_fix_spendable(s) for s in spendables]\n txs_in = [spendable.tx_in() for spendable in spendables]\n\n txs_out = []\n for payable in payables:\n if len(payable) == 2:\n bitcoin_address, coin_value = payable\n else:\n bitcoin_address = payable\n coin_value = 0\n script = network.ui.script_for_address(bitcoin_address)\n txs_out.append(Tx.TxOut(coin_value, script))\n\n tx = Tx(version=version, txs_in=txs_in, txs_out=txs_out, lock_time=lock_time)\n tx.set_unspents(spendables)\n\n distribute_from_split_pool(tx, fee)\n return tx\n\n\ndef split_with_remainder(total_amount, split_count):\n value_each, extra_count = divmod(total_amount, split_count)\n for _ in range(extra_count):\n yield value_each + 1\n for _ in range(split_count-extra_count):\n yield value_each\n\n\ndef distribute_from_split_pool(tx, fee):\n \"\"\"\n :param tx: a transaction\n :param fee: integer, satoshi value to set aside for transaction fee\n\n This function looks at TxOut items of a transaction tx and\n and puts TxOut items with a coin value of zero into a \"split pool\".\n Funds not explicitly claimed by the fee or other TxOut items are\n shared as equally as possible among the split pool. If the amount\n to be split does not divide evenly, some of the earlier TxOut items\n will get an extra satoshi. This function modifies `tx` in place.\n \"\"\"\n\n # calculate fees\n if fee == 'standard':\n # TODO: improve this\n # 1: the tx is not fully built out, so it will actually be larger than implied at this point\n # 2: recommended_fee_for_tx gives estimates that are too high\n fee = tx_fee.recommended_fee_for_tx(tx)\n\n zero_txs_out = [tx_out for tx_out in tx.txs_out if tx_out.coin_value == 0]\n zero_count = len(zero_txs_out)\n if zero_count > 0:\n total_coin_value = sum(spendable.coin_value for spendable in tx.unspents)\n coins_allocated = sum(tx_out.coin_value for tx_out in tx.txs_out) + fee\n remaining_coins = total_coin_value - coins_allocated\n if remaining_coins < 0:\n raise ValueError(\"insufficient inputs for outputs\")\n if remaining_coins < zero_count:\n raise ValueError(\"not enough to pay nonzero amounts to at least one of the unspecified outputs\")\n for value, tx_out in zip(split_with_remainder(remaining_coins, zero_count), zero_txs_out):\n tx_out.coin_value = value\n return zero_count\n\n\ndef sign_tx(tx, wifs=[], secret_exponent_db=None, network=BitcoinMainnet, **kwargs):\n \"\"\"\n :param tx: a transaction\n :param wifs: the list of WIFs required to sign this transaction.\n :param secret_exponent_db: (optional) a dictionary (or any object with a .get method) that contains\n a bitcoin address => (secret_exponent, public_pair, is_compressed) tuple lookup.\n This will be built automatically lazily with the list of WIFs.\n You can pass in an empty dictionary and as WIFs are processed, they\n will be cached here. If you have multiple transactions to sign, each with\n the same WIF list, passing a cache dictionary in may speed things up a bit.\n :return: :class:`Tx ` object, modified in place\n\n This is a convenience function used to sign a transaction.\n The transaction must have \"unspents\" set by, for example, calling tx.unspents_from_db.\n\n Returns the signed Tx transaction, or raises an exception.\n\n At least one of \"wifs\" and \"secret_exponent_db\" must be included for there\n to be any hope of signing the transaction.\n\n Usage::\n\n >> sign_tx(tx, wifs=[\"KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9M7rFU73sVHnoWn\"])\n \"\"\"\n secret_exponent_db = secret_exponent_db or {}\n solver = tx.Solver(tx)\n solver.sign(LazySecretExponentDB(wifs, secret_exponent_db, tx.SolutionChecker.generators, network), **kwargs)\n\n\ndef create_signed_tx(spendables, payables, wifs=[], fee=\"standard\",\n lock_time=0, version=1, secret_exponent_db={},\n netcode='BTC', network=BitcoinMainnet, **kwargs):\n \"\"\"\n This convenience function calls :func:`create_tx` and :func:`sign_tx` in turn. Read the documentation\n for those functions for information on the parameters.\n\n Usage::\n\n >>> spendables = spendables_for_address(\"1BgGZ9tcN4rm9KBzDn7KprQz87SZ26SAMH\")\n >>> wifs = [\"KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9M7rFU73sVHnoWn\"]\n >>> payables = [\"1cMh228HTCiwS8ZsaakH8A8wze1JR5ZsP\"]\n >>> tx = create_signed_tx(spendables, payables, wifs=wifs, fee=0)\n\n This will move all available reported funds from 1BgGZ9tcN4rm9KBzDn7KprQz87SZ26SAMH\n to 1cMh228HTCiwS8ZsaakH8A8wze1JR5ZsP, with no transaction fees (which means it might\n take a while to confirm, possibly never).\n \"\"\"\n\n tx = create_tx(spendables, payables, fee=fee, lock_time=lock_time, version=version, network=network)\n sign_tx(tx, wifs=wifs, secret_exponent_db=secret_exponent_db,\n netcode=netcode, **kwargs)\n for idx, tx_out in enumerate(tx.txs_in):\n if not tx.is_signature_ok(idx):\n raise SecretExponentMissing(\"failed to sign spendable for %s\" %\n tx.unspents[idx].bitcoin_address())\n return tx\n","sub_path":"pycoin/tx/tx_utils.py","file_name":"tx_utils.py","file_ext":"py","file_size_in_byte":8748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"418308906","text":"\"\"\"\n\tBuild computational graph\n\t\tNodes:\n\t\t\t-placeholder\n\t\t\t-variable\n\t\t\t-constant\n\tRun computational graph\n\t\tSession\n\n\"\"\"\n\nimport tensorflow as tf\n\nW = tf.Variable([.3], tf.float32, name=\"W\")\nb = tf.Variable([-.3], tf.float32, name=\"b\")\n\nx = tf.placeholder(tf.float32, name=\"x\")\n\nresult = x * W + b\ninit = tf.global_variables_initializer()\n\ny = tf.placeholder(tf.float32, name=\"y\")\nsquare_delta = tf.square(result - y)\nloss = tf.reduce_sum(square_delta)\n\noptimizer = tf.train.GradientDescentOptimizer(.01)\ntrain = optimizer.minimize(loss)\n\nsess = tf.Session()\nsess.run(init)\n\nfor i in range(1000):\n\tsess.run(train, {x:[1,2,3,4], y:[0,-1,-2,-3]})\n\nprint(sess.run([W,b]))\n","sub_path":"sample.py","file_name":"sample.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"248302508","text":"\nimport spotipy\nfrom spotipy.oauth2 import SpotifyClientCredentials\nimport sys\nimport time\nfrom flask import Flask, jsonify, Response, render_template, request\nfrom flask_sqlalchemy import SQLAlchemy\nimport pandas as pd\nimport numpy as np\nfrom os import getenv\nfrom dotenv import load_dotenv\nfrom json.decoder import JSONDecodeError\nimport json as simplejson\nfrom flask_cors import CORS\n# from .db_model import db, Song, History\nimport plotly.graph_objects as go\nimport plotly\n# DS ML model\nimport pickle\nfrom sklearn.neighbors import NearestNeighbors\n# functions for encapsulation and reabability\nfrom .spotify import search_artist_info, search_track_info, get_album_list, pull_features, plot_radar_one, get_song_info\nfrom .suggest import find_recommended_songs\n# from .etl_postgres import create_tables\n\n\n\ndef create_app():\n '''Create and configure an instance of the Flask application'''\n app = Flask(__name__)\n\n CORS(app)\n \n filename = 'beats/testing_model.sav'\n loaded_model = pickle.load(open(filename, 'rb'))\n\n\n @app.route('/songsuggester', methods=[\"GET\"])\n def feedmodel(user_input_fav_song=None):\n '''\n This function produces a suggested playlist\n\n params:\n user_input_fav_song : str - Song Name\n\n returns :\n ssresults : list of tuples of\n (track, artist, danceability, instrumentalness, loadness, speechiness, valance)\n '''\n user_input_fav_song = request.values['user_input_fav_song']\n if user_input_fav_song == \"\":\n return render_template('home.html')\n if \"_\" in user_input_fav_song:\n user_input_fav_song = user_input_fav_song.replace(\"_\",\" \")\n \n results = search_track_info(user_input_fav_song)# api call\n\n song_id = results['tracks']['items'][0]['id'] \n \n track_features = pull_features(song_id) \n \n danceability = track_features[0]['danceability']\n instrumentalness = track_features[0]['instrumentalness']\n loadness = track_features[0]['loudness']\n speechiness = track_features[0]['speechiness']\n valance = track_features[0]['valence']\n fav_five = [danceability, instrumentalness, loadness, speechiness, valance]\n # shaping the data to fit the model inputs\n y = [fav_five]\n x = ['danceability', 'instrumentalness', 'loudness', 'speechiness', 'valence'] # Series\n df_new = pd.DataFrame(y, columns= x)\n audio_features = df_new.iloc[0, 0:].to_numpy() \n\n song_list = find_recommended_songs(audio_features)\n \n results = []\n for song in song_list: \n all_audio_features = pull_features(song)\n\n danceability = all_audio_features[0]['danceability']\n instrumentalness = all_audio_features[0]['instrumentalness']\n loadness = all_audio_features[0]['loudness']\n speechiness = all_audio_features[0]['speechiness']\n valance = all_audio_features[0]['valence']\n \n result = get_song_info(song)\n artist = result['album']['artists'][0]['name'] # artist \n track = result['album']['name'] # track \n\n ssresults = (track, artist, danceability, instrumentalness, loadness, speechiness, valance)\n ssresults = str(ssresults) \n # NOTE ssresults this is a list\n print(ssresults) \n results.append(ssresults)\n \n return render_template('home.html', results=results) # this is to render list to webpage\n # return str(results) #return the list of song suggests\n \n\n @app.route('/suggest/', methods=['GET'])\n def modelweb(user_input_fav_song=None):\n '''\n This can be accessed thru the web link defined in Documentation.md\n This function produces a suggested playlist\n\n params:\n user_input_fav_song : str - Song Name\n\n returns :\n ssresults : list of tuples of\n (track, artist, danceability, instrumentalness, loadness, speechiness, valance)\n '''\n if \"_\" in user_input_fav_song:\n user_input_fav_song = user_input_fav_song.replace(\"_\",\" \")\n \n results = search_track_info(user_input_fav_song)# api call\n\n song_id = results['tracks']['items'][0]['id'] \n \n track_features = pull_features(song_id) \n \n danceability = track_features[0]['danceability']\n instrumentalness = track_features[0]['instrumentalness']\n loadness = track_features[0]['loudness']\n speechiness = track_features[0]['speechiness']\n valance = track_features[0]['valence']\n fav_five = [danceability, instrumentalness, loadness, speechiness, valance]\n \n y = [fav_five]\n x = ['danceability', 'instrumentalness', 'loudness', 'speechiness', 'valence'] # Series\n df_new = pd.DataFrame(y, columns= x)\n audio_features = df_new.iloc[0, 0:].to_numpy() \n\n song_list = find_recommended_songs(audio_features)\n \n results = []\n for song in song_list: \n # search api for song features\n all_audio_features = pull_features(song)\n\n danceability = all_audio_features[0]['danceability']\n instrumentalness = all_audio_features[0]['instrumentalness']\n loadness = all_audio_features[0]['loudness']\n speechiness = all_audio_features[0]['speechiness']\n valance = all_audio_features[0]['valence']\n \n result = get_song_info(song)\n artist = result['album']['artists'][0]['name'] # artist Weather Report\n track = result['album']['name'] # track \n\n ssresults = (track, artist, danceability, instrumentalness, loadness, speechiness, valance)\n\n ssresults = str(ssresults) \n # NOTE ssresult this is a list\n results.append(ssresults)\n \n return str(results) #return the list of song suggests\n\n\n @app.route('/hello')\n def hello_world():\n return 'Hello from DSPT5 and DSPT6 Lambda School 2020'\n\n\n @app.route('/')\n def index():\n return render_template('home.html')\n\n\n @app.route('/song')\n def getsong():\n '''\n Test page to\n take the artist name and returns cover art additional artist info\n takes the song name and returns song details\n takes artist name and returns up to 10 tracks per artist\n '''\n return render_template('asksong.html')\n\n \n @app.route('/artistinfo', methods=['GET'])\n @app.route('/artist/', methods=['GET'])\n def getartist(input_artist=None):\n '''\n This function uses spotify.py to find track info\n\n params:\n name : str - name of artist\n\n returns:\n json file of all artist info \n ''' \n input_artist = input_artist or request.values['input_artist']\n if input_artist == \"\":\n return render_template('home.html')\n if \"_\" in input_artist:\n input_artist = input_artist.replace(\"_\",\" \")\n name = input_artist\n\n searchResults = search_artist_info(name)\n artist = searchResults['artists']['items'][0]\n\n return artist\n\n\n @app.route('/songinfo', methods=['POST']) #/output changed to songinfo\n @app.route('/track/', methods=['GET'])\n def output(user_input_song=None):\n '''\n This function uses spotify.py to find track info\n\n params:\n user_input_song : str - name of song\n\n returns:\n json file of all track info associated with track\n '''\n user_input_song = user_input_song or request.form['user_input_song']\n if user_input_song == \"\":\n return render_template('home.html')\n if \"_\" in user_input_song:\n user_input_song = user_input_song.replace(\"_\",\" \")\n\n results = search_track_info(user_input_song)\n return results\n \n\n @app.route('/getsongs')\n @app.route('/albums/', methods=['GET'])\n def albumlist(input_artist=None):\n '''\n This function uses spotify.py to find albums list\n\n params:\n name : str - name of artist\n\n returns:\n json file of all albums info associated with artist\n '''\n input_artist = input_artist or request.values['input_artist']\n if input_artist == \"\":\n return render_template('home.html')\n if \"_\" in input_artist:\n input_artist = input_artist.replace(\"_\",\" \")\n name = input_artist\n\n # Search of the artist\n albumResults = get_album_list(name)\n return str(albumResults)\n\n\n return app","sub_path":"beats/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":8832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"226080752","text":"from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport math\n\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\n\n\n# For each set of style and range settings, plot n random points in the box\n# defined by x in [23, 32], y in [0, 100], z in [zlow, zhigh].\n\ng = 9.81\nm = 0.175\np = 1.23\nA = 0.0568 \nCLo = 0.1\nCLa = 1.4\nCDo = 0.08\nCDa = 2.72\nalphao = -4\n\nxs = [0]\nys = [0]\nzs = [1]\n\npos = [0,0,1]\n\n################Modify########################\nv0 = [10, 0, 2]\nalpha = 0\nphi = 5\ndeltaT = 0.01\n\n##############################################\n\nCL = CLo + CLa*alpha*np.pi/180\nCD = CDo + CDa*pow((alpha-alphao)*np.pi/180,2)\n\nv = v0\n\nd1 = [math.cos(alpha*np.pi/180),0,math.sin(alpha*np.pi/180)]\nd2 = [0,math.cos(phi*np.pi/180),math.sin(phi*np.pi/180)]\nk = [0,0,1]\nz=pos[2]\n\n\nwhile z>=0:\n \n alpha = math.acos(np.dot(v, d1)/(np.linalg.norm(v)*np.linalg.norm(d1))) #remove?\n print(alpha)\n \n CL = CLo + CLa*alpha*np.pi/180\n CD = CDo + CDa*pow((alpha-alphao)*np.pi/180,2)\n \n vmag = np.linalg.norm(v)\n \n L = (0.5*CL*A*p*pow(vmag,2)/m*deltaT)*np.array((np.cross(v,d2)/np.linalg.norm(np.cross(v, d2))))\n D = -(0.5*CD*A*p*vmag/m*deltaT)*np.array(v)\n W = -g*deltaT*np.array(k)\n \n deltaV = L + D + W\n v = v + deltaV\n pos = pos + deltaT*v\n \n xs.append(pos[0])\n ys.append(pos[1])\n zs.append(pos[2])\n \n z = pos[2] \n \n \n \n\n \nax.scatter(xs, ys, zs, c='r', marker='o') \n\nax.set_xlabel('X Label')\nax.set_ylabel('Y Label')\nax.set_zlabel('Z Label')\n\nplt.show()","sub_path":"vector.py","file_name":"vector.py","file_ext":"py","file_size_in_byte":1604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"626850462","text":"# From Joel Gottlieb - Tut- 2 Prob 3 - https://www.youtube.com/watch?v=vknIOydOJOo&ab_channel=D-WaveSystems\n\n# Solution code hugely influenced from D-Wave knapsack example: https://github.com/RonanOD/knapsack\n\nimport pandas as pd\nimport sys\nfrom dwave.system import LeapHybridSampler\nfrom math import log2, floor\nimport dimod\n\ndef build_bqm(costs, weights, weight_capacity):\n \"\"\"Construct BQM\n \n Args:\n costs (array-like):\n Array of costs associated with the items\n weights (array-like):\n Array of weights associated with the items\n weight_capacity (int):\n Maximum allowable weight\n \n Returns:\n Binary quadratic model instance\n \"\"\"\n\n # Initialize BQM - use large-capacity BQM so that the problem can be\n # scaled by the user.\n bqm = dimod.AdjVectorBQM(dimod.Vartype.BINARY)\n\n # Lagrangian multiplier\n # First guess as suggested in Lucas's paper\n lagrange = max(costs)\n\n # Number of objects\n x_size = len(costs)\n\n # Lucas's algorithm introduces additional slack variables to\n # handle the inequality. M+1 binary slack variables are needed to\n # represent the sum using a set of powers of 2.\n M = floor(log2(weight_capacity))\n num_slack_variables = M + 1\n\n # Slack variable list for Lucas's algorithm. The last variable has\n # a special value because it terminates the sequence.\n y = [2**n for n in range(M)]\n y.append(weight_capacity + 1 - 2**M)\n\n # Hamiltonian xi-xi terms\n for k in range(x_size):\n bqm.set_linear('x' + str(k), lagrange * (weights[k]**2) - costs[k])\n\n # Hamiltonian xi-xj terms\n for i in range(x_size):\n for j in range(i + 1, x_size):\n key = ('x' + str(i), 'x' + str(j))\n bqm.quadratic[key] = 2 * lagrange * weights[i] * weights[j]\n\n # Hamiltonian y-y terms\n for k in range(num_slack_variables):\n bqm.set_linear('y' + str(k), lagrange * (y[k]**2))\n\n # Hamiltonian yi-yj terms\n for i in range(num_slack_variables):\n for j in range(i + 1, num_slack_variables):\n key = ('y' + str(i), 'y' + str(j))\n bqm.quadratic[key] = 2 * lagrange * y[i] * y[j]\n\n # Hamiltonian x-y terms\n for i in range(x_size):\n for j in range(num_slack_variables):\n key = ('x' + str(i), 'y' + str(j))\n bqm.quadratic[key] = -2 * lagrange * weights[i] * y[j]\n\n return bqm\n\ndef solve(costs, weights, weight_capacity, sampler=None):\n \"\"\"Construct BQM and solve the problem\n \n Args:\n costs (array-like):\n Array of costs associated with the items\n weights (array-like):\n Array of weights associated with the items\n weight_capacity (int):\n Maximum allowable weight\n sampler (BQM sampler instance or None):\n A BQM sampler instance or None, in which case\n LeapHybridSampler is used by default\n \n Returns:\n Tuple:\n List of indices of selected items\n Solution energy\n \"\"\"\n bqm = build_bqm(costs, weights, weight_capacity)\n\n if sampler is None:\n sampler = LeapHybridSampler()\n\n sampleset = sampler.sample(bqm)\n sample = sampleset.first.sample\n energy = sampleset.first.energy\n\n # Build solution from returned binary variables:\n selected_item_indices = []\n for varname, value in sample.items():\n # For each \"x\" variable, check whether its value is set, which\n # indicates that the corresponding item is included in the\n # knapsack\n if value and varname.startswith('x'):\n # The index into the weight array is retrieved from the\n # variable name\n selected_item_indices.append(int(varname[1:]))\n\n return sorted(selected_item_indices), energy\n\n\nif __name__ == '__main__':\n # Weight capacity is what we want only 3 of the 5 numbers to add to:\n weight_capacity = 8\n # Construct a dict that is the set of {1,2,3,4,5}\n d = {'cost': [1, 2, 3, 4, 5], 'weight': [1, 2, 3, 4, 5]}\n df = pd.DataFrame(data=d)\n\n selected_item_indices, energy = solve(df['cost'], df['weight'], weight_capacity)\n selected_weights = list(df.loc[selected_item_indices,'weight'])\n selected_costs = list(df.loc[selected_item_indices,'cost'])\n\n print(\"Found solution at energy {}\".format(energy))\n print(\"Selected item numbers (0-indexed):\", selected_item_indices)\n print(\"Selected item weights: {}, total = {}\".format(selected_weights, sum(selected_weights)))\n print(\"Selected item costs: {}, total = {}\".format(selected_costs, sum(selected_costs)))\n\n\"\"\"\nNOTES:\n\nMy first solution:\n\nQ = {('a1', 1): 1, ('a2', 1): 2, ('a3', 1): 3, ('a4', 1): 4, ('a5', 1): 5}\n\nbqm = dimod.BinaryQuadraticModel.from_qubo(Q)\nresults = exactsolver.sample(bqm)\n\n# Print everything out\nfor sample, energy in results.data(['sample', 'energy']):\n print(sample, energy)\n\"\"\"\n\n\"\"\"\nFrom Joel:\n I write the “add up to 8” equation in the following way:\n x_1 + 2x_2 + 3x_3 + 4x_4 + 5x_5 = 8\n\n and then the “need to use three numbers” equation is this:\n x_1 + x_2 + x_3 + x_4 + x_5 = 3\n\nI replied:\n\nThat makes a lot more sense to me. So to make this QUBO appropriate you take the two formulas:\n\nobjective => x1 + 2x_2 + 3x_3 + 4x_4 + 5x_5 = 8\nconstraints => x_1 + x_2 + x_3 + x_4 + x_5 = 3\n\nand join them together as:\n\nmin( x1 + 2x_2 + 3x_3 + 4x_4 + 5x_5 - 8) + GAMMA(( x_1 + x_2 + x_3 + x_4 + x_5 -3) ** 2)\n\nFrom Joel:\nRonan,\n\nThe equation is slightly different:\n\nmin(( x1 + 2x_2 + 3x_3 + 4x_4 + 5x_5 - 8) ** 2) + GAMMA(( x_1 + x_2 + x_3 + x_4 + x_5 -3) ** 2)\n\nBoth expressions need to be squared.\n\n\"\"\"\n","sub_path":"prob3.py","file_name":"prob3.py","file_ext":"py","file_size_in_byte":5643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"292808087","text":"def flip(array, i):\n start = 0\n while start < i:\n t = array[start]\n array[start] = array[i]\n array[i] = t\n start += 1\n i -= 1\n\n\ndef findMaximumIndex(arr, n):\n max_index = 0\n for i in range(0, n):\n if arr[i] > arr[max_index]:\n max_index = i\n return max_index\n\n\ndef pancakeSort(arr):\n curr_size = len(arr)\n while curr_size > 1:\n max_index = findMaximumIndex(arr, curr_size)\n if max_index != curr_size - 1:\n flip(arr, max_index)\n flip(arr, curr_size - 1)\n curr_size -= 1\n\n\nif __name__ == \"__main__\":\n array = [\"Z\", \"Y\", \"X\", \"C\", \"B\", \"A\"]\n pancakeSort(array)\n print(array)\n","sub_path":"src/pancakeSort.py","file_name":"pancakeSort.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"142448694","text":"# coding: utf-8\n\nfrom scipy import *\nimport numpy as np\nfrom numpy import sin, cos, sqrt, arctan, pi, exp\nimport matplotlib.pyplot as plt\nfrom qutip import *\nfrom scipy import integrate\nfrom scipy.integrate import quad, dblquad, nquad\nimport math\nfrom matplotlib.colors import BoundaryNorm\nfrom matplotlib.ticker import MaxNLocator\nimport csv\n\n# GHz / ns\n# omega * f\ndef set_figorder(ax, order='a',x=-0.2, y=1):\n ax.set_title(order, x=x, y=y, fontsize=18)\n return\ndef draw_2d(kx, ky, kz, fig=None, ax=None, fig_label=None, xlabel=None, ylabel=None):\n if fig == None:\n fig = plt.figure(figsize=(8, 6))\n ax = fig.add_subplot(1, 1, 1)\n if ax == None:\n ax = fig.add_subplot(1, 1, 1)\n\n font_xylabel = 12\n cmap = plt.get_cmap('viridis') #RdBu\n\n levels = MaxNLocator(nbins=100).tick_values(kz.min(), kz.max())\n norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True)\n\n im = ax.pcolormesh(kx, ky, kz, cmap=cmap, norm=norm)\n cbar = fig.colorbar(im, ax=ax)\n # ax.legend()\n # ax.set_title(fig_label)\n ax.set_xlabel(xlabel)\n ax.set_ylabel(ylabel,rotation = 90)\n ax.set_xticks(np.linspace(kx.min(), kx.max(), 4))\n ax.set_yticks(np.linspace(ky.min(), ky.max(), 4))\n return\n\t\nf_bare = 6.5\t\nalpha = 240 * 1e-3\ng = 45 * 1e-3\nQ_l = 1e5\nS_min = 10\n\ndef freq_r(state = 0,Delta = -1):\n\tsigmaz = [1,-1]\n\tfr = f_bare - g**2/Delta + sigmaz[state] * g**2 * alpha / Delta**2\n\treturn fr\ndef get_ab(Delta,omega):\n\tdef freq_r(state = 0,Delta = -1):\n\t\tsigmaz = [1,-1]\n\t\tfr = f_bare - g**2/Delta + sigmaz[state] * g**2 * alpha / Delta**2\n\t\treturn fr\n\ta = Q_l * (omega/freq_r(state = 0,Delta = Delta) - 1)\n\tb = Q_l * (omega/freq_r(state = 1,Delta = Delta) - 1)\n\treturn a,b\n\t\ndef get_DeltaD(Delta,d_omega):\t\n\tdef _DeltaD(a,b):\n\t\tup = a - b\n\t\tdown = np.sqrt((1+4*a**2)*(1+4*b**2))\n\t\treturn up/down\n\tdef s21(a):\n\t\treturn (S_min+ 2*a*1j)/(1+2*a*1j)\n\tomega = f_bare+d_omega #- g**2/Delta \n\ta,b = get_ab(Delta,omega)\n\n\ts21a = s21(a)\n\ts21b = s21(b)\n\t# deltad = _DeltaD(a,b)\n\tdeltad = s21a-s21b\n\treturn np.abs(deltad)\n\ndef trans_db(A):\n\tA = np.abs(A)\n\treturn np.log10(A/np.max(A))\n\nfig = plt.figure(figsize = (12,4))\nmax_Delta = 2\nDelta = np.linspace(-max_Delta,-max_Delta/10,1000)\n\nomega0 = f_bare + g**2/max_Delta\nmax_omega = 5*1e-3\n# omega is the delta\ny0 = freq_r(state = 0,Delta =Delta)-f_bare\ny1 = freq_r(state = 1,Delta =Delta)-f_bare\nax2 = fig.add_subplot(1,2,2)\nax2.plot(Delta,y0*1e3,label=r'$f_{r,0}$')\nax2.plot(Delta,y1*1e3,label=r'$f_{r,1}$')\nax2.plot(Delta,(y0+y1)/2*1e3,label=r'$\\overline{f_{r}}$')\nax2.set_xlabel(r'$\\Delta/2\\pi $ (GHz)')\nax2.set_ylabel(r'$f_{r} -f_{bare} $ (MHz)')\n\n\nd_omega = np.linspace( -max_omega/10,max_omega,1000)\t\n# d_omega = np.linspace( 0.9667*1e-3,1.1*1e-3,1000)\n# d_omega = np.linspace( y0[0],y1,1000)\t\n\nDelta,d_omega = np.meshgrid(Delta,d_omega)\n\nDeltaD = get_DeltaD(Delta,d_omega)\n\n\nax = fig.add_subplot(1,2,1)\n\ndraw_2d(Delta,d_omega*1e3,DeltaD,ax=ax,fig=fig\n\t, xlabel=r'$\\Delta/2\\pi $ (GHz)',ylabel=r'$f_{probe} -f_{bare} $ (MHz)')\n\n\n\n\n\n# xticks\n\ndef setfig_label(ax):\n\txticks = np.arange(-2,0.2,0.4)\n\tyticks = np.arange(-0.5,6,1)\n\tax.set_yticks(yticks)\n\tax.set_xticks(xticks)\n\tax.set_xlim(-2,-0.2)\n\tax.set_ylim(-0.5,5)\n\treturn\n# setfig_label(ax)\n# setfig_label(ax2)\n\n#trans_db(DeltaD)\n# fig.savefig('full')\nax2.legend()\nfig.tight_layout()\nplt.show()\n\n","sub_path":"undergrad_thesis/code/visibility/visibi.py","file_name":"visibi.py","file_ext":"py","file_size_in_byte":3329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"167781279","text":"import statsmodels.api as sm\nfrom arch import arch_model\nfrom scipy.stats import norm, skew, kurtosis\nimport warnings\nfrom utils import *\n\n\ndef calc_volatility(daily_ret, tgt_sd=None):\n # TODO: Determine format of tgt_sd from markets.csv, load and pass to this function\n '''\n Returns the annualized daily volatility (standard deviation) of returns, per market per param set.\n If a target standard deviation is provided, returns the ratio of the actual to the per market target.\n\n :param daily_ret: Numpy array with daily return for all runs: Format (Param #, run #, day #, Market #)\n :return: sd_annual, sd_ratio: Annualized standard deviation, and ratio against target standard deviation\n Format: Tuple of numpy arrays (Param #, SD, Market #)\n '''\n\n sd_annual = np.sqrt(252) * np.nanstd(daily_ret, axis=(1, 2))\n\n if tgt_sd is None:\n sd_ratio = None\n else:\n sd_ratio = sd_annual / tgt_sd\n\n return sd_annual, sd_ratio\n\ndef calc_skewness(daily_ret):\n '''\n\n :param daily_ret: Numpy array with daily return for all runs: Format (Param #, run #, day #, Market #)\n :return: Skewness averaged across runs (Param #, avg skewness, Market #)\n '''\n skewness = skew(daily_ret[:,:,1:,:], axis=2)\n skewness = np.mean(skewness, axis=1)\n return skewness\n\ndef calc_kurtosis(daily_ret):\n '''\n\n :param daily_ret: Numpy array with daily return for all runs: Format (Param #, run #, day #, Market #)\n :return: Kurtosis averaged across runs (Param #, avg skewness, Market #)\n '''\n kurt = kurtosis(daily_ret[:,:,1:,:], axis=2)\n kurt = np.mean(kurt, axis=1)\n return kurt\n\n\n\ndef calc_mean_ret(daily_ret):\n '''\n Returns the average annualized daily return per market per parameter set\n\n\n :param daily_ret: Numpy array with daily return for all runs: Format (Param #, run #, day #, Market #)\n :return: Average Daily Return per market. Format: (Param #, SD, Market #)\n '''\n return 252 * np.nanmean(daily_ret, axis=(1, 2))\n\n\ndef calc_corr(daily_ret, tgt_corr=None):\n # TODO: Consider simplifying comparison with target correlation into a single value, possibly matrix distance like\n # Frobenius Norm\n\n '''\n Returns the correlation matrix per parameter set.\n If a target correlation matrix is provided, provides the difference between the target and the realized.\n\n :param daily_ret: Numpy array with daily return for all runs: Format (Param #, run #, day #, Market #)\n :param tgt_corr: Target Correlation Matrix (MxM for M markets)\n :return: Tuple of correlation, difference from target, both np arrays with format (Param #, Correlation Matrix)\n '''\n\n corr_list = [] # Store all outputs so they can be stacked later\n\n # Pass off processing of correlations to pandas; handles nan values (first daily return) more smoothly\n for idx in range(daily_ret.shape[0]):\n temp = daily_ret[idx, :, 1:].reshape(-1, daily_ret.shape[3])\n corr = np.corrcoef(temp, rowvar=False).reshape(-1, daily_ret.shape[3])\n corr_list.append(corr)\n\n # Stack the resulting correlation matrices so we have the format we want\n corr_arr = np.stack(corr_list)\n\n # Subtract target correlation matrix, if provided\n if tgt_corr is None:\n corr_diff = None\n else:\n corr_diff = corr_arr - tgt_corr\n\n return corr_arr, corr_diff\n\n\ndef calc_tails(log_ret, shift=1):\n '''\n Calculates the number of tails above/below 2.5 and 3. Provides the ratio when compared with normal distribution.\n\n :param log_ret: Numpy array with log return for all runs: Format (Param #, run #, day #, Market #)\n :param shift: Number of days over which to compute returns. Default shift 1 is daily returns, shift=5 is weekly, etc\n :return: Ratio of realized tails to expected for normal, at the given std dev level, per param set.\n '''\n\n daily_log_ret = log_ret[:, :, 2:, :] - log_ret[:, :, 1:-1, :]\n # Find the daily standard deviation\n std = np.nanstd(daily_log_ret, axis=(1, 2)) * np.sqrt(shift)\n mean = np.nanmean(daily_log_ret, axis=(1, 2)) * shift\n\n period_ret = log_ret[:, :, 1 + shift:, :] - log_ret[:, :, 1:-shift, :]\n\n # Convert each day to a number of standard deviations\n period_sd_move = (period_ret - mean[:,np.newaxis,np.newaxis,:]) / std[:, np.newaxis, np.newaxis, :]\n sim_count = period_ret.shape[1] * period_ret.shape[2]\n\n # Count occurrences above the thresholds and compare to normal CDF, attentive to maintain correct axes\n sd_pos25 = np.sum(period_sd_move > 2.5, axis=(1, 2)) / sim_count / (1 - norm.cdf(2.5))\n sd_neg25 = np.sum(period_sd_move < -2.5, axis=(1, 2)) / sim_count / norm.cdf(-2.5)\n\n sd_pos3 = np.sum(period_sd_move > 3, axis=(1, 2)) / sim_count / (1 - (norm.cdf(3)))\n sd_neg3 = np.sum(period_sd_move < -3, axis=(1, 2)) / sim_count / norm.cdf(-3)\n\n return sd_pos25, sd_neg25, sd_pos3, sd_neg3\n\n\ndef calc_quantiles(daily_ret):\n '''\n Calculates the quantiles corresponding to + / - 2 and 3 standard deviations. Compares the location of those\n quantiles with the normal distribution. Whereas calculate tails looks at the number of returns exceeding that\n threshold, this looks at the location of the threshold itself.\n\n :param daily_ret: Numpy array with daily return for all runs: Format (Param #, run #, day #, Market #)\n :return: Tuple with ratio of location of empirical quantile with normal quantile for 97.5, 2.5, 99.5, and .5.\n '''\n\n sd_daily = np.nanstd(daily_ret, axis=(1, 2))\n\n # Find location of quantiles and compare to normal distribution with same std deviation\n q975 = np.nanquantile(daily_ret, q=.975, axis=(1, 2)) / norm.ppf(.975, scale=sd_daily)\n q995 = np.nanquantile(daily_ret, q=.995, axis=(1, 2)) / norm.ppf(.995, scale=sd_daily)\n q025 = np.nanquantile(daily_ret, q=.025, axis=(1, 2)) / norm.ppf(.025, scale=sd_daily)\n q005 = np.nanquantile(daily_ret, q=.005, axis=(1, 2)) / norm.ppf(.005, scale=sd_daily)\n\n return q975, q025, q995, q005\n\n\ndef _helper_calc_mkt_exponent(mkt_ln_ret):\n # TODO: Verify what return values are needed, add intercept if necessary\n '''\n Helper function for calculating the market exponent. Offloads the calculations to Statsmodels. Currently this is\n not using any of the more advanced tools within statsmodels, and so could be reduced to a simple matrix\n calculation in numpy. The implementation was left in statsmodels to allow for flexibility with other models.\n\n :param mkt_ln_ret: Log returns of the market. This is a slice of the full log return matrix for a particular\n market and set of parameters.\n :return: Currently exp_b and R2. May add intercept as well\n '''\n\n # Find the std deviation per day (i.e., for occurrences of day 50 across every simulation)\n sd_per_day = np.std(mkt_ln_ret, axis=0)[1:] # Skip index one to avoid nan on first date\n\n # Take logs. We are fitting the equation ln(stddev(t)) = ln(stddev(1)) + b*ln(t)\n y = np.log(sd_per_day).reshape(-1, 1)\n x = (np.log(np.arange(1, (len(sd_per_day) + 1), 1)).reshape(-1, 1))\n x = sm.add_constant(x)\n model = sm.OLS(y, x) # Use statsmodels OLS regression, which gives many additional details if needed\n results = model.fit()\n\n ## These calculations were in the original R code but I am not sure their purpose or if we need them\n # v0_d = results.params[0] / ?MARKET SD? / sqrt(252)?\n # v0_y = results.params[0] * sqrt(252) / ?MARKET SD?\n\n b = results.params[1] / .5\n r2 = results.rsquared\n\n return b, r2\n\n\ndef calc_mkt_exponent(log_ret):\n '''\n Calculate Exponential B for each market. This is scaled such that a value of 1.0 corresponds to an exponent of .5,\n the same as the normal. This means that risk grows with the sqrt of time. Values less than 1 indicate risk grows slower\n than sqrt(t). This would happen if, for example, the market demonstrated a strong degree of mean reversion, so that\n volatility on a long term basis was a fraction of what it was on a daily basis. Likewise, values greater than 1 indicate\n risk growing faster than the sqrt(t).\n\n This moment requires at least two runs for a given parameter set, or it will\n return nan. In practice, this will work best if there are numerous runs per parameter set.\n\n :param log_ret: Log Returns generated by the gen_return_data function from utils. Numpy array with (Param #, run #,\n day #, Market #)\n :return: Numpy array with b, r2 for each market, for each run. Format: (Param #, Mkt #)\n '''\n\n ret_arrays = []\n\n # Loop over runs and markets to calculate exponent.\n for run in range(log_ret.shape[0]):\n ret_vals = []\n for mkt in range(log_ret.shape[3]):\n ret_vals.append(_helper_calc_mkt_exponent(log_ret[run, :, :, mkt]))\n ret_arrays.append(np.stack(ret_vals))\n\n exponent = np.stack(ret_arrays)\n b, r2 = exponent[:, :, 0], exponent[:, :, 1]\n\n return b, r2\n\ndef _get_RS(ts_arr):\n '''\n Calculates Rescaled Range for Hurst Exponent across entire return array. Optimmized to work on an entire subset\n of the series at once (i.e., for all params, runs, and markets, work on the subset of days)\n\n :param ts_arr: Array of subseries of format (Param #, run #, [subseries] day #, Market #). So this is a\n slice of the full return data.\n :return: Rescaled Range in format (Param #, run #, R/S, Market #)\n '''\n\n # First calculate the mean of the series and find the mean-adjusted series (e.g., series of deviations from mean)\n mean = np.mean(ts_arr, axis=2)\n mean = np.expand_dims(mean, axis=2)\n ts_adj = ts_arr - mean\n\n # Take that cumulative value\n cum_dev = np.cumsum(ts_adj, axis=2)\n\n # Subtract the max from the min to get the range of the cumulative deviation series\n ts_range = np.max(cum_dev, axis=2) - np.min(cum_dev, axis=2)\n\n # Divide the range of the series calculated as max - min by the standard deviation\n std_dev = np.std(ts_adj, axis=2)\n rescaled_range = ts_range / std_dev\n\n # Fix axis for processing in main hurst function\n rescaled_range = np.expand_dims(rescaled_range, axis=2)\n\n return rescaled_range\n\n\ndef calc_hurst_exponent(daily_ret, min_window=10):\n '''\n Calculates Hurst Exponent for run_data. Adapted from the hurst python package, optimized to exploit structure of\n the model output data.\n :param daily_ret: Numpy array with daily return for all runs: Format (Param #, run #, day #, Market #)\n :param min_window: Minimum window size for rescaled range analysis, default 10\n :return: hurst exponent, averaged across all runs for a given paramset/market (Param #, Market #)\n '''\n\n daily_ret_temp = daily_ret[:,:,1:,:] # Skip first return which will always be NaN\n params, runs, days, mkts = daily_ret_temp.shape\n\n # Set window sizes in log space to later perform linear regression\n max_window = days - 1\n window_sizes = list(map(\n lambda x: int(10**x),\n np.arange(math.log10(min_window), math.log10(max_window), 0.25)))\n window_sizes.append(days) # Include full series as final window\n\n avg_rs_per_window = None # Set RS array to None so we can create it when needed\n for w in window_sizes:\n rs_vals = None\n for start in range(0, days, w): # Loop over window increments\n if (start+w) > days:\n break\n else:\n ts_arr = daily_ret_temp[:,:,start:start+w, :] # Find subseries\n rescaled_range = _get_RS(ts_arr) # Calculate Rescaled Range\n if rs_vals is None: # Save rescaled range or concatenate with existing values\n rs_vals = rescaled_range\n else:\n rs_vals = np.concatenate([rs_vals, rescaled_range], axis=2)\n rs_vals = np.mean(rs_vals, axis=2, keepdims=True) # Average across axis\n if avg_rs_per_window is None: # Stack the averages per each window size\n avg_rs_per_window = rs_vals\n else:\n avg_rs_per_window = np.concatenate([avg_rs_per_window, rs_vals], axis=2)\n\n # Next we need to run a linear regression on the data. The slope is the approximate hurst exponent\n\n # Variables are the same for all iterations\n A = np.vstack([np.log10(window_sizes), np.ones(avg_rs_per_window.shape[2])]).T\n\n # Create a zero array that will be filled as we iterate over observations\n hurst = np.zeros((params, runs, 1, mkts))\n\n # Loop over all markets. This runs quickly as there is very little to do in each loop\n for i in range(params):\n for j in range(runs):\n for k in range(mkts):\n H, c = np.linalg.lstsq(A, np.log10(avg_rs_per_window[i, j, :, k]), rcond=-1)[0]\n hurst[i,j,0,k] = H\n\n hurst_avg = np.mean(hurst, axis=(1,2)) # Average across runs\n\n return hurst_avg\n\ndef calc_self_similarity(daily_ret, periods = [1,2,4,8,16,32,64]):\n '''\n Calculates the ratio between the length of the path at successive increments of granularity.\n Begins with the length of the return path on a daily basis (e.g., sum of abs value of all returns). Compares\n that to the length every other day, etc, for all periods (default 1,2,4,8,16,32,64). Brownian Motion has a ratio of\n .5 for doubling periods.\n\n Will only calculate up to an even length of the max period. E.g.,, if max period is the default of 64, it will\n truncate a 250 day path to 193 days [skipping the first day with no return], and truncate a 260 day path to 257\n days.\n\n :param daily_ret: Numpy array with daily return for all runs: Format (Param #, run #, day #, Market #)\n :param periods: Periods of return to calculate over as a list. Default [1,2,4,8,16,32,64]\n :return: Numpy array with ratios as (runs, ratios, mkts).\n '''\n params, runs, days, mkts = daily_ret.shape\n max_days = ((days // periods[-1] ) * periods[-1]) + 1 # Add one to account for 0 indexing\n lengths = np.zeros((params, runs, len(periods), mkts))\n for i,interval in enumerate(periods):\n subseries = np.abs(daily_ret[:,:,1:max_days:interval,:])\n lengths[:,:,i,:] = np.sum(subseries, axis=2)\n ratios = np.zeros((params, runs, len(periods)-1, mkts))\n for i in range(len(periods)-1):\n ratios[:,:,i,:] = lengths[:,:,i+1,:] / lengths[:,:,i,:]\n\n ratios = np.mean(ratios, axis=1)\n\n return ratios\n\n\n\n\n\n\ndef _rolling_window(arr, window):\n '''\n Helper function for computing RSI over arr rolling window. RSI requires the average of up and down moves over 14\n day windows. This function uses the numpy stride tricks to perform that looping in numpy rather than in python,\n which results in an order of magnitude improvement in performance.\n\n :param arr: Array to be strided.\n :param window: Window size to use\n :return: Strided array for fast processing\n '''\n\n ## WARNING! The Numpy stride-tricks is highly efficient but very finnicky. Be careful when modifying this code.\n shape = arr.shape[:-1] + (arr.shape[-1] - window + 1, window)\n strides = arr.strides + (arr.strides[-1],)\n return np.lib.stride_tricks.as_strided(arr, shape=shape, strides=strides)\n\n\ndef _calc_rsi(daily_ret, rsi_length=14):\n '''\n Helper function for calculating RSI. Calculates the RSI for every simulation in daily_ret. Used in the\n calc_rsi_moment function, which calculates the uptrends and downtrends based on RSI.\n\n RSI is calculate as 1 - (100 / (1 - RelativeStrength)), where RS is give by the average of\n up returns / down returns for the given periods. Note that a 14 day average is taken regardless of\n the pattern of up and down returns. For example, a single 14% up day and 13 down days gives a relative up\n strength of 1% (14 / 14 total days).\n\n\n :param daily_ret: Numpy array with daily return for all runs: Format (Param #, run #, day #, Market #)\n :param rsi_length: Window length for RSI\n :return: Numpy array of same format as daily_ret with RSI for each point\n '''\n\n # Group all up returns and down returns together.\n ret_up = np.where(np.nan_to_num(daily_ret) > 0, daily_ret, 0)\n ret_down = np.where(np.nan_to_num(daily_ret) < 0, daily_ret, 0)\n\n params, trials, days, markets = daily_ret.shape\n rsi_results = np.zeros((params, trials, days, markets))\n\n # Iterate over indexes, simulations, and windows to calculate the RSI\n for idx in range(daily_ret.shape[0]):\n for sim in range(daily_ret.shape[1]):\n rs_up = np.mean(_rolling_window(ret_up[idx, sim, :, :].T, rsi_length), -1).T\n rs_down = np.mean(_rolling_window(ret_down[idx, sim, :, :].T, rsi_length), -1).T + .000001 # Avoid\n # divide by 0\n rsi = 100 - (100 / (1 - rs_up / rs_down))\n rsi_results[idx, sim, :, :] = np.pad(rsi, ((rsi_length - 1, 0), (0, 0)), mode='constant',\n constant_values=np.nan)\n return rsi_results\n\n\ndef calc_rsi_moment(daily_ret, rsi_length=14):\n '''\n Returns percentage of time that RSI is below 10, below 30, above 70, and above 90. Note that time below 30\n includes time below 10, and likewise for above 70/90.\n\n RSI is calculate as 1 - (100 / (1 - RelativeStrength)), where RS is give by the average of\n up returns / down returns for the given periods. Note that a 14 day average is taken regardless of\n the pattern of up and down returns. For example, a single 14% up day and 13 down days gives a relative up\n strength of 1% (14 / 14 total days).\n\n The calc RSI function is one of the slowest moments. It takes about 5 seconds for 24 markets/1000 paths/250 days.\n This could be improved by improving the calc_rsi function, which uses a lot of loops.\n\n :param daily_ret: Numpy array with daily return for all runs: Format (Param #, run #, day #, Market #)\n :param rsi_length: Window length for RSI\n :return: Tuple of percentage that RSI is below 10, below 30, above 70, and above 90.\n '''\n\n temp_daily_ret = daily_ret - np.expand_dims(np.nanmean(daily_ret,axis=2),axis=2)\n\n rsi = _calc_rsi(temp_daily_ret, rsi_length)\n\n # skip RSI burn in period\n rsi10 = np.mean(rsi[:, :, (rsi_length - 1):, :] < 10, axis=(1, 2)) / .00498\n rsi30 = np.mean(rsi[:, :, (rsi_length - 1):, :] < 30, axis=(1, 2)) / .1198\n rsi70 = np.mean(rsi[:, :, (rsi_length - 1):, :] > 70, axis=(1, 2)) / .1198\n rsi90 = np.mean(rsi[:, :, (rsi_length - 1):, :] > 90, axis=(1, 2)) / .00498\n\n\n return rsi10, rsi30, rsi70, rsi90\n\n\ndef calc_garch_moment(daily_ret, max_sims=50):\n '''\n Calculates the parameters of a GARCH(1,1) model: mu, alpha, beta, gamma. Calculates path by path and averages the\n moments across all paths.\n\n The interpretation of the parameters of the standard GARCH model are roughly as follows:\n\n Alpha: How much large volatility today predicts large volatility tomorrow\n Beta: How quickly a period of high volatility dies over time.\n Alpha + Beta: Persistence of volatility (Alpha + Beta >= 1 indicates volatility is not stationary).\n Mu: The long-run mean of the residulas. In this case, it roughly represents the average return.\n Omega: If alpah + Beta < 1, then omega / (1 - alpha - beta) is the unconditional variance of the process\n\n For the purposes of moments, I believe Alpha, Beta, and their sum are the most important features.\n\n Furthermore, alpha+beta is returned (ab) as an indication of persistence. If ab > 1, the process is not stationary.\n\n NOTES RE MODELS:\n Standard Errors are not reported because they are only accurate for a single path, not for averaging multiple\n paths. The code is left in (commented out for performance) in case a pathwise std error is desired\n\n NOTES RE PERFORMANCE:\n This is by far the slowest moment, so the simulations are capped at default of 50 to make implementation reasonable.\n Even with this cap, it is omitted by default as it is an order of magnitude slower than the remaining moments.\n\n :param daily_ret: Numpy array with daily return for all runs: Format (Param #, run #, day #, Market #)\n :param max_sims: Maximum Number of simulations for GARCH to run\n :return: Numpy Array with garch parameters per param set per market, averaged across runs\n '''\n # TODO Consider alternative vol models like GJR Garch (Note: Scaling may need to be changed)\n params, trials, days, markets = daily_ret.shape\n\n garch_results = np.zeros((params, markets, 5)) # GARCH has 4 parameters, plus persistence=alpha+beta\n\n for idx in range(daily_ret.shape[0]):\n for mkt in range(daily_ret.shape[3]):\n paramlist = []\n std_err_list = []\n for sim in range(daily_ret.shape[1]):\n if sim > max_sims:\n break\n temp = daily_ret[idx, sim, :, mkt]\n am = arch_model(100 * temp[1:], rescale=True) # Allow furhter rescaling to increase MLE convergence\n try:\n res = am.fit(disp='off', show_warning=False)\n except OverflowError:\n warnings.warn('Overflow Error on this pass')\n continue\n if res.optimization_result.success:\n if res.scale != 1.0:\n # Standard scale is 100*returns, i.e. pct returns (5% = 5, not .05)\n # If model rescales further for convergence, this code adjusts the results to match scale of\n # the other runs\n res.params['mu'] = res.params['mu'] / res.scale\n res.params['omega'] = res.params['omega'] / (res.scale ** 2)\n # std_err_list.append(np.diag(res.param_cov ** .5))\n res.params['ab'] = res.params['alpha[1]'] + res.params['beta[1]']\n paramlist.append(np.array(res.params))\n # garch_errs[idx, mkt, :] = np.array(std_err_list).mean(axis=0)\n garch_results[idx, mkt, :] = np.array(paramlist).mean(axis=0)\n\n return garch_results\n","sub_path":"moments.py","file_name":"moments.py","file_ext":"py","file_size_in_byte":22049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"308855161","text":"\n\nfrom xai.brain.wordbase.verbs._lather import _LATHER\n\n#calss header\nclass _LATHERED(_LATHER, ):\n\tdef __init__(self,): \n\t\t_LATHER.__init__(self)\n\t\tself.name = \"LATHERED\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"lather\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_lathered.py","file_name":"_lathered.py","file_ext":"py","file_size_in_byte":240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"616571837","text":"from nose.tools import *\n\nfrom framework.mongo import database as db\n\nfrom scripts.remove_wiki_title_forward_slashes import main\n\nfrom tests.base import OsfTestCase\nfrom tests.factories import NodeWikiFactory, ProjectFactory\n\n\nclass TestRemoveWikiTitleForwardSlashes(OsfTestCase):\n\n def test_forward_slash_is_removed_from_wiki_title(self):\n project = ProjectFactory()\n wiki = NodeWikiFactory(node=project)\n\n invalid_name = 'invalid/name'\n db.nodewikipage.update({'_id': wiki._id}, {'$set': {'page_name': invalid_name}})\n project.wiki_pages_current['invalid/name'] = project.wiki_pages_current[wiki.page_name]\n project.wiki_pages_versions['invalid/name'] = project.wiki_pages_versions[wiki.page_name]\n project.save()\n\n main()\n wiki.reload()\n\n assert_equal(wiki.page_name, 'invalidname')\n assert_in('invalidname', project.wiki_pages_current)\n assert_in('invalidname', project.wiki_pages_versions)\n\n def test_valid_wiki_title(self):\n project = ProjectFactory()\n wiki = NodeWikiFactory(node=project)\n page_name = wiki.page_name\n main()\n wiki.reload()\n assert_equal(page_name, wiki.page_name)\n assert_in(page_name, project.wiki_pages_current)\n assert_in(page_name, project.wiki_pages_versions)\n","sub_path":"scripts/tests/test_remove_wiki_title_forward_slashes.py","file_name":"test_remove_wiki_title_forward_slashes.py","file_ext":"py","file_size_in_byte":1335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"268761713","text":"import vtk\nfrom sympy import Polygon\nfrom model_02 import *\nfrom colorutils import *\n\n\ndef irregular_right_prism_to_polydata(prism):\n \"\"\"References:\n - https://cmake.org/Wiki/VTK/Examples/Python/GeometricObjects/Display/Polygon\n \"\"\"\n\n sympy_polygon = prism.polygon_base\n surface_color = prism.surface_color\n base_p = prism.position\n\n vtk_polydata = vtk.vtkPolyData()\n\n # Setup four points\n points = vtk.vtkPoints()\n points_number = 0\n for p in prism.get_point3d_list():\n points_number = points_number + 1\n points.InsertNextPoint(p.x, p.y, p.z)\n\n # Add the polygon to a list of polygons\n polygons = vtk.vtkCellArray()\n\n # Create the polygon\n for my_polygon in prism.get_polygon_list_by_index():\n print(my_polygon)\n polygon = vtk.vtkPolygon()\n polygon.GetPointIds().SetNumberOfIds(len(prism.get_point3d_list()))\n polygon.GetPoints().DeepCopy(points)\n for my_point in my_polygon:\n print(my_point)\n polygon.GetPointIds().SetId(my_point, my_point)\n polygons.InsertNextCell(polygon)\n\n # Create a PolyData\n vtk_polydata.SetPoints(points)\n vtk_polydata.SetPolys(polygons)\n\n # setup colors (setting the name to \"Colors\" is nice but not necessary)\n vtk_colors = vtk.vtkUnsignedCharArray()\n vtk_colors.SetNumberOfComponents(3)\n vtk_colors.SetName(\"Colors\")\n vtk_colors.InsertNextTuple3(surface_color.red, surface_color.green, surface_color.blue)\n\n vtk_polydata.GetCellData().SetScalars(vtk_colors)\n vtk_polydata.Modified()\n\n return vtk_polydata\n","sub_path":"model_02/renderer_vtk/fun_irregular_right_prism_to_polydata.py","file_name":"fun_irregular_right_prism_to_polydata.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"371232419","text":"#!/usr/bin/env python2\n\"\"\"\nalloc_test.py: Tests for alloc.py\n\"\"\"\n\nimport unittest\n\nfrom _devbuild.gen.syntax_asdl import source\nfrom core import alloc # module under test\n\n\nclass AllocTest(unittest.TestCase):\n\n def setUp(self):\n self.arena = alloc.Arena()\n\n def testArena(self):\n arena = self.arena\n arena.PushSource(source.MainFile('one.oil'))\n\n line_id = arena.AddLine('line 1', 1)\n self.assertEqual(0, line_id)\n line_id = arena.AddLine('line 2', 2)\n self.assertEqual(1, line_id)\n\n span_id = arena.AddLineSpan(0, 1, 2)\n self.assertEqual(0, span_id)\n\n arena.PopSource()\n\n self.assertEqual('one.oil', arena.GetLineSource(0).path)\n self.assertEqual(1, arena.GetLineNumber(0))\n\n self.assertEqual('one.oil', arena.GetLineSource(1).path)\n self.assertEqual(2, arena.GetLineNumber(1))\n\n def testPushSource(self):\n arena = self.arena\n\n arena.PushSource(source.MainFile('one.oil'))\n arena.AddLine('echo 1a', 1)\n arena.AddLine('source two.oil', 2)\n\n arena.PushSource(source.MainFile('two.oil'))\n arena.AddLine('echo 2a', 1)\n id2 = arena.AddLine('echo 2b', 2) # line 2 of two.oil\n arena.PopSource()\n\n id3 = arena.AddLine('echo 1c', 3) # line 3 of one.oil\n arena.PopSource()\n\n self.assertEqual('two.oil', arena.GetLineSource(id2).path)\n self.assertEqual(2, arena.GetLineNumber(id2))\n\n self.assertEqual('one.oil', arena.GetLineSource(id3).path)\n self.assertEqual(3, arena.GetLineNumber(id3))\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"core/alloc_test.py","file_name":"alloc_test.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"166407113","text":"\"\"\"\napi.py\nAll API route endpoints\n\n:copyright: (C) 2014 by github.com/alfg.\n:license: MIT, see README for more details.\n\"\"\"\n\nfrom datetime import timedelta\n\nfrom flask import request, jsonify, json, Response\nfrom flask.ext.classy import FlaskView, route\n\nfrom app import app, meta, auth, auth_enabled, adapter\nfrom app.utils import obj_to_dict, get_server_conf, get_server_port, get_all_users_count, conditional\nfrom app.callbacks import ServerCallback, ServerAuthenticator, MetaCallback\n\nimport Murmur\n\nclass ServersView(FlaskView):\n \"\"\"\n Primary interface for creating, reading and writing to mumble servers.\n \"\"\"\n\n @conditional(auth.login_required, auth_enabled)\n def index(self):\n \"\"\"\n Lists all servers\n \"\"\"\n\n servers = []\n for s in meta.getAllServers():\n servers.append({\n 'id': s.id(),\n 'name': get_server_conf(meta, s, 'registername'),\n 'address': '%s:%s' % (\n get_server_conf(meta, s, 'host'),\n get_server_port(meta, s),\n ),\n 'host': get_server_conf(meta, s, 'host'),\n 'port': get_server_port(meta, s),\n 'running': s.isRunning(),\n 'users': (s.isRunning() and len(s.getUsers())) or 0,\n 'maxusers': get_server_conf(meta, s, 'users') or 0,\n 'channels': (s.isRunning() and len(s.getChannels())) or 0,\n 'uptime_seconds': s.getUptime() if s.isRunning() else 0,\n 'uptime': str(\n timedelta(seconds=s.getUptime()) if s.isRunning() else ''\n ),\n 'log_length': s.getLogLen()\n })\n\n # Workaround response due to jsonify() not allowing top-level json response\n # https://github.com/mitsuhiko/flask/issues/170\n return Response(json.dumps(servers, sort_keys=True, indent=4), mimetype='application/json')\n\n @conditional(auth.login_required, auth_enabled)\n def get(self, id):\n \"\"\"\n Lists server details\n \"\"\"\n\n id = long(id)\n s = meta.getServer(id)\n\n # Return 404 if not found\n if s is None:\n return jsonify(message=\"Not Found\"), 404\n\n tree = obj_to_dict(s.getTree()) if s.isRunning() else None\n\n json_data = {\n 'id': s.id(),\n 'name': get_server_conf(meta, s, 'registername'),\n 'host': get_server_conf(meta, s, 'host'),\n 'port': get_server_port(meta, s),\n 'address': '%s:%s' % (\n get_server_conf(meta, s, 'host'),\n get_server_port(meta, s),\n ),\n 'password': get_server_conf(meta, s, 'password'),\n 'welcometext': get_server_conf(meta, s, 'welcometext'),\n 'user_count': (s.isRunning() and len(s.getUsers())) or 0,\n 'maxusers': get_server_conf(meta, s, 'users') or 0,\n 'running': s.isRunning(),\n 'uptime': s.getUptime() if s.isRunning() else 0,\n 'humanize_uptime': str(\n timedelta(seconds=s.getUptime()) if s.isRunning() else ''\n ),\n 'parent_channel': tree['c'] if s.isRunning() else None,\n 'sub_channels': tree['children'] if s.isRunning() else None,\n 'users': tree['users'] if s.isRunning() else None,\n 'registered_users': s.getRegisteredUsers('') if s.isRunning() else None,\n 'log_length': s.getLogLen(),\n 'bans': s.getBans() if s.isRunning() else 0\n }\n\n return jsonify(json_data)\n\n @conditional(auth.login_required, auth_enabled)\n def post(self):\n \"\"\"\n Creates a server, starts server, and returns id\n \"\"\"\n\n # Basic Configuration\n password = request.form.get('password')\n port = request.form.get('port') # Defaults to inifile+server_id-1\n timeout = request.form.get('timeout')\n bandwidth = request.form.get('bandwidth')\n users = request.form.get('users')\n welcometext = request.form.get('welcometext')\n\n # Data for registration in the public server list\n registername = request.form.get('registername')\n registerpassword = request.form.get('registerpassword')\n registerhostname = request.form.get('registerhostname')\n registerurl = request.form.get('registerurl')\n\n # Create server\n server = meta.newServer()\n\n # Set conf if provided\n server.setConf('password', password) if password else None\n server.setConf('port', port) if port else None\n server.setConf('timeout', timeout) if timeout else None\n server.setConf('bandwidth', bandwidth) if bandwidth else None\n server.setConf('users', users) if users else None\n server.setConf('welcometext', welcometext) if welcometext else None\n server.setConf('registername', registername) if registername else None\n\n # Start server\n server.start()\n\n # Format to JSON\n json_data = {\n 'id': server.id()\n }\n\n return jsonify(json_data)\n\n @conditional(auth.login_required, auth_enabled)\n def delete(self, id):\n \"\"\"\n Shuts down and deletes a server\n \"\"\"\n\n server = meta.getServer(int(id))\n\n # Return 404 if not found\n if server is None:\n return jsonify(message=\"Not Found\"), 404\n\n # Stop server first if it is running\n if server.isRunning():\n server.stop()\n\n # Delete server instance\n server.delete()\n return jsonify(message=\"Server deleted\")\n\n ##\n # Nested routes and actions\n ##\n @conditional(auth.login_required, auth_enabled)\n @route('/start', methods=['POST'])\n def start(self, id):\n \"\"\" Starts server\n \"\"\"\n\n server = meta.getServer(id)\n\n # Return 404 if not found\n if server is None:\n return jsonify(message=\"Not Found\"), 404\n\n # Message if server is already running\n if server.isRunning():\n return jsonify(message=\"Server already running.\")\n\n # Start server instance\n server.start()\n return jsonify(message=\"Server started.\")\n\n @conditional(auth.login_required, auth_enabled)\n @route('/stop', methods=['POST'])\n def stop(self, id):\n \"\"\" Stops server\n \"\"\"\n\n server = meta.getServer(id)\n\n # Return 404 if not found\n if server is None:\n return jsonify(message=\"Not Found\"), 404\n\n # Stop server first if it is running\n if not server.isRunning():\n return jsonify(message=\"Server already stopped.\")\n\n # Stop server instance\n server.stop()\n return jsonify(message=\"Server stopped.\")\n\n @conditional(auth.login_required, auth_enabled)\n @route('/logs', methods=['GET'])\n def logs(self, id):\n \"\"\" Gets all server logs by server ID\n \"\"\"\n\n server = meta.getServer(int(id))\n\n # Return 404 if not found\n if server is None:\n return jsonify(message=\"Not Found\"), 404\n\n logs = []\n\n for l in server.getLog(0, -1):\n logs.append({\n \"message\": l.txt,\n \"timestamp\": l.timestamp,\n })\n return Response(json.dumps(logs, sort_keys=True, indent=4), mimetype='application/json')\n\n @conditional(auth.login_required, auth_enabled)\n @route('/user/', methods=['DELETE'])\n def user_del_user(self, id, user):\n \"\"\" Deletes user\n \"\"\"\n\n server = meta.getServer(int(id))\n\n # Return 404 if not found\n if server is None:\n return jsonify(message=\"No Server Found for ID \"+str(id)), 500\n\n olduser = server.getRegistration(int(user))\n\n if olduser is None:\n return jsonify(message=\"No User Found for ID \"+str(user)), 500\n\n server.unregisterUser(int(user))\n\n json_data = {\n \"user_id\": user,\n \"deleted\": 'Success'\n }\n return Response(json.dumps(json_data, sort_keys=True, indent=4), mimetype='application/json')\n\n\n @conditional(auth.login_required, auth_enabled)\n @route('/user', methods=['POST'])\n def user_new_user(self, id):\n \"\"\" Creates user\n \"\"\"\n\n server = meta.getServer(int(id))\n\n # Return 404 if not found\n if server is None:\n return jsonify(message=\"Not Found\"), 404\n\n username = request.form.get('username')\n password = request.form.get('password')\n\n new_user = {\n Murmur.UserInfo.UserName: username,\n Murmur.UserInfo.UserPassword: password\n }\n\n added = server.registerUser(new_user)\n\n data = obj_to_dict(server.getRegistration(added))\n\n\n json_data = {\n \"user_id\": added,\n \"username\": data['UserName'],\n \"last_active\": data['UserLastActive']\n }\n return Response(json.dumps(json_data, sort_keys=True, indent=4), mimetype='application/json')\n\n @conditional(auth.login_required, auth_enabled)\n @route('/user/', methods=['GET'])\n def register_user(self, id, user):\n \"\"\" Gets registered user by ID\n \"\"\"\n\n server = meta.getServer(int(id))\n\n # Return 404 if not found\n if server is None:\n return jsonify(message=\"Not Found\"), 404\n\n data = obj_to_dict(server.getRegistration(int(user)))\n\n json_data = {\n \"user_id\": user,\n \"username\": data['UserName'],\n \"last_active\": data['UserLastActive']\n }\n return Response(json.dumps(json_data, sort_keys=True, indent=4), mimetype='application/json')\n\n @conditional(auth.login_required, auth_enabled)\n @route('/channels', methods=['GET'])\n def channels(self, id):\n \"\"\" Gets all channels in server\n \"\"\"\n\n server = meta.getServer(int(id))\n\n # Return 404 if not found\n if server is None:\n return jsonify(message=\"Not Found\"), 404\n\n data = obj_to_dict(server.getChannels())\n\n return Response(json.dumps(data, sort_keys=True, indent=4), mimetype='application/json')\n\n @conditional(auth.login_required, auth_enabled)\n @route('/channels/', methods=['GET'])\n def channel(self, id, channel_id):\n \"\"\" Gets all channels in server\n \"\"\"\n\n server = meta.getServer(id)\n\n # Return 404 if not found\n if server is None:\n return jsonify(message=\"Not Found\"), 404\n\n data = obj_to_dict(server.getChannelState(channel_id))\n\n return Response(json.dumps(data, sort_keys=True, indent=4), mimetype='application/json')\n\n @conditional(auth.login_required, auth_enabled)\n @route('/bans', methods=['GET'])\n def bans(self, id):\n \"\"\" Gets all banned IPs in server\n \"\"\"\n\n server = meta.getServer(id)\n\n # Return 404 if not found\n if server is None:\n return jsonify(message=\"Not Found\"), 404\n\n data = obj_to_dict(server.getBans())\n return Response(json.dumps(data, sort_keys=True, indent=4), mimetype='application/json')\n\n @conditional(auth.login_required, auth_enabled)\n @route('/conf', methods=['GET'])\n def conf(self, id):\n \"\"\" Gets all configuration in server\n \"\"\"\n\n server = meta.getServer(id)\n\n # Return 404 if not found\n if server is None:\n return jsonify(message=\"Not Found\"), 404\n\n data = obj_to_dict(server.getAllConf())\n return Response(json.dumps(data, sort_keys=True, indent=4), mimetype='application/json')\n\n @conditional(auth.login_required, auth_enabled)\n @route('/conf', methods=['POST'])\n def set_conf(self, id):\n \"\"\" Sends a message to all channels in a server\n \"\"\"\n\n key = request.form.get('key')\n value = request.form.get('value')\n\n if key and value:\n server = meta.getServer(id)\n\n # Return 404 if not found\n if server is None:\n return jsonify(message=\"Not Found\"), 404\n\n server.setConf(key, value)\n return jsonify(message=\"Configuration updated.\")\n else:\n return jsonify(message=\"Configuration key and value required.\")\n\n @conditional(auth.login_required, auth_enabled)\n @route('/channels//acl', methods=['GET'])\n def channel_acl(self, id, channel_id):\n \"\"\" Gets all channel ACLs in server\n \"\"\"\n\n server = meta.getServer(id)\n\n # Return 404 if not found\n if server is None:\n return jsonify(message=\"Not Found\"), 404\n\n data = obj_to_dict(server.getACL(channel_id))\n return Response(json.dumps(data, sort_keys=True, indent=4), mimetype='application/json')\n\n @conditional(auth.login_required, auth_enabled)\n @route('/sendmessage', methods=['POST'])\n def send_message(self, id):\n \"\"\" Sends a message to all channels in a server\n \"\"\"\n\n message = request.form.get('message')\n\n if message:\n server = meta.getServer(id)\n\n # Return 404 if not found\n if server is None:\n return jsonify(message=\"Not Found\"), 404\n\n server.sendMessageChannel(0, True, message)\n return jsonify(message=\"Message sent.\")\n else:\n return jsonify(message=\"Message required.\")\n\n @conditional(auth.login_required, auth_enabled)\n @route('/setsuperuserpw', methods=['POST'])\n def set_superuser_pw(self, id):\n \"\"\" Sets SuperUser password for server id\n \"\"\"\n\n password = request.form.get('password')\n\n if password:\n server = meta.getServer(id)\n\n # Return 404 if not found\n if server is None:\n return jsonify(message=\"Not Found\"), 404\n\n server.setSuperuserPassword(password)\n return jsonify(message=\"Superuser password set.\")\n else:\n return jsonify(message=\"Password required.\")\n\n @conditional(auth.login_required, auth_enabled)\n @route('/kickuser', methods=['POST'])\n def kick_user(self, id):\n \"\"\" Kicks user from server.\n \"\"\"\n\n user_session = int(request.form.get(\"usersession\")) # Session ID of user\n reason = request.form.get(\"reason\", \"Reason not defined.\") # Reason messaged for being kicked.\n\n if user_session:\n server = meta.getServer(id)\n\n # Return 404 if not found\n if server is None:\n return jsonify(message=\"Not Found\"), 404\n\n try:\n server.kickUser(user_session, reason)\n return jsonify(message=\"User kicked from server.\")\n\n except Murmur.InvalidSessionException:\n return jsonify(message=\"Not a valid session ID.\")\n\n else:\n return jsonify(message=\"User session required.\")\n\n @conditional(auth.login_required, auth_enabled)\n @route('/authenticator', methods=['GET'])\n def authenticator (self, id):\n \"\"\"Some testing\n \"\"\"\n s = meta.getServer(int(id))\n #serverprx = Murmur.ServerCallbackPrx.uncheckedCast(adapter.addWithUUID(ServerCallback(s)))\n #s.addCallback(serverprx)\n s.setAuthenticator(Murmur.ServerAuthenticatorPrx.uncheckedCast(adapter.addWithUUID(ServerAuthenticator(int(id)))))\n return jsonify(message=\"Callback attached for: \"+str(id))\n\n\nclass StatsView(FlaskView):\n \"\"\"\n View for gathering stats on murmur statistics.\n \"\"\"\n\n @conditional(auth.login_required, auth_enabled)\n def index(self):\n \"\"\"\n Lists all stats\n \"\"\"\n\n stats = {\n 'all_servers': len(meta.getAllServers()),\n 'booted_servers': len(meta.getBootedServers()),\n 'users_online': get_all_users_count(meta),\n 'murmur_version': meta.getVersion()[3],\n 'murmur-rest_version': '0.1',\n 'uptime': meta.getUptime()\n }\n\n # Workaround response due to jsonify() not allowing top-level json response\n # https://github.com/mitsuhiko/flask/issues/170\n return Response(json.dumps(stats, sort_keys=True, indent=4), mimetype='application/json')\n\n# Register views\nServersView.register(app)\nStatsView.register(app)\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"app/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":16451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"425687961","text":"import json\nimport logging\n\nfrom functools import partial\n\nfrom django.conf import settings\nfrom django.contrib.auth.models import User\nfrom django.db.models import Q\nfrom django.http import Http404, HttpResponseRedirect, HttpResponse\nfrom django.shortcuts import render\nfrom django.utils.datastructures import SortedDict\nfrom django.views.decorators.http import require_GET\n\nimport jinja2\nfrom tower import ugettext_lazy as _lazy, ugettext as _\nfrom waffle.decorators import waffle_flag\n\nfrom dashboards.readouts import (overview_rows, READOUTS, L10N_READOUTS,\n CONTRIBUTOR_READOUTS)\nfrom sumo_locales import LOCALES\nfrom sumo.parser import get_object_fallback\nfrom sumo.urlresolvers import reverse\nfrom sumo.utils import smart_int\nfrom wiki.events import (ApproveRevisionInLocaleEvent,\n ReviewableRevisionInLocaleEvent)\nfrom wiki.models import Document, Revision\nfrom wiki.views import SHOWFOR_DATA\nfrom wiki.helpers import format_comment\n\nfrom datetime import datetime\n\n\nHOME_DOCS = {'quick': 'Home page - Quick', 'explore': 'Home page - Explore'}\nMOBILE_DOCS = {'quick': 'Mobile home - Quick',\n 'explore': 'Mobile home - Explore'}\nPAGE_SIZE = 100\n\n\ndef home(request):\n data = {}\n for side, title in HOME_DOCS.iteritems():\n message = _lazy(u'The template \"%s\" does not exist.') % title\n data[side] = get_object_fallback(\n Document, title, request.locale, message)\n\n data.update(SHOWFOR_DATA)\n return render(request, 'dashboards/home.html', data)\n\n\ndef mobile(request):\n data = {}\n for side, title in MOBILE_DOCS.iteritems():\n message = _lazy(u'The template \"%s\" does not exist.') % title\n data[side] = get_object_fallback(\n Document, title, request.locale, message)\n\n data.update(SHOWFOR_DATA)\n return render(request, 'dashboards/mobile.html', data)\n\n\ndef _kb_readout(request, readout_slug, readouts, locale=None, mode=None):\n \"\"\"Instantiate and return the readout with the given slug.\n\n Raise Http404 if there is no such readout.\n\n \"\"\"\n if readout_slug not in readouts:\n raise Http404\n return readouts[readout_slug](request, locale=locale, mode=mode)\n\n\ndef _kb_detail(request, readout_slug, readouts, main_view_name,\n main_dash_title, locale=None):\n \"\"\"Show all the rows for the given KB article statistics table.\"\"\"\n return render(request, 'dashboards/kb_detail.html',\n {'readout': _kb_readout(request, readout_slug, readouts, locale),\n 'locale': locale,\n 'main_dash_view': main_view_name,\n 'main_dash_title': main_dash_title})\n\n\n@require_GET\ndef contributors_detail(request, readout_slug):\n \"\"\"Show all the rows for the given contributor dashboard table.\"\"\"\n return _kb_detail(request, readout_slug, CONTRIBUTOR_READOUTS,\n 'dashboards.contributors', _('Contributor Dashboard'),\n locale=settings.WIKI_DEFAULT_LANGUAGE)\n\n\n@require_GET\ndef localization_detail(request, readout_slug):\n \"\"\"Show all the rows for the given localizer dashboard table.\"\"\"\n return _kb_detail(request, readout_slug, L10N_READOUTS,\n 'dashboards.localization', _('Localization Dashboard'))\n\n\ndef _kb_main(request, readouts, template, locale=None, extra_data=None):\n \"\"\"Render a KB statistics overview page.\n\n Use the given template, pass the template the given readouts, limit the\n considered data to the given locale, and pass along anything in the\n `extra_data` dict to the template in addition to the standard data.\n\n \"\"\"\n data = {'readouts': SortedDict((slug, class_(request, locale=locale))\n for slug, class_ in readouts.iteritems()),\n 'default_locale': settings.WIKI_DEFAULT_LANGUAGE,\n 'default_locale_name':\n LOCALES[settings.WIKI_DEFAULT_LANGUAGE].native,\n 'current_locale_name': LOCALES[request.locale].native,\n 'is_watching_approved': ApproveRevisionInLocaleEvent.is_notifying(\n request.user, locale=request.locale),\n 'is_watching_locale': ReviewableRevisionInLocaleEvent.is_notifying(\n request.user, locale=request.locale),\n 'is_watching_approved_default':\n ApproveRevisionInLocaleEvent.is_notifying(\n request.user, locale=settings.WIKI_DEFAULT_LANGUAGE)}\n if extra_data:\n data.update(extra_data)\n return render(request, 'dashboards/' + template, data)\n\n\n@require_GET\ndef localization(request):\n \"\"\"Render aggregate data about articles in a non-default locale.\"\"\"\n if request.locale == settings.WIKI_DEFAULT_LANGUAGE:\n return HttpResponseRedirect(reverse('dashboards.contributors'))\n data = {'overview_rows': partial(overview_rows, request.locale)}\n return _kb_main(request, L10N_READOUTS, 'localization.html',\n extra_data=data)\n\n\n@require_GET\ndef contributors(request):\n \"\"\"Render aggregate data about the articles in the default locale.\"\"\"\n return _kb_main(request, CONTRIBUTOR_READOUTS, 'contributors.html',\n locale=settings.WIKI_DEFAULT_LANGUAGE)\n\n\n@require_GET\n@waffle_flag('revisions_dashboard')\ndef revisions(request):\n \"\"\"Dashboard for reviewing revisions\"\"\"\n if request.is_ajax():\n username = request.GET.get('user', None)\n locale = request.GET.get('locale', None)\n topic = request.GET.get('topic', None)\n newusers = request.GET.get('newusers', None)\n\n display_start = int(request.GET.get('iDisplayStart', 0))\n\n revisions = (Revision.objects.select_related('creator').all()\n .order_by('-created'))\n\n # apply filters, limits, and pages\n if username:\n revisions = (revisions\n .filter(creator__username__istartswith=username))\n if locale:\n revisions = revisions.filter(document__locale=locale)\n\n if topic:\n revisions = revisions.filter(slug__icontains=topic)\n\n if newusers:\n \"\"\"Users with the first edit not older than 7 days or\n with fewer than 20 revisions at all\"\"\"\n sql = \"\"\"SELECT id, creator_id, MIN(created)\n FROM wiki_revision\n GROUP BY creator_id\n HAVING COUNT(*) <= 20\n OR MIN(created) >= DATE_SUB(NOW(), INTERVAL 7 DAY)\"\"\"\n result = list(Revision.objects.raw(sql))\n if result:\n users = [u.creator_id for u in result]\n revisions = revisions.filter(creator__id__in=users)\n else:\n revisions = Revision.objects.none()\n\n total = revisions.count()\n revisions = revisions[display_start:display_start + PAGE_SIZE]\n\n # build the master JSON\n revision_json = {\n 'iTotalRecords': total,\n 'iTotalDisplayRecords': total,\n 'aaData': []\n }\n for rev in revisions:\n prev = rev.get_previous()\n from_rev = str(prev.id if prev else rev.id)\n doc_url = reverse('wiki.document', args=[rev.document.full_path],\n locale=rev.document.locale)\n articleUrl = '%s' % (doc_url,\n jinja2.escape(rev.document.slug))\n articleLocale = ('%s'\n % rev.document.locale)\n articleComment = ('%s'\n % format_comment(rev))\n articleIsNew = ''\n if rev.based_on_id is None and not rev.document.is_redirect:\n articleIsNew = 'New: '\n richTitle = (articleIsNew + articleUrl + articleLocale +\n articleComment)\n\n revision_json['aaData'].append({\n 'id': rev.id,\n 'prev_id': from_rev,\n 'doc_url': doc_url,\n 'edit_url': reverse('wiki.edit_document',\n args=[rev.document.full_path], locale=rev.document.locale),\n 'compare_url': reverse('wiki.compare_revisions',\n args=[rev.document.full_path], locale=rev.document.locale)\n + '?from=%s&to=%s&raw=1' % (from_rev, str(rev.id)),\n 'revert_url': reverse('wiki.revert_document',\n args=[rev.document.full_path, rev.id],\n locale=rev.document.locale),\n 'history_url': reverse('wiki.document_revisions',\n args=[rev.document.full_path], locale=rev.document.locale),\n 'creator': ('%s'\n % jinja2.escape(rev.creator.username)),\n 'title': rev.title,\n 'richTitle': richTitle,\n 'date': rev.created.strftime('%b %d, %y - %H:%M'),\n 'slug': rev.document.slug\n })\n\n result = json.dumps(revision_json)\n return HttpResponse(result, mimetype='application/json')\n\n return render(request, 'dashboards/revisions.html')\n\n\n@require_GET\n@waffle_flag('revisions_dashboard')\ndef user_lookup(request):\n \"\"\"Returns partial username matches\"\"\"\n userlist = []\n\n if request.is_ajax():\n user = request.GET.get('user', '')\n if user:\n matches = User.objects.filter(username__istartswith=user)\n for u in matches:\n userlist.append({'label': u.username})\n\n data = json.dumps(userlist)\n return HttpResponse(data,\n content_type='application/json; charset=utf-8')\n\n\n@require_GET\n@waffle_flag('revisions_dashboard')\ndef topic_lookup(request):\n \"\"\"Returns partial topic matches\"\"\"\n topiclist = []\n\n if request.is_ajax():\n topic = request.GET.get('topic', '')\n if topic:\n matches = Document.objects.filter(slug__icontains=topic)\n for d in matches:\n topiclist.append({'label': d.slug})\n\n data = json.dumps(topiclist)\n return HttpResponse(data,\n content_type='application/json; charset=utf-8')\n\n\n@require_GET\ndef wiki_rows(request, readout_slug):\n \"\"\"Return the table contents HTML for the given readout and mode.\"\"\"\n readout = _kb_readout(request, readout_slug, READOUTS,\n locale=request.GET.get('locale'),\n mode=smart_int(request.GET.get('mode'), None))\n max_rows = smart_int(request.GET.get('max'), fallback=None)\n return HttpResponse(readout.render(max_rows=max_rows))\n","sub_path":"apps/dashboards/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"266781364","text":"#!/usr/bin/env python\n# coding: utf-8 \n#\n# Project: \n# http://www.edna-site.org\n#\n# File: \"$Id:$\"\n#\n# Copyright (C) \n#\n# Principal author: \n#\n# Contributing authors: \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# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n#\nfrom __future__ import with_statement\nimport os, sys, subprocess, tempfile\n\nxsDataName = \"\"\nxsdHomeDir = os.path.dirname(os.path.abspath(sys.argv[0]))\ndestDir = os.path.join(os.path.dirname(xsdHomeDir), \"plugins\")\noutputModule = os.path.join(destDir, os.path.splitext(xsDataName)[0] + \".py\")\n\n\ndef patchFile(filename):\n \"\"\"\n correct \"XSDataCommon\": \"workspace/edna/kernel/datamodel\", \\\n in \"XSDataCommon\": \"kernel/datamodel\", \\\n \"\"\"\n print(\"patching file %s\" % filename)\n outfile = []\n last = None\n edna_idx = None\n for i in open(filename):\n if i.lstrip().startswith('\"XSData') and (\":\" in i):\n mod, loc = i.split(\":\", 1)\n if edna_idx is None:\n edna_idx = loc.find(\"kernel\")\n if len(loc) > edna_idx:\n i = mod + ': \"' + loc[edna_idx:]\n if i != last:\n outfile.append(i)\n last = i\n with open(filename, \"w\") as f:\n f.writelines(outfile)\n\nif \"EDNA_HOME\" not in os.environ:\n full_path = os.path.abspath(sys.argv[0])\n while True:\n old_path = full_path\n full_path = os.path.dirname(old_path)\n if old_path == full_path:\n print(\"Something weird is happening: I did not find the EDNA_ROOT !!!\")\n sys.exit(1)\n if os.path.isdir(os.path.join(full_path, \"kernel\", \"datamodel\")):\n EDNA_HOME = full_path\n os.environ[\"EDNA_HOME\"] = full_path\n break\nelse:\n EDNA_HOME = os.environ[\"EDNA_HOME\"]\n\ncmdLine = [\"java\", \"-jar\"]\ncmdLine.append(os.path.join(EDNA_HOME, \"kernel\", \"datamodel\", \"EDGenerateDS.jar\"))\ncmdLine.append(\"-includepaths\")\ncmdLine.append(os.path.join(EDNA_HOME, \"kernel\", \"datamodel\"))\ncmdLine.append(\"-sourceDir\")\ncmdLine.append(xsdHomeDir)\ncmdLine.append(\"-sourceFile\")\ncmdLine.append(xsDataName)\ncmdLine.append(\"-targetdir\")\ncmdLine.append(os.path.join(os.path.dirname(xsdHomeDir), \"plugins\"))\nsub = subprocess.Popen(cmdLine, cwd=tempfile.gettempdir())\nprint(\"Java code for data-binding finished with exit code %s\" % sub.wait())\npatchFile(outputModule)\n","sub_path":"template/datamodel/generateXSDataTemplate.py","file_name":"generateXSDataTemplate.py","file_ext":"py","file_size_in_byte":2995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"267992850","text":"# this is to use cross validation to obtain the number of states\r\nimport numpy as np\r\nfrom sklearn.model_selection import KFold\r\nfrom hmm_class import hmm\r\nimport random\r\nfrom sklearn.preprocessing import normalize\r\n\r\n# load the obs and split into k fold.\r\ndef split_load_data(filename, k_splits):\r\n\tobs_seq = np.loadtxt(filename, dtype = int)\r\n\tkf = KFold(n_splits = k_splits, shuffle = False)\r\n\tfor train_index, test_index in kf.split(obs_seq):\r\n\t\tobs_train, obs_test = obs_seq[train_index], obs_seq[test_index]\r\n\r\n\treturn obs_train, obs_test\r\n\r\ndef sts_seq_generate(N, size_data, len_obs): # N states\r\n\tsts_seq = np.zeros((size_data, len_obs))\r\n\tfor i in range(size_data):\r\n\t\tfor j in range(len_obs):\r\n\t\t\tsts_seq[i][j] = random.randint(0,N-1)\r\n\treturn sts_seq\r\n\r\ndef param_generate(n, obs_seq):\r\n\tsize_data = len(obs_seq) # cal the line of obs 1000\r\n\tlen_obs = len(obs_seq[0]) # cal the len of each obs. only works for the same length\r\n\tsts_seq = sts_seq_generate(n, size_data, len_obs)\r\n\r\n\treturn size_data, len_obs, sts_seq\r\n\r\ndef em_prob_generate(n, m): # n:# states, m: # obs\r\n\tem_prob = np.zeros((n,m))\r\n\tfor i in range(n):\r\n\t\tfor j in range(m):\r\n\t\t\tem_prob[i][j] = np.random.uniform(0,1)\r\n\tem_prob = normalize(em_prob, axis = 1, norm = 'l1')\r\n\treturn np.asmatrix(em_prob)\r\n\r\ndef trans_prob_generate(n): # n:# states\r\n\ttrans_prob = np.zeros((n,n))\r\n\tfor i in range(n):\r\n\t\tfor j in range(n):\r\n\t\t\ttrans_prob[i][j] = np.random.uniform(0,1)\r\n\ttrans_prob = normalize(trans_prob, axis = 1, norm = 'l1')\r\n\treturn np.asmatrix(trans_prob)\r\n\r\ndef pi_generate(n):\r\n\tpi = np.zeros(n)\r\n\tfor i in range(n):\r\n\t\tpi[i] = np.random.uniform(0,1)\r\n\tpi = normalize([pi], axis = 1, norm = 'l1')\r\n\treturn np.asmatrix(pi)\r\n\r\ndef predict_obs(first_sts,ep, tp):\r\n\tpredicted_obs = []\r\n\tnext_sts = np.argmax(tp[int(first_sts),:]) # from the first to compute 2nd states\r\n\tfor _ in range(len_obs_test):\r\n\t\t# from the next sts to find out the argmax of the index\r\n\t\t# so that we know the most emission output\t\t\r\n\t\tout = np.argmax(ep[next_sts,:])\r\n\t\t# print(\"obs index\", out)\r\n\t\tpredicted_obs.append(uniq_obs[out]) # from the output list to take out the obs\r\n\t\tnext_sts = np.argmax(tp[next_sts,:]) # update the next sts\r\n\t\t# print(\"next states: \", next_sts)\r\n\treturn predicted_obs\r\n\r\ndef loss_count(hidden_sts, predicted_obs):\r\n\tloss = 0\r\n\thidden_sts = [int(i) for i in hidden_sts]\r\n\tfor i in range(len(hidden_sts)):\r\n\t\tif hidden_sts[i] != predicted_obs[i]:\r\n\t\t\tloss += 1\r\n\treturn loss\r\n\r\nif __name__ == '__main__':\r\n\tn = 6 # number of states\r\n\tm = 4 # number of obs\r\n\tk = 5 # number of fold\r\n\tnum_iter = 1000\r\n\ttolerance = 10**(-4)\r\n\r\n\tobs_train, obs_test = split_load_data('train534.dat', k)\r\n\r\n\t# train data\r\n\tsize_train_data, len_obs_train, sts_seq_train = param_generate(n, obs_train)\r\n\r\n\t# test data\r\n\tsize_test_data, len_obs_test, sts_seq_test = param_generate(n, obs_test)\r\n\r\n\t# uniq seq of sts and obs\r\n\tuniq_sts = list(np.unique(sts_seq_train)) # the function need to feed in a list of uniq states\r\n\tuniq_obs = list(np.unique(obs_train))\r\n\tquantities = np.ones(size_test_data)\r\n\r\n\t# prob param\r\n\tpi = pi_generate(n)\r\n\ttrans_prob = trans_prob_generate(n)\r\n\tem_prob = em_prob_generate(n, m)\r\n\r\n\tmodel = hmm(uniq_sts, uniq_obs, pi, trans_prob, em_prob) # init the model\r\n\tep, tp, sp, prob_lst, iter_count, loss_lst = model.train_hmm(obs_test, num_iter, quantities, tolerance)\r\n\r\n\thidden_sts = []\r\n\tfor i in range(size_train_data):\r\n\t\thidden_sts.append(model.viterbi(obs_train[i]))\r\n\r\n\t# print(\"hidden states for training data:\\n\", hidden_sts)\r\n\t# print(len(hidden_sts))\r\n\tprint(\"em_prob\\n\", ep)\r\n\tprint(\"trans_prob\\n\", trans_prob)\r\n\r\n\t# predicted output from the training data\r\n\tfirst_index = []\r\n\tfor i in range(len(hidden_sts)):\r\n\t\tfirst_index.append(hidden_sts[i][0])\r\n\r\n\tpredicted_obs = []\r\n\tfor i in range(len(hidden_sts)):\r\n\t\tpredicted_obs.append(predict_obs(first_index[i], ep, tp))\r\n\t# print(\"predicted obs\", predicted_obs)\r\n\r\n\tloss = []\r\n\tfor i in range(len(hidden_sts)):\r\n\t\tloss.append(loss_count(hidden_sts[i], predicted_obs[i]))\r\n\r\n\tprint(\"total loss: \", sum(loss))\r\n","sub_path":"cross_validation.py","file_name":"cross_validation.py","file_ext":"py","file_size_in_byte":4062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"337846709","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Feb 25 13:53:05 2017\n\n@author: venusgrape\n\nIn this problem, you'll create a program that guesses a secret number!\n\nThe program works as follows: you (the user) thinks of an integer between 0 (inclusive) and 100 (not inclusive). \nThe computer makes guesses, and you give it input - is its guess too high or too low? Using bisection search, \nthe computer will guess the user's secret number!\n\nHere is a transcript of an example session:\n\nPlease think of a number between 0 and 100!\nIs your secret number 50?\nEnter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. l\nIs your secret number 75?\nEnter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. l\nIs your secret number 87?\nEnter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. h\nIs your secret number 81?\nEnter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. l\nIs your secret number 84?\nEnter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. h\nIs your secret number 82?\nEnter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. l\nIs your secret number 83?\nEnter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. c\nGame over. Your secret number was: 83\n\nImportant\nHint: Endpoints\n** Your program should use bisection search. So think carefully what that means. What will the first guess always be? \n How should you calculate subsequent guesses?\n** Your initial endpoints should be 0 and 100. Do not optimize your subsequent endpoints by making them be the halfway point plus or minus 1. Rather, just make them be the halfway point.\nPython Trick: Printing on the same line\n\n\nNote: your program should use input to obtain the user's input! Be sure to handle the case when the user's input is not one of h, l, or c.\n\nWhen the user enters something invalid, you should print out a message to the user explaining you did not understand their input. Then, \nyou should re-ask the question, and prompt again for input. For example:\n\nIs your secret number 91?\nEnter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. y\nSorry, I did not understand your input.\nIs your secret number 91?\nEnter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. c\n\n\n\"\"\"\n\nn = 100\nepsilon = 0.01\nlow = 0\nhigh = n\nans = (low + high)/2.0\n#print(ans)\nwhile ans**2 - n >= epsilon:\n print('Is your secret number', end = ' ')\n print(ans,end = ' ')\n print('?')\n \n letter = input(\"Enter 'h' to indicate the guess is too high. \\\n Enter 'l' to indicate the guess is too low. \\\n Enter 'c' to indicate I guessed correctly.\")\n if letter == 'h':\n high = ans\n ans = (high + low)/2\n elif letter == 'l':\n low = ans\n ans = (high + low)/2\n elif letter == 'c':\n print('Game over, My answer is:',end = ' ')\n print(ans)\n break \n else:\n print(\"Sorry, I did not understand your input.\")\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n ","sub_path":"guess _my_number.py","file_name":"guess _my_number.py","file_ext":"py","file_size_in_byte":3740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"453870128","text":"\"\"\"编译js语言的grpc-web模块.\"\"\"\nimport warnings\nimport subprocess\nimport chardet\n\n\ndef build_pb_web(name: str, dir_: str, to: str, grpc: bool) -> None:\n \"\"\"编译js语言的grpc-web模块.\n\n Args:\n name (str): 要编译的pb文件\n dir_ (str): 要编译的pb文件所在文件夹\n to (str): 将模块文件编译到目标位置\n grpc (bool): 编译grpc\n \"\"\"\n if grpc:\n warnings.warn(\n \"\"\"编译grpc-web需要安装`protoc-gen-grpc-web`\"\"\"\n )\n command = f\"protoc -I {dir_} {dir_}/{name} --js_out=import_style=commonjs:{to} \\\n --grpc-web_out=import_style=commonjs,mode=grpcwebtext:{to}\"\n print(command)\n res = subprocess.run(command, capture_output=True, shell=True)\n if res.returncode == 0:\n print(f\"编译grpc的protobuf项目<{name}>为go语言模块完成!\")\n else:\n print(f\"编译grpc的protobuf项目{name}为go语言模块失败!\")\n encoding = chardet.detect(res.stderr).get(\"encoding\")\n print(res.stderr.decode(encoding))\n else:\n warnings.warn(\"\"\"编译为js模块需要安装`protoc-gen-js`\"\"\")\n command = f\"protoc -I={dir_} --js_out=import_style=commonjs,binary:{to} {dir_}/{name}\"\n res = subprocess.run(command, capture_output=True, shell=True)\n if res.returncode == 0:\n print(f\"编译protobuf项目<{name}>为js语言模块完成!\")\n else:\n print(f\"编译protobuf项目{name}为js语言模块失败!\")\n encoding = chardet.detect(res.stderr).get(\"encoding\")\n print(res.stderr.decode(encoding))\n","sub_path":"pmfp/build_pb/build_pb_web.py","file_name":"build_pb_web.py","file_ext":"py","file_size_in_byte":1732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"75598858","text":"import json\nimport csv\nimport os\n\nlab_users = []\nwith open('final_classifier_dataset.txt','r') as inf:\n\treader = csv.reader(inf)\n\tfor i in reader:\n\t\tlab_users.append(i)\n\n\nuw_tweets=os.listdir('tweets_text')\nnews = []\nfor i in uw_tweets:\n\tnews.append(i[:-4])\n\ntrained = []\nfor i in lab_users:\n\tif i[0] in news:\n\t\ttemp = []\n\t\twith open('tweets_text/'+i[0]+'.txt','r') as inf:\n\t\t\treader = csv.reader(inf)\n\t\t\tfor j in reader:\n\t\t\t\ttmp = [x for x in j if 'http' not in x]\n\t\t\t\t#print tmp\n\t\t\t\ttmp = \" \".join(tmp)\n\t\t\t\tif tmp not in temp:\n\t\t\t\t\ttemp.append(tmp)\n\t\ttrained.append({'id':i[0],'vet':i[1],'tweets':temp})\n\nwith open(\"cleaner.json\",'w') as of:\n\tjson.dump(trained,of,indent = 4)\n","sub_path":"mk_dataset.py","file_name":"mk_dataset.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"459625093","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/galleryremote/multipart.py\n# Compiled at: 2011-06-09 07:24:08\nimport mimetypes\n\ndef multipart(boundary, arguments, file_info):\n \"\"\"\n Generates the body of a multipart data.\n \"\"\"\n parts = []\n for key, value in arguments.iteritems():\n parts.append('--%s' % boundary)\n parts.append('Content-disposition: form-data; name=\"%s\"' % key)\n parts.append('')\n parts.append(value)\n\n if file_info is not None:\n content_type = mimetypes.guess_type(file_info[1])[0] or 'application/octet-stream'\n parts.append('--%s' % boundary)\n parts.append('Content-disposition: form-data; ' + 'name=\"%s\"; filename=\"%s\"' % (\n file_info[0], file_info[1]))\n parts.append('Content-Type: %s' % content_type)\n parts.append('Content-Transfer-Encoding: base64')\n parts.append('')\n image = file(file_info[1], 'rb')\n contents = image.read()\n image.close()\n parts.append(contents)\n parts.append('--%s--' % boundary)\n return ('\\r\\n').join(parts)","sub_path":"pycfiles/GalleryRemote-0.7-py2.7/multipart.py","file_name":"multipart.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"589727634","text":"import pandas as pd\r\nimport steagsupports_factory\r\n\r\n\r\n# Classe to create inverter dataframe and save in sheet destiny\r\nclass Inverter:\r\n\r\n @staticmethod\r\n def calcinverter(frm, periodo, place, destino):\r\n df = frm.fillna(0.00)\r\n column = df.columns.values\r\n lista_plant = Inverter.organizetuplainverter(column)\r\n files = steagsupports_factory.sheetdestination(destino, periodo, place)\r\n numberinv = 0\r\n for i in lista_plant:\r\n columnfilter = [column[0], column[1], i[0], i[1]]\r\n df_fin = df.filter(items=columnfilter)\r\n df_fin = Inverter.readframe(df_fin)\r\n df_fin = df_fin[[column[0], i[0], i[1]]]\r\n df_fin.rename(columns={'Date': 'timestamp', i[0]: 'ACTIVE POWER', i[1]: 'COMS STATUS'}, inplace=True)\r\n namesfile = Inverter.stamp(periodo, i[0], place, 'Inverter')\r\n sheetname = r'{}\\{}.csv'.format(files, namesfile)\r\n df_fin.to_csv(sheetname, index=False)\r\n numberinv += 1\r\n print('Arquivo \"{}\" salvo com sucesso!!!'.format(namesfile))\r\n\r\n @staticmethod\r\n # Function to analize data of equipment inverter\r\n def organizetuplainverter(listcol):\r\n flag = True\r\n listdata = []\r\n lencollumn = len(listcol)\r\n index1 = 2\r\n index2 = 3\r\n while flag:\r\n collumntupla = (listcol[index1], listcol[index2])\r\n listdata.append(collumntupla)\r\n index1 += 2\r\n index2 += 2\r\n if index2 > lencollumn:\r\n flag = False\r\n return listdata\r\n\r\n @staticmethod\r\n def readframe(df):\r\n df['Date'] = pd.to_datetime(df['Date'])\r\n df['Date'] = df['Date'].dt.strftime('%Y-%m-%d')\r\n df['Time'] = pd.to_datetime(df['Time'])\r\n df['Time'] = df['Time'].dt.strftime('%H:%M:%S')\r\n df['Date'] = df['Date'] + ' ' + df['Time']\r\n return df\r\n\r\n @staticmethod\r\n def stamp(*args):\r\n if args[2] == 1:\r\n namestamp1 = f'Sao Pedro-data-{args[0]}-{args[3]}-{args[1][12:21]}'\r\n return namestamp1\r\n elif args[2] == 2:\r\n namestamp2 = f'Juazeiro-data-{args[0]}-{args[3]}-{args[1][11:22]}'\r\n return namestamp2\r\n elif args[2] == 3:\r\n namestamp3 = f'Sol do Futuro-data-{args[0]}-{args[3]}-{args[1][16:27]}'\r\n return namestamp3","sub_path":"v1/steag_inverter.py","file_name":"steag_inverter.py","file_ext":"py","file_size_in_byte":2393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"12749133","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 23 10:27:40 2021\n\n@author: Tom\n\"\"\"\n\nimport liionpack as lp\nimport numpy as np\nimport pybamm\nimport matplotlib.pyplot as plt\n\nplt.close('all')\npybamm.logger.setLevel('NOTICE')\n\nNp = 16\nNs = 96\nNspm = Np * Ns\nI_app = Np * 2.0\n\n# Generate the netlist\nnetlist = lp.setup_circuit(Np=Np, Ns=Ns, Rb=1e-4, Rc=1e-2, Ri=5e-2, V=3.2, I=I_app)\n\noutput_variables = [\n 'X-averaged total heating [W.m-3]',\n 'Volume-averaged cell temperature [K]',\n 'X-averaged negative particle surface concentration [mol.m-3]',\n 'X-averaged positive particle surface concentration [mol.m-3]',\n]\n\n# Heat transfer coefficients\nhtc = np.ones(Nspm) * 10\n\n# Cycling protocol\nprotocol = lp.generate_protocol(I_dch=-I_app, I_chg=I_app, \n t_dch=100, t_chg=100, t_rest=100,\n chg_first=False)\n\n# PyBaMM parameters\nchemistry = pybamm.parameter_sets.Chen2020\nparameter_values = pybamm.ParameterValues(chemistry=chemistry)\n\n# lp.create_init_funcs(parameter_values)\n\n# Solve pack\noutput = lp.solve(netlist=netlist,\n parameter_values=parameter_values,\n protocol=protocol,\n output_variables=output_variables,\n htc=htc)\n\nlp.plot_output(output)\n","sub_path":"examples/scripts/big_circuit.py","file_name":"big_circuit.py","file_ext":"py","file_size_in_byte":1285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"119232231","text":"\"\"\"Benchmarks for the GridArchive.\"\"\"\nimport numpy as np\n\nfrom ribs.archives import GridArchive\n\n\ndef benchmark_add_10k(benchmark, benchmark_data_10k):\n n, solutions, objective_values, behavior_values = benchmark_data_10k\n\n def setup():\n archive = GridArchive((64, 64), [(-1, 1), (-1, 1)])\n archive.initialize(solutions.shape[1])\n\n # Let numba compile.\n archive.add(solutions[0], objective_values[0], behavior_values[0])\n\n return (archive,), {}\n\n def add_10k(archive):\n for i in range(n):\n archive.add(solutions[i], objective_values[i], behavior_values[i])\n\n benchmark.pedantic(add_10k, setup=setup, rounds=5, iterations=1)\n\n\ndef benchmark_get_10k_random_elites(benchmark, benchmark_data_10k):\n n, solutions, objective_values, behavior_values = benchmark_data_10k\n archive = GridArchive((64, 64), [(-1, 1), (-1, 1)])\n archive.initialize(solutions.shape[1])\n for i in range(n):\n archive.add(solutions[i], objective_values[i], behavior_values[i])\n\n def get_elites():\n for _ in range(n):\n archive.get_random_elite()\n\n benchmark(get_elites)\n\n\ndef benchmark_as_pandas_2025_items(benchmark):\n dim = 45\n archive = GridArchive((dim, dim), [(-1, 1), (-1, 1)])\n archive.initialize(10)\n\n for x in np.linspace(-1, 1, dim):\n for y in np.linspace(-1, 1, dim):\n sol = np.random.random(10)\n sol[0] = x\n sol[1] = y\n archive.add(sol, 1.0, np.array([x, y]))\n\n # Archive should be full.\n assert len(archive) == dim * dim\n\n benchmark(archive.as_pandas)\n","sub_path":"tests/archives/grid_archive_benchmark.py","file_name":"grid_archive_benchmark.py","file_ext":"py","file_size_in_byte":1612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"283463448","text":"def calc(a, b, c):\n return (a + b == c)\n\nt = int(input())\nwhile t > 0:\n a, b, c = map(int, input().split())\n a, b, c = a * a, b * b, c * c\n if calc(a, b, c) or calc(a, c, b) or calc(b, c, a):\n print('YES')\n else:\n print('NO')\n t -= 1\n","sub_path":"Online_Judge/Aizu/0003/14323720_AC_3ms_5604kB.py","file_name":"14323720_AC_3ms_5604kB.py","file_ext":"py","file_size_in_byte":266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"343088819","text":"'''Returns project values across multiple masters for specified keys of interest. Return for each key is provided\non a separate wb. Code can handle both standard and project milestone keys, as well as project name lists across\nmultiple quarters.\n\nThere are two outputs.\n1) wb containing all values\n2) wb containing bl values only\n\nConditional formatting is placed in the files as follows:\nrag_rating colours\nmissing data (md) = black grey\nproject not reporting (pnr) = light grey\nkey not collected (knc) = light blue grey\n'''\n\n\nfrom openpyxl import Workbook\nfrom analysis.data import list_of_masters_all, latest_quarter_project_names, root_path, gen_txt_list, \\\n gen_txt_colours, gen_fill_colours, list_column_ltrs, list_of_rag_keys, rag_txt_list_full, \\\n rag_fill_colours, rag_txt_colours, all_project_names, salmon_fill, bc_index\nfrom analysis.engine_functions import all_milestone_data_bulk, conditional_formatting, get_quarter_stamp\n\ndef return_data(project_name_list, data_key_list):\n \"\"\"Returns project values across multiple masters for specified keys of interest:\n project_names_list: list of project names\n data_key_list: list of data keys\n \"\"\"\n wb = Workbook()\n\n for i, key in enumerate(data_key_list):\n '''worksheet is created for each project'''\n ws = wb.create_sheet(key, i) # creating worksheets\n ws.title = key # title of worksheet\n\n '''list project names, groups and stage in ws'''\n for y, project_name in enumerate(project_name_list):\n\n # get project group info\n try:\n group = list_of_masters_all[0].data[project_name]['DfT Group']\n except KeyError:\n for m, master in enumerate(list_of_masters_all):\n if project_name in master.projects:\n group = list_of_masters_all[m].data[project_name]['DfT Group']\n\n ws.cell(row=2 + y, column=1, value=group) # group info return\n ws.cell(row=2 + y, column=2, value=project_name) # project name returned\n\n for x, master in enumerate(list_of_masters_all):\n if project_name in master.projects:\n try:\n #standard keys\n if key in list_of_masters_all[x].data[project_name].keys():\n value = list_of_masters_all[x].data[project_name][key]\n ws.cell(row=2 + y, column=3 + x, value=value) #returns value\n if value is None:\n ws.cell(row=2 + y, column=3 + x, value='md')\n\n try: # checks for change against last quarter\n lst_value = list_of_masters_all[x + 1].data[project_name][key]\n if value != lst_value:\n ws.cell(row=2 + y, column=3 + x).fill = salmon_fill\n except (KeyError, IndexError):\n pass\n\n # milestone keys\n else:\n milestones = all_milestone_data_bulk([project_name], list_of_masters_all[x])\n value = tuple(milestones[project_name][key])[0]\n ws.cell(row=2 + y, column=3 + x, value=value)\n ws.cell(row=2 + y, column=3 + x).number_format = 'dd/mm/yy'\n if value is None:\n ws.cell(row=2 + y, column=3 + x, value='md')\n\n try: # loop checks if value has changed since last quarter\n old_milestones = all_milestone_data_bulk([project_name], list_of_masters_all[x + 1])\n lst_value = tuple(old_milestones[project_name][key])[0]\n if value != lst_value:\n ws.cell(row=2 + y, column=3 + x).fill = salmon_fill\n except (KeyError, IndexError):\n pass\n\n except KeyError:\n if project_name in master.projects:\n #loop calculates if project was not reporting or data missing\n ws.cell(row=2 + y, column=3 + x, value='knc')\n else:\n ws.cell(row=2 + y, column=3 + x, value='pnr')\n\n else:\n ws.cell(row=2 + y, column=3 + x, value='pnr')\n\n '''quarter tag information'''\n ws.cell(row=1, column=1, value='Group')\n ws.cell(row=1, column=2, value='Projects')\n quarter_labels = get_quarter_stamp(list_of_masters_all)\n for l, label in enumerate(quarter_labels):\n ws.cell(row=1, column=l + 3, value=label)\n\n list_columns = list_column_ltrs[0:len(list_of_masters_all)+3]\n\n if key in list_of_rag_keys:\n conditional_formatting(ws, list_columns, rag_txt_list_full, rag_txt_colours, rag_fill_colours, '1', '60')\n\n conditional_formatting(ws, list_columns, gen_txt_list, gen_txt_colours, gen_fill_colours, '1', '60')\n\n return wb\n\ndef return_baseline_data(project_name_list, data_key_list):\n '''\n returns values of interest across multiple ws for baseline values only.\n project_name_list: list of project names\n data_key_list: list of data keys containing values of interest.\n '''\n wb = Workbook()\n\n for i, key in enumerate(data_key_list):\n '''worksheet is created for each project'''\n ws = wb.create_sheet(key, i) # creating worksheets\n ws.title = key # title of worksheet\n\n '''list project names, groups and stage in ws'''\n for y, project_name in enumerate(project_name_list):\n\n # get project group info\n try:\n group = list_of_masters_all[0].data[project_name]['DfT Group']\n except KeyError:\n for m, master in enumerate(list_of_masters_all):\n if project_name in master.projects:\n group = list_of_masters_all[m].data[project_name]['DfT Group']\n\n ws.cell(row=2 + y, column=1, value=group) # group info\n ws.cell(row=2 + y, column=2, value=project_name) # project name returned\n\n for x in range(0, len(bc_index[project_name])):\n index = bc_index[project_name][x]\n try: # standard keys\n value = list_of_masters_all[index].data[project_name][key]\n if value is None:\n ws.cell(row=2 + y, column=3 + x).value = 'md'\n else:\n ws.cell(row=2 + y, column=3 + x, value=value)\n except KeyError:\n try: # milestone keys\n milestones = all_milestone_data_bulk([project_name], list_of_masters_all[index])\n value = tuple(milestones[project_name][key])[0]\n if value is None:\n ws.cell(row=2 + y, column=3 + x).value = 'md'\n else:\n ws.cell(row=2 + y, column=3 + x).value = value\n ws.cell(row=2 + y, column=3 + x).number_format = 'dd/mm/yy'\n except KeyError: # exception catches both standard and milestone keys\n ws.cell(row=2 + y, column=3 + x).value = 'knc'\n except TypeError:\n ws.cell(row=2 + y, column=3 + x).value = 'pnr'\n\n ws.cell(row=1, column=1, value='Group')\n ws.cell(row=1, column=2, value='Project')\n ws.cell(row=1, column=3, value='Latest')\n ws.cell(row=1, column=4, value='Last quarter')\n ws.cell(row=1, column=5, value='BL 1')\n ws.cell(row=1, column=6, value='BL 2')\n ws.cell(row=1, column=7, value='BL 3')\n ws.cell(row=1, column=8, value='BL 4')\n ws.cell(row=1, column=9, value='BL 5')\n\n list_columns = list_column_ltrs[2:9] # hard coded so not ideal\n\n if key in list_of_rag_keys:\n conditional_formatting(ws, list_columns, rag_txt_list_full, rag_txt_colours, rag_fill_colours, '1', '60')\n\n conditional_formatting(ws, list_columns, gen_txt_list, gen_txt_colours, gen_fill_colours, '1', '60')\n\n return wb\n\n'''data keys of interest. Place all keys of interest as stings in this list'''\ndata_interest = ['Project End Date']\n\n'''Running the programme'''\n\n'''output one - all data. \nfirst variable = list of project names. There are two options. 1) latest_quarter_project_names 2) all_projects_names\n(which includes older projects that are not currently reporting. \nsecond variable = data_interest. This name does not change. List compiled above'''\nrun_standard = return_data(latest_quarter_project_names, data_interest)\n\n'''output two - bl data\nfirst variable = list of project names. There are two options. 1) latest_quarter_project_names 2) all_projects_names\n(which includes older projects that are not currently reporting. \nsecond variable = data_interest. This name does not change. List compiled above'''\nrun_baseline = return_baseline_data(latest_quarter_project_names, data_interest)\n\n'''Specify name of the output document here. See general guidance re saving output files'''\nrun_standard.save(root_path/'output/data_query.xlsx')\nrun_baseline.save(root_path/'output/data_query_bl.xlsx')\n\n'''old lists stored here for use in future'''\nproject_basics = ['Brief project description (GMPP - brief descripton)',\n 'Delivery Narrative']\n\nvfm_analysis_list = ['Departmental DCA',\n 'Working Contact Name',\n 'Working Contact Email',\n 'Brief project description (GMPP - brief descripton)',\n 'Business Case & Version No.',\n 'BICC approval point',\n 'NPV for all projects and NPV for programmes if available',\n 'Initial Benefits Cost Ratio (BCR)',\n 'Adjusted Benefits Cost Ratio (BCR)',\n 'VfM Category single entry',\n 'VfM Category lower range',\n 'VfM Category upper range',\n 'Present Value Cost (PVC)',\n 'Present Value Benefit (PVB)',\n 'SRO Benefits RAG',\n 'Benefits Narrative',\n 'Ben comparison with last quarters cost - narrative']\n\nipa_ar_fields_1920 = ['Department',\n '19-20 RDEL BL Total',\n '19-20 CDEL BL WLC',\n '19-20 RDEL Forecast Total',\n '19-20 CDEL Forecast Total WLC',\n 'Total BL',\n 'GMPP - IPA ID Number']\n\nmilestones = ['Start of Operation',\n 'Full Operations',\n 'Project End Date']\n\ncosts = ['Total Forecast']\n\nrags = ['SRO Benefits RAG',\n 'GMPP - IPA DCA']\n\nbaselines = ['IPDC approval point']","sub_path":"data_query/data_query.py","file_name":"data_query.py","file_ext":"py","file_size_in_byte":11071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"181774015","text":"\"\"\"ChunkLoader related utilities.\n\"\"\"\n\n\ndef get_data_id(layer) -> int:\n \"\"\"Return the data_id to use for this layer.\n\n Parameters\n ----------\n layer\n The layer to get the data_id from.\n\n Notes\n -----\n We use data_id rather than just the layer_id, because if someone\n changes the data out from under a layer, we do not want to use the\n wrong chunks.\n \"\"\"\n data = layer.data\n if isinstance(data, list):\n assert data # data should not be empty for image layers.\n return id(data[0]) # Just use the ID from the 0'th layer.\n\n return id(data) # Not a list, just use it.\n","sub_path":"napari/components/chunk/_utils.py","file_name":"_utils.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"320712632","text":"# For BEASTBOT v3\n# By Priyam Kalra\n# Syntax .ipadrop [or as a reply to IPA file]\n\nimport os\nimport math\nimport time\nimport asyncio\nimport httplib2\nimport requests\n\nfrom random import randint\nfrom dropbox import dropbox\nfrom datetime import datetime\nfrom mimetypes import guess_type\nfrom oauth2client.file import Storage\nfrom apiclient.discovery import build\nfrom apiclient.http import MediaFileUpload\nfrom oauth2client import file, tools\nfrom apiclient.errors import ResumableUploadError\nfrom oauth2client.client import OAuth2WebServerFlow\n\n# Global Variables\nG_DRIVE_TOKEN_FILE = Config.DOWNLOAD_DIRECTORY + \"/auth_token.txt\"\nCLIENT_ID = Config.DRIVE_CLIENT_ID\nCLIENT_SECRET = Config.DRIVE_CLIENT_SECRET\nOAUTH_SCOPE = \"https://www.googleapis.com/auth/drive.file\"\nREDIRECT_URI = \"urn:ietf:wg:oauth:2.0:oob\"\nfolder_link = Config.IPABOX_FOLDER\nfolder_id = None\nif folder_link is not None:\n if folder_link.endswith(\"?usp=sharing\"):\n folder_link = folder_link[:-12]\n link_split = folder_link.split(\"/\")\n link = link_split[-1]\n if link.startswith(\"open?id=\"):\n link = link[8:]\n folder_id = link\nG_DRIVE_F_PARENT_ID = folder_id\ntoken_file = Config.DROPBOX_TOKEN\ndrive_acc = Config.DRIVE_ACCOUNT\n\n\n# Select a mode - dbx or drive\n@client.on(register(pattern=\"ipabox\"))\nasync def drive(event):\n message = \"Please specify as valid mode:\\nUse .ipadrive to use google drive or .ipadrop to use dropbox for hosting installations.\"\n await event.edit(message)\n return\n\n\n@client.on(register(pattern=\"ipadrop ?(.*)\"))\nasync def dbx(event):\n if token_file is None:\n return await event.edit(f\"You need to set `DROPBOX_TOKEN` enviroment variable!\")\n host = \"dbx\"\n await main(host, event)\n\n\n@client.on(register(pattern=\"ipadrive ?(.*)\"))\nasync def drive(event):\n if drive_acc is None:\n return await event.edit(f\"You need to set `G_DRIVE_ACCOUNT` enviroment variable!\")\n host = \"drive\"\n await main(host, event)\n\n# Main function that connects everything else together\n\n\nasync def main(mode, msg):\n event = msg\n args = event.pattern_match.group(1)\n idnum = randint(101, 9999999999)\n ipa = await download(args, event, idnum)\n if not os.path.exists(ipa):\n await event.edit(\"404: IPA not found!\")\n return\n else:\n ipa_link = await upload(mode, ipa, event)\n ipa_dl_link = get_dl_link(mode, ipa_link)\n get_plist(ipa_dl_link, ipa)\n manifest = f\"manifest_{name}.plist\"\n with open(manifest, \"w\") as f:\n f.write(plist)\n manifest_link = await upload(mode, manifest, event, idnum)\n manifest_dl_link = get_dl_link(mode, manifest_link)\n final_link = get_itunes_link(manifest_dl_link)\n message = f\"\\nRun this link in safari to install `{name}`:\\n`{final_link}`\\nIf the app icon is grey after installation, the IPA file has expired.\"\n if G_DRIVE_F_PARENT_ID is None:\n tip = \"\\n\\nTIP: To store all the IPAbox files in one folder, create a folder named \\\"IPAbox\\\" in the root of your drive, copy its link and paste it in env variable \\\"IPABOX_FOLDER\\\".\"\n message += tip\n await event.edit(message)\n await log(message)\n clean(ipa, manifest)\n\n\n# Simple userbot logging\nasync def log(text):\n await client.send_message(LOGGER, text)\n\n\n# Cleans the files\ndef clean(*args):\n for i in args:\n try:\n os.remove(i)\n except FileNotFoundError:\n pass\n\n\n# Returns an itunes link which can be used for on-air installation\ndef get_itunes_link(link):\n itunes_prefix = \"itms-services://?action=download-manifest&url=\"\n itunes_link = itunes_prefix + link\n return itunes_link\n\n\n# Converts dropbox sharing link into usercontent link\ndef get_dl_link(mode, link):\n if mode == \"drive\":\n drivetw_url = f\"https://drv.tw/~{drive_acc}/gd/{link}\"\n return drivetw_url\n elif mode == \"dbx\":\n if not link.startswith(\"https://www.dropbox.com/s/\"):\n return link\n link = link[26:]\n if link.endswith(\"?dl=0\"):\n link = link[:-5]\n dl_link = \"https://dl.dropboxusercontent.com/s/\" + link\n return dl_link\n\n\n# Downloads data to local server and returns path\nasync def download(url, msg, id):\n idnum = id\n args = url\n event = msg\n if event.reply_to_msg_id:\n reply_message = await event.get_reply_message()\n try:\n c_time = time.time()\n downloaded_file_name = await client.download_media(\n reply_message,\n \"/app/\",\n progress_callback=lambda d, t: asyncio.get_event_loop().create_task(\n progress(d, t, event, c_time, \"Downloading IPA..\")\n )\n )\n except Exception as e:\n await event.edit(str(e))\n else:\n await event.edit(f\"Downloaded IPA to `{downloaded_file_name}`.\")\n ipa_split = downloaded_file_name.split(\"/\")\n ipa_full = ipa_split[-1]\n ipa_noext = ipa_full[:-4]\n ipa = f\"{ipa_noext}_{idnum}.ipa\"\n os.rename(ipa_full, ipa)\n return ipa\n elif args.startswith(\"http\"):\n if not args.endswith(\".ipa\"):\n return await event.edit(\"Unsupported link!\\nPlease provide a direct link to the IPA file.\")\n ipa_split = args.split(\"/\")\n ipa = ipa_split[-1]\n ipa_noext = ipa[:-4]\n ipa = f\"{ipa_noext}_{idnum}.ipa\"\n await event.edit(f\"Downloading IPA: `{ipa}`\")\n request = requests.get(args)\n with open(ipa, \"wb\") as f:\n f.write(request.content)\n return ipa\n\n\n# Prepare enviroment for drive upload and return sharing link after completion\nclass DriveUpload:\n def __init__(self, file):\n self.file = file\n\n async def upload_file(self, event, idnum=None):\n filename = self.file\n filepath = filename\n if G_DRIVE_F_PARENT_ID is not None:\n filepath = f\"IPAbox/{filename}\"\n if filename.startswith(\"manifest_\"):\n display_name = filename[:int(f\"-{len(str(idnum))+7}\")]\n elif filename.endswith(\".ipa\"):\n display_name = filename[:-4]\n if not filename:\n return await event.edit(\"404: IPA not found\")\n if Config.DRIVE_AUTH_TOKEN_DATA is not None:\n with open(G_DRIVE_TOKEN_FILE, \"w\") as t_file:\n t_file.write(Config.DRIVE_AUTH_TOKEN_DATA)\n storage = None\n if not os.path.isfile(G_DRIVE_TOKEN_FILE):\n storage = await create_token_file(G_DRIVE_TOKEN_FILE, event)\n http = authorize(G_DRIVE_TOKEN_FILE, storage)\n mime_type = file_ops(filename)\n try:\n await event.edit(f\"Processing `{display_name}`: 0%\")\n await upload_to_drive(http, filename, filename, mime_type, event, G_DRIVE_F_PARENT_ID)\n await event.edit(f\"Processing `{display_name}`: 100%\")\n return filepath\n except Exception as e:\n await event.edit(f\"Looks like something went wrong while uploading `{display_name}` to drive: {e}\")\n return\n\n\n# Uploads data to dropbox and returns sharing link\nclass DropboxUpload:\n def __init__(self, access_token):\n self.access_token = access_token\n\n async def upload_file(self, file_path, dest_path, msg, idnum=None):\n dbx = dropbox.Dropbox(self.access_token, timeout=None)\n filename = file_path\n if filename.startswith(\"manifest_\"):\n filename = filename[:int(f\"-{len(str(idnum))+7}\")]\n elif filename.endswith(\".ipa\"):\n filename = filename[:-4]\n try:\n with open(file_path, \"rb\") as f:\n file_size = os.path.getsize(file_path)\n CHUNK_SIZE = 5 * 1024 * 1024\n if file_size <= CHUNK_SIZE:\n await msg.edit(f\"Processing `{filename}`..\")\n dbx.files_upload(f.read(), dest_path)\n else:\n upload_session_start_result = dbx.files_upload_session_start(\n f.read(CHUNK_SIZE))\n progress = int(CHUNK_SIZE/file_size*100)\n if msg != None:\n await msg.edit(f\"Processing `{filename}`: {progress}%\")\n cursor = dropbox.files.UploadSessionCursor(\n session_id=upload_session_start_result.session_id, offset=f.tell())\n commit = dropbox.files.CommitInfo(path=dest_path)\n while f.tell() < file_size:\n if ((file_size - f.tell()) <= CHUNK_SIZE):\n dbx.files_upload_session_finish(\n f.read(CHUNK_SIZE), cursor, commit)\n await msg.edit(f\"Processing `{filename}`: 100%\")\n else:\n dbx.files_upload_session_append(\n f.read(CHUNK_SIZE), cursor.session_id, cursor.offset)\n cursor.offset = f.tell()\n progress = int(f.tell()/file_size*100)\n await msg.edit(f\"Processing `{filename}`: {progress}%\")\n shared_link_metadata = dbx.sharing_create_shared_link_with_settings(\n dest_path)\n link = shared_link_metadata.url\n return link\n except FileNotFoundError:\n return False\n\n\n# Initialization for upload\nasync def upload(mode, ipa_path, mesg, num=None):\n if mode == \"drive\":\n origin = ipa_path\n driveupload = DriveUpload(ipa_path)\n link = await driveupload.upload_file(mesg, num)\n return link\n elif mode == \"dbx\":\n access_token = token_file\n dropboxupload = DropboxUpload(access_token)\n file_from = ipa_path\n file_to = f\"/IPAdropTG/{file_from}\"\n link = await dropboxupload.upload_file(file_from, file_to, msg=mesg, idnum=num)\n return link\n\n# Upload data to drive\n\n\nasync def upload_to_drive(http, file_path, file_name, mime_type, event, parent_id):\n drive_service = build(\"drive\", \"v2\", http=http, cache_discovery=False)\n media_body = MediaFileUpload(file_path, mimetype=mime_type, resumable=True)\n body = {\n \"title\": file_name,\n \"description\": \"Used for hosting OTA Installations - IPAbox\",\n \"mimeType\": mime_type,\n }\n if parent_id is not None:\n body[\"parents\"] = [{\"id\": parent_id}]\n permissions = {\n \"role\": \"reader\",\n \"type\": \"anyone\",\n \"value\": None,\n \"withLink\": True\n }\n file = drive_service.files().insert(body=body, media_body=media_body)\n response = None\n display_message = \"\"\n while response is None:\n status, response = file.next_chunk()\n await asyncio.sleep(1)\n if status:\n percentage = int(status.progress() * 100)\n if display_message != percentage:\n try:\n await event.edit(f\"Processing `{file_name}`: {percentage}%\")\n display_message = percentage\n except Exception as e:\n logger.info(str(e))\n pass\n file_id = response.get(\"id\")\n try:\n drive_service.permissions().insert(fileId=file_id, body=permissions).execute()\n except:\n pass\n file = drive_service.files().get(fileId=file_id).execute()\n download_url = file.get(\"webContentLink\")\n return file_id\n\n# Get mime type and name of given file\n\n\ndef file_ops(file_path):\n mime_type = guess_type(file_path)[0]\n mime_type = mime_type if mime_type else \"text/plain\"\n return mime_type\n\n# Run through the OAuth flow and retrieve credentials\n\n\nasync def create_token_file(token_file, event):\n flow = OAuth2WebServerFlow(\n CLIENT_ID,\n CLIENT_SECRET,\n OAUTH_SCOPE,\n redirect_uri=REDIRECT_URI\n )\n authorize_url = flow.step1_get_authorize_url()\n async with event.client.conversation(Config.LOGGER_GROUP) as conv:\n await conv.send_message(f\"Go to the following link in your browser: {authorize_url} and reply the code\")\n response = conv.wait_event(events.NewMessage(\n outgoing=True,\n chats=Config.LOGGER_GROUP\n ))\n response = await response\n code = response.message.message.strip()\n credentials = flow.step2_exchange(code)\n storage = Storage(token_file)\n storage.put(credentials)\n return storage\n\n# Get credentials\n\n\ndef authorize(token_file, storage):\n if storage is None:\n storage = Storage(token_file)\n credentials = storage.get()\n http = httplib2.Http()\n credentials.refresh(http)\n http = credentials.authorize(http)\n return http\n\n# Returns manifest/plist for app\n\n\ndef get_plist(ipaurl, ipaname):\n global plist, name\n name = ipaname\n if name.endswith(\".ipa\"):\n name = name[:-4]\n plist = f\"\"\"\n\n\n\n\n items\n \n \n assets\n \n \n kind\n software-package\n url\n {ipaurl}\n \n\t\t\t\t\n\t\t\t\t\tkind\n\t\t\t\t\tfull-size-image\n\t\t\t\t\tneeds-shine\n\t\t\t\t\t\n\t\t\t\t\turl\n\t\t\t\t\thttps://raw.githubusercontent.com/PriyamKalra/IPAbox/master/icon.png\n\t\t\t\t\n \n kind\n display-image\n needs-shine\n \n url\n https://raw.githubusercontent.com/PriyamKalra/IPAbox/master/icon.png\n \n metadata\n \n bundle-identifier\n com.{name}.app\n bundle-version\n v1.0.0\n kind\n software\n subtitle\n {name}\n title\n {name}\n \n \n \n\n\n\"\"\"\n\n\nConfig.HELPER.update({\n \"ipabox\": \"\\\n```.ipadrop [or as a reply to IPA file]```\\\n\\nUsage: Provide a direct link or reply to an IPA file to host an OTA installation via dropbox.\\\n\\n\\n```.ipadrive [or as a reply to IPA file]```\\\n\\nUsage: Provide a direct link or reply to an IPA file to host an OTA installation via google drive.\\\n\"\n})\n","sub_path":"modules/ipabox.py","file_name":"ipabox.py","file_ext":"py","file_size_in_byte":14814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"222916729","text":"# Prop Code\n# Don Kuettel\n\"\"\"This code propagates a trajectory of a spacecraft around Bennu \nwith a finite low-thrust burn incorparated using cartesian coordinates.\n\nCURRENTLY USING KEPLERIAN DYNAMICS\n\n\"\"\"\n\n####################\n## Import modules ##\n####################\nimport time\nimport numpy as np\nimport constants as c\nfrom bodies import Body\nimport coord_trans as ct\nfrom math import factorial\nimport astro_functions as af\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import odeint\nfrom legendre_poly import legendre_poly\nfrom mpl_toolkits.mplot3d import Axes3D\n\n\n######################\n## Global Constants ##\n######################\n\n\n######################\n## Define Functions ##\n######################\n# -------------------------------------------------------------------\ndef odefun_burn(X, t, mu_host, r_bod, isp, T, A, B):\n \"\"\"This function computes the keplerian velocity and acceleration \n of a spacecraft's state accounting for gravity field, srp, and \n solar gravity perturbations. \n\n ASSUMPTIONS:\n \n INPUT:\n X - 7 dimensional state of the spacecraft in a numpy array\n where X = [a, e, i, raan, w, nu, kg] in [km], [rad], and\n [kg]\n t - time of integration in seconds\n constants:\n u - control law acceleration in [km/s^2]\n mu_host - gravitational parameter of central\n body [km^3/s^2]\n R - radius of central body in [km]\n isp - specific impulse of thruster\n T - thrust\n A - guidance constants\n B - guidance constants\n\n OUTPUT:\n dX - dX/dt. 7x1 matrix of the spacraft velocity and \n acceleration where dX = [vx, vy, vz, ax, ay, az, mdot] \n in [m/s], [m/s2], and [kg/s]\n\n NOTES:\n This derivation uses the normalized spherical harmonic \n coefficents (C_lm and S_lm).\n \"\"\"\n\n dX = np.zeros(len(X))\n g0 = 9.80665\n \n # Orbital Elements\n a = X[0] # semi-major axis [km]\n e = X[1] # eccentricity [-]\n inc = X[2] # inclination [rad]\n raan = X[3] # right ascension of the ascending node [rad]\n w = X[4] # argument of periapsis [rad]\n nu = X[5] # true anomaly [rad]\n mass = X[6] # Mass [kg]\n\n oe = X[0:6]\n p = a*(1 - e*e)\n h = np.sqrt(mu_host*p)\n r_mag = p/(1 + e*np.cos(nu))\n\n # Mass flow rate\n at = T/mass\n m_dot = T/g0/isp\n\n # Control (A and B are defined in BCI frame)\n u = A + B*t\n # u_hat_bci = u/np.sqrt(u.dot(u))\n u_hat_bci = u/np.sqrt(u.dot(u))\n u_hat = ct.CoordTrans('BCI', 'RSW', u_hat_bci, oe=oe)\n\n # Perturbations\n if r_mag < r_bod:\n u_hat = float('NaN')\n print('ERROR: SC is inside the host body!')\n\n FR = at*u_hat[0]\n FS = at*u_hat[1]\n FW = at*u_hat[2]\n\n # LPEs\n dX[0] = 2*a*a/h*(e*np.sin(nu)*FR + p/r_mag*FS)\n dX[1] = (p*np.sin(nu)*FR + ((p + r_mag)*np.cos(nu) + r_mag*e)*FS)/h\n dX[2] = r_mag*np.cos(w + nu)/h*FW\n dX[3] = r_mag*np.sin(w + nu)/h/np.sin(inc)*FW\n dX[4] = (-p*np.cos(nu)*FR + (p + r_mag)*np.sin(nu)*FS)/h/e - r_mag*np.sin(w + nu)*np.cos(inc)/h/np.sin(inc)*FW\n dX[5] = h/r_mag/r_mag + (p*np.cos(nu)*FR - (p + r_mag)*np.sin(nu)*FS)/e/h\n dX[6] = -m_dot\n\n return dX\n# -------------------------------------------------------------------\n\n\n#################\n## Main Script ##\n#################\ndef main():\n\n tic = time.time()\n\n # ===========================================================\n ## INITIAL CONSTANTS ##\n\n # Initial Conditions\n r_bod = 246. # m, radius of central body\n mu = 5.2 # m3/s2, gravitational parameter\n a0 = 1000. # m, semi-major axis\n e0 = 0.01 # -, eccentricity\n inc0 = np.deg2rad(90) # rad, inclination\n raan0 = np.deg2rad(270) # rad, raan\n w0 = np.deg2rad(0) # rad, arg of periapsis\n nu0 = np.deg2rad(300) # rad, true anomaly\n oe0 = [a0, e0, inc0, raan0, w0, nu0]\n\n # Thruster Specs\n m0 = 1000. # kg\n T = 4e-3 # N\n isp = 2000. # s-1, specific impulse\n\n # Guidance Parameters\n A = np.array([-100., 50., 0.])\n B = np.array([5e-3, 1e-2, 0.])\n\n # Time\n t0 = 0. # sec, initial time\n t_cutoff = 1.*3*60*60 # sec, end-of-burn time\n t_fin = 1.*25*60*60 # sec, final time\n tstep = 60. # sec, time step\n\n # Integration Constants\n mu_sun = c.mu_sun*1000*1000*1000\n d_sun = c.AU*1000*1.3559 #*0.8969\n r_sun = c.r_sun*1000\n Cr = 1.2\n a2m = 0.01\n degree = 5\n order = 5\n theta_gst0 = np.deg2rad(0)\n\n body_extras = {}\n body_extras['degree'] = degree\n body_extras['order'] = order\n body_cons = Body('bennu', True, body_extras)\n w_body = body_cons['w_body']\n gc = body_cons['gc']\n\n A = np.array([30.24484547, 49.59282314, -18.88564783])\n B = np.array([0.0298361, -0.07089163, 0.00883016])\n\n extras_burn = (mu, r_bod, isp, T, A, B)\n # extras_burn = (mu, mu_sun, d_sun, r_sun, r_bod, Cr, a2m, degree, order, theta_gst0, w_body, gc, isp, T, A, B)\n # extras_coast = (mu, mu_sun, d_sun, r_sun, r_bod, Cr, a2m, degree, order, theta_gst0, w_body, gc)\n # ===========================================================\n\n # ===========================================================\n ## INTEGRATION ##\n\n # Burn\n # X_burn = [np.hstack([oe0, m0])]\n X_burn = [np.array([2.14814402e+00*500, 7.33109114e-02, 1.57443680e+00, 4.70540223e+00, -3.12376167e-01, 5.51325672e+00, 9.99999951e+02])]\n t = 240.; tvec_burn = [t]\n t_cutoff = 11349.6221593\n tvec = np.linspace(t, t_cutoff, 1e2)\n\n X_oe, infodict = odeint(odefun_burn, X_burn[-1], tvec, \n args=extras_burn, rtol=1e-10, atol=1e-10, full_output=1)\n\n print(infodict)\n\n X_rv = []\n for val in X_oe:\n test = af.kep2cart(val[0:6], mu)\n X_rv.append(np.hstack((test)))\n\n if val[2] > 2*np.pi:\n val[2] -= 2*np.pi\n elif val[2] < 2*np.pi:\n val[2] += 2*np.pi\n\n if val[3] > 2*np.pi:\n val[3] -= 2*np.pi\n elif val[3] < 2*np.pi:\n val[3] += 2*np.pi\n\n if val[4] > 2*np.pi:\n val[4] -= 2*np.pi\n elif val[4] < 2*np.pi:\n val[4] += 2*np.pi\n\n if val[5] > 2*np.pi:\n val[5] -= 2*np.pi\n elif val[5] < 2*np.pi:\n val[5] += 2*np.pi\n\n if val[6] > 2*np.pi:\n val[6] -= 2*np.pi\n elif val[6] < 2*np.pi:\n val[6] += 2*np.pi\n\n X_rv = np.asarray(X_rv)\n\n\n # ------------------------------------------------------------\n # 3D Plot\n plt.figure()\n ax = plt.axes(projection='3d')\n\n # Burn Plot\n ax.plot(X_rv[:,0], X_rv[:,1], X_rv[:,2], '-k')\n ax.plot([X_rv[0,0]], [X_rv[0,1]], [X_rv[0,2]], 'og')\n ax.plot([X_rv[-1,0]], [X_rv[-1,1]], [X_rv[-1,2]], 'or')\n \n # Plot Labels\n ax.set_xlabel('X [m]')\n ax.set_ylabel('Y [m]')\n ax.set_zlabel('Z [m]')\n plt.title(r'Spacecraft Trajectory', fontsize=14)\n # ------------------------------------------------------------\n\n # ------------------------------------------------------------\n # Position Component Plot\n \n fig = plt.figure()\n ax1 = fig.add_subplot(311)\n plt.grid()\n plt.plot(tvec/3600, X_oe[:,0], '-k')\n plt.xlim([0, tvec[-1]/3600])\n plt.ylabel('a [m]'); plt.title('OE Components')\n\n ax2 = fig.add_subplot(312)\n plt.grid()\n plt.plot(tvec/3600, X_oe[:,1], '-k')\n plt.xlim([0, tvec[-1]/3600])\n plt.ylabel('e [-]')\n\n ax3 = fig.add_subplot(313)\n plt.grid()\n plt.plot(tvec/3600, np.rad2deg(X_oe[:,2]), '-k')\n plt.xlim([0, tvec[-1]/3600])\n plt.ylim([0, 180])\n plt.ylabel('inc [deg]'); plt.xlabel('Time [hr]')\n \n # ------------------------------------------------------------\n \n # ------------------------------------------------------------\n # Velocity Component Plot\n \n fig = plt.figure()\n ax1 = fig.add_subplot(311)\n plt.grid()\n plt.plot(tvec/3600, np.rad2deg(X_oe[:,3]), '-k')\n plt.xlim([0, tvec[-1]/3600])\n plt.ylim([0, 360])\n plt.ylabel('raan [deg]'); plt.title('OE Components')\n\n ax2 = fig.add_subplot(312)\n plt.grid()\n plt.plot(tvec/3600, np.rad2deg(X_oe[:,4]), '-k')\n plt.xlim([0, tvec[-1]/3600])\n plt.ylim([0, 360])\n plt.ylabel('w [deg]')\n\n ax3 = fig.add_subplot(313)\n plt.grid()\n plt.plot(tvec/3600, np.rad2deg(X_oe[:,5]), '-k')\n plt.xlim([0, tvec[-1]/3600])\n plt.ylim([0, 360])\n plt.ylabel('nu [deg]'); plt.xlabel('Time [hr]')\n\n # ------------------------------------------------------------\n\n\n # burn = [1]\n # while t < t_cutoff:\n\n # # ICs\n # IC_current = X_burn[-1]\n\n # # Time\n # tspan = [t, t + tstep]\n # if tspan[-1] >= t_cutoff:\n # tspan[-1] = t_cutoff\n # t = t_cutoff\n # else:\n # t += tstep\n # tvec_burn.append(tspan[-1])\n\n # X_step = odeint(odefun_burn, IC_current, tspan, \n # args=extras_burn, rtol=1e-10, atol=1e-10)\n # X_burn.append(X_step[-1])\n\n # burn.append(1)\n\n # X_burn = np.asarray(X_burn)\n # tvec_burn = np.asarray(tvec_burn)\n\n # # Finishing Integration\n # if t < t_fin:\n # tvec_fin = np.arange(t, t_fin+tstep, tstep*5)\n # tvec_fin[-1] = t_fin\n # X_fin = odeint(odefun_coast, X_burn[-1], tvec_fin, \n # args=extras_coast, rtol=1e-10, atol=1e-10)\n\n # X = np.vstack((X_burn, X_fin))\n # tvec = np.hstack((tvec_burn, tvec_fin))\n # burn = np.hstack((burn, np.zeros(len(tvec_fin))))\n\n\n # ===========================================================\n\n # ===========================================================\n ## SAVING DATA\n save_traj =False\n if save_traj:\n SAVE = []\n\n SAVE.append(X[:,0]); SAVE.append(X[:,1]); SAVE.append(X[:,2])\n SAVE.append(X[:,3]); SAVE.append(X[:,4]); SAVE.append(X[:,5])\n SAVE.append(X[:,-1]); SAVE.append(burn); SAVE.append(tvec)\n np.savetxt('full_bennu_nom_traj.txt', SAVE, delimiter=',')\n\n # ===========================================================\n\n toc = time.time()\n\n print('\\n', (toc - tic), 'seconds elapsed.')\n\n plt.show()\n\nif __name__ == '__main__':\n main()","sub_path":"propagation/prop_code_oe.py","file_name":"prop_code_oe.py","file_ext":"py","file_size_in_byte":10423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"450757825","text":"import smtplib\nimport TextToSpeech\nimport sys\nimport time\nimport os\ncwd = os.getcwd()\n\ndirectory = \"\"\nmadLibType = \"\"\n\n\ndef getFile():\n choice = input(\"\\nWould you like to create a madlib about pizza, apples, or thanksgiving?\\n-> \").lower()\n while True:\n if choice.__contains__(\"apple\"):\n return \"Apples\"\n break\n elif choice.__contains__(\"pizza\"):\n return \"Pizza\"\n break\n elif choice.__contains__(\"thanks\"):\n return \"Thanksgiving\"\n break\n else:\n choice = input(\"\\nSorry, I don't understand, choose between a madlib about pizza, apples, or thanksgiving.\\n-> \")\n\n\ndef findWord(input, index=False):\n frontIndex = input.index(\"<\")\n\n if not index:\n output = input[frontIndex:]\n rearIndex = output.index(\">\")\n output = str(output[:rearIndex + 1])\n output = output.replace(\"<\", \"\").replace(\">\", \"\")\n return output\n else:\n return frontIndex\n return rearIndex\n\n\ndef checkIfPlural(input):\n input = str(input)\n index = len(input) - 1\n if input[index:] == \"s\":\n return True\n else:\n return False\n\n\ndef checkVowel(input):\n input = str(input)\n input = input[:1]\n if input == \"a\" or input == \"e\" or input == \"i\" or input == \"o\" or input == \"u\":\n return True\n else:\n return False\n\ndef getSingular(input):\n input = str(input)\n index = len(input) - 1\n return str(input[:index])\n\n\ndef getAdjectiveQuestion(input):\n if checkVowel(input):\n return \"Please enter an \" + input\n else:\n return \"Please enter a \" + input\n\ndef sendMail(messageInput):\n email = input(\"\\nPlease enter your email address\\n-> \")\n\n server = smtplib.SMTP('smtp.gmail.com', 587)\n server.starttls()\n server.login('autosendpy@gmail.com', 'oUUgw3Zp95MWDzWX9U0u0UtSl')\n message = messageInput\n sender = 'autosendpy@gmail.com'\n reciever = email\n server.send\n server.sendmail(sender, reciever, message)\n print(\"\\nEmail sent successfully!\")\n\n server.close()\n\ndef saveType():\n choice = input(\"Would you like your Madlib saved locally, or have it emailed to you?\\n-> \").lower()\n while True:\n if choice.__contains__(\"local\") or choice.__contains__(\"here\"):\n choice = \"l\"\n break\n elif choice.__contains__(\"email\") or choice.__contains__(\"sent\") or choice.__contains__(\"send\"):\n choice = \"e\"\n break\n else:\n choice = input(\"\\nSorry, I don't understand. Would you like your Madlib saved\" +\n \" locally, or would you liked it emailed to you?\\n-> \")\n return choice\n\ndef textToSpeech(localDir, typeMadLib):\n tts = open(cwd+\"/MadLib/\" + typeMadLib + \"Final.txt\", 'r+')\n lineList = tts.readlines()\n listLength = int(100 / len(lineList))\n listIndex = 0\n\n while listIndex < len(lineList):\n line = lineList[listIndex]\n TextToSpeech.textToSpeech(line, str(listIndex + 1))\n listIndex += 1\n sys.stdout.write(\"\\rDownloading: %d\" % (listLength * listIndex) + \"%\")\n time.sleep(0.2)\n sys.stdout.flush()\n\n time.sleep(0.2)\n sys.stdout.write(\"\\rDownloaded!: 100%\")\n max = listIndex + 1\n listIndex = 2\n\n file = open(cwd+\"/Audio/\" + typeMadLib + \".mp3\", \"wb+\")\n fileContent = \"\"\n concatFile = open(cwd+\"/Audio/response1.mp3\", \"rb\").read()\n fileContent = concatFile\n while listIndex < max:\n tempFile = open(cwd+\"/Audio/response\" + str(listIndex) + \".mp3\", \"rb\").read()\n fileContent += tempFile\n listIndex += 1\n file.write(fileContent)\n print(\"\\nFile was written to the directory:\"+cwd+\"/Audio/\" + typeMadLib + \".mp3\")\n file.close()\n\n\ndef main():\n print(\"Welcome to MadLib maker!\")\n time.sleep(0.2)\n madLibType = getFile()\n directory = cwd+\"/MadLib/\" + madLibType\n\n customDir = input(\"Would you like to save to a custom directory?\\n-> \").lower()\n if customDir.__contains__('y'):\n directory = input(\"\\nPlease enter the directory you would like to save to: \")\n while not directory:\n directory = input(\"\\nDirectory not valid. Please enter a new directory: \")\n\n\n file = open(cwd+\"/MadLib/\" + madLibType + \".txt\", \"r+\")\n modFile = open(directory + \"Final.txt\", 'w+')\n\n lines = file.readlines()\n sentenceNum = 0\n\n while sentenceNum < len(lines):\n line = lines[sentenceNum]\n while line.__contains__(\"<\"):\n word = findWord(line)\n question = getAdjectiveQuestion(word)\n response = input(question + \": \")\n line = line.replace(\"<\" + word + \">\", response)\n modFile.write(line)\n sentenceNum += 1\n\n\n\n save = saveType()\n if save == \"l\":\n print(\"\\nFile \\\"\" + modFile.name + \"\\\" was saved to the directory ~\" + directory)\n modFile.close()\n elif save == \"e\":\n modFile.close()\n with open(directory + \"Final.txt\", 'r+') as content_file:\n content = content_file.read()\n sendMail(content)\n\n\n listen = input(\"\\nWould you like to hear your Madlib read back to you?\\n-> \").lower()\n if listen.__contains__(\"y\"):\n textToSpeech(directory, madLibType)\n else:\n print(\"Ok, goodbye!\")\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Presentation_1/MadLib.py","file_name":"MadLib.py","file_ext":"py","file_size_in_byte":5309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"1293622","text":"class Solution:\n\t# @param {integer} n\n\t# @return {integer}\n\tdef climbStairs(self, n):\n\t\tif(n == 1):\n\t\t\treturn 1\n\t\telif(n == 2):\n\t\t\treturn 2\n\t\telse:\n\t\t\tcnt, pre, now = 1, 1, 2\n\t\t\twhile (cnt < n - 1):\n\t\t\t\ttmp = pre + now\n\t\t\t\tpre = now\n\t\t\t\tnow = tmp\n\t\t\t\tcnt += 1\n\t\t\treturn now\n\ns = Solution()\nprint(s.climbStairs(4))","sub_path":"Python/070E_Climbing_Stairs.py","file_name":"070E_Climbing_Stairs.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"397361491","text":"from time import sleep\n\nfrom colorama import Fore\n\nfrom oeda.databases import db\nfrom oeda.log import *\nfrom oeda.rtxlib.changeproviders import init_change_provider\nfrom oeda.rtxlib.dataproviders import init_data_providers\nfrom oeda.rtxlib.preprocessors import init_pre_processors, kill_pre_processors\nfrom oeda.rtxlib.executionstrategy.FactorialExperimentStrategy import start_factorial_experiment\nfrom oeda.rtxlib.executionstrategy.TtestStrategy import start_ttest_analysis\nfrom oeda.analysis.analysis_execution import start_one_sample_tests\nfrom oeda.rtxlib.executionstrategy import run_execution_strategy\nfrom oeda.rtxlib.simulationchannels import init_channels, create_scenario_file, init_simulation, experiment_ACK, fetch_results, fetch_status\nfrom oeda.rtxlib.analysischannels import create_start_command, send_command_analysis, fetch_analysis_response, validate_ack_analysis, wait_ack_analysis\n\n\ndef execute_analysis(wf):\n # start the right execution strategy\n if wf.analysis[\"type\"] == \"factorial_experiment\":\n start_factorial_experiment(wf)\n if wf.analysis[\"type\"] == \"t_test\":\n start_ttest_analysis(wf)\n if wf.analysis[\"type\"] == \"one_sample_tests\":\n start_one_sample_tests(wf)\n\ndef execute_workflow(wf):\n \"\"\" this is the main workflow for executing a given workflow \"\"\"\n try:\n info(\"######################################\", Fore.CYAN)\n info(\"> Workflow | \" + str(wf.name), Fore.CYAN)\n debug(\"execution_strategy:\" + str(wf.execution_strategy))\n\n except KeyError as e:\n error(\"workflow is missing a value \" + str(e))\n exit(1)\n\n # initialize channels for simulation\n init_channels(wf)\n # for simulation - wf.secondary_data_providers.extend(orchestration_data_providers)\n # for analysis - wf.secondary_data_providers.extend(orchestration_data_providers_analysis)\n\n # initialize the experiment environment\n init_pre_processors(wf)\n # wf type independent - for each preprocessor - p[\"instance\"] = SparkPreProcessor(wf, p)\n\n init_change_provider(wf)\n # wf type independent - loads the specified change provider into the workflow\n\n init_data_providers(wf)\n # wf type independent - creates the required data providers\n\n if wf.is_type('simulation'):\n # generate sce-file\n sc, resources = create_scenario_file(wf, wf._oeda_target[\"simulationType\"])\n\n # initiate send it on orchestration\n init_simulation(wf, sc, resources)\n\n ack = experiment_ACK(wf, \"Scenario\")\n if (len(ack) == 0):\n debug(\"No acknowledgement received from simulator. Please check if it is running.\", Fore.RED)\n exit(1)\n\n if wf.is_type('analysis'):\n # initialize analysis channels\n # received an ack for the initialized simulation experiment from the simulation service\n # if combined simulation & analysis create the analysis experiment and channels\n print(\"Simulation && Analysis\")\n command = create_start_command(wf)\n send_command_analysis(wf, command)\n\n if wf.is_type('simulation'):\n # read out result channel, when generated and save it into db\n if wf._oeda_experiment[\"results_downloadable\"]:\n result_url = fetch_results(wf)\n wf.save_experiment_result_url(result_url)\n\n # execute chosen strategy and run analysis\n run_execution_strategy(wf)\n\n if wf.is_type('analysis'):\n # wait for response\n waiting = True\n wait_ack_analysis(wf)\n\n # fetch analysis result from output channel\n fetch_analysis_response(wf)\n\n wf.run_oeda_callback({\"status\": \"EXPERIMENT_DONE\"})\n\n # we are done, now we clean up\n kill_pre_processors(wf)\n info(\"> Finished workflow\")\n","sub_path":"Backend/oeda/rtxlib/workflow.py","file_name":"workflow.py","file_ext":"py","file_size_in_byte":3751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"575223833","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nimport os\nimport string\nimport codecs\nimport logging\nimport tempfile\nimport sys\nfrom collections import Counter, OrderedDict\nimport torch\nfrom .config import *\n\nsys.path.append(os.path.abspath(os.path.join(\n os.path.dirname(__file__), './subword-nmt')))\nimport learn_bpe\nimport apply_bpe\n\ntry:\n from sacremoses import MosesTokenizer, MosesDetokenizer\n _MOSES_AVAILABLE = True\nexcept ImportError:\n _MOSES_AVAILABLE = False\n\ntry:\n import sentencepiece as spm\n _SENTENCEPIECE_AVAILABLE = True\nexcept ImportError:\n _SENTENCEPIECE_AVAILABLE = False\n\n\nclass OrderedCounter(Counter, OrderedDict):\n pass\n\n\ndef _segment_words(line, pre_apply=None):\n if pre_apply is not None:\n line = pre_apply(line)\n line = str(line)\n return line.strip('\\r\\n ').split()\n\n\ndef _get_vocabulary(item_list, segment=_segment_words, from_filenames=True):\n vocab = OrderedCounter()\n if from_filenames:\n filenames = item_list\n # get combined vocabulary of all input files\n for fname in filenames:\n with codecs.open(fname, encoding='UTF-8') as f:\n for line in f:\n for word in segment(line):\n vocab[word] += 1\n else:\n for line in item_list:\n for word in segment(line):\n vocab[word] += 1\n return vocab\n\n\nclass Tokenizer(object):\n\n def __init__(self, vocab_file=None, additional_tokens=None, use_moses=None):\n self.special_tokens = [PAD_TOKEN, UNK_TOKEN, BOS_TOKEN, EOS_TOKEN]\n if use_moses is not None:\n self.enable_moses(lang=use_moses)\n if additional_tokens is not None:\n self.special_tokens += additional_tokens\n self.__word2idx = {}\n self.vocab_file = vocab_file\n if os.path.isfile(vocab_file):\n self.load_vocab(vocab_file)\n\n def enable_moses(self, lang='en', tokenize=True, detokenize=True):\n if tokenize:\n self._moses_tok = MosesTokenizer(lang=lang)\n else:\n self._moses_tok = None\n\n if detokenize:\n self._moses_detok = MosesDetokenizer(lang=lang)\n else:\n self._moses_detok = None\n\n @property\n def vocab_size(self):\n return len(self.vocab) + len(self.special_tokens)\n\n def pre_tokenize(self, line):\n if hasattr(self, '_moses_tok'):\n return self._moses_tok.tokenize(line, return_str=True)\n return line\n\n def post_detokenize(self, tokens):\n if hasattr(self, '_moses_detok'):\n return self._moses_detok.detokenize(tokens, return_str=False)\n return tokens\n\n def idx2word(self, idx):\n if idx < len(self.special_tokens):\n return self.special_tokens[idx]\n else:\n return self.vocab[idx - len(self.special_tokens)][0]\n\n def update_word2idx(self):\n self.__word2idx = {\n word[0]: idx + len(self.special_tokens) for idx, word in enumerate(self.vocab)}\n for i, tok in enumerate(self.special_tokens):\n self.__word2idx[tok] = i\n\n def word2idx(self, word):\n return self.__word2idx.get(word, UNK)\n\n def segment(self, line, sample=None):\n \"\"\"segments a line to tokenizable items\"\"\"\n line = self.pre_tokenize(line)\n return _segment_words(line)\n\n def get_vocab(self, item_list, from_filenames=True, limit=None):\n vocab = _get_vocabulary(item_list=item_list, segment=self.segment,\n from_filenames=from_filenames)\n self.vocab = vocab.most_common(limit)\n self.update_word2idx()\n\n def save_vocab(self, vocab_filename):\n if self.vocab is not None:\n with codecs.open(vocab_filename, 'w', encoding='UTF-8') as f:\n for (key, freq) in self.vocab:\n f.write(\"{0} {1}\\n\".format(key, freq))\n\n def load_vocab(self, vocab_filename, limit=None, min_count=1):\n vocab = OrderedCounter()\n with codecs.open(vocab_filename, encoding='UTF-8') as f:\n for line in f:\n try:\n word, count = line.strip().split()\n except: # no count\n word, count = line.strip(), 1\n count = int(count)\n if count >= min_count:\n vocab[word] = count\n self.vocab = vocab.most_common(limit)\n self.update_word2idx()\n\n def tokenize(self, line, insert_start=None, insert_end=None, sample=None):\n \"\"\"tokenize a line, insert_start and insert_end are lists of tokens\"\"\"\n inputs = self.segment(line)\n targets = []\n if insert_start is not None:\n targets += insert_start\n for w in inputs:\n targets.append(self.word2idx(w))\n if insert_end is not None:\n targets += insert_end\n return torch.LongTensor(targets)\n\n def detokenize(self, inputs, delimiter=u' '):\n token_list = [self.idx2word(int(idx)) for idx in inputs]\n token_list = self.post_detokenize(token_list)\n outputs = delimiter.join(token_list)\n return outputs\n\n\nclass BPETokenizer(Tokenizer):\n\n def __init__(self, codes_file, vocab_file, additional_tokens=None,\n num_symbols=10000, min_frequency=2, total_symbols=False, separator='@@',\n **kwargs):\n super(BPETokenizer, self).__init__(vocab_file=vocab_file,\n additional_tokens=additional_tokens,\n **kwargs)\n self.num_symbols = num_symbols\n self.min_frequency = min_frequency\n self.total_symbols = total_symbols\n self.separator = separator\n self.codes_file = codes_file\n if os.path.isfile(codes_file):\n self.set_bpe(codes_file)\n\n def set_bpe(self, codes_file):\n with codecs.open(self.codes_file, encoding='UTF-8') as codes:\n self.bpe = apply_bpe.BPE(codes, separator=self.separator)\n\n def segment(self, line):\n if not hasattr(self, 'bpe'):\n raise NameError('Learn bpe first!')\n line = self.pre_tokenize(line)\n return self.bpe.segment(line.strip('\\r\\n ')).split(' ')\n\n def learn_bpe(self, item_list, from_filenames=True):\n logging.info('generating bpe codes file. saving to %s' %\n self.codes_file)\n\n # get vocabulary at word level (before bpe)\n def segment_words(line): return _segment_words(line, self.pre_tokenize)\n vocab_words = _get_vocabulary(item_list,\n from_filenames=from_filenames,\n segment=segment_words)\n vocab_list = ['{0} {1}'.format(key, freq)\n for (key, freq) in vocab_words.items()]\n # learn BPE on combined vocabulary\n with codecs.open(self.codes_file, 'w', encoding='UTF-8') as output:\n learn_bpe.learn_bpe(vocab_list, output, num_symbols=self.num_symbols,\n min_frequency=self.min_frequency, verbose=False,\n is_dict=True, total_symbols=self.total_symbols)\n self.set_bpe(self.codes_file)\n\n def detokenize(self, inputs, delimiter=' '):\n self.separator = getattr(self, 'separator', '@@')\n detok_string = super(BPETokenizer, self).detokenize(inputs, delimiter)\n try:\n detok_string = detok_string.decode('utf-8')\n except:\n pass\n detok_string = detok_string\\\n .replace(self.separator + ' ', '')\\\n .replace(self.separator, '')\n return detok_string\n\n\nclass CharTokenizer(Tokenizer):\n\n def segment(self, line):\n line = self.pre_tokenize(line)\n return list(line.strip())\n\n def detokenize(self, inputs, delimiter=u''):\n return super(CharTokenizer, self).detokenize(inputs, delimiter)\n\n\nclass SentencePiece(Tokenizer):\n def __init__(self, model_prefix, additional_tokens=None,\n num_symbols=10000, model_type='unigram',\n character_coverage=None, split_by_whitespace=False):\n assert _SENTENCEPIECE_AVAILABLE\n self.model_prefix = os.path.abspath(model_prefix)\n self.num_symbols = num_symbols\n self.model_type = model_type\n self.character_coverage = character_coverage\n self.split_by_whitespace = split_by_whitespace\n self.vocab_file = '{}.vocab'.format(model_prefix)\n self.model_file = '{}.model'.format(model_prefix)\n self.model = None\n if additional_tokens is not None:\n self.special_tokens += additional_tokens\n if os.path.isfile(self.model_file):\n self.load_model(self.model_file)\n\n def serialize_model(self, model_file):\n with open(model_file, 'rb') as f:\n return f.read()\n\n def deserialize_model(self, model_serialized):\n fd, path = tempfile.mkstemp()\n try:\n with os.fdopen(fd, 'wb') as tmp:\n tmp.write(model_serialized)\n self.load_model(path)\n finally:\n os.remove(path)\n\n def load_model(self, model_file):\n self.model = spm.SentencePieceProcessor()\n self.model.Load(model_file)\n self._model_serialized = self.serialize_model(model_file)\n\n def learn_model(self, file_list, **kwargs):\n file_list = ','.join([os.path.abspath(filename)\n for filename in file_list])\n self.train_sp_model(input=file_list,\n model_prefix=self.model_prefix,\n vocab_size=self.num_symbols,\n character_coverage=self.character_coverage,\n model_type=self.model_type,\n split_by_whitespace=self.split_by_whitespace,\n **kwargs)\n self.load_model(self.model_file)\n\n def tokenize(self, line, insert_start=None, insert_end=None, sample=None):\n \"\"\"tokenize a line, insert_start and insert_end are lists of tokens\"\"\"\n if sample is None or sample is False:\n targets = self.model.EncodeAsIds(line)\n else:\n sample = sample if isinstance(sample, dict) else {}\n sample.setdefault('nbest_size', 64)\n sample.setdefault('alpha', 0.1)\n targets = self.model.SampleEncodeAsIds(line, **sample)\n if insert_start is not None:\n targets = insert_start + targets\n if insert_end is not None:\n targets += insert_end\n return torch.LongTensor(targets)\n\n def detokenize(self, inputs):\n outputs = self.model.DecodeIds([int(idx) for idx in inputs])\n return outputs\n\n def idx2word(self, idx):\n return self.model.IdToPiece(idx)\n\n def word2idx(self, word):\n return self.model.PieceToId(word)\n\n def segment(self, line, sample=None):\n \"\"\"segments a line to tokenizable items\"\"\"\n if sample is None or sample is False:\n return self.model.EncodeAsPieces(line)\n else:\n sample = sample if isinstance(sample, dict) else {}\n sample.setdefault('nbest_size', 64)\n sample.setdefault('alpha', 0.1)\n return self.model.SampleEncodeAsPieces(line, **sample)\n\n @property\n def vocab_size(self):\n return len(self.model)\n\n @staticmethod\n def train_sp_model(**kwargs):\n \"\"\"possible arguments:\n --input: one-sentence-per-line raw corpus file. You can pass a comma-separated list of files.\n --model_prefix: output model name prefix. .model and .vocab are generated.\n --vocab_size: vocabulary size, e.g., 8000, 16000, or 32000\n --character_coverage: amount of characters covered by the model\n --model_type: model type. Choose from unigram (default), bpe, char, or word. The input sentence must be pretokenized when using word type.\n \"\"\"\n kwargs.update({'unk_piece': UNK_TOKEN, 'bos_piece': BOS_TOKEN,\n 'eos_piece': EOS_TOKEN, 'pad_piece': PAD_TOKEN,\n 'unk_id': UNK, 'bos_id': BOS,\n 'eos_id': EOS, 'pad_id': PAD\n })\n for arg, val in kwargs.items():\n if isinstance(val, bool):\n kwargs[arg] = 'true' if val else 'false'\n config = ' '.join(['--{}={}'.format(name, value)\n for name, value in kwargs.items() if value is not None])\n spm.SentencePieceTrainer.Train(config)\n\n def __getstate__(self):\n state = self.__dict__.copy()\n del state['model']\n return state\n\n def __setstate__(self, newstate):\n self.deserialize_model(newstate['_model_serialized'])\n\n","sub_path":"pytorch tutorial/Source/additional/seq2seq+attention/eladhoffer/seq2seq/tools/tokenizer.py","file_name":"tokenizer.py","file_ext":"py","file_size_in_byte":12809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"126015774","text":"#!/usr/bin/env python\n#\n# Author: Daniela Duricekova \n#\n\nimport ctypes\nimport functools\nimport multiprocessing\nimport unittest\n\nfrom symmetric_matrix import SymmetricMatrix as SM\n\n\nclass SymmetricMatrixTests(unittest.TestCase):\n def test_len_returns_correct_value(self):\n m = SM(3)\n self.assertEqual(len(m), 3)\n\n def test_values_are_zero_after_creation(self):\n m = SM(3)\n for x in range(3):\n for y in range(3):\n self.assertEqual(m[x, y], 0)\n\n def test_value_can_be_read_after_write(self):\n m = SM(3)\n m[0, 0] = 5\n self.assertEqual(m[0, 0], 5)\n\n def test_write_above_diagonal_does_not_write_to_invalid_index(self):\n m = SM(3)\n m[1, 2] = 5\n self.assertEqual(m[2, 0], 0)\n\n def test_write_to_x_y_writes_also_to_y_x(self):\n m = SM(3)\n m[1, 2] = 5\n self.assertEqual(m[2, 1], 5)\n\n def test_access_out_of_range_raises_exception(self):\n m = SM(3)\n with self.assertRaises(IndexError):\n m[3, 0] = 5\n\n def test_non_positive_size_raises_exception(self):\n with self.assertRaises(ValueError):\n SM(0)\n\n def test_can_pass_custom_create_storage(self):\n create_storage = functools.partial(\n multiprocessing.RawArray,\n ctypes.c_int\n )\n m = SM(3, create_storage)\n m[1, 2] = 5\n self.assertEqual(m[2, 1], 5)\n","sub_path":"2016-09-18-speeding-up-symmetric-matrix-with-cython/symmetric_matrix_tests.py","file_name":"symmetric_matrix_tests.py","file_ext":"py","file_size_in_byte":1458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"72219541","text":"#!/usr/bin/python3\n\n# Local Modules\nfrom src.bidict import BiDict\nfrom src.capture_database import CaptureDatabase\n#from capture_database import DatabaseHandler\nfrom src.capture_database import CaptureDigest\nfrom src.lookup import lookup_mac, lookup_hostname\nfrom src.generate_mudfile import MUDgeeWrapper\nfrom src.generate_report import ReportGenerator\nfrom src.multicolumn_listbox import MultiColumnListbox\n\n# External Modules\nimport concurrent\nfrom datetime import datetime\nfrom datetime import timedelta\nimport hashlib\nimport math\nimport multiprocessing\n#from multiprocessing import Process, Queue\nimport mysql.connector\nimport pyshark\nimport subprocess\nimport sys\nimport time\nimport tkinter as tk\nfrom tkinter import ttk\nfrom tkinter import messagebox\nfrom tkinter.filedialog import askopenfilename\n\nfield2db = BiDict({'File':'fileName', 'Activity':'activity', 'Notes (optional)':'details',\n 'Lifecycle Phase':'lifecyclePhase','Setup':'setup', 'Normal Operation':'normalOperation', 'Removal':'removal',\n 'Internet':'internet', 'Human Interaction':'humanInteraction', 'Preferred DNS Enabled':'preferredDNS','Isolated':'isolated',\n 'Duration-based':'durationBased', 'Duration':'duration', 'Action-based':'actionBased', 'Action':'deviceAction',\n 'Date of Capture':'capDate', 'Time of Capture':'capTime',\n 'Manufacturer':'mfr' , 'MAC':'mac_addr', 'Model':'model', 'Internal Name':'internalName',\n 'Category':'deviceCategory', 'Notes':'notes',\n #'MUD':'mudCapable', 'WiFi':'wifi', 'Bluetooth':'bluetooth', 'Zigbee':'zigbee',\n 'MUD':'mudCapable', 'WiFi':'wifi', 'Ethernet':'ethernet', 'Bluetooth':'bluetooth', 'Zigbee':'zigbee',\n 'ZWave':'zwave', '3G':'G3', '4G':'G4', '5G':'G5', 'Other':'otherProtocols',\n 'Firmware Version': 'fw_ver', 'IP Address' : 'ipv4_addr', 'IPv6 Address' : 'ipv6_addr'})\ndbFields = 'host', 'database', 'user', 'passwd'\ndbNewFields = 'host', 'user', 'passwd', 'new database'\n#dbField2Var = {'Host' : 'host', 'Database' : 'database', 'Username' : 'user', 'Password' : 'passwd'}\n#captureFields = 'File', 'Activity', 'Notes (optional)'\ncaptureFields = 'File', 'Notes (optional)'\nlifecyclePhaseFields = 'Setup', 'Normal Operation', 'Removal'\ncaptureEnvFields = 'Internet', 'Human Interaction', 'Preferred DNS Enabled','Isolated'\ncaptureTypeFields = 'Duration-based', 'Duration', 'Action-based', 'Action'\n#captureField2Var = {'File' : 'fileLoc', 'Activity' : 'activity', 'Details' : 'details'}\ncaptureInfoFields = 'Date of Capture', 'Time of Capture'#, 'Devices'\n#deviceFields = 'Model', 'Internal Name', 'Device Category', 'Communication Standards', 'Notes'\ndeviceFields = 'Manufacturer', 'Model', 'MAC', 'Internal Name', 'Category', 'Notes', 'Capabilities'\n#deviceField2Var = {'Model' : 'model', 'Internal Name' : 'internalName', 'Device Category' : 'deviceCategory', 'Communication Standards', 'Notes': 'notes'}\n#deviceOptions = 'WiFi', 'Bluetooth', 'Zigbee', 'ZWave', '4G', '5G', 'Other'\ndeviceOptions = 'MUD', 'WiFi', 'Ethernet', 'Bluetooth', 'Zigbee', 'ZWave', '3G', '4G', '5G', 'Other'\n#deviceOptions2Var = {'WiFi' : 'wifi', 'Bluetooth' : 'bluetooth', 'Zigbee' : 'zigbee', 'ZWave' : 'zwave', '4G' : '4G', '5G' : '5G', 'Other', 'other'}\n#deviceStateFields = 'Firmware Version' #maybe include this with device fields entry and note that it will be associated with the capture only\n\n#fields = 'Last Name', 'First Name', 'Job', 'Country'\n\n\n\n'''\nclass popupWindow(object):\n def __init__(self, master):\n top=self.top = tk.Toplevel(master)\n self.l = tk.Label(top,text=\"Hello World\")\n self.l.pack()\n self.e = tk.Entry(top)\n self.e.pack()\n self.b = tk.Button(top, text='Ok', command=self.cleanup)\n def cleanup(self):\n self.value=self.e.get()\n self.top.destroy()\n'''\n\n'''\n +--------+--------+\n | | |\n | menu bar frame |\n | | |\n +--------+--------+\n | capture| device |\n | list | list |\n | | | |\n +-- | ---+--------+\n | V | comm |\n | | detail |\n | | |\n +--------+--------+\n | | |\n | status bar frame|\n | | |\n +--------+--------+\n\n +----------------------------------------------------------------------+\n | Menu bar (menuFrame) |\n +-------------------+--------------------------------------------------+\n | Capture List (capFrame) | Device List (devFrame) |\n +-------------------------+--------------------------------------------+\n | | |\n | | |\n | | |\n | | |\n | | |\n | | |\n | | |\n | | |\n | | |\n | | |\n | +--------------------------------------------+\n | | Communications Details (commFrame) |\n | +--------------------------------------------+\n | | |\n | | |\n | | |\n | | |\n | | |\n | | |\n | | |\n | | |\n +-------------------------+--------------------------------------------+\n | Status bar |\n +----------------------------------------------------------------------+\n\n'''\n\n#GUI Class for the MUD Capture Analysis\nclass MudCaptureApplication(tk.Frame):\n\n\n def __init__(self, parent, *args, **kwargs):\n tk.Frame.__init__(self, parent, *args, **kwargs)\n self.parent = parent\n self.parent.title(\"MUD-PD: MUD Profiling Database\") #MUDdy Airwaves\n\n self.window_stack = []\n self.yield_focus(self.parent)\n\n # Main menu bar\n self.fileMenu = tk.Menu(self.parent)\n self.parent.config(menu=self.fileMenu)\n self.fileSubMenu = tk.Menu(self.fileMenu)\n self.fileMenu.add_cascade(label=\"File\", menu=self.fileSubMenu)\n self.fileSubMenu.add_command(label=\"Connect to Database...\", command=self.popup_connect2database)\n self.fileSubMenu.add_command(label=\"Create New Database...\", command=self.popup_createNewDatabase)\n self.fileSubMenu.add_command(label=\"Import Capture File...\", command=self.popup_import_capture)\n self.fileSubMenu.add_separator()\n self.fileSubMenu.add_command(label=\"Quit\", command=self.__exit__)\n \n self.helpSubMenu = tk.Menu(self.fileMenu)\n self.fileMenu.add_cascade(label=\"Help\", menu=self.helpSubMenu)\n self.helpSubMenu.add_command(label=\"About\", command=self.popup_about)\n\n\n #### Main Window ####\n # Menu top\n self.menuFrame = tk.Frame(self.parent, bd=1, bg=\"#dfdfdf\") #, bg=\"#dfdfdf\"\n\n icon_db_connect = tk.PhotoImage(file=\"data/icons/database_connect40px.png\")\n self.b_main_db_connect = tk.Button(self.menuFrame, compound=\"top\", image=icon_db_connect, width=\"40\", height=\"40\", command=self.popup_connect2database, highlightthickness=0, activebackground=\"black\", bd=0)\n self.b_main_db_connect.image = icon_db_connect\n self.b_main_db_connect.pack(side=\"left\")\n\n icon_db_new = tk.PhotoImage(file=\"data/icons/database_new40px.png\")\n self.b_main_db_new = tk.Button(self.menuFrame, compound=\"top\", image=icon_db_new, width=\"40\", height=\"40\", command=self.popup_createNewDatabase, highlightthickness=0, activebackground=\"black\", bd=0)\n self.b_main_db_new.image = icon_db_new\n self.b_main_db_new.pack(side=\"left\")\n\n icon_import = tk.PhotoImage(file=\"data/icons/import40px.png\")\n #self.b_main_import = tk.Button(self.menuFrame, compound=\"top\", image=icon_import, width=\"40\", height=\"40\", command=self.popup_import_capture, highlightthickness=0, activebackground=\"black\", bd=0)\n self.b_main_import = tk.Button(self.menuFrame, compound=\"top\", state='disabled', image=icon_import, width=\"40\", height=\"40\", command=self.popup_import_capture, highlightthickness=0, activebackground=\"black\", bd=0)\n self.b_main_import.image = icon_import\n self.b_main_import.pack(side=\"left\")\n\n #b_y = tk.Button(self.menuFrame, state=\"disabled\", text=\"Generate MUD File\", highlightbackground=\"#dfdfdf\", wraplength=80)#, anchor=tk.N+tk.W)\n #b_generate_MUD = tk.Button(self.menuFrame, text=\"Generate MUD File\", wraplength=80, command=self.generate_MUD_wizard)#, anchor=tk.N+tk.W)\n #self.b_main_generate_MUD = tk.Button(self.menuFrame, text=\"Generate MUD File\", wraplength=80, command=self.popup_generate_mud_wizard)#, anchor=tk.N+tk.W)\n self.b_main_generate_MUD = tk.Button(self.menuFrame, text=\"Generate MUD File\", state='disabled', wraplength=80, command=self.popup_generate_mud_wizard)#, anchor=tk.N+tk.W)\n #b_generate_MUD = tk.Button(self.menuFrame, state=\"disabled\", text=\"Generate MUD File\", wraplength=80, command=self.generate_MUD_wizard)#, anchor=tk.N+tk.W)\n self.b_main_generate_MUD.pack(side=\"left\")\n\n self.b_main_generate_report = tk.Button(self.menuFrame, state=\"disabled\", text=\"Generate Report\", wraplength=80, command=self.generate_report_wizard)#, anchor=tk.N+tk.W)\n self.b_main_generate_report.pack(side=\"left\")\n\n ### Left (capture) frame ###\n self.capFrame = tk.Frame(self.parent, width=300, bd=1, bg=\"#eeeeee\")#, bg=\"#dfdfdf\")\n\n # title\n self.cap_title_var=tk.StringVar()\n self.cap_title_var.set(\"Captures\")\n self.cap_title = tk.Label(self.capFrame, textvariable=self.cap_title_var, bg=\"#eeeeee\", bd=1, relief=\"flat\")\n self.cap_title.pack(side=\"top\", fill=tk.X)\n\n # capture list\n self.cap_header = [\"Date\", \"Capture Name\", \"Activity\", \"Duration\", \"Details\", \"Capture File Location\"]\n #self.cap_header = [\"Date\",\"Capture Name\",\"Activity\", \"Details\",\"Capture File Location\"]\n self.cap_list = MultiColumnListbox(self.capFrame, self.cap_header, list(), keep1st=True)\n #self.cap_list.bind(\"<>\", self.update_dev_list)\n self.cap_list.bind(\"<>\", self.update_dev_list)\n '''\n self.cap_list.bind(\">\", (lambda idx=0, hd0=4, hd1=1\n : self.popup_import_capture_devices(\n CaptureDigest(self.cap_list.get(self.cap_list.selection()[idx])[hd0] + \"/\" + \n self.cap_list.get(self.cap_list.selection()[idx])[hd1]))))\n '''\n\n #(lambda d=unknown_dev_list.curselection(): self.popup_import_device(d)))\n self.b_main_inspect = tk.Button(self.capFrame, text=\"Inspect\",\n #command=(lambda c=CaptureDigest((lambda x=None, idx=0, hd0=4, hd1=1\n # : self.cap_list.selection(x)[idx].get(self.cap_header[hd0]) +\n # self.cap_list.selection(x)[idx].get(self.cap_header[hd1])))\n # : self.popup_import_capture_devices(c)))\n command=self.pre_popup_import_capture_devices)\n '''\n command=(lambda hd0=4, hd1=1 :\n self.popup_import_capture_devices(\n CaptureDigest(\n self.cap_list.get_selected_row()[hd0] + \"/\" +\n self.cap_list.get_selected_row()[hd1]))))\n '''\n self.b_main_inspect.pack(side=\"right\")\n self.b_main_inspect.config(state=\"disabled\")\n self.cap = None\n\n\n ### Right Frame ###\n self.rightFrame = tk.Frame(self.parent, width=500, bd=1, bg=\"#dfdfdf\")\n\n ## Top Right (device) frame ##\n self.devFrame = tk.Frame(self.rightFrame, width=500)#, bd=1, bg=\"#eeeeee\")\n\n # title\n self.dev_title_var=tk.StringVar()\n self.dev_title_var.set(\"Devices\")\n self.dev_title = tk.Label(self.devFrame, textvariable=self.dev_title_var, bg=\"#eeeeee\", bd=1, relief=\"flat\")\n self.dev_title.pack(fill=tk.X)\n\n\n # device list\n self.dev_header = [\"Manufacturer\", \"Model\", \"Internal Name\", \"MAC\", \"Category\"]\n self.dev_list = MultiColumnListbox(self.devFrame, self.dev_header, list(), keep1st=True)\n #self.dev_list.bind(\"<>\", self.update_comm_list)\n self.dev_list.bind(\"<>\", self.update_comm_list)\n\n self.devFrame.pack(side=\"top\", fill=\"both\", expand=True)\n\n\n ## Bottom Right (communication) frame ##\n self.commFrame = tk.Frame(self.rightFrame, width=500, bd=1, bg=\"#eeeeee\")\n\n # title\n self.comm_title_var=tk.StringVar()\n self.comm_title_var.set(\"Communication\")\n self.comm_title = tk.Label(self.commFrame, textvariable=self.comm_title_var, bg=\"#eeeeee\", bd=1, relief=\"flat\")\n self.comm_title.pack(fill=tk.X)\n\n # scrollbar\n '''\n self.comm_scrollbar = tk.Scrollbar(self.commFrame)\n self.comm_scrollbar.pack(side=\"right\", fill=\"both\")\n '''\n\n # communication list\n self.comm_header = [\"Time\", \"MAC\", \"IPver\", \"Source\", \"Destination\", \"E/W\",\n \"Protocol\", \"Transport Protocol\", \"Source Port\",\n #\"Destination Port\", \"Length\", \"Direction\", \"Raw\"] #Direction being NS or EW\n #\"Destination Port\", \"Length\", \"Raw\"] #Direction being NS or EW\n \"Destination Port\", \"Length\"] #Direction being NS or EW\n self.comm_list = MultiColumnListbox(self.commFrame, self.comm_header, list())#, keep1st=True)\n #self.comm_list.bind(\"<>\", self.update_comm_list)\n\n '''\n self.comm_list = tk.Listbox(self.commFrame, yscrollcommand = self.comm_scrollbar.set, selectmode=\"extended\", exportselection=0, bd=0)\n\n self.comm_list.pack(side=\"left\", fill=\"both\", expand=True)\n self.comm_scrollbar.config( command = self.comm_list.yview )\n '''\n\n #:LKJ To be added once packets have been added to the table\n self.comm_state = \"any\"\n self.b_ns = tk.Button(self.commFrame, text=\"N/S\", command=(lambda s=\"ns\" : self.modify_comm_state(s)))\n self.b_ew = tk.Button(self.commFrame, text=\"E/W\", command=(lambda s=\"ew\" : self.modify_comm_state(s)))\n\n self.comm_dev_restriction = \"none\"\n self.b_between = tk.Button(self.commFrame, text=\"Between\", command=(lambda r=\"between\" : self.modify_comm_dev_restriction(r)))\n self.b_either = tk.Button(self.commFrame, text=\"Either\", command=(lambda r=\"either\" : self.modify_comm_dev_restriction(r)))\n\n self.b_pkt10 = tk.Button(self.commFrame, text=\"10\", command=(lambda n=10 : self.modify_comm_num_pkts(n)))\n self.b_pkt100 = tk.Button(self.commFrame, text=\"100\", command=(lambda n=100 : self.modify_comm_num_pkts(n)))\n self.b_pkt1000 = tk.Button(self.commFrame, text=\"1000\", command=(lambda n=1000 : self.modify_comm_num_pkts(n)))\n self.b_pkt10000 = tk.Button(self.commFrame, text=\"10000\", command=(lambda n=10000 : self.modify_comm_num_pkts(n)))\n #self.b_internal = tk.Button(self.commFrame, text=\"Subnets\", command=self.popup_internal_addr_list)\n\n self.b_ns.pack(side=\"left\")\n self.b_ew.pack(side=\"left\")\n self.b_between.pack(side=\"left\")\n self.b_either.pack(side=\"left\")\n\n self.b_pkt10000.pack(side=\"right\")\n self.b_pkt1000.pack(side=\"right\")\n self.b_pkt100.pack(side=\"right\")\n self.b_pkt10.pack(side=\"right\")\n\n self.comm_list_num_pkts = 100\n #self.b_pkt100.config(state='disabled')\n\n\n self.b_ns.config(state='disabled')\n self.b_ew.config(state='disabled')\n self.b_between.config(state='disabled')\n self.b_either.config(state='disabled')\n self.b_pkt10.config(state='disabled')\n self.b_pkt100.config(state='disabled')\n self.b_pkt1000.config(state='disabled')\n self.b_pkt10000.config(state='disabled')\n\n\n self.comm_list_all_pkts = []\n\n #self.b_internal.pack(side=\"right\")\n\n self.commFrame.pack(side=\"top\", fill=\"both\", expand=True)\n\n\n ### Status Bar ###\n self.statusFrame = tk.Frame(self.parent)\n self.status_var = tk.StringVar()\n self.status_var.set(\"No database connected...\")\n self.status = tk.Label(self.statusFrame, textvariable=self.status_var, bd=1, bg=\"#eeeeee\", relief=tk.SUNKEN, anchor=tk.W, padx=5)\n self.status.pack(fill=\"both\", expand=True)\n\n\n ### Grid Placement ###\n self.menuFrame.grid(row=0, column=0, columnspan=2, sticky=\"ew\")\n self.capFrame.grid(row=1, column=0, rowspan=2, sticky=\"nsew\")\n self.rightFrame.grid(row=1, column=1, rowspan=2, sticky=\"nsew\")\n self.statusFrame.grid(row=3, column=0, columnspan=2, sticky=\"ew\")\n\n # Grid configuration #\n self.parent.grid_rowconfigure(1, weight=1)\n self.parent.grid_columnconfigure(0, weight=1)\n self.parent.grid_columnconfigure(1, weight=3)\n\n\n def yield_focus(self, window = None):\n if len(self.window_stack) == 0:\n if window == None:\n print(\"Error with yielding focus\")\n else:\n self.window_stack.append(window)\n self.yield_focus()\n elif window == None:\n self.window_stack[-1].focus_set()\n self.window_stack[-1].grab_set()\n if self.window_stack[-1] != self.parent:\n self.window_stack[-1].transient(self.parent)\n self.window_stack[-1].lift()\n self.window_stack[-1].attributes('-topmost',True)\n self.window_stack[-1].attributes('-topmost',False)\n elif self.window_stack[-1] != window:\n # Previously top window yield status\n self.window_stack[-1].attributes('-topmost',False)\n #self.window_stack[-1].focus_release()\n self.window_stack[-1].grab_release()\n\n # Push new window to the top of the stack\n self.window_stack.append(window)\n self.yield_focus()\n\n # Wait for window to close before yielding focus to next in stack\n self.window_stack[-2].wait_window(self.window_stack[-1])\n #self.window_stack[-1].focus_release()\n self.window_stack[-1].grab_release()\n self.window_stack.pop()\n self.yield_focus()\n #else:\n # Remove the current top window from the stack and destroy\n '''\n self.window_stack[-1].attributes('-topmost',False)\n w = self.window_stack.pop()\n w.destroy()\n self.yield_focus()\n '''\n # self.window_stack[-1].destroy()\n\n\n\n def popup_connect2database(self):\n self.w_db = tk.Toplevel()\n self.w_db.wm_title(\"Connect to Database\")\n\n ents = self.make_form_database(dbFields)\n\n self.bind('', (lambda event, e=ents: self.connect_and_close(e))) \n\n b_connect = tk.Button(self.w_db, text='Connect',\n command=(lambda e=ents: self.connect_and_close(e)))\n b_cancel = tk.Button(self.w_db, text='Cancel', command=self.w_db.destroy)\n\n if sys.platform == \"win32\":\n b_cancel.pack(side=tk.RIGHT, padx=5, pady=5)\n b_connect.pack(side=tk.RIGHT, padx=5, pady=5)\n else:\n b_connect.pack(side=tk.RIGHT, padx=5, pady=5)\n b_cancel.pack(side=tk.RIGHT, padx=5, pady=5)\n\n # Save checkbutton\n checkvar = tk.IntVar()\n ckb_save = tk.Checkbutton(self.w_db, text=\"Save\", width=7, justify=tk.LEFT, variable=checkvar)\n ckb_save.pack(side=tk.LEFT, anchor=tk.W, padx=5)\n ents.append((\"Save\", checkvar))\n\n self.yield_focus(self.w_db)\n\n\n def make_form_database(self, fields):\n db_handler_temp = DatabaseHandler()\n entries = []\n\n for field in fields:\n row = tk.Frame(self.w_db)\n lab = tk.Label(row, width=12, text=field, anchor='w')\n if field == \"passwd\":\n ent = tk.Entry(row, show=\"\\u2022\", width=15)\n else:\n ent = tk.Entry(row)\n ent.insert( 10, db_handler_temp.config.get(field,\"none\") )\n\n row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=2)\n lab.pack(side=tk.LEFT)\n ent.pack(side=tk.RIGHT, expand=tk.YES, fill=tk.X)\n entries.append((field, ent))\n\n return entries\n\n def popup_createNewDatabase(self):\n self.w_db_new = tk.Toplevel()\n self.w_db_new.wm_title(\"Create New Database\")\n\n ents = self.make_form_new_database(dbNewFields)\n\n self.bind('', (lambda event, e=ents, c=True: self.connect_and_close(e, create=c))) \n\n b_create = tk.Button(self.w_db_new, text='Create',\n command=(lambda e=ents, c=True: self.connect_and_close(e, create=c)))\n b_cancel = tk.Button(self.w_db_new, text='Cancel', command=self.w_db_new.destroy)\n\n if sys.platform == \"win32\":\n b_cancel.pack(side=tk.RIGHT, padx=5, pady=5)\n b_create.pack(side=tk.RIGHT, padx=5, pady=5)\n else:\n b_create.pack(side=tk.RIGHT, padx=5, pady=5)\n b_cancel.pack(side=tk.RIGHT, padx=5, pady=5)\n\n # Save checkbutton\n checkvar = tk.IntVar()\n ckb_save = tk.Checkbutton(self.w_db_new, text=\"Save\", width=7, justify=tk.LEFT, variable=checkvar)\n ckb_save.pack(side=tk.LEFT, anchor=tk.W, padx=5)\n ents.append((\"Save\", checkvar))\n\n messagebox.showinfo(\"CREATING a New Database\",\n \"You are CREATING a new database.\\n\\nYou will need to use the existing mysql server password.\")\n\n self.yield_focus(self.w_db_new)\n\n\n def make_form_new_database(self, fields):\n db_handler_temp = DatabaseHandler()\n entries = []\n\n for field in fields:\n row = tk.Frame(self.w_db_new)\n lab = tk.Label(row, width=12, text=field, anchor='w')\n if field == \"passwd\":\n ent = tk.Entry(row, show=\"\\u2022\", width=15)\n skip_line = True\n else:\n ent = tk.Entry(row)\n skip_line = False\n ent.insert( 10, db_handler_temp.config.get(field,\"none\") )\n\n row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=2)\n lab.pack(side=tk.LEFT)\n ent.pack(side=tk.RIGHT, expand=tk.YES, fill=tk.X)\n entries.append((field, ent))\n\n if skip_line:\n xtra_row = tk.Frame(self.w_db_new)\n xtra_lab = tk.Label(xtra_row, width=12, text=' ', anchor='w')\n xtra_row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=2)\n xtra_lab.pack(side=tk.LEFT)\n skip_line = False\n\n return entries\n\n def connect_and_close(self, entries, create=False):\n db_handler_temp = DatabaseHandler()\n (save_name, save_var) = entries.pop()\n save_val = save_var.get()\n #print(save_name, \" = \", save_var, \" = \", save_val)\n\n if create:\n (db_label, db_name) = entries.pop()\n db_name = db_name.get()\n db_handler_temp.db_connect(entries)\n\n if not db_handler_temp.connected:\n tk.messagebox.showerror(\"Error Connecting to Database\",\n \"There was some error while connecting to the database.\\n\" +\n \"Please check all the data fields and try again.\")\n return\n \n try:\n db_handler_temp.db.init_new_database(db_name)\n except mysql.connector.Error as err:\n if err.errno == mysql.connector.errorcode.ER_DB_CREATE_EXISTS: # 1007\n print(\"Database already exists\")\n\n reinit = tk.messagebox.askyesno(\"Database Creation Error\",\n \"Cannot create database '%s' because it already exists.\\n\\n\" % db_name +\n \"Re-initialize the existing database?\",\n default='no')\n \n if reinit:\n confirm = tk.messagebox.askyesno(\"Overwrite Existing Database\",\n \"Are you sure you want to overwrite the database '%s'?\\n\\n\" % db_name +\n \"This action is IRREVERSIBLE and all existing data will be LOST!\",\n default='no')\n if confirm:\n db_handler_temp.db.reinit_database(db_name);\n else:\n tk.messagebox.showinfo(\"Create New Database Name\",\n \"Please choose a new database name\")\n return\n else:\n tk.messagebox.showinfo(\"Create New Database Name\",\n \"Please choose a new database name\")\n return\n else:\n tk.messagebox.showerror(\"Error Creating Database\",\n \"There was some error in creating the database.\\n\" +\n \"Please try again using a different name\")\n return\n\n db_handler_temp.db_config['database'] = db_name\n #entries.append(('database', db_name))\n else:\n db_handler_temp.db_connect(entries)\n #db_handler_temp.db_connect(entries)\n\n if db_handler_temp.connected:\n self.db_handler = db_handler_temp\n self.status_var.set(\"Connected to \" + self.db_handler.config.get(\"database\", \"none\"))\n self.populate_capture_list()\n if save_val:\n self.popup_confirm_save()\n\n if create:\n #messagebox.showinfo(\"Success!\",\"Successfully created and connected to the new database '%s'\" % db_name)\n self.w_db_new.destroy()\n else:\n #messagebox.showinfo(\"Success!\",\"Successfully connected to the database\")\n self.w_db.destroy()\n\n\n #Enable main menu buttons\n self.b_main_import.config(state='normal')\n self.b_main_generate_MUD.config(state='normal')\n self.b_main_generate_report.config(state='normal')\n self.b_main_inspect.config(state=\"disabled\")\n self.b_ns.config(state='normal')\n self.b_ew.config(state='normal')\n self.b_between.config(state='normal')\n self.b_either.config(state='normal')\n self.b_pkt10.config(state='normal')\n self.b_pkt100.config(state='disabled')\n self.b_pkt1000.config(state='normal')\n self.b_pkt10000.config(state='normal')\n\n\n\n else:\n tk.messagebox.showerror(\"Error\", \"Problem connecting to database\")\n entries.append((save_name, save_var))\n '''\n tk.Tk().withdraw()\n messagebox.showerror(\"Error\", \"Problem connecting to database\")\n '''\n\n def popup_confirm_save(self):\n confirm = tk.messagebox.askyesno(\"MUD-PD: MUD Profiling Database\",\n \"Are you sure you want to save this configuration?\\n\\n\" +\n \"Any existing configuration will be OVERWRITTEN.\",\n default='no')\n save_pwd = tk.messagebox.askyesno(\"WARNING\",\n \"Password will be saved in plaintext.\\n\\nSave password anyway?\",\n default='no')\n #print(confirm)\n if confirm:\n self.db_handler.save_db_config(save_pwd=save_pwd)\n return\n\n def popup_import_capture(self):\n self.w_cap = tk.Toplevel()\n self.w_cap.wm_title(\"Import Packet Capture\")\n\n\n #self.ents = self.make_form_capture(captureFields)\n self.ents = self.make_form_capture(captureFields, lifecyclePhaseFields, captureEnvFields, captureTypeFields)\n\n self.bind('', (lambda event, e=self.ents: self.import_and_close(e)))\n\n self.b_import = tk.Button(self.w_cap, text='Import',\n command=(lambda e=self.ents: self.import_and_close(e)))\n\n self.b_cancel = tk.Button(self.w_cap, text='Cancel', command=self.w_cap.destroy)\n\n if sys.platform == \"win32\":\n self.b_cancel.pack(side=tk.RIGHT, padx=5, pady=5)\n self.b_import.pack(side=tk.RIGHT, padx=5, pady=5)\n else:\n self.b_import.pack(side=tk.RIGHT, padx=5, pady=5)\n self.b_cancel.pack(side=tk.RIGHT, padx=5, pady=5)\n\n self.yield_focus(self.w_cap)\n\n\n def openFileCallBack(self, entry):\n tk.Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing\n\n #filename = tk.filedialog.askopenfilename() # show an \"Open\" dialog box and return the path to the selected file\n filename = askopenfilename() # show an \"Open\" dialog box and return the path to the selected file\n entry.delete(0, tk.END)\n entry.insert(0, filename)\n\n\n '''\n def make_form_capture(self, fields):\n entries = []\n #entries = {}\n for i, field in enumerate(fields):\n row = tk.Frame(self.w_cap)\n lab = tk.Label(row, width=15, text=field, anchor='w')\n ent = tk.Entry(row)\n\n if i == 0:\n b_open = tk.Button(row, text='...', command=(lambda e=ent: self.openFileCallBack(e)))#openFileCallBack())\n row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)\n lab.pack(side=tk.LEFT)\n ent.pack(side=tk.LEFT, fill=tk.X)\n b_open.pack(side=tk.LEFT, expand=tk.YES, fill=tk.X)\n else:\n row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)\n lab.pack(side=tk.LEFT)\n ent.pack(side=tk.RIGHT, expand=tk.YES, fill=tk.X)\n\n entries.append((field, ent))\n #entries[field] = ent\n\n return entries\n '''\n\n def make_form_capture(self, generalFields, phaseFields, envFields, typeFields):\n entries = []\n #entries = {}\n for i, field in enumerate(generalFields):\n row = tk.Frame(self.w_cap)\n lab = tk.Label(row, width=15, text=field, anchor='w')\n ent = tk.Entry(row)\n\n if i == 0:\n b_open = tk.Button(row, text='...', command=(lambda e=ent: self.openFileCallBack(e)))#openFileCallBack())\n row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)\n lab.pack(side=tk.LEFT)\n ent.pack(side=tk.LEFT, fill=tk.X)\n b_open.pack(side=tk.LEFT, expand=tk.YES, fill=tk.X)\n else:\n row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)\n lab.pack(side=tk.LEFT)\n ent.pack(side=tk.RIGHT, expand=tk.YES, fill=tk.X)\n\n entries.append((field, ent))\n #entries[field] = ent\n\n # Device Phase (Setup, Normal Operation, Removal)\n # lifecyclePhaseFields = 'Setup', 'Normal Operation', 'Removal'\n row = tk.Frame(self.w_cap)\n lab = tk.Label(row, width=15, text=\"Lifecycle Phase\", anchor='w')\n row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)\n lab.pack(side=tk.LEFT)\n\n row = tk.Frame(self.w_cap)\n row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)\n v_phz = tk.IntVar(None,1)\n for i, field in enumerate(phaseFields):\n b_phz = tk.Radiobutton(row, text=field, variable=v_phz, value=i)\n b_phz.pack(side=tk.LEFT, fill=tk.X, padx=5, pady=5, anchor=tk.W)\n\n entries.append((lab, v_phz))\n\n\n # Environment Variables (Internet, Human Interaction, Preferred DNS Enabled, Isolated\n # captureEnvFields = 'Internet', 'Human Interaction', 'Preferred DNS Enabled','Isolated'\n row = tk.Frame(self.w_cap)\n lab = tk.Label(row, width=20, text=\"Environmental Variables\", anchor='w')\n row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)\n lab.pack(side=tk.LEFT)\n for i, field in enumerate(envFields):\n if i % 2 == 0:\n row = tk.Frame(self.w_cap)\n row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)\n v_env = tk.IntVar(None, 1)\n else:\n v_env = tk.IntVar()\n\n #v_env = tk.IntVar()\n b_env = tk.Checkbutton(row, text=field, variable=v_env)\n b_env.pack(side=tk.LEFT, padx=20, anchor=tk.W)\n\n entries.append((field, v_env))\n #entries.append((b_env, v_env))\n\n\n # Capture Type (Duration-based, Duration, Action-based, Action)\n # captureTypeFields = 'Duration-based', 'Duration', 'Action-based', 'Action'\n row = tk.Frame(self.w_cap)\n lab = tk.Label(row, width=15, text=\"Capture Type\", anchor='w')\n row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)\n lab.pack(side=tk.LEFT)\n\n\n def activateCheckDur():\n if v_dur.get() == 1: #whenever checked\n e_dur.config(state='normal')\n elif v_dur.get() == 0: #whenever unchecked\n e_dur.config(state='disabled')\n\n i = 0\n # Duration-based\n row = tk.Frame(self.w_cap)\n row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)\n v_dur = tk.IntVar()\n b_dur = tk.Checkbutton(row, text=typeFields[i], variable=v_dur, command=activateCheckDur)\n b_dur.pack(side=tk.LEFT, fill=tk.X, padx=5, pady=5, anchor=tk.W)\n entries.append((typeFields[i], v_dur))\n \n # Duration\n i += 1\n row = tk.Frame(self.w_cap)\n row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)\n lab = tk.Label(row, padx=5, width=9, text=typeFields[i], anchor='w')\n lab.pack(side=tk.LEFT)\n e_dur = tk.Entry(row)\n e_dur.pack(side=tk.LEFT, expand=tk.YES, fill=tk.X)\n e_dur.config(state='disabled')\n entries.append((typeFields[i], e_dur))\n\n\n def activateCheckAct():\n if v_act.get() == 1: #whenever checked\n e_act.config(state='normal')\n elif v_act.get() == 0: #whenever unchecked\n e_act.config(state='disabled')\n\n # Action-based\n i += 1\n row = tk.Frame(self.w_cap)\n row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)\n v_act = tk.IntVar()\n b_act = tk.Checkbutton(row, text=typeFields[i], variable=v_act, command=activateCheckAct)\n b_act.pack(side=tk.LEFT, fill=tk.X, padx=5, pady=5, anchor=tk.W)\n entries.append((typeFields[i], v_act))\n\n # Action\n i += 1\n row = tk.Frame(self.w_cap)\n row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)\n lab = tk.Label(row, padx=5, width=9, text=typeFields[i], anchor='w')\n lab.pack(side=tk.LEFT)\n e_act = tk.Entry(row)\n e_act.pack(side=tk.LEFT, expand=tk.YES, fill=tk.X)\n e_act.config(state='disabled')\n entries.append((typeFields[i], e_act))\n\n '''\n for i, field in typeFields:\n row = tk.Frame(self.w_cap)\n row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)\n\n if i % 2 == 0:\n typ = tk.intVar()\n b_typ = tk.Checkbutton(row, text=field, variable=typ, command=activateCheck)\n b_typ.pack(side=tk.LEFT, fill=tk.X, padx=5, pady=5, anchor=tk.W)\n entries.append((field, typ))\n else:\n lab = tk.Label(row, width=15, text=field, anchor='w')\n lab.pack(side=tk.LEFT)\n ent = tk.Entry(row)\n typ.pack(side=tk.LEFT, expand=tk.YES, fill=tk.X)\n entries.append((field, ent))\n '''\n return entries\n\n\n def import_with_progbar(self, cap=None):\n #tk.Tk().withdraw()\n self.w_import_progress = tk.Toplevel()\n self.w_import_progress.wm_title(\"Capture Import\")\n self.w_import_progress.geometry(\"200x50\")\n if cap != None:\n self.cap = cap\n #self.cap = cap\n\n tk.Label(self.w_import_progress, text=\"Import progress\", width=20).grid(row=0, column=0)\n\n progress_var = tk.IntVar()\n progress_bar = ttk.Progressbar(self.w_import_progress, variable=progress_var, maximum=self.cap.fsize)\n progress_bar.grid(row=1, column=0)\n self.w_import_progress.pack_slaves()\n\n progress_var.set(self.cap.progress)\n self.w_import_progress.update()\n \n #start = datetime.now()\n def update_progress():\n for i, pkt in enumerate(self.cap.cap):\n if i % 4095 == 0:\n progress_var.set(self.cap.progress)\n self.w_import_progress.update()\n self.cap.append_pkt(pkt)\n\n progress_var.set(self.cap.progress)\n self.w_import_progress.update()\n self.w_import_progress.destroy()\n\n self.cap.id_unique_addrs()\n\n def try_multiple_operations(pkt):\n try:\n self.cap.append_pkt(pkt)\n except:\n print(\"error with item\")\n\n def digest_segment(file, results, status, proc):\n print(file, results, status, proc)\n cap = pyshark.FileCapture(file)\n for pkt in cap:\n results[proc].append(pkt)\n #status += 1\n\n print(\"number of packets\", len(results[proc]))\n '''\n if proc:\n for pkt in pyshark.FileCapture(file):\n results.append(pkt)\n status += 1\n else:\n for i, pkt in enumerate(pyshark.FileCapture(file)):\n results.append(pkt)\n status += 1\n if i % 1024 == 0:\n progress_var.set(sum(self.stat))\n self.w_import_progress.update()\n \n progress_var.set(sum(self.stat))\n self.w_import_progress.update()\n self.w_import_progress.destroy()\n ''' \n\n #executor = concurrent.futures.ProcessPoolExecutor(10)\n #futures = [executor.submit(try_multiple_operations, group) for group in grouper(5, self.cap.cap)]\n #self.w_import_progress.after(0, futures = [executor.submit(try_multiple_operations, pkt) for pkt in self.cap.cap])\n #self.w_import_progress.after(0, concurrent.futures.wait(futures))\n\n #num_pkts = int(cln.sub('', str(subprocess.check_output(\"capinfos -c \" + fname, stderr=subprocess.STDOUT, shell=True).split()[-1])))\n start = datetime.now()\n\n try:\n #num_pkts = subprocess.check_output(\"capinfos -c -M \" + self.cap.fpath, stderr=subprocess.STDOUT, shell=True).decode('ascii').split()[-1].replace(',', '')\n #num_pkts = int(subprocess.check_output(\"capinfos -c -M \" + self.cap.fpath, stderr=subprocess.STDOUT, shell=True).decode('ascii').split()[-1])\n num_pkts = int(subprocess.check_output(\"capinfos -c -M \" + self.cap.fpath, stderr=subprocess.PIPE, shell=True).decode('ascii').split()[-1])\n except Exception as e:\n output = e.output\n print(str(output))\n num_pkts = int(output.decode('ascii').split()[-1])\n\n print(\"num_pkts\", num_pkts)\n num_threads = multiprocessing.cpu_count()\n num_threads = 2\n temp = \"./.temp/\"\n #;lkj\n # Packets per process\n ppp = math.ceil(num_pkts / num_threads)\n print(\"packets per process =\", ppp)\n #subprocess.call(\"rm -f ./.temp/*\", stderr=subprocess.STDOUT, shell=True))\n #subprocess.call([\"rm\", temp+\"*\"], stderr=subprocess.STDOUT, shell=True)\n subprocess.call(\"rm \" + temp+\"*\", stderr=subprocess.PIPE, shell=True)\n \n #subprocess.call([\"editcap\", \"-c\", str(ppp), fname, \" ./.temp/split.pcap\"], stderr=subprocess.STDOUT, shell=True) \n #subprocess.call([\"editcap\", \"-c\", str(ppp), self.cap.fpath, temp+\"split.pcap\"], stderr=subprocess.STDOUT, shell=True) \n subprocess.call([\"editcap\", \"-c\", str(ppp), self.cap.fpath, temp+\"split.pcap\"], stderr=subprocess.PIPE, shell=True) \n\n files = subprocess.check_output([\"ls\", temp]).decode('ascii').split()\n jobs = []\n self.res = [[]]*num_threads\n self.stat = [0]*num_threads\n\n for i, f in enumerate(files):\n proc = multiprocessing.Process(target=digest_segment, args=(temp+f, self.res, self.stat[i], i))\n jobs.append(proc)\n\n for j in jobs:\n #j.start()\n self.w_import_progress.after(0, j.start)\n\n for i,j in enumerate(jobs):\n j.join()\n print(\"job\", i, \"complete\")\n print(len(self.res[i]))\n\n #self.w_import_progress.after(0, update_progress)\n\n self.cap.pkt = [y for x in self.res for y in x]\n\n stop = datetime.now()\n print(\"time to process = \", (stop-start).total_seconds())\n\n print(\"number of packets = \", len(self.cap.pkt))\n #self.w_import_progress.after(10, self.cap.import_pkts())\n\n self.yield_focus(self.w_import_progress)\n #print(\"yielded focus\")\n\n '''\n #while self.cap.progress < self.cap.fsize:\n for pkt in self.cap.cap:\n progress_var.set(self.cap.progress)\n self.w_import_progress.update()\n self.cap.append_pkt(pkt)\n #time.sleep(5)\n #p.join()\n '''\n #stop = datetime.now()\n #print(\"time to import = \", (stop-start).total_seconds())\n #return\n #self.w_import_progress.destroy()\n\n def import_and_close(self, entries):\n\n #Check if capture is already in database (using sha256)\n filehash = hashlib.sha256(open(entries[0][1].get(),'rb').read()).hexdigest()\n self.db_handler.db.select_unique_captures()\n\n captures = self.db_handler.db.cursor.fetchall()\n #print(type(captures))\n #print(captures)\n\n #if any(filehash in hash for hash in self.db_handler.db.cursor):\n if any(filehash in hash for hash in captures):\n tk.Tk().withdraw()\n messagebox.showerror(\"Error\", \"Capture file already imported into database\")\n else:\n #tk.Tk().withdraw()\n #self.cap = CaptureDigest(entries[0][1].get())\n #self.import_progress()\n #self.cap.import_pkts()\n\n self.cap = CaptureDigest(entries[0][1].get())\n #:LKJ\n '''\n if self.cap.fsize > 512000:\n self.import_with_progbar()\n else:\n self.import_with_progbar()\n '''\n #self.cap.import_pkts()\n #:LKJ\n self.cap.import_pkts()\n\n #self.import_with_progbar(CaptureDigest(entries[0][1].get()))\n \n print(\"finished importing\")\n #messagebox.showinfo(\"Importing\", \"Please wait for the capture file to be processed\")\n\n data_capture = {\n \"fileName\" : self.cap.fname,\n \"fileLoc\" : self.cap.fdir,\n \"fileHash\" : self.cap.fileHash,\n #;lkj;lkj\n \"capDate\" : epoch2datetime(float(self.cap.capTimeStamp)),#epoch2datetime(float(self.cap.capDate)),\n #\"duration\" : self.cap.capDuration.seconds,\n \"capDuration\" : self.cap.capDuration,\n #\"activity\" : entries[1][1].get(),\n #\"details\" : entries[2][1].get()\n \"details\" : entries[1][1].get(),\n field2db[ entries[2][0].cget('text') ] : field2db[ lifecyclePhaseFields[ entries[2][1].get() ] ]\n #\"Internet\" : entries[3][1].get(),\n #\"Human Interaction\" : entries[4][1].get(),\n #\"Preferred DNS Enabled\" : entries[5][1].get(),\n #\"Isolated\" : entries[6][1].get(),\n #\"Duration-based\" : entries[7][1].get(),\n #\"Duration\" : entries[8][1].get(),\n #\"Action-based\" : entries[9][1].get(),\n #\"Action\" : entries[10][1].get()\n }\n\n for i in range(3,11):\n data_capture[ field2db[ entries[i][0] ] ] = entries[i][1].get()\n print(i, entries[i][1].get())\n\n print('data_capture:', data_capture)\n\n # Popup window\n #self.yield_focus(self.w_cap)\n #print(\"(A) popup_import_capture_devices\")\n self.popup_import_capture_devices(self.cap)\n\n #print(\"(B) db_handler.db.insert_capture\")\n self.db_handler.db.insert_capture(data_capture)\n #print(\"(C) populate_capture_list\")\n self.populate_capture_list()\n\n #print(\"(D) import_packets\")\n self.import_packets(self.cap)\n\n self.w_cap.destroy()\n\n\n def pre_popup_import_capture_devices(self):\n sel_cap_path = self.cap_list.get_selected_row()[4] + \"/\" + self.cap_list.get_selected_row()[1]\n\n if self.cap == None or (self.cap.fdir + \"/\" + self.cap.fname) != sel_cap_path:\n #self.popup_import_capture_devices( CaptureDigest(sel_cap_path, gui=True) )\n start = datetime.now()\n self.cap = CaptureDigest(sel_cap_path)\n\n\n #:LKJ\n '''\n if self.cap.fsize > 512000:\n self.import_with_progbar()\n else:\n self.import_with_progbar()\n #self.cap.import_pkts()\n '''\n #:LKJ\n self.cap.import_pkts()\n\n #self.import_with_progbar( CaptureDigest(sel_cap_path) )\n stop = datetime.now()\n print(\"time to import = \", (stop-start).total_seconds())\n #self.popup_import_capture_devices( cap=self.cap )\n self.popup_import_capture_devices()\n #self.popup_import_capture_devices( CaptureDigest(sel_cap_path) )\n else:\n self.popup_import_capture_devices()\n\n #self.import_with_progbar( CaptureDigest(sel_cap_path) )\n stop = datetime.now()\n print(\"time to import = \", (stop-start).total_seconds())\n '''\n #self.popup_import_capture_devices( cap=self.cap )\n self.popup_import_capture_devices()\n #self.popup_import_capture_devices( CaptureDigest(sel_cap_path) )\n else:\n self.popup_import_capture_devices()\n '''\n\n #def popup_import_capture_devices(self, cap):\n def popup_import_capture_devices(self, cap=None):\n self.w_cap_dev = tk.Toplevel()\n\n if cap == None:\n if self.cap == None:# or self.cap != cap:\n print(\"Error: If no previous capture imported, a capture file must be provided.\")\n elif self.cap == None:\n self.cap = cap\n\n self.w_cap_dev.wm_title(self.cap.fname)\n\n self.topDevFrame = tk.Frame(self.w_cap_dev, width=600, bd=1, bg=\"#eeeeee\")#, bg=\"#dfdfdf\")\n ents = self.make_form_capture_devices(captureInfoFields, self.cap.capDate, self.cap.capTime)\n\n self.botDevFrame = tk.Frame(self.w_cap_dev, width=600, bd=1, bg=\"#eeeeee\")#, bg=\"#dfdfdf\")\n\n ## Left (Unidentified) Dev Frame\n self.unidentifiedDevFrame = tk.Frame(self.botDevFrame, width=300)#, bd=1, bg=\"#dfdfdf\")\n\n self.cap_dev_title = tk.Label(self.botDevFrame, text=\"Devices\", bg=\"#dfdfdf\", bd=1, relief=\"flat\", anchor=\"n\")\n\n self.unidentified_title_var=tk.StringVar()\n self.unidentified_title_var.set(\"Unidentified\")\n self.unidentified_title = tk.Label(self.unidentifiedDevFrame, textvariable=self.unidentified_title_var, bg=\"#eeeeee\", bd=1, relief=\"flat\")\n self.unidentified_title.pack(side=\"top\", fill=tk.X)\n\n self.unidentified_dev_header = [\"Manufacturer\", \"MAC\", \"IPv4\", \"IPv6\"]\n self.unidentified_dev_list = MultiColumnListbox(parent=self.unidentifiedDevFrame,\n header=self.unidentified_dev_header,\n list=list(), selectmode=\"browse\")\n self.unidentified_dev_list.bind(\"<>\", self.update_unidentified_list_selection)\n\n ## Right (Identified) Dev Frame\n self.identifiedDevFrame = tk.Frame(self.botDevFrame, width=300)#, bd=1, bg=\"#dfdfdf\")\n\n self.identified_title_var=tk.StringVar()\n self.identified_title_var.set(\"Identified\")\n self.identified_title = tk.Label(self.identifiedDevFrame, textvariable=self.identified_title_var, bg=\"#eeeeee\", bd=1, relief=\"flat\")\n self.identified_title.pack(side=\"top\", fill=tk.X)\n\n self.identified_dev_header = [\"Manufacturer\", \"Model\", \"Internal Name\", \"Category\", \"MAC\", \"IPv4\", \"IPv6\"]\n self.identified_dev_list = MultiColumnListbox(parent=self.identifiedDevFrame,\n header=self.identified_dev_header,\n list=list(), selectmode=\"browse\")\n self.identified_dev_list.bind(\"<>\", self.update_identified_list_selection)\n\n\n # Grid placements #\n self.topDevFrame.grid(row=0, column=0, sticky=\"new\")\n self.botDevFrame.grid(row=1, column=0, sticky=\"nsew\")\n self.cap_dev_title.grid(row=0, column=0, columnspan=2, sticky=\"new\")\n self.unidentifiedDevFrame.grid(row=1, column=0, sticky=\"nsew\")\n self.identifiedDevFrame.grid(row=1, column=1, sticky=\"nsew\")\n\n # Grid configuration #\n self.botDevFrame.grid_rowconfigure(1, weight=1)\n self.botDevFrame.grid_columnconfigure(0, weight=1)\n self.botDevFrame.grid_columnconfigure(1, weight=1)\n\n self.w_cap_dev.grid_rowconfigure(1, weight=1)\n self.w_cap_dev.grid_columnconfigure(0, weight=1)\n\n '''\n # Select first element of each list\n # Try becuase the list might be empty\n self.unidentified_dev_list.focus(0)\n self.unidentified_dev_list.selection_set(0)\n self.identified_dev_list.focus(0)\n self.identified_dev_list.selection_set(0)\n\n try:\n self.unidentified_dev_list.focus(0)\n self.unidentified_dev_list.selection_set(0)\n except:\n pass\n\n try:\n self.identified_dev_list.focus(0)\n self.identified_dev_list.selection_set(0)\n except:\n pass\n '''\n\n # Buttons #\n self.b_cap_dev_close = tk.Button(self.unidentifiedDevFrame, text='Close', command=(lambda c=self.cap.fname : self.close_w_cap_dev(c)))\n self.b_cap_dev_import = tk.Button(self.unidentifiedDevFrame, text='Import Device', state='disabled',\n command=(lambda f={'fileName':self.cap.fname,'fileHash':self.cap.fileHash}:\n self.popup_import_device(f)))\n #command=(lambda e=0, d={'fileName':self.cap.fname,'fileHash':self.cap.fileHash,\n # 'mac_addr':self.unidentified_dev_list.get_selected_row()[1]}:\n # self.popup_import_device(self.unidentified_dev_list.get_selected_row()[e],d)))\n \n self.b_cap_dev_modify = tk.Button(self.identifiedDevFrame, text='Modify State', state='disabled',\n #command=(lambda d=self.identified_dev_list.selection(): self.prep_popup_update_device_state(d)))\n command=(lambda d=self.identified_dev_list.get_selected_row(): self.prep_popup_update_device_state(d)))\n\n self.b_cap_dev_close.pack(side=tk.LEFT, padx=5, pady=5)\n self.b_cap_dev_import.pack(side=tk.RIGHT, padx=5, pady=5)\n self.b_cap_dev_modify.pack(side=tk.RIGHT, padx=5, pady=5)\n\n # Update unidentified, identified lists and try to select the first element\n self.refresh_unidentified_identified_lists()\n # Select first element of each list\n # Try becuase the list might be empty\n self.unidentified_dev_list.focus(0)\n self.unidentified_dev_list.selection_set(0)\n self.identified_dev_list.focus(0)\n self.identified_dev_list.selection_set(0)\n\n self.yield_focus(self.w_cap_dev)\n\n def update_unidentified_list_selection(self, event):\n self.unidentified_dev_list_sel = self.unidentified_dev_list.get( self.unidentified_dev_list.selection() )\n print(\"self.identified_dev_list_sel = \", self.unidentified_dev_list_sel)\n\n def update_identified_list_selection(self, event):\n self.identified_dev_list_sel = self.identified_dev_list.get( self.identified_dev_list.selection() )\n print(\"self.identified_dev_list_sel = \", self.identified_dev_list_sel)\n\n def prep_popup_update_device_state(self, d):\n d = self.identified_dev_list_sel\n #print(\"d = \",d)\n mac = d[4]\n self.db_handler.db.select_most_recent_fw_ver({'mac_addr' : mac,\n #'capDate' : self.cap.capTimeStamp})\n 'capDate' : self.cap.capDate + \" \" + self.cap.capTime})\n print(self.cap.capTimeStamp)\n temp = self.db_handler.db.cursor.fetchone()\n print(\"temp: \", temp)\n\n if temp == None:\n fw_ver = ''\n else:\n fw_ver = temp[0]\n\n device_state_data = {'fileHash' : self.cap.fileHash,\n 'mac_addr' : mac.upper(),\n 'internalName' : d[2],\n 'fw_ver' : fw_ver,\n #'ipv4_addr' : self.cap.findIP(mac),\n #'ipv6_addr' : self.cap.findIP(mac, v6=True)}\n 'ipv4_addr' : d[5],\n 'ipv6_addr' : d[6]}\n\n print(\"ipv4:\",device_state_data['ipv4_addr'])\n print(\"ipv6:\",device_state_data['ipv6_addr'])\n \n self.popup_update_device_state(device_state_data)\n\n def close_w_cap_dev(self, capName):\n\n #Check if any of the devices seen have been added to the device_state table already and add if not\n #for dev in self.identified\n\n self.populate_device_list(capture = capName)\n self.w_cap_dev.destroy()\n\n\n def refresh_unidentified_identified_lists(self):\n # Clear lists\n self.unidentified_dev_list.clear()\n self.identified_dev_list.clear()\n\n # Sort devices from Capture into either identified or unidentified device lists\n self.db_handler.db.select_device_macs()\n macsInDevTbl = self.db_handler.db.cursor.fetchall()\n #print(\"macsInDevTbl: \", macsInDevTbl)\n #print()\n #identifiedMacsInDb = self.db_handler.db.cursor.fetchall()\n #print(\"identifiedMacsInDb: \", identifiedMacsInDb)\n self.db_handler.db.select_identified_devices_from_cap(self.cap.fileHash)\n #macsInDfCTbl = self.db_handler.db.cursor.fetchall()\n #print(\"macsInDfCTbl: \", macsInDfCTbl)\n devFromCapTbl = self.db_handler.db.cursor.fetchall()\n #print(\"devFromCapTbl: \", devFromCapTbl)\n #print()\n\n print(\"num uniqueMacs:\", len(self.cap.uniqueMAC))\n for mac in self.cap.uniqueMAC:\n unidentified = True\n if mac.upper() in [x.upper() for (x,) in macsInDevTbl]:\n # Get device info\n self.db_handler.db.select_device(mac)\n (id, mfr, model, mac_addr, internalName, category, mudCapable, wifi, ethernet, bluetooth, G3, G4, G5, zigbee, zwave, other, notes, unidentified) = self.db_handler.db.cursor.fetchone()\n\n # Get device state info\n self.db_handler.db.select_device_state(self.cap.fileHash, mac)\n if self.db_handler.db.cursor.rowcount == 1:\n (id, hash, mac_addr, internalName, fw_ver, ip, ipv6) = self.db_handler.db.cursor.fetchone()\n elif self.db_handler.db.cursor.rowcount == 0:\n #ip = self.cap.findIP(mac)\n #ipv6 = self.cap.findIP(mac, v6=True)\n (ip, ipv6) = self.cap.findIPs(mac)\n\n # May want to modify this not to take the previous fw_version\n self.db_handler.db.select_most_recent_fw_ver({'mac_addr' : mac,\n #'capDate' : self.cap.capTimeStamp})\n 'capDate' : self.cap.capDate + \" \" + self.cap.capTime})\n try:\n (fw_ver,) = self.db_handler.db.cursor.fetchone()\n except TypeError as te:\n fw_ver = ''\n\n self.db_handler.db.insert_device_state({\"fileHash\":self.cap.fileHash,\n \"mac_addr\":mac.upper(),\n \"internalName\":internalName,\n #\"fw_ver\":prev_fw_ver,\n \"fw_ver\":fw_ver,\n \"ipv4_addr\":ip,\n \"ipv6_addr\":ipv6})\n else:\n print(\"ERROR, something went horribly wrong with the database\")\n \n '''\n if unidentified:\n self.unidentified_dev_list.append((lookup_mac(mac), mac.upper(), self.cap.findIP(mac), self.cap.findIP(mac, v6=True)))\n else: #May want to include firmware version here\n self.identified_dev_list.append((mfr, model, internalName, category, mac.upper(), ip, ipv6))\n '''\n\n else:\n # Insert device info into device table\n #device_data = {'mfr' : , 'mac_addr' : mac.upper()}\n\n #device_data = {'mac_addr' : mac.upper()}\n\n # Check if MAC to Mfr entry exists\n self.db_handler.db.select_mac_to_mfr()\n mac2mfr = self.db_handler.db.cursor.fetchall()\n mac_prefix = mac.upper()[0:8]\n if mac_prefix in [x for (id, x, mfr) in mac2mfr]:\n if mfr == \"**company not found**\" or mfr == \"None\" or mfr == None:\n mfr = lookup_mac(mac)\n else:\n mfr = lookup_mac(mac)\n\n if mfr != \"**company not found**\" and mfr != \"None\" and mfr != None:\n self.db_handler.db.insert_mac_to_mfr({'mac_prefix':mac_prefix, 'mfr':mfr})\n\n device_data = {'mac_addr' : mac.upper(), 'mfr': mfr}\n\n self.db_handler.db.insert_device_unidentified(device_data)\n\n\n # Insert device_state info into device_state table\n #ip = self.cap.findIP(mac)\n #ipv6 = self.cap.findIP(mac, v6=True)\n (ip, ipv6) = self.cap.findIPs(mac)\n\n self.db_handler.db.insert_device_state_unidentified(\n {\"fileHash\":self.cap.fileHash,\n \"mac_addr\":mac.upper(),\n \"ipv4_addr\":ip,\n \"ipv6_addr\":ipv6})\n \n '''\n # Insert device_state info into device_state table\n # THIS SHOULD BE UNNECESSARY BECAUSE IT SHOULD NEVER BE IN THE device_state table without being in the device_table, but no reason not to safety check\n self.db_handler.db.select_device_state(self.cap.fileHash, mac)\n if self.db_handler.db.cursor.rowcount == 1:\n (id, hash, mac_addr, internalName, fw_ver, ip, ipv6) = self.db_handler.db.cursor.fetchone()\n print(\"ERROR: Instance that shouldn't exist\\n\\tSomething went horribly wrong with the database\")\n elif self.db_handler.db.cursor.rowcount == 0:\n ip = self.cap.findIP(mac)\n ipv6 = self.cap.findIP(mac, v6=True)\n\n # May want to modify this not to take the previous fw_version\n self.db_handler.db.select_most_recent_fw_ver({'mac_addr' : mac,\n #'capDate' : self.cap.capTimeStamp})\n 'capDate' : self.cap.capDate + \" \" + self.cap.capTime})\n try:\n (fw_ver,) = self.db_handler.db.cursor.fetchone()\n except TypeError as te:\n fw_ver = ''\n\n self.db_handler.db.insert_device_state({\"fileHash\":self.cap.fileHash,\n \"mac_addr\":mac.upper(),\n \"internalName\":internalName,\n #\"fw_ver\":prev_fw_ver,\n \"fw_ver\":fw_ver,\n \"ipv4_addr\":ip,\n \"ipv6_addr\":ipv6})\n else:\n print(\"ERROR: Multiple Instances:\\n\\tSomething went horribly wrong with the database\")\n '''\n '''\n # Put device into unidentified_dev_list\n self.unidentified_dev_list.append((lookup_mac(mac), mac.upper(), self.cap.findIP(mac), self.cap.findIP(mac, v6=True)))\n '''\n\n if unidentified:\n self.unidentified_dev_list.append((lookup_mac(mac), mac.upper(), self.cap.findIP(mac), self.cap.findIP(mac, v6=True)))\n else: #May want to include firmware version here\n self.identified_dev_list.append((mfr, model, internalName, category, mac.upper(), ip, ipv6))\n\n\n '''\n # Get device state info\n self.db_handler.db.select_device_state(self.cap.fileHash, mac)\n if self.db_handler.db.cursor.rowcount == 1:\n (id, hash, mac_addr, internalName, fw_ver, ip, ipv6) = self.db_handler.db.cursor.fetchone()\n elif self.db_handler.db.cursor.rowcount == 0:\n ip = self.cap.findIP(mac)\n ipv6 = self.cap.findIP(mac, v6=True)\n\n # May want to modify this not to take the previous fw_version\n self.db_handler.db.select_most_recent_fw_ver({'mac_addr' : mac,\n #'capDate' : self.cap.capTimeStamp})\n 'capDate' : self.cap.capDate + \" \" + self.cap.capTime})\n try:\n (fw_ver,) = self.db_handler.db.cursor.fetchone()\n except TypeError as te:\n fw_ver = ''\n\n self.db_handler.db.insert_device_state({\"fileHash\":self.cap.fileHash,\n \"mac_addr\":mac.upper(),\n \"internalName\":internalName,\n #\"fw_ver\":prev_fw_ver,\n \"fw_ver\":fw_ver,\n \"ipv4_addr\":ip,\n \"ipv6_addr\":ipv6})\n else:\n print(\"ERROR, something went horribly wrong with the database\")\n '''\n\n '''\n if unidentified:\n self.unidentified_dev_list.append((lookup_mac(mac), mac.upper(), self.cap.findIP(mac), self.cap.findIP(mac, v6=True)))\n else:\n self.identified_dev_list.append((mfr, model, internalName, category, mac.upper(), ip, ipv6))\n '''\n # Check if the mac address is in the device_in_capture table and update if necessary\n if mac.upper() not in [x.upper() for (_,_,_,x) in devFromCapTbl]:\n #print(\"mac not found in table for this capture\")\n self.db_handler.db.insert_device_in_capture({'fileName':self.cap.fname,\n 'fileHash':self.cap.fileHash,\n 'mac_addr':mac.upper()})\n\n \"\"\"\n print(\"num uniqueMacs:\", len(self.cap.uniqueMAC))\n for mac in self.cap.uniqueMAC:\n #print(\"In for mac in self.cap.uniqueMAC\")\n #print(\"\\tmac\", mac)\n #print(\"\\tmfr = \", lookup_mac(mac))\n if mac.upper() in [x.upper() for (x,) in macsInDevTbl]:\n # Get device info\n self.db_handler.db.select_device(mac)\n (id, mfr, model, mac_addr, internalName, category, mudCapable, wifi, bluetooth, G3, G4, G5, zigbee, zwave, other, notes, unidentified) = self.db_handler.db.cursor.fetchone()\n\n # Get device state info\n self.db_handler.db.select_device_state(self.cap.fileHash, mac)\n if self.db_handler.db.cursor.rowcount == 1:\n (id, hash, mac_addr, internalName, fw_ver, ip, ipv6) = self.db_handler.db.cursor.fetchone()\n elif self.db_handler.db.cursor.rowcount == 0:\n #if ip == None:\n ip = self.cap.findIP(mac)\n #if ipv6 == None:\n ipv6 = self.cap.findIP(mac, v6=True)\n\n # May want to modify this not to take the previous fw_version\n self.db_handler.db.select_most_recent_fw_ver({'mac_addr' : mac,\n #'capDate' : self.cap.capTimeStamp})\n 'capDate' : self.cap.capDate + \" \" + self.cap.capTime})\n try:\n (fw_ver,) = self.db_handler.db.cursor.fetchone()\n except TypeError as te:\n fw_ver = ''\n\n self.db_handler.db.insert_device_state({\"fileHash\":self.cap.fileHash,\n \"mac_addr\":mac.upper(),\n \"internalName\":internalName,\n #\"fw_ver\":prev_fw_ver,\n \"fw_ver\":fw_ver,\n \"ipv4_addr\":ip,\n \"ipv6_addr\":ipv6})\n else:\n print(\"ERROR, something went horribly wrong with the database\")\n \n '''\n # Check if the mac address is in the device_in_capture table and update if necessary\n if mac.upper() not in [x.upper() for (id,x) in identifiedMacsInDb]:\n print(\"mac not found in db\")\n self.db_handler.db.insert_device_in_capture({'fileName':self.cap.fname,'fileHash':self.cap.fileHash,\n 'mac_addr':mac_addr.upper(), 'imported':True})\n #self.db_handler.db.insert_mac_to_mfr({'mac_prefix':mac_addr.upper()[0:8], 'mfr':mfr})\n # Update the entry\n else:\n print(\"mac found in db\")\n output = [item for item in identifiedMacsInDb if item[1] == mac_addr.upper() and not item[2]]\n print(output)\n id = output[0][0]\n imported = output[0][2]\n if not imported:\n print(\"Id =\", id)\n print(\"mac_addr =\", mac_addr)\n print(\"imported =\", imported)\n self.db_handler.db.update_device_in_capture({'id':id, 'fileName':self.cap.fname,'fileHash':self.cap.fileHash,\n 'mac_addr':mac_addr.upper(), 'imported':True})\n #self.db_handler.db.select_mac_to_mfr()\n #mac2mfr = self.db_handler.db.cursor.fetchall()\n #self.db_handler.db.insert_mac_to_mfr({'mac_prefix':mac_addr.upper()[0:8], 'mfr':mfr})\n '''\n if unidentified:\n self.unidentified_dev_list.append((lookup_mac(mac), mac.upper(), self.cap.findIP(mac), self.cap.findIP(mac, v6=True)))\n else:\n self.identified_dev_list.append((mfr, model, internalName, category, mac.upper(), ip, ipv6))\n else:\n #Insert device into Device Table\n\n if unidentified:\n self.unidentified_dev_list.append((lookup_mac(mac), mac.upper(), self.cap.findIP(mac), self.cap.findIP(mac, v6=True)))\n else:\n self.identified_dev_list.append((mfr, model, internalName, category, mac.upper(), ip, ipv6))\n #print(\"Not in macsInDevTbl\")\n #print(\"\\tmac\", mac)\n #print(\"\\tmfr = \", lookup_mac(mac))\n\n\n #self.unidentified_dev_list.append((lookup_mac(mac), mac.upper(), self.cap.findIP(mac), self.cap.findIP(mac, v6=True)))\n '''\n self.db_handler.db.insert_device_in_capture({'fileName':self.cap.fname,'fileHash':self.cap.fileHash,\n #'mac_addr':mac_addr.upper(), 'imported':False})\n 'mac_addr':mac.upper(), 'imported':False})\n '''\n # Check if the mac address is in the device_in_capture table and update if necessary\n if mac.upper() not in [x.upper() for (_,_,_,x) in devFromCapTbl]:\n #print(\"mac not found in table for this capture\")\n self.db_handler.db.insert_device_in_capture({'fileName':self.cap.fname,\n 'fileHash':self.cap.fileHash,\n 'mac_addr':mac.upper()})\n\n\n \"\"\"\n\n # Enable / Disable buttons as deemed necessary\n if self.unidentified_dev_list.num_nodes > 0:\n self.b_cap_dev_import.config(state=\"normal\")\n else:\n self.b_cap_dev_import.config(state=\"disabled\")\n\n if self.identified_dev_list.num_nodes > 0:\n self.b_cap_dev_modify.config(state=\"normal\")\n else:\n self.b_cap_dev_modify.config(state=\"disabled\")\n\n def make_form_capture_devices(self, fields, capDate, capTime):\n entries = []\n\n for i, field in enumerate(fields):\n row = tk.Frame(self.topDevFrame)#w_cap_dev)\n #row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)\n row.pack(side=tk.TOP, fill=tk.X)\n\n lab = tk.Label(row, width=15, text=field, anchor='w')\n lab.pack(side=tk.LEFT, fill=\"both\")#previously just tk.LEFT\n ent = tk.Entry(row, width=15)\n #ent.pack(side=tk.TOP, expand=tk.YES, fill=tk.X)#previously tk.X\n ent.pack(side=tk.LEFT)#, fill=tk.X)#previously tk.X\n\n if not i:\n ent.insert( 10, capDate )\n else:\n ent.insert( 10, capTime )\n\n entries.append((field, ent))\n '''\n if i < len(fields)-1:\n lab = tk.Label(row, width=15, text=field, anchor='w')\n lab.pack(side=tk.LEFT)\n ent = tk.Entry(row)\n ent.pack(side=tk.TOP, expand=tk.YES, fill=tk.X)\n entries.append((field, ent))\n else:\n lab = tk.Label(row, width=15, text=field, anchor='s')\n lab.pack(side=tk.BOTTOM)\n '''\n\n def popup_import_device(self, fname):\n self.w_dev = tk.Toplevel()\n self.w_dev.wm_title(\"Import Devices\")\n\n mfr = self.unidentified_dev_list_sel[0]\n mac = self.unidentified_dev_list_sel[1].upper()\n ipv4 = self.unidentified_dev_list_sel[2]\n ipv6 = self.unidentified_dev_list_sel[3]\n #print(\"ipv4\",ipv4)\n #print(\"ipv6\",ipv6)\n #print(mfr)\n\n ents = self.make_form_device(deviceFields, deviceOptions, mfr, mac)\n\n dev_in_cap_data = fname\n dev_in_cap_data['mac_addr'] = mac\n #dev_in_cap_data['imported'] = True\n\n b_import = tk.Button(self.w_dev, text='Import',\n command=(lambda e=ents, d=dev_in_cap_data, i=(ipv4, ipv6): self.import_dev_and_close(e,d,i)))\n\n b_cancel = tk.Button(self.w_dev, text='Cancel', command=self.w_dev.destroy)\n\n if sys.platform == \"win32\":\n b_cancel.pack(side=tk.RIGHT, padx=5, pady=5)\n b_import.pack(side=tk.RIGHT, padx=5, pady=5)\n else:\n b_import.pack(side=tk.RIGHT, padx=5, pady=5)\n b_cancel.pack(side=tk.RIGHT, padx=5, pady=5)\n\n b_import.pack(side=tk.RIGHT, padx=5, pady=5)\n\n self.yield_focus(self.w_dev)\n\n\n def make_form_device(self, fields, options, mfr, mac_addr):\n entries = []\n\n for i, field in enumerate(fields):\n row = tk.Frame(self.w_dev)\n row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)\n\n lab = tk.Label(row, width=15, text=field, anchor='w')\n lab.pack(side=tk.LEFT)\n\n if i < len(fields)-1:\n if field == 'MAC':\n lab = tk.Label(row, width=15, text=mac_addr, anchor='w', fg='gray')\n lab.pack(side=tk.LEFT)\n entries.append((field, mac_addr))\n continue\n else:\n ent = tk.Entry(row)\n ent.pack(side=tk.RIGHT, expand=tk.YES, fill=tk.X)\n\n if not i:\n ent.insert(30, mfr)\n\n entries.append((field, ent))\n\n for i, option in enumerate(options):\n if i == len(options)-1:\n row = tk.Frame(self.w_dev)\n lab = tk.Label(row, width=10, text=option, anchor='w')\n ent = tk.Entry(row)\n\n row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)\n #lab.pack(side=tk.LEFT, expand=tk.YES, fill=tk.X)\n lab.pack(side=tk.LEFT)\n ent.pack(side=tk.RIGHT, expand=tk.YES, fill=tk.X)\n \n entries.append((option, ent))\n else:\n if i%5 == 0:\n row = tk.Frame(self.w_dev)\n row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)\n\n checkvar = tk.IntVar()\n ckb = tk.Checkbutton(row, text=option, width=10, justify=tk.LEFT, variable=checkvar)\n ckb.pack(side=tk.LEFT, anchor=\"w\")\n \n if option == \"wifi\" or option == \"WiFi\":\n checkvar.set(True)\n\n entries.append((option, checkvar))\n\n return entries\n\n def import_dev_and_close(self, entries, dev_in_cap_data, ips):\n device_data = {\"unidentified\":False}\n for entry in entries:\n field = entry[0]\n if field == 'MAC':\n value = dev_in_cap_data['mac_addr']\n else:\n value = entry[1].get()\n\n try:\n dbfield = field2db[field]\n except:\n pass\n else:\n device_data[dbfield] = value\n print('field: %s value %s -> database field: %s' % (field, value, dbfield))\n\n self.db_handler.db.insert_device(device_data)\n self.db_handler.db.insert_device_in_capture(dev_in_cap_data)\n\n mac = dev_in_cap_data['mac_addr']\n #print(\"mac:\", mac)\n\n # Check if MAC to Mfr entry exists ;lkj\n self.db_handler.db.select_mac_to_mfr()\n mac2mfr = self.db_handler.db.cursor.fetchall()\n #mac_prefix = dev_in_cap_data['mac_addr'].upper()[0:8]\n mac_prefix = mac.upper()[0:8]\n if mac_prefix not in [x for (id, x, mfr) in mac2mfr]:\n #print(entries[0])\n self.db_handler.db.insert_mac_to_mfr({'mac_prefix':mac_prefix, 'mfr':entries[0][1].get()})\n\n self.refresh_unidentified_identified_lists()\n\n #mac = dev_in_cap_data['mac_addr']\n\n self.db_handler.db.select_most_recent_fw_ver({'mac_addr' : mac,\n #'capDate' : self.cap.capTimeStamp})\n 'capDate' : self.cap.capDate + \" \" + self.cap.capTime})\n try:\n (fw_ver,) = self.db_handler.db.cursor.fetchone()\n except TypeError as te:\n fw_ver = ''\n \n device_state_data = {'fileHash' : dev_in_cap_data['fileHash'],\n 'mac_addr' : mac,\n 'internalName' : device_data['internalName'],\n 'fw_ver' : fw_ver,\n #'ipv4_addr' : self.cap.findIP(mac),\n #'ipv6_addr' : self.cap.findIP(mac, v6=True)}\n 'ipv4_addr' : ips[0],\n 'ipv6_addr' : ips[1]}\n\n try:\n self.popup_update_device_state(device_state_data)\n except _mysql_connector.MySQLInterfaceError as msqle:\n tk.Tk().withdraw()\n messagebox.showerror(\"Error\", \"Please create a unique Internal Name\")\n\n self.w_dev.destroy()\n\n def popup_update_device_state(self, device_state_data):\n self.w_dev_state = tk.Toplevel()\n self.w_dev_state.wm_title(device_state_data['internalName'])\n\n ents = self.make_form_device_state(device_state_data)\n\n self.w_dev_state.bind('', (lambda event, d=device_state_data, e=ents: self.import_dev_state_and_close(d,e)))\n \n b_update = tk.Button(self.w_dev_state, text='Update',\n command=(lambda d=device_state_data, e=ents: self.import_dev_state_and_close(d, e)))\n\n b_close = tk.Button(self.w_dev_state, text='Close', command=self.w_dev_state.destroy)\n\n if sys.platform == \"win32\":\n b_close.pack(side=tk.RIGHT, padx=5, pady=5)\n b_update.pack(side=tk.RIGHT, padx=5, pady=5)\n else:\n b_update.pack(side=tk.RIGHT, padx=5, pady=5)\n b_close.pack(side=tk.RIGHT, padx=5, pady=5)\n\n self.yield_focus(self.w_dev_state)\n\n\n def make_form_device_state(self, device_state_data):\n entries = {}\n\n for i, (label, value) in enumerate(device_state_data.items()):\n if not i:\n continue\n row = tk.Frame(self.w_dev_state)\n row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)\n\n lab = tk.Label(row, width=15, text=str(field2db.inverse[label]).replace('[','').replace(']','').replace(\"'\",''), anchor='w')\n lab.pack(side=tk.LEFT)\n if label == 'fw_ver':\n v = tk.StringVar()\n ent = tk.Entry(row, textvariable=v)\n ent.pack(side=tk.RIGHT, expand=tk.YES, fill=tk.X)\n ent.insert(25, value)\n\n entries[label] = v\n else:\n lab = tk.Label(row, width=25, text=value, anchor='w', fg='gray')\n lab.pack(side=tk.LEFT)\n entries[label] = value\n\n return entries\n\n\n def import_dev_state_and_close(self, device_state_data, entries):\n print(\"device_state_data: \",device_state_data)\n print(\"entries: \",entries)\n\n print(entries['fw_ver'].get())\n device_state_data['fw_ver'] = str(entries['fw_ver'].get())\n \n # Check if there is already an entry for this data:\n #self.db_handler.db.select_device_state_exact(device_state_data)\n self.db_handler.db.select_device_state(device_state_data[\"fileHash\"], device_state_data[\"mac_addr\"])\n temp = self.db_handler.db.cursor.fetchone()\n print(temp)\n if temp == None:\n self.db_handler.db.insert_device_state(device_state_data)\n else:\n device_state_data[\"id\"] = temp[0]\n self.db_handler.db.update_device_state(device_state_data)\n\n self.w_dev_state.destroy()\n\n\n def fetch(self,entries):\n for entry in entries:\n field = entry[0]\n text = entry[1].get()\n print('%s: \"%s\"' % (field, text)) \n\n\n # Uses Treeview\n def populate_capture_list(self):\n # clear previous list\n self.cap_list.clear()\n self.cap_list.append((\"All...\",))\n\n # Get and insert all captures currently added to database\n self.db_handler.db.select_imported_captures()\n\n for (id, fileName, fileLoc, fileHash, capDate, capDuration, lifecyclePhase,\n internet, humanInteraction, preferredDNS, isolated, durationBased,\n duration, actionBased, deviceAction, details) in self.db_handler.db.cursor:\n self.cap_list.append((capDate, fileName, deviceAction, capDuration, details, fileLoc))\n #for (id, fileName, fileLoc, fileHash, capDate, activity,\n #duration, details) in self.db_handler.db.cursor:\n #self.cap_list.append((capDate, fileName, activity, duration, details, fileLoc)) #for early stages\n #self.cap_list.append((capDate, fileName, activity, details, fileLoc)) #for early stages\n \n # Set focus on the first element\n self.cap_list.focus(0)\n self.cap_list.selection_set(0)\n\n\n # Uses Treeview\n def update_dev_list(self, event):\n first = True\n\n for cap in self.cap_list.selection():\n cap_details = self.cap_list.get(cap)\n cap_date = cap_details[0]\n\n if cap_date == \"All...\":\n self.populate_device_list()\n self.b_main_inspect.config(state=\"disabled\")\n break\n else:\n cap_name = cap_details[1]\n self.populate_device_list( capture=cap_name, append=(not first) )\n first=False\n self.b_main_inspect.config(state=\"normal\")\n \n #;lkj\n #self.update_comm_list(None)\n\n '''#;lkj somehow this was here uncommented before\n # Uses Listbox\n def populate_device_list(self, capture=None, append=False):\n # clear previous list\n if not append:\n self.dev_list.delete(0,tk.END)\n self.dev_list.insert(tk.END, \"All...\")\n\n # Get and insert all captures currently added to database\n if capture == None:\n self.db_handler.db.select_devices()\n else:\n self.db_handler.db.select_devices_from_cap(capture)\n\n for (id, mfr, model, mac_addr, internalName, deviceCategory, mudCapable, wifi, bluetooth,\n G3, G4, G5, zigbee, zwave, otherProtocols, notes) in self.db_handler.db.cursor:\n device_list = self.dev_list.get(0, tk.END)\n\n self.dev_list.insert(tk.END, [mfr, model, mac_addr, internalName])\n\n # Set focus on the first element\n self.dev_list.focus(0)\n self.dev_list.selection_set(0)\n '''\n \n # Uses Treeview\n def populate_device_list(self, capture=None, append=False):\n # clear previous list\n if not append:\n self.dev_list.clear()\n self.dev_list.append((\"All...\",))\n\n # Get and insert all captures currently added to database\n if capture == None:\n self.db_handler.db.select_devices()\n else:\n self.db_handler.db.select_devices_from_cap(capture)\n \n\n for (id, mfr, model, mac_addr, internalName, deviceCategory, mudCapable, wifi, ethernet, bluetooth,\n G3, G4, G5, zigbee, zwave, otherProtocols, notes, unidentified) in self.db_handler.db.cursor:\n self.dev_list.append_unique((mfr, model, internalName, mac_addr, deviceCategory)) #for early stages\n\n self.dev_list.focus(0)\n self.dev_list.selection_set(0)\n \n #:LKJ\n #self.populate_comm_list(None)\n\n\n def update_comm_list(self, event):\n first = True\n\n\n self.populate_comm_list()\n return\n\n\n\n #for dev in self.dev_list.curselection():\n for dev in self.dev_list.selection():\n cap_details = self.cap_list.get(cap)\n cap_date = cap_details[0]\n dev_name = self.dev_list.get(dev)\n\n # To simplify debugging\n print(\"\\nin update_comm_list\")\n\n if type(dev_name) is str:\n print(\"dev = \" + dev_name)\n else:\n print(\"dev = \" + str(dev_name[0]))\n if dev_name == \"All...\":\n print(\"Processing \\'All...\\'\")\n #self.populate_comm_list(dev_name)\n #self.populate_comm_list(\"*\")\n self.populate_comm_list(append=(not first))\n break\n else:\n #self.populate_comm_list(dev_name, not first)\n self.populate_comm_list(append=(not first))\n first=False\n\n\n def import_packets(self, cap):\n '''\n for p in cap.pkt:\n pkt_data = {\"fileHash\":cap.fileHash,\n \"mac\":a,\n \"src\":b,\n \"dest\":c,\n \"protocol\":d,\n \"length\":e,\n \"direction\":f,\n \"raw\":p}\n self.db_handler.db.insert_packets(pkt_data)\n\n '''\n print(\"In import_packets\")\n h = {\"fileHash\" : cap.fileHash}\n for p in cap.pkt_info:\n #print(\"pre update:\", p)\n p.update(h)\n #print(\"post update:\", p)\n self.db_handler.db.insert_packet( p )\n\n self.populate_comm_list()\n\n #;lkj\n #def populate_comm_list(self, device, append=False):\n def populate_comm_list(self, append=False):\n # Clear previous list\n if not append:\n #self.comm_list.delete(0,tk.END)\n self.comm_list.clear()\n self.db_handler.db.drop_cap_toi()\n self.db_handler.db.drop_dev_toi()\n self.db_handler.db.drop_pkt_toi()\n first = True\n else:\n first = False\n\n print(\"\\nPopulate Comm List\")\n \n # Selecting based on cap list\n first = True\n for cap in self.cap_list.selection():\n cap_details = self.cap_list.get(cap)\n cap_date = cap_details[0]\n\n if cap_date == \"All...\":\n #self.populate_device_list()\n print(\"All Captures\")\n self.db_handler.db.create_cap_toi()\n break\n else:\n cap_name = cap_details[1] #{'fileName':cap_name}\n print(cap_name)\n capture = {'fileName':cap_name}\n if first:\n # Create packet table of interest\n self.db_handler.db.create_pkt_toi(capture)\n\n self.db_handler.db.create_cap_toi(capture)\n first=False\n else:\n # Update packet table of interest\n self.db_handler.db.update_pkt_toi(capture)\n\n self.db_handler.db.update_cap_toi(capture)\n \n\n\n # Selecting based on dev list\n first = True\n for dev in self.dev_list.selection():\n dev_details = self.dev_list.get(dev)\n\n print(dev_details)\n\n print(\"dev =\", dev_details[0])\n dev_name = dev_details[0]\n\n if dev_name == \"All...\":\n print(\"No device restrictions\")\n # Create dev_toi\n self.db_handler.db.create_dev_toi()\n break\n else:\n print(\"mac =\", dev_details[3])\n dev_mac = dev_details[3]\n mac = {'mac_addr':dev_mac}\n if first:\n self.db_handler.db.create_dev_toi(mac)\n else:\n self.db_handler.db.update_dev_toi(mac)\n\n # Update dev_toi\n #self.populate_comm_list(dev_name, not first)\n #self.populate_comm_list(append=(not first))\n first=False\n\n\n\n # Selecting based on E/W or N/S\n if self.comm_state == \"any\":\n ew = {\"ew\":\"(TRUE OR FALSE)\"}\n elif self.comm_state == \"ns\":\n ew = {\"ew\":False}\n elif self.comm_state == \"ew\":\n ew = {\"ew\":True}\n '''\n if self.comm_state == \"any\":\n pass\n elif self.comm_state == \"ns\":\n pass\n elif self.comm_state == \"ew\":\n pass\n '''\n # Selecting based on restriction\n '''\n if self.comm_dev_restriction == \"none\":\n pass\n elif self.comm_dev_restriction == \"between\":\n pass\n elif self.comm_dev_restriction == \"either\":\n pass\n '''\n\n # Get files from tables of interest\n self.db_handler.db.select_pkt_toi(ew)\n\n\n # Get and insert all captures currently added to database\n #######self.db_handler.db.select_packets()\n\n # might be interesting to include destination URL and NOTES\n # Limiting version for debugging at least\n #self.comm_list_num_pkts = 100\n self.comm_list_all_pkts = self.db_handler.db.cursor\n\n\n #for (i, (id, fileHash, pkt_datetime, pkt_epochtime, mac_addr, protocol, ip_ver, ip_src, ip_dst,\n # ew, tlp, tlp_srcport, tlp_dstport, pkt_length)) in enumerate(self.db_handler.db.cursor): \n\n\n\n #for (i, (id, fileHash, pkt_datetime, pkt_epochtime, mac_addr, protocol, ip_ver, ip_src, ip_dst,\n # ew, tlp, tlp_srcport, tlp_dstport, pkt_length)) in enumerate(self.comm_list_all_pkts): \n\n\n\n i = 0\n for (id, fileHash, pkt_datetime, pkt_epochtime, mac_addr, protocol, ip_ver, ip_src, ip_dst,\n ew, tlp, tlp_srcport, tlp_dstport, pkt_length) in self.comm_list_all_pkts: \n #self.comm_list.insert(tk.END, [pkt_time, mac_addr, ip_ver, ip_src, ip_dst, ew, \n # protocol, tlp, tlp_srcport, tlp_dstport, pkt_length])\n\n \n \n self.comm_list.append_unique((pkt_datetime, mac_addr, ip_ver, ip_src, ip_dst, ew, \n protocol, tlp, tlp_srcport, tlp_dstport, pkt_length))\n \n i+=1\n\n '''\n # Temporary solution: ********************\n if self.comm_state == \"any\":\n self.comm_list.append_unique((pkt_datetime, mac_addr, ip_ver, ip_src, ip_dst, ew, \n protocol, tlp, tlp_srcport, tlp_dstport, pkt_length))\n i += 1\n elif self.comm_state == \"ew\":\n if ew:\n self.comm_list.append_unique((pkt_datetime, mac_addr, ip_ver, ip_src, ip_dst, ew, \n protocol, tlp, tlp_srcport, tlp_dstport, pkt_length))\n i += 1\n elif self.comm_state == \"ns\":\n if not ew:\n self.comm_list.append_unique((pkt_datetime, mac_addr, ip_ver, ip_src, ip_dst, ew, \n protocol, tlp, tlp_srcport, tlp_dstport, pkt_length))\n i += 1\n '''\n if i >= self.comm_list_num_pkts: \n break\n\n '''\n for (id, fileHash, pkt_datetime, pkt_epochtime, mac_addr, protocol, ip_ver, ip_src, ip_dst,\n ew, tlp, tlp_srcport, tlp_dstport, pkt_length) in self.db_handler.db.cursor: \n #self.comm_list.insert(tk.END, [pkt_time, mac_addr, ip_ver, ip_src, ip_dst, ew, \n # protocol, tlp, tlp_srcport, tlp_dstport, pkt_length])\n self.comm_list.append_unique((pkt_datetime, mac_addr, ip_ver, ip_src, ip_dst, ew, \n protocol, tlp, tlp_srcport, tlp_dstport, pkt_length))\n '''\n '''\n self.db_handler.db.select_device_communication(device)\n \n for (id, fileHash, pkt_time, mac_addr, protocol, ip_ver, ip_src, ip_dst,\n tlp, tlp_srcport, tlp_dstport, pkt_length, raw) in self.db_handler.db.cursor: # might be interesting to include destination URL and NOTES\n self.comm_list.insert(tk.END, [pkt_time, mac_addr, ip_ver, ip_src, ip_dst, protocol, tlp, tlp_srcport, tlp_dstport, pkt_length, raw])\n '''\n '''\n for (id, fileHash, mac_addr, protocol, src_port, dst_ip_addr, ipv6, dst_url,\n dst_port, notes) in self.db_handler.db.cursor:\n self.comm_list.insert(tk.END, [protocol, src_port, dst_ip_addr, ipv6, dst_url, dst_port, notes])\n '''\n # Set focus on the first element\n #self.comm_list.select_set(0)\n #self.comm_list.event_generate(\"<>\")\n self.comm_list.focus(0)\n self.comm_list.selection_set(0)\n\n\n def modify_comm_state(self, button):\n print(\"button:\",button)\n # Check current filter\n if self.comm_state == \"any\":\n if button == \"ns\":\n self.comm_state = \"ns\"\n elif button == \"ew\":\n self.comm_state = \"ew\"\n else:\n print(\"Something went wrong with modifying the communication state\")\n elif self.comm_state == \"ns\":\n if button == \"ns\":\n self.comm_state = \"any\"\n elif button == \"ew\":\n self.comm_state = \"ew\"\n else:\n print(\"Something went wrong with modifying the communication state\")\n elif self.comm_state == \"ew\":\n if button == \"ns\":\n self.comm_state = \"ns\"\n elif button == \"ew\":\n self.comm_state = \"any\"\n else:\n print(\"Something went wrong with modifying the communication state\")\n else:\n print(\"Something went wrong with modifying the communication state\")\n\n # Update the filter\n if self.comm_state == \"any\":\n self.b_ns.config(fg = \"black\")\n self.b_ew.config(fg = \"black\")\n #update communication table view\n elif self.comm_state == \"ns\":\n self.b_ns.config(fg = \"green\")\n self.b_ew.config(fg = \"red\")\n #update communication table view\n elif self.comm_state == \"ew\":\n self.b_ns.config(fg = \"red\")\n self.b_ew.config(fg = \"green\")\n #update communication table view\n else:\n print(\"Something went wrong with modifying the communication state\")\n\n print(\"comm_state:\", self.comm_state)\n self.populate_comm_list()\n\n\n def modify_comm_num_pkts(self, num_pkts):\n print(\"number of packets:\", num_pkts)\n self.comm_list_num_pkts = num_pkts\n\n if num_pkts == 10:\n self.b_pkt10.config(state='disabled')\n self.b_pkt100.config(state='normal')\n self.b_pkt1000.config(state='normal')\n self.b_pkt10000.config(state='normal')\n elif num_pkts == 100:\n self.b_pkt10.config(state='normal')\n self.b_pkt100.config(state='disabled')\n self.b_pkt1000.config(state='normal')\n self.b_pkt10000.config(state='normal')\n pass\n elif num_pkts == 1000:\n self.b_pkt10.config(state='normal')\n self.b_pkt100.config(state='normal')\n self.b_pkt1000.config(state='disabled')\n self.b_pkt10000.config(state='normal')\n elif num_pkts == 10000:\n self.b_pkt10.config(state='normal')\n self.b_pkt100.config(state='normal')\n self.b_pkt1000.config(state='normal')\n self.b_pkt10000.config(state='disabled')\n else:\n print(\"unidentified value for modify_comm_num_pkts\")\n \n self.populate_comm_list()\n\n\n def modify_comm_dev_restriction(self, r_button):\n print(\"comm_dev_restriction: \",self.comm_dev_restriction)\n print(\"communication device restriction:\", r_button)\n\n if self.comm_dev_restriction == \"none\":\n if r_button == \"between\":\n self.comm_dev_restriction = \"between\"\n elif r_button == \"either\":\n self.comm_dev_restriction = \"either\"\n else:\n print(\"Something went wrong with modifying the communication device restriction\")\n elif self.comm_dev_restriction == \"between\":\n if r_button == \"between\":\n self.comm_dev_restriction = \"none\"\n elif r_button == \"either\":\n self.comm_dev_restriction = \"either\"\n else:\n print(\"Something went wrong with modifying the communication device restriction\")\n elif self.comm_dev_restriction == \"either\":\n if r_button == \"between\":\n self.comm_dev_restriction = \"between\"\n elif r_button == \"either\":\n self.comm_dev_restriction = \"none\"\n else:\n print(\"Something went wrong with modifying the communication device restriction\")\n else:\n print(\"Something went wrong with modifying the communication device restriction\")\n\n # Update the filter\n if self.comm_dev_restriction == \"none\":\n self.b_between.config(fg = \"black\")\n self.b_either.config(fg = \"black\")\n #update communication table view\n elif self.comm_dev_restriction == \"between\":\n self.b_between.config(fg = \"green\")\n self.b_either.config(fg = \"red\")\n #update communication table view\n elif self.comm_dev_restriction == \"either\":\n self.b_between.config(fg = \"red\")\n self.b_either.config(fg = \"green\")\n #update communication table view\n else:\n print(\"Something went wrong with modifying the communication device restriction\")\n\n \n print(\"comm_dev_restriction:\", self.comm_dev_restriction)\n self.populate_comm_list()\n\n def popup_internal_addr_list(self):\n # Currently not functional... Needs to be worked out\n pass\n \n self.w_internal_addr = tk.Toplevel()\n\n self.w_internal_addr.wm_title(\"Internal Address Ranges\")\n\n topFrame = tk.Frame(self.w_internal_addr, bd=1, bg=\"#eeeeee\")#, bg=\"#dfdfdf\")\n subtitle = tk.Label(topFrame, text=\"Current Address Ranges\", bg=\"#eeeeee\", bd=1, relief=\"flat\")\n subtitle.pack(side=\"top\", fill=tk.X)\n\n botFrame = tk.Frame(elf.w_internal_addr, width=300, bd=1, bg=\"#eeeeee\")#, bg=\"#dfdfdf\")\n\n addr_range_list_header = [\"Lower Bound\", \"Upper Bound\", \"IP Version\"]\n addr_range_list = MultiColumnListbox(parent=botFrame,\n header=addr_range_list_header,\n list=list(), selectmode=\"browse\")\n #To be aded later\n #self.unidentified_dev_list.bind(\"<>\", self.update_unidentified_list_selection)\n\n\n # Grid placements #\n #self.topDevFrame.grid(row=0, column=0, sticky=\"new\")\n #self.botDevFrame.grid(row=1, column=0, sticky=\"nsew\")\n topFrame.grid(row=0, column=0, sticky=\"new\")\n botFrame.grid(row=1, column=0, sticky=\"nsew\")\n\n # Grid configuration #\n '''\n self.topFrame.grid_columnconfigure(0, weight=0)\n self.botDevFrame.grid_rowconfigure(1, weight=1)\n self.botDevFrame.grid_columnconfigure(0, weight=1)\n self.botDevFrame.grid_columnconfigure(1, weight=1)\n\n self.w_cap_dev.grid_rowconfigure(1, weight=1)\n self.w_cap_dev.grid_columnconfigure(0, weight=1)\n '''\n\n # Buttons #\n self.b_internal_addr_close = tk.Button(botFrame, text='Close', command=self.w_internal_addr.destroy)\n self.b_internal_addr_new = tk.Button(botFrame, text='+', command=self.popup_internal_addr)\n #TO BE COMPLETED\n self.b_internal_addr_modify = tk.Button(botFrame, text='Modify', state='disabled',\n command=(lambda d=self.identified_dev_list.get_selected_row(): self.prep_popup_update_device_state(d)))\n\n self.b_internal_addr_close.pack(side=tk.LEFT, padx=5, pady=5)\n self.b_internal_addr_new.pack(side=tk.RIGHT, padx=5, pady=5)\n self.b_internal_addr_modify.pack(side=tk.RIGHT, padx=5, pady=5)\n\n self.yield_focus(self.w_internal_addr)\n\n\n\n\n\n\n # Not yet implemented\n '''\n def populate_string_list(self, device, append=False):\n # clear previous list\n if not append:\n self.string_list.delete(0,tk.END)\n\n # Get and insert all captures currently added to database\n self.db_handler.db.select_device_communication(device)\n\n for (id, ...) in self.db_handler.db.cursor:\n self.string_list.insert(tk.END, [protocol, src_port, dst_ip_addr, ipv6, dst_url, dst_port, notes])\n\n def update_string_list(self):\n print(\"update_comm_list will do something eventually\")\n\n ''' \n\n '''\n def generate_MUD_wizard(self):\n #print(\"You shouldn't have gotten to the generate MUD wizard yet\")\n\n self.w_gen_mud = tk.Toplevel()\n self.w_gen_mud.wm_title('Generate MUD File Wizard')\n\n # Prompt for selecting the device\n prompt_row = tk.Frame(self.w_gen_mud)\n prompt_row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)\n\n dev_select_label = tk.Label(prompt_row, width=45, text=\"Please select the device you would like to profile:\", anchor='w')\n dev_select_label.pack(side=tk.LEFT)\n\n\n list_row = tk.Frame(self.w_gen_mud)\n list_row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)\n\n self.mud_dev_header = [\"Manufacturer\", \"Model\", \"Internal Name\", \"Category\", \"MAC\"]#, \"IPv4\", \"IPv6\"]\n #self.mud_dev_list = MultiColumnListbox(parent=self.mudDevFrame,\n self.mud_dev_list = MultiColumnListbox(parent=list_row,\n header=self.mud_dev_header,\n list=list(), selectmode=\"browse\")\n self.mud_dev_list.bind(\"<>\", self.update_mud_device_selection)\n\n #self.w_gen_mud.bind('', (lambda event, n=internalName, m=mac: self.select_mud_dev(n, m)))\n self.w_gen_mud.bind('', (lambda event : self.select_mud_dev()))\n \n b_select = tk.Button(self.w_gen_mud, text='select',\n #command=(lambda n=internalName, m=mac: self.select_mud_dev(n, m)))\n command=(self.select_mud_dev()))\n\n b_cancel = tk.Button(self.w_gen_mud, text='Cancel', command=self.w_gen_mud.destroy)\n\n if sys.platform == \"win32\":\n b_cancel.pack(side=tk.RIGHT, padx=5, pady=5)\n b_select.pack(side=tk.RIGHT, padx=5, pady=5)\n else:\n b_select.pack(side=tk.RIGHT, padx=5, pady=5)\n b_cancel.pack(side=tk.RIGHT, padx=5, pady=5)\n\n self.populate_mud_dev_list()\n\n self.yield_focus(self.w_gen_mud)\n \n '''\n\n def select_mud_dev(self):\n pass\n\n\n\n\n\n\n\n\n def popup_generate_mud_wizard(self):\n self.w_gen_mud = tk.Toplevel()\n self.w_gen_mud.wm_title('Generate MUD File Wizard')\n\n\n #Frames for Device, Gateway, and PCAPs\n self.topMudDevFrame = tk.Frame(self.w_gen_mud, width=300, bd=1, bg=\"#eeeeee\")#, bg=\"#dfdfdf\")\n self.midMudGateFrame = tk.Frame(self.w_gen_mud, width=300, bd=1, bg=\"#eeeeee\")#, bg=\"#dfdfdf\")\n self.botMudPCAPFrame = tk.Frame(self.w_gen_mud, width=300, bd=1, bg=\"#eeeeee\")#, bg=\"#dfdfdf\")\n\n ## Top Device Frame\n #dev_select_label = tk.Label(self.topDevFrame, width=20, text=\"Select the device to profile:\", anchor='w')\n #dev_select_label.pack(side=tk.LEFT)\n\n #self.cap_dev_title = tk.Label(self.botDevFrame, text=\"Devices\", bg=\"#dfdfdf\", bd=1, relief=\"flat\", anchor=\"n\")\n\n self.mud_dev_title_var=tk.StringVar()\n self.mud_dev_title_var.set(\"Device to Profile:\")\n self.mud_dev_title = tk.Label(self.topMudDevFrame, textvariable=self.mud_dev_title_var,\n bg=\"#eeeeee\", bd=1, relief=\"flat\")\n self.mud_dev_title.pack(side=\"top\", fill=tk.X)\n\n #self.mud_dev_header = [\"Manufacturer\", \"Model\", \"MAC Address\", \"Internal Name\", \"Category\"]\n self.mud_dev_header = [\"Internal Name\", \"Manufacturer\", \"Model\", \"MAC Address\", \"Category\"]\n self.mud_dev_list = MultiColumnListbox(parent=self.topMudDevFrame,\n header=self.mud_dev_header,\n list=list(), selectmode=\"browse\")\n #unidentified_list_selection\n #self.mud_dev_list.bind(\"<>\", self.update_gateway_list_selection)\n self.mud_dev_list.bind(\"<>\", self.populate_mud_gate_list)\n\n\n\n ## Middle Gateway Frame\n self.mud_gate_title_var=tk.StringVar()\n self.mud_gate_title_var.set(\"Network Gateway:\")\n self.mud_gate_title = tk.Label(self.midMudGateFrame, textvariable=self.mud_gate_title_var,\n bg=\"#eeeeee\", bd=1, relief=\"flat\")\n self.mud_gate_title.pack(side=\"top\", fill=tk.X)\n\n self.mud_gate_header = [\"Internal Name\", \"Manufacturer\", \"Model\", \"Category\",\n \"MAC Address\", \"IPv4\", \"IPv6\"]\n self.mud_gate_list = MultiColumnListbox(parent=self.midMudGateFrame,\n header=self.mud_gate_header,\n list=list(), selectmode=\"browse\")\n #identified_list_selection\n #self.mud_gate_list.bind(\"<>\", self.update_pcap_list_selection)\n self.mud_gate_list.bind(\"<>\", self.populate_mud_pcap_list)\n\n\n\n ## Bot PCAP Frame\n self.mud_pcap_title_var=tk.StringVar()\n self.mud_pcap_title_var.set(\"Select Packet Captures (PCAPs):\")\n self.mud_pcap_title = tk.Label(self.botMudPCAPFrame, textvariable=self.mud_pcap_title_var,\n bg=\"#eeeeee\", bd=1, relief=\"flat\")\n self.mud_pcap_title.pack(side=\"top\", fill=tk.X)\n\n\n self.mud_pcap_header = [\"Date\", \"Capture Name\", \"Activity\", \"Duration (seconds)\", \"Details\",\n \"Capture File Location\"]\n #self.mud_pcap_header = [\"Date\",\"Capture Name\",\"Activity\", \"Details\",\"Capture File Location\"]\n self.mud_pcap_list = MultiColumnListbox(parent=self.botMudPCAPFrame,\n header=self.mud_pcap_header,\n list=list(), keep1st=True)\n #identified_list_selection\n self.mud_pcap_list.bind(\"<>\", self.select_mud_pcaps)\n\n\n\n # Grid placements #\n self.topMudDevFrame.grid(row=0, column=0, sticky=\"nsew\") #new\n self.midMudGateFrame.grid(row=1, column=0, sticky=\"nsew\")\n self.botMudPCAPFrame.grid(row=2, column=0, sticky=\"nsew\")\n\n\n # Grid configuration #\n #self.topMudDevFrame.grid_rowconfigure(0, weight=1)\n #self.midMudGateFrame.grid_rowconfigure(1, weight=1)\n #self.botMudPCAPFrame.grid_rowconfigure(2, weight=1)\n\n\n self.w_gen_mud.grid_rowconfigure(0, weight=1)\n self.w_gen_mud.grid_rowconfigure(1, weight=1)\n self.w_gen_mud.grid_rowconfigure(2, weight=1)\n\n\n self.b_mud_generate = tk.Button(self.botMudPCAPFrame, text='Generate', state='disabled',\n #command=(lambda n=internalName, m=mac: self.select_mud_dev(n, m)))\n #command=(self.select_mud_dev()))\n command=(self.generate_mud_file))\n\n self.b_mud_cancel = tk.Button(self.botMudPCAPFrame, text='Cancel', command=self.w_gen_mud.destroy)\n\n if sys.platform == \"win32\":\n self.b_mud_cancel.pack(side=tk.RIGHT, padx=5, pady=5)\n self.b_mud_generate.pack(side=tk.RIGHT, padx=5, pady=5)\n else:\n self.b_mud_generate.pack(side=tk.RIGHT, padx=5, pady=5)\n self.b_mud_cancel.pack(side=tk.RIGHT, padx=5, pady=5)\n\n\n\n\n\n # Update unidentified, identified lists and try to select the first element\n #self.refresh_mud_lists()\n self.populate_mud_dev_list()\n\n\n # Select first element of each list\n # Try becuase the list might be empty\n self.mud_dev_list.focus(0)\n self.mud_dev_list.selection_set(0)\n self.mud_gate_list.focus(0)\n self.mud_gate_list.selection_set(0)\n self.mud_pcap_list.focus(0)\n self.mud_pcap_list.selection_set(0)\n\n self.yield_focus(self.w_gen_mud)\n\n\n\n def select_mud_pcaps(self, event):\n print(\"Select MUD pcaps\")\n self.mud_pcap_sel = []\n\n print(\"mud_pcap_list.selection():\",self.mud_pcap_list.selection())\n\n #print(\"self.mud_pcap_list.get( self.mud_pcap_list.selection() ):\", self.mud_pcap_list.get( self.mud_pcap_list.selection() ))\n\n for pcap_item in self.mud_pcap_list.selection():\n pcap = self.mud_pcap_list.get( pcap_item )\n print(\"pcap:\",pcap)\n\n if pcap[0] == \"All...\":\n self.db_handler.db.select_imported_captures_with({\"dev_mac\":self.dev_mac, \"gateway_mac\":self.gateway_mac})\n #for (id, fileName, fileLoc, fileHash, capDate, activity, details) in self.db_handler.db.cursor:\n\n for (id, fileName, fileLoc, fileHash, capDate, capDuration, lifecyclePhase,\n internet, humanInteraction, preferredDNS, isolated, durationBased,\n duration, actionBased, deviceAction, details) in self.db_handler.db.cursor:\n self.mud_pcap_sel.append(fileLoc + \"/\" + fileName)\n #for (id, fileName, fileLoc, fileHash, capDate, duration, activity, details) in self.db_handler.db.cursor:\n # self.mud_pcap_sel.append(fileLoc + \"/\" + fileName)\n break\n else:\n self.mud_pcap_sel.append(pcap[4] + pcap[1])\n\n #for pcap in self.mud_pcap_list.get( self.mud_pcap_list.selection() ):\n # print(\"pcap:\",pcap)\n # self.mud_pcap_sel.append(pcap[4] + pcap[1])\n\n self.b_mud_generate.config(state='normal')\n\n\n def generate_mud_file(self):#, event):\n print(\"Preparing to generate mud file\")\n self.mud_gen_obj = MUDgeeWrapper()\n\n \n self.mud_gen_obj.set_device(mac=self.mud_device[3], name=self.mud_device[2])\n #self.mud_config = MUDgeeWrapper({'device_config':{'device':mac, 'deviceName':internalName}})\n\n\n self.db_handler.db.select_gateway_ips({'gateway_mac':self.gateway_mac})\n\n ip = None\n ipv6 = None\n\n for (ipv4_addr, ipv6_addr) in self.db_handler.db.cursor:\n print(\"ipv4_addr:\",ipv4_addr)\n print(\"ipv4:\",ip)\n print(\"ipv6_addr:\",ipv6_addr)\n print(\"ipv6:\",ipv6)\n\n if (ip != None and ip != ipv4_addr):\n if ip == \"Not found\" or ip == \"0.0.0.0\":\n if ipv4 != \"Not found\" and ipv4 != \"0.0.0.0\":\n ip = ipv4_addr\n else:\n messagebox.showerror(\"MUD Gateway Selection Error\",\n \"The selected gateway appears to have either multiple IPv4 addresses or IPv6 addresses!\")\n return\n else:\n ip = ipv4_addr\n \n if (ipv6 != None and ipv6 != ipv6_addr):\n if ipv6 == \"Not found\" or ipv6 == \"::\":\n if ipv6_addr != \"Not found\" and ipv6_addr != \"::\":\n ipv6 = ipv6_addr\n else:\n messagebox.showerror(\"MUD Gateway Selection Error\",\n \"The selected gateway appears to have either multiple IPv4 addresses or IPv6 addresses!\")\n return\n else:\n ipv6 = ipv6_addr\n\n if (ip == \"Not found\" or ip == \"0.0.0.0\"):\n if (ipv6 == \"Not found\" or ipv6 == \"::\"):\n messagebox.showwarning(\"MUD Gateway Selection Warning\",\n \"The selected gateway does not have valid IPv4 or IPV6 addresses.\")\n else:\n messagebox.showwarning(\"MUD Gateway Selection Warning\",\n \"The selected gateway does not have a valid IPv4 address.\")\n #return\n elif (ipv6 == \"Not found\" or ipv6 == \"::\"):\n messagebox.showwarning(\"Problem with MUD Gateway Selection\",\n \"The selected gateway does not have a valid IPv6 address.\")\n #return\n\n\n #self.mud_gate_list.append((mfr, model, internalName, category, mac))\n\n\n self.mud_gen_obj.set_gateway(mac=self.mud_gateway[4], ip=ip, ipv6=ipv6)\n\n #pcap_list = self.mud_pcap_sel\n\n #self.mud_gen_obj.gen_mudfile(pcap_list)\n print(\"Generating MUD file\")\n self.mud_gen_obj.gen_mudfile(self.mud_pcap_sel)\n messagebox.showinfo(\"MUD File Generation Complete\", \"The generated MUD file is in the 'mudfiles' directory.\")\n\n\n\n def populate_mud_dev_list(self):\n # Get and insert all captures currently added to database\n self.mud_dev_list.clear()\n print(\"Populating MUD Device List\")\n self.db_handler.db.select_devices_imported()\n\n for (id, mfr, model, mac, internalName, category) in self.db_handler.db.cursor:\n self.mud_dev_list.append((internalName, mfr, model, mac, category))\n #self.mud_dev_list.append(internalName + ' | ' + mac)\n\n #self.gate_select_list = tk.OptionMenu(self.row_gate, self.mud_gate_var, *self.mud_gate_list)\n #self.gate_select_list.pack(side=tk.LEFT)\n\n def populate_mud_gate_list(self, event=None):#, ignored_dev = None):\n print(\"Populating MUD Gateway list\")\n self.mud_gate_list.clear()\n #self.mud_gate_list.append(('--',))\n \n #device = self.mud_dev_list.get_selected_row()\n self.mud_device = self.mud_dev_list.get( self.mud_dev_list.selection() )\n print(\"device:\",self.mud_device)\n #ignored_dev = self.mud_device[4]\n self.dev_mac = self.mud_device[3]\n print(\"self.dev_mac:\")\n print(\"\\t\",self.dev_mac)\n\n \n\n #if (ignored_dev == '--'):\n if (self.dev_mac == None):\n print(\"Returning from gate selection early\")\n return\n\n # Get and insert all captures currently added to database\n self.db_handler.db.select_devices_imported_ignore({'ignored_dev':self.dev_mac})\n\n for (id, mfr, model, mac, internalName, category, ipv4, ipv6) in self.db_handler.db.cursor:\n self.mud_gate_list.append((internalName, mfr, model, category, mac, ipv4, ipv6))\n #self.mud_gate_list.append(internalName + ' | ' + mac)\n #print(\"\\t\" + internalName + ' | ' + mac)\n # Set focus on the first element\n\n self.mud_gate_list.focus(0)\n self.mud_gate_list.selection_set(0)\n\n self.populate_mud_pcap_list()#'--','--')\n\n\n\n def populate_mud_pcap_list(self, event=None):#, device=None, gateway=None):\n print(\"Populating MUD PCAP list\")\n\n # clear previous list\n self.mud_pcap_list.clear()\n \n\n self.mud_device = self.mud_dev_list.get( self.mud_dev_list.selection() )\n self.dev_mac = self.mud_device[3]\n\n self.mud_gateway = self.mud_gate_list.get( self.mud_gate_list.selection() )\n self.gateway_mac = self.mud_gateway[4]\n\n print(\"device:\",self.dev_mac)\n print(\"gateway:\",self.gateway_mac)\n\n if self.dev_mac == None or self.gateway_mac == None:\n print(\"Returning from mud pcap selection early\")\n return\n self.mud_pcap_list.append((\"All...\",))\n\n # Get and insert all captures currently added to database\n #self.db_handler.db.select_imported_captures_with(dev='', gate='')\n self.db_handler.db.select_imported_captures_with({\"dev_mac\":self.dev_mac, \"gateway_mac\":self.gateway_mac})\n\n for (id, fileName, fileLoc, fileHash, capDate, capDuration, lifecyclePhase,\n internet, humanInteraction, preferredDNS, isolated, durationBased,\n duration, actionBased, deviceAction, details) in self.db_handler.db.cursor:\n self.mud_pcap_list.append((capDate, fileName, deviceAction, duration, details, fileLoc)) #for early stages\n\n #for (id, fileName, fileLoc, fileHash, capDate, duration, activity, details) in self.db_handler.db.cursor:\n # self.mud_pcap_list.append((capDate, fileName, activity, duration, details, fileLoc)) #for early stages\n \n # Set focus on the first element\n self.mud_pcap_list.focus(0)\n self.mud_pcap_list.selection_set(0)\n\n\n\n\n\n\n\n ## OLD ATTEMPT ##\n '''\n def generate_MUD_wizard_dropdown(self):\n #print(\"You shouldn't have gotten to the generate MUD wizard yet\")\n\n self.w_gen_mud = tk.Toplevel()\n self.w_gen_mud.wm_title('Generate MUD File Wizard')\n\n # Prompt for selecting the device\n self.row_dev = tk.Frame(self.w_gen_mud)\n self.row_dev.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)\n\n dev_select_label = tk.Label(self.row_dev, width=20, text=\"Select the device to profile:\", anchor='w')\n dev_select_label.pack(side=tk.LEFT)\n\n # Prompt for selecting the gateway\n self.row_gate = tk.Frame(self.w_gen_mud)\n self.row_gate.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)\n\n gate_select_label = tk.Label(self.row_gate, width=20, text=\"Select the network gateway:\", anchor='w')\n gate_select_label.pack(side=tk.LEFT)\n\n \n\n self.mud_gate_list = ['--']\n self.mud_gate_var = tk.StringVar(self.w_gen_mud)\n self.mud_gate_var.set(self.mud_gate_list[0])\n\n\n #Device\n self.populate_mud_dev_list()\n\n self.mud_dev_var = tk.StringVar(self.w_gen_mud)\n self.mud_dev_var.set(self.mud_dev_list[0])\n\n #row_dropdown_device = tk.Frame(self.w_gen_mud)\n #row_dropdown_device.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)\n\n\n #dev_select_dropdown = tk.OptionMenu(row_dropdown_device, mud_dev_var, *self.mud_dev_list)\n self.dev_select_dropdown = tk.OptionMenu(self.row_dev, self.mud_dev_var, *self.mud_dev_list)\n self.dev_select_dropdown.pack(side=tk.LEFT)\n\n\n\n #Gateway\n\n #self.populate_mud_gate_list()\n\n #self.mud_gate_var = tk.StringVar(self.w_gen_mud)\n #self.mud_gate_var.set(self.mud_gate_list[0])\n\n #gate_select_dropdown = tk.OptionMenu(row_gate, mud_gate_var, *self.mud_gate_list)\n #gate_select_dropdown.pack(side=tk.LEFT)\n\n\n def change_dev(*args):\n print(\"Device Changed\")\n print(self.mud_dev_var.get())\n self.populate_mud_gate_list(ignored_dev=self.mud_dev_var.get().split(' | ')[-1])\n print(\"Mac =\", self.mud_dev_var.get().split(' | ')[-1])\n\n #mud_gate_var = tk.StringVar(self.w_gen_mud)\n #mud_gate_var.set(self.mud_dev_list[0])\n\n #gate_select_dropdown = tk.OptionMenu(row_gate, mud_gate_var, *self.mud_gate_list)\n #gate_select_dropdown.pack(side=tk.LEFT)\n\n self.mud_dev_var.trace('w', change_dev)\n\n def change_gate(*args):\n print(self.mud_gate_var.get())\n self.populate_mud_pcap_list(self.mud_dev_var.get().split(' | ')[-1],\n self.mud_gate_var.get().split(' | ')[-1])\n\n self.mud_gate_var.trace('w', change_gate)\n\n '''\n\n '''\n list_row = tk.Frame(self.w_gen_mud)\n list_row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)\n\n self.mud_dev_header = [\"Manufacturer\", \"Model\", \"Internal Name\", \"Category\", \"MAC\"]#, \"IPv4\", \"IPv6\"]\n #self.mud_dev_list = MultiColumnListbox(parent=self.mudDevFrame,\n self.mud_dev_list = MultiColumnListbox(parent=list_row,\n header=self.mud_dev_header,\n list=list(), selectmode=\"browse\")\n self.mud_dev_list.bind(\"<>\", self.update_mud_device_selection)\n\n #self.w_gen_mud.bind('', (lambda event, n=internalName, m=mac: self.select_mud_dev(n, m)))\n self.w_gen_mud.bind('', (lambda event : self.select_mud_dev()))\n \n '''\n\n '''\n b_select = tk.Button(self.w_gen_mud, text='Select',\n #command=(lambda n=internalName, m=mac: self.select_mud_dev(n, m)))\n command=(self.select_mud_dev()))\n\n b_cancel = tk.Button(self.w_gen_mud, text='Cancel', command=self.w_gen_mud.destroy)\n\n if sys.platform == \"win32\":\n b_cancel.pack(side=tk.RIGHT, padx=5, pady=5)\n b_select.pack(side=tk.RIGHT, padx=5, pady=5)\n else:\n b_select.pack(side=tk.RIGHT, padx=5, pady=5)\n b_cancel.pack(side=tk.RIGHT, padx=5, pady=5)\n\n #self.populate_mud_dev_list()\n\n self.yield_focus(self.w_gen_mud)\n\n\n\n\n\n\n def update_mud_device_selection():\n print(\"update_mud_device_selection\")\n self.mud_dev = {name:\"internalName\", mac:\"mac\"}\n '''\n '''\n def populate_mud_dev_list(self):\n # clear previous list\n self.mud_dev_list.clear()\n\n # Get and insert all captures currently added to database\n self.db_handler.db.select_devices_imported()\n\n for (id, mfr, model, mac, internalName, category) in self.db_handler.db.cursor:\n self.mud_dev_list.append((mfr, model, internalName, category, mac))\n \n # Set focus on the first element\n #self.mud_dev_list.focus(0)\n #self.mud_dev_list.selection_set(0)\n '''\n '''\n def populate_mud_dev_list_dropdown(self):\n self.mud_dev_list = ['--']\n\n # Get and insert all captures currently added to database\n self.db_handler.db.select_devices_imported()\n\n for (id, mfr, model, mac, internalName, category) in self.db_handler.db.cursor:\n #self.mud_dev_list.append((mfr, model, internalName, category, mac))\n self.mud_dev_list.append(internalName + ' | ' + mac)\n\n self.gate_select_dropdown = tk.OptionMenu(self.row_gate, self.mud_gate_var, *self.mud_gate_list)\n self.gate_select_dropdown.pack(side=tk.LEFT)\n '''\n\n '''\n def populate_mud_gateway_list(self):\n # clear previous list\n self.mud_gateway_list.clear()\n\n # Get and insert all captures currently added to database\n self.db_handler.db.select_all_local_devices(ignore='')\n\n for (id, mfr, model, internalName, category, mac) in self.db_handler.db.cursor:\n self.mud_gateway_list.append((mfr, model, internalName, category, mac))\n \n # Set focus on the first element\n self.mud_gateway_list.focus(0)\n self.mud_gateway_list.selection_set(0)\n\n '''\n '''\n def populate_mud_gate_list_dropdown(self, ignored_dev = '--'):\n print(\"Populating mud gate list\")\n self.mud_gate_list = ['--']\n \n if (ignored_dev == '--'):\n print(\"Ignored device:\", ignored_dev)\n print(\"Returning\")\n return\n\n # Get and insert all captures currently added to database\n self.db_handler.db.select_devices_imported_ignore({'ignored_dev':ignored_dev})\n\n for (id, mfr, model, internalName, category, mac) in self.db_handler.db.cursor:\n #self.mud_gateway_list.append((mfr, model, internalName, category, mac))\n self.mud_gate_list.append(internalName + ' | ' + mac)\n print(\"\\t\" + internalName + ' | ' + mac)\n\n\n def populate_mud_pcap_list_dropdown(self, device, gateway):\n # clear previous list\n self.mud_pcap_list.clear()\n self.mud_dev_list.append((\"All...\",))\n\n # Get and insert all captures currently added to database\n self.db_handler.db.select_imported_captures_with(dev='', gateway='')\n\n for (id, fileName, fileLoc, fileHash, capDate, activity, details) in self.db_handler.db.cursor:\n self.cap_list.append((capDate, fileName, activity, details, fileLoc)) #for early stages\n \n # Set focus on the first element\n self.cap_list.focus(0)\n self.cap_list.selection_set(0)\n '''\n\n \n\n def generate_report_wizard(self):\n self.w_gen_report = tk.Toplevel()\n self.w_gen_report.wm_title('Generate Device Report Wizard')\n\n\n #Frames for Device, Gateway, and PCAPs\n self.topReportDevFrame = tk.Frame(self.w_gen_report, width=300, bd=1, bg=\"#eeeeee\")#, bg=\"#dfdfdf\")\n self.botReportPCAPFrame = tk.Frame(self.w_gen_report, width=300, bd=1, bg=\"#eeeeee\")#, bg=\"#dfdfdf\")\n\n\n ## Top Device Frame\n # Title\n self.report_dev_title_var=tk.StringVar()\n self.report_dev_title_var.set(\"Device to Profile:\")\n self.report_dev_title = tk.Label(self.topReportDevFrame, textvariable=self.report_dev_title_var, bg=\"#eeeeee\", bd=1, relief=\"flat\")\n self.report_dev_title.pack(side=\"top\", fill=tk.X)\n\n # Listbox\n self.report_dev_header = [\"Internal Name\", \"Manufacturer\", \"Model\", \"MAC Address\", \"Category\"]\n self.report_dev_list = MultiColumnListbox(parent=self.topReportDevFrame,\n header=self.report_dev_header,\n list=list(), keep1st=True)\n self.report_dev_list.bind(\"<>\", self.populate_report_pcap_list)\n\n\n\n ## Bot PCAP Frame\n # Title\n self.report_pcap_title_var=tk.StringVar()\n self.report_pcap_title_var.set(\"Select Packet Captures (PCAPs):\")\n self.report_pcap_title = tk.Label(self.botReportPCAPFrame, textvariable=self.report_pcap_title_var, bg=\"#eeeeee\", bd=1, relief=\"flat\")\n self.report_pcap_title.pack(side=\"top\", fill=tk.X)\n\n # Listbox\n self.report_pcap_header = [\"Date\",\"Capture Name\",\"Activity\", \"Duration (seconds)\", \"Details\", \"Capture File Location\", \"ID\"]\n #self.report_pcap_header = [\"Date\",\"Capture Name\",\"Activity\", \"Details\", \"Capture File Location\", \"ID\"]\n self.report_pcap_list = MultiColumnListbox(parent=self.botReportPCAPFrame,\n header=self.report_pcap_header,\n list=list(), keep1st=True)\n self.report_pcap_list.bind(\"<>\", self.select_report_pcaps)\n\n\n\n # Grid placements #\n self.topReportDevFrame.grid(row=0, column=0, sticky=\"nsew\")\n self.botReportPCAPFrame.grid(row=1, column=0, sticky=\"nsew\")\n\n self.w_gen_report.grid_rowconfigure(0, weight=1)\n self.w_gen_report.grid_rowconfigure(1, weight=1)\n\n\n ## Buttons\n self.b_report_generate = tk.Button(self.botReportPCAPFrame, text='Generate', state='disabled',\n command=(self.generate_report))\n\n self.b_report_close = tk.Button(self.botReportPCAPFrame, text='Close', command=self.w_gen_report.destroy)\n\n if sys.platform == \"win32\":\n self.b_report_close.pack(side=tk.RIGHT, padx=5, pady=5)\n self.b_report_generate.pack(side=tk.RIGHT, padx=5, pady=5)\n else:\n self.b_report_generate.pack(side=tk.RIGHT, padx=5, pady=5)\n self.b_report_close.pack(side=tk.RIGHT, padx=5, pady=5)\n\n\n self.populate_report_dev_list()\n\n\n # Select first element of each list\n # Try because the list might be empty\n self.report_dev_list.focus(0)\n self.report_dev_list.selection_set(0)\n self.report_pcap_list.focus(0)\n self.report_pcap_list.selection_set(0)\n\n self.yield_focus(self.w_gen_report)\n\n\n def populate_report_dev_list(self):\n # Get and insert all captures currently added to database\n self.report_dev_list.clear()\n self.report_dev_list.append((\"All...\",))\n\n print(\"Populating Report Device List\")\n\n self.db_handler.db.select_devices_imported()\n for (id, mfr, model, mac, internalName, category) in self.db_handler.db.cursor:\n self.report_dev_list.append((internalName, mfr, model, mac, category))\n\n\n def populate_report_pcap_list(self, event=None): #unknown if need \"event\"\n print(\"Populating Report PCAP list\")\n\n # clear previous list\n self.report_pcap_list.clear()\n \n\n self.report_device = self.report_dev_list.get( self.report_dev_list.selection() )\n try:\n self.dev_mac = self.report_device[3]\n except:\n self.dev_mac = None\n\n print(\"device:\",self.dev_mac)\n\n #if self.dev_mac == None:\n # print(\"Returning from report pcap selection early\")\n # return\n self.report_pcap_list.append((\"All...\",))\n\n # Get and insert all captures currently added to database\n #print(\"self.report_device[0] == 'All...':\", self.report_device[0] == \"All...\")\n\n if self.report_device[0] == \"All...\":\n print(\"all devices selected\")\n self.db_handler.db.select_imported_captures()\n else:\n self.db_handler.db.select_imported_captures_with_device({\"dev_mac\":self.dev_mac})\n\n for (id, fileName, fileLoc, fileHash, capDate, capDuration, lifecyclePhase,\n internet, humanInteraction, preferredDNS, isolated, durationBased,\n duration, actionBased, deviceAction, details) in self.db_handler.db.cursor:\n #self.report_pcap_list.append((capDate, fileName, activity, duration, details, fileLoc, id)) #for early stages\n self.report_pcap_list.append((capDate, fileName, deviceAction, duration, details, fileLoc, id)) #for early stages\n #for (id, fileName, fileLoc, fileHash, capDate, duration, activity, details) in self.db_handler.db.cursor:\n # self.report_pcap_list.append((capDate, fileName, activity, duration, details, fileLoc, id)) #for early stages\n\n\n #for (id, fileName, fileLoc, fileHash, capDate, activity, details) in self.db_handler.db.cursor:\n # self.report_pcap_list.append((capDate, fileName, activity, details, fileLoc, id)) #for early stages\n \n # Set focus on the first element\n self.report_pcap_list.focus(0)\n self.report_pcap_list.selection_set(0)\n\n\n def select_report_pcaps(self, event):\n print(\"Select Report pcaps\")\n #self.report_pcap_sel = []\n self.report_pcap_where = ' '\n\n print(\"report_pcap_list.selection():\",self.report_pcap_list.selection())\n\n first = True\n\n for pcap_item in self.report_pcap_list.selection():\n pcap = self.report_pcap_list.get( pcap_item )\n print(\"pcap:\",pcap)\n\n if pcap[0] != \"All...\":\n if first:\n self.report_pcap_where = \" WHERE c.id = %s\" % pcap[6]\n first = False\n else:\n self.report_pcap_where += \" OR c.id = %s\" % pcap[6]\n \n self.report_pcap_where += ';'\n\n print(\"self.report_pcap_where:\",self.report_pcap_where)\n\n self.b_report_generate.config(state='normal')\n\n\n def generate_report(self):\n print(\"Preparing to generate report file\")\n #self.report_gen_obj = ReportGenerator()\n\n\n for dev_item in self.report_dev_list.selection():\n dev = self.report_dev_list.get( dev_item )\n \n if dev[0] == \"All...\":\n print(\"All selected\")\n self.db_handler.db.select_devices_imported()\n devs_imported = self.db_handler.db.cursor.fetchall()\n #for (id, mfr, model, mac, internalName, category) in self.db_handler.db.cursor:\n for (id, mfr, model, mac, internalName, category) in devs_imported:\n self.report_gen_obj = ReportGenerator({'name':internalName, 'mac':mac})\n\n # Write to file\n self.report_gen_obj.write_header()\n\n self.db_handler.db.select_caps_with_device_where({'mac_addr':mac}, conditions=self.report_pcap_where)\n pcap_info = self.db_handler.db.cursor.fetchall()\n print(\"len(pcap_info)\",len(pcap_info))\n\n capture_info = {} #;lkj;lkj;lkj\n #Need to add end_time and duration information to database\n #for (cap_id, filename, sha256, activity, start_time, duration, details) in pcap_info:\n for (cap_id, fileName, fileLoc, fileHash, start_time, capDuration, lifecyclePhase,\n internet, humanInteraction, preferredDNS, isolated, durationBased,\n duration, actionBased, deviceAction, details) in pcap_info:\n capture_info = {'filename' : fileName,\n 'sha256' : fileHash,\n #'activity' : activity,\n #'modifiers' : modifiers,\n 'phase' : field2db.inverse[lifecyclePhase][0],\n 'internet' : internet,\n 'humanInteraction' : humanInteraction,\n 'preferredDNS' : preferredDNS,\n 'isolated' : isolated,\n 'actionBased' : actionBased,\n 'deviceAction' : deviceAction,\n 'durationBased' : durationBased, \n 'duration' : duration,\n 'capDuration' : capDuration,\n 'start_time' : start_time,\n 'end_time' : start_time + timedelta(seconds=int(capDuration)),\n 'details' : details}\n\n capture_info['other_devices'] = []\n self.db_handler.db.select_devices_in_caps_except({\"cap_id\":cap_id, \"mac_addr\":mac})\n for (id, internalName, mac) in self.db_handler.db.cursor:\n capture_info['other_devices'].append({'name': internalName, 'mac' : mac})\n\n # Append capture information\n self.report_gen_obj.write_capture_info(capture_info)\n break\n\n else:\n print(\"Generating report for one device:\\t%s\" % dev[0])\n self.report_gen_obj = ReportGenerator({'name':dev[0], 'mac':dev[3]})\n\n # Write header to file\n self.report_gen_obj.write_header()\n\n self.db_handler.db.select_caps_with_device_where({'mac_addr':dev[3]}, conditions=self.report_pcap_where)\n pcap_info = self.db_handler.db.cursor.fetchall()\n \n capture_info = {}\n #for (cap_id, filename, sha256, activity, start_time, duration, details) in pcap_info:\n for (cap_id, fileName, fileLoc, fileHash, start_time, capDuration, lifecyclePhase,\n internet, humanInteraction, preferredDNS, isolated, durationBased,\n duration, actionBased, deviceAction, details) in pcap_info:\n\n capture_info = {'filename' : fileName,\n 'sha256' : fileHash,\n #'activity' : activity,\n #'modifiers' : modifiers,\n 'phase' : field2db.inverse[lifecyclePhase][0],\n 'internet' : internet,\n 'humanInteraction' : humanInteraction,\n 'preferredDNS' : preferredDNS,\n 'isolated' : isolated,\n 'actionBased' : actionBased,\n 'deviceAction' : deviceAction,\n 'durationBased' : durationBased, \n 'duration' : duration,\n 'capDuration' : capDuration,\n 'start_time' : start_time,\n 'end_time' : start_time + timedelta(seconds=int(capDuration)),\n 'details' : details}\n '''\n capture_info = {'filename' : filename,\n 'sha256' : sha256,\n 'activity' : activity,\n #'modifiers' : modifiers,\n 'start_time': start_time,\n 'end_time' : start_time + timedelta(seconds=int(duration)),\n 'capDuration' : duration,\n 'details' : details}\n '''\n capture_info['other_devices'] = []\n self.db_handler.db.select_devices_in_caps_except({\"cap_id\":cap_id, \"mac_addr\":dev[3]})\n for (id, internalName, mac) in self.db_handler.db.cursor:\n capture_info['other_devices'].append({'name': internalName, 'mac' : mac})\n\n # Append capture information\n self.report_gen_obj.write_capture_info(capture_info)\n\n messagebox.showinfo(\"Report Generation Complete\", \"The generated reports are in the 'reports' directory.\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n def popup_about(self):\n self.w_about = tk.Toplevel()\n self.w_about.wm_title(\"About\")\n\n summaryFrame = tk.Frame(self.w_about)\n summary = tk.Message(summaryFrame,\n text=\"This is a proof of concept for evaluating network traffic \" +\n \"for use in auditing the network, generating MUD files, and \" +\n \"identifying various privacy concerns.\\n\\n\" +\n \"This is a work in progress.\", width=500)\n\n summaryFrame.pack(side=\"top\", fill=\"both\", padx=5, pady=2, expand=True)\n summary.pack(side=\"left\")\n\n srcFrame = tk.Frame(self.w_about)\n sources = tk.Message(srcFrame, text=\"Icons used under Creative Commons BY 3.0 License:\\n\" +\n \"CC 3.0 BY Flaticon: www.flaticon.com is licensed by \" +\n \"http://creativecommons.org/licenses/by/3.0/ \" +\n \"Icons made by https://www.flaticon.com/authors/smashicons\\n\" +\n \"Icons made by Kirill Kazachek\", width=500)\n srcFrame.pack(side=\"top\", fill=\"both\", padx=5, pady=2, expand=True)\n sources.pack(side=\"left\")\n\n closeFrame = tk.Frame(self.w_about)\n b_close = tk.Button(closeFrame, text=\"Close\", command=self.w_about.destroy)\n closeFrame.pack(side=\"top\", fill=\"x\", padx=5, pady=2, expand=True)\n b_close.pack(side=\"bottom\", padx=5, pady=5)\n\n self.yield_focus(self.w_about)\n\n def __exit__(self):\n try:\n self.db_handler.__exit__()\n print(\"Cleaned up on exit\")\n except:\n print(\"Problem with cleanup\")\n\n self.parent.quit()\n\n\nimport time\ndef epoch2datetime(epochtime):\n return time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime(epochtime))\n\nfrom configparser import ConfigParser\n\n\nclass DatabaseHandler:\n\n\n def __init__(self, filename='config.ini', section='mysql'):\n\n try:\n self.config = self.read_db_config(filename, section)\n except:\n self.config = {\"host\": \"\", \"database\" : \"\", \"user\" : \"\", \"passwd\" : \"\"}\n self.connected = False\n\n def read_db_config(self, filename='config.ini', section='mysql'):\n parser = ConfigParser()\n parser.read(filename)\n\n db = {}\n if parser.has_section(section):\n items = parser.items(section)\n for item in items:\n db[item[0]] = item[1]\n else:\n raise Exception('{0} not found in the {1} file'.format(section, filename))\n\n return db\n\n def save_db_config(self, filename='config.ini', section='mysql', save_pwd=False):\n f = open(filename, \"w\")\n f.write(\"[%s]\" % section)\n\n for key in self.db_config:\n if save_pwd or key != \"passwd\":\n f.write(\"\\n%s = %s\" % (key, self.db_config[key]))\n else:\n f.write(\"\\n%s = \" % key)\n\n f.write(\"\\n\")\n f.close()\n \n def db_connect(self, entries):\n self.db_config = {}\n\n for entry in entries:\n field = entry[0]\n text = entry[1].get()\n #print(field, \" = \", text)\n self.db_config[field] = text\n\n try:\n self.db = CaptureDatabase(self.db_config)\n except:\n self.connected = False\n else:\n self.connected = True\n\n def __exit__(self):\n self.db.__exit__()\n\n\n'''\ndef fetch(entries):\n for entry in entries:\n field = entry[0]\n text = entry[1].get()\n print('%s: \"%s\"' % (field, text)) \n\n\ndef makeform(root, fields):\n entries = []\n for field in fields:\n row = Frame(root)\n lab = Label(row, width=15, text=field, anchor='w')\n ent = Entry(row)\n row.pack(side=TOP, fill=X, padx=5, pady=5)\n lab.pack(side=LEFT)\n ent.pack(side=RIGHT, expand=YES, fill=X)\n entries.append((field, ent))\n\n return entries\n \n\ndef importFileWindow(entry):\n #Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing\n importFile = Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing\n \n f_details = makeImportForm(importFile, captureFields)\n importFile.bind('', (lambda event, e=ents: fetch(e)))\n\n b_submit = Button(importFile, text=\"Submit\",\n command=(lambda e=ents: fetch(e)))\n b_submit.pack(side=LEFT, padx=5, pady=5)\n\n b_submit = Button(importFile, text=\"Quit\", command=root.quit)\n b_submit.pack(side=LEFT, padx=5, pady=5)\n\n importFile.mainloop()\n'''\n\nif __name__ == '__main__':\n root = tk.Tk()\n gui = MudCaptureApplication(root)\n root.mainloop()\n\n","sub_path":"mudpd.py","file_name":"mudpd.py","file_ext":"py","file_size_in_byte":144533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"467447835","text":"def is_admin(bot, update, specfic=None):\n if specfic:\n chat = specfic[0]\n uid = specfic[1]\n user = bot.get_chat_member(chat, uid)\n elif update.callback_query:\n user = bot.get_chat_member(\n update.callback_query.message.chat.id,\n update.callback_query.message.from_user.id)\n else:\n user = bot.get_chat_member(\n update.message.chat.id, update.message.from_user.id)\n\n if user.status not in ['administrator', 'creator']:\n return False\n else:\n return True\n","sub_path":"plugin/is_admin.py","file_name":"is_admin.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"566959574","text":"from tkinter import *\r\nfrom backend import Database # Import database class from backend\r\n \r\ndatabase=Database(\"books.db\") # Object\r\n \r\nclass Window(object):\r\n \r\n # Initialize the Object for class\r\n def __init__(self,window):\r\n self.window = window\r\n self.window.wm_title(\"BookStore Database\")\r\n \r\n l1=Label(window,text=\"Title\")\r\n l1.grid(row=0,column=0)\r\n \r\n l2=Label(window,text=\"Author\")\r\n l2.grid(row=0,column=2)\r\n \r\n l3=Label(window,text=\"Year\")\r\n l3.grid(row=1,column=0)\r\n \r\n l4=Label(window,text=\"ISBN\")\r\n l4.grid(row=1,column=2)\r\n \r\n self.title_text=StringVar()\r\n self.e1=Entry(window,textvariable=self.title_text)\r\n self.e1.grid(row=0,column=1)\r\n \r\n self.author_text=StringVar()\r\n self.e2=Entry(window,textvariable=self.author_text)\r\n self.e2.grid(row=0,column=3)\r\n \r\n self.year_text=StringVar()\r\n self.e3=Entry(window,textvariable=self.year_text)\r\n self.e3.grid(row=1,column=1)\r\n \r\n self.isbn_text=StringVar()\r\n self.e4=Entry(window,textvariable=self.isbn_text)\r\n self.e4.grid(row=1,column=3)\r\n \r\n self.list1=Listbox(window, height=6,width=35)\r\n self.list1.grid(row=2,column=0,rowspan=6,columnspan=2)\r\n \r\n sb1=Scrollbar(window)\r\n sb1.grid(row=2,column=2,rowspan=6)\r\n \r\n self.list1.configure(yscrollcommand=sb1.set)\r\n sb1.configure(command=self.list1.yview)\r\n \r\n self.list1.bind('<>',self.get_selected_row)\r\n \r\n b1=Button(window,text=\"View all records\", width=12,command=self.view_command,fg=\"sky blue\")\r\n b1.grid(row=2,column=3)\r\n \r\n b2=Button(window,text=\"Search entry\", width=12,command=self.search_command,fg=\"rosy brown\")\r\n b2.grid(row=3,column=3)\r\n \r\n b3=Button(window,text=\"Add entry\", width=12,command=self.add_command,fg=\"dark green\")\r\n b3.grid(row=4,column=3)\r\n \r\n b4=Button(window,text=\"Update record\", width=12,command=self.update_command,fg=\"lime green\")\r\n b4.grid(row=5,column=3)\r\n \r\n b5=Button(window,text=\"Delete record\", width=12,command=self.delete_command,fg=\"red\")\r\n b5.grid(row=6,column=3)\r\n \r\n b6=Button(window,text=\"Close aplecation\", width=12,command=window.destroy,fg=\"brown4\")\r\n b6.grid(row=7,column=3)\r\n \r\n # Method to return the selected tuple\r\n def get_selected_row(self,event):\r\n index=self.list1.curselection()[0]\r\n self.selected_tuple=self.list1.get(index)\r\n self.e1.delete(0,END)\r\n self.e1.insert(END,self.selected_tuple[1])\r\n self.e2.delete(0,END)\r\n self.e2.insert(END,self.selected_tuple[2])\r\n self.e3.delete(0,END)\r\n self.e3.insert(END,self.selected_tuple[3])\r\n self.e4.delete(0,END)\r\n self.e4.insert(END,self.selected_tuple[4])\r\n \r\n # Method to iterate through the tuple list\r\n def view_command(self):\r\n self.list1.delete(0,END)\r\n for row in database.view():\r\n self.list1.insert(END,row)\r\n \r\n # Method to loop through the backend and search\r\n def search_command(self):\r\n self.list1.delete(0,END)\r\n for row in database.search(self.title_text.get(),self.author_text.get(),self.year_text.get(),self.isbn_text.get()):\r\n self.list1.insert(END,row)\r\n \r\n # Method to insert the data into backend\r\n def add_command(self):\r\n database.insert(self.title_text.get(),self.author_text.get(),self.year_text.get(),self.isbn_text.get())\r\n self.list1.delete(0,END)\r\n self.list1.insert(END,(self.title_text.get(),self.author_text.get(),self.year_text.get(),self.isbn_text.get()))\r\n \r\n # Method to get the id of record and send it to the backend\r\n def delete_command(self):\r\n database.delete(self.selected_tuple[0])\r\n \r\n # Method to send the updated record to backend\r\n def update_command(self):\r\n database.update(self.selected_tuple[0],self.title_text.get(),self.author_text.get(),self.year_text.get(),self.isbn_text.get())\r\n\r\n# Object instance\r\nwindow=Tk()\r\nWindow(window)\r\nwindow.mainloop()","sub_path":"frontend.py","file_name":"frontend.py","file_ext":"py","file_size_in_byte":4129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"584628795","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Nov 11 17:48:50 2018\n\n@author: riccardo\n\"\"\"\nimport telebot #Telegram Bot API\n\nbot = telebot.TeleBot('741605487:AAGqpMtFxMEvHXnwxsIc4UvLd4q_0JRJGy0')\n\n@bot.message_handler(commands=['start','go'])\ndef send_welcome(message):\n name = message.chat.id\n\n bot.send_message(name, \"Welcome\" + str(name))\n\nbot.polling()\n#\n# bot.message_loop(rispondi)\n# while 1:\n# time.sleep(10)\n","sub_path":"bot/giorgiobot.py","file_name":"giorgiobot.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"25921237","text":"#!/usr/local/bin/python3\n\nimport argparse\nfrom SCNIC.within_correls import within_correls\nfrom SCNIC.between_correls import between_correls\nfrom SCNIC.module import module_maker\n\n__author__ = 'shafferm'\n\n\"\"\"Entry to both module_maker and between_correls, only holds main and args are passed to the corresponding program\"\"\"\n\n\ndef main():\n \"\"\"Things\"\"\"\n parser = argparse.ArgumentParser()\n\n subparsers = parser.add_subparsers()\n within_corr = subparsers.add_parser(\"within\", help=\"Find pairwise correlations within a table\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n make_modules = subparsers.add_parser(\"modules\", help=\"Make modules on a network\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n between_corr = subparsers.add_parser(\"between\", help=\"Find correlations between two tables\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n # parser for making correlation network with a single biom table\n within_corr.add_argument(\"-i\", \"--input\", help=\"location of input biom file\", required=True)\n within_corr.add_argument(\"-o\", \"--output\", help=\"output directory\")\n within_corr.add_argument(\"-m\", \"--correl_method\", help=\"correlation method\", default=\"sparcc\")\n within_corr.add_argument(\"-a\", \"--p_adjust\", help=\"p-value adjustment\", default=\"bh\")\n within_corr.add_argument(\"-s\", \"--min_sample\", help=\"minimum number of samples present in\", type=int)\n within_corr.add_argument(\"--procs\", help=\"number of processors to use\", default=1, type=int)\n within_corr.add_argument(\"-f\", \"--force\", help=\"force overwrite output folder if it already exists\", default=False,\n action=\"store_true\")\n within_corr.add_argument(\"--sparcc_filter\", help=\"filter as described in SparCC paper\", default=False,\n action=\"store_true\")\n within_corr.add_argument(\"--sparcc_p\", help=\"Calculate p-value for sparCC R value\", type=int)\n within_corr.add_argument(\"--verbose\", help=\"give verbose messages to STDOUT\", default=False, action=\"store_true\")\n within_corr.set_defaults(func=within_correls)\n\n # parser for finding modules in a correlation network\n make_modules.add_argument(\"-i\", \"--input\", help=\"location of input distance matrix\", required=True)\n make_modules.add_argument(\"-o\", \"--output\", help=\"output directory\")\n make_modules.add_argument(\"--prefix\", help=\"prefix for module names in collapsed file\", default=\"module_\")\n make_modules.add_argument(\"--min_p\", help=\"minimum p-value to determine edges, p must have been calculated\",\n type=float)\n make_modules.add_argument(\"--min_r\", help=\"minimum correlation value to determine edges\", type=float)\n make_modules.add_argument(\"--table\", help=\"biom table usede to make network to be collapsed\")\n make_modules.add_argument(\"-v\", \"--verbose\", help=\"give verbose messages to STDOUT\")\n make_modules.set_defaults(func=module_maker)\n\n # parser for building a bipartite correlation network between two data types\n between_corr.add_argument(\"-1\", \"--table1\", help=\"table to be correlated\", required=True)\n between_corr.add_argument(\"-2\", \"--table2\", help=\"second table to be correlated\", required=True)\n between_corr.add_argument(\"-o\", \"--output\", help=\"output file location\")\n between_corr.add_argument(\"-m\", \"--correl_method\", help=\"correlation method\", default=\"spearman\")\n between_corr.add_argument(\"-a\", \"--p_adjust\", help=\"p-value adjustment\", default=\"bh\")\n between_corr.add_argument(\"-s\", \"--min_sample\", help=\"minimum number of samples present in\", type=int)\n between_corr.add_argument(\"--min_p\", help=\"minimum p-value to determine edges\", type=float)\n between_corr.add_argument(\"--min_r\", help=\"minimum R to determine edges\", type=float)\n between_corr.add_argument(\"--sparcc_filter\", help=\"filter using parameters from SparCC publication\", default=False,\n action=\"store_true\")\n between_corr.add_argument(\"--procs\", help=\"number of processors to use\", default=1, type=int)\n between_corr.add_argument(\"-f\", \"--force\", help=\"force overwrite output folder if it already exists\", default=False,\n action=\"store_true\")\n between_corr.set_defaults(func=between_correls)\n\n args = parser.parse_args()\n args.func(args)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"scripts/SCNIC_analysis.py","file_name":"SCNIC_analysis.py","file_ext":"py","file_size_in_byte":4501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"128293915","text":"import cv2\r\nfrom os import listdir,makedirs\r\nfrom os.path import isfile,join\r\nimport os\r\n\r\npath = r'E:\\Deep learning\\ml project\\ml\\images' # Source Folder\r\ndstpath = r'E:\\Deep learning\\ml project\\ml\\Grayscale' # Destination Folder\r\n\r\ntry:\r\n makedirs(dstpath)\r\nexcept:\r\n print (\"Directory already exist, images will be written in asme folder\")\r\n\r\n# Folder won't used\r\nfiles = [f for f in listdir(path) if isfile(join(path,f))]\r\n\r\nfor image in files:\r\n try:\r\n img = cv2.imread(os.path.join(path,image))\r\n gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\r\n dstPath = join(dstpath,image)\r\n cv2.imwrite(dstPath,gray)\r\n except:\r\n print (\"{} is not converted\".format(image))","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"631574051","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Feb 2 23:04:46 2017\n\n@author: yxl\n\"\"\"\n\nimport wx\nfrom imagepy.core.engine import Tool\nfrom .setting import Setting\nfrom imagepy import IPy\nimport pandas as pd\n\nclass Coordinate:\n \"\"\"Define the coordinate class\"\"\"\n dtype = 'coordinate'\n def __init__(self, body=None, unit=None):\n self.body = body if body!=None else []\n self.unit = unit\n \n def add(self, p):\n self.body.append(p)\n \n def snap(self, x, y, lim):\n cur, minl = None, 1000\n for i in self.body:\n d = (i[0]-x)**2+(i[1]-y)**2\n if d < minl:cur,minl = i,d\n if minl**0.5>lim:return None\n return self.body.index(cur)\n \n def pick(self, x, y, lim):\n return self.snap(x, y, lim)\n \n def draged(self, ox, oy, nx, ny, i):\n self.body[i] = (nx, ny)\n \n def draw(self, dc, f, **key):\n dc.SetPen(wx.Pen(Setting['color'], width=1, style=wx.SOLID))\n dc.SetTextForeground(Setting['tcolor'])\n font = wx.Font(10, wx.FONTFAMILY_DEFAULT, \n wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False)\n \n dc.SetFont(font)\n for i in self.body:\n x,y = f(*i)\n unit = 1 if self.unit is None else self.unit[0]\n dc.DrawCircle(x, y, 2)\n dc.DrawText('(%.1f,%.1f)'%(i[0]*unit, i[1]*unit), x, y)\n\n def report(self, title):\n unit = 1 if self.unit is None else self.unit[0]\n rst = [(x*unit, y*unit) for x,y in self.body]\n titles = ['OX', 'OY']\n IPy.show_table(pd.DataFrame(rst, columns=titles), title)\n\nclass Plugin(Tool):\n \"\"\"Define the coordinate class plugin with the event callback functions\"\"\"\n title = 'Coordinate'\n def __init__(self):\n self.curobj = None\n self.odx, self.ody = 0, 0\n \n def mouse_down(self, ips, x, y, btn, **key):\n if key['ctrl'] and key['alt']:\n if isinstance(ips.mark, Coordinate):\n ips.mark.report(ips.title)\n return\n lim = 5.0/key['canvas'].scale \n if btn==1:\n if isinstance(ips.mark, Coordinate):\n self.curobj = ips.mark.pick(x, y, lim)\n if self.curobj!=None:return\n if not isinstance(ips.mark, Coordinate):\n ips.mark = Coordinate(unit=ips.unit)\n elif not key['shift']:\n ips.mark = Coordinate(unit=ips.unit)\n ips.mark.add((x,y))\n self.curobj = ips.mark.pick(x,y, lim)\n ips.update()\n self.odx, self.ody = x, y\n \n def mouse_up(self, ips, x, y, btn, **key):\n self.curobj = None\n \n def mouse_move(self, ips, x, y, btn, **key):\n if not isinstance(ips.mark, Coordinate):return\n lim = 5.0/key['canvas'].scale \n if btn==None:\n self.cursor = wx.CURSOR_CROSS\n if ips.mark.snap(x, y, lim)!=None:\n self.cursor = wx.CURSOR_HAND\n elif btn==1:\n ips.mark.draged(self.odx, self.ody, x, y, self.curobj)\n ips.update()\n self.odx, self.ody = x, y\n \n def mouse_wheel(self, ips, x, y, d, **key):\n pass","sub_path":"imagepy/tools/Measure/coordinate_tol.py","file_name":"coordinate_tol.py","file_ext":"py","file_size_in_byte":3204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"634862127","text":"\"\"\"\nGiven a string S, find the largest alphabetic character, whose both uppercase and lowercase appear in S.\nThe uppercase character should be returned. For example, for S = \"admeDCAB\", return \"D\".\nIf there is no such character, return \"NO\".\n\"\"\"\n\"\"\"\nPython two pass solution using a set.\nTime Complexity: O(N)\nSpace Complexity: O(1) - Since set can only have 26 characters at best\n\"\"\"\n\n\ndef largestAlphabeticCharacter(s):\n res = \"\"\n lower_chars = set()\n\n for c in s:\n if c.islower():\n lower_chars.add(c)\n for c in s:\n if c.isupper() and c.lower() in lower_chars:\n res = max(res, c)\n\n return res if len(res) > 0 else \"NO\"\n\n\"\"\"\ndef largest_uppercase_char(S):\n max_upper_char = None\n for c in S:\n if ord(\"A\") <= ord(c) <= ord(\"Z\"):\n if not max_upper_char or ord(c) > ord(max_upper_char):\n max_upper_char = c\n \n if not max_upper_char:\n max_upper_char = \"NO\"\n return max_upper_char\n\nprint(largest_uppercase_char(\"admeDCAB\"))\n\"\"\"","sub_path":"Challenges/MicrosoftOA/LargestAlphabeticCharacter.py","file_name":"LargestAlphabeticCharacter.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"265343795","text":"import frappe\nfrom latte.database_utils.connection_pool import PatchedDatabase\nfrom pymysql.err import IntegrityError\n\ndef lockless_gapless_autoname(doc, _=None):\n\t# print('Gapless')\n\tnaming_series = doc.naming_series.replace('.', '').replace('#', '')\n\tdigits = doc.naming_series.split('.')[-1].count('#') or 5\n\tgetter_db = get_db()\n\ttry:\n\t\tnext_name = get_next_value(getter_db, doc.doctype, naming_series, digits)\n\t\tdoc.name = next_name\n\t\tdoc.flags.retry_on_duplicate_insert = True\n\tfinally:\n\t\tgetter_db.close()\n\ndef get_db():\n\ttry:\n\t\treturn frappe.local.gapless_autoname_conn\n\texcept AttributeError:\n\t\tgetter_db = frappe.local.gapless_autoname_conn = PatchedDatabase()\n\t\treturn getter_db\n\ndef get_next_value(db, doctype, naming_series, digits, failsafe=10):\n\tif failsafe < 0:\n\t\tfrappe.throw('Failsafe broke')\n\n\tcurrent = db.sql('select current from `tabSeries` where name = %(name)s for update', {\n\t\t'name': naming_series,\n\t})\n\tif current:\n\t\tcurrent = current[0][0]\n\telse:\n\t\ttry:\n\t\t\tmax_val = db.sql(f'''\n\t\t\t\tSELECT\n\t\t\t\t\tmax(name)\n\t\t\t\tfrom\n\t\t\t\t\t`tab{doctype}`\n\t\t\t\twhere\n\t\t\t\t\tname like %(naming_series)s\n\t\t\t\t\tand name regexp \"^{db.escape(naming_series)}[0-9]+$\"\n\t\t\t''', {\n\t\t\t\t'naming_series': f'{naming_series}%',\n\t\t\t})[0][0]\n\t\t\tcurrent = int(max_val[len(naming_series):]) if max_val else 0\n\t\t\tprint('FOund new current = ', current)\n\t\t\tdb.sql('insert into `tabSeries` (name, current) value (%(name)s, %(current)s)', {\n\t\t\t\t'name': naming_series,\n\t\t\t\t'current': current,\n\t\t\t})\n\t\texcept IntegrityError:\n\t\t\treturn get_next_value(db, naming_series, digits, failsafe - 1)\n\t# print('Current Value', naming_series, current)\n\n\tnext_name = get_min_used_name(db, doctype, naming_series, digits, current)\n\t# print('Found Next name=', next_name)\n\tdb.commit()\n\treturn next_name\n\nINCR_BY = 10\nINSERT_STRING = f'''\n\tinsert into `tabGapless Name Record`\n\t\t(ref_doctype, naming_series, generated_name, status, modified)\n\tvalues\n\t\t{','.join([\"(%s, %s, %s, %s, %s)\"] * INCR_BY)}\n'''\ndef get_min_used_name(db, doctype, naming_series, digits, current):\n\tmin_name = db.sql('''\n\t\tSELECT\n\t\t\tmin(generated_name)\n\t\tfrom\n\t\t\t`tabGapless Name Record`\n\t\twhere\n\t\t\tnaming_series = %(naming_series)s\n\t\t\tand status = \"Pending\"\n\t''', {\n\t\t'naming_series': naming_series\n\t})[0][0]\n\t# print('Min name', min_name)\n\tif min_name:\n\t\tdb.sql('''\n\t\t\tupdate\n\t\t\t\t`tabGapless Name Record`\n\t\t\tset\n\t\t\t\tstatus = \"Used\"\n\t\t\twhere\n\t\t\t\tnaming_series = %(naming_series)s\n\t\t\t\tand status = 'Pending'\n\t\t\t\tand generated_name = %(used_name)s\n\t\t''', {\n\t\t\t'used_name': min_name,\n\t\t\t'naming_series': naming_series,\n\t\t})\n\t\treturn min_name\n\n\t# print(f'Incrementing current {current} to {INCR_BY}', current + INCR_BY)\n\n\tnow = frappe.utils.now_datetime()\n\tdb.sql('update tabSeries set current = %(new_val)s where name = %(naming_series)s', {\n\t\t'new_val': current + INCR_BY,\n\t\t'naming_series': naming_series,\n\t})\n\tnext_names = [\n\t\tj\n\t\tfor i in range(1, INCR_BY + 1)\n\t\tfor j in [\n\t\t\tdoctype,\n\t\t\tnaming_series,\n\t\t\tf'{naming_series}%0{digits}d' % (current + i),\n\t\t\t'Pending',\n\t\t\tnow,\n\t\t]\n\t]\n\tnext_names[3] = 'Used'\n\n\tdb.sql(INSERT_STRING, next_names)\n\n\treturn next_names[2]\n\ndef reconcile():\n\tdoctypes = frappe.db.sql_list('''\n\t\tselect distinct ref_doctype from `tabGapless Name Record`\n\t''')\n\tfor doctype in doctypes:\n\t\ttry:\n\t\t\tclean_up(doctype)\n\t\texcept:\n\t\t\tpass\n\ndef clean_up(doctype):\n\tfrappe.db.sql(f'''\n\t\tdelete gnr from\n\t\t\t`tabGapless Name Record` gnr\n\t\twhere\n\t\t\tgnr.ref_doctype = %(doctype)s\n\t\t\tand gnr.status = 'Used'\n\t\t\tand exists (\n\t\t\t\tselect 1\n\t\t\t\tfrom `tab{doctype}` dt\n\t\t\t\twhere dt.name = gnr.generated_name\n\t\t\t)\n\t''', {\n\t\t'doctype': doctype\n\t})\n\tfrappe.db.commit()\n\n\tfrappe.db.sql(f'''\n\t\tupdate\n\t\t\t`tabGapless Name Record` gnr\n\t\tset\n\t\t\tgnr.status = 'Pending'\n\t\twhere\n\t\t\tgnr.ref_doctype = %(doctype)s\n\t\t\tand gnr.status = 'Used'\n\t\t\tand gnr.modified < %(now)s - interval 5 minute\n\t\t\tand not exists (\n\t\t\t\tselect 1\n\t\t\t\tfrom `tab{doctype}` dt\n\t\t\t\twhere dt.name = gnr.generated_name\n\t\t\t)\n\t''', {\n\t\t'doctype': doctype,\n\t\t'now': frappe.utils.now_datetime(),\n\t})\n\tfrappe.db.commit()\n","sub_path":"latte/latte_core/naming/lockless_gapless_autoname.py","file_name":"lockless_gapless_autoname.py","file_ext":"py","file_size_in_byte":4016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"448664731","text":"import os\nimport csv\nimport numpy as np\nimport tensorflow as tf\nimport pandas as pd\nfrom tensorflow_vgg import vgg16\nfrom tensorflow_vgg import utils\nfrom sklearn.preprocessing import LabelBinarizer\n\ndef wxsc_main(dir):\n sess = tf.Session()\n batch = []\n codes = None\n img = utils.load_image(dir)\n vgg = vgg16.Vgg16()\n input_ = tf.placeholder(tf.float32, [None, 224, 224, 3])\n with tf.name_scope(\"content_vgg\"):\n # 载入VGG16模型\n vgg.build(input_)\n batch.append(img.reshape((1, 224, 224, 3)))\n images = np.concatenate(batch)\n feed_dict = {input_: images}\n # 计算特征值\n codes = sess.run(vgg.relu6, feed_dict=feed_dict)\n # 清空数组准备下一个batch的计算\n batch = []\n\n\n\n labels = [\"beef_carpaccio\", \"baklava\", \"apple_pie\", \"beef_tartare\", \"beignets\", \"bibimbap\", \"beet_salad\",\n \"baby_back_ribs\"]\n lb = LabelBinarizer()\n lb.fit(labels)\n labels_vecs = lb.transform(labels)\n\n # 输入数据的维度\n inputs_ = tf.placeholder(tf.float32, shape=[None, codes.shape[1]])\n # 标签数据的维度\n labels_ = tf.placeholder(tf.int64, shape=[None, labels_vecs.shape[1]])\n\n # 加入一个256维的全连接的层\n fc = tf.contrib.layers.fully_connected(inputs_, 256)\n\n # 加入一个5维的全连接层\n logits = tf.contrib.layers.fully_connected(fc, labels_vecs.shape[1], activation_fn=None)\n\n # 计算cross entropy值\n cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=labels_, logits=logits)\n\n # 计算损失函数\n cost = tf.reduce_mean(cross_entropy)\n\n # 采用用得最广泛的AdamOptimizer优化器\n optimizer = tf.train.AdamOptimizer().minimize(cost)\n\n # 得到最后的预测分布\n predicted = tf.nn.softmax(logits)\n\n # 计算准确度\n correct_pred = tf.equal(tf.argmax(predicted, 1), tf.argmax(labels_, 1))\n accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n\n pre = tf.arg_max(predicted, 1)\n saver = tf.train.Saver()\n sess = tf.Session()\n saver.restore(sess, tf.train.latest_checkpoint('my_test_model'))\n\n feed = {inputs_: codes}\n test_acc = sess.run(pre, feed_dict=feed)\n\n return test_acc[0]","sub_path":"img_read.py","file_name":"img_read.py","file_ext":"py","file_size_in_byte":2195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"287951167","text":"import unittest\n\nfrom sentinelhub import get_tile_info, get_area_dates, BBox, CRS, TestSentinelHub\n\n\nclass TestOpensearch(TestSentinelHub):\n def test_get_tile_info(self):\n tile_info = get_tile_info('T30SVH', '2015-11-29', aws_index=1)\n self.assertTrue(isinstance(tile_info, dict), msg=\"Expected a dict, got {}\".format(type(tile_info)))\n\n def test_get_area_dates(self):\n bbox = BBox([1059111.463919402, 4732980.791418114, 1061557.4488245277, 4735426.776323237], crs=CRS.POP_WEB)\n dates = get_area_dates(bbox, ('2016-01-23', '2016-11-24'), maxcc=0.7)\n self.assertTrue(isinstance(dates, list), msg=\"Expected a list, got {}\".format(type(dates)))\n self.assertEqual(len(dates), 22, \"Expected a list of length 22, got length {}\".format(len(dates)))\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_opensearch.py","file_name":"test_opensearch.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"142143803","text":"import numpy as np\nfrom sklearn import svm, metrics\nimport matplotlib.pyplot as plt\n\ndef model_accuracy (train_data, train_targets, test_data, test_targets, parameter, sigma):\n linear_SVM = svm.SVC(C=parameter, kernel='rbf', gamma=sigma)\n linear_SVM.fit(train_data, train_targets)\n test_results = linear_SVM.predict(test_data)\n accuracy = metrics.accuracy_score(test_targets, test_results)\n return parameter, accuracy, sigma\n\nif __name__ == \"__main__\":\n # load data and extract them from the npz file\n data = np.load('forest_data.npz')\n training_data = data['data_training']\n training_labels = data['label_training']\n testing_data = data['data_val']\n testing_labels = data['label_val']\n\n # trim to first 2000 rows only\n training_data_trimmed = training_data[0:2000, :]\n training_labels_trimmed = training_labels[0:2000]\n\n\n # create empty lists to store data\n parameter_list = []\n accuracy_list = []\n sigma_list = []\n\n sigma_range = range(-8, 5)\n c_range = range(-12, 6)\n\n # loop to create model based on non normalized data and check for accuracy\n for sig in sigma_range:\n for c in c_range:\n parameter, accuracy, sigma = model_accuracy(training_data_trimmed, training_labels_trimmed, testing_data, testing_labels, 10**c, 10**sig)\n parameter_list.append(parameter)\n accuracy_list.append(accuracy)\n sigma_list.append(sigma)\n\n length = len(c_range)\n for sigma_index in range(len(sigma_range)):\n plt.semilogx(parameter_list[length*sigma_index:length*(sigma_index+1)], accuracy_list[length*sigma_index:length*(sigma_index+1)])\n\n plt.legend(sigma_list, loc='lower left', title='Sigma Values')\n plt.ylabel('Accuracy')\n plt.xlabel('Penalty Parameter')\n plt.ylim(0, 1)\n plt.show()\n","sub_path":"assignment6/kernelSVM.py","file_name":"kernelSVM.py","file_ext":"py","file_size_in_byte":1813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"509246008","text":"import osutools\nimport discord\nfrom discord.ext import commands\n\nosu = osutools.OsuClientV1(\"token\")\nbot = commands.Bot(command_prefix=\"!\")\n\n\n@bot.command(name=\"profile\")\nasync def profile(ctx, *, username):\n user = osu.fetch_user(username=username)\n embed = discord.Embed(title=f\"osu! Profile for {user.username}\")\n embed.set_thumbnail(url=user.avatar_url)\n embed.add_field(name=\"Rank\", value=f\"#{user.rank}\")\n embed.add_field(name=\"pp\", value=f\"{user.pp}\")\n embed.add_field(name=\"Accuracy\", value=f\"{round(user.accuracy, 2)}%\")\n embed.add_field(name=\"Playcount\", value=f\"{user.play_count}\")\n await ctx.send(embed=embed)\n\nbot.run(\"token2\")\n","sub_path":"examples/discord_bot.py","file_name":"discord_bot.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"489988983","text":"from django.urls import path\n\nfrom .views import (DaftarSuratMasuk, TambahSuratMasuk, UbahSuratMasuk, DaftarSuratKeluar,\n TambahSuratKeluar, UbahSuratKeluar, DaftarSuratKeluarKhusus, TambahSuratKeluarKhusus,\n UbahSuratKeluarKhusus)\n\napp_name = 'persuratanApp'\n\nurlpatterns = [\n path('masuk/', DaftarSuratMasuk.as_view(), name='suratMasukUrl'),\n path('masuk/tambah/', TambahSuratMasuk.as_view(), name='tambahSuratMasukUrl'),\n path('masuk//ubah/', UbahSuratMasuk.as_view(), name='ubahSuratMasukUrl'),\n\n path('keluar/biasa/', DaftarSuratKeluar.as_view(), name='suratKeluarUrl'),\n path('keluar/biasa/tambah/', TambahSuratKeluar.as_view(), name='tambahSuratKeluarUrl'),\n path('keluar/biasa//ubah/', UbahSuratKeluar.as_view(), name='ubahSuratKeluarUrl'),\n\n path('keluar/khusus/', DaftarSuratKeluarKhusus.as_view(), name='suratKeluarKhususUrl'),\n path('keluar/khusus/tambah/', TambahSuratKeluarKhusus.as_view(), name='tambahSuratKeluarKhususUrl'),\n path('keluar/khusus//ubah/', UbahSuratKeluarKhusus.as_view(), name='ubahSuratKeluarKhususUrl'),\n]\n","sub_path":"ortala/persuratan/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"132509394","text":"import pytest\nfrom models.Question import Question\nfrom init_db import *\nfrom models.Answer import Answer\n\nclass TestQuestion:\n\n def test_db(self):\n ses = init_db_session()\n\n assert ses.query(Question).count() == 0\n\n question = Question()\n a = Answer(option='Yes', question=question)\n ses.add(a)\n ses.commit()\n\n assert ses.query(Answer).count() == 1\n assert ses.query(Question).count() == 1\n\n def test_name_nonnumeric(self):\n q = Question('1234')\n assert p.validate() == False","sub_path":"tests/test_questions.py","file_name":"test_questions.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"255351044","text":"#!/usr/bin/env python3\nimport socket\nimport argparse\nimport termios\nimport tty\nimport sys\nimport select\nimport signal\nimport array\n\nparser = argparse.ArgumentParser('remote serial tcp/ip client')\nparser.add_argument('server', type=str, help='server ip add port, sample: 127.0.0.1:1234')\nparser.add_argument('-o', '--output', type=argparse.FileType('w'), help='save log file name')\nparser.add_argument('-c', '--password', type=int, help='password', default=32485967)\nargs = parser.parse_args()\n\norig_settings = termios.tcgetattr(sys.stdin)\n\ndef term_sig_handler(signum, frame):\n termios.tcsetattr(sys.stdin, termios.TCSADRAIN, orig_settings)\n print()\n exit()\n\ndef main():\n signal.signal(signal.SIGTERM, term_sig_handler)\n try:\n client = socket.socket()\n ip, port = args.server.split(':')\n client.connect((ip, int(port)))\n except ConnectionRefusedError:\n print(\"connect error!\") \n return\n\n print(\"connected to {}:{}, Please Enter Control+X to exit!\".format(*client.getpeername()))\n\n s_epoll = select.epoll()\n s_epoll.register(client.fileno(), select.POLLIN)\n s_epoll.register(sys.stdin.fileno(), select.POLLIN)\n\n tty.setraw(sys.stdin)\n matched = False\n\n try:\n while True:\n events = s_epoll.poll(2)\n for fileno, event in events:\n if fileno == client.fileno() and event == select.POLLIN:\n data = client.recv(1024).decode()\n if not matched:\n a = array.array('I', [args.password]).tobytes()\n client.sendall(a)\n matched = True\n break\n print(data, end='', flush=True)\n if args.output:\n args.output.write(data)\n elif fileno == sys.stdin.fileno() and event == select.POLLIN:\n data = sys.stdin.read(1).encode()\n if data == b'\\x18': # Control+x\n termios.tcsetattr(sys.stdin, termios.TCSADRAIN, orig_settings)\n print()\n return\n client.send(data)\n except ConnectionResetError:\n print(\"connect reset!\")\n except IOError:\n pass\n finally:\n termios.tcsetattr(sys.stdin, termios.TCSADRAIN, orig_settings)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"python/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":2399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"602403619","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[24]:\n\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport warnings\nimport os\n\nget_ipython().run_line_magic('matplotlib', 'inline')\nwarnings.filterwarnings('ignore')\n\nplt.rcParams['font.family'] = 'DejaVu Sans'\n\n\n# In[25]:\n\n\nimport FinanceDataReader as fdr\nsamsung = fdr.DataReader('005930')\nsamsung.tail()\n\n\n# In[26]:\n\n\napple = fdr.DataReader('AAPL')\napple.tail()\napple.head()\n\n\n# In[27]:\n\n\nford = fdr.DataReader('F', '1980-01-01', '2019-12-30')\nford.head()\n\n\n# In[28]:\n\n\nford.tail()\n\n\n# In[29]:\n\n\nSTOCK_CODE = '005930'\n\n\n# In[30]:\n\n\nstock = fdr.DataReader(STOCK_CODE)\n\n\n# In[31]:\n\n\nstock.head()\n\n\n# In[32]:\n\n\nstock.tail()\n\n\n# In[33]:\n\n\nstock.index\n\n\n# # DatetimeIndex로 정의되어 있다면 연도, 월, 일을 쪼갤 수 있으며, 월별, 연도별 피벗 데이터를 만들 때 유용하게 활용할 수 있다\n\n# In[34]:\n\n\nstock['Year'] = stock.index.year\nstock['Month'] = stock.index.month\nstock['Day'] = stock.index.day\n\n\n# In[35]:\n\n\nstock.head()\n\n\n# In[36]:\n\n\nplt.figure(figsize=(16,9))\nsns.lineplot(y=stock['Close'], x=stock.index)\n\n\n# In[37]:\n\n\ntime_steps = [['1990', '2000'],\n ['2000', '2010'],\n ['2010', '2015'],\n ['2015', '2020']]\nfig, axes = plt.subplots(2,2)\nfig.set_size_inches(16,9)\nfor i in range(4):\n ax = axes[i//2, i%2]\n df = stock.loc[(stock.index > time_steps[i][0])&(stock.index < time_steps[i][1])]\n sns.lineplot(y=df['Close'], x=df.index, ax=ax)\n ax.set_title(f'{time_steps[i][0]}~{time_steps[i][1]}')\n ax.set_xlabel('time')\n ax.set_ylabel('price')\nplt.tight_layout()\nplt.show()\n\n\n# # 데이터 전처리\n\n# In[38]:\n\n\nfrom sklearn.preprocessing import MinMaxScaler\n\n\n# In[39]:\n\n\nscaler = MinMaxScaler()\nscale_cols = ['Open', 'High', 'Low', 'Close', 'Volume']\nscaled = scaler.fit_transform(stock[scale_cols])\nscaled\n\n\n# In[40]:\n\n\ndf = pd.DataFrame(scaled, columns=scale_cols)\n\n\n# In[41]:\n\n\nfrom sklearn.model_selection import train_test_split\n\n\n# In[42]:\n\n\nx_train, x_test, y_train, y_test = train_test_split(df.drop('Close',1), df['Close'], test_size=0.2, random_state=0, shuffle=False)\n\n\n# In[43]:\n\n\nx_train.shape, y_train.shape\n\n\n# In[44]:\n\n\nx_test.shape, y_test.shape\n\n\n# In[45]:\n\n\nx_train\n\n\n# In[46]:\n\n\nimport tensorflow as tf\n\n\n# In[47]:\n\n\ndef windowed_dataset(series, window_size, batch_size, shuffle):\n series = tf.expand_dims(series, axis=-1)\n ds = tf.data.Dataset.from_tensor_slices(series)\n ds = ds.window(window_size + 1, shift=1, drop_remainder=True)\n ds = ds.flat_map(lambda w: w.batch(window_size + 1))\n if shuffle:\n ds = ds.shuffle(1000)\n ds = ds.map(lambda w: (w[:-1], w[-1]))\n return ds.batch(batch_size).prefetch(1)\n\n\n# In[48]:\n\n\nWINDOW_SIZE = 20\nBATCH_SIZE = 32\n\n\n# In[49]:\n\n\ntrain_data = windowed_dataset(y_train, WINDOW_SIZE, BATCH_SIZE, True)\ntest_data = windowed_dataset(y_test, WINDOW_SIZE, BATCH_SIZE, False)\n\n\n# In[50]:\n\n\nfor data in train_data.take(1):\n print(f'데이터셋(X) 구성(batch_size, window_size, feature갯수): {data[0].shape}')\n print(f'데이터셋(Y) 구성(batch_size, window_size, feature갯수): {data[1].shape}')\n\n\n# In[53]:\n\n\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, LSTM, Conv1D, Lambda\nfrom tensorflow.keras.losses import Huber\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint\n\nmodel = Sequential([\n Conv1D(filters=32, kernel_size=5,\n padding=\"causal\",\n activation=\"relu\",\n input_shape=[WINDOW_SIZE, 1]),\n LSTM(16, activation='tanh'),\n Dense(16, activation=\"relu\"),\n Dense(1),\n])\n\n\n# In[54]:\n\n\nloss = Huber()\noptimizer = Adam(0.0005)\nmodel.compile(loss=Huber(), optimizer=optimizer, metrics=['mse'])\n\n\n# In[55]:\n\n\nearlystopping = EarlyStopping(monitor='val_loss', patience=10)\nfilename = os.path.join('tmp', 'checkpointer.ckpt')\ncheckpoint = ModelCheckpoint(filename,\n save_weights_only=True,\n save_best_only=True,\n monitor='val_loss',\n verbose=1)\n\n\n# In[56]:\n\n\nhistory = model.fit(train_data,\n validation_data=(test_data),\n epochs=50,\n callbacks=[checkpoint, earlystopping])\n\n\n# In[57]:\n\n\nmodel.load_weights(filename)\n\n\n# In[58]:\n\n\npred = model.predict(test_data)\n\n\n# In[59]:\n\n\npred.shape\n\n\n# In[60]:\n\n\nplt.figure(figsize=(12,9))\nplt.plot(np.asarray(y_test)[20:], label='actual')\nplt.plot(pred, label='prediction')\nplt.legend()\nplt.show()\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"Exercise(ipynb)/LSTM 주가예측-2.py","file_name":"LSTM 주가예측-2.py","file_ext":"py","file_size_in_byte":4638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"595858853","text":"# -*- coding:utf-8 -*-\nimport numpy as np\nimport pandas as pd\nimport matplotlib as plt\n\ndef readData(filePath):\n f = pd.read_table(filePath)\n dataFrame = f[['A','B','C']]\n labels = f['D']\n return dataFrame, labels\n\ndef normData(dataFrame):\n lam = lambda x: (x-x.min()) / (x.max() - x.min())\n return(dataFrame.apply(lam))\n\ndef calculateDistance(dataFrame,vector):\n vectorSeries = pd.Series(vector,index = ['A','B','C'])\n dataFrame = dataFrame - vectorSeries\n lam = lambda x: (x['A'] ** 2 + x['B'] ** 2 + x['C'] ** 2) ** 0.5\n return(dataFrame.apply(lam,axis = 1))\n \n \ndef category(distanceDataFrame,labels,k):\n distanceAndLabels = pd.concat([distanceDataFrame,labels],axis = 1).ix[0:k-1]\n return(distanceAndLabels['D'].value_counts().index[0])\n\ndef test():\n dataFrame, labels = readData(\"/home/daiab/program/KNN/datingTestSet4.txt\")\n dataFrameNorm = normData(dataFrame)\n testDataFrame, testLabels = readData(\"/home/daiab/program/KNN/datingTestSet3.txt\")\n testDataFrameNorm = normData(testDataFrame)\n rowNum = testDataFrameNorm.shape[0]\n rightPredictCount = 0\n for i in range(rowNum):\n distanceDataFrame = calculateDistance(dataFrameNorm,testDataFrameNorm.ix[i])\n predictCategory = category(distanceDataFrame,labels,3)\n print(\"the predict category is\",predictCategory)\n realCategory = testLabels[i]\n print(\"the real category is\",realCategory)\n if predictCategory == realCategory:\n rightPredictCount += 1\n print(\"the right predict rate is \",rightPredictCount / rowNum)\n \nif __name__ == '__main__':\n test()\n","sub_path":"algorithm/KNN/KNN-usepandas.py","file_name":"KNN-usepandas.py","file_ext":"py","file_size_in_byte":1631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"493202624","text":"import re, argparse, copy, os\nfrom igf_data.illumina.samplesheet import SampleSheet\n\n\nparser=argparse.ArgumentParser()\nparser.add_argument('-i','--samplesheet_file', required=True, help='Illumina format samplesheet file')\nparser.add_argument('-d','--output_dir', required=True, help='Output directory for writing samplesheet file')\nparser.add_argument('-p','--print_stats', default=False, action='store_true', help='Print available statse for the samplesheet and exit')\nargs=parser.parse_args()\n\nsamplesheet_file=args.samplesheet_file\nprint_stats=args.print_stats\noutput_dir=args.output_dir\nfile_prefix=os.path.basename(samplesheet_file)\n\nsamplesheet_data=SampleSheet(infile=samplesheet_file)\nplatform_name=samplesheet_data.get_platform_name()\nsample_lane=samplesheet_data.get_lane_count()\n\nplatform_pattern=re.compile('^HISEQ',re.IGNORECASE)\n\ndata_group=dict()\n\nif len(sample_lane) > 1:\n '''\n Run this loop only for the HiSeq data\n '''\n\n for lane_id in sample_lane:\n samplesheet_data_tmp=copy.copy(samplesheet_data)\n samplesheet_data_tmp.filter_sample_data( condition_key='Lane', condition_value=lane_id )\n data_group[lane_id]=samplesheet_data_tmp.group_data_by_index_length()\n\nelse:\n '''\n For MiSeq and NextSeq\n '''\n data_group[1]=samplesheet_data.group_data_by_index_length()\n\n\nfor lane_id in data_group.keys():\n for index_length in data_group[lane_id].keys():\n output_file=os.path.join(output_dir, '{0}_{1}_{2}'.format(file_prefix,lane_id,index_length))\n data_group[lane_id][index_length].print_sampleSheet(outfile=output_file)\n","sub_path":"scripts/SampleSheet/divide_samplesheet.py","file_name":"divide_samplesheet.py","file_ext":"py","file_size_in_byte":1556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"641155337","text":"from odoo import api, fields, models, _\nimport qrcode\nimport base64\nimport io\nfrom odoo.tools.misc import formatLang, format_date\nfrom odoo import http\nfrom num2words import num2words\n\n\nclass AccountMove(models.Model):\n _inherit = 'account.invoice'\n\n invoice_date_supply = fields.Date('Date Of Supply')\n\n def get_product_arabic_name(self,pid):\n translation = self.env['ir.translation'].search([\n ('name','=','product.product,name'),('state','=','translated'),\n ('res_id','=',pid)])\n if translation :\n return translation.value\n else: \n product = self.env['product.product'].browse(int(pid))\n translation = self.env['ir.translation'].search([\n ('name','=','product.product,name'),('state','=','translated'),\n ('res_id','=',product.product_tmpl_id.id)])\n if translation :\n return translation.value\n return ''\n \n\n def amount_word(self, amount):\n language = self.partner_id.lang or 'en'\n language_id = self.env['res.lang'].search([('code', '=', 'ar_AA')])\n if language_id:\n language = language_id.iso_code\n amount_str = str('{:2f}'.format(amount))\n amount_str_splt = amount_str.split('.')\n before_point_value = amount_str_splt[0]\n after_point_value = amount_str_splt[1][:2] \n before_amount_words = num2words(int(before_point_value),lang=language)\n after_amount_words = num2words(int(after_point_value),lang=language)\n amount = before_amount_words + ' ' + after_amount_words\n return amount\n\n def amount_total_words(self, amount):\n words_amount = self.currency_id.amount_to_text(amount)\n return words_amount\n\n @api.model\n def get_qr_code(self):\n\n def get_qr_encoding(tag, field):\n company_name_byte_array = field.encode('UTF-8')\n company_name_tag_encoding = tag.to_bytes(length=1, byteorder='big')\n company_name_length_encoding = len(company_name_byte_array).to_bytes(length=1, byteorder='big')\n return company_name_tag_encoding + company_name_length_encoding + company_name_byte_array\n\n qr_code_str = ''\n seller_name_enc = get_qr_encoding(1, self.company_id.display_name)\n company_vat_enc = get_qr_encoding(2, self.company_id.vat or '')\n date_order = fields.Datetime.from_string(self.create_date)\n time_sa = fields.Datetime.context_timestamp(self.with_context(tz='Asia/Riyadh'),date_order)\n timestamp_enc = get_qr_encoding(3, time_sa.isoformat())\n invoice_total_enc = get_qr_encoding(4, str(self.amount_total))\n total_vat_enc = get_qr_encoding(5, str(self.currency_id.round(self.amount_total - self.amount_untaxed)))\n\n str_to_encode = seller_name_enc + company_vat_enc + timestamp_enc + invoice_total_enc + total_vat_enc\n qr_code_str = base64.b64encode(str_to_encode).decode('UTF-8')\n return qr_code_str\n\n \n\n @api.multi\n def action_invoice_sent(self):\n self.ensure_one()\n template = self.env.ref('ob_saudi_vat_invoice.email_template_edi_invoice_etir', False)\n compose_form = self.env.ref('account.account_invoice_send_wizard_form', False)\n # have model_description in template language\n lang = self.env.context.get('lang')\n if template and template.lang:\n lang = template._render_template(template.lang, 'account.invoice', self.id)\n self = self.with_context(lang=lang)\n TYPES = {\n 'out_invoice': _('Invoice'),\n 'in_invoice': _('Vendor Bill'),\n 'out_refund': _('Credit Note'),\n 'in_refund': _('Vendor Credit note'),\n }\n ctx = dict(\n default_model='account.invoice',\n default_res_id=self.id,\n default_use_template=bool(template),\n default_template_id=template and template.id or False,\n default_composition_mode='comment',\n mark_invoice_as_sent=True,\n model_description=TYPES[self.type],\n custom_layout=\"mail.mail_notification_paynow\",\n force_email=True\n )\n return {\n 'name': _('Send Invoice'),\n 'type': 'ir.actions.act_window',\n 'view_type': 'form',\n 'view_mode': 'form',\n 'res_model': 'account.invoice.send',\n 'views': [(compose_form.id, 'form')],\n 'view_id': compose_form.id,\n 'target': 'new',\n 'context': ctx,\n }\n\n\nclass ResPartner(models.Model):\n _inherit = 'res.partner'\n\n building_no = fields.Char('Building No')\n additional_no = fields.Char('Additional No')\n other_seller_id = fields.Char('Other Seller Id')\n\n\nclass ResCompany(models.Model):\n _inherit = 'res.company'\n\n building_no = fields.Char(related='partner_id.building_no', store=True, readonly=False, string='Building No')\n additional_no = fields.Char(related='partner_id.additional_no', store=True, readonly=False, string='Additional No')\n other_seller_id = fields.Char(related='partner_id.other_seller_id', store=True, readonly=False, string='Other Seller Id')\n arabic_name = fields.Char('Name')\n arabic_street = fields.Char('Street')\n arabic_street2 = fields.Char('Street2')\n arabic_city = fields.Char('City')\n arabic_state = fields.Char('State')\n arabic_country = fields.Char('Country')\n arabic_zip = fields.Char('Zip')\n","sub_path":"ob_saudi_vat_invoice/models/sale_purchase_invoice.py","file_name":"sale_purchase_invoice.py","file_ext":"py","file_size_in_byte":5495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"459158841","text":"import re\nimport collections\nfrom functools import lru_cache, singledispatch, update_wrapper\n\n\nclass RecursiveDict(dict):\n \"\"\" A dictionary that can directly access items from nested dictionaries\n using the '/' character.\n Example:\n d = RecursiveDict((('inner', {'innerkey':'innerval'}),))\n d['inner/innerkey'] returns 'innerval'\n \"\"\"\n def __init__(self, *args, **kwargs):\n dict.__init__(self, *args, **kwargs)\n\n def __repr__(self):\n string = 'Recursive dict with\\nTop level keys:\\n{}\\nLeaf keys:\\n{}'.\\\n format(', '.join((k for k in self.keys())),\n ', '.join((k for k in self._get_keys())))\n return string\n\n def __getitem__(self, key):\n if key == '/':\n return self\n key_split = key.split('/')\n key = key_split.pop(0)\n if key == '':\n return KeyError('')\n if key_split:\n return dict.__getitem__(self, key).__getitem__('/'.join(key_split))\n else:\n return dict.__getitem__(self, key)\n\n def __setitem__(self, key, value):\n key_split = key.split('/')\n key = key_split.pop(0)\n if key == '':\n return KeyError('')\n if key_split:\n self[key].__setitem__(self, key, value)\n else:\n dict.__setitem__(self, key, value)\n\n def _get_x(self, xattr):\n out = []\n for x, v in zip(getattr(self, xattr)(), self.values()):\n if isinstance(v, RecursiveDict):\n out.extend(v._get_x(xattr))\n elif isinstance(v, dict) & hasattr(v, xattr):\n out.extend(getattr(v, xattr)())\n else:\n out.append(x)\n return out\n\n def _get_items(self):\n return self._get_x('items')\n\n def _get_values(self):\n return self._get_x('values')\n\n def _get_keys(self):\n return self._get_x('keys')\n\n def __iter__(self):\n return iter(self._get_values())\n\n def __len__(self):\n return len(self._get_keys())\n\n\nclass AttrRecDict(RecursiveDict):\n \"\"\" A dictionary, based on RecursiveDict, that allows recurisve access to\n nested dictionary items using object attributes.\n Only the final level / leaf dictionaries will have attribute accessible\n items. Primarily used to access subproject participants from a higher level\n project.\n Example:\n d = AttrRecDict((('inner', {'innerkey':'innerval'}),))\n d.inner raises an AttributeError\n d.innerkey returns 'innerval'\n d['inner'] returns {'inner': 'innerkey'}\n d['inner/innerkey'] returns 'innerval\n \"\"\"\n def __getattr__(self, name):\n if name not in [x for x in self._get_keys()]:\n raise AttributeError(\n \"No such attribute '{}' in '{}'\".format(name, self))\n kv = self._get_items()\n val = [x[1] for x in kv if x[0] == name] or None\n if val is None:\n raise AttributeError(\n \"No such attribute '{}' in '{}'\".format(name, self))\n elif len(val) > 1:\n raise ValueError(\n 'Multiple participants with the same ID: {}'.format(name))\n return val[0]\n\n def __repr__(self):\n string = super(AttrRecDict, self).__repr__()\n string = string.split('\\n')\n string[0] = 'Attribute recursive dict with'\n string = '\\n'.join(string)\n return string\n\n def __dir__(self):\n return self.keys()\n\n\nclass AttrDict(dict):\n def __init__(self, *args, **kwargs):\n super(AttrDict, self).__init__(*args, **kwargs)\n self.__dict__ = self\n\n\ndef update(d, u):\n for k, v in u.items():\n if isinstance(v, collections.Mapping):\n d[k] = update(d.get(k, {}), v)\n else:\n d[k] = v\n return d\n\n\ndef methdispatch(func):\n def wrapper(*args, **kw):\n return dispatcher.dispatch(args[1].__class__)(*args, **kw)\n dispatcher = singledispatch(func)\n wrapper.register = dispatcher.register\n update_wrapper(wrapper, func)\n return wrapper\n\n@lru_cache(8)\ndef re_compile(pattern):\n return re.compile(pattern)\n","sub_path":"radar/generic.py","file_name":"generic.py","file_ext":"py","file_size_in_byte":4133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"141608498","text":"from django.core.cache import cache\nfrom django.http import JsonResponse\nfrom django.shortcuts import render\n\n# Create your views here.\n\nimport logging\n\nfrom django.views import View\n\nfrom apps.areas.models import Area\nfrom utils.response_code import RETCODE\n\nlogger = logging.getLogger('django')\n\n\nclass AreasView(View):\n \"\"\"省市区数据\"\"\"\n def get(self, request):\n \"\"\"\n 提供省市区数据\n 如果前端没有传入area_id,表示用户需要省份数据\n 如果前端传入了area_id,表示用户需要市或区数据\n :param request:\n :return:\n \"\"\"\n area_id = request.GET.get('area_id')\n if not area_id:\n # 读取省份缓存数据\n province_list = cache.get('province_list')\n if not province_list:\n # 提供省份数据\n try:\n # 查询省份数据\n province_model_list = Area.objects.filter(parent__isnull=True)\n # 序列化省份数据\n province_list = []\n for province_model in province_model_list:\n province_list.append({'id': province_model.id, 'name': province_model.name})\n except Exception as e:\n logger.error(e)\n return JsonResponse({'code': RETCODE.DBERR,\n 'errmsg': '省份数据错误'})\n # 存储省份缓存数据\n cache.set('province_list', province_list, 3600)\n # 响应省份数据\n return JsonResponse({'code': RETCODE.OK,\n 'errmsg': 'ok',\n 'province_list': province_list})\n else:\n # 读取市区缓存数据\n sub_data = cache.get('sub_area_' + area_id)\n if not sub_data:\n # 提供市区数据\n try:\n # 查询市区父级\n parent_model = Area.objects.get(id=area_id)\n sub_model_list = parent_model.subs.all()\n # 序列化市区数据\n sub_list = []\n for sub_model in sub_model_list:\n sub_list.append({'id': sub_model.id, \"name\": sub_model.name})\n sub_data = {\n 'id': parent_model.id, # 父级pk\n 'name': parent_model.name, # 父级name\n 'subs': sub_list # 父级的子集\n }\n except Exception as e:\n logger.error(e)\n return JsonResponse({'code': RETCODE.DBERR,\n 'errmsg': '市区数据错误'})\n # 缓存市区数据\n cache.set('sub_area_' + area_id, sub_data, 3600)\n # 响应市区数据\n return JsonResponse({'code': RETCODE.OK,\n 'errmsg': 'ok',\n 'sub_data': sub_data})\n","sub_path":"meiduo_mall/apps/areas/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"342746473","text":"#Derek Low \n#Moderation Project- Fall 2016\n\nfrom Graphics import *\nfrom Myro import *\nimport random\nimport time\n\nclass physicsCharacter(object):\n\n JUMPING = 2\n NOT_JUMPING = 3\n ON_GROUND = True\n GRAVITY = 300\n \n def __init__(self, win):\n self.win = win\n self.state = character.LIVE\n\n self.velocityX = 0\n self.velocityY = 0\n self.onGround = True\n self.jump = character.NOT_JUMPING\n \n \n def update(self, step):\n self.appearance.x += self.velocityX * step\n self.appearance.y += self.velocityY * step\n self.velocityY += character.GRAVITY * step\n \n if self.velocityX > 0:\n self.velocityX -= 8\n \n if self.velocityX < 0:\n self.velocityX += 8\n\n def setOnGround(self, platform):\n self.velocityY = 0\n self.onGround = True\n self.jump = character.NOT_JUMPING\n self.appearance.y = platform.appearance.y - self.appearance.getHeight()/2 - 5\n \n def setOffLeft(self,platform):\n self.velocityX = 0\n self.onGround = False\n self.jump = character.JUMPING\n self.appearance.x = platform.appearance.x - platform.width/2 - self.appearance.getWidth()/2\n\n def setOffRight(self, platform):\n self.velocityX = 0\n self.onGround = False\n self.jump = character.JUMPING\n self.appearance.x = platform.appearance.x + platform.width/2 + self.appearance.getWidth()/2\n\n def setUnderGround(self,platform):\n self.velocityY = 0\n self.onGround = False\n self.jump = character.JUMPING\n self.appearance.y = platform.appearance.y + 1\n\n def collidedWith(self, other):\n return\n \nclass character(physicsCharacter):\n\n DEAD = 0\n LIVE = 1\n JUMPING = 2\n NOT_JUMPING = 3\n ON_GROUND = True\n GRAVITY = 300\n WIN = 6\n \n def __init__(self, win):\n physicsCharacter.__init__(self, win)\n self.startTime = currentTime()\n self.win = win\n self.state = character.LIVE\n \n self.appearance = makePicture('Bob.png')\n self.appearance.x = 430\n self.appearance.y = getHeight(win) - 50\n self.appearance.draw(win)\n self.width = self.appearance.getWidth()\n self.height = self.appearance.getHeight()\n self.hp = 100\n \n def collidedWith(self, other):\n if other in Monsters:\n self.hp = self.hp - 25\n if self.velocityX > 0:\n self.velocityX = -500\n if self.velocityX < 0:\n self.velocityX = 500\n self.velocityY = -100\n self.onGround = False\n self.jump = character.JUMPING\n if other in Treasure:\n self.state = character.WIN \n \n def update(self, step):\n physicsCharacter.update(self,step)\n \n if self.hp <= 0:\n self.state = character.DEAD\n \nclass monster(physicsCharacter):\n GRAVITY = 300\n def __init__(self, win):\n physicsCharacter.__init__(self, win)\n self.startTime = currentTime()\n self.win = win\n #self.state = character.LIVE\n \n self.appearance = makePicture('enemy.gif')\n self.appearance.x = random.choice(Platforms).appearance.x\n self.appearance.y = random.choice(Platforms).appearance.y - 30\n self.appearance.draw(win)\n self.width = self.appearance.getWidth()\n self.height = self.appearance.getHeight()\n self.velocityX = -70\n \n def update(self,step):\n self.appearance.x += self.velocityX * step\n self.appearance.y += self.velocityY * step\n self.velocityY += character.GRAVITY * step\n\n def setOnGround(self, platform):\n self.velocityY = 0\n self.onGround = True\n self.jump = character.NOT_JUMPING\n self.appearance.y = platform.appearance.y - self.appearance.getHeight()/2 - 5\n if self.appearance.x < platform.appearance.x - platform.width/2 + 15:\n self.velocityX = 70\n if self.appearance.x > platform.appearance.x + platform.width/2 - 15: \n self.velocityX = -70\n \nclass treasureChest(physicsCharacter):\n def __init__(self, win):\n physicsCharacter.__init__(self,win)\n self.appearance = makePicture('chest.png')\n self.appearance.x = 50\n self.appearance.y = 50\n self.appearance.draw(win)\n self.width = self.appearance.getWidth()\n self.height = self.appearance.getHeight()\n \ndef isCollision (self, other):\n myx1 = self.x - self.width/2 #left\n myy1 = self.y - self.height/2 #top\n myx2 = self.x + self.width/2 #right\n myy2 = self.y + self.height/2 #bottom\n\n otherx1 = other.appearance.x - other.appearance.getWidth()/2 #left\n othery1 = other.appearance.y - other.appearance.getHeight()/2 #top\n otherx2 = other.appearance.x + other.appearance.getWidth()/2 #right\n othery2 = other.appearance.y + other.appearance.getHeight()/2 #bottom \n return myy1 < othery2 and myy2 > othery1 and myx1 < otherx2 and myx2 > otherx1\n \n#the reason for the presence of isCollision and checkCollision is because certain classes have an appearance.x and others do not\ndef checkCollision (self,other):\n myx1 = self.appearance.x - self.appearance.width/2 #left\n myy1 = self.appearance.y - self.appearance.height/2 #top\n myx2 = self.appearance.x + self.appearance.width/2 #right\n myy2 = self.appearance.y + self.appearance.height/2 #bottom\n\n otherx1 = other.appearance.x - other.appearance.getWidth()/2 #left\n othery1 = other.appearance.y - other.appearance.getHeight()/2 #top\n otherx2 = other.appearance.x + other.appearance.getWidth()/2 #right\n othery2 = other.appearance.y + other.appearance.getHeight()/2 #bottom\n\n return myy1 < othery2 and myy2 > othery1 and myx1 < otherx2 and myx2 > otherx1\n\ndef detectPlatCollisions(platformList,entities):\n # do collision detection here\n for Platform in platformList:\n for Entity in entities:\n if platforms.checkCollision(Platform, Entity):\n if Platform.correctCollision(Entity) ==1 :\n Entity.setOnGround(Platform) \n if Platform.correctCollision(Entity) ==2:\n Entity.setUnderGround(Entity) \n if Platform.correctCollision(Entity) ==3:\n if Entity.appearance.y > Platform.appearance.y:\n Entity.setOffLeft(Platform)\n else:\n Entity.setOnGround(Platform)\n if Platform.correctCollision(Entity) ==4 :\n if Entity.appearance.y > Platform.appearance.y:\n Entity.setOffRight(Platform)\n else:\n Entity.setOnGround(Platform)\n \ndef detectEntCollisions(entities):\n for idx, entityA in enumerate(entities):\n for entityB in enumerate(entities, start = idx+1):\n if checkCollision(entityA, entityB[1]):\n entityA.collidedWith(entityB)\n entityB[1].collidedWith(entityA)\n \ndef updatePhysics(step):\n for Entity in Entities:\n Entity.update(step)\n\nclass platforms(object):\n MIN_SIZE = 50\n MAX_SIZE = 1000\n def __init__(self, x , y, width, win):\n self.win = win\n self.width = width \n self.height = 10\n self.appearance = Rectangle(Point(x - self.width/2, y - self.height/2),\n Point(x + self.width/2, y + self.height/2))\n # The left rectangle's top left corner\n lefttopLeftX = self.appearance.x - self.width/2\n lefttopLeftY = self.appearance.y - self.height/2\n # The left rectangle's bottom right corner\n leftbottomrightx = self.appearance.x - self.width/2 + 4\n leftbottomrighty = self.appearance.y +self.height/2\n # The right rectangle's top left corner\n righttopleftx = self.appearance.x + self.width/2 - 4\n righttoplefty = self.appearance.y - self.height/2\n # The right rectangle's bottom right corner\n rightbottomrightx = self.appearance.x + self.width/2\n rightbottomrighty = self.appearance.y + self.height/2\n # The top rectangle's top left corner\n toptopleftx = self.appearance.x - self.width/2 + 4\n toptoplefty = self.appearance.y - self.height/2\n # The top rectangle's bottom right corner\n topbottomrightx = self.appearance.x + self.width/2 - 4\n topbottomrighty = self.appearance.y\n # The bottom rectangle's top left corner\n bottomtopleftx = self.appearance.x -self.width/2 + 4\n bottomtoplefty = self.appearance.y\n # The bottom rectangle's bottom right corner\n bottombottomrightx= self.appearance.x + self.width/2 - 4\n bottombottomrighty = self.appearance.y + self.height/2\n # topRightX =\n self.leftRect = Rectangle( Point(lefttopLeftX, lefttopLeftY), \n Point (leftbottomrightx, leftbottomrighty))\n \n self.rightRect = Rectangle( Point(righttopleftx, righttoplefty) ,\n Point (rightbottomrightx,rightbottomrighty ))\n self.bottom = Rectangle( Point(bottomtopleftx,bottomtoplefty) ,\n Point (bottombottomrightx,bottombottomrighty))\n self.top = Rectangle( Point(toptopleftx, toptoplefty) ,\n Point (topbottomrightx, topbottomrighty))\n self.appearance.draw(win)\n\n def checkCollision (self,other):\n myx1 = self.appearance.x - self.width/2 #left\n myy1 = self.appearance.y - self.height/2 #top\n myx2 = self.appearance.x + self.width/2 #right\n myy2 = self.appearance.y + self.height/2#bottom\n\n otherx1 = other.appearance.x - other.appearance.getWidth()/2 #left\n othery1 = other.appearance.y - other.appearance.getHeight()/2 #top\n otherx2 = other.appearance.x + other.appearance.getWidth()/2 #right\n othery2 = other.appearance.y + other.appearance.getHeight()/2 #bottom\n\n return myy1 < othery2 and myy2 > othery1 and myx1 < otherx2 and myx2 > otherx1\n\n def correctCollision (self, other):\n if isCollision(self.top, other):\n return 1\n if isCollision(self.bottom,other):\n return 2\n if isCollision(self.leftRect, other):\n return 3\n if isCollision(self.rightRect, other):\n return 4\n \n return False \n\nPlatforms = []\nMonsters = []\nEntities = []\nTreasure = []\n\nMAX_SUBNODES = 4\nMAX_OBJECTS = 4\nINIT_DEPTH = 1\nclass QuadNode(object):\n def __init__(self, x, y, width, height, depth):\n self.x = x\n self.y = y\n self.w = width\n self.h = height\n \n self.midX = self.x + self.w/2\n self.maxX = self.x + self.w\n self.midY = self.y + self.h/2\n self.maxY = self.y + self.h\n self.depth = depth\n self.entities = []*MAX_OBJECTS\n self.subNodes = [None] * MAX_SUBNODES\n self.numNodes = 0 \n \n def split(self):\n subWidth = self.w/2\n subHeight = self.h/2\n \n self.subNodes[0] = QuadNode(self.midX, self.midY, subWidth, subHeight,self.depth + 1) \n self.subNodes[1] = QuadNode(self.x, self.midY, subWidth, subHeight, self.depth + 1)\n self.subNodes[2] = QuadNode(self.midX, self.y, subWidth, subHeight, self.depth + 1)\n self.subNodes[3] = QuadNode(self.x, self.y, subWidth, subHeight, self.depth + 1)\n self.empty()\n #print (\"split one time!\")\n \n def insert(self, obj, x, y, width, height):\n idx = -1\n if self.subNodes[0] != None:\n idx = self.calculateSubnode(x, y, width, height)\n if idx != -1:\n self.subNodes[idx].insert(obj, x, y, width, height)\n return\n \n self.entities.append(obj)\n \n if self.entities.__len__() > MAX_OBJECTS:\n self.split()\n newNode = self.partition(idx)\n #newNode.insert(obj, obj.appearance.x, obj.appearance.y, obj.appearance.getWidth(), obj.appearance.getHeight())\n return newNode.depth\n \n def inBoundary(self, x, y):\n if x >= self.x and y >= self.y:\n if x <= self.maxX and y <= self.maxY:\n return True\n return False\n\n def isLeftHalf(self, x, y):\n if x < self.midX:\n return 1\n return 0\n\n def isTopHalf(self, x, y):\n if y < self.midY: \n return 2\n return 0\n\n def empty(self):\n return self.entities.__len__() == 0\n\n def calculateSubnode(self, x, y, width, height):\n if self.inBoundary(x,y):\n idx = self.isLeftHalf(x,y) + self.isTopHalf(x,y)\n return idx\n return -1\n \n def partition(self, idx):\n i = self.entities.__len__() - 1\n while i >= 0:\n obj = self.entities.pop(i)\n body = obj\n idx = self.calculateSubnode(body.appearance.x, body.appearance.y, body.width, body.height)\n if idx != -1:\n self.subNodes[idx].insert(obj, body.appearance.x, body.appearance.y, body.width, body.height)\n else:\n self.entities.append(obj)\n i-= 1\n return self.subNodes[idx]\n \n def testCollisions(self,object):\n if self.subNodes[0] != None:\n for subnode in self.subNodes: \n subnode.testCollisions(object) \n else:\n detectPlatCollisions(Platforms, Entities)\n detectEntCollisions(Entities)\n #print (\"running collision testing\") \ndef mainLevel1():\n win = Window('Explore!', 900,800)\n\n caves = makePicture(\"background.png\")\n caves.draw(win)\n\n\n Platforms.append(platforms(450, getHeight(win) - 10, getWidth(win),win))\n Platforms.append(platforms(250, 700, 100,win))\n Platforms.append(platforms(500, 650, 300,win))\n Platforms.append(platforms(850, 700, 100, win))\n Platforms.append(platforms(650, 700, 100,win))\n Platforms.append(platforms(800, 550, 200,win))\n Platforms.append(platforms(300,500,600,win))\n Platforms.append(platforms(450, 400, 200, win))\n Platforms.append(platforms(200, 325, 200, win))\n Platforms.append(platforms(700, 325, 200, win))\n Platforms.append(platforms(100, 250, 200, win))\n Platforms.append(platforms(800, 250, 200,win))\n Platforms.append(platforms(450, 200, 200, win))\n Platforms.append(platforms(200, 100, 400, win))\n \n \n Bob = character(win)\n Entities.append(Bob)\n treasureWin = Treasure.append(treasureChest(win))\n for i in range(16):\n Monsters.append(monster(win))\n Entities.extend(Monsters)\n Entities.extend(Treasure)\n qt = QuadNode(0,0,win.getWidth(), win.getHeight(),INIT_DEPTH)\n for platform in Platforms:\n qt.insert(platform, platform.appearance.x, platform.appearance.y, platform.width, platform.height)\n for entity in Entities:\n qt.insert(entity, entity.appearance.x, entity.appearance.y, entity.appearance.getWidth(), entity.appearance.getHeight())\n \n frameRate = 0\n fps = 25\n time_delta = 1/fps\n while Bob.state == character.LIVE:\n \n t0 = time.clock()\n time.sleep(time_delta)\n t1 = time.clock()\n delta = t1 - t0\n # The Game Loop\n qt.testCollisions(Platforms)\n updatePhysics(delta)\n \n if win.getKeyPressed('Left') == True:\n Bob.velocityX = -100\n \n if win.getKeyPressed('Right') == True:\n Bob.velocityX = 100\n \n if win.getKeyPressed('Up') == True:\n # only when bob isn't jumping does the up\n # button actually do anything\n \n if Bob.jump != character.JUMPING:\n Bob.velocityY = -250\n Bob.jump = character.JUMPING\n Bob.onGround = False\n \n if win.getKeyPressed('Down') == True:\n Bob.velocityY+= 50\n\n if win.getKeyPressed('x') == True:\n print(\"shoot\")\n \n if Bob.state == character.DEAD:\n caves.undraw()\n win.setBackground(Color(\"black\"))\n loser = Text((300,100), \"YOU LOSE :(\")\n loser.setColor(Color(\"white\"))\n loser.fontSize = 60\n loser.draw(win)\n if Bob.state == character.WIN:\n caves.undraw()\n win.setBackground(Color(\"gold\"))\n winner = Text((300,100),\"YOU WIN!!!\" )\n winner.fontSize = 60\n winner.draw(win)\n \nmainLevel1()","sub_path":"scratch.py","file_name":"scratch.py","file_ext":"py","file_size_in_byte":16666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"28470915","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Mar 28 10:04:47 2020\r\n\r\n@author: User\r\n\"\"\"\r\nfrom mcpi.minecraft import Minecraft\r\nmc=Minecraft.create()\r\nx,y,z=mc.player.getTilePos()\r\ntry:\r\n blockType=int(input(\"請輸入要放的方塊ID:\"))\r\n h=int(input(\"請輸入屋子的高度:\"))\r\n w=int(input(\"請輸入屋子的寬度:\"))\r\n l=int(input(\"請輸入屋子的長度:\"))\r\n hblockType=int(input(\"請輸入要的屋頂方塊ID:\"))\r\n mc.setBlocks(x+l ,y+h ,z+w ,x-l ,y ,z-w ,blockType)\r\n mc.setBlocks(x+l-1 ,y+h-1 ,z+w-1 ,x-l+1 ,y+1,z-w+1,0)\r\n mc.setBlocks(x+l-1 ,y+h-1 ,z+w-1 ,x-l+1 ,y+h,z-w+1,hblockType)\r\n \r\n mc.postToChat(\"blockType\"+str(blockType))\r\nexcept:\r\n print(\"只能輸入數字!!!\")","sub_path":"401-04.py","file_name":"401-04.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"633738128","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Mar 8 16:45:06 2020\r\n\r\n@author: abcd\r\n\"\"\"\r\n\r\ndef maxDistance(arr, n):\r\n max1=0\r\n d={}\r\n for i in range(n):\r\n if arr[i] not in d:\r\n d[arr[i]]=i\r\n elif max1<(i-d[arr[i]]):\r\n max1=i-d[arr[i]]\r\n \r\n \r\n return max1\r\n","sub_path":"maxdiffofsameele.py","file_name":"maxdiffofsameele.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"102326180","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Apr 27 22:19:16 2018\n\n@author: Thomas\n\"\"\"\nimport requests\nfrom bs4 import BeautifulSoup\nfrom Fighter import Fighter\nimport pandas as pd\n\ndef fighterList(webSoup): #pull fighter names from fight card, make a list of names\n\t\n\tskipList = webSoup.find_all(itemprop='name')\n\ttextList = [span.text for span in skipList]\n\tfighterNamesx = [x for x in textList if \"vs.\" not in x]\n\tfighterNamesy = [x for x in fighterNamesx if \"UFC\" not in x] \n\tfighterNames = [x.title() for x in fighterNamesy if x] #prob simpler way to do this\n\treturn (fighterNames)\n\ndef fighterInformation(fighterStatPages, count): #Returns a class containing all fighter information\n\t\n\t\n\tfighterPage = []\n\tx = 0\n\tfightCount = 0\n\t\n\tfor i in fighterStatPages:\n\t\tif(x == count):\n\t\t\tfighterPage = i['href']\n\t\t\tbreak\n\t\tx += 1\n\t\n\ttry:\n\t\tfighterUrl = requests.get(fighterPage)\n\texcept:\n\t\tprint(\"**Error finding fighter stats page\")\n\t\treturn 0\n\t\n\tfighterSoup = BeautifulSoup(fighterUrl.text, 'html.parser')\n\tstatList = fighterSoup.find_all(class_='b-list__box-list-item b-list__box-list-item_type_block')\n\thistoryList = fighterSoup.find_all(class_='b-fight-details__table-row b-fight-details__table-row__hover js-fight-details-click') #fight count\n\t\t\n\tfor i in statList:\n\t\ttempName = (i.find(\"i\").text).strip()\n\t\ttemp = ((i.text).strip())\n\t\tclearedTemp = temp.replace(' ','')\n\t\tnewlineTemp = clearedTemp.replace('\\n','')\n\t\tsplitTemp = newlineTemp.split(':')\n\n\t\tif tempName == 'Reach:':\n\t\t\treachTmp = splitTemp[1].replace('\\\"','')\n\t\t\ttry:\n\t\t\t\tReach = float(reachTmp)\n\t\t\texcept ValueError:\n\t\t\t\tprint(\"Reach Assignment Error\")\n\t\t\t\tReach = 0\n\t\telif tempName == 'STANCE:':\n\t\t\tStance = splitTemp[1]\n\t\telif tempName == 'DOB:':\n\t\t\tDOB = splitTemp[1]\n\t\telif tempName == 'SLpM:':\n\t\t\ttry:\n\t\t\t\tSLpM = float(splitTemp[1].replace('%',''))\n\t\t\texcept ValueError:\n\t\t\t\tprint(\"SLpM Assignment Error\")\n\t\t\t\tSLpM = 0\n\t\telif tempName == 'Str. Acc.:':\n\t\t\ttry:\n\t\t\t\tStrAcc = float(splitTemp[1].replace('%',''))\n\t\t\texcept ValueError:\n\t\t\t\tprint(\"StrAcc Assignment Error\")\n\t\t\t\tStrAcc = 0\n\t\telif tempName == 'SApM:':\n\t\t\ttry:\n\t\t\t\tSApM = float(splitTemp[1].replace('%',''))\n\t\t\texcept ValueError:\n\t\t\t\tprint(\"SApM Assignment Error\")\n\t\t\t\tSApM = 0\n\t\telif tempName == 'Str. Def:':\n\t\t\ttry:\n\t\t\t\tStrDef = float(splitTemp[1].replace('%',''))\n\t\t\texcept ValueError:\n\t\t\t\tprint(\"StrDef Assignment Error\")\n\t\t\t\tStrDef = 0\n\t\telif tempName == 'TD Avg.:':\n\t\t\ttry:\n\t\t\t\tTDAvg = float(splitTemp[1].replace('%',''))\n\t\t\texcept ValueError:\n\t\t\t\tprint(\"TDAvg Assignment Error\")\n\t\t\t\tTDAvg = 0\n\t\telif tempName == 'TD Acc.:':\n\t\t\ttry:\n\t\t\t\tTDAcc = float(splitTemp[1].replace('%',''))\n\t\t\texcept ValueError:\n\t\t\t\tprint(\"TDAcc Assignment Error\")\n\t\t\t\tTDAcc = 0\n\t\telif tempName == 'TD Def.:':\n\t\t\ttry:\n\t\t\t\tTDDef = float(splitTemp[1].replace('%',''))\n\t\t\texcept ValueError:\n\t\t\t\tprint(\"TDDef Assignment Error\")\n\t\t\t\tTDDef = 0\n\t\telif tempName == 'Sub. Avg.:':\n\t\t\ttry:\n\t\t\t\tSubAvg = float(splitTemp[1].replace('%',''))\n\t\t\texcept ValueError:\n\t\t\t\tprint(\"SubAvg Assignment Error\")\n\t\t\t\tSubAvg = 0\n\t\telif tempName == 'Weight:':\n\t\t\ttry:\n\t\t\t\tWeight = float(splitTemp[1].replace('lbs.',''))\n\t\t\texcept ValueError:\n\t\t\t\tprint(\"Weight Assignment Error\")\n\t\t\t\tWeight = 0\n\t\t\t\n\t\tfighterNameLoc = fighterSoup.find(class_ = 'b-content__title-highlight')\n\t\tfighterName = fighterNameLoc.text\n\t\tfighterName = fighterName.rstrip('\\n').strip()\n\t\t\n\tif fighterName == 'Marian Reneau' or 'Cat Zingano' or 'Liz Carmouche' or 'Jennifer Maia' or 'Jessica Aguilar' or 'Jodie Esquibel':\n\t\tGender = 1\n\t\n\t\t\n\t\n\tfor i in historyList:\n\t\tfightCount += 1\n\t\t\t\n\tfighter = Fighter(fighterName, fightCount, Reach, DOB, SLpM, \n\t\t\t\t StrAcc, SApM, StrDef, TDAvg, TDAcc, TDDef, \n\t\t\t\t SubAvg, Weight, Stance, Gender)\n\treturn fighter\n\n\n#Follows link on sherdog to determine better name to use to pull betting/stat data\ndef nickname(fighter, nicks): \n\tfighterNick = fighter.Name #No nickname is assumed\n\t\n\tfor index,row in nicks.iterrows():\n\t\tif fighter.Name == row['Name']:\n\t\t\tfighterNick = row['Nickname']\n\t\t\t\n\treturn fighterNick\n\ndef realname(nickname, nicks): \n\tfor index,row in nicks.iterrows():\n\t\tif nickname == row['Nickname']:\n\t\t\tfighterName = row['Name']\n\t\t\t\n\treturn fighterName\n\n\ndef bettingData(bettingUrl, fighterList, nicks): \n\tbettingDict = dict.fromkeys(fighterList)\n\tbettingSoup = BeautifulSoup(bettingUrl.text, 'html5lib')\n\tnicksList = nicks['Nickname'].tolist()\n\tchecker = False\n\ttable = bettingSoup.find_all(class_='tw')\n\tfor i in table:\n\t\tparent = i.parent.parent.parent\n\t\ttry:\n\t\t\t\n\t\t\tif(parent.get(\"class\")[0] == 'odd' or parent.get(\"class\")[0] == 'even'):\n\t\t\t\t\n\t\t\t\tif(i.children):\n\t\t\t\t\tchild = i.children\n\t\t\t\t\t\n\t\t\t\t\tfor j in child: # Find fighter name and assign value\n\t\t\t\t\t\tif (j in fighterList):\n\t\t\t\t\t\t\tindex = fighterList.index(j)\n\t\t\t\t\t\t\tfoundName = True\n\t\t\t\t\t\tif (j in nicksList):\n\t\t\t\t\t\t\tindex = fighterList.index(realname(j,nicks)) # gets index from fighterlist\n\t\t\t\t\t\t\tfoundNick = True \t\t # using the found nickname\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\tif ('bestbet' in str(j) and foundName):\n\t\t\t\t\t\t\tbetVal = str(j)[-11:-7]\n\t\t\t\t\t\t\tbettingDict[fighterList[index]] = float(betVal)\n\t\t\t\t\t\t\tfoundName = False\n\t\t\t\t\t\telif ('bestbet' in str(j) and foundNick):\n\t\t\t\t\t\t\tbetVal = str(j)[-11:-7]\n\t\t\t\t\t\t\tbettingDict[fighterList[index]] = float(betVal)\n\t\t\t\t\t\t\tfoundNick = False\n\t\t\t\t\t\tif checker:\n\t\t\t\t\t\t\tbreak\n\t\texcept:\n\t\t\tpass # yeah maybe this should be addressed, but i'm not an html programmer\n\treturn bettingDict\n\n'''def bettingData2(bettingUrl, fighterList, nicks): fuck this shit, it already works\n\tbettingDict = dict.fromkeys(fighterList)\n\tbettingSoup = BeautifulSoup(bettingUrl.text, 'html5lib')\n\t\n\ttableParent = bettingSoup.find(class_='table-scroller')\n\ttable = tableParent.find(class_='odds-table')\n\tchildren = table.find_all(True, {\"class\":[\"odd\", \"even\"]})\n\t\n\tfoundName = False\n\tfoundNick = False\n\t\t\n\tfor i in children: # Find fighter name and assign value\n\t\tchild = i.children\n\t\tfor j in child:\n\t\t\tprint(j.text)\n\t\t\tif (j in fighterList):\n\t\t\t\tindex = fighterList.index(j)\n\t\t\t\tfoundName = True\n\t\t\t\tprint('Found, {0}'.format(j))\t\n\t\t\telif (j in nicks):\n\t\t\t\tindex = fighterList.index(realname(j,nicks)) # gets index from fighterlist\n\t\t\t\tfoundNick = True \t\t\n\t\t\t\tprint('Found, {0}'.format(j))\t\t\t\t\t\t\t\t# using the found nickname\n\t\t\t\n\t\t\tif ('bestbet' in str(j) and foundName):\n\t\t\t\tbetVal = str(j)[-11:-7]\n\t\t\t\tbettingDict[fighterList[index]] = float(betVal)\n\t\t\t\tprint('Bet value, {0}'.format(betVal))\n\t\t\t\tfoundName = False\n\t\t\telif ('bestbet' in str(j) and foundNick):\n\t\t\t\tbetVal = str(j)[-11:-7]\n\t\t\t\tbettingDict[fighterList[index]] = float(betVal)\n\t\t\t\tfoundNick = False\n\t\n\treturn bettingDict'''","sub_path":"WebScraping.py","file_name":"WebScraping.py","file_ext":"py","file_size_in_byte":6586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"53515855","text":"Talents = [\"Sing\", \"Dance\", \"Magic\", \"Act\", \"Flex\", \"Code\"]\nCandidates = [\"Aly\", \"Bob\", \"Cal\", \"Don\", \"Eve\", \"Fay\"]\nCandidateTalents = [[\"Flex\", \"Code\"], [\"Dance\", \"Magic\"], \n [\"Sing\", \"Magic\"], [\"Sing\", \"Dance\"], \n [\"Dance\", \"Act\", \"Code\"], [\"Act\", \"Code\"]]\n\n\ndef Good(Comb: list, candList: list, candTalents: list, AllTalents: list):\n \"\"\"선택된 참가자의 프로그램에 모든 재능이\n 방송 되는지 확인한다.\n\n Args:\n Comb (list): [선택 참가자]\n candList (list): [모든 참가자]\n candTalents (list): [참가자 각각의 재능]\n AllTalents (list): [참가자의 모든 재능]\n\n Returns:\n [bool]: [모든 재능을 포함했는지 확인합니다.]\n \"\"\"\n\n for tal in AllTalents: # 모든 재능 검사\n cover = False\n for cand in Comb: # 선택 참가자 1명씩 검사\n candTal = candTalents[candList.index(cand)]\n if tal in candTal: # 있으면 통과\n cover = True\n if not cover: # 없으면 False\n return False\n\n return True # 있으면 True\n\n\ndef Hire4Show(candList: list, candTalents: list, talentList: list):\n \"\"\"최소한의 후보를 출력합니다.\n\n Args:\n candList (list): [모든 참가자]\n candTalents (list): [모든 참가자의 재능]\n talentList (list): [재능]\n \"\"\"\n\n # prac 1\n # 제거 하는 함수 생성\n # candList, candTalents = check_overlap_talent(candList, candTalents)\n\n n = len(candList)\n print(n)\n hire = candList[:]\n \n # print(candList)\n\n # 모든 경우의 수\n for i in range(2**n):\n Combination = []\n num = i\n print(f\"num : {num}\")\n\n # 조합 뽑기\n for j in range(n):\n if (num % 2 == 1):\n print(f\"{num} % 2 == 1 : {num % 2 == 1}\")\n Combination = [candList[n-1-j]] + Combination\n num = num // 2\n \n # 모든 재능 만족하는지 확인\n if Good(Combination, candList, candTalents, talentList):\n if len(hire) > len(Combination):\n hire = Combination\n # print(Combination)\n\n print(\"Optimum Solution: \", hire)\n\n\nHire4Show(Candidates, CandidateTalents, Talents)","sub_path":"20171483_한태규_Puzzlie9/1234.py","file_name":"1234.py","file_ext":"py","file_size_in_byte":2304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"644605703","text":"import sqlite3\nimport functools\n\ndef dict_factory(cursor, row):\n d = {}\n for idx, col in enumerate(cursor.description):\n d[col[0]] = row[idx]\n return d\n\nclass SqliteDB:\n def __init__(self, database):\n self.database = database\n self.conn = None\n\n\n def tx(self, func):\n @functools.wraps(func)\n def wrapper_decorator(*args, **kwargs):\n self.open()\n try:\n with self.conn as tx:\n value = func(tx, *args, **kwargs)\n return value\n except sqlite3.Error as e:\n print(e)\n return False\n finally:\n self.close()\n return wrapper_decorator\n\n\n def open(self):\n try:\n conn = sqlite3.connect( self.database )\n conn.row_factory = dict_factory\n self.conn = conn\n except sqlite3.Error as e:\n print(\"Error connecting to database!\")\n\n\n def close(self):\n if self.conn:\n self.conn.close()\n\n\n\nimport dataclasses as dc\nfrom typing import List, Dict, Any\nfrom collections import namedtuple\nimport json\n\n\nclass BaseMetaData:\n def __init__(self, table, fields):\n self.table = table\n self.fields = fields\n self.form = { k : \"\" for k in self.fields }\n self.vals = [ \"?\" for k in range(1, 1+len(self.fields)) ]\n\n def __str__(self) : return f\"Model\\t: {self.table}\\nFields\\t: {self.fields}\\nForm\\t: {self.form}\\nVals\\t: {self.vals}\"\n def __repr__(self): return f\"Model: {self.table}\\nFields: {self.fields}\\nForm: {self.form}\\nVals: {self.vals}\"\n\n\ndef js_dumps(v): return v if isinstance(v, int) else json.dumps(v)\ndef js_loads(v): return v if isinstance(v, int) else json.loads(v)\n\n\n@dc.dataclass\nclass Model:\n ______db______ : Any\n\n def __post_init__(self):\n self.____db____ = SqliteDB( self.______db______ )\n\n\n @property\n def _meta(self):\n hidden_keys = ['____db____', '______db______']\n return BaseMetaData(\n table = self.__class__.__name__.title(),\n fields = list(filter(lambda v: v not in hidden_keys, self.__annotations__.keys() ))\n )\n\n\n\n def ____create____(self, tx, id=None,**kwargs):\n form = self._meta.form.copy()\n form.update( kwargs )\n query = f'insert into { self._meta.table } values (?,{ \",\".join( self._meta.vals ) });'\n inputs = [id] + [ js_dumps(form[k]) for k in self._meta.fields ]\n last_row_id = tx.execute(query, inputs)\n form.update({ \"id\": last_row_id })\n return form\n\n def ____update____(self, tx, **kwargs):\n form = kwargs.copy()\n del form['id']\n query = f'update { self._meta.table } set { \",\".join( [ f\"{k}=?\" for k in form.keys()] ) } where id=?;'\n inputs = [ js_dumps(form[k]) for k in form.keys() ] + [ int(kwargs['id']) ]\n return tx.execute(query, inputs)\n\n def ____delete____(self, tx, uid):\n query = f'delete from { self._meta.table } where id=?;'\n return tx.execute(query, [uid])\n\n def ____list_items____(self, tx):\n query = f'select * from { self._meta.table };'\n return tx.execute(query).fetchall()\n\n def ____get_item____(self, tx, uid):\n query = f'select * from { self._meta.table } where id=?;'\n return tx.execute(query, [uid]).fetchone()\n\n def ____create_table____(self, tx):\n query = f\"create table { self._meta.table } (id INTEGER PRIMARY KEY AUTOINCREMENT, { ','.join(self._meta.fields) })\"\n return tx.execute(query)\n\n def ____drop_table____(self, tx):\n query = f\"drop table { self._meta.table };\"\n return tx.execute(query)\n\n\n\n\n def create(self, id=None, **kwargs):\n status = self.____db____.tx( self.____create____ )(id, **kwargs)\n if status: return status\n return False\n\n\n def update(self, **kwargs):\n status = self.____db____.tx( self.____update____ )(**kwargs)\n if status: return True\n return False\n\n\n def delete(self, uid):\n status = self.____db____.tx( self.____delete____ )(uid)\n if status: return True\n return False\n\n\n def all(self):\n items = self.____db____.tx( self.____list_items____ )()\n RecordsAPI = namedtuple(\"Records\", ['list', 'dict'])\n objs = {}\n arr = []\n if items:\n for d in items:\n data = { k : js_loads(v) for k,v in d.items() }\n objs[ d['id'] ] = data\n arr.append(data)\n if items: return RecordsAPI(arr, objs)\n return RecordsAPI(arr, objs)\n\n def get(self, uid):\n items = self.____db____.tx( self.____get_item____ )(uid)\n if items:\n objs = { k : js_loads(v) for k,v in items.items() }\n\n return objs\n return {}\n\n def reset_table(self):\n try:\n self.drop_table()\n except Exception as e:\n pass\n if self.create_table(): return True\n\n\n def create_table(self):\n status = False\n try:\n status = self.____db____.tx( self.____create_table____ )()\n except Exception as e:\n pass\n if status: return True\n return False\n\n\n def drop_table(self):\n status = False\n try:\n status = self.____db____.tx( self.____drop_table____ )()\n except Exception as e:\n pass\n if status: return True\n return False\n","sub_path":"amdam/api/sqlow/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"184602567","text":"import gspread\nfrom oauth2client.service_account import ServiceAccountCredentials\nfrom django.http import JsonResponse, HttpResponse\nfrom itertools import izip, chain\nfrom collections import OrderedDict\nimport json\nfrom OpenSSL import SSL\n\nfrom gdoc_keys import google_spreadsheet_keys\n\ndef gdoc_auth():\n #auth for fall grid 2015\n json_key = json.load(open('google-api-cred.json'))\n scope = ['https://spreadsheets.google.com/feeds']\n\n credentials = ServiceAccountCredentials.from_json_keyfile_name('google-api-cred.json', scope)\n\n gcred = gspread.authorize(credentials)\n gcred.login()\n return gcred\n\n\n\ndef test_parse(output_key, worksheet_id_string, *worksheet_name_string):\n authenticate = gdoc_auth()\n\n doc = authenticate.open_by_key(worksheet_id_string)\n\n # test the list of args\n if len(worksheet_name_string) < 2:\n sheet_name = worksheet_name_string[0]\n sheet = doc.worksheet(sheet_name)\n get_data_as_dict = sheet.get_all_records()\n t_data = tuple(get_data_as_dict)\n else:\n t_combined = []\n\n for sheet_name in worksheet_name_string:\n sheet = doc.worksheet(sheet_name)\n get_data_as_dict = sheet.get_all_records()\n t_combined.append(get_data_as_dict)\n \n # flatten the list\n t_data = [region for show in t_combined for region in show]\n \n data = {\n output_key: t_data\n }\n\n return data\n\n\ndef test_schedule_with_parse(requst):\n return JsonResponse(test_parse('schedule', google_spreadsheet_keys.master_schedule_key, 'data'), safe=False)\n\n\ndef test_football_with_parse(request):\n return JsonResponse(test_parse('football', google_spreadsheet_keys.football_key, 'data'), safe=False)\n\n\ndef test_fall_grid_with_parse(request):\n grid_sheet_list = ['t_Arizona','t_Bay_Area','t_Colorado','t_Los_Angeles','t_Oregon','t_Utah','t_Washington','t_WSU']\n return JsonResponse(test_parse('events', google_spreadsheet_keys.fall_grid_key, *grid_sheet_list), safe=False)\n\n\ndef test_winter_grid_with_parse(request):\n grid_sheet_list = ['t_Arizona','t_Bay_Area','t_Colorado','t_Los_Angeles','t_Oregon','t_Utah','t_Washington','t_WSU'] \n return JsonResponse(test_parse('events', google_spreadsheet_keys.winter_grid_key, *grid_sheet_list), safe=False)\n\n\ndef test_spring_grid_with_parse(request):\n grid_sheet_list = ['t_Arizona','t_Bay_Area','t_Colorado','t_Los_Angeles','t_Oregon','t_Utah','t_Washington','t_WSU'] \n return JsonResponse(test_parse('events', google_spreadsheet_keys.spring_grid_key, *grid_sheet_list), safe=False)\n\n# '''causes the showcode to be keys. Test only'''\n# def get_fall_grid_keys(request):\n# grid_id = '18Y3kocQXntrb2GAif8ngUKSye-SgLgdrhlV__lyjlxE'\n# az_list = parse_gdoc_transpose('t_Arizona', grid_id)\n# ba_list = parse_gdoc_transpose('t_Bay_Area', grid_id)\n# co_list = parse_gdoc_transpose('t_Colorado', grid_id)\n# la_list = parse_gdoc_transpose('t_Los_Angeles', grid_id)\n# or_list = parse_gdoc_transpose('t_Oregon', grid_id)\n# ut_list = parse_gdoc_transpose('t_Utah', grid_id)\n# wa_list = parse_gdoc_transpose('t_Washington', grid_id)\n# wsu_list = parse_gdoc_transpose('t_WSU', grid_id)\n\n# t_fall_list = tuple(az_list + ba_list + co_list + la_list + or_list + ut_list + wa_list + wsu_list)\n\n# showcode_key_list = []\n\n# for obj in t_fall_list:\n# for k, v in obj.items():\n# #check every key,value in each dictionary\n# if v == 'X' or v == '':\n# #delete the key if it's value is X or \"\"\n# del obj[k]\n# if k == 'SHOW CODE':\n# #save the value if the key SHOW CODE exists\n# showcode_key_list.append(obj[k])\n\n# new_list = OrderedDict(zip(showcode_key_list, t_fall_list))\n\n# data = {\n# #'events': t_fall_list,\n# #'more keys': showcode_key_list,\n# 'combined': new_list,\n# }\n\n# return JsonResponse(data)\n\n# '''for testing only '''\n# def get_budgets(request):\n# authenticate = gdoc_auth()\n# doc = authenticate.open_by_key('1L35wDl_gQm0VYjuiab1bf_EHwu-DZx6bRGMr5jmjMfM')\n# sheet = doc.worksheet('budget_json')\n\n# #list index is by columns\n# values_list = tuple(sheet.get_all_values())\n\n# data = {\n# 'budget': values_list\n# }\n# return JsonResponse(data)","sub_path":"minions/views_google_api_dev.py","file_name":"views_google_api_dev.py","file_ext":"py","file_size_in_byte":4140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"524827448","text":"# encoding: utf-8\n\nfrom sqlalchemy import create_engine, MetaData, Table, Column, TIMESTAMP\nimport datetime\nimport pandas as pd\nfrom WindPy import w\nimport os\nfrom data_access import db_utilities as du\nfrom data_access import spider_api_dce as dce\nfrom data_access import spider_api_sfe as sfe\nfrom data_access import spider_api_czce as czce\nimport data_access.table_options_mktdata_daily as table_options\nimport data_access.table_futures_mktdata_daily as table_futures\n\nw.start()\n# tradetype = 0 # 0:期货,1:期权\nbeg_date = datetime.date(2017, 1, 1)\nend_date = datetime.date(2017, 12, 4)\n\nengine = create_engine('mysql+pymysql://root:liz1128@101.132.148.152/mktdata',\n echo=False)\nconn = engine.connect()\nmetadata = MetaData(engine)\noptions_mktdata_daily = Table('options_mktdata_daily', metadata, autoload=True)\nfutures_mktdata_daily = Table('futures_mktdata_daily', metadata, autoload=True)\n# futures_institution_positions = Table('futures_institution_positions', metadata, autoload=True)\n\n\ndate_range = w.tdays(beg_date, end_date, \"\").Data[0]\n\ni = 0\nwhile i < len(date_range):\n # crawd and insert into db 5-day data at a time\n begdate = date_range[i]\n if i+5 < len(date_range): enddate = date_range[i+5]\n else : enddate = date_range[-1]\n print(begdate,enddate)\n # # dce option data (type = 1), day\n # ds = dce.spider_mktdata_day(begdate, enddate, 1)\n # for dt in ds.keys():\n # data = ds[dt]\n # if len(data) == 0: continue\n # db_data = table_options.dce_day(dt, data)\n # if len(db_data) == 0 : continue\n # try:\n # conn.execute(options_mktdata_daily.insert(), db_data)\n # print('inserted into data base succefully')\n # except Exception as e:\n # print(dt)\n # print(e)\n # continue\n # # dce option data (type = 1), night\n # ds = dce.spider_mktdata_night(begdate, enddate, 1)\n # for dt in ds.keys():\n # data = ds[dt]\n # if len(data) == 0: continue\n # db_data = table_options.dce_night(dt, data)\n # if len(db_data) == 0: continue\n # try:\n # conn.execute(options_mktdata_daily.insert(), db_data)\n # print('inserted into data base succefully')\n # except Exception as e:\n # print(dt)\n # print(e)\n # continue\n # # czce option data\n # ds = czce.spider_option(begdate, enddate)\n # for dt in ds.keys():\n # data = ds[dt]\n # if len(data) == 0: continue\n # db_data = table_options.czce_daily(dt, data)\n # if len(db_data) == 0: continue\n # try:\n # conn.execute(options_mktdata_daily.insert(), db_data)\n # print('inserted into data base succefully')\n # except Exception as e:\n # print(dt)\n # print(e)\n # continue\n # dce futures data (type = 0),, day\n ds = dce.spider_mktdata_day(begdate, enddate, 0)\n for dt in ds.keys():\n data = ds[dt]\n db_data = table_futures.dce_day(dt,data)\n if len(db_data) == 0 : continue\n try:\n conn.execute(futures_mktdata_daily.insert(), db_data)\n except Exception as e:\n print(dt)\n print(e)\n continue\n ds = dce.spider_mktdata_night(begdate, enddate, 0)\n for dt in ds.keys():\n data = ds[dt]\n db_data = table_futures.dce_night(dt,data)\n if len(db_data) == 0 : continue\n try:\n conn.execute(futures_mktdata_daily.insert(), db_data)\n except Exception as e:\n print(dt)\n print(e)\n continue\n i += 6\n\n","sub_path":"data_access/craw_data_historical.py","file_name":"craw_data_historical.py","file_ext":"py","file_size_in_byte":3643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"259951333","text":"from fractions import Fraction\n\nclass Simplex(object):\n def __init__(self, num_vars, constraints, objective_function):\n \"\"\"\n num_vars: Number of variables\n\n constraints: A list of strings representing constraints\n each variable should start with the coefficient, then x followed by a underscore\n and a number\n eg of constraints\n ['1x_1 + 2x_2 >= 4', '2x_3 + 3x_1 <= 5', 'x_3 + 3x_2 = 6']\n Note that in x_num, num should not be more than num_vars.\n Also single spaces should be used in expressions.\n\n objective_function: should be a tuple with first element\n either 'min' or 'max', and second element be the equation\n eg\n ('min', '2x_1 + 4x_3 + 5x_2')\n\n For solution finding algorithm uses two-phase simplex method\n \"\"\"\n self.num_vars = num_vars\n self.objective = objective_function[0]\n self.objective_function = objective_function[1]\n self.coeff_matrix, self.r_rows, self.num_s_vars, self.num_r_vars = self.construct_matrix_from_constraints(constraints)\n self.basic_vars = [0 for i in range(len(self.coeff_matrix))]\n self.phase1()\n r_index = self.num_r_vars + self.num_s_vars\n\n for i in self.basic_vars:\n if i > r_index:\n raise ValueError(\"Infeasible solution\")\n\n self.delete_r_vars()\n\n if 'min' in self.objective.lower():\n self._solution = self.objective_minimize()\n\n else:\n self._solution = self.objective_maximize()\n self.optimize_val = self.coeff_matrix[0][-1]\n\n def solution(self):\n r = 'Solution:\\n'\n for key, value in self._solution.items():\n r += key + ' = ' + str(value) + '\\n'\n\n return r + self.objective + ' = ' + str(self.optimize_val)\n\n def construct_matrix_from_constraints(self, constraints):\n num_s_vars = 0 # number of slack and surplus variables\n num_r_vars = 0 # number of additional variables to balance equality and less than equal to\n\n for expression in constraints:\n if '>=' in expression:\n num_s_vars += 1\n elif '<=' in expression:\n num_s_vars += 1\n num_r_vars += 1\n elif '=' in expression:\n num_r_vars += 1\n\n total_vars = self.num_vars + num_s_vars + num_r_vars\n\n coeff_matrix = [[Fraction(\"0\") for i in range(total_vars + 1)] for j in range(len(constraints) + 1)]\n s_index = self.num_vars\n r_index = self.num_vars + num_s_vars\n r_rows = [] # stores the non -zero index of r\n\n for i in range(1, len(constraints) + 1):\n constraint = constraints[i - 1].split(' ')\n\n for j in range(len(constraint)):\n if '_' in constraint[j]:\n coeff, index = constraint[j].split('_')\n coeff = coeff[:-1]\n\n if coeff is '':\n coeff = 1\n if constraint[j - 1] is '-':\n coeff = '-' + coeff\n\n coeff_matrix[i][int(index) - 1] = Fraction(coeff)\n\n elif constraint[j] == '<=':\n coeff_matrix[i][s_index] = Fraction(\"1\") # add surplus variable\n s_index += 1\n\n elif constraint[j] == '>=':\n coeff_matrix[i][s_index] = Fraction(\"-1\") # slack variable\n coeff_matrix[i][r_index] = Fraction(\"1\") # r variable\n s_index += 1\n r_index += 1\n r_rows.append(i)\n\n elif constraint[j] == '=':\n coeff_matrix[i][r_index] = Fraction(\"1\") # r variable\n r_index += 1\n r_rows.append(i)\n\n coeff_matrix[i][-1] = Fraction(constraint[-1])\n\n return coeff_matrix, r_rows, num_s_vars, num_r_vars\n\n def phase1(self):\n # Objective function here is minimize r1+ r2 + r3 + ... + rn\n r_index = self.num_vars + self.num_s_vars\n for i in range(r_index, len(self.coeff_matrix[0])-1):\n self.coeff_matrix[0][i] = Fraction(\"-1\")\n\n coeff_0 = 0\n for i in self.r_rows:\n self.coeff_matrix[0] = add_row(self.coeff_matrix[0], self.coeff_matrix[i])\n self.basic_vars[i] = r_index\n r_index += 1\n\n s_index = self.num_vars\n for i in range(1, len(self.basic_vars)):\n if self.basic_vars[i] == 0:\n self.basic_vars[i] = s_index\n s_index += 1\n\n # Run the simplex iterations\n key_column = max_index(self.coeff_matrix[0])\n\n while self.coeff_matrix[0][key_column] > 0:\n key_row = self.find_key_row(key_column)\n self.basic_vars[key_row] = key_column\n pivot = self.coeff_matrix[key_row][key_column]\n self.normalize_to_pivot(key_row, pivot)\n self.make_key_column_zero(key_column, key_row)\n\n key_column = max_index(self.coeff_matrix[0])\n\n def find_key_row(self, key_column):\n min_val = float(\"inf\")\n min_i = 0\n for i in range(1, len(self.coeff_matrix)):\n if self.coeff_matrix[i][key_column] > 0:\n val = self.coeff_matrix[i][-1] / self.coeff_matrix[i][key_column]\n if val < min_val:\n min_val = val\n min_i = i\n\n if min_val == float(\"inf\"):\n raise ValueError(\"Unbounded solution\")\n if min_val == 0:\n print(\"Degeneracy\")\n return min_i\n\n def normalize_to_pivot(self, key_row, pivot):\n for i in range(len(self.coeff_matrix[0])):\n self.coeff_matrix[key_row][i] /= pivot\n\n def make_key_column_zero(self, key_column, key_row):\n num_columns = len(self.coeff_matrix[0])\n for i in range(len(self.coeff_matrix)):\n if i != key_row:\n factor = self.coeff_matrix[i][key_column]\n for j in range(num_columns):\n self.coeff_matrix[i][j] -= self.coeff_matrix[key_row][j] * factor\n\n def delete_r_vars(self):\n for i in range(len(self.coeff_matrix)):\n non_r_length = self.num_vars + self.num_s_vars + 1\n length = len(self.coeff_matrix[i])\n while length != non_r_length:\n del self.coeff_matrix[i][non_r_length-1]\n length -= 1\n\n def update_objective_function(self):\n objective_function_coeffs = self.objective_function.split()\n for i in range(len(objective_function_coeffs)):\n if '_' in objective_function_coeffs[i]:\n coeff, index = objective_function_coeffs[i].split('_')\n coeff = coeff[:-1]\n\n if coeff is '':\n coeff = 1\n if objective_function_coeffs[i - 1] is not '-':\n coeff = '-' + coeff\n\n self.coeff_matrix[0][int(index)-1] = Fraction(coeff)\n\n def check_alternative_solution(self):\n for i in range(len(self.coeff_matrix[0])):\n if self.coeff_matrix[0][i] and i not in self.basic_vars[1:]:\n # alternative solution exists\n break\n\n def objective_minimize(self):\n self.update_objective_function()\n\n for row, column in enumerate(self.basic_vars[1:]):\n if self.coeff_matrix[0][column] != 0:\n self.coeff_matrix[0] = add_row(self.coeff_matrix[0], multiply_const_row(-self.coeff_matrix[0][column], self.coeff_matrix[row+1]))\n\n key_column = max_index(self.coeff_matrix[0])\n\n while self.coeff_matrix[0][key_column] > 0:\n key_row = self.find_key_row(key_column = key_column)\n self.basic_vars[key_row] = key_column\n pivot = self.coeff_matrix[key_row][key_column]\n self.normalize_to_pivot(key_row, pivot)\n self.make_key_column_zero(key_column, key_row)\n\n key_column = max_index(self.coeff_matrix[0])\n\n solution = {}\n for i, var in enumerate(self.basic_vars[1:]):\n if var < self.num_vars:\n solution['x_'+str(var+1)] = self.coeff_matrix[i+1][-1]\n\n for i in range(0, self.num_vars):\n if i not in self.basic_vars[1:]:\n solution['x_'+str(i+1)] = Fraction(\"0\")\n self.check_alternative_solution()\n return solution\n\n def objective_maximize(self):\n self.update_objective_function()\n\n for row, column in enumerate(self.basic_vars[1:]):\n if self.coeff_matrix[0][column] != 0:\n self.coeff_matrix[0] = add_row(self.coeff_matrix[0], multiply_const_row(-self.coeff_matrix[0][column], self.coeff_matrix[row+1]))\n\n key_column = min_index(self.coeff_matrix[0])\n\n while self.coeff_matrix[0][key_column] < 0:\n key_row = self.find_key_row(key_column = key_column)\n self.basic_vars[key_row] = key_column\n pivot = self.coeff_matrix[key_row][key_column]\n self.normalize_to_pivot(key_row, pivot)\n self.make_key_column_zero(key_column, key_row)\n\n key_column = min_index(self.coeff_matrix[0])\n\n solution = {}\n for i, var in enumerate(self.basic_vars[1:]):\n if var < self.num_vars:\n solution['x_'+str(var+1)] = self.coeff_matrix[i+1][-1]\n\n for i in range(0, self.num_vars):\n if i not in self.basic_vars[1:]:\n solution['x_'+str(i+1)] = Fraction(\"0\")\n\n self.check_alternative_solution()\n\n return solution\n\ndef add_row(row1, row2):\n return [row1[i] + row2[i] for i in range(len(row1))]\n\ndef max_index(row):\n max_i = 0\n for i in range(len(row) - 1):\n if row[i] > row[max_i]:\n max_i = i\n\n return max_i\n\ndef multiply_const_row(const, row):\n return [const * i for i in row]\n\ndef min_index(row):\n min_i = 0\n for i in range(len(row)):\n if row[min_i] > row[i]:\n min_i = i\n\n return min_i\n","sub_path":"simplex.py","file_name":"simplex.py","file_ext":"py","file_size_in_byte":10028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"495774157","text":"import sys\n# フィボナッチ数列を計算する\n\n\n# 漸化式通り\ndef fib_base(n):\n if n <= 1:\n return n\n return fib_base(n - 2) + fib_base(n - 1)\n\n\n# メモ化\ndef fib_memo(n):\n memo = [-1] * (n + 1)\n\n def _fib(n):\n if n <= 1:\n return n\n if memo[n] != -1:\n return memo[n]\n memo[n] = _fib(n - 2) + _fib(n - 1)\n return memo[n]\n\n return _fib(n)\n\n\n# dp\ndef fib_dp(n):\n dp = [-1] * (n + 1)\n if n <= 1:\n return n\n dp[0] = 0\n dp[1] = 1\n\n def _fib(n):\n for i in range(2, n + 1):\n dp[i] = dp[i - 2] + dp[i - 1]\n return dp[n]\n return _fib(n)\n\n\nn = int(sys.argv[1])\nprint(fib_base(n))\nprint(fib_memo(n))\nprint(fib_dp(n))\n","sub_path":"snippets/fibonacci/fibonacci.py","file_name":"fibonacci.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"242330384","text":"class Global_Authed():\n '''\n \n '''\n\n Global_Authed_Users = [\n 'mach2simultaions'\n ]\nclass Global_Banned():\n '''\n \n '''\n Global_Banned_Users = [\n 'streamelements',\n \n ]\n Global_Banned_Words = [\n 'gifted',\n ]\n Global_Loved_Users = [\n 'ashley_pie200',\n 'nandos4',\n 'jddotst'\n \n ]\n \n \nclass Global_Conf():\n Global_Commands = [\n \"!clip\",\n \"!orange\",\n \"!purp\",\n \"!hc @Jddotst\"\n \n ]\n Langs = [\n 'ru',\n 'yi'\n ]\n\n","sub_path":"Global_Conf.py","file_name":"Global_Conf.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"576229362","text":"from sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report\nfrom sklearn.datasets import make_blobs\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef sigmoid_activation(x):\n return 1.0 / (1 + np.exp(-x))\n\ndef sigmoid_deriv(x):\n return x * (1 - x)\n\n\ndef predict(X,W):\n preds = sigmoid_activation(X.dot(W))\n\n preds[preds<=0.5]=0\n preds[preds>0.5]=1\n\n return preds\n\ndef next_batch(X,y,batchSize):\n for i in np.arange(0,X.shape[0],batchSize):\n yield(X[i:i+batchSize],y[i:i+batchSize])\n\n\n(X, y) = make_blobs(n_samples=1000, n_features=2, centers=2,cluster_std=1.5, random_state=1)\n\ny = y.reshape((y.shape[0], 1))\n\nX = np.c_[X, np.ones((X.shape[0]))]\n\n\n(trainX, testX, trainY, testY) = train_test_split(X, y,test_size=0.5, random_state=42)\n\n\nepochs=100\nalpha=0.01\nbatch_size=32\ngamma = 0.9\n\nprint(\"[INFO] training...\")\nW = np.random.randn(X.shape[1], 1)\nV = np.zeros_like(W)\nlosses = []\n\n\nfor epoch in np.arange(0,epochs):\n epochLoss = []\n for (batchX, batchY) in next_batch(trainX, trainY, batch_size):\n\n W_ahead= -gamma*V+W\n preds = sigmoid_activation(batchX.dot(W_ahead))\n error = preds - batchY\n epochLoss.append(np.sum(error ** 2))\n\n d = error * sigmoid_deriv(preds)\n gradient = batchX.T.dot(d)\n\n V=gamma*V+alpha*gradient\n W-=V\n loss = np.average(epochLoss)\n losses.append(loss)\n\n if epoch == 0 or (epoch + 1) % 5 == 0:\n print(\"[INFO] epoch={}, loss={:.7f}\".format(int(epoch + 1),loss))\n\nprint(\"[INFO] evaluating...\")\npreds = predict(testX, W)\nprint(classification_report(testY, preds))\n\nplt.style.use(\"ggplot\")\nplt.figure()\nplt.title(\"Data\")\nplt.scatter(testX[:, 0], testX[:, 1], marker=\"o\", c=testY[:, 0], s=30)\n\n\nplt.style.use(\"ggplot\")\nplt.figure()\nplt.plot(np.arange(0, epochs), losses)\nplt.title(\"Training Loss\")\nplt.xlabel(\"Epoch #\")\nplt.ylabel(\"Loss\")\n\n\nplt.show()\n\n\n\n\n","sub_path":"SB_PRACTICE/CH9/SGD_Nesterow.py","file_name":"SGD_Nesterow.py","file_ext":"py","file_size_in_byte":2038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"378755250","text":"from sklearn.linear_model import LogisticRegression\nimport mglearn\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nX, y = mglearn.datasets.make_forge()\n\nclf = LogisticRegression(C=0.01).fit(X, y)\n\nx_min, x_max = X[:, 0].min(), X[:, 0].max() \ny_min, y_max = X[:, 1].min(), X[:, 1].max() \n\nxx = np.linspace(x_min, x_max, 1000)\nyy = np.linspace(y_min, y_max, 1000)\n\nX1, X2 = np.meshgrid(xx, yy)\nX_grid = np.c_[X1.ravel(), X2.ravel()]\n\ndecision_values = clf.decision_function(X_grid)\n\nplt.contour(X1, X2, decision_values.reshape(X1.shape), levels=[0])\nplt.plot(X[y==0][:,0], X[y==0][:,1], \"o\")\nplt.plot(X[y==1][:,0], X[y==1][:,1], \"*\")\n\nplt.show()","sub_path":"liner_logistic_clasifer_graph.py","file_name":"liner_logistic_clasifer_graph.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"119177474","text":"import ovh\nimport config\nfrom dbdriver import select\n\nconfig = config.get('ovh')\n\nclient = ovh.Client(\n endpoint='ovh-eu',\n application_key=config['application_key'],\n application_secret=config['application_secret'],\n consumer_key=config['consumer_key']\n)\n\ndef send(dest, message):\n user = select('users', {'name': dest})[0]\n\n phone = user['phone']\n account = user['sms_account']\n\n try:\n result = client.post('/sms/'+account+'/jobs',\n message=message,\n receivers=[phone],\n senderForResponse=True\n )\n return result, None\n except ovh.exceptions.APIError as e:\n print (e)\n return None, e\n","sub_path":"api/sms.py","file_name":"sms.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"360726929","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Nov 3 18:44:36 2016\r\n\r\nCall Adobe Illustrator to convert .svg to .eps\r\n\r\n@author: Edward\r\n\"\"\"\r\nimport os\r\nimport sys\r\nimport signal\r\nimport subprocess\r\nimport time\r\nfrom pdb import set_trace\r\n\r\njsx_file_str_AI_CS6 = \"\"\"\r\nfunction exportFigures_AI_CS6(sourceFile, targetFile, exportType, ExportOpts) {\r\n if (sourceFile){ // if not an empty string\r\n var fileRef = new File(sourceFile)\r\n var sourceDoc = app.open(fileRef); // returns the document object\r\n } else { // for empty string, use current active document\r\n sourceDoc = app.activeDocument();\r\n }\r\n var newFile = new File(targetFile) // newly saved file\r\n\r\n switch(exportType){\r\n case 'png':\r\n if (ExportOpts == null) {\r\n var ExportOpts = new ExportOptionsPNG24()\r\n ExportOpts.antiAliasing = true;\r\n ExportOpts.transparency = true;\r\n ExportOpts.saveAsHTML = true;\r\n }\r\n // Export as PNG\r\n sourceDoc.exportFile(newFile, ExportType.PNG24, ExportOpts);\r\n case 'tiff':\r\n if (ExportOpts == null) {\r\n var ExportOpts = new ExportOptionsTIFF();\r\n ExportOpts.resolution = 600;\r\n ExportOpts.byteOrder = TIFFByteOrder.IBMPC;\r\n ExportOpts.IZWCompression = false;\r\n ExportOpts.antiAliasing = true\r\n }\r\n sourceDoc.exportFile(newFile, ExportType.TIFF, ExportOpts);\r\n case 'svg':\r\n if (ExportOpts == null) {\r\n var ExportOpts = new ExportOptionsSVG();\r\n ExportOpts.embedRasterImages = true;\r\n ExportOpts.embedAllFonts = true;\r\n ExportOpts.fontSubsetting = SVGFontSubsetting.GLYPHSUSED;\r\n }\r\n // Export as SVG\r\n sourceDoc.exportFile(newFile, ExportType.SVG, ExportOpts);\r\n case 'eps':\r\n if (ExportOpts == null) {\r\n var ExportOpts = new EPSSaveOptions();\r\n ExportOpts.cmykPostScript = true;\r\n ExportOpts.embedAllFonts = true;\r\n }\r\n // Export as EPS\r\n sourceDoc.saveAs(newFile, ExportOpts);\r\n }\r\n // Close the file after saving. Simply save another copy, do not overwrite\r\n sourceDoc.close(SaveOptions.DONOTSAVECHANGES);\r\n}\r\n\r\n// Use the function to convert the files\r\nexportFigures_AI_CS6(sourceFile=\"{format_source_file}\", targetFile=\"{format_target_file}\", exportType=\"eps\", ExportOpts=null)\r\n// exportFigures_AI_CS6(sourceFile=arguments[0], targetFile=arguments[1], exportType=arguments[2])\r\n\"\"\"\r\n\r\n\r\ndef svg2eps_ai(source_file, target_file, \\\r\n illustrator_path=\"D:/Edward/Software/Adobe Illustrator CS6/Support Files/Contents/Windows/Illustrator.exe\",\\\r\n jsx_file_str = jsx_file_str_AI_CS6, DEBUG=False):\r\n \"\"\"Use Adobe Illustrator to convert svg to eps\"\"\"\r\n # Change the strings\r\n jsx_file_str = jsx_file_str.replace('{format_source_file}', source_file)\r\n jsx_file_str = jsx_file_str.replace('{format_target_file}', target_file).replace('\\\\','/')\r\n tmp_f = os.path.join(os.path.dirname(target_file), \"tmp.jsx\")\r\n #set_trace()\r\n #print(tmp_f)\r\n tmp_osa = None\r\n f = open(tmp_f, 'w')\r\n f.write(jsx_file_str)\r\n f.close()\r\n\r\n # Remove previous target file if already existed\r\n if os.path.isfile(target_file):\r\n os.remove(target_file)\r\n\r\n running_os = sys.platform[:3].lower()\r\n if running_os == 'win':\r\n cmd = \" \".join(['\"'+illustrator_path+'\"', '-run', '\"'+tmp_f+'\"'])\r\n pro = subprocess.Popen(cmd, stdout=subprocess.PIPE)\r\n # continuously check if new files are updated\r\n time.sleep(5.0)\r\n sleep_iter = 5.0\r\n max_sleep_iter = 40\r\n while not os.path.isfile(target_file):\r\n time.sleep(1.0)\r\n sleep_iter = sleep_iter + 1.0\r\n if sleep_iter > max_sleep_iter:\r\n break\r\n pro.kill()\r\n elif running_os == 'dar': # mac\r\n applescript = '''tell application \"Adobe Illustrator\"\r\n activate\r\n do javascript \"#include {}\"\r\n quit\r\n end tell\r\n '''.format(tmp_f)\r\n args = [item for x in [(\"-e\", l.strip()) for l in applescript.split('\\n') if l.strip() != ''] for item in x]\r\n proc = subprocess.Popen([\"osascript\"] + args, stdout=subprocess.PIPE)\r\n progname = proc.stdout.read().strip()\r\n sys.stdout.write(str(progname))\r\n else:\r\n raise(Exception(\"Unrecognized system\"))\r\n\r\n os.remove(tmp_f)\r\n\r\ndef svg2eps_inkscape(source_file, target_file, \\\r\n inkscape_path='\"D:\\\\Edward\\\\Software\\\\inkscape-0.91-1-win64\\\\inkscape.exe\"'):\r\n \"\"\"Use inkscape to convert svg to eps\"\"\"\r\n # cmd = \"inkscape in.svg -E out.eps --export-ignore-filters --export-ps-level=3\"\r\n cmd = inkscape_path+\" \"+source_file+\" --export-eps=\"+target_file +\" --export-ignore-filters --export-ps-level=3\"\r\n print(cmd) # Problem: text was not kept as text, but converted into paths\r\n pro = subprocess.Popen(cmd, stdout=subprocess.PIPE)\r\n #subprocess.check_call([inkscape_path, source_file, '-E', target_file])\r\n print(pro.stdout)\r\n \r\n#def svg2eps_cloudconvert(source_file, target_file):\r\n# import cloudconvert\r\n# api = cloudconvert.Api('5PGyLT7eAn0yLbnBU3G-7j1JLFWTfcnFUk6x7k_lhuwzioGwqO7bVQ-lJNunsDkrr9fL1JDdjdVog6iDZ31yIw')\r\n# process = api.convert({\"input\": \"upload\",\r\n# \"file\": open('R:/temp.svg', 'rb'),\r\n# \"inputformat\": \"svg\",\r\n# \"outputformat\": \"eps\",\r\n# })\r\n# process.wait()\r\n# process.download()\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n source_file = '/Volumes/SD/temp.svg'\r\n target_file = '/Volumes/SD/temp.eps'\r\n illustrator_path=\"D:/Edward/Software/Adobe Illustrator CS6/Support Files/Contents/Windows/Illustrator.exe\"\r\n javascript_path=\"/Volumes/SD/tmp.jsx\"\r\n svg2eps_ai(source_file, target_file)\r\n # svg2eps_inkscape(source_file, target_file)\r\n","sub_path":"PySynapse/util/svg2eps.py","file_name":"svg2eps.py","file_ext":"py","file_size_in_byte":5996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"291418279","text":"import os\nimport sys\nimport json\nimport argparse\nfrom pathlib import Path\n\nparser = argparse.ArgumentParser(description=\"Read CSV files from the specified folder (inside the data folder)\")\nparser.add_argument('--date',\n type=str,\n nargs='?',\n default='0717-1217',\n action='store',\n help='choose the date to analyse (eg. 0517 or 1217')\nparser.add_argument('--sub_num',\n type=str,\n nargs='?',\n default='13000',\n action='store',\n help='choose the number of top subreddits (by number of comments) to take into account (eg. 1000 or 15000')\nargs = parser.parse_args()\n\ndate = str(args.date)\nif args.sub_num == 'all':\n sub_num = 'all'\nelse:\n sub_num = 'top' + str(args.sub_num)\n\nwk_dir = os.path.dirname(os.path.realpath('__file__'))\n\np = Path(wk_dir).parents[2]\nos.chdir(str(p) + '/data/' + date + '/subreddit_comment_pair/' + sub_num)\nnum_files = len(os.listdir(os.getcwd()))\n\nnum_comments = dict()\n\nfor i in range(num_files):\n in_file = str(i).zfill(12)\n print(\"Processing file: {}\".format(in_file))\n with open(in_file, 'r') as file:\n for line in file:\n subreddits = json.loads(line)\n subreddit = subreddits['subreddit']\n if subreddit not in num_comments:\n num_comments[subreddit] = 0\n elif num_comments[subreddit] <= 3:\n num_comments[subreddit] += 1\n body = subreddits['body']\n out_name = subreddit + '.txt'\n with open(out_name, 'a+') as out:\n out.write(body)\n","sub_path":"scripts/ug4/final submission/convert_comments_to_text_files.py","file_name":"convert_comments_to_text_files.py","file_ext":"py","file_size_in_byte":1707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"342521824","text":"class Solution:\n def func_3sum(self, list_enter, target):\n res = []\n for i in range(len(list_enter)-2):\n res_single = self.func_2sum(list_enter[i+1:], target - list_enter[i])\n for tuple in res_single:\n tuple.append(list_enter[i])\n if tuple not in res:\n res.append(tuple)\n\n def func_2sum(self, list_enter, target):\n dirc = {}\n res = []\n for i, num in enumerate(list_enter):\n if (target - num) not in dirc.keys():\n dirc[num] = i\n else:\n res_single = [list_enter[dirc[target-num]], num]\n res_single.sort()\n dirc.pop(target - num)\n if res_single not in res:\n res.append(res_single)\n return res\n\n\na = Solution()\nprint(a.func_2sum([1, 2, 2, 1, 3, 0, 4, -1], 3))\n\n\n\n\n\n","sub_path":"leetcode/三数之和为0.py","file_name":"三数之和为0.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"385502006","text":"from sqlalchemy import *\nfrom migrate import *\n\n\nfrom migrate.changeset import schema\npre_meta = MetaData()\npost_meta = MetaData()\nmigration_tmp = Table('migration_tmp', pre_meta,\n Column('id', Integer, primary_key=True, nullable=False),\n Column('post_date', DateTime),\n Column('description', String),\n Column('pic_path', String),\n Column('handle', String),\n)\n\nbuying = Table('buying', post_meta,\n Column('id', Integer, primary_key=True, nullable=False),\n Column('brand', String),\n Column('model', String),\n Column('price', Float),\n Column('size', Float),\n Column('email', String),\n Column('handle', String),\n)\n\ncomments = Table('comments', post_meta,\n Column('id', Integer, primary_key=True, nullable=False),\n Column('handle', String(length=64)),\n Column('comment_date', DateTime),\n Column('body', String(length=140)),\n Column('release_id', Integer),\n)\n\nselling = Table('selling', post_meta,\n Column('id', Integer, primary_key=True, nullable=False),\n Column('description', String(length=140)),\n Column('sale_date', DateTime),\n Column('price', Float),\n Column('new', Boolean),\n Column('email', String(length=128)),\n Column('size', Float),\n Column('handle', String),\n Column('sold', Boolean),\n)\n\nposts = Table('posts', post_meta,\n Column('id', Integer, primary_key=True, nullable=False),\n Column('post_date', DateTime),\n Column('description', String(length=512)),\n Column('user_id', Integer),\n Column('handle', String(length=64)),\n Column('pic_path', String(length=512)),\n)\n\n\ndef upgrade(migrate_engine):\n # Upgrade operations go here. Don't create your own engine; bind\n # migrate_engine to your metadata\n pre_meta.bind = migrate_engine\n post_meta.bind = migrate_engine\n pre_meta.tables['migration_tmp'].drop()\n post_meta.tables['buying'].create()\n post_meta.tables['comments'].create()\n post_meta.tables['selling'].create()\n post_meta.tables['posts'].columns['handle'].create()\n\n\ndef downgrade(migrate_engine):\n # Operations to reverse the above upgrade go here.\n pre_meta.bind = migrate_engine\n post_meta.bind = migrate_engine\n pre_meta.tables['migration_tmp'].create()\n post_meta.tables['buying'].drop()\n post_meta.tables['comments'].drop()\n post_meta.tables['selling'].drop()\n post_meta.tables['posts'].columns['handle'].drop()\n","sub_path":"db_repository/versions/019_migration.py","file_name":"019_migration.py","file_ext":"py","file_size_in_byte":2379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"490238630","text":"#!/usr/bin/python3\n\nimport subprocess\n\n# Add comments for all changes\n# Use library information to fix types\n# Build into single decompile, filter recompile, analyze script\n # On compilation, open vim to errors for manual fixing\n# Iterate error and code deletion\n# Show iterating code deletion using library it doesn't know\n# Figure out what libraries to add\n\nglobal code\nglobal fixes\nglobal filename\n\nfilename = \"grep.c\"\nfixes = 0\n\ndef main():\n global filename\n #read_file(\"test_decomp.c\")\n read_file(filename)\n fix_types()\n fix_utypes()\n filter_functions()\n filter_structs()\n filter_typedefs() # This needs to replace not filter\n #filter_comments()\n filter_library_calls() # This needs to be automated\n filter_random() # Needs to be more robust\n #filter_structs()\n #filter_functions()\n #compile-delete-loop()\n filter_whitespace()\n add_libraries()\n #print_code()\n output_code()\n recompile()\n recompile_info()\n\ndef add_libraries():\n global fixes\n fixes += 3\n\n code.insert(0, \"#include \")\n code.insert(0, \"#include \")\n code.insert(0, \"#include \")\n code.insert(0, \"#include \")\n\ndef filter_random():\n global code\n global fixes\n\n filter_whitespace()\n\n print(\"\")\n print(\"Filtering randoms\")\n\n temp = []\n\n i = 0\n while i < len(code):\n if \"FUN\" in code[i] and \"{\" in code[i+1] and \"0x0\" in code[i+2] and \"(*\" in code[i+2] and \"return;\" in code[i+3] and \"}\" in code[i+4]:\n print(\"[*] Removing strange function pointer return\")\n fixes += 1 # Fixes\n i += 5\n else:\n temp.append(code[i])\n i += 1\n code = temp\n\n temp = []\n i = 0\n for line in code:\n if \"__isoc99_scanf\" in line:\n var = line[line.index(\",\"):line.index(\");\")]\n print(\"Value is: \" + str(var))\n temp.append(\"scanf(\" + var[1:] + \");\")\n fixes += 1 # Fixes\n else:\n temp.append(line)\n code = temp\n\n\ndef filter_library_calls():\n print(\"\")\n print(\"Filtering library call functions\")\n filter_function(\"puts\")\n filter_function(\"free\")\n filter_function(\"putchar\")\n filter_function(\"strlen\")\n filter_function(\"malloc\")\n filter_function(\"realloc\")\n filter_function(\"__isoc99_scanf\")\n\ndef fix_utypes():\n fix_type(\"uint\", \"int\")\n fix_type(\"ulong\", \"long\")\n fix_type(\" true \", \" 1 \")\n fix_type(\" false \", \" 0 \")\n fix_type(\"code *\", \"fun_ptr *\")\n\ndef fix_types(): # Add comments describing fixes\n global code\n global fixes\n\n print(\"Fixing undefined types\")\n i = 0\n\n for line in code:\n if \"typedef\" in line:\n old = str(line.split(\" \")[-1].strip(\";\"))\n new = str(\" \".join(line.split(\" \")[1:-3]))\n\n print(\"[*] Replacing \" + old + \" with \" + new)\n fix_type(old + \" \", new + \" \")\n fix_type(\"(\" + old + \")\", \"(\" + new + \")\")\n\n fixes += 1 # Fixes\n\n i += 1\n elif \"eh_frame_hdr\" in line:\n code = code[i:]\n break\n\ndef fix_type(old, new):\n global code\n global fixes\n\n temp = []\n\n for line in code:\n temp.append(line.replace(old, new))\n if line.replace(old, new) != line:\n fixes += 1\n\n code = temp\n\ndef filter_functions():\n print(\"\")\n print(\"Filtering functions\")\n filter_function(\"_init\")\n filter_function(\"printf\")\n filter_function(\"__cxa_finalize\")\n filter_function(\"_start\")\n filter_function(\"deregister_tm_clones\")\n filter_function(\"register_tm_clones\")\n filter_function(\"frame_dummy\")\n filter_function(\"__libc_csu_init\")\n filter_function(\"__do_global_dtors_aux\")\n filter_function(\"__libc_csu_fini\")\n filter_function(\"_fini\")\n #filter_function(\"__stack_chk_fail\")\n\ndef filter_structs():\n print(\"\")\n print(\"Filtering structs\")\n filter_struct(\"eh_frame_hdr\")\n filter_struct(\"fde_table_entry\")\n filter_struct(\"Elf_ProgramHeaderType\")\n filter_struct(\"Elf64_Phdr\")\n filter_struct(\"Elf_SectionHeaderType\")\n filter_struct(\"Elf64_Shdr\")\n filter_struct(\"Elf64_DynTag\")\n filter_struct(\"Elf64_Dyn\")\n filter_struct(\"Elf64_Sym\")\n filter_struct(\"Elf64_Rela\")\n filter_struct(\"Elf64_Ehdr\")\n filter_struct(\"evp_pkey_ctx_st\")\n\ndef filter_typedefs():\n global code\n global fixes\n\n temp = []\n for i in range(0, len(code)):\n if \"typedef struct\" not in code[i]:\n temp.append(code[i])\n else:\n fixes += 1\n code = temp\n\ndef filter_function(name):\n global code\n global fixes\n print(\"[*] Removing function \" + name)\n\n found = False\n for i in range(0, len(code)):\n if name in code[i] and \"{\" in code[i+2]:\n found = True\n break\n fixes += 1\n if found:\n k = 0\n j = i + 3\n for j in range(i+3, len(code)):\n if \"{\" in code[j]:\n k += 1\n if \"}\" in code[j]:\n if k == 0:\n break\n else:\n k -= 1\n\n #print(\"Removed: \" + str(code[i:j]))\n temp1 = code[:i]\n temp2 = code[j+1:]\n code = temp1 + temp2\n\ndef filter_struct(name):\n global code\n global fixes\n\n print(\"[*] Removing struct \" + name)\n fixes += 1\n\n for i in range(0, len(code)):\n if name in code[i] and \"{\" in code[i]:\n break\n k = 0\n for j in range(i+1, len(code)):\n if \"{\" in code[j]:\n k += 1\n if \"}\" in code[j]:\n if k == 0:\n break\n else:\n k -= 1\n\n #print(\"Removed: \" + str(code[i:j]))\n temp1 = code[:i]\n temp2 = code[j+1:]\n code = temp1 + temp2\n\ndef filter_comments():\n global code\n\n temp = []\n for i in range(0, len(code)):\n if \"//\" not in code[i]:\n temp.append(code[i])\n code = temp\n\ndef filter_whitespace():\n global code\n\n temp = []\n for i in range(0, len(code)):\n if code[i] != \"\":\n temp.append(code[i])\n if code[i] == \"}\":\n temp.append(\"\")\n code = temp\n\ndef read_file(name):\n global code\n arr = \"\"\n with open(name, \"r\") as f:\n arr = f.readlines()\n arr2 = []\n for line in arr:\n arr2.append(line.replace(\"\\n\", \"\"))\n code = arr2\n\ndef print_code():\n global code\n print(\"=\"*80)\n for line in code:\n print(line)\n print(\"=\"*80)\n\ndef output_code():\n global code\n print(\"\")\n print(\"Saving code to file: output_decomp.c\")\n with open(\"output_decomp.c\", \"w\") as f:\n for line in code:\n f.write(line + \"\\n\")\n print(\"done\")\n\ndef recompile_info():\n global filename\n result = subprocess.run([\"gcc\", filename, \"-o\", \"output_recomp2\"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n errors = []\n warnings = []\n for line in result.stderr.decode().split(\"\\n\"):\n if \"ls\" in line and \"error\" in line:\n errors.append(line)\n if \"ls\" in line and \"warning\" in line:\n warnings.append(line)\n \n print(\"\")\n print(\"Original has \" + str(len(warnings)) + \" warnings\")\n print(\"Original has \" + str(len(errors)) + \" errors\")\n\ndef recompile():\n global fixes\n\n result = subprocess.run([\"gcc\", \"output_decomp.c\", \"-o\", \"output_recomp\"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n errors = []\n warnings = []\n a = 0\n b = 0\n c = 0\n d = 0\n e = 0\n f = 0\n g = 0\n h = 0\n i = 0\n j = 0\n k = 0\n l = 0\n m = 0\n for line in result.stderr.decode().split(\"\\n\"):\n if \"output\" in line and \"error\" in line:\n if \"assignment to expression\" in line:\n #errors.append(line[line.find(\" \"):])\n a += 1\n elif \"too many arguments\" in line:\n b += 1\n elif \"too few arguments\" in line:\n c += 1\n elif \"conflicting types\" in line:\n d += 1\n elif \"undeclared\" in line and \"DAT_\" in line:\n print(line)\n e += 1\n elif \"undeclared\" in line:\n f += 1\n elif \"void value not ignored\" in line:\n g += 1\n elif \"unknown type name\" in line:\n h += 1\n elif \"cast specifies array type\" in line:\n i += 1\n elif \"expected \" in line and \"before\" in line:\n j += 1\n elif \"invalid use of void\" in line:\n k += 1\n elif \"invalid operands to binary\" in line:\n l += 1\n elif \"request for member\" in line:\n m += 1\n else:\n errors.append(line)\n if \"output\" in line and \"warning\" in line:\n warnings.append(line)\n \n errors.sort(key=lambda x: x[x.find(\" \"):])\n\n print(\"=\"*80)\n print(\"\")\n\n for line in errors:\n print(line)\n\n print(\"\")\n print(\"=\"*80)\n\n print(\"\")\n print(\"Assignment to expression with array type: \" + str(a))\n print(\"Too many arguments: \" + str(b))\n print(\"Too few arguments: \" + str(c))\n print(\"Conflicting types: \" + str(d))\n print(\"DAT_* is undeclared: \" + str(e))\n print(\"Other is undeclared: \" + str(f))\n print(\"Void value not ignored: \" + str(g))\n print(\"Unknown type name: \" + str(h))\n print(\"Casts to array: \" + str(i))\n print(\"Expected ) or ; before something: \" + str(j))\n print(\"Invalid use of void expression: \" + str(k))\n print(\"Invalid operands to binary: \" + str(l))\n print(\"Request for member not in struct: \" + str(m))\n print(\"Other errors: \" + str(len(errors)))\n print(\"\")\n print(\"Found \" + str(len(warnings)) + \" warnings\")\n print(\"\")\n print(\"Made \" + str(fixes) + \" fixes\")\n\nmain()\n","sub_path":"filter.py","file_name":"filter.py","file_ext":"py","file_size_in_byte":9821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"380193001","text":"from subprocess import call\nfrom time import sleep\n\nwhile (True):\n\n\tfor i in range(1,10):\n\t\tcall([\"phantomjs\", \"Channel.js\", str(i)], shell=True)\n\t\n\tprint(\"waiting.. 10min\")\n\tsleep(10*60) # [s] \n\n","sub_path":"downloader W.py","file_name":"downloader W.py","file_ext":"py","file_size_in_byte":196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"63337319","text":"import datetime\nimport TipoConta\nimport ConnSQLite\nfrom FormatData import FormatData\n\n\nclass TipoContaDAO:\n\t__conn = None\n\t__cursor = None\n\t__schema = \"financeiro\"\n\t__tabela = \"tipos_conta\"\n\t__pk = \"cod_tipo_conta\"\n\n\tdef __init__(self):\n\t\tself.__conn = ConnSQLite.ConnSQLite()\n\t\tself.__conn.getConn(self.__schema, self.__tabela, self.__pk)\n\t\tself.__cursor = self.__conn.cursor()\n\n# ==================================== CRUD ====================================\n# ==============================================================================\n\n\tdef insert(self, tipoConta):\n\t\tsql = \\\n\t\t\t\"\"\"\n\t\t\tINSERT INTO\n\t\t\t\t\"\"\" + self.__tabela + \"\"\"\n\t\t\t\t(\n\t\t\t\t\tTIPO_CONTA,\n\t\t\t\t\tCOD_PAGADOR,\n\t\t\t\t\tCOD_TIPO_GASTO,\n\t\t\t\t\tTIPO_CONTA_ATIVO,\n\t\t\t\t\tDT_INICIO,\n\t\t\t\t\tDT_FINAL,\n\t\t\t\t\tCOD_TIPO_CONTA\n\t\t\t\t)\n\t\t\t\tVALUES\n\t\t\t\t\t(?, ?, ?, ?, ?, ?, ?);\n\t\t\"\"\"\n\t\tself.setStatement(tipoConta, sql)\n\n\tdef select(self, pk):\n\t\tsql = \\\n\t\t\t\"\"\"\n\t\t\tSELECT\n\t\t\t\t\t*\n\t\t\t\tFROM\n\t\t\t\t\t\"\"\" + self.__tabela + \"\"\"\n\t\t\t\tWHERE\n\t\t\t\t\t\"\"\" + self.__pk + \"\"\" = ?\n\t\t\t;\n\t\t\"\"\"\n\n\t\to = TipoConta.TipoConta()\n\n\t\ttry:\n\t\t\tself.__cursor.execute(sql, (pk, ))\n\t\t\tfor array in self.__cursor.fetchall():\n\t\t\t\to = o.povoarObj(array)\n\t\texcept ValueError:\n\t\t\tpass\n\t\treturn o\n\n\tdef update(self, tipoConta):\n\t\tsql = \\\n\t\t\t\"\"\"\n\t\t\tUPDATE\n\t\t\t\t\t\"\"\" + self.__tabela + \"\"\"\n\t\t\t\tSET\n\t\t\t\t\tTIPO_CONTA = ?,\n\t\t\t\t\tCOD_PAGADOR = ?,\n\t\t\t\t\tCOD_TIPO_GASTO = ?,\n\t\t\t\t\tTIPO_CONTA_ATIVO = ?,\n\t\t\t\t\tDT_INICIO = ?,\n\t\t\t\t\tDT_FINAL = ?\n\t\t\t\tWHERE\n\t\t\t\t\tCOD_TIPO_CONTA = ?\n\t\t\t;\n\t\t\"\"\"\n\t\tself.setStatement(tipoConta, sql)\n\n\tdef delete(self, pk):\n\t\tsql = \\\n\t\t\t\"\"\"\n\t\t\tDELETE\n\t\t\t\tFROM\n\t\t\t\t\t\"\"\" + self.__tabela + \"\"\"\n\t\t\t\tWHERE\n\t\t\t\t\t\"\"\" + self.__pk + \"\"\" = ?\n\t\t\t;\n\t\t\"\"\"\n\t\tself.__cursor.execute(sql, (pk, ))\n\n\tdef __getList(self, sql):\n\t\tlista = []\n\n\t\ttry:\n\t\t\tself.__cursor.executeList(sql)\n\t\t\tfor array in self.__cursor.fetchall():\n\t\t\t\tlista.append(self.select(array[0]))\n\t\texcept ValueError:\n\t\t\tpass\n\t\treturn lista\n\n\tdef setStatement(self, tipoConta, sql):\n\n\t\tif tipoConta.getCOD_TIPO_CONTA() == 0:\n\t\t\ttipoConta.setCOD_TIPO_CONTA(self.__conn.autoNumeracao())\n\t\t\n\t\tcontext = \\\n\t\t\tstr(tipoConta.getTIPO_CONTA()),\\\n\t\t\tstr(tipoConta.getCOD_PAGADOR()),\\\n\t\t\tstr(tipoConta.getCOD_TIPO_GASTO()),\\\n\t\t\tstr(tipoConta.getTIPO_CONTA_ATIVO()),\\\n\t\t\tFormatData.para_JDate(tipoConta.getDT_INICIO()),\\\n\t\t\tFormatData.para_JDate(tipoConta.getDT_FINAL()),\\\n\t\t\tstr(tipoConta.getCOD_TIPO_CONTA())\n\n\t\tself.__cursor.execute(sql, context)\n\n# ==================================== CRUD ====================================\n# ==============================================================================\n\n\tdef getLista(self):\n\t\tsql = \\\n\t\t\t\"\"\"\n\t\t\tSELECT\n\t\t\t\t\t*\n\t\t\t\tFROM\n\t\t\t\t\ttipos_conta\n\t\t\t\tORDER BY\n\t\t\t\t\ttipo_conta\n\t\t\t;\n\t\t\"\"\"\n\t\treturn self.__getList(sql)\n\n\tdef listaNaoConstam(self, lista):\n\t\t\n\t\tstrNaoConsta = str(lista)\n\t\tstrNaoConsta = strNaoConsta.replace(\"[\", \"\")\n\t\tstrNaoConsta = strNaoConsta.replace(\"]\", \"\")\n\t\t\n\t\tsql = \\\n\t\t\t\"\"\"\n\t\t\t\n\t\t\tSELECT\n\t\t\t\t\t*\n\t\t\t\tFROM\n\t\t\t\t\ttipos_conta\n\t\t\t\tWHERE\n\t\t\t\t\ttipo_conta_ativo = -1\n\t\t\t\t\tAND\n\t\t\t\t\tcod_tipo_conta NOT IN\n\t\t\t\t\t(\"\"\" + strNaoConsta + \"\"\")\n\t\t\t\tORDER BY\n\t\t\t\t\ttipo_conta\n\t\t\t;\n\t\t\"\"\"\n\t\treturn self.__getList(sql)\n\n\tdef listaAtivos(self):\n\t\tsql = \\\n\t\t\t\"\"\"\n\t\t\tSELECT\n\t\t\t\t\t*\n\t\t\t\tFROM\n\t\t\t\t\ttipos_conta\n\t\t\t\tWHERE\n\t\t\t\t\ttipo_conta_ativo = -1\n\t\t\t\tORDER BY\n\t\t\t\t\ttipo_conta\n\t\t\t;\n\t\t\"\"\"\n\t\treturn self.__getList(sql)\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"cgi-bin/TipoContaDAO.py","file_name":"TipoContaDAO.py","file_ext":"py","file_size_in_byte":3308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"373451719","text":"#!/usr/bin/env python\nimport sys\nimport subprocess\nimport getopt\n\ndef main():\n # set up variables\n # global something\n\n # set up our commandline options\n try:\n opts, args = getopt.getopt(sys.argv[1:],\"n:u:m:h\",[\"namespace=\",\"username=\",\"master=\",\"help\"])\n except getopt.GetoptError as err:\n print(err)\n usage()\n sys.exit(2)\n\n # loop over the arguments\n for o, a in opts:\n if o in (\"-n\",\"--namespace\"):\n namespaces.append(a)\n elif o in (\"-u\",\"--username\"):\n username = a\n elif o in (\"-m\",\"--master\"):\n master = a\n elif o in (\"-h\",\"--help\"):\n usage()\n else:\n assert False, \"Unknown option\"\n\n # main code logic\n for item in list:\n try:\n if not doSomething(username, item):\n doSomethingElse(username, item)\n else:\n print(username+\" is already defined in \"+item)\n except subprocess.CalledProcessError as e:\n print(\"Call failed:\")\n print(e)\n\ndef doSomething(u,ns):\n # kubectl get serviceaccount -n kubesystem\n # subprocess.check_call([\"ssh\",master,\"ls\",\"-l\"])\n return False\n\ndef usage():\n print(\"The following options are supported:\")\n print(\"-f|--force Push without checking the checksums\")\n print(\"-m|--master The kubernetes master\")\n print(\"-p|--path The path at the end to copy the files to\")\n print(\"-u|--user The user on the remote system to log in as\")\n exit(0)\n\nif __name__ == \"__main__\": main()\n","sub_path":"skeleton.py","file_name":"skeleton.py","file_ext":"py","file_size_in_byte":1558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"171419086","text":"from speedling import facility\nfrom speedling import inv\nfrom speedling import util\nfrom speedling import conf\nfrom osinsutils import localsh\nfrom speedling.srv import haproxy\nimport os\nimport re\nimport time\nimport speedling\n\nfrom osinsutils import cfgfile\n\nimport logging\nimport urllib\n\n\nLOG = logging.getLogger(__name__)\n\n\n# innodb_flush_log_at_trx_commit 1\n# less fsync/fdatasync call\n# with replication it is only an issue of all node\n# losses power within seconds\n\n# innodb_flush_method O_DIRECT\n# depending on your system, but it might be terrible option.\n# Typically the data written with O_DIRECT\n# are directly written to the disk (bypassing os page cache)\n# if you have good disk or controller it can ensure power loss\n# tolerence for data which is just in his cache\n\ndef etc_my_cnf_d_mariadb_openstack_cnf(seed=False):\n # TODO: create a monitoring script for lock waits\n peers = get_peer_info('cluster')\n big = False\n mysql_conf = \"\"\"[mysqld]\ndefault-storage-engine = innodb\ninnodb_file_per_table\ncollation-server = utf8_general_ci\ninit-connect = 'SET NAMES utf8'\ncharacter-set-server = utf8\nskip-name-resolve\nmax_connections = 15360\ninnodb_flush_log_at_trx_commit = 0\ninnodb_flush_method = O_DIRECT\nslow-query-log = 1\nslow-query-log-file = /var/log/mariadb/slow_query.log\nlong_query_time = 0.1\n\"\"\"\n\n# innodb_log_file_size changes requires manual file deletion,\n# inorder to enusre you know what you are doing\n# on new system it can be configure easly before the first start\n\n# TODO: increase the wsresp/galera related sizes\n# for tolerate longer memeber outage!\n\n# TODO: configure `point in time recovery` able setup\n\n# NOTE: thread pools can be good idea, if you have lot of idle connection\n\n if big:\n mysql_conf += \"\"\"innodb_log_file_size = 1500M\ninnodb_log_files_in_group = 2\ninnodb_buffer_pool_size = 16G\n\"\"\"\n if (len(peers) > 1):\n mysql_conf += \"\"\"\ninnodb_autoinc_lock_mode = 2\nbinlog_format=ROW\nwsrep_provider=/usr/lib64/galera/libgalera_smm.so\nwsrep_provider_options=\"gcache.size=300M; gcache.page_size=300M\"\n\"\"\"\n if not seed:\n mysql_conf += \"\"\"\n wsrep_cluster_address=\"gcomm://{nodes}\"\n\"\"\".format(nodes=','.join(n['addr'] for n in peers))\n\n return mysql_conf\n\n\ndef etc_systemd_system_mariadb_service_d_limits_conf(): return {\n 'Service': {'LimitNOFILE': 16384}\n }\n\n\n# TODO: reconsider xinitd version or creating an another way\ndef etc_systemd_system_mysqlchk_socket(): return {\n 'Socket': {'ListenStream': 9200,\n 'Accept': 'yes'},\n 'Unit': {'Description': 'Galera monitoring socket for proxies'},\n 'Install': {'WantedBy': 'sockets.target'}\n }\n\n\ndef etc_systemd_system_mysqlchk_service(): return {\n 'Service': {'ExecStart': '-/usr/bin/clustercheck',\n 'StandardInput': 'socket'},\n 'Unit': {'Description': 'Galera monitoring service for proxies'}\n }\n\n\ndef etc_sysconfig_clustercheck():\n password = util.get_keymgr()('mysql', 'clustercheckuser')\n return \"\"\"MYSQL_USERNAME=\"clustercheckuser\"\nMYSQL_PASSWORD={pwd}\nMYSQL_HOST=localhost\nMYSQL_PORT=\"3306\"\nERR_FILE=\"/tmp/clustercheckuser_42328756\"\nAVAILABLE_WHEN_DONOR=0\nAVAILABLE_WHEN_READONLY=0\nDEFAULTS_EXTRA_FILE=/etc/my.cnf\"\"\".format(pwd=util.cmd_quote(password))\n\n\ndef mariadb_etccfg(services):\n cfgfile.ensure_path_exists('/etc/systemd/system/mariadb.service.d')\n cfgfile.ini_file_sync('/etc/systemd/system/mariadb.service.d/limits.conf',\n etc_systemd_system_mariadb_service_d_limits_conf())\n cfgfile.ini_file_sync('/etc/systemd/system/mysqlchk@.service', etc_systemd_system_mysqlchk_service())\n cfgfile.ini_file_sync('/etc/systemd/system/mysqlchk.socket', etc_systemd_system_mysqlchk_socket())\n cfgfile.content_file('/etc/sysconfig/clustercheck', etc_sysconfig_clustercheck(),\n mode=0o640)\n\n\ndef mariadb_pkgs():\n return {'mariadb-server-galera'}\n\n\ndef do_mariadb():\n localsh.run(\"systemctl enable mysqlchk.socket && systemctl start mysqlchk.socket\")\n localsh.run(\"systemctl start mariadb\")\n localsh.run(\"mysql <<<\\\"SHOW GLOBAL STATUS LIKE 'wsrep_%';\\\" >/tmp/wsrep_init_state \")\n\n\ndef do_mariadb_cfg(nodes, seed=False):\n cfgfile.content_file('/etc/my.cnf.d/mariadb_openstack.cnf',\n etc_my_cnf_d_mariadb_openstack_cnf(seed), mode=0o644)\n\n\ndef do_create_clustr_user():\n passwd = util.get_keymgr()('mysql', 'clustercheckuser')\n pwd = passwd.replace('\\\\', '\\\\\\\\').replace(\"'\", r\"\\'\").replace('$', '\\$')\n sql = \"GRANT PROCESS ON *.* TO 'clustercheckuser'@'localhost' IDENTIFIED BY '{pwd}'\".format(pwd=pwd)\n # $ for shell, the others for mysql\n retry = 1024 # wating for mariadb become ready\n while True:\n try:\n script = 'mysql -u root < 1:\n check = ' check inter 3s on-marked-down shutdown-sessions port 9200'\n else:\n check = ''\n for i in ci:\n servers.append(' '.join((i['hostname'], i['addr'] + ':' + str(i['port']),\n 'backup' + check)))\n\n if 'haproxy' in gconf['global_service_flags']:\n haproxy.add_listener('mariadb', {\n 'bind': '*:13306',\n 'stick': 'on dst',\n 'stick-table': 'type ip size 1024',\n 'option': ['tcpka', 'httpchk'],\n 'timeout': {'client': '128m',\n 'server': '128m'},\n 'server': servers})\n\n # clustercheckuser allowed from localhost only\n util.bless_with_principal(h, [('mysql', 'clustercheckuser')])\n\n\ndef register():\n mariadb = {'component': 'mariadb',\n 'deploy_source': 'pkg',\n 'services': {'mariadb': {'deploy_mode': 'standalone'}},\n 'variant': 'galera',\n 'compose': mariadb_compose,\n 'pkg_deps': mariadb_pkgs,\n 'cfg_step': mariadb_etccfg,\n 'goal': task_mariadb_steps}\n facility.register_component(mariadb)\n\n\nregister()\n","sub_path":"speedling/srv/mariadb.py","file_name":"mariadb.py","file_ext":"py","file_size_in_byte":10655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"322808841","text":"# Copyright © 2017-2018 Cedric Legrand\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 (including the next\n# paragraph) shall be included in all copies or substantial portions of the\n# 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\nfrom reflex.parser.ast import (Reference, Array, ArrayAccess, BuiltinType, FunctionType,\n FunctionDeclaration, FunctionCall, Symbol, Struct)\n\nclass SourceWriter:\n def __init__(self, ast, f):\n self.file = sys.stdout if f == '-' else open(f, 'w')\n\n self.indent = 0\n self.in_import = 0\n self.types = {\n 'str': 'char*',\n 'any': 'void*',\n 'void': 'void',\n 'char': 'int8_t',\n 'int': 'int32_t',\n 'int8': 'int8_t',\n 'int16': 'int16_t',\n 'int32': 'int32_t',\n 'int64': 'int64_t',\n 'uint8': 'uint8_t',\n 'uint16': 'uint16_t',\n 'uint32': 'uint32_t',\n 'uint64': 'uint64_t',\n 'size': 'size_t',\n 'bool': 'uint8_t',\n }\n\n self.control_structures = {\n 'if': 'if',\n 'elif': 'else if',\n 'else': 'else',\n 'while': 'while',\n }\n\n self.file.write('#include \\n#include \\n')\n\n for node in ast:\n self.write(node)\n\n if f != '-':\n self.file.close()\n\n def write(self, node):\n func = getattr(self, 'write' + type(node).__name__)\n func(node)\n\n def write_indent(self):\n i = 0\n while i < self.indent:\n self.file.write(' ')\n i += 1\n\n def write_value(self, node):\n if type(node.decl) is FunctionDeclaration:\n parent = node.parent\n while type(parent) is Reference or type(parent) is Symbol:\n parent = parent.parent\n if type(parent) is not FunctionCall:\n self.file.write('&')\n return\n if node.ref_offset == -1:\n self.file.write('&')\n else:\n i = node.ref_offset\n while i > 0:\n self.file.write('*')\n i -= 1\n if node.cast is not None:\n self.file.write('(')\n self.write_type_prefix(node.cast)\n self.write(node.cast)\n self.file.write(')')\n if node.is_type and node.is_const:\n self.file.write(' const')\n\n def writeInclude(self, inc):\n self.write_indent()\n self.file.write('#include <')\n self.write(inc.lib)\n self.file.write('.h>\\n')\n\n def writeImport(self, node):\n self.in_import += 1\n for sym in node.syms:\n self.write(sym)\n self.in_import -= 1\n\n def writeBuiltinType(self, typ):\n self.file.write(self.types[typ.name])\n if typ.is_const:\n self.file.write(' const')\n\n def writeReference(self, ref):\n self.write(ref.child)\n if ref.is_type:\n self.file.write('*')\n if ref.is_const:\n self.file.write(' const')\n\n def writeArray(self, arr):\n self.write(arr.child)\n if arr.length is None:\n self.file.write('*')\n if self.array_needs_parens(arr):\n self.file.write('(')\n\n def is_dynamic_array(self, node):\n typ = type(node)\n return (typ is Array and node.length is None) or typ is Reference\n\n def array_needs_parens(self, node):\n if self.is_dynamic_array(node):\n return False\n typ = type(node.parent)\n if typ is not Array and typ is not Reference:\n return False\n return self.is_dynamic_array(node.parent)\n\n def write_declaration_post(self, node):\n typ = type(node)\n if typ is FunctionType:\n self.file.write(')(')\n i = 0\n while i < len(node.args):\n if i is not 0:\n self.file.write(', ')\n self.write(node.args[i])\n i += 1\n self.file.write(')')\n elif typ is Array or typ is Reference:\n if self.array_needs_parens(node):\n self.file.write(')')\n if typ is Array and node.length is not None:\n self.file.write('[')\n self.write(node.length)\n self.file.write(']')\n self.write_declaration_post(node.child)\n\n def writeFunctionType(self, node):\n self.write_type_prefix(node.ret)\n self.write(node.ret)\n self.file.write('(*')\n\n def write_type_prefix(self, typ):\n while type(typ) is Reference:\n typ = typ.child\n if type(typ) is Symbol:\n typ = typ.decl\n prefix = {\n Struct: 'struct',\n }.get(type(typ))\n if prefix is not None:\n self.file.write(prefix + ' ')\n\n def writeDeclaration(self, decl):\n self.write_type_prefix(decl.typ)\n self.write(decl.typ)\n if decl.sym is not None:\n self.file.write(' ')\n self.write(decl.sym)\n self.write_declaration_post(decl.typ)\n\n def writeVariableDeclaration(self, decl):\n self.write(decl.decl)\n if decl.assign is not None:\n self.write(decl.assign)\n\n def writeArgumentDefinitionList(self, args):\n if len(args) == 0:\n self.file.write('void')\n else:\n i = 0\n count = len(args)\n while i < count:\n self.writeDeclaration(args[i])\n i += 1\n if i < count:\n self.file.write(', ')\n\n def writeFunctionPrototype(self, proto):\n self.write_type_prefix(proto.typ)\n self.write(proto.typ)\n self.file.write(' ')\n self.write(proto.sym)\n self.file.write('(')\n self.writeArgumentDefinitionList(proto.args)\n self.file.write(\")\")\n\n def writeFunctionDeclaration(self, fun):\n self.write_indent()\n self.writeFunctionPrototype(fun)\n self.file.write(';\\n')\n\n def writeFunctionDefinition(self, fun):\n if self.in_import > 0:\n self.writeFunctionDeclaration(fun.proto)\n return\n\n self.write_indent()\n self.file.write(\"\\n\")\n self.writeFunctionPrototype(fun.proto)\n self.file.write(\"\\n{\\n\")\n\n self.indent += 1\n for instruction in fun.body:\n self.write(instruction)\n self.indent -= 1\n\n self.file.write(\"}\\n\")\n\n def writeStatement(self, stmt):\n self.write_indent()\n self.write(stmt.expr)\n self.file.write(';\\n')\n\n def writeExpression(self, expr):\n if expr.is_parenthesised:\n self.file.write('(')\n i = 0\n count = len(expr.contents)\n while i < count:\n self.write(expr.contents[i])\n i += 1\n if i < count:\n self.file.write(' ')\n if expr.is_parenthesised:\n self.file.write(')')\n\n def writeAssignment(self, assign):\n self.file.write(' ')\n if assign.operator is not None:\n self.write(assign.operator)\n self.file.write('= ')\n self.write(assign.expr)\n\n def writeVariableAssignment(self, assign):\n self.write(assign.var)\n self.write(assign.assign)\n\n def writeFunctionCall(self, call):\n if call.is_cast:\n self.file.write('((')\n self.write_type_prefix(call.sym)\n self.write(call.sym)\n self.file.write(')')\n self.write(call.args[0])\n self.file.write(')')\n else:\n self.write(call.sym)\n self.file.write('(')\n i = 0\n count = len(call.args)\n while i < count:\n self.write(call.args[i])\n i += 1\n if i < count:\n self.file.write(', ')\n self.file.write(')')\n\n def writeArrayAccess(self, arr):\n self.write_value(arr)\n decl = arr.decl.typ\n sym = arr\n while type(decl) is Array or type(decl) is Reference or BuiltinType('str') == decl:\n if type(sym) is ArrayAccess:\n sym = sym.child\n decl = decl.child\n cur = sym.parent\n decl = decl.parent\n while type(decl) is Array or type(decl) is Reference or BuiltinType('str') == decl:\n if type(decl) is Reference:\n rdecl = decl\n while type(rdecl) is Reference:\n rdecl = rdecl.parent\n if type(rdecl) is Array:\n self.file.write('*')\n elif type(cur) is ArrayAccess:\n if type(decl.parent) is Reference:\n self.file.write('(')\n cur = cur.parent\n decl = decl.parent\n self.write(sym)\n decl = arr.decl.typ\n while type(decl) is Reference:\n decl = decl.child\n while type(arr) is ArrayAccess or type(decl) is Reference:\n if type(decl) is not Reference and type(arr) is ArrayAccess:\n if type(decl.parent) is Reference:\n self.file.write(')')\n self.file.write('[')\n self.write(arr.idx)\n self.file.write(']')\n arr = arr.child\n decl = decl.child\n\n def writeControlStructure(self, struct):\n self.write_indent()\n self.file.write(self.control_structures[struct.name])\n if struct.cond is not None:\n self.file.write(' (')\n self.write(struct.cond)\n self.file.write(')')\n self.file.write('\\n')\n\n self.write_indent()\n self.file.write('{\\n')\n self.indent += 1\n for instruction in struct.body:\n self.write(instruction)\n self.indent -= 1\n\n self.write_indent()\n self.file.write('}\\n')\n\n def writeCondition(self, cond):\n for branch in cond.branches:\n self.write(branch)\n\n def writeReturn(self, ret):\n self.file.write('return (')\n self.write(ret.expr)\n self.file.write(')')\n\n def writeOperator(self, op):\n self.file.write(op.op)\n\n def writeSymbol(self, node):\n self.write_value(node)\n i = 0\n while i < len(node.elems):\n if i < len(node.elems) - 1:\n ref_offset = node.elems[i].ref_offset\n if ref_offset is 0:\n self.write(node.elems[i])\n self.file.write('.')\n elif ref_offset is 1:\n self.write(node.elems[i])\n self.file.write('->')\n else:\n self.file.write('(')\n while ref_offset > 1:\n self.file.write('*')\n ref_offset -= 1\n self.write(node.elems[i])\n self.file.write(')->')\n else:\n self.write(node.elems[i])\n i += 1\n\n def writeIdentifier(self, node):\n if node.decl is not None:\n self.file.write(node.decl.name)\n else:\n self.file.write(node.name)\n\n def writeChar(self, c):\n self.file.write('\\'')\n self.file.write(c.char)\n self.file.write('\\'')\n\n def writeString(self, s):\n self.file.write('\"')\n self.file.write(s.string)\n self.file.write('\"')\n\n def writeNumber(self, num):\n self.file.write(num.num)\n\n def writeNullValue(self, stmt):\n self.file.write('NULL')\n\n def writeBoolValue(self, node):\n self.file.write('0' if node.val is False else '!0')\n\n def writePrefixOperatorValue(self, val):\n self.file.write(val.op)\n self.write(val.val)\n\n def writeSuffixOperatorValue(self, val):\n self.write(val.val)\n self.file.write(val.op)\n\n def writeSizeof(self, node):\n self.file.write('sizeof(')\n self.write_type_prefix(node.sz_typ)\n self.write(node.sz_typ)\n self.file.write(')')\n\n def writeAlias(self, node):\n if node.src.is_type:\n self.file.write('typedef ')\n self.write(node.src)\n self.file.write(' ')\n self.write(node.dst)\n self.file.write(';\\n')\n\n def writeStruct(self, node):\n self.file.write('\\nstruct ')\n self.write(node.sym)\n self.file.write('\\n{\\n')\n self.indent += 1\n for f in node.fields:\n self.write_indent()\n self.write(f)\n self.file.write(';\\n')\n self.indent -= 1\n self.file.write('};\\n')\n","sub_path":"reflex/writer/source.py","file_name":"source.py","file_ext":"py","file_size_in_byte":11692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"81431096","text":"from .base import BaseDocument\nfrom ._properties import MetaField\nfrom motorengine.fields import *\n\n\nclass Data(BaseDocument):\n\n __indexes__ = [('value', BaseDocument.TEXT)]\n\n thing_id = StringField(required=True)\n key = StringField(required=True)\n value = MetaField(required=True)\n\n @classmethod\n async def add(cls, thing_id, key, value):\n item = cls(thing_id=thing_id, key=key, value=value)\n await item.save()\n return item\n\n @classmethod\n async def update(cls, thing_id, key, value):\n results = await cls.objects.filter(thing_id=thing_id, key=key) \\\n .find_all()\n if results:\n result = results[0]\n setattr(result, key, value)\n await result.save()\n return result\n\n\nclass Thing(BaseDocument):\n thing_id = StringField(required=True, unique=True)\n name = StringField(required=True)\n reads = IntField(required=True, default=0)\n\n @classmethod\n async def add(cls, table, thing_id):\n item = cls(thing_id=thing_id, name=table)\n await item.save()\n return item\n","sub_path":"schema/thing.py","file_name":"thing.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"550729734","text":"import math\ndef mcm(num):\n minimum = 1\n for i in num:\n minimum = int(i) * int(minimum) / math.gcd(int(i), int(minimum))\n return int(minimum)\nnumber=int(input(\"\"))\nlist=input(\"\").split(\" \")\nsource=[]\nfor i in range(number):\n source.append(int(list[i]))\nsource.sort()\nall=[]\nfor i in source:\n if(not i in all):\n all.append(i)\nif(len(all)==1):\n print(\"Yes\")\nelse:\n a=mcm(all)\n times=[]\n for i in range(len(all)):\n times.append(a/all[i])\n result=[]\n for i in times:\n x=i\n while(x%2==0):\n x=x/2\n while(x%3==0):\n x=x/3\n result.append(x)\n result.sort()\n if(result[-1]==1):\n print(\"Yes\")\n else:\n print(\"No\")\n\n ","sub_path":"Code/CodeRecords/2799/60636/266615.py","file_name":"266615.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"487760615","text":"from django.urls import path\nfrom . import views\n\napp_name = 'auth'\nurlpatterns = [\n path('register', views.register, name='register'),\n # 这个是用于发出注册请求之后,后台进行的异步任务\n # 或者也可以用户手动再次触发(由于某些情况没有发送成功)\n path('register/precheck/email', views.precheck_register_email, name='precheck_register_email'),\n path('register/precheck/nick',views.precheck_register_nick,name='precheck_register_nick'),\n path('register/email/send', views.send_register_email, name='send_register_email'),\n # 这个应该是一个get请求,使用jwt token进行验证\n path('register/email/verify', views.verify_register_email, name='verify_register_email'),\n\n path('login',views.login,name='login'),\n path('cdpwd',views.cdpwd,name='cdpwd'),\n path('logout',views.logout,name='logout')\n]\n","sub_path":"src/apps/auth/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"28121109","text":"from mininet.topo import Topo\nfrom mininet.net import Mininet\nfrom mininet.util import dumpNodeConnections\nfrom mininet.node import CPULimitedHost\nfrom mininet.link import TCLink\nfrom mininet.log import setLogLevel\nfrom mininet.cli import CLI\nfrom mininet.node import OVSController\nfrom mininet.node import RemoteController, OVSSwitch\n\nBANDWIDTH = 10\nDELAY = '5ms'\nLOSS = 2\nMAX_QUEUE_SIZE = 1000\n\n# BANDWIDTH = 100\n# DELAY = '5ms'\n# LOSS = 2\n# MAX_QUEUE_SIZE = 1000\n\n# BANDWIDTH = 10\n# DELAY = '15ms'\n# LOSS = 2\n# MAX_QUEUE_SIZE = 1000\n\n# BANDWIDTH = 10\n# DELAY = '5ms'\n# LOSS = 5\n# MAX_QUEUE_SIZE = 1000\n\n# BANDWIDTH = 10\n# DELAY = '5ms'\n# LOSS = 2\n# MAX_QUEUE_SIZE = 700\n\nclass RingTopo(Topo):\n \"Ring topology of n hosts and n switches\"\n def build(self, n=2):\n prevSwitch = None\n firstSwitch = None\n for h in range(n):\n host = self.addHost('h%s' % (h+1))\n switch = self.addSwitch('s%s' % (h+1))\n self.addLink(host,switch,bw=BANDWIDTH, delay=DELAY, loss=LOSS, max_queue_size=MAX_QUEUE_SIZE)\n if(h>0):\n self.addLink(prevSwitch,switch,bw=BANDWIDTH, delay=DELAY, loss=LOSS, max_queue_size=MAX_QUEUE_SIZE)\n else:\n firstSwitch = switch\n prevSwitch = switch\n self.addLink(prevSwitch,firstSwitch,bw=BANDWIDTH, delay=DELAY, loss=LOSS, max_queue_size=MAX_QUEUE_SIZE)\n \n\ndef simpleTest():\n \"Create and test a simple network\"\n topo = RingTopo(n=10)\n net = Mininet(topo=topo,controller = RemoteController, host=CPULimitedHost, link=TCLink )\n net.start()\n\n print(\"Dumping host connections\")\n dumpNodeConnections(net.hosts)\n \n switches = net.switches\n\n for i in range(len(switches)):\n switches[i].cmd('ovs-vsctl set bridge s%s stp-enable=true' % (i+1))\n\n net.waitConnected()\n print(\"Testing network connectivity\")\n\n net.pingAll()\n \n hosts = net.hosts\n\n print(\"Pinging h6 from h1\")\n print(hosts[0].cmd('ping -c1 %s' % hosts[5].IP())) \n \n print(\"Running iperf between h1 and h6\") \n print(net.iperf([hosts[0],hosts[5]]))\n\n print(\"Running iperf between h1 and h10\") \n print(net.iperf([hosts[0],hosts[9]]))\n\n print(\"Running ifconfig on h1\")\n print(hosts[0].cmd('ifconfig')) \n\n print(\"Running route on h1\")\n print(hosts[0].cmd('route'))\n\n print(\"Running traceroute from h1 to h10\")\n print(hosts[0].cmd('traceroute %s' % hosts[9].IP())) \n\n # print(\"Running nslookup from h1\")\n # print(hosts[0].cmd('nslookup www.google.com'))\n\n net.stop()\n\nif __name__ == '__main__':\n # Tell mininet to print useful information\n setLogLevel('info')\n simpleTest()\n","sub_path":"A1/Ring.py","file_name":"Ring.py","file_ext":"py","file_size_in_byte":2672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"121384301","text":"import os\nfrom flask import render_template,request,redirect,session,jsonify\nfrom app.main import main\nfrom sdk.getDate import MyDate\nfrom app.models import *\nfrom settings import STATIC_PATH\nimport hashlib\nimport functools\nfrom sdk.pager import Pager\nfrom .form import TaskForm# from main import csrf\n# from main import api\nfrom app import csrf,api\nfrom flask_restful import Resource\n\ndef set_password(password):\n md5 = hashlib.md5()\n md5.update(password.encode())\n result = md5.hexdigest()\n return result\n\n\ndef LoginVaild(func):\n @functools.wraps(func) ## 保留原来的函数名字\n def inner(*args,**kwargs):\n user_id = request.cookies.get(\"user_id\")\n email = request.cookies.get(\"email\")\n session_email = session.get(\"email\")\n print (session_email)\n if user_id and email and email == session_email:\n ##\n user = User.query.filter(User.email == email,User.id==user_id).first()\n if user:\n return func(*args,**kwargs)\n else:\n return redirect(\"/login/\")\n else:\n return redirect(\"/login/\")\n return inner\n\n\n@main.route(\"/index/\")\n@LoginVaild\ndef index():\n ## userinfo 数据\n # userinfo = UserInfo(name=\"python\",age=19)\n # userinfo.save()\n data = UserInfo.query.get(7)\n return render_template(\"index.html\",data=data)\n@main.route(\"/userinfo/\")\n@LoginVaild\ndef userinfo():\n obj = MyDate()\n result = obj.get_date()\n\n return render_template(\"userinfo.html\",**locals())\n\n\n@main.route(\"/register1/\",methods=[\"get\",\"post\"])\ndef register1():\n if request.method == \"POST\":\n ## 注册\n email = request.form.get(\"email\")\n password= request.form.get(\"password\")\n data = User.query.filter(User.email == email).first()\n if data:\n ## 存在\n return redirect(\"http://www.baidu.com\")\n user = User(email = email,password = password)\n user.save()\n\n return \"注册成功\"\n # return render_template(\"register.html\")\n\n\n@main.route(\"/perfect/information/\",methods=[\"get\",\"post\"])\ndef perfect_information():\n if request.method == \"POST\":\n ## 注册\n user_id = request.form.get(\"id\")\n ### 获取图片 图片的名字 获取图片的内容 保存图片\n ### 数据中存 图片路径\n photo = request.files.get(\"photo\")\n\n user = User.query.filter(User.id == user_id).first()\n if user:\n ## 保存图片\n\n file_name = photo.filename\n photo_path = os.path.join(\"img\",file_name) ##img/xxx.jpg\n path = os.path.join(STATIC_PATH,photo_path)\n photo.save(path)\n ## 将图片路径存在数据库中\n user.photo = photo_path\n user.merge()\n else:\n return \"用户不存在\"\n # return \"增加信息成功\"\n user = User.query.filter(User.id ==1).first()\n photo = user.photo\n return render_template(\"photo.html\",**locals())\n\n## 登录\n@main.route(\"/login/\",methods=[\"get\",\"post\"])\ndef login():\n error = \"\"\n if request.method == \"POST\":\n\n email = request.form.get(\"email\")\n password = request.form.get(\"password\")\n if email and password:\n user = User.query.filter_by(email = email,password=set_password(password)).first()\n if user is not None:\n # return redirect(\"/index/\")\n response = redirect(\"/index/\")\n response.set_cookie(\"email\",user.email)\n response.set_cookie(\"user_id\",str(user.id))\n session[\"email\"] = user.email\n return response\n else:\n error = \"邮箱或者密码错误\"\n\n else:\n error = \"参数不能为空\"\n return render_template(\"login.html\",error = error)\n\n@main.route(\"/register/\",methods=[\"get\",\"post\"])\ndef register():\n error = \"\"\n if request.method == \"POST\":\n email = request.form.get(\"email\")\n password = request.form.get(\"password\")\n if email and password:\n user = User.query.filter(User.email == email).first()\n if user:\n error = \"邮箱已存在\"\n else:\n user = User()\n user.email = email\n user.password = set_password(password)\n user.save()\n return redirect(\"/login/\")\n else:\n error = \"参数不能为空\"\n return render_template(\"register.html\",error = error)\n\n@main.route(\"/logout/\",methods=[\"get\",\"post\"])\ndef logout():\n rep = redirect(\"/login/\")\n rep.delete_cookie(\"email\")\n rep.delete_cookie(\"user_id\")\n session.pop(\"email\")\n del session[\"email\"]\n return rep\n\n@main.route(\"/testget/\")\ndef testget():\n # name = request.args.get(\"name\",None)\n name = request.form.get(\"name\",None)\n print (name)\n return render_template(\"testget.html\")\n\n@main.route(\"/leave_list/\",methods=[\"get\",\"post\"])\n@LoginVaild\n@csrf.exempt\ndef leave_list():\n if request.method == \"POST\":\n user_id = request.cookies.get(\"user_id\")\n data = request.form\n print (type(request.form.get(\"start_time\")))\n start_time = data.get(\"start_time\")\n end_time = data.get(\"end_time\")\n ## 保存数据\n leave = Leave()\n leave.request_id = int(user_id) ## 请假人id\n leave.request_name = data.get(\"username\") ## 请假人姓名\n leave.request_type = data.get(\"type\") ### 假期类型\n leave.request_start = start_time ## 请假的开始时间\n leave.request_end = end_time ## 请假的结束时间\n leave.request_description = data.get(\"dec\") ## 请假描述\n leave.request_phone = data.get(\"phone\") ###联系人手机号\n leave.request_status = 0 ## 请假状态\n leave.save()\n return redirect(\"/leave_all_list/1/\")\n return render_template(\"leave_list.html\")\n\n\n\n@main.route(\"/leave_all_list//\",methods=[\"get\",\"post\"])\n@LoginVaild\ndef leave_all_list(page):\n leave = Leave.query.filter(Leave.request_id == request.cookies.get(\"user_id\")).all()\n pager = Pager(leave,10)\n page_data = pager.page_data(page)\n return render_template(\"leave_all_list.html\",**locals())\n\n\n@main.route(\"/chexiao/\",methods=[\"get\",\"post\"])\ndef chexiao():\n ## 获取请假条 leave_id\n id = request.form.get(\"id\")\n # print (id)\n ## delete操作\n leave = Leave.query.filter(Leave.id == id).first()\n leave.delete()\n ##return \"删除成功\"\n result = {\"code\":10000,\"msg\":\"删除成功\"}\n return jsonify(result) ## 返回json 串\n\n\n\n@main.route(\"/add_task/\",methods=[\"get\",\"post\"])\ndef add_task():\n task = TaskForm()\n # print(dir(task))\n # print (\"csrf_token%s\" % task.csrf_token) ### csrf_token\n # print (\"errors %s\" % task.errors) ###错误\n # print (task.validate()) ### 判断是否是一个合法的请求\n # print (task.validate_on_submit()) ### 判断是否是一个有效post、请求\n # print (task.data) ### 请求的数据\n #\n error = {}\n if request.method == \"POST\":\n if task.validate_on_submit(): ## 校验\n ## 获取数据数据\n FormData = task.data\n ## 保存数据 数据库当中 建立模型\n else:\n ##\n error = task.errors\n return render_template(\"add_task.html\",**locals())\n\n\n\n\n# @api.resource(\"/Api/v1/leave/\")\nclass LeaveApi(Resource):\n def __init__(self):\n super(LeaveApi, self).__init__()\n self.result = {\n \"method\": \"get\",\n \"version\": \"v1\",\n \"data\":\"\"\n }\n def create_data(self,leave):\n \"\"\"\n 定义返回的数据\n :return:\n \"\"\"\n result_data = {\n \"request_id\": leave.request_id,\n \"request_name\": leave.request_name,\n \"request_type\": leave.request_type,\n \"request_start\": str(leave.request_start),\n \"request_end\": str(leave.request_end),\n \"request_description\": leave.request_description,\n \"request_phone\": leave.request_phone,\n \"request_status\": leave.request_status\n }\n return result_data\n\n method_decorators = {\n \"get\":[LoginVaild]\n }\n def get(self):\n \"\"\"\n 处理get请求\n 获取资源\n :return:\n \"\"\"\n data = request.args\n id = data.get(\"id\")\n result_data = {}\n if id:\n leave = Leave.query.get(int(id))\n if leave is not None:\n result_data = self.create_data(leave)\n else:\n leaves = Leave.query.all() ### 所有数据\n result_data = []\n for leave in leaves:\n info = self.create_data(leave)\n result_data.append(info)\n\n self.result[\"data\"] = result_data\n\n return jsonify(self.result)\n\n # return \"get 请求 %s\" % data\n def post(self):\n \"\"\"\n 处理post请求 增加数据的功能\n :return:\n \"\"\"\n data = request.form\n leave = Leave()\n leave.request_id = data.get(\"request_id\") ## 请假人id\n leave.request_name = data.get(\"request_name\") ## 请假人姓名\n leave.request_type = data.get(\"request_type\") ### 假期类型\n leave.request_start = data.get(\"request_start\") ## 请假的开始时间\n leave.request_end = data.get(\"request_end\") ## 请假的结束时间\n leave.request_description = data.get(\"request_description\") ## 请假描述\n leave.request_phone = data.get(\"request_phone\") ###联系人手机号\n leave.request_status = data.get(\"request_status\") ## 请假状态\n leave.save()\n self.result[\"method\"] = \"post\"\n self.result[\"data\"] = self.create_data(leave)\n return jsonify(self.result)\n def put(self):\n \"\"\"\n 处理put请求 更新数据\n 可以支持更改部分数据\n 根据id查询的 -》 对象\n 修改的是 对象中属性\n 对象属性中 ——》 setattr\n\n :return:\n \"\"\"\n data = request.form ## 字典\n id = data.get(\"id\") ##假条id\n leave = Leave.query.get(id) ## 找到被修改的数据 leave是一个对象\n for key,value in data.items():\n ## 传过来的 key 和 value\n if key != \"id\":\n if hasattr(leave,key):\n setattr(leave,key,value)\n leave.merge()\n self.result[\"method\"] = \"put\"\n self.result[\"data\"] = self.create_data(leave)\n return jsonify(self.result)\n\n\n def delete(self):\n \"\"\"\n 处理delete方法 删除数据\n :return:\n \"\"\"\n data = request.form\n id = data.get(\"id\")\n leave = Leave.query.get(id)\n leave.delete()\n self.result[\"method\"] = \"delete\"\n self.result[\"msg\"] = \"删除成功\"\n return jsonify(self.result)\n\n\n\n@main.route('/apidemo/')\ndef apidemo():\n return render_template(\"apidemo.html\")\n\n\n\ndef func1(func):\n def inner():\n print (\"func1 装饰器\")\n func()\n return inner\n\ndef func2(func):\n def inner():\n print (\"func2 装饰器\")\n func()\n return inner\n\n\n# @api.resource(\"/Demo/\")\nclass Demo(Resource):\n method_decorators = {\n \"get\":[func1,func2],\n \"post\":[func2]\n }\n\n def get(self):\n \"\"\"\n\n :return:\n \"\"\"\n return \"get请求\"\n def post(self):\n \"\"\"\n\n :return:\n \"\"\"\n return \"post 请求\"\n\n# api.add_resource(Demo,\"/Demo/\") ##\n\n\n\n@main.route(\"/mytest/\")\ndef mytest():\n id = request.args.get(\"id\")\n\n\n\n result = {\"code\":10000,\"msg\":\"sucess\"}\n if id:\n result[\"data\"]= \"fdsfsfs\"\n\n return jsonify(result)\n\n","sub_path":"flasknew/app/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"286460782","text":"#!/usr/bin/env python\n\"\"\"Legacy procedural codebase, retained during functional migration\"\"\"\n\nimport logging\nlogger = logging.getLogger(__name__)\n\nfrom prototype import _key_coded_dict\n\n__author__ = 'Nathan Pinger, Clayton C. Daley III'\n__copyright__ = \"Copyright 2012-2015 Nathan Pinger, Clayton Daley III\"\n__license__ = \"Apache License 2.0\"\n__version__ = \"1.0.0\"\n__maintainer__ = \"Clayton Daley III\"\n__status__ = \"Development\"\n\n\nclass LegacyService(object):\n ##########################\n # Resource Builders\n #\n # BaseCRM has started to transition object identification from the path to the parameters (or a combination). In\n # response, URL builder functions (returning just a url string) are being replaced with \"resource\" functions\n # returning a tuple of URL string (excluding parameters) and parameter dict.\n ##########################\n def _build_resource_url(self, resource, version, path=''):\n \"\"\"\n Builds a URL for a resource using the not-officially-documented format:\n https://app.futuresimple.com/apis//api/v/.\n \"\"\"\n if version == 2:\n if self.debug:\n url = 'https://api.sandbox.getbase.com/v%d%s' % (version, path)\n else:\n url = 'https://api.getbase.com/v%d%s' % (version, path)\n else:\n url = 'https://app.futuresimple.com/apis/%s/api/v%d%s' % (resource, version, path)\n return self._apply_format(url, self.format)\n\n def _build_search_url(self, type):\n if type == 'contact':\n url, params = self._build_contact_resource()\n elif type == 'deal':\n url, params = self._build_deal_resource()\n elif type == 'lead':\n url, params = self._build_lead_resource()\n else:\n raise ValueError(\"Invalid search type.\")\n url += '/search'\n return self._apply_format(url, self.format)\n\n ##########################\n # Feed (i.e. Activity) Functions\n #\n # NOTE: feeds overlap to some degree with tasks (completed only) and notes\n ##########################\n def _build_feed_resource(self, contact_id=None, lead_id=None, deal_id=None, type=None, timestamp=None):\n \"\"\"\n Returns a tuple of URL (without parameters) and format_data_get that will produce a list of activities (i.e. feed) in\n batches of 20.\n\n ARGUMENTS\n\n Parent objects (optional, include only one):\n contact_id (default None) - load activities for a specific contact\n lead_id (default None) - load activities for a specific lead\n deal_id (default None) - load activities for a specific deal\n Activity Types:\n type=None (default) - load all types\n type='Email' - returns only emails\n type='Note' - returns only notes\n type='Call' - returns only phone calls\n type='Task' - returns only completed tasks\n Paging:\n timestamp - feed paging is achieved using the timestamp parameter, not a traditional page number (see the\n stateful client for automatic handling of feed paging\n\n RESPONSE STRUCTURE\n\n see get_feed()\n \"\"\"\n path = '/feed'\n url_params = dict()\n\n url_params['api_mailman'] = 'v2'\n\n if timestamp is not None:\n url_params['timestamp'] = timestamp\n\n if contact_id is not None:\n path += \"/contact/%d\" % contact_id\n elif lead_id is not None:\n path += \"/lead/%d\" % lead_id\n elif deal_id is not None:\n path += \"/deal/%d\" % deal_id\n\n if type is not None:\n if type in ['Email', 'Note', 'Call', 'Task']:\n url_params['only'] = type\n else:\n raise ValueError(\n \"'%s' is not a valid type, must be None, 'Email', 'Note', 'Call', or 'Task'\" % str(type))\n\n url_noparam = self._build_resource_url('feeder', 1, path, self.format)\n return url_noparam, url_params\n\n def _get_feed(self, contact_id=None, lead_id=None, deal_id=None, type=None, timestamp=None):\n \"\"\"\n Returns the most recent 20 activities (i.e. feed) that meet the filter conditions\n\n ARGUMENTS\n\n Parent Objects (optional, include only one):\n contact_id (default None) - load activities for a specific contact\n lead_id (default None) - load activities for a specific lead\n deal_id (default None) - load activities for a specific deal\n Activity Types:\n type=None (default) - load all types\n type='Email' returns only emails\n type='Note' returns only notes\n type='Call' returns only phone calls\n type='Task' returns only completed tasks\n Paging:\n timestamp - feed paging is achieved using the timestamp parameter, not a traditional page number (see the\n stateful client for automatic handling of feed paging\n Format:\n format (default None) - see BaseAPIService._apply_format() for accepted values\n\n RESPONSE STRUCTURE\n\n see get_feed()\n \"\"\"\n url_noparam, url_params = self._build_feed_resource(contact_id=contact_id, deal_id=deal_id, lead_id=lead_id,\n type=type, timestamp=timestamp)\n return self._get_data(url_noparam, url_params)\n\n def get_feed(self, type=None, timestamp=None):\n \"\"\"\n Returns the most recent 20 activities (i.e. feed) that meet the filter conditions\n\n ARGUMENTS\n\n Activity Types:\n type=None (default) - load all types\n type='Email' returns only emails\n type='Note' returns only notes\n type='Call' returns only phone calls\n type='Task' returns only completed tasks\n Paging:\n timestamp - feed paging is achieved using the timestamp parameter, not a traditional page number (see the\n stateful client for automatic handling of feed paging\n\n RESPONSE STRUCTURE\n\n {'items':\n [{'feed_item':\n {'attributes': {...} # Depends on object type, see attributes below\n 'api': ... # 'v1' or 'v2'\n 'type': ... # 'lead', 'note', 'deal', 'contact', 'deal_stage_change', 'synced_email'...\n 'sorted_by': ... # the value of the field on which the item was sorted\n }\n 'success': ...\n 'metadata': ...\n }, ...]\n 'success': ...\n 'metadata': ...\n }\n\n ATTRIBUTES DICTIONARY KEYS\n\n For 'lead':\n 'first_name', 'last_name', 'user_id', 'account_id', 'state', 'created_at', 'status_id', 'updated_at',\n 'has_any_email', 'last_activity_date', 'created_via', 'company_name', 'deleted_at', 'id', 'owner_id'\n\n For 'deal':\n 'user_id', 'account_id', 'created_at', 'currency', 'creator_id', 'scope', 'id', 'name'\n\n For 'contact':\n 'first_name', 'last_name', 'user_id', 'name', 'title', 'mobile', 'created_at', 'is_sales_account', 'contact_id',\n 'email', 'phone', 'creator_id', 'id', 'account_id'\n\n For 'note':\n 'user_id', 'account_id', 'permissions_holder_id', 'created_at', 'updated_at', 'noteable_type', 'content',\n 'private', 'noteable_id', 'id'\n\n For 'deal_stage_change':\n 'user_id', 'account_id', 'created_at', 'to_stage_name', 'to_stage', 'from_stage', 'from_stage_name', 'id',\n 'deal_id'\n\n For 'synced_email':\n ['status', 'addresses', 'from', 'sender', 'to', 'synced_email_thread_id', 'created_at', 'attachments', 'bcc',\n 'content', 'sha', 'mailbox_type', 'reply_to', 'related_objects', 'date', 'seen', 'internal_forwarded_from',\n 'id', 'cc', 'subject']\n\n \"\"\"\n return self._get_feed(type=type, timestamp=timestamp)\n\n def get_contact_feed(self, contact_id, timestamp=None):\n return self._get_feed(contact_id=contact_id, timestamp=timestamp)\n\n def get_contact_feed_emails(self, contact_id, timestamp=None):\n return self._get_feed(contact_id=contact_id, type='Email', timestamp=timestamp)\n\n def get_contact_feed_notes(self, contact_id, timestamp=None):\n return self._get_feed(contact_id=contact_id, type='Note', timestamp=timestamp)\n\n def get_contact_feed_calls(self, contact_id, timestamp=None):\n return self._get_feed(contact_id=contact_id, type='Call', timestamp=timestamp)\n\n def get_contact_feed_tasks_completed(self, contact_id, timestamp=None):\n return self._get_feed(contact_id=contact_id, type='Task', timestamp=timestamp)\n\n def get_deal_feed(self, deal_id, timestamp=None):\n return self._get_feed(deal_id=deal_id, timestamp=timestamp)\n\n def get_deal_feed_emails(self, deal_id, timestamp=None):\n return self._get_feed(deal_id=deal_id, type='Email', timestamp=timestamp)\n\n def get_deal_feed_notes(self, deal_id, timestamp=None):\n return self._get_feed(deal_id=deal_id, type='Note', timestamp=timestamp)\n\n def get_deal_feed_calls(self, deal_id, timestamp=None):\n return self._get_feed(deal_id=deal_id, type='Call', timestamp=timestamp)\n\n def get_deal_feed_tasks_completed(self, deal_id, timestamp=None):\n return self._get_feed(deal_id=deal_id, type='Task', timestamp=timestamp)\n\n def get_lead_feed(self, lead_id, timestamp=None):\n return self._get_feed(lead_id=lead_id, timestamp=timestamp)\n\n def get_lead_feed_emails(self, lead_id, timestamp=None):\n return self._get_feed(lead_id=lead_id, type='Email', timestamp=timestamp)\n\n def get_lead_feed_notes(self, lead_id, timestamp=None):\n return self._get_feed(lead_id=lead_id, type='Note', timestamp=timestamp)\n\n def get_lead_feed_notes_alt(self, lead_id, timestamp=None):\n return self._get_notes(lead_id=lead_id, timestamp=timestamp)\n\n def get_lead_feed_calls(self, lead_id, timestamp=None):\n return self._get_feed(lead_id=lead_id, type='Call', timestamp=timestamp)\n\n def get_lead_feed_tasks_completed(self, lead_id, timestamp=None):\n return self._get_feed(lead_id=lead_id, type='Task', timestamp=timestamp)\n\n ##########################\n # Tags Functions\n ##########################\n def _build_tags_resource(self, tag_id=None, app_id=None, page=None):\n \"\"\"\n Returns a tuple of URL (without parameters) and format_data_get to obtain a list of tags in batches of 20\n\n ARGUMENTS\n\n Filters:\n tag_id - returns information about a single tag\n app_id - gets all tags for a particular app_id (i.e. type of object)\n Paging:\n page (default 1)\n Format:\n format (default None) - see BaseAPIService._apply_format() for accepted values\n\n RESPONSE STRUCTURE\n\n see get_tags()\n \"\"\"\n path = '/tags'\n url_params = dict()\n\n if tag_id is not None:\n path += '/%s' % tag_id\n elif app_id is not None:\n url_params['app_id'] = app_id\n\n if page is not None:\n url_params['page'] = page\n\n url_noparam = self._build_resource_url('tags', 1, path)\n return url_noparam, url_params\n\n def get_tags(self, type, page=1):\n \"\"\"\n Gets tag objects for a particular type of object in batches of 20\n\n ARGUMENTS\n\n Type:\n type='Contact'\n type='ContactAlt' - Due to a quirk in the backend, contact tags appear to have two access methods which\n have been duplicated in the API client in case they are functional\n type='Deal'\n type='Lead'\n Paging\n page (default 1)\n\n RESPONSE STRUCTURE\n\n [{'tag':\n {'id': ...\n 'name': ...\n 'permissions_holder_id': ...\n }\n }, ...]\n \"\"\"\n # Translates between object types and friendly names\n if type == 'Contact':\n # https://app.futuresimple.com/apis/tags/api/v1/tags.json?app_id=4\n app_id = 4\n elif type == 'ContactAlt':\n # https://app.futuresimple.com/apis/tags/api/v1/tags.json?app_id=7\n app_id = 7\n elif type == 'Deal':\n # https://app.futuresimple.com/apis/tags/api/v1/tags.json?app_id=1\n app_id = 1\n elif type == 'Lead':\n # https://app.futuresimple.com/apis/tags/api/v1/tags.json?app_id=5\n app_id = 5\n else:\n raise ValueError(\"type was '%s' but must be 'Contact', 'ContactAlt', 'Deal', or 'Lead'\" % str(type))\n\n url_noparam, url_params = self._build_tags_resource(app_id=app_id, page=page)\n return self._get_data(url_noparam, url_params)\n\n def get_tag(self, tag_id):\n \"\"\"\n Returns the contents of one tag identified by tag_id\n\n RESPONSE STRUCTURE\n\n {'tag':\n {'id': ...\n 'name': ...\n 'permissions_holder_id': ...\n }\n }\n \"\"\"\n url_noparam, url_params = self._build_tags_resource(tag_id=tag_id)\n return self._get_data(url_noparam, url_params)\n\n def get_contact_tags(self, page=1):\n \"\"\"\n Returns tags associated with Contacts in batches of 20\n\n NOTE: Due to an underlying ambiguity in the API, see also get_contact_tags_alt()\n \"\"\"\n return self.get_tags('Contact', page)\n\n def get_contact_tags_alt(self, page=1):\n \"\"\"\n Returns tags associated with Contacts in batches of 20\n\n NOTE: Due to an underlying ambiguity in the API, see also get_contact_tags()\n \"\"\"\n return self.get_tags('ContactAlt', page)\n\n def get_deal_tags(self, page=1):\n \"\"\"\n Returns tags associated with Deals in batches of 20\n \"\"\"\n return self.get_tags('Deal', page)\n\n def get_lead_tags(self, page=1):\n \"\"\"\n Returns tags associated with Leads in batches of 20\n \"\"\"\n return self.get_tags('Lead', page)\n\n def _upsert_tag(self):\n raise NotImplementedError\n\n def update_tag(self):\n raise NotImplementedError\n\n def create_contact_tag(self):\n app_id = 4\n raise NotImplementedError\n\n def create_deal_tag(self):\n app_id = 1\n raise NotImplementedError\n\n def create_lead_tag(self):\n app_id = 5\n raise NotImplementedError\n\n def _build_taggings_resource(self, tag_list, method='add', contact_id=None, deal_id=None, lead_id=None,\n contact_ids=None, deal_ids=None, lead_ids=None):\n \"\"\"\n Returns a tuple of URL (without parameters) and format_data_get to modify object tags\n\n ARGUMENTS\n\n Behavior:\n tag_list - list of one to many tags (\n method (default 'add') - determines the change made ('add', 'remove', or 'replace')\n Parent Objects (only valid for 'replace', include only one)\n contact_id\n deal_id\n lead_id\n Parent Objects (only valid for 'add' and 'remove', include only one)\n contact_ids\n deal_ids\n lead_ids\n Format:\n format (default None) - see BaseAPIService._apply_format() for accepted values\n\n RESPONSE STRUCTURE\n\n see _add_tags(), _remove_tag(), _replace_tags()\n \"\"\"\n path = '/taggings'\n url_params = dict()\n\n url_params['tag_list'] = ','.join(tag_list)\n\n # Configure parameters for method and target object (together because there are strict compatibilities)\n if method == 'replace':\n # Only singular id values are compatible\n if contact_id is not None:\n url_params['taggable_id'] = contact_id\n url_params['taggable_type'] = 'Contact'\n elif deal_id is not None:\n url_params['taggable_id'] = deal_id\n url_params['taggable_type'] = 'Deal'\n elif lead_id is not None:\n url_params['taggable_id'] = lead_id\n url_params['taggable_type'] = 'Lead'\n elif method in ['add', 'remove']:\n if method == 'add':\n path += '/batch_add'\n else: # method == 'replace'\n path += '/batch_untag'\n # Only plural ids values are compatible\n if contact_ids is not None:\n url_params['taggable_ids'] = ','.join([str(x) for x in contact_ids])\n url_params['taggable_type'] = 'Contact'\n elif deal_ids is not None:\n url_params['taggable_ids'] = ','.join([str(x) for x in deal_ids])\n url_params['taggable_type'] = 'Deal'\n elif lead_ids is not None:\n url_params['taggable_ids'] = ','.join([str(x) for x in lead_ids])\n url_params['taggable_type'] = 'Lead'\n else:\n raise ValueError(\"'method' is '%s' but must be 'add', 'remove', or 'replace'\" % str(method))\n\n if url_params['taggable_type'] == 'Contact':\n url_params['app_id'] = 4\n elif url_params['taggable_type'] == 'Deal':\n url_params['app_id'] = 1\n elif url_params['taggable_type'] == 'Lead':\n url_params['app_id'] = 5\n\n url_noparam = self._build_resource_url('tags', 1, path)\n return url_noparam, url_params\n\n def _add_tags(self, tag_list, contact_id=None, deal_id=None, lead_id=None,\n contact_ids=None, deal_ids=None, lead_ids=None):\n \"\"\"\n PRIVATE FUNCTION that enforces data integrity rules for adding tags, to be called by public single-purpose tag\n functions.\n\n ARGUMENTS\n\n Tags:\n tag_list - list of textual tags\n Parent Object(s) (include only one):\n contact_id - singular id\n deal_id - singular id\n lead_id - singular id\n contact_ids - list of ids\n deal_ids - list of ids\n lead_ids - list of ids\n\n RESPONSE STRUCTURE\n\n {'':\n ['',\n ''\n ],\n ...\n }\n\n NOTE: In the response dict, a key is present for each submitted object. The value is a list of tags actually\n added to the object. If no tags were added to a particular object, the value is an empty list.\n \"\"\"\n method = 'add'\n if not isinstance(tag_list, list):\n tag_list = [tag_list]\n else:\n # Ensure None (if present) is not translated into a string\n # lower() because UI implementation of tags seems to assume case insensitivity, but API is case sensitive\n tag_list = [str(x).lower() for x in tag_list if x]\n\n contacts, deals, leads = None, None, None\n # Support both singleton id and list ids\n if contact_id is not None:\n contacts = [contact_id]\n elif deal_id is not None:\n deals = [deal_id]\n elif lead_id is not None:\n leads = [lead_id]\n elif contact_ids is not None:\n contacts = contact_ids\n elif deal_ids is not None:\n deals = deal_ids\n elif lead_ids is not None:\n leads = lead_ids\n else:\n raise ValueError('_add_tags request must include a valid object')\n\n url_noparam, url_params = self._build_taggings_resource(tag_list=tag_list, method=method,\n contact_ids=contacts, deal_ids=deals, lead_ids=leads)\n return self._post_data(url_noparam, url_params)\n\n def _remove_tag(self, tag, contact_id=None, deal_id=None, lead_id=None,\n contact_ids=None, deal_ids=None, lead_ids=None):\n \"\"\"\n PRIVATE FUNCTION that enforces data integrity rules for removing tags, to be called by public single-purpose\n tag functions.\n\n ARGUMENTS\n\n Tags:\n tag - single textual tag\n Parent Object(s) (include only one):\n contact_id - singular id\n deal_id - singular id\n lead_id - singular id\n contact_ids\n deal_ids\n lead_ids\n\n RESPONSE STRUCTURE\n\n {'untagged_ids': null}\n\n OR\n\n {'untagged_ids':\n [,\n ...\n ]\n }\n\n NOTE: Only includes objects where the tag was removed. If no objects were affected, the value of\n 'untagged_ids' is None (rather than an empty list).\n \"\"\"\n method = 'remove'\n # The remove method only supports a single tag. Since most other tag methods support lists of tags, we\n # explicitly check that the input in valid.\n if isinstance(tag, list):\n raise ValueError(\"'tag' does not accept a list\")\n if ',' in tag:\n raise ValueError(\"'tag' may not include a comma as only one tag can be removed at a time\")\n\n # _build_taggings_resource only accepts a list of tags so we recast our single tag appropriately\n if tag: # ensure None is not translated into a string\n # lower() because UI implementation of tags seems to assume case insensitivity, but API is case sensitive\n tag = [str(tag).lower()]\n else:\n tag = [] # The API considers this a valid request so we don't bother raising an error\n\n url_noparam, url_params = self._build_taggings_resource(tag_list=tag, method=method, contact_id=contact_id,\n deal_id=deal_id, lead_id=lead_id,\n contact_ids=contact_ids, deal_ids=deal_ids,\n lead_ids=lead_ids)\n return self._post_data(url_noparam, url_params)\n\n def _replace_tags(self, tag_list, contact_id=None, deal_id=None, lead_id=None):\n \"\"\"\n PRIVATE FUNCTION that enforces data integrity rules for replacing tags, to be called by public single-purpose\n tag functions.\n\n ARGUMENTS\n\n Tags:\n tag_list - list of textual tags\n Parent Object (include only one):\n contact_id\n deal_id\n lead_id\n\n RESPONSE STRUCTURE\n\n [{'tag':\n {'id': ...\n 'name': ...\n 'permissions_holder_id': ...\n }\n }, ...]\n\n NOTE: Lists ids of all tags included in tag_list\n \"\"\"\n method = 'replace'\n if not isinstance(tag_list, list):\n raise ValueError(\"'tag_list' must be a list\")\n else:\n # Ensure None (if present) is not translated into a string\n # lower() because UI implementation of tags seems to assume case insensitivity, but API is case sensitive\n tag_list = [str(x).lower() for x in tag_list if x]\n\n url_noparam, url_params = self._build_taggings_resource(tag_list=tag_list, method=method, contact_id=contact_id,\n deal_id=deal_id, lead_id=lead_id)\n return self._post_data(url_noparam, url_params)\n\n def tag_contacts(self, tag_list, contact_ids):\n \"\"\"\n Adds one or more tags to one or more contacts\n\n ARGUMENTS\n\n tag_list - list of tags (text form, not ids)\n contact_ids - list of IDs or single ID (automatically converted to a one-item list)\n\n RESPONSE STRUCTURE\n\n see _add_tags()\n \"\"\"\n if not isinstance(contact_ids, list):\n contact_ids = [contact_ids]\n return self._add_tags(tag_list=tag_list, contact_ids=contact_ids)\n\n def untag_contacts(self, tag, contact_ids):\n \"\"\"\n Removes one tag from one or more contacts\n\n ARGUMENTS\n\n tag - single tag (text form, not ids)\n contact_ids - list of IDs or single ID (automatically converted to a one-item list)\n\n RESPONSE STRUCTURE\n\n see _remove_tag()\n \"\"\"\n if not isinstance(contact_ids, list):\n contact_ids = [contact_ids]\n return self._remove_tag(tag=tag, contact_ids=contact_ids)\n\n def retag_contact(self, tag_list, contact_id):\n \"\"\"\n Replaces all tags for contact_id with tags in tag_list\n\n ARGUMENTS\n\n tag_list - list of tags (text form, not ids)\n contact_id - id of contact to be updated\n\n RESPONSE STRUCTURE\n\n see _replace_tags()\n \"\"\"\n return self._replace_tags(tag_list=tag_list, contact_id=contact_id)\n\n def update_contact_tags(self, tag_list, contact_id):\n \"\"\"\n Alias for retag_contact(): Replaces all tags for contact_id with tags in tag_list\n \"\"\"\n return self.retag_contact(tag_list=tag_list, contact_id=contact_id)\n\n def tag_deals(self, tag_list, deal_ids):\n \"\"\"\n Adds one or more tags to one or more deals\n\n ARGUMENTS\n\n tag_list - list of tags (text form, not ids)\n deal_ids - list of IDs or single ID (automatically converted to a one-item list)\n\n RESPONSE STRUCTURE\n\n see _add_tags()\n \"\"\"\n if not isinstance(deal_ids, list):\n deal_ids = [deal_ids]\n return self._add_tags(tag_list=tag_list, deal_ids=deal_ids)\n\n def untag_deals(self, tag, deal_ids):\n \"\"\"\n Removes one tag from one or more deals\n\n ARGUMENTS\n\n tag - single tag (text form, not ids)\n deal_ids - list of IDs or single ID (automatically converted to a one-item list)\n\n RESPONSE STRUCTURE\n\n see _remove_tag()\n \"\"\"\n if not isinstance(deal_ids, list):\n deal_ids = [deal_ids]\n return self._remove_tag(tag=tag, deal_ids=deal_ids)\n\n def retag_deal(self, tag_list, deal_id):\n \"\"\"\n Replaces all tags for deal_id with tags in tag_list\n\n ARGUMENTS\n\n tag_list - list of tags (text form, not ids)\n deal_id - id of deal to be updated\n\n RESPONSE STRUCTURE\n\n see _replace_tags()\n \"\"\"\n return self._replace_tags(tag_list=tag_list, deal_id=deal_id)\n\n def update_deal_tags(self, tag_list, deal_id):\n \"\"\"\n Alias for retag_deal(): Replaces all tags for deal_id with tags in tag_list\n \"\"\"\n return self.retag_deal(tag_list=tag_list, deal_id=deal_id)\n\n def tag_leads(self, tag_list, lead_ids):\n \"\"\"\n Adds one or more tags to one or more leads\n\n ARGUMENTS\n\n tag_list - list of tags (text form, not ids)\n lead_ids - list of IDs or single ID (automatically converted to a one-item list)\n\n RESPONSE STRUCTURE\n\n see _add_tags()\n \"\"\"\n if not isinstance(lead_ids, list):\n lead_ids = [lead_ids]\n return self._add_tags(tag_list=tag_list, lead_ids=lead_ids)\n\n def untag_leads(self, tag, lead_ids):\n \"\"\"\n Removes one tag from one or more leads\n\n ARGUMENTS\n\n tag - single tag (text form, not ids)\n lead_ids - list of IDs or single ID (automatically converted to a one-item list)\n\n RESPONSE STRUCTURE\n\n see _remove_tag()\n \"\"\"\n if not isinstance(lead_ids, list):\n lead_ids = [lead_ids]\n return self._remove_tag(tag=tag, lead_ids=lead_ids)\n\n def retag_lead(self, tag_list, lead_id):\n \"\"\"\n Replaces all tags for lead_id with tags in tag_list\n\n ARGUMENTS\n\n tag_list - list of tags (text form, not ids)\n lead_id - id of lead to be updated\n\n RESPONSE STRUCTURE\n\n see _replace_tags()\n \"\"\"\n return self._replace_tags(tag_list=tag_list, lead_id=lead_id)\n\n def update_lead_tags(self, tag_list, lead_id):\n \"\"\"\n Alias for retag_lead(): Replaces all tags for lead_id with tags in tag_list\n \"\"\"\n return self.retag_lead(tag_list=tag_list, lead_id=lead_id)\n\n ##########################\n # Notes Functions\n #\n # NOTE: notes overlap to some degree with feeds\n ##########################\n def _build_note_resource(self, note_id=None, contact_id=None, deal_id=None, lead_id=None, page=None):\n \"\"\"\n Returns a tuple of URL (without parameters) and format_data_get to get notes matching filter criteria in batches of 20\n\n Parent Objects (optional, include only one):\n contact_id\n deal_id\n lead_id\n Paging:\n page (default 1): the page of results to be loaded\n Format:\n format (default None) - see BaseAPIService._apply_format() for accepted values\n\n Returns a URL to obtain either all notes (note_id=None) or a specific note (note_id=integer). This call must\n include a format:\n - SEE BaseAPIService._apply_format() FOR ACCEPTED VALUES\n \"\"\"\n path = '/notes'\n url_params = dict()\n\n if note_id is not None:\n path += '/%s' % note_id\n elif contact_id is not None:\n url_params['noteable_type'] = 'Contact'\n url_params['noteable_id'] = contact_id\n elif deal_id is not None:\n url_params['noteable_type'] = 'Deal'\n url_params['noteable_id'] = deal_id\n elif lead_id is not None:\n url_params['noteable_type'] = 'Lead'\n url_params['noteable_id'] = lead_id\n\n if page is not None:\n url_params['page'] = page\n\n url_noparam = self._build_resource_url('common', 1, path, format)\n return url_noparam, url_params\n\n def _get_notes(self, note_id=None, contact_id=None, deal_id=None, lead_id=None, page=None):\n \"\"\"\n PRIVATE FUNCTION to get notes that can be called by public, single-purpose notes functions.\n\n RESPONSE STRUCTURE\n\n see get_notes(), get_note()\n \"\"\"\n url_noparam, url_params = self._build_note_resource(note_id=note_id, contact_id=contact_id, deal_id=deal_id,\n lead_id=lead_id, page=page)\n return self._get_data(url_noparam, url_params)\n\n def get_notes(self, page=1):\n \"\"\"\n Returns notes visible to the authenticated user in batches of 20. To filter by object type or ID see\n get_contact_notes(), get_lead_notes(), and get_deal_notes().\n\n ARGUMENTS\n\n Paging:\n page\n\n RESPONSE STRUCTURE\n\n [{'note':\n {'user_id': ...\n 'account_id': ...\n 'permissions_holder_id': ...\n 'created_at': ...\n 'updated_at': ...\n 'noteable_id': ...\n 'noteable_type': ...\n 'content': ...\n 'private': ...\n 'id': ...\n }\n }, ...]\n \"\"\"\n return self._get_notes(page=page)\n\n def get_note(self, note_id):\n \"\"\"\n Gets the attributes for the given note_id\n\n RESPONSE STRUCTURE\n\n {'note':\n {'user_id': ...\n 'account_id': ...\n 'permissions_holder_id': ...\n 'created_at': ...\n 'updated_at': ...\n 'noteable_id': ...\n 'noteable_type': ...\n 'content': ...\n 'private': ...\n 'id': ...\n }\n }\n \"\"\"\n return self._get_notes(note_id=note_id)\n\n def _upsert_note(self, content, note_id=None, contact_id=None, deal_id=None, lead_id=None):\n \"\"\"\n PRIVATE FUNCTION to create or update notes\n\n ATTRIBUTES\n\n Content:\n content - body of note\n Note Object or Parent Object (must include one, include only one):\n note_id\n contact_id\n deal_id\n lead_id\n Format:\n format (default None) - see BaseAPIService._apply_format() for accepted values\n\n RESPONSE STRUCTURE\n\n see get_note()\n\n NOTE that all objects must be encoded as note[] without the quotes normally introduced by URL encoding\n python dicts.\n \"\"\"\n url_noparams, note_params = self._build_note_resource(note_id=note_id, contact_id=contact_id, deal_id=deal_id,\n lead_id=lead_id)\n\n note_params['content'] = content\n url_params = _key_coded_dict({'note': note_params})\n\n if note_id is None:\n return self._post_data(url_noparams, url_params)\n else:\n return self._put_data(url_noparams, url_params)\n\n def update_note(self, content, note_id):\n \"\"\"\n Updates the content for the given note_id\n\n ATTRIBUTES\n\n note_id - id of note being modified\n content - the new content for the note\n\n RESPONSE STRUCTURE\n\n see get_note()\n \"\"\"\n self._upsert_note(content=content, note_id=note_id)\n\n def get_contact_notes(self, contact_id, page=0):\n \"\"\"\n Gets all notes associated with a specific contact (defined by Base's unique contat_id) in batches of 20\n\n RESPONSE STRUCTURE\n\n see get_note()\n \"\"\"\n return self._get_notes(contact_id=contact_id, page=page)\n\n def create_contact_note(self, content, contact_id):\n \"\"\"\n Creates a note associated with a specific contact (defined by Base's unique contact_id)\n with the content 'content'.\n\n RESPONSE STRUCTURE\n\n see get_note()\n \"\"\"\n return self._upsert_note(content=content, contact_id=contact_id)\n\n def update_contact_note(self, content, note_id):\n \"\"\"\n Edits a note (the note's unique note_id) with the content content.\n Returns a json or xml response.\n\n RESPONSE STRUCTURE\n\n see get_note()\n \"\"\"\n return self._upsert_note(content=content, note_id=note_id)\n\n def get_deal_notes(self, deal_id, page=0):\n return self._get_notes(deal_id=deal_id, page=page)\n\n def create_deal_note(self, content, deal_id):\n \"\"\"\n Creates a note associated with a specific deal (defined by Base's unique deal_id)\n with the content 'content'.\n Returns a json or xml response.\n \"\"\"\n return self._upsert_note(content=content, deal_id=deal_id)\n\n def update_deal_note(self, content, note_id):\n \"\"\"\n Edits a note (defined by Base's unique deal_id and the note's unique note_id)\n with the content content.\n Returns a json or xml response.\n \"\"\"\n return self._upsert_note(content=content, note_id=note_id)\n\n def get_lead_notes(self, lead_id, page=0):\n return self._get_notes(lead_id=lead_id, page=page)\n\n def create_lead_note(self, content, lead_id):\n \"\"\"\n Creates a note associated with a specific lead (defined by Base's unique lead_id)\n with the content 'content'.\n Returns a json or xml response.\n \"\"\"\n return self._upsert_note(content=content, lead_id=lead_id)\n\n def update_lead_note(self, content, note_id):\n \"\"\"\n Edits a note (the note's unique note_id) with the content content.\n Returns a json or xml response.\n\n RESPONSE STRUCTURE\n\n see get_note()\n \"\"\"\n return self._upsert_note(content=content, note_id=note_id)\n\n ##########################\n # Tasks Functions\n #\n # NOTE: tasks overlap to some degree with feeds (completed only)\n ##########################\n\n TASK_STATUS_OPTIONS = ['active', 'done']\n TASK_DUE_OPTIONS = ['today', 'tomorrow', 'this_week', 'overdue', 'no_due_date']\n\n # Count\n # https://app.futuresimple.com/apis/common/api/v1/tasks/context_count.json?page=1&status=done&_=1394056005668\n\n def _build_task_resource(self, task_id=None, contact_id=None, lead_id=None, deal_id=None, status=None, due=None,\n due_range=None, page=1):\n \"\"\"\n Returns a tuple of URL (without parameters) and format_data_get to get tasks in batches of 20.\n\n ARGUMENTS\n\n ...\n Format:\n format (default None) - see BaseAPIService._apply_format() for accepted values\n\n RESPONSE STRUCTURE\n\n see get_tasks()\n \"\"\"\n path = '/tasks'\n url_params = dict()\n\n if task_id is not None:\n path += '/%s' % task_id\n elif contact_id is not None:\n url_params['taskable_type'] = 'Contact'\n url_params['taskable_id'] = contact_id\n elif deal_id is not None:\n url_params['taskable_type'] = 'Deal'\n url_params['taskable_id'] = deal_id\n elif lead_id is not None:\n url_params['taskable_type'] = 'Lead'\n url_params['taskable_id'] = lead_id\n\n if due is not None:\n if due in self.TASK_DUE_OPTIONS:\n url_params['date'] = due\n else:\n raise ValueError(\"'due' is set to '%s', but only accepts: '%s'\" % str(due),\n \"', '\".join(self.TASK_DUE_OPTIONS))\n elif due_range is not None:\n if isinstance(due_range, tuple):\n if len(due_range) == 2:\n if due_range[0] > due_range[1]:\n url_params['send_time_from'] = due_range[1]\n url_params['send_time_to'] = due_range[0]\n else:\n url_params['send_time_from'] = due_range[0]\n url_params['send_time_to'] = due_range[1]\n else:\n raise ValueError(\"'due_range' must have length 2\")\n else:\n raise ValueError(\"'due_range' must be a tuple\")\n\n if status is not None:\n if status in self.TASK_STATUS_OPTIONS:\n url_params['status'] = status\n else:\n raise ValueError(\"'status' is set to '%s', but only accepts: '%s'\" % str(status),\n \"', '\".join(self.TASK_STATUS_OPTIONS))\n\n if page == -1:\n url_params['skip_pagination'] = True\n else:\n url_params['page'] = page\n\n url_params['page'] = page\n\n url_noparam = self._build_resource_url('common', 1, path)\n return url_noparam, url_params\n\n def _get_tasks(self, task_id=None, contact_id=None, lead_id=None, deal_id=None, status=None, due=None,\n due_range=None, page=1):\n \"\"\"\n PRIVATE FUNCTION to get tasks that can be called by public, single-purpose tasks functions.\n\n RESPONSE STRUCTURE\n\n see get_tasks(), get_task()\n \"\"\"\n url_noparam, url_params = self._build_task_resource(task_id=task_id, contact_id=contact_id, lead_id=lead_id,\n deal_id=deal_id, status=status, due=due,\n due_range=due_range, page=page)\n return self._get_data(url_noparam, url_params)\n\n def get_tasks(self, status=None, due=None, page=1):\n \"\"\"\n Returns tasks visible to the authenticated user in batches of 20. To filter by object type or ID see\n get_contact_tasks(), get_lead_tasks(), and get_deal_tasks().\n\n ARGUMENTS\n\n RESPONSE STRUCTURE\n\n [{task:\n {'due_date': ...\n 'is_overdue': ...\n 'user_id': ...\n 'account_id': ...\n 'hour': ...\n 'taskable_type': ...\n 'created_at': ...\n 'send_time': ...\n 'updated_at': ...\n 'content': ...\n 'remind': ...\n 'taskable_id': ...\n 'permissions_holder_id': ...\n 'done_at': ...\n 'date': ...\n 'done': ...\n 'id': ...\n 'owner_id': ...\n }\n }, ...]\n\n \"\"\"\n return self._get_tasks(status=status, due=due, page=page)\n\n def get_tasks_by_date_range(self, due_from, due_to, status=None, page=1):\n \"\"\"\n Gets all tasks meeting criteria in groups of 20\n\n ARGUMENTS\n\n Date Range (automatically detects order)\n date_from - tested with values of type datetime.datetime()\n date_to - tested with values of type datetime.datetime()\n Status\n status=None - all tasks\n status='active' - incomplete tasks\n status='done' - completed tasks\n Other\n page (default 1)\n\n RESPONSE STRUCTURE\n\n see get_tasks()\n \"\"\"\n return self._get_tasks(status=status, due_range=(due_from, due_to), page=page)\n\n def get_task(self, task_id):\n \"\"\"\n Returns the attributes of task identified by task_id\n\n RESPONSE STRUCTURE\n\n {task:\n {'due_date': ...\n 'is_overdue': ...\n 'user_id': ...\n 'account_id': ...\n 'hour': ...\n 'taskable_type': ...\n 'created_at': ...\n 'send_time': ...\n 'updated_at': ...\n 'content': ...\n 'remind': ...\n 'taskable_id': ...\n 'permissions_holder_id': ...\n 'done_at': ...\n 'date': ...\n 'done': ...\n 'id': ...\n 'owner_id': ...\n }\n }\n \"\"\"\n return self._get_tasks(task_id=task_id)\n\n # Relocate\n def get_contact_tasks(self, contact_id):\n return self._get_tasks(contact_id=contact_id)\n\n def get_deal_tasks(self, deal_id):\n return self._get_tasks(deal_id=deal_id)\n\n def get_lead_tasks(self, lead_id):\n return self._get_tasks(lead_id=lead_id)\n\n def _upsert_task(self, task_info, task_id=None, contact_id=None, lead_id=None, deal_id=None):\n \"\"\"\n PRIVATE FUNCTION to create or update a task\n\n ARGUMENTS\n\n task_info - dict of fields\n task_id (optional) - task being updated (otherwise it will be created)\n Parent object (choose one and only one):\n contact_id\n lead_id\n deal_id\n Format:\n format (default None) - see BaseAPIService._apply_format() for accepted values\n\n RESPONSE STRUCTURE\n\n see get_task()\n \"\"\"\n url_noparam, url_params = self._build_task_resource(task_id=task_id, contact_id=contact_id,\n lead_id=lead_id, deal_id=deal_id)\n if contact_id is not None:\n task_info['taskable_type'] = 'Contact'\n task_info['taskable_id'] = contact_id\n elif deal_id is not None:\n task_info['taskable_type'] = 'Deal'\n task_info['taskable_id'] = deal_id\n elif lead_id is not None:\n task_info['taskable_type'] = 'Lead'\n task_info['taskable_id'] = lead_id\n url_params = _key_coded_dict({'task': task_info})\n if task_id is None:\n return self._post_data(url_noparam, url_params)\n else:\n return self._put_data(url_noparam, url_params)\n\n def create_contact_task(self, task_info, contact_id):\n \"\"\"\n Creates a new task based on task_info and assigns it to a contact\n \"\"\"\n return self._upsert_task(task_info=task_info, contact_id=contact_id)\n\n def update_contact_task(self, task_info, task_id):\n \"\"\"\n Updates task identified by task_id with information from task_info\n \"\"\"\n return self._upsert_task(task_info=task_info, task_id=task_id)\n\n def create_deal_task(self, task_info, deal_id):\n \"\"\"\n Creates a new task based on task_info and assigns it to a deal\n \"\"\"\n return self._upsert_task(task_info=task_info, deal_id=deal_id)\n\n def update_deal_task(self, task_info, task_id):\n \"\"\"\n Updates task identified by task_id with information from task_info\n \"\"\"\n return self._upsert_task(task_info=task_info, task_id=task_id)\n\n def create_lead_task(self, task_info, lead_id):\n \"\"\"\n Creates a new task based on task_info and assigns it to a lead\n \"\"\"\n return self._upsert_task(task_info=task_info, lead_id=lead_id)\n\n def update_lead_task(self, task_info, task_id):\n \"\"\"\n Updates task identified by task_id with information from task_info\n \"\"\"\n return self._upsert_task(task_info=task_info, task_id=task_id)\n\n ##########################\n # Reminder Functions\n ##########################\n def _build_reminder_resource(self, reminder_id=None, contact_id=None, deal_id=None, format=None):\n \"\"\"\n Returns a tuple of URL (without parameters) and format_data_get to get reminders meeting the filter criteria\n\n Parent Object (optional, include only one):\n contact_id\n lead_id\n deal_id\n Format:\n format (default None) - see BaseAPIService._apply_format() for accepted values\n \"\"\"\n path = ''\n url_params = dict()\n\n if contact_id is not None:\n path += '/contacts/%d' % contact_id\n elif deal_id is not None:\n path += '/deals/%d' % deal_id\n else:\n raise ValueError(\"Reminders URL constructor requires a valid object (lead, contact, deal).\")\n path += '/reminders'\n if reminder_id is not None:\n path += '/%s' % reminder_id\n\n url_noparam = self._build_resource_url('sales', 1, path, format)\n return url_noparam, url_params\n\n def _get_reminder(self, reminder_id=None, contact_id=None, deal_id=None, format=None):\n url_noparam, url_params = self._build_reminder_resource(reminder_id=reminder_id, contact_id=contact_id,\n deal_id=deal_id, format=format)\n return self._get_data(url_noparam, url_params)\n\n def get_contact_reminders(self, contact_id):\n return self._get_reminder(contact_id=contact_id)\n\n def get_deal_reminders(self, deal_id):\n return self._get_reminder(deal_id=deal_id)\n\n # API does not appear to support reminders for leads\n\n def _upsert_reminder(self, reminder_info, reminder_id=None, contact_id=None, deal_id=None, format=None):\n \"\"\"\n PRIVATE FUNCTION to create or update a reminder\n\n ARGUMENTS\n\n reminder_info - dict of fields\n reminder_id (optional) - reminder being updated (otherwise it will be created)\n Parent object (choose one and only one):\n contact_id\n deal_id\n Format:\n format (default None) - see BaseAPIService._apply_format() for accepted values\n \"\"\"\n url_noparam, url_params = self._build_reminder_resource(reminder_id=reminder_id, contact_id=contact_id, deal_id=deal_id)\n url_params = _key_coded_dict({'reminder': reminder_info})\n if reminder_id is None:\n return self._post_data(url_noparam, url_params)\n else:\n return self._put_data(url_noparam, url_params)\n\n def create_contact_reminder(self, reminder_info, contact_id):\n \"\"\"\n Creates a reminder based on reminder_info and assigns it to a contact\n \"\"\"\n return self._upsert_reminder(reminder_info=reminder_info, contact_id=contact_id)\n\n def create_deal_reminder(self, reminder_info, deal_id):\n \"\"\"\n Creates a reminder based on reminder_info and assigns it to a deal\n \"\"\"\n return self._upsert_reminder(reminder_info=reminder_info, deal_id=deal_id)\n # Base returns error 500 when updating any kind of reminders\n\n ##########################\n # Contact Functions and Constants\n #\n # NOT YET IMPLEMENTED\n ##########################\n def _build_contact_resource(self, contact_id=None, contact_ids=None, company_id=None, deal_id=None,\n page=1, per_page=None, format=None):\n \"\"\"\n Returns a tuple of URL (without parameters) and format_data_get to get contacts that meet filter criteria in batches\n of 20\n\n ARGUMENTS\n\n Object or Parent Object (optional, include only one)\n deal_id - gets all contacts under the submitted deal_id\n contact_ids - list of contacts\n company_id - ID of the BaseCRM contact object for the parent company\n Paging:\n page (default 1)\n per_page (API default 20) - changes the batch size of pages\n Format:\n format (default None) - see BaseAPIService._apply_format() for accepted values\n \"\"\"\n path = '/contacts'\n url_params = dict()\n\n if deal_id is not None:\n # Nested under deals URL so we have to use an atypical construction\n url_noparam, ignore_params = self._build_deal_resource(deal_id)\n url_noparam += path\n self._apply_format(url_noparam, format)\n else:\n if contact_id is not None:\n # Creates contacts/ path required for updates\n path += '/%d' % contact_id\n elif contact_ids is not None:\n # Used by all get() callers to increase standardization of response\n url_params['contact_ids'] = ','.join(str(x) for x in contact_ids)\n elif company_id is not None:\n url_params['contact_id'] = company_id\n url_noparam = self._build_resource_url('crm', 1, path, format)\n\n url_params['page'] = page\n if per_page is not None:\n url_params['per_page'] = per_page\n\n return url_noparam, url_params\n\n def get_contacts(self, contact_ids=None, page=1, per_page=None):\n \"\"\"\n Gets full contact records (38 fields) in batches of (default) 20.\n\n Arguments:\n page (default: 1) - the page of contacts to return\n per_page (default: 20) - the number of contacts to return per page\n contact_ids - allows the caller to specify a list of contacts to be returned\n\n Native response structure:\n [{'contact':\n {'account_id': ...\n 'address': ...\n 'city': ...\n 'contact_id': ...\n 'country': ...\n 'created_at': ...\n 'creator_id': ...\n 'custom_fields': ...\n 'description': ...\n 'email': ...\n 'facebook': ...\n 'fax': ...\n 'first_name': ...\n 'id': ...\n 'industry': ...\n 'is_organisation': ...\n 'is_sales_account': ...\n 'last_name': ...\n 'linkedin': ...\n 'linkedin_display': ...\n 'mobile': ...\n 'name': ...\n 'organisation': ...\n 'organisation_name': ...\n 'phone': ...\n 'picture_url': ...\n 'private': ...\n 'region': ...\n 'root_entity_id': ...\n 'root_entity_name': ...\n 'sales_account': ...\n 'skype': ...\n 'tags_joined_by_comma': ...\n 'title': ...\n 'twitter': ...\n 'updated_at': ...\n 'user_id': ...\n 'website': ...\n 'zip': ...\n }\n }, ...]\n \"\"\"\n url_noparam, url_params = self._build_contact_resource(contact_ids=contact_ids, page=page, per_page=per_page)\n return self._get_data(url_noparam, url_params)\n\n def get_deal_contacts(self, deal_id, page=1, per_page=None):\n url_noparam, url_params = self._build_contact_resource(deal_id=deal_id, page=page, per_page=per_page)\n return self._get_data(url_noparam, url_params)\n\n def get_contact(self, contact_id):\n \"\"\"\n Gets the contact with the given contact_id. Returns the contact info.\n \"\"\"\n response = self.get_contacts(contact_ids=[contact_id])\n if len(response) > 0:\n return response[0]\n else:\n return None\n\n def search_contacts(self, filters=None, sort_by=None, sort_order='asc', tags_exclusivity='and', page=0):\n \"\"\"\n Returns short (17 field) records for contacts meeting the filter criteria and ordered by sort criteria, in\n batches of 20\n\n ARGUMENTS\n\n Filter:\n filters - dict of filters (automatically joined by AND) where the key is the field name (see CONTACT_FILTERS\n for valid values) and the value is the matching criteria\n tags_exclusivity - if 'tags' or 'tag_ids' are included in the filter criteria, this determines whether the\n tags are combined using the AND or OR operator\n Sort:\n sort_by - a string identifying the field on which the responses should be sorted (see CONTACT_SORTS for\n valid values)\n sort_order - 'asc' or 'desc'\n Paging:\n page (default 0)\n\n RESPONSE STRUCTURE\n\n {'items':\n [{'contact':\n {'organisation_name': ...\n 'first_name': ...\n 'last_name': ...\n 'user_id': ...\n 'account_id': ...\n 'title': ...\n 'mobile': ...\n 'created_at': ...\n 'overdue_tasks': ...\n 'is_sales_account': ...\n 'id': ...\n 'phone': ...\n 'is_organisation': ...\n 'sort_value': ...\n 'email': ...\n 'unread_emails': ...\n 'name': ...\n }\n }, ...],\n 'success': ...\n 'metadata': ...\n }\n \"\"\"\n url_noparam = self._build_search_url('contact')\n\n valid_params = {'page': page}\n if filters is not None:\n for key, value in filters.items():\n if key in self.CONTACT_FILTERS:\n if key in ['tag_ids', 'tags']:\n # tags are case sensitive\n valid_params[key] = ','.join(value)\n if tags_exclusivity in ['and', 'or']:\n valid_params['tags_exclusivity'] = tags_exclusivity\n else:\n raise ValueError(\"tags_exclusivity must be 'and' or 'or'\")\n else:\n # only lower case strings successfully match (regardless of original text case)\n valid_params[key] = str(value).lower()\n else:\n raise ValueError(\"%s is not a valid filter for a Contact search\" % key)\n if sort_by is not None:\n if sort_by in self.CONTACT_SORTS:\n valid_params['sort_by'] = sort_by\n else:\n raise ValueError(\"%s is not a valid sort field for a Contact search\" % sort_by)\n if sort_order in ['asc', 'desc']:\n valid_params['sort_order'] = sort_order\n else:\n raise ValueError(\"%s is not a valid sort order for a Contact search\" % sort_order)\n\n return self._get_data(url_noparam, valid_params)\n\n def _upsert_contact(self, contact_info=None, contact_id=None):\n \"\"\"\n Updates or Inserts a contact\n\n ARGUMENTS\n\n contact_info - dict of fields (see CONTACT_PARAMS for valid field names)\n contact_id (optional) - contact being updated (otherwise contact will be created)\n\n RESPONSE STRUCTURE\n\n see get_contact()\n \"\"\"\n url_noparam, url_params = self._build_contact_resource(contact_id=contact_id)\n\n # If we are creating a new contact, we must have name and last_name parameters\n # and we always must have some parameter\n if contact_info is None or contact_info == {} or \\\n (contact_id is None and 'name' not in contact_info.keys() and 'last_name' not in contact_info.keys()):\n raise KeyError(\"Contact record must include 'contact_id' or a name ('name' or 'last_name')\")\n\n custom_fields = contact_info.pop('custom_fields', {})\n # Keys in contact_info need to be in CONTACT_PARAMS\n for key in contact_info.keys():\n if key not in self.CONTACT_PARAMS:\n raise KeyError(\"'%s' is not a valid parameter for Contact creation.\" % key)\n\n # To urlencode properly, the python dict key must be set to 'contact[]'\n # _key_coded_dict() is designed to automate this process\n contact_param = _key_coded_dict({'contact': contact_info})\n for key, value in custom_fields.items():\n contact_param['contact[custom_fields][%s]' % key] = value\n url_params.update(contact_param)\n\n if contact_id is None:\n return self._post_data(url_noparam, url_params)\n else:\n return self._put_data(url_noparam, url_params)\n\n def create_contact(self, contact_info):\n \"\"\"\n Creates a new contact based on contact_info\n\n ARGUMENTS\n\n contact_info - dict of fields (see CONTACT_PARAMS for valid field names)\n\n RESPONSE STRUCTURE\n\n see get_contact()\n \"\"\"\n return self._upsert_contact(contact_info=contact_info, contact_id=None)\n\n def update_contact(self, contact_info, contact_id):\n \"\"\"\n Edits contact with the unique base_id based on contact_info with fields shown in CONTACT_PARAMS.\n\n ARGUMENTS\n\n contact_info - dict of fields (see CONTACT_PARAMS for valid field names)\n contact_id - contact being updated\n\n RESPONSE STRUCTURE\n\n see get_contact()\n \"\"\"\n return self._upsert_contact(contact_info=contact_info, contact_id=contact_id)\n\n def _unwrap_custom_fields(self, response):\n \"\"\"\n Unwraps one level of indirection of custom field definitions\n \"\"\"\n fields = {}\n for item in response:\n field = item['custom_field']\n if field['list_options']:\n field['list_options'] = dict(field['list_options'])\n fields[field['name']] = field\n return fields\n\n def get_contact_custom_fields(self, filterable=False):\n \"\"\"\n Returns contact custom field definitions\n\n ARGUMENTS\n\n filterable - if True, return only fields marked as filterable\n\n RESPONSE STRUCTURE\n\n Note: for dropdown fields, list_options is a dict mapping option IDs\n to their values\n\n {'field name':\n {'custom_scope': ...\n 'date_time': ...\n 'field_type': ...\n 'filterable': ...\n 'for_contact': ...\n 'for_organisation': ...\n 'id': ...\n 'list_options': ...\n 'list_options_max': ...\n 'name': ...\n 'owner_id': ...\n 'owner_type': ...\n 'position': ...\n 'settings': ...\n 'value_editable_only_by_admin': ...\n },\n ...}\n \"\"\"\n path = '/custom_fields'\n url_noparam = self._build_resource_url('crm', 1, path)\n url_params = {\n 'filterable': str(filterable).lower(),\n }\n response = self._get_data(url_noparam, url_params)\n return self._unwrap_custom_fields(response)\n\n ##########################\n # Deals Functions and Constants\n ##########################\n def _build_deal_resource(self, deal_id=None, deal_ids=None, contact_ids=None, stage=None, page=1, per_page=None,\n format=None):\n \"\"\"\n Returns a tuple of URL (without parameters) and format_data_get to get deal objects meeting filter criteria\n\n ARGUMENTS\n\n Object or Parent Object (include only one)\n deal_id\n contact_id\n Format:\n format (default None) - see BaseAPIService._apply_format() for accepted values\n\n RESPONSE STRUCTURE\n\n see get_deal()\n \"\"\"\n url_params = dict()\n path = '/deals'\n\n if contact_ids is not None:\n # https://app.futuresimple.com/apis/sales/api/v2/contacts/deals.json?contact_ids=40905809\n url_params['contact_ids'] = contact_ids\n url_noparam = self._build_resource_url('sales', 2, '/contacts/deals', format)\n else:\n if stage is None:\n url_params['dont_scope_by_stage'] = 'true'\n elif stage in self.DEAL_STAGES:\n url_params['stage'] = stage\n else:\n raise ValueError(\"'%s' is not a valid stage, must come from '%s'\" % str(stage),\n ','.join(self.DEAL_STAGES))\n\n if deal_id is not None:\n path += '/%d' % deal_id\n elif deal_ids is not None:\n # Used by all get() callers to increase standardization\n url_params['deal_ids'] = ','.join(str(x) for x in deal_ids)\n url_noparam = self._build_resource_url('sales', 1, path, format)\n\n url_params['page'] = page\n if per_page is not None:\n url_params['per_page'] = per_page\n\n return url_noparam, url_params\n\n def get_deals(self, deal_ids=None, page=1, stage=None):\n \"\"\"\n Gets deal objects matching filter criteria.\n\n ARGUMENTS\n\n stage (default None) - the stage of deals to return (see DEAL_STAGES list for options)\n page (default 1) - the set of deals to return\n\n RESPONSE STRUCTURE\n\n see search_deals()\n \"\"\"\n url_noparam, url_params = self._build_deal_resource(deal_ids=deal_ids, stage=stage, page=page)\n return self._get_data(url_noparam, url_params)\n\n def get_deal(self, deal_id):\n \"\"\"\n Gets the deal with the given deal_id. Returns the deal info.\n \"\"\"\n url_noparam, url_params = self._build_deal_resource(deal_ids=[deal_id])\n return self._get_data(url_noparam, url_params)\n\n def search_deals(self, filters=None, sort_by=None, sort_order='asc', tags_exclusivity='and', page=1):\n \"\"\"\n Returns records for deals meeting the filter criteria and ordered by sort criteria, in batches of 20\n\n Native response structure:\n {'items':\n [{'deal':\n {'account_id': ...\n 'added_on': ...\n 'contact_ids': ...\n 'created_at': ...\n 'currency': ...\n 'deal_account': ...\n 'deal_tags': ...\n 'dropbox_email': ...\n 'entity_id': ...\n 'exchange_rate': ...\n 'hot': ...\n 'id': ...\n 'is_closed': ...\n 'is_new': ...\n 'last_stage_change_at': ...\n 'loss_reason_id': ...\n 'name': ...\n 'overdue_tasks': ...\n 'scope': ...\n 'sort_value': ...\n 'source_id': ...\n 'stage_code': ...\n 'stage_id': ...\n 'stage_name': ...\n 'unread_emails': ...\n 'updated_at': ...\n 'user_id': ...\n 'user_name': ...\n }\n }, ...],\n 'success': ...\n 'metadata': ...\n }\n \"\"\"\n url_noparam = self._build_search_url('deal')\n\n valid_params = dict()\n valid_params['page'] = page\n\n # Handle stage separately because it requires extra validation\n if filters is None or 'stage' not in filters:\n valid_params['dont_scope_by_stage'] = True\n elif filters['stage'] is None:\n valid_params['dont_scope_by_stage'] = True\n del filters['stage']\n elif filters['stage'] in self.DEAL_STAGES:\n valid_params['stage'] = filters['stage']\n del filters['stage']\n else:\n raise ValueError('Stage must be absent, None, or a value from DEAL_STAGES.')\n\n # Handle other filters\n if filters is not None:\n for key, value in filters.items():\n if key in self.DEAL_FILTERS:\n if key in ['tag_ids', 'tags']:\n # tags are case sensitive\n valid_params[key] = ','.join(value)\n if tags_exclusivity in ['and', 'or']:\n valid_params['tags_exclusivity'] = tags_exclusivity\n else:\n raise ValueError(\"tags_exclusivity must be 'and' or 'or'\")\n else:\n # only lower case strings successfully match (regardless of original text case)\n valid_params[key] = str(value).lower()\n else:\n raise ValueError(\"%s is not a valid filter for a deal search\" % key)\n\n # Configure sort order\n if sort_by is not None:\n if sort_by in self.DEAL_SORTS:\n valid_params['sort_by'] = sort_by\n else:\n raise ValueError(\"%s is not a valid sort field for a deal search\" % sort_by)\n if sort_order in ['asc', 'desc']:\n valid_params['sort_order'] = sort_order\n else:\n raise ValueError(\"%s is not a valid sort order for a deal search\" % sort_order)\n\n return self._get_data(url_noparam, valid_params)\n\n def _upsert_deal(self, deal_info=None, deal_id=None):\n \"\"\"\n Updates or Inserts a deal\n\n ARGUMENTS\n\n deal_info - dict of fields (see DEAL_PARAMS for valid field names)\n deal_id (optional) - deal being updated (otherwise new deal will be created)\n\n RESPONSE STRUCTURE\n\n see get_deal()\n \"\"\"\n url_noparam, url_params = self._build_deal_resource(deal_id=deal_id)\n\n # If we are creating a new deal, we must have name and entity_id parameters\n # and we always must have some parameter\n if deal_info is None or (deal_id is None and\n ('name' not in deal_info.keys() or 'entity_id' not in deal_info.keys())):\n return \"Missing required attributes 'name' or 'entity_id'\"\n\n final_params = dict()\n custom_fields = deal_info.pop('custom_fields', {})\n for key in deal_info.keys():\n if key not in self.DEAL_PARAMS:\n return \"%s is not a legal deal attribute\" % key\n else:\n final_params[key] = deal_info[key]\n for key, value in custom_fields.items():\n final_params['custom_fields[%s]' % key] = value\n\n if deal_id is None:\n return self._post_data(url_noparam, final_params)\n else:\n return self._put_data(url_noparam, final_params)\n\n def create_deal(self, deal_info):\n \"\"\"\n Creates a new deal based on deal_info\n\n ARGUMENTS\n\n deal_info - dict of fields (see CONTACT_PARAMS for valid field names)\n\n RESPONSE STRUCTURE\n\n see get_deal()\n \"\"\"\n return self._upsert_deal(deal_info=deal_info)\n\n def update_deal(self, deal_info, deal_id):\n \"\"\"\n Edits deal with the unique base_id based on deal_info with fields shown in CONTACT_PARAMS.\n\n ARGUMENTS\n\n deal_info - dict of fields (see CONTACT_PARAMS for valid field names)\n deal_id - deal being updated\n\n RESPONSE STRUCTURE\n\n see get_deal()\n \"\"\"\n return self._upsert_deal(deal_info=deal_info, deal_id=deal_id)\n\n def get_deal_custom_fields(self, filterable=False):\n \"\"\"\n Returns deal custom field definitions\n\n ARGUMENTS\n\n filterable - if True, return only fields marked as filterable\n\n RESPONSE STRUCTURE\n\n Note: for dropdown fields, list_options is a dict mapping option IDs\n to their values\n\n {'field name':\n {'custom_scope': ...\n 'date_time': ...\n 'field_type': ...\n 'filterable': ...\n 'id': ...\n 'list_options': ...\n 'list_options_max': ...\n 'name': ...\n 'owner_id': ...\n 'owner_type': ...\n 'position': ...\n 'settings': ...\n 'value_editable_only_by_admin': ...\n 'writable': ...\n },\n ...}\n \"\"\"\n path = '/deal_custom_fields'\n url_noparam = self._build_resource_url('sales', 1, path)\n url_params = {\n 'filterable': str(filterable).lower(),\n }\n response = self._get_data(url_noparam, url_params)\n return self._unwrap_custom_fields(response)\n\n ##########################\n # Sources Functions\n ##########################\n SOURCES_VALUES = ['all', 'mine', 'auto']\n\n def _build_sources_resource(self, source_id=None, type='all', format=None):\n \"\"\"\n Returns a tuple of URL (without parameters) and format_data_get to get source objects meeting filter criteria\n\n ARGUMENTS\n\n Object ID (do not combine with type):\n source_id - the ID of the source record\n Type (do not combine with source_id):\n type='all' (default) - list all sources, regardless of who created them\n type='mine' - only list sources created by authenticated user\n type='auto' - (unknown behavior)\n\n RESPONSE STRUCTURE\n\n see get_sources(), get_source()\n \"\"\"\n path = '/sources'\n url_params = dict()\n\n if source_id is not None:\n path += '/%d' % source_id\n else:\n if type in self.SOURCES_VALUES:\n if type == 'all':\n url_params['other'] = 1\n elif type == 'auto':\n url_params['auto'] = 1\n else:\n raise ValueError(\"'type' was set to '%s', but must come from '%s'\" % str(type),\n \"', '\".join(['all', 'mine', 'auto']))\n\n url_noparam = self._build_resource_url('sales', 1, path, format)\n return url_noparam, url_params\n\n def get_sources(self, type='auto'):\n \"\"\"\n Get all records for sources (of deals) of the indicated type\n\n ARGUMENTS\n\n Type:\n type='all' (default) - list all sources, regardless of who created them\n type='mine' - only list sources created by authenticated user\n type='auto' - (unknown behavior)\n\n RESPONSE STRUCTURE\n\n [{'source':\n {'created_at': ...\n 'id': ...\n 'name': ...\n 'permissions_holder_id': ...\n 'updated_at': ...\n 'user_id': ...\n }\n }, ...]\n \"\"\"\n url_noparam, url_params = self._build_sources_resource(type=type)\n return self._get_data(url_noparam, url_params)\n\n def get_source(self, source_id):\n \"\"\"\n Get record for source (of deals) indicated by source_id\n\n ARGUMENTS\n\n source_id - the ID of the source record\n\n RESPONSE STRUCTURE\n\n {'source':\n {'created_at': ...\n 'id': ...\n 'name': ...\n 'permissions_holder_id': ...\n 'updated_at': ...\n 'user_id': ...\n }\n }\n \"\"\"\n url_noparam, url_params = self._build_sources_resource(source_id=source_id)\n return self._get_data(url_noparam, url_params)\n\n ##########################\n # Lead Functions and Constants\n ##########################\n\n def _build_lead_resource(self, lead_id=None, page=None, per_page=None, format=None):\n \"\"\"\n Returns a tuple of URL (without parameters) and format_data_get to get lead objects meeting filter criteria\n\n ARGUMENTS\n\n Object ID:\n lead_id -\n Format:\n format (default None) - see BaseAPIService._apply_format() for accepted values\n\n RESPONSE STRUCTURE\n\n see get_leads(), get_lead()\n \"\"\"\n path = '/leads'\n url_params = dict()\n\n if lead_id is not None:\n path += '/%d' % lead_id\n if page is not None:\n url_params['page'] = page\n if per_page is not None:\n url_params['per_page'] = per_page\n\n url_noparam = self._build_resource_url('leads', 1, path, format)\n return url_noparam, url_params\n\n def get_leads(self, page=0, per_page=20):\n \"\"\"\n Gets lead objects in batches of 20\n\n ARGUMENTS\n\n page - the set of leads to return. 0 (default) returns the first 20.\n\n RESPONSE STRUCTURE\n\n {'items':\n [{'lead':\n {'account_id': ...\n 'added_on': ...\n 'company_name': ...\n 'conversion_name': ...\n 'created_at': ...\n 'display_name': ...\n 'first_name': ...\n 'id': ...\n 'last_activity_date': ...\n 'last_name': ...\n 'owner_id': ...\n 'sort_value': ...\n 'state': ...\n 'user_id': ...\n }\n 'success': ...\n 'metatdata': ...\n }, ...],\n 'success': ...\n 'metadata': ...\n }\n \"\"\"\n url_noparam, url_params = self._build_lead_resource(page=page, per_page=per_page)\n return self._get_data(url_noparam, url_params)\n\n def get_lead(self, lead_id):\n \"\"\"\n Gets the lead with the given lead_id\n\n ARGUMENTS\n\n lead_id - the ID of a lead\n\n RESPONSE STRUCTURE\n\n {'lead':\n {'first_name': ...\n 'last_name': ...\n 'user_id': ...\n 'account_id': ...\n 'sort_value': ...\n 'created_at': ...\n 'last_activity_date': ...\n 'conversion_name': ...\n 'state': ...\n 'company_name': ...\n 'display_name': ...\n 'id': ...\n 'added_on': ...\n 'owner_id': ...\n }\n 'success': ...\n 'metatdata': ...\n }\n \"\"\"\n url_noparam, url_params = self._build_lead_resource(lead_id=lead_id)\n return self._get_data(url_noparam, url_params)\n\n def search_leads(self, filters=None, sort_by=None, sort_order='asc', tags_exclusivity='and', page=0, per_page=20):\n \"\"\"\n Returns records for leads meeting the filter criteria and ordered by sort criteria, in batches\n\n ARGUMENTS\n\n Paging:\n page (default 0) - the set of leads to return\n per_page - the number of objects listed on each page\n\n RESPONSE STRUCTURE\n\n {'items':\n [{'lead':\n {'first_name': ...\n 'last_name': ...\n 'user_id': ...\n 'account_id': ...\n 'sort_value': ...\n 'created_at': ...\n 'last_activity_date': ...\n 'conversion_name': ...\n 'state': ...\n 'company_name': ...\n 'display_name': ...\n 'id': ...\n 'added_on': ...\n 'owner_id': ...\n }\n 'success': ...\n 'metatdata': ...\n }, ...],\n 'success': ...\n 'metadata': ...\n }\n \"\"\"\n url_noparam = self._build_search_url('lead')\n valid_params = dict()\n\n valid_params['page'] = page\n valid_params['per_page'] = per_page\n\n if filters is not None:\n for key, value in filters.items():\n if key in self.LEAD_FILTERS:\n if key in ['tag_ids', 'tags']:\n # tags are case sensitive\n valid_params[key] = ','.join(value)\n if tags_exclusivity in ['and', 'or']:\n valid_params['tags_exclusivity'] = tags_exclusivity\n else:\n raise ValueError(\"tags_exclusivity must be 'and' or 'or'\")\n else:\n # only lower case strings successfully match (regardless of original text case)\n valid_params[key] = str(value).lower()\n else:\n raise ValueError(\"%s is not a valid filter for a Lead search\" % key)\n\n if sort_by is not None:\n if sort_by in self.LEAD_SORTS:\n valid_params['sort_by'] = sort_by\n else:\n raise ValueError(\"%s is not a valid sort field for a Lead search\" % sort_by)\n if sort_order in ['asc', 'desc']:\n valid_params['sort_order'] = sort_order\n else:\n raise ValueError(\"%s is not a valid sort order for a Lead search\" % sort_order)\n\n return self._get_data(url_noparam, valid_params)\n\n def _upsert_lead(self, lead_info=None, lead_id=None):\n \"\"\"\n Updates or Inserts a lead\n\n ARGUMENTS\n\n lead_info - dict of fields (see DEAL_PARAMS for valid field names)\n lead_id (optional) - lead being updated (otherwise new lead will be created)\n\n RESPONSE STRUCTURE\n\n see get_lead()\n \"\"\"\n url_noparam, url_params = self._build_lead_resource(lead_id=lead_id)\n\n # If we are creating a new lead, we must have name and entity_id parameters\n # and we always must have some parameter\n if lead_info is None or (lead_id is None and 'last_name' not in lead_info.keys() and\n 'company_name' not in lead_info.keys()):\n raise KeyError(\"Lead record must include 'lead_id' or a name ('last_name' or 'company_name')\")\n\n lead_params = dict()\n custom_fields = lead_info.pop('custom_fields', {})\n for key in lead_info.keys():\n if key not in self.LEAD_PARAMS:\n raise KeyError(\"'%s' is not a legal lead attribute\" % key)\n else:\n lead_params[key] = lead_info[key]\n lead_params = _key_coded_dict({'lead': lead_params})\n for key, value in custom_fields.items():\n lead_params['lead[custom_field_values][%s]' % key] = value\n url_params.update(lead_params)\n\n if lead_id is None:\n return self._post_data(url_noparam, url_params)\n else:\n return self._put_data(url_noparam, url_params)\n\n","sub_path":"v1/legacy.py","file_name":"legacy.py","file_ext":"py","file_size_in_byte":78537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"425749001","text":"\n# coding: utf-8\n\n# In[1]:\n\n\n# All the file imports\nget_ipython().system('pip install prettytable')\nfrom datetime import datetime\nfrom prettytable import PrettyTable\nimport os\n\n\n# In[2]:\n\n\ndef isDateParent(A):\n return A[1] in tag_fam[\"DATE\"]\n\n\n# In[3]:\n\n\n# Convert month string to month number\n# :param month for which we need the number\ndef month_to_num(shortMonth):\n return{\n 'JAN' : \"1\",\n 'FEB' : \"2\",\n 'MAR' : \"3\",\n 'APR' : \"4\",\n 'MAY' : \"5\",\n 'JUN' : \"6\",\n 'JUL' : \"7\",\n 'AUG' : \"8\",\n 'SEP' : \"9\", \n 'OCT' : \"10\",\n 'NOV' : \"11\",\n 'DEC' : \"12\"\n }[shortMonth]\n\n\n# In[4]:\n\n\n# Convert input date to standard format\n# :param date array in input\ndef convert_date(date_arr):\n return \"{}-{}-{}\".format(date_arr[2], month_to_num(date_arr[1]), date_arr[0])\n\n\n# In[5]:\n\n\n# Determine age based on birthdate and death date\n# If death date is not present then function uses the current date as a comparison\ndef determine_age(birth_date, death_date):\n birth_month= birth_date.split('-')[1]\n birth_day= birth_date.split('-')[2]\n \n if death_date:\n death_month=death_date.split('-')[1]\n death_day=death_date.split('-')[2]\n return int(death_date.split('-')[0]) - int(birth_date.split('-')[0])-((int(death_month), int(death_day))< (int(birth_month), int(birth_day)))\n else:\n today = datetime.today()\n return today.year - int(birth_date.split('-')[0]) - ((today.month, today.day) < (int(birth_month), int(birth_day)))\n\n\n# In[6]:\n\n\n# Determine days difference\n# For US 08 and 09\ndef determine_days(date1, date2):\n year1=int(date1.split('-')[0])\n month1= int(date1.split('-')[1])\n day1= int(date1.split('-')[2])\n \n if date2 == None:\n year2 = int(datetime.today().strftime(\"%Y\"))\n month2 = int(datetime.today().strftime(\"%m\"))\n day2 = int(datetime.today().strftime(\"%d\"))\n else:\n year2=int(date2.split('-')[0])\n month2= int(date2.split('-')[1])\n day2= int(date2.split('-')[2])\n \n return (year2 - year1) * 365 + (month2 - month1)* 30 + day2- day1\n\n\n# In[7]:\n\n\ndef find_name(arr, _id):\n #takes array of dict objects\n for indi in arr:\n if _id == indi[\"INDI\"]:\n return indi[\"NAME\"]\n return \"NA\"\n\n\n# In[8]:\n\n\n# create dictionary entry for the passed tag\n# :param current_arr is the current array line being processed\n# :param tag can will be either FAM or INDI\ndef create_dic_entry(current_arr, tag):\n current_tag=tag\n dic={}\n dic[tag]=current_arr[1]\n return dic, current_tag\n\n\n# In[9]:\n\n\n# Adds missing tags with \"NA\"\ndef add_missing_entries(dic):\n if \"DIV\" not in dic:\n dic[\"DIV\"] = \"NA\"\n if \"HUSB\" not in dic:\n dic[\"HUSB\"] = \"NA\"\n if \"HUSB_NAME\" not in dic:\n dic[\"HUSB_NAME\"] = \"NA\"\n if \"WIFE\" not in dic:\n dic[\"WIFE\"] = \"NA\"\n if \"WIFE_NAME\" not in dic:\n dic[\"WIFE_NAME\"] = \"NA\"\n if \"FAM_CHILD\" not in dic:\n dic[\"FAM_CHILD\"] = \"NA\"\n if \"MARR\" not in dic:\n dic[\"MARR\"] = \"NA\" \n\n\n# In[10]:\n\n\n# Checking if one date is after another\n# :param date_one is the date being compared with\n# :param date_two is the date being compared t0\ndef is_date_after(date_one, date_two):\n return date_one < date_two\n\n\n# In[11]:\n\n\n# Create map of individuals where key is the individual id and\n# individual object is the value\ndef create_individuals_map():\n global individuals\n individuals = {}\n for individual in document[\"INDI\"]:\n individuals[individual[\"INDI\"]] = individual\n\n\n# In[12]:\n\n\n# Creating a family dictionary with the key as the family id and the value as the\n# information about the family and the objects corresponding to husband, wife and children\ndef create_family_dic():\n global family_dic\n family_dic = {}\n for family in document[\"FAM\"]:\n if family[\"HUSB\"] != \"NA\" and family[\"HUSB\"] in individuals:\n family[\"husband_object\"] = individuals[family[\"HUSB\"]]\n elif family[\"HUSB\"] != \"NA\" and family[\"HUSB\"] not in individuals:\n #append husband error\n error_array.append(\"ERROR: FAMILY: US26: {}: Family {} has invalid husband ID\".format(family[\"FAM_LINE\"], family[\"FAM\"]))\n family[\"husband_object\"] = \"NA\"\n family[\"HUSB\"] = \"NA\"\n if family[\"WIFE\"] != \"NA\" and family[\"WIFE\"] in individuals:\n family[\"wife_object\"] = individuals[family[\"WIFE\"]]\n elif family[\"WIFE\"] != \"NA\" and family[\"WIFE\"] not in individuals:\n #append wife error\n error_array.append(\"ERROR: FAMILY: US26: {}: Family {} has invalid wife ID\".format(family[\"FAM_LINE\"], family[\"FAM\"]))\n family[\"wife_object\"] = \"NA\"\n family[\"WIFE\"] = \"NA\"\n if family[\"FAM_CHILD\"] != \"NA\":\n children = []\n valid_children_id = []\n for child in family[\"FAM_CHILD\"]:\n if child in individuals and individuals[child] != \"NA\":\n children.append(individuals[child])\n valid_children_id.append(child)\n else:\n #append child error\n error_array.append(\"ERROR: FAMILY: US26: {}: Family {} has invalid child ID\".format(family[\"FAM_LINE\"], family[\"FAM\"]))\n family[\"children_objects\"] = children\n family[\"FAM_CHILD\"] = valid_children_id\n family_dic[family[\"FAM\"]] = family\n \n\n\n# In[13]:\n\n\n# Reads the input GEDCOM file line by line and store the data into the dictionary\ndef read_in(file):\n doc={\"INDI\":[], \"FAM\":[]}\n dic={}\n global ui\n ui=[]\n global uf\n uf=[]\n temp = \"\"\n flag=False #indicates whether the correct tag has appeared before DATE tag\n with open(file) as f:\n all_lines=f.readlines()\n line_num = 1 #line number of each \n for line, next_line in zip(all_lines, all_lines[1:]):\n current_arr=line.strip().split(\" \")\n next_arr=next_line.strip().split(\" \")\n #if the current tag is individual\n if (len(current_arr)==3 and current_arr[0]=='0' and current_arr[2]== \"INDI\"):\n temp = current_arr[1]\n unique_indi_and_family(temp, \"INDI\", line_num)\n #inserts individual's ID into the dictionary\n dic, current_tag=create_dic_entry(current_arr, \"INDI\") \n #inserts line number\n dic[\"INDI_LINE\"] = line_num\n #if the current tag is family\n elif len(current_arr)==3 and current_arr[0]=='0' and current_arr[2]==\"FAM\": \n temp = current_arr[1]\n unique_indi_and_family(temp, \"FAM\", line_num)\n dic, current_tag=create_dic_entry(current_arr, \"FAM\")\n #inserts line number\n dic[\"FAM_LINE\"] = line_num\n #if the current tag is date\n elif current_arr[1]==\"DATE\" and flag:\n flag=False\n date_arr = current_arr[2:] #extracts the date argument from the line\n partial_date=include_partial_dates(date_arr, line_num, tmp, list(dic.values())[0])\n datecheck=convert_date(partial_date) #converts the date into correct format\n valid_date=validate_date(datecheck, line_num, tmp, list(dic.values())[0])\n dic[tmp]=valid_date\n #determines if the tag level is correct\n elif current_arr[0]=='1' and current_arr[1] in tag_one:\n #\"NAME\", \"SEX\", \"BIRT\", \"DEAT\",\"FAMC\",\"FAMS\",\"MARR\", \"DIV\",\"HUSB\",\"WIFE\",\"CHIL\"\n if (isDateParent(current_arr)): #determines whether the current tag is parent of DATE tag\n tmp=current_arr[1] #extracts the tag name\n flag=True\n #inserts line number\n dic[tmp + \"_LINE\"] = line_num\n else: \n #current tag is not the parent tag of DATE tag\n if current_arr[1] == \"HUSB\":\n dic[\"HUSB_NAME\"]=find_name(doc[\"INDI\"], current_arr[2])\n #inserts line number\n dic[\"HUSB_LINE\"] = line_num\n if current_arr[1] == \"WIFE\":\n dic[\"WIFE_NAME\"]=find_name(doc[\"INDI\"], current_arr[2])\n #inserts line number\n dic[\"WIFE_LINE\"] = line_num\n if current_arr[1] == 'CHIL':\n #INDI_CHILD indicates all the children within a family\n children = dic[\"FAM_CHILD\"] if \"FAM_CHILD\" in dic else []\n children.append(current_arr[2])\n dic[\"FAM_CHILD\"] = children\n #inserts line number\n dic[\"CHIL_LINE_\" + current_arr[2]] = line_num\n if current_arr[1] == 'FAMC' or current_arr[1] == 'FAMS':\n child = dic[\"INDI_CHILD\"] if \"INDI_CHILD\" in dic else []\n spouse = dic[\"SPOUSE\"] if \"SPOUSE\" in dic else []\n child.append(current_arr[2]) if current_arr[1] == 'FAMC' else spouse.append(current_arr[2])\n dic['INDI_CHILD'] = child #FAM_CHILD indicates which family this individual belongs to\n dic['SPOUSE'] = spouse\n #inserts line number\n dic[current_arr[1] + \"_LINE\"] = line_num\n else: #other type of tag\n dic[current_arr[1]]=' '.join(current_arr[2:])\n #inserts line number\n dic[current_arr[1] + \"_LINE\"] = line_num\n #TRLR ==> end of the GEDCOM file\n if (len(next_arr)==3 and next_arr[0]=='0' and next_arr[2] in tag_sp) or next_arr[1]==\"TRLR\":\n if dic: #if the dic exists or not\n if current_tag == 'INDI':\n if 'DEAT' in dic and dic[\"DEAT\"]!=\"NA\":\n age, alive = include_individual_ages(dic['BIRT'], dic['DEAT'], line_num, list(dic.values())[0])\n else:\n dic['DEAT'] = \"NA\"\n age, alive = include_individual_ages(dic['BIRT'], dic['DEAT'], line_num, list(dic.values())[0])\n dic[\"AGE\"] = str(age)\n dic['ALIVE']= alive\n if not dic[\"SPOUSE\"]:\n dic[\"SPOUSE\"] = \"NA\"\n elif not dic[\"INDI_CHILD\"]:\n dic[\"INDI_CHILD\"] = \"NA\"\n if current_tag == 'FAM':\n add_missing_entries(dic)\n doc[current_tag].append(dic) \n line_num += 1 #increments the line counter by \n return doc\n \n\n\n# In[14]:\n\n\n# USID: 01\n# The Dates we need to check includes: birth, marriage, divorce, death\n# Birth always exists, the rests we need to check for NA\n# Iteration through individuals and family\ndef is_dates_before_current_date():\n for family in family_dic.values():\n if family[\"MARR\"] !=\"NA\":\n if(determine_age(family[\"MARR\"], None) < 0):\n error_array.append(\"ERROR: FAMILY: US01: {}: {}: Family has marrige date {} later than today\".format(family[\"MARR_LINE\"], family[\"FAM\"], family[\"MARR\"]))\n if family[\"DIV\"] != \"NA\":\n if(determine_age(family[\"DIV\"], None) < 0):\n error_array.append(\"ERROR: FAMILY: US01: {}: {}: Family has divorce date {} later than today\".format(family[\"DIV_LINE\"], family[\"FAM\"], family[\"DIV\"])) \n \n for indi in individuals.values():\n # for birthday simply check age\n if(indi[\"BIRT\"]==\"NA\"):\n error_array.append(\"ERROR: INDIVIDUAL: US01: {}: {}: Individual does not have a birth date\".format(indi[\"BIRT_LINE\"], indi[\"INDI\"])) \n elif(determine_age(indi[\"BIRT\"], None) < 0):\n error_array.append(\"ERROR: INDIVIDUAL: US01: {}: {}: Individual has birth date {} later than today\".format(indi[\"BIRT_LINE\"], indi[\"INDI\"], indi[\"BIRT\"])) \n if indi[\"DEAT\"] != \"NA\":\n if(determine_age(indi[\"DEAT\"], None) < 0):\n error_array.append(\"ERROR: INDIVIDUAL: US01: {}: {}: Individual has death date {} later than today\".format(indi[\"DEAT_LINE\"], indi[\"INDI\"], indi[\"DEAT\"]))\n\n\n# In[15]:\n\n\n#USID: 02\n#\n# This function checks if the birth of the person is before their \n# marriage date\n# If birth of the person is after the marriage date then the error\n# is appended to the error array\ndef is_birth_before_marraige():\n for family_id in family_dic:\n family = family_dic[family_id]\n \n if \"MARR\" in family and family[\"MARR\"] != \"NA\":\n marriage_date = family[\"MARR\"];\n husband_birth_date = None;\n wife_birth_date = None;\n if \"husband_object\" in family and family[\"husband_object\"] != \"NA\" and family[\"husband_object\"][\"BIRT\"] !=\"NA\":\n husband_birth_date = family[\"husband_object\"][\"BIRT\"]\n else:\n continue\n if \"wife_object\" in family and family[\"wife_object\"] != \"NA\" and family[\"wife_object\"][\"BIRT\"] !=\"NA\":\n wife_birth_date = family[\"wife_object\"][\"BIRT\"]\n else:\n continue\n if is_date_after(marriage_date, husband_birth_date):\n error_array.append((\"ERROR: INDIVIDUAL: US02: {}: {}: Person has marriage date {} before birth date {}\") .format(family['MARR_LINE'], family[\"husband_object\"][\"INDI\"], marriage_date, husband_birth_date))\n if is_date_after(marriage_date, wife_birth_date):\n error_array.append((\"ERROR: INDIVIDUAL: US02: {}: {}: Person has marriage date {} before birth date {}\") .format(family['MARR_LINE'], family[\"wife_object\"][\"INDI\"], marriage_date, wife_birth_date))\n\n\n# In[16]:\n\n\n#US03 - Birth Before Death - The birth of an individual SHOULD occur before his/her death\n\ndef is_birth_before_death():\n for currentIndividual in individuals.values():\n if(currentIndividual['BIRT'] == 'NA'):\n error_array.append(\"ERROR: INDIVIDUAL: US03: {}: Individual has no Birth Date\".format(currentIndividual[\"INDI\"]))\n elif(currentIndividual['DEAT'] != 'NA'):\n if(currentIndividual['BIRT'] > currentIndividual['DEAT']):\n error_array.append(\"ERROR: INDIVIDUAL: US03: {}: Individual has Birth date {} after Death Date {}\".format(currentIndividual[\"INDI\"], currentIndividual[\"BIRT\"], currentIndividual[\"DEAT\"]))\n\n\n# In[17]:\n\n\n# US04 - Marriage Before Divorce\n\ndef is_marriage_after_divorce():\n # Iterating through all individuals\n for currentIndividual in individuals.values():\n # Ignoring all individuals who weren't ever married\n if(currentIndividual['SPOUSE'] != 'NA'):\n # Iterating through all the families they were related to\n for currentFamily in currentIndividual['SPOUSE']:\n for checkingFamily in family_dic.values():\n if(checkingFamily['FAM'] == currentFamily):\n # Ignoring all the marriages without a divorce\n if(checkingFamily['DIV'] != 'NA'):\n # Checking if a divorce date is before a marriage date\n if(checkingFamily['MARR']==\"NA\"):\n anomaly_array.append(\"ANOMALY: INDIVIDUAL: US04: {}: {}: Has No Marriage Date\".format(checkingFamily[\"MARR_LINE\"], currentIndividual['INDI']))\n if(checkingFamily['MARR'] > checkingFamily['DIV']):\n anomaly_array.append(\"ANOMALY: INDIVIDUAL: US04: {}: {}: Marriage Before Divorce - Marriage Date {} - Divorce Date {}\".format(checkingFamily[\"MARR_LINE\"], currentIndividual['INDI'], checkingFamily['MARR'], checkingFamily['DIV']))\n\n\n# In[18]:\n\n\n# US05 - Marriage Before Death\n\ndef is_marriage_after_death():\n # Iterating through all individuals\n for currentIndividual in individuals.values():\n # Ignoring all individuals who weren't ever married\n if(currentIndividual['SPOUSE'] != 'NA'):\n # Iterating through all the families they were related to\n for currentFamily in currentIndividual['SPOUSE']:\n for checkingFamily in family_dic.values():\n if(checkingFamily['FAM'] == currentFamily):\n if(checkingFamily['MARR'] != 'NA' and currentIndividual['DEAT'] != \"NA\"):\n if(checkingFamily['MARR'] > currentIndividual['DEAT']):\n anomaly_array.append(\"ANOMALY: INDIVIDUAL: US05: {}: {}: Marriage Before Death - Marriage Date {} - Death Date {}\".format(checkingFamily[\"MARR_LINE\"], currentIndividual['INDI'], checkingFamily['MARR'], currentIndividual['DEAT']))\n\n\n# In[19]:\n\n\n#USID: 06\ndef check_divorce_before_death():\n for family in family_dic.values():\n husband_flag=False\n wife_flag=False\n if \"DIV\" in family and family[\"DIV\"]!=\"NA\":\n divorce_date = family[\"DIV\"]\n if \"husband_object\" in family and family[\"husband_object\"] != 'NA':\n husband=family[\"husband_object\"]\n if \"DEAT\" in husband and husband[\"DEAT\"] != 'NA':\n husband_flag=True\n husband_death=husband[\"DEAT\"]\n if \"wife_object\" in family and family[\"wife_object\"] != 'NA':\n wife=family[\"wife_object\"]\n if \"DEAT\" in wife and wife[\"DEAT\"] != 'NA':\n wife_flag=True\n wife_death=wife[\"DEAT\"]\n if husband_flag and wife_flag:\n husband_invalid = False\n wife_invalid = False\n if determine_days(husband_death, divorce_date) > 0:\n husband_invalid = True\n if determine_days(wife_death, divorce_date) > 0:\n wife_invalid = True\n if husband_invalid and wife_invalid:\n error_array.append(\"ERROR: FAMILY: US06: {}: {}: Divorce {} happened after the death of both spouses - Husband: {} Wife: {}.\".format(family[\"DIV_LINE\"], family[\"FAM\"], family[\"DIV\"], husband_death, wife_death))\n elif husband_invalid:\n error_array.append(\"ERROR: FAMILY: US06: {}: {}: Divorce {} happened after the death of husband {}.\".format(family[\"DIV_LINE\"], family[\"FAM\"], family[\"DIV\"], husband_death, wife_death))\n elif wife_invalid:\n error_array.append(\"ERROR: FAMILY: US06: {}: {}: Divorce {} happened after the death of wife {}.\".format(family[\"DIV_LINE\"], family[\"FAM\"], family[\"DIV\"], husband_death, wife_death))\n \n\n\n# In[20]:\n\n\n#USID: 07\ndef is_age_legal():\n for indi_id in individuals:\n indi=individuals[indi_id]\n if \"AGE\" in indi:\n if indi[\"AGE\"]==\"NA\":\n error_array.append(\"ERROR: INDIVIDUAL: US07: {}: {}: Person has no Birthday\".format(indi[\"BIRT_LINE\"], indi_id))\n else:\n age =indi[\"AGE\"]\n if int(age) > 150:\n if indi[\"ALIVE\"]==\"NA\":\n error_array.append(\"ERROR: INDIVIDUAL: US07: {}: {}: Person has no Birthday\".format(indi[\"BIRT_LINE\"], indi_id))\n elif indi[\"ALIVE\"]:\n anomaly_array.append(\"ANOMALY: INDIVIDUAL: US07: {}: {}: More than 150 years old - Birth Date {}\".format(indi[\"BIRT_LINE\"], indi_id, indi[\"BIRT\"]))\n else:\n anomaly_array.append(\"ANOMALY: INDIVIDUAL: US07: {}: {}: More than 150 years old at death - Birth Date {}: Death Date {}\".format(indi[\"BIRT_LINE\"], indi_id, indi[\"BIRT\"], indi[\"DEAT\"]))\n\n\n# In[21]:\n\n\n#Birth before marriage of parents USID: 08\ndef birth_before_marriage():\n for family in family_dic.values():\n if \"children_objects\" in family:\n marriage_date=family['MARR']\n divorce_date=family[\"DIV\"]\n for child in family[\"children_objects\"]:\n if (child[\"BIRT\"]==\"NA\"):\n error_array.append(\"ERROR: INDIVIDUAL: US08: {}: Child {}: has no Birthday\".format(child[\"BIRT_LINE\"], child[\"INDI\"]))\n continue\n if(marriage_date!= \"NA\"):\n if(determine_days(marriage_date, child[\"BIRT\"]) < 0):\n anomaly_array.append(\"ANOMALY: INDIVIDUAL: US08: {}: {}: Child was born at {} before marriage of parents {}\".format(child[\"BIRT_LINE\"], child[\"INDI\"], child[\"BIRT\"], marriage_date))\n if(divorce_date!= \"NA\"):\n if(determine_days(divorce_date, child[\"BIRT\"])/30 > 9):\n anomaly_array.append(\"ANOMALY: INDIVIDUAL: US08: {}: {}: Child was born at {} after 9 month divorce of parents {}\".format(child[\"BIRT_LINE\"], child[\"INDI\"], child[\"BIRT\"], divorce_date))\n\n\n# In[22]:\n\n\n#Birth before death of parents USID: 09\ndef birth_before_death():\n for family in family_dic.values():\n if \"children_objects\" in family:\n if \"husband_object\" in family and family[\"husband_object\"] != \"NA\":\n husband_death=family[\"husband_object\"][\"DEAT\"]\n else:\n husband_death = \"NA\"\n if \"wife_object\" in family and family[\"wife_object\"] != \"NA\":\n wife_death=family[\"wife_object\"][\"DEAT\"]\n else:\n wife_death = \"NA\"\n for child in family[\"children_objects\"]:\n if (child[\"BIRT\"]==\"NA\"):\n error_array.append(\"ERROR: INDIVIDUAL: US09: {}: Child {}: has no Birthday\".format(child[\"BIRT_LINE\"], child[\"INDI\"]))\n continue\n if(wife_death!= \"NA\"):\n if(determine_days(child[\"BIRT\"], wife_death) < 0):\n error_array.append(\"ERROR: INDIVIDUAL: US09: {}: {}: Child was born at {} after death of mother {}\".format(child[\"BIRT_LINE\"], child[\"INDI\"], child[\"BIRT\"], wife_death))\n if(husband_death!= \"NA\"):\n if(determine_days(husband_death, child[\"BIRT\"])/30 > 9):\n error_array.append(\"ERROR: INDIVIDUAL: US09: {}: {}: Child was born at {} after 9 month death of father {}\".format(child[\"BIRT_LINE\"], child[\"INDI\"], child[\"BIRT\"], husband_death))\n\n\n# In[23]:\n\n\n# USID: 10\ndef is_marriage_legal():\n for family_id in family_dic:\n if \"MARR\" in family_dic[family_id]:\n married_date=family_dic[family_id][\"MARR\"]\n if \"husband_object\" in family_dic[family_id] and family_dic[family_id][\"husband_object\"]!=\"NA\":\n husband=family_dic[family_id][\"husband_object\"]\n if husband[\"BIRT\"]==\"NA\" or married_date==\"NA\":\n error_array.append(\"ERROR: INDIVIDUAL: US10: {}: {}: Husband of family {}: has no Birth Date\".format(husband[\"BIRT_LINE\"], husband[\"INDI\"], family_id))\n elif int(determine_age(husband[\"BIRT\"], married_date)) < 14:\n anomaly_array.append(\"ANOMALY: INDIVIDUAL: US10: {}: {}: Husband of family {} is younger than 14 years old - Birth Date {}\".format(husband[\"BIRT_LINE\"], husband[\"INDI\"], family_id,husband[\"BIRT\"]))\n if \"wife_object\" in family_dic[family_id] and family_dic[family_id][\"wife_object\"]!=\"NA\":\n wife=family_dic[family_id][\"wife_object\"]\n if wife[\"BIRT\"]==\"NA\" or married_date==\"NA\":\n error_array.append(\"ERROR: INDIVIDUAL: US10: {}: {}: Wife of family {}: has no Birth Date\".format(wife[\"BIRT_LINE\"], wife[\"INDI\"], family_id))\n elif int(determine_age(wife[\"BIRT\"], married_date)) < 14:\n anomaly_array.append(\"ANOMALY: INDIVIDUAL: US10: {}: {}: Wife of family {} is younger than 14 years old - Birth Date {}\".format(wife[\"BIRT_LINE\"], wife[\"INDI\"], family_id, wife[\"BIRT\"]))\n\n\n# In[24]:\n\n\n# USID: 11\ndef check_for_bigamy():\n for individual_id in individuals:\n individual = individuals[individual_id]\n if \"SPOUSE\" in individual and individual[\"SPOUSE\"] != 'NA':\n spouse_in_families = individual[\"SPOUSE\"]\n if len(spouse_in_families) > 1:\n dates = []\n for family_id in spouse_in_families:\n family = family_dic[family_id]\n date = {}\n if \"MARR\" in family and family[\"MARR\"] != 'NA':\n date[\"MARR\"] = family[\"MARR\"]\n if \"DIV\" in family and family[\"DIV\"] != 'NA':\n date[\"DIV\"] = family[\"DIV\"]\n elif \"husband_object\" in family and family[\"husband_object\"] != 'NA':\n if \"DEAT\" in family[\"husband_object\"] and family[\"husband_object\"][\"DEAT\"] != 'NA':\n date[\"DIV\"] = family[\"husband_object\"][\"DEAT\"]\n dates.append(date)\n if compare_marraige_dates(dates):\n anomaly_array.append(\"ANOMALY: INDIVIDUAL: US11: {}: {}: Performing bigamy\".format(individual[\"INDI_LINE\"], individual[\"INDI\"]))\n\n\n# In[25]:\n\n\n# USID: 12\ndef check_parents_not_too_old():\n for family in family_dic.values():\n husband_flag=False\n wife_flag=False\n if \"husband_object\" in family and family[\"husband_object\"] != 'NA' and family[\"husband_object\"][\"AGE\"]!=\"NA\":\n husband_age = family[\"husband_object\"][\"AGE\"]\n husband_flag=True\n else:\n husband_age = \"NA\"\n if \"wife_object\" in family and family[\"wife_object\"] != 'NA' and family[\"wife_object\"][\"AGE\"]!=\"NA\":\n wife_age = family[\"wife_object\"][\"AGE\"]\n wife_flag=True\n else:\n wife_age = \"NA\"\n if \"children_objects\" in family and family[\"children_objects\"] != 'NA' and husband_age!=\"NA\" and wife_age!=\"NA\":\n for child in family[\"children_objects\"]:\n if child[\"AGE\"]==\"NA\":\n error_array.append(\"ERROR: INDIVIDUAL: US12: {}: Child {} has no Birthday.\".format(child[\"INDI_LINE\"], child[\"INDI\"]))\n else:\n child_age = child[\"AGE\"]\n husband_to_child = int(husband_age) - int(child_age)\n wife_to_child = int(wife_age) - int(child_age)\n if husband_flag and husband_to_child >= 80:\n error_array.append(\"ERROR: INDIVIDUAL: US12: {}: {}: Father is {} older than the child {}.\" .format(family[\"husband_object\"][\"INDI_LINE\"], family[\"FAM\"], husband_to_child, child[\"INDI\"]))\n if wife_flag and wife_to_child >= 60:\n error_array.append(\"ERROR: FAMILY: US12: {}: {}: Wife is {} older than the child {}.\" .format(family[\"wife_object\"][\"INDI_LINE\"], family[\"FAM\"], wife_to_child, child[\"INDI\"]))\n\n\n# In[26]:\n\n\ndef compare_marraige_dates(dates):\n for i in range(0, len(dates)):\n dateOne = dates[i]\n for j in range(i + 1, len(dates)):\n dateTwo = dates[j]\n if \"MARR\" in dateOne and \"DIV\" in dateOne:\n if \"MARR\" in dateTwo:\n if dateOne[\"MARR\"] <= dateTwo[\"MARR\"] < dateOne[\"DIV\"]:\n return True\n if \"DIV\" in dateTwo:\n if dateOne[\"MARR\"] < dateTwo[\"DIV\"] < dateOne[\"DIV\"]:\n return True\n elif \"MARR\" in dateOne:\n if \"MARR\" in dateTwo and \"DIV\" in dateTwo:\n if dateTwo[\"MARR\"] <= dateOne[\"MARR\"] < dateTwo[\"DIV\"]:\n return True\n if \"MARR\" in dateTwo and dateOne[\"MARR\"] <= dateTwo[\"MARR\"]:\n return True\n if \"DIV\" in dateTwo and dateOne[\"MARR\"] < dateTwo[\"DIV\"]:\n return True\n if \"MARR\" in dateTwo and \"DIV\" not in dateTwo and dateTwo[\"MARR\"] <= dateOne[\"MARR\"]:\n return True\n elif \"DIV\" in dateOne:\n if \"MARR\" in dateTwo and \"DIV\" in dateTwo:\n if dateTwo[\"MARR\"] <= dateOne[\"DIV\"] < dateTwo[\"DIV\"]:\n return True\n return False\n\n\n# In[27]:\n\n\n# US13\ndef check_sibling_spacing():\n for family_id in family_dic:\n family = family_dic[family_id]\n if (len(family[\"FAM_CHILD\"]) > 0) and family[\"FAM_CHILD\"] != \"NA\":\n for child in family[\"FAM_CHILD\"]:\n siblings = get_individual_siblings(child, False, True)\n child_object = individuals[child]\n if child_object[\"BIRT\"]!=\"NA\":\n for sibling in siblings:\n if sibling != child:\n sibling_object = individuals[sibling]\n if sibling_object[\"BIRT\"]!=\"NA\": \n days = determine_days(child_object[\"BIRT\"], sibling_object[\"BIRT\"])\n days = abs(days)\n if 2 < days < (8 * 30):\n error_array.append(\"ERROR: INDIVIDUAL: US13: {}: Child {} is born within 8 months and more than 2 days of sibling\" .format(child_object[\"INDI_LINE\"], child))\n\n\n# In[28]:\n\n\ndef get_individual_siblings(_id, include_husb, include_wife):\n if (_id not in individuals):\n return []\n individual = individuals[_id]\n siblings = []\n if \"INDI_CHILD\" in individual and individual[\"INDI_CHILD\"] != \"NA\":\n for family_id in individual[\"INDI_CHILD\"]:\n family = family_dic[family_id]\n if \"FAM_CHILD\" in family and family[\"FAM_CHILD\"] != \"NA\":\n siblings.extend(family[\"FAM_CHILD\"])\n if include_husb:\n if \"husband_object\" in family and family[\"husband_object\"] != \"NA\":\n siblings.extend(get_all_children(family[\"husband_object\"]))\n if include_wife:\n if \"wife_object\" in family and family[\"wife_object\"] != \"NA\":\n siblings.extend(get_all_children(family[\"wife_object\"]))\n siblings = list(set(siblings))\n return siblings\n\n\n# In[29]:\n\n\ndef get_all_children(individual_object):\n spouses = individual_object[\"SPOUSE\"]\n children = []\n if spouses != 'NA':\n for spouse_family_id in spouses:\n individual_family = family_dic[spouse_family_id]\n if (len(individual_family[\"FAM_CHILD\"]) > 0) and individual_family[\"FAM_CHILD\"] != \"NA\":\n children.extend(individual_family[\"FAM_CHILD\"])\n return children\n\n\n# In[30]:\n\n\n# User Story: US14\ndef check_multiple_births():\n for family_id in family_dic:\n family = family_dic[family_id]\n if \"FAM_CHILD\" in family and family[\"FAM_CHILD\"] != 'NA' and len(family[\"FAM_CHILD\"]) > 0:\n random_child = family[\"FAM_CHILD\"][0]\n siblings = get_individual_siblings(random_child, False, False)\n if len(siblings) < 5:\n continue;\n birthdates = {}\n for sibling_id in siblings:\n individual = individuals[sibling_id]\n if individual is not None and individual != 'NA':\n if \"BIRT\" in individual and individual[\"BIRT\"] != 'NA':\n if individual[\"BIRT\"] in birthdates:\n count = birthdates[individual[\"BIRT\"]]\n count += 1\n birthdates[individual[\"BIRT\"]] = count\n else:\n birthdates[individual[\"BIRT\"]] = 1\n result = {k:v for (k,v) in birthdates.items() if v > 5}\n if len(result) > 0:\n anomaly_array.append(\"ANOMALY: FAMILY: US14: {}: {}: Family has more than 5 siblings with same birthdate\" .format(family[\"FAM_LINE\"], family_id))\n\n\n# In[31]:\n\n\n# User Story: US15\ndef check_sibling_count():\n for family_id in family_dic:\n family = family_dic[family_id]\n if (len(family[\"FAM_CHILD\"]) > 15):\n anomaly_array.append(\"ANOMALY: FAMILY: US15: {}: {}: Family has {} siblings which is more than 15 siblings\" .format(family[\"FAM_LINE\"], family_id, len(family[\"FAM_CHILD\"])))\n\n\n# In[32]:\n\n\n# Returns the lastname of the name\n# Last name is surrounded by '/' in the name\n# :param name is the full name of the person\ndef get_last_name(name):\n return name.split('/')[1];\n\n\n# In[33]:\n\n\n# User story: US16\n# This function goes over the family dictionary and \n# returns the array of family ids which contain males with different last name\n# It uses the last name of the husband in the family as the initial reference\n# \n# :returns array of family ids\ndef check_last_names():\n for family_id in family_dic:\n family = family_dic[family_id]\n last_name = None\n if \"HUSB_NAME\" in family:\n if family[\"HUSB_NAME\"] != \"NA\":\n last_name = get_last_name(family[\"HUSB_NAME\"])\n else:\n continue\n if \"children_objects\" in family:\n for child in family[\"children_objects\"]:\n if child[\"SEX\"] == \"M\":\n if last_name is None:\n last_name = get_last_name(child[\"NAME\"])\n else:\n if last_name != get_last_name(child[\"NAME\"]):\n anomaly_array.append(\"ANOMALY: INDIVIDUAL: US16: {}: {}: Individual has different last name {} than family {}\" .format(child[\"NAME_LINE\"], child[\"INDI\"], get_last_name(child[\"NAME\"]), last_name))\n\n\n# In[34]:\n\n\n# User Story 17\ndef check_parent_child_marriage():\n for family_id in family_dic:\n family = family_dic[family_id]\n if \"HUSB\" in family and family[\"HUSB\"] != 'NA' and \"WIFE\" in family and family[\"WIFE\"] != 'NA':\n if is_spouse_a_child(family[\"HUSB\"], family[\"WIFE\"]):\n anomaly_array.append(\"ANOMALY: INDIVIDUAL: US17: {}: {}: Individual married to child {}\" .format(family[\"HUSB_LINE\"], family[\"HUSB\"], family[\"WIFE\"]))\n if is_spouse_a_child(family[\"WIFE\"], family[\"HUSB\"]):\n anomaly_array.append(\"ANOMALY: INDIVIDUAL: US17: {}: {}: Individual married to child {}\" .format(family[\"WIFE_LINE\"], family[\"WIFE\"], family[\"HUSB\"]))\n\n\n# In[35]:\n\n\ndef is_spouse_a_child(individual_id, spouse_id):\n individual_object = individuals[individual_id]\n if 'SPOUSE' in individual_object and individual_object['SPOUSE'] != 'NA':\n for spouse_fam in individual_object['SPOUSE']:\n if spouse_fam in family_dic:\n family = family_dic[spouse_fam]\n if \"FAM_CHILD\" in family and spouse_id in family[\"FAM_CHILD\"]:\n return True\n return False\n\n\n# In[36]:\n\n\n# User story 18\ndef check_sibling_marriage():\n for individual_id in individuals:\n individual = individuals[individual_id]\n if \"SPOUSE\" in individual and individual[\"SPOUSE\"] != \"NA\":\n siblings = get_individual_siblings(individual_id, True, True)\n for spouse_family_id in individual[\"SPOUSE\"]:\n spouse_family = family_dic[spouse_family_id]\n spouse_id = None\n if \"WIFE\" in spouse_family and spouse_family[\"WIFE\"] != \"NA\":\n if spouse_family[\"WIFE\"] != individual_id:\n spouse_id = spouse_family[\"WIFE\"]\n if \"HUSB\" in spouse_family and spouse_family[\"HUSB\"] != \"NA\":\n if spouse_family[\"HUSB\"] != individual_id:\n spouse_id = spouse_family[\"HUSB\"]\n if spouse_id is not None and spouse_id in siblings:\n anomaly_array.append(\"ANOMALY: INDIVIDUAL: US18: {}: {}: Individual married to sibling {}\" .format(individual[\"INDI_LINE\"], individual_id, spouse_id))\n\n\n# In[37]:\n\n\n#User story 19\ndef check_cousins_marriage():\n for individual_id in individuals:\n individual = individuals[individual_id]\n if \"SPOUSE\" in individual and individual[\"SPOUSE\"] != \"NA\":\n if \"INDI_CHILD\" in individual and individual[\"INDI_CHILD\"] != \"NA\":\n cousins = []\n for child_in_family in individual[\"INDI_CHILD\"]:\n family = family_dic[child_in_family]\n parent_siblings = []\n if \"HUSB\" in family and family[\"HUSB\"] != \"NA\":\n parent_siblings.extend(get_individual_siblings(family[\"HUSB\"], True, True))\n if \"WIFE\" in family and family[\"WIFE\"] != \"NA\":\n parent_siblings.extend(get_individual_siblings(family[\"WIFE\"], True, True))\n for parent_sibling in parent_siblings:\n cousins.extend(get_all_children(individuals[parent_sibling]))\n for spouse_family_id in individual[\"SPOUSE\"]:\n spouse_family = family_dic[spouse_family_id]\n spouse_id = None\n if \"WIFE\" in spouse_family and spouse_family[\"WIFE\"] != \"NA\":\n if spouse_family[\"WIFE\"] != individual_id:\n spouse_id = spouse_family[\"WIFE\"]\n if \"HUSB\" in spouse_family and spouse_family[\"HUSB\"] != \"NA\":\n if spouse_family[\"HUSB\"] != individual_id:\n spouse_id = spouse_family[\"HUSB\"]\n if spouse_id is not None and spouse_id in cousins:\n anomaly_array.append(\"ANOMALY: INDIVIDUAL: US19: {}: {}: Individual married to cousin {}\".format(individual[\"INDI_LINE\"], individual_id, spouse_id))\n\n\n# In[38]:\n\n\n#User_Story_20 Aunts and uncles\n#Aunts and uncles should not marry their nieces or nephews\ndef is_uncle_aunt_marriage_legal():\n for indi in individuals.values(): #scans through each individual first\n current_sp = indi[\"SPOUSE\"] #Array of spouse's family IDs\n current_fm = indi[\"INDI_CHILD\"] #gets the family ID that the person belongs to\n if (current_sp != \"NA\" and current_fm != \"NA\"): #if the person has a spouse\n for fam_id in current_fm: #scans through uncle's families\n current_family = family_dic[fam_id]\n current_siblings = current_family[\"children_objects\"] #get the uncle's siblings\n for child in current_siblings: #scans through all siblings\n child_spouses = child[\"SPOUSE\"]\n if (child_spouses != \"NA\"):\n for spouse in child_spouses:\n spouse_family = family_dic[spouse]\n for sp in current_sp:\n if (family_dic[sp][\"WIFE\"] in spouse_family[\"FAM_CHILD\"]):\n current_sp_family = family_dic[sp].values()\n anomaly_array.append(\"ANOMALY: FAMILY: US20: {}: {}: Person {} should not marry person {}\".format(family_dic[sp][\"HUSB_LINE\"], family_dic[sp][\"FAM\"], family_dic[sp][\"HUSB\"], family_dic[sp][\"WIFE\"]))\n return False\n elif(family_dic[sp][\"HUSB\"] in spouse_family[\"FAM_CHILD\"]):\n anomaly_array.append(\"ANOMALY: FAMILY: US20: {}: {}: Person {} should not marry person {}\".format(family_dic[sp][\"WIFE_LINE\"], family_dic[sp][\"FAM\"], family_dic[sp][\"WIFE\"], family_dic[sp][\"HUSB\"]))\n return False\n return True\n\n\n# In[39]:\n\n\n# US 21:\ndef correct_gender():\n for family in family_dic.values():\n if \"husband_object\" in family and family[\"husband_object\"]!=\"NA\":\n husband_sex=family[\"husband_object\"][\"SEX\"]\n if(husband_sex != \"M\"):\n error_array.append(\"ERROR: FAMILY: US21: {}: {}: Is Husband and has Sex as Female\".format(family[\"husband_object\"][\"SEX_LINE\"], family[\"husband_object\"][\"INDI\"] ))\n if \"wife_object\" in family and family[\"wife_object\"]!=\"NA\":\n wife_sex=family[\"wife_object\"][\"SEX\"]\n if(wife_sex != \"F\"):\n error_array.append(\"ERROR: FAMILY: US21: {}: {}: Is Wife and has Sex as Male\".format(family[\"wife_object\"][\"SEX_LINE\"], family[\"wife_object\"][\"INDI\"] ))\n\n\n# In[40]:\n\n\n# US 22:\ndef unique_indi_and_family(value, flag, line_num):\n if flag==\"INDI\":\n if value in ui:\n error_array.append(\"ERROR: INDIVIDUAL: US22: {}: Two or more Individuals {}: have the same ID\".format(line_num, value))\n return False\n else:\n ui.append(value)\n return True\n else: \n if value in uf:\n error_array.append(\"ERROR: FAMILY: US22: {}: Two or more families {}: have the same ID\".format(line_num, value))\n return False\n else:\n uf.append(value)\n return True\n\n\n# In[41]:\n\n\n#USID: 23\ndef unique_name_and_birth():\n li = {}\n for value in individuals.values():\n if value[\"BIRT\"]==\"NA\":\n error_array.append(\"ERROR: INDIVIDUAL: US23: {}: {}: {}: Individuals have no birth date \".format(value[\"INDI_LINE\"], value[\"INDI\"], value[\"NAME\"]))\n else: \n temp = value[\"NAME\"] + value[\"BIRT\"]\n if temp in li:\n anomaly_array.append(\"ANOMALY: INDIVIDUAL: US23: {}: {}: {}: Individuals have the same name {} and birth date {}\".format(value[\"INDI_LINE\"], value[\"INDI\"], li[temp], value[\"NAME\"], value[\"BIRT\"]))\n else:\n li[temp]=value[\"INDI\"]\n\n\n# In[42]:\n\n\n#User Story: 24\ndef unique_family_by_spouses():\n fams = []\n for family in family_dic.values():\n fam = {}\n compare = False\n if \"husband_object\" in family and family[\"husband_object\"] != 'NA':\n fam[\"HUSB\"] = family[\"husband_object\"][\"NAME\"]\n compare = True\n if \"wife_object\" in family and family[\"wife_object\"] != 'NA':\n fam[\"WIFE\"] = family[\"wife_object\"][\"NAME\"]\n compare = True\n if \"MARR\" in family and family[\"MARR\"] != 'NA':\n fam[\"MARR\"] = family[\"MARR\"]\n compare = True\n if compare:\n if fam in fams:\n anomaly_array.append(\"ANOMALY: FAMILY: US24: {}: {}: Family contains same husband, wife and marriage date as another family\".format(family[\"FAM_LINE\"], family[\"FAM\"]))\n else:\n fams.append(fam)\n\n \n\n\n# In[43]:\n\n\n#USID: 25\ndef unique_family_name_and_birth():\n li = {}\n for value in family_dic.values():\n if \"children_objects\" in value:\n for child in value[\"children_objects\"]:\n temp = child[\"NAME\"] + child[\"BIRT\"]\n if temp in li:\n anomaly_array.append(\"ANOMALY: INDIVIDUAL: US25: {}: {}: {}: Individuals share the same first name {} and birth date {} from family {}\".format(value[\"FAM_LINE\"], child[\"INDI\"], li[temp], child[\"NAME\"], child[\"BIRT\"], value[\"FAM\"]))\n else: \n li[temp]=child[\"INDI\"]\n\n\n# In[44]:\n\n\n#USID: 26\ndef check_corresponding_entries():\n for family_id in family_dic:\n family = family_dic[family_id]\n if \"HUSB\" in family and family[\"HUSB\"] != \"NA\":\n husband_object = family[\"husband_object\"]\n if husband_object != \"NA\" and family_id not in husband_object[\"SPOUSE\"]:\n error_array.append(\"ERROR: FAMILY: US26: {}: {}: Husband id does not match with family id in individuals spouse entry\".format(family[\"FAM_LINE\"], family[\"HUSB\"]))\n if \"WIFE\" in family and family[\"WIFE\"] != \"NA\":\n wife_object = family[\"wife_object\"]\n if wife_object != \"NA\" and family_id not in wife_object[\"SPOUSE\"]:\n error_array.append(\"ERROR: FAMILY: US26: {}: {}: Wife id does not match with family id in individuals spouse entry\".format(family[\"FAM_LINE\"], family[\"WIFE\"]))\n if \"children_objects\" in family and family[\"children_objects\"] != \"NA\":\n for child_object in family[\"children_objects\"]:\n if child_object != \"NA\" and family_id not in child_object[\"INDI_CHILD\"]:\n error_array.append(\"ERROR: FAMILY: US26: {}: {}: Child id does not match with family id in individuals spouse entry\".format(family[\"FAM_LINE\"], child_object[\"INDI\"]))\n\n\n# In[45]:\n\n\n#US27 - Include Individual Ages in the INDIVIDUALS dictionary\nfrom datetime import date \n\ndef include_individual_ages(birth_date, death_date, line_num, tag):\n if birth_date==\"NA\":\n error_array.append(\"ERROR: INDIVIDUAL: US27: {}: {}: Person does not have birth date when caculating age\".format(line_num, tag))\n return \"NA\", \"NA\"\n else: \n birth_month= birth_date.split('-')[1]\n birth_day= birth_date.split('-')[2]\n if death_date!=\"NA\":\n death_month=death_date.split('-')[1]\n death_day=death_date.split('-')[2]\n return int(death_date.split('-')[0]) - int(birth_date.split('-')[0])-((int(death_month), int(death_day))< (int(birth_month), int(birth_day))), False\n else: \n birth_month= birth_date.split('-')[1]\n birth_day= birth_date.split('-')[2]\n today = datetime.today()\n return today.year - int(birth_date.split('-')[0]) - ((today.month, today.day) < (int(birth_month), int(birth_day))), True\n\n\n# In[46]:\n\n\n#US28 List siblings in families by decreasing age, i.e. oldest siblings first\ndef listSiblingsByAge():\n error_count = 0\n print(\"US28: List siblings by decreasing age\")\n file = open(\"cs555_sprint_outputs.txt\", \"a\")\n file.write(\"US28: List siblings by decreasing age\" + \"\\n\")\n file.close()\n for fam in family_dic.values():\n currentSiblings = fam[\"FAM_CHILD\"]\n sibling_count = 1\n if (currentSiblings != \"NA\"):\n current_dic = {}\n for sibling in currentSiblings:\n siblingAge = individuals[sibling][\"AGE\"]\n if (siblingAge == \"NA\"): #one of the siblings does not have age\n error_array.append((\"ERROR: FAMILY: US28: {}: Child {} has no age\").format(individuals[sibling][\"INDI_LINE\"], sibling))\n sibling_count = 0\n error_count += 1\n break;\n if int(siblingAge) in current_dic:\n sibling_list = current_dic[int(siblingAge)]\n sibling_list.append(sibling)\n current_dic[int(siblingAge)] = sibling_list\n else:\n sibling_list = [sibling]\n current_dic[int(siblingAge)] = sibling_list\n if (sibling_count == 1):\n temp_dic = sorted(current_dic.keys(), reverse=True)\n resultList = []\n print(\"+-----Family \" + str(fam[\"FAM\"]) + \"-----+\")\n file = open(\"cs555_sprint_outputs.txt\", \"a\")\n file.write(\"+-----Family \" + str(fam[\"FAM\"]) + \"-----+\" + \"\\n\")\n for childList in temp_dic:\n for child in current_dic[childList]:\n resultList.append(str(child))\n print(\"Individual:\" + str(child) + \", Age:\" + str(childList) + \" \")\n file.write(\"Individual:\" + str(child) + \", Age:\" + str(childList) + \" \\n\")\n# print(\"\\n\")\n# file.write(\"\\n\")\n file.close()\n else: #no children in the family\n anomaly_array.append(\"ANOMALY: FAMILY: US28: {}: Family {} has no children\".format(fam[\"FAM_LINE\"], fam[\"FAM\"]))\n error_count += 1\n print(\"\\n\")\n file = open(\"cs555_sprint_outputs.txt\", \"a\")\n file.write(\"+-----End of US28-----+\\n\\n\")\n file.close()\n return error_count\n\n\n# In[47]:\n\n\n#User_Story_29: List all deceased individuals in a GEDCOM file\n#Prints out a table with all the deceased people's information\ndef listDeceased():\n current_dic = {}\n deceased_count = 0\n for value in individuals.values():\n if(str(value[\"DEAT\"]) != \"NA\" and (value[\"ALIVE\"])):\n error_array.append((\"ERROR: INDIVIDUAL: US29: {}: Person is alive but has Death Date {}\").format(value[\"NAME_LINE\"], value[\"NAME\"], value[\"DEAT\"]))\n #print((\"ERROR: INDIVIDUAL: US29: {}: Person is alive but has Death Date {}\").format(value[\"NAME_LINE\"], value[\"NAME\"], value[\"DEAT\"]))\n elif(str(value[\"DEAT\"]) == \"NA\" and (not value[\"ALIVE\"])):\n error_array.append((\"ERROR: INDIVIDUAL: US29: {}: Person {}: is dead but has no Death Date\").format(value[\"INDI_LINE\"], value[\"INDI\"]));\n #print((\"ERROR: INDIVIDUAL: US29: {}: Person {}: is dead but has no Death Date\").format(value[\"INDI_LINE\"], value[\"INDI\"]))\n elif(not value[\"ALIVE\"]):\n deceased_count += 1\n current_dic[value[\"INDI\"]] = value \n if deceased_count > 0:\n #print(\"User_Story_29: List all deceased individuals in a GEDCOM file\")\n #Use pretty table module to print out the results\n allFields = [\"ID\", \"Name\", \"Gender\", \"Birthday\", \"Age\", \"Alive\", \"Death\"]\n tagNames = [\"INDI\", \"NAME\", \"SEX\", \"BIRT\", \"AGE\", \"ALIVE\", \"DEAT\"]\n printTable(\"US29: Deceased People Table\", allFields, tagNames, current_dic)\n \n\n\n# In[48]:\n\n\n#User_Story_30: List all living married people in a GEDCOM file\n#Prints out a table with all the living married people's information\ndef listLivingMarried():\n current_dic = {}\n living_count = 0\n for value in individuals.values():\n if(value[\"ALIVE\"] and value[\"SPOUSE\"] != \"NA\"):\n current_dic[value[\"INDI\"]] = value\n living_count += 1\n elif(not value[\"ALIVE\"] and value[\"SPOUSE\"] != \"NA\"):\n error_array.append(\"ERROR: INDIVIDUAL: US30: {}: {}: Deceased Person is married to Person {}\".format(value[\"INDI_LINE\"], value[\"INDI\"], \"\".join(value[\"SPOUSE\"])))\n# print(\"ERROR: INDIVIDUAL: US30: {}: {}: Deceased Person is married to Person {}\".format(value[\"INDI_LINE\"], value[\"INDI\"], \"\".join(value[\"SPOUSE\"])))\n if living_count > 0:\n# print(\"User_Story_30: List all living married people in a GEDCOM file\")\n #Use pretty table module to print out the results\n allFields = [\"ID\", \"Name\", \"Gender\", \"Birthday\", \"Age\", \"Alive\", \"Death\", \"Spouse\"]\n tagNames = [\"INDI\", \"NAME\", \"SEX\", \"BIRT\", \"AGE\", \"ALIVE\", \"DEAT\", \"SPOUSE\"]\n printTable(\"US30: Living & Married People Table\", allFields, tagNames, current_dic)\n\n\n# In[49]:\n\n\n#User_Story_31: List all living people over 30 who have never been married in a GEDCOM file\ndef listLivingSingle():\n current_dic = {}\n single_count = 0\n result = True\n for value in individuals.values():\n if (value[\"AGE\"] != \"NA\" and int(value[\"AGE\"]) > 30 and value[\"ALIVE\"] == True and value[\"SPOUSE\"] == \"NA\"): #found single \n #what should the error case be?\n if (value[\"BIRT\"] == \"NA\"):\n error_array.append(\"ERROR: INDIVIDUAL: US31: {}: Single Person {} does not have birthday!\".format(value[\"INDI_LINE\"], value[\"INDI\"]))\n result = False\n else:\n current_dic[value[\"INDI\"]] = value\n single_count += 1\n if single_count > 0:\n allFields = [\"ID\", \"Name\", \"Gender\", \"Birthday\", \"Age\", \"Alive\", \"Death\", \"Spouse\"]\n tagNames = [\"INDI\", \"NAME\", \"SEX\", \"BIRT\", \"AGE\", \"ALIVE\", \"DEAT\", \"SPOUSE\"]\n printTable(\"US31: Unmarried people over 30\", allFields, tagNames, current_dic)\n return result\n\n\n# In[50]:\n\n\n#US 32: List multiple births\ndef multiple_birth():\n for value in family_dic.values():\n li={}\n if \"children_objects\" in value:\n for child in value[\"children_objects\"]:\n temp = str(child[\"INDI_CHILD\"]) + child[\"BIRT\"]\n if temp in li:\n anomaly_array.append(\"ANOMALY: FAMILY: US32: {}: {}: The two or more individuals were born at the same time\".format(value[\"FAM_LINE\"], value[\"FAM\"]))\n else: \n li[temp]=child[\"INDI\"]\n\n\n# In[51]:\n\n\n#User_Story_33: List all orphaned children (both parents dead and child < 18 years old) in a GEDCOM file\ndef listAllOrphand():\n current_dic = {}\n orphand_count = 0\n result = True\n for person in individuals.values():\n if (person[\"AGE\"] == \"NA\"):\n error_array.append(\"ERROR: INDIVIDUAL: US33: {}: Orphaned child {} does not have age!\".format(person[\"INDI_LINE\"], person[\"INDI\"]))\n result = False\n elif (int(person[\"AGE\"]) < 18 and person[\"ALIVE\"] == True):\n famID = person[\"INDI_CHILD\"]\n #converts family id from list to string\n if (isinstance(famID, list) == True):\n famID = \"\".join(famID)\n else:\n famID = str(famID)\n if (famID != \"NA\"):\n if (famID in family_dic.keys()):\n currentFamily = family_dic[famID]\n current_husb = str(currentFamily[\"HUSB\"])\n current_wife = str(currentFamily[\"WIFE\"])\n #both parents are dead\n if (current_husb!=\"NA\" and individuals[current_husb][\"ALIVE\"] == False and individuals[current_wife][\"ALIVE\"] == False):\n current_dic[person[\"INDI\"]] = person\n orphand_count += 1\n else:\n error_array.append(\"ERROR: INDIVIDUAL: US33: {}: Orphaned child {} does not belong to a family!\".format(person[\"INDI_LINE\"], person[\"INDI\"]))\n result = False \n else:\n error_array.append(\"ERROR: INDIVIDUAL: US33: {}: Orphaned child {} does not have a family ID!\".format(person[\"INDI_LINE\"], person[\"INDI\"]))\n result = False \n if orphand_count > 0:\n allFields = [\"ID\", \"Name\", \"Gender\", \"Birthday\", \"Age\", \"Alive\", \"Death\", \"Spouse\"]\n tagNames = [\"INDI\", \"NAME\", \"SEX\", \"BIRT\", \"AGE\", \"ALIVE\", \"DEAT\", \"SPOUSE\"]\n printTable(\"US33: Orphaned Children\", allFields, tagNames, current_dic)\n return result\n\n\n# In[52]:\n\n\n#US 34: \ndef large_age_diff():\n for value in family_dic.values():\n# for family_id in family_dic:\n family= value[\"FAM\"]\n if \"husband_object\" in family_dic[family] and family_dic[family][\"husband_object\"] != \"NA\":\n husband=family_dic[family][\"husband_object\"]\n if (husband[\"AGE\"] != \"NA\"):\n hage = int(husband[\"AGE\"])\n else:\n hage = \"NA\"\n else:\n hage = \"NA\"\n if \"wife_object\" in family_dic[family] and family_dic[family][\"wife_object\"] != \"NA\":\n wife=family_dic[family][\"wife_object\"]\n if (wife[\"AGE\"] != \"NA\"):\n wage = int(wife[\"AGE\"])\n else:\n wage = \"NA\"\n if (hage != \"NA\" and wage != \"NA\"):\n agediff = hage/wage\n if agediff>=2 or agediff<=0.5:\n anomaly_array.append(\"ANOMALY: FAMILY: US34: {}: {}: Family has a large spouse age difference\".format(value[\"FAM_LINE\"], value[\"FAM\"]))\n else:\n agediff = 0\n anomaly_array.append(\"ANOMALY: FAMILY: US34: {}: {}: One of the spouses or both have no age value\".format(value[\"FAM_LINE\"], value[\"FAM\"]))\n\n\n# In[53]:\n\n\n#US 35 List recent births\ndef list_recent_births():\n current_dic = {}\n bday_count = 0\n result = True\n \n for value in individuals.values():\n if (value[\"BIRT\"] == 'NA'):\n error_array.append(\"ERROR: INDIVIDUAL: US35: {}: Person {} does not have birthday!\".format(value[\"BIRT_LINE\"], value[\"BIRT\"]))\n result = False\n else:\n day_difference = determine_days(value[\"BIRT\"], None)\n if (day_difference > 0 and day_difference <= 30):\n current_dic[value[\"INDI\"]] = value\n bday_count += 1\n\n if bday_count > 0:\n #Use pretty table module to print out the results\n allFields = [\"ID\", \"Name\", \"Gender\", \"Birthday\", \"Age\", \"Alive\", \"Death\", \"Spouse\"]\n tagNames = [\"INDI\", \"NAME\", \"SEX\", \"BIRT\", \"AGE\", \"ALIVE\", \"DEAT\", \"SPOUSE\"]\n printTable(\"US35 List Recent Births Table\", allFields, tagNames, current_dic) \n return result\n\n\n# In[54]:\n\n\n#US 38 List upcoming birthdays\ndef list_upcoming_bday():\n today_month = int(datetime.today().strftime(\"%m\"))\n today_date = int(datetime.today().strftime(\"%d\"))\n current_dic = {}\n bday_count = 0\n result = True\n \n for value in individuals.values():\n if (value[\"BIRT\"] == 'NA'):\n error_array.append(\"ERROR: INDIVIDUAL: US38: {}: Person {} does not have birthday!\".format(value[\"BIRT_LINE\"], value[\"BIRT\"]))\n result = False\n else:\n current_birt = value[\"BIRT\"]\n current_month = int(current_birt.split(\"-\")[1])\n current_date = int(current_birt.split(\"-\")[2])\n day_difference = (current_month - today_month)* 30 + (current_date- today_date)\n if (day_difference > 0 and day_difference <= 30):\n current_dic[value[\"INDI\"]] = value\n bday_count += 1\n\n if bday_count > 0:\n #Use pretty table module to print out the results\n allFields = [\"ID\", \"Name\", \"Gender\", \"Birthday\", \"Age\", \"Alive\", \"Death\", \"Spouse\"]\n tagNames = [\"INDI\", \"NAME\", \"SEX\", \"BIRT\", \"AGE\", \"ALIVE\", \"DEAT\", \"SPOUSE\"]\n printTable(\"US38 List Upcoming Birthdays Table\", allFields, tagNames, current_dic)\n \n return result\n\n\n# In[55]:\n\n\n#US 39 List upcoming anniversaries\ndef list_upcoming_anni():\n today_month = int(datetime.today().strftime(\"%m\"))\n today_date = int(datetime.today().strftime(\"%d\"))\n current_dic = {}\n marr_count = 0\n result = True\n for value in family_dic.values():\n if (value[\"MARR\"] == 'NA'):\n error_array.append(\"ERROR: FAMILY: US39: {}: {}: Family does not have married date!\".format(value[\"FAM_LINE\"], value[\"FAM\"]))\n result = False\n else:\n current_marr = value[\"MARR\"]\n current_month = int(current_marr.split(\"-\")[1])\n current_date = int(current_marr.split(\"-\")[2])\n day_difference = (current_month - today_month)* 30 + (current_date - today_date)\n if (day_difference > 0 and day_difference <= 30):\n current_dic[value[\"FAM\"]] = value\n marr_count += 1\n if marr_count > 0:\n #Use pretty table module to print out the results\n allFields = [\"ID\", \"Married\", \"Husband ID\", \"Husband Name\", \"Wife ID\", \"Wife Name\"]\n tagNames = [\"FAM\", \"MARR\", \"HUSB\", \"HUSB_NAME\", \"WIFE\", \"WIFE_NAME\"]\n printTable(\"US39: List Upcoming Anniversaries Table\", allFields, tagNames, current_dic)\n \n return result\n\n\n# In[56]:\n\n\nvalid_month=['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']\n#US 41 Include partial dates\ntag_map={\"BIRT\": \"INDIVIDUAL\", \"DEAT\": \"INDIVIDUAL\", \"MARR\": \"FAMILY\", \"DIV\": \"FAMILY\"}\ndef include_partial_dates(date, line_num, tag, tag_id):\n error_tag=tag_map[tag]\n if len(date) == 2:\n if date[0] not in valid_month:\n error_array.append(\"ERROR: \"+ error_tag + \": US41: {}: {}: Invalid month format!\".format(line_num, tag_id))\n date[0]=\"JAN\"\n date.insert(0, 1)\n elif len(date) == 1:\n date.insert(0, \"JAN\")\n date.insert(0, 1)\n return date\n \n\n\n# In[57]:\n\n\n#US 42\ntag_map={\"BIRT\": \"INDIVIDUAL\", \"DEAT\": \"INDIVIDUAL\", \"MARR\": \"FAMILY\", \"DIV\": \"FAMILY\"}\ndef validate_date(date, line_num, tag, tag_id):\n error_tag=tag_map[tag]\n if (date != \"NA\"):\n try:\n datetime.strptime(date, '%Y-%m-%d')\n except ValueError:\n error_array.append(\"ERROR: \"+ error_tag +\": US42: {}: {}: {} Date is Invalid {}\".format(line_num, tag_id, tag, date))\n date=\"NA\"\n return date\n\n\n# In[58]:\n\n\n# Prints out the Individual Table\ndef printIndividualTable():\n #print(\"People Table\")\n allFields = [\"ID\", \"Name\", \"Gender\", \"Birthday\", \"Age\", \"Alive\", \"Death\", \"Child\", \"Spouse\"]\n tagNames = [\"INDI\", \"NAME\", \"SEX\", \"BIRT\", \"AGE\", \"ALIVE\", \"DEAT\", \"INDI_CHILD\", \"SPOUSE\"]\n \n printTable(\"People Table\", allFields, tagNames, individuals)\n\n\n# In[59]:\n\n\n# Prints out the Family Table\ndef printFamilyTable():\n #print(\"Families Table\")\n allFields = [\"ID\", \"Married\", \"Divorced\", \"Husband ID\", \"Husband Name\", \"Wife ID\", \"Wife Name\", \"Children\"]\n tagNames = [\"FAM\", \"MARR\", \"DIV\", \"HUSB\", \"HUSB_NAME\", \"WIFE\", \"WIFE_NAME\", \"FAM_CHILD\"]\n \n printTable(\"Families Table\", allFields, tagNames, family_dic)\n\n\n# In[60]:\n\n\n# Prints out the data in both error and anomaly arrays\ndef printError():\n file = open(\"cs555_sprint_outputs.txt\", \"a\")\n if (len(error_array) > 0):\n print(\"------error messages------\")\n file.write(\"------error messages------\" + \"\\n\")\n for error in error_array:\n print(error)\n file.write(error + \"\\n\")\n if(len(anomaly_array) > 0):\n print(\"-----anomaly messages-----\")\n file.write(\"-----anomaly messages-----\" + \"\\n\")\n for anomaly in anomaly_array:\n print(anomaly)\n file.write(anomaly + \"\\n\")\n file.close()\n \n\n\n# In[61]:\n\n\n# Prints out a table of dictionary data with the passed-in arguments\n# Parameters:\n# fields: a list of fields for the table\n# tag_names: tag names used to access each data field\n# dictionary: a dictionary filled with data\ndef printTable(table_name, fields, tag_names, dictionary):\n print(table_name)\n table = PrettyTable()\n table.field_names = fields\n for element in dictionary.values(): \n count = 1\n row_data = \"\" #string uses to store each tag within the current element\n for name in tag_names:\n if (count < int(len(tag_names))): #not the last element\n if (isinstance(element[name], list)): #current element is an array\n row_data += (\",\".join(element[name]) + \"? \")\n else: #current element is not an array\n row_data += (str(element[name]) + \"? \")\n elif (count == int(len(tag_names))):\n if (isinstance(element[name], list)): #current element is an array\n row_data += (\",\".join(element[name]))\n else: #current element is not an array\n row_data += (str(element[name]))\n break\n count+= 1;\n table.add_row(row_data.split('?'))\n # Stores outputs to a text file\n storeResults(table_name, table.get_string())\n print(table)\n\n\n# In[62]:\n\n\n# Stores all Project outputs into a single text file\n# Parameters:\n# result_name: name that will appear \ndef storeResults(result_name, outputs):\n file = open(\"cs555_sprint_outputs.txt\", \"a\")\n file.write(result_name + \"\\n\")\n file.write(outputs + \"\\n\\n\")\n file.close()\n\n\n# In[63]:\n\n\n# Global variables initialization\ntag_sp = [\"INDI\", \"FAM\"]\n#Level Zero Tags\ntag_zero = [\"HEAD\", \"TRLR\", \"NOTE\"]\n#Level One Tags\ntag_one = [\"NAME\", \"SEX\", \"BIRT\", \"DEAT\",\"FAMC\",\"FAMS\",\"MARR\", \"DIV\",\"HUSB\",\"WIFE\",\"CHIL\"]\n#Level Zero Tags\ntag_fam = {\"INDI\":[\"NAME\", \"SEX\",\"BIRT\", \"DEAT\",\"FAMC\",\"FAMS\"],\n \"FAM\":[\"MARR\", \"DIV\",\"HUSB\",\"WIFE\",\"CHIL\"], \n \"DATE\":[\"BIRT\", \"DEAT\", \"DIV\", \"MARR\"]}\nfamily_dic = None\nindividuals = None\nerror_array = []\nanomaly_array = []\n\n\n# In[64]:\n\n\ndocument = read_in(\"./acceptance_test_file_sprint4.ged\")\nif os.path.exists(\"cs555_sprint_outputs.txt\"):\n os.remove(\"cs555_sprint_outputs.txt\")\n\ncreate_individuals_map()\ncreate_family_dic()\n# Prints out all the people in GEDCOM file\nprintIndividualTable()\n# Prints out all the families in GEDCO file\nprintFamilyTable()\n\n#User 01\nis_dates_before_current_date()\n#User 02\nis_birth_before_marraige()\n#User 03\nis_birth_before_death()\n#User 04\nis_marriage_after_divorce()\n#User 05\nis_marriage_after_death()\n#User 06\ncheck_divorce_before_death()\n#User 07\nis_age_legal()\n#User 08\nbirth_before_marriage()\n#User 09\nbirth_before_death()\n#User 10\nis_marriage_legal()\n#User 11\ncheck_for_bigamy()\n#User 12\ncheck_parents_not_too_old()\n#User 13\ncheck_sibling_spacing()\n#User 14\ncheck_multiple_births()\n#User 15\ncheck_sibling_count()\n#User 16\ncheck_last_names()\n#User 17\ncheck_parent_child_marriage()\n#User 18\ncheck_sibling_marriage()\n#User 19\ncheck_cousins_marriage()\n#User 20\nis_uncle_aunt_marriage_legal()\n#User 21\ncorrect_gender()\n#User 23\nunique_name_and_birth()\n#User 24\nunique_family_by_spouses()\n#User 25\nunique_family_name_and_birth()\n#User 26\ncheck_corresponding_entries()\n#User 28\nlistSiblingsByAge()\n#User 29\nlistDeceased()\n#User 30\nlistLivingMarried()\n#User 31\nlistLivingSingle()\n#User 32\nmultiple_birth()\n#User 33\nlistAllOrphand()\n#User 34\nlarge_age_diff()\n#US 35 \nlist_recent_births()\n#User 38\nlist_upcoming_bday()\n#User 39\nlist_upcoming_anni()\n\n\n#Prints out all the errors and anomalies of each function\nprintError()\n\n","sub_path":"Project.py","file_name":"Project.py","file_ext":"py","file_size_in_byte":65371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"293634077","text":"from sklearn.datasets import make_classification\nfrom random import randint, choice\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nimport pickle\n\nfrom sklearn.naive_bayes import BernoulliNB\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.svm import LinearSVC\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import GradientBoostingClassifier\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import RandomizedSearchCV\n\nmodels = {BernoulliNB: \"BernoulliNB\", KNeighborsClassifier: 'KNeighborsClassifier', LinearSVC: 'LinearSVC',\n LogisticRegression: 'LogisticRegression', GradientBoostingClassifier: \"GBS\"}\n\nparam_grid_bernoulliNB = {'alpha': np.arange(0.01, 10000, 0.01)}\nparam_grid_k_neighbors = {'n_neighbors': np.arange(1, 100, 1), 'weights': ['uniform', 'distance'], 'p': [1, 2]}\nparam_grid_linearSVC = {\n\n 'C': np.exp(np.arange(np.log(0.001), np.log(10000), 0.01))}\nparam_grid_logistic_reg = {\n 'C': np.exp(np.arange(np.log(0.001), np.log(10000), 0.01))}\nparam_grid_gbc = {'learning_rate': np.arange(0.01, 0.3, 0.01), 'n_estimators': np.arange(5, 1000, 1),\n 'max_depth': np.arange(1, 10, 1), 'min_samples_split': np.arange(2, 10, 1),\n 'min_samples_leaf': np.arange(1, 10, 1), 'subsample': np.arange(0.6, .99, 0.05),\n 'max_features': [None, 'auto', 'sqrt', 'log2']}\n\nparam_grid = [param_grid_bernoulliNB, param_grid_k_neighbors, param_grid_linearSVC, param_grid_logistic_reg,\n param_grid_gbc]\n\n\ndef train_model(data, target, model, param_grid):\n X_train, X_test, y_train, y_test = train_test_split(data, target, random_state=42)\n\n random_search = RandomizedSearchCV(model(), param_distributions=param_grid,\n n_iter=100, cv=5).fit(X_train, y_train)\n\n return list(random_search.best_params_.values())\n\n\ndef plot_rand_search(best_params, model_name, param_name, png, j=0):\n x, y = [], []\n n = 100\n for i in best_params:\n x.append(i[j])\n plt.figure(figsize=(10, 10))\n plt.hist(x, n, facecolor='g', normed=True)\n plt.title(model_name + ':' + param_name)\n plt.grid(True)\n plt.xlabel(param_name)\n plt.savefig(png)\n plt.show()\n\n\ndef classification_generator():\n features = randint(5, 200)\n informative = randint(5, features)\n redundant = randint(0, features - informative)\n classes = randint(2, 5)\n clusters_per_class = randint(2, 20)\n flip_y = randint(1, 300) / 100\n class_sep = randint(1, 1000) / 10\n hypercube = choice([True, False])\n scale = choice([None, randint(0, 1000) / 10])\n\n data, target = make_classification(n_samples=400,\n n_features=features,\n n_informative=informative,\n n_redundant=redundant,\n n_classes=classes,\n n_clusters_per_class=clusters_per_class,\n flip_y=flip_y,\n class_sep=class_sep,\n hypercube=hypercube,\n scale=scale\n )\n return data, target\n\n\ndef func(model, param, n=20):\n result, i = [], 0\n while i < n:\n try:\n print(i)\n data, target = classification_generator()\n best_params = train_model(data, target, model, param)\n result.append(best_params)\n i += 1\n except:\n print(\"error\")\n return result\n\n\ndef aa():\n a = func(BernoulliNB, param_grid_bernoulliNB, n=50)\n plot_rand_search(a, 'BernoulliNB', 'alpha')\n\n\nif __name__ == \"__main__\":\n aa()\n # data, target = classification_generator()\n # print(train_model(data, target, GradientBoostingClassifier, param_grid_gbc))\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"456255603","text":"### test_geom.py\n\nimport sqlite3\nimport os\nimport json\nfrom spatialdb import GEODB\nfrom geomet import wkt, wkb\nimport traceback\n\nsamplePoint = 'POINT(4 4)'\nsampleLineString = 'LINESTRING(-109.6305759999999623 44.8447470000000408, -109.6304449999999520 44.8447440000000483, -109.6304429999999570 44.8447840000000610, -109.6305739999999673 44.8447870000000535, -109.6305759999999623 44.8447470000000408)'\nsamplePolygon = 'POLYGON ((-109.6305759999999623 44.8447470000000408, -109.6304449999999520 44.8447440000000483, -109.6304429999999570 44.8447840000000610, -109.6305739999999673 44.8447870000000535, -109.6305759999999623 44.8447470000000408))'\nsampleSRIDPrefix = 'SRID=4326;'\n\n\ndef test2(stateFile):\n gdb = GEODB(stateFile)\n\n print(\"\"\"\n**SQLITE tables**\"\"\")\n cur = gdb.cursor()\n cur.execute('''SELECT type, name, sql FROM sqlite_master WHERE type = 'table' and name = 'ms_bldgs' ''')\n r = cur.fetchall()\n print(r)\n\n print(\"\"\"\n**count(*) by type of ms_bldgs**\"\"\")\n cur = gdb.cursor()\n cur.execute('''SELECT count(*), st_isvalid(geom), st_geometrytype(geom) FROM ms_bldgs GROUP BY 3''')\n r = cur.fetchall()\n print(r)\n\n try:\n print(\"\"\"\n**STGEOMETRY isValid of ms_bldgs**\"\"\")\n cur = gdb.cursor()\n cur.execute('''SELECT count(*),\n st_isvalid(st_geomfromwkb(st_asbinary(geom), 4326)),\n st_geometrytype(st_geomfromwkb(st_asbinary(geom), 4326))\n FROM ms_bldgs GROUP BY 3''')\n r = cur.fetchall()\n print(r)\n except:\n traceback.print_exc()\n\n print(\"\"\"\n**HEX() of ms_bldgs**\"\"\")\n cur = gdb.cursor()\n cur.execute('''SELECT substr(hex(geom),2,2000) FROM ms_bldgs LIMIT 2''')\n r = cur.fetchall()\n print(r)\n\n print(\"\"\"\n**HEX() of st_geomfrotext() of WKT POINT**\"\"\")\n cur = gdb.cursor()\n cur.execute('''SELECT hex((st_geomfromtext('POINT(4 4)', 4326))) ''')\n r = cur.fetchall()\n print(r)\n\n print(\"\"\"\n**HEX() of Geomet WKB POINT**\"\"\")\n cur = gdb.cursor()\n # use plain WKB\n #wkbgeo = wkb.dumps(wkt.loads('POINT(4 4)'))\n # force EWKB format\n wkbgeo = wkb.dumps(wkt.loads('POINT(4 4)'))\n cur.execute('''SELECT hex(?) ''', [buffer(wkbgeo)])\n r = cur.fetchall()\n print(r)\n\n print(\"\"\"\n**HEX() of Geomet EWKB POINT**\"\"\")\n cur = gdb.cursor()\n # use plain WKB\n #wkbgeo = wkb.dumps(wkt.loads('POINT(4 4)'))\n # force EWKB format\n wkbgeo = wkb.dumps(wkt.loads('SRID=4326;POINT(4 4)'))\n cur.execute('''SELECT hex(?) ''', [buffer(wkbgeo)])\n r = cur.fetchall()\n print(r)\n\n try:\n print(\"\"\"\n**HEX(st_geomfromwkb()) of WKB POINT**\"\"\")\n cur = gdb.cursor()\n # use plain WKB\n wkbgeo = wkb.dumps(wkt.loads('POINT(4 4)'))\n cur.execute('''SELECT hex((st_geomfromwkb(?, 4326))) ''', [buffer(wkbgeo)])\n r = cur.fetchall()\n print(r)\n except:\n traceback.print_exc()\n\n try:\n print(\"\"\"\n**HEX(st_geomfromwkb()) of EWKB POINT**\"\"\")\n cur = gdb.cursor()\n # force EWKB format\n wkbgeo = wkb.dumps(wkt.loads('SRID=4326;POINT(4 4)'))\n cur.execute('''SELECT hex((st_geomfromwkb(?, 4326))) ''', [buffer(wkbgeo)])\n r = cur.fetchall()\n print(r)\n except:\n traceback.print_exc()\n\n print(\"\"\"\n**GEOMET import st_asbinary() to WKT**\"\"\")\n cur = gdb.cursor()\n cur.execute('''SELECT id, st_asbinary(geom) FROM ms_bldgs LIMIT 2''')\n r = cur.fetchall()\n\n for row in r:\n geo = wkb.loads(row[1])\n wkttext = wkt.dumps(geo)\n print(\"\"\"{id}: {wkt}, {js}\"\"\".format(id=row[0], wkt=wkttext, js=geo))\n\nstate='Wyoming'\ndbFile = 'db/' + state + '.sqlite'\nassert os.path.exists(dbFile), \"dbFile does not exist {}\".format(dbFile)\n\n#test_geom(dbFile)\ntest2(dbFile)\n","sub_path":"tests/test_geom.py","file_name":"test_geom.py","file_ext":"py","file_size_in_byte":3749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"609876067","text":"# -*- coding: utf-8 -*-\n\nfrom django.conf.urls import patterns, url\n\nfrom repo.views import RepoView, FileEdit\n\nurlpatterns = patterns('repo.views',\n url(r'^view/$', RepoView.as_view(), name='repo_view'),\n url(r'^edit/(?P.*)$', FileEdit.as_view(), name='repo_edit'),\n \n url(r'^api/files$', 'list_files', name='list_files'),\n url(r'^api/commit$', 'commit_info', name='commit_info'),\n url(r'^api/save$', 'save', name='save'),\n url(r'^api/create$', 'create', name='create'),\n url(r'^api/lock$', 'lock', name='lock'),\n url(r'^api/unlock$', 'unlock', name='unlock'),\n url(r'^api/update$', 'update', name='update'),\n url(r'^api/content$', 'content', name='content'),\n \n url(r'^api/tree$', 'tree_list', name='tree_list'),\n \n)\n","sub_path":"sc_web/repo/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"34064811","text":"import torch.utils.data as data\nfrom PIL import Image\nimport os\nimport os.path\nimport torch\nimport numpy as np\nimport torchvision.transforms as transforms\nimport argparse\nimport time\nimport random\nfrom lib.transformations import quaternion_from_euler, euler_matrix, random_quaternion, quaternion_matrix\nimport numpy.ma as ma\nimport copy\nimport scipy.misc\nimport scipy.io as scio\nimport matplotlib.pyplot as plt\nimport cv2\n\n#######################################\n#######################################\n\nfrom affpose.ARLAffPose.utils import helper_utils\n\nfrom affpose.ARLAffPose import cfg as config\n\nfrom affpose.ARLAffPose.dataset import arl_affpose_dataset_utils\nfrom affpose.ARLAffPose.utils.pose.load_obj_ply_files import load_obj_ply_files\nfrom affpose.ARLAffPose.utils.bbox.extract_bboxs_from_label import get_obj_bbox\n\n#######################################\n#######################################\n\nclass PoseDataset(data.Dataset):\n def __init__(self, mode, num_pt, add_noise, root, noise_trans, refine):\n\n ##################################\n # init path\n ##################################\n\n if mode == 'train':\n self.path = config.TRAIN_FILE\n elif mode == 'test':\n self.path = config.VAL_FILE\n print(self.path)\n\n self.num_pt = num_pt\n self.root = config.ROOT_DATA_PATH\n self.add_noise = add_noise\n self.noise_trans = noise_trans\n\n ##################################\n # image list\n ##################################\n\n self.list = []\n self.real = []\n self.syn = []\n input_file = open(self.path)\n while 1:\n input_line = input_file.readline()\n if not input_line:\n break\n if input_line[-1:] == '\\n':\n input_line = input_line[:-1]\n _is_syn = input_line.split(self.root)[1].split('/')[0] == 'Syn'\n if _is_syn:\n self.syn.append(input_line)\n else:\n self.real.append(input_line)\n self.list.append(input_line)\n input_file.close()\n\n self.length = len(self.list)\n self.len_real = len(self.real)\n self.len_syn = len(self.syn)\n\n print(\"Loaded: \", len(self.list))\n print(\"Real Images: \", len(self.real))\n print(\"SYN Images: \", len(self.syn))\n\n ##################################\n # IMGAUG\n ##################################\n\n self.trancolor = transforms.ColorJitter(0.2, 0.2, 0.2, 0.05)\n self.noise_img_loc = 0.0\n self.noise_img_scale = 7.0\n\n self.norm = transforms.Normalize(mean=config.IMG_MEAN, std=config.IMG_STD)\n\n ##################################\n # 3D models\n ##################################\n\n self.symmetry_obj_idx = config.SYM_OBJECTS\n self.minimum_num_pt = config.NUM_PT_MIN\n self.num_pt_mesh_small = config.NUM_PT_MESH_SMALL\n self.num_pt_mesh_large = config.NUM_PT_MESH_LARGE\n self.refine = refine\n self.front_num = config.FRONT_NUM\n\n self.cld, self.cld_obj_centered, self.cld_obj_part_centered, \\\n self.obj_classes, self.obj_part_classes, \\\n self.obj_ids, self.obj_part_ids = load_obj_ply_files()\n\n print()\n\n def __getitem__(self, index):\n\n ##################################\n # init\n ##################################\n\n image_addr = self.list[index].rstrip()\n dataset_dir = image_addr.split('rgb/')[0]\n image_num = image_addr.split('rgb/')[-1]\n\n img_addr = dataset_dir + 'rgb/' + image_num + config.RGB_EXT\n depth_addr = dataset_dir + 'depth/' + image_num + config.DEPTH_EXT\n obj_part_label_addr = dataset_dir + 'masks_obj_part/' + image_num + config.OBJ_PART_LABEL_EXT\n meta_addr = dataset_dir + 'meta/' + image_num + config.META_EXT\n\n img = np.array(self.trancolor(Image.open(img_addr))) if self.add_noise else np.array(Image.open(img_addr))\n depth = np.array(Image.open(depth_addr))\n obj_part_label = np.array(Image.open(obj_part_label_addr))\n meta = scio.loadmat(meta_addr)\n\n _is_syn = image_addr.split(self.root)[1].split('/')[0] == 'Syn'\n\n ##################################\n ### RESIZE & CROP\n ##################################\n\n img = cv2.resize(img, config.RESIZE, interpolation=cv2.INTER_CUBIC)\n obj_part_label = cv2.resize(obj_part_label, config.RESIZE, interpolation=cv2.INTER_NEAREST)\n depth = cv2.resize(depth, config.RESIZE, interpolation=cv2.INTER_NEAREST)\n\n img = helper_utils.crop(pil_img=img, crop_size=config.CROP_SIZE, is_img=True)\n obj_part_label = helper_utils.crop(pil_img=obj_part_label, crop_size=config.CROP_SIZE)\n depth = helper_utils.crop(pil_img=depth, crop_size=config.CROP_SIZE)\n\n ####################\n # Add Noise\n ####################\n\n mask_back = ma.getmaskarray(ma.masked_equal(obj_part_label, 0))\n\n add_front = False\n if self.add_noise:\n for k in range(5):\n # selecting random images\n image_addr = random.choice(self.syn).rstrip()\n dataset_dir = image_addr.split('rgb/')[0]\n image_num = image_addr.split('rgb/')[-1]\n _img_addr = dataset_dir + 'rgb/' + image_num + config.RGB_EXT\n _label_addr = dataset_dir + 'masks_obj_part/' + image_num + config.OBJ_PART_LABEL_EXT\n # loading random images\n front = np.array(self.trancolor(Image.open(_img_addr).convert(\"RGB\")))\n front = cv2.resize(front, config.RESIZE, interpolation=cv2.INTER_CUBIC)\n front = helper_utils.crop(pil_img=front, crop_size=config.CROP_SIZE, is_img=True)\n front = np.transpose(front, (2, 0, 1))\n f_label = np.array(Image.open(_label_addr))\n f_label = cv2.resize(f_label, config.RESIZE, interpolation=cv2.INTER_NEAREST)\n f_label = helper_utils.crop(pil_img=f_label, crop_size=config.CROP_SIZE)\n front_label = np.unique(f_label).tolist()[1:]\n if len(front_label) < self.front_num:\n continue\n front_label = random.sample(front_label, self.front_num)\n for f_i in front_label:\n mk = ma.getmaskarray(ma.masked_not_equal(f_label, f_i))\n if f_i == front_label[0]:\n mask_front = mk\n else:\n mask_front = mask_front * mk\n t_label = obj_part_label * mask_front\n if len(t_label.nonzero()[0]) > 1000:\n obj_part_label = t_label\n add_front = True\n break\n\n ##################################\n # select random obj id\n ##################################\n\n label_obj_part_ids = np.unique(np.array(obj_part_label))[1:]\n\n obj_part_ids = []\n for obj_part_id in label_obj_part_ids:\n if obj_part_id in self.obj_part_ids:\n obj_part_ids.append(obj_part_id)\n\n while True:\n obj_part_id = obj_part_ids[np.random.randint(0, len(obj_part_ids))]\n obj_id = arl_affpose_dataset_utils.map_obj_part_id_to_obj_id(obj_part_id)\n obj_name = \"{:<15}\".format(arl_affpose_dataset_utils.map_obj_id_to_name(obj_id))\n mask_label = ma.getmaskarray(ma.masked_equal(obj_part_label, obj_part_id))\n mask_rgb = np.repeat(mask_label, 3).reshape(obj_part_label.shape[0], obj_part_label.shape[1], -1) * img\n mask_depth = mask_label * ma.getmaskarray(ma.masked_not_equal(depth, 0))\n num_mask = len(mask_depth.nonzero()[0])\n # WE NEED AT LEAST minimum_num_pt ON DEPTH IMAGE.\n # This is affected by add_front to label.\n print(\"------------> {} Obj Part:{}\\tMasked Depth:{}\".format(obj_name, obj_part_id, num_mask))\n if num_mask > self.minimum_num_pt:\n break\n\n # # todo (visualize): RGB ROIs\n # cv2_img = mask_rgb.copy()\n # img_name = config.TEST_DENSEFUSION_FOLDER + 'masked_rgb.png'\n # cv2.imwrite(img_name, cv2.cvtColor(cv2_img, cv2.COLOR_BGR2RGB))\n # # todo (visualize): DEPTH ROIs\n # cv2_img = helper_utils.convert_16_bit_depth_to_8_bit(mask_depth.copy())\n # img_name = config.TEST_DENSEFUSION_FOLDER + 'masked_depth.png'\n # cv2.imwrite(img_name, cv2_img)\n # # cv2.imwrite(img_name, cv2.applyColorMap(cv2_img, cv2.COLORMAP_JET))\n\n ##################################\n # BBOX\n ##################################\n\n x1, y1, x2, y2 = get_obj_bbox(obj_part_label, obj_part_id, config.HEIGHT, config.WIDTH, config.BORDER_LIST)\n # print(\"y1, y2, x1, x2: \", y1, y2, x1, x2)\n\n # # todo (visualize): bbox\n # cv2_img = np.array(Image.open(img_addr))\n # cv2_img = cv2.resize(cv2_img, config.RESIZE, interpolation=cv2.INTER_CUBIC)\n # cv2_img = helper_utils.crop(pil_img=cv2_img, crop_size=config.CROP_SIZE, is_img=True)\n # img_name = config.TEST_DENSEFUSION_FOLDER + 'bbox.png'\n # cv2.rectangle(cv2_img, (x1, y1), (x2, y2), (255, 0, 0), 2)\n # cv2.imwrite(img_name, cv2.cvtColor(cv2_img, cv2.COLOR_BGR2RGB))\n\n ##################################\n # IMGAUG\n ##################################\n\n img = np.transpose(np.array(img)[:, :, :3], (2, 0, 1))[:, y1:y2, x1:x2]\n\n if _is_syn:\n is_blank_background = False\n while not is_blank_background:\n # selecting random images\n image_addr = random.choice(self.real).rstrip()\n dataset_dir = image_addr.split('rgb/')[0]\n image_num = image_addr.split('rgb/')[-1]\n _img_addr = dataset_dir + 'rgb/' + image_num + config.RGB_EXT\n _label_addr = dataset_dir + 'masks_obj_part/' + image_num + config.OBJ_PART_LABEL_EXT\n # loading random images\n back = np.array(self.trancolor(Image.open(_img_addr).convert(\"RGB\")))\n back = cv2.resize(back, config.RESIZE, interpolation=cv2.INTER_CUBIC)\n back = helper_utils.crop(pil_img=back, crop_size=config.CROP_SIZE, is_img=True)\n back = np.transpose(back, (2, 0, 1))[:, y1:y2, x1:x2]\n back_label = np.array(Image.open(_label_addr))[y1:y2, x1:x2]\n back_label = cv2.resize(back_label, config.RESIZE, interpolation=cv2.INTER_NEAREST)\n back_label = helper_utils.crop(pil_img=back_label, crop_size=config.CROP_SIZE)\n back_obj_ids = np.unique(np.array(back_label)).tolist()\n # print('is_blank_background: ', is_blank_background, ', back_obj_ids: ', back_obj_ids)\n if len(back_obj_ids) == 1:\n is_blank_background = True\n # print('is_blank_background: ', is_blank_background, ', back_obj_ids: ', back_obj_ids)\n img_masked = back * mask_back[y1:y2, x1:x2] + np.transpose(mask_rgb, (2, 0, 1))[:, y1:y2, x1:x2]\n else:\n img_masked = img\n\n if self.add_noise and add_front:\n img_masked = img_masked * mask_front[y1:y2, x1:x2] + front[:, y1:y2, x1:x2] * ~(mask_front[y1:y2, x1:x2])\n\n if _is_syn:\n img_masked = img_masked + np.random.normal(loc=self.noise_img_loc, scale=self.noise_img_scale,\n size=img_masked.shape)\n\n # # todo (visualize): RGB ROIs\n # cv2_img = np.transpose(img_masked, (1, 2, 0)).astype(np.float32).copy()\n # img_name = config.TEST_DENSEFUSION_FOLDER + 'imgaug_img.png'\n # cv2.imwrite(img_name, cv2.cvtColor(cv2_img, cv2.COLOR_BGR2RGB))\n # cv2_img = mask_depth[y1:y2, x1:x2].astype(np.int32).copy()\n # img_name = config.TEST_DENSEFUSION_FOLDER + 'imgaug_depth.png'\n # cv2.imwrite(img_name, cv2_img)\n\n ##################################\n # META\n ##################################\n\n self.xmap = config.XMAP\n self.ymap = config.YMAP\n\n cam_scale = config.CAMERA_SCALE # 1000 for depth [mm] to [m]\n cam_cx = meta['cam_cx'].flatten()[0] * config.X_SCALE\n cam_cy = meta['cam_cy'].flatten()[0] * config.Y_SCALE\n cam_fx = meta['cam_fx'].flatten()[0]\n cam_fy = meta['cam_fy'].flatten()[0]\n\n cam_mat = np.array([[cam_fx, 0, cam_cx], [0, cam_fy, cam_cy], [0, 0, 1]])\n cam_distortion = np.array([0.0, 0.0, 0.0, 0.0, 0.0])\n\n ##################################\n # GT POSE\n ##################################\n\n obj_part_id_idx = str(1000 + obj_part_id)[1:]\n\n obj_part_r = meta['obj_part_rotation_' + np.str(obj_part_id_idx)]\n obj_part_t = meta['obj_part_translation_' + np.str(obj_part_id_idx)] # in [m]\n\n # # todo (visualize): gt pose\n # cv2_img = np.array(Image.open(img_addr))\n # cv2_img = cv2.resize(cv2_img, config.RESIZE, interpolation=cv2.INTER_CUBIC)\n # cv2_img = helper_utils.crop(pil_img=cv2_img, crop_size=config.CROP_SIZE, is_img=True)\n # imgpts, jac = cv2.projectPoints(self.cld_obj_part_centered[obj_part_id] * 1e3, obj_part_r, obj_part_t * 1e3, cam_mat, cam_distortion)\n # cv2_img = cv2.polylines(np.array(cv2_img), helper_utils.sort_imgpts(imgpts), True, (0, 255, 255))\n # temp_folder = config.TEST_DENSEFUSION_FOLDER + 'pose_gt.png'\n # cv2.imwrite(temp_folder, cv2.cvtColor(cv2_img, cv2.COLOR_BGR2RGB))\n\n ##################################\n # Select Region of Interest\n ##################################\n\n choose = mask_depth[y1:y2, x1:x2].flatten().nonzero()[0]\n\n if len(choose) > self.num_pt:\n c_mask = np.zeros(len(choose), dtype=int)\n c_mask[:self.num_pt] = 1\n np.random.shuffle(c_mask)\n choose = choose[c_mask.nonzero()]\n else:\n choose = np.pad(choose, (0, self.num_pt - len(choose)), 'wrap')\n\n depth_masked = depth[y1:y2, x1:x2].flatten()[choose][:, np.newaxis].astype(np.float32)\n xmap_masked = self.xmap[y1:y2, x1:x2].flatten()[choose][:, np.newaxis].astype(np.float32)\n ymap_masked = self.ymap[y1:y2, x1:x2].flatten()[choose][:, np.newaxis].astype(np.float32)\n choose = np.array([choose])\n\n ######################################\n # create point cloud from depth image\n ######################################\n\n pt2 = depth_masked / cam_scale\n pt0 = (ymap_masked - cam_cx) * pt2 / cam_fx\n pt1 = (xmap_masked - cam_cy) * pt2 / cam_fy\n cloud = np.concatenate((pt0, pt1, pt2), axis=1)\n\n translation_noise = np.array([random.uniform(-self.noise_trans, self.noise_trans) for i in range(3)])\n if self.add_noise:\n cloud = np.add(cloud, translation_noise)\n\n # # todo (visualize): pointcloud_from_depth\n # cv2_img = np.array(Image.open(img_addr))\n # cv2_img = cv2.resize(cv2_img, config.RESIZE, interpolation=cv2.INTER_CUBIC)\n # cv2_img = helper_utils.crop(pil_img=cv2_img, crop_size=config.CROP_SIZE, is_img=True)\n # imgpts, jac = cv2.projectPoints(cloud, np.eye(3), np.zeros(shape=obj_part_t.shape), cam_mat, cam_distortion)\n # cv2_img = cv2.polylines(np.array(cv2_img), helper_utils.sort_imgpts(imgpts), True, (0, 255, 255))\n # temp_folder = config.TEST_DENSEFUSION_FOLDER + 'pose_pointcloud_from_depth.png'\n # cv2.imwrite(temp_folder, cv2.cvtColor(cv2_img, cv2.COLOR_BGR2RGB))\n\n ######################################\n # create target from gt pose\n ######################################\n\n dellist = [j for j in range(0, len(self.cld_obj_part_centered[obj_part_id]))]\n if self.refine:\n dellist = random.sample(dellist, len(self.cld_obj_part_centered[obj_part_id]) - self.num_pt_mesh_large)\n else:\n dellist = random.sample(dellist, len(self.cld_obj_part_centered[obj_part_id]) - self.num_pt_mesh_small)\n model_points = np.delete(self.cld_obj_part_centered[obj_part_id], dellist, axis=0)\n\n target = np.dot(model_points, obj_part_r.T)\n if self.add_noise:\n target = np.add(target, obj_part_t + translation_noise)\n else:\n target = np.add(target, obj_part_t)\n\n # # todo (visualize): gt pose from object mesh\n # cv2_img = np.array(Image.open(img_addr))\n # cv2_img = cv2.resize(cv2_img, config.RESIZE, interpolation=cv2.INTER_CUBIC)\n # cv2_img = helper_utils.crop(pil_img=cv2_img, crop_size=config.CROP_SIZE, is_img=True)\n # imgpts, jac = cv2.projectPoints(target, np.eye(3), np.zeros(shape=obj_part_t.shape), cam_mat, cam_distortion)\n # cv2_img = cv2.polylines(np.array(cv2_img), helper_utils.sort_imgpts(imgpts), True, (0, 255, 255))\n # temp_folder = config.TEST_DENSEFUSION_FOLDER + 'pose_gt_target.png'\n # cv2.imwrite(temp_folder, cv2.cvtColor(cv2_img, cv2.COLOR_BGR2RGB))\n\n ######################################\n ######################################\n\n return torch.from_numpy(cloud.astype(np.float32)), \\\n torch.LongTensor(choose.astype(np.int32)), \\\n self.norm(torch.from_numpy(img_masked.astype(np.float32))), \\\n torch.from_numpy(target.astype(np.float32)), \\\n torch.from_numpy(model_points.astype(np.float32)), \\\n torch.LongTensor([int(obj_id) - 1])\n\n ######################################\n ######################################\n\n def __len__(self):\n return self.length\n\n def get_sym_list(self):\n return self.symmetry_obj_idx\n\n def get_num_points_mesh(self):\n if self.refine:\n return self.num_pt_mesh_large\n else:\n return self.num_pt_mesh_small\n\n ######################################\n ######################################","sub_path":"datasets/arl_affpose/dataset_aff.py","file_name":"dataset_aff.py","file_ext":"py","file_size_in_byte":18085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"56579703","text":"\"\"\"\nClass: Stat232C\nProject 1: Bayesian inference\nName: \nDate: April 2020\n\n\"\"\"\n\ndef getPosterior(priorOfA, priorOfB, likelihood):\n\t\n##################################################\n#\t\tYour code here\n##################################################\n \n\n\n\n\n\n\n\n\n\n\n\n\n return([marginalOfA, marginalOfB])\n\n\n\ndef main():\n exampleOnePriorofA = {'a0': .5, 'a1': .5}\n exampleOnePriorofB = {'b0': .25, 'b1': .75}\n exampleOneLikelihood = {('a0', 'b0'): 0.42, ('a0', 'b1'): 0.12, ('a1', 'b0'): 0.07, ('a1', 'b1'): 0.02}\n print(getPosterior(exampleOnePriorofA, exampleOnePriorofB, exampleOneLikelihood))\n\n exampleTwoPriorofA = {'red': 1/10 , 'blue': 4/10, 'green': 2/10, 'purple': 3/10}\n exampleTwoPriorofB = {'x': 1/5, 'y': 2/5, 'z': 2/5}\n exampleTwoLikelihood = {('red', 'x'): 0.2, ('red', 'y'): 0.3, ('red', 'z'): 0.4, ('blue', 'x'): 0.08, ('blue', 'y'): 0.12, ('blue', 'z'): 0.16, ('green', 'x'): 0.24, ('green', 'y'): 0.36, ('green', 'z'): 0.48, ('purple', 'x'): 0.32, ('purple', 'y'): 0.48, ('purple', 'z'): 0.64}\n print(getPosterior(exampleTwoPriorofA, exampleTwoPriorofB, exampleTwoLikelihood))\n\n\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"hw1/BayesianInference.py","file_name":"BayesianInference.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"360701598","text":"import os\nimport sys\nimport argparse\n\nfrom sklearn.datasets import load_iris\nfrom sklearn.model_selection import train_test_split\n\nsys.path.append(os.getcwd())\nfrom solnml.utils.data_manager import DataManager\nfrom solnml.estimators import Classifier\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--time_limit', type=int, default=150)\nparser.add_argument('--eval_type', type=str, default='holdout', choices=['holdout', 'cv', 'partial'])\nparser.add_argument('--ens_method', default='ensemble_selection',\n choices=['none', 'bagging', 'blending', 'stacking', 'ensemble_selection'])\n\nargs = parser.parse_args()\ntime_limit = args.time_limit\neval_type = args.eval_type\nensemble_method = args.ens_method\n\nsave_dir = './data/tmps/'\nif not os.path.exists(save_dir):\n os.makedirs(save_dir)\n\niris = load_iris()\nX, y = iris.data, iris.target\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=1)\ndm = DataManager(X_train, y_train)\ntrain_data = dm.get_data_node(X_train, y_train)\ntest_data = dm.get_data_node(X_test, y_test)\n\nclf = Classifier(time_limit=150,\n output_dir=save_dir,\n ensemble_method=ensemble_method,\n evaluation=eval_type,\n metric='acc')\nclf.fit(train_data)\nclf.refit()\npred = clf.predict(test_data)\nprint('final score', clf.score(test_data))\n","sub_path":"test/automl_estimators/evaluate_estimators.py","file_name":"evaluate_estimators.py","file_ext":"py","file_size_in_byte":1378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"235039525","text":"# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html\n\n\n# useful for handling different item types with a single interface\nimport pymongo\nimport pymysql\nfrom itemadapter import ItemAdapter\nfrom keep.util import *\n\n\n# 数据源数据存储\nclass MongoPipeline:\n\n def __init__(self, mongo_uri, mongo_db):\n self.mongo_uri = mongo_uri\n self.mongo_db = mongo_db\n\n @classmethod\n def from_crawler(cls, crawler):\n return cls(\n mongo_uri=crawler.settings.get('MONGODB_URI'),\n mongo_db=crawler.settings.get('MONGODB_DB', 'djData')\n )\n\n def open_spider(self, spider):\n self.client = pymongo.MongoClient(self.mongo_uri)\n self.db = self.client[self.mongo_db]\n\n def close_spider(self, spider):\n self.client.close()\n\n def process_item(self, item, spider):\n data = get_collection_name(spider, item)\n prefix = spider.settings.get('COLLECTION_PREFIX')\n ret = self.db[prefix + data['collection']].update(\n data['spec'], {'$set': ItemAdapter(item).asdict()}, True)\n\n if ret['updatedExisting'] and ret['nModified'] == 0: # 数据存在,且数据没有变化\n return None\n\n if data['collection'] == 'match':\n # 保存战队信息\n for team in item['participants']:\n if team['id'] is None:\n continue\n self.db[prefix + 'team'].update(\n {'id': team['id']}, {'$set': team}, True)\n # return get_match_item(item)\n return None\n\n\n# 数据源 -> 游戏元数据\nclass MapPipeline:\n def __init__(self, mongo_uri, mongo_db):\n self.mongo_uri = mongo_uri\n self.mongo_db = mongo_db\n\n @classmethod\n def from_crawler(cls, crawler):\n return cls(\n mongo_uri=crawler.settings.get('MONGODB_URI'),\n mongo_db=crawler.settings.get('MONGODB_DB_STABLE', 'djDataStable'),\n )\n\n def open_spider(self, spider):\n self.client = pymongo.MongoClient(self.mongo_uri)\n self.db = self.client[self.mongo_db]\n\n def close_spider(self, spider):\n self.client.close()\n\n def process_item(self, item, spider):\n if item is None:\n return\n if 'bet_id' in item.keys():\n collection = 'bet'\n spec = {'bet_id': item['bet_id'], 'match_id': item['match_id']}\n elif 'match_id' in item.keys():\n collection = 'match'\n spec = {'match_id': item['match_id']}\n else:\n return\n prefix = spider.settings.get('COLLECTION_PREFIX')\n ret = self.db[prefix + collection].update(\n spec, {'$set': ItemAdapter(item).asdict()}, True)\n print(ret)\n\n\n# 游戏元数据 -> 真实数据\nclass MySQLPipeline(object):\n\n def __init__(self, mysql_host, mysql_port, mysql_db, mysql_user, mysql_pwd):\n self.mysql_host = mysql_host\n self.mysql_port = mysql_port\n self.mysql_db = mysql_db\n self.mysql_user = mysql_user\n self.mysql_pwd = mysql_pwd\n\n @classmethod\n def from_crawler(cls, crawler):\n return cls(\n mysql_host=crawler.settings.get('MYSQL_HOST'),\n mysql_port=crawler.settings.get('MYSQL_PORT'),\n mysql_user=crawler.settings.get('MYSQL_USER'),\n mysql_pwd=crawler.settings.get('MYSQL_PWD'),\n mysql_db=crawler.settings.get('MYSQL_DB'),\n )\n\n def open_spider(self, spider):\n # 连接数据库\n self.connect = pymysql.connect(\n host=self.mysql_host, # 数据库地址\n port=self.mysql_port, # 数据库端口\n db=self.mysql_db, # 数据库名\n user=self.mysql_user, # 数据库用户名\n passwd=self.mysql_pwd, # 数据库密码\n charset='utf8', # 编码方式\n use_unicode=True)\n # 通过cursor执行增删查改\n self.cursor = self.connect.cursor()\n\n def close_spider(self, spider):\n self.cursor.close()\n self.connect.close()\n\n def process_item(self, item, spider):\n self.cursor.execute(\n \"\"\"insert into mingyan(tag, cont)\n value (%s, %s)\"\"\", # 纯属python操作mysql知识,不熟悉请恶补\n (item['tag'], # item里面定义的字段和表字段对应\n item['cont'],))\n # 提交sql语句\n self.connect.commit()\n return item # 必须实现返回\n","sub_path":"keep/keep/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":4557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"270056356","text":"'''\r\nDATE SERIES ADJUSTED PLOTTED GRAPH Moving Average adjusted\r\n'''\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport datetime\r\n#import seaborn\r\n\r\n\r\ndef simple_mva(value, mvarange):\r\n weights = np.repeat(1.0, mvarange) / mvarange\r\n simple_mva = np.convolve(value, weights, 'valid')\r\n return simple_mva\r\n\r\ndef Data_Frame_plot(Data_Frame):\r\n Data_Frame.plot()\r\n plt.show()\r\n\r\ndef MVA_DF(File):\r\n Data_File = pd.read_csv(File)\r\n\r\n D_F_Data_COL = Data_File.loc[0:1000,'Value']\r\n D_F_Date_COL = Data_File.loc[0:1000,'Date']\r\n\r\n Value_Original = D_F_Data_COL.tolist()#-------------------Parsing Data from CSV DATA_Frame to a lis t\r\n Value_Original = Value_Original[::-1]\r\n\r\n Value_Original_adj = Value_Original[199:1001]\r\n Value_Original_adj = pd.Series(Value_Original_adj)\r\n Value_series = pd.Series(Value_Original)#--------------Parsing Values from list to a pandas Series Object\r\n\r\n Dates_Original = D_F_Date_COL.tolist() #-------------------Parsing Dates from CSV DATA_Frame to a list\r\n Dates_series = pd.Series(Dates_Original[801::-1])#------------------Parsing Dates to a Pandas Series Object\r\n\r\n MVA_10_Val = simple_mva(Value_Original,10)#------------------Parsing output of Simple moving average to a list\r\n MVA_50_Val = simple_mva(Value_Original,50)#------------------Parsing output of Simple moving average to a list\r\n MVA_120_Val = simple_mva(Value_Original,120)#------------------Parsing output of Simple moving average to a list\r\n MVA_200_Val = simple_mva(Value_Original,200)#------------------Parsing output of Simple moving average to a list\r\n\r\n\r\n MVA_10_series_adj = pd.Series(MVA_10_Val[190:])#------------------Parsing Simple moving average list to a Pandas Series Object\r\n MVA_50_series_adj = pd.Series(MVA_50_Val[150:])#------------------Parsing Simple moving average list to a Pandas Series Object\r\n MVA_120_series_adj = pd.Series(MVA_120_Val[80:])#------------------Parsing Simple moving average list to a Pandas Series Object\r\n MVA_200_series = pd.Series(MVA_200_Val)#------------------Parsing Simple moving average list to a Pandas Series Object\r\n\r\n#----------------------------------------------Creating DataFrame--------------------------------------------------\r\n\r\n Data_Frame_adj = pd.DataFrame({'Dates':Dates_series,'MVA_10':MVA_10_series_adj,'MVA_50':MVA_50_series_adj,'MVA_120':MVA_120_series_adj,'MVA_200':MVA_200_series,'Data':Value_Original_adj})\r\n Data_Frame_adj[\"Dates\"] = pd.to_datetime(Data_Frame_adj[\"Dates\"])#--------------------Parsing the old Data Frame to Date time series representation....\r\n Data_Frame_adj_Dates = Data_Frame_adj.set_index('Dates')\r\n print(Data_Frame_adj_Dates)\r\n\r\n#---------------------------------------TRADING ALGORITHM 1------------------------------------------------------------------------\r\n i=0\r\n Buy_list=[]\r\n Sell_list=[]\r\n Dates_Sell =[]\r\n Dates_Buy=[]\r\n\r\n for i in range(0,801):\r\n if MVA_10_series_adj[i] > MVA_50_series_adj[i] > MVA_120_series_adj[i] > MVA_200_series[i] :\r\n\r\n print(Dates_series[i])\r\n print(Value_Original_adj[i])\r\n print('Buy')\r\n Buy_list.append(Value_Original_adj[i])\r\n Dates_Buy.append(Dates_series[i])\r\n i += 1\r\n\r\n elif MVA_10_series_adj[i] > MVA_50_series_adj[i] > MVA_120_series_adj[i] < MVA_200_series[i] :\r\n\r\n print(Dates_series[i])\r\n print(Value_Original_adj[i])\r\n #print('Buy POTENTIAL')\r\n i += 1\r\n\r\n elif MVA_10_series_adj[i] > MVA_50_series_adj[i] < MVA_120_series_adj[i] < MVA_200_series[i]:\r\n\r\n print(Dates_series[i])\r\n print(Value_Original_adj[i])\r\n # print('Buy POTENTIAL -1')\r\n i += 1\r\n\r\n elif MVA_10_series_adj[i] > MVA_50_series_adj[i] < MVA_120_series_adj[i] < MVA_200_series[i]:\r\n\r\n print(Dates_series[i])\r\n print(Value_Original_adj[i])\r\n print('Buy POTENTIAL -2')\r\n i += 1\r\n\r\n elif MVA_10_series_adj[i] < MVA_50_series_adj[i] < MVA_120_series_adj[i] < MVA_200_series[i]:\r\n\r\n print(Dates_series[i])\r\n print(Value_Original_adj[i])\r\n # print('Buy POTENTIAL -3')\r\n i += 1\r\n\r\n elif MVA_50_series_adj[i] < MVA_200_series[i]:\r\n\r\n print(Dates_series[i])\r\n print(Value_Original_adj[i])\r\n print('Sell')\r\n Sell_list.append(Value_Original_adj[i])\r\n Dates_Sell.append(Dates_series[i])\r\n i += 1\r\n\r\n#--------------------------------TRADING ALGORITHM LOGIC ENDDS\r\n\r\n\r\n Buy_list = pd.Series(Buy_list[0:57])\r\n Dates_Buy = pd.Series(Dates_Buy[0:57])\r\n Sell_list = pd.Series(Sell_list)\r\n Dates_Sell=pd.Series(Dates_Sell)\r\n\r\n\r\n Buy_list_list = Buy_list.tolist()\r\n Sell_list_list = Sell_list.tolist()\r\n\r\n\r\n print(Buy_list)\r\n print(Dates_Buy)\r\n print(Sell_list)\r\n print(Dates_Sell)\r\n\r\n\r\n\r\n DF_Buy = pd.DataFrame({'Date':Dates_Buy,'Buy_Price':Buy_list})\r\n DF_Buy = DF_Buy.set_index('Date')\r\n\r\n DF_Sell = pd.DataFrame({'Date': Dates_Sell, 'Sell_Price': Sell_list})\r\n DF_Sell = DF_Sell.set_index('Date')\r\n\r\n\r\n\r\n print(DF_Buy)\r\n print(DF_Sell)\r\n\r\n Data_Frame_plot(Data_Frame_adj_Dates)#------------------------Plotting Function is called\r\n Data_Frame_plot(DF_Buy)\r\n Data_Frame_plot(DF_Sell)\r\n\r\n print(len(Buy_list))\r\n print(len(Dates_Buy))\r\n print(len(Sell_list))\r\n print(len(Dates_Sell))\r\n\r\n# Data_Frame_WO_MVA =\r\n\r\n\r\n frames = [DF_Buy,DF_Sell]\r\n result = pd.concat(frames)\r\n print(result)\r\n\r\n\r\n#--------------------------------------------------INTEGRATING PROFIT LOSS-------------------------\r\n\r\n trade_cost_buy = [] # List for storing the value of trading cost of buy\r\n update_list_amount = [] # List for storing the value of available balance\r\n trade_cost_sell = [] # List for storing the value of trading cost of sell\r\n # update_list_sell=[]\r\n final_amount_list = [] # List for storing the value of final amount\r\n final_profit_loss = [] # List for storing the value of final profit or loss\r\n flag = False\r\n\r\n quant = 200\r\n\r\n def buy(i, j): # Funcation for buy\r\n\r\n k = 0\r\n a = 0\r\n\r\n print(\"Please enter your balance:\\n\")\r\n amount = input() # getting the value in string\r\n amount = float(amount) # convert sting into integer value\r\n\r\n for value in Buy_list_list:\r\n total_trade = Buy_list_list[k] * quant # total trade for buy\r\n print(\"\\nBuy\", k, \":\", total_trade)\r\n trade_cost_buy.append(total_trade) # update the list\r\n\r\n if (total_trade != 0):\r\n flag = True\r\n k = k + 1 # increment\r\n\r\n for update in trade_cost_buy:\r\n avl_balance = amount - trade_cost_buy[a]\r\n amount = avl_balance\r\n # amount=avl_balance\r\n print(\"\\nBalance\", a, \"is:\", avl_balance)\r\n a = a + 1\r\n if avl_balance < 0:\r\n print(\"Margin\")\r\n update_list_amount.append(avl_balance) # update the list\r\n\r\n elif avl_balance > 0:\r\n print(\"No Margin\")\r\n update_list_amount.append(avl_balance) # update the list\r\n\r\n # Total_margin = update_list_amount(update_list_amount.__len__() -1 )\r\n\r\n\r\n buy(10, 20) # Function call to buy\r\n\r\n print(\"\\n..........Your selling value..........\")\r\n\r\n def sell(p, q): # Funcation for sell\r\n\r\n b = 0\r\n\r\n for value1 in Sell_list_list:\r\n\r\n if (flag == True): # checking the condition if buy is done or not\r\n print(\"Sorry,Sell is not possible yet!\\n\")\r\n\r\n else:\r\n total_trade1 = Sell_list_list[b] * quant # total trade for sell\r\n print(\"\\nSell\", b, \"is:\", total_trade1)\r\n trade_cost_sell.append(total_trade1) # update the list\r\n b = b + 1 # increment\r\n\r\n sell(14, 25) # function call to sell\r\n\r\n print(\"\\n..........Your Final Amount..........\")\r\n\r\n def final(a, b): # Funcation for profit\r\n\r\n y = 0\r\n z = 0\r\n m = 0\r\n p = 0\r\n\r\n for calculate in trade_cost_sell:\r\n for calculate1 in trade_cost_buy:\r\n\r\n final_amount = (trade_cost_sell[y] - trade_cost_buy[z]) # Final amount(profit or Loss)\r\n\r\n final_amount_list.append(final_amount) # update the list\r\n y = y + 1\r\n z = z + 1\r\n p = p + 1\r\n\r\n if (final_amount_list[m] < 0):\r\n print(\"\\nYou get\", final_amount, \" in forex treding \", m)\r\n m = m + 1 # increment\r\n\r\n elif (final_amount_list[m] > 0):\r\n print(\"\\nYou get\", final_amount, \" in forex trading \", m)\r\n m = m + 1 # increment\r\n\r\n else:\r\n print(\"\\nSorry!your final amount is zero!\")\r\n\r\n m = m + 1 # increment\r\n\r\n return\r\n\r\n\r\n\r\n\r\n final(14, 17) # function call to profit\r\n\r\n print(\"\\n.......... Your profit or Loss ..........\")\r\n\r\n def profit(i): # Function define for profit\r\n a = 0\r\n sum = 0\r\n for pro_or_loss in final_amount_list: # logic for getting the value from list\r\n sum1 = sum + final_amount_list[a]\r\n sum = sum1\r\n a = a + 1\r\n final_profit_loss.append(sum1) # List is updated\r\n\r\n if sum > 0:\r\n print(\"\\nYour Profit is:\", sum)\r\n if (update_list_amount[len(update_list_amount)- 1] < 0):\r\n #print(\"No Margin is:\", abs(update_list_amount[len(update_list_amount)- 1]))\r\n print(print(\"Margin is:\", abs(update_list_amount[len(update_list_amount)- 1])))\r\n else:\r\n print(\"You have No Margin Your Balance is: \",abs(update_list_amount[len(update_list_amount)- 1]))\r\n elif sum < 0:\r\n print(\"\\nYour Loss is:\", sum)\r\n # print(\"Margin is:\", update_list_amount[len(update_list_amount) - 1])\r\n\r\n profit(10)\r\n #list_len1=len(update_list_amount)-1\r\n\r\n\r\n#---------------------------------------------------PROFIT LOSS END--------------------------------------------------\r\n\r\n\r\n#----------------------------------------------------------------------------------------------------------------------------------\r\nMVA_DF(\"BOE-EUR-USD.csv\")#-------------------------------------Calls MVA FUNCTION to plot respective Currec\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":"Integrated_1_BS_M.py","file_name":"Integrated_1_BS_M.py","file_ext":"py","file_size_in_byte":10638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"456193636","text":"from aws_cdk import core\nfrom aws_cdk import (\n aws_glue as glue,\n aws_iam as iam,\n)\nfrom data_platform import Environment\nfrom data_platform.data_lake.base import BaseDataLakeBucket\n\n\nclass BaseDataLakeGlueDatabase(glue.Database):\n \"\"\"\n Creates a glue database associated to a data lake bucket\n \"\"\"\n\n def __init__(\n self, scope: core.Construct, data_lake_bucket: BaseDataLakeBucket, **kwargs\n ) -> None:\n self.data_lake_bucket = data_lake_bucket\n self.deploy_env = self.data_lake_bucket.deploy_env\n self.obj_name = f\"glue-juan-armond-{self.deploy_env.value}-data-lake-{self.data_lake_bucket.layer.value}\"\n\n super().__init__(\n scope,\n self.obj_name,\n database_name=self.database_name,\n location_uri=self.location_uri,\n )\n\n @property\n def database_name(self):\n \"\"\"\n Returns the glue database name\n \"\"\"\n return self.obj_name.replace(\"-\", \"_\")\n\n @property\n def location_uri(self):\n \"\"\"\n Returns the database location\n \"\"\"\n return f\"s3://{self.data_lake_bucket.bucket_name}\"\n\n\nclass BaseDataLakeGlueRole(iam.Role):\n def __init__(\n self, scope: core.Construct, data_lake_bucket: BaseDataLakeBucket, **kwargs\n ) -> None:\n self.data_lake_bucket = data_lake_bucket\n self.deploy_env = self.data_lake_bucket.deploy_env\n self.layer = self.data_lake_bucket.layer\n super().__init__(\n scope,\n id=f\"iam-{self.deploy_env.value}-glue-data-lake-{self.layer.value}-role\",\n assumed_by=iam.ServicePrincipal(\"glue.amazonaws.com\"),\n description=f\"Allows using Glue on Data Lake {self.layer.value}\",\n )\n self.bucket_arn = self.data_lake_bucket.bucket_arn\n self.add_policy()\n self.add_instance_profile()\n\n def add_policy(self):\n policy = iam.Policy(\n self,\n id=f\"iam-{self.deploy_env.value}-glue-data-lake-{self.layer.value}-policy\",\n policy_name=f\"iam-{self.deploy_env.value}-glue-data-lake-{self.layer.value}-policy\",\n statements=[\n iam.PolicyStatement(\n actions=[\"s3:ListBucket\", \"s3:GetObject\", \"s3:PutObject\"],\n resources=[self.bucket_arn, f\"{self.bucket_arn}/*\"],\n ),\n iam.PolicyStatement(\n actions=[\"cloudwatch:PutMetricData\"],\n resources=[\"arn:aws:cloudwatch:*\"],\n ),\n iam.PolicyStatement(actions=[\"glue:*\"], resources=[\"arn:aws:glue:*\"]),\n iam.PolicyStatement(\n actions=[\n \"logs:CreateLogGroup\",\n \"logs:CreateLogStream\",\n \"logs:PutLogEvents\",\n ],\n resources=[\"arn:aws:logs:*:*:/aws-glue/*\"],\n ),\n ],\n )\n self.attach_inline_policy(policy)\n\n def add_instance_profile(self):\n iam.CfnInstanceProfile(\n self,\n id=f\"iam-{self.deploy_env.value}-glue-data-lake-{self.layer.value}-instance-profile\",\n instance_profile_name=f\"iam-{self.deploy_env.value}-glue-data-lake-{self.layer.value}-instance-profile\",\n roles=[self.role_name],\n )\n\n\nclass BaseGlueCrawler(glue.CfnCrawler):\n def __init__(\n self,\n scope: core.Construct,\n table_name: str,\n glue_database: BaseDataLakeGlueDatabase,\n schedule_expression: str,\n glue_role: BaseDataLakeGlueRole,\n **kwargs,\n ) -> None:\n\n self.glue_database = glue_database\n self.glue_role = glue_role\n self.schedule_expression = schedule_expression\n self.table_name = table_name\n self.deploy_env = self.glue_database.deploy_env\n self.data_lake_bucket = self.glue_database.data_lake_bucket\n self.obj_name = f\"glue-{self.deploy_env.value}-{self.data_lake_bucket.layer.value}-{self.table_name}-crawler\"\n super().__init__(\n scope,\n id=self.obj_name,\n name=self.obj_name,\n description=f\"Crawler to detect a data scheme of data store at \"\n f\"Data Lake {self.data_lake_bucket.layer.value}.{self.table_name}\",\n schedule=self.crawler_schedule,\n role=self.glue_role.role_arn,\n database_name=self.glue_database.database_name,\n targets=self.targets,\n **kwargs,\n )\n\n @property\n def crawler_schedule(self):\n return glue.CfnCrawler.ScheduleProperty(\n schedule_expression=self.schedule_expression\n )\n\n @property\n def targets(self):\n return glue.CfnCrawler.TargetsProperty(\n s3_targets=[\n glue.CfnCrawler.S3TargetProperty(\n path=f\"s3://{self.data_lake_bucket.bucket_name}/{self.table_name}\"\n ),\n ]\n )\n\n\nclass OrdersTable(glue.Table):\n def __init__(\n self,\n scope: core.Construct,\n glue_database: BaseDataLakeGlueDatabase,\n glue_role: BaseDataLakeGlueRole,\n **kwargs,\n ) -> None:\n self.glue_role = glue_role\n self.glue_database = glue_database\n self.deploy_env = self.glue_database.deploy_env\n self.data_lake_bucket = self.glue_database.data_lake_bucket\n self.obj_name = f\"glue-{self.deploy_env.value}-orders-table\"\n super().__init__(\n scope,\n self.obj_name,\n table_name=\"orders\",\n description=\"orders captured from Postgres using DMS CDC\",\n database=self.glue_database,\n compressed=True,\n data_format=glue.DataFormat.PARQUET,\n s3_prefix=\"orders/public/orders\",\n bucket=self.data_lake_bucket,\n columns=[\n glue.Column(\n name=\"op\", type=glue.Type(input_string=\"string\", is_primitive=True)\n ),\n glue.Column(\n name=\"extracted_at\",\n type=glue.Type(input_string=\"string\", is_primitive=True),\n ),\n glue.Column(\n name=\"created_at\",\n type=glue.Type(input_string=\"timestamp\", is_primitive=True),\n ),\n glue.Column(\n name=\"order_id\", type=glue.Type(input_string=\"int\", is_primitive=True)\n ),\n glue.Column(\n name=\"product_name\",\n type=glue.Type(input_string=\"string\", is_primitive=True),\n ),\n glue.Column(\n name=\"value\", type=glue.Type(input_string=\"double\", is_primitive=True)\n ),\n ],\n **kwargs,\n )\n","sub_path":"day 3 and 4/bootcamp-data-platform/data_platform/glue_catalog/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":6833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"156293011","text":"import requests\nimport json\nfrom datetime import datetime\n\n#ORI API variables\nbase = 'http://api.openraadsinformatie.nl/v0/search/events'\nquery = {\"query\": \"\",\n \"filters\": {\"organization_id\": {\n \"terms\": [\"gemeente-nieuwkoop-nieuwkoop\"]}},\n \"size\": \"10\",\n \"scroll\": \"5m\"}\nr = requests.post(base, data=json.dumps(query))\nevents = r.json()[\"events\"]\ntotal = r.json()[\"meta\"][\"total\"]\n\n#Loop through ORI API\nwhile len(events) < total:\n # query[\"scroll_id\"] = r.json()[\"meta\"][\"scroll\"]\n r = requests.post(base, data=json.dumps({\"scroll_id\": r.json()[\"meta\"][\"scroll\"], \"scroll\": \"1m\"}))\n if \"events\" not in r.json():\n break\n events += r.json()[\"events\"]\n print(len(events))\n\n#Get data in right format\nori_data=[]\nfor event in events:\n if 'sources' in event:\n masterid=event['id']\n try:place=event['organization']['id']\n except:place=event['meta']['collection']\n try:date=event['start_date']\n except:date=event['meta']['processing_started']\n date=datetime.date(datetime.strptime(date[:19], '%Y-%m-%dT%H:%M:%S')).strftime('%d-%m-%Y')\n author='unknown'\n if event['classification']=='Moties':\n localid=masterid\n document=event['sources'][0]['description']\n try:summary=event['sources'][0]['note']\n except:summary=event['sources'][0]['notes']\n ori_data.append({'id':localid,\n 'document':document,\n 'summary':summary,\n 'masterID':masterid,\n 'place':place,\n 'date':date,\n 'author':author})\n else:\n for source in event['sources']:\n localid=source['url']\n document=source['description']\n try:summary=source['note']\n except:summary=source['notes']\n ori_data.append({'id':localid,\n 'document':document,\n 'summary':summary,\n 'masterID':masterid,\n 'place':place,\n 'date':date,\n 'author':author})\n\ndef replacemonth(string):\n for r in ((\"januari\", \"January\"),\n (\"februari\", \"February\"),\n (\"maart\", \"March\"),\n (\"april\", \"April\"),\n (\"mei\", \"May\"),\n (\"juni\", \"June\"),\n (\"juli\", \"July\"),\n (\"augustus\", \"August\"),\n (\"september\", \"September\"),\n (\"oktober\", \"October\"),\n (\"november\", \"November\"),\n (\"december\", \"December\")):\n string = string.replace(*r)\n return string\n\n#import tks data\nwith open ('TKS.json', 'rb') as file:\n tkv_events = json.load(file)\n\n#get data in right format\ntkv_data=[]\nfor event in tkv_events:\n if type(event['Bestanden']) == str:\n document=event['Bestanden']\n elif type(event['Bestanden']) == list:\n if len(event['Bestanden'])==1:\n document=event['Bestanden'][0]\n else:\n document=''\n for doc in event['Bestanden']:\n document+=doc\n tkv_data.append({'id':event['id'],\n 'document':document,\n 'summary':event['Titel'],\n 'masterID':event['id'],\n 'place':'TK',\n 'date':datetime.date(datetime.strptime(replacemonth(event['Publicatiedatum']), '%d %B %Y')).strftime('%d-%m-%Y'),\n 'author':event['Indiener']})\n\ntotal_data=[]\ntotal_data.extend(ori_data)\ntotal_data.extend(tkv_data)\n\n#save data\nwith open(\"total.json\", \"w\") as f:\n json.dump(total_data, f)\n","sub_path":"get_data_nieuwkoop.py","file_name":"get_data_nieuwkoop.py","file_ext":"py","file_size_in_byte":3762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"37596506","text":"from clpsych.data import read_indices\n\nimport pandas as pd\nimport argparse\nimport random\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('-d', dest='dataset', default='**/**/TRAIN.txt')\n parser.add_argument('-n', dest='n', type=int, default=1000)\n args = parser.parse_args()\n\n train_indices = read_indices(args.dataset)\n # randomly sample n indices\n sample = random.sample(train_indices.user_id, k=args.n)\n # save it to a text file\n sample_df = pd.DataFrame(sample, columns=['user_id'])\n sample_df['user_id'].to_csv('SAMPLE.txt', header=False, index=False)\n\n positive_count = len(sample_df[sample_df['user_id'] > 0])\n controls_count = len(sample_df[sample_df['user_id'] < 0])\n\n print('Sampled {0} elements, with:'.format(args.n))\n print('\\t{0} from the positive class, and'.format(positive_count))\n print('\\t{0} from the controls'.format(controls_count))\n","sub_path":"scripts/sample.py","file_name":"sample.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"109424878","text":"from neorl import MFO\r\n\r\n#Define the fitness function\r\ndef FIT(individual):\r\n \"\"\"Sphere test objective function.\r\n F(x) = sum_{i=1}^d xi^2\r\n d=1,2,3,...\r\n Range: [-100,100]\r\n Minima: 0\r\n \"\"\"\r\n y=sum(x**2 for x in individual)\r\n return y\r\n\r\n#Setup the parameter space (d=5)\r\nnx=5\r\nBOUNDS={}\r\nfor i in range(1,nx+1):\r\n BOUNDS['x'+str(i)]=['float', -100, 100]\r\n\r\n#setup and evolute MFO\r\nmfo=MFO(mode='min', bounds=BOUNDS, fit=FIT, nmoths=50, ncores=1, seed=1)\r\nx_best, y_best, mfo_hist=mfo.evolute(ngen=200, verbose=1)","sub_path":"examples/ex_mfo.py","file_name":"ex_mfo.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"649532038","text":"#!/usr/bin/python3\n\nimport requests\nimport os.path\nfrom datetime import datetime\nimport csv\nimport argparse\n\n# Settings\nsdir = os.path.expanduser(\"~\") + \"/.config/vitahelper/\"\nsheeturl = \"https://docs.google.com/spreadsheets/d/18PTwQP7mlwZH1smpycHsxbEwpJnT8IwFP7YZWQT7ZSs\"\ngid = {'game': 1180017671, 'dlc': 743196745, 'psm': 1652602430, 'update': 50164469, 'public': 139786558}\n\n\n# cli argument processing\nparser = argparse.ArgumentParser(description='cli-tool for NoPayStation')\ngroup = parser.add_mutually_exclusive_group(required=True)\ngroup.add_argument('-t', '--titleid', type=str, dest=\"titleid\", \n help=\"search by TITLEID\")\ngroup.add_argument('-n', '--name', type=str, dest=\"name\", \n help=\"search by Name\")\ngroup.add_argument('-p', '--pkg', type=str, dest=\"pkgfile\", \n help=\"search by .pkg filename\")\nparser.add_argument('--license-only', dest=\"licenseonly\", action='store_true', \n help=\"prints only the zRIF/klicensee -String(for CLI usage)\")\nparser.add_argument('--update', action='store_true', \n help=\"force update of data files from GDrive\")\nparser.add_argument('--region', type=str, \n help=\"filter results by Region (EU, US, JP)\")\nargs = parser.parse_args()\n\n### main Script ###\n\n# check for file existence and mod-date\ntoday = datetime.today()\nfor fn, gid in gid.items():\n # check if file needs to be updated\n fileh = sdir + fn + \".csv\"\n url = sheeturl + \"/export?format=csv&gid=\" + str(gid)\n update = False\n if os.path.exists(fileh):\n file_mod = datetime.fromtimestamp(os.path.getmtime(fileh))\n timespan = today - file_mod\n if timespan.days > 7:\n update=True\n print(\"File \\\"\" + fn + \".csv\\\" older than 7 days!\")\n else:\n update=True\n print(\"File \\\"\" + fn + \".csv\\\" doesn't exist!\")\n\n # download file(s)\n if update == True or args.update == True:\n print(\"Downloading File: \" + url)\n r = requests.get(url, stream=True)\n if r.status_code == 200:\n with open(fileh, \"wb\") as f:\n for chunk in r:\n f.write(chunk)\n\n# prints info about current row (iterator below)\ndef print_info(row):\n # region check\n if args.region:\n if row['Region'].lower() != args.region.lower():\n return\n # print only license?\n if args.licenseonly == True:\n print(row['zRIF / klicensee'])\n return\n # print all Info\n print(\"TITLEID:\\t\\t\" + row['Title ID'])\n print(\"NAME/REGION:\\t\\t\" + row['Name'] + \" (\" + row['Region'] + \")\")\n print(\"ZEUS:\\t\\t\\t\" + row['PKG direct link'])\n print(\"PKG:\\t\\t\\t\" + row['PKG direct link'].rsplit('/', 1)[-1])\n print(\"zRIF / klicensee:\\t\" + row['zRIF / klicensee'])\n\n# read csv\nwith open(sdir + \"game.csv\", newline='') as gamecsv:\n gamereader = csv.DictReader(gamecsv, delimiter=',')\n for row in gamereader:\n # return row(s) of the specified TitleID\n if args.titleid:\n if row['Title ID'] == args.titleid:\n print_info(row)\n elif args.name:\n name = args.name.lower()\n if name in row['Name'].lower():\n print_info(row)\n elif args.pkgfile:\n pkg_file = row['PKG direct link'].rsplit('/', 1)[-1]\n if pkg_file == args.pkgfile:\n print_info(row)\n","sub_path":"Vita/NoPayStationHelper/npshlp.py","file_name":"npshlp.py","file_ext":"py","file_size_in_byte":3326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"163846900","text":"#! -*- encoding: utf8 -*-\n\nimport numpy as np\nfrom sc.feature_extractor import FeatureExtractor\nimport logging\nimport os\nfrom sc.model import ModelVersionFeatureConfig\nfrom sklearn.externals import joblib\n\nlogger = logging.getLogger('server')\n\nclass Classifier(object):\n \"\"\"\n Basic Signal Classifier\n \"\"\"\n NORMAL_TYPE = 0\n FLAW_TYPE_MISSING_PEAK = 1\n FLAW_TYPE_UNSYMMENTRIC_SHOULDER = 2\n FLAW_TYPE_HEIGHT_VARIANCE = 3\n FLAW_TYPE_WIDTH_VARIANCE = 4\n FLAW_TYPE_SPEED_INVALID = 5\n FLAW_TYPE_TWO_MANY_DOWN_PEAKS = 6\n ERR_RET_PARAM = dict({'stat': 1, 'reason': 0, 'speed': 0})\n\n def __init__(self, model_path='', model_version=''):\n self.featureExtractor = FeatureExtractor()\n self.features = dict()\n self.wanted_features = []\n\n if model_version != '' and model_version in ModelVersionFeatureConfig:\n self.wanted_features = ModelVersionFeatureConfig[model_version]['features']\n model_path = os.path.sep.join([os.path.dirname(os.path.abspath(__file__)), '..', 'models', ModelVersionFeatureConfig[model_version]['path'],'model.pkl'])\n\n if model_path == 'train' or model_path == None:\n return\n\n if model_path != '':\n self.model = joblib.load(model_path)\n else:\n self.model = joblib.load(os.path.abspath('..') + os.sep + \"models\" + os.sep + \"model.pkl\")\n\n def normalize_signals(self, signals):\n \"\"\"\n N(0, 1) normalization of input signals\n \"\"\"\n mean = np.mean(signals)\n delta = np.std(signals)\n return (signals - mean) / delta\n\n def predict(self, signals, params, request_params = dict()):\n \"\"\"\n return 0 if signal is normal, otherwise -1\n \"\"\"\n if 'mode' in request_params.keys() and request_params['mode'] == 'speed':\n return self.predictSpeedOnly(signals, params, request_params)\n \n return self.predictWithModel(signals, params, request_params)\n\n def predictSpeedOnly(self, raw_signals, params, request_params = dict()):\n \"\"\"\n predict signals' speed only\n \"\"\"\n feature_masks = []\n f = self.get_speed_features(raw_signals, params)\n self.upwardsEdges = f['up_edges']\n self.downwardsEdges = f['down_edges']\n \n retParam = dict()\n retParam['stat'] = 0\n retParam['reason'] = -1\n retParam['speed'] = 0\n retParam['speedResult'] = 0\n retParam['waveScore'] = 0\n retParam['waveResult'] = 0\n \n # calculate speed\n samplerate = request_params.get('samplerate', [params['SAMPLING_DT']])[0]\n retParam['speed'] = self.calcSpeed(raw_signals, params, float(samplerate))\n\n #judge speeds\n speed_lower_bound = int(request_params.get('speed_lower_bound', [params['SPEED_LOWER_BOUND']])[0])\n speed_upper_bound = int(request_params.get('speed_upper_bound', [params['SPEED_UPPER_BOUND']])[0])\n if retParam['speed'] < speed_lower_bound or retParam['speed'] > speed_upper_bound:\n retParam['speedResult']= 1\n \n if retParam['speedResult'] == 1:\n retParam['stat'] = 1\n retParam['reason'] = Classifier.FLAW_TYPE_SPEED_INVALID\n return retParam\n\n def predictWithModel(self, raw_signals, params, request_params = dict()):\n feature_masks = self.wanted_features if len(self.wanted_features) > 0 else None\n f = self.get_features(raw_signals[0:1024], params, request_params, feature_masks=feature_masks)\n feature = self.get_feature_vec(f)\n result = int(self.model.predict(feature)[0])\n score = self.model.predict_proba(feature)\n \n retParam = dict()\n retParam['stat'] = result\n retParam['reason'] = -1\n retParam['speed'] = 0\n retParam['speedResult'] = 0\n retParam['waveResult'] = result\n retParam['waveScore'] = score[0][1]\n\n speed_params = self.predictSpeedOnly(raw_signals, params, request_params)\n retParam['speed'] = speed_params['speed']\n retParam['speedResult'] = speed_params['speedResult']\n # calculate speed\n # samplerate = request_params.get('samplerate', [params['SAMPLING_DT']])[0]\n # #samplerate = request_params.get('samplerate', params['SAMPLING_DT']) \n # retParam['speed'] = self.calcSpeed(raw_signals, params, float(samplerate))\n\n # #judge speeds\n # speed_lower_bound = int(request_params.get('speed_lower_bound', [params['SPEED_LOWER_BOUND']])[0])\n # speed_upper_bound = int(request_params.get('speed_upper_bound', [params['SPEED_UPPER_BOUND']])[0])\n # if retParam['speed'] < speed_lower_bound or retParam['speed'] > speed_upper_bound:\n # retParam['speedResult']= 1\n # \n if result == 0 and retParam['speedResult'] == 1:\n retParam['stat'] = 1\n retParam['reason'] = Classifier.FLAW_TYPE_SPEED_INVALID\n return retParam\n \n def get_feature_vec(self, features):\n if len(self.wanted_features) > 0:\n feature_list = sorted(self.wanted_features)\n else:\n feature_list = sorted(self.get_feature_list())\n fea_vec = np.zeros(len(feature_list))\n for i in range(len(feature_list)):\n fea_vec[i] = features[feature_list[i]]\n return fea_vec.reshape(1, -1)\n\n def get_feature_list(self):\n \"\"\"\n predefined feature lists, order is sensitive\n \"\"\"\n return ['peaks_num', 'up_edges_num', 'down_edges_num', 'down_peaks_num', 'peak_edge_ratio', 'down_peak_edge_ratio', 'edge_diff_10', 'edge_diff_20', 'edge_diff_50', 'width_diff_10', 'negative_peak_num']\n \n def get_speed_features(self, raw_signals, params, enable_normalization=True):\n \"\"\"\n shortened feature extractions\n \"\"\"\n signals_length = len(raw_signals)\n feature_dict = dict()\n if enable_normalization:\n signals = self.normalize_signals(raw_signals)\n else:\n signals = raw_signals\n feature_dict['normalize_signals'] = signals\n feature_dict['up_edges'] = self.getUpEdges_(signals, params)\n feature_dict['down_edges'] = self.getDownEdges_(signals, params)\n return feature_dict\n\n def get_features(self, raw_signals, params, enable_normalization=True, request_params=dict(), feature_masks=None):\n \"\"\"\n calculate features dicts\n \"\"\"\n raw_signals = raw_signals[0:1024]\n signal_length = len(raw_signals)\n feature_dict = dict()\n if feature_masks is not None:\n feature_masks = [].extend(set(feature_masks))\n if 0 == signal_length:\n return feature_dict\n \n if enable_normalization:\n signals = self.normalize_signals(raw_signals[0:1024])\n else:\n signals = raw_signals[0:1024]\n # tracing & debuging features, for visualizations\n feature_dict['normalized_signals'] = signals\n # get peaks / edges, basic features:\n feature_dict['peaks'] = self.getPeakLoc_(signals, params)\n feature_dict['down_peaks'] = self.getDownPeakLoc_(signals, params)\n feature_dict['negative_peak_num'] = self.getNegativePeakNum_(raw_signals, params)\n feature_dict['max_down_peak_point'] = self.getExtremeDownPeakVal_(raw_signals, params)\n feature_dict['up_edges'] = self.getUpEdges_(signals, params)\n feature_dict['down_edges'] = self.getDownEdges_(signals, params)\n\n # combined features\n if not feature_masks or 'peaks_num' in feature_masks:\n feature_dict['peaks_num'] = len(feature_dict['peaks'])\n if not feature_masks or 'down_peaks_num' in feature_masks:\n feature_dict['down_peaks_num'] = len(feature_dict['down_peaks'])\n if not feature_masks or 'up_edges_num' in feature_masks:\n feature_dict['up_edges_num'] = len(feature_dict['up_edges'])\n if not feature_masks or 'down_edges_num' in feature_masks:\n feature_dict['down_edges_num'] = len(feature_dict['down_edges'])\n if (not feature_masks or ['up_edges_num', 'down_edges_num'] <= feature_masks) and feature_dict['up_edges_num'] + feature_dict['down_edges_num'] != 0:\n if not feature_masks or ['peak_edge_ratio', 'peaks_num'] <= feature_masks:\n feature_dict['peak_edge_ratio'] = feature_dict['peaks_num'] * 1.0 / ((feature_dict['up_edges_num'] + feature_dict['down_edges_num']) / 2.0)\n if not feature_masks or ['down_peak_edge_ratio', 'down_peaks_num'] <= feature_masks:\n feature_dict['down_peak_edge_ratio'] = feature_dict['down_peaks_num'] * 1.0 / ((feature_dict['up_edges_num'] + feature_dict['down_edges_num']) / 2.0)\n else:\n feature_dict['peak_edge_ratio'] = 0.0\n feature_dict['down_peak_edge_ratio'] = 0.0\n\n if not feature_masks or ['up_edges', 'up_edge_height'] <= feature_masks:\n feature_dict['up_edge_height'] = self.getEdgeHeight_(signals, feature_dict['up_edges'])\n if not feature_masks or ['down_edge_height', 'down_edges'] <= feature_masks:\n feature_dict['down_edge_height'] = self.getEdgeHeight_(signals, feature_dict['down_edges'])\n if not feature_masks or ['up_edges', 'down_edges'] <= feature_masks:\n feature_dict['paired_edges'] = self.getPairedEdges_(params, feature_dict['up_edges'], feature_dict['down_edges'])\n # 上下沿对比数据\n feature_dict['paired_edge_height'] = self.getPairedEdgeHeight_(signals, feature_dict['paired_edges'])\n feature_dict['paired_edge_height_diff'] = sorted(self.getPairedEdgeDifference_(feature_dict['paired_edge_height']), reverse=True)\n\n # 下拉及无头等缺陷的序列周期性检测\n feature_dict['cyclic_nopeak_seq'] = self.unitMaskGenerate(feature_dict['peaks'], feature_dict['paired_edges'], flip=True)\n feature_dict['cyclic_downpeak_seq'] = self.unitMaskGenerate(feature_dict['down_peaks'], feature_dict['paired_edges'])\n feature_dict['cyclic_intense_nopeak'] = self.cyclicIntense(feature_dict['cyclic_nopeak_seq'], params['PHRASE_NUM'])\n feature_dict['cyclic_intense_downpeak'] = self.cyclicIntense(feature_dict['cyclic_downpeak_seq'], params['PHRASE_NUM'])\n\n # 获取波形单元间隔宽度数据\n feature_dict['unit_interviene_length'] = self.getIntervieneLength_(feature_dict['paired_edges'])\n feature_dict['unit_interviene_length_diff'] = self.getIntervieneLengthDifference_(feature_dict['unit_interviene_length'])\n if len(feature_dict['unit_interviene_length_diff']) > 0:\n feature_dict['inter_diff_mean'] = np.mean(feature_dict['unit_interviene_length_diff'])\n feature_dict['inter_diff_delta'] = np.std(feature_dict['unit_interviene_length_diff'])\n else:\n feature_dict['inter_diff_mean'] = 0\n feature_dict['inter_diff_delta'] = 0\n\n # 获取波形单元间隔底部的不对称性角度\n feature_dict['unit_interviene_skewness'] = self.getIntervieneSkewness_(signals, feature_dict['paired_edges'])\n if len(feature_dict['unit_interviene_skewness']) > 0:\n feature_dict['skewness_mean'] = np.mean(feature_dict['unit_interviene_skewness'])\n feature_dict['skewness_delta'] = np.std(feature_dict['unit_interviene_skewness'])\n else:\n feature_dict['skewness_mean'] = 0\n feature_dict['skewness_delta'] = 0\n\n # 获取上下沿边的长度diff分位数据\n if len(feature_dict['paired_edge_height_diff']) != 0:\n if not feature_masks or 'edge_diff_10' in feature_masks:\n feature_dict['edge_diff_10'] = np.percentile(feature_dict['paired_edge_height_diff'], 90)\n if not feature_masks or 'edge_diff_20' in feature_masks:\n feature_dict['edge_diff_20'] = np.percentile(feature_dict['paired_edge_height_diff'], 80)\n if not feature_masks or 'edge_diff_30' in feature_masks:\n feature_dict['edge_diff_30'] = np.percentile(feature_dict['paired_edge_height_diff'], 70)\n if not feature_masks or 'edge_diff_50' in feature_masks:\n feature_dict['edge_diff_50'] = np.percentile(feature_dict['paired_edge_height_diff'], 50)\n else:\n feature_dict['edge_diff_10'] = 100\n feature_dict['edge_diff_20'] = 100\n feature_dict['edge_diff_30'] = 100\n feature_dict['edge_diff_50'] = 100\n \n\n # 上下边缘对比数据\n feature_dict['paired_edge_width'] = self.getPairedEdgeUpperBottomWidth_(signals, feature_dict['paired_edges'])\n feature_dict['paired_edge_width_diff'] = sorted(self.getPairedWidthDifference_(feature_dict['paired_edge_width']), reverse=True)\n\n if len(feature_dict['paired_edge_width_diff']) != 0:\n if not feature_masks or 'width_diff_10' in feature_masks:\n feature_dict['width_diff_10'] = np.percentile(feature_dict['paired_edge_width_diff'], 90)\n if not feature_masks or 'width_diff_20' in feature_masks:\n feature_dict['width_diff_20'] = np.percentile(feature_dict['paired_edge_width_diff'], 80)\n if not feature_masks or 'width_diff_30' in feature_masks:\n feature_dict['width_diff_30'] = np.percentile(feature_dict['paired_edge_width_diff'], 70)\n if not feature_masks or 'width_diff_50' in feature_masks:\n feature_dict['width_diff_50'] = np.percentile(feature_dict['paired_edge_width_diff'], 50)\n else:\n feature_dict['width_diff_10'] = 100\n feature_dict['width_diff_20'] = 100\n feature_dict['width_diff_30'] = 100\n feature_dict['width_diff_50'] = 100\n\n return feature_dict\n\n def predictWithReason(self, signals, params, request_params = dict()):\n \"\"\"\n return a tupple consists of status and reasons\n \"\"\"\n signal_length = len(signals)\n \n if signal_length == 0:\n return Classifier.ERR_RET_PARAM\n\n # get all peak points\n self.peakLocations = self.getPeakLoc_(signals, params)\n # get all down-peak points\n self.downPeakLocations = self.getDownPeakLoc_(signals, params)\n # get all upwards edges\n self.downwardsEdges = self.getDownEdges_(signals, params)\n # get all downwards edges\n self.upwardsEdges = self.getUpEdges_(signals, params)\n\n # start analysis\n (result, reason) = self.signalDiagnosis(signals, params)\n \n retParam = dict()\n retParam['stat'] = result\n retParam['reason'] = reason\n\n if result != 0:\n retParam['speed'] = 0\n else:\n # calculate speed\n #logger.debug('request_params: %s' % str(request_params))\n samplerate = request_params.get('samplerate', [params['SAMPLING_DT']])[0]\n #samplerate = request_params.get('samplerate', params['SAMPLING_DT']) \n retParam['speed'] = self.calcSpeed(signals, params, float(samplerate))\n if retParam['speed'] < 12300 or retParam['speed'] > 15500:\n retParam['stat']= 1\n retParam['reason'] = Classifier.FLAW_TYPE_SPEED_INVALID\n\n if request_params.get('debug', False):\n retParam['debug'] = dict()\n # adding noarmalized information\n retParam['debug']['normalized_signal'] = signals\n retParam['debug']['peaks'] = self.peakLocations\n retParam['debug']['up_edges'] = self.upwardsEdges\n retParam['debug']['down_edges'] = self.downwardsEdges\n retParam['debug']['down_peaks'] = self.downPeakLocations\n retParam['debug']['shoulder_height'] = self.shoulder_mean_heights\n #retParam['debug']['height_delta'] = self.edge_deltas\n return retParam\n\n def calcSpeed(self, signals, params, sampling_dt):\n \"\"\"\n round per minute\n dt * edge_pairs\n \"\"\"\n #sampling_dt = params['SAMPLING_DT'] # second\n total_secs = len(signals) * sampling_dt\n cycle_num = (len(self.upwardsEdges) + len(self.downwardsEdges)) / 2.0 + 1\n rpm = cycle_num / 4.0 / total_secs * 60.0\n if total_secs == 0:\n rpm = 0\n #print \"total_time:%.7lf cycle_num:%d\" % (total_secs, cycle_num)\n return rpm\n\n #### get signal features ####\n def getPeakLoc_(self, signals, params):\n \"\"\"\n return all peak pointer location within signals\n \"\"\"\n _peak_window_size = params['PEAK_WINDOW_SIZE']\n _peak_threshold = params['PEAK_THRESHOLD']\n return self.featureExtractor.peakPointers(signals, _peak_window_size, _peak_threshold)\n\n def getNegativePeakNum_(self, raw_signals, params):\n \"\"\"\n return total negative downpeak numbers\n NOTICE: input signals should be raw signals\n \"\"\"\n return self.featureExtractor.outlierPointNum(raw_signals, 0, lambda x, y: x <= y)\n\n def getExtremeDownPeakVal_(self, raw_signals, params):\n \"\"\"\n return extreme down peak values\n \"\"\"\n return self.featureExtractor.valley(raw_signals)\n\n def getDownPeakLoc_(self, signals, params):\n \"\"\"\n return all extreme down-peak locations\n \"\"\"\n _bottom_window_size = params['DOWN_PEAK_WINDOW_SIZE']\n _bottom_threshold = params['DOWN_PEAK_THESHOLD']\n return self.featureExtractor.peakPointers(signals, _bottom_window_size, _bottom_threshold, True)\n\n def getUpEdges_(self, signals, params):\n \"\"\"\n return [start, end] for upwards edges\n \"\"\"\n _edge_window_size = params['EDGE_WINDOW_SIZE']\n _edge_threshold_H = params['EDGE_THRESHOLD_HIGH']\n _edge_threshold_L = params['EDGE_THRESHOLD_LOW']\n \n return self.featureExtractor.upwardsEdges(signals, _edge_window_size, _edge_threshold_H)\n\n def getDownEdges_(self, signals, params):\n \"\"\"\n return [start, end] for downwards edges\n \"\"\"\n \n _edge_window_size = params['EDGE_WINDOW_SIZE']\n _edge_threshold_H = params['EDGE_THRESHOLD_HIGH']\n _edge_threshold_L = params['EDGE_THRESHOLD_LOW']\n\n return self.featureExtractor.downwardsEdges(signals, _edge_window_size, _edge_threshold_H)\n\n def getPairedEdgeHeight_(self, signals, up_down_edge_pairs):\n \"\"\"\n get paired edge's height\n \"\"\"\n up_down_height_paired_list = list()\n for (up_idx, down_idx) in up_down_edge_pairs:\n up_height = self.featureExtractor.singleEdgeHeight(signals, up_idx)\n down_height = self.featureExtractor.singleEdgeHeight(signals, down_idx)\n up_down_height_paired_list.append((up_height, down_height))\n return up_down_height_paired_list\n\n def getPairedEdgeUpperBottomWidth_(self, signals, up_down_edge_pairs):\n \"\"\"\n get paired edges's upper/bottom width\n \"\"\"\n up_down_width_paired_list = list()\n for (up_idx, down_idx) in up_down_edge_pairs:\n upper_width = abs(up_idx[1] - down_idx[0]) + 1\n bottom_width = abs(up_idx[0] - down_idx[1]) + 1\n up_down_width_paired_list.append((bottom_width, upper_width))\n return up_down_width_paired_list\n\n def getIntervieneLength_(self, up_down_edge_pairs):\n \"\"\"\n one up & one down edge forms a single unit\n the length between them should have the same size\n \"\"\"\n interviene_length_list = list()\n for i in range(1, len(up_down_edge_pairs)):\n prev_down_idx = up_down_edge_pairs[i - 1][1]\n cur_up_idx = up_down_edge_pairs[i][0]\n interviene_length_list.append(abs(prev_down_idx[1] - cur_up_idx[0]))\n return interviene_length_list\n\n def getIntervieneLengthDifference_(self, inter_length_list):\n \"\"\"\n input is the difference lengths\n the interviene length distribution should be Guassian\n we can use Guassian normalization\n \"\"\"\n differences_ = list()\n for i in range(1, len(inter_length_list)):\n differences_.append(abs(inter_length_list[i - 1] - inter_length_list[i]))\n \n return differences_\n\n def getIntervieneSkewness_(self, signals, up_down_edge_pairs):\n \"\"\"\n Interates through all edges\n \"\"\"\n interviene_skewness = list()\n for i in range(1, len(up_down_edge_pairs)):\n down = up_down_edge_pairs[i - 1][1]\n up = up_down_edge_pairs[i][0]\n bottom1 = min(signals[up[0]], signals[up[1]])\n bottom2 = min(signals[down[0]], signals[down[1]])\n interviene_width = abs(up[0] - down[1]) + 1\n interviene_skewness.append(abs(bottom1 - bottom2) * 1.0 / interviene_width)\n\n # for (up, down) in up_down_edge_pairs:\n # bottom1 = min(signals[up[0]], signals[up[1]])\n # bottom2 = min(signals[down[0]], signals[down[1]])\n # interviene_width = abs(up[1] - down[0]) + 1\n # interviene_skewness.append(abs(bottom1 - bottom2) * 1.0 / interviene_width)\n return interviene_skewness\n\n def getPairedEdgeDifference_(self, up_down_edge_height_paired_list):\n \"\"\"\n given paired height list, scale difference to [0, 1]\n \"\"\"\n up_down_height_diff = list()\n for (up_height, down_height) in up_down_edge_height_paired_list:\n base = max(up_height, down_height)\n diff = abs(up_height - down_height)\n assert(base != 0)\n up_down_height_diff.append(diff / base)\n return up_down_height_diff\n\n def getPairedWidthDifference_(self, up_down_edge_width_paired_list):\n \"\"\"\n given paired width list, scale difference to [0, 1]\n \"\"\"\n up_down_width_diff = list()\n for (up_width, down_width) in up_down_edge_width_paired_list:\n assert(down_width != 0)\n up_down_width_diff.append(abs(up_width - down_width) * 1.0 / down_width)\n return up_down_width_diff\n\n def getPairedEdges_(self, params, up_edges = None, down_edges = None):\n \"\"\"\n group upwards edges & downwards edge list\n \"\"\"\n paired_edges = list()\n up_idx = 0\n down_idx = 0\n upwardsEdges = None\n downwardsEdges = None\n if up_edges != None:\n upwardsEdges = up_edges\n else:\n upwardsEdges = self.upwardsEdges\n\n if down_edges != None:\n downwardsEdges = down_edges\n else:\n downwardsEdges = self.downwardsEdges\n #logger.debug(\"upwardsEdges: %d downwardsEdges: %d\" % (len(self.upwardsEdges), len(self.downwardsEdges)))\n while up_idx < len(upwardsEdges) and down_idx < len(downwardsEdges):\n up = upwardsEdges[up_idx]\n down = downwardsEdges[down_idx]\n #print \"up_idx:%d down_idx:%d up:%s down:%s\" % (up_idx, down_idx, str(up), str(down))\n if up[1] > down[0]:\n down_idx += 1\n continue\n paired_edges.append((up, down))\n up_idx += 1\n down_idx +=1\n return paired_edges\n \n def getEdgeHeight_(self, signals, edge_loc):\n \"\"\"\n caculate edge's absolute height\n \"\"\"\n return self.featureExtractor.edgeHeight(signals, edge_loc)\n\n #### abnormal signal reasoning ####\n def isLackOfPeaks(self, params):\n \"\"\" \n detects whether peak exists or missing\n \"\"\"\n _peak_missing_ratio = params['PEAK_MISSING_RATIO']\n peak_num = len(self.peakLocations)\n up_edge_num = len(self.upwardsEdges)\n downward_edge_num = len(self.downwardsEdges)\n expect_num = (up_edge_num + downward_edge_num) / 2.0\n \n if 0 == peak_num or 0 == up_edge_num or 0 == downward_edge_num or 0 == expect_num:\n return True\n missing_ratio = abs(expect_num - peak_num) * 1.0 / expect_num\n #print \"peak_num:%d up_edge_num:%d downward_edge_num:%d expect_peak_num:%.2lf missing_ratio:%.2lf expect_missing_ratio:%.2f\" % (peak_num, up_edge_num, downward_edge_num, expect_num, missing_ratio, _peak_missing_ratio)\n #print \"peak_num:%d up_edge_num:%d downward_edge_num:%d peaks:%s\" % (peak_num, up_edge_num, downward_edge_num, str(self.peakLocations))\n return missing_ratio >= _peak_missing_ratio\n \n def isTooManyDownPeaks(self, params):\n \"\"\"\n detects normal peaks\n \"\"\"\n _down_peak_appear_ratio = params['DOWN_PEAK_APPEARING_RATIO']\n down_peak_num = len(self.downPeakLocations)\n up_edge_num = len(self.upwardsEdges)\n downward_edge_num = len(self.downwardsEdges)\n if up_edge_num + downward_edge_num == 0:\n return True\n appearing_ratio = down_peak_num / ((up_edge_num + downward_edge_num) / 2.0)\n return appearing_ratio >= _down_peak_appear_ratio\n \n def isShoulderWidthAbnormal(self, params):\n \"\"\" \n detect edge width\n \"\"\"\n _shoulder_symmentric_mean_threshold = params['SHOULDER_SYMMENTRIC_MEAN_THRESHOLD']\n _shoulder_symmentric_variance_threshold = params['SHOULDER_SYMMENTRIC_VARIANCE_THRESHOLD']\n paired_edges = self.getPairedEdges_(params)\n widths = list()\n for (up, down) in paired_edges:\n up_width = abs(up[0] - up[1])\n down_width = abs(down[0] - down[1])\n width_diff = abs(up_width - down_width)\n widths.append(width_diff)\n global_width_mean = np.mean(widths)\n global_width_std = np.std(widths)\n \n #logger.debug(\"width mean: %.2lf width variance: %.2lf\" % (global_width_mean, global_width_std))\n if global_width_mean > _shoulder_symmentric_mean_threshold or global_width_std > _shoulder_symmentric_variance_threshold:\n return True \n return False\n\n def isShoulderHeightAbnormal(self, signals, params):\n \"\"\"\n detect shoulder height variances\n \"\"\"\n _height_variances_error_threshold = params['SHOULDER_HEIGHT_VARIANCE_THRESHOLD']\n self.paired_edges = self.getPairedEdges_(params)\n heights = list()\n for (up, down) in self.paired_edges:\n mean_height = (signals[up[0]] + signals[down[1]]) / 2.0\n heights.append(mean_height)\n #norm_height = self.standardGuassianNormalize(height)\n global_height_mean = np.mean(heights)\n global_height_std = np.std(heights)\n \n self.shoulder_mean_heights = heights\n return global_height_std > _height_variances_error_threshold\n\n def standardGuassianNormalize(self, input_val):\n mean = np.mean(input_val)\n dev = np.std(input_val)\n return (input_val - mean) / dev\n\n def isShoulderNotSymmetric(self, signals, params):\n \"\"\"\n check whether the diff of max(upwardsEdge) - max(downwardsEdge) is in appropriate margin\n \"\"\"\n _unsymmetric_ratio = params['SHOULDER_UNSYMMETRIC_RATIO']\n _unsymmetric_threshold = params['SHOULDER_UNSYMMETRIC_THRESHOLD']\n _unsymmetric_var = params['SHOULDER_UNSYMMETRIC_VAR']\n paired_edges = self.getPairedEdges_(params)\n if len(paired_edges) == 0:\n return True\n invalid_cnt = 0\n edge_deltas = list()\n for (up, down) in paired_edges:\n l_height_idx = np.argmax(up)\n r_height_idx = np.argmax(down)\n delta = abs(signals[up[l_height_idx]] - signals[down[r_height_idx]])\n edge_deltas.append(delta)\n # if delta >= _unsymmetric_threshold:\n # invalid_cnt += 1\n\n #invalid_ratio = invalid_cnt * 1.0 / len(paired_edges)\n self.edge_deltas = edge_deltas\n return np.std(edge_deltas) >= _unsymmetric_var\n \n def signalDiagnosis(self, signals, params):\n \"\"\"\n Rule assembled to classify & recognize signals\n \"\"\"\n isFlawSignal = False\n flawType = Classifier.NORMAL_TYPE\n if self.isLackOfPeaks(params):\n isFlawSignal = True\n flawType = Classifier.FLAW_TYPE_MISSING_PEAK\n if self.isTooManyDownPeaks(params):\n isFlawSignal = True\n flawType = Classifier.FLAW_TYPE_TWO_MANY_DOWN_PEAKS\n if self.isShoulderHeightAbnormal(signals, params):\n isFlawSignal = True\n flawType = Classifier.FLAW_TYPE_HEIGHT_VARIANCE\n # if self.isShoulderNotSymmetric(signals, params):\n # isFlawSignal = True\n # flawType = Classifier.FLAW_TYPE_UNSYMMENTRIC_SHOULDER\n if isFlawSignal:\n result = 1\n else:\n result = 0\n return (result, flawType)\n\n def unitMaskGenerate(self, eventAxis, paired_edges, flip=False):\n \"\"\"\n paired_edges divide signals into units\n foreach unit we will give each signals a label-1 if eventAxis appears\n if flip equals true, we will use 0 label for positive events\n return list of masks\n \"\"\"\n unit_num = len(paired_edges)\n positive_label = 1\n negtive_label = 0\n if flip == True:\n positive_label = 0\n negtive_label = 1\n\n unit_num = len(paired_edges) - 1\n # initialize intial labels\n masks = np.full(unit_num, negtive_label)\n for i in range(0, unit_num):\n left = paired_edges[i][0][0]\n right = paired_edges[i + 1][0][0]\n for j in eventAxis:\n if j >= left and j < right:\n masks[i] = positive_label\n break\n\n return masks.tolist()\n \n def cyclicIntense(self, seqs, interval):\n cyclic_pair = 0\n max_cyclic_pairs = 0\n for i in range(0, interval):\n cyclic_pair = 0\n for j in range(i, len(seqs), interval):\n if seqs[j] > 0:\n cyclic_pair += 1\n max_cyclic_pairs = max(max_cyclic_pairs, cyclic_pair)\n return max_cyclic_pairs\n\n # def cyclicIntense(self, seqs, interval):\n # \"\"\"\n # using auto self-correlation to calculate cyclic informations\n # \"\"\"\n # periodic_pairs = 0.0\n # for i in range(0, len(seqs) - interval):\n # if seqs[i] == 1 and seqs[i + interval] == 1:\n # periodic_pairs += 1\n # #s = pd.Series(seqs)\n # #ret = s.autocorr(lag = interval)\n # #if pd.isna(ret):\n # # ret = 0\n # return periodic_pairs\n","sub_path":"sc/classifier.py","file_name":"classifier.py","file_ext":"py","file_size_in_byte":30489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"278419857","text":"import time\n# モジュールのインポート\nfrom bs4 import BeautifulSoup\nimport requests\nimport os\nimport json\nimport unicodedata\nimport glob\nimport csv\n\nfiles = glob.glob(\"/Users/nakamurasatoru/git/d_hi/website/hi/news/*.html\")\n\nmap = {}\n\nfor file in files:\n print(file)\n\n soup = BeautifulSoup(open(file), \"lxml\")\n\n tables = soup.find_all(class_=\"mtx\")\n\n for table in tables:\n\n trs = table.find_all(\"tr\")\n\n for i in range(len(trs)):\n \n tr = trs[i]\n tds = tr.find_all(\"td\")\n \n date = tr.find(\"th\")\n\n if date == None:\n continue\n\n date = date.text.replace(\"/\", \"-\")\n\n value = tr.find(\"td\")\n\n if value != None:\n value = str(value).replace(\"
\", \"\").strip()\n else:\n value = \"None\"\n\n content = '''---\ndate: {}\nlang: ja\nfeatured: false\ntype: news\n---\n{}\n'''.format(date, value)\n\n vol = file.split(\"/\")[-1].split(\"news\")[0].split(\".\")[0]\n dir = \"../content/news\"\n os.makedirs(dir, exist_ok=True)\n \n name = date + \"-\" + str(len(trs) - i).zfill(4)\n path = dir + \"/\" + name +\".md\"\n with open(path, mode='w') as f:\n f.write(content)","sub_path":"src/201_news.py","file_name":"201_news.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"528416141","text":"from openapi_server.models.original_sample import OriginalSample\nfrom openapi_server.models.original_samples import OriginalSamples\nfrom openapi_server.models.location import Location\nfrom openapi_server.models.attr import Attr\nfrom backbone_server.errors.missing_key_exception import MissingKeyException\n\nfrom backbone_server.location.fetch import LocationFetch\nfrom backbone_server.original_sample.fetch import OriginalSampleFetch\n\nfrom backbone_server.original_sample.edit import OriginalSampleEdit\n\nimport logging\n\nclass OriginalSamplesGetByTaxa():\n\n def __init__(self, conn):\n self._logger = logging.getLogger(__name__)\n self._connection = conn\n\n\n def get(self, taxa_id, start, count):\n with self._connection:\n with self._connection.cursor() as cursor:\n\n stmt = '''SELECT id FROM taxonomies WHERE id = %s'''\n cursor.execute(stmt, (taxa_id, ))\n vtaxa_id = None\n for tid in cursor:\n vtaxa_id = tid\n\n if not vtaxa_id:\n raise MissingKeyException(\"No taxa {}\".format(taxa_id))\n\n fields = '''SELECT os.id, study_name, sampling_event_id,\n days_in_culture, partner_species '''\n query_body = ''' FROM original_samples os\n LEFT JOIN sampling_events se ON se.id = os.sampling_event_id\n LEFT JOIN studies s ON s.id = os.study_id\n LEFT JOIN partner_species_identifiers psi ON psi.id = os.partner_species_id\n JOIN taxonomy_identifiers ti ON ti.partner_species_id = os.partner_species_id\n WHERE ti.taxonomy_id = %s'''\n args = (taxa_id,)\n\n count_args = args\n count_query = 'SELECT COUNT(os.id) ' + query_body\n\n query_body = query_body + ''' ORDER BY doc, study_name, os.id'''\n\n if not (start is None and count is None):\n query_body = query_body + ' LIMIT %s OFFSET %s'\n args = args + (count, start)\n\n original_samples = OriginalSamples(original_samples=[], count=0)\n\n stmt = fields + query_body\n\n cursor.execute(stmt, args)\n\n original_samples.original_samples, original_samples.sampling_events = OriginalSampleFetch.load_original_samples(cursor, True)\n\n if not (start is None and count is None):\n cursor.execute(count_query, count_args)\n original_samples.count = cursor.fetchone()[0]\n else:\n original_samples.count = len(original_samples.original_samples)\n\n original_samples.attr_types = []\n\n col_query = '''select distinct attr_type from original_sample_attrs sea\n JOIN attrs a ON a.id=sea.attr_id\n JOIN original_samples os ON os.id = sea.original_sample_id\n LEFT JOIN taxonomy_identifiers ti ON ti.partner_species_id = os.partner_species_id\n WHERE ti.taxonomy_id = %s'''\n\n cursor.execute(col_query, (taxa_id,))\n for (attr_type,) in cursor:\n original_samples.attr_types.append(attr_type)\n\n\n return original_samples\n","sub_path":"server/backbone_server/original_sample/get_by_taxa.py","file_name":"get_by_taxa.py","file_ext":"py","file_size_in_byte":3282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"165296150","text":"fruit = []\r\nnumber = []\r\nwith open('fruit_inventory.txt','r') as f:\r\n for lines in f:\r\n line = lines.split()\r\n fruit_list = line[0]\r\n stock_level = line[1]\r\n fruit.append(fruit_list)\r\n fruit.sort()\r\n number.append(stock_level)\r\n print('fruit = ',fruit)\r\n print('number = ',number)\r\n f.close()\r\n\r\n","sub_path":"Labs/week07/lab07_file04.py","file_name":"lab07_file04.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"455530296","text":"from json import load, loads\n\n\nMARKER_MAP = {\n \"{\": \"}\",\n \"[\": \"]\"\n}\n\n\ndef get_tests(test_path):\n inputs = {}\n for selector_path in test_path.visit(\"*.selector\"):\n input_path = selector_path.new(\n purebasename=selector_path.purebasename.split(\"_\")[0],\n ext=\"json\"\n )\n\n output_path = selector_path.new(ext=\"output\")\n\n if input_path not in inputs:\n with input_path.open(\"r\") as f:\n inputs[input_path] = load(f)\n\n with selector_path.open(\"r\") as selector_f:\n with output_path.open(\"r\") as output_f:\n yield (\n selector_f.read().strip(),\n inputs[input_path],\n read_output(output_f),\n selector_path.purebasename,\n )\n\n\ndef parse_output(output):\n marker = None\n collected = []\n collecting = \"\"\n\n for line in output.split(\"\\n\"):\n if not line:\n continue\n\n # int value?\n try:\n collected.append(int(line))\n continue\n except ValueError:\n pass\n\n # string\n if line[0] == \"\\\"\":\n collected.append(loads(line))\n continue\n\n # closing object or array\n if line[0] == marker:\n collecting += line\n collected.append(loads(collecting))\n collecting = \"\"\n marker = None\n continue\n\n # opening object or array\n if line[0] in \"[{\":\n marker = MARKER_MAP[line[0]]\n collecting += line\n continue\n\n # object or array body\n if marker:\n collecting += line\n continue\n\n # anything else\n collected.append(line)\n\n return collected\n\n\ndef items_equal(l1, l2):\n \"\"\"assert that two lists and their items are equal\n\n Taken from: http://stackoverflow.com/questions/12813633\n \"\"\"\n\n return len(l1) == len(l2) and sorted(l1) == sorted(l2)\n\n\ndef read_output(output_f):\n output = output_f.read().strip()\n\n try:\n output = loads(output)\n return output\n except ValueError:\n return parse_output(output)\n","sub_path":"tests/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"509814878","text":"# Description:\n# Given a reference of a node in a connected undirected graph.\n# Return a deep copy (clone) of the graph.\n# Each node in the graph contains a val (int) and a list (List[Node]) of its neighbors.\n# Constraints:\n# 1 <= Node.val <= 100\n# Node.val is unique for each node.\n# Number of Nodes will not exceed 100.\n# There is no repeated edges and no self-loops in the graph.\n# The Graph is connected and all nodes can be visited starting from the given node.\n\nfrom typing import List\n\n# Definition for a Node.\nclass Node:\n def __init__(self, val = 0, neighbors = []):\n self.val = val\n self.neighbors = neighbors\n\n# Main Code\nclass Solution:\n\tdef cloneGraph(self, node: Node) -> Node:\n\n\t\t# dictionary to store created nodes\n\t\tcurrGraph = {}\n\n\t\t# helper function to iterate through nodes and create nodes\n\t\tdef nodeBuild(node, currGraph):\n\t\t\t# check for empty graph or no neighbors\n\t\t\tif(node == None):\n\t\t\t\treturn None\n\t\t\t# check for 1-node graph\n\t\t\tif(node.neighbors == []):\n\t\t\t\treturn Node(node.val)\n\n\t\t\t# otherwise, go through neighbors DFS\n\t\t\tnewNode = Node(node.val)\n\t\t\tcurrGraph[node.val] = newNode\n\n\t\t\tfor neighbor in node.neighbors:\n\t\t\t\tif(neighbor.val not in currGraph):\n\t\t\t\t\tnewerNode = nodeBuild(neighbor, currGraph)\n\t\t\t\tnewNode.neighbors.append(currGraph[neighbor.val])\n\n\t\t\treturn newNode\n\n\t\toutputGraph = nodeBuild(node, currGraph)\n\t\treturn outputGraph\n\n","sub_path":"Graphs/CloneGraph.py","file_name":"CloneGraph.py","file_ext":"py","file_size_in_byte":1390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"270419678","text":"# -*- coding: UTF-8 -*-\n\"\"\"PyPoll Homework Challenge Solution.\"\"\"\n\n# Add our dependencies.\nimport csv\nimport os\n# Add a variable to load a file from a path.\nfile_to_load = os.path.join(\"Resources\", \"election_results.csv\")\n# Add a variable to save the file to a path.\nfile_to_save = os.path.join(\"Analysis\", \"election_results.txt\")\n\n# Initialize a total vote counter.\ntotal_votes = 0\n\n# Candidate Options and candidate votes.\ncandidate_options = []\ncandidate_votes = {}\n\n# 1: Create a county list and county votes dictionary.\ncounty_list =[]\ncounty_votes = {}\n\n# Track the winning candidate, vote count and percentage\nwinning_candidate = \"\"\nwinning_count = 0\nwinning_percentage = 0\n\n# 2: Track the largest county and county voter turnout.\nlargest_county = ''\ncounty_voter_turnout = 0\n#2.2 Tracks name of county with most votes, vote count for that county, and percentage of votes for that county\nc_w_most_votes = \"\"\nc_most_votes_count = 0\nc_votes_percentage = 0\n\n# Duplicate Checker Array (Will declare below in for loop)\nvoter_id_list = []\nvoter_id_dict = dict()\ndup_output = dict()\n\n\n# Read the csv and convert it into a list of dictionaries\nwith open(file_to_load) as election_data:\n reader = csv.reader(election_data)\n\n # Read the header\n header = next(reader)\n\n # For each row in the CSV file.\n for row in reader:\n #Duplicate voter ID detector\n # Create list of voter ids\n\n # Add to the total vote count\n total_votes = total_votes + 1\n # Get the candidate name from each row.\n candidate_name = row[2]\n\n # 3: Extract the\n # county name from each row.\n county_name = row[1]\n\n # Get the voter ID from each Row\n \n # If the candidate does not match any existing candidate add it to\n # the candidate list\n if candidate_name not in candidate_options:\n\n # Add the candidate name to the candidate list.\n candidate_options.append(candidate_name)\n\n # And begin tracking that candidate's voter count.\n candidate_votes[candidate_name] = 0\n\n # Add a vote to that candidate's count\n candidate_votes[candidate_name] += 1\n\n # 4a: Write an if statement that checks that the\n # county does not match any existing county in the county list.\n if county_name not in county_list: \n # 4b: Add the existing county to the list of counties.\n county_list.append(county_name)\n\n # 4c: Begin tracking the county's vote count.\n county_votes[county_name] = 0\n\n # 5: Add a vote to that county's vote count.\n county_votes[county_name] += 1\n \n\n \n \n\n# Save the results to our text file.\nwith open(file_to_save, \"w\") as txt_file:\n\n # Print the final vote count (to terminal)\n election_results = (\n f\"\\nElection Results\\n\"\n f\"-------------------------\\n\"\n f\"Total Votes: {total_votes:,}\\n\"\n f\"-------------------------\\n\\n\"\n f\"County Votes:\\n\")\n print(election_results, end=\"\")\n\n txt_file.write(election_results)\n\n # 6a: Write a for loop to get the county from the county dictionary.\n for county_name in county_votes:\n # 6b: Retrieve the county vote count.\n c_votes = county_votes.get(county_name)\n # 6c: Calculate the percentage of votes for the county.\n c_vote_percentage = (float(c_votes)/(float(total_votes)))*100\n # 6d: Print the county results to the terminal.\n county_results = (\n f'{county_name}: {c_vote_percentage:.1f}% ({c_votes:,} votes)\\n'\n )\n print(county_results)\n # 6e: Save the county votes to a text file.\n txt_file.write(county_results)\n # 6f: Write an if statement to determine the winning county and get its vote count.\n if c_votes > c_most_votes_count:\n c_most_votes_count = c_votes\n c_w_most_votes = county_name\n\n #7: Print the county with the largest turnout to the terminal.\n print(f\"The county with the most votes is {c_w_most_votes}.\\n\")\n\n #8: Save the county with the largest turnout to a text file.\n txt_file.write(\n f\"\\n-------------------------\\n\"\n f\"Largest County Turnout: {c_w_most_votes}\\n\"\n f\"-------------------------\\n\"\n )\n print(\n f\"\\n-------------------------\\n\"\n f'Candidate Results\\n'\n f\"-------------------------\\n\"\n )\n # Save the final candidate vote count to the text file.\n for candidate_name in candidate_votes:\n\n # Retrieve vote count and percentage\n votes = candidate_votes.get(candidate_name)\n vote_percentage = float(votes) / float(total_votes) * 100\n candidate_results = (\n f\"{candidate_name}: {vote_percentage:.1f}% ({votes:,})\\n\")\n\n # Print each candidate's voter count and percentage to the\n # terminal.\n print(candidate_results)\n # Save the candidate results to our text file.\n txt_file.write(candidate_results)\n\n # Determine winning vote count, winning percentage, and candidate.\n if (votes > winning_count) and (vote_percentage > winning_percentage):\n winning_count = votes\n winning_candidate = candidate_name\n winning_percentage = vote_percentage\n\n # Print the winning candidate (to terminal)\n winning_candidate_summary = (\n f\"-------------------------\\n\"\n f\"Winner: {winning_candidate}\\n\"\n f\"Winning Vote Count: {winning_count:,}\\n\"\n f\"Winning Percentage: {winning_percentage:.1f}%\\n\"\n f\"-------------------------\\n\")\n print(winning_candidate_summary)\n\n # Save the winning candidate's name to the text file\n txt_file.write(winning_candidate_summary)\n\n\n\n## TEST FOR DUPLICATES\n## NOTE: The code below (ln 180 - 193) tests for duplicate voter id numbers\n## and is commented out because it takes a very long time to run, so beware...\n## Read the csv and convert it into a list of dictionaries\n\n# with open(file_to_load) as election_data:\n# Read = csv.reader(election_data)\n\n# header = next(Read)\n\n# for row in Read:\n# voter_id = row[0]\n# if voter_id not in voter_id_list: \n# voter_id_list.append(voter_id)\n# voter_id_dict[voter_id] = 0\n# voter_id_dict[voter_id] +=1\n# if voter_id_dict[voter_id] > 1:\n# dup_output[voter_id]\n# print(dup_output)","sub_path":"PyPoll_Challenge.py","file_name":"PyPoll_Challenge.py","file_ext":"py","file_size_in_byte":6429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"293832852","text":"import json\nfrom ahoy.dockerApi.containers import docker_containers_bp\nfrom ahoy.dockerApi import docker_client\nfrom flask import jsonify, request\nfrom docker.errors import APIError, ContainerError, InvalidArgument, NullResource\n\n\n@docker_containers_bp.route('/', methods=['GET','POST'])\ndef container_get():\n if request.method == \"POST\":\n try:\n container_id = json.loads(request.data.decode())['container_id'] or None\n return docker_client.containers.get(container_id=container_id).attrs\n except NullResource as err:\n return {'error': err.args[0]}\n\n return {'state':\"get\"}\n\n\n@docker_containers_bp.route('/list')\ndef docker_list():\n container_list = []\n for container in docker_client.containers.list(all=True):\n container_list.append(container.attrs)\n return jsonify(container_list)\n\n\n@docker_containers_bp.route('/run', methods=[\"POST\"])\ndef run_container():\n # ports format {'1900/udp': 1900, '32400/tcp': 32400}\n try:\n docker_client.containers.run( **json.loads(request.data.decode()) )\n return {\"status\":\"COntainer is created.\"}, 200\n\n except APIError as err :\n return {\"error\": f\"API Error: {err.explanation}\", },400\n\n except ContainerError as err:\n return {\"error\": f\"Container configration has error(s). Check container's logs.\"},400\n except InvalidArgument as err:\n return {\"error\": f\"{err}\" },400\n except Exception as e:\n return {\"error\": f\"{e}\" },400\n\n\n@docker_containers_bp.route('/remove', methods=[\"POST\"])\ndef remove_container():\n container_info = json.loads(request.data.decode())\n\n try:\n container = docker_client.containers.get(container_info['container_id'])\n container.remove(force=container_info['force'])\n return {\"state\": f\"{str(container.attrs['Name']).strip('/')} is removed\"}\n except APIError as err:\n return {\"msg\": str(err.explanation).split(':')[-1]},400\n except Exception as err:\n return {\"msg\":\"Something went wrong.\"}\n\n\n@docker_containers_bp.route('/start', methods=['POST'])\ndef container_start():\n\n if request.method == \"POST\":\n container_id = json.loads(request.data.decode())['container_id'] or None\n if (container_id):\n try:\n docker_client.containers.get(container_id).start()\n return {\"status\": f\"{container_id} is started.\"}\n except APIError as err:\n return {\"msg\": str(err.explanation).split(':')[-1]},400\n except Exception as err:\n return {\"msg\":\"Something went wrong.\"}\n\n return {'state':\"start\"}\n\n\n@docker_containers_bp.route('/stop', methods=['POST'])\ndef container_stop():\n\n if request.method == \"POST\":\n container_id = json.loads(request.data.decode())['container_id'] or None\n if (container_id):\n try:\n docker_client.containers.get(container_id).stop()\n return {\"status\": f\"{container_id} is stopped.\"}\n except APIError as err:\n return {\"msg\": str(err.explanation).split(':')[-1]},400\n except Exception as err:\n return {\"msg\":\"Something went wrong.\"}\n\n return {'state':\"stop\"}\n\n\n\n\n# attrs\n# id\n# image\n# labels\n# name\n# short_id\n# status\n# attach(**kwargs)\n# attach_socket(**kwargs)\n# diff()\n# exec_run(cmd, stdout=True, stderr=True, stdin=False, tty=False, privileged=False, user='', detach=False, stream=False, socket=False, environment=None, workdir=None, demux=False)\n# export(chunk_size=2097152)\n# get_archive(path, chunk_size=2097152, encode_stream=False)\n# kill(signal=None)\n# logs(**kwargs)\n# pause()\n# reload()\n# resize(height, width)\n# restart(**kwargs)\n#### start(**kwargs)\n#### stop(**kwargs)\n# stats(**kwargs)\n# top(**kwargs)\n# unpause()\n# update(**kwargs)\n# wait(**kwargs)\n\n\n\n########################################################################################################\n########################################################################################################\n########################################################################################################\n# attrs\n\n# id\n\n# The ID of the object.\n\n# image\n\n# The image of the container.\n\n# labels\n\n# The labels of a container as dictionary.\n\n# name\n\n# The name of the container.\n\n# short_id\n\n# The ID of the object, truncated to 10 characters.\n\n# status\n\n# The status of the container. For example, running, or exited. The raw representation of this object from the server.\n\n# attach(**kwargs)\n\n# Attach to this container.\n\n# logs() is a wrapper around this method, which you can use instead if you want to fetch/stream container output without first retrieving the entire backlog.\n# Parameters:\t\n\n# stdout (bool) – Include stdout.\n# stderr (bool) – Include stderr.\n# stream (bool) – Return container output progressively as an iterator of strings, rather than a single string.\n# logs (bool) – Include the container’s previous output.\n\n# Returns:\t\n\n# By default, the container’s output as a single string.\n\n# If stream=True, an iterator of output strings.\n\n# Raises:\t\n\n# docker.errors.APIError – If the server returns an error.\n\n# attach_socket(**kwargs)\n\n# Like attach(), but returns the underlying socket-like object for the HTTP request.\n# Parameters:\t\n\n# params (dict) – Dictionary of request parameters (e.g. stdout, stderr, stream).\n# ws (bool) – Use websockets instead of raw HTTP.\n\n# Raises:\t\n\n# docker.errors.APIError – If the server returns an error.\n\n# commit(repository=None, tag=None, **kwargs)\n\n# Commit a container to an image. Similar to the docker commit command.\n# Parameters:\t\n\n# repository (str) – The repository to push the image to\n# tag (str) – The tag to push\n# message (str) – A commit message\n# author (str) – The name of the author\n# changes (str) – Dockerfile instructions to apply while committing\n# conf (dict) –\n\n# The configuration for the container. See the Engine API documentation for full details.\n\n# Raises:\t\n\n# docker.errors.APIError – If the server returns an error.\n\n# diff()\n\n# Inspect changes on a container’s filesystem.\n# Returns:\t(str)\n# Raises:\tdocker.errors.APIError – If the server returns an error.\n\n# exec_run(cmd, stdout=True, stderr=True, stdin=False, tty=False, privileged=False, user='', detach=False, stream=False, socket=False, environment=None, workdir=None, demux=False)\n\n# Run a command inside this container. Similar to docker exec.\n# Parameters:\t\n\n# cmd (str or list) – Command to be executed\n# stdout (bool) – Attach to stdout. Default: True\n# stderr (bool) – Attach to stderr. Default: True\n# stdin (bool) – Attach to stdin. Default: False\n# tty (bool) – Allocate a pseudo-TTY. Default: False\n# privileged (bool) – Run as privileged.\n# user (str) – User to execute command as. Default: root\n# detach (bool) – If true, detach from the exec command. Default: False\n# stream (bool) – Stream response data. Default: False\n# socket (bool) – Return the connection socket to allow custom read/write operations. Default: False\n# environment (dict or list) – A dictionary or a list of strings in the following format [\"PASSWORD=xxx\"] or {\"PASSWORD\": \"xxx\"}.\n# workdir (str) – Path to working directory for this exec session\n# demux (bool) – Return stdout and stderr separately\n\n# Returns:\t\n\n# A tuple of (exit_code, output)\n\n# exit_code: (int):\n\n# Exit code for the executed command or None if either stream or socket is True.\n# output: (generator, bytes, or tuple):\n\n# If stream=True, a generator yielding response chunks. If socket=True, a socket object for the connection. If demux=True, a tuple of two bytes: stdout and stderr. A bytestring containing response data otherwise.\n\n# Return type:\t\n\n# (ExecResult)\n# Raises:\t\n\n# docker.errors.APIError – If the server returns an error.\n\n# export(chunk_size=2097152)\n\n# Export the contents of the container’s filesystem as a tar archive.\n# Parameters:\tchunk_size (int) – The number of bytes returned by each iteration of the generator. If None, data will be streamed as it is received. Default: 2 MB\n# Returns:\tThe filesystem tar archive\n# Return type:\t(str)\n# Raises:\tdocker.errors.APIError – If the server returns an error.\n\n# get_archive(path, chunk_size=2097152, encode_stream=False)\n\n# Retrieve a file or folder from the container in the form of a tar archive.\n# Parameters:\t\n\n# path (str) – Path to the file or folder to retrieve\n# chunk_size (int) – The number of bytes returned by each iteration of the generator. If None, data will be streamed as it is received. Default: 2 MB\n# encode_stream (bool) – Determines if data should be encoded (gzip-compressed) during transmission. Default: False\n\n# Returns:\t\n\n# First element is a raw tar data stream. Second element is a dict containing stat information on the specified path.\n# Return type:\t\n\n# (tuple)\n# Raises:\t\n\n# docker.errors.APIError – If the server returns an error.\n\n# Example\n\n# >>> f = open('./sh_bin.tar', 'wb')\n# >>> bits, stat = container.get_archive('/bin/sh')\n# >>> print(stat)\n# {'name': 'sh', 'size': 1075464, 'mode': 493,\n# 'mtime': '2018-10-01T15:37:48-07:00', 'linkTarget': ''}\n# >>> for chunk in bits:\n# ... f.write(chunk)\n# >>> f.close()\n\n# kill(signal=None)\n\n# Kill or send a signal to the container.\n# Parameters:\tsignal (str or int) – The signal to send. Defaults to SIGKILL\n# Raises:\tdocker.errors.APIError – If the server returns an error.\n\n# logs(**kwargs)\n\n# Get logs from this container. Similar to the docker logs command.\n\n# The stream parameter makes the logs function return a blocking generator you can iterate over to retrieve log output as it happens.\n# Parameters:\t\n\n# stdout (bool) – Get STDOUT. Default True\n# stderr (bool) – Get STDERR. Default True\n# stream (bool) – Stream the response. Default False\n# timestamps (bool) – Show timestamps. Default False\n# tail (str or int) – Output specified number of lines at the end of logs. Either an integer of number of lines or the string all. Default all\n# since (datetime or int) – Show logs since a given datetime or integer epoch (in seconds)\n# follow (bool) – Follow log output. Default False\n# until (datetime or int) – Show logs that occurred before the given datetime or integer epoch (in seconds)\n\n# Returns:\t\n\n# Logs from the container.\n# Return type:\t\n\n# (generator or str)\n# Raises:\t\n\n# docker.errors.APIError – If the server returns an error.\n\n# pause()\n\n# Pauses all processes within this container.\n# Raises:\tdocker.errors.APIError – If the server returns an error.\n\n# put_archive(path, data)\n\n# Insert a file or folder in this container using a tar archive as source.\n# Parameters:\t\n\n# path (str) – Path inside the container where the file(s) will be extracted. Must exist.\n# data (bytes) – tar data to be extracted\n\n# Returns:\t\n\n# True if the call succeeds.\n# Return type:\t\n\n# (bool)\n# Raises:\t\n\n# APIError If an error occurs.\n\n# reload()\n\n# Load this object from the server again and update attrs with the new data.\n\n# remove(**kwargs)\n\n# Remove this container. Similar to the docker rm command.\n# Parameters:\t\n\n# v (bool) – Remove the volumes associated with the container\n# link (bool) – Remove the specified link and not the underlying container\n# force (bool) – Force the removal of a running container (uses SIGKILL)\n\n# Raises:\t\n\n# docker.errors.APIError – If the server returns an error.\n\n# rename(name)\n\n# Rename this container. Similar to the docker rename command.\n# Parameters:\tname (str) – New name for the container\n# Raises:\tdocker.errors.APIError – If the server returns an error.\n\n# resize(height, width)\n\n# Resize the tty session.\n# Parameters:\t\n\n# height (int) – Height of tty session\n# width (int) – Width of tty session\n\n# Raises:\t\n\n# docker.errors.APIError – If the server returns an error.\n\n# restart(**kwargs)\n\n# Restart this container. Similar to the docker restart command.\n# Parameters:\ttimeout (int) – Number of seconds to try to stop for before killing the container. Once killed it will then be restarted. Default is 10 seconds.\n# Raises:\tdocker.errors.APIError – If the server returns an error.\n\n# start(**kwargs)\n\n# Start this container. Similar to the docker start command, but doesn’t support attach options.\n# Raises:\tdocker.errors.APIError – If the server returns an error.\n\n# stats(**kwargs)\n\n# Stream statistics for this container. Similar to the docker stats command.\n# Parameters:\t\n\n# decode (bool) – If set to true, stream will be decoded into dicts on the fly. Only applicable if stream is True. False by default.\n# stream (bool) – If set to false, only the current stats will be returned instead of a stream. True by default.\n\n# Raises:\t\n\n# docker.errors.APIError – If the server returns an error.\n\n# stop(**kwargs)\n\n# Stops a container. Similar to the docker stop command.\n# Parameters:\ttimeout (int) – Timeout in seconds to wait for the container to stop before sending a SIGKILL. Default: 10\n# Raises:\tdocker.errors.APIError – If the server returns an error.\n\n# top(**kwargs)\n\n# Display the running processes of the container.\n# Parameters:\tps_args (str) – An optional arguments passed to ps (e.g. aux)\n# Returns:\tThe output of the top\n# Return type:\t(str)\n# Raises:\tdocker.errors.APIError – If the server returns an error.\n\n# unpause()\n\n# Unpause all processes within the container.\n# Raises:\tdocker.errors.APIError – If the server returns an error.\n\n# update(**kwargs)\n\n# Update resource configuration of the containers.\n# Parameters:\t\n\n# blkio_weight (int) – Block IO (relative weight), between 10 and 1000\n# cpu_period (int) – Limit CPU CFS (Completely Fair Scheduler) period\n# cpu_quota (int) – Limit CPU CFS (Completely Fair Scheduler) quota\n# cpu_shares (int) – CPU shares (relative weight)\n# cpuset_cpus (str) – CPUs in which to allow execution\n# cpuset_mems (str) – MEMs in which to allow execution\n# mem_limit (int or str) – Memory limit\n# mem_reservation (int or str) – Memory soft limit\n# memswap_limit (int or str) – Total memory (memory + swap), -1 to disable swap\n# kernel_memory (int or str) – Kernel memory limit\n# restart_policy (dict) – Restart policy dictionary\n\n# Returns:\t\n\n# Dictionary containing a Warnings key.\n# Return type:\t\n\n# (dict)\n# Raises:\t\n\n# docker.errors.APIError – If the server returns an error.\n\n# wait(**kwargs)\n\n# Block until the container stops, then return its exit code. Similar to the docker wait command.\n# Parameters:\t\n\n# timeout (int) – Request timeout\n# condition (str) – Wait until a container state reaches the given condition, either not-running (default), next-exit, or removed\n\n# Returns:\t\n\n# The API’s response as a Python dictionary, including\n\n# the container’s exit code under the StatusCode attribute.\n\n# Return type:\t\n\n# (dict)\n# Raises:\t\n\n# requests.exceptions.ReadTimeout – If the timeout is exceeded.\n# docker.errors.APIError – If the server returns an error.\n\n","sub_path":"ahoy/dockerApi/containers/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":15993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"285320209","text":"#pylint: disable-msg=E1101\n# -*- coding: iso-8859-1 -*-\n#\n# $Id: sasnCommands.py,v 1.3 2013/03/20 15:19:56 xjoaalm Exp $\n#\n# Copyright (c) Ericsson Espa�a S.A., 2012.\n# All rights reserved.\n#\n# This product or document is proprietary to and embodies the\n# confid;id+=1ential technology of Ericsson Espa�a S.A.\n# Possession, use, duplication or distribution of this product\n# or document is authorized only pursuant to a valid;id+=1 written\n# license from Ericsson Espa�a S.A\n#\n'''\nThis module contains a class to be used for encapsulating the commands\nthat can be executed in SASN\n'''\nimport copy, re\nimport os\nfrom sasnVersions import SASNVersions\nfrom execution_mode import ExecutionMode\nfrom command import Command, CommandLevel\nfrom NSTpyfw.utils.exception.framework import InvalidArgument, ArgumentNotPresent, InvalidLogFile\nfrom NSTpyfw.utils.sasn_paths import SASNPaths\n\n\"\"\"\nALL_COMMANDS = {\n \"command_name\": {\n \"com\": {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"command string\"\n }\n }\n CommandLevel.nssh: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"command string\"\n }\n }\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"command string\"\n }\n }\n }\n}\n\"\"\"\n\nALL_COMMANDS = {\n \"CHANGE_PART\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns partition set %1\"\n }\n }\n },\n \"PARTITION_CONFIGURATION\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns partition show config\"\n }\n }\n },\n \"STOP_PART\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns partition stop\"\n }\n },\n \"com_available\": True\n },\n \"CLUSTER\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"ns cluster '%1' %2%3\"\n }\n }\n },\n \"ADD_TARGET\": {\n CommandLevel.nssh: {\n SASNVersions().get_version_id(\"14A\"): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"%1 %2 %3\"\n }\n }\n },\n\n \"SASN_START\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns system boot start %1\"\n }\n },\n \"com_available\":[\n [\".*\"]\n ]\n },\n \"SASN_STOP\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns system boot stop %1 %2\"\n }\n },\n \"com_available\":[\n [\".*\"]\n ]\n },\n \"SASN_RESTART\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns system boot restart%1\"\n }\n },\n \"com_available\":[\n [\".*\"]\n ]\n },\n \"SASN_STOP_ALL\": {\n CommandLevel.nssh: {\n SASNVersions().get_version_id(\"14A\"): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"ns stop%1%2\"\n }\n },\n \"com_available\": True\n },\n\n \"RD_START\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns system rd-boot start %1\"\n }\n },\n \"com_available\":[\n [\".*\"]\n ]\n },\n \"RD_STOP\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns system rd-boot stop %1\"\n }\n },\n \"com_available\":[\n [\".*\"]\n ]\n },\n \"RD_RESTART\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns system rd-boot restart%1\"\n }\n },\n \"com_available\":[\n [\".*\"]\n ]\n },\n \"SHOW_PEER\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns config %1 show peer\"\n }\n },\n \"com_available\":[\n [\".*\"]\n ]\n },\n \"DIAM_APP_PARAM\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns config %1 set application-param %2 %3\"\n }\n }\n },\n \"SHOW_STATUS\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns system show status %1\"\n }\n },\n \"com_available\": True\n },\n \"SHOW_BOOT\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns system show boot\"\n }\n },\n \"com_available\": True\n },\n \"SHOW_RD_BOOT\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns system show rd-boot\"\n }\n },\n \"com_available\": True\n },\n \"LOAD_CFG_BCK\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns system wizard cluster load %1 local rd-backup force\"\n },\n SASNVersions().get_version_id(\"2012A\"): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns system wizard load %1 local backup1 force\"\n }\n }\n },\n \"LOAD_CFG_MASTER\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns system wizard cluster load %1 force\"\n },\n SASNVersions().get_version_id(\"2012A\"): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns system wizard load %1 force continue\"\n }\n }\n },\n \"LOAD_CFG_CLUSTER\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns system wizard cluster load %1 force %2\"\n },\n SASNVersions().get_version_id(\"2012A\"): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns system wizard load %1 force continue\"\n }\n }\n },\n \"CHECK_DELTA\": {\n CommandLevel.nssh: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"ns check-delta\"\n }\n },\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns system check-delta %1\"\n }\n },\n \"com_available\": True\n },\n \"APPLY_CFG\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns system wizard %1 apply %2 %3 %4 %5\"\n },\n SASNVersions().get_version_id(\"2012A\"): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns system wizard apply %2 %3 %4 %5\"\n }\n }\n },\n \"LICENSE_INSTALL\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns system license install %1\"\n }\n }\n },\n \"LICENSE_INSTALLED\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns system license install %1\"\n }\n }\n },\n \"SHOW_SYS_CONFIG\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns system show config %1\"\n }\n },\n \"com_available\":[\n [\"(server|process|aggregated-qos|tcp|bearer|service|rating-group-control|\" + \\\n \"content-editor|content-filter|tcp-deferred-charging|\" + \\\n \"tcp-retransmitted-packets|charging-profile|qbau-reporting|gx|icap|gy|\" + \\\n \"rx|shaper|running|startup)\"]\n ]\n },\n \"SHOW_SYS_PERSISTENT_ROUTES\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns system show persistent-routes\"\n }\n },\n \"com_available\": True\n },\n \"SHOW_SYS_SESSION\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns system show session%1\"\n }\n },\n \"com_available\":[\n [\".*\"]\n ]\n },\n \"SHOW_SYS_STATS\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns system show statistics %1\"\n }\n },\n \"com_available\":[\n [\"(server|process|aggregated-qos|tcp|bearer|service|rating-group-control|\" + \\\n \"content-editor|content-filter|tcp-deferred-charging|\" + \\\n \"tcp-retransmitted-packets|charging-profile|qbau-reporting|gx|icap|gy|\" + \\\n \"rx|shaper|dr-rest|dr-job|event-reporting-ebm)\"]\n ]\n },\n \"CLEAR_SYS_STATS\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns system clear statistics %1\"\n }\n },\n \"com_available\":[\n [\"(server|process|aggregated-qos|tcp|bearer|service|rating-group-control|\" + \\\n \"content-editor|content-filter|tcp-deferred-charging|\" + \\\n \"tcp-retransmitted-packets|charging-profile|qbau-reporting|gx|icap|gy|\" + \\\n \"rx|shaper|dr-rest|dr-job|event-reporting-ebm)\"]\n ]\n },\n \"DOMAIN_REPORTING_SYS_CMD\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns system domain-reporting %1\"\n }\n }\n },\n \"HEALTH_CHECK\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"ns system health-check basic\"\n }\n },\n \"com_available\": False\n },\n \"CHECK_CLUSTER\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns system wizard cluster check %1\"\n }\n }\n },\n \"SHOW_PROC_CFG\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns process show %1\"\n }\n },\n \"com_available\":[\n [\"(information|detail|ipc)\"]\n ]\n },\n \"START_STOP_PROCESS\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns process %1%2\"\n }\n },\n \"com_available\":[\n [\"(start|stop)\"]\n ]\n },\n\n \"SET_PROCESS\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns process set %1 %2\"\n }\n },\n \"com_available\":[\n [\".*\"]\n ]\n },\n\n \"CHANGE_COREDUMP\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns process set %1 coredump %2\"\n }\n },\n \"com_available\":[\n [\"pmain\", \"(on|off)\"],\n ]\n },\n \"MOD_SHOW_STAT\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns config %1 show statistics\"\n }\n },\n \"com_available\":[\n [\"sml\"]\n ],\n },\n \"MOD_PLG_SHOW\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns config %1 plugin %2 show %3\"\n }\n },\n \"com_available\":[\n [\"scm\", \"canalyzer\", \"(analyzers|cache|content-editor-matches|dbc|\" + \\\n \"dbc hosts|dbc rules|dbc servers|dbc timer|fields|\" + \\\n \"fields .+|flow-summary|flow-tree|flow-tree .+|\" + \\\n \"flows|flows .+|plugin|rule-matches|show statistics|\" + \\\n \"statistics all|plugin|protocols|version built-in|\" + \\\n \"version running)\"],\n [\"scm\", \"cfe\", \"(cache|cache verbose|sesssion|statistics)\"],\n [\"scm\", \"cfe profile .+\", \"cache\"],\n [\"scm\", \"relay shaper\", \"(session|statistics)\"],\n [\"scm\", \"relay$\", \"(deferred-charging-stats|dynamic-charging-statistics|\" + \\\n \"gargabe-collector|qbau-statistics|\" + \\\n \"rating-group-control-statistics|session|session all|\" + \\\n \"statistics queue|tcp-retransmit-stats|virtual-session)\"]\n ]\n },\n \"MOD_PLG_CLEAR\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns config %1 plugin %2 clear %3\"\n }\n },\n \"com_available\":[\n [\"scm\", \"canalyzer\", \"(content-editor-matches|dbc-shallow-rules)\"],\n [\"scm\", \"cfe\", \"statistics\"],\n [\"scm\", \"relay\", \"(deferred-charging-stats|dynamic-charging-statistics|\" + \\\n \"qbau-statistics|rating-group-control-statistics|\" + \\\n \"tcp-retransmit-stats)\"],\n [\"scm\", \"relay shaper\", \"statistics\"],\n ]\n },\n \"MOD_PLG_DELETE\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns config %1 plugin %2 delete %3\"\n }\n },\n \"com_available\":[\n [\"scm\", \"cfe\", \"cache\"],\n [\"scm\", \"relay\", \"session all$\"],\n [\"scm\", \"canalyzer\", \"(rule-matches|all-flows)\"],\n ]\n },\n \"MOD_PLG_DELETE_PROFILE\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns config %1 plugin %2 profile %3 delete %4\"\n }\n },\n \"com_available\":[\n [\"scm\", \"cfe\", \".*\", \"cache\"]\n ]\n },\n \"MOD_PLG_SET\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns config %1 plugin %2 set %3\"\n }\n },\n \"com_available\":[\n [\"scm\", \"canalyzer\", \"DNS config domain.*\"]\n ]\n },\n \"MOD_SHOW\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"force_nssh\": True,\n \"command\": \"ns config %1 show%2\",\n }\n },\n \"com_available\":[\n [\".*\", \"application$\"],\n [\"broker\", \"(active|config|registry)\"],\n [\"^ha\", \"(config|process|redundancy|redundancy history|sync)\"],\n [\"probe\", \"status\"],\n [\"rdha\", \"(config|process|redundancy|redundancy history|sync)\"],\n [\"scm\", \"(control-class|replication|replication statistics|session .+)\"],\n [\"smg\", \"statistics\"],\n [\"tcp\", \"socket\"],\n [\"udr\", \"session all\"],\n [\"aocmgr\", \"session .*\"],\n [\"dataprobe\", \"status\"],\n [\"^probe\", \"status\"],\n [\"radiusproxy\", \"pools\"],\n [\"diamtr-.*\", \"(avps|categories|categories .+|debug|message|message queue|\" + \\\n \"peer|session|session .+|stat)\"],\n [\"rdvr\", \"redundancy\"],\n [\".*\", \"storage-area\"],\n [\"workflow\", \"running\"],\n [\"monitor\", \"information\"],\n [\"partition\", \"information\"],\n [\"vr\", \"(notification|process|redundancy|route|snmp)\"],\n ]\n\n },\n \"MOD_SHOW_NO_CLUSTER\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"force_nssh\": True,\n \"command\": \"ns config %1 show%2\",\n }\n },\n \"com_available\":[\n [\"tsmssr\", \"(status|config)\"],\n [\"rpcm\", \"status\"],\n [\"broker\", \"(vm-instance|status)\"]\n ]\n\n },\n \"MOD_CLEAR\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns config %1 clear %2\"\n }\n }\n },\n \"MOD_SET_NO_CLUSTER\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"ns config %1 set %2%3\"\n }\n },\n \"com_available\":[\n [\"^ha\", \"redundancy manual\", \".*\"],\n [\"rdha\", \"redundancy manual\", \".*\"],\n ]\n },\n \"MOD_SET\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns config %1 set %2%3\"\n }\n },\n \"com_available\":[\n [\"broker\", \"(partition|partitions|probe)\", \".*\"],\n [\"^ha\", \"(process|redundancy|sync)\", \".*\"],\n [\"rdha\", \"(process|redundancy|redundancy manual|sync)\", \".*\"],\n [\"vr\", \"redundancy manual\", \".*\"],\n ]\n },\n \"MOD_SET_LOGGING\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns module set %1 logging %2\"\n }\n },\n \"com_available\":[\n [\".*\"]\n ]\n },\n \"MOD_DELETE\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns config %1 delete %2%3\"\n }\n },\n \"com_available\":[\n [\"^ha\", \"(process|sync|interface|platform-health-lockfile|subscriber)\", \".*\"],\n [\"rdha\", \"(process|sync|interface|platform-health-lockfile|subscriber)\", \".*\"]\n ]\n },\n \"XDR_CONFIG\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns config udr plugin %1 set %2\"\n }\n }\n },\n \"SNMP_SHOW\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns snmp show %1\"\n }\n },\n \"com_available\":[\n [\".*\"]\n ]\n },\n \"SNMP_MANUAL\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns snmp manual %1\"\n }\n },\n \"com_available\":[\n [\"(set|clear).*\"]\n ]\n },\n \"STATISTICS\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns statistics show %1\"\n }\n },\n \"com_available\":[\n [\"information\"]\n ]\n },\n \"VAR_SHOW\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns variable show value %1\"\n }\n }\n },\n \"SET_REDUNDANCY\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns part set 0 && ns config rdvr set redundancy manual %1\"\n }\n }\n },\n \"DEL_SHMEM\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns management delete shmem %1\"\n }\n },\n \"com_available\":[\n [\"id\"]\n ]\n },\n \"SHOW_SHMEM\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns management shmem show %1%2\"\n }\n },\n \"com_available\":[\n [\".+\"]\n ]\n },\n \"DUMP_SHMEM\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns management shmem dump %1\"\n }\n },\n \"com_available\": True\n },\n \"DIAGNOSTIC\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns management diagnostic %1\"\n }\n },\n \"com_available\":[\n [\".+\"]\n ]\n },\n \"MEMDOMAIN\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"ns management memdomain %1%2\"\n }\n },\n \"com_available\": True\n },\n \"MANAGEMENT_BACKUP\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"ns management backup\"\n }\n },\n \"com_available\": True\n },\n \"MANAGEMENT_CAPTURE\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"ns management capture %1\"\n }\n },\n \"com_available\": True\n },\n \"MANAGEMENT_SET_BACKUP\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"ns management set backup %1 %2\"\n }\n },\n \"com_available\": True\n },\n \"MANAGEMENT_TRACE\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"ns management trace %1\"\n }\n },\n \"com_available\": True\n },\n \"MONITOR_ACTION\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns monitor %1 %2 %3\"\n }\n },\n \"com_available\":[\n [\"show\", \"information\"]\n ]\n },\n \"RDMONITOR_ACTION\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns rdmonitor %1 %2%3\"\n }\n },\n \"com_available\":[\n [\"show\", \"config\", \"\"]\n ]\n },\n \"SET_ANONYMOUS_SESSION\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns config scm plugin relay set session auto-msisdn true\"\n },\n SASNVersions().get_version_id(\"13B\"): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns config scm plugin relay set session anonymous-sessions true\"\n }\n\n }\n },\n \"SOFTWARE\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns system show software %1%2\"\n }\n },\n \"com_available\": True\n },\n \"VERSION\": {\n CommandLevel.com: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"display\",\n \"use_cluster\": False,\n \"command\": \"ns version\"\n }\n },\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"ns version\",\n \"force_nssh\": True\n }\n },\n \"com_available\": True\n },\n \"CFG_VALIDATE_HL\": {\n CommandLevel.nssh: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"ns validate %1\",\n \"force_nssh\": True\n }\n },\n \"com_available\": True\n },\n \"CFG_COMMIT\": {\n CommandLevel.nssh: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"ns commit %1\",\n \"force_nssh\": True\n }\n }\n },\n \"CHECK_COMMIT_STATUS\": {\n CommandLevel.nssh: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"ns commit show status\"\n }\n },\n \"com_available\": True\n },\n \"COMMIT_CLEAR\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"ns commit clear\"\n }\n },\n \"com_available\": True\n },\n \"COMMIT_SET\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"ns commit set %1\"\n }\n },\n \"com_available\": [\n [\".*sequential.*\"]\n ]\n },\n \"COMMIT_SHOW\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"ns commit show %1\"\n }\n },\n \"com_available\": [\n [\"(info|status)\"]\n ]\n },\n \"BROKER_CARDS\": {\n CommandLevel.nssh: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"ns broker cards\"\n }\n },\n \"com_available\": True\n },\n \"BROKER_HOSTNAME\": {\n CommandLevel.nssh: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"ns broker hostname %1\"\n }\n },\n \"com_available\": True\n },\n \"BROKER_B2B\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"ns config broker b2b %1%2\",\n }\n },\n \"com_available\": False\n },\n \"RECOVER\": {\n CommandLevel.nssh: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"ns recover%1\"\n }\n },\n \"com_available\": True\n },\n \"SINACTIVITY_CMD\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"/opt/nsfw/bin/sinactivity %1\"\n }\n }\n },\n \"SHMSEARCH_CMD\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"/opt/nsfw/bin/shmsearch %1\"\n }\n }\n },\n \"RST_DOMAIN_REPORTING_STATUS\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"ns config reporterEP report status reset\"\n }\n }\n },\n \"DOMAIN_REPORTING_REPORT_DOMAIN_JOB\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"ns config reporterEP report domain job %1\"\n }\n }\n },\n \"LOG\": {\n CommandLevel.nssh: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"ns log %1 %2\"\n }\n },\n \"com_available\": True\n },\n \"BROKER_FILE_TRANSFER\": {\n CommandLevel.nssh: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"ns host set %1; ns copy %2 %3 %4\"\n }\n }\n },\n \"HOST\": {\n CommandLevel.nssh: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"ns host set %1\"\n }\n }\n },\n \"COPY\": {\n CommandLevel.nssh: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"ns copy %1 %2 %3\"\n }\n }\n },\n \"SASN_INSTALLATION\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"ns system software install %1%2%3%4\"\n }\n },\n \"com_available\": True\n },\n \"SASN_ROLLBACK\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"ns system software rollback %1 %2%3%4\"\n }\n },\n \"com_available\": True\n },\n \"INSTALL_HEURISTICS\": {\n CommandLevel.nssh: {\n SASNVersions().get_version_id(\"14A\"): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"ns install-heuristics %1\"\n }\n },\n \"com_available\": True\n },\n \"UPDATE_HEURISTICS\": {\n CommandLevel.nssh: {\n SASNVersions().get_version_id(\"14A\"): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"ns update-heuristics %1\"\n }\n },\n \"com_available\": True\n },\n \"VALIDATE_HEURISTICS\": {\n CommandLevel.nssh: {\n SASNVersions().get_version_id(\"14A\"): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"ns validate-heuristics\"\n }\n },\n \"com_available\": True\n },\n \"APPLY_HEURISTICS\": {\n CommandLevel.nssh: {\n SASNVersions().get_version_id(\"14A\"): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"ns apply-heuristics\"\n }\n },\n \"com_available\": True\n },\n \"MIGRATION\": {\n CommandLevel.nssh: {\n SASNVersions().get_version_id(\"14A\"): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"ns migrate %1 outfile %2\"\n }\n },\n \"com_available\": True\n },\n \"SECURITY_CHANGE\": {\n CommandLevel.nssh: {\n SASNVersions().get_version_id(\"14A\"): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"/tmp/hs %1 pass %2\"\n }\n }\n },\n \"RUN_CHANGE_ROOT_PASSWORD\": {\n CommandLevel.nssh: {\n SASNVersions().get_version_id(\"14A\"): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"/opt/nstest/bin/run_change_root_password %1 %2 %3 %4 %5 %6\"\n }\n }\n },\n \"RUN_AND_CHECK_NS_COMMAND\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"/opt/nstest/bin/run_and_check_ns_command %1 %2 %3 %4\"\n }\n }\n },\n \"RUN_AND_CHECK_SU_USER\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"/opt/nstest/bin/run_and_check_su %1 %2 %3 %4 %5 %6\"\n }\n }\n },\n \"CHANGE_ROOT_PASSWORD\": {\n CommandLevel.nssh: {\n SASNVersions().get_version_id(\"14A\"): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns system security set pass root\"\n }\n }\n },\n \"CHECK_ROOT_PASSWORD\": {\n CommandLevel.nssh: {\n SASNVersions().get_version_id(\"14A\"): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"/opt/nstest/bin/check_su_root %1 %2 %3 %4\"\n }\n }\n },\n \"ICAP_SET_MODE\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns config %1 set mode csv\"\n }\n }\n },\n \"ICAP_SET_SERVER\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns config %1 set server icapserver%2\"\n }\n }\n },\n \"ICAP_SET_TRANSACTION\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns config %1 set transaction%2\"\n }\n }\n },\n \"ICAP_SHOW_CONFIG\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns config %1 show config verbose\"\n }\n }\n },\n \"PROBE_RESET\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns config probe reset %1\"\n }\n }\n },\n \"MODULE_SHOW_CONFIG\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"ns module show config\"\n }\n },\n \"com_available\": True\n },\n \"MONITOR_SHOW_CONFIG\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"ns monitor show config\"\n }\n },\n \"com_available\": True\n },\n \"PARTITION_SET\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"ns partition set %1\"\n }\n },\n \"com_available\": True\n },\n \"PARTITION_SHOW_CURRENT\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"ns partition show current\"\n }\n },\n \"com_available\": True\n },\n \"PARTITION_SHOW_INFORMATION\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns partition show information\"\n }\n },\n },\n \"VARIABLE_SHOW\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"ns variable show %1\"\n }\n },\n \"com_available\": True\n },\n \"SYSTEM_BOOT\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns system %1 %2%3\"\n }\n },\n \"com_available\": [\n [\"^boot\", \"auto\", \"(on|off)\"],\n [\"^boot\", \"recover\", \"\"],\n [\"rd-boot\", \"auto\", \"(on|off)\"],\n [\"rd-boot\", \"recover\", \"\"],\n ],\n },\n \"SYSTEM_SET_CONFIG\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns system set config %1 %2\"\n }\n },\n \"com_available\": [\n [\"rollback-max\", \".*\"],\n ],\n },\n \"SYSTEM_SET_PDC\": {\n CommandLevel.nssh: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"force_nssh\": True,\n \"command\": \"ns system set pdc %1%2\"\n }\n },\n \"com_available\": False\n },\n \"SYSTEM_SHOW\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns system show %1%2\"\n }\n },\n \"com_available\": [\n [\"pmd\", \"\"],\n [\"wizard\", \".*\"],\n [\"coredump\", \".*\"],\n ],\n },\n \"SYSTEM_WIZARD_CLUSTER\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns system wizard cluster %1%2\"\n }\n },\n \"com_available\": True\n },\n \"CHECK_CONSISTENCY\": {\n CommandLevel.nssh: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"ns check-consistency\"\n }\n },\n \"com_available\": True\n },\n \"MIGRATE\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"ns migrate %1\"\n }\n },\n \"com_available\": True\n },\n \"CONFIG_RPFM\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"ns config rpfm %1\"\n }\n },\n \"com_available\": True\n },\n \"CONFIG_RPCM\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"ns config rpcm %1 %2\"\n }\n },\n \"com_available\": True\n },\n \"CAT\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns cat %1\"\n }\n },\n \"com_available\": True\n },\n \"ZCAT\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns zcat %1\"\n }\n },\n \"com_available\": True\n },\n \"DF\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns df\"\n }\n },\n \"com_available\": True\n },\n \"FREE\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns free\"\n }\n },\n \"com_available\": True\n },\n \"LS\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns ls %1%2\"\n }\n },\n \"com_available\": True\n },\n \"PS\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns ps\"\n }\n },\n \"com_available\": True\n },\n \"TAIL\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns tail %1 %2\"\n }\n },\n \"com_available\": True\n },\n \"TOP\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns top%1\"\n }\n },\n \"com_available\": True\n },\n \"UPTIME\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns uptime\"\n }\n },\n \"com_available\": True\n },\n \"SOS_COMMAND\": {\n CommandLevel.nssh: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"/opt/disk/service-pools/sasnpool/active/libexec/sos.sh %1\"\n }\n }\n },\n \"TSMSSR_CLEAN\": {\n CommandLevel.nssh: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"/opt/disk/service-pools/sasnpool/active/libexec/tsm.sh clean %1\"\n }\n }\n },\n \"RM\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": False,\n \"command\": \"ns rm %1\"\n }\n },\n \"com_available\": True\n },\n \"MEMORY_BENCHMARK\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns process show memory-benchmark %1 %2 %3\"\n }\n }\n },\n \"SASN_MEMORY\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"action\": \"execute\",\n \"use_cluster\": True,\n \"command\": \"ns system show memory info\"\n }\n }\n },\n#########################################\n## Folders and Paths\n#########################################\n \"CPUCHK_LOCAL_PATH\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"use_cluster\": False,\n \"command\": \"/opt/nstest/scripts/cpuchk\"\n }\n }\n },\n \"CPUCHK_REMOTE_PATH\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"use_cluster\": False,\n \"command\": \"/tmp/cpuchk/cpuchk\"\n }\n }\n },\n \"CPUCHK_COMMAND\": {\n CommandLevel.oracle: {\n SASNVersions().get_all_versions_id(): {\n \"use_cluster\": False,\n \"command\": \"%1%2\"\n }\n }\n },\n}\n\nclass SASNCommands(object):\n '''\n This module contains a class to be used for encapsulating the\n commands that can be executed in SASN\n '''\n __SSR_COMMANDS = 0\n __ORACLE_COMMANDS = 1\n __VSASN_COMMANDS = 2\n\n def __init__(self):\n \"\"\"\n Constructor for the class\n \"\"\"\n self._sasn_commands = ALL_COMMANDS\n self._sasn_version = None\n self.__execution_more = SASNCommands.__ORACLE_COMMANDS\n self.__command_type = CommandLevel.oracle\n ## END METHOD __init__()\n def __repr__(self):\n \"\"\"\n Return a string representation of this object, for debugging.\n\n @rtype: str\n \"\"\"\n out = '{SASNCommands'\n for i in (\"sasnCommands\", \"sasnVersion\"):\n out += ' %s=%s' % (i, repr(eval(\"self._\" + i)))\n out += '}'\n\n return out\n ## END METHOD __repr__( ... )\n def __initialize(self):\n \"\"\"\n This function initializes the class\n \"\"\"\n ## END METHOD __initialize\n def set_sasn_version(self, version ):\n \"\"\"\n Method used to set the version to be used while retrieving\n commads\n\n @param version: Version name\n @type version: str\n \"\"\"\n if 0 > SASNVersions().get_version_id(version):\n raise Exception(\"Not available version\")\n ## End If\n self._sasn_version = SASNVersions().get_version_id(version)\n SASNPaths().set_sasn_version(version)\n ## END METHOD set_sasn_version( version )\n def _set_execution_mode(self, execution_mode, command_type ):\n \"\"\"\n Function used to set execution mode to be used in\n while retrieving commands\n\n @param execution_mode: Execution mode\n @type execution_mode: str\n @param command_type: Type of commands that need to be sent:\n - B{com}: Commands will be sent via COM\n - B{nssh}: Commands will be sent via NSSH\n @type command_type: str\n \"\"\"\n if ExecutionMode().get_is_ssr(execution_mode):\n self.__execution_more = SASNCommands.__SSR_COMMANDS\n elif ExecutionMode().get_is_vsasn(execution_mode):\n self.__execution_more = SASNCommands.__VSASN_COMMANDS\n else:\n if command_type == CommandLevel.get_value(\"com\"):\n raise Exception(\"Command Type cannot be 'com' if the execution mode is not SSR\")\n ## End If\n self.__execution_more = SASNCommands.__ORACLE_COMMANDS\n ## End If\n self.__command_type = CommandLevel.get_value(command_type)\n ## END METHOD _set_execution_mode( ... )\n def __generate_command_path(self, path):\n \"\"\"\n Genearte a command or a string depending on the platform\n :param path:\n :return:\n \"\"\"\n if self.__execution_more != SASNCommands.__ORACLE_COMMANDS:\n _cmd = Command()\n _cmd.command = path\n return _cmd\n else:\n return path\n ## End If\n ## END METHOD __generate_command_path()\n def __retrieve_command(self, name, *args):\n \"\"\"\n Method that select the command needed by the caller\n\n @param name: Name of the command to be retrieved\n @type name: str\n @param args: List of arguments\n @type args: list\n\n @return: Depending on the execution mode the return will be a string\n or a tuple.\n If the execution mode is Oracle:\n Return a string with he command\n If the execution mode is SSR:\n Return a tuple with the following values:\n (type_of_command, use_or_not_ns_cluster, command)\n @rtype: str|(str,str,str)\n \"\"\"\n if None == self._sasn_version:\n raise Exception(\"SASN version need to be set first\")\n ## End If\n cmd = self._sasn_commands[name]\n result = copy.deepcopy(cmd)\n version = -1\n cmd_type = \"\"\n if result.get(CommandLevel.com) and self.__command_type == CommandLevel.com and\\\n self.__execution_more == SASNCommands.__SSR_COMMANDS:\n for key, _ in result[CommandLevel.com].iteritems():\n if version < key and self._sasn_version >= key:\n version = key\n cmd_type = CommandLevel.com\n ## End If\n ## End For\n ## End If\n\n if version == -1 and result.get(CommandLevel.nssh) and \\\n (self.__execution_more == SASNCommands.__SSR_COMMANDS or self.__execution_more == SASNCommands.__VSASN_COMMANDS):\n for key, _ in result[CommandLevel.nssh].iteritems():\n if version < key and self._sasn_version >= key:\n version = key\n cmd_type = CommandLevel.nssh\n ## End If\n ## End For\n ## End If\n if version == -1 and result.get(CommandLevel.oracle):\n for key, _ in result[CommandLevel.oracle].iteritems():\n if version < key and self._sasn_version >= key:\n version = key\n cmd_type = CommandLevel.oracle\n ## End If\n ## End For\n ## End If\n\n if -1 == version:\n raise Exception((\"The command[%s] do not exist for the version of SASN[%s]!\"%\n (name,SASNVersions().get_version_name(self._sasn_version))\n )\n )\n ## End If\n for arg_id, arg in enumerate(args):\n result[cmd_type][version][\"command\"] = result[cmd_type][version][\"command\"]\\\n .replace((\"%%%s\" % (arg_id+1)), str(arg) )\n ## End For\n if self.__execution_more != SASNCommands.__ORACLE_COMMANDS:\n com_available = False\n if result.get(\"com_available\"):\n if list != type(result[\"com_available\"]):\n com_available = True\n else:\n for cmd_list in result[\"com_available\"]:\n for param_idx, parameter in enumerate(cmd_list):\n if re.search( parameter, args[param_idx] ):\n com_available = True\n else:\n com_available = False\n break\n ## End If\n ## End For\n if com_available:\n break\n ## End If\n ## End For\n ## End If\n ## End If\n\n result_cmd = Command( result[cmd_type][version][\"command\"],\n result[cmd_type][version].get(\"action\"),\n result[cmd_type][version][\"use_cluster\"],\n cmd_type,\n com_available)\n return result_cmd\n else:\n return result[cmd_type][version][\"command\"]\n ## End If\n ## END METHOD retrieve_command(name)\n def retrieve_change_partition(self, number ):\n \"\"\"\n Function to retrieve the command to change partition\n\n @param number: Partition number to change to\n @type nunber: Integer\n @rtype: String\n \"\"\"\n return self.__retrieve_command(\"CHANGE_PART\", number)\n ## End If\n ## END METHOD retrieve_change_partition( force )\n def retrieve_partition_configuration(self):\n \"\"\"\n Function to retrieve the command to see the partition configuration\n \"\"\"\n return self.__retrieve_command(\"PARTITION_CONFIGURATION\")\n ## END METHOD retrieve_partition_configuration()\n def retrieve_stop_partition(self):\n \"\"\"\n Function to retrieve the command to stop partition\n\n @rtype: str\n \"\"\"\n return self.__retrieve_command(\"STOP_PART\")\n ## END METHOD retrieve_stop_partition( force )\n def retrieve_cluster_command(self, command,\n target,\n partition = -1\n ):\n \"\"\"\n Function to wrap a command to a specific target\n and partition\n If no partition is needed then the value should be -1\n\n @param command: Command to be sent\n @type command: String\n @param target: Target platform or card\n @type target: String\n @param partition: Partiton where the command should be performed\n @type partition: Integer\n\n @rtype: String\n \"\"\"\n part = \"\"\n if str(-1) != str(partition):\n part = \" partition %s\" % partition\n ## End If\n if type(command) == Command:\n cmd = command.command\n else:\n cmd = command\n ## End If\n\n cmd = self.__retrieve_command(\"CLUSTER\", cmd,\n target,\n part)\n if type(command) == Command:\n command.command = cmd.command\n else:\n command = cmd\n ## End If\n\n return command\n\n ## END METHOD retrieve_cluster_command( ... )\n def retrieve_target_command(self, command,\n target,\n partition = -1\n ):\n \"\"\"\n Function to wrap a command to a specific target\n and partition\n If no partition is needed then the value should be -1\n\n @param command: Command to be sent\n @type command: String\n @param target: Target platform or card\n @type target: String\n @param partition: Partiton where the command should be performed\n @type partition: Integer\n\n @rtype: String\n \"\"\"\n part = \"\"\n if str(-1) != str(partition):\n part = \" %s\" % partition\n ## End If\n if type(command) == Command:\n cmd = command.command\n else:\n cmd = command\n ## End If\n\n cmd = self.__retrieve_command(\"ADD_TARGET\", cmd,\n target,\n part)\n if type(command) == Command:\n command.command = cmd.command\n else:\n command = cmd\n ## End If\n\n return command\n\n ## END METHOD retrieve_target_command( ... )\n\n def retrieve_cluster_sasn_start(self, force = True ):\n \"\"\"\n Function to retrieve the command to start SASN in all\n the cluster\n\n @param force: Apply force\n @type force: Boolean\n @rtype: String\n \"\"\"\n cmd = self.retrieve_sasn_start(force)\n return self.retrieve_cluster_command(cmd, \"all\")\n\n ## END METHOD retrieve_cluster_sasn_start( force )\n def retrieve_sasn_start(self, force = True ):\n \"\"\"\n Function to retrieve the command to start SASN\n\n @param force: Apply force\n @type force: Boolean\n @rtype: String\n \"\"\"\n if force:\n return self.__retrieve_command(\"SASN_START\",\"force\")\n else:\n return self.__retrieve_command(\"SASN_START\",\"\")\n ## End If\n ## END METHOD retrieve_sasn_start( force )\n def retrieve_cluster_sasn_stop(self, abrupt = True, force = True ):\n \"\"\"\n Function to retrieve the command to stop SASN in all\n the cluster\n\n @param abrupt: Add abrupt to the command\n @type abrupt: Boolean\n @param force: Apply force\n @type force: Boolean\n @rtype: String\n \"\"\"\n cmd = self.retrieve_sasn_stop(abrupt, force)\n return self.retrieve_cluster_command(cmd, \"all\")\n\n ## End If\n ## END METHOD retrieve_cluster_sasn_stop( abrupt force )\n def retrieve_sasn_stop(self, abrupt = True, force = True ):\n \"\"\"\n Function to retrieve the command to stop SASN\n\n @param abrupt: Add abrupt to the command\n @type abrupt: Boolean\n @param force: Apply force\n @type force: Boolean\n @rtype: String\n \"\"\"\n cmd_abr = \"abrupt\" if abrupt else \"\"\n cmd_force = \"force\" if force else \"\"\n return self.__retrieve_command(\"SASN_STOP\", cmd_abr, cmd_force)\n\n ## End If\n ## END METHOD retrieve_cluster_sasn_stop( abrupt force )\n def retrieve_sasn_restart(self, force = True ):\n \"\"\"\n Function to retrieve the command to restart SASN\n\n @param force: Apply force\n @type force: Boolean\n @rtype: String\n \"\"\"\n if force:\n return self.__retrieve_command(\"SASN_RESTART\",\" force\")\n else:\n return self.__retrieve_command(\"SASN_RESTART\",\"\")\n ## End If\n ## END METHOD retrieve_sasn_restart( force )\n def retrieve_cluster_rd_start(self, force = True ):\n \"\"\"\n Function to retrieve the command to start Radius Distributor\n in all the cluster\n\n @param force: Apply force\n @type force: Boolean\n @rtype: String\n \"\"\"\n cmd = self.retrieve_rd_start(force)\n return self.retrieve_cluster_command(cmd, \"all\")\n ## END METHOD retrieve_cluster_rd_start( force )\n def retrieve_rd_start(self, force = True ):\n \"\"\"\n Function to retrieve the command to start Radius Distributor\n\n @param force: Apply force\n @type force: Boolean\n @rtype: String\n \"\"\"\n cmd_force = \"force\" if force else \"\"\n return self.__retrieve_command(\"RD_START\", cmd_force)\n ## End If\n ## END METHOD retrieve_rd_start( force )\n def retrieve_cluster_rd_stop(self, force = True ):\n \"\"\"\n Function to retrieve the command to stop Radius Distributor\n in all the cluster\n\n @param force: Apply force\n @type force: Boolean\n @rtype: String\n \"\"\"\n cmd = self.retrieve_rd_stop(force)\n return self.retrieve_cluster_command(cmd, \"all\")\n\n ## End If\n ## END METHOD retrieve_cluster_rd_stop( abrupt, force )\n def retrieve_rd_stop(self, force = True ):\n \"\"\"\n Function to retrieve the command to stop Radius Distributor\n\n @param force: Apply force\n @type force: Boolean\n @rtype: String\n \"\"\"\n cmd_force = \"force\" if force else \"\"\n return self.__retrieve_command(\"RD_STOP\", cmd_force)\n\n ## End If\n ## END METHOD retrieve_rd_stop( abrupt, force )\n def retrieve_rd_restart(self, force = True ):\n \"\"\"\n Function to retrieve the command to restart Radius Distributor\n\n @param force: Apply force\n @type force: Boolean\n @rtype: String\n \"\"\"\n cmd_force = \" force\" if force else \"\"\n return self.__retrieve_command(\"RD_RESTART\", cmd_force)\n ## END METHOD retrieve_rd_restart( force )\n def retrieve_show_peer(self, server_name):\n \"\"\"\n Function to retrieve the command to show a peer information.\n For cluster evolution newer versions the partition argument\n will be ignored\n\n @param server_name: Name of the peer to check\n @type server_name: String\n @rtype: String\n \"\"\"\n return self.__retrieve_command(\"SHOW_PEER\", server_name)\n ## END METHOD retrieve_show_peer( abrupt, force )\n def retrieve_status(self, verbose = True):\n \"\"\"\n Function to retrieve the command to show status of SASN\n\n @param verbose: Set verbose output\n @type verbose: Boolean\n @rtype: String\n \"\"\"\n _verbose = \"verbose\" if verbose else \"\"\n return self.__retrieve_command(\"SHOW_STATUS\", _verbose)\n ## END METHOD retrieve_cluster_rd_stop( abrupt, force )\n def retrieve_show_boot(self):\n \"\"\"\n Function to retrieve the command to show system show boot data of SASN\n\n @rtype: String\n \"\"\"\n return self.__retrieve_command(\"SHOW_BOOT\")\n ## END METHOD retrieve_cluster_rd_stop( abrupt, force )\n def retrieve_show_rd_boot(self):\n \"\"\"\n Function to retrieve the command to show system show rd-boot data of SASN\n @rtype: String\n \"\"\"\n return self.__retrieve_command(\"SHOW_RD_BOOT\")\n ## END METHOD retrieve_cluster_rd_stop( abrupt, force )\n def retrieve_load_configuration_backup(self, config_file_path):\n \"\"\"\n Function to retrieve the command to load SASN configuration file\n into the Backup PPU\n\n @param config_file_path: Path to the HL file\n @type config_file_path: String\n @rtype: String\n \"\"\"\n\n return self.__retrieve_command(\"LOAD_CFG_BCK\", config_file_path)\n\n ## End If\n ## END METHOD retrieve_load_configuration_backup( config_file_path )\n def retrieve_load_configuration_master(self, config_file_path):\n \"\"\"\n Function to retrieve the command to load SASN configuration file\n into the Master PPU\n\n @param config_file_path: Path to the HL file\n @type config_file_path: String\n @rtype: String\n \"\"\"\n return self.__retrieve_command(\"LOAD_CFG_MASTER\", config_file_path)\n\n ## End If\n ## END METHOD retrieve_load_configuration_master( config_file_path )\n def retrieve_load_configuration_cluster(self, config_file_path,\n cnt = False):\n \"\"\"\n Function to retrieve the command to load SASN configuration file\n into the Master PPU\n\n @param config_file_path: Path to the HL file\n @type config_file_path: String\n @param cnt: Add continue to the command\n @type cnt: Boolean\n @rtype: String\n \"\"\"\n command = \"\"\n if cnt:\n command = \"continue\"\n ## End If\n\n return self.__retrieve_command(\"LOAD_CFG_CLUSTER\", config_file_path, command)\n ## END METHOD retrieve_load_configuration_cluster( config_file_path )\n def retrieve_check_delta(self, config_file_path = \"\"):\n \"\"\"\n Function to retrieve the command to check delta configuration on SASN\n\n @param config_file_path: Path to the HL file\n @type config_file_path: String\n @rtype: String\n \"\"\"\n return self.__retrieve_command(\"CHECK_DELTA\", config_file_path)\n ## END METHOD retrieve_check_delta( config_file_path )\n def retrieve_apply_configuration(self, apply_mode = \"sequential\", cluster = False, \\\n p_timeout = 10, abrupt = True, rate = None,\\\n force = True, continue_apply = True):\n \"\"\"\n Function to retrieve the command to apply configuration to SASN\n\n @param cluster: Apply to all cluster\n @type cluster: Boolean\n @param apply_mode: Defines the mode to apply a config. Available values: parallel, local or sequential. Default value: sequential\n @type apply_mode: str\n @param p_timeout: Parallel timeout. When the apply_mode is set to \"parallel\", this value will be used as timeout.\n @type p_timeout: Integer\n @param abrupt: Do an abrupt apply\n @type abrupt: Boolean\n @param rate: If abrupt is false check this variable to see if\n a rate of session drop should be placed.\n @type rate: Integer\n @param force: Force apply\n @type force: Boolean\n @param continue_apply: Ignore errors\n @type continue_apply: Boolean\n @param local: Add local\n @type local: Boolean\n @rtype: String\n \"\"\"\n\n if cluster:\n _cluster = \"cluster\"\n else:\n _cluster = \"\"\n ## End If\n\n if apply_mode == \"parallel\":\n _sequential = \"parallel timeout %s\" % p_timeout\n elif apply_mode == \"local\":\n _sequential = \"local\"\n else:\n _sequential = \"sequential\"\n ## End If\n\n if abrupt:\n _abrupt = \"abrupt\"\n elif rate != None:\n _abrupt = \"rate %s\"% rate\n else:\n _abrupt = \"\"\n ## End If\n _force = \"force\" if force else \"\"\n _continue = \"continue\" if continue_apply else \"\"\n\n return self.__retrieve_command(\"APPLY_CFG\", _cluster, _sequential, \\\n _abrupt, _force, _continue)\n\n ## End If\n ## END METHOD retrieve_load_configuration_master( config_file_path )\n def retrieve_process_show(self,\n option = \"\",\n *args, **kwargs):\n \"\"\"\n Function to retrieve the command to show process configuration\n\n @param option: Defines the process options that you want to retrieve\n @type options: str\n @rtype: String\n \"\"\"\n\n assert option in [\"config\", \"detail\", \"information\", \"ipc\"]\n value = option\n\n if len(args) > 0:\n for extra_parameter in args:\n value += \" \" + extra_parameter\n ## End If\n return self.__retrieve_command(\"SHOW_PROC_CFG\", value)\n\n ## END METHOD retrieve_load_configuration_master( config_file_path )\n\n def retrieve_set_process(self, process, *args, **kwargs):\n \"\"\"\n Function to retrieve the command to activate or deactivate cores on a\n process\n\n @param process: Process name\n @type process: String\n @rtype: String\n \"\"\"\n extra_param = \"\"\n for param in args:\n extra_param += \" \" + param\n return self.__retrieve_command(\"SET_PROCESS\", process, extra_param)\n\n def retrieve_coredump_change(self, process, change_type = \"on\"):\n \"\"\"\n Function to retrieve the command to activate or deactivate cores on a\n process\n\n @param process: Process name\n @type process: String\n @param change_type: Values allowed( on, off ) to activate or deactivate\n CORE's into the process\n @type change_type: String\n @rtype: String\n \"\"\"\n return self.__retrieve_command(\"CHANGE_COREDUMP\", process, change_type)\n\n def retrieve_show_module_stat(self, module_name):\n \"\"\"\n Function to retrieve the command to show probe status\n\n @param partition: Partition number\n @type partition: Integer\n @param module_name: Name of the module\n @type module_name: String\n @rtype: String\n \"\"\"\n return self.__retrieve_command(\"MOD_SHOW_STAT\", module_name)\n\n ## End If\n ## END METHOD retrieve_show_module_stat( partition )\n# def retrieve_show_module_plugin_stat(self, partition, module, plugin,\\\n# virtualSessions = False):\n# \"\"\"\n# Function to retrieve the command to show plugin status\n#\n# @param partition: Partition number\n# @type partition: Integer\n# @param module: Module name\n# @type module: String\n# @param plugin: Plugin name\n# @type plugin: String\n# @param virtualSessions: Get virtual session stat\n# @type virtualSessions: Boolean\n# @rtype: String\n# \"\"\"\n# return self.__retrieve_command(\"MOD_SHOW_STAT\", partition,\\\n# module, plugin,\\\n# (\"virtual-sessions\" if virtualSessions else \"\") )\n# ## End If\n# ## END METHOD retrieve_show_module_plugin_stat( partition, module, plugin,\n# ## virtualSessions )\n\n def retrieve_show_module_plugin(self, module, plugin, option_stat, *args, **kwargs):\n \"\"\"\n Function to retrieve the command to show plugin status.\n\n The following option_stat are available:\n - For plugin relay:\n - \"rating_group\"\n - \"apr\"\n - \"qbau\"\n - \"deferred_charging\"\n - \"dynamic_charging\"\n - \"config\"\n - \"content_editor\"\n - \"garbage_collector\"\n - \"limits\"\n - \"statistics\"\n - \"session\"\n - \"virtual_class\"\n - \"virtual_session\"\n - \"tcp_retrasmit\"\n - \"topup_apns\"\n - \"shaper_session\"\n - \"statistics_queue\"\n - For plugin canalyzer:\n - \"rule_matches\"\n - \"extended_rule_hits_info\"\n - \"flow_summary\"\n - \"session_all\"\n - \"session_ip\": An IP should be provide as extra parameter (set at the first position of args)\n - \"session_id\" : An ID should be provide as extra parameter (set at the first position of args)\n - \"session_nai\" : An NAI should be provide as extra parameter (set at the first position of args)\n - \"session_imsi\" : An IMSI should be provide as extra parameter (set at the first position of args)\n - \"session_msid\" : An MSID should be provide as extra parameter (set at the first position of args)\n - \"p2p_cache\"\n - \"p2p_port_cache\"\n - \"p2p_group\"\n - \"p2p_pattern\"\n - \"p2p_detector\"\n - \"umc_report\"\n - \"umc_mk_report\"\n - \"dbc_rules\"\n - \"dbc_hosts\"\n - \"dbc_servers\"\n - \"dbc_timer\"\n - \"sig_running\"\n - \"sig_built\"\n - \"sig_protocol\"\n - \"detector_running\"\n - \"detector_built\"\n - \"dns_reporting_job_hosts\"\n - \"domain_reporting\"\n - \"domain_reporting_list\"\n - \"domain_reporting_jobs\"\n - \"rule_space_name\" : A rule space name should be provided as extra parameter (set at the first position of args)\n - \"pkt_mark\"\n - \"qos_information\"\n - \"routing_rules\"\n - \"analyzers\"\n - \"fields\"\n - \"flows\"\n - \"flow_tree\"\n - \"plugin\"\n - \"statistics_all\"\n - \"statistics_content_type\"\n - \"content_editor_matches\"\n - \"dpi_version\"\n - For plugin cfe:\n - \"cache\"\n - \"cache profile\"\n - \"profile\"\n - \"cache_plain\"\n - \"cache_verbose\"\n - \"profile_cache\"\n - \"statistics\"\n - \"session\"\n\n\n @param partition: Partition number\n @type partition: Integer\n @param module: Module name\n @type module: String\n @param plugin: Plugin name\n @type plugin: String\n @param option_stat: The option or stat to retrieve the information\n @type option_stat: str\n\n @rtype: String\n \"\"\"\n extra_value = \"\"\n if len(args) > 0:\n extra_value = args[0]\n\n dict_table_plugin = {\"sig_running\" : \"signatures\",\n \"sig_built\" : \"signatures\",\n \"sig_protocol\" : \"signatures\",\n \"detector_running\" : \"detectors\",\n \"detector_built\" : \"detectors\",\n \"sig_running\" : \"signatures\",\n \"qos_information\": \"pccrules\",\n \"pcc_rule\": \"pccrules\",\n \"pcc_rule_group\": \"pccrules\",\n \"pcc_rule_profile\": \"pccrules\",\n \"cache profile\": \"profile %s\" % extra_value,\n \"profile_cache\" : \"profile %s\" % extra_value,\n \"shaper_session\" : \"shaper\"\n }\n dict_table_option_stat = {\"rating_group\" : \"rating-group-control-statistics\",\n \"apr\" : \"apr-statistics\",\n \"qbau\" : \"qbau-statistics\",\n \"deferred_charging\" : \"deferred-charging-stats\",\n \"dynamic_charging\" : \"dynamic-charging-statistics\",\n \"config\" : \"config\",\n \"content_editor\" : \"content-editor-matches\",\n \"garbage_collector\" : \"garbage-collector\",\n \"limits\" : \"limits\",\n \"statistics\" : \"statistics\",\n \"session\" : \"session\",\n \"virtual_class\" : \"stat virtual-class\",\n \"virtual_session\" : \"virtual-session\",\n \"tcp_retrasmit\" : \"tcp-retransmit-stats\",\n \"topup_apns\" : \"topup-apns\",\n \"rule_matches\" : \"rule-matches\",\n \"extended_rule_hits_info\" : \"rule-matches extended-rule-hits-info\",\n \"flow_summary\" : \"flow-summary\",\n \"session_all\" : \"session all\",\n \"session_ip\" : \"session ip %s\" % extra_value,\n \"session_id\" : \"session id %s\" % extra_value,\n \"session_nai\" : \"session nai %s\" % extra_value,\n \"session_imsi\" : \"session imsi %s\" % extra_value,\n \"session_msid\" : \"session msid %s\" % extra_value,\n \"cfe_session\" : \"session %s\" % extra_value,\n \"cfe_session_all\" : \"session\",\n \"cfe_session_id\" : \"session id %s\" % extra_value,\n \"cfe_session_msisdn\" : \"session msisdn %s\" % extra_value,\n \"p2p_cache\" : \"p2p-cache\",\n \"p2p_port_cache\" : \"p2p-port-cache\",\n \"p2p_group\" : \"p2p-group-matches\",\n \"p2p_pattern\" : \"p2p-pattern-matches\",\n \"p2p_detector\" : \"p2p-detector-matches\",\n \"umc_report\" : \"umc-statistics\",\n \"umc_mk_report\" : \"umc-mk-statistics\",\n \"dbc_rules\" : \"dbc rules\",\n \"dbc_hosts\" : \"dbc hosts\",\n \"dbc_servers\" : \"dbc servers\",\n \"dbc_timer\" : \"dbc timer\",\n \"sig_running\" : \"version running\",\n \"sig_built\" : \"version built-in\",\n \"sig_protocol\" : \"protocols\",\n \"detector_running\" : \"version running\",\n \"detector_built\" : \"version built-in\",\n \"dns_reporting_job_hosts\" : \"dns-reporting-job %s hosts\" % extra_value,\n \"domain_reporting\" : \"domain-reporting statistics\",\n \"domain_reporting_jobs\": \"domain-reporting jobs\",\n \"domain_reporting_list\": \"domain-reporting list %s\" % extra_value,\n \"rule_space_name\" : \"rule-space %s\" % extra_value,\n \"pkt_mark\" : \"pkt-mark\",\n \"qos_information\": \"qos-information\",\n \"pcc_rule\": \"pcc-rule\",\n \"pcc_rule_group\": \"pcc-rule-group\",\n \"pcc_rule_profile\": \"pcc-rule-profile\",\n \"cache\": \"cache verbose\",\n \"cache profile\": \"cache verbose\",\n \"profile\": \"profile\",\n \"cache_plain\" : \"cache\",\n \"cache_verbose\": \"cache verbose\",\n \"profile_cache\": \"cache\",\n \"routing_rules\": \"routing-rules\",\n \"analyzers\" : \"analyzers\",\n \"fields\" : \"fields %s\" % extra_value,\n \"flows\" : \"flows %s\" % extra_value,\n \"flow_tree\" : \"flow-tree %s\" % extra_value,\n \"plugin\" : \"plugin\",\n \"statistics_all\" : \"statistics all\",\n \"shaper_session\" : \"session\",\n \"statistics_queue\" : \"statistics queue\",\n \"statistics_content_type\" : \"statistics content-type %s\" % extra_value,\n \"content_editor_matches\": \"content-editor-matches\",\n \"cdpi_version\": \"cdpi version\"}\n\n assert option_stat in dict_table_option_stat.keys(), \"Invalid option_stat [%s] will be found for pluging %s\" % (option_stat, plugin)\n\n if dict_table_plugin.get(option_stat):\n plugin += \" \" + dict_table_plugin.get(option_stat, \"\")\n value = dict_table_option_stat.get(option_stat)\n\n return self.__retrieve_command(\"MOD_PLG_SHOW\", module, plugin, value )\n ## End If\n ## END METHOD retrieve_show_module_plugin_stat( partition, module, plugin,\n ## * )\n def retrieve_show_module(self, module, *args, **kwargs):\n \"\"\"\n Function to retrieve the command to show\n from module\n\n Some extra parameter can be set using args (list of values) depending on the module:\n - \"session all\"\n - \"config\"\n - \"reconciliation\"\n - \"delete\"\n - \"redundancy\"\n - \"verbose\"\n - ...\n\n @param module: Module name\n @type module: String\n\n @rtype: String\n \"\"\"\n value = \"\"\n for option in args:\n value += \" \" + option\n\n no_cluster_options = {\"tsmssr\": [],\n \"rpcm\": [],\n \"broker\": [\"vm-instance\", \"status\"],\n }\n\n no_cluster = False\n if module in no_cluster_options.keys():\n if len(no_cluster_options[module]) > 0:\n for elem in args:\n if elem in no_cluster_options[module]:\n no_cluster = True\n break\n else:\n no_cluster = True\n\n\n if no_cluster:\n return self.__retrieve_command(\"MOD_SHOW_NO_CLUSTER\", module, value )\n else:\n return self.__retrieve_command(\"MOD_SHOW\", module, value )\n ## End If\n ## END METHOD retrieve_show_module( ... )\n\n def retrieve_clear_module(self, module, *args, **kwargs):\n \"\"\"\n Function to retrieve the command to clear\n from module\n\n @param module: Module name\n @type module: String\n @rtype: String\n \"\"\"\n value = \"\"\n for option in args:\n value += \" \" + option\n ## End If\n return self.__retrieve_command(\"MOD_CLEAR\", module, value )\n ## End If\n ## END METHOD retrieve_clear_module( ... )\n def retrieve_show_set(self, module, option, *args, **kwargs):\n \"\"\"\n Function to retrieve the command to set an option to the module.\n\n The options will depends the selected module.\n\n And it also depends of the option to add some extra parameters.\n\n @param partition: Partition number\n @type partition: Integer\n @param module: Module name\n @type module: String\n\n @rtype: String\n \"\"\"\n module_suffix_table = {\"redirect-agent\" : \"redirect-agent\"}\n\n value = \"\"\n for extra_param in args:\n value = \"%s %s\" % (value, extra_param)\n\n no_cluster_options = {\"ha\": [\"redundancy manual\", \"config-provisioning\", \"interface\",\n \"platform-health-lockfile\", \"subscriber \",\n \"redundancy exclude\", \"redundancy include\"],\n \"rdha\": [\"redundancy manual\", \"config-provisioning\",\n \"interface\", \"platform-health-lockfile\",\n \"subscriber \"],\n \"tsmssr\": [\"timeout pap\", \"timeout tssleep\", \"tsft_size\"],\n \"rpfm\": [\"alarm\"]\n }\n no_cluster = False\n if module in no_cluster_options.keys():\n if len(no_cluster_options[module]) > 0:\n if option in no_cluster_options[module]:\n no_cluster = True\n else:\n no_cluster = True\n\n if module_suffix_table.get(option):\n module += \" \" + module_suffix_table.get(option, \"\")\n option = \"\"\n\n if no_cluster:\n cmd = self.__retrieve_command(\"MOD_SET_NO_CLUSTER\", module, option, value )\n cmd.set_local(True)\n return cmd\n else:\n return self.__retrieve_command(\"MOD_SET\", module, option, value )\n ## End If\n\n ## End If\n\n ## End If\n ## END METHOD retrieve_show_set( ... )\n\n def retrieve_module_set_logging(self, module, level):\n \"\"\"\n Function to retrieve the command to set module logging\n\n @param module: Module name\n @type module: String\n @param level: The logging level to set\n @type level: int\n\n @param parameter: Extra parameters to be passed to the command\n @type parameter: String\n @rtype: String\n \"\"\"\n ## End If\n return self.__retrieve_command(\"MOD_SET_LOGGING\", \\\n module, \\\n level)\n ## End If\n ## END METHOD retrieve_module_set_logging( ... )\n\n def retrieve_show_delete(self, module, option, *args, **kwargs):\n \"\"\"\n Function to retrieve the command to delete an option from the module.\n\n The options will depends the selected module.\n\n And it also depends of the option to add some extra parameters.\n\n @param partition: Partition number\n @type partition: Integer\n @param module: Module name\n @type module: String\n\n @rtype: String\n \"\"\"\n value = \"\"\n for extra_param in args:\n value += \" \" + extra_param\n\n return self.__retrieve_command(\"MOD_DELETE\", module, option, value )\n ## END METHOD retrieve_show_delete( ... )\n\n def retrieve_clear_module_plugin(self, module, plugin, option_stat, *args, **kwargs):\n \"\"\"\n Function to retrieve the command to clear\n from plugin\n\n The following option_stat are available:\n - For plugin relay:\n - \"virtual_class\"\n - \"qbau\"\n - \"statistics\"\n - \"content_editor\"\n - \"deferred_charging\"\n - \"tcp_retrasmit\"\n - \"dynamic_charging\"\n - \"rating_group\"\n\n - For plugin canalyzer:\n - \"session_all\"\n - \"umc_report\"\n - \"umc_mk_report\"\n - \"p2p_cache\"\n - \"p2p_port_cache\"\n - \"p2p_group\"\n - \"p2p_pattern\"\n - \"p2p_detector\"\n - \"domain_reporting\"\n - \"domain_reporting_list\"\n - \"dbc_shallow_rules\"\n - \"content_editor_matches\"\n\n @param module: Module name\n @type module: String\n @param plugin: Plugin name\n @type plugin: String\n @param option_stat: The option or stat to clear information\n @type option_stat: str\n @rtype: String\n \"\"\"\n\n dict_table_option_stat = {\n \"virtual_class\" : \"statistics virtual-class\",\n \"session_all\" : \"session all\",\n \"qbau\" : \"qbau-statistics\",\n \"statistics\" : \"statistics\",\n \"content_editor\" : \"content-editor-matches\",\n \"deferred_charging\" : \"deferred-charging-stats\",\n \"tcp_retrasmit\" : \"tcp-retransmit-stats\",\n \"dynamic_charging\" : \"dynamic-charging-statistics\",\n \"rating_group\" : \"rating-group-control-statistics\",\n \"umc_report\" : \"umc-statistics\",\n \"umc_mk_report\" : \"umc-mk-statistics\",\n \"p2p_cache\" : \"p2p-cache\",\n \"p2p_port_cache\" : \"p2p-port-cache\",\n \"p2p_group\" : \"p2p-group-matches\",\n \"p2p_pattern\" : \"p2p-pattern-matches\",\n \"p2p_detector\" : \"p2p-detector-matches\",\n \"domain_reporting\" : \"domain-reporting statistics\",\n \"domain_reporting_list\" : \"domain-reporting list\",\n \"dbc_shallow_rules\": \"dbc-shallow-rules\",\n \"content_editor_matches\": \"content-editor-matches\",\n \"session\": \"session\"}\n\n value = dict_table_option_stat.get(option_stat)\n\n return self.__retrieve_command(\"MOD_PLG_CLEAR\", module, plugin, value )\n ## End If\n ## END METHOD retrieve_clear_module_plugin( partition, module, plugin,\n ## virtualSessions )\n def retrieve_delete_module_plugin(self, module, plugin, option_stat, *args, **kwargs):\n \"\"\"\n Function to retrieve the command to delete\n from plugin\n\n @param module: Module name\n @type module: String\n @param plugin: Plugin name\n @type plugin: String\n @param option_stat: The option or stat to clear information\n @type option_stat: str\n\n @rtype: String\n \"\"\"\n\n extra_value = \"\"\n if len(args) > 0:\n extra_value = args[0]\n dict_table_option_stat = {\n \"rule_matches\" : \"rule-matches\",\n \"session_all\" : \"session all\",\n \"session_id\" : \"session %s\" % extra_value,\n \"all_flows\" : \"all-flows %s\" % extra_value,\n \"cache\" : \"cache\"}\n\n value = dict_table_option_stat.get(option_stat)\n if option_stat == \"session_all\" and kwargs.get(\"rate\") != None:\n value += \" rate %s\" % kwargs.get(\"rate\")\n return self.__retrieve_command(\"MOD_PLG_DELETE\", module, plugin, value )\n ## End If\n ## END METHOD retrieve_delete_module_plugin( partition, module, plugin,\n ## virtualSessions )\n\n def retrieve_delete_module_plugin_profile(self, module, plugin, profile, option, *args, **kwargs):\n \"\"\"\n Function to retrieve the command to delete\n from plugin\n\n @param module: Module name\n @type module: String\n @param plugin: Plugin name\n @type plugin: String\n @param profile: Profile name\n @type profile: String\n @param option: The option to clear information\n @type option: str\n\n @rtype: String\n \"\"\"\n return self.__retrieve_command(\"MOD_PLG_DELETE_PROFILE\", module, plugin, profile, option)\n ## End If\n ## END METHOD retrieve_delete_module_plugin_profile( ... )\n\n def retrieve_set_module_plugin(self, module, plugin, option_stat, *args, **kwargs):\n \"\"\"\n Function to retrieve the command to set plugin\n\n @param module: Module name\n @type module: String\n @param plugin: Plugin name\n @type plugin: String\n @param option_stat: Availabe options: debug_internal_all, pkt_mark, domain_reporting\n @oaram option_stat: str\n\n @param enable: Enable/Disable a parameter in the plugin\n @type enable: Boolean\n @rtype: String\n \"\"\"\n value = \"\"\n if option_stat == \"debug_internal_all\":\n value = \"debug internal all\"\n\n elif option_stat == \"pkt_mark\":\n\n value = \"pkt-mark enable \"\n if kwargs.get(\"enable\"):\n value += \"on\"\n else:\n value += \"off\"\n ## End If\n elif option_stat == \"domain\":\n\n value = \"analyzer DNS config domain %s\" % kwargs.get(\"action\")\n ## End If\n elif option_stat == \"flow\":\n\n value = \"flow %s\" % kwargs.get(\"action\")\n ## End If\n elif option_stat == \"domain_reporting\":\n\n if kwargs.get(\"max_list_size\"):\n value = \"domain-reporting max-list-size %s\" % str(kwargs.get(\"max_list_size\"))\n else:\n raise Exception(\"Invalid arguments was found for domain_reporting options\")\n ## End If\n ## End If\n return self.__retrieve_command(\"MOD_PLG_SET\", module, plugin, value )\n ## End If\n ## END METHOD retrieve_set_module_plugin( partition, module, plugin,\n ## virtualSessions )\n def retrieve_xdr_configuration(self, xdr_type, option, reporting = False, *args, **kwargs):\n \"\"\"\n Function to retrieve the command to retrieve\n XDR configuration\n\n @param xdr_type: XDR Type\n @type xdr_type: String\n @param option: The available options are: sequence_file, binary_filename or filename\n @type option: str\n @param reporting: This flag indicates which file pattern should be used to read the XDR files: charging (default) or reporting\n @type reporting: bool\n\n @rtype: String\n \"\"\"\n value = \"\"\n if reporting:\n value = \"reporting \"\n\n if option == \"sequence_file\":\n value += \"sequence filename %s\" % args[0]\n elif option == \"binary_filename\":\n value += \"filename binary %s\" % args[0]\n elif option == \"filename\":\n value += \"filename %s\" % args[0]\n elif option == \"rotation interval\":\n extra_options = str(kwargs.get(\"time\"))\n if kwargs.get(\"force\"):\n extra_options += \" force\"\n value += \"rotation-interval %s\" % extra_options\n ## End If\n return self.__retrieve_command(\"XDR_CONFIG\", \\\n xdr_type, value )\n ## End If\n ## END METHOD retrieve_xdr_configuration( partition, module, plugin,\n ## virtualSessions )\n def retrieve_snmp_show(self, option, *args, **kwargs):\n \"\"\"\n Function to retrieve the command to show commands\n on SNMP\n\n @param option: Option to retrieve\n @type option: str\n\n @rtype: String\n \"\"\"\n assert option in [\"config\", \"event\", \"information\", \"mib\", \"status\"], \"Invalid option was requested as snmp option.\"\n value = option\n\n ## End If\n return self.__retrieve_command(\"SNMP_SHOW\", \\\n value )\n ## End If\n ## END METHOD retrieve_snmp_show( status )\n def retrieve_snmp_manual(self, option,\n event_number,\n event_text = \"\",\n event_level = \"\"):\n \"\"\"\n Function to retrieve the command to execute manual\n commands on SNMP\n\n @param option: this string value could be set with: clear or set\n @type option: str\n\n @param event_number: Event number to be set or clear\n @type event_number: String\n @param event_text: Additional text for the event\n @type event_text: String\n @param event_level: Event level\n @type event_level: String\n @rtype: String\n \"\"\"\n value = \"\"\n if option == \"clear\":\n value = \"clear %s\" % (event_number)\n elif option == \"set\":\n value = \"set %s\" % (event_number)\n ## End If\n if event_text != \"\" and event_text is not None:\n value += \" \\\"%s\\\"\" % event_text\n ## End If\n if event_level != \"\":\n value += event_level\n ## End If\n return self.__retrieve_command(\"SNMP_MANUAL\", \\\n value )\n ## End If\n ## END METHOD retrieve_snmp_manual( ... )\n\n def retrieve_show_system_config(self, option = \"\", *args, **kwargs):\n \"\"\"\n Function to retrieve the command to show system configuration\n\n @param option: Defines the config option that you want to retrieve\n @type options: str\n @rtype: String\n \"\"\"\n\n assert option in [\"running\", \"startup\"]\n value = option\n return self.__retrieve_command(\"SHOW_SYS_CONFIG\", value)\n ## END METHOD retrieve_show_system_config( ... )\n\n def retrieve_show_system_persistent_routes(self, *args, **kwargs):\n \"\"\"\n Function to retrieve the command to show system persistent routes\n\n @rtype: String\n \"\"\"\n\n return self.__retrieve_command(\"SHOW_SYS_PERSISTENT_ROUTES\")\n ## END METHOD retrieve_show_system_persistent_routes( ... )\n\n def retrieve_show_system_session(self, *args, **kwargs):\n \"\"\"\n Function to retrieve the command to show system session\n\n @param option: Defines the session option that you want to retrieve\n @type options: str\n @rtype: String\n \"\"\"\n if len(args) > 0:\n value = \"\"\n for extra_parameter in args:\n value += \" \" + extra_parameter\n ## End If\n return self.__retrieve_command(\"SHOW_SYS_SESSION\", value)\n ## END METHOD retrieve_show_system_session( ... )\n\n def retrieve_show_system_stats(self, option_stat, *args, **kwargs):\n \"\"\"\n Function to retrieve the command to show system\n statistics.\n\n The following options are available as option_stat:\n - \"server\"\n - \"process\"\n - \"bearer\"\n - \"service\"\n - \"gx\"\n - \"gy\"\n - \"rx\"\n - \"icap\"\n - \"ldap\"\n - \"process\"\n - \"qbau\"\n - \"shaper\"\n - \"aggregated_qos\"\n - \"content_filter\"\n - \"content_editor\"\n - \"tcp\"\n - \"tcp_deferred_charging\"\n - \"tcp_retransmitted_packets\"\n - \"charging_profile\"\n - \"rating_group_control\"\n - \"umc_report\"\n - \"umc_mk_report\"\n - \"pcc_rule_control\"\n - \"pcc_rule_qos\"\n - \"dr_rest\"\n - \"dr_job\"\n - \"event_reporting_ebm\"\n\n @param option_stat: One of the option showed above.\n @type option_stat: str\n\n @rtype: String\n \"\"\"\n\n\n dict_table_option_stat = {\n \"server\" : \"server\",\n \"process\" : \"process\",\n \"bearer\" : \"bearer\",\n \"service\" : \"service\",\n \"gx\" : \"gx\",\n \"gy\" : \"gy\",\n \"rx\" : \"rx\",\n \"icap\" : \"icap\",\n \"ldap\" : \"ldap\",\n \"process\" : \"process\",\n \"qbau\" : \"qbau-reporting\",\n \"shaper\" : \"shaper\",\n \"aggregated_qos\" : \"aggregated-qos\",\n \"content_filter\" : \"content-filter\",\n \"content_editor\" : \"content-editor\",\n \"tcp\" : \"tcp\",\n \"tcp_deferred_charging\" : \"tcp-deferred-charging\",\n \"tcp_retransmitted_packets\": \"tcp-retransmitted-packets\",\n \"charging_profile\" : \"charging-profile\",\n \"rating_group_control\": \"rating-group-control\",\n \"umc_report\" : \"umc-reporting\",\n \"umc_mk_report\" : \"umc-mk-reporting\",\n \"pcc_rule_control\" : \"pcc-rule-control\",\n \"pcc_rule_qos\" : \"pcc-rule-qos\",\n \"dr_rest\" : \"dr-rest\",\n \"dr_job\" : \"dr-job\",\n \"event_reporting_ebm\" : \"event-reporting-ebm\"}\n\n value = dict_table_option_stat.get(option_stat)\n\n return self.__retrieve_command(\"SHOW_SYS_STATS\", value )\n ## End If\n ## END METHOD retrieve_show_system_stats( ... )\n\n def retrieve_clear_system_statistics(self, module ):\n \"\"\"\n Function to retrieve the command to clear information\n from the statistics\n\n @param module: Name of the module to clear statistics\n @type module: String\n\n @rtype: String\n \"\"\"\n return self.__retrieve_command(\"CLEAR_SYS_STATS\", module)\n ## End If\n ## END METHOD retrieve_snmp_show( status )\n\n def retrieve_domain_reporting_system_command(self, option_stat, *args, **kwargs):\n \"\"\"\n Function to retrieve the command to show ns system\n domain-reporting option\n \"\"\"\n\n extra_value = \"\"\n if len(args) > 0:\n extra_value = args[0]\n\n dict_table_option_stat = {\n \"jobs\" : \"list jobs\",\n \"clear\" : \"clear list\",\n \"status\" : \"show status server %s\" % extra_value,\n \"hosts\": \"show hosts job %s\" % extra_value,\n \"report\" : \"report filters job %s\" % extra_value,\n \"filters\" : \"show filters job %s\" % extra_value}\n\n value = dict_table_option_stat.get(option_stat)\n\n return self.__retrieve_command(\"DOMAIN_REPORTING_SYS_CMD\", value)\n ## END METHOD retrieve_snmp_show( status )\n\n def retrieve_health_check(self):\n \"\"\"\n Function to retrieve the command to check health\n\n @rtype: str\n \"\"\"\n cmd = self.__retrieve_command(\"HEALTH_CHECK\")\n if type(cmd) == Command:\n cmd.set_local(True)\n return cmd\n ## END METHOD retrieve_health_check()\n\n def retrieve_check_cluster(self, target):\n \"\"\"\n Function to retrieve the command to check cluster\n\n @param target: Target platform or card\n @type target: str\n @rtype: str\n \"\"\"\n return self.__retrieve_command(\"CHECK_CLUSTER\", target)\n ## END METHOD retrieve_check_cluster()\n\n def retrieve_show_statistics(self ):\n \"\"\"\n Function to retrieve the command to show information\n from the statistics\n\n @rtype: String\n \"\"\"\n return self.__retrieve_command(\"STATISTICS\", \"information\")\n ## End If\n ## END METHOD retrieve_snmp_show( status )\n def retrieve_show_variable(self, name ):\n \"\"\"\n Function to retrieve the command to show a\n specific variable\n\n @param name: Name of the variable to show\n @type name: String\n\n @rtype: String\n \"\"\"\n return self.__retrieve_command(\"VAR_SHOW\",\n name)\n ## END METHOD retrieve_show_variable( ... )\n def retrieve_license_install(self,\n license_file ):\n \"\"\"\n Function to retrieve the command to install license\n file\n\n @param license_file: File path of the license file\n @type license_file: String\n @rtype: String\n \"\"\"\n return self.__retrieve_command(\"LICENSE_INSTALL\", license_file)\n ## END METHOD retrieve_license_install( ... )\n def retrieve_set_redundancy(self,\n master = False,\n slave = False,\n id = \"\" ):\n \"\"\"\n Function to retrieve the command to set redundancy.\n If both attributes are False set shmem to off\n\n @param master: Set as Master\n @type master: Boolean\n @param slave: Set as slave\n @type slave: Boolean\n @param id: If is different from \"\" will add the ID of the master\n @type id: String\n @rtype: String\n \"\"\"\n role = \"\"\n if master:\n role = \"master\"\n elif slave:\n role = \"slave\"\n else:\n role = \"off\"\n ## End If\n if id != \"\":\n role += \" id %s\" % id\n ## End If\n return self.__retrieve_command(\"SET_REDUNDANCY\", role)\n ## End If\n ## END METHOD retrieve_set_redundancy( ... )\n\n\n def retrieve_sinactivity_command(self, duration = True, \\\n inactivity = True,\n delete = False,\n extra_param = \"--seconds 1\"):\n \"\"\"\n Retrieve the command to enable/disable the testing mode described by feature.\n \"\"\"\n params = \"\"\n if duration:\n params += \" --duration\"\n if inactivity:\n params += \" --inactivity\"\n if delete:\n params += \" --delete\"\n\n params += \" \" + extra_param\n\n return self.__retrieve_command(\"SINACTIVITY_CMD\", params)\n\n\n ## END METHOD retrieve_sinactivity_command()\n def retrieve_shmsearch_cmd(self, ip_addr_list, *args, **kwargs):\n \"\"\"\n Function to retrieve the command to show the shared\n memory session IPs\n\n @param ip_addr_list: The output type. Available values: verbose or dump\n @type ip_addr_list: str\n\n @rtype: str\n \"\"\"\n param = \" \".join(ip_addr_list)\n\n return self.__retrieve_command(\"SHMSEARCH_CMD\", param)\n ## END METHOD retrieve_show_shmem( ... )\n\n def retrieve_show_shmem(self, option, output = \"\", *args, **kwargs):\n \"\"\"\n Function to retrieve the command to show the shared\n memory session IPs\n\n @param option: The option to show. Available values: all, local, id ID or ppu_name.\n @type option: Boolean\n @param output: The output type. Available values: verbose or dump\n @type output: str\n\n @rtype: String\n \"\"\"\n\n assert output in [\"\", \"verbose\", \"dump\"]\n if output != \"\":\n output = \" \" + output\n\n ## End If\n return self.__retrieve_command(\"SHOW_SHMEM\", option, output)\n ## End If\n ## END METHOD retrieve_show_shmem( ... )\n\n def retrieve_dump_shmem(self, option, *args, **kwargs):\n \"\"\"\n Function to retrieve the command to dump the shared memory session IPs\n\n @param option: The option to show. Available values: all, id ID or local.\n @type option: str\n\n @rtype: str\n \"\"\"\n return self.__retrieve_command(\"DUMP_SHMEM\", option)\n ## END METHOD retrieve_dump_shmem( ... )\n\n def retrieve_delete_shmem(self, option, *args, **kwargs):\n \"\"\"\n Function to retrieve the command to delete the shared\n memory or part of it\n\n @param option: The option to show. Available values: all, local, id ID or ipc.\n @type option: Boolean\n\n @rtype: String\n \"\"\"\n return self.__retrieve_command(\"DEL_SHMEM\", option)\n ## End If\n ## END METHOD retrieve_delete_shmem( ... )\n\n def retrieve_set_diagnostic(self, diagnostic_file, *args, **kwargs):\n \"\"\"\n Function to retrieve the command to create a diagnostic file.\n\n @param diagnostic_file: Defines the diagnostic file to create\n @type diagnostic_file: str\n @rtype: String\n \"\"\"\n return self.__retrieve_command(\"DIAGNOSTIC\", diagnostic_file)\n ## END METHOD retrieve_set_diagnostic( ... )\n\n def retrieve_management_backup(self, *args, **kwargs):\n \"\"\"\n Function to retrieve the command for management backup\n\n @rtype: str\n \"\"\"\n return self.__retrieve_command(\"MANAGEMENT_BACKUP\")\n ## END METHOD retrieve_management_backup( ... )\n\n def retrieve_management_capture(self, option, *args, **kwargs):\n \"\"\"\n Function to retrieve the command for management capture\n\n @param option: Capture option\n @type option: str\n @rtype: str\n \"\"\"\n return self.__retrieve_command(\"MANAGEMENT_CAPTURE\", option)\n ## END METHOD retrieve_management_capture( ... )\n\n def retrieve_management_set_backup(self, option, value, *args, **kwargs):\n \"\"\"\n Function to retrieve the command for\n\n @param option: Set backup option\n @type option: str\n @param value: Set backup value\n @type value: str\n @rtype: str\n \"\"\"\n return self.__retrieve_command(\"MANAGEMENT_SET_BACKUP\", option, value)\n ## END METHOD retrieve_management_set_backup( ... )\n\n def retrieve_management_trace(self, option, *args, **kwargs):\n \"\"\"\n Function to retrieve the command for\n\n @param option: Trace option\n @type option: str\n @rtype: str\n \"\"\"\n return self.__retrieve_command(\"MANAGEMENT_TRACE\", option)\n ## END METHOD retrieve_management_trace( ... )\n\n def retrieve_monitor_action(self, action, option, target = \"\"):\n \"\"\"\n Function to retrieve the command to do an action\n over the monitor\n\n @param action: Action preformed\n @type action: str\n @param option: Option of the action\n @type option: str\n @param target: Target of the action\n @type target: String\n @rtype: String\n \"\"\"\n\n return self.__retrieve_command(\"MONITOR_ACTION\", action, option, target)\n ## END METHOD retrieve_monitor_action( ... )\n def retrieve_rdmonitor_action(self, action, option, target = \"\"):\n \"\"\"\n Function to retrieve the command to do an action\n over the rdmonitor\n\n @param action: Action preformed\n @type action: str\n @param option: Option of the action\n @type option: str\n @param target: Target of the action\n @type target: String\n @rtype: String\n \"\"\"\n if target != \"\":\n target = \" \" + target\n return self.__retrieve_command(\"RDMONITOR_ACTION\", action, option, target)\n\n ## END METHOD retrieve_rdmonitor_action( ... )\n\n def retrieve_set_anon_session(self):\n \"\"\"\n Function to retrieve the command set anonymous section\n \"\"\"\n return self.__retrieve_command(\"SET_ANONYMOUS_SESSION\")\n ## END METHOD retrieve_set_anon_session()\n\n def retrieve_sasn_ebm_directory(self):\n \"\"\"\n Function to retrieve the SASN etc directory\n \"\"\"\n path = SASNPaths().get_sasn_ebm_folder()\n return self.__generate_command_path(path)\n ## END METHOD retrieve_sasn_ebm_directory()\n\n def retrieve_sasn_pdc_file_name_pattern(self, option):\n \"\"\"\n Function to retrieve the SASN pdc report file name patterns: daily, monthly, archive\n \"\"\"\n valid_options = {\"daily\": SASNPaths().get_pdc_daily_report_file_pattern(), \\\n \"monthly\": SASNPaths().get_pdc_monthly_report_file_pattern(), \\\n \"archive\": SASNPaths().get_pdc_archive_report_file_pattern()}\n if not option in valid_options.keys():\n raise InvalidArgument('option')\n\n return self.__generate_command_path(valid_options[option])\n ## END METHOD retrieve_sasn_pdc_file_name_pattern()\n\n def retrieve_sasn_pdc_data_directory(self, option = \"\", service_role = False):\n \"\"\"\n Function to retrieve the SASN pdc data directories\n - /var/sans/pdc/\n - /var/sans/pdc/daily_output/\n - /var/sans/pdc/monthly_ouput/\n - /var/sans/pdc/pdc_archive/\n - /var/sans/pdc/log\n \"\"\"\n valid_options = {\"\": \"\", \"daily\": \"daily_output/\", \"monthly\": \"monthly_output/\", \"archive\": \"pdc_archive/\", \"log\": \"log/\"}\n if not option in valid_options.keys():\n raise InvalidArgument('option')\n\n subdir = valid_options[option]\n path = \"\"\n if service_role:\n path = SASNPaths().get_pdc_service_role_data_directory()\n else:\n path = SASNPaths().get_pdc_data_directory()\n ## End If\n path = os.path.join(path, subdir)\n return self.__generate_command_path(path)\n ## END METHOD retrieve_sasn_pdc_data_directory()\n\n def retrieve_stat_location(self, stat_type):\n \"\"\"\n Function to retrieve the path to statistics files\n @param stat_type: String to define the stat to retrieve the folder. Available stats: offline, uri_report or oss):\n @type stat_type: str\n\n @rtype: String\n \"\"\"\n path = \"\"\n if stat_type == \"offline\":\n path = SASNPaths().get_offline_stat_folder()\n elif stat_type == \"uri_report\":\n path = SASNPaths().get_uri_stat_folder()\n elif stat_type == \"oss\":\n path = SASNPaths().get_oss_stat_folder()\n ## End If\n return self.__generate_command_path(path)\n ## END METHOD retrieve_stat_location( ... )\n\n def retrieve_sasn_hl_file_path(self):\n \"\"\"\n Function to retrieve the HL config file path\n \"\"\"\n path = SASNPaths().get_sasn_hl_file()\n return self.__generate_command_path(path)\n ## END METHOD retrieve_sasn_hl_file_path()\n def retrieve_sasn_ll_file_path(self):\n \"\"\"\n Function to retrieve the LL config file path\n \"\"\"\n path = SASNPaths().get_sasn_ll_file()\n return self.__generate_command_path(path)\n ## END METHOD retrieve_sasn_ll_file_path()\n\n def retrieve_sasn_ebm_spec_xml_file(self):\n \"\"\"\n Function to retrieve the HL config file path\n \"\"\"\n path = os.path.split(SASNPaths().get_sasn_ebm_file())[-1]\n return self.__generate_command_path(path)\n ## END METHOD retrieve_sasn_ebm_spec_xml_file()\n\n def retrieve_testing_mode_path(self, feature):\n \"\"\"\n Retrieve the command to enable/disable the testing mode described by feature.\n \"\"\"\n if feature == \"bypass-radius-client-delta\":\n tm_file = \".bypass-radius-client-delta\"\n tm_path = SASNPaths().get_sasn_configuration_folder()\n tm_path = self.__generate_command_path(tm_path)\n else:\n raise Exception(\"Impossible to retrieve the testing mode path. Invalid feature %s\" % feature)\n ## End if\n if type(tm_path) == Command:\n tm_path.command += tm_file\n else:\n tm_path += tm_file\n ## End If\n return tm_path\n ## END METHOD retrieve_testing_mode_path()\n def retrieve_xdr_location(self):\n \"\"\"\n Function to retrieve the path to XDR files\n\n @rtype: String\n \"\"\"\n\n return self.__generate_command_path(SASNPaths().get_xdr_folder())\n ## END METHOD retrieve_ssr_xdr_location( )\n\n def retrieve_software(self, action, module = \"\"):\n \"\"\"\n Function to retrieve the software information\n\n @param action: The actio to perform. Available values: history or information\n @type action: str\n @param module: The module to retrive the action. Default value is an empty string.\n @type module: str\n\n @rtype: String\n \"\"\"\n if module != \"\":\n module = \" \" + module\n\n return self.__retrieve_command(\"SOFTWARE\", action, module)\n ## END METHOD retrieve_software( )\n def retrieve_heur_conf_file(self):\n \"\"\"\n Function to retrieve the file path and name of the\n heuristics configuration file\n\n\n @rtype: String\n \"\"\"\n return self.__generate_command_path(SASNPaths().get_heuristic_configuration_file())\n ## END METHOD retrieve_heur_conf_file( )\n def retrieve_diam_app_param_set(self, server_name, parameter,\n enable = None):\n \"\"\"\n Function to retrieve the command to set an application parameter\n for a Diameter server\n\n @param server_name: Name of the diameter server\n @type server_name: str\n @param parameter: Parameter to be set\n @type parameter: str\n @param enable: Enable or disable a parameter\n @type enable: Boolean\n @rtype: String\n \"\"\"\n action = \"\"\n if enable:\n action = \"on\"\n elif enable == False:\n action = \"off\"\n ## End If\n return self.__retrieve_command(\"DIAM_APP_PARAM\", server_name, parameter, \\\n action)\n ## END METHOD retrieve_diam_app_param_set( )\n\n def _retrieve_validate(self, file_name = \"\" ):\n \"\"\"\n Function to retrieve the command to validate a configuration\n\n @param file_name: Name of the HL to validate, only used if hl is True\n @type file_name: String\n @rtype: String\n \"\"\"\n return self.__retrieve_command(\"CFG_VALIDATE_HL\", file_name)\n ## END METHOD retrieve_validate( ... )\n def _retrieve_commit(self, hl_file = \"\"):\n \"\"\"\n Function to retrieve the command to apply configuration to SASN\n\n @param hl_file: HL File path\n @type hl_file: String\n\n @rtype: String\n \"\"\"\n return self.__retrieve_command(\"CFG_COMMIT\", hl_file)\n ## END METHOD retrieve_validate( force )\n def retrieve_commit_status(self):\n \"\"\"\n Function to retrieve the command to retrieve the status of the\n command commit\n\n @rtype: String\n \"\"\"\n return self.__retrieve_command(\"CHECK_COMMIT_STATUS\")\n\n ## End If\n ## END METHOD retrieve_check_delta( )\n def retrieve_commit_clear(self):\n \"\"\"\n Function to retrieve the command to clear commit settings\n\n @rtype: String\n \"\"\"\n return self.__retrieve_command(\"COMMIT_CLEAR\")\n ## END METHOD retrieve_commit_clear( ... )\n def retrieve_commit_set(self, option, timeout = 0, abrupt = False, rate = None, cont = False, ):\n \"\"\"\n Function to retrieve the command to do apply commit settings\n\n @rtype: String\n \"\"\"\n assert option in [\"sequential\", \"parallel\"]\n value = option\n if option == \"parallel\":\n value += \" timeout \" + str(timeout) + \" all-appvms\"\n if abrupt:\n value += \" abrupt\"\n elif rate:\n value += \" rate \" + str(rate)\n if cont:\n value += \" continue\"\n return self.__retrieve_command(\"COMMIT_SET\", value)\n ## END METHOD retrieve_commit_set(... )\n def retrieve_commit_show(self, option):\n \"\"\"\n Function to retrieve the command to do show commit settings\n\n @param option: Option\n @type options: str\n @rtype: String\n \"\"\"\n assert option in [\"info\", \"status\"]\n return self.__retrieve_command(\"COMMIT_SHOW\", option)\n ## END METHOD retrieve_commit_show( ... )\n def retrieve_broker_status(self):\n \"\"\"\n Function to retrieve the command to get the broker status\n @rtype: Command\n \"\"\"\n\n return self.retrieve_show_module(\"broker\", \"status\")\n ## END METHOD retrieve_broker_status()\n def retrieve_broker_b2b(self, option, *args, **kwargs):\n \"\"\"\n Function to retrieve the command to show\n from module\n\n Some extra parameter can be set using args (list of values) depending on the module:\n - \"interface\"\n - ...\n\n @param option: Command option: interface, role, slave, remove\n @type option: String\n\n @rtype: String\n \"\"\"\n value = \"\"\n for extra_args in args:\n value += \" \" + extra_args\n\n return self.__retrieve_command(\"BROKER_B2B\", option, value )\n ## End If\n ## END METHOD retrieve_broker_b2b( ... )\n\n def retrieve_broker_stats(self):\n \"\"\"\n Function to retrieve the command to get the broker stats\n @rtype: Command\n \"\"\"\n return self.retrieve_show_module(\"broker\", \"stats\")\n ## END METHOD retrieve_broker_stats()\n def retrieve_broker_cards(self):\n \"\"\"\n Function to retrieve the command to get the broker cards\n @rtype: Command\n \"\"\"\n return self.__retrieve_command(\"BROKER_CARDS\")\n ## END METHOD retrieve_broker_cards()\n def retrieve_broker_hostname(self, hostname):\n \"\"\"\n Function to retrieve the command to get the broker cards\n @rtype: Command\n \"\"\"\n return self.__retrieve_command(\"BROKER_HOSTNAME\", hostname)\n ## END METHOD retrieve_broker_hostname()\n def retrieve_binaries_folder(self, entity=\"application\"):\n \"\"\"\n Function to retrieve the path to the SASN binaries folder\n B{entity} can have the following options:\n application: Application Entity path\n control: Control Entity path\n @param entity: Entity type\n @type entity: str\n @rtype: Command\n \"\"\"\n if \"application\" == entity:\n path = SASNPaths().get_sasn_bin_folder()\n elif \"control\" == entity:\n path = SASNPaths().get_ce_sasn_bin_folder()\n else:\n raise InvalidArgument(\"entity\", \"\", \"application, control\", entity)\n ## End If\n return self.__generate_command_path(path)\n ## END METHOD retrieve_binaries_folder()\n def retrieve_modules_folder(self, entity = \"application\"):\n \"\"\"\n Function to retrieve the path to the SASN modules folder\n @param entity: Location of the modules:\n \"control\" In the Control Entity\n \"application\" In the Application Entity\n @rtype: Command\n \"\"\"\n if \"application\" == entity:\n path = SASNPaths().get_sasn_modules_folder()\n elif \"control\" == entity:\n path = SASNPaths().get_ce_sasn_modules_folder()\n else:\n raise InvalidArgument(\"entity\", \"\", \"application, control\", entity)\n ## End If\n return self.__generate_command_path(path)\n ## END METHOD retrieve_modules_folder()\n def retrieve_statistics_path(self):\n \"\"\"\n Function to retrieve the path to the statistics folder in SSR\n @rtype: String\n \"\"\"\n path = SASNPaths().get_statistics_folder()\n return self.__generate_command_path(path)\n ## END METHOD retrieve_statistics_path()\n def retrieve_sasn_installation_path(self, location = None):\n \"\"\"\n Retrieve the location where SASN is installed for Oracle\n \"\"\"\n if location in [\"rp_card\", \"control_entity\"]:\n path = SASNPaths().get_ce_sasn_folder()\n else:\n path = SASNPaths().get_sasn_folder()\n ## End If\n return self.__generate_command_path(path)\n ## END METHOD retrieve_sasn_installation_path()\n def retrieve_process_start_stop(self,\n option,\n process_name = \"\"):\n \"\"\"\n Function to retrieve the command to start or stop process\n\n @param option: Defines if the process should start or stop\n @type options: str\n @param process_name: Name of the process\n @type process_name: str\n @rtype: String\n \"\"\"\n option_with_argument = [\"start\", \"stop\"]\n available_options = option_with_argument + [\"broker-start\", \"broker-stop\"]\n if option not in available_options:\n raise InvalidArgument(\"option\",\n possible_values = available_options,\n current_value = option)\n ## End If\n if option in option_with_argument:\n if process_name is None or len(process_name) == 0:\n raise ArgumentNotPresent(\"process_name\")\n ## End If\n process_name = \" %s\" % process_name\n ## End If\n\n return self.__retrieve_command(\"START_STOP_PROCESS\", option, process_name)\n ## END METHOD retrieve_process_start_stop( .. )\n def retrieve_recover(self, target):\n \"\"\"\n Function to retrieve the command to get the broker cards\n @rtype: Command\n \"\"\"\n if target != \"\":\n target = \" \" + target\n ## End If\n return self.__retrieve_command(\"RECOVER\", target)\n ## END METHOD retrieve_recover()\n\n def retrieve_reset_domain_reporting_status(self):\n \"\"\"\n Function to retrieve the command to get the broker cards\n @rtype: Command\n \"\"\"\n return self.__retrieve_command(\"RST_DOMAIN_REPORTING_STATUS\")\n ## END METHOD retrieve_reset_domain_reporting_status()\n def retrieve_domain_reporting_report_domain_job(self, id = \"all\"):\n \"\"\"\n Function to retrieve the command to get the report domain job command\n @rtype: Command\n \"\"\"\n if id.strip() == \"\":\n id = \"all\"\n elif id != \"all\":\n id = \"id \" + id\n return self.__retrieve_command(\"DOMAIN_REPORTING_REPORT_DOMAIN_JOB\", id)\n ## END METHOD retrieve_broker_cards()\n def retrieve_stop_all_sasn(self, abrupt = True, rate = None ):\n \"\"\"\n Function to retrieve the command to stop SASN\n\n @param abrupt: Add abrupt to the command\n @type abrupt: Boolean\n @param force: Apply force\n @type force: Boolean\n @rtype: String\n \"\"\"\n cmd_abr = \" abrupt\" if abrupt else \"\"\n cmd_rate = \" rate %s\" % rate if rate is not None else \"\"\n return self.__retrieve_command(\"SASN_STOP_ALL\", cmd_rate, cmd_abr)\n\n ## End If\n ## END METHOD retrieve_stop_all_sasn( abrupt force )\n def retrieve_log(self, target, msg):\n \"\"\"\n Function to retrieve the command to get the broker cards\n @rtype: Command\n \"\"\"\n return self.__retrieve_command(\"LOG\", target, msg)\n ## END METHOD retrieve_log()\n def retrieve_broker_file_transfer(self, transfer_type,\n hostname,\n source_file,\n destination_file):\n \"\"\"\n Function to retrieve the command to transfer a file\n from or to another host\n @param transfer_type: Type of transfer {put, get}\n @type transfer_type: str\n @param hostname: Hostname to transfer from or to\n @type hostname: str\n @param source_file: Source file path\n @type source_file: str\n @param destination_file: Destination file path\n @type destination_file: str\n\n @rtype: Command\n \"\"\"\n available_transfer = [\"get\", \"put\"]\n if transfer_type not in available_transfer:\n raise Exception(\"Invalid transfer mode, the available ones are %s!\" % available_transfer)\n ## End If\n return self.__retrieve_command(\"BROKER_FILE_TRANSFER\",\n hostname,\n transfer_type,\n source_file,\n destination_file)\n ## END METHOD retrieve_broker_file_transfer(...)\n\n def retrieve_host(self, hostname):\n \"\"\"\n Function to retrieve the command to transfer a file\n from or to another host\n @param hostname: Hostname to transfer from or to\n @type hostname: str\n\n @rtype: Command\n \"\"\"\n return self.__retrieve_command(\"HOST\",\n hostname)\n ## END METHOD retrieve_host(...)\n\n def retrieve_copy(self, transfer_type,\n source_file,\n destination_file):\n \"\"\"\n Function to retrieve the command to transfer a file\n from or to another host\n @param transfer_type: Type of transfer {put, get}\n @type transfer_type: str\n @param source_file: Source file path\n @type source_file: str\n @param destination_file: Destination file path\n @type destination_file: str\n\n @rtype: Command\n \"\"\"\n available_transfer = [\"get\", \"put\"]\n if transfer_type not in available_transfer:\n raise Exception(\"Invalid transfer mode, the available ones are %s!\" % available_transfer)\n ## End If\n return self.__retrieve_command(\"COPY\",\n transfer_type,\n source_file,\n destination_file)\n ## END METHOD retrieve_copy(...)\n\n def retrieve_installation(self, filename, *args):\n \"\"\"\n Function to retrieve the command to get the installation\n command\n extra arguments available:\n -B{force}: Force the installation\n -B{start}: Start\n -B{if-newer}: Install only if newer\n\n @param filename: Name of the file\n @type filename: str\n @rtype: Command\n \"\"\"\n force = \"\"\n start = \"\"\n newer = \"\"\n if \"force\" in args:\n force = \" force\"\n ## End If\n if \"start\" in args:\n start = \" start\"\n ## End If\n if \"if-newer\" in args:\n newer = \" if-newer\"\n ## End If\n return self.__retrieve_command(\"SASN_INSTALLATION\", filename, force, start, newer)\n ## END METHOD retrieve_log()\n def retrieve_migration(self, hlFile, comFile):\n \"\"\"\n Function to retrieve the command to migrate an HL file\n into a COM configuration file\n @param hlFile: HL File to be converted\n @type hlFile: str\n @param comFile: COM output file\n @type comFile: str\n @rtype: Command\n \"\"\"\n return self.__retrieve_command(\"MIGRATION\", hlFile, comFile)\n ## END METHOD retrieve_log()\n def retrieve_rollback(self, dist_name, DID, *args, **kwargs):\n \"\"\"\n Function to retrieve the command to get the installation\n command\n extra arguments available:\n -B{force}: Force the installation\n -B{CID=value}: Load a specific configuration after rollback\n\n @param dist_name: Name of the distribution to rollback\n @type dist_name: str\n @param DID: Distribution ID\n @type DID: int\n @rtype: Command\n \"\"\"\n force = \"\"\n load = \"\"\n if \"force\" in args or \"force\" in kwargs:\n force = \" force\"\n ## End If\n if \"CID\" in kwargs:\n load = \" load %s\" % kwargs[\"CID\"]\n ## End If\n return self.__retrieve_command(\"SASN_ROLLBACK\", dist_name, DID, force, load)\n ## END METHOD retrieve_rollback()\n def retrieve_install_heuristics(self, filepath):\n \"\"\"\n Function to retrieve the command to install a new heuristics\n package\n @param filepath: File path to the new package\n @type filepath: str\n @rtype: Command\n \"\"\"\n return self.__retrieve_command(\"INSTALL_HEURISTICS\", filepath)\n ## END METHOD retrieve_install_heuristics()\n def retrieve_update_heuristics(self, filepath):\n \"\"\"\n Function to retrieve the command to update a new heuristics\n package\n @param filepath: File path to the new package\n @type filepath: str\n @rtype: Command\n \"\"\"\n return self.__retrieve_command(\"UPDATE_HEURISTICS\", filepath)\n ## END METHOD retrieve_update_heuristics()\n def retrieve_validate_heuristics(self):\n \"\"\"\n Function to retrieve the command to validate the previously\n installed heuristics package\n @rtype: Command\n \"\"\"\n return self.__retrieve_command(\"VALIDATE_HEURISTICS\")\n ## END METHOD retrieve_validate_heuristics()\n def retrieve_apply_heuristics(self):\n \"\"\"\n Function to retrieve the command to apply the previously\n installed heuristics package\n @rtype: Command\n \"\"\"\n return self.__retrieve_command(\"APPLY_HEURISTICS\")\n ## END METHOD retrieve_validate_heuristics()\n def retrieve_security_change(self, action, *args):\n \"\"\"\n Function to retrieve the command to enable/disable\n or show the security\n @param action: Action to be performed:\n -B{set}: changes the configuration\n -B{show}: Show the current configuration\n @type action: str\n @param args: List with options:\n -B{enable}: Used with 'set' enables the security\n -B{disable}: Used with 'set' disable the security\n -B{default}: Set the default password \"root\" for root user\n @type args: list\n @rtype: Command\n \"\"\"\n extra_options = \"\"\n if \"set\" == action:\n if \"enable\" in args:\n extra_options = \"enable\"\n elif \"disable\" in args:\n extra_options = \"disable\"\n elif \"default\" in args:\n extra_options = \"default\"\n ## End If\n ## End If\n return self.__retrieve_command(\"SECURITY_CHANGE\", action, extra_options)\n ## END METHOD retrieve_security_change()\n def retrieve_check_root_password(self, *args, **kwargs):\n \"\"\"\n Function to check if the root password is correct\n \"\"\"\n return self.__retrieve_command(\"CHECK_ROOT_PASSWORD\", *args, **kwargs)\n ## END METHOD retrieve_change_centralized_password\n def retrieve_run_change_root_password(self, *args, **kwargs):\n \"\"\"\n Function to change the root password in a centralized way\n \"\"\"\n return self.__retrieve_command(\"RUN_CHANGE_ROOT_PASSWORD\", *args, **kwargs)\n ## END METHOD retrieve_change_centralized_password_\n def retrieve_change_root_password(self, *args, **kwargs):\n \"\"\"\n Function to execute a command to change the root password in a centralized way\n \"\"\"\n return self.__retrieve_command(\"CHANGE_ROOT_PASSWORD\", *args, **kwargs)\n ## END METHOD retrieve_change_root_password\n def retrieve_run_and_check_ns_command(self, *args, **kwargs):\n \"\"\"\n Function to execute the script perform_ns_command\n \"\"\"\n return self.__retrieve_command(\"RUN_AND_CHECK_NS_COMMAND\", *args, **kwargs)\n ## END METHOD retrieve_run_ns_command()\n def retrieve_run_and_check_su_user(self, *args, **kwargs):\n \"\"\"\n Function to execute the script run_and_check_su_user\n \"\"\"\n return self.__retrieve_command(\"RUN_AND_CHECK_SU_USER\", *args, **kwargs)\n ## END METHOD retrieve_run_and_check_su_user()\n def retrieve_icap_set_mode(self, server, *args, **kwargs):\n \"\"\"\n Function to retrieve the command to set ICAP mode\n\n @param server: ICAP server\n @type server: str\n @rtype: str\n \"\"\"\n value = \"\"\n for option in args:\n value += \" \" + option\n ## End For\n return self.__retrieve_command(\"ICAP_SET_MODE\", server, value)\n ## End If\n ## END METHOD retrieve_icap_set_mode( ... )\n def retrieve_icap_set_server(self, server, *args, **kwargs):\n \"\"\"\n Function to retrieve the command to set ICAP server option\n\n @param server: ICAP server\n @type server: str\n @rtype: str\n \"\"\"\n value = \"\"\n for option in args:\n value += \" \" + option\n ## End For\n return self.__retrieve_command(\"ICAP_SET_SERVER\", server, value)\n ## End If\n ## END METHOD retrieve_icap_set_server( ... )\n def retrieve_icap_set_transaction(self, server, *args, **kwargs):\n \"\"\"\n Function to retrieve the command to set ICAP transaction option\n\n @param server: ICAP server\n @type server: str\n @rtype: str\n \"\"\"\n value = \"\"\n for option in args:\n value += \" \" + option\n ## End For\n return self.__retrieve_command(\"ICAP_SET_TRANSACTION\", server, value)\n ## End If\n ## END METHOD retrieve_icap_set_transaction( ... )\n def retrieve_icap_show_config(self, server, *args, **kwargs):\n \"\"\"\n Function to retrieve the command to show ICAP config\n\n @param server: ICAP server\n @type server: str\n @rtype: str\n \"\"\"\n return self.__retrieve_command(\"ICAP_SHOW_CONFIG\", server)\n ## End If\n ## END METHOD retrieve_icap_show_config( ... )\n def retrieve_probe_reset(self, link, *args, **kwargs):\n \"\"\"\n Function to retrieve the command to reset probe\n\n @rtype: str\n \"\"\"\n return self.__retrieve_command(\"PROBE_RESET\", link)\n ## End If\n ## END METHOD retrieve_probe_reset( ... )\n\n def retrieve_module_show_config(self, *args, **kwargs):\n \"\"\"\n Function to retrieve the command for module show config\n\n @rtype: str\n \"\"\"\n return self.__retrieve_command(\"MODULE_SHOW_CONFIG\")\n ## End If\n ## END METHOD retrieve_module_show_config( ... )\n\n def retrieve_monitor_show_config(self, *args, **kwargs):\n \"\"\"\n Function to retrieve the command for monitor show config\n\n @rtype: str\n \"\"\"\n return self.__retrieve_command(\"MONITOR_SHOW_CONFIG\")\n ## End If\n ## END METHOD retrieve_monitor_show_config( ... )\n def retrieve_partition_set(self, partition, *args, **kwargs):\n \"\"\"\n Function to retrieve the command for partition set\n\n @param partition: Partition\n @type partition: int\n @rtype: str\n \"\"\"\n return self.__retrieve_command(\"PARTITION_SET\", partition)\n ## END METHOD retrieve_partition_set( ... )\n\n def retrieve_partition_show_current(self, *args, **kwargs):\n \"\"\"\n Function to retrieve the command for partition set\n\n @rtype: str\n \"\"\"\n return self.__retrieve_command(\"PARTITION_SHOW_CURRENT\")\n ## END METHOD retrieve_partition_show_current( ... )\n def retrieve_partition_show_information(self, *args, **kwargs):\n \"\"\"\n Function to retrieve the command for partition show information\n\n @rtype: str\n \"\"\"\n return self.__retrieve_command(\"PARTITION_SHOW_INFORMATION\")\n ## END METHOD retrieve_partition_show_information( ... )\n\n def retrieve_variable_show(self, variable, *args, **kwargs):\n \"\"\"\n Function to retrieve the command for variable show\n\n @param variable: Variable\n @type variable: str\n @rtype: str\n \"\"\"\n return self.__retrieve_command(\"VARIABLE_SHOW\", variable)\n ## END METHOD retrieve_variable_show( ... )\n\n def retrieve_system_boot(self, module, option, value = \"\", *args, **kwargs):\n \"\"\"\n Function to retrieve the command for system boot\n\n @param module: Module\n @type module: str\n @param option: Option\n @type option: str\n @param value: Value\n @type value: str\n @rtype: str\n \"\"\"\n if value != \"\":\n value = \" \" + value\n return self.__retrieve_command(\"SYSTEM_BOOT\", module, option, value)\n ## END METHOD retrieve_system_boot( ... )\n\n def retrieve_system_set_config(self, option, value, *args, **kwargs):\n \"\"\"\n Function to retrieve the command for system set config\n\n @param option: Option\n @type option: str\n @param value: Value\n @type value: str\n @rtype: str\n \"\"\"\n return self.__retrieve_command(\"SYSTEM_SET_CONFIG\", option, value)\n ## END METHOD retrieve_system_set_config( ... )\n\n def retrieve_system_set_pdc(self, option, *args, **kwargs):\n \"\"\"\n Function to retrieve the command for system set pdc\n\n @param option: enable\n @type option: str\n @param value: dailyprocessing\n @type value: str\n @rtype: str\n \"\"\"\n options = {\"enable\": \"enable on\", \\\n \"disable\": \"enable off\"}\n assert option in options.keys(), \\\n \"retrieve_system_set_pdc: option %s not allowed. Available options: %s\" % (option, str(options))\n option = options[option]\n dailyprocessing = kwargs.get(\"dailyprocessing\", None)\n if dailyprocessing:\n dailyprocessing = \" dailyprocessing \" + str(dailyprocessing)\n else:\n dailyprocessing = \"\"\n\n return self.__retrieve_command(\"SYSTEM_SET_PDC\", option, dailyprocessing)\n ## END METHOD retrieve_system_set_pdc( ... )\n\n def retrieve_system_show(self, option, value = \"\", *args, **kwargs):\n \"\"\"\n Function to retrieve the command for system set config\n\n @param option: Option\n @type option: str\n @param value: Value\n @type value: str\n @rtype: str\n \"\"\"\n if value != \"\":\n value = \" \" + value\n return self.__retrieve_command(\"SYSTEM_SHOW\", option, value)\n ## END METHOD retrieve_system_show( ... )\n\n def retrieve_system_wizard_cluster(self, option, *args, **kwargs):\n \"\"\"\n Function to retrieve the command for system wizard cluster\n\n @param option: Option\n @type option: str\n @rtype: str\n \"\"\"\n value = \"\"\n if len(args) > 0:\n for arg in args:\n value += \" \" + arg\n return self.__retrieve_command(\"SYSTEM_WIZARD_CLUSTER\", option, value)\n ## END METHOD retrieve_system_show( ... )\n\n def retrieve_version(self, *args, **kwargs):\n \"\"\"\n Function to retrieve the command for version\n\n @rtype: str\n \"\"\"\n return self.__retrieve_command(\"VERSION\")\n ## END METHOD retrieve_system_show( ... )\n\n def retrieve_dpi_version(self, *args, **kwargs):\n \"\"\"\n Function to retrieve the command for version\n\n @rtype: str\n \"\"\"\n return self.__retrieve_command(\"VERSION\")\n ## END METHOD retrieve_system_show( ... )\n\n def retrieve_check_consistency(self, *args, **kwargs):\n \"\"\"\n Function to retrieve the command for check-consistency\n\n @rtype: str\n \"\"\"\n return self.__retrieve_command(\"CHECK_CONSISTENCY\")\n ## END METHOD retrieve_check_consistency( ... )\n def retrieve_tmp_folder(self, *args, **kwargs):\n \"\"\"\n Function to retrieve the tmp folder path\n\n @rtype: str\n \"\"\"\n path = \"/tmp/\"\n if \"control\" in args:\n if \"sasn\" in args:\n path = SASNPaths().get_ce_sasn_tmp_folder()\n ## End If\n elif \"application\" in args:\n if \"sasn\" in args:\n path = SASNPaths().get_sasn_tmp_folder()\n ## End If\n ## End If\n return self.__generate_command_path(path)\n ## END METHOD retrieve_tmp_folder( ... )\n\n\n def retrieve_migrate(self, options, *args, **kwargs):\n \"\"\"\n Function to retrieve the command to for migrate\n\n @rtype: Command\n \"\"\"\n return self.__retrieve_command(\"MIGRATE\", options)\n ## END METHOD retrieve_migrate( ... )\n\n def retrieve_config_rpfm(self, option, *args, **kwargs):\n \"\"\"\n Function to retrieve the command for config rpfm\n\n @param option: Option\n @type option: str\n @rtype: str\n \"\"\"\n return self.__retrieve_command(\"CONFIG_RPFM\", option)\n ## END METHOD retrieve_config_rpfm( ... )\n\n def retrieve_config_rpcm(self, option, value, *args, **kwargs):\n \"\"\"\n Function to retrieve the command for config rpcm\n\n @param option: Option\n @type option: str\n @param value: Value\n @type value: str\n @rtype: str\n \"\"\"\n return self.__retrieve_command(\"CONFIG_RPCM\", option, value)\n ## END METHOD retrieve_config_rpcm( ... )\n\n def retrieve_cat(self, filename, *args, **kwargs):\n \"\"\"\n Function to retrieve the command for cat\n\n @param filename: File name\n @type filename: str\n @rtype: str\n \"\"\"\n return self.__retrieve_command(\"CAT\", filename)\n ## END METHOD retrieve_cat( ... )\n\n def retrieve_zcat(self, filename, *args, **kwargs):\n \"\"\"\n Function to retrieve the command for zcat\n\n @param filename: File name\n @type filename: str\n @rtype: str\n \"\"\"\n return self.__retrieve_command(\"ZCAT\", filename)\n ## END METHOD retrieve_zcat( ... )\n\n def retrieve_df(self, *args, **kwargs):\n \"\"\"\n Function to retrieve the command for df\n\n @rtype: str\n \"\"\"\n return self.__retrieve_command(\"DF\")\n ## END METHOD retrieve_df( ... )\n\n def retrieve_free(self, *args, **kwargs):\n \"\"\"\n Function to retrieve the command for free\n\n @rtype: str\n \"\"\"\n return self.__retrieve_command(\"FREE\")\n ## END METHOD retrieve_free( ... )\n\n def retrieve_ls(self, directory, options = \"\", *args, **kwargs):\n \"\"\"\n Function to retrieve the command for ls\n\n @param directory: Directory\n @type directory: str\n @param options: Options\n @type options: str\n @rtype: str\n \"\"\"\n if options != \"\":\n options = options + \" \"\n return self.__retrieve_command(\"LS\", options, directory)\n ## END METHOD retrieve_ls( ... )\n\n def retrieve_ps(self, *args, **kwargs):\n \"\"\"\n Function to retrieve the command for ps\n\n @rtype: str\n \"\"\"\n return self.__retrieve_command(\"PS\")\n ## END METHOD retrieve_ps( ... )\n\n def retrieve_tail(self, numlines, filename, *args, **kwargs):\n \"\"\"\n Function to retrieve the command for tail\n\n @param numlines: Number of lines\n @type numlines: int\n @param filename: File name\n @type filename: str\n @rtype: str\n \"\"\"\n return self.__retrieve_command(\"TAIL\", numlines, filename)\n ## END METHOD retrieve_tail( ... )\n\n def retrieve_top(self, options = \"\", *args, **kwargs):\n \"\"\"\n Function to retrieve the command for top\n\n @param options: Options\n @type options: str\n @rtype: str\n \"\"\"\n if options != \"\":\n options = \" \" + options\n return self.__retrieve_command(\"TOP\", options)\n ## END METHOD retrieve_top( ... )\n def retrieve_rm(self, file_name = \"\", *args, **kwargs):\n \"\"\"\n Function to retrieve the command for ns rm\n\n @param file_name: file name\n @type file_name: str\n @rtype: str\n \"\"\"\n return self.__retrieve_command(\"RM\", file_name)\n ## END METHOD retrieve_rm( ... )\n def retrieve_uptime(self, *args, **kwargs):\n \"\"\"\n Function to retrieve the command for uptime\n\n @rtype: str\n \"\"\"\n return self.__retrieve_command(\"UPTIME\")\n ## END METHOD retrieve_uptime( ... )\n def retrieve_security_hack_filename(self):\n \"\"\"\n Function to retrieve the name of the file that do the hack\n @rtype: str\n \"\"\"\n path = SASNPaths().get_security_hack_filename()\n return self.__generate_command_path(path)\n ## END METHOD retrieve_security_hack_filename( ... )\n\n def retrieve_security_hack_injector_filepath(self, add_filename = True):\n \"\"\"\n Function to retrieve the command for uptime\n @param add_filename: If enables the filename will be added\n @type add_filename: bool\n @rtype: str\n \"\"\"\n path = SASNPaths().get_security_hack_injector()\n if add_filename:\n path = \"\".join([path, SASNPaths().get_security_hack_filename()])\n ## End If\n return self.__generate_command_path(path)\n ## END METHOD retrieve_security_hack_injector_filepath( ... )\n def retrieve_sos_command(self, action = \"start\"):\n \"\"\"\n Function to retrieve the command to stop/start/restart sos in the RP\n @param action: Action to be dne in SOS\n @type action: bool\n @rtype: str\n \"\"\"\n return self.__retrieve_command(\"SOS_COMMAND\", action)\n ## END METHOD retrieve_sos_command( ... )\n def retrieve_tsmssr_clean(self, to_clean = \"all\"):\n \"\"\"\n Function to retrieve the command clean the TSMSSR configuration\n @param to_clean: What should be cleaned\n - B{all} Clean everything\n - B{smartnic} Clean SmartNIC entries\n @type to_clean: str\n @rtype: str\n \"\"\"\n args = \"\"\n if \"smartnic\" == to_clean:\n args = \"-s\"\n ## End If\n return self.__retrieve_command(\"TSMSSR_CLEAN\", args)\n ## END METHOD retrieve_tsmssr_clean( ... )\n def retrieve_tsm_smaller_tables_file(self, enable = True):\n \"\"\"\n Function to retrieve the command clean the TSMSSR configuration\n @param to_clean: What should be cleaned\n - B{all} Clean everything\n - B{smartnic} Clean SmartNIC entries\n @type to_clean: str\n @rtype: str\n \"\"\"\n args = \"\"\n if enable:\n cmd_start = \"touch\"\n else:\n cmd_start = \"rm\"\n ## End If\n cmd = \" \".join([cmd_start, SASNPaths().get_tsm_small_table_file()])\n return self.__generate_command_path(cmd)\n ## END METHOD retrieve_tsm_smaller_tables_file( ... )\n def retrieve_cpuchk_local_path(self):\n \"\"\"\n Function to retrieve the local path where the script cpuchk is found\n @rtype: str\n \"\"\"\n return self.__retrieve_command(\"CPUCHK_LOCAL_PATH\")\n ## END METHOD retrieve_security_hack_filename( ... )\n def retrieve_cpuchk_remote_path(self):\n \"\"\"\n Function to retrieve the remote path where the script cpuchk is found\n @rtype: str\n \"\"\"\n return self.__retrieve_command(\"CPUCHK_REMOTE_PATH\")\n ## END METHOD retrieve_security_hack_filename( ... )\n def retrieve_cpuchk_command(self,\n injector_time = None,\n alarm_time = None,\n log_delay = None,\n **kwargs):\n \"\"\"\n Function to retrieve the command to execute script cpuchk\n @param injector_time: Time in the injector\n @type injector_time: str\n @param alarm_time: Alarm time\n @type alarm_time: str\n @param log_delay: Log delay in micro seconds\n @type log_delay: str\n @rtype: str\n \"\"\"\n options = \"\"\n if injector_time is not None:\n options += \" --injector-time %s\" % injector_time\n ## End If\n if alarm_time is not None:\n options += \" --alarm %s\" % alarm_time\n ## End If\n if log_delay is not None:\n options += \" --logdelay %s\" % log_delay\n ## End If\n cmd_path = self.retrieve_cpuchk_remote_path()\n if isinstance(cmd_path, Command):\n cmd_path = cmd_path.get_command()\n ## End If\n return self.__retrieve_command(\"CPUCHK_COMMAND\",\n cmd_path,\n options)\n ## END METHOD retrieve_security_hack_filename( ... )\n def retrieve_set_canalyzer_config(self,\n parameter,\n value,\n **kwargs):\n \"\"\"\n Function to retrieve the command to execute script cpuchk\n @param parameter: Name parameter to change\n @type parameter: str\n @param value: Value of the parameter\n @type value: str\n @rtype: str\n \"\"\"\n options = \"\"\n if \"ignore-filter-ip-src\" in parameter:\n options = \"analyzer MASCS config %s\" % parameter\n if value:\n options += \" true\"\n else:\n options += \" false\"\n ## End If\n ## End If\n return self.__retrieve_command(\"MOD_PLG_SET\",\n \"scm\",\n \"canalyzer\",\n options)\n ## END METHOD retrieve_set_canalyzer_config( ... )\n def retrieve_management_memdomain(self, option, *args, **kwargs):\n \"\"\"\n Function to retrieve the command to show memdomain parameters\n from module\n\n Some extra parameter can be set using args (list of values) depending on the module:\n - \"cpu set\"\n - ...\n\n @param option: Command option: apply, cpualias all, cpualias foreground, set, huge-pages-total-2M\n @type option: String\n\n @rtype: String\n \"\"\"\n value = \"\"\n for extra_args in args:\n value += \" \" + extra_args\n\n return self.__retrieve_command(\"MEMDOMAIN\", option, value )\n ## End If\n ## END METHOD retrieve_management_memdomain( ... )\n def retrieve_memory_benchmark(self, process, allocation_type, size):\n \"\"\"\n Function to retrieve the command to show memory benchmark\n\n @param process: Name of SASN process\n @type process: str\n @param allocation_type: Type of memoy allocation (B{mmap} of B{malloc})\n @type allocation_type: str\n @param process: Size in MB to test\n @type process: int\n\n @rtype: String\n \"\"\"\n return self.__retrieve_command(\"MEMORY_BENCHMARK\", process, allocation_type, size)\n ## End If\n ## END METHOD retrieve_memory_benchmark( ... )\n def retrieve_memory(self):\n \"\"\"\n Function to retrieve the command to show memory of SASN\n\n @rtype: String\n \"\"\"\n return self.__retrieve_command(\"SASN_MEMORY\")\n ## END METHOD retrieve_memory()\n def retrieve_xml_file_path(self, add_name = True, validate = True ):\n \"\"\"\n Function to retrieve the path to the XML file\n with COM configuration\n\n @param add_name: Add the filename also\n @type add_name: Boolean\n @param validate: Retrieve XML validate file or the commit file\n @type validate: Boolean\n @rtype: String\n \"\"\"\n command = \"\"\n if add_name:\n command = self.retrieve_xml_filename(validate).command\n ## End If\n path = SASNPaths().get_xml_file_location()\n path += command\n return self.__generate_command_path(path)\n ## END METHOD retrieve_xml_filename( )\n def retrieve_xml_filename(self, validate = True ):\n \"\"\"\n Function to retrieve the name of the XML file\n with COM configuration\n\n @rtype: String\n \"\"\"\n filename = \"\"\n if validate:\n filename = SASNPaths().get_xml_validate_file_name()\n else:\n filename = SASNPaths().get_xml_commit_file_name()\n ## End If\n return self.__generate_command_path(filename)\n ## END METHOD retrieve_xml_filename( )\n\n def retrieve_log_location(self, domain, log_type):\n \"\"\"\n Function to retrieve the location of the logs from the different\n cards and the different applications\n The available domains are:\n -B{rp_card} Log from RP Card\n -B{ssc_card} Log from SSC Card\n -B{line_card} Log from Line Card\n The available log types are:\n -B{sasn_log} Logs from SASN\n -B{ssr_log} Logs from SSR\n -B{sasn_snmp} Logs of SNMP from SASN\n -B{persistent_log} Persistent log from the cards\n -B{startup_log} Startup log from the cards\n @param domain: Domain types are the\n @type domain: str\n @param log_type: Type of logs\n @type log_type: str\n @rtype: String\n \"\"\"\n available_domains = ['control_entity', 'application_entity', 'network_entity']\n available_types = ['sasn_log',\n 'sasn_snmp']\n\n if not domain in available_domains:\n raise InvalidArgument(\"domain\", possible_values=\"%s\" % available_domains, current_value = domain)\n #EndIf\n if not log_type in available_types:\n raise InvalidArgument(\"log_type\", possible_values=\"%s\" % available_types, current_value = log_type)\n #EndIf\n\n if domain in ['control_entity']:\n if log_type == 'sasn_log':\n path=SASNPaths().get_ce_sasn_messages_file()\n return self.__generate_command_path(path)\n elif log_type == 'sasn_snmp':\n path=SASNPaths().get_ce_sasn_snmp_file()\n return self.__generate_command_path(path)\n #EndIf\n #EndIf\n\n raise InvalidLogFile(domain, log_type)\n ## END METHOD retrieve_log_location( ... )\n## END CLASS SASNCommands\n\n","sub_path":"sds/back_test/ref/utils/sasnCommands.py","file_name":"sasnCommands.py","file_ext":"py","file_size_in_byte":173617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"507739105","text":"'''\n\n新進測試\n\n'''\n\nprint('------------------------------------------------------------')\t#60個\nprint('準備工作')\n\nimport sqlite3\nimport time\n\ndef show_data_base_contents(db_filename, table_name, length):\n conn = sqlite3.connect(db_filename) # 建立資料庫連線\n sqlstr = 'SELECT * FROM {};'.format(table_name)#same\n sqlstr = 'SELECT * FROM %s' % table_name\n cursor = conn.execute(sqlstr)\n\n n = 0\n for row in cursor:\n print(row)\n n = n + 1\n #讀取 N 筆資料, 即跳出\n if n == length:\n break\n conn.close() # 關閉資料庫連線\n\ndef show_data_base_contents_all(db_filename, table_name):\n conn = sqlite3.connect(db_filename) # 建立資料庫連線\n sqlstr = 'SELECT * FROM {};'.format(table_name)#same\n sqlstr = 'SELECT * FROM %s' % table_name\n results = str(conn.execute(sqlstr).fetchall())\n print(results)\n conn.close() # 關閉資料庫連線\n\nprint('------------------------------------------------------------')\t#60個\n\nprint('新進測試')\n\ndb_filename = 'C:/_git/vcs/_1.data/______test_files2/db_' + time.strftime(\"%Y%m%d_%H%M%S\", time.localtime()) + '.a.qlite';\n\n\nmem_conn = sqlite3.connect(':memory:')\t# 建立資料庫連線, 記憶體\ndisk_conn = sqlite3.connect('example.db') # 建立資料庫連線, 磁碟\n\ncursor = mem_conn.cursor()\ncursor.execute(\"CREATE TABLE table01 (name_last, age)\")\n\nprint('目前共有修改資料次數 : ', mem_conn.total_changes)\n\nwho = \"David\"\nage = 18\n\ncursor.execute(\"INSERT INTO table01 VALUES (?, ?)\", (who, age))\n\nprint('目前共有修改資料次數 : ', mem_conn.total_changes)\n\ncursor.execute(\"INSERT INTO table01 VALUES (?, ?)\", (who, age))\ncursor.execute(\"INSERT INTO table01 VALUES (?, ?)\", (who, age))\ncursor.execute(\"INSERT INTO table01 VALUES (?, ?)\", (who, age))\nprint('目前共有修改資料次數 : ', mem_conn.total_changes)\n\ncursor.execute('''CREATE TABLE stocks (date text, trans text, symbol text, qty real, price real)''')\ncursor.execute(\"INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)\")\n\n\nmem_conn.commit()\n\ncursor.execute(\"SELECT * FROM table01\")\nprint(cursor.fetchall())\n\n#使用 backup 命令将内存数据库备份到磁盘数据库。\n\n# 备份内存数据库到磁盘数据库\nmem_conn.backup(disk_conn)\n\n'''\nbackup 覆蓋\nattach 附加\n'''\n\n'''\n# 将磁盘数据库附加到内存数据库中\nmem_conn.execute(\"ATTACH DATABASE 'example.db' AS disk_db\")\n\n# 执行插入命令将数据插入到磁盘数据库中\nmem_conn.execute(\"INSERT INTO disk_db.example_table VALUES (1, 'example')\")\n'''\n\n# 关闭数据库连接对象\nmem_conn.close()\ndisk_conn.close()\n\nprint('------------------------------------------------------------')\t#60個\n\ndb_filename = 'example.db'\ntable_name = 'table01'\nshow_data_base_contents_all(db_filename, table_name)\n\n\ntable_name = 'stocks'\nshow_data_base_contents_all(db_filename, table_name)\n\n\n\n\n\nprint('------------------------------------------------------------')\t#60個\nprint('測 executemany')\n\nimport sqlite3\nstocks = [('2006-01-05', 'BUY', 'RHAT', 100, 35.14),\n ('2006-03-28', 'BUY', 'IBM', 1000, 45.0),\n ('2006-04-06', 'SELL', 'IBM', 500, 53.0),\n ('2006-04-05', 'BUY', 'MSFT', 1000, 72.0)]\nconn = sqlite3.connect(\":memory:\")\nconn.execute(\"create table stocks (date text, buysell text, symb text, amount int, price real)\")\nconn.executemany(\"insert into stocks values (?, ?, ?, ?, ?)\", stocks) \ncur = conn.cursor()\n \nfor row in cur.execute('SELECT * FROM stocks ORDER BY price'):\n print(row)\n \n# Output:\n# ('2006-01-05', 'BUY', 'RHAT', 100, 35.14)\n# ('2006-03-28', 'BUY', 'IBM', 1000, 45.0)\n# ('2006-04-06', 'SELL', 'IBM', 500, 53.0)\n# ('2006-04-05', 'BUY', 'MSFT', 1000, 72.0)\n\n\ncur.execute('SELECT * FROM stocks ORDER BY price')\n\none_row_data = cur.fetchone()\nprint('fetchone', one_row_data)\n\nwhile one_row_data:\n one_row_data = cur.fetchone()\n print('fetchone', one_row_data)\n \n\nprint('------------------------------------------------------------')\t#60個\nprint('測試各種fetch')\n'''\nfetchone()\t#抓一行 tuple\nfetchmany(size=cursor.arraysize)\t#抓n行 list\nfetchall()\t#抓取剩下的全部 list\n\n'''\n\ndb_filename = 'ims_sql/db_ims.sqlite'\ndb_filename = 'C:/_git/vcs/_1.data/______test_files1/_db/gasoline.sqlite'\n#db_filename = 'db_20230703_113217.sqlite'\n\nprint('建立資料庫連線, 資料庫 : ' + db_filename)\nconn = sqlite3.connect(db_filename) # 建立資料庫連線\n\ncursor = conn.execute('SELECT * FROM prices;')\n\naaaa = cursor.fetchone()\nprint(type(aaaa))\nprint(aaaa)\n\naaaa = cursor.fetchone()\nprint(type(aaaa))\nprint(aaaa)\n\nbbbb = cursor.fetchmany(3)\nprint(type(bbbb))\nprint(bbbb)\n\ncccc = cursor.fetchall()\nprint(type(cccc))\n#print(cccc)\n\n\n\n\n\n\n\nconn.close() # 關閉資料庫連線\n\n\n\nprint('------------------------------------------------------------')\t#60個\nprint('xxxxx new 0717')\n\nconn = sqlite3.connect(\":memory:\")\ncursor = conn.cursor()\ncursor.execute(\"CREATE TABLE table01(key INTEGER PRIMARY KEY, task TEXT)\")\n\ntasks = (\n'give food to fish',\n'prepare group meeting',\n'fight with a zebra',\n)\n\nfor task in tasks:\n cursor.execute(\"INSERT INTO table01 VALUES(NULL, ?)\", (task,))\n\ncursor.execute(\"SELECT * FROM table01\")\nprint(cursor.fetchall())\n\n\n# Update a record, just for good measure.\ncursor.execute(\"UPDATE table01 SET task = 'learn italian' WHERE key = 1\")\n\n\ncursor.execute(\"SELECT * FROM table01\")\nprint(cursor.fetchall())\n\n\nkey_id = 2\ncursor.execute(\"SELECT * FROM table01 WHERE key=?\", (str(key_id),))\nkey, task = cursor.fetchone()\n\nprint(key)\nprint(task)\n\n\n\n\n\nprint(\"程式執行完畢!\")\n\n\n\n\n'''\n\n注意:不要使用%s 將字串插入 SQL 命令,因為它可能使你的程式容易受到 SQL 注入攻擊(請參閱 SQL 注入 )。\n\n'''\n","sub_path":"_4.python/sqlite/sqlite_新進測試2.py","file_name":"sqlite_新進測試2.py","file_ext":"py","file_size_in_byte":5764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"583357900","text":"import pathlib\nimport transformers\nfrom my_module import path_manager as pm\nimport tensorflow as tf\nimport numpy as np\nimport pandas as pd\nimport statistics\n\nmodel_name = str(pm.get_abs_path(\n __file__, 'resources/BERT/BERT-base_mecab-ipadic-bpe-32k'))\ntokenizer = transformers.BertTokenizer.from_pretrained(model_name)\n\n\n# テキストのリストをtransformers用の入力データに変換\ndef to_features(texts, max_length):\n shape = (len(texts), max_length)\n # input_idsやattention_mask, token_type_idsの説明はglossaryに記載(cf. https://huggingface.co/transformers/glossary.html)\n input_ids = np.zeros(shape, dtype=\"int32\")\n attention_mask = np.zeros(shape, dtype=\"int32\")\n token_type_ids = np.zeros(shape, dtype=\"int32\")\n for i, text in enumerate(texts):\n encoded_dict = tokenizer.encode_plus(\n text, max_length=max_length, pad_to_max_length=True)\n input_ids[i] = encoded_dict[\"input_ids\"]\n attention_mask[i] = encoded_dict[\"attention_mask\"]\n token_type_ids[i] = encoded_dict[\"token_type_ids\"]\n return [input_ids, attention_mask, token_type_ids]\n\n\n# 単一テキストをクラス分類するモデルの構築\ndef build_model(model_name, num_classes, max_length):\n input_shape = (max_length, )\n input_ids = tf.keras.layers.Input(input_shape, dtype=tf.int32)\n attention_mask = tf.keras.layers.Input(input_shape, dtype=tf.int32)\n token_type_ids = tf.keras.layers.Input(input_shape, dtype=tf.int32)\n bert_model = transformers.TFBertModel.from_pretrained(model_name)\n last_hidden_state, pooler_output = bert_model(\n input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids\n )\n output = tf.keras.layers.Dense(\n num_classes, activation=\"softmax\")(pooler_output)\n model = tf.keras.Model(\n inputs=[input_ids, attention_mask, token_type_ids], outputs=[output])\n optimizer = tf.keras.optimizers.Adam(\n learning_rate=3e-5, epsilon=1e-08, clipnorm=1.0)\n model.compile(optimizer=optimizer,\n loss=\"categorical_crossentropy\", metrics=[\"acc\"])\n return model\n\n\ndef train(train_texts, train_labels, model_name):\n\n num_classes = 2\n # max_length = 15\n max_length = 27\n batch_size = 10\n epochs = 3\n\n x_train = to_features(train_texts, max_length)\n y_train = tf.keras.utils.to_categorical(\n train_labels, num_classes=num_classes)\n model = build_model(model_name, num_classes=num_classes,\n max_length=max_length)\n\n # 訓練\n model.fit(\n x_train,\n y_train,\n batch_size=batch_size,\n epochs=epochs,\n )\n\n model.save_weights('resources/train/checkpoints/my_checkpoint')\n\n\ndef gen_model(boundary: float = 0.0):\n '''\n BERTモデルを生成します。\n\n Parameters\n ---\n boundary (float, optional): 学習に用いる極性値を決定する境界値\n '''\n # データフレームの読み込み\n df = pd.read_csv('sent_senti.csv')\n # 無極性のレビューを除去する。\n df = df[df['score'] != 0]\n # 感情値の絶対値が境界値以上の行を抽出\n df = df[abs(df['score']) >= boundary]\n train_texts = df['content'].values\n # 感情値が正の場合は1、負の場合は0\n train_labels = [1 if 0 < score else 0 for score in df['score'].values]\n # 学習を開始\n train(train_texts, train_labels, model_name)\n\n\ndef load_model():\n num_classes = 2\n # max_length = 15\n max_length = 27\n model = build_model(model_name, num_classes=num_classes,\n max_length=max_length)\n model.load_weights('resources/train/checkpoints/my_checkpoint')\n return model\n\n\nif __name__ == \"__main__\":\n # show_status_of_sentences()\n # gen_model(boundary=0.2)\n # model = load_model()\n # df = pd.read_csv('sent_senti.csv')\n # df = df[df['score'] != 0]\n # test_texts = df['content'].values[:100]\n # test_labels = [1 if 0 < score else -\n # 1 for score in df['score'].values][:100]\n # max_length = 27\n # # 予測\n # x_test = to_features(test_texts, max_length)\n # y_test = np.asarray(test_labels)\n # y_preda = model.predict(x_test)\n # y_pred = np.argmax(y_preda, axis=1)\n # print(\"Accuracy: %.5f\" % accuracy_score(y_test, y_pred))\n # model.evaluate()\n pass\n","sub_path":"tespy/gen_bert_model.py","file_name":"gen_bert_model.py","file_ext":"py","file_size_in_byte":4355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"415902234","text":"#! /usr/bin/env python\n# Importing psycopg2 from python standard library\n\nimport psycopg2\n\nDBNAME = \"newsdata.article\"\n\n\ndef exer(cmd):\n dbm = psycopg2.connect(database=DBNAME)\n cr = dbm.cursor()\n cr.execute(cmd)\n resc = cr.fetchall()\n dbm.close()\n return resc\n\n# Question 1\n\n\ndef popular_author():\n cmd = \"\"\"select authors.name, count(*)\n as number from authors\n join articles\n on authors.id = articles.author\n join log\n on log.path like concat('/article/%',articles.slug)\n group by authors.name\n order by number\n desc limit 3; \"\"\"\n result = exer(cmd)\n counter = 1\n print(\"\\nBest Authors:\")\n for z in result:\n print(str(counter) + '.' + z[0] + '---' + str(z[1]) + \" views\")\n counter += 1\n\n# Question 2\n\nraw_input()\ndef famous_article():\n cmd = \"\"\"select articles.title, count(*)\n as number from articles\n join log\n on log.path like concat('/article/%',articles.slug)\n group by articles.title\n order by number\n desc limit 3;\"\"\"\n\n result = exer(cmd)\n counter = 1\n print(\"Best Articles:\")\n for z in result:\n numbers = str(counter) + '. \"'\n titles = z[0]\n views = '\" --- ' + str(z[1]) + \" views\"\n print(numbers + titles + views)\n counter += 1\n\n# Quesion 3\n\n\ndef error_ter():\n cmd = \"\"\"select tot.day,((errors.er*100)/tot.ers)as percent\n from ( select date_trunc('day', time) \"day\", count(*) as er from log\n where status like '404%' group by day) as errors\n join( select date_trunc('day',time) \"day\", count(*) as ers from log\n group by day) as tot on tot.day = errors.day\n where (((errors.er*100)/tot.ers)>1)\n order by percent desc;\"\"\"\n result = exer(cmd)\n print(\"\\nMaximum errors on:\")\n for z in result:\n dat = z[0].strftime('%B %d, %Y')\n err = str(z[1]) + \"%\" + \" errors\"\n print(dat + \"---\" + err)\n# here,functions are called\nfamous_article()\npopular_author()\nerror_ter()\nraw_input()\n","sub_path":"log_analysis.py","file_name":"log_analysis.py","file_ext":"py","file_size_in_byte":2093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"510807372","text":"import subprocess \nfrom socket import *\nimport time\n\nif __name__ == '__main__':\n#All menus are going to be stored here\n\n tools= {\n 1: \"ping\",\n 2: \"hydra\",\n 3: \"GoBuster\",\n 4: \"john the ripper\",\n 5: \"Burpsuite\",\n 6: \"Port Scanner\",\n\n }\n\n hydra_options= {\n 1: \"SSH\",\n 2: \"HTTP-GET\",\n\n }\n \n\n yes_or_no= [\"1) Yes\",\n \"2) No\",\n ]\n\n\nfor number, tool in tools.items():\n print(str(number)+\" \" + tool)\n\noption=int(input(\"what tool would you like to use?\"))\n\n\n\n#All Fuctions will go here\n\n# ping a host function\ndef ping():\n host = str(input(\"what host would you like to ping?\"))\n subprocess.run('ping %s' %(host) , shell=True)\n\n# Hydra Bruteforce Function\ndef hydra():\n for number, optionselect in hydra_options.items():\n print(str(number)+ \" \" + optionselect)\n option= int(input(\"What are you trying to bruteforce? \"))\n\n if option == 1:\n print(\"SSH Selected\")\n user= str(input(\"what user are you tryng to bruteforce? \"))\n wordlist= str(input(\"specify your wordlist path \"))\n targetIP= str(input(\"What is the target IP \"))\n subprocess.run('hydra -l %s -P ' %(user) + wordlist + ' ' + targetIP +' ssh -t 4' , shell=True)\n\n# GoBuster Directoy Bruteforce Function \ndef gobuster():\n pass\n\n# John The Ripper Bruteforce Function\ndef john():\n pass\n\n# Burpsuite Open Function\ndef burp():\n pass\n\n# Stealth Port Scanner Function\ndef portscanner():\n target = input('Enter the host to be scanned: ')\n first_Port = int(input(\"What port would you like to start with? \"))\n last_Port = int(input(\"What is the ending port?\"))\n t_IP = gethostbyname(target)\n print ('Starting scan on host: ', t_IP)\n\n for i in range(first_Port, last_Port):\n s = socket(AF_INET, SOCK_STREAM)\n\n conn = s.connect_ex((t_IP, i))\n\n if(conn == 0):\n print ('Port %d: OPEN' % (i,))\n\n s.close()\n\n print(\"Scan finished\")\n\n\n\nif option == 1:\n ping()\n\nif option == 2:\n hydra()\n\nif option == 3:\n gobuster()\n\nif option == 4:\n john()\n\nif option == 5:\n burp()\n\nif option == 6:\n portscanner()\n \n","sub_path":"multi_tool.py","file_name":"multi_tool.py","file_ext":"py","file_size_in_byte":2202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"563950402","text":"import unittest\n\nfrom werkzeug import exceptions\n\nfrom Python.src.constants import DATA_MODEL_ERROR\nfrom Python.src.preprocessor import Preprocessor\n\nresponse_type = '400 Bad Request: '\n\n\nclass TestPreprocessor(unittest.TestCase):\n def test_nlp_preprocessor_green(self):\n init_preprocessor = Preprocessor('test', 'en_core_web_sm')\n self.assertIsNotNone(init_preprocessor._nlp_pre_process())\n\n def test_nlp_preprocessor_no_text(self):\n init_preprocessor = Preprocessor(None, 'en_core_web_sm')\n with self.assertRaisesRegex(exceptions.BadRequest, response_type + DATA_MODEL_ERROR):\n init_preprocessor._nlp_pre_process()\n\n def test_nlp_preprocessor_no_model(self):\n init_preprocessor = Preprocessor('test', '')\n with self.assertRaisesRegex(exceptions.BadRequest, response_type + DATA_MODEL_ERROR):\n init_preprocessor._nlp_pre_process()\n","sub_path":"Python/test/preprocessor_text.py","file_name":"preprocessor_text.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"294572385","text":"class Solution:\n def groupAnagrams(self, strs: List[str]) -> List[List[str]]:\n import collections\n\n res = collections.defaultdict(list)\n for word in strs:\n count = [0] * 26\n for c in word:\n count[ord(c) - ord('a')] += 1\n res[tuple(count)].append(word)\n\n return res.values()\n","sub_path":"Problems/049-group-anagrams/group-anagrams.py","file_name":"group-anagrams.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"322239564","text":"'''\n当我们写一个参数比较多的函数时,如果有些参数在大多数情况下都是某个固定值,\n那么为了简化使用,就可以创建一个新函数,指定我们要使用的某个参数位固定值,\n这个新函数就是偏函数\n'''\n\ndef test(a,b,c,d=1):\n print(a+b+c+d)\n#\n# test(1,2,3)\n#\n#\n# def test2(a,b,c=1,d=2):\n# test(a,b,c,d)\n# test2(1,2,3)\n\n# 比较麻烦\n\nimport functools\nnewfunc=functools.partial(test,c=5)\nprint(newfunc,type(newfunc))\nnewfunc(1,3)\n#------------------------------ 场景-----------------------------\nnumStr=\"100010\"\n# result=int(numStr,base=2)\n# print(result)\n# 往后一段时间都需要把2进制字符串转换成10进制数据\nint2=functools.partial(int,base=2)\nprint(int2(numStr))","sub_path":"StudyPython/Python-函数-偏函数.py","file_name":"Python-函数-偏函数.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
name#inputoutput
%s---[%d]---
\", \"\").replace(\"